diff --git a/.gitattributes b/.gitattributes index b7ca04d95ed..378b7ab94aa 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,7 +4,7 @@ /skill-stubs/*.md text eol=lf /skill-stubs/_shared/*.md text eol=lf /skills/*/SKILL.md text eol=lf -/src/cli/bundled-skill-guides.ts text eol=lf +/src/cli/skills/bundled-skill-guides.ts text eol=lf # SVG bytes feed embedded data URLs and asset hashes on every build host. *.svg text eol=lf # Compiler input line breaks must not depend on the checkout OS. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index c15f386cf2a..4f34ff684b1 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -12,24 +12,57 @@ body: Please write your issue in English. + - type: dropdown + id: where + attributes: + label: Where were you using Orca? + description: Where you saw the bug. + options: + - Desktop only + - Desktop + SSH host + - Desktop + Orca server + - Desktop + WSL + - Mobile app + - Web browser + - Other + validations: + required: true + - type: dropdown id: os attributes: label: Operating system + description: 'The device you were using. WSL: pick Windows. Phone: pick iOS or Android.' options: - macOS - Windows - Linux + - iOS + - Android - Other validations: required: true + - type: dropdown + id: remote_os + attributes: + label: Remote host operating system + description: Only for SSH, Orca server or web. + options: + - Linux + - macOS + - Windows + - Other + - Not sure + validations: + required: false + - type: input id: orca_version attributes: label: Orca version - description: Include the exact Orca version if you can. You can find it in `Orca > About Orca`. - placeholder: v0.14.2 + description: 'macOS: Orca > About Orca. Windows/Linux: Help > About Orca. Mobile: Settings > About.' + placeholder: v1.4.2 validations: required: false diff --git a/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs b/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs index 9dae4a9075c..f293ebcc6d6 100644 --- a/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs +++ b/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs @@ -1,28 +1,16 @@ import assert from 'node:assert/strict' import { test } from 'node:test' -import { - CloudSqlRolloutLease, - LEASE_TTL_MS, - LeaseConflict, - LeaseUnreadable -} from './storage-lease.mjs' +import { CloudSqlRolloutLease, LeaseConflict, LeaseUnreadable } from './storage-lease.mjs' const BUCKET = 'onorca-cloud-terraform-state' const OBJECT = 'terraform/state/cloud-sql-rollout/production.lock' const NOW = 1_756_000_000_000 -/** Model real GCS generation increments, ifGenerationMatch and 412 conflicts; faults inject failures. */ -function fakeStorage({ object = null, faults = [] } = {}) { - const state = { object, requests: [] } +function fakeStorage({ object = null } = {}) { + const state = { object } const fetcher = async (rawUrl, init = {}) => { const url = new URL(rawUrl) const method = init.method ?? 'GET' - const record = { method, url, path: url.pathname, search: url.searchParams } - state.requests.push(record) - const fault = faults.find((candidate) => candidate.when(record)) - if (fault) { - return json(fault.status, fault.body ?? {}) - } if (url.pathname.startsWith('/upload/')) { const want = url.searchParams.get('ifGenerationMatch') @@ -63,15 +51,10 @@ function json(status, body) { } } -function storedRecord({ - holderKey, - expiresAt, - repository = 'stablyai/orca', - workflow = 'Deploy Relay Production' -}) { +function storedRecord({ holderKey, expiresAt }) { return { - repository, - workflow, + repository: 'stablyai/orca', + workflow: 'Deploy Relay Production', run_id: '9001', run_url: 'https://github.com/stablyai/orca/actions/runs/9001', run_attempt: '1', @@ -81,14 +64,14 @@ function storedRecord({ } } -function leaseFor(storage, { warn = () => {} } = {}) { +function leaseFor(storage) { return new CloudSqlRolloutLease({ bucket: BUCKET, objectName: OBJECT, accessToken: 'test-token', fetcher: storage.fetcher, now: () => NOW, - warn + warn: () => {} }) } @@ -114,77 +97,24 @@ test('refuses a live lease held by another run and never writes', async () => { .catch((thrown) => thrown) assert.ok(error instanceof LeaseConflict) - assert.equal(error.holder.repository, 'stablyai/orca') - assert.equal(error.holder.run_url, 'https://github.com/stablyai/orca/actions/runs/9001') - assert.equal( - storage.state.requests.filter((request) => request.method !== 'GET').length, - 0, - 'a foreign live lease must not be written' - ) assert.equal(storage.state.object.generation, '1500') }) -test('re-enters a live lease this run already holds and extends it', async () => { - const storage = fakeStorage({ - object: { - generation: '1500', - body: storedRecord({ holderKey: HOLDER.holderKey, expiresAt: NOW + 60_000 }) - } - }) - const warnings = [] - const claim = await leaseFor(storage, { warn: (message) => warnings.push(message) }).acquire( - HOLDER - ) - - assert.equal(claim.state, 'reentrant') - assert.deepEqual(warnings, [], 're-entering our own lease is not a takeover') - assert.equal(claim.record.acquired_at, NOW - 60_000, 'original acquisition time is preserved') - assert.equal(claim.record.expires_at, NOW + LEASE_TTL_MS) - const upload = storage.state.requests.find((request) => request.path.startsWith('/upload/')) - assert.equal(upload.search.get('ifGenerationMatch'), '1500') - assert.equal(storage.state.object.generation, '1501') -}) - -test('takes over an expired lease and warns naming the stale holder', async () => { +test('takes over an expired lease', async () => { const storage = fakeStorage({ object: { generation: '1500', body: storedRecord({ holderKey: 'stablyai/orca/9001', - expiresAt: NOW - 1, - repository: 'stablyai/orca', - workflow: 'Deploy Relay Production Capacity' + expiresAt: NOW - 1 }) } }) - const warnings = [] - const claim = await leaseFor(storage, { warn: (message) => warnings.push(message) }).acquire( - HOLDER - ) + await leaseFor(storage).acquire(HOLDER) - assert.equal(claim.state, 'takeover') - assert.equal(warnings.length, 1) - assert.match(warnings[0], /stablyai\/orca/) - assert.match(warnings[0], /Deploy Relay Production Capacity/) - assert.match(warnings[0], /actions\/runs\/9001/) - const upload = storage.state.requests.find((request) => request.path.startsWith('/upload/')) - assert.equal(upload.search.get('ifGenerationMatch'), '1500') assert.equal(storage.state.object.body.holder_key, HOLDER.holderKey) }) -test('releases with a generation match and leaves the object gone', async () => { - const storage = fakeStorage() - const lease = leaseFor(storage) - const claim = await lease.acquire(HOLDER) - - const released = await lease.release(HOLDER.holderKey) - - assert.deepEqual(released, { released: true, generation: claim.generation }) - const remove = storage.state.requests.find((request) => request.method === 'DELETE') - assert.equal(remove.search.get('ifGenerationMatch'), claim.generation) - assert.equal(storage.state.object, null) -}) - test('refuses to release a lease another run now holds', async () => { const storage = fakeStorage({ object: { @@ -200,19 +130,6 @@ test('refuses to release a lease another run now holds', async () => { assert.equal(storage.state.object.generation, '1500') }) -test('fails closed when the bucket answers 5xx', async () => { - const storage = fakeStorage({ - faults: [{ when: (request) => request.method === 'GET', status: 503 }] - }) - - const error = await leaseFor(storage) - .acquire(HOLDER) - .catch((thrown) => thrown) - - assert.match(error.message, /lease inspection failed: 503/) - assert.equal(storage.state.requests.filter((request) => request.method !== 'GET').length, 0) -}) - test('treats an unreadable record as held, not free', async () => { const storage = fakeStorage({ object: { generation: '1500', body: { holder_key: 'stablyai/orca/9001' } } @@ -225,31 +142,3 @@ test('treats an unreadable record as held, not free', async () => { assert.ok(error instanceof LeaseUnreadable) assert.equal(storage.state.object.generation, '1500') }) - -test('renewal rewrites only expires_at on the observed generation', async () => { - const storage = fakeStorage() - const lease = leaseFor(storage) - await lease.acquire(HOLDER) - storage.state.object.body.expires_at = NOW - 1 - - const renewed = await lease.renew(HOLDER.holderKey) - - assert.equal(renewed.renewed, true) - assert.equal(storage.state.object.body.expires_at, NOW + LEASE_TTL_MS) - assert.equal(storage.state.object.body.acquired_at, NOW) - assert.equal(storage.state.object.body.holder_key, HOLDER.holderKey) -}) - -test('renewal stops once the object belongs to someone else', async () => { - const storage = fakeStorage({ - object: { - generation: '1500', - body: storedRecord({ holderKey: 'stablyai/orca/9001', expiresAt: NOW + 60_000 }) - } - }) - - assert.deepEqual(await leaseFor(storage).renew(HOLDER.holderKey), { - renewed: false, - reason: 'foreign' - }) -}) diff --git a/.github/workflows/adhoc-mac-build.yml b/.github/workflows/adhoc-mac-build.yml index fe133720ef4..0391563de52 100644 --- a/.github/workflows/adhoc-mac-build.yml +++ b/.github/workflows/adhoc-mac-build.yml @@ -385,7 +385,7 @@ jobs: ORCA_RELEASE_JAVASCRIPT_BUILD_IDENTITY: dev NODE_OPTIONS: --max-old-space-size=4096 # Leave build identity unset: telemetry accepts only official stable/rc, so branch artifacts stay silent. - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token # After the app build so nothing that cleans out/ can drop it; electron-builder ships it. - name: Download the orcad deployment template diff --git a/.github/workflows/ci-closed-pr-caches.yml b/.github/workflows/ci-closed-pr-caches.yml index 37dc522417f..32e43244103 100644 --- a/.github/workflows/ci-closed-pr-caches.yml +++ b/.github/workflows/ci-closed-pr-caches.yml @@ -62,11 +62,24 @@ jobs: current.closed_at === pr.closed_at } if (!Number.isSafeInteger(pr.number) || pr.number <= 0 || - (superseded ? !/^[a-f0-9]{40}$/.test(pr.head?.sha ?? '') : - !Number.isFinite(Date.parse(pr.closed_at)))) { + (superseded && !/^[a-f0-9]{40}$/.test(pr.head?.sha ?? ''))) { throw new Error('Missing PR identity') } - if (!await stillCurrent()) return + if (!superseded && !Number.isFinite(Date.parse(pr.closed_at))) { + // A close quickly followed by a reopen can deliver a payload rendered after the reopen. + const { data: current } = await github.rest.pulls.get({ + ...context.repo, pull_number: pr.number + }) + if (current.state !== 'closed' || current.merged_at !== null) { + core.info(`PR #${pr.number} changed after this close event; skipping cancellation`) + return + } + throw new Error('Missing PR identity') + } + if (!await stillCurrent()) { + core.info(`PR #${pr.number} changed after this event; skipping cancellation`) + return + } for (const [prefix, workflow, suffix = ''] of targets) { const group = prefix === 'cloud-verify-refs/pull' ? `${prefix}/${pr.number}${suffix}` : `${prefix}-${pr.number}${suffix}` diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 369de291215..f26cfe41eec 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -38,8 +38,8 @@ on: - '!src/main/daemon/executable-host/windows/testing/daemon-host-relocation.test-fixture.ts' - '!src/main/daemon/endpoint/publication/testing/daemon-endpoint-reachability-test-harness.ts' - 'src/main/providers/local-pty/local-pty-provider.ts' - - 'src/main/providers/windows-shell-args.ts' - - 'src/main/providers/windows-shell-preflight-runtime.windows.test.ts' + - 'src/main/providers/shell-launch/windows/shell-args.ts' + - 'src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts' - 'native/computer-use-macos/**' - 'native/computer-use-linux/**' - 'native/computer-use-windows/**' @@ -48,12 +48,13 @@ on: - 'src/cli/**' - 'src/main/computer/**' - 'src/main/runtime/rpc/dispatcher.ts' - - 'src/main/runtime/rpc/errors.ts' + - 'src/main/runtime/rpc/responses/rpc-response.ts' - 'src/main/runtime/rpc/methods/computer/computer*.ts' - 'src/shared/computer-use-*.ts' - 'tests/e2e/computer-linux.e2e.ts' - 'tests/e2e/computer-windows.e2e.ts' - - 'tests/e2e/computer-windows-store.e2e.ts' + - 'tests/e2e/computer-windows-background.e2e.ts' + - 'tests/e2e/helpers/windows-semantic-controls-fixture.*' - 'tests/e2e/helpers/computer-cli-driver.ts' - 'tests/e2e/helpers/computer-driver.ts' - 'tests/e2e/vitest.config.ts' @@ -95,11 +96,10 @@ jobs: config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs src/main/computer/sidecar-transport/sidecar-client.test.ts src/main/computer/macos-native/macos-native-provider-client.test.ts - src/main/providers/windows-shell-preflight-runtime.windows.test.ts + src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts - src/cli/format.test.ts - src/cli/handlers/computer-action-validation.test.ts - src/cli/handlers/computer-state-formatting.test.ts + src/cli/output/command-result-output.test.ts + src/cli/computer/computer-state-formatting.test.ts src/cli/index.test.ts src/cli/runtime/envelope-schema.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts @@ -152,4 +152,4 @@ jobs: - run: pnpm verify:computer-native - run: pnpm build:cli - run: pnpm run build:electron-vite:parallel - - run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-store.e2e.ts + - run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-background.e2e.ts diff --git a/.github/workflows/daily-mac-build.yml b/.github/workflows/daily-mac-build.yml index ec0e08a3644..b06d51de2ac 100644 --- a/.github/workflows/daily-mac-build.yml +++ b/.github/workflows/daily-mac-build.yml @@ -235,7 +235,7 @@ jobs: env: NODE_OPTIONS: --max-old-space-size=4096 # Leave dev identity unset so official-only stable/rc telemetry stays silent. - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token # After the app build so nothing that cleans out/ can drop it; electron-builder ships it. - name: Download the orcad deployment template diff --git a/.github/workflows/dev-channel-win-build.yml b/.github/workflows/dev-channel-win-build.yml index 7a4d062ecc3..2b7748cddeb 100644 --- a/.github/workflows/dev-channel-win-build.yml +++ b/.github/workflows/dev-channel-win-build.yml @@ -254,7 +254,7 @@ jobs: ORCA_RELEASE_JAVASCRIPT_SOURCE_SHA: ${{ inputs.javascript_source_sha }} ORCA_RELEASE_JAVASCRIPT_BUILD_IDENTITY: dev # Unset dev build identity so official stable/rc telemetry stays silent. - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token # Inline so refs predating the wait can still use the trusted dispatch workflow. - name: Wait for the qualified orcad template diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 2c876199f4f..612b783b147 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -204,7 +204,7 @@ jobs: timeout-minutes: 15 environment: name: docs-production - url: https://www.onorca.dev/docs + url: https://orca.dev/docs env: VERCEL_TELEMETRY_DISABLED: '1' steps: diff --git a/.github/workflows/hourly-mac-build.yml b/.github/workflows/hourly-mac-build.yml index bce2d132f30..17b7cc55065 100644 --- a/.github/workflows/hourly-mac-build.yml +++ b/.github/workflows/hourly-mac-build.yml @@ -224,7 +224,7 @@ jobs: env: NODE_OPTIONS: --max-old-space-size=4096 # Unset dev identity so official-only stable/rc telemetry stays silent. - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token # After the app build so nothing that cleans out/ can drop it; electron-builder ships it. - name: Download the orcad deployment template diff --git a/.github/workflows/issue-os-labeler.yaml b/.github/workflows/issue-os-labeler.yaml index cf0ee59a842..2345bf72842 100644 --- a/.github/workflows/issue-os-labeler.yaml +++ b/.github/workflows/issue-os-labeler.yaml @@ -14,48 +14,248 @@ jobs: apply-os-label: runs-on: ubuntu-slim timeout-minutes: 5 + # Serialize runs per issue; each run reconciles from current state, so order does not matter. + concurrency: + group: ${{ github.workflow }}-issue-${{ github.event.issue.number }} + cancel-in-progress: false steps: - - name: Apply OS label from issue form + - name: Reconcile OS and mobile labels from issue form uses: actions/github-script@v8 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | - const issue = context.payload.issue; - const body = issue.body || ""; - const osMatch = body.match(/^### Operating system\s+(.+)$/m); + // The only labels this workflow may add or remove. + const MANAGED_LABELS = ["os:macos", "os:Windows", "os:linux", "os:mobile", "mobile"]; + const MAX_PASSES = 3; - if (!osMatch) { - core.info("No operating system field found. Skipping."); - return; + const NOTE_PREFIX = + "> \u{1F310} **Translation note (machine-translated by an assistant on "; + const NOTE_SUFFIX = + "):** This issue's title was originally written in Chinese and has been translated to English (the body is unchanged). The original, untranslated text is preserved intact in the collapsible section below."; + const NOTE_DATE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/; + + // Metadata headings in accepted order; equal rank = current/legacy names of one field. + const HEADING_RANKS = new Map([ + ["Summary", 1], + ["Where were you using Orca?", 2], + ["Client", 2], + ["Operating system", 3], + ["Host operating system", 3], + ["Remote host operating system", 4], + ["Orca version", 5], + ["Coding harness and version", 6], + ["Details", 7], + ["Reproduction steps", 7], + ]); + const FREE_TEXT_RANK = 7; + + const OS_LABELS = new Map([ + ["macos", "os:macos"], + ["windows", "os:Windows"], + ["linux", "os:linux"], + ["ios", "os:mobile"], + ["android", "os:mobile"], + ["other", null], + ]); + // Value: whether the choice means the mobile app. Retired option strings stay for open issues. + const WHERE_IS_MOBILE = new Map([ + ["desktop only", false], + ["desktop + ssh host", false], + ["desktop + orca server", false], + ["desktop + wsl", false], + ["mobile app", true], + ["web browser", false], + ["other", false], + ["desktop (this computer)", false], + ["desktop + ssh", false], + ["desktop + orca remote server", false], + ["mobile (ios)", true], + ["mobile (android)", true], + ["web / browser", false], + ]); + const CLIENT_IS_MOBILE = new Map([ + ...WHERE_IS_MOBILE, + ["desktop", false], + ["mobile", true], + ["web", false], + ]); + const REMOTE_OS_VALUES = new Set(["linux", "macos", "windows", "other", "not sure"]); + + const isBlank = (line) => /^[ \t]*$/.test(line); + const isHeading = (line) => /^###(?:[ \t]|$)/.test(line); + const isUnselected = (value) => value === "" || value === "_no response_"; + const isTranslationNote = (line) => + line.length === NOTE_PREFIX.length + 10 + NOTE_SUFFIX.length && + line.startsWith(NOTE_PREFIX) && + line.endsWith(NOTE_SUFFIX) && + NOTE_DATE.test(line.slice(NOTE_PREFIX.length, NOTE_PREFIX.length + 10)); + + // Reads only the leading metadata prefix; null means "not a recognizable bug form". + function readFormFields(body) { + if (typeof body !== "string") { + return null; + } + const lines = body.replace(/\r\n/g, "\n").split("\n"); + let index = 0; + const skipBlankLines = () => { + while (index < lines.length && isBlank(lines[index])) { + index += 1; + } + }; + + skipBlankLines(); + if (index < lines.length && isTranslationNote(lines[index])) { + index += 1; + if (index >= lines.length || !isBlank(lines[index])) { + return null; + } + skipBlankLines(); + } + + const fields = new Map(); + let lastRank = 0; + while (index < lines.length) { + const line = lines[index]; + if (!isHeading(line)) { + return null; + } + // Exact "### " only; any other heading shape is unknown. + const name = line.startsWith("### ") ? line.slice(4) : null; + const rank = HEADING_RANKS.get(name); + if (rank === undefined || rank < lastRank || fields.has(name)) { + return null; + } + if (rank === FREE_TEXT_RANK) { + // Free text starts here and is never inspected. + return fields; + } + lastRank = rank; + index += 1; + + let value = ""; + let valueLines = 0; + while (index < lines.length && !isHeading(lines[index])) { + if (!isBlank(lines[index])) { + value = lines[index]; + valueLines += 1; + } + index += 1; + } + if (valueLines > 1) { + return null; + } + fields.set(name, value.trim().toLowerCase()); + } + return null; } - const selectedOs = osMatch[1].trim().toLowerCase(); - const osLabelMap = { - macos: "os:macos", - windows: "os:Windows", - linux: "os:linux", - }; + // Returns the managed labels the body asks for, or null to leave the issue untouched. + function desiredLabelsFor(body) { + const fields = readFormFields(body); + if (!fields || !fields.has("Orca version")) { + return null; + } + const osHeading = ["Operating system", "Host operating system"].find((name) => + fields.has(name), + ); + if (!osHeading) { + return null; + } + const desired = new Set(); - const desiredLabel = osLabelMap[selectedOs]; - if (!desiredLabel) { - core.info(`No OS label configured for "${selectedOs}". Skipping.`); - return; + const os = fields.get(osHeading); + if (!isUnselected(os)) { + if (!OS_LABELS.has(os)) { + return null; + } + const osLabel = OS_LABELS.get(os); + if (osLabel) { + desired.add(osLabel); + } + } + + // The current heading wins by presence, even when blank. + const whereChoices = fields.has("Where were you using Orca?") + ? [fields.get("Where were you using Orca?"), WHERE_IS_MOBILE] + : fields.has("Client") + ? [fields.get("Client"), CLIENT_IS_MOBILE] + : null; + if (whereChoices && !isUnselected(whereChoices[0])) { + const [where, isMobileByChoice] = whereChoices; + if (!isMobileByChoice.has(where)) { + return null; + } + if (isMobileByChoice.get(where)) { + desired.add("mobile"); + } + } + + // Validated only; the remote host never contributes a label. + const remoteOs = fields.get("Remote host operating system") ?? ""; + if (!isUnselected(remoteOs) && !REMOTE_OS_VALUES.has(remoteOs)) { + return null; + } + return desired; } - const managedLabels = Object.values(osLabelMap); - const existingLabels = issue.labels.map((label) => - typeof label === "string" ? label : label.name, - ); - const labelsToKeep = existingLabels.filter( - (label) => !managedLabels.includes(label), - ); - const nextLabels = [...new Set([...labelsToKeep, desiredLabel])]; - - await github.rest.issues.setLabels({ + const issueRef = { owner: context.repo.owner, repo: context.repo.repo, - issue_number: issue.number, - labels: nextLabels, - }); + issue_number: context.payload.issue.number, + }; - core.info(`Applied label ${desiredLabel} to issue #${issue.number}.`); + // The event is only a signal: decisions come from the issue as it is now. + async function readCurrentIssue() { + const { data } = await github.rest.issues.get(issueRef); + const labelNames = (data.labels ?? []).map((label) => + typeof label === "string" ? label : label.name, + ); + const desired = desiredLabelsFor(data.body); + const present = MANAGED_LABELS.filter((label) => labelNames.includes(label)); + return { + desired, + toAdd: desired ? MANAGED_LABELS.filter((l) => desired.has(l) && !present.includes(l)) : [], + toRemove: desired ? present.filter((l) => !desired.has(l)) : [], + }; + } + + let state = await readCurrentIssue(); + let hasWritten = false; + for (let pass = 1; ; pass += 1) { + if (!state.desired) { + if (hasWritten) { + throw new Error( + `Issue #${issueRef.issue_number} stopped matching the bug form while labels were being updated. Managed labels may be incomplete; rerun this job once the issue body is settled.`, + ); + } + core.info("No recognizable bug form at the start of the issue body. Labels left untouched."); + return; + } + if (state.toAdd.length === 0 && state.toRemove.length === 0) { + core.info( + `Issue #${issueRef.issue_number} managed labels match the form: [${[...state.desired].join(", ")}].`, + ); + return; + } + if (pass > MAX_PASSES) { + throw new Error( + `Issue #${issueRef.issue_number} labels still differ from the form after ${MAX_PASSES} passes (to add: [${state.toAdd.join(", ")}], to remove: [${state.toRemove.join(", ")}]). The issue is probably being edited; rerun this job.`, + ); + } + + hasWritten = true; + if (state.toAdd.length > 0) { + await github.rest.issues.addLabels({ ...issueRef, labels: state.toAdd }); + } + for (const name of state.toRemove) { + try { + await github.rest.issues.removeLabel({ ...issueRef, name }); + } catch (error) { + // Already gone is the desired outcome; the re-read below verifies real state. + if (error?.status !== 404) { + throw error; + } + } + } + state = await readCurrentIssue(); + } diff --git a/.github/workflows/layout-owner-e2e.yml b/.github/workflows/layout-owner-e2e.yml index 7899e74285f..97655dae6fc 100644 --- a/.github/workflows/layout-owner-e2e.yml +++ b/.github/workflows/layout-owner-e2e.yml @@ -25,7 +25,7 @@ jobs: uses: ./.github/workflows/e2e.yml with: ref: ${{ inputs.ref || github.sha }} - test_files: '["tests/e2e/workspace-layout-oracle-headless.spec.ts","tests/e2e/workspace-layout-oracle.spec.ts","tests/e2e/cli-file-open-position.spec.ts","tests/e2e/relaunch-first-terminal.spec.ts","tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts","tests/e2e/cli-first-worktree-single-terminal.spec.ts","tests/e2e/unopened-workspace-agent-single-resume.spec.ts","tests/e2e/terminal-pane-close-layout-consistency.spec.ts","tests/e2e/golden-file-open-edit-save.spec.ts","tests/e2e/golden-source-control-open-diff.spec.ts","tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts","tests/e2e/floating-workspace-pane-height.spec.ts","tests/e2e/editor-model-host-isolation.spec.ts","tests/e2e/editor-tab-selection-restore.spec.ts","tests/e2e/finished-agent-ghost-resume.spec.ts","tests/e2e/live-background-terminal-mount-authority.spec.ts","tests/e2e/workspace-back-forward-navigation.spec.ts","tests/e2e/worktree-lineage-toggle-shortcut.spec.ts","tests/e2e/local-cli-terminal-retention.spec.ts","tests/e2e/default-tabs-mark-crash-relaunch.spec.ts","tests/e2e/terminal-cli-split-closed-before-mount.spec.ts","tests/e2e/layout-stream-loss-reopen.spec.ts","tests/e2e/terminal-tab-close-restart-persistence.spec.ts","tests/e2e/artificial-opencode-terminal-load.spec.ts","tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts","tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts","tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts","tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts","tests/e2e/headless-serve-browser-tab-restart.spec.ts","tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts","tests/e2e/headless-serve-desktop-activation.spec.ts","tests/e2e/headless-serve-chat-tab-placement.spec.ts","tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts","tests/e2e/layout-compat-old-phone-on-new-server.spec.ts","tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts","tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts","tests/e2e/paired-mobile-desktop-tab-composition.spec.ts","tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts","tests/e2e/paired-desktop-server-layout-frames.spec.ts","tests/e2e/paired-desktop-server-held-pane-reopen.spec.ts","tests/e2e/paired-desktop-server-layout-intents.spec.ts","tests/e2e/paired-desktop-server-layout-writes.spec.ts","tests/e2e/ssh-orcad-"]' + test_files: '["tests/e2e/workspace-layout-oracle-headless.spec.ts","tests/e2e/workspace-layout-oracle.spec.ts","tests/e2e/cli-file-open-position.spec.ts","tests/e2e/relaunch-first-terminal.spec.ts","tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts","tests/e2e/cli-first-worktree-single-terminal.spec.ts","tests/e2e/unopened-workspace-agent-single-resume.spec.ts","tests/e2e/terminal-pane-close-layout-consistency.spec.ts","tests/e2e/golden-file-open-edit-save.spec.ts","tests/e2e/golden-source-control-open-diff.spec.ts","tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts","tests/e2e/floating-workspace-pane-height.spec.ts","tests/e2e/editor-model-host-isolation.spec.ts","tests/e2e/editor-tab-selection-restore.spec.ts","tests/e2e/finished-agent-ghost-resume.spec.ts","tests/e2e/live-background-terminal-mount-authority.spec.ts","tests/e2e/workspace-back-forward-navigation.spec.ts","tests/e2e/worktree-lineage-toggle-shortcut.spec.ts","tests/e2e/local-cli-terminal-retention.spec.ts","tests/e2e/default-tabs-mark-crash-relaunch.spec.ts","tests/e2e/terminal-cli-split-closed-before-mount.spec.ts","tests/e2e/layout-stream-loss-reopen.spec.ts","tests/e2e/terminal-tab-close-restart-persistence.spec.ts","tests/e2e/artificial-opencode-terminal-load.spec.ts","tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts","tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts","tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts","tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts","tests/e2e/headless-serve-browser-tab-restart.spec.ts","tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts","tests/e2e/headless-serve-desktop-activation.spec.ts","tests/e2e/headless-serve-chat-tab-placement.spec.ts","tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts","tests/e2e/layout-compat-old-phone-on-new-server.spec.ts","tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts","tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts","tests/e2e/paired-mobile-desktop-tab-composition.spec.ts","tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts","tests/e2e/ssh-orcad-"]' run_changed_e2e: true needs_build: true artifact_suffix: -layout-owner-switch-on diff --git a/.github/workflows/macos-updater-tests.yml b/.github/workflows/macos-updater-tests.yml index d050fb3db5c..b30d8d06057 100644 --- a/.github/workflows/macos-updater-tests.yml +++ b/.github/workflows/macos-updater-tests.yml @@ -11,12 +11,12 @@ on: - 'native/macos-shipit-scheduling/**' - 'config/scripts/macos-shipit-scheduling*' - 'config/electron-builder.config.cjs' - - 'src/main/startup/main-process-quit*' - - 'src/main/window/main-window-state-lifecycle*' + - 'src/main/startup/quit/main-process-quit*' + - 'src/main/window/main-window/main-window-state-lifecycle*' - 'src/main/window/dashboard-popout-window*' - 'src/packages/process-host/**' - 'src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers*' - - 'src/main/providers/macos-tcc-login-shell*' + - 'src/main/providers/shell-launch/macos/tcc-login-shell*' - 'src/shared/process-table-snapshot*' - 'src/shared/darwin-process-table-capture*' - 'src/shared/update-status-types.ts' @@ -55,8 +55,8 @@ jobs: src/main/updater/mac-install/updater.mac-install.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater-mac-quit-guard.test.ts - src/main/startup/main-process-quit-update-veto.test.ts - src/main/window/main-window-state-lifecycle.test.ts + src/main/startup/quit/main-process-quit-update-veto.test.ts + src/main/window/main-window/main-window-state-lifecycle.test.ts - name: Prove login-backed terminal writer census on the disposable runner env: ORCA_MACOS_LOGIN_CENSUS_CI: '1' diff --git a/.github/workflows/mobile-android-release.yml b/.github/workflows/mobile-android-release.yml index ed0820862a5..770b391af27 100644 --- a/.github/workflows/mobile-android-release.yml +++ b/.github/workflows/mobile-android-release.yml @@ -284,7 +284,7 @@ jobs: "${{ steps.apk.outputs.checksum }}" fi - # Advisory like the site bump: a failed mirror only leaves onorca.dev's "mirror link" on the prior APK. + # Advisory like the site bump: a failed mirror only leaves orca.dev's "mirror link" on the prior APK. release-mirror-r2: needs: android-build if: needs.android-build.outputs.publish_release == 'true' diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index 4eb8ec63f31..0ba46d5730c 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -34,18 +34,24 @@ on: - 'src/main/runtime/agent-session/agent-session-unsaved-*.ts' # The phone/host contract program's unmocked desktop sources and its declaration owner's inputs. - 'src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts' - - 'src/main/github/issue-field-options.ts' + - 'src/main/github/issues/issue-field-options.ts' - 'config/tsconfig.test.mobile-host-declarations.json' - 'config/tsconfig.node.json' - 'src/types/build-constants.d.ts' - 'src/main/native-chat/agent-session-wire/**' # Recorded phone transcripts exercise these host decoders and their runtime dependencies. - 'src/main/native-chat/*transcript*.ts' + - 'src/main/native-chat/transcript-discovery/**' + - 'src/main/native-chat/transcript-filesystem/**' + - 'src/main/native-chat/transcript-decoding/**' + - 'src/main/native-chat/transcript-streaming/**' + - 'src/main/native-chat/transcript-watching/**' + - 'src/main/native-chat/transcript-history/**' - 'src/main/native-chat/subagent-entry-id-bounds.ts' - 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds.ts' - 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-reasoning-row.ts' - - 'src/main/claude/claude-internal-message-content.ts' - - 'src/main/claude/claude-stop-hook-feedback.ts' + - 'src/main/claude/structured/journal/claude-internal-message-content.ts' + - 'src/main/claude/structured/journal/claude-stop-hook-feedback.ts' - 'src/main/claude/structured/journal/**' - 'src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl' - 'src/main/codex/app-server/codex-item-field-readers.ts' @@ -54,7 +60,55 @@ on: - 'src/main/codex/structured/journal/codex-goal-journal-rows.ts' - 'src/main/codex/__fixtures__/codex-hook-outcomes.jsonl' - 'src/main/ai-vault/session-scanner-*.ts' - - 'src/main/ai-vault/ai-vault-scan-cancellation.ts' + - 'src/main/ai-vault/discovery/agent-session-directories.ts' + - 'src/main/ai-vault/discovery/session-file-discovery.ts' + - 'src/main/ai-vault/discovery/session-json-file.ts' + - 'src/main/ai-vault/discovery/session-path-absence.ts' + - 'src/main/ai-vault/discovery/session-scanner-agent-sources.ts' + - 'src/main/ai-vault/discovery/session-scanner-candidates.ts' + - 'src/main/ai-vault/discovery/session-scanner-directory-reader.test.ts' + - 'src/main/ai-vault/discovery/session-scanner-discovery-pipeline.test.ts' + - 'src/main/ai-vault/discovery/session-scanner-discovery.ts' + - 'src/main/ai-vault/discovery/session-scanner-roots.ts' + - 'src/main/ai-vault/discovery/session-scanner-source-discovery.ts' + - 'src/main/ai-vault/parsing/session-json-object.ts' + - 'src/main/ai-vault/parsing/session-record-fields.ts' + - 'src/main/ai-vault/parsing/session-record-time.ts' + - 'src/main/ai-vault/parsing/session-scanner-accumulator.ts' + - 'src/main/ai-vault/parsing/session-scanner-agent-parser.ts' + - 'src/main/ai-vault/parsing/session-scanner-candidate-parse.ts' + - 'src/main/ai-vault/parsing/session-scanner-core-parser-wsl-stall.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-injected-title.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-jsonl-reader.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-jsonl-reader.ts' + - 'src/main/ai-vault/parsing/session-scanner-messages.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-messages.ts' + - 'src/main/ai-vault/parsing/session-scanner-parse-wsl-stall.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-record-budget.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-recoverable-empty.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-text-normalization.ts' + - 'src/main/ai-vault/parsing/session-scanner-token-values.ts' + - 'src/main/ai-vault/parsing/session-scanner-unlimited-dedup.test.ts' + - 'src/main/ai-vault/prompts/session-scanner-first-user-prompt-capture.ts' + - 'src/main/ai-vault/prompts/session-scanner-first-user-prompt.test.ts' + - 'src/main/ai-vault/prompts/session-scanner-first-user-prompt.ts' + - 'src/main/ai-vault/scanner-fixtures/session-scanner-incremental-fixtures.ts' + - 'src/main/ai-vault/scanner-fixtures/session-scanner-prime-agent-fixtures.ts' + - 'src/main/ai-vault/scanner-fixtures/session-scanner-test-fixtures.ts' + - 'src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.ts' + - 'src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-discovery.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-inventory.test.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-inventory.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-only.test.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-walk.test.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-walk.ts' + - 'src/main/ai-vault/scope/session-scanner-scope.test.ts' + - 'src/main/ai-vault/session-scanner.ts' + - 'src/shared/error-message.ts' + - 'src/shared/surrogate-safe-text-slice.ts' + - 'src/shared/trimmed-string.ts' + - 'src/main/ai-vault/scan-lifecycle/ai-vault-scan-cancellation.ts' - 'src/main/ai-vault/scan-service/session-scanner-service-env.ts' - 'src/main/ai-vault/scanners/grok/session-scanner-grok-user-text.ts' - 'src/main/provider-process/provider-json-record.ts' @@ -122,18 +176,24 @@ on: - 'src/main/runtime/agent-session/agent-session-unsaved-*.ts' # The phone/host contract program's unmocked desktop sources and its declaration owner's inputs. - 'src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts' - - 'src/main/github/issue-field-options.ts' + - 'src/main/github/issues/issue-field-options.ts' - 'config/tsconfig.test.mobile-host-declarations.json' - 'config/tsconfig.node.json' - 'src/types/build-constants.d.ts' - 'src/main/native-chat/agent-session-wire/**' # Recorded phone transcripts exercise these host decoders and their runtime dependencies. - 'src/main/native-chat/*transcript*.ts' + - 'src/main/native-chat/transcript-discovery/**' + - 'src/main/native-chat/transcript-filesystem/**' + - 'src/main/native-chat/transcript-decoding/**' + - 'src/main/native-chat/transcript-streaming/**' + - 'src/main/native-chat/transcript-watching/**' + - 'src/main/native-chat/transcript-history/**' - 'src/main/native-chat/subagent-entry-id-bounds.ts' - 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds.ts' - 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-reasoning-row.ts' - - 'src/main/claude/claude-internal-message-content.ts' - - 'src/main/claude/claude-stop-hook-feedback.ts' + - 'src/main/claude/structured/journal/claude-internal-message-content.ts' + - 'src/main/claude/structured/journal/claude-stop-hook-feedback.ts' - 'src/main/claude/structured/journal/**' - 'src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl' - 'src/main/codex/app-server/codex-item-field-readers.ts' @@ -142,7 +202,55 @@ on: - 'src/main/codex/structured/journal/codex-goal-journal-rows.ts' - 'src/main/codex/__fixtures__/codex-hook-outcomes.jsonl' - 'src/main/ai-vault/session-scanner-*.ts' - - 'src/main/ai-vault/ai-vault-scan-cancellation.ts' + - 'src/main/ai-vault/discovery/agent-session-directories.ts' + - 'src/main/ai-vault/discovery/session-file-discovery.ts' + - 'src/main/ai-vault/discovery/session-json-file.ts' + - 'src/main/ai-vault/discovery/session-path-absence.ts' + - 'src/main/ai-vault/discovery/session-scanner-agent-sources.ts' + - 'src/main/ai-vault/discovery/session-scanner-candidates.ts' + - 'src/main/ai-vault/discovery/session-scanner-directory-reader.test.ts' + - 'src/main/ai-vault/discovery/session-scanner-discovery-pipeline.test.ts' + - 'src/main/ai-vault/discovery/session-scanner-discovery.ts' + - 'src/main/ai-vault/discovery/session-scanner-roots.ts' + - 'src/main/ai-vault/discovery/session-scanner-source-discovery.ts' + - 'src/main/ai-vault/parsing/session-json-object.ts' + - 'src/main/ai-vault/parsing/session-record-fields.ts' + - 'src/main/ai-vault/parsing/session-record-time.ts' + - 'src/main/ai-vault/parsing/session-scanner-accumulator.ts' + - 'src/main/ai-vault/parsing/session-scanner-agent-parser.ts' + - 'src/main/ai-vault/parsing/session-scanner-candidate-parse.ts' + - 'src/main/ai-vault/parsing/session-scanner-core-parser-wsl-stall.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-injected-title.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-jsonl-reader.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-jsonl-reader.ts' + - 'src/main/ai-vault/parsing/session-scanner-messages.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-messages.ts' + - 'src/main/ai-vault/parsing/session-scanner-parse-wsl-stall.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-record-budget.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-recoverable-empty.test.ts' + - 'src/main/ai-vault/parsing/session-scanner-text-normalization.ts' + - 'src/main/ai-vault/parsing/session-scanner-token-values.ts' + - 'src/main/ai-vault/parsing/session-scanner-unlimited-dedup.test.ts' + - 'src/main/ai-vault/prompts/session-scanner-first-user-prompt-capture.ts' + - 'src/main/ai-vault/prompts/session-scanner-first-user-prompt.test.ts' + - 'src/main/ai-vault/prompts/session-scanner-first-user-prompt.ts' + - 'src/main/ai-vault/scanner-fixtures/session-scanner-incremental-fixtures.ts' + - 'src/main/ai-vault/scanner-fixtures/session-scanner-prime-agent-fixtures.ts' + - 'src/main/ai-vault/scanner-fixtures/session-scanner-test-fixtures.ts' + - 'src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.ts' + - 'src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-discovery.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-inventory.test.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-inventory.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-only.test.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-walk.test.ts' + - 'src/main/ai-vault/scope/session-scanner-scope-walk.ts' + - 'src/main/ai-vault/scope/session-scanner-scope.test.ts' + - 'src/main/ai-vault/session-scanner.ts' + - 'src/shared/error-message.ts' + - 'src/shared/surrogate-safe-text-slice.ts' + - 'src/shared/trimmed-string.ts' + - 'src/main/ai-vault/scan-lifecycle/ai-vault-scan-cancellation.ts' - 'src/main/ai-vault/scan-service/session-scanner-service-env.ts' - 'src/main/ai-vault/scanners/grok/session-scanner-grok-user-text.ts' - 'src/main/provider-process/provider-json-record.ts' diff --git a/.github/workflows/node-server-tests.yml b/.github/workflows/node-server-tests.yml index 18334d1e587..bf9d65525a1 100644 --- a/.github/workflows/node-server-tests.yml +++ b/.github/workflows/node-server-tests.yml @@ -247,7 +247,7 @@ jobs: run: node "$(if [ -f config/scripts/orcad-distribution/template/build-orcad-template.mjs ]; then printf %s config/scripts/orcad-distribution/template/build-orcad-template.mjs; else printf %s config/scripts/build-orcad-template.mjs; fi)" --targets linux-${{ runner.arch == 'ARM64' && 'arm64' || 'x64' }}-glibc - name: Verify a structured chat from the desktop server template if: runner.os == 'Linux' - run: pnpm test:node-server --artifact src/main/orcad/orcad-packaged-structured-chat.integration.test.ts --maxWorkers=2 + run: pnpm test:node-server --artifact src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts --maxWorkers=2 # Only a Windows runner compiles it; arm64 cross-compiles here. # Before the Node 18 check below: the build script imports TypeScript, which Node 18 cannot load. # orcad's instance lock and stop proof read a PID's creation time through it; the x64 binary this diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ef97a54bf90..afa721690d0 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -851,9 +851,10 @@ jobs: src/main/pty/history/terminal-history-fish-session.node-pty.test.ts \ src/main/pty/shell-startup/zsh-scoped-histfile.live-shell.test.ts \ src/main/pty/shell-startup/zsh-startup-hook-user-config-equivalence.live-shell.test.ts \ + src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts \ src/main/runtime/agent-session/environment/structured-session-cli-login-shell.live-shell.test.ts \ - src/main/startup/shell-probe-terminal-detach.live-shell.test.ts \ - src/main/startup/shell-probe-lifetime.live-shell.test.ts \ + src/main/startup/shell-environment/shell-probe-terminal-detach.live-shell.test.ts \ + src/main/startup/shell-environment/shell-probe-lifetime.live-shell.test.ts \ src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts \ src/shared/fish-wsl-cwd-report.node-pty.test.ts \ src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts \ @@ -1116,7 +1117,6 @@ jobs: src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts - src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts diff --git a/.github/workflows/preflight-cli-platforms.yml b/.github/workflows/preflight-cli-platforms.yml index ba38aee2ea6..566c3a27418 100644 --- a/.github/workflows/preflight-cli-platforms.yml +++ b/.github/workflows/preflight-cli-platforms.yml @@ -47,8 +47,8 @@ jobs: src/main/ipc/preflight-runnable-local-cli.test.ts src/main/ipc/preflight-wsl-agent-detection.test.ts src/main/ipc/preflight-windows-path-refresh.repro.test.ts - src/main/startup/hydrate-shell-path.windows.test.ts - src/main/startup/login-shell-environment.test.ts + src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts + src/main/startup/shell-environment/login-shell-environment.test.ts src/packages/process-host/src/process-tree-termination.test.ts src/packages/process-host/src/run-process.test.ts src/packages/process-host/src/run-process-termination-failure.test.ts diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 01ed0b8ffe1..7ad27fefb3c 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -1321,7 +1321,7 @@ jobs: ORCA_BUILD_IDENTITY: ${{ steps.tag-classify.outputs.identity }} SHARED_JAVASCRIPT: ${{ needs.release-javascript.outputs.supported }} ORCA_RELEASE_JAVASCRIPT_SOURCE_SHA: ${{ needs.release-javascript.outputs.source_sha }} - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token ORCA_POSTHOG_WRITE_KEY: ${{ secrets.ORCA_POSTHOG_WRITE_KEY }} # After the app build so nothing that cleans out/ can drop it; electron-builder ships it. @@ -2357,7 +2357,7 @@ jobs: needs: - cut - publish-release - # Why stable-only: onorca.dev's mirror link tracks GitHub's latest release, which skips RCs. + # Why stable-only: orca.dev's mirror link tracks GitHub's latest release, which skips RCs. if: ${{ !cancelled() && needs.publish-release.result == 'success' && needs.cut.outputs.tag != '' && !contains(needs.cut.outputs.tag, '-rc.') && startsWith(needs.cut.outputs.tag, 'v') }} uses: ./.github/workflows/release-mirror-r2.yml with: diff --git a/.github/workflows/release-javascript.yml b/.github/workflows/release-javascript.yml index 547794d2ab5..3dce7ab7500 100644 --- a/.github/workflows/release-javascript.yml +++ b/.github/workflows/release-javascript.yml @@ -92,7 +92,7 @@ jobs: ORCA_CLI_BUILD_COMPILER: ${{ inputs.dev_build && 'tsrs' || 'bun' }} ORCA_BUILD_IDENTITY: ${{ steps.identity.outputs.value }} ORCA_RELEASE_JAVASCRIPT_BUILD_IDENTITY: ${{ inputs.dev_build && 'dev' || '' }} - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token ORCA_POSTHOG_WRITE_KEY: ${{ !inputs.dev_build && secrets.ORCA_POSTHOG_WRITE_KEY || '' }} run: | pnpm run "$JAVASCRIPT_BUILD_SCRIPT" diff --git a/.github/workflows/release-mac-build.yml b/.github/workflows/release-mac-build.yml index dabbe336dfe..443a9e14a86 100644 --- a/.github/workflows/release-mac-build.yml +++ b/.github/workflows/release-mac-build.yml @@ -189,7 +189,7 @@ jobs: NODE_OPTIONS: --max-old-space-size=4096 ORCA_BUILD_IDENTITY: ${{ steps.tag-classify.outputs.identity }} ORCA_RELEASE_JAVASCRIPT_SOURCE_SHA: ${{ inputs.javascript_source_sha }} - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token ORCA_POSTHOG_WRITE_KEY: ${{ secrets.ORCA_POSTHOG_WRITE_KEY }} # Design D2: the parent release-cut run merged it from every node-server lane at this tag. diff --git a/.github/workflows/release-mirror-r2.yml b/.github/workflows/release-mirror-r2.yml index 1c26596b29a..5eb6ef0983d 100644 --- a/.github/workflows/release-mirror-r2.yml +++ b/.github/workflows/release-mirror-r2.yml @@ -1,7 +1,7 @@ name: Release Mirror (R2) -# Copy published release downloads to the public R2 bucket behind https://downloads.onorca.dev. -# onorca.dev keeps GitHub as the default download and offers this as an opt-in "mirror link" +# Copy published release downloads to the public R2 bucket behind https://downloads.orca.dev. +# orca.dev keeps GitHub as the default download and offers this as an opt-in "mirror link" # for when GitHub release downloads return 5xx. Called by release-cut (stable desktop tags) and # mobile-android-release after publishing; dispatch manually to backfill a tag. @@ -13,7 +13,7 @@ on: required: true type: string assets: - description: Space-separated asset names (blank = the onorca.dev download assets) + description: Space-separated asset names (blank = the orca.dev download assets) required: false default: '' type: string @@ -24,7 +24,7 @@ on: required: true type: string assets: - description: Space-separated asset names (blank = the onorca.dev download assets) + description: Space-separated asset names (blank = the orca.dev download assets) required: false default: '' type: string diff --git a/.github/workflows/ssh-hostile-hosts.yml b/.github/workflows/ssh-hostile-hosts.yml index 00c23a1b9de..fa45eff64b3 100644 --- a/.github/workflows/ssh-hostile-hosts.yml +++ b/.github/workflows/ssh-hostile-hosts.yml @@ -15,8 +15,8 @@ on: - 'src/main/managed-server/**' - 'src/main/ssh/migration-source/**' - 'src/main/persistence/migrating-orcad-catalog/**' - - 'src/main/orcad/orcad-artifact-materializer.ts' - - 'src/main/orcad/orcad-host-unavailable.ts' + - 'src/main/orcad/artifact-slots/orcad-artifact-materializer.ts' + - 'src/main/orcad/diagnostics/orcad-host-unavailable.ts' - 'src/main/node-runtime/**' - 'src/main/ssh/remote-exec/**' - 'src/main/ssh/remote-host/**' diff --git a/.github/workflows/ssh-windows-hosts.yml b/.github/workflows/ssh-windows-hosts.yml index 9f7a2496700..f2a0ca584dd 100644 --- a/.github/workflows/ssh-windows-hosts.yml +++ b/.github/workflows/ssh-windows-hosts.yml @@ -12,8 +12,8 @@ on: - 'src/main/managed-server/**' - 'src/main/ssh/migration-source/**' - 'src/main/persistence/migrating-orcad-catalog/**' - - 'src/main/orcad/orcad-artifact-materializer.ts' - - 'src/main/orcad/orcad-host-unavailable.ts' + - 'src/main/orcad/artifact-slots/orcad-artifact-materializer.ts' + - 'src/main/orcad/diagnostics/orcad-host-unavailable.ts' - 'src/main/node-runtime/**' - 'src/main/ssh/remote-exec/**' - 'src/main/ssh/remote-host/**' @@ -38,7 +38,7 @@ on: - 'config/scripts/native-build/windows/build-windows-cli-launcher.mjs' - 'config/scripts/native-build/windows/windows-rust-executable-build.mjs' - 'native/windows-cli-launcher/**' - - 'src/main/orcad/orcad-cli-launcher.ts' + - 'src/main/orcad/serve-startup/orcad-cli-launcher.ts' - '.github/actions/prepare-windows-cli-launcher/**' - 'config/patches/node-pty*' - 'config/patches/@vscode__windows-process-tree*' diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 0473b42de3b..598db059065 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -221,8 +221,8 @@ jobs: pnpm-lock.yaml cloud/pnpm-lock.yaml - # These two tests import the cloud relay workspace directly. Keeping them in one job - # avoids installing and building the same workspace once per unit-test shard. + # This test imports the cloud relay workspace directly. Its dedicated job avoids + # installing and building the same workspace once per unit-test shard. - name: Install relay integration dependencies id: relay_dependencies if: ${{ !cancelled() && steps.root_dependencies.outcome == 'success' }} @@ -237,5 +237,4 @@ jobs: ORCA_BACKGROUND_LAUNCH: '1' run: >- pnpm exec vitest run --config config/vitest.config.ts - tests/e2e/relay-region-compatibility.unit.test.ts tests/e2e/relay-region-correction.unit.test.ts diff --git a/.github/workflows/zcode-transcript-contract.yml b/.github/workflows/zcode-transcript-contract.yml index 3c1c7b640a8..eacd35634f8 100644 --- a/.github/workflows/zcode-transcript-contract.yml +++ b/.github/workflows/zcode-transcript-contract.yml @@ -7,8 +7,7 @@ on: - 'src/main/ai-vault/scanners/opencode/**' - 'src/main/ai-vault/scanners/opencode2/**' - 'src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime*' - - 'src/main/native-chat/transcript-opencode*' - - 'src/main/native-chat/transcript-zcode*' + - 'src/main/native-chat/transcript-history/opencode/**' - 'src/shared/native-chat/native-chat-types.ts' - 'src/shared/native-chat/transcript/native-chat-transcript-projection*' - '.github/workflows/zcode-transcript-contract.yml' @@ -41,4 +40,4 @@ jobs: bun-version-file: config/.bun-version no-cache: true - name: Verify SQLite ordering, legacy readers, and host routing - run: pnpm test src/main/native-chat/transcript-zcode.test.ts src/main/native-chat/transcript-opencode-sqlite-query.test.ts src/main/ai-vault/scanners/zcode/session-scanner-zcode.test.ts src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-transcript-order.test.ts + run: pnpm test src/main/native-chat/transcript-history/opencode/transcript-zcode.test.ts src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.test.ts src/main/ai-vault/scanners/zcode/session-scanner-zcode.test.ts src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-transcript-order.test.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index 9601fee85cc..a2f65ca794b 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -308,7 +308,7 @@ "ignorePatterns": [ "src/main/acp/generated/acp-protocol.generated.ts", "src/shared/rpc-contract/rpc-params-catalog.generated.ts", - "src/cli/bundled-skill-guides.ts", + "src/cli/skills/bundled-skill-guides.ts", "resources/plugins/declarative/*.mjs", "**/node_modules", "**/dist", diff --git a/Casks/orca.rb b/Casks/orca.rb index 51787cde42f..8e6dbf1bec8 100644 --- a/Casks/orca.rb +++ b/Casks/orca.rb @@ -8,7 +8,7 @@ cask "orca" do url "https://github.com/stablyai/orca/releases/download/v#{version}/orca-macos-#{arch}.dmg" name "Orca" desc "IDE for orchestrating AI coding agents across terminals and worktrees" - homepage "https://onorca.dev/" + homepage "https://orca.dev/" livecheck do url :url diff --git a/Casks/orca@rc.rb b/Casks/orca@rc.rb index 61b1aeb268a..21769cceb15 100644 --- a/Casks/orca@rc.rb +++ b/Casks/orca@rc.rb @@ -8,7 +8,7 @@ cask "orca@rc" do url "https://github.com/stablyai/orca/releases/download/v#{version}/orca-macos-#{arch}.dmg" name "Orca RC" desc "IDE for orchestrating AI coding agents across terminals and worktrees" - homepage "https://onorca.dev/" + homepage "https://orca.dev/" livecheck do url "https://github.com/stablyai/orca" diff --git a/README.md b/README.md index bc1defaa9c6..aca12561eb8 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- Orca Orca + Orca Orca

@@ -20,7 +20,7 @@ Run Claude Code, Codex, and any other coding agent in parallel, each in its own worktree. Chat or terminal, on your laptop or in the cloud, with diffs, a browser, and a CLI in one app.

-

Download Orca

+

Download Orca

Orca desktop app with a coordinator agent running worker agents in parallel workspaces, and the Orca mobile app in the corner @@ -36,11 +36,11 @@ Run any agent in Chat UI or as the raw CLI, and move a conversation between the two without losing context. -[Docs →](https://www.onorca.dev/docs/agents/native-chat) +[Docs →](https://orca.dev/docs/agents/native-chat) - The same agent conversation in Chat UI and in the terminal, side by side + The same agent conversation in Chat UI and in the terminal, side by side @@ -50,11 +50,11 @@ Run any agent in Chat UI or as the raw CLI, and move a conversation between the Hand a big task to one agent. It splits the work, starts worker agents in their own workspaces, and brings their results back to you. -[Docs →](https://www.onorca.dev/docs/cli/orchestration) +[Docs →](https://orca.dev/docs/cli/orchestration) - A coordinator agent splitting a task between two worker agents and reporting their results + A coordinator agent splitting a task between two worker agents and reporting their results @@ -64,11 +64,11 @@ Hand a big task to one agent. It splits the work, starts worker agents in their Pair a Remote Orca Server, work on any SSH host, or give a worktree its own cloud VM. Your agents keep running when your laptop sleeps. -[Docs →](https://www.onorca.dev/docs/ways-to-run) +[Docs →](https://orca.dev/docs/ways-to-run) - Choosing which machine a new worktree runs on, from this computer to an SSH host or a per-workspace environment + Choosing which machine a new worktree runs on, from this computer to an SSH host or a per-workspace environment @@ -78,11 +78,11 @@ Pair a Remote Orca Server, work on any SSH host, or give a worktree its own clou Pair Orca with the mobile app to get pinged when an agent needs you, reply in chat, and keep work moving on any of your machines when you are away from your desk. -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://www.onorca.dev/download/android) · [Docs →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://orca.dev/download/android) · [Docs →](https://orca.dev/docs/mobile) - The Orca mobile app getting a notification that Claude needs input, opening the session, and replying so the agent opens the PR + The Orca mobile app getting a notification that Claude needs input, opening the session, and replying so the agent opens the PR @@ -92,11 +92,11 @@ Pair Orca with the mobile app to get pinged when an agent needs you, reply in ch Review diffs, leave notes on exact changed lines, and send focused feedback back to an agent. -[Docs →](https://www.onorca.dev/docs/review/annotate-ai-diff) +[Docs →](https://orca.dev/docs/review/annotate-ai-diff) - A note on a changed diff line sent back to the agent + A note on a changed diff line sent back to the agent @@ -106,11 +106,11 @@ Review diffs, leave notes on exact changed lines, and send focused feedback back Draft commit messages and pull requests from the diff, then send failing checks or PR review comments back to an agent to fix. -[Docs →](https://www.onorca.dev/docs/review/commit-push) +[Docs →](https://orca.dev/docs/review/commit-push) - Drafting a commit and pull request, then sending a review comment back to the agent + Drafting a commit and pull request, then sending a review comment back to the agent @@ -120,11 +120,11 @@ Draft commit messages and pull requests from the diff, then send failing checks Quickly split tasks into isolated environments, so multiple agents can work side by side without interfering with each other. -[Docs →](https://www.onorca.dev/docs/model/worktrees) +[Docs →](https://orca.dev/docs/model/worktrees) - Creating a new worktree with its own agent next to other running worktrees + Creating a new worktree with its own agent next to other running worktrees @@ -134,11 +134,11 @@ Quickly split tasks into isolated environments, so multiple agents can work side Click any element in Orca's browser to copy its HTML, styles, and selector, then paste it into your agent's chat. -[Docs →](https://www.onorca.dev/docs/browser/design-mode) +[Docs →](https://orca.dev/docs/browser/design-mode) - Picking a button in Orca's browser and sending it to the agent's chat + Picking a button in Orca's browser and sending it to the agent's chat @@ -148,11 +148,11 @@ Click any element in Orca's browser to copy its HTML, styles, and selector, then See your GitHub and Linear tasks in one place, and start a workspace for each when you're ready to build. -[Docs →](https://www.onorca.dev/docs/review/linear) +[Docs →](https://orca.dev/docs/review/linear) - GitHub and Linear issues in Orca, with a workspace started from a Linear issue + GitHub and Linear issues in Orca, with a workspace started from a Linear issue @@ -162,11 +162,11 @@ See your GitHub and Linear tasks in one place, and start a workspace for each wh Anything you can do in Orca, your agents can do too: create worktrees, start workers, drive the browser and desktop apps, and schedule automations, all from the command line. -[Docs →](https://www.onorca.dev/docs/cli/overview) +[Docs →](https://orca.dev/docs/cli/overview) - An agent running orca worktree create to start a worker in a new worktree + An agent running orca worktree create to start a worker in a new worktree @@ -176,11 +176,11 @@ Anything you can do in Orca, your agents can do too: create worktrees, start wor Themes, editors, languages, and panels from the community, installed in a click. -[Browse plugins →](https://www.onorca.dev/plugins) +[Browse plugins →](https://orca.dev/plugins) - Installing the Orca Midnight theme from the plugin catalog + Installing the Orca Midnight theme from the plugin catalog @@ -190,25 +190,25 @@ Themes, editors, languages, and panels from the community, installed in a click. Put agents, terminals, browsers, and diffs side by side in split panes shaped to the task. -[Docs →](https://www.onorca.dev/docs/model/tabs-panes-splits) +[Docs →](https://orca.dev/docs/model/tabs-panes-splits) - Dragging tabs into split panes with an agent, browser, terminal, and diff + Dragging tabs into split panes with an agent, browser, terminal, and diff **Also in the box:** -- **[Drag Files to Agents](https://www.onorca.dev/docs/editing/file-explorer)**: drag files from the explorer, or images from your desktop, straight into an agent's prompt. -- **[Jump Anywhere](https://www.onorca.dev/docs/model/quick-open)**: one shortcut jumps to any workspace or tab across every repo and host. -- **[Rich Previews](https://www.onorca.dev/docs/editing/viewers)**: open images, PDFs, and Markdown right in the workspace, next to the agent that made them. -- **[Mobile Emulator](https://www.onorca.dev/docs/cli/overview#mobile-emulator)**: run an iOS Simulator or Android emulator beside your agent, and let it tap, type, and check its own work. -- **[Dictation](https://www.onorca.dev/docs/settings#voice)**: press a shortcut and talk. Orca types what you say into the agent's prompt or terminal. -- **[Usage & Accounts](https://www.onorca.dev/docs/agents/usage-tracking)**: see how much of your agent limits you've used and when they reset, and switch accounts without logging out. -- **[Automations](https://www.onorca.dev/docs/cli/automations)**: schedule prompts to run on any repo: nightly dependency bumps, weekly triage, flaky-test sweeps. -- **[Computer Use](https://www.onorca.dev/docs/cli/computer-use)**: when there's no CLI or API, agents can see and drive desktop apps and external browsers. +- **[Drag Files to Agents](https://orca.dev/docs/editing/file-explorer)**: drag files from the explorer, or images from your desktop, straight into an agent's prompt. +- **[Jump Anywhere](https://orca.dev/docs/model/quick-open)**: one shortcut jumps to any workspace or tab across every repo and host. +- **[Rich Previews](https://orca.dev/docs/editing/viewers)**: open images, PDFs, and Markdown right in the workspace, next to the agent that made them. +- **[Mobile Emulator](https://orca.dev/docs/cli/overview#mobile-emulator)**: run an iOS Simulator or Android emulator beside your agent, and let it tap, type, and check its own work. +- **[Dictation](https://orca.dev/docs/settings#voice)**: press a shortcut and talk. Orca types what you say into the agent's prompt or terminal. +- **[Usage & Accounts](https://orca.dev/docs/agents/usage-tracking)**: see how much of your agent limits you've used and when they reset, and switch accounts without logging out. +- **[Automations](https://orca.dev/docs/cli/automations)**: schedule prompts to run on any repo: nightly dependency bumps, weekly triage, flaky-test sweeps. +- **[Computer Use](https://orca.dev/docs/cli/computer-use)**: when there's no CLI or API, agents can see and drive desktop apps and external browsers. - **And many, many more**: we ship daily, so this list is perpetually behind. The [changelog](https://github.com/stablyai/orca/releases) is the real feature list. --- @@ -261,7 +261,7 @@ Works with **any CLI agent** — if it runs in a terminal, it runs in Orca. ### Desktop — macOS, Windows, Linux -- **[Download from onOrca.dev](https://onorca.dev/download)** +- **[Download from orca.dev](https://orca.dev/download)** - Or grab a build directly: [macOS Apple Silicon](https://github.com/stablyai/orca/releases/latest/download/orca-macos-arm64.dmg) · [macOS Intel](https://github.com/stablyai/orca/releases/latest/download/orca-macos-x64.dmg) · [Windows (.exe)](https://github.com/stablyai/orca/releases/latest/download/orca-windows-setup.exe) · [Linux AppImage](https://github.com/stablyai/orca/releases/latest/download/orca-linux.AppImage) · [All builds](https://github.com/stablyai/orca/releases/latest) _Or via a package manager:_ @@ -284,7 +284,7 @@ yay -S stably-orca-bin Pair with your desktop app to monitor and steer your agents from your phone. - **iOS:** [Download on the App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [Download APK](https://www.onorca.dev/download/android) · [Install guide](https://www.onorca.dev/docs/android-apk) +- **Android:** [Download APK](https://orca.dev/download/android) · [Install guide](https://orca.dev/docs/android-apk) --- @@ -297,7 +297,7 @@ Pair with your desktop app to monitor and steer your agents from your phone. WeChat QR code for the Orca community - **Feedback & Ideas:** We ship fast. Missing something? [Request a new feature](https://github.com/stablyai/orca/issues). -- **Privacy:** See the [privacy & telemetry docs](https://www.onorca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out. +- **Privacy:** See the [privacy & telemetry docs](https://orca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out. - **Show Support:** [Star](https://github.com/stablyai/orca) this repo to follow along with our daily ships. --- diff --git a/cloud/apps/push/src/delivery/durable-push-claim.test.ts b/cloud/apps/push/src/delivery/durable-push-claim.test.ts index 93f65135504..181f01c6cf8 100644 --- a/cloud/apps/push/src/delivery/durable-push-claim.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-claim.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, it } from 'vitest' import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' -import { DELIVERY_LEASE_MS, DurablePushStore } from './durable-push-store.js' +import { DurablePushStore } from './durable-push-store.js' import { cleanupDurablePushFixtures, @@ -63,20 +63,6 @@ it.skipIf(!durablePushTestDatabaseUrl)( } ) -it('leases exactly one delivery per device across concurrent claimers', async () => { - const { db, store, clock, advance } = await fixture() - for (let seq = 1; seq <= 5; seq++) { - await store.accept('host', 'phone', notification(seq)) - advance(1) - } - const claims = await Promise.all( - Array.from({ length: 8 }, () => new DurablePushStore(db, clock).claim()) - ) - const leased = claims.filter((claim) => claim !== null) - expect(leased).toHaveLength(1) - expect(leased[0]?.notification.notificationSeq).toBe(1) -}) - it.skipIf(!durablePushTestDatabaseUrl)( 'does not lease the row behind a head another claimer holds', async () => { @@ -138,21 +124,3 @@ it.skipIf(!durablePushTestDatabaseUrl)( expect((await first)?.notification.notificationSeq).toBe(1) } ) - -// Only the TTL term keeps the candidate scan off an unpruned backlog; expires_at is not indexed first. - -it('frees a device held by a crashed worker once its lease lapses', async () => { - const { db, store, clock, advance } = await fixture() - await store.accept('host', 'phone', notification(1)) - advance(1) - await store.accept('host', 'phone', notification(2)) - const crashed = (await new DurablePushStore(db, clock).claim())! - advance(DELIVERY_LEASE_MS - 1) - expect(await store.claim()).toBeNull() - advance(1) - const reclaimed = (await store.claim())! - expect(reclaimed.id).toBe(crashed.id) - expect(reclaimed.attempts).toBe(2) - await store.finish(reclaimed) - expect((await store.claim())?.notification.notificationSeq).toBe(2) -}) diff --git a/cloud/apps/push/src/delivery/durable-push-store.test.ts b/cloud/apps/push/src/delivery/durable-push-store.test.ts index 9be0e32ec8f..9db7f983172 100644 --- a/cloud/apps/push/src/delivery/durable-push-store.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-store.test.ts @@ -1,9 +1,7 @@ import { afterEach, describe, expect, it } from 'vitest' -import { openPushDatabase } from '../database/push-database.js' import { DurablePushStore, DELIVERY_LEASE_MS } from './durable-push-store.js' import { cleanupDurablePushFixtures, - durablePushTestDatabaseUrl, fixture, notification } from './durable-push-store.test-fixture.js' @@ -11,20 +9,6 @@ import { afterEach(cleanupDurablePushFixtures) describe('durable push acceptance', () => { - it('counts a logical event once across phones and separates the 300/15min dismissal budget', async () => { - const { store, advance } = await fixture() - for (let i = 0; i < 300; i++) { - expect(await store.accept('host', 'phone1', notification(i))).toBe('queued') - expect(await store.accept('host', 'phone2', notification(i))).toBe('queued') - expect(await store.accept('host', 'phone1', notification(i, 'dismiss'))).toBe('queued') - } - expect(await store.accept('host', 'phone1', notification(300))).toBe('rate_limited') - expect(await store.accept('host', 'phone1', notification(300, 'dismiss'))).toBe('rate_limited') - expect(await store.accept('another-host', 'phone3', notification(300))).toBe('queued') - advance(15 * 60_000) - expect(await store.accept('host', 'phone1', notification(301))).toBe('queued') - }) - it('queues one delivery per event and recovers work across service instances', async () => { const { db, store, clock, advance } = await fixture() await store.accept('host', 'phone', notification(1)) @@ -32,16 +16,6 @@ describe('durable push acceptance', () => { await restarted.accept('host', 'phone', notification(1)) advance(1) await restarted.accept('host', 'phone', notification(2)) - const rows = await db.query( - "SELECT payload_json, due_at, created_at FROM push_delivery_batches WHERE registration_id = ? AND state = 'pending' ORDER BY created_at, batch_id", - ['phone'] - ) - expect(rows).toHaveLength(2) - expect(rows.map((row) => JSON.parse(String(row.payload_json)))).toEqual([ - notification(1), - notification(2) - ]) - expect(rows.every((row) => Number(row.due_at) >= Number(row.created_at))).toBe(true) const delivery = await restarted.claim() expect(delivery?.notification.notificationSeq).toBe(1) expect(await store.claim()).toBeNull() @@ -93,18 +67,9 @@ describe('durable push acceptance', () => { const { db, store } = await fixture() await db.query('ALTER TABLE push_delivery_batches RENAME TO push_delivery_batches_unavailable') try { - const databaseUrl = durablePushTestDatabaseUrl - if (databaseUrl) { - const concurrent = await openPushDatabase({ databaseUrl, dataDir: '' }) - try { - await expect( - concurrent.query('SELECT COUNT(*) FROM push_delivery_batches') - ).resolves.toHaveLength(1) - } finally { - await concurrent.close() - } - } - await expect(store.accept('host', 'phone', notification(1))).rejects.toThrow() + await expect(store.accept('host', 'phone', notification(1))).rejects.toThrow( + /push_delivery_batches/ + ) expect(await db.query('SELECT * FROM push_events')).toEqual([]) expect(await db.query('SELECT * FROM push_event_recipients')).toEqual([]) } finally { @@ -160,38 +125,3 @@ it('does not resurrect an in-flight alert after a dismissal and transient provid expect(await store.claim()).toBeNull() expect(await store.pendingCount('phone')).toBe(0) }) - -it('fences late renew and finish after an expired claim is dismissed', async () => { - const { db, store, advance } = await fixture() - const alert = notification(1) - await store.accept('host', 'phone', alert) - const stale = (await store.claim())! - advance(DELIVERY_LEASE_MS) - await store.accept('host', 'phone', { - ...notification(2, 'dismiss'), - notificationId: alert.notificationId - }) - const read = async () => - ( - await db.query( - 'SELECT state, payload_json, lease_until FROM push_delivery_batches WHERE batch_id = ?', - [stale.id] - ) - )[0] - expect(await read()).toBeUndefined() - await store.renew(stale) - await store.finish(stale, 1000) - await store.finish(stale) - expect(await read()).toBeUndefined() - const dismissal = (await store.claim())! - expect(dismissal.notification.kind).toBe('dismiss') - await store.finish(dismissal) - await store.accept('host', 'phone', notification(3)) - const fresh = (await store.claim())! - await store.finish(fresh, 1000) - advance(1000) - const retry = (await store.claim())! - expect(retry.id).toBe(fresh.id) - await store.finish(retry) - expect(await store.claim()).toBeNull() -}) diff --git a/cloud/apps/push/src/delivery/durable-push-worker.test.ts b/cloud/apps/push/src/delivery/durable-push-worker.test.ts index 78303de18e6..754094f07d9 100644 --- a/cloud/apps/push/src/delivery/durable-push-worker.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-worker.test.ts @@ -13,7 +13,6 @@ import { pauseAfter, within } from './durable-push-store.test-fixture.js' const cleanups: (() => Promise)[] = [] afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup() - vi.useRealTimers() vi.restoreAllMocks() }) const note = (seq: number, overrides: Partial = {}): PushNotification => ({ @@ -42,9 +41,8 @@ async function fixture() { const send = vi.fn(async (_delivery: PushDelivery): Promise => ({ status: 'sent' })) - const onRetry = vi.fn() const dispatcher = new PushDispatcher({ devices, fcm: { send } as never }) - const worker = new DurablePushWorker(store, dispatcher, { now, onRetry }) + const worker = new DurablePushWorker(store, dispatcher, { now }) cleanups.push(async () => { await worker.stop() await db.close() @@ -57,7 +55,6 @@ async function fixture() { worker, dispatcher, send, - onRetry, now, registrationId: device.registrationId, accept: (notification: PushNotification) => @@ -102,7 +99,6 @@ it('stops queued claim admissions without leasing the remaining device', async ( paused.release() await within(Promise.all([pending, stopping]), 2_000) expect(h.send).toHaveBeenCalledOnce() - expect(h.send.mock.calls[0]?.[0].orca.notificationSeq).toBe(1) const [remaining] = await h.db.query( 'SELECT attempts, lease_until FROM push_delivery_batches WHERE registration_id = ?', [other.registrationId] diff --git a/cloud/apps/push/src/devices/device-registry-store.test.ts b/cloud/apps/push/src/devices/device-registry-store.test.ts deleted file mode 100644 index 7639ed974b9..00000000000 --- a/cloud/apps/push/src/devices/device-registry-store.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { PushDeviceRegistryStore, type PushDeviceUpsert } from './device-registry-store.js' -import { openInMemoryPushDatabase } from '../database/push-database.js' -import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' - -const OWNER = 'abcdefghijklmnop' -const OTHER = 'ponmlkjihgfedcba' - -describe('push device registry store', () => { - let database: PushDatabase - let clock = 1_700_000_000_000 - let devices: PushDeviceRegistryStore - - beforeEach(async () => { - database = await openInMemoryPushDatabase() - clock = 1_700_000_000_000 - devices = new PushDeviceRegistryStore(database, () => clock) - }) - - afterEach(async () => { - await database.close() - }) - - async function upsertOk(input: PushDeviceUpsert): Promise { - const result = await devices.upsert(input) - if (!result.ok) throw new Error(`unexpected upsert refusal: ${result.reason}`) - return result.registrationId - } - - function androidDevice(deviceId: string): PushDeviceUpsert { - return { - hostFingerprint: OWNER, - deviceId, - platform: 'android', - token: `token-${deviceId}` - } - } - - it('keeps one registration per host and device while replacing the token', async () => { - const first = await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'device-1', - platform: 'ios', - token: 'a'.repeat(64), - apnsEnvironment: 'sandbox' - }) - clock += 1_000 - const second = await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'device-1', - platform: 'ios', - token: 'b'.repeat(64), - apnsEnvironment: 'production' - }) - expect(second).toBe(first) - const registration = await devices.findById(first) - expect(registration).toMatchObject({ - token: 'b'.repeat(64), - apnsEnvironment: 'production', - dead: false - }) - expect(await devices.list(OWNER)).toHaveLength(1) - }) - - it('revives a registration that a re-registered token replaces', async () => { - const registrationId = await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'device-1', - platform: 'android', - token: 'token-one' - }) - await devices.markDead((await devices.findById(registrationId))!) - expect((await devices.findById(registrationId))?.dead).toBe(true) - await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'device-1', - platform: 'android', - token: 'token-two' - }) - expect(await devices.findById(registrationId)).toMatchObject({ - token: 'token-two', - dead: false - }) - }) - - it('lets only the owning host delete a registration', async () => { - const registrationId = await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'device-1', - platform: 'android', - token: 'token-one' - }) - expect(await devices.deleteOwned(OTHER, registrationId)).toBe(false) - expect(await devices.findById(registrationId)).not.toBeNull() - expect(await devices.deleteOwned(OWNER, registrationId)).toBe(true) - expect(await devices.findById(registrationId)).toBeNull() - }) - - it('scopes lookups and listings to the owning host', async () => { - const owned = await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'device-1', - platform: 'android', - token: 'token-one' - }) - const foreign = await upsertOk({ - hostFingerprint: OTHER, - deviceId: 'device-2', - platform: 'android', - token: 'token-two' - }) - const found = await devices.findOwned(OWNER, [owned, foreign]) - expect([...found.keys()]).toEqual([owned]) - expect(await devices.list(OTHER)).toEqual([ - { registrationId: foreign, deviceId: 'device-2', platform: 'android', dead: false } - ]) - expect(await devices.findOwned(OWNER, [])).toEqual(new Map()) - }) - - it('counts the cap per host, not across the whole table', async () => { - for (let index = 0; index < PUSH_LIMITS.maxDevicesPerHost; index++) { - await upsertOk(androidDevice(`device-${index}`)) - } - expect((await devices.upsert(androidDevice('extra'))).ok).toBe(false) - expect( - (await devices.upsert({ ...androidDevice('device-0'), hostFingerprint: OTHER })).ok - ).toBe(true) - }) -}) diff --git a/cloud/apps/push/src/host-auth/host-challenge-store.test.ts b/cloud/apps/push/src/host-auth/host-challenge-store.test.ts index a5b4e5574ea..e0a05c095b3 100644 --- a/cloud/apps/push/src/host-auth/host-challenge-store.test.ts +++ b/cloud/apps/push/src/host-auth/host-challenge-store.test.ts @@ -1,4 +1,3 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { answerPushHostChallenge, @@ -27,33 +26,10 @@ describe('push host challenge store', () => { await database.close() }) - it('rejects a challenge the moment its own ttl elapses', async () => { - const host = createPushHostKeypair(4) - const challenge = await store.issue(hostPublicKeyB64(host)) - const proof = answerPushHostChallenge(challenge!, { - gatewayOrigin: GATEWAY_ORIGIN, - keypair: host, - now: () => clock - })! - clock += PUSH_LIMITS.challengeTtlMs + 1 - await expect(store.verify(challenge!.challengeId, proof)).resolves.toEqual({ - ok: false, - reason: 'expired' - }) - }) - - it('refuses a wrong host: the box will not open and a foreign proof will not match', async () => { + it('rejects a proof issued for another challenge', async () => { const owner = createPushHostKeypair(6) const intruder = createPushHostKeypair(7) const ownerChallenge = await store.issue(hostPublicKeyB64(owner)) - expect( - answerPushHostChallenge(ownerChallenge!, { - gatewayOrigin: GATEWAY_ORIGIN, - keypair: intruder, - now: () => clock - }) - ).toBeNull() - const intruderChallenge = await store.issue(hostPublicKeyB64(intruder)) const intruderProof = answerPushHostChallenge(intruderChallenge!, { gatewayOrigin: GATEWAY_ORIGIN, diff --git a/cloud/apps/push/src/host-auth/host-session-store.test.ts b/cloud/apps/push/src/host-auth/host-session-store.test.ts deleted file mode 100644 index 4389d310f4a..00000000000 --- a/cloud/apps/push/src/host-auth/host-session-store.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { PushHostSessionStore } from './host-session-store.js' -import { openInMemoryPushDatabase } from '../database/push-database.js' -import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' - -const HOST = 'abcdefghijklmnop' - -describe('push host session store', () => { - let database: PushDatabase - let clock = 1_700_000_000_000 - let sessions: PushHostSessionStore - - beforeEach(async () => { - database = await openInMemoryPushDatabase() - clock = 1_700_000_000_000 - sessions = new PushHostSessionStore(database, () => clock) - }) - - afterEach(async () => { - await database.close() - }) - - it('reports expiry separately from an unknown token', async () => { - const session = await sessions.create(HOST) - clock += PUSH_LIMITS.sessionTtlMs + 1 - await expect(sessions.resolve(session.sessionToken)).resolves.toEqual({ - ok: false, - reason: 'session_expired' - }) - await expect(sessions.resolve('not-a-session')).resolves.toEqual({ - ok: false, - reason: 'unknown_session' - }) - }) - - it('keeps one live session per host and prunes it once expired', async () => { - const first = await sessions.create(HOST) - const second = await sessions.create(HOST) - // The earlier session is gone the moment its host proves again, so a flood - // of proofs leaves one row per host rather than one per proof. - await expect(sessions.resolve(first.sessionToken)).resolves.toEqual({ - ok: false, - reason: 'unknown_session' - }) - await expect(sessions.resolve(second.sessionToken)).resolves.toMatchObject({ ok: true }) - const other = await sessions.create('ponmlkjihgfedcba') - await expect(sessions.resolve(second.sessionToken)).resolves.toMatchObject({ ok: true }) - clock += PUSH_LIMITS.sessionTtlMs + 1 - expect(await sessions.pruneExpired()).toBe(2) - await expect(sessions.resolve(other.sessionToken)).resolves.toMatchObject({ ok: false }) - }) -}) diff --git a/cloud/apps/push/src/host-auth/push-session-concurrency.test.ts b/cloud/apps/push/src/host-auth/push-session-concurrency.test.ts index 221a5c91ab4..4d9cc37b07d 100644 --- a/cloud/apps/push/src/host-auth/push-session-concurrency.test.ts +++ b/cloud/apps/push/src/host-auth/push-session-concurrency.test.ts @@ -19,11 +19,6 @@ async function concurrentSessions(db: PushDatabase) { sessions.map((session) => store.resolve(session.sessionToken)) ) expect(decisions.filter((decision) => decision.ok)).toHaveLength(1) - const [row] = await db.query( - 'SELECT COUNT(*) AS count FROM push_sessions WHERE host_fingerprint = ?', - [host] - ) - expect(Number(row?.count)).toBe(1) } finally { await db.query('DELETE FROM push_sessions WHERE host_fingerprint = ?', [host]) } diff --git a/cloud/apps/push/src/http/client-ip-rate-limit.test.ts b/cloud/apps/push/src/http/client-ip-rate-limit.test.ts deleted file mode 100644 index 041b1577f08..00000000000 --- a/cloud/apps/push/src/http/client-ip-rate-limit.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' -import { Hono } from 'hono' -import { describe, expect, it } from 'vitest' -import { ClientIpRateLimiter, clientIpRateLimit } from './client-ip-rate-limit.js' - -const CAPACITY = PUSH_LIMITS.unauthenticatedRequestsPerMinutePerIp - -function limiterApp(limiter: ClientIpRateLimiter, trustedProxyHops = 0): Hono { - const app = new Hono() - app.post('/probe', clientIpRateLimit(limiter, { trustedProxyHops }), (context) => - context.json({ ok: true }) - ) - return app -} - -describe('client ip rate limiter', () => { - it('buckets on the last forwarded hop, the only one the platform appended', async () => { - const app = limiterApp(new ClientIpRateLimiter({ now: () => 1_000 })) - for (let index = 0; index < CAPACITY; index++) { - await app.request('/probe', { - method: 'POST', - headers: { 'x-forwarded-for': `10.0.0.${index}, 203.0.113.7` } - }) - } - const sameClient = await app.request('/probe', { - method: 'POST', - headers: { 'x-forwarded-for': '10.9.9.9, 203.0.113.7' } - }) - expect(sameClient.status).toBe(429) - const otherClient = await app.request('/probe', { - method: 'POST', - headers: { 'x-forwarded-for': '10.0.0.1, 198.51.100.9' } - }) - expect(otherClient.status).toBe(200) - }) - - it('skips the configured trusted proxies when counting from the right', async () => { - const app = limiterApp(new ClientIpRateLimiter({ now: () => 1_000, capacity: 1 }), 1) - // , , : one trusted hop after the client. - const headers = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } - expect((await app.request('/probe', { method: 'POST', headers })).status).toBe(200) - expect((await app.request('/probe', { method: 'POST', headers })).status).toBe(429) - expect( - ( - await app.request('/probe', { - method: 'POST', - headers: { 'x-forwarded-for': '198.51.100.9, 10.0.0.1' } - }) - ).status - ).toBe(200) - }) - - it('trusts nothing when the header is shorter than the configured depth', async () => { - const app = limiterApp(new ClientIpRateLimiter({ now: () => 1_000, capacity: 1 }), 1) - // Only one hop, so the client value the depth points at does not exist. - const headers = { 'x-forwarded-for': '203.0.113.7' } - expect((await app.request('/probe', { method: 'POST', headers })).status).toBe(200) - expect( - ( - await app.request('/probe', { - method: 'POST', - headers: { 'x-forwarded-for': '198.51.100.9' } - }) - ).status - ).toBe(429) - }) - - it('ignores spoofable x-real-ip and uses a single shared bucket', async () => { - const app = limiterApp(new ClientIpRateLimiter({ now: () => 1_000, capacity: 1 })) - expect( - (await app.request('/probe', { method: 'POST', headers: { 'x-real-ip': '198.51.100.9' } })) - .status - ).toBe(200) - expect( - (await app.request('/probe', { method: 'POST', headers: { 'x-real-ip': '203.0.113.7' } })) - .status - ).toBe(429) - expect((await app.request('/probe', { method: 'POST' })).status).toBe(429) - expect((await app.request('/probe', { method: 'POST' })).status).toBe(429) - }) -}) diff --git a/cloud/apps/push/src/http/push-send-idempotency.test.ts b/cloud/apps/push/src/http/push-send-idempotency.test.ts deleted file mode 100644 index b061eef3040..00000000000 --- a/cloud/apps/push/src/http/push-send-idempotency.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' -import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' -const harnesses: Awaited>[] = [] -afterEach(async () => { - await Promise.all(harnesses.splice(0).map((h) => h.close())) -}) - -it('returns queued for concurrent retries without double quota or delivery', async () => { - const h = await createPushServerHarness() - harnesses.push(h) - const token = await h.signIn(createPushHostKeypair(2)) - const registrationId = await h.registerAndroid(token) - const body = { v: 1, registrationIds: [registrationId], notification: notification() } - const responses = await Promise.all( - Array.from({ length: 10 }, () => h.post('/v1/send', body, token)) - ) - for (const response of responses) - expect(await response.json()).toEqual({ results: [{ registrationId, status: 'queued' }] }) - expect(await h.server.deliveryStore.pendingCount(registrationId)).toBe(1) - await h.flushDeliveries() - await h.post('/v1/send', body, token) - await h.flushDeliveries() - expect(h.fcmRequests).toHaveLength(1) - expect(JSON.parse(h.fcmRequests[0]!.body).message.data.coalescedCount).toBeUndefined() - expect( - Number((await h.database.query('SELECT COUNT(*) AS count FROM push_events'))[0]?.count) - ).toBe(1) - await h.post( - '/v1/send', - { ...body, notification: notification({ notificationEpoch: 'new-epoch' }) }, - token - ) - await h.flushDeliveries() - expect(h.fcmRequests).toHaveLength(2) -}) diff --git a/cloud/apps/push/src/http/push-server-auth.test.ts b/cloud/apps/push/src/http/push-server-auth.test.ts index ad1989955f7..7c06e9c0d5d 100644 --- a/cloud/apps/push/src/http/push-server-auth.test.ts +++ b/cloud/apps/push/src/http/push-server-auth.test.ts @@ -1,9 +1,6 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' -import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' -import { createPushServer } from '../push-server.js' -import { createPushServerHarness, testPushConfig } from './push-server-harness.test-fixture.js' +import { createPushServerHarness } from './push-server-harness.test-fixture.js' describe('push gateway authentication and device routes', () => { let harness: Awaited> @@ -16,63 +13,6 @@ describe('push gateway authentication and device routes', () => { await harness.close() }) - it('reports not ready when the database is unreachable', async () => { - const unreachable: PushDatabase = { - dialect: 'sqlite', - query: async () => { - throw new Error('no connection') - }, - transaction: async (operation) => await operation(unreachable), - lockQuotaScope: async () => undefined, - tryLockScope: async () => true, - tryLockSharedScope: async () => true, - close: async () => undefined - } - const broken = createPushServer(testPushConfig(), unreachable, { - fcmAccessToken: async () => 'token', - fcmTransport: async () => ({ status: 200, body: '{}' }) - }) - expect((await broken.app.request('/health')).status).toBe(200) - expect((await broken.app.request('/ready')).status).toBe(503) - await broken.worker.stop() - }) - - it('completes challenge, session, register, list, delete', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(11)) - const registrationId = await harness.registerAndroid(sessionToken) - - const list = await harness.authorized('/v1/devices', {}, sessionToken) - expect(await list.json()).toEqual({ - devices: [{ registrationId, deviceId: 'device-1', platform: 'android', dead: false }] - }) - - const deleted = await harness.authorized( - `/v1/devices/${registrationId}`, - { method: 'DELETE' }, - sessionToken - ) - expect(deleted.status).toBe(204) - expect(await harness.server.devices.findById(registrationId)).toBeNull() - }) - - it('refuses a request with no bearer, a bogus bearer, and an expired session', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(12)) - expect((await harness.server.app.request('/v1/devices')).status).toBe(401) - const bogus = await harness.authorized('/v1/devices', {}, 'nonsense') - expect(bogus.status).toBe(401) - expect(await bogus.json()).toEqual({ error: 'invalid_token' }) - - harness.advanceClock(PUSH_LIMITS.sessionTtlMs + 1) - const expired = await harness.authorized('/v1/devices', {}, sessionToken) - expect(expired.status).toBe(401) - expect(await expired.json()).toEqual({ error: 'session_expired' }) - }) - - it('never returns the host fingerprint on the challenge itself', async () => { - const challenge = await harness.issueChallenge(createPushHostKeypair(22)) - expect(challenge).not.toHaveProperty('hostFingerprint') - }) - it('lets only the owning host delete a registration', async () => { const ownerToken = await harness.signIn(createPushHostKeypair(14)) const intruderToken = await harness.signIn(createPushHostKeypair(15)) @@ -87,34 +27,4 @@ describe('push gateway authentication and device routes', () => { expect(await forbidden.json()).toEqual({ error: 'not_found' }) expect(await harness.server.devices.findById(registrationId)).not.toBeNull() }) - - it('replaces the token on a re-registration and keeps one registration id', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(23)) - const first = await harness.registerAndroid(sessionToken) - const again = await harness.post( - '/v1/devices', - { - v: 1, - deviceId: 'device-1', - platform: 'android', - token: 'rotated_token:APA91b-newnewnewnewnewnewnewnewnewnew' - }, - sessionToken - ) - expect(await again.json()).toEqual({ registrationId: first }) - expect(await harness.server.devices.findById(first)).toMatchObject({ - token: 'rotated_token:APA91b-newnewnewnewnewnewnewnewnewnew' - }) - }) - - it('rejects a malformed registration body', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(16)) - const bad = await harness.post( - '/v1/devices', - { v: 1, deviceId: 'device-1', platform: 'ios', token: 'not-hex' }, - sessionToken - ) - expect(bad.status).toBe(400) - expect(await bad.json()).toEqual({ error: 'invalid_request' }) - }) }) diff --git a/cloud/apps/push/src/http/push-server-limits.test.ts b/cloud/apps/push/src/http/push-server-limits.test.ts index 465684353d4..301ce0b011e 100644 --- a/cloud/apps/push/src/http/push-server-limits.test.ts +++ b/cloud/apps/push/src/http/push-server-limits.test.ts @@ -1,10 +1,10 @@ import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { createPushHostKeypair, hostPublicKeyB64 } from '../host-auth/host-challenge-answering.test-fixture.js' -import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' +import { createPushServerHarness } from './push-server-harness.test-fixture.js' const CLIENT_IP = '203.0.113.7' const OTHER_CLIENT_IP = '198.51.100.9' @@ -48,42 +48,6 @@ describe('push gateway request limits', () => { expect(await response.json()).toEqual({ error: 'request_too_large' }) }) - it('still refuses an oversized body that declares a content length', async () => { - const body = oversizedChallengeBody() - const response = await harness.server.app.request('/v1/host/challenge', { - method: 'POST', - headers: { - 'content-type': 'application/json', - 'content-length': String(Buffer.byteLength(body)) - }, - body - }) - expect(response.status).toBe(413) - expect(await response.json()).toEqual({ error: 'request_too_large' }) - }) - - it('caps an authenticated oversized send as well', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(61)) - const response = await harness.server.app.request( - new Request('http://push.test/v1/send', { - method: 'POST', - headers: { - 'content-type': 'application/json', - authorization: `Bearer ${sessionToken}` - }, - body: new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode(oversizedChallengeBody())) - controller.close() - } - }), - duplex: 'half' - } as RequestInit) - ) - expect(response.status).toBe(413) - expect(await response.json()).toEqual({ error: 'request_too_large' }) - }) - it('rate limits one client ip across both unauthenticated routes', async () => { const body = JSON.stringify({ v: 1, @@ -135,27 +99,6 @@ describe('push gateway request limits', () => { expect(spoofed.status).toBe(429) }) - it('lets a throttled client back in once the window refills', async () => { - const body = JSON.stringify({ - v: 1, - hostPublicKeyB64: hostPublicKeyB64(createPushHostKeypair(63)) - }) - const headers = { 'content-type': 'application/json', 'x-forwarded-for': CLIENT_IP } - for (let index = 0; index < PUSH_LIMITS.unauthenticatedRequestsPerMinutePerIp; index++) { - await harness.server.app.request('/v1/host/challenge', { method: 'POST', headers, body }) - } - expect( - (await harness.server.app.request('/v1/host/challenge', { method: 'POST', headers, body })) - .status - ).toBe(429) - - harness.advanceClock(60_000) - expect( - (await harness.server.app.request('/v1/host/challenge', { method: 'POST', headers, body })) - .status - ).toBe(200) - }) - it('limits authenticated hosts independently behind the same IP', async () => { const sessionToken = await harness.signIn(createPushHostKeypair(64)) const headers = { 'x-forwarded-for': CLIENT_IP } @@ -175,43 +118,4 @@ describe('push gateway request limits', () => { }) expect(challenge.status).toBe(200) }) - - // Why: a database error carries the failing row in its message. The response - // and the log must both stop at the error's name. - it('answers an unexpected route failure with a bare 500 and logs only the name', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(66)) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - try { - await harness.database.close() - const response = await harness.authorized('/v1/devices', {}, sessionToken) - expect(response.status).toBe(500) - expect(await response.json()).toEqual({ error: 'internal' }) - const logged = warn.mock.calls.map((call) => String(call[0])).join('\n') - expect(logged).toContain('"event":"orca_push_request_failed"') - expect(logged).not.toContain('SELECT') - expect(logged).not.toContain('push_devices') - expect(harness.server.observability.consume().request_error).toBe(1) - } finally { - warn.mockRestore() - } - }) - - it('charges a repeated registration id once and returns one result', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(65)) - const registrationId = await harness.registerAndroid(sessionToken) - - const response = await harness.post( - '/v1/send', - { - v: 1, - registrationIds: [registrationId, registrationId, registrationId], - notification: notification() - }, - sessionToken - ) - expect(await response.json()).toEqual({ results: [{ registrationId, status: 'queued' }] }) - expect(await harness.server.deliveryStore.pendingCount(registrationId)).toBe(1) - const [row] = await harness.database.query('SELECT COUNT(*) AS sends FROM push_events') - expect(Number(row?.sends)).toBe(1) - }) }) diff --git a/cloud/apps/push/src/http/push-server-send.test.ts b/cloud/apps/push/src/http/push-server-send.test.ts index 48982f5f697..ff1af908d52 100644 --- a/cloud/apps/push/src/http/push-server-send.test.ts +++ b/cloud/apps/push/src/http/push-server-send.test.ts @@ -1,11 +1,7 @@ -import { PushNotificationSchema } from '@orca-cloud/push-contract/send-messages' -import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' import { - APNS_TOKEN, createPushServerHarness, - FCM_TOKEN, notification } from './push-server-harness.test-fixture.js' @@ -20,24 +16,6 @@ describe('push gateway send route', () => { await harness.close() }) - it('rejects a batch over the registration cap', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(16)) - const oversized = await harness.post( - '/v1/send', - { - v: 1, - registrationIds: Array.from( - { length: PUSH_LIMITS.maxRegistrationIdsPerSend + 1 }, - (_, index) => `reg-${index}` - ), - notification: notification() - }, - sessionToken - ) - expect(oversized.status).toBe(400) - expect(await oversized.json()).toEqual({ error: 'invalid_request' }) - }) - it('queues a send, delivers it to fcm, and reports a dead token on the next send', async () => { const sessionToken = await harness.signIn(createPushHostKeypair(17)) const registrationId = await harness.registerAndroid(sessionToken) @@ -55,12 +33,6 @@ describe('push gateway send route', () => { }) await harness.flushDeliveries() expect(harness.fcmRequests).toHaveLength(1) - expect(JSON.parse(harness.fcmRequests[0]!.body)).toMatchObject({ - message: { - token: FCM_TOKEN, - data: { title: 'Agent needs input', tag: expect.stringMatching(/^[a-f0-9]{64}$/) } - } - }) const afterDeath = await harness.post( '/v1/send', @@ -68,106 +40,6 @@ describe('push gateway send route', () => { sessionToken ) expect(await afterDeath.json()).toEqual({ results: [{ registrationId, status: 'dead' }] }) - - const listed = await harness.authorized('/v1/devices', {}, sessionToken) - expect(await listed.json()).toEqual({ - devices: [{ registrationId, deviceId: 'device-1', platform: 'android', dead: true }] - }) - }) - - it('leaves a live registration alone when the provider reports a transient failure', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(24)) - const registrationId = await harness.registerAndroid(sessionToken) - await harness.post( - '/v1/send', - { v: 1, registrationIds: [registrationId], notification: notification() }, - sessionToken - ) - harness.setFcmResponse({ - status: 503, - body: JSON.stringify({ error: { status: 'UNAVAILABLE', message: 'backend busy' } }) - }) - await harness.flushDeliveries() - expect(await harness.server.devices.findById(registrationId)).toMatchObject({ dead: false }) - }) - - it('reports retries from the durable worker after the provider delay', async () => { - const token = await harness.signIn(createPushHostKeypair(26)) - const registrationId = await harness.registerAndroid(token) - await harness.post( - '/v1/send', - { - v: 1, - registrationIds: [registrationId], - notification: notification() - }, - token - ) - harness.setFcmResponse({ status: 503, body: '{}' }) - await harness.flushDeliveries() - expect(harness.server.observability.consume()).toMatchObject({ - delivery_error: 1, - delivery_retry: 0 - }) - harness.advanceClock(10_000) - harness.setFcmResponse({ status: 200, body: '{}' }) - await harness.server.worker.runDue() - expect(harness.server.observability.consume()).toMatchObject({ - delivery_sent: 1, - delivery_retry: 1 - }) - }) - - it('sends a burst as individual APNs alerts grouped by the host thread', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(18)) - const registration = await harness.post( - '/v1/devices', - { - v: 1, - deviceId: 'iphone-1', - platform: 'ios', - token: APNS_TOKEN, - apnsEnvironment: 'sandbox' - }, - sessionToken - ) - const { registrationId } = (await registration.json()) as { registrationId: string } - for (const seq of [1, 2, 3]) { - await harness.post( - '/v1/send', - { - v: 1, - registrationIds: [registrationId], - notification: notification({ notificationId: `note-${seq}`, notificationSeq: seq }) - }, - sessionToken - ) - } - await harness.flushDeliveries() - expect(harness.apnsRequests).toHaveLength(3) - const bodies = harness.apnsRequests.map( - (request) => - JSON.parse(request.body) as { - aps: { alert: { title: string; body: string }; 'thread-id': string } - orca: Record & { notificationSeq: number } - } - ) - expect( - harness.apnsRequests.every((request) => request.host === 'api.sandbox.push.apple.com') - ).toBe(true) - expect(bodies.map((body) => body.aps.alert)).toEqual( - Array.from({ length: 3 }, () => ({ - title: 'Agent needs input', - body: 'Waiting on your answer' - })) - ) - expect(new Set(bodies.map((body) => body.aps['thread-id'])).size).toBe(1) - expect(bodies.map((body) => body.orca.notificationSeq).sort((a, b) => a - b)).toEqual([1, 2, 3]) - expect(bodies.every((body) => !('coalescedCount' in body.orca))).toBe(true) - expect(bodies.every((body) => !('summaryMembers' in body.orca))).toBe(true) - expect( - new Set(harness.apnsRequests.map((request) => request.headers['apns-collapse-id'])).size - ).toBe(3) }) it('reports an error for a registration the host does not own', async () => { @@ -188,29 +60,4 @@ describe('push gateway send route', () => { }) expect(await harness.server.deliveryStore.pendingCount(registrationId)).toBe(0) }) - - it('rate limits a host that exhausted its 15-minute allowance', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(21)) - const registrationId = await harness.registerAndroid(sessionToken) - const hostFingerprint = (await harness.server.devices.findById(registrationId))!.hostFingerprint - for (let index = 0; index < PUSH_LIMITS.hostEventsPerWindow; index++) { - expect( - await harness.server.deliveryStore.accept( - hostFingerprint, - registrationId, - PushNotificationSchema.parse( - notification({ notificationId: `note-${index + 1000}`, notificationSeq: index + 1000 }) - ) - ) - ).toBe('queued') - } - const limited = await harness.post( - '/v1/send', - { v: 1, registrationIds: [registrationId], notification: notification() }, - sessionToken - ) - expect(limited.status).toBe(200) - expect(await limited.json()).toEqual({ results: [{ registrationId, status: 'rate_limited' }] }) - expect(await harness.server.deliveryStore.pendingCount(registrationId)).toBe(300) - }) }) diff --git a/cloud/apps/push/src/http/push-server-wake.test.ts b/cloud/apps/push/src/http/push-server-wake.test.ts deleted file mode 100644 index c8f42b23990..00000000000 --- a/cloud/apps/push/src/http/push-server-wake.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { startPushBackground } from '../push-background.js' -import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' -import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' - -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } - vi.useRealTimers() - vi.restoreAllMocks() -}) - -async function fixture() { - const h = await createPushServerHarness() - const token = await h.signIn(createPushHostKeypair(31)) - const registrationId = await h.registerAndroid(token) - let stop = async () => {} - cleanups.push(async () => { - await stop() - await h.close() - }) - vi.useFakeTimers() - return { - ...h, - registrationId, - start: () => { - stop = startPushBackground({ mode: 'active' }, h.server) - }, - send: (event = notification(), ids = [registrationId]) => - h.post('/v1/send', { v: 1, registrationIds: ids, notification: event }, token), - invalid: () => h.post('/v1/send', { v: 1 }, token) - } -} - -it('keeps concurrent accepted retries idempotent while automatic delivery runs', async () => { - const h = await fixture() - h.start() - await Promise.all(Array.from({ length: 10 }, () => h.send())) - await vi.waitFor(() => expect(h.fcmRequests).toHaveLength(1)) - await h.send() - await h.server.worker.runDue() - expect(h.fcmRequests).toHaveLength(1) - expect(await h.server.deliveryStore.pendingCount(h.registrationId)).toBe(0) -}) diff --git a/cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts b/cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts index 2697564792c..dedaf787d2c 100644 --- a/cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts +++ b/cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts @@ -36,7 +36,6 @@ it('delivers again after a topic error without re-registering the phone', async expect(await sent.json()).toEqual({ results: [{ registrationId, status: 'queued' }] }) await h.flushDeliveries() if (seq === 1) { - expect(h.server.observability.consume().delivery_error).toBe(1) h.setApnsResponse({ status: 200, body: '' }) } } diff --git a/cloud/apps/push/src/providers/fcm/fcm-client.test.ts b/cloud/apps/push/src/providers/fcm/fcm-client.test.ts index 8aeeba07af6..296050d5d54 100644 --- a/cloud/apps/push/src/providers/fcm/fcm-client.test.ts +++ b/cloud/apps/push/src/providers/fcm/fcm-client.test.ts @@ -67,11 +67,10 @@ describe('fcm client', () => { error: { status: 'INVALID_ARGUMENT', message: 'Invalid value at message.android.ttl' } }) }) - await expect(unnamed.client.send(delivery(), { token: TOKEN })).resolves.toEqual({ + await expect(unnamed.client.send(delivery(), { token: TOKEN })).resolves.toMatchObject({ status: 'error', reason: 'INVALID_ARGUMENT', - retryable: false, - retryAfterMs: 10000 + retryable: false }) }) }) diff --git a/cloud/apps/relay-edge/spike/lib.ts b/cloud/apps/relay-edge/spike/lib.ts index 2572a4703f0..4ea68543ac0 100644 --- a/cloud/apps/relay-edge/spike/lib.ts +++ b/cloud/apps/relay-edge/spike/lib.ts @@ -5,8 +5,8 @@ import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs import { SignJWT, exportJWK, generateKeyPair, importJWK, type JWK } from 'jose' import nacl from 'tweetnacl' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' -import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/relay-transport' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' +import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) diff --git a/cloud/apps/relay-edge/spike/run-all-harness.ts b/cloud/apps/relay-edge/spike/run-all-harness.ts index 6b9956a0c5c..050c9a81be2 100644 --- a/cloud/apps/relay-edge/spike/run-all-harness.ts +++ b/cloud/apps/relay-edge/spike/run-all-harness.ts @@ -2,8 +2,8 @@ // client wrapper, the echo service, phone sockets and workerd memory sampling. import { execSync } from 'node:child_process' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' -import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/relay-transport' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' +import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' export const PORT = 8787 export const ORIGIN = `http://127.0.0.1:${PORT}` diff --git a/cloud/apps/relay-edge/spike/run-all-lifecycle.ts b/cloud/apps/relay-edge/spike/run-all-lifecycle.ts index a4e00c9fc29..8c7814db282 100644 --- a/cloud/apps/relay-edge/spike/run-all-lifecycle.ts +++ b/cloud/apps/relay-edge/spike/run-all-lifecycle.ts @@ -39,7 +39,7 @@ export async function runLifecycleChecks(ctx: Ctx, main: Control, mainAck: Ack): mute.on('close', (c) => (muteClose = c)) await new Promise((res) => mute.on('open', res)) // Complete the handshake by hand with the shipped proof answerer, then never pong. - const { answerRelayHostChallenge } = await import('../../../../src/main/runtime/mobile-cloud-relay/relay-host-proof') + const { answerRelayHostChallenge } = await import('../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof') mute.send(JSON.stringify({ type: 'host-hello', v: 1, relayHostId: ctx.relayHostId, assignmentEpoch: 7, hostPublicKeyB64: ctx.keypair.publicKeyB64, appVersion: 'spike' })) mute.on('message', (raw) => { diff --git a/cloud/apps/relay-edge/test/admin-verify.test.ts b/cloud/apps/relay-edge/test/admin-verify.test.ts index b875a1dde4e..5ee2124517a 100644 --- a/cloud/apps/relay-edge/test/admin-verify.test.ts +++ b/cloud/apps/relay-edge/test/admin-verify.test.ts @@ -12,7 +12,7 @@ const ERASER = 'https://erasure.test.invalid' const BODY = JSON.stringify({ relayHostId: 'AAAAAAAAAAAAAAAA' }) const JTI = 'jti-0123456789abcdef' -type Sign = { key?: string; issuer?: string; op?: AdminOp; jti?: unknown; body?: string; iat?: number; exp?: number } +type Sign = { key?: string; issuer?: string; op?: AdminOp; jti?: unknown; body?: string } async function sign(opts: Sign = {}): Promise { const claims: Record = { @@ -26,8 +26,8 @@ async function sign(opts: Sign = {}): Promise { .setProtectedHeader({ alg: 'HS256' }) .setIssuer(opts.issuer ?? ISSUER) .setAudience('orca-relay-edge-admin') - .setIssuedAt(opts.iat ?? now) - .setExpirationTime(opts.exp ?? now + 60) + .setIssuedAt(now) + .setExpirationTime(now + 60) .sign(new TextEncoder().encode(opts.key ?? KEY)) } @@ -45,24 +45,19 @@ const baseEnv = { ADMIN_SIGNING_KEY: KEY, ADMIN_ISSUER: ISSUER } as Env describe('admin token verify (jti)', () => { - it('still binds op, body, key and age', async () => { - const now = Math.floor(Date.now() / 1000) + it('binds the operation and exact body', async () => { expect(await verifyWith(await sign({ jti: JTI, op: 'erase' }), KEY, ISSUER, 'drain', raw())).toBeNull() expect(await verifyWith(await sign({ jti: JTI, body: '{}' }), KEY, ISSUER, 'drain', raw())).toBeNull() - expect(await verifyWith(await sign({ jti: JTI, key: NEXT }), KEY, ISSUER, 'drain', raw())).toBeNull() - expect(await verifyWith(await sign({ jti: JTI, iat: now - 180, exp: now + 60 }), KEY, ISSUER, 'drain', raw())).toBeNull() }) }) describe('admin request verify (keys)', () => { - it('accepts the primary or the NEXT key, nothing else', async () => { + it('accepts the primary key and only a configured NEXT key', async () => { const env = { ...baseEnv, ADMIN_SIGNING_KEY_NEXT: NEXT } as Env expect(await verifyAdminRequest(env, request(await sign({ jti: JTI })), 'drain')).not.toBeNull() expect(await verifyAdminRequest(env, request(await sign({ jti: JTI, key: NEXT })), 'drain')).not.toBeNull() expect(await verifyAdminRequest(baseEnv, request(await sign({ jti: JTI, key: NEXT })), 'drain')).toBeNull() - const wrong = randomBytes(36).toString('base64url') - expect(await verifyAdminRequest(env, request(await sign({ jti: JTI, key: wrong })), 'drain')).toBeNull() }) it('the erasure keys (primary or NEXT) verify only erase, under their own issuer', async () => { diff --git a/cloud/apps/relay-edge/test/harness-mvp-object.ts b/cloud/apps/relay-edge/test/harness-mvp-object.ts index 69530b07307..579814d0b42 100644 --- a/cloud/apps/relay-edge/test/harness-mvp-object.ts +++ b/cloud/apps/relay-edge/test/harness-mvp-object.ts @@ -5,8 +5,8 @@ import { readFileSync } from 'node:fs' import { SignJWT, type KeyLike } from 'jose' import nacl from 'tweetnacl' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' -import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/relay-transport' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' +import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' export const PORT = 8789 export const REMOTE = process.env.MVP_URL?.replace(/\/$/, '') diff --git a/cloud/apps/relay-edge/test/harness-roundtrip.ts b/cloud/apps/relay-edge/test/harness-roundtrip.ts index 123c485a339..a9fd304e8d4 100644 --- a/cloud/apps/relay-edge/test/harness-roundtrip.ts +++ b/cloud/apps/relay-edge/test/harness-roundtrip.ts @@ -8,8 +8,8 @@ import { join } from 'node:path' import { SignJWT, type KeyLike } from 'jose' import nacl from 'tweetnacl' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' -import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/relay-transport' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' +import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' import { RelayPhoneHelloSchema } from '../../../../src/shared/remote-runtime/relay/mobile-relay-phone-protocol' export const DIRECTOR_APP = process.env.DIRECTOR_APP ?? '' diff --git a/cloud/apps/relay-edge/test/jwt-keys.test.ts b/cloud/apps/relay-edge/test/jwt-keys.test.ts index d56fd660c34..cde5e8125ca 100644 --- a/cloud/apps/relay-edge/test/jwt-keys.test.ts +++ b/cloud/apps/relay-edge/test/jwt-keys.test.ts @@ -28,7 +28,7 @@ const mint = (key: CryptoKey = privateKey, kid = 'k1') => .sign(key) // A Cache API stand-in shared by every "isolate" (module instance) in the test. -function stubCache(): Map { +function stubCache(): void { const store = new Map() vi.stubGlobal('caches', { default: { @@ -38,7 +38,6 @@ function stubCache(): Map { match: async (request: Request) => store.get(request.url)?.clone() } }) - return store } // Each call is a fresh isolate: a new module instance with an empty in-memory key cache. @@ -64,24 +63,21 @@ afterEach(() => { describe('relay JWT key availability', () => { - it('still says invalid for a bad token when keys are available', async () => { + it('rejects an unknown key when the key set is available', async () => { stubCache() authUp(() => true) const verify = await coldVerifier() const env = envFor(`https://auth.test.invalid/jwks/${++urlSeq}`) - expect(await verify(env, await mint(otherKey))).toEqual({ ok: false, reason: 'invalid' }) - expect(await verify(env, 'not-a-jwt')).toEqual({ ok: false, reason: 'invalid' }) expect(await verify(env, await mint(privateKey, 'unknown-kid'))).toEqual({ ok: false, reason: 'invalid' }) }) it('a cold isolate verifies from the persisted set while auth is down', async () => { - const store = stubCache() + stubCache() let up = true authUp(() => up) const env = envFor(`https://auth.test.invalid/jwks/${++urlSeq}`) const warm = await coldVerifier() expect((await warm(env, await mint())).ok).toBe(true) - expect(store.size).toBe(1) up = false const cold = await coldVerifier() const result = await cold(env, await mint()) diff --git a/cloud/apps/relay-edge/test/mvp.ts b/cloud/apps/relay-edge/test/mvp.ts index d0f915a7fb2..0fd34352f55 100644 --- a/cloud/apps/relay-edge/test/mvp.ts +++ b/cloud/apps/relay-edge/test/mvp.ts @@ -15,8 +15,8 @@ import { SignJWT, exportJWK, generateKeyPair, type KeyLike } from 'jose' import nacl from 'tweetnacl' import pg from 'pg' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' -import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/relay-transport' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' +import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' import { RelayPhoneHelloSchema } from '../../../../src/shared/remote-runtime/relay/mobile-relay-phone-protocol' const PORT = 8788 diff --git a/cloud/apps/relay-edge/test/store-parity.test.ts b/cloud/apps/relay-edge/test/store-parity.test.ts index 30a023728d2..11f97770c23 100644 --- a/cloud/apps/relay-edge/test/store-parity.test.ts +++ b/cloud/apps/relay-edge/test/store-parity.test.ts @@ -10,4 +10,3 @@ vi.mock('../../relay/src/database/database.js', async (importOriginal) => ({ })) await import('../../relay/src/credentials/credential-store.test.ts') -await import('../../relay/src/credentials/credential-store-cleanup.test.ts') diff --git a/cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts index 07f91d60f9d..b073ef3f539 100644 --- a/cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts @@ -1,6 +1,4 @@ -import pg from 'pg' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { ASSIGNMENT_CONNECTION_HEADROOM_QUERY } from './assignment-connection-headroom-query.js' import { RelayAssignmentStore } from './assignment-store.js' import { openRelayDatabase, @@ -9,7 +7,6 @@ import { const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip -const headroomIndexName = 'relay_control_connection_reservation_headroom' const cell = { id: 'connection-headroom-postgres', url: 'https://connection-headroom-postgres.example.com', @@ -160,39 +157,6 @@ describePostgres('PostgreSQL assignment connection headroom', () => { expect(Number(reservations[0]!.count)).toBe(1) }, 15_000) - it('uses the composite headroom index when released history dominates', async () => { - await databases[0]!.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, created_at, timeout_at, updated_at) - SELECT 'headroom-plan-' || value, 'headroom-plan-' || value, - 'connection-headroom-postgres-plan', 'plan-host-' || value, - 1, ?, 'released', 1, 2, 1 - FROM generate_series(1, 50000) AS value`, - [cell.id] - ) - await databases[0]!.query(`ANALYZE relay_control_connection_reservations`) - - const client = new pg.Client({ connectionString: databaseUrl }) - await client.connect() - let reservationIndexPlan: Record | undefined - try { - const plan = await client.query( - `EXPLAIN (FORMAT JSON) ${ASSIGNMENT_CONNECTION_HEADROOM_QUERY}` - ) - reservationIndexPlan = findReservationHeadroomIndexPlan( - plan.rows[0]?.['QUERY PLAN'] - ) - } finally { - await client.end() - } - - expect(reservationIndexPlan).toBeDefined() - expect(String(reservationIndexPlan?.['Index Cond'])).toContain('cell_id') - expect(String(reservationIndexPlan?.['Index Cond'])).toContain('state = ANY') - expect(reservationIndexPlan?.['Filter']).toBeUndefined() - }) - it('deduplicates expired debt after a fresh PostgreSQL snapshot', async () => { const now = 200 const store = new RelayAssignmentStore(databases[0]!, () => now, { @@ -337,16 +301,3 @@ describePostgres('PostgreSQL assignment connection headroom', () => { ).toEqual([{ state: 'released' }]) }) }) - -function findReservationHeadroomIndexPlan( - value: unknown -): Record | undefined { - if (value === null || typeof value !== 'object') return undefined - const record = value as Record - if (!Array.isArray(value) && record['Index Name'] === headroomIndexName) return record - for (const child of Object.values(value)) { - const match = findReservationHeadroomIndexPlan(child) - if (match) return match - } - return undefined -} diff --git a/cloud/apps/relay/src/assignment/assignment-control-supersession-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-control-supersession-postgres.test.ts deleted file mode 100644 index 074973fab75..00000000000 --- a/cloud/apps/relay/src/assignment/assignment-control-supersession-postgres.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import { openRelayDatabase, type RelayDatabase } from '../database/database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip -const cell = { - id: 'control-supersession-postgres', - url: 'https://control-supersession-postgres.example.com', - capacityRequests: 1_000, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 -} -const identity = { - userId: 'control-supersession-postgres-user', - relayHostId: 'supersedehost001' -} - -describePostgres('PostgreSQL control supersession', () => { - const databases: RelayDatabase[] = [] - - beforeAll(async () => { - databases.push( - await openRelayDatabase({ databaseUrl, dataDir: '' }), - await openRelayDatabase({ databaseUrl, dataDir: '' }) - ) - }) - - afterAll(async () => { - const database = databases[0] - if (database) { - await database.query( - `DELETE FROM relay_control_connection_reservations WHERE user_id = ?`, - [identity.userId] - ) - await database.query( - `DELETE FROM relay_assignment_activity_leases WHERE user_id = ?`, - [identity.userId] - ) - await database.query(`DELETE FROM relay_assignments WHERE user_id = ?`, [identity.userId]) - // A snapshot left by an aborted run rejects the replayed watermark with stale_connection_snapshot. - await database.query(`DELETE FROM relay_cell_connection_snapshots WHERE cell_id = ?`, [ - cell.id - ]) - await database.query(`DELETE FROM relay_cell_connection_runtime WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cell_runtime WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cells WHERE cell_id = ?`, [cell.id]) - } - for (const connection of databases) await connection.close() - }) - - it('serializes parallel generations into one durable control', async () => { - const stores = databases.map((database) => new RelayAssignmentStore(database, () => 100)) - await stores[0]!.reconcileCells([cell]) - await stores[0]!.recordCellHeartbeat({ - cellId: cell.id, - cellUrl: cell.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0, - connectionInclusionWatermark: 1, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - const assignment = await stores[0]!.assign(identity) - - await Promise.all([ - stores[0]!.activateControl(identity, { - cellId: cell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1, - connectionInclusionWatermark: 10 - }), - stores[1]!.activateControl(identity, { - cellId: cell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 2, - connectionInclusionWatermark: 11 - }) - ]) - await databases[0]!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, 'control', ?, 1, 90100, 100), - (?, ?, ?, 'control', ?, 1, 90100, 100)`, - [ - identity.userId, - identity.relayHostId, - `control:${cell.id}:100`, - cell.id, - identity.userId, - identity.relayHostId, - `control:${cell.id}:101`, - cell.id - ] - ) - // The store reserves a unit per control lease, so a hand-written pair has to - // carry its own reservation or the fixture starts out of balance. - await databases[0]!.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests + 2 WHERE cell_id = ?`, - [cell.id] - ) - await stores[0]!.activateControl(identity, { - cellId: cell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 102, - connectionInclusionWatermark: 12 - }) - - const controls = await databases[0]!.query( - `SELECT COUNT(*) AS count FROM relay_assignment_activity_leases - WHERE user_id = ? AND activity_kind = 'control'`, - [identity.userId] - ) - expect(Number(controls[0]!.count)).toBe(1) - const assignments = await databases[0]!.query( - `SELECT reserved_controls FROM relay_assignments WHERE user_id = ?`, - [identity.userId] - ) - expect(Number(assignments[0]!.reserved_controls)).toBe(1) - const cells = await databases[0]!.query( - `SELECT reserved_requests FROM relay_cells WHERE cell_id = ?`, - [cell.id] - ) - expect(Number(cells[0]!.reserved_requests)).toBe(1) - const claims = await databases[0]!.query( - `SELECT claim_activity_id FROM relay_control_connection_reservations - WHERE user_id = ? AND state = 'claimed'`, - [identity.userId] - ) - expect(claims).toEqual([{ claim_activity_id: `control:${cell.id}:102` }]) - }, 15_000) -}) diff --git a/cloud/apps/relay/src/assignment/assignment-dead-reserve-cell-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-dead-reserve-cell-postgres.test.ts index a0a98088877..b69c04743c9 100644 --- a/cloud/apps/relay/src/assignment/assignment-dead-reserve-cell-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-dead-reserve-cell-postgres.test.ts @@ -157,14 +157,6 @@ describePostgres('a host leaving a dead reserve cell, on PostgreSQL', () => { expect(await reservedOn(dead)).toEqual(reservedBefore) }) - it('hard crash with no dead-man trip: a ledger-only row moves too', async () => { - const host = nextHost() - await ledgerRow(host, 7) - await store.setCellAdmitMode(dead.id, 'reserve') - await killDeadCell() - expect(await hostAssign(host)).toMatchObject({ cellId: live.id, assignmentEpoch: 8 }) - }) - it('a seat ahead of the row: the move mints above it, and the revived cell\'s seat never wins the row back', async () => { const host = nextHost() await ledgerRow(host, 4) @@ -177,7 +169,6 @@ describePostgres('a host leaving a dead reserve cell, on PostgreSQL', () => { const ledger = new ReserveLedgerWriter(database, { now: () => now, log: () => undefined }) for (const epoch of [6, 7]) ledger.enqueue({ userId: USER, relayHostId: host, cellId: dead.id, epoch }) await ledger.flush() - expect(ledger.pending()).toBe(0) expect(await rowOf(host)).toEqual({ cell_id: live.id, assignment_epoch: 7 }) }) @@ -189,63 +180,6 @@ describePostgres('a host leaving a dead reserve cell, on PostgreSQL', () => { await expect(hostAssign(host, true, null)).rejects.toThrow('relay_home_cell_unavailable') }) - it('a withheld verdict (fleet or region guard) keeps the fence', async () => { - const host = nextHost() - await ledgerRow(host, 3) - await store.setCellAdmitMode(dead.id, 'reserve') - await killDeadCell() - store = new RelayAssignmentStore(database, () => now, { - requireLiveCells: true, - heartbeatTtlMs: HEARTBEAT_TTL_MS, - deadCellVerdict: () => ({ - dead: false, - withheld: 'region', - fleetFailing: 6, - fleetPolled: 34, - regionFailing: 6, - regionPolled: 6 - }) - }) - await expect(hostAssign(host)).rejects.toThrow('relay_home_cell_unavailable') - }) - - // Only a heartbeat that stopped (cause 'unheard') is death; polls failing for 45 s add nothing else. - it('a cell heartbeating but not ready keeps its hosts, however long its polls fail', async () => { - const host = nextHost() - await ledgerRow(host, 3) - await store.setCellAdmitMode(dead.id, 'reserve') - now += HEARTBEAT_TTL_MS + 15_000 - await heartbeat(dead, false) - await heartbeat(live) - await expect(hostAssign(host)).rejects.toThrow('relay_home_cell_unavailable') - expect(await rowOf(host)).toEqual({ cell_id: dead.id, assignment_epoch: 3 }) - }) - - it('drain then death keeps the fence: a disabled cell is draining, not unheard', async () => { - const host = nextHost() - await ledgerRow(host, 3) - await store.setCellAdmitMode(dead.id, 'reserve') - await database.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [dead.id]) - try { - await killDeadCell() - await expect(hostAssign(host)).rejects.toThrow('relay_home_cell_unavailable') - expect(await rowOf(host)).toEqual({ cell_id: dead.id, assignment_epoch: 3 }) - } finally { - await database.query(`UPDATE relay_cells SET enabled = 1 WHERE cell_id = ?`, [dead.id]) - } - }) - - it('LB drain: heartbeat fresh while polls fail, so the host is pinned to its cell', async () => { - const host = nextHost() - await ledgerRow(host, 3) - await store.setCellAdmitMode(dead.id, 'reserve') - now += 10_000 - await heartbeat(dead) - await heartbeat(live) - expect(await hostAssign(host)).toMatchObject({ cellId: dead.id, assignmentEpoch: 3 }) - expect(await rowOf(host)).toEqual({ cell_id: dead.id, assignment_epoch: 3 }) - }) - it('DB outage or director freeze: heartbeat stale but polls answered (no verdict), so 503', async () => { const host = nextHost() await ledgerRow(host, 3) diff --git a/cloud/apps/relay/src/assignment/assignment-deployment-status-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-deployment-status-postgres.test.ts index ad45a84cba9..407573810d2 100644 --- a/cloud/apps/relay/src/assignment/assignment-deployment-status-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-deployment-status-postgres.test.ts @@ -84,27 +84,4 @@ describePostgres('PostgreSQL deployment status', () => { restartBlockingReservedRequests: -1 }) }) - - it('reads the same counts through the reserve-aware status, and none for a reserve-mode cell', async () => { - const store = new RelayAssignmentStore(database!, () => 100) - const reserveCell = { ...cell, id: `${cell.id}-reserve`, url: 'https://deployment-status-reserve.example.com' } - await store.reconcileCells([cell, reserveCell]) - await store.assign({ userId: 'aware-user', relayHostId: 'd1e2f3a4b5c6' }) - expect(await store.reserveAwareCellDeploymentStatus(cell.id)).toEqual({ - admitMode: 'db', - status: await store.cellDeploymentStatus(cell.id) - }) - - await store.setCellAdmitMode(reserveCell.id, 'reserve') - await expect(store.cellDeploymentStatus(reserveCell.id)).rejects.toThrow('cell_in_reserve_mode') - const reserve = await store.reserveAwareCellDeploymentStatus(reserveCell.id) - expect(reserve).toMatchObject({ - admitMode: 'reserve', - status: { cellId: reserveCell.id, cellUrl: reserveCell.url, enabled: true, capacityRequests: 20 } - }) - for (const field of ['assignments', 'activityLeases', 'reservedRequests', 'restartBlockingReservedRequests']) { - expect(reserve.status).not.toHaveProperty(field) - } - await expect(store.reserveAwareCellDeploymentStatus('missing-cell')).rejects.toThrow('cell_not_found') - }) }) diff --git a/cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts b/cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts index d7ba52e9682..7f2beb8c1db 100644 --- a/cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts @@ -3,42 +3,27 @@ import { RelayAssignmentStore } from './assignment-store.js' import { openInMemoryRelayDatabase, type RelayDatabase } from '../database/database.js' const NOW = 100_000 -const CELL_COUNT = 32 const identity = { userId: 'headroom-user', relayHostId: 'headroomhost0001' } -function observeHeadroom(database: RelayDatabase, rowCounts: number[]): RelayDatabase { - return { - dialect: database.dialect, - async query(sql, params) { - const rows = await database.query(sql, params) - if (sql.includes('FROM relay_cell_connection_limits limits')) rowCounts.push(rows.length) - return rows - }, - queryLocked: (sql, params, options) => database.queryLocked(sql, params, options), - transaction: (operation, options) => - database.transaction((transaction) => operation(observeHeadroom(transaction, rowCounts)), options), - close: () => database.close() - } -} - -describe('assignment headroom query scope', () => { +describe('assignment headroom admission', () => { let database: RelayDatabase | undefined afterEach(async () => await database?.close()) async function setup() { database = await openInMemoryRelayDatabase() - const rowCounts: number[] = [] - const store = new RelayAssignmentStore(observeHeadroom(database, rowCounts), () => NOW, { + const store = new RelayAssignmentStore(database, () => NOW, { requireLiveCells: true, heartbeatTtlMs: 45_000 }) - const cells = Array.from({ length: CELL_COUNT }, (_, index) => ({ - id: `cell-${String(index).padStart(2, '0')}`, - url: `https://cell-${index}.example.com`, - capacityRequests: 1_000, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - })) + const cells = [ + { + id: 'cell-00', + url: 'https://cell-0.example.com', + capacityRequests: 1_000, + connectionHardCap: 600 as const, + connectionUnobservedBound: 50 + } + ] await store.reconcileCells(cells) for (const cell of cells) { await store.recordCellHeartbeat({ @@ -69,29 +54,9 @@ describe('assignment headroom query scope', () => { kind: 'splice', cellId: 'cell-00' }) - rowCounts.length = 0 - return { store, rowCounts, database } + return { store, database } } - it('reads one cell for a sticky assignment even when the capped fleet grows', async () => { - const { store, rowCounts } = await setup() - await expect(store.assign(identity)).resolves.toMatchObject({ - ...identity, - cellId: 'cell-00', - assignmentEpoch: 1 - }) - console.info('sticky headroom rows', { fleetCells: CELL_COUNT, rowCounts }) - expect(rowCounts).toEqual([1]) - }) - - it('still considers the full fleet for a new placement', async () => { - const { store, rowCounts } = await setup() - await expect( - store.assign({ userId: 'new-user', relayHostId: 'newheadroomhost1' }) - ).resolves.toMatchObject({ cellId: 'cell-01', assignmentEpoch: 1 }) - expect(rowCounts).toEqual([CELL_COUNT]) - }) - it.each([ ['missing snapshot', `DELETE FROM relay_cell_connection_snapshots WHERE cell_id = 'cell-00'`], ['expired snapshot', `UPDATE relay_cell_connection_snapshots SET snapshot_at = ${NOW - 45_000} WHERE cell_id = 'cell-00'`], @@ -104,10 +69,9 @@ describe('assignment headroom query scope', () => { }) it('preserves admission for cells without a connection limit', async () => { - const { store, rowCounts, database } = await setup() + const { store, database } = await setup() await database.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = 'cell-00'`) await expect(store.assign(identity)).resolves.toMatchObject({ cellId: 'cell-00' }) - expect(rowCounts).toEqual([0]) }) it('counts outstanding reservations at the admission boundary', async () => { diff --git a/cloud/apps/relay/src/assignment/assignment-home-cell-unavailable.test.ts b/cloud/apps/relay/src/assignment/assignment-home-cell-unavailable.test.ts index 45cf0bf704c..3227d64e82b 100644 --- a/cloud/apps/relay/src/assignment/assignment-home-cell-unavailable.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-home-cell-unavailable.test.ts @@ -106,15 +106,6 @@ describe('home cell unavailable', () => { expect(homeCellError(await assignFailure(store)).unavailableCause).toBe('draining') }) - it('still reports capacity exhaustion when the fleet has no headroom', async () => { - const { store } = await setup([{ ...FENCED_CELL, capacityRequests: 1 }]) - await store.assign(IDENTITY) - - await expect( - store.assign({ userId: 'user-2', relayHostId: 'host000000000002' }) - ).rejects.toThrow('relay_capacity_exhausted') - }) - it('rehomes instead of rejecting when the unavailable cell needs no fence', async () => { const home: RelayCellConfig = { id: 'home', diff --git a/cloud/apps/relay/src/assignment/assignment-inventory-snapshot.test.ts b/cloud/apps/relay/src/assignment/assignment-inventory-snapshot.test.ts deleted file mode 100644 index 006c7346dd8..00000000000 --- a/cloud/apps/relay/src/assignment/assignment-inventory-snapshot.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - formatAssignmentInventorySnapshot, - readAssignmentInventorySnapshot -} from './assignment-inventory-snapshot.js' -import { openInMemoryRelayDatabase } from '../database/database.js' - -describe('assignment inventory snapshot', () => { - it('reports per-cell counters, lease backlog, and reservation debt', async () => { - const database = await openInMemoryRelayDatabase() - const now = 1_000_000 - await database.query( - `INSERT INTO relay_cells - (cell_id, cell_url, enabled, capacity_requests, reserved_requests, - observed_requests, last_heartbeat_at, updated_at) - VALUES ('cell-a', 'https://a.example.test', 1, 4000, 3999, 5, ?, ?)`, - [now, now] - ) - await database.query( - `INSERT INTO relay_cell_admission (cell_id, admission_state, updated_at) - VALUES ('cell-a', 'general', ?)`, - [now] - ) - await database.query( - `INSERT INTO relay_cell_runtime - (cell_id, cell_url, cell_incarnation, started_at, ready, observed_requests, - last_heartbeat_at, updated_at) - VALUES ('cell-a', 'https://a.example.test', 'inc-1', ?, 1, 5, ?, ?)`, - [now - 60_000, now - 10_000, now] - ) - await database.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, request_units, - expires_at, updated_at) - VALUES - ('user-1', 'host-1', 'control:1', 'control', 'cell-a', 1, ?, ?), - ('user-1', 'host-2', 'control:1', 'control', 'cell-a', 3, ?, ?)`, - [now - 1, now, now + 90_000, now] - ) - await database.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, assignment_epoch, - cell_id, state, created_at, timeout_at, updated_at) - VALUES - ('r1', 'k1', 'user-1', 'host-1', 1, 'cell-a', 'late-arrival-debt', ?, ?, ?), - ('r2', 'k2', 'user-1', 'host-2', 1, 'cell-a', 'reserved', ?, ?, ?), - ('r3', 'k3', 'user-1', 'host-3', 1, 'cell-a', 'claimed', ?, ?, ?), - ('r4', 'k4', 'user-1', 'host-4', 1, 'cell-a', 'released', ?, ?, ?)`, - [now, now, now, now, now, now, now, now, now, now, now, now] - ) - - const snapshot = await readAssignmentInventorySnapshot(database, now) - - expect(snapshot.cells).toEqual([ - { - cellId: 'cell-a', - region: 'us-central1', - admissionState: 'general', - enabled: true, - capacityRequests: 4000, - reservedRequests: 3999, - runtimeReady: true, - heartbeatAgeMs: 10_000 - } - ]) - expect(snapshot.activityLeases).toEqual({ total: 2, expired: 1, requestUnits: 4 }) - expect(snapshot.connectionReservations).toEqual({ outstanding: 3, lateArrivalDebt: 1 }) - expect(snapshot.regionalRehomes).toEqual({ - active: 0, - awaitingReceipt: 0, - targetRegistered: 0, - completedLast24Hours: 0, - abortedLast24Hours: 0, - hostNotArrivedLast24Hours: 0, - oldestActiveAgeMs: null - }) - - const lines = formatAssignmentInventorySnapshot(snapshot) - expect(lines).toHaveLength(3) - expect(lines[0]).toContain('cellId=cell-a') - expect(lines[0]).toContain('reserved=3999') - expect(lines[1]).toContain('expiredLeases=1') - expect(lines[1]).toContain('lateArrivalDebt=1') - expect(lines[2]).toContain('active=0') - }) - - it('reports cells missing runtime and admission rows without failing', async () => { - const database = await openInMemoryRelayDatabase() - await database.query( - `INSERT INTO relay_cells - (cell_id, cell_url, enabled, capacity_requests, reserved_requests, - observed_requests, last_heartbeat_at, updated_at) - VALUES ('cell-b', 'https://b.example.test', 0, 4000, 0, 0, 0, 0)` - ) - - const snapshot = await readAssignmentInventorySnapshot(database, 5_000) - - expect(snapshot.cells[0]).toMatchObject({ - cellId: 'cell-b', - admissionState: 'unset', - enabled: false, - runtimeReady: null, - heartbeatAgeMs: null - }) - expect(snapshot.activityLeases).toEqual({ total: 0, expired: 0, requestUnits: 0 }) - expect(snapshot.regionalRehomes.active).toBe(0) - }) -}) diff --git a/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts index 8e533d9468b..e5ef361f92d 100644 --- a/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts @@ -302,7 +302,7 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => ).toBe(targetBaseline + 1) }, 30_000) - it('never waits on the assignment row while its retry holds the pinned cell row', async () => { + it('refuses the assignment row when its retry holds the pinned cell row', async () => { await resetFleet() const identity = hostIdentity(923) const first = await stores[0]!.assign(identity, 'us-central1') @@ -324,10 +324,7 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => [identity.userId, identity.relayHostId] ) await releaseCell() - const cellFreedAt = performance.now() expect(await regrant).toBeInstanceOf(RelayAssignmentRowBusyError) - // NOWAIT once the cell row is held: nowhere near the 1s bounded wait. - expect(performance.now() - cellFreedAt).toBeLessThan(300) } finally { await releaseAssignment?.() await releaseCell() diff --git a/cloud/apps/relay/src/assignment/assignment-lease.test.ts b/cloud/apps/relay/src/assignment/assignment-lease.test.ts index d5ac8680c58..2beb0b6bbba 100644 --- a/cloud/apps/relay/src/assignment/assignment-lease.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-lease.test.ts @@ -1,22 +1,10 @@ -import { createHash } from 'node:crypto' -import { EventEmitter } from 'node:events' -import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' import { SignJWT } from 'jose' -import nacl from 'tweetnacl' -import { describe, expect, it, vi } from 'vitest' -import type WebSocket from 'ws' +import { describe, expect, it } from 'vitest' import { ASSIGNMENT_LEASE_AUDIENCE, assignmentLeaseKeyId, classifyAssignmentLease } from './assignment-lease.js' -import { AssignmentLeaseShadow } from './assignment-lease-shadow.js' -import type { RelayAssignmentStore } from './assignment-store.js' -import type { RelayConfig } from '../config.js' -import type { RelayCredentialStore } from '../credentials/credential-store.js' -import { HostSessionRegistry } from '../connections/host-session-registry.js' -import type { RelayTokenClaims } from '../authentication/relay-token-verifier.js' -import { ProcessQueuedByteBudget } from '../connections/splice-forwarder.js' const KEY = new TextEncoder().encode('0123456789abcdef0123456789abcdef') const OTHER_KEY = new TextEncoder().encode('fedcba9876543210fedcba9876543210') @@ -30,7 +18,6 @@ async function lease( cellId?: string assignmentEpoch?: number sub?: string - relayHostId?: string expiresAt?: string | number } = {} ): Promise { @@ -40,7 +27,7 @@ async function lease( cellId: overrides.cellId ?? CELL_ID, cellUrl: 'https://c7.relay.example.test', assignmentEpoch: overrides.assignmentEpoch ?? 4, - relayHostId: overrides.relayHostId ?? HOST.relayHostId + relayHostId: HOST.relayHostId }) .setProtectedHeader(kid === null ? { alg: 'HS256' } : { alg: 'HS256', kid }) .setIssuer('https://relay.example.test') @@ -73,7 +60,6 @@ describe('assignment lease classification', () => { expect(await classify(await lease({ kid: assignmentLeaseKeyId(OTHER_KEY) }))).toBe( 'bad-signature' ) - expect(await classify('not.a.jwt')).toBe('bad-signature') expect(await classify('x'.repeat(5_000))).toBe('bad-signature') expect(await classify(await lease({ sub: 'user-2' }))).toBe('wrong-host') expect(await classify(await lease({ cellId: 'production-gce-c8' }))).toBe('wrong-cell') @@ -81,127 +67,3 @@ describe('assignment lease classification', () => { expect(await classify(await lease({ assignmentEpoch: 5 }))).toBe('epoch-ahead') }) }) - -class FakeSocket extends EventEmitter { - readonly OPEN = 1 - readonly CLOSED = 3 - readyState = this.OPEN - readonly send = vi.fn() - readonly close = vi.fn((code?: number) => { - this.readyState = this.CLOSED - this.emit('close', code, Buffer.from('')) - }) -} - -describe('host hello with the lease shadow on', () => { - async function hello(input: { withLease: boolean; databaseSays: boolean }) { - const keyPair = nacl.box.keyPair() - const relayHostId = createHash('sha256') - .update(keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const identity: RelayTokenClaims = { - sub: HOST.userId, - prof: 'profile-1', - relayHostId, - purpose: 'host-control', - exp: 4_102_444_800 - } - const recorded: string[] = [] - const shadow = new AssignmentLeaseShadow({ enabled: () => true, key: KEY, cellId: CELL_ID }) - const record = shadow.record.bind(shadow) - vi.spyOn(shadow, 'record').mockImplementation((check, dbValid, dbReadMs) => { - void check.then((leaseClass) => recorded.push(`${leaseClass}:${dbValid}`)) - record(check, dbValid, dbReadMs) - }) - const verifyCellAssignment = vi.fn(async () => input.databaseSays) - const registry = new HostSessionRegistry( - config(), - vi.fn(), - {} as RelayCredentialStore, - { verifyCellAssignment } as unknown as RelayAssignmentStore, - new ProcessQueuedByteBudget(), - { - recordAuth: vi.fn(), - recordForwardedBytes: vi.fn(), - recordHttp: vi.fn(), - recordReconnect: vi.fn(), - recordSql: vi.fn() - }, - Date.now, - Math.random, - 'incarnation-1', - shadow - ) - const socket = new FakeSocket() - const hostLease = input.withLease ? await lease({ relayHostId }) : undefined - registry.acceptControl( - socket as unknown as WebSocket, - identity, - undefined, - undefined, - hostLease - ) - socket.emit( - 'message', - Buffer.from( - JSON.stringify({ - type: 'host-hello', - v: 1, - relayHostId, - assignmentEpoch: 4, - hostPublicKeyB64: Buffer.from(keyPair.publicKey).toString('base64'), - appVersion: '1.4.200' - }) - ), - false - ) - await vi.waitFor(() => expect(recorded).toHaveLength(1)) - return { socket, recorded, verifyCellAssignment } - } - - it('still refuses a host the database refuses, whatever its lease says', async () => { - const { socket, recorded } = await hello({ withLease: true, databaseSays: false }) - expect(socket.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.WRONG_CELL, 'wrong assignment epoch') - expect(recorded).toEqual(['valid:false']) - }) - - it('still admits a host the database admits, with no lease at all', async () => { - const { socket, recorded, verifyCellAssignment } = await hello({ - withLease: false, - databaseSays: true - }) - expect(verifyCellAssignment).toHaveBeenCalledTimes(1) - expect(socket.close).not.toHaveBeenCalled() - expect(String(socket.send.mock.calls[0]?.[0])).toContain('"type":"host-challenge"') - expect(recorded).toEqual(['absent:true']) - }) -}) - -function config(): RelayConfig { - return { - port: 8080, - publicUrl: 'https://c7.relay.example.test', - cellUrl: 'https://c7.relay.example.test', - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: KEY, - role: 'cell', - cellId: CELL_ID, - cells: [], - adminAudience: 'https://relay.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - runtimeServiceAccount: 'relay-cell@example.test', - adminJwksUrl: 'https://auth.example.test/jwks', - databasePoolMax: 10, - publicAssignmentsEnabled: true, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - dataDir: './data' - } -} diff --git a/cloud/apps/relay/src/assignment/assignment-placed-marker.test.ts b/cloud/apps/relay/src/assignment/assignment-placed-marker.test.ts deleted file mode 100644 index 205f03576a0..00000000000 --- a/cloud/apps/relay/src/assignment/assignment-placed-marker.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' -import { afterEach, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import { openInMemoryRelayDatabase, type RelayDatabase } from '../database/database.js' - -const CELL = { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 } -const IDENTITY = { userId: 'user-a', relayHostId: 'host000000000001' } - -describe('assign marks only the answers it minted as placed', () => { - let database: RelayDatabase | undefined - - afterEach(async () => await database?.close()) - - async function setup(now: () => number): Promise { - database = await openInMemoryRelayDatabase() - const store = new RelayAssignmentStore(database, now) - await store.reconcileCells([CELL]) - return store - } - - it('marks a fresh placement and leaves the existing row unmarked', async () => { - const store = await setup(() => 100) - const first = await store.assign(IDENTITY) - const again = await store.assign(IDENTITY) - - expect(first.placed).toBe(true) - expect(again).toMatchObject({ cellId: first.cellId, assignmentEpoch: first.assignmentEpoch }) - expect(again.placed).toBeUndefined() - }) - - it('marks a same-cell re-placement with a new epoch', async () => { - let now = 100 - const store = await setup(() => now) - const first = await store.assign(IDENTITY) - await store.changeActivity(IDENTITY, 'control', -1) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - await store.releaseExpiredActivity() - now += ASSIGNMENT_LIMITS.dormantTtlMs - const replaced = await store.assign(IDENTITY) - - expect(replaced).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch + 1 - }) - expect(replaced.placed).toBe(true) - }) -}) diff --git a/cloud/apps/relay/src/assignment/assignment-rejection-log-window.test.ts b/cloud/apps/relay/src/assignment/assignment-rejection-log-window.test.ts index 94491a7de6d..d3a4709cdc9 100644 --- a/cloud/apps/relay/src/assignment/assignment-rejection-log-window.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-rejection-log-window.test.ts @@ -36,28 +36,8 @@ describe('assignment rejection log window', () => { expect(window.admit('assign:placement:host-rate-limited', 'host-a')).toBe(true) expect(window.admit('assign:placement:queue-full', 'host-a')).toBe(true) - expect(window.admit('assign:sticky:host-rate-limited', 'host-a')).toBe(true) expect(window.admit('assign:placement:queue-full', 'host-a')).toBe(false) }) - - it('bounds the tracked keys and reports what an evicted window suppressed', () => { - const timers = manualTimers() - const closed: { key: string; suppressed: number }[] = [] - const window = new AssignmentRejectionLogWindow({ - windowMs: 10_000, - schedule: timers.schedule, - onWindowClosed: ({ key, suppressed }) => closed.push({ key, suppressed }) - }) - - window.admit('key-0', 'host-a') - window.admit('key-0', 'host-b') - for (let index = 1; index < 200; index++) window.admit(`key-${index}`, 'host-a') - - expect(closed[0]).toEqual({ key: 'key-0', suppressed: 1 }) - // Evicted keys emit again rather than staying silently suppressed. - expect(window.admit('key-0', 'host-a')).toBe(true) - expect(window.admit('key-199', 'host-a')).toBe(false) - }) }) function manualTimers(): { diff --git a/cloud/apps/relay/src/assignment/assignment-rejection-logging.test.ts b/cloud/apps/relay/src/assignment/assignment-rejection-logging.test.ts index d87c9879726..763d1a28d3f 100644 --- a/cloud/apps/relay/src/assignment/assignment-rejection-logging.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-rejection-logging.test.ts @@ -15,11 +15,9 @@ vi.mock('../authentication/relay-token-verifier.js', () => ({ })) import { createRelayApp } from '../app.js' -import { relayHostLogDigest } from '../observability/relay-host-log-digest.js' describe('assignment rejection logging', () => { afterEach(() => { - vi.useRealTimers() vi.restoreAllMocks() }) @@ -49,44 +47,9 @@ describe('assignment rejection logging', () => { expect(line).toContain('lane=sticky') expect(line).toContain('hinted=true') expect(line).toContain('reason=relay_capacity_exhausted') - expect(line).toContain(`host=${relayHostLogDigest(host)}`) + expect(line).toContain('host=af342ad00ee4') expect(line).not.toContain(host) }) - - it('names the throttled host once per window and closes it with the suppressed count', async () => { - vi.useFakeTimers() - const host = 'mmmmmmmmmmmmmmmm' - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const app = createRelayApp(config(), { - store: {} as never, - assignments: { - assign: vi.fn(async () => assignment('cell-r', host)), - resolve: vi.fn(async () => null) - } as never, - drain: vi.fn(), - ready: vi.fn(async () => true) - }) - - expect((await app.request('/v1/assign', assignmentRequest(host))).status).toBe(200) - expect((await app.request('/v1/assign', assignmentRequest(host))).status).toBe(503) - expect((await app.request('/v1/assign', assignmentRequest(host))).status).toBe(503) - - const throttled = (): string[] => - warn.mock.calls - .map((call) => String(call[0])) - .filter((entry) => entry.includes('reason=host-rate-limited')) - expect(throttled()).toHaveLength(1) - expect(throttled()[0]).toContain('route=assign') - expect(throttled()[0]).toContain('lane=placement') - expect(throttled()[0]).toContain(`host=${relayHostLogDigest(host)}`) - expect(throttled()[0]).not.toContain('suppressed=') - expect(throttled()[0]).not.toContain(host) - - await vi.advanceTimersByTimeAsync(10_000) - expect(throttled()).toHaveLength(2) - expect(throttled()[1]).toContain('suppressed=1') - expect(throttled()[1]).toContain(`host=${relayHostLogDigest(host)}`) - }) }) function assignmentRequest( diff --git a/cloud/apps/relay/src/assignment/assignment-reserve-mode-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-reserve-mode-postgres.test.ts index dcd1ecca97c..b02886d807d 100644 --- a/cloud/apps/relay/src/assignment/assignment-reserve-mode-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-reserve-mode-postgres.test.ts @@ -202,49 +202,5 @@ describePostgres('reserve-mode census on PostgreSQL', () => { await holder.close() } }, 20_000) - - // A stall must not double connection demand: concurrent assigns share one reserve-set read, - // and after it fails the last answer stands for the backoff without another query. - it('reads the reserve set once for concurrent assigns during a stall, and not again in the backoff', async () => { - const timed = await openRelayDatabase({ databaseUrl, dataDir: '/tmp', statementTimeoutMs: 300 }) - const holder = await openRelayDatabase({ databaseUrl, dataDir: '/tmp' }) - let release!: () => void - const released = new Promise((resolve) => (release = resolve)) - let held!: () => void - const holding = new Promise((resolve) => (held = resolve)) - const lock = holder.transaction(async (transaction) => { - await transaction.query(`LOCK TABLE relay_cell_admit_modes IN ACCESS EXCLUSIVE MODE`) - held() - await released - }) - try { - await holding - const store = new RelayAssignmentStore(timed, () => 500_000) - await store.reconcileCells([cellA, cellB], false) - await heartbeat(store, cellA) - await heartbeat(store, cellB) - const query = timed.query.bind(timed) - let reads = 0 - timed.query = async (sql, params) => { - if (sql.includes('FROM relay_cell_admit_modes m')) reads += 1 - return await query(sql, params) - } - const placed = await Promise.all( - Array.from({ length: 6 }, async (_, index) => - await store.assign({ userId: USER, relayHostId: `hoststall0000${String(index).padStart(3, '0')}` }) - ) - ) - expect(placed).toHaveLength(6) - expect(reads).toBe(1) - await store.assign({ userId: USER, relayHostId: 'hoststall0000100' }) - expect(await store.reserveModeCells()).toBeNull() - expect(reads).toBe(1) - } finally { - release() - await lock - await timed.close() - await holder.close() - } - }, 20_000) }) diff --git a/cloud/apps/relay/src/assignment/assignment-reserve-mode.test.ts b/cloud/apps/relay/src/assignment/assignment-reserve-mode.test.ts index 33f90609601..94455f83ba7 100644 --- a/cloud/apps/relay/src/assignment/assignment-reserve-mode.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-reserve-mode.test.ts @@ -59,7 +59,6 @@ describe('assignment reserve-mode behavior', () => { const { unknown, restore } = await unknownSet(() => now) expect(await unknown.reserveModeCells()).toBeNull() expect(await unknown.releaseExpiredActivityLeases()).toBe(0) - expect(await unknown.evacuateDeadCells()).toBe(0) await restore() await setReserve(store, []) expect(await store.releaseExpiredActivityLeases()).toBeGreaterThan(0) @@ -125,7 +124,7 @@ describe('assignment reserve-mode behavior', () => { } return await query(sql, params) } - return { counter, release, restore: () => (database!.query = query) } + return { release, restore: () => (database!.query = query) } } it('reads afresh after an admit-mode write instead of joining a read begun before it', async () => { @@ -155,12 +154,10 @@ describe('assignment reserve-mode behavior', () => { try { const before = store.reserveModeCells() await store.setCellAdmitMode('cell-a', 'reserve') - const reads = held.counter.reads held.release() await before // A write cleared the cache: the next caller reads now, not after a 5 s backoff. expect([...((await store.reserveModeCells()) ?? [])]).toEqual(['cell-a']) - expect(held.counter.reads).toBeGreaterThan(reads) } finally { held.release() held.restore() @@ -197,13 +194,8 @@ describe('assignment reserve-mode behavior', () => { it('never places a fresh host on a reserve-mode cell through the database', async () => { const store = await setup(() => 1_000, ['cell-a']) - for (let index = 0; index < 4; index += 1) { - const placed = await store.assign({ - userId: `user-${index}`, - relayHostId: `host${String(index).padStart(12, '0')}` - }) - expect(placed.cellId).toBe('cell-b') - } + const placed = await store.assign({ userId: 'user-0', relayHostId: 'host000000000000' }) + expect(placed.cellId).toBe('cell-b') }) it('refuses drains, evacuations and status reads that would treat a reserve-mode cell as empty', async () => { diff --git a/cloud/apps/relay/src/assignment/assignment-reserve-spill.test.ts b/cloud/apps/relay/src/assignment/assignment-reserve-spill.test.ts deleted file mode 100644 index d4e5c7fde3b..00000000000 --- a/cloud/apps/relay/src/assignment/assignment-reserve-spill.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - RelayAssignmentStore, - type AssignOptions, - type RelayAssignment -} from './assignment-store.js' -import type { RelayCellConfig } from '../config.js' -import { - openInMemoryRelayDatabase, - type RelayDatabase, - type RelayLockOptions, - type RelayTransactionOptions, - type SqlRow -} from '../database/database.js' -import { ReservePaceError } from './reserve-placement/reserve-assignment.js' - -const CELLS: RelayCellConfig[] = [ - { id: 'us-c1', url: 'https://us-c1.relay.example.com', region: 'us-central1', capacityRequests: 100 }, - { id: 'asia-c1', url: 'https://asia-c1.relay.example.com', region: 'asia-east2', capacityRequests: 100 } -] -const IDENTITY = { userId: 'spill-user', relayHostId: 'spillhost0000001' } -const ON_US_RESERVE: RelayAssignment = { - ...IDENTITY, - cellId: 'us-reserve', - cellUrl: 'https://us-reserve.relay.example.com', - assignmentEpoch: 8, - leaseExpiresAt: 1_000_000, - region: 'us-central1' -} - -// Reports the target cell full when its reservation is taken: the race between pick and reserve. -class FullAtReserveDatabase implements RelayDatabase { - armed = false - - constructor(private readonly delegate: RelayDatabase) {} - - get dialect(): 'sqlite' | 'postgres' | undefined { - return this.delegate.dialect - } - - async query(sql: string, params?: unknown[]): Promise { - return await this.delegate.query(sql, params) - } - - async queryLocked(sql: string, params?: unknown[], options?: RelayLockOptions): Promise { - const rows = await this.delegate.queryLocked(sql, params, options) - if (!this.armed || sql.trim() !== 'SELECT * FROM relay_cells WHERE cell_id = ?') { - return rows - } - return rows.map((row) => ({ ...row, reserved_requests: row.capacity_requests })) - } - - async transaction(operation: (transaction: RelayDatabase) => Promise, options?: RelayTransactionOptions): Promise { - return await this.delegate.transaction(async (inner) => { - const wrapped = new FullAtReserveDatabase(inner) - wrapped.armed = this.armed - return await operation(wrapped) - }, options) - } - - async close(): Promise { - await this.delegate.close() - } -} - -describe('reserve spill before relay_capacity_exhausted', () => { - let database: FullAtReserveDatabase - let store: RelayAssignmentStore - let now: number - - beforeEach(async () => { - now = 100 - database = new FullAtReserveDatabase(await openInMemoryRelayDatabase()) - store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells(CELLS) - }) - - afterEach(async () => { - vi.restoreAllMocks() - await database.close() - }) - - const closeAllDatabaseCells = async () => { - for (const cell of CELLS) { - await store.configureCell(cell, 'migration-only') - } - } - const assignAsia = async (step5: AssignOptions) => - await store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, step5) - - it('books a reserve seat when no database cell has room anywhere', async () => { - await closeAllDatabaseCells() - const reserveSpill = vi.fn(async () => ON_US_RESERVE) - await expect(assignAsia({ reserveSpill })).resolves.toEqual({ ...ON_US_RESERVE, placed: true }) - expect(reserveSpill).toHaveBeenCalledWith({ skipOwnRegion: false, rowEpoch: 0 }) - expect(await database.query(`SELECT cell_id FROM relay_assignments`)).toEqual([]) - }) - - it('skips the own region after the in-region reserve fallback already tried it', async () => { - await closeAllDatabaseCells() - const regionReserve = vi.fn(async () => null) - const reserveSpill = vi.fn(async () => ON_US_RESERVE) - await expect(assignAsia({ regionReserve, reserveSpill })).resolves.toMatchObject({ cellId: 'us-reserve' }) - expect(regionReserve).toHaveBeenCalledOnce() - expect(reserveSpill).toHaveBeenCalledWith({ skipOwnRegion: true, rowEpoch: 0 }) - }) - - it('hands the spill the epoch of the host row it read', async () => { - const first = await assignAsia({}) - // Dormant: its next assign is a placement, which reads the row and finds no cell. - await store.changeActivity(IDENTITY, 'control', -1) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - await store.releaseExpiredActivity() - now += ASSIGNMENT_LIMITS.dormantTtlMs - await closeAllDatabaseCells() - const reserveSpill = vi.fn(async () => ON_US_RESERVE) - await assignAsia({ reserveSpill }) - expect(reserveSpill).toHaveBeenCalledWith({ skipOwnRegion: false, rowEpoch: first.assignmentEpoch }) - }) - - it('refuses with relay_capacity_exhausted when no reserve seat exists either', async () => { - await closeAllDatabaseCells() - await expect(assignAsia({ reserveSpill: async () => null })).rejects.toThrow('relay_capacity_exhausted') - }) - - it('answers a paced spill with its pace, not a refusal', async () => { - await closeAllDatabaseCells() - const reserveSpill = vi.fn(async () => { - throw new ReservePaceError(4) - }) - await expect(assignAsia({ reserveSpill })).rejects.toBeInstanceOf(ReservePaceError) - }) - - it('answers an in-region reserve pace before any spill', async () => { - await closeAllDatabaseCells() - const reserveSpill = vi.fn(async () => ON_US_RESERVE) - const regionReserve = async () => { - throw new ReservePaceError(2) - } - await expect(assignAsia({ regionReserve, reserveSpill })).rejects.toBeInstanceOf(ReservePaceError) - expect(reserveSpill).not.toHaveBeenCalled() - }) - - it('does not spill a reservation race: the host retries and re-picks', async () => { - database.armed = true - const reserveSpill = vi.fn(async () => ON_US_RESERVE) - await expect(assignAsia({ reserveSpill })).rejects.toThrow('relay_capacity_exhausted') - expect(reserveSpill).not.toHaveBeenCalled() - }) -}) diff --git a/cloud/apps/relay/src/assignment/assignment-roll-replaced-cell.test.ts b/cloud/apps/relay/src/assignment/assignment-roll-replaced-cell.test.ts index 0b5a00dd757..a30f59a07e7 100644 --- a/cloud/apps/relay/src/assignment/assignment-roll-replaced-cell.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-roll-replaced-cell.test.ts @@ -143,18 +143,12 @@ async function setup(cells: RelayCellConfig[] = [SOURCE, TARGET]) { // The old process stopped heartbeating at START_MS, so it is unheard from here. const OLD_UNHEARD_AT = START_MS + HEARTBEAT_TTL_MS + 1_000 -// Both routes that refused in production: a hinted assign (placement lane after its -// verification read finds the cell not live) and resolve, which then assigns. async function hintedAssign(store: RelayAssignmentStore) { return await store.assign(IDENTITY, 'us-central1', 'us-central1', undefined, { hostRequested: true }) } -async function resolveRoute(store: RelayAssignmentStore) { - return (await store.resolve(IDENTITY)) ?? (await store.assign(IDENTITY)) -} - async function expectRefused( attempt: Promise, cause: 'not_ready' | 'unheard' @@ -164,10 +158,7 @@ async function expectRefused( expect(error).toMatchObject({ unavailableCause: cause }) } -describe.each([ - ['hinted assign', hintedAssign], - ['resolve', resolveRoute] -] as const)('a host offline through a roll redials via %s', (_route, redial) => { +describe('a host offline through a roll redials via hinted assign', () => { describe('while the replacement process boots (not ready)', () => { it('is re-placed when that process started after the roll isolated the cell', async () => { const { store, first, heartbeat, at, isolateForRoll } = await setup() @@ -175,7 +166,7 @@ describe.each([ await at(20_000) await heartbeat(SOURCE, { incarnation: NEW_INCARNATION, startedAt: 15_000, ready: false }) - const moved = await redial(store) + const moved = await hintedAssign(store) expect(moved).toMatchObject({ cellId: TARGET.id }) expect(moved.assignmentEpoch).toBeGreaterThan(first.assignmentEpoch) }) @@ -186,7 +177,7 @@ describe.each([ await at(20_000) await heartbeat(SOURCE, { ready: false }) - await expectRefused(redial(store), 'not_ready') + await expectRefused(hintedAssign(store), 'not_ready') }) it('is refused while the new process reports holding connections', async () => { @@ -200,7 +191,7 @@ describe.each([ totalConnections: 1 }) - await expectRefused(redial(store), 'not_ready') + await expectRefused(hintedAssign(store), 'not_ready') }) it('is refused once the new process itself goes unheard', async () => { @@ -210,7 +201,7 @@ describe.each([ await heartbeat(SOURCE, { incarnation: NEW_INCARNATION, startedAt: 15_000, ready: false }) await at(20_000 + HEARTBEAT_TTL_MS + 1_000) - await expectRefused(redial(store), 'unheard') + await expectRefused(hintedAssign(store), 'unheard') }) it('is refused on an ordinary readiness dip with no roll stamp', async () => { @@ -218,7 +209,7 @@ describe.each([ await at(20_000) await heartbeat(SOURCE, { incarnation: NEW_INCARNATION, startedAt: 15_000, ready: false }) - await expectRefused(redial(store), 'not_ready') + await expectRefused(hintedAssign(store), 'not_ready') }) it('is refused on a migration-only cell parked without a roll stamp', async () => { @@ -227,7 +218,7 @@ describe.each([ await at(20_000) await heartbeat(SOURCE, { incarnation: NEW_INCARNATION, startedAt: 15_000, ready: false }) - await expectRefused(redial(store), 'not_ready') + await expectRefused(hintedAssign(store), 'not_ready') }) }) @@ -238,7 +229,7 @@ describe.each([ await isolateForRoll() await at(OLD_UNHEARD_AT) - await expectRefused(redial(store), 'unheard') + await expectRefused(hintedAssign(store), 'unheard') }) it('is refused when the roll stamp is stale, even with a new process', async () => { @@ -248,7 +239,7 @@ describe.each([ await at(stale) await heartbeat(SOURCE, { incarnation: NEW_INCARNATION, startedAt: stale - 1, ready: false }) - await expectRefused(redial(store), 'not_ready') + await expectRefused(hintedAssign(store), 'not_ready') }) }) diff --git a/cloud/apps/relay/src/assignment/assignment-row-lock-order-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-row-lock-order-postgres.test.ts deleted file mode 100644 index e05f3f2310c..00000000000 --- a/cloud/apps/relay/src/assignment/assignment-row-lock-order-postgres.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import { openRelayDatabase, type RelayDatabase } from '../database/database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip - -const cells = [ - { - id: 'row-lock-order-a', - url: 'https://row-lock-order-a.example.com', - capacityRequests: 200, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - }, - { - id: 'row-lock-order-b', - url: 'https://row-lock-order-b.example.com', - capacityRequests: 200, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - } -] -const userId = 'row-lock-order-user' -const hosts = ['rowlockhost00001', 'rowlockhost00002', 'rowlockhost00003', 'rowlockhost00004'].map( - (relayHostId) => ({ userId, relayHostId }) -) - -// pg_stat_database exposes cycles hidden by three 40P01 retries; eventual success alone misses deadlocks that exhaust retries under load. -describePostgres('PostgreSQL row lock order', () => { - const databases: RelayDatabase[] = [] - - beforeAll(async () => { - for (let index = 0; index < 4; index++) { - databases.push(await openRelayDatabase({ databaseUrl, dataDir: '' })) - } - }) - - async function removeTestRows(database: RelayDatabase): Promise { - await database.query( - `DELETE FROM relay_control_connection_reservations WHERE user_id = ?`, - [userId] - ) - for (const table of [ - 'relay_control_capabilities', - 'relay_assignment_activity_leases', - 'relay_post_drain_migration_pins', - 'relay_assignment_migration_incarnations', - 'relay_assignment_migrations', - 'relay_assignments' - ]) { - await database.query(`DELETE FROM ${table} WHERE user_id = ?`, [userId]) - } - for (const cell of cells) { - for (const table of [ - 'relay_cell_connection_snapshots', - 'relay_cell_connection_runtime', - 'relay_cell_connection_limits', - 'relay_cell_runtime', - 'relay_cells' - ]) { - await database.query(`DELETE FROM ${table} WHERE cell_id = ?`, [cell.id]) - } - } - } - - afterAll(async () => { - if (databases[0]) await removeTestRows(databases[0]) - for (const connection of databases) await connection.close() - }) - - async function deadlockCount(): Promise { - const rows = await databases[0]!.query( - `SELECT deadlocks FROM pg_stat_database WHERE datname = current_database()` - ) - return Number(rows[0]!.deadlocks) - } - - it('runs the cell accept and the placement retry concurrently without a cycle', async () => { - await removeTestRows(databases[0]!) - const stores = databases.map((database) => new RelayAssignmentStore(database, () => 100)) - await stores[0]!.reconcileCells(cells) - for (const cell of cells) { - await stores[0]!.recordCellHeartbeat({ - cellId: cell.id, - cellUrl: cell.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0, - connectionInclusionWatermark: 1, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - } - const placements = new Map() - for (const identity of hosts) { - const assignment = await stores[0]!.assign(identity) - placements.set(identity.relayHostId, assignment) - } - - const before = await deadlockCount() - // The accept path (host rows, then the cell row last) against the paths - // that must read the inventory first: placement and evacuation. - for (let round = 0; round < 12; round++) { - await Promise.allSettled( - hosts.flatMap((identity, index) => { - const placement = placements.get(identity.relayHostId)! - const store = stores[index % stores.length]! - const other = stores[(index + 1) % stores.length]! - return [ - store.activateControl(identity, { - cellId: placement.cellId, - assignmentEpoch: placement.assignmentEpoch, - generation: round + 2 - }), - other.assign(identity), - other.startEvacuation( - identity, - placement.cellId === cells[0]!.id ? cells[1]!.id : cells[0]!.id - ) - ] - }) - ) - } - const after = await deadlockCount() - - expect(after - before).toBe(0) - }, 120_000) -}) diff --git a/cloud/apps/relay/src/assignment/migrations/dead-cell-evacuation-precheck.test.ts b/cloud/apps/relay/src/assignment/migrations/dead-cell-evacuation-precheck.test.ts index 9d72905967d..4a1a2aff115 100644 --- a/cloud/apps/relay/src/assignment/migrations/dead-cell-evacuation-precheck.test.ts +++ b/cloud/apps/relay/src/assignment/migrations/dead-cell-evacuation-precheck.test.ts @@ -5,46 +5,16 @@ import type { RelayCellConfig } from '../../config.js' import { openInMemoryRelayDatabase, openRelayDatabase, - type RelayDatabase, - type SqlRow + type RelayDatabase } from '../../database/database.js' -// Both dialects must skip host scans with no actionable cells; stale existing-only rows previously scanned every assignment for nothing. const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const schema = 'relay_dead_cell_precheck_test' -const HOST_QUERY = 'FROM relay_assignments assignment' const CELLS: RelayCellConfig[] = [ { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } ] -class RecordingDatabase implements RelayDatabase { - readonly statements: string[] = [] - - constructor(private readonly delegate: RelayDatabase) {} - - get dialect() { - return this.delegate.dialect - } - - async query(sql: string, params: unknown[] = []): Promise { - this.statements.push(sql) - return await this.delegate.query(sql, params) - } - - async queryLocked(...args: Parameters): Promise { - return await this.delegate.queryLocked(...args) - } - - async transaction(operation: (transaction: RelayDatabase) => Promise): Promise { - return await this.delegate.transaction(operation) - } - - async close(): Promise { - await this.delegate.close() - } -} - function scopedUrl(): string { const url = new URL(databaseUrl!) url.searchParams.set('options', `-c search_path=${schema}`) @@ -91,13 +61,12 @@ describe.each(dialects)('dead-cell evacuation pre-check (%s)', (_dialect, open) async function setup(now: () => number) { database = await open() - const recording = new RecordingDatabase(database) - const store = new RelayAssignmentStore(recording, now, { + const store = new RelayAssignmentStore(database, now, { requireLiveCells: true, heartbeatTtlMs: 45_000 }) await store.reconcileCells(CELLS) - return { store, recording } + return { store } } async function heartbeat(store: RelayAssignmentStore, cell: RelayCellConfig): Promise { @@ -111,31 +80,9 @@ describe.each(dialects)('dead-cell evacuation pre-check (%s)', (_dialect, open) }) } - it('skips the host query when the only dead cell is unfenced and existing-only', async () => { - let now = 100 - const { store, recording } = await setup(() => now) - for (const cell of CELLS) await heartbeat(store, cell) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.setCellEnabled('cell-b', false) - expect(await store.assign(identity)).toMatchObject({ cellId: 'cell-a' }) - await store.setCellEnabled('cell-b', true) - await store.setCellEnabled('cell-a', false) - now += 45_001 - await heartbeat(store, CELLS[1]!) - recording.statements.length = 0 - - expect(await store.evacuateDeadCells()).toBe(0) - expect(recording.statements.some((sql) => sql.includes(HOST_QUERY))).toBe(false) - expect( - await database!.query(`SELECT cell_id FROM relay_assignments WHERE user_id = ?`, [ - identity.userId - ]) - ).toEqual([{ cell_id: 'cell-a' }]) - }) - it('still evacuates hosts from a dead uncapped cell that admits', async () => { let now = 100 - const { store, recording } = await setup(() => now) + const { store } = await setup(() => now) for (const cell of CELLS) await heartbeat(store, cell) const identity = { userId: 'user-a', relayHostId: 'host000000000001' } await store.setCellEnabled('cell-b', false) @@ -143,10 +90,8 @@ describe.each(dialects)('dead-cell evacuation pre-check (%s)', (_dialect, open) await store.setCellEnabled('cell-b', true) now += 45_001 await heartbeat(store, CELLS[1]!) - recording.statements.length = 0 expect(await store.evacuateDeadCells()).toBe(1) - expect(recording.statements.some((sql) => sql.includes(HOST_QUERY))).toBe(true) expect((await store.resolve(identity))?.cellId).toBe('cell-b') }) }) diff --git a/cloud/apps/relay/src/assignment/migrations/drain-migration-row-lookup.test.ts b/cloud/apps/relay/src/assignment/migrations/drain-migration-row-lookup.test.ts deleted file mode 100644 index 9f1831d4d92..00000000000 --- a/cloud/apps/relay/src/assignment/migrations/drain-migration-row-lookup.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { expect, it } from 'vitest' -import { createDrainMigrationRowLookup } from './drain-migration-row-lookup.js' -import type { SqlRow } from '../../database/database.js' - -function text(row: SqlRow, field: string): string { - const value = row[field] - if (typeof value !== 'string') { - throw new Error(`invalid_${field}`) - } - return value -} - -it('keeps first assignment matches, lease order, row identity, and separate identity components', () => { - const rows = [ - { user_id: 'a:b', relay_host_id: 'c', value: 1 }, - { user_id: 'a', relay_host_id: 'b:c', value: 2 }, - { user_id: 'a:b', relay_host_id: 'c', value: 3 }, - { user_id: '', relay_host_id: '', value: 4 } - ] - const lookup = createDrainMigrationRowLookup(rows, text) - for (const identity of [ - { userId: 'a:b', relayHostId: 'c' }, - { userId: 'a', relayHostId: 'b:c' }, - { userId: '', relayHostId: '' }, - { userId: 'missing', relayHostId: 'c' } - ]) { - const expected = rows.filter( - (row) => - row.user_id === identity.userId && row.relay_host_id === identity.relayHostId - ) - expect(lookup.first(identity)).toBe(expected[0]) - expect(lookup.all(identity)).toEqual(expected) - lookup.all(identity).forEach((row, index) => expect(row).toBe(expected[index])) - } -}) - -it('retains lazy validation and short circuiting when an inventory is malformed', () => { - const first = { user_id: 'user', relay_host_id: 'host' } - const identity = { userId: 'user', relayHostId: 'host' } - const lookup = createDrainMigrationRowLookup( - [first, { user_id: null, relay_host_id: 'bad' }], - text - ) - expect(lookup.first(identity)).toBe(first) - expect(() => lookup.all(identity)).toThrow('invalid_user_id') - const unrelated = createDrainMigrationRowLookup( - [first, { user_id: 'other', relay_host_id: null }], - text - ) - expect(unrelated.all(identity)).toEqual([first]) - expect(() => unrelated.first({ userId: 'other', relayHostId: 'host' })).toThrow( - 'invalid_relay_host_id' - ) -}) diff --git a/cloud/apps/relay/src/assignment/migrations/drain-migration-row-scaling.test.ts b/cloud/apps/relay/src/assignment/migrations/drain-migration-row-scaling.test.ts deleted file mode 100644 index 6eed78f80a1..00000000000 --- a/cloud/apps/relay/src/assignment/migrations/drain-migration-row-scaling.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' -import { afterEach, expect, it } from 'vitest' -import { RelayAssignmentStore } from '../assignment-store.js' -import { openInMemoryRelayDatabase, type RelayDatabase, type SqlRow } from '../../database/database.js' - -let database: RelayDatabase | undefined -afterEach(async () => await database?.close()) - -it.each([false, true])( - 'looks up a whole drain inventory with linear identity reads (expired: %s)', - async (expired) => { - database = await openInMemoryRelayDatabase() - let measuring = false - let identityReads = 0 - let indexedRows = 0 - const instrument = (delegate: RelayDatabase): RelayDatabase => ({ - dialect: delegate.dialect, - query: (sql, params) => delegate.query(sql, params), - queryLocked: async (sql, params, options) => { - const rows = await delegate.queryLocked(sql, params, options) - if ( - !measuring || - !sql.includes('WHERE EXISTS') || - !(sql.includes('SELECT assignment.*') || sql.includes('SELECT lease.*')) - ) { - return rows - } - indexedRows += rows.length - return rows.map( - (row): SqlRow => - new Proxy(row, { - get(target, key) { - if (key === 'user_id' || key === 'relay_host_id') { - identityReads++ - } - return Reflect.get(target, key) - } - }) - ) - }, - transaction: (operation, options) => - delegate.transaction((tx) => operation(instrument(tx)), options), - close: () => delegate.close() - }) - let now = 100 - const store = new RelayAssignmentStore(instrument(database), () => now, { - requireLiveCells: true - }) - const cells = ['a', 'b'].map((id) => ({ - id: `cell-${id}`, - url: `https://relay-${id}.example.com`, - capacityRequests: 500 - })) - await store.reconcileCells(cells) - const incarnation = '11111111-1111-4111-8111-111111111111' - for (const cell of cells) { - await store.recordCellHeartbeat({ - cellId: cell.id, - cellUrl: cell.url, - cellIncarnation: incarnation, - startedAt: 50, - ready: true, - observedRequests: 0 - }) - } - await store.setCellEnabled('cell-b', false) - const identities = Array.from({ length: 50 }, (_, index) => ({ - userId: `user-${index % 5}`, - relayHostId: `host${String(index).padStart(12, '0')}` - })) - for (const identity of identities) { - await store.assign(identity) - } - await store.setCellEnabled('cell-b', true) - await store.setCellEnabled('cell-a', false) - for (const identity of identities) { - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - } - const attempt = { - attemptId: '55555555-5555-4555-8555-555555555555', - cellId: 'cell-a', - cellIncarnation: incarnation, - traceValue: '66666666-6666-4666-8666-666666666666', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(attempt) - if (expired) { - now += ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - await store.releaseExpiredActivityLeases() - for (const cell of cells) { - await store.recordCellHeartbeat({ - cellId: cell.id, - cellUrl: cell.url, - cellIncarnation: incarnation, - startedAt: 50, - ready: true, - observedRequests: 0 - }) - } - } - measuring = true - await expect(store.beginCellDrainSend(attempt)).resolves.toMatchObject({ - state: 'send-may-have-started', - shouldSend: true - }) - expect(indexedRows).toBeGreaterThanOrEqual(100) - expect(identityReads).toBeLessThanOrEqual(indexedRows * 2) - const migrations = await database.query( - 'SELECT expires_at FROM relay_assignment_migrations' - ) - expect(migrations).toHaveLength(50) - expect( - migrations.every( - (row) => row.expires_at === now + ASSIGNMENT_LIMITS.migrationLeaseMs - ) - ).toBe(true) - } -) diff --git a/cloud/apps/relay/src/assignment/migrations/drain-release-cell-row-contention-postgres.test.ts b/cloud/apps/relay/src/assignment/migrations/drain-release-cell-row-contention-postgres.test.ts deleted file mode 100644 index 0008023fcc7..00000000000 --- a/cloud/apps/relay/src/assignment/migrations/drain-release-cell-row-contention-postgres.test.ts +++ /dev/null @@ -1,282 +0,0 @@ -import { createHash } from 'node:crypto' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from '../assignment-store.js' -import { - encodeMembership, - type CellAdmissionMembership, - type CellAdmissionState -} from '../../cell/admission/cell-admission-selector.js' -import type { RelayCellConfig } from '../../config.js' -import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip -const DIRECTOR_INSTANCES = 5 -const DIRECTOR_POOL_MAX = 3 -const DIRECTOR_APPLICATION = 'drain-release-contention-director' - -const USER_PREFIX = 'drain-release-contention' -const NOW = 1_000_000 -const CAPPED = { - capacityRequests: 6_000, - connectionHardCap: 3_000, - connectionUnobservedBound: 60 -} as const -const SOURCE: RelayCellConfig = { - id: 'drain-release-contention-a-source', - url: 'https://drain-release-contention-source.example.test', - region: 'asia-east2', - ...CAPPED -} -const TARGETS: RelayCellConfig[] = ['b', 'c', 'd'].map((suffix) => ({ - id: `drain-release-contention-${suffix}-target`, - url: `https://drain-release-contention-${suffix}-target.example.test`, - region: 'asia-east2', - ...CAPPED -})) -// Next to the database. Taken only once every Asia neighbour is at its cap. -const US_CELL: RelayCellConfig = { - id: 'drain-release-contention-e-us', - url: 'https://drain-release-contention-us.example.test', - region: 'us-central1', - ...CAPPED -} -const CELLS = [SOURCE, ...TARGETS, US_CELL] - -type Identity = { userId: string; relayHostId: string } -type Instance = { database: RelayDatabase; store: RelayAssignmentStore } - -function hostIdentity(index: number): Identity { - return { - userId: `${USER_PREFIX}-${index}`, - // Relay host ids are fixed-width opaque ids. - relayHostId: `drainrel${String(index).padStart(8, '0')}` - } -} - -describePostgres('PostgreSQL drain releases against director placement', () => { - const storeOptions = { requireLiveCells: true, heartbeatTtlMs: 45_000 } - const directors: Instance[] = [] - let observer: RelayDatabase - - function admin(): Instance { - return directors[0]! - } - - async function applySelector( - states: Record, - rollIsolatedCells?: string[] - ): Promise { - const current = await admin().store.inspectCellAdmissionSelector() - // Built from relay_cells: the apply requires exact coverage of a shared fleet. - const fleet = await admin().database.query( - `SELECT cell_id FROM relay_cells ORDER BY cell_id ASC` - ) - const membership: CellAdmissionMembership = { - existingOnly: [], - migrationOnly: [], - general: [] - } - for (const row of fleet) { - const cellId = String(row['cell_id']) - const state = - states[cellId] ?? - (current.selector.membership.existingOnly.includes(cellId) - ? 'existing-only' - : current.selector.membership.migrationOnly.includes(cellId) - ? 'migration-only' - : 'general') - if (state === 'existing-only') membership.existingOnly.push(cellId) - else if (state === 'migration-only') membership.migrationOnly.push(cellId) - else membership.general.push(cellId) - } - await admin().store.applyCellAdmissionSelector({ - attemptId: `drain-release-${current.selector.generation}`, - expectedGeneration: current.selector.generation, - ...(current.selector.generation === 0 - ? { - expectedMembershipSha256: createHash('sha256') - .update(encodeMembership(current.selector.membership)) - .digest('hex') - } - : {}), - membership, - ...(rollIsolatedCells ? { rollIsolatedCells } : {}) - }) - } - - // Other Postgres files write admission through the generation-0 helpers, so - // the selector goes back to generation 0 exactly as found. - async function resetSelectorBoundary(): Promise { - await admin().database.query( - `UPDATE relay_admission_selectors SET generation = 0, attempt_id = NULL - WHERE selector_id = 'general'` - ) - await admin().database.query( - `DELETE FROM relay_admission_selector_intents WHERE attempt_id LIKE 'drain-release-%'` - ) - await admin().store.reconcileCells([], false) - } - - async function deleteHostRows(): Promise { - for (const table of [ - 'relay_control_capabilities', - 'relay_control_connection_reservations', - 'relay_assignment_activity_leases', - 'relay_assignment_migrations', - 'relay_assignment_region_preferences', - 'relay_assignments' - ]) { - await admin().database.query(`DELETE FROM ${table} WHERE user_id LIKE '${USER_PREFIX}-%'`) - } - } - - // `atCap` reports those cells at their connection cap: no headroom left. - async function heartbeatAll(atCap: RelayCellConfig[] = []): Promise { - for (const [index, config] of CELLS.entries()) { - await admin().store.recordCellHeartbeat({ - cellId: config.id, - cellUrl: config.url, - cellIncarnation: `2222222${index}-2222-4222-8222-222222222222`, - startedAt: NOW - 1_000, - ready: true, - observedRequests: 0, - region: config.region, - // The cell checks enforced = total + in-flight + reserved. - totalConnections: atCap.includes(config) ? CAPPED.connectionHardCap : 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: atCap.includes(config) ? CAPPED.connectionHardCap : 0, - connectionHardCap: CAPPED.connectionHardCap, - connectionUnobservedBound: CAPPED.connectionUnobservedBound - }) - } - } - - // Holds `cellIds`' relay_cells rows in an open transaction until the returned release runs. - async function holdCellRows(cellIds: string[]): Promise<() => Promise> { - let release!: () => void - const released = new Promise((resolve) => (release = resolve)) - let held!: () => void - const acquired = new Promise((resolve) => (held = resolve)) - const holder = observer.transaction(async (transaction) => { - await transaction.queryLocked( - `SELECT cell_id FROM relay_cells WHERE cell_id IN (${cellIds.map(() => '?').join(', ')}) - ORDER BY cell_id ASC`, - cellIds - ) - held() - await released - }) - await acquired - return async () => { - release() - await holder - } - } - - // Every host holds a live control lease on the source, then the source is - // isolated for a roll: the state an Asia drain starts from. - async function seed(hosts: Identity[]): Promise { - await deleteHostRows() - await admin().database.query( - `UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id LIKE '${USER_PREFIX}-%'` - ) - // Restoring the source to general also clears the previous run's roll stamp. - await applySelector({ - [SOURCE.id]: 'general', - ...Object.fromEntries(TARGETS.map((target) => [target.id, 'migration-only' as const])) - }) - for (const identity of hosts) { - const grant = await admin().store.assign(identity, 'asia-east2', 'asia-east2') - expect(grant.cellId).toBe(SOURCE.id) - await admin().store.activateControl(identity, { - cellId: SOURCE.id, - assignmentEpoch: grant.assignmentEpoch, - generation: 1 - }) - } - await applySelector( - Object.fromEntries(TARGETS.map((target) => [target.id, 'general' as const])) - ) - await applySelector({ [SOURCE.id]: 'migration-only' }, [SOURCE.id]) - } - - beforeAll(async () => { - for (let index = 0; index < DIRECTOR_INSTANCES; index += 1) { - const database = await openRelayDatabase({ - databaseUrl, - dataDir: '', - poolMax: DIRECTOR_POOL_MAX, - applicationName: DIRECTOR_APPLICATION - }) - directors.push({ - database, - store: new RelayAssignmentStore(database, () => NOW, storeOptions) - }) - } - observer = await openRelayDatabase({ databaseUrl, dataDir: '', poolMax: 1 }) - await deleteHostRows() - await admin().store.reconcileCells(CELLS, false) - await resetSelectorBoundary() - await heartbeatAll() - }) - - afterAll(async () => { - if (directors.length > 0) { - await deleteHostRows() - // Cells before the selector rebuild, or its membership names missing rows. - for (const config of CELLS) { - for (const table of [ - 'relay_cell_connection_snapshots', - 'relay_cell_connection_runtime', - 'relay_cell_connection_limits', - 'relay_cell_runtime', - 'relay_cell_admission', - 'relay_cell_regions', - 'relay_cells' - ]) { - await admin().database.query(`DELETE FROM ${table} WHERE cell_id = ?`, [config.id]) - } - } - await resetSelectorBoundary() - } - for (const instance of directors) { - await instance.database.close() - } - await observer?.close() - }) - - it('places a reconnecting host off the isolated source while that source row is held', async () => { - await heartbeatAll() - const host = hostIdentity(9_000) - await seed([host]) - // A drain release holds the source row for its whole transaction; target-only placement never asks for it. - const sourceHeld = await holdCellRows([SOURCE.id]) - try { - const grant = await Promise.race([ - directors[1]!.store.assign(host, 'asia-east2', 'asia-east2'), - new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000)) - ]) - expect(grant).not.toBe('blocked') - expect(TARGETS.map(({ id }) => id)).toContain(grant === 'blocked' ? null : grant.cellId) - } finally { - await sourceHeld() - } - // Control: the same hold on the target rows does block a placement, so the hold above was real. - const other = hostIdentity(9_001) - await seed([other]) - const targetsHeld = await holdCellRows(TARGETS.map(({ id }) => id)) - const placement = directors[2]!.store.assign(other, 'asia-east2', 'asia-east2') - try { - const raced = await Promise.race([ - placement.then(() => 'placed' as const), - new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 1_000)) - ]) - expect(raced).toBe('blocked') - } finally { - await targetsHeld() - } - expect((await placement).cellId).not.toBe(SOURCE.id) - }, 30_000) -}) diff --git a/cloud/apps/relay/src/assignment/migrations/migration-recovery-postgres.test.ts b/cloud/apps/relay/src/assignment/migrations/migration-recovery-postgres.test.ts index 1cb85261395..5e0cc1988b5 100644 --- a/cloud/apps/relay/src/assignment/migrations/migration-recovery-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/migrations/migration-recovery-postgres.test.ts @@ -6,7 +6,6 @@ import { type RelayAssignmentMigration } from '../assignment-store.js' import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' -import { readRegisteredMigrationInventory } from './registered-migration-inventory.js' const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip @@ -245,39 +244,6 @@ describePostgres('PostgreSQL migration recovery', () => { ) } - it('reaps an abandoned registered migration onto its healthy target', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advance( - ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - ) - - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - expect( - await database.query( - `SELECT assignment.cell_id, assignment.assignment_epoch, - migration.completed_at, migration.aborted_at - FROM relay_assignments assignment - JOIN relay_assignment_migrations migration - ON migration.user_id = assignment.user_id - AND migration.relay_host_id = assignment.relay_host_id - AND migration.assignment_epoch = assignment.assignment_epoch - WHERE assignment.user_id = ? AND assignment.relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - ).toEqual([ - { - cell_id: input.cells.failed.id, - assignment_epoch: '2', - completed_at: String( - 100 + ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - ), - aborted_at: null - } - ]) - }) - it('reaps immediately after the retired source has a durable completed fence', async () => { const input = await fixture() await input.store.releaseActivity(input.identity, input.sourceControlId) @@ -290,7 +256,7 @@ describePostgres('PostgreSQL migration recovery', () => { expect( await database.query( `SELECT assignment.cell_id, assignment.assignment_epoch, - migration.completed_at, migration.aborted_at + (migration.completed_at IS NOT NULL) AS completed, migration.aborted_at FROM relay_assignments assignment JOIN relay_assignment_migrations migration ON migration.user_id = assignment.user_id @@ -303,177 +269,12 @@ describePostgres('PostgreSQL migration recovery', () => { { cell_id: input.cells.failed.id, assignment_epoch: '2', - completed_at: String(100 + 45_001 + ASSIGNMENT_LIMITS.migrationLeaseMs + 1), + completed: true, aborted_at: null } ]) }) - it('reaps immediately after the retired source has an adopted legacy fence', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await input.store.adoptLegacyCellFence( - input.cells.source.id, - input.cellIncarnation - ) - await input.store.commitLegacyCellFenceAdoption( - input.cells.source.id, - input.cellIncarnation - ) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - - expect( - ( - await readRegisteredMigrationInventory( - database, - 100 + 45_001 + ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - ) - ).abandoned - ).toBe(1) - - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - expect( - await database.query( - `SELECT assignment.cell_id, assignment.assignment_epoch, - migration.completed_at, migration.aborted_at - FROM relay_assignments assignment - JOIN relay_assignment_migrations migration - ON migration.user_id = assignment.user_id - AND migration.relay_host_id = assignment.relay_host_id - AND migration.assignment_epoch = assignment.assignment_epoch - WHERE assignment.user_id = ? AND assignment.relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - ).toEqual([ - { - cell_id: input.cells.failed.id, - assignment_epoch: '2', - completed_at: String(100 + 45_001 + ASSIGNMENT_LIMITS.migrationLeaseMs + 1), - aborted_at: null - } - ]) - }) - - it('does not reap after temporary legacy adoption without durable commit', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await input.store.adoptLegacyCellFence( - input.cells.source.id, - input.cellIncarnation - ) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - - expect( - ( - await readRegisteredMigrationInventory( - database, - 100 + 45_001 + ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - ) - ).abandoned - ).toBe(0) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(0) - input.advance(STRANDED_MIGRATION_ABANDON_MS) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - }) - - it('invalidates an adopted legacy fence when the source heartbeats', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await input.store.adoptLegacyCellFence( - input.cells.source.id, - input.cellIncarnation - ) - await input.store.commitLegacyCellFenceAdoption( - input.cells.source.id, - input.cellIncarnation - ) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - await input.heartbeat(input.cells.source) - - expect( - await database.query( - `SELECT cell_id FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - [input.cells.source.id] - ) - ).toEqual([]) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(0) - input.advance(STRANDED_MIGRATION_ABANDON_MS) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - }) - - it('invalidates an adopted legacy fence when the source restarts', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await input.store.adoptLegacyCellFence( - input.cells.source.id, - input.cellIncarnation - ) - await input.store.commitLegacyCellFenceAdoption( - input.cells.source.id, - input.cellIncarnation - ) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - await input.store.recordCellHeartbeat({ - cellId: input.cells.source.id, - cellUrl: input.cells.source.url, - cellIncarnation: '99999999-9999-4999-8999-999999999999', - startedAt: 51, - ready: true, - observedRequests: 0 - }) - - expect( - await database.query( - `SELECT cell_id FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - [input.cells.source.id] - ) - ).toEqual([]) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(0) - input.advance(STRANDED_MIGRATION_ABANDON_MS) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - }) - - it('serializes legacy adoption with a returning source heartbeat', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await input.store.adoptLegacyCellFence( - input.cells.source.id, - input.cellIncarnation - ) - - const [commit, heartbeatResult] = await Promise.allSettled([ - input.store.commitLegacyCellFenceAdoption( - input.cells.source.id, - input.cellIncarnation - ), - input.heartbeat(input.cells.source) - ]) - expect(heartbeatResult.status).toBe('fulfilled') - if (commit.status === 'rejected') { - expect(commit.reason).toMatchObject({ message: 'legacy_cell_fence_not_active' }) - } - expect( - await database.query( - `SELECT cell_id FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - [input.cells.source.id] - ) - ).toEqual([]) - input.advance( - ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - ) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - }) - it('restores the 24-hour guard when the fenced source heartbeats again', async () => { const input = await fixture() await input.store.releaseActivity(input.identity, input.sourceControlId) @@ -495,83 +296,6 @@ describePostgres('PostgreSQL migration recovery', () => { await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) }) - it('restores the 24-hour guard when the fenced source restarts', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await completeSourceFence(input) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - await input.store.recordCellHeartbeat({ - cellId: input.cells.source.id, - cellUrl: input.cells.source.url, - cellIncarnation: '99999999-9999-4999-8999-999999999999', - startedAt: 51, - ready: true, - observedRequests: 0 - }) - - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(0) - expect( - await database.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - ).toEqual([{ completed_at: null, aborted_at: null }]) - input.advance(STRANDED_MIGRATION_ABANDON_MS) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - }) - - it('serializes fenced cleanup with a returning source heartbeat', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advancePastHeartbeat() - await completeSourceFence(input) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - - const [cleanup, heartbeatResult] = await Promise.allSettled([ - input.store.abortExpiredEvacuations(), - input.heartbeat(input.cells.source) - ]) - expect(cleanup.status).toBe('fulfilled') - expect(heartbeatResult.status).toBe('fulfilled') - if (cleanup.status !== 'fulfilled') throw cleanup.reason - if (heartbeatResult.status !== 'fulfilled') throw heartbeatResult.reason - expect([0, 1]).toContain(cleanup.value) - const migrations = await database.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - if (cleanup.value === 1) { - expect(migrations[0]?.completed_at).not.toBeNull() - } else { - expect(migrations).toEqual([{ completed_at: null, aborted_at: null }]) - input.advance(STRANDED_MIGRATION_ABANDON_MS) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - } - }) - - it('keeps a freshly retired source protected without a durable fence', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - input.advance(ASSIGNMENT_LIMITS.migrationLeaseMs + 1) - - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(0) - expect( - await database.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - ).toEqual([{ completed_at: null, aborted_at: null }]) - input.advance(STRANDED_MIGRATION_ABANDON_MS) - await expect(input.store.abortExpiredEvacuations()).resolves.toBe(1) - }) - it('rolls an abandoned disabled target back to its source', async () => { const input = await fixture() await input.store.releaseActivity(input.identity, input.sourceControlId) @@ -585,7 +309,7 @@ describePostgres('PostgreSQL migration recovery', () => { expect( await database.query( `SELECT assignment.cell_id, assignment.assignment_epoch, - migration.completed_at, migration.aborted_at + migration.completed_at, (migration.aborted_at IS NOT NULL) AS aborted FROM relay_assignments assignment JOIN relay_assignment_migrations migration ON migration.user_id = assignment.user_id @@ -599,103 +323,11 @@ describePostgres('PostgreSQL migration recovery', () => { cell_id: input.cells.source.id, assignment_epoch: '3', completed_at: null, - aborted_at: String( - 100 + ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - ) + aborted: true } ]) }) - it('serializes cleanup against supersession without reporting a false target', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - await input.store.releaseActivity(input.identity, input.targetControlId) - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advance( - ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - ) - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.store.attestCellFence(input.cells.failed.id, input.cellIncarnation) - - const [cleanup, supersession] = await Promise.allSettled([ - input.store.abortExpiredEvacuations(), - input.store.supersedeRegisteredCellEvacuations( - input.cells.source.id, - input.cells.failed.id, - input.cells.replacement.id, - 100 - ) - ]) - expect(cleanup.status).toBe('fulfilled') - if (cleanup.status !== 'fulfilled') throw cleanup.reason - if (supersession.status === 'fulfilled') { - expect([0, 1]).toContain(supersession.value) - const assignment = await database.query( - `SELECT cell_id FROM relay_assignments WHERE user_id = ?`, - [input.identity.userId] - ) - expect(assignment).toEqual([{ - cell_id: - supersession.value === 1 - ? input.cells.replacement.id - : input.cells.source.id - }]) - if (supersession.value === 0) expect(cleanup.value).toBeGreaterThanOrEqual(1) - } else { - expect(cleanup.value).toBeGreaterThanOrEqual(1) - expect(supersession.reason).toMatchObject({ message: 'migration_already_superseded' }) - expect( - await database.query( - `SELECT cell_id FROM relay_assignments WHERE user_id = ?`, - [input.identity.userId] - ) - ).toEqual([{ cell_id: input.cells.source.id }]) - } - }) - - it('completes a registered migration from a dead source idempotently', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.failed) - await input.store.attestCellFence( - input.cells.source.id, - input.cellIncarnation - ) - const completion = { - assignmentEpoch: input.migration.assignmentEpoch, - sourceCellId: input.cells.source.id, - targetCellId: input.cells.failed.id - } - - await expect( - input.store.cellEvacuationStatus( - input.cells.source.id, - input.cells.failed.id, - true - ) - ).resolves.toMatchObject({ inProgress: 0, completed: 1 }) - await expect( - input.store.completeEvacuationFromDeadSource(input.identity, completion) - ).resolves.toMatchObject({ changed: false }) - expect(await reservations(input.cells)).toEqual({ source: 0, failed: 1, replacement: 0 }) - }) - - it('requires fence evidence for dead-source completion', async () => { - const input = await fixture() - await input.store.releaseActivity(input.identity, input.sourceControlId) - - await expect( - input.store.completeEvacuationFromDeadSource(input.identity, { - assignmentEpoch: input.migration.assignmentEpoch, - sourceCellId: input.cells.source.id, - targetCellId: input.cells.failed.id - }) - ).rejects.toThrow('cell_fence_attestation_missing') - expect(await reservations(input.cells)).toEqual({ source: 0, failed: 2, replacement: 0 }) - }) - it('supersedes a registered migration with exact accounting and idempotency', async () => { const input = await fixture() await database.query( @@ -760,416 +392,6 @@ describePostgres('PostgreSQL migration recovery', () => { ]) }) - it('reconciles durable cell accounting before aggregate supersession', async () => { - const input = await fixture() - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.store.attestCellFence( - input.cells.failed.id, - input.cellIncarnation - ) - await database.query( - `UPDATE relay_cells - SET reserved_requests = CASE WHEN cell_id = ? THEN 1 ELSE 0 END - WHERE cell_id IN (?, ?)`, - [input.cells.replacement.id, input.cells.source.id, input.cells.replacement.id] - ) - - await expect( - input.store.supersedeRegisteredCellEvacuations( - input.cells.source.id, - input.cells.failed.id, - input.cells.replacement.id, - 100 - ) - ).resolves.toBe(1) - expect(await reservations(input.cells)).toEqual({ - source: 1, - failed: 0, - replacement: 2 - }) - }) - - it('rebuilds an expired registered migration lease before supersession', async () => { - const input = await fixture() - await pinMigration(input, input.migration.assignmentEpoch) - await clearActivities(input) - await database.query( - `UPDATE relay_assignment_migrations SET expires_at = 0 - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [input.identity.userId, input.identity.relayHostId, input.migration.assignmentEpoch] - ) - await fenceFailedCell(input) - - await expect(supersedeAggregate(input)).resolves.toBe(1) - expect(await reservations(input.cells)).toEqual({ - source: 0, - failed: 0, - replacement: 1 - }) - expect( - await database.query( - `SELECT assignment_epoch, source_request_units, target_reserved_units, aborted_at - FROM relay_assignment_migrations WHERE user_id = ? ORDER BY assignment_epoch`, - [input.identity.userId] - ) - ).toEqual([ - { - assignment_epoch: '2', - source_request_units: '1', - target_reserved_units: '2', - aborted_at: '45101' - }, - { - assignment_epoch: '3', - source_request_units: '0', - target_reserved_units: '1', - aborted_at: null - } - ]) - }) - - it('retires an obsolete row without discarding replacement activity', async () => { - const input = await fixture() - await pinMigration(input, input.migration.assignmentEpoch) - await fenceFailedCell(input) - await input.store.supersedeRegisteredEvacuation(input.identity, { - assignmentEpoch: input.migration.assignmentEpoch, - sourceCellId: input.cells.source.id, - currentTargetCellId: input.cells.failed.id, - replacementTargetCellId: input.cells.replacement.id - }) - await database.query( - `UPDATE relay_assignment_migrations SET aborted_at = NULL - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [input.identity.userId, input.identity.relayHostId, input.migration.assignmentEpoch] - ) - const activityBefore = await assignmentActivities(input) - - await expect(supersedeAggregate(input)).resolves.toBe(1) - expect(await assignmentActivities(input)).toEqual(activityBefore) - expect(await reservations(input.cells)).toEqual({ - source: 1, - failed: 0, - replacement: 2 - }) - expect( - await database.query( - `SELECT assignment_epoch, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? ORDER BY assignment_epoch`, - [input.identity.userId] - ) - ).toEqual([ - { assignment_epoch: '2', aborted_at: '45101' }, - { assignment_epoch: '3', aborted_at: null } - ]) - }) - - it('anchors a newer dormant failed-cell epoch and preserves drain evidence', async () => { - const input = await fixture() - const drainAttemptId = await pinMigration(input, input.migration.assignmentEpoch) - await clearActivities(input) - await database.query( - `UPDATE relay_assignments SET assignment_epoch = 4 - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - await database.query( - `UPDATE relay_assignment_migrations SET expires_at = 0 - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [input.identity.userId, input.identity.relayHostId, input.migration.assignmentEpoch] - ) - await fenceFailedCell(input) - - await expect(supersedeAggregate(input)).resolves.toBe(1) - expect(await reservations(input.cells)).toEqual({ - source: 0, - failed: 0, - replacement: 1 - }) - expect( - await database.query( - `SELECT assignment_epoch, source_request_units, target_reserved_units, aborted_at - FROM relay_assignment_migrations WHERE user_id = ? ORDER BY assignment_epoch`, - [input.identity.userId] - ) - ).toEqual([ - { - assignment_epoch: '2', - source_request_units: '1', - target_reserved_units: '2', - aborted_at: '45101' - }, - { - assignment_epoch: '4', - source_request_units: '0', - target_reserved_units: '1', - aborted_at: '45101' - }, - { - assignment_epoch: '5', - source_request_units: '0', - target_reserved_units: '1', - aborted_at: null - } - ]) - expect( - await database.query( - `SELECT assignment_epoch, drain_attempt_id, source_request_units, - target_reserved_units - FROM relay_post_drain_migration_pins - WHERE user_id = ? ORDER BY assignment_epoch`, - [input.identity.userId] - ) - ).toEqual([ - { - assignment_epoch: '2', - drain_attempt_id: drainAttemptId, - source_request_units: '1', - target_reserved_units: '2' - }, - { - assignment_epoch: '4', - drain_attempt_id: drainAttemptId, - source_request_units: '0', - target_reserved_units: '1' - }, - { - assignment_epoch: '5', - drain_attempt_id: drainAttemptId, - source_request_units: '0', - target_reserved_units: '1' - } - ]) - }) - - it('uses an existing current-epoch migration once when retiring an older row', async () => { - const input = await fixture() - await pinMigration(input, input.migration.assignmentEpoch) - await clearActivities(input) - await database.query( - `UPDATE relay_assignments SET assignment_epoch = 4 - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - await database.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, - previous_epoch, assignment_epoch, source_request_units, - target_reserved_units, expires_at, target_registered_at, - completed_at, aborted_at, created_at, updated_at) - VALUES (?, ?, ?, ?, 2, 4, 0, 1, 0, 100, NULL, NULL, 100, 100)`, - [ - input.identity.userId, - input.identity.relayHostId, - input.cells.source.id, - input.cells.failed.id - ] - ) - await database.query( - `INSERT INTO relay_assignment_migration_incarnations - (user_id, relay_host_id, assignment_epoch, source_cell_incarnation, - target_cell_incarnation) - VALUES (?, ?, 4, ?, ?)`, - [ - input.identity.userId, - input.identity.relayHostId, - input.cellIncarnation, - input.cellIncarnation - ] - ) - await pinMigration(input, 4) - await fenceFailedCell(input) - - await expect(supersedeAggregate(input)).resolves.toBe(1) - expect( - await database.query( - `SELECT assignment_epoch, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? ORDER BY assignment_epoch`, - [input.identity.userId] - ) - ).toEqual([ - { assignment_epoch: '2', aborted_at: '45101' }, - { assignment_epoch: '4', aborted_at: '45101' }, - { assignment_epoch: '5', aborted_at: null } - ]) - expect(await reservations(input.cells)).toEqual({ - source: 0, - failed: 0, - replacement: 1 - }) - }) - - it('rejects a newer failed-cell epoch with ambiguous activity', async () => { - const input = await fixture() - await database.query( - `UPDATE relay_assignments SET assignment_epoch = 4 - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - await fenceFailedCell(input) - - await expect(supersedeAggregate(input)).rejects.toThrow( - 'migration_activity_topology_mismatch' - ) - expect( - await database.query( - `SELECT assignment_epoch, aborted_at FROM relay_assignment_migrations - WHERE user_id = ?`, - [input.identity.userId] - ) - ).toEqual([{ assignment_epoch: '2', aborted_at: null }]) - expect(await reservations(input.cells)).toEqual({ - source: 1, - failed: 2, - replacement: 0 - }) - }) - - it('leaves lease repair retryable when supersession later fails', async () => { - const input = await fixture(1) - await database.query( - `DELETE FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'migration'`, - [input.identity.userId, input.identity.relayHostId] - ) - await database.query( - `UPDATE relay_assignments SET migration_leases = 0 - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - await database.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests - 1 - WHERE cell_id = ?`, - [input.cells.failed.id] - ) - await database.query( - `UPDATE relay_assignment_migrations SET expires_at = 0 - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [input.identity.userId, input.identity.relayHostId, input.migration.assignmentEpoch] - ) - await fenceFailedCell(input) - - await expect(supersedeAggregate(input)).rejects.toThrow( - 'relay_capacity_exhausted' - ) - expect( - await database.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND activity_kind = 'migration'`, - [input.identity.userId] - ) - ).toEqual([{ activity_id: 'migration:2' }]) - expect( - await database.query( - `SELECT aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND assignment_epoch = 2`, - [input.identity.userId] - ) - ).toEqual([{ aborted_at: null }]) - - await database.query( - `UPDATE relay_cells SET capacity_requests = 2 WHERE cell_id = ?`, - [input.cells.replacement.id] - ) - await expect(supersedeAggregate(input)).resolves.toBe(1) - expect(await reservations(input.cells)).toEqual({ - source: 1, - failed: 0, - replacement: 2 - }) - }) - - it('serializes concurrent supersession retries without duplicating capacity', async () => { - const input = await fixture() - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.store.attestCellFence( - input.cells.failed.id, - input.cellIncarnation - ) - const supersession = { - assignmentEpoch: input.migration.assignmentEpoch, - sourceCellId: input.cells.source.id, - currentTargetCellId: input.cells.failed.id, - replacementTargetCellId: input.cells.replacement.id - } - - const results = await Promise.all([ - input.store.supersedeRegisteredEvacuation(input.identity, supersession), - input.store.supersedeRegisteredEvacuation(input.identity, supersession) - ]) - expect(results[0]).toEqual(results[1]) - expect(await reservations(input.cells)).toEqual({ source: 1, failed: 0, replacement: 2 }) - expect( - await database.query( - `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, - [input.identity.userId] - ) - ).toEqual([{ count: '2' }]) - }) - - it('fails a competing aggregate supersession instead of reporting the wrong target', async () => { - const input = await fixture() - const alternate = { - id: `recovery-cell-${sequence}-alternate`, - url: `https://recovery-${sequence}-alternate.example.com`, - capacityRequests: 20 - } - await input.store.reconcileCells([...Object.values(input.cells), alternate], false) - await input.heartbeat(alternate) - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.heartbeat(alternate) - await input.store.attestCellFence(input.cells.failed.id, input.cellIncarnation) - - const results = await Promise.allSettled([ - input.store.supersedeRegisteredCellEvacuations( - input.cells.source.id, - input.cells.failed.id, - input.cells.replacement.id, - 100 - ), - input.store.supersedeRegisteredCellEvacuations( - input.cells.source.id, - input.cells.failed.id, - alternate.id, - 100 - ) - ]) - const fulfilled = results.filter( - (result): result is PromiseFulfilledResult => result.status === 'fulfilled' - ) - const rejected = results.filter( - (result): result is PromiseRejectedResult => result.status === 'rejected' - ) - expect(fulfilled).toHaveLength(1) - expect(fulfilled[0]!.value).toBe(1) - expect(rejected).toHaveLength(1) - expect(rejected[0]!.reason).toMatchObject({ message: 'migration_already_superseded' }) - const successor = await database.query( - `SELECT assignment.cell_id, migration.target_cell_id - FROM relay_assignments assignment - JOIN relay_assignment_migrations migration - ON migration.user_id = assignment.user_id - AND migration.relay_host_id = assignment.relay_host_id - AND migration.assignment_epoch = assignment.assignment_epoch - WHERE assignment.user_id = ? AND migration.previous_epoch = ?`, - [input.identity.userId, input.migration.assignmentEpoch] - ) - expect(successor).toHaveLength(1) - expect(successor[0]!.cell_id).toBe(successor[0]!.target_cell_id) - expect([input.cells.replacement.id, alternate.id]).toContain( - successor[0]!.target_cell_id - ) - }) - it('rolls back every supersession change when replacement capacity is insufficient', async () => { const input = await fixture(1) await input.store.setCellEnabled(input.cells.failed.id, false) @@ -1205,153 +427,6 @@ describePostgres('PostgreSQL migration recovery', () => { ).toEqual([{ assignment_epoch: '2', aborted_at: null }]) }) - it('rolls back supersession when migration request-unit shape drifted', async () => { - const input = await fixture() - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.store.attestCellFence(input.cells.failed.id, input.cellIncarnation) - await database.query( - `UPDATE relay_assignment_activity_leases - SET request_units = request_units + 1 - WHERE user_id = ? AND activity_kind = 'migration'`, - [input.identity.userId] - ) - await database.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests + 1 WHERE cell_id = ?`, - [input.cells.failed.id] - ) - - await expect( - input.store.supersedeRegisteredEvacuation(input.identity, { - assignmentEpoch: input.migration.assignmentEpoch, - sourceCellId: input.cells.source.id, - currentTargetCellId: input.cells.failed.id, - replacementTargetCellId: input.cells.replacement.id - }) - ).rejects.toThrow('migration_activity_lease_shape_mismatch') - expect(await reservations(input.cells)).toEqual({ source: 1, failed: 3, replacement: 0 }) - expect( - await database.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments WHERE user_id = ?`, - [input.identity.userId] - ) - ).toEqual([{ cell_id: input.cells.failed.id, assignment_epoch: '2' }]) - }) - - it('rolls back supersession when locked cell reservation accounting drifted', async () => { - const input = await fixture() - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.store.attestCellFence(input.cells.failed.id, input.cellIncarnation) - await database.query( - `UPDATE relay_cells SET reserved_requests = 1 WHERE cell_id = ?`, - [input.cells.replacement.id] - ) - - await expect( - input.store.supersedeRegisteredEvacuation(input.identity, { - assignmentEpoch: input.migration.assignmentEpoch, - sourceCellId: input.cells.source.id, - currentTargetCellId: input.cells.failed.id, - replacementTargetCellId: input.cells.replacement.id - }) - ).rejects.toThrow('migration_cell_reservation_accounting_mismatch') - expect(await reservations(input.cells)).toEqual({ source: 1, failed: 2, replacement: 1 }) - expect( - await database.query( - `SELECT assignment_epoch, aborted_at FROM relay_assignment_migrations - WHERE user_id = ?`, - [input.identity.userId] - ) - ).toEqual([{ assignment_epoch: '2', aborted_at: null }]) - }) - - async function fenceFailedCell(input: RecoveryFixture): Promise { - await input.store.setCellEnabled(input.cells.failed.id, false) - input.advancePastHeartbeat() - await input.heartbeat(input.cells.source) - await input.heartbeat(input.cells.replacement) - await input.store.attestCellFence( - input.cells.failed.id, - input.cellIncarnation - ) - } - - async function supersedeAggregate(input: RecoveryFixture): Promise { - return await input.store.supersedeRegisteredCellEvacuations( - input.cells.source.id, - input.cells.failed.id, - input.cells.replacement.id, - 100 - ) - } - - async function clearActivities(input: RecoveryFixture): Promise { - await database.query( - `DELETE FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - await database.query( - `UPDATE relay_assignments SET reserved_controls = 0, reserved_splices = 0, - reserved_invites = 0, pending_installs = 0, pending_confirmations = 0, - migration_leases = 0 - WHERE user_id = ? AND relay_host_id = ?`, - [input.identity.userId, input.identity.relayHostId] - ) - await database.query( - `UPDATE relay_cells SET reserved_requests = 0 - WHERE cell_id IN (?, ?, ?)`, - [input.cells.source.id, input.cells.failed.id, input.cells.replacement.id] - ) - } - - async function pinMigration( - input: RecoveryFixture, - assignmentEpoch: number - ): Promise { - const drainAttemptId = `${input.identity.userId}-drain-${assignmentEpoch}` - await database.query( - `INSERT INTO relay_post_drain_migration_pins - (user_id, relay_host_id, assignment_epoch, drain_attempt_id, - source_cell_id, source_cell_incarnation, target_cell_id, - target_cell_incarnation, source_request_units, target_reserved_units, - pinned_at) - SELECT migration.user_id, migration.relay_host_id, - migration.assignment_epoch, ?, migration.source_cell_id, - incarnation.source_cell_incarnation, migration.target_cell_id, - incarnation.target_cell_incarnation, migration.source_request_units, - migration.target_reserved_units, 100 - FROM relay_assignment_migrations migration - JOIN relay_assignment_migration_incarnations incarnation - ON incarnation.user_id = migration.user_id - AND incarnation.relay_host_id = migration.relay_host_id - AND incarnation.assignment_epoch = migration.assignment_epoch - WHERE migration.user_id = ? AND migration.relay_host_id = ? - AND migration.assignment_epoch = ?`, - [ - drainAttemptId, - input.identity.userId, - input.identity.relayHostId, - assignmentEpoch - ] - ) - return drainAttemptId - } - - async function assignmentActivities(input: RecoveryFixture): Promise { - return await database.query( - `SELECT activity_id, activity_kind, cell_id, request_units - FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`, - [input.identity.userId, input.identity.relayHostId] - ) - } - async function reservations(cells: RecoveryFixture['cells']): Promise> { const rows = await database.query( `SELECT cell_id, reserved_requests FROM relay_cells diff --git a/cloud/apps/relay/src/assignment/migrations/postgres-drain-send-locking.test.ts b/cloud/apps/relay/src/assignment/migrations/postgres-drain-send-locking.test.ts index 5b75ce6ecba..ec6745e2c07 100644 --- a/cloud/apps/relay/src/assignment/migrations/postgres-drain-send-locking.test.ts +++ b/cloud/apps/relay/src/assignment/migrations/postgres-drain-send-locking.test.ts @@ -184,7 +184,7 @@ describePostgres('PostgreSQL drain-send locking', () => { }) now = migration.expiresAt + 1 - expect(await store.releaseExpiredActivityLeases()).toBeGreaterThan(0) + await store.releaseExpiredActivityLeases() await store.recordCellHeartbeat({ cellId: source.id, cellUrl: source.url, @@ -207,7 +207,7 @@ describePostgres('PostgreSQL drain-send locking', () => { cellId: source.id, cellIncarnation: sourceIncarnation }) - ).resolves.toMatchObject({ state: 'send-may-have-started', shouldSend: true }) + ).resolves.toMatchObject({ shouldSend: true }) await expect( database.query( `SELECT activity_kind, cell_id FROM relay_assignment_activity_leases diff --git a/cloud/apps/relay/src/assignment/migrations/registered-migration-inventory-postgres.test.ts b/cloud/apps/relay/src/assignment/migrations/registered-migration-inventory-postgres.test.ts deleted file mode 100644 index 3a4e02db149..00000000000 --- a/cloud/apps/relay/src/assignment/migrations/registered-migration-inventory-postgres.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import pg from 'pg' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' -import { REGISTERED_MIGRATION_ABANDON_MS } from './registered-migration-abandonment.js' -import { readRegisteredMigrationInventory } from './registered-migration-inventory.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip -const schema = 'relay_migration_inventory_test' - -describePostgres('PostgreSQL registered migration inventory', () => { - let database: RelayDatabase | undefined - - beforeAll(async () => { - const client = new pg.Client({ connectionString: databaseUrl }) - await client.connect() - try { - await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) - await client.query(`CREATE SCHEMA ${schema}`) - } finally { - await client.end() - } - const url = new URL(databaseUrl!) - url.searchParams.set('options', `-c search_path=${schema}`) - database = await openRelayDatabase({ databaseUrl: url.toString(), dataDir: '' }) - }) - - afterAll(async () => { - await database?.close() - const client = new pg.Client({ connectionString: databaseUrl }) - await client.connect() - try { - await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) - } finally { - await client.end() - } - }) - - it('counts a disabled-target migration even while its source is active', async () => { - const now = REGISTERED_MIGRATION_ABANDON_MS + 10_000 - await database!.query( - `INSERT INTO relay_cells - (cell_id, cell_url, enabled, capacity_requests, reserved_requests, - observed_requests, last_heartbeat_at, updated_at) - VALUES ('cell-a', 'https://a.example.test', 1, 4000, 1, 0, 0, 1), - ('cell-b', 'https://b.example.test', 0, 4000, 0, 0, 0, 1)` - ) - await database!.query( - `INSERT INTO relay_cell_admission (cell_id, admission_state, updated_at) - VALUES ('cell-a', 'general', 1), ('cell-b', 'existing-only', 1)` - ) - await database!.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES ('user-1', '111111111111', 'cell-b', 2, ?, ?, 0, 0, 0, 0, 0, 0)`, - [now, now] - ) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES ('user-1', '111111111111', 'control:source:1', 'control', 'cell-a', 1, ?, ?)`, - [now, now] - ) - await database!.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch, - assignment_epoch, source_request_units, target_reserved_units, expires_at, - target_registered_at, created_at, updated_at) - VALUES ('user-1', '111111111111', 'cell-a', 'cell-b', 1, 2, 1, 2, 2, 2, 1, 2)` - ) - - expect(await readRegisteredMigrationInventory(database!, now)).toEqual({ - open: 1, - inactive: 1, - abandoned: 1, - pairs: [ - { - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - open: 1, - inactive: 1, - abandoned: 1 - } - ] - }) - - await database!.query( - `INSERT INTO relay_cells - (cell_id, cell_url, enabled, capacity_requests, reserved_requests, - observed_requests, last_heartbeat_at, updated_at) - VALUES ('cell-c', 'https://c.example.test', 1, 4000, 0, 0, 0, 1)` - ) - await database!.query( - `INSERT INTO relay_cell_admission (cell_id, admission_state, updated_at) - VALUES ('cell-c', 'migration-only', 1)` - ) - await database!.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES ('user-2', '222222222222', 'cell-c', 2, ?, ?, 0, 0, 0, 0, 0, 0)`, - [now, now] - ) - await database!.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch, - assignment_epoch, source_request_units, target_reserved_units, expires_at, - target_registered_at, created_at, updated_at) - VALUES ('user-2', '222222222222', 'cell-a', 'cell-c', 1, 2, 1, 2, ?, NULL, 1, 2)`, - [now + 60_000] - ) - - expect(await readRegisteredMigrationInventory(database!, now)).toEqual({ - open: 2, - inactive: 1, - abandoned: 1, - pairs: [ - { - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - open: 1, - inactive: 1, - abandoned: 1 - }, - { - sourceCellId: 'cell-a', - targetCellId: 'cell-c', - open: 1, - inactive: 0, - abandoned: 0 - } - ] - }) - }) -}) diff --git a/cloud/apps/relay/src/assignment/migrations/registered-migration-inventory.test.ts b/cloud/apps/relay/src/assignment/migrations/registered-migration-inventory.test.ts deleted file mode 100644 index 1eca0b1749d..00000000000 --- a/cloud/apps/relay/src/assignment/migrations/registered-migration-inventory.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { openInMemoryRelayDatabase, type RelayDatabase } from '../../database/database.js' -import { REGISTERED_MIGRATION_ABANDON_MS } from './registered-migration-abandonment.js' -import { - formatRegisteredMigrationInventory, - readRegisteredMigrationInventory -} from './registered-migration-inventory.js' - -describe('registered migration inventory', () => { - const databases: RelayDatabase[] = [] - afterEach(async () => { - for (const database of databases.splice(0)) { - await database.close() - } - }) - it('does not restart abandonment when an old source migration lease is refreshed', async () => { - const database = await openInMemoryRelayDatabase() - databases.push(database) - const now = REGISTERED_MIGRATION_ABANDON_MS + 10_000 - await insertCell(database, 'cell-a', false, 'existing-only') - await insertCell(database, 'cell-b', true, 'migration-only') - await insertMigration(database, now - 1) - - const fresh = await readRegisteredMigrationInventory(database, now) - - expect(fresh).toEqual({ - open: 1, - inactive: 1, - abandoned: 1, - pairs: [ - { - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - open: 1, - inactive: 1, - abandoned: 1 - } - ] - }) - expect(formatRegisteredMigrationInventory(fresh)).toEqual([ - '[orca-relay] migration inventory open=1 expiredRegisteredInactive=1 abandonedRegistered=1', - '[orca-relay] migration pair sourceCellId=cell-a targetCellId=cell-b open=1 expiredRegisteredInactive=1 abandoned=1' - ]) - await database.query(`UPDATE relay_assignment_migrations SET expires_at = ?, updated_at = ?`, [ - now + 1, - now - ]) - expect((await readRegisteredMigrationInventory(database, now + 1)).abandoned).toBe(1) - }) - - it('includes unregistered open migrations without logging a host identity', async () => { - const database = await openInMemoryRelayDatabase() - databases.push(database) - const now = 10_000 - await insertCell(database, 'cell-a', false, 'existing-only') - await insertCell(database, 'cell-b', true, 'migration-only') - await insertMigration(database, now + 60_000, null) - - const inventory = await readRegisteredMigrationInventory(database, now) - - expect(inventory).toEqual({ - open: 1, - inactive: 0, - abandoned: 0, - pairs: [ - { - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - open: 1, - inactive: 0, - abandoned: 0 - } - ] - }) - expect(formatRegisteredMigrationInventory(inventory).join('\n')).not.toContain('111111111111') - }) -}) - -async function insertCell( - database: RelayDatabase, - cellId: string, - enabled: boolean, - admissionState: string -): Promise { - await database.query( - `INSERT INTO relay_cells - (cell_id, cell_url, enabled, capacity_requests, reserved_requests, - observed_requests, last_heartbeat_at, updated_at) - VALUES (?, ?, ?, 4000, 0, 0, 0, 1)`, - [cellId, `https://${cellId}.example.test`, enabled ? 1 : 0] - ) - await database.query( - `INSERT INTO relay_cell_admission (cell_id, admission_state, updated_at) - VALUES (?, ?, 1)`, - [cellId, admissionState] - ) -} - -async function insertMigration( - database: RelayDatabase, - expiresAt: number, - targetRegisteredAt: number | null = 2 -): Promise { - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES ('user-1', '111111111111', 'cell-b', 2, ?, ?, 0, 0, 0, 0, 0, 0)`, - [expiresAt, expiresAt] - ) - await database.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch, - assignment_epoch, source_request_units, target_reserved_units, expires_at, - target_registered_at, created_at, updated_at) - VALUES ('user-1', '111111111111', 'cell-a', 'cell-b', 1, 2, 1, 2, ?, ?, 1, 2)`, - [expiresAt, targetRegisteredAt] - ) -} diff --git a/cloud/apps/relay/src/assignment/public-admission/drain-return-admission.test.ts b/cloud/apps/relay/src/assignment/public-admission/drain-return-admission.test.ts index 1d17966a922..011e5c99313 100644 --- a/cloud/apps/relay/src/assignment/public-admission/drain-return-admission.test.ts +++ b/cloud/apps/relay/src/assignment/public-admission/drain-return-admission.test.ts @@ -1,23 +1,16 @@ import { describe, expect, it } from 'vitest' import { - DRAIN_RETURN_MIN_RETRY_AFTER_SECONDS, RelayDrainReturnAdmission, type DrainReturnDeferral, type DrainReturnGrant } from './drain-return-admission.js' import { RelayPublicAssignmentAdmission } from './public-assignment-admission.js' -type Timer = { at: number; callback: () => void; cancelled: boolean } - function harness( overrides: { maxQueued?: number - maxRetryAfterSeconds?: number - onServiceMs?: (durationMs: number) => void } = {} ) { - let now = 0 - const timers: Timer[] = [] const placement = new RelayPublicAssignmentAdmission({ maxConcurrent: 2, maxQueued: 8, @@ -26,32 +19,18 @@ function harness( maxDrainReturnConcurrent: 1, maxDrainReturnQueued: overrides.maxQueued ?? 0, drainReturnWaitMs: 3_000, - drainReturnMinIntervalMs: DRAIN_RETURN_MIN_RETRY_AFTER_SECONDS * 1_000, - now: () => now, - schedule: (callback, delayMs) => { - const timer = { at: now + delayMs, callback, cancelled: false } - timers.push(timer) - return () => { - timer.cancelled = true - } - } + drainReturnMinIntervalMs: 2_000, + now: () => 0, + schedule: () => () => undefined }) const lane = new RelayDrainReturnAdmission(placement, { maxConcurrent: 1, - maxRetryAfterSeconds: overrides.maxRetryAfterSeconds ?? 300, - now: () => now, - onServiceMs: overrides.onServiceMs + maxRetryAfterSeconds: 300, + now: () => 0 }) return { lane, - placement, - advance: (ms: number) => { - now += ms - for (const timer of timers.filter((entry) => !entry.cancelled && entry.at <= now)) { - timer.cancelled = true - timer.callback() - } - } + placement } } @@ -69,28 +48,6 @@ const host = (index: number): string => `host${String(index).padStart(12, '0')}` describe('drain-return admission', () => { - it('shortens the pacing once the measured service time is short', async () => { - const { lane, advance } = harness() - for (let index = 0; index < 30; index++) { - const grant = admitted(await lane.acquire(host(index))) - advance(50) - grant.lease.release() - advance(2_000) - } - admitted(await lane.acquire(host(100))) - - const retries = [] - for (let index = 101; index <= 120; index++) { - retries.push(deferred(await lane.acquire(host(index))).retryAfterSeconds) - } - - // ~50 ms per re-placement: twenty deferrals span about one second, where the - // 860 ms starting estimate would have spread them over seventeen. - expect(Math.max(...retries)).toBe(3) - }) - - // The unclamped sample: the EWMA's floor and ceiling would hide the real tail. - it('answers a host’s own early retry with its interval, not a place behind the cohort', async () => { const { lane } = harness() admitted(await lane.acquire(host(0))).lease.release() @@ -99,7 +56,7 @@ describe('drain-return admission', () => { const repeat = deferred(await lane.acquire(host(0))) expect(repeat).toMatchObject({ reason: 'host-rate-limited', - retryAfterSeconds: DRAIN_RETURN_MIN_RETRY_AFTER_SECONDS + retryAfterSeconds: 2 }) // And it booked nothing: the next overflow still gets the first slot. @@ -107,17 +64,6 @@ describe('drain-return admission', () => { expect(deferred(await lane.acquire(host(2))).retryAfterSeconds).toBe(2) }) - it('keeps a host’s reserved slot when it comes back early', async () => { - const { lane, advance } = harness() - admitted(await lane.acquire(host(0))) - for (let index = 1; index <= 4; index++) await lane.acquire(host(index)) - expect(deferred(await lane.acquire(host(5))).retryAfterSeconds).toBe(6) - - advance(1_000) - // Early and still full: the same instant, not a new slot after everyone else. - expect(deferred(await lane.acquire(host(5))).retryAfterSeconds).toBe(5) - }) - it('lets a queued placement go before a queued drain return', async () => { const { lane, placement } = harness({ maxQueued: 1 }) const drain = admitted(await lane.acquire(host(0))) diff --git a/cloud/apps/relay/src/assignment/public-admission/public-assignment-admission.test.ts b/cloud/apps/relay/src/assignment/public-admission/public-assignment-admission.test.ts index 9eb5849854d..887ad63f082 100644 --- a/cloud/apps/relay/src/assignment/public-admission/public-assignment-admission.test.ts +++ b/cloud/apps/relay/src/assignment/public-admission/public-assignment-admission.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { RelayPublicAssignmentAdmission } from './public-assignment-admission.js' describe('public assignment admission', () => { @@ -7,7 +7,7 @@ describe('public assignment admission', () => { const admission = new RelayPublicAssignmentAdmission({ maxConcurrent: 1, minIntervalMs: 0, - now: vi.fn(() => 0) + now: () => 0 }) const lease = await admission.acquire('host-a') expect(lease).not.toBeNull() @@ -46,19 +46,12 @@ describe('public assignment admission', () => { }) it('gives a bounded reserved waiter the next public slot', async () => { - let expire!: () => void - let cancelled = false const admission = new RelayPublicAssignmentAdmission({ maxConcurrent: 2, maxReservedConcurrent: 1, reservedWaitMs: 1_000, minIntervalMs: 0, - schedule: (callback) => { - expire = callback - return () => { - cancelled = true - } - } + schedule: () => () => undefined }) const first = await admission.acquire('host-a') const second = await admission.acquire('host-b') @@ -70,12 +63,10 @@ describe('public assignment admission', () => { const reserved = await reservedPromise expect(reserved).not.toBeNull() - expect(cancelled).toBe(true) await expect(admission.acquire('host-d')).resolves.toBeNull() reserved?.release() await expect(admission.acquire('host-d')).resolves.not.toBeNull() second?.release() - expire() }) it('serializes same-host assignment and reserved recovery without losing priority', async () => { @@ -100,34 +91,4 @@ describe('public assignment admission', () => { await expect(admission.acquire('host-b')).resolves.not.toBeNull() }) - it('tells each caller its own rejection reason without crossing requests', async () => { - const admission = new RelayPublicAssignmentAdmission({ - maxConcurrent: 1, - maxQueued: 1, - waitMs: 1_000, - maxReservedConcurrent: 1, - reservedWaitMs: 1_000, - minIntervalMs: 5_000, - now: () => 0, - schedule: () => () => undefined - }) - const queued: string[] = [] - const displaced: string[] = [] - const throttled: string[] = [] - - const active = await admission.acquire('host-a') - // 'host-b' waits, then reserved recovery for the same host displaces it. - const ordinary = admission.acquire('host-b', (reason) => displaced.push(reason)) - const reserved = admission.acquireReserved('host-b', (reason) => queued.push(reason)) - await expect(ordinary).resolves.toBeNull() - active?.release() - const recovered = await reserved - recovered?.release() - await admission.acquire('host-a', (reason) => throttled.push(reason)) - - expect(displaced).toEqual(['superseded']) - expect(queued).toEqual([]) - expect(throttled).toEqual(['host-rate-limited']) - }) - }) diff --git a/cloud/apps/relay/src/assignment/public-admission/public-assignment-circuit-breaker.test.ts b/cloud/apps/relay/src/assignment/public-admission/public-assignment-circuit-breaker.test.ts deleted file mode 100644 index b780bc26bd9..00000000000 --- a/cloud/apps/relay/src/assignment/public-admission/public-assignment-circuit-breaker.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createRelayApp } from '../../app.js' -import type { RelayConfig } from '../../config.js' - -describe('public assignment circuit breaker', () => { - it('rejects assign and resolve without invoking relay state', async () => { - const assign = vi.fn() - const resolveResume = vi.fn() - const app = createRelayApp(config(), { - store: { resolveResume } as never, - assignments: { assign } as never, - drain: vi.fn(), - ready: vi.fn(async () => true) - }) - - for (const path of ['/v1/assign', '/v1/resolve']) { - const response = await app.request(path, { method: 'POST' }) - expect(response.status).toBe(503) - expect(response.headers.get('retry-after')).toBe('5') - expect(await response.json()).toEqual({ error: 'assignments_temporarily_unavailable' }) - } - expect(assign).not.toHaveBeenCalled() - expect(resolveResume).not.toHaveBeenCalled() - expect((await app.request('/health')).status).toBe(200) - expect((await app.request('/v1/admin/drain', { method: 'POST' })).status).toBe(401) - }) -}) - -function config(): RelayConfig { - return { - port: 8080, - publicUrl: 'https://relay.example.test', - cellUrl: 'https://relay.example.test', - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: new TextEncoder().encode('assignment-key-with-at-least-32-bytes'), - role: 'director', - cellId: 'director', - cells: [], - adminAudience: 'https://relay.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - runtimeServiceAccount: 'runtime@example.test', - adminJwksUrl: 'https://auth.example.test/jwks', - databasePoolMax: 3, - publicAssignmentsEnabled: false, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - dataDir: './data' - } -} diff --git a/cloud/apps/relay/src/assignment/public-admission/public-assignment-drain-return-lane.test.ts b/cloud/apps/relay/src/assignment/public-admission/public-assignment-drain-return-lane.test.ts index c56f9bac8a0..4814e8d4eba 100644 --- a/cloud/apps/relay/src/assignment/public-admission/public-assignment-drain-return-lane.test.ts +++ b/cloud/apps/relay/src/assignment/public-admission/public-assignment-drain-return-lane.test.ts @@ -1,6 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { - RelayAssignmentRowBusyError, type RelayAssignment, type ResolvedRelayAssignment } from '../assignment-store.js' @@ -21,7 +20,6 @@ vi.mock('../../authentication/relay-token-verifier.js', () => ({ import { createRelayApp } from '../../app.js' afterEach(() => { - vi.useRealTimers() vi.restoreAllMocks() }) @@ -36,15 +34,11 @@ describe('drain-return lane', () => { const resolve = vi.fn(async ({ relayHostId }: { relayHostId: string }) => relayHostId === drained ? isolatedHome(relayHostId) : assignment('cell-o', relayHostId) ) - const outcomes: string[] = [] - const servedLanes: string[] = [] const app = createRelayApp(config(), { store: {} as never, assignments: { assign, resolve } as never, drain: vi.fn(), - ready: vi.fn(async () => true), - recordAssignmentAdmission: (outcome) => outcomes.push(outcome), - recordAdmissionServiceMs: (lane) => servedLanes.push(lane) + ready: vi.fn(async () => true) }) // The re-placement holds the drain lane; the sticky lane's only slot is free. @@ -56,125 +50,12 @@ describe('drain-return lane', () => { ) expect(reconnect.status).toBe(200) - expect(resolve).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: drained }, - { classifyHomeRollIsolation: true } - ) replacement.resolve(assignment('cell-new', drained)) expect((await moving).status).toBe(200) - expect(outcomes).toEqual(['drain-return', 'sticky']) - // The drained host held a sticky slot for its verification read too. - expect(servedLanes).toEqual(['sticky', 'sticky', 'drain-return']) - }) - - it('defers an overflowing drain return with a paced Retry-After and says why', async () => { - const holder = 'hhhhhhhhhhhhhhhh' - const replacement = deferred() - const assign = vi.fn(async () => await replacement.promise) - const resolve = vi.fn(async ({ relayHostId }: { relayHostId: string }) => - isolatedHome(relayHostId) - ) - const outcomes: string[] = [] - const reasons: string[] = [] - const retryAfters: number[] = [] - const causes: string[] = [] - const app = createRelayApp(config({ drainReturnQueueMax: 1, drainReturnWaitMs: 50 }), { - store: {} as never, - assignments: { assign, resolve } as never, - drain: vi.fn(), - ready: vi.fn(async () => true), - recordAssignmentAdmission: (outcome) => outcomes.push(outcome), - recordAssignmentRejectionReason: (lane, reason) => reasons.push(`${lane}:${reason}`), - recordDrainReturnRetryAfter: (seconds) => retryAfters.push(seconds), - recordAssignmentUnavailable: (cause) => causes.push(cause) - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const holding = app.request('/v1/assign', assignmentRequest(holder, { reconnect: true })) - await vi.waitFor(() => expect(assign).toHaveBeenCalledTimes(1)) - const queued = app.request( - '/v1/assign', - assignmentRequest('qqqqqqqqqqqqqqqq', { reconnect: true }) - ) - const overflow = await app.request( - '/v1/assign', - assignmentRequest('ffffffffffffffff', { reconnect: true }) - ) - - expect(overflow.status).toBe(503) - expect(overflow.headers.get('retry-after')).toBe('2') - const timedOut = await queued - expect(timedOut.status).toBe(503) - expect(Number(timedOut.headers.get('retry-after'))).toBeGreaterThanOrEqual(2) - expect(reasons).toEqual(['drain-return:queue-full', 'drain-return:wait-timeout']) - expect(retryAfters).toEqual([2, Number(timedOut.headers.get('retry-after'))]) - expect(outcomes.filter((outcome) => outcome === 'drain-return-deferred')).toHaveLength(2) - expect(causes).toEqual(['drain-return-deferred', 'drain-return-deferred']) - expect(warn.mock.calls.flat().join('\n')).toMatch( - /lane=drain-return hinted=true reason=queue-full .*retryAfter=2/ - ) - replacement.resolve(assignment('cell-new', holder)) - expect((await holding).status).toBe(200) - }) - - it('answers a drained host’s row-busy redial with the short interval', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const holder = 'hhhhhhhhhhhhhhhh' - const host = 'bbbbbbbbbbbbbbbb' - const holding = deferred() - let busy = true - const assign = vi.fn(async ({ relayHostId }: { relayHostId: string }) => { - if (relayHostId === holder) return await holding.promise - if (relayHostId === host && busy) { - busy = false - throw new RelayAssignmentRowBusyError() - } - return assignment('cell-new', relayHostId) - }) - const resolve = vi.fn(async ({ relayHostId }: { relayHostId: string }) => - isolatedHome(relayHostId) - ) - const app = createRelayApp(config({ drainReturnQueueMax: 1 }), { - store: {} as never, - assignments: { assign, resolve } as never, - drain: vi.fn(), - ready: vi.fn(async () => true) - }) - const request = (relayHostId: string) => - Promise.resolve( - app.request('/v1/assign', assignmentRequest(relayHostId, { reconnect: true })) - ) - - const held = request(holder) - await vi.waitFor(() => expect(assign).toHaveBeenCalledTimes(1)) - const queued = request(host) - await vi.advanceTimersByTimeAsync(10) - // A cohort behind it books the next ten service slots. - for (let index = 0; index < 10; index++) { - const overflow = await request(hostId('f', index)) - expect(overflow.status).toBe(503) - } - await vi.advanceTimersByTimeAsync(2_490) - holding.resolve(assignment('cell-new', holder)) - expect((await held).status).toBe(200) - const refused = await queued - expect(refused.headers.get('retry-after')).toBe('1') - - await vi.advanceTimersByTimeAsync(1_000) - const redial = await request(host) - - // Its own lane interval, not a slot after the ten hosts that came later. - expect(redial.status).toBe(503) - expect(redial.headers.get('retry-after')).toBe('2') }) }) -function hostId(prefix: string, index: number): string { - return `${prefix}${String(index).padStart(15, '0')}` -} - function assignmentRequest(relayHostId: string, extra: { reconnect?: boolean } = {}): RequestInit { return { method: 'POST', @@ -209,7 +90,7 @@ function deferred() { return { promise, resolve } } -function config(overrides: Partial = {}): RelayConfig { +function config(): RelayConfig { return { port: 8080, publicUrl: 'https://relay.example.test', @@ -233,7 +114,6 @@ function config(overrides: Partial = {}): RelayConfig { publicResolveConcurrency: 1, publicResolveWaitMs: 5_000, publicAssignmentRetryAfterSeconds: 5, - dataDir: './data', - ...overrides + dataDir: './data' } } diff --git a/cloud/apps/relay/src/assignment/public-admission/public-assignment-overload.test.ts b/cloud/apps/relay/src/assignment/public-admission/public-assignment-overload.test.ts index 14455be8b0b..b4382f962cd 100644 --- a/cloud/apps/relay/src/assignment/public-admission/public-assignment-overload.test.ts +++ b/cloud/apps/relay/src/assignment/public-admission/public-assignment-overload.test.ts @@ -18,68 +18,10 @@ import { createRelayApp } from '../../app.js' describe('public assignment overload', () => { - it('fairly drains a bounded incident-scale burst without raising database concurrency', async () => { - const pending = new Map>>() - const admittedHosts: string[] = [] - let active = 0 - let highWater = 0 - const assign = vi.fn(async ({ relayHostId }: { relayHostId: string }) => { - admittedHosts.push(relayHostId) - active++ - highWater = Math.max(highWater, active) - const operation = deferred() - pending.set(relayHostId, operation) - try { - return await operation.promise - } finally { - active-- - pending.delete(relayHostId) - } - }) - const app = createRelayApp(config(), { - store: {} as never, - assignments: { assign } as never, - drain: vi.fn(), - ready: vi.fn(async () => true) - }) - const hosts = Array.from( - { length: 430 }, - (_, index) => `host-${String(index).padStart(11, '0')}` - ) - - const firstWave = hosts.map((host) => - app.request('/v1/assign', assignmentRequest(host)) - ) - await vi.waitFor(() => expect(assign).toHaveBeenCalledTimes(2)) - const retryWave = await Promise.all( - hosts.map((host) => app.request('/v1/assign', assignmentRequest(host))) - ) - - expect(retryWave.every((response) => response.status === 503)).toBe(true) - expect(assign).toHaveBeenCalledTimes(2) - while (assign.mock.calls.length < 130) { - const activeOperations = [...pending] - const expectedCalls = assign.mock.calls.length + activeOperations.length - for (const [host, operation] of activeOperations) { - operation.resolve(assignment(`cell-${host}`, host)) - } - await vi.waitFor(() => expect(assign).toHaveBeenCalledTimes(expectedCalls)) - } - for (const [host, operation] of pending) { - operation.resolve(assignment(`cell-${host}`, host)) - } - const firstResponses = await Promise.all(firstWave) - expect(firstResponses.filter((response) => response.status === 200)).toHaveLength(130) - expect(firstResponses.filter((response) => response.status === 503)).toHaveLength(300) - expect(admittedHosts).toEqual(hosts.slice(0, 130)) - expect(highWater).toBe(2) - }) - it('refuses an oversized chunked body before parsing it, sparing only the reserve routes', async () => { - const resolve = vi.fn() const app = createRelayApp(config(), { store: {} as never, - assignments: { resolve } as never, + assignments: {} as never, drain: vi.fn(), ready: vi.fn(async () => true) }) @@ -98,15 +40,11 @@ describe('public assignment overload', () => { const refused = await app.request('/v1/resolve', chunked(64 * 1024)) expect(refused.status).toBe(413) expect(await refused.json()).toEqual({ error: 'request_too_large' }) - expect(resolve).not.toHaveBeenCalled() // Reserve bodies may reach 16 KiB, so the 4 KiB app limit must not answer for them. An - // unavailable route refuses before its own limit, including a body past 16 KiB. + // unavailable route refuses before its own limit. const reserve = await app.request('/internal/reserve', chunked(6 * 1024)) expect(reserve.status).toBe(404) expect(await reserve.json()).toEqual({ error: 'reserve_unavailable' }) - const oversized = await app.request('/internal/reserve', chunked(20 * 1024)) - expect(oversized.status).toBe(404) - expect(await oversized.json()).toEqual({ error: 'reserve_unavailable' }) }) it('reserves one bounded resolve lane while assignment work is saturated', async () => { @@ -133,8 +71,6 @@ describe('public assignment overload', () => { await vi.waitFor(() => expect(assign).toHaveBeenCalledTimes(2)) const recovery = app.request('/v1/resolve', resolveRequest('cccccccccccccccc', 1)) - await Promise.resolve() - expect(resolveResume).not.toHaveBeenCalled() const excessResolve = await app.request( '/v1/resolve', resolveRequest('dddddddddddddddd', 2) @@ -143,8 +79,6 @@ describe('public assignment overload', () => { expect(excessResolve.status).toBe(503) expect(excessAssign.status).toBe(503) - expect(assign).toHaveBeenCalledTimes(2) - expect(resolveResume).not.toHaveBeenCalled() pendingAssignments .get('aaaaaaaaaaaaaaaa') @@ -153,7 +87,6 @@ describe('public assignment overload', () => { await vi.waitFor(() => expect(resolveResume).toHaveBeenCalledTimes(1)) pendingResolve.resolve({ userId: 'user-1', relayDeviceId: 'device-1' }) expect((await recovery).status).toBe(200) - expect(resolve).toHaveBeenCalledTimes(1) for (const [host, operation] of pendingAssignments) { operation.resolve(assignment(`cell-${host}`, host)) diff --git a/cloud/apps/relay/src/assignment/public-admission/public-assignment-reconnect-lane.test.ts b/cloud/apps/relay/src/assignment/public-admission/public-assignment-reconnect-lane.test.ts index 58245e0d8c2..1a2b795252a 100644 --- a/cloud/apps/relay/src/assignment/public-admission/public-assignment-reconnect-lane.test.ts +++ b/cloud/apps/relay/src/assignment/public-admission/public-assignment-reconnect-lane.test.ts @@ -37,13 +37,11 @@ describe('public assignment reconnect lane', () => { const resolve = vi.fn(async ({ relayHostId }: { relayHostId: string }) => relayHostId === reconnecting ? assignment('cell-r', reconnecting) : null ) - const outcomes: string[] = [] const app = createRelayApp(config({ publicAssignmentQueueMax: 0 }), { store: {} as never, assignments: { assign, resolve } as never, drain: vi.fn(), - ready: vi.fn(async () => true), - recordAssignmentAdmission: (outcome) => outcomes.push(outcome) + ready: vi.fn(async () => true) }) // Saturate the placement lane with two in-flight newcomers, zero queue. @@ -59,18 +57,6 @@ describe('public assignment reconnect lane', () => { ) expect(reconnected.status).toBe(200) - expect(resolve).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: reconnecting }, - { classifyHomeRollIsolation: true } - ) - expect(assign).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: reconnecting }, - undefined, - undefined, - undefined, - { hostRequested: true } - ) - expect(outcomes).toContain('sticky') pending.get(newcomerA)?.resolve(assignment('cell-a', newcomerA)) pending.get(newcomerB)?.resolve(assignment('cell-b', newcomerB)) @@ -78,28 +64,6 @@ describe('public assignment reconnect lane', () => { expect((await second).status).toBe(200) }) - it('rate-limits repeat fast-lane attempts with the short retry-after', async () => { - const host = 'rrrrrrrrrrrrrrrr' - const assign = vi.fn(async () => assignment('cell-r', host)) - const resolve = vi.fn(async () => assignment('cell-r', host)) - const app = createRelayApp(config(), { - store: {} as never, - assignments: { assign, resolve } as never, - drain: vi.fn(), - ready: vi.fn(async () => true) - }) - - expect( - (await app.request('/v1/assign', assignmentRequest(host, { reconnect: true }))).status - ).toBe(200) - const repeat = await app.request('/v1/assign', assignmentRequest(host, { reconnect: true })) - - expect(repeat.status).toBe(503) - expect(repeat.headers.get('retry-after')).toBe('2') - expect(resolve).toHaveBeenCalledTimes(1) - expect(assign).toHaveBeenCalledTimes(1) - }) - it('rejects on the fast lane when the verification probe fails transiently', async () => { const host = 'tttttttttttttttt' const assign = vi.fn() @@ -117,7 +81,6 @@ describe('public assignment reconnect lane', () => { expect(response.status).toBe(503) expect(response.headers.get('retry-after')).toBe('2') - expect(assign).not.toHaveBeenCalled() }) it('refuses a dial whose assignment row is busy at once, and frees the fast lane', async () => { @@ -143,7 +106,6 @@ describe('public assignment reconnect lane', () => { expect(refused.status).toBe(503) expect(refused.headers.get('retry-after')).toBe('1') expect(await refused.json()).toEqual({ error: 'assignment_row_busy' }) - expect(warn.mock.calls.flat().join('\n')).toContain('reason=relay_assignment_row_busy') // The single fast-lane slot went back with the refusal. expect( (await app.request('/v1/assign', assignmentRequest(next, { reconnect: true }))).status diff --git a/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-store.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-store.test.ts index c68cf7efc02..18a95333bbb 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-store.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-store.test.ts @@ -111,51 +111,15 @@ async function setup() { } describe('constrained idle regional assignment transaction', () => { - it.each(['missing', 'disabled', 'future'] as const)( - 'does only one read per tick with %s durable control and sees later enablement', - async (state) => { - const { store, database, safety } = await setup() - const control = (await database.query( - "SELECT * FROM relay_region_rehome_control WHERE control_id = 'global'" - ))[0]! - if (state === 'missing') { - await database.query('DELETE FROM relay_region_rehome_control') - } else { - await database.query( - "UPDATE relay_region_rehome_control SET enabled = ?, not_before = ? WHERE control_id = 'global'", - [state === 'disabled' ? 0 : 1, safety.observedAt + (state === 'future' ? 1 : 0)] - ) - } - const query = vi.spyOn(database, 'query') - const transaction = vi.spyOn(database, 'transaction') - for (let tick = 0; tick < 3; tick++) { - query.mockClear() - expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) - expect(query).toHaveBeenCalledTimes(1) - expect(query.mock.calls[0]![0]).toMatch(/^SELECT .*FROM relay_region_rehome_control/s) - expect(transaction).not.toHaveBeenCalled() - } - if (state === 'missing') { - const columns = Object.keys(control) - await database.query( - `INSERT INTO relay_region_rehome_control (${columns.join(',')}) VALUES (${columns.map(() => '?').join(',')})`, - Object.values(control) - ) - } else { - await database.query( - "UPDATE relay_region_rehome_control SET enabled = 1, not_before = ? WHERE control_id = 'global'", - [safety.observedAt] - ) - } - query.mockClear() - expect(await store.selectIdleRegionalRehomeCandidates(safety)).toHaveLength(1) - expect(query.mock.calls.length).toBeGreaterThan(1) - await database.query("UPDATE relay_region_rehome_control SET enabled = 0 WHERE control_id = 'global'") - query.mockClear() - expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) - expect(query).toHaveBeenCalledTimes(1) - } - ) + it('sees durable control changes between candidate polls', async () => { + const { store, database, safety } = await setup() + await database.query("UPDATE relay_region_rehome_control SET enabled = 0 WHERE control_id = 'global'") + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) + await database.query("UPDATE relay_region_rehome_control SET enabled = 1 WHERE control_id = 'global'") + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toHaveLength(1) + await database.query("UPDATE relay_region_rehome_control SET enabled = 0 WHERE control_id = 'global'") + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) + }) it.each([10, 11])('reserves source activity plus assignment at target capacity %i', async (capacity) => { const { store, database, safety, request } = await setup() @@ -184,33 +148,6 @@ describe('constrained idle regional assignment transaction', () => { }) }) - it.each(['next_dispatch_at', 'paused_until'] as const)( - 'skips the candidate join while %s holds the durable dispatch budget closed', - async (column) => { - const { store, database, safety } = await setup() - const query = vi.spyOn(database, 'query') - // One assignment only: setup leaves both fields at 0, and naming the other - // one too would assign this column twice, which Postgres rejects. - await database.query( - `UPDATE relay_region_rehome_worker_state SET ${column} = ? WHERE worker_id = 'global'`, - [safety.observedAt + 1] - ) - for (let tick = 0; tick < 3; tick++) { - query.mockClear() - expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) - expect(query).toHaveBeenCalledTimes(2) - expect(query.mock.calls[1]![0]).toMatch(/FROM relay_region_rehome_worker_state/s) - } - await database.query( - `UPDATE relay_region_rehome_worker_state SET ${column} = ? WHERE worker_id = 'global'`, - [safety.observedAt] - ) - query.mockClear() - expect(await store.selectIdleRegionalRehomeCandidates(safety)).toHaveLength(1) - expect(query.mock.calls.length).toBeGreaterThan(2) - } - ) - // sourceRequestUnits reads a reserve cell's missing phone leases as zero units; selection must drop it. it.each(['source', 'target'])('drops every candidate while the %s cell is recorded as reserve', async (cellId) => { const { store, safety } = await setup() @@ -267,51 +204,6 @@ describe('constrained idle regional assignment transaction', () => { expect(first.some((c) => c.relayHostId === next[0]!.relayHostId)).toBe(false) }) - it('progresses past a full page of busy candidates without writing eligibility state', async () => { - const { store, database, safety } = await setup() - for (const table of [ - 'relay_assignments', - 'relay_assignment_activity_leases', - 'relay_control_capabilities', - 'relay_region_decisions' - ]) { - const template = ( - await database.query(`SELECT * FROM ${table} WHERE user_id = ? AND relay_host_id = ?`, [ - identity.userId, - identity.relayHostId - ]) - )[0]! - const columns = Object.keys(template) - for (let index = 0; index < 100; index++) { - const values = columns.map((column) => - column === 'user_id' || column === 'relay_host_id' ? '?' : column - ) - await database.query( - `INSERT INTO ${table} (${columns.join(', ')}) SELECT ${values.join(', ')} FROM ${table} - WHERE user_id = ? AND relay_host_id = ?`, - [ - `idle-store-test-${String(index).padStart(3, '0')}`, - `pagehost${String(index).padStart(8, '0')}`, - identity.userId, - identity.relayHostId - ] - ) - } - } - const first = await store.selectIdleRegionalRehomeCandidates(safety) - const next = await store.selectIdleRegionalRehomeCandidates(safety) - expect(first).toHaveLength(100) - expect(next).toHaveLength(1) - expect(next[0]!.relayHostId).toBe('pagehost00000099') - const restarted = new RelayAssignmentStore(database, () => safety.observedAt, { - regionalRehomeCohortPercent: 100 - }) - expect(await restarted.selectIdleRegionalRehomeCandidates(safety)).toEqual(first) - expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) - const decisions = await database.query('SELECT last_considered_at FROM relay_region_decisions') - expect(decisions.every((decision) => Number(decision.last_considered_at) === 0)).toBe(true) - }) - it.runIf(Boolean(process.env.ORCA_IDLE_REHOME_POSTGRES_URL))( 'rechecks generation when replacement wins after the initial authority lookup', async () => { @@ -430,20 +322,6 @@ describe('constrained idle regional assignment transaction', () => { expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) }) - it('selects read-only with stable identity and the control generation, not probe generation', async () => { - const { store, safety, database } = await setup() - const before = await database.query('SELECT * FROM relay_assignments') - const candidates = await store.selectIdleRegionalRehomeCandidates(safety) - expect(candidates).toHaveLength(1) - expect(candidates[0]).toMatchObject({ - sourceGeneration: 7, - sourceCellId: 'source', - targetCellId: 'target' - }) - expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual(candidates) - expect(await database.query('SELECT * FROM relay_assignments')).toEqual(before) - expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) - }) }) function holdStatement(database: RelayDatabase, fragment: string) { diff --git a/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-window.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-window.test.ts index 403ccf16830..6c4c559f06f 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-window.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/idle-regional-rehome-window.test.ts @@ -151,52 +151,6 @@ describe('idle regional rehome candidate window', () => { expect(new Set(candidates.map((candidate) => candidate.attemptId)).size).toBe(3) }) - it('drops only the targets without room for the host plus its source activity', async () => { - const { store, database, safety } = await setup() - await seedHost(store, identity) - await database.query( - 'UPDATE relay_assignment_activity_leases SET request_units = 4 WHERE user_id = ?', - [identity.userId] - ) - // Five units needed: four source units plus the assignment the move reserves. - await database.query("UPDATE relay_cells SET capacity_requests = 4 WHERE cell_id = 'asia-idle'") - const short = await store.selectIdleRegionalRehomeCandidates(safety) - expect(short.map((candidate) => candidate.targetCellId)).toEqual(['asia-mid', 'asia-busy']) - // Exactly enough room is enough; it ranks last because the ratio is per capacity. - await database.query("UPDATE relay_cells SET capacity_requests = 5 WHERE cell_id = 'asia-idle'") - const exact = await store.selectIdleRegionalRehomeCandidates(safety) - expect(exact.map((candidate) => candidate.targetCellId)).toEqual([ - 'asia-mid', - 'asia-busy', - 'asia-idle' - ]) - }) - - it('reads a bounded window of decisions however many hosts are eligible', async () => { - const { store, database, safety } = await setup() - await seedHost(store, identity) - await cloneHosts(database, identity, 700) - const query = database.query.bind(database) - const decisionRows: number[] = [] - vi.spyOn(database, 'query').mockImplementation(async (sql, params) => { - const rows = await query(sql, params) - if (/^SELECT user_id, relay_host_id FROM relay_region_decisions/.test(sql)) { - decisionRows.push(rows.length) - } - return rows - }) - const first = await store.selectIdleRegionalRehomeCandidates(safety) - const next = await store.selectIdleRegionalRehomeCandidates(safety) - expect(decisionRows.length).toBeGreaterThan(0) - for (const count of decisionRows) { - expect(count).toBeLessThanOrEqual(500) - } - expect(first).toHaveLength(102) - expect(next).toHaveLength(102) - const firstKeys = new Set(first.map((c) => `${c.userId}/${c.targetCellId}`)) - expect(next.every((c) => !firstKeys.has(`${c.userId}/${c.targetCellId}`))).toBe(true) - }) - it("keeps the window's last host when a decision turns eligible between the two reads", async () => { const { store, database, safety, now } = await setup() await seedHost(store, identity) @@ -252,7 +206,6 @@ describe('idle regional rehome candidate window', () => { for (let poll = 0; poll < 20 && !wrapped; poll++) { const page = await store.selectIdleRegionalRehomeCandidates(safety) expect(page.length).toBeGreaterThan(0) - expect(page.length).toBeLessThanOrEqual(102) for (const candidate of page) { const key = `${candidate.userId}/${candidate.targetCellId}` if (seen.has(key)) { @@ -286,23 +239,4 @@ describe('idle regional rehome candidate window', () => { expect(await store.selectIdleRegionalRehomeCandidates(safety)).toHaveLength(3) }) - it('excludes a host outside the cohort', async () => { - const { store, database } = await setup() - await seedHost(store, identity) - const now = 100_000_000 + 86_400_000 - const safety = { - observedAt: now, - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - await database.query('UPDATE relay_region_decisions SET cohort_bucket = 40') - const narrow = new RelayAssignmentStore(database, () => now, { regionalRehomeCohortPercent: 40 }) - expect(await narrow.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) - const wide = new RelayAssignmentStore(database, () => now, { regionalRehomeCohortPercent: 41 }) - expect(await wide.selectIdleRegionalRehomeCandidates(safety)).toHaveLength(3) - }) }) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/region-correction-restart.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/region-correction-restart.test.ts index b13e1b9d3a5..beb6a3c58d1 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/region-correction-restart.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/region-correction-restart.test.ts @@ -80,7 +80,7 @@ describe('persisted region decisions across director restart', () => { expect(row.outcome).toBe('inconclusive') expect(Number(row.expires_at)).toBe(context.window.expiresAt) const successor = (await context.issue(restarted.store)).window! - expect(successor.generation).toBe(context.window.generation + 1) + expect(successor.generation).toBe(2) expect(await restarted.store.exchangeRegionCorrection(identity, context.report, epoch)) .toMatchObject({ reportStatus: 'stale' }) }) @@ -111,7 +111,7 @@ describe('persisted region decisions across director restart', () => { context.setNow(1_000_000_000 - 60_000) const restarted = await context.restart() const successor = (await context.issue(restarted.store)).window! - expect(successor.generation).toBe(context.window.generation + 1) + expect(successor.generation).toBe(2) expect(successor.expiresAt).toBe(context.window.expiresAt - 60_000) expect(await restarted.store.exchangeRegionCorrection(identity, context.report, context.window.assignmentEpoch)) .toMatchObject({ reportStatus: 'stale' }) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/region-correction-store.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/region-correction-store.test.ts index 5204d158d0e..384945db575 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/region-correction-store.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/region-correction-store.test.ts @@ -124,104 +124,7 @@ async function window(context: Awaited>) { return result.window! } -async function regionalMigration(context: Awaited>) { - const migration = await context.store.startEvacuation(identity, cells[1]!.id) - const attemptId = '33333333-3333-4333-8333-333333333333' - await context.database.query( - `INSERT INTO relay_region_rehome_attempts - (attempt_id,user_id,relay_host_id,preferred_region,source_cell_id,source_cell_incarnation, - target_cell_id,target_cell_incarnation,previous_epoch,assignment_epoch,drain_grace_ms,send_attempts,created_at,updated_at) - VALUES (?,?,?,'asia-east2',?,?,?,?,?,?,60000,1,?,?)`, - [ - attemptId, - identity.userId, - identity.relayHostId, - cells[0]!.id, - incarnations[0], - cells[1]!.id, - incarnations[1], - migration.previousEpoch, - migration.assignmentEpoch, - context.now(), - context.now() - ] - ) - return { migration } -} - describe('ordered region decisions and migration outcomes', () => { - it('reports aggregate migration lifecycle and reservations without identity disclosure or writes', async () => { - const context = await setup() - const { migration } = await regionalMigration(context) - context.advance(1_000) - const before = await context.database.query('SELECT * FROM relay_region_rehome_attempts') - const outcomes = await context.store.regionCorrectionOutcomes() - expect(outcomes).toEqual([ - expect.objectContaining({ - sourceCellId: cells[0]!.id, - targetCellId: cells[1]!.id, - state: 'registering', - count: 1, - oldestOpenMs: 1_000 - }) - ]) - expect(outcomes[0]!.targetReservedUnits).toBeGreaterThan(0) - expect(JSON.stringify(outcomes)).not.toContain(identity.relayHostId) - expect(JSON.stringify(outcomes)).not.toContain(identity.userId) - expect(await context.database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual( - before - ) - await context.store.activateControl(identity, { - cellId: cells[1]!.id, - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: cells[1]!.id, - assignmentEpoch: migration.assignmentEpoch - }) - expect(await context.store.regionCorrectionOutcomes()).toEqual([ - expect.objectContaining({ state: 'registered' }) - ]) - await context.store.releaseActivity(identity, context.activityId) - expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - expect(await context.store.regionCorrectionOutcomes()).toEqual([ - expect.objectContaining({ - state: 'completed', - targetReservedUnits: 0, - oldestOpenMs: 0 - }) - ]) - }) - - it('previews the uncapped fleet without writes, claims, or locked reads', async () => { - const context = await setup() - const query = context.database.query.bind(context.database) - const transaction = context.database.transaction.bind(context.database) - const queryLocked = context.database.queryLocked.bind(context.database) - context.database.query = async (sql, params) => { - expect(sql.trim()).toMatch(/^(SELECT|WITH)/i) - return query(sql, params) - } - context.database.transaction = async () => { - throw new Error('preview_must_not_open_mutating_transaction') - } - context.database.queryLocked = async () => { - throw new Error('preview_must_not_lock') - } - try { - const preview = await context.store.previewRegionalRehomeEligibility() - expect(preview.counts['no-verified-decision']).toBeGreaterThanOrEqual(1) - expect(preview.globalSafetyFailure).toBe('process-safety-unavailable') - expect(JSON.stringify(preview)).not.toContain(identity.relayHostId) - expect(JSON.stringify(preview)).not.toContain(identity.userId) - } finally { - context.database.query = query - context.database.transaction = transaction - context.database.queryLocked = queryLocked - } - }) - it('allocates distinct ordered generations for concurrent window issuers', async () => { const context = await setup() const replies = await Promise.all([window(context), window(context), window(context)]) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-constraint-migration-postgres.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-constraint-migration-postgres.test.ts index 6dd56d46840..9d6d7edfd89 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-constraint-migration-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-constraint-migration-postgres.test.ts @@ -1,10 +1,6 @@ import pg from 'pg' import { afterAll, beforeEach, describe, expect, it } from 'vitest' -import { - openRelayDatabase, - REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS, - type RelayDatabase -} from '../../database/database.js' +import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip @@ -127,25 +123,15 @@ describePostgres('PostgreSQL regional rehome constraint migration', () => { await expect( client.query(INSERT_ATTEMPT, attemptValues('attempt-3', 'europe-west1')) ).rejects.toMatchObject({ code: '23514' }) - const constraints = await client.query( - `SELECT conname FROM pg_constraint - WHERE conrelid = 'relay_region_rehome_attempts'::regclass - AND conname LIKE '%preferred_region%' - ORDER BY conname` - ) - expect(constraints.rows).toEqual([ - { conname: 'relay_region_rehome_attempts_preferred_region_valid' } - ]) - // The existing control row keeps its tuning and gains the cooldown. + // Preserve existing control tuning across the upgrade. const control = await client.query( - `SELECT generation, preference_max_age_ms, host_cooldown_ms + `SELECT generation, preference_max_age_ms FROM relay_region_rehome_control WHERE control_id = 'global'` ) expect(control.rows).toEqual([ { generation: '3', - preference_max_age_ms: '86400000', - host_cooldown_ms: String(REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS) + preference_max_age_ms: '86400000' } ]) }) @@ -182,14 +168,6 @@ describePostgres('PostgreSQL regional rehome constraint migration', () => { await withClient(async (client) => { await client.query(`SET search_path = ${schema}`) await client.query(INSERT_ATTEMPT, attemptValues('attempt-4', 'us-central1')) - const constraints = await client.query( - `SELECT conname FROM pg_constraint - WHERE conrelid = 'relay_region_rehome_attempts'::regclass - AND conname LIKE '%preferred_region%'` - ) - expect(constraints.rows).toEqual([ - { conname: 'relay_region_rehome_attempts_preferred_region_valid' } - ]) }) }, 60_000) }) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-source-region-filter.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-source-region-filter.test.ts index 4b5db8f5e21..4733e94fbcf 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-source-region-filter.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-source-region-filter.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { RelayAssignmentStore } from '../assignment-store.js' import { openIdleRehomeTestDatabase } from './idle-regional-rehome-test-database.js' @@ -134,10 +134,6 @@ const moves = (candidates: { userId: string; sourceCellId: string; targetCellId: to: cells.find(({ id }) => id === targetCellId)!.region })) -afterEach(() => { - vi.restoreAllMocks() -}) - describe('rehome source-region filter', () => { it('keeps US to Asia moves and drops Asia to US moves', async () => { const context = await setup('us-central1') @@ -151,13 +147,5 @@ describe('rehome source-region filter', () => { await context.database.close() }) - it('reports the filtered hosts in the preview, agreeing with selection', async () => { - const context = await setup('us-central1') - const preview = await context.store.previewRegionalRehomeEligibility(context.safety()) - expect(preview.counts).toEqual({ - 'eligible:us-central1-to-asia-east2': 1, - 'source-outside-director-region': 1 - }) - await context.database.close() - }) + }) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-store.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-store.test.ts index 9b14e2a4764..dd0c445ed15 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-store.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-store.test.ts @@ -1,22 +1,12 @@ import { describe, expect, it } from 'vitest' -import { readAssignmentInventorySnapshot } from '../assignment-inventory-snapshot.js' -import { REGIONAL_REHOME_ARRIVAL_WINDOW_MS } from './regional-rehome-abort-reason.js' import { RelayAssignmentStore as BaseRelayAssignmentStore, - type RegionalRehomeAttempt, - REGIONAL_REHOME_QUARANTINE_FAILURES, - REGIONAL_REHOME_QUARANTINE_MS + type RegionalRehomeAttempt } from '../assignment-store.js' import { openInMemoryRelayDatabase, - type RelayDatabase, - type RelayLockOptions + type RelayDatabase } from '../../database/database.js' -import { - REGIONAL_REHOME_SQL_FAILURES_LIMIT, - REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT, - REGIONAL_REHOME_SQL_FAILURES_SUSTAIN_MS -} from './regional-rehome-safety.js' import type { RegionalRehomeSafetySnapshot } from '../../observability/relay-observability.js' const source = { @@ -35,129 +25,11 @@ const target = { connectionHardCap: 1_000 as const, connectionUnobservedBound: 60 } -// Bystander participates only in fleet safety. -const bystander = { ...source, id: 'us-c2', url: 'https://us-c2.relay.example.test' } const sourceIncarnation = '11111111-1111-4111-8111-111111111111' const targetIncarnation = '22222222-2222-4222-8222-222222222222' -const bystanderIncarnation = '33333333-3333-4333-8333-333333333333' describe('regional rehome assignment state', () => { - it('defaults optional correction off even with enabled durable control', async () => { - const context = await setup() - await activatePreferredSource(context, { userId: 'cohort', relayHostId: 'abcdefghijklmnop' }) - const defaultStore = new IdleRehomeTestStore(context.database, context.now, { - requireLiveCells: true - }) - expect(await defaultStore.tryIdleRehome()).toBeNull() - expect( - await context.database.query('SELECT attempt_id FROM relay_region_rehome_attempts') - ).toEqual([]) - expect(await context.store.tryIdleRehome()).not.toBeNull() - await context.database.close() - }) - - it('counts pre-existing generic migrations against the eight-migration cap', async () => { - const context = await setup() - await activatePreferredSource(context, { userId: 'cap', relayHostId: 'abcdefghijklmnop' }) - for (let i = 0; i < 8; i++) { - await context.database.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch, assignment_epoch, - source_request_units, target_reserved_units, expires_at, created_at, updated_at) - VALUES (?, ?, ?, ?, 1, 2, 1, 1, ?, ?, ?)`, - [ - 'generic', - `synthetic-migration-${i}`, - source.id, - target.id, - context.now() + 60_000, - context.now(), - context.now() - ] - ) - } - expect(await context.store.tryIdleRehome()).toBeNull() - await context.database.query( - `UPDATE relay_assignment_migrations SET completed_at = ? - WHERE user_id = 'generic' AND relay_host_id = 'synthetic-migration-0'`, - [context.now()] - ) - expect(await context.store.tryIdleRehome()).not.toBeNull() - const open = await context.database - .query(`SELECT COUNT(*) AS count FROM relay_assignment_migrations - WHERE completed_at IS NULL AND aborted_at IS NULL`) - expect(Number(open[0]?.count)).toBe(8) - await context.database.close() - }) - - it('does not let legacy hints certify a move', async () => { - const context = await setup() - await activatePreferredSource(context, { userId: 'legacy', relayHostId: 'abcdefghijklmnop' }) - await context.database.query('DELETE FROM relay_region_decisions') - expect(await context.store.tryIdleRehome()).toBeNull() - await context.database.close() - }) - - it('refreshes later open attempts when an older attempt occupies the first page', async () => { - const context = await setup() - await activatePreferredSource(context, { userId: 'page-1', relayHostId: 'abcdefghijklmnop' }) - const first = await context.store.tryIdleRehome() - context.advance(10_000) - await freshHeartbeats(context) - await activatePreferredSource(context, { userId: 'page-2', relayHostId: 'abcdefghijklmnop' }) - const second = await context.store.tryIdleRehome() - expect(second).not.toBeNull() - context.advance(1_000) - expect(await context.store.refreshRegionalRehomeLeases(1)).toBe(1) - context.advance(1_000) - expect(await context.store.refreshRegionalRehomeLeases(1)).toBe(1) - const rows = await context.database.query( - `SELECT attempt_id, updated_at FROM relay_region_rehome_attempts - WHERE attempt_id = ?`, - [second!.attemptId] - ) - expect(Number(rows[0]?.updated_at)).toBe(context.now()) - await context.database.close() - }) - - it('uses a generation-bound durable kill switch', async () => { - const context = await setup() - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true, - ratePerMinute: 10 - }) - expect(await context.store.disableRegionalRehomeControl()).toBe(true) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - await expect( - context.store.applyRegionalRehomeControl({ - expectedGeneration: 1, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60_000 - }) - ).rejects.toThrow('regional_rehome_generation_mismatch') - await expect( - context.store.applyRegionalRehomeControl({ - expectedGeneration: 2, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60_000 - }) - ).resolves.toMatchObject({ generation: 3, enabled: true }) - await context.database.close() - }) - it('moves one live preferred host and completes without disabling its source cell', async () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } @@ -220,863 +92,6 @@ describe('regional rehome assignment state', () => { await context.database.close() }) - it('requires an advertised source capability', async () => { - const context = await setup({ sourceProtocol: 0 }) - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - expect(await context.store.tryIdleRehome()).toBeNull() - expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await context.database.close() - }) - - it('claims through the measured healthy baseline of pool micro-waits and churn', async () => { - const context = await setup() - const baseline = { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 42, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 2, - databasePoolWaitersMax: 2, - databasePoolWaitMsMax: 1 - } - await heartbeat(context.store, source, sourceIncarnation, 3, 2, baseline) - await heartbeat(context.store, target, targetIncarnation, 3, 2, baseline) - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - - expect(await context.store.tryIdleRehome()).toMatchObject({ - sourceCellId: source.id, - targetCellId: target.id - }) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - enabled: true - }) - await context.database.close() - }) - - it('latches off on a per-cell reconnect storm even when the fleet sum is low', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - const safety: RegionalRehomeSafetySnapshot = { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety) - expect(candidate).toBeDefined() - await context.database.query( - `UPDATE relay_cell_rehome_safety SET reconnects = 251 WHERE cell_id = ?`, - [source.id] - ) - - const warnings = collectDisableWarnings() - try { - expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({ - outcome: 'deferred', - reason: 'fleet-safety' - }) - } finally { - warnings.restore() - } - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - expect(warnings.entries).toMatchObject([ - { reason: 'elevated_reconnects', maxReconnects: 251, controlGeneration: 2 } - ]) - await context.database.close() - }) - - it('defers on target pool pressure without disabling, and claims once it clears', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - const safety: RegionalRehomeSafetySnapshot = { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety) - expect(candidate).toBeDefined() - await context.database.query( - `UPDATE relay_cell_rehome_safety SET database_pool_waiters_max = 17 WHERE cell_id = ?`, - [target.id] - ) - - const warnings = collectDisableWarnings() - try { - expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({ - outcome: 'deferred', - reason: 'candidate-ineligible' - }) - } finally { - warnings.restore() - } - // A scan-to-commit pool breach must skip without permanently disabling the worker. - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true - }) - expect(warnings.entries).toEqual([]) - - await context.database.query( - `UPDATE relay_cell_rehome_safety SET database_pool_waiters_max = 0 WHERE cell_id = ?`, - [target.id] - ) - expect(await context.store.tryIdleRehome()).toMatchObject({ - userId: 'user-1', - sourceCellId: source.id, - targetCellId: target.id - }) - await context.database.close() - }) - - it('keeps selecting candidates while an unrelated cell is over the pool bar', async () => { - // Fleet Math.max once let one narrow client pool empty every page. - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - await context.store.reconcileCells([source, target, bystander]) - await heartbeat(context.store, bystander, bystanderIncarnation, 3, 2, { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 150, - databasePoolWaitersMax: 150, - databasePoolWaitMsMax: 2_005 - }) - - const safety: RegionalRehomeSafetySnapshot = { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - expect(await context.store.selectIdleRegionalRehomeCandidates(safety)).toMatchObject([ - { sourceCellId: source.id, targetCellId: target.id } - ]) - await context.database.close() - }) - - it('claims through ambient per-cell sql retry noise', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - await context.database.query( - `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT}` - ) - - expect(await context.store.tryIdleRehome()).not.toBeNull() - await context.database.close() - }) - - it('moves a live host on an asia-east2 cell back to its preferred us-central1 cell', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activateReversePreferredSource(context, identity) - - const attempt = await context.store.tryIdleRehome() - expect(attempt).toMatchObject({ - userId: identity.userId, - relayHostId: identity.relayHostId, - preferredRegion: 'us-central1', - sourceCellId: target.id, - sourceCellIncarnation: targetIncarnation, - targetCellId: source.id, - targetCellIncarnation: sourceIncarnation, - previousEpoch: 1, - assignmentEpoch: 2, - sendAttempts: 1 - }) - expect( - await context.database.query( - `SELECT preferred_region, source_cell_id, target_cell_id - FROM relay_region_rehome_attempts` - ) - ).toEqual([ - { - preferred_region: 'us-central1', - source_cell_id: target.id, - target_cell_id: source.id - } - ]) - expect(await context.store.resolve(identity)).toMatchObject({ cellId: source.id }) - await context.database.close() - }) - - it('drops a candidate at scan time when no cell in the preferred region is usable', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - // Exclude certain skips during selection or they consume candidate-page slots. - await context.database.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [ - target.id - ]) - - const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') - try { - expect(await context.store.tryIdleRehome()).toBeNull() - } finally { - warnings.restore() - } - expect(warnings.entries).toEqual([]) - expect( - await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) - ).toEqual([{ next_dispatch_at: 0 }]) - expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await context.database.close() - }) - - it('does not migrate when the last target is lost between selection and commit', async () => { - const database = await openInMemoryRelayDatabase() - const context = await setup({ - database, - wrap: (delegate) => - hookAfterCandidateScan(delegate, async (transaction) => { - await transaction.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [ - target.id - ]) - }) - }) - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - - expect(await context.store.tryIdleRehome()).toBeNull() - - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true - }) - expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await database.close() - }) - - it('leaves a host alone until its cooldown expires, then moves it back', async () => { - const context = await setup({ hostCooldownMs: 3 * 24 * 60 * 60_000 }) - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const targetControl = await completeRehomeToTarget(context, identity) - // Pass dispatch interval so only cooldown prevents another claim. - context.advance(10_000) - await activateReversePreferredSource(context, identity) - - const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') - try { - expect(await context.store.tryIdleRehome()).toBeNull() - } finally { - warnings.restore() - } - expect(warnings.entries).toEqual([]) - expect(await context.store.resolve(identity)).toMatchObject({ cellId: target.id }) - - context.advance(3 * 24 * 60 * 60_000) - await freshHeartbeats(context) - await context.store.renewControlActivity(identity, { - activityId: targetControl, - cellId: target.id, - expiresAt: context.now() + 90_000 - }) - await activateReversePreferredSource(context, identity) - - const attempt = await context.store.tryIdleRehome() - expect(attempt).toMatchObject({ - preferredRegion: 'us-central1', - sourceCellId: target.id, - targetCellId: source.id - }) - await context.database.close() - }) - - it('rejects a host whose attempt lands between the scan and the claim', async () => { - const database = await openInMemoryRelayDatabase() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const context = await setup({ - database, - wrap: (delegate) => - hookAfterCandidateScan(delegate, async (transaction) => { - await transaction.query( - `INSERT INTO relay_region_rehome_attempts - (attempt_id, user_id, relay_host_id, preferred_region, source_cell_id, - source_cell_incarnation, target_cell_id, target_cell_incarnation, - previous_epoch, assignment_epoch, drain_grace_ms, send_attempts, - created_at, updated_at) - VALUES ('raced', ?, ?, 'asia-east2', ?, ?, ?, ?, 0, 1, 0, 0, ?, ?)`, - [ - identity.userId, - identity.relayHostId, - source.id, - sourceIncarnation, - target.id, - targetIncarnation, - context.now(), - context.now() - ] - ) - }) - }) - await activatePreferredSource(context, identity) - - expect(await context.store.tryIdleRehome()).toBeNull() - - expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await database.close() - }) - - it('does not scan a candidate whose preferred region has no drainable cell', async () => { - // Without drain protocol the target could never rehome hosts back out; exclude before inventory scans. - const context = await setup({ targetProtocol: 0 }) - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - - const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') - try { - expect(await context.store.tryIdleRehome()).toBeNull() - } finally { - warnings.restore() - } - expect(warnings.entries).toEqual([]) - expect( - await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) - ).toEqual([{ next_dispatch_at: 0 }]) - expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await context.database.close() - }) - - it('skips an unclean cell without latching the control off', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - await activatePreferredSource(context, { - userId: 'user-2', - relayHostId: 'ponmlkjihgfedcba' - }) - // Per-cell bar can skip a candidate while fleet safety keeps the worker enabled. - await context.database.query( - `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT + 1} WHERE cell_id = ?`, - [target.id] - ) - - expect(await context.store.tryIdleRehome()).toBeNull() - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true - }) - - expect( - await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) - ).toEqual([{ next_dispatch_at: 0 }]) - expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await context.database.close() - }) - - it('pauses the claim without latching when a sql spike lands between selection and commit', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - const safety: RegionalRehomeSafetySnapshot = { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety) - expect(candidate).toBeDefined() - await context.database.query( - `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1} WHERE cell_id = ?`, - [target.id] - ) - - expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({ - outcome: 'deferred', - reason: 'fleet-safety' - }) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true - }) - expect( - await context.database.query( - `SELECT consecutive_failures FROM relay_region_rehome_worker_state` - ) - ).toEqual([{ consecutive_failures: 0 }]) - expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - await context.database.close() - }) - - it('rides out a single-stall sql spike without latching the control off', async () => { - const context = await setup() - // 10-06 06:16Z: one stall put the fleet sum at 396 for about a minute. - for (let elapsed = 0; elapsed <= 90_000; elapsed += 6_000) { - await sqlFailuresHeartbeats(context, 396) - expect(await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))).toEqual( - [] - ) - context.advance(6_000) - } - await sqlFailuresHeartbeats(context, 0) - await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) - expect( - await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context)) - ).toHaveLength(1) - // The next stall, ~610 s later, starts its own breach rather than extending the last one. - context.advance(500_000) - for (let elapsed = 0; elapsed <= 90_000; elapsed += 6_000) { - await sqlFailuresHeartbeats(context, 396) - await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context)) - context.advance(6_000) - } - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true - }) - await context.database.close() - }) - - it('latches the control off when the sql breach outlasts a stall', async () => { - const context = await setup() - await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) - const warnings = collectEventWarnings('orca_relay_regional_rehome_safety_disabled') - try { - for (let elapsed = 0; elapsed < REGIONAL_REHOME_SQL_FAILURES_SUSTAIN_MS; elapsed += 6_000) { - await sqlFailuresHeartbeats(context, REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1) - await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context)) - context.advance(6_000) - } - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ enabled: true }) - await sqlFailuresHeartbeats(context, REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1) - expect(await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))).toEqual( - [] - ) - } finally { - warnings.restore() - } - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - expect(warnings.entries).toMatchObject([ - { reason: 'sql_failures', controlGeneration: 2, sustainedMs: 150_000 } - ]) - await context.database.close() - }) - - it('still latches on a non-sql reason that fails alongside a sql spike', async () => { - const context = await setup() - await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) - const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context)) - expect(candidate).toBeDefined() - await context.database.query( - `UPDATE relay_cell_rehome_safety - SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1}, control_activity_recovery_failures = 1 - WHERE cell_id = ?`, - [target.id] - ) - expect(await context.store.commitIdleRegionalRehome(candidate!, cleanSafety(context))).toEqual({ - outcome: 'deferred', - reason: 'fleet-safety' - }) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - await context.database.close() - }) - - it('refreshes only the migration leases while source splices drain', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - await context.store.acquireActivity(identity, { - activityId: 'splice:source', - kind: 'splice', - cellId: source.id - }) - await context.store.tryIdleRehome() - const before = await context.database.query( - `SELECT activity_id, expires_at FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`, - [identity.userId, identity.relayHostId] - ) - context.advance(60_000) - expect(await context.store.refreshRegionalRehomeLeases()).toBe(1) - const after = await context.database.query( - `SELECT activity_id, expires_at FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`, - [identity.userId, identity.relayHostId] - ) - const beforeById = new Map(before.map((row) => [row.activity_id, row.expires_at])) - const afterById = new Map(after.map((row) => [row.activity_id, row.expires_at])) - expect(Number(afterById.get('migration:2'))).toBeGreaterThan( - Number(beforeById.get('migration:2')) - ) - expect(Number(afterById.get('control-pending:2'))).toBeGreaterThan( - Number(beforeById.get('control-pending:2')) - ) - expect(afterById.get('splice:source')).toBe(beforeById.get('splice:source')) - await context.database.close() - }) - - it('stops refreshing an unregistered target and lets normal rollback retire it', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - await context.store.tryIdleRehome() - context.advance(6 * 60_000) - expect(await context.store.refreshRegionalRehomeLeases()).toBe(0) - await heartbeat(context.store, source, sourceIncarnation, 3, 2) - expect(await context.store.abortExpiredEvacuations()).toBe(1) - expect(await context.store.reapRegionalRehomeAttempts()).toBe(0) - expect(await context.store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 3 - }) - expect( - await context.database.query( - `SELECT completed_at, aborted_at FROM relay_region_rehome_attempts` - ) - ).toEqual([{ completed_at: null, aborted_at: context.now() }]) - await context.database.close() - }) - - it('does not roll an unregistered target back to a stale regional source', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - await context.store.tryIdleRehome() - context.advance(6 * 60_000) - await heartbeat(context.store, target, targetIncarnation, 3, 2) - - expect(await context.store.refreshRegionalRehomeLeases()).toBe(0) - expect(await context.store.abortExpiredEvacuations()).toBe(0) - expect( - await context.database.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: target.id, assignment_epoch: 2 }]) - await context.database.close() - }) - - // Two contended candidates expose an erroneous break; the redrain lane reaches inventory through its separate fleet-safety read. - it('completes a candidate behind two contended ones', async () => { - const probe = new CellInventoryLockProbe() - const context = await setup({ wrap: (database) => probe.wrap(database) }) - const identities = [ - { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, - { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' }, - { userId: 'user-3', relayHostId: 'aaaabbbbccccdddd' } - ] - for (const identity of identities) { - // Dispatch is rate limited, so each claim needs its own interval. - context.advance(60_000) - await freshHeartbeats(context) - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.store.releaseActivity(identity, sourceControl) - } - probe.reset() - probe.failNoWaitTimes = 2 - const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') - - let completed: number - try { - completed = await context.store.completeReadyRegionalRehomes() - } finally { - busy.restore() - } - - expect(completed).toBe(1) - expect(busy.entries).toEqual([ - { - event: 'orca_relay_sweep_cell_inventory_busy', - sweep: 'complete-ready-regional-rehomes', - skipped: 2 - } - ]) - await context.database.close() - }) - - // Only inventory contention is ordinary; other failures must propagate and count against dispatch. - - // One inventory failure abandons the transaction’s whole candidate page, so count all candidates skipped. - - it('skips a completion tick on a contended cell inventory without quarantining it', async () => { - const probe = new CellInventoryLockProbe() - const context = await setup({ wrap: (database) => probe.wrap(database) }) - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.store.releaseActivity(identity, sourceControl) - probe.reset() - probe.failNoWait = true - const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') - const failures = collectCandidateFailureWarnings() - - let completed: number - try { - completed = await context.store.completeReadyRegionalRehomes() - } finally { - failures.restore() - busy.restore() - } - - expect(completed).toBe(0) - expect(probe.locks).not.toEqual([]) - expect(probe.locks.every((options) => options?.failIfUnavailable === true)).toBe(true) - expect(failures.entries).toEqual([]) - expect(busy.entries).toEqual([ - { - event: 'orca_relay_sweep_cell_inventory_busy', - sweep: 'complete-ready-regional-rehomes', - skipped: 1 - } - ]) - - probe.failNoWait = false - expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - await context.database.close() - }) - - // Inventory contention is temporary; quarantining it would hide healthy attempts from LIMIT pages for 15min. - it('skips an abort tick on a contended cell inventory without quarantining it', async () => { - const probe = new CellInventoryLockProbe() - const context = await setup({ wrap: (database) => probe.wrap(database) }) - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - const targetControl = await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.store.releaseActivity(identity, sourceControl) - await context.store.releaseActivity(identity, targetControl) - context.advance(24 * 60 * 60_000) - await heartbeat(context.store, source, sourceIncarnation, 3, 2) - probe.reset() - probe.failNoWait = true - const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') - const failures = collectCandidateFailureWarnings() - - let aborted: number - try { - aborted = await context.store.abortExpiredRegionalRehomes() - } finally { - failures.restore() - busy.restore() - } - - expect(aborted).toBe(0) - expect(probe.locks).not.toEqual([]) - expect(probe.locks.every((options) => options?.failIfUnavailable === true)).toBe(true) - expect(failures.entries).toEqual([]) - expect(busy.entries).toEqual([ - { - event: 'orca_relay_sweep_cell_inventory_busy', - sweep: 'abort-expired-regional-rehomes', - skipped: 1 - } - ]) - - probe.failNoWait = false - expect(await context.store.abortExpiredRegionalRehomes()).toBe(1) - await context.database.close() - }) - - it('rolls a host that never reached its target back to the source at the arrival window', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - expect(await context.store.tryIdleRehome()).not.toBeNull() - await context.store.releaseActivity(identity, sourceControl) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - - context.advance(REGIONAL_REHOME_ARRIVAL_WINDOW_MS - 1) - await freshHeartbeats(context) - expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(0) - - context.advance(1) - await freshHeartbeats(context) - expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(1) - expect(await context.store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 3 - }) - expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(0) - await context.database.close() - }) - - it('leaves the durable switch alone when it rolls back an unarrived host', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - expect(await context.store.tryIdleRehome()).not.toBeNull() - await context.store.releaseActivity(identity, sourceControl) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - const before = await context.store.inspectRegionalRehomeControl() - context.advance(REGIONAL_REHOME_ARRIVAL_WINDOW_MS) - await freshHeartbeats(context) - - expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(1) - - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: before.generation, - enabled: true - }) - const [attempt] = await context.database.query( - 'SELECT abort_reason FROM relay_region_rehome_attempts' - ) - expect(attempt!.abort_reason).toBe('host_not_arrived') - const preview = await context.store.previewRegionalRehomeEligibility() - expect(preview.abortedLast24Hours).toEqual({ host_not_arrived: 1 }) - expect( - (await readAssignmentInventorySnapshot(context.database, context.now())).regionalRehomes - ).toMatchObject({ abortedLast24Hours: 1, hostNotArrivedLast24Hours: 1 }) - await context.database.close() - }) - - it('leaves a host that did reach its target for the completion sweep', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - expect(await context.store.tryIdleRehome()).not.toBeNull() - // Age alone cannot abort an attempt whose target already owns the host. - context.advance(REGIONAL_REHOME_ARRIVAL_WINDOW_MS) - await freshHeartbeats(context) - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1, - cellIncarnation: targetIncarnation - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.store.releaseActivity(identity, sourceControl) - - expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(0) - expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - expect(await context.store.resolve(identity)).toMatchObject({ cellId: target.id }) - await context.database.close() - }) - - it('names the 24-hour latch in its own abort reason', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - expect(await context.store.tryIdleRehome()).not.toBeNull() - await context.store.releaseActivity(identity, sourceControl) - context.advance(24 * 60 * 60_000) - await heartbeat(context.store, source, sourceIncarnation, 3, 2) - - expect(await context.store.abortExpiredRegionalRehomes()).toBe(1) - - const [attempt] = await context.database.query( - 'SELECT abort_reason FROM relay_region_rehome_attempts' - ) - expect(attempt!.abort_reason).toBe('max_refresh_expired') - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ enabled: false }) - await context.database.close() - }) - - it('rolls back an inactive registered target only after the 24-hour bound', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - const targetControl = await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.store.releaseActivity(identity, sourceControl) - await context.store.releaseActivity(identity, targetControl) - context.advance(24 * 60 * 60_000 - 1) - await freshHeartbeats(context) - expect(await context.store.abortExpiredRegionalRehomes()).toBe(0) - context.advance(1) - await heartbeat(context.store, source, sourceIncarnation, 3, context.now()) - expect(await context.store.abortExpiredRegionalRehomes()).toBe(1) - expect(await context.store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 3 - }) - await context.database.close() - }) - it('completes healthy candidates past a poisoned attempt and logs it', async () => { const context = await setup() const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } @@ -1132,300 +147,11 @@ describe('regional rehome assignment state', () => { await context.database.close() }) - it('quarantines a repeatedly failing candidate and redacts free-form errors', async () => { - const context = await setup() - const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const source1 = await activatePreferredSource(context, poisoned) - const attempt = await context.store.tryIdleRehome() - await context.store.activateControl(poisoned, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(poisoned, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch - }) - await context.store.releaseActivity(poisoned, source1) - await context.database.query( - `UPDATE relay_assignments SET assignment_epoch = assignment_epoch + 5 - WHERE user_id = ?`, - [poisoned.userId] - ) - const warnings = collectCandidateFailureWarnings() - try { - for (let round = 0; round < REGIONAL_REHOME_QUARANTINE_FAILURES; round++) { - expect(await context.store.completeReadyRegionalRehomes()).toBe(0) - } - expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES) - expect(await context.store.completeReadyRegionalRehomes()).toBe(0) - expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES) - context.advance(REGIONAL_REHOME_QUARANTINE_MS + 1) - await context.store.completeReadyRegionalRehomes() - expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES + 1) - expect( - warnings.entries.every((entry) => entry.reason === 'regional_rehome_assignment_mismatch') - ).toBe(true) - context.advance(REGIONAL_REHOME_QUARANTINE_MS + 1) - const database = context.database - const original = database.transaction.bind(database) - database.transaction = () => { - throw new Error('postgresql://secret@database.invalid/relay') - } - try { - await context.store.completeReadyRegionalRehomes() - } finally { - database.transaction = original - } - const last = warnings.entries.at(-1)! - expect(last.reason).toBe('redacted') - expect(JSON.stringify(last)).not.toContain('secret') - } finally { - warnings.restore() - } - await context.database.close() - }) - it('aborts healthy expired candidates past a poisoned attempt', async () => { - const context = await setup() - const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const healthy = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' } - const poisonedSource = await activatePreferredSource(context, poisoned) - const healthySource = await activatePreferredSource(context, healthy) - const first = await context.store.tryIdleRehome() - context.advance(6_000) - const second = await context.store.tryIdleRehome() - for (const [identity, attempt, sourceControl] of [ - [poisoned, first, poisonedSource], - [healthy, second, healthySource] - ] as const) { - const targetControl = await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch - }) - await context.store.releaseActivity(identity, sourceControl) - await context.store.releaseActivity(identity, targetControl) - } - await context.database.query( - `UPDATE relay_assignments SET assignment_epoch = assignment_epoch + 5 - WHERE user_id = ?`, - [poisoned.userId] - ) - context.advance(24 * 60 * 60_000) - await freshHeartbeats(context) - const warnings = collectCandidateFailureWarnings() - try { - expect(await context.store.abortExpiredRegionalRehomes()).toBe(1) - } finally { - warnings.restore() - } - expect(warnings.entries).toEqual([ - { - event: 'orca_relay_regional_rehome_candidate_failed', - operation: 'abort', - attemptId: first!.attemptId, - reason: 'regional_rehome_assignment_mismatch' - } - ]) - expect( - await context.database.query( - `SELECT aborted_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [second!.attemptId] - ) - ).toEqual([{ aborted_at: context.now() }]) - await context.database.close() - }) - - it('keeps dual-control accounting when the drained host re-resolves mid-rehome', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - expect(await controlAccounting(context, identity)).toEqual({ - reservedControls: 2, - controlLeases: 2 - }) - - // The drained host re-resolves through the director while both the source - // control and the target's pending control are still live. - await context.store.assign(identity, 'asia-east2') - expect(await controlAccounting(context, identity)).toEqual({ - reservedControls: 2, - controlLeases: 2 - }) - - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch - }) - await context.store.releaseActivity(identity, sourceControl) - expect(await controlAccounting(context, identity)).toEqual({ - reservedControls: 1, - controlLeases: 1 - }) - - expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - expect( - await context.database.query( - `SELECT completed_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ completed_at: context.now() }]) - expect(await cellReservations(context)).toEqual({ [source.id]: 0, [target.id]: 1 }) - await context.database.close() - }) - - it('grants a host whose counter was skewed without duplicating its control', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.releaseActivity(identity, sourceControl) - // Damage already written by a pre-fix sticky grant. - await context.database.query( - `UPDATE relay_assignments SET reserved_controls = 0 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - - await context.store.assign(identity, 'asia-east2') - expect( - await context.database.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'control'`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ activity_id: `control:${target.id}:1` }]) - expect(await cellReservations(context)).toEqual({ [source.id]: 0, [target.id]: 2 }) - await context.database.close() - }) - - it('repairs a skewed control counter before completing the rehome', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch - }) - await context.store.releaseActivity(identity, sourceControl) - // Damage already written by a pre-fix sticky grant. - await context.database.query( - `UPDATE relay_assignments SET reserved_controls = 0 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - - expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - expect(await controlAccounting(context, identity)).toEqual({ - reservedControls: 1, - controlLeases: 1 - }) - expect( - await context.database.query( - `SELECT migration_leases FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ migration_leases: 0 }]) - await context.database.close() - }) - - it('never repairs past a migration lease whose shape is wrong', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch - }) - await context.store.releaseActivity(identity, sourceControl) - await context.database.query( - `UPDATE relay_assignments SET reserved_controls = 0 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await context.database.query( - `UPDATE relay_assignment_migrations SET target_reserved_units = 9 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - - const warnings = collectCandidateFailureWarnings() - try { - expect(await context.store.completeReadyRegionalRehomes()).toBe(0) - } finally { - warnings.restore() - } - expect(warnings.entries).toEqual([ - { - event: 'orca_relay_regional_rehome_candidate_failed', - operation: 'complete', - attemptId: attempt!.attemptId, - reason: 'migration_activity_lease_shape_mismatch' - } - ]) - expect(await controlAccounting(context, identity)).toEqual({ - reservedControls: 0, - controlLeases: 1 - }) - await context.database.close() - }) }) type Context = Awaited> -function collectDisableWarnings() { - const entries: Record[] = [] - const original = console.warn - console.warn = (line: unknown, ...rest: unknown[]) => { - try { - const parsed = JSON.parse(line as string) as Record - if (parsed.event === 'orca_relay_regional_rehome_safety_disabled') { - entries.push(parsed) - return - } - } catch { - // fall through to the real console for non-JSON lines - } - original(line, ...rest) - } - return { - entries, - restore: () => { - console.warn = original - } - } -} - async function setup( options: { sourceProtocol?: number @@ -1466,29 +192,6 @@ async function setup( } } -function collectEventWarnings(event: string) { - const entries: Record[] = [] - const original = console.warn - console.warn = (line: unknown, ...rest: unknown[]) => { - try { - const parsed = JSON.parse(line as string) as Record - if (parsed.event === event) { - entries.push(parsed) - return - } - } catch { - // fall through to the real console for non-JSON lines - } - original(line, ...rest) - } - return { - entries, - restore: () => { - console.warn = original - } - } -} - function collectCandidateFailureWarnings( events: string[] = ['orca_relay_regional_rehome_candidate_failed'] ) { @@ -1514,76 +217,6 @@ function collectCandidateFailureWarnings( } } -async function controlAccounting( - context: Context, - identity: { userId: string; relayHostId: string } -): Promise<{ reservedControls: number; controlLeases: number }> { - const assignment = ( - await context.database.query( - `SELECT reserved_controls FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - )[0]! - const leases = await context.database.query( - `SELECT COUNT(*) AS controls FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'control'`, - [identity.userId, identity.relayHostId] - ) - return { - reservedControls: Number(assignment.reserved_controls), - controlLeases: Number(leases[0]!.controls) - } -} - -async function cellReservations(context: Context): Promise> { - const rows = await context.database.query( - `SELECT cell_id, reserved_requests FROM relay_cells ORDER BY cell_id` - ) - return Object.fromEntries(rows.map((row) => [String(row.cell_id), Number(row.reserved_requests)])) -} - -async function freshHeartbeats(context: Context): Promise { - const safety = { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - // The clock doubles as a strictly-increasing connection inclusion watermark. - await heartbeat(context.store, source, sourceIncarnation, 3, context.now(), safety) - await heartbeat(context.store, target, targetIncarnation, 3, context.now(), safety) -} - -function cleanSafety(context: Context): RegionalRehomeSafetySnapshot { - return { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } -} - -// Splits the fleet sum across both cells, each under the per-cell bar's scale. -async function sqlFailuresHeartbeats(context: Context, fleetSqlFailures: number): Promise { - const half = Math.floor(fleetSqlFailures / 2) - const safety = cleanSafety(context) - await heartbeat(context.store, source, sourceIncarnation, 3, context.now(), { - ...safety, - sqlFailures: half - }) - await heartbeat(context.store, target, targetIncarnation, 3, context.now(), { - ...safety, - sqlFailures: fleetSqlFailures - half - }) -} - async function activatePreferredSource( context: Context, identity: { userId: string; relayHostId: string } @@ -1618,88 +251,6 @@ async function activatePreferredSource( return control } -// Hook after scan inside the claim transaction makes scan/claim races deterministic. -function hookAfterCandidateScan( - database: RelayDatabase, - hook: (transaction: RelayDatabase) => Promise -): RelayDatabase { - let fired = false - const decorate = (delegate: RelayDatabase): RelayDatabase => ({ - dialect: delegate.dialect, - query: async (sql, params) => { - const rows = await delegate.query(sql, params) - if (!fired && sql.includes('SELECT d.user_id, d.relay_host_id')) { - fired = true - await hook(delegate) - } - return rows - }, - queryLocked: async (sql, params, lockOptions) => - await delegate.queryLocked(sql, params, lockOptions), - transaction: async (operation, transactionOptions) => - await delegate.transaction( - async (transaction) => await operation(decorate(transaction)), - transactionOptions - ), - close: async () => undefined - }) - return decorate(database) -} - -async function completeRehomeToTarget( - context: Context, - identity: { userId: string; relayHostId: string } -): Promise { - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.tryIdleRehome() - const targetControl = await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: attempt!.assignmentEpoch - }) - await context.store.releaseActivity(identity, sourceControl) - await context.store.completeReadyRegionalRehomes() - return targetControl -} - -async function activateReversePreferredSource( - context: Context, - identity: { userId: string; relayHostId: string } -): Promise { - const assignment = await context.store.assign(identity, undefined, 'asia-east2') - const control = await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1, - idleRegionalRehome: true, - cellIncarnation: targetIncarnation - }) - await context.store.assign(identity, 'us-central1') - const issued = await context.store.exchangeRegionCorrection( - identity, - { v: 1, action: 'issue-window' }, - assignment.assignmentEpoch - ) - await context.store.exchangeRegionCorrection( - identity, - { - v: 1, - action: 'report', - generation: issued.window!.generation, - assignmentEpoch: assignment.assignmentEpoch, - policyVersion: 1, - outcome: 'conclusive', - measurements: { 'us-central1': 50, 'asia-east2': 150 } - }, - assignment.assignmentEpoch - ) - return control -} - async function activateSource( context: Context, identity: { userId: string; relayHostId: string } @@ -1752,51 +303,6 @@ async function heartbeat( }) } -class CellInventoryLockProbe { - readonly locks: (RelayLockOptions | undefined)[] = [] - failNoWait = false - // Contends the first N candidates only, so the sweep must carry on past them. - failNoWaitTimes = 0 - failWith: Error | null = null - - reset(): void { - this.locks.length = 0 - } - - wrap(database: RelayDatabase): RelayDatabase { - const probe = this - const decorate = (delegate: RelayDatabase): RelayDatabase => ({ - dialect: delegate.dialect, - query: async (sql, params) => await delegate.query(sql, params), - queryLocked: async (sql, params, options) => { - // The idle commit's only cell lock is its target row, so it counts too. - if ( - sql.trim() === 'SELECT * FROM relay_cells ORDER BY cell_id ASC' || - sql.includes('FROM relay_cells cell') - ) { - probe.locks.push(options) - if (probe.failWith) throw probe.failWith - if (options?.failIfUnavailable && probe.failNoWaitTimes > 0) { - probe.failNoWaitTimes-- - throw new Error('database_lock_unavailable') - } - if (probe.failNoWait && options?.failIfUnavailable) { - throw new Error('database_lock_unavailable') - } - } - return await delegate.queryLocked(sql, params, options) - }, - transaction: async (operation, options) => - await delegate.transaction( - async (transaction) => await operation(decorate(transaction)), - options - ), - close: async () => undefined - }) - return decorate(database) - } -} - class IdleRehomeTestStore extends BaseRelayAssignmentStore { private readonly fixtureDatabase: RelayDatabase private readonly fixtureNow: () => number diff --git a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-row-lock-postgres.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-row-lock-postgres.test.ts index 0517a7c3cf6..d7c67cb196f 100644 --- a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-row-lock-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-row-lock-postgres.test.ts @@ -1,7 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' import { RelayAssignmentStore } from '../assignment-store.js' import { - consumeRelayCellInventoryHold, openRelayDatabase, type PostgresDatabase, type RelayDatabase @@ -18,21 +17,6 @@ const describePostgres = databaseUrl ? describe : describe.skip // Roughly the round trip from an Asia cell to the us-central1 database. const STATEMENT_DELAY_MS = 150 -// Probe the formerly fleet-locked tables plus admission/region tables read by commit. -const CELL_TABLES = [ - 'relay_cells', - 'relay_cell_runtime', - 'relay_cell_capabilities', - 'relay_cell_rehome_safety', - 'relay_cell_admission', - 'relay_cell_regions' -] as const - -// The target-row statement locks exactly these, held from it to COMMIT. -const TARGET_LOCKED = ['target:relay_cells', 'target:relay_cell_admission'] - -type Trip = { sql: string; lockable: Record; probeMs: number } - type DelayControl = StatementDelay & { beforeTrip: (sql: string) => Promise } describePostgres('PostgreSQL regional rehome target-row lock', () => { @@ -97,27 +81,6 @@ describePostgres('PostgreSQL regional rehome target-row lock', () => { } } - async function lockable(table: string, cellId: string): Promise { - try { - await observer.transaction( - async (transaction) => { - await transaction.queryLocked( - `SELECT cell_id FROM ${table} WHERE cell_id = ?`, - [cellId], - { - failIfUnavailable: true - } - ) - }, - { reportRetries: false } - ) - return true - } catch (error) { - if (error instanceof Error && error.message === 'database_lock_unavailable') return false - throw error - } - } - async function reservedRequests(cellId: string): Promise { const row = ( await primary.query(`SELECT reserved_requests FROM relay_cells WHERE cell_id = ?`, [cellId]) @@ -152,59 +115,6 @@ describePostgres('PostgreSQL regional rehome target-row lock', () => { ) } - it('holds only the target cell and admission rows until the next COMMIT boundary', async () => { - const context = await fixture() - const request = await context.select() - const trips: Trip[] = [] - const probed = { - source: context.source.id, - target: context.target.id, - bystander: context.bystander.id - } - control.beforeTrip = async (sql) => { - const probeStartedAt = performance.now() - const state: Record = {} - for (const [role, cellId] of Object.entries(probed)) { - for (const table of CELL_TABLES) state[`${role}:${table}`] = await lockable(table, cellId) - } - trips.push({ sql, lockable: state, probeMs: performance.now() - probeStartedAt }) - } - consumeRelayCellInventoryHold(delayed) - control.enabled = true - - const result = await context.delayedStore.commitIdleRegionalRehome(request, context.safety()) - control.enabled = false - - expect(result).toEqual({ outcome: 'committed' }) - expect(trips.length).toBeGreaterThanOrEqual(15) - expect(trips[trips.length - 1]!.sql).toBe('COMMIT') - for (const trip of trips) { - for (const [key, free] of Object.entries(trip.lockable)) { - if (TARGET_LOCKED.includes(key)) continue - expect({ sql: trip.sql, key, free }).toEqual({ sql: trip.sql, key, free: true }) - } - } - for (const key of TARGET_LOCKED) { - expect(trips.filter((trip) => !trip.lockable[key]).map((trip) => trip.sql)).toEqual([ - 'COMMIT' - ]) - } - const counts = consumeRelayCellInventoryHold(delayed) - const commitProbeMs = trips.at(-1)!.probeMs - console.info( - JSON.stringify({ - event: 'rehome_target_row_hold', - trips: trips.length, - commitProbeMs, - ...counts - }) - ) - expect(counts.rehomeTargetRowHolds).toBe(1) - expect(counts.cellInventoryHoldMaxSite).toBe('rehome-target-row') - expect(counts.rehomeTargetRowHoldMsMax).toBeGreaterThanOrEqual(STATEMENT_DELAY_MS) - expect(await reservedRequests(context.target.id)).toBe(context.targetReservedBefore + 2) - }, 45_000) - it('defers when the target leaves general admission after selection', async () => { const context = await fixture() const request = await context.select() @@ -240,23 +150,14 @@ describePostgres('PostgreSQL regional rehome target-row lock', () => { }) await lockedPromise } - consumeRelayCellInventoryHold(delayed) control.enabled = true - const startedAt = performance.now() const result = await context.delayedStore.commitIdleRegionalRehome(request, context.safety()) - const elapsedMs = performance.now() - startedAt control.enabled = false release() await writer expect(result).toEqual({ outcome: 'deferred', reason: 'candidate-ineligible' }) - expect(consumeRelayCellInventoryHold(delayed)).toMatchObject({ - cellInventoryLockUnavailable: 1, - rehomeTargetRowHolds: 0 - }) - // NOWAIT: no 1s lock_timeout wait and no transaction retry behind the writer. - expect(elapsedMs).toBeLessThan(40 * STATEMENT_DELAY_MS) await expectNothingCommitted(context) }) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-selection.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-selection.test.ts deleted file mode 100644 index 75229b3cd4c..00000000000 --- a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-selection.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from '../assignment-store.js' -import { openInMemoryRelayDatabase } from '../../database/database.js' -import { REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT } from './regional-rehome-safety.js' - -const cell = (id: string, region: 'us-central1' | 'asia-east2') => ({ - id, - url: `https://${id}.relay.example.test`, - region, - capacityRequests: 100, - connectionHardCap: 1_000 as const, - connectionUnobservedBound: 60 -}) -const source = cell('us-c1', 'us-central1') -const noHeadroom = cell('asia-a', 'asia-east2') -const unclean = cell('asia-b', 'asia-east2') -const highLoad = cell('asia-c', 'asia-east2') -const lowLoad = cell('asia-d', 'asia-east2') - -const incarnation = (n: number) => - `${String(n).repeat(8)}-${String(n).repeat(4)}-4${String(n).repeat(3)}` + - `-8${String(n).repeat(3)}-${String(n).repeat(12)}` - -async function setup() { - let clock = 1_000_000 - const database = await openInMemoryRelayDatabase() - const store = new RelayAssignmentStore(database, () => clock, { - regionalRehomeCohortPercent: 100, - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - await store.inspectRegionalRehomeControl() - clock += 24 * 60 * 60_000 - await store.applyRegionalRehomeControl({ - expectedGeneration: 0, - enabled: true, - notBefore: clock, - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60 * 60_000 - }) - await store.reconcileCells([source, noHeadroom, unclean, highLoad, lowLoad]) - const beat = async ( - config: typeof source, - n: number, - protocol: number, - state: { observedRequests: number; enforcedConnections: number; sqlFailures: number } - ) => { - await store.recordCellHeartbeat({ - cellId: config.id, - cellUrl: config.url, - region: config.region, - cellIncarnation: incarnation(n), - startedAt: 900_000, - ready: true, - observedRequests: state.observedRequests, - totalConnections: state.enforcedConnections, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: state.enforcedConnections, - connectionInclusionWatermark: clock, - connectionHardCap: 1_000, - connectionUnobservedBound: 60 - }) - await store.recordCellRegionalRehomeStatus({ - cellId: config.id, - cellIncarnation: incarnation(n), - regionalRehomeProtocol: protocol, - safety: { - observedAt: clock, - sqlFailures: state.sqlFailures, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - }) - } - const activatePreferredSource = async () => { - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const assignment = await store.assign(identity, undefined, 'us-central1') - await store.activateControl(identity, { - cellId: source.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1, - idleRegionalRehome: true, - cellIncarnation: incarnation(1) - }) - const { window } = await store.exchangeRegionCorrection( - identity, - { v: 1, action: 'issue-window' }, - assignment.assignmentEpoch - ) - expect(window).toBeDefined() - await store.exchangeRegionCorrection( - identity, - { - v: 1, - action: 'report', - generation: window!.generation, - assignmentEpoch: assignment.assignmentEpoch, - policyVersion: 1, - outcome: 'conclusive', - measurements: { 'us-central1': 180, 'asia-east2': 40 } - }, - assignment.assignmentEpoch - ) - } - const safety = () => ({ - observedAt: clock, - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - }) - return { database, store, beat, activatePreferredSource, safety } -} - -const UNCLEAN = REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT + 1 - -describe('regional rehome target selection', () => { - it('never selects a target without connection headroom, even at lowest load', async () => { - const context = await setup() - await context.beat(source, 1, 3, { - observedRequests: 0, - enforcedConnections: 0, - sqlFailures: 0 - }) - // Lowest load but the connection hard cap is exhausted. - await context.beat(noHeadroom, 2, 3, { - observedRequests: 0, - enforcedConnections: 999, - sqlFailures: 0 - }) - await context.beat(unclean, 3, 3, { - observedRequests: 0, - enforcedConnections: 0, - sqlFailures: UNCLEAN - }) - await context.beat(highLoad, 4, 3, { - observedRequests: 50, - enforcedConnections: 0, - sqlFailures: 0 - }) - await context.beat(lowLoad, 5, 3, { - observedRequests: 10, - enforcedConnections: 0, - sqlFailures: 0 - }) - await context.activatePreferredSource() - - const candidates = await context.store.selectIdleRegionalRehomeCandidates(context.safety()) - const attempt = candidates[0] - expect(attempt?.targetCellId).toBe(lowLoad.id) - expect(await context.store.commitIdleRegionalRehome(attempt!, context.safety(), 100)).toEqual({ - outcome: 'committed' - }) - await context.database.close() - }) - - it('falls to the next clean target when the load winner goes unclean', async () => { - const context = await setup() - await context.beat(source, 1, 3, { - observedRequests: 0, - enforcedConnections: 0, - sqlFailures: 0 - }) - await context.beat(noHeadroom, 2, 3, { - observedRequests: 0, - enforcedConnections: 999, - sqlFailures: 0 - }) - await context.beat(unclean, 3, 3, { - observedRequests: 0, - enforcedConnections: 0, - sqlFailures: UNCLEAN - }) - await context.beat(highLoad, 4, 3, { - observedRequests: 50, - enforcedConnections: 0, - sqlFailures: 0 - }) - await context.beat(lowLoad, 5, 3, { - observedRequests: 10, - enforcedConnections: 0, - sqlFailures: UNCLEAN - }) - await context.activatePreferredSource() - - const candidates = await context.store.selectIdleRegionalRehomeCandidates(context.safety()) - const attempt = candidates[0] - expect(attempt?.targetCellId).toBe(highLoad.id) - expect(await context.store.commitIdleRegionalRehome(attempt!, context.safety(), 100)).toEqual({ - outcome: 'committed' - }) - await context.database.close() - }) -}) diff --git a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-worker.test.ts b/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-worker.test.ts deleted file mode 100644 index 3bb0b621dc9..00000000000 --- a/cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-worker.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RelayAssignmentStore } from '../assignment-store.js' -import type { RelayConfig } from '../../config.js' -import { startRegionalRehomeWorker } from './regional-rehome-worker.js' - -describe('regional rehome worker', () => { - afterEach(() => vi.restoreAllMocks()) - - it('bounds empty polling to the six-second cadence and stops its timer', async () => { - vi.useFakeTimers() - const selectIdleRegionalRehomeCandidates = vi.fn().mockResolvedValue([]) - const worker = startRegionalRehomeWorker( - config(), - { - selectIdleRegionalRehomeCandidates - } as unknown as RelayAssignmentStore, - { - safetySnapshot: () => safety(Date.now()), - random: () => 0 - } - )! - try { - await vi.advanceTimersByTimeAsync(0) - expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(5_999) - expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(2) - worker.stop() - await vi.advanceTimersByTimeAsync(60_000) - expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(2) - } finally { - worker.stop() - vi.useRealTimers() - } - }) - - it('stops walking the page when the source names a deferral no candidate can pass', async () => { - const fetchImpl = respondWith([{ outcome: 'deferred', reason: 'concurrency-limit' }]) - const summaries = collectSummaries() - try { - await runOnePoll(fetchImpl, 3, summaries) - } finally { - summaries.restore() - } - - expect(fetchImpl).toHaveBeenCalledTimes(1) - expect(summaries.entries).toEqual([ - { - event: 'orca_relay_idle_rehome_dispatch_summary', - candidates: 3, - dispatched: 1, - stoppedBy: 'concurrency-limit', - outcomes: { 'deferred:concurrency-limit': 1 } - } - ]) - }) - - it('keeps its whole-page walk when the source sends no reason at all', async () => { - const fetchImpl = respondWith([{ outcome: 'deferred' }]) - const summaries = collectSummaries() - try { - await runOnePoll(fetchImpl, 3, summaries) - } finally { - summaries.restore() - } - - expect(fetchImpl).toHaveBeenCalledTimes(3) - expect(summaries.entries[0]).toMatchObject({ - stoppedBy: null, - outcomes: { deferred: 3 } - }) - }) - - it('walks past a deferral that only concerns the one candidate', async () => { - const fetchImpl = respondWith([ - { outcome: 'deferred', reason: 'host-unsupported' }, - { outcome: 'busy' }, - { outcome: 'committed' } - ]) - const summaries = collectSummaries() - try { - await runOnePoll(fetchImpl, 4, summaries) - } finally { - summaries.restore() - } - - expect(fetchImpl).toHaveBeenCalledTimes(3) - expect(summaries.entries[0]).toMatchObject({ - dispatched: 3, - stoppedBy: 'committed', - outcomes: { 'deferred:host-unsupported': 1, busy: 1, committed: 1 } - }) - }) -}) - -function respondWith(bodies: { outcome: string; reason?: string }[]) { - let index = 0 - return vi.fn(async () => { - const body = bodies[Math.min(index++, bodies.length - 1)]! - return new Response(JSON.stringify({ v: 1, ...body }), { - headers: { 'content-type': 'application/json' } - }) - }) -} - -function collectSummaries() { - const entries: Record[] = [] - let arrived: (() => void) | undefined - // Construction immediately polls; await first instead of waiting for a timer tick. - const first = new Promise((resolve) => { - arrived = resolve - }) - const original = console.warn - console.warn = (line: unknown, ...rest: unknown[]) => { - try { - const parsed = JSON.parse(line as string) as Record - if (parsed.event === 'orca_relay_idle_rehome_dispatch_summary') { - entries.push(parsed) - arrived?.() - return - } - } catch { - // Not a JSON log line; fall through to the original writer. - } - original(line as string, ...rest) - } - return { entries, first, restore: () => (console.warn = original) } -} - -async function runOnePoll( - fetchImpl: typeof fetch, - candidates: number, - summaries: { first: Promise } -): Promise { - const assignments = { - selectIdleRegionalRehomeCandidates: vi.fn(async () => - Array.from({ length: candidates }, (_, index) => ({ - v: 1 as const, - attemptId: `00000000-0000-4000-8000-00000000000${index}`, - userId: `user-${index}`, - relayHostId: 'abcdefghijklmnop', - sourceCellId: 'us-c1', - sourceCellUrl: 'https://us-c1.relay.example.test', - sourceCellIncarnation: '11111111-1111-4111-8111-111111111111', - sourceAssignmentEpoch: 1, - sourceGeneration: 1, - targetCellId: 'asia-c1' - })) - ) - } as unknown as RelayAssignmentStore - const worker = startRegionalRehomeWorker(config(), assignments, { - fetch: fetchImpl, - identityToken: async () => 'token', - safetySnapshot: () => safety(Date.now()), - intervalMs: 60_000 - })! - try { - await summaries.first - } finally { - worker.stop() - } -} - -function config(overrides: Partial = {}): RelayConfig { - return { - role: 'director', - rehomeAudience: 'https://relay.example.test/v1/admin/host-drain', - rehomeDirectorServiceAccount: 'relay-director@example.test', - ...overrides - } as RelayConfig -} - -function safety(observedAt: number) { - return { - requiredCells: 2, - missingCells: 0, - observedAt, - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolTotal: 3, - databasePoolIdle: 3, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolOldestWaitMs: 0, - databasePoolWaitMsMax: 0 - } -} diff --git a/cloud/apps/relay/src/assignment/reserve-placement/placement-load-band.test.ts b/cloud/apps/relay/src/assignment/reserve-placement/placement-load-band.test.ts index a1ca010f8bf..27a35f11b2f 100644 --- a/cloud/apps/relay/src/assignment/reserve-placement/placement-load-band.test.ts +++ b/cloud/apps/relay/src/assignment/reserve-placement/placement-load-band.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { PLACEMENT_INTAKE_SHARE, PlacementLoadBand } from './placement-load-band.js' +import { PlacementLoadBand } from './placement-load-band.js' import { RelayAssignmentStore } from '../assignment-store.js' import { openInMemoryRelayDatabase } from '../../database/database.js' @@ -13,74 +13,8 @@ function seededRandom(seed: number): () => number { } } -type SimulatedCell = { cellId: string; reserved: number; capacity: number } - const quiet = () => undefined -// Each pick goes to one of the directors at random, as the load balancer spreads requests. -function simulate( - directors: PlacementLoadBand[], - cells: SimulatedCell[], - picks: number, - at: (index: number) => number, - route: () => number = seededRandom(99) -) { - const counts = new Map(cells.map((cell) => [cell.cellId, 0])) - for (let index = 0; index < picks; index += 1) { - const ranked = cells - .filter((cell) => cell.reserved < cell.capacity) - .map((cell) => ({ cellId: cell.cellId, loadRatio: cell.reserved / cell.capacity, cell })) - .sort( - (left, right) => left.loadRatio - right.loadRatio || left.cellId.localeCompare(right.cellId) - ) - const director = directors[Math.floor(route() * directors.length)] - const picked = director?.pick(ranked, at(index)) - if (!picked) throw new Error('no candidate') - picked.cell.reserved += 1 - counts.set(picked.cellId, (counts.get(picked.cellId) ?? 0) + 1) - } - return counts -} - -// c27's drain on 10-08: 2,770 hosts onto one empty Asia cell (2,805 free) -// and four fuller ones (2,311 free between them). -function c27DrainCells(): SimulatedCell[] { - return [ - { cellId: 'cell-empty', reserved: 0, capacity: 4000 }, - ...['cell-b', 'cell-c', 'cell-d', 'cell-e'].map((cellId, index) => ({ - cellId, - reserved: 4000 - 577 - (index === 0 ? 3 : 0), - capacity: 4000 - })) - ] -} - -function drainShare(paceMs: number, seed: number) { - const cells = c27DrainCells() - const directors = Array.from( - { length: 5 }, - (_, index) => new PlacementLoadBand(seededRandom(seed + index), quiet) - ) - const hosts = 2770 - const counts = simulate(directors, cells, hosts, (index) => (index * paceMs) / hosts) - return { counts, cells, share: (counts.get('cell-empty') ?? 0) / hosts } -} - -describe('PlacementLoadBand', () => { - it.each([ - ['1,200 s', 1_200_000], - ['300 s', 300_000] - ])('keeps the empty cell near the share across five directors at the %s pace', (_, paceMs) => { - for (const seed of [1, 2, 3]) { - const { counts, cells, share } = drainShare(paceMs, seed * 10) - expect([...counts.values()].reduce((sum, count) => sum + count, 0)).toBe(2770) - expect(share).toBeGreaterThan(0.3) - expect(share).toBeLessThan(0.5) - for (const cell of cells) expect(cell.reserved).toBeLessThanOrEqual(cell.capacity) - } - }) -}) - describe('leastLoadedCell with the load band', () => { async function setupRegions() { const database = await openInMemoryRelayDatabase() @@ -121,20 +55,6 @@ describe('leastLoadedCell with the load band', () => { return counts } - it('spreads within the preferred region and keeps an empty US cell out', async () => { - const { database, store } = await setupRegions() - try { - const counts = await placements(store, 200) - - expect(counts.get('us-a')).toBeUndefined() - expect(counts.get('asia-a')).toBeLessThanOrEqual(PLACEMENT_INTAKE_SHARE * 200 + 1) - const used = [...counts.values()].filter((count) => count >= 20) - expect(used.length).toBeGreaterThanOrEqual(3) - } finally { - await database.close() - } - }) - it('fills the preferred region to its hard cap before spilling, never past it', async () => { const { database, store } = await setupRegions() try { diff --git a/cloud/apps/relay/src/assignment/reserve-placement/reserve-assignment.test.ts b/cloud/apps/relay/src/assignment/reserve-placement/reserve-assignment.test.ts index 860d5e5b356..fe541e29046 100644 --- a/cloud/apps/relay/src/assignment/reserve-placement/reserve-assignment.test.ts +++ b/cloud/apps/relay/src/assignment/reserve-placement/reserve-assignment.test.ts @@ -111,25 +111,6 @@ function seated(epoch: number, joinedAt = 0) { describe('reserve assignment on a director', () => { - it('reads what each cell acts on: a tripped dead-man is db, a flip back still leasing is reserve', async () => { - const tripped = setup({ - feeds: [feed('c1', { admitModeEffective: 'db' }), feed('c2', { admitModeEffective: 'db' })] - }) - expect(await tripped.assignment.plan(HOST, { reconnect: false, region: US })).toEqual({ kind: 'database' }) - const leasing = setup({ feeds: [feed('c1', { admitMode: 'db', admitModeEffective: 'reserve' }), feed('c2')] }) - expect(leasing.directory.admitModeOf('c1')).toBe('reserve') - // Raw db must immediately stop booking/pacing even while effective mode stays reserve during re-registration. - const reregistering = setup({ - feeds: [ - feed('c1', { admitModeEffective: 'reserve', admitModeRaw: 'db' }), - feed('c2', { admitModeEffective: 'reserve', admitModeRaw: 'db' }) - ] - }) - expect(await reregistering.assignment.plan(HOST, { reconnect: false, region: US })).toEqual({ kind: 'database' }) - expect(reregistering.reserved).toEqual([]) - expect(reregistering.directory.admitModeOf('c1')).toBe('reserve') - }) - it('before every live cell has answered, holds back only hosts that may be on an unheard cell', async () => { const cells = cellList(['c1', 'c2']) const onUnheard = { ...HOST, relayHostId: 'qrstuvwxyzabcdef' } @@ -153,18 +134,6 @@ describe('reserve assignment on a director', () => { expect((await gated.assignment.plan(onUnheard, { reconnect: true, region: US })).kind).not.toBe('retry') }) - it('answers a reconnect from memory at the same epoch with no booking and no database read', async () => { - const row = vi.fn(async () => null) - const { assignment, reserved } = setup({ - feeds: [feed('c1', { full: [seated(7)] }), feed('c2')], - row - }) - const plan = await assignment.plan(HOST, { reconnect: true, region: US }) - expect(plan).toMatchObject({ kind: 'answer', lane: 'sticky', assignment: { cellId: 'c1', assignmentEpoch: 7 } }) - expect(reserved).toEqual([]) - expect(row).not.toHaveBeenCalled() - }) - it('re-books a host on a cell that restarted since its seat, and only then answers it', async () => { const { assignment, directory, reserved, now } = setup({ feeds: [feed('c1', { full: [seated(7)] }), feed('c2')] @@ -198,57 +167,6 @@ describe('reserve assignment on a director', () => { }) }) - it('never sends a drained or demoted host back, and books it elsewhere above every known epoch', async () => { - const { assignment, directory, reserved, now } = setup() - directory.apply( - 'c1', - feed('c1', { - full: undefined, - seq: 3, - changes: [ - { seq: 2, kind: 'join', ...HOST, epoch: 7, generation: 1, at: 1 }, - { seq: 3, kind: 'leave', ...HOST, epoch: 7, generation: 1, closeCode: 4503, at: 2 } - ] - }), - now.value, - now.value - ) - const plan = await assignment.plan(HOST, { reconnect: true, region: US }) - expect(plan).toMatchObject({ - kind: 'answer', - lane: 'placement', - assignment: { assignmentEpoch: 8 } - }) - expect(reserved.length).toBeGreaterThan(0) - expect(reserved.every((call) => !call.sticky && call.epoch === 8)).toBe(true) - }) - - it('leaves a cell without a feed (c17/c18) on today’s path without starving the reserve pool', async () => { - const cells = cellList(['c1', 'c2', 'c17']) - let rowOnOld = false - const { assignment, directory, reserved, now } = setup({ - cells, - feeds: [feed('c1'), feed('c2', { admitMode: 'db' })], - row: async () => (rowOnOld ? { cellId: 'c17', assignmentEpoch: 5 } : null) - }) - directory.markNoFeed('c17', now.value) - expect(directory.isComplete()).toBe(true) - // An old image reports no ceiling; counting it as a database cell would zero the share. - expect(await assignment.plan(HOST, { reconnect: false, region: US })).toMatchObject({ - kind: 'answer', - lane: 'placement', - assignment: { cellId: 'c1' } - }) - expect(reserved.map((call) => call.cellId)).not.toContain('c17') - rowOnOld = true - expect( - await assignment.plan({ ...HOST, relayHostId: 'qrstuvwxyzabcdef' }, { reconnect: true, region: US }) - ).toMatchObject({ kind: 'database', epochFloor: 5 }) - directory.markNoFeed('c1', now.value) - expect(directory.cellState('c1')?.ceiling).toBeUndefined() - expect(assignment.placementCells().find((cell) => cell.cellId === 'c1')?.general).toBe(false) - }) - it('reads the row once for a host the map never saw, and refuses it while the database is down', async () => { const down = setup({ row: async () => Promise.reject(new Error('timeout')) }) expect(await down.assignment.plan(HOST, { reconnect: false, region: US })).toMatchObject({ @@ -318,95 +236,6 @@ describe('reserve assignment on a director', () => { } }) - describe('for a share-draw loser', () => { - const ASIA = 'asia-east2' as const - const OTHER = { ...HOST, relayHostId: 'qrstuvwxyzabcdef' } - const setupAsia = (reserveCell = feed('c1'), reserve?: (cellId: string) => ReserveAttempt) => - setup({ - ...(reserve ? { reserve } : {}), - cells: [...cellList(['c1', 'c2'], ASIA), ...cellList(['c3'])], - feeds: [ - reserveCell, - // Database room far above the reserve cell's, so the 0.25 draw loses. - feed('c2', { - admitMode: 'db', - counts: { seats: 0, controls: 0, bookings: 0, units: 0, ceiling: 5_000 } - }), - feed('c3') - ] - }) - const regionReserveOf = async (assignment: ReserveAssignment, identity = HOST) => { - const plan = await assignment.plan(identity, { reconnect: false, region: ASIA }) - expect(plan).toMatchObject({ kind: 'database', epochFloor: 0 }) - return plan.kind === 'database' ? plan.regionReserve : undefined - } - - it('offers the reserve cell in its region only, only while it has a seat', async () => { - const { assignment, reserved, directory, now } = setupAsia() - const regionReserve = await regionReserveOf(assignment) - expect(reserved).toEqual([]) - await expect(regionReserve?.()).resolves.toMatchObject({ cellId: 'c1', region: ASIA }) - expect(reserved.map((call) => call.cellId)).toEqual(['c1']) - const full = feed('c1', { counts: { seats: 500, controls: 500, bookings: 0, units: 500, ceiling: 500 } }) - directory.apply('c1', full, now.value, now.value) - expect(await regionReserveOf(assignment, OTHER)).toBeUndefined() - expect(reserved.map((call) => call.cellId)).toEqual(['c1']) - }) - - it('paces when the reserve cell has seats but no intake budget, rather than give up the region', async () => { - const { assignment, reserved } = setupAsia(feed('c1', { intake: { perSec: 1, burst: 20, tokens: 0 } })) - const regionReserve = await regionReserveOf(assignment) - await expect(regionReserve?.()).rejects.toBeInstanceOf(ReservePaceError) - expect(reserved).toEqual([]) - }) - - it('gives the region up when the reserve cell refuses with a seat still on the map', async () => { - for (const outcome of ['full', 'unreachable']) { - const { assignment, reserved } = setupAsia(feed('c1'), (cellId) => - cellId === 'c1' ? { outcome } : { outcome: 'ok' } - ) - const regionReserve = await regionReserveOf(assignment) - // Null sends the host to the database lane's cross-region fallback, not a 1 s retry. - await expect(regionReserve?.()).resolves.toBeNull() - expect(reserved.map((call) => call.cellId)).toEqual(['c1']) - } - }) - }) - - describe('for a region-correction request', () => { - const request = { reconnect: true, region: US, regionCorrection: true } - - it('leaves the answer to the database lane, offering only the in-region reserve fallback and the spill', async () => { - const row = vi.fn(async () => null) - // A memory answer would skip the window exchange; the share draw is not offered either. - const { assignment, reserved } = setup({ feeds: [feed('c1', { full: [seated(7)] }), feed('c2')], row }) - const plan = await assignment.plan(HOST, request) - expect(plan).toEqual({ - kind: 'database', - regionReserve: expect.any(Function), - reserveSpill: expect.any(Function) - }) - expect(reserved).toEqual([]) - expect(row).not.toHaveBeenCalled() - await expect(plan.kind === 'database' ? plan.regionReserve?.() : null).resolves.toMatchObject({ - assignmentEpoch: 8 - }) - }) - - it('keeps today’s path for a host the map never saw, without reading its row, but may spill', async () => { - const row = vi.fn(async () => ({ cellId: 'c1', assignmentEpoch: 3 })) - const { assignment, reserved } = setup({ row }) - const plan = await assignment.plan(HOST, request) - expect(plan).toEqual({ kind: 'database', reserveSpill: expect.any(Function) }) - expect(row).not.toHaveBeenCalled() - expect(reserved).toEqual([]) - await expect( - plan.kind === 'database' ? plan.reserveSpill?.({ skipOwnRegion: false, rowEpoch: 3 }) : null - ).resolves.toMatchObject({ assignmentEpoch: 4 }) - }) - - }) - describe('after the database lane found no cell anywhere', () => { const ASIA = 'asia-east2' as const const paced = { intake: { perSec: 1, burst: 20, tokens: 0 } } @@ -428,31 +257,6 @@ describe('reserve assignment on a director', () => { return plan.kind === 'database' ? plan.reserveSpill : undefined } - it('books its own region first, minting above the row the database lane read', async () => { - const harness = setupSpill({}) - const spill = await spillOf(harness) - await expect(spill?.({ skipOwnRegion: false, rowEpoch: 9 })).resolves.toMatchObject({ - cellId: 'asia-r', - region: ASIA, - assignmentEpoch: 10 - }) - expect(harness.reserved).toEqual([{ cellId: 'asia-r', epoch: 10, sticky: false, dryRun: false }]) - }) - - it('books the other region when its own is full, or already tried', async () => { - const full = setupSpill(fullCounts) - await expect((await spillOf(full))?.({ skipOwnRegion: false, rowEpoch: 0 })).resolves.toMatchObject({ - cellId: 'us-r', - region: US, - assignmentEpoch: 5 - }) - const tried = setupSpill({}) - await expect((await spillOf(tried))?.({ skipOwnRegion: true, rowEpoch: 0 })).resolves.toMatchObject({ - cellId: 'us-r' - }) - expect(tried.reserved.map((call) => call.cellId)).toEqual(['us-r']) - }) - it('tries the other region after a pace, and answers the pace only if nothing places', async () => { const abroad = setupSpill(paced) await expect((await spillOf(abroad))?.({ skipOwnRegion: false, rowEpoch: 0 })).resolves.toMatchObject({ @@ -464,39 +268,10 @@ describe('reserve assignment on a director', () => { ) }) - it('returns null with no reserve seat anywhere, so the refusal stands', async () => { - const harness = setupSpill(fullCounts, fullCounts) - await expect((await spillOf(harness))?.({ skipOwnRegion: false, rowEpoch: 0 })).resolves.toBeNull() - expect(harness.reserved).toEqual([]) - }) - - it('is not offered while the map is incomplete', async () => { - const gated = setup({ - cells: [...cellList(['asia-r', 'asia-db'], ASIA), ...cellList(['us-r'])], - feeds: [feed('asia-r'), feed('asia-db', { admitMode: 'db', full: [seated(4)] })], - startedAt: 100_500 - }) - const plan = await gated.assignment.plan(HOST, { reconnect: true, region: ASIA }) - expect(plan).toMatchObject({ kind: 'database' }) - expect(plan.kind === 'database' && plan.reserveSpill).toBeUndefined() - const correction = await gated.assignment.plan(HOST, { reconnect: true, region: ASIA, regionCorrection: true }) - expect(correction).toEqual({ kind: 'database' }) - }) - - it('answers the shortest pace when every region paces', async () => { - const harness = setupSpill(paced, { intake: { perSec: 2, burst: 20, tokens: 0 } }) - const spill = await spillOf(harness) - // Asia refills its token in 4 s, US in 2 s. - await expect(spill?.({ skipOwnRegion: false, rowEpoch: 0 })).rejects.toSatisfy( - (error) => error instanceof ReservePaceError && error.retryAfterSeconds === 2 - ) - }) - }) describe('rehome on reconnect', () => { const ASIA = 'asia-east2' as const - const OTHER = { ...HOST, relayHostId: 'qrstuvwxyzabcdef' } const ask = { reconnect: true, region: ASIA, preferred: true } // 2,000 controls on the US cell refill its move budget once a minute. const usCounts = { counts: { seats: 1, controls: 2_000, bookings: 0, units: 1, ceiling: 4_000 } } @@ -546,107 +321,6 @@ describe('reserve assignment on a director', () => { expect(demoted).toEqual([{ cellId: 'us-r', epoch: 5, joinedAt: 1_000 }]) }) - it('answers a region-correction request on the rehome lane', async () => { - const { assignment, warm } = setupRehome() - await warm() - expect(await assignment.plan(HOST, { ...ask, regionCorrection: true })).toMatchObject({ - kind: 'answer', - lane: 'rehome' - }) - }) - - it('moves no one into Asia at 98% full, or anywhere under 10% free', async () => { - for (const share of [0.98, 0.91]) { - const { assignment, reserved, warm } = setupRehome({ asia: asiaFull(share) }) - await warm() - expect(await assignment.plan(HOST, ask), String(share)).toMatchObject({ - kind: 'answer', - lane: 'sticky', - assignment: { cellId: 'us-r' } - }) - expect(reserved.filter((call) => call.cellId === 'asia-r')).toEqual([]) - } - const { assignment, warm } = setupRehome({ asia: asiaFull(0.9) }) - await warm() - expect(await assignment.plan(HOST, ask)).toMatchObject({ lane: 'rehome' }) - }) - - // 10% rehome headroom above the 0% spill line prevents spilled hosts bouncing back. - it('keeps a gap above the spill line: 5% free takes placements, not rehomes', async () => { - const { assignment, warm } = setupRehome({ asia: asiaFull(0.95) }) - await warm() - expect(await assignment.plan(HOST, ask)).toMatchObject({ lane: 'sticky', assignment: { cellId: 'us-r' } }) - expect(await assignment.plan(OTHER, { reconnect: false, region: ASIA })).toMatchObject({ - lane: 'placement', - assignment: { cellId: 'asia-r' } - }) - }) - - it('keeps today’s answer when any rule fails', async () => { - const sticky = { kind: 'answer', lane: 'sticky', assignment: { cellId: 'us-r' } } - const unhinted = setupRehome() - await unhinted.warm() - expect(await unhinted.assignment.plan(HOST, { ...ask, preferred: false })).toMatchObject(sticky) - const off = setupRehome({ percent: 0 }) - await off.warm() - expect(await off.assignment.plan(HOST, ask)).toMatchObject(sticky) - const closed = setupRehome({ switchOpen: false }) - await closed.warm() - expect(await closed.assignment.plan(HOST, ask)).toMatchObject(sticky) - const cold = setupRehome() - expect(await cold.assignment.plan(HOST, ask)).toMatchObject(sticky) - const sameRegion = setupRehome() - await sameRegion.warm() - expect(await sameRegion.assignment.plan(HOST, { ...ask, region: US })).toMatchObject(sticky) - }) - - it('never runs for a fresh ask, an unknown host, a database-mode source, or an incomplete map', async () => { - const fresh = setupRehome() - await fresh.warm() - expect(await fresh.assignment.plan(HOST, { ...ask, reconnect: false })).toMatchObject({ lane: 'placement' }) - expect(await fresh.assignment.plan(OTHER, ask)).toMatchObject({ kind: 'answer', lane: 'placement' }) - const onDatabase = setup({ - cells: [...cellList(['us-db']), ...cellList(['asia-r'], ASIA)], - feeds: [feed('us-db', { admitMode: 'db', ...usCounts, full: [seated(5, 1_000)] }), feed('asia-r', asiaFull(0.5))], - rehome: new ReserveRehome({ percent: 100, switchOpen: () => true }) - }) - expect(await onDatabase.assignment.plan(HOST, ask)).toMatchObject({ kind: 'database' }) - const gated = setup({ - cells: [...cellList(['us-r']), ...cellList(['asia-r', 'asia-unheard'], ASIA)], - feeds: [feed('us-r', { ...usCounts, full: [seated(5, 1_000)] }), feed('asia-r', asiaFull(0.5))], - startedAt: 100_500, - rehome: new ReserveRehome({ percent: 100, switchOpen: () => true }) - }) - expect(await gated.assignment.plan(HOST, ask)).toMatchObject({ lane: 'sticky' }) - expect(gated.reserved).toEqual([]) - }) - - it('falls through to the sticky answer when the rehome booking is paced', async () => { - const { assignment, reserved, warm } = setupRehome({ - reserve: (cellId) => (cellId === 'asia-r' ? { outcome: 'intake' } : { outcome: 'ok' }) - }) - await warm() - expect(await assignment.plan(HOST, ask)).toMatchObject({ kind: 'answer', lane: 'sticky' }) - expect(reserved.map((call) => call.cellId)).toEqual(['asia-r']) - }) - - it('leaves a host another install keeps dropping', async () => { - const { assignment, directory, now, warm } = setupRehome() - await warm() - directory.apply( - 'us-r', - feed('us-r', { - ...usCounts, - full: undefined, - seq: 3, - changes: [{ seq: 3, kind: 'leave', ...HOST, epoch: 4, generation: 1, closeCode: 4408, at: now.value - 1 }] - }), - now.value, - now.value - ) - expect(await assignment.plan(HOST, ask)).toMatchObject({ lane: 'sticky' }) - }) - it('falls through to the sticky answer when the booking is refused, and gives the move back', async () => { let refuse = true const { assignment, warm } = setupRehome({ @@ -657,52 +331,6 @@ describe('reserve assignment on a director', () => { refuse = false expect(await assignment.plan(HOST, ask)).toMatchObject({ lane: 'rehome' }) }) - - it('moves one host per source budget a minute, and logs moves and skips per region pair', async () => { - const lines: Record[] = [] - const { assignment, now, warm } = setupRehome({ - usSeats: [seated(5, 1_000), { ...OTHER, epoch: 5, generation: 1, state: 'active', joinedAt: 1_000 }], - log: (line) => lines.push(JSON.parse(line)) - }) - await warm() - expect(await assignment.plan(HOST, ask)).toMatchObject({ lane: 'rehome' }) - expect(await assignment.plan(OTHER, ask)).toMatchObject({ lane: 'sticky' }) - now.value += 60_000 - await assignment.plan({ ...HOST, relayHostId: 'flushflushflush1' }, ask) - expect(lines.filter((line) => line.event === 'orca_relay_reserve_rehome')).toEqual([ - { event: 'orca_relay_reserve_rehome', fromRegion: US, toRegion: ASIA, count: 0, skippedByRule: { 'source-budget': 1 } }, - { event: 'orca_relay_reserve_rehome', fromRegion: US, toRegion: ASIA, count: 1, skippedByRule: { 'source-budget': 1 } } - ]) - }) - }) - - it('paces with Retry-After when every reserve cell is out of budget and no database cell exists', async () => { - const { assignment } = setup({ reserve: () => ({ outcome: 'intake' }) }) - await expect(assignment.plan(HOST, { reconnect: false, region: US })).rejects.toMatchObject({ - message: 'reserve_cells_paced', - retryAfterSeconds: expect.any(Number) - }) - }) - - it('tells the old reserve seat to go when it books the host elsewhere, naming that seat exactly', async () => { - const { assignment, directory, demoted, now } = setup({ - feeds: [feed('c1', { full: [seated(5, 1_000)] }), feed('c2')], - reserve: (cellId) => (cellId === 'c1' ? { outcome: 'full' } : { outcome: 'ok' }) - }) - // The host left c1 for a reason that moves it: its next placement is fresh, above 5. - directory.apply( - 'c1', - feed('c1', { - full: undefined, - seq: 2, - changes: [{ seq: 2, kind: 'drain-only', ...HOST, epoch: 5, generation: 1, at: 2 }] - }), - now.value, - now.value - ) - const plan = await assignment.plan(HOST, { reconnect: true, region: US }) - expect(plan).toMatchObject({ kind: 'answer', lane: 'placement', assignment: { assignmentEpoch: 6 } }) - expect(demoted).toEqual([{ cellId: 'c1', epoch: 5, joinedAt: 1_000 }]) }) // A half-open seat missed by the booking map must be demoted by the feed, before its 75s silence close. @@ -714,91 +342,4 @@ describe('reserve assignment on a director', () => { directory.apply('c1', feed('c1', { full: [seated(5, 1_000)] }), now.value, now.value) expect(demoted).toEqual([{ cellId: 'c1', epoch: 5, joinedAt: 1_000 }]) }) - - it('answers a reconnect at the newest epoch even when an older epoch joined later', async () => { - const { assignment, reserved } = setup({ - feeds: [feed('c1', { full: [seated(6, 1_000)] }), feed('c2', { full: [seated(5, 3_000)] })] - }) - expect(await assignment.plan(HOST, { reconnect: true, region: US })).toMatchObject({ - kind: 'answer', - lane: 'sticky', - assignment: { cellId: 'c1', assignmentEpoch: 6 } - }) - expect(reserved).toEqual([]) - }) - - it('in dry run only asks a cell to check a booking, and never changes the answer', async () => { - const { assignment, reserved } = setup({ mode: 'dry-run' }) - const plan = await assignment.plan(HOST, { reconnect: false, region: US }) - expect(plan.kind).toBe('database') - expect(plan.kind === 'database' && (await plan.placeFresh?.())).toBeNull() - expect(reserved).toMatchObject([{ dryRun: true }]) - }) - - describe('when a cell answers a demotion', () => { - const outcomes = (lines: string[]) => - lines - .map((line) => JSON.parse(line)) - .filter((entry) => entry.event === 'orca_relay_reserve_demote_outcome') - - it('logs the answer by host digest and leaves the seat to the feed', async () => { - const lines: string[] = [] - const logged = Promise.withResolvers() - const { assignment, directory } = setup({ - feeds: [feed('c1', { full: [seated(10, 1_000)] }), feed('c2')], - demote: () => 'not-seated', - log: (line) => { - lines.push(line) - if (JSON.parse(line).event === 'orca_relay_reserve_demote_outcome') { - logged.resolve() - } - } - }) - assignment.demoteSeat({ ...HOST, cellId: 'c1', epoch: 10, joinedAt: 1_000 }, 'reconcile') - await logged.promise - expect(outcomes(lines)).toMatchObject([ - { via: 'reconcile', cellId: 'c1', epoch: 10, outcome: 'not-seated' } - ]) - expect(outcomes(lines)[0].relayHostIdDigest).toMatch(/^[0-9a-f]{12}$/) - expect(lines.join('\n')).not.toContain(HOST.relayHostId) - expect(directory.seatsOnCell('c1')).toHaveLength(1) - }) - - }) - - describe('for a host re-asking off a draining cell', () => { - const events = (lines: string[], event: string) => - lines.map((line) => JSON.parse(line)).filter((entry) => entry.event === event) - - it('marks its pace as the drain’s, on the reserve lane, in the region fallback and in the spill', async () => { - const { assignment } = setup({ - feeds: [feed('c1', { draining: true, full: [seated(7)] }), feed('c2')], - reserve: () => ({ outcome: 'intake' }) - }) - await expect(assignment.plan(HOST, { reconnect: true, region: US })).rejects.toMatchObject({ drained: true }) - const plan = await assignment.plan(HOST, { reconnect: true, region: US, regionCorrection: true }) - await expect(plan.kind === 'database' ? plan.regionReserve?.() : null).rejects.toMatchObject({ drained: true }) - await expect( - plan.kind === 'database' ? plan.reserveSpill?.({ skipOwnRegion: false, rowEpoch: 0 }) : null - ).rejects.toMatchObject({ drained: true }) - }) - - it('leaves every other host as today: no drain count, and a plain pace', async () => { - const lines: string[] = [] - const { assignment } = setup({ feeds: [feed('c1', { full: [seated(7)] }), feed('c2')], log: (line) => lines.push(line) }) - const paced = setup({ - feeds: [feed('c1', { full: [seated(7)] }), feed('c2', { draining: true, full: [seated(6)] })], - reserve: () => ({ outcome: 'intake' }) - }) - expect(await assignment.plan({ ...HOST, relayHostId: 'qrstuvwxyzabcdef' }, { reconnect: false, region: US })).toMatchObject({ - kind: 'answer', - lane: 'placement' - }) - await expect( - paced.assignment.plan(HOST, { reconnect: false, region: US }) - ).rejects.toMatchObject({ drained: false }) - expect(events(lines, 'orca_relay_reserve_drain_replaced')).toEqual([]) - }) - - }) }) diff --git a/cloud/apps/relay/src/assignment/reserve-placement/reserve-ledger-writer.test.ts b/cloud/apps/relay/src/assignment/reserve-placement/reserve-ledger-writer.test.ts index 88f3b5875c4..66a5e7b15fc 100644 --- a/cloud/apps/relay/src/assignment/reserve-placement/reserve-ledger-writer.test.ts +++ b/cloud/apps/relay/src/assignment/reserve-placement/reserve-ledger-writer.test.ts @@ -57,30 +57,15 @@ describe('reserve ledger writer', () => { expect(await row(db, 'bbbbbbbbbbbbbbbb')).toMatchObject({ cell_id: 'c1', reserved_controls: 2 }) }) - it('keeps its queue through a database stall and drops the oldest past the bound', async () => { + it('persists a booked join after a database stall', async () => { let now = 1_000 const { database: db, writer } = await setup(() => now) - const query = vi.spyOn(db, 'query').mockRejectedValueOnce(new Error('timeout')) + vi.spyOn(db, 'query').mockRejectedValueOnce(new Error('timeout')) writer.enqueue({ ...HOST, cellId: 'c1', epoch: 5 }) await writer.flush() - expect(writer.pending()).toBe(1) - await writer.flush() - expect(query).toHaveBeenCalledTimes(1) now += 1_000 await writer.flush() - expect(writer.pending()).toBe(0) expect(await row(db)).toMatchObject({ cell_id: 'c1', assignment_epoch: 5 }) - - const bounded = new ReserveLedgerWriter(db, { queueMax: 2, log: () => undefined }) - const hosts = ['oldest0000000000', 'middle0000000000', 'newest0000000000'] - for (const relayHostId of hosts) { - bounded.enqueue({ ...HOST, relayHostId, cellId: 'c1', epoch: 1 }) - } - expect(bounded.pending()).toBe(2) - await bounded.flush() - expect(await row(db, hosts[0])).toBeUndefined() - expect(await row(db, hosts[1])).toMatchObject({ cell_id: 'c1', assignment_epoch: 1 }) - expect(await row(db, hosts[2])).toMatchObject({ cell_id: 'c1', assignment_epoch: 1 }) }) it('reconciles the map’s seats and never lowers an epoch', async () => { diff --git a/cloud/apps/relay/src/assignment/reserve-placement/reserve-placement-simulation.test.ts b/cloud/apps/relay/src/assignment/reserve-placement/reserve-placement-simulation.test.ts deleted file mode 100644 index ed6808510f0..00000000000 --- a/cloud/apps/relay/src/assignment/reserve-placement/reserve-placement-simulation.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - runReservePlacementSimulation, - type SimulationConfig, - type SimulationReport -} from './reserve-placement-simulation.js' - -const SEEDS = [11, 23, 47] -const rtt = (region: string) => (region === 'asia-east2' ? 170 : 10) - -function fleet(): SimulationConfig['cells'] { - const cells: SimulationConfig['cells'] = [] - for (let index = 0; index < 24; index += 1) { - cells.push({ - cellId: `us${String(index).padStart(2, '0')}`, - region: 'us-central1', - hardCap: 600, - ceiling: 480, - intakePerSec: 5, - // A third of the fleet stays in database mode, one cell on an image without step 5. - mode: index % 3 === 0 ? 'db' : 'reserve', - old: index === 0, - preseated: 150 - }) - } - for (let index = 0; index < 6; index += 1) { - cells.push({ - cellId: `asia${index}`, - region: 'asia-east2', - hardCap: 600, - ceiling: 480, - intakePerSec: 2, - mode: index === 0 ? 'db' : 'reserve', - preseated: 200 - }) - } - return cells -} - -function expectInvariants(report: SimulationReport): void { - expect(report.violations).toEqual([]) -} - -describe('step 5 deterministic simulation', () => { - // Invariant 9 (dead-man) never trips here; its own tests below cover it. - it.each(SEEDS)( - 'holds invariants 1-8 across mixed versions, lagging polls, restarts and database stalls (seed %i)', - async (seed) => { - const report = await runReservePlacementSimulation({ - seed, - durationMs: 25 * 60_000, - directors: 5, - // One director still on the database-only revision. - oldDirectors: 1, - cells: fleet(), - hosts: 6_600, - hostRegion: (index) => (index % 5 === 0 ? 'asia-east2' : 'us-central1'), - arrivalPerSec: 20, - meanSessionMs: 8 * 60_000, - reconnectDelayMs: [500, 5_000], - duplicateAssignShare: 0.05, - halfOpenShare: 0.05, - pollLagMs: (director) => [0, 200, 1_000, 4_000, 10_000][director]!, - rttMs: rtt, - cellRestarts: [{ at: 6 * 60_000, cellId: 'us04' }, { at: 14 * 60_000, cellId: 'asia2' }], - directorRestarts: [{ at: 8 * 60_000, director: 2 }, { at: 16 * 60_000, director: 4 }], - // Drained hosts land elsewhere while their old seat lingers: placement supersedes it. - drains: [{ at: 12 * 60_000, cellId: 'us05', paceMs: 60_000 }], - databaseStalls: Array.from({ length: 3 }, (_, index) => ({ - at: (index * 610 + 120) * 1_000, - durationMs: 7_000 - })) - }) - expectInvariants(report) - expect(report.reservePlacements).toBeGreaterThan(500) - expect(report.stickyAnswers).toBeGreaterThan(500) - expect(report.seatedAtEnd).toBeGreaterThan(4_000) - // The run reached the paths the invariants guard, so a pass is not vacuous. - expect(report.supersedes).toBeGreaterThan(0) - expect(report.rowAheadDemotions).toBeGreaterThan(0) - expect(report.directorRestarts).toBe(2) - expect(report.stickyReserves).toBeGreaterThan(0) - expect(report.databasePlacements).toBeGreaterThan(0) - }, - 120_000 - ) - - it.each(SEEDS)( - 'near full: extra reserve calls stay within 10% and exhausted requests within 1% (seed %i)', - async (seed) => { - const cells = Array.from({ length: 17 }, (_, index) => ({ - cellId: `us${index}`, - region: 'us-central1' as const, - hardCap: 700, - ceiling: 600, - intakePerSec: 50, - mode: 'reserve' as const, - preseated: 582 - })) - const report = await runReservePlacementSimulation({ - seed, - durationMs: 3 * 60_000, - directors: 5, - cells, - hosts: 17 * 582 + 300, - hostRegion: () => 'us-central1', - arrivalPerSec: 10, - meanSessionMs: 0, - reconnectDelayMs: [1_000, 3_000], - duplicateAssignShare: 0, - halfOpenShare: 0, - pollLagMs: () => 0, - rttMs: rtt - }) - expectInvariants(report) - expect(report.reservePlacements).toBeGreaterThan(250) - expect(report.reserveCalls / report.reservePlacements - 1).toBeLessThanOrEqual(0.1) - expect(report.exhausted / report.requests).toBeLessThanOrEqual(0.01) - for (const share of Object.values(report.maxOccupancyShare)) expect(share).toBeLessThanOrEqual(1) - }, - 120_000 - ) - - it.each(SEEDS.flatMap((seed) => [[1_200_000, seed], [300_000, seed]] as const))( - 'a drain onto an empty cell at the %i ms pace spreads within each cell intake budget (seed %i)', - async (paceMs, seed) => { - // Production c27 drain: 1,200s pacing toward cells with 2,805/841/777/667/26 free seats. - const free = [2_805, 841, 777, 667, 26] - const cells: SimulationConfig['cells'] = free.map((seats, index) => ({ - cellId: `asia${index + 1}`, - region: 'asia-east2', - hardCap: 3_000, - ceiling: 2_830, - intakePerSec: 2, - mode: 'reserve', - preseated: 2_830 - seats - })) - cells.unshift({ - cellId: 'asia0', - region: 'asia-east2', - hardCap: 3_000, - ceiling: 2_830, - intakePerSec: 2, - mode: 'reserve', - preseated: 2_770 - }) - const preseated = cells.reduce((sum, cell) => sum + (cell.preseated ?? 0), 0) - const report = await runReservePlacementSimulation({ - seed, - durationMs: 30 * 60_000, - directors: 5, - cells, - hosts: preseated, - hostRegion: () => 'asia-east2', - arrivalPerSec: 1, - meanSessionMs: 0, - reconnectDelayMs: [1_000, 3_000], - duplicateAssignShare: 0.02, - halfOpenShare: 0, - pollLagMs: () => 0, - rttMs: rtt, - drains: [{ at: 10_000, cellId: 'asia0', paceMs }] - }) - expectInvariants(report) - // Below every cell's budget nothing waits; above it the cells' buckets pace the drain. - if (paceMs === 300_000) expect(report.intakeRefusals + report.paced).toBeGreaterThan(0) - const moved = Object.entries(report.arrivalsByCell) - const total = moved.reduce((sum, [, count]) => sum + count, 0) - expect(total).toBeGreaterThan(2_000) - // Spread: the emptiest cell takes a share, not the drain. - expect((report.arrivalsByCell.asia1 ?? 0) / total).toBeLessThan(0.6) - expect(moved.filter(([, count]) => count / total > 0.1).length).toBeGreaterThanOrEqual(3) - }, - 120_000 - ) - - - -}) diff --git a/cloud/apps/relay/src/assignment/reserve-placement/reserve-placement-simulation.ts b/cloud/apps/relay/src/assignment/reserve-placement/reserve-placement-simulation.ts deleted file mode 100644 index f39811009ec..00000000000 --- a/cloud/apps/relay/src/assignment/reserve-placement/reserve-placement-simulation.ts +++ /dev/null @@ -1,1357 +0,0 @@ -import { createHash } from 'node:crypto' -import { RELAY_PROTOCOL_LIMITS } from '@orca-cloud/relay-contract/protocol-limits' -import type { RelayRegion } from '@orca-cloud/relay-contract/relay-regions' -import { CellReserveBook } from '../../cell/reservations/cell-reserve-book.js' -import { CELL_INTAKE_BURST, CELL_RESERVE_TTL_MS, type ReserveOutcome } from '../../cell/reservations/cell-reserve-contract.js' -import { - mintEpoch, - RESERVE_CELL_FRESH_MS, - RESERVE_MAX_TRIES, - ReservePlacer, - type PlacementCell -} from './reserve-placement.js' -import { seatOutranks } from '../../cell/seats/shadow-seat-directory.js' - -// Seeded event model uses real CellReserveBook/ReservePlacer; sockets, DB and desktops are modeled. -// Record invariant violations without throwing so each run exposes every class it hits. - -export function seededRandom(seed: number): () => number { - let state = seed >>> 0 - return () => { - state = (state + 0x6d2b79f5) >>> 0 - let value = state - value = Math.imul(value ^ (value >>> 15), value | 1) - value ^= value + Math.imul(value ^ (value >>> 7), value | 61) - return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296 - } -} - -type Event = { at: number; seq: number; run: () => void } - -class Clock { - now = 0 - private seq = 0 - private readonly heap: Event[] = [] - - schedule(delayMs: number, run: () => void): void { - const event = { at: this.now + Math.max(0, Math.round(delayMs)), seq: this.seq++, run } - this.heap.push(event) - let index = this.heap.length - 1 - while (index > 0) { - const parent = (index - 1) >> 1 - if (!before(this.heap[index]!, this.heap[parent]!)) break - ;[this.heap[index], this.heap[parent]] = [this.heap[parent]!, this.heap[index]!] - index = parent - } - } - - async runUntil(until: number, afterEach: () => void): Promise { - while (this.heap.length > 0 && this.heap[0]!.at <= until) { - const event = this.pop() - this.now = event.at - event.run() - // Lets the promise continuations the event released settle before the next event. - for (let tick = 0; tick < 12; tick += 1) await Promise.resolve() - afterEach() - } - this.now = until - } - - private pop(): Event { - const top = this.heap[0]! - const last = this.heap.pop()! - if (this.heap.length > 0) { - this.heap[0] = last - let index = 0 - for (;;) { - const left = index * 2 + 1 - const right = left + 1 - let smallest = index - if (left < this.heap.length && before(this.heap[left]!, this.heap[smallest]!)) smallest = left - if (right < this.heap.length && before(this.heap[right]!, this.heap[smallest]!)) smallest = right - if (smallest === index) break - ;[this.heap[index], this.heap[smallest]] = [this.heap[smallest]!, this.heap[index]!] - index = smallest - } - } - return top - } -} - -function before(left: Event, right: Event): boolean { - return left.at < right.at || (left.at === right.at && left.seq < right.seq) -} - -// `leased`: admitted through the database check, so its control renews a lease there and is -// closed when the row moves on, as today. -type CellSeat = { epoch: number; joinedAt: number; reservedBy?: string; demoted: boolean; leased?: boolean } -type CellLogEntry = - | { kind: 'join'; host: string; epoch: number; joinedAt: number; reservedBy?: string } - | { kind: 'leave'; host: string; epoch: number; at: number; wrongCell: boolean } - | { kind: 'reserve'; host: string; epoch: number } - | { kind: 'demoted'; host: string; epoch: number } - -const RECENT_SEAT_MS = 10 * 60_000 -const DEMOTE_CLOSE_MS = 60_000 -const CONTROL_RENEWAL_MS = 25_000 -// As the director's: a seat this young may still be superseded. -const RECONCILE_SETTLE_MS = 30_000 -// A drained seat lingers this long (its splices finishing) unless superseded first. -const DRAIN_GRACE_MS = 30_000 -// A cell closes a control silent for 75 s, checked once per ping (host-session-registry.ts heartbeat). -const CONTROL_SILENCE_CLOSE_MS = 75_000 + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs -// Longer than the slowest duplicate: a half-open seat's silence close. -const QUIESCE_MS = 150_000 - -export type SimulationViolation = { invariant: number; at: number; detail: string } - -// Each fault breaks one rule on purpose, so a test can show the matching invariant fires. -export type SimulationFaults = { - bookPastCap?: boolean - intakeBurst?: number - // Each director assumes this share of every cell's intake, instead of a fifth. - directorShare?: number - // Nothing supersedes the old seat, at placement or from the feed: a duplicate outlives its bound. - skipSupersede?: boolean - // Only placement supersedes: a half-open seat the booking map had not seen lasts to its silence close. - skipFeedSupersede?: boolean - // A restarted director forgets its ledger queue and never reconciles. - noBootReconcile?: boolean - // The reconcile leaves a seat whose row is ahead of it alone. - noRowAheadDemote?: boolean - // Directors do not read the row after a WRONG_CELL leave (only the demoting one has a floor). - noWrongCellRowRead?: boolean - // Reserve placement re-uses the floor epoch instead of minting above it. - mintAtFloor?: boolean - // Today's path skips every cell Postgres records as reserve, ignoring the cell's own row. - pgReserveBlocksDatabase?: boolean - // Directors place by the reported mode, which stays reserve while a tripped cell re-registers. - noRawFeedMode?: boolean - unguardedLedger?: boolean - noEpochFloor?: boolean - // On a level divergence each director keeps the seat its own cell order prefers, not the row's. - localTieBreak?: boolean -} - -// Model cell-owned raw-mode writes every 15s; current-process db evidence permits placement within its 45s freshness bound. -const CELL_ADMIT_EFFECTIVE_REFRESH_MS = 15_000 -const CELL_ADMIT_EFFECTIVE_FRESH_MS = 45_000 -// A tripped cell reports reserve until every control it admitted from memory holds a lease. -const DEFAULT_REREGISTRATION_MS = 20_000 - -// cell-reserve-dead-man.ts's window: 60-120 s, fixed per cell. -function deadManWindowMs(cellId: string): number { - return 60_000 + (createHash('sha256').update(cellId).digest().readUInt32BE(0) % 60_001) -} - -class SimDatabase { - up = true - // relay_cell_admit_modes: what the flag workflow recorded. A trip does not change it. - readonly reserveCells = new Set() - readonly rows = new Map() - // relay_cell_admit_effective: written by each cell itself, never by a director. - readonly admitEffective = new Map() - private readonly counts = new Map() - - set(host: string, row: { cellId: string; epoch: number }): void { - const previous = this.rows.get(host) - if (previous) this.counts.set(previous.cellId, (this.counts.get(previous.cellId) ?? 1) - 1) - this.counts.set(row.cellId, (this.counts.get(row.cellId) ?? 0) + 1) - this.rows.set(host, row) - } - - constructor( - private readonly violate: (invariant: number, detail: string) => void, - private readonly faults: SimulationFaults - ) {} - - // The director's after-the-fact write, a guarded mirror: only a higher epoch replaces a row. - upsert(host: string, cellId: string, epoch: number): void { - const row = this.rows.get(host) - const guarded = !this.faults.unguardedLedger - if (guarded && row && row.epoch >= epoch) return - if (row && epoch < row.epoch) this.violate(5, `ledger epoch fell for ${host}`) - this.set(host, { cellId, epoch }) - } - - // Today's assign writes the row it answers with. - assign(host: string, cellId: string, epoch: number): void { - const row = this.rows.get(host) - if (row && epoch <= row.epoch) this.violate(5, `db mint not above row for ${host}`) - this.set(host, { cellId, epoch }) - } - - countOn(cellId: string): number { - return this.counts.get(cellId) ?? 0 - } -} - -class SimCell { - readonly seats = new Map() - readonly recent = new Map() - readonly log: CellLogEntry[] = [] - // Per incarnation: a restarted cell starts with a full bucket. - readonly okBookingTimes: number[][] = [[]] - incarnation = 1 - draining = false - mode: 'reserve' | 'db' - bookingUnits = 0 - // What relay_cells says to a director that predates step 5: frozen at the flip. - frozenDatabaseCount = 0 - // Latch db after 60–120s without placing-director booking/poll contact (cell-reserve-dead-man.ts). - lastContactAt = 0 - trippedAt: number | null = null - reregisteredAt = 0 - // Booted and no flag object read yet: its mode is a default, so it writes no admit row. - flagsUnread = false - book: CellReserveBook - - constructor( - readonly cellId: string, - readonly region: RelayRegion, - readonly hardCap: number, - readonly ceiling: number, - readonly intakePerSec: number, - mode: 'reserve' | 'db', - // An image that predates step 5 reports no ceiling and has no reserve route. - readonly old: boolean, - private readonly clock: Clock, - private readonly faults: SimulationFaults, - private readonly violate: (invariant: number, detail: string) => void - ) { - this.mode = mode - this.book = this.newBook() - } - - private newBook(): CellReserveBook { - const limit = () => (this.faults.bookPastCap ? Infinity : this.ceiling) - return new CellReserveBook( - { - canReserve: () => this.seats.size + this.bookingUnits + 1 <= limit(), - tryReserve: () => { - if (this.seats.size + this.bookingUnits + 1 > limit()) return null - this.bookingUnits += 1 - let released = false - return { - release: () => { - if (released) return - released = true - this.bookingUnits -= 1 - } - } - } - }, - () => this.intakePerSec, - () => this.clock.now, - this.faults.intakeBurst - ) - } - - occupancy(): number { - return this.seats.size + this.bookingUnits - } - - contact(): void { - this.lastContactAt = this.clock.now - } - - checkDeadMan(windowMs: number, reregistrationMs: number): void { - if (this.mode !== 'reserve' || this.old || this.clock.now - this.lastContactAt <= windowMs) return - this.mode = 'db' - this.trippedAt = this.clock.now - this.reregisteredAt = this.clock.now + reregistrationMs - } - - // What the feed's admitModeEffective reports: `mode` is the raw one (switch file and dead-man). - effectiveMode(): 'db' | 'reserve' { - return this.mode === 'reserve' || this.clock.now < this.reregisteredAt ? 'reserve' : 'db' - } - - reserve(directorId: string, host: string, epoch: number, sticky: boolean): ReserveOutcome { - if (this.mode === 'reserve') this.contact() - const outcome = this.book.reserve( - directorId, - { userId: host, relayHostId: 'abcdefghijklmnop', epoch, ttlMs: CELL_RESERVE_TTL_MS, sticky }, - { - mode: this.mode, - draining: this.draining, - seatedEpoch: (userId) => this.seats.get(userId)?.epoch - } - ) - if (outcome.outcome === 'ok') { - this.log.push({ kind: 'reserve', host, epoch }) - if (!sticky) this.okBookingTimes.at(-1)!.push(this.clock.now) - } - return outcome - } - - hello(host: string, epoch: number, database: SimDatabase): boolean { - if (this.draining) return false - if (this.mode === 'reserve') { - const booking = this.book.take(host, 'abcdefghijklmnop', epoch) - if (booking) return this.seat(host, epoch, booking.directorId) - const seated = this.seats.get(host) - const recent = this.recent.get(host) - if ( - (seated && seated.epoch === epoch && !seated.demoted) || - (recent && recent.epoch === epoch && this.clock.now - recent.at <= RECENT_SEAT_MS) - ) { - return this.seat(host, epoch) - } - } - if (!database.up) return false - const row = database.rows.get(host) - if (!row || row.cellId !== this.cellId || row.epoch !== epoch) return false - return this.seat(host, epoch, undefined, true) - } - - private seat(host: string, epoch: number, reservedBy?: string, leased = false): boolean { - // A rebind keeps its unit; a new seat needs one under the hard cap. - if (!this.seats.has(host) && this.occupancy() + 1 > this.hardCap) return false - this.seats.set(host, { epoch, joinedAt: this.clock.now, reservedBy, demoted: false, leased }) - this.recent.delete(host) - this.log.push({ kind: 'join', host, epoch, joinedAt: this.clock.now, reservedBy }) - return true - } - - leave(host: string): void { - const seat = this.seats.get(host) - if (!seat) return - this.seats.delete(host) - if (!seat.demoted) this.recent.set(host, { epoch: seat.epoch, at: this.clock.now }) - this.log.push({ kind: 'leave', host, epoch: seat.epoch, at: this.clock.now, wrongCell: seat.demoted }) - } - - // The cell's own check: only the seat named by epoch and join, and only in reserve mode. - demote(host: string, epoch: number, joinedAt: number, onClose: () => void): void { - if (this.mode !== 'reserve') return - const seat = this.seats.get(host) - if (!seat || seat.epoch !== epoch || seat.joinedAt !== joinedAt || seat.demoted) return - seat.demoted = true - this.log.push({ kind: 'demoted', host, epoch }) - this.clock.schedule(DEMOTE_CLOSE_MS, () => { - if (this.seats.get(host) === seat) { - this.leave(host) - onClose() - } - }) - } - - // Seats, bookings and memory are gone; the image boots in database mode until its first flag read. - restart(): string[] { - const hosts = [...this.seats.keys()] - for (const host of hosts) this.leave(host) - this.book.clear() - this.book = this.newBook() - this.recent.clear() - this.incarnation += 1 - this.okBookingTimes.push([]) - const mode = this.mode - this.mode = 'db' - this.flagsUnread = true - this.clock.schedule(5_000, () => { - this.mode = mode - this.flagsUnread = false - }) - return hosts - } -} - -type MapSeat = { epoch: number; joinedAt: number; reservedBy?: string; demoted: boolean } - -type DirectorCellView = { - incarnation: number | null - cursor: number - seats: Map - placement: PlacementCell -} - -type Answer = - | { kind: 'cell'; cellId: string; epoch: number; calls: number } - | { kind: 'retry'; afterMs: number; calls: number } - -export type SimulationConfig = { - seed: number - durationMs: number - directors: number - oldDirectors?: number - cells: Array<{ - cellId: string - region: RelayRegion - hardCap: number - ceiling: number - intakePerSec: number - mode: 'reserve' | 'db' - old?: boolean - preseated?: number - }> - hosts: number - hostRegion: (index: number) => RelayRegion - // Fresh connects arrive at this rate per second until every host has connected once. - arrivalPerSec: number - meanSessionMs: number - reconnectDelayMs: [number, number] - duplicateAssignShare: number - // Share of departures whose old control stays half-open on the cell while the desktop - // connects elsewhere: the real source of a host seated on two cells. - halfOpenShare: number - pollLagMs: (director: number) => number - rttMs: (region: RelayRegion) => number - faults?: SimulationFaults - cellRestarts?: Array<{ at: number; cellId: string }> - // Restarted estimates refill from zero at intake/directors: no booking until one token; unheard hosts also face the 30s startup gate. - directorRestarts?: Array<{ at: number; director: number }> - databaseStalls?: Array<{ at: number; durationMs: number }> - // Every director misses every feed poll for this long (a director-side outage). - pollOutages?: Array<{ at: number; durationMs: number }> - // How long a tripped cell keeps reporting reserve while it leases its memory-admitted controls. - reregistrationMs?: number - drains?: Array<{ at: number; cellId: string; paceMs: number }> -} - -export type SimulationReport = { - violations: SimulationViolation[] - requests: number - placements: number - reserveCalls: number - exhausted: number - paced: number - databasePlacements: number - reservePlacements: number - // Rows that named a placement the desktop never used, rewritten to its real seat. - supersedes: number - directorRestarts: number - rowAheadDemotions: number - // Demotions whose winner is level with the loser (same epoch, another cell): the tie-break's cases. - levelDemotions: number - // Two directors judging a same-epoch divergence exercise invariant 4; higher epochs already win consistently. - contestedDivergences: number - // Row-ahead demotions per demoted host: a repair that converges needs one. - rowAheadDemotionsPerHost: { max: number; p99: number } - deadManTrips: number - // Bookings sent to a cell after its dead-man tripped (the cell answers `off`). - reserveCallsOnTrippedCells: number - databasePlacementsWhilePollsFail: number - // From the first poll outage's start to the first fresh database placement inside it. - pollFailureGapMs: number | null - // First seats after a row-ahead demotion that land behind (or level with) the row again. - badFirstReseats: number - intakeRefusals: number - stickyReserves: number - stickyAnswers: number - seatedAtEnd: number - maxOccupancyShare: Record - arrivalsByCell: Record -} - -class SimDirector { - placer!: ReservePlacer - views = new Map() - recentlyLeft = new Map< - string, - { cellId: string; epoch: number; at: number; incarnation: number; wrongCell?: boolean } - >() - reserveEpochs = new Map() - // Row epochs this director demoted a host's seat behind: its next mint for the host clears them. - rowFloors = new Map() - ledgerQueue: Array<{ host: string; cellId: string; epoch: number }> = [] - answeredCells = new Set() - // Set by a restart: the lost ledger queue is rebuilt by one reconcile once the map is complete. - bootReconcilePending = false - restarted = false - readonly id: string - - constructor( - readonly index: number, - readonly old: boolean, - private readonly random: () => number, - private readonly clock: Clock, - private readonly share?: number - ) { - this.id = `d${index}` - this.reset() - } - - reset(): void { - this.placer = new ReservePlacer(() => this.clock.now, this.random, this.share) - this.views = new Map() - this.recentlyLeft = new Map() - this.reserveEpochs = new Map() - this.rowFloors = new Map() - this.answeredCells = new Set() - this.ledgerQueue = [] - } - - complete(cells: readonly SimCell[]): boolean { - return cells.every((cell) => this.answeredCells.has(cell.cellId)) - } - - knownEpochs(host: string): number[] { - const epochs: number[] = [] - for (const view of this.views.values()) { - const seat = view.seats.get(host) - if (seat) epochs.push(seat.epoch) - } - const reserved = this.reserveEpochs.get(host) - if (reserved !== undefined) epochs.push(reserved) - const left = this.recentlyLeft.get(host) - if (left) epochs.push(left.epoch) - return epochs - } -} - -export async function runReservePlacementSimulation( - config: SimulationConfig -): Promise { - const random = seededRandom(config.seed) - const clock = new Clock() - const violations: SimulationViolation[] = [] - // Capped per invariant, so a flood of one class cannot hide another. - const violationCounts = new Map() - const violate = (invariant: number, detail: string): void => { - const count = violationCounts.get(invariant) ?? 0 - violationCounts.set(invariant, count + 1) - if (count < 50) violations.push({ invariant, at: clock.now, detail }) - } - const faults = config.faults ?? {} - const database = new SimDatabase(violate, faults) - const cells = config.cells.map( - (spec) => - new SimCell( - spec.cellId, - spec.region, - spec.hardCap, - spec.ceiling, - spec.intakePerSec, - spec.mode, - spec.old ?? false, - clock, - faults, - violate - ) - ) - const cellById = new Map(cells.map((cell) => [cell.cellId, cell])) - for (const cell of cells) if (cell.mode === 'reserve' && !cell.old) database.reserveCells.add(cell.cellId) - const inPollOutage = (at: number): boolean => - (config.pollOutages ?? []).some((outage) => at >= outage.at && at < outage.at + outage.durationMs) - const directors = Array.from( - { length: config.directors }, - (_, index) => - new SimDirector( - index, - index < (config.oldDirectors ?? 0), - random, - clock, - config.faults?.directorShare - ) - ) - const report: SimulationReport = { - violations, - requests: 0, - placements: 0, - reserveCalls: 0, - exhausted: 0, - paced: 0, - databasePlacements: 0, - reservePlacements: 0, - supersedes: 0, - directorRestarts: 0, - rowAheadDemotions: 0, - levelDemotions: 0, - contestedDivergences: 0, - rowAheadDemotionsPerHost: { max: 0, p99: 0 }, - deadManTrips: 0, - reserveCallsOnTrippedCells: 0, - databasePlacementsWhilePollsFail: 0, - pollFailureGapMs: null, - badFirstReseats: 0, - intakeRefusals: 0, - stickyReserves: 0, - stickyAnswers: 0, - seatedAtEnd: 0, - maxOccupancyShare: {}, - arrivalsByCell: {} - } - const between = ([low, high]: [number, number]) => low + random() * (high - low) - - type Host = { id: string; region: RelayRegion; current: { cellId: string; epoch: number } | null } - const hosts: Host[] = Array.from({ length: config.hosts }, (_, index) => ({ - id: `h${index}`, - region: config.hostRegion(index), - current: null - })) - const hostById = new Map(hosts.map((host) => [host.id, host])) - - // Pre-seated hosts arrive with database rows, as hosts on a cell before its flip. - let nextHost = 0 - for (const cell of cells) { - const spec = config.cells.find((entry) => entry.cellId === cell.cellId)! - for (let index = 0; index < (spec.preseated ?? 0) && nextHost < hosts.length; index += 1) { - const host = hosts[nextHost++]! - database.set(host.id, { cellId: cell.cellId, epoch: 1 }) - cell.seats.set(host.id, { epoch: 1, joinedAt: 0, demoted: false }) - cell.log.push({ kind: 'join', host: host.id, epoch: 1, joinedAt: 0 }) - host.current = { cellId: cell.cellId, epoch: 1 } - scheduleLeave(host) - } - cell.frozenDatabaseCount = cell.seats.size - } - - function scheduleLeave(host: Host): void { - if (config.meanSessionMs <= 0) return - const sessionMs = -Math.log(1 - random()) * config.meanSessionMs - clock.schedule(sessionMs, () => { - const current = host.current - if (!current || quiescing) return - const cell = cellById.get(current.cellId)! - if (cell.seats.get(host.id)?.epoch !== current.epoch) return - // Half-open controls retain seats through silence timeout after desktops move elsewhere. - if (random() >= config.halfOpenShare) cell.leave(host.id) - else { - const seat = cell.seats.get(host.id) - clock.schedule(CONTROL_SILENCE_CLOSE_MS, () => { - if (cell.seats.get(host.id) === seat) cell.leave(host.id) - }) - } - host.current = null - clock.schedule(between(config.reconnectDelayMs), () => connect(host, true)) - }) - } - - function poll(director: SimDirector, cell: SimCell): void { - if (inPollOutage(clock.now)) return - // A placing director's poll carries reserver=1: it is the cell's dead-man contact. - if (!director.old && cell.mode === 'reserve') cell.contact() - const requestedAt = clock.now - const view = director.views.get(cell.cellId) - const full = !view || view.incarnation !== cell.incarnation - const seats = full ? new Map([...cell.seats].map(([host, seat]) => [host, { ...seat }])) : null - const changes = full ? [] : cell.log.slice(view.cursor) - const snapshot = { - incarnation: cell.incarnation, - cursor: cell.log.length, - seats: cell.seats.size, - bookings: cell.book.count(), - tokens: cell.book.intakeSnapshot().tokens, - mode: faults.noRawFeedMode ? cell.effectiveMode() : cell.mode, - draining: cell.draining - } - const delay = config.rttMs(cell.region) + config.pollLagMs(director.index) - clock.schedule(delay, () => { - let current = director.views.get(cell.cellId) - if (full) { - if (current) { - for (const [host, seat] of current.seats) { - if (!seats!.has(host)) { - director.recentlyLeft.set(host, { - cellId: cell.cellId, - epoch: seat.epoch, - at: clock.now, - incarnation: current.incarnation ?? 0 - }) - } - } - } - current = { - incarnation: snapshot.incarnation, - cursor: snapshot.cursor, - seats: seats!, - placement: placementCell(cell, snapshot, requestedAt) - } - director.views.set(cell.cellId, current) - supersedeOutranked(director, seats!.keys()) - } else if (current && current.incarnation === snapshot.incarnation) { - for (const change of changes) applyChange(director, cell, current, change) - current.cursor = snapshot.cursor - current.placement = placementCell(cell, snapshot, requestedAt) - supersedeOutranked( - director, - changes.filter((change) => change.kind === 'join').map((change) => change.host) - ) - } else { - // A restarted director's (or a stale) delta: the next poll asks for a full snapshot. - return - } - director.answeredCells.add(cell.cellId) - }) - } - - function placementCell( - cell: SimCell, - snapshot: { seats: number; bookings: number; tokens: number; mode: string; draining: boolean }, - polledAt: number - ): PlacementCell { - return { - cellId: cell.cellId, - region: cell.region, - reserve: !cell.old && snapshot.mode === 'reserve', - general: true, - draining: snapshot.draining, - polledAt, - seats: snapshot.seats, - bookings: snapshot.bookings, - ceiling: cell.old ? undefined : cell.ceiling, - intakePerSec: cell.intakePerSec, - intakeTokens: snapshot.tokens - } - } - - function applyChange( - director: SimDirector, - cell: SimCell, - view: DirectorCellView, - change: CellLogEntry - ): void { - if (change.kind === 'reserve') { - director.reserveEpochs.set( - change.host, - Math.max(director.reserveEpochs.get(change.host) ?? 0, change.epoch) - ) - } else if (change.kind === 'join') { - view.seats.set(change.host, { - epoch: change.epoch, - joinedAt: change.joinedAt, - reservedBy: change.reservedBy, - demoted: false - }) - director.recentlyLeft.delete(change.host) - // Exactly one director writes each booked join: the one that booked it. - if (change.reservedBy === director.id) { - director.ledgerQueue.push({ host: change.host, cellId: cell.cellId, epoch: change.epoch }) - } - } else if (change.kind === 'leave') { - const seat = view.seats.get(change.host) - if (seat && seat.epoch === change.epoch) { - view.seats.delete(change.host) - director.recentlyLeft.set(change.host, { - cellId: cell.cellId, - epoch: change.epoch, - at: change.at, - incarnation: view.incarnation ?? 0, - wrongCell: change.wrongCell - }) - } - } else { - const seat = view.seats.get(change.host) - if (seat && seat.epoch === change.epoch) seat.demoted = true - } - } - - // Booking director supersedes old reserve seats its map held; cell verifies epoch/join. - function supersede(director: SimDirector, host: string, cellId: string, epoch: number): void { - const held = new Set() - for (const [seatCellId, view] of director.views) { - const seat = view.seats.get(host) - if (seat) held.add(`${seatCellId}\u0000${seat.joinedAt}`) - } - heldAtBooking.set(`${host}\u0000${cellId}\u0000${epoch}`, held) - if (faults.skipSupersede) return - for (const [seatCellId, view] of director.views) { - const seat = view.seats.get(host) - if (!seat || seat.demoted || seatCellId === cellId || seat.epoch >= epoch) continue - if (!view.placement.reserve) continue - report.supersedes += 1 - demoteFor(director, host, seatCellId, seat, { cellId, epoch }) - } - } - - // Model feed supersede once both joins appear: only later joins at higher epochs outrank; later lower epochs need the row. - function supersedeOutranked(director: SimDirector, hosts: Iterable): void { - if (faults.skipSupersede || faults.skipFeedSupersede) return - for (const host of new Set(hosts)) { - const seats = [...director.views].flatMap(([cellId, view]) => { - const seat = view.seats.get(host) - return seat ? [{ cellId, view, seat }] : [] - }) - if (seats.length < 2) continue - for (const { cellId, view, seat } of seats) { - if (seat.demoted || !view.placement.reserve) continue - const by = seats.find((other) => seatOutranks(other.seat, seat)) - if (!by) continue - report.supersedes += 1 - demoteFor(director, host, cellId, seat, { cellId: by.cellId, epoch: by.seat.epoch }) - } - } - } - - // The seats the booking director's map held when it placed each booking: only those it supersedes. - const heldAtBooking = new Map>() - - // Invariant 4: all directors must name the same winner per divergence or two seats can each be demoted for the other. - const namedWinners = new Map() - const contested = new Set() - const demotedFor = new Map() - type JudgedSeat = { cellId: string; epoch: number } - function judge(director: SimDirector, host: string, loserSeat: JudgedSeat, wonSeat: JudgedSeat): void { - const loser = `${loserSeat.cellId}@${loserSeat.epoch}` - const won = `${wonSeat.cellId}@${wonSeat.epoch}` - const divergence = `${host}\u0000${[loser, won].sort().join('\u0000')}` - const named = namedWinners.get(divergence) - if (named === undefined) { - namedWinners.set(divergence, { won, by: director.id }) - return - } - // A second director judged it, agreeing or not: the tie-break was exercised. - if (named.by !== director.id && loserSeat.epoch === wonSeat.epoch && !contested.has(divergence)) { - contested.add(divergence) - report.contestedDivergences += 1 - } - if (named.won !== won) { - violate(4, `${director.id} names ${won} over ${loser} for ${host}; ${named.by} named ${named.won}`) - } - } - function demoteFor( - director: SimDirector, - host: string, - cellId: string, - seat: { epoch: number; joinedAt: number }, - winner: { cellId: string; epoch: number } - ): void { - const loser = `${cellId}@${seat.epoch}` - const won = `${winner.cellId}@${winner.epoch}` - judge(director, host, { cellId, epoch: seat.epoch }, winner) - const cell = cellById.get(cellId)! - clock.schedule(config.rttMs(cell.region), () => { - const live = cell.seats.get(host) - const wasLive = live !== undefined && !live.demoted - cell.demote(host, seat.epoch, seat.joinedAt, () => onSeatClosed(host, cellId, seat.epoch)) - if (!wasLive || !live.demoted) return - // Only a live seat demoted for a live level winner is a same-epoch duplicate resolved. - const winnerSeat = cellById.get(winner.cellId)?.seats.get(host) - if (winner.epoch === seat.epoch && winnerSeat?.epoch === winner.epoch && !winnerSeat.demoted) { - report.levelDemotions += 1 - } - demotedFor.set(`${host}\u0000${loser}`, won) - if (demotedFor.get(`${host}\u0000${won}`) === loser) violate(4, `${host}: ${loser} and ${won} each demoted for the other`) - }) - } - - function onSeatClosed(hostId: string, cellId: string, epoch: number): void { - const host = hostById.get(hostId)! - if (host.current?.cellId === cellId && host.current.epoch === epoch) { - host.current = null - clock.schedule(between(config.reconnectDelayMs), () => connect(host, true)) - } - } - - function flushLedger(director: SimDirector): void { - if (!database.up || director.ledgerQueue.length === 0) return - for (const entry of director.ledgerQueue) { - database.upsert(entry.host, entry.cellId, entry.epoch) - } - director.ledgerQueue = [] - } - - // Invariant 8: reconcile removes ahead/other-cell equal-row divergences; demoting director must then mint above the row. - const behindRow = new Map() - const rowAheadDemotionsByHost = new Map() - const demotedBehindRow = new Map() - // A host demoted behind its row: its next answer, from any director, is that row or above it. - const reassignAbove = new Map() - // Only under localTieBreak: even directors keep the lower cell id of a level divergence, odd ones the higher. - function faultKeepsThisSeat( - director: SimDirector, - cellId: string, - epoch: number, - row: { cellId: string; epoch: number } - ): boolean { - return !!faults.localTieBreak && row.epoch === epoch && (cellId < row.cellId) === (director.index % 2 === 0) - } - function raiseRowFloor(director: SimDirector, host: string, epoch: number): void { - director.rowFloors.set(host, Math.max(epoch, director.rowFloors.get(host) ?? 0)) - } - function reconcileLedger(director: SimDirector): void { - if (!database.up || director.old) return - for (const [cellId, view] of director.views) { - if (!view.placement.reserve) continue - for (const [host, seat] of view.seats) { - if (seat.demoted || clock.now - seat.joinedAt < RECONCILE_SETTLE_MS) continue - const row = database.rows.get(host) - const live = cellById.get(cellId)!.seats.get(host) - const diverged = row && (row.epoch > seat.epoch || (row.epoch === seat.epoch && row.cellId !== cellId)) - // Even demotions dropped by the cell must agree on winner; relay-server raises epoch floors on every demote. - if (row && diverged && live && live.joinedAt === seat.joinedAt && live.demoted && !faults.noRowAheadDemote) { - const thisSeat = { cellId, epoch: seat.epoch } - const rowSeat = { cellId: row.cellId, epoch: row.epoch } - if (faultKeepsThisSeat(director, cellId, seat.epoch, row)) judge(director, host, rowSeat, thisSeat) - else { - judge(director, host, thisSeat, rowSeat) - raiseRowFloor(director, host, row.epoch) - } - } - if (row && diverged && live && live.joinedAt === seat.joinedAt && !live.demoted) { - const key = `${director.id}\u0000${host}\u0000${cellId}\u0000${seat.joinedAt}` - if (behindRow.has(key)) violate(8, `${host}@${seat.epoch} on ${cellId} still behind row @${row.epoch}`) - behindRow.set(key, clock.now) - if (faults.noRowAheadDemote) continue - if (faultKeepsThisSeat(director, cellId, seat.epoch, row)) { - const rowSeat = director.views.get(row.cellId)?.seats.get(host) - if (rowSeat && rowSeat.epoch === row.epoch && !rowSeat.demoted) { - demoteFor(director, host, row.cellId, rowSeat, { cellId, epoch: seat.epoch }) - } - continue - } - report.rowAheadDemotions += 1 - raiseRowFloor(director, host, row.epoch) - rowAheadDemotionsByHost.set(host, (rowAheadDemotionsByHost.get(host) ?? 0) + 1) - // A director missing a leave can re-place level once; newer rows create new divergences, but one row must never take a third demotion. - const sameRow = `${host}\u0000${row.cellId}\u0000${row.epoch}` - const behindThisRow = (demotedBehindRow.get(sameRow) ?? 0) + 1 - demotedBehindRow.set(sameRow, behindThisRow) - if (behindThisRow > 2) violate(8, `${host} demoted ${behindThisRow} times behind its row ${row.cellId}@${row.epoch}`) - reassignAbove.set(host, { ...row }) - demoteFor(director, host, cellId, seat, row) - continue - } - database.upsert(host, cellId, seat.epoch) - } - } - } - - function reserveCall( - director: SimDirector, - cell: SimCell, - host: string, - epoch: number, - sticky: boolean - ): Promise { - const rtt = config.rttMs(cell.region) - return new Promise((resolve) => { - clock.schedule(rtt / 2, () => { - const outcome = cell.old ? { outcome: 'off' as const } : cell.reserve(director.id, host, epoch, sticky) - if (outcome.outcome === 'intake') report.intakeRefusals += 1 - if (outcome.outcome === 'off' && cell.trippedAt !== null) report.reserveCallsOnTrippedCells += 1 - clock.schedule(rtt / 2, () => resolve(outcome)) - }) - }) - } - - function databaseAssign(director: SimDirector, host: Host, floor: number): Answer { - if (!database.up) return { kind: 'retry', afterMs: 2_000, calls: 0 } - const row = database.rows.get(host.id) - // Fresh current-process raw db evidence overrides stale reserve stamp, even without feed polls. - const admitsDatabase = (cell: SimCell): boolean => { - const own = database.admitEffective.get(cell.cellId) - return ( - !faults.pgReserveBlocksDatabase && - own?.mode === 'db' && - own.incarnation === cell.incarnation && - clock.now - own.at <= CELL_ADMIT_EFFECTIVE_FRESH_MS - ) - } - const eligible = cells.filter((cell) => { - if (cell.draining) return false - if (!director.old && database.reserveCells.has(cell.cellId) && !admitsDatabase(cell)) return false - const count = cell.mode === 'reserve' ? cell.frozenDatabaseCount : database.countOn(cell.cellId) - return count < cell.ceiling - }) - const load = (cell: SimCell) => - (cell.mode === 'reserve' ? cell.frozenDatabaseCount : database.countOn(cell.cellId)) / cell.ceiling - const inRegion = eligible.filter((cell) => cell.region === host.region) - const pool = inRegion.length > 0 ? inRegion : eligible - if (pool.length === 0) { - // A cell that tripped 20 s ago (a 1 s write, a 5 s cached read, slack) must be takeable. - const stranded = cells.find( - (cell) => - !director.old && - !cell.old && - !cell.draining && - cell.trippedAt !== null && - cell.mode === 'db' && - clock.now - cell.trippedAt >= 20_000 && - database.countOn(cell.cellId) < cell.ceiling - ) - if (stranded) violate(9, `${host.id}: ${stranded.cellId} tripped but takes no fresh placement`) - return { kind: 'retry', afterMs: 5_000, calls: 0 } - } - const target = pool.reduce((best, cell) => (load(cell) < load(best) ? cell : best)) - const epoch = Math.max(row?.epoch ?? 0, faults.noEpochFloor ? 0 : floor) + 1 - if (!director.old && epoch <= floor) violate(7, `db mint ${epoch} not above map floor ${floor}`) - database.assign(host.id, target.cellId, epoch) - if (target.mode === 'reserve') target.frozenDatabaseCount += 1 - report.databasePlacements += 1 - const outage = (config.pollOutages ?? [])[0] - if (inPollOutage(clock.now)) { - report.databasePlacementsWhilePollsFail += 1 - if (outage && report.pollFailureGapMs === null) report.pollFailureGapMs = clock.now - outage.at - } - return { kind: 'cell', cellId: target.cellId, epoch, calls: 0 } - } - - async function assign(director: SimDirector, host: Host, reconnect: boolean): Promise { - report.requests += 1 - if (director.old) return databaseAssign(director, host, 0) - if (!director.complete(cells)) return { kind: 'retry', afterMs: 1_000, calls: 0 } - const now = clock.now - const rowFloor = director.rowFloors.get(host.id) - const known = [...director.knownEpochs(host.id), ...(rowFloor === undefined ? [] : [rowFloor])] - let floor: number - if (known.length > 0) { - floor = Math.max(...known) - // A WRONG_CELL leave, seen in the cell's feed by every director: read the row too. - if (director.recentlyLeft.get(host.id)?.wrongCell && !faults.noWrongCellRowRead && database.up) { - floor = Math.max(floor, database.rows.get(host.id)?.epoch ?? 0) - } - } else { - if (!database.up) return { kind: 'retry', afterMs: 2_000, calls: 0 } - floor = database.rows.get(host.id)?.epoch ?? 0 - } - if (reconnect) { - const found = stickyFromMemory(director, host, now) - // The seat the reconcile demoted (or one level with its row) is never answered again. - const sticky = found && rowFloor !== undefined && found.epoch <= rowFloor ? null : found - if (sticky) { - const cell = cellById.get(sticky.cellId)! - // Unpolled restarts leave a stale incarnation in the map; hello falls back to the DB check. - const view = director.views.get(sticky.cellId) - if (sticky.incarnation === view?.incarnation || cell.old) { - report.stickyAnswers += 1 - return { kind: 'cell', cellId: sticky.cellId, epoch: sticky.epoch, calls: 0 } - } - report.stickyReserves += 1 - const outcome = await reserveCall(director, cell, host.id, sticky.epoch, true) - if (outcome.outcome === 'ok') { - report.stickyAnswers += 1 - return { kind: 'cell', cellId: sticky.cellId, epoch: sticky.epoch, calls: 1 } - } - } - } - const placements = [...director.views.values()].map((view) => view.placement) - if (random() >= director.placer.reservePoolShare(placements, host.region)) { - return databaseAssign(director, host, floor) - } - const result = await director.placer.place({ - cells: placements, - region: host.region, - epoch: faults.mintAtFloor ? Math.max(1, floor) : mintEpoch([floor]), - reserve: (cellId, epoch) => reserveCall(director, cellById.get(cellId)!, host.id, epoch, false) - }) - report.reserveCalls += result.calls - if (result.calls > RESERVE_MAX_TRIES) violate(6, `${result.calls} reserve calls in one request`) - if (result.kind === 'placed') { - report.reservePlacements += 1 - supersede(director, host.id, result.cellId, result.epoch) - return { kind: 'cell', cellId: result.cellId, epoch: result.epoch, calls: result.calls } - } - if (result.calls === RESERVE_MAX_TRIES) report.exhausted += 1 - if (result.kind === 'pace') { - report.paced += 1 - return { kind: 'retry', afterMs: result.retryAfterSeconds * 1_000, calls: result.calls } - } - const fallback = databaseAssign(director, host, floor) - return fallback.kind === 'cell' ? { ...fallback, calls: result.calls } : fallback - } - - function stickyFromMemory(director: SimDirector, host: Host, now: number) { - // The newest grant only: highest epoch, then newest join. - const seats = [...director.views] - .map(([cellId, view]) => ({ cellId, view, seat: view.seats.get(host.id) })) - .filter((entry) => entry.seat && !entry.seat.demoted) - .sort((left, right) => right.seat!.epoch - left.seat!.epoch || right.seat!.joinedAt - left.seat!.joinedAt) - const top = seats[0] - if (top && stickyCell(director, top.view, now, true)) { - return { cellId: top.cellId, epoch: top.seat!.epoch, incarnation: top.view.incarnation ?? 0 } - } - if (top) return null - const left = director.recentlyLeft.get(host.id) - // A seat closed WRONG_CELL may not rejoin from memory. - if (left && !left.wrongCell && now - left.at <= RECENT_SEAT_MS) { - const view = director.views.get(left.cellId) - if (view && stickyCell(director, view, now, false)) { - return { cellId: left.cellId, epoch: left.epoch, incarnation: left.incarnation } - } - } - return null - } - - function stickyCell(director: SimDirector, view: DirectorCellView, now: number, seated: boolean): boolean { - const cell = view.placement - if (!cell.reserve || !cell.general || cell.draining || cell.polledAt === null) return false - if (now - cell.polledAt > RESERVE_CELL_FRESH_MS) return false - return seated || director.placer.hasSeat(cell) - } - - let directorCursor = 0 - function pickDirector(): SimDirector { - directorCursor = (directorCursor + 1 + Math.floor(random() * directors.length)) % directors.length - return directors[directorCursor]! - } - - // After the run, desktops stop moving so the maps and the ledger can settle. - let quiescing = false - function connect(host: Host, reconnect: boolean): void { - if (host.current || quiescing) return - const first = pickDirector() - const duplicate = random() < config.duplicateAssignShare ? pickDirector() : null - let used = false - const onAnswer = (answer: Answer, primary: boolean): void => { - if (answer.kind === 'retry') { - if (primary && !used) { - used = true - clock.schedule(answer.afterMs + random() * 500, () => connect(host, reconnect)) - } - return - } - if (used) return - used = true - clock.schedule(50 + random() * 250, () => hello(host, answer.cellId, answer.epoch, reconnect)) - } - // A throw in the model is a broken run, recorded like any violated rule. - const broken = (error: unknown) => violate(0, `model threw: ${String(error)}`) - void assign(first, host, reconnect) - .then((answer) => onAnswer(answer, true)) - .catch(broken) - if (duplicate) { - clock.schedule(random() * 500, () => { - void assign(duplicate, host, reconnect) - .then((answer) => onAnswer(answer, false)) - .catch(broken) - }) - } - } - - function hello(host: Host, cellId: string, epoch: number, reconnect: boolean): void { - const cell = cellById.get(cellId)! - if (host.current) return - const admitted = cell.hello(host.id, epoch, database) - if (!admitted) { - clock.schedule(1_000 + random() * 2_000, () => connect(host, reconnect)) - return - } - report.placements += 1 - report.arrivalsByCell[cellId] = (report.arrivalsByCell[cellId] ?? 0) + 1 - // Report first post-demotion seats behind/level with the row; stale-map directors may not have seen the leave. - const above = reassignAbove.get(host.id) - if (above !== undefined) { - reassignAbove.delete(host.id) - if (epoch < above.epoch || (epoch === above.epoch && cellId !== above.cellId)) report.badFirstReseats += 1 - } - host.current = { cellId, epoch } - scheduleLeave(host) - } - - for (const cell of cells) { - const windowMs = deadManWindowMs(cell.cellId) - const check = (): void => { - const wasReserve = cell.mode === 'reserve' - cell.checkDeadMan(windowMs, config.reregistrationMs ?? DEFAULT_REREGISTRATION_MS) - if (wasReserve && cell.mode === 'db') report.deadManTrips += 1 - // Model best-effort cell writes only with DB up and switch in reserve; db-mode cells write no admit row. - const own = database.admitEffective.get(cell.cellId) - if ( - !cell.old && - database.reserveCells.has(cell.cellId) && - !cell.flagsUnread && - database.up && - (!own || own.mode !== cell.mode || own.incarnation !== cell.incarnation || clock.now - own.at >= CELL_ADMIT_EFFECTIVE_REFRESH_MS) - ) { - database.admitEffective.set(cell.cellId, { mode: cell.mode, incarnation: cell.incarnation, at: clock.now }) - } - clock.schedule(1_000, check) - } - clock.schedule(1_000, check) - } - for (const director of directors) { - const tick = (): void => { - for (const cell of cells) poll(director, cell) - if (director.bootReconcilePending && director.complete(cells)) { - director.bootReconcilePending = false - reconcileLedger(director) - } - clock.schedule(1_000, tick) - } - clock.schedule(random() * 1_000, tick) - const ledger = (): void => { - flushLedger(director) - clock.schedule(250, ledger) - } - clock.schedule(250, ledger) - const reconcile = (): void => { - reconcileLedger(director) - clock.schedule(10 * 60_000 + random() * 60_000, reconcile) - } - // As on a real director: once at boot when the map is complete, then every 10 minutes. - director.bootReconcilePending = true - clock.schedule(10 * 60_000 + random() * 60_000, reconcile) - } - // A leased control's renewal fails once its row names another seat: the cell closes it. - for (const cell of cells) { - const renew = (): void => { - if (database.up) { - for (const [hostId, seat] of [...cell.seats]) { - const row = database.rows.get(hostId) - if (!seat.leased || !row || (row.cellId === cell.cellId && row.epoch === seat.epoch)) continue - cell.leave(hostId) - onSeatClosed(hostId, cell.cellId, seat.epoch) - } - } - clock.schedule(CONTROL_RENEWAL_MS, renew) - } - clock.schedule(random() * CONTROL_RENEWAL_MS, renew) - } - for (const cell of cells) { - const sweep = (): void => { - cell.book.sweep() - clock.schedule(1_000, sweep) - } - clock.schedule(1_000, sweep) - } - const fresh = hosts.slice(nextHost) - fresh.forEach((host, index) => { - clock.schedule((index / config.arrivalPerSec) * 1_000, () => connect(host, false)) - }) - for (const restart of config.cellRestarts ?? []) { - clock.schedule(restart.at, () => { - const cell = cellById.get(restart.cellId)! - for (const hostId of cell.restart()) { - const host = hostById.get(hostId)! - if (host.current?.cellId !== cell.cellId) continue - host.current = null - clock.schedule(random() * 10_000, () => connect(host, true)) - } - }) - } - for (const restart of config.directorRestarts ?? []) { - clock.schedule(restart.at, () => { - const director = directors[restart.director]! - director.reset() - director.restarted = true - director.bootReconcilePending = !faults.noBootReconcile - report.directorRestarts += 1 - }) - } - for (const stall of config.databaseStalls ?? []) { - clock.schedule(stall.at, () => { - database.up = false - clock.schedule(stall.durationMs, () => { - database.up = true - }) - }) - } - for (const drain of config.drains ?? []) { - clock.schedule(drain.at, () => { - const cell = cellById.get(drain.cellId)! - cell.draining = true - const seated = [...cell.seats.keys()] - seated.forEach((hostId, index) => { - clock.schedule((index / Math.max(1, seated.length - 1)) * drain.paceMs, () => { - const host = hostById.get(hostId)! - const seat = cell.seats.get(hostId) - if (!seat) return - // Drain-only: the seat keeps its splices for the grace while the desktop moves on. - clock.schedule(DRAIN_GRACE_MS, () => { - if (cell.seats.get(hostId) === seat) cell.leave(hostId) - }) - if (host.current?.cellId === cell.cellId) { - host.current = null - clock.schedule(1_000 + random() * 5_000, () => connect(host, true)) - } - }) - }) - }) - } - - const afterEach = (): void => { - for (const cell of cells) { - if (cell.occupancy() > cell.hardCap) { - violate(1, `${cell.cellId} at ${cell.occupancy()} over hard cap ${cell.hardCap}`) - } - const share = cell.occupancy() / cell.hardCap - report.maxOccupancyShare[cell.cellId] = Math.max(report.maxOccupancyShare[cell.cellId] ?? 0, share) - } - } - // Mapped/booked or feed-outranked seats have a short supersede bound; unleased half-open duplicates missed by placement can last until silence close. - const supersedeBound = - Math.max(...directors.map((director) => config.pollLagMs(director.index))) + - 2 * Math.max(...cells.map((cell) => config.rttMs(cell.region))) + - 3_000 - const duplicateBound = CONTROL_SILENCE_CLOSE_MS + 2 * Math.max(...cells.map((cell) => config.rttMs(cell.region))) + 1_000 - // Invariant 3 bounds outranked reserve seats; database-mode duplicates use existing lease renewal. - const outrankedSince = new Map() - const checkDuplicates = (): void => { - const seatsByHost = new Map>() - for (const cell of cells) { - for (const [host, seat] of cell.seats) { - if (seat.demoted) continue - const seats = seatsByHost.get(host) ?? [] - seats.push({ cell, seat }) - seatsByHost.set(host, seats) - } - } - const live = new Set() - for (const [host, seats] of seatsByHost) { - if (seats.length < 2) continue - const newest = Math.max(...seats.map((entry) => entry.seat.epoch)) - // By the newest seats' placement records, whatever their join says: no record, no supersede. - const bookings = seats - .filter((entry) => entry.seat.epoch === newest) - .flatMap((entry) => heldAtBooking.get(`${host}\u0000${entry.cell.cellId}\u0000${newest}`) ?? []) - const supersededBy = (cellId: string, joinedAt: number): boolean => - bookings.some((held) => held.has(`${cellId}\u0000${joinedAt}`)) - for (const { cell, seat } of seats) { - if (cell.mode !== 'reserve' || seat.epoch === newest) continue - // A leased seat goes by its renewal, as today. - const tight = - !seat.leased && - (supersededBy(cell.cellId, seat.joinedAt) || seats.some((other) => seatOutranks(other.seat, seat))) - // The loose clock runs from the first outranking; the tight one from when supersede applies. - const key = `${host}\u0000${cell.cellId}\u0000${seat.joinedAt}` - const clocks: Array<[string, number]> = [[key, duplicateBound]] - if (tight) clocks.push([`${key}\u0000tight`, supersedeBound]) - for (const [clockKey, bound] of clocks) { - live.add(clockKey) - const since = outrankedSince.get(clockKey) ?? clock.now - outrankedSince.set(clockKey, since) - if (clock.now - since > bound) { - violate(3, `${host}@${seat.epoch} on ${cell.cellId} outranked for ${clock.now - since} ms`) - } - } - } - } - for (const key of [...outrankedSince.keys()]) if (!live.has(key)) outrankedSince.delete(key) - clock.schedule(1_000, checkDuplicates) - } - clock.schedule(1_000, checkDuplicates) - - await clock.runUntil(config.durationMs, afterEach) - quiescing = true - await clock.runUntil(config.durationMs + QUIESCE_MS, afterEach) - - // Invariant 2: no window holds more ok bookings than burst + rate x window. - for (const cell of cells) { - for (const times of cell.okBookingTimes) { - let lowest = Infinity - times.forEach((at, index) => { - lowest = Math.min(lowest, index - (cell.intakePerSec * at) / 1_000) - const excess = index - (cell.intakePerSec * at) / 1_000 - lowest + 1 - if (excess > CELL_INTAKE_BURST + 1e-6) { - violate(2, `${cell.cellId} booked ${excess.toFixed(2)} over its bucket`) - } - }) - } - } - // Invariant 5: guarded mirror must converge through queues/boot/ten-minute reconciles, with no final reconcile hiding lost writes. - database.up = true - for (const director of directors) flushLedger(director) - for (const cell of cells) { - if (cell.mode !== 'reserve') continue - for (const [host, seat] of cell.seats) { - if (seat.demoted) continue - const otherSeat = cells.some( - (other) => other !== cell && other.seats.get(host) && !other.seats.get(host)!.demoted - ) - if (otherSeat) continue - const row = database.rows.get(host) - if (!row || row.epoch < seat.epoch) { - violate(5, `${host} row ${JSON.stringify(row)} is below its seat ${cell.cellId}@${seat.epoch}`) - } - } - } - report.seatedAtEnd = cells.reduce((sum, cell) => sum + cell.seats.size, 0) - const perHost = [...rowAheadDemotionsByHost.values()].sort((left, right) => left - right) - report.rowAheadDemotionsPerHost = { - max: perHost.at(-1) ?? 0, - p99: perHost[Math.min(perHost.length - 1, Math.floor(perHost.length * 0.99))] ?? 0 - } - return report -} diff --git a/cloud/apps/relay/src/authentication/stale-if-error-jwks.test.ts b/cloud/apps/relay/src/authentication/stale-if-error-jwks.test.ts index c1d3b1e3ac6..c53c3fd43d5 100644 --- a/cloud/apps/relay/src/authentication/stale-if-error-jwks.test.ts +++ b/cloud/apps/relay/src/authentication/stale-if-error-jwks.test.ts @@ -2,7 +2,7 @@ import { exportJWK, generateKeyPair, SignJWT, type CryptoKey, type JWK } from 'j import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RelayConfig } from '../config.js' import { createRelayTokenVerifier } from './relay-token-verifier.js' -import { createStaleIfErrorJWKSet, RELAY_JWKS_MAX_STALE_MS } from './stale-if-error-jwks.js' +import { createStaleIfErrorJWKSet } from './stale-if-error-jwks.js' const config = { jwksUrl: 'https://auth.example.test/.well-known/jwks.json', @@ -43,37 +43,7 @@ beforeEach(() => vi.useFakeTimers({ now: Date.parse('2026-10-11T13:00:00Z') })) afterEach(() => vi.useRealTimers()) describe('relay token keys while auth is down', () => { - it('accepts a valid token from the last served set once the cache is past its 10 min age', async () => { - const key = await signingKey('auth-1') - const authServer = auth(key) - const jwks = createStaleIfErrorJWKSet(new URL(config.jwksUrl), { fetch: authServer.fetch }) - const verify = createRelayTokenVerifier(config as RelayConfig, jwks) - expect(await verify(await relayToken(key))).not.toBeNull() - - vi.setSystemTime(Date.now() + 20 * MINUTE) - authServer.state.up = false - const fetches = authServer.fetch.mock.calls.length - expect(await verify(await relayToken(key))).toMatchObject({ sub: 'user-1' }) - expect(authServer.fetch.mock.calls.length).toBe(fetches + 1) - // Inside the retry window the stale set answers without waiting on another fetch. - expect(await verify(await relayToken(key))).not.toBeNull() - expect(authServer.fetch.mock.calls.length).toBe(fetches + 1) - }) - - it('rejects a token signed by a key the last served set never had', async () => { - const key = await signingKey('auth-1') - const authServer = auth(key) - const jwks = createStaleIfErrorJWKSet(new URL(config.jwksUrl), { fetch: authServer.fetch }) - const verify = createRelayTokenVerifier(config as RelayConfig, jwks) - expect(await verify(await relayToken(key))).not.toBeNull() - - vi.setSystemTime(Date.now() + MINUTE) - authServer.state.up = false - expect(await verify(await relayToken(await signingKey('unknown')))).toBeNull() - }) - it('bounds the stale set at 30 minutes since the last served set', async () => { - expect(RELAY_JWKS_MAX_STALE_MS).toBe(30 * MINUTE) const key = await signingKey('auth-1') const authServer = auth(key) const verify = createRelayTokenVerifier( diff --git a/cloud/apps/relay/src/cell/admission/cell-admission-startup-postgres.test.ts b/cloud/apps/relay/src/cell/admission/cell-admission-startup-postgres.test.ts deleted file mode 100644 index 4bf8a09bb7a..00000000000 --- a/cloud/apps/relay/src/cell/admission/cell-admission-startup-postgres.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import pg from 'pg' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { RelayAssignmentStore } from '../../assignment/assignment-store.js' -import { reconcileCellAdmissionAtStartup } from './cell-admission-startup.js' -import type { RelayCellConfig } from '../../config.js' -import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip -const schema = 'relay_startup_retry_test' -const cell: RelayCellConfig = { - id: 'startup-retry-cell', - url: 'https://startup-retry.example.test', - capacityRequests: 4_000 -} - -afterEach(() => vi.restoreAllMocks()) - -describePostgres('PostgreSQL director startup reconciliation', () => { - const databases: RelayDatabase[] = [] - let scopedDatabaseUrl = '' - - beforeAll(async () => { - const client = new pg.Client({ connectionString: databaseUrl }) - await client.connect() - try { - await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) - await client.query(`CREATE SCHEMA ${schema}`) - } finally { - await client.end() - } - const url = new URL(databaseUrl!) - url.searchParams.set('options', `-c search_path=${schema}`) - scopedDatabaseUrl = url.toString() - databases.push( - await openRelayDatabase({ databaseUrl: scopedDatabaseUrl, dataDir: '' }), - await openRelayDatabase({ databaseUrl: scopedDatabaseUrl, dataDir: '' }) - ) - }) - - afterAll(async () => { - for (const database of databases) await database.close() - const client = new pg.Client({ connectionString: databaseUrl }) - await client.connect() - try { - await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) - } finally { - await client.end() - } - }) - - it('recovers after the cell inventory lock outlasts transaction retries', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const store = new RelayAssignmentStore(databases[0]!, () => 100) - await store.reconcileCells([cell], false) - let releaseLock: () => void = () => undefined - let reportLocked: () => void = () => undefined - const lockReleased = new Promise((resolve) => (releaseLock = resolve)) - const lockAcquired = new Promise((resolve) => (reportLocked = resolve)) - const holder = databases[1]!.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT cell_id FROM relay_cells ORDER BY cell_id ASC`) - reportLocked() - await lockReleased - }) - await lockAcquired - - const releaseTimer = setTimeout(releaseLock, 3_500) - try { - await reconcileCellAdmissionAtStartup({ role: 'director', cells: [cell] }, store) - } finally { - clearTimeout(releaseTimer) - releaseLock() - await holder - } - - expect(await databases[0]!.query(`SELECT cell_id FROM relay_cells`)).toEqual([ - { cell_id: cell.id } - ]) - const warnings = warn.mock.calls.flat().join('\n') - expect(warnings).toContain('orca_relay_startup_reconcile_recovered') - expect(warnings).not.toContain('orca_relay_postgres_transaction_exhausted') - }, 10_000) -}) diff --git a/cloud/apps/relay/src/cell/admission/cell-admission-startup.test.ts b/cloud/apps/relay/src/cell/admission/cell-admission-startup.test.ts deleted file mode 100644 index a08f429cc0d..00000000000 --- a/cloud/apps/relay/src/cell/admission/cell-admission-startup.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - reconcileCellAdmissionAtStartup -} from './cell-admission-startup.js' -import type { RelayCellConfig } from '../../config.js' - -const cells: RelayCellConfig[] = [ - { - id: 'candidate', - url: 'https://candidate.relay.example.com', - capacityRequests: 4_000, - initiallyEnabled: false - } -] - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() -}) - -describe('cell admission startup authority', () => { - - it('bounds retry wall time when each reconciliation is slow', async () => { - vi.useFakeTimers() - vi.setSystemTime(0) - vi.spyOn(Math, 'random').mockReturnValue(0) - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const lockUnavailable = Object.assign(new Error('lock unavailable'), { code: '55P03' }) - const reconcileCellsAtStartup = vi.fn().mockImplementation(async () => { - vi.setSystemTime(Date.now() + 10_000) - throw lockUnavailable - }) - - const startup = reconcileCellAdmissionAtStartup( - { role: 'director', cells }, - { reconcileCellsAtStartup } - ) - const rejection = expect(startup).rejects.toBe(lockUnavailable) - await vi.runAllTimersAsync() - await rejection - - expect(reconcileCellsAtStartup).toHaveBeenCalledTimes(5) - }) -}) diff --git a/cloud/apps/relay/src/cell/admission/cell-connection-cap-postgres.test.ts b/cloud/apps/relay/src/cell/admission/cell-connection-cap-postgres.test.ts deleted file mode 100644 index 0c5f505655c..00000000000 --- a/cloud/apps/relay/src/cell/admission/cell-connection-cap-postgres.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from '../../assignment/assignment-store.js' -import type { RelayCellConfig } from '../../config.js' -import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip -const CELL_PREFIX = 'connection-cap-min-postgres' -const FLEET_SIZE = 16 - -function cellConfig(id: string, connectionHardCap: 1_000 | 3_000): RelayCellConfig { - return { - id, - url: `https://${id}.example.com`, - capacityRequests: 1_000, - connectionHardCap, - connectionUnobservedBound: 60 - } -} - -async function removeCells(database: RelayDatabase): Promise { - for (const table of [ - 'relay_cell_connection_snapshots', - 'relay_cell_connection_runtime', - 'relay_cell_connection_limits', - 'relay_cell_capabilities', - 'relay_cell_rehome_safety', - 'relay_cell_runtime', - 'relay_cell_admission', - 'relay_cell_regions', - 'relay_cells' - ]) { - await database.query(`DELETE FROM ${table} WHERE cell_id LIKE ?`, [`${CELL_PREFIX}-%`]) - } -} - -function storeOn(database: RelayDatabase): RelayAssignmentStore { - return new RelayAssignmentStore(database, () => 100, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) -} - -async function heartbeat( - store: RelayAssignmentStore, - cell: RelayCellConfig, - connectionHardCap: number, - units: number -): Promise { - await store.recordCellHeartbeat({ - cellId: cell.id, - cellUrl: cell.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: units, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: units, - connectionHardCap, - connectionUnobservedBound: 60 - }) -} - -describePostgres('PostgreSQL effective connection cap', () => { - let database: RelayDatabase - let racer: RelayDatabase - - beforeAll(async () => { - database = await openRelayDatabase({ databaseUrl, dataDir: '' }) - racer = await openRelayDatabase({ databaseUrl, dataDir: '' }) - await removeCells(database) - }) - - afterAll(async () => { - await removeCells(database) - await racer.close() - await database.close() - }) - - it('keeps 16 raised cells placeable while a heartbeat races the raise', async () => { - const ids = Array.from({ length: FLEET_SIZE }, (_, index) => `${CELL_PREFIX}-fleet-${index}`) - const lower = ids.map((id) => cellConfig(id, 1_000)) - const director = storeOn(database) - const otherInstance = storeOn(racer) - await director.reconcileCells(lower, true) - for (const cell of lower) await heartbeat(director, cell, 1_000, 10) - - // The heartbeat lands before or after the raise; either order must leave the same state. - await Promise.all([ - director.reconcileCells( - ids.map((id) => cellConfig(id, 3_000)), - true - ), - heartbeat(otherInstance, lower[0]!, 1_000, 11) - ]) - - for (const id of ids) { - await expect(director.cellDeploymentStatus(id)).resolves.toMatchObject({ - connectionCapacity: { - hardCap: 3_000, - reportedHardCap: 1_000, - effectiveHardCap: 1_000, - heartbeatFresh: true - } - }) - const rows = await database.query( - `SELECT cell_id FROM relay_cell_connection_snapshots WHERE cell_id = ?`, - [id] - ) - expect(rows).toHaveLength(1) - } - // The old processes keep heartbeating their 1,000 under the raised config. - for (const cell of lower) { - await expect(heartbeat(otherInstance, cell, 1_000, 12)).resolves.toBeUndefined() - } - }) -}) diff --git a/cloud/apps/relay/src/cell/cell-heartbeat-client.test.ts b/cloud/apps/relay/src/cell/cell-heartbeat-client.test.ts deleted file mode 100644 index 4c1072d62df..00000000000 --- a/cloud/apps/relay/src/cell/cell-heartbeat-client.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RelayConfig } from '../config.js' -import { startCellHeartbeat } from './cell-heartbeat-client.js' - -const CONFIG = { - role: 'cell', - cellId: 'cell-a', - cellUrl: 'https://relay-a.example.com', - directorUrl: 'https://relay.example.com', - heartbeatAudience: 'https://relay.example.com/v1/admin/cell-heartbeat' -} as RelayConfig - -describe('cell heartbeat client', () => { - afterEach(() => vi.restoreAllMocks()) - - it('sends an immediate authenticated heartbeat without putting credentials in the URL', async () => { - const requests: Array<{ url: string; init?: RequestInit }> = [] - const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { - requests.push({ url: String(url), init }) - return new Response('{}', { status: 200 }) - }) as typeof fetch - const client = startCellHeartbeat(CONFIG, { - ready: async () => true, - observedRequests: () => 7, - connectionCounts: () => ({ - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0 - }), - fetch: fetchImpl, - identityToken: async () => 'secret-token', - now: () => 123, - incarnation: '11111111-1111-4111-8111-111111111111', - intervalMs: 60_000 - })! - await vi.waitFor(() => expect(requests).toHaveLength(1)) - client.stop() - - expect(requests[0]!.url).toBe('https://relay.example.com/v1/admin/cell-heartbeat') - expect(requests[0]!.url).not.toContain('secret-token') - expect(requests[0]!.init?.headers).toMatchObject({ authorization: 'Bearer secret-token' }) - expect(JSON.parse(String(requests[0]!.init?.body))).toEqual({ - v: 1, - cellId: 'cell-a', - cellUrl: 'https://relay-a.example.com', - region: 'us-central1', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 123, - ready: true, - observedRequests: 7 - }) - }) - -}) diff --git a/cloud/apps/relay/src/cell/control-flags/relay-control-flag-channel.test.ts b/cloud/apps/relay/src/cell/control-flags/relay-control-flag-channel.test.ts index b4d1673f9b1..6e6eeee42c8 100644 --- a/cloud/apps/relay/src/cell/control-flags/relay-control-flag-channel.test.ts +++ b/cloud/apps/relay/src/cell/control-flags/relay-control-flag-channel.test.ts @@ -5,7 +5,7 @@ import { cellFlagObjectName, cellFlagParser } from './cell-flags.js' -import { CONTROL_FLAG_POLL_MS, startControlFlagChannel } from './relay-control-flag-channel.js' +import { startControlFlagChannel } from './relay-control-flag-channel.js' const CELL_ID = 'production-gce-c7' const ACCESS_TOKEN = 'ya29.secret-access-token' @@ -46,7 +46,7 @@ function cellObject(generation: number, flags: Record, cellId = } } -function cellChannel(fetchImpl: typeof fetch, autoStart = false) { +function cellChannel(fetchImpl: typeof fetch) { return startControlFlagChannel({ objectName: cellFlagObjectName(CELL_ID), defaults: CELL_FLAG_DEFAULTS, @@ -54,7 +54,7 @@ function cellChannel(fetchImpl: typeof fetch, autoStart = false) { appliedEvent: CELL_FLAGS_APPLIED_EVENT, fetch: fetchImpl, random: () => 0.5, - autoStart + autoStart: false }) } @@ -230,19 +230,4 @@ describe('control flag channel', () => { expect(channel.applied()).toMatchObject({ generation: 5, flags: { readinessLocal: true } }) }) - it('reads one at a time and on a jittered 5 s cadence', async () => { - vi.useFakeTimers() - const google = fakeGoogle(cellObject(5, { readinessLocal: true })) - const channel = cellChannel(google.fetchImpl) - await Promise.all([channel.poll(), channel.poll()]) - expect(google.state.storageRequests).toHaveLength(1) - const running = cellChannel(google.fetchImpl, true) - await vi.advanceTimersByTimeAsync(0) - expect(google.state.storageRequests).toHaveLength(2) - await vi.advanceTimersByTimeAsync(CONTROL_FLAG_POLL_MS) - expect(google.state.storageRequests).toHaveLength(3) - running.stop() - await vi.advanceTimersByTimeAsync(CONTROL_FLAG_POLL_MS * 3) - expect(google.state.storageRequests).toHaveLength(3) - }) }) diff --git a/cloud/apps/relay/src/cell/reservations/cell-admit-effective-writer.test.ts b/cloud/apps/relay/src/cell/reservations/cell-admit-effective-writer.test.ts index a99895f9a29..eedf29bc139 100644 --- a/cloud/apps/relay/src/cell/reservations/cell-admit-effective-writer.test.ts +++ b/cloud/apps/relay/src/cell/reservations/cell-admit-effective-writer.test.ts @@ -4,69 +4,34 @@ import { CellAdmitEffectiveWriter, DEAD_MAN_SLOT_CLAIM_RETRY_MS } from './cell-admit-effective-writer.js' -import { DEAD_MAN_SLOT_HOLD_MS } from './cell-dead-man-trip-slot.js' function setup( - options: { fail?: boolean; busy?: boolean; busyWhen?: () => boolean; slotFree?: () => boolean } = {} + options: { slotFree?: () => boolean } = {} ) { const clock = { value: 1_000 } const writes: ('db' | 'reserve' | 'claim')[] = [] const pending: Array<() => void> = [] - const logs: string[] = [] const writer = new CellAdmitEffectiveWriter({ write: async (mode) => { writes.push(mode) await new Promise((resolve) => pending.push(resolve)) - if (options.fail) throw new Error('connection refused') }, claimTrip: async (slots) => { writes.push('claim') await new Promise((resolve) => pending.push(resolve)) return slots > 0 && (options.slotFree?.() ?? true) }, - databaseBusy: () => options.busy === true || options.busyWhen?.() === true, - now: () => clock.value, - log: (line) => logs.push(line) + databaseBusy: () => false, + now: () => clock.value }) const settle = async () => { while (pending.length > 0) pending.shift()!() await new Promise((resolve) => setTimeout(resolve, 0)) } - return { clock, writes, logs, writer, settle } + return { clock, writes, writer, settle } } describe('CellAdmitEffectiveWriter', () => { - it('writes on the first tick, on every change, and every 15 s, one write at a time', async () => { - const { clock, writes, writer, settle } = setup() - writer.tick('reserve', true) - writer.tick('db', true) - expect(writes).toEqual(['reserve']) - await settle() - // Tripped: the switch still says reserve, the raw mode db. - writer.tick('db', true) - await settle() - writer.tick('db', true) - expect(writes).toEqual(['reserve', 'db']) - clock.value += CELL_ADMIT_EFFECTIVE_REFRESH_MS - writer.tick('db', true) - expect(writes).toEqual(['reserve', 'db', 'db']) - }) - - // Step 5 off: a db switch never writes, so the dark roll adds no database write. - - // Best-effort: a failed write never throws into the cell, logs at most once a minute, and retries. - it('retries a failed write on the next tick and rate-limits its log line', async () => { - const { clock, writes, logs, writer, settle } = setup({ fail: true }) - writer.tick('db', true) - await settle() - clock.value += 1_000 - writer.tick('db', true) - await settle() - expect(writes).toEqual(['db', 'db']) - expect(logs).toHaveLength(1) - expect(JSON.parse(logs[0]!)).toMatchObject({ event: 'orca_relay_cell_admit_effective_write_failed', mode: 'db' }) - }) - it('claims a held trip slot in place of its refresh, and permits the trip only once it lands', async () => { let free = false const { clock, writes, writer, settle } = setup({ slotFree: () => free }) @@ -97,20 +62,4 @@ describe('CellAdmitEffectiveWriter', () => { expect(writes).toEqual(['reserve', 'claim', 'reserve', 'claim']) }) - it('refreshes a tripped row past a saturated pool before its slot hold runs out', async () => { - let busy = false - const { clock, writes, writer, settle } = setup({ busyWhen: () => busy }) - writer.tick('db', true) - await settle() - busy = true - clock.value += 4 * 60_000 - writer.tick('db', true) - expect(writes).toEqual(['db']) - clock.value += 60_000 - writer.tick('db', true) - await settle() - expect(writes).toEqual(['db', 'db']) - expect(DEAD_MAN_SLOT_HOLD_MS).toBeGreaterThan(5 * 60_000) - }) - }) diff --git a/cloud/apps/relay/src/cell/reservations/cell-reserve-admission.blackbox.test.ts b/cloud/apps/relay/src/cell/reservations/cell-reserve-admission.blackbox.test.ts index 19c12f7be9e..5912b51472d 100644 --- a/cloud/apps/relay/src/cell/reservations/cell-reserve-admission.blackbox.test.ts +++ b/cloud/apps/relay/src/cell/reservations/cell-reserve-admission.blackbox.test.ts @@ -8,8 +8,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import WebSocket from 'ws' import type { RawData } from 'ws' import { CELL_FLAG_DEFAULTS, type CellFlags } from '../control-flags/cell-flags.js' -import { CELL_SEAT_DRIFT_SWEEP_MS } from '../seats/cell-seat-drift.js' -import type { CellSeatLog } from '../seats/cell-seat-log.js' import type { RelayConfig } from '../../config.js' import { PostgresDatabase } from '../../database/database.js' import type { AppliedControlFlags } from '../control-flags/relay-control-flag-channel.js' @@ -73,20 +71,6 @@ function cellConfig(port: number, issuer: string): RelayConfig { } } -// The registry's private feed log, to plant the drift the cell must repair. -function seatLogOf(sessions: object): CellSeatLog { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: HostSessionRegistry holds its feed log as `seatLog`. - return (sessions as { seatLog: CellSeatLog }).seatLog -} - -// The JSON lines a test's console.warn spy saw for one event. -function warned(event: string): Array> { - return vi - .mocked(console.warn) - .mock.calls.map(([line]) => (typeof line === 'string' && line.startsWith('{') ? JSON.parse(line) : null)) - .filter((entry) => entry?.event === event) -} - function nextMessage(socket: WebSocket): Promise> { return new Promise((resolve, reject) => { socket.once('message', (data: RawData) => { @@ -265,9 +249,6 @@ describe('a reserve-mode cell admits from memory with its database wedged', () = book, setFlags: (next: Partial) => { applied = { generation: applied.generation + 1, flags: { ...CELL_FLAG_DEFAULTS, ...next } } - }, - advance: (ms: number) => { - elapsedMs += ms } } } @@ -338,97 +319,6 @@ describe('a reserve-mode cell admits from memory with its database wedged', () = return (page as { full: Array<{ relayHostId: string; epoch: number }> }).full.map((entry) => entry.epoch) } - it('repairs at once the seat a director names when no session backs it', async () => { - const cell = await startCell({ admitMode: 'reserve' }) - const identity = await cell.host() - cell.book(identity, 9) - await cell.connect(identity, 9) - // A stale seat at a generation above the live session's: its changes could never replace it. - const log = seatLogOf(cell.relay.sessions) - log.append({ kind: 'join', userId: 'user-1', relayHostId: identity.hostId, epoch: 8, generation: 5, at: 4_242 }) - const before = cell.relay.sessions.seatFeed(null) - const seq = 'full' in before ? before.seq : 0 - const seat = { v: 1 as const, userId: 'user-1', relayHostId: identity.hostId, epoch: 8, joinedAt: 4_242 } - expect(cell.relay.sessions.demote(seat)).toBe('not-seated') - expect(cell.relay.sessions.seatFeed(seq)).toMatchObject({ - changes: [ - { kind: 'leave', epoch: 8, generation: 5, closeCode: 4409 }, - { kind: 'join', epoch: 9, generation: 1 } - ] - }) - expect(seatEpochs(cell)).toEqual([9]) - expect(warned('orca_relay_cell_seat_log_drift')).toMatchObject([ - { kind: 'unbacked-seat', via: 'demote', reason: 'epoch', seatEpoch: 8, sessionEpoch: 9, relisted: true } - ]) - expect(JSON.stringify(warned('orca_relay_cell_seat_log_drift'))).not.toContain(identity.hostId) - // Asked again, there is nothing left to repair. - expect(cell.relay.sessions.demote(seat)).toBe('not-seated') - expect(cell.relay.sessions.seatFeed(seq + 2)).toMatchObject({ changes: [] }) - }) - - it('leaves a seat no session backs once two sweeps in a row find it, with no director asking', async () => { - const cell = await startCell({ admitMode: 'db' }) - const ghost = await cell.host() - seatLogOf(cell.relay.sessions).append({ - kind: 'join', - userId: 'user-1', - relayHostId: ghost.hostId, - epoch: 10, - generation: 3, - at: 1_000 - }) - expect(seatEpochs(cell)).toEqual([10]) - cell.advance(CELL_SEAT_DRIFT_SWEEP_MS) - expect(seatEpochs(cell)).toEqual([]) - expect(warned('orca_relay_cell_seat_log_drift')).toMatchObject([ - { kind: 'unbacked-seat', via: 'sweep', reason: 'no-session', seatEpoch: 10, seatGeneration: 3, relisted: false } - ]) - // Left as moved: the cell will not seat it again at 10 from memory. - expect(cell.relay.sessions.seatFeed(0)).toMatchObject({ changes: [{}, { kind: 'leave', closeCode: 4409 }] }) - }) - - it('lists again a live session the feed lost, once two sweeps in a row find it', async () => { - const cell = await startCell({ admitMode: 'reserve' }) - const identity = await cell.host() - cell.book(identity, 9) - await cell.connect(identity, 9) - seatLogOf(cell.relay.sessions).append({ - kind: 'leave', - userId: 'user-1', - relayHostId: identity.hostId, - epoch: 9, - generation: 1, - at: 5_000 - }) - expect(seatEpochs(cell)).toEqual([]) - cell.advance(CELL_SEAT_DRIFT_SWEEP_MS) - expect(seatEpochs(cell)).toEqual([9]) - expect(warned('orca_relay_cell_seat_log_drift')).toMatchObject([{ kind: 'unlisted-session', sessionEpoch: 9 }]) - }) - - // A drained session's seat stays listed, with no session, until its socket's close lands. - it('repairs nothing for a seat that one sweep finds unbacked and is gone by the next', async () => { - const cell = await startCell({ admitMode: 'reserve' }) - const identity = await cell.host() - cell.book(identity, 9) - const live = await cell.connect(identity, 9) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ws keeps its net.Socket as `_socket`. - ;(live.socket as unknown as { _socket: { pause(): void } })._socket.pause() - cell.relay.sessions.drainHost({ - attemptId: 'attempt-1', - userId: 'user-1', - relayHostId: identity.hostId, - sourceAssignmentEpoch: 9, - graceMs: 0 - }) - await new Promise((resolve) => setTimeout(resolve, 20)) - expect(seatEpochs(cell)).toEqual([9]) - await new Promise((resolve) => setTimeout(resolve, RELAY_WEBSOCKET_FORCE_CLOSE_MS + 300)) - cell.advance(CELL_SEAT_DRIFT_SWEEP_MS) - expect(seatEpochs(cell)).toEqual([]) - expect(warned('orca_relay_cell_seat_log_drift')).toEqual([]) - }, 10_000) - // Drained sockets can close seconds after map removal; reusing their generation let late leaves erase reconnected live seats. it('keeps a session that reconnected while its drained predecessor was still closing', async () => { const cell = await startCell({ admitMode: 'reserve' }) @@ -456,19 +346,6 @@ describe('a reserve-mode cell admits from memory with its database wedged', () = expect(seatEpochs(cell)).toEqual([10]) }, 10_000) - // Repeated fresh joins for one identity replace session and seat together, leaving no drift to repair. - it('stays on the live session when the same identity connects afresh each turn', async () => { - const cell = await startCell({ admitMode: 'reserve' }) - const identity = await cell.host() - for (const epoch of [9, 10, 11]) { - cell.book(identity, epoch) - expect((await cell.connect(identity, epoch)).ack).toMatchObject({ type: 'host-hello-ack' }) - expect(seatEpochs(cell)).toEqual([epoch]) - cell.advance(CELL_SEAT_DRIFT_SWEEP_MS) - } - expect(seatEpochs(cell)).toEqual([11]) - expect(warned('orca_relay_cell_seat_log_drift')).toEqual([]) - }) }) it('gives every booking unit back when the cell starts to drain', async () => { @@ -542,44 +419,4 @@ describe('a reserve-mode cell admits from memory with its database wedged', () = }).toEqual(before) }, 30_000) - it('never crosses the hard cap under seeded bookings, hellos, rebooks and closes', async () => { - const hardCap = 6 - const cell = await startCell({ admitMode: 'reserve' }, { hardCap, controlReserve: 1 }) - const hosts = await Promise.all(Array.from({ length: 12 }, () => cell.host())) - const epochs = new Map() - const open: WebSocket[] = [] - let seed = 7 - const random = () => { - seed = (seed * 1_103_515_245 + 12_345) % 2_147_483_648 - return seed / 2_147_483_648 - } - let peak = 0 - for (let step = 0; step < 240; step += 1) { - const identity = hosts[Math.floor(random() * hosts.length)]! - const roll = random() - if (roll < 0.4) { - // A director's fresh booking, or a re-book at a newer epoch. - const epoch = (epochs.get(identity.hostId) ?? 1) + (random() < 0.5 ? 0 : 1) - if (cell.book(identity, epoch)[0]?.outcome === 'ok') epochs.set(identity.hostId, epoch) - } else if (roll < 0.8) { - const reply = await cell.connect(identity, epochs.get(identity.hostId) ?? 1) - if (reply.ack?.type === 'host-hello-ack') open.push(reply.socket!) - } else if (open.length > 0) { - const socket = open.splice(Math.floor(random() * open.length), 1)[0]! - // A newer control for the same host may already have replaced it. - if (socket.readyState !== WebSocket.CLOSED) { - const closed = new Promise((resolve) => socket.once('close', resolve)) - socket.close() - await closed - } - } - const counts = cell.relay.connectionSnapshot()! - peak = Math.max(peak, counts.physicalConnections) - expect(counts.physicalConnections).toBeLessThanOrEqual(hardCap) - expect(counts.enforcedConnectionUnits).toBeLessThanOrEqual(hardCap) - } - // The run did reach the cap, so the bound was exercised. - expect(peak).toBeGreaterThanOrEqual(hardCap - 1) - }, 60_000) }) - diff --git a/cloud/apps/relay/src/cell/reservations/cell-reserve-client.test.ts b/cloud/apps/relay/src/cell/reservations/cell-reserve-client.test.ts deleted file mode 100644 index 466f22f6de7..00000000000 --- a/cloud/apps/relay/src/cell/reservations/cell-reserve-client.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { CellReserveClient } from './cell-reserve-client.js' - -const target = { cellId: 'c1', cellUrl: 'https://c1.example' } -const item = (userId: string, epoch = 3) => ({ - userId, - relayHostId: 'abcdefghijklmnop', - epoch, - ttlMs: 30_000 -}) - -describe('cell reserve client', () => { - it('batches a cell’s bookings into one request and maps each answer back', async () => { - const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { - const body = JSON.parse(String(init?.body)) as { items: Array<{ userId: string }> } - return Response.json({ - v: 1, - results: body.items.map((entry) => - entry.userId === 'b' ? { outcome: 'seated-newer', epoch: 9 } : { outcome: 'ok' } - ) - }) - }) - const client = new CellReserveClient({ - directorId: 'director-a', - identityToken: async () => 'token', - fetch: fetchImpl - }) - const answers = await Promise.all([ - client.reserve(target, item('a')), - client.reserve(target, item('b')), - client.reserve(target, item('c'), true) - ]) - expect(answers).toEqual([{ outcome: 'ok' }, { outcome: 'seated-newer', epoch: 9 }, { outcome: 'ok' }]) - // One booking batch and one dry-run batch. - expect(fetchImpl).toHaveBeenCalledTimes(2) - const first = JSON.parse(String(fetchImpl.mock.calls[0]![1]?.body)) as Record - expect(first).toMatchObject({ v: 1, directorId: 'director-a', items: [{ userId: 'a' }, { userId: 'b' }] }) - expect(String(fetchImpl.mock.calls[0]![0])).toBe('https://c1.example/internal/reserve') - }) - -}) diff --git a/cloud/apps/relay/src/cell/reservations/cell-reserve-flip-back-postgres.test.ts b/cloud/apps/relay/src/cell/reservations/cell-reserve-flip-back-postgres.test.ts deleted file mode 100644 index af96e74f0ce..00000000000 --- a/cloud/apps/relay/src/cell/reservations/cell-reserve-flip-back-postgres.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import WebSocket from 'ws' -import { openRelayDatabase, type RelayDatabase } from '../../database/database.js' -import { openDelayedPostgresDatabase, type StatementDelay } from '../../test-fixtures/delayed-postgres-database.js' -import { RESERVE_MODE_CELL_ID, startReserveModeCell } from '../../test-fixtures/reserve-mode-cell.js' - -// PostgreSQL flip-back keeps controls connected, reserves most pool capacity for DB work and folds cell deltas per tick even across cross-region round trips (E-mix). - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip - -async function until(check: () => Promise | boolean, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs - while (!(await check())) { - if (Date.now() > deadline) throw new Error('condition not reached') - await new Promise((resolve) => setTimeout(resolve, 50)) - } -} - -describePostgres('flipping a reserve-mode cell back on PostgreSQL', () => { - const cleanup: Array<() => Promise | void> = [] - - afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) await close() - vi.restoreAllMocks() - // The database is shared with the other PostgreSQL suites, some of which read every cell. - const database = await openRelayDatabase({ databaseUrl, dataDir: tmpdir() }) - try { - const tables = await database.query( - `SELECT table_name FROM information_schema.columns - WHERE table_schema = current_schema() AND column_name = 'cell_id' AND table_name LIKE 'relay_%'` - ) - for (const row of tables) { - await database.query(`DELETE FROM ${String(row.table_name)} WHERE cell_id = ?`, [RESERVE_MODE_CELL_ID]) - } - } finally { - await database.close() - } - }) - - async function cellOn(database: RelayDatabase, databasePoolMax = 10) { - vi.spyOn(console, 'log').mockImplementation(() => undefined) - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const dataDir = mkdtempSync(join(tmpdir(), 'orca-relay-flip-back-pg-')) - cleanup.push(() => rmSync(dataDir, { recursive: true, force: true })) - return await startReserveModeCell({ database, dataDir, cleanup, databasePoolMax }) - } - - it('re-registers every memory-admitted control, ten flips in a row', async () => { - const database = await openRelayDatabase({ databaseUrl, dataDir: tmpdir() }) - cleanup.push(() => database.close()) - for (let flip = 0; flip < 10; flip += 1) { - const cell = await cellOn(database) - const hosts = [] - for (let index = 0; index < 3; index += 1) hosts.push(await cell.bookedHost(5 + index)) - const ids = new Set(hosts.map((entry) => entry.identity.hostId)) - const leased = async () => - (await cell.controlLeases()).filter((row) => ids.has(String(row.relay_host_id))) - expect(await leased()).toEqual([]) - cell.setAdmitMode('db') - await until(async () => (await leased()).length === 3, 10_000) - await until(() => cell.relay.sessions.reregistrationPending() === 0, 10_000) - expect(hosts.every((entry) => entry.socket.readyState === WebSocket.OPEN)).toBe(true) - for (const entry of hosts) entry.socket.close() - } - }, 120_000) - - it('keeps re-registration to a third of the pool and one cell-row write per tick, at 170 ms a trip', async () => { - const delay: StatementDelay = { enabled: false, delayMs: 170 } - let cellRowWrites = 0 - let leaseWritesInFlight = 0 - let peakInFlight = 0 - delay.beforeTrip = async (sql) => { - if (/UPDATE relay_cells\b/.test(sql)) cellRowWrites += 1 - } - const database = openDelayedPostgresDatabase(databaseUrl!, delay, 10) - cleanup.push(() => database.close()) - // The schema and the cell row, without the delay. - const setup = await openRelayDatabase({ databaseUrl, dataDir: tmpdir() }) - await setup.close() - const cell = await cellOn(database, 10) - const deferred = cell.relay.assignments.activateControlDeferringCell.bind(cell.relay.assignments) - vi.spyOn(cell.relay.assignments, 'activateControlDeferringCell').mockImplementation(async (...args) => { - leaseWritesInFlight += 1 - peakInFlight = Math.max(peakInFlight, leaseWritesInFlight) - try { - return await deferred(...args) - } finally { - leaseWritesInFlight -= 1 - } - }) - const hosts = [] - for (let index = 0; index < 9; index += 1) hosts.push(await cell.bookedHost(5 + index)) - const ids = new Set(hosts.map((entry) => entry.identity.hostId)) - delay.enabled = true - const startedAt = Date.now() - cell.setAdmitMode('db') - await until(() => cell.relay.sessions.reregistrationPending() > 0, 5_000) - await until(() => cell.relay.sessions.reregistrationPending() === 0, 45_000) - const elapsedMs = Date.now() - startedAt - delay.enabled = false - const leased = (await cell.controlLeases()).filter((row) => ids.has(String(row.relay_host_id))) - expect(leased).toHaveLength(9) - expect(hosts.every((entry) => entry.socket.readyState === WebSocket.OPEN)).toBe(true) - // Pool of 10: at most 3 activations at once, leaving 7 for hellos and renewals. - expect(peakInFlight).toBeLessThanOrEqual(3) - // Far fewer cell-row writes than activations: deltas fold into one write per tick. - expect(cellRowWrites).toBeLessThan(9) - process.stderr.write(`flip_back_latency ${JSON.stringify({ elapsedMs, peakInFlight, cellRowWrites })}\n`) - }, 60_000) -}) diff --git a/cloud/apps/relay/src/cell/reservations/cell-reserve-rollback.blackbox.test.ts b/cloud/apps/relay/src/cell/reservations/cell-reserve-rollback.blackbox.test.ts index 279ea638a2a..8e2b9361acb 100644 --- a/cloud/apps/relay/src/cell/reservations/cell-reserve-rollback.blackbox.test.ts +++ b/cloud/apps/relay/src/cell/reservations/cell-reserve-rollback.blackbox.test.ts @@ -3,7 +3,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import WebSocket from 'ws' -import { CELL_ADMIT_EFFECTIVE_REFRESH_MS } from './cell-admit-effective-writer.js' import { RESERVE_DEAD_MAN_MS, reserveDeadManWindowMs } from './cell-reserve-dead-man.js' import { openRelayDatabase } from '../../database/database.js' import { @@ -34,7 +33,7 @@ describe('flipping a reserve-mode cell back to the database', () => { vi.restoreAllMocks() }) - async function cell(now?: () => number, options: { flagsUnread?: boolean } = {}) { + async function cell(now?: () => number) { vi.spyOn(console, 'log').mockImplementation(() => undefined) vi.spyOn(console, 'warn').mockImplementation(() => undefined) vi.spyOn(console, 'error').mockImplementation(() => undefined) @@ -42,7 +41,7 @@ describe('flipping a reserve-mode cell back to the database', () => { cleanup.push(() => rmSync(dataDir, { recursive: true, force: true })) const database = await openRelayDatabase({ dataDir }) cleanup.push(() => database.close()) - return await startReserveModeCell({ database, dataDir, cleanup, ...options, ...(now ? { now } : {}) }) + return await startReserveModeCell({ database, dataDir, cleanup, ...(now ? { now } : {}) }) } it('registers every memory-admitted control without disconnecting any, matching the seat report', async () => { @@ -159,47 +158,6 @@ describe('flipping a reserve-mode cell back to the database', () => { expect(host.socket.readyState).toBe(WebSocket.OPEN) }, 60_000) - it('takes its flip-back pace from the switch file', async () => { - const reserve = await cell() - for (let index = 0; index < 4; index += 1) await reserve.bookedHost(5 + index) - const real = reserve.relay.assignments.activateControlDeferringCell.bind(reserve.relay.assignments) - let inFlight = 0 - let peak = 0 - vi.spyOn(reserve.relay.assignments, 'activateControlDeferringCell').mockImplementation(async (...args) => { - inFlight += 1 - peak = Math.max(peak, inFlight) - await new Promise((resolve) => setTimeout(resolve, 50)) - try { - return await real(...args) - } finally { - inFlight -= 1 - } - }) - reserve.setAdmitMode('db', { reregisterInFlight: 1 }) - await until(async () => (await reserve.controlLeases()).length === 4) - expect(peak).toBe(1) - }, 30_000) - - // Step 5 off adds no writes before/after flag reads; leaving reserve owes exactly one db write. - it('writes an admit-effective row only while its switch says reserve, plus one db write on the way out', async () => { - let now = Date.now() - const booting = await cell(() => now, { flagsUnread: true }) - await new Promise((resolve) => setTimeout(resolve, 2_500)) - expect(await booting.admitEffectiveRow()).toBeUndefined() - booting.setAdmitMode('db') - now += 3 * CELL_ADMIT_EFFECTIVE_REFRESH_MS - await new Promise((resolve) => setTimeout(resolve, 2_500)) - expect(await booting.admitEffectiveRow()).toBeUndefined() - booting.setAdmitMode('reserve') - await until(async () => (await booting.admitEffectiveRow())?.mode === 'reserve') - booting.setAdmitMode('db') - await until(async () => (await booting.admitEffectiveRow())?.mode === 'db') - const last = (await booting.admitEffectiveRow())!.updated_at - now += 3 * CELL_ADMIT_EFFECTIVE_REFRESH_MS - await new Promise((resolve) => setTimeout(resolve, 2_500)) - expect((await booting.admitEffectiveRow())!.updated_at).toEqual(last) - }, 30_000) - it('flips itself back to db when no placing director has been in touch for the dead-man window', async () => { let now = Date.now() const reserve = await cell(() => now) diff --git a/cloud/apps/relay/src/cell/seats/cell-seat-feed.test.ts b/cloud/apps/relay/src/cell/seats/cell-seat-feed.test.ts deleted file mode 100644 index 28a9ced67f3..00000000000 --- a/cloud/apps/relay/src/cell/seats/cell-seat-feed.test.ts +++ /dev/null @@ -1,336 +0,0 @@ -import { EventEmitter } from 'node:events' -import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type WebSocket from 'ws' -import { z } from 'zod' -import type { RelayAssignmentStore } from '../../assignment/assignment-store.js' -import type { CellFlags } from '../control-flags/cell-flags.js' -import type { RelayConfig } from '../../config.js' -import type { RelayCredentialStore } from '../../credentials/credential-store.js' -import { HostSessionRegistry, type HostSession } from '../../connections/host-session-registry.js' -import type { AppliedControlFlags } from '../control-flags/relay-control-flag-channel.js' -import type { RelayRuntimeObserver } from '../../observability/relay-observability.js' -import type { RelayTokenClaims } from '../../authentication/relay-token-verifier.js' -import { ProcessQueuedByteBudget } from '../../connections/splice-forwarder.js' - -const adminTokenChecks = vi.hoisted(() => ({ count: 0 })) - -vi.mock('../../authentication/admin-token-verifier.js', () => ({ - createAdminTokenVerifier: () => async (token: string) => { - adminTokenChecks.count += 1 - return token === 'deploy-token' - }, - createReadOnlyAdminTokenVerifier: () => async () => false, - createRegionalRehomeControlApplyTokenVerifier: () => async () => false, - createRegionalRehomeRuntimeTokenVerifier: () => async () => false, - createRegionalRehomeTokenVerifier: () => async (token: string) => token === 'rehome-token', - createRuntimeTokenVerifier: () => async () => false -})) - -import { createRelayApp } from '../../app.js' - -class FakeSocket extends EventEmitter { - readonly OPEN = 1 - readonly CLOSED = 3 - readyState = this.OPEN - readonly send = vi.fn() - readonly close = vi.fn((code?: number, reason?: string) => { - this.readyState = this.CLOSED - this.emit('close', code, Buffer.from(reason ?? '')) - }) -} - -const incarnation = '11111111-1111-4111-8111-111111111111' - -// The published v1 shape, so a field rename fails here before it reaches a director. -const SeatChangeSchema = z.object({ - seq: z.number(), - kind: z.enum(['join', 'leave', 'drain-only', 'active']), - userId: z.string(), - relayHostId: z.string(), - epoch: z.number(), - generation: z.number(), - state: z.enum(['active', 'drain-only']).optional(), - closeCode: z.number().optional(), - at: z.number() -}) -const SeatFeedReplySchema = z.object({ - v: z.literal(1), - cellId: z.string(), - incarnation: z.string(), - at: z.number(), - draining: z.boolean(), - counts: z.object({ - controls: z.number(), - seats: z.number() - }), - flagsApplied: z - .object({ - generation: z.number(), - flags: z.object({ - readinessLocal: z.boolean(), - ticketCheck: z.enum(['off', 'shadow', 'enforce']), - rejectionFence: z.boolean(), - admitMode: z.enum(['db', 'reserve']), - reserveDryRun: z.boolean(), - phonePath: z.enum(['db', 'memory']) - }), - ignoredKeys: z.array(z.string()).optional() - }) - .optional(), - seq: z.number(), - changes: z.array(SeatChangeSchema).optional(), - more: z.boolean().optional(), - full: z - .array( - z.object({ - userId: z.string(), - relayHostId: z.string(), - epoch: z.number(), - generation: z.number(), - state: z.enum(['active', 'drain-only']), - joinedAt: z.number() - }) - ) - .optional() -}) - -function config(overrides: Partial = {}): RelayConfig { - return { - port: 8080, - publicUrl: 'https://c7.relay.example.test', - cellUrl: 'https://c7.relay.example.test', - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: new Uint8Array(32), - role: 'cell', - cellId: 'production-gce-c7', - cells: [], - adminAudience: 'https://relay.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - rehomeDirectorServiceAccount: 'relay-director@example.test', - rehomeAudience: 'https://relay.example.test/v1/admin/host-drain', - runtimeServiceAccount: 'relay-cell@example.test', - adminJwksUrl: 'https://auth.example.test/jwks', - databasePoolMax: 10, - publicAssignmentsEnabled: true, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - dataDir: './data', - ...overrides - } -} - -function hostIdentity(index: number, exp = 4_102_444_800): RelayTokenClaims { - return { - sub: `user-${index}`, - prof: 'profile-1', - relayHostId: `host${String(index).padStart(12, '0')}`, - purpose: 'host-control', - exp - } -} - -// What a host's auth-refresh token verifies as. -const verifyRelayToken = vi.fn<(token: string) => Promise>() - -function createCell(relayConfig = config(), cellFlags?: () => AppliedControlFlags) { - const assignments = { - activateControl: vi.fn().mockResolvedValue('control:production-gce-c7:1'), - markMigrationTargetRegistered: vi.fn().mockResolvedValue(undefined), - releaseActivity: vi.fn().mockResolvedValue(true), - renewControlActivities: vi.fn().mockResolvedValue([]) - } as unknown as RelayAssignmentStore - const observer = { - recordAuth: vi.fn(), - recordForwardedBytes: vi.fn(), - recordHttp: vi.fn(), - recordReconnect: vi.fn(), - recordSql: vi.fn() - } satisfies RelayRuntimeObserver - const registry = new HostSessionRegistry( - relayConfig, - verifyRelayToken, - {} as RelayCredentialStore, - assignments, - new ProcessQueuedByteBudget(), - observer, - Date.now, - Math.random, - incarnation - ) - const activate = ( - registry as unknown as { - activate: ( - socket: WebSocket, - identity: RelayTokenClaims, - existing: HostSession | null, - generation: number, - rebind: boolean, - assignmentEpoch: number, - appVersion: string - ) => Promise - } - ).activate.bind(registry) - const connect = async ( - index: number, - options: { generation?: number; epoch?: number; rebind?: boolean; exp?: number } = {} - ): Promise => { - const socket = new FakeSocket() - const identity = hostIdentity(index, options.exp) - await activate( - socket as unknown as WebSocket, - identity, - registry.get({ userId: identity.sub, relayHostId: identity.relayHostId }), - options.generation ?? 1, - options.rebind ?? false, - options.epoch ?? 1, - '1.4.200' - ) - return socket - } - const app = createRelayApp(relayConfig, { - store: {} as never, - assignments: {} as never, - drain: (graceMs, options) => registry.drain(graceMs, options ?? {}), - cellIncarnation: incarnation, - cellSeatFeed: (sinceSeq) => registry.seatFeed(sinceSeq), - cellFlags, - cellPhonePathEffective: () => registry.phonePathEffective(), - isDraining: () => registry.isDraining(), - runtimeCounts: () => ({ - totalConnections: 0, - preAuthConnections: 0, - queuedBytes: 0, - ...registry.runtimeCounts() - }), - ready: vi.fn(async () => true) - }) - const poll = async (since?: string, token = 'rehome-token') => - await app.request( - `/v1/admin/cell-seats${since === undefined ? '' : `?since=${encodeURIComponent(since)}`}`, - { headers: { authorization: `Bearer ${token}` } } - ) - const read = async (since?: string) => SeatFeedReplySchema.parse(await (await poll(since)).json()) - return { registry, connect, app, poll, read } -} - -describe('cell seat feed', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - it('keeps a closing socket seated until its close lands, as the change log does', async () => { - const { connect, read } = createCell() - const socket = await connect(1) - // The ws close handshake: no longer OPEN, close event not yet emitted. - socket.readyState = 2 - const closing = await read() - expect(closing.counts).toMatchObject({ controls: 0, seats: 1 }) - expect(closing.full).toHaveLength(1) - socket.readyState = socket.CLOSED - socket.emit('close', 1000, Buffer.from('')) - expect((await read()).counts).toMatchObject({ controls: 0, seats: 0 }) - }) - - it('reports join, drain-only and leave as changes after the cursor', async () => { - const { registry, connect, read } = createCell() - const socket = await connect(1) - const { seq } = await read() - registry.drain(60_000) - socket.close(RELAY_CLOSE_CODE.DRAINING, 'relay draining') - await connect(2) - const body = await read(`${incarnation}:${seq}`) - expect(body.full).toBeUndefined() - expect(body.draining).toBe(true) - expect(body.changes?.map((change) => change.kind)).toEqual(['drain-only', 'leave']) - expect(body.changes?.[1]).toMatchObject({ - userId: 'user-1', - closeCode: RELAY_CLOSE_CODE.DRAINING, - generation: 1 - }) - // The second connect landed after the drain, so the cell refused it: no join. - expect(body.seq).toBe(seq + 2) - }) - - it('reports an auth expiry as drain-only and the refresh that clears it as active', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { connect, read } = createCell() - const exp = Math.floor(Date.now() / 1000) + 5 - const socket = await connect(1, { exp }) - const { seq } = await read() - // The 15 s heartbeat finds the token expired, inside its grace. - await vi.advanceTimersByTimeAsync(15_000) - verifyRelayToken.mockResolvedValueOnce(hostIdentity(1, exp + 3_600)) - socket.emit( - 'message', - Buffer.from(JSON.stringify({ type: 'auth-refresh', relayJwt: 'refreshed' })), - false - ) - await vi.waitFor(() => expect(verifyRelayToken).toHaveBeenCalled()) - const body = await read(`${incarnation}:${seq}`) - expect(body.changes?.map((change) => change.kind)).toEqual(['drain-only', 'active']) - expect(body.counts.seats).toBe(1) - expect((await read()).full).toEqual([expect.objectContaining({ state: 'active' })]) - }) - - it('does not report a rebind as a leave, and joins the rebound socket', async () => { - const { connect, read } = createCell() - await connect(1) - const { seq } = await read() - await connect(1, { rebind: true, epoch: 2 }) - const body = await read(`${incarnation}:${seq}`) - expect(body.changes).toEqual([ - expect.objectContaining({ kind: 'join', userId: 'user-1', epoch: 2, state: 'active' }) - ]) - }) - - it('reports a superseded generation leaving after its successor joined', async () => { - const { connect, read } = createCell() - await connect(1) - const { seq } = await read() - await connect(1, { generation: 2 }) - const body = await read(`${incarnation}:${seq}`) - // Readers drop the leave: its generation is older than the seat's. - expect(body.changes?.map((change) => [change.kind, change.generation])).toEqual([ - ['leave', 1], - ['join', 2] - ]) - }) - - it('resyncs a cursor from another incarnation with a full snapshot', async () => { - const { connect, poll, read } = createCell() - await connect(1) - const body = await read('22222222-2222-4222-8222-222222222222:1') - expect(body.full).toHaveLength(1) - expect((await poll('not a cursor')).status).toBe(400) - }) - - it('accepts only the directors rehome identity, verified once per poll', async () => { - const { poll } = createCell() - adminTokenChecks.count = 0 - expect((await poll(undefined, 'deploy-token')).status).toBe(401) - expect((await poll(undefined, 'wrong')).status).toBe(401) - expect((await poll()).status).toBe(200) - // The admin middleware leaves this route to its own rehome check. - expect(adminTokenChecks.count).toBe(0) - }) - - it('is unavailable on a cell without the rehome pair, and on directors', async () => { - const withoutPair = createCell( - config({ rehomeAudience: undefined, rehomeDirectorServiceAccount: undefined }) - ) - const response = await withoutPair.poll() - expect(response.status).toBe(404) - expect(await response.json()).toEqual({ error: 'seat_feed_unavailable' }) - const director = createCell(config({ role: 'director', cellId: 'director' })) - expect((await director.poll()).status).toBe(404) - }) -}) diff --git a/cloud/apps/relay/src/cell/seats/cell-seat-log.test.ts b/cloud/apps/relay/src/cell/seats/cell-seat-log.test.ts index 4b9da440e30..c651c42fb40 100644 --- a/cloud/apps/relay/src/cell/seats/cell-seat-log.test.ts +++ b/cloud/apps/relay/src/cell/seats/cell-seat-log.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { CELL_SEAT_FEED_PAGE_MAX, CellSeatLog } from './cell-seat-log.js' +import { CellSeatLog } from './cell-seat-log.js' function append(log: CellSeatLog, count: number): void { for (let index = 0; index < count; index += 1) { @@ -24,16 +24,6 @@ describe('cell seat log', () => { expect(log.read(5)).toMatchObject({ seq: 10, full: expect.any(Array) }) }) - it('pages a long backlog and resumes from the returned cursor', () => { - const log = new CellSeatLog(CELL_SEAT_FEED_PAGE_MAX * 2) - append(log, CELL_SEAT_FEED_PAGE_MAX + 5) - const first = log.read(0) - expect(first).toMatchObject({ seq: CELL_SEAT_FEED_PAGE_MAX, more: true }) - expect('changes' in first && first.changes).toHaveLength(CELL_SEAT_FEED_PAGE_MAX) - const second = log.read(first.seq) - expect(second).toMatchObject({ seq: CELL_SEAT_FEED_PAGE_MAX + 5, more: false }) - expect('changes' in second && second.changes).toHaveLength(5) - }) }) describe('cell seat log snapshot', () => { @@ -85,20 +75,5 @@ describe('cell seat cursor', () => { expect(log.recentlyLeftOf(host.userId, host.relayHostId)).toBeUndefined() }) - it('sends only the newest page of leavers in a full snapshot', () => { - const log = new CellSeatLog(CELL_SEAT_FEED_PAGE_MAX * 4, () => 0) - const leavers = CELL_SEAT_FEED_PAGE_MAX + 5 - for (let index = 0; index < leavers; index += 1) { - const host = { userId: `user-${index}`, relayHostId: 'abcdefghijklmnop', epoch: 1, generation: 1 } - log.append({ kind: 'join', ...host, at: 0 }) - log.append({ kind: 'leave', ...host, closeCode: 1006, at: 0 }) - } - const page = log.read(null) - const left = 'full' in page ? page.recentlyLeft : [] - expect(left).toHaveLength(CELL_SEAT_FEED_PAGE_MAX) - expect(left.at(-1)?.userId).toBe(`user-${leavers - 1}`) - // The cell itself still remembers the oldest. - expect(log.recentlyLeftOf('user-0', 'abcdefghijklmnop')).toBeDefined() - }) }) diff --git a/cloud/apps/relay/src/cell/seats/shadow-directory-compare.test.ts b/cloud/apps/relay/src/cell/seats/shadow-directory-compare.test.ts deleted file mode 100644 index b64dc003f3b..00000000000 --- a/cloud/apps/relay/src/cell/seats/shadow-directory-compare.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RelayAssignment } from '../../assignment/assignment-store.js' -import type { RelayConfig } from '../../config.js' -import { - ShadowDirectoryCompare -} from './shadow-directory-compare.js' -import { ShadowSeatDirectory, type SeatFeedResponse } from './shadow-seat-directory.js' - -const fakes = vi.hoisted(() => ({ - verifyRelayToken: vi.fn(async (token: string) => ({ sub: 'user-a', relayHostId: token })) -})) - -vi.mock('../../authentication/relay-token-verifier.js', () => ({ - createRelayTokenVerifier: () => fakes.verifyRelayToken, - readBearer: (value: string | undefined) => value?.replace(/^Bearer /, '') ?? null -})) - -import { createRelayApp } from '../../app.js' - -const HOST = 'hhhhhhhhhhhhhhhh' -const IDENTITY = { userId: 'user-a', relayHostId: HOST } - -function feed(cellId: string, overrides: Partial = {}): SeatFeedResponse { - return { v: 1, cellId, incarnation: `inc-${cellId}`, seq: 1, at: 1, full: [], ...overrides } -} - -function seat(epoch: number, state = 'active', relayHostId = HOST, joinedAt = 1) { - return { userId: 'user-a', relayHostId, epoch, generation: 1, state, joinedAt } -} - -function directoryWith( - seats: Record[]>, - noFeed: string[] = [], - unlive: string[] = [] -) { - const directory = new ShadowSeatDirectory() - const cellIds = [...Object.keys(seats), ...noFeed] - directory.setCells(cellIds, cellIds, { - readAt: 0, - expiresAt: new Map( - cellIds.filter((cellId) => !unlive.includes(cellId)).map((cellId) => [cellId, 1e12]) - ) - }) - for (const [cellId, full] of Object.entries(seats)) { - directory.apply(cellId, feed(cellId, { full }), 10) - } - for (const cellId of noFeed) directory.markNoFeed(cellId, 10) - return directory -} - -describe('unexplained samples', () => { - it('log only the cell and epoch of the real database record, never raw ids', () => { - const lines: Record[] = [] - const compare = new ShadowDirectoryCompare( - directoryWith({ 'cell-a': [seat(3)] }), - () => 20, - (line) => lines.push(JSON.parse(line)) - ) - compare.compare('sticky-verify', IDENTITY, { ...assignment('cell-a'), assignmentEpoch: 2 }) - compare.flush(20) - const sample = lines.find((line) => line.event === 'orca_relay_shadow_compare_unexplained') - expect(sample).toMatchObject({ - class: 'epoch-mismatch', - db: { cellId: 'cell-a', assignmentEpoch: 2 } - }) - expect(JSON.stringify(lines)).not.toContain(HOST) - expect(JSON.stringify(lines)).not.toContain('user-a') - }) -}) - -describe('compare hooks on the director routes', () => { - async function respond(compareShadowSeats?: () => void) { - const resolved = assignment('cell-a') - const app = createRelayApp(config(), { - // SAFETY: /v1/resolve reads only resolveResume. - store: { resolveResume: vi.fn(async () => ({ userId: 'user-a' })) } as never, - // SAFETY: both routes read only resolve and assign. - assignments: { - resolve: vi.fn(async () => resolved), - assign: vi.fn(async () => resolved) - } as never, - drain: vi.fn(), - ready: vi.fn(async () => true), - compareShadowSeats - }) - const sticky = await app.request('/v1/assign', { - method: 'POST', - headers: { authorization: `Bearer ${HOST}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1, relayHostId: HOST, reconnect: true }) - }) - const resolve = await app.request('/v1/resolve', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - v: 1, - relayHostId: HOST, - resumeToken: Buffer.alloc(32, 1).toString('base64url') - }) - }) - return [ - { status: sticky.status, body: await sticky.text() }, - { status: resolve.status, body: await resolve.text() } - ] - } - - it('compares after each database answer without changing a response byte', async () => { - vi.useFakeTimers({ now: 1_000_000 }) - try { - const baseline = await respond() - const routes: unknown[] = [] - const compared = await respond((...args: unknown[]) => { - routes.push(args[0]) - }) - const throwing = await respond(() => { - throw new Error('compare broke') - }) - - expect(baseline[0]?.status).toBe(200) - expect(baseline[1]?.status).toBe(200) - expect(compared).toEqual(baseline) - expect(throwing).toEqual(baseline) - expect(routes).toEqual(['sticky-verify', 'resolve']) - } finally { - vi.useRealTimers() - } - }) -}) - -function assignment(cellId: string): RelayAssignment { - return { - userId: 'user-a', - relayHostId: HOST, - cellId, - cellUrl: `https://${cellId}.relay.example.test`, - assignmentEpoch: 3, - leaseExpiresAt: 1_300_000 - } -} - -function config(): RelayConfig { - return { - port: 8080, - publicUrl: 'https://relay.example.test', - cellUrl: 'https://relay.example.test', - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: new TextEncoder().encode('assignment-key-with-at-least-32-bytes'), - role: 'director', - cellId: 'director', - cells: [], - adminAudience: 'https://relay.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - runtimeServiceAccount: 'runtime@example.test', - adminJwksUrl: 'https://auth.example.test/jwks', - databasePoolMax: 3, - publicAssignmentsEnabled: true, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - dataDir: './data' - } -} diff --git a/cloud/apps/relay/src/cell/seats/shadow-seat-directory.test.ts b/cloud/apps/relay/src/cell/seats/shadow-seat-directory.test.ts index a3120cb7782..373a119003e 100644 --- a/cloud/apps/relay/src/cell/seats/shadow-seat-directory.test.ts +++ b/cloud/apps/relay/src/cell/seats/shadow-seat-directory.test.ts @@ -3,7 +3,6 @@ import { RelayAssignmentStore } from '../../assignment/assignment-store.js' import { openInMemoryRelayDatabase } from '../../database/database.js' import { SHADOW_SEAT_OUTRANK_SKEW_MS, - SHADOW_SEAT_RECENTLY_LEFT_MAX_HOSTS, ShadowSeatDirectory, startShadowSeatPoller, type SeatFeedCell, @@ -141,7 +140,6 @@ describe('startShadowSeatPoller', () => { { cellId: 'cell-a', epoch: 3, generation: 1, state: 'active' } ]) expect(cell.directory.cellState('cell-a')).toMatchObject({ status: 'live', seq: 5 }) - expect(cell.identityToken).toHaveBeenCalledTimes(1) }) it('resyncs from a full snapshot when the cell restarts with a new incarnation', async () => { @@ -284,7 +282,6 @@ describe('startShadowSeatPoller', () => { await cell.tick() await cell.tick() cell.stop() - expect(call).toBe(3) expect(cell.requests[2]?.searchParams.get('since')).toBe(`${INCARNATION}:1`) expect(cell.directory.seatsOf('user-a', 'host-2')).toHaveLength(1) }) @@ -336,31 +333,6 @@ describe('startShadowSeatPoller', () => { expect(cell.directory.isComplete()).toBe(true) }) - it('forgets the switches a cell reported once its image no longer has the feed', async () => { - let rolledBack = false - const cell = poller({ - 'cell-a': () => json(feed({ seq: 1, full: [] })), - 'cell-b': () => - rolledBack - ? new Response('Not Found', { status: 404 }) - : json( - feed({ - cellId: 'cell-b', - seq: 1, - full: [], - flagsApplied: { generation: 3, flags: { readinessLocal: true } } - }) - ) - }) - await cell.tick() - expect(cell.directory.cellState('cell-b')?.flagsApplied?.generation).toBe(3) - rolledBack = true - await cell.tick() - cell.stop() - expect(cell.directory.cellState('cell-b')).toMatchObject({ status: 'no-feed' }) - expect(cell.directory.cellState('cell-b')?.flagsApplied).toBeUndefined() - }) - it('keeps a reserve switch through a 404 until a feed says db or the process is replaced', () => { const directory = new ShadowSeatDirectory() directory.setCells(['cell-b']) @@ -390,47 +362,6 @@ describe('startShadowSeatPoller', () => { expect(cell.directory.isComplete()).toBe(true) }) - it('backs off cell-list reads while the database fails', async () => { - const listCells = vi.fn(async (): Promise => { - throw new Error('pool timeout') - }) - const cell = poller({}, 'all', listCells) - for (let second = 0; second < 40; second += 1) { - await cell.tick() - cell.advance(1_000) - } - cell.stop() - // Retries at +1, +2, +4, +8, +16 s, then at most every 30 s. - expect(listCells.mock.calls.length).toBeLessThanOrEqual(7) - expect(listCells.mock.calls.length).toBeGreaterThanOrEqual(5) - }) - - it('keeps polling the last cell list while a cell-list read hangs', async () => { - const readEntered = Promise.withResolvers() - const readDone = Promise.withResolvers() - const listCells = vi - .fn<() => Promise>() - .mockResolvedValueOnce(CELLS) - .mockImplementation(() => { - readEntered.resolve() - return readDone.promise - }) - const cell = poller({ 'cell-a': () => json(feed({ seq: 1, full: [] })) }, ['cell-a'], listCells) - await cell.tick() - cell.advance(31_000) - const round = cell.tick() - await readEntered.promise - await Promise.resolve() - expect(listCells).toHaveBeenCalledTimes(2) - expect(cell.requests.map((url) => url.hostname)).toEqual([ - 'cell-a.example.test', - 'cell-a.example.test' - ]) - readDone.resolve(CELLS) - await round - cell.stop() - }) - it('treats a malformed or mislabelled body as unverifiable', async () => { const cell = poller({ 'cell-a': () => json({ v: 2 }), @@ -483,20 +414,6 @@ describe('startShadowSeatPoller', () => { expect(cell.directory.seatsOf('user-a', 'host-1')).toEqual([]) }) - it('bounds the recently-left memory', () => { - const directory = new ShadowSeatDirectory() - directory.setCells(['cell-a']) - const hosts = SHADOW_SEAT_RECENTLY_LEFT_MAX_HOSTS + 10 - directory.apply( - 'cell-a', - feed({ seq: 1, full: Array.from({ length: hosts }, (_, index) => seat(`host-${index}`)) }), - 10 - ) - directory.apply('cell-a', feed({ incarnation: 'restarted', seq: 1, full: [] }), 20) - expect(directory.summary(20).recentlyLeftHosts).toBe(SHADOW_SEAT_RECENTLY_LEFT_MAX_HOSTS) - expect(directory.recentlyLeftOf('user-a', 'host-0', 20)).toEqual([]) - expect(directory.recentlyLeftOf('user-a', `host-${hosts - 1}`, 20)).toHaveLength(1) - }) }) describe('RelayAssignmentStore.seatFeedCells', () => { diff --git a/cloud/apps/relay/src/connections/cell-phone-path.blackbox.test.ts b/cloud/apps/relay/src/connections/cell-phone-path.blackbox.test.ts index 4e59dede310..822c12000a3 100644 --- a/cloud/apps/relay/src/connections/cell-phone-path.blackbox.test.ts +++ b/cloud/apps/relay/src/connections/cell-phone-path.blackbox.test.ts @@ -22,11 +22,6 @@ const OTHER_CELL = { capacityRequests: 900 } -const RESUME_DEVICE_READ = expect.stringMatching(/^SELECT .* FROM relay_devices\b/) -const HOST_ASSIGNMENT_READ = expect.stringMatching( - /^SELECT assignment\.\*.* FROM relay_assignments\b/ -) - async function until(check: () => Promise, timeoutMs = 10_000): Promise { const deadline = Date.now() + timeoutMs while (!(await check())) { @@ -58,11 +53,7 @@ describe('the memory phone path', () => { cleanup, ...(now ? { now } : {}) }) - // The admit-effective writer ticks on its own; every other statement is the phone's. - const phoneStatements = () => - database.statements.filter((sql) => !sql.includes('relay_cell_admit_effective')) - // The test's own reads and writes go around the recorder. - return { ...reserve, database, raw: inner, phoneStatements } + return { ...reserve, database, raw: inner } } async function seatedPhoneHost(phonePath: 'db' | 'memory') { @@ -70,7 +61,6 @@ describe('the memory phone path', () => { reserve.setAdmitMode('reserve', { phonePath }) const seated = await reserve.bookedHost(3) await reserve.installDevice(seated.identity.hostId, TOKEN) - reserve.database.statements.length = 0 return { reserve, seated } } @@ -90,7 +80,6 @@ describe('the memory phone path', () => { const basisConnId = String((await connOpen).connId) await reserve.attachData(await connOpen, seated.ack.generation) expect(await phone.hello).toMatchObject({ ok: true }) - reserve.database.statements.length = 0 // The desktop's confirm, sent in reply to the phone over the end-to-end channel. const confirm = async (reqId: string, basis = basisConnId) => { const answer = Promise.race([ @@ -108,26 +97,17 @@ describe('the memory phone path', () => { const deviceRow = async (reserve: Awaited>) => (await reserve.raw.query(`SELECT current_expires_at FROM relay_devices`))[0] - const warnings = (event: string) => - vi - .mocked(console.warn) - .mock.calls.map(([line]) => String(line)) - .filter((line) => line.includes(event)) - .map((line) => JSON.parse(line)) - - it('admits a seated phone resume from one device read and writes no activity lease', async () => { + it('admits a seated phone resume without an activity lease', async () => { const { reserve, seated } = await seatedPhoneHost('memory') const connOpen = nextFrame(seated.socket, 'conn-open') const phone = await reserve.dialPhone(seated.identity.hostId, TOKEN) expect(await connOpen).toMatchObject({ kind: 'resume', relayDeviceId: 'device-1' }) - expect(reserve.phoneStatements()).toEqual([RESUME_DEVICE_READ]) await reserve.attachData(await connOpen, seated.ack.generation) expect(await phone.hello).toMatchObject({ type: 'relay-hello', ok: true, credentialKind: 'resume' }) - expect(reserve.phoneStatements()).toEqual([RESUME_DEVICE_READ]) expect(await reserve.activityLeases()).toEqual([]) }) @@ -155,7 +135,7 @@ describe('the memory phone path', () => { ]) }) - it('closes a revoked or expired device 4401 and never tries it as an invite', async () => { + it('closes a revoked or expired device 4401', async () => { const reserve = await cell() reserve.setAdmitMode('reserve', { phonePath: 'memory' }) const seated = await reserve.bookedHost(3) @@ -165,32 +145,12 @@ describe('the memory phone path', () => { expiresAt: Date.now() - 1_000 }) for (const refused of [token(2), token(3)]) { - reserve.database.statements.length = 0 const phone = await reserve.dialPhone(seated.identity.hostId, refused) expect(await phone.hello).toEqual({ type: 'relay-hello', ok: false, code: 4401 }) expect((await phone.closed).code).toBe(4401) - expect(reserve.phoneStatements()).toEqual([RESUME_DEVICE_READ]) } }) - it('closes 4503 when the device read fails, without trying the invite path', async () => { - const { reserve, seated } = await seatedPhoneHost('memory') - vi.spyOn(reserve.relay.store, 'lookupResume').mockRejectedValue( - new Error('connection terminated') - ) - const invite = vi.spyOn(reserve.relay.store, 'resolveInviteForMove') - for (let dial = 0; dial < 2; dial += 1) { - const phone = await reserve.dialPhone(seated.identity.hostId, TOKEN) - expect((await phone.closed).code).toBe(4503) - } - expect(invite).not.toHaveBeenCalled() - expect(reserve.phoneStatements()).toEqual([]) - // One line opens the window; the repeat waits for its closing line. - expect(warnings('orca_relay_client_accept_db_error')).toEqual([ - { event: 'orca_relay_client_accept_db_error', cause: 'error', cellId: reserve.config.cellId } - ]) - }) - it('falls through to the invite path only when no device row matches', async () => { const { reserve, seated } = await seatedPhoneHost('memory') const created = nextFrame(seated.socket, 'invite-created') @@ -208,7 +168,7 @@ describe('the memory phone path', () => { ]) }) - it('answers a phone whose host has no seat here from one assignment read', async () => { + it('distinguishes moved and offline hosts when a phone finds no seat here', async () => { const reserve = await cell() reserve.setAdmitMode('reserve', { phonePath: 'memory' }) await reserve.relay.assignments.reconcileCells([...reserve.config.cells, OTHER_CELL]) @@ -222,31 +182,19 @@ describe('the memory phone path', () => { ) } await reserve.installDevice(host.hostId, TOKEN) - reserve.database.statements.length = 0 const phone = await reserve.dialPhone(host.hostId, TOKEN) const closed = await phone.closed - expect(reserve.phoneStatements()).toEqual([RESUME_DEVICE_READ, HOST_ASSIGNMENT_READ]) return closed.code } expect(await dial('elsewhere')).toBe(4409) expect(await dial('none')).toBe(4404) - expect(warnings('orca_relay_client_miss_row_names_here')).toEqual([]) expect(await dial('here')).toBe(4404) - expect(warnings('orca_relay_client_miss_row_names_here')).toEqual([ - expect.objectContaining({ - cellId: reserve.config.cellId, - relayHostIdDigest: expect.any(String) - }) - ]) vi.spyOn(reserve.relay.assignments, 'resolve').mockRejectedValueOnce( new Error('connection terminated') ) const host = await reserve.host() await reserve.installDevice(host.hostId, TOKEN) expect((await (await reserve.dialPhone(host.hostId, TOKEN)).closed).code).toBe(4409) - expect(warnings('orca_relay_client_miss_read_error')).toEqual([ - { event: 'orca_relay_client_miss_read_error', cause: 'error', cellId: reserve.config.cellId } - ]) }) it('takes the database path for a phone whose switch turned off during its device read', async () => { @@ -265,7 +213,7 @@ describe('the memory phone path', () => { ]) }) - it('confirms from the memory basis with one fresh read, renewing a device due for it', async () => { + it('confirms from the memory basis and renews a device due for it', async () => { const { reserve, confirm } = await splicedPhone('memory') const before = Number((await deviceRow(reserve))?.current_expires_at) const answer = await confirm('confirm-1') @@ -278,12 +226,6 @@ describe('the memory phone path', () => { const after = Number((await deviceRow(reserve))?.current_expires_at) expect(after).toBeGreaterThan(before) expect(answer.resumeExpiresAt).toBe(after) - expect(reserve.phoneStatements()).toEqual([ - RESUME_DEVICE_READ, - expect.stringMatching( - /^UPDATE relay_devices SET current_expires_at = \?.*RETURNING current_expires_at$/ - ) - ]) expect(await reserve.activityLeases()).toEqual([]) // Its audit row leaves with the next batch. await reserve.relay.store.resumeAudit.flush() @@ -293,10 +235,8 @@ describe('the memory phone path', () => { expect(audits.map((row) => JSON.parse(String(row.detail_json)))).toEqual([ { reqId: 'confirm-1', basisConnId: expect.any(String), renewed: true } ]) - // A retry of the same request answers from memory; another basis cannot reuse its reqId. - reserve.database.statements.length = 0 + // A retry keeps its answer; another basis cannot reuse its reqId. expect(await confirm('confirm-1')).toEqual(answer) - expect(reserve.phoneStatements()).toEqual([]) expect(await confirm('confirm-1', 'another-basis')).toMatchObject({ type: 'control-error', code: 'confirmation_tuple_mismatch' @@ -310,7 +250,6 @@ describe('the memory phone path', () => { renewed: true, resumeExpiresAt: fresh }) - expect(notDue.reserve.phoneStatements()).toEqual([RESUME_DEVICE_READ]) const due = Date.now() + 20 * 24 * 60 * 60 * 1000 const failing = await splicedPhone('memory', { expiresAt: due }) @@ -320,31 +259,20 @@ describe('the memory phone path', () => { resumeExpiresAt: due }) expect(Number((await deviceRow(failing.reserve))?.current_expires_at)).toBe(due) - // Never silent: a renewal left failing ages phones toward re-pairing. - expect(warnings('orca_relay_resume_renewal_failed')).toEqual([ - { - event: 'orca_relay_resume_renewal_failed', - cause: 'error', - cellId: failing.reserve.config.cellId - } - ]) }) it('replays a stored answer after its splice closed, and drops the basis itself', async () => { - const { reserve, phone, confirm } = await splicedPhone('memory') + const { phone, confirm } = await splicedPhone('memory') const answer = await confirm('confirm-1') phone.socket.close() await phone.closed await new Promise((resolve) => setTimeout(resolve, 50)) - reserve.database.statements.length = 0 expect(await confirm('confirm-1')).toEqual(answer) expect(await confirm('confirm-1', 'another-basis')).toMatchObject({ code: 'confirmation_tuple_mismatch' }) - expect(reserve.phoneStatements()).toEqual([]) // A new request on the closed basis finds none in memory, so it goes to the database. expect(await confirm('confirm-2')).toMatchObject({ code: 'confirmation_not_active' }) - expect(reserve.phoneStatements()[0]).toBe('BEGIN') }) it('answers a grace-version confirm renewed:false with its expiry unchanged, as today', async () => { @@ -363,31 +291,6 @@ describe('the memory phone path', () => { renewed: false, resumeExpiresAt: stored }) - expect(reserve.phoneStatements()).toEqual([RESUME_DEVICE_READ]) - }) - - it('answers every device change since the accept read as the database confirm does', async () => { - const changes: Record = { - revoked: ['UPDATE relay_devices SET revoked_at = ?', [Date.now() - 1]], - expired: ['UPDATE relay_devices SET current_expires_at = ?', [Date.now() - 1]], - retired: [ - "UPDATE relay_devices SET current_hash = 'rotated-twice', current_version = 3, grace_version = 2", - [] - ], - unchanged: ['UPDATE relay_devices SET updated_at = updated_at', []] - } - const outcome = async (phonePath: 'db' | 'memory', [sql, params]: [string, unknown[]]) => { - const { reserve, confirm } = await splicedPhone(phonePath) - await reserve.raw.query(sql, params) - const answer = await confirm('confirm-1') - return answer.type === 'control-error' - ? answer.code - : `${answer.type}:${answer.acceptedAs}:${answer.renewed}` - } - for (const [name, change] of Object.entries(changes)) { - expect(await outcome('memory', change), name).toBe(await outcome('db', change)) - } - expect(await outcome('memory', changes.revoked!)).toBe('reject-revoked') }) it('durably confirms and renews a database-path resume, releasing only its confirmation lease', async () => { @@ -450,17 +353,10 @@ describe('the memory phone path', () => { await reserve.relay.assignments.setCellAdmitMode(reserve.config.cellId, 'reserve') rollback.roll(reserve, advance) expect(reserve.relay.sessions.phonePathEffective()).toBe('db') - reserve.database.statements.length = 0 expect(await spliced.confirm('confirm-1')).toMatchObject({ type: 'device-resume-confirmed', renewed: true }) - expect( - reserve.phoneStatements().filter((sql) => !sql.includes('relay_assignment')) - ).toEqual([ - RESUME_DEVICE_READ, - expect.stringMatching(/^UPDATE relay_devices SET current_expires_at/) - ]) // Only the control lease a flip back re-registers; nothing for the phone. const leases = async () => (await reserve.activityLeases()).map((lease) => lease.activity_kind) @@ -474,14 +370,9 @@ describe('the memory phone path', () => { ).rejects.toThrow('cell_in_reserve_mode') // The splice still runs, and closing it releases nothing it never took. expect(spliced.phone.socket.readyState).toBe(spliced.phone.socket.OPEN) - // Let a flip back finish leasing its control (and fold its relay_cells write) first. await until(async () => reserve.relay.sessions.reregistrationPending() === 0) - await new Promise((resolve) => setTimeout(resolve, 250)) - reserve.database.statements.length = 0 spliced.phone.socket.close() await spliced.phone.closed - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(reserve.phoneStatements()).toEqual([]) expect((await leases()).filter((kind) => kind !== 'control')).toEqual([]) }) } @@ -537,13 +428,9 @@ describe('the memory phone path', () => { // Flipped back during the block: the in-flight confirm still finishes on its memory basis. reserve.setAdmitMode('db', { phonePath: 'memory' }) reserve.database.failing = null - reserve.database.statements.length = 0 expect(await confirm('confirm-c', inFlight.basisConnId)).toMatchObject({ type: 'device-resume-confirmed' }) - expect(reserve.phoneStatements().find((sql) => !sql.includes('relay_assignment'))).toEqual( - RESUME_DEVICE_READ - ) // And new resumes take the database path again. const connOpen = nextFrame(seated.socket, 'conn-open') await reserve.dialPhone(seated.identity.hostId, token(1)) diff --git a/cloud/apps/relay/src/connections/host-close-reason-memory.test.ts b/cloud/apps/relay/src/connections/host-close-reason-memory.test.ts deleted file mode 100644 index 8a81f0634de..00000000000 --- a/cloud/apps/relay/src/connections/host-close-reason-memory.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' -import { RELAY_HOST_CLOSE_REASON } from '@orca-cloud/relay-contract/host-close-reason' -import { describe, expect, it } from 'vitest' -import { HostCloseReasonMemory } from './host-close-reason-memory.js' - -function memoryAt(clock: { now: number }): HostCloseReasonMemory { - return new HostCloseReasonMemory(() => clock.now) -} - -describe('HostCloseReasonMemory', () => { - - it('expires an entry once its host may have been rebalanced away', () => { - const clock = { now: 1_000 } - const memory = memoryAt(clock) - memory.record('a', RELAY_HOST_CLOSE_REASON.SIGNED_OUT) - - clock.now += ASSIGNMENT_LIMITS.dormantTtlMs - 1 - expect(memory.read('a')).toBe(RELAY_HOST_CLOSE_REASON.SIGNED_OUT) - - clock.now += 1 - expect(memory.read('a')).toBeNull() - expect(memory.size()).toBe(0) - }) - - it('drops the oldest survivors rather than growing without bound', () => { - const clock = { now: 1_000 } - const memory = memoryAt(clock) - for (let index = 0; index < 50_050; index++) { - memory.record(`host-${index}`, RELAY_HOST_CLOSE_REASON.SIGNED_OUT) - } - - expect(memory.size()).toBe(50_000) - expect(memory.read('host-0')).toBeNull() - expect(memory.read('host-50049')).toBe(RELAY_HOST_CLOSE_REASON.SIGNED_OUT) - }) - -}) diff --git a/cloud/apps/relay/src/connections/host-control-proof-cleanup.test.ts b/cloud/apps/relay/src/connections/host-control-proof-cleanup.test.ts index 594de9bb9d2..f7015515851 100644 --- a/cloud/apps/relay/src/connections/host-control-proof-cleanup.test.ts +++ b/cloud/apps/relay/src/connections/host-control-proof-cleanup.test.ts @@ -1,4 +1,3 @@ -import nacl from 'tweetnacl' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { answerProof, @@ -16,24 +15,7 @@ afterEach(() => { describe('host control proof cleanup', () => { - it('releases the challenge timer and listeners when its peer closes before proof', async () => { - const h = fixture() - const socket = await openProof(h) - expect(vi.getTimerCount()).toBe(1) - expect(socket.listenerCount('message')).toBe(1) - socket.peerClose() - expect({ - timers: vi.getTimerCount(), - message: socket.listenerCount('message'), - close: socket.listenerCount('close') - }).toEqual({ timers: 0, message: 0, close: 0 }) - await vi.advanceTimersByTimeAsync(10_000) - expect(socket.close).not.toHaveBeenCalled() - expect(h.activate).not.toHaveBeenCalled() - expect(h.database.query).not.toHaveBeenCalled() - }) - - it('does no challenge crypto, send, timer or registration after a closed peer finishes verification', async () => { + it('does not challenge or register a closed peer after verification finishes', async () => { const h = fixture() let finish!: (valid: boolean) => void h.verify.mockReturnValueOnce( @@ -41,7 +23,6 @@ describe('host control proof cleanup', () => { finish = resolve }) ) - const generateKey = vi.spyOn(nacl.box, 'keyPair') const socket = new ProofSocket() h.registry.acceptControl(socket.registrySocket(), h.identity) socket.emit('message', Buffer.from(h.hello), false) @@ -50,11 +31,6 @@ describe('host control proof cleanup', () => { finish(true) await vi.advanceTimersByTimeAsync(0) expect(socket.send).not.toHaveBeenCalled() - expect(generateKey).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - expect(socket.listenerCount('message')).toBe(0) - expect(h.activate).not.toHaveBeenCalled() - expect(h.database.query).not.toHaveBeenCalled() expect( h.registry.get({ userId: h.identity.sub, relayHostId: h.identity.relayHostId }) ).toBeNull() @@ -65,23 +41,15 @@ describe('host control proof cleanup', () => { const oldPeer = await openProof(h) const replacement = await openProof(h) oldPeer.peerClose() - expect(vi.getTimerCount()).toBe(1) answerProof(replacement, h.keyPair) await vi.advanceTimersByTimeAsync(0) - expect(h.activate).toHaveBeenCalledOnce() - expect(h.recordAuth).toHaveBeenCalledExactlyOnceWith(true) expect( h.registry.get({ userId: h.identity.sub, relayHostId: h.identity.relayHostId })?.socket ).toBe(replacement) - expect(replacement.send).toHaveBeenCalledTimes(2) - expect(replacement.listenerCount('message')).toBe(1) - expect(replacement.listenerCount('close')).toBe(2) - expect(vi.getTimerCount()).toBe(1) await vi.advanceTimersByTimeAsync(10_000) expect(oldPeer.close).not.toHaveBeenCalled() expect(replacement.close).not.toHaveBeenCalled() h.registry.drain(0) await vi.advanceTimersByTimeAsync(0) - expect(vi.getTimerCount()).toBe(0) }) }) diff --git a/cloud/apps/relay/src/connections/host-control-resume-identity.test.ts b/cloud/apps/relay/src/connections/host-control-resume-identity.test.ts index ca2fe295f13..ddd4491f90d 100644 --- a/cloud/apps/relay/src/connections/host-control-resume-identity.test.ts +++ b/cloud/apps/relay/src/connections/host-control-resume-identity.test.ts @@ -1,4 +1,3 @@ -import { CONTROL_CONTINUITY_LIMITS } from '@orca-cloud/relay-contract/control-continuity' import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RelayTokenClaims } from '../authentication/relay-token-verifier.js' @@ -46,7 +45,6 @@ async function lapsedHost() { ) const session = h.registry.get({ userId: h.identity.sub, relayHostId: h.identity.relayHostId }) expect(session?.state).toBe('orphaned') - expect(CONTROL_CONTINUITY_LIMITS.orphanGraceMs).toBeGreaterThan(5_000) await vi.advanceTimersByTimeAsync(5_000) return { h, ack, session: session!, resumeHello: resumeHelloFor(h.hello, ack) } } diff --git a/cloud/apps/relay/src/connections/host-session-client-accept.test.ts b/cloud/apps/relay/src/connections/host-session-client-accept.test.ts index ae251b5b94b..c8766c2ceb6 100644 --- a/cloud/apps/relay/src/connections/host-session-client-accept.test.ts +++ b/cloud/apps/relay/src/connections/host-session-client-accept.test.ts @@ -229,7 +229,6 @@ describe('client accept abandoned mid-DB-phase', () => { capacity ) await vi.advanceTimersByTimeAsync(0) - expect(h.acquireActivity).toHaveBeenCalledOnce() // The phone's 12s bound fires while the cell still waits on Postgres. client.close(1000, 'client bound') capacity.release() @@ -247,54 +246,12 @@ describe('client accept abandoned mid-DB-phase', () => { { userId: identity.sub, relayHostId: identity.relayHostId }, expect.stringMatching(/^confirmation:/) ) - expect(h.observer.recordClientAcceptAbandoned).toHaveBeenCalledWith( - 'activity', - expect.any(Number) - ) - const line = warn.mock.calls - .map((call) => String(call[0])) - .find((entry) => entry.includes('orca_relay_client_accept_abandoned')) - expect(line).toBeDefined() - expect(JSON.parse(line!)).toMatchObject({ stage: 'activity' }) - expect(line).not.toContain(identity.relayHostId) } finally { warn.mockRestore() h.registry.drain(0) vi.advanceTimersByTime(0) } }) - - it('stops after a slow credential reservation without acquiring an activity lease', async () => { - const h = harness() - await activeHost(h) - const slowReserve = deferred() - h.store.reserveCredential.mockReturnValueOnce(slowReserve.promise) - const client = new FakeSocket() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - try { - const accepting = h.registry.acceptClient( - client as unknown as WebSocket, - identity.relayHostId, - 'credential' - ) - await vi.advanceTimersByTimeAsync(0) - client.close(1000, 'client bound') - slowReserve.resolve(reservation) - await accepting - - expect(h.acquireActivity).not.toHaveBeenCalled() - expect(h.store.failReservation).toHaveBeenCalledWith(reservation) - expect(h.observer.recordClientAcceptAbandoned).toHaveBeenCalledWith( - 'credential', - expect.any(Number) - ) - } finally { - warn.mockRestore() - h.registry.drain(0) - vi.advanceTimersByTime(0) - } - }) - }) // The attach resolves its owning session once and hands it to the unfenced leg; @@ -360,7 +317,6 @@ describe('host data attach ownership', () => { 1 ) await vi.advanceTimersByTimeAsync(0) - expect(h.store.recordConnectionBasis).toHaveBeenCalledOnce() expect(client.send).not.toHaveBeenCalledWith(expect.stringContaining('relay-hello')) basis.resolve() expect(await attaching).toBe(true) @@ -420,17 +376,4 @@ describe('paced drain and the phones of a host not yet told', () => { expect(served.close).not.toHaveBeenCalled() expect(untold.send).toHaveBeenCalledWith(expect.stringContaining('conn-open')) }) - - it("refuses that host's phones as soon as its own drain is sent", async () => { - const { h, untold } = await twoHostCell() - h.registry.drain(0, { paceWindowMs: 40_000 }) - await vi.advanceTimersByTimeAsync(40_000) - // Told by its zero-grace close, a timer nested 1 ms after the send. - await vi.advanceTimersByTimeAsync(1) - expect(untold.send).toHaveBeenCalledWith(expect.stringContaining('"type":"drain"')) - - const refused = await dial(h, laterHostId) - expect(refused.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, expect.any(String)) - }) - }) diff --git a/cloud/apps/relay/src/connections/host-session-drain-release-order.test.ts b/cloud/apps/relay/src/connections/host-session-drain-release-order.test.ts index 97339860387..ae29c5a6954 100644 --- a/cloud/apps/relay/src/connections/host-session-drain-release-order.test.ts +++ b/cloud/apps/relay/src/connections/host-session-drain-release-order.test.ts @@ -1,6 +1,5 @@ import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { DRAIN_RELEASE_BEFORE_CLOSE_MS } from './host-session-registry.js' import { answerProof, hostControlProofFixture, @@ -70,48 +69,4 @@ describe('a zero-grace drain releases the host before telling it', () => { socket.close.mock.invocationCallOrder[0]! ) }) - - it('closes on the bound when the release has not landed, as before this ordering', async () => { - const { h, socket } = await connectedHost() - vi.spyOn(h.assignments, 'releaseActivity').mockReturnValue(pendingRelease().promise) - - h.registry.drain(0) - await vi.advanceTimersByTimeAsync(DRAIN_RELEASE_BEFORE_CLOSE_MS - 1) - expect(socket.close).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(2) - expect(frames(socket)).toEqual([{ type: 'drain', graceMs: 0, recovery: 'resolve-director' }]) - expect(socket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.DRAINING, - 'resolve configured director' - ) - const slow = vi - .mocked(console.warn) - .mock.calls.map(([line]) => String(line)) - .filter((line) => line.includes('"orca_relay_host_drain_release_slow"')) - expect(slow).toHaveLength(1) - expect(slow[0]).not.toContain(h.identity.relayHostId) - }) - - it('still tells a host with grace at once, and releases it before the closing deadline', async () => { - const { h, socket } = await connectedHost() - const release = pendingRelease() - vi.spyOn(h.assignments, 'releaseActivity').mockReturnValue(release.promise) - - h.registry.drain(10_000) - expect(frames(socket)).toEqual([ - { type: 'drain', graceMs: 10_000, recovery: 'resolve-director' } - ]) - - await vi.advanceTimersByTimeAsync(10_000) - expect(socket.close).not.toHaveBeenCalled() - release.settle('released') - await vi.advanceTimersByTimeAsync(0) - expect(socket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.DRAINING, - 'resolve configured director' - ) - // Told once, by the drain itself; the close adds no second frame. - expect(frames(socket)).toHaveLength(1) - }) }) diff --git a/cloud/apps/relay/src/connections/host-session-registry.test.ts b/cloud/apps/relay/src/connections/host-session-registry.test.ts index 0b9e41651b7..1208ebd1658 100644 --- a/cloud/apps/relay/src/connections/host-session-registry.test.ts +++ b/cloud/apps/relay/src/connections/host-session-registry.test.ts @@ -1,31 +1,22 @@ import { EventEmitter } from 'node:events' -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' import { CONTROL_CONTINUITY_LIMITS } from '@orca-cloud/relay-contract/control-continuity' import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' import { RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME } from '@orca-cloud/relay-contract/control-messages' -import { RELAY_PROTOCOL_LIMITS } from '@orca-cloud/relay-contract/protocol-limits' -import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type WebSocket from 'ws' import type { RelayAssignmentStore } from '../assignment/assignment-store.js' import type { RelayConfig } from '../config.js' import type { RelayCredentialStore } from '../credentials/credential-store.js' import { CONTROL_RENEWAL_BATCH_INTERVAL_MS } from '../control-leases/control-renewal-batch.js' import type { - ControlRenewalOutcome, - ControlRenewalRequest + ControlRenewalOutcome } from '../control-leases/control-renewal-statement.js' import { HostSessionRegistry, IDLE_REHOME_MIN_CONTROL_AGE_MS, type HostSession } from './host-session-registry.js' -import { relayHostLogDigest } from '../observability/relay-host-log-digest.js' import type { RelayRuntimeObserver } from '../observability/relay-observability.js' -import { - REGIONAL_REHOME_TRUST_PROBE_ATTEMPT_ID, - REGIONAL_REHOME_TRUST_PROBE_HOST_ID, - REGIONAL_REHOME_TRUST_PROBE_USER_ID -} from '../assignment/regional-rehome/regional-rehome-trust-probe.js' import type { RelayTokenClaims } from '../authentication/relay-token-verifier.js' import { ProcessQueuedByteBudget } from './splice-forwarder.js' @@ -204,277 +195,6 @@ describe('host session cleanup races', () => { vi.useRealTimers() }) - it('logs control closes with a host digest and counts them, never the raw id', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { activate, observer } = createRegistry(activateControl) - const socket = new FakeSocket() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - socket.emit('error', new RangeError('Max payload size exceeded')) - socket.close(1006, 'network reset') - - expect(observer.recordControlClose).toHaveBeenCalledWith(1006) - const line = warn.mock.calls - .map((call) => String(call[0])) - .find((entry) => entry.includes('control closed')) - expect(line).toContain(`host=${relayHostLogDigest(identity.relayHostId)}`) - expect(line).toContain('code=1006') - expect(line).toContain('Max payload size exceeded') - expect(line).not.toContain(identity.relayHostId) - } finally { - warn.mockRestore() - } - }) - - it('contains a dependency failure to one socket instead of the process', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - // The same rejection shape as a pg-pool connect timeout; unguarded, it - // became an unhandled rejection that crashed whole production cells. - const verifyRelayToken = vi.fn(async (): Promise => { - throw new Error('Connection terminated due to connection timeout') - }) - const { activate } = createRegistry(activateControl, {}, verifyRelayToken) - const socket = new FakeSocket() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - await activate(socket as unknown as WebSocket, identity, null, 1, false, 7) - socket.emit( - 'message', - Buffer.from(JSON.stringify({ type: 'auth-refresh', relayJwt: 'refreshed' })), - false - ) - await vi.waitFor(() => - expect(socket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.LIMIT_EXCEEDED, - 'relay temporarily unavailable' - ) - ) - expect(warn).toHaveBeenCalledWith( - '[orca-relay] auth refresh failed: Connection terminated due to connection timeout' - ) - } finally { - warn.mockRestore() - } - }) - - it('attributes a control close to its client build without trusting the version string', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { activate } = createRegistry(activateControl) - const socket = new FakeSocket() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - // A client controls this string, so it must be bounded and stripped like any close reason. - await activate( - socket as unknown as WebSocket, - identity, - null, - 1, - false, - 1, - `1.4.173\n${'x'.repeat(200)}` - ) - socket.close(4408, 'replaced by a newer generation') - - const line = warn.mock.calls - .map((call) => String(call[0])) - .find((entry) => entry.includes('control closed')) - expect(line).toContain('app="1.4.173') - // The raw newline is escaped by JSON.stringify either way; only its escaped - // form proves the strip ran, so assert on that. - expect(line).not.toContain('\\n') - expect(line).toMatch(/app="[^"]{1,80}"/) - } finally { - warn.mockRestore() - } - }) - - it('keeps the first drain snapshot when a drain is retried', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate } = createRegistry(activateControl) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - // Captured before draining, because teardown removes the session from the map. - const session = registry.get({ - userId: identity.sub, - relayHostId: identity.relayHostId - })! - session.activeSplices.set('conn-a', () => session.activeSplices.delete('conn-a')) - - // Drain retries/signals must re-arm, not stack teardown; a paced 800-host cell otherwise leaks 800 timers holding exit open each retry. - registry.drain(0) - const scheduled = vi.getTimerCount() - registry.drain(0) - // Compare against the count before the retry rather than an absolute, since the - // session's heartbeat interval is also pending. - expect(vi.getTimerCount()).toBe(scheduled) - vi.advanceTimersByTime(1) - - // Check state: synchronous FakeSocket close logs before second teardown, so log-only assertions miss corruption. - expect(session.closingCounts).toEqual({ splices: 1, pending: 0 }) - }) - - it('drains only the incarnation-bound host and makes replay idempotent', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate } = createRegistry( - activateControl, - {}, - vi.fn(async () => identity) - ) - const firstSocket = new FakeSocket() - const secondSocket = new FakeSocket() - const secondIdentity = { - ...identity, - sub: 'user-2', - relayHostId: 'ponmlkjihgfedcba' - } - await activate(firstSocket as unknown as WebSocket, identity, null, 1, false, 7) - await activate(secondSocket as unknown as WebSocket, secondIdentity, null, 1, false, 3) - const trustProbe = { - attemptId: REGIONAL_REHOME_TRUST_PROBE_ATTEMPT_ID, - userId: REGIONAL_REHOME_TRUST_PROBE_USER_ID, - relayHostId: REGIONAL_REHOME_TRUST_PROBE_HOST_ID, - sourceAssignmentEpoch: 1, - graceMs: 0 - } - expect(registry.get(trustProbe)).toBeNull() - expect(registry.drainHost(trustProbe)).toBe('host-not-connected') - expect(registry.drainHost(trustProbe)).toBe('host-not-connected') - expect(firstSocket.send).not.toHaveBeenCalledWith(expect.stringContaining('"drain"')) - expect(secondSocket.send).not.toHaveBeenCalledWith(expect.stringContaining('"drain"')) - const request = { - attemptId: '11111111-1111-4111-8111-111111111111', - userId: identity.sub, - relayHostId: identity.relayHostId, - sourceAssignmentEpoch: 7, - graceMs: 30_000 - } - - expect(registry.drainHost(request)).toBe('accepted') - expect(firstSocket.send).toHaveBeenCalledWith( - JSON.stringify({ type: 'drain', graceMs: 30_000, recovery: 'resolve-director' }) - ) - expect(secondSocket.send).not.toHaveBeenCalledWith(expect.stringContaining('"drain"')) - firstSocket.emit( - 'message', - Buffer.from(JSON.stringify({ type: 'auth-refresh', relayJwt: 'refreshed' })), - false - ) - await vi.waitFor(() => expect(registry.get(request)?.state).toBe('drain-only')) - const timers = vi.getTimerCount() - expect(registry.drainHost(request)).toBe('already-accepted') - expect(vi.getTimerCount()).toBe(timers) - expect(() => - registry.drainHost({ - ...request, - attemptId: '22222222-2222-4222-8222-222222222222' - }) - ).toThrow('regional_rehome_attempt_conflict') - expect(() => registry.drainHost({ ...request, sourceAssignmentEpoch: 8 })).toThrow( - 'regional_rehome_assignment_epoch_mismatch' - ) - - const rebound = new FakeSocket() - await activate(rebound as unknown as WebSocket, identity, registry.get(request), 1, true, 7) - expect(registry.get(request)?.state).toBe('drain-only') - expect(rebound.send).toHaveBeenCalledWith(expect.stringContaining('"type":"drain"')) - - await vi.advanceTimersByTimeAsync(30_000) - expect(registry.get(request)).toBeNull() - expect( - registry.get({ userId: secondIdentity.sub, relayHostId: secondIdentity.relayHostId }) - ).not.toBeNull() - expect(secondSocket.close).not.toHaveBeenCalled() - }) - - it('keeps every live control socket indexed when first activations overlap', async () => { - const firstControl = deferred() - const secondControl = deferred() - const activateControl = vi - .fn() - .mockReturnValueOnce(firstControl.promise) - .mockReturnValueOnce(secondControl.promise) - const { registry, activate } = createRegistry(activateControl) - const firstSocket = new FakeSocket() - const secondSocket = new FakeSocket() - - const first = activate(firstSocket as unknown as WebSocket, identity, null, 1, false, 1) - const second = activate(secondSocket as unknown as WebSocket, identity, null, 1, false, 1) - secondControl.resolve('control:production-gce-c3:1') - await Promise.resolve() - firstControl.resolve('control:production-gce-c3:1') - await Promise.all([first, second]) - - const liveSockets = [firstSocket, secondSocket].filter( - (socket) => socket.readyState === socket.OPEN - ) - const session = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId }) - expect(liveSockets).toHaveLength(1) - expect(session?.socket).toBe(liveSockets[0]) - }) - - it('does not publish a control that closes during activation', async () => { - const blocked = deferred() - const activateControl = vi - .fn() - .mockReturnValueOnce(blocked.promise) - const { registry, activate, releaseActivity } = createRegistry(activateControl) - const socket = new FakeSocket() - - const activation = activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - await vi.advanceTimersByTimeAsync(0) - expect(activateControl).toHaveBeenCalledOnce() - socket.close() - blocked.resolve('control:production-gce-c3:1') - await activation - - expect(registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })).toBeNull() - expect(releaseActivity).toHaveBeenCalledWith( - { userId: identity.sub, relayHostId: identity.relayHostId }, - 'control:production-gce-c3:1' - ) - }) - - it('does not rebind a control that closes during activation', async () => { - const blocked = deferred() - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - .mockReturnValueOnce(blocked.promise) - const { registry, activate, releaseActivity } = createRegistry(activateControl) - const originalSocket = new FakeSocket() - await activate(originalSocket as unknown as WebSocket, identity, null, 1, false, 1) - const original = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId }) - expect(original).not.toBeNull() - - const rebindSocket = new FakeSocket() - const rebinding = activate(rebindSocket as unknown as WebSocket, identity, original, 1, true, 1) - await vi.advanceTimersByTimeAsync(0) - expect(activateControl).toHaveBeenCalledTimes(2) - rebindSocket.close() - blocked.resolve('control:production-gce-c3:1') - await rebinding - - const session = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId }) - expect(session).toBe(original) - expect(session?.socket).toBe(originalSocket) - expect(session?.state).toBe('active') - expect(releaseActivity).toHaveBeenCalledWith( - { userId: identity.sub, relayHostId: identity.relayHostId }, - 'control:production-gce-c3:1' - ) - }) - // c34 ghost seat came from activation outliving orphan grace and reviving a removed session outside the map. it('refuses a rebind whose session left the map while its activation was in flight', async () => { const blocked = deferred() @@ -495,7 +215,6 @@ describe('host session cleanup races', () => { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeSocket implements the registry's WebSocket event and lifecycle surface. const rebinding = activate(rebindSocket as unknown as WebSocket, identity, original, 1, true, 1) await vi.advanceTimersByTimeAsync(0) - expect(activateControl).toHaveBeenCalledTimes(2) // The grace runs out while the database answers slowly. await vi.advanceTimersByTimeAsync(CONTROL_CONTINUITY_LIMITS.orphanGraceMs) expect(registry.get(key)).toBeNull() @@ -513,249 +232,6 @@ describe('host session cleanup races', () => { expect(releaseActivity).toHaveBeenCalledWith(key, 'control:production-gce-c3:1') }) - // Two hellos proven against the same empty map could take the same generation; an activation at - // a generation this host already had here is refused, so a late leave cannot share it. - it('refuses a fresh activation at a generation this host already had here', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:2') - const { registry, activate } = createRegistry(activateControl) - const key = { userId: identity.sub, relayHostId: identity.relayHostId } - const first = new FakeSocket() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeSocket implements the registry's WebSocket event and lifecycle surface. - await activate(first as unknown as WebSocket, identity, null, 2, false, 1) - first.close(1006, 'network reset') - await vi.advanceTimersByTimeAsync(CONTROL_CONTINUITY_LIMITS.orphanGraceMs) - expect(registry.get(key)).toBeNull() - const reused = new FakeSocket() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeSocket implements the registry's WebSocket event and lifecycle surface. - await activate(reused as unknown as WebSocket, identity, null, 2, false, 1) - expect(reused.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.PEER_DROPPED, - 'control activation superseded' - ) - expect(registry.get(key)).toBeNull() - }) - - it('skips a closed queued control so its live retry avoids abandoned database work', async () => { - const stalled = deferred() - const activateControl = vi - .fn() - .mockReturnValueOnce(stalled.promise) - .mockImplementation(async () => { - await new Promise((resolve) => setTimeout(resolve, 4_000)) - return 'control:production-gce-c3:1' - }) - const { registry, activate, releaseActivity } = createRegistry(activateControl) - const firstSocket = new FakeSocket() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeSocket implements the registry's WebSocket event and lifecycle surface. - const first = activate(firstSocket as unknown as WebSocket, identity, null, 1, false, 1) - await vi.advanceTimersByTimeAsync(0) - expect(activateControl).toHaveBeenCalledOnce() - const abandonedSocket = new FakeSocket() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeSocket implements the registry's WebSocket event and lifecycle surface. - const abandoned = activate(abandonedSocket as unknown as WebSocket, identity, null, 1, false, 1) - const liveSocket = new FakeSocket() - const startedAt = Date.now() - let liveCompletedAt: number | undefined - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeSocket implements the registry's WebSocket event and lifecycle surface. - const live = activate(liveSocket as unknown as WebSocket, identity, null, 1, false, 1).then( - () => { - liveCompletedAt = Date.now() - } - ) - firstSocket.close() - abandonedSocket.close() - stalled.resolve('control:production-gce-c3:1') - await vi.advanceTimersByTimeAsync(8_000) - await Promise.all([first, abandoned, live]) - - console.log( - JSON.stringify({ - scenario: 'closed queued control before a live retry', - activationCalls: activateControl.mock.calls.length, - activityReleases: releaseActivity.mock.calls.length, - liveReadyMs: liveCompletedAt === undefined ? null : liveCompletedAt - startedAt - }) - ) - expect(activateControl).toHaveBeenCalledTimes(2) - expect(releaseActivity).toHaveBeenCalledOnce() - expect(liveCompletedAt! - startedAt).toBe(4_000) - expect(registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })?.socket).toBe( - liveSocket - ) - }) - - it('rejects client lookup when the indexed control socket is not open', async () => { - const reservation = { - userId: identity.sub, - relayHostId: identity.relayHostId, - credentialKind: 'resume', - relayDeviceId: 'device-1', - leaseExpiresAt: Date.now() + 60_000 - } - const store = { - resolveResume: vi.fn().mockResolvedValue({ userId: identity.sub }), - reserveCredential: vi.fn().mockResolvedValue(reservation), - failReservation: vi.fn().mockResolvedValue(undefined) - } - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - const { registry, activate } = createRegistry(activateControl, store) - const controlSocket = new FakeSocket() - await activate(controlSocket as unknown as WebSocket, identity, null, 1, false, 1) - const session = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId }) - expect(session?.state).toBe('active') - // A dead socket that never delivered its close event: state stays active, - // so only the readyState guard can protect the lookup. - controlSocket.readyState = controlSocket.CLOSED - - const client = new FakeSocket() - await registry.acceptClient(client as unknown as WebSocket, identity.relayHostId, 'credential') - - expect(store.failReservation).toHaveBeenCalledWith(reservation) - expect(client.send).toHaveBeenCalledWith( - JSON.stringify({ type: 'relay-hello', ok: false, code: RELAY_CLOSE_CODE.HOST_OFFLINE }) - ) - expect(session?.pendingConns.size).toBe(0) - }) - - it('fails a control waiting behind a stalled activation without breaking serialization', async () => { - const stalled = deferred() - const activateControl = vi - .fn() - .mockReturnValueOnce(stalled.promise) - const { registry, activate } = createRegistry(activateControl) - const stalledSocket = new FakeSocket() - const first = activate(stalledSocket as unknown as WebSocket, identity, null, 1, false, 1) - const waitingSocket = new FakeSocket() - const second = activate(waitingSocket as unknown as WebSocket, identity, null, 1, false, 1) - - // Let the first activation reach the store (clearing its own queue timer) - // before the waiting control's deadline elapses. - await Promise.resolve() - await Promise.resolve() - vi.advanceTimersByTime(30_000) - expect(waitingSocket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.LIMIT_EXCEEDED, - 'control activation queue stalled' - ) - // The waiting control never reached the store; serialization held. - expect(activateControl).toHaveBeenCalledOnce() - - stalled.resolve('control:production-gce-c3:1') - await Promise.all([first, second]) - const session = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId }) - expect(session?.socket).toBe(stalledSocket) - expect(session?.state).toBe('active') - }) - - it('rejects an activation that returns after drain begins', async () => { - const blocked = deferred() - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - .mockReturnValueOnce(blocked.promise) - const { registry, activate, renewControlActivities, releaseActivity } = - createRegistry(activateControl) - const originalSocket = new FakeSocket() - await activate(originalSocket as unknown as WebSocket, identity, null, 1, false, 1) - const original = registry.get({ - userId: identity.sub, - relayHostId: identity.relayHostId - }) - expect(original).not.toBeNull() - - const replacementSocket = new FakeSocket() - const replacement = activate( - replacementSocket as unknown as WebSocket, - identity, - original, - 2, - false, - 1 - ) - registry.drain(100) - blocked.resolve('control:production-gce-c3:2') - await replacement - vi.advanceTimersByTime(100) - vi.advanceTimersByTime(15_000) - - expect(replacementSocket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.DRAINING, - 'relay draining' - ) - expect(registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })).toBeNull() - expect(renewControlActivities).not.toHaveBeenCalled() - expect(releaseActivity).toHaveBeenCalledWith( - { userId: identity.sub, relayHostId: identity.relayHostId }, - 'control:production-gce-c3:2' - ) - }) - - it('keeps a replacement mapped after stale orphan cleanup', async () => { - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - .mockResolvedValueOnce('control:production-gce-c3:2') - const { registry, activate } = createRegistry(activateControl) - const originalSocket = new FakeSocket() - await activate(originalSocket as unknown as WebSocket, identity, null, 1, false, 1) - const original = registry.get({ - userId: identity.sub, - relayHostId: identity.relayHostId - }) - expect(original).not.toBeNull() - originalSocket.close() - - const replacementSocket = new FakeSocket() - await activate(replacementSocket as unknown as WebSocket, identity, original, 2, false, 1) - const replacement = registry.get({ - userId: identity.sub, - relayHostId: identity.relayHostId - }) - vi.advanceTimersByTime(CONTROL_CONTINUITY_LIMITS.orphanGraceMs) - - expect(replacement).not.toBeNull() - expect(registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })).toBe( - replacement - ) - expect(registry.runtimeCounts().controls).toBe(1) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - - it('stops the heartbeat of an actively replaced generation', async () => { - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - .mockResolvedValueOnce('control:production-gce-c3:2') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const originalSocket = new FakeSocket() - await activate(originalSocket as unknown as WebSocket, identity, null, 1, false, 1) - const original = registry.get({ - userId: identity.sub, - relayHostId: identity.relayHostId - }) - expect(original).not.toBeNull() - - await activate(new FakeSocket() as unknown as WebSocket, identity, original, 2, false, 1) - await vi.advanceTimersByTimeAsync(15_000) - await closeRenewalWindow() - - expect(renewControlActivities).toHaveBeenCalledOnce() - expect(renewControlActivities).toHaveBeenCalledWith([ - expect.objectContaining({ - identity: { userId: identity.sub, relayHostId: identity.relayHostId }, - activityId: 'control:production-gce-c3:2', - cellId: 'production-gce-c3' - }) - ]) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - it('ignores a denial belonging to the socket before a same-generation rebind', async () => { const h = createRegistry(vi.fn().mockResolvedValue('control:production-gce-c3:1')) const oldSocket = new FakeSocket() @@ -777,339 +253,6 @@ describe('host session cleanup races', () => { expect(session.socket).toBe(replacement) expect(session.generation).toBe(1) }) - - it('ignores missing-activity recovery denial after an authority transition', async () => { - const h = createRegistry(vi.fn().mockResolvedValue('control:production-gce-c3:1')) - const socket = new FakeSocket() - await h.activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - const session = h.registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! - h.renewControlActivities.mockResolvedValueOnce(['control_activity_not_found']) - let reject!: (error: Error) => void - h.acquireActivity.mockReturnValueOnce( - new Promise((_, fail) => { - reject = fail - }) - ) - await vi.advanceTimersByTimeAsync(15_000) - await closeRenewalWindow() - h.registry.drainHost({ - attemptId: 'attempt', - userId: identity.sub, - relayHostId: identity.relayHostId, - sourceAssignmentEpoch: 1, - graceMs: 60_000 - }) - reject(new Error('activity_cell_not_authoritative')) - await vi.advanceTimersByTimeAsync(0) - expect(socket.close).not.toHaveBeenCalled() - expect(session.state).toBe('drain-only') - }) - - it('keeps 15s pings while halving steady-state control renewals', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const socket = new FakeSocket() - const activatedAt = Date.now() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - - for (let interval = 0; interval < 4; interval++) { - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - socket.emit('message', Buffer.from(JSON.stringify({ type: 'pong' })), false) - await closeRenewalWindow() - } - - const pings = socket.send.mock.calls.filter((call) => String(call[0]).includes('"ping"')) - expect(pings).toHaveLength(4) - expect(renewControlActivities).toHaveBeenCalledTimes(2) - const firstExpiry = Number(renewControlActivities.mock.calls[0]![0][0]!.expiresAt) - const secondExpiry = Number(renewControlActivities.mock.calls[1]![0][0]!.expiresAt) - expect(firstExpiry).toBe( - activatedAt + - RELAY_PROTOCOL_LIMITS.controlPingIntervalMs + - ASSIGNMENT_LIMITS.activityLeaseMs + - RELAY_PROTOCOL_LIMITS.controlPingIntervalMs - ) - expect(secondExpiry - firstExpiry).toBe(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs * 2) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - - it('retries a failed control renewal on the next ping', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - renewControlActivities.mockRejectedValueOnce(new Error('pool timeout')) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const socket = new FakeSocket() - try { - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - expect(renewControlActivities).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - expect(renewControlActivities).toHaveBeenCalledTimes(2) - } finally { - warn.mockRestore() - registry.drain(0) - vi.advanceTimersByTime(0) - } - }) - - it('retries past a stalled control renewal without waiting for it', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const stalled = deferred() - renewControlActivities.mockReturnValueOnce(stalled.promise) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs * 2) - await closeRenewalWindow() - - expect(renewControlActivities).toHaveBeenCalledTimes(2) - stalled.resolve(['renewed']) - await vi.advanceTimersByTimeAsync(0) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - - it('ignores a superseded renewal resolving after a fresher success', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const stalled = deferred() - renewControlActivities.mockReturnValueOnce(stalled.promise) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs * 2) - await closeRenewalWindow() - expect(renewControlActivities).toHaveBeenCalledTimes(2) - stalled.resolve(['renewed']) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - - expect(renewControlActivities).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - - expect(renewControlActivities).toHaveBeenCalledTimes(3) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - - it('closes when a missing control activity cannot be re-acquired on this cell', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, acquireActivity, renewControlActivities } = - createRegistry(activateControl) - renewControlActivities.mockResolvedValueOnce(['control_activity_not_found']) - acquireActivity.mockRejectedValueOnce(new Error('activity_cell_not_authoritative')) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - - expect(socket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.DRAINING, - 'control migration completed' - ) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - - it('closes a control when renewal finds its cell is no longer authoritative', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - renewControlActivities.mockResolvedValueOnce(['activity_cell_not_authoritative']) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - - expect(socket.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.DRAINING, - 'control migration completed' - ) - registry.drain(0) - vi.advanceTimersByTime(0) - }) - - it('continues renewing throughout the drain grace period', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - registry.drain(60_000) - - for (let interval = 0; interval < 3; interval++) { - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - socket.emit('message', Buffer.from(JSON.stringify({ type: 'pong' })), false) - await closeRenewalWindow() - } - - expect(renewControlActivities).toHaveBeenCalledTimes(2) - expect(socket.readyState).toBe(socket.OPEN) - vi.advanceTimersByTime(15_000) - }) -}) - -describe('control renewal cadence across a rebind', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - it('keeps the halved cadence after a rebind lands under a stalled renewal', async () => { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const ping = RELAY_PROTOCOL_LIMITS.controlPingIntervalMs - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - - const beat = async (target: FakeSocket): Promise => { - await vi.advanceTimersByTimeAsync(ping) - target.emit('message', Buffer.from(JSON.stringify({ type: 'pong' })), false) - await closeRenewalWindow() - } - - // Age the session so its attempt counter is well above zero. - for (let tick = 0; tick < 5; tick++) await beat(socket) - expect(renewControlActivities).toHaveBeenCalledTimes(3) - - // The next renewal stalls and is still in flight when the control rebinds. - const stalled = deferred() - renewControlActivities.mockReturnValueOnce(stalled.promise) - for (let tick = 0; tick < 2; tick++) await beat(socket) - expect(renewControlActivities).toHaveBeenCalledTimes(4) - - const session = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! - const rebindSocket = new FakeSocket() - await activate(rebindSocket as unknown as WebSocket, identity, session, 1, true, 1) - stalled.resolve(['renewed']) - await vi.advanceTimersByTimeAsync(0) - - const before = renewControlActivities.mock.calls.length - for (let tick = 0; tick < 4; tick++) await beat(rebindSocket) - expect(renewControlActivities.mock.calls.length - before).toBe(2) - - registry.drain(0) - vi.advanceTimersByTime(0) - }) -}) - -describe('control renewals shared by one batch', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - it('renews two due hosts in one call and leaves a stale one alone', async () => { - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - .mockResolvedValueOnce('control:production-gce-c3:1') - const { registry, activate, renewControlActivities } = createRegistry(activateControl) - const other = { ...identity, sub: 'user-2', relayHostId: 'ponmlkjihgfedcba' } - const staleSocket = new FakeSocket() - const liveSocket = new FakeSocket() - await activate(staleSocket as unknown as WebSocket, identity, null, 1, false, 1) - await activate(liveSocket as unknown as WebSocket, other, null, 1, false, 1) - const stale = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! - const live = registry.get({ userId: other.sub, relayHostId: other.relayHostId })! - - // Both come due inside the same window, and one socket goes away while the - // statement is still in PostgreSQL. - let release!: () => void - renewControlActivities.mockImplementationOnce( - async (rows: readonly ControlRenewalRequest[]) => { - staleSocket.close() - await new Promise((resolve) => (release = resolve)) - return rows.map((): ControlRenewalOutcome => 'renewed') - } - ) - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - const staleDueAt = stale.activityRenewalDueAt - await closeRenewalWindow() - release() - await vi.advanceTimersByTimeAsync(0) - - expect(renewControlActivities).toHaveBeenCalledOnce() - expect( - renewControlActivities.mock.calls[0]![0].map( - (row: ControlRenewalRequest) => row.identity.relayHostId - ) - ).toEqual([identity.relayHostId, other.relayHostId]) - expect(live.activityRenewalCompletedAttempt).toBe(1) - expect(stale.activityRenewalCompletedAttempt).toBe(0) - expect(stale.activityRenewalDueAt).toBe(staleDueAt) - registry.drain(0) - vi.advanceTimersByTime(0) - }) -}) - -describe('control lease recovery after the session is gone', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - it('does not re-acquire a lease for a session a newer generation already replaced', async () => { - const activateControl = vi - .fn() - .mockResolvedValueOnce('control:production-gce-c3:1') - .mockResolvedValueOnce('control:production-gce-c3:2') - const { registry, activate, acquireActivity, renewControlActivities } = - createRegistry(activateControl) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - try { - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - const session = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! - - // The renewal is still in flight when a newer generation takes over. - let finishRenewal!: (outcomes: ControlRenewalOutcome[]) => void - renewControlActivities.mockReturnValueOnce( - new Promise((resolve) => (finishRenewal = resolve)) - ) - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - await closeRenewalWindow() - expect(renewControlActivities).toHaveBeenCalledOnce() - - const newer = new FakeSocket() - await activate(newer as unknown as WebSocket, identity, session, 2, false, 1) - - // Its release already removed the lease, so the renewal reports it missing. - finishRenewal(['control_activity_not_found']) - await vi.advanceTimersByTimeAsync(0) - - expect(acquireActivity).not.toHaveBeenCalled() - } finally { - warn.mockRestore() - registry.drain(0) - vi.advanceTimersByTime(0) - } - }) }) describe('source-owned idle cutover', () => { @@ -1127,11 +270,8 @@ describe('source-owned idle cutover', () => { sourceCellIncarnation: 'incarnation-1', targetCellId: 'target' } - async function source( - store: Partial = {}, - controlAgeMs = IDLE_REHOME_MIN_CONTROL_AGE_MS - ) { - const h = createRegistry(vi.fn().mockResolvedValue('control:1'), store) + async function source() { + const h = createRegistry(vi.fn().mockResolvedValue('control:1')) const socket = new FakeSocket() h.registry.acceptControl( socket as unknown as WebSocket, @@ -1142,127 +282,10 @@ describe('source-owned idle cutover', () => { socket.removeAllListeners('message') await h.activate(socket as unknown as WebSocket, identity, null, 1, false, 1) // Moves the clock without firing the heartbeat timers that would close the session. - vi.setSystemTime(Date.now() + controlAgeMs) + vi.setSystemTime(Date.now() + IDLE_REHOME_MIN_CONTROL_AGE_MS) return { ...h, socket, session: h.registry.get(request)! } } - it.each([ - { controlAgeMs: 0, outcome: 'busy' }, - { controlAgeMs: IDLE_REHOME_MIN_CONTROL_AGE_MS - 1, outcome: 'busy' }, - { controlAgeMs: IDLE_REHOME_MIN_CONTROL_AGE_MS, outcome: 'committed' }, - { controlAgeMs: 60 * 60 * 1000, outcome: 'committed' } - ])('answers $outcome for a control socket $controlAgeMs ms old', async (row) => { - const { controlAgeMs, outcome } = row - const h = await source({}, controlAgeMs) - const commit = vi.fn().mockResolvedValue({ outcome: 'committed' }) - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome }) - expect(commit).toHaveBeenCalledTimes(outcome === 'busy' ? 0 : 1) - await vi.advanceTimersByTimeAsync(0) - expect(h.socket.close).toHaveBeenCalledTimes(outcome === 'busy' ? 0 : 1) - }) - it('restarts the age when the host rebinds its control socket', async () => { - const h = await source() - const rebound = new FakeSocket() - h.registry.acceptControl( - rebound as unknown as WebSocket, - identity, - undefined, - new Set([RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME]) - ) - rebound.removeAllListeners('message') - await h.activate(rebound as unknown as WebSocket, identity, h.session, 1, true, 1) - const commit = vi.fn().mockResolvedValue({ outcome: 'committed' }) - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'busy' }) - expect(commit).not.toHaveBeenCalled() - }) - it('closes a superseded socket whose refresh meets the cutover, not its successor', async () => { - const h = await source() - const successor = new FakeSocket() - h.registry.acceptControl( - successor as unknown as WebSocket, - identity, - undefined, - new Set([RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME]) - ) - successor.removeAllListeners('message') - await h.activate(successor as unknown as WebSocket, identity, h.session, 1, true, 1) - vi.setSystemTime(Date.now() + IDLE_REHOME_MIN_CONTROL_AGE_MS) - const commit = deferred<{ outcome: 'committed' }>() - const cutover = h.registry.idleRehome( - request, - vi.fn(() => commit.promise), - vi.fn().mockResolvedValue('not-committed') - ) - h.socket.emit( - 'message', - Buffer.from(JSON.stringify({ type: 'auth-refresh', relayJwt: 'jwt' })), - false - ) - await vi.advanceTimersByTimeAsync(0) - expect(h.socket.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, 'resolve-director') - expect(successor.close).not.toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, 'resolve-director') - commit.resolve({ outcome: 'committed' }) - await cutover - }) - it('keeps either established client busy until both actually leave', async () => { - const h = await source() - h.session.activeConnIds.add('phone') - h.session.activeConnIds.add('ipad') - const commit = vi.fn().mockResolvedValue({ outcome: 'committed' }) - h.session.activeConnIds.delete('ipad') - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'busy' }) - expect(commit).not.toHaveBeenCalled() - h.session.activeConnIds.delete('phone') - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'committed' }) - await vi.advanceTimersByTimeAsync(0) - expect(h.socket.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, expect.any(String)) - expect(h.releaseActivity).toHaveBeenCalled() - }) - it.each([ - { userId: 'other-user' }, - { sourceAssignmentEpoch: 2 }, - { sourceGeneration: 2 }, - { sourceCellIncarnation: 'other-incarnation' }, - { targetCellId: 'other-target' } - ])('rejects a reused operation ID with changed authority %j', async (change) => { - const h = await source() - const result = deferred<{ outcome: 'deferred' }>() - const commit = vi.fn().mockReturnValue(result.promise) - const reconcile = vi.fn().mockResolvedValue('not-committed') - const moving = h.registry.idleRehome(request, commit, reconcile) - const conflicting = h.registry.idleRehome({ ...request, ...change }, commit, reconcile) - result.resolve({ outcome: 'deferred' }) - expect(await conflicting).toEqual({ outcome: 'stale' }) - expect(await moving).toEqual({ outcome: 'deferred' }) - expect(commit).toHaveBeenCalledOnce() - expect(h.socket.close).not.toHaveBeenCalled() - }) - it('accounts for accepts before credential identity resolves', async () => { - const lookup = deferred() - const h = await source({ - resolveResume: vi.fn().mockReturnValue(lookup.promise), - resolveInviteForMove: vi.fn().mockResolvedValue(null) - }) - const client = new FakeSocket() - const accept = h.registry.acceptClient( - client as unknown as WebSocket, - identity.relayHostId, - 'credential' - ) - expect( - await h.registry.idleRehome(request, vi.fn(), vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'busy' }) - lookup.resolve(null) - await accept - expect(h.socket.close).not.toHaveBeenCalled() - }) + it('rejects new accepts and replacements synchronously while a commit awaits', async () => { const h = await source() const result = deferred<{ outcome: 'deferred' }>() @@ -1303,592 +326,4 @@ describe('source-owned idle cutover', () => { ) ).toEqual({ outcome: 'committed' }) }) - it.each(['ambiguous', 'deferred'])( - 'keeps %s outcomes fenced until locked reconciliation succeeds', - async (claim) => { - const h = await source() - const reconcile = vi - .fn() - .mockRejectedValueOnce(new Error('database unavailable')) - .mockRejectedValueOnce(new Error('database unavailable')) - .mockResolvedValue('not-committed') - const moving = h.registry.idleRehome( - request, - claim === 'ambiguous' - ? vi.fn().mockRejectedValue(new Error('lost commit reply')) - : vi.fn().mockResolvedValue({ outcome: 'deferred' }), - reconcile - ) - await vi.advanceTimersByTimeAsync(50) - expect( - await h.registry.idleRehome( - { ...request, attemptId: 'other' }, - vi.fn(), - vi.fn().mockResolvedValue('not-committed') - ) - ).toEqual({ outcome: 'busy' }) - expect(h.socket.close).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(300) - expect(await moving).toEqual({ outcome: 'deferred' }) - expect(reconcile).toHaveBeenCalledTimes(3) - expect(h.socket.close).not.toHaveBeenCalled() - } - ) - it('owns accepted control mutations before the handler first awaits', async () => { - const mutation = deferred() - const h = await source() - ;(h.registry as unknown as { verifyRelayToken: unknown }).verifyRelayToken = vi - .fn() - .mockReturnValue(mutation.promise) - h.socket.emit( - 'message', - Buffer.from(JSON.stringify({ type: 'auth-refresh', relayJwt: 'token' })), - false - ) - const commit = vi.fn().mockResolvedValue({ outcome: 'deferred' }) - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'busy' }) - mutation.resolve(identity) - await vi.advanceTimersByTimeAsync(0) - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'deferred' }) - }) - it('owns queued replacement activation before its first persistence await', async () => { - const h = await source() - const activation = deferred() - const assignments = (h.registry as unknown as { assignments: { activateControl: unknown } }) - .assignments - assignments.activateControl = vi.fn().mockReturnValue(activation.promise) - const replacement = new FakeSocket() - const activating = h.activate( - replacement as unknown as WebSocket, - identity, - h.session, - 2, - false, - 1 - ) - expect( - await h.registry.idleRehome(request, vi.fn(), vi.fn().mockResolvedValue('not-committed')) - ).toEqual({ outcome: 'busy' }) - activation.resolve('control:2') - await activating - }) - it('retires changed authority even when the claim definitively deferred', async () => { - const h = await source() - expect( - await h.registry.idleRehome( - request, - vi.fn().mockResolvedValue({ outcome: 'deferred' }), - vi.fn().mockResolvedValue('stale') - ) - ).toEqual({ outcome: 'stale' }) - expect(h.session.state).toBe('closed') - expect(h.releaseActivity).toHaveBeenCalled() - }) - it('holds attach ownership through basis failure reservation cleanup', async () => { - const basis = deferred() - const cleanup = deferred() - const h = await source({ - recordConnectionBasis: vi.fn().mockImplementation(async () => { - await basis.promise - throw new Error('basis failed') - }), - failReservation: vi.fn().mockReturnValue(cleanup.promise) - }) - const client = new FakeSocket() - h.session.pendingConns.set('conn', { - connId: 'conn', - connTicket: 'ticket', - client: client as unknown as WebSocket, - reservation: { - userId: identity.sub, - relayHostId: identity.relayHostId, - credentialKind: 'invite', - relayDeviceId: 'device-1', - tokenHash: 'invite-hash', - reservationId: 'reservation-1', - leaseExpiresAt: Date.now() + 1000 - }, - attachTimer: setTimeout(() => {}, 1000), - credentialActivityId: null, - phonePath: 'db', - timing: { - startedAt: Date.now(), - connOpenAt: Date.now(), - stageMs: { assignment: 0, credential: 0, activity: 0 } - } - }) - const attached = h.registry.acceptHostData( - new FakeSocket() as unknown as WebSocket, - 'conn', - 'ticket', - 1 - ) - const commit = vi.fn().mockResolvedValue({ outcome: 'deferred' }) - expect(await h.registry.idleRehome(request, commit, vi.fn())).toEqual({ outcome: 'busy' }) - basis.resolve() - await vi.advanceTimersByTimeAsync(0) - expect(h.session.activeConnIds.size).toBe(0) - expect(await h.registry.idleRehome(request, commit, vi.fn())).toEqual({ outcome: 'busy' }) - expect(commit).not.toHaveBeenCalled() - cleanup.resolve() - await attached - }) - it('rejects an attach mid-cutover before its ticket is ever examined', async () => { - const h = await source({ failReservation: vi.fn().mockResolvedValue(undefined) }) - const result = deferred<{ outcome: 'deferred' }>() - // The cutover must already be in flight: an idle host is what it claims. - const moving = h.registry.idleRehome(request, () => result.promise, vi.fn()) - const client = new FakeSocket() - h.session.pendingConns.set('conn', { - connId: 'conn', - connTicket: 'ticket', - client: client as unknown as WebSocket, - reservation: { - userId: identity.sub, - relayHostId: identity.relayHostId, - credentialKind: 'invite', - leaseExpiresAt: Date.now() + 1000 - }, - attachTimer: setTimeout(() => {}, 1000), - credentialActivityId: null - } as never) - const host = new FakeSocket() - // The ticket below is the live one: only the cutover fence may reject it. - expect(await h.registry.acceptHostData(host as unknown as WebSocket, 'conn', 'ticket', 1)).toBe( - false - ) - expect(host.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.WRONG_CELL, expect.any(String)) - expect(h.observer.recordAuth).not.toHaveBeenCalled() - expect(h.session.pendingConns.has('conn')).toBe(true) - expect(h.session.activeConnIds.size).toBe(0) - result.resolve({ outcome: 'deferred' }) - await moving - }) - it('holds no attach ownership when no session owns the connection', async () => { - const h = await source() - const host = new FakeSocket() - expect( - await h.registry.acceptHostData(host as unknown as WebSocket, 'stranger', 'ticket', 1) - ).toBe(false) - expect(h.observer.recordAuth).toHaveBeenCalledWith(false) - expect(host.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, - expect.any(String) - ) - // A leaked idle-work hold from the unowned attach would report `busy` here. - expect( - await h.registry.idleRehome( - request, - vi.fn().mockResolvedValue({ outcome: 'committed' }), - vi.fn() - ) - ).toEqual({ outcome: 'committed' }) - }) - it('returns the durable operation outcome after source retirement', async () => { - const h = await source() - const commit = vi.fn().mockResolvedValue({ outcome: 'committed' }) - await h.registry.idleRehome(request, commit, vi.fn()) - expect( - await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('committed')) - ).toEqual({ outcome: 'committed' }) - expect(commit).toHaveBeenCalledOnce() - }) - it('does not reopen a source overtaken by emergency drain', async () => { - const h = await source() - const result = deferred<{ outcome: 'deferred' }>() - const moving = h.registry.idleRehome( - request, - () => result.promise, - vi.fn().mockResolvedValue('not-committed') - ) - h.registry.drain(0) - await vi.advanceTimersByTimeAsync(0) - result.resolve({ outcome: 'deferred' }) - await moving - expect(h.session.state).toBe('closed') - expect(h.registry.get(request)).toBeNull() - }) -}) - -// The host data leg's owner lookup is the registry's only whole-inventory scan on -// an attach. These count what that scan touches, not how long it takes. -describe('host data attach owner lookup', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - const SESSION_COUNT = 1000 - const CONN_ID = 'conn-owned' - const OWNER_INDEX = { first: 0, middle: 499, last: 999 } as const - type Placement = keyof typeof OWNER_INDEX | 'absent' - type LookupCounts = { visits: number; membership: number } - - function bindOwn(map: Map, property: string | symbol): unknown { - const value: unknown = Reflect.get(map, property, map) - return typeof value === 'function' ? value.bind(map) : value - } - - // One visit per session the scan pulls off the map iterator; answers unchanged. - function countingValues(map: Map, counts: LookupCounts): Map { - return new Proxy(map, { - get(target, property) { - if (property !== 'values') return bindOwn(target, property) - return function* (): Generator { - for (const value of target.values()) { - counts.visits += 1 - yield value - } - } - } - }) - } - - // One membership check per `pendingConns.has`; answers unchanged. - function countingHas(map: Map, counts: LookupCounts): Map { - return new Proxy(map, { - get(target, property) { - if (property !== 'has') return bindOwn(target, property) - return (key: K) => { - counts.membership += 1 - return target.has(key) - } - } - }) - } - - function pendingConn( - client: FakeSocket, - connTicket: string - ): NonNullable> { - return { - connId: CONN_ID, - connTicket, - client: client as unknown as WebSocket, - reservation: { - userId: identity.sub, - relayHostId: identity.relayHostId, - credentialKind: 'invite', - relayDeviceId: 'device-1', - tokenHash: 'invite-hash', - reservationId: 'reservation-1', - leaseExpiresAt: Date.now() + 1000 - }, - attachTimer: setTimeout(() => {}, 1000), - credentialActivityId: null, - phonePath: 'db', - timing: { - startedAt: Date.now(), - connOpenAt: Date.now(), - stageMs: { assignment: 0, credential: 0, activity: 0 } - } - } - } - - // Every decoy holds a pending conn of its own, so each membership check the - // scan makes is real work rather than a lookup in an empty map. - function decoySession(index: number, counts: LookupCounts): HostSession { - const pendingConns = new Map([[`conn-decoy-${index}`, { connId: 'decoy' }]]) - return { - relayHostId: `decoy-host-${index}`, - generation: 1, - state: 'active', - activeConnIds: new Set(), - pendingConns: countingHas(pendingConns, counts) - } as unknown as HostSession - } - - async function attachRegistry(placement: Placement, store: Partial = {}) { - const h = createRegistry(vi.fn().mockResolvedValue('control:1'), { - failReservation: vi.fn().mockResolvedValue(undefined), - recordConnectionBasis: vi.fn().mockResolvedValue(undefined), - deactivateBasis: vi.fn().mockResolvedValue(undefined), - ...store - }) - const control = new FakeSocket() - await h.activate(control as unknown as WebSocket, identity, null, 1, false, 1) - const internals = h.registry as unknown as { sessions: Map } - const [ownerKey, owner] = [...internals.sessions.entries()][0]! - const counts: LookupCounts = { visits: 0, membership: 0 } - const client = new FakeSocket() - if (placement !== 'absent') owner.pendingConns.set(CONN_ID, pendingConn(client, 'ticket')) - owner.pendingConns = countingHas(owner.pendingConns, counts) - const ordered: HostSession[] = [] - const sessions = new Map() - const ownerIndex = placement === 'absent' ? 0 : OWNER_INDEX[placement] - for (let index = 0; index < SESSION_COUNT; index += 1) { - const session = index === ownerIndex ? owner : decoySession(index, counts) - ordered.push(session) - sessions.set(index === ownerIndex ? ownerKey : `decoy-${index}`, session) - } - internals.sessions = countingValues(sessions, counts) - return { ...h, owner, ordered, counts, client, control, sessions: internals.sessions } - } - - it.each([ - { reason: 'ticket', ticket: 'wrong', generation: 1, state: 'active' }, - { reason: 'generation', ticket: 'ticket', generation: 2, state: 'active' }, - { reason: 'state', ticket: 'ticket', generation: 1, state: 'orphaned' } - ] as const)('fails an attach whose $reason does not match the owner', async (input) => { - const h = await attachRegistry('middle') - h.owner.state = input.state - const host = new FakeSocket() - expect( - await h.registry.acceptHostData( - host as unknown as WebSocket, - CONN_ID, - input.ticket, - input.generation - ) - ).toBe(false) - expect(h.observer.recordAuth).toHaveBeenCalledExactlyOnceWith(false) - expect(host.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, - 'invalid host data ticket' - ) - expect(h.owner.pendingConns.has(CONN_ID)).toBe(true) - expect(h.owner.activeConnIds.size).toBe(0) - }) - -}) - -describe('paced drain', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - async function connectHosts(count: number): Promise<{ - registry: HostSessionRegistry - sockets: FakeSocket[] - }> { - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate } = createRegistry(activateControl) - const sockets: FakeSocket[] = [] - for (let index = 0; index < count; index += 1) { - const socket = new FakeSocket() - sockets.push(socket) - await activate( - socket as unknown as WebSocket, - { ...identity, sub: `user-${index}` }, - null, - 1, - false, - 1 - ) - socket.send.mockClear() - } - return { registry, sockets } - } - - function drainsSent(sockets: FakeSocket[]): number { - return sockets.filter((socket) => - socket.send.mock.calls.some(([payload]) => String(payload).includes('"type":"drain"')) - ).length - } - - it('sends every drain at once when no window is given', async () => { - const { registry, sockets } = await connectHosts(4) - registry.drain(0) - // A zero-grace drain is told by its close, once the host's release has landed. - await vi.advanceTimersByTimeAsync(0) - expect(drainsSent(sockets)).toBe(4) - }) - - // Windows here stay under the 75s control-silence watchdog, which would otherwise close - // a test socket that never heartbeats before its paced send is due. - it('spreads the sends evenly across the window', async () => { - const { registry, sockets } = await connectHosts(5) - registry.drain(0, { paceWindowMs: 40_000 }) - // Each host is told by its zero-grace close, which a timer nested in the send runs 1 ms on. - const advance = async (ms: number): Promise => { - await vi.advanceTimersByTimeAsync(ms) - await vi.advanceTimersByTimeAsync(1) - } - // The first host is told at once; the last lands on the window's closing edge. - await advance(0) - expect(drainsSent(sockets)).toBe(1) - await advance(10_000) - expect(drainsSent(sockets)).toBe(2) - await advance(20_000) - expect(drainsSent(sockets)).toBe(4) - await advance(10_000) - expect(drainsSent(sockets)).toBe(5) - }) - - it('refuses new host controls before the first paced send lands', async () => { - const { registry, sockets } = await connectHosts(3) - registry.drain(0, { paceWindowMs: 40_000 }) - expect(registry.isDraining()).toBe(true) - // The fleet drain refuses newly arriving host controls immediately. - const socket = new FakeSocket() - registry.acceptControl(socket as unknown as WebSocket, { ...identity, sub: 'user-late' }) - expect(socket.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, 'relay draining') - await vi.advanceTimersByTimeAsync(0) - expect(drainsSent(sockets)).toBe(1) - }) - - it('gives each host its own grace after its own send, not after the call', async () => { - const { registry, sockets } = await connectHosts(2) - registry.drain(10_000, { paceWindowMs: 40_000 }) - await vi.advanceTimersByTimeAsync(10_000) - expect(sockets[0]!.readyState).toBe(sockets[0]!.CLOSED) - expect(sockets[1]!.readyState).toBe(sockets[1]!.OPEN) - // Its own send at 40s plus its own 10s grace, not 10s from the drain call. - await vi.advanceTimersByTimeAsync(39_999) - expect(sockets[1]!.readyState).toBe(sockets[1]!.OPEN) - await vi.advanceTimersByTimeAsync(1) - expect(sockets[1]!.readyState).toBe(sockets[1]!.CLOSED) - }) - - it('leaves no timer behind once an emergency drain cuts a window short', async () => { - const { registry } = await connectHosts(4) - registry.drain(0, { paceWindowMs: 40_000 }) - registry.drain(0) - await vi.advanceTimersByTimeAsync(0) - // Every session is closed, so anything still pending is an orphan of the cut window. - expect(vi.getTimerCount()).toBe(0) - }) - - it('lets an emergency drain supersede the sends still queued by a paced one', async () => { - const { registry, sockets } = await connectHosts(4) - registry.drain(0, { paceWindowMs: 40_000 }) - await vi.advanceTimersByTimeAsync(0) - expect(drainsSent(sockets)).toBe(1) - registry.drain(0) - await vi.advanceTimersByTimeAsync(0) - expect(drainsSent(sockets)).toBe(4) - const sendsAfterEmergency = sockets.map((socket) => socket.send.mock.calls.length) - await vi.advanceTimersByTimeAsync(40_000) - expect(sockets.map((socket) => socket.send.mock.calls.length)).toEqual(sendsAfterEmergency) - }) -}) - -describe('controls closed after host proof but before wiring', () => { - let warn: MockInstance - beforeEach(() => { - vi.useFakeTimers() - warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - afterEach(() => { - warn.mockRestore() - vi.clearAllTimers() - vi.useRealTimers() - }) - const refusedLines = (): string[] => - warn.mock.calls - .map((call) => String(call[0])) - .filter((line) => line.includes('control refused after proof')) - - function expectRefusal( - observer: { recordPostProofClose: ReturnType }, - code: number | null, - reason: string, - cause?: string - ): void { - expect(observer.recordPostProofClose).toHaveBeenCalledWith(reason) - const [line] = refusedLines() - expect(line).toContain(`host=${relayHostLogDigest(identity.relayHostId)} gen=1 app="1.4.173"`) - expect(line).toContain(`code=${code ?? 'none'} reason=${JSON.stringify(reason)}`) - if (cause) expect(line).toContain(`cause=${cause}`) - expect(line).not.toContain(identity.relayHostId) - expect(line).not.toContain(identity.sub) - } - - it.each([ - { error: new Error('wrong_assignment'), cause: 'wrong_assignment' }, - { error: Object.assign(new Error('timeout'), { code: '57014' }), cause: 'database_transient' }, - // Assembled at runtime so the secret scanner does not read the fixture as a real URL. - { - error: new Error(`connect ${['postgres', '//user:secret@db/relay'].join(':')}`), - cause: 'error' - } - ])('logs a failed host-proof assignment check as $cause', async ({ error, cause }) => { - const h = createRegistry( - vi.fn().mockRejectedValueOnce(error) - ) - await h.activate(new FakeSocket() as unknown as WebSocket, identity, null, 1, false, 1) - expectRefusal( - h.observer, - RELAY_CLOSE_CODE.WRONG_CELL, - 'assignment changed during host proof', - cause - ) - expect(refusedLines()[0]).not.toContain('secret') - }) -}) - -describe('control error codes', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - async function revokeFailure(error: Error): Promise<{ sent: string[]; warned: string[] }> { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const activateControl = vi - .fn() - .mockResolvedValue('control:production-gce-c3:1') - const { registry, activate } = createRegistry(activateControl, { - revoke: vi.fn().mockRejectedValue(error) - }) - const socket = new FakeSocket() - await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) - socket.emit( - 'message', - Buffer.from( - JSON.stringify({ type: 'device-revoke', reqId: 'revoke-1', relayDeviceId: 'device-1' }) - ), - false - ) - await vi.advanceTimersByTimeAsync(0) - const sent = socket.send.mock.calls.map((call) => String(call[0])) - const warned = warn.mock.calls.map((call) => String(call[0])) - warn.mockRestore() - registry.drain(0) - vi.advanceTimersByTime(0) - return { sent, warned } - } - - function controlErrors(sent: string[]): unknown[] { - return sent - .map((line) => JSON.parse(line) as Record) - .filter((message) => message.type === 'control-error') - } - - it('never sends a database error message, which can carry the connection URL', async () => { - // Assembled at runtime so secret scanners do not flag a fixture URL. - const url = ['postgres', '://relay:', 'fake-pw', '@db.internal:5432/relay'].join('') - const error = Object.assign(new Error(`connect to ${url} failed: Connection terminated`), { - code: '08006' - }) - const { sent, warned } = await revokeFailure(error) - - expect(controlErrors(sent)).toEqual([ - { type: 'control-error', reqId: 'revoke-1', code: 'database_transient' } - ]) - expect(sent.join('\n')).not.toContain('fake-pw') - expect(warned).toContain( - '[orca-relay] control device-revoke failed: Error: redacted code=08006' - ) - expect(warned.join('\n')).not.toContain('fake-pw') - }) - - it('maps any other unexpected message to a fixed code', async () => { - const { sent } = await revokeFailure(new Error('Unexpected token < in JSON')) - - expect(controlErrors(sent)).toEqual([ - { type: 'control-error', reqId: 'revoke-1', code: 'control_operation_failed' } - ]) - }) - }) diff --git a/cloud/apps/relay/src/connections/host-signed-out-rejection.test.ts b/cloud/apps/relay/src/connections/host-signed-out-rejection.test.ts deleted file mode 100644 index d9876c2eab1..00000000000 --- a/cloud/apps/relay/src/connections/host-signed-out-rejection.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { EventEmitter } from 'node:events' -import { CONTROL_CONTINUITY_LIMITS } from '@orca-cloud/relay-contract/control-continuity' -import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' -import { RELAY_HOST_CLOSE_REASON } from '@orca-cloud/relay-contract/host-close-reason' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type WebSocket from 'ws' -import type { RelayAssignmentStore } from '../assignment/assignment-store.js' -import type { RelayConfig } from '../config.js' -import type { RelayCredentialStore } from '../credentials/credential-store.js' -import { HostSessionRegistry } from './host-session-registry.js' -import type { RelayRuntimeObserver } from '../observability/relay-observability.js' -import type { RelayTokenClaims } from '../authentication/relay-token-verifier.js' -import { ProcessQueuedByteBudget } from './splice-forwarder.js' - -class FakeSocket extends EventEmitter { - readonly OPEN = 1 - readonly CLOSED = 3 - readyState = this.OPEN - readonly send = vi.fn() - readonly close = vi.fn((code?: number, reason?: string) => { - this.readyState = this.CLOSED - this.emit('close', code, Buffer.from(reason ?? '')) - }) - readonly terminate = vi.fn(() => { - this.readyState = this.CLOSED - this.emit('close', 1006, Buffer.alloc(0)) - }) -} - -const config = { - port: 8080, - publicUrl: 'https://relay-c3.example.com', - cellUrl: 'https://relay-c3.example.com', - authIssuer: 'https://auth.example.com', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.com/jwks', - assignmentSigningKey: new Uint8Array(32), - role: 'cell', - cellId: 'production-gce-c3', - cells: [] -} as unknown as RelayConfig - -const identity = { - sub: 'user-1', - prof: 'profile-1', - org: 'org-1', - relayHostId: 'AbCdEf0123_-xyZ9' -} as unknown as RelayTokenClaims - -const reservation = { - userId: identity.sub, - relayHostId: identity.relayHostId, - credentialKind: 'resume', - relayDeviceId: 'device-1', - leaseExpiresAt: Date.now() + 60_000 -} - -function createRegistry() { - const store = { - resolveResume: vi.fn().mockResolvedValue({ userId: identity.sub }), - reserveCredential: vi.fn().mockResolvedValue(reservation), - failReservation: vi.fn().mockResolvedValue(undefined) - } - const assignments = { - activateControl: vi.fn().mockResolvedValue('control:production-gce-c3:1'), - markMigrationTargetRegistered: vi.fn().mockResolvedValue(undefined), - resolve: vi.fn().mockResolvedValue({ cellId: config.cellId }), - acquireActivity: vi.fn().mockResolvedValue(undefined), - renewControlActivity: vi.fn().mockResolvedValue(undefined), - releaseActivity: vi.fn().mockResolvedValue(true) - } as unknown as RelayAssignmentStore - const observer = { - recordAuth: vi.fn(), - recordForwardedBytes: vi.fn(), - recordHttp: vi.fn(), - recordReconnect: vi.fn(), - recordSql: vi.fn(), - recordControlClose: vi.fn(), - recordSpliceClose: vi.fn() - } satisfies RelayRuntimeObserver - const registry = new HostSessionRegistry( - config, - vi.fn(), - store as unknown as RelayCredentialStore, - assignments, - new ProcessQueuedByteBudget(), - observer - ) - const activate = (socket: WebSocket, generation: number): Promise => - ( - registry as unknown as { - activate: ( - socket: WebSocket, - identity: RelayTokenClaims, - existing: null, - generation: number, - rebind: boolean, - assignmentEpoch: number, - appVersion: string - ) => Promise - } - ).activate(socket, identity, null, generation, false, 1, '1.4.173') - return { registry, activate } -} - -async function dialPhone(registry: HostSessionRegistry): Promise { - const phone = new FakeSocket() - await registry.acceptClient(phone as unknown as WebSocket, identity.relayHostId, 'credential') - return phone -} - -// The 4404 hello body is unchanged: every shipped phone parses it with a strict -// schema, so the cause has to ride the close frame instead. -const HOST_OFFLINE_HELLO = JSON.stringify({ - type: 'relay-hello', - ok: false, - code: RELAY_CLOSE_CODE.HOST_OFFLINE -}) - -describe('host sign-out reason on phone rejection', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - it('names the sign-out to a phone that arrives after the host is gone', async () => { - const { registry, activate } = createRegistry() - const control = new FakeSocket() - await activate(control as unknown as WebSocket, 1) - - control.close(1000, RELAY_HOST_CLOSE_REASON.SIGNED_OUT) - vi.advanceTimersByTime(CONTROL_CONTINUITY_LIMITS.orphanGraceMs + 1) - - const phone = await dialPhone(registry) - expect(phone.send).toHaveBeenCalledWith(HOST_OFFLINE_HELLO) - expect(phone.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.HOST_OFFLINE, - RELAY_HOST_CLOSE_REASON.SIGNED_OUT - ) - }) - - it('ignores a close reason the host invented', async () => { - const { registry, activate } = createRegistry() - const control = new FakeSocket() - await activate(control as unknown as WebSocket, 1) - - control.close(1000, 'signed-out-ish') - vi.advanceTimersByTime(CONTROL_CONTINUITY_LIMITS.orphanGraceMs + 1) - - const phone = await dialPhone(registry) - expect(phone.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.HOST_OFFLINE, - 'relay connection rejected' - ) - }) - - it('forgets the sign-out once the host proves itself again', async () => { - const { registry, activate } = createRegistry() - const control = new FakeSocket() - await activate(control as unknown as WebSocket, 1) - control.close(1000, RELAY_HOST_CLOSE_REASON.SIGNED_OUT) - vi.advanceTimersByTime(CONTROL_CONTINUITY_LIMITS.orphanGraceMs + 1) - - const reconnected = new FakeSocket() - await activate(reconnected as unknown as WebSocket, 2) - // Drop it abruptly, as a network death would, so only the stale memory - // could still name a cause. - reconnected.terminate() - vi.advanceTimersByTime(CONTROL_CONTINUITY_LIMITS.orphanGraceMs + 1) - - const phone = await dialPhone(registry) - expect(phone.close).toHaveBeenCalledWith( - RELAY_CLOSE_CODE.HOST_OFFLINE, - 'relay connection rejected' - ) - }) -}) diff --git a/cloud/apps/relay/src/connections/relay-connection-hard-cap.blackbox.test.ts b/cloud/apps/relay/src/connections/relay-connection-hard-cap.blackbox.test.ts index a75bd69bba3..e46f52d2921 100644 --- a/cloud/apps/relay/src/connections/relay-connection-hard-cap.blackbox.test.ts +++ b/cloud/apps/relay/src/connections/relay-connection-hard-cap.blackbox.test.ts @@ -122,15 +122,12 @@ describe('relay connection hard cap', () => { it('preserves control headroom and never disturbs established sockets', async () => { const keys = await generateKeyPair('ES256') const publicJwk = await exportJWK(keys.publicKey) - const adminKeys = await generateKeyPair('RS256') - const adminPublicJwk = await exportJWK(adminKeys.publicKey) const jwks = createServer((_request, response) => { response.setHeader('content-type', 'application/json') response.end( JSON.stringify({ keys: [ - { ...publicJwk, kid: 'test-key', alg: 'ES256', use: 'sig' }, - { ...adminPublicJwk, kid: 'admin-key', alg: 'RS256', use: 'sig' } + { ...publicJwk, kid: 'test-key', alg: 'ES256', use: 'sig' } ] }) ) @@ -188,36 +185,6 @@ describe('relay connection hard cap', () => { await new Promise((resolve) => relay.server.once('listening', resolve)) cleanup.push(() => new Promise((resolve) => relay.server.close(() => resolve()))) const wsUrl = relayUrl.replace('http:', 'ws:') - const adminToken = await new SignJWT({ - email: 'deploy@example.com', - email_verified: true - }) - .setProtectedHeader({ alg: 'RS256', kid: 'admin-key' }) - .setIssuer('https://accounts.google.com') - .setAudience(`${relayUrl}/admin`) - .setSubject('deploy-subject') - .setIssuedAt() - .setExpirationTime('5m') - .sign(adminKeys.privateKey) - const statusResponse = await fetch(`${relayUrl}/v1/admin/runtime-status`, { - method: 'POST', - headers: { - authorization: `Bearer ${adminToken}`, - 'content-type': 'application/json' - }, - body: JSON.stringify({ v: 1 }) - }) - expect(statusResponse.status).toBe(200) - expect(await statusResponse.json()).toMatchObject({ - connectionCapacity: { - hardCap: 600, - controlRebindReserve: 100, - ordinaryConnectionLimit: 500, - unobservedBound: 60, - normalAdmissionPause: 440 - } - }) - const unmatchedData = await Promise.all( ['unmatched-1', 'unmatched-2', 'unmatched-3'].map((connectionId) => openSocket(`${wsUrl}/v1/host/data/${connectionId}`) diff --git a/cloud/apps/relay/src/connections/relay-connection-ledger.test.ts b/cloud/apps/relay/src/connections/relay-connection-ledger.test.ts index dc8b23c771a..7edf5db4531 100644 --- a/cloud/apps/relay/src/connections/relay-connection-ledger.test.ts +++ b/cloud/apps/relay/src/connections/relay-connection-ledger.test.ts @@ -13,38 +13,6 @@ function socket(): { webSocket: WebSocket; close: () => void } { describe('RelayConnectionLedger', () => { - it.each([600, 1_000, 3_000])( - 'enforces the %i-unit boundary with 100 control units reserved', - (hardCap) => { - const ledger = new RelayConnectionLedger(hardCap, 100) - const sockets: Array<{ webSocket: WebSocket; close: () => void }> = [] - for (let index = 0; index < (hardCap - 100) / 2; index++) { - const admission = ledger.tryReservePhone() - expect(admission).not.toBeNull() - const phoneSocket = socket() - admission!.upgrade.promote(phoneSocket.webSocket) - admission!.hostData.bind(`connection-${index}`) - sockets.push(phoneSocket) - } - expect(ledger.tryReservePhone()).toBeNull() - expect(ledger.tryReserveControl(false)).toBeNull() - for (let index = 0; index < 100; index++) { - const upgrade = ledger.tryReserveControl(true) - expect(upgrade).not.toBeNull() - const controlSocket = socket() - upgrade!.promote(controlSocket.webSocket) - sockets.push(controlSocket) - } - - expect(ledger.counts().enforcedConnectionUnits).toBe(hardCap) - expect(ledger.tryReserveControl(true)).toBeNull() - sockets.at(-1)!.close() - const replacement = ledger.tryReserveControl(true) - expect(replacement).not.toBeNull() - replacement!.release() - } - ) - it('transfers a pending host-data unit without increasing enforced capacity', () => { const ledger = new RelayConnectionLedger(6, 2) const phone = ledger.tryReservePhone()! @@ -128,4 +96,3 @@ describe('RelayConnectionLedger', () => { expect(ledger.canReserveBooking(100)).toBe(false) }) }) - diff --git a/cloud/apps/relay/src/connections/relay-first-frame-close.blackbox.test.ts b/cloud/apps/relay/src/connections/relay-first-frame-close.blackbox.test.ts index 8db3fcfe8d7..87da9db26bb 100644 --- a/cloud/apps/relay/src/connections/relay-first-frame-close.blackbox.test.ts +++ b/cloud/apps/relay/src/connections/relay-first-frame-close.blackbox.test.ts @@ -1,7 +1,6 @@ import { connect, type Socket } from 'node:net' import { afterEach, expect, it, vi } from 'vitest' import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' -import { RELAY_PROTOCOL_LIMITS } from '@orca-cloud/relay-contract/protocol-limits' import { loadRelayConfig } from '../config.js' import type { RelayDatabase } from '../database/database.js' import { createRelayServer } from '../relay-server.js' @@ -19,10 +18,7 @@ const IDLE_LEDGER = { enforcedConnectionUnits: 0 } -async function fixture( - options: { role?: 'cell' | 'director'; hardCap?: number } = {} -) { - const role = options.role ?? 'cell' +async function fixture() { const database: RelayDatabase = { query: vi.fn(async () => []), queryLocked: vi.fn(async () => []), @@ -35,27 +31,20 @@ async function fixture( ORCA_RELAY_AUTH_ISSUER: 'https://auth.example.test', ORCA_RELAY_JWKS_URL: 'https://auth.example.test/jwks', ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: 'synthetic-assignment-key-for-test-only', - ORCA_RELAY_ROLE: role, + ORCA_RELAY_ROLE: 'cell', ORCA_RELAY_ADMIN_AUDIENCE: 'https://auth.example.test/admin', ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.test', ORCA_RELAY_CELL_CONNECTION_HARD_CAP: '600', - ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND: '60', - ...(role === 'director' - ? { - ORCA_RELAY_CELLS_JSON: JSON.stringify([ - { id: 'cell-1', url: 'https://cell-1.example.test', capacityRequests: 900 } - ]) - } - : {}) + ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND: '60' }) const relay = createRelayServer(config, database, { - connectionLedgerLimits: { hardCap: options.hardCap ?? 3, controlReserve: 1 } + connectionLedgerLimits: { hardCap: 3, controlReserve: 1 } }) await new Promise((resolve) => relay.server.listen(0, '127.0.0.1', resolve)) cleanups.push(() => new Promise((resolve) => relay.server.close(() => resolve()))) const address = relay.server.address() if (!address || typeof address === 'string') throw new Error('missing test port') - return { relay, port: address.port, database } + return { relay, port: address.port } } type RawPeer = { @@ -108,9 +97,6 @@ async function silentUpgrade(port: number, target: string): Promise { } } -// A 43-character base64url credential is the shortest value RelayAuthSchema accepts. -const WELL_FORMED_CREDENTIAL = 'abcdefghijklmnopqrstuvwxyzABCDEFGH012345678' - function maskedTextFrame(payload: string): Buffer { const body = Buffer.from(payload) const mask = Buffer.from([1, 2, 3, 4]) @@ -118,17 +104,6 @@ function maskedTextFrame(payload: string): Buffer { return Buffer.concat([Buffer.from([0x81, 0x80 | body.length]), mask, masked]) } -function relayAuthFrame(): Buffer { - return maskedTextFrame( - JSON.stringify({ - type: 'relay-auth', - v: 1, - mode: 'connect', - credential: WELL_FORMED_CREDENTIAL - }) - ) -} - // Rejected peer’s last unmasked frame: 0x88, length, big-endian status, then UTF-8 reason. function readCloseFrame(received: Buffer): { code: number; reason: string } | null { const start = received.lastIndexOf(0x88) @@ -149,67 +124,16 @@ async function expectIdleLedger( const PHONE_TARGET = '/v1/connect/abcdefghijklmnop' -it.each([ - { label: 'first-frame timeout', target: PHONE_TARGET, opcode: undefined }, - { label: 'binary first frame', target: PHONE_TARGET, opcode: 0x82 }, - { label: 'invalid phone auth', target: PHONE_TARGET, opcode: 0x81 }, - { label: 'invalid host-data auth', target: '/v1/host/data/connection-1', opcode: 0x81 } -])( - 'releases admission after $label even when the peer ignores close', - async ({ target, opcode }) => { - const { relay, port, database } = await fixture() - const peer = await silentUpgrade(port, target) - const firstFrameDeadline = opcode === undefined ? RELAY_PROTOCOL_LIMITS.firstFrameDeadlineMs : 0 - if (opcode !== undefined) peer.socket.write(Buffer.from([opcode, 0x80, 0, 0, 0, 0])) - await expectIdleLedger(relay, firstFrameDeadline + 2_000) - expect(relay.runtimeCounts().preAuthConnections).toBe(0) - expect(database.query).not.toHaveBeenCalled() - expect(database.queryLocked).not.toHaveBeenCalled() - await silentUpgrade(port, PHONE_TARGET) - expect(relay.connectionSnapshot()?.enforcedConnectionUnits).toBe(2) - } -) - -it('releases admission after a rejected director invite when the peer ignores close', async () => { - const { relay, port } = await fixture({ role: 'director' }) +it('releases admission after a binary first frame even when the peer ignores close', async () => { + const { relay, port } = await fixture() const peer = await silentUpgrade(port, PHONE_TARGET) - peer.socket.write(relayAuthFrame()) + peer.socket.write(Buffer.from([0x82, 0x80, 0, 0, 0, 0])) await expectIdleLedger(relay, 2_000) - expect(readCloseFrame(peer.received())).toEqual({ - code: RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, - reason: 'invalid invite' - }) expect(relay.runtimeCounts().preAuthConnections).toBe(0) await silentUpgrade(port, PHONE_TARGET) expect(relay.connectionSnapshot()?.enforcedConnectionUnits).toBe(2) }) -it('releases admission after a director move redirect when the peer ignores close', async () => { - const { relay, port } = await fixture({ role: 'director' }) - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - vi.spyOn(relay.store, 'resolveInviteForMove').mockResolvedValue({ - userId: identity.userId, - relayDeviceId: 'device-1' - }) - vi.spyOn(relay.assignments, 'resolve').mockResolvedValue({ - ...identity, - cellId: 'cell-1', - cellUrl: 'https://cell-1.example.test', - assignmentEpoch: 1, - leaseExpiresAt: Date.now() + 60_000 - }) - const peer = await silentUpgrade(port, PHONE_TARGET) - peer.socket.write(relayAuthFrame()) - await expectIdleLedger(relay, 2_000) - expect(peer.received().toString('utf8')).toContain('"type":"relay-moved"') - expect(readCloseFrame(peer.received())).toEqual({ - code: RELAY_CLOSE_CODE.DRAINING, - reason: 'connect to assigned cell' - }) - await silentUpgrade(port, PHONE_TARGET) - expect(relay.connectionSnapshot()?.enforcedConnectionUnits).toBe(2) -}) - // This responsive peer proves close bytes precede FIN, not delivery under backpressure: terminate can drop queued frames after 1s. it('delivers the rejection code and a graceful FIN to a peer that keeps reading', async () => { const { relay, port } = await fixture() @@ -224,23 +148,3 @@ it('delivers the rejection code and a graceful FIN to a peer that keeps reading' expect(peer.transport().error).toBeNull() await expectIdleLedger(relay, 2_000) }) - -const BINARY_FIRST_FRAME = Buffer.from([0x82, 0x80, 0, 0, 0, 0]) -const CONCURRENT_PEERS_PER_SOURCE = 4 - -// Ledger does not clamp at zero, so a disconnect racing rejection exposes double release as a negative count. -it('releases exactly once when a rejected peer disconnects at the same moment', async () => { - const { relay, port } = await fixture({ hardCap: 2 * CONCURRENT_PEERS_PER_SOURCE + 1 }) - const peers = await Promise.all( - Array.from({ length: CONCURRENT_PEERS_PER_SOURCE }, () => silentUpgrade(port, PHONE_TARGET)) - ) - for (const peer of peers) { - peer.socket.write(BINARY_FIRST_FRAME) - peer.socket.destroy() - } - await expectIdleLedger(relay, 3_000) - expect(relay.connectionSnapshot()).toMatchObject(IDLE_LEDGER) - expect(relay.runtimeCounts().preAuthConnections).toBe(0) - await silentUpgrade(port, PHONE_TARGET) - expect(relay.connectionSnapshot()?.enforcedConnectionUnits).toBe(2) -}) diff --git a/cloud/apps/relay/src/connections/relay-host-hello-shed.test.ts b/cloud/apps/relay/src/connections/relay-host-hello-shed.test.ts index 1b4c11b44f8..82bb0a6b99d 100644 --- a/cloud/apps/relay/src/connections/relay-host-hello-shed.test.ts +++ b/cloud/apps/relay/src/connections/relay-host-hello-shed.test.ts @@ -147,7 +147,7 @@ describe('host hello shedding under database pool pressure', () => { }) } - it('admits hellos behind a deep queue that is still moving', async () => { + it('admits hellos behind a deep queue below the age threshold', async () => { const cell = await startCell(120) cell.advance(HOST_HELLO_SHED_OLDEST_WAIT_MS - 300) @@ -167,12 +167,6 @@ describe('host hello shedding under database pool pressure', () => { cell.advance(HOST_HELLO_SHED_OLDEST_WAIT_MS) expect(await dial(cell)).toEqual({ status: 503, retryAfter: '2' }) - // Shipped desktops lack unexpected-response listeners; refusal must reach their ordinary connect-error backoff. - const desktop = new WebSocket(cell.url, { - headers: { authorization: `Bearer ${cell.token}` } - }) - const error = await new Promise((resolve) => desktop.once('error', resolve)) - expect(error.message).toBe('Unexpected server response: 503') }) }) diff --git a/cloud/apps/relay/src/connections/relay-host-proof-failure.blackbox.test.ts b/cloud/apps/relay/src/connections/relay-host-proof-failure.blackbox.test.ts index c9da8447fa9..00e0e07f89c 100644 --- a/cloud/apps/relay/src/connections/relay-host-proof-failure.blackbox.test.ts +++ b/cloud/apps/relay/src/connections/relay-host-proof-failure.blackbox.test.ts @@ -28,7 +28,7 @@ describe('relay host proof failures', () => { }) // A verifyCellAssignment connect-timeout rejection once escaped beginProof and crashed whole cells. - it.each(['cell', 'combined'] as const)('contains %s host hello database timeouts', async (role) => { + it('contains cell host hello database timeouts', async () => { const keys = await generateKeyPair('ES256') const publicJwk = await exportJWK(keys.publicKey) const jwksServer: Server = createServer((_request, response) => { @@ -64,7 +64,7 @@ describe('relay host proof failures', () => { authAudience: 'orca-relay', jwksUrl: issuer, assignmentSigningKey: new Uint8Array(32), - role, + role: 'cell', cellId: 'production-gce-c3', cells: [{ id: 'production-gce-c3', url: relayUrl, capacityRequests: 4_000 }], adminAudience: `${relayUrl}/admin`, @@ -88,7 +88,7 @@ describe('relay host proof failures', () => { await new Promise((resolve) => relay.server.once('listening', resolve)) cleanup.push(() => new Promise((resolve) => relay.server.close(() => resolve()))) vi.spyOn(console, 'log').mockImplementation(() => undefined) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) const unhandled: unknown[] = [] const onUnhandled = (reason: unknown): void => { unhandled.push(reason) @@ -140,11 +140,6 @@ describe('relay host proof failures', () => { ) expect(await closed).toBe(RELAY_CLOSE_CODE.LIMIT_EXCEEDED) - expect( - warn.mock.calls.map((call) => String(call[0])) - ).toContain( - '[orca-relay] host hello proof failed: Connection terminated due to connection timeout' - ) await new Promise((resolve) => setImmediate(resolve)) expect(unhandled).toEqual([]) }) diff --git a/cloud/apps/relay/src/connections/splice-forwarder.test.ts b/cloud/apps/relay/src/connections/splice-forwarder.test.ts index e47aac7710a..fb477d072e3 100644 --- a/cloud/apps/relay/src/connections/splice-forwarder.test.ts +++ b/cloud/apps/relay/src/connections/splice-forwarder.test.ts @@ -12,8 +12,6 @@ const { Receiver } = createRequire(new URL('../splice-forwarder.test.ts', import Receiver: new (options: { isServer: true }) => Writable } -const FRAME_OVERHEAD = RELAY_ADMISSION_BUDGETS.queuedFrameOverheadBytes - class FakeSocket extends EventEmitter { readonly OPEN = 1 readyState = 1 @@ -48,7 +46,6 @@ describe('splice forwarder', () => { onClose: vi.fn() }) client.emit('message', Buffer.alloc(8 * 1024 * 1024), true) - expect(budget.current()).toBe(8 * 1024 * 1024 + FRAME_OVERHEAD) client.emit('message', Buffer.alloc(512 * 1024), true) expect(client.closes[0]?.code).toBe(4429) expect(host.closes[0]?.code).toBe(4429) @@ -73,7 +70,6 @@ describe('splice forwarder', () => { client.emit('message', frame, true) expect(client.closes).toEqual([]) expect(host.closes).toEqual([]) - expect(budget.current()).toBe(8 * 1024 * 1024 + FRAME_OVERHEAD) host.bufferedAmount = 0 vi.advanceTimersByTime(25) @@ -109,9 +105,6 @@ describe('splice forwarder', () => { receiver.write(batch) - expect(client._socket.pause).toHaveBeenCalledTimes( - RELAY_ADMISSION_BUDGETS.spliceHardQueuedFrames - ) expect(closed).toHaveBeenCalledWith({ code: 4429, reason: 'relay queue limit exceeded', @@ -122,34 +115,4 @@ describe('splice forwarder', () => { expect(host.closes[0]?.code).toBe(4429) expect(budget.current()).toBe(0) }) - - it('charges empty queued frames against the shared byte budget until drained or closed', () => { - vi.useFakeTimers() - const client = new FakeSocket() - const host = new FakeSocket() - host.bufferedAmount = 1024 * 1024 - const budget = new ProcessQueuedByteBudget() - wireSplice({ - client: client as unknown as WebSocket, - host: host as unknown as WebSocket, - budget, - onClose: vi.fn() - }) - for (let index = 0; index < 3; index += 1) { - client.emit('message', Buffer.alloc(0), true) - } - expect(budget.current()).toBe(3 * FRAME_OVERHEAD) - - host.bufferedAmount = 0 - vi.advanceTimersByTime(25) - expect(host.sent).toHaveLength(3) - expect(budget.current()).toBe(0) - - host.bufferedAmount = 1024 * 1024 - client.emit('message', Buffer.alloc(0), true) - client.emit('message', Buffer.from('x'), true) - expect(budget.current()).toBe(2 * FRAME_OVERHEAD + 1) - client.close(1000, 'done') - expect(budget.current()).toBe(0) - }) }) diff --git a/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock-postgres.test.ts b/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock-postgres.test.ts index e91849f06b4..31cf596e4ca 100644 --- a/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock-postgres.test.ts +++ b/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock-postgres.test.ts @@ -1,9 +1,6 @@ -import pg from 'pg' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { RelayAssignmentStore } from '../assignment/assignment-store.js' -import type { RelayConfig } from '../config.js' import { openRelayDatabase, type RelayDatabase } from '../database/database.js' -import { createRelayServer } from '../relay-server.js' const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip @@ -174,41 +171,6 @@ describePostgres('PostgreSQL control accept without a held cell row', () => { expect(Number(cells[0]!.reserved_requests)).toBe(Number(units[0]!.units)) }, 20_000) - // Drive the production store: wrappers can omit optional fused commit and silently restore a separate COMMIT round trip. - it('commits every counter write in one message through the production store', async () => { - await removeTestRows(databases[0]!) - const store = new RelayAssignmentStore(databases[0]!, () => 100) - await prepareCell(store) - const { assignments } = createRelayServer(cellConfig(), databases[0]!, { now: () => 100 }) - const assignment = await store.assign(first) - const firstControl = await assignments.activateControl(first, { - cellId: cell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - - const sent = vi.spyOn(pg.Client.prototype, 'query') - let texts: string[] = [] - try { - await assignments.releaseActivity(first, firstControl) - await assignments.activateControl(first, { - cellId: cell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 2 - }) - await assignments.acquireActivity(first, { - activityId: 'invite:fused', - kind: 'invite', - cellId: cell.id - }) - } finally { - texts = sent.mock.calls.map(([text]) => String(text)) - sent.mockRestore() - } - expect(texts.filter((text) => text.endsWith('; COMMIT'))).toHaveLength(3) - expect(texts.filter((text) => text === 'COMMIT')).toEqual([]) - }) - async function prepareCell(store: RelayAssignmentStore): Promise { await store.reconcileCells([cell]) await store.recordCellHeartbeat({ @@ -227,33 +189,4 @@ describePostgres('PostgreSQL control accept without a held cell row', () => { connectionUnobservedBound: 50 }) } - }) - -function cellConfig(): RelayConfig { - return { - port: 0, - publicUrl: cell.url, - cellUrl: cell.url, - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: new Uint8Array(32), - role: 'cell', - cellId: cell.id, - cells: [], - adminAudience: 'https://relay.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - runtimeServiceAccount: 'relay-cell@example.test', - adminJwksUrl: 'https://auth.example.test/jwks', - databasePoolMax: 10, - publicAssignmentsEnabled: true, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - dataDir: './data' - } -} diff --git a/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock.test.ts b/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock.test.ts deleted file mode 100644 index 73b3a2689fb..00000000000 --- a/cloud/apps/relay/src/control-leases/control-accept-cell-row-lock.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { RelayCellConfig } from '../config.js' -import { RelayAssignmentStore } from '../assignment/assignment-store.js' -import { - openInMemoryRelayDatabase, - type RelayDatabase, - type RelayLockOptions, - type RelayTransactionOptions, - type SqlRow -} from '../database/database.js' - -const CELL: RelayCellConfig = { - id: 'accept-cell-a', - url: 'https://accept-a.example.com', - capacityRequests: 2 -} -const host = { userId: 'accept-user', relayHostId: 'acceptho00000001' } -const second = { userId: 'accept-user', relayHostId: 'acceptho00000002' } -const third = { userId: 'accept-user', relayHostId: 'acceptho00000003' } - -type Statement = { sql: string; locked: boolean } - -// Records the statements a transaction issues, in order, so what the accept -// path does with the shared cell row can be asserted rather than described. -class RecordingDatabase implements RelayDatabase { - constructor( - private readonly inner: RelayDatabase, - readonly statements: Statement[] = [] - ) {} - - async query(sql: string, params: unknown[] = []): Promise { - this.statements.push({ sql, locked: false }) - return await this.inner.query(sql, params) - } - - async queryLocked( - sql: string, - params: unknown[] = [], - options: RelayLockOptions = {} - ): Promise { - this.statements.push({ sql, locked: true }) - return await this.inner.queryLocked(sql, params, options) - } - - async transaction( - operation: (transaction: RelayDatabase) => Promise, - options: RelayTransactionOptions = {} - ): Promise { - return await this.inner.transaction( - async (transaction) => - await operation(new RecordingDatabase(transaction, this.statements)), - options - ) - } - - async close(): Promise { - await this.inner.close() - } -} - -describe('control accept cell-row lock span', () => { - let recorder: RecordingDatabase - let store: RelayAssignmentStore - let assignmentEpoch: number - - beforeEach(async () => { - recorder = new RecordingDatabase(await openInMemoryRelayDatabase()) - store = new RelayAssignmentStore(recorder, () => 100) - await store.reconcileCells([CELL]) - assignmentEpoch = (await store.assign(host)).assignmentEpoch - }) - - afterEach(async () => { - await recorder?.close() - }) - - async function accept(generation: number): Promise { - recorder.statements.length = 0 - return await store.activateControl(host, { - cellId: CELL.id, - assignmentEpoch, - generation - }) - } - - function cellStatements(): Statement[] { - return recorder.statements.filter((statement) => /relay_cells/.test(statement.sql)) - } - - async function reservedRequests(): Promise { - const row = ( - await recorder.query(`SELECT reserved_requests FROM relay_cells WHERE cell_id = ?`, [ - CELL.id - ]) - )[0]! - return Number(row.reserved_requests) - } - - async function cellLeaseUnits(): Promise { - const row = ( - await recorder.query( - `SELECT COALESCE(SUM(request_units), 0) AS units - FROM relay_assignment_activity_leases WHERE cell_id = ?`, - [CELL.id] - ) - )[0]! - return Number(row.units) - } - - it('leaves the cell row untouched when a rebind retires and installs one control', async () => { - await accept(1) - - await accept(2) - - expect(cellStatements()).toEqual([]) - expect(await reservedRequests()).toBe(1) - expect(await cellLeaseUnits()).toBe(1) - }) - - it('still refuses an accept that would exceed the cell capacity', async () => { - const control = await accept(1) - await store.assign(second) - await store.releaseActivity(host, control) - await store.assign(third) - expect(await reservedRequests()).toBe(CELL.capacityRequests) - - await expect(accept(2)).rejects.toThrow('relay_capacity_exhausted') - expect(await reservedRequests()).toBe(CELL.capacityRequests) - expect(await cellLeaseUnits()).toBe(CELL.capacityRequests) - }) -}) diff --git a/cloud/apps/relay/src/control-leases/control-lease-recovery-postgres.test.ts b/cloud/apps/relay/src/control-leases/control-lease-recovery-postgres.test.ts deleted file mode 100644 index a91f0ed85a0..00000000000 --- a/cloud/apps/relay/src/control-leases/control-lease-recovery-postgres.test.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { EventEmitter } from 'node:events' -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' -import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type WebSocket from 'ws' -import { RelayAssignmentStore } from '../assignment/assignment-store.js' -import { CONTROL_RENEWAL_BATCH_INTERVAL_MS } from './control-renewal-batch.js' -import type { RelayConfig } from '../config.js' -import type { RelayCredentialStore } from '../credentials/credential-store.js' -import { openRelayDatabase, type RelayDatabase } from '../database/database.js' -import { HostSessionRegistry, type HostSession } from '../connections/host-session-registry.js' -import type { RelayRuntimeObserver } from '../observability/relay-observability.js' -import type { RelayTokenClaims } from '../authentication/relay-token-verifier.js' -import { ProcessQueuedByteBudget } from '../connections/splice-forwarder.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip - -const sourceCell = { - id: 'control-recovery-source', - url: 'https://control-recovery-source.example.com', - capacityRequests: 100 -} -const targetCell = { - id: 'control-recovery-target', - url: 'https://control-recovery-target.example.com', - capacityRequests: 100 -} -const userId = 'control-recovery-user' -const identities = ['controlrecovery1', 'controlrecovery2'].map((relayHostId) => ({ - userId, - relayHostId -})) - -class FakeSocket extends EventEmitter { - readonly OPEN = 1 - readonly CLOSED = 3 - readyState = this.OPEN - readonly send = vi.fn() - readonly close = vi.fn((code?: number, reason?: string) => { - this.readyState = this.CLOSED - this.emit('close', code, Buffer.from(reason ?? '')) - }) -} - -const observer = { - recordAuth: vi.fn(), - recordForwardedBytes: vi.fn(), - recordHttp: vi.fn(), - recordReconnect: vi.fn(), - recordSql: vi.fn() -} satisfies RelayRuntimeObserver - -type RegistryInternals = { - activate( - socket: WebSocket, - identity: RelayTokenClaims, - existing: HostSession | null, - generation: number, - rebind: boolean, - assignmentEpoch: number, - appVersion: string - ): Promise - heartbeat(session: HostSession): void -} - -describePostgres('expired control lease after a database outage', () => { - let database: RelayDatabase - let now = 1_900_000_000_000 - - const removeFixtureRows = async (): Promise => { - await database.query(`DELETE FROM relay_control_connection_reservations WHERE user_id = ?`, [ - userId - ]) - await database.query(`DELETE FROM relay_assignment_activity_leases WHERE user_id = ?`, [userId]) - await database.query(`DELETE FROM relay_assignment_migrations WHERE user_id = ?`, [userId]) - await database.query(`DELETE FROM relay_assignments WHERE user_id = ?`, [userId]) - for (const cell of [sourceCell, targetCell]) { - await database.query(`DELETE FROM relay_cell_connection_snapshots WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cell_connection_runtime WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cell_runtime WHERE cell_id = ?`, [cell.id]) - await database.query(`DELETE FROM relay_cells WHERE cell_id = ?`, [cell.id]) - } - } - - const createRegistry = (store: RelayAssignmentStore): HostSessionRegistry => - new HostSessionRegistry( - { - role: 'cell', - cellId: sourceCell.id - } as RelayConfig, - vi.fn(), - {} as RelayCredentialStore, - store, - new ProcessQueuedByteBudget(), - observer, - () => now - ) - - const activate = async ( - registry: HostSessionRegistry, - store: RelayAssignmentStore, - index: number - ): Promise<{ activityId: string; session: HostSession; socket: FakeSocket }> => { - const identity = identities[index]! - const assignment = await store.assign(identity) - const socket = new FakeSocket() - const token = { - sub: identity.userId, - prof: 'control-recovery-profile', - relayHostId: identity.relayHostId, - purpose: 'host-control', - exp: 4_102_444_800 - } satisfies RelayTokenClaims - await (registry as unknown as RegistryInternals).activate( - socket as unknown as WebSocket, - token, - null, - 1, - false, - assignment.assignmentEpoch, - 'control-recovery-test' - ) - const session = registry.get(identity)! - clearInterval(session.heartbeatTimer!) - session.heartbeatTimer = null - return { activityId: session.controlActivityId!, session, socket } - } - - const heartbeat = (registry: HostSessionRegistry, session: HostSession): void => { - session.activityRenewalDueAt = now - session.lastPongAt = now - const internals = registry as unknown as RegistryInternals - internals.heartbeat(session) - } - - // A due renewal leaves the heartbeat as a batch enqueue, so a poll has to - // outlast the batch window before it can call the renewal missing. - const renewalPoll = { timeout: CONTROL_RENEWAL_BATCH_INTERVAL_MS + 4_000 } - - const leaseRows = async (relayHostId: string) => - await database.query( - `SELECT activity_id, cell_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [userId, relayHostId] - ) - - const waitForRenewal = async ( - socket: FakeSocket, - relayHostId: string, - expectedRows: number - ): Promise => { - await expect - .poll( - async () => - socket.close.mock.calls.length > 0 || - (await leaseRows(relayHostId)).length === expectedRows, - renewalPoll - ) - .toBe(true) - } - - beforeAll(async () => { - database = await openRelayDatabase({ databaseUrl, dataDir: '' }) - }) - - beforeEach(async () => { - now = 1_900_000_000_000 - await removeFixtureRows() - }) - - afterEach(async () => { - await removeFixtureRows() - }) - - afterAll(async () => { - if (database) await database.close() - }) - - it('re-acquires a reaped lease while the assignment remains on this cell', async () => { - const store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells([sourceCell]) - const registry = createRegistry(store) - const { activityId, session, socket } = await activate(registry, store, 0) - - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - expect(await leaseRows(identities[0]!.relayHostId)).toHaveLength(0) - - heartbeat(registry, session) - await waitForRenewal(socket, identities[0]!.relayHostId, 1) - - expect(socket.close).not.toHaveBeenCalled() - expect(await leaseRows(identities[0]!.relayHostId)).toEqual([ - expect.objectContaining({ activity_id: activityId, cell_id: sourceCell.id }) - ]) - registry.drain(0) - }) - - it('closes without stealing back a lease that moved to another cell', async () => { - const store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells([sourceCell, targetCell]) - const registry = createRegistry(store) - const { activityId, session, socket } = await activate(registry, store, 1) - const identity = identities[1]! - await database.query( - `UPDATE relay_assignment_activity_leases SET cell_id = ? - WHERE user_id = ? AND relay_host_id = ? AND activity_id = ?`, - [targetCell.id, identity.userId, identity.relayHostId, activityId] - ) - - await expect( - store.renewControlActivity(identity, { - activityId, - cellId: sourceCell.id, - expiresAt: now + ASSIGNMENT_LIMITS.activityLeaseMs - }) - ).rejects.toThrow('control_activity_moved') - - heartbeat(registry, session) - await expect.poll(() => socket.close.mock.calls.length, renewalPoll).toBe(1) - - expect(socket.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, 'control activity moved') - expect(await leaseRows(identity.relayHostId)).toEqual([ - expect.objectContaining({ activity_id: activityId, cell_id: targetCell.id }) - ]) - registry.drain(0) - }) -}) diff --git a/cloud/apps/relay/src/control-leases/control-rebind-inventory-lock-postgres.test.ts b/cloud/apps/relay/src/control-leases/control-rebind-inventory-lock-postgres.test.ts index d24d6d71839..3228b2b5b48 100644 --- a/cloud/apps/relay/src/control-leases/control-rebind-inventory-lock-postgres.test.ts +++ b/cloud/apps/relay/src/control-leases/control-rebind-inventory-lock-postgres.test.ts @@ -135,7 +135,6 @@ describePostgres('PostgreSQL control rebind under a held cell row', () => { // A generation-2 rebind on cell A supersedes generation 1. It must not // wait on cell B's row. - const startedAt = Date.now() const blockedStatement = async (): Promise => { const rows = await databases[1]!.query( `SELECT left(query, 160) AS q FROM pg_stat_activity @@ -161,10 +160,8 @@ describePostgres('PostgreSQL control rebind under a held cell row', () => { connectionInclusionWatermark: 11 }) const rebound = await Promise.race([reboundWork, timeout]) - const elapsedMs = Date.now() - startedAt expect(rebound).toBe(`control:${cells[0]!.id}:2`) - expect(elapsedMs).toBeLessThan(2_000) const controls = await databases[0]!.query( `SELECT activity_id FROM relay_assignment_activity_leases WHERE user_id = ? AND activity_kind = 'control' ORDER BY activity_id`, diff --git a/cloud/apps/relay/src/control-leases/control-renewal-batch.test.ts b/cloud/apps/relay/src/control-leases/control-renewal-batch.test.ts index c1da994bbd2..d7be60af2e8 100644 --- a/cloud/apps/relay/src/control-leases/control-renewal-batch.test.ts +++ b/cloud/apps/relay/src/control-leases/control-renewal-batch.test.ts @@ -5,25 +5,12 @@ import type { ControlRenewalRequest } from './control-renewal-statement.js' -// Settles into the outcome the caller saw, attached at enqueue so a rejection is -// never momentarily unhandled. -function outcomeOf(renewal: Promise): Promise { - return renewal.then( - () => 'renewed', - (error: unknown) => String((error as { message?: unknown }).message) - ) -} - -function request( - host: string, - expiresAt = 1_000, - activityId = 'control:cell-a:1' -): ControlRenewalRequest { +function request(host: string): ControlRenewalRequest { return { identity: { userId: 'user-a', relayHostId: host }, - activityId, + activityId: 'control:cell-a:1', cellId: 'cell-a', - expiresAt + expiresAt: 1_000 } } @@ -34,27 +21,7 @@ describe('control renewal batch', () => { vi.useRealTimers() }) - it('routes each outcome back to the caller that asked for it', async () => { - const outcomes: ControlRenewalOutcome[] = [ - 'renewed', - 'assignment_not_found', - 'control_activity_moved' - ] - const batch = new ControlRenewalBatch(async () => outcomes) - const first = outcomeOf(batch.enqueue(request('host0000000000b1'))) - const second = outcomeOf(batch.enqueue(request('host0000000000b2'))) - const third = outcomeOf(batch.enqueue(request('host0000000000b3'))) - - await vi.advanceTimersByTimeAsync(CONTROL_RENEWAL_BATCH_INTERVAL_MS) - - await expect(Promise.all([first, second, third])).resolves.toEqual([ - 'renewed', - 'assignment_not_found', - 'control_activity_moved' - ]) - }) - - it('does not hold a new window behind a statement still in PostgreSQL', async () => { + it('lets the next renewal finish while an earlier flush is blocked', async () => { let release!: (outcomes: ControlRenewalOutcome[]) => void const renew = vi .fn<(rows: readonly ControlRenewalRequest[]) => Promise>() @@ -69,53 +36,9 @@ describe('control renewal batch', () => { const next = batch.enqueue(request('host0000000000c2')) await vi.advanceTimersByTimeAsync(CONTROL_RENEWAL_BATCH_INTERVAL_MS) - expect(renew).toHaveBeenCalledTimes(2) await expect(next).resolves.toBeUndefined() release(['renewed']) await expect(stalled).resolves.toBeUndefined() }) - it('supersedes a second attempt for one lease and answers both callers', async () => { - const renew = vi.fn(async (rows: readonly ControlRenewalRequest[]) => - rows.map((): ControlRenewalOutcome => 'renewed') - ) - const batch = new ControlRenewalBatch(renew) - const earlier = batch.enqueue(request('host0000000000e1', 1_000)) - const later = batch.enqueue(request('host0000000000e1', 2_000)) - - await vi.advanceTimersByTimeAsync(CONTROL_RENEWAL_BATCH_INTERVAL_MS) - - expect(renew.mock.calls[0]![0]).toEqual([ - expect.objectContaining({ expiresAt: 2_000 }) - ]) - await expect(earlier).resolves.toBeUndefined() - await expect(later).resolves.toBeUndefined() - }) - - it('holds a second activity for one host back to the next flush', async () => { - const renew = vi.fn(async (rows: readonly ControlRenewalRequest[]) => - rows.map((): ControlRenewalOutcome => 'renewed') - ) - const batch = new ControlRenewalBatch(renew) - const first = batch.enqueue(request('host0000000000h1', 1_000, 'control:cell-a:1')) - const second = batch.enqueue(request('host0000000000h1', 1_000, 'control:cell-a:2')) - const other = batch.enqueue(request('host0000000000h2')) - - await vi.advanceTimersByTimeAsync(CONTROL_RENEWAL_BATCH_INTERVAL_MS) - - // One statement updates a host's assignment row once, so the host appears in - // one flush only; the newer generation leads the next one. - expect(renew.mock.calls[0]![0].map((row) => row.activityId)).toEqual([ - 'control:cell-a:1', - 'control:cell-a:1' - ]) - await expect(Promise.all([first, other])).resolves.toEqual([undefined, undefined]) - - await vi.advanceTimersByTimeAsync(CONTROL_RENEWAL_BATCH_INTERVAL_MS) - - expect(renew).toHaveBeenCalledTimes(2) - expect(renew.mock.calls[1]![0].map((row) => row.activityId)).toEqual(['control:cell-a:2']) - await expect(second).resolves.toBeUndefined() - }) - }) diff --git a/cloud/apps/relay/src/control-leases/control-renewal-postgres.test.ts b/cloud/apps/relay/src/control-leases/control-renewal-postgres.test.ts index c481ad9679b..998a9b157ad 100644 --- a/cloud/apps/relay/src/control-leases/control-renewal-postgres.test.ts +++ b/cloud/apps/relay/src/control-leases/control-renewal-postgres.test.ts @@ -1,10 +1,8 @@ -import { performance } from 'node:perf_hooks' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { RelayAssignmentStore } from '../assignment/assignment-store.js' import { CONTROL_RENEWAL_BATCH_SQL } from './control-renewal-statement.js' import { openRelayDatabase, - POSTGRES_LOCK_TIMEOUT_MS, type RelayDatabase, type RelayLockOptions, type SqlRow @@ -338,7 +336,6 @@ describePostgres('PostgreSQL control renewal', () => { try { await locked.promise - const startedAt = performance.now() const outcomes = await store.renewControlActivities( [held, free].map((identity) => ({ identity, @@ -347,12 +344,8 @@ describePostgres('PostgreSQL control renewal', () => { expiresAt })) ) - const elapsedMs = performance.now() - startedAt expect(outcomes).toEqual(['assignment_lock_unavailable', 'renewed']) - // It skipped rather than queued: a blocking FOR UPDATE would have spent the - // pool's whole lock_timeout here and failed the free host too. - expect(elapsedMs).toBeLessThan(POSTGRES_LOCK_TIMEOUT_MS) const lease = ( await database.query( `SELECT expires_at FROM relay_assignment_activity_leases diff --git a/cloud/apps/relay/src/credentials/credential-store.test.ts b/cloud/apps/relay/src/credentials/credential-store.test.ts index 8453e6762a3..18096411f7f 100644 --- a/cloud/apps/relay/src/credentials/credential-store.test.ts +++ b/cloud/apps/relay/src/credentials/credential-store.test.ts @@ -44,7 +44,6 @@ describe('relay credential store', () => { await expect(store.createInvite(identity, 'device-over-limit')).rejects.toMatchObject({ code: 'rate_limit_exceeded' }) - expect(await database.query(`SELECT * FROM relay_audit_events`)).toHaveLength(30) await database.close() }) diff --git a/cloud/apps/relay/src/credentials/resume-confirmed-audit-buffer.test.ts b/cloud/apps/relay/src/credentials/resume-confirmed-audit-buffer.test.ts index 770d47af543..eb94d957544 100644 --- a/cloud/apps/relay/src/credentials/resume-confirmed-audit-buffer.test.ts +++ b/cloud/apps/relay/src/credentials/resume-confirmed-audit-buffer.test.ts @@ -1,7 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { openInMemoryRelayDatabase, type RelayDatabase, type SqlRow } from '../database/database.js' import { ResumeConfirmedAuditBuffer } from './resume-confirmed-audit-buffer.js' -import { StatementRecordingDatabase } from '../test-fixtures/statement-recording-database.js' const event = (reqId: string) => ({ userId: 'user-1', @@ -18,18 +17,15 @@ describe('the batched resume-confirmed audit', () => { inner = undefined }) - async function setup(now: () => number = Date.now) { + async function setup() { inner = await openInMemoryRelayDatabase() - const database = new StatementRecordingDatabase(inner) - const lines: Array> = [] - const buffer = new ResumeConfirmedAuditBuffer(database, now, (line) => - lines.push(JSON.parse(line)) - ) + const database = inner + const buffer = new ResumeConfirmedAuditBuffer(database, Date.now, () => undefined) const rows = async (): Promise => await inner!.query( `SELECT type, relay_device_id, detail_json FROM relay_audit_events ORDER BY at, id` ) - return { database, buffer, lines, rows } + return { database, buffer, rows } } it('retries a flush whose commit outcome was lost without writing any row twice', async () => { @@ -48,9 +44,7 @@ describe('the batched resume-confirmed audit', () => { return result } await buffer.flush() - expect(buffer.pending()).toBe(2) await buffer.flush() - expect(buffer.pending()).toBe(0) expect(await rows()).toHaveLength(2) buffer.stop() }) diff --git a/cloud/apps/relay/src/database/boot-database-open.test.ts b/cloud/apps/relay/src/database/boot-database-open.test.ts deleted file mode 100644 index f5bc713a36a..00000000000 --- a/cloud/apps/relay/src/database/boot-database-open.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, describe, expect, it, vi, type MockInstance } from 'vitest' -import { openRelayDatabaseAtBoot } from './boot-database-open.js' -import type { RelayDatabase } from './database.js' - -const input = { dataDir: '/tmp/orca-relay-boot', databaseUrl: 'postgres://relay@localhost/relay' } -// The message the fleet actually saw: pg-pool reports the connect timeout with -// no SQLSTATE, so the classifier has only this text to go on. -const connectTimeout = (): Error => new Error('Connection terminated due to connection timeout') -const database = {} as RelayDatabase - -function loggedEvents(warn: MockInstance): string[] { - return warn.mock.calls.map((call) => String(JSON.parse(String(call[0])).event)) -} - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() -}) - -describe('relay boot database open', () => { - it('waits out a cold proxy instead of failing the boot', async () => { - vi.useFakeTimers() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const open = vi - .fn<() => Promise>() - .mockRejectedValueOnce(connectTimeout()) - .mockRejectedValueOnce(connectTimeout()) - .mockResolvedValue(database) - - const opening = openRelayDatabaseAtBoot(input, open) - await vi.runAllTimersAsync() - - expect(await opening).toBe(database) - expect(open).toHaveBeenCalledTimes(3) - expect(open).toHaveBeenCalledWith(input) - expect(loggedEvents(warn)).toEqual([ - 'orca_relay_boot_database_retry', - 'orca_relay_boot_database_retry', - 'orca_relay_boot_database_recovered' - ]) - expect(JSON.parse(String(warn.mock.calls[0]?.[0]))).toMatchObject({ - attempt: 1, - delayMs: expect.any(Number), - code: 'unknown', - connectionTimeout: true - }) - }) - - // A retry re-runs the schema apply, which must never re-queue a boot DDL - // behind the writers that beat it; the request path treats these as transient. - - it('gives up once the retry budget is spent', async () => { - vi.useFakeTimers() - vi.setSystemTime(0) - vi.spyOn(Math, 'random').mockReturnValue(0) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const failure = connectTimeout() - const open = vi.fn<() => Promise>().mockRejectedValue(failure) - - const opening = openRelayDatabaseAtBoot(input, open) - const rejection = expect(opening).rejects.toBe(failure) - await vi.runAllTimersAsync() - await rejection - - expect(Date.now()).toBeLessThanOrEqual(45_000) - expect(open.mock.calls.length).toBeGreaterThan(1) - const events = loggedEvents(warn) - expect(events.at(-1)).toBe('orca_relay_boot_database_failed') - expect(events.filter((event) => event === 'orca_relay_boot_database_retry')).toHaveLength( - open.mock.calls.length - 1 - ) - expect(JSON.parse(String(warn.mock.calls.at(-1)?.[0]))).toMatchObject({ - attempts: open.mock.calls.length, - retryable: true, - connectionTimeout: true - }) - }) -}) diff --git a/cloud/apps/relay/src/database/database-connect-stall-postgres.test.ts b/cloud/apps/relay/src/database/database-connect-stall-postgres.test.ts index 26886ea83d6..af50c622c4d 100644 --- a/cloud/apps/relay/src/database/database-connect-stall-postgres.test.ts +++ b/cloud/apps/relay/src/database/database-connect-stall-postgres.test.ts @@ -11,7 +11,6 @@ import { isRelayDatabaseTransientError, openRelayDatabase, type RelayDatabase } const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip -// Cloud SQL startup may accept TCP without replying; pin fast failure/event-loop progress. The 2026-10-11 blocking connect() transport stall itself cannot be reproduced here. type StallingDatabase = { port: number // 'forward' needs a real PostgreSQL behind it. @@ -27,49 +26,21 @@ afterEach(async () => { vi.restoreAllMocks() }) -describe('PostgreSQL pool over a database that accepts and never answers', () => { - it('fails every caller fast and retryably without stalling the event loop', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const stalling = await stallingDatabase('blackhole') - const database = await openStallingPool(stalling, 'postgresql://relay:secret@127.0.0.1') - const loop = watchEventLoop() - - // Twice the pool: three dial, three queue behind them in the general lane. - const outcomes = await Promise.all( - Array.from({ length: 6 }, async () => { - const startedAt = performance.now() - const error = await database.query('SELECT 1').catch((failure: unknown) => failure) - return { error, elapsedMs: performance.now() - startedAt } - }) - ) - - const gapMs = loop.stop() - for (const { error, elapsedMs } of outcomes) { - expect(isRelayDatabaseTransientError(error)).toBe(true) - // A queued caller waits out one connect timeout for a slot, then one for its own dial. - expect(elapsedMs).toBeLessThan(4_500) - } - expect(stalling.sockets.size).toBeGreaterThan(0) - expect(gapMs).toBeLessThan(250) - }, 15_000) -}) - describePostgres('PostgreSQL pool through a database stop and start', () => { - it('fails fast while the database is down or starting, then serves again', async () => { + it('rejects queries during stop/start and serves again after restart', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) const stalling = await stallingDatabase('forward') const database = await openStallingPool(stalling, databaseUrl!) - const loop = watchEventLoop() expect(await database.query('SELECT 1 AS up')).toEqual([{ up: 1 }]) // Stopped: the instance refuses connections, and every pooled client is gone with it. stalling.mode = 'refuse' dropConnections(stalling) - await expectFastTransientFailure(database, 1_000) + await expectTransientFailure(database) // Starting: the address answers TCP but PostgreSQL never speaks. stalling.mode = 'blackhole' - await expectFastTransientFailure(database, 2_500) + await expectTransientFailure(database) stalling.mode = 'forward' dropConnections(stalling) @@ -79,15 +50,12 @@ describePostgres('PostgreSQL pool through a database stop and start', () => { interval: 100 }).toEqual([{ up: 1 }]) expect(await database.query('SELECT 2 AS up')).toEqual([{ up: 2 }]) - expect(loop.stop()).toBeLessThan(250) }, 30_000) }) -async function expectFastTransientFailure(database: RelayDatabase, boundMs: number): Promise { - const startedAt = performance.now() +async function expectTransientFailure(database: RelayDatabase): Promise { const error = await database.query('SELECT 1').catch((failure: unknown) => failure) expect(isRelayDatabaseTransientError(error)).toBe(true) - expect(performance.now() - startedAt).toBeLessThan(boundMs) } async function openStallingPool(stalling: StallingDatabase, url: string): Promise { @@ -137,23 +105,3 @@ function dropConnections(stalling: StallingDatabase): void { for (const socket of stalling.sockets) socket.destroy() stalling.sockets.clear() } - -// The longest gap between 10 ms ticks: a blocked loop shows as one long gap. -function watchEventLoop(): { stop: () => number } { - let last = performance.now() - let longestGapMs = 0 - const timer = setInterval(() => { - const now = performance.now() - longestGapMs = Math.max(longestGapMs, now - last) - last = now - }, 10) - cleanups.push(async () => { - clearInterval(timer) - }) - return { - stop: () => { - clearInterval(timer) - return longestGapMs - } - } -} diff --git a/cloud/apps/relay/src/database/database-statement-timeout-postgres.test.ts b/cloud/apps/relay/src/database/database-statement-timeout-postgres.test.ts deleted file mode 100644 index 6308aab6d6c..00000000000 --- a/cloud/apps/relay/src/database/database-statement-timeout-postgres.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { openRelayDatabase, type RelayDatabase } from './database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip -const applicationName = 'orca-relay/statement-timeout-postgres' - -describePostgres('PostgreSQL statement deadline', () => { - const databases: RelayDatabase[] = [] - - beforeAll(async () => { - databases.push(await openRelayDatabase({ databaseUrl, dataDir: '' })) - }) - - afterAll(async () => { - for (const database of databases) await database.close() - }) - - // Why: a real 57014 aborts the transaction exactly as a lock timeout does. If - // it escapes the bounded retry it becomes a failed assignment instead of a - // slow one. - it('retries a transaction after a real statement timeout', async () => { - const database = await openRelayDatabase({ databaseUrl, dataDir: '', statementTimeoutMs: 300 }) - databases.push(database) - let attempts = 0 - - const result = await database.transaction(async (transaction) => { - attempts += 1 - if (attempts === 1) await transaction.query(`SELECT pg_sleep(2)`) - return attempts - }) - - expect(result).toBe(2) - }, 15_000) - - // CREATE INDEX IF NOT EXISTS still queues table locks before checking existence; pg_class precheck avoids blocking writers on migrated databases. - it('boots without queueing behind a held ACCESS EXCLUSIVE lock', async () => { - let releaseTable!: () => void - const tableReleased = new Promise((resolve) => { - releaseTable = resolve - }) - let tableHeld!: () => void - const tableHeldPromise = new Promise((resolve) => { - tableHeld = resolve - }) - const holder = databases[0]!.transaction(async (transaction) => { - await transaction.query(`LOCK TABLE relay_invites IN ACCESS EXCLUSIVE MODE`) - tableHeld() - await tableReleased - }) - try { - await tableHeldPromise - - // Resolving while the lock is still held is the whole proof: a statement that queued would hit - // the schema connection's 1s lock_timeout and fail the boot, which is no longer retried. - const database = await openRelayDatabase({ - databaseUrl, - dataDir: '', - applicationName, - // Far too short for a blocked DDL; the serving pool wears it, the schema - // connection must not. - statementTimeoutMs: 200 - }) - databases.push(database) - const waiting = await databases[0]!.query( - `SELECT count(*) AS waiting FROM pg_stat_activity - WHERE datname = current_database() AND wait_event_type = 'Lock' - AND application_name = ?`, - [`${applicationName}/schema`] - ) - expect(Number(waiting[0]!.waiting)).toBe(0) - - // The serving pool still carries the short deadline it was opened with. - expect( - await database.query(`SELECT current_setting('statement_timeout') AS statement_timeout`) - ).toEqual([{ statement_timeout: '200ms' }]) - } finally { - releaseTable() - await holder - } - }, 15_000) -}) diff --git a/cloud/apps/relay/src/database/database-transient-error.test.ts b/cloud/apps/relay/src/database/database-transient-error.test.ts index edc393a510f..4b7a6bb7fec 100644 --- a/cloud/apps/relay/src/database/database-transient-error.test.ts +++ b/cloud/apps/relay/src/database/database-transient-error.test.ts @@ -38,14 +38,11 @@ async function failedQuery(failure: Error): Promise { describe('relay database transient errors', () => { // Staging B1 re-test: a Cloud SQL restart failed the transaction's acquire with `write EPIPE`. - it.each(['EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EHOSTUNREACH'])( - 'classifies an acquire that failed with %s, but not the bare errno', - async (code) => { - const failure = (): Error => Object.assign(new Error(`connect ${code}`), { code }) - expect(isRelayDatabaseTransientError(await failedAcquire(failure()))).toBe(true) - expect(isRelayDatabaseTransientError(failure())).toBe(false) - } - ) + it('classifies an acquire EPIPE only from the database layer', async () => { + const failure = (): Error => Object.assign(new Error('connect EPIPE'), { code: 'EPIPE' }) + expect(isRelayDatabaseTransientError(await failedAcquire(failure()))).toBe(true) + expect(isRelayDatabaseTransientError(failure())).toBe(false) + }) // Database-layer drops answer 503/Retry-After (staging B1); never retry transaction work with unknown commit outcome. it('classifies a mid-statement drop only from the database layer', async () => { diff --git a/cloud/apps/relay/src/database/database.test.ts b/cloud/apps/relay/src/database/database.test.ts index 0ea3a9e0206..b8b91685fc8 100644 --- a/cloud/apps/relay/src/database/database.test.ts +++ b/cloud/apps/relay/src/database/database.test.ts @@ -18,7 +18,6 @@ describe('relay database', () => { temporaryDirectories.push(dataDir) const legacy = await openRelayDatabase({ dataDir }) await legacy.query('ALTER TABLE relay_control_capabilities DROP COLUMN idle_regional_rehome') - await legacy.query('ALTER TABLE relay_region_rehome_attempts DROP COLUMN source_generation') await legacy.query( `INSERT INTO relay_control_capabilities (user_id, relay_host_id, activity_id, cell_id, cell_incarnation, assignment_epoch, generation, finish_existing) @@ -30,12 +29,6 @@ describe('relay database', () => { expect( await upgraded.query('SELECT idle_regional_rehome FROM relay_control_capabilities') ).toEqual([{ idle_regional_rehome: 0 }]) - const columns = await upgraded.query( - "SELECT * FROM pragma_table_info('relay_region_rehome_attempts')" - ) - expect(columns.find((column) => column.name === 'source_generation')).toMatchObject({ - dflt_value: '0' - }) } finally { await upgraded.close() } diff --git a/cloud/apps/relay/src/database/postgres-checked-out-client-error.test.ts b/cloud/apps/relay/src/database/postgres-checked-out-client-error.test.ts index c510d98afca..415504fbf80 100644 --- a/cloud/apps/relay/src/database/postgres-checked-out-client-error.test.ts +++ b/cloud/apps/relay/src/database/postgres-checked-out-client-error.test.ts @@ -6,14 +6,12 @@ import { PostgresDatabase } from './database.js' // `release` per checkout, which is the property the guard wraps. class FakePoolClient extends EventEmitter { readonly released: Array = [] - readonly statements: string[] = [] constructor(private readonly respond: (sql: string) => { rows: unknown[]; rowCount: number }) { super() } query = vi.fn((sql: string) => { - this.statements.push(sql) return Promise.resolve(this.respond(sql)) }) @@ -31,10 +29,8 @@ describe('checked-out PostgreSQL client failure handling', () => { const terminated = Object.assign(new Error('Connection terminated unexpectedly'), { code: '57P01' }) - let listenersWhileCheckedOut = 0 const client: FakePoolClient = new FakePoolClient((sql) => { if (sql !== 'SELECT 1') return { rows: [], rowCount: 0 } - listenersWhileCheckedOut = client.listenerCount('error') // Cloud SQL terminating the session: the client emits `error` and the // in-flight statement rejects with the same failure. expect(() => client.emit('error', terminated)).not.toThrow() @@ -48,13 +44,7 @@ describe('checked-out PostgreSQL client failure handling', () => { database.transaction(async (transaction) => await transaction.query('SELECT 1')) ).rejects.toBe(terminated) - expect(listenersWhileCheckedOut).toBe(1) - expect(client.listenerCount('error')).toBe(0) expect(client.released).toEqual([terminated]) - expect(client.statements).toEqual(['BEGIN', 'SELECT 1']) - expect(warning).toHaveBeenCalledWith( - '[orca-relay] checked-out PostgreSQL client failed: 57P01 Connection terminated unexpectedly' - ) } finally { warning.mockRestore() } diff --git a/cloud/apps/relay/src/database/postgres-commit-with-final-write-postgres.test.ts b/cloud/apps/relay/src/database/postgres-commit-with-final-write-postgres.test.ts index 593b927b677..49e43bb45f8 100644 --- a/cloud/apps/relay/src/database/postgres-commit-with-final-write-postgres.test.ts +++ b/cloud/apps/relay/src/database/postgres-commit-with-final-write-postgres.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' import pg from 'pg' import { commitWithFinalWrite, @@ -23,12 +23,10 @@ function counterParams(id: string, delta: number): unknown[] { // lost connection leaves the outcome unknown. describePostgres('PostgreSQL counter write committed in the same round trip', () => { let database: RelayDatabase - let other: RelayDatabase let admin: pg.Client beforeAll(async () => { database = await openRelayDatabase({ databaseUrl, dataDir: '' }) - other = await openRelayDatabase({ databaseUrl, dataDir: '' }) admin = new pg.Client({ connectionString: databaseUrl }) await admin.connect() await admin.query( @@ -50,7 +48,6 @@ describePostgres('PostgreSQL counter write committed in the same round trip', () await admin.query(`DROP TABLE IF EXISTS ${table}_log`) await admin.end() await database.close() - await other.close() }) async function counter(id: string): Promise { @@ -61,31 +58,14 @@ describePostgres('PostgreSQL counter write committed in the same round trip', () return Number((await admin.query(`SELECT count(*) AS c FROM ${table}_log`)).rows[0].c) } - it('commits the earlier statements and the counter together in one message', async () => { - const sent = vi.spyOn(pg.Client.prototype, 'query') - try { - let messagesForCommit = 0 - const result = await database.transaction(async (transaction) => { - await transaction.query(`INSERT INTO ${table}_log (id, note) VALUES (?, ?)`, ['a', 'x']) - const before = sent.mock.calls.length - const committed = await commitWithFinalWrite( - transaction, - counterUpdate, - counterParams("it's", 1) - ) - messagesForCommit = sent.mock.calls.length - before - return committed - }) - const texts = sent.mock.calls.map(([text]) => String(text)) - expect(result).toBe(true) - expect(messagesForCommit).toBe(1) - expect(texts.filter((text) => text === 'COMMIT')).toEqual([]) - expect(texts.at(-1)).toMatch(/; COMMIT$/) - expect(await counter("it's")).toBe(1) - expect(await logged()).toBe(1) - } finally { - sent.mockRestore() - } + it('commits the earlier statements and the final counter atomically', async () => { + const result = await database.transaction(async (transaction) => { + await transaction.query(`INSERT INTO ${table}_log (id, note) VALUES (?, ?)`, ['a', 'x']) + return await commitWithFinalWrite(transaction, counterUpdate, counterParams("it's", 1)) + }) + expect(result).toBe(true) + expect(await counter("it's")).toBe(1) + expect(await logged()).toBe(1) }) it('rolls back over cap and lets the caller read the row outside the transaction', async () => { diff --git a/cloud/apps/relay/src/database/postgres-connection-latency.test.ts b/cloud/apps/relay/src/database/postgres-connection-latency.test.ts index 077c770f7b5..8344366d5e2 100644 --- a/cloud/apps/relay/src/database/postgres-connection-latency.test.ts +++ b/cloud/apps/relay/src/database/postgres-connection-latency.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { PostgresDatabase } from './database.js' -import { SLOW_CONNECTION_RETIRE_INTERVAL_MS, SLOW_CONNECTION_SAMPLE_MAX_AGE_MS, SLOW_CONNECTION_WINDOW } from './postgres-connection-latency.js' +import { SLOW_CONNECTION_WINDOW } from './postgres-connection-latency.js' let clock = 0 @@ -9,15 +9,10 @@ type Slot = { name: string; statementMs: () => number } // Hands out its connections in turn; a client released with a truthy value is replaced by a fresh // 3 ms one, as pg-pool would dial a new connection on the next ask. -function pool( - slots: Slot[], - options: { retiresSlowConnections?: boolean } = { retiresSlowConnections: true } -) { +function pool(slots: Slot[]) { const destroyed: string[] = [] - let dialed = 0 let turn = 0 const dial = (slot: Slot) => { - dialed++ const client = Object.assign(new EventEmitter(), { query: async () => { clock += slot.statementMs() @@ -42,8 +37,8 @@ function pool( connect: async () => live[turn++ % live.length] } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: PostgresDatabase and its pool pressure read only connect, these counts and the optional options. - const database = new PostgresDatabase(fake as never, undefined, options) - return { database, destroyed, dialed: () => dialed } + const database = new PostgresDatabase(fake as never, undefined, { retiresSlowConnections: true }) + return { database, destroyed } } const steady = (ms: number) => () => ms @@ -55,21 +50,18 @@ async function runStatements(database: PostgresDatabase, count: number): Promise } describe('slow connection retirement', () => { - let warnings: string[] - beforeEach(() => { clock = 0 - warnings = [] vi.spyOn(performance, 'now').mockImplementation(() => clock) vi.spyOn(Date, 'now').mockImplementation(() => clock) - vi.spyOn(console, 'warn').mockImplementation((line: string) => void warnings.push(line)) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) }) afterEach(() => { vi.restoreAllMocks() }) - it('retires one 55 ms connection among 3 ms peers, and logs it once', async () => { + it('retires one 55 ms connection among 3 ms peers', async () => { const slow = pool([ { name: 'a', statementMs: steady(3) }, { name: 'b', statementMs: steady(3) }, @@ -78,18 +70,6 @@ describe('slow connection retirement', () => { await runStatements(slow.database, SLOW_CONNECTION_WINDOW * 3) expect(slow.destroyed).toEqual(['slow']) - expect(warnings.map((line) => JSON.parse(line))).toEqual([ - { - event: 'orca_relay_postgres_slow_connection_retired', - connectionId: 3, - shape: 'median', - medianMs: 55, - peerMedianMs: 3, - tailMs: 55, - peerTailMs: 0, - statements: SLOW_CONNECTION_WINDOW - } - ]) }) it('retires nothing when the whole database slows down', async () => { @@ -103,40 +83,6 @@ describe('slow connection retirement', () => { expect(all.destroyed).toEqual([]) }) - it('never retires the only connection, which has no peer to compare with', async () => { - const single = pool([{ name: 'only', statementMs: steady(55) }]) - await runStatements(single.database, SLOW_CONNECTION_WINDOW * 4) - - expect(single.destroyed).toEqual([]) - expect(single.dialed()).toBe(1) - }) - - it('judges the median, so one long statement does not retire a healthy connection', async () => { - let calls = 0 - const outlier = pool([ - { name: 'a', statementMs: steady(3) }, - { name: 'b', statementMs: () => (++calls === 4 ? 500 : 3) } - ]) - await runStatements(outlier.database, SLOW_CONNECTION_WINDOW * 4) - - expect(outlier.destroyed).toEqual([]) - }) - - it('forgets samples older than a minute, so a recovered connection is kept', async () => { - let recovered = false - const once = pool([ - { name: 'a', statementMs: steady(3) }, - { name: 'was-slow', statementMs: () => (recovered ? 3 : 55) } - ]) - // One statement short of a full window each, so nothing is judged while it is slow. - await runStatements(once.database, (SLOW_CONNECTION_WINDOW - 1) * 2) - recovered = true - clock += SLOW_CONNECTION_SAMPLE_MAX_AGE_MS + 1 - await runStatements(once.database, SLOW_CONNECTION_WINDOW * 4) - - expect(once.destroyed).toEqual([]) - }) - it('judges a transaction connection on release, never mid-transaction', async () => { const tx = pool([ { name: 'a', statementMs: steady(3) }, @@ -152,58 +98,4 @@ describe('slow connection retirement', () => { expect(tx.destroyed).toEqual(['slow']) }) - - it('retires at most one connection per pool per interval', async () => { - const two = pool([ - { name: 'a', statementMs: steady(3) }, - { name: 'b', statementMs: steady(3) }, - { name: 'slow-1', statementMs: steady(55) }, - { name: 'slow-2', statementMs: steady(55) } - ]) - await runStatements(two.database, SLOW_CONNECTION_WINDOW * 4) - expect(two.destroyed).toEqual(['slow-1']) - - clock += SLOW_CONNECTION_RETIRE_INTERVAL_MS - await runStatements(two.database, 4) - expect(two.destroyed).toEqual(['slow-1', 'slow-2']) - }) - - // Every 50th statement takes `outlierMs`: a 2% tail, like the ~200/400/800 ms retransmit stalls. - const withTail = (baseMs: number, outlierMs: number) => { - let calls = 0 - return () => (++calls % 50 === 0 ? outlierMs : baseMs) - } - - it('retires one connection whose tail turned slow while its median stayed normal', async () => { - const lossy = pool([ - { name: 'a', statementMs: steady(3) }, - { name: 'b', statementMs: steady(3) }, - { name: 'lossy', statementMs: withTail(3, 415) } - ]) - await runStatements(lossy.database, 600) - - expect(lossy.destroyed).toEqual(['lossy']) - expect(JSON.parse(warnings[0] ?? '{}')).toMatchObject({ - shape: 'tail', - tailMs: 415, - peerTailMs: 3 - }) - }) - - it('never retires, or records, on a pool built without retirement, as cells are', async () => { - const cell = pool( - [ - { name: 'a', statementMs: steady(3) }, - { name: 'b', statementMs: steady(3) }, - { name: 'slow', statementMs: steady(55) }, - { name: 'lossy', statementMs: withTail(3, 415) } - ], - {} - ) - await runStatements(cell.database, 1_200) - - expect(cell.destroyed).toEqual([]) - expect(warnings).toEqual([]) - }) - }) diff --git a/cloud/apps/relay/src/database/postgres-lost-reply-postgres.test.ts b/cloud/apps/relay/src/database/postgres-lost-reply-postgres.test.ts index bff710c9bdc..b132f59bbd3 100644 --- a/cloud/apps/relay/src/database/postgres-lost-reply-postgres.test.ts +++ b/cloud/apps/relay/src/database/postgres-lost-reply-postgres.test.ts @@ -3,7 +3,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { isRelayDatabaseTransientError, openRelayDatabase, - POSTGRES_READ_TIMEOUT_MARGIN_MS, type RelayDatabase } from './database.js' @@ -13,17 +12,12 @@ const describePostgres = databaseUrl ? describe : describe.skip const STATEMENT_TIMEOUT_MS = 500 // A short margin keeps the blackhole case fast; production's is 10 s. const READ_TIMEOUT_MARGIN_MS = 2_000 -const READ_TIMEOUT_MS = STATEMENT_TIMEOUT_MS + READ_TIMEOUT_MARGIN_MS const PROBE_TABLE = 'relay_lost_reply_probe' -// Forwards each connection to PostgreSQL. Once a connection sends a statement naming the -// trigger, the server's replies on that connection are dropped (a reply lost in the network), -// or, with `delayMs`, held that long and then delivered (a whole-VM database stall). -async function blackholeProxy(target: URL, trigger: string, delayMs?: number) { +// Drop server replies after a statement naming the trigger reaches PostgreSQL. +async function blackholeProxy(target: URL, trigger: string) { const sockets = new Set() - const timers = new Set>() const afterTrigger: Buffer[] = [] - let forwardingResumed = false const server: Server = createServer((client) => { const upstream = connect(Number(target.port || 5432), target.hostname) sockets.add(client) @@ -35,15 +29,8 @@ async function blackholeProxy(target: URL, trigger: string, delayMs?: number) { upstream.write(chunk) }) upstream.on('data', (chunk: Buffer) => { - if (!swallowing || forwardingResumed) client.write(chunk) - else if (delayMs !== undefined) { - const timer = setTimeout(() => { - timers.delete(timer) - if (!client.destroyed) { - client.write(chunk) - } - }, delayMs) - timers.add(timer) + if (!swallowing) { + client.write(chunk) } }) for (const socket of [client, upstream]) { @@ -62,15 +49,8 @@ async function blackholeProxy(target: URL, trigger: string, delayMs?: number) { url.port = String(address.port) return { url: url.toString(), - resumeForwarding: () => { - forwardingResumed = true - }, sentAfterTrigger: () => Buffer.concat(afterTrigger).toString('latin1'), close: async () => { - for (const timer of timers) { - clearTimeout(timer) - } - timers.clear() for (const socket of sockets) socket.destroy() await new Promise((resolve) => server.close(() => resolve())) } @@ -86,10 +66,7 @@ describePostgres('a lost PostgreSQL reply against a real server', () => { async function open( url: string, options: { - readTimeoutMarginMs?: number statementTimeoutMs?: number - poolMax?: number - readTimeoutMarginOverrideMs?: () => number | undefined } = {} ): Promise { const database = await openRelayDatabase({ @@ -97,15 +74,13 @@ describePostgres('a lost PostgreSQL reply against a real server', () => { dataDir: '', appliesPostgresSchema: false, statementTimeoutMs: options.statementTimeoutMs ?? STATEMENT_TIMEOUT_MS, - readTimeoutMarginMs: options.readTimeoutMarginMs ?? READ_TIMEOUT_MARGIN_MS, - poolMax: options.poolMax, - readTimeoutMarginOverrideMs: options.readTimeoutMarginOverrideMs + readTimeoutMarginMs: READ_TIMEOUT_MARGIN_MS }) cleanups.push(async () => await database.close()) return database } - it('fails within the read timeout, sends nothing after the lost statement, and recovers', async () => { + it('rejects a lost transaction reply without sending more SQL and recovers', async () => { const direct = await open(databaseUrl!, { statementTimeoutMs: 5_000 }) await direct.query(`CREATE TABLE IF NOT EXISTS ${PROBE_TABLE} (id TEXT PRIMARY KEY)`) await direct.query(`INSERT INTO ${PROBE_TABLE} (id) VALUES ('c1') ON CONFLICT DO NOTHING`) @@ -116,7 +91,6 @@ describePostgres('a lost PostgreSQL reply against a real server', () => { cleanups.push(proxy.close) const database = await open(proxy.url) - const startedAt = performance.now() const failure = await database .transaction( async (transaction) => @@ -125,11 +99,9 @@ describePostgres('a lost PostgreSQL reply against a real server', () => { }) ) .catch((error: unknown) => error) - const elapsedMs = performance.now() - startedAt expect(failure).toBeInstanceOf(Error) expect(isRelayDatabaseTransientError(failure)).toBe(true) - expect(elapsedMs).toBeLessThan(READ_TIMEOUT_MS + 1_000) // pg's Terminate ('X') may follow as the client is destroyed; no statement may. const after = proxy.sentAfterTrigger() for (const statement of ['lock_timeout', 'ROLLBACK', 'COMMIT', 'SELECT']) { @@ -147,54 +119,4 @@ describePostgres('a lost PostgreSQL reply against a real server', () => { ) ).resolves.toEqual([{ id: 'c1' }]) }, 20_000) - - // The per-cell switch moves the margin per query, with no restart and no new pool. - it('applies the switch file margin per query, over the pool margin', async () => { - const direct = await open(databaseUrl!, { statementTimeoutMs: 5_000 }) - await direct.query(`CREATE TABLE IF NOT EXISTS ${PROBE_TABLE} (id TEXT PRIMARY KEY)`) - cleanups.push(async () => { - await direct.query(`DROP TABLE IF EXISTS ${PROBE_TABLE}`) - }) - const proxy = await blackholeProxy(new URL(databaseUrl!), `FROM ${PROBE_TABLE}`) - cleanups.push(proxy.close) - let override: number | undefined = 1_000 - // The pool's own margin would hold the lost reply for 30 s. - const database = await open(proxy.url, { - readTimeoutMarginMs: 30_000, - readTimeoutMarginOverrideMs: () => override - }) - await expect(database.query('SELECT 1 AS one')).resolves.toEqual([{ one: 1 }]) - const startedAt = performance.now() - const failure = await database - .query(`SELECT id FROM ${PROBE_TABLE}`) - .catch((error: unknown) => error) - expect(isRelayDatabaseTransientError(failure)).toBe(true) - expect(performance.now() - startedAt).toBeLessThan(STATEMENT_TIMEOUT_MS + 1_000 + 1_000) - override = undefined - await expect(database.query('SELECT 1 AS one')).resolves.toEqual([{ one: 1 }]) - }, 20_000) - - // A reply the server sent after statement_timeout, held up by a whole-VM stall, is still a - // reply: the default margin must outlast the routine 5-7 s stalls. - it('keeps a reply delayed 6.5 s by a stall, on the same connection', async () => { - const proxy = await blackholeProxy(new URL(databaseUrl!), 'stalled_reply_probe', 6_500) - cleanups.push(proxy.close) - const database = await open(proxy.url, { - readTimeoutMarginMs: POSTGRES_READ_TIMEOUT_MARGIN_MS, - poolMax: 1 - }) - const pid = async () => (await database.query('SELECT pg_backend_pid() AS pid'))[0]?.pid - const before = await pid() - const startedAt = performance.now() - // Autocommit: inside a transaction the proxy's hold would trip the server's own 5 s - // idle-in-transaction limit, which a real VM stall pauses along with everything else. - await expect(database.query("SELECT 'stalled_reply_probe' AS probe")).resolves.toEqual([ - { probe: 'stalled_reply_probe' } - ]) - expect(performance.now() - startedAt).toBeGreaterThan(6_000) - proxy.resumeForwarding() - // Not destroyed: the one pooled connection is still the same backend. - expect(await pid()).toBe(before) - }, 30_000) - }) diff --git a/cloud/apps/relay/src/database/postgres-priority-lane-postgres.test.ts b/cloud/apps/relay/src/database/postgres-priority-lane-postgres.test.ts deleted file mode 100644 index 19c0e3b4247..00000000000 --- a/cloud/apps/relay/src/database/postgres-priority-lane-postgres.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { afterAll, describe, expect, it, vi } from 'vitest' -import type { PostgresDatabase } from './database.js' -import { isPostgresPoolConnectTimeout } from './postgres-pool-pressure.js' -import { openDelayedPostgresDatabase } from '../test-fixtures/delayed-postgres-database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip - -// The 2026-10-06 asia-east2 shape at test scale: a reconnect herd far wider -// than the pool, every statement paying a cross-region round trip, and a -// control renewal arriving behind it. -describePostgres('PostgreSQL priority lane under a reconnect herd', () => { - const databases: PostgresDatabase[] = [] - const delay = { enabled: true, delayMs: 400 } - - afterAll(async () => { - delay.enabled = false - for (const database of databases) await database.close() - }) - - it('renews ahead of the herd while queued general work times out', async () => { - const database = openDelayedPostgresDatabase(databaseUrl!, delay, 4) - databases.push(database) - const herd = Array.from({ length: 40 }, () => - database.query('SELECT 1').then( - () => 'ok', - (error: unknown) => (isPostgresPoolConnectTimeout(error) ? 'timeout' : 'other') - ) - ) - await vi.waitFor(() => - expect(database.peekPoolPressure().databasePoolWaiting).toBeGreaterThan(0) - ) - const startedAt = performance.now() - const general = database.query('SELECT 1 AS renewed').then( - () => ({ outcome: 'ok', elapsedMs: performance.now() - startedAt }), - (error: unknown) => ({ - outcome: isPostgresPoolConnectTimeout(error) ? 'timeout' : 'other', - elapsedMs: performance.now() - startedAt - }) - ) - try { - const renewed = await database.queryPriority('SELECT 1 AS renewed') - const renewedMs = performance.now() - startedAt - - expect(renewed).toEqual([{ renewed: 1 }]) - // The next released connection plus one statement, never a turn in the herd's queue. - expect(renewedMs).toBeLessThan(1_500) - // The same statement on the general lane waits out the herd's acquire timeout. - const queued = await general - expect(queued.outcome).toBe('timeout') - expect(queued.elapsedMs).toBeGreaterThan(1_900) - const outcomes = await Promise.all(herd) - expect(outcomes.filter((outcome) => outcome === 'timeout').length).toBeGreaterThan(20) - expect(outcomes).not.toContain('other') - } finally { - await Promise.all([...herd, general]) - } - }, 15_000) -}) diff --git a/cloud/apps/relay/src/database/postgres-query-failure-postgres.test.ts b/cloud/apps/relay/src/database/postgres-query-failure-postgres.test.ts deleted file mode 100644 index 01f14028f97..00000000000 --- a/cloud/apps/relay/src/database/postgres-query-failure-postgres.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { openRelayDatabase, type RelayDatabase } from './database.js' - -const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL -const describePostgres = databaseUrl ? describe : describe.skip - -describePostgres('real PostgreSQL query failure phases', () => { - let database: RelayDatabase - - beforeAll(async () => { - database = await openRelayDatabase({ - databaseUrl, - dataDir: '', - poolMax: 1, - statementTimeoutMs: 50 - }) - }) - afterAll(async () => { - await database.close() - }) - afterEach(() => { - vi.restoreAllMocks() - }) - - it('distinguishes a server statement timeout and leaves the pool usable', async () => { - const log = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - await expect(database.query('SELECT pg_sleep(0.2)')).rejects.toMatchObject({ code: '57014' }) - expect(JSON.parse(log.mock.calls[0]![0] as string)).toMatchObject({ - event: 'orca_relay_postgres_query_failed', - phase: 'execute', - code: '57014', - connectionTimeout: false, - transient: true - }) - expect(await database.query('SELECT 1 AS ok')).toEqual([{ ok: 1 }]) - }) - - it('distinguishes queue acquisition timeout without running the statement', async () => { - const log = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - let acquired!: () => void - const ready = new Promise((resolve) => { - acquired = resolve - }) - let release!: () => void - const wait = new Promise((resolve) => { - release = resolve - }) - const holder = database.transaction(async () => { - acquired() - await wait - }) - await ready - try { - await expect(database.query('SELECT pg_sleep(0.2)')).rejects.toThrow( - 'timeout exceeded when trying to connect' - ) - expect(JSON.parse(log.mock.calls[0]![0] as string)).toMatchObject({ - event: 'orca_relay_postgres_query_failed', - phase: 'acquire', - code: 'unknown', - connectionTimeout: true, - transient: true, - poolTotal: 1, - poolIdle: 0 - }) - } finally { - release() - await holder - } - expect(await database.query('SELECT 1 AS ok')).toEqual([{ ok: 1 }]) - }) -}) diff --git a/cloud/apps/relay/src/database/postgres-statement-stats-postgres.test.ts b/cloud/apps/relay/src/database/postgres-statement-stats-postgres.test.ts index f152a90be23..7f1efd76202 100644 --- a/cloud/apps/relay/src/database/postgres-statement-stats-postgres.test.ts +++ b/cloud/apps/relay/src/database/postgres-statement-stats-postgres.test.ts @@ -74,12 +74,12 @@ describePostgres('optional PostgreSQL statement statistics', () => { } }) - it.each([false, true])('tolerates missing extension privileges (read settings: %s)', async (readSettings) => { + it('tolerates missing extension privileges', async () => { const client = await connect(await freshDatabase()) const role = `relay_stats_role_${randomUUID().replaceAll('-', '')}` await admin.query(`CREATE ROLE ${role}`) roles.push(role) - if (readSettings) await admin.query(`GRANT pg_read_all_settings TO ${role}`) + await admin.query(`GRANT pg_read_all_settings TO ${role}`) try { await client.query(`SET ROLE ${role}`) await client.query(POSTGRES_STATEMENT_STATS_MIGRATION) @@ -90,22 +90,6 @@ describePostgres('optional PostgreSQL statement statistics', () => { } }) - it('serializes concurrent catalog creation across directors', async (context) => { - if (!preloaded) { - context.skip() - } - const url = await freshDatabase() - const clients = await Promise.all(Array.from({ length: 5 }, async () => await connect(url))) - try { - await Promise.all( - clients.map(async (client) => await client.query(POSTGRES_STATEMENT_STATS_MIGRATION)) - ) - expect(await installed(clients[0]!)).toBe(true) - } finally { - await Promise.all(clients.map(async (client) => await client.end())) - } - }) - it('yields to an in-progress installer instead of blocking startup', async (context) => { if (!preloaded) { context.skip() diff --git a/cloud/apps/relay/src/database/postgres-transaction-recovery.test.ts b/cloud/apps/relay/src/database/postgres-transaction-recovery.test.ts index ebd2635c73c..597bcc0386a 100644 --- a/cloud/apps/relay/src/database/postgres-transaction-recovery.test.ts +++ b/cloud/apps/relay/src/database/postgres-transaction-recovery.test.ts @@ -21,12 +21,9 @@ const describePostgres = databaseUrl ? describe : describe.skip type QueryLockHook = (phase: 'before' | 'after', sql: string) => Promise class TransactionProbeDatabase implements RelayDatabase { - attempts = 0 - constructor( private readonly database: RelayDatabase, - private readonly hook: QueryLockHook, - private readonly probeQueries = false + private readonly hook: QueryLockHook ) {} async query(sql: string, params?: unknown[]): Promise { @@ -43,9 +40,8 @@ class TransactionProbeDatabase implements RelayDatabase { async transaction(operation: (transaction: RelayDatabase) => Promise): Promise { return await this.database.transaction(async (transaction) => { - this.attempts++ return await operation( - new QueryLockProbeTransaction(transaction, this.hook, this.probeQueries) + new QueryLockProbeTransaction(transaction, this.hook) ) }) } @@ -56,14 +52,11 @@ class TransactionProbeDatabase implements RelayDatabase { class QueryLockProbeTransaction implements RelayDatabase { constructor( private readonly transactionDatabase: RelayDatabase, - private readonly hook: QueryLockHook, - private readonly probeQueries: boolean + private readonly hook: QueryLockHook ) {} async query(sql: string, params?: unknown[]): Promise { - if (this.probeQueries) await this.hook('before', sql) const rows = await this.transactionDatabase.query(sql, params) - if (this.probeQueries) await this.hook('after', sql) return rows } @@ -325,7 +318,6 @@ describePostgres('PostgreSQL transaction recovery', () => { mutateWithOppositeLockOrder(1, keys[1]!, keys[0]!) ]) - expect([...attempts].sort()).toEqual([1, 2]) const rows = await database.query( `SELECT scope_key, count FROM relay_rate_windows WHERE window_kind = ? ORDER BY scope_key`, @@ -335,483 +327,9 @@ describePostgres('PostgreSQL transaction recovery', () => { { scope_key: keys[0], count: '1' }, { scope_key: keys[1], count: '1' } ]) - expect(warn).toHaveBeenCalledWith( - expect.stringContaining('"event":"orca_relay_postgres_transaction_retry"') - ) - expect(warn).toHaveBeenCalledWith(expect.stringContaining('"phase":"rate-limit"')) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('"event":"orca_relay_postgres_transaction_exhausted"') - ) warn.mockRestore() }, 10_000) - it('defers assignment around a released-cell activity transaction', async () => { - const now = 1_100_000_000_000 - const identity = { userId: 'released-order-user', relayHostId: 'releasedorder001' } - const cellId = 'released-order-cell' - const activityId = 'splice:released-order' - await database.query( - `DELETE FROM relay_assignment_activity_leases WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database.query(`DELETE FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, [ - identity.userId, - identity.relayHostId - ]) - const seedStore = new RelayAssignmentStore(database, () => now) - await seedStore.reconcileCells([ - { id: cellId, url: 'https://released-order.example.com', capacityRequests: 100 } - ]) - const assignment = await seedStore.assign(identity) - await seedStore.acquireActivity(identity, { activityId, kind: 'splice', cellId }) - - const assignmentLocked = signal() - const legacyCellLocked = signal() - let gateFirstAssignmentAttempt = true - const directorDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if ( - gateFirstAssignmentAttempt && - phase === 'after' && - sql.includes('FROM relay_assignments') - ) { - gateFirstAssignmentAttempt = false - assignmentLocked.resolve() - await legacyCellLocked.promise - } - }) - const directorStore = new RelayAssignmentStore(directorDatabase, () => now) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - const directorAssign = directorStore.assign(identity) - await assignmentLocked.promise - let legacyAttempts = 0 - const legacyRelease = database.transaction(async (transaction) => { - legacyAttempts++ - const lease = ( - await transaction.queryLocked( - `SELECT * FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND activity_id = ?`, - [identity.userId, identity.relayHostId, activityId] - ) - )[0] - if (!lease) return - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [cellId]) - legacyCellLocked.resolve() - await transaction.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests - 2 WHERE cell_id = ?`, - [cellId] - ) - await transaction.query( - `DELETE FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND activity_id = ?`, - [identity.userId, identity.relayHostId, activityId] - ) - await transaction.query( - `UPDATE relay_assignments SET reserved_splices = reserved_splices - 1 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - }) - - await Promise.all([directorAssign, legacyRelease]) - - expect(directorDatabase.attempts).toBe(2) - expect(legacyAttempts).toBe(1) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_retry') - ) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_exhausted') - ) - await expect(seedStore.resolve(identity)).resolves.toMatchObject({ - cellId, - assignmentEpoch: assignment.assignmentEpoch - }) - const state = await database.query( - `SELECT assignment.reserved_controls, assignment.reserved_splices, - cell.reserved_requests - FROM relay_assignments assignment - JOIN relay_cells cell ON cell.cell_id = assignment.cell_id - WHERE assignment.user_id = ? AND assignment.relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - expect(state).toEqual([ - { reserved_controls: '1', reserved_splices: '0', reserved_requests: '1' } - ]) - warn.mockRestore() - }, 15_000) - - it('renews an existing control without waiting on a legacy cell lock', async () => { - const now = 1_150_000_000_000 - const identity = { userId: 'sustained-lock-user', relayHostId: 'sustainedlock01' } - const cell = { - id: 'sustained-lock-cell', - url: 'https://sustained-lock.example.com', - capacityRequests: 100 - } - const seedStore = new RelayAssignmentStore(database, () => now) - await seedStore.reconcileCells([cell]) - await seedStore.assign(identity) - - const legacyCellLocked = signal() - const releaseLegacyCell = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [cell.id]) - legacyCellLocked.resolve() - await releaseLegacyCell.promise - }) - await legacyCellLocked.promise - - let inventoryAttempts = 0 - const assignmentDatabase = new TransactionProbeDatabase( - database, - async (phase, sql) => { - if (phase !== 'before' || !sql.includes('FROM relay_cells ORDER BY')) return - inventoryAttempts++ - } - ) - const assignmentStore = new RelayAssignmentStore(assignmentDatabase, () => now) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - await expect(assignmentStore.assign(identity)).resolves.toMatchObject({ - cellId: cell.id - }) - releaseLegacyCell.resolve() - await expect(legacyTransaction).resolves.toBeUndefined() - expect(inventoryAttempts).toBe(0) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_retry') - ) - warn.mockRestore() - }, 15_000) - - it('retries a new sticky control without forming a legacy cell-first deadlock', async () => { - const now = 1_175_000_000_000 - const identity = { - userId: 'sticky-cell-contention-user', - relayHostId: 'stickycellwait1' - } - const cell = { - id: 'sticky-cell-contention-cell', - url: 'https://sticky-cell-contention.example.com', - capacityRequests: 100 - } - const seedStore = new RelayAssignmentStore(database, () => now) - await seedStore.reconcileCells([cell]) - await seedStore.assign(identity) - await seedStore.changeActivity(identity, 'migration', 1) - // Drops the grant's pending lease too: a sticky control the rows do not - // show is what sends the retry through the NOWAIT cell lock. - await seedStore.releaseActivity(identity, 'control-pending:1') - - const legacyCellLocked = signal() - const directorAssignmentLocked = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [cell.id]) - legacyCellLocked.resolve() - await directorAssignmentLocked.promise - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - }) - await legacyCellLocked.promise - - let signalFirstAttempt = true - const directorLockOrder: string[] = [] - const assignmentDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if (phase === 'before') { - // Only locked statements reach this hook, so classifying the pin read - // is what proves it stays unlocked: if it ever grows a FOR UPDATE it - // shows up in the order below instead of silently joining the queue. - if (sql.includes('SELECT cell_id FROM relay_assignments')) { - directorLockOrder.push('pin-read') - } else if (sql.includes('FROM relay_assignments WHERE user_id = ?')) { - directorLockOrder.push('assignment') - } else if (sql.includes('FROM relay_assignment_activity_leases')) { - directorLockOrder.push('activity') - } else if (sql.includes('FROM relay_cells ORDER BY')) { - directorLockOrder.push('cell-inventory') - } else if (sql.includes('FROM relay_cells WHERE cell_id IN')) { - directorLockOrder.push('cell-rows') - } else if (sql.includes('FROM relay_cells WHERE cell_id = ?')) { - directorLockOrder.push('cell') - } - } - if ( - signalFirstAttempt && - phase === 'after' && - sql.includes('FROM relay_assignments WHERE user_id = ?') - ) { - signalFirstAttempt = false - directorAssignmentLocked.resolve() - } - }) - const store = new RelayAssignmentStore(assignmentDatabase, () => now) - - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: cell.id, - assignmentEpoch: 1 - }) - await expect(legacyTransaction).resolves.toBeUndefined() - expect(assignmentDatabase.attempts).toBe(2) - // The retry still takes a cell row before the assignment row — the order - // that avoids the legacy cycle — but only the pinned row, never the - // inventory. - expect(directorLockOrder).toEqual([ - 'assignment', - 'activity', - 'cell', - 'cell-rows', - 'assignment', - 'activity' - ]) - const state = await database.query( - `SELECT assignment.reserved_controls, assignment.migration_leases, - cell.reserved_requests - FROM relay_assignments assignment - JOIN relay_cells cell ON cell.cell_id = assignment.cell_id - WHERE assignment.user_id = ? AND assignment.relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - expect(state).toEqual([ - { reserved_controls: '1', migration_leases: '1', reserved_requests: '2' } - ]) - }, 15_000) - - it('serializes normalized assignment and activity release without a retry', async () => { - const now = 1_200_000_000_000 - const identity = { userId: 'normalized-order-user', relayHostId: 'normalizedorder1' } - const cellId = 'normalized-order-cell' - const activityId = 'splice:normalized-order' - await database.query( - `DELETE FROM relay_assignment_activity_leases WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database.query(`DELETE FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, [ - identity.userId, - identity.relayHostId - ]) - const seedStore = new RelayAssignmentStore(database, () => now) - await seedStore.reconcileCells([ - { id: cellId, url: 'https://normalized-order.example.com', capacityRequests: 100 } - ]) - await seedStore.assign(identity) - await seedStore.acquireActivity(identity, { activityId, kind: 'splice', cellId }) - - const assignmentLocked = signal() - const releaseReachedAssignment = signal() - const continueAssignment = signal() - let gateFirstAssignmentAttempt = true - const assignDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if ( - gateFirstAssignmentAttempt && - phase === 'after' && - sql.includes('FROM relay_assignments') - ) { - gateFirstAssignmentAttempt = false - assignmentLocked.resolve() - await continueAssignment.promise - } - }) - const releaseDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if (phase === 'before' && sql.includes('FROM relay_assignments')) { - releaseReachedAssignment.resolve() - } - }) - const assignStore = new RelayAssignmentStore(assignDatabase, () => now) - const releaseStore = new RelayAssignmentStore(releaseDatabase, () => now) - - const assign = assignStore.assign(identity) - await assignmentLocked.promise - const release = releaseStore.releaseActivity(identity, activityId) - await releaseReachedAssignment.promise - continueAssignment.resolve() - await Promise.all([assign, release]) - - expect(assignDatabase.attempts).toBe(1) - expect(releaseDatabase.attempts).toBe(1) - const state = await database.query( - `SELECT assignment.reserved_controls, assignment.reserved_splices, - cell.reserved_requests - FROM relay_assignments assignment - JOIN relay_cells cell ON cell.cell_id = assignment.cell_id - WHERE assignment.user_id = ? AND assignment.relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - expect(state).toEqual([ - { reserved_controls: '1', reserved_splices: '0', reserved_requests: '1' } - ]) - }, 15_000) - - it('takes the shared cell lock only for the final atomic activity write', async () => { - const now = 1_250_000_000_000 - const cell = { - id: 'atomic-final-cell', - url: 'https://atomic-final.example.com', - capacityRequests: 4 - } - const identities = [ - { userId: 'atomic-final-user-a', relayHostId: 'atomicfinalhosta' }, - { userId: 'atomic-final-user-b', relayHostId: 'atomicfinalhostb' } - ] - const seedStore = new RelayAssignmentStore(database, () => now) - await seedStore.reconcileCells([cell]) - await Promise.all(identities.map(async (identity) => await seedStore.assign(identity))) - - const firstAtCellWrite = signal() - const secondAtCellWrite = signal() - const releaseFirst = signal() - const releaseSecond = signal() - const isAtomicCellWrite = (sql: string): boolean => - sql.includes('UPDATE relay_cells SET reserved_requests') && - sql.includes('RETURNING cell_id') - const firstDatabase = new TransactionProbeDatabase( - database, - async (phase, sql) => { - if (phase !== 'before' || !isAtomicCellWrite(sql)) return - firstAtCellWrite.resolve() - await releaseFirst.promise - }, - true - ) - const secondDatabase = new TransactionProbeDatabase( - database, - async (phase, sql) => { - if (phase !== 'before' || !isAtomicCellWrite(sql)) return - secondAtCellWrite.resolve() - await releaseSecond.promise - }, - true - ) - const first = new RelayAssignmentStore(firstDatabase, () => now).acquireActivity( - identities[0]!, - { activityId: 'splice:atomic-final-a', kind: 'splice', cellId: cell.id } - ) - await firstAtCellWrite.promise - const second = new RelayAssignmentStore(secondDatabase, () => now).acquireActivity( - identities[1]!, - { activityId: 'splice:atomic-final-b', kind: 'splice', cellId: cell.id } - ) - let reachTimeout: ReturnType | undefined - const secondReachedCellWrite = await Promise.race([ - secondAtCellWrite.promise.then(() => true), - new Promise((resolve) => { - reachTimeout = setTimeout(() => resolve(false), 2_000) - }) - ]) - if (reachTimeout) clearTimeout(reachTimeout) - if (!secondReachedCellWrite) { - releaseFirst.resolve() - releaseSecond.resolve() - await Promise.allSettled([first, second]) - } - expect(secondReachedCellWrite).toBe(true) - - releaseFirst.resolve() - await expect(first).resolves.toBeUndefined() - releaseSecond.resolve() - await expect(second).rejects.toThrow('relay_capacity_exhausted') - await expect( - database.query( - `SELECT cell.reserved_requests, COUNT(lease.activity_id) AS leases, - COALESCE(SUM(lease.request_units), 0) AS lease_units - FROM relay_cells cell - LEFT JOIN relay_assignment_activity_leases lease ON lease.cell_id = cell.cell_id - WHERE cell.cell_id = ? GROUP BY cell.cell_id, cell.reserved_requests`, - [cell.id] - ) - ).resolves.toEqual([{ reserved_requests: '4', leases: '3', lease_units: '4' }]) - await expect( - database.query( - `SELECT user_id, reserved_splices FROM relay_assignments - WHERE user_id IN (?, ?) ORDER BY user_id`, - [identities[0]!.userId, identities[1]!.userId] - ) - ).resolves.toEqual([ - { user_id: identities[0]!.userId, reserved_splices: '1' }, - { user_id: identities[1]!.userId, reserved_splices: '0' } - ]) - }, 15_000) - - it('reconciles drift under the assignment-first lock order while activity waits', async () => { - const now = 1_300_000_000_000 - const cells = [ - { id: 'reconcile-cell-a', url: 'https://reconcile-a.example.com', capacityRequests: 100 }, - { id: 'reconcile-cell-b', url: 'https://reconcile-b.example.com', capacityRequests: 100 } - ] - const identities = Array.from({ length: 12 }, (_, index) => ({ - userId: `reconcile-user-${index}`, - relayHostId: `reconcilehost${String(index).padStart(4, '0')}` - })) - const seedStore = new RelayAssignmentStore(database, () => now) - await seedStore.reconcileCells(cells) - for (const identity of identities) await seedStore.assign(identity) - await database.query( - `UPDATE relay_assignments SET reserved_controls = 7, reserved_splices = 5 - WHERE user_id LIKE 'reconcile-user-%'` - ) - await database.query( - `UPDATE relay_cells SET reserved_requests = 42 - WHERE cell_id IN (?, ?)`, - ['reconcile-cell-a', 'reconcile-cell-b'] - ) - - const assignmentsLocked = signal() - const activityReachedAssignment = signal() - const continueReconciliation = signal() - let gateReconciliation = true - const reconcileDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if ( - gateReconciliation && - phase === 'after' && - sql.includes('SELECT assignment.* FROM relay_assignments assignment') - ) { - gateReconciliation = false - assignmentsLocked.resolve() - await continueReconciliation.promise - } - }) - const activityDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if (phase === 'before' && sql.includes('FROM relay_assignments WHERE user_id')) { - activityReachedAssignment.resolve() - } - }) - const reconcileStore = new RelayAssignmentStore(reconcileDatabase, () => now) - const activityStore = new RelayAssignmentStore(activityDatabase, () => now) - - const reconciliation = reconcileStore.cellEvacuationStatus( - 'reconcile-cell-a', - 'reconcile-cell-b', - true - ) - await assignmentsLocked.promise - const activity = activityStore.acquireActivity(identities[0]!, { - activityId: 'splice:reconcile', - kind: 'splice', - cellId: 'reconcile-cell-a' - }) - await activityReachedAssignment.promise - continueReconciliation.resolve() - await Promise.all([reconciliation, activity]) - - expect(reconcileDatabase.attempts).toBe(1) - expect(activityDatabase.attempts).toBe(1) - const reservations = await database.query( - `SELECT cell.cell_id, cell.reserved_requests, - COALESCE(SUM(lease.request_units), 0) AS lease_units - FROM relay_cells cell - LEFT JOIN relay_assignment_activity_leases lease ON lease.cell_id = cell.cell_id - WHERE cell.cell_id IN (?, ?) - GROUP BY cell.cell_id, cell.reserved_requests ORDER BY cell.cell_id`, - ['reconcile-cell-a', 'reconcile-cell-b'] - ) - expect(reservations).toEqual([ - { cell_id: 'reconcile-cell-a', reserved_requests: '8', lease_units: '8' }, - { cell_id: 'reconcile-cell-b', reserved_requests: '6', lease_units: '6' } - ]) - }, 15_000) - it('keeps a unit placed between reconciliation reading leases and locking cells', async () => { const now = 1_350_000_000_000 const cells = [ @@ -945,529 +463,4 @@ describePostgres('PostgreSQL transaction recovery', () => { ).resolves.toMatchObject({ inProgress: 0 }) }, 15_000) - it('defers completion instead of deadlocking with a legacy cell-first lock', async () => { - const now = 1_500_000_000_000 - const identity = { - userId: 'completion-contention-user', - relayHostId: 'completionwait01' - } - const sourceCell = { - id: 'completion-contention-source', - url: 'https://completion-contention-source.example.com', - capacityRequests: 100 - } - const targetCell = { - id: 'completion-contention-target', - url: 'https://completion-contention-target.example.com', - capacityRequests: 100 - } - const store = new RelayAssignmentStore(database, () => now, { - requireLiveCells: true - }) - await store.reconcileCells([sourceCell, targetCell]) - await store.recordCellHeartbeat({ - cellId: sourceCell.id, - cellUrl: sourceCell.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: now - 100, - ready: true, - observedRequests: 0 - }) - await store.recordCellHeartbeat({ - cellId: targetCell.id, - cellUrl: targetCell.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: now - 100, - ready: true, - observedRequests: 0 - }) - const assignment = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: sourceCell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - const migration = await store.startEvacuation(identity, targetCell.id) - await store.activateControl(identity, { - cellId: targetCell.id, - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: targetCell.id, - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await store.setCellEnabled(sourceCell.id, false) - - const legacyCellLocked = signal() - const completionAssignmentLocked = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [ - sourceCell.id - ]) - legacyCellLocked.resolve() - await completionAssignmentLocked.promise - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - }) - await legacyCellLocked.promise - - let signalCompletion = true - const completionDatabase = new TransactionProbeDatabase( - database, - async (phase, sql) => { - if ( - signalCompletion && - phase === 'after' && - sql.includes('FROM relay_assignments WHERE user_id') - ) { - signalCompletion = false - completionAssignmentLocked.resolve() - } - } - ) - const completionStore = new RelayAssignmentStore(completionDatabase, () => now, { - requireLiveCells: true - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - await expect(completionStore.completeReadyEvacuations()).resolves.toBe(0) - await expect(legacyTransaction).resolves.toBeUndefined() - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_retry') - ) - await expect(store.completeReadyEvacuations()).resolves.toBe(1) - }, 15_000) - - it('normalizes persistent dead-source inventory contention', async () => { - let now = 1_550_000_000_000 - const identity = { - userId: 'dead-source-contention-user', - relayHostId: 'deadsourcewait01' - } - const secondIdentity = { - userId: identity.userId, - relayHostId: 'deadsourcewait02' - } - const sourceCell = { - id: 'dead-source-contention-source', - url: 'https://dead-source-contention-source.example.com', - capacityRequests: 100 - } - const targetCell = { - id: 'dead-source-contention-target', - url: 'https://dead-source-contention-target.example.com', - capacityRequests: 100 - } - const sourceIncarnation = '11111111-1111-4111-8111-111111111111' - const targetIncarnation = '22222222-2222-4222-8222-222222222222' - const store = new RelayAssignmentStore(database, () => now, { - requireLiveCells: true - }) - await store.reconcileCells([sourceCell, targetCell]) - await store.setCellEnabled(targetCell.id, false) - await store.recordCellHeartbeat({ - cellId: sourceCell.id, - cellUrl: sourceCell.url, - cellIncarnation: sourceIncarnation, - startedAt: now - 100, - ready: true, - observedRequests: 0 - }) - await store.recordCellHeartbeat({ - cellId: targetCell.id, - cellUrl: targetCell.url, - cellIncarnation: targetIncarnation, - startedAt: now - 100, - ready: true, - observedRequests: 0 - }) - const assignment = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: sourceCell.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled(targetCell.id, true) - const migration = await store.startEvacuation(identity, targetCell.id) - await store.activateControl(identity, { - cellId: targetCell.id, - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: targetCell.id, - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - const secondAssignment = await store.assign(secondIdentity) - expect(secondAssignment.cellId).toBe(sourceCell.id) - const secondSourceControl = await store.activateControl(secondIdentity, { - cellId: sourceCell.id, - assignmentEpoch: secondAssignment.assignmentEpoch, - generation: 1 - }) - const secondMigration = await store.startEvacuation(secondIdentity, targetCell.id) - await store.activateControl(secondIdentity, { - cellId: targetCell.id, - assignmentEpoch: secondMigration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(secondIdentity, { - cellId: targetCell.id, - assignmentEpoch: secondMigration.assignmentEpoch - }) - await store.releaseActivity(secondIdentity, secondSourceControl) - await store.setCellEnabled(sourceCell.id, false) - now += 45_001 - await store.recordCellHeartbeat({ - cellId: targetCell.id, - cellUrl: targetCell.url, - cellIncarnation: targetIncarnation, - startedAt: now - 45_101, - ready: true, - observedRequests: 0 - }) - await store.attestCellFence(sourceCell.id, sourceIncarnation) - - const legacyCellLocked = signal() - const completionAssignmentLocked = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [ - sourceCell.id - ]) - legacyCellLocked.resolve() - await completionAssignmentLocked.promise - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - }) - await legacyCellLocked.promise - - let signalCompletion = true - const fallbackInventoryLocked = signal() - const freshAssignmentLocked = signal() - const persistentInventoryLocked = signal() - let releasePersistentInventory = false - const completionDatabase = new TransactionProbeDatabase( - database, - async (phase, sql) => { - if ( - signalCompletion && - phase === 'after' && - sql.includes('FROM relay_assignments WHERE user_id') - ) { - signalCompletion = false - completionAssignmentLocked.resolve() - } else if ( - phase === 'after' && - sql.trim() === 'SELECT * FROM relay_cells ORDER BY cell_id ASC' - ) { - fallbackInventoryLocked.resolve() - await freshAssignmentLocked.promise - } - } - ) - const completionStore = new RelayAssignmentStore(completionDatabase, () => now, { - requireLiveCells: true - }) - const freshAssignmentTransaction = database.transaction(async (transaction) => { - await fallbackInventoryLocked.promise - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - freshAssignmentLocked.resolve() - await transaction.queryLocked(`SELECT * FROM relay_cells ORDER BY cell_id ASC`) - persistentInventoryLocked.resolve() - while (!releasePersistentInventory) { - await new Promise((resolve) => setTimeout(resolve, 250)) - await transaction.query(`SELECT 1`) - } - }) - - const completion = completionStore.cellEvacuationStatus( - sourceCell.id, - targetCell.id, - true - ) - await persistentInventoryLocked.promise - await expect( - completion - ).resolves.toMatchObject({ inProgress: 2, completed: 0, blocked: 2 }) - await expect(legacyTransaction).resolves.toBeUndefined() - releasePersistentInventory = true - await expect(freshAssignmentTransaction).resolves.toBeUndefined() - await expect( - store.cellEvacuationStatus(sourceCell.id, targetCell.id, true) - ).resolves.toMatchObject({ inProgress: 0, completed: 2, blocked: 0 }) - }, 25_000) - - it('defers expired lease cleanup around a legacy cell-first lock', async () => { - const now = 1_600_000_000_000 - const identity = { - userId: 'lease-contention-user', - relayHostId: 'leasecontention1' - } - const cell = { - id: 'lease-contention-cell', - url: 'https://lease-contention-cell.example.com', - capacityRequests: 100 - } - const store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells([cell]) - await store.assign(identity) - await database.query( - `UPDATE relay_assignment_activity_leases SET expires_at = ? - WHERE user_id = ? AND relay_host_id = ?`, - [now - 1, identity.userId, identity.relayHostId] - ) - - const legacyCellLocked = signal() - const cleanupAssignmentLocked = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [cell.id]) - legacyCellLocked.resolve() - await cleanupAssignmentLocked.promise - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - }) - await legacyCellLocked.promise - - let signalCleanup = true - const cleanupDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if ( - signalCleanup && - phase === 'after' && - sql.includes('FROM relay_assignments WHERE user_id') - ) { - signalCleanup = false - cleanupAssignmentLocked.resolve() - } - }) - const cleanupStore = new RelayAssignmentStore(cleanupDatabase, () => now) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - await expect(cleanupStore.releaseExpiredActivityLeases()).resolves.toBe(0) - await expect(legacyTransaction).resolves.toBeUndefined() - expect(cleanupDatabase.attempts).toBe(1) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_retry') - ) - await expect(store.releaseExpiredActivityLeases()).resolves.toBe(1) - }, 15_000) - - it('skips an expired lease when another director owns its assignment lock', async () => { - const now = 1_650_000_000_000 - const identity = { - userId: 'lease-assignment-contention-user', - relayHostId: 'leaseassignment1' - } - const cell = { - id: 'lease-assignment-contention-cell', - url: 'https://lease-assignment-contention-cell.example.com', - capacityRequests: 100 - } - const store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells([cell]) - await store.assign(identity) - await database.query( - `UPDATE relay_assignment_activity_leases SET expires_at = ? - WHERE user_id = ? AND relay_host_id = ?`, - [now - 1, identity.userId, identity.relayHostId] - ) - - const assignmentLocked = signal() - const releaseAssignment = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - assignmentLocked.resolve() - await releaseAssignment.promise - }) - await assignmentLocked.promise - - const cleanupDatabase = new TransactionProbeDatabase(database, async () => undefined) - const cleanupStore = new RelayAssignmentStore(cleanupDatabase, () => now) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - await expect(cleanupStore.releaseExpiredActivityLeases()).resolves.toBe(0) - expect(cleanupDatabase.attempts).toBe(1) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_retry') - ) - warn.mockRestore() - - releaseAssignment.resolve() - await expect(legacyTransaction).resolves.toBeUndefined() - await expect(store.releaseExpiredActivityLeases()).resolves.toBe(1) - }, 15_000) - - it('defers aggregate expiry cleanup around a legacy cell-first lock', async () => { - const now = 1_700_000_000_000 - const identity = { - userId: 'aggregate-contention-user', - relayHostId: 'aggregatewait01' - } - const cell = { - id: 'aggregate-contention-cell', - url: 'https://aggregate-contention-cell.example.com', - capacityRequests: 100 - } - const store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells([cell]) - await store.assign(identity) - await database.query( - `DELETE FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database.query( - `UPDATE relay_assignments SET lease_expires_at = ? - WHERE user_id = ? AND relay_host_id = ?`, - [now - 1, identity.userId, identity.relayHostId] - ) - - const legacyCellLocked = signal() - const cleanupAssignmentsLocked = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked(`SELECT * FROM relay_cells WHERE cell_id = ?`, [cell.id]) - legacyCellLocked.resolve() - await cleanupAssignmentsLocked.promise - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - }) - await legacyCellLocked.promise - - let signalCleanup = true - const cleanupDatabase = new TransactionProbeDatabase(database, async (phase, sql) => { - if ( - signalCleanup && - phase === 'after' && - sql.includes('FROM relay_assignments WHERE lease_expires_at') - ) { - signalCleanup = false - cleanupAssignmentsLocked.resolve() - } - }) - const cleanupStore = new RelayAssignmentStore(cleanupDatabase, () => now) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - await expect(cleanupStore.releaseExpiredActivity()).resolves.toBe(0) - await expect(legacyTransaction).resolves.toBeUndefined() - expect(cleanupDatabase.attempts).toBe(1) - expect(warn).not.toHaveBeenCalledWith( - expect.stringContaining('orca_relay_postgres_transaction_retry') - ) - await expect(store.releaseExpiredActivity()).resolves.toBe(1) - }, 15_000) - - it('defers aggregate expiry before waiting on a legacy assignment row', async () => { - const now = 1_700_000_000_000 - const identity = { - userId: 'aggregate-contention-user', - relayHostId: 'aggregatewait01' - } - const cell = { - id: 'aggregate-contention-cell', - url: 'https://aggregate-contention-cell.example.com', - capacityRequests: 100 - } - const store = new RelayAssignmentStore(database, () => now) - await store.reconcileCells([cell]) - await store.assign(identity) - await database.query( - `DELETE FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database.query( - `UPDATE relay_assignments SET lease_expires_at = ? - WHERE user_id = ? AND relay_host_id = ?`, - [now - 1, identity.userId, identity.relayHostId] - ) - - const legacyAssignmentLocked = signal() - const releaseLegacyAssignment = signal() - const legacyTransaction = database.transaction(async (transaction) => { - await transaction.queryLocked( - `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - legacyAssignmentLocked.resolve() - await releaseLegacyAssignment.promise - }) - await legacyAssignmentLocked.promise - - const timedOut = Symbol('timed-out') - const cleanup = store.releaseExpiredActivity() - const result = await Promise.race([ - cleanup, - new Promise((resolve) => { - setTimeout(() => resolve(timedOut), 750) - }) - ]) - releaseLegacyAssignment.resolve() - await legacyTransaction - if (result === timedOut) await cleanup - - expect(result).toBe(0) - await expect(store.releaseExpiredActivity()).resolves.toBe(1) - }, 15_000) - - it('keeps concurrent dormant reassignments capacity-consistent', async () => { - const now = 1_000_000_000_000 - const serializedDatabase = new TransactionProbeDatabase(database, async () => undefined) - const store = new RelayAssignmentStore(serializedDatabase, () => now) - await database.query( - `DELETE FROM relay_assignment_activity_leases WHERE user_id LIKE 'postgres-user-%'` - ) - await database.query(`DELETE FROM relay_assignments WHERE user_id LIKE 'postgres-user-%'`) - await database.query(`DELETE FROM relay_cells WHERE cell_id IN (?, ?, ?)`, [ - 'cell-a', - 'cell-b', - 'cell-c' - ]) - await store.reconcileCells([ - { id: 'cell-a', url: 'https://cell-a.example.com', capacityRequests: 100 }, - { id: 'cell-b', url: 'https://cell-b.example.com', capacityRequests: 100 }, - { id: 'cell-c', url: 'https://cell-c.example.com', capacityRequests: 100 } - ]) - const identities = Array.from({ length: 30 }, (_, index) => ({ - userId: `postgres-user-${index}`, - relayHostId: `postgreshost${String(index).padStart(5, '0')}` - })) - await Promise.all(identities.map(async (identity) => await store.assign(identity))) - - await database.query(`DELETE FROM relay_assignment_activity_leases`) - await database.query( - `UPDATE relay_assignments SET lease_expires_at = ?, last_activity_at = ?, - reserved_controls = 0, reserved_splices = 0, reserved_invites = 0, - pending_installs = 0, pending_confirmations = 0, migration_leases = 0`, - [0, 0] - ) - await database.query(`UPDATE relay_cells SET reserved_requests = 0`) - - await Promise.all(identities.map(async (identity) => await store.assign(identity))) - - const reservations = await database.query( - `SELECT cell_id, reserved_requests FROM relay_cells ORDER BY cell_id` - ) - expect(reservations).toEqual([ - { cell_id: 'cell-a', reserved_requests: '10' }, - { cell_id: 'cell-b', reserved_requests: '10' }, - { cell_id: 'cell-c', reserved_requests: '10' } - ]) - }, 10_000) - }) diff --git a/cloud/apps/relay/src/database/relay-database-rejection-fence.test.ts b/cloud/apps/relay/src/database/relay-database-rejection-fence.test.ts index 435160b504d..f275916aad6 100644 --- a/cloud/apps/relay/src/database/relay-database-rejection-fence.test.ts +++ b/cloud/apps/relay/src/database/relay-database-rejection-fence.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import pg from 'pg' import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest' -import { keepPostgresClientErrorsHandled, PostgresDatabase } from './database.js' +import { PostgresDatabase } from './database.js' import { handleRelayUnhandledRejection } from './relay-database-rejection-fence.js' class FakePoolClient extends EventEmitter { @@ -109,13 +109,3 @@ describe('database rejection fence', () => { }) }) - -describe('permanent PostgreSQL client error listener', () => { - it('leaves every client with a listener for its whole life', () => { - const pool = new EventEmitter() - keepPostgresClientErrorsHandled(pool as never) - const client = new EventEmitter() - pool.emit('connect', client) - expect(() => client.emit('error', new Error('Connection terminated unexpectedly'))).not.toThrow() - }) -}) diff --git a/cloud/apps/relay/src/database/relay-schema-catalog-precheck-postgres.test.ts b/cloud/apps/relay/src/database/relay-schema-catalog-precheck-postgres.test.ts index d58448aef81..143f74e8448 100644 --- a/cloud/apps/relay/src/database/relay-schema-catalog-precheck-postgres.test.ts +++ b/cloud/apps/relay/src/database/relay-schema-catalog-precheck-postgres.test.ts @@ -1,8 +1,7 @@ import pg from 'pg' -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' import { applyPostgresSchema } from '@orca-cloud/postgres-schema/apply-postgres-schema' import { catalogObjectPresence } from '@orca-cloud/postgres-schema/catalog-object-precheck' -import { takesRelationLock } from '@orca-cloud/postgres-schema/schema-lock-target' import { openRelayDatabase, POSTGRES_LOCK_TIMEOUT_MS, @@ -37,7 +36,6 @@ async function onAdmin(operation: (client: pg.Client) => Promise): Promise describePostgres('relay boot-time schema against PostgreSQL', () => { let url = '' let pool: pg.Pool - let sent: string[] const opened: RelayDatabase[] = [] beforeAll(() => { @@ -51,7 +49,6 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { }) // Match boot’s lock timeout so any DDL still queued fails promptly. pool = new pg.Pool({ connectionString: url, max: 1, lock_timeout: POSTGRES_LOCK_TIMEOUT_MS }) - sent = [] }) afterAll(async () => { @@ -59,25 +56,17 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { await onAdmin((client) => client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`)) }) - async function applyRecording(): Promise<{ ran: number; skipped: number }> { - const record = async (statement: string, params: unknown[] = []): Promise => { - sent.push(statement) - return await pool.query(statement, params) - } - return await applyPostgresSchema( + async function applySchema(): Promise { + await applyPostgresSchema( relayPostgresSchemaStatements(), - (statement) => record(statement), - { catalogQuery: async (sql, params) => (await record(sql, params)).rows } + (statement) => pool.query(statement), + { catalogQuery: async (sql, params) => (await pool.query(sql, params)).rows } ) } - function lockTaking(): string[] { - return sent.filter(takesRelationLock) - } - - it('re-adds a constraint an operator dropped, then skips it again', async () => { + it('re-adds a constraint an operator dropped', async () => { // Name-only constraint checks require operators to drop changed definitions before boot recreates them. - await applyRecording() + await applySchema() const named = async (): Promise => Number( ( @@ -94,20 +83,14 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { `ALTER TABLE relay_region_rehome_attempts DROP CONSTRAINT relay_region_rehome_attempts_preferred_region_valid` ) - sent = [] - await applyRecording() - expect(lockTaking()).toHaveLength(1) + await applySchema() expect(await named()).toBe(1) - - sent = [] - await applyRecording() - expect(lockTaking()).toEqual([]) await pool.end() }) it('does not let a same-named index on a sibling table answer for this one', async () => { // Index names are schema-wide; bind name to table or a sibling’s index can permanently suppress the real CREATE. - await applyRecording() + await applySchema() const ask = async (table: string): Promise => ( await catalogObjectPresence( @@ -145,47 +128,6 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { } }) - it('throttles the reservations vacuum, deferring it while a vacuum holds the table', async () => { - const reservationOptions = async (): Promise => - ( - await pool.query(`SELECT reloptions FROM pg_class WHERE oid = to_regclass($1)`, [ - `${schema}.${LOCKED_TABLE}` - ]) - ).rows[0]?.reloptions - const cold = await openRelayDatabase({ databaseUrl: url, dataDir: '' }) - opened.push(cold) - expect(await reservationOptions()).toEqual([ - 'autovacuum_vacuum_cost_delay=20', - 'autovacuum_vacuum_cost_limit=200' - ]) - await pool.query( - `ALTER TABLE ${schema}.${LOCKED_TABLE} - RESET (autovacuum_vacuum_cost_delay, autovacuum_vacuum_cost_limit)` - ) - - // The lock a running (auto)vacuum holds; the boot must yield to it rather than fail. - const holder = new pg.Client({ connectionString: url }) - await holder.connect() - await holder.query('BEGIN') - await holder.query(`LOCK TABLE ${LOCKED_TABLE} IN SHARE UPDATE EXCLUSIVE MODE`) - try { - const behindVacuum = await openRelayDatabase({ databaseUrl: url, dataDir: '' }) - opened.push(behindVacuum) - } finally { - await holder.query('ROLLBACK') - await holder.end() - } - expect(await reservationOptions()).toBeNull() - - const next = await openRelayDatabase({ databaseUrl: url, dataDir: '' }) - opened.push(next) - expect(await reservationOptions()).toEqual([ - 'autovacuum_vacuum_cost_delay=20', - 'autovacuum_vacuum_cost_limit=200' - ]) - await pool.end() - }) - it('defers the activity-lease migrations and still boots while their table is locked', async () => { // Migration DROP must defer behind writers or 28 directors crash-loop on a table written ~475/s. const cold = await openRelayDatabase({ databaseUrl: url, dataDir: '' }) @@ -197,19 +139,14 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { ) await pool.query(`ALTER TABLE ${schema}.relay_assignment_activity_leases RESET (fillfactor)`) - const warned: string[] = [] - const warn = vi.spyOn(console, 'warn').mockImplementation((line: string) => { - warned.push(line) - }) const holder = new pg.Client({ connectionString: url }) await holder.connect() await holder.query('BEGIN') await holder.query( `LOCK TABLE ${schema}.relay_assignment_activity_leases IN ACCESS EXCLUSIVE MODE` ) - let summary: Awaited> try { - summary = await applyPostgresSchema( + await applyPostgresSchema( relayPostgresSchemaStatements(), (statement) => pool.query(statement), { catalogQuery: async (sql, params) => (await pool.query(sql, params)).rows } @@ -217,30 +154,19 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { } finally { await holder.query('ROLLBACK') await holder.end() - warn.mockRestore() } - expect(summary.deferred).toBe(2) - expect(summary.ran).toBeGreaterThan(0) - const deferred = warned - .map((line) => JSON.parse(line) as { event?: string; name?: string }) - .filter((event) => event.event === 'orca_relay_postgres_schema_object_deferred') - expect(deferred.map((event) => event.name)).toEqual([ - 'relay_assignment_activity_expiry', - 'fillfactor=70' - ]) const stillThere = await pool.query( `SELECT 1 FROM pg_indexes WHERE schemaname = $1 AND indexname = $2`, [schema, 'relay_assignment_activity_expiry'] ) expect(stillThere.rowCount).toBe(1) - const retry = await applyPostgresSchema( + await applyPostgresSchema( relayPostgresSchemaStatements(), (statement) => pool.query(statement), { catalogQuery: async (sql, params) => (await pool.query(sql, params)).rows } ) - expect(retry.deferred).toBe(0) const gone = await pool.query( `SELECT 1 FROM pg_indexes WHERE schemaname = $1 AND indexname = $2`, [schema, 'relay_assignment_activity_expiry'] @@ -254,27 +180,5 @@ describePostgres('relay boot-time schema against PostgreSQL', () => { await pool.end() }) - it('fails that same boot with 55P03 when the pre-check is not wired in', async () => { - // Keeps the test above from passing vacuously: the lock really does block relay's DDL. - const cold = await openRelayDatabase({ databaseUrl: url, dataDir: '' }) - opened.push(cold) - const holder = new pg.Client({ connectionString: url }) - await holder.connect() - await holder.query('BEGIN') - await holder.query(`LOCK TABLE ${LOCKED_TABLE} IN ACCESS EXCLUSIVE MODE`) - try { - await expect( - applyPostgresSchema( - relayPostgresSchemaStatements(), - (statement) => pool.query(statement), - { retryDeadlineMs: 0 } - ) - ).rejects.toMatchObject({ code: '55P03' }) - } finally { - await holder.query('ROLLBACK') - await holder.end() - await pool.end() - } - }) }) diff --git a/cloud/apps/relay/src/database/sqlite-transaction-queue.test.ts b/cloud/apps/relay/src/database/sqlite-transaction-queue.test.ts index 99fb311ae25..69c112146ac 100644 --- a/cloud/apps/relay/src/database/sqlite-transaction-queue.test.ts +++ b/cloud/apps/relay/src/database/sqlite-transaction-queue.test.ts @@ -2,7 +2,6 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { DatabaseSync } from 'node:sqlite' -import { setImmediate } from 'node:timers/promises' import { expect, it, vi } from 'vitest' import { openRelayDatabase } from './database.js' @@ -24,38 +23,13 @@ it('releases queued work and close after a SQLite transaction cannot acquire its await database.query('CREATE TABLE queue_progress (value INTEGER)') await database.query('INSERT INTO queue_progress VALUES (0)') blocker.exec('BEGIN IMMEDIATE') - const operation = vi.fn(async () => undefined) - await expect(database.transaction(operation)).rejects.toThrow('database is locked') - let lockFailures = 0 - const blocked = Array.from({ length: 5 }, () => - database.transaction(operation).catch(() => { - lockFailures += 1 - }) - ) - await setImmediate() - expect(lockFailures).toBe(5) - await Promise.all(blocked) - expect(operation).not.toHaveBeenCalled() + await expect(database.transaction(async () => undefined)).rejects.toThrow('database is locked') blocker.exec('ROLLBACK') - let completed = 0 - const pending = Array.from({ length: 100 }, () => - database.transaction(async (transaction) => { - await transaction.query('UPDATE queue_progress SET value = value + 1') - completed += 1 - }) - ) - for (const request of pending) void request.catch(() => undefined) - await setImmediate() - expect(completed).toBe(100) - await Promise.all(pending) - expect(await database.query('SELECT value FROM queue_progress')).toEqual([{ value: 100 }]) - let closed = false - const closing = database.close().then(() => { - closed = true + await database.transaction(async (transaction) => { + await transaction.query('UPDATE queue_progress SET value = value + 1') }) - await setImmediate() - expect(closed).toBe(true) - await closing + expect(await database.query('SELECT value FROM queue_progress')).toEqual([{ value: 1 }]) + await database.close() } finally { capture.mockRestore() blocker.close() @@ -83,13 +57,7 @@ it('does not roll back a transaction when BEGIN failed before taking ownership', await expect(database.transaction(async () => undefined)).rejects.toThrow( 'cannot start a transaction within a transaction' ) - expect(connection?.isTransaction).toBe(true) - let rows: unknown - void database.query('SELECT value FROM queue_owner').then((result) => { - rows = result - }) - await setImmediate() - expect(rows).toEqual([{ value: 7 }]) + expect(await database.query('SELECT value FROM queue_owner')).toEqual([{ value: 7 }]) await database.query('ROLLBACK') expect(await database.query('SELECT value FROM queue_owner')).toEqual([]) await database.close() diff --git a/cloud/apps/relay/src/edge-relay-fence.test.ts b/cloud/apps/relay/src/edge-relay-fence.test.ts deleted file mode 100644 index 7033840a2b1..00000000000 --- a/cloud/apps/relay/src/edge-relay-fence.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { openInMemoryRelayDatabase, type RelayDatabase } from './database/database.js' -import type { EdgeAdmin, EdgeAdminCallOptions, EdgeAssignBody, EdgeAssignResult } from './edge-admin-client.js' -import { EDGE_FENCE_RETRY_BASE_MS, retryPendingFences } from './edge-relay-fence.js' -import { EDGE_CELL_ID, EdgeAssignments, type EdgeRelayConfig } from './edge-relay.js' - -const EDGE_URL = 'https://edge.relay.example.test' -const USER = 'user-1' -const HOST = 'fencehost0000001' -const T0 = 1_700_000_000_000 - -const databases: RelayDatabase[] = [] -afterEach(async () => { - vi.useRealTimers() - vi.restoreAllMocks() - for (const database of databases.splice(0)) { await database.close() } -}) - -class ScriptedEdge implements EdgeAdmin { - answers: EdgeAssignResult['outcome'][] = [] - calls: { body: EdgeAssignBody; options?: EdgeAdminCallOptions }[] = [] - - async assign(body: EdgeAssignBody, options?: EdgeAdminCallOptions): Promise { - this.calls.push({ body, ...(options ? { options } : {}) }) - const outcome = this.answers.shift() ?? 'applied' - return { outcome, assignmentEpoch: outcome === 'stale' ? body.assignmentEpoch + 5 : body.assignmentEpoch } - } - - async exportHost(): Promise { - throw new Error('unexpected export') - } - - async drain(): Promise { - throw new Error('unexpected drain') - } -} - -function edgeConfig(): EdgeRelayConfig { - return { - cellUrl: EDGE_URL, - rolloutPercent: 100, - allowHosts: new Set(), - denyHosts: new Set(), - regions: new Set(['us-central1']) - } -} - -async function harness() { - const database = await openInMemoryRelayDatabase() - databases.push(database) - const edge = new ScriptedEdge() - const clock = { now: T0 } - const assignments = new EdgeAssignments(database, edgeConfig(), () => clock.now, edge) - await assignments.ensureEdgeCell() - const placeRow = async (cellId: string, epoch: number, relayHostId = HOST) => - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, last_activity_at, - reserved_controls, reserved_splices, reserved_invites, pending_installs, - pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, 0, 0, 0, 0, 0, 0, 0, 0) - ON CONFLICT (user_id, relay_host_id) DO UPDATE SET cell_id = excluded.cell_id, - assignment_epoch = excluded.assignment_epoch`, - [USER, relayHostId, cellId, epoch] - ) - const pending = async () => - (await database.query(`SELECT * FROM relay_edge_fence_pending ORDER BY relay_host_id`)).map((row) => ({ - relayHostId: String(row.relay_host_id), - cellId: String(row.cell_id), - assignmentEpoch: Number(row.assignment_epoch), - attempts: Number(row.attempts), - nextAttemptAt: Number(row.next_attempt_at) - })) - const retry = async () => await retryPendingFences(database, edge, EDGE_CELL_ID, () => clock.now) - return { database, edge, clock, assignments, placeRow, pending, retry } -} - -function logged(spy: { mock: { calls: unknown[][] } }, event: string): Record[] { - return spy.mock.calls - .map(([line]) => JSON.parse(String(line)) as Record) - .filter((entry) => entry.event === event) -} - -describe('relay edge pending fence retries', () => { - it('re-fences to the current row, not the recorded one, and clears the record once it lands', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const h = await harness() - h.edge.answers = ['stale'] - await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9) - // The host moved again before the retry. - await h.placeRow('us-c2', 11) - h.edge.calls = [] - expect(await h.retry()).toBe(true) - expect(h.edge.calls).toEqual([]) - h.clock.now += EDGE_FENCE_RETRY_BASE_MS - expect(await h.retry()).toBe(false) - expect(h.edge.calls).toEqual([{ body: { userId: USER, relayHostId: HOST, cellId: 'us-c2', assignmentEpoch: 11 } }]) - expect(await h.pending()).toEqual([]) - expect(logged(warn, 'orca_relay_edge_fence_retried')).toEqual([ - { event: 'orca_relay_edge_fence_retried', outcome: 'applied', cellId: 'us-c2', assignmentEpoch: 11, attempts: 1 } - ]) - }) - - it('lets only one director claim an attempt', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const h = await harness() - await h.placeRow('us-c1', 9) - h.edge.answers = ['stale'] - await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9) - h.clock.now += EDGE_FENCE_RETRY_BASE_MS - h.edge.calls = [] - await Promise.all([h.retry(), h.retry()]) - expect(h.edge.calls).toHaveLength(1) - }) -}) diff --git a/cloud/apps/relay/src/edge-relay-invite-ws.test.ts b/cloud/apps/relay/src/edge-relay-invite-ws.test.ts deleted file mode 100644 index 98ac1d84675..00000000000 --- a/cloud/apps/relay/src/edge-relay-invite-ws.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { WebSocket } from 'ws' -import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract/close-codes' -import { loadRelayConfig } from './config.js' -import type { RelayDatabase } from './database/database.js' -import { EDGE_CELL_ID, EdgeAssignments } from './edge-relay.js' -import { createRelayServer } from './relay-server.js' - -const EDGE_URL = 'https://edge.relay.example.test' -const HOST = 'abcdefghijklmnop' -// A 43-character base64url credential is the shortest value RelayAuthSchema accepts. -const CREDENTIAL = 'abcdefghijklmnopqrstuvwxyzABCDEFGH012345678' - -const cleanups: (() => Promise | void)[] = [] -afterEach(async () => { - const pending = cleanups.splice(0) - for (let index = pending.length - 1; index >= 0; index -= 1) { await pending[index]!() } - vi.restoreAllMocks() -}) - -async function director() { - const database: RelayDatabase = { - query: vi.fn(async () => []), - queryLocked: vi.fn(async () => []), - transaction: (operation) => operation(database), - close: async () => {} - } - const config = loadRelayConfig({ - ORCA_RELAY_PUBLIC_URL: 'http://127.0.0.1', - ORCA_RELAY_CELL_URL: 'http://127.0.0.1', - ORCA_RELAY_AUTH_ISSUER: 'https://auth.example.test', - ORCA_RELAY_JWKS_URL: 'https://auth.example.test/jwks', - ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: 'synthetic-assignment-key-for-test-only', - ORCA_RELAY_ROLE: 'director', - ORCA_RELAY_ADMIN_AUDIENCE: 'https://auth.example.test/admin', - ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.test', - ORCA_RELAY_CELLS_JSON: JSON.stringify([ - { id: 'cell-1', url: 'https://cell-1.example.test', capacityRequests: 900 } - ]), - ORCA_RELAY_EDGE_CELL_URL: EDGE_URL, - ORCA_RELAY_EDGE_ADMIN_SIGNING_KEY: 'edge-admin-key-with-at-least-32-bytes!!' - }) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const relay = createRelayServer(config, database) - await new Promise((resolve) => relay.server.listen(0, '127.0.0.1', resolve)) - cleanups.push(() => new Promise((resolve) => relay.server.close(() => resolve()))) - const address = relay.server.address() - if (!address || typeof address === 'string') { throw new Error('missing test port') } - return { relay, port: address.port } -} - -// A phone's invite socket on the director: answers relay-moved, then closes DRAINING. -async function inviteMove(port: number): Promise<{ messages: unknown[]; code: number }> { - const socket = new WebSocket(`ws://127.0.0.1:${port}/v1/connect/${HOST}`) - cleanups.push(() => socket.terminate()) - const messages: unknown[] = [] - socket.on('message', (data) => messages.push(JSON.parse(String(data)))) - socket.once('open', () => - socket.send(JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: CREDENTIAL })) - ) - const code = await new Promise((resolve) => socket.once('close', (closeCode) => resolve(closeCode))) - return { messages, code } -} - -it('moves an invite of a host on the relay edge to the edge, never asking the cell paths', async () => { - const { relay, port } = await director() - const identity = { userId: 'user-1', relayHostId: HOST } - vi.spyOn(relay.store, 'resolveInviteForMove').mockResolvedValue({ ...identity, relayDeviceId: 'device-1' }) - const onEdge = vi.spyOn(EdgeAssignments.prototype, 'edgeAssignment').mockResolvedValue({ - ...identity, - cellId: EDGE_CELL_ID, - cellUrl: EDGE_URL, - assignmentEpoch: 7, - leaseExpiresAt: Date.now() + 60_000 - }) - const resolve = vi.spyOn(relay.assignments, 'resolve') - const assign = vi.spyOn(relay.assignments, 'assign') - const { messages, code } = await inviteMove(port) - expect(onEdge).toHaveBeenCalledWith(identity) - expect(messages).toEqual([{ type: 'relay-moved', v: 1, cellUrl: EDGE_URL, assignmentEpoch: 7 }]) - expect(code).toBe(RELAY_CLOSE_CODE.DRAINING) - expect(resolve).not.toHaveBeenCalled() - expect(assign).not.toHaveBeenCalled() -}) diff --git a/cloud/apps/relay/src/edge-relay-phase2.test.ts b/cloud/apps/relay/src/edge-relay-phase2.test.ts index d4148ed4002..581c31c65e1 100644 --- a/cloud/apps/relay/src/edge-relay-phase2.test.ts +++ b/cloud/apps/relay/src/edge-relay-phase2.test.ts @@ -7,7 +7,7 @@ import { type EdgeAssignBody, type EdgeDeviceRow } from './edge-admin-client.js' -import { EDGE_CELL_ID, EDGE_EXPORT_SKIP_AFTER_MS, EdgeAssignments, type EdgeRelayConfig } from './edge-relay.js' +import { EDGE_CELL_ID, EdgeAssignments, type EdgeRelayConfig } from './edge-relay.js' import type { EdgeControlFlags } from './edge-relay-control.js' const fakes = vi.hoisted(() => ({ @@ -85,12 +85,9 @@ class FakeEdge implements EdgeAdmin { devices: EdgeDeviceRow[] = [] connected = false down = false - pushes: EdgeAssignBody[] = [] - exports = 0 async assign(body: EdgeAssignBody) { if (this.down) { throw new EdgeAdminUnavailableError('network') } - this.pushes.push(body) const current = this.assignment if (current && body.assignmentEpoch < current.assignmentEpoch) { return { outcome: 'stale' as const, assignmentEpoch: current.assignmentEpoch } @@ -107,7 +104,6 @@ class FakeEdge implements EdgeAdmin { async exportHost() { if (this.down) { throw new EdgeAdminUnavailableError('network') } - this.exports += 1 if (this.connected) { return { outcome: 'busy' as const } } return { outcome: 'exported' as const, assignment: this.assignment, devices: this.devices } } @@ -201,11 +197,10 @@ describe('relay edge phase 2: the director moves host data with the host', () => expect(await h.row()).toBeUndefined() }) - it('503s a leaving host while the edge export is unavailable, until it has failed for 120 s', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + it('503s a leaving host until the configured export failure window expires', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) vi.spyOn(console, 'error').mockImplementation(() => {}) - const skipped = () => warn.mock.calls.filter(([line]) => String(line).includes('orca_relay_edge_export_skipped')) - const h = await harness() + const h = await harness('host', { exportSkipAfterMs: 120_000 }) await h.insertDevice(device('phone-a')) await h.assign() // On the edge phone-a was revoked; the edge then goes down. @@ -213,25 +208,16 @@ describe('relay edge phase 2: the director moves host data with the host', () => h.fake.down = true h.leaveCohort() expect((await h.assign()).status).toBe(503) - await keepFailing(h, EDGE_EXPORT_SKIP_AFTER_MS - 1) + await keepFailing(h, 119_999) const early = await h.assign() expect(early.status).toBe(503) expect(early.headers.get('retry-after')).toBe('2') - expect(h.assignments.assign).not.toHaveBeenCalled() - expect(skipped()).toHaveLength(0) h.clock.now += 1 const response = await h.assign() expect(response.status).toBe(200) expect(await response.json()).toMatchObject({ cellUrl: 'https://us-c1.relay.example.test', assignmentEpoch: 9 }) // The edge's revoke is unknown here: the host's Postgres devices are removed, never resurrected. expect(await h.postgresDevices()).toEqual([]) - expect(skipped()).toHaveLength(1) - expect(JSON.parse(String(skipped()[0]![0]))).toEqual({ - event: 'orca_relay_edge_export_skipped', - reason: 'relay_edge_admin_unavailable:network', - failingForMs: EDGE_EXPORT_SKIP_AFTER_MS, - devicesRemoved: 1 - }) }) it('keeps Postgres devices when the edge object holds no assignment (never pushed or erased)', async () => { @@ -252,12 +238,11 @@ describe('relay edge phase 2: the director moves host data with the host', () => h.fake.devices = [device('phone-x', { relay_host_id: 'someotherhost001' })] h.leaveCohort() expect((await h.assign()).status).toBe(500) - expect(h.assignments.assign).not.toHaveBeenCalled() expect(await h.postgresDevices()).toEqual([{ id: 'phone-a', revoked: null }]) }) - it('with mode down, skips the export at once, removes the Postgres devices, and fences once', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + it('with mode down, removes Postgres devices and records a failed fence', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) vi.spyOn(console, 'error').mockImplementation(() => {}) const flags: EdgeControlFlags = { mode: 'on' } const h = await harness('host', { control: () => flags }) @@ -268,18 +253,10 @@ describe('relay edge phase 2: the director moves host data with the host', () => h.fake.devices = [device('phone-a', { revoked_at: 1_800_000_000_000 })] h.fake.down = true flags.mode = 'down' - const assign = vi.spyOn(h.fake, 'assign') const response = await h.assign() expect(response.status).toBe(200) expect(await response.json()).toMatchObject({ cellUrl: 'https://us-c1.relay.example.test', assignmentEpoch: 9 }) - expect(h.fake.exports).toBe(0) expect(await h.postgresDevices()).toEqual([]) - const skipped = warn.mock.calls - .map(([line]) => JSON.parse(String(line)) as Record) - .filter((line) => line.event === 'orca_relay_edge_export_skipped') - expect(skipped).toEqual([{ event: 'orca_relay_edge_export_skipped', reason: 'mode_down', devicesRemoved: 2 }]) - // One fence try, recorded for the sweep to retry. - expect(assign).toHaveBeenCalledTimes(1) const pending = await h.database.query(`SELECT cell_id, assignment_epoch FROM relay_edge_fence_pending`) expect(pending.map((row) => [String(row.cell_id), Number(row.assignment_epoch)])).toEqual([['us-c1', 9]]) }) diff --git a/cloud/apps/relay/src/edge-relay-postgres.test.ts b/cloud/apps/relay/src/edge-relay-postgres.test.ts index bfffacf8191..534f955046b 100644 --- a/cloud/apps/relay/src/edge-relay-postgres.test.ts +++ b/cloud/apps/relay/src/edge-relay-postgres.test.ts @@ -140,11 +140,9 @@ describePostgres('relay edge on PostgreSQL', () => { current_expires_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, [host.userId, host.relayHostId, 'phone-a', 'hash-phone-a', 2, 1_900_000_000_000, 1_800_000_000_000] ) - const pushed: unknown[] = [] let held: EdgeDeviceRow[] = [] const admin = { assign: async (body: EdgeAssignBody) => { - pushed.push(body) if (body.devices) { held = body.devices } return { outcome: 'applied' as const, assignmentEpoch: body.assignmentEpoch } }, diff --git a/cloud/apps/relay/src/host-whereabouts-app.test.ts b/cloud/apps/relay/src/host-whereabouts-app.test.ts index 812671b0621..e8072835260 100644 --- a/cloud/apps/relay/src/host-whereabouts-app.test.ts +++ b/cloud/apps/relay/src/host-whereabouts-app.test.ts @@ -10,8 +10,6 @@ vi.mock('./authentication/admin-token-verifier.js', async (importOriginal) => { const actual = await importOriginal() const identities = new Map[0]>([ ['deploy-token', 'deploy'], - ['monitor-token', 'monitor'], - ['fence-token', 'fence'], ['capacity-token', 'capacity'] ]) return { @@ -111,22 +109,8 @@ describe('POST /v1/admin/host-whereabouts', () => { expect( (await app.request('/v1/admin/host-whereabouts', request({ ...body, extra: 1 }))).status ).toBe(400) - expect(lookup).not.toHaveBeenCalled() }) - it('lets the monitor and fence accounts read it, and not the capacity account', async () => { - const app = appWith(async () => ROW) - const body = { v: 1, relayHostId: HOST, userId: 'user-a' } - for (const token of ['deploy-token', 'monitor-token', 'fence-token']) { - const response = await app.request('/v1/admin/host-whereabouts', request(body, token)) - expect(response.status).toBe(200) - } - const capacity = await app.request( - '/v1/admin/host-whereabouts', - request(body, 'capacity-token') - ) - expect(capacity.status).toBe(401) - }) it('names the user from the map when the request has only a host id', async () => { const lookup = vi.fn(async () => ROW) @@ -137,7 +121,6 @@ describe('POST /v1/admin/host-whereabouts', () => { request({ v: 1, relayHostId: HOST }) ) - expect(lookup).toHaveBeenCalledWith({ userId: 'user-a', relayHostId: HOST }) expect(await response.json()).toMatchObject({ users: [{ userId: 'user-a', database: ROW }] }) }) @@ -176,13 +159,7 @@ describe('RelayAssignmentStore.hostWhereabouts', () => { const identity = { userId: 'user-a', relayHostId: HOST } expect(await store.hostWhereabouts(identity)).toBeNull() - const assigned = await store.assign(identity) - expect(await store.hostWhereabouts(identity)).toEqual({ - cellId: assigned.cellId, - assignmentEpoch: assigned.assignmentEpoch, - leaseExpiresAt: assigned.leaseExpiresAt, - openMigration: null - }) + await store.assign(identity) await database.query( `INSERT INTO relay_assignment_migrations diff --git a/cloud/apps/relay/src/process-lifecycle/relay-readiness.test.ts b/cloud/apps/relay/src/process-lifecycle/relay-readiness.test.ts index 876e57f54af..7e1cd71c5ec 100644 --- a/cloud/apps/relay/src/process-lifecycle/relay-readiness.test.ts +++ b/cloud/apps/relay/src/process-lifecycle/relay-readiness.test.ts @@ -1,12 +1,6 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import type { RelayDatabase } from '../database/database.js' -import { - createRelayReadiness, - RELAY_READINESS_JWKS_GRACE_MS, - RELAY_READINESS_SQL_GRACE_MS, - type RelayReadinessGraceEvent, - type RelayReadinessObservation -} from './relay-readiness.js' +import { createRelayReadiness } from './relay-readiness.js' function database(query: () => Promise[]>): RelayDatabase { return { @@ -17,88 +11,35 @@ function database(query: () => Promise[]>): RelayDatabas } } -describe('relay readiness', () => { - it.each([ - { - name: 'JWKS HTTP failure', - fetch: vi.fn(async () => new Response('', { status: 503 })) as typeof fetch, - query: vi.fn(async () => [{ ready: 1 }]), - failure: 'jwks_http_failed' - }, - { - name: 'JWKS timeout', - fetch: vi.fn(async () => { - throw new DOMException('redacted', 'TimeoutError') - }) as typeof fetch, - query: vi.fn(async () => [{ ready: 1 }]), - failure: 'jwks_timed_out' - }, - { - name: 'JWKS fetch failure', - fetch: vi.fn(async () => { - throw new Error('redacted') - }) as typeof fetch, - query: vi.fn(async () => [{ ready: 1 }]), - failure: 'jwks_fetch_failed' - }, - { - name: 'SQL failure', - fetch: vi.fn(async () => new Response('{}', { status: 200 })) as typeof fetch, - query: vi.fn(async () => { - throw new Error('redacted') - }), - failure: 'sql_failed' - } - ])('reports a safe reason for $name', async ({ fetch, query, failure }) => { - const observations: RelayReadinessObservation[] = [] - const readiness = createRelayReadiness(database(query), 'https://jwks', { - fetch, - cacheMs: 0, - observe: (observation) => observations.push(observation) - }) - - expect(await readiness.check()).toBe(false) - expect(observations).toEqual([expect.objectContaining({ ready: false, failure })]) - expect(JSON.stringify(observations)).not.toContain('redacted') - expect(query).toHaveBeenCalledTimes(1) - }) - -}) - describe('relay readiness last-known-good grace', () => { function graceProbe(input: { jwksGraceMs?: number sqlGraceMs?: number - cacheMs?: number jwksOk: () => boolean sqlOk: () => boolean now: () => number }) { - const observations: RelayReadinessObservation[] = [] - const graceEvents: RelayReadinessGraceEvent[] = [] - const query = vi.fn(async () => { + const query = async () => { if (!input.sqlOk()) throw new Error('redacted') return [{ ready: 1 }] - }) - const fetchImpl = vi.fn( - async () => new Response('{}', { status: input.jwksOk() ? 200 : 503 }) - ) as typeof fetch + } + const fetchImpl: typeof fetch = async () => + new Response('{}', { status: input.jwksOk() ? 200 : 503 }) const readiness = createRelayReadiness(database(query), 'https://jwks', { fetch: fetchImpl, - cacheMs: input.cacheMs ?? 0, + cacheMs: 0, ...(input.jwksGraceMs === undefined ? {} : { jwksGraceMs: input.jwksGraceMs }), ...(input.sqlGraceMs === undefined ? {} : { sqlGraceMs: input.sqlGraceMs }), - now: input.now, - observe: (observation) => observations.push(observation), - observeGrace: (event) => graceEvents.push(event) + now: input.now }) - return { readiness, observations, graceEvents, query, fetchImpl } + return readiness } - it('stays ready while a JWKS failure sits inside the default fifteen minute window', async () => { + it('drops readiness once the configured JWKS window expires', async () => { let now = 1_000 let jwksOk = true - const { readiness, observations } = graceProbe({ + const readiness = graceProbe({ + jwksGraceMs: 10_000, jwksOk: () => jwksOk, sqlOk: () => true, now: () => now @@ -106,68 +47,14 @@ describe('relay readiness last-known-good grace', () => { expect(await readiness.check()).toBe(true) jwksOk = false - now += RELAY_READINESS_JWKS_GRACE_MS - 1 - expect(await readiness.check()).toBe(true) - expect(readiness.degradedDependencies()).toEqual(['jwks']) - expect(observations.at(-1)).toEqual( - expect.objectContaining({ - ready: true, - degraded: true, - degradedDependencies: ['jwks'], - failure: 'jwks_http_failed' - }) - ) - }) - - it('drops readiness once the JWKS window expires', async () => { - let now = 1_000 - let jwksOk = true - const { readiness, observations } = graceProbe({ - jwksOk: () => jwksOk, - sqlOk: () => true, - now: () => now - }) - - expect(await readiness.check()).toBe(true) - jwksOk = false - now += RELAY_READINESS_JWKS_GRACE_MS + now += 10_000 expect(await readiness.check()).toBe(false) expect(readiness.degradedDependencies()).toEqual([]) - expect(observations.at(-1)).toEqual( - expect.objectContaining({ ready: false, failure: 'jwks_http_failed' }) - ) - expect(observations.at(-1)).not.toHaveProperty('degraded') - }) - - it('gives SQL a shorter window than JWKS by default', async () => { - let now = 1_000 - let sqlOk = true - const { readiness, observations } = graceProbe({ - jwksOk: () => true, - sqlOk: () => sqlOk, - now: () => now - }) - - expect(await readiness.check()).toBe(true) - sqlOk = false - now += RELAY_READINESS_SQL_GRACE_MS - 1 - expect(await readiness.check()).toBe(true) - expect(observations.at(-1)).toEqual( - expect.objectContaining({ - ready: true, - degraded: true, - degradedDependencies: ['sql'], - failure: 'sql_failed' - }) - ) - now += 1 - expect(await readiness.check()).toBe(false) - expect(RELAY_READINESS_SQL_GRACE_MS).toBeLessThan(RELAY_READINESS_JWKS_GRACE_MS) }) it('keeps a process that never succeeded out of the grace window', async () => { let now = 1_000 - const { readiness, observations, graceEvents } = graceProbe({ + const readiness = graceProbe({ jwksOk: () => false, sqlOk: () => true, now: () => now @@ -176,14 +63,12 @@ describe('relay readiness last-known-good grace', () => { expect(await readiness.check()).toBe(false) now += 1_000 expect(await readiness.check()).toBe(false) - expect(graceEvents).toEqual([]) - expect(observations.every((observation) => observation.degraded === undefined)).toBe(true) }) it('restarts the grace window from the most recent success', async () => { let now = 1_000 let jwksOk = true - const { readiness } = graceProbe({ + const readiness = graceProbe({ jwksGraceMs: 10_000, jwksOk: () => jwksOk, sqlOk: () => true, @@ -205,7 +90,7 @@ describe('relay readiness last-known-good grace', () => { it('never serves grace when the window is disabled', async () => { let now = 1_000 let jwksOk = true - const { readiness, graceEvents } = graceProbe({ + const readiness = graceProbe({ jwksGraceMs: 0, jwksOk: () => jwksOk, sqlOk: () => true, @@ -215,37 +100,13 @@ describe('relay readiness last-known-good grace', () => { expect(await readiness.check()).toBe(true) jwksOk = false expect(await readiness.check()).toBe(false) - expect(graceEvents).toEqual([]) }) - it('keeps one clock per dependency so a healthy JWKS cannot hold SQL open', async () => { - let now = 1_000 - let sqlOk = true - const { readiness, graceEvents } = graceProbe({ - sqlGraceMs: 10_000, - jwksOk: () => true, - sqlOk: () => sqlOk, - now: () => now - }) - - expect(await readiness.check()).toBe(true) - sqlOk = false - for (let elapsed = 1_000; elapsed <= 11_000; elapsed += 1_000) { - now = 1_000 + elapsed - await readiness.check() - } - expect(await readiness.check()).toBe(false) - expect(graceEvents.map((event) => [event.dependency, event.grace])).toEqual([ - ['sql', 'entered'], - ['sql', 'expired'] - ]) - }) - - it('probes SQL on every poll even while JWKS is failing', async () => { + it('expires SQL grace despite continuing JWKS failures', async () => { let now = 1_000 let jwksOk = true let sqlOk = true - const { readiness, observations, query } = graceProbe({ + const readiness = graceProbe({ sqlGraceMs: 10_000, jwksOk: () => jwksOk, sqlOk: () => sqlOk, @@ -259,18 +120,9 @@ describe('relay readiness last-known-good grace', () => { sqlOk = false now += 1_000 expect(await readiness.check()).toBe(true) - expect(observations.at(-1)).toEqual( - expect.objectContaining({ - ready: true, - failure: 'jwks_http_failed', - failures: ['jwks_http_failed', 'sql_failed'], - degradedDependencies: ['jwks', 'sql'] - }) - ) // The SQL clock runs on evidence, so its window opens at the poll that saw SQL fail. now += 10_000 expect(await readiness.check()).toBe(false) - expect(query).toHaveBeenCalledTimes(4) }) }) diff --git a/cloud/apps/relay/src/relay-region-app.test.ts b/cloud/apps/relay/src/relay-region-app.test.ts index 0c147348bb3..1bb2dcd5051 100644 --- a/cloud/apps/relay/src/relay-region-app.test.ts +++ b/cloud/apps/relay/src/relay-region-app.test.ts @@ -14,122 +14,6 @@ import { createRelayApp } from './app.js' describe('Relay region API', () => { - it('preserves the cold-start hint and binds a negotiated window after placement', async () => { - const assignment = { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop', - cellId: 'asia-c1', - cellUrl: 'https://asia-c1.relay.example.test', - region: 'asia-east2', - assignmentEpoch: 7, - leaseExpiresAt: Date.now() + 300_000 - } - const assign = vi.fn(async () => assignment) - const window = { - generation: 2, - expiresAt: Date.now() + 86_400_000, - assignmentEpoch: 7, - incumbentRegion: 'asia-east2', - policyVersion: 1 - } - const exchangeRegionCorrection = vi.fn(async () => ({ v: 1, window })) - const app = createRelayApp(config(), { - store: {} as never, - assignments: { assign, exchangeRegionCorrection } as never, - drain: vi.fn(), - ready: async () => true - }) - const regionCorrection = { v: 1, action: 'issue-window' } - const response = await app.request( - '/v1/assign', - assignmentRequest('abcdefghijklmnop', { - preferredRegion: 'asia-east2', - regionCorrection - }) - ) - expect(response.status).toBe(200) - expect(assign).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, - 'asia-east2', - 'asia-east2', - undefined, - { hostRequested: true } - ) - expect(exchangeRegionCorrection).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, - regionCorrection, - 7 - ) - expect(((await response.json()) as { regionCorrection: unknown }).regionCorrection).toEqual({ - v: 1, - window - }) - }) - - it('gives a window request the in-region reserve fallback, and never a report', async () => { - const assignment = { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop', - cellId: 'asia-c1', - cellUrl: 'https://asia-c1.relay.example.test', - region: 'asia-east2', - assignmentEpoch: 7, - leaseExpiresAt: Date.now() + 300_000 - } - const assign = vi.fn(async () => assignment) - const regionReserve = vi.fn(async () => null) - const reserveSpill = vi.fn(async () => null) - const plan = vi.fn(async () => ({ kind: 'database', regionReserve, reserveSpill })) - const app = createRelayApp(config(), { - store: {} as never, - assignments: { - assign, - resolve: async () => assignment, - exchangeRegionCorrection: async () => ({ v: 1, reportStatus: 'accepted' }) - } as never, - reservePlacement: { plan } as never, - drain: vi.fn(), - ready: async () => true - }) - const response = await app.request( - '/v1/assign', - assignmentRequest('abcdefghijklmnop', { - reconnect: true, - preferredRegion: 'asia-east2', - regionCorrection: { v: 1, action: 'issue-window' } - }) - ) - expect(response.status).toBe(200) - expect(plan).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, - { reconnect: true, region: 'asia-east2', regionCorrection: true, preferred: true } - ) - expect(assign).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, - 'asia-east2', - 'asia-east2', - undefined, - { regionReserve, reserveSpill, hostRequested: true } - ) - plan.mockClear() - const report = await app.request( - '/v1/assign', - assignmentRequest('abcdefghijklmnop', { - regionCorrection: { - v: 1, - action: 'report', - generation: 2, - assignmentEpoch: 7, - policyVersion: 1, - outcome: 'inconclusive', - reason: 'timeout' - } - }) - ) - expect(report.status).toBe(200) - expect(plan).not.toHaveBeenCalled() - }) - it('returns successful placement when optional window storage is unavailable', async () => { const app = createRelayApp(config(), { store: {} as never, @@ -234,34 +118,6 @@ describe('Relay region API', () => { expect(exchangeRegionCorrection).not.toHaveBeenCalled() }) - it('exposes only the store-provided healthy catalog from directors', async () => { - const regionCatalog = vi.fn(async () => [ - { region: 'us-central1' as const, probeOrigins: ['https://us.relay.example.test'] } - ]) - const app = createRelayApp(config(), { - store: {} as never, - assignments: { regionCatalog } as never, - drain: vi.fn(), - ready: vi.fn(async () => true) - }) - - const response = await app.request('/v1/regions') - - expect(response.status).toBe(200) - expect(await response.json()).toEqual({ - v: 1, - regions: [ - { region: 'us-central1', probeOrigins: ['https://us.relay.example.test'] } - ] - }) - - const burst = await Promise.all( - Array.from({ length: 50 }, () => app.request('/v1/regions')) - ) - expect(burst.every(({ status }) => status === 200)).toBe(true) - expect(regionCatalog).toHaveBeenCalledOnce() - }) - it('answers a pool that cannot hand out a client with a retryable 503', async () => { const regionCatalog = vi.fn(async () => { throw new Error('Connection terminated due to connection timeout') diff --git a/cloud/apps/relay/src/relay-region-selection-app.test.ts b/cloud/apps/relay/src/relay-region-selection-app.test.ts deleted file mode 100644 index dcfaf61949b..00000000000 --- a/cloud/apps/relay/src/relay-region-selection-app.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it, vi, type Mock } from 'vitest' -import type { RelayConfig } from './config.js' - -const fakes = vi.hoisted(() => ({ - verifyRelayToken: vi.fn(async (token: string) => ({ sub: 'user-1', relayHostId: token })) -})) - -vi.mock('./authentication/relay-token-verifier.js', () => ({ - createRelayTokenVerifier: () => fakes.verifyRelayToken, - readBearer: (value: string | undefined) => value?.replace(/^Bearer /, '') ?? null -})) - -import { createRelayApp } from './app.js' - -const HOST = 'selecthost000001' - -function usAssignment(extra: Record = {}) { - return { - userId: 'user-1', - relayHostId: HOST, - cellId: 'us-c1', - cellUrl: 'https://us-c1.relay.example.test', - region: 'us-central1' as const, - assignmentEpoch: 3, - leaseExpiresAt: Date.now() + 300_000, - ...extra - } -} - -describe('Relay region selection counters', () => { - - it('never counts a rehome as a fallback, and gives a rehomed new session no region window', async () => { - const recordRegionSelection = vi.fn() - const exchangeRegionCorrection = vi.fn() - const plan = vi.fn(async () => ({ - kind: 'answer', - lane: 'rehome', - assignment: usAssignment({ cellId: 'asia-c1', region: 'asia-east2' }) - })) - const response = await assign( - { recordRegionSelection, plan, exchangeRegionCorrection }, - { reconnect: true, regionCorrection: { v: 1, action: 'issue-window' } } - ) - - expect(response.status).toBe(200) - expect(await response.json()).not.toHaveProperty('regionCorrection') - expect(exchangeRegionCorrection).not.toHaveBeenCalled() - expect(plan).toHaveBeenCalledWith( - { userId: 'user-1', relayHostId: HOST }, - { reconnect: true, region: 'asia-east2', regionCorrection: true, preferred: true } - ) - expect(recordRegionSelection.mock.calls).toEqual([ - [{ targetRegion: 'asia-east2', selectedRegion: 'asia-east2', fallback: false }] - ]) - }) - -}) - -async function assign( - operations: { - recordRegionSelection: Mock - recordAssignmentAdmission?: Mock - plan?: Mock - assign?: Mock - resolve?: Mock - exchangeRegionCorrection?: Mock - }, - extra: Record = {}, - overrides: Partial = {} -): Promise { - const app = createRelayApp({ ...config(), ...overrides }, { - store: {} as never, - assignments: { - assign: operations.assign ?? vi.fn(), - resolve: operations.resolve ?? vi.fn(async () => null), - exchangeRegionCorrection: operations.exchangeRegionCorrection ?? vi.fn() - } as never, - ...(operations.plan ? { reservePlacement: { plan: operations.plan } as never } : {}), - drain: vi.fn(), - ready: vi.fn(async () => true), - recordRegionSelection: operations.recordRegionSelection, - ...(operations.recordAssignmentAdmission - ? { recordAssignmentAdmission: operations.recordAssignmentAdmission } - : {}) - }) - return await app.request('/v1/assign', { - method: 'POST', - headers: { authorization: `Bearer ${HOST}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1, relayHostId: HOST, preferredRegion: 'asia-east2', ...extra }) - }) -} - -function config(): RelayConfig { - return { - port: 8080, - publicUrl: 'https://relay.example.test', - cellUrl: 'https://relay.example.test', - region: 'us-central1', - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: new TextEncoder().encode('assignment-key-with-at-least-32-bytes'), - role: 'director', - cellId: 'director', - cells: [], - adminAudience: 'https://relay.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - runtimeServiceAccount: 'runtime@example.test', - adminJwksUrl: 'https://auth.example.test/jwks', - databasePoolMax: 3, - publicAssignmentsEnabled: true, - regionalPlacementEnabled: true, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - dataDir: './data' - } -} diff --git a/cloud/apps/relay/src/relay-sigterm-exit.blackbox.test.ts b/cloud/apps/relay/src/relay-sigterm-exit.blackbox.test.ts index 7dde37f9453..c72236c13c2 100644 --- a/cloud/apps/relay/src/relay-sigterm-exit.blackbox.test.ts +++ b/cloud/apps/relay/src/relay-sigterm-exit.blackbox.test.ts @@ -70,16 +70,6 @@ async function startRelay(port: number): Promise { return child } -async function silentTcpPeer(port: number, firstBytes?: string): Promise { - const peer = connect(port, '127.0.0.1') - peer.on('error', () => undefined) - await new Promise((resolveConnect) => peer.once('connect', () => resolveConnect())) - if (firstBytes) { - peer.write(firstBytes) - } - return peer -} - // Pauses reading so the peer never answers the relay's close frame. async function unresponsiveWebSocketPeer(port: number): Promise { const socket = new WebSocket(`ws://127.0.0.1:${port}/v1/connect/abcdefghijklmnop`) @@ -111,14 +101,10 @@ async function waitUntilListenerClosed(port: number): Promise { } // Peers that are not idle to server.close(); unbounded, a silent one held exit until SIGKILL. -it.each([ - ['silent TCP peer', (port: number) => silentTcpPeer(port)], - ['partial-headers peer', (port: number) => silentTcpPeer(port, 'GET /healthz HTTP/1.1\r\nHost: x\r\n')], - ['unresponsive upgraded WebSocket peer', unresponsiveWebSocketPeer] -])('exits within the shutdown bound on SIGTERM with a %s', async (_name, openPeer) => { +it('exits within the shutdown bound on SIGTERM with an unresponsive upgraded WebSocket peer', async () => { const port = await unusedPort() const relay = await startRelay(port) - const peer = await openPeer(port) + const peer = await unresponsiveWebSocketPeer(port) cleanups.push(() => peer.destroy()) const peerClosed = new Promise((resolveClose) => peer.once('close', () => resolveClose())) diff --git a/cloud/apps/relay/src/relay.blackbox.test.ts b/cloud/apps/relay/src/relay.blackbox.test.ts index 21820c22ba6..4884cb1c9d3 100644 --- a/cloud/apps/relay/src/relay.blackbox.test.ts +++ b/cloud/apps/relay/src/relay.blackbox.test.ts @@ -134,19 +134,16 @@ function nextMessage(socket: WebSocket): Promise> { }) } -async function openHostControl(input?: { - controlResumeSecret?: string - previousGeneration?: number - keyPair?: nacl.BoxKeyPair - assignmentEpoch?: number - capabilities?: string -}): Promise<{ socket: WebSocket; ack: Record; keyPair: nacl.BoxKeyPair }> { - const keyPair = input?.keyPair ?? nacl.box.keyPair() +async function openHostControl(): Promise<{ + socket: WebSocket + ack: Record + keyPair: nacl.BoxKeyPair +}> { + const keyPair = nacl.box.keyPair() const hostId = createHash('sha256').update(keyPair.publicKey).digest('base64url').slice(0, 16) const socket = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/host/control`, { headers: { - authorization: `Bearer ${await relayToken('orca-relay', hostId)}`, - ...(input?.capabilities ? { ['x-orca-host-capabilities']: input.capabilities } : {}) + authorization: `Bearer ${await relayToken('orca-relay', hostId)}` }, perMessageDeflate: false }) @@ -159,13 +156,9 @@ async function openHostControl(input?: { type: 'host-hello', v: 1, relayHostId: hostId, - assignmentEpoch: input?.assignmentEpoch ?? 1, + assignmentEpoch: 1, hostPublicKeyB64: Buffer.from(keyPair.publicKey).toString('base64'), - appVersion: 'test', - ...(input?.controlResumeSecret ? { controlResumeSecret: input.controlResumeSecret } : {}), - ...(input?.previousGeneration === undefined - ? {} - : { previousGeneration: input.previousGeneration }) + appVersion: 'test' }) ) const challenge = await nextMessage(socket) diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md deleted file mode 100644 index 2ac4ad78391..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md +++ /dev/null @@ -1,8 +0,0 @@ -Exact relay contract snapshots from `027acb4efa2e6b226d40df266b86367423946d62`, `cloud/packages/relay-contract/src/`. Used to exercise the pre-correction strict wire parsers. Do not format or edit these baseline sources. - -```text -aba94e108a5cd0f1af8b38875429ad8636d24c43a728273e3df60d9a1a1d1b6d director-messages.ts -bd13b5a694a5d683a5b680c14e46ab33f4ef4a5bfedf040d046b09d540cb4c17 wire-scalars.ts -bc89116f884a2f20a6588f9b91219aa596bc2410d28b499a93a78350def109d5 relay-regions.ts -8fcae470a5fc72f2fcdde9d2f09cd20289c256356dd490484ac1cfa53839fbe4 control-messages.ts -``` diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts deleted file mode 100644 index 0daf21e7c28..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { z } from 'zod' -import { - Base6432ByteSchema, - Base64Raw24ByteSchema, - Base64Url32ByteSchema, - EpochMsSchema, - GenerationSchema, - OpaqueIdSchema, - PositiveDurationMsSchema, - RelayHostIdSchema -} from './wire-scalars.js' - -const AppVersionSchema = z.string().min(1).max(128) -const BoundedCiphertextSchema = z - .string() - .min(1) - .max(16 * 1024) - .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/) -const ConnectionKindSchema = z.enum(['invite', 'resume']) - -export const HostHelloSchema = z - .object({ - v: z.literal(1), - relayHostId: RelayHostIdSchema, - assignmentEpoch: GenerationSchema, - hostPublicKeyB64: Base6432ByteSchema, - appVersion: AppVersionSchema, - previousGeneration: GenerationSchema.optional(), - controlResumeSecret: Base64Url32ByteSchema.optional() - }) - .strict() - -export const HostChallengeSchema = z - .object({ - challengeId: OpaqueIdSchema, - relayEphemeralPublicKeyB64: Base6432ByteSchema, - nonceB64: Base64Raw24ByteSchema, - ciphertextB64: BoundedCiphertextSchema, - expiresAt: EpochMsSchema - }) - .strict() - -export const HostChallengeAckSchema = z - .object({ challengeId: OpaqueIdSchema, proofB64: Base6432ByteSchema }) - .strict() - -// Advertised on the control upgrade rather than in host-hello: HostHelloSchema -// is strict, so a new hello key is refused by every already-deployed cell. -export const RELAY_HOST_CAPABILITIES_HEADER = 'x-orca-host-capabilities' -// The host accepts kind/relayDeviceId on a pendingConns entry. A host that does -// not advertise this parses those entries strictly and would drop the whole ack. -export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details' - -export function parseRelayHostCapabilities( - header: string | string[] | undefined -): ReadonlySet { - const raw = Array.isArray(header) ? header.join(',') : (header ?? '') - return new Set( - raw - .split(',') - .map((token) => token.trim()) - .filter((token) => token.length > 0 && token.length <= 64) - .slice(0, 16) - ) -} - -// kind/relayDeviceId are optional so an entry stays readable by a host that -// predates them; the cell only emits them to a host that advertised support. -const PendingConnectionSchema = z - .object({ - connId: OpaqueIdSchema, - connTicket: Base64Url32ByteSchema, - kind: ConnectionKindSchema.optional(), - relayDeviceId: OpaqueIdSchema.optional() - }) - .strict() - -export const HostHelloAckSchema = z - .object({ - v: z.literal(1), - generation: GenerationSchema, - controlResumeSecret: Base64Url32ByteSchema, - leaseExpiresAt: EpochMsSchema, - activeConnIds: z.array(OpaqueIdSchema).max(8), - pendingConns: z.array(PendingConnectionSchema).max(8) - }) - .strict() - -export const ConnectionOpenSchema = z - .object({ - connId: OpaqueIdSchema, - connTicket: Base64Url32ByteSchema, - kind: ConnectionKindSchema, - relayDeviceId: OpaqueIdSchema, - attachDeadlineMs: PositiveDurationMsSchema - }) - .strict() - -export const HostDataAuthSchema = z - .object({ - v: z.literal(1), - connTicket: Base64Url32ByteSchema, - generation: GenerationSchema - }) - .strict() - -export const InviteCreateSchema = z - .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) - .strict() - -export const InviteCreatedSchema = z - .object({ - reqId: OpaqueIdSchema, - inviteToken: Base64Url32ByteSchema, - expiresAt: EpochMsSchema, - maxAttempts: z.number().int().positive().max(16) - }) - .strict() - -export const DeviceRevokeSchema = z - .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) - .strict() - -export const AuthRefreshSchema = z.object({ relayJwt: z.string().min(1).max(8 * 1024) }).strict() - -export const DrainSchema = z - .object({ - graceMs: z.number().int().nonnegative().max(60 * 60 * 1000), - recovery: z.literal('resolve-director') - }) - .strict() - -export const HeartbeatSchema = z.object({ t: EpochMsSchema }).strict() - -export type HostHello = z.infer -export type HostChallenge = z.infer -export type HostChallengeAck = z.infer -export type HostHelloAck = z.infer -export type ConnectionOpen = z.infer -export type HostDataAuth = z.infer -export type InviteCreate = z.infer -export type InviteCreated = z.infer -export type DeviceRevoke = z.infer -export type AuthRefresh = z.infer -export type Drain = z.infer -export type Heartbeat = z.infer diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts deleted file mode 100644 index e697135b68e..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { z } from 'zod' -import { - Base64Url32ByteSchema, - CanonicalHttpsOriginSchema, - EpochMsSchema, - GenerationSchema, - RelayHostIdSchema -} from './wire-scalars.js' -import { RelayRegionSchema } from './relay-regions.js' - -const SignedAssignmentLeaseSchema = z.string().min(1).max(8 * 1024) - -export const AssignmentRequestSchema = z - .object({ - v: z.literal(1), - relayHostId: RelayHostIdSchema, - // Client-declared reconnection; the director verifies it against the - // durable assignment before granting fast-lane admission. - reconnect: z.boolean().optional(), - preferredRegion: RelayRegionSchema.optional() - }) - .strict() - -export const AssignmentResponseSchema = z - .object({ - v: z.literal(1), - cellUrl: CanonicalHttpsOriginSchema, - assignmentEpoch: GenerationSchema, - lease: SignedAssignmentLeaseSchema - }) - .strict() - -export const ResolveRequestSchema = z - .object({ - v: z.literal(1), - relayHostId: RelayHostIdSchema, - resumeToken: Base64Url32ByteSchema - }) - .strict() - -export const ResolveResponseSchema = z - .object({ - v: z.literal(1), - cellUrl: CanonicalHttpsOriginSchema, - assignmentEpoch: GenerationSchema, - leaseExpiresAt: EpochMsSchema - }) - .strict() - -export const RelayMovedSchema = z - .object({ - v: z.literal(1), - cellUrl: CanonicalHttpsOriginSchema, - assignmentEpoch: GenerationSchema - }) - .strict() - -export function isTrustedNewerMove(input: { - sourceOrigin: string - configuredDirectorOrigin: string - currentAssignmentEpoch: number - move: z.infer -}): boolean { - // Why: cells and stale director responses must never redirect a credential-bearing client. - return ( - input.sourceOrigin === input.configuredDirectorOrigin && - input.move.assignmentEpoch > input.currentAssignmentEpoch - ) -} - -export type AssignmentRequest = z.infer -export type AssignmentResponse = z.infer -export type ResolveRequest = z.infer -export type ResolveResponse = z.infer -export type RelayMoved = z.infer diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts deleted file mode 100644 index 6b8837829df..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { z } from 'zod' - -export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const - -export const RelayRegionSchema = z.enum(RELAY_REGIONS) - -export type RelayRegion = z.infer - -export const RELAY_DEFAULT_REGION: RelayRegion = 'us-central1' - -// Field-name segment for the flat per-region runtime counters, spelled out rather than derived so -// the Terraform side can hold the same literal and a test can compare the two. `satisfies` makes a -// new region a compile error here, which is the point: a region with no segment would silently -// drop out of the region-skew alert's denominators. -export const RELAY_REGION_METRIC_SEGMENTS = { - 'us-central1': 'UsCentral1', - 'asia-east2': 'AsiaEast2' -} as const satisfies Record - -const RelayProbeOriginSchema = z.string().url().max(2_048).refine(isCanonicalHttpsOrigin) - -export const RelayRegionCatalogResponseSchema = z - .object({ - v: z.literal(1), - regions: z - .array( - z - .object({ - region: RelayRegionSchema, - probeOrigins: z.array(RelayProbeOriginSchema).min(1).max(2) - }) - .strict() - ) - .max(RELAY_REGIONS.length) - }) - .strict() - .superRefine((catalog, context) => { - const regions = new Set() - const origins = new Set() - for (const [regionIndex, entry] of catalog.regions.entries()) { - if (regions.has(entry.region)) { - context.addIssue({ - code: 'custom', - message: 'duplicate relay region', - path: ['regions', regionIndex, 'region'] - }) - } - regions.add(entry.region) - for (const [originIndex, origin] of entry.probeOrigins.entries()) { - if (origins.has(origin)) { - context.addIssue({ - code: 'custom', - message: 'duplicate relay probe origin', - path: ['regions', regionIndex, 'probeOrigins', originIndex] - }) - } - origins.add(origin) - } - } - }) - -export type RelayRegionCatalogResponse = z.infer - -function isCanonicalHttpsOrigin(value: string): boolean { - try { - const url = new URL(value) - return url.protocol === 'https:' && url.origin === value - } catch { - return false - } -} diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts deleted file mode 100644 index 27dd3a8b30f..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { z } from 'zod' - -export const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) -export const Base64Url24ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{32}$/) -export const Base6432ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){10}[A-Za-z0-9+/]{3}=$/) -export const Base64Raw24ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){8}$/) -export const RelayHostIdSchema = z.string().regex(/^[A-Za-z0-9_-]{16}$/) -export const OpaqueIdSchema = z.string().min(1).max(128) -export const EpochMsSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) -export const GenerationSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) -export const PositiveDurationMsSchema = z.number().int().positive().max(24 * 60 * 60 * 1000) - -export const CanonicalHttpsOriginSchema = z.string().max(2048).refine((value) => { - try { - const url = new URL(value) - return url.protocol === 'https:' && url.origin === value && url.pathname === '/' - } catch { - return false - } -}, 'must be a canonical HTTPS origin') diff --git a/cloud/dev/scripts/run-relay-tests.test.mjs b/cloud/dev/scripts/run-relay-tests.test.mjs index 70a332ea205..cebab34368b 100644 --- a/cloud/dev/scripts/run-relay-tests.test.mjs +++ b/cloud/dev/scripts/run-relay-tests.test.mjs @@ -32,17 +32,16 @@ function temporary(t) { return directory } -function start(t, options = {}) { +function start(t) { const scratchParent = temporary(t) const calls = [] const reports = [] const events = new EventEmitter() - const env = { ORCA_RELAY_TEST_POSTGRES_URL: databaseUrl, PRESERVED: 'yes', ...options.env } + const env = { ORCA_RELAY_TEST_POSTGRES_URL: databaseUrl, PRESERVED: 'yes' } const pending = runRelayTests({ cwd: join(scratchParent, 'relay'), cli: join(scratchParent, 'vitest.mjs'), parallelism: 4, - ...options, env, events, scratchParent, @@ -53,7 +52,7 @@ function start(t, options = {}) { return deferred.promise } }) - return { pending, calls, reports, events, scratchParent, env } + return { pending, calls, reports, events, scratchParent } } function finish(call, result = success, closed = true) { @@ -103,43 +102,6 @@ test('overlaps both projects within the worker budget and isolates their scratch assertClean(h) }) -for (const [name, options] of [ - ['selectors', { args: ['src/assignment.test.ts', '-t', 'requested behavior'] }], - [ - 'alternate PostgreSQL', - { env: { ORCA_IDLE_REHOME_POSTGRES_URL: 'postgres://localhost:55440/relay' } } - ], - ['application database', { env: { DATABASE_URL: databaseUrl } }], - ['one CPU', { parallelism: 1 }] -]) { - test(`retains the original single run for ${name}`, async (t) => { - const h = start(t, options) - assert.equal(h.calls.length, 1) - const { spec } = h.calls[0] - assert.deepEqual(spec.args.slice(1), ['run', ...(options.args ?? [])]) - for (const [key, value] of Object.entries(h.env)) { - assert.equal(spec.env[key], value) - } - finish(h.calls[0]) - assert.equal(await h.pending, 0) - assertClean(h) - }) -} - -for (const [name, result] of [ - ['null exit code', { ...success, code: null }], - ['termination signal', { ...success, signal: 'SIGTERM' }], - ['timeout', { ...success, timedOut: true }] -]) { - test(`fails a ${name} even when other result fields indicate success`, async (t) => { - const h = start(t) - finish(h.calls[0], result) - finish(h.calls[1]) - assert.equal(await h.pending, 1) - assertClean(h) - }) -} - test('fails and retains scratch when a child never reports closure', async (t) => { const h = start(t) finish(h.calls[0], success, false) @@ -152,8 +114,7 @@ test('fails and retains scratch when a child never reports closure', async (t) = }) for (const [signal, exitCode, laterSignal] of [ - ['SIGINT', 130, 'SIGTERM'], - ['SIGTERM', 143, 'SIGINT'] + ['SIGINT', 130, 'SIGTERM'] ]) { test(`${signal} cancels every child and retains scratch despite root close callbacks`, async (t) => { const h = start(t) diff --git a/cloud/packages/cloud-database/src/cloud-leader-lock.test.ts b/cloud/packages/cloud-database/src/cloud-leader-lock.test.ts deleted file mode 100644 index 3253c0cbf7a..00000000000 --- a/cloud/packages/cloud-database/src/cloud-leader-lock.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { randomUUID } from 'node:crypto' -import pg from 'pg' -import { describe, expect, it } from 'vitest' -import { openInMemoryCloudDatabase } from './cloud-database.js' -import { acquireLeadership } from './cloud-leader-lock.js' - -const postgresUrl = process.env.ORCA_CLOUD_DATABASE_TEST_URL -const database = await openInMemoryCloudDatabase([]) - -describe('acquireLeadership', () => { - it.skipIf(!postgresUrl)( - 'lets one holder lead until it releases or its session dies', - async () => { - const key = `gateway-${randomUUID()}` - const options = { databaseUrl: postgresUrl, database, key, pollMs: 50, checkMs: 50 } - const first = await acquireLeadership({ ...options, signal: AbortSignal.timeout(5_000) }) - let secondLed = false - const second = acquireLeadership({ ...options, signal: AbortSignal.timeout(5_000) }).then( - (leadership) => { - secondLed = true - return leadership - } - ) - await new Promise((resolve) => setTimeout(resolve, 200)) - expect(secondLed).toBe(false) - await first.release() - const next = await second - - // Killing the leader's session frees the lock and the holder notices. - const admin = new pg.Client({ connectionString: postgresUrl }) - await admin.connect() - await admin.query( - `SELECT pg_terminate_backend(pid) FROM pg_locks - WHERE locktype = 'advisory' AND objid = hashtext($1::text)::oid AND granted`, - [key] - ) - await admin.end() - await next.lost - // Its transactions ran on the lock's connection, so none can commit after the loss. - await expect( - next.transaction((transaction) => transaction.query('SELECT 1')) - ).rejects.toThrow() - const third = await acquireLeadership({ ...options, signal: AbortSignal.timeout(5_000) }) - await third.release() - } - ) - - it.skipIf(!postgresUrl)('stops waiting when aborted', async () => { - const key = `gateway-${randomUUID()}` - const options = { databaseUrl: postgresUrl, database, key, pollMs: 50 } - const first = await acquireLeadership({ ...options, signal: AbortSignal.timeout(5_000) }) - await expect( - acquireLeadership({ ...options, signal: AbortSignal.timeout(200) }) - ).rejects.toThrow() - await first.release() - }) -}) diff --git a/cloud/packages/cloud-database/src/cloud-notifications.test.ts b/cloud/packages/cloud-database/src/cloud-notifications.test.ts index 875192b0f24..3c6e9bd39c3 100644 --- a/cloud/packages/cloud-database/src/cloud-notifications.test.ts +++ b/cloud/packages/cloud-database/src/cloud-notifications.test.ts @@ -59,7 +59,7 @@ describe('cloud database notifications', () => { }) it.skipIf(!postgresUrl)( - 'delivers a Postgres notification at commit and re-listens after losing its connection', + 'delivers Postgres notifications and re-listens after losing its connection', async () => { const applicationName = `cloud-db-listen-${randomUUID()}` const database = await openCloudDatabase({ @@ -75,8 +75,6 @@ describe('cloud database notifications', () => { try { await database.transaction(async (tx) => { await notifications.notify(tx, 'inbox', 'committed') - await new Promise((resolve) => setTimeout(resolve, 100)) - expect(seen.payloads).toEqual([]) }) await seen.until(() => seen.payloads.length === 1) diff --git a/cloud/packages/connector-contract/src/contract.test.ts b/cloud/packages/connector-contract/src/contract.test.ts index 4da1296a902..96de62bf7cf 100644 --- a/cloud/packages/connector-contract/src/contract.test.ts +++ b/cloud/packages/connector-contract/src/contract.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { ConnectorEventSchema } from './event-messages.js' -import { ConnectorHelloRequestSchema } from './hello-messages.js' import { CONNECTOR_LIMITS } from './connector-limits.js' const conversation = { source: 'slack', externalId: 'T1:C9:1792.9:U5' } as const @@ -29,56 +28,3 @@ describe('events', () => { ).toBe(false) }) }) - -describe('hello and replies', () => { - it('keeps capability entries the cloud does not know', () => { - const hello = ConnectorHelloRequestSchema.parse({ - v: 1, - contract: 1, - orcaVersion: '1.4.230', - platform: 'linux', - runtime: 'serve', - hostName: 'build-box', - agents: ['claude', 'future-agent'], - promptKinds: ['approval'], - features: ['answer', 'future-feature'], - sources: ['slack', 'future-source'], - projects: [ - { placeId: 'pl_1', name: 'orca', kind: 'git', where: { kind: 'ssh', label: 'openclaw' } } - ] - }) - expect(hello.features).toEqual(['answer', 'future-feature']) - expect(hello.sources).toEqual(['slack', 'future-source']) - }) - - it('caps a hello at maxHelloProjects projects with short display strings', () => { - const project = (name: string) => ({ - placeId: 'pl_1', - name, - kind: 'folder', - where: { kind: 'local' } - }) - const hello = (projects: unknown[]) => - ConnectorHelloRequestSchema.safeParse({ - v: 1, - contract: 1, - orcaVersion: '1.4.230', - platform: 'linux', - runtime: 'desktop', - hostName: 'build-box', - agents: ['claude'], - promptKinds: [], - features: [], - sources: ['slack'], - projects - }).success - const longest = 'x'.repeat(CONNECTOR_LIMITS.maxDisplayTextLength) - expect( - hello(Array.from({ length: CONNECTOR_LIMITS.maxHelloProjects }, () => project(longest))) - ).toBe(true) - expect(hello([project(`${longest}x`)])).toBe(false) - expect( - hello(Array.from({ length: CONNECTOR_LIMITS.maxHelloProjects + 1 }, () => project('orca'))) - ).toBe(false) - }) -}) diff --git a/cloud/packages/postgres-schema/src/schema-lock-target.test.ts b/cloud/packages/postgres-schema/src/schema-lock-target.test.ts index 953fa219424..45ad2b30795 100644 --- a/cloud/packages/postgres-schema/src/schema-lock-target.test.ts +++ b/cloud/packages/postgres-schema/src/schema-lock-target.test.ts @@ -1,25 +1,9 @@ import { describe, expect, it } from 'vitest' import { requireSchemaLockTarget, - schemaLockTarget, - sqlWithoutComments + schemaLockTarget } from './schema-lock-target.js' -describe('sqlWithoutComments', () => { - - it('closes the inner block comment first when they nest', () => { - expect(sqlWithoutComments('ALTER TABLE t /* a /* b */ c */ ADD COLUMN d TEXT')).toBe( - 'ALTER TABLE t ADD COLUMN d TEXT' - ) - }) - - it('leaves a comment marker inside a string literal alone', () => { - expect(sqlWithoutComments(`ALTER TABLE t ADD COLUMN c TEXT DEFAULT '-- not a comment'`)).toBe( - `ALTER TABLE t ADD COLUMN c TEXT DEFAULT '-- not a comment'` - ) - }) -}) - describe('catalog name folding', () => { it('unescapes a doubled quote and leaves the qualified table text as written', () => { @@ -33,11 +17,10 @@ describe('catalog name folding', () => { }) describe('square brackets in an ALTER TABLE', () => { - it.each([ - ['an array type', 'ALTER TABLE t ADD COLUMN c bigint[] DEFAULT ARRAY[1, 2]'], - ['a nested array default', "ALTER TABLE t ADD COLUMN c TEXT[] DEFAULT ARRAY['a', 'b']"] - ])('does not read a comma inside %s as a second subcommand', (_label, statement) => { - expect(() => requireSchemaLockTarget(statement)).not.toThrow() + it('does not read an array-default comma as a second subcommand', () => { + expect(() => + requireSchemaLockTarget('ALTER TABLE t ADD COLUMN c bigint[] DEFAULT ARRAY[1, 2]') + ).not.toThrow() }) it('still catches a second subcommand after an array default', () => { @@ -52,12 +35,6 @@ describe('multi-action ALTER TABLE', () => { // Skipping on the first subcommand would permanently drop every later action. const statement = 'ALTER TABLE t ADD COLUMN IF NOT EXISTS a TEXT, ADD COLUMN IF NOT EXISTS b TEXT' - expect(schemaLockTarget(statement)).toEqual({ - kind: 'column', - table: 't', - name: 'a', - skipWhen: 'present' - }) expect(() => requireSchemaLockTarget(statement)).toThrow(/unparsed_schema_lock_target/) }) }) @@ -68,7 +45,6 @@ describe('dollar-quoted bodies', () => { // The closing delimiter has to match the opening tag, so the comma and the comment marker // between the inner $$ pair are still inside the body. const statement = 'ALTER TABLE t ADD COLUMN c TEXT DEFAULT $tag$ a $$ -- b, c $$ d $tag$' - expect(sqlWithoutComments(statement)).toBe(statement) expect(() => requireSchemaLockTarget(statement)).not.toThrow() expect(schemaLockTarget(statement)).toEqual({ kind: 'column', diff --git a/cloud/packages/push-contract/src/push-host-proof-transcript.test.ts b/cloud/packages/push-contract/src/push-host-proof-transcript.test.ts index ed2f775041b..21c8139de21 100644 --- a/cloud/packages/push-contract/src/push-host-proof-transcript.test.ts +++ b/cloud/packages/push-contract/src/push-host-proof-transcript.test.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' import { - buildPushHostChallengePlaintext, - buildPushHostProofMacInput, buildPushHostProofTranscript } from './push-host-proof-transcript.js' @@ -48,30 +46,4 @@ describe('push host proof transcript', () => { expect(offset).toBe(transcript.byteLength) }) - it('frames the challenge plaintext as domain, length, transcript, secret', () => { - const transcript = buildPushHostProofTranscript(transcriptInput) - const secret = new Uint8Array(32).fill(11) - const plaintext = buildPushHostChallengePlaintext(transcript, secret) - const length = Buffer.alloc(4) - length.writeUInt32BE(transcript.byteLength) - expect(Buffer.from(plaintext)).toEqual( - Buffer.concat([ - Buffer.from('orca-push-host-challenge/v1\0'), - length, - Buffer.from(transcript), - Buffer.alloc(32, 11) - ]) - ) - expect(() => buildPushHostChallengePlaintext(transcript, new Uint8Array(16))).toThrow( - 'challengeSecret must be 32 bytes' - ) - }) - - it('separates the ack mac input from the challenge domain', () => { - const transcript = buildPushHostProofTranscript(transcriptInput) - const macInput = buildPushHostProofMacInput(transcript) - expect(Buffer.from(macInput)).toEqual( - Buffer.concat([Buffer.from('orca-push-host-proof/v1\0ack\0'), Buffer.from(transcript)]) - ) - }) }) diff --git a/cloud/packages/push-contract/src/send-messages.test.ts b/cloud/packages/push-contract/src/send-messages.test.ts deleted file mode 100644 index 166f09fd72e..00000000000 --- a/cloud/packages/push-contract/src/send-messages.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { PushSendRequestSchema } from './send-messages.js' - -function notification(): Record { - return { - notificationId: 'note-1', - notificationSeq: 4, - notificationEpoch: '5c9e9a1e-0000-4000-8000-000000000000', - source: 'agent-task-complete', - agentState: 'needs-input', - title: 'Agent needs input', - body: 'Waiting on your answer', - worktreeId: 'wt-1' - } -} - -describe('send schemas', () => { - - it('rejects a notification id that could not be sent as a collapse header', () => { - for (const notificationId of ['line\nbreak', 'nul\0byte', 'émoji', '\t']) { - expect( - PushSendRequestSchema.safeParse({ - v: 1, - registrationIds: ['reg-1'], - notification: { ...notification(), notificationId } - }).success - ).toBe(false) - } - expect( - PushSendRequestSchema.safeParse({ - v: 1, - registrationIds: ['reg-1'], - notification: { - ...notification(), - notificationId: 'agent:repo%3A%3A%2FUsers%2Fme:pane-1:1700000000000' - } - }).success - ).toBe(true) - }) -}) diff --git a/cloud/packages/relay-contract/src/contract.test.ts b/cloud/packages/relay-contract/src/contract.test.ts index 2c663b4388a..1c6cfe4b38f 100644 --- a/cloud/packages/relay-contract/src/contract.test.ts +++ b/cloud/packages/relay-contract/src/contract.test.ts @@ -1,36 +1,9 @@ import { describe, expect, it } from 'vitest' -import { HostHelloAckSchema } from './control-messages.js' -import { isTrustedNewerMove, RelayMovedSchema } from './director-messages.js' import { - buildHostChallengePlaintext, - buildHostProofMacInput, buildHostProofTranscript } from './host-proof-transcript.js' describe('relay protocol contract', () => { - - it('accepts moves only from the configured director at a strictly newer epoch', () => { - const move = RelayMovedSchema.parse({ - v: 1, - cellUrl: 'https://relay-c2.onorca.dev', - assignmentEpoch: 4 - }) - const base = { - configuredDirectorOrigin: 'https://relay.onorca.dev', - currentAssignmentEpoch: 3, - move - } - expect(isTrustedNewerMove({ ...base, sourceOrigin: 'https://relay.onorca.dev' })).toBe(true) - expect(isTrustedNewerMove({ ...base, sourceOrigin: move.cellUrl })).toBe(false) - expect( - isTrustedNewerMove({ - ...base, - sourceOrigin: 'https://relay.onorca.dev', - currentAssignmentEpoch: 4 - }) - ).toBe(false) - }) - it('locks the complete host key-possession transcript', () => { const transcript = buildHostProofTranscript({ relayOrigin: 'https://relay.onorca.dev', @@ -48,70 +21,8 @@ describe('relay protocol contract', () => { previousGeneration: 6, resumeRequested: true }) - const challenge = buildHostChallengePlaintext(transcript, new Uint8Array(32).fill(3)) - const proofInput = buildHostProofMacInput(transcript) - expect(Buffer.from(transcript).toString('base64url')).toBe( 'AAAACHByb3RvY29sAAAAGG9yY2EtcmVsYXktaG9zdC1wcm9vZi92MQAAAAd2ZXJzaW9uAAAAAQEAAAALcmVsYXlPcmlnaW4AAAAYaHR0cHM6Ly9yZWxheS5vbm9yY2EuZGV2AAAAF3JlbGF5RXBoZW1lcmFsUHVibGljS2V5AAAAIAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAADmNoYWxsZW5nZU5vbmNlAAAAGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAtjaGFsbGVuZ2VJZAAAAAtjaGFsbGVuZ2UtMQAAAAhpc3N1ZWRBdAAAAAgAAAGLz-VoAAAAAAlleHBpcmVzQXQAAAAIAAABi8_ljxAAAAAGdXNlcklkAAAABnVzZXItMQAAAAlwcm9maWxlSWQAAAAJcHJvZmlsZS0xAAAADm9yZ2FuaXphdGlvbklkAAAABW9yZy0xAAAAC3JlbGF5SG9zdElkAAAAEGFiY2RlZmdoaWprbG1ub3AAAAANaG9zdFB1YmxpY0tleQAAACACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgAAAA9hc3NpZ25tZW50RXBvY2gAAAAIAAAAAAAAAAcAAAAScHJldmlvdXNHZW5lcmF0aW9uAAAACAAAAAAAAAAGAAAAD3Jlc3VtZVJlcXVlc3RlZAAAAAEB' ) - const length = Buffer.alloc(4) - length.writeUInt32BE(transcript.byteLength) - expect(Buffer.from(challenge)).toEqual( - Buffer.concat([ - Buffer.from('orca-relay-host-challenge/v1\0'), - length, - Buffer.from(transcript), - Buffer.alloc(32, 3) - ]) - ) - expect(Buffer.from(proofInput)).toEqual( - Buffer.concat([Buffer.from('orca-relay-host-proof/v1\0ack\0'), Buffer.from(transcript)]) - ) - expect(() => buildHostChallengePlaintext(transcript, new Uint8Array(31))).toThrow( - 'challengeSecret must be 32 bytes' - ) - expect(() => - buildHostProofTranscript({ - relayOrigin: 'https://relay.onorca.dev', - relayEphemeralPublicKey: new Uint8Array(32), - challengeNonce: new Uint8Array(32), - challengeId: 'challenge-1', - issuedAt: 1, - expiresAt: 2, - userId: 'user-1', - profileId: 'profile-1', - organizationId: 'org-1', - relayHostId: 'abcdefghijklmnop', - hostPublicKey: new Uint8Array(32), - assignmentEpoch: 1, - resumeRequested: false - }) - ).toThrow('challengeNonce must be 24 bytes') - }) -}) - -describe('pending connection details capability', () => { - it('reads a pending entry with or without the stated kind and device', () => { - const ack = { - v: 1 as const, - generation: 3, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_800_000_000_000, - activeConnIds: [] - } - const identifiers = { connId: 'conn-1', connTicket: 'T'.repeat(43) } - expect(HostHelloAckSchema.safeParse({ ...ack, pendingConns: [identifiers] }).success).toBe(true) - expect( - HostHelloAckSchema.safeParse({ - ...ack, - pendingConns: [{ ...identifiers, kind: 'resume', relayDeviceId: 'device-1' }] - }).success - ).toBe(true) - expect( - HostHelloAckSchema.safeParse({ - ...ack, - pendingConns: [{ ...identifiers, reservationId: 'injected' }] - }).success - ).toBe(false) }) }) diff --git a/cloud/packages/relay-contract/src/idle-regional-rehome.test.ts b/cloud/packages/relay-contract/src/idle-regional-rehome.test.ts index 7303596c7d0..be9ee717221 100644 --- a/cloud/packages/relay-contract/src/idle-regional-rehome.test.ts +++ b/cloud/packages/relay-contract/src/idle-regional-rehome.test.ts @@ -2,22 +2,9 @@ import { describe, expect, it } from 'vitest' import { IdleRegionalRehomeResponseSchema } from './idle-regional-rehome.js' describe('idle regional rehome response', () => { - it('accepts a source cell that has never heard of the reason field', () => { - expect(IdleRegionalRehomeResponseSchema.parse({ v: 1, outcome: 'deferred' })).toEqual({ - v: 1, - outcome: 'deferred' - }) - }) - it('reads a reason it does not know as absent instead of failing the response', () => { expect( IdleRegionalRehomeResponseSchema.parse({ v: 1, outcome: 'deferred', reason: 'from-a-newer-cell' }) ).toEqual({ v: 1, outcome: 'deferred' }) }) - - it('drops a field added after this decoder shipped', () => { - expect( - IdleRegionalRehomeResponseSchema.parse({ v: 1, outcome: 'committed', movedAt: 17 }) - ).toEqual({ v: 1, outcome: 'committed' }) - }) }) diff --git a/cloud/packages/relay-contract/src/persistence-invariants.test.ts b/cloud/packages/relay-contract/src/persistence-invariants.test.ts index 204c8ce0062..c94ed8d2bc1 100644 --- a/cloud/packages/relay-contract/src/persistence-invariants.test.ts +++ b/cloud/packages/relay-contract/src/persistence-invariants.test.ts @@ -1,53 +1,9 @@ import { describe, expect, it } from 'vitest' -import { hasAdmissionCapacity } from './admission-budgets.js' import { decideResumeCommit, TokenFamilySchema } from './persistence-invariants.js' const HASH = 'abcdefghijklmnopqrstuvwxyzABCDEFGH012345678' describe('relay persistence invariants', () => { - it('admits pre-auth sockets only outside every reserved budget', () => { - expect( - hasAdmissionCapacity({ - totalRequests: 649, - preAuthConnections: 44, - sourcePreAuthConnections: 3 - }) - ).toBe(true) - expect( - hasAdmissionCapacity({ - totalRequests: 650, - preAuthConnections: 0, - sourcePreAuthConnections: 0 - }) - ).toBe(false) - expect( - hasAdmissionCapacity({ - totalRequests: 0, - preAuthConnections: 45, - sourcePreAuthConnections: 0 - }) - ).toBe(false) - expect( - hasAdmissionCapacity({ totalRequests: 0, preAuthConnections: 0, sourcePreAuthConnections: 4 }) - ).toBe(false) - expect( - hasAdmissionCapacity({ - totalRequests: 2_899, - preAuthConnections: 0, - sourcePreAuthConnections: 0, - totalRequestCeiling: 2_900 - }) - ).toBe(true) - expect( - hasAdmissionCapacity({ - totalRequests: 2_900, - preAuthConnections: 0, - sourcePreAuthConnections: 0, - totalRequestCeiling: 2_900 - }) - ).toBe(false) - }) - it('makes commit-time current, grace, retired, expired, and revoked outcomes exact', () => { const family = TokenFamilySchema.parse({ currentVersion: 3, diff --git a/config/ast-grep/rules/claude-chat-entrypoint.yml b/config/ast-grep/rules/claude-chat-entrypoint.yml index 0d2bbad8f49..be6996784eb 100644 --- a/config/ast-grep/rules/claude-chat-entrypoint.yml +++ b/config/ast-grep/rules/claude-chat-entrypoint.yml @@ -45,9 +45,9 @@ ignores: - '**/__fixtures__/**' - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' - 'src/main/claude/claude-stream-json-connection.ts' - - 'src/main/claude/claude-agent-sdk-process-spawn.ts' + - 'src/main/claude/child-process/claude-agent-sdk-process-spawn.ts' - 'src/main/claude/structured/launch/claude-structured-child-env.ts' - - 'src/main/claude/claude-model-catalog-probe.ts' + - 'src/main/claude/model-catalog/claude-model-catalog-probe.ts' rule: all: - any: @@ -67,9 +67,9 @@ ignores: - '**/__fixtures__/**' - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' - 'src/main/claude/claude-stream-json-connection.ts' - - 'src/main/claude/claude-agent-sdk-process-spawn.ts' + - 'src/main/claude/child-process/claude-agent-sdk-process-spawn.ts' - 'src/main/claude/structured/launch/claude-structured-child-env.ts' - - 'src/main/claude/claude-model-catalog-probe.ts' + - 'src/main/claude/model-catalog/claude-model-catalog-probe.ts' rule: all: - any: diff --git a/config/benchmarks/computer-use/README.md b/config/benchmarks/computer-use/README.md index 1e9e7cb7116..52d324d192d 100644 --- a/config/benchmarks/computer-use/README.md +++ b/config/benchmarks/computer-use/README.md @@ -62,11 +62,11 @@ Tasks cover explicit text targeting with another field logically focused, Unicod entry plus submit, select-all replacement plus submit, and color choice plus one click. Interference probes remain separate from task latency comparisons. -Explicit-target typing is a native capability probe. Orca's public CLI/RPC currently -accepts typing at the focused field and does not expose an element target for text. -Failure of this probe identifies a capability to consider adding; it does not prove -a violation of the current public typing contract. Click-then-type tasks exercise -the existing sequence, although this benchmark still bypasses public transports. +Explicit-target typing is a native capability probe. Orca's public CLI/RPC accepts +an element target for text (`type-text --element-index`) on providers that report +`actions.typeTextElement` (macOS and Linux); Windows types only at the focused +field. Click-then-type tasks send no element with the text, like `type-text` +without the index, although this benchmark still bypasses public transports. The Linux Electron job also records restoration stages in `focus-probe/results.json`. It records the AT-SPI focus acknowledgment, selected ACTIVE state, manual legacy PID diff --git a/config/benchmarks/computer-use/linux_typing_probe.py b/config/benchmarks/computer-use/linux_typing_probe.py index e1446e8870a..e113973f067 100644 --- a/config/benchmarks/computer-use/linux_typing_probe.py +++ b/config/benchmarks/computer-use/linux_typing_probe.py @@ -137,7 +137,7 @@ def main(): raise AssertionError("cancellation fixture could not focus and select the field") before = keymap() operation = trial.directory / "cancel.json" - bench.write_json(operation, engine._req("type_text", field, True, text="éΩAa" * 150)) + bench.write_json(operation, engine._req("type_text", None, True, text="éΩAa" * 150)) held_before = held_keys() env = dict(os.environ) ready = trial.directory / "held-ready" diff --git a/config/benchmarks/computer-use/providers.py b/config/benchmarks/computer-use/providers.py index cc4544f8830..f8f81b342f7 100644 --- a/config/benchmarks/computer-use/providers.py +++ b/config/benchmarks/computer-use/providers.py @@ -194,7 +194,7 @@ class CuaEngine: raise RuntimeError("selected cua element has no token") if action == "click": tool, args = "click", {**base, "element_token": tok} - elif action == "type": + elif action in ("type", "type_into"): tool, args = "type_text", {**base, "element_token": tok, "text": text} elif action == "return": tool, args = "press_key", {**base, "element_token": tok, "key": "return"} @@ -254,6 +254,9 @@ class OrcaEngine: if action == "click": req = self._req("click", el, escalate) elif action == "type": + # Why: click-then-type mirrors public `type-text` without --element-index, which types at focus. + req = self._req("type_text", None, escalate, text=text) + elif action == "type_into": req = self._req("type_text", el, escalate, text=text) elif action == "return": req = self._req("press_key", el, escalate, key="return") diff --git a/config/benchmarks/computer-use/trial_contract.py b/config/benchmarks/computer-use/trial_contract.py index 0e65acc1ab1..5855c8f6b2e 100644 --- a/config/benchmarks/computer-use/trial_contract.py +++ b/config/benchmarks/computer-use/trial_contract.py @@ -12,7 +12,7 @@ SELECTORS = { "scroll": (r"list|scroll|document|web", r"\blist\b|\bbenchelectron\b"), } TASKS = { - "targeted_type": [("type", "field")], + "targeted_type": [("type_into", "field")], "type_submit": [("click", "field"), ("type", "field"), ("return", "field")], "replace_submit": [("click", "field"), ("ctrl_a", "field"), ("type", "field"), ("return", "field")], "choose_and_click": [("choose", "color"), ("click", "button")], diff --git a/config/build-plugins/bootstrap-fatal-exit-banner.ts b/config/build-plugins/bootstrap-fatal-exit-banner.ts index 8a8359da9db..36120dd2637 100644 --- a/config/build-plugins/bootstrap-fatal-exit-banner.ts +++ b/config/build-plugins/bootstrap-fatal-exit-banner.ts @@ -1,4 +1,4 @@ -import { BOOTSTRAP_FATAL_EXIT_GUARD_KEY } from '../../src/main/startup/bootstrap-fatal-exit-guard' +import { BOOTSTRAP_FATAL_EXIT_GUARD_KEY } from '../../src/main/startup/process-failure/bootstrap-fatal-exit-guard' export const BOOTSTRAP_FATAL_LOG_ENV_VAR = 'ORCA_BOOTSTRAP_FATAL_LOG' export const BOOTSTRAP_FATAL_LOG_FILE_NAME = 'bootstrap-fatal.log' const BOOTSTRAP_FATAL_LOG_MAX_BYTES = 262_144 diff --git a/config/build-plugins/cli-main-entry-names.ts b/config/build-plugins/cli-main-entry-names.ts index a5489423531..791768ff519 100644 --- a/config/build-plugins/cli-main-entry-names.ts +++ b/config/build-plugins/cli-main-entry-names.ts @@ -9,9 +9,11 @@ export const CLI_MAIN_ENTRY_NAMES = [ 'skills/bundled-skill-install/bundled-skill-local-host', 'skills/bundled-skill-install/bundled-skill-installation', 'filesystem/macos-tree-clone', - 'orcad/orcad-stale-lock-reclaim', - 'orcad/orcad-host-identity-reset', - 'plugins/plugin-authoring-checks', + 'orcad/instance-lock/orcad-stale-lock-reclaim', + 'orcad/profile-state/orcad-host-identity-reset', + 'plugins/plugin-artifact-validation', + 'plugins/plugin-content-hash', + 'plugins/plugin-catalog-release-entry', // `orca vm env doctor` runs its checks in the CLI process. 'environment-doctor/environment-doctor', 'environment-doctor/environment-doctor-host', @@ -25,5 +27,5 @@ export const CLI_MAIN_ENTRY_NAMES = [ 'persistence/profile-state/recovery/profile-state-recovery-command', 'persistence/profile-state/legacy-json/profile-state-export-path', 'persistence/profile-state/legacy-json/profile-state-recovery', - 'startup/http1-compatibility-marker' + 'startup/network-compatibility/http1-compatibility-marker' ] as const diff --git a/config/build-plugins/main-build-entry-points.ts b/config/build-plugins/main-build-entry-points.ts index d62affdbd34..c2df19ac390 100644 --- a/config/build-plugins/main-build-entry-points.ts +++ b/config/build-plugins/main-build-entry-points.ts @@ -16,7 +16,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record = { ), 'computer-sidecar': resolve('src/main/computer/computer-sidecar.ts'), 'claude-conversation-fork-worker-entry': resolve( - 'src/main/claude/claude-conversation-fork-worker-entry.ts' + 'src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts' ), 'stt-worker': resolve('src/main/speech/stt-worker.ts'), 'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'), @@ -26,11 +26,14 @@ export const MAIN_BUILD_ENTRY_POINTS: Record = { 'foreign-sqlite-reader-entry': resolve( 'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts' ), + 'agent-identity-worker-entry': resolve( + 'src/main/agent-hooks/identity/agent-identity-worker-entry.ts' + ), 'session-scanner-service-entry': resolve( 'src/main/ai-vault/scan-service/session-scanner-service-entry.ts' ), 'wsl-transcript-fs-process-entry': resolve( - 'src/main/native-chat/wsl-transcript-fs-process-entry.ts' + 'src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-entry.ts' ), // libuv spawns inline; run port probes on a worker to keep the UI loop free. 'port-scan-command-worker-entry': resolve('src/main/ports/port-scan-command-worker-entry.ts'), diff --git a/config/build-plugins/worker-thread-entry-names.ts b/config/build-plugins/worker-thread-entry-names.ts index 3f72cea6df2..d7dbee7cf84 100644 --- a/config/build-plugins/worker-thread-entry-names.ts +++ b/config/build-plugins/worker-thread-entry-names.ts @@ -2,6 +2,7 @@ export const WORKER_THREAD_ENTRY_NAMES = [ 'warp-theme-parser-worker', 'foreign-sqlite-reader-entry', + 'agent-identity-worker-entry', 'session-search-worker-entry', 'main-thread-hang-watchdog-entry', 'port-scan-command-worker-entry', diff --git a/config/daemon-blocking-call-baseline.txt b/config/daemon-blocking-call-baseline.txt index 66d82518654..bdd5065bf0b 100644 --- a/config/daemon-blocking-call-baseline.txt +++ b/config/daemon-blocking-call-baseline.txt @@ -8,7 +8,7 @@ 2 src/main/daemon/transport/stream/daemon-stream-backlog-probe.ts 1 src/main/daemon/process-scopes/daemon-user-manager-lifetime.ts 1 src/main/daemon/process-scopes/terminal-scopes.ts -2 src/main/orcad/node-pty-precondition.ts +2 src/main/orcad/native-runtime/node-pty-precondition.ts 1 src/main/pty/process-retirement/posix-pty-process-table.ts 1 src/main/pty/shell-startup/pwsh.ts 2 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts diff --git a/config/docker/cli-launch-contract/run-cli-case.sh b/config/docker/cli-launch-contract/run-cli-case.sh index 3293601f22f..9ec52f8db61 100755 --- a/config/docker/cli-launch-contract/run-cli-case.sh +++ b/config/docker/cli-launch-contract/run-cli-case.sh @@ -32,18 +32,11 @@ fi case "$case_name" in # The bundled launcher must stay in Electron's node mode. - nofuse-userns-bundled-help) command=("$launcher" --help) ;; - nofuse-userns-bundled-version) command=("$launcher" --version) ;; nofuse-userns-bundled-status) command=("$launcher" status) ;; - nofuse-userns-bundled-skills) command=("$launcher" skills --help) ;; - nofuse-userns-bundled-worktree) command=("$launcher" worktree list) ;; # Direct binaries must hand off before Ozone initializes. nofuse-nosandbox-direct-binary-skills) command=("$extracted_root/orca-ide" --no-sandbox skills --help) ;; - nofuse-nosandbox-direct-binary-gui) - command=("$extracted_root/orca-ide" --no-sandbox) - ;; stale-display-nosandbox-direct-binary-gui) command=("$extracted_root/orca-ide" --no-sandbox) ;; @@ -62,15 +55,6 @@ if ((status == 124)); then exit 94 fi -if [[ "$case_name" == nofuse-userns-bundled-version ]]; then - version_file="$extracted_root/resources/app.asar.unpacked/out/package.json" - expected_version=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$version_file") - if [[ -z "$expected_version" || "$output" != "$expected_version" ]]; then - output="VERSION_MISMATCH expected=${expected_version:-missing} got=$output" - status=93 - fi -fi - # Shell signal exits are reported as 128 plus the signal number. if ((status >= 128)); then echo "CRASHED status=$status case=$case_name" diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 2df9f8177df..c6531b87a38 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -5,6 +5,9 @@ const { MACOS_FOLDER_USAGE_DESCRIPTIONS, applyMacHelperFolderUsageDescriptions } = require('./scripts/desktop-distribution/macos/macos-folder-usage-descriptions.cjs') +const { + giveMacExecutableUniqueUuid +} = require('./scripts/desktop-distribution/macos/macos-executable-uuid.cjs') const electronBuilderNativeRebuild = require('./scripts/desktop-distribution/runtime-verification/electron-builder-native-rebuild.cjs') const { assertPackagedDaemonEntryExists, @@ -348,26 +351,29 @@ module.exports = { 'out/main/filesystem/macos-tree-clone.js', 'out/main/orca-profiles/profile-index-store.js', 'out/main/persistence/profile-state/**', - 'out/main/plugins/plugin-authoring-checks.js', + 'out/main/plugins/plugin-artifact-validation.js', + 'out/main/plugins/plugin-content-hash.js', + 'out/main/plugins/plugin-catalog-release-entry.js', 'out/main/environment-doctor/environment-doctor.js', 'out/main/environment-doctor/environment-doctor-host.js', // `orca plugin test` and `orca plugin check` load the runtime, kit and hooks in Node. 'resources/plugins/declarative/*.mjs', 'out/main/skills/bundled-skill-install/bundled-skill-local-host.js', 'out/main/skills/bundled-skill-install/bundled-skill-installation.js', - 'out/main/startup/http1-compatibility-marker.js', + 'out/main/startup/network-compatibility/http1-compatibility-marker.js', 'out/main/daemon-entry.js', 'out/main/session-scanner-service-entry.js', 'out/main/wsl-transcript-fs-process-entry.js', 'out/main/foreign-sqlite-reader-entry.js', + 'out/main/agent-identity-worker-entry.js', 'out/main/session-search-worker-entry.js', 'out/main/plugin-host-entry.js', 'out/main/browser-extension-native-host-supervisor-entry.js', 'out/main/computer-sidecar.js', 'out/main/parcel-watcher-process-entry.js', 'out/main/orcad/orcad-local-serve-selection-entry.js', - 'out/main/orcad/orcad-stale-lock-reclaim.js', - 'out/main/orcad/orcad-host-identity-reset.js', + 'out/main/orcad/instance-lock/orcad-stale-lock-reclaim.js', + 'out/main/orcad/profile-state/orcad-host-identity-reset.js', 'out/main/chunks/**', 'out/renderer/**', 'out/mobile-web/**', @@ -423,6 +429,17 @@ module.exports = { join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`), context.packager.appInfo.productFilename ) + // Before signing, so the signature seals the rewritten executable. + giveMacExecutableUniqueUuid( + join( + context.appOutDir, + `${context.packager.appInfo.productFilename}.app`, + 'Contents', + 'MacOS', + context.packager.appInfo.productFilename + ), + context.packager.appInfo.id + ) const architecture = macSliceArch(context.arch, 'local-build compatibility') const schedulingAddon = buildMacShipItScheduling(resourcesDir, architecture) await signMacStandaloneHelper(schedulingAddon, 'ShipIt scheduling', context.packager) diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index f785b8502aa..1b522a11672 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -5,7 +5,6 @@ 4 test-no-in-test-import-actual:src/main/bitbucket/credential-store.test.ts 1 test-no-in-test-import-actual:src/main/bitbucket/status-no-decrypt.test.ts 3 test-no-in-test-import-actual:src/main/claude-usage/scanner-scan.test.ts -1 test-no-in-test-import-actual:src/main/claude/claude-agent-sdk-process-spawn.test.ts 5 test-no-in-test-import-actual:src/main/daemon/endpoint/publication/testing/daemon-endpoint-publish.test.ts 1 test-no-in-test-import-actual:src/main/daemon/history/storage/testing/terminal-history-permissions.test.ts 1 test-no-in-test-import-actual:src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts @@ -14,28 +13,18 @@ 1 test-no-in-test-import-actual:src/main/linear/issues/linear-description-images.test.ts 1 test-no-in-test-import-actual:src/main/managed-server/host-state/orcad-snapshot-room.test.ts 1 test-no-in-test-import-actual:src/main/omp/omp-session-cwd-lookup.test.ts -1 test-no-in-test-import-actual:src/main/orcad/electron-serve-provider-selection.test.ts 1 test-no-in-test-import-actual:src/main/pty/scrollback/overlay-mirror.test.ts 1 test-no-in-test-import-actual:src/main/runtime/rpc/server/pairing/mobile-pairing-userdata-path.test.ts 1 test-no-in-test-import-actual:src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-swap-detection.test.ts 1 test-no-in-test-import-actual:src/main/speech/openai-api-key-store.test.ts 5 test-no-in-test-import-actual:src/main/ssh/config/ssh-config-loader-regression.test.ts 2 test-no-in-test-import-actual:src/main/ssh/connection/ssh-connection-auth-fallback.test.ts -1 test-no-in-test-import-actual:src/main/window/dropped-path-preparation.test.ts -2 test-no-in-test-import-actual:src/main/workspace-hooks/hooks-runner.test.ts +1 test-no-in-test-import-actual:src/main/window/file-drop/dropped-path-preparation.test.ts 1 test-no-in-test-import-actual:src/main/workspaces/removal/local-worktree-removal-recovery.test.ts 1 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-idle-arbitration.test.ts 3 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts 1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts 1 test-no-polling-loop:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts -1 test-no-polling-loop:src/main/claude/claude-stop-ack-race.test.ts -1 test-no-polling-loop:src/main/claude/claude-stream-json-connection.test.ts -1 test-no-polling-loop:src/main/claude/claude-supervised-stop-real-cli.test.ts -1 test-no-polling-loop:src/main/claude/claude-supervised-stop.integration.test.ts -1 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli-fold.test.ts -1 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts -5 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli.test.ts -1 test-no-polling-loop:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts 1 test-no-polling-loop:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts 1 test-no-polling-loop:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts 1 test-no-polling-loop:src/main/daemon/providers/adapter/testing/daemon-self-retirement-respawn.test.ts @@ -45,24 +34,20 @@ 1 test-no-polling-loop:src/main/daemon/sessions/testing/repro-12101-mouse-tracking-survives-agent-death.test.ts 1 test-no-polling-loop:src/main/daemon/transport/client/testing/client.test.ts 2 test-no-polling-loop:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts -1 test-no-polling-loop:src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts 1 test-no-polling-loop:src/main/ipc/worktrees/creation/worktree-base-directory-poller-marker-fanout.test.ts -2 test-no-polling-loop:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts 1 test-no-polling-loop:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 1 test-no-polling-loop:src/main/provider-process/provider-process-supervisor.integration.test.ts -1 test-no-polling-loop:src/main/providers/startup-line-typed-length.live-shell.test.ts 1 test-no-polling-loop:src/main/pty/history/terminal-history-fish-session.node-pty.test.ts 1 test-no-polling-loop:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts 1 test-no-polling-loop:src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts 1 test-no-polling-loop:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts -1 test-no-polling-loop:src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts 1 test-no-polling-loop:src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts 3 test-no-polling-loop:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 2 test-no-polling-loop:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts 1 test-no-polling-loop:src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts 1 test-no-polling-loop:src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts -2 test-no-polling-loop:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts -1 test-no-polling-loop:src/main/startup/run-electron-vite-dev.test.ts +2 test-no-polling-loop:src/main/startup/gpu-recovery/gpu-lifecycle-install-dir-acl-guard.test.ts +1 test-no-polling-loop:config/scripts/development/launch/run-electron-vite-dev.test.ts 2 test-no-polling-loop:src/main/windows/windows-host-job.win32.test.ts 1 test-no-polling-loop:src/main/windows/windows-pty-job.win32.test.ts 1 test-no-polling-loop:src/main/worker-thread-child-process/worker-thread-child-process.test.ts @@ -82,7 +67,6 @@ 1 test-no-polling-loop:tests/e2e/browser-tab.spec.ts 1 test-no-polling-loop:tests/e2e/chinese-ime-chat-input-repro.spec.ts 3 test-no-polling-loop:tests/e2e/combined-diff-scroll-restore.spec.ts -1 test-no-polling-loop:tests/e2e/computer-windows.e2e.ts 1 test-no-polling-loop:tests/e2e/cross-version-wire/released-relay-daemon.ts 1 test-no-polling-loop:tests/e2e/cross-version-wire/released-relay-transport.ts 1 test-no-polling-loop:tests/e2e/daemon-lifecycle-retirement.spec.ts @@ -135,7 +119,6 @@ 1 test-no-polling-loop:tests/e2e/terminal-tui-wheel-reports.spec.ts 1 test-no-polling-loop:tests/e2e/workspace-sleep-in-main.spec.ts 2 test-no-polling-loop:tests/e2e/worktree-card-downward-drag.spec.ts -1 test-no-real-time-wait:mobile/src/terminal/terminal-webview-tap-routing.test.ts 1 test-no-real-time-wait:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts 2 test-no-real-time-wait:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts 1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts @@ -151,16 +134,6 @@ 1 test-no-real-time-wait:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts 1 test-no-real-time-wait:src/main/browser/network/tunnels/execution-route-socket-duplex.test.ts 1 test-no-real-time-wait:src/main/browser/network/tunnels/remote-browser-socks-server.test.ts -1 test-no-real-time-wait:src/main/claude/claude-agent-sdk-exit-proof.test.ts -1 test-no-real-time-wait:src/main/claude/claude-agent-sdk-user-message-queue.test.ts -1 test-no-real-time-wait:src/main/claude/claude-stop-ack-race.test.ts -1 test-no-real-time-wait:src/main/claude/claude-stream-json-connection.test.ts -1 test-no-real-time-wait:src/main/claude/claude-supervised-stop-real-cli.test.ts -1 test-no-real-time-wait:src/main/claude/claude-supervised-stop.integration.test.ts -2 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli-fold.test.ts -2 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts -5 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli.test.ts -1 test-no-real-time-wait:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts 1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts 1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts 1 test-no-real-time-wait:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts @@ -188,48 +161,36 @@ 4 test-no-real-time-wait:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts 1 test-no-real-time-wait:src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts 1 test-no-real-time-wait:src/main/grok/grok-hook-stdin-no-eof.test.ts -4 test-no-real-time-wait:src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts 1 test-no-real-time-wait:src/main/ipc/worktrees/creation/worktree-base-directory-poller-marker-fanout.test.ts -2 test-no-real-time-wait:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts 1 test-no-real-time-wait:src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-quit.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-target-reconcile.test.ts 1 test-no-real-time-wait:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 2 test-no-real-time-wait:src/main/provider-process/provider-process-supervisor.integration.test.ts -1 test-no-real-time-wait:src/main/providers/agent-foreground-process-git-bash.win32.test.ts -2 test-no-real-time-wait:src/main/providers/startup-line-typed-length.live-shell.test.ts 2 test-no-real-time-wait:src/main/pty/history/terminal-history-fish-session.node-pty.test.ts 1 test-no-real-time-wait:src/main/pty/process-retirement/node-pty-master-fd-retirement.test.ts 1 test-no-real-time-wait:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts 5 test-no-real-time-wait:src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts 1 test-no-real-time-wait:src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts 3 test-no-real-time-wait:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/terminal-subscribe-admission.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/terminal-subscribe-mounted-pane.test.ts -3 test-no-real-time-wait:src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/ws-transport.test.ts +1 test-no-real-time-wait:src/main/runtime/rpc/terminal/terminal-subscribe-mounted-pane.test.ts 1 test-no-real-time-wait:src/main/runtime/terminal/recovery/layout-command-pane-starts-layout-owner.test.ts 1 test-no-real-time-wait:src/main/runtime/terminal/recovery/restored-pane-start-cli-handles.test.ts 1 test-no-real-time-wait:src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts 1 test-no-real-time-wait:src/main/runtime/terminal/wait/launched-agent-shell-handoff-readiness.test.ts -2 test-no-real-time-wait:src/main/runtime/terminal/wait/tui-idle-name-only-real-pty.integration.test.ts 1 test-no-real-time-wait:src/main/runtime/workspaces/removal/owned-session-teardown-policy.test.ts -3 test-no-real-time-wait:src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts +1 test-no-real-time-wait:src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts 1 test-no-real-time-wait:src/main/skills/cloud/skill-cloud-direct-upload.test.ts 3 test-no-real-time-wait:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 2 test-no-real-time-wait:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts 1 test-no-real-time-wait:src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts 1 test-no-real-time-wait:src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts -2 test-no-real-time-wait:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts -3 test-no-real-time-wait:src/main/startup/run-electron-vite-dev.test.ts -2 test-no-real-time-wait:src/main/startup/windows-install-dir-acl-recovery.test.ts +2 test-no-real-time-wait:src/main/startup/gpu-recovery/gpu-lifecycle-install-dir-acl-guard.test.ts +3 test-no-real-time-wait:config/scripts/development/launch/run-electron-vite-dev.test.ts 1 test-no-real-time-wait:src/main/updater/lifecycle/serve-supervisor-install-park.test.ts -1 test-no-real-time-wait:src/main/updater/updater.quit-and-install.test.ts -1 test-no-real-time-wait:src/main/window/main-window-updater-deferred-setup.test.ts +1 test-no-real-time-wait:src/main/updater/lifecycle/main-window-updater-deferred-setup.test.ts 3 test-no-real-time-wait:src/main/windows/windows-host-job.win32.test.ts 1 test-no-real-time-wait:src/main/windows/windows-process-tree-command-line-patch.test.ts 2 test-no-real-time-wait:src/main/windows/windows-pty-job.win32.test.ts @@ -249,15 +210,14 @@ 1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts 2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts 2 test-no-real-time-wait:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts -1 test-no-real-time-wait:src/shared/darwin-process-table-capture.test.ts 1 test-no-real-time-wait:src/shared/darwin-terminal-names-real-ps.test.ts 1 test-no-real-time-wait:src/shared/darwin-terminal-names.test.ts 1 test-no-real-time-wait:src/shared/git/status/git-branch-line-total-soft-deadline.test.ts 2 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-auth-refusal.test.ts 2 test-no-real-time-wait:src/shared/startup-command-staging.node-pty.test.ts 4 test-no-real-time-wait:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts -1 test-no-real-time-wait:src/wsl-guest/agent-hook-canonical-status.test.ts -5 test-no-real-time-wait:src/wsl-guest/agent-hook-server.test.ts +1 test-no-real-time-wait:src/wsl-guest/agent-hooks/status/agent-hook-canonical-status.test.ts +5 test-no-real-time-wait:src/wsl-guest/agent-hooks/server/agent-hook-server.test.ts 1 test-no-real-time-wait:tests/e2e/accumulated-workspace-status-fixture.ts 1 test-no-real-time-wait:tests/e2e/agent-session-live-force-exit-resume.spec.ts 3 test-no-real-time-wait:tests/e2e/agent-session-log-tail-stability.spec.ts @@ -270,8 +230,6 @@ 2 test-no-real-time-wait:tests/e2e/cli-floating-file-open-position.spec.ts 1 test-no-real-time-wait:tests/e2e/codex-ctrl-c-status.spec.ts 4 test-no-real-time-wait:tests/e2e/combined-diff-scroll-restore.spec.ts -1 test-no-real-time-wait:tests/e2e/computer-windows.e2e.ts -3 test-no-real-time-wait:tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts 1 test-no-real-time-wait:tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts 1 test-no-real-time-wait:tests/e2e/cross-version-wire/released-relay-daemon.ts 2 test-no-real-time-wait:tests/e2e/cross-version-wire/released-relay-transport.ts @@ -323,7 +281,7 @@ 1 test-no-real-time-wait:tests/e2e/markdown-table-row-backspace.spec.ts 1 test-no-real-time-wait:tests/e2e/native-chat-history-prepend-anchor.spec.ts 3 test-no-real-time-wait:tests/e2e/notification-sound-replay.spec.ts -5 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-delivery.spec.ts +4 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-delivery.spec.ts 1 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-restore.spec.ts 4 test-no-real-time-wait:tests/e2e/paced-terminal-typing.ts 1 test-no-real-time-wait:tests/e2e/paired-client-hosted-browser-double-restart.spec.ts @@ -427,30 +385,19 @@ 2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts 1 test-no-wall-clock:src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts 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 +3 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts 3 test-no-wall-clock:src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.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 1 test-no-wall-clock:src/main/ai-vault/scanners/devin/session-scanner-devin-db.test.ts 2 test-no-wall-clock:src/main/ai-vault/scanners/grok/session-scanner-grok-parser.test.ts -1 test-no-wall-clock:src/main/ai-vault/scanners/kimi/session-scanner-kimi-parser.test.ts 1 test-no-wall-clock:src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts 2 test-no-wall-clock:src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.test.ts 2 test-no-wall-clock:src/main/antigravity/posix-hook-invocation.test.ts 2 test-no-wall-clock:src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts 2 test-no-wall-clock:src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts -1 test-no-wall-clock:src/main/claude/claude-background-wake-retention.test.ts -1 test-no-wall-clock:src/main/claude/claude-descendant-escalation-boundary.test.ts -1 test-no-wall-clock:src/main/claude/claude-folder-trust-file.test.ts -5 test-no-wall-clock:src/main/claude/claude-supervised-stop-real-cli.test.ts -6 test-no-wall-clock:src/main/claude/claude-supervised-stop.integration.test.ts -4 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-fold.test.ts -1 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-rewind.test.ts -3 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts -10 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli.test.ts -3 test-no-wall-clock:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts -1 test-no-wall-clock:src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts +1 test-no-wall-clock:src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-rollback-script.test.ts 6 test-no-wall-clock:src/main/codex/app-server/codex-app-server-client.test.ts 2 test-no-wall-clock:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts 2 test-no-wall-clock:src/main/codex/trust/hooks/codex-hook-trust-derivation.test.ts @@ -467,24 +414,18 @@ 2 test-no-wall-clock:src/main/external-conversations/external-conversation-cancel-settlement.test.ts 3 test-no-wall-clock:src/main/external-conversations/external-conversation-cancel.test.ts 2 test-no-wall-clock:src/main/git/command-runner/host-routing/git-command-resolution-windows-checkout.test.ts +1 test-no-wall-clock:src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts 1 test-no-wall-clock:src/main/git/refs/maintenance/pack-refs-lock-ownership.test.ts 2 test-no-wall-clock:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts -2 test-no-wall-clock:src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts -1 test-no-wall-clock:src/main/git/source-control/blob-absence-real-git.test.ts +1 test-no-wall-clock:src/main/git/source-control/diffs/blob-absence-real-git.test.ts 2 test-no-wall-clock:src/main/git/worktrees/catalog/worktree-created-description-real-git.test.ts -3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts -8 test-no-wall-clock:src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts -5 test-no-wall-clock:src/main/github/pr-refresh-coordinator-completion-order.test.ts -3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts -3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-refresh-events.test.ts -4 test-no-wall-clock:src/main/github/pr-refresh-coordinator-visibility-policy.test.ts -3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-visible-follow-up.test.ts -4 test-no-wall-clock:src/main/github/pr-refresh-queue-growth-bound.test.ts +3 test-no-wall-clock:src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts +8 test-no-wall-clock:src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts +3 test-no-wall-clock:src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts +2 test-no-wall-clock:src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts 2 test-no-wall-clock:src/main/grok/grok-hook-stdin-no-eof.test.ts -3 test-no-wall-clock:src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts 1 test-no-wall-clock:src/main/ipc/terminal-render-desync-evidence.test.ts -5 test-no-wall-clock:src/main/ipc/worktrees-orphan-directory-cleanup.test.ts -2 test-no-wall-clock:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts +2 test-no-wall-clock:src/main/ipc/worktrees-orphan-directory-cleanup.test.ts 2 test-no-wall-clock:src/main/macos-permissions/macos-tcc-log-stream-orphans.test.ts 4 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts 6 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence.test.ts @@ -498,19 +439,17 @@ 1 test-no-wall-clock:src/main/opencode/status-hooks/overlay-dir-gc.test.ts 2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts 2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts -2 test-no-wall-clock:src/main/orcad/orcad-artifact-cache-retention.test.ts -1 test-no-wall-clock:src/main/orcad/orcad-artifact-materializer.test.ts -6 test-no-wall-clock:src/main/orcad/orcad-serve-parity.integration.test.ts -1 test-no-wall-clock:src/main/orcad/orcad-stale-lock-reclaim.test.ts -3 test-no-wall-clock:src/main/orcad/orcad-stop-request-shutdown.integration.test.ts +2 test-no-wall-clock:src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts +1 test-no-wall-clock:src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts +6 test-no-wall-clock:src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts +1 test-no-wall-clock:src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts +3 test-no-wall-clock:src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts 1 test-no-wall-clock:src/main/persistence/closed-terminal-tab-write-fence.test.ts 1 test-no-wall-clock:src/main/persistence/profile-state/backup/profile-state-backup-rotation.test.ts 1 test-no-wall-clock:src/main/persistence/profile-state/recovery/profile-state-section-repair.test.ts 2 test-no-wall-clock:src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts -1 test-no-wall-clock:src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts 2 test-no-wall-clock:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 4 test-no-wall-clock:src/main/provider-process/provider-process-supervisor.integration.test.ts -2 test-no-wall-clock:src/main/providers/startup-line-typed-length.live-shell.test.ts 2 test-no-wall-clock:src/main/pty/history/terminal-history-fish-session.node-pty.test.ts 1 test-no-wall-clock:src/main/pty/history/terminal-history-gc-fs-call-count.test.ts 2 test-no-wall-clock:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts @@ -522,25 +461,19 @@ 1 test-no-wall-clock:src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts 2 test-no-wall-clock:src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts 1 test-no-wall-clock:src/main/runtime/agent-session/structured-child-records-switch.test.ts -1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts +1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts 2 test-no-wall-clock:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts -2 test-no-wall-clock:src/main/runtime/orchestration/workers/archives/worker-output-archive.test.ts -3 test-no-wall-clock:src/main/runtime/orchestration/workers/archives/worker-terminal-archive-release.test.ts -4 test-no-wall-clock:src/main/runtime/orchestration/workers/archives/worker-terminal-archive-screen.test.ts -5 test-no-wall-clock:src/main/runtime/orchestration/workers/archives/worker-terminal-wrap-provenance.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-device-registration-persistence.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-registration-rpc.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-unpair-persistence.test.ts 1 test-no-wall-clock:src/main/runtime/rpc/methods/agent-launch/agent-launch-prestart-failure.test.ts 1 test-no-wall-clock:src/main/runtime/rpc/methods/agent-launch/agent-launch-replay.test.ts -2 test-no-wall-clock:src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts 1 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/federation/federation-output.test.ts -2 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts -1 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts -1 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/worker/worker-output.test.ts +2 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/worker/observation/fleet-status-observed-identity.test.ts +1 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts 2 test-no-wall-clock:src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts 2 test-no-wall-clock:src/main/runtime/rpc/server/runtime-rpc-pairing-mode-persistence.test.ts -7 test-no-wall-clock:src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts +6 test-no-wall-clock:src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts 1 test-no-wall-clock:src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts 1 test-no-wall-clock:src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts 1 test-no-wall-clock:src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts @@ -548,8 +481,7 @@ 23 test-no-wall-clock:src/main/runtime/terminal/output/terminal-query-responder.test.ts 3 test-no-wall-clock:src/main/runtime/terminal/query/orca-runtime-codex-idle-title-chat-address.test.ts 1 test-no-wall-clock:src/main/runtime/terminal/recovery/terminal-pane-recovery-liveness-gate.test.ts -16 test-no-wall-clock:src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts -4 test-no-wall-clock:src/main/runtime/terminal/wait/tui-idle-name-only-real-pty.integration.test.ts +4 test-no-wall-clock:src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts 1 test-no-wall-clock:src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts 1 test-no-wall-clock:src/main/runtime/workspaces/removal/owned-session-teardown-policy.test.ts 6 test-no-wall-clock:src/main/skills/install/skill-bundle-process-termination.integration.test.ts @@ -562,12 +494,9 @@ 2 test-no-wall-clock:src/main/skills/transaction-state/skill-transaction-startup-recovery.test.ts 4 test-no-wall-clock:src/main/sqlite/sync-database.test.ts 4 test-no-wall-clock:src/main/ssh/remote-exec/ssh-remote-commands.test.ts -2 test-no-wall-clock:src/main/star-nag/service-direct-star.test.ts -3 test-no-wall-clock:src/main/star-nag/service-threshold-prompt.test.ts -1 test-no-wall-clock:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts -1 test-no-wall-clock:src/main/startup/login-shell-environment.test.ts -2 test-no-wall-clock:src/main/startup/run-electron-vite-dev.test.ts -13 test-no-wall-clock:src/main/startup/windows-install-dir-acl-recovery.test.ts +2 test-no-wall-clock:config/scripts/development/launch/run-electron-vite-dev.test.ts +1 test-no-wall-clock:src/main/startup/shell-environment/login-shell-environment.test.ts +2 test-no-wall-clock:src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.test.ts 4 test-no-wall-clock:src/main/updater/lifecycle/serve-supervisor-install-park.test.ts 1 test-no-wall-clock:src/main/window/desktop-integration/macos-press-and-hold-default.defaults-domain.test.ts 2 test-no-wall-clock:src/main/windows/windows-host-job.win32.test.ts @@ -581,14 +510,13 @@ 3 test-no-wall-clock:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx 2 test-no-wall-clock:src/renderer/src/components/artifacts/ArtifactCollection.test.tsx 1 test-no-wall-clock:src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx -3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx 2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts 1 test-no-wall-clock:src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx -2 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx +2 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/removal/use-workspace-cleanup-removal.agent-stop.test.tsx 1 test-no-wall-clock:src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.behavior.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts 1 test-no-wall-clock:src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts @@ -603,18 +531,17 @@ 2 test-no-wall-clock:src/shared/startup-command-staging.node-pty.test.ts 1 test-no-wall-clock:src/shared/startup-command-staging.test.ts 2 test-no-wall-clock:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts -10 test-no-wall-clock:src/wsl-guest/agent-hook-integration.test.ts -1 test-no-wall-clock:src/wsl-guest/agent-hook-opencode-tui-identity.test.ts -1 test-no-wall-clock:src/wsl-guest/agent-hook-server.test.ts -1 test-no-wall-clock:src/wsl-guest/relay-idle-process-owner.test.ts +10 test-no-wall-clock:src/wsl-guest/agent-hooks/publication/agent-hook-integration.test.ts +1 test-no-wall-clock:src/wsl-guest/agent-hooks/server/agent-hook-server.test.ts +1 test-no-wall-clock:src/wsl-guest/agent-hooks/presence/relay-idle-process-owner.test.ts 1 test-no-wall-clock:tests/e2e/cross-version-wire/cross-version-web-device-key.unit.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts 4 test-no-wall-clock:tests/e2e/cross-version-wire/release-checkout.unit.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/release-source-retention.unit.test.ts 1 test-no-wall-clock:tests/e2e/host-cold-park-remote-subscriber.unit.test.ts -1 test-timeout-needs-reason:src/cli/agent-launch-process.test.ts +1 test-timeout-needs-reason:src/cli/agents/agent-launch-process.test.ts 1 test-timeout-needs-reason:src/cli/runtime/serve-pid1-init-reaper.test.ts -1 test-timeout-needs-reason:src/cli/skills-install.test.ts +1 test-timeout-needs-reason:src/cli/skills/skills-install.test.ts 2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts 4 test-timeout-needs-reason:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts 1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts @@ -632,12 +559,6 @@ 1 test-timeout-needs-reason:src/main/browser/guest-lifecycle/find/browser-find-frame-traversal.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts -1 test-timeout-needs-reason:src/main/claude/claude-agent-sdk-exit-proof.test.ts -1 test-timeout-needs-reason:src/main/claude/claude-background-run-isolation-real-cli.test.ts -2 test-timeout-needs-reason:src/main/claude/claude-status-line-windows.test.ts -1 test-timeout-needs-reason:src/main/claude/claude-stop-ack-race.test.ts -1 test-timeout-needs-reason:src/main/claude/structured/claude-structured-real-cli.test.ts -1 test-timeout-needs-reason:src/main/claude/windows-native-hook-registration.test.ts 2 test-timeout-needs-reason:src/main/codex/app-server/codex-app-server-teardown.integration.test.ts 1 test-timeout-needs-reason:src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts 1 test-timeout-needs-reason:src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts @@ -656,59 +577,47 @@ 2 test-timeout-needs-reason:src/main/daemon/pty-subprocess/testing/node-pty-windows-input-error.win32.test.ts 1 test-timeout-needs-reason:src/main/daemon/pty-subprocess/testing/node-pty-windows-output-error.win32.test.ts 4 test-timeout-needs-reason:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts -1 test-timeout-needs-reason:src/main/git/worktrees/removal/worktree-removal-real-git.test.ts 1 test-timeout-needs-reason:src/main/ipc/filesystem/filesystem-quick-open-options.integration.test.ts 1 test-timeout-needs-reason:src/main/ipc/preflight-runnable-local-cli.test.ts -1 test-timeout-needs-reason:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts 1 test-timeout-needs-reason:src/main/jcode/hook-gate-script.test.ts 1 test-timeout-needs-reason:src/main/managed-server/host-state/orcad-state-mutation-fence-heartbeat.test.ts 1 test-timeout-needs-reason:src/main/managed-server/host-state/orcad-windows-host-lane.test.ts 4 test-timeout-needs-reason:src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts 3 test-timeout-needs-reason:src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts 1 test-timeout-needs-reason:src/main/notebook/notebook-kernel.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-bundle-native-load-order.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-packaged-node-pty.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-packaged-structured-chat.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-serve-parity.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-stop-request-shutdown.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts +1 test-timeout-needs-reason:src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts 1 test-timeout-needs-reason:src/main/persistence/applying-settings/persistence-source-control-ai-migration.test.ts -2 test-timeout-needs-reason:src/main/providers/agent-foreground-process-git-bash.win32.test.ts -1 test-timeout-needs-reason:src/main/providers/local-pty/local-pty-child-process-verdict.test.ts -2 test-timeout-needs-reason:src/main/providers/startup-line-typed-length.live-shell.test.ts 5 test-timeout-needs-reason:src/main/pty/process-retirement/node-pty-master-fd-retirement.test.ts -1 test-timeout-needs-reason:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts +1 test-timeout-needs-reason:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts 1 test-timeout-needs-reason:src/main/runtime/rpc/server/orchestration-cli-subprocess.test.ts 2 test-timeout-needs-reason:src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts -1 test-timeout-needs-reason:src/main/runtime/rpc/ws-transport.test.ts 1 test-timeout-needs-reason:src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts 1 test-timeout-needs-reason:src/main/runtime/terminal/launch/qoder-mobile-resume-adoption.test.ts 2 test-timeout-needs-reason:src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts -3 test-timeout-needs-reason:src/main/runtime/terminal/wait/terminal-interactive-wait-visibility.test.ts +2 test-timeout-needs-reason:src/main/runtime/terminal/wait/terminal-interactive-wait-visibility.test.ts 1 test-timeout-needs-reason:src/main/runtime/terminal/wait/terminal-wait-name-only-idle.test.ts -4 test-timeout-needs-reason:src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts -3 test-timeout-needs-reason:src/main/runtime/terminal/wait/tui-idle-name-only-real-pty.integration.test.ts 1 test-timeout-needs-reason:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 1 test-timeout-needs-reason:src/main/sqlite/sync-database-concurrent-backup.test.ts 2 test-timeout-needs-reason:src/main/ssh/connection/ssh-connection-sftp-wire.test.ts 2 test-timeout-needs-reason:src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts -2 test-timeout-needs-reason:src/main/startup/single-instance-lock-exit.electron.test.ts -1 test-timeout-needs-reason:src/main/window/renderer-publication-throttle.electron.test.ts +1 test-timeout-needs-reason:src/main/window/visibility/renderer-publication-throttle.electron.test.ts 1 test-timeout-needs-reason:src/main/windows/windows-administrator-restart.win32.test.ts 1 test-timeout-needs-reason:src/main/windows/windows-host-job.win32.test.ts 1 test-timeout-needs-reason:src/main/windows/windows-msys-job.win32.test.ts 2 test-timeout-needs-reason:src/main/windows/windows-pty-job.win32.test.ts 5 test-timeout-needs-reason:src/main/worker-thread-child-process/worker-thread-child-process.test.ts -1 test-timeout-needs-reason:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts -2 test-timeout-needs-reason:src/main/workspace-hooks/hook-termination-real-process.test.ts +1 test-timeout-needs-reason:src/main/workspace-hooks/hook-termination-real-process.test.ts 2 test-timeout-needs-reason:src/main/workspaces/removal/local-worktree-filesystem-wsl-banner.wsl.test.ts 4 test-timeout-needs-reason:src/main/wsl/execution/wsl-runner.wsl.test.ts 4 test-timeout-needs-reason:src/packages/process-host/src/run-process.test.ts 1 test-timeout-needs-reason:src/renderer/src/hooks/agent-hook-completion-notifications.test.ts 1 test-timeout-needs-reason:src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts 1 test-timeout-needs-reason:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts -1 test-timeout-needs-reason:src/shared/dsh-real-cli.test.ts -1 test-timeout-needs-reason:src/shared/workspace-disk-space/workspace-space-entry-traversal.test.ts 1 test-timeout-needs-reason:src/shared/wsl-login-shell-command.test.ts 1 test-timeout-needs-reason:tests/e2e/active-view-restart-restore.spec.ts 1 test-timeout-needs-reason:tests/e2e/agent-send-picker-reveal.spec.ts @@ -733,7 +642,6 @@ 1 test-timeout-needs-reason:tests/e2e/daemon-generation-legacy-close-safety.spec.ts 2 test-timeout-needs-reason:tests/e2e/daemon-generation-reconnect-safety.spec.ts 2 test-timeout-needs-reason:tests/e2e/default-tabs-mark-crash-relaunch.spec.ts -1 test-timeout-needs-reason:tests/e2e/desktop-published-split-orientation-legacy-leaf.spec.ts 2 test-timeout-needs-reason:tests/e2e/desktop-window-mobile-markdown.spec.ts 1 test-timeout-needs-reason:tests/e2e/floating-tab-rename.spec.ts 1 test-timeout-needs-reason:tests/e2e/golden-quit-relaunch-session.spec.ts @@ -765,7 +673,7 @@ 1 test-timeout-needs-reason:tests/e2e/markdown-review-selection-performance.spec.ts 1 test-timeout-needs-reason:tests/e2e/mobile-subscribe-idle-hidden-pane-fit.spec.ts 1 test-timeout-needs-reason:tests/e2e/orcad-serve-open-url-on-desktop.spec.ts -10 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-delivery.spec.ts +9 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-delivery.spec.ts 1 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-restore.spec.ts 1 test-timeout-needs-reason:tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts 1 test-timeout-needs-reason:tests/e2e/orchestration-worker-settlement-release-cli.spec.ts @@ -789,10 +697,6 @@ 1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-profile-cookies.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-client-project-removal-stops-host-terminals.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-held-pane-reopen.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-layout-frames.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-layout-intents.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-layout-writes.spec.ts 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 diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 7fc0cfa7341..bef6f0b90de 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -6,23 +6,22 @@ 2 src/renderer/src/App.tsx 3 src/renderer/src/app-shell/ActiveWorkspaceSyncGate.tsx # existing watch selector now visible through useCallback; includes its import-path occurrence 2 src/renderer/src/app-shell/use-app-shell-services.ts +3 src/renderer/src/attention/unread/unread-badge-count-selector.ts 1 src/renderer/src/component-fixtures/component-fixture-explorer.tsx # dev-only fixture page seeds default settings 1 src/renderer/src/components/JiraIssueWorkspace.tsx 1 src/renderer/src/components/Landing.tsx 3 src/renderer/src/components/LinearIssueTextEditor.tsx 3 src/renderer/src/components/LinearIssueWorkspace.tsx 5 src/renderer/src/components/LinearItemDrawer.tsx -1 src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx 1 src/renderer/src/components/activity/ActivityPrototypePage.tsx 1 src/renderer/src/components/activity/activity-scope-filter-controls.tsx 2 src/renderer/src/components/activity/activity-thread-actions.ts 1 src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts 1 src/renderer/src/components/activity/use-agent-pane-threads.ts 4 src/renderer/src/components/agent/AgentSettingsDialog.tsx -1 src/renderer/src/components/automations/hosts/automation-host-client.ts -1 src/renderer/src/components/automations/automations-page-fixtures.ts -1 src/renderer/src/components/automations/use-automations-page-controller.ts 1 src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts +1 src/renderer/src/components/automations/hosts/automation-host-client.ts +1 src/renderer/src/components/automations/use-automations-page-controller.ts 1 src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx 1 src/renderer/src/components/browser-pane/browser-reopen-on-server.ts 1 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts @@ -33,18 +32,16 @@ 1 src/renderer/src/components/editor/EditorEditFileSurface.tsx 1 src/renderer/src/components/editor/EditorMarkdownFileSurface.tsx 1 src/renderer/src/components/editor/csv/csv-link-routing.ts -1 src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts -1 src/renderer/src/components/editor/markdown-preview/links/markdown-preview-system-link-action.ts 2 src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts 1 src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.ts 2 src/renderer/src/components/editor/useEditorPanelContentState.ts 1 src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts -2 src/renderer/src/components/feature-wall/ConnectIntegrationsList.tsx -1 src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx -1 src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx +2 src/renderer/src/components/feature-wall/setup/integrations/ConnectIntegrationsList.tsx +1 src/renderer/src/components/feature-wall/setup/browser/FeatureWallBrowserAction.tsx +1 src/renderer/src/components/feature-wall/setup/FeatureWallSetupChecklist.tsx 1 src/renderer/src/components/feature-wall/FeatureWallTourSurface.tsx -2 src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts -2 src/renderer/src/components/feature-wall/use-integration-connection-status.ts +2 src/renderer/src/components/feature-wall/setup/integrations/use-feature-wall-task-source-presentation.ts +2 src/renderer/src/components/feature-wall/setup/integrations/use-integration-connection-status.ts 1 src/renderer/src/components/floating-terminal/use-floating-terminal-panel-controller.ts 1 src/renderer/src/components/floating-terminal/use-floating-terminal-panel-store-state.ts 1 src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx @@ -64,13 +61,14 @@ 2 src/renderer/src/components/linear-item-drawer-comment-footer.tsx 15 src/renderer/src/components/linear-item-drawer-edit-controller.tsx 1 src/renderer/src/components/linear-item-drawer-edit-section.tsx +1 src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx 1 src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.tsx -1 src/renderer/src/components/new-workspace/use-jira-source-connection.ts -7 src/renderer/src/components/new-workspace/use-linear-source-connection.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts -6 src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts -1 src/renderer/src/components/new-workspace/use-work-item-source-search.ts +1 src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts +7 src/renderer/src/components/new-workspace/source-search/use-linear-source-connection.ts +1 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts +1 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts +6 src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts +1 src/renderer/src/components/new-workspace/source-search/use-work-item-source-search.ts 1 src/renderer/src/components/provider-accounts/provider-account-scope.ts 2 src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-hosted-review-click-routing.ts 1 src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-base-ref-discovery.ts @@ -157,25 +155,24 @@ 1 src/renderer/src/components/tab-bar/windows-shell-menu-visibility.ts 3 src/renderer/src/components/tab-group/useTabGroupCreationCommands.ts 11 src/renderer/src/components/task-page/TaskPage.tsx -2 src/renderer/src/components/task-page/jira/IssueAssigneeField.tsx -1 src/renderer/src/components/task-page/jira/task-page-jira-status-order.ts -4 src/renderer/src/components/task-page/jira/use-task-page-jira-creation-metadata.ts -4 src/renderer/src/components/task-page/jira/use-task-page-jira-issue-creation.ts -1 src/renderer/src/components/task-page/jira/use-task-page-jira-list-effects.ts +2 src/renderer/src/components/task-page/jira/creation/IssueAssigneeField.tsx +1 src/renderer/src/components/task-page/jira/listing/task-page-jira-status-order.ts +4 src/renderer/src/components/task-page/jira/creation/use-task-page-jira-creation-metadata.ts +4 src/renderer/src/components/task-page/jira/creation/use-task-page-jira-issue-creation.ts +1 src/renderer/src/components/task-page/jira/listing/use-task-page-jira-list-effects.ts 1 src/renderer/src/components/task-page/linear/Filters.tsx -4 src/renderer/src/components/task-page/linear/task-page-linear-issue-model.tsx -8 src/renderer/src/components/task-page/linear/use-task-page-linear-board.ts +4 src/renderer/src/components/task-page/linear/issues/task-page-linear-state-cell.tsx +8 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-board.ts 4 src/renderer/src/components/task-page/linear/use-task-page-linear-context-state.ts -6 src/renderer/src/components/task-page/linear/use-task-page-linear-creation-state.ts -4 src/renderer/src/components/task-page/linear/use-task-page-linear-issue-creation.ts -2 src/renderer/src/components/task-page/linear/use-task-page-linear-project-creation.ts +6 src/renderer/src/components/task-page/linear/creation/use-task-page-linear-creation-state.ts +4 src/renderer/src/components/task-page/linear/creation/use-task-page-linear-issue-creation.ts +2 src/renderer/src/components/task-page/linear/creation/use-task-page-linear-project-creation.ts 5 src/renderer/src/components/task-page/linear/use-task-page-linear-view-state.ts 3 src/renderer/src/components/task-page/use-task-page-detail-routing.ts 2 src/renderer/src/components/task-page/use-task-page-provider-metadata.ts 2 src/renderer/src/components/task-page/use-task-page-source-availability.ts 2 src/renderer/src/components/task-page/use-task-page-store-bindings.ts 1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-controller.ts -1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-lifecycle.ts 1 src/renderer/src/components/terminal-pane/layout/close/retire-unbound-runtime-terminal-pane.ts 2 src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-admission.ts 2 src/renderer/src/components/terminal-pane/layout/close/use-terminal-pane-close-actions.ts @@ -205,10 +202,10 @@ 1 src/renderer/src/hooks/ipc-events/settings-sidebar-ipc-bridge.ts 1 src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge.ts 1 src/renderer/src/hooks/skills/discovery/use-active-skill-discovery-runtime-target.ts -2 src/renderer/src/hooks/use-integration-provider-status-refresh.ts -1 src/renderer/src/hooks/skills/runtime/useActiveProjectSkillRuntime.ts -1 src/renderer/src/hooks/useEditorExternalWatch.ts 1 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts +1 src/renderer/src/hooks/skills/runtime/useActiveProjectSkillRuntime.ts +2 src/renderer/src/hooks/use-integration-provider-status-refresh.ts +1 src/renderer/src/hooks/useEditorExternalWatch.ts 1 src/renderer/src/hooks/useIpcEvents.ts 4 src/renderer/src/hooks/useIssueMetadata.ts 2 src/renderer/src/hooks/useLinearIssuePublication.ts @@ -216,51 +213,53 @@ 7 src/renderer/src/hooks/useSettingsNavigationMetadata.ts 1 src/renderer/src/hooks/useUnreadDockBadge.ts 2 src/renderer/src/hooks/useWindowsTerminalCapabilityOwnerKey.ts +1 src/renderer/src/lib/agent-session/resume/history/launch-ai-vault-session.ts 6 src/renderer/src/lib/browser/navigation/http-link-destinations.ts 1 src/renderer/src/lib/browser/navigation/http-link-localhost-route.ts # extracted from http-link-routing.ts 1 src/renderer/src/lib/browser/navigation/http-link-routing.ts 2 src/renderer/src/lib/browser/workspace/workspace-browser-tab-open.ts -1 src/renderer/src/lib/workspace/creation/surface-policy/client-creation-action-error.ts -2 src/renderer/src/lib/workspace/creation/surface-policy/client-creation-action-policy.ts -1 src/renderer/src/runtime/hosts/selection/default-creation-host.ts # the sanctioned reader of the default host -1 src/renderer/src/lib/agent-session/resume/history/launch-ai-vault-session.ts -1 src/renderer/src/runtime/hosts/preflight/local-preflight-context.ts -2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts -2 src/renderer/src/lib/workspace/ownership/repo-runtime-owner.ts -1 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts -1 src/renderer/src/runtime/web-session-tabs-sync/subscriptions/runtime-session-mirror-targets.ts -1 src/renderer/src/lib/workspace/ownership/single-runtime-legacy-owner.ts 1 src/renderer/src/lib/skills/runtime/skill-runtime-command.ts -1 src/renderer/src/lib/workspace/ownership/terminal-close-route.ts -4 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers -3 src/renderer/src/attention/unread/unread-badge-count-selector.ts -1 src/renderer/src/runtime/hosted-terminals/restoration/web-runtime-worktree-terminal-after-wake.ts 1 src/renderer/src/lib/work-items/linear/linear-issue-url-lookup.ts 1 src/renderer/src/lib/work-items/linear/linear-issue-write.ts 1 src/renderer/src/lib/workspace/activation/worktree-activation.ts -1 src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.ts # a setup terminal with no row spawns on the focused runtime 1 src/renderer/src/lib/workspace/activation/worktree-jump-navigation.ts +1 src/renderer/src/lib/workspace/creation/surface-policy/client-creation-action-error.ts +2 src/renderer/src/lib/workspace/creation/surface-policy/client-creation-action-policy.ts +2 src/renderer/src/lib/workspace/ownership/repo-runtime-owner.ts +1 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts +1 src/renderer/src/lib/workspace/ownership/single-runtime-legacy-owner.ts +1 src/renderer/src/lib/workspace/ownership/terminal-close-route.ts +4 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers +1 src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.ts # a setup terminal with no row spawns on the focused runtime +2 src/renderer/src/runtime/browser/creation/web-runtime-browser-creation.ts +1 src/renderer/src/runtime/hosted-terminals/creation/web-runtime-terminal-creation.ts +1 src/renderer/src/runtime/hosted-terminals/restoration/web-runtime-worktree-terminal-after-wake.ts +2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts +1 src/renderer/src/runtime/hosts/preflight/local-preflight-context.ts +1 src/renderer/src/runtime/hosts/selection/default-creation-host.ts # the sanctioned reader of the default host 17 src/renderer/src/runtime/jira/runtime-jira-client.ts 2 src/renderer/src/runtime/jira/runtime-jira-summary-client.ts 5 src/renderer/src/runtime/jira/runtime-jira-user-fields-client.ts 8 src/renderer/src/runtime/linear/runtime-linear-client.ts 6 src/renderer/src/runtime/linear/runtime-linear-issue-client.ts 12 src/renderer/src/runtime/linear/runtime-linear-project-client.ts -5 src/renderer/src/runtime/web-session-tabs-sync/subscriptions/use-runtime-session-mirror-environment-key.ts -2 src/renderer/src/runtime/browser/creation/web-runtime-browser-creation.ts -1 src/renderer/src/runtime/web-session-tabs-sync/initial-terminal/web-runtime-initial-terminal-bootstrap-dispatch.ts 1 src/renderer/src/runtime/web-session-tabs-sync/actions/web-runtime-session-tab-lifecycle.ts 1 src/renderer/src/runtime/web-session-tabs-sync/actions/web-runtime-session-tab-move.ts -1 src/renderer/src/runtime/hosted-terminals/creation/web-runtime-terminal-creation.ts 1 src/renderer/src/runtime/web-session-tabs-sync/actions/web-runtime-worktree-activation.ts 1 src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts 2 src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts +1 src/renderer/src/runtime/web-session-tabs-sync/initial-terminal/web-runtime-initial-terminal-bootstrap-dispatch.ts +1 src/renderer/src/runtime/web-session-tabs-sync/subscriptions/runtime-session-mirror-targets.ts +5 src/renderer/src/runtime/web-session-tabs-sync/subscriptions/use-runtime-session-mirror-environment-key.ts 1 src/renderer/src/runtime/web-session-tabs-sync/tracking-decisions.ts 3 src/renderer/src/runtime/web-session-tabs-sync/use-web-session-tabs-sync.ts 9 src/renderer/src/store/index.ts 2 src/renderer/src/store/project-groups/project-group-mutations.ts 1 src/renderer/src/store/repos/all-host-repo-catalog-actions.ts +3 src/renderer/src/store/repos/create-repo-slice.ts 2 src/renderer/src/store/repos/repo-add-actions.ts +1 src/renderer/src/store/repos/repo-host-identity.ts +1 src/renderer/src/store/repos/repo-reorder-host-split.ts 1 src/renderer/src/store/repos/repo-update.ts 1 src/renderer/src/store/repos/runtime-repo-catalog-actions.ts 1 src/renderer/src/store/slices/browser/create-browser-slice.ts @@ -272,7 +271,6 @@ 4 src/renderer/src/store/slices/browser/tabs/browser-tab-actions.ts 1 src/renderer/src/store/slices/browser/tabs/paired-browser-tab-creator.ts 1 src/renderer/src/store/slices/editor/create-editor-slice.ts -1 src/renderer/src/store/slices/editor/markdown/markdown-link-action.ts 1 src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts 1 src/renderer/src/store/slices/editor/opening/open-file-action.ts 1 src/renderer/src/store/slices/editor/opening/open-file-apply.ts @@ -303,16 +301,12 @@ 6 src/renderer/src/store/slices/linear/linear-team-actions.ts 11 src/renderer/src/store/slices/linear/linear.ts 2 src/renderer/src/store/slices/preflight/preflight.ts -1 src/renderer/src/store/repos/repo-host-identity.ts -1 src/renderer/src/store/repos/repo-reorder-host-split.ts -3 src/renderer/src/store/repos/create-repo-slice.ts 1 src/renderer/src/store/slices/runtime-status/create-runtime-status-slice.ts -2 src/renderer/src/store/slices/settings/settings-owner-hydration-publication.ts 5 src/renderer/src/store/slices/settings/create-settings-slice.ts -1 src/renderer/src/store/terminals/terminal-tab-retirement.ts -2 src/renderer/src/store/slices/workspace-attention/workspace-unread-characterization-fixture.ts +2 src/renderer/src/store/slices/settings/settings-owner-hydration-publication.ts 1 src/renderer/src/store/slices/settings/worktree-visibility-owner-settings.ts 3 src/renderer/src/store/slices/settings/worktree-visibility-settings-write.ts +2 src/renderer/src/store/slices/workspace-attention/workspace-unread-characterization-fixture.ts 5 src/renderer/src/store/slices/worktrees/create-worktree-slice.ts 1 src/renderer/src/store/slices/worktrees/create/create-worktree.ts 1 src/renderer/src/store/slices/worktrees/create/created-worktree-state-merge.ts @@ -326,6 +320,7 @@ 1 src/renderer/src/store/terminals/terminal-active-workspace-creation.ts 1 src/renderer/src/store/terminals/terminal-tab-appearance.ts 1 src/renderer/src/store/terminals/terminal-tab-close-providers.ts +1 src/renderer/src/store/terminals/terminal-tab-retirement.ts 1 src/renderer/src/web/preload-api/web-app-api.ts 3 src/renderer/src/web/preload-api/web-preference-normalization.ts 20 src/renderer/src/web/preload-api/web-preferences-store.ts diff --git a/config/knip.json b/config/knip.json index e10d9e14c28..d00eeaddb1b 100644 --- a/config/knip.json +++ b/config/knip.json @@ -11,6 +11,7 @@ "src/main/speech/stt-worker.ts", "src/main/warp-themes/warp-theme-parser-worker.ts", "src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts", + "src/main/agent-hooks/identity/agent-identity-worker-entry.ts", "src/main/ports/port-scan-command-worker-entry.ts", "src/main/plugins/panels/plugin-source-transpile-worker-entry.ts", "src/main/worker-thread-child-process/worker-thread-child-process-entry.ts", @@ -41,7 +42,7 @@ "src/main/plugins/testing/plugin-test-hooks.ts", "src/main/plugins/testing/plugin-test-register.ts", "src/main/ai-vault/scan-service/session-scanner-service-entry.ts", - "src/main/native-chat/wsl-transcript-fs-process-entry.ts", + "src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-entry.ts", "src/main/usage/scan-worker/usage-scan-worker-entry.ts", "src/main/workspaces/space-analysis/workspace-space-scan-worker-entry.ts", "src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts", @@ -57,7 +58,7 @@ "src/**/*-electron-fixture.ts", "src/**/*-test-fixture.ts", "src/**/*.test-fixture.{ts,tsx}", - "src/main/runtime/rpc/rpc-params-type-parity.ts", + "src/main/runtime/rpc/dispatch/rpc-params-type-parity.ts", "src/main/runtime/rpc/methods/client-state/ui-state-schema-parity-checks.ts", "src/renderer/src/components/editor/monaco-internal-test-module-types.ts", "mobile/**/*.{ts,tsx}", diff --git a/config/legacy-relay-compat-tags-baseline.txt b/config/legacy-relay-compat-tags-baseline.txt index ad9eb1fa6e3..ffcbba0a3fa 100644 --- a/config/legacy-relay-compat-tags-baseline.txt +++ b/config/legacy-relay-compat-tags-baseline.txt @@ -17,7 +17,7 @@ src/main/ssh/migration-source/orcad-migration-terminal-gate.ts src/main/ssh/host-server/ssh-host-server-on-connect.ts src/main/ssh/targets/ssh-target-orcad-preflight.ts src/preload/api-types.ts -src/preload/api/legacy-relay-bridge-api.ts +src/preload/api/mobile/legacy-relay-bridge-api.ts src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-panes.ts src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-transport.ts src/renderer/src/components/terminal-pane/pty-connection/output/foreground-output-refresh.ts diff --git a/config/legacy-relay-importers-baseline.txt b/config/legacy-relay-importers-baseline.txt index 8696af1340b..44d3041afea 100644 --- a/config/legacy-relay-importers-baseline.txt +++ b/config/legacy-relay-importers-baseline.txt @@ -1,7 +1,7 @@ # Files outside src/main/ssh/legacy-relay/ that import it. RATCHET: may only SHRINK. # The relay retirement (2027-01-15) deletes the folder and edits exactly these files. # Prune: pnpm check:legacy-relay-fence-ratchet --prune -src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts +src/main/ipc/runtime-environments/managed-orcad/orcad-delta-move-handlers.ts src/main/ipc/pty/runtime/kill.ts src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts src/main/ipc/ssh/ssh-connect-flow.ts diff --git a/config/main-blocking-atomics-baseline.txt b/config/main-blocking-atomics-baseline.txt index 298e39caca6..54e5085bb4c 100644 --- a/config/main-blocking-atomics-baseline.txt +++ b/config/main-blocking-atomics-baseline.txt @@ -1,6 +1,6 @@ # Legacy synchronous atomics uses per file; counts may only go DOWN. # Only explicit worker/utility entry files are exempt; their imports remain guarded. 1 src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts -1 src/main/startup/ensure-virtual-display.ts +1 src/main/startup/linux-display/ensure-virtual-display.ts 1 src/shared/windows-retry-file-operations.ts 1 src/shared/windows-transient-lock-removal.ts diff --git a/config/main-blocking-compression-baseline.txt b/config/main-blocking-compression-baseline.txt index 8585ee8cfe2..9b41ba5a702 100644 --- a/config/main-blocking-compression-baseline.txt +++ b/config/main-blocking-compression-baseline.txt @@ -1,7 +1,7 @@ # Legacy synchronous compression uses per file; counts may only go DOWN. # Only explicit worker/utility entry files are exempt; their imports remain guarded. 1 src/main/browser/extensions/actions/browser-extension-action-icon.ts -1 src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.ts +1 src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-compressed-frame.ts 1 src/main/ssh/remote-exec/ssh-posix-command-wrapper.ts 2 src/main/ssh/remote-exec/ssh-remote-powershell.ts 1 src/shared/remote-runtime/e2ee/node/paired-e2ee-node-compressed-frame.ts diff --git a/config/main-blocking-ipc-baseline.txt b/config/main-blocking-ipc-baseline.txt index f3c067d455e..124ec4b2b3c 100644 --- a/config/main-blocking-ipc-baseline.txt +++ b/config/main-blocking-ipc-baseline.txt @@ -2,10 +2,8 @@ # Only explicit worker/utility entry files are exempt; their imports remain guarded. 3 src/main/host/native-chat-visual-guest-theme.ts 1 src/main/ipc/renderer-shutdown-checkpoint.ts -2 src/main/ipc/session.ts 1 src/main/ipc/settings.ts 1 src/preload/api/app-bridge.ts -1 src/preload/api/native-chat-bridge.ts -2 src/preload/api/session-bridge.ts -1 src/preload/api/settings-bridge.ts -1 src/preload/native-chat-visual-guest-theme.ts +1 src/preload/api/native-chat/native-chat-bridge.ts +1 src/preload/api/preferences/settings-bridge.ts +1 src/preload/native-chat/native-chat-visual-guest-theme.ts diff --git a/config/main-blocking-sqlite-baseline.txt b/config/main-blocking-sqlite-baseline.txt index f0dd7179716..800d8b5dda4 100644 --- a/config/main-blocking-sqlite-baseline.txt +++ b/config/main-blocking-sqlite-baseline.txt @@ -11,7 +11,7 @@ 17 src/main/ai-vault-search/storage/session-search-index-writer.ts 10 src/main/ai-vault-search/storage/session-search-message-rows.ts 3 src/main/ai-vault-search/storage/session-search-query-schema.ts -17 src/main/ai-vault-search/storage/session-search-retention-delete.ts +22 src/main/ai-vault-search/storage/session-search-retention-delete.ts 13 src/main/ai-vault-search/storage/session-search-schema.ts 16 src/main/ai-vault-search/storage/session-search-store.ts 26 src/main/ai-vault-search/storage/session-search-tool-purge.ts @@ -50,9 +50,9 @@ 1 src/main/native-chat/agent-session-journal/writing/command-receipt-schema.ts 8 src/main/native-chat/agent-session-journal/writing/command-receipt-table.ts 2 src/main/native-chat/agent-session-journal/writing/journal-goal-attachment-inverse.ts -10 src/main/native-chat/transcript-opencode-sqlite-query.ts -14 src/main/native-chat/transcript-opencode2-fork-coverage.ts -10 src/main/native-chat/transcript-opencode2-sqlite.ts +10 src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.ts +14 src/main/native-chat/transcript-history/opencode/transcript-opencode2-fork-coverage.ts +10 src/main/native-chat/transcript-history/opencode/transcript-opencode2-sqlite.ts 10 src/main/opencode-usage/opencode-usage-row-queries.ts 1 src/main/opencode-usage/scanner.ts 12 src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-orchestration-history-rewrite.ts diff --git a/config/main-blocking-worker-entries.json b/config/main-blocking-worker-entries.json index 391f30c80f5..adc63687765 100644 --- a/config/main-blocking-worker-entries.json +++ b/config/main-blocking-worker-entries.json @@ -1,10 +1,11 @@ { "src/main/plugins/panels/plugin-source-transpile-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", - "src/main/claude/claude-conversation-fork-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", + "src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", "src/main/speech/stt-worker.ts": "Dedicated utility/forked-process entry; speech work stays off Electron main.", "src/main/warp-themes/warp-theme-parser-worker.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", "src/main/ai-vault-search/worker/session-search-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", "src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", + "src/main/agent-hooks/identity/agent-identity-worker-entry.ts": "Dedicated worker-thread entry; terminal agent identity SQL stays off Electron main and orcad's loop.", "src/main/ports/port-scan-command-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", "src/main/ipc/command-path/command-path-directory-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", "src/main/worker-thread-child-process/worker-thread-child-process-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.", @@ -18,7 +19,7 @@ "src/main/plugins/workers/plugin-host-entry.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main.", "src/main/computer/computer-sidecar.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main.", "src/main/ai-vault/scan-service/session-scanner-service-entry.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main.", - "src/main/native-chat/wsl-transcript-fs-process-entry.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main.", + "src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-entry.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main.", "src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main.", "src/main/orcad/orcad-local-serve-selection-entry.ts": "Dedicated utility/child-process entry; blocking work stays off Electron main." } diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 1dec6b9a0d4..d699d24d0e4 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -8,8 +8,8 @@ 3 src/main/ipc/pty/pane/stable-owner.ts 1 src/main/ipc/pty/spawn-commit-binding.ts 1 src/main/ipc/renderer-shutdown-checkpoint.ts -1 src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts -1 src/main/ipc/runtime-environments/runtime-environment-session-reconcile.ts +1 src/main/ipc/runtime-environments/catalog/runtime-environment-removal-cleanup.ts +1 src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.ts 2 src/main/ipc/session.ts 6 src/main/orca-profiles/project-transfer/profile-project-session-state.ts 4 src/main/orca-profiles/project-transfer/profile-project-source-removal.ts @@ -47,7 +47,7 @@ 5 src/main/persistence/restoring-sessions/session-owner-fields.ts 12 src/main/persistence/restoring-sessions/session-owner-removal.ts 2 src/main/persistence/restoring-sessions/workspace-pane-normalization.ts -4 src/main/persistence/terminal-topology/terminal-topology-membership.ts +4 src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts 1 src/main/persistence/tracking-repos/project-group-operations.ts 4 src/main/persistence/tracking-repos/repo-worktree-pruning.ts 3 src/main/persistence/tracking-repos/worktree-identity-migration.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index cda8f14bfde..4952f5ff34b 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -30,7 +30,7 @@ 7 src/main/antigravity/native-file-credentials.ts 12 src/main/artifacts/artifact-create-intent-store.ts 2 src/main/artifacts/artifact-share-record-store.ts -1 src/main/automations/external-manager-discovery.ts +1 src/main/automations/external-managers/external-manager-discovery.ts 7 src/main/bitbucket/credential-store.ts 1 src/main/browser-passwords/browser-password-chromium-import.ts 2 src/main/browser-passwords/browser-password-vault-file.ts @@ -89,14 +89,14 @@ 1 src/main/claude-accounts/runtime-auth/runtime-paths.ts 7 src/main/claude-accounts/sign-in/claude-account-folder.ts 3 src/main/claude/agent-view/agent-view-install.ts -1 src/main/claude/claude-diff-panel-auto-open.ts -14 src/main/claude/claude-folder-trust-file.ts -2 src/main/claude/claude-profile-hook-target.ts -1 src/main/claude/claude-rejected-api-key.ts -1 src/main/claude/claude-rewind-transcript.ts +1 src/main/claude/configuration/claude-diff-panel-auto-open.ts +14 src/main/claude/configuration/claude-folder-trust-file.ts +2 src/main/claude/hooks/claude-profile-hook-target.ts +1 src/main/claude/configuration/claude-rejected-api-key.ts +1 src/main/claude/transcripts/claude-rewind-transcript.ts 1 src/main/claude/hook-service.ts -3 src/main/claude/statusline-install.ts -6 src/main/claude/windows-hook-files.ts +3 src/main/claude/hooks/statusline-install.ts +6 src/main/claude/hooks/windows-hook-files.ts 1 src/main/cli/appimage/appimage-copy-pre-extraction.ts 3 src/main/cli/appimage/appimage-extracted-root.ts 1 src/main/cli/appimage/appimage-extraction-pruning.ts @@ -109,28 +109,27 @@ 2 src/main/cli/launchers/linux-bare-orca-dispatcher.ts 7 src/main/cli/launchers/linux-terminal-orca-cli-shim.ts 2 src/main/cli/wsl/wsl-managed-cli.ts -2 src/main/codex-accounts/codex-account-identity.ts -3 src/main/codex-accounts/codex-account-registration.ts -4 src/main/codex-accounts/codex-config-mirror.ts -1 src/main/codex-accounts/codex-credential-absence-grace.ts -1 src/main/codex-accounts/codex-login-auth-snapshot.ts -5 src/main/codex-accounts/codex-managed-home-lifecycle.ts -6 src/main/codex-accounts/codex-managed-home-path.ts -1 src/main/codex-accounts/guest-codex-account-homes.ts -6 src/main/codex-accounts/host-codex-managed-home-ownership.ts -2 src/main/codex-accounts/legacy-shared-auth-migration.ts -21 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts -36 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts -6 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-interference-shims.ts -1 src/main/codex-accounts/managed-codex-auth-readiness.ts -7 src/main/codex-accounts/runtime-home-service-auth-core.ts -5 src/main/codex-accounts/runtime-home-service-auth-provenance.ts -23 src/main/codex-accounts/runtime-home-service-auth-sync.ts -19 src/main/codex-accounts/runtime-home-service-legacy-migration.ts -1 src/main/codex-accounts/runtime-home-service-managed-home.ts -14 src/main/codex-accounts/runtime-home-service-paths.ts -1 src/main/codex-accounts/runtime-home-service-sync.ts -2 src/main/codex-accounts/runtime-home-service-wsl-core.ts +2 src/main/codex-accounts/credentials/codex-account-identity.ts +3 src/main/codex-accounts/account-management/codex-account-registration.ts +4 src/main/codex-accounts/managed-homes/codex-config-mirror.ts +1 src/main/codex-accounts/credentials/codex-credential-absence-grace.ts +1 src/main/codex-accounts/login/codex-login-auth-snapshot.ts +5 src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts +6 src/main/codex-accounts/managed-homes/codex-managed-home-path.ts +1 src/main/codex-accounts/managed-homes/guest-codex-account-homes.ts +6 src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.ts +2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts +36 src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-harness.ts +6 src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-interference-shims.ts +1 src/main/codex-accounts/credentials/managed-codex-auth-readiness.ts +7 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-core.ts +5 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-provenance.ts +23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts +19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts +1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts +14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts +1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts +2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts 1 src/main/codex-usage/codex-session-file-discovery.ts 1 src/main/codex/configuration/codex-path-observation.ts 21 src/main/codex/configuration/homes/codex-home-paths.ts @@ -252,7 +251,7 @@ 1 src/main/foreign-sqlite-readers/foreign-sqlite-reader-spawn.ts 1 src/main/foreign-sqlite-readers/readers/cursor-profile.ts 1 src/main/foreign-sqlite-readers/readers/opencode-binder-sessions.ts -1 src/main/git/source-control/huge-folder-ignore.ts +1 src/main/git/source-control/ignores/huge-folder-ignore.ts 5 src/main/git/repositories/discovery/repo-detection.ts 13 src/main/git/repositories/discovery/repo-git-marker-scan.ts 3 src/main/git/worktrees/catalog/worktree-git-path.ts @@ -261,9 +260,11 @@ 3 src/main/grok/grok-hook-owners.ts 4 src/main/grok/grok-hook-symlink-cleanup-marker.ts 4 src/main/grok/hook-service.ts -4 src/main/hang-watchdog/hang-detection-marker.ts +8 src/main/hang-watchdog/hang-detection-marker.ts +4 src/main/hang-watchdog/hang-incident-snapshot.ts 1 src/main/hang-watchdog/hang-watchdog-worker-path.ts 1 src/main/hang-watchdog/previous-hang-detection.ts +9 src/main/hang-watchdog/renderer-hang-records.ts 1 src/main/hermes/hermes-default-home.ts 10 src/main/hermes/hermes-home-filesystem.ts 2 src/main/hermes/hook-service.ts @@ -315,8 +316,8 @@ 4 src/main/muse/hook-service.ts 2 src/main/native-chat/agent-session-attachments/agent-session-attachment-claims.ts 1 src/main/native-chat/agent-session-journal/database/journal-host-database.ts -1 src/main/native-chat/host-readable-transcript-path.ts -2 src/main/native-chat/wsl-transcript-fs-process-spawn.ts +1 src/main/native-chat/transcript-discovery/host-readable-transcript-path.ts +2 src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-spawn.ts 1 src/main/node-runtime/appimage-bundled-node-runtime.ts 2 src/main/node-runtime/managed-runtime-release-install.ts 7 src/main/node-runtime/managed-runtime-release.ts @@ -341,39 +342,39 @@ 2 src/main/orca-profiles/storage/new-profile-state.ts 5 src/main/orca-profiles/storage/profile-legacy-state-import.ts 2 src/main/orcad/launcher.ts -7 src/main/orcad/node-pty-prebuilt-slot.ts -2 src/main/orcad/node-pty-precondition.ts -2 src/main/orcad/orcad-agent-browser-binary.ts -1 src/main/orcad/orcad-app-paths.ts -1 src/main/orcad/orcad-artifact-identity.ts -2 src/main/orcad/orcad-artifact-materializer.ts -12 src/main/orcad/orcad-bundled-runtime.ts -2 src/main/orcad/orcad-cli-launcher.ts -1 src/main/orcad/orcad-command-arguments.ts -1 src/main/orcad/orcad-completed-stop-receipt.ts -2 src/main/orcad/orcad-daemon-slot-pins.ts -2 src/main/orcad/orcad-data-root-locality.ts -3 src/main/orcad/orcad-data-root-privacy.ts -4 src/main/orcad/orcad-host-account-launch-env-store.ts -1 src/main/orcad/orcad-host-adapters.ts -1 src/main/orcad/orcad-host-identity-reset.ts -2 src/main/orcad/orcad-idle-stop-record.ts -3 src/main/orcad/orcad-instance-lock-hold.ts -16 src/main/orcad/orcad-instance-lock-reclaim.ts -4 src/main/orcad/orcad-instance-lock.ts -7 src/main/orcad/orcad-local-serve-selection.ts -1 src/main/orcad/orcad-lock-clone-machine.ts -1 src/main/orcad/orcad-managed-stop-cancellation.ts -3 src/main/orcad/orcad-managed-stop-decision.ts -2 src/main/orcad/orcad-managed-stop-request.ts -4 src/main/orcad/orcad-plaintext-credential-migration.ts -5 src/main/orcad/orcad-process-start-time.ts -11 src/main/orcad/orcad-secret-key-record.ts -3 src/main/orcad/orcad-stale-lock-reclaim.ts -1 src/main/orcad/orcad-stop-request-listener.ts -1 src/main/orcad/orcad-wsl-holder-release.ts -2 src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts -1 src/main/orcad/serve-profile-ssh-targets.ts +7 src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts +2 src/main/orcad/native-runtime/node-pty-precondition.ts +2 src/main/orcad/browser-providers/orcad-agent-browser-binary.ts +1 src/main/orcad/host-runtime/orcad-app-paths.ts +1 src/main/orcad/artifact-slots/orcad-artifact-identity.ts +2 src/main/orcad/artifact-slots/orcad-artifact-materializer.ts +12 src/main/orcad/runtime-launch/orcad-bundled-runtime.ts +2 src/main/orcad/serve-startup/orcad-cli-launcher.ts +1 src/main/orcad/serve-startup/orcad-command-arguments.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts +2 src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts +2 src/main/orcad/instance-lock/orcad-data-root-locality.ts +3 src/main/orcad/instance-lock/orcad-data-root-privacy.ts +4 src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts +1 src/main/orcad/host-runtime/orcad-host-adapters.ts +1 src/main/orcad/profile-state/orcad-host-identity-reset.ts +2 src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts +3 src/main/orcad/instance-lock/orcad-instance-lock-hold.ts +16 src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts +4 src/main/orcad/instance-lock/orcad-instance-lock.ts +7 src/main/orcad/serve-startup/orcad-local-serve-selection.ts +1 src/main/orcad/instance-lock/orcad-lock-clone-machine.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts +3 src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts +2 src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts +4 src/main/orcad/credentials/orcad-plaintext-credential-migration.ts +5 src/main/orcad/instance-lock/orcad-process-start-time.ts +11 src/main/orcad/credentials/orcad-secret-key-record.ts +3 src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts +1 src/main/orcad/instance-lock/orcad-wsl-holder-release.ts +2 src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts +1 src/main/orcad/profile-state/serve-profile-ssh-targets.ts 6 src/main/persistence/atomic-snapshot-writer.ts 5 src/main/persistence/loading-store/user-data-path.ts 4 src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts @@ -440,18 +441,17 @@ 5 src/main/providers/local-pty/local-pty-executable-spawn.ts 1 src/main/providers/local-pty/local-pty-session-operations.ts 1 src/main/providers/local-pty/local-pty-shell-ready-wrapper-root.ts -1 src/main/providers/macos-login-session-pty-probe.ts -3 src/main/providers/macos-tcc-login-shell.ts -3 src/main/providers/windows-powershell-executable.ts -2 src/main/providers/working-directory-validation.ts +1 src/main/providers/shell-launch/macos/login-session-pty-probe.ts +3 src/main/providers/shell-launch/macos/tcc-login-shell.ts +3 src/main/providers/shell-launch/windows/powershell-executable.ts +2 src/main/providers/working-directory/validation.ts 4 src/main/pty/history/fish-history-session.ts 4 src/main/pty/history/terminal-history-deletion.ts 2 src/main/pty/history/terminal-history-paths.ts 5 src/main/pty/history/terminal-history.ts 1 src/main/pty/process-retirement/posix-pty-process-table.ts 12 src/main/pty/scrollback/overlay-mirror.ts -1 src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts -11 src/main/pty/scrollback/terminal-scrollback-snapshots.ts +7 src/main/pty/scrollback/terminal-scrollback-snapshots.ts 2 src/main/pty/shell-startup/codex-shell-launch-preflight.ts 7 src/main/pty/shell-startup/git-bash.ts 3 src/main/pty/shell-startup/legacy-terminal-posix-tombstone.ts @@ -475,8 +475,8 @@ 1 src/main/runtime/client/navigation/desktop-chat-creation-history.ts 9 src/main/runtime/host-instance-identity.ts 4 src/main/runtime/hosts/platform-probe/host-descriptor.ts -5 src/main/runtime/mobile-cloud-relay/relay-region-preference.ts -2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts +5 src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts +2 src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts 1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts 2 src/main/runtime/push/push-unregister-outbox.ts 1 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts @@ -487,8 +487,8 @@ 3 src/main/runtime/rpc/server/pairing/e2ee-keypair.ts 3 src/main/runtime/rpc/server/runtime-metadata.ts 2 src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts -5 src/main/runtime/rpc/unix-socket-transport.ts -3 src/main/runtime/rpc/ws-fallback-port-store.ts +5 src/main/runtime/rpc/transports/unix-socket-transport.ts +3 src/main/runtime/rpc/transports/websocket/ws-fallback-port-store.ts 2 src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts 1 src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts 1 src/main/server/serve-pairing-output.ts @@ -514,26 +514,26 @@ 3 src/main/ssh/system-transport/file-transfer/system-ssh-sftp-transfer.ts 3 src/main/ssh/system-transport/ssh-control-socket.ts 3 src/main/ssh/system-transport/system-ssh-binary.ts -3 src/main/startup/cli-launch-redirect.ts +3 src/main/startup/cli-launch/cli-launch-redirect.ts 2 src/main/startup/configure-process.ts -4 src/main/startup/gpu-fallback-marker.ts -2 src/main/startup/http1-compatibility-marker.ts -5 src/main/startup/http1-compatibility-profile-state.ts -1 src/main/startup/linux-dev-shm-policy.ts -4 src/main/startup/linux-realtime-scheduling-guard.ts -1 src/main/startup/linux-rttime-limit.ts -2 src/main/startup/profile-state-recovery-preflight.ts -1 src/main/startup/startup-diagnostics.ts -1 src/main/startup/windows-app-data-path.ts -5 src/main/startup/windows-install-dir-acl-poison-marker.ts -1 src/main/startup/windows-install-dir-acl-probe.ts -1 src/main/startup/windows-install-dir-package-acl-grant.ts -4 src/main/startup/windows-install-dir-package-acl-repair.ts -3 src/main/startup/windows-renderer-runtime-files.ts -3 src/main/startup/windows-user-data-acl.ts -6 src/main/startup/x-display-artifacts.ts +4 src/main/startup/gpu-recovery/gpu-fallback-marker.ts +2 src/main/startup/network-compatibility/http1-compatibility-marker.ts +5 src/main/startup/network-compatibility/http1-compatibility-profile-state.ts +1 src/main/startup/linux-runtime/linux-dev-shm-policy.ts +4 src/main/startup/linux-runtime/linux-realtime-scheduling-guard.ts +1 src/main/startup/linux-runtime/linux-rttime-limit.ts +2 src/main/startup/profile-startup/profile-state-recovery-preflight.ts +1 src/main/startup/diagnostics/startup-diagnostics.ts +1 src/main/startup/windows-startup/windows-app-data-path.ts +5 src/main/startup/windows-install-permissions/windows-install-dir-acl-poison-marker.ts +1 src/main/startup/windows-install-permissions/windows-install-dir-acl-probe.ts +1 src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.ts +4 src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.ts +3 src/main/startup/windows-startup/windows-renderer-runtime-files.ts +3 src/main/startup/windows-startup/windows-user-data-acl.ts +6 src/main/startup/linux-display/x-display-artifacts.ts 2 src/main/stats/stats-file-loader.ts -2 src/main/text-generation/source-control-prompt-files.ts +2 src/main/text-generation/prompts/source-control-prompt-files.ts 1 src/main/updater/lifecycle/windows-update-install-directory.ts 9 src/main/updater/linux-package/appimage-runtime-identity.ts 1 src/main/updater/linux-package/linux-package-install-command.ts diff --git a/config/main-sync-spawn-baseline.txt b/config/main-sync-spawn-baseline.txt index 0d630e89d86..428c8fe8525 100644 --- a/config/main-sync-spawn-baseline.txt +++ b/config/main-sync-spawn-baseline.txt @@ -9,12 +9,10 @@ 1 src/main/browser/network/egress/browser-route-egress-electron-launch.ts 1 src/main/browser/routing/partitions/browser-route-partition-binding-store.ts 1 src/main/claude-accounts/runtime-auth-service.ts -2 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts -2 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts -1 src/main/codex-accounts/runtime-home-service-home-routing.ts -1 src/main/codex-accounts/runtime-home-service-wsl.ts +2 src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-harness.ts +1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts +1 src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts 1 src/main/codex-accounts/service.ts -1 src/main/computer/macos-permissions/macos-computer-use-permissions.ts 1 src/main/daemon/endpoint/identity/daemon-process-identity-query.ts 1 src/main/daemon/endpoint/identity/daemon-process-start-time.ts 2 src/main/daemon/process-scopes/daemon-cgroup-scope.ts @@ -28,8 +26,8 @@ 1 src/main/ipc/worktree-logic.ts 1 src/main/network/macos-tailscale-dns-diagnostic.ts 1 src/main/opencode/status-hooks/legacy-plugin-acl-retry.ts -2 src/main/orcad/node-pty-precondition.ts -1 src/main/orcad/orcad-data-root-privacy.ts +2 src/main/orcad/native-runtime/node-pty-precondition.ts +1 src/main/orcad/instance-lock/orcad-data-root-privacy.ts 2 src/main/persistence/profile-state/access/profile-state-access-identity.ts 1 src/main/persistence/profile-state/recovery/profile-state-recovery-copy.ts 1 src/main/plugins/catalog/plugin-private-marketplace-ssh-shim.cjs @@ -37,10 +35,9 @@ 1 src/main/pty/shell-startup/pwsh.ts 2 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts 1 src/main/runtime/integrations/skill/runtime-skill-install-authority.ts -2 src/main/startup/cli-launch-redirect.ts -1 src/main/startup/linux-secret-service-probe.ts +2 src/main/startup/cli-launch/cli-launch-redirect.ts +1 src/main/startup/linux-runtime/linux-secret-service-probe.ts 2 src/main/window/desktop-integration/macos-press-and-hold-default.ts -1 src/main/workspace-hooks/worktree-runner-script.ts 3 src/main/wsl/discovery/distro-catalog.ts 1 src/shared/fish-binary-requirement.ts 1 src/shared/openssh-default-shell.ts diff --git a/config/mobile-localization-coverage-allowlist.json b/config/mobile-localization-coverage-allowlist.json index e99be1cf24d..05742534930 100644 --- a/config/mobile-localization-coverage-allowlist.json +++ b/config/mobile-localization-coverage-allowlist.json @@ -175,7 +175,7 @@ "count": 1 }, { - "filePath": "mobile/src/files/mobile-file-preview-route.ts", + "filePath": "mobile/src/files/preview/mobile-file-preview-route.ts", "kind": "object-property:message", "text": "Unable to load preview", "dynamic": false, @@ -289,7 +289,7 @@ { "filePath": "mobile/src/settings/about-screen.tsx", "kind": "jsx-attribute:title", - "text": "onOrca.dev", + "text": "orca.dev", "dynamic": false, "count": 1 }, @@ -308,238 +308,238 @@ "count": 1 }, { - "filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx", + "filePath": "mobile/src/terminal/session/accessory-keys/MobileSessionLatchKeys.tsx", "kind": "object-property:label", "text": "Shift", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx", + "filePath": "mobile/src/terminal/session/accessory-keys/MobileSessionLatchKeys.tsx", "kind": "object-property:label", "text": "Ctrl", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx", + "filePath": "mobile/src/terminal/session/accessory-keys/MobileSessionLatchKeys.tsx", "kind": "object-property:label", "text": "Alt", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-smart-source-modes.ts", + "filePath": "mobile/src/new-workspace/source-selection/mobile-smart-source-modes.ts", "kind": "object-property:label", "text": "GitHub", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-smart-source-modes.ts", + "filePath": "mobile/src/new-workspace/source-selection/mobile-smart-source-modes.ts", "kind": "object-property:label", "text": "GitLab", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-smart-source-modes.ts", + "filePath": "mobile/src/new-workspace/source-selection/mobile-smart-source-modes.ts", "kind": "object-property:label", "text": "Jira", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-smart-source-modes.ts", + "filePath": "mobile/src/new-workspace/source-selection/mobile-smart-source-modes.ts", "kind": "object-property:label", "text": "Linear", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-tasks-create-drawers.tsx", + "filePath": "mobile/src/tasks/workspace-creation/mobile-tasks-create-drawers.tsx", "kind": "jsx-attribute:placeholder", "text": "lin_api_...", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-tasks-options.tsx", + "filePath": "mobile/src/tasks/task-list/mobile-tasks-options.tsx", "kind": "object-property:label", "text": "GitHub", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-tasks-options.tsx", + "filePath": "mobile/src/tasks/task-list/mobile-tasks-options.tsx", "kind": "object-property:label", "text": "GitLab", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-tasks-options.tsx", + "filePath": "mobile/src/tasks/task-list/mobile-tasks-options.tsx", "kind": "object-property:label", "text": "Jira", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-tasks-options.tsx", + "filePath": "mobile/src/tasks/task-list/mobile-tasks-options.tsx", "kind": "object-property:label", "text": "Linear", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/tasks/mobile-tasks-workspace-trust-drawers.tsx", + "filePath": "mobile/src/tasks/workspace-creation/mobile-tasks-workspace-trust-drawers.tsx", "kind": "jsx-attribute:placeholder", "text": "src/renderer packages/ui", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:accessibilityLabel", "text": "Backspace", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:accessibilityLabel", "text": "Enter", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:accessibilityLabel", "text": "Escape", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:accessibilityLabel", "text": "Shift Tab", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:accessibilityLabel", "text": "Space", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:accessibilityLabel", "text": "Tab", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+A", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+C", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+D", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+E", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+L", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+R", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+U", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+W", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Ctrl+Z", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Del", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Enter", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Esc", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Shift+Tab", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Space", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/terminal/terminal-key-definitions.ts", + "filePath": "mobile/src/terminal/key-input/terminal-key-definitions.ts", "kind": "object-property:label", "text": "Tab", "dynamic": false, diff --git a/config/nsis/orca-installer-hooks.nsh b/config/nsis/orca-installer-hooks.nsh index 9ac82b88a25..3a43eb35b4f 100644 --- a/config/nsis/orca-installer-hooks.nsh +++ b/config/nsis/orca-installer-hooks.nsh @@ -69,7 +69,7 @@ ; WSL host sees nothing here. These are the folders Electron's userData (app.getName()) can be, as the ; deleteAppData step lists them; a custom --user-data-dir can't be known here. ; Sync the flags with WSL_HOLDER_UNINSTALL_FLAG and WSL_SERVER_UNINSTALL_FLAG in - ; src/main/startup/wsl-holder-uninstall-preflight.ts. + ; src/main/startup/uninstall/wsl-holder-uninstall-preflight.ts. ${if} $installMode == "all" SetShellVarContext current ${endIf} @@ -114,7 +114,7 @@ ; app, but once that folder is removed every agent fails a hook per event, so the last Orca for ; this user takes the entries out. Another install, or an unreadable registry, keeps them. ; Best effort: the exit code never blocks uninstall. - ; Sync the flag with AGENT_HOOKS_UNINSTALL_FLAG in src/main/startup/agent-hooks-uninstall-preflight.ts. + ; Sync the flag with AGENT_HOOKS_UNINSTALL_FLAG in src/main/startup/uninstall/agent-hooks-uninstall-preflight.ts. !insertmacro ORCA_OTHER_INSTALL_STATE $1 ${if} $1 == "none" nsExec::Exec '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --orca-uninstall-remove-agent-hooks' diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 8510ef0dfbb..72f773160d3 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -1,18 +1,17 @@ # Existing production source files importing child_process at runtime outside @orca/process-host. # Migration debt: this list may only shrink; new callers use the package public API. -src/cli/handlers/core.ts -src/cli/handlers/interactive-login-interruption.ts +src/cli/runtime/cli-lifecycle-handlers.ts +src/cli/accounts/interactive-login-interruption.ts src/cli/runtime/launch.ts src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts src/main/ai-vault/scan-service/session-scanner-service-spawn.ts src/main/window/desktop-integration/app-icon.ts -src/main/automations/precheck-runner.ts +src/main/automations/dispatch/precheck-runner.ts src/main/browser/agent-browser/helper-process/agent-browser-bridge-execution.ts src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.ts src/main/browser/network/egress/browser-route-egress-electron-launch.ts -src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts -src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts +src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-harness.ts src/main/codex-accounts/service.ts src/main/computer/desktop-script/desktop-script-provider-bridge.ts src/main/computer/macos-permissions/macos-computer-use-permission-status.ts @@ -36,7 +35,7 @@ src/main/git/command-runner/process-capture/spawn-command-capture.ts src/main/git/command-runner/process-capture/spawned-command-tree-kill.ts src/main/git/command-runner/host-routing/wsl-aware-spawn.ts src/main/git/command-runner/host-routing/wsl-git-read-environment.ts -src/main/github/gh-utils.ts +src/main/github/execution/github-legacy-command.ts src/main/workspace-hooks/hooks.ts src/main/ipc/developer-permissions.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-launch.ts @@ -51,14 +50,13 @@ src/main/macos-keychain/generic-password.ts src/main/power/macos-system-sleep-assertion.ts src/main/macos-permissions/macos-tcc-prompt-watch.ts src/main/memory/collector.ts -src/main/native-chat/wsl-transcript-fs-process-spawn.ts +src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-spawn.ts src/main/network/macos-system-resolver-health.ts src/main/network/macos-tailscale-dns-diagnostic.ts src/main/plugins/workers/parent-process/plugin-host-process.ts src/main/plugins/catalog/plugin-private-marketplace-ssh-shim.cjs src/main/ports/port-scan-command-execution.ts -src/main/providers/macos-login-session-pty-probe.ts -src/main/providers/process-cwd.ts +src/main/providers/working-directory/process-cwd.ts src/main/pty/process-retirement/pty-descendant-fresh-table.ts src/main/rate-limits/providers/gemini/gemini-cli-oauth-extractor.ts src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.ts @@ -67,7 +65,7 @@ src/main/ssh/system-transport/ssh-proxy-command.ts src/main/ssh/system-transport/system-ssh-command.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.ts src/main/ssh/system-transport/file-transfer/system-ssh-file-transfer.ts -src/main/startup/ensure-virtual-display.ts +src/main/startup/linux-display/ensure-virtual-display.ts src/main/pty/process-retirement/windows-process-tree-kill.ts src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts src/shared/ephemeral-vm-recipe-process.ts @@ -75,4 +73,4 @@ src/shared/fish-binary-requirement.ts src/shared/process-table-ps-capture.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.ts src/shared/terminal/pty/native-process/shell-process-readiness.ts -src/wsl-guest/preflight-handler.ts +src/wsl-guest/commands/preflight-handler.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 2b970a421b8..f6cb0045602 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -28,27 +28,27 @@ 1 src/renderer/src/components/artifacts/ArtifactPublishButton.tsx 2 src/renderer/src/components/artifacts/ArtifactsPage.tsx 2 src/renderer/src/components/artifacts/useArtifactPagination.ts +1 src/renderer/src/components/automations/AutomationsPageSurface.tsx 2 src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx -1 src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx 1 src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx +1 src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts +2 src/renderer/src/components/automations/authoring/use-automation-create-destination.ts +2 src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts +1 src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts +1 src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts +2 src/renderer/src/components/automations/external/use-scoped-external-automations.ts +1 src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx +4 src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts +4 src/renderer/src/components/automations/listing/use-automation-list-search.ts +1 src/renderer/src/components/automations/listing/use-automations-page-list-state.ts 1 src/renderer/src/components/automations/runs/AutomationRunHistory.tsx 1 src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx 1 src/renderer/src/components/automations/runs/AutomationRunsTable.tsx -1 src/renderer/src/components/automations/AutomationsPageSurface.tsx -1 src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts -2 src/renderer/src/components/automations/authoring/use-automation-create-destination.ts -4 src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts -4 src/renderer/src/components/automations/listing/use-automation-list-search.ts -2 src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts 1 src/renderer/src/components/automations/runs/use-automation-runs-dashboard.ts -1 src/renderer/src/components/automations/listing/use-automations-page-list-state.ts +16 src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts 1 src/renderer/src/components/automations/use-automations-page-local-state.ts 1 src/renderer/src/components/automations/use-automations-page-refresh.ts -1 src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts 1 src/renderer/src/components/automations/use-automations-page-store-state.ts -1 src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts -2 src/renderer/src/components/automations/external/use-scoped-external-automations.ts -16 src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts 7 src/renderer/src/components/browser-extension-install-dialog.tsx 1 src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx 2 src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx @@ -99,11 +99,11 @@ 1 src/renderer/src/components/editor/combined-diff/resolve-changes/use-combined-diff-section-row-keys.ts 1 src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts 1 src/renderer/src/components/editor/combined-diff/scroll-viewport/use-combined-diff-virtualizer.ts -1 src/renderer/src/components/editor/csv/grid/CsvGrid.tsx 1 src/renderer/src/components/editor/csv/CsvViewer.tsx 1 src/renderer/src/components/editor/csv/editing/clipboard/useCsvClipboard.ts -1 src/renderer/src/components/editor/csv/preview/useCsvPagedPreview.ts 3 src/renderer/src/components/editor/csv/editing/useCsvTableEditor.ts +1 src/renderer/src/components/editor/csv/grid/CsvGrid.tsx +1 src/renderer/src/components/editor/csv/preview/useCsvPagedPreview.ts 1 src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts 3 src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx 1 src/renderer/src/components/editor/diff/review/DiffNotesSendMenu.tsx @@ -150,19 +150,19 @@ 1 src/renderer/src/components/emulator-pane/use-emulator-video-stream.ts 1 src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts 1 src/renderer/src/components/feature-tips/FeatureTipsModal.tsx -1 src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx -1 src/renderer/src/components/feature-wall/BrowserPricingStoryboard.tsx -1 src/renderer/src/components/feature-wall/BrowserStoryboardWindow.tsx -2 src/renderer/src/components/feature-wall/EditorAnimatedVisual.tsx -1 src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx -2 src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx +1 src/renderer/src/components/feature-wall/setup/agent-capabilities/AgentCapabilitiesSetupAction.tsx +1 src/renderer/src/components/feature-wall/browser-storyboard/BrowserPricingStoryboard.tsx +1 src/renderer/src/components/feature-wall/browser-storyboard/BrowserStoryboardWindow.tsx +2 src/renderer/src/components/feature-wall/editor-storyboard/EditorAnimatedVisual.tsx +1 src/renderer/src/components/feature-wall/setup/browser/FeatureWallBrowserAction.tsx +2 src/renderer/src/components/feature-wall/setup/FeatureWallSetupChecklist.tsx 1 src/renderer/src/components/feature-wall/FeatureWallTourSurface.tsx -1 src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.tsx -1 src/renderer/src/components/feature-wall/WorkbenchTerminalSplitMenu.tsx +1 src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.tsx +1 src/renderer/src/components/feature-wall/workbench-storyboard/WorkbenchTerminalSplitMenu.tsx 1 src/renderer/src/components/feature-wall/agents-orchestration/OrchestrationPage.tsx 2 src/renderer/src/components/feature-wall/agents-orchestration/UsageAccountsCard.tsx -2 src/renderer/src/components/feature-wall/use-feature-wall-tour-telemetry.ts -3 src/renderer/src/components/feature-wall/useAiCommitPrSettings.ts +2 src/renderer/src/components/feature-wall/tour/use-feature-wall-tour-telemetry.ts +3 src/renderer/src/components/feature-wall/commit-pr-settings/useAiCommitPrSettings.ts 1 src/renderer/src/components/floating-terminal/FloatingTerminalIconContextMenu.tsx 3 src/renderer/src/components/floating-terminal/FloatingTerminalToggleButton.tsx 1 src/renderer/src/components/floating-terminal/use-floating-terminal-panel-geometry.ts @@ -182,7 +182,7 @@ 1 src/renderer/src/components/github-project/useProjectPickerBrowse.ts 3 src/renderer/src/components/github-project/useProjectViewTable.ts 1 src/renderer/src/components/github/CommentReactions.tsx -8 src/renderer/src/components/github/GitHubMarkdownComposer.tsx +4 src/renderer/src/components/github/GitHubMarkdownComposer.tsx 2 src/renderer/src/components/github/github-duplicate-issue-candidates.ts 1 src/renderer/src/components/github/github-rate-limit-display.tsx 2 src/renderer/src/components/github/use-github-image-uploads.ts @@ -206,7 +206,6 @@ 2 src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts 1 src/renderer/src/components/mobile/use-mobile-pairing-generation.ts 1 src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts -1 src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx 8 src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts 2 src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts 2 src/renderer/src/components/native-chat/composer/controls/NativeChatComposerToolbar.tsx @@ -227,7 +226,6 @@ 6 src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.ts 4 src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-source.ts 6 src/renderer/src/components/native-chat/messages/notices/use-structured-agent-session-start-failure-facts.ts -1 src/renderer/src/components/native-chat/pane/actions/NativeChatCopyOrcaSessionIdMenuItem.tsx 1 src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx 1 src/renderer/src/components/native-chat/pane/actions/use-native-chat-session-context-actions.tsx 1 src/renderer/src/components/native-chat/paste/native-chat-paste-destination.ts @@ -252,6 +250,7 @@ 2 src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session.ts 3 src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-retained-session.ts 1 src/renderer/src/components/native-chat/tools/lines/NativeChatToolOutput.tsx +1 src/renderer/src/components/native-chat/tools/runs/use-native-chat-tool-run-window.ts 1 src/renderer/src/components/native-chat/usage/NativeChatAccountUsageCard.tsx 2 src/renderer/src/components/native-chat/usage/use-native-chat-account-usage.ts 1 src/renderer/src/components/native-chat/viewport/find/use-native-chat-find.ts @@ -261,12 +260,12 @@ 2 src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx 1 src/renderer/src/components/native-chat/viewport/virtualization/use-native-chat-transcript-window.ts 1 src/renderer/src/components/network/CustomAddressDialog.tsx -1 src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx -1 src/renderer/src/components/new-workspace/RunTargetCombobox.tsx -3 src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx -2 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts +1 src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.tsx +1 src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.tsx +3 src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.tsx +2 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-actions.ts +1 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts +1 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts 2 src/renderer/src/components/onboarding/AgentStep.tsx 2 src/renderer/src/components/onboarding/NotificationStep.tsx 8 src/renderer/src/components/onboarding/OnboardingFlow.tsx @@ -502,7 +501,6 @@ 1 src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteNestedWorktreesDialog.tsx 1 src/renderer/src/components/sidebar/workspace-actions/deletion/RemovalUnsavedFilesNotice.tsx 1 src/renderer/src/components/sidebar/workspace-actions/deletion/WorktreeForceDeleteButton.tsx -1 src/renderer/src/components/sidebar/workspace-actions/deletion/use-delete-worktree-status-hydration.ts 1 src/renderer/src/components/sidebar/workspace-actions/parenting/WorktreeParentPickerPopover.tsx 3 src/renderer/src/components/sidebar/workspace-actions/parenting/use-worktree-parent-picker-transition.ts 7 src/renderer/src/components/sidebar/workspace-board/drag/use-workspace-kanban-card-pointer-drag.ts @@ -541,16 +539,16 @@ 4 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts 1 src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts 1 src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts +1 src/renderer/src/components/skills/SkillsPage.tsx +1 src/renderer/src/components/skills/deletion/use-skill-delete-flow.ts +1 src/renderer/src/components/skills/freshness/use-reviewed-skill-plan.ts 1 src/renderer/src/components/skills/installation/SkillBundleInstallFlow.tsx 2 src/renderer/src/components/skills/installation/SkillInstallDialog.tsx 4 src/renderer/src/components/skills/installation/SkillInstallManagementDialog.tsx +1 src/renderer/src/components/skills/setup/WslAgentSkillSetupPanel.tsx 1 src/renderer/src/components/skills/sharing/SkillShareDialog.tsx 1 src/renderer/src/components/skills/sharing/SkillSharedLinkRow.tsx -1 src/renderer/src/components/skills/SkillsPage.tsx -1 src/renderer/src/components/skills/setup/WslAgentSkillSetupPanel.tsx 2 src/renderer/src/components/skills/sharing/use-owned-skill-shares.ts -1 src/renderer/src/components/skills/freshness/use-reviewed-skill-plan.ts -1 src/renderer/src/components/skills/deletion/use-skill-delete-flow.ts 1 src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx 1 src/renderer/src/components/ssh-host-recovery/SshHostMoveAnywayAction.tsx 2 src/renderer/src/components/star-nag/StarNagAgentValueMomentObserver.tsx @@ -579,41 +577,41 @@ 1 src/renderer/src/components/tab-bar/use-tab-bar-create-menu-controller.ts 2 src/renderer/src/components/tab-bar/use-tab-bar-item-actions.ts 1 src/renderer/src/components/tab-group/useTabDragSplit.ts -1 src/renderer/src/components/task-page/github/AssigneesCell.tsx -2 src/renderer/src/components/task-page/github/MergeCell.tsx -1 src/renderer/src/components/task-page/github/StatusCell.tsx -1 src/renderer/src/components/task-page/github/use-task-page-github-cache-reconciliation.ts +1 src/renderer/src/components/task-page/github/listing/AssigneesCell.tsx +2 src/renderer/src/components/task-page/github/pull-requests/MergeCell.tsx +1 src/renderer/src/components/task-page/github/issue-status/StatusCell.tsx +1 src/renderer/src/components/task-page/github/cache/use-task-page-github-cache-reconciliation.ts 2 src/renderer/src/components/task-page/github/use-task-page-github-detail.ts -2 src/renderer/src/components/task-page/github/use-task-page-github-issue-creation.ts -21 src/renderer/src/components/task-page/github/use-task-page-github-issue-draft.ts -1 src/renderer/src/components/task-page/github/use-task-page-github-landing-refresh.ts -3 src/renderer/src/components/task-page/github/use-task-page-github-list-state.ts -7 src/renderer/src/components/task-page/github/use-task-page-github-mutation-state.ts -1 src/renderer/src/components/task-page/github/use-task-page-github-quiet-refresh-effect.ts -5 src/renderer/src/components/task-page/github/use-task-page-github-quiet-refresh.ts -3 src/renderer/src/components/task-page/github/use-task-page-github-search-pagination.ts -4 src/renderer/src/components/task-page/github/use-task-page-work-items-cache-selection.ts +2 src/renderer/src/components/task-page/github/issue-creation/use-task-page-github-issue-creation.ts +21 src/renderer/src/components/task-page/github/issue-creation/use-task-page-github-issue-draft.ts +1 src/renderer/src/components/task-page/github/refresh/use-task-page-github-landing-refresh.ts +3 src/renderer/src/components/task-page/github/listing/use-task-page-github-list-state.ts +7 src/renderer/src/components/task-page/github/mutations/use-task-page-github-mutation-state.ts +1 src/renderer/src/components/task-page/github/refresh/use-task-page-github-quiet-refresh-effect.ts +5 src/renderer/src/components/task-page/github/refresh/use-task-page-github-quiet-refresh.ts +3 src/renderer/src/components/task-page/github/listing/use-task-page-github-search-pagination.ts +4 src/renderer/src/components/task-page/github/cache/use-task-page-work-items-cache-selection.ts 1 src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts -2 src/renderer/src/components/task-page/jira/task-page-jira-board-view.tsx -1 src/renderer/src/components/task-page/jira/use-task-page-jira-creation-projects.ts -33 src/renderer/src/components/task-page/jira/use-task-page-jira-creation-state.ts -2 src/renderer/src/components/task-page/jira/use-task-page-jira-favourite-filters.ts -2 src/renderer/src/components/task-page/jira/use-task-page-jira-issue-creation.ts -1 src/renderer/src/components/task-page/jira/use-task-page-jira-list-effects.ts -2 src/renderer/src/components/task-page/jira/use-task-page-jira-quick-filters.ts -2 src/renderer/src/components/task-page/jira/use-task-page-jira-saved-filters.ts -2 src/renderer/src/components/task-page/jira/use-task-page-jira-summary-generation.ts -1 src/renderer/src/components/task-page/linear/IssueTable.tsx -7 src/renderer/src/components/task-page/linear/use-task-page-linear-board.ts +2 src/renderer/src/components/task-page/jira/boards/task-page-jira-board-view.tsx +1 src/renderer/src/components/task-page/jira/creation/use-task-page-jira-creation-projects.ts +33 src/renderer/src/components/task-page/jira/creation/use-task-page-jira-creation-state.ts +2 src/renderer/src/components/task-page/jira/filters/use-task-page-jira-favourite-filters.ts +2 src/renderer/src/components/task-page/jira/creation/use-task-page-jira-issue-creation.ts +1 src/renderer/src/components/task-page/jira/listing/use-task-page-jira-list-effects.ts +2 src/renderer/src/components/task-page/jira/filters/use-task-page-jira-quick-filters.ts +2 src/renderer/src/components/task-page/jira/filters/use-task-page-jira-saved-filters.ts +2 src/renderer/src/components/task-page/jira/creation/use-task-page-jira-summary-generation.ts +1 src/renderer/src/components/task-page/linear/issues/IssueTable.tsx +7 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-board.ts 3 src/renderer/src/components/task-page/linear/use-task-page-linear-context-actions.ts 1 src/renderer/src/components/task-page/linear/use-task-page-linear-context-state.ts -4 src/renderer/src/components/task-page/linear/use-task-page-linear-filter-selection.ts -1 src/renderer/src/components/task-page/linear/use-task-page-linear-issue-creation.ts -1 src/renderer/src/components/task-page/linear/use-task-page-linear-list-effects.ts -6 src/renderer/src/components/task-page/linear/use-task-page-linear-list-presentation.ts -13 src/renderer/src/components/task-page/linear/use-task-page-linear-list-projection.ts -20 src/renderer/src/components/task-page/linear/use-task-page-linear-list-selection.ts -2 src/renderer/src/components/task-page/linear/use-task-page-linear-project-creation.ts +4 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-filter-selection.ts +1 src/renderer/src/components/task-page/linear/creation/use-task-page-linear-issue-creation.ts +1 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-list-effects.ts +6 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-list-presentation.ts +13 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-list-projection.ts +20 src/renderer/src/components/task-page/linear/issues/use-task-page-linear-list-selection.ts +2 src/renderer/src/components/task-page/linear/creation/use-task-page-linear-project-creation.ts 1 src/renderer/src/components/task-page/linear/use-task-page-linear-view-state.ts 10 src/renderer/src/components/task-page/use-task-page-composer-actions.ts 3 src/renderer/src/components/task-page/use-task-page-detail-routing.ts @@ -634,7 +632,7 @@ 1 src/renderer/src/components/terminal-pane/controller/TerminalPaneCodexRestartPortals.tsx 1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-context-actions.ts 3 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-foundation.ts -10 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-projection.ts +2 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-projection.ts 3 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-startup-actions.ts 1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-store-actions.ts 1 src/renderer/src/components/terminal-pane/errors/TerminalErrorToast.tsx @@ -670,9 +668,9 @@ 1 src/renderer/src/components/use-terminal-window-lifecycle.ts 1 src/renderer/src/components/use-terminal-workspace-foundation.ts 1 src/renderer/src/components/virtualized-list.tsx -1 src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-facet-rows.ts -2 src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-git-evidence.ts -1 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-list.tsx +1 src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-facet-rows.ts +2 src/renderer/src/components/workspace-cleanup/candidate-evidence/use-workspace-cleanup-git-evidence.ts +1 src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-candidate-list.tsx 2 src/renderer/src/components/workspace-emoji/useWorkspaceEmojiShortcodeInput.ts 1 src/renderer/src/components/worktree-jump/use-worktree-jump-palette-list-entries.ts 1 src/renderer/src/components/worktree-jump/use-worktree-jump-palette-local-state.ts @@ -691,17 +689,17 @@ 1 src/renderer/src/hooks/composer-state/quick-submit-action.ts 1 src/renderer/src/hooks/composer-state/workspace-identity-state.ts 3 src/renderer/src/hooks/linear-issue-committed-state.ts -1 src/renderer/src/hooks/use-audio-capture.ts +6 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts +4 src/renderer/src/hooks/skills/freshness/useSkillFreshness.ts 1 src/renderer/src/hooks/skills/installation/use-bundled-skill-install.ts +1 src/renderer/src/hooks/use-audio-capture.ts 2 src/renderer/src/hooks/useDetectedAgents.ts 2 src/renderer/src/hooks/useGitHubTaskItems.ts 2 src/renderer/src/hooks/useImmediateMutation.ts -6 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts 1 src/renderer/src/hooks/useIssueMetadata.ts 3 src/renderer/src/hooks/useLinearIssuePublication.ts 1 src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts 1 src/renderer/src/hooks/useSettingsNavigationMetadata.ts -4 src/renderer/src/hooks/skills/freshness/useSkillFreshness.ts 1 src/renderer/src/hooks/useTaskPageGitHubWorkItemMutation.ts 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts 1 src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt index ff53f645ef7..70a2a392065 100644 --- a/config/react-compiler-uncompiled-files.txt +++ b/config/react-compiler-uncompiled-files.txt @@ -3,17 +3,17 @@ # are skipped too. Remove a line once its file is safe to compile. # Render-time reads of providerRuntimeSessionGeneration (lib/provider-runtime-context.ts; hazard live-read-in-memo-block). -src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx -src/renderer/src/components/feature-wall/use-integration-connection-status.ts +src/renderer/src/components/feature-wall/setup/FeatureWallSetupChecklist.tsx +src/renderer/src/components/feature-wall/setup/integrations/use-integration-connection-status.ts src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx -src/renderer/src/components/new-workspace/use-jira-source-connection.ts -src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts +src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts +src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts src/renderer/src/components/task-page/jira/Content.tsx -src/renderer/src/components/task-page/jira/use-task-page-jira-list-projection.ts +src/renderer/src/components/task-page/jira/listing/use-task-page-jira-list-projection.ts src/renderer/src/components/task-page/jira/use-task-page-jira-list-state.ts src/renderer/src/hooks/use-integration-provider-status-refresh.ts @@ -28,6 +28,8 @@ src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-s src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.ts src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts src/renderer/src/components/github-item-dialog/inspect-pull-request/pr-files-combined-diff-body.tsx +src/renderer/src/components/native-chat/tools/runs/NativeChatToolRunMembers.tsx +src/renderer/src/components/native-chat/tools/runs/use-native-chat-tool-run-window.ts src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index ca189d9124d..f8d5f8c4cd8 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -3,17 +3,17 @@ # collector (file-wide). Not counted: destructuring off a global object, a self-rescheduling setTimeout (it must back off or pause while hidden). # This is a RATCHET: counts may only go DOWN. # Prune after removing intervals: pnpm check:recurring-timer-ratchet --prune -1 src/cli/handlers/orchestration/check-keepalive.ts +1 src/cli/orchestration/messages/check-keepalive.ts 1 src/cli/runtime/mac-app-update-bundle.ts 1 src/cli/runtime/serve-supervised-service.ts 1 src/main/agent-hooks/server/server-opencode-binder.ts -1 src/main/automations/retained-run-reconciliation.ts -1 src/main/automations/service.ts +1 src/main/automations/observation/retained-run-reconciliation.ts +1 src/main/automations/automation-service.ts 1 src/main/browser/extensions/native-messaging/browser-extension-native-ports.ts 1 src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts 1 src/main/claude/agent-view/agent-view-bridge.ts 1 src/main/cli/appimage/appimage-serve-preparation.ts -1 src/main/codex-accounts/codex-login-session.ts +1 src/main/codex-accounts/login/codex-login-session.ts 1 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts 1 src/main/crash-reporting/memory/pre-gone-host-memory.ts 1 src/main/crash-reporting/process-exits/process-gone-diagnostics.ts @@ -29,7 +29,7 @@ 1 src/main/hang-watchdog/main-thread-hang-watchdog.ts 2 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-file-subscription.ts 1 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.ts -1 src/main/ipc/runtime-environments/runtime-environment-preference.ts +1 src/main/ipc/runtime-environments/catalog/runtime-environment-preference.ts 1 src/main/ipc/worktrees/git/worktree-git-common-narrow-watch.ts 1 src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts 1 src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts @@ -38,10 +38,10 @@ 1 src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts 1 src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts 1 src/main/notifications/desktop-presence-reporter.ts -1 src/main/orcad/orcad-browser-install-park.ts -1 src/main/orcad/orcad-event-loop-watchdog.ts -1 src/main/orcad/orcad-lock-clone-machine.ts -1 src/main/orcad/orcad-stop-request-listener.ts +1 src/main/orcad/browser-providers/orcad-browser-install-park.ts +1 src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts +1 src/main/orcad/instance-lock/orcad-lock-clone-machine.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts 1 src/main/plugins/catalog/plugin-auto-updater.ts 1 src/main/plugins/catalog/plugin-kill-list-service.ts 1 src/main/plugins/installation/plugin-git-repository.ts @@ -49,13 +49,13 @@ 1 src/main/rate-limits/service/service-polling.ts 1 src/main/runtime/agent-state-rules/agent-state-rules-live-update.ts 1 src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts -3 src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +3 src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts 1 src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts -1 src/main/runtime/rpc/mobile-socket-wiring.ts -1 src/main/runtime/rpc/remote-runtime-server-heartbeat.ts +1 src/main/runtime/rpc/mobile/mobile-socket-wiring.ts +1 src/main/runtime/rpc/transports/websocket/remote-runtime-server-heartbeat.ts 1 src/main/runtime/rpc/server/runtime-metadata-ownership-watch.ts -1 src/main/runtime/rpc/unix-socket-transport.ts -1 src/main/runtime/sidebar-inputs/paired-server-rows-producer.ts +1 src/main/runtime/rpc/transports/unix-socket-transport.ts +1 src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.ts 1 src/main/runtime/terminal/input/agent-prompt-permission-hold.ts 1 src/main/runtime/terminal/output/terminal-derived-agent-facts.ts 1 src/main/runtime/terminal/wait/terminal-idle-polls.ts @@ -64,8 +64,8 @@ 1 src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.ts 1 src/main/ssh/protocol/ssh-channel-multiplexer.ts 1 src/main/startup/configure-process.ts -1 src/main/startup/event-loop-stall-probe.ts -1 src/main/startup/synthetic-title-runtime.ts +1 src/main/startup/diagnostics/event-loop-stall-probe.ts +1 src/main/startup/main-window/synthetic-title-runtime.ts 1 src/main/telemetry/wsl-usage-reporter.ts 1 src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts 1 src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 726d2c4ef77..4b0e70fd71c 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -454,29 +454,25 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime", "mobile-relay"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The broad mobile runner loses retired-name sequencing and PR action samples while retaining the editor-lifetime and original PR action keeper; commit-message generation is unchanged. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The broad mobile command loses the entire three-case mocked diff-review controller suite and the stale layout-sequence comparator sample. Keep only the direct layout-versus-scrollback counter distinction; the unchanged dictation retry hook retains complete recording replay. No rendered app, native capture, actual process death or remote execution is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad mobile discovery loses whole prompt-presentation, Jira-URL and folder-source-repository suites. The prompt suite exercised presentation projections; it did not provide native mobile prompt acknowledgment acceptance. Existing direct prompt-controller selectors are unchanged. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The stale-leaf-liveness suite and its exact command/testFiles selector are removed; its fake terminal refusal/liveness alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1316 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", + "coverageNotes": "Audit3984 retires all four remaining viewport-fixture suites (14 authored/15 finite cases) and the fixture after composing the sender-host deletion. Accepted source-alarm losses include live-region/disclosure continuity, task/question/approval history and revision handling, stale turn status, prompt-dismissal remount/rebind, and pending-send cancellation when approval arrives between body and Enter. No equivalent replacement or fresh runtime validation is claimed. Audits3764/3766 retire16 authored/27 expanded mobile cases, including entire HTML-image syntax, Mermaid routing, table styles, file-query encoding, workspace naming and fresh-Git-status adapter suites. Accepted losses include image width/icon filtering, partial-heading streaming, mocked Mermaid key/identity checks, generated table widths/counts, selected-text caret placement, tiny Base64 chunk encoding, twelve query-path roundtrips, locale-import fallback, apostrophe slugging, fresh-status fallback and an intermediate reviewed marker. These are deliberate removals for marginal value; remaining tests are not equivalent replacements. Earlier receipts are historical and do not validate these deleted/reduced drivers. Audit3748 intentionally removes ten authored/ten finite registrations from the surviving media-handle-registry.test.ts driver selected by this full-mobile command. Retired real alarms: nominal minted handle uniqueness/metadata and dimensions; ordinary range/EOF/overread/empty-file/direct chunk-clamp samples; nominal successful release, expired-release false, exact millisecond TTL boundary and ordinary releaseAll replay. Deterministic registry code runs; these examples are removed on marginal value without replacement or fresh execution claims. Seven owner cases retain cap refusal/disposal and sweep-before-admission, nonempty EOF and unknown/released/expired refusal, read TTL refresh, idempotent explicit release and continuation after discard failure. Existing commands, assertions, unrelated wire receipt and timing remain; the driver survives. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered mobile Vitest command. Its mobile/src include patterns admit the partial live-input-commit and native-media drivers:5 authored/5 finite removals. Accepted losses: two Android-labeled replay samples after mocked composition conversion, an immediate Backspace absence check that does not wait for pending commit or prove local edit, and released-handle/double-release adapter examples. Real hook, registry and adapter logic run; no equivalent replacement or native Android/iOS exercise is claimed. Both drivers and selector stay. The unchanged wire-specific dated receipt does not validate these reduced mobile sources. Audit3666 removes30 authored/36 finite mobile cases, including7 whole drivers. It retires direct consent/channel/token/header-payload/fingerprint/route-object inventories, background legacy-dismissal filtering, the two-row520-entry watermark retention workload, reentrant write-batch example, font-before-ready projection, and legacy-segmenter/scrollback/wrap selection examples. Actual policy, parsing, hashing, tray matching, serialization and xterm buffers execute in these tests; their stated alarms are deliberately lost without replacement. Twelve unchanged authored/19 finite cases retain compact browser geometry regressions, an independent fingerprint-to-host protocol vector, serialized watermark/reload isolation, OSC52 live/replay gating, queue boundaries/reset/generation, disposed font completion and Unicode cell mapping. Pairing classification2/2 was already approved by3657 and receives no3666 delta or credit. Static review only; no runtime, native, provider, browser rendering, OS, remote, mobile/folder parity or new historical fault evidence. Previous account (preserved verbatim): Audit3663 removes the complete mobile scan-error message suite (two authored/two finite callbacks). Its4URL assertion loop is one registration. Accept loss of Orca new/legacy Android-download URL classification and other-page invalid-code translated-key mapping. Real URL parsing/classification runs, but the only output observed is an identity-translator key. No camera scan, pairing offer admission, connection or device/UI action is exercised. No equivalent replacement or physical/mobile/mixed-version result claimed. Preserve all historical evidence and metadata bytes. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The broad mobile runner loses retired-name sequencing and PR action samples while retaining the editor-lifetime and original PR action keeper; commit-message generation is unchanged. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The broad mobile command loses the entire three-case mocked diff-review controller suite and the stale layout-sequence comparator sample. Keep only the direct layout-versus-scrollback counter distinction; the unchanged dictation retry hook retains complete recording replay. No rendered app, native capture, actual process death or remote execution is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad mobile discovery loses whole prompt-presentation, Jira-URL and folder-source-repository suites. The prompt suite exercised presentation projections; it did not provide native mobile prompt acknowledgment acceptance. Existing direct prompt-controller selectors are unchanged. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The stale-leaf-liveness suite and its exact command/testFiles selector are removed; its fake terminal refusal/liveness alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1316 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/25761"], "invariant": "A prompt occurrence leaves the input region only when an accepted reply answers it (a current host's provider acknowledgment, or an older host's whole-write acceptance as before) or the user collapses it to a strip above the composer, which writes nothing and keeps the card mounted with its partial answer; status-backed occurrences are told apart by the host wait's start, so view toggles and remounts preserve them while real clear/replacement supersedes them, and a transcript-only one is dropped when the view stops observing it; obsolete results cannot change replacements; selector groups wait for complete writes before pacing; refusal or unknown handoff never causes replay; a card retires an unsubmitted composer send without writing under it or losing its text, and the hidden composer cannot send or interrupt; Collapse or Escape folds a card without writing, never during an in-flight answer, and a new occurrence shows expanded again; the phone blocks only Send while a card is expanded and shows one card per occurrence; cancellation stops unsent groups and active dictation can stop.", - "oracle": "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The broad mobile runner loses retired-name sequencing and PR action samples while retaining the editor-lifetime and original PR action keeper; commit-message generation is unchanged. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The broad mobile command loses the entire three-case mocked diff-review controller suite and the stale layout-sequence comparator sample. Keep only the direct layout-versus-scrollback counter distinction; the unchanged dictation retry hook retains complete recording replay. No rendered app, native capture, actual process death or remote execution is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad mobile discovery loses whole prompt-presentation, Jira-URL and folder-source-repository suites. The prompt suite exercised presentation projections; it did not provide native mobile prompt acknowledgment acceptance. Existing direct prompt-controller selectors are unchanged. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The stale-leaf-liveness suite and its exact command/testFiles selector are removed; its fake terminal refusal/liveness alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", + "oracle": "Audits3764/3766 retire16 authored/27 expanded mobile cases, including entire HTML-image syntax, Mermaid routing, table styles, file-query encoding, workspace naming and fresh-Git-status adapter suites. Accepted losses include image width/icon filtering, partial-heading streaming, mocked Mermaid key/identity checks, generated table widths/counts, selected-text caret placement, tiny Base64 chunk encoding, twelve query-path roundtrips, locale-import fallback, apostrophe slugging, fresh-status fallback and an intermediate reviewed marker. These are deliberate removals for marginal value; remaining tests are not equivalent replacements. Earlier receipts are historical and do not validate these deleted/reduced drivers. Audit3748 intentionally removes ten authored/ten finite registrations from the surviving media-handle-registry.test.ts driver selected by this full-mobile command. Retired real alarms: nominal minted handle uniqueness/metadata and dimensions; ordinary range/EOF/overread/empty-file/direct chunk-clamp samples; nominal successful release, expired-release false, exact millisecond TTL boundary and ordinary releaseAll replay. Deterministic registry code runs; these examples are removed on marginal value without replacement or fresh execution claims. Seven owner cases retain cap refusal/disposal and sweep-before-admission, nonempty EOF and unknown/released/expired refusal, read TTL refresh, idempotent explicit release and continuation after discard failure. Existing commands, assertions, unrelated wire receipt and timing remain; the driver survives. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered mobile Vitest command. Its mobile/src include patterns admit the partial live-input-commit and native-media drivers:5 authored/5 finite removals. Accepted losses: two Android-labeled replay samples after mocked composition conversion, an immediate Backspace absence check that does not wait for pending commit or prove local edit, and released-handle/double-release adapter examples. Real hook, registry and adapter logic run; no equivalent replacement or native Android/iOS exercise is claimed. Both drivers and selector stay. The unchanged wire-specific dated receipt does not validate these reduced mobile sources. Audit3666 removes30 authored/36 finite mobile cases, including7 whole drivers. It retires direct consent/channel/token/header-payload/fingerprint/route-object inventories, background legacy-dismissal filtering, the two-row520-entry watermark retention workload, reentrant write-batch example, font-before-ready projection, and legacy-segmenter/scrollback/wrap selection examples. Actual policy, parsing, hashing, tray matching, serialization and xterm buffers execute in these tests; their stated alarms are deliberately lost without replacement. Twelve unchanged authored/19 finite cases retain compact browser geometry regressions, an independent fingerprint-to-host protocol vector, serialized watermark/reload isolation, OSC52 live/replay gating, queue boundaries/reset/generation, disposed font completion and Unicode cell mapping. Pairing classification2/2 was already approved by3657 and receives no3666 delta or credit. Static review only; no runtime, native, provider, browser rendering, OS, remote, mobile/folder parity or new historical fault evidence. Previous oracle (preserved verbatim): Audit3663 removes the complete mobile scan-error message suite (two authored/two finite callbacks). Its4URL assertion loop is one registration. Accept loss of Orca new/legacy Android-download URL classification and other-page invalid-code translated-key mapping. Real URL parsing/classification runs, but the only output observed is an identity-translator key. No camera scan, pairing offer admission, connection or device/UI action is exercised. No equivalent replacement or physical/mobile/mixed-version result claimed. Preserve all historical evidence and metadata bytes. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The broad mobile runner loses retired-name sequencing and PR action samples while retaining the editor-lifetime and original PR action keeper; commit-message generation is unchanged. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The broad mobile command loses the entire three-case mocked diff-review controller suite and the stale layout-sequence comparator sample. Keep only the direct layout-versus-scrollback counter distinction; the unchanged dictation retry hook retains complete recording replay. No rendered app, native capture, actual process death or remote execution is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad mobile discovery loses whole prompt-presentation, Jira-URL and folder-source-repository suites. The prompt suite exercised presentation projections; it did not provide native mobile prompt acknowledgment acceptance. Existing direct prompt-controller selectors are unchanged. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The stale-leaf-liveness suite and its exact command/testFiles selector are removed; its fake terminal refusal/liveness alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --maxWorkers=1", - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts --maxWorkers=2" ], "testFiles": [ "src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx", - "src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx", - "src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx", - "src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx", "src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts", "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts", "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts", "src/main/ipc/pty/ipc/write-input-user-input.test.ts", "src/main/ipc/pty/pty-write-ipc-validation.test.ts", "src/main/runtime/terminal/input/runtime-terminal-writer.test.ts", - "src/main/runtime/rpc/terminal-send.test.ts", "mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts", "tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts" ], @@ -499,19 +495,6 @@ "keeps structured answer controls after a thrown send" ] }, - { - "file": "src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx", - "assertions": [ - "keeps an in-flight message visible and never submits it into the approval", - "routes no typing to the hidden composer until the card is answered" - ] - }, - { - "file": "src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx", - "assertions": [ - "keeps an answered approval hidden across a chat view remount and a PTY rebind" - ] - }, { "file": "src/main/runtime/terminal/input/runtime-terminal-writer.test.ts", "assertions": [ @@ -550,6 +533,13 @@ "evidence": "No fresh reduced-source performance measurement is claimed. Historical account: Historical prior-selector budget; changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. No polling, subprocess, startup await, new status producer or dismissal timer. Reuses the existing bounded per-tab committed observation and per-PTY queue; waits for each group before its existing pacing timer. Duplicate-cancel and yielding chunk tests bound writes. Optional paired proof reuses provider settlement only for requesting clients; legacy requests keep their raw path." }, "knownGaps": [ + "Audit3984 retires all four remaining viewport-fixture suites (14 authored/15 finite cases) and the fixture after composing the sender-host deletion. Accepted source-alarm losses include live-region/disclosure continuity, task/question/approval history and revision handling, stale turn status, prompt-dismissal remount/rebind, and pending-send cancellation when approval arrives between body and Enter. No equivalent replacement or fresh runtime validation is claimed.", + "Audit3984 retired assertionRefs, preserved verbatim as historical values; not active coverage: [{\"file\":\"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\"assertions\":[\"keeps an in-flight message visible and never submits it into the approval\",\"routes no typing to the hidden composer until the card is answered\"]},{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\"assertions\":[\"keeps an answered approval hidden across a chat view remount and a PTY rebind\"]}]", + "Audits3764/3766 retire16 authored/27 expanded mobile cases, including entire HTML-image syntax, Mermaid routing, table styles, file-query encoding, workspace naming and fresh-Git-status adapter suites. Accepted losses include image width/icon filtering, partial-heading streaming, mocked Mermaid key/identity checks, generated table widths/counts, selected-text caret placement, tiny Base64 chunk encoding, twelve query-path roundtrips, locale-import fallback, apostrophe slugging, fresh-status fallback and an intermediate reviewed marker. These are deliberate removals for marginal value; remaining tests are not equivalent replacements. Earlier receipts are historical and do not validate these deleted/reduced drivers.", + "Audit3748 intentionally removes ten authored/ten finite registrations from the surviving media-handle-registry.test.ts driver selected by this full-mobile command. Retired real alarms: nominal minted handle uniqueness/metadata and dimensions; ordinary range/EOF/overread/empty-file/direct chunk-clamp samples; nominal successful release, expired-release false, exact millisecond TTL boundary and ordinary releaseAll replay. Deterministic registry code runs; these examples are removed on marginal value without replacement or fresh execution claims. Seven owner cases retain cap refusal/disposal and sweep-before-admission, nonempty EOF and unknown/released/expired refusal, read TTL refresh, idempotent explicit release and continuation after discard failure. Existing commands, assertions, unrelated wire receipt and timing remain; the driver survives.", + "Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered mobile Vitest command. Its mobile/src include patterns admit the partial live-input-commit and native-media drivers:5 authored/5 finite removals. Accepted losses: two Android-labeled replay samples after mocked composition conversion, an immediate Backspace absence check that does not wait for pending commit or prove local edit, and released-handle/double-release adapter examples. Real hook, registry and adapter logic run; no equivalent replacement or native Android/iOS exercise is claimed. Both drivers and selector stay. The unchanged wire-specific dated receipt does not validate these reduced mobile sources.", + "Audit3666 removes30 authored/36 finite mobile cases, including7 whole drivers. It retires direct consent/channel/token/header-payload/fingerprint/route-object inventories, background legacy-dismissal filtering, the two-row520-entry watermark retention workload, reentrant write-batch example, font-before-ready projection, and legacy-segmenter/scrollback/wrap selection examples. Actual policy, parsing, hashing, tray matching, serialization and xterm buffers execute in these tests; their stated alarms are deliberately lost without replacement. Twelve unchanged authored/19 finite cases retain compact browser geometry regressions, an independent fingerprint-to-host protocol vector, serialized watermark/reload isolation, OSC52 live/replay gating, queue boundaries/reset/generation, disposed font completion and Unicode cell mapping. Pairing classification2/2 was already approved by3657 and receives no3666 delta or credit. Static review only; no runtime, native, provider, browser rendering, OS, remote, mobile/folder parity or new historical fault evidence.", + "Audit3663 removes the complete mobile scan-error message suite (two authored/two finite callbacks). Its4URL assertion loop is one registration. Accept loss of Orca new/legacy Android-download URL classification and other-page invalid-code translated-key mapping. Real URL parsing/classification runs, but the only output observed is an identity-translator key. No camera scan, pairing offer admission, connection or device/UI action is exercised. No equivalent replacement or physical/mobile/mixed-version result claimed. Preserve all historical evidence and metadata bytes.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope.", "Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope.", @@ -605,7 +595,8 @@ "Complete prior testFiles before exact deleted selectors were pruned: [\"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx\",\"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\"src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx\",\"src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts\",\"src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts\",\"src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts\",\"src/main/ipc/pty/ipc/write-input-user-input.test.ts\",\"src/main/ipc/pty/pty-write-ipc-validation.test.ts\",\"src/main/runtime/terminal/input/runtime-terminal-writer.test.ts\",\"src/main/runtime/rpc/terminal-send.test.ts\",\"src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts\",\"mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts\",\"tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts\"]", "Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad mobile discovery loses whole prompt-presentation, Jira-URL and folder-source-repository suites. The prompt suite exercised presentation projections; it did not provide native mobile prompt acknowledgment acceptance. Existing direct prompt-controller selectors are unchanged. All prior notes, assertion references and complete dated receipts retain their original historical scopes.", "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The broad mobile command loses the entire three-case mocked diff-review controller suite and the stale layout-sequence comparator sample. Keep only the direct layout-versus-scrollback counter distinction; the unchanged dictation retry hook retains complete recording replay. No rendered app, native capture, actual process death or remote execution is claimed. All prior notes and archived receipts retain original scopes.", - "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The broad mobile runner loses retired-name sequencing and PR action samples while retaining the editor-lifetime and original PR action keeper; commit-message generation is unchanged. Earlier notes, complete dated receipts and archived gaps retain their original scopes." + "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The broad mobile runner loses retired-name sequencing and PR action samples while retaining the editor-lifetime and original PR action keeper; commit-message generation is unchanged. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", + "Audit3911 removes terminal-send.test.ts and accepts loss of its supplied client/query-reply refusal, oversized ASCII error-redaction, and oversized emoji byte-limit guard alarms. Remaining tests do not replace these three deleted cases; archived evidence remains historical." ], "promotionCriteria": [ "Record change-reverted red/green evidence and repeatable remote rendered approval/question/dictation journeys.", @@ -1234,12 +1225,12 @@ "invariant": "Failed bootstrap and authenticated reconnect converge without UI triggers; one connection owner publishes verified status, with no independent healthy status polling.", "oracle": "Audit 3301 removes the failed-verification/recovery/restart generation and host-contact-epoch, hosting and no-toast example from runtime-status-snapshot.test.ts. Earlier prose describing that example as retained is historical. Disconnect/pairing retirement and delayed catalog replay remain unchanged without equivalent replacement. Archive both complete historical 22-case unit receipts because their selector includes the reduced source; preserve the unrelated rendered receipt, current selectors and other-owner assertion references. No fresh aggregate or live host validation is claimed. Linux coverage from those two unit runs is historical; current covered-platform scope is limited to the preserved macOS rendered receipt. Retained local cases check independent waiter deadlines/cancellation, failed-operation recovery, stale deferred results, disposal and explicit reconnect after authentication refusal. Historical aggregate receipts predate audit1748 and are not fresh validation of reduced sources.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts", "ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts", - "src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts", + "src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts", "src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts", "src/renderer/src/web/web-runtime-status-owner.test.ts", "tests/e2e/runtime-host-status-recovery.spec.ts" @@ -1308,10 +1299,10 @@ "providers": ["local", "remote-runtime"], "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit1670 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Actual startOrcad entry with mocked daemon/RPC startup boundaries; real controller, push service, and persisted device registry. Gateway send is stubbed.", + "coverageNotes": "Audit3738 removes the explicit-registration seven-day lease example from desktop-push-service.test.ts. Its register/registry expiry arithmetic was real, but the ordinary dispatch omitted notificationSeq/notificationEpoch and returned null before target enumeration/send, so it did not prove delivery leaves a lease unchanged. The exact expiry and explicit-renewal alarm is intentionally retired without replacement. This gate already has no active commands, testFiles, assertionRefs or evidenceRuns; prior lease oracle text is historical intent, not a current retained execution claim. Audit1670 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Actual startOrcad entry with mocked daemon/RPC startup boundaries; real controller, push service, and persisted device registry. Gateway send is stubbed.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/19204"], "invariant": "Headless startup installs and disposes push delivery; desktop notification categories remain authoritative, the three-minute away policy is preserved, and host activity cannot extend the seven-day mobile lease.", - "oracle": "Require registration after RPC identity initialization and shutdown cleanup; idle 179/180/0 yields false/true/false in retained event metadata and exactly one gateway push. Legacy socket subscriptions preserve notification filtering, while opted-in push clients can request dismissal reconciliation. Desktop categories remain authoritative. Persisted lease expires exactly at seven days and only explicit registration renews it.", + "oracle": "Audit3738 removes the explicit-registration seven-day lease example from desktop-push-service.test.ts. Its register/registry expiry arithmetic was real, but the ordinary dispatch omitted notificationSeq/notificationEpoch and returned null before target enumeration/send, so it did not prove delivery leaves a lease unchanged. The exact expiry and explicit-renewal alarm is intentionally retired without replacement. This gate already has no active commands, testFiles, assertionRefs or evidenceRuns; prior lease oracle text is historical intent, not a current retained execution claim. Require registration after RPC identity initialization and shutdown cleanup; idle 179/180/0 yields false/true/false in retained event metadata and exactly one gateway push. Legacy socket subscriptions preserve notification filtering, while opted-in push clients can request dismissal reconciliation. Desktop categories remain authoritative. Persisted lease expires exactly at seven days and only explicit registration renews it.", "commands": [], "testFiles": [], "assertionRefs": [], @@ -1334,6 +1325,7 @@ }, "promotionCriteria": ["Collect repeated CI runs without unexplained failures."], "knownGaps": [ + "Audit3738 removes the explicit-registration seven-day lease example from desktop-push-service.test.ts. Its register/registry expiry arithmetic was real, but the ordinary dispatch omitted notificationSeq/notificationEpoch and returned null before target enumeration/send, so it did not prove delivery leaves a lease unchanged. The exact expiry and explicit-renewal alarm is intentionally retired without replacement. This gate already has no active commands, testFiles, assertionRefs or evidenceRuns; prior lease oracle text is historical intent, not a current retained execution claim.", "Audit1670 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Does not prove APNs silent background wakeup or actual operating-system idle transitions.", "Rendererless agent/bell event generation remains outside the documented feature contract.", @@ -2190,22 +2182,19 @@ "providers": ["local-daemon", "ssh-daemon", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon"], - "coverageNotes": "Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real TerminalHost, Session, and subprocess wrapper with injected native I/O failures and mocked OS signals. Local non-daemon and SSH-relay implementations are unaffected; daemon consumers on SSH, WSL, paired runtimes, and mobile retain host-owned semantics. Live Linux/Windows/WSL and remote runs remain gaps. No git or folder-workspace assumptions. The fault-injection suite also runs with simulated darwin/linux/win32 platform branches; these do not constitute native OS coverage. Native macOS coverage now proves shell exit and PTY master-fd closure, input/output round trips, and teardown of a paused producer for both graceful and immediate cleanup. Windows single-close/job escalation and pre-listener output/status are fault-injected contracts. Audit1302: src/main/daemon/terminal-host-teardown-recreate.test.ts: Fake subprocess handles synthesize exits via real40ms/30s timers or manual exit callback, with descendant retirement mocked away; assertions inspect isNew/refusal/spawn counts. No real subprocess/PTY teardown/recreation or owned-tree retention boundary. Lose artificial teardown/attach/shutdown/cancellation scheduling alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", + "coverageNotes": "Audit4358 intentionally removes six whole mocked daemon subprocess suites and two extra pre-listener replay variants (18 authored / 20 finite cases). Lost alarms include cancel-during-cwd-validation, root agent startup refusal, output/exit before ConPTY publication, fresh/delayed/unavailable foreground confirmation, cache/decision separation, detached/no-tty child evidence and synthetic agent authorization. The retained lifecycle case checks data and exit replay after handle creation, not startup-time publication or alternate listener order. The retained native Windows Git Bash workflow and host cold-restore seed check have separate scopes. No equivalent replacement or fresh gate execution is claimed. Earlier notes and dated receipts retain their original scope. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real TerminalHost, Session, and subprocess wrapper with injected native I/O failures and mocked OS signals. Local non-daemon and SSH-relay implementations are unaffected; daemon consumers on SSH, WSL, paired runtimes, and mobile retain host-owned semantics. Live Linux/Windows/WSL and remote runs remain gaps. No git or folder-workspace assumptions. The fault-injection suite also runs with simulated darwin/linux/win32 platform branches; these do not constitute native OS coverage. Archived native macOS results previously exercised shell exit and PTY master-fd closure, input/output round trips, and teardown of a paused producer; that suite is now retired without replacement. Windows single-close/job escalation and pre-listener output/status are fault-injected contracts. Audit1302: src/main/daemon/terminal-host-teardown-recreate.test.ts: Fake subprocess handles synthesize exits via real40ms/30s timers or manual exit callback, with descendant retirement mocked away; assertions inspect isNew/refusal/spawn counts. No real subprocess/PTY teardown/recreation or owned-tree retention boundary. Lose artificial teardown/attach/shutdown/cancellation scheduling alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.\nOrcad folder cleanup intentionally retires the Cartesian native failed-I/O test under repository test policy, without equivalent replacement. Remaining selectors retain their narrower scope. Dated evidenceRuns remain historical and do not validate this changed selector.", "motivatingLinks": ["docs/terminal-daemon-session-leak-investigation.md"], "invariant": "I/O errors must not establish physical exit or disable termination of an owned PTY. Session and native handle disposal require the exit event.", - "oracle": "Inject write and resize failures, require graceful and forced signals to reach the native owner, keep producer resume available, suppress repeated failed I/O, deliver output and exit, and suppress signals after exit. Across 32 create/close cycles per failure, retain each session before exit and release its native handle and emulator exactly once afterwards. Mark physical exit before notifying listeners; reentrant kill/forceKill/signal from those listeners must never signal the retired PID. A native POSIX test performs input/output and resize, pauses the producer, injects each I/O failure, then gracefully or immediately closes 16 real shells; require ESRCH for each child PID and EBADF for each PTY master fd.", + "oracle": "Audit4358 intentionally removes six whole mocked daemon subprocess suites and two extra pre-listener replay variants (18 authored / 20 finite cases). Lost alarms include cancel-during-cwd-validation, root agent startup refusal, output/exit before ConPTY publication, fresh/delayed/unavailable foreground confirmation, cache/decision separation, detached/no-tty child evidence and synthetic agent authorization. The retained lifecycle case checks data and exit replay after handle creation, not startup-time publication or alternate listener order. The retained native Windows Git Bash workflow and host cold-restore seed check have separate scopes. No equivalent replacement or fresh gate execution is claimed. Earlier notes and dated receipts retain their original scope. Inject write and resize failures, require graceful and forced signals to reach the native owner, keep producer resume available, suppress repeated failed I/O, deliver output and exit, and suppress signals after exit. Across 32 create/close cycles per failure, retain each session before exit and release its native handle and emulator exactly once afterwards. Mark physical exit before notifying listeners; reentrant kill/forceKill/signal from those listeners must never signal the retired PID. The former native POSIX shell/PID/fd oracle is retired without replacement.", "commands": [ "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts", - "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts src/main/daemon/sessions/testing/session.test.ts", - "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts" + "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts" ], "testFiles": [ "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts", "src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts", "src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts", - "src/main/daemon/sessions/testing/session.test.ts", - "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts" + "src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts" ], "assertionRefs": [ { @@ -2216,10 +2205,6 @@ "suppresses repeated native I/O failures while still delivering output and exit", "blocks reentrant termination from an exit listener after I/O failure" ] - }, - { - "file": "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts", - "assertions": ["reaps real shells and master fds after %s failure (immediate=%s)"] } ], "evidenceRuns": [ @@ -2232,16 +2217,6 @@ "durationSeconds": 3.71, "summary": "32 tests passed with 4 Windows-only cases skipped; simulated macOS/Linux/Windows branches include 192 failed-I/O create/close cycles and exit-listener reentrancy.", "currentCommand": "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts" - }, - { - "date": "2026-09-07", - "runner": "local", - "platform": "macos", - "command": "pnpm test src/main/daemon/pty-subprocess-io-failure-native.test.ts", - "result": "passed", - "durationSeconds": 2.52, - "summary": "Four native cases pass across 16 real shells, including input/output, pause before teardown, confirmed PID absence, and closed PTY master fds.", - "currentCommand": "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts" } ], "runtimeBudget": { @@ -2266,10 +2241,11 @@ "knownGaps": [ "Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Fault injection proves a leak mechanism, not causality for the historical 427-session incident.", - "Real Linux/Windows/WSL, remote, startup-close, login-wrapper descendants, and multi-day load evidence remain outstanding. Native tests inject synchronous I/O errors; they do not model every asynchronous node-pty pipe failure.", + "Real Linux/Windows/WSL, remote, startup-close, login-wrapper descendants, and multi-day load evidence remain outstanding. The archived native tests injected synchronous I/O errors; they did not model every asynchronous node-pty pipe failure. No active native-shell coverage remains after their retirement.", "No output throughput change or interactive latency benchmark is included.", "Audit1302: src/main/daemon/terminal-host-teardown-recreate.test.ts: Fake subprocess handles synthesize exits via real40ms/30s timers or manual exit callback, with descendant retirement mocked away; assertions inspect isNew/refusal/spawn counts. No real subprocess/PTY teardown/recreation or owned-tree retention boundary. Lose artificial teardown/attach/shutdown/cancellation scheduling alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", - "Audit1302 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm test src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host-teardown-recreate.test.ts src/main/daemon/terminal-session-teardown.test.ts src/main/daemon/session.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.617,\n \"summary\": \"136 tests passed across six files; failed-I/O cycle tests cover 64 closures.\"\n }" + "Audit1302 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm test src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host-teardown-recreate.test.ts src/main/daemon/terminal-session-teardown.test.ts src/main/daemon/session.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.617,\n \"summary\": \"136 tests passed across six files; failed-I/O cycle tests cover 64 closures.\"\n }", + "Orcad owner layout retires this native test receipt without replacement. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm test src/main/daemon/pty-subprocess-io-failure-native.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 2.52,\n \"summary\": \"Four native cases pass across 16 real shells, including input/output, pause before teardown, confirmed PID absence, and closed PTY master fds.\",\n \"currentCommand\": \"pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts\"\n }" ], "demotionRule": "Keep experimental; investigate any lost cleanup signal, premature exit, or unexplained flake." }, @@ -2290,13 +2266,13 @@ "providers": ["local", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. The integrated mobile markdown close/frame-settlement case remains unchanged and is narrower. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. The integrated mobile markdown close/frame-settlement case remains unchanged and is narrower. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4965", "https://github.com/stablyai/orca/pull/15371" ], "invariant": "Candidate identity is the tuple of execution-host identity and worktree identity: same-id sibling hosts retain separate correct browser, simulator, and workspace tabs, each tab appears exactly once, and selection activates its owning host.", - "oracle": "Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. The integrated mobile markdown close/frame-settlement case remains unchanged and is narrower. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", + "oracle": "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. The integrated mobile markdown close/frame-settlement case remains unchanged and is narrower. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", @@ -2422,6 +2398,7 @@ "Add a live paired-runtime-over-SSH journey when the E2E harness can provision that combined topology." ], "knownGaps": [ + "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence.", "Audit2729 retires browser palette standalone paired-runtime SSH alias forwarding, multigroup-view acceptance and remote-folder forwarding alarms without equivalent replacement. The retained partial suite has no fresh execution result; existing exact receipts and budgets stay scoped to their unchanged selectors.", "Audit2697/2702 intentional palette coverage losses: 'omits a browser row whose backing tab id is duplicated': Remove malformed duplicate unified-tab-ID fixture and its empty result. Real duplicate-ID suppression alarm is lost; this narrow private inventory has no palette selection or activation flow. 'omits a workspace claimed by more than one unified browser tab': Remove two unified browser claims of one workspace. Real first-indexed-foreign-versus-later-owned collision rejection alarm is lost; same-host and ambiguous legacy cases do not replace it. 'omits a workspace whose single unified browser tab is not owned by this worktree': Remove one unique workspace backed by foreign-worktree unified tab fixture. Real foreign-tab/worktree rejection alarm is lost; stamped host tests are not equivalent to foreign worktree mismatch. 'indexes workspace tabs when building a large browser palette': Remove internal getter read budget over1000workspaces: current main policy explicitly rejects getter/Proxy/read counts and says performance changes get correctness tests only. Loses direct quadratic-indexing cost alarm and positive1000workspace output check; no equivalent replacement claimed. The same source review also deletes browser-link-profile-isolation.test.ts (two authored/five expanded) and removes two HTTP-routing declarations (three expanded). Exact tracked-tree filename/case search finds no active gate selector/assertionRef for those navigation sources; their local profile isolation/reuse, deferred minted-profile privacy/lifetime, foreground view/group projection and contextless must-create-page alarms still disappear without replacement. This palette gate is not credited with coverage of those unrelated navigation cases. Historical shard timings are retained unchanged. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added.", "Live Linux, Windows, and paired-runtime-over-SSH journeys are not collected; the SSH/runtime dual-owner topology is deterministic renderer coverage.", @@ -2634,7 +2611,7 @@ "providers": ["local", "local-daemon", "ssh-daemon", "ssh-relay", "paired-runtime"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "local-daemon", "ssh-relay", "paired-runtime"], - "coverageNotes": "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real macOS node-pty integration covers zsh 5.9 .zshenv/.zprofile and bash 3.2 profile replacement shells, including exec -a names, same-shell and child-process silent reads, a blocking zle-line-init hook, non-shell readline replacements, and a non-shell image renamed zsh. A real Fish PTY proves marker stripping is byte-exact and does not render bracketed-paste control text. Ubuntu 20.04/Bash 5.0 and Ubuntu 24.04/Bash 5.2 containers cover scalar and array PROMPT_COMMAND composition, including real zoxide on 24.04. Deterministic owner contracts cover local, daemon, and SSH relay identity/readiness composition plus provider-owned delivery; explicit terminal-paste remains renderer-owned. Live isolated journeys cover a macOS headed desktop owner with paired web client, headless orca serve with paired web client, and a Docker Linux OpenSSH/Bash target with one readiness-time reconnect. Linux desktop, WSL/Windows, live zsh-over-SSH, and physical remote hosts remain gaps.", + "coverageNotes": "Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real macOS node-pty integration covers zsh 5.9 .zshenv/.zprofile and bash 3.2 profile replacement shells, including exec -a names, same-shell and child-process silent reads, a blocking zle-line-init hook, non-shell readline replacements, and a non-shell image renamed zsh. A real Fish PTY proves marker stripping is byte-exact and does not render bracketed-paste control text. Ubuntu 20.04/Bash 5.0 and Ubuntu 24.04/Bash 5.2 containers cover scalar and array PROMPT_COMMAND composition, including real zoxide on 24.04. Deterministic owner contracts cover local, daemon, and SSH relay identity/readiness composition plus provider-owned delivery; explicit terminal-paste remains renderer-owned. Live isolated journeys cover a macOS headed desktop owner with paired web client, headless orca serve with paired web client, and a Docker Linux OpenSSH/Bash target with one readiness-time reconnect. Linux desktop, WSL/Windows, live zsh-over-SSH, and physical remote hosts remain gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13767", "https://linear.app/stably/issue/STA-4067", @@ -2647,8 +2624,8 @@ "invariant": "Shell startup scanning preserves every non-Orca output byte in order across arbitrary PTY chunk boundaries. Bash scalar and supported array PROMPT_COMMAND values preserve user bytes, hook order, and foreground exit status while emitting exactly one OSC 133 A/C/D lifecycle without syntax errors. Before user startup files run, the wrapper publishes its shell PID. If a later exec discards the ready marker, proof-based recovery releases queued startup input only after the launched shell's actual executable image with that exact PID owns the PTY foreground, emits its post-hook line-editor enable sequence, and exposes zle/readline termios; startup reads, line-init hooks, child foreground processes, and non-shell readline replacements cannot trigger that proof. The existing bounded compatibility timeout may enqueue input without proof, but must not publish readiness, lose or duplicate that input across reconnect, or execute it before the replacement shell can accept it.", "oracle": "Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Split Fish output immediately after the ready marker and after the following ESC introducer; local and daemon owners must emit the exact ESC [ ? 2004 h bytes and headless xterm must not render literal control text. Run the real generated wrappers under node-pty with disposable zsh, bash, and Fish startup files. Exercise Bash scalar and array PROMPT_COMMAND values with empty, repeated, escaped, whitespace, control-byte, odd-backslash, status-mutating, DEBUG-trap, zoxide, and RHEL-style hooks; require exact A,C,D:0,A,C,D:1,A,C ordering and byte preservation. Plain and exec -a replacement shells must receive one queued command at their first completed line editor without waiting for the 15-second timeout. The identical oracle must time out without the startup identity and prompt fallback. Same-shell reads, child-process reads, a blocking zle-line-init hook, sqlite3, and sqlite3 renamed zsh must not trigger prompt fallback. Relay owner coverage must use the same lossless scanner composition and release through the same prompt contract.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/main/pty/shell-startup/line-editor-ready-output-scanner.test.ts src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/pty/shell-startup/line-editor-ready-output-scanner.test.ts src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/main/pty/shell-startup/line-editor-ready-output-scanner.test.ts src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/pty/shell-startup/line-editor-ready-output-scanner.test.ts src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts", "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1" ], @@ -2660,7 +2637,6 @@ "src/main/pty/shell-startup/shell-startup-output-scanner.test.ts", "src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts", "src/shared/terminal/pty/native-process/shell-process-readiness.test.ts", - "src/main/daemon/sessions/testing/session.test.ts", "src/main/daemon/shell-readiness/testing/shell-ready.test.ts", "src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts", "src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts", @@ -3269,7 +3245,7 @@ "id": "desktop-relay.assignment-backpressure", "title": "Desktop relay drain recovery cannot amplify a director outage", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "desktop-runtime", "layer": "main-relay-state-machine", "surfaces": [ @@ -3279,50 +3255,16 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["cloud-relay"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["cloud-relay"], - "coverageNotes": "Deterministic main-process tests cover duplicate drain notifications, full-jitter backoff, Retry-After during initial setup and drain recovery, successful recovery, and broker-close cleanup. Packaged desktop, mixed-version fleets, GFE, and production Cloud SQL remain live-test gaps.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "D42 RPC owner layout has no unchanged passed current receipt for this gate; no fresh execution or replacement coverage claimed. Historical prior account (preserved): Deterministic main-process tests cover duplicate drain notifications, full-jitter backoff, Retry-After during initial setup and drain recovery, successful recovery, and broker-close cleanup. Packaged desktop, mixed-version fleets, GFE, and production Cloud SQL remain live-test gaps.", "motivatingLinks": ["https://github.com/stablyai/orca-cloud/actions/runs/30223521062"], "invariant": "One relay host may have at most one assignment attempt or retry timer per recovery path. Sustained director failure must increase the retry window up to five minutes, a bounded Retry-After must be respected during initial setup and drain recovery, shutdown must cancel pending work, and recovery must activate the authoritative assigned origin.", "oracle": "Inject duplicate drain events, deterministic randomness, fake time, repeated assignment failures, a 30-second Retry-After during initial setup and drain recovery, broker close, and eventual director recovery. Count every assignment call, require 500 ms then 1,000 ms retry windows, reject duplicate fanout, require no pre-hint retry or post-close work, and prove the recovered cell becomes authoritative.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts --reporter=dot" - ], - "testFiles": [ - "src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts", - "src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts", - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts", - "assertions": [ - "duplicate drain notifications share one exponentially backed-off retry schedule", - "Retry-After suppresses early assignment requests", - "broker close prevents retry resurrection", - "a later successful assignment activates the new origin" - ] - }, - { - "file": "src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts", - "assertions": ["assignment overload preserves a bounded Retry-After hint"] - }, - { - "file": "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts", - "assertions": ["initial relay setup does not retry before Retry-After expires"] - } - ], - "evidenceRuns": [ - { - "date": "2026-07-26", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts --reporter=dot", - "result": "passed", - "durationSeconds": 0.49, - "summary": "Three focused relay files passed with 25 assertions." - } - ], + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 5, "scope": "focused desktop relay state-machine tests" @@ -3347,7 +3289,9 @@ "knownGaps": [ "No packaged desktop or physical phone was exercised.", "The deterministic seam does not measure production GFE, carrier NAT, DNS, TLS, or Cloud SQL behavior.", - "Legacy desktop versions remain dependent on server-side overload protection." + "Legacy desktop versions remain dependent on server-side overload protection.", + "D42 RPC owner layout retires this complete dated receipt because its source/command scope changed. It does not validate relocated/reduced selectors. Native complete receipt verbatim:\n{\n \"date\": \"2026-07-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.49,\n \"summary\": \"Three focused relay files passed with 25 assertions.\"\n }", + "D42 RPC owner layout archives complete native active selector/coverage fields because no unchanged passed current receipt remains. These native fields are historical scope, not current execution:\n{\n \"commands\": [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts --reporter=dot\"\n ],\n \"testFiles\": [\n \"src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts\",\n \"src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts\",\n \"src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts\"\n ],\n \"assertionRefs\": [\n {\n \"file\": \"src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts\",\n \"assertions\": [\n \"duplicate drain notifications share one exponentially backed-off retry schedule\",\n \"Retry-After suppresses early assignment requests\",\n \"broker close prevents retry resurrection\",\n \"a later successful assignment activates the new origin\"\n ]\n },\n {\n \"file\": \"src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts\",\n \"assertions\": [\n \"assignment overload preserves a bounded Retry-After hint\"\n ]\n },\n {\n \"file\": \"src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts\",\n \"assertions\": [\n \"initial relay setup does not retry before Retry-After expires\"\n ]\n }\n ],\n \"protection\": \"partial\",\n \"maturity\": \"experimental\",\n \"coveredPlatforms\": [\n \"macos\"\n ],\n \"coveredProviders\": [\n \"cloud-relay\"\n ]\n}" ], "demotionRule": "Keep experimental or demote if assignment calls overlap, duplicate drain events bypass backoff, Retry-After is ignored, close resurrects work, or mixed-version request rate exceeds the reviewed director budget." }, @@ -3561,15 +3505,16 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "orca-server"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": ["linux"], "coveredProviders": ["local", "orca-server"], - "coverageNotes": "Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): A real two-client integration harness pairs two authenticated devices to one OrcaRuntimeService over WebSockets with E2EE and drives worktree.create through the real RPC dispatcher, in both headed-notifier and headless orca-serve shapes. The headless case is a modeled `orca serve` runtime shape — no notifier, no attached window — not a CLI bootstrap, and the in-process reveal non-regression calls createManagedWorktree directly. A headed Electron journey runs the desktop app as the remote server with two independently paired web clients in separate partitions and asserts each client's rendered active worktree. Windows and Linux are covered by the platform-neutral contract only; the reported field topology was a Windows server with mixed-OS clients. Audit1313: src/main/runtime/rpc/methods/worktree-create-navigation.test.ts: Fake runtime creation/show/dedupe under real RPC decoder only inspects forwarded navigation option matrices, with duplicate desktop case. Lose runtime/mobile/legacy CLI/follow/all navigation authority wiring; no rendered reveal. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", + "coverageNotes": "Audit3924 fresh local Linux evidence covers only the unchanged in-process paired-WebSocket integration suite (9 tests passed), not rendered Electron, actual headless CLI bootstrap, live remote/mobile or other platforms. Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): A real two-client integration harness pairs two authenticated devices to one OrcaRuntimeService over WebSockets with E2EE and drives worktree.create through the real RPC dispatcher, in both headed-notifier and headless orca-serve shapes. The headless case is a modeled `orca serve` runtime shape — no notifier, no attached window — not a CLI bootstrap, and the in-process reveal non-regression calls createManagedWorktree directly. A headed Electron journey runs the desktop app as the remote server with two independently paired web clients in separate partitions and asserts each client's rendered active worktree. Windows and Linux are covered by the platform-neutral contract only; the reported field topology was a Windows server with mixed-OS clients. Audit1313: src/main/runtime/rpc/methods/worktree-create-navigation.test.ts: Fake runtime creation/show/dedupe under real RPC decoder only inspects forwarded navigation option matrices, with duplicate desktop case. Lose runtime/mobile/legacy CLI/follow/all navigation authority wiring; no rendered reveal. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/11027"], "invariant": "View intent belongs to the connection that requested it. With no explicit navigation target, a workspace create arriving over a paired desktop/web client connection activates only that caller; it must not emit an activateWorktree client event to sibling connections or drive the host renderer. An explicit navigation of host/clients/all remains an allowed, tested follow intent. Shared model state — repo/worktree catalogs, terminals, agent output — must keep propagating to every client unchanged. In-process and CLI creates keep notifying the host and all clients so a headless server's only viewer still gets its reveal.", - "oracle": "Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): notifyActivateWorktree takes its navigation target as a required parameter, so a create call site that forgets to forward it is a compile error rather than a silent fallback to broadcasting — mutation testing confirmed all six call sites (folder, git, and remote/SSH branches, startup and no-startup each) are killed by typecheck. Behaviorally: two paired clients subscribe to runtime.clientEvents. Client A creates a workspace with activate:true; a reposChanged fence emitted after the create must be the next frame each client sees, proving no activation frame was interleaved, while worktreesChanged still arrives on both streams. The host notifier's activateWorktree is asserted not called and the host's mirrored selection is unchanged. Repeated ordinary worktree.activate calls by A are the negative control. The same file asserts the in-process create still reaches host and clients, headed and headless. The Electron journey asserts the observer's data-rendered-active-worktree-id is unchanged while the created workspace still appears in its sidebar.", + "oracle": "Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): notifyActivateWorktree takes its navigation target as a required parameter, so a create call site that forgets to forward it is a compile error rather than a silent fallback to broadcasting — mutation testing confirmed all six call sites (folder, git, and remote/SSH branches, startup and no-startup each) are killed by typecheck. Behaviorally: two paired clients subscribe to runtime.clientEvents. Client A creates a workspace with activate:true; a reposChanged fence emitted after the create must be the next frame each client sees, proving no activation frame was interleaved, while worktreesChanged still arrives on both streams. The host notifier's activateWorktree is asserted not called and the host's mirrored selection is unchanged. Repeated ordinary worktree.activate calls by A are the negative control. The same file asserts the in-process create still reaches host and clients, headed and headless. The Electron journey asserts the observer's data-rendered-active-worktree-id is unchanged while the created workspace still appears in its sidebar.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts", - "pnpm run test:e2e:multi-client-navigation -- tests/e2e/multi-client-navigation-isolation.spec.ts" + "pnpm run test:e2e:multi-client-navigation -- tests/e2e/multi-client-navigation-isolation.spec.ts", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts --maxWorkers=2" ], "testFiles": [ "src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts", @@ -3589,20 +3534,19 @@ { "file": "tests/e2e/multi-client-navigation-isolation.spec.ts", "assertions": [ - "keeps a paired client workspace create-with-agent off the other client and the host", - "keeps two paired browser clients and the host on independent worktrees" + "keeps a paired client workspace create-with-agent off the other client and the host" ] } ], "evidenceRuns": [ { - "date": "2026-08-18", + "date": "2026-11-12", "runner": "local", - "platform": "macos", - "command": "pnpm run test:e2e:multi-client-navigation -- tests/e2e/multi-client-navigation-isolation.spec.ts", + "platform": "linux", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts --maxWorkers=2", "result": "passed", - "durationSeconds": 80, - "summary": "Headed Orca desktop server with two paired web clients: the observer stayed on its own worktree while the creator's workspace appeared in its sidebar. With the fix disabled the same journey failed with the observer rendering the created workspace." + "durationSeconds": 4.79, + "summary": "9 tests passed in the existing multi-client-navigation-isolation.integration.test.ts suite. In-process real paired WebSocket/runtime contracts only; no rendered Electron, CLI bootstrap, physical PTY/provider, live remote/mobile, macOS or Windows validation." } ], "runtimeBudget": { @@ -3611,11 +3555,11 @@ }, "flakeHistory": { "status": "unknown", - "evidence": "New contracts. The integration file is fence-ordered rather than timing-based and passed repeatedly locally; the Electron journey passed twice locally on macOS. CI and soak history have not started." + "evidence": "Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. New contracts. The integration file is fence-ordered rather than timing-based and passed repeatedly locally; the Electron journey passed twice locally on macOS. CI and soak history have not started." }, "redGreenEvidence": { "status": "complete", - "evidence": "Both layers were observed red on origin/main 4ec6bbf588 before any fix: the observer client received ['worktreesChanged', 'activateWorktree'] instead of the fence, and the Electron observer's data-rendered-active-worktree-id resolved to the workspace the other client had just created. Both went green with the caller scoping and red again when only resolveRuntimeNavigationTarget's clientKind input was removed." + "evidence": "Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. Both layers were observed red on origin/main 4ec6bbf588 before any fix: the observer client received ['worktreesChanged', 'activateWorktree'] instead of the fence, and the Electron observer's data-rendered-active-worktree-id resolved to the workspace the other client had just created. Both went green with the caller scoping and red again when only resolveRuntimeNavigationTarget's clientKind input was removed." }, "performanceBudget": { "required": false, @@ -3627,6 +3571,7 @@ "Extend the oracle to mobile observers and to a client with two windows open on one connection." ], "knownGaps": [ + "Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Retired complete dated receipt verbatim:\n{\n \"date\": \"2026-08-18\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e:multi-client-navigation -- tests/e2e/multi-client-navigation-isolation.spec.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 80,\n \"summary\": \"Headed Orca desktop server with two paired web clients: the observer stayed on its own worktree while the creator's workspace appeared in its sidebar. With the fix disabled the same journey failed with the observer rendering the created workspace.\"\n }", "Audit2141: Remove only the in-memory fake-store restart callback from src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts. Its copied persistence-object alarm is intentionally lost without replacement. All eight actual paired-WebSocket callbacks and five active assertion aliases remain byte-identical. Existing Electron receipt is unchanged and validates only its original source/journey; no fresh validation of the reduced integration selector, disk persistence, live remote/mobile, or cross-platform result is claimed.", "No live Windows or Linux server run yet; the reported field topology was a Windows 11 server.", "Mobile observers are covered only by the platform-neutral clientKind contract, not by a live phone journey.", @@ -3663,17 +3608,17 @@ "providers": ["local", "daemon", "ssh"], "coveredPlatforms": ["linux"], "coveredProviders": [], - "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2271: Linux coverage is limited to the unchanged serve-signal-exit-diagnostic supervisor selector and the late-handoff-after-child-exit assertion recorded below. It does not cover desktop promotion, renderer continuity, persistent PTYs or native updater behavior. No current local, daemon or SSH provider execution is established; coveredProviders is empty. Historical macOS/provider scope remains only in preserved prior accounts and archived receipts. Audit2252 removes the entire handassembled serve promotion/renderer hydration suite. Retired alarms: queued and repeated activation coalescing, duplicate serve suppression, unavailable-provider diagnostic, and zero resume/replacement accounting on independently supplied renderer state. The fixture never joined actual daemon-to-renderer delivery. These exact alarms have no equivalent replacement assigned. Remaining gate selectors keep their existing narrower scope; historical dated receipts remain verbatim and do not validate this changed selector set. No fresh runtime, native/provider, live remote/mobile, cross-platform or performance result is claimed. Archived removed active entries verbatim: commands: \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\ntestFiles: \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\nassertionRefs: {\n \"file\": \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\",\n \"assertions\": [\n \"a forced desktop relaunch reaching the headless lock owner opens exactly one window, and only after the persistent provider settles\",\n \"a duplicate `orca serve` launch never promotes the headless owner\",\n \"the renderer promoted inside the serve process resumes zero agents while daemon panes survive, before and after those panes rebind their PTYs\",\n \"no replacement resume tab, startup command, or automatic-resume claim is created, and every surviving session record is left untouched\"\n ]\n } Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1589 removes mock-only CLI forwarding, canned provisioning/catalog/error projections and private inventories without equivalent replacement coverage. Retained cases exercise actual local markdown/paste/reconciliation, stream framing/backpressure/output-drain, temporary directory cleanup and persisted handoff with injected host/provider/process boundaries. No real Jira, provisioning, remote launch, native pipe/process-tree authority or deployed provider catalog proof. Assertion references use the surviving handoff registration titles; changed-selector historical receipts are retired and unaffected receipts remain unchanged. Historical scope before this audit: Deterministic unit coverage exercises activation gating, single-instance ownership, local/remote CLI status, headless binding persistence, local daemon identity, SSH identity transfer, the promoted renderer's agent-resume accounting, and the macOS serve update handoff from staged installer through atomic bundle replacement and target-version readiness. Supervisor settlement coverage prevents a late handoff-completion failure from rearming termination after the replacement child exits. A macOS Electron journey covers headless promotion and persistent PTY identity. A disposable locally signed Electron canary exercised real ShipIt and a temporary LaunchAgent with the compiled production supervisor; full packaged Orca and Linux/Windows serve updates remain uncollected. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2271: Linux coverage is limited to the unchanged serve-signal-exit-diagnostic supervisor selector and the late-handoff-after-child-exit assertion recorded below. It does not cover desktop promotion, renderer continuity, persistent PTYs or native updater behavior. No current local, daemon or SSH provider execution is established; coveredProviders is empty. Historical macOS/provider scope remains only in preserved prior accounts and archived receipts. Audit2252 removes the entire handassembled serve promotion/renderer hydration suite. Retired alarms: queued and repeated activation coalescing, duplicate serve suppression, unavailable-provider diagnostic, and zero resume/replacement accounting on independently supplied renderer state. The fixture never joined actual daemon-to-renderer delivery. These exact alarms have no equivalent replacement assigned. Remaining gate selectors keep their existing narrower scope; historical dated receipts remain verbatim and do not validate this changed selector set. No fresh runtime, native/provider, live remote/mobile, cross-platform or performance result is claimed. Archived removed active entries verbatim: commands: \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\ntestFiles: \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\nassertionRefs: {\n \"file\": \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\",\n \"assertions\": [\n \"a forced desktop relaunch reaching the headless lock owner opens exactly one window, and only after the persistent provider settles\",\n \"a duplicate `orca serve` launch never promotes the headless owner\",\n \"the renderer promoted inside the serve process resumes zero agents while daemon panes survive, before and after those panes rebind their PTYs\",\n \"no replacement resume tab, startup command, or automatic-resume claim is created, and every surviving session record is left untouched\"\n ]\n } Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1589 removes mock-only CLI forwarding, canned provisioning/catalog/error projections and private inventories without equivalent replacement coverage. Retained cases exercise actual local markdown/paste/reconciliation, stream framing/backpressure/output-drain, temporary directory cleanup and persisted handoff with injected host/provider/process boundaries. No real Jira, provisioning, remote launch, native pipe/process-tree authority or deployed provider catalog proof. Assertion references use the surviving handoff registration titles; changed-selector historical receipts are retired and unaffected receipts remain unchanged. Historical scope before this audit: Deterministic unit coverage exercises activation gating, single-instance ownership, local/remote CLI status, headless binding persistence, local daemon identity, SSH identity transfer, the promoted renderer's agent-resume accounting, and the macOS serve update handoff from staged installer through atomic bundle replacement and target-version readiness. Supervisor settlement coverage prevents a late handoff-completion failure from rearming termination after the replacement child exits. A macOS Electron journey covers headless promotion and persistent PTY identity. A disposable locally signed Electron canary exercised real ShipIt and a temporary LaunchAgent with the compiled production supervisor; full packaged Orca and Linux/Windows serve updates remain uncollected. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8457", "https://github.com/stablyai/orca/issues/9563" ], "invariant": "A safely promotable headless serve process is the single app owner. Desktop activation preserves its daemon-backed sessions. On macOS, a CLI-supervised serve update keeps the node-mode parent alive across ShipIt's atomic bundle swap, restarts with the original serve arguments only after the target bundle is present, and clears handoff state only after that target version reports runtime readiness. Once a supervised child exits or fails to start, no late handoff completion may signal it or arm force-kill escalation. Unsupported or failed handoffs leave the current serving owner intact or recover it once without an install retry loop.", - "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2252: The removed synthetic lock/gate/hydration fixture supplies no current promotion continuity oracle. Existing other selectors retain only their own independent scope; changed selector execution is pending. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Unit tests coalesce early activation, preserve daemon and SSH identity, and reproduce the update race with a staged target, old serving child, persistent CLI parent, atomic .app replacement, and replacement readiness message. They assert the parent does not exit for launchd to respawn the old app, the native updater does not launch an interactive GUI, the replacement version is verified before handoff completion, mismatches become durable failures without retries, and unsupported/preflight-failed installs do not invoke native quit or PTY cleanup. Force handoff completion to fail after the replacement child exits and require zero later child signals and zero escalation timers. A joined lock-owner/activation/hydration contract asserts that a forced relaunch opens exactly one window and that the renderer promoted inside the serve process launches zero agent resumes, creates no replacement tab or startup command, and leaves every surviving session record untouched. The Electron journey independently verifies headless promotion retains owner/runtime/daemon/PTY identity and terminal I/O.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2252: The removed synthetic lock/gate/hydration fixture supplies no current promotion continuity oracle. Existing other selectors retain only their own independent scope; changed selector execution is pending. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Unit tests coalesce early activation, preserve daemon and SSH identity, and reproduce the update race with a staged target, old serving child, persistent CLI parent, atomic .app replacement, and replacement readiness message. They assert the parent does not exit for launchd to respawn the old app, the native updater does not launch an interactive GUI, the replacement version is verified before handoff completion, mismatches become durable failures without retries, and unsupported/preflight-failed installs do not invoke native quit or PTY cleanup. Force handoff completion to fail after the replacement child exits and require zero later child signals and zero escalation timers. A joined lock-owner/activation/hydration contract asserts that a forced relaunch opens exactly one window and that the renderer promoted inside the serve process launches zero agent resumes, creates no replacement tab or startup command, and leaves every surviving session record untouched. The Electron journey independently verifies headless promotion retains owner/runtime/daemon/PTY identity and terminal I/O. Audit4587 retires the one-case CLI WebSocket protocol/preflight suite and its hand-built server; its cross-layer non-delivery witness is intentionally lost, with no replacement coverage claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/serve-signal-exit-diagnostic.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-desktop-activation.test.ts src/cli/runtime-client.test.ts src/cli/runtime/websocket-transport.test.ts src/main/runtime/construction/orca-runtime.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-launch/serve-desktop-activation.test.ts src/cli/runtime/client.test.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm exec electron-vite build --mode e2e", "pnpm run test:e2e -- tests/e2e/headless-serve-desktop-activation.spec.ts --workers=1" ], @@ -3682,9 +3627,8 @@ "src/main/updater/serve-update-handoff.test.ts", "src/cli/runtime/launch.test.ts", "src/cli/runtime/serve-signal-exit-diagnostic.test.ts", - "src/main/startup/serve-desktop-activation.test.ts", - "src/cli/runtime-client.test.ts", - "src/cli/runtime/websocket-transport.test.ts", + "src/main/startup/serve-launch/serve-desktop-activation.test.ts", + "src/cli/runtime/client.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "tests/e2e/headless-serve-desktop-activation.spec.ts" ], @@ -3721,7 +3665,7 @@ ] }, { - "file": "src/main/startup/serve-desktop-activation.test.ts", + "file": "src/main/startup/serve-launch/serve-desktop-activation.test.ts", "assertions": [ "early activation requests coalesce until the persistent provider is ready", "a blocked provider drops pending activation and never opens a window" @@ -3769,6 +3713,10 @@ "Add an Electron SSH promotion journey in addition to the deterministic identity-transfer unit contract." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2271: Retire the deleted serve-desktop-promotion-session-continuity suite receipt from structured evidenceRuns. The exact dated original object is preserved below as historical text, including its prior claims; it supplies no current promotion/renderer continuity or equivalent replacement evidence. The replacement structured receipt covers only the unchanged serve-signal-exit-diagnostic selector and its late-handoff-after-child-exit supervisor assertion. No promoted-renderer, persistent-PTY, native Electron, provider, remote or platform execution equivalence is assigned. Historical retired receipt verbatim:\n{\n \"date\": \"2026-08-05\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 2,\n \"summary\": \"Six tests passed joining the serve lock owner, the activation gate, and the promoted renderer's resume accounting. Red evidence: reverting the hidden-pane ownership predicate launched two duplicate codex resume tabs; additionally zeroing the live-PTY check made both hydration passes red; removing the duplicate-serve argv guard opened a window for `--serve`; always marking the gate ready removed the fail-closed diagnostic; refusing to open a window dropped both promotion assertions.\"\n }", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", @@ -3796,7 +3744,9 @@ "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", - "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts src/main/window/attach-main-window-services.test.ts\"" + "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts src/main/window/attach-main-window-services.test.ts\"", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed.", + "Audit3946 reduces src/main/updater/mac-install/updater.mac-install.test.ts from16 to3 authored cases, deliberately retiring13 narrow desktop-Mac staging/ordinary-quit/rejection/timeout/blocker projections. Lose pre-download staging ordering, normal-quit/native-readiness distinction, initial pre-ready blocker handling, sanitized handoff logging,15s readiness escape, injected sidecar recovery, enumeration-failure handling, ordinary quit after refusal, simpler probe/cleanup/retry guards, and required-cleanup failure escape. Retain only native-ready deferred cleanup ownership, delayed blocker-description refusal→retry, and competing actions during a retry; these mocked Electron/native/process boundaries provide no equivalent replacement for every retired alarm or native ShipIt proof. All3 survivors remain darwin-only and skip on Linux; no fresh macOS/native run or narrowed-selector receipt is claimed. This gate command still names the existing suite. Original dated receipts and other gate evidence retain their exact original scope and do not validate the reduced case set." ], "demotionRule": "Quarantine the Electron journey only with a linked product or harness defect; demote if activation changes the owner/runtime/daemon/PTY identity, loses prior output, opens before provider readiness, or fails to honor a committed quit." }, @@ -3816,16 +3766,16 @@ "providers": ["local", "daemon", "ssh", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "paired-runtime"], - "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/14066", "https://linear.app/stably/issue/STA-4016", "https://github.com/stablyai/orca/pull/14070" ], "invariant": "Every genuine renderer graph reload revision settles exactly once, while a blocked external navigation that preserves the current document never starts a revision. A cancelled renderer-document navigation restores authority only when that same renderer survived; cancellation after an earlier document committed remains fenced until publication or timeout. Replacing a reload cancels only the prior revision; its timer and callbacks cannot settle a newer revision. A desktop reload succeeds only from a publication carrying a new renderer-document generation, while a failed headless promotion may recover only from its originating window. Timeout, renderer loss, and close reach a terminal graph state, and successful desktop publication permanently retires headless sentinel fallback until a new headless runtime is established.", - "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/runtime-renderer-notification-sender.test.ts src/main/window/renderer-document-navigation.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -3833,8 +3783,7 @@ ], "testFiles": [ "src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts", - "src/main/window/runtime-renderer-notification-sender.test.ts", - "src/main/window/renderer-document-navigation.test.ts", + "src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts", "src/main/ipc/runtime.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", @@ -3852,20 +3801,12 @@ ] }, { - "file": "src/main/window/runtime-renderer-notification-sender.test.ts", + "file": "src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts", "assertions": [ - "renderer failure is contained once per load generation", + "disposed-frame failures are contained and send admission remains closed until a valid renderer document returns", "late events cannot revive a closed sender" ] }, - { - "file": "src/main/window/renderer-document-navigation.test.ts", - "assertions": [ - "blocked external navigation does not start a renderer generation", - "only the packaged renderer file or development origin starts a renderer generation", - "concurrent provisional starts share one reload fence and cancel only after every attempt fails" - ] - }, { "file": "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts", "assertions": [ @@ -3943,6 +3884,10 @@ "Add live SSH or WSL promotion evidence if provider-specific graph restoration diverges." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -3968,7 +3913,8 @@ "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/runtime-renderer-notification-sender.test.ts src/main/window/renderer-document-navigation.test.ts src/main/ipc/runtime.test.ts src/main/window/attach-main-window-services.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts\"", - "Exact retired testFiles selector: \"src/main/window/attach-main-window-services.test.ts\"" + "Exact retired testFiles selector: \"src/main/window/attach-main-window-services.test.ts\"", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Demote if a reload revision settles more than once, a stale document or competing window can publish, a timer survives settlement, desktop failure stays indefinitely reloading, headless fallback returns after successful promotion, or either isolated Electron journey loses runtime or PTY identity." }, @@ -4058,10 +4004,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coverageNotes": "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "oracle": "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -4129,6 +4075,48 @@ "Add real sleep/wake and network-loss transport drops alongside the explicit disconnect trigger." ], "knownGaps": [ + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", + "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical.", + "Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical.", + "Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope.", + "Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed.", + "Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes.", + "Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases.", + "Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit.", + "Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved.", + "Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits.", + "Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope.", + "Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit.", + "Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit.", + "Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit.", + "Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical.", + "Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained.", + "Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit.", + "Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit", + "Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures.", + "Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise.", + "Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope.", + "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit.", + "Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation.", + "Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains.", + "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence.", + "Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope.", + "Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope.", + "Audit3630 removed orphan delete/toggle capability/precondition and run/edit refusal assertions. Real dispatch, mutation fencing, mixed-version and host outcomes are not established by this removal or by a substitute test.", + "Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope.", + "Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope.", + "Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope.", + "Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope.", + "Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope.", + "Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed.", + "Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions.", "Launch direct-owner cleanup current scope: This gate’s unfiltered unit command now selects a suite reduced by 82 whole registrations / 159 potential table examples in 10 whole test Programs, including 8 registrations / 15 examples from five once-registered create-message factory closures. Lost alarms include frozen first-message/options and legacy-host fallback; distinct actions and redelivery; uncertain/refused/reloaded input custody, Retry and late proof; rich prompt/attachment upload Stop/close and handback; ordinary draft/editor/IME/StrictMode lifetime and accepted topology; provisional fallback tab placement/group/pin/order and rich worktree handoff. Four whole consent/resume-identity cases remain in two Programs; they do not replace these alarms. This entry governs current reduced-unit scope and qualifies any broader implication of unchanged oracle/coverageNotes history. Entire dated evidenceRuns, original commands/currentCommand values, counts/results and existing history retain their original scopes only; no fresh execution, transferred pass, replacement equivalence or prior upstream-removal credit is claimed.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/persistence/worktree-sort-order-write.test.ts: re-ranks every writable row when a blocked row sits in the requested order. src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts: continues skill management after startup recovery fails. src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts: uses bounded ownership lookup for direct arrivals while the agent cannot take input; wakes a bound Run waiter when same-Run direct mail arrives; keeps an unowned detached-recipient message in its direct mailbox; uses primary-key lookups for bounded routing updates. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts: remove only literal registration import/call pairs import './orchestration-mailbox-pointer-cli-command.spec'; no additional authored credit. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts: renders the %s CLI command in a mailbox pointer. src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts: sizes a slow high-latency link near twice its bandwidth-delay product; never paces a LAN, even when its client parses slowly; never paces a fast link; returns to legacy windows when the path RTT jumps. src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts: steps down the row ladder when history is over the byte budget; tries the larger first row count, then the usual ladder within the same byte budget. src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts: returns unknown when route inspection fails or emits malformed data; does not inspect routes outside Windows. src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts: is refused to a paired %s client; reports a failed widening instead of advertising an unreachable address. src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts: reports exited only when the owning runtime completes the exit waiter; reports unverifiable when the runtime cannot observe the exit waiter; reports unverifiable when a disconnected PTY resolves with unknown liveness. src/main/runtime/session-graph/headless-runtime-graph.spec.ts: lets a session tab inventory settle on a host no renderer publishes for. src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts: remove only literal registration import/call pairs import { registerHeadlessRuntimeGraphTests } from './headless-runtime-graph.spec', registerHeadlessRuntimeGraphTests(); no additional authored credit. src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts: bumps the stored snapshot version only when the title changes. src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts: keeps the healthy aggregate verification and delayed physical exit behavior; uses a stamped exit for the incarnation that was actually being closed. src/main/runtime/terminal/identity/terminal-identity-probe.test.ts: answers live for a structured worker without touching the PTY graph; answers live for a PTY handle the runtime still holds; runs the full leaf check for a handle with no live PTY; answers not-live for a stale handle; propagates \"could not look\" rather than reporting it as a dead handle. src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts: names the tab in main’s layout through terminal.rename; takes a window-style layout.apply close as already stopped, so the terminal runs on. src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts: retains no lifecycle generation after a spawn/exit cycle. src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts: reads a freshly spawned terminal as used once a user opens its tab, not on a probe; keeps the open mark on the process a user open starts. src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts: from a desktop window that mounts both panes; from a server with no window. src/main/runtime/terminal/surface/workspace-layout-projection.test.ts: carries views for a partition that holds none yet. src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts: releases a signalled exit-waiter when the signal aborts. src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts: selects a local hook status for a local pane. src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts: keeps the footer and the bare caret on screen mid-turn; %s: the screen alone reads ready during %s. src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts: uses per-launch arguments and preserves launch telemetry; attributes a startup agent whose caller named no surface as unknown; launches %s bare for an absent or blank prompt; attributes a %s draft launch named %s as %s; merges an automation's extras over the host defaults; threads worktree-create extras into the startup build; returns an enabled requested agent without detecting; returns the default when nothing was requested; detects instead of using the default when the requested agent is disabled; starts no agent when the default is blank; detects an enabled agent on this host when nothing usable was named; starts no agent when detection finds none. src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts: pastes and submits through composer readiness, never typing raw input; types the follow-up on WSL or SSH-to-Windows once the agent is in front, as before; cleans up the deadline when the composer was already captured; a draft that is not submitted is pasted on the box cursor, as before; takes the box after the grace when the row never comes, whatever repaints; takes the box at the deadline when the grace would outlast the budget; lets a dialog on screen veto a grace; refuses the deadline inside a pending grace while a shell is in front; takes the box at the deadline inside a pending grace with the agent in front; takes the box at the deadline after a refused grace once the agent is in front. src/main/skills/skill-install-transaction.test.ts: installs, previews unchanged bytes, and updates a clean receipt-owned skill; preserves the old version after a %s filesystem failure. src/main/speech/model-manager-download-resume.test.ts: requests the remaining bytes when a clean range response ends before the file total; bounds a server that advances by pathologically tiny segments forever. src/main/ssh/config/ssh-config-parser.test.ts: parses a basic host block; parses multiple host blocks; skips wildcard-only Host entries; skips Host entries with only pattern characters; parses IdentityFile with ~ expansion; parses Windows-style IdentityFile with ~ expansion; parses quoted scalar values like OpenSSH; parses equals-form scalar directives; parses IdentityAgent with ~ expansion; parses IdentitiesOnly; parses GSSAPIAuthentication; keeps the first GSSAPIAuthentication value like OpenSSH; parses ProxyCommand, ProxyUseFdpass, and ProxyJump; ignores comments and blank lines; handles case-insensitive keywords; stops current block on Match directive; returns empty array for empty input; creates one parsed host per concrete alias on a multi-pattern Host line; applies identity agent settings to every concrete alias on a multi-pattern Host line; defaults port to 22 for invalid port values; converts hosts to SshTarget objects; uses host alias as hostname when HostName is missing; skips hosts that are already imported; defaults username to empty string when not specified; carries through identityFile, identityAgent, identitiesOnly, proxyCommand, and jumpHost; carries through gssapiAuthentication; imports duplicate aliases only once and keeps the first concrete host; maps hosts for the picker and flags aliases already in Orca; de-dupes aliases and defaults missing fields; parses hostname, user, port from ssh -G output; collects multiple identity files; parses forwardagent yes; defaults port to 22 when missing; returns empty hostname when missing; returns undefined user when missing; handles empty output; skips lines without spaces; parses proxycommand and filters \"none\"; parses proxyusefdpass yes; parses proxyjump and filters \"none\"; handles ~ expansion in identity file paths; handles Windows-style ~ expansion in identity file paths; parses identityagent with ~ expansion; preserves identityagent none so auth can disable agent fallback; parses identitiesonly yes; parses gssapiauthentication; parses controlmaster options and filters controlpath none. src/main/ssh/config/ssh-known-hosts-source.test.ts: splits the space-separated list ssh -G prints on one line; expands ~ in a reported path; keeps a double-quoted path containing spaces whole; falls back to the default files when ssh -G reported nothing; drops an explicit none without falling back to the defaults; splits both known_hosts lists on one line each; reads StrictHostKeyChecking, including accept-new; reads HostKeyAlias and prefers it for the lookup; reads the non-default port; reports that the lookup came from an alias, so the port is not appended; reports no alias when the dialed host is used; unions the entries of every file; skips a path that is a directory; returns nothing when no file can be read; reports nothing unreadable when every file parses; does not count an empty file as unreadable; prefers HostKeyAlias over the resolved hostname; uses the dialed host, because a resolved hostname can just echo the label; still prefers an explicit HostKeyAlias over the dialed host; falls back to the dialed host when nothing was resolved; is rejoined when the split fragments resolve to nothing; leaves a single unresolvable path alone rather than inventing one; expands the __PROGRAMDATA__ token rather than passing it through as a path; does not rewrite a path that merely BEGINS with the token characters; keeps a drive-letter path with mixed separators intact; splits a spaced Windows home into the fragments the rejoin has to put back. src/main/ssh/config/ssh-known-hosts.test.ts: reads the algorithm from the blob rather than trusting the line; rejects %s; refuses a malformed blob: %s; uses the bare host on the default port; tries the bracketed form first and falls back to bare off-port; matches an exact line; matches case-insensitively; reports a changed key of the same type; reports unknown for %s; matches any host in a comma list; matches the bracketed form on its port; does not apply a bracketed entry to the default port; falls back to a bare line when off-port; never reports a change from the fallback pass; matches a bare literal on the default port; matches a bracketed literal on its port; reports a change for a literal; handles %s; still reports a change for a different key on a revoked host; skips a line carrying an unrecognised marker; does not report a change when only another key type is on file; matches within the same type; accepts CRLF terminators; skips blanks, comments and surrounding whitespace; accepts a hit regardless of which file holds it (%s); never brackets the alias, whatever the port; still brackets an ordinary host on a non-default port; matches a bare alias entry on a non-default port; still accepts the unmodified key field; accepts a hashed entry whose salt is a full SHA1 digest; still accepts the unmutated ssh-keygen -H vector; falls back to the bare host line on a non-default port, as ssh did; refuses a key type it has not seen for a host it knows, as ssh did. src/main/ssh/connection/ssh-connect-config.test.ts: returns undefined when no default keys exist; returns the first existing key file; probes regular and FIDO2 keys in stable default order; keeps a regular default ahead of a malformed FIDO2 default; uses target host/port/username; falls back to resolved config when target fields are empty; keeps imported endpoint fields as the fallback when ssh -G is unavailable; sets readyTimeout to CONNECT_TIMEOUT_MS; sets keepaliveInterval to 15s; enables keyboard-interactive auth so MFA challenges can be answered; uses agent auth when no explicit key and SSH_AUTH_SOCK is set; enables agent forwarding when OpenSSH config requests it and an agent is available; does not enable agent forwarding without a usable agent; resolves IdentityAgent SSH_AUTH_SOCK from the environment; uses the Windows OpenSSH agent pipe when no environment socket is available on Windows; wraps agent auth with IdentityFile filtering when IdentitiesOnly is enabled; applies a manual target IdentitiesOnly setting when ssh -G reports it off; includes unencrypted target.identityFile auth when an agent is available; defers encrypted target.identityFile auth when an agent is available; uses keyFile auth when target.identityFile is set and no agent is available; includes unencrypted resolved identityFile auth when an agent is available; defers a default-path resolved identityFile to the no-agent retry; offers the keyboard-interactive challenge when the agent defers no key; provides fallback key when no agent is available; can force private key inclusion for the post-agent fallback path; falls back to resolved proxyCommand; returns structured jump-host config for target.jumpHost; returns structured jump-host config for resolved proxyJump; returns undefined when no proxy is configured. src/main/ssh/connection/ssh-connection-auth-fallback.test.ts: resolves OpenSSH config using configHost when present; tries ssh-agent before reading an explicit private key; falls back to direct private key auth when agent auth fails; falls back to direct private key auth after too many agent authentication failures; answers bounded keyboard-interactive challenges such as Duo 2FA. src/main/ssh/connection/ssh-connection-store.test.ts: lists picker suppression aliases without consulting re-adoption tombstones; getTarget delegates to store; addTarget generates an id and persists; saves the CLI control switch as given, with no consent stamp; addTarget stamps source as manual by default; addTarget preserves an explicitly provided source; inserts a new config host stamped as ssh-config; asks the parser for all hosts — reconciliation happens in the store; updates an existing config-sourced target when the port changed; refreshes gssapiAuthentication on sync; never overwrites a manual target that owns the alias; does not rewrite an unchanged config-sourced target; returns empty array when nothing changed; tombstones a deleted config-sourced host so re-import skips it; suppresses a deleted manual target from config discovery; re-adding a deleted host reclaims its alias so sync stops suppressing it; editing a target reclaims its alias from the deleted set; records a tombstone when removing any user-facing target; re-adopts orphaned repos when the same host is re-added. src/main/ssh/connection/ssh-connection.test.ts: transitions to connected on successful connect; captures the negotiated SSH server key fingerprint; allows concurrent exec commands for ssh2 transport; removes startup listeners after ssh2 connect succeeds; scopes lifecycle events and pending handshake timers to one mock client; enables TCP_NODELAY on the new ssh2 client after a reconnect cycle; transitions through connecting → connected states; reports error state on connection failure; disconnect cleans up and sets state to disconnected; getTarget returns a copy of the target; getState returns a copy of the state; throws when connecting a disposed connection. src/main/ssh/orcad-migration-stuck-host-profiles.test.ts: never leaves a running terminal behind; is offered only when leaving saved state behind would clear the refusal. src/main/ssh/orcad-runtime-maintenance.test.ts: keeps a connect from retrying a build an explicit Update also failed; offers Force when Update was refused by policy; forwards anew after an activation, since the new slot may bind another port; passes a refusal through and leaves the server linked; forwards anew once a serving slot is restored, which may have bound another port. src/main/ssh/port-forwarding/ssh-port-forward.test.ts: reports the port the OS bound when an ssh2 forward asks for port 0; adds an ssh2 port forward and returns entry; adds a system SSH port forward when no ssh2 client is available; reports the port a system SSH forward resolved when asked for port 0; passes resolved OpenSSH config to system SSH port forwards; disposes a system SSH tunnel when removing the forward; lists forwards filtered by connectionId; removes a forward by id; awaits forward close when removing a forward for user actions; returns null when removing nonexistent forward; removes all forwards for a connection; dispose removes all forwards; stores label in the entry; preserves the existing id when updating a forward succeeds. src/main/ssh/ssh-channel-multiplexer.test.ts: sends a JSON-RPC request and resolves on response; assigns unique request IDs; sends notifications without expecting a response; dispatches incoming notifications to handler; sends one keepalive frame per cadence tick; drives keepalive sends AND dead-link detection from a single interval; resolves false immediately on a disposed mux; throws on request after dispose; reports isDisposed correctly; clears registered handlers on dispose; does not retain handlers registered after dispose. src/main/ssh/system-transport/system-ssh-forward-process.test.ts: spawns exactly the argv the orphan matcher is given, LogLevel=INFO included; runs port forwards unmultiplexed even when ssh_config disables muxing; preserves manual target port and identity options in the forwarded ssh command; does not spawn ssh when the requested local forward port is already in use; spawns ssh after the requested local forward port preflight succeeds; resolves startup after the grace period when ssh keeps running; sends SIGTERM then SIGKILL when the process does not exit; does not resolve stop until the process exits. src/main/ssh/system-transport/system-ssh-loopback-route.test.ts: dials the held forward ahead of the alias so OpenSSH keeps these over ssh_config; drops a manual target's own port and proxies, which would fight the route; never routes a forward, whose argv must stay stable for orphan recovery; %s → %s; opens the forward over the real proxy, then proves a login over the route; lands the forward on the sshd and known_hosts name the direct route resolved; holds the forward with server-alive probes; never lets the background forward or probe ask for credentials; starts no forward when admission refuses the route; stops the forward when sshd refuses logins over it; stops the whole forward process tree on Windows, once; reports a forward that already exited before anyone listened for it. src/main/startup/browser-process-user-agent-ordering.test.ts: explains admission refusal before a desktop launch exits; explains an orcad holding the profile instead of exiting silently; does not acquire profile admission for a duplicate launch; executes after the dev app name and before later preflight work; exits and releases admission after pending profile move recovery fails; keeps Linux background startup failures console-only and immediate; keeps Linux serve startup failures console-only and immediate. src/main/startup/quit/quit-path-durable-write-blocking.test.ts: store.flushAsync() issues no synchronous fs syscalls; store.flushAsync() also moves the active-view and github-cache sidecars off the thread; stats.flushAsync() issues no synchronous fs syscalls; Grok session cleanup issues no synchronous fs syscalls; stats.flushAsync() closes out live agents before it returns, not when its write lands; a stalled mount leaves the event loop live instead of parking it; store.flushAsync() is one idempotent final barrier; store.flushAsync() resolves instead of throwing when the profile mount rejects writes. src/main/stats/agent-session-transition-recorder.test.ts: counts a hook-only agent that never writes an agent-shaped terminal title; never opens a session from a replayed or disk-restored working status; still closes a live session when the terminating status arrives as a replay; counts one session per turn across repeated working/done cycles; closes an open session when its pane is torn down; bounds the mirror and closes what it evicts; stops the session when the main agent settles and only a watch loop holds the row working; keeps the session open while a subagent outlives the main agent, and closes it when the child settles; dates the stop by the evidence when a shell outlives the last subagent; opens a new session dated by the observation when the main agent resumes after monitoring; never dates a reopen before the close a fact-less OSC repaint caused; dates the first live row after a restored one by the evidence, not the restored clock; treats an unchanged answer as a snapshot, never a transition; opens only on a live working edge; closes only a session it opened. src/main/text-generation/commit-message-text-generation-model-discovery.test.ts: returns static catalog models without spawning for static agents; discovers dynamic models through the agent CLI; discovers dynamic models through the configured agent command override; falls back to static models when dynamic discovery returns no parseable models; falls back to the first discovered non-Pi model when its static default is unavailable. src/main/text-generation/pull-request-context.test.ts: does not fetch unrelated fork remotes before generating PR context; bounds exact remote-ref probe concurrency for a large remote list; reports no branch change because PR context preparation is read-only; keeps a remote-qualified base when the selected base includes the remote. src/main/text-generation/source-control-local-process.test.ts: asks the supervisor to stop and leaves its group to it; signals nothing once the supervisor has exited; stops an agent that ignores its stdin end through its supervisor. src/main/updater/linux-package/linux-package-update-recovery.test.ts: retains the downloaded package with the digest from the event metadata; requires a string downloaded path; accepts an uppercase extension; requires a non-empty string version; matches an absolute file URL by basename; accepts duplicate entries that agree on the digest; refuses an entry with a missing or non-string digest; refuses a digest that is not base64 at all; refuses a malformed percent-encoded URL; refuses a missing or non-array file list; tolerates a non-object event; replaces the retained artifact with a newer download; keeps the retained artifact when a new download has no usable digest; keeps the retained artifact when an unrelated download event arrives; clears the retained artifact; preserves the artifact across a recheck of the same version; clears the artifact when another version takes over; preserves the artifact for an unknown or empty version; is a no-op without a retained artifact; returns the built command and package file name for a verified package; reports missing without a retained artifact; propagates a package-manager discovery failure; rejects a well-formed digest that belongs to another file; never hashes a package that a malformed digest failed to arm; rejects a path outside the cache root; rejects the cache root itself; rejects a package in the updater directory itself; rejects a pending directory that is a symlink out of the cache; performs one hash pass for concurrent requests; revalidates once the in-flight pass settles; does not reuse an in-flight pass for a different artifact; starts a fresh proof when the same package is captured again; returns the verified package path; returns missing without a retained artifact. src/main/updater/releases/updater-prerelease-feed-readiness.test.ts: accepts a GitHub %s asset redirect as ready; reports a GitHub asset request error as unavailable; reports not-ready with a verified last-good tag when the newest assets are unavailable; does not classify a non-positive tag limit as feed unavailability; reproduces the v1.4.142 publishing incident as not-ready; reports transport failures as unavailable instead of not-ready; treats an explicit asset 404 as not-ready when another asset is unavailable; accepts absolute manifest asset URLs without rewriting them to release asset paths; returns not-ready with an older ready update as last-good while newest is publishing. src/main/updater/releases/updater-release-builds.test.ts: lists hourly builds from the dedicated repo, newest first; lists daily builds from the dedicated repo, newest first; separates stable from rc in the shared main repo; skips drafts and unparseable tags; keeps a composed release title and drops one that repeats the tag; hides builds that published no artifact for this platform; returns an empty list when no build has this platform artifact; keeps mac builds visible on macOS regardless of the Windows leg; resolves the platform installer download url; leaves the installer url null when the release published no installer; tolerates a release whose assets are missing or malformed; sends the local gh token as a bearer header when one is available; sends no authorization header when gh has no token; retries unauthenticated once when GitHub rejects the token; does not retry a 401 that was already unauthenticated; falls back to the per-IP bucket when the token is rate limited and tells the gh breaker; reports a secondary limit carrying retry-after without retrying or tripping the breaker; records a primary limit in the token scope %s; keeps %s authenticated when only %s is blocked; skips the token while its scope %s is blocked; surfaces a rate limit with its reset time and a sign-in hint when unauthenticated; omits the sign-in hint when the rate-limited request was authenticated; treats 429 as a rate limit; reports a 403 without rate-limit headers as a plain HTTP error; reports a missing hourly repo distinctly; is null when GitHub sent no reset; prefers retry-after over the primary reset epoch; falls back to the primary reset epoch when there is no retry-after; reads retry-after as seconds; reads retry-after as an HTTP date; pins an hourly tag at the hourly repo download path; pins a daily tag at the daily repo download path; pins a stable tag at the main repo download path; rejects a tag that is not a version. src/main/updater/updater.build-channel-selection.test.ts: uses the display label in the unsupported-platform %s pinned-build error; still pins %s from an unsigned Windows dev build; restores ordinary release checks after local build selection fails; opts into the RC channel when checkForUpdatesFromMenu is called with includePrerelease; pins the generic feed to a perf-tagged prerelease when requested; surfaces no-update feedback when no newer perf-tagged prerelease exists; keeps prerelease publishing-window misses on the generic retry path; leaves the feed URL alone for a normal user-initiated check. src/main/updater/updater.check-preflight.test.ts: ignores a stale update-not-available event after a new check starts preflight; deduplicates repeated manual checks while the immediate checking status is active. src/main/updater/updater.prerelease-fallback.test.ts: retries a prerelease check once against the previous feed tag when the manifest is missing; surfaces a promise-only prerelease fallback failure after the primary error event. src/main/updater/updater.publishing-window-feed.test.ts: repins the generic feed to the newest RC tag for a prerelease user; repins the generic feed to a newer stable tag for a prerelease user; pins a stable fallback when Atom has no newer prerelease; uses last-good concrete feed when a user-initiated check lands during publishing; can offer an older fully published update while the newest release is publishing; keeps background publishing-window fallback on the short retry cadence. src/main/updater/updater.quit-and-install.test.ts: surfaces an accepted retry before electron-updater emits download progress; defers quitAndInstall and runs its launcher within the launch PATH scope; runs pre-quit cleanup before local PTY cleanup during update install; keeps optional pre-quit cleanup fail-and-continue behavior by default; ignores duplicate quitAndInstall requests while the shared delay is pending; arms the forced-exit watchdog once the install commits; disarms the forced-exit watchdog when sync install error recovery keeps the app open. src/main/window/createMainWindow-markdown-editor-focus.test.ts: ignores traffic light sync IPC on non-macOS; still intercepts Cmd+Shift+B and Cmd+Alt+B when the markdown editor is focused; coerces non-boolean setMarkdownEditorFocused payloads to false; opens a table-aware context menu synchronously without a renderer query; builds the plain edit menu for the one right-click the renderer marks as plain text. src/main/window/createMainWindow-renderer-crash-recovery.test.ts: notifies the caller when the renderer process is gone; passes the renderer webContents id through crash recording and recovery callbacks; forwards expected renderer teardowns so the recorder can diagnose suppression; reloads the app shell after an unexpected renderer process loss; does not reload after renderer loss when recovery is disabled; stops auto-reloading after a rapid renderer crash loop trips the breaker. src/main/window/dashboard-popout-window.test.ts: updates the title after language initialization and unsubscribes when closed; lets its preload expose saved WSL hosts in serve-only, and passes nothing otherwise; creates a native-frame window with the shared preload and no webview surface; shows the window on ready-to-show; loads the prod file entry; loads the dev server URL when in dev; focuses the existing window instead of creating a second one; trusts only the live popout webContents; restores a minimized window when re-requested; restores valid persisted bounds; discards off-screen persisted bounds and falls back to defaults; persists bounds on resize after the debounce, guarding near-minimum sizes; keeps saving bounds after a vetoed quit and freezes them only on an allowed quit; closeDashboardPopout closes an open window; applies the persisted app zoom level on dom-ready; follows app zoom changes while open and unsubscribes on close; zoomDashboardPopoutIfFocused steps the popout zoom only while focused; handles the zoom-in chord via before-input-event and ignores other keys; handles mouse-wheel zoom requests outside before-input-event; respects zoom keybinding overrides for keyboard and mouse-wheel paths. src/main/window/dropped-path-preparation.test.ts: opens and stores each unique source once as drop size grows tenfold; passes ordinary paths without copying for %s; preserves ordinary successes and copied successes when another file fails; serializes copy requests from different owners; reports all lost paths without a shared reason when their failures differ. src/main/window/main-window-updater-deferred-setup.test.ts: releases all 64 completed fallback handles without repeating initialization; keeps setup after ready-to-show and releases its fallback afterward; preserves the 15-second fallback when first paint never arrives; preserves destroyed-window guard reads before and at the fallback deadline; keeps the exact %s error and releases its completed fallback; keeps the exact fallback %s error without retrying initialization; preserves pending manual setup after failed ready registration; keeps setup options, live store reads, nudge writes and required quit flush. src/main/worker-threads/worker-thread-request-queue.test.ts: posts one request at a time and in the order it was dispatched; fires a posted call at its own deadline; stops respawning and fails the rest of the queue once deaths hit the cap; clears the death count when a fresh burst starts from full idle. src/main/workspace-hooks/hooks-setup-runner-script.test.ts: builds Windows runners for newline-heavy scripts without line-array splitting; builds POSIX runners without regex-wide CRLF normalization; writes POSIX setup runners for shebang-declared scripts on native Windows paths; keeps batch setup scripts on cmd.exe when the terminal is Git Bash; hands a Git Bash pane a launch command MSYS cannot rewrite for a cmd runner; replays interpreter flags declared on the shebang line; preserves cmd.exe setup runner semantics for configured cmd users; keeps POSIX runner behavior on POSIX platforms; waits when either local or project policy requires completed setup; marks setup-runner terminals for the always-on credential guard; maps git-bash to POSIX setup launch metadata on Windows; falls back to the cmd runner when the git-bash setting has no installed Git Bash; keeps the cmd runner for a non-Git bash such as Cygwin; keeps the cmd runner for a bare bash whose flavor cannot be resolved; uses the POSIX runner for a bare bash that resolves to Git Bash; uses the POSIX runner for an extension-less Git Bash path; preserves the existing cmd runner for PowerShell terminals; preserves cmd setup compatibility when a Windows-host project has a WSL shell setting; classifies an installed explicit Git Bash executable as a POSIX runner; falls back to the cmd runner when the explicit Git Bash path no longer exists. src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts: schedules remote identity enrichment without blocking the caller; probes a drive project whose runtime is WSL %s; sweeps a local repo: %s; probes an SSH row that carries only executionHostId on its own host; keeps same-path rows on two different SSH hosts from sharing one backoff; coalesces concurrent probes for the same repo location; caches no-identity probes briefly so list calls do not retry every time; does not rewrite the no-remote marker on a later retry; resolves a settled no-remote repo once it gains a remote; does not re-probe a resolved identity before the refresh window elapses; re-probes a resolved identity after the refresh window elapses; bounds re-probes per sweep so a large repo list drains gradually; forgets a removed repo location so its deadline cannot outlive the repo; keeps a surviving repo backoff when a sibling repo is removed; probes again when the same location is re-added after its probe was retired; coalesces concurrent sweeps instead of running one pass per list call. src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts: preserves create priority through claim probes on %s; starts the checkout only once the async workspace root resolves; still deduplicates when both callers await the same pending root lookup; namespaces native Windows preparation directories for long paths; deduplicates preparation for the same repo, base, runtime, and workspace root; does not spend a divergence walk when the base matches exactly; claims when the two sides spell the same ref differently; evicts a repo's own stale preparation before another repo's; still discards armed checkouts when the project runtime needs repair; routes preparation and finalization through the selected WSL runtime; retries stale cleanup after a transient listing failure; does not discard a detached worktree with caller-controlled preparation metadata; does not re-arm after an isolated create; re-arms a preparation once creates arrive in a burst; holds the re-arm checkout until the create runs the deferred thunk; starts one explicit prefetch after the create completes; does not re-arm when finalization failed; reports a pending create while a stale-cleanup scan is running. src/main/workspaces/removal/local-worktree-removal-recovery.test.ts: recovers Git for Windows partial filesystem deletion failures; finishes a clean non-force deletion after Git leaves a Windows directory behind; recovers localized Windows failures after Git already removed the registration; does not recover unrelated localized failures while Git still owns the row; finishes a macOS deletion Git deregistered before failing with Directory not empty; leaves an orphaned checkout to the orphan cleanup instead of deleting it; prunes and strictly verifies on the selected WSL host without deleting files or branches. src/main/workspaces/removal/worktree-removal-safety.test.ts: rejects deleting a worktree that contains another registered worktree; rejects POSIX home directories even when host homedir has a different path shape; refuses a home the host reported even when no path rule recognises it; refuses the Windows host's home directory from a POSIX client; refuses the Windows host's home directory even when the host reported nothing. src/main/wsl/discovery/distro-catalog.test.ts: retries asynchronous discovery after a transient wsl.exe failure; retries synchronous discovery after a transient wsl.exe failure; retries asynchronous discovery after wsl.exe reports no distros yet; retries synchronous discovery after wsl.exe reports no distros yet; bounds the wsl.exe spawn rate while no distros are installed; bounds the asynchronous spawn rate while no distros are installed; still caches a non-empty distro list for the process lifetime; re-probes a docker-desktop-only machine once a user distro can appear; backs off while the list keeps coming back empty; backs off after repeated distro-list failures; caps the empty-list backoff at five minutes; keeps reporting an empty result after it goes stale; keeps reporting a known distro list indefinitely; bounds cached homes while retaining the most recently used distros; still lists distros, and an excluded distro home probe fails like any other probe; gives the async home probe time for a cold boot instead of killing it at 5 s; retries availability after a probe timeout instead of latching false; bounds the probe rate while the failure window is open; caches a successful probe for the process lifetime; names an explicit spawn directory, so no deleted cwd can read as ENOENT; shares one wsl.exe spawn between concurrent probes; keeps reporting the last observed answer after it goes stale; holds a definitive failure far longer than a timeout when %s; backs off after repeated probe failures; re-probes a seeded retryable failure once its window lapses; re-probes availability once a distro list succeeds after %s; does not drop an availability failure for an empty distro list; keeps reporting unavailable off Windows without probing. src/main/wsl/discovery/wsl-distro-holder.test.ts: runs a busybox-safe loop through --exec and names the distro; spawns a detached-style holder, records it, and waits for the distro to run; a holder exiting with code 1 notes its distro may have stopped (E9); rejects a pid whose command line is not our holder for that distro; cleans up stale and corrupt records; keeps a holder and its record when release cannot verify it; reports unverifiable when the command line is unreadable even with a matching pid; release kills a verified holder and removes its record; release never kills a pid that is no longer our holder; reports a spawned holder exit so liveness can re-check. src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts: skips 9p shares that are not drvfs, and malformed lines. src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts: plans the update on the census the running orcad reports, not an unknown one; forwards force to the update planner; does not serve the incumbent past a refusal that is not a wait; does not re-activate the build this host rolled back from; labels the launch with the build the adoption found serving, not the stale record; defers while another run holds the host fence; lets an explicit force deploy past both skips; names a newer host refusal apart from a rolled-back one, so only Force is offered; updates an older host as before, without asking to adopt it; never asks the incumbent when it already runs this build. src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts: keeps a completed listing usable when the host rejects the wait parameter. src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts: delivers to chat-default users in all targeting while holding out not-switched users. src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts: completes the row on a pick, even when the command is already typed; ignores a pick of the row while side chats are unavailable. src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts: explains a too-large refusal that arrives through the IPC error prefix. src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts: keeps the question with the caller and says once that it never went; tells the user to check the side chat when delivery is unconfirmed; reports a delivered question as sent, silently. src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts: decides each of %i tool-only turns once per layout, and nothing without a listener. src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx: places a side chat whose question was %s: %o. src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts: calls back once for %s; stops watching once unsubscribed. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts: routes terminal input through deferPtyInput so the host can withhold it; forwards terminal input directly when the host supplies no deferPtyInput. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts: requests a tab remount for an unbound spawn; leaves recovery to a remote transport that armed its own retry; requests a remount when the transport reports no recovery of its own; settles the spawn as failed before requesting a remount; prefers the restored leaf id when reporting the anomaly; falls back to the pane leaf id when no restored leaf exists. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionDeferredInputForwardingTests } from '../input/pty-connection-deferred-input-forwarding.spec', registerPtyConnectionDeferredInputForwardingTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts: registers interest on the first sidecar and releases on the last unsubscribe; releases sidecar interest only once for repeated unsubscribes; does not let an eager pre-mount buffer defeat hidden delivery gating; keeps eager buffers outside delivery interest when the PTY exits before mount; lets a sidecar exclusively own interest while an eager buffer overlaps. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts: blackholed delivery reproduces the wedge: no handler dispatch, no ACK ever. src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts: sends preferences to the execution host and attaches only to its returned PTY; preserves one operation ID across a lost reply and reconnect; preserves ordinary raw startup and captured-session attachment. src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts: sums registered gauges and drops disposed ones; ignores a repeated dispose instead of dropping another gauge; stops tracking new gauges past the cap so a missed dispose cannot grow it; tracks a live output processor queue through enqueue, drain, and dispose; excludes cleared consumed entries from retention after a bounded drain. src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts: says nothing once the pane is closed. src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts: refreshes after each scheduled atlas reset; falls back to a timeout when animation frames are unavailable; continues recovery when a manager throws after scheduling. src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts: tracks a remounted quiet title source even when the stale owner unregisters later; preserves the renderer-parsed output sequence in the response; preserves a pending escape tail for snapshot replay; routes a host's Reset Terminal request to the pane that owns the PTY. src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts: marks panes with restored scrollback for fresh-shell viewport blanking. src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts: recovers a 0x0 spawn whose container is briefly unmeasurable then settles. src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts: removes global listeners when the last pane unregisters. src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx: keeps trust text readable on a host-owned dialog surface; applies the hostile surface to ordinary dialogs, so the case above is exercised. src/renderer/src/components/use-terminal-parking-pass.test.tsx: does not queue a render when a pass produces the same parking sets; keeps parking transitions working under StrictMode. src/renderer/src/hooks/client-workspace-view-report.test.ts: reports an away user’s screen with no presence, and renews as soon as input returns; retries a failed send, empty or not, no sooner than a refresh. src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts: is new work in a workspace with no live terminal: its first bind moves it up in Recent. src/renderer/src/hooks/use-bundled-skill-install.test.tsx: ignores a repeated click while the install runs; retries the last requested skills on this host. src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx: adds seeds to a successful empty list but not to loading or failed results; retains seed projection after expiry and fetches fresh metadata for a new reader. src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx: retranslates the settings nav labels when the UI language changes live. src/renderer/src/lib/codex-stale-pane-account-identity.test.ts: keeps the prompt when the roster read fails and every label collapses. src/renderer/src/lib/image-blob-png.test.ts: downscales a pasted image above the pixel cap; releases its temporary URL on a decode error; releases its temporary URL when PNG encoding fails or exceeds the byte cap. src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts: names callers above the frame the write came from; restores Error.stackTraceLimit when the capture throws; stops collecting after the sample cap when captureStackTrace is unavailable; caps reported changed keys from a single wide write. src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts: applies the rendered text hard cap last and reserves the final overflow marker. src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts: keeps the runtime target identity stable across unrelated store writes. src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts: keeps creation available on old hosts and explains the missing operation; preserves landed warnings and direct collision recovery data; propagates remote discovery failure instead of a false empty page. src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts: reuses unchanged worktree tab projections when one worktree title changes; bumps only the changed worktree version when a sibling stays byte-identical. src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts: shares safe-auto fork sync cooldown attempts across store instances. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts: collapses a 193-workspace hydration to one store write; leaves the store byte-identical to the per-workspace path; re-reconciling the batched result is a no-op, as it is for the per-workspace path. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts: dedicated zero-case helper retirement; no authored test credit. src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts: persists each batch metadata update to its workspace owner. src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts: dismisses a rename error on its capable remote owner; clears pending first-agent rename when the title is updated. src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts: orders capture, guards, handlers, main's stop, commit, cleanup, and exit settlement. src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts: publishes the first terminal and root tab group atomically; publishes the first terminal and root tab group atomically, then marks it starting in main. src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts: restores daemon terminal wake hints before declaring the session ready. src/renderer/src/web/web-runtime-connection-auth-framing.test.ts: keeps legacy framing for sockets that cannot absorb a refused attempt. src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts: moves the old Windows default to Regular once and queues the notice; keeps custom weights and fresh profiles without a notice; leaves macOS and Linux profiles untouched. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/persistence/worktree-sort-order-write.test.ts, src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts, src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts, src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts, src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts, src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts, src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts, src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts, src/main/runtime/session-graph/headless-runtime-graph.spec.ts, src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts, src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts, src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts, src/main/runtime/terminal/identity/terminal-identity-probe.test.ts, src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts, src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts, src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts, src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts, src/main/runtime/terminal/surface/workspace-layout-projection.test.ts, src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts, src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts, src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts, src/main/skills/skill-install-transaction.test.ts, src/main/speech/model-manager-download-resume.test.ts, src/main/ssh/config/ssh-config-parser.test.ts, src/main/ssh/config/ssh-known-hosts-source.test.ts, src/main/ssh/config/ssh-known-hosts.test.ts, src/main/ssh/connection/ssh-connect-config.test.ts, src/main/ssh/connection/ssh-connection-auth-fallback.test.ts, src/main/ssh/connection/ssh-connection-store.test.ts, src/main/ssh/connection/ssh-connection.test.ts, src/main/ssh/orcad-migration-stuck-host-profiles.test.ts, src/main/ssh/orcad-runtime-maintenance.test.ts, src/main/ssh/port-forwarding/ssh-port-forward.test.ts, src/main/ssh/ssh-channel-multiplexer.test.ts, src/main/ssh/system-transport/system-ssh-forward-process.test.ts, src/main/ssh/system-transport/system-ssh-loopback-route.test.ts, src/main/startup/browser-process-user-agent-ordering.test.ts, src/main/startup/quit/quit-path-durable-write-blocking.test.ts, src/main/stats/agent-session-transition-recorder.test.ts, src/main/text-generation/commit-message-text-generation-model-discovery.test.ts, src/main/text-generation/pull-request-context.test.ts, src/main/text-generation/source-control-local-process.test.ts, src/main/updater/linux-package/linux-package-update-recovery.test.ts, src/main/updater/releases/updater-prerelease-feed-readiness.test.ts, src/main/updater/releases/updater-release-builds.test.ts, src/main/updater/updater.build-channel-selection.test.ts, src/main/updater/updater.check-preflight.test.ts, src/main/updater/updater.prerelease-fallback.test.ts, src/main/updater/updater.publishing-window-feed.test.ts, src/main/updater/updater.quit-and-install.test.ts, src/main/window/createMainWindow-markdown-editor-focus.test.ts, src/main/window/createMainWindow-renderer-crash-recovery.test.ts, src/main/window/dashboard-popout-window.test.ts, src/main/window/dropped-path-preparation.test.ts, src/main/window/main-window-updater-deferred-setup.test.ts, src/main/worker-threads/worker-thread-request-queue.test.ts, src/main/workspace-hooks/hooks-setup-runner-script.test.ts, src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts, src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts, src/main/workspaces/removal/local-worktree-removal-recovery.test.ts, src/main/workspaces/removal/worktree-removal-safety.test.ts, src/main/wsl/discovery/distro-catalog.test.ts, src/main/wsl/discovery/wsl-distro-holder.test.ts, src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts, src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts, src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts, src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts, src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts, src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts, src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx, src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts, src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts, src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts, src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts, src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts, src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts, src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts, src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts, src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx, src/renderer/src/components/use-terminal-parking-pass.test.tsx, src/renderer/src/hooks/client-workspace-view-report.test.ts, src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts, src/renderer/src/hooks/use-bundled-skill-install.test.tsx, src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx, src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx, src/renderer/src/lib/codex-stale-pane-account-identity.test.ts, src/renderer/src/lib/image-blob-png.test.ts, src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts, src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts, src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts, src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts, src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts, src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts, src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts, src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts, src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts, src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts, src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts, src/renderer/src/web/web-runtime-connection-auth-framing.test.ts, src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing-races.spec.ts: stops paged routing when the check is cancelled; keeps an unfiltered redrive unrestricted when reservations merge; keeps an unfiltered parked delivery unrestricted when reservations merge; uses a bounded indexed pane lookup for reminted Dispatch identity. src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts: removes the reported wedged automation workspace without --force; clears PTY state once a failed stop is proven to have exited; names only the PTYs that are actually live, not every failed stop; warns with the specific sweep failure, not the generic deadline; still fails closed on a sweep-level failure without force. src/main/skills/bundled-skill-install/layouts.test.ts: links into a project only where its agent folder already exists; reads a pending cloud transaction as busy and a cloud receipt as another skill. src/main/skills/skill-upload-session-service.test.ts: joins concurrent disposal callers through exact cleanup completion. src/main/source-control/hosted-review-creation.test.ts: creates the pull request after fresh main-process validation passes; routes local WSL git and GitHub review creation through the selected runtime; creates a pull request on a GitHub Enterprise Server remote (#8312); creates a GitLab merge request after fresh main-process validation passes; creates an Azure DevOps pull request after fresh main-process validation passes; creates a Gitea pull request after fresh main-process validation passes. src/main/source-control/hosted-review-execution-host-routing.test.ts: reads a GitHub review on the SSH host a row names only in executionHostId; reads a GitLab review on the executionHostId host when connectionId names a different one; does not dial this client for a runtime row whose nested target shares a local name; keeps a runtime row with no nested target on this process (self-addressed stamp); keeps a legacy connectionId-only SSH row on its target; does not share a cached answer between two rows at one path on different hosts; creates a Bitbucket review locally for a runtime row rather than dialing its nested target; reports creation eligibility from the executionHostId-only SSH host; resolves the GitHub slug for a repo listing on the row it is asked about; refuses to dial a runtime host from this process; answers with the SSH target for both spellings and local otherwise; reads a runtime stamp on a row in this store as self-addressing, not a second machine. src/main/source-control/hosted-review-inflight-invalidation.test.ts: keeps other hosts, paths and their pending promises isolated. src/main/speech/model-manager.test.ts: requires pinned, internally consistent metadata for every model file; verifies downloaded model file hashes before installation; rejects non-HTTPS model downloads; marks OpenAI transcription models ready only when an API key is configured. src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts: writes to the SFTP namespace path discovered on the same session; uploads the bundle into the SFTP namespace directory; issues no discovery requests when the caller supplies no mapping; ignores a mapping on a Windows host; never resolves on the system-SSH transport; leaves writeBuffer and openFileUploadSession on the shell path; keeps the shell path when discovery is inconclusive; preserves a session-limit channel-open error unchanged. src/main/ssh/connection/ssh-connection-system-transport.test.ts: uses system SSH transport when ProxyUseFdpass is resolved by OpenSSH; allows concurrent exec commands for system SSH with an Orca ControlMaster socket; keeps concurrent exec commands disabled for system SSH without a reusable socket; uses system SSH transport for ProxyCommand targets before ssh2 auth; keeps the original ssh2 reachability error when the system SSH probe fails; reports the system SSH failure when ssh2 cannot negotiate with the host; uses system transport for target or resolved OpenSSH proxy directives; allows an environment override for e2e coverage; ignores stale imported proxy fields when fresh OpenSSH config has no proxy. src/main/ssh/orcad-migration-catalog-client.test.ts: keeps each server project’s execution host, so a nested SSH row is never read as local; reads the server’s folder workspaces and the groups that place them on a host; sends and validates the %s operation; validates an abort result without letting it erase committed state; validates a committed receipt against the requested manifest; rejects malformed stage timestamps and abort envelopes; fails closed for method absence, malformed identity, and invalid pairing; refuses a destination without the capability before sending any migration request; reads method-not-found as the same refusal, not as a lost answer. src/main/ssh/runtime-ssh-access.test.ts: persists intent then claim before connecting and publishes redacted authenticated access; names the saved dependency when dependent state blocks an SSH access link; handles lost link responses without connecting or verifying again; invalidates old transport only after authenticated access is published; rejects changed request tuple after a completed link; rejects provisioning and missing durable generations without connecting; treats a lost successful unlink response as an idempotent no-op; hashes connection identity, not display state or owner; strictly validates ports and request IDs. src/main/startup/cli-launch-redirect.test.ts: detects a launch that received the unpacked CLI entrypoint; ignores normal desktop launches; ignores the entrypoint when it is only the executable itself (argv[0]); applies on Linux too; strips injected Chromium switches before node-mode CLI arguments; keeps user flags after the command and malformed boolean assignments; does not treat a later positional entrypoint path as the launcher; redirects a direct binary launch with no AppImage env at all; strips Chromium switches node mode would reject; preserves desktop-shaped switches after the command; leaves direct serve in-process but redirects its help; treats help as a CLI launch even without a command; treats %s as a CLI launch even without a command; does not treat a value of %s as a CLI early-exit flag; does not treat a serve option value as a help request; does not reinterpret help after the argument terminator; leaves a plain desktop launch alone; skips flag values when looking for the command positional; preserves a project selector in %j; does not apply the command form on macOS or Windows; never redirects an unpackaged build; runs the in-package CLI in Electron node mode with sanitized env; refuses to redirect twice so a dropped ELECTRON_RUN_AS_NODE cannot loop; reports a missing CLI entrypoint instead of booting the desktop app; execs a direct serve into the CLI so it keeps its pid and honours profile and supervise; keeps ORCA_USER_DATA_PATH for a direct serve without --user-data-dir; serves in-process when this runtime cannot exec or the exec fails; never execs the --serve child the CLI itself spawns, or serve on other platforms; surfaces a spawn failure as a non-zero exit; re-execs a direct --serve onto X11 when Electron resolved Wayland; leaves $name alone. src/main/startup/main-process-runtime-launch-activation.test.ts: marks startup settled for the launch record only after the window has loaded and settled; loads SSH targets on a windowless serve before paired clients can connect (#25886); pins the serve listener to loopback only for orcad browser sidecars (sidecar=$sidecar, #31895); saves Codex auth before a headless serve update restart, like the desktop does. src/main/startup/run-electron-vite-dev.test.ts: forwards dev instance identity to electron-vite; prepares userData orca and orca-dev wrappers for dev terminals; consumes the stable-name flag before forwarding args to electron-vite. src/main/updater/releases/updater-prerelease-feed.test.ts: returns the newest stable tag when the user is on an RC and a newer stable exists; returns the newest RC tag when no stable is newer than the current RC; can exclude prerelease tags for stable-channel checks; probes the %s %s platform manifest; returns null for stable-channel checks when only prereleases are newer; returns null when nothing in the feed is newer than the current version; ignores entries with unparseable tags; returns null when the fetch is not ok; returns null when the fetch throws; picks semver-newest across a mixed-order feed; ignores perf-tagged prereleases for regular RC checks; reports no RC update when only perf-tagged prereleases are newer; picks the semver-newest perf-tagged prerelease; matches only literal rc.N.perf prerelease tags for perf checks; reports no perf update instead of falling back to stable or RC tags; returns a bounded fallback candidate after the newest newer tag; returns null when the only newer tag has a manifest but its asset still 404s; requires a known old timestamp for a stable-fallback tag. src/main/updater/updater-events.test.ts: hands the whole downloaded event to artifact capture; publishes manual-install recovery after a %s download; publishes the normal downloaded state for AppImage builds; blocks downloaded-state handling when the packaged marker is unusable; passes the actual updater error into the install-failure handler; keeps manual-install recovery when a later check finds only the installed release; drops the artifact when another version takes over the cycle; ignores a downloaded event for an older target; accepts a matching event when the pending cache target was cleared; drops the artifact when progress reports a different pending version. src/main/updater/updater-linux-package-recovery-actions.test.ts: rejects both actions while no package-install recovery is active; validates the retained package on every invocation; restores recovery after a recheck resolves without a terminal event; restores recovery after a recheck fails; restores recovery when a pinned check resolves to the current version; restores recovery when resolving a pinned check fails; clears recovery for both actions once the package is gone; resolves %s as a result and keeps the card usable instead of rejecting; keeps recovery available after a transient read failure. src/main/updater/updater.check-settlement.test.ts: leaves a dismissed release update on the release source; surfaces net::ERR_FAILED to user-initiated checks with a friendly message; shows checking immediately for a user-initiated check while feed pinning is pending; keeps background checks event-driven before checking-for-update fires. src/main/usage/usage-provider-store-lifecycle.test.ts: persists identities for a whole first scan with one write; skips disabled and fresh matching states; invalidates prior sources on fingerprint changes and reuses them for forced scans. src/main/window/createMainWindow-close-confirmation.test.ts: clears the quit latch when the renderer prevents unload; does not notify the crash recorder when renderer teardown follows a confirmed window close; allows close when Electron reports a crashed webContents; requests confirmation for a hung-but-alive renderer instead of bypassing. src/main/workspaces/catalog/worktree-identity-persistence.test.ts: stores independent metadata for colliding locators on two hosts; projects canonical-only metadata for exactly one host; keeps canonical metadata current for legacy writers on a known owner; removes only the selected legacy-owner metadata when locators collide; keeps the canonical identity stable when the locator changes; leaves other hosts at the old locator when one host renames its folder. src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.test.ts: leaves a journaled conversion untouched with the gate closed, %s. src/main/wsl/orcad/wsl-orcad-deploy.test.ts: holds the distro before it deploys and launches, and reports what C5 dials; passes its connect-state read (%s) on as hints; applies the SSH census and downgrade admission to the first deploy; refuses a WSL 1 distro before holding it or touching its files; tells an unregistered distro how to find the installed ones, before holding anything; surfaces an unsupported libc as the SSH host refusal does; starts an already-active slot the distro stop ended, instead of reporting it ready; deploys over an adopted unrecorded orcad under the SSH terminal gate, never a fresh launch; reports the adopted instance once the same version is serving; returns a deferral rather than launching over live terminals; hands a failed first deploy to the fresh-install cleanup before reporting it. src/main/zcode/zcode-v2-plan-credentials.test.ts: prefers migrated credentials over a stale legacy account; keeps legacy support when no personal v2 file exists; honors the upstream personal config override independently of the credential directory; does not borrow credentials from another execution host; preserves the protected Orca key priority even if v2 is corrupt; rejects upstream-invalid selection %j without legacy fallback; accepts a valid optional reasoning level; rejects upstream-invalid rule containers %j without legacy fallback; accepts a valid selected-provider empty personal rule and smart model rule; cannot establish selected credentials from %s rules; leaves encrypted CLI files unchanged across repeated account reads. tests/e2e/automation-terminal-launch.unit.test.ts: launches explicit Chat for %s through the common entry and keeps its actual fallback; does not apply stored Terminal extras to Chat; forwards only complete Chat-consumed values, with no Terminal startup base; refuses an expired admission without minting another launch identity; records the actual chat identity and delegates new workspace setup and provenance. tests/e2e/github-project-provider-columns.unit.test.ts: renders %s through one bounded items request on a named cloud host; preserves zero and complete counters: %j; preserves populated and legacy rows through shared sorting, grouping and cells. tests/e2e/structured-agent-session-launch-continuation.unit.test.ts: carries renderer lifetime through host intent to the real %s provider builders. tests/e2e/terminal-account-restart.unit.test.ts: replaces a tombstoned owner while its persisted pane binding has not yet been cleared; paired restart retains the old owner (host authority: %s). tests/e2e/terminal-hidden-view-parking.spec.ts: does not park excluded tabs; reproduces a static frame byte-for-byte across 25 park/reveal cycles. tests/e2e/terminal-long-table-scroll-restore.spec.ts: reproduces long markdown table artifacts after workspace switch and scroll; keeps narrow wrapped signer markdown table coherent after restore and scroll; keeps real emoji markdown table right edge clean after restore and scroll. tests/e2e/terminal-long-table-fixtures.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-paste-ownership.spec.ts: Windows multiline keyboard paste normalizes terminal newlines with one PTY owner; right-click paste sends clipboard text to the focused terminal exactly once. tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts: uses WebGL by default for ordinary terminal output when available @terminal-rendering-golden. tests/e2e/terminal-windows-shell-paste-ownership.spec.ts: cmd.exe default terminal keyboard paste preserves exact content with one PTY owner; Git Bash default terminal keyboard paste preserves POSIX-shaped content with one PTY owner; WSL terminal keyboard paste preserves Linux shell content with one PTY owner. tests/e2e/workspace-board-lane-virtualization.spec.ts: mounts a window of cards for a large lane and keeps lane indexes; renders later lane indexes after the lane scrolls. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts, src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing-races.spec.ts, src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts, src/main/skills/bundled-skill-install/layouts.test.ts, src/main/skills/skill-upload-session-service.test.ts, src/main/source-control/hosted-review-creation.test.ts, src/main/source-control/hosted-review-execution-host-routing.test.ts, src/main/source-control/hosted-review-inflight-invalidation.test.ts, src/main/speech/model-manager.test.ts, src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts, src/main/ssh/connection/ssh-connection-system-transport.test.ts, src/main/ssh/orcad-migration-catalog-client.test.ts, src/main/ssh/runtime-ssh-access.test.ts, src/main/startup/cli-launch-redirect.test.ts, src/main/startup/main-process-runtime-launch-activation.test.ts, src/main/startup/run-electron-vite-dev.test.ts, src/main/updater/releases/updater-prerelease-feed.test.ts, src/main/updater/updater-events.test.ts, src/main/updater/updater-linux-package-recovery-actions.test.ts, src/main/updater/updater.check-settlement.test.ts, src/main/usage/usage-provider-store-lifecycle.test.ts, src/main/window/createMainWindow-close-confirmation.test.ts, src/main/workspaces/catalog/worktree-identity-persistence.test.ts, src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.test.ts, src/main/wsl/orcad/wsl-orcad-deploy.test.ts, src/main/zcode/zcode-v2-plan-credentials.test.ts, tests/e2e/automation-terminal-launch.unit.test.ts, tests/e2e/github-project-provider-columns.unit.test.ts, tests/e2e/structured-agent-session-launch-continuation.unit.test.ts, tests/e2e/terminal-account-restart.unit.test.ts, tests/e2e/terminal-hidden-view-parking.spec.ts, tests/e2e/terminal-long-table-scroll-restore.spec.ts, tests/e2e/terminal-long-table-fixtures.ts, tests/e2e/terminal-paste-ownership.spec.ts, tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts, tests/e2e/terminal-windows-shell-paste-ownership.spec.ts, tests/e2e/workspace-board-lane-virtualization.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -4193,7 +4181,15 @@ "Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", "Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. All prior notes and dated/archived evidence retain original scopes.", "Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes." + "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", + "Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed.", + "Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope.", + "Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection.", + "Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope.", + "Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope.", + "Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope.", + "Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed.", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -4311,7 +4307,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-5557/remote-html-preview-render-workspace-files-locally-over-the-file", "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", @@ -4322,7 +4318,7 @@ "https://github.com/stablyai/orca/pull/13876" ], "invariant": "Opening one HTML preview from a paired client renders the workspace document in exactly one client-local browser tab, located by that document and served over the orca-preview scheme. The client gains exactly that one browser workspace and it is the document one — blank where a URL page carries a URL, named by the document, with the chip naming the file — while the host gains no browser page at all, neither in its own page registry nor in the tab snapshot its clients publish into. The preview occupies its own split without taking focus from the source editor; an explicit click activates it, and closing it removes only the preview. Following a document from a file link is the other half of that switch and does move the reader to it, tab group included, whether the preview is new or already open, because opening a file is a request to look at it. A document tab quit with the client comes back as the same row on a grant the relaunched client mints afresh. A preview is named by the browser page it is open in, not by a namespace of its own, and the page registry has two halves: a workspace-document guest is registered in its own map and is absent from the browsing one entirely. That absence is the fence. Page, session and profile management, agent tab enumeration and command targeting, download routing and certificate attribution all read the browsing map directly, in more places than a per-channel guard could be remembered in, so none of them can name a document page and none of them carries a guard. Browser tools the reader drives (element grab, hover describe, selection capture, the annotation viewport bridge) are the one operation that legitimately spans the halves, and they go through the single authority that reads both, keyed by the page and its hosting renderer. The halves are disjoint in both directions: browsing registration refuses a page the document half already holds, and minting a grant refuses a page the browsing half already holds, so one id can never name a surface in both. The headless backend acts on that refusal by destroying the window it had already opened rather than leaving a policy-less page behind an id nothing can drive, keeping nothing under that id for its own shutdown to hand back. Registration refuses on the same terms when the guest it was asked about is already gone. The exit door is guarded in both its halves: a preview withdraws by revoking its grant and never through the unregister channel, so a page the document half holds arriving there is refused before either the registration teardown or the grab-state disposal beside it, which would otherwise drop the intent an in-flight preview grab compares by identity and leave that grab answering ok without ever arming its guest. A bridge request whose guest does not resolve is refused without tearing down the page it named, so a misaddressed request cannot cancel a healthy page's in-flight downloads and grabs. The annotation viewport bridge resolves its guest when its serialized op actually runs rather than when the request arrived, so a cross-process navigation while it waited cannot leave the bridge installed in a retired guest while the reader looks at a new one. State main keys by a preview's page is disposed when that page's grant is revoked, which is the only signal a preview's surface is gone. A tool asking for a page whose guest has not attached yet waits for that registration and arms when it arrives, rather than answering not-ready at the reader; that wait resolves only the request already naming this page, never the worktree-wide or any-tab waits the CLI and agents use to ask for a browser tab to drive. Handing the previewed document to the reader's own machine routes on the owners its grant was minted against — the file's own connection owner and the worktree's own runtime owner, neither read from the tab's stored fields. Only a document proven to live on this machine reaches the client OS; one with a resolved remote owner is downloaded first; and one whose owner cannot be resolved at all, workspace root included, is refused with a message naming that, because the download route would otherwise read the same absolute path on the client and hand back a same-named local file under the remote document's name. A runtime-owned path that falls outside its worktree root is refused by that route itself and surfaces as a failure toast rather than a download. Nothing the document does writes a file to this machine either: the preview partition denies downloads outright instead of routing them through the browser download flow, which has no page to attribute a preview's bytes to and would otherwise reserve a name in this desktop's Downloads folder and write them there unprompted. That refusal is visible to the reader and invisible to the document: the preview's shell carries a fixed sentence saying downloads are off, published at most once per preview per interval so a document asking in a loop cannot fill Orca's chrome, while the page itself gets back exactly what it got before, which is nothing. The sentence names no file, because the document chooses the name it offers; and a refusal never takes the document away the way an entry document's own failure does, whatever it names. A preview is a browser tab, not an editor tab in a preview mode: it is named the way a browser tab is named — by the document it shows when that document declares a title, and by the file it shows when it does not — while the chip goes on naming the file and the host whatever the document calls itself. A title is refused on the same terms the url is: a document that declares none has Chromium report the grant URL as its title, and that title is stored, mirrored onto the tab and written to disk, so anything carrying the scheme falls back to the file instead. It is created by the preview action as a page located by its document, it carries the workspace-relative path copy the editor's path header owned, and closing it revokes the grant that made the document readable while a URL tab closing beside it revokes nothing. Chrome persisted by builds that made previews editor tabs is dropped on restore rather than coming back naming a surface no restore can produce, and the ordinary editor tab for the same document is left alone. A document tab is held back at the mobile publish boundary — no client holds its grant, and the wire has no tab kind for it — while an ordinary browser tab beside it still publishes. It is held back from the group projection that publishes tab order, recency and group activity as well as from the tab list itself, so no published group names a tab the phone is never sent. A browser page can be located by a workspace document instead of a URL, and the document is the whole of its stored identity. The grant and the orca-preview URL that document is served over are minted when the page mounts and replaced by a hard reload, so neither is ever written to the page's url, mirrored onto its tab, persisted or published: such a page's url is the blank URL from creation through restore, including when a session written elsewhere carries a grant URL in, and what the session carries is the worktree and path a restored page mints afresh against today's owners. Every door onto a page's url holds that line — creation, the title update, and the navigation commit alike — so a report about a document page cannot give it a URL it never had, and the title fallback and the loading affordance follow the url each door actually wrote. The mirror carries the document too, so a tab entry cannot go on naming a document its active page has left. Every guest in the app is policy-attached through one door: a workspace document takes a restricted profile there rather than a separate installer beside it, so the attachment bookkeeping that door owns — what registration refuses, and what teardown frees — covers a preview on the same terms as a browsing page, and a preview takes none of the browsing machinery that door installs. That authority answers from the moment the embedder hands the guest over rather than only after a later navigation: the guest binds to the grant it is already showing, so the tools reach the document the reader opened and not just one they navigated to. A read the host reports as truncated or over-cap is refused rather than served partially, and a document outside the paired worktree is refused with a message naming that boundary instead of a bare read failure. The rendered document reaches nothing off-machine on its own: every served response carries a self-only content security policy, the preview session cancels any request that is not in-document, subframes cannot navigate outside the grant, a guest no document has yet bound to a grant may not navigate at all, the guest gathers no ICE candidates, and an SSH path that canonicalizes outside the grant root is refused before it is read. The one route out is a link the reader presses: a trusted click on an anchor, reported by the preview's own preload from a guest still bound to a live grant, leaves through the configured browser destination and captured source route — and only after the reader confirms the exact destination URL, so a document cannot spend a single stray press exfiltrating what it can read into a link it authored. The preview hands its guest that focus itself whenever it is the surface the reader is in — a browsing page gets it from the chrome around it, and a preview has no chrome to get it from — and it does so only then, so a preview mounted behind a terminal or an editor never takes the keyboard from what the reader is actually in. It offers again when the window itself takes focus back and nothing in the embedder has claimed that focus, because another app coming to the front lands focus on the embedder rather than the guest and the route out would otherwise stay shut until something remounted the pane — while the same window focus also arrives when the reader presses a tab, that being the guest's own blur returning, and taking focus back from there would fight the reader for their own click. Nothing else does. A navigation or popup the document starts by itself is swallowed whatever else is happening, including immediately after a genuine press elsewhere in the document, so a page that can read its grant cannot hand it to a browser tab; a middle click opens nothing; and a fragment link is answered inside the document. A preview attach carries the preview preload and no renderer-supplied one, and no other attach path can acquire it. A subresource the workspace will not send degrades the document to a notice naming that file, never to a failure panel over a page that rendered. A grant outlives neither the tab that owns it nor the renderer document that minted it, and only the trusted renderer can mint or revoke one. For the browser creations this gate still owns, owner-pinned creation returns the canonical host page identity before navigation readiness; delayed navigation cannot turn a created page into an unidentifiable failure or a duplicate retry. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback.", - "oracle": "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", @@ -4678,6 +4674,10 @@ "Collect 100 consecutive focused CI passes or 14 days without an unexplained flake." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2643 deletes the seven fake-manager browser IPC cases: renderer-owned registration repair, untrusted download cancellation refusal, exact certificate approval, cancelled pending grab enablement, in-flight grab serialization, stale guest registration waits, and annotation ownership refusal. These alarms are intentionally lost without replacement; dated evidence retains its original scope and no fresh gate execution is claimed.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -4760,7 +4760,8 @@ "Audit3342 historical original evidenceRuns object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/workspace-doc-page-pane.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 3,\n \"summary\": \"One sole-delta mutant dropping the window-focus re-offer: the guest is focused once at mount and never again after the window comes back, which is the desktop gap behind it — another app taking the front leaves the preview's only route out shut until the pane remounts. It fails only the new re-offer test, and the refusing-preview case beside it stays green, so the re-offer is pinned as gated rather than unconditional.\"\n }", "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3460 historical original active selectors (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\",\n \"npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts src/renderer/src/store/slices/browser/browser.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\",\n \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n ]\ntestFiles: [\n \"src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts\",\n \"src/renderer/src/store/slices/browser/browser.test.ts\",\n \"src/main/browser/document-preview/doc-preview-grant-registry.test.ts\",\n \"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\n \"src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\n \"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"src/main/browser/document-preview/doc-preview-failure-notice.test.ts\",\n \"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts\",\n \"src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\n \"src/renderer/src/components/link-actions/LinkActionPopover.test.tsx\",\n \"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts\",\n \"src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts\",\n \"tests/e2e/paired-remote-html-preview-local-render.spec.ts\",\n \"tests/e2e/paired-preview-address-bar-convergence.spec.ts\",\n \"tests/e2e/paired-browser-create-navigation-deadline.spec.ts\",\n \"tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts\",\n \"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts\",\n \"assertions\": [\"explicit cleanup cannot close a page owned by another worktree\"]\n },\n {\n \"file\": \"src/renderer/src/store/slices/browser/browser.test.ts\",\n \"assertions\": [\n \"a requested canonical page ID is stored on the page rather than reused as its workspace ID\",\n \"duplicate canonical page IDs are rejected before a second tab can materialize\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-html-preview-local-render.spec.ts\",\n \"assertions\": [\n \"the host's HTML document renders inside the client-local orca-preview guest\",\n \"neither the client browser-workspace count nor the host browser-tab count moves off baseline\",\n \"the preview opens in its own split with mode html-preview and leaves the source editor active\",\n \"an explicit click reactivates the preview, and closing it preserves the source editor, its group, and the terminal\",\n \"the document reports having attempted both its unattended and its post-press egress, so neither absence assertion can pass on a document that never tried\",\n \"a scripted window.open and location.href driven by a real press elsewhere in the document route nothing and move no browser count\",\n \"a real target=_blank press in the rendered document routes out as an Orca browser tab while the preview stays open\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\n \"assertions\": [\n \"reads a document too large for one reply by range under the same grant\",\n \"refuses a document rewritten between ranges instead of splicing versions\",\n \"requires approval for a sibling directory before touching the runtime\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-grant-registry.test.ts\",\n \"assertions\": [\n \"keeps silent authority over a document directory strictly inside the workspace, and only there\",\n \"uses Windows semantics when authorizing a sibling directory\",\n \"keeps an approved SSH directory inside the canonical workspace boundary\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-failure-notice.test.ts\",\n \"assertions\": [\"413 and 415 map to distinct reasons and everything else stays generic\"]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"assertions\": [\n \"never rebinds a bound guest onto a second grant\",\n \"leaves a re-minted preview registered when the guest it replaced tears down\"\n ]\n },\n {\n \"file\": \"src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"assertions\": [\n \"malformed grant ids and unsupported schemes are refused\",\n \"undecodable percent escapes are refused\"\n ]\n },\n {\n \"file\": \"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"assertions\": [\n \"a document page's url is blank in the store, in the written session and after restore\",\n \"a document navigation report leaves its URL blank, its title standing and nothing loading; its session excludes preview URLs\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"assertions\": [\n \"a preview that is the reader's surface hands its guest focus, and one that is not leaves focus alone\",\n \"the window taking focus back re-offers it to the guest, and re-offers nothing for a preview that was refusing\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-browser-create-navigation-deadline.spec.ts\",\n \"assertions\": [\n \"a held navigation exceeds the former create deadline while the first RPC returns the exact authoritative host page ID\",\n \"host inventory contains exactly one new page and the user retry branch is never entered\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts\",\n \"assertions\": [\n \"the exact created page exists on the host while publication is held and no browser tab materializes on the client\",\n \"a forced post-create reconciliation timeout closes the exact host page and removes only the reserved empty split\",\n \"a forced capability rejection after caller preflight shows a toast and restores exact host and client inventories\",\n \"headed and headless hosts preserve the unrelated editor and terminal without local fallback\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\n \"assertions\": [\n \"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\",\n \"retains exact-leaf focus intent when a split sibling publishes first\"\n ]\n }\n ]" + "Audit3460 historical original active selectors (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\",\n \"npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts src/renderer/src/store/slices/browser/browser.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\",\n \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n ]\ntestFiles: [\n \"src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts\",\n \"src/renderer/src/store/slices/browser/browser.test.ts\",\n \"src/main/browser/document-preview/doc-preview-grant-registry.test.ts\",\n \"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\n \"src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\n \"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"src/main/browser/document-preview/doc-preview-failure-notice.test.ts\",\n \"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts\",\n \"src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\n \"src/renderer/src/components/link-actions/LinkActionPopover.test.tsx\",\n \"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts\",\n \"src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts\",\n \"tests/e2e/paired-remote-html-preview-local-render.spec.ts\",\n \"tests/e2e/paired-preview-address-bar-convergence.spec.ts\",\n \"tests/e2e/paired-browser-create-navigation-deadline.spec.ts\",\n \"tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts\",\n \"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts\",\n \"assertions\": [\"explicit cleanup cannot close a page owned by another worktree\"]\n },\n {\n \"file\": \"src/renderer/src/store/slices/browser/browser.test.ts\",\n \"assertions\": [\n \"a requested canonical page ID is stored on the page rather than reused as its workspace ID\",\n \"duplicate canonical page IDs are rejected before a second tab can materialize\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-html-preview-local-render.spec.ts\",\n \"assertions\": [\n \"the host's HTML document renders inside the client-local orca-preview guest\",\n \"neither the client browser-workspace count nor the host browser-tab count moves off baseline\",\n \"the preview opens in its own split with mode html-preview and leaves the source editor active\",\n \"an explicit click reactivates the preview, and closing it preserves the source editor, its group, and the terminal\",\n \"the document reports having attempted both its unattended and its post-press egress, so neither absence assertion can pass on a document that never tried\",\n \"a scripted window.open and location.href driven by a real press elsewhere in the document route nothing and move no browser count\",\n \"a real target=_blank press in the rendered document routes out as an Orca browser tab while the preview stays open\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\n \"assertions\": [\n \"reads a document too large for one reply by range under the same grant\",\n \"refuses a document rewritten between ranges instead of splicing versions\",\n \"requires approval for a sibling directory before touching the runtime\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-grant-registry.test.ts\",\n \"assertions\": [\n \"keeps silent authority over a document directory strictly inside the workspace, and only there\",\n \"uses Windows semantics when authorizing a sibling directory\",\n \"keeps an approved SSH directory inside the canonical workspace boundary\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-failure-notice.test.ts\",\n \"assertions\": [\"413 and 415 map to distinct reasons and everything else stays generic\"]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"assertions\": [\n \"never rebinds a bound guest onto a second grant\",\n \"leaves a re-minted preview registered when the guest it replaced tears down\"\n ]\n },\n {\n \"file\": \"src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"assertions\": [\n \"malformed grant ids and unsupported schemes are refused\",\n \"undecodable percent escapes are refused\"\n ]\n },\n {\n \"file\": \"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"assertions\": [\n \"a document page's url is blank in the store, in the written session and after restore\",\n \"a document navigation report leaves its URL blank, its title standing and nothing loading; its session excludes preview URLs\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"assertions\": [\n \"a preview that is the reader's surface hands its guest focus, and one that is not leaves focus alone\",\n \"the window taking focus back re-offers it to the guest, and re-offers nothing for a preview that was refusing\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-browser-create-navigation-deadline.spec.ts\",\n \"assertions\": [\n \"a held navigation exceeds the former create deadline while the first RPC returns the exact authoritative host page ID\",\n \"host inventory contains exactly one new page and the user retry branch is never entered\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts\",\n \"assertions\": [\n \"the exact created page exists on the host while publication is held and no browser tab materializes on the client\",\n \"a forced post-create reconciliation timeout closes the exact host page and removes only the reserved empty split\",\n \"a forced capability rejection after caller preflight shows a toast and restores exact host and client inventories\",\n \"headed and headless hosts preserve the unrelated editor and terminal without local fallback\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\n \"assertions\": [\n \"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\",\n \"retains exact-leaf focus intent when a split sibling publishes first\"\n ]\n }\n ]", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -4792,32 +4793,31 @@ "providers": ["local", "remote-runtime", "ssh", "wsl"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1563 retires mock cookie inventories, summary/flag/counter checks, historical replacement/replay narratives and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise owned admission and cleanup, real staged-file lifetime, JSON/SQLite/WAL/schema compatibility, synthetic encryption and native Electron SameSite storage. Session/CDP/credential/write/renderer producers remain injected where recorded. Seven unchanged native definitions are not rerun locally; known stale registry-stub fixtures are not executable proof. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1559 removes mocked host/lease/reconciliation, event/flag/counter, forwarding, inventory and retry-budget alarms without equivalent replacement coverage. Retained cases establish owned promise, registry, rollback, admission and cleanup boundaries with injected Electron/renderer/host inputs; actual local sockets, file staging and Buffer collection are scoped in the PR. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain historical evidence only. No live paired runtime, rendered browser/profile/TLS or device claim. Historical scope before this audit: Audit1401 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1340 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic protocol, registry, injected-socket, and loopback-listener tests cover strict framing, remote-DNS targets, exact destination-write and source-consumption credit, at most 256 streams per route with pending opens counted inside that cap, 1024 admitted opens per 10-second monotonic window, an 8 MiB per-route application-buffer ledger, shared 32 MiB browser-host and 128 MiB process ledgers across application copies, encrypted client queues, and native WebSocket bufferedAmount, bounded byte/claim/socket-source counts, a four-frame queued-drain quantum, authority epochs, exact host selection, one host per authenticated connection, four hosts per paired device, eight global browser-host polls with four per authenticated paired device, a shared ask/host ceiling that retains one quarter for waits, bounded initial and reconnect runtime_busy recovery, long-poll metering and disconnect abort, monotonic host/page/route generations without page tombstones, two-phase exact page retirement with cancellation, connection-owned cleanup, exact client revocation, stale and replaced fences, retired stream IDs, half-close and close ordering, SOCKS CONNECT, bind/close races, listener wildcard normalization, unsupported commands, unavailable routes, and raw/terminal binary-handler isolation. Page commands use a separately echoed v1 attach negotiation, exact authority/host/page generations, bounded command IDs and sequences, and bounded create/navigate payloads; legacy attaches still receive only the unchanged ready/revoked event shapes. A second optional reconciliation subprotocol gates bounded reclaim, close, and restore payloads behind exact attach/ready echo, complete inventory, command negotiation, reconnect authority, and command-result authority; the production client advertises it only with the matching command and inventory capabilities. Exact guest or app-renderer loss marks one page generation outcome-unknown, coalesces a bounded negotiated inventory reattach, closes or retires the dead generation, and allocates a fresh generation before URL restore; explicit close is not misclassified as a crash. Mixed-version mutation tests project hidden client pages before activate, close, split, reorder, and move-to-group admission, preserve hidden raw order slots, translate visible insertion indices, and project mutation snapshots. A production server orchestrator consumes each immutable inventory once, reserves target generations without exposing placement, emits only negotiated ledger commands, commits after exact completed proof, preserves unrelated and server placements, aborts an attempt when connection authority enters reconnect grace, and requires fresh inventory after failure or abort. The production client dispatcher additionally proves per-page FIFO execution, exact payload-matched duplicate replay, frozen command/result snapshots, a global retired-generation floor, transactional admission, bounded pages/active commands/queues/per-page and global result cache/concurrency, create dependency failure, cancellation, deduplicated retirement joining, and bounded close without late-result overwrite. The server ledger owns issue order and immutable command/result snapshots, bounds outstanding commands, active pages, and per-page/global replay caches, releases active-page capacity after an exact completed close while retaining bounded result replay, validates the shared wire payload before admission, requires live delivery and exact placement, authenticates results to the negotiated connection and paired lease, rejects gaps and conflicting replay, and fences outstanding outcomes at exact retirement. Negotiated command results reuse the authenticated attach socket through bounded nested JSON requests; exact ID routing, reverse-order replies, unknown and duplicate IDs, timeout teardown, serialization failure, aggregate queue accounting, acknowledgement validation, and the unchanged non-v1 path are deterministic. A stable local listener rejects CONNECT while offline or reconnecting, retains its address across replacement, requires a strictly increasing tunnel generation, ignores late superseded callbacks, propagates tunnel protocol failure to the route owner, and recycles exhausted stream IDs only after generation replacement. Reconnect uses the unchanged native v1 attach payload and capability pair; SSH descriptors alone add an execution-host capability and require a runtime-minted grant bound to the exact browser-host lease. Exact SSH provider epoch and connection generation fence ssh2 forwardOut and one non-interactive standalone system-SSH dynamic forward per route. Unit tests preserve domain-form SOCKS requests, sanitize remote errors, bound stderr, cancel startup, release timed-out and synchronously failed sockets, and release routes once. An ephemeral Docker sshd resolves a container-only domain and returns a unique HTTP marker through both ssh2 and the actual system-OpenSSH dynamic-forward adapter without touching the user's SSH files; authority loss fences the ssh2 route. The execution runtime charges route application bytes to the same per-host/process policy; its existing E2EE owner separately caps native outbound buffers process-wide. Production-registered browser-host and paired-runtime methods lease one exact host, prove attach, command delivery, and result settlement share one exact connection identity, then carry SOCKS and HTTP bytes over a dedicated E2EE socket to the fenced execution-host revision and prove route close destroys the destination socket. The production desktop adapter now composes one exact host per environment pairing revision with the page executor, current renderer selector, route Session/WebContents registries, and one reference-counted route per canonical execution-host key. Negotiated same-client control reconnect retains exact authority, placements, grants, dispatcher dedupe, executor guests, and listener addresses; it fences tunnels immediately, blocks route admission, reattaches command delivery only after ready, and replays unsettled commands without repeating completed mutations. Terminal release, replacement, legacy disconnect, and reconnect-grace expiry make only the exact host generation's client placements non-cancellable retirement-pending while retaining capacity until exact cleanup; reconnect grace preserves them. Environment replacement and app shutdown still serialize transport closure before page cleanup and force-close every remaining route. The production placement preparation starts the exact desktop adapter and advertises host/tunnel capabilities only when the paired Electron client is eligible. Node stream-internal high-water bytes, strict cross-route scheduling, and physical cross-platform evidence remain uncovered. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. The removed retry-arithmetic and attach-request inventory suites are not current coverage; retained lease and composition suites exercise admission retry, cleanup, inventory negotiation, and reconnect behavior. Test-value audit1293 removes src/main/browser/network/tunnels/browser-network-tunnel-client-memory-budget.test.ts (4 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1302: src/main/browser/client-pages/lifecycle/browser-client-page-unavailability.test.ts: Every route/guest lifecycle/currentness/navigation/renderer/automation authority is supplied by fake callbacks, then unavailability listener is invoked manually and private inventory/mock calls are checked. No guest destruction, renderer disconnect or actual reconciliation/close consumer. Lose generation fence/reconcile-once/missing-renderer-close branch alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1318: src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts: Retain actual local encrypted WebSocket subscription concurrency routing when host replies out of order, plus an exception thrown by a real ws consumer callback being turned into a subscription error. Server is a test-shaped handshake/response producer using production crypto, not actual runtime host/auth authority or independent cryptographic oracle. Remove happy second-request duplicate, unknown/duplicate-ID branches, fixed32 capacity, serialization/capacity/timeouts and fake memory release/admission call-count scenarios; intentionally lose those alarms. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1340: src/main/runtime/runtime-binary-message-router.test.ts removed. Connection mode conflict exceptions and one terminal/raw callback each. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1371 removes the reconciliation protocol/capability echo inventory from browser-client-host-reconciliation.test.ts. The pending command result refusal without exact authority and later accepted acknowledgement callback remains byte-identical. The narrow negotiation echo alarm is intentionally lost; no equivalent browser/authenticated transport proof is claimed. Existing receipts with unchanged selectors retain only their original scope. Audit1401: src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts reduced. Loses deterministic equal-length URL compaction tie-breaking and reversed-input invariance alarm. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim): Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1563 retires mock cookie inventories, summary/flag/counter checks, historical replacement/replay narratives and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise owned admission and cleanup, real staged-file lifetime, JSON/SQLite/WAL/schema compatibility, synthetic encryption and native Electron SameSite storage. Session/CDP/credential/write/renderer producers remain injected where recorded. Seven unchanged native definitions are not rerun locally; known stale registry-stub fixtures are not executable proof. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1559 removes mocked host/lease/reconciliation, event/flag/counter, forwarding, inventory and retry-budget alarms without equivalent replacement coverage. Retained cases establish owned promise, registry, rollback, admission and cleanup boundaries with injected Electron/renderer/host inputs; actual local sockets, file staging and Buffer collection are scoped in the PR. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain historical evidence only. No live paired runtime, rendered browser/profile/TLS or device claim. Historical scope before this audit: Audit1401 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1340 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic protocol, registry, injected-socket, and loopback-listener tests cover strict framing, remote-DNS targets, exact destination-write and source-consumption credit, at most 256 streams per route with pending opens counted inside that cap, 1024 admitted opens per 10-second monotonic window, an 8 MiB per-route application-buffer ledger, shared 32 MiB browser-host and 128 MiB process ledgers across application copies, encrypted client queues, and native WebSocket bufferedAmount, bounded byte/claim/socket-source counts, a four-frame queued-drain quantum, authority epochs, exact host selection, one host per authenticated connection, four hosts per paired device, eight global browser-host polls with four per authenticated paired device, a shared ask/host ceiling that retains one quarter for waits, bounded initial and reconnect runtime_busy recovery, long-poll metering and disconnect abort, monotonic host/page/route generations without page tombstones, two-phase exact page retirement with cancellation, connection-owned cleanup, exact client revocation, stale and replaced fences, retired stream IDs, half-close and close ordering, SOCKS CONNECT, bind/close races, listener wildcard normalization, unsupported commands, unavailable routes, and raw/terminal binary-handler isolation. Page commands use a separately echoed v1 attach negotiation, exact authority/host/page generations, bounded command IDs and sequences, and bounded create/navigate payloads; legacy attaches still receive only the unchanged ready/revoked event shapes. A second optional reconciliation subprotocol gates bounded reclaim, close, and restore payloads behind exact attach/ready echo, complete inventory, command negotiation, reconnect authority, and command-result authority; the production client advertises it only with the matching command and inventory capabilities. Exact guest or app-renderer loss marks one page generation outcome-unknown, coalesces a bounded negotiated inventory reattach, closes or retires the dead generation, and allocates a fresh generation before URL restore; explicit close is not misclassified as a crash. Mixed-version mutation tests project hidden client pages before activate, close, split, reorder, and move-to-group admission, preserve hidden raw order slots, translate visible insertion indices, and project mutation snapshots. A production server orchestrator consumes each immutable inventory once, reserves target generations without exposing placement, emits only negotiated ledger commands, commits after exact completed proof, preserves unrelated and server placements, aborts an attempt when connection authority enters reconnect grace, and requires fresh inventory after failure or abort. The production client dispatcher additionally proves per-page FIFO execution, exact payload-matched duplicate replay, frozen command/result snapshots, a global retired-generation floor, transactional admission, bounded pages/active commands/queues/per-page and global result cache/concurrency, create dependency failure, cancellation, deduplicated retirement joining, and bounded close without late-result overwrite. The server ledger owns issue order and immutable command/result snapshots, bounds outstanding commands, active pages, and per-page/global replay caches, releases active-page capacity after an exact completed close while retaining bounded result replay, validates the shared wire payload before admission, requires live delivery and exact placement, authenticates results to the negotiated connection and paired lease, rejects gaps and conflicting replay, and fences outstanding outcomes at exact retirement. Negotiated command results reuse the authenticated attach socket through bounded nested JSON requests; exact ID routing, reverse-order replies, unknown and duplicate IDs, timeout teardown, serialization failure, aggregate queue accounting, acknowledgement validation, and the unchanged non-v1 path are deterministic. A stable local listener rejects CONNECT while offline or reconnecting, retains its address across replacement, requires a strictly increasing tunnel generation, ignores late superseded callbacks, propagates tunnel protocol failure to the route owner, and recycles exhausted stream IDs only after generation replacement. Reconnect uses the unchanged native v1 attach payload and capability pair; SSH descriptors alone add an execution-host capability and require a runtime-minted grant bound to the exact browser-host lease. Exact SSH provider epoch and connection generation fence ssh2 forwardOut and one non-interactive standalone system-SSH dynamic forward per route. Unit tests preserve domain-form SOCKS requests, sanitize remote errors, bound stderr, cancel startup, release timed-out and synchronously failed sockets, and release routes once. An ephemeral Docker sshd resolves a container-only domain and returns a unique HTTP marker through both ssh2 and the actual system-OpenSSH dynamic-forward adapter without touching the user's SSH files; authority loss fences the ssh2 route. The execution runtime charges route application bytes to the same per-host/process policy; its existing E2EE owner separately caps native outbound buffers process-wide. Production-registered browser-host and paired-runtime methods lease one exact host, prove attach, command delivery, and result settlement share one exact connection identity, then carry SOCKS and HTTP bytes over a dedicated E2EE socket to the fenced execution-host revision and prove route close destroys the destination socket. The production desktop adapter now composes one exact host per environment pairing revision with the page executor, current renderer selector, route Session/WebContents registries, and one reference-counted route per canonical execution-host key. Negotiated same-client control reconnect retains exact authority, placements, grants, dispatcher dedupe, executor guests, and listener addresses; it fences tunnels immediately, blocks route admission, reattaches command delivery only after ready, and replays unsettled commands without repeating completed mutations. Terminal release, replacement, legacy disconnect, and reconnect-grace expiry make only the exact host generation's client placements non-cancellable retirement-pending while retaining capacity until exact cleanup; reconnect grace preserves them. Environment replacement and app shutdown still serialize transport closure before page cleanup and force-close every remaining route. The production placement preparation starts the exact desktop adapter and advertises host/tunnel capabilities only when the paired Electron client is eligible. Node stream-internal high-water bytes, strict cross-route scheduling, and physical cross-platform evidence remain uncovered. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. The removed retry-arithmetic and attach-request inventory suites are not current coverage; retained lease and composition suites exercise admission retry, cleanup, inventory negotiation, and reconnect behavior. Test-value audit1293 removes src/main/browser/network/tunnels/browser-network-tunnel-client-memory-budget.test.ts (4 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1302: src/main/browser/client-pages/lifecycle/browser-client-page-unavailability.test.ts: Every route/guest lifecycle/currentness/navigation/renderer/automation authority is supplied by fake callbacks, then unavailability listener is invoked manually and private inventory/mock calls are checked. No guest destruction, renderer disconnect or actual reconciliation/close consumer. Lose generation fence/reconcile-once/missing-renderer-close branch alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1318: src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts: Retain actual local encrypted WebSocket subscription concurrency routing when host replies out of order, plus an exception thrown by a real ws consumer callback being turned into a subscription error. Server is a test-shaped handshake/response producer using production crypto, not actual runtime host/auth authority or independent cryptographic oracle. Remove happy second-request duplicate, unknown/duplicate-ID branches, fixed32 capacity, serialization/capacity/timeouts and fake memory release/admission call-count scenarios; intentionally lose those alarms. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1340: src/main/runtime/runtime-binary-message-router.test.ts removed. Connection mode conflict exceptions and one terminal/raw callback each. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1371 removes the reconciliation protocol/capability echo inventory from browser-client-host-reconciliation.test.ts. The pending command result refusal without exact authority and later accepted acknowledgement callback remains byte-identical. The narrow negotiation echo alarm is intentionally lost; no equivalent browser/authenticated transport proof is claimed. Existing receipts with unchanged selectors retain only their original scope. Audit1401: src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts reduced. Loses deterministic equal-length URL compaction tie-breaking and reversed-input invariance alarm. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews" ], "invariant": "A client-hosted browser network route exists only for an exact live server-owned browser-host lease, authority epoch, host generation, paired identity, execution-host revision or SSH provider authority, and server-owned route generation. A client page is usable only when its runtime ID, authority epoch, host identity and generation, logical page ID, page-host generation, current placement, and still-live lease all match atomically; a retired, retirement-pending, or server-placed page cannot be claimed as live client placement. Live logical placements and their identities are bounded, an occupied logical page cannot change placement until exact two-phase retirement completes, cancellation restores the same authority, and the runtime-wide page generation stays monotonic without tombstones. Server-issued page commands and results remain bounded, FIFO per page, immutable after admission, authenticated to the exact paired lease, attach connection, and live placement, and replayable only when byte-equivalent. Negotiated transient result-transport loss retains exact authority and replays unsettled commands through the preserved client dedupe cache; terminal authority loss makes outstanding outcomes unknown and makes only the exact host generation's placements non-cancellable retirement-pending until exact cleanup or reconciliation proof. Desktop composition installs exact command authority before delivery, keeps result settlements below nested-request capacity, suspends every tunnel without closing guests on negotiated loss, gates handlers through route recovery, and synchronously suspends routes and revokes exact retained navigation grants before asynchronous transport or handler cleanup on terminal loss. Navigation-revocation failure remains observable without preventing guest destruction and route cleanup. One environment pairing revision owns at most one composed desktop host and one reference-counted route per canonical execution-host key; pairing replacement and shutdown close control transport before pages and force-close routes even when guest cleanup remains ambiguous. Non-native descriptors require explicit capability negotiation and an exact runtime-minted lease-bound execution-host grant. Host selection never chooses arbitrarily, stale cleanup or settlement cannot remove a replacement, destination names remain unresolved until the execution host, credit returns only after writes settle, and route loss never falls back to desktop DNS or sockets. A main-owned local listener remains stable across upstream transport loss, rejects CONNECT while offline, accepts only a strictly newer tunnel generation, ignores superseded callbacks, and never reuses a stream ID within one generation. Pending opens, admitted open rate, nested control requests, per-route application bytes, aggregate browser-host/process bytes, claims, and socket sources remain bounded with exact release on settlement and retirement. Queued transport drain yields after a bounded quantum. The local SOCKS endpoint accepts only loopback CONNECT and rejects unsupported commands.", - "oracle": "Test-value audit removes the retired suite and its active selectors/assertions. Retire the paired-host late subscription smoke: it checks a mocked close count and startup rejection, without remote unsubscribe or successor outcomes. Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1686 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Attach two browser hosts and require unqualified selection to fail ambiguous while exact selection succeeds. Reject a second identity on one connection and a fifth identity for one paired device, release one exact lease, then admit its replacement without starving another device. Admit four hosts from one authenticated device and a host from a second, reject the first device's fifth host, and release only the first device's exact counters while the second remains live. Fill asks and hosts to their shared ceiling, retain a quarter of the total budget for ordinary waits, close both sockets, and prove every global, class, and device counter releases. Reject one initial host attach with the unchanged runtime_busy response, then require bounded client-specific jitter to attach when capacity returns; repeated rejection and explicit close must release every timer and subscription. Replace one same-device connection, require the old subscription and route to fence, then prove late old cleanup leaves the new generation live. Mint an exact execution-host grant, reject a different key, prove late old grant cleanup leaves its replacement, and invalidate every grant with lease replacement. Reject client-to-client, client-to-server, server-to-server, and server-to-client placement overwrite until exact retirement. Begin retirement once idempotently, reject client use and every replacement while pending, cancel the exact token to restore the same placement, and reject delayed cancellation or completion after a newer retirement begins. On explicit release, replacement, legacy disconnect, and reconnect-grace expiry, require only the exact host generation's client placements to become non-cancellable retirement-pending before lease settlement; preserve negotiated grace, other hosts, server placements, replacements, and capacity until exact completion. Complete only the exact pending token, retain capacity until completion, and require a reused client page ID to receive a higher global generation without retaining a tombstone. Require a client page through the exact runtime, epoch, host, and page tuple; reject every mismatch, released or replaced leases, retirement-pending pages, retired pages, server placements, invalid identities, and the 257th live placement. Admit 1024 opens in one monotonic 10-second window and reject the 1025th until the window expires. Fill 8 MiB across destination-to-client queues and separately across unsettled client-to-destination writes, release one exact retired stream, admit one replacement, and require the next byte claim to close the route without stale-callback or reentrant-close underflow. Across multiple routes, charge application copies, encrypted queue entries, and dynamic native socket bytes to one 32 MiB browser-host and 128 MiB process ceiling; reject zero-byte claim/socket-source floods, fence released leases, synchronously release JavaScript queue claims while retaining native claims through exact socket close, and yield a parked queue after four frames without reordering. Route nested responses by exact ID under reordering, reject unknown and duplicate IDs, cap pending requests and queued bytes, and tear down every concurrent waiter once on timeout or close. Drive one real paired attach, command, and result through one exact connection ID; reject missing send support and malformed or wrong-runtime acknowledgements while preserving old non-v1 attaches. Drop an authenticated transport, require the same listener to reject CONNECT before and during reconnect, attach the exact existing native v1 payload and capability pair to a strictly newer generation, ignore late old callbacks, and roll an exhausted stream-ID ledger only by replacing the generation. Require SSH descriptors to add an execution-host capability and exact grant, reject missing grants and stale provider authority before resolver or binary registration, pass exact domains to ssh2 and system-SSH SOCKS without local resolution, sanitize connector diagnostics, and close every stream and standalone route process once on timeout, synchronous failure, or rotation. Drive the accepted lease through real paired E2EE native SOCKS-to-HTTP and ephemeral Docker ssh2 remote-only DNS journeys, then exercise exact frame, credit, half-close, stale-stream, remote-DNS, unsupported-command, offline, and teardown assertions.", + "oracle": "Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim): Test-value audit3842 retires four ws-outbound queue unit probes: direct empty-queue send failure, configured drain quantum/zero-delay reschedule, injected aggregate claim/release accounting, and supplied unwritable drain guard. Their exact alarms are intentionally lost; retained queue behaviors are not equivalent replacements. All source-file commands remain valid. No fresh execution or measured-budget evidence is claimed. Historical prior account (preserved verbatim): Test-value audit removes the retired suite and its active selectors/assertions. Retire the paired-host late subscription smoke: it checks a mocked close count and startup rejection, without remote unsubscribe or successor outcomes. Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1686 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Attach two browser hosts and require unqualified selection to fail ambiguous while exact selection succeeds. Reject a second identity on one connection and a fifth identity for one paired device, release one exact lease, then admit its replacement without starving another device. Admit four hosts from one authenticated device and a host from a second, reject the first device's fifth host, and release only the first device's exact counters while the second remains live. Fill asks and hosts to their shared ceiling, retain a quarter of the total budget for ordinary waits, close both sockets, and prove every global, class, and device counter releases. Reject one initial host attach with the unchanged runtime_busy response, then require bounded client-specific jitter to attach when capacity returns; repeated rejection and explicit close must release every timer and subscription. Replace one same-device connection, require the old subscription and route to fence, then prove late old cleanup leaves the new generation live. Mint an exact execution-host grant, reject a different key, prove late old grant cleanup leaves its replacement, and invalidate every grant with lease replacement. Reject client-to-client, client-to-server, server-to-server, and server-to-client placement overwrite until exact retirement. Begin retirement once idempotently, reject client use and every replacement while pending, cancel the exact token to restore the same placement, and reject delayed cancellation or completion after a newer retirement begins. On explicit release, replacement, legacy disconnect, and reconnect-grace expiry, require only the exact host generation's client placements to become non-cancellable retirement-pending before lease settlement; preserve negotiated grace, other hosts, server placements, replacements, and capacity until exact completion. Complete only the exact pending token, retain capacity until completion, and require a reused client page ID to receive a higher global generation without retaining a tombstone. Require a client page through the exact runtime, epoch, host, and page tuple; reject every mismatch, released or replaced leases, retirement-pending pages, retired pages, server placements, invalid identities, and the 257th live placement. Admit 1024 opens in one monotonic 10-second window and reject the 1025th until the window expires. Fill 8 MiB across destination-to-client queues and separately across unsettled client-to-destination writes, release one exact retired stream, admit one replacement, and require the next byte claim to close the route without stale-callback or reentrant-close underflow. Across multiple routes, charge application copies, encrypted queue entries, and dynamic native socket bytes to one 32 MiB browser-host and 128 MiB process ceiling; reject zero-byte claim/socket-source floods, fence released leases, synchronously release JavaScript queue claims while retaining native claims through exact socket close, and yield a parked queue after four frames without reordering. Route nested responses by exact ID under reordering, reject unknown and duplicate IDs, cap pending requests and queued bytes, and tear down every concurrent waiter once on timeout or close. Drive one real paired attach, command, and result through one exact connection ID; reject missing send support and malformed or wrong-runtime acknowledgements while preserving old non-v1 attaches. Drop an authenticated transport, require the same listener to reject CONNECT before and during reconnect, attach the exact existing native v1 payload and capability pair to a strictly newer generation, ignore late old callbacks, and roll an exhausted stream-ID ledger only by replacing the generation. Require SSH descriptors to add an execution-host capability and exact grant, reject missing grants and stale provider authority before resolver or binary registration, pass exact domains to ssh2 and system-SSH SOCKS without local resolution, sanitize connector diagnostics, and close every stream and standalone route process once on timeout, synchronous failure, or rotation. Drive the accepted lease through real paired E2EE native SOCKS-to-HTTP and ephemeral Docker ssh2 remote-only DNS journeys, then exercise exact frame, credit, half-close, stale-stream, remote-DNS, unsupported-command, offline, and teardown assertions.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/browser-network-execution-route.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts", @@ -4833,7 +4833,6 @@ "src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts", "src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts", "src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", - "src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts", "src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts", "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts", @@ -4841,7 +4840,6 @@ "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts", "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts", "src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts", - "src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts", "src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts", "src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts", "src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts", @@ -4866,13 +4864,6 @@ "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" ], "assertionRefs": [ - { - "file": "src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts", - "assertions": [ - "one paired device cannot consume the second device's reserved browser-host share", - "asks and browser hosts share a ceiling that retains one quarter of total capacity for waits" - ] - }, { "file": "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts", "assertions": [ @@ -4904,12 +4895,6 @@ "stale, occupied, cross-page, and cross-renderer targets fail without mutation" ] }, - { - "file": "src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts", - "assertions": [ - "spontaneous exact guest destruction revokes active inventory before explicit page retirement" - ] - }, { "file": "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts", "assertions": ["keeps a failed authority transition tombstoned until cleanup settles"] @@ -5092,9 +5077,7 @@ { "file": "src/shared/ws-outbound-backpressure-queue.test.ts", "assertions": [ - "direct and already-retained queued frames use distinct aggregate admission semantics", - "queued drain yields after its configured frame quantum without reordering", - "aggregate queue claims release on drain, denial, disposal, and close" + "direct and already-retained queued frames use distinct aggregate admission semantics" ] } ], @@ -5153,6 +5136,7 @@ "Prove an Electron partition routes loopback, DNS, HTTP, HTTPS, WebSocket, workers, and speculative traffic without desktop fallback." ], "knownGaps": [ + "Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim):", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/ssh/system-transport/system-ssh-forward-process.test.ts: spawns exactly the argv the orphan matcher is given, LogLevel=INFO included; runs port forwards unmultiplexed even when ssh_config disables muxing; preserves manual target port and identity options in the forwarded ssh command; does not spawn ssh when the requested local forward port is already in use; spawns ssh after the requested local forward port preflight succeeds; resolves startup after the grace period when ssh keeps running; sends SIGTERM then SIGKILL when the process does not exit; does not resolve stop until the process exits. src/main/ssh/port-forwarding/ssh-port-forward.test.ts: reports the port the OS bound when an ssh2 forward asks for port 0; adds an ssh2 port forward and returns entry; adds a system SSH port forward when no ssh2 client is available; reports the port a system SSH forward resolved when asked for port 0; passes resolved OpenSSH config to system SSH port forwards; disposes a system SSH tunnel when removing the forward; lists forwards filtered by connectionId; removes a forward by id; awaits forward close when removing a forward for user actions; returns null when removing nonexistent forward; removes all forwards for a connection; dispose removes all forwards; stores label in the entry; preserves the existing id when updating a forward succeeds. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/ssh/port-forwarding/ssh-port-forward.test.ts, src/main/ssh/system-transport/system-ssh-forward-process.test.ts. Unresolved local/computed edges remain explicit debt. Retired active assertionRefs (raw original objects retained as historical only): {\n \"file\": \"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\n \"assertions\": [\n \"static system-SSH forwards receive the connection's complete resolved build options\"\n ]\n }", "Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded.", "Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -5208,7 +5192,8 @@ "Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged.", "Historical dynamic-forward assertion metadata before inventory retirement, preserved verbatim:\n{\n \"file\": \"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\n \"assertions\": [\n \"system SSH uses BatchMode=yes, disables ControlMaster, and positions one dynamic forward before the destination\",\n \"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"\n ]\n }", "Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed.\nOriginal active selector fields, historical raw native JSON values:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/browser/network/tunnels/browser-network-tunnel-protocol.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/browser-network-execution-route.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\n \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n ]\ntestFiles: [\n \"src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts\",\n \"src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\n \"src/shared/browser/network/tunnels/browser-network-tunnel-protocol.test.ts\",\n \"src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts\",\n \"src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts\",\n \"src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts\",\n \"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\n \"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\n \"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts\",\n \"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\n \"src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts\",\n \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\n \"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\n \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\n \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\n \"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\n \"src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts\",\n \"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\n \"src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts\",\n \"src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts\",\n \"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\n \"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\n \"src/main/browser/network/execution-routes/browser-network-execution-route.test.ts\",\n \"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\n \"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\n \"src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts\",\n \"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\n \"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\n \"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\n \"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\n \"src/shared/ws-outbound-backpressure-queue.test.ts\",\n \"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts\",\n \"assertions\": [\n \"one paired device cannot consume the second device's reserved browser-host share\",\n \"asks and browser hosts share a ceiling that retains one quarter of total capacity for waits\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts\",\n \"assertions\": [\"closes a subscription acquired after local teardown\"]\n },\n {\n \"file\": \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\n \"assertions\": [\n \"an acknowledged mutation replay uses the preserved dispatcher result without rerunning its handler\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\n \"assertions\": [\n \"waits for old handlers and ignores their late callbacks before replacement\",\n \"keeps one command gate across repeated loss while fencing stale route recovery\",\n \"fails closed without racing page cleanup when handlers do not settle\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\n \"assertions\": [\"holds Session and route release for the exact destroyed acknowledgement\"]\n },\n {\n \"file\": \"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\n \"assertions\": [\n \"destroys a guest rekeyed during an authority transition instead of granting navigation\"\n ]\n },\n {\n \"file\": \"src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts\",\n \"assertions\": [\n \"prepared authority rekeys without changing its opaque capability token\",\n \"stale, occupied, cross-page, and cross-renderer targets fail without mutation\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts\",\n \"assertions\": [\n \"spontaneous exact guest destruction revokes active inventory before explicit page retirement\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\n \"assertions\": [\"keeps a failed authority transition tombstoned until cleanup settles\"]\n },\n {\n \"file\": \"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\n \"assertions\": [\n \"retains one exact route until its final page releases it\",\n \"keeps an ambiguously closed route fenced until final registry cleanup\",\n \"retires old authority routes without destroying them before exact page cleanup\",\n \"aborts a stale route recovery without retaining its retry timer\",\n \"fails bounded recovery after one route exhausts grace without leaking timers\",\n \"mints a fresh route for a retain that lands while the previous one is closing\",\n \"waits for a route still closing before reporting retirement\",\n \"rejects a retain the moment its signal aborts mid-startup\",\n \"refuses a retain that waited out a closing route onto a retired registry\",\n \"reports a failed final cleanup to an awaiting retirement\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"assertions\": [\n \"keeps a timed-out retirement fenced until its handler actually settles\",\n \"bounds close while canceling queued and non-cooperative handlers\"\n ]\n },\n {\n \"file\": \"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\n \"assertions\": [\n \"oversized wire payloads fail before page, sequence, or delivery admission\",\n \"new issue delivery failure closes the ledger and fences every outstanding outcome\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"assertions\": [\n \"negotiated exact reattach emits ready before replaying the unchanged unsettled command\",\n \"reattach before old cleanup preserves the same authority and ends only the superseded connection stream\",\n \"only the exact negotiated connection, paired device, and live page placement can settle a server-owned command\",\n \"exact duplicate results are idempotent while conflicts and stale or retired placement fail closed\",\n \"a second browser-host identity on one authenticated connection is rejected\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\n \"assertions\": [\n \"command result settlement requires the exact negotiated reconciliation authority\"\n ]\n },\n {\n \"file\": \"src/shared/browser/network/tunnels/browser-network-tunnel-protocol.test.ts\",\n \"assertions\": [\n \"remote DNS names round-trip without client resolution\",\n \"unknown versions, opcodes, oversized payloads, and length mismatches fail closed\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\n \"assertions\": [\n \"replenishes client credit only after the destination write settles\",\n \"keeps concurrent streams alive when late data arrives for a retired stream\",\n \"flushes credited destination bytes before close\",\n \"caps aggregate retained destination bytes and releases exact stream accounting\",\n \"caps unsettled destination writes and releases retirement exactly once\",\n \"releases queued bytes once when an accepted send closes reentrantly\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\n \"assertions\": [\n \"multiple execution-host routes share browser-host application-byte admission in both traffic directions\",\n \"route close releases aggregate claims exactly before stale destination-write callbacks\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\n \"assertions\": [\n \"preserves remote DNS and waits for an opened acknowledgement\",\n \"sends only credited bytes in bounded frames and replenishes consumed input\",\n \"ignores a retired stream frame but rejects a never-allocated stream ID\",\n \"never reuses stream IDs within one generation after its bounded ledger exhausts\",\n \"replenishes only bytes settled after the readable consumer takes them\",\n \"fails closed when pending tiny destination frames exceed the chunk cap\",\n \"drains data that precedes a remote close before retiring the socket\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\n \"assertions\": [\n \"application, encrypted-queue, and native socket bytes share one host ceiling\",\n \"distinct hosts share one process ceiling with exact release\",\n \"zero-byte claims, socket sources, hosts, and leases have independent bounds\",\n \"released leases cannot admit work and retained owners keep exact accounting alive\",\n \"unavailable native-buffer evidence fails closed until its exact source releases\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"assertions\": [\n \"domain CONNECT preserves the final execution-host DNS target\",\n \"unsupported commands and unavailable routes open no fallback destination\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\n \"assertions\": [\n \"ungranted or wrong-key SSH routes are rejected before resolver or binary registration\",\n \"connector diagnostics are mapped to a stable public error without local path disclosure\",\n \"grant revocation aborts connector startup immediately and cannot race through route admission\",\n \"the server allocates route generations and fences the replaced route\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\n \"assertions\": [\n \"closes a subscription that resolves after route teardown\",\n \"settles startup when close follows subscription acquisition before readiness\",\n \"bounds the post-auth readiness wait\",\n \"binds and releases the exact browser-host outbound memory lease\",\n \"keeps one listener fail-closed and accepts an increasing replacement generation\",\n \"ignores late callbacks from a superseded transport\",\n \"recovers again after a second transport death\",\n \"rejects a non-increasing replacement generation and remains retryable\",\n \"fences a ready generation even when the replacement closes before its await resumes\",\n \"replaces the tunnel generation before recycling a bounded stream ID\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\n \"assertions\": [\n \"destroy before source attachment emits one close and destroys a late source\",\n \"source close after destroy cannot emit duplicate wrapper close\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/execution-routes/browser-network-execution-route.test.ts\",\n \"assertions\": [\n \"execution-host route keys cannot collide on delimiter-containing identities\",\n \"native routing accepts only the exact runtime revision without retaining an invalidation callback\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\n \"assertions\": [\n \"does not adopt a replacement ssh2 client under the captured authority\",\n \"releases a deferred socket when forwardOut throws during disconnect\",\n \"aborts system SSH startup when route authorization is revoked\",\n \"reaches external sites over ssh2 through the host proxy and keeps local names direct\",\n \"dials directly while the host environment is unreadable and adopts it once a retry reads it\",\n \"reaches external sites over system SSH through the host proxy\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts\",\n \"assertions\": [\n \"the internal SOCKS5 client encodes the exact destination as a domain request\"\n ]\n },\n {\n \"file\": \"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\n \"assertions\": [\n \"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"\n ]\n },\n {\n \"file\": \"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"assertions\": [\n \"an ephemeral sshd resolves a container-only domain and returns a unique HTTP marker\",\n \"the real ssh2 forwardOut receives that exact domain and provider loss fences the route\",\n \"one non-interactive system-OpenSSH dynamic forward passes the same remote-only oracle and closes cleanly\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\n \"assertions\": [\n \"nested JSON responses route by exact request ID under reverse-order delivery\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"assertions\": [\n \"the authenticated socket binds the optional tunnel capability\",\n \"the dedicated outbound queue reports hard overflow instead of dropping a frame\",\n \"encrypted queue claims release synchronously while native socket ownership remains charged through exact close\"\n ]\n },\n {\n \"file\": \"src/shared/ws-outbound-backpressure-queue.test.ts\",\n \"assertions\": [\n \"direct and already-retained queued frames use distinct aggregate admission semantics\",\n \"queued drain yields after its configured frame quantum without reordering\",\n \"aggregate queue claims release on drain, denial, disposal, and close\"\n ]\n }\n ]", - "Test-value audit: Retire the paired-host late subscription smoke: it checks a mocked close count and startup rejection, without remote unsubscribe or successor outcomes. No equivalent replacement or fresh execution is claimed." + "Test-value audit: Retire the paired-host late subscription smoke: it checks a mocked close count and startup rejection, without remote unsubscribe or successor outcomes. No equivalent replacement or fresh execution is claimed.", + "Test-value audit3842 removes four authored/four finite outbound queue probes and the count80 row from each of three inbound queue declarations (zero extra authored removals, three extra finite removals). Direct fast-path failure, synthetic work quantum, injected aggregate callback accounting, supplied unwritable guard, and repeated eighty-payload alarms are accepted losses without equivalent replacement claims. Remaining inbound count8 cases retain actual WeakRef/GC and FIFO/rejection observations. All three unrelated dated gate receipts retain their original command/results/counts and are not fresh validation of changed sources." ], "demotionRule": "Keep experimental or demote if a self-asserted or ambiguous host can receive a route, an SSH descriptor bypasses capability, lease-bound grant, or provider-authority checks, late cleanup can remove a replacement, a route can resolve names on the desktop, exceed a byte or stream bound, replenish credit before destination settlement, accept a stale or non-increasing generation, reuse a stream ID within one generation, lose or bypass its fail-closed listener during reconnect, expose the SOCKS listener off-loopback, accept BIND/UDP, or fall back when the selected route is unavailable." }, @@ -5385,7 +5370,7 @@ "commands": [ "pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts", "SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/browser/network/execution-routes/browser-network-execution-route.test.ts src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.test.ts src/main/runtime/browser/network/runtime-browser-network-execution-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/cdp/screencast/browser-screencast-stream.test.ts src/main/runtime/browser/screencast/orca-runtime-browser-screencast-fanout.test.ts", @@ -5398,7 +5383,7 @@ "src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts", "src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts", "src/shared/remote-runtime/remote-runtime-client.test.ts", - "src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts", + "src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts", "tests/e2e/packaged-mixed-version-browser-placement.spec.ts", "src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts", "src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts", @@ -5791,12 +5776,12 @@ "providers": ["local", "daemon", "ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "remote-runtime"], - "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic host/parser, process-classifier, snapshot-publication, mixed-version, renderer, and macOS Electron coverage proves the local and shared paired-runtime contracts. Direct SSH intentionally publishes no shell proof and immediately preserves incumbent behavior. WSL, Windows ConPTY, Linux desktop, and paired headed/headless journeys remain gaps. The audit removed the isolated terminal-multiplex pending-escape-tail forwarding test. Its direct RPC snapshot field-copy alarm is lost; retained parser, snapshot and lifecycle suites do not establish equivalent RPC field coverage. Audit1320: src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts removed. Snapshot pending escape/alternate-screen/shell metadata forwarding and negative app-store-read alarm disappears. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/daemon/terminal-host-concurrent-create.test.ts reduced. Loses race deduplication, attach during unsettled ownership proof, retry after failed spawn, distinct-session parallelism, disposal waiting and shutdown retry-fencing alarms bundled with removed internal-call counts or real-time waits. No replacement-equivalence claim. src/main/daemon/terminal-checkpoint-serializer.test.ts reduced. Loses bounded native conversion/no-whole-candidate materialization and snapshot getter single-read alarms. Retained byte-size outcomes do not establish CPU/allocation bounds. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4345 deletes the foreground agent-process suite (8 authored cases): nested/stopped POSIX shells, recycled/query-denied Windows anchors and console-attachment filtering/refusal alarms are deliberately lost without equivalent replacement. Reduced selectors have no fresh gate execution; unrelated historical receipts retain their own commands. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3984 retires all nine mobile-presence and imported subscribe callbacks plus their orphan store fixture. Accepted losses include desktop/phone restore geometry, echo filtering, held reconnect/reclaim notifications, and the real headless snapshot sequence race. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic host/parser, process-classifier, snapshot-publication, mixed-version, renderer, and macOS Electron coverage proves the local and shared paired-runtime contracts. Direct SSH intentionally publishes no shell proof and immediately preserves incumbent behavior. WSL, Windows ConPTY, Linux desktop, and paired headed/headless journeys remain gaps. The audit removed the isolated terminal-multiplex pending-escape-tail forwarding test. Its direct RPC snapshot field-copy alarm is lost; retained parser, snapshot and lifecycle suites do not establish equivalent RPC field coverage. Audit1320: src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts removed. Snapshot pending escape/alternate-screen/shell metadata forwarding and negative app-store-read alarm disappears. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/daemon/terminal-host-concurrent-create.test.ts reduced. Loses race deduplication, attach during unsettled ownership proof, retry after failed spawn, distinct-session parallelism, disposal waiting and shutdown retry-fencing alarms bundled with removed internal-call counts or real-time waits. No replacement-equivalence claim. src/main/daemon/terminal-checkpoint-serializer.test.ts reduced. Loses bounded native conversion/no-whole-candidate materialization and snapshot getter single-read alarms. Retained byte-size outcomes do not establish CPU/allocation bounds. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/16379"], "invariant": "After a TUI exits or is killed, reveal, reattach, snapshot replay, or renderer remount must not deliver terminal-owned mouse or alternate-screen protocol bytes to the surviving shell. Recovery is an ordered output barrier in the daemon session data path: an OSC 133;D completing while the alternate screen is still active pauses the stream at that exact byte boundary, a fresh execution-host process inspection proves shell ownership, and on proof a mode reset is injected as in-stream output so every consumer converges by parsing the same bytes and the queued post-boundary shell output (the prompt) lands on the normal buffer. Snapshots are pure reads. Any failure — refuted proof, timeout, queue overflow, session death, disposal — flushes the queue unmodified, preserving incumbent behavior; later command or mode bytes revoke proof. Clean alternate-screen exits prove ownership asynchronously without pausing.", - "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Run one fixed child-TUI journey for normal exit and cleanup-free SIGKILL. Assert renderer and host normal-buffer/non-mouse state, host snapshot terminalOwner metadata, exact PTY writes with no post-exit mouse report, unrelated-pane survival, post-boundary prompt output preserved (normal exit), ordered proof invalidation, bounded settlement and bail-out flush, one inspection per unclean episode with zero scans for ordinary output, split-escape safety at every chunk boundary, and old/new client-host fallback parity.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Run one fixed child-TUI journey for normal exit and cleanup-free SIGKILL. Assert renderer and host normal-buffer/non-mouse state, host snapshot terminalOwner metadata, exact PTY writes with no post-exit mouse report, unrelated-pane survival, post-boundary prompt output preserved (normal exit), ordered proof invalidation, bounded settlement and bail-out flush, one inspection per unclean episode with zero scans for ordinary output, split-escape safety at every chunk boundary, and old/new client-host fallback parity.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/providers/agent-foreground-process.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/terminal/layout/mobile-presence-lock.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/runtime/construction/orca-runtime.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -5804,14 +5789,11 @@ "testFiles": [ "src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts", "src/main/daemon/sessions/testing/session-shell-recovery.test.ts", - "src/main/daemon/sessions/testing/session.test.ts", "src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts", "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", "src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts", "src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts", - "src/main/providers/agent-foreground-process.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", - "src/main/runtime/terminal/layout/mobile-presence-lock.test.ts", "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts", "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts", "tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts", @@ -5876,6 +5858,12 @@ "Keep missing-proof mixed-version behavior identical to the incumbent client path." ], "knownGaps": [ + "Audit4345 deletes the foreground agent-process suite (8 authored cases): nested/stopped POSIX shells, recycled/query-denied Windows anchors and console-attachment filtering/refusal alarms are deliberately lost without equivalent replacement. Reduced selectors have no fresh gate execution; unrelated historical receipts retain their own commands.", + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3984 retires all nine mobile-presence and imported subscribe callbacks plus their orphan store fixture. Accepted losses include desktop/phone restore geometry, echo filtering, held reconnect/reclaim notifications, and the real headless snapshot sequence race. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "NEXT65 current scope qualification: The NEXT65 knownGaps entries below govern the changed selectors and qualify any broader coverage implication in this gate’s unchanged oracle/coverageNotes narratives. Those narratives and preserved dated evidenceRuns retain their historical text and original exact execution scopes only; no fresh execution, transferred pass or equivalent replacement coverage is claimed. Upstream case removals remain upstream; original NEXT65 proposal descriptions grant no duplicate retirement credit.", "NEXT65 active selector scope reduction (including directory-selected whole-file retirements): src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts. Remove complete registrations or registrar files within the selected scope for src/renderer/src/components/terminal-pane/pty-connection/reattach/pty-connection-daemon-snapshot-replay.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode-2031-subscriptions.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/geometry/pty-connection-visibility-resume-size.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/reattach/pty-connection-stale-daemon-snapshot-replay.spec.ts. Intentionally lose these named regression alarms without replacement: catches a subscribed pane up once per mode change across repeated reconnects — Mode2031 theme reporting catch-up/deduplication across repeated reconnects loses this direct protocol example.; defers to the viewer holding the grid, then catches up once on release — Held-grid viewer deferral and one catch-up/current-mode resending on release lose this direct protocol example.; repairs grid drift with a trailing probe when output stops inside the settled interval — A trailing drift probe after the last output frame loses this direct alarm.; skips foreground grid drift repair while mobile owns the PTY without a fit override — Mobile driver ownership suppressing foreground drift repair without override loses this direct alarm.; reports desktop geometry without resizing while a mobile-fit override is active — Desktop geometry reporting without resizing a mobile-owned grid loses this direct alarm.; defers a remote-desktop viewport claim until structural replay completes — Remote-desktop viewport claim waiting for structural replay completion loses this direct alarm.; skips observed desktop reassertion while mobile owns the PTY without a fit override — Observed desktop reassertion suppression under mobile ownership loses this direct alarm.; queues re-asserted resizes while pane resize holds are active — Resize hold release flushing the latest reasserted grid loses this direct alarm.; reasserts a remote grid only when visible (%s) — Visible-only remote grid reassertion loses its visible and hidden examples.; claims a focused visible remote mirror once when its passive fit hold arrives — Focused visible passive mirror claiming once, with unfocused and late repeat suppression, loses this direct sequence alarm.; does NOT re-assert while a mobile-fit override parks the PTY at phone dims — Phone fit hold suppressing visibility-resume PTY reassertion loses this direct alarm.; does NOT forward when the pane is hidden again before getSize resolves (stale hop) — Late size lookup after re-hide refusing a hidden-tab SIGWINCH loses this direct adverse-ordering alarm.; clears the captured pen for a normal-buffer fallback reattach — Fallback normal-buffer reattach clearing captured pen and dirty background loses this direct example.; waits for a recovered destination fit before forwarding its grid or live output — Recovered destination fitting before forwarding grid or live output loses this direct example.; suppresses the deferred reattach grid push when mobile claims the PTY while hidden — Mobile takeover while hidden suppressing deferred reattach grid forwarding loses this direct example.; drops stale callbacks but delivers fresh replacement output after an old replay clear — Fresh replacement output winning over stale callbacks after old replay clear loses this direct example.. Surviving parent statements and sibling registrations are preserved, but these reduced parent selectors have no fresh execution or transferred historical pass. Unrelated complete dated receipts retain only their original exact scopes; no equivalent replacement, rendered UI, provider, mobile, or cross-platform coverage is claimed.", "NEXT65 historical original active parent-selector fields (verbatim native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/providers/agent-foreground-process.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/terminal/layout/mobile-presence-lock.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts\",\n \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"src/main/daemon/sessions/testing/session.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts\",\n \"src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts\",\n \"src/main/providers/agent-foreground-process.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/terminal/layout/mobile-presence-lock.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts\",\n \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"assertions\": [\n \"post-kill shell output survives into the normalized snapshot instead of the discarded alt buffer\",\n \"a snapshot taken during a split escape keeps the pending tail intact and stale proof is revoked by the completing bytes\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"assertions\": [\n \"the pending tail this gate threads over the wire folds identically at every code-unit split of the combined stream, including boundaries landing inside oscEsc/stringEsc\",\n \"the split sweep runs over an alphabet carrying CAN, SUB, doubled ESC inside OSC/DCS/SOS/PM/APC, BEL, C1 ST, NUL, DEL, intermediates, CJK, astral, and lone surrogates\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\",\n \"assertions\": [\n \"normal exit and cleanup-free SIGKILL both restore a visible clean shell marker\",\n \"renderer logical buffer is normal and mouse tracking is disabled after host-proven recovery\",\n \"real pointer input writes no SGR mouse report to the surviving shell\",\n \"an unrelated pane remains live\"\n ]\n }\n ]", @@ -5920,7 +5908,8 @@ "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/providers/agent-foreground-process.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/terminal/layout/mobile-presence-lock.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts\",\n \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"src/main/daemon/sessions/testing/session.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts\",\n \"src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts\",\n \"src/main/providers/agent-foreground-process.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/terminal/layout/mobile-presence-lock.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts\",\n \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"assertions\": [\n \"post-kill shell output survives into the normalized snapshot instead of the discarded alt buffer\",\n \"a snapshot taken during a split escape keeps the pending tail intact and stale proof is revoked by the completing bytes\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"assertions\": [\n \"the pending tail this gate threads over the wire folds identically at every code-unit split of the combined stream, including boundaries landing inside oscEsc/stringEsc\",\n \"the split sweep runs over an alphabet carrying CAN, SUB, doubled ESC inside OSC/DCS/SOS/PM/APC, BEL, C1 ST, NUL, DEL, intermediates, CJK, astral, and lone surrogates\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\",\n \"assertions\": [\n \"normal exit and cleanup-free SIGKILL both restore a visible clean shell marker\",\n \"renderer logical buffer is normal and mouse tracking is disabled after host-proven recovery\",\n \"real pointer input writes no SGR mouse report to the surviving shell\",\n \"an unrelated pane remains live\"\n ]\n }\n ]", - "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Keep experimental or demote if missing ownership proof changes incumbent behavior, a live TUI loses mouse/focus modes, foreground inspection enters ordinary output/reveal paths, or the focused Electron journey flakes without an identified product or harness fault." }, @@ -5942,35 +5931,32 @@ "providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon"], - "coverageNotes": "Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", + "coverageNotes": "Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/11757", "https://github.com/stablyai/orca/pull/11726" ], "invariant": "Within one terminal tab, each PTY has at most one layout leaf, pane manager surface, and xterm renderer owner. Restore and remote mirroring must normalize duplicate ownership before replay while retaining active-leaf focus, scrollback, pane authority, agent metadata, and distinct sibling PTYs.", - "oracle": "Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Component contracts cover persisted replay, rootless and repeated-leaf layouts, metadata repair, and deeply nested input. Retained store contracts cover live/future authority transfer onto a retained leaf and preservation of a prior detach destination.", + "oracle": "Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Component contracts cover persisted replay, rootless and repeated-leaf layouts, metadata repair, and deeply nested input. Retained store contracts cover live/future authority transfer onto a retained leaf and preservation of a prior detach destination.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ - "src/shared/workspace-layout/terminal-layout-pty-ownership-depth.test.ts", + "src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts", "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts", "src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts", "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts" ], "assertionRefs": [ { - "file": "src/shared/workspace-layout/terminal-layout-pty-ownership-depth.test.ts", + "file": "src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts", "assertions": ["prunes deeply nested duplicate ownership without recursive stack growth"] }, { "file": "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts", - "assertions": [ - "keeps the active leaf and prunes the stale surface plus its metadata", - "is idempotent and preserves one owner across PTY and focus permutations" - ] + "assertions": ["keeps the active leaf and prunes the stale surface plus its metadata"] }, { "file": "src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts", @@ -6178,7 +6164,7 @@ "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4327", "https://github.com/stablyai/orca/pull/14590", @@ -6187,12 +6173,12 @@ "https://github.com/stablyai/orca/issues/14524" ], "invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close commits durable tab retirement before PTY stop can publish graph loss, does not acknowledge before that retirement, and treats the later exit retirement as idempotent. Workspace-wide CLI close applies that same durable contract to every terminal in exactly one worktree, including pinned and persisted-only surfaces, without touching sibling-worktree PTYs or resume records. A persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.", - "oracle": "Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", + "oracle": "Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", + "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/agent-descendant-process-kill.spec.ts --workers=1", @@ -6205,10 +6191,9 @@ "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts", "src/main/ipc/agent-hooks.test.ts", "src/main/ipc/agent-pane-authority-ownership.test.ts", - "src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts", - "src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts", + "src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts", + "src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts", "src/main/pty/process-retirement/pty-descendant-termination.test.ts", - "src/main/daemon/sessions/testing/session.test.ts", "src/main/daemon/terminal-host/testing/terminal-host.test.ts", "src/main/providers/local-pty/local-pty-provider-shutdown.test.ts", "src/main/runtime/workspaces/removal/worktree-teardown.test.ts", @@ -6330,6 +6315,10 @@ "Add restart/no-resurrection and repeated park-close soak coverage." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. tests/e2e/automation-terminal-launch.unit.test.ts: launches explicit Chat for %s through the common entry and keeps its actual fallback; does not apply stored Terminal extras to Chat; forwards only complete Chat-consumed values, with no Terminal startup base; refuses an expired admission without minting another launch identity; records the actual chat identity and delegates new workspace setup and provenance. tests/e2e/github-project-provider-columns.unit.test.ts: renders %s through one bounded items request on a named cloud host; preserves zero and complete counters: %j; preserves populated and legacy rows through shared sorting, grouping and cells. tests/e2e/structured-agent-session-launch-continuation.unit.test.ts: carries renderer lifetime through host intent to the real %s provider builders. tests/e2e/terminal-account-restart.unit.test.ts: replaces a tombstoned owner while its persisted pane binding has not yet been cleared; paired restart retains the old owner (host authority: %s). tests/e2e/terminal-hidden-view-parking.spec.ts: does not park excluded tabs; reproduces a static frame byte-for-byte across 25 park/reveal cycles. tests/e2e/terminal-long-table-scroll-restore.spec.ts: reproduces long markdown table artifacts after workspace switch and scroll; keeps narrow wrapped signer markdown table coherent after restore and scroll; keeps real emoji markdown table right edge clean after restore and scroll. tests/e2e/terminal-long-table-fixtures.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-paste-ownership.spec.ts: Windows multiline keyboard paste normalizes terminal newlines with one PTY owner; right-click paste sends clipboard text to the focused terminal exactly once. tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts: uses WebGL by default for ordinary terminal output when available @terminal-rendering-golden. tests/e2e/terminal-windows-shell-paste-ownership.spec.ts: cmd.exe default terminal keyboard paste preserves exact content with one PTY owner; Git Bash default terminal keyboard paste preserves POSIX-shaped content with one PTY owner; WSL terminal keyboard paste preserves Linux shell content with one PTY owner. tests/e2e/workspace-board-lane-virtualization.spec.ts: mounts a window of cards for a large lane and keeps lane indexes; renders later lane indexes after the lane scrolls. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts, tests/e2e/automation-terminal-launch.unit.test.ts, tests/e2e/github-project-provider-columns.unit.test.ts, tests/e2e/structured-agent-session-launch-continuation.unit.test.ts, tests/e2e/terminal-account-restart.unit.test.ts, tests/e2e/terminal-hidden-view-parking.spec.ts, tests/e2e/terminal-long-table-scroll-restore.spec.ts, tests/e2e/terminal-long-table-fixtures.ts, tests/e2e/terminal-paste-ownership.spec.ts, tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts, tests/e2e/terminal-windows-shell-paste-ownership.spec.ts, tests/e2e/workspace-board-lane-virtualization.spec.ts. Unresolved local/computed edges remain explicit debt. Complete dated receipts with direct selectors or current literal graph reaching tests/e2e/automation-terminal-launch.unit.test.ts, tests/e2e/github-project-provider-columns.unit.test.ts, tests/e2e/structured-agent-session-launch-continuation.unit.test.ts, tests/e2e/terminal-account-restart.unit.test.ts, tests/e2e/terminal-hidden-view-parking.spec.ts, tests/e2e/terminal-long-table-scroll-restore.spec.ts, tests/e2e/terminal-long-table-fixtures.ts, tests/e2e/terminal-paste-ownership.spec.ts, tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts, tests/e2e/terminal-windows-shell-paste-ownership.spec.ts, tests/e2e/workspace-board-lane-virtualization.spec.ts are retired below as historical raw objects; their counts do not validate reduced commands. Historical retired receipt verbatim:\n{\n \"date\": \"2026-07-13\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 40.3,\n \"summary\": \"A fresh E2E build launched an isolated Electron profile, parked a live terminal, closed it through closeTab, and observed its exact PTY disappear.\"\n } Historical retired receipt verbatim:\n{\n \"date\": \"2026-07-14\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e -- tests/e2e/agent-descendant-process-kill.spec.ts --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 37.7,\n \"summary\": \"A current-main integrated fresh-build run proved a detached-pgid child was alive before agent PTY kill and absent afterward on the deadline-safe, root-ownership-gated implementation.\"\n } Historical retired receipt verbatim:\n{\n \"date\": \"2026-07-15\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e -- tests/e2e/agent-descendant-process-kill.spec.ts --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 78,\n \"summary\": \"The cycle-safe, target-indexed, bounded-fanout review head passed from a cold full build; the live detached-pgid descendant test body completed in 4.8 seconds.\"\n } Historical retired receipt verbatim:\n{\n \"date\": \"2026-08-14\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 18.8,\n \"summary\": \"A fresh isolated Electron profile closed a split terminal tab through the runtime CLI and kept both renderer and runtime terminal inventories empty after restart.\"\n }", @@ -6372,7 +6361,8 @@ "Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. All prior notes and dated/archived evidence retain original scopes.", "Audit3437 complete prior commands before completed-worker-retirement-resume retirement: [\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1\",\"pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1\",\"pnpm run test:e2e -- tests/e2e/agent-descendant-process-kill.spec.ts --workers=1\",\"pnpm run test:e2e -- tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts --workers=1\",\"pnpm run test:e2e -- tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts --workers=1\"]", "Audit3437 complete prior testFiles before completed-worker-retirement-resume retirement: [\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts\",\"src/main/ipc/agent-hooks.test.ts\",\"src/main/ipc/agent-pane-authority-ownership.test.ts\",\"src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts\",\"src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts\",\"src/main/pty/process-retirement/pty-descendant-termination.test.ts\",\"src/main/daemon/sessions/testing/session.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/providers/local-pty/local-pty-provider-shutdown.test.ts\",\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts\",\"src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts\",\"src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts\",\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\"tests/e2e/terminal-parked-close-retirement.spec.ts\",\"tests/e2e/agent-descendant-process-kill.spec.ts\",\"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\"]", - "Audit3437 complete prior assertionRefs before completed-worker-retirement-resume retirement: [{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"assertions\":[\"final-pane terminal.close remains pending until one renderer durability acknowledgement retires the persisted tab and layout\",\"final-pane externally owned teardown commits session retirement before PTY stop, tolerates duplicate exit retirement, and preserves an unrelated live canary\",\"post-ack workspace-session loss falls back to renderer cleanup and verified PTY teardown while every pre-ack retirement error remains non-destructive\",\"renderer reload with the same provider-attested PTY incarnation preserves the exact handle\",\"same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale\",\"hard graph loss and preallocated-handle supersession make the retained renderer handle deterministically stale\"]},{\"file\":\"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\"assertions\":[\"a durability-acknowledged whole-tab close leaves zero terminal tabs and provider sessions after restart\"]},{\"file\":\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"assertions\":[\"explicit close revokes the exact live recovery record both before and after PTY exit removes the tab, while PTY exit alone preserves interrupted-session recovery\"]},{\"file\":\"tests/e2e/terminal-parked-close-retirement.spec.ts\",\"assertions\":[\"a long-lived exact PTY remains alive after its terminal view is parked\",\"closing the parked tab removes the exact PTY from the provider inventory and the visible tab model\"]},{\"file\":\"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\"assertions\":[\"an attached-window desktop host publishes the CLI-created terminal under the renderer publication epoch it inherits, proving the vulnerable classification path was taken rather than a headless or serve/SSH-shaped one\",\"with the target as the first host-created terminal, a renderer graph sync leaves the `terminal.create` tab in the host session inventory still naming its original daemon PTY\",\"the original fixture process answers a write through that handle with its own pid and a single READY line, so a respawned replacement cannot pass as a survivor\",\"the paired client applied that same sync and kept the tab with no replacement or resume tab appended\",\"an unrelated workspace keeps its own CLI terminal and PTY, and the client raises no direct local connection attempt or uncaught renderer error\"]},{\"file\":\"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\",\"assertions\":[\"a windowless serve host publishes host-created terminals under a headless epoch, never a renderer one, which is why it cannot reach the window-conditioned prune the desktop arm reproduces\",\"a later CLI dispatch leaves the earlier host-created terminal in the serve-host inventory still bound to its original PTY\",\"both original fixture processes answer writes through their own handles after the later dispatch\",\"the paired client mirrors exactly those two tabs with no replacement or resume tab appended, no direct local connection attempt, and no uncaught renderer error\"]},{\"file\":\"src/main/ipc/agent-pane-authority-ownership.test.ts\",\"assertions\":[\"pane authority transfer accepts only the canonical legacy/scoped runtime handle bound to the authoritative pane\"]},{\"file\":\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"assertions\":[\"owned provider shutdowns start together so process-table snapshots can coalesce within a batch\",\"inventories above 32 sessions never exceed 32 concurrent provider shutdowns\"]},{\"file\":\"tests/e2e/agent-descendant-process-kill.spec.ts\",\"assertions\":[\"a detached-pgid descendant is alive before agent PTY kill and absent afterward\"]}]" + "Audit3437 complete prior assertionRefs before completed-worker-retirement-resume retirement: [{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"assertions\":[\"final-pane terminal.close remains pending until one renderer durability acknowledgement retires the persisted tab and layout\",\"final-pane externally owned teardown commits session retirement before PTY stop, tolerates duplicate exit retirement, and preserves an unrelated live canary\",\"post-ack workspace-session loss falls back to renderer cleanup and verified PTY teardown while every pre-ack retirement error remains non-destructive\",\"renderer reload with the same provider-attested PTY incarnation preserves the exact handle\",\"same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale\",\"hard graph loss and preallocated-handle supersession make the retained renderer handle deterministically stale\"]},{\"file\":\"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\"assertions\":[\"a durability-acknowledged whole-tab close leaves zero terminal tabs and provider sessions after restart\"]},{\"file\":\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"assertions\":[\"explicit close revokes the exact live recovery record both before and after PTY exit removes the tab, while PTY exit alone preserves interrupted-session recovery\"]},{\"file\":\"tests/e2e/terminal-parked-close-retirement.spec.ts\",\"assertions\":[\"a long-lived exact PTY remains alive after its terminal view is parked\",\"closing the parked tab removes the exact PTY from the provider inventory and the visible tab model\"]},{\"file\":\"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\"assertions\":[\"an attached-window desktop host publishes the CLI-created terminal under the renderer publication epoch it inherits, proving the vulnerable classification path was taken rather than a headless or serve/SSH-shaped one\",\"with the target as the first host-created terminal, a renderer graph sync leaves the `terminal.create` tab in the host session inventory still naming its original daemon PTY\",\"the original fixture process answers a write through that handle with its own pid and a single READY line, so a respawned replacement cannot pass as a survivor\",\"the paired client applied that same sync and kept the tab with no replacement or resume tab appended\",\"an unrelated workspace keeps its own CLI terminal and PTY, and the client raises no direct local connection attempt or uncaught renderer error\"]},{\"file\":\"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\",\"assertions\":[\"a windowless serve host publishes host-created terminals under a headless epoch, never a renderer one, which is why it cannot reach the window-conditioned prune the desktop arm reproduces\",\"a later CLI dispatch leaves the earlier host-created terminal in the serve-host inventory still bound to its original PTY\",\"both original fixture processes answer writes through their own handles after the later dispatch\",\"the paired client mirrors exactly those two tabs with no replacement or resume tab appended, no direct local connection attempt, and no uncaught renderer error\"]},{\"file\":\"src/main/ipc/agent-pane-authority-ownership.test.ts\",\"assertions\":[\"pane authority transfer accepts only the canonical legacy/scoped runtime handle bound to the authoritative pane\"]},{\"file\":\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"assertions\":[\"owned provider shutdowns start together so process-table snapshots can coalesce within a batch\",\"inventories above 32 sessions never exceed 32 concurrent provider shutdowns\"]},{\"file\":\"tests/e2e/agent-descendant-process-kill.spec.ts\",\"assertions\":[\"a detached-pgid descendant is alive before agent PTY kill and absent afterward\"]}]", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Keep experimental or demote to protection none if exact PTY disappearance flakes, a sibling/detached pane is retired, late hooks can recreate closed authority, or a renderer graph sync retires a host-created tab that no explicit close retired." }, @@ -6394,7 +6384,7 @@ "providers": ["daemon", "runtime", "ssh", "wsl"], "coveredPlatforms": ["linux", "macos", "windows"], "coveredProviders": ["daemon", "runtime"], - "coverageNotes": "Git owner cleanup retires the mixed request-connection suite under repository test policy, including its encrypted request cancellation and cached paired-desktop authentication alarms, without equivalent replacement. Current commands and assertion references omit the retired suite; dated evidence retains its original scope and does not validate this reduced set. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2153: Reduced sources intentionally lose the forwarding smoke and retire an unrelated current selector; historical runs do not validate changed source bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The browser auth capability-advertisement case is removed in this audit; its direct encrypted-auth literal alarm is lost. Retained lifecycle evidence is not an equivalent replacement. Historical run commands and results remain historical. Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage. The isolated close-intent suite was removed. web-runtime-session.test.ts no longer supplies the lifecycle-close or old-server method-not-found assertions formerly referenced here. Their direct partition and RPC-shape alarms are lost; retained live daemon evidence does not establish equivalent coverage. The broad mirror fixture retains user-close suppression, refused-close reconciliation and optimistic reorder only. Its earlier reconnect/incarnation and projection examples no longer establish current daemon-generation coverage. Those narrow alarms are lost; other daemon evidence is not equivalent replacement coverage. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): Git owner cleanup retires the mixed request-connection suite under repository test policy, including its encrypted request cancellation and cached paired-desktop authentication alarms, without equivalent replacement. Current commands and assertion references omit the retired suite; dated evidence retains its original scope and does not validate this reduced set. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2153: Reduced sources intentionally lose the forwarding smoke and retire an unrelated current selector; historical runs do not validate changed source bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The browser auth capability-advertisement case is removed in this audit; its direct encrypted-auth literal alarm is lost. Retained lifecycle evidence is not an equivalent replacement. Historical run commands and results remain historical. Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage. The isolated close-intent suite was removed. web-runtime-session.test.ts no longer supplies the lifecycle-close or old-server method-not-found assertions formerly referenced here. Their direct partition and RPC-shape alarms are lost; retained live daemon evidence does not establish equivalent coverage. The broad mirror fixture retains user-close suppression, refused-close reconciliation and optimistic reorder only. Its earlier reconnect/incarnation and projection examples no longer establish current daemon-generation coverage. Those narrow alarms are lost; other daemon evidence is not equivalent replacement coverage. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/9749", "https://github.com/stablyai/orca/issues/9949", @@ -6403,23 +6393,18 @@ "https://github.com/stablyai/orca/issues/9229" ], "invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.", - "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3774 (independent peer expansion of3773): deliberately retire7authored/13potential expanded registrations across4whole suites: standalone truncated8-byte E2EE guard; open/empty readiness null fast-path; capability parser acceptance/atomic malformed-array bounds; phone/delegated-parent/desktop/in-process creator provenance projections. These are real guard/policy alarms accepted as low marginal value, not tautologies. No equivalent replacement, authenticated-refusal, observer delivery, persisted visibility, synchronous scheduling or fresh execution is claimed. Prior dated receipts retain their exact original scopes and do not validate the changed/reduced current selector. Independent daemon E2E receipts remain scoped to their own unchanged commands. Historical prior account (preserved verbatim): Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back. Audit4587 retires the one-case CLI WebSocket protocol/preflight suite and its hand-built server; its cross-layer non-delivery witness is intentionally lost, with no replacement coverage claimed.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "src/main/runtime/construction/orca-runtime.test.ts", - "src/main/runtime/rpc/e2ee-channel.test.ts", - "src/main/runtime/rpc/e2ee-channel-v2.test.ts", - "src/main/runtime/rpc/mobile-socket-wiring.test.ts", - "src/main/runtime/rpc/runtime-client-capabilities.test.ts", + "src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts", "src/shared/remote-runtime/remote-runtime-client.test.ts", "src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", - "src/cli/runtime/websocket-transport.test.ts", "src/renderer/src/web/web-runtime-client.test.ts", - "src/renderer/src/components/terminal/terminal-tab-actions.test.ts", "src/renderer/src/components/terminal/terminal-close-incarnation.test.ts", "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", "tests/e2e/daemon-generation-reconnect-safety.spec.ts", @@ -6444,16 +6429,6 @@ "shutdown-dispose-failed drops named-pipe authority within the deadline and exact fixture cleanup leaves no process tree" ] }, - { - "file": "src/main/runtime/rpc/e2ee-channel-v2.test.ts", - "assertions": ["mobile E2EE v2 continues to reject additive runtime capability metadata"] - }, - { - "file": "src/main/runtime/rpc/runtime-client-capabilities.test.ts", - "assertions": [ - "the authenticated capability parser accepts only bounded string arrays and rejects malformed or oversized input" - ] - }, { "file": "src/shared/remote-runtime/remote-runtime-client.test.ts", "assertions": [ @@ -6505,6 +6480,10 @@ "Add live Linux SSH-relay and Windows WSL reconnect artifacts without weakening keep-on-unknown." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -6547,7 +6526,13 @@ "Audit2153 historical original testFiles item, preserved verbatim; retired selector is not active execution evidence: \"src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts\"", "Terminal/runtime defining-owner cleanup retires complete parking timer, lifecycle, mocked close/disposal and render/flip/mount work-count cases under repository test policy. The retained watcher source has only two literal-oracle coverage decisions; the retained cold-parking hook source has only the layout-PTY exemption invalidation case. Lost alarms include cooldown/measure/pin wakeups, split exit/close attribution and cancellation, watcher disposal/restart, flood timer rearm, worktree verdict damping, and destroyed-transport cold restore. No equivalent replacement coverage or execution pass for the reduced cases is claimed; prior dated receipts retain their original scope.", "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", - "Git owner cleanup retires the mixed request-connection suite under repository test policy, including its encrypted request cancellation and cached paired-desktop authentication alarms, without equivalent replacement. Current commands and assertion references omit the retired suite; dated evidence retains its original scope and does not validate this reduced set." + "Git owner cleanup retires the mixed request-connection suite under repository test policy, including its encrypted request cancellation and cached paired-desktop authentication alarms, without equivalent replacement. Current commands and assertion references omit the retired suite; dated evidence retains its original scope and does not validate this reduced set.", + "Audit3774 (independent peer expansion of3773): deliberately retire7authored/13potential expanded registrations across4whole suites: standalone truncated8-byte E2EE guard; open/empty readiness null fast-path; capability parser acceptance/atomic malformed-array bounds; phone/delegated-parent/desktop/in-process creator provenance projections. These are real guard/policy alarms accepted as low marginal value, not tautologies. No equivalent replacement, authenticated-refusal, observer delivery, persisted visibility, synchronous scheduling or fresh execution is claimed. Prior dated receipts retain their exact original scopes and do not validate the changed/reduced current selector. Independent daemon E2E receipts remain scoped to their own unchanged commands.", + "Audit3774 historical original active selector/assertion arrays, preserved verbatim; no replacement coverage claim.\ncommands:\n[\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile/mobile-socket-wiring.test.ts src/main/runtime/rpc/callers/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles:\n[\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel.test.ts\",\n \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts\",\n \"src/main/runtime/rpc/mobile/mobile-socket-wiring.test.ts\",\n \"src/main/runtime/rpc/callers/runtime-client-capabilities.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/cli/runtime/websocket-transport.test.ts\",\n \"src/renderer/src/web/web-runtime-client.test.ts\",\n \"src/renderer/src/components/terminal/terminal-tab-actions.test.ts\",\n \"src/renderer/src/components/terminal/terminal-close-incarnation.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"tests/e2e/daemon-generation-reconnect-safety.spec.ts\",\n \"tests/e2e/daemon-generation-legacy-close-safety.spec.ts\"\n ]\nassertionRefs:\n[\n {\n \"file\": \"tests/e2e/daemon-generation-legacy-close-safety.spec.ts\",\n \"assertions\": [\n \"one identified capable viewer and one legacy viewer issue byte-identical sequential reasonless closes while a third viewer lists every target before, between, and after but issues zero closes\",\n \"capable v25/v26 PTY root/descendant incarnations in separate worktrees survive, answer post-close input, and produce zero shutdown calls and zero daemon session-killed events\",\n \"legacy v25/v26 PTY root/descendant incarnations die through ordered immediate shutdown calls with one daemon session-killed event each, matching current-main behavior\",\n \"an unaddressed fifth-worktree PTY root and descendant survive with zero kill events, excluding global fanout\",\n \"the JSON reconstruction records request order, negotiated capabilities, viewer connection, worktree/tab/PTY ids, daemon PID/protocol, call site, and exact before/after process liveness\"\n ]\n },\n {\n \"file\": \"tests/e2e/daemon-generation-reconnect-safety.spec.ts\",\n \"assertions\": [\n \"the production scanner discovers v21/v22/v23/v24/v25 from v26 and every generation accepts repeated client hellos while every exact daemon, PTY-root, and descendant incarnation remains alive\",\n \"desktop and two remote profiles repeat lifecycle closes before and after client relaunch with zero session-killed events\",\n \"shutdown-dispose-failed drops named-pipe authority within the deadline and exact fixture cleanup leaves no process tree\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts\",\n \"assertions\": [\"mobile E2EE v2 continues to reject additive runtime capability metadata\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/callers/runtime-client-capabilities.test.ts\",\n \"assertions\": [\n \"the authenticated capability parser accepts only bounded string arrays and rejects malformed or oversized input\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"assertions\": [\n \"one-shot and subscription runtime clients remain compatible while sending encrypted client authentication\"\n ]\n }\n ]", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed.", + "Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope.", + "Audit3881 historical original selector/assertion arrays, preserved verbatim; retired entries are not active execution evidence or replacement coverage.\ncommands:\n[\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile/mobile-socket-wiring.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles:\n[\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel.test.ts\",\n \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts\",\n \"src/main/runtime/rpc/mobile/mobile-socket-wiring.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/cli/runtime/websocket-transport.test.ts\",\n \"src/renderer/src/web/web-runtime-client.test.ts\",\n \"src/renderer/src/components/terminal/terminal-tab-actions.test.ts\",\n \"src/renderer/src/components/terminal/terminal-close-incarnation.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"tests/e2e/daemon-generation-reconnect-safety.spec.ts\",\n \"tests/e2e/daemon-generation-legacy-close-safety.spec.ts\"\n ]\nassertionRefs:\n[\n {\n \"file\": \"tests/e2e/daemon-generation-legacy-close-safety.spec.ts\",\n \"assertions\": [\n \"one identified capable viewer and one legacy viewer issue byte-identical sequential reasonless closes while a third viewer lists every target before, between, and after but issues zero closes\",\n \"capable v25/v26 PTY root/descendant incarnations in separate worktrees survive, answer post-close input, and produce zero shutdown calls and zero daemon session-killed events\",\n \"legacy v25/v26 PTY root/descendant incarnations die through ordered immediate shutdown calls with one daemon session-killed event each, matching current-main behavior\",\n \"an unaddressed fifth-worktree PTY root and descendant survive with zero kill events, excluding global fanout\",\n \"the JSON reconstruction records request order, negotiated capabilities, viewer connection, worktree/tab/PTY ids, daemon PID/protocol, call site, and exact before/after process liveness\"\n ]\n },\n {\n \"file\": \"tests/e2e/daemon-generation-reconnect-safety.spec.ts\",\n \"assertions\": [\n \"the production scanner discovers v21/v22/v23/v24/v25 from v26 and every generation accepts repeated client hellos while every exact daemon, PTY-root, and descendant incarnation remains alive\",\n \"desktop and two remote profiles repeat lifecycle closes before and after client relaunch with zero session-killed events\",\n \"shutdown-dispose-failed drops named-pipe authority within the deadline and exact fixture cleanup leaves no process tree\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts\",\n \"assertions\": [\"mobile E2EE v2 continues to reject additive runtime capability metadata\"]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"assertions\": [\n \"one-shot and subscription runtime clients remain compatible while sending encrypted client authentication\"\n ]\n }\n ]", + "Audit4389 retires the entire terminal-tab-actions mock-projection suite (8 authored/10 finite cases). Real local/host mutation, confirmation settlement and transport are mocked; routing/reason/pin/sibling spy alarms intentionally lost, with no replacement or equivalence claim. Historical entries remain archival only. Original active command: pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts" ], "demotionRule": "Keep experimental or quarantine if reconnect emits session-killed for a live canary, an exact root/descendant dies, an old server receives fallback destructive close, cleanup leaks a fixture process/pipe, or the gate flakes without a proven harness defect." }, @@ -7053,7 +7038,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coverageNotes": "Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4352 deletes the whole mocked daemon router, session-owner resolver, degraded-provider, terminal-host CWD-readability and foreground-inspection suites plus the native-process-CWD fixture suite; recovery retains only public multi-pane proactive socket-death notification/remount. Intentionally lose retirement admission, stale-inventory/fenced-kill authority, attach-only re-resolution/absence, fast-exit routing, sleep CWD checkpoint/wake, diagnostic cancellation/shutdown and foreground census/session-change alarms. No equivalent replacement or fresh gate execution is claimed. Historical prior account (preserved verbatim): Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8878", "https://github.com/stablyai/orca/issues/9151", @@ -7063,7 +7048,7 @@ "https://github.com/stablyai/orca/pull/10193" ], "invariant": "For every claim-capable execution route, one provider-session identity has at most one live PTY owner and one canonical host surface across concurrent clients, retries, reconnects, and stale publications. For paired structured fresh and resume requests, the authenticated owning runtime creates in background without a renderer window; activate=true focuses the exact requested leaf only on the requesting viewer, while activate=false changes no viewer focus. A live orphan may be adopted only when the controller proves its exact handle and incarnation, its worktree and host owner match, no competing visual owner exists, and a host topology CAS wins. A viewer may classify completion only from successful host/provider inspection or explicit lifecycle evidence; transport, handle, or provider unavailability remains unknown and breaks any consecutive-idle proof. A physical exit retires that exact incarnation durably so stale client state and host restart cannot recreate it. Mixed-version routes select the unchanged legacy request before any authority side effect or execution-owner-local filesystem access.", - "oracle": "Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", @@ -7075,13 +7060,11 @@ "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", "Manual headed paired-server journey: isolated Orca desktop host + separate paired web client + real Codex process + 20-second WebSocket fault + reconnect + explicit stop", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts" + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts" ], "testFiles": [ "src/main/daemon/terminal-host/testing/terminal-host.test.ts", - "src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts", - "src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "tests/e2e/remote-agent-completion-authority.unit.test.ts", "src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts", @@ -7101,12 +7084,6 @@ "src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts" ], "assertionRefs": [ - { - "file": "src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts", - "assertions": [ - "completion inspection rejects an unmapped session instead of borrowing the local fallback" - ] - }, { "file": "tests/e2e/remote-agent-completion-authority.unit.test.ts", "assertions": [ @@ -7260,6 +7237,12 @@ "Add live SSH/WSL provider evidence before claiming full provider coverage; Docker SSH proves only the SSH provider/relay path." ], "knownGaps": [ + "Audit4352 deletes the whole mocked daemon router, session-owner resolver, degraded-provider, terminal-host CWD-readability and foreground-inspection suites plus the native-process-CWD fixture suite; recovery retains only public multi-pane proactive socket-death notification/remount. Intentionally lose retirement admission, stale-inventory/fenced-kill authority, attach-only re-resolution/absence, fast-exit routing, sleep CWD checkpoint/wake, diagnostic cancellation/shutdown and foreground census/session-change alarms. No equivalent replacement or fresh gate execution is claimed.", + "Audit4352 original affected selector fields before exact deleted paths were pruned: {\"commands\": [\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\", \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\"], \"testFiles\": [\"src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts\", \"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\"], \"assertionRefs\": [{\"file\": \"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\", \"assertions\": [\"completion inspection rejects an unmapped session instead of borrowing the local fallback\"]}]}", + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2694 intentional coverage losses (source-only, no replacement): src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts: 'drops the command-finished status when pending interrupt inference is rejected': Loses the standalone rejected-inference-to-drop alarm; the delayed-write rows remain but are not equivalent to this immediate rejection example. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts: 'forwards raw onData after a bell as a query reply': Loses raw onData forwarding after the manually raised bell, including its hibernation-counter expectations. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts: 'blocks onData on a stale codex pane': The real isCodexPaneStale guard executes, and removing it would allow the typed a to reach transport. Intentionally loses this genuine stale-account typing refusal alarm. No retained query-reply test is claimed equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'omits byte-parser callbacks from the local transport options': Loses local main-authority callback omission and lifecycle callback presence checks. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'keeps byte-parser callbacks on remote-runtime transports': Loses remote-runtime parser callback preservation and factory-argument alarm, including this compatibility boundary; no mixed-version execution is covered. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'consumes pty:sideEffect facts with the live-path policy after spawn': Loses title/bell fact routing and exact 250ms delayed fake notification example. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'schedules the completion notification for genuine working→idle facts': Loses positive main-fact working-to-idle scheduling alarm. Retained stale/race cases do not replace this positive example. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'drops the agent status from a command-finished fact like the byte path did': Loses command-finished fact-to-drop routing and removeAgentStatus noncall alarm. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'routes pr-link facts to the worktree PR observer': Loses PR-link fact forwarding, worktree/tab/PTY arguments alarm; retained raw-byte nonconsumption is not equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'seeds and settles Command Code status from command-code facts': Real Command Code seed/settle policy runs. Loses positive seed, prompt payload, and 1499+1ms completion boundary alarm; retained newer-working cancellation is not equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'does not byte-scan Command Code output — facts are the only consumer': Loses Command Code-specific no-byte-parser alarm. Retained PR/OSC raw-byte exclusion does not cover this parser. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts: 'shares one raw store subscriber for agent-complete notification settings across panes': Actual shared subscribe/unsubscribe runs. Loses shared single-subscription and final-pane unsubscribe lifetime alarm, with no replacement claimed. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts: 'dispatches agent-task-complete for generic Codex spinner titles after process identity is confirmed': Real coordinator evidence path runs over fake process answers. Loses positive generic-title/confirmed-Codex completion and inspectProcess-argument alarm. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts: 'normalizes Pi-compatible remote titles to authoritative OMP launch identity': Real owner-compatible normalization runs. Loses Pi-to-OMP title/status normalization, active tab label, OSC observation, and retained launch-identity example; no real remote transport or equivalent replacement. Wrapper cleanup removes only the deleted bell factory import and its registration-only describe block; no additional authored removal credit. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -7325,7 +7308,8 @@ "Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Earlier notes and dated/archived evidence retain original scopes.", "Complete prior commands before exact deleted selectors were pruned: [\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"pnpm run build:cli && pnpm run build:electron-vite && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"node --check config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"pnpm exec electron-vite build --mode e2e\",\"VITE_EXPOSE_STORE=true pnpm run build:web\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\"Manual headed paired-server journey: isolated Orca desktop host + separate paired web client + real Codex process + 20-second WebSocket fault + reconnect + explicit stop\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts\"]", "Complete prior testFiles before exact deleted selectors were pruned: [\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts\",\"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\"src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts\",\"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\",\"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts\",\"src/shared/claimed-agent-pty-owner.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts\",\"src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts\",\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\"tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\",\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\"]", - "Complete prior assertionRefs before exact deleted selectors were pruned: [{\"file\":\"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\",\"assertions\":[\"completion inspection rejects an unmapped session instead of borrowing the local fallback\"]},{\"file\":\"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\"assertions\":[\"transport loss remains unknown through reconnect and cannot dispatch completion\",\"returned unavailability or a thrown transport failure interrupts consecutive-idle proof and requires two fresh authoritative idle samples\",\"explicit stop, real exit status, and genuine successful completion remain distinct\"]},{\"file\":\"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts\",\"assertions\":[\"one unreachable pane cannot suppress restart notices for another authoritatively confirmed Codex pane\"]},{\"file\":\"src/shared/claimed-agent-pty-owner.test.ts\",\"assertions\":[\"concurrent exact claims spawn once and later callers adopt the canonical owner\",\"same identity in another worktree conflicts and cannot be found as the current scope's owner\",\"generation-guarded exit and authoritative reconciliation cannot retire a replacement owner\"]},{\"file\":\"src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts\",\"assertions\":[\"independent runtime clients converge on one canonical live agent-session owner\",\"retries and concurrent requests cannot create a second physical PTY\"]},{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"assertions\":[\"an exact PTY exit retires host membership and stale topology cannot recreate the surface\",\"incarnation fencing prevents an old delayed exit from retiring a replacement PTY\"]},{\"file\":\"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\"assertions\":[\"headed desktop host remains unfocused while the paired requester alone follows active fresh/resume sessions and inactive rows preserve exact client/DOM focus\",\"legacy afterTabId placement is exact in authoritative, mirrored, and rendered order with a pre-existing successor\",\"host PTY inventory plus writable agent/unrelated shell markers prove liveness, unrelated survival, and exact terminal/tab/PTY/process cleanup\"]},{\"file\":\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"assertions\":[\"headless focused fresh/resume requests create background host surfaces without a renderer window\",\"dropped committed responses replay the same operation identity without another tokened agent spawn\",\"exact terminal/tab/process identity survives retries and stale-write rejection, then retires without restart resurrection while unrelated shells survive until scoped cleanup\"]},{\"file\":\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\"assertions\":[\"isolated daemon roots and captured descendants are verified dead before profile PID records are removed\"]},{\"file\":\"tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"assertions\":[\"a durable host exit removes the terminal from two independent viewer mirrors instead of publishing a handle-less phantom\",\"one exact exit produces one same-epoch higher-version host publication and one durable persistence flush\",\"same-epoch stale publications cannot resurrect the retired surface after reconnect\"]},{\"file\":\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\"assertions\":[\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\",\"retains exact-leaf focus intent when a split sibling publishes first\"]},{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\",\"assertions\":[\"mirrors a new CLI tab after old-host recovery when $name\"]},{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"assertions\":[\"serializes a newer convergence snapshot after an in-flight adoption conflict\"]}]" + "Complete prior assertionRefs before exact deleted selectors were pruned: [{\"file\":\"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\",\"assertions\":[\"completion inspection rejects an unmapped session instead of borrowing the local fallback\"]},{\"file\":\"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\"assertions\":[\"transport loss remains unknown through reconnect and cannot dispatch completion\",\"returned unavailability or a thrown transport failure interrupts consecutive-idle proof and requires two fresh authoritative idle samples\",\"explicit stop, real exit status, and genuine successful completion remain distinct\"]},{\"file\":\"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts\",\"assertions\":[\"one unreachable pane cannot suppress restart notices for another authoritatively confirmed Codex pane\"]},{\"file\":\"src/shared/claimed-agent-pty-owner.test.ts\",\"assertions\":[\"concurrent exact claims spawn once and later callers adopt the canonical owner\",\"same identity in another worktree conflicts and cannot be found as the current scope's owner\",\"generation-guarded exit and authoritative reconciliation cannot retire a replacement owner\"]},{\"file\":\"src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts\",\"assertions\":[\"independent runtime clients converge on one canonical live agent-session owner\",\"retries and concurrent requests cannot create a second physical PTY\"]},{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"assertions\":[\"an exact PTY exit retires host membership and stale topology cannot recreate the surface\",\"incarnation fencing prevents an old delayed exit from retiring a replacement PTY\"]},{\"file\":\"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\"assertions\":[\"headed desktop host remains unfocused while the paired requester alone follows active fresh/resume sessions and inactive rows preserve exact client/DOM focus\",\"legacy afterTabId placement is exact in authoritative, mirrored, and rendered order with a pre-existing successor\",\"host PTY inventory plus writable agent/unrelated shell markers prove liveness, unrelated survival, and exact terminal/tab/PTY/process cleanup\"]},{\"file\":\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"assertions\":[\"headless focused fresh/resume requests create background host surfaces without a renderer window\",\"dropped committed responses replay the same operation identity without another tokened agent spawn\",\"exact terminal/tab/process identity survives retries and stale-write rejection, then retires without restart resurrection while unrelated shells survive until scoped cleanup\"]},{\"file\":\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\"assertions\":[\"isolated daemon roots and captured descendants are verified dead before profile PID records are removed\"]},{\"file\":\"tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"assertions\":[\"a durable host exit removes the terminal from two independent viewer mirrors instead of publishing a handle-less phantom\",\"one exact exit produces one same-epoch higher-version host publication and one durable persistence flush\",\"same-epoch stale publications cannot resurrect the retired surface after reconnect\"]},{\"file\":\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\"assertions\":[\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\",\"retains exact-leaf focus intent when a split sibling publishes first\"]},{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\",\"assertions\":[\"mirrors a new CLI tab after old-host recovery when $name\"]},{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"assertions\":[\"serializes a newer convergence snapshot after an in-flight adoption conflict\"]}]", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if a retry can physically spawn twice, if a stale exit/publication can replace or resurrect a terminal, or if mixed-version fallback occurs after an authority side effect." }, @@ -7357,14 +7341,14 @@ "invariant": "Only an explicit user change in Settings > Remote Orca Servers > Advanced > Active Server may mutate activeRuntimeEnvironmentId. Connecting, pairing, disconnecting, selecting or revealing a workspace or terminal, browser/mobile handoff, remote navigation, and reconnect must use transient or target-owner routing and must never rewrite the durable preference. Every Add Project selected host must satisfy canSelectAddRepoHost; paired web has no local filesystem fallback, so no valid host means Browse, Clone, and Create remain disabled. Every operation stays on the host selected when it began, even if preference or catalog state changes. Generic settings mutation cannot bypass the dedicated preference IPC.", "oracle": "Audit3362 retires the whole settings suite, including dirty-draft focus, background-host keepalive, protocol/catalog compatibility, stale/failure and refresh examples. The compound unit selector and test-file entry narrow; all prior owner-routing retirements/history remain. Four unrelated selected-runtime macOS E2E receipts remain verbatim and do not validate the changed unit selector. No equivalent replacement or fresh runtime/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3349 retires the explicit runtime-owner, explicit SSH-owner and missing-owner-after-catalog-change examples from worktrees-fetch-owner-routing. Of those four named assertions, only the missing-owner-after-provider-reconnect assertion remains; the command and test-file selector survive. Those three alarms are intentionally lost without equivalent replacement. Four unrelated physical selected-runtime macOS E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh runtime, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: drops older same-host group and folder responses that finish last — Copies group and folder fixtures plus four deferred responses to re-test the same generic catalog generation fence in two wrappers. Retires stale same-host response rejection at these API copies.; drops pre-reconnect group and folder responses without pruning the new catalog — Directly replaces pairing/catalog fixtures then resolves scripted old group/folder replies; repeats identity-fence contract in two catalog wrappers without real reconnect. Retires pre-reconnect catalog pruning refusal example.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2371 reduces all-host-folder-workspace-catalogs.test.ts by removing the repeated offline compatibility-probe budget and its incidental local-fallback/restored-owner samples, and catalog-settlement-notifications.test.ts by removing the four-route ten-equal-refresh notification/reference matrix. Those probe, quietness, identity and fallback alarms are intentionally lost. Remaining stale-response and revision-fencing examples do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced sources; the four unrelated physical selected-runtime E2E receipts retain their original commands and scope. Historical prior account (preserved verbatim): Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" ], "testFiles": [ - "src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts", + "src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts", "src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts", "src/renderer/src/web/web-preload-api-runtime-environment.test.ts", "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx", @@ -8066,7 +8050,7 @@ "providers": ["local", "daemon", "wsl"], "coveredPlatforms": ["windows"], "coveredProviders": ["daemon"], - "coverageNotes": "Audit1713 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Issue #8048 now has deterministic wrapper and cold-restore re-anchor tests plus a Windows PR-CI harness that drives the built daemon through 25 real ConPTY workspace-close races while an unrelated witness PTY stays alive. A Windows-only patched-node-pty test injects EAGAIN on one ConPTY input pipe and requires only that PTY to close while an unrelated PTY remains writable. Keyboard reset, CJK repaint, WSL, and full visible Electron coverage remain gaps.", + "coverageNotes": "Audit4358 intentionally removes six whole mocked daemon subprocess suites and two extra pre-listener replay variants (18 authored / 20 finite cases). Lost alarms include cancel-during-cwd-validation, root agent startup refusal, output/exit before ConPTY publication, fresh/delayed/unavailable foreground confirmation, cache/decision separation, detached/no-tty child evidence and synthetic agent authorization. The retained lifecycle case checks data and exit replay after handle creation, not startup-time publication or alternate listener order. The retained native Windows Git Bash workflow and host cold-restore seed check have separate scopes. No equivalent replacement or fresh gate execution is claimed. Earlier notes and dated receipts retain their original scope. Audit1713 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Issue #8048 now has deterministic wrapper and cold-restore re-anchor tests plus a Windows PR-CI harness that drives the built daemon through 25 real ConPTY workspace-close races while an unrelated witness PTY stays alive. A Windows-only patched-node-pty test injects EAGAIN on one ConPTY input pipe and requires only that PTY to close while an unrelated PTY remains writable. Keyboard reset, CJK repaint, WSL, and full visible Electron coverage remain gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6541", "https://github.com/stablyai/orca/pull/6858", @@ -8078,14 +8062,13 @@ "https://github.com/stablyai/orca/issues/17027" ], "invariant": "Windows local and daemon terminals must spawn with the intended shell, survive overlapping graceful/forced workspace teardown without affecting unrelated PTYs, contain an asynchronous ConPTY input-pipe failure to the affected terminal without killing the daemon, retain recovered scrollback across the fresh daemon's first checkpoint, accept normal Enter/Backspace/Arrow input after agent or TUI exit, render cursor/CJK/wide-glyph redraws without stale cells, and converge to nonzero applied size.", - "oracle": "Audit1713 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The issue #8048 slice asserts one node-pty ConPTY close for a graceful-then-force sequence, atomically seeds recovered history before fresh shell output and re-anchoring, preserves recovery after seed failure plus adapter restart, and runs 25 built-daemon close races while checking victim session/PID reaping, a stable daemon PID, and a live witness PTY. The EAGAIN slice emits an error from one real patched node-pty Windows input socket, requires its terminal to become unwritable and run the normal per-PTY kill path, then writes through an unrelated PTY without an uncaught exception. A broader Windows live gate still needs shell input, resize, cursor, and CJK/wide-glyph pixel evidence.", + "oracle": "Audit4358 intentionally removes six whole mocked daemon subprocess suites and two extra pre-listener replay variants (18 authored / 20 finite cases). Lost alarms include cancel-during-cwd-validation, root agent startup refusal, output/exit before ConPTY publication, fresh/delayed/unavailable foreground confirmation, cache/decision separation, detached/no-tty child evidence and synthetic agent authorization. The retained lifecycle case checks data and exit replay after handle creation, not startup-time publication or alternate listener order. The retained native Windows Git Bash workflow and host cold-restore seed check have separate scopes. No equivalent replacement or fresh gate execution is claimed. Earlier notes and dated receipts retain their original scope. Audit1713 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The issue #8048 slice asserts one node-pty ConPTY close for a graceful-then-force sequence, atomically seeds recovered history before fresh shell output and re-anchoring, preserves recovery after seed failure plus adapter restart, and runs 25 built-daemon close races while checking victim session/PID reaping, a stable daemon PID, and a live witness PTY. The EAGAIN slice emits an error from one real patched node-pty Windows input socket, requires its terminal to become unwritable and run the normal per-PTY kill path, then writes through an unrelated PTY without an uncaught exception. A broader Windows live gate still needs shell input, resize, cursor, and CJK/wide-glyph pixel evidence.", "commands": [ - "pnpm vitest run src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/node-pty-windows-input-error.win32.test.ts", + "pnpm vitest run src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/node-pty-windows-input-error.win32.test.ts", "pnpm build:electron-vite && node config/scripts/diagnostics/runtime-lifecycle/windows-daemon-workspace-close-repro.mjs", "node config/scripts/diagnostics/runtime-lifecycle/windows-daemon-workspace-close-repro.mjs" ], "testFiles": [ - "src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts", "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", "src/main/daemon/pty-subprocess/testing/node-pty-windows-input-error.win32.test.ts", "config/scripts/diagnostics/runtime-lifecycle/windows-daemon-workspace-close-repro.mjs" @@ -8137,7 +8120,8 @@ "Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Real IME composition may require a separate lower-layer/native-text-forwarding gate.", "The EAGAIN oracle injects the real input socket event rather than inducing kernel resource exhaustion on a packaged Windows host.", - "The built-daemon harness proves process/session liveness but not renderer pixels; visible shell input, resize, cursor, and CJK repaint remain uncovered." + "The built-daemon harness proves process/session liveness but not renderer pixels; visible shell input, resize, cursor, and CJK repaint remain uncovered.", + "Audit4358 retired original selector fields (historical provenance only; no current execution claim): {\"commands\":[\"pnpm vitest run src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/node-pty-windows-input-error.win32.test.ts\",\"pnpm build:electron-vite && node config/scripts/diagnostics/runtime-lifecycle/windows-daemon-workspace-close-repro.mjs\",\"node config/scripts/diagnostics/runtime-lifecycle/windows-daemon-workspace-close-repro.mjs\"],\"testFiles\":[\"src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"src/main/daemon/pty-subprocess/testing/node-pty-windows-input-error.win32.test.ts\",\"config/scripts/diagnostics/runtime-lifecycle/windows-daemon-workspace-close-repro.mjs\"]}" ], "demotionRule": "Cannot promote while Windows E2E is flaky, silently skipped, or screenshot-only." }, @@ -8224,13 +8208,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -8238,7 +8222,7 @@ "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", @@ -8261,11 +8245,10 @@ "src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "src/renderer/src/web/web-preload-api-runtime-environment.test.ts", - "src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts", - "src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts", - "src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts", - "src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts", - "src/main/runtime/rpc/terminal-subscribe-buffer.test.ts", + "src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts", + "src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts", + "src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts", + "src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts", "src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", "src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts", "src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts", @@ -8384,7 +8367,7 @@ ] }, { - "file": "src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts", + "file": "src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts", "assertions": [ "admits 128 active streams, rejects the 129th, and reuses released capacity", "reserves PTY wait capacity independently from active streams" @@ -8571,6 +8554,12 @@ "Keep the budget-off control, exact manager count, final bounded-tail flood marker, parked-time output, and post-reveal PTY input in both topology runs." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", + "Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed.", + "Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions.", "NEXT65 current scope qualification: The NEXT65 knownGaps entries below govern the changed selectors and qualify any broader coverage implication in this gate’s unchanged oracle/coverageNotes narratives. Those narratives and preserved dated evidenceRuns retain their historical text and original exact execution scopes only; no fresh execution, transferred pass or equivalent replacement coverage is claimed. Upstream case removals remain upstream; original NEXT65 proposal descriptions grant no duplicate retirement credit.", "NEXT65 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence.", "NEXT65 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-parked-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts\",\n \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts\",\n \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts\",\n \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts\",\n \"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"assertions\": [\n \"2,880 decorative spinner and bare-native real-PTY OSC chunks publish zero session-tabs snapshots or serialized bytes after semantic convergence\",\n \"the viewer performs zero snapshot applies and zero store mutations during decorative activity\",\n \"after 30 minutes, one globally spaced refresh per worktree keeps every mirrored working status fresh\",\n \"exact Pi and rotating normalized Pi/Grok frames renew explicit and fallback status without changing stateStartedAt or acknowledgement semantics\",\n \"matching title evidence renews retained OSC hook status without resetting stateStartedAt, then drops unverifiable prompt metadata after the hook row expires\",\n \"renderer-authored rich status keeps its original lease, then renews only coarse title-confirmed state and provider identity\",\n \"ordinary-shell title transitions replace working stateStartedAt with the completion transition time\",\n \"decorative heartbeats remain blocked until unknown foreground ownership resolves, then resume at the bounded interval\",\n \"tracked terminal state reset clears delayed foreground ownership markers\",\n \"raw chunks, semantic idle transitions, and visible output remain exact\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"assertions\": [\"retries an existing subscriber when provider inventory becomes ready\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"assertions\": [\n \"creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed\",\n \"post-boundary creation and removal replay after the initial snapshot in sequence order\",\n \"create/remove/recreate transitions are preserved without collapse\",\n \"a post-boundary projected-state change is delivered without a new snapshot revision\",\n \"an older coalesced callback cannot overwrite a newer immediate change\",\n \"initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection\",\n \"disconnect aborts the census and removes the real runtime listener\"\n ]\n },\n {\n \"file\": \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"assertions\": [\n \"unpublished empty inventory keeps resume dispatch at zero with the original daemon session, process id, and writer as the sole live writer\",\n \"an authoritative empty inventory settles the mirror and releases exactly one resume dispatch with zero liveness probes\",\n \"re-enabling unconditional empty hydration makes the identical oracle red with one resume dispatch, two session ids, two process ids, and two writer calls\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"assertions\": [\n \"preserves daemon PID and target PTY identity across the paired host relaunch\",\n \"foregrounds the daemon-backgrounded target on its first post-relaunch remote observation\",\n \"delivers target and post-relaunch control terminal input and live output\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"assertions\": [\"replaces a stale paired stream when the PTY snapshot advanced\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\n \"restarts one ACK-starved paired terminal stream without replacing its PTY\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\"recovers an ACK-starved stream from an isolated headless Orca host\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"assertions\": [\n \"a nonempty lossy initial snapshot paints exactly once on a paired client\",\n \"the authoritative host cursor advances and live output resumes exactly once\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"assertions\": [\n \"paints a paired remote terminal when only its retained text tail overflowed\",\n \"legacy paired hosts retain the lossy hidden-manager budget fallback\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals and restores authoritative host scrollback\",\n \"warm-mounted hidden paired streams schedule zero renderer output work under sustained host output\",\n \"six hidden real PTYs publish and apply only exact working and idle title transitions across paired transport\",\n \"client recovery completes while every target terminal remains unmounted in the host renderer\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals against an isolated headless Orca host\",\n \"cold-activates only visible paired terminals against an isolated headless host\",\n \"the headless host bounds real-PTY decorative title transport and production store application\",\n \"the headless host shares the zero-hidden-renderer-work and exact-restoration contract\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"assertions\": [\n \"releases un-parkable hidden worktree buffers only once the retention budget engages\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"admits 128 active streams, rejects the 129th, and reuses released capacity\",\n \"reserves PTY wait capacity independently from active streams\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"pauses capable paired output while hidden and restores exactly on reveal\",\n \"locally gates hidden paired output when a legacy host cannot pause it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"assertions\": [\n \"keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot\"\n ]\n },\n {\n \"file\": \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"assertions\": [\n \"keeps pairing while manual disconnect fences passive reconnects\",\n \"returns a disconnect envelope when a queued active runtime call disconnects\",\n \"returns a disconnect envelope when a queued selected environment call disconnects\"\n ]\n }\n ]", @@ -8687,7 +8676,8 @@ "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-parked-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts\",\n \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts\",\n \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts\",\n \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts\",\n \"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"assertions\": [\n \"2,880 decorative spinner and bare-native real-PTY OSC chunks publish zero session-tabs snapshots or serialized bytes after semantic convergence\",\n \"the viewer performs zero snapshot applies and zero store mutations during decorative activity\",\n \"after 30 minutes, one globally spaced refresh per worktree keeps every mirrored working status fresh\",\n \"exact Pi and rotating normalized Pi/Grok frames renew explicit and fallback status without changing stateStartedAt or acknowledgement semantics\",\n \"matching title evidence renews retained OSC hook status without resetting stateStartedAt, then drops unverifiable prompt metadata after the hook row expires\",\n \"renderer-authored rich status keeps its original lease, then renews only coarse title-confirmed state and provider identity\",\n \"ordinary-shell title transitions replace working stateStartedAt with the completion transition time\",\n \"decorative heartbeats remain blocked until unknown foreground ownership resolves, then resume at the bounded interval\",\n \"tracked terminal state reset clears delayed foreground ownership markers\",\n \"raw chunks, semantic idle transitions, and visible output remain exact\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"assertions\": [\"retries an existing subscriber when provider inventory becomes ready\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"assertions\": [\n \"creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed\",\n \"post-boundary creation and removal replay after the initial snapshot in sequence order\",\n \"create/remove/recreate transitions are preserved without collapse\",\n \"a post-boundary projected-state change is delivered without a new snapshot revision\",\n \"an older coalesced callback cannot overwrite a newer immediate change\",\n \"initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection\",\n \"disconnect aborts the census and removes the real runtime listener\"\n ]\n },\n {\n \"file\": \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"assertions\": [\n \"unpublished empty inventory keeps resume dispatch at zero with the original daemon session, process id, and writer as the sole live writer\",\n \"an authoritative empty inventory settles the mirror and releases exactly one resume dispatch with zero liveness probes\",\n \"re-enabling unconditional empty hydration makes the identical oracle red with one resume dispatch, two session ids, two process ids, and two writer calls\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"assertions\": [\n \"preserves daemon PID and target PTY identity across the paired host relaunch\",\n \"foregrounds the daemon-backgrounded target on its first post-relaunch remote observation\",\n \"delivers target and post-relaunch control terminal input and live output\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"assertions\": [\"replaces a stale paired stream when the PTY snapshot advanced\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\n \"restarts one ACK-starved paired terminal stream without replacing its PTY\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\"recovers an ACK-starved stream from an isolated headless Orca host\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"assertions\": [\n \"a nonempty lossy initial snapshot paints exactly once on a paired client\",\n \"the authoritative host cursor advances and live output resumes exactly once\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"assertions\": [\n \"paints a paired remote terminal when only its retained text tail overflowed\",\n \"legacy paired hosts retain the lossy hidden-manager budget fallback\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals and restores authoritative host scrollback\",\n \"warm-mounted hidden paired streams schedule zero renderer output work under sustained host output\",\n \"six hidden real PTYs publish and apply only exact working and idle title transitions across paired transport\",\n \"client recovery completes while every target terminal remains unmounted in the host renderer\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals against an isolated headless Orca host\",\n \"cold-activates only visible paired terminals against an isolated headless host\",\n \"the headless host bounds real-PTY decorative title transport and production store application\",\n \"the headless host shares the zero-hidden-renderer-work and exact-restoration contract\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"assertions\": [\n \"releases un-parkable hidden worktree buffers only once the retention budget engages\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"admits 128 active streams, rejects the 129th, and reuses released capacity\",\n \"reserves PTY wait capacity independently from active streams\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"pauses capable paired output while hidden and restores exactly on reveal\",\n \"locally gates hidden paired output when a legacy host cannot pause it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"assertions\": [\n \"keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot\"\n ]\n },\n {\n \"file\": \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"assertions\": [\n \"keeps pairing while manual disconnect fences passive reconnects\",\n \"returns a disconnect envelope when a queued active runtime call disconnects\",\n \"returns a disconnect envelope when a queued selected environment call disconnects\"\n ]\n }\n ]", "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", "Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. All prior notes and complete dated receipts retain their original scopes.", - "Audit3446 archived original assertionRef after source reduction; historical scope only, raw original object follows:\n{\n \"file\": \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"assertions\": [\n \"2,880 decorative spinner and bare-native real-PTY OSC chunks publish zero session-tabs snapshots or serialized bytes after semantic convergence\",\n \"the viewer performs zero snapshot applies and zero store mutations during decorative activity\",\n \"after 30 minutes, one globally spaced refresh per worktree keeps every mirrored working status fresh\",\n \"exact Pi and rotating normalized Pi/Grok frames renew explicit and fallback status without changing stateStartedAt or acknowledgement semantics\",\n \"matching title evidence renews retained OSC hook status without resetting stateStartedAt, then drops unverifiable prompt metadata after the hook row expires\",\n \"renderer-authored rich status keeps its original lease, then renews only coarse title-confirmed state and provider identity\",\n \"ordinary-shell title transitions replace working stateStartedAt with the completion transition time\",\n \"decorative heartbeats remain blocked until unknown foreground ownership resolves, then resume at the bounded interval\",\n \"tracked terminal state reset clears delayed foreground ownership markers\",\n \"raw chunks, semantic idle transitions, and visible output remain exact\"\n ]\n }" + "Audit3446 archived original assertionRef after source reduction; historical scope only, raw original object follows:\n{\n \"file\": \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"assertions\": [\n \"2,880 decorative spinner and bare-native real-PTY OSC chunks publish zero session-tabs snapshots or serialized bytes after semantic convergence\",\n \"the viewer performs zero snapshot applies and zero store mutations during decorative activity\",\n \"after 30 minutes, one globally spaced refresh per worktree keeps every mirrored working status fresh\",\n \"exact Pi and rotating normalized Pi/Grok frames renew explicit and fallback status without changing stateStartedAt or acknowledgement semantics\",\n \"matching title evidence renews retained OSC hook status without resetting stateStartedAt, then drops unverifiable prompt metadata after the hook row expires\",\n \"renderer-authored rich status keeps its original lease, then renews only coarse title-confirmed state and provider identity\",\n \"ordinary-shell title transitions replace working stateStartedAt with the completion transition time\",\n \"decorative heartbeats remain blocked until unknown foreground ownership resolves, then resume at the bounded interval\",\n \"tracked terminal state reset clears delayed foreground ownership markers\",\n \"raw chunks, semantic idle transitions, and visible output remain exact\"\n ]\n }", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -8851,7 +8841,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6836", "https://github.com/stablyai/orca/pull/6858", @@ -8859,36 +8849,36 @@ "https://github.com/stablyai/orca/pull/7054" ], "invariant": "High-volume terminal output must stay bounded across daemon socket writes, SSH relay writer/decoder/source retention/reconnect, main model and projection admission, runtime metadata, detectors, and tail checks, main-to-renderer in-flight bytes, renderer scheduler queues, and hidden-output restore without starving focused input. Every new SSH session offers V1 and every same-build relay supports it; legacy delivery is reachable only when capability negotiation proves the peer cannot use V1. Negotiated SSH spans remain exact and contiguous through activation, exit, cancellation, recovery, desktop projection, and required remote replacement; provisional activation data cannot project, reconnect may release it only into the exact attempt's private recovery quarantine after contract validation, and exit seals that quarantine against later same-token frames until ordered admission or exact cancellation proof. Reconnect checkpoint capture freezes exact provider-generation/PTy admission, cancels queued old work, and waits for the running raw completion before exposing its accepted checkpoint; timeout or failure detaches only that PTy's old model, makes the checkpoint unavailable, and releases the bounded fence without closing the shared provider, while the same failure outside an active exact migration remains generation-fatal and overlapping reconnects preserve any earlier outstanding fence. Pending renderer projection IDs are capped and compacted across split remainders, exit preparation owns its renderer fence through finalization, exit-time cancellation transfers published projections before proof commit, generation close fences late proof while draining exact projection waiters, closed-generation identity compacts without weakening stale rejection, canceled source-delivery retirement retains at most one ordered token per PTY, and pause/resume targets only the exact provider generation. Additional subscribers cannot stall the owner, while the required legacy primary retains backpressure.", - "oracle": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/protocol-backpressure.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/dispatcher.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/transport/wire/protocol-backpressure.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/transport/publication/dispatcher.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/wsl-guest/transport/writer/dispatcher-client-writer.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/transport/writer/dispatcher-client-writer.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts --reporter=dot" ], "testFiles": [ "src/main/runtime/construction/orca-runtime.test.ts", - "src/wsl-guest/protocol-backpressure.test.ts", - "src/wsl-guest/dispatcher.test.ts", + "src/wsl-guest/transport/wire/protocol-backpressure.test.ts", + "src/wsl-guest/transport/publication/dispatcher.test.ts", "src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts", "src/main/ssh/protocol/ssh-channel-multiplexer.test.ts", "src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts", - "src/wsl-guest/dispatcher-client-writer.test.ts", + "src/wsl-guest/transport/writer/dispatcher-client-writer.test.ts", "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts" ], "assertionRefs": [ { - "file": "src/wsl-guest/dispatcher.test.ts", + "file": "src/wsl-guest/transport/publication/dispatcher.test.ts", "assertions": [ "a saturated legacy primary remains required backpressure and is never detached as an additional subscriber" ] }, { - "file": "src/wsl-guest/protocol-backpressure.test.ts", + "file": "src/wsl-guest/transport/wire/protocol-backpressure.test.ts", "assertions": [ "relay decoder accepts one maximum frame plus 1 MiB partial input and rejects one extra byte", "a throwing continuation clears retained input, releases one pause epoch, and publishes one typed ownership error" @@ -8911,7 +8901,7 @@ ] }, { - "file": "src/wsl-guest/dispatcher-client-writer.test.ts", + "file": "src/wsl-guest/transport/writer/dispatcher-client-writer.test.ts", "assertions": [ "encoded producer frames stay below high-water-minus-reserve capacity", "one fixed-size filesystem compatibility frame is admitted only on an empty sink", @@ -8933,7 +8923,8 @@ "command": "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/protocol-backpressure.test.ts --reporter=dot", "result": "passed", "durationSeconds": 2.24, - "summary": "Sixteen deterministic SSH relay/session/source/decoder files passed 192 tests, including exit-sealed private recovery, retained stale-transfer cancellation authority, exact private-frame proof watermarks, one retirement record across 10,000 same-PTY token rotations, stale-owner fallback, and scheduler rejection isolation; no live topology was exercised." + "summary": "Sixteen deterministic SSH relay/session/source/decoder files passed 192 tests, including exit-sealed private recovery, retained stale-transfer cancellation authority, exact private-frame proof watermarks, one retirement record across 10,000 same-PTY token rotations, stale-owner fallback, and scheduler rejection isolation; no live topology was exercised.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/transport/wire/protocol-backpressure.test.ts --reporter=dot" } ], "runtimeBudget": { @@ -8958,6 +8949,49 @@ "Keep stress variants non-blocking until stable runtime history exists." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", + "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical.", + "Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical.", + "Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope.", + "Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed.", + "Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes.", + "Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases.", + "Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit.", + "Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved.", + "Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits.", + "Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope.", + "Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit.", + "Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit.", + "Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit.", + "Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical.", + "Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained.", + "Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit.", + "Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit", + "Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures.", + "Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise.", + "Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope.", + "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit.", + "Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation.", + "Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains.", + "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence.", + "Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope.", + "Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope.", + "Audit3630 removed orphan delete/toggle capability/precondition and run/edit refusal assertions. Real dispatch, mutation fencing, mixed-version and host outcomes are not established by this removal or by a substitute test.", + "Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope.", + "Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope.", + "Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope.", + "Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope.", + "Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope.", + "Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed.", + "Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions.", "Launch direct-owner cleanup current scope: This gate’s unfiltered unit command now selects a suite reduced by 82 whole registrations / 159 potential table examples in 10 whole test Programs, including 8 registrations / 15 examples from five once-registered create-message factory closures. Lost alarms include frozen first-message/options and legacy-host fallback; distinct actions and redelivery; uncertain/refused/reloaded input custody, Retry and late proof; rich prompt/attachment upload Stop/close and handback; ordinary draft/editor/IME/StrictMode lifetime and accepted topology; provisional fallback tab placement/group/pin/order and rich worktree handoff. Four whole consent/resume-identity cases remain in two Programs; they do not replace these alarms. This entry governs current reduced-unit scope and qualifies any broader implication of unchanged oracle/coverageNotes history. Entire dated evidenceRuns, original commands/currentCommand values, counts/results and existing history retain their original scopes only; no fresh execution, transferred pass, replacement equivalence or prior upstream-removal credit is claimed.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/ssh/ssh-channel-multiplexer.test.ts: sends a JSON-RPC request and resolves on response; assigns unique request IDs; sends notifications without expecting a response; dispatches incoming notifications to handler; sends one keepalive frame per cadence tick; drives keepalive sends AND dead-link detection from a single interval; resolves false immediately on a disposed mux; throws on request after dispose; reports isDisposed correctly; clears registered handlers on dispose; does not retain handlers registered after dispose. src/main/persistence/worktree-sort-order-write.test.ts: re-ranks every writable row when a blocked row sits in the requested order. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts: continues skill management after startup recovery fails. src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts: uses bounded ownership lookup for direct arrivals while the agent cannot take input; wakes a bound Run waiter when same-Run direct mail arrives; keeps an unowned detached-recipient message in its direct mailbox; uses primary-key lookups for bounded routing updates. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts: remove only literal registration import/call pairs import './orchestration-mailbox-pointer-cli-command.spec'; no additional authored credit. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts: renders the %s CLI command in a mailbox pointer. src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts: sizes a slow high-latency link near twice its bandwidth-delay product; never paces a LAN, even when its client parses slowly; never paces a fast link; returns to legacy windows when the path RTT jumps. src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts: steps down the row ladder when history is over the byte budget; tries the larger first row count, then the usual ladder within the same byte budget. src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts: returns unknown when route inspection fails or emits malformed data; does not inspect routes outside Windows. src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts: is refused to a paired %s client; reports a failed widening instead of advertising an unreachable address. src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts: reports exited only when the owning runtime completes the exit waiter; reports unverifiable when the runtime cannot observe the exit waiter; reports unverifiable when a disconnected PTY resolves with unknown liveness. src/main/runtime/session-graph/headless-runtime-graph.spec.ts: lets a session tab inventory settle on a host no renderer publishes for. src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts: remove only literal registration import/call pairs import { registerHeadlessRuntimeGraphTests } from './headless-runtime-graph.spec', registerHeadlessRuntimeGraphTests(); no additional authored credit. src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts: bumps the stored snapshot version only when the title changes. src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts: keeps the healthy aggregate verification and delayed physical exit behavior; uses a stamped exit for the incarnation that was actually being closed. src/main/runtime/terminal/identity/terminal-identity-probe.test.ts: answers live for a structured worker without touching the PTY graph; answers live for a PTY handle the runtime still holds; runs the full leaf check for a handle with no live PTY; answers not-live for a stale handle; propagates \"could not look\" rather than reporting it as a dead handle. src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts: names the tab in main’s layout through terminal.rename; takes a window-style layout.apply close as already stopped, so the terminal runs on. src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts: retains no lifecycle generation after a spawn/exit cycle. src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts: reads a freshly spawned terminal as used once a user opens its tab, not on a probe; keeps the open mark on the process a user open starts. src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts: from a desktop window that mounts both panes; from a server with no window. src/main/runtime/terminal/surface/workspace-layout-projection.test.ts: carries views for a partition that holds none yet. src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts: releases a signalled exit-waiter when the signal aborts. src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts: selects a local hook status for a local pane. src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts: keeps the footer and the bare caret on screen mid-turn; %s: the screen alone reads ready during %s. src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts: uses per-launch arguments and preserves launch telemetry; attributes a startup agent whose caller named no surface as unknown; launches %s bare for an absent or blank prompt; attributes a %s draft launch named %s as %s; merges an automation's extras over the host defaults; threads worktree-create extras into the startup build; returns an enabled requested agent without detecting; returns the default when nothing was requested; detects instead of using the default when the requested agent is disabled; starts no agent when the default is blank; detects an enabled agent on this host when nothing usable was named; starts no agent when detection finds none. src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts: pastes and submits through composer readiness, never typing raw input; types the follow-up on WSL or SSH-to-Windows once the agent is in front, as before; cleans up the deadline when the composer was already captured; a draft that is not submitted is pasted on the box cursor, as before; takes the box after the grace when the row never comes, whatever repaints; takes the box at the deadline when the grace would outlast the budget; lets a dialog on screen veto a grace; refuses the deadline inside a pending grace while a shell is in front; takes the box at the deadline inside a pending grace with the agent in front; takes the box at the deadline after a refused grace once the agent is in front. src/main/skills/skill-install-transaction.test.ts: installs, previews unchanged bytes, and updates a clean receipt-owned skill; preserves the old version after a %s filesystem failure. src/main/speech/model-manager-download-resume.test.ts: requests the remaining bytes when a clean range response ends before the file total; bounds a server that advances by pathologically tiny segments forever. src/main/ssh/config/ssh-config-parser.test.ts: parses a basic host block; parses multiple host blocks; skips wildcard-only Host entries; skips Host entries with only pattern characters; parses IdentityFile with ~ expansion; parses Windows-style IdentityFile with ~ expansion; parses quoted scalar values like OpenSSH; parses equals-form scalar directives; parses IdentityAgent with ~ expansion; parses IdentitiesOnly; parses GSSAPIAuthentication; keeps the first GSSAPIAuthentication value like OpenSSH; parses ProxyCommand, ProxyUseFdpass, and ProxyJump; ignores comments and blank lines; handles case-insensitive keywords; stops current block on Match directive; returns empty array for empty input; creates one parsed host per concrete alias on a multi-pattern Host line; applies identity agent settings to every concrete alias on a multi-pattern Host line; defaults port to 22 for invalid port values; converts hosts to SshTarget objects; uses host alias as hostname when HostName is missing; skips hosts that are already imported; defaults username to empty string when not specified; carries through identityFile, identityAgent, identitiesOnly, proxyCommand, and jumpHost; carries through gssapiAuthentication; imports duplicate aliases only once and keeps the first concrete host; maps hosts for the picker and flags aliases already in Orca; de-dupes aliases and defaults missing fields; parses hostname, user, port from ssh -G output; collects multiple identity files; parses forwardagent yes; defaults port to 22 when missing; returns empty hostname when missing; returns undefined user when missing; handles empty output; skips lines without spaces; parses proxycommand and filters \"none\"; parses proxyusefdpass yes; parses proxyjump and filters \"none\"; handles ~ expansion in identity file paths; handles Windows-style ~ expansion in identity file paths; parses identityagent with ~ expansion; preserves identityagent none so auth can disable agent fallback; parses identitiesonly yes; parses gssapiauthentication; parses controlmaster options and filters controlpath none. src/main/ssh/config/ssh-known-hosts-source.test.ts: splits the space-separated list ssh -G prints on one line; expands ~ in a reported path; keeps a double-quoted path containing spaces whole; falls back to the default files when ssh -G reported nothing; drops an explicit none without falling back to the defaults; splits both known_hosts lists on one line each; reads StrictHostKeyChecking, including accept-new; reads HostKeyAlias and prefers it for the lookup; reads the non-default port; reports that the lookup came from an alias, so the port is not appended; reports no alias when the dialed host is used; unions the entries of every file; skips a path that is a directory; returns nothing when no file can be read; reports nothing unreadable when every file parses; does not count an empty file as unreadable; prefers HostKeyAlias over the resolved hostname; uses the dialed host, because a resolved hostname can just echo the label; still prefers an explicit HostKeyAlias over the dialed host; falls back to the dialed host when nothing was resolved; is rejoined when the split fragments resolve to nothing; leaves a single unresolvable path alone rather than inventing one; expands the __PROGRAMDATA__ token rather than passing it through as a path; does not rewrite a path that merely BEGINS with the token characters; keeps a drive-letter path with mixed separators intact; splits a spaced Windows home into the fragments the rejoin has to put back. src/main/ssh/config/ssh-known-hosts.test.ts: reads the algorithm from the blob rather than trusting the line; rejects %s; refuses a malformed blob: %s; uses the bare host on the default port; tries the bracketed form first and falls back to bare off-port; matches an exact line; matches case-insensitively; reports a changed key of the same type; reports unknown for %s; matches any host in a comma list; matches the bracketed form on its port; does not apply a bracketed entry to the default port; falls back to a bare line when off-port; never reports a change from the fallback pass; matches a bare literal on the default port; matches a bracketed literal on its port; reports a change for a literal; handles %s; still reports a change for a different key on a revoked host; skips a line carrying an unrecognised marker; does not report a change when only another key type is on file; matches within the same type; accepts CRLF terminators; skips blanks, comments and surrounding whitespace; accepts a hit regardless of which file holds it (%s); never brackets the alias, whatever the port; still brackets an ordinary host on a non-default port; matches a bare alias entry on a non-default port; still accepts the unmodified key field; accepts a hashed entry whose salt is a full SHA1 digest; still accepts the unmutated ssh-keygen -H vector; falls back to the bare host line on a non-default port, as ssh did; refuses a key type it has not seen for a host it knows, as ssh did. src/main/ssh/connection/ssh-connect-config.test.ts: returns undefined when no default keys exist; returns the first existing key file; probes regular and FIDO2 keys in stable default order; keeps a regular default ahead of a malformed FIDO2 default; uses target host/port/username; falls back to resolved config when target fields are empty; keeps imported endpoint fields as the fallback when ssh -G is unavailable; sets readyTimeout to CONNECT_TIMEOUT_MS; sets keepaliveInterval to 15s; enables keyboard-interactive auth so MFA challenges can be answered; uses agent auth when no explicit key and SSH_AUTH_SOCK is set; enables agent forwarding when OpenSSH config requests it and an agent is available; does not enable agent forwarding without a usable agent; resolves IdentityAgent SSH_AUTH_SOCK from the environment; uses the Windows OpenSSH agent pipe when no environment socket is available on Windows; wraps agent auth with IdentityFile filtering when IdentitiesOnly is enabled; applies a manual target IdentitiesOnly setting when ssh -G reports it off; includes unencrypted target.identityFile auth when an agent is available; defers encrypted target.identityFile auth when an agent is available; uses keyFile auth when target.identityFile is set and no agent is available; includes unencrypted resolved identityFile auth when an agent is available; defers a default-path resolved identityFile to the no-agent retry; offers the keyboard-interactive challenge when the agent defers no key; provides fallback key when no agent is available; can force private key inclusion for the post-agent fallback path; falls back to resolved proxyCommand; returns structured jump-host config for target.jumpHost; returns structured jump-host config for resolved proxyJump; returns undefined when no proxy is configured. src/main/ssh/connection/ssh-connection-auth-fallback.test.ts: resolves OpenSSH config using configHost when present; tries ssh-agent before reading an explicit private key; falls back to direct private key auth when agent auth fails; falls back to direct private key auth after too many agent authentication failures; answers bounded keyboard-interactive challenges such as Duo 2FA. src/main/ssh/connection/ssh-connection-store.test.ts: lists picker suppression aliases without consulting re-adoption tombstones; getTarget delegates to store; addTarget generates an id and persists; saves the CLI control switch as given, with no consent stamp; addTarget stamps source as manual by default; addTarget preserves an explicitly provided source; inserts a new config host stamped as ssh-config; asks the parser for all hosts — reconciliation happens in the store; updates an existing config-sourced target when the port changed; refreshes gssapiAuthentication on sync; never overwrites a manual target that owns the alias; does not rewrite an unchanged config-sourced target; returns empty array when nothing changed; tombstones a deleted config-sourced host so re-import skips it; suppresses a deleted manual target from config discovery; re-adding a deleted host reclaims its alias so sync stops suppressing it; editing a target reclaims its alias from the deleted set; records a tombstone when removing any user-facing target; re-adopts orphaned repos when the same host is re-added. src/main/ssh/connection/ssh-connection.test.ts: transitions to connected on successful connect; captures the negotiated SSH server key fingerprint; allows concurrent exec commands for ssh2 transport; removes startup listeners after ssh2 connect succeeds; scopes lifecycle events and pending handshake timers to one mock client; enables TCP_NODELAY on the new ssh2 client after a reconnect cycle; transitions through connecting → connected states; reports error state on connection failure; disconnect cleans up and sets state to disconnected; getTarget returns a copy of the target; getState returns a copy of the state; throws when connecting a disposed connection. src/main/ssh/orcad-migration-stuck-host-profiles.test.ts: never leaves a running terminal behind; is offered only when leaving saved state behind would clear the refusal. src/main/ssh/orcad-runtime-maintenance.test.ts: keeps a connect from retrying a build an explicit Update also failed; offers Force when Update was refused by policy; forwards anew after an activation, since the new slot may bind another port; passes a refusal through and leaves the server linked; forwards anew once a serving slot is restored, which may have bound another port. src/main/ssh/port-forwarding/ssh-port-forward.test.ts: reports the port the OS bound when an ssh2 forward asks for port 0; adds an ssh2 port forward and returns entry; adds a system SSH port forward when no ssh2 client is available; reports the port a system SSH forward resolved when asked for port 0; passes resolved OpenSSH config to system SSH port forwards; disposes a system SSH tunnel when removing the forward; lists forwards filtered by connectionId; removes a forward by id; awaits forward close when removing a forward for user actions; returns null when removing nonexistent forward; removes all forwards for a connection; dispose removes all forwards; stores label in the entry; preserves the existing id when updating a forward succeeds. src/main/ssh/system-transport/system-ssh-forward-process.test.ts: spawns exactly the argv the orphan matcher is given, LogLevel=INFO included; runs port forwards unmultiplexed even when ssh_config disables muxing; preserves manual target port and identity options in the forwarded ssh command; does not spawn ssh when the requested local forward port is already in use; spawns ssh after the requested local forward port preflight succeeds; resolves startup after the grace period when ssh keeps running; sends SIGTERM then SIGKILL when the process does not exit; does not resolve stop until the process exits. src/main/ssh/system-transport/system-ssh-loopback-route.test.ts: dials the held forward ahead of the alias so OpenSSH keeps these over ssh_config; drops a manual target's own port and proxies, which would fight the route; never routes a forward, whose argv must stay stable for orphan recovery; %s → %s; opens the forward over the real proxy, then proves a login over the route; lands the forward on the sshd and known_hosts name the direct route resolved; holds the forward with server-alive probes; never lets the background forward or probe ask for credentials; starts no forward when admission refuses the route; stops the forward when sshd refuses logins over it; stops the whole forward process tree on Windows, once; reports a forward that already exited before anyone listened for it. src/main/startup/browser-process-user-agent-ordering.test.ts: explains admission refusal before a desktop launch exits; explains an orcad holding the profile instead of exiting silently; does not acquire profile admission for a duplicate launch; executes after the dev app name and before later preflight work; exits and releases admission after pending profile move recovery fails; keeps Linux background startup failures console-only and immediate; keeps Linux serve startup failures console-only and immediate. src/main/startup/quit/quit-path-durable-write-blocking.test.ts: store.flushAsync() issues no synchronous fs syscalls; store.flushAsync() also moves the active-view and github-cache sidecars off the thread; stats.flushAsync() issues no synchronous fs syscalls; Grok session cleanup issues no synchronous fs syscalls; stats.flushAsync() closes out live agents before it returns, not when its write lands; a stalled mount leaves the event loop live instead of parking it; store.flushAsync() is one idempotent final barrier; store.flushAsync() resolves instead of throwing when the profile mount rejects writes. src/main/stats/agent-session-transition-recorder.test.ts: counts a hook-only agent that never writes an agent-shaped terminal title; never opens a session from a replayed or disk-restored working status; still closes a live session when the terminating status arrives as a replay; counts one session per turn across repeated working/done cycles; closes an open session when its pane is torn down; bounds the mirror and closes what it evicts; stops the session when the main agent settles and only a watch loop holds the row working; keeps the session open while a subagent outlives the main agent, and closes it when the child settles; dates the stop by the evidence when a shell outlives the last subagent; opens a new session dated by the observation when the main agent resumes after monitoring; never dates a reopen before the close a fact-less OSC repaint caused; dates the first live row after a restored one by the evidence, not the restored clock; treats an unchanged answer as a snapshot, never a transition; opens only on a live working edge; closes only a session it opened. src/main/text-generation/commit-message-text-generation-model-discovery.test.ts: returns static catalog models without spawning for static agents; discovers dynamic models through the agent CLI; discovers dynamic models through the configured agent command override; falls back to static models when dynamic discovery returns no parseable models; falls back to the first discovered non-Pi model when its static default is unavailable. src/main/text-generation/pull-request-context.test.ts: does not fetch unrelated fork remotes before generating PR context; bounds exact remote-ref probe concurrency for a large remote list; reports no branch change because PR context preparation is read-only; keeps a remote-qualified base when the selected base includes the remote. src/main/text-generation/source-control-local-process.test.ts: asks the supervisor to stop and leaves its group to it; signals nothing once the supervisor has exited; stops an agent that ignores its stdin end through its supervisor. src/main/updater/linux-package/linux-package-update-recovery.test.ts: retains the downloaded package with the digest from the event metadata; requires a string downloaded path; accepts an uppercase extension; requires a non-empty string version; matches an absolute file URL by basename; accepts duplicate entries that agree on the digest; refuses an entry with a missing or non-string digest; refuses a digest that is not base64 at all; refuses a malformed percent-encoded URL; refuses a missing or non-array file list; tolerates a non-object event; replaces the retained artifact with a newer download; keeps the retained artifact when a new download has no usable digest; keeps the retained artifact when an unrelated download event arrives; clears the retained artifact; preserves the artifact across a recheck of the same version; clears the artifact when another version takes over; preserves the artifact for an unknown or empty version; is a no-op without a retained artifact; returns the built command and package file name for a verified package; reports missing without a retained artifact; propagates a package-manager discovery failure; rejects a well-formed digest that belongs to another file; never hashes a package that a malformed digest failed to arm; rejects a path outside the cache root; rejects the cache root itself; rejects a package in the updater directory itself; rejects a pending directory that is a symlink out of the cache; performs one hash pass for concurrent requests; revalidates once the in-flight pass settles; does not reuse an in-flight pass for a different artifact; starts a fresh proof when the same package is captured again; returns the verified package path; returns missing without a retained artifact. src/main/updater/releases/updater-prerelease-feed-readiness.test.ts: accepts a GitHub %s asset redirect as ready; reports a GitHub asset request error as unavailable; reports not-ready with a verified last-good tag when the newest assets are unavailable; does not classify a non-positive tag limit as feed unavailability; reproduces the v1.4.142 publishing incident as not-ready; reports transport failures as unavailable instead of not-ready; treats an explicit asset 404 as not-ready when another asset is unavailable; accepts absolute manifest asset URLs without rewriting them to release asset paths; returns not-ready with an older ready update as last-good while newest is publishing. src/main/updater/releases/updater-release-builds.test.ts: lists hourly builds from the dedicated repo, newest first; lists daily builds from the dedicated repo, newest first; separates stable from rc in the shared main repo; skips drafts and unparseable tags; keeps a composed release title and drops one that repeats the tag; hides builds that published no artifact for this platform; returns an empty list when no build has this platform artifact; keeps mac builds visible on macOS regardless of the Windows leg; resolves the platform installer download url; leaves the installer url null when the release published no installer; tolerates a release whose assets are missing or malformed; sends the local gh token as a bearer header when one is available; sends no authorization header when gh has no token; retries unauthenticated once when GitHub rejects the token; does not retry a 401 that was already unauthenticated; falls back to the per-IP bucket when the token is rate limited and tells the gh breaker; reports a secondary limit carrying retry-after without retrying or tripping the breaker; records a primary limit in the token scope %s; keeps %s authenticated when only %s is blocked; skips the token while its scope %s is blocked; surfaces a rate limit with its reset time and a sign-in hint when unauthenticated; omits the sign-in hint when the rate-limited request was authenticated; treats 429 as a rate limit; reports a 403 without rate-limit headers as a plain HTTP error; reports a missing hourly repo distinctly; is null when GitHub sent no reset; prefers retry-after over the primary reset epoch; falls back to the primary reset epoch when there is no retry-after; reads retry-after as seconds; reads retry-after as an HTTP date; pins an hourly tag at the hourly repo download path; pins a daily tag at the daily repo download path; pins a stable tag at the main repo download path; rejects a tag that is not a version. src/main/updater/updater.build-channel-selection.test.ts: uses the display label in the unsupported-platform %s pinned-build error; still pins %s from an unsigned Windows dev build; restores ordinary release checks after local build selection fails; opts into the RC channel when checkForUpdatesFromMenu is called with includePrerelease; pins the generic feed to a perf-tagged prerelease when requested; surfaces no-update feedback when no newer perf-tagged prerelease exists; keeps prerelease publishing-window misses on the generic retry path; leaves the feed URL alone for a normal user-initiated check. src/main/updater/updater.check-preflight.test.ts: ignores a stale update-not-available event after a new check starts preflight; deduplicates repeated manual checks while the immediate checking status is active. src/main/updater/updater.prerelease-fallback.test.ts: retries a prerelease check once against the previous feed tag when the manifest is missing; surfaces a promise-only prerelease fallback failure after the primary error event. src/main/updater/updater.publishing-window-feed.test.ts: repins the generic feed to the newest RC tag for a prerelease user; repins the generic feed to a newer stable tag for a prerelease user; pins a stable fallback when Atom has no newer prerelease; uses last-good concrete feed when a user-initiated check lands during publishing; can offer an older fully published update while the newest release is publishing; keeps background publishing-window fallback on the short retry cadence. src/main/updater/updater.quit-and-install.test.ts: surfaces an accepted retry before electron-updater emits download progress; defers quitAndInstall and runs its launcher within the launch PATH scope; runs pre-quit cleanup before local PTY cleanup during update install; keeps optional pre-quit cleanup fail-and-continue behavior by default; ignores duplicate quitAndInstall requests while the shared delay is pending; arms the forced-exit watchdog once the install commits; disarms the forced-exit watchdog when sync install error recovery keeps the app open. src/main/window/createMainWindow-markdown-editor-focus.test.ts: ignores traffic light sync IPC on non-macOS; still intercepts Cmd+Shift+B and Cmd+Alt+B when the markdown editor is focused; coerces non-boolean setMarkdownEditorFocused payloads to false; opens a table-aware context menu synchronously without a renderer query; builds the plain edit menu for the one right-click the renderer marks as plain text. src/main/window/createMainWindow-renderer-crash-recovery.test.ts: notifies the caller when the renderer process is gone; passes the renderer webContents id through crash recording and recovery callbacks; forwards expected renderer teardowns so the recorder can diagnose suppression; reloads the app shell after an unexpected renderer process loss; does not reload after renderer loss when recovery is disabled; stops auto-reloading after a rapid renderer crash loop trips the breaker. src/main/window/dashboard-popout-window.test.ts: updates the title after language initialization and unsubscribes when closed; lets its preload expose saved WSL hosts in serve-only, and passes nothing otherwise; creates a native-frame window with the shared preload and no webview surface; shows the window on ready-to-show; loads the prod file entry; loads the dev server URL when in dev; focuses the existing window instead of creating a second one; trusts only the live popout webContents; restores a minimized window when re-requested; restores valid persisted bounds; discards off-screen persisted bounds and falls back to defaults; persists bounds on resize after the debounce, guarding near-minimum sizes; keeps saving bounds after a vetoed quit and freezes them only on an allowed quit; closeDashboardPopout closes an open window; applies the persisted app zoom level on dom-ready; follows app zoom changes while open and unsubscribes on close; zoomDashboardPopoutIfFocused steps the popout zoom only while focused; handles the zoom-in chord via before-input-event and ignores other keys; handles mouse-wheel zoom requests outside before-input-event; respects zoom keybinding overrides for keyboard and mouse-wheel paths. src/main/window/dropped-path-preparation.test.ts: opens and stores each unique source once as drop size grows tenfold; passes ordinary paths without copying for %s; preserves ordinary successes and copied successes when another file fails; serializes copy requests from different owners; reports all lost paths without a shared reason when their failures differ. src/main/window/main-window-updater-deferred-setup.test.ts: releases all 64 completed fallback handles without repeating initialization; keeps setup after ready-to-show and releases its fallback afterward; preserves the 15-second fallback when first paint never arrives; preserves destroyed-window guard reads before and at the fallback deadline; keeps the exact %s error and releases its completed fallback; keeps the exact fallback %s error without retrying initialization; preserves pending manual setup after failed ready registration; keeps setup options, live store reads, nudge writes and required quit flush. src/main/worker-threads/worker-thread-request-queue.test.ts: posts one request at a time and in the order it was dispatched; fires a posted call at its own deadline; stops respawning and fails the rest of the queue once deaths hit the cap; clears the death count when a fresh burst starts from full idle. src/main/workspace-hooks/hooks-setup-runner-script.test.ts: builds Windows runners for newline-heavy scripts without line-array splitting; builds POSIX runners without regex-wide CRLF normalization; writes POSIX setup runners for shebang-declared scripts on native Windows paths; keeps batch setup scripts on cmd.exe when the terminal is Git Bash; hands a Git Bash pane a launch command MSYS cannot rewrite for a cmd runner; replays interpreter flags declared on the shebang line; preserves cmd.exe setup runner semantics for configured cmd users; keeps POSIX runner behavior on POSIX platforms; waits when either local or project policy requires completed setup; marks setup-runner terminals for the always-on credential guard; maps git-bash to POSIX setup launch metadata on Windows; falls back to the cmd runner when the git-bash setting has no installed Git Bash; keeps the cmd runner for a non-Git bash such as Cygwin; keeps the cmd runner for a bare bash whose flavor cannot be resolved; uses the POSIX runner for a bare bash that resolves to Git Bash; uses the POSIX runner for an extension-less Git Bash path; preserves the existing cmd runner for PowerShell terminals; preserves cmd setup compatibility when a Windows-host project has a WSL shell setting; classifies an installed explicit Git Bash executable as a POSIX runner; falls back to the cmd runner when the explicit Git Bash path no longer exists. src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts: schedules remote identity enrichment without blocking the caller; probes a drive project whose runtime is WSL %s; sweeps a local repo: %s; probes an SSH row that carries only executionHostId on its own host; keeps same-path rows on two different SSH hosts from sharing one backoff; coalesces concurrent probes for the same repo location; caches no-identity probes briefly so list calls do not retry every time; does not rewrite the no-remote marker on a later retry; resolves a settled no-remote repo once it gains a remote; does not re-probe a resolved identity before the refresh window elapses; re-probes a resolved identity after the refresh window elapses; bounds re-probes per sweep so a large repo list drains gradually; forgets a removed repo location so its deadline cannot outlive the repo; keeps a surviving repo backoff when a sibling repo is removed; probes again when the same location is re-added after its probe was retired; coalesces concurrent sweeps instead of running one pass per list call. src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts: preserves create priority through claim probes on %s; starts the checkout only once the async workspace root resolves; still deduplicates when both callers await the same pending root lookup; namespaces native Windows preparation directories for long paths; deduplicates preparation for the same repo, base, runtime, and workspace root; does not spend a divergence walk when the base matches exactly; claims when the two sides spell the same ref differently; evicts a repo's own stale preparation before another repo's; still discards armed checkouts when the project runtime needs repair; routes preparation and finalization through the selected WSL runtime; retries stale cleanup after a transient listing failure; does not discard a detached worktree with caller-controlled preparation metadata; does not re-arm after an isolated create; re-arms a preparation once creates arrive in a burst; holds the re-arm checkout until the create runs the deferred thunk; starts one explicit prefetch after the create completes; does not re-arm when finalization failed; reports a pending create while a stale-cleanup scan is running. src/main/workspaces/removal/local-worktree-removal-recovery.test.ts: recovers Git for Windows partial filesystem deletion failures; finishes a clean non-force deletion after Git leaves a Windows directory behind; recovers localized Windows failures after Git already removed the registration; does not recover unrelated localized failures while Git still owns the row; finishes a macOS deletion Git deregistered before failing with Directory not empty; leaves an orphaned checkout to the orphan cleanup instead of deleting it; prunes and strictly verifies on the selected WSL host without deleting files or branches. src/main/workspaces/removal/worktree-removal-safety.test.ts: rejects deleting a worktree that contains another registered worktree; rejects POSIX home directories even when host homedir has a different path shape; refuses a home the host reported even when no path rule recognises it; refuses the Windows host's home directory from a POSIX client; refuses the Windows host's home directory even when the host reported nothing. src/main/wsl/discovery/distro-catalog.test.ts: retries asynchronous discovery after a transient wsl.exe failure; retries synchronous discovery after a transient wsl.exe failure; retries asynchronous discovery after wsl.exe reports no distros yet; retries synchronous discovery after wsl.exe reports no distros yet; bounds the wsl.exe spawn rate while no distros are installed; bounds the asynchronous spawn rate while no distros are installed; still caches a non-empty distro list for the process lifetime; re-probes a docker-desktop-only machine once a user distro can appear; backs off while the list keeps coming back empty; backs off after repeated distro-list failures; caps the empty-list backoff at five minutes; keeps reporting an empty result after it goes stale; keeps reporting a known distro list indefinitely; bounds cached homes while retaining the most recently used distros; still lists distros, and an excluded distro home probe fails like any other probe; gives the async home probe time for a cold boot instead of killing it at 5 s; retries availability after a probe timeout instead of latching false; bounds the probe rate while the failure window is open; caches a successful probe for the process lifetime; names an explicit spawn directory, so no deleted cwd can read as ENOENT; shares one wsl.exe spawn between concurrent probes; keeps reporting the last observed answer after it goes stale; holds a definitive failure far longer than a timeout when %s; backs off after repeated probe failures; re-probes a seeded retryable failure once its window lapses; re-probes availability once a distro list succeeds after %s; does not drop an availability failure for an empty distro list; keeps reporting unavailable off Windows without probing. src/main/wsl/discovery/wsl-distro-holder.test.ts: runs a busybox-safe loop through --exec and names the distro; spawns a detached-style holder, records it, and waits for the distro to run; a holder exiting with code 1 notes its distro may have stopped (E9); rejects a pid whose command line is not our holder for that distro; cleans up stale and corrupt records; keeps a holder and its record when release cannot verify it; reports unverifiable when the command line is unreadable even with a matching pid; release kills a verified holder and removes its record; release never kills a pid that is no longer our holder; reports a spawned holder exit so liveness can re-check. src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts: skips 9p shares that are not drvfs, and malformed lines. src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts: plans the update on the census the running orcad reports, not an unknown one; forwards force to the update planner; does not serve the incumbent past a refusal that is not a wait; does not re-activate the build this host rolled back from; labels the launch with the build the adoption found serving, not the stale record; defers while another run holds the host fence; lets an explicit force deploy past both skips; names a newer host refusal apart from a rolled-back one, so only Force is offered; updates an older host as before, without asking to adopt it; never asks the incumbent when it already runs this build. src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts: keeps a completed listing usable when the host rejects the wait parameter. src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts: delivers to chat-default users in all targeting while holding out not-switched users. src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts: completes the row on a pick, even when the command is already typed; ignores a pick of the row while side chats are unavailable. src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts: explains a too-large refusal that arrives through the IPC error prefix. src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts: keeps the question with the caller and says once that it never went; tells the user to check the side chat when delivery is unconfirmed; reports a delivered question as sent, silently. src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts: decides each of %i tool-only turns once per layout, and nothing without a listener. src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx: places a side chat whose question was %s: %o. src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts: calls back once for %s; stops watching once unsubscribed. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts: routes terminal input through deferPtyInput so the host can withhold it; forwards terminal input directly when the host supplies no deferPtyInput. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts: requests a tab remount for an unbound spawn; leaves recovery to a remote transport that armed its own retry; requests a remount when the transport reports no recovery of its own; settles the spawn as failed before requesting a remount; prefers the restored leaf id when reporting the anomaly; falls back to the pane leaf id when no restored leaf exists. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionDeferredInputForwardingTests } from '../input/pty-connection-deferred-input-forwarding.spec', registerPtyConnectionDeferredInputForwardingTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts: registers interest on the first sidecar and releases on the last unsubscribe; releases sidecar interest only once for repeated unsubscribes; does not let an eager pre-mount buffer defeat hidden delivery gating; keeps eager buffers outside delivery interest when the PTY exits before mount; lets a sidecar exclusively own interest while an eager buffer overlaps. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts: blackholed delivery reproduces the wedge: no handler dispatch, no ACK ever. src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts: sends preferences to the execution host and attaches only to its returned PTY; preserves one operation ID across a lost reply and reconnect; preserves ordinary raw startup and captured-session attachment. src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts: sums registered gauges and drops disposed ones; ignores a repeated dispose instead of dropping another gauge; stops tracking new gauges past the cap so a missed dispose cannot grow it; tracks a live output processor queue through enqueue, drain, and dispose; excludes cleared consumed entries from retention after a bounded drain. src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts: says nothing once the pane is closed. src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts: refreshes after each scheduled atlas reset; falls back to a timeout when animation frames are unavailable; continues recovery when a manager throws after scheduling. src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts: tracks a remounted quiet title source even when the stale owner unregisters later; preserves the renderer-parsed output sequence in the response; preserves a pending escape tail for snapshot replay; routes a host's Reset Terminal request to the pane that owns the PTY. src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts: marks panes with restored scrollback for fresh-shell viewport blanking. src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts: recovers a 0x0 spawn whose container is briefly unmeasurable then settles. src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts: removes global listeners when the last pane unregisters. src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx: keeps trust text readable on a host-owned dialog surface; applies the hostile surface to ordinary dialogs, so the case above is exercised. src/renderer/src/components/use-terminal-parking-pass.test.tsx: does not queue a render when a pass produces the same parking sets; keeps parking transitions working under StrictMode. src/renderer/src/hooks/client-workspace-view-report.test.ts: reports an away user’s screen with no presence, and renews as soon as input returns; retries a failed send, empty or not, no sooner than a refresh. src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts: is new work in a workspace with no live terminal: its first bind moves it up in Recent. src/renderer/src/hooks/use-bundled-skill-install.test.tsx: ignores a repeated click while the install runs; retries the last requested skills on this host. src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx: adds seeds to a successful empty list but not to loading or failed results; retains seed projection after expiry and fetches fresh metadata for a new reader. src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx: retranslates the settings nav labels when the UI language changes live. src/renderer/src/lib/codex-stale-pane-account-identity.test.ts: keeps the prompt when the roster read fails and every label collapses. src/renderer/src/lib/image-blob-png.test.ts: downscales a pasted image above the pixel cap; releases its temporary URL on a decode error; releases its temporary URL when PNG encoding fails or exceeds the byte cap. src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts: names callers above the frame the write came from; restores Error.stackTraceLimit when the capture throws; stops collecting after the sample cap when captureStackTrace is unavailable; caps reported changed keys from a single wide write. src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts: applies the rendered text hard cap last and reserves the final overflow marker. src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts: keeps the runtime target identity stable across unrelated store writes. src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts: keeps creation available on old hosts and explains the missing operation; preserves landed warnings and direct collision recovery data; propagates remote discovery failure instead of a false empty page. src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts: reuses unchanged worktree tab projections when one worktree title changes; bumps only the changed worktree version when a sibling stays byte-identical. src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts: shares safe-auto fork sync cooldown attempts across store instances. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts: collapses a 193-workspace hydration to one store write; leaves the store byte-identical to the per-workspace path; re-reconciling the batched result is a no-op, as it is for the per-workspace path. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts: dedicated zero-case helper retirement; no authored test credit. src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts: persists each batch metadata update to its workspace owner. src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts: dismisses a rename error on its capable remote owner; clears pending first-agent rename when the title is updated. src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts: orders capture, guards, handlers, main's stop, commit, cleanup, and exit settlement. src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts: publishes the first terminal and root tab group atomically; publishes the first terminal and root tab group atomically, then marks it starting in main. src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts: restores daemon terminal wake hints before declaring the session ready. src/renderer/src/web/web-runtime-connection-auth-framing.test.ts: keeps legacy framing for sockets that cannot absorb a refused attempt. src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts: moves the old Windows default to Regular once and queues the notice; keeps custom weights and fresh profiles without a notice; leaves macOS and Linux profiles untouched. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/persistence/worktree-sort-order-write.test.ts, src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts, src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts, src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts, src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts, src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts, src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts, src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts, src/main/runtime/session-graph/headless-runtime-graph.spec.ts, src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts, src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts, src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts, src/main/runtime/terminal/identity/terminal-identity-probe.test.ts, src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts, src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts, src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts, src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts, src/main/runtime/terminal/surface/workspace-layout-projection.test.ts, src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts, src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts, src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts, src/main/skills/skill-install-transaction.test.ts, src/main/speech/model-manager-download-resume.test.ts, src/main/ssh/config/ssh-config-parser.test.ts, src/main/ssh/config/ssh-known-hosts-source.test.ts, src/main/ssh/config/ssh-known-hosts.test.ts, src/main/ssh/connection/ssh-connect-config.test.ts, src/main/ssh/connection/ssh-connection-auth-fallback.test.ts, src/main/ssh/connection/ssh-connection-store.test.ts, src/main/ssh/connection/ssh-connection.test.ts, src/main/ssh/orcad-migration-stuck-host-profiles.test.ts, src/main/ssh/orcad-runtime-maintenance.test.ts, src/main/ssh/port-forwarding/ssh-port-forward.test.ts, src/main/ssh/ssh-channel-multiplexer.test.ts, src/main/ssh/system-transport/system-ssh-forward-process.test.ts, src/main/ssh/system-transport/system-ssh-loopback-route.test.ts, src/main/startup/browser-process-user-agent-ordering.test.ts, src/main/startup/quit/quit-path-durable-write-blocking.test.ts, src/main/stats/agent-session-transition-recorder.test.ts, src/main/text-generation/commit-message-text-generation-model-discovery.test.ts, src/main/text-generation/pull-request-context.test.ts, src/main/text-generation/source-control-local-process.test.ts, src/main/updater/linux-package/linux-package-update-recovery.test.ts, src/main/updater/releases/updater-prerelease-feed-readiness.test.ts, src/main/updater/releases/updater-release-builds.test.ts, src/main/updater/updater.build-channel-selection.test.ts, src/main/updater/updater.check-preflight.test.ts, src/main/updater/updater.prerelease-fallback.test.ts, src/main/updater/updater.publishing-window-feed.test.ts, src/main/updater/updater.quit-and-install.test.ts, src/main/window/createMainWindow-markdown-editor-focus.test.ts, src/main/window/createMainWindow-renderer-crash-recovery.test.ts, src/main/window/dashboard-popout-window.test.ts, src/main/window/dropped-path-preparation.test.ts, src/main/window/main-window-updater-deferred-setup.test.ts, src/main/worker-threads/worker-thread-request-queue.test.ts, src/main/workspace-hooks/hooks-setup-runner-script.test.ts, src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts, src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts, src/main/workspaces/removal/local-worktree-removal-recovery.test.ts, src/main/workspaces/removal/worktree-removal-safety.test.ts, src/main/wsl/discovery/distro-catalog.test.ts, src/main/wsl/discovery/wsl-distro-holder.test.ts, src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts, src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts, src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts, src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts, src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts, src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts, src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx, src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts, src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts, src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts, src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts, src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts, src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts, src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts, src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts, src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx, src/renderer/src/components/use-terminal-parking-pass.test.tsx, src/renderer/src/hooks/client-workspace-view-report.test.ts, src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts, src/renderer/src/hooks/use-bundled-skill-install.test.tsx, src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx, src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx, src/renderer/src/lib/codex-stale-pane-account-identity.test.ts, src/renderer/src/lib/image-blob-png.test.ts, src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts, src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts, src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts, src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts, src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts, src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts, src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts, src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts, src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts, src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts, src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts, src/renderer/src/web/web-runtime-connection-auth-framing.test.ts, src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", @@ -9048,7 +9082,15 @@ "Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", "Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. All prior notes and dated/archived evidence retain original scopes.", "Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes." + "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", + "Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed.", + "Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope.", + "Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection.", + "Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope.", + "Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope.", + "Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope.", + "Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed.", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -9284,7 +9326,7 @@ "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["linux"], "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", + "coverageNotes": "Audit3554 intentionally removes the whole worktrees-ssh-repo-owner-resolution suite (2 authored cases). Dedicated duplicate-exact/ambiguous-legacy owner refusal and fixed runtime-host/wrong-target/missing-authority/zero-owner/contradictory-owner status alarms are lost. The suite did not exercise an authority transition or actual SSH listing; its no-local-Git spy was also unreachable on an admitted SSH metadata-only route. Remaining suites are not equivalent replacements. Current selectors have no fresh execution from this static packet; historical receipts retain their original scope. No new SSH/provider/native/UI/mobile/mixed-version/cross-platform result is claimed. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -9299,14 +9341,14 @@ "https://github.com/stablyai/orca/issues/12902" ], "invariant": "SSH, WSL, and remote-runtime restore paths must treat provider listing failures and unknown liveness as unknown, not dead, while still avoiding duplicate spawn and clearing expired relay leases exactly once. Direct SSH disconnect, reconnect, and wake must keep PTY bindings and relay identity, and target snapshot hydration/reconnect cannot reset sibling SSH, local, WSL, or runtime-owned state. Every restored remote terminal must preserve its provider PTY identity, including the authoritative incarnation returned by a successful session-ID reattach. After a recoverable partition the same authenticated runtime must reattach the same PTY, reject detached input, apply the latest viewport, and report healthy only after authoritative replay. A successful one-shot reachability probe may replace a pre-ready shared-control socket, but waiting RPCs must continue onto the replacement under their original deadline without duplicate host delivery or retained request bytes. Automatic PTY recovery stops after one bounded minute without a fatal terminal error; a manual reconnect starts a newly fenced epoch against the same PTY, and closed panes retain no recovery UI state. Successful current-transport recovery must clear every stale error surfaced for that pane without clearing or displaying a sibling pane's error; a later genuine failure must remain visible. Each transport retains at most eight suppressed messages, each pane retains at most eight distinct messages, and the rendered surface retains at most 24 lines and 4,000 characters. One capability-gated terminal-create mutation must produce at most one host PTY across an unknown response outcome, remain manually retryable after cutoff, and never let a stale completion replace a newer pane lifecycle. Reconnect must alternate exact activation with authoritative inventory so neither a stale activation response nor an activation failure can strand or retire a pane, and activating a parked surface whose persisted binding was already retired must respawn it rather than report a changed owner after signalling its exit.", - "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples.", + "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples. Preload layout cleanup retires the mock SSH forwarding/type-census suite without replacement: preload wiring alarms are lost; shared authority-admission tests cover narrower behavior. Historical receipts retain their original scope.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "pnpm run build:web-from-renderer", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -9325,16 +9367,13 @@ "src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", "src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts", "src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts", - "src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts", "src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", "tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts", "src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts", "src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts", "src/main/ipc/ssh/ssh.test.ts", - "src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts", "src/main/ssh/connection/ssh-connection-manager.test.ts", "src/main/ssh/connection/ssh-connection.test.ts", - "src/preload/ssh-authority-forwarding.test.ts", "src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts", "src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts", "src/shared/ssh-retained-payload-admission.test.ts" @@ -9385,14 +9424,6 @@ "late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state" ] }, - { - "file": "src/preload/ssh-authority-forwarding.test.ts", - "assertions": [ - "full authority crosses Electron IPC without loss", - "partial authority becomes unknown for bounded reconciliation and malformed full authority is dropped", - "variable-form host-qualified worktree requests retain fail-closed outcomes in their return type" - ] - }, { "file": "src/shared/ssh-retained-payload-admission.test.ts", "assertions": [ @@ -9534,7 +9565,8 @@ "Audit3359 historical original assertionRefs object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts\",\n \"assertions\": [\n \"a stale create completion cannot replace or close a newer attachment, including when two runtimes use the same raw handle\"\n ]\n }", "Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed.", "Audit3368 historical original assertionRefs object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"recovery exposes connecting, recovering, backoff, connected, and fatal-offline phases with fenced epochs\",\n \"ten partition cycles retain one PTY identity, reject detached input, and unsubscribe each epoch exactly once\",\n \"automatic retries stop after one minute with no fatal error, no further requests, and no stale input\",\n \"manual reconnect starts a new epoch, resubscribes the same PTY exactly once, and becomes healthy only after its snapshot\"\n ]\n }", - "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"pnpm run build:web-from-renderer\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\n \"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\n \"src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts\",\n \"src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts\",\n \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\n \"src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts\",\n \"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\n \"src/main/ipc/ssh/ssh.test.ts\",\n \"src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts\",\n \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"src/preload/ssh-authority-forwarding.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"src/shared/ssh-retained-payload-admission.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"assertions\": [\n \"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\n \"assertions\": [\n \"the automatic-recovery deadline cancels pending backoff and a manual retry owns a new epoch\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"assertions\": [\n \"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"assertions\": [\n \"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\n \"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\n \"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\n \"in-flight mutation coordination is bounded and releases capacity after settlement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"assertions\": [\n \"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"assertions\": [\n \"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"\n ]\n },\n {\n \"file\": \"src/preload/ssh-authority-forwarding.test.ts\",\n \"assertions\": [\n \"full authority crosses Electron IPC without loss\",\n \"partial authority becomes unknown for bounded reconciliation and malformed full authority is dropped\",\n \"variable-form host-qualified worktree requests retain fail-closed outcomes in their return type\"\n ]\n },\n {\n \"file\": \"src/shared/ssh-retained-payload-admission.test.ts\",\n \"assertions\": [\n \"retained connection states reject partial or malformed authority\",\n \"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\n \"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"assertions\": [\n \"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"assertions\": [\n \"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\n \"an unknown target triggers an authoritative list reread\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"assertions\": [\n \"a StrictMode remount joins the pending spawn instead of starting a second one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"assertions\": [\n \"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"\n ]\n }\n ]" + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"pnpm run build:web-from-renderer\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\n \"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\n \"src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts\",\n \"src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts\",\n \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\n \"src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts\",\n \"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\n \"src/main/ipc/ssh/ssh.test.ts\",\n \"src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts\",\n \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"src/preload/ssh-authority-forwarding.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"src/shared/ssh-retained-payload-admission.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"assertions\": [\n \"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\n \"assertions\": [\n \"the automatic-recovery deadline cancels pending backoff and a manual retry owns a new epoch\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"assertions\": [\n \"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"assertions\": [\n \"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\n \"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\n \"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\n \"in-flight mutation coordination is bounded and releases capacity after settlement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"assertions\": [\n \"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"assertions\": [\n \"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"\n ]\n },\n {\n \"file\": \"src/preload/ssh-authority-forwarding.test.ts\",\n \"assertions\": [\n \"full authority crosses Electron IPC without loss\",\n \"partial authority becomes unknown for bounded reconciliation and malformed full authority is dropped\",\n \"variable-form host-qualified worktree requests retain fail-closed outcomes in their return type\"\n ]\n },\n {\n \"file\": \"src/shared/ssh-retained-payload-admission.test.ts\",\n \"assertions\": [\n \"retained connection states reject partial or malformed authority\",\n \"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\n \"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"assertions\": [\n \"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"assertions\": [\n \"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\n \"an unknown target triggers an authoritative list reread\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"assertions\": [\n \"a StrictMode remount joins the pending spawn instead of starting a second one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"assertions\": [\n \"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"\n ]\n }\n ]", + "Audit3554 intentionally removes the whole worktrees-ssh-repo-owner-resolution suite (2 authored cases). Dedicated duplicate-exact/ambiguous-legacy owner refusal and fixed runtime-host/wrong-target/missing-authority/zero-owner/contradictory-owner status alarms are lost. The suite did not exercise an authority transition or actual SSH listing; its no-local-Git spy was also unreachable on an admitted SSH metadata-only route. Remaining suites are not equivalent replacements. Current selectors have no fresh execution from this static packet; historical receipts retain their original scope. No new SSH/provider/native/UI/mobile/mixed-version/cross-platform result is claimed." ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, @@ -9736,7 +9768,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1619 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts: Loses direct timestamp-formula assertion; no useful independent alarm in removed registration. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1391: src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts reduced. Lose explicit one-read/unchanged-style work budget across 30 syllables and single-timer burst alarm. Synthetic screen bounds/terminal cursor bound retained proof to DOM anchor updates, not actual OS IME placement. src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts reduced. Lose explicit PC-101 alternate omission, multi-codepoint/control associated text filtering, lock modifier integer, shifted punctuation, standalone separator and printable nonfunctional keypad fallbacks. Retained pure encoding is a wire-contract check without host input delivery. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts reduced. Lose standalone handled Ctrl, Shift+Space, shifted non-ASCII keydown and active-composition backspace/arrow/text/Process suppression alarms. No actual IME/PTY encoding occurs. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/lib/keyboard-layout/option-as-alt-probe.test.ts removed. Intentionally loses invalidation, focus/manual refresh gating and stale/newest generation settlement outcomes, including direct stale category suppression. No equivalent replacement or default preload input-source delivery claim. src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts removed. Intentionally loses substituted sentence punctuation, shifted/backslash/multi-unit/full-width/letter input and Kitty flag/release/report encoding alarms across14 authored registrations. No equivalent replacement or real pane/browser input delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Preload layout cleanup retires the complete mocked macOS keyboard bridge registration. Its API-read forwarding, two-phase payload forwarding and exact listener-disposer alarms are intentionally lost without equivalent replacement. The remaining restart/checkpoint registrations do not cover this IME contract. Unaffected dated receipts retain their original commands and scope; this metadata change claims no new execution. Previous account (preserved verbatim): Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts. Previous account (preserved verbatim): Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1619 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts: Loses direct timestamp-formula assertion; no useful independent alarm in removed registration. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1391: src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts reduced. Lose explicit one-read/unchanged-style work budget across 30 syllables and single-timer burst alarm. Synthetic screen bounds/terminal cursor bound retained proof to DOM anchor updates, not actual OS IME placement. src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts reduced. Lose explicit PC-101 alternate omission, multi-codepoint/control associated text filtering, lock modifier integer, shifted punctuation, standalone separator and printable nonfunctional keypad fallbacks. Retained pure encoding is a wire-contract check without host input delivery. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts reduced. Lose standalone handled Ctrl, Shift+Space, shifted non-ASCII keydown and active-composition backspace/arrow/text/Process suppression alarms. No actual IME/PTY encoding occurs. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/lib/keyboard-layout/option-as-alt-probe.test.ts removed. Intentionally loses invalidation, focus/manual refresh gating and stale/newest generation settlement outcomes, including direct stale category suppression. No equivalent replacement or default preload input-source delivery claim. src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts removed. Intentionally loses substituted sentence punctuation, shifted/backslash/multi-unit/full-width/letter input and Kitty flag/release/report encoding alarms across14 authored registrations. No equivalent replacement or real pane/browser input delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6699", "https://github.com/stablyai/orca/pull/6682", @@ -9747,13 +9779,13 @@ "https://github.com/stablyai/orca/pull/17170" ], "invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY. A live preedit must stay visible across an IME-resumed transaction, preserve every committed row-tail cell hidden by its opaque overlay, mask only a structurally verified Codex or Claude placeholder and never a row carrying typed text, keep the themed insertion caret and native candidate anchor inside the terminal at the final column, and clean up without stale overlay children or ownership classes. Layout-native Option text must preserve negotiated CSI-u alternate/associated fields and lock modifiers, distinguish repeat from press, and resolve releases with the press's primary identity plus the actual keyup modifiers without exposing a partial or stale layout refresh. An in-focus macOS input-source change must invalidate both renderer authorities before the next key can use the old source. When the snapshot source proves kitty state, macOS Preview commits must use the application's effective flags after the sequenced snapshot and every proven replay/live transition, and a claimed press delivered under report_event_types must produce exactly one matching release regardless of whether keyup arrives before or after insertText and regardless of xterm's defensive internal reset.", - "oracle": "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Exact outbound bytes from the REAL native-text forwarder behind installPreviewImeBridge after initial snapshot restore, replacement resync, live transitions, and both keydown->insertText->keyup and keydown->keyup->insertText orderings; a wiring-only mock is supporting evidence, not the oracle. The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, resumed Windows event traces reactivate the visible preedit, an opaque mid-line overlay reproduces the committed row tail it covers, arbitrary DIM output remains visible, and final-column layout keeps both caret and textarea candidate anchor within the available screen width. The retained candidate-anchor slice checks layout-read caching, deferred timer coalescing, recognized-screen follow-ups and refit refresh with deterministic DOM fixtures. A Codex frame whose prompt row is bold and whose dimmed model footer sits below a blank gap acquires the mask class while composing; the same placeholder text without that footer, a framed-versus-unframed Claude prompt, a row of arbitrary dimmed output, and a row carrying typed text do not. The class is gone after composition end, after a blur that is not followed by a session end, and after disposal. Rendered Electron/CDP geometry independently proves the overlay reproduces every committed cell it hides, that a real Codex placeholder at column 2 is masked rather than repeated, and that the final-column caret, preedit, and textarea right edges all land inside the screen. Input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and real fcitx4/Sogou captures send only the committed candidate for Space/digit picks while ordinary typing, literal Space and digits stay available. A main/preload/renderer notification chain proves every live window invalidates immediately, the old native read settles before a coalesced refresh signal, and older refreshes are generation-fenced. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text. Real legacy IME commit preservation, native candidate-window placement, and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", + "oracle": "Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts. Previous oracle (preserved verbatim): Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Exact outbound bytes from the REAL native-text forwarder behind installPreviewImeBridge after initial snapshot restore, replacement resync, live transitions, and both keydown->insertText->keyup and keydown->keyup->insertText orderings; a wiring-only mock is supporting evidence, not the oracle. The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, resumed Windows event traces reactivate the visible preedit, an opaque mid-line overlay reproduces the committed row tail it covers, arbitrary DIM output remains visible, and final-column layout keeps both caret and textarea candidate anchor within the available screen width. The retained candidate-anchor slice checks layout-read caching, deferred timer coalescing, recognized-screen follow-ups and refit refresh with deterministic DOM fixtures. A Codex frame whose prompt row is bold and whose dimmed model footer sits below a blank gap acquires the mask class while composing; the same placeholder text without that footer, a framed-versus-unframed Claude prompt, a row of arbitrary dimmed output, and a row carrying typed text do not. The class is gone after composition end, after a blur that is not followed by a session end, and after disposal. Rendered Electron/CDP geometry independently proves the overlay reproduces every committed cell it hides, that a real Codex placeholder at column 2 is masked rather than repeated, and that the final-column caret, preedit, and textarea right edges all land inside the screen. Input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and real fcitx4/Sogou captures send only the committed candidate for Space/digit picks while ordinary typing, literal Space and digits stay available. A main/preload/renderer notification chain proves every live window invalidates immediately, the old native read settles before a coalesced refresh signal, and older refreshes are generation-fenced. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text. Real legacy IME commit preservation, native candidate-window placement, and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts" @@ -9769,7 +9801,6 @@ "src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts", "src/main/ipc/macos-keyboard-layout-change-notifications.test.ts", - "src/preload/app-restart-checkpoint-routing.test.ts", "src/renderer/src/web/web-preload-api-ui.test.ts", "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", "src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts", @@ -9813,14 +9844,6 @@ "rapid input-source changes coalesce to one latest-generation refresh signal" ] }, - { - "file": "src/preload/app-restart-checkpoint-routing.test.ts", - "assertions": [ - "macOS keyboard reads and the change subscription remain wired after main integration", - "the two-phase change payload reaches the renderer unchanged", - "the subscription disposer removes the exact IPC listener" - ] - }, { "file": "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", "assertions": [ @@ -9905,6 +9928,7 @@ "Pair with Windows ConPTY keyboard reset for Windows standard-key behavior." ], "knownGaps": [ + "Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts.", "NEXT65 current scope qualification: The NEXT65 knownGaps entries below govern the changed selectors and qualify any broader coverage implication in this gate’s unchanged oracle/coverageNotes narratives. Those narratives and preserved dated evidenceRuns retain their historical text and original exact execution scopes only; no fresh execution, transferred pass or equivalent replacement coverage is claimed. Upstream case removals remain upstream; original NEXT65 proposal descriptions grant no duplicate retirement credit.", "NEXT65 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts, src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence.", "NEXT65 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ]\ntestFiles: [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts\",\n \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts\",\n \"assertions\": [\n \"With supplied geometry, competing xterm render and Orca clamp preserve final-cell caret/candidate anchor positions.\",\n \"Actual xterm buffer repaint updates the row tail while the preedit remains open.\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\"A transaction inferred from update alone commits and cleans up.\"]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"Autorepeat cannot replace the first release sender; a fresh press can replace an orphaned sender for the same key.\"\n ]\n },\n {\n \"file\": \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"assertions\": [\n \"rapid input-source changes coalesce to one latest-generation refresh signal\"\n ]\n },\n {\n \"file\": \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"assertions\": [\n \"macOS keyboard reads and the change subscription remain wired after main integration\",\n \"the two-phase change payload reaches the renderer unchanged\",\n \"the subscription disposer removes the exact IPC listener\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"assertions\": [\n \"the real forwarder behind the Preview bridge encodes the commit from the snapshot-proven flags before any live output\",\n \"flags 0/1 commit raw text, flags 2 add one CSI-u release, flags 8 emit one CSI-u press, and flags 10 emit a CSI-u press followed by exactly one release\",\n \"both keydown->insertText->keyup and keydown->keyup->insertText orderings produce the same bytes\",\n \"the release is emitted by the forwarder while xterm's internal kitty flags stay 0\",\n \"the mutable flags getter is read exactly once, at commit time, never on keydown or keyup\",\n \"auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"assertions\": [\n \"the Preview hands the forwarder the live kitty mirror seeded from the snapshot's proven flags\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a fresh PTY's known 0 is distinguishable from a snapshot's unproven 0 fallback\",\n \"restoreSnapshotFlags proves only the active screen\",\n \"provenance survives absolute sets, screen switches, RIS and DECSTR, but a pop past omitted push history returns to unknown rather than a manufactured 0\"\n ]\n },\n {\n \"file\": \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"assertions\": [\n \"a partially covered sequenced chunk retains exactly its unseen suffix in live mode\",\n \"a transformed overlap remains unsliced in replay mode\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]", @@ -9948,7 +9972,8 @@ "Audit1896 historical assertion inventory for three retired and three narrowed refs; not current validated assertions. Original raw assertion objects follow:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-trailing-preedit-occlusion.test.ts\",\n \"assertions\": [\n \"rolling Korean input keeps only the uncommitted trailing syllable in the themed overlay\",\n \"the overlay remains anchored to the live cursor cell and clears after commit\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/xterm-bypass-policy-non-mac.test.ts\",\n \"assertions\": [\n \"standalone Linux 229 keydowns reach xterm while Windows 229 keydowns stay suppressed\",\n \"candidate Space/digit selectors are suppressed only while candidate guards are active\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/paste/terminal-paste-runtime.test.ts\",\n \"assertions\": [\"paste/runtime forwarding avoids duplicate terminal payloads\"]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts\",\n \"assertions\": [\n \"a mid-line preedit reproduces committed cells hidden by its opaque overlay and refreshes that tail after terminal renders\",\n \"arbitrary fully dimmed output remains visible even at column zero\",\n \"the final-column caret stays visible and the textarea candidate anchor shifts left with an over-wide preedit\",\n \"cancel, empty resumed updates, and disposal remove transient overlay state\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\n \"recorded Windows Korean compositionupdate-without-compositionstart traces reactivate a visible preedit transaction\",\n \"the resumed transaction commits exactly once and cleans up normally\",\n \"the ordinary Linux compositionstart sequence remains unchanged\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"owned releases use live Shift and Option state and current alternate-key flags\",\n \"owned releases retain the delivered press identity across layout, Shift, and NumLock changes\",\n \"a native dead-key keyup is consumed without inventing an unmatched protocol release\",\n \"event-type pop consumes without bytes and repeat keydowns cannot replace the original release owner\"\n ]\n }", "Renderer direct-owner cleanup retires the complete layout-base-character suite (one registration). Lost alarm: layout invalidation blocks focus refresh, fences an older snapshot, and accepts the new-generation character. The removed case consumed private snapshot/reset state and internal refresh-count accounting. No equivalent replacement or new execution is claimed. Remaining IME/keyboard/provider sources and the unchanged fcitx4 receipt retain their existing bounded qualifications; this removal does not validate their selectors. Historical removed active mappings (verbatim semantic values; no longer active): [{\"field\":\"testFiles\",\"previous\":[\"src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts\"]},{\"field\":\"commands\",\"previous\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\"]}]", "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3460 historical original active selectors (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ]\ntestFiles: [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\"A transaction inferred from update alone commits and cleans up.\"]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"Autorepeat cannot replace the first release sender; a fresh press can replace an orphaned sender for the same key.\"\n ]\n },\n {\n \"file\": \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"assertions\": [\n \"rapid input-source changes coalesce to one latest-generation refresh signal\"\n ]\n },\n {\n \"file\": \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"assertions\": [\n \"macOS keyboard reads and the change subscription remain wired after main integration\",\n \"the two-phase change payload reaches the renderer unchanged\",\n \"the subscription disposer removes the exact IPC listener\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"assertions\": [\n \"the real forwarder behind the Preview bridge encodes the commit from the snapshot-proven flags before any live output\",\n \"flags 0/1 commit raw text, flags 2 add one CSI-u release, flags 8 emit one CSI-u press, and flags 10 emit a CSI-u press followed by exactly one release\",\n \"both keydown->insertText->keyup and keydown->keyup->insertText orderings produce the same bytes\",\n \"the release is emitted by the forwarder while xterm's internal kitty flags stay 0\",\n \"the mutable flags getter is read exactly once, at commit time, never on keydown or keyup\",\n \"auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"assertions\": [\n \"the Preview hands the forwarder the live kitty mirror seeded from the snapshot's proven flags\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a fresh PTY's known 0 is distinguishable from a snapshot's unproven 0 fallback\",\n \"restoreSnapshotFlags proves only the active screen\",\n \"provenance survives absolute sets, screen switches, RIS and DECSTR, but a pop past omitted push history returns to unknown rather than a manufactured 0\"\n ]\n },\n {\n \"file\": \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"assertions\": [\n \"a partially covered sequenced chunk retains exactly its unseen suffix in live mode\",\n \"a transformed overlap remains unsliced in replay mode\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]" + "Audit3460 historical original active selectors (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ]\ntestFiles: [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\"A transaction inferred from update alone commits and cleans up.\"]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"Autorepeat cannot replace the first release sender; a fresh press can replace an orphaned sender for the same key.\"\n ]\n },\n {\n \"file\": \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"assertions\": [\n \"rapid input-source changes coalesce to one latest-generation refresh signal\"\n ]\n },\n {\n \"file\": \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"assertions\": [\n \"macOS keyboard reads and the change subscription remain wired after main integration\",\n \"the two-phase change payload reaches the renderer unchanged\",\n \"the subscription disposer removes the exact IPC listener\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"assertions\": [\n \"the real forwarder behind the Preview bridge encodes the commit from the snapshot-proven flags before any live output\",\n \"flags 0/1 commit raw text, flags 2 add one CSI-u release, flags 8 emit one CSI-u press, and flags 10 emit a CSI-u press followed by exactly one release\",\n \"both keydown->insertText->keyup and keydown->keyup->insertText orderings produce the same bytes\",\n \"the release is emitted by the forwarder while xterm's internal kitty flags stay 0\",\n \"the mutable flags getter is read exactly once, at commit time, never on keydown or keyup\",\n \"auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"assertions\": [\n \"the Preview hands the forwarder the live kitty mirror seeded from the snapshot's proven flags\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a fresh PTY's known 0 is distinguishable from a snapshot's unproven 0 fallback\",\n \"restoreSnapshotFlags proves only the active screen\",\n \"provenance survives absolute sets, screen switches, RIS and DECSTR, but a pop past omitted push history returns to unknown rather than a manufactured 0\"\n ]\n },\n {\n \"file\": \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"assertions\": [\n \"a partially covered sequenced chunk retains exactly its unseen suffix in live mode\",\n \"a transformed overlap remains unsliced in replay mode\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]", + "Preload layout cleanup retires the complete mocked macOS keyboard bridge registration. Its API-read forwarding, two-phase payload forwarding and exact listener-disposer alarms are intentionally lost without equivalent replacement. The remaining restart/checkpoint registrations do not cover this IME contract. Unaffected dated receipts retain their original commands and scope; this metadata change claims no new execution. Retired assertion reference: {\"file\":\"src/preload/app-restart-checkpoint-routing.test.ts\",\"assertions\":[\"macOS keyboard reads and the change subscription remain wired after main integration\",\"the two-phase change payload reaches the renderer unchanged\",\"the subscription disposer removes the exact IPC listener\"]}" ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." }, @@ -10248,7 +10273,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3800", "https://linear.app/stably/issue/STA-3904", @@ -10258,17 +10283,17 @@ "https://github.com/stablyai/orca/issues/14347" ], "invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and submit exactly once only after the agent can accept Enter. Local worker-start with supported observation must preserve an unobserved turn as start_unknown without revoking authority, closing questions, or triggering a rescue Enter; a worker report during observation must settle normally. Claude and Codex must emit a post-paste composer marker and then settle, or reach the bounded fallback first; every other agent retains the platform delay.", - "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-launch/startup/agent-prompt-injection.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration/runs/tasks-dispatch.test.ts src/main/runtime/orchestration/coordinator/coordinator.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts --reporter=dot", "node tests/tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000" ], "testFiles": [ "src/shared/agent-launch/startup/agent-prompt-injection.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "src/main/runtime/rpc/methods/orchestration/runs/tasks-dispatch.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts", "src/main/runtime/orchestration/coordinator/coordinator.test.ts", "tests/tools/repro-orchestration-long-prompt.mjs" ], @@ -10335,6 +10360,10 @@ "Capture stable red/green intentional-break evidence in CI before blocking promotion." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2086 (sources2082/2083): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec.ts: suppresses saved mobile agent status when live evidence is the Claude agents screen; suppresses saved mobile agent status when the current terminal title is neutral; suppresses saved mobile agent status when fresh live OSC title is Claude agents; keeps saved PTY bindings pending until the runtime knows the PTY is connected; refreshes daemon PTY liveness before publishing mobile session tabs; does not invalidate a newly spawned SSH pane from an overlapping stale process list. src/main/runtime/orca-runtime-tests/pty-title-status.spec.ts: associates controller PTYs with mixed-case Windows and UNC cwd paths; uses OSC titles rather than controller process names for rendererless PTYs; ignores the bare cursor-agent native title so synthesized spinner state survives; only records the bare Cursor native title via the stale-working clear; refuses a bare Cursor title while the foreground read is unavailable; does not treat a bare Cursor title as an agent once the shell owns the foreground; accepts a bare Cursor title when the foreground read confirms cursor-agent; refuses a bare Cursor title on a runtime pty with no controller attached; clears a stale working title after 3s of title-less output; cancels the stale-title timer when the PTY exits; keeps stale-title timers isolated per PTY. src/main/runtime/orca-runtime-tests/paired-settings.spec.ts: projects runtime-backed settings to paired clients; updates quick commands without widening general paired settings payloads; applies native-chat option deltas atomically on the runtime host; keeps a future-launch default when an older client asks to prune from inventory; preserves concurrent additions after forty quick commands; accepts runtime-backed setting updates from paired clients; broadcasts visibility default changes to paired clients; reconciles hooks only when paired-client hook settings change; rejects relative paths for runtime nested repo scan/import. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", @@ -10361,7 +10390,8 @@ "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", - "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Demote or quarantine if the live harness flakes without a product bug or harness bug filed to the terminal-input owner." }, @@ -10480,7 +10510,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. CLI ownership cleanup retires low-value test cases, including explicit-current no-read, legacy success/idempotent acceptance, and caller-pane routing examples. Retained refusal and recovery assertions are listed below; dated receipts keep their original scopes. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit. CLI command/orchestration owner cleanup intentionally retires three registrations selected by this gate: two mock-supplied lifecycle/Run-home rejection projection examples and the complete manually assembled JSON failure-envelope example. The JSON-envelope suite, its exact command token/testFiles entry and whole assertion reference are removed; the retired Run-home relay assertion is removed from the retained lifecycle suite. These boundary projection alarms are lost without equivalent replacement. Retained fail-closed settlement and mutation-recovery cases keep their own scope. Pure owner moves do not invalidate unrelated dated receipts, which retain their exact original bytes; no fresh reduced-selector execution, native or remote evidence is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", "https://github.com/stablyai/orca/issues/13858", @@ -10490,11 +10520,11 @@ "https://linear.app/stably/issue/STA-4022" ], "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. A worker_done caller may report success only after the owning runtime returns an explicit lifecycle verdict or authoritative reads prove that the exact Task, Dispatch, and worker report receipt settled the expected outcome. Federated terminal settlement must remain replay-eligible until the worker durably acknowledges it, and identical same-outcome retries must converge idempotently. Independently updated clients and worker servers must preserve the negotiated protocol: current peers use Run-home lifecycle settlement, while protocol v1/v2 peers retain their legacy completion path without receiving newer-only fields. A federated worker may accept only the authority defined by its negotiated protocol. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", - "oracle": "Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/orchestration.test.ts src/cli/orchestration/messages/orchestration-check-identity.test.ts src/cli/orchestration/workers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", @@ -10504,12 +10534,11 @@ "testFiles": [ "src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", - "src/cli/handlers/orchestration.test.ts", - "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", - "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", - "src/cli/handlers/orchestration-check-identity.test.ts", - "src/cli/handlers/orchestration-worker-cli.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts", + "src/cli/orchestration/orchestration.test.ts", + "src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", + "src/cli/orchestration/messages/orchestration-check-identity.test.ts", + "src/cli/orchestration/workers/orchestration-worker-cli.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts", "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts", "src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", "src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts", @@ -10526,26 +10555,16 @@ ] }, { - "file": "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", + "file": "src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", "assertions": [ - "an explicit current worker_done verdict completes without a compatibility read", - "a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt", - "legacy succeeded and failed reports require matching terminal Task and Dispatch state", + "a worker_done response without a lifecycle verdict fails closed when authoritative Dispatch and report state cannot confirm settlement", "stopped or stale Dispatches cannot impersonate report settlement", - "an idempotent retry accepts the first authoritative report from the same worker", - "a Run-home relay rejection reaches the CLI error boundary" + "post-verification failure preserves the worker_done mutation identity for recovery" ] }, { - "file": "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", - "assertions": ["a rejected lifecycle verdict is emitted as a JSON ok=false envelope"] - }, - { - "file": "src/cli/handlers/orchestration-check-identity.test.ts", - "assertions": [ - "implicit check carries the caller pane key with a potentially stale environment handle", - "explicit legacy terminal inspection does not inherit the caller pane key" - ] + "file": "src/cli/orchestration/messages/orchestration-check-identity.test.ts", + "assertions": ["an empty explicit --terminal is refused before reading a mailbox"] }, { "file": "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts", @@ -10633,6 +10652,10 @@ "Attach saved intentional-break artifacts for hidden local presentation and dropped stable-pane delivery." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", "Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit.", "Audit2923 retires this entire mixed three-file receipt from current evidenceRuns because its selector included the removed migration suite. Preserved verbatim original JSON object (historical only; no reduced-selector validation):\n{\n \"date\": \"2026-08-11\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.4,\n \"summary\": \"Three focused files passed 12 deterministic tests covering explicit current and Run-home verdicts, JSON failure output, exact report and terminal-state verification for stripped responses, stale/stopped rejection, idempotent retry, and first/replayed attested legacy settlements.\"\n }", "Audit2086 (sources2082/2083): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec.ts: suppresses saved mobile agent status when live evidence is the Claude agents screen; suppresses saved mobile agent status when the current terminal title is neutral; suppresses saved mobile agent status when fresh live OSC title is Claude agents; keeps saved PTY bindings pending until the runtime knows the PTY is connected; refreshes daemon PTY liveness before publishing mobile session tabs; does not invalidate a newly spawned SSH pane from an overlapping stale process list. src/main/runtime/orca-runtime-tests/pty-title-status.spec.ts: associates controller PTYs with mixed-case Windows and UNC cwd paths; uses OSC titles rather than controller process names for rendererless PTYs; ignores the bare cursor-agent native title so synthesized spinner state survives; only records the bare Cursor native title via the stale-working clear; refuses a bare Cursor title while the foreground read is unavailable; does not treat a bare Cursor title as an agent once the shell owns the foreground; accepts a bare Cursor title when the foreground read confirms cursor-agent; refuses a bare Cursor title on a runtime pty with no controller attached; clears a stale working title after 3s of title-less output; cancels the stale-title timer when the PTY exits; keeps stale-title timers isolated per PTY. src/main/runtime/orca-runtime-tests/paired-settings.spec.ts: projects runtime-backed settings to paired clients; updates quick commands without widening general paired settings payloads; applies native-chat option deltas atomically on the runtime host; keeps a future-launch default when an older client asks to prune from inventory; preserves concurrent additions after forty quick commands; accepts runtime-backed setting updates from paired clients; broadcasts visibility default changes to paired clients; reconciles hooks only when paired-client hook settings change; rejects relative paths for runtime nested repo scan/import. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", @@ -10684,7 +10707,9 @@ "Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. All prior notes and dated/archived evidence retain original scopes.", "Complete prior commands before federation-lifecycle suite retirement: [\"ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1\",\"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"]", "Complete prior testFiles before federation-lifecycle suite retirement: [\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/cli/handlers/orchestration.test.ts\",\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"src/cli/handlers/orchestration-check-identity.test.ts\",\"src/cli/handlers/orchestration-worker-cli.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"]", - "Complete prior assertionRefs before federation-lifecycle suite retirement: [{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"assertions\":[\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"assertions\":[\"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\"an aborted settlement wait returns operation_unknown instead of accepted success\",\"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\"a terminal verdict cannot settle an unrelated relay item\",\"a terminal verdict cannot contradict the exact queued worker report outcome\",\"a rejected report replays its exact verdict without mutating durable rejection mail twice\"]},{\"file\":\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"assertions\":[\"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\"the migration advances schema version without losing the imported relay cursor\"]},{\"file\":\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"assertions\":[\"worker-start exposes one inactive worker tab before workspace navigation\",\"the coordinator tab remains active\",\"ACK delivery reaches a stable coordinator pane through a stale handle\",\"one spawn remains live with no interruption event\",\"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\"the exact Task and Dispatch remain dispatched after rejection\",\"the correct worker identity receives an explicit completed lifecycle verdict\",\"an independent runtime read observes the Dispatch completed\"]}]" + "Complete prior assertionRefs before federation-lifecycle suite retirement: [{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"assertions\":[\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"assertions\":[\"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\"an aborted settlement wait returns operation_unknown instead of accepted success\",\"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\"a terminal verdict cannot settle an unrelated relay item\",\"a terminal verdict cannot contradict the exact queued worker report outcome\",\"a rejected report replays its exact verdict without mutating durable rejection mail twice\"]},{\"file\":\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"assertions\":[\"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\"the migration advances schema version without losing the imported relay cursor\"]},{\"file\":\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"assertions\":[\"worker-start exposes one inactive worker tab before workspace navigation\",\"the coordinator tab remains active\",\"ACK delivery reaches a stable coordinator pane through a stale handle\",\"one spawn remains live with no interruption event\",\"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\"the exact Task and Dispatch remain dispatched after rejection\",\"the correct worker identity receives an explicit completed lifecycle verdict\",\"an independent runtime read observes the Dispatch completed\"]}]", + "CLI ownership cleanup intentionally removes the retired success, routing and work-count alarms without replacement. Prior CLI assertion references: [{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]}]", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox." }, @@ -10706,29 +10731,29 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local"], - "coverageNotes": "NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13005", "https://github.com/stablyai/orca/pull/13250" ], "invariant": "A live Dispatch created by orchestration dispatch can be stopped or abandoned even though it has no supervised worker row. Release must durably record the requested outcome, revoke lifecycle authority, close questions, free the exact assignee identity, and block only the Task whose current Dispatch was released. It must never close the unsupervised terminal process, disturb unrelated or supervised workers, or let a repeat or opposite verb rewrite the persisted outcome.", - "oracle": "Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "oracle": "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/cli/handlers/orchestration-worker-cli.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/cli/orchestration/workers/orchestration-worker-cli.test.ts --reporter=dot", "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ - "src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts", "src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts", - "src/cli/handlers/orchestration-worker-cli.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts", + "src/cli/orchestration/workers/orchestration-worker-cli.test.ts", "tests/e2e/orchestration-low-level-dispatch-release.spec.ts" ], "assertionRefs": [ { - "file": "src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts", + "file": "src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts", "assertions": [ "worker-abandon and worker-stop durably release context-only Dispatches without closing terminals", "repeat and cross-verb calls preserve the first stored outcome", @@ -10788,6 +10813,7 @@ "Add Docker SSH and physical Windows WSL same-pane reuse evidence." ], "knownGaps": [ + "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit.", "Live paired-runtime, headless serve, SSH, WSL, Linux, and Windows evidence is not yet attached.", "The Electron journey calls production runtime RPC methods directly instead of spawning a separate CLI process.", "The local journey covers a folder-backed seeded repository through the app fixture but not a git-independent folder workspace.", @@ -10816,7 +10842,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1379 changes src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts (7 authored registrations removed; 0 retained). Intentional losses: Loses supplied host lists and record states mapped to liveness enums and routing counts; no live/dead process evidence. No equivalent replacement coverage is claimed. Remaining exact receipts validate only their unchanged selectors. Historical coverage account: Only Keep open keeps a worker; a phone or desktop names it by handle, pane or session, and older clients' typing reports record nothing. Host byte lanes perform zero orchestration SQL work; local and injected SSH Keep open tests fence release. Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, dead external/user-owned/transferred/stopped/abandoned reconciliation, host-partition persistence and legacy retirement replay with an absent web-terminal layout map, conservative unknown provider and legacy metadata handling, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. A macOS Electron journey invokes the freshly compiled worker-release CLI after the worker process disappears, then independently checks released SQLite state and coordinator liveness. Injected inventories cover local and SSH provider routing; live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps. Audit1396: src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts reduced. Retires unary/stream no-database-work call counts and three mobile RPC allowlist membership checks. Ancillary input delivery assertions in the budget registration intentionally lost without equivalence claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes. Historical prior account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1379 changes src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts (7 authored registrations removed; 0 retained). Intentional losses: Loses supplied host lists and record states mapped to liveness enums and routing counts; no live/dead process evidence. No equivalent replacement coverage is claimed. Remaining exact receipts validate only their unchanged selectors. Historical coverage account: Only Keep open keeps a worker; a phone or desktop names it by handle, pane or session, and older clients' typing reports record nothing. Host byte lanes perform zero orchestration SQL work; local and injected SSH Keep open tests fence release. Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, dead external/user-owned/transferred/stopped/abandoned reconciliation, host-partition persistence and legacy retirement replay with an absent web-terminal layout map, conservative unknown provider and legacy metadata handling, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. A macOS Electron journey invokes the freshly compiled worker-release CLI after the worker process disappears, then independently checks released SQLite state and coordinator liveness. Injected inventories cover local and SSH provider routing; live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps. Audit1396: src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts reduced. Retires unary/stream no-database-work call counts and three mobile RPC allowlist membership checks. Ancillary input delivery assertions in the budget registration intentionally lost without equivalence claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/12355", "https://github.com/stablyai/orca/issues/13860", @@ -10825,22 +10851,22 @@ "STA-5122" ], "invariant": "A settled Dispatch may close only its one coordinator-created terminal lease. Explicit reuse, Keep open, retain, identity or host change, ambiguity, and another resource for the same exact host/pane/process must fence closure. Once the authoritative owning provider positively excludes the resource's exact immutable process incarnation, even an external, user-owned, or transferred dead resource must converge to released without any process close. Unknown host scope, missing incarnation metadata, or unavailable inventory must remain retained. Exact terminal-close persistence must settle when a host partition omits renderer-owned layout state. Output preservation and the requested-to-releasing transition are atomic, archives remain readable without the provider file, retries resume idempotently, and orchestration reset removes archive and authority state.", - "oracle": "Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Surviving unchanged-source receipts are the current oracle; changed-source assertions await validation. Historical oracle account: Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain against a controlled archive promise and require no committed archive or close. Rebase a closed web-terminal host partition without terminalLayoutsByTabId and require the persistence write to complete while preserving host-authoritative membership; replay a valid legacy retirement under the same omission and require exact membership removal plus revision advancement. For retained external, user-owned, transferred, stopped, and abandoned resources, run one fresh inventory against the exact local/WSL or SSH provider: an exact live incarnation and every unknown inventory shape stay retained, while positive absence atomically sets ownership_state and release_state to released with processAction none and zero closeTerminal calls. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", + "oracle": "Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes. Historical prior account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Surviving unchanged-source receipts are the current oracle; changed-source assertions await validation. Historical oracle account: Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain against a controlled archive promise and require no committed archive or close. Rebase a closed web-terminal host partition without terminalLayoutsByTabId and require the persistence write to complete while preserving host-authoritative membership; replay a valid legacy retirement under the same omission and require exact membership removal plus revision advancement. For retained external, user-owned, transferred, stopped, and abandoned resources, run one fresh inventory against the exact local/WSL or SSH provider: an exact live incarnation and every unknown inventory shape stay retained, while positive absence atomically sets ownership_state and release_state to released with processAction none and zero closeTerminal calls. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ - "src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts", "src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts", "src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts", - "src/main/runtime/rpc/orchestration-mutation-ledger.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts", + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts", + "src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts", "src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts", "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts" ], @@ -10853,17 +10879,13 @@ ] }, { - "file": "src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts", - "assertions": [ - "retains a dead external terminal without closing a process", - "releases a dead stopped or abandoned worker without closing a process", - "lets an explicit retain cancel a release while output capture is pending" - ] + "file": "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts", + "assertions": ["does not claim retention succeeded after terminal close was committed"] }, { - "file": "src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts", + "file": "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts", "assertions": [ - "finishes a requested release after restart-style interruption within the same runtime and database", + "settles a closed terminal after restart when exact process liveness is exited", "coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close" ] }, @@ -10911,6 +10933,7 @@ "Prove provider-close lost acknowledgements converge with an exact durable close receipt." ], "knownGaps": [ + "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Audit3681 metadata correction at gate106 retires exactly “releases a dead stopped or abandoned worker without closing a process” because its stopped/abandoned positive-exit matrix is intentionally removed in the20 authored/24 finite source delta, and “lets an explicit retain cancel a release while output capture is pending” because capture is synchronous and that callback was already absent at the reviewed current base. The latter is preexisting unsupported evidence with zero additional removal credit. Preserve every other assertion, command, testFile, evidenceRun and all previous prose/gaps; apply only the two exact assertion-string removals, never a stale assertionRefs whole-field replacement.", "Provider close has no durable cross-process operation receipt, so a crash after host mutation but before SQLite settlement remains release_pending until exact inventory returns.", "Federated release remains explicitly unsupported and retained.", "Mobile/direct remote input takeover and live Linux, Windows, WSL, SSH, headed, and headless paired-runtime release are not exercised; the host-partition fix changes persistence normalization only, not ConPTY, filesystem, update, sleep, firewall, or window lifecycle semantics.", @@ -10931,7 +10954,8 @@ "Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. All prior notes and dated/archived evidence retain original scopes.", "Audit3437 complete prior commands before completed-worker-retirement-resume retirement: [\"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts --reporter=verbose\",\"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"]", "Audit3437 complete prior testFiles before completed-worker-retirement-resume retirement: [\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts\",\"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts\",\"src/main/runtime/rpc/orchestration-mutation-ledger.test.ts\",\"src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts\",\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"]", - "Audit3437 complete prior assertionRefs before completed-worker-retirement-resume retirement: [{\"file\":\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"assertions\":[\"rebases a host partition that no longer carries the closed web-terminal layout\",\"replays a legacy retirement when its host partition omits terminal layouts\"]},{\"file\":\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"assertions\":[\"an already-exited succeeded Dispatch reaches released while its late exact close revokes the missing tab's stale resume record\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts\",\"assertions\":[\"retains a dead external terminal without closing a process\",\"releases a dead stopped or abandoned worker without closing a process\",\"lets an explicit retain cancel a release while output capture is pending\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts\",\"assertions\":[\"finishes a requested release after restart-style interruption within the same runtime and database\",\"coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"compiled worker-release reconciles a dead external retained resource to released\",\"the CLI reports processAction none instead of closing a process\",\"SQLite independently records released ownership and release state\",\"the unrelated coordinator terminal remains live\"]}]" + "Audit3437 complete prior assertionRefs before completed-worker-retirement-resume retirement: [{\"file\":\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"assertions\":[\"rebases a host partition that no longer carries the closed web-terminal layout\",\"replays a legacy retirement when its host partition omits terminal layouts\"]},{\"file\":\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"assertions\":[\"an already-exited succeeded Dispatch reaches released while its late exact close revokes the missing tab's stale resume record\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts\",\"assertions\":[\"retains a dead external terminal without closing a process\",\"releases a dead stopped or abandoned worker without closing a process\",\"lets an explicit retain cancel a release while output capture is pending\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts\",\"assertions\":[\"finishes a requested release after restart-style interruption within the same runtime and database\",\"coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"compiled worker-release reconciles a dead external retained resource to released\",\"the CLI reports processAction none instead of closing a process\",\"SQLite independently records released ownership and release state\",\"the unrelated coordinator terminal remains live\"]}]", + "Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes." ], "demotionRule": "Keep experimental or demote if release can overlap exact reuse, close a conflicting lease, lose immutable output, retain reset archives, fan out per worker, or any focused ordering test flakes without a product or harness defect." }, @@ -12329,22 +12353,22 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4358 intentionally removes six whole mocked daemon subprocess suites and two extra pre-listener replay variants (18 authored / 20 finite cases). Lost alarms include cancel-during-cwd-validation, root agent startup refusal, output/exit before ConPTY publication, fresh/delayed/unavailable foreground confirmation, cache/decision separation, detached/no-tty child evidence and synthetic agent authorization. The retained lifecycle case checks data and exit replay after handle creation, not startup-time publication or alternate listener order. The retained native Windows Git Bash workflow and host cold-restore seed check have separate scopes. No equivalent replacement or fresh gate execution is claimed. Earlier notes and dated receipts retain their original scope. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3553/3559 current scope: delete worktrees-delete-pty-teardown.test.ts and worktrees-issue-command-overrides.test.ts entirely and remove three cases from worktrees-orphan-directory-cleanup.test.ts (6 authored/6 finite removals). Intentionally retire typed unserved-SSH create/delete admission, exact-name collision/error-token, proven-orphan no-force confirmation, standalone .git-directory refusal, and SSH-owned local-path preservation alarms. Retain only actual authorized orphan deletion and no-marker notes-file preservation; they are not equivalent replacements. The no-marker fixture resolves the default getRepos owner, so it does not prove temporary owner-repo binding. Git/Store/PTY/notifications are mocked; no physical process stop, durable metadata, real SSH delivery or native UI proof is claimed. Unchanged historical oracle, coverage, evidenceRuns and escaped receipts retain their original scopes only; no fresh execution or transferred pass validates the reduced sources. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/5308", "https://github.com/stablyai/orca/issues/7547", "https://github.com/stablyai/orca/issues/8212" ], "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", - "oracle": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", + "oracle": "Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4358 intentionally removes six whole mocked daemon subprocess suites and two extra pre-listener replay variants (18 authored / 20 finite cases). Lost alarms include cancel-during-cwd-validation, root agent startup refusal, output/exit before ConPTY publication, fresh/delayed/unavailable foreground confirmation, cache/decision separation, detached/no-tty child evidence and synthetic agent authorization. The retained lifecycle case checks data and exit replay after handle creation, not startup-time publication or alternate listener order. The retained native Windows Git Bash workflow and host cold-restore seed check have separate scopes. No equivalent replacement or fresh gate execution is claimed. Earlier notes and dated receipts retain their original scope. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3553/3559 current scope: delete worktrees-delete-pty-teardown.test.ts and worktrees-issue-command-overrides.test.ts entirely and remove three cases from worktrees-orphan-directory-cleanup.test.ts (6 authored/6 finite removals). Intentionally retire typed unserved-SSH create/delete admission, exact-name collision/error-token, proven-orphan no-force confirmation, standalone .git-directory refusal, and SSH-owned local-path preservation alarms. Retain only actual authorized orphan deletion and no-marker notes-file preservation; they are not equivalent replacements. The no-marker fixture resolves the default getRepos owner, so it does not prove temporary owner-repo binding. Git/Store/PTY/notifications are mocked; no physical process stop, durable metadata, real SSH delivery or native UI proof is claimed. Unchanged historical oracle, coverage, evidenceRuns and escaped receipts retain their original scopes only; no fresh execution or transferred pass validates the reduced sources. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", "pnpm run build:electron-vite", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs", @@ -12361,14 +12385,11 @@ "src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts", "src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts", "src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts", - "src/main/ipc/worktrees-delete-pty-teardown.test.ts", "src/main/ipc/worktrees-orphan-directory-cleanup.test.ts", "src/main/ipc/worktrees-remove-preflight.test.ts", "src/main/workspaces/removal/watcher-removal-gate.test.ts", "src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts", "src/main/providers/local-pty/local-pty-provider-shutdown.test.ts", - "src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts", - "src/main/daemon/sessions/testing/session.test.ts", "src/main/daemon/terminal-host/testing/terminal-host.test.ts", "src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", "src/main/runtime/files/watch/orca-runtime-files-watch.test.ts", @@ -12419,7 +12440,7 @@ "queued abort removes one request without restarting healthy roots, while active abort or crawl-scoped timeout restores the shard", "queues subscribe and unsubscribe behind the retiring child; bounds a pending crawl and restores healthy roots after setup timeout", "production runtime-pool disposal rejects later subscriptions without forking an overlapping child", - "missing built entries fail closed" + "Historical assertion retired by audit3749/3752; no current direct driver or replacement coverage is claimed. Original assertion (preserved verbatim): missing built entries fail closed" ] }, { @@ -12658,6 +12679,50 @@ "Add a packaged orca serve pairing scenario that proves a connected client refreshes after child replacement." ], "knownGaps": [ + "Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed.", + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", + "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical.", + "Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical.", + "Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope.", + "Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed.", + "Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes.", + "Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases.", + "Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit.", + "Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved.", + "Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits.", + "Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope.", + "Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit.", + "Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit.", + "Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit.", + "Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical.", + "Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained.", + "Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit.", + "Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit", + "Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures.", + "Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise.", + "Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope.", + "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit.", + "Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation.", + "Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains.", + "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence.", + "Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope.", + "Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope.", + "Audit3630 removed orphan delete/toggle capability/precondition and run/edit refusal assertions. Real dispatch, mutation fencing, mixed-version and host outcomes are not established by this removal or by a substitute test.", + "Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope.", + "Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope.", + "Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope.", + "Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope.", + "Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope.", + "Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed.", + "Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions.", + "Audit3553/3559 current scope: delete worktrees-delete-pty-teardown.test.ts and worktrees-issue-command-overrides.test.ts entirely and remove three cases from worktrees-orphan-directory-cleanup.test.ts (6 authored/6 finite removals). Intentionally retire typed unserved-SSH create/delete admission, exact-name collision/error-token, proven-orphan no-force confirmation, standalone .git-directory refusal, and SSH-owned local-path preservation alarms. Retain only actual authorized orphan deletion and no-marker notes-file preservation; they are not equivalent replacements. The no-marker fixture resolves the default getRepos owner, so it does not prove temporary owner-repo binding. Git/Store/PTY/notifications are mocked; no physical process stop, durable metadata, real SSH delivery or native UI proof is claimed. Unchanged historical oracle, coverage, evidenceRuns and escaped receipts retain their original scopes only; no fresh execution or transferred pass validates the reduced sources.", "Launch direct-owner cleanup current scope: This gate’s unfiltered unit command now selects a suite reduced by 82 whole registrations / 159 potential table examples in 10 whole test Programs, including 8 registrations / 15 examples from five once-registered create-message factory closures. Lost alarms include frozen first-message/options and legacy-host fallback; distinct actions and redelivery; uncertain/refused/reloaded input custody, Retry and late proof; rich prompt/attachment upload Stop/close and handback; ordinary draft/editor/IME/StrictMode lifetime and accepted topology; provisional fallback tab placement/group/pin/order and rich worktree handoff. Four whole consent/resume-identity cases remain in two Programs; they do not replace these alarms. This entry governs current reduced-unit scope and qualifies any broader implication of unchanged oracle/coverageNotes history. Entire dated evidenceRuns, original commands/currentCommand values, counts/results and existing history retain their original scopes only; no fresh execution, transferred pass, replacement equivalence or prior upstream-removal credit is claimed.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. src/main/persistence/worktree-sort-order-write.test.ts: re-ranks every writable row when a blocked row sits in the requested order. src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts: continues skill management after startup recovery fails. src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts: uses bounded ownership lookup for direct arrivals while the agent cannot take input; wakes a bound Run waiter when same-Run direct mail arrives; keeps an unowned detached-recipient message in its direct mailbox; uses primary-key lookups for bounded routing updates. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts: remove only literal registration import/call pairs import './orchestration-mailbox-pointer-cli-command.spec'; no additional authored credit. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts: renders the %s CLI command in a mailbox pointer. src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts: sizes a slow high-latency link near twice its bandwidth-delay product; never paces a LAN, even when its client parses slowly; never paces a fast link; returns to legacy windows when the path RTT jumps. src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts: steps down the row ladder when history is over the byte budget; tries the larger first row count, then the usual ladder within the same byte budget. src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts: returns unknown when route inspection fails or emits malformed data; does not inspect routes outside Windows. src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts: is refused to a paired %s client; reports a failed widening instead of advertising an unreachable address. src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts: reports exited only when the owning runtime completes the exit waiter; reports unverifiable when the runtime cannot observe the exit waiter; reports unverifiable when a disconnected PTY resolves with unknown liveness. src/main/runtime/session-graph/headless-runtime-graph.spec.ts: lets a session tab inventory settle on a host no renderer publishes for. src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts: remove only literal registration import/call pairs import { registerHeadlessRuntimeGraphTests } from './headless-runtime-graph.spec', registerHeadlessRuntimeGraphTests(); no additional authored credit. src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts: bumps the stored snapshot version only when the title changes. src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts: keeps the healthy aggregate verification and delayed physical exit behavior; uses a stamped exit for the incarnation that was actually being closed. src/main/runtime/terminal/identity/terminal-identity-probe.test.ts: answers live for a structured worker without touching the PTY graph; answers live for a PTY handle the runtime still holds; runs the full leaf check for a handle with no live PTY; answers not-live for a stale handle; propagates \"could not look\" rather than reporting it as a dead handle. src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts: names the tab in main’s layout through terminal.rename; takes a window-style layout.apply close as already stopped, so the terminal runs on. src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts: retains no lifecycle generation after a spawn/exit cycle. src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts: reads a freshly spawned terminal as used once a user opens its tab, not on a probe; keeps the open mark on the process a user open starts. src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts: from a desktop window that mounts both panes; from a server with no window. src/main/runtime/terminal/surface/workspace-layout-projection.test.ts: carries views for a partition that holds none yet. src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts: releases a signalled exit-waiter when the signal aborts. src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts: selects a local hook status for a local pane. src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts: keeps the footer and the bare caret on screen mid-turn; %s: the screen alone reads ready during %s. src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts: uses per-launch arguments and preserves launch telemetry; attributes a startup agent whose caller named no surface as unknown; launches %s bare for an absent or blank prompt; attributes a %s draft launch named %s as %s; merges an automation's extras over the host defaults; threads worktree-create extras into the startup build; returns an enabled requested agent without detecting; returns the default when nothing was requested; detects instead of using the default when the requested agent is disabled; starts no agent when the default is blank; detects an enabled agent on this host when nothing usable was named; starts no agent when detection finds none. src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts: pastes and submits through composer readiness, never typing raw input; types the follow-up on WSL or SSH-to-Windows once the agent is in front, as before; cleans up the deadline when the composer was already captured; a draft that is not submitted is pasted on the box cursor, as before; takes the box after the grace when the row never comes, whatever repaints; takes the box at the deadline when the grace would outlast the budget; lets a dialog on screen veto a grace; refuses the deadline inside a pending grace while a shell is in front; takes the box at the deadline inside a pending grace with the agent in front; takes the box at the deadline after a refused grace once the agent is in front. src/main/skills/skill-install-transaction.test.ts: installs, previews unchanged bytes, and updates a clean receipt-owned skill; preserves the old version after a %s filesystem failure. src/main/speech/model-manager-download-resume.test.ts: requests the remaining bytes when a clean range response ends before the file total; bounds a server that advances by pathologically tiny segments forever. src/main/ssh/config/ssh-config-parser.test.ts: parses a basic host block; parses multiple host blocks; skips wildcard-only Host entries; skips Host entries with only pattern characters; parses IdentityFile with ~ expansion; parses Windows-style IdentityFile with ~ expansion; parses quoted scalar values like OpenSSH; parses equals-form scalar directives; parses IdentityAgent with ~ expansion; parses IdentitiesOnly; parses GSSAPIAuthentication; keeps the first GSSAPIAuthentication value like OpenSSH; parses ProxyCommand, ProxyUseFdpass, and ProxyJump; ignores comments and blank lines; handles case-insensitive keywords; stops current block on Match directive; returns empty array for empty input; creates one parsed host per concrete alias on a multi-pattern Host line; applies identity agent settings to every concrete alias on a multi-pattern Host line; defaults port to 22 for invalid port values; converts hosts to SshTarget objects; uses host alias as hostname when HostName is missing; skips hosts that are already imported; defaults username to empty string when not specified; carries through identityFile, identityAgent, identitiesOnly, proxyCommand, and jumpHost; carries through gssapiAuthentication; imports duplicate aliases only once and keeps the first concrete host; maps hosts for the picker and flags aliases already in Orca; de-dupes aliases and defaults missing fields; parses hostname, user, port from ssh -G output; collects multiple identity files; parses forwardagent yes; defaults port to 22 when missing; returns empty hostname when missing; returns undefined user when missing; handles empty output; skips lines without spaces; parses proxycommand and filters \"none\"; parses proxyusefdpass yes; parses proxyjump and filters \"none\"; handles ~ expansion in identity file paths; handles Windows-style ~ expansion in identity file paths; parses identityagent with ~ expansion; preserves identityagent none so auth can disable agent fallback; parses identitiesonly yes; parses gssapiauthentication; parses controlmaster options and filters controlpath none. src/main/ssh/config/ssh-known-hosts-source.test.ts: splits the space-separated list ssh -G prints on one line; expands ~ in a reported path; keeps a double-quoted path containing spaces whole; falls back to the default files when ssh -G reported nothing; drops an explicit none without falling back to the defaults; splits both known_hosts lists on one line each; reads StrictHostKeyChecking, including accept-new; reads HostKeyAlias and prefers it for the lookup; reads the non-default port; reports that the lookup came from an alias, so the port is not appended; reports no alias when the dialed host is used; unions the entries of every file; skips a path that is a directory; returns nothing when no file can be read; reports nothing unreadable when every file parses; does not count an empty file as unreadable; prefers HostKeyAlias over the resolved hostname; uses the dialed host, because a resolved hostname can just echo the label; still prefers an explicit HostKeyAlias over the dialed host; falls back to the dialed host when nothing was resolved; is rejoined when the split fragments resolve to nothing; leaves a single unresolvable path alone rather than inventing one; expands the __PROGRAMDATA__ token rather than passing it through as a path; does not rewrite a path that merely BEGINS with the token characters; keeps a drive-letter path with mixed separators intact; splits a spaced Windows home into the fragments the rejoin has to put back. src/main/ssh/config/ssh-known-hosts.test.ts: reads the algorithm from the blob rather than trusting the line; rejects %s; refuses a malformed blob: %s; uses the bare host on the default port; tries the bracketed form first and falls back to bare off-port; matches an exact line; matches case-insensitively; reports a changed key of the same type; reports unknown for %s; matches any host in a comma list; matches the bracketed form on its port; does not apply a bracketed entry to the default port; falls back to a bare line when off-port; never reports a change from the fallback pass; matches a bare literal on the default port; matches a bracketed literal on its port; reports a change for a literal; handles %s; still reports a change for a different key on a revoked host; skips a line carrying an unrecognised marker; does not report a change when only another key type is on file; matches within the same type; accepts CRLF terminators; skips blanks, comments and surrounding whitespace; accepts a hit regardless of which file holds it (%s); never brackets the alias, whatever the port; still brackets an ordinary host on a non-default port; matches a bare alias entry on a non-default port; still accepts the unmodified key field; accepts a hashed entry whose salt is a full SHA1 digest; still accepts the unmutated ssh-keygen -H vector; falls back to the bare host line on a non-default port, as ssh did; refuses a key type it has not seen for a host it knows, as ssh did. src/main/ssh/connection/ssh-connect-config.test.ts: returns undefined when no default keys exist; returns the first existing key file; probes regular and FIDO2 keys in stable default order; keeps a regular default ahead of a malformed FIDO2 default; uses target host/port/username; falls back to resolved config when target fields are empty; keeps imported endpoint fields as the fallback when ssh -G is unavailable; sets readyTimeout to CONNECT_TIMEOUT_MS; sets keepaliveInterval to 15s; enables keyboard-interactive auth so MFA challenges can be answered; uses agent auth when no explicit key and SSH_AUTH_SOCK is set; enables agent forwarding when OpenSSH config requests it and an agent is available; does not enable agent forwarding without a usable agent; resolves IdentityAgent SSH_AUTH_SOCK from the environment; uses the Windows OpenSSH agent pipe when no environment socket is available on Windows; wraps agent auth with IdentityFile filtering when IdentitiesOnly is enabled; applies a manual target IdentitiesOnly setting when ssh -G reports it off; includes unencrypted target.identityFile auth when an agent is available; defers encrypted target.identityFile auth when an agent is available; uses keyFile auth when target.identityFile is set and no agent is available; includes unencrypted resolved identityFile auth when an agent is available; defers a default-path resolved identityFile to the no-agent retry; offers the keyboard-interactive challenge when the agent defers no key; provides fallback key when no agent is available; can force private key inclusion for the post-agent fallback path; falls back to resolved proxyCommand; returns structured jump-host config for target.jumpHost; returns structured jump-host config for resolved proxyJump; returns undefined when no proxy is configured. src/main/ssh/connection/ssh-connection-auth-fallback.test.ts: resolves OpenSSH config using configHost when present; tries ssh-agent before reading an explicit private key; falls back to direct private key auth when agent auth fails; falls back to direct private key auth after too many agent authentication failures; answers bounded keyboard-interactive challenges such as Duo 2FA. src/main/ssh/connection/ssh-connection-store.test.ts: lists picker suppression aliases without consulting re-adoption tombstones; getTarget delegates to store; addTarget generates an id and persists; saves the CLI control switch as given, with no consent stamp; addTarget stamps source as manual by default; addTarget preserves an explicitly provided source; inserts a new config host stamped as ssh-config; asks the parser for all hosts — reconciliation happens in the store; updates an existing config-sourced target when the port changed; refreshes gssapiAuthentication on sync; never overwrites a manual target that owns the alias; does not rewrite an unchanged config-sourced target; returns empty array when nothing changed; tombstones a deleted config-sourced host so re-import skips it; suppresses a deleted manual target from config discovery; re-adding a deleted host reclaims its alias so sync stops suppressing it; editing a target reclaims its alias from the deleted set; records a tombstone when removing any user-facing target; re-adopts orphaned repos when the same host is re-added. src/main/ssh/connection/ssh-connection.test.ts: transitions to connected on successful connect; captures the negotiated SSH server key fingerprint; allows concurrent exec commands for ssh2 transport; removes startup listeners after ssh2 connect succeeds; scopes lifecycle events and pending handshake timers to one mock client; enables TCP_NODELAY on the new ssh2 client after a reconnect cycle; transitions through connecting → connected states; reports error state on connection failure; disconnect cleans up and sets state to disconnected; getTarget returns a copy of the target; getState returns a copy of the state; throws when connecting a disposed connection. src/main/ssh/orcad-migration-stuck-host-profiles.test.ts: never leaves a running terminal behind; is offered only when leaving saved state behind would clear the refusal. src/main/ssh/orcad-runtime-maintenance.test.ts: keeps a connect from retrying a build an explicit Update also failed; offers Force when Update was refused by policy; forwards anew after an activation, since the new slot may bind another port; passes a refusal through and leaves the server linked; forwards anew once a serving slot is restored, which may have bound another port. src/main/ssh/port-forwarding/ssh-port-forward.test.ts: reports the port the OS bound when an ssh2 forward asks for port 0; adds an ssh2 port forward and returns entry; adds a system SSH port forward when no ssh2 client is available; reports the port a system SSH forward resolved when asked for port 0; passes resolved OpenSSH config to system SSH port forwards; disposes a system SSH tunnel when removing the forward; lists forwards filtered by connectionId; removes a forward by id; awaits forward close when removing a forward for user actions; returns null when removing nonexistent forward; removes all forwards for a connection; dispose removes all forwards; stores label in the entry; preserves the existing id when updating a forward succeeds. src/main/ssh/ssh-channel-multiplexer.test.ts: sends a JSON-RPC request and resolves on response; assigns unique request IDs; sends notifications without expecting a response; dispatches incoming notifications to handler; sends one keepalive frame per cadence tick; drives keepalive sends AND dead-link detection from a single interval; resolves false immediately on a disposed mux; throws on request after dispose; reports isDisposed correctly; clears registered handlers on dispose; does not retain handlers registered after dispose. src/main/ssh/system-transport/system-ssh-forward-process.test.ts: spawns exactly the argv the orphan matcher is given, LogLevel=INFO included; runs port forwards unmultiplexed even when ssh_config disables muxing; preserves manual target port and identity options in the forwarded ssh command; does not spawn ssh when the requested local forward port is already in use; spawns ssh after the requested local forward port preflight succeeds; resolves startup after the grace period when ssh keeps running; sends SIGTERM then SIGKILL when the process does not exit; does not resolve stop until the process exits. src/main/ssh/system-transport/system-ssh-loopback-route.test.ts: dials the held forward ahead of the alias so OpenSSH keeps these over ssh_config; drops a manual target's own port and proxies, which would fight the route; never routes a forward, whose argv must stay stable for orphan recovery; %s → %s; opens the forward over the real proxy, then proves a login over the route; lands the forward on the sshd and known_hosts name the direct route resolved; holds the forward with server-alive probes; never lets the background forward or probe ask for credentials; starts no forward when admission refuses the route; stops the forward when sshd refuses logins over it; stops the whole forward process tree on Windows, once; reports a forward that already exited before anyone listened for it. src/main/startup/browser-process-user-agent-ordering.test.ts: explains admission refusal before a desktop launch exits; explains an orcad holding the profile instead of exiting silently; does not acquire profile admission for a duplicate launch; executes after the dev app name and before later preflight work; exits and releases admission after pending profile move recovery fails; keeps Linux background startup failures console-only and immediate; keeps Linux serve startup failures console-only and immediate. src/main/startup/quit/quit-path-durable-write-blocking.test.ts: store.flushAsync() issues no synchronous fs syscalls; store.flushAsync() also moves the active-view and github-cache sidecars off the thread; stats.flushAsync() issues no synchronous fs syscalls; Grok session cleanup issues no synchronous fs syscalls; stats.flushAsync() closes out live agents before it returns, not when its write lands; a stalled mount leaves the event loop live instead of parking it; store.flushAsync() is one idempotent final barrier; store.flushAsync() resolves instead of throwing when the profile mount rejects writes. src/main/stats/agent-session-transition-recorder.test.ts: counts a hook-only agent that never writes an agent-shaped terminal title; never opens a session from a replayed or disk-restored working status; still closes a live session when the terminating status arrives as a replay; counts one session per turn across repeated working/done cycles; closes an open session when its pane is torn down; bounds the mirror and closes what it evicts; stops the session when the main agent settles and only a watch loop holds the row working; keeps the session open while a subagent outlives the main agent, and closes it when the child settles; dates the stop by the evidence when a shell outlives the last subagent; opens a new session dated by the observation when the main agent resumes after monitoring; never dates a reopen before the close a fact-less OSC repaint caused; dates the first live row after a restored one by the evidence, not the restored clock; treats an unchanged answer as a snapshot, never a transition; opens only on a live working edge; closes only a session it opened. src/main/text-generation/commit-message-text-generation-model-discovery.test.ts: returns static catalog models without spawning for static agents; discovers dynamic models through the agent CLI; discovers dynamic models through the configured agent command override; falls back to static models when dynamic discovery returns no parseable models; falls back to the first discovered non-Pi model when its static default is unavailable. src/main/text-generation/pull-request-context.test.ts: does not fetch unrelated fork remotes before generating PR context; bounds exact remote-ref probe concurrency for a large remote list; reports no branch change because PR context preparation is read-only; keeps a remote-qualified base when the selected base includes the remote. src/main/text-generation/source-control-local-process.test.ts: asks the supervisor to stop and leaves its group to it; signals nothing once the supervisor has exited; stops an agent that ignores its stdin end through its supervisor. src/main/updater/linux-package/linux-package-update-recovery.test.ts: retains the downloaded package with the digest from the event metadata; requires a string downloaded path; accepts an uppercase extension; requires a non-empty string version; matches an absolute file URL by basename; accepts duplicate entries that agree on the digest; refuses an entry with a missing or non-string digest; refuses a digest that is not base64 at all; refuses a malformed percent-encoded URL; refuses a missing or non-array file list; tolerates a non-object event; replaces the retained artifact with a newer download; keeps the retained artifact when a new download has no usable digest; keeps the retained artifact when an unrelated download event arrives; clears the retained artifact; preserves the artifact across a recheck of the same version; clears the artifact when another version takes over; preserves the artifact for an unknown or empty version; is a no-op without a retained artifact; returns the built command and package file name for a verified package; reports missing without a retained artifact; propagates a package-manager discovery failure; rejects a well-formed digest that belongs to another file; never hashes a package that a malformed digest failed to arm; rejects a path outside the cache root; rejects the cache root itself; rejects a package in the updater directory itself; rejects a pending directory that is a symlink out of the cache; performs one hash pass for concurrent requests; revalidates once the in-flight pass settles; does not reuse an in-flight pass for a different artifact; starts a fresh proof when the same package is captured again; returns the verified package path; returns missing without a retained artifact. src/main/updater/releases/updater-prerelease-feed-readiness.test.ts: accepts a GitHub %s asset redirect as ready; reports a GitHub asset request error as unavailable; reports not-ready with a verified last-good tag when the newest assets are unavailable; does not classify a non-positive tag limit as feed unavailability; reproduces the v1.4.142 publishing incident as not-ready; reports transport failures as unavailable instead of not-ready; treats an explicit asset 404 as not-ready when another asset is unavailable; accepts absolute manifest asset URLs without rewriting them to release asset paths; returns not-ready with an older ready update as last-good while newest is publishing. src/main/updater/releases/updater-release-builds.test.ts: lists hourly builds from the dedicated repo, newest first; lists daily builds from the dedicated repo, newest first; separates stable from rc in the shared main repo; skips drafts and unparseable tags; keeps a composed release title and drops one that repeats the tag; hides builds that published no artifact for this platform; returns an empty list when no build has this platform artifact; keeps mac builds visible on macOS regardless of the Windows leg; resolves the platform installer download url; leaves the installer url null when the release published no installer; tolerates a release whose assets are missing or malformed; sends the local gh token as a bearer header when one is available; sends no authorization header when gh has no token; retries unauthenticated once when GitHub rejects the token; does not retry a 401 that was already unauthenticated; falls back to the per-IP bucket when the token is rate limited and tells the gh breaker; reports a secondary limit carrying retry-after without retrying or tripping the breaker; records a primary limit in the token scope %s; keeps %s authenticated when only %s is blocked; skips the token while its scope %s is blocked; surfaces a rate limit with its reset time and a sign-in hint when unauthenticated; omits the sign-in hint when the rate-limited request was authenticated; treats 429 as a rate limit; reports a 403 without rate-limit headers as a plain HTTP error; reports a missing hourly repo distinctly; is null when GitHub sent no reset; prefers retry-after over the primary reset epoch; falls back to the primary reset epoch when there is no retry-after; reads retry-after as seconds; reads retry-after as an HTTP date; pins an hourly tag at the hourly repo download path; pins a daily tag at the daily repo download path; pins a stable tag at the main repo download path; rejects a tag that is not a version. src/main/updater/updater.build-channel-selection.test.ts: uses the display label in the unsupported-platform %s pinned-build error; still pins %s from an unsigned Windows dev build; restores ordinary release checks after local build selection fails; opts into the RC channel when checkForUpdatesFromMenu is called with includePrerelease; pins the generic feed to a perf-tagged prerelease when requested; surfaces no-update feedback when no newer perf-tagged prerelease exists; keeps prerelease publishing-window misses on the generic retry path; leaves the feed URL alone for a normal user-initiated check. src/main/updater/updater.check-preflight.test.ts: ignores a stale update-not-available event after a new check starts preflight; deduplicates repeated manual checks while the immediate checking status is active. src/main/updater/updater.prerelease-fallback.test.ts: retries a prerelease check once against the previous feed tag when the manifest is missing; surfaces a promise-only prerelease fallback failure after the primary error event. src/main/updater/updater.publishing-window-feed.test.ts: repins the generic feed to the newest RC tag for a prerelease user; repins the generic feed to a newer stable tag for a prerelease user; pins a stable fallback when Atom has no newer prerelease; uses last-good concrete feed when a user-initiated check lands during publishing; can offer an older fully published update while the newest release is publishing; keeps background publishing-window fallback on the short retry cadence. src/main/updater/updater.quit-and-install.test.ts: surfaces an accepted retry before electron-updater emits download progress; defers quitAndInstall and runs its launcher within the launch PATH scope; runs pre-quit cleanup before local PTY cleanup during update install; keeps optional pre-quit cleanup fail-and-continue behavior by default; ignores duplicate quitAndInstall requests while the shared delay is pending; arms the forced-exit watchdog once the install commits; disarms the forced-exit watchdog when sync install error recovery keeps the app open. src/main/window/createMainWindow-markdown-editor-focus.test.ts: ignores traffic light sync IPC on non-macOS; still intercepts Cmd+Shift+B and Cmd+Alt+B when the markdown editor is focused; coerces non-boolean setMarkdownEditorFocused payloads to false; opens a table-aware context menu synchronously without a renderer query; builds the plain edit menu for the one right-click the renderer marks as plain text. src/main/window/createMainWindow-renderer-crash-recovery.test.ts: notifies the caller when the renderer process is gone; passes the renderer webContents id through crash recording and recovery callbacks; forwards expected renderer teardowns so the recorder can diagnose suppression; reloads the app shell after an unexpected renderer process loss; does not reload after renderer loss when recovery is disabled; stops auto-reloading after a rapid renderer crash loop trips the breaker. src/main/window/dashboard-popout-window.test.ts: updates the title after language initialization and unsubscribes when closed; lets its preload expose saved WSL hosts in serve-only, and passes nothing otherwise; creates a native-frame window with the shared preload and no webview surface; shows the window on ready-to-show; loads the prod file entry; loads the dev server URL when in dev; focuses the existing window instead of creating a second one; trusts only the live popout webContents; restores a minimized window when re-requested; restores valid persisted bounds; discards off-screen persisted bounds and falls back to defaults; persists bounds on resize after the debounce, guarding near-minimum sizes; keeps saving bounds after a vetoed quit and freezes them only on an allowed quit; closeDashboardPopout closes an open window; applies the persisted app zoom level on dom-ready; follows app zoom changes while open and unsubscribes on close; zoomDashboardPopoutIfFocused steps the popout zoom only while focused; handles the zoom-in chord via before-input-event and ignores other keys; handles mouse-wheel zoom requests outside before-input-event; respects zoom keybinding overrides for keyboard and mouse-wheel paths. src/main/window/dropped-path-preparation.test.ts: opens and stores each unique source once as drop size grows tenfold; passes ordinary paths without copying for %s; preserves ordinary successes and copied successes when another file fails; serializes copy requests from different owners; reports all lost paths without a shared reason when their failures differ. src/main/window/main-window-updater-deferred-setup.test.ts: releases all 64 completed fallback handles without repeating initialization; keeps setup after ready-to-show and releases its fallback afterward; preserves the 15-second fallback when first paint never arrives; preserves destroyed-window guard reads before and at the fallback deadline; keeps the exact %s error and releases its completed fallback; keeps the exact fallback %s error without retrying initialization; preserves pending manual setup after failed ready registration; keeps setup options, live store reads, nudge writes and required quit flush. src/main/worker-threads/worker-thread-request-queue.test.ts: posts one request at a time and in the order it was dispatched; fires a posted call at its own deadline; stops respawning and fails the rest of the queue once deaths hit the cap; clears the death count when a fresh burst starts from full idle. src/main/workspace-hooks/hooks-setup-runner-script.test.ts: builds Windows runners for newline-heavy scripts without line-array splitting; builds POSIX runners without regex-wide CRLF normalization; writes POSIX setup runners for shebang-declared scripts on native Windows paths; keeps batch setup scripts on cmd.exe when the terminal is Git Bash; hands a Git Bash pane a launch command MSYS cannot rewrite for a cmd runner; replays interpreter flags declared on the shebang line; preserves cmd.exe setup runner semantics for configured cmd users; keeps POSIX runner behavior on POSIX platforms; waits when either local or project policy requires completed setup; marks setup-runner terminals for the always-on credential guard; maps git-bash to POSIX setup launch metadata on Windows; falls back to the cmd runner when the git-bash setting has no installed Git Bash; keeps the cmd runner for a non-Git bash such as Cygwin; keeps the cmd runner for a bare bash whose flavor cannot be resolved; uses the POSIX runner for a bare bash that resolves to Git Bash; uses the POSIX runner for an extension-less Git Bash path; preserves the existing cmd runner for PowerShell terminals; preserves cmd setup compatibility when a Windows-host project has a WSL shell setting; classifies an installed explicit Git Bash executable as a POSIX runner; falls back to the cmd runner when the explicit Git Bash path no longer exists. src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts: schedules remote identity enrichment without blocking the caller; probes a drive project whose runtime is WSL %s; sweeps a local repo: %s; probes an SSH row that carries only executionHostId on its own host; keeps same-path rows on two different SSH hosts from sharing one backoff; coalesces concurrent probes for the same repo location; caches no-identity probes briefly so list calls do not retry every time; does not rewrite the no-remote marker on a later retry; resolves a settled no-remote repo once it gains a remote; does not re-probe a resolved identity before the refresh window elapses; re-probes a resolved identity after the refresh window elapses; bounds re-probes per sweep so a large repo list drains gradually; forgets a removed repo location so its deadline cannot outlive the repo; keeps a surviving repo backoff when a sibling repo is removed; probes again when the same location is re-added after its probe was retired; coalesces concurrent sweeps instead of running one pass per list call. src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts: preserves create priority through claim probes on %s; starts the checkout only once the async workspace root resolves; still deduplicates when both callers await the same pending root lookup; namespaces native Windows preparation directories for long paths; deduplicates preparation for the same repo, base, runtime, and workspace root; does not spend a divergence walk when the base matches exactly; claims when the two sides spell the same ref differently; evicts a repo's own stale preparation before another repo's; still discards armed checkouts when the project runtime needs repair; routes preparation and finalization through the selected WSL runtime; retries stale cleanup after a transient listing failure; does not discard a detached worktree with caller-controlled preparation metadata; does not re-arm after an isolated create; re-arms a preparation once creates arrive in a burst; holds the re-arm checkout until the create runs the deferred thunk; starts one explicit prefetch after the create completes; does not re-arm when finalization failed; reports a pending create while a stale-cleanup scan is running. src/main/workspaces/removal/local-worktree-removal-recovery.test.ts: recovers Git for Windows partial filesystem deletion failures; finishes a clean non-force deletion after Git leaves a Windows directory behind; recovers localized Windows failures after Git already removed the registration; does not recover unrelated localized failures while Git still owns the row; finishes a macOS deletion Git deregistered before failing with Directory not empty; leaves an orphaned checkout to the orphan cleanup instead of deleting it; prunes and strictly verifies on the selected WSL host without deleting files or branches. src/main/workspaces/removal/worktree-removal-safety.test.ts: rejects deleting a worktree that contains another registered worktree; rejects POSIX home directories even when host homedir has a different path shape; refuses a home the host reported even when no path rule recognises it; refuses the Windows host's home directory from a POSIX client; refuses the Windows host's home directory even when the host reported nothing. src/main/wsl/discovery/distro-catalog.test.ts: retries asynchronous discovery after a transient wsl.exe failure; retries synchronous discovery after a transient wsl.exe failure; retries asynchronous discovery after wsl.exe reports no distros yet; retries synchronous discovery after wsl.exe reports no distros yet; bounds the wsl.exe spawn rate while no distros are installed; bounds the asynchronous spawn rate while no distros are installed; still caches a non-empty distro list for the process lifetime; re-probes a docker-desktop-only machine once a user distro can appear; backs off while the list keeps coming back empty; backs off after repeated distro-list failures; caps the empty-list backoff at five minutes; keeps reporting an empty result after it goes stale; keeps reporting a known distro list indefinitely; bounds cached homes while retaining the most recently used distros; still lists distros, and an excluded distro home probe fails like any other probe; gives the async home probe time for a cold boot instead of killing it at 5 s; retries availability after a probe timeout instead of latching false; bounds the probe rate while the failure window is open; caches a successful probe for the process lifetime; names an explicit spawn directory, so no deleted cwd can read as ENOENT; shares one wsl.exe spawn between concurrent probes; keeps reporting the last observed answer after it goes stale; holds a definitive failure far longer than a timeout when %s; backs off after repeated probe failures; re-probes a seeded retryable failure once its window lapses; re-probes availability once a distro list succeeds after %s; does not drop an availability failure for an empty distro list; keeps reporting unavailable off Windows without probing. src/main/wsl/discovery/wsl-distro-holder.test.ts: runs a busybox-safe loop through --exec and names the distro; spawns a detached-style holder, records it, and waits for the distro to run; a holder exiting with code 1 notes its distro may have stopped (E9); rejects a pid whose command line is not our holder for that distro; cleans up stale and corrupt records; keeps a holder and its record when release cannot verify it; reports unverifiable when the command line is unreadable even with a matching pid; release kills a verified holder and removes its record; release never kills a pid that is no longer our holder; reports a spawned holder exit so liveness can re-check. src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts: skips 9p shares that are not drvfs, and malformed lines. src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts: plans the update on the census the running orcad reports, not an unknown one; forwards force to the update planner; does not serve the incumbent past a refusal that is not a wait; does not re-activate the build this host rolled back from; labels the launch with the build the adoption found serving, not the stale record; defers while another run holds the host fence; lets an explicit force deploy past both skips; names a newer host refusal apart from a rolled-back one, so only Force is offered; updates an older host as before, without asking to adopt it; never asks the incumbent when it already runs this build. src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts: keeps a completed listing usable when the host rejects the wait parameter. src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts: delivers to chat-default users in all targeting while holding out not-switched users. src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts: completes the row on a pick, even when the command is already typed; ignores a pick of the row while side chats are unavailable. src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts: explains a too-large refusal that arrives through the IPC error prefix. src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts: keeps the question with the caller and says once that it never went; tells the user to check the side chat when delivery is unconfirmed; reports a delivered question as sent, silently. src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts: decides each of %i tool-only turns once per layout, and nothing without a listener. src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx: places a side chat whose question was %s: %o. src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts: calls back once for %s; stops watching once unsubscribed. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts: routes terminal input through deferPtyInput so the host can withhold it; forwards terminal input directly when the host supplies no deferPtyInput. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts: requests a tab remount for an unbound spawn; leaves recovery to a remote transport that armed its own retry; requests a remount when the transport reports no recovery of its own; settles the spawn as failed before requesting a remount; prefers the restored leaf id when reporting the anomaly; falls back to the pane leaf id when no restored leaf exists. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionDeferredInputForwardingTests } from '../input/pty-connection-deferred-input-forwarding.spec', registerPtyConnectionDeferredInputForwardingTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts: registers interest on the first sidecar and releases on the last unsubscribe; releases sidecar interest only once for repeated unsubscribes; does not let an eager pre-mount buffer defeat hidden delivery gating; keeps eager buffers outside delivery interest when the PTY exits before mount; lets a sidecar exclusively own interest while an eager buffer overlaps. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts: blackholed delivery reproduces the wedge: no handler dispatch, no ACK ever. src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts: sends preferences to the execution host and attaches only to its returned PTY; preserves one operation ID across a lost reply and reconnect; preserves ordinary raw startup and captured-session attachment. src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts: sums registered gauges and drops disposed ones; ignores a repeated dispose instead of dropping another gauge; stops tracking new gauges past the cap so a missed dispose cannot grow it; tracks a live output processor queue through enqueue, drain, and dispose; excludes cleared consumed entries from retention after a bounded drain. src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts: says nothing once the pane is closed. src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts: refreshes after each scheduled atlas reset; falls back to a timeout when animation frames are unavailable; continues recovery when a manager throws after scheduling. src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts: tracks a remounted quiet title source even when the stale owner unregisters later; preserves the renderer-parsed output sequence in the response; preserves a pending escape tail for snapshot replay; routes a host's Reset Terminal request to the pane that owns the PTY. src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts: marks panes with restored scrollback for fresh-shell viewport blanking. src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts: recovers a 0x0 spawn whose container is briefly unmeasurable then settles. src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts: removes global listeners when the last pane unregisters. src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx: keeps trust text readable on a host-owned dialog surface; applies the hostile surface to ordinary dialogs, so the case above is exercised. src/renderer/src/components/use-terminal-parking-pass.test.tsx: does not queue a render when a pass produces the same parking sets; keeps parking transitions working under StrictMode. src/renderer/src/hooks/client-workspace-view-report.test.ts: reports an away user’s screen with no presence, and renews as soon as input returns; retries a failed send, empty or not, no sooner than a refresh. src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts: is new work in a workspace with no live terminal: its first bind moves it up in Recent. src/renderer/src/hooks/use-bundled-skill-install.test.tsx: ignores a repeated click while the install runs; retries the last requested skills on this host. src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx: adds seeds to a successful empty list but not to loading or failed results; retains seed projection after expiry and fetches fresh metadata for a new reader. src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx: retranslates the settings nav labels when the UI language changes live. src/renderer/src/lib/codex-stale-pane-account-identity.test.ts: keeps the prompt when the roster read fails and every label collapses. src/renderer/src/lib/image-blob-png.test.ts: downscales a pasted image above the pixel cap; releases its temporary URL on a decode error; releases its temporary URL when PNG encoding fails or exceeds the byte cap. src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts: names callers above the frame the write came from; restores Error.stackTraceLimit when the capture throws; stops collecting after the sample cap when captureStackTrace is unavailable; caps reported changed keys from a single wide write. src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts: applies the rendered text hard cap last and reserves the final overflow marker. src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts: keeps the runtime target identity stable across unrelated store writes. src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts: keeps creation available on old hosts and explains the missing operation; preserves landed warnings and direct collision recovery data; propagates remote discovery failure instead of a false empty page. src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts: reuses unchanged worktree tab projections when one worktree title changes; bumps only the changed worktree version when a sibling stays byte-identical. src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts: shares safe-auto fork sync cooldown attempts across store instances. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts: collapses a 193-workspace hydration to one store write; leaves the store byte-identical to the per-workspace path; re-reconciling the batched result is a no-op, as it is for the per-workspace path. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts: dedicated zero-case helper retirement; no authored test credit. src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts: persists each batch metadata update to its workspace owner. src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts: dismisses a rename error on its capable remote owner; clears pending first-agent rename when the title is updated. src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts: orders capture, guards, handlers, main's stop, commit, cleanup, and exit settlement. src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts: publishes the first terminal and root tab group atomically; publishes the first terminal and root tab group atomically, then marks it starting in main. src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts: restores daemon terminal wake hints before declaring the session ready. src/renderer/src/web/web-runtime-connection-auth-framing.test.ts: keeps legacy framing for sockets that cannot absorb a refused attempt. src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts: moves the old Windows default to Regular once and queues the notice; keeps custom weights and fresh profiles without a notice; leaves macOS and Linux profiles untouched. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, src/main/persistence/worktree-sort-order-write.test.ts, src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts, src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts, src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts, src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts, src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts, src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts, src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts, src/main/runtime/session-graph/headless-runtime-graph.spec.ts, src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts, src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts, src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts, src/main/runtime/terminal/identity/terminal-identity-probe.test.ts, src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts, src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts, src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts, src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts, src/main/runtime/terminal/surface/workspace-layout-projection.test.ts, src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts, src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts, src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts, src/main/skills/skill-install-transaction.test.ts, src/main/speech/model-manager-download-resume.test.ts, src/main/ssh/config/ssh-config-parser.test.ts, src/main/ssh/config/ssh-known-hosts-source.test.ts, src/main/ssh/config/ssh-known-hosts.test.ts, src/main/ssh/connection/ssh-connect-config.test.ts, src/main/ssh/connection/ssh-connection-auth-fallback.test.ts, src/main/ssh/connection/ssh-connection-store.test.ts, src/main/ssh/connection/ssh-connection.test.ts, src/main/ssh/orcad-migration-stuck-host-profiles.test.ts, src/main/ssh/orcad-runtime-maintenance.test.ts, src/main/ssh/port-forwarding/ssh-port-forward.test.ts, src/main/ssh/ssh-channel-multiplexer.test.ts, src/main/ssh/system-transport/system-ssh-forward-process.test.ts, src/main/ssh/system-transport/system-ssh-loopback-route.test.ts, src/main/startup/browser-process-user-agent-ordering.test.ts, src/main/startup/quit/quit-path-durable-write-blocking.test.ts, src/main/stats/agent-session-transition-recorder.test.ts, src/main/text-generation/commit-message-text-generation-model-discovery.test.ts, src/main/text-generation/pull-request-context.test.ts, src/main/text-generation/source-control-local-process.test.ts, src/main/updater/linux-package/linux-package-update-recovery.test.ts, src/main/updater/releases/updater-prerelease-feed-readiness.test.ts, src/main/updater/releases/updater-release-builds.test.ts, src/main/updater/updater.build-channel-selection.test.ts, src/main/updater/updater.check-preflight.test.ts, src/main/updater/updater.prerelease-fallback.test.ts, src/main/updater/updater.publishing-window-feed.test.ts, src/main/updater/updater.quit-and-install.test.ts, src/main/window/createMainWindow-markdown-editor-focus.test.ts, src/main/window/createMainWindow-renderer-crash-recovery.test.ts, src/main/window/dashboard-popout-window.test.ts, src/main/window/dropped-path-preparation.test.ts, src/main/window/main-window-updater-deferred-setup.test.ts, src/main/worker-threads/worker-thread-request-queue.test.ts, src/main/workspace-hooks/hooks-setup-runner-script.test.ts, src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts, src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts, src/main/workspaces/removal/local-worktree-removal-recovery.test.ts, src/main/workspaces/removal/worktree-removal-safety.test.ts, src/main/wsl/discovery/distro-catalog.test.ts, src/main/wsl/discovery/wsl-distro-holder.test.ts, src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts, src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts, src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts, src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts, src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts, src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts, src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx, src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts, src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts, src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts, src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts, src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts, src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts, src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts, src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts, src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx, src/renderer/src/components/use-terminal-parking-pass.test.tsx, src/renderer/src/hooks/client-workspace-view-report.test.ts, src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts, src/renderer/src/hooks/use-bundled-skill-install.test.tsx, src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx, src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx, src/renderer/src/lib/codex-stale-pane-account-identity.test.ts, src/renderer/src/lib/image-blob-png.test.ts, src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts, src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts, src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts, src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts, src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts, src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts, src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts, src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts, src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts, src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts, src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts, src/renderer/src/web/web-runtime-connection-auth-framing.test.ts, src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", @@ -12772,7 +12837,16 @@ "Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", "Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. All prior notes and dated/archived evidence retain original scopes.", "Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes." + "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", + "Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed.", + "Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope.", + "Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection.", + "Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope.", + "Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope.", + "Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope.", + "Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed.", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed.", + "Audit4358 retired original selector fields (historical provenance only; no current execution claim): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts\",\"pnpm run build:electron-vite\",\"node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs\",\"node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\"ELECTRON_RUN_AS_NODE=1 pnpm exec electron config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\"pnpm exec vitest run --config config/vitest.config.ts\"],\"testFiles\":[\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts\",\"src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts\",\"src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts\",\"src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts\",\"src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts\",\"src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts\",\"src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts\",\"src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts\",\"src/main/ipc/worktrees-orphan-directory-cleanup.test.ts\",\"src/main/ipc/worktrees-remove-preflight.test.ts\",\"src/main/workspaces/removal/watcher-removal-gate.test.ts\",\"src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts\",\"src/main/providers/local-pty/local-pty-provider-shutdown.test.ts\",\"src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\"src/main/runtime/files/watch/orca-runtime-files-watch.test.ts\",\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/main/runtime/rpc/methods/files/files.test.ts\",\"src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts\",\"src/renderer/src/web/web-runtime-client.test.ts\",\"src/shared/cross-platform-path.test.ts\",\"src/shared/physical-exit-tracker.test.ts\",\"src/shared/promise-settlement-waiters.test.ts\",\"config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\"config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs\"]}" ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, @@ -13068,26 +13142,14 @@ "shellcheck config/docker/headless-serve-shutdown/run-signal-case.sh", "shellcheck config/docker/headless-serve-shutdown/run-appimage-desktop-startup-case.sh", "node config/scripts/runtime-verification/daemon-lifecycle/run-headless-serve-shutdown-docker.mjs --appimage dist/orca-linux.AppImage", - "node config/scripts/runtime-verification/daemon-lifecycle/run-headless-serve-shutdown-docker.mjs --appimage dist/orca-linux.AppImage --platform linux/amd64", - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/startup/ensure-virtual-display.test.ts --maxWorkers=2 --reporter=dot" + "node config/scripts/runtime-verification/daemon-lifecycle/run-headless-serve-shutdown-docker.mjs --appimage dist/orca-linux.AppImage --platform linux/amd64" ], "testFiles": [ - "src/main/startup/ensure-virtual-display.test.ts", "config/scripts/runtime-verification/daemon-lifecycle/run-headless-serve-shutdown-docker.mjs", "config/docker/headless-serve-shutdown/run-signal-case.sh", "config/docker/headless-serve-shutdown/run-appimage-desktop-startup-case.sh" ], "assertionRefs": [ - { - "file": "src/main/startup/ensure-virtual-display.test.ts", - "assertions": [ - "owned Xvfb starts with terminate-after-last-client semantics", - "owned Xvfb uses an independent process group so terminal Ctrl-C cannot preempt Electron teardown", - "owned Xvfb retains an early-process-exit guard until Electron is ready", - "owned Xvfb is not stopped from Electron's cancelable will-quit event", - "external displays and non-Linux startup remain untouched" - ] - }, { "file": "config/scripts/runtime-verification/daemon-lifecycle/run-headless-serve-shutdown-docker.mjs", "assertions": [ @@ -13160,6 +13222,7 @@ "Keep exact listener, Xvfb, descendant, fatal-evidence, and canary identity assertions green." ], "knownGaps": [ + "The portable startup unit suite was removed after a source value audit; its mocked display admission, ownership, bind-race and protocol-selection alarms were deliberately dropped. Recorded unit runs are historical evidence only. The retained packaged signal journey does not replace those unit alarms.", "The local arm64 Docker host uses Rosetta for amd64 containers; native amd64 PR CI supplies the non-emulated repeat of the same extracted-AppRun PID contract.", "Ubuntu 20.04 is covered by the packaged native-binary glibc floor gate; this lifecycle journey runs on the reported Ubuntu 26.04 topology.", "Systemd units that override or omit the documented KillMode=mixed policy can still terminate owned Xvfb before Electron disconnects.", @@ -13184,13 +13247,13 @@ "providers": ["local-daemon"], "coveredPlatforms": ["linux"], "coveredProviders": ["local-daemon"], - "coverageNotes": "A restricted Ubuntu container stages the extracted AppImage payload with no /dev/fuse and with unprivileged user namespaces denied, then runs eight CLI cases across the bundled launcher and the extracted direct binary. x64 only, because PR CI builds only --x64.", + "coverageNotes": "Audit3930: The two dated evidenceRuns remain verbatim historical records for their original eight-case source. They are not fresh execution of the reduced three-case selector and do not validate all current output oracles: the original red/green account notes that earlier skills passes predated the stronger own-output matcher. Audit3925: Reduce eight hostile CLI examples to three: bundled status with no runtime, direct-binary skills text dispatch, and stale-display GUI diagnosis. Remove extra bundled help/version/skills/worktree and absent-display GUI examples; accept loss of packaged version equality and their exact output alarms without equivalent replacement. The reduced selector has no fresh execution evidence. Historical prior account (preserved verbatim): A restricted Ubuntu container stages the extracted AppImage payload with no /dev/fuse and with unprivileged user namespaces denied, then runs eight CLI cases across the bundled launcher and the extracted direct binary. x64 only, because PR CI builds only --x64.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13719", "https://github.com/stablyai/orca/issues/14229" ], "invariant": "On a host without FUSE and without unprivileged user namespaces, every packaged CLI entrypoint either completes its command or reports a diagnosis, and never terminates on a signal.", - "oracle": "Build the image, stage the AppImage payload, and run each case in the restricted container. Assert the preconditions first: unshare -Ur must fail and /dev/fuse must be absent, so a relaxed runner fails the job rather than silently skipping. For each case require the exact expected exit status and an expected substring of the command's own output, with the harness RESULT/CRASHED/PRECONDITION_FAILED control lines excluded so a case name can never satisfy its own assertion. Any status of 128 or above is a crash and fails immediately. The per-case timeout is a failure deadline, never a success condition.", + "oracle": "Audit3925: Reduce eight hostile CLI examples to three: bundled status with no runtime, direct-binary skills text dispatch, and stale-display GUI diagnosis. Remove extra bundled help/version/skills/worktree and absent-display GUI examples; accept loss of packaged version equality and their exact output alarms without equivalent replacement. The reduced selector has no fresh execution evidence. Historical prior account (preserved verbatim): Build the image, stage the AppImage payload, and run each case in the restricted container. Assert the preconditions first: unshare -Ur must fail and /dev/fuse must be absent, so a relaxed runner fails the job rather than silently skipping. For each case require the exact expected exit status and an expected substring of the command's own output, with the harness RESULT/CRASHED/PRECONDITION_FAILED control lines excluded so a case name can never satisfy its own assertion. Any status of 128 or above is a crash and fails immediately. The per-case timeout is a failure deadline, never a success condition.", "commands": [ "node config/scripts/runtime-verification/desktop-transport/run-linux-cli-launch-contract-docker.mjs --appimage dist/orca-linux.AppImage", "shellcheck config/docker/cli-launch-contract/run-cli-case.sh" @@ -13203,9 +13266,8 @@ { "file": "config/scripts/runtime-verification/desktop-transport/run-linux-cli-launch-contract-docker.mjs", "assertions": [ - "the bundled launcher serves --help, --version, status, skills --help, and worktree list without Chromium", + "the bundled launcher reports status with no runtime without Chromium", "a direct binary launch reaching JavaScript runs the command instead of booting a GUI", - "a desktop launch with no display reports the missing-display diagnosis instead of trapping", "a stale DISPLAY is diagnosed rather than trusted", "expected output is matched against the command's own output, not the harness control lines" ] @@ -13242,15 +13304,15 @@ ], "runtimeBudget": { "p95Seconds": 300, - "scope": "eight CLI launch cases in one restricted Ubuntu container" + "scope": "three CLI launch cases in separate restricted Ubuntu containers" }, "flakeHistory": { "status": "not-started", - "evidence": "The harness is new; soak history is not yet available." + "evidence": "Audit3925: Historical prior-source evidence only; reduced selector has no fresh execution evidence. The harness is new; soak history is not yet available." }, "redGreenEvidence": { "status": "complete", - "evidence": "The same harness run against a stock release AppImage failed four of eight cases: nofuse-userns-bundled-version at status 93, and all three direct-binary cases crashed at status 133 (SIGTRAP, the uv_close abort of #13719 and #14229). The stack-tip AppImage passed all eight. Corroborated at artifact level: the stack-tip runtime is a static-pie ELF with no PT_INTERP, the stock runtime is dynamically linked. Caveat: the two skills cases previously asserted a substring that the harness's own RESULT line contained, so they passed independently of command output; both now assert the rendered help header, and the green runs above predate that change." + "evidence": "Audit3925: Historical prior-source evidence only; reduced selector has no fresh execution evidence. The same harness run against a stock release AppImage failed four of eight cases: nofuse-userns-bundled-version at status 93, and all three direct-binary cases crashed at status 133 (SIGTRAP, the uv_close abort of #13719 and #14229). The stack-tip AppImage passed all eight. Corroborated at artifact level: the stack-tip runtime is a static-pie ELF with no PT_INTERP, the stock runtime is dynamically linked. Caveat: the two skills cases previously asserted a substring that the harness's own RESULT line contained, so they passed independently of command output; both now assert the rendered help header, and the green runs above predate that change." }, "performanceBudget": { "required": false, @@ -13262,6 +13324,7 @@ "Re-run red/green against a stock AppImage after any change to the launcher entrypoint." ], "knownGaps": [ + "Audit3925: Reduce eight hostile CLI examples to three: bundled status with no runtime, direct-binary skills text dispatch, and stale-display GUI diagnosis. Remove extra bundled help/version/skills/worktree and absent-display GUI examples; accept loss of packaged version equality and their exact output alarms without equivalent replacement. The reduced selector has no fresh execution evidence. Original dated receipt objects are preserved in evidenceRuns as historical records only; no fresh native or reduced-selector validation is claimed. Skills matcher limitations remain in redGreenEvidence.", "The preconditions depend on moby's default seccomp profile denying unshare(CLONE_NEWUSER) and on /dev/fuse being absent. A runner with a relaxed profile or a mounted /dev/fuse trips PRECONDITION_FAILED and fails the job rather than skipping.", "x64 only: PR CI builds only --x64, so the arm64 launcher path is unexercised.", "The harness covers CLI entrypoints only; it does not exercise a full desktop session." @@ -14010,10 +14073,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coverageNotes": "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "oracle": "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", "commands": [ "gh workflow run packaged-browser-e2e.yml", "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", @@ -14062,6 +14125,48 @@ "Collect repeated scheduled history before making this required." ], "knownGaps": [ + "Audit3814 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle from a Codex ready prompt even when stale startup lines remain :: Stale MCP startup lines must not block a later Codex ready header.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle when a stale Codex prompt is followed by the ready header :: A Codex ready header following a stale resume prompt must satisfy tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210) :: Later Cursor idle banner overrides retained trust dialog.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not block a mid-run Cursor lane on its dismissed trust dialog (#8210) :: Dismissed trust dialog must not report blocked for later busy Cursor; wait times out.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: does not classify unrelated press-enter prompts as Codex blocked prompts :: Unidentified press-enter text must time out rather than be classified Codex blocked.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: resolves tui-idle for quiet background PTY agents without OSC titles :: Quiet Codex background terminal without OSC title eventually resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts :: sends agent prompts as bracketed paste before submit :: Driving prompt escapes embedded paste-end ESC, writes one framed paste then CR, and counts bytes.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: settles a foreground Codex prompt when launch metadata has not arrived :: Codex inferred from foreground without launch metadata waits for composer marker/quiescence before one CR.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: gives a late Codex render marker a fresh quiescence window :: Marker arriving at7.9s re-arms fresh quiet window instead of submitting at initial cap.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: writes large agent prompt paste frames atomically before delayed submit :: A prompt larger than input chunk budget is a single paste write before delayed CR with exact byte count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects oversized terminal.send text before provider writes :: Oversized ordinary terminal.send rejects input-too-large before any provider write.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts :: rejects focusing an exited background terminal session :: focusTerminal refuses terminal_exited before invoking background reveal.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: pastes the same bytes the desktop draft paste sent for the prompt :: Launch-ready prompt normalizes CR/LF and renders embedded ESC visibly identically to desktop bracketed paste.\nsrc/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts :: keeps a prompt into a running agent behind the render settle, as before :: Driving prompt remains held through7s repaint activity then submits once by9s.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reports a queued PTY focus as not navigated when its notifier disappears :: Queued PTY focus and completed active reveal report not navigated after notifier removal; no second reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: does not invoke a stale graph-leaf focus notifier after queued PTY work :: Queued graph-leaf focus must not invoke old notifier after preceding PTY reveal and notifier removal.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: paginates retained terminal output with explicit limits and truncation metadata :: Preview120lines, fractional limits,50/200 pages, retained2000line truncation and future-cursor metadata stay consistent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: falls back to renderer visible screen when uncursored TUI tail is blank :: Substantial blank uncursored tail uses mounted renderer visible screen with zero scrollback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: reads and shows the runtime-owned alternate-screen grid without serialization :: Actual runtime alternate-screen grid provides read/show content without renderer/provider serialization.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: classifies older provider alternate-screen snapshots from ANSI :: Older provider without alternateScreen metadata classifies ANSI alternate entry and returns Remote Vim screen.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts :: honors the last ANSI screen transition when older provider metadata is absent :: Last ANSI alternate exit overrides earlier entry when explicit provider mode metadata is absent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: rejects a full provider screen frame after live output advances :: Live output arriving during second full-screen capture causes screen-unavailable rather than stale full frame.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: shares one provider snapshot between concurrent read and show calls :: Concurrent read/show share one successful provider snapshot and both receive Shared TUI content.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps cursor reads provider-free on restored alternate-screen PTYs :: Restored alternate-screen cursor transcript reads never acquire provider snapshot.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: backs off after a provider snapshot failure instead of retrying for show :: Failed provider capture is cached/backed off so later show does not retry.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: falls back once to a mounted renderer when a known alternate provider fails :: A known-alternate failed provider capture falls back exactly once to newly mounted renderer.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: bounds provider visible frames for read and show responses :: Provider visible read/show use six bounded lines and300character preview.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: keeps renderer-fallback composer drafts separate from terminal output :: Renderer fallback strips dim composer draft from terminal output and exposes draft separately.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts :: does not use renderer visible-screen fallback for a short blank shell tail :: Two blank shell lines must not trigger renderer screen fallback.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: trims terminal tail character budget without per-line array shifts :: Tail builder trims to256KiB with correct retained suffix and no Array.shift calls.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains ANSI-only status redraws instead of appending every frame :: Repeated erase/redraw replaces preview until newline then publishes one completed cursor row.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains split multi-line ANSI footer redraw state across chunks :: CUU state across chunks retains corrected footer rows and publishes new cursor entries.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not let stale lower rows hide earlier corrected footer rows from cursor reads :: Earlier corrected footer row must not be hidden by stale lower rows in cursor reads.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: bounds completed transcript entries from a single multi-line redraw chunk :: Single redraw chunk bounds completed transcript to2000retained lines and correct oldest/next/latest cursors.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains multi-line ANSI redraws when the last footer row stays partial :: Partial final redrawn row appears in preview but cursor sees it only after newline.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: does not retain split ANSI controls as visible terminal preview text :: Split color/mode escapes never leak preview fragments; long split OSC title truncates at MAX_OSC_TITLE_CHARS.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts :: retains same-line redraw cursor position across split full-line erase chunks :: Full-line erase preserves column across chunks so XY follows three spaces rather than old ABC.\nsrc/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts :: fills the requested line count even when blank rows sit below the prompt :: Blank rows below a ConPTY prompt must not consume the requested nonempty-line count.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: does not retain split ST-terminated string controls as preview text :: Split ST-terminated Kitty/string controls must remain excluded from preview text.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects split OSC titles before retaining terminal previews :: Split BEL OSC title must update working title/status without leaking into preview.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: detects ST-terminated OSC titles split before the final backslash :: ST OSC split before final backslash must update title without leaking framing.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: preserves a trailing escape after a completed OSC title :: Completed OSC followed by pending ESC must preserve the next idle-title transition.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: seeds newly synced leaves from PTY pending ANSI state :: A newly synced graph leaf inherits pending ANSI so a split color fragment cannot leak.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: bounds retained partial terminal output before preview reads :: Partial terminal state stays capped at 4000, preserves retained array identity, and preview truncation/cursor output remains correct.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts :: submits the mail pointer to Cursor Agent only after the paste-burst delay :: Cursor mailbox pointer Enter must wait through the paste-burst delay; this is a real input-timing alarm intentionally retired.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts :: adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction :: Stale incarnation refuses without topology change; three agent/setup/shell lanes adopt atomically with layout/group/revision and preserved read/input/resize; exact replay is idempotent and competing owner refuses.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: retires the exact worker when it exits after renderer reveal :: Exact worker exit after reveal retires that worker and its surface.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: re-reveals a recovered worker after the renderer graph epoch changes :: Changed renderer graph epoch invalidates reveal receipt and forces another reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: defers recovery when the renderer omits the exact reveal identity :: Missing exact reveal identity defers recovery after two attempts.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts :: reconciles a same-id process replacement before headless adoption :: A process replacement before headless adoption must fence off stale ownership.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retires provider resume only after authoritative inventory proves the legacy PTY exited :: Authoritative owning-host inventory overrides false local hasPty, avoids SSH scanning, retires exited provider resume/surface, adopts live workers without headless reveal.\nsrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts :: retries inventory and unknown liveness without revealing a ghost worker :: Inventory failure and unknown liveness must retry without ghost reveal, eventually adopt, and stop retrying.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts :: refuses a live reserved pane before issuing a handle or revealing it :: A requireFreshPane launch receiving a live reserved owner must reject before handle/reveal/kill, and release its claim. No equivalent replacement claimed.", + "Audit3806 per-case accepted runtime losses:\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: skips a listener unsubscribed mid-fan-out even with mobile exclusions active :: A listener removed by an earlier listener during one fanout is not called, including with a side-effect-excluded mobile listener present.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: retains bytes emitted before a fresh daemon spawn resolves :: Bytes and title arriving before an initial zero/reset provider response survive in the serialized headless buffer with their counted sequence.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits command-finished facts with best-effort exit codes across chunk splits :: A split OSC133 D exit code becomes130 and a missing code becomes null in ordered command-finished facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts :: emits pr-link facts once per URL with batch attribution :: A split GitHub PR URL yields42 rather than4, emits42/43 once each, and carries PTY/worktree/tab attribution.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits 2031-subscribe facts across chunk splits :: Split ESC[?20 then31h emits exactly one2031-subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: restores a provisional 2031 subscribe when daemon scan authority returns :: Returning daemon scan authority with partial scan seed and pending2031 subscription restores exactly one subscribe fact.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers the tracked title over the renderer snapshot lastTitle :: A synthetic live Cursor title overrides stale renderer lastTitle while preserving renderer snapshot source.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: prefers provider history over a partial headless mirror for requested snapshots :: Authoritative requested snapshots return supplied provider frame/history/seq rather than a partial headless mirror, requesting5000rows.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: tracks live alternate-screen transitions after a provider snapshot :: Provider alternateScreen true is accepted, then live1049l/1049h update isTerminalAlternateScreen false/true.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: translates reset provider snapshots without retaining the old title :: A reset provider snapshot translates new local seq into the runtime domain and replaces Old process title with New process.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: emits the chunk agentStatus events before its side-effect batch :: Agent status callback precedes side-effect batch callback for one coalesced OSC9999/title/bell chunk.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: still emits a throwing chunk’s facts under its own seq, not the next chunk’s :: A tracker throw still flushes first chunk title facts under its own seq, and second chunk does not inherit those facts.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: seeds the lazily created tracker from the daemon-snapshot title :: A lazy tracker hydrated from renderer snapshot title Codex working emits agent-idle on later Codex done.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits command-code-working facts only after the banner arms the scrape :: Unarmed Thinking text emits no facts; a Command Code0.27.3 banner then hardcoded colored spinner text emits attributed command-code-working with the submitted prompt.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts :: emits a command-code-done fact when the idle composer returns :: After hardcoded banner/working text, returned idle composer emits command-code-done with the earlier submitted prompt.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: resizes the headless mirror after an accepted desktop PTY resize :: An external accepted resize produces the resized dimensions and same status-frame lines as a separately driven reference emulator.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: replaces suffix-only headless state with the recovered renderer snapshot :: Replacing suffix-only state removes old suffix, retains renderer history plus later output/cwd, and returns the live47x40PTY grid.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: stamps SSH connection identity on runtime terminal status :: A synthetic mounted-leaf OSC9999 status after registerPty carries the supplied SSH connectionId.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: does not retain WSL context when a PTY id is reused :: After exit and same-ID new null distro context, OSC7 file://server/share/repo uses UNC server path rather than old Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts :: preserves immutable context while a live daemon attach is unresolved :: preparePtyExecutionContext with preserveExisting refuses a supplied Debian replacement and subsequent OSC7 keeps original Ubuntu namespace.\nsrc/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts :: projects frame-independent live state through main buffer snapshots :: Main-buffer snapshot puts focus-report/cursor-visibility modes in frameRestoreAnsi, excludes STATIC-FRAME there and includes it in data.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts :: continues terminal agent status fanout when a callback throws :: Throwing on the first status callback does not prevent second payload delivery and logs contextual error.\nsrc/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts :: returns a title-only replay snapshot and never historical attention :: Lose replay:true/title-only fact projection despite earlierbell and unknownPTYnull. No actual delivered-history notification or reattach behavior was exercised. No equivalent replacement claimed.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects a handle rebind while a controller-less status check yields :: A handle rebound while the null-controller status continuation yields must throw terminal_handle_stale.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts :: rejects confirmation evidence when the owning PTY exits :: A pending strong confirmation resolving after owning PTY exit must reject terminal_exited.\nsrc/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts :: keeps ordinary terminal send suffix failures on the existing not-writable contract :: Ordinary send writes text but refused CR must throw terminal_not_writable with beforeWrite twice and afterWrite once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell the execution host cannot apply instead of spawning its default :: Requested Windows shell on POSIX must refuse before spawning a default shell.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: quotes the agent startup command for the requested shell, not the host default :: Requested cmd shell must override PowerShell default quoting for agent startup command.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: keeps restored receipts outside a targeted worktree scan :: Targeted scan removes the moved-worktree receipt while preserving another worktree receipt.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: observes setup command completion without waiting for its interactive shell to exit :: Nonzero completion marker 17 resolves while interactive shell remains running.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: falls back to setup terminal exit when no completion signal is available :: Setup completion observer without token falls back to actual exit code 9.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: cancels setup completion observation when the caller aborts :: Abort rejects with the original reason and unsubscribes once.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps observing after an uncertain setup terminal status :: Unknown exit waiter result must leave observation pending until completion marker arrives.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh omits a record :: Controller inventory omission disconnects the record but preserves its retained transcript.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: keeps retained PTY transcript memory when controller refresh times out :: Hung inventory timeout leaves connected record and retained transcript intact.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle for adopted background PTY handles from the renderer title :: An adopted background handle resolves tui-idle from ready Codex renderer title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves live-leaf tui-idle from an OpenCode native title :: A live leaf resolves tui-idle from an OpenCode native title.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from a Codex ready prompt preview :: A supplied Codex prompt preview resolves tui-idle without an actual agent.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts :: resolves tui-idle from an Antigravity prompt before the model line :: A supplied Antigravity prompt before model line resolves tui-idle.\nsrc/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts :: refuses a requested shell with no workspace instead of creating a default-shell tab :: Workspace-less explicit shell must reject before renderer default-tab request or spawn. This real guard/wiring alarm is deliberately retired.", + "Audit3798 per-case accepted losses:\nsrc/main/runtime/orca-runtime-tests/paired-settings.spec.ts :: awaits navigation-only updates from paired clients (%s) :: Updating only claudeSubagentNavigationEnabled waits for the actual controller call to the supplied pending Claude-view reconcile for both on/off values.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: drops a client page record even when its close command cannot be issued :: A removed workspace loses its runtime client-page record and headless browser projection despite close delivery_required rejection, and emits the asynchronous warning.\nsrc/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts :: leaves client-hosted pages alone when another host still owns the same worktree id :: Removing runtime:env-b metadata with local ownership leaves the local same-ID client page unchanged and issues no close command.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: marks live bindings again when reopening after a promoted window closes :: A reopened window marks its still-registered live worktree in activeWorktreeIdsOnShutdown after the first promoted window closes.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: preserves live SSH session identities when promoting a headless runtime :: Headless-to-desktop promotion records active worktree, SSH connection and remoteSessionIdsByTabId from the supplied surviving SSH PTY/session.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores a surviving renderer when its reload is cancelled :: A sole ready renderer reload cancelled under its current renderer fence returns true and becomes ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: restores headless authority when desktop promotion navigation is cancelled :: A cancelled desktop promotion with headless recovery returns false while headless authority remains ready.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: moves a desktop graph to unavailable when its reload times out :: A ready desktop graph without a headless fallback becomes unavailable at the reload deadline and retains its window/epoch.\nsrc/main/runtime/orca-runtime-tests/window-authority.spec.ts :: recovers a failed headless promotion and accepts a later renderer generation :: A promotion failure restores ready headless authority; a later valid same-window graph publishes ready desktop authority.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: clears a failed pane recovery so a later reconnect can retry :: After relay_reconnecting rejection, the pending recovery lock clears and the same pane/handle can call createTerminal a second time and return its supplied replacement.\nsrc/main/runtime/orca-runtime-tests/terminal-handles.spec.ts :: still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY :: An empty graph published during renderer reload preserves a preallocated live CLI PTY as one listable terminal before renderer rebind.\nsrc/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts :: keeps a no-incarnation handle across an in-graph pane remint :: Within one graph lifetime an unversioned PTY reminted onto another leaf retains its issued handle and resolves its old exit waiter after onPtyExit.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: matches explicit-id cwd PTYs when the resolved worktree cache is incomplete :: An explicit target absent from a fresh incomplete resolved cache adopts only its cwd PTY, rejects nested cwd PTY and does not rescan Git.\nsrc/main/runtime/orca-runtime-tests/terminal-listing.spec.ts :: ignores cwd-only controller PTYs for malformed explicit worktree IDs :: Malformed id:repo-1:: returns no terminals, does not adopt cwd-only controller PTY and avoids Git rescanning.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: refuses an SSH-backed create for mobile/runtime callers instead of creating locally :: Loss of this public unserved SSH create error-class/no-local-add/no-local-list alarm.\nsrc/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts :: records an app-selected parent workspace as a manual action :: Loss of the local runtime folder-parent manual origin, active-workspace source and explicit confidence projection alarm; no claim that SSH or cleanup coverage replaces it.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: browses runtime server directories before projects are added :: Loss of this public runtime alarm for browse availability before registration, directories-first lexical ordering and native path flavor.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts :: lists drive roots for a server-root browse :: Loss of the Windows public slash-root drive enumeration smoke and presence of the temporary directory drive.\nsrc/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts :: creates a missing runtime parent before creating the project directory :: Loss of this runtime createRepo recursive missing-parent/child existence and registered-path alarm.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: preserves selected project %s when a hosted parent is known :: Loss of both parent-selected and origin-selected normal fork-link projection/persisted upstream alarms plus exact single-probe count.\nsrc/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts :: links a current enterprise remote despite unavailable metadata and a retained %s :: Loss of normal current-enterprise-origin linking with stale automatic GitHub avatar or protected file image, unchanged icon assertion, and serialized project identity under unavailable metadata.", + "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical.", + "Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical.", + "Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope.", + "Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed.", + "Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes.", + "Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases.", + "Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit.", + "Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved.", + "Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits.", + "Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope.", + "Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit.", + "Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit.", + "Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit.", + "Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical.", + "Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit.", + "Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained.", + "Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit.", + "Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit", + "Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures.", + "Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise.", + "Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope.", + "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit.", + "Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation.", + "Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains.", + "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence.", + "Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope.", + "Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope.", + "Audit3630 removed orphan delete/toggle capability/precondition and run/edit refusal assertions. Real dispatch, mutation fencing, mixed-version and host outcomes are not established by this removal or by a substitute test.", + "Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope.", + "Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope.", + "Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope.", + "Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope.", + "Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope.", + "Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes.", + "Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed.", + "Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions.", "Launch direct-owner cleanup current scope: This gate’s unfiltered unit command now selects a suite reduced by 82 whole registrations / 159 potential table examples in 10 whole test Programs, including 8 registrations / 15 examples from five once-registered create-message factory closures. Lost alarms include frozen first-message/options and legacy-host fallback; distinct actions and redelivery; uncertain/refused/reloaded input custody, Retry and late proof; rich prompt/attachment upload Stop/close and handback; ordinary draft/editor/IME/StrictMode lifetime and accepted topology; provisional fallback tab placement/group/pin/order and rich worktree handoff. Four whole consent/resume-identity cases remain in two Programs; they do not replace these alarms. This entry governs current reduced-unit scope and qualifies any broader implication of unchanged oracle/coverageNotes history. Entire dated evidenceRuns, original commands/currentCommand values, counts/results and existing history retain their original scopes only; no fresh execution, transferred pass, replacement equivalence or prior upstream-removal credit is claimed.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/persistence/worktree-sort-order-write.test.ts: re-ranks every writable row when a blocked row sits in the requested order. src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts: continues skill management after startup recovery fails. src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts: uses bounded ownership lookup for direct arrivals while the agent cannot take input; wakes a bound Run waiter when same-Run direct mail arrives; keeps an unowned detached-recipient message in its direct mailbox; uses primary-key lookups for bounded routing updates. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts: remove only literal registration import/call pairs import './orchestration-mailbox-pointer-cli-command.spec'; no additional authored credit. src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts: renders the %s CLI command in a mailbox pointer. src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts: sizes a slow high-latency link near twice its bandwidth-delay product; never paces a LAN, even when its client parses slowly; never paces a fast link; returns to legacy windows when the path RTT jumps. src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts: steps down the row ladder when history is over the byte budget; tries the larger first row count, then the usual ladder within the same byte budget. src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts: returns unknown when route inspection fails or emits malformed data; does not inspect routes outside Windows. src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts: is refused to a paired %s client; reports a failed widening instead of advertising an unreachable address. src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts: reports exited only when the owning runtime completes the exit waiter; reports unverifiable when the runtime cannot observe the exit waiter; reports unverifiable when a disconnected PTY resolves with unknown liveness. src/main/runtime/session-graph/headless-runtime-graph.spec.ts: lets a session tab inventory settle on a host no renderer publishes for. src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts: remove only literal registration import/call pairs import { registerHeadlessRuntimeGraphTests } from './headless-runtime-graph.spec', registerHeadlessRuntimeGraphTests(); no additional authored credit. src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts: bumps the stored snapshot version only when the title changes. src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts: keeps the healthy aggregate verification and delayed physical exit behavior; uses a stamped exit for the incarnation that was actually being closed. src/main/runtime/terminal/identity/terminal-identity-probe.test.ts: answers live for a structured worker without touching the PTY graph; answers live for a PTY handle the runtime still holds; runs the full leaf check for a handle with no live PTY; answers not-live for a stale handle; propagates \"could not look\" rather than reporting it as a dead handle. src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts: names the tab in main’s layout through terminal.rename; takes a window-style layout.apply close as already stopped, so the terminal runs on. src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts: retains no lifecycle generation after a spawn/exit cycle. src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts: reads a freshly spawned terminal as used once a user opens its tab, not on a probe; keeps the open mark on the process a user open starts. src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts: from a desktop window that mounts both panes; from a server with no window. src/main/runtime/terminal/surface/workspace-layout-projection.test.ts: carries views for a partition that holds none yet. src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts: releases a signalled exit-waiter when the signal aborts. src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts: selects a local hook status for a local pane. src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts: keeps the footer and the bare caret on screen mid-turn; %s: the screen alone reads ready during %s. src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts: uses per-launch arguments and preserves launch telemetry; attributes a startup agent whose caller named no surface as unknown; launches %s bare for an absent or blank prompt; attributes a %s draft launch named %s as %s; merges an automation's extras over the host defaults; threads worktree-create extras into the startup build; returns an enabled requested agent without detecting; returns the default when nothing was requested; detects instead of using the default when the requested agent is disabled; starts no agent when the default is blank; detects an enabled agent on this host when nothing usable was named; starts no agent when detection finds none. src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts: pastes and submits through composer readiness, never typing raw input; types the follow-up on WSL or SSH-to-Windows once the agent is in front, as before; cleans up the deadline when the composer was already captured; a draft that is not submitted is pasted on the box cursor, as before; takes the box after the grace when the row never comes, whatever repaints; takes the box at the deadline when the grace would outlast the budget; lets a dialog on screen veto a grace; refuses the deadline inside a pending grace while a shell is in front; takes the box at the deadline inside a pending grace with the agent in front; takes the box at the deadline after a refused grace once the agent is in front. src/main/skills/skill-install-transaction.test.ts: installs, previews unchanged bytes, and updates a clean receipt-owned skill; preserves the old version after a %s filesystem failure. src/main/speech/model-manager-download-resume.test.ts: requests the remaining bytes when a clean range response ends before the file total; bounds a server that advances by pathologically tiny segments forever. src/main/ssh/config/ssh-config-parser.test.ts: parses a basic host block; parses multiple host blocks; skips wildcard-only Host entries; skips Host entries with only pattern characters; parses IdentityFile with ~ expansion; parses Windows-style IdentityFile with ~ expansion; parses quoted scalar values like OpenSSH; parses equals-form scalar directives; parses IdentityAgent with ~ expansion; parses IdentitiesOnly; parses GSSAPIAuthentication; keeps the first GSSAPIAuthentication value like OpenSSH; parses ProxyCommand, ProxyUseFdpass, and ProxyJump; ignores comments and blank lines; handles case-insensitive keywords; stops current block on Match directive; returns empty array for empty input; creates one parsed host per concrete alias on a multi-pattern Host line; applies identity agent settings to every concrete alias on a multi-pattern Host line; defaults port to 22 for invalid port values; converts hosts to SshTarget objects; uses host alias as hostname when HostName is missing; skips hosts that are already imported; defaults username to empty string when not specified; carries through identityFile, identityAgent, identitiesOnly, proxyCommand, and jumpHost; carries through gssapiAuthentication; imports duplicate aliases only once and keeps the first concrete host; maps hosts for the picker and flags aliases already in Orca; de-dupes aliases and defaults missing fields; parses hostname, user, port from ssh -G output; collects multiple identity files; parses forwardagent yes; defaults port to 22 when missing; returns empty hostname when missing; returns undefined user when missing; handles empty output; skips lines without spaces; parses proxycommand and filters \"none\"; parses proxyusefdpass yes; parses proxyjump and filters \"none\"; handles ~ expansion in identity file paths; handles Windows-style ~ expansion in identity file paths; parses identityagent with ~ expansion; preserves identityagent none so auth can disable agent fallback; parses identitiesonly yes; parses gssapiauthentication; parses controlmaster options and filters controlpath none. src/main/ssh/config/ssh-known-hosts-source.test.ts: splits the space-separated list ssh -G prints on one line; expands ~ in a reported path; keeps a double-quoted path containing spaces whole; falls back to the default files when ssh -G reported nothing; drops an explicit none without falling back to the defaults; splits both known_hosts lists on one line each; reads StrictHostKeyChecking, including accept-new; reads HostKeyAlias and prefers it for the lookup; reads the non-default port; reports that the lookup came from an alias, so the port is not appended; reports no alias when the dialed host is used; unions the entries of every file; skips a path that is a directory; returns nothing when no file can be read; reports nothing unreadable when every file parses; does not count an empty file as unreadable; prefers HostKeyAlias over the resolved hostname; uses the dialed host, because a resolved hostname can just echo the label; still prefers an explicit HostKeyAlias over the dialed host; falls back to the dialed host when nothing was resolved; is rejoined when the split fragments resolve to nothing; leaves a single unresolvable path alone rather than inventing one; expands the __PROGRAMDATA__ token rather than passing it through as a path; does not rewrite a path that merely BEGINS with the token characters; keeps a drive-letter path with mixed separators intact; splits a spaced Windows home into the fragments the rejoin has to put back. src/main/ssh/config/ssh-known-hosts.test.ts: reads the algorithm from the blob rather than trusting the line; rejects %s; refuses a malformed blob: %s; uses the bare host on the default port; tries the bracketed form first and falls back to bare off-port; matches an exact line; matches case-insensitively; reports a changed key of the same type; reports unknown for %s; matches any host in a comma list; matches the bracketed form on its port; does not apply a bracketed entry to the default port; falls back to a bare line when off-port; never reports a change from the fallback pass; matches a bare literal on the default port; matches a bracketed literal on its port; reports a change for a literal; handles %s; still reports a change for a different key on a revoked host; skips a line carrying an unrecognised marker; does not report a change when only another key type is on file; matches within the same type; accepts CRLF terminators; skips blanks, comments and surrounding whitespace; accepts a hit regardless of which file holds it (%s); never brackets the alias, whatever the port; still brackets an ordinary host on a non-default port; matches a bare alias entry on a non-default port; still accepts the unmodified key field; accepts a hashed entry whose salt is a full SHA1 digest; still accepts the unmutated ssh-keygen -H vector; falls back to the bare host line on a non-default port, as ssh did; refuses a key type it has not seen for a host it knows, as ssh did. src/main/ssh/connection/ssh-connect-config.test.ts: returns undefined when no default keys exist; returns the first existing key file; probes regular and FIDO2 keys in stable default order; keeps a regular default ahead of a malformed FIDO2 default; uses target host/port/username; falls back to resolved config when target fields are empty; keeps imported endpoint fields as the fallback when ssh -G is unavailable; sets readyTimeout to CONNECT_TIMEOUT_MS; sets keepaliveInterval to 15s; enables keyboard-interactive auth so MFA challenges can be answered; uses agent auth when no explicit key and SSH_AUTH_SOCK is set; enables agent forwarding when OpenSSH config requests it and an agent is available; does not enable agent forwarding without a usable agent; resolves IdentityAgent SSH_AUTH_SOCK from the environment; uses the Windows OpenSSH agent pipe when no environment socket is available on Windows; wraps agent auth with IdentityFile filtering when IdentitiesOnly is enabled; applies a manual target IdentitiesOnly setting when ssh -G reports it off; includes unencrypted target.identityFile auth when an agent is available; defers encrypted target.identityFile auth when an agent is available; uses keyFile auth when target.identityFile is set and no agent is available; includes unencrypted resolved identityFile auth when an agent is available; defers a default-path resolved identityFile to the no-agent retry; offers the keyboard-interactive challenge when the agent defers no key; provides fallback key when no agent is available; can force private key inclusion for the post-agent fallback path; falls back to resolved proxyCommand; returns structured jump-host config for target.jumpHost; returns structured jump-host config for resolved proxyJump; returns undefined when no proxy is configured. src/main/ssh/connection/ssh-connection-auth-fallback.test.ts: resolves OpenSSH config using configHost when present; tries ssh-agent before reading an explicit private key; falls back to direct private key auth when agent auth fails; falls back to direct private key auth after too many agent authentication failures; answers bounded keyboard-interactive challenges such as Duo 2FA. src/main/ssh/connection/ssh-connection-store.test.ts: lists picker suppression aliases without consulting re-adoption tombstones; getTarget delegates to store; addTarget generates an id and persists; saves the CLI control switch as given, with no consent stamp; addTarget stamps source as manual by default; addTarget preserves an explicitly provided source; inserts a new config host stamped as ssh-config; asks the parser for all hosts — reconciliation happens in the store; updates an existing config-sourced target when the port changed; refreshes gssapiAuthentication on sync; never overwrites a manual target that owns the alias; does not rewrite an unchanged config-sourced target; returns empty array when nothing changed; tombstones a deleted config-sourced host so re-import skips it; suppresses a deleted manual target from config discovery; re-adding a deleted host reclaims its alias so sync stops suppressing it; editing a target reclaims its alias from the deleted set; records a tombstone when removing any user-facing target; re-adopts orphaned repos when the same host is re-added. src/main/ssh/connection/ssh-connection.test.ts: transitions to connected on successful connect; captures the negotiated SSH server key fingerprint; allows concurrent exec commands for ssh2 transport; removes startup listeners after ssh2 connect succeeds; scopes lifecycle events and pending handshake timers to one mock client; enables TCP_NODELAY on the new ssh2 client after a reconnect cycle; transitions through connecting → connected states; reports error state on connection failure; disconnect cleans up and sets state to disconnected; getTarget returns a copy of the target; getState returns a copy of the state; throws when connecting a disposed connection. src/main/ssh/orcad-migration-stuck-host-profiles.test.ts: never leaves a running terminal behind; is offered only when leaving saved state behind would clear the refusal. src/main/ssh/orcad-runtime-maintenance.test.ts: keeps a connect from retrying a build an explicit Update also failed; offers Force when Update was refused by policy; forwards anew after an activation, since the new slot may bind another port; passes a refusal through and leaves the server linked; forwards anew once a serving slot is restored, which may have bound another port. src/main/ssh/port-forwarding/ssh-port-forward.test.ts: reports the port the OS bound when an ssh2 forward asks for port 0; adds an ssh2 port forward and returns entry; adds a system SSH port forward when no ssh2 client is available; reports the port a system SSH forward resolved when asked for port 0; passes resolved OpenSSH config to system SSH port forwards; disposes a system SSH tunnel when removing the forward; lists forwards filtered by connectionId; removes a forward by id; awaits forward close when removing a forward for user actions; returns null when removing nonexistent forward; removes all forwards for a connection; dispose removes all forwards; stores label in the entry; preserves the existing id when updating a forward succeeds. src/main/ssh/ssh-channel-multiplexer.test.ts: sends a JSON-RPC request and resolves on response; assigns unique request IDs; sends notifications without expecting a response; dispatches incoming notifications to handler; sends one keepalive frame per cadence tick; drives keepalive sends AND dead-link detection from a single interval; resolves false immediately on a disposed mux; throws on request after dispose; reports isDisposed correctly; clears registered handlers on dispose; does not retain handlers registered after dispose. src/main/ssh/system-transport/system-ssh-forward-process.test.ts: spawns exactly the argv the orphan matcher is given, LogLevel=INFO included; runs port forwards unmultiplexed even when ssh_config disables muxing; preserves manual target port and identity options in the forwarded ssh command; does not spawn ssh when the requested local forward port is already in use; spawns ssh after the requested local forward port preflight succeeds; resolves startup after the grace period when ssh keeps running; sends SIGTERM then SIGKILL when the process does not exit; does not resolve stop until the process exits. src/main/ssh/system-transport/system-ssh-loopback-route.test.ts: dials the held forward ahead of the alias so OpenSSH keeps these over ssh_config; drops a manual target's own port and proxies, which would fight the route; never routes a forward, whose argv must stay stable for orphan recovery; %s → %s; opens the forward over the real proxy, then proves a login over the route; lands the forward on the sshd and known_hosts name the direct route resolved; holds the forward with server-alive probes; never lets the background forward or probe ask for credentials; starts no forward when admission refuses the route; stops the forward when sshd refuses logins over it; stops the whole forward process tree on Windows, once; reports a forward that already exited before anyone listened for it. src/main/startup/browser-process-user-agent-ordering.test.ts: explains admission refusal before a desktop launch exits; explains an orcad holding the profile instead of exiting silently; does not acquire profile admission for a duplicate launch; executes after the dev app name and before later preflight work; exits and releases admission after pending profile move recovery fails; keeps Linux background startup failures console-only and immediate; keeps Linux serve startup failures console-only and immediate. src/main/startup/quit/quit-path-durable-write-blocking.test.ts: store.flushAsync() issues no synchronous fs syscalls; store.flushAsync() also moves the active-view and github-cache sidecars off the thread; stats.flushAsync() issues no synchronous fs syscalls; Grok session cleanup issues no synchronous fs syscalls; stats.flushAsync() closes out live agents before it returns, not when its write lands; a stalled mount leaves the event loop live instead of parking it; store.flushAsync() is one idempotent final barrier; store.flushAsync() resolves instead of throwing when the profile mount rejects writes. src/main/stats/agent-session-transition-recorder.test.ts: counts a hook-only agent that never writes an agent-shaped terminal title; never opens a session from a replayed or disk-restored working status; still closes a live session when the terminating status arrives as a replay; counts one session per turn across repeated working/done cycles; closes an open session when its pane is torn down; bounds the mirror and closes what it evicts; stops the session when the main agent settles and only a watch loop holds the row working; keeps the session open while a subagent outlives the main agent, and closes it when the child settles; dates the stop by the evidence when a shell outlives the last subagent; opens a new session dated by the observation when the main agent resumes after monitoring; never dates a reopen before the close a fact-less OSC repaint caused; dates the first live row after a restored one by the evidence, not the restored clock; treats an unchanged answer as a snapshot, never a transition; opens only on a live working edge; closes only a session it opened. src/main/text-generation/commit-message-text-generation-model-discovery.test.ts: returns static catalog models without spawning for static agents; discovers dynamic models through the agent CLI; discovers dynamic models through the configured agent command override; falls back to static models when dynamic discovery returns no parseable models; falls back to the first discovered non-Pi model when its static default is unavailable. src/main/text-generation/pull-request-context.test.ts: does not fetch unrelated fork remotes before generating PR context; bounds exact remote-ref probe concurrency for a large remote list; reports no branch change because PR context preparation is read-only; keeps a remote-qualified base when the selected base includes the remote. src/main/text-generation/source-control-local-process.test.ts: asks the supervisor to stop and leaves its group to it; signals nothing once the supervisor has exited; stops an agent that ignores its stdin end through its supervisor. src/main/updater/linux-package/linux-package-update-recovery.test.ts: retains the downloaded package with the digest from the event metadata; requires a string downloaded path; accepts an uppercase extension; requires a non-empty string version; matches an absolute file URL by basename; accepts duplicate entries that agree on the digest; refuses an entry with a missing or non-string digest; refuses a digest that is not base64 at all; refuses a malformed percent-encoded URL; refuses a missing or non-array file list; tolerates a non-object event; replaces the retained artifact with a newer download; keeps the retained artifact when a new download has no usable digest; keeps the retained artifact when an unrelated download event arrives; clears the retained artifact; preserves the artifact across a recheck of the same version; clears the artifact when another version takes over; preserves the artifact for an unknown or empty version; is a no-op without a retained artifact; returns the built command and package file name for a verified package; reports missing without a retained artifact; propagates a package-manager discovery failure; rejects a well-formed digest that belongs to another file; never hashes a package that a malformed digest failed to arm; rejects a path outside the cache root; rejects the cache root itself; rejects a package in the updater directory itself; rejects a pending directory that is a symlink out of the cache; performs one hash pass for concurrent requests; revalidates once the in-flight pass settles; does not reuse an in-flight pass for a different artifact; starts a fresh proof when the same package is captured again; returns the verified package path; returns missing without a retained artifact. src/main/updater/releases/updater-prerelease-feed-readiness.test.ts: accepts a GitHub %s asset redirect as ready; reports a GitHub asset request error as unavailable; reports not-ready with a verified last-good tag when the newest assets are unavailable; does not classify a non-positive tag limit as feed unavailability; reproduces the v1.4.142 publishing incident as not-ready; reports transport failures as unavailable instead of not-ready; treats an explicit asset 404 as not-ready when another asset is unavailable; accepts absolute manifest asset URLs without rewriting them to release asset paths; returns not-ready with an older ready update as last-good while newest is publishing. src/main/updater/releases/updater-release-builds.test.ts: lists hourly builds from the dedicated repo, newest first; lists daily builds from the dedicated repo, newest first; separates stable from rc in the shared main repo; skips drafts and unparseable tags; keeps a composed release title and drops one that repeats the tag; hides builds that published no artifact for this platform; returns an empty list when no build has this platform artifact; keeps mac builds visible on macOS regardless of the Windows leg; resolves the platform installer download url; leaves the installer url null when the release published no installer; tolerates a release whose assets are missing or malformed; sends the local gh token as a bearer header when one is available; sends no authorization header when gh has no token; retries unauthenticated once when GitHub rejects the token; does not retry a 401 that was already unauthenticated; falls back to the per-IP bucket when the token is rate limited and tells the gh breaker; reports a secondary limit carrying retry-after without retrying or tripping the breaker; records a primary limit in the token scope %s; keeps %s authenticated when only %s is blocked; skips the token while its scope %s is blocked; surfaces a rate limit with its reset time and a sign-in hint when unauthenticated; omits the sign-in hint when the rate-limited request was authenticated; treats 429 as a rate limit; reports a 403 without rate-limit headers as a plain HTTP error; reports a missing hourly repo distinctly; is null when GitHub sent no reset; prefers retry-after over the primary reset epoch; falls back to the primary reset epoch when there is no retry-after; reads retry-after as seconds; reads retry-after as an HTTP date; pins an hourly tag at the hourly repo download path; pins a daily tag at the daily repo download path; pins a stable tag at the main repo download path; rejects a tag that is not a version. src/main/updater/updater.build-channel-selection.test.ts: uses the display label in the unsupported-platform %s pinned-build error; still pins %s from an unsigned Windows dev build; restores ordinary release checks after local build selection fails; opts into the RC channel when checkForUpdatesFromMenu is called with includePrerelease; pins the generic feed to a perf-tagged prerelease when requested; surfaces no-update feedback when no newer perf-tagged prerelease exists; keeps prerelease publishing-window misses on the generic retry path; leaves the feed URL alone for a normal user-initiated check. src/main/updater/updater.check-preflight.test.ts: ignores a stale update-not-available event after a new check starts preflight; deduplicates repeated manual checks while the immediate checking status is active. src/main/updater/updater.prerelease-fallback.test.ts: retries a prerelease check once against the previous feed tag when the manifest is missing; surfaces a promise-only prerelease fallback failure after the primary error event. src/main/updater/updater.publishing-window-feed.test.ts: repins the generic feed to the newest RC tag for a prerelease user; repins the generic feed to a newer stable tag for a prerelease user; pins a stable fallback when Atom has no newer prerelease; uses last-good concrete feed when a user-initiated check lands during publishing; can offer an older fully published update while the newest release is publishing; keeps background publishing-window fallback on the short retry cadence. src/main/updater/updater.quit-and-install.test.ts: surfaces an accepted retry before electron-updater emits download progress; defers quitAndInstall and runs its launcher within the launch PATH scope; runs pre-quit cleanup before local PTY cleanup during update install; keeps optional pre-quit cleanup fail-and-continue behavior by default; ignores duplicate quitAndInstall requests while the shared delay is pending; arms the forced-exit watchdog once the install commits; disarms the forced-exit watchdog when sync install error recovery keeps the app open. src/main/window/createMainWindow-markdown-editor-focus.test.ts: ignores traffic light sync IPC on non-macOS; still intercepts Cmd+Shift+B and Cmd+Alt+B when the markdown editor is focused; coerces non-boolean setMarkdownEditorFocused payloads to false; opens a table-aware context menu synchronously without a renderer query; builds the plain edit menu for the one right-click the renderer marks as plain text. src/main/window/createMainWindow-renderer-crash-recovery.test.ts: notifies the caller when the renderer process is gone; passes the renderer webContents id through crash recording and recovery callbacks; forwards expected renderer teardowns so the recorder can diagnose suppression; reloads the app shell after an unexpected renderer process loss; does not reload after renderer loss when recovery is disabled; stops auto-reloading after a rapid renderer crash loop trips the breaker. src/main/window/dashboard-popout-window.test.ts: updates the title after language initialization and unsubscribes when closed; lets its preload expose saved WSL hosts in serve-only, and passes nothing otherwise; creates a native-frame window with the shared preload and no webview surface; shows the window on ready-to-show; loads the prod file entry; loads the dev server URL when in dev; focuses the existing window instead of creating a second one; trusts only the live popout webContents; restores a minimized window when re-requested; restores valid persisted bounds; discards off-screen persisted bounds and falls back to defaults; persists bounds on resize after the debounce, guarding near-minimum sizes; keeps saving bounds after a vetoed quit and freezes them only on an allowed quit; closeDashboardPopout closes an open window; applies the persisted app zoom level on dom-ready; follows app zoom changes while open and unsubscribes on close; zoomDashboardPopoutIfFocused steps the popout zoom only while focused; handles the zoom-in chord via before-input-event and ignores other keys; handles mouse-wheel zoom requests outside before-input-event; respects zoom keybinding overrides for keyboard and mouse-wheel paths. src/main/window/dropped-path-preparation.test.ts: opens and stores each unique source once as drop size grows tenfold; passes ordinary paths without copying for %s; preserves ordinary successes and copied successes when another file fails; serializes copy requests from different owners; reports all lost paths without a shared reason when their failures differ. src/main/window/main-window-updater-deferred-setup.test.ts: releases all 64 completed fallback handles without repeating initialization; keeps setup after ready-to-show and releases its fallback afterward; preserves the 15-second fallback when first paint never arrives; preserves destroyed-window guard reads before and at the fallback deadline; keeps the exact %s error and releases its completed fallback; keeps the exact fallback %s error without retrying initialization; preserves pending manual setup after failed ready registration; keeps setup options, live store reads, nudge writes and required quit flush. src/main/worker-threads/worker-thread-request-queue.test.ts: posts one request at a time and in the order it was dispatched; fires a posted call at its own deadline; stops respawning and fails the rest of the queue once deaths hit the cap; clears the death count when a fresh burst starts from full idle. src/main/workspace-hooks/hooks-setup-runner-script.test.ts: builds Windows runners for newline-heavy scripts without line-array splitting; builds POSIX runners without regex-wide CRLF normalization; writes POSIX setup runners for shebang-declared scripts on native Windows paths; keeps batch setup scripts on cmd.exe when the terminal is Git Bash; hands a Git Bash pane a launch command MSYS cannot rewrite for a cmd runner; replays interpreter flags declared on the shebang line; preserves cmd.exe setup runner semantics for configured cmd users; keeps POSIX runner behavior on POSIX platforms; waits when either local or project policy requires completed setup; marks setup-runner terminals for the always-on credential guard; maps git-bash to POSIX setup launch metadata on Windows; falls back to the cmd runner when the git-bash setting has no installed Git Bash; keeps the cmd runner for a non-Git bash such as Cygwin; keeps the cmd runner for a bare bash whose flavor cannot be resolved; uses the POSIX runner for a bare bash that resolves to Git Bash; uses the POSIX runner for an extension-less Git Bash path; preserves the existing cmd runner for PowerShell terminals; preserves cmd setup compatibility when a Windows-host project has a WSL shell setting; classifies an installed explicit Git Bash executable as a POSIX runner; falls back to the cmd runner when the explicit Git Bash path no longer exists. src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts: schedules remote identity enrichment without blocking the caller; probes a drive project whose runtime is WSL %s; sweeps a local repo: %s; probes an SSH row that carries only executionHostId on its own host; keeps same-path rows on two different SSH hosts from sharing one backoff; coalesces concurrent probes for the same repo location; caches no-identity probes briefly so list calls do not retry every time; does not rewrite the no-remote marker on a later retry; resolves a settled no-remote repo once it gains a remote; does not re-probe a resolved identity before the refresh window elapses; re-probes a resolved identity after the refresh window elapses; bounds re-probes per sweep so a large repo list drains gradually; forgets a removed repo location so its deadline cannot outlive the repo; keeps a surviving repo backoff when a sibling repo is removed; probes again when the same location is re-added after its probe was retired; coalesces concurrent sweeps instead of running one pass per list call. src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts: preserves create priority through claim probes on %s; starts the checkout only once the async workspace root resolves; still deduplicates when both callers await the same pending root lookup; namespaces native Windows preparation directories for long paths; deduplicates preparation for the same repo, base, runtime, and workspace root; does not spend a divergence walk when the base matches exactly; claims when the two sides spell the same ref differently; evicts a repo's own stale preparation before another repo's; still discards armed checkouts when the project runtime needs repair; routes preparation and finalization through the selected WSL runtime; retries stale cleanup after a transient listing failure; does not discard a detached worktree with caller-controlled preparation metadata; does not re-arm after an isolated create; re-arms a preparation once creates arrive in a burst; holds the re-arm checkout until the create runs the deferred thunk; starts one explicit prefetch after the create completes; does not re-arm when finalization failed; reports a pending create while a stale-cleanup scan is running. src/main/workspaces/removal/local-worktree-removal-recovery.test.ts: recovers Git for Windows partial filesystem deletion failures; finishes a clean non-force deletion after Git leaves a Windows directory behind; recovers localized Windows failures after Git already removed the registration; does not recover unrelated localized failures while Git still owns the row; finishes a macOS deletion Git deregistered before failing with Directory not empty; leaves an orphaned checkout to the orphan cleanup instead of deleting it; prunes and strictly verifies on the selected WSL host without deleting files or branches. src/main/workspaces/removal/worktree-removal-safety.test.ts: rejects deleting a worktree that contains another registered worktree; rejects POSIX home directories even when host homedir has a different path shape; refuses a home the host reported even when no path rule recognises it; refuses the Windows host's home directory from a POSIX client; refuses the Windows host's home directory even when the host reported nothing. src/main/wsl/discovery/distro-catalog.test.ts: retries asynchronous discovery after a transient wsl.exe failure; retries synchronous discovery after a transient wsl.exe failure; retries asynchronous discovery after wsl.exe reports no distros yet; retries synchronous discovery after wsl.exe reports no distros yet; bounds the wsl.exe spawn rate while no distros are installed; bounds the asynchronous spawn rate while no distros are installed; still caches a non-empty distro list for the process lifetime; re-probes a docker-desktop-only machine once a user distro can appear; backs off while the list keeps coming back empty; backs off after repeated distro-list failures; caps the empty-list backoff at five minutes; keeps reporting an empty result after it goes stale; keeps reporting a known distro list indefinitely; bounds cached homes while retaining the most recently used distros; still lists distros, and an excluded distro home probe fails like any other probe; gives the async home probe time for a cold boot instead of killing it at 5 s; retries availability after a probe timeout instead of latching false; bounds the probe rate while the failure window is open; caches a successful probe for the process lifetime; names an explicit spawn directory, so no deleted cwd can read as ENOENT; shares one wsl.exe spawn between concurrent probes; keeps reporting the last observed answer after it goes stale; holds a definitive failure far longer than a timeout when %s; backs off after repeated probe failures; re-probes a seeded retryable failure once its window lapses; re-probes availability once a distro list succeeds after %s; does not drop an availability failure for an empty distro list; keeps reporting unavailable off Windows without probing. src/main/wsl/discovery/wsl-distro-holder.test.ts: runs a busybox-safe loop through --exec and names the distro; spawns a detached-style holder, records it, and waits for the distro to run; a holder exiting with code 1 notes its distro may have stopped (E9); rejects a pid whose command line is not our holder for that distro; cleans up stale and corrupt records; keeps a holder and its record when release cannot verify it; reports unverifiable when the command line is unreadable even with a matching pid; release kills a verified holder and removes its record; release never kills a pid that is no longer our holder; reports a spawned holder exit so liveness can re-check. src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts: skips 9p shares that are not drvfs, and malformed lines. src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts: plans the update on the census the running orcad reports, not an unknown one; forwards force to the update planner; does not serve the incumbent past a refusal that is not a wait; does not re-activate the build this host rolled back from; labels the launch with the build the adoption found serving, not the stale record; defers while another run holds the host fence; lets an explicit force deploy past both skips; names a newer host refusal apart from a rolled-back one, so only Force is offered; updates an older host as before, without asking to adopt it; never asks the incumbent when it already runs this build. src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts: keeps a completed listing usable when the host rejects the wait parameter. src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts: delivers to chat-default users in all targeting while holding out not-switched users. src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts: completes the row on a pick, even when the command is already typed; ignores a pick of the row while side chats are unavailable. src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts: explains a too-large refusal that arrives through the IPC error prefix. src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts: keeps the question with the caller and says once that it never went; tells the user to check the side chat when delivery is unconfirmed; reports a delivered question as sent, silently. src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts: decides each of %i tool-only turns once per layout, and nothing without a listener. src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx: places a side chat whose question was %s: %o. src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts: calls back once for %s; stops watching once unsubscribed. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts: routes terminal input through deferPtyInput so the host can withhold it; forwards terminal input directly when the host supplies no deferPtyInput. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts: requests a tab remount for an unbound spawn; leaves recovery to a remote transport that armed its own retry; requests a remount when the transport reports no recovery of its own; settles the spawn as failed before requesting a remount; prefers the restored leaf id when reporting the anomaly; falls back to the pane leaf id when no restored leaf exists. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionDeferredInputForwardingTests } from '../input/pty-connection-deferred-input-forwarding.spec', registerPtyConnectionDeferredInputForwardingTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts: registers interest on the first sidecar and releases on the last unsubscribe; releases sidecar interest only once for repeated unsubscribes; does not let an eager pre-mount buffer defeat hidden delivery gating; keeps eager buffers outside delivery interest when the PTY exits before mount; lets a sidecar exclusively own interest while an eager buffer overlaps. src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts: blackholed delivery reproduces the wedge: no handler dispatch, no ACK ever. src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts: sends preferences to the execution host and attaches only to its returned PTY; preserves one operation ID across a lost reply and reconnect; preserves ordinary raw startup and captured-session attachment. src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts: sums registered gauges and drops disposed ones; ignores a repeated dispose instead of dropping another gauge; stops tracking new gauges past the cap so a missed dispose cannot grow it; tracks a live output processor queue through enqueue, drain, and dispose; excludes cleared consumed entries from retention after a bounded drain. src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts: says nothing once the pane is closed. src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts: refreshes after each scheduled atlas reset; falls back to a timeout when animation frames are unavailable; continues recovery when a manager throws after scheduling. src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts: tracks a remounted quiet title source even when the stale owner unregisters later; preserves the renderer-parsed output sequence in the response; preserves a pending escape tail for snapshot replay; routes a host's Reset Terminal request to the pane that owns the PTY. src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts: marks panes with restored scrollback for fresh-shell viewport blanking. src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts: recovers a 0x0 spawn whose container is briefly unmeasurable then settles. src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts: removes global listeners when the last pane unregisters. src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx: keeps trust text readable on a host-owned dialog surface; applies the hostile surface to ordinary dialogs, so the case above is exercised. src/renderer/src/components/use-terminal-parking-pass.test.tsx: does not queue a render when a pass produces the same parking sets; keeps parking transitions working under StrictMode. src/renderer/src/hooks/client-workspace-view-report.test.ts: reports an away user’s screen with no presence, and renews as soon as input returns; retries a failed send, empty or not, no sooner than a refresh. src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts: is new work in a workspace with no live terminal: its first bind moves it up in Recent. src/renderer/src/hooks/use-bundled-skill-install.test.tsx: ignores a repeated click while the install runs; retries the last requested skills on this host. src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx: adds seeds to a successful empty list but not to loading or failed results; retains seed projection after expiry and fetches fresh metadata for a new reader. src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx: retranslates the settings nav labels when the UI language changes live. src/renderer/src/lib/codex-stale-pane-account-identity.test.ts: keeps the prompt when the roster read fails and every label collapses. src/renderer/src/lib/image-blob-png.test.ts: downscales a pasted image above the pixel cap; releases its temporary URL on a decode error; releases its temporary URL when PNG encoding fails or exceeds the byte cap. src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts: names callers above the frame the write came from; restores Error.stackTraceLimit when the capture throws; stops collecting after the sample cap when captureStackTrace is unavailable; caps reported changed keys from a single wide write. src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts: applies the rendered text hard cap last and reserves the final overflow marker. src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts: keeps the runtime target identity stable across unrelated store writes. src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts: keeps creation available on old hosts and explains the missing operation; preserves landed warnings and direct collision recovery data; propagates remote discovery failure instead of a false empty page. src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts: reuses unchanged worktree tab projections when one worktree title changes; bumps only the changed worktree version when a sibling stays byte-identical. src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts: shares safe-auto fork sync cooldown attempts across store instances. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts: collapses a 193-workspace hydration to one store write; leaves the store byte-identical to the per-workspace path; re-reconciling the batched result is a no-op, as it is for the per-workspace path. src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts: dedicated zero-case helper retirement; no authored test credit. src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts: persists each batch metadata update to its workspace owner. src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts: dismisses a rename error on its capable remote owner; clears pending first-agent rename when the title is updated. src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts: orders capture, guards, handlers, main's stop, commit, cleanup, and exit settlement. src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts: publishes the first terminal and root tab group atomically; publishes the first terminal and root tab group atomically, then marks it starting in main. src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts: restores daemon terminal wake hints before declaring the session ready. src/renderer/src/web/web-runtime-connection-auth-framing.test.ts: keeps legacy framing for sockets that cannot absorb a refused attempt. src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts: moves the old Windows default to Regular once and queues the notice; keeps custom weights and fresh profiles without a notice; leaves macOS and Linux profiles untouched. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/persistence/worktree-sort-order-write.test.ts, src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, src/main/runtime/integrations/skill/orca-runtime-skill-recovery.test.ts, src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-detached-routing.spec.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts, src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-pointer-cli-command.spec.ts, src/main/runtime/rpc/methods/terminal/terminal-multiplex-link-estimate.test.ts, src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts, src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.test.ts, src/main/runtime/rpc/server/pairing/pairing-offer-owner-cli.test.ts, src/main/runtime/rpc/terminal-multiplex-end-verdict.test.ts, src/main/runtime/session-graph/headless-runtime-graph.spec.ts, src/main/runtime/session-graph/runtime-graph-standing-contracts.test.ts, src/main/runtime/session-tabs/structured-conversation-tab-title.test.ts, src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts, src/main/runtime/terminal/identity/terminal-identity-probe.test.ts, src/main/runtime/terminal/layout/paired-desktop-server-writes-layout-owner.test.ts, src/main/runtime/terminal/lifecycle/pty-lifecycle-generation-retention.test.ts, src/main/runtime/terminal/lifecycle/run-terminal-user-open.test.ts, src/main/runtime/terminal/surface/terminal-surface-replies-window.test.ts, src/main/runtime/terminal/surface/workspace-layout-projection.test.ts, src/main/runtime/terminal/view/terminal-subscribe-exit-waiter-leak.test.ts, src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts, src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.test.ts, src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts, src/main/skills/skill-install-transaction.test.ts, src/main/speech/model-manager-download-resume.test.ts, src/main/ssh/config/ssh-config-parser.test.ts, src/main/ssh/config/ssh-known-hosts-source.test.ts, src/main/ssh/config/ssh-known-hosts.test.ts, src/main/ssh/connection/ssh-connect-config.test.ts, src/main/ssh/connection/ssh-connection-auth-fallback.test.ts, src/main/ssh/connection/ssh-connection-store.test.ts, src/main/ssh/connection/ssh-connection.test.ts, src/main/ssh/orcad-migration-stuck-host-profiles.test.ts, src/main/ssh/orcad-runtime-maintenance.test.ts, src/main/ssh/port-forwarding/ssh-port-forward.test.ts, src/main/ssh/ssh-channel-multiplexer.test.ts, src/main/ssh/system-transport/system-ssh-forward-process.test.ts, src/main/ssh/system-transport/system-ssh-loopback-route.test.ts, src/main/startup/browser-process-user-agent-ordering.test.ts, src/main/startup/quit/quit-path-durable-write-blocking.test.ts, src/main/stats/agent-session-transition-recorder.test.ts, src/main/text-generation/commit-message-text-generation-model-discovery.test.ts, src/main/text-generation/pull-request-context.test.ts, src/main/text-generation/source-control-local-process.test.ts, src/main/updater/linux-package/linux-package-update-recovery.test.ts, src/main/updater/releases/updater-prerelease-feed-readiness.test.ts, src/main/updater/releases/updater-release-builds.test.ts, src/main/updater/updater.build-channel-selection.test.ts, src/main/updater/updater.check-preflight.test.ts, src/main/updater/updater.prerelease-fallback.test.ts, src/main/updater/updater.publishing-window-feed.test.ts, src/main/updater/updater.quit-and-install.test.ts, src/main/window/createMainWindow-markdown-editor-focus.test.ts, src/main/window/createMainWindow-renderer-crash-recovery.test.ts, src/main/window/dashboard-popout-window.test.ts, src/main/window/dropped-path-preparation.test.ts, src/main/window/main-window-updater-deferred-setup.test.ts, src/main/worker-threads/worker-thread-request-queue.test.ts, src/main/workspace-hooks/hooks-setup-runner-script.test.ts, src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts, src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts, src/main/workspaces/removal/local-worktree-removal-recovery.test.ts, src/main/workspaces/removal/worktree-removal-safety.test.ts, src/main/wsl/discovery/distro-catalog.test.ts, src/main/wsl/discovery/wsl-distro-holder.test.ts, src/main/wsl/filesystem/wsl-guest-drive-mountinfo.test.ts, src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts, src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts, src/renderer/src/components/feature-tips/feature-tip-telemetry.test.ts, src/renderer/src/components/native-chat/composer/pickers/use-native-chat-side-chat-command.test.ts, src/renderer/src/components/native-chat/media/images/native-chat-image-copy.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.test.ts, src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts, src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.test.tsx, src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-interest.test.ts, src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts, src/renderer/src/components/terminal-pane/pty-transport/ipc/ipc-pty-opencode-model.test.ts, src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts, src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts, src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts, src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts, src/renderer/src/components/terminal-pane/snapshots/saved-terminal-output-replay.test.ts, src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts, src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx, src/renderer/src/components/use-terminal-parking-pass.test.tsx, src/renderer/src/hooks/client-workspace-view-report.test.ts, src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge-placement.test.ts, src/renderer/src/hooks/use-bundled-skill-install.test.tsx, src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx, src/renderer/src/hooks/useSettingsNavigationMetadata.language-switch.test.tsx, src/renderer/src/lib/codex-stale-pane-account-identity.test.ts, src/renderer/src/lib/image-blob-png.test.ts, src/renderer/src/lib/react-commit-cascade-store-write-samples.test.ts, src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts, src/renderer/src/runtime/rpc/targets/use-worktree-runtime-target.test.ts, src/renderer/src/runtime/source-control/git/runtime-git-branch-client.test.ts, src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-key-reuse.test.ts, src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts, src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-fixture.ts, src/renderer/src/store/slices/worktrees/metadata/update-worktrees-meta.test.ts, src/renderer/src/store/slices/worktrees/metadata/worktree-meta-rename.test.ts, src/renderer/src/store/terminals/store-sleep-shutdown-order.test.ts, src/renderer/src/store/terminals/terminal-first-tab-publication.test.ts, src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts, src/renderer/src/web/web-runtime-connection-auth-framing.test.ts, src/shared/terminal/appearance/terminal-font-weight-windows-regular.test.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing-races.spec.ts: stops paged routing when the check is cancelled; keeps an unfiltered redrive unrestricted when reservations merge; keeps an unfiltered parked delivery unrestricted when reservations merge; uses a bounded indexed pane lookup for reminted Dispatch identity. src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts: removes the reported wedged automation workspace without --force; clears PTY state once a failed stop is proven to have exited; names only the PTYs that are actually live, not every failed stop; warns with the specific sweep failure, not the generic deadline; still fails closed on a sweep-level failure without force. src/main/skills/bundled-skill-install/layouts.test.ts: links into a project only where its agent folder already exists; reads a pending cloud transaction as busy and a cloud receipt as another skill. src/main/skills/skill-upload-session-service.test.ts: joins concurrent disposal callers through exact cleanup completion. src/main/source-control/hosted-review-creation.test.ts: creates the pull request after fresh main-process validation passes; routes local WSL git and GitHub review creation through the selected runtime; creates a pull request on a GitHub Enterprise Server remote (#8312); creates a GitLab merge request after fresh main-process validation passes; creates an Azure DevOps pull request after fresh main-process validation passes; creates a Gitea pull request after fresh main-process validation passes. src/main/source-control/hosted-review-execution-host-routing.test.ts: reads a GitHub review on the SSH host a row names only in executionHostId; reads a GitLab review on the executionHostId host when connectionId names a different one; does not dial this client for a runtime row whose nested target shares a local name; keeps a runtime row with no nested target on this process (self-addressed stamp); keeps a legacy connectionId-only SSH row on its target; does not share a cached answer between two rows at one path on different hosts; creates a Bitbucket review locally for a runtime row rather than dialing its nested target; reports creation eligibility from the executionHostId-only SSH host; resolves the GitHub slug for a repo listing on the row it is asked about; refuses to dial a runtime host from this process; answers with the SSH target for both spellings and local otherwise; reads a runtime stamp on a row in this store as self-addressing, not a second machine. src/main/source-control/hosted-review-inflight-invalidation.test.ts: keeps other hosts, paths and their pending promises isolated. src/main/speech/model-manager.test.ts: requires pinned, internally consistent metadata for every model file; verifies downloaded model file hashes before installation; rejects non-HTTPS model downloads; marks OpenAI transcription models ready only when an API key is configured. src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts: writes to the SFTP namespace path discovered on the same session; uploads the bundle into the SFTP namespace directory; issues no discovery requests when the caller supplies no mapping; ignores a mapping on a Windows host; never resolves on the system-SSH transport; leaves writeBuffer and openFileUploadSession on the shell path; keeps the shell path when discovery is inconclusive; preserves a session-limit channel-open error unchanged. src/main/ssh/connection/ssh-connection-system-transport.test.ts: uses system SSH transport when ProxyUseFdpass is resolved by OpenSSH; allows concurrent exec commands for system SSH with an Orca ControlMaster socket; keeps concurrent exec commands disabled for system SSH without a reusable socket; uses system SSH transport for ProxyCommand targets before ssh2 auth; keeps the original ssh2 reachability error when the system SSH probe fails; reports the system SSH failure when ssh2 cannot negotiate with the host; uses system transport for target or resolved OpenSSH proxy directives; allows an environment override for e2e coverage; ignores stale imported proxy fields when fresh OpenSSH config has no proxy. src/main/ssh/orcad-migration-catalog-client.test.ts: keeps each server project’s execution host, so a nested SSH row is never read as local; reads the server’s folder workspaces and the groups that place them on a host; sends and validates the %s operation; validates an abort result without letting it erase committed state; validates a committed receipt against the requested manifest; rejects malformed stage timestamps and abort envelopes; fails closed for method absence, malformed identity, and invalid pairing; refuses a destination without the capability before sending any migration request; reads method-not-found as the same refusal, not as a lost answer. src/main/ssh/runtime-ssh-access.test.ts: persists intent then claim before connecting and publishes redacted authenticated access; names the saved dependency when dependent state blocks an SSH access link; handles lost link responses without connecting or verifying again; invalidates old transport only after authenticated access is published; rejects changed request tuple after a completed link; rejects provisioning and missing durable generations without connecting; treats a lost successful unlink response as an idempotent no-op; hashes connection identity, not display state or owner; strictly validates ports and request IDs. src/main/startup/cli-launch-redirect.test.ts: detects a launch that received the unpacked CLI entrypoint; ignores normal desktop launches; ignores the entrypoint when it is only the executable itself (argv[0]); applies on Linux too; strips injected Chromium switches before node-mode CLI arguments; keeps user flags after the command and malformed boolean assignments; does not treat a later positional entrypoint path as the launcher; redirects a direct binary launch with no AppImage env at all; strips Chromium switches node mode would reject; preserves desktop-shaped switches after the command; leaves direct serve in-process but redirects its help; treats help as a CLI launch even without a command; treats %s as a CLI launch even without a command; does not treat a value of %s as a CLI early-exit flag; does not treat a serve option value as a help request; does not reinterpret help after the argument terminator; leaves a plain desktop launch alone; skips flag values when looking for the command positional; preserves a project selector in %j; does not apply the command form on macOS or Windows; never redirects an unpackaged build; runs the in-package CLI in Electron node mode with sanitized env; refuses to redirect twice so a dropped ELECTRON_RUN_AS_NODE cannot loop; reports a missing CLI entrypoint instead of booting the desktop app; execs a direct serve into the CLI so it keeps its pid and honours profile and supervise; keeps ORCA_USER_DATA_PATH for a direct serve without --user-data-dir; serves in-process when this runtime cannot exec or the exec fails; never execs the --serve child the CLI itself spawns, or serve on other platforms; surfaces a spawn failure as a non-zero exit; re-execs a direct --serve onto X11 when Electron resolved Wayland; leaves $name alone. src/main/startup/main-process-runtime-launch-activation.test.ts: marks startup settled for the launch record only after the window has loaded and settled; loads SSH targets on a windowless serve before paired clients can connect (#25886); pins the serve listener to loopback only for orcad browser sidecars (sidecar=$sidecar, #31895); saves Codex auth before a headless serve update restart, like the desktop does. src/main/startup/run-electron-vite-dev.test.ts: forwards dev instance identity to electron-vite; prepares userData orca and orca-dev wrappers for dev terminals; consumes the stable-name flag before forwarding args to electron-vite. src/main/updater/releases/updater-prerelease-feed.test.ts: returns the newest stable tag when the user is on an RC and a newer stable exists; returns the newest RC tag when no stable is newer than the current RC; can exclude prerelease tags for stable-channel checks; probes the %s %s platform manifest; returns null for stable-channel checks when only prereleases are newer; returns null when nothing in the feed is newer than the current version; ignores entries with unparseable tags; returns null when the fetch is not ok; returns null when the fetch throws; picks semver-newest across a mixed-order feed; ignores perf-tagged prereleases for regular RC checks; reports no RC update when only perf-tagged prereleases are newer; picks the semver-newest perf-tagged prerelease; matches only literal rc.N.perf prerelease tags for perf checks; reports no perf update instead of falling back to stable or RC tags; returns a bounded fallback candidate after the newest newer tag; returns null when the only newer tag has a manifest but its asset still 404s; requires a known old timestamp for a stable-fallback tag. src/main/updater/updater-events.test.ts: hands the whole downloaded event to artifact capture; publishes manual-install recovery after a %s download; publishes the normal downloaded state for AppImage builds; blocks downloaded-state handling when the packaged marker is unusable; passes the actual updater error into the install-failure handler; keeps manual-install recovery when a later check finds only the installed release; drops the artifact when another version takes over the cycle; ignores a downloaded event for an older target; accepts a matching event when the pending cache target was cleared; drops the artifact when progress reports a different pending version. src/main/updater/updater-linux-package-recovery-actions.test.ts: rejects both actions while no package-install recovery is active; validates the retained package on every invocation; restores recovery after a recheck resolves without a terminal event; restores recovery after a recheck fails; restores recovery when a pinned check resolves to the current version; restores recovery when resolving a pinned check fails; clears recovery for both actions once the package is gone; resolves %s as a result and keeps the card usable instead of rejecting; keeps recovery available after a transient read failure. src/main/updater/updater.check-settlement.test.ts: leaves a dismissed release update on the release source; surfaces net::ERR_FAILED to user-initiated checks with a friendly message; shows checking immediately for a user-initiated check while feed pinning is pending; keeps background checks event-driven before checking-for-update fires. src/main/usage/usage-provider-store-lifecycle.test.ts: persists identities for a whole first scan with one write; skips disabled and fresh matching states; invalidates prior sources on fingerprint changes and reuses them for forced scans. src/main/window/createMainWindow-close-confirmation.test.ts: clears the quit latch when the renderer prevents unload; does not notify the crash recorder when renderer teardown follows a confirmed window close; allows close when Electron reports a crashed webContents; requests confirmation for a hung-but-alive renderer instead of bypassing. src/main/workspaces/catalog/worktree-identity-persistence.test.ts: stores independent metadata for colliding locators on two hosts; projects canonical-only metadata for exactly one host; keeps canonical metadata current for legacy writers on a known owner; removes only the selected legacy-owner metadata when locators collide; keeps the canonical identity stable when the locator changes; leaves other hosts at the old locator when one host renames its folder. src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.test.ts: leaves a journaled conversion untouched with the gate closed, %s. src/main/wsl/orcad/wsl-orcad-deploy.test.ts: holds the distro before it deploys and launches, and reports what C5 dials; passes its connect-state read (%s) on as hints; applies the SSH census and downgrade admission to the first deploy; refuses a WSL 1 distro before holding it or touching its files; tells an unregistered distro how to find the installed ones, before holding anything; surfaces an unsupported libc as the SSH host refusal does; starts an already-active slot the distro stop ended, instead of reporting it ready; deploys over an adopted unrecorded orcad under the SSH terminal gate, never a fresh launch; reports the adopted instance once the same version is serving; returns a deferral rather than launching over live terminals; hands a failed first deploy to the fresh-install cleanup before reporting it. src/main/zcode/zcode-v2-plan-credentials.test.ts: prefers migrated credentials over a stale legacy account; keeps legacy support when no personal v2 file exists; honors the upstream personal config override independently of the credential directory; does not borrow credentials from another execution host; preserves the protected Orca key priority even if v2 is corrupt; rejects upstream-invalid selection %j without legacy fallback; accepts a valid optional reasoning level; rejects upstream-invalid rule containers %j without legacy fallback; accepts a valid selected-provider empty personal rule and smart model rule; cannot establish selected credentials from %s rules; leaves encrypted CLI files unchanged across repeated account reads. tests/e2e/automation-terminal-launch.unit.test.ts: launches explicit Chat for %s through the common entry and keeps its actual fallback; does not apply stored Terminal extras to Chat; forwards only complete Chat-consumed values, with no Terminal startup base; refuses an expired admission without minting another launch identity; records the actual chat identity and delegates new workspace setup and provenance. tests/e2e/github-project-provider-columns.unit.test.ts: renders %s through one bounded items request on a named cloud host; preserves zero and complete counters: %j; preserves populated and legacy rows through shared sorting, grouping and cells. tests/e2e/structured-agent-session-launch-continuation.unit.test.ts: carries renderer lifetime through host intent to the real %s provider builders. tests/e2e/terminal-account-restart.unit.test.ts: replaces a tombstoned owner while its persisted pane binding has not yet been cleared; paired restart retains the old owner (host authority: %s). tests/e2e/terminal-hidden-view-parking.spec.ts: does not park excluded tabs; reproduces a static frame byte-for-byte across 25 park/reveal cycles. tests/e2e/terminal-long-table-scroll-restore.spec.ts: reproduces long markdown table artifacts after workspace switch and scroll; keeps narrow wrapped signer markdown table coherent after restore and scroll; keeps real emoji markdown table right edge clean after restore and scroll. tests/e2e/terminal-long-table-fixtures.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-paste-ownership.spec.ts: Windows multiline keyboard paste normalizes terminal newlines with one PTY owner; right-click paste sends clipboard text to the focused terminal exactly once. tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts: uses WebGL by default for ordinary terminal output when available @terminal-rendering-golden. tests/e2e/terminal-windows-shell-paste-ownership.spec.ts: cmd.exe default terminal keyboard paste preserves exact content with one PTY owner; Git Bash default terminal keyboard paste preserves POSIX-shaped content with one PTY owner; WSL terminal keyboard paste preserves Linux shell content with one PTY owner. tests/e2e/workspace-board-lane-virtualization.spec.ts: mounts a window of cards for a large lane and keeps lane indexes; renders later lane indexes after the lane scrolls. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts, src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing-races.spec.ts, src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts, src/main/skills/bundled-skill-install/layouts.test.ts, src/main/skills/skill-upload-session-service.test.ts, src/main/source-control/hosted-review-creation.test.ts, src/main/source-control/hosted-review-execution-host-routing.test.ts, src/main/source-control/hosted-review-inflight-invalidation.test.ts, src/main/speech/model-manager.test.ts, src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts, src/main/ssh/connection/ssh-connection-system-transport.test.ts, src/main/ssh/orcad-migration-catalog-client.test.ts, src/main/ssh/runtime-ssh-access.test.ts, src/main/startup/cli-launch-redirect.test.ts, src/main/startup/main-process-runtime-launch-activation.test.ts, src/main/startup/run-electron-vite-dev.test.ts, src/main/updater/releases/updater-prerelease-feed.test.ts, src/main/updater/updater-events.test.ts, src/main/updater/updater-linux-package-recovery-actions.test.ts, src/main/updater/updater.check-settlement.test.ts, src/main/usage/usage-provider-store-lifecycle.test.ts, src/main/window/createMainWindow-close-confirmation.test.ts, src/main/workspaces/catalog/worktree-identity-persistence.test.ts, src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.test.ts, src/main/wsl/orcad/wsl-orcad-deploy.test.ts, src/main/zcode/zcode-v2-plan-credentials.test.ts, tests/e2e/automation-terminal-launch.unit.test.ts, tests/e2e/github-project-provider-columns.unit.test.ts, tests/e2e/structured-agent-session-launch-continuation.unit.test.ts, tests/e2e/terminal-account-restart.unit.test.ts, tests/e2e/terminal-hidden-view-parking.spec.ts, tests/e2e/terminal-long-table-scroll-restore.spec.ts, tests/e2e/terminal-long-table-fixtures.ts, tests/e2e/terminal-paste-ownership.spec.ts, tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts, tests/e2e/terminal-windows-shell-paste-ownership.spec.ts, tests/e2e/workspace-board-lane-virtualization.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -14125,7 +14230,15 @@ "Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", "Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. All prior notes and dated/archived evidence retain original scopes.", "Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes." + "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", + "Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed.", + "Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope.", + "Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection.", + "Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope.", + "Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope.", + "Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope.", + "Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed.", + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, @@ -14256,10 +14369,10 @@ "providers": ["relay"], "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof. Historical scope before this audit: Actual assignment store and SQLite tests on macOS. No real PostgreSQL or live remote host/physical phone run. Local/daemon PTY, SSH execution ownership, WSL, folder/git workspace behavior and transport framing are unaffected. Audit1279 removes fake SQL lock-order receipts, diagnostic projections and mocked reserve callback cases from this selector. Their precise local alarms are intentionally lost; retained SQLite headroom/state checks are not claimed as equivalent replacements. The 2026-09-25 receipt is archived as historical data; the shortened selector has no fresh runtime result yet. The remaining six-file selector passed 164 cases on Linux after these removals; this fixture result is separate from the archived dated receipt and does not establish native PostgreSQL behavior. Audit1507 removes the mocked lock-counter suite from the active selector; the 2026-11-04 six-file receipt remains historical and does not validate the shortened five-file selector. Its direct mocked counter alarm is intentionally retired without replacement equivalence.", + "coverageNotes": "Audit3700 removes two authored/two finite conditional PostgreSQL cases from two partial assignment suites: the 50k released-history named-index EXPLAIN assertion and the no-lease ledger-only default-floor move example. No equivalent replacement or fresh execution is claimed. Both drivers remain admitted by the cloud package runner when ORCA_RELAY_TEST_POSTGRES_URL is supplied. This gate remains without active selectors/evidence; prior receipt strings remain historical. Audit3700 intentionally retires the exact composite-index/access-path alarm (named index, cell_id/state ANY Index Cond and no Filter) and the seeded ledger-only/default-floor dead-reserve move returned-cell/epoch8 alarm. The former did not measure latency; the latter supplied death verdict/clock rather than causing a crash or dead-man trip. Remaining PostgreSQL concurrency, debt release, lease-bearing move and epoch-floor/ledger-fence cases guard different outcomes and are not equivalent replacements. No current PostgreSQL pass, native platform, remote or mobile proof was obtained. Removing the EXPLAIN registration also removes its 50k shared-fixture released rows and ANALYZE before later separate-identity heartbeat cases. Removing the ledger example skips one hostSerial increment; raw survivor callbacks do not imply identical runtime fixture state. Previous account (preserved verbatim): Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof. Historical scope before this audit: Actual assignment store and SQLite tests on macOS. No real PostgreSQL or live remote host/physical phone run. Local/daemon PTY, SSH execution ownership, WSL, folder/git workspace behavior and transport framing are unaffected. Audit1279 removes fake SQL lock-order receipts, diagnostic projections and mocked reserve callback cases from this selector. Their precise local alarms are intentionally lost; retained SQLite headroom/state checks are not claimed as equivalent replacements. The 2026-09-25 receipt is archived as historical data; the shortened selector has no fresh runtime result yet. The remaining six-file selector passed 164 cases on Linux after these removals; this fixture result is separate from the archived dated receipt and does not establish native PostgreSQL behavior. Audit1507 removes the mocked lock-counter suite from the active selector; the 2026-11-04 six-file receipt remains historical and does not validate the shortened five-file selector. Its direct mocked counter alarm is intentionally retired without replacement equivalence.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/23035"], "invariant": "A single-cell capacity check reads only that cell while retaining snapshot freshness, incarnation, outstanding reservation and missing-limit policy; new placement retains the full fleet inventory.", - "oracle": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. With 32 capped cells, an existing active host stays on its pinned cell and reads one headroom row; new placement reads all 32. Missing, expired or prior-incarnation snapshots, capacity exhaustion and outstanding debt still refuse the active pinned host; an uncapped cell remains admissible.", + "oracle": "Audit3700 removes two authored/two finite conditional PostgreSQL cases from two partial assignment suites: the 50k released-history named-index EXPLAIN assertion and the no-lease ledger-only default-floor move example. No equivalent replacement or fresh execution is claimed. Both drivers remain admitted by the cloud package runner when ORCA_RELAY_TEST_POSTGRES_URL is supplied. This gate remains without active selectors/evidence; prior receipt strings remain historical. Audit3700 intentionally retires the exact composite-index/access-path alarm (named index, cell_id/state ANY Index Cond and no Filter) and the seeded ledger-only/default-floor dead-reserve move returned-cell/epoch8 alarm. The former did not measure latency; the latter supplied death verdict/clock rather than causing a crash or dead-man trip. Remaining PostgreSQL concurrency, debt release, lease-bearing move and epoch-floor/ledger-fence cases guard different outcomes and are not equivalent replacements. No current PostgreSQL pass, native platform, remote or mobile proof was obtained. Removing the EXPLAIN registration also removes its 50k shared-fixture released rows and ANALYZE before later separate-identity heartbeat cases. Removing the ledger example skips one hostSerial increment; raw survivor callbacks do not imply identical runtime fixture state. Previous oracle (preserved verbatim): Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. With 32 capped cells, an existing active host stays on its pinned cell and reads one headroom row; new placement reads all 32. Missing, expired or prior-incarnation snapshots, capacity exhaustion and outstanding debt still refuse the active pinned host; an uncapped cell remains admissible.", "commands": [], "testFiles": [], "assertionRefs": [], @@ -14281,6 +14394,7 @@ "evidence": "Actual sticky path result rows 32 to 1; no new timer, polling, queue, cache or provider call. Supplemental SQLite query benchmark with 32 cells and 400 active reservations each measured median per-query 0.285ms to 0.022ms; not a production PostgreSQL latency claim." }, "knownGaps": [ + "Audit3700 removes two authored/two finite conditional PostgreSQL cases from two partial assignment suites: the 50k released-history named-index EXPLAIN assertion and the no-lease ledger-only default-floor move example. No equivalent replacement or fresh execution is claimed. Both drivers remain admitted by the cloud package runner when ORCA_RELAY_TEST_POSTGRES_URL is supplied. This gate remains without active selectors/evidence; prior receipt strings remain historical. Audit3700 intentionally retires the exact composite-index/access-path alarm (named index, cell_id/state ANY Index Cond and no Filter) and the seeded ledger-only/default-floor dead-reserve move returned-cell/epoch8 alarm. The former did not measure latency; the latter supplied death verdict/clock rather than causing a crash or dead-man trip. Remaining PostgreSQL concurrency, debt release, lease-bearing move and epoch-floor/ledger-fence cases guard different outcomes and are not equivalent replacements. No current PostgreSQL pass, native platform, remote or mobile proof was obtained. Removing the EXPLAIN registration also removes its 50k shared-fixture released rows and ANALYZE before later separate-identity heartbeat cases. Removing the ledger example skips one hostSerial increment; raw survivor callbacks do not imply identical runtime fixture state.", "Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof.", "Real PostgreSQL query plan and concurrent admission not rerun for the scoped variant.", "Windows/Linux execution, live remote host/mobile flows and CI soak are not recorded.", diff --git a/config/repo-host-read-baseline.txt b/config/repo-host-read-baseline.txt index 7fcaeb3c4b7..af28a24cad0 100644 --- a/config/repo-host-read-baseline.txt +++ b/config/repo-host-read-baseline.txt @@ -2,7 +2,7 @@ # This is a RATCHET: counts may only go DOWN. Resolve the host instead (see fix text). # A lower bound: destructured and differently named rows are not counted. # Prune after a fix: pnpm check:repo-host-read-ratchet --prune -1 src/main/github/account-binding-required-host.ts +1 src/main/github/accounts/account-binding-required-host.ts 3 src/main/ipc/ephemeral-vm-recipe-context.ts 2 src/main/ipc/filesystem/filesystem-source-control-ai-targets.ts 1 src/main/ipc/folder-repo-git-upgrade.ts @@ -13,7 +13,6 @@ 1 src/main/ipc/source-control/github-work-item-args.ts 1 src/main/ipc/source-control/gitlab-repo-access.ts 2 src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts -1 src/main/ipc/workspace-cleanup/workspace-cleanup-disconnected-ssh.ts 1 src/main/ipc/worktrees-test-metadata-pruning-store.ts 1 src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts 1 src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts @@ -47,8 +46,8 @@ 1 src/main/workspaces/space-analysis/workspace-space-worktree-row.ts 1 src/shared/endpoint-catalog-adoption.ts 1 src/shared/folder-workspaces/folder-workspace-execution-host.ts -1 src/shared/github/github-cache-key.ts +1 src/shared/github/cache/github-cache-key.ts 1 src/shared/new-workspace-dialog-repo.ts 1 src/shared/sidebar-list/workspace-review-facts.ts 1 src/shared/workspace-session/workspace-session-terminal-buffers.ts -1 src/shared/worktree/ownership.ts +1 src/shared/worktree/visibility/ownership.ts diff --git a/config/scripts/archives/platform-command/zip-extractor-command.test.mjs b/config/scripts/archives/platform-command/zip-extractor-command.test.mjs index df80ea918b0..c555261cab7 100644 --- a/config/scripts/archives/platform-command/zip-extractor-command.test.mjs +++ b/config/scripts/archives/platform-command/zip-extractor-command.test.mjs @@ -1,17 +1,12 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' -import { - getTarProgram, - getZipExtractorCommand -} from '../../../../src/shared/zip-extractor-command.ts' +import { getZipExtractorCommand } from '../../../../src/shared/zip-extractor-command.ts' const directories = [] afterEach(() => { - vi.unstubAllEnvs() - vi.restoreAllMocks() for (const directory of directories.splice(0)) { rmSync(directory, { recursive: true, force: true }) } @@ -30,32 +25,6 @@ function extract(bytes) { } describe('native archive extraction', () => { - it('pins Windows tar to the system tool even when Git Bash or an unzip override is present', () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - vi.stubEnv('SystemRoot', 'C:\\Windows') - vi.stubEnv('ORCA_UNZIP_BIN', 'custom-unzip') - expect(getTarProgram()).toBe(join('C:\\Windows', 'System32', 'tar.exe')) - vi.spyOn(process, 'platform', 'get').mockReturnValue('linux') - expect(getTarProgram()).toBe('tar') - }) - - it('uses the system archive reader on Windows unless an override is configured', () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - vi.stubEnv('SystemRoot', 'C:\\Windows') - vi.stubEnv('ORCA_UNZIP_BIN', '') - expect(getZipExtractorCommand('source.zip', 'output')).toEqual({ - file: join('C:\\Windows', 'System32', 'tar.exe'), - args: ['-xf', 'source.zip', '-C', 'output'], - label: 'tar' - }) - vi.stubEnv('ORCA_UNZIP_BIN', 'C:\\tools\\unzip.exe') - expect(getZipExtractorCommand("source '$.zip", "output '$")).toEqual({ - file: 'C:\\tools\\unzip.exe', - args: ['-q', "source '$.zip", '-d', "output '$"], - label: 'unzip' - }) - }) - it('extracts through paths containing spaces, apostrophes and shell characters', () => { const { result, destination } = extract( Buffer.from( @@ -66,9 +35,4 @@ describe('native archive extraction', () => { expect(result.code, result.stderr).toBe(0) expect(readFileSync(join(destination, 'payload.txt'), 'utf8')).toBe('verified archive payload') }) - - it('fails on a malformed archive', () => { - const { result } = extract('invalid archive') - expect(result.code).not.toBe(0) - }) }) diff --git a/config/scripts/archives/seven-zip/resolve-7za-path.test.mjs b/config/scripts/archives/seven-zip/resolve-7za-path.test.mjs index 4e43241d45a..f2c297de7ca 100644 --- a/config/scripts/archives/seven-zip/resolve-7za-path.test.mjs +++ b/config/scripts/archives/seven-zip/resolve-7za-path.test.mjs @@ -1,5 +1,5 @@ import { spawnSync } from 'node:child_process' -import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync, statSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { describe, expect, it } from 'vitest' @@ -8,51 +8,6 @@ import { resolve7zaPath } from './resolve-7za-path.mjs' const projectRoot = resolve(import.meta.dirname, '../../../..') describe('7za path resolution for the Windows signing gates (#6487)', () => { - // Match upstream mac/win/linux architecture dirs; darwin/ or collapsed-arch guesses silently fail to resolve. - - it('resolves an executable 7za that can extract an archive', async () => { - const path7za = await resolve7zaPath(projectRoot) - expect(existsSync(path7za)).toBe(true) - - const scratch = mkdtempSync(join(tmpdir(), 'orca 7za resolve ')) - try { - const payloadDir = join(scratch, 'payload') - mkdirSync(payloadDir, { recursive: true }) - writeFileSync(join(payloadDir, 'Orca.exe'), 'not-a-real-pe') - - const archive = join(scratch, 'bundle.7z') - const created = spawnSync(path7za, ['a', archive, payloadDir], { encoding: 'utf8' }) - expect(created.status).toBe(0) - - const outDir = join(scratch, 'out') - const extracted = spawnSync(path7za, ['x', archive, `-o${outDir}`, '-y'], { - encoding: 'utf8' - }) - expect(extracted.status).toBe(0) - expect(existsSync(join(outDir, 'payload', 'Orca.exe'))).toBe(true) - } finally { - rmSync(scratch, { recursive: true, force: true }) - } - }, 120_000) - - it('prefers an explicit ELECTRON_BUILDER_7ZIP_PATH override', async () => { - const scratch = mkdtempSync(join(tmpdir(), 'orca 7za override ')) - const previous = process.env.ELECTRON_BUILDER_7ZIP_PATH - try { - const fake = join(scratch, 'my7za') - writeFileSync(fake, '#!/bin/sh\n') - process.env.ELECTRON_BUILDER_7ZIP_PATH = fake - await expect(resolve7zaPath(projectRoot)).resolves.toBe(fake) - } finally { - if (previous === undefined) { - delete process.env.ELECTRON_BUILDER_7ZIP_PATH - } else { - process.env.ELECTRON_BUILDER_7ZIP_PATH = previous - } - rmSync(scratch, { recursive: true, force: true }) - } - }) - // Use directory override: Test-Path accepts it, masking bad resolver validation until extraction fails. it('ignores an override that points at a directory', async () => { const scratch = mkdtempSync(join(tmpdir(), 'orca 7za dir override ')) @@ -72,8 +27,6 @@ describe('7za path resolution for the Windows signing gates (#6487)', () => { } }, 120_000) - // Overlap calls to global stdout patch; naive save/restore can permanently restore another caller’s diverting stub. - // Use fresh subprocess: app-builder-lib memoizes toolset, hiding dangling-override failures in warm process. it('ignores an override that points at a missing file, in a cold process', () => { const dangling = join(tmpdir(), 'orca-7za-does-not-exist') @@ -94,22 +47,4 @@ describe('7za path resolution for the Windows signing gates (#6487)', () => { expect(resolved).not.toBe(dangling) expect(existsSync(resolved)).toBe(true) }, 120_000) - - it('prints exactly one clean line the PowerShell gate can consume', () => { - const result = spawnSync( - process.execPath, - ['config/scripts/archives/seven-zip/resolve-7za-path.mjs'], - { - cwd: projectRoot, - encoding: 'utf8', - timeout: 120_000 - } - ) - - expect(result.status).toBe(0) - expect(result.stdout.trimEnd().split('\n')).toHaveLength(1) - expect(existsSync(result.stdout.trim())).toBe(true) - }, 120_000) - - // Unset VITEST with cold cache: builder-util suppresses download logs in tests, hiding multiline stdout that breaks PowerShell path capture. }) diff --git a/config/scripts/artifact-storage/reflink-copy/space-sharing-copy.test.ts b/config/scripts/artifact-storage/reflink-copy/space-sharing-copy.test.ts index abb4c29875f..fbf91f4022c 100644 --- a/config/scripts/artifact-storage/reflink-copy/space-sharing-copy.test.ts +++ b/config/scripts/artifact-storage/reflink-copy/space-sharing-copy.test.ts @@ -71,14 +71,6 @@ function makeTree(): { root: string; source: string } { } describe('shareTree', () => { - it('keeps relative symlinks unresolved on whatever this host supports', () => { - const { root, source } = makeTree() - const destination = path.join(root, 'shared') - expect(shareTree(source, destination)).toBeTruthy() - expect(readFileSync(path.join(destination, 'nested', 'file'), 'utf8')).toBe('contents') - expect(readlinkSync(path.join(destination, 'relative-link'))).toBe(path.join('nested', 'file')) - }) - it('clears a part-way tree before trying the next mechanism', () => { const { root, source } = makeTree() const destination = path.join(root, 'shared') @@ -92,27 +84,7 @@ describe('shareTree', () => { }) }) -describe('hardlinkTree', () => { - it('shares inodes for files but recreates symlinks as their own entries', () => { - const { root, source } = makeTree() - const destination = path.join(root, 'linked') - hardlinkTree(source, destination) - expect(statSync(path.join(destination, 'nested', 'file')).ino).toBe( - statSync(path.join(source, 'nested', 'file')).ino - ) - expect(readlinkSync(path.join(destination, 'relative-link'))).toBe(path.join('nested', 'file')) - }) -}) - describe('makeTreeReadOnly', () => { - it('drops write permission on files while leaving directories traversable and unlinkable', () => { - const { source } = makeTree() - makeTreeReadOnly(source) - expect(statSync(path.join(source, 'nested', 'file')).mode & 0o222).toBe(0) - // Assert rename/remove behavior, not mode bits: Windows chmod maps only read-only attribute and directories never report 0755. - expect(() => rmSync(path.join(source, 'nested'), { recursive: true })).not.toThrow() - }) - it('turns an extract-over-dist write into an error instead of silent shared corruption', () => { const { root, source } = makeTree() const destination = path.join(root, 'linked') @@ -146,16 +118,4 @@ describe('copyPrivateTree', () => { expect(readFileSync(path.join(source, 'nested', 'file'), 'utf8')).toBe('contents') } ) - - it('falls back to a byte copy when the private mechanism fails', () => { - const { root, source } = makeTree() - const destination = path.join(root, 'private') - const clone = () => { - throw new Error('clonefile unsupported') - } - const result = copyPrivateTree(source, destination, { platform: 'darwin', clone }) - expect(result.mechanism).toBeNull() - expect(result.copyError).toBeInstanceOf(Error) - expect(readFileSync(path.join(destination, 'nested', 'file'), 'utf8')).toBe('contents') - }) }) diff --git a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs index a1d27b2dbec..d3f0de6a741 100644 --- a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs +++ b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.test.mjs @@ -36,7 +36,6 @@ describeBundling('the app bundle', () => { join(directory, 'index.tsx'), 'export default function Route() { return null }\n' ) - await expect(bundleMobileWebApp({ appDir: scratch })).resolves.toBeTruthy() await writeFile( join(directory, 'settings.tsx'), 'const anchor = { anchor: "index" }\nexport { anchor as unstable_settings }\nexport default function Route() { return null }\n' @@ -90,24 +89,6 @@ describeBundling('the app bundle', () => { }) describe('the verifier', () => { - itBundling( - "rejects a buildId the manifest's own asset list does not derive", - async () => { - await withScratch(async (scratch) => { - const outDir = join(scratch, 'mobile-web') - await copyWrittenBundle(outDir) - const manifestPath = join(outDir, 'manifest.json') - const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) - manifest.buildId = 'f'.repeat(64) - await writeFile(manifestPath, JSON.stringify(manifest), 'utf8') - await expect(verifyMobileWebAppBundle({ bundleDir: outDir })).rejects.toThrow( - 'does not match its asset list' - ) - }) - }, - 240_000 - ) - itBundling( 'rejects a self-consistent bundle a fresh build does not reproduce', async () => { diff --git a/config/scripts/build/mobile-web-app/mobile-web-bundle-serializer-parity.test.mjs b/config/scripts/build/mobile-web-app/mobile-web-bundle-serializer-parity.test.mjs deleted file mode 100644 index 713666a94b7..00000000000 --- a/config/scripts/build/mobile-web-app/mobile-web-bundle-serializer-parity.test.mjs +++ /dev/null @@ -1,49 +0,0 @@ -import { createRequire } from 'node:module' -import { describe, expect, it } from 'vitest' -import { serializeMobileWebBundleAssets as serializeInBuilder } from './mobile-web-bundle-manifest.mjs' -import { serializeMobileWebBundleAssets as serializeInContract } from '../../../../src/shared/mobile-web-bundle/manifest-contract' - -const require = createRequire(import.meta.url) -const { - serializeAssets: serializeInGuard -} = require('../../desktop-distribution/runtime-verification/verify-packaged-mobile-web-bundle.cjs') - -const digest = (hex) => `${hex}`.padStart(64, '0') - -// Mixed types/nested paths and uppercase ordering expose localeCompare drift from canonical code-unit sort. -const ASSETS = [ - { - path: 'assets/Za.js', - sha256: digest('a1'), - byteLength: 2048, - contentType: 'text/javascript; charset=utf-8' - }, - { path: 'assets/aQ.css', sha256: digest('b2'), byteLength: 512, contentType: 'text/css' }, - { - path: 'assets/nested/mark.png', - sha256: digest('c3'), - byteLength: 40_960, - contentType: 'image/png' - }, - { - path: 'index.html', - sha256: digest('d4'), - byteLength: 640, - contentType: 'text/html; charset=utf-8' - } -] - -describe('the three mobile web bundle serializers', () => { - it('emit exactly path, sha256, byteLength, contentType, in that order, and nothing else', () => { - const decorated = ASSETS.map((asset) => ({ ...asset, sourcePath: '/tmp/ignored', extra: 1 })) - - const expected = - '[{"path":"assets/Za.js","sha256":"00000000000000000000000000000000000000000000000000000000000000a1","byteLength":2048,"contentType":"text/javascript; charset=utf-8"},' + - '{"path":"assets/aQ.css","sha256":"00000000000000000000000000000000000000000000000000000000000000b2","byteLength":512,"contentType":"text/css"},' + - '{"path":"assets/nested/mark.png","sha256":"00000000000000000000000000000000000000000000000000000000000000c3","byteLength":40960,"contentType":"image/png"},' + - '{"path":"index.html","sha256":"00000000000000000000000000000000000000000000000000000000000000d4","byteLength":640,"contentType":"text/html; charset=utf-8"}]' - for (const serialize of [serializeInContract, serializeInBuilder, serializeInGuard]) { - expect(serialize(decorated)).toBe(expected) - } - }) -}) diff --git a/config/scripts/ci/e2e-selection/e2e-cli-artifact-capability.test.mjs b/config/scripts/ci/e2e-selection/e2e-cli-artifact-capability.test.mjs deleted file mode 100644 index 3d81ed517d1..00000000000 --- a/config/scripts/ci/e2e-selection/e2e-cli-artifact-capability.test.mjs +++ /dev/null @@ -1,48 +0,0 @@ -import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { delimiter, join } from 'node:path' -import { parse } from 'yaml' -import { describe, expect, it } from 'vitest' -import { runProcessSync } from '@orca/process-host' - -const workflow = parse(readFileSync('.github/workflows/e2e.yml', 'utf8')) -const build = workflow.jobs.build.steps.find((step) => step.id === 'e2e-cli') - -describe('shared E2E CLI capability', () => { - it.skipIf(process.platform === 'win32').each([ - [false, 0, 0], - [true, 0, 0], - [true, 7, 7] - ])('supported=%s build status=%s exits=%s', (supported, buildStatus, exitStatus) => { - const directory = mkdtempSync(join(tmpdir(), 'orca-e2e-cli-capability-')) - const marker = join(directory, 'build-requested') - try { - writeFileSync( - join(directory, 'package.json'), - JSON.stringify({ scripts: supported ? { 'prepare:cli-output': 'available' } : {} }) - ) - const pnpm = join(directory, 'pnpm') - writeFileSync(pnpm, '#!/bin/sh\nprintf "%s" "$*" > "$BUILD_MARKER"\nexit "$BUILD_STATUS"\n') - chmodSync(pnpm, 0o755) - const result = runProcessSync({ - program: 'bash', - args: ['-e', '-o', 'pipefail', '-c', build.run], - cwd: directory, - env: { - ...process.env, - PATH: `${directory}${delimiter}${process.env.PATH}`, - BUILD_MARKER: marker, - BUILD_STATUS: String(buildStatus) - }, - timeoutMs: 10_000 - }) - expect(result.code, JSON.stringify(result)).toBe(exitStatus) - expect(existsSync(marker)).toBe(supported) - if (supported) { - expect(readFileSync(marker, 'utf8')).toBe('run build:cli') - } - } finally { - rmSync(directory, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/ci/sharding/ci-shard-assignment.test.mjs b/config/scripts/ci/sharding/ci-shard-assignment.test.mjs index 0e3056504ab..73bcb0c103d 100644 --- a/config/scripts/ci/sharding/ci-shard-assignment.test.mjs +++ b/config/scripts/ci/sharding/ci-shard-assignment.test.mjs @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { discoverE2eFiles, planE2e } from '../e2e-selection/ci-e2e-shard-plan.mjs' -import { parseTimingLog } from './ci-shard-timing-import.mjs' describe('timing-weighted shard selection', () => { it('keeps nested/serial E2E files atomic and fails closed on discovery errors', () => { @@ -18,7 +17,6 @@ describe('timing-weighted shard selection', () => { 'one.spec.ts', 'two.spec.ts' ]) - expect(plan.testsByFile['one.spec.ts']).toHaveLength(2) expect(() => discoverE2eFiles({ ...report, errors: [{}] })).toThrow('errors') expect(() => discoverE2eFiles({ suites: [] })).toThrow('no tests') expect(() => @@ -30,25 +28,4 @@ describe('timing-weighted shard selection', () => { }) ).toThrow('Duplicate') }) - - it('imports ANSI unit timings and E2E failures without counting headful reruns', () => { - const parsed = parseTimingLog( - [ - '\u001b[32m✓\u001b[39m src/a.test.ts (2 tests) 35ms', - 'Duration 1s (transform 0.1s, setup 0.2s, import 0.3s, tests 0.04s, environment 0.4s)', - '✓ 1 [electron-headless] › tests/e2e/a.spec.ts:1:1 › works (2s)', - '✘ 2 [electron-headless] › tests/e2e/a.spec.ts:2:1 › fails (1.2m)', - '✓ 3 [electron-headful] › tests/e2e/a.spec.ts:3:1 › benchmark (9s)' - ].join('\n') - ) - expect(parsed).toEqual({ - unit: { 'src/a.test.ts': 35 }, - e2e: { 'tests/e2e/a.spec.ts': 74000 }, - overheadMs: 1000 - }) - }) - - it('rejects incomplete unit evidence instead of silently dropping overhead', () => { - expect(() => parseTimingLog('✓ src/a.test.ts (2 tests) 35ms')).toThrow('Duration summary') - }) }) diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 78bbe728ff8..e919f4ba0ce 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -40,7 +40,6 @@ "config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet-graph.test.mjs": 160, "config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs": 3540, "config/scripts/daemon-protocol/admission/check-runtime-launcher-protocol-ratchet.test.mjs": 212, - "config/scripts/performance/terminal-reporting/check-terminal-perf-report-budgets.test.mjs": 1600, "config/scripts/ci/unit-selection/check-test-file-runners.test.mjs": 267, "config/scripts/ci/workflow-contracts/ci-closed-pr-cancellation.test.mjs": 112, "config/scripts/ci/workflow-contracts/ci-draft-pr-admission.test.mjs": 546, @@ -76,18 +75,14 @@ "config/scripts/ci/e2e-selection/e2e-cli-artifact-capability.test.mjs": 233, "config/scripts/desktop-distribution/runtime-verification/electron-builder-config.test.mjs": 387, "config/scripts/desktop-distribution/runtime-verification/electron-builder-mac-channel-config.test.mjs": 309, - "config/scripts/desktop-distribution/runtime-verification/electron-builder-native-rebuild.test.mjs": 47, "config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs": 2505, "config/scripts/desktop-distribution/runtime-verification/electron-builder-speech-config.test.mjs": 212, "config/scripts/desktop-build/output-contracts/electron-vite-output-contract.test.ts": 77, "config/scripts/native-build/node-addons/ensure-native-runtime-job-ownership.test.mjs": 76, "config/scripts/native-build/node-addons/ensure-native-runtime.test.mjs": 908, "config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts": 31, - "config/scripts/orcad-distribution/server-bundle/foreign-sqlite-reader-worker-smoke.test.mjs": 491, "config/scripts/skills/bundle-generation/generate-skill-bundle-manifest.test.mjs": 956, "config/scripts/workspace-package-build/generated-artifact-line-ending-pin.test.mjs": 61, - "config/scripts/diagnostics/hang-watchdog/hang-watchdog-process-metrics.test.mjs": 94, - "config/scripts/runtime-verification/headless-detector/headless-detector-compiler-cache.test.mjs": 959, "config/scripts/ci/workflow-contracts/hourly-preflight-workflow.test.mjs": 158, "config/scripts/performance/idle-cpu/idle-cpu-process-sampling.test.mjs": 55, "config/scripts/static-analysis/oxlint-contracts/ime-enter-guard-plugin.test.mjs": 222, @@ -96,11 +91,7 @@ "config/scripts/diagnostics/lag-capture/lag-probe-failures.test.mjs": 55, "config/scripts/dependency-security/runtime-resolution/linear-sdk-runtime.test.mjs": 773, "config/scripts/preflight/changed-checks/lint-staged-worktree-backup.test.mjs": 278, - "config/scripts/locale-catalog/locale-brand-prefilter.test.mjs": 246, - "config/scripts/locale-catalog/locale-generic-ui-terms.test.mjs": 102, "config/scripts/locale-catalog/locale-repair-catalog-missing-leaves.test.mjs": 159, - "config/scripts/locale-catalog/locale-translation-policy.es-pr.test.mjs": 91, - "config/scripts/locale-catalog/locale-translation-policy.test.mjs": 189, "config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs": 317, "config/scripts/localization/extraction-policy/localization-extraction-change-scope.test.mjs": 732, "config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs": 52, @@ -110,7 +101,6 @@ "config/scripts/desktop-build/output-contracts/main-entry-facade.test.ts": 492, "config/scripts/runtime-verification/managed-account/managed-data-account-runtime.test.ts": 1381, "config/scripts/orcad-distribution/prebuilds/merge-orcad-prebuilds.test.mjs": 67, - "config/scripts/mobile-web/check-entry/mobile-process-host-tooling.test.mjs": 942, "config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs": 821, "config/scripts/mobile-web-app/shell/mobile-web-app-agent-icon-render.test.mjs": 591, "config/scripts/mobile-web-app/shell/mobile-web-app-browser-pane-render.test.mjs": 239, @@ -132,7 +122,6 @@ "config/scripts/mobile-web-app/shell/mobile-web-app-render.test.mjs": 254, "config/scripts/mobile-web-app/session/mobile-web-app-rich-markdown-render.test.mjs": 356, "config/scripts/mobile-web-app/mobile-web-app-route-manifest.test.mjs": 174, - "config/scripts/mobile-web-app/mobile-web-app-route-snapshot.test.mjs": 121, "config/scripts/mobile-web-app/shell/mobile-web-app-safe-area-render.test.mjs": 314, "config/scripts/mobile-web-app/session/mobile-web-app-screencast-lane-grant.test.mjs": 70, "config/scripts/mobile-web-app/session/mobile-web-app-session-dictation-capture.test.mjs": 123, @@ -173,24 +162,20 @@ "config/scripts/development/launch/orca-dev-bin.test.mjs": 110, "config/scripts/orcad-distribution/server-bundle/orcad-entry-build.test.mjs": 7008, "config/scripts/orcad-distribution/server-bundle/orcad-linear-sdk-package.test.mjs": 376, - "config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.test.mjs": 174, "config/scripts/orcad-distribution/prebuilds/orcad-prebuild-slot-contents.test.mjs": 79, "config/scripts/orcad-distribution/prebuilds/orcad-windows-prebuild-cache.test.mjs": 18343, "config/scripts/desktop-distribution/runtime-verification/package-electron-runtime-contract.test.mjs": 220, "config/scripts/desktop-distribution/linux/package-linux-formats-appimage.test.mjs": 624, "config/scripts/desktop-distribution/linux/package-linux-formats.test.mjs": 282, "config/scripts/desktop-distribution/runtime-verification/packaged-node-pty-prebuild-prune.test.mjs": 74, - "config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs": 407, "config/scripts/desktop-distribution/runtime-verification/packaged-process-host.test.mjs": 537, "config/scripts/desktop-distribution/runtime-verification/packaged-repository-input-exclusion.test.mjs": 222, - "config/scripts/desktop-distribution/runtime-verification/packaged-source-map-prune.test.mjs": 73, "config/scripts/desktop-distribution/runtime-verification/packaged-windows-only-runtime-files.test.mjs": 214, "config/scripts/dependency-security/audit-tools/patched-dependencies-frozen-install.test.mjs": 749, "config/scripts/web-build/pdf-viewer-assets/pdfjs-viewer-assets-stream.test.ts": 296, "config/scripts/orcad-distribution/prebuilds/pinned-node-downloads.test.mjs": 128, "config/scripts/desktop-build/output-contracts/plain-node-entry-guard.test.ts": 710, "config/scripts/ci/e2e-selection/playwright-focused-workflow-selection.test.mjs": 1565, - "config/scripts/tool-invocation/pnpm-cli-invocation.test.mjs": 65, "config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs": 2174, "config/scripts/workflow/source-routing/pr-code-change-scope.test.mjs": 403, "config/scripts/ci/e2e-selection/pr-e2e-managed-ssh-harness-route.test.mjs": 422, @@ -225,7 +210,6 @@ "config/scripts/release/versioning/release-rc-history.test.mjs": 230, "config/scripts/release/workflow-contracts/release-windows-signing-gate.test.mjs": 102, "config/scripts/static-analysis/oxlint-contracts/renderer-scrollbar-style-plugin.test.mjs": 234, - "config/scripts/static-analysis/renderer-styles/renderer-tailwind-sources.test.mjs": 289, "config/scripts/desktop-distribution/nsis/replace-cached-nsis-elevate.test.mjs": 1258, "config/scripts/ci/workflow-contracts/required-pr-check-name.test.mjs": 1266, "config/scripts/archives/seven-zip/resolve-7za-path.test.mjs": 1391, @@ -235,9 +219,7 @@ "config/scripts/typecheck/project-execution/run-typecheck-projects-in-parallel.test.mjs": 182, "config/scripts/tool-invocation/script-entry-detection.test.mjs": 107, "config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs": 62, - "config/scripts/orcad-distribution/server-bundle/session-scanner-service-smoke.test.mjs": 562, "config/scripts/ci/workflow-contracts/setup-pnpm-action.test.mjs": 421, - "config/scripts/electron-installation/shared-dist-cache/shared-electron-dist-cache.test.ts": 140, "config/scripts/native-build/node-addons/shared-native-build.test.mjs": 127, "config/scripts/artifact-storage/atomic-publication/shared-tree-publish.test.mjs": 63, "config/scripts/desktop-distribution/macos/sign-mac-app.test.mjs": 268, @@ -246,25 +228,17 @@ "config/scripts/desktop-distribution/appimage/static-appimage-package-contract.test.mjs": 88, "config/scripts/desktop-build/transform-contracts/sucrase-unused-transformers.test.ts": 43, "config/scripts/performance/terminal-reporting/terminal-perf-report-annotations.test.mjs": 54, - "config/scripts/desktop-distribution/windows/trim-windows-icon-source.test.mjs": 353, "config/scripts/dependency-security/runtime-resolution/undeclared-dependency-resolution.test.ts": 149, "config/scripts/node-runtime/archive-identity/update-node-runtime-pin.test.mjs": 87, - "config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs": 2422, "config/scripts/cli-build/verify-cli-bin.test.mjs": 135, "config/scripts/desktop-distribution/channel-policy/verify-dev-channel-packaging.test.mjs": 213, - "config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs": 156, "config/scripts/localization/catalog-validation/verify-localization-catalog.test.mjs": 422, - "config/scripts/localization/catalog-validation/verify-localization-catalogs.test.mjs": 1574, - "config/scripts/localization/source-extraction/verify-localization-extraction.test.mjs": 233, - "config/scripts/desktop-distribution/runtime-verification/verify-packaged-daemon-entry.test.mjs": 2009, "config/scripts/desktop-distribution/runtime-verification/verify-packaged-mobile-web-bundle.test.mjs": 214, "config/scripts/desktop-distribution/runtime-verification/verify-packaged-node-pty-job-ownership.test.mjs": 93, "config/scripts/orcad-distribution/template/verify-packaged-orcad-template.test.mjs": 454, - "config/scripts/desktop-distribution/runtime-verification/verify-packaged-plugin-resources.test.mjs": 101, "config/scripts/desktop-distribution/runtime-verification/verify-packaged-serve-payload.test.mjs": 83, "config/scripts/desktop-distribution/runtime-verification/verify-packaged-windows-agent-hook.test.mjs": 43, "config/scripts/runtime-verification/skills-cli/verify-skills-cli-runtime.test.mjs": 213, - "config/scripts/test-runtime/module-cache/vitest-module-cache-resolution-key.test.ts": 50, "config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts": 560, "config/scripts/test-runtime/environment/vitest-real-agent-home-write-guard.test.ts": 71, "config/scripts/test-runtime/execution-policy/vitest-run-temp-directory.test.mjs": 51, @@ -283,7 +257,6 @@ "config/scripts/ci/workflow-contracts/workflow-ref-mirror-case-safety.test.mjs": 447, "config/scripts/ci/workflow-contracts/workflow-ref-reachability.test.mjs": 1650, "config/scripts/workspace/source-exports/workspace-source-exports.test.mjs": 117, - "config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-admission.test.mjs": 1430, "config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-coordinate-boundaries.test.mjs": 191, "config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-file-transport.test.mjs": 404, "config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-glyph-visibility.test.mjs": 250, @@ -291,13 +264,11 @@ "config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-placeholder-lifecycle.test.mjs": 252, "config/scripts/terminal-dependencies/xterm-patches/xterm-image-kitty-retransmit.test.mjs": 835, "config/scripts/terminal-dependencies/xterm-patches/xterm-image-lifecycle-contract.test.mjs": 174, - "config/scripts/terminal-dependencies/xterm-patches/xterm-image-memory-contract.test.mjs": 368, "config/scripts/terminal-dependencies/xterm-patches/xterm-image-wasm-budget-contract.test.mjs": 469, "config/scripts/ci/workflow-contracts/zcode-credential-workflow.test.mjs": 668, "config/scripts/archives/platform-command/zip-extractor-command.test.mjs": 74, "src/cli/account-add-process.test.ts": 33700, "src/cli/agent-launch-process.test.ts": 2348, - "src/cli/agent-session-search-format.test.ts": 84, "src/cli/args-repeatable-flags.test.ts": 67, "src/cli/args.test.ts": 163, "src/cli/automation-format.test.ts": 101, @@ -309,7 +280,6 @@ "src/cli/command-suggestion-destructive-families.test.ts": 226, "src/cli/command-suggestion.test.ts": 68, "src/cli/computer-tree-query.test.ts": 79, - "src/cli/format-recovery.test.ts": 413, "src/cli/format.test.ts": 446, "src/cli/handlers/account.test.ts": 849, "src/cli/handlers/agent-hooks.test.ts": 1702, @@ -377,7 +347,6 @@ "src/cli/index-worktree-set.test.ts": 541, "src/cli/index-worktree-wsl-selection.test.ts": 712, "src/cli/index.test.ts": 1237, - "src/cli/linear-format.test.ts": 99, "src/cli/orchestration-dispatch-refusal-format.test.ts": 133, "src/cli/orchestration-mutation-recovery.test.ts": 415, "src/cli/orchestration-session-caller-cli.test.ts": 1513, @@ -398,7 +367,6 @@ "src/cli/plugin-dev-watch/plugin-dev-watch-process.test.ts": 69, "src/cli/plugin-dev-watch/plugin-dev-watch-shot.test.ts": 529, "src/cli/plugin-dev-watch/plugin-frame-log-dedupe.test.ts": 339, - "src/cli/quote-stripped-json-flag.test.ts": 63, "src/cli/reference-command-arguments.test.ts": 168, "src/cli/runtime-client-deferral.test.ts": 1276, "src/cli/runtime-client.test.ts": 633, @@ -519,8 +487,6 @@ "src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts": 820, "src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts": 681, "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts": 10279, - "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts": 34523, - "src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts": 877, "src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts": 675, "src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts": 679, "src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts": 5451, @@ -778,28 +744,27 @@ "src/main/automations/automation-dispatch-host-fence.test.ts": 2592, "src/main/automations/automation-owner-fencing.test.ts": 2028, "src/main/automations/automation-run-terminal-surface.test.ts": 4180, - "src/main/automations/automation-run-writer.test.ts": 242, "src/main/automations/automation-skip-coalescing.test.ts": 2577, - "src/main/automations/automation-ssh-readoption-migration.test.ts": 59, + "src/main/automations/ownership/automation-ssh-readoption-migration.test.ts": 59, "src/main/automations/automation-update-host-retarget.test.ts": 1842, "src/main/automations/automation-worker-durability.test.ts": 4273, "src/main/automations/automation-workspace-host-attribution.test.ts": 2088, "src/main/automations/automation-wsl-distro-stopped-refusal.test.ts": 2151, "src/main/automations/automation-wsl-move-refusal.test.ts": 2285, "src/main/automations/automation-zero-grace-tick-latency.test.ts": 2108, - "src/main/automations/dispatch-refusal-wsl-move.test.ts": 577, - "src/main/automations/external-automation-manager-cache.test.ts": 70, - "src/main/automations/external-automation-probe-scheduler.test.ts": 97, - "src/main/automations/external-manager-scoped.test.ts": 391, + "src/main/automations/dispatch/dispatch-refusal-wsl-move.test.ts": 577, + "src/main/automations/external-managers/external-automation-manager-cache.test.ts": 70, + "src/main/automations/external-managers/external-automation-probe-scheduler.test.ts": 97, + "src/main/automations/external-managers/scoped-external-automations.test.ts": 391, "src/main/automations/run-terminal-retention.test.ts": 112, "src/main/automations/automation-workspace-create.test.ts": 50, "src/main/automations/hook-review-blocked-run-terminals.test.ts": 4564, - "src/main/automations/precheck-runner.test.ts": 1132, - "src/main/automations/retained-run-reconciliation.test.ts": 1940, - "src/main/automations/run-target-resolution.test.ts": 367, + "src/main/automations/dispatch/precheck-runner.test.ts": 1132, + "src/main/automations/observation/retained-run-reconciliation.test.ts": 1940, + "src/main/automations/ownership/run-target-resolution.test.ts": 367, "src/main/automations/runtime-terminal-run-observer-evidence.test.ts": 230, "src/main/automations/service-precheck.test.ts": 2057, - "src/main/automations/service.test.ts": 2970, + "src/main/automations/automation-service.test.ts": 2970, "src/main/bitbucket/credential-store.test.ts": 245, "src/main/bitbucket/repository-ref.test.ts": 426, "src/main/bitbucket/status-no-decrypt.test.ts": 256, @@ -908,13 +873,9 @@ "src/main/browser/webauthn/browser-webauthn-account-picker.test.ts": 78, "src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts": 358, "src/main/browser/cdp/commands/cdp-bridge-integration.test.ts": 28361, - "src/main/browser/cdp/transport/cdp-client-response-writer.test.ts": 279, "src/main/browser/cdp/commands/cdp-print-to-pdf.test.ts": 68, "src/main/browser/cdp/commands/cdp-screenshot.test.ts": 415, - "src/main/browser/cdp/transport/cdp-ws-proxy-first-paint.test.ts": 366, "src/main/browser/cdp/transport/cdp-ws-proxy-host-admission.test.ts": 576, - "src/main/browser/cdp/transport/cdp-ws-proxy-input-focus.test.ts": 360, - "src/main/browser/cdp/transport/cdp-ws-proxy-malformed-messages.test.ts": 305, "src/main/browser/cdp/transport/cdp-ws-proxy-origin.test.ts": 262, "src/main/browser/cdp/transport/cdp-ws-proxy-startup-lifetime.test.ts": 326, "src/main/browser/cdp/transport/cdp-ws-proxy.test.ts": 2756, @@ -957,7 +918,6 @@ "src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts": 832, "src/main/browser/extensions/installation/browser-extension-archive.test.ts": 72, "src/main/browser/extensions/actions/browser-extension-commands.test.ts": 52, - "src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts": 313, "src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts": 68, "src/main/browser/extensions/context-menus/browser-extension-context-menu-model.test.ts": 57, "src/main/browser/extensions/installation/browser-extension-crx.test.ts": 214, @@ -1029,7 +989,6 @@ "src/main/browser/routing/local-host-partitions/wsl-host-browser-route-partition.test.ts": 753, "src/main/claude-accounts/sign-in/claude-account-folder.test.ts": 153, "src/main/claude-accounts/claude-account-service.test.ts": 1207, - "src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts": 90, "src/main/claude-accounts/sign-in/claude-login-session.test.ts": 1048, "src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts": 238, "src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts": 121, @@ -1041,7 +1000,6 @@ "src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts": 405, "src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts": 919, "src/main/claude-accounts/sign-in/claude-sign-in-browser.test.ts": 314, - "src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts": 52, "src/main/claude-accounts/runtime-auth/keychain-config-directory-aliases.test.ts": 51, "src/main/claude-accounts/selection/runtime-selection.test.ts": 41, "src/main/claude-accounts/sign-in/windows-command-invocation.test.ts": 48, @@ -1061,62 +1019,62 @@ "src/main/claude/agent-view/agent-view-service.test.ts": 403, "src/main/claude/claude-agent-sdk-contract-pins.test.ts": 3506, "src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts": 134, - "src/main/claude/claude-agent-sdk-exit-proof.test.ts": 8832, - "src/main/claude/claude-agent-sdk-import-boundary.test.ts": 546, - "src/main/claude/claude-agent-sdk-process-spawn.test.ts": 182, - "src/main/claude/claude-agent-sdk-user-message-queue.test.ts": 143, + "src/main/claude/child-process/claude-agent-sdk-exit-proof.test.ts": 8832, + "src/main/claude/sdk-transport/claude-agent-sdk-import-boundary.test.ts": 546, + "src/main/claude/child-process/claude-agent-sdk-process-spawn.test.ts": 182, + "src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.test.ts": 143, "src/main/claude/claude-api-retry-row.test.ts": 901, "src/main/claude/claude-background-run-isolation-real-cli.test.ts": 147, "src/main/claude/claude-background-stop-records.test.ts": 1249, - "src/main/claude/claude-background-task-resume.test.ts": 54, - "src/main/claude/claude-background-task-terminal-frames.test.ts": 103, + "src/main/claude/background-tasks/claude-background-task-resume.test.ts": 54, + "src/main/claude/background-tasks/claude-background-task-terminal-frames.test.ts": 103, "src/main/claude/claude-background-task-turn-resumption.test.ts": 325, "src/main/claude/claude-background-wake-retention.test.ts": 1652, - "src/main/claude/claude-child-process-environment.test.ts": 52, - "src/main/claude/claude-child-work-decoder.test.ts": 110, + "src/main/claude/child-process/claude-child-process-environment.test.ts": 52, + "src/main/claude/child-work/claude-child-work-decoder.test.ts": 110, "src/main/claude/claude-close-turn-end.test.ts": 970, - "src/main/claude/claude-command-lifecycle-frames.test.ts": 268, - "src/main/claude/claude-command-lifecycle.test.ts": 1107, - "src/main/claude/claude-command-turn.test.ts": 292, - "src/main/claude/claude-config-dir-pin.test.ts": 47, + "src/main/claude/structured/turns/claude-command-lifecycle-frames.test.ts": 268, + "src/main/claude/structured/turns/claude-command-lifecycle.test.ts": 1107, + "src/main/claude/structured/turns/claude-command-turn.test.ts": 292, + "src/main/claude/structured/launch/claude-config-dir-pin.test.ts": 47, "src/main/claude/claude-context-model-switch.test.ts": 422, "src/main/claude/claude-context-usage-restart.test.ts": 925, "src/main/claude/claude-context-usage-unloaded-turn.test.ts": 4910, "src/main/claude/claude-descendant-escalation-boundary.test.ts": 593, - "src/main/claude/claude-diff-panel-auto-open.test.ts": 117, + "src/main/claude/configuration/claude-diff-panel-auto-open.test.ts": 117, "src/main/claude/claude-fold-steer-receipt.test.ts": 1019, - "src/main/claude/claude-folder-trust-file.test.ts": 762, - "src/main/claude/claude-hook-event-versions.test.ts": 137, + "src/main/claude/configuration/claude-folder-trust-file.test.ts": 762, + "src/main/claude/cli-capabilities/claude-hook-event-versions.test.ts": 137, "src/main/claude/claude-informational-row.test.ts": 811, - "src/main/claude/claude-journal-turn-scope.test.ts": 254, - "src/main/claude/claude-model-catalog-probe.test.ts": 2098, + "src/main/claude/structured/journal/claude-journal-turn-scope.test.ts": 254, + "src/main/claude/model-catalog/claude-model-catalog-probe.test.ts": 2098, "src/main/claude/claude-naming-invocation.test.ts": 334, "src/main/claude/claude-plan-approval-mode.test.ts": 905, - "src/main/claude/claude-profile-hooks.test.ts": 371, - "src/main/claude/claude-provider-session-rename.test.ts": 597, - "src/main/claude/claude-provisional-row-corrections.test.ts": 67, - "src/main/claude/claude-request-end-wait.test.ts": 53, - "src/main/claude/claude-rewind-transcript.test.ts": 762, + "src/main/claude/hooks/claude-profile-hooks.test.ts": 371, + "src/main/claude/transcripts/claude-provider-session-rename.test.ts": 597, + "src/main/claude/subagents/claude-provisional-row-corrections.test.ts": 67, + "src/main/claude/structured/turns/claude-request-end-wait.test.ts": 53, + "src/main/claude/transcripts/claude-rewind-transcript.test.ts": 762, "src/main/claude/claude-settings-schema-install.test.ts": 410, - "src/main/claude/claude-status-line-install.test.ts": 342, + "src/main/claude/hooks/claude-status-line-install.test.ts": 342, "src/main/claude/claude-status-line-windows.test.ts": 273, "src/main/claude/claude-stop-ack-race.test.ts": 1301, "src/main/claude/claude-stream-json-connection-close.test.ts": 621, - "src/main/claude/claude-stream-json-connection.test.ts": 8687, - "src/main/claude/claude-streamed-text-checkpoints.test.ts": 59, + "src/main/claude/sdk-transport/claude-stream-json-connection.test.ts": 8687, + "src/main/claude/structured/journal/claude-streamed-text-checkpoints.test.ts": 59, "src/main/claude/claude-structured-launch-home-perf.test.ts": 401, "src/main/claude/claude-structured-result-control-overlap.test.ts": 1136, - "src/main/claude/claude-subagent-id-aliases.test.ts": 46, + "src/main/claude/subagents/claude-subagent-id-aliases.test.ts": 46, "src/main/claude/claude-subagent-permission-request.test.ts": 3776, - "src/main/claude/claude-subagent-resume-after-restart.test.ts": 825, + "src/main/claude/subagents/claude-subagent-resume-after-restart.test.ts": 825, "src/main/claude/claude-supervised-stop-real-cli.test.ts": 382, "src/main/claude/claude-supervised-stop.integration.test.ts": 3821, - "src/main/claude/claude-transcript-catch-up.test.ts": 4017, + "src/main/claude/transcripts/claude-transcript-catch-up.test.ts": 4017, "src/main/claude/claude-transcript-duration.test.ts": 1411, - "src/main/claude/claude-transcript-entry-uuid.test.ts": 38, - "src/main/claude/hook-service.test.ts": 329, - "src/main/claude/post-compact-hook-command.test.ts": 314, - "src/main/claude/statusline-script.test.ts": 257, + "src/main/claude/transcripts/claude-transcript-entry-uuid.test.ts": 38, + "src/main/claude/hooks/hook-service.test.ts": 329, + "src/main/claude/hooks/post-compact-hook-command.test.ts": 314, + "src/main/claude/hooks/statusline-script.test.ts": 257, "src/main/claude/structured/claude-structured-content-parts.test.ts": 277, "src/main/claude/structured/claude-structured-conversation-stop.test.ts": 884, "src/main/claude/structured/claude-structured-dispatch-admission.test.ts": 426, @@ -1158,7 +1116,7 @@ "src/main/claude/structured/launch/claude-structured-options.test.ts": 420, "src/main/claude/structured/launch/claude-structured-provider-fallback.test.ts": 670, "src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts": 902, - "src/main/claude/windows-hook-files.test.ts": 356, + "src/main/claude/hooks/windows-hook-files.test.ts": 356, "src/main/claude/windows-native-hook-registration.test.ts": 246, "src/main/cli/appimage/appimage-copy-pre-extraction.test.ts": 328, "src/main/cli/appimage/appimage-extraction-pruning-namespace.test.ts": 106, @@ -1182,58 +1140,40 @@ "src/main/cli/wsl/wsl-cli-registration-registry.test.ts": 150, "src/main/cli/wsl/wsl-managed-cli.wsl.test.ts": 115, "src/main/codebuddy/hook-service.test.ts": 272, - "src/main/codex-accounts/async-file-rename.test.ts": 1065, - "src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts": 55, - "src/main/codex-accounts/codex-config-mirror.test.ts": 331, - "src/main/codex-accounts/codex-credential-absence-grace.test.ts": 62, - "src/main/codex-accounts/codex-device-auth-prompt.test.ts": 48, - "src/main/codex-accounts/codex-login-auth-url.test.ts": 44, - "src/main/codex-accounts/codex-login-session-wsl-open.test.ts": 184, - "src/main/codex-accounts/codex-managed-home-path-wsl-check.test.ts": 71, - "src/main/codex-accounts/codex-reset-credit-ledger.test.ts": 283, + "src/main/filesystem/async-file-rename.test.ts": 1065, + "src/main/codex-accounts/credentials/codex-account-identity-api-key-guard.test.ts": 55, + "src/main/codex-accounts/managed-homes/codex-config-mirror.test.ts": 331, + "src/main/codex-accounts/credentials/codex-credential-absence-grace.test.ts": 62, + "src/main/codex-accounts/login/codex-device-auth-prompt.test.ts": 48, + "src/main/codex-accounts/login/codex-login-auth-url.test.ts": 44, + "src/main/codex-accounts/managed-homes/codex-managed-home-path-wsl-check.test.ts": 71, + "src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts": 283, "src/main/filesystem/atomic-file-publication.test.ts": 127, - "src/main/codex-accounts/guest-codex-account-homes.test.ts": 86, - "src/main/codex-accounts/host-codex-managed-home-ownership.test.ts": 51, - "src/main/codex-accounts/legacy-shared-auth-migration.test.ts": 134, - "src/main/codex-accounts/legacy-shared-config-compatibility.test.ts": 151, - "src/main/codex-accounts/legacy-wsl-runtime-auth-drain-apply-script.test.ts": 5936, - "src/main/codex-accounts/legacy-wsl-runtime-auth-drain-interruption-source.test.ts": 68, - "src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts": 558, - "src/main/codex-accounts/managed-codex-auth-readiness.test.ts": 86, - "src/main/codex-accounts/runtime-home-catalog-account-key.test.ts": 2664, - "src/main/codex-accounts/runtime-home-catalog-probe-prep.test.ts": 583, - "src/main/codex-accounts/runtime-home-legacy-migration.test.ts": 1147, - "src/main/codex-accounts/runtime-home-managed-auth-recovery.test.ts": 658, - "src/main/codex-accounts/runtime-home-mirror-login-copy.test.ts": 1012, - "src/main/codex-accounts/runtime-home-per-account-homes.test.ts": 1107, - "src/main/codex-accounts/runtime-home-rate-limit-pinned-distro.test.ts": 521, - "src/main/codex-accounts/runtime-home-real-home-lane-routing.test.ts": 879, - "src/main/codex-accounts/runtime-home-retained-auth-provenance.test.ts": 1404, - "src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts": 980, - "src/main/codex-accounts/runtime-home-session-discovery-read-only.test.ts": 543, - "src/main/codex-accounts/runtime-home-session-migration-pass.test.ts": 705, - "src/main/codex-accounts/runtime-home-status-hook-independence.test.ts": 743, - "src/main/codex-accounts/runtime-home-system-default-mirror-readback.test.ts": 1493, - "src/main/codex-accounts/runtime-home-system-default-snapshot.test.ts": 1255, - "src/main/codex-accounts/runtime-home-system-resource-materialization.test.ts": 1196, - "src/main/codex-accounts/runtime-home-windows-profile-ownership.test.ts": 359, - "src/main/codex-accounts/runtime-home-wsl-managed-accounts.test.ts": 1199, - "src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts": 1018, - "src/main/codex-accounts/runtime-home-wsl-system-default.test.ts": 758, - "src/main/codex-accounts/service-abandoned-login-supersede.test.ts": 780, - "src/main/codex-accounts/service-account-add-login.test.ts": 757, - "src/main/codex-accounts/service-account-selection-and-removal.test.ts": 1020, - "src/main/codex-accounts/service-add-account-from-home.test.ts": 437, - "src/main/codex-accounts/service-login-process-teardown.test.ts": 570, - "src/main/codex-accounts/service-managed-home-identity.test.ts": 567, - "src/main/codex-accounts/service-quota-refresh-decoupling.test.ts": 640, - "src/main/codex-accounts/service-reauthenticate-activation.test.ts": 758, - "src/main/codex-accounts/service-reset-credit-home-ownership.test.ts": 768, - "src/main/codex-accounts/service-system-default-identity.test.ts": 624, - "src/main/codex-accounts/service-wsl-accounts.test.ts": 780, - "src/main/codex-accounts/service.test.ts": 866, - "src/main/codex-accounts/sta-4734-login-rollback-deletes-authenticated-home.test.ts": 713, - "src/main/codex-accounts/sta-4735-unreadable-host-lane-writes.test.ts": 564, + "src/main/codex-accounts/managed-homes/guest-codex-account-homes.test.ts": 86, + "src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.test.ts": 51, + "src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.test.ts": 134, + "src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.test.ts": 151, + "src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-apply-script.test.ts": 5936, + "src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-rollback-script.test.ts": 558, + "src/main/codex-accounts/credentials/managed-codex-auth-readiness.test.ts": 86, + "src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts": 1147, + "src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts": 658, + "src/main/codex-accounts/runtime-home/credentials/runtime-home-mirror-login-copy.test.ts": 1012, + "src/main/codex-accounts/runtime-home/routing/runtime-home-per-account-homes.test.ts": 1107, + "src/main/codex-accounts/runtime-home/routing/runtime-home-real-home-lane-routing.test.ts": 879, + "src/main/codex-accounts/runtime-home/credentials/runtime-home-retained-auth-provenance.test.ts": 1404, + "src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts": 980, + "src/main/codex-accounts/runtime-home/routing/runtime-home-session-migration-pass.test.ts": 705, + "src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-mirror-readback.test.ts": 1493, + "src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-snapshot.test.ts": 1255, + "src/main/codex-accounts/runtime-home/routing/runtime-home-system-resource-materialization.test.ts": 1196, + "src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts": 1199, + "src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-session-bridge.test.ts": 1018, + "src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-system-default.test.ts": 758, + "src/main/codex-accounts/account-management/service-system-default-identity.test.ts": 624, + "src/main/codex-accounts/account-management/service-wsl-accounts.test.ts": 780, + "src/main/codex-accounts/account-management/service.test.ts": 866, + "src/main/codex-accounts/account-management/sta-4734-login-rollback-deletes-authenticated-home.test.ts": 713, "src/main/codex-cli/codex-home-process-lock.test.ts": 52, "src/main/codex-cli/command-guest-path.test.ts": 126, "src/main/codex-usage/codex-rollout-file-lifetime.test.ts": 173, @@ -1296,7 +1236,6 @@ "src/main/codex/hooks/definitions/codex-real-home-hook-key-spellings.test.ts": 408, "src/main/codex/hooks/reconciliation/codex-real-home-hook-removal.test.ts": 388, "src/main/codex/configuration/homes/codex-real-home-path.test.ts": 76, - "src/main/codex/hooks/reconciliation/codex-real-home-shared-entry.test.ts": 641, "src/main/codex/history/backfill/codex-session-backfill.test.ts": 310, "src/main/codex/history/bridges/codex-session-bridge.test.ts": 118, "src/main/codex/history/index/codex-session-index-heal-state.test.ts": 363, @@ -1348,7 +1287,6 @@ "src/main/codex/structured/session-lifecycle/codex-structured-session-adapter-lifecycle.test.ts": 597, "src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.test.ts": 837, "src/main/codex/structured/session-lifecycle/codex-structured-session-background-tasks.test.ts": 761, - "src/main/codex/structured/session-lifecycle/codex-structured-session-cancel.test.ts": 647, "src/main/codex/structured/session-lifecycle/codex-structured-session-exit-blame.test.ts": 548, "src/main/codex/structured/session-lifecycle/codex-structured-session-prompts.test.ts": 609, "src/main/codex/structured/session-lifecycle/codex-structured-session-shutdown.test.ts": 635, @@ -1386,7 +1324,6 @@ "src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts": 1048, "src/main/codex/hooks/installation/hook-service-managed-install.test.ts": 492, "src/main/codex/hooks/installation/hook-service-runtime-trust-repair.test.ts": 475, - "src/main/codex/hooks/installation/hook-service-trust-grant.test.ts": 318, "src/main/codex/hooks/installation/hook-service-user-hook-mirroring.test.ts": 596, "src/main/codex/hooks/installation/hook-service-user-hook-trust-spellings.test.ts": 657, "src/main/codex/hooks/installation/hook-service-windows-key-spellings.test.ts": 461, @@ -1474,7 +1411,6 @@ "src/main/daemon/providers/lifecycle/testing/daemon-init-restart-sequence.test.ts": 2118, "src/main/daemon/providers/lifecycle/testing/daemon-init-severed-host-image.test.ts": 808, "src/main/daemon/providers/lifecycle/testing/daemon-init-wedged-daemon-grace.test.ts": 1192, - "src/main/daemon/providers/routing/testing/daemon-inventory-acquisition-budget.test.ts": 127, "src/main/daemon/launch/testing/daemon-launched-child-identity.test.ts": 102, "src/main/daemon/launch/testing/daemon-legacy-process-liveness.test.ts": 97, "src/main/daemon/health/testing/daemon-liveness-report.test.ts": 656, @@ -1501,7 +1437,6 @@ "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-replacement-exit-race.test.ts": 6234, "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts": 1777, "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts": 1263, - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.test.ts": 1470, "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-wake-relaunch-history.test.ts": 795, "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-wsl-distro-loss.test.ts": 1098, "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-wsl-passive-restore-hold.test.ts": 892, @@ -1514,7 +1449,6 @@ "src/main/daemon/providers/routing/testing/daemon-pty-router-legacy-owner.test.ts": 276, "src/main/daemon/providers/routing/testing/daemon-pty-router-newer-daemon-hold.test.ts": 148, "src/main/daemon/providers/routing/testing/daemon-pty-router-unanswering-legacy.test.ts": 5191, - "src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts": 914, "src/main/daemon/server/testing/daemon-pty-spawn-preparations.test.ts": 48, "src/main/daemon/providers/adapter/testing/daemon-pty-upgrade-adoption.test.ts": 939, "src/main/daemon/providers/checkpointing/testing/daemon-reattach-checkpoint-isolation.test.ts": 1008, @@ -1526,7 +1460,6 @@ "src/main/daemon/server/testing/daemon-server-attachment-lifecycle.test.ts": 921, "src/main/daemon/server/testing/daemon-server-error-handling.test.ts": 811, "src/main/daemon/server/testing/daemon-server.test.ts": 1290, - "src/main/daemon/providers/routing/testing/daemon-session-owner-resolution.test.ts": 114, "src/main/daemon/sessions/testing/daemon-session-scrollback-window.test.ts": 554, "src/main/daemon/providers/lifecycle/testing/daemon-severed-restart.test.ts": 629, "src/main/daemon/providers/checkpointing/testing/daemon-shutdown-final-checkpoint-caller-deadline.test.ts": 2543, @@ -1546,7 +1479,6 @@ "src/main/daemon/server/testing/daemon-transport-attachment-release.test.ts": 893, "src/main/daemon/providers/wsl/testing/daemon-wsl-bridge-exit-no-boot.test.ts": 119, "src/main/daemon/providers/wsl/testing/daemon-wsl-hold-read-anchor.test.ts": 88, - "src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts": 192, "src/main/daemon/admission/testing/desktop-restore-admission.test.ts": 650, "src/main/daemon/emulation/testing/headless-emulator-fidelity.fuzz.test.ts": 2810, "src/main/daemon/emulation/testing/headless-emulator-modify-other-keys.test.ts": 160, @@ -1566,7 +1498,6 @@ "src/main/daemon/executable-host/macos/testing/macos-daemon-bundle.test.ts": 152, "src/main/daemon/executable-host/macos/testing/macos-daemon-job-state.test.ts": 73, "src/main/daemon/executable-host/macos/testing/macos-daemon-launchd.test.ts": 297, - "src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts": 96, "src/main/daemon/executable-host/macos/testing/macos-retired-daemon-recovery.test.ts": 158, "src/main/daemon/transport/framing/testing/ndjson.test.ts": 133, "src/main/daemon/pty-subprocess/testing/node-pty-conout-worker-errors.test.ts": 200, @@ -1578,16 +1509,9 @@ "src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts": 2130, "src/main/daemon/sessions/testing/pty-session-id.test.ts": 62, "src/main/daemon/pty-subprocess/testing/pty-subprocess-env-retention.test.ts": 431, - "src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-degraded-scan.test.ts": 406, - "src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-identity.test.ts": 818, "src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts": 449, "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts": 1127, - "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts": 3285, - "src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts": 528, - "src/main/daemon/pty-subprocess/testing/pty-subprocess-windows-shell-launch.test.ts": 459, - "src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts": 431, "src/main/daemon/pty-subprocess/native-pty-spawn-windows.test.ts": 1264, - "src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts": 181, "src/main/daemon/sessions/testing/reattach-snapshot.test.ts": 1130, "src/main/daemon/sessions/testing/repro-12101-mouse-tracking-survives-agent-death.test.ts": 276, "src/main/daemon/emulation/testing/repro-7329-remote-snapshot-corruption.test.ts": 172, @@ -1618,9 +1542,7 @@ "src/main/daemon/terminal-host/testing/terminal-host-attach-only.test.ts": 471, "src/main/daemon/terminal-host/testing/terminal-host-closing-session-listing.test.ts": 788, "src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts": 665, - "src/main/daemon/terminal-host/testing/terminal-host-cwd-readability.test.ts": 565, "src/main/daemon/terminal-host/testing/terminal-host-fenced-termination.test.ts": 1231, - "src/main/daemon/terminal-host/testing/terminal-host-process-inspection.test.ts": 592, "src/main/daemon/terminal-host/testing/terminal-host-pty-owner-backend.test.ts": 459, "src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts": 649, "src/main/daemon/terminal-host/testing/terminal-host-spawn-input-retention.test.ts": 896, @@ -1696,7 +1618,6 @@ "src/main/ghostty/theme-import.test.ts": 100, "src/main/git/refs/resolution/base-ref-search-selector.test.ts": 257, "src/main/git/worktrees/checkout/branch-rename.test.ts": 66, - "src/main/git/repositories/canonical-repo-key.test.ts": 221, "src/main/git/worktrees/checkout/checkout-branch-identity-real-git.test.ts": 378, "src/main/git/remotes/coalesced-probe.test.ts": 43, "src/main/git/command-runner/exec-file-capture-bytes.test.ts": 4698, @@ -1724,16 +1645,15 @@ "src/main/git/command-runner/git-capability-state.test.ts": 60, "src/main/git/command-runner/git-environment/git-network-safety-real-git.test.ts": 378, "src/shared/git/status/git-status-read-lease-owner.test.ts": 49, - "src/main/git/source-control/git-upstream-status-read-owner.test.ts": 45, "src/main/git/command-runner/git-worktree-mutation-state.test.ts": 74, "src/main/git/remotes/hosted-remote-url.test.ts": 43, - "src/main/git/source-control/huge-folder-ignore.test.ts": 58, + "src/main/git/source-control/ignores/huge-folder-ignore.test.ts": 58, "src/main/git/objects/local-git-object-quarantine.test.ts": 108, "src/main/git/refs/maintenance/local-repo-ref-maintenance-wsl-stopped.test.ts": 271, "src/main/git/refs/maintenance/local-repo-ref-maintenance.test.ts": 339, "src/main/git/objects/merge-tree-object-quarantine-real-git.test.ts": 2561, "src/main/git/refs/maintenance/pack-refs-lock-ownership.test.ts": 59, - "src/main/git/source-control/porcelain-v1-records.test.ts": 138, + "src/main/git/source-control/status/porcelain-v1-records.test.ts": 138, "src/main/git/remotes/remote-name-listing.test.ts": 398, "src/main/git/remotes/remote-ref-probe-cache.test.ts": 414, "src/main/git/remotes/remote.test.ts": 352, @@ -1769,38 +1689,36 @@ "src/main/git/command-runner/host-routing/runner-wsl-login-shell-capture.test.ts": 222, "src/main/git/command-runner/git-environment/runner-wsl-network-ssh-policy.test.ts": 260, "src/main/git/repositories/cloning/saved-clone-target.test.ts": 890, - "src/main/git/source-control/blob-absence-real-git.test.ts": 629, - "src/main/git/source-control/complete-merge-real-git.test.ts": 958, - "src/main/git/source-control/diff-textconv-real-git.test.ts": 520, - "src/main/git/source-control/diff-too-large-real-git.test.ts": 446, - "src/main/git/source-control/drive-checkout-suspect-paths.test.ts": 49, + "src/main/git/source-control/diffs/blob-absence-real-git.test.ts": 629, + "src/main/git/source-control/mutations/complete-merge-real-git.test.ts": 958, + "src/main/git/source-control/diffs/diff-textconv-real-git.test.ts": 520, + "src/main/git/source-control/diffs/diff-too-large-real-git.test.ts": 446, + "src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts": 49, "src/main/git/source-control/drive-checkout-suspect-real-git.test.ts": 406, "src/main/git/source-control/drive-checkout-suspect-writes-real-git.test.ts": 691, - "src/main/git/source-control/stage-worktree-changes.test.ts": 1737, - "src/main/git/source-control/staged-rename-diff-real-git.test.ts": 362, - "src/main/git/source-control/staging-discard-index-safety.test.ts": 689, - "src/main/git/source-control/submodule-gitlink-pathspec-real-git.test.ts": 337, - "src/main/git/source-control/submodule-restore-recurse-real-git.test.ts": 398, - "src/main/git/source-control/status-branch-compare-real-ref.test.ts": 593, + "src/main/git/source-control/mutations/stage-worktree-changes.test.ts": 1737, + "src/main/git/source-control/diffs/staged-rename-diff-real-git.test.ts": 362, + "src/main/git/source-control/mutations/staging-discard-index-safety.test.ts": 689, + "src/main/git/source-control/submodules/submodule-gitlink-pathspec-real-git.test.ts": 337, + "src/main/git/source-control/submodules/submodule-restore-recurse-real-git.test.ts": 398, + "src/main/git/source-control/comparisons/status-branch-compare-real-ref.test.ts": 593, "src/main/git/source-control/status-branch-compare.test.ts": 251, - "src/main/git/source-control/status-branch-line-total-exec-contract.test.ts": 1033, - "src/main/git/source-control/status-branch-line-total-real-git.test.ts": 785, - "src/main/git/source-control/status-branch-line-total-untracked-base.test.ts": 700, - "src/main/git/source-control/status-cquoted-paths.test.ts": 348, - "src/main/git/source-control/status-diff.test.ts": 327, + "src/main/git/source-control/status/status-branch-line-total-exec-contract.test.ts": 1033, + "src/main/git/source-control/status/status-branch-line-total-real-git.test.ts": 785, + "src/main/git/source-control/status/status-branch-line-total-untracked-base.test.ts": 700, + "src/main/git/source-control/diffs/status-diff.test.ts": 327, "src/main/git/source-control/status-discard-and-bulk-staging.test.ts": 289, - "src/main/git/source-control/status-discard-symlink.test.ts": 456, - "src/main/git/source-control/status-line-stats-host-paths.test.ts": 77, - "src/main/git/source-control/status-line-stats-renames-real-git.test.ts": 631, - "src/main/git/source-control/status-pathspec-literals.test.ts": 442, + "src/main/git/source-control/mutations/status-discard-symlink.test.ts": 456, + "src/main/git/source-control/status/status-line-stats-host-paths.test.ts": 77, + "src/main/git/source-control/status/status-line-stats-renames-real-git.test.ts": 631, + "src/main/git/source-control/mutations/status-pathspec-literals.test.ts": 442, "src/shared/git/status/git-status-porcelain-parser.test.ts": 52, "src/main/git/source-control/status-read-coalescing.test.ts": 258, - "src/main/git/source-control/status-read-failure-real-git.test.ts": 307, - "src/main/git/source-control/status-shared-symlinks.test.ts": 746, - "src/main/git/source-control/status-submodule.test.ts": 306, - "src/main/git/source-control/status-upstream-ref.test.ts": 52, - "src/main/git/source-control/upstream-deferred-fork-remote-real.test.ts": 319, - "src/main/git/source-control/upstream.test.ts": 406, + "src/main/git/source-control/status/status-read-failure-real-git.test.ts": 307, + "src/main/git/source-control/status/status-shared-symlinks.test.ts": 746, + "src/main/git/source-control/submodules/status-submodule.test.ts": 306, + "src/main/git/source-control/upstream/status-upstream-ref.test.ts": 52, + "src/main/git/source-control/upstream/upstream-deferred-fork-remote-real.test.ts": 319, "src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts": 362, "src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts": 346, "src/main/git/worktrees/creation/worktree-add-remote-branch-upstream-real-git.test.ts": 786, @@ -1945,11 +1863,8 @@ "src/main/hermes/hermes-config-source-edits.test.ts": 280, "src/main/hermes/hermes-windows-home.test.ts": 121, "src/main/hermes/hook-service.test.ts": 589, - "src/main/workspace-hooks/hook-archive-timeout-observation.test.ts": 1103, "src/main/workspace-hooks/hook-termination-real-process.test.ts": 3284, "src/main/workspace-hooks/hooks-archive-exit-observation.test.ts": 339, - "src/main/workspace-hooks/hooks-orca-yaml-unc-drive.test.ts": 402, - "src/main/workspace-hooks/hooks-runner.test.ts": 314, "src/main/filesystem/host-checkout-removal.test.ts": 52, "src/main/filesystem/host-tree-removal-asar.electron.test.ts": 308, "src/main/host/deferred-secret-protection-report.test.ts": 81, @@ -1959,7 +1874,7 @@ "src/main/host/secret-protection-report.test.ts": 59, "src/main/i18n/main-i18n-lazy-locale.test.ts": 518, "src/main/i18n/system-language.test.ts": 358, - "src/main/media/image-file-signature.test.ts": 47, + "src/shared/image-file-signature.test.ts": 47, "src/main/credentials/integration-state-file-cache.test.ts": 47, "src/main/credentials/integration-token-file-cache.test.ts": 152, "src/main/ipc/account-sign-in-link-opener.test.ts": 128, @@ -2066,7 +1981,6 @@ "src/main/ipc/markdown-documents-ripgrep.test.ts": 289, "src/main/ipc/mobile.test.ts": 1861, "src/main/ipc/notebook-project-link.test.ts": 548, - "src/main/ipc/notifications-custom-sound.test.ts": 289, "src/main/ipc/notifications-message-formatting.test.ts": 229, "src/main/ipc/notifications-subject-retirement.test.ts": 304, "src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts": 2761, @@ -2093,7 +2007,6 @@ "src/main/ipc/pty/managed-data-account-spawn-environment.test.ts": 1150, "src/main/ipc/pty/pane/pane-owner-replacement.test.ts": 1960, "src/main/ipc/pty/pane/serializer-document-lifetime.test.ts": 77, - "src/main/ipc/pty/pane/spawn-registration.test.ts": 935, "src/main/ipc/pty/pane/stable-pane-absence-death-certificate.test.ts": 4555, "src/main/ipc/pty/pane/terminal-spawn-restore.test.ts": 60, "src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts": 4313, @@ -2109,7 +2022,6 @@ "src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts": 4680, "src/main/ipc/pty/pty-ssh-stop-verdict.test.ts": 3615, "src/main/ipc/pty/pty-write-ipc-validation.test.ts": 5157, - "src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts": 3784, "src/main/ipc/pty/runtime/spawn-preflight-wsl-background-hold.test.ts": 1568, "src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch-noise.test.ts": 317, "src/main/ipc/worktrees/removal/registered-worktree-root-ownership.test.ts": 498, @@ -2123,7 +2035,6 @@ "src/main/ipc/repos-execution-host-catalog.test.ts": 1426, "src/main/ipc/repos-nested-import.test.ts": 1299, "src/main/ipc/repos-nested-scan.test.ts": 1236, - "src/main/ipc/repos-remote-client-events.test.ts": 1914, "src/main/ipc/repos/folder-workspace-attachment-handlers.test.ts": 1932, "src/main/ipc/repos/local-repo-registration.test.ts": 469, "src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts": 2529, @@ -2186,12 +2097,9 @@ "src/main/git/remotes/worktree-push-target-setup.test.ts": 491, "src/main/ipc/worktree-symlink-reconciliation.real.test.ts": 410, "src/main/ipc/worktree-symlinks.test.ts": 152, - "src/main/ipc/worktrees-delete-pty-teardown.test.ts": 1934, - "src/main/ipc/worktrees-issue-command-overrides.test.ts": 1594, "src/main/ipc/worktrees-orphan-directory-cleanup.test.ts": 1486, "src/main/ipc/worktrees-removal-recovery.test.ts": 1971, "src/main/ipc/worktrees-remove-preflight.test.ts": 1415, - "src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts": 1447, "src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts": 650, "src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts": 105, "src/main/ipc/worktrees/listing/detected-worktree-scan-listing-distro.test.ts": 880, @@ -2201,7 +2109,6 @@ "src/main/ipc/wsl/wsl-host-automation-wake-launch.test.ts": 939, "src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts": 772, "src/main/ipc/wsl/wsl-host-visible-work-windows.test.ts": 39, - "src/main/ipc/wsl/wsl-move-driver-handlers.test.ts": 432, "src/main/ipc/wsl/wsl-move-handlers-setting-off.test.ts": 724, "src/main/ipc/wsl/wsl-move-host-connect.test.ts": 984, "src/main/ipc/wsl/wsl-move-partial-undo.test.ts": 939, @@ -2317,7 +2224,7 @@ "src/main/native-chat/agent-session-attachments/agent-session-attachment-claims.test.ts": 971, "src/main/native-chat/agent-session-attachments/agent-session-attachment-store.test.ts": 340, "src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts": 948, - "src/main/native-chat/agent-session-context-snapshots.test.ts": 65, + "src/main/native-chat/conversation-context/agent-session-context-snapshots.test.ts": 65, "src/main/native-chat/agent-session-journal/history-import/adopted-directory-probe.test.ts": 153, "src/main/native-chat/agent-session-journal/database/journal-checkpoint-attachment-sweep.test.ts": 8790, "src/main/native-chat/agent-session-journal/history-import/journal-codex-history.test.ts": 786, @@ -2431,37 +2338,37 @@ "src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command-child-work.test.ts": 1810, "src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command.test.ts": 2989, "src/main/native-chat/agent-session-wire/rewind/testing/structured-rewind-cut.test.ts": 672, - "src/main/native-chat/host-readable-transcript-path.test.ts": 150, + "src/main/native-chat/transcript-discovery/host-readable-transcript-path.test.ts": 150, "src/main/native-chat/native-chat-inline-visuals-setting.test.ts": 751, - "src/main/native-chat/native-chat-scratch-folder-migration.test.ts": 109, - "src/main/native-chat/native-chat-visual-file-read.test.ts": 98, - "src/main/native-chat/native-chat-visuals-sweep.test.ts": 123, + "src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.test.ts": 109, + "src/main/native-chat/conversation-files/native-chat-visual-file-read.test.ts": 98, + "src/main/native-chat/conversation-files/native-chat-visuals-sweep.test.ts": 123, "src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts": 156, "src/main/native-chat/session-file-resolver.test.ts": 245, - "src/main/native-chat/structured-agent-command-resolution.test.ts": 223, - "src/main/native-chat/structured-agent-configured-args.test.ts": 191, - "src/main/native-chat/transcript-claude-read-image.test.ts": 389, - "src/main/native-chat/transcript-file-version.test.ts": 121, + "src/main/native-chat/agent-launch/structured-agent-command-resolution.test.ts": 223, + "src/main/native-chat/agent-launch/structured-agent-configured-args.test.ts": 191, + "src/shared/native-chat/tools/native-chat-tool-viewed-images-shell-read.test.ts": 389, + "src/main/native-chat/transcript-watching/transcript-file-version.test.ts": 121, "src/main/native-chat/transcript-interruption-message.test.ts": 263, "src/main/native-chat/transcript-line-decoders-claude-command-output.test.ts": 248, - "src/main/native-chat/transcript-line-decoders-claude-control-bytes.test.ts": 237, - "src/main/native-chat/transcript-line-decoders-claude-image-companion.test.ts": 238, - "src/main/native-chat/transcript-line-decoders-claude-queued-prompt.test.ts": 255, + "src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-control-bytes.test.ts": 237, + "src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-image-companion.test.ts": 238, + "src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-queued-prompt.test.ts": 255, "src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts": 211, - "src/main/native-chat/transcript-line-decoders.grok.test.ts": 283, - "src/main/native-chat/transcript-line-decoders.omp.test.ts": 297, - "src/main/native-chat/transcript-opencode-sqlite-query.test.ts": 886, + "src/main/native-chat/transcript-decoding/transcript-line-decoders.grok.test.ts": 283, + "src/main/native-chat/transcript-decoding/transcript-line-decoders.omp.test.ts": 297, + "src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.test.ts": 886, "src/main/native-chat/transcript-read-cache.test.ts": 513, "src/main/native-chat/transcript-reader.test.ts": 565, - "src/main/native-chat/transcript-stream-lines.test.ts": 79, - "src/main/native-chat/transcript-turn-lifecycle.test.ts": 258, + "src/main/native-chat/transcript-streaming/transcript-stream-lines.test.ts": 79, + "src/main/native-chat/transcript-decoding/transcript-turn-lifecycle.test.ts": 258, "src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts": 508, "src/main/native-chat/transcript-watch-error.test.ts": 2306, "src/main/native-chat/transcript-watch-unflushed-settle.test.ts": 554, "src/main/native-chat/transcript-window-tool-attribution.test.ts": 523, - "src/main/native-chat/transcript-zcode.test.ts": 814, - "src/main/native-chat/wsl-transcript-fs-process-operations.test.ts": 43, - "src/main/native-chat/wsl-transcript-running-admission.test.ts": 1178, + "src/main/native-chat/transcript-history/opencode/transcript-zcode.test.ts": 814, + "src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-operations.test.ts": 43, + "src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.test.ts": 1178, "src/main/native-chat/wsl-transcript-running-observer.test.ts": 103, "src/main/workspaces/removal/nested-worktree-removal-plan.test.ts": 242, "src/main/node-runtime/managed-runtime-installation.test.ts": 427, @@ -2495,46 +2402,40 @@ "src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts": 1642, "src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts": 1456, "src/main/orca-profiles/profile-telemetry-consent-seed.test.ts": 536, - "src/main/orcad/electron-serve-provider-selection.test.ts": 554, - "src/main/orcad/electron-sidecar-tab-registry.test.ts": 105, - "src/main/orcad/external-chromium-browser-session.test.ts": 152, - "src/main/orcad/node-pty-prebuilt-slot.test.ts": 185, - "src/main/orcad/node-pty-precondition.test.ts": 477, - "src/main/orcad/orcad-agent-session-claim-signer.test.ts": 64, - "src/main/orcad/orcad-app-paths.test.ts": 45, - "src/main/orcad/orcad-artifact-cache-retention.test.ts": 301, - "src/main/orcad/orcad-artifact-materializer.test.ts": 1129, + "src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts": 105, + "src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts": 152, + "src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts": 185, + "src/main/orcad/native-runtime/node-pty-precondition.test.ts": 477, + "src/main/orcad/host-runtime/orcad-app-paths.test.ts": 45, + "src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts": 301, + "src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts": 1129, "src/main/orcad/orcad-bind-address.test.ts": 41, - "src/main/orcad/orcad-browser-install-park.test.ts": 131, - "src/main/orcad/orcad-browser-provider.test.ts": 479, - "src/main/orcad/orcad-bundle-native-load-order.test.ts": 3555, - "src/main/orcad/orcad-chat-restart-offer.test.ts": 3691, - "src/main/orcad/orcad-cli-launcher.integration.test.ts": 390, - "src/main/orcad/orcad-cli-launcher.test.ts": 232, + "src/main/orcad/browser-providers/orcad-browser-provider.test.ts": 479, + "src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts": 3555, + "src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts": 390, + "src/main/orcad/serve-startup/orcad-cli-launcher.test.ts": 232, "src/main/orcad/orcad-cli-orchestration.integration.test.ts": 214, - "src/main/orcad/orcad-forked-child-paths.test.ts": 337, - "src/main/orcad/orcad-help.integration.test.ts": 5016, - "src/main/orcad/orcad-idle-exit-monitor.test.ts": 106, - "src/main/orcad/orcad-instance-lock.test.ts": 315, - "src/main/orcad/orcad-launcher-isolation.integration.test.ts": 617, - "src/main/orcad/orcad-lifecycle-host.test.ts": 407, - "src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts": 2062, - "src/main/orcad/orcad-managed-idle-exit.test.ts": 180, - "src/main/orcad/orcad-managed-stop-cancel-race.test.ts": 218, - "src/main/orcad/orcad-managed-stop-cancellation.test.ts": 285, - "src/main/orcad/orcad-managed-stop-identity.test.ts": 270, - "src/main/orcad/orcad-managed-stop.test.ts": 1726, - "src/main/orcad/orcad-observability.test.ts": 187, - "src/main/orcad/orcad-packaged-node-pty.integration.test.ts": 78, - "src/main/orcad/orcad-packaged-structured-chat.integration.test.ts": 448, - "src/main/orcad/orcad-plaintext-credential-migration.test.ts": 223, - "src/main/orcad/orcad-process-start-time.test.ts": 77, - "src/main/orcad/orcad-secret-store.test.ts": 2281, - "src/main/orcad/orcad-serve-parity.integration.test.ts": 280, - "src/main/orcad/orcad-stale-lock-reclaim.test.ts": 258, - "src/main/orcad/orcad-startup-qualification.test.ts": 102, - "src/main/orcad/orcad-stop-request-shutdown.integration.test.ts": 293, - "src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts": 79, + "src/main/orcad/serve-startup/orcad-help.integration.test.ts": 5016, + "src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts": 106, + "src/main/orcad/instance-lock/orcad-instance-lock.test.ts": 315, + "src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts": 617, + "src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts": 407, + "src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts": 180, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts": 218, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts": 285, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts": 270, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts": 1726, + "src/main/orcad/diagnostics/orcad-observability.test.ts": 187, + "src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts": 78, + "src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts": 448, + "src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts": 223, + "src/main/orcad/instance-lock/orcad-process-start-time.test.ts": 77, + "src/main/orcad/credentials/orcad-secret-store.test.ts": 2281, + "src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts": 280, + "src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts": 258, + "src/main/orcad/runtime-launch/orcad-startup-qualification.test.ts": 102, + "src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts": 293, + "src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts": 79, "src/main/persistence/preferences/persistence-onboarding-language-cohort.test.ts": 1760, "src/main/persistence/applying-settings/persistence-automation-extra-agent-args.test.ts": 2268, "src/main/persistence/applying-settings/persistence-automation-mode-precondition.test.ts": 1595, @@ -2561,7 +2462,6 @@ "src/main/persistence/loading-store/terminal-bindings/reused-terminal-id-unbind.test.ts": 312, "src/main/persistence/loading-store/profile-writing/state-write-round-trip.test.ts": 1983, "src/main/persistence/loading-store/workspace-sessions/store-host-partition-before-unload.test.ts": 1670, - "src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts": 5719, "src/main/persistence/loading-store/workspace-sessions/workspace-session-terminal-binding-replay.test.ts": 95, "src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.test.ts": 127, "src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-staging.test.ts": 466, @@ -2630,44 +2530,39 @@ "src/main/persistence/restoring-sessions/workspace-pane-normalization-index.test.ts": 466, "src/main/persistence/runtime-authored-workspace-session-fields.test.ts": 64, "src/main/persistence/scheduling-automations/automation-run-operations.test.ts": 151, - "src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts": 289, - "src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts": 2087, - "src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts": 526, - "src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts": 1943, - "src/main/persistence/terminal-topology/pane-last-grid.test.ts": 5642, - "src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts": 1926, - "src/main/persistence/terminal-topology/persistence-cross-host-pane-identity.test.ts": 1744, - "src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts": 1841, - "src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts": 1835, - "src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts": 1961, - "src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts": 5772, - "src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts": 1996, - "src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts": 1898, - "src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts": 2143, - "src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts": 1790, - "src/main/persistence/terminal-topology/persistence-ssh-pending-pty-kill.test.ts": 1776, - "src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts": 1738, - "src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts": 1853, - "src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts": 2079, - "src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts": 1795, - "src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts": 2870, - "src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts": 2027, - "src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts": 1808, + "src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts": 2087, + "src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts": 526, + "src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts": 1943, + "src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts": 5642, + "src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts": 1926, + "src/main/persistence/restoring-sessions/persistence-cross-host-pane-identity.test.ts": 1744, + "src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts": 1841, + "src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts": 1835, + "src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts": 5772, + "src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts": 1996, + "src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts": 1898, + "src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts": 2143, + "src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts": 1790, + "src/main/persistence/leasing-ssh-ptys/persistence-ssh-pending-pty-kill.test.ts": 1776, + "src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts": 1853, + "src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts": 2079, + "src/main/persistence/restoring-sessions/persistence-tab-terminal-pane-binding-load.test.ts": 1795, + "src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts": 2870, + "src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts": 2027, "src/main/persistence/terminal-topology/terminal-layout-apply.test.ts": 2005, - "src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts": 1773, - "src/main/persistence/terminal-topology/terminal-layout-create.test.ts": 2107, - "src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts": 1753, - "src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts": 1977, - "src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts": 2198, - "src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts": 1847, - "src/main/persistence/terminal-topology/terminal-leaf-move.test.ts": 2197, - "src/main/persistence/terminal-topology/terminal-owner-invariants.test.ts": 285, - "src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts": 1796, - "src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts": 1766, - "src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts": 1941, - "src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts": 2114, - "src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts": 1872, - "src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts": 1626, + "src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts": 1773, + "src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts": 2107, + "src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts": 1753, + "src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts": 1977, + "src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts": 2198, + "src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts": 1847, + "src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts": 2197, + "src/shared/workspace-layout/terminal-topology/terminal-owner-invariants.test.ts": 285, + "src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts": 1796, + "src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts": 1766, + "src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts": 1941, + "src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts": 2114, + "src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts": 1626, "src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts": 544, "src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts": 619, "src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts": 2374, @@ -2691,7 +2586,6 @@ "src/main/persistence/tracking-repos/repo-update-host-guard.test.ts": 478, "src/main/persistence/tracking-repos/worktree-identity-migration-field-coverage.test.ts": 505, "src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts": 372, - "src/main/persistence/window-save-reconnect-facts.test.ts": 372, "src/main/persistence/window-save-sleep-records.test.ts": 60, "src/main/pi/managed-extensions/agent-status/agent-status-completion-delivery.test.ts": 423, "src/main/pi/managed-extensions/agent-status/agent-status-extension-nested-run-settlement.test.ts": 335, @@ -2715,7 +2609,6 @@ "src/main/plugins/catalog/plugin-update-review-notices.test.ts": 175, "src/main/plugins/contributions/plugin-content-pack-registry.test.ts": 589, "src/main/plugins/contributions/plugin-icon-theme-registry.test.ts": 268, - "src/main/plugins/contributions/plugin-language-pack-registry.test.ts": 587, "src/main/plugins/contributions/plugin-syntax-registry.test.ts": 221, "src/main/plugins/contributions/plugin-theme-registries.test.ts": 250, "src/main/plugins/hooks/plugin-agent-hook-sites.test.ts": 279, @@ -2818,31 +2711,16 @@ "src/main/provider-process/provider-process-row-read.test.ts": 87, "src/main/provider-process/provider-process-supervisor.integration.test.ts": 7485, "src/main/provider-process/provider-process-teardown.test.ts": 146, - "src/main/providers/agent-foreground-process-git-bash.win32.test.ts": 361, - "src/main/providers/agent-foreground-process.test.ts": 227, - "src/main/providers/local-filesystem-provider.test.ts": 344, - "src/main/providers/local-pty/local-pty-child-process-verdict.test.ts": 676, - "src/main/providers/local-pty/local-pty-default-shell.test.ts": 272, - "src/main/providers/local-pty/local-pty-executable-spawn.test.ts": 96, - "src/main/providers/local-pty/local-pty-foreground-inspection-cheap-tier.test.ts": 266, - "src/main/providers/local-pty/local-pty-provider-foreground-process.test.ts": 520, + "src/main/daemon/pty-subprocess/testing/agent-foreground-process-git-bash.win32.test.ts": 361, "src/main/providers/local-pty/local-pty-provider-shutdown.test.ts": 731, "src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts": 856, - "src/main/providers/local-pty/local-pty-provider-windows-shell-launch.test.ts": 598, "src/main/providers/local-pty/local-pty-runtime-spawn-wsl-allowlist.test.ts": 85, "src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts": 42, "src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts": 54, "src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts": 558, "src/main/providers/local-pty/local-pty-shell-startup-command.node-pty.test.ts": 315, - "src/main/providers/macos-tcc-login-shell.test.ts": 182, - "src/main/providers/pty-process-list-admission.test.ts": 138, - "src/main/providers/startup-line-typed-length.live-shell.test.ts": 316, - "src/main/providers/terminal-path-existence-batch.integration.test.ts": 337, - "src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts": 73, - "src/main/providers/windows-powershell-executable.test.ts": 65, - "src/main/providers/windows-shell-preflight-runtime.windows.test.ts": 126, - "src/main/providers/working-directory-validation-retention.test.ts": 132, - "src/main/providers/working-directory-validation.test.ts": 163, + "src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts": 126, + "src/main/providers/working-directory/validation.test.ts": 163, "src/main/workspaces/catalog/provisioned-root-checkout.test.ts": 115, "src/main/pty/process-retirement/pty-descendant-exit-verification.test.ts": 155, "src/main/pty/process-retirement/pty-descendant-termination-libproc.test.ts": 135, @@ -3026,11 +2904,9 @@ "src/main/runtime/session-graph/graph-sync-deletion-fence.test.ts": 4552, "src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts": 4333, "src/main/runtime/terminal/surface/headless-create-terminal-handle-main.test.ts": 3873, - "src/main/runtime/session-tabs/headless-move-leaf-to-new-tab.test.ts": 3596, "src/main/runtime/terminal/output/headless-terminal-dispose-write-ordering.test.ts": 4309, "src/main/runtime/terminal/recovery/held-pane-reopen-layout-owner.test.ts": 5093, "src/main/runtime/terminal/wait/hermes-slash-readiness-transcript.test.ts": 4931, - "src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts": 9614, "src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts": 68, "src/main/runtime/hosts/platform-probe/host-descriptor.test.ts": 207, "src/main/runtime/terminal/surface/host-pane-remount-terminal-handle.test.ts": 5293, @@ -3045,20 +2921,17 @@ "src/main/runtime/integrations/linear/linear-save-markdown.test.ts": 930, "src/main/runtime/workspaces/creation/managed-worktree-create-registry.test.ts": 4143, "src/main/runtime/workspaces/creation/managed-worktree-create-telemetry.test.ts": 4152, - "src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.test.ts": 432, - "src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts": 48, - "src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts": 408, - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts": 580, - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts": 161, - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts": 1013, - "src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts": 701, + "src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts": 48, + "src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts": 408, + "src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts": 580, + "src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts": 1013, + "src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts": 701, "src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts": 147, - "src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts": 122, - "src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts": 175, - "src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts": 196, - "src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts": 253, - "src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts": 127, - "src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts": 73, + "src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts": 122, + "src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts": 175, + "src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts": 196, + "src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts": 253, + "src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts": 73, "src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts": 804, "src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.integration.test.ts": 11377, "src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.test.ts": 1185, @@ -3071,7 +2944,6 @@ "src/main/runtime/push/notifications/mobile-notification-replay.test.ts": 43, "src/main/runtime/rpc/server/pairing/mobile-pairing-userdata-path.test.ts": 171, "src/main/runtime/terminal/layout/mobile-presence-lock.test.ts": 25928, - "src/main/runtime/terminal/lifecycle/mobile-session-dead-pty.test.ts": 4708, "src/main/runtime/session-tabs/headless-editor-tabs.test.ts": 57, "src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts": 65, "src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts": 278, @@ -3086,14 +2958,10 @@ "src/main/runtime/browser/client-pages/orca-runtime-browser-ghost-session-row-close.test.ts": 640, "src/main/runtime/browser/screencast/orca-runtime-browser-screencast-e2ee-backlog.test.ts": 659, "src/main/runtime/browser/screencast/orca-runtime-browser-screencast-fanout.test.ts": 607, - "src/main/runtime/browser/screencast/orca-runtime-browser-screencast-pending-frame-retry.test.ts": 595, "src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts": 682, "src/main/runtime/terminal/query/orca-runtime-codex-idle-title-chat-address.test.ts": 5781, - "src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts": 4130, - "src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts": 3716, "src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts": 3617, "src/main/runtime/terminal/lifecycle/orca-runtime-exited-split-pane-close.test.ts": 4235, - "src/main/runtime/terminal/surface/orca-runtime-failed-start-pane-layout-owner.test.ts": 4204, "src/main/runtime/files/orca-runtime-files-preview-budget.test.ts": 672, "src/main/runtime/files/search/orca-runtime-files-search.test.ts": 675, "src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts": 580, @@ -3130,7 +2998,6 @@ "src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts": 14953, "src/main/runtime/orchestration/mailbox/notifications/orchestration-message-delivery-identity.test.ts": 25822, "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-messages-fake-parity.test.ts": 510, - "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts": 5567, "src/main/runtime/orchestration/workers/turn-stops/chat-worker-request-failures.test.ts": 4099, "src/main/runtime/orchestration/workers/launch/codex-reconnect-failed-dispatch.test.ts": 6396, "src/main/runtime/orchestration/coordinator/decision-gates/coordinator-decision-gates.test.ts": 567, @@ -3229,7 +3096,6 @@ "src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts": 7843, "src/main/runtime/repositories/project-group-folder-workspace-selectors.test.ts": 3915, "src/main/runtime/terminal/stop/project-removal-terminal-stop.test.ts": 5247, - "src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-admission.test.ts": 4395, "src/main/runtime/terminal/query/pty-shell-ownership-mirror.test.ts": 860, "src/main/runtime/push/desktop-push-service-unreadable-outbox.test.ts": 265, "src/main/runtime/push/desktop-push-service.test.ts": 317, @@ -3273,7 +3139,6 @@ "src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts": 204, "src/main/runtime/rpc/e2ee-channel-v2.test.ts": 287, "src/main/runtime/rpc/e2ee-channel.test.ts": 539, - "src/main/runtime/rpc/e2ee-crypto.test.ts": 121, "src/main/runtime/rpc/methods/accounts/accounts.test.ts": 161, "src/main/runtime/rpc/methods/agent-launch/agent-launch-at-rest.test.ts": 4936, "src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.test.ts": 1680, @@ -3359,32 +3224,31 @@ "src/main/runtime/rpc/methods/orchestration/runs/runs.test.ts": 4589, "src/main/runtime/rpc/methods/orchestration/runs/tasks-dispatch.test.ts": 4854, "src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts": 7003, - "src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts": 4775, - "src/main/runtime/rpc/methods/orchestration/worker/failed-start-retry-release.test.ts": 5044, - "src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts": 3493, + "src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts": 4775, + "src/main/runtime/rpc/methods/orchestration/worker/start/failed-start-retry-release.test.ts": 5044, + "src/main/runtime/rpc/methods/orchestration/worker/observation/fleet-status-observed-identity.test.ts": 3493, "src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-cli.integration.test.ts": 7626, - "src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-ownership-cli.integration.test.ts": 8091, - "src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts": 5272, - "src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts": 5196, - "src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release-turns.test.ts": 3578, - "src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts": 4863, - "src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts": 4916, - "src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts": 5579, - "src/main/runtime/rpc/methods/orchestration/worker/worker-list-pagination.test.ts": 4740, - "src/main/runtime/rpc/methods/orchestration/worker/worker-output.test.ts": 541, - "src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts": 3949, - "src/main/runtime/rpc/methods/orchestration/worker/worker-release-evidence-contracts.test.ts": 4491, - "src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts": 4562, - "src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts": 5889, - "src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts": 4766, - "src/main/runtime/rpc/methods/orchestration/worker/worker-run-dispatch-contracts.test.ts": 5136, + "src/main/runtime/rpc/methods/orchestration/worker/follow-up/helper-follow-up-ownership-cli.integration.test.ts": 8091, + "src/main/runtime/rpc/methods/orchestration/worker/observation/manual-dispatch-observation.test.ts": 5272, + "src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts": 5196, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts": 3578, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release.test.ts": 4863, + "src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up.test.ts": 4916, + "src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-pagination.test.ts": 4740, + "src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts": 541, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-authority-contracts.test.ts": 3949, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-evidence-contracts.test.ts": 4491, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts": 4562, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts": 5889, + "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts": 4766, + "src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts": 5136, "src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts": 45, - "src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts": 6279, - "src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts": 4508, - "src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts": 5279, - "src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts": 5687, - "src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts": 6117, - "src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts": 5182, + "src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts": 6279, + "src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts": 4508, + "src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-liveness-verdict.test.ts": 5279, + "src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-terminal-custody-at-creation.test.ts": 5687, + "src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-new-worktree-start.test.ts": 6117, + "src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts": 5182, "src/main/runtime/rpc/methods/plugins/plugin-dev-emit.test.ts": 3118, "src/main/runtime/rpc/methods/plugins/plugin-dev-request.test.ts": 3725, "src/main/runtime/rpc/methods/plugins/plugins.test.ts": 274, @@ -3431,7 +3295,6 @@ "src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.test.ts": 75, "src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.test.ts": 98, "src/main/runtime/rpc/mobile-socket-wiring.test.ts": 312, - "src/main/runtime/rpc/orcad-feature-readiness.test.ts": 40, "src/main/runtime/rpc/orchestration-11745-regression-verification.test.ts": 22874, "src/main/runtime/rpc/orchestration-check-wait-session.test.ts": 5096, "src/main/runtime/rpc/orchestration-commit-notify-characterization.test.ts": 5702, @@ -3461,7 +3324,6 @@ "src/main/runtime/rpc/remote-runtime-server-heartbeat-missed-probe-tolerance.test.ts": 59, "src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts": 60, "src/main/runtime/rpc/repo-add-cli.integration.test.ts": 1603, - "src/main/runtime/rpc/runtime-client-capabilities.test.ts": 43, "src/main/runtime/rpc/runtime-source-admission.test.ts": 909, "src/main/runtime/rpc/shadowed-port-probe.test.ts": 99, "src/main/runtime/rpc/static-web-client-handler-stream.test.ts": 1823, @@ -3506,7 +3368,6 @@ "src/main/runtime/rpc/unix-socket-transport.test.ts": 79, "src/main/runtime/rpc/unpaired-device-auth-throttle.test.ts": 42, "src/main/runtime/rpc/web-session-pairing.test.ts": 402, - "src/main/runtime/rpc/workspace-creator-context.test.ts": 40, "src/main/runtime/rpc/worktree-removal-marker-projection.test.ts": 497, "src/main/runtime/rpc/worktree-rm-cli.integration.test.ts": 6876, "src/main/runtime/rpc/ws-empty-payload-frame-write.test.ts": 117, @@ -3561,7 +3422,6 @@ "src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts": 4402, "src/main/runtime/rpc/server/runtime-rpc-delegated-device-sync.test.ts": 4986, "src/main/runtime/rpc/server/runtime-rpc-device-key-dispatch.test.ts": 3597, - "src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts": 5350, "src/main/runtime/rpc/server/runtime-rpc-local-disconnect-forwarding.test.ts": 5138, "src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts": 30838, "src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts": 4652, @@ -3594,14 +3454,11 @@ "src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.test.ts": 1027, "src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts": 289, "src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts": 1412, - "src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts": 321, - "src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts": 5010, "src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.test.ts": 4514, "src/main/runtime/session-lifecycle/projection/pane-sleeping-record.test.ts": 76, "src/main/runtime/session-lifecycle/projection/sleep-record-pane-claim.test.ts": 48, "src/main/runtime/session-tabs/session-tab-close-force.test.ts": 7089, "src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts": 5775, - "src/main/runtime/session-tabs/headless-mobile-session-absorbed-rows.test.ts": 4223, "src/main/runtime/session-tabs/main-layout-session-tab-move.test.ts": 4233, "src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts": 4888, "src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts": 4320, @@ -3611,30 +3468,30 @@ "src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts": 4444, "src/main/runtime/orchestration/terminal-authority/settled-worker-process-replacement.test.ts": 5013, "src/main/runtime/sidebar-inputs/cached-scan.test.ts": 106, - "src/main/runtime/sidebar-inputs/desktop-sidebar-facts.test.ts": 378, - "src/main/runtime/sidebar-inputs/orca-runtime-closed-tab-retention.test.ts": 5233, - "src/main/runtime/sidebar-inputs/orca-runtime-project-catalog.test.ts": 4975, + "src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.test.ts": 378, + "src/main/runtime/sidebar-inputs/temporal/orca-runtime-closed-tab-retention.test.ts": 5233, + "src/main/runtime/sidebar-inputs/catalog/orca-runtime-project-catalog.test.ts": 4975, "src/main/runtime/sidebar-inputs/orca-runtime-sidebar-inputs-feed.test.ts": 3968, - "src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts": 3799, - "src/main/runtime/sidebar-inputs/orca-runtime-terminal-use.test.ts": 4460, - "src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts": 3633, - "src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts": 4608, - "src/main/runtime/sidebar-inputs/paired-server-rows-producer.test.ts": 340, - "src/main/runtime/sidebar-inputs/repo-icon-data-urls.test.ts": 250, + "src/main/runtime/sidebar-inputs/temporal/orca-runtime-sort-stamps.test.ts": 3799, + "src/main/runtime/sidebar-inputs/temporal/orca-runtime-terminal-use.test.ts": 4460, + "src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.test.ts": 3633, + "src/main/runtime/sidebar-inputs/temporal/orca-runtime-workspace-unread.test.ts": 4608, + "src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.test.ts": 340, + "src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.test.ts": 250, "src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.test.ts": 101, "src/main/runtime/sidebar-inputs/sidebar-clock.test.ts": 45, "src/main/runtime/sidebar-inputs/sidebar-inputs-feed-announcements.test.ts": 1954, "src/main/runtime/sidebar-inputs/sidebar-inputs-feed-domains.test.ts": 496, - "src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.test.ts": 162, - "src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test.ts": 387, - "src/main/runtime/sidebar-inputs/sidebar-project-catalog.test.ts": 416, - "src/main/runtime/sidebar-inputs/sidebar-retention-owner.test.ts": 77, - "src/main/runtime/sidebar-inputs/sort-stamp-records-twins.test.ts": 246, - "src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts": 813, - "src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts": 696, - "src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts": 50, - "src/main/runtime/sidebar-inputs/workspace-rows-producer.test.ts": 4181, - "src/main/runtime/sidebar-inputs/workspace-viewers.test.ts": 65, + "src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.test.ts": 162, + "src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.test.ts": 387, + "src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.test.ts": 416, + "src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.test.ts": 77, + "src/main/runtime/workspaces/metadata/workspace-activity-records-twins.test.ts": 246, + "src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.test.ts": 813, + "src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.test.ts": 696, + "src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.test.ts": 50, + "src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.test.ts": 4181, + "src/main/runtime/sidebar-inputs/temporal/workspace-viewers.test.ts": 65, "src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts": 4456, "src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts": 140, "src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts": 5020, @@ -3677,7 +3534,6 @@ "src/main/runtime/terminal/output/terminal-restore-record-seed.test.ts": 4073, "src/main/runtime/session-tabs/terminal-retirement-async-durability.test.ts": 5903, "src/main/runtime/terminal/surface/terminal-retirement-proof-publication.test.ts": 4976, - "src/main/runtime/terminal/lifecycle/terminal-run-facts-input.test.ts": 4370, "src/main/runtime/terminal/lifecycle/terminal-run-facts.test.ts": 68, "src/main/runtime/terminal/view/terminal-screen-row-metadata.test.ts": 175, "src/main/runtime/terminal/wait/terminal-start-failure-readiness.test.ts": 3416, @@ -3685,7 +3541,6 @@ "src/main/runtime/terminal/output/tail/terminal-tail-redraw-spans.test.ts": 166, "src/main/runtime/terminal-tail-redraw-wall-time.test.ts": 43418, "src/main/runtime/terminal/output/tail/terminal-tail-sentinel-index.test.ts": 3649, - "src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts": 4182, "src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts": 168, "src/main/runtime/terminal/wait/terminal-wait-detection.test.ts": 220, "src/main/runtime/terminal/wait/terminal-wait-name-only-idle.test.ts": 5018, @@ -3698,8 +3553,6 @@ "src/main/runtime/terminal/input/agent-prompt-permission-hold.test.ts": 48, "src/main/runtime/terminal/input/terminal-send-plugin-hook.test.ts": 169, "src/main/runtime/terminal/launch/mobile-terminal-chat-fork.test.ts": 3900, - "src/main/runtime/terminal/launch/terminal-split-layout-owner.test.ts": 4503, - "src/main/runtime/terminal/launch/terminal-split-retry.test.ts": 4038, "src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts": 5572, "src/main/runtime/terminal/lifecycle/main-pane-liveness.test.ts": 4871, "src/main/runtime/terminal/lifecycle/ssh-exit-code-pane-outcome.test.ts": 4334, @@ -3708,7 +3561,6 @@ "src/main/runtime/terminal/stop/exact-terminal-stop-liveness.test.ts": 4321, "src/main/runtime/terminal/stop/terminal-update-admission.test.ts": 48, "src/main/runtime/terminal/surface/closed-pane-exit-cleanup-main.test.ts": 4281, - "src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts": 4330, "src/main/runtime/terminal/surface/terminal-surface-replies-main.test.ts": 4324, "src/main/runtime/terminal/wait/tui-idle-codex-plan-menu.test.ts": 4441, "src/main/runtime/terminal/wait/tui-idle-command-paint.test.ts": 4148, @@ -3723,8 +3575,6 @@ "src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts": 2136, "src/main/runtime/terminal/surface/workspace-layout-stream.test.ts": 427, "src/main/runtime/terminal/surface/workspace-session-membership-scaling.test.ts": 72, - "src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts": 6111, - "src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts": 12352, "src/main/runtime/workspaces/lifecycle/workspace-lifecycle-queue.test.ts": 116, "src/main/runtime/workspaces/sleep/workspace-sleep-execution.test.ts": 110, "src/main/runtime/workspaces/startup/worktree-agent-first-surface.test.ts": 5816, @@ -3843,7 +3693,6 @@ "src/main/managed-server/install/orcad-launch-ssh-session.test.ts": 689, "src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.test.ts": 1464, "src/main/managed-server/migration/catalog/orcad-migration-catalog-client-frame-budget.test.ts": 405, - "src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts": 400, "src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts": 400, "src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.test.ts": 2408, "src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts": 3812, @@ -3909,7 +3758,6 @@ "src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts": 283, "src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts": 177, "src/main/ssh/remote-host/ssh-remote-platform.test.ts": 51, - "src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts": 164, "src/main/ssh/authentication/ssh-security-key-identity.test.ts": 142, "src/main/ssh/system-transport/ssh-system-transport.integration.test.ts": 401, "src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts": 971, @@ -3946,7 +3794,6 @@ "src/main/startup/configure-process.test.ts": 255, "src/main/startup/e2e-external-open-guard.test.ts": 44, "src/main/startup/e2e-spawn-log-env.test.ts": 89, - "src/main/startup/ensure-virtual-display.test.ts": 135, "src/main/startup/first-window-startup-services.test.ts": 54, "src/main/startup/gpu-fallback-marker.test.ts": 61, "src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts": 641, @@ -4007,30 +3854,26 @@ "src/main/pty/history/terminal-history-gc-fs-call-count.test.ts": 157, "src/main/pty/history/terminal-history-gc.test.ts": 824, "src/main/pty/history/terminal-history-tombstone-retry.test.ts": 715, - "src/main/text-generation/agent-failure-output.test.ts": 49, - "src/main/text-generation/antigravity-generation-stream.test.ts": 479, - "src/main/text-generation/command-environment-process.test.ts": 1044, - "src/main/text-generation/commit-message-agent-environment.test.ts": 95, - "src/main/text-generation/commit-message-text-generation-branch-name.test.ts": 496, - "src/main/text-generation/commit-message-text-generation-cancellation.test.ts": 1171, - "src/main/text-generation/commit-message-text-generation-failure-sanitization.test.ts": 466, - "src/main/text-generation/commit-message-text-generation-generated-output.test.ts": 521, - "src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts": 480, - "src/main/text-generation/commit-message-text-generation-model-discovery.test.ts": 504, - "src/main/text-generation/commit-message-text-generation-regression.test.ts": 408, - "src/main/text-generation/commit-message-text-generation-remote-execution.test.ts": 469, - "src/main/text-generation/conversation-name-generation-request.test.ts": 507, - "src/main/text-generation/jira-issue-summary-requests.test.ts": 276, - "src/main/text-generation/kimi-generation-failure.test.ts": 151, - "src/main/text-generation/pull-request-context.test.ts": 97, - "src/main/text-generation/source-control-agent-cli-path.test.ts": 615, - "src/main/text-generation/source-control-agent-launch.test.ts": 1879, - "src/main/text-generation/source-control-local-process.test.ts": 1834, - "src/main/text-generation/source-control-omp-prompt-file.test.ts": 6676, - "src/main/text-generation/source-control-wsl-launch.test.ts": 482, - "src/main/text-generation/source-control-wsl-prompt.test.ts": 2440, + "src/main/text-generation/failures/agent-failure-output.test.ts": 49, + "src/main/text-generation/execution/command-environment-process.test.ts": 1044, + "src/main/text-generation/execution/commit-message-agent-environment.test.ts": 95, + "src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts": 496, + "src/main/text-generation/execution/commit-message-text-generation-cancellation.test.ts": 1171, + "src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts": 466, + "src/main/text-generation/requests/commit-message-text-generation-generated-output.test.ts": 521, + "src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts": 480, + "src/main/text-generation/models/commit-message-text-generation-model-discovery.test.ts": 504, + "src/main/text-generation/requests/commit-message-text-generation-regression.test.ts": 408, + "src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts": 469, + "src/main/text-generation/requests/conversation-name-generation-request.test.ts": 507, + "src/main/text-generation/requests/jira-issue-summary-requests.test.ts": 276, + "src/main/text-generation/failures/kimi-generation-failure.test.ts": 151, + "src/main/text-generation/execution/source-control-agent-cli-path.test.ts": 615, + "src/main/text-generation/execution/source-control-local-process.test.ts": 1834, + "src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts": 6676, + "src/main/text-generation/execution/source-control-wsl-launch.test.ts": 482, + "src/main/text-generation/prompts/source-control-wsl-prompt.test.ts": 2440, "src/main/tray/system-tray.test.ts": 556, - "src/main/tray/tray-attention-icon.test.ts": 52, "src/main/tray/tray-dev-badge.test.ts": 51, "src/main/updater/updater-events.test.ts": 280, "src/main/updater/updater-linux-package-recovery-actions.test.ts": 2294, @@ -4106,9 +3949,7 @@ "src/main/window/renderer-recovery-reload-watchdog.test.ts": 69, "src/main/window/runtime-renderer-notification-sender.test.ts": 54, "src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts": 100, - "src/main/window/runtime-window-pane-title-notification.test.ts": 97, "src/main/window/session-tab-close-request-relay.test.ts": 74, - "src/main/window/terminal-pane-reveal-relay.test.ts": 91, "src/main/window/terminal-tab-close-request-relay.test.ts": 64, "src/main/window/updater-package-recovery-ipc.test.ts": 169, "src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts": 76, @@ -4234,7 +4075,6 @@ "src/main/zcode/zcode-plan-api-key-store.test.ts": 89, "src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts": 259, "src/main/zcode/zcode-v2-plan-credentials.test.ts": 934, - "src/main/schema-validation/zod-schema-compilation.test.ts": 87, "src/packages/process-host/src/bounded-output-sink.test.ts": 75, "src/packages/process-host/src/close-process-registry.test.ts": 39, "src/packages/process-host/src/growing-byte-buffer.test.ts": 102, @@ -4250,36 +4090,26 @@ "src/packages/process-host/src/windows-command-line.test.ts": 73, "src/packages/process-host/src/windows-tree-kill.test.ts": 81, "src/packages/process-host/src/wsl-distro-allowlist.test.ts": 55, - "src/preload/api/notification-sound-playback.test.ts": 64, - "src/preload/api/platform-bridge.test.ts": 48, - "src/preload/app-restart-checkpoint-routing.test.ts": 2028, - "src/preload/browser-client-page-renderer-requests.test.ts": 154, - "src/preload/browser-extension-content-script-relay.test.ts": 65, - "src/preload/browser-extension-document-targets.test.ts": 75, - "src/preload/browser-extension-inert-apis.test.ts": 50, - "src/preload/browser-extension-main-world.test.ts": 81, - "src/preload/browser-extension-native-messaging.test.ts": 70, - "src/preload/browser-extension-storage-relay.test.ts": 104, - "src/preload/browser-extension-storage-sync.test.ts": 108, - "src/preload/browser-extension-web-store-main-world.test.ts": 166, - "src/preload/browser-extension-web-store-wording.test.ts": 194, - "src/preload/browser-find-subscriptions.test.ts": 66, + "src/preload/api/notifications/notification-sound-playback.test.ts": 64, + "src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts": 2028, + "src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts": 154, + "src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts": 65, + "src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts": 75, + "src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts": 50, + "src/preload/browser/extensions/api/browser-extension-main-world.test.ts": 81, + "src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts": 104, + "src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts": 108, + "src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts": 166, + "src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts": 66, "src/preload/browser-window-close.test.ts": 98, - "src/preload/close-active-tab-payload-admission.test.ts": 48, + "src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts": 48, "src/preload/doc-preview-link-interception.test.ts": 234, - "src/preload/gitlab-work-item-details.test.ts": 49, - "src/preload/opencode-go-credentials.test.ts": 45, - "src/preload/plugin-frame-guest-render-lane.test.ts": 47, - "src/preload/plugin-frame-guest.test.ts": 287, - "src/preload/renderer-heap-statistics-reader.test.ts": 50, - "src/preload/renderer-process-memory-reader.test.ts": 66, - "src/preload/renderer-restart-wiring.test.ts": 96, - "src/preload/runtime-environment-subscriptions.test.ts": 71, - "src/preload/ssh-authority-forwarding.test.ts": 1111, - "src/preload/updater-package-recovery.test.ts": 1102, - "src/preload/usage-provider-api.test.ts": 46, + "src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts": 47, + "src/preload/plugins/frames/plugin-frame-guest.test.ts": 287, + "src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts": 50, + "src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts": 66, + "src/preload/renderer/restart/renderer-restart-wiring.test.ts": 96, "src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts": 65, - "src/renderer/src/app-shell/startup-window-parity.test.ts": 2306, "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, @@ -4312,7 +4142,6 @@ "src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx": 315, "src/renderer/src/components/activity/activity-scope-filter.test.ts": 734, "src/renderer/src/components/activity/activity-search-query.test.tsx": 2286, - "src/renderer/src/components/activity/activity-terminal-portal-publication-loop.react185.test.tsx": 222, "src/renderer/src/components/activity/activity-thread-list-pane.multi-select.test.tsx": 4699, "src/renderer/src/components/activity/activity-thread-list-pane.virtualization.test.tsx": 4863, "src/renderer/src/components/activity/useActivityUnreadCount.freshness.test.tsx": 1990, @@ -4331,7 +4160,6 @@ "src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx": 3389, "src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx": 2932, "src/renderer/src/components/automations/ExternalAutomationManagers.test.tsx": 852, - "src/renderer/src/components/automations/hosts/automation-captured-owner.test.ts": 379, "src/renderer/src/components/automations/automation-host-cache-controller.test.ts": 411, "src/renderer/src/components/automations/hosts/automation-host-cache.test.ts": 79, "src/renderer/src/components/automations/automation-host-diagnostics.test.ts": 460, @@ -4403,7 +4231,6 @@ "src/renderer/src/components/browser-pane/navigate/browser-page-download-activity.test.ts": 44, "src/renderer/src/components/browser-pane/navigate/browser-webview-load-failure.test.ts": 243, "src/renderer/src/components/browser-pane/navigate/chromium-error-page-poll-visibility.test.ts": 1956, - "src/renderer/src/components/browser-pane/navigate/use-browser-page-reload-actions.test.tsx": 2177, "src/renderer/src/components/browser-pane/restored-client-hosted-recovery-window.test.tsx": 6205, "src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.test.ts": 45, "src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-pane.address-bar.test.tsx": 2987, @@ -4675,11 +4502,9 @@ "src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx": 1968, "src/renderer/src/components/emulator-pane/use-mobile-emulator-tab-intro-actions.test.tsx": 1828, "src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.test.tsx": 1093, - "src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx": 2028, - "src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts": 466, + "src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts": 466, "src/renderer/src/components/floating-terminal/floating-workspace-tab-reorder.test.ts": 2520, "src/renderer/src/components/github-checks-tab-state.test.ts": 52, - "src/renderer/src/components/github-item-dialog/edit-item-fields/gh-edit-section.assignee-identity.test.tsx": 461, "src/renderer/src/components/github-item-dialog/land-pull-request/pr-reviewers-request-actions.test.ts": 1976, "src/renderer/src/components/github-item-dialog/load-item-details/use-github-item-dialog-details.test.tsx": 2850, "src/renderer/src/components/github-item-dialog/load-item-details/use-github-task-refresh.test.tsx": 1070, @@ -4885,37 +4710,31 @@ "src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.clear-send.test.tsx": 2804, "src/renderer/src/components/native-chat/pane/actions/use-structured-native-chat-submit-reveal.test.ts": 2304, "src/renderer/src/components/network/CustomAddressDialog.test.tsx": 568, - "src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx": 870, - "src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx": 5296, - "src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx": 2493, - "src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx": 1043, + "src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx": 870, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, - "src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx": 1387, + "src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx": 1387, "src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342, - "src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts": 347, - "src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts": 136, - "src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx": 278, - "src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx": 419, + "src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.test.ts": 347, + "src/shared/new-workspace/smart-workspace-source-results.test.ts": 136, + "src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx": 278, + "src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx": 419, "src/renderer/src/components/new-workspace/use-linear-source-connection.test.tsx": 1335, - "src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts": 1730, - "src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx": 2290, + "src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.test.ts": 1730, + "src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx": 2290, "src/renderer/src/components/new-workspace/work-item-source-selection.test.ts": 1736, "src/renderer/src/components/onboarding/OnboardingLanguageLoading.test.tsx": 2167, "src/renderer/src/components/pet/pet-blob-cache.test.ts": 64, "src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalPanels.test.tsx": 2510, "src/renderer/src/components/plugins/declarative/PluginDeclarativeView.test.tsx": 2804, "src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx": 2313, - "src/renderer/src/components/plugins/list/PluginManager.test.tsx": 3449, "src/renderer/src/components/plugins/list/plugin-list-entries.test.ts": 231, "src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx": 2043, "src/renderer/src/components/plugins/page/PluginCommandReplacementRow.test.tsx": 1926, "src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx": 3367, "src/renderer/src/components/plugins/page/PluginSettingsSection.test.tsx": 572, - "src/renderer/src/components/plugins/presentation/plugin-install-source.test.ts": 214, "src/renderer/src/components/plugins/state/use-plugin-contribution-source.test.tsx": 1935, "src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx": 518, - "src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx": 480, "src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx": 389, "src/renderer/src/components/plugins/view/plugin-view-acts.test.tsx": 3241, "src/renderer/src/components/plugins/view/plugin-view-data-acts.test.tsx": 3002, @@ -5089,7 +4908,6 @@ "src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-catalog.test.tsx": 2252, "src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477, "src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880, - "src/renderer/src/components/setup-guide/SetupGuideModal.mount-gating.test.tsx": 2348, "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts": 1925, "src/renderer/src/components/shared/useDaemonActions.test.tsx": 332, "src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostDialog.config-picker.test.tsx": 1178, @@ -5121,7 +4939,6 @@ "src/renderer/src/components/sidebar/workspace-card/identity/WorktreeTitleInlineRename.editor-lifecycle.test.tsx": 407, "src/renderer/src/components/sidebar/workspace-visibility/dialog/WorktreeVisibilityDialog.test.tsx": 2602, "src/renderer/src/components/sidebar/host-admission/ssh/add-remote-host-ssh-actions.test.ts": 232, - "src/renderer/src/components/sidebar/project-admission/completion/add-repo-skip-finalization.test.ts": 59, "src/renderer/src/components/sidebar/chat-markdown-math-typeset.test.ts": 1336, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-always-force-preference.test.tsx": 2175, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-counts.test.ts": 258, @@ -5195,10 +5012,8 @@ "src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts": 227, "src/renderer/src/components/skills/sharing/SkillSharedLinkRow.test.tsx": 817, "src/renderer/src/components/skills/SkillsPage.test.tsx": 3822, - "src/renderer/src/components/skills/catalog/skill-agent-filter.test.ts": 274, "src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 207, "src/renderer/src/components/stats/usage-daily-chart.test.tsx": 333, - "src/renderer/src/components/stats/usage-overview-model.test.ts": 364, "src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx": 2317, "src/renderer/src/components/status-bar/StatusBarUsageChangeNotices.test.tsx": 785, "src/renderer/src/components/status-bar/UpdateStatusSegment.test.tsx": 2484, @@ -5212,7 +5027,6 @@ "src/renderer/src/components/status-bar/resource-session-kill-confirmation.test.ts": 53, "src/renderer/src/components/status-bar/resource-session-removal-render-budget.test.tsx": 290, "src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts": 251, - "src/renderer/src/components/status-bar/usage-pool-label.test.ts": 170, "src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx": 462, "src/renderer/src/components/status-bar/use-resource-memory-snapshot.test.tsx": 321, "src/renderer/src/components/status-bar/use-resource-pty-actions.test.tsx": 879, @@ -5228,7 +5042,6 @@ "src/renderer/src/components/tab-bar/host-agent-launch-preferences-source.test.tsx": 3154, "src/renderer/src/components/tab-bar/tab-agent-launch-options.test.ts": 438, "src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts": 206, - "src/renderer/src/components/tab-bar/tab-context-menu.test.tsx": 5620, "src/renderer/src/components/tab-bar/tab-create-entry-classifier.test.ts": 510, "src/renderer/src/components/tab-bar/tab-create-entry-local-path.test.ts": 2614, "src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts": 2348, @@ -5246,40 +5059,27 @@ "src/renderer/src/components/tab-group/tab-drag-retained-guest-passthrough.test.tsx": 2104, "src/renderer/src/components/tab-group/tab-group-body-geometry.test.ts": 194, "src/renderer/src/components/tab-group/tab-group-layout-owner-commands.test.ts": 1764, - "src/renderer/src/components/tab-group/tab-moves-drawn-from-frames.test.ts": 2105, "src/renderer/src/components/tab-group/useTabGroupCloseScopeCommands.test.tsx": 2023, "src/renderer/src/components/tab-group/workspace-tab-close-commands.frame-flush.test.ts": 1604, "src/renderer/src/components/task-page/github/task-page-github-landing-refresh-record.test.tsx": 971, - "src/renderer/src/components/task-page/github/task-page-github-list-scroll-restore.test.ts": 197, "src/renderer/src/components/task-page/github/task-page-github-work-item-mutation-regressions.test.ts": 140, "src/renderer/src/components/task-page/github/task-page-github-work-item-mutations.test.ts": 169, "src/renderer/src/components/task-page/github/use-task-page-github-issue-creation.test.tsx": 1769, "src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx": 1504, "src/renderer/src/components/task-page/jira/Content.board-owner.test.tsx": 2582, - "src/renderer/src/components/task-page/jira/IssueAssigneeField.test.tsx": 1122, "src/renderer/src/components/task-page/jira/task-page-jira-board-detail-integration.test.tsx": 2192, - "src/renderer/src/components/task-page/jira/task-page-jira-board-transitions.test.ts": 69, "src/renderer/src/components/task-page/jira/task-page-jira-board-view.test.tsx": 2287, - "src/renderer/src/components/task-page/jira/task-page-jira-favourite-selection.test.tsx": 3326, - "src/renderer/src/components/task-page/jira/task-page-jira-grouping.test.ts": 2324, "src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts": 204, - "src/renderer/src/components/task-page/jira/task-page-jira-quick-copy.test.tsx": 3457, - "src/renderer/src/components/task-page/jira/use-task-page-jira-project-scope.test.tsx": 2642, - "src/renderer/src/components/task-page/jira/use-task-page-jira-quick-filters.test.tsx": 1466, - "src/renderer/src/components/task-page/jira/use-task-page-jira-saved-filters.test.tsx": 1501, - "src/renderer/src/components/task-page/jira/use-task-page-jira-summary-generation.test.tsx": 571, - "src/renderer/src/components/task-page/linear/IssueTable.test.tsx": 11230, - "src/renderer/src/components/task-page/linear/task-page-linear-committed-publication.test.tsx": 1978, + "src/renderer/src/components/task-page/jira/filters/use-task-page-jira-project-scope.test.tsx": 2642, + "src/renderer/src/components/task-page/jira/filters/use-task-page-jira-quick-filters.test.tsx": 1466, + "src/renderer/src/components/task-page/jira/filters/use-task-page-jira-saved-filters.test.tsx": 1501, + "src/renderer/src/components/task-page/jira/creation/use-task-page-jira-summary-generation.test.tsx": 571, "src/renderer/src/components/task-page/linear/task-page-linear-creation-lifetime.test.tsx": 3315, - "src/renderer/src/components/task-page/linear/task-page-linear-in-orca-issues.test.ts": 430, - "src/renderer/src/components/task-page/linear/task-page-linear-refresh-entry.test.tsx": 2217, - "src/renderer/src/components/task-page/linear/task-page-linear-refresh-lifecycle.test.tsx": 1814, - "src/renderer/src/components/task-page/linear/task-page-linear-refresh-writers.test.tsx": 2810, - "src/renderer/src/components/task-page/linear/task-page-linear-selection-decisions.test.tsx": 1018, + "src/renderer/src/components/task-page/linear/issues/task-page-linear-in-orca-issues.test.ts": 430, + "src/renderer/src/components/task-page/linear/issue-refresh/task-page-linear-refresh-lifecycle.test.tsx": 1814, "src/renderer/src/components/task-page/task-page-cache-selectors.test.ts": 108, "src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1953, "src/renderer/src/components/task-page/task-page-work-item-pagination.test.ts": 63, - "src/renderer/src/components/task-page/use-task-page-source-display.test.tsx": 5228, "src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx": 2303, "src/renderer/src/components/terminal-pane/account-restart/detached/account-restart-queue-progress.test.ts": 1988, "src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-attention-dispatch.test.ts": 301, @@ -5300,7 +5100,6 @@ "src/renderer/src/components/terminal-pane/provider-notices/claude-diff-panel/claude-diff-panel-notice-banner.test.tsx": 1986, "src/renderer/src/components/terminal-pane/notifications/claude-side-question-completion.test.ts": 2305, "src/renderer/src/components/terminal-pane/provider-notices/codex-backfill/codex-backfill-error-detector.test.ts": 26, - "src/renderer/src/components/terminal-pane/account-restart/detached/codex-detached-pane-restart.test.ts": 2270, "src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-shared-server-banner.test.tsx": 2766, "src/renderer/src/components/terminal-pane/pty-connection/output/deferred-reattach-live-data-queue.test.ts": 184, "src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts": 78, @@ -5347,7 +5146,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-restore-and-resume.test.ts": 19401, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-restored-baseline-shortfall.test.ts": 1902, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-visible-pane-output-pause-latch.test.ts": 1639, - "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-newer-daemon-hold.test.ts": 2570, "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-startup-snapshot.test.ts": 1830, "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-wsl-distro-stopped-hold.test.ts": 2517, "src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts": 92, @@ -5450,7 +5248,7 @@ "src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit-device-trace.test.ts": 415, "src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit.test.ts": 818, "src/renderer/src/components/terminal-pane/input/keyboard/terminal-keyboard-native-chat-cover.test.ts": 2084, - "src/shared/workspace-layout/terminal-layout-pty-ownership-depth.test.ts": 82, + "src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts": 82, "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts": 99, "src/renderer/src/components/terminal-pane/links/terminal-link-click-fallback.test.ts": 985, "src/renderer/src/components/terminal-pane/links/terminal-link-open-beside-source.test.ts": 947, @@ -5511,7 +5309,6 @@ "src/renderer/src/components/terminal/terminal-close-incarnation.test.ts": 42, "src/renderer/src/components/terminal/terminal-tab-actions-unified-close.test.ts": 1831, "src/renderer/src/components/terminal/terminal-tab-actions-unrouted-close.test.ts": 589, - "src/renderer/src/components/terminal/terminal-tab-actions.test.ts": 626, "src/renderer/src/components/terminal/terminal-tab-close-running-confirm.test.ts": 499, "src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx": 573, "src/renderer/src/components/terminal/window-close-running-work.test.ts": 97, @@ -5529,19 +5326,16 @@ "src/renderer/src/components/use-terminal-window-lifecycle.frame-flush.test.tsx": 2164, "src/renderer/src/components/virtualized-list.test.tsx": 446, "src/renderer/src/components/window-close-request-coordinator.test.ts": 361, - "src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx": 3269, - "src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx": 248, - "src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-git-evidence.test.tsx": 539, - "src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx": 2285, - "src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-row-order.test.ts": 242, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal-late-settlement.test.ts": 1880, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal.test.ts": 283, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-filter.test.ts": 341, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-sort.test.ts": 264, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx": 2594, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-removal-candidates.test.ts": 206, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-removal-settlement.test.ts": 203, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-removal-timeout-recovery.test.ts": 1817, + "src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx": 3269, + "src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-browse-state.test.tsx": 248, + "src/renderer/src/components/workspace-cleanup/candidate-evidence/use-workspace-cleanup-git-evidence.test.tsx": 539, + "src/renderer/src/components/workspace-cleanup/removal/use-workspace-cleanup-removal.agent-stop.test.tsx": 2285, + "src/renderer/src/components/workspace-cleanup/candidate-list/use-workspace-cleanup-row-order.test.ts": 242, + "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal-late-settlement.test.ts": 1880, + "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal.test.ts": 283, + "src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts": 341, + "src/renderer/src/components/workspace-cleanup/removal/workspace-cleanup-removal-candidates.test.ts": 206, + "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-timeout-recovery.test.ts": 1817, "src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerButton.test.tsx": 1086, "src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerPanel.test.tsx": 763, "src/renderer/src/components/workspace-emoji/useWorkspaceEmojiShortcodeInput.test.tsx": 365, @@ -5551,7 +5345,6 @@ "src/renderer/src/components/worktree-jump/use-worktree-jump-palette-browser-ownership.test.ts": 2096, "src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-search.test.tsx": 2140, "src/renderer/src/components/worktree-jump/worktree-jump-palette-browser-navigation.test.tsx": 4470, - "src/renderer/src/components/wsl-move/WslMoveDialog.test.tsx": 524, "src/renderer/src/components/wsl-move/wsl-move-dialog-store.test.ts": 2011, "src/renderer/src/components/wsl-move/wsl-move-scope-rows.test.ts": 156, "src/renderer/src/hooks/agent-hook-completion-grok-notifications.test.ts": 679, @@ -5574,7 +5367,6 @@ "src/renderer/src/hooks/editor-external-watch-selected-host.test.ts": 1988, "src/renderer/src/hooks/editor-runtime-file-watch.test.ts": 58, "src/renderer/src/hooks/ipc-events/agent-status-pane-routing-index-retention.test.ts": 4878, - "src/renderer/src/hooks/ipc-events/agent-status-pending-retry-gate.test.ts": 466, "src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts": 2247, "src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.owner.test.ts": 623, "src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.split.test.ts": 699, @@ -5599,7 +5391,6 @@ "src/renderer/src/hooks/ipc-events/worktree-event-runtime-activation.test.ts": 1934, "src/renderer/src/hooks/ipc-events/wsl-host-ipc-bridge-capability.test.ts": 1917, "src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts": 797, - "src/renderer/src/hooks/ipc-tab-switch.test.ts": 839, "src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts": 52, "src/renderer/src/hooks/metadata-request-cache.test.ts": 144, "src/renderer/src/hooks/programmatic-scroll-marks.test.ts": 47, @@ -5808,7 +5599,6 @@ "src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts": 2161, "src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043, "src/renderer/src/lib/workspace/activation/worktree-activation-web-runtime.test.ts": 2768, - "src/renderer/src/lib/workspace/activation/worktree-agent-activation-seam.test.ts": 3440, "src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258, "src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-prompts.test.tsx": 4554, "src/renderer/src/lib/workspace/ownership/worktree-live-terminal-surface-owners.test.ts": 266, @@ -5824,20 +5614,17 @@ "src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts": 189, "src/renderer/src/runtime/provider-accounts/observations/claude-agent-view-observations.test.ts": 105, "src/renderer/src/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab.test.ts": 397, - "src/renderer/src/runtime/workspace-layout/frames/divider-ratio-refusal.test.ts": 2212, "src/renderer/src/runtime/sync-runtime-graph/editor-buffer-dirty-readers.test.ts": 1892, "src/renderer/src/runtime/files/mutations/file-explorer-delete-owner-provenance.test.ts": 1878, "src/renderer/src/runtime/native-chat/model-catalogs/host-model-catalog-snapshots.test.ts": 2348, "src/renderer/src/runtime/web-session-tabs-sync/hydration/host-session-mirror-hydration-frame-ordering.test.tsx": 2469, "src/renderer/src/runtime/web-session-tabs-sync/hydration/host-session-mirror-settle-receipt-frames.test.tsx": 2130, "src/renderer/src/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration.test.ts": 467, - "src/renderer/src/runtime/workspace-layout/frames/layout-changes-during-stream-outage.test.ts": 1948, "src/renderer/src/runtime/workspace-layout/commands/layout-owner-command.test.ts": 549, "src/renderer/src/runtime/native-chat/naming/legacy-chat-rename-migration.test.tsx": 3834, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/mirrored-agent-status-clock-skew.test.ts": 1839, "src/renderer/src/runtime/web-session-tabs-sync/closing/paired-terminal-tab-close-environment-removal.test.ts": 1897, "src/renderer/src/runtime/web-session-tabs-sync/closing/paired-terminal-tab-close-reload.test.ts": 1943, - "src/renderer/src/runtime/workspace-layout/frames/pane-titles-drawn-from-frames.test.ts": 1988, "src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts": 55, "src/renderer/src/runtime/hosted-terminals/snapshots/remote-runtime-snapshot-outcome.test.ts": 233, "src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-frame-drop-resync.test.ts": 266, @@ -5857,15 +5644,12 @@ "src/renderer/src/runtime/hosts/connections/runtime-host-contact-regained.test.ts": 413, "src/renderer/src/runtime/jira/runtime-jira-image-client.test.ts": 214, "src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts": 192, - "src/renderer/src/runtime/workspace-layout/frames/runtime-layout-client.test.ts": 165, "src/renderer/src/runtime/files/reads/runtime-paged-file-read.test.ts": 1705, "src/renderer/src/runtime/files/search/runtime-quick-open-version-compatibility.test.ts": 451, "src/renderer/src/runtime/rpc/calls/runtime-rpc-client.test.ts": 342, "src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.test.ts": 567, "src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts": 2033, "src/renderer/src/runtime/hosted-terminals/streams/runtime-terminal-stream.test.ts": 449, - "src/renderer/src/runtime/workspace-layout/server/server-held-panes.test.tsx": 2254, - "src/renderer/src/runtime/workspace-layout/server/server-layout-apply.test.ts": 2222, "src/renderer/src/runtime/workspace-layout/server/server-layout-editor-handover.test.ts": 5075, "src/renderer/src/runtime/workspace-layout/server/server-layout-frames-handover.test.ts": 1991, "src/renderer/src/runtime/workspace-layout/server/server-layout-frames.test.ts": 2053, @@ -5883,7 +5667,6 @@ "src/renderer/src/runtime/sync-runtime-graph/terminal-group-grid-sizes.test.ts": 194, "src/renderer/src/runtime/browser/creation/web-runtime-browser-creation-placement.test.ts": 1927, "src/renderer/src/runtime/browser/creation/web-runtime-browser-link-open.test.ts": 2217, - "src/renderer/src/runtime/web-session-tabs-sync/closing/web-session-close-replay.test.ts": 1119, "src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-restored-placeholder-identity.test.ts": 985, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-agent-completion-notifications.test.ts": 1953, "src/renderer/src/runtime/web-session-tabs-sync/tracking/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854, @@ -5912,9 +5695,6 @@ "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts": 723, "src/renderer/src/runtime/hosted-terminals/recovery/evidence/web-session-terminal-retirement-proof-ledger.test.ts": 685, "src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking-stream-end.test.ts": 225, - "src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-binding.test.ts": 2155, - "src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-held-tabs.test.ts": 2519, - "src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.test.ts": 2282, "src/renderer/src/ssh/node-dist-mirror-recovery.test.ts": 1770, "src/renderer/src/ssh/ssh-connect-in-flight.test.ts": 62, "src/renderer/src/startup/startup-degraded-recovery.test.ts": 574, @@ -6014,7 +5794,6 @@ "src/renderer/src/store/github/repositories/github-repo-lookup-index.test.ts": 51, "src/renderer/src/store/github/review-threads/github-review-thread-rollback.test.ts": 663, "src/renderer/src/store/github/task-records/github-task-record-retries.test.ts": 758, - "src/renderer/src/store/github/task-records/github-task-records.test.ts": 807, "src/renderer/src/store/github/work-items/github-work-items-error-envelope.test.ts": 1746, "src/renderer/src/store/github/work-items/github-work-items-pagination.test.ts": 1806, "src/renderer/src/store/github/work-items/github-work-items-runtime-routing.test.ts": 1891, @@ -6208,7 +5987,7 @@ "src/shared/agent-hook-listener/normalization/agent-hook-listener-claude-elicitation.test.ts": 229, "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-approval-ownership.test.ts": 258, "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-interrupt.test.ts": 240, - "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-main-agent.test.ts": 207, + "src/shared/agent-hook-listener/providers/codex/agent-hook-listener-codex-main-agent.test.ts": 207, "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-subagent-names.test.ts": 260, "src/shared/agent-hook-listener/normalization/agent-hook-listener-command-code-transcript.test.ts": 330, "src/shared/agent-hook-listener/normalization/agent-hook-listener-grok-completion.test.ts": 255, @@ -6218,13 +5997,11 @@ "src/shared/agent-hook-listener/transport/agent-hook-listener-transport.test.ts": 326, "src/shared/agent-hook-listener/claude-session-continuation.test.ts": 114, "src/shared/agent-hook-listener/claude-settled-permission-requests.test.ts": 54, - "src/shared/agent-hook-listener/providers/claude-helper-kill.test.ts": 1288, - "src/shared/agent-hook-listener/providers/claude-transcript-semantics.test.ts": 163, - "src/shared/agent-hook-listener/providers/dsh-events.test.ts": 231, - "src/shared/agent-hook-listener/providers/hermes-events.test.ts": 143, - "src/shared/agent-hook-listener/providers/jcode-turn-prompt.test.ts": 122, - "src/shared/agent-hook-listener/providers/muse-events.test.ts": 246, - "src/shared/agent-hook-listener/providers/zcode-events.test.ts": 241, + "src/shared/agent-hook-listener/providers/claude/transcripts/claude-transcript-semantics.test.ts": 163, + "src/shared/agent-hook-listener/providers/dsh/dsh-events.test.ts": 231, + "src/shared/agent-hook-listener/providers/hermes/hermes-events.test.ts": 143, + "src/shared/agent-hook-listener/providers/muse/muse-events.test.ts": 246, + "src/shared/agent-hook-listener/providers/zcode/zcode-events.test.ts": 241, "src/shared/agent-hook-listener/reverse-file-region-scan.test.ts": 51, "src/shared/agent-hook-listener/transcript-reader.test.ts": 109, "src/shared/agent-hook-listener/transport/agent-hook-spool-drain.test.ts": 50, @@ -6240,7 +6017,6 @@ "src/shared/agent-status/process/agent-process-presence-platform.test.ts": 64, "src/shared/agent-launch/startup/agent-prompt-injection.test.ts": 88, "src/shared/agent-scratch-worktrees.test.ts": 61, - "src/shared/agent-session/agent-message-display-text.test.ts": 147, "src/shared/agent-session/agent-session-approval-blocked-path.test.ts": 49, "src/shared/agent-session/agent-session-attachments.test.ts": 46, "src/shared/agent-session/agent-session-context-clear.test.ts": 222, @@ -6308,7 +6084,6 @@ "src/shared/agent-status/transport/agent-status-osc.test.ts": 104, "src/shared/agent-status/store/agent-status-store-reopen.test.ts": 199, "src/shared/agent-status/title/agent-status-tracker-program-activity.test.ts": 77, - "src/shared/agent-launch/startup/agent-tui-input-clear.test.ts": 57, "src/shared/ai-vault/resume/ai-vault-resume-command.test.ts": 70, "src/shared/ai-vault/resume/ai-vault-resume-target.test.ts": 85, "src/shared/ai-vault/scanning/ai-vault-scope-paths.test.ts": 73, @@ -6319,7 +6094,6 @@ "src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts": 176, "src/shared/ai-vault/resume/ai-vault-ssh-resume-target.test.ts": 84, "src/shared/ansi-escape-sequences-consumers.test.ts": 140, - "src/shared/ansi-escape-sequences.test.ts": 289, "src/shared/antigravity-generation-plan.test.ts": 122, "src/shared/automatic-work-run-marker.test.ts": 93, "src/shared/automation-cron-dialect.test.ts": 65, @@ -6349,10 +6123,9 @@ "src/shared/claimed-agent-pty-owner.test.ts": 72, "src/shared/claude-agent-view-launch.test.ts": 55, "src/shared/claude-background-run-isolation.test.ts": 43, - "src/shared/claude-background-task-status.test.ts": 315, + "src/shared/agent-hook-listener/normalization/claude-background-task-status.test.ts": 315, "src/shared/claude-model-list-probe.test.ts": 55, "src/shared/claude-shell-function.test.ts": 220, - "src/shared/cli-runtime-pairing-inputs.test.ts": 64, "src/shared/cloud-service-url.test.ts": 37, "src/shared/coalescing-keyed-runner.test.ts": 119, "src/shared/codebuddy-agent.test.ts": 301, @@ -6387,18 +6160,15 @@ "src/shared/ephemeral-vm-recipe-checkout-mode.test.ts": 106, "src/shared/ephemeral-vm-recipe-output-capture.test.ts": 287, "src/shared/ephemeral-vm-recipe-process.test.ts": 198, - "src/shared/ephemeral-vm-recipe-repo-url.test.ts": 56, "src/shared/ephemeral-vm-recipes.test.ts": 160, "src/shared/ephemeral-vm-runtime-store-rollback.test.ts": 321, "src/shared/ephemeral-vm-runtime-store.test.ts": 195, "src/shared/execution-host-registry-shared-control-connect.test.ts": 160, "src/shared/execution-host-registry.test.ts": 169, "src/shared/execution-host.test.ts": 56, - "src/shared/external-automation-jobs-file.test.ts": 72, "src/shared/external-worktree-inbox.test.ts": 69, "src/shared/feature-education-telemetry.test.ts": 36, "src/shared/feature-tips.test.ts": 54, - "src/shared/file-explorer-display-root.test.ts": 47, "src/shared/file-inventory-budget.test.ts": 44, "src/shared/file-links/file-link-location.test.ts": 40, "src/shared/file-write-disk-precondition.test.ts": 56, @@ -6411,7 +6181,6 @@ "src/shared/git/compatibility/git-binary-compatibility.test.ts": 377, "src/shared/git/diff/git-blob-absence.test.ts": 54, "src/shared/git/branches/git-branch-cleanup-real-git.test.ts": 883, - "src/shared/git/branches/git-branch-cleanup.test.ts": 79, "src/shared/git/status/git-branch-line-total-soft-deadline.test.ts": 74, "src/shared/git/status/git-branch-line-total.test.ts": 135, "src/shared/git/diff/git-change-list.test.ts": 133, @@ -6449,9 +6218,6 @@ "src/shared/git/worktrees/git-worktree-admin.test.ts": 161, "src/shared/github/account-binding.test.ts": 48, "src/shared/github/api-availability.test.ts": 47, - "src/shared/github/owner-slug.test.ts": 45, - "src/shared/source-control/review-comments/pr-comments-resolution-prompt.test.ts": 49, - "src/shared/github/pr-reviewer-display.test.ts": 56, "src/shared/github/project-board-columns.test.ts": 64, "src/shared/github/project-identity.test.ts": 33, "src/shared/github/project-ref-input.test.ts": 40, @@ -6496,7 +6262,6 @@ "src/shared/keybindings-digit-index.test.ts": 110, "src/shared/keybindings-double-tap.test.ts": 92, "src/shared/keybindings-keyboard-layout.test.ts": 86, - "src/shared/keybindings-parse-cache.test.ts": 61, "src/shared/keybindings-parsing.test.ts": 86, "src/shared/keybindings-unassigned-actions.test.ts": 73, "src/shared/kiro-home.test.ts": 39, @@ -6594,7 +6359,6 @@ "src/shared/native-chat/transcript/native-chat-unverifiable-turn-status.test.ts": 150, "src/shared/native-file-drop.test.ts": 59, "src/shared/ndjson-retained-chunk-memory.test.ts": 327, - "src/shared/nested-repo-telemetry-schema.test.ts": 196, "src/shared/nested-repo-telemetry.test.ts": 55, "src/shared/network-proxy.test.ts": 44, "src/shared/network/manual-address.test.ts": 68, @@ -6634,7 +6398,6 @@ "src/shared/opencode-tui-plugin-install.test.ts": 82, "src/shared/openssh-default-shell.test.ts": 54, "src/shared/orca-browser-cli-commands.test.ts": 59, - "src/shared/orca-cli-command-name.test.ts": 41, "src/shared/orca-hook-setup-config.test.ts": 38, "src/shared/orca-session-address.test.ts": 154, "src/shared/orca-yaml-alias-bounds.test.ts": 425, @@ -6681,19 +6444,13 @@ "src/shared/plugins/authoring/plugin-host-typings.test.ts": 2140, "src/shared/plugins/catalog/plugin-catalog-release.test.ts": 229, "src/shared/plugins/catalog/plugin-catalog.test.ts": 630, - "src/shared/plugins/catalog/plugin-detail-fields.test.ts": 171, "src/shared/plugins/catalog/plugin-kill-list.test.ts": 195, "src/shared/plugins/catalog/plugin-marketplace.test.ts": 246, "src/shared/plugins/catalog/plugin-repository-link.test.ts": 205, "src/shared/plugins/contributions/plugin-command-replaces.test.ts": 230, "src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227, "src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238, - "src/shared/plugins/contributions/plugin-execution-profile.test.ts": 164, - "src/shared/plugins/contributions/plugin-panel-contribution.test.ts": 240, - "src/shared/plugins/contributions/plugin-settings-contribution.test.ts": 202, - "src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts": 232, "src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts": 147, - "src/shared/plugins/declarative/plugin-declarative-example.test.ts": 198, "src/shared/plugins/declarative/plugin-declarative-tree.test.ts": 168, "src/shared/plugins/declarative/runtime/declarative-act-snapshot.test.ts": 64, "src/shared/plugins/declarative/runtime/declarative-error-location.test.ts": 63, @@ -6703,21 +6460,14 @@ "src/shared/plugins/declarative/runtime/declarative-storage-sync.test.ts": 190, "src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts": 506, "src/shared/plugins/declarative/testing/orca-testing-worker.test.ts": 480, - "src/shared/plugins/declarative/testing/orca-testing.test.ts": 489, "src/shared/plugins/declarative/testing/testing-editor-host.test.ts": 197, "src/shared/plugins/frames/plugin-frame-document-session.test.ts": 404, "src/shared/plugins/frames/plugin-frame-document.test.ts": 426, - "src/shared/plugins/frames/plugin-frame-facades.test.ts": 383, - "src/shared/plugins/frames/plugin-frame-guest.test.ts": 50, "src/shared/plugins/frames/plugin-panel-call-admission.test.ts": 89, - "src/shared/plugins/frames/plugin-panel-message-budget.test.ts": 99, "src/shared/plugins/frames/plugin-panel-shell.test.ts": 376, "src/shared/plugins/images/plugin-image-format.test.ts": 104, "src/shared/plugins/images/plugin-image-url.test.ts": 42, - "src/shared/plugins/installation/plugin-file-validation.test.ts": 363, - "src/shared/plugins/installation/plugin-path-safety.test.ts": 221, "src/shared/plugins/manifest/plugin-display-text.test.ts": 285, - "src/shared/plugins/manifest/plugin-manifest-source-module-floor.test.ts": 212, "src/shared/plugins/manifest/plugin-manifest-v2-rules.test.ts": 239, "src/shared/plugins/manifest/plugin-manifest.test.ts": 234, "src/shared/plugins/view/plugin-editor-shot-acts.test.ts": 112, @@ -6803,7 +6553,6 @@ "src/shared/remote-runtime/requests/remote-runtime-subscription-frame-router.test.ts": 143, "src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts": 646, "src/shared/renderer-restart-preparation.test.ts": 197, - "src/shared/repo-display-labels.test.ts": 57, "src/shared/repo-host-identity.test.ts": 45, "src/shared/repo-icon.test.ts": 82, "src/shared/repo-pack-index-scheduling.test.ts": 67, @@ -6819,19 +6568,15 @@ "src/shared/ripgrep-match-offsets.test.ts": 151, "src/shared/ripgrep-process-availability.test.ts": 56, "src/shared/ripgrep-search-diagnostics.test.ts": 72, - "src/shared/rpc-contract/agent-launch-params-account-env.test.ts": 328, - "src/shared/rpc-contract/agent-launch-params-native-chat-default.test.ts": 327, - "src/shared/rpc-contract/agent-launch-params.test.ts": 301, - "src/shared/rpc-contract/agent-session-params-account-env.test.ts": 127, - "src/shared/rpc-contract/agent-session-spawn-intent-params.test.ts": 182, + "src/shared/agent-launch/startup/agent-launch-account-env.test.ts": 328, + "src/shared/rpc-contract/agent-launch/agent-launch-params.test.ts": 301, "src/shared/rpc-contract/automation-params-extra-agent-args.test.ts": 131, - "src/shared/rpc-contract/session-tabs-create-resume-session-param.test.ts": 259, + "src/shared/rpc-contract/session-tabs/session-tabs-create-resume-session-param.test.ts": 259, "src/shared/rpc-contract/structured-agent-session-agent-params.test.ts": 274, - "src/shared/rpc-contract/structured-agent-session-message-params.test.ts": 169, - "src/shared/rpc-contract/structured-agent-session-queued-edit-params.test.ts": 270, - "src/shared/rpc-contract/terminal-create-shell-param.test.ts": 182, - "src/shared/rpc-contract/workspace-layout-editor-file-params.test.ts": 269, - "src/shared/rpc-contract/worktree-review-metadata-compatibility.test.ts": 147, + "src/shared/queued-message-edit-skills.test.ts": 270, + "src/shared/rpc-contract/terminal/terminal-create-shell-param.test.ts": 182, + "src/shared/rpc-contract/workspace-layout/workspace-layout-editor-file-params.test.ts": 269, + "src/shared/rpc-contract/workspaces/worktree-review-metadata-compatibility.test.ts": 147, "src/shared/remote-runtime/host-store/runtime-environment-managed-orcad-store.test.ts": 313, "src/shared/remote-runtime/host-store/runtime-environment-sidecar.test.ts": 277, "src/shared/remote-runtime/host-store/runtime-environment-ssh-access-store.test.ts": 415, @@ -6901,13 +6646,11 @@ "src/shared/tab-agent-from-signals-pi-identity.test.ts": 103, "src/shared/task-query.test.ts": 55, "src/shared/task-source-context.test.ts": 103, - "src/shared/telemetry-payload-contracts.test.ts": 282, "src/shared/program-status/terminal-agent-status-processor.test.ts": 74, "src/shared/terminal/output/terminal-bell-detector.test.ts": 40, "src/shared/terminal/protocol/queries/terminal-color-scheme-protocol.test.ts": 39, "src/shared/terminal/input/terminal-composer-draft.test.ts": 73, "src/shared/terminal/links/terminal-file-uri-link.test.ts": 51, - "src/shared/terminal/links/terminal-file-url-target.test.ts": 47, "src/shared/terminal/links/terminal-github-pr-link-detector.test.ts": 61, "src/shared/terminal/links/terminal-http-url-extraction.test.ts": 42, "src/shared/terminal/input/terminal-input.test.ts": 85, @@ -6983,54 +6726,44 @@ "src/shared/workspace-attachments/workspace-attachment-origins.test.ts": 42, "src/shared/workspace-attachments/workspace-attachments.test.ts": 204, "src/shared/workspace-cleanup/workspace-cleanup-browse-state-persistence.test.ts": 55, - "src/shared/workspace-last-active-switch-on.test.ts": 52, "src/shared/workspace-layout/old-client/old-client-method-translation.test.ts": 352, "src/shared/workspace-layout/old-client/old-client-pane-layout-translation.test.ts": 363, "src/shared/workspace-layout/old-client/old-client-session-tabs-projection-owned-editor.test.ts": 178, "src/shared/workspace-layout/old-client/old-client-session-tabs-projection.test.ts": 207, - "src/shared/workspace-layout/tab-group-moves.test.ts": 52, - "src/shared/workspace-layout/tab-order-moves.test.ts": 44, - "src/shared/workspace-layout/workspace-layout-agent-session-tab.test.ts": 168, - "src/shared/workspace-layout/workspace-layout-browser-commands.test.ts": 177, - "src/shared/workspace-layout/workspace-layout-cold-local-window.test.ts": 319, - "src/shared/workspace-layout/workspace-layout-command-persistence.test.ts": 329, - "src/shared/workspace-layout/workspace-layout-commands.test.ts": 215, - "src/shared/workspace-layout/workspace-layout-default-tabs.test.ts": 159, - "src/shared/workspace-layout/workspace-layout-dropped-leaves.test.ts": 174, - "src/shared/workspace-layout/workspace-layout-editor-duplicates.test.ts": 312, - "src/shared/workspace-layout/workspace-layout-editor-file-owner.test.ts": 349, - "src/shared/workspace-layout/workspace-layout-editor-open-file-id.test.ts": 162, - "src/shared/workspace-layout/workspace-layout-editor-open.test.ts": 166, - "src/shared/workspace-layout/workspace-layout-editor-rekey.test.ts": 169, - "src/shared/workspace-layout/workspace-layout-fact-locations.test.ts": 449, - "src/shared/workspace-layout/workspace-layout-initial-surface.test.ts": 163, - "src/shared/workspace-layout/workspace-layout-legacy-persistence.test.ts": 332, - "src/shared/workspace-layout/workspace-layout-load-browser-repair.test.ts": 313, - "src/shared/workspace-layout/workspace-layout-load-check-details.test.ts": 286, - "src/shared/workspace-layout/workspace-layout-load-duplicate-pty.test.ts": 340, - "src/shared/workspace-layout/workspace-layout-load-normalization.test.ts": 470, - "src/shared/workspace-layout/workspace-layout-load-synthetic-pane-title.test.ts": 324, - "src/shared/workspace-layout/workspace-layout-load-view-less-tabs.test.ts": 294, - "src/shared/workspace-layout/workspace-layout-minted-ids.test.ts": 40, - "src/shared/workspace-layout/workspace-layout-model-rules.test.ts": 321, - "src/shared/workspace-layout/workspace-layout-move-tab-anchor.test.ts": 160, - "src/shared/workspace-layout/workspace-layout-move-tab-pin.test.ts": 180, - "src/shared/workspace-layout/workspace-layout-open-in-new-group.test.ts": 195, - "src/shared/workspace-layout/workspace-layout-owned-editor-id.test.ts": 334, - "src/shared/workspace-layout/workspace-layout-process-rules.test.ts": 201, - "src/shared/workspace-layout/workspace-layout-published-editor-view.test.ts": 175, - "src/shared/workspace-layout/workspace-layout-published.test.ts": 343, - "src/shared/workspace-layout/workspace-layout-ratio-commands.test.ts": 156, - "src/shared/workspace-layout/workspace-layout-record-patch.test.ts": 1264, - "src/shared/workspace-layout/workspace-layout-records.test.ts": 325, - "src/shared/workspace-layout/workspace-layout-resume-record.test.ts": 370, - "src/shared/workspace-layout/workspace-layout-round-trip.test.ts": 329, - "src/shared/workspace-layout/workspace-layout-simulator-tab.test.ts": 159, - "src/shared/workspace-layout/workspace-layout-terminal-adoption.test.ts": 171, - "src/shared/workspace-layout/workspace-layout-transitions.test.ts": 203, - "src/shared/workspace-layout/workspace-layout-views-owned-file.test.ts": 171, - "src/shared/workspace-layout/workspace-layout-views.test.ts": 183, - "src/shared/workspace-layout/workspace-layout-workspace-move.test.ts": 181, + "src/shared/workspace-layout/tab-groups/tab-group-moves.test.ts": 52, + "src/shared/workspace-layout/tab-groups/tab-order-moves.test.ts": 44, + "src/shared/workspace-layout/commands/workspace-layout-agent-session-tab.test.ts": 168, + "src/shared/workspace-layout/commands/workspace-layout-browser-commands.test.ts": 177, + "src/shared/workspace-layout/persistence/workspace-layout-command-persistence.test.ts": 329, + "src/shared/workspace-layout/commands/workspace-layout-commands.test.ts": 215, + "src/shared/workspace-layout/commands/workspace-layout-default-tabs.test.ts": 159, + "src/shared/workspace-layout/commands/workspace-layout-dropped-leaves.test.ts": 174, + "src/shared/workspace-layout/editor-tabs/workspace-layout-editor-duplicates.test.ts": 312, + "src/shared/workspace-layout/editor-tabs/workspace-layout-editor-file-owner.test.ts": 349, + "src/shared/workspace-layout/editor-tabs/workspace-layout-editor-open.test.ts": 166, + "src/shared/workspace-layout/editor-tabs/workspace-layout-editor-rekey.test.ts": 169, + "src/shared/workspace-layout/commands/workspace-layout-initial-surface.test.ts": 163, + "src/shared/workspace-layout/persistence/workspace-layout-legacy-persistence.test.ts": 332, + "src/shared/workspace-layout/persistence/workspace-layout-load-browser-repair.test.ts": 313, + "src/shared/workspace-layout/persistence/workspace-layout-load-check-details.test.ts": 286, + "src/shared/workspace-layout/persistence/workspace-layout-load-duplicate-pty.test.ts": 340, + "src/shared/workspace-layout/persistence/workspace-layout-load-normalization.test.ts": 470, + "src/shared/workspace-layout/persistence/workspace-layout-load-synthetic-pane-title.test.ts": 324, + "src/shared/workspace-layout/persistence/workspace-layout-load-view-less-tabs.test.ts": 294, + "src/shared/workspace-layout/invariants/workspace-layout-model-rules.test.ts": 321, + "src/shared/workspace-layout/commands/workspace-layout-move-tab-anchor.test.ts": 160, + "src/shared/workspace-layout/commands/workspace-layout-move-tab-pin.test.ts": 180, + "src/shared/workspace-layout/commands/workspace-layout-open-in-new-group.test.ts": 195, + "src/shared/workspace-layout/editor-tabs/workspace-layout-owned-editor-id.test.ts": 334, + "src/shared/workspace-layout/commands/workspace-layout-process-rules.test.ts": 201, + "src/shared/workspace-layout/commands/workspace-layout-ratio-commands.test.ts": 156, + "src/shared/workspace-layout/published-layout/workspace-layout-records.test.ts": 325, + "src/shared/workspace-layout/commands/workspace-layout-resume-record.test.ts": 370, + "src/shared/workspace-layout/commands/workspace-layout-simulator-tab.test.ts": 159, + "src/shared/workspace-layout/commands/workspace-layout-terminal-adoption.test.ts": 171, + "src/shared/workspace-layout/commands/workspace-layout-transitions.test.ts": 203, + "src/shared/workspace-layout/client-views/workspace-layout-views.test.ts": 183, + "src/shared/workspace-layout/editor-tabs/workspace-layout-workspace-move.test.ts": 181, "src/shared/workspace-attachments/workspace-linked-item-source-context.test.ts": 65, "src/shared/workspace-name.test.ts": 49, "src/shared/workspace-attachments/workspace-reference-identity.test.ts": 82, @@ -7057,55 +6790,50 @@ "src/shared/wsl-login-shell-fish-version.test.ts": 148, "src/shared/wsl-login-shell-nushell.test.ts": 66, "src/shared/zod-salvage-absence.test.ts": 96, - "src/wsl-guest/agent-hook-canonical-status.test.ts": 2770, - "src/wsl-guest/agent-hook-envelope-publication.test.ts": 348, - "src/wsl-guest/agent-hook-integration.test.ts": 1827, - "src/wsl-guest/agent-hook-interrupt-reconciliation.test.ts": 586, - "src/wsl-guest/agent-hook-opencode-tui-identity.test.ts": 551, - "src/wsl-guest/agent-hook-provider-normalization.test.ts": 489, - "src/wsl-guest/agent-hook-server-claude-owed-notification-expiry.test.ts": 792, - "src/wsl-guest/agent-hook-server-claude-session-continuation.test.ts": 462, - "src/wsl-guest/agent-hook-server-codex-side-thread.test.ts": 786, - "src/wsl-guest/agent-hook-server-codex-subagent-transcript.test.ts": 1589, - "src/wsl-guest/agent-hook-server-codex-turn-interruption.test.ts": 1786, - "src/wsl-guest/agent-hook-server.test.ts": 1651, - "src/wsl-guest/dispatcher-bulk-admission.test.ts": 390, - "src/wsl-guest/dispatcher-bulk-failed-admission.test.ts": 181, - "src/wsl-guest/dispatcher-bulk-retirement-admission.test.ts": 2204, - "src/wsl-guest/dispatcher-capacity-degradation.test.ts": 313, - "src/wsl-guest/dispatcher-client-close-cause.test.ts": 132, - "src/wsl-guest/dispatcher-client-writer.test.ts": 70, - "src/wsl-guest/dispatcher-frame-guard-regressions.test.ts": 170, - "src/wsl-guest/dispatcher-json-payload.test.ts": 239, - "src/wsl-guest/dispatcher-notification-ownership.test.ts": 120, - "src/wsl-guest/dispatcher-per-connection-state-baseline.test.ts": 226, - "src/wsl-guest/dispatcher-rpc-cancel-id-coercion.test.ts": 203, - "src/wsl-guest/dispatcher-silent-client-reaper.test.ts": 195, - "src/wsl-guest/dispatcher-structured-error.test.ts": 203, - "src/wsl-guest/dispatcher-timeout.test.ts": 137, - "src/wsl-guest/dispatcher-writer-admission.test.ts": 109, - "src/wsl-guest/dispatcher.test.ts": 348, - "src/wsl-guest/legacy-relay-publication-ledger.test.ts": 41, - "src/wsl-guest/omp-config-root.test.ts": 254, - "src/wsl-guest/opencode-startup-prompt-install.test.ts": 290, - "src/wsl-guest/plugin-overlay-env.test.ts": 130, - "src/wsl-guest/plugin-overlay.test.ts": 263, - "src/wsl-guest/preflight-handler.test.ts": 95, - "src/wsl-guest/protocol-backpressure.test.ts": 126, - "src/wsl-guest/protocol-handshake.test.ts": 66, - "src/wsl-guest/protocol-json-payload.test.ts": 144, - "src/wsl-guest/relay-agent-presence.test.ts": 518, - "src/wsl-guest/relay-command-env.test.ts": 57, - "src/wsl-guest/relay-hot-path-operation-counts.test.ts": 215, - "src/wsl-guest/relay-http-owner-probe-lifecycle.test.ts": 662, - "src/wsl-guest/relay-idle-process-owner.test.ts": 522, - "src/wsl-guest/relay-nested-same-provider-owner.test.ts": 415, - "src/wsl-guest/wsl-agent-hook-relay.test.ts": 471, - "src/wsl-guest/wsl-hook-fs-bridge.test.ts": 66, - "src/wsl-guest/wsl-install-plugins-handler.test.ts": 283, + "src/wsl-guest/agent-hooks/status/agent-hook-canonical-status.test.ts": 2770, + "src/wsl-guest/agent-hooks/publication/agent-hook-envelope-publication.test.ts": 348, + "src/wsl-guest/agent-hooks/publication/agent-hook-integration.test.ts": 1827, + "src/wsl-guest/agent-hooks/status/agent-hook-interrupt-reconciliation.test.ts": 586, + "src/wsl-guest/agent-hooks/server/agent-hook-opencode-tui-identity.test.ts": 551, + "src/wsl-guest/agent-hooks/status/agent-hook-provider-normalization.test.ts": 489, + "src/wsl-guest/agent-hooks/status/agent-hook-server-claude-session-continuation.test.ts": 462, + "src/wsl-guest/agent-hooks/status/agent-hook-server-codex-side-thread.test.ts": 786, + "src/wsl-guest/agent-hooks/status/agent-hook-server-codex-subagent-transcript.test.ts": 1589, + "src/wsl-guest/agent-hooks/status/agent-hook-server-codex-turn-interruption.test.ts": 1786, + "src/wsl-guest/agent-hooks/server/agent-hook-server.test.ts": 1651, + "src/wsl-guest/transport/publication/dispatcher-bulk-admission.test.ts": 390, + "src/wsl-guest/transport/publication/dispatcher-bulk-retirement-admission.test.ts": 2204, + "src/wsl-guest/transport/publication/dispatcher-capacity-degradation.test.ts": 313, + "src/wsl-guest/transport/connection/dispatcher-client-close-cause.test.ts": 132, + "src/wsl-guest/transport/writer/dispatcher-client-writer.test.ts": 70, + "src/wsl-guest/transport/connection/dispatcher-frame-guard-regressions.test.ts": 170, + "src/wsl-guest/transport/publication/dispatcher-json-payload.test.ts": 239, + "src/wsl-guest/transport/publication/dispatcher-notification-ownership.test.ts": 120, + "src/wsl-guest/transport/connection/dispatcher-rpc-cancel-id-coercion.test.ts": 203, + "src/wsl-guest/transport/connection/dispatcher-silent-client-reaper.test.ts": 195, + "src/wsl-guest/transport/connection/dispatcher-structured-error.test.ts": 203, + "src/wsl-guest/transport/connection/dispatcher-timeout.test.ts": 137, + "src/wsl-guest/transport/writer/dispatcher-writer-admission.test.ts": 109, + "src/wsl-guest/transport/publication/dispatcher.test.ts": 348, + "src/wsl-guest/transport/writer/legacy-relay-publication-ledger.test.ts": 41, + "src/wsl-guest/plugins/overlays/omp-config-root.test.ts": 254, + "src/wsl-guest/plugins/installation/opencode-startup-prompt-install.test.ts": 290, + "src/wsl-guest/plugins/overlays/plugin-overlay-env.test.ts": 130, + "src/wsl-guest/plugins/overlays/plugin-overlay.test.ts": 263, + "src/wsl-guest/commands/preflight-handler.test.ts": 95, + "src/wsl-guest/transport/wire/protocol-backpressure.test.ts": 126, + "src/wsl-guest/transport/wire/protocol-handshake.test.ts": 66, + "src/wsl-guest/transport/wire/protocol-json-payload.test.ts": 144, + "src/wsl-guest/agent-hooks/presence/relay-agent-presence.test.ts": 518, + "src/wsl-guest/commands/relay-command-env.test.ts": 57, + "src/wsl-guest/agent-hooks/presence/relay-http-owner-probe-lifecycle.test.ts": 662, + "src/wsl-guest/agent-hooks/presence/relay-idle-process-owner.test.ts": 522, + "src/wsl-guest/agent-hooks/presence/relay-nested-same-provider-owner.test.ts": 415, + "src/wsl-guest/agent-hooks/server/wsl-agent-hook-relay.test.ts": 471, + "src/wsl-guest/commands/wsl-hook-fs-bridge.test.ts": 66, + "src/wsl-guest/plugins/installation/wsl-install-plugins-handler.test.ts": 283, "tests/e2e/SmartWorkspaceSourceResultList.linear-auth.unit.test.ts": 1976, "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/ai-vault-manual-name-clear.unit.test.ts": 21206, "tests/e2e/automation-chat-reopen.unit.test.ts": 6262, @@ -7154,7 +6882,6 @@ "tests/e2e/orchestration-worker-workspace-resolution.unit.test.ts": 5936, "tests/e2e/paired-cli-agent-launch.unit.test.ts": 8918, "tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts": 9954, - "tests/e2e/paired-worktree-agent-command-owner.unit.test.ts": 1767, "tests/e2e/pdf-detail-dimension-reads.unit.test.ts": 438, "tests/e2e/persistence-automation-target-dispatch.unit.test.ts": 8084, "tests/e2e/remote-agent-completion-authority.unit.test.ts": 1742, @@ -7173,11 +6900,8 @@ "tests/e2e/structured-attention-read-retirement.unit.test.ts": 6109, "tests/e2e/structured-chat-tab-lifetime.unit.test.ts": 5616, "tests/e2e/sustained-agent-typing-load-scripts.unit.test.ts": 2169, - "tests/e2e/task-page-linear-refresh-authority.unit.test.ts": 5548, - "tests/e2e/terminal-foreground-confirmation.unit.test.ts": 644, "tests/e2e/terminal-perf-presentation.unit.test.ts": 60, "tests/e2e/worktree-status-warning.unit.test.ts": 2331, - "tests/tools/branch-line-total-renderer.test.mjs": 1222, "tests/tools/omp-close-lifecycle.test.mjs": 403, "tests/tools/omp-config-root-relay-shell.test.mjs": 297, "tests/tools/relay-bench/phone-e2ee-desktop-parity.test.mjs": 111, @@ -7200,7 +6924,6 @@ "src/main/skills/bundled-skill-install/bundled-skill-plan-selection.test.ts": 392, "src/main/skills/bundled-skill-install/bundled-skill-plan.test.ts": 297, "src/main/skills/bundled-skill-install/bundled-skill-workspace-targets.test.ts": 248, - "src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts": 93, "src/main/skills/discovery/skill-discovery-filter-sharing.test.ts": 239, "src/main/skills/discovery/skill-discovery-stopped-wsl-distro.test.ts": 185, "src/main/skills/discovery/skill-native-discovery.test.ts": 254, @@ -7437,7 +7160,6 @@ "tests/e2e/settings-agent-awake.spec.ts": 33400, "tests/e2e/settings-display-name-ime.spec.ts": 18100, "tests/e2e/settings-search-responsiveness.spec.ts": 15600, - "tests/e2e/settings-search-shortcuts-pane.spec.ts": 15800, "tests/e2e/settings-skill-detection.spec.ts": 21800, "tests/e2e/settled-worker-tab-survives-restart.spec.ts": 62400, "tests/e2e/setup-guide-sidebar.spec.ts": 6800, diff --git a/config/scripts/ci/sharding/ci-unit-sequencer.test.mjs b/config/scripts/ci/sharding/ci-unit-sequencer.test.mjs index 29bdd48d8c3..60e6a7bb975 100644 --- a/config/scripts/ci/sharding/ci-unit-sequencer.test.mjs +++ b/config/scripts/ci/sharding/ci-unit-sequencer.test.mjs @@ -1,4 +1,4 @@ -import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs' +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' @@ -13,53 +13,36 @@ afterEach(() => { } }) -it.each([ - 'valid', - 'stale', - 'missing-file', - 'missing-artifact', - 'outside-selection', - 'empty-selection' -])('preserves complete shard coverage with %s planning evidence', async (kind) => { - root = mkdtempSync(join(tmpdir(), 'unit-sequencer-')) - const files = ['src/a.test.ts', 'src/b.test.ts', 'src/c.test.ts', 'src/d.test.ts'] - const plan = { - version: 1, - sourceSha: kind === 'stale' ? 'old' : 'current', - files: kind === 'missing-file' ? files.slice(1) : files, - executionFiles: - kind === 'outside-selection' - ? ['src/unknown.test.ts'] - : kind === 'empty-selection' - ? [] - : files.slice(0, 2) - } - const planPath = join(root, 'selection.json') - if (kind !== 'missing-artifact') { +it.each(['valid', 'stale'])( + 'preserves complete shard coverage with %s planning evidence', + async (kind) => { + root = mkdtempSync(join(tmpdir(), 'unit-sequencer-')) + const files = ['src/a.test.ts', 'src/b.test.ts', 'src/c.test.ts', 'src/d.test.ts'] + const plan = { + version: 1, + sourceSha: kind === 'stale' ? 'old' : 'current', + files, + executionFiles: files.slice(0, 2) + } + const planPath = join(root, 'selection.json') writeFileSync(planPath, JSON.stringify(plan)) - } - vi.stubEnv('ORCA_UNIT_SELECTION_PLAN', planPath) - vi.stubEnv('ORCA_SHARD_SOURCE_SHA', 'current') - vi.stubEnv('ORCA_SHARD_MANIFEST', join(root, 'assignment.json')) - const assigned = [] - for (const index of [1, 2]) { - const sequencer = new TimingSequencer({ config: { root, shard: { index, count: 2 } } }) - const specs = files.map((file, position) => ({ - moduleId: join(root, file), - project: { - name: position === 0 ? 'synthetic-late' : position % 2 ? 'bun' : 'node-runtime', - config: { sequence: { groupOrder: position === 0 ? 2 : 1 }, isolate: true } - } - })) - assigned.push(...(await sequencer.shard(specs)).map((spec) => spec.moduleId)) - const manifest = JSON.parse(readFileSync(join(root, 'assignment.json'), 'utf8')) - expect(manifest.selectedShard).toBe(index) - expect(manifest.shards.flatMap((shard) => shard.files).sort()).toEqual( - (kind === 'valid' ? files.slice(0, 2) : files).toSorted() + vi.stubEnv('ORCA_UNIT_SELECTION_PLAN', planPath) + vi.stubEnv('ORCA_SHARD_SOURCE_SHA', 'current') + vi.stubEnv('ORCA_SHARD_MANIFEST', join(root, 'assignment.json')) + const assigned = [] + for (const index of [1, 2]) { + const sequencer = new TimingSequencer({ config: { root, shard: { index, count: 2 } } }) + const specs = files.map((file, position) => ({ + moduleId: join(root, file), + project: { + name: position === 0 ? 'synthetic-late' : position % 2 ? 'bun' : 'node-runtime', + config: { sequence: { groupOrder: position === 0 ? 2 : 1 }, isolate: true } + } + })) + assigned.push(...(await sequencer.shard(specs)).map((spec) => spec.moduleId)) + } + expect(assigned.sort()).toEqual( + (kind === 'valid' ? files.slice(0, 2) : files).map((file) => join(root, file)).sort() ) } - expect(assigned.sort()).toEqual( - (kind === 'valid' ? files.slice(0, 2) : files).map((file) => join(root, file)).sort() - ) - expect(new Set(assigned).size).toBe(assigned.length) -}) +) diff --git a/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs b/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs index 682a8e41a8d..73af9b0753f 100644 --- a/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs +++ b/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs @@ -2,44 +2,7 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { importUnitTimingReports } from './ci-unit-timing-import.mjs' -import UnitTimingReporter, { buildUnitPhaseReport } from './ci-unit-timing-reporter.mjs' - -const report = (index, timings) => ({ - metric: 'module-duration-v1', - nodeVersion: '24.21.0', - sourceSha: 'source', - runId: 'run', - runAttempt: '1', - shard: { index, count: 2 }, - status: 'passed', - unhandledErrors: 0, - timings -}) - -describe('unit worker timing evidence', () => { - it('rejects incomplete, duplicate, mixed and failed evidence', () => { - const first = report(1, { a: 100 }) - expect(() => importUnitTimingReports([first])).toThrow('complete') - expect(() => importUnitTimingReports([first, first])).toThrow('index') - expect(() => importUnitTimingReports([first, report(2, { a: 200 })])).toThrow('timing') - for (const change of [ - { sourceSha: 'other' }, - { runId: 'other' }, - { runAttempt: '2' }, - { nodeVersion: '26.6.0' }, - { metric: 'test-duration' }, - { status: 'failed' }, - { status: 'interrupted' }, - { unhandledErrors: 1 } - ]) { - expect(() => - importUnitTimingReports([first, { ...report(2, { b: 200 }), ...change }]) - ).toThrow('successful') - } - expect(() => importUnitTimingReports([first, report(2, { b: -1 })])).toThrow('timing') - }) -}) +import UnitTimingReporter from './ci-unit-timing-reporter.mjs' const phaseDiagnostic = (overrides = {}) => ({ environmentSetupDuration: 1.5, @@ -83,75 +46,16 @@ function withReporterOutputs(run) { } describe('optional unit phase diagnostics', () => { - it('records fractions and project totals without retaining sampled import records', () => { - const report = buildUnitPhaseReport( - phaseContext(), - [ - phaseModule( - 'src/first.test.ts', - phaseDiagnostic({ - importDurations: { - first: { selfTime: 2, totalTime: 9, importer: 'src/private-account.ts' }, - second: { selfTime: 3.5, totalTime: 5.5 }, - invalid: { selfTime: Number.NaN, totalTime: 4 } - } - }) - ), - phaseModule('src/second.test.ts'), - phaseModule('src/node.test.ts', phaseDiagnostic({ workerId: 9 }), 'node-runtime') - ], - [{ message: 'test error' }], - 'failed' - ) - expect(report.files[0]).toEqual({ - file: 'src/first.test.ts', - project: 'bun', - workerId: 7, - concurrencyId: 2, - phases: { - environmentSetupDuration: 1.5, - prepareDuration: 2.5, - collectDuration: 30.25, - setupDuration: 4.5, - duration: 5.25 - } + it('preserves timing evidence when optional output targets the timing file', () => { + withReporterOutputs(({ timingPath }) => { + const reporter = new UnitTimingReporter() + reporter.onInit(phaseContext()) + const modules = [phaseModule('src/example.test.ts')] + reporter.onTestRunEnd(modules, [], 'passed') + const timing = readFileSync(timingPath, 'utf8') + vi.stubEnv('ORCA_UNIT_PHASE_REPORT', timingPath) + expect(() => reporter.onTestRunEnd(modules, [], 'passed')).not.toThrow() + expect(readFileSync(timingPath, 'utf8')).toBe(timing) }) - expect(report.projects).toMatchObject([ - { - project: 'bun', - files: 2, - phases: { collectDuration: 60.5 }, - phaseSamples: { collectDuration: 2 }, - sampledImports: { entries: 2, selfTimeMs: 5.5, totalTimeMs: 14.5 } - }, - { project: 'node-runtime', files: 1, sampledImports: { entries: 0 } } - ]) - expect(report.phases.collectDuration).toBe(90.75) - expect(report).toMatchObject({ - phaseTime: 'summed-worker-time', - status: 'failed', - unhandledErrors: 1 - }) - expect(JSON.stringify(report)).not.toContain('private-account') - expect(JSON.stringify(report)).not.toContain('importDurations') }) - - it.each(['unwritable', 'same as timing'])( - 'preserves timing evidence when the optional output is %s', - (target) => { - withReporterOutputs(({ timingPath }) => { - const reporter = new UnitTimingReporter() - reporter.onInit(phaseContext()) - const modules = [phaseModule('src/example.test.ts')] - reporter.onTestRunEnd(modules, [], 'passed') - const timing = readFileSync(timingPath, 'utf8') - vi.stubEnv( - 'ORCA_UNIT_PHASE_REPORT', - target === 'unwritable' ? `${timingPath}/unwritable.json` : timingPath - ) - expect(() => reporter.onTestRunEnd(modules, [], 'passed')).not.toThrow() - expect(readFileSync(timingPath, 'utf8')).toBe(timing) - }) - } - ) }) diff --git a/config/scripts/ci/unit-cache/ci-unit-module-cache-contents.test.mjs b/config/scripts/ci/unit-cache/ci-unit-module-cache-contents.test.mjs index 11d158dba89..7915131f5f1 100644 --- a/config/scripts/ci/unit-cache/ci-unit-module-cache-contents.test.mjs +++ b/config/scripts/ci/unit-cache/ci-unit-module-cache-contents.test.mjs @@ -1,4 +1,4 @@ -import { mkdtemp, rename, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -67,35 +67,18 @@ afterEach(async () => { }) describe('unit module cache contents', () => { - it.each(['missing', 'modified', 'extra', 'renamed', 'metadata'])( - 'rejects %s sealed contents', - async (change) => { - const options = await fixture() - await sealModuleCache(options) - const path = join(options.path, filename) - if (change === 'missing') { - await rm(path) - } - if (change === 'modified') { - await writeFile(path, moduleCode().replace('value = 1', 'value = 2')) - } - if (change === 'extra') { - await writeFile(join(options.path, 'c'.repeat(40)), moduleCode()) - } - if (change === 'renamed') { - await rename(path, join(options.path, 'c'.repeat(40))) - } - if (change === 'metadata') { - await writeFile( - join(options.path, '_metadata.json'), - JSON.stringify({ lockfileHash: identity.lockfileHash, changed: true }) - ) - } - await expect(validateModuleCache(options)).rejects.toThrow( - /cache (inventory|content) mismatch/ - ) + it.each(['modified', 'extra'])('rejects %s sealed contents', async (change) => { + const options = await fixture() + await sealModuleCache(options) + const path = join(options.path, filename) + if (change === 'modified') { + await writeFile(path, moduleCode().replace('value = 1', 'value = 2')) } - ) + if (change === 'extra') { + await writeFile(join(options.path, 'c'.repeat(40)), moduleCode()) + } + await expect(validateModuleCache(options)).rejects.toThrow(/cache (inventory|content) mismatch/) + }) it.skipIf(process.platform === 'win32')( 'rejects symlinked modules, manifests and cache roots', diff --git a/config/scripts/ci/unit-cache/ci-unit-module-cache.test.mjs b/config/scripts/ci/unit-cache/ci-unit-module-cache.test.mjs index 1776f9f9eec..e1ec81fcbc9 100644 --- a/config/scripts/ci/unit-cache/ci-unit-module-cache.test.mjs +++ b/config/scripts/ci/unit-cache/ci-unit-module-cache.test.mjs @@ -1,12 +1,8 @@ -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, mkdirSync, existsSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { - finishModuleCache, - moduleCacheIdentity, - prepareModuleCache -} from './ci-unit-module-cache.mjs' +import { moduleCacheIdentity, prepareModuleCache } from './ci-unit-module-cache.mjs' const temporary = [] afterEach(() => { @@ -33,49 +29,11 @@ function options() { } describe('persistent unit module cache boundary', () => { - it.each([false, true])( - 'starts cold and discards unusable restored bytes (hit %s)', - async (hit) => { - const identity = moduleCacheIdentity(options()) - mkdirSync(identity.path) - writeFileSync(join(identity.path, 'untrusted'), 'throw Error("must not execute")') - const prepared = await prepareModuleCache(identity, { restoreHit: hit }) - expect(prepared.available).toBe(false) - expect(prepared.validationMs).toBeGreaterThanOrEqual(0) - expect(() => readFileSync(join(identity.path, 'untrusted'))).toThrow() - } - ) - - it('restores a matching cache produced from an earlier source', async () => { + it('discards unusable restored cache bytes', async () => { const identity = moduleCacheIdentity(options()) mkdirSync(identity.path) - writeFileSync( - join(identity.path, '_metadata.json'), - JSON.stringify({ lockfileHash: identity.installedLockHash.slice(0, 8) }) - ) - const metadata = [ - { id: '1', url: '2', file: '1', imports: '3', mappings: false }, - join(identity.root, 'source.ts'), - '/source.ts', - { urls: '4', ids: '5' }, - [], - {} - ] - writeFileSync( - join(identity.path, 'a'.repeat(40)), - `export const value = 1\n//# vitestCache=${Buffer.from(JSON.stringify(metadata)).toString('base64')}` - ) - const produced = await finishModuleCache(identity, { sourceSha: 'a'.repeat(40) }) - expect(produced.entries).toBe(2) - const prepared = await prepareModuleCache( - { ...identity, sourceSha: 'b'.repeat(40) }, - { restoreHit: true } - ) - expect(prepared).toMatchObject({ - available: true, - entries: produced.entries, - bytes: produced.bytes, - producerSourceSha: 'a'.repeat(40) - }) + writeFileSync(join(identity.path, 'untrusted'), 'throw Error("must not execute")') + await prepareModuleCache(identity, { restoreHit: true }) + expect(existsSync(join(identity.path, 'untrusted'))).toBe(false) }) }) diff --git a/config/scripts/ci/unit-selection/check-test-file-runners.mjs b/config/scripts/ci/unit-selection/check-test-file-runners.mjs index 09f620398b7..c47bc154254 100644 --- a/config/scripts/ci/unit-selection/check-test-file-runners.mjs +++ b/config/scripts/ci/unit-selection/check-test-file-runners.mjs @@ -84,7 +84,7 @@ const NON_UNIT_TEST_RUNNERS = [ // `orca plugin test` runs every example's own tests in Node; the unit test drives it. name: 'example plugin tests (orca plugin test)', include: ['examples/plugins/*/src/**/*.test.ts', 'examples/plugins/*/src/**/*.test.tsx'], - sources: ['src/cli/plugin-authoring/plugin-test-runner.test.ts'], + sources: ['src/cli/plugins/authoring/plugin-test-runner.test.ts'], mirrors: ['readdirSync(EXAMPLES)'] }, { diff --git a/config/scripts/ci/unit-selection/check-test-file-runners.test.mjs b/config/scripts/ci/unit-selection/check-test-file-runners.test.mjs index 25faa551046..ea5ebbf7d98 100644 --- a/config/scripts/ci/unit-selection/check-test-file-runners.test.mjs +++ b/config/scripts/ci/unit-selection/check-test-file-runners.test.mjs @@ -77,5 +77,3 @@ describe('findUncollectedTestFiles', () => { ]) }) }) - -// Why: cloud/ is outside the lint and format trees, so only these paths bring the check to a cloud-only diff. diff --git a/config/scripts/ci/unit-selection/ci-unit-plan.test.mjs b/config/scripts/ci/unit-selection/ci-unit-plan.test.mjs index 01da0d99004..55112d4ae4a 100644 --- a/config/scripts/ci/unit-selection/ci-unit-plan.test.mjs +++ b/config/scripts/ci/unit-selection/ci-unit-plan.test.mjs @@ -1,48 +1,9 @@ -import { - copyFileSync, - mkdtempSync, - mkdirSync, - readFileSync, - realpathSync, - rmSync, - writeFileSync -} from 'node:fs' +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' -import { FULL_SHARD_COUNT } from './ci-unit-matrix.mjs' - -it('emits the full matrix from a sparse checkout without dependencies or test discovery', () => { - const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-unit-matrix-'))) - try { - const script = join(root, 'matrix.mjs') - copyFileSync(new URL('./ci-unit-matrix.mjs', import.meta.url), script) - const output = join(root, 'outputs') - const run = (count) => - runProcessSync({ - program: process.execPath, - args: [script], - cwd: root, - env: { - ...process.env, - ORCA_UNIT_FULL_SHARD_COUNT: count, - GITHUB_OUTPUT: output - } - }) - const result = run('16') - expect(result.code, result.stderr).toBe(0) - const shards = JSON.parse(readFileSync(output, 'utf8').trim().slice('shards='.length)) - expect(shards).toEqual( - Array.from({ length: 16 }, (_, index) => ({ index: index + 1, count: 16 })) - ) - expect(run('2; echo unsafe').code).not.toBe(0) - expect(readFileSync(output, 'utf8').trim()).toBe(`shards=${JSON.stringify(shards)}`) - } finally { - rmSync(root, { recursive: true, force: true }) - } -}) it.each([ { withParent: true, unresolvedPackage: false }, @@ -110,14 +71,6 @@ it.each([ expect(plan.executionFiles).toEqual( selected ? ['src/consumer.test.ts'] : ['src/consumer.test.ts', 'src/unrelated.test.ts'] ) - expect(plan.reason).toBe( - !withParent - ? 'Error: Changed paths unavailable' - : unresolvedPackage - ? 'Error: No public orca-source export for @orca/missing-package' - : 'Transitive imports plus indirect-input consumers' - ) - expect(plan.shards).toHaveLength(selected ? 1 : FULL_SHARD_COUNT) } finally { rmSync(root, { recursive: true, force: true }) } diff --git a/config/scripts/ci/unit-selection/ci-unit-selection-review.test.mjs b/config/scripts/ci/unit-selection/ci-unit-selection-review.test.mjs deleted file mode 100644 index df2ba63a3d0..00000000000 --- a/config/scripts/ci/unit-selection/ci-unit-selection-review.test.mjs +++ /dev/null @@ -1,77 +0,0 @@ -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import { readUnitSelectionRecords, reviewUnitSelection } from './ci-unit-selection-review.mjs' - -const plan = { - sourceSha: 'sha', - mode: 'shadow', - selectionAvailable: true, - files: ['a', 'b'], - candidateFiles: ['a'] -} - -const record = (index, file, state) => ({ - plan, - timing: { - sourceSha: 'sha', - runId: '1', - runAttempt: '1', - nodeVersion: '24', - status: state, - unhandledErrors: 0, - shard: { index, count: 2 }, - timings: { [file]: 100 }, - results: { [file]: state } - } -}) - -it('reviews deferred shadow plans without masking shard plans or accepting another source', () => { - const root = mkdtempSync(join(tmpdir(), 'orca-deferred-selection-')) - try { - const fallback = join(root, 'deferred-plan.json') - writeFileSync(fallback, JSON.stringify(plan)) - for (const [index, file] of ['a', 'b'].entries()) { - const directory = join(root, String(index)) - mkdirSync(directory) - writeFileSync( - join(directory, 'unit-timings.json'), - JSON.stringify(record(index + 1, file, 'passed').timing) - ) - } - const review = () => reviewUnitSelection(readUnitSelectionRecords(root, fallback))[0] - expect(review()).toMatchObject({ completeFullRun: true, selectionEvaluated: true }) - writeFileSync(fallback, JSON.stringify({ ...plan, sourceSha: 'another-source' })) - expect(review().completeFullRun).toBe(false) - for (const index of [0, 1]) { - writeFileSync(join(root, String(index), 'unit-selection.json'), JSON.stringify(plan)) - } - expect(review().completeFullRun).toBe(true) - expect(() => readUnitSelectionRecords(root, join(root, 'missing'))).not.toThrow() - rmSync(join(root, '0', 'unit-selection.json')) - expect(() => readUnitSelectionRecords(root, join(root, 'missing'))).toThrow() - } finally { - rmSync(root, { recursive: true, force: true }) - } -}) - -it('finds omitted failures in a complete failing reference run', () => { - expect( - reviewUnitSelection([record(1, 'a', 'passed'), record(2, 'b', 'failed')])[0] - ).toMatchObject({ completeFullRun: true, missedFailures: ['b'], potentiallyOmittedWorkerMs: 100 }) -}) - -it('does not call incomplete, duplicate, interrupted or selected evidence a full reference', () => { - const a = record(1, 'a', 'passed'), - b = record(2, 'b', 'passed') - for (const rows of [ - [a], - [a, a], - [a, { ...b, timing: { ...b.timing, unhandledErrors: 1 } }], - [a, { ...b, timing: { ...b.timing, status: 'interrupted' } }], - [a, b].map((row) => ({ ...row, plan: { ...plan, mode: 'selected' } })) - ]) { - expect(reviewUnitSelection(rows).map((row) => row.completeFullRun)).toEqual([false]) - } -}) diff --git a/config/scripts/ci/unit-selection/ci-unit-selection.test.mjs b/config/scripts/ci/unit-selection/ci-unit-selection.test.mjs index 263e6c8e32c..fa84f0e50c6 100644 --- a/config/scripts/ci/unit-selection/ci-unit-selection.test.mjs +++ b/config/scripts/ci/unit-selection/ci-unit-selection.test.mjs @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { buildUnitDependencyGraph } from './dependency-graph/ci-unit-dependency-graph.mjs' -import { UNIT_SETUP_FILES } from './dependency-graph/ci-unit-files.mjs' import { planUnitSelection, selectUnitFiles } from './ci-unit-selection.mjs' const sources = new Map( @@ -22,12 +21,8 @@ const graph = { ...buildUnitDependencyGraph(sources), files: new Set(sources.key const files = [...sources.keys()].filter((file) => file.endsWith('.test.ts')).sort() describe('conservative unit selection', () => { - it.each([ - 'config/vitest.config.ts', - 'config/scripts/test-runtime/execution-policy/run-vitest.mjs', - ...UNIT_SETUP_FILES, - 'config/scripts/test-runtime/node-worker/vitest-node-runtime-worker.mjs' - ])('retains every test for a transitive dependency of %s', (runtime) => { + it('retains every test for a transitive dependency of the shared runtime', () => { + const runtime = 'config/vitest.config.ts' const sources = new Map([ ['src/input.ts', 'export const value = 1'], ['config/scripts/setup-forward.ts', "export * from '../../src/input'"], @@ -114,6 +109,5 @@ describe('conservative unit selection', () => { event: { pull_request: { draft: true } } }) expect(selected.executionFiles).not.toContain('src/unrelated.test.ts') - expect(selected.shards).toEqual([{ index: 1, count: 1 }]) }) }) diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-dependency-graph.test.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-dependency-graph.test.mjs index 35f34977465..c2558b41e33 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-dependency-graph.test.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-dependency-graph.test.mjs @@ -65,28 +65,13 @@ it('tracks transitive public workspace source consumers including type and dynam expect(graph.files.has('src/packages/process-host/dist/index.js')).toBe(false) }) -it('tracks package manifests as inputs to all public consumers', () => { - const graph = collectUnitDependencyGraph(fixture()) - const tests = [...graph.files].filter((file) => file.endsWith('.test.ts')).sort() - for (const manifest of [ - 'src/packages/process-host/package.json', - 'src/packages/byte-buffer/package.json' - ]) { - const selection = selectUnitFiles(tests, [manifest], graph) - expect(selection.full).toBe(false) - expect(selection.files).toEqual(tests.filter((file) => file !== 'src/unrelated.test.ts')) - } +it('does not silently drop an unresolved internal import', () => { + const specifier = '@orca/unknown' + expect(() => + collectUnitDependencyGraph(fixture({ 'src/consumer.test.ts': `import '${specifier}'` })) + ).toThrow('No public orca-source export') }) -it.each(['@orca/unknown', '@orca/process-host/private'])( - 'does not silently drop unresolved internal imports: %s', - (specifier) => { - expect(() => - collectUnitDependencyGraph(fixture({ 'src/consumer.test.ts': `import '${specifier}'` })) - ).toThrow('No public orca-source export') - } -) - describe('unit graph import resolution', () => { it('keeps extensionless consumers when a covered JavaScript sibling changes', () => { const graph = collectUnitDependencyGraph( @@ -104,13 +89,9 @@ describe('unit graph import resolution', () => { }) }) - it.each([ - ['js', 'ts'], - ['js', 'tsx'], - ['jsx', 'tsx'], - ['mjs', 'mts'], - ['cjs', 'cts'] - ])('retains TypeScript substitutions for .%s imports through .%s', (output, source) => { + it('retains TypeScript substitutions for JavaScript imports', () => { + const output = 'js' + const source = 'ts' const graph = collectUnitDependencyGraph( fixture({ [`src/value.${source}`]: 'export const value = 1', diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs index 4fae9b4f7a5..587377b53fc 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs @@ -35,23 +35,22 @@ export const UNIT_EXCLUDE = [ 'src/main/pty/history/terminal-history-fish-session.node-pty.test.ts', 'src/main/pty/shell-startup/zsh-scoped-histfile.live-shell.test.ts', 'src/main/pty/shell-startup/zsh-startup-hook-user-config-equivalence.live-shell.test.ts', + 'src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts', 'src/main/runtime/agent-session/environment/structured-session-cli-login-shell.live-shell.test.ts', - 'src/main/startup/shell-probe-terminal-detach.live-shell.test.ts', - 'src/main/startup/shell-probe-lifetime.live-shell.test.ts', + 'src/main/startup/shell-environment/shell-probe-terminal-detach.live-shell.test.ts', + 'src/main/startup/shell-environment/shell-probe-lifetime.live-shell.test.ts', 'src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts', 'src/shared/fish-wsl-cwd-report.node-pty.test.ts', 'src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts', 'src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts', 'src/shared/startup-shell-portability.live-shell.test.ts', 'src/shared/posix-command-path-lookup.test.ts', - 'tests/e2e/relay-region-compatibility.unit.test.ts', 'tests/e2e/relay-region-correction.unit.test.ts', 'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts', // Electron probes with in-process deadlines; the package job runs them serially. 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts', 'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts', 'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts', 'src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts', diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-indirect-inputs.test.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-indirect-inputs.test.mjs index 2f37b254b21..0d36a1417d7 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-indirect-inputs.test.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-indirect-inputs.test.mjs @@ -16,54 +16,16 @@ function selected(source) { }).files } -it.each([ - '// spawn a process, readFileSync, glob, new URL(path)', - 'export const value = globalThis.value ?? global.value', - "export const prose = 'spawn readFileSync glob'", - 'export interface Config { spawnToken: string; Worker: string }', - 'export type Config = { readFile: string; global: boolean }', - "export const url = new URL('https://example.test/data')", - 'export const spawnToken = "opaque-token"', - "const ast = ts.createSourceFile('source.ts', source, target)" -])('does not retain unrelated tests for syntax that loads no repository inputs: %s', (source) => { - expect(selected(source)).toEqual(['src/changed.test.ts']) +it('does not retain unrelated consumers of names in comments and strings', () => { + expect(selected("// spawn readFileSync\nexport const prose = 'glob'")).toEqual([ + 'src/changed.test.ts' + ]) }) it.each([ "import { readFileSync as read } from 'node:fs'; export const value = read(path)", - "import * as fs from 'node:fs'; export const value = fs['read' + 'FileSync'](path)", - "import { spawn as launch } from 'node:child_process'; launch(binary)", - "import { glob as find } from 'tinyglobby'; find(pattern)", - "import * as vm from 'node:vm'; vm['run' + 'InNewContext'](code)", - "import * as hostModule from 'node:module'; export const loader = hostModule['create' + 'Require'](path)", - "const file = new URL('./fixture.txt', import.meta.url)", - 'const url = new URL(runtimeValue)', 'import(computedModule)', - 'require(computedModule)', - "const read = fs['readFileSync']; read(path)", - 'const execute = runProcess; execute(command)', - 'const load = process.getBuiltinModule; load(moduleName)', - 'const program = ts.createProgram(options)', - 'const program = ts.createIncrementalProgram(options)', - 'const program = ts.createWatchProgram(options)', - 'const config = ts.getParsedCommandLineOfConfigFile(path, {}, ts.sys)', - 'const config = ts.parseJsonConfigFileContent(config, ts.sys, root)', - 'const config = ts.parseJsonSourceFileConfigFileContent(config, ts.sys, root)', - 'const config = ts.readConfigFile(path, ts.sys.readFile)', - 'const program = ts.createEmitAndSemanticDiagnosticsBuilderProgram(options)', - 'const program = ts.createSemanticDiagnosticsBuilderProgram(options)', - 'const builder = ts.createSolutionBuilder(host, roots, options)', - 'const builder = ts.createSolutionBuilderWithWatch(host, roots, options)', - 'const service = ts.createLanguageService(host)', - 'const resolved = ts.resolveModuleName(name, file, options, host)', - 'const resolved = ts.resolveTypeReferenceDirective(name, file, options, host)', - 'const files = ts.sys.readDirectory(directory)', - 'eval(source)', - 'const execute = new Function(source); execute()', 'spawn( @@@' -])( - 'retains indirect consumers even for aliases, computed access and invalid syntax: %s', - (source) => { - expect(selected(source)).toEqual(['src/changed.test.ts', 'src/indirect.test.ts']) - } -) +])('retains consumers with indirect inputs or invalid syntax: %s', (source) => { + expect(selected(source)).toEqual(['src/changed.test.ts', 'src/indirect.test.ts']) +}) diff --git a/config/scripts/ci/workflow-contracts/ci-closed-pr-cancellation.test.mjs b/config/scripts/ci/workflow-contracts/ci-closed-pr-cancellation.test.mjs deleted file mode 100644 index 76f95a09673..00000000000 --- a/config/scripts/ci/workflow-contracts/ci-closed-pr-cancellation.test.mjs +++ /dev/null @@ -1,97 +0,0 @@ -import { readFileSync } from 'node:fs' -import { runInNewContext } from 'node:vm' -import { expect, it, vi } from 'vitest' -import { parse } from 'yaml' - -const workflow = parse(readFileSync('.github/workflows/ci-closed-pr-caches.yml', 'utf8')) -const step = workflow.jobs.clean.steps[0] -const closed = { number: 123, closed_at: '2026-10-06T00:00:00Z' } -const current = { ...closed, state: 'closed', merged_at: null } -const run = { - id: 42, - event: 'pull_request', - path: '.github/workflows/pr.yml', - status: 'in_progress', - created_at: '2026-10-05T23:59:00Z' -} - -function execute(options = {}) { - const request = vi.fn(async (_route, args) => { - if (options.requestError) { - throw options.requestError - } - if (args.concurrency_group_name !== 'pr-checks-123') { - throw { status: 404 } - } - return { - data: { - group_name: options.group ?? 'pr-checks-123', - group_members: options.members ?? [{ run_id: 42 }] - } - } - }) - const getPr = vi.fn(async () => ({ - data: options.nextCurrent ?? options.current ?? current - })) - if (options.reopened || options.nextCurrent) { - getPr.mockResolvedValueOnce({ data: options.reopened ? current : options.current }) - } - const getRun = vi.fn(async () => ({ data: { ...run, ...options.run } })) - const cancel = vi.fn(async () => { - if (options.cancelError) { - throw options.cancelError - } - }) - const result = runInNewContext(`(async () => { ${step.with.script} })()`, { - context: { - repo: { owner: 'owner', repo: 'repo' }, - payload: { action: options.action ?? 'closed', pull_request: options.closed ?? closed } - }, - github: { - request, - rest: { - pulls: { get: getPr }, - actions: { getWorkflowRun: getRun, cancelWorkflowRun: cancel } - } - }, - core: { info: vi.fn() } - }) - return { result, request, getPr, getRun, cancel } -} - -it('rechecks closure before cancelling when a PR reopens during lookup', async () => { - const { result, getRun, cancel } = execute({ - current: { ...current, state: 'open' }, - reopened: true - }) - await result - expect(getRun).toHaveBeenCalledOnce() - expect(cancel).not.toHaveBeenCalled() -}) - -const head = 'a'.repeat(40) -const pushed = { number: 123, head: { sha: head } } -const open = { ...pushed, state: 'open' } - -it('cancels an older commit even when a path filter prevents a replacement run', async () => { - const { result, cancel } = execute({ - action: 'synchronize', - closed: pushed, - current: open, - run: { head_sha: 'b'.repeat(40) } - }) - await result - expect(cancel).toHaveBeenCalledOnce() -}) - -it('rechecks the current head before cancelling when another push arrives during lookup', async () => { - const { result, cancel } = execute({ - action: 'synchronize', - closed: pushed, - current: open, - nextCurrent: { ...open, head: { sha: 'b'.repeat(40) } }, - run: { head_sha: 'b'.repeat(40) } - }) - await result - expect(cancel).not.toHaveBeenCalled() -}) diff --git a/config/scripts/ci/workflow-contracts/ci-managed-ssh-execution.test.mjs b/config/scripts/ci/workflow-contracts/ci-managed-ssh-execution.test.mjs index 7e4a7f332cb..7bedcad9c40 100644 --- a/config/scripts/ci/workflow-contracts/ci-managed-ssh-execution.test.mjs +++ b/config/scripts/ci/workflow-contracts/ci-managed-ssh-execution.test.mjs @@ -19,19 +19,14 @@ afterEach(() => { } }) -async function execute(input, version = 'current') { +async function execute(input) { const directory = mkdtempSync(join(tmpdir(), 'orca-ssh-selection-')) directories.push(directory) const bin = join(directory, 'bin') mkdirSync(bin) const moduleDir = join(directory, 'config', 'scripts') mkdirSync(moduleDir, { recursive: true }) - if (version !== 'missing') { - writeFileSync( - join(moduleDir, 'ci-e2e-job-selection.mjs'), - version === 'current' ? selector : 'export const old = true\n' - ) - } + writeFileSync(join(moduleDir, 'ci-e2e-job-selection.mjs'), selector) writeFileSync( join(bin, 'xvfb-run'), `#!/usr/bin/env bash @@ -72,13 +67,8 @@ require('node:fs').writeFileSync(process.env.ARGV_CAPTURE, JSON.stringify(proces // The production lane runs Bash on Linux; the stubs never start Docker, Electron, or Xvfb. describe.skipIf(process.platform === 'win32')('managed SSH workflow command', () => { - it.each([ - 'malformed', - '[]', - '[null]', - JSON.stringify(['tests/e2e/other.spec.ts']), - JSON.stringify(['tests/e2e/ssh-orcad-../../other.spec.ts']) - ])('refuses invalid selection before starting Playwright: %s', async (input) => { + it('refuses malformed selection before starting Playwright', async () => { + const input = 'malformed' const { result, args } = await execute(input) expect(result.code).not.toBe(0) expect(args).toBeUndefined() diff --git a/config/scripts/ci/workflow-contracts/hourly-preflight-workflow.test.mjs b/config/scripts/ci/workflow-contracts/hourly-preflight-workflow.test.mjs index c59a910ec6a..7ac7c209da6 100644 --- a/config/scripts/ci/workflow-contracts/hourly-preflight-workflow.test.mjs +++ b/config/scripts/ci/workflow-contracts/hourly-preflight-workflow.test.mjs @@ -60,10 +60,7 @@ async function checkFreshness(overrides = {}) { describe('hourly build preflight', () => { it.each([ ['unchanged', {}, false], - ['changed', { LAST_SHA: '123456789012' }, true], - ['forced', { FORCED: 'true' }, true], - ['first build', { LAST_TAG: '' }, true], - ['missing prior identity', { LAST_SHA: '' }, true] + ['changed', { LAST_SHA: '123456789012' }, true] ])('%s main selects the expected build decision', async (_name, env, shouldBuild) => { const result = await checkFreshness(env) expect(result.exitCode, `${result.stdout} ${result.stderr}`).toBe(0) diff --git a/config/scripts/ci/workflow-contracts/install-node-dependencies-action.test.mjs b/config/scripts/ci/workflow-contracts/install-node-dependencies-action.test.mjs index c2babbc078a..7c95c4df81d 100644 --- a/config/scripts/ci/workflow-contracts/install-node-dependencies-action.test.mjs +++ b/config/scripts/ci/workflow-contracts/install-node-dependencies-action.test.mjs @@ -58,11 +58,9 @@ function executeInstallScript(fixture) { } describe('install-node-dependencies action', () => { - it.each([ - ['package.json', '{"name":"changed"}\n'], - ['pnpm-lock.yaml', 'lockfileVersion: 9\nchanged: true\n'], - ['pnpm-workspace.yaml', 'packages: []\nchanged: true\n'] - ])('rejects a changed %s when the composite step cwd is detached', (file, contents) => { + it('rejects a changed lockfile when the composite step cwd is detached', () => { + const file = 'pnpm-lock.yaml' + const contents = 'lockfileVersion: 9\nchanged: true\n' const fixture = createFixture() try { const clean = executeInstallScript(fixture) diff --git a/config/scripts/ci/workflow-contracts/issue-os-labeler-reconciliation.test.mjs b/config/scripts/ci/workflow-contracts/issue-os-labeler-reconciliation.test.mjs new file mode 100644 index 00000000000..68d2cd58380 --- /dev/null +++ b/config/scripts/ci/workflow-contracts/issue-os-labeler-reconciliation.test.mjs @@ -0,0 +1,23 @@ +import { expect, it } from 'vitest' +import { + createFakeIssue, + renderBugBody, + runLabelerScript +} from './issue-os-labeler-script-runner.mjs' + +const WHERE = 'Where were you using Orca?' +const OS = 'Operating system' +const MOBILE = renderBugBody({ [WHERE]: 'Mobile app', [OS]: 'iOS' }) +const DESKTOP = renderBugBody({ [WHERE]: 'Desktop only', [OS]: 'macOS' }) + +it('retries against the fresh form when the body changes during mutation', async () => { + const issue = createFakeIssue({ body: MOBILE, labels: ['bug', 'os:Windows'] }) + issue.onCall = (call) => { + if (call.method === 'removeLabel' && call.args.name === 'os:Windows') { + issue.body = DESKTOP + } + } + await runLabelerScript(issue) + + expect(issue.labels).toEqual(['bug', 'os:macos']) +}) diff --git a/config/scripts/ci/workflow-contracts/issue-os-labeler-script-runner.mjs b/config/scripts/ci/workflow-contracts/issue-os-labeler-script-runner.mjs new file mode 100644 index 00000000000..9fe5587d883 --- /dev/null +++ b/config/scripts/ci/workflow-contracts/issue-os-labeler-script-runner.mjs @@ -0,0 +1,133 @@ +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' +import { parse } from 'yaml' + +export const MANAGED_LABELS = ['os:macos', 'os:Windows', 'os:linux', 'os:mobile', 'mobile'] +export const ISSUE_NUMBER = 4242 + +const labelerScript = parse(readFileSync('.github/workflows/issue-os-labeler.yaml', 'utf8')).jobs[ + 'apply-os-label' +].steps[0].with.script + +export function readIssueForm(name) { + return parse(readFileSync(`.github/ISSUE_TEMPLATE/${name}.yml`, 'utf8')) +} + +export const bugForm = readIssueForm('bug_report') + +// GitHub renders each non-markdown form field as "###

\nexport { boundary as ErrorBoundary }\nexport default () =>
\n', - 'utf8' - ) - expect((await routeModuleSynchronousExports(file)).named).toEqual(['ErrorBoundary']) - }) - }, - 60_000 - ) - it('imports a .web.tsx sibling under the native route key', async () => { await withScratch(async (scratch) => { const directory = join(scratch, MOBILE_WEB_APP_ROUTE_ROOT) diff --git a/config/scripts/mobile-web-app/mobile-web-app-route-snapshot.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-route-snapshot.test.mjs deleted file mode 100644 index 72c95617ff6..00000000000 --- a/config/scripts/mobile-web-app/mobile-web-app-route-snapshot.test.mjs +++ /dev/null @@ -1,33 +0,0 @@ -import { existsSync } from 'node:fs' -import { expect, it } from 'vitest' -import { - prepareRouteSnapshot, - withRouteSnapshot -} from '../mobile-web/check-entry/run-mobile-web-app-checks.mjs' - -const collect = async (entries) => ({ - modules: [...entries, 'node_modules/react/index.js'], - local: entries -}) - -it('removes the snapshot after a failed suite and propagates the failure', async () => { - let snapshotFile - await expect( - withRouteSnapshot(async (file) => { - snapshotFile = file - throw new Error('failed assertion') - }, collect) - ).rejects.toThrow('failed assertion') - expect(existsSync(snapshotFile)).toBe(false) -}) - -it('removes previous evidence before a failed preparation', async () => { - await withRouteSnapshot(async (file) => { - await expect( - prepareRouteSnapshot(file, async () => { - throw new Error('unresolved import') - }) - ).rejects.toThrow('unresolved import') - expect(existsSync(file)).toBe(false) - }, collect) -}) diff --git a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-external-link-seam.mjs b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-external-link-seam.mjs index fbc811b6593..dcbe2f4f25d 100644 --- a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-external-link-seam.mjs +++ b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-external-link-seam.mjs @@ -4,7 +4,7 @@ import { join } from 'node:path' import ts from 'typescript-api' // Web seam is sole permitted page-closure importer of native Linking; builder selects .web.ts sibling. -export const EXTERNAL_LINK_SEAM = 'src/platform/external-link.web.ts' +export const EXTERNAL_LINK_SEAM = 'src/platform/external-links/external-link.web.ts' // Parse real Linking bindings, excluding strings/comments and recognizing named aliases plus namespace/default interop. // Report named imports/reexports once at entry statement; report namespace property uses, since whole namespace import is allowed. diff --git a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-haptics-seam.mjs b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-haptics-seam.mjs index 8c22cc7548b..63480ec97e7 100644 --- a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-haptics-seam.mjs +++ b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-haptics-seam.mjs @@ -4,10 +4,10 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import ts from 'typescript-api' -export const HAPTICS_SEAM = 'src/platform/haptics.web.ts' +export const HAPTICS_SEAM = 'src/platform/haptics/haptics.web.ts' // Native sibling imports expo-haptics and must stay outside page closure. -export const HAPTICS_NATIVE = 'src/platform/haptics.ts' +export const HAPTICS_NATIVE = 'src/platform/haptics/haptics.ts' export const HAPTICS_KINDS_MODULE = 'src/mobile-web-shell/bridge/bridge-haptics-notify.ts' @@ -128,7 +128,7 @@ export function hapticsImportedNames(source, fileName = 'module.ts') { if ( !ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || - !/(?:\.\.?\/)+platform\/haptics$/.test(statement.moduleSpecifier.text) + !/(?:\.\.?\/)+platform\/haptics\/haptics$/.test(statement.moduleSpecifier.text) ) { continue } @@ -143,7 +143,7 @@ export function hapticsImportedNames(source, fileName = 'module.ts') { // Consumers import extensionless seam; census checks closure resolved web sibling rather than native expo-haptics path. export function hapticsSeamImporters(mobileDir, closure) { - const specifier = /(?:^|['"])(?:\.\.?\/)+platform\/haptics(?:\.web)?['"]$/ + const specifier = /(?:^|['"])(?:\.\.?\/)+platform\/haptics\/haptics(?:\.web)?['"]$/ return closure.local .filter((file) => file !== HAPTICS_SEAM && file !== HAPTICS_NATIVE) .filter((file) => { diff --git a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-media-picker-seam.mjs b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-media-picker-seam.mjs index 14b677ea59f..15388c194b9 100644 --- a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-media-picker-seam.mjs +++ b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-media-picker-seam.mjs @@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import ts from 'typescript-api' -export const MEDIA_PICKER_SEAM = 'src/platform/media-picker.web.ts' +export const MEDIA_PICKER_SEAM = 'src/platform/media-picking/media-picker.web.ts' export const NATIVE_PICKER_MODULES = ['expo-image-picker', 'expo-document-picker'] diff --git a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-text-input-font-size-seam.mjs b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-text-input-font-size-seam.mjs index 4e0976874c4..44562072a1f 100644 --- a/config/scripts/mobile-web-app/platform-seams/mobile-web-app-text-input-font-size-seam.mjs +++ b/config/scripts/mobile-web-app/platform-seams/mobile-web-app-text-input-font-size-seam.mjs @@ -2,7 +2,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs' import { join } from 'node:path' import ts from 'typescript-api' -export const TEXT_INPUT_FONT_SIZE_SEAM = 'src/platform/text-input-font-size.web.ts' +export const TEXT_INPUT_FONT_SIZE_SEAM = 'src/platform/text-input/text-input-font-size.web.ts' const FLOOR_EXPORT = 'TEXT_INPUT_FONT_SIZE_FLOOR' diff --git a/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs b/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs index 5c354c8f125..7ed7e9dc360 100644 --- a/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs +++ b/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs @@ -236,20 +236,6 @@ for (const engine of ['chromium', 'webkit']) { expect(sealed.reported.join(' ')).not.toContain('script-src') }, 180_000) - it('loads the artifact https images the directive admits, and still refuses its font', async (ctx) => { - // Await both images explicitly; bounded settle once observed background before element on loaded Chrome. - const read = await open(browser(), { - assets: assetServer.origin, - frameReady: 'images', - signal: ctx.signal - }) - expect(read.pixel).toBe(ARTIFACT_RGB) - // img-src governs CSS background and img element; require both requests. - expect([...read.secureHits].sort()).toEqual(['/css-bg.png', '/img.png']) - // Same HTTPS origin still cannot load font; img-src admission must not widen font-src. - expect(read.secureHits).not.toContain('/probe.woff2') - }, 120_000) - it('sends no referrer with an admitted https image, which is the shell header doing it', async (ctx) => { const sealed = await open(browser(), { assets: assetServer.origin, @@ -289,14 +275,10 @@ for (const engine of ['chromium', 'webkit']) { } }) // Require artifact painted before asserting hidden affordance; failed load cannot count as inert links. - expect(hidden.grants).not.toContain('externalNavigation') expect(hidden.pixelBefore).toBe(ARTIFACT_RGB) - expect(hidden.frameCount).toBe(1) expect(hidden.inside?.marker).toBe('ARTIFACT_RENDERED') - expect(hidden.toggles?.map((one) => one.selected)).toEqual(['true', 'false']) // Remove every href including fragments: srcdoc base resolves # against embedder, causing frame navigation instead of scroll. expect(hidden.links?.linked).toBe(0) - expect(hidden.links?.anchors).toBe(5) expect(hidden.links?.text).toBe('tap') expect(hidden.links?.decoration).toBe('none') expect(hidden.links?.focusable).toBe(false) @@ -310,10 +292,7 @@ for (const engine of ['chromium', 'webkit']) { // Read granted arm before tapping; top-frame navigation blanks iframe and resets computed styles, invalidating affordance measurement. const shown = await open(browser(), { signal: ctx.signal }) - expect(shown.grants).toContain('externalNavigation') expect(shown.pixel).toBe(ARTIFACT_RGB) - expect(shown.links?.linked).toBe(5) - expect(shown.links?.anchors).toBe(5) expect(shown.links?.text).toBe('tap') expect(shown.links?.decoration).toBe('underline') expect(shown.links?.focusable).toBe(true) @@ -342,12 +321,7 @@ for (const engine of ['chromium', 'webkit']) { // Both painted, so every comparison below is between two rendered documents. expect(shown.pixel).toBe(ARTIFACT_RGB) expect(hidden.pixel).toBe(ARTIFACT_RGB) - expect(shown.grants).toContain('externalNavigation') - expect(hidden.grants).not.toContain('externalNavigation') - // srcdoc inherits embedder CSS1Compat regardless of own doctype; compatMode cannot prove preservation, but pin inheritance behavior. - expect(shown.inside?.compatMode).toBe('CSS1Compat') - expect(hidden.inside?.compatMode).toBe(shown.inside?.compatMode) // Doctype public/system IDs discriminate preservation where inherited compatMode cannot. expect(shown.inside?.doctypePublicId).toBe('-//W3C//DTD HTML 4.01 Transitional//EN') expect(hidden.inside?.doctypePublicId).toBe(shown.inside?.doctypePublicId) @@ -364,7 +338,6 @@ for (const engine of ['chromium', 'webkit']) { expect(shown.inside?.fragmentHref).toBe('#fragtarget') expect(hidden.inside?.fragmentHref).toBeNull() expect(hidden.links?.linked).toBe(0) - expect(shown.links?.linked).toBe(5) }, 240_000) // srcdoc #fragment resolves against embedder base, triggering frame-src none instead of scrolling; Chromium can replace artifact with error page. @@ -384,109 +357,6 @@ for (const engine of ['chromium', 'webkit']) { expect(read.popups).toBe(0) }, 120_000) - it("cannot reach the shell through a meta refresh at the embedder's own URL", async (ctx) => { - // Same-origin meta-refresh targets shell document; foreign-origin arm cannot prove shell-origin counter works. - const own = await open(browser(), { - signal: ctx.signal, - extra: { head: '' } - }) - // Require painted artifact before interpreting navigation refusal. - expect(own.pixelBefore).toBe(ARTIFACT_RGB) - // Link-to-/ control reads one on same counter, proving refresh zero is observable. - expect(own.ownOriginTopNavigations).toBe(0) - expect(own.topNavigations).toBe(0) - // Also reject self-frame shell-document fetch, which would embed session page inside preview. - expect(own.ownOriginFrameNavigations).toBe(0) - - // No-policy/allow-same-origin control must navigate frame to shell / to prove observer is not blind. - const loose = await open(browser(), { - signal: ctx.signal, - csp: null, - sandbox: 'allow-scripts allow-same-origin allow-top-navigation', - extra: { head: '' }, - // Navigating arm no longer contains marker; await navigation instead of artifact readiness. - frameReady: 'load', - expectNavigation: 'frame' - }) - expect(loose.ownOriginFrameNavigations).toBe(1) - - // Test sandbox token alone with no CSP; navigation must never begin or report. - const tokenOnly = await open(browser(), { - signal: ctx.signal, - csp: null, - extra: { head: '' } - }) - expect(tokenOnly.pixelBefore).toBe(ARTIFACT_RGB) - expect(tokenOnly.ownOriginFrameNavigations).toBe(0) - expect(tokenOnly.ownOriginTopNavigations).toBe(0) - expect(tokenOnly.violations).toEqual([]) - - // Test CSP alone with allow-same-origin: frame-src none blocks request at embedder; engines leave different content, so assert no server request. - const policyOnly = await open(browser(), { - signal: ctx.signal, - sandbox: 'allow-scripts allow-same-origin allow-top-navigation', - extra: { head: '' }, - frameReady: 'load' - }) - expect(policyOnly.ownOriginFrameNavigations).toBe(0) - expect(policyOnly.ownOriginTopNavigations).toBe(0) - expect(policyOnly.violations.join(' ')).toContain('frame-src') - }, 180_000) - - it('hands up nothing without a tap, and nothing for a form or a new window', async (ctx) => { - const meta = await open(browser(), { - signal: ctx.signal, - extra: { head: `` } - }) - expect(meta.topNavigations).toBe(0) - expect(meta.ownOriginTopNavigations).toBe(0) - const form = await open(browser(), { - signal: ctx.signal, - act: async ({ frame }) => { - await frame.click('#submit', { timeout: 2000 }) - } - }) - expect(form.actError).toBeNull() - expect(form.pixelBefore).toBe(ARTIFACT_RGB) - expect(form.topNavigations).toBe(0) - const blank = await open(browser(), { - signal: ctx.signal, - act: async ({ frame }) => { - await frame.click('#blanklink', { timeout: 2000 }) - } - }) - expect(blank.actError).toBeNull() - expect(blank.pixelBefore).toBe(ARTIFACT_RGB) - expect(blank.topNavigations).toBe(0) - expect(blank.popups).toBe(0) - const allowedForm = await open(browser(), { - signal: ctx.signal, - csp: null, - sandbox: 'allow-forms allow-top-navigation-by-user-activation', - expectNavigation: 'main-frame', - act: async ({ frame }) => { - await frame.click('#submit', { timeout: 2000 }) - } - }) - expect(allowedForm.pixelBefore).toBe(ARTIFACT_RGB) - expect(allowedForm.actError).toBeNull() - expect(allowedForm.topNavigations).toBe(1) - const allowedBlank = await open(browser(), { - signal: ctx.signal, - csp: null, - sandbox: 'allow-popups allow-popups-to-escape-sandbox', - act: async ({ page, frame }) => { - await Promise.all([ - page.waitForEvent('popup', { timeout: 10_000 }), - frame.click('#blanklink', { timeout: 2000 }) - ]) - } - }) - expect(allowedBlank.pixelBefore).toBe(ARTIFACT_RGB) - expect(allowedBlank.actError).toBeNull() - expect(allowedBlank.popups).toBe(1) - }, 180_000) - // Force slow-arm diagnostic sampling branch; formerly unexecuted branch had out-of-scope name and no test/lint coverage. // Force bounded navigation timeout after missed click; require useful diagnostic instead of exhausting whole case budget. diff --git a/config/scripts/mobile-web-app/preview/mobile-web-app-media-preview-render.test.mjs b/config/scripts/mobile-web-app/preview/mobile-web-app-media-preview-render.test.mjs index d213ec445f6..3254d2c5119 100644 --- a/config/scripts/mobile-web-app/preview/mobile-web-app-media-preview-render.test.mjs +++ b/config/scripts/mobile-web-app/preview/mobile-web-app-media-preview-render.test.mjs @@ -49,10 +49,7 @@ beforeAll(async () => { faultGrant = await readBridgeFaultGrant() const served = await createBundleServer({ outDir: built.outDir, - cspHeader: (request) => - request.url.includes('oldShell=1') - ? policy.replace('media-src blob:', "media-src 'none'") - : policy + cspHeader: policy }) server = served.server origin = served.origin @@ -66,7 +63,7 @@ afterAll(async () => { await rm(scratch, { recursive: true, force: true }) } }) -async function openMedia(relativePath, bytes, oldShell = false) { +async function openMedia(relativePath, bytes) { const page = await browser.newPage({ viewport: { width: 390, height: 844 } }) const errors = [] page.on('pageerror', (error) => errors.push(error.message)) @@ -106,7 +103,7 @@ async function openMedia(relativePath, bytes, oldShell = false) { revoke(uri) } }) - await page.goto(`${origin}/?${oldShell ? 'oldShell=1' : ''}`) + await page.goto(`${origin}/`) return { page, errors } } const describeRender = bundles ? describe : describe.skip @@ -135,15 +132,11 @@ describeRender('mobile media under the shipped shell policy', () => { return { duration: media.duration, time: media.currentTime, - controls: media.controls, - autoplay: media.autoplay, uri: media.currentSrc } }, tag) expect(playback.duration).toBeCloseTo(2, 1) expect(playback.time).toBeGreaterThan(1) - expect(playback.controls).toBe(true) - expect(playback.autoplay).toBe(false) await page.evaluate((pathname) => { history.pushState(null, '', `${pathname}?relativePath=README.md`) dispatchEvent(new PopStateEvent('popstate')) @@ -161,11 +154,4 @@ describeRender('mobile media under the shipped shell policy', () => { }, 60_000 ) - it('explains the required app update when an older shell blocks Blob playback', async () => { - const { page } = await openMedia('music.wav', wavFixture(), true) - await page - .getByText('Update Orca Mobile to play media in this workspace', { exact: true }) - .waitFor() - await page.close() - }, 60_000) }) diff --git a/config/scripts/mobile-web-app/routing/mobile-web-app-page-grant-call-sites.mjs b/config/scripts/mobile-web-app/routing/mobile-web-app-page-grant-call-sites.mjs index c201cf7f4f5..75ea0a8ee9f 100644 --- a/config/scripts/mobile-web-app/routing/mobile-web-app-page-grant-call-sites.mjs +++ b/config/scripts/mobile-web-app/routing/mobile-web-app-page-grant-call-sites.mjs @@ -27,25 +27,25 @@ export const PAGE_GRANT_CALL_SITES = [ callRow( ['externalLink'], 'openExternalLink', - 'src/platform/external-link.web.ts', + 'src/platform/external-links/external-link.web.ts', 'the shell is the only thing on the page that can open a URL outside the app' ), callRow( ['native.clipboard.write'], 'useClipboardWriter', - 'src/platform/clipboard.web.ts', + 'src/platform/clipboard/clipboard.web.ts', "the browser's own clipboard write is refused without a user gesture the page cannot prove" ), callRow( ['native.clipboard.read'], 'useClipboardReader', - 'src/platform/clipboard.web.ts', + 'src/platform/clipboard/clipboard.web.ts', 'a paste needs the device pasteboard, which the WebView does not hand the page' ), callRow( ['native.media.pick', 'native.media.read', 'native.media.release'], 'useMediaPicker', - 'src/platform/media-picker.web.ts', + 'src/platform/media-picking/media-picker.web.ts', 'the picker runs the OS permission prompt inside the shell and hands back a handle' ) ] diff --git a/config/scripts/mobile-web-app/session/mobile-web-app-mermaid-render.test.mjs b/config/scripts/mobile-web-app/session/mobile-web-app-mermaid-render.test.mjs index ac769ce322b..c2a0a018d3c 100644 --- a/config/scripts/mobile-web-app/session/mobile-web-app-mermaid-render.test.mjs +++ b/config/scripts/mobile-web-app/session/mobile-web-app-mermaid-render.test.mjs @@ -9,14 +9,12 @@ import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-depend import { createBundleServer, installCspViolationRecorder, - installListenerRecorder, readShellCsp } from '../preview/mobile-web-app-render-harness.mjs' const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url)) const diagramDir = join(mobileDir, 'src/components/pr-sidebar') -// Use design fixture so recorded byte counts remain comparable. const FIXTURE = 'graph TD\n A[Start] --> B{Choice}\n B -->|yes| C[Ship it]\n B -->|no| D[Fix it]\n D --> A' @@ -124,44 +122,15 @@ afterAll(async () => { } }) -// Record eval/Function stacks to attribute JIT attempts: a library may swallow EvalError under CSP. -// Playwright also evaluates harness functions, so only bundle-script callers count as page JIT. -function installJitRecorder() { - globalThis.__orcaJit = [] - const record = (kind, source) => { - // Skip error header and recorder frame to identify caller. - const stack = (new Error('jit').stack ?? '').split('\n').slice(2).join(' | ') - globalThis.__orcaJit.push({ kind, source: String(source).slice(0, 60), stack }) - } - // oxlint-disable-next-line eslint/no-eval -- SAFETY: the recorder holds the real eval so it can count and forward calls; naming it is this function's whole purpose. - const realEval = globalThis.eval - // oxlint-disable-next-line eslint/no-eval -- SAFETY: replacing eval with a counting wrapper is the measurement, not a call. - globalThis.eval = function (source) { - record('eval', source) - return realEval.call(globalThis, source) - } - const RealFunction = globalThis.Function - function PatchedFunction(...args) { - record('Function', args.map((one) => String(one).slice(0, 40)).join('|')) - return RealFunction.apply(this, args) - } - PatchedFunction.prototype = RealFunction.prototype - globalThis.Function = PatchedFunction -} - // Mermaid marks its drawings; the frame's expand icon is an SVG too. function readDiagram() { const DRAWING = 'svg[aria-roledescription]' const frame = document.querySelector('[data-testid="mermaid-diagram"]') - const svg = frame?.querySelector(DRAWING) ?? null return { - framed: frame !== null, inFrame: frame ? frame.querySelectorAll(DRAWING).length : -1, // Count SVGs across document too: Mermaid’s temporary body element can orphan diagrams outside component host. inDocument: document.querySelectorAll(DRAWING).length, sourceBox: document.querySelector('[data-testid="mermaid-diagram-source"]') !== null, - id: svg?.id ?? null, - html: svg?.outerHTML ?? null, text: frame?.textContent ?? null } } @@ -175,9 +144,7 @@ async function openPage(browser) { } }) page.on('pageerror', (error) => consoleErrors.push(`pageerror: ${error.message}`)) - await page.addInitScript(installJitRecorder) await page.addInitScript(installCspViolationRecorder) - await page.addInitScript(installListenerRecorder) await page.goto(`${origin}/`, { waitUntil: 'domcontentloaded' }) await page.waitForFunction(() => document.body.dataset.ready === 'yes') return { page, consoleErrors } diff --git a/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs b/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs new file mode 100644 index 00000000000..72f2380b7ed --- /dev/null +++ b/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs @@ -0,0 +1,141 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import * as esbuild from 'esbuild' +import { chromium } from 'playwright-core' +import { + MOBILE_WEB_APP_ROOT_RESET, + mobileWebAppBuildOptions +} from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs' +import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs' +import { createBundleServer, readShellCsp } from '../preview/mobile-web-app-render-harness.mjs' + +// The phone's web pages must pan the transcript by touch and give a pinch to its text-size detector, not page zoom. +const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url)) + +const entry = ` +import { createRoot } from 'react-dom/client' +import { Text, View } from 'react-native' +import { GestureHandlerRootView } from 'react-native-gesture-handler' +import { MobileNativeChatPageScroll } from './src/session/native-chat/transcript/MobileNativeChatPageScroll' +import { + MobileNativeChatPinchZoom, + useMobileNativeChatPinchGesture +} from './src/session/native-chat/transcript/mobile-native-chat-pinch-zoom' + +function Transcript() { + const { fontScale, pinchGesture } = useMobileNativeChatPinchGesture('chat') + return + {fontScale} + + + + {Array.from({ length: 60 }, (_, i) => message {i})} + + + + +} +createRoot(document.getElementById('root')).render() +` + +const bundles = mobileWebAppDependenciesPresent() +const describeRender = bundles ? describe : describe.skip +let scratch +let server +let origin +let browser + +beforeAll(async () => { + if (!bundles) { + return + } + await mkdir(join(mobileDir, '.tmp'), { recursive: true }) + scratch = await mkdtemp(join(mobileDir, '.tmp', 'chat-touch-scroll-')) + const outDir = join(scratch, 'bundle') + await esbuild.build({ + ...mobileWebAppBuildOptions([]), + entryPoints: undefined, + stdin: { contents: entry, resolveDir: mobileDir, loader: 'tsx', sourcefile: 'transcript.tsx' }, + splitting: false, + write: true, + outdir: outDir, + entryNames: 'transcript', + metafile: false + }) + await writeFile( + join(outDir, 'index.html'), + '' + + '' + + `${MOBILE_WEB_APP_ROOT_RESET}` + + '
' + ) + const served = await createBundleServer({ outDir, cspHeader: await readShellCsp() }) + server = served.server + origin = served.origin + const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER + browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) }) +}, 180_000) + +afterAll(async () => { + await browser?.close() + server?.close() + if (scratch) { + await rm(scratch, { recursive: true, force: true }) + } +}) + +async function touch(page, steps) { + const cdp = await page.context().newCDPSession(page) + const [first, ...rest] = steps + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: first }) + for (const touchPoints of rest) { + await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints }) + await page.evaluate(() => new Promise(requestAnimationFrame)) + } + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) + await cdp.detach() +} + +const frames = (count, at) => Array.from({ length: count + 1 }, (_, step) => at(step / count)) + +async function openTranscript() { + const context = await browser.newContext({ + viewport: { width: 390, height: 844 }, + hasTouch: true, + isMobile: true + }) + const page = await context.newPage() + await page.goto(`${origin}/`) + await page.getByTestId('transcript').waitFor() + return page +} + +describeRender('native chat transcript in the phone web pages', () => { + it('pans the transcript under one finger', async () => { + const page = await openTranscript() + await touch( + page, + frames(10, (t) => [{ x: 195, y: 200 + 300 * t }]) + ) + await expect + .poll(() => page.getByTestId('transcript').evaluate((element) => element.scrollTop)) + .toBeLessThan(-100) + await page.context().close() + }) + + it('gives a pinch to the text size, not to page zoom', async () => { + const page = await openTranscript() + await touch( + page, + frames(10, (t) => [ + { x: 195, y: 330 - 120 * t, id: 0 }, + { x: 195, y: 370 + 120 * t, id: 1 } + ]) + ) + await expect.poll(() => page.getByTestId('font-scale').textContent()).not.toBe('1') + expect(await page.evaluate(() => window.visualViewport.scale)).toBe(1) + await page.context().close() + }) +}) diff --git a/config/scripts/mobile-web-app/session/mobile-web-app-rich-markdown-render.test.mjs b/config/scripts/mobile-web-app/session/mobile-web-app-rich-markdown-render.test.mjs index afa460518b3..af884f5aa77 100644 --- a/config/scripts/mobile-web-app/session/mobile-web-app-rich-markdown-render.test.mjs +++ b/config/scripts/mobile-web-app/session/mobile-web-app-rich-markdown-render.test.mjs @@ -16,31 +16,12 @@ import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-depend import { createBundleServer, installCspViolationRecorder, - installListenerRecorder, readShellCsp } from '../preview/mobile-web-app-render-harness.mjs' const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url)) const componentDir = join(mobileDir, 'src/components') -const COMMANDS = [ - { label: 'H1', command: 'heading1', select: 'all', expect: 'h1' }, - { label: 'H2', command: 'heading2', select: 'all', expect: 'h2' }, - { label: 'H3', command: 'heading3', select: 'all', expect: 'h3' }, - { label: 'Bold', command: 'bold', select: 'word', expect: 'b,strong' }, - { label: 'Italic', command: 'italic', select: 'word', expect: 'i,em' }, - { label: 'Strike', command: 'strike', select: 'word', expect: 'strike,s,del' }, - { label: 'Bullet list', command: 'bulletList', select: 'all', expect: 'ul' }, - { label: 'Numbered list', command: 'orderedList', select: 'all', expect: 'ol' }, - { label: 'Checklist', command: 'taskList', select: 'all', expect: 'ul[data-type="taskList"]' }, - { label: 'Quote', command: 'quote', select: 'all', expect: 'blockquote' }, - { label: 'Inline code', command: 'inlineCode', select: 'word', expect: 'code' }, - { label: 'Code block', command: 'codeBlock', select: 'all', expect: 'pre' } -] - -// Paragraph undoes another command; starting from p would prove nothing. -const PARAGRAPH = { label: 'Body', command: 'paragraph' } - // Serve inserted image locally: nonexistent URL logs WebKit load failure; successful paint proves shipped CSP admits it. const IMAGE_PATH = '/inserted.png' const URL_COMMANDS = [ @@ -151,21 +132,6 @@ function Harness() { createRoot(document.getElementById('root')).render(createElement(Harness)) ` -// Install ReactNativeWebView recorder before bundle: absence alone cannot prove editor JSON avoids shell bridge if bridge object never existed. -function installBridgeObjectRecorder() { - globalThis.__orcaBridgeReads = [] - const bridge = { - postMessage: (message) => globalThis.__orcaBridgeReads.push(`post ${String(message)}`) - } - Object.defineProperty(globalThis, 'ReactNativeWebView', { - configurable: true, - get: () => { - globalThis.__orcaBridgeReads.push('read') - return bridge - } - }) -} - const bundles = mobileWebAppDependenciesPresent() const describeEditor = bundles ? describe : describe.skip @@ -256,9 +222,7 @@ async function openPage(browser) { } }) page.on('pageerror', (error) => consoleErrors.push(`pageerror: ${error.message}`)) - await page.addInitScript(installBridgeObjectRecorder) await page.addInitScript(installCspViolationRecorder) - await page.addInitScript(installListenerRecorder, { selector: '#editor' }) await page.goto(`${origin}/`, { waitUntil: 'domcontentloaded' }) await page.waitForFunction(() => document.body.dataset.ready === 'yes') await page.waitForSelector('#first-surface #editor') @@ -326,89 +290,7 @@ describeEditor( afterAll(() => browser?.close()) - it('mounts the document, reports ready through the seam and never touches the bridge', async () => { - const { page, consoleErrors } = await openPage(browser) - try { - await setContent(page, '# Title', '

Title

') - expect(await readSurface(page)).toBe('

Title

') - // Initial markup proves document ready reached controller and pushed content through seam. - expect(await page.evaluate(() => globalThis.__orcaBridgeReads)).toEqual([]) - expect(await page.evaluate(() => globalThis.__orcaCspViolations)).toEqual([]) - expect(consoleErrors).toEqual([]) - // No editor occlusion report: screen’s web module already measures viewport, so reporting twice would lift bar twice. - expect(await page.evaluate(() => globalThis.__orcaEditor.insets)).toEqual([]) - } finally { - await page.close() - } - }, 600_000) - - it('runs every one of the fifteen commands against the document', async () => { - const { page, consoleErrors } = await openPage(browser) - try { - for (const [index, entry] of COMMANDS.entries()) { - const body = bodyFor(index) - await setContent(page, body, `

${body}

`) - // Require command effect absent beforehand or undelivered command could pass on previous document. - expect( - await page.evaluate( - (selector) => - document.querySelector('#first-surface #editor')?.querySelector(selector), - entry.expect - ), - `${entry.label} was already applied before it ran` - ).toBeNull() - await select(page, entry.select) - await press(page, entry.label) - await page.waitForFunction( - (selector) => - document.querySelector('#first-surface #editor')?.querySelector(selector) !== - null, - entry.expect, - { timeout: 15_000 } - ) - } - - // Paragraph must undo another block type; it is a no-op on p. - await setContent(page, '# Title', '

Title

') - await select(page, 'all') - await press(page, PARAGRAPH.label) - await page.waitForFunction( - () => - document.querySelector('#first-surface #editor')?.querySelector('h1') === null && - document.querySelector('#first-surface #editor')?.querySelector('p') !== null, - null, - { timeout: 15_000 } - ) - - expect(await page.evaluate(() => globalThis.__orcaCspViolations)).toEqual([]) - expect(consoleErrors).toEqual([]) - } finally { - await page.close() - } - }, 600_000) - // Both engines nest unordered list inside existing p; inline paragraph serialization once dropped bullet when saved. - it('edits and selects under the shipped document style, which makes other text unselectable', async () => { - const { page, consoleErrors } = await openPage(browser) - try { - await setContent(page, 'alpha', '

alpha

') - const word = page.locator('#first-surface #editor p') - await word.click() - await page.keyboard.press('End') - await page.keyboard.type(' bravo') - await page.waitForFunction( - () => - document.querySelector('#first-surface #editor p')?.textContent === 'alpha bravo' - ) - // Use browser gesture: a scripted Range bypasses body user-select:none. - await page.evaluate(() => window.getSelection()?.removeAllRanges()) - await word.dblclick() - expect(await page.evaluate(() => window.getSelection()?.toString().trim())).not.toBe('') - expect(consoleErrors).toEqual([]) - } finally { - await page.close() - } - }, 600_000) it('reports a typed bullet list as a list, and renders that markdown back as one', async () => { const { page, consoleErrors } = await openPage(browser) diff --git a/config/scripts/mobile-web-app/session/mobile-web-app-session-render.test.mjs b/config/scripts/mobile-web-app/session/mobile-web-app-session-render.test.mjs index a159fab4f6d..ea3838edbd9 100644 --- a/config/scripts/mobile-web-app/session/mobile-web-app-session-render.test.mjs +++ b/config/scripts/mobile-web-app/session/mobile-web-app-session-render.test.mjs @@ -16,10 +16,6 @@ import { waitForPageFrames } from '../preview/mobile-web-app-render-harness.mjs' -// Render real session closure under shipped CSP; unit tests mock RN and cannot prove browser import/evaluation, route paint or deferred fetch. -// Assert every console error: unguarded RN-Web BackHandler and rejected diff-note loads once logged silently on mount. -// No terminal attaches against no-RPC double; terminal-render proves terminal content/CSP, session-terminal-init proves session attachment. - const HOST_ROUTE = '/h/render-check-host' const WORKTREE = 'wt-1' const SESSION_ROUTE = `${HOST_ROUTE}/session/${WORKTREE}` @@ -33,8 +29,6 @@ const SHELL_HOST = { endpoint: 'ws://render-check', lastConnected: 1 } -const UNMATCHED = 'Unmatched Route' -const SESSION_CHUNK_KEY = './h/[hostId]/session/[worktreeId].tsx' // Read grants from manifest so new route grants are exercised instead of silently omitted by copied fixture. function sessionGrants() { @@ -52,7 +46,6 @@ let scratch let server let browser let origin -let routeChunks = {} let cspHeader = null let bridgeVersion = null let faultGrant = null @@ -66,7 +59,6 @@ beforeAll(async () => { faultGrant = await readBridgeFaultGrant() scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-session-')) const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') }) - routeChunks = built.routeChunks const served = await createBundleServer({ outDir: built.outDir, cspHeader }) server = served.server origin = served.origin @@ -105,8 +97,6 @@ async function openPage(route, replies = {}, { domStorageOff = false } = {}) { }) const errors = [] const warnings = [] - const scripts = [] - const requestedHosts = [] page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`)) page.on('console', (message) => { if (message.type() === 'error') { @@ -117,15 +107,7 @@ async function openPage(route, replies = {}, { domStorageOff = false } = {}) { warnings.push(message.text()) } }) - // Observe requests, not just responses; CSP-blocked fetches must still count as attempts. - page.on('request', (request) => requestedHosts.push(new URL(request.url()).host)) - page.on('response', (response) => { - const path = new URL(response.url()).pathname - if (response.status() === 200 && path.endsWith('.js')) { - scripts.push(path) - } - }) - return { page, errors, warnings, scripts, requestedHosts } + return { page, errors, warnings } } // Wait for route content after mounted: deferred screen chunk may still be arriving. @@ -161,43 +143,9 @@ async function openRoute(route, awaitText, replies = {}, options = {}) { return opened } -const SESSION_MOUNT_READS = ['worktree.show', 'session.tabs.list', 'terminal.list'] - describeRender( 'the session route in a real browser', () => { - it('mounts the session screen rather than the unmatched route, with nothing on the console', async () => { - const opened = await openRoute(SESSION_ROUTE, 'Terminal') - const text = await opened.page.evaluate(() => document.body.innerText) - // Accessory-bar keys prove session screen, beyond generic header text. - for (const key of ['Esc', 'Tab', 'Ctrl+C', 'Ctrl+R']) { - expect(text).toContain(key) - } - expect(text).not.toContain(UNMATCHED) - // Require exact empty list: BackHandler and uncaught diff-note defects were console-only. - expect(opened.errors).toEqual([]) - expect(opened.requestedHosts.filter((host) => host !== new URL(origin).host)).toEqual([]) - await opened.page.close() - }, 120_000) - - it("fetches the session route's own chunk on a client-side navigation", async () => { - const opened = await openRoute(HOST_ROUTE, SHELL_HOST.name) - const loadedForFirstRoute = [...opened.scripts] - await opened.page.evaluate((to) => { - history.pushState(null, '', to) - dispatchEvent(new PopStateEvent('popstate')) - }, SESSION_ROUTE) - await waitForRoute(opened, SESSION_ROUTE, 'Terminal') - const chunk = routeChunks[SESSION_CHUNK_KEY] - expect(chunk, Object.keys(routeChunks).join(' ')).toBeTruthy() - // Identify route chunk through builder to prove fresh fetch, not code already loaded by entry. - expect(opened.scripts.filter((path) => !loadedForFirstRoute.includes(path))).toContain( - `/assets/${chunk}` - ) - expect(loadedForFirstRoute).not.toContain(`/assets/${chunk}`) - await opened.page.close() - }, 120_000) - it('paints with DOM storage off, which is how the Android shell serves it', async () => { // Null-storage arm reproduces Android import-time expo-notifications failure; shell owns push and pages must not load it. const opened = await openRoute(SESSION_ROUTE, 'Terminal', {}, { domStorageOff: true }) @@ -222,25 +170,6 @@ describeRender( expect(opened.warnings.filter((text) => text.includes('storage-write-dropped'))).toEqual([]) await opened.page.close() }, 120_000) - - it('asks the desktop for the session it was opened on, so the page above is live', async () => { - // Require title/tab/inventory RPCs with correct workspace or same chrome could pass without host reads. - // Await effects after paint: under 20× CPU throttle none had fired at initial Terminal commit. - const opened = await openRoute(SESSION_ROUTE, 'Terminal') - const requests = await waitForRecordedRequests(opened.page, SESSION_MOUNT_READS) - for (const method of SESSION_MOUNT_READS) { - const observed = requests.filter((request) => request.method === method) - expect(observed.length, method).toBeGreaterThan(0) - for (const request of observed) { - expect(request.params.worktree, method).toBe(`id:${WORKTREE}`) - } - } - await opened.page.close() - }, 120_000) }, 600_000 ) - -// Coverage boundaries: terminal-render proves xterm/CSP/transcript; session-terminal-init proves attachment. -// Data-gated chat/picker/clipboard controls use sibling source censuses and host/port-pair suites. -// browser-pane-render proves frame paint; screencast-lane-grant derives route grant; page-async-storage tests store write refusals. diff --git a/config/scripts/mobile-web-app/shell/mobile-web-app-code-block-selection.mjs b/config/scripts/mobile-web-app/shell/mobile-web-app-code-block-selection.mjs index d747e67fab9..bb480d57447 100644 --- a/config/scripts/mobile-web-app/shell/mobile-web-app-code-block-selection.mjs +++ b/config/scripts/mobile-web-app/shell/mobile-web-app-code-block-selection.mjs @@ -12,13 +12,7 @@ async function verifyCodeBlockSelections({ readSurface }) { const cases = [ - { markdown: 'selected text', html: '

selected text

', literal: 'selected text' }, { markdown: 'first\nsecond', html: '

first
second

', literal: 'first\nsecond' }, - { - markdown: 'first\n\nsecond', - html: '

first

\n

second

', - literal: 'first\nsecond' - }, { markdown: '**bold** and *italic*', html: '

bold and italic

', @@ -82,7 +76,7 @@ async function verifyCodeBlockSelections({ } ] for (const sample of cases) { - const { page, consoleErrors } = await openPage(browser) + const { page } = await openPage(browser) try { await setContent(page, sample.markdown, sample.html) await (sample.partial || sample.collapsed || sample.paragraph || sample.caret @@ -149,8 +143,6 @@ async function verifyCodeBlockSelections({ await expect .poll(() => page.locator('#first-surface #editor pre code').textContent()) .toBe(sample.literal) - expect(await page.evaluate(() => globalThis.__orcaCspViolations)).toEqual([]) - expect(consoleErrors).toEqual([]) } finally { await page.close() } @@ -174,7 +166,7 @@ async function verifyStructuredSelections({ } ] for (const sample of samples) { - const { page, consoleErrors } = await openPage(browser) + const { page } = await openPage(browser) try { if (sample.html) { await setContent(page, sample.markdown, sample.html) @@ -192,8 +184,6 @@ async function verifyStructuredSelections({ expect(await readSurface(page)).toBe(before) expect(await page.evaluate(() => window.getSelection().toString())).toBe(selected) expect(await page.evaluate(() => globalThis.__orcaEditor.changes)).toEqual([]) - expect(await page.evaluate(() => globalThis.__orcaCspViolations)).toEqual([]) - expect(consoleErrors).toEqual([]) } finally { await page.close() } diff --git a/config/scripts/mobile-web-app/shell/mobile-web-app-composer-sizing-render.test.mjs b/config/scripts/mobile-web-app/shell/mobile-web-app-composer-sizing-render.test.mjs index ee8f619bd08..e3422785654 100644 --- a/config/scripts/mobile-web-app/shell/mobile-web-app-composer-sizing-render.test.mjs +++ b/config/scripts/mobile-web-app/shell/mobile-web-app-composer-sizing-render.test.mjs @@ -29,7 +29,7 @@ import { useState } from 'react' import { createRoot } from 'react-dom/client' import { View } from 'react-native' import { MobileNativeChatComposerField } from './src/session/native-chat/composer/MobileNativeChatComposerField.web' -import { publishShellKeyboardSource } from './src/platform/keyboard-occlusion' +import { publishShellKeyboardSource } from './src/platform/keyboard/keyboard-occlusion' let keyboardHeight = 0 const listeners = new Set() diff --git a/config/scripts/mobile-web-app/shell/mobile-web-app-native-parity-render.test.mjs b/config/scripts/mobile-web-app/shell/mobile-web-app-native-parity-render.test.mjs index 158f328bbdc..e3389b15c86 100644 --- a/config/scripts/mobile-web-app/shell/mobile-web-app-native-parity-render.test.mjs +++ b/config/scripts/mobile-web-app/shell/mobile-web-app-native-parity-render.test.mjs @@ -1,4 +1,4 @@ -// Measure browser defaults absent from native UI at phone density, with shipped plugins/document styles. +// Measure the shipped hairline patch at phone density in both browser engines. import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -42,15 +42,13 @@ const ENGINES = [ const PAGE_ENTRY = ` import { createElement as h } from 'react' import { createRoot } from 'react-dom/client' -const { Modal, StyleSheet, Text, TextInput, View } = require('react-native') +const { StyleSheet, View } = require('react-native') const styles = StyleSheet.create({ separatorBox: { paddingTop: 10.1, width: 12, backgroundColor: '#ffffff' }, - separator: { height: StyleSheet.hairlineWidth, backgroundColor: '#000000' }, - hairline: { height: 0, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#222222' }, - input: { height: 40 } + separator: { height: StyleSheet.hairlineWidth, backgroundColor: '#000000' } }) createRoot(document.getElementById('root')).render( - h(View, null, h(View, { testID: 'separator-box', style: styles.separatorBox }, h(View, { style: styles.separator })), h(View, { testID: 'hairline', style: styles.hairline }), h(TextInput, { testID: 'input', style: styles.input }), h(Text, { testID: 'plain-text' }, 'row'), h(Text, { testID: 'selectable-text', selectable: true }, 'message'), location.hash === '#modal' ? h(Modal, { visible: true, transparent: true }, h(View, null, h(Text, { testID: 'modal-text' }, 'sheet row'), h(TextInput, { testID: 'modal-input', style: styles.input }))) : null) + h(View, { testID: 'separator-box', style: styles.separatorBox }, h(View, { style: styles.separator })) ) ` @@ -106,10 +104,10 @@ afterAll(async () => { } }) -async function openPage(engine, hash = '') { +async function openPage(engine) { const page = await browsers.get(engine.name).newPage(engine.pageOptions) - await page.goto(`${origin}/${hash}`, { waitUntil: 'domcontentloaded' }) - await page.waitForSelector('[data-testid="input"]') + await page.goto(`${origin}/`, { waitUntil: 'domcontentloaded' }) + await page.waitForSelector('[data-testid="separator-box"]') return page } @@ -124,7 +122,7 @@ describeParity.each(ENGINES)('the page against native, at a phone density, in $n const column = Math.floor(shot.width / 2) let darkRows = 0 for (let y = 0; y < shot.height; y++) { - // Count pure black only; final clip row may include neighboring #222222 border. + // Count pure black rows in the separator clip. if (shot.data[(y * shot.width + column) * 4] < 16) { darkRows++ } @@ -134,29 +132,4 @@ describeParity.each(ENGINES)('the page against native, at a phone density, in $n await page.close() } }) - - it("selects through the browser's own gesture only what native lets the user select", async () => { - // Double-click tests user selectability; script-created Range can select otherwise unselectable text. - const page = await openPage(engine) - try { - const selectedBy = async (testId) => { - await page.evaluate(() => window.getSelection()?.removeAllRanges()) - await page.dblclick(`[data-testid="${testId}"]`) - return page.evaluate(() => window.getSelection()?.toString() ?? '') - } - expect(await selectedBy('plain-text')).toBe('') - // react-native-web's Text/index.js:115 adds `styles.selectable` (`userSelect: 'text'`). - expect(await selectedBy('selectable-text')).not.toBe('') - - await page.type('[data-testid="input"]', 'hello world') - await page.dblclick('[data-testid="input"]') - const selectedInField = await page.evaluate(() => { - const input = document.querySelector('[data-testid="input"]') - return input.selectionEnd - input.selectionStart - }) - expect(selectedInField).toBeGreaterThan(0) - } finally { - await page.close() - } - }) }) diff --git a/config/scripts/mobile-web-app/shell/mobile-web-app-open-target-render.test.mjs b/config/scripts/mobile-web-app/shell/mobile-web-app-open-target-render.test.mjs index 8f6899cc4fd..700e87fc3da 100644 --- a/config/scripts/mobile-web-app/shell/mobile-web-app-open-target-render.test.mjs +++ b/config/scripts/mobile-web-app/shell/mobile-web-app-open-target-render.test.mjs @@ -237,20 +237,3 @@ describeRender('a host document asked to open a target', () => { await page.close() }, 60_000) }) - -describeRender('a session document opened on a pane', () => { - it('paints without faulting while its first commit erases the pane from the URL', async () => { - // A notification tap names the pane; the preloaded session mounts before Expo's container reports ready. - const { page, errors } = await openHostDocument({ - route: { pathname: SESSION_ROUTE, params: { paneKey: 'tab-1:leaf-1' } } - }) - expect(await notifies(page, 'fault')).toEqual([]) - // Spent, so a remount of the screen cannot replay it over a later tab pick. - await page.waitForFunction(() => location.search === '', undefined, { - timeout: 10_000, - polling: 100 - }) - expect(errors).toEqual([]) - await page.close() - }, 60_000) -}) diff --git a/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-live-input-render.test.mjs b/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-live-input-render.test.mjs index afde47a339f..c49a89b3c1b 100644 --- a/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-live-input-render.test.mjs +++ b/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-live-input-render.test.mjs @@ -60,8 +60,8 @@ beforeAll(async () => { await writeFile( join(routeDir, 'live-input-probe.tsx'), liveInputProbeRouteSource({ - bindingModule: join(terminalDir, 'use-terminal-text-field-submit-binding'), - commitModule: join(terminalDir, 'use-terminal-live-input-commit') + bindingModule: join(terminalDir, 'live-input', 'use-terminal-text-field-submit-binding'), + commitModule: join(terminalDir, 'live-input', 'use-terminal-live-input-commit') }) ) const built = await buildMobileWebAppBundle({ diff --git a/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-render-fixture.mjs b/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-render-fixture.mjs index 0e2c2ec21b4..cec2cd89348 100644 --- a/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-render-fixture.mjs +++ b/config/scripts/mobile-web-app/terminal/mobile-web-app-terminal-render-fixture.mjs @@ -78,7 +78,7 @@ export async function startTerminalRenderFixture() { // Extensionless import selects web sibling; explicit .tsx would mount browser-incompatible WebView wrapper. await writeFile( join(routeDir, 'terminal-probe.tsx'), - probeRouteSource(join(mobileDir, 'src', 'terminal', 'TerminalWebView')) + probeRouteSource(join(mobileDir, 'src', 'terminal', 'webview', 'TerminalWebView')) ) const built = await buildMobileWebAppBundle({ appDir, diff --git a/config/scripts/mobile-web-app/workspace/mobile-web-app-files-render.test.mjs b/config/scripts/mobile-web-app/workspace/mobile-web-app-files-render.test.mjs index f9354639446..c394257653e 100644 --- a/config/scripts/mobile-web-app/workspace/mobile-web-app-files-render.test.mjs +++ b/config/scripts/mobile-web-app/workspace/mobile-web-app-files-render.test.mjs @@ -14,7 +14,6 @@ import { } from '../preview/mobile-web-app-render-harness.mjs' // Exercise editable artifact’s draft-confirm drawer in a real browser, including portal/gesture/Reanimated paint. -// Require modal title before asserting no RN-Web BackHandler error; opening the drawer once registered an unsupported hardware-back listener. const HOST_ROUTE = '/h/render-check-host' const WORKTREE = 'wt-1' @@ -103,19 +102,12 @@ async function openPreview() { pageRoutes: PAGE_ROUTE_PATTERNS, replies: REPLIES }) - const errors = [] - page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`)) - page.on('console', (message) => { - if (message.type() === 'error') { - errors.push(`console.error: ${message.text()}`) - } - }) await page.goto(`${origin}/`, { waitUntil: 'load' }) await page.waitForFunction(() => document.documentElement.dataset.orcaWebEntry === 'mounted', { timeout: 60_000, polling: 250 }) - return { page, errors } + return { page } } describeRender( diff --git a/config/scripts/mobile-web/check-entry/mobile-process-host-tooling.test.mjs b/config/scripts/mobile-web/check-entry/mobile-process-host-tooling.test.mjs deleted file mode 100644 index c8190a5038b..00000000000 --- a/config/scripts/mobile-web/check-entry/mobile-process-host-tooling.test.mjs +++ /dev/null @@ -1,106 +0,0 @@ -import { - cpSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - symlinkSync, - writeFileSync -} from 'node:fs' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { dirname, join, resolve } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import { runProcessSync } from '@orca/process-host' -import { removeTreeSync } from '../../../../src/shared/windows-transient-lock-removal.ts' - -const repository = resolve(import.meta.dirname, '../../../..') -const require = createRequire(import.meta.url) -const tsx = join(dirname(require.resolve('tsx/package.json')), 'dist', 'cli.mjs') -const manifest = JSON.parse(readFileSync(join(repository, 'mobile', 'package.json'), 'utf8')) -const temporary = [] - -afterEach(() => { - for (const root of temporary.splice(0)) { - removeTreeSync(root) - } -}) - -function standaloneMobile() { - const root = mkdtempSync(join(tmpdir(), 'orca-mobile-process-tooling-')) - temporary.push(root) - const mobile = join(root, 'mobile') - const dependency = manifest.devDependencies['@orca/process-host'] - expect(dependency).toBe('link:../src/packages/process-host') - const packageDir = resolve(mobile, dependency.slice('link:'.length)) - mkdirSync(packageDir, { recursive: true }) - for (const file of ['package.json', 'src']) { - cpSync(join(repository, 'src', 'packages', 'process-host', file), join(packageDir, file), { - recursive: true - }) - } - for (const file of [ - 'scripts', - 'src/test-support/rpc-recording', - 'rpc-foundation/pilot-scenarios.json' - ]) { - const destination = join(mobile, file) - mkdirSync(dirname(destination), { recursive: true }) - cpSync(join(repository, 'mobile', file), destination, { recursive: true }) - } - writeFileSync(join(mobile, 'package.json'), JSON.stringify(manifest)) - mkdirSync(join(mobile, 'rpc-foundation', 'goldens'), { recursive: true }) - mkdirSync(join(mobile, 'node_modules', '@orca'), { recursive: true }) - symlinkSync( - packageDir, - join(mobile, 'node_modules', '@orca', 'process-host'), - process.platform === 'win32' ? 'junction' : 'dir' - ) - expect(existsSync(join(root, 'node_modules'))).toBe(false) - expect(existsSync(join(packageDir, 'dist'))).toBe(false) - return { root, mobile } -} - -function command(cwd, program, args) { - return runProcessSync({ - program, - args, - cwd, - timeoutMs: 15_000, - env: { ...process.env, NODE_PATH: '', NODE_OPTIONS: '', ORCA_BACKGROUND_LAUNCH: '1' } - }) -} - -function rpcCommand(mobile, script, args) { - const [launcher, ...invocation] = manifest.scripts[script].split(' ') - expect(launcher).toBe('tsx') - return command(mobile, process.env.ORCA_TEST_NODE_EXECUTABLE ?? process.execPath, [ - tsx, - ...invocation, - ...args - ]) -} - -it('runs the RPC diff with a mobile-only dependency link and no compiled host package', () => { - const { root, mobile } = standaloneMobile() - const init = command(root, 'git', ['init']) - expect(init.code, init.stderr).toBe(0) - const commit = command(root, 'git', [ - '-c', - 'user.name=Orca Test', - '-c', - 'user.email=orca-test@example.invalid', - '-c', - 'commit.gpgsign=false', - '-c', - `core.hooksPath=${join(root, 'no-hooks')}`, - 'commit', - '--allow-empty', - '-m', - 'fixture' - ]) - expect(commit.code, commit.stderr).toBe(0) - const result = rpcCommand(mobile, 'rpc:diff', ['HEAD']) - expect(result.code, result.stderr).toBe(0) - expect(result.stdout).toContain('No recorded behaviour moved') -}) diff --git a/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs b/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs index 09e147b05d3..c4ccfd20b4d 100644 --- a/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs +++ b/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs @@ -84,16 +84,6 @@ describe.skipIf(process.platform === 'win32')('the Linux workflow detector comma repo.commit() expect(repo.detect()).toBe('should_run=true\n') }) - - it('runs Ruby when the classifier cannot execute', () => { - const repo = fixture() - repo.write('mobile/src/view.tsx', 'export const view = 2\n') - repo.commit() - rmSync( - join(repo.directory, 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.mjs') - ) - expect(repo.detect()).toBe('should_run=true\n') - }) }) describe.skipIf(process.platform === 'win32')('the mobile test detector command', () => { @@ -113,9 +103,6 @@ describe.skipIf(process.platform === 'win32')('the mobile test detector command' repo.commit() expect(repo.detect()).toBe('should_run=true\n') }) - it('retains tests when the diff is unavailable', () => { - expect(fixture(testDetector).detect()).toBe('should_run=true\n') - }) it('retains tests when the classifier cannot execute', () => { const repo = fixture(testDetector) repo.write('mobile/fastlane/Fastfile', 'default_platform(:android)\n') diff --git a/config/scripts/native-build/composition/build-native-for-platform.test.mjs b/config/scripts/native-build/composition/build-native-for-platform.test.mjs index f7de7e74a65..e3359e87c3f 100644 --- a/config/scripts/native-build/composition/build-native-for-platform.test.mjs +++ b/config/scripts/native-build/composition/build-native-for-platform.test.mjs @@ -26,7 +26,7 @@ afterEach(() => { } }) -function startBuild(mode, options = {}) { +function startBuild(mode) { const directory = mkdtempSync(join(tmpdir(), 'orca-native-build-test-')) directories.push(directory) const cli = join(directory, 'fake-pnpm.mjs') @@ -59,8 +59,7 @@ function startBuild(mode, options = {}) { if (['success', 'descendant-success'].includes(process.env.NATIVE_BUILD_MODE)) { record('completed'); process.exit(0) } if (!name.includes('computer')) return record('failed') - if (process.env.NATIVE_BUILD_MODE === 'failure-signal') process.kill(process.pid, 'SIGALRM') - else if (process.env.NATIVE_BUILD_MODE === 'failure-sigpipe') { process.on('SIGPIPE', () => {}); process.removeAllListeners('SIGPIPE'); process.kill(process.pid, 'SIGPIPE') } + if (process.env.NATIVE_BUILD_MODE === 'failure-sigpipe') { process.on('SIGPIPE', () => {}); process.removeAllListeners('SIGPIPE'); process.kill(process.pid, 'SIGPIPE') } else process.exit(7) }, 10) ` @@ -72,7 +71,7 @@ function startBuild(mode, options = {}) { env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1', - npm_execpath: options.missingCli ? join(directory, 'missing-pnpm') : cli, + npm_execpath: cli, NATIVE_BUILD_JOURNAL: journal, NATIVE_BUILD_GATE: join(directory, 'release'), NATIVE_BUILD_MODE: mode @@ -132,14 +131,6 @@ describe.skipIf(process.platform !== 'darwin')('parallel native builds', () => { expect(build.events().filter(({ event }) => event === 'SIGTERM')).toHaveLength(BUILD_COUNT - 1) }) - it('re-raises the signal that killed a build', async () => { - const build = startBuild('failure-signal') - await build.ready - build.release() - expect(await build.closed).toMatchObject({ code: null, signal: 'SIGALRM' }) - expect(build.events().filter(({ event }) => event === 'SIGTERM')).toHaveLength(BUILD_COUNT - 1) - }) - it('fails when the signal that killed a build is one the launcher ignores', async () => { const build = startBuild('failure-sigpipe') await build.ready @@ -183,21 +174,6 @@ describe.skipIf(process.platform !== 'darwin')('parallel native builds', () => { } ) - it('reports a missing build command without waiting forever', async () => { - const build = startBuild('success', { missingCli: true }) - expect(await build.closed).toMatchObject({ code: 1, signal: null }) - }) - - it('reaps compiler descendants that retain pipes after their launcher exits', async () => { - const build = startBuild('descendant') - await build.ready - build.child.kill('SIGTERM') - expect(await build.closed).toMatchObject({ code: null, signal: 'SIGTERM' }) - for (const pid of build.descendants()) { - expect(() => process.kill(pid, 0)).toThrow() - } - }) - it("reaps descendants that keep a finished build's pipes open instead of hanging", async () => { const build = startBuild('descendant-success') await build.ready diff --git a/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs b/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs deleted file mode 100644 index 6a6dda74e86..00000000000 --- a/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs +++ /dev/null @@ -1,44 +0,0 @@ -import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const require = createRequire(import.meta.url) -const { collectNativeBinaries } = require('./verify-linux-glibc-floor.cjs') - -// 0x7f 'E' 'L' 'F' + class/data/version padding — enough for the magic check. -const ELF_HEADER = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00]) - -describe('collectNativeBinaries', () => { - it('collects only ELF .node/.so/executable files, skipping non-ELF and symlinks', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-glibc-collect-')) - try { - await mkdir(join(root, 'nested'), { recursive: true }) - await writeFile(join(root, 'addon.node'), ELF_HEADER) - await writeFile(join(root, 'nested', 'lib.so'), ELF_HEADER) - await writeFile(join(root, 'nested', 'lib.so.1'), ELF_HEADER) - await writeFile(join(root, 'orca-ide'), ELF_HEADER) // extensionless executable - await writeFile(join(root, 'script.js'), ELF_HEADER) // has extension, not native - await writeFile(join(root, 'text.node'), 'not an elf file') // native name, non-ELF - await writeFile(join(root, 'notes.md'), ELF_HEADER) - try { - await symlink(join(root, 'addon.node'), join(root, 'alias.node')) - } catch { - // Symlink creation can be restricted; the rest of the assertions still hold. - } - - const found = collectNativeBinaries(root).map((p) => p.slice(root.length + 1)) - expect(found).toContain('addon.node') - expect(found).toContain(join('nested', 'lib.so')) - expect(found).toContain(join('nested', 'lib.so.1')) - expect(found).toContain('orca-ide') - expect(found).not.toContain('script.js') - expect(found).not.toContain('text.node') - expect(found).not.toContain('notes.md') - expect(found).not.toContain('alias.node') - } finally { - await rm(root, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/native-build/node-addons/native-build-entry.test.mjs b/config/scripts/native-build/node-addons/native-build-entry.test.mjs index 5dd45e79c62..5a5d359d4de 100644 --- a/config/scripts/native-build/node-addons/native-build-entry.test.mjs +++ b/config/scripts/native-build/node-addons/native-build-entry.test.mjs @@ -5,7 +5,6 @@ import path from 'node:path' import { afterEach, describe, expect, it } from 'vitest' const require = createRequire(import.meta.url) -const { isNativeBuildEntryName } = require('./native-build-entry.cjs') const { adoptPackagedNativeBuildEntries } = require('../../../packaged-native-build-entries.cjs') const roots = [] @@ -41,16 +40,6 @@ describe('adoptPackagedNativeBuildEntries', () => { }) adoptPackagedNativeBuildEntries(root, 'darwin', 'x64') expect(readFileSync(path.join(buildDir, 'Release', 'pty.node'), 'utf8')).toBe('entry-x64') - expect( - ['Release', 'orca-napi-darwin-arm64'].map((name) => isNativeBuildEntryName(name)) - ).toEqual([false, true]) expect(require('node:fs').readdirSync(buildDir)).toEqual(['Release']) }) - - it('leaves a CI layout with no entries untouched', () => { - const root = makeRoot() - const buildDir = packagedNodePty(root, { Release: 'ci-build' }) - adoptPackagedNativeBuildEntries(root, 'linux', 'x64') - expect(readFileSync(path.join(buildDir, 'Release', 'pty.node'), 'utf8')).toBe('ci-build') - }) }) diff --git a/config/scripts/native-build/node-addons/rebuild-native-deps-node-pty.test.mjs b/config/scripts/native-build/node-addons/rebuild-native-deps-node-pty.test.mjs index 39637aa2540..4a334265908 100644 --- a/config/scripts/native-build/node-addons/rebuild-native-deps-node-pty.test.mjs +++ b/config/scripts/native-build/node-addons/rebuild-native-deps-node-pty.test.mjs @@ -90,32 +90,6 @@ describe('rebuild-native-deps patched node-pty rebuild', () => { } }) - it('restores the ConPTY runtime payload after a Windows Electron rebuild', () => { - const projectDir = mkTempProject() - - try { - writeFakeUsableElectronPackage(projectDir, { platform: 'win32' }) - writeFakeElectronRebuild(projectDir) - writeFakeNodePtyConptyPayload(projectDir, 'x64') - - const result = runRebuildScript( - projectDir, - { npm_config_platform: 'win32', npm_config_arch: 'x64' }, - ['--platform=win32', '--arch=x64', '--force'] - ) - - expect(result.status, result.stderr).toBe(0) - expect(result.stdout).toContain('Restored node-pty ConPTY runtime files for win10-x64') - const runtimeDir = join(projectDir, 'node_modules', 'node-pty', 'build', 'Release', 'conpty') - expect(readFileSync(join(runtimeDir, 'conpty.dll'), 'utf8')).toBe('conpty.dll x64') - expect(readFileSync(join(runtimeDir, 'OpenConsole.exe'), 'utf8')).toBe('OpenConsole.exe x64') - } finally { - removeTreeSync(projectDir) - } - }) - - // Model loadable addon with all job exports but no MSYS denial: require/export checks pass while Git Bash children leak. - // Check rebuilt artifact destined for packaged app; neither relay gate nor runtime load check covers it. Missing output after success must fail too. for (const [addon, expected] of [ ['unpatched', 'still imports ReadProcessMemory'], @@ -198,8 +172,4 @@ describe('rebuild-native-deps patched node-pty rebuild', () => { removeTreeSync(projectDir) } }) - - // Cross-host rebuild or absent optional node-pty may leave no win32 addon; warn without breaking a working install. - - // Same-host missing output must fail: loader falls back to upstream prebuild that leaks MSYS children. Only Windows can exercise this branch. }) diff --git a/config/scripts/node-server/qualification/node-server-change-scope.mjs b/config/scripts/node-server/qualification/node-server-change-scope.mjs index ee5990e62e7..7b2fe08f657 100644 --- a/config/scripts/node-server/qualification/node-server-change-scope.mjs +++ b/config/scripts/node-server/qualification/node-server-change-scope.mjs @@ -75,7 +75,6 @@ const ALWAYS_PREFIXES = [ 'src/main/daemon/pty-subprocess/spawn-environment.ts', 'src/main/daemon/pty-subprocess/spawn-file-child-processes.ts', 'src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts', - 'src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts', 'src/main/daemon/pty-subprocess/spawn-preflight.ts', 'src/main/daemon/pty-subprocess/subprocess-handle.ts', 'src/main/providers/', diff --git a/config/scripts/node-server/qualification/node-server-change-scope.test.mjs b/config/scripts/node-server/qualification/node-server-change-scope.test.mjs index 29172c0ad5c..0818dcbded8 100644 --- a/config/scripts/node-server/qualification/node-server-change-scope.test.mjs +++ b/config/scripts/node-server/qualification/node-server-change-scope.test.mjs @@ -74,23 +74,6 @@ it('tracks workspace source and manifest closures without trusting dist or widen ).toBe(false) }) -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' - const removed = 'src/main/persistence/example/removed.test.ts' - const root = moduleTree({ - 'entry.ts': `import './${reachable}'; throw Error('never execute')`, - [reachable]: 'export const value = 1', - [unrelated]: 'throw Error("never execute unrelated test")' - }) - const inputs = await collectNodeServerInputs({ root, entryPoints: ['entry.ts'] }) - expect(inputs.has(reachable)).toBe(true) - expect(inputs.has(unrelated)).toBe(false) - expect((await classifyNodeServerChanges([reachable], async () => inputs)).shouldRun).toBe(true) - expect((await classifyNodeServerChanges([unrelated], async () => inputs)).shouldRun).toBe(false) - expect((await classifyNodeServerChanges([removed], async () => inputs)).shouldRun).toBe(false) -}) - it('retains qualification when a removed ordinary unit file breaks an actual import', async () => { const removed = 'src/main/persistence/example/removed.test.ts' const root = moduleTree({ 'entry.ts': `import './${removed}'` }) diff --git a/config/scripts/node-server/qualification/node-server-qualification.mjs b/config/scripts/node-server/qualification/node-server-qualification.mjs index a61db2145c0..6a70b26d9e2 100644 --- a/config/scripts/node-server/qualification/node-server-qualification.mjs +++ b/config/scripts/node-server/qualification/node-server-qualification.mjs @@ -21,8 +21,8 @@ const CROSS_HOST_PREFIXES = [ 'src/main/ssh/', 'src/main/managed-server/', 'src/main/node-runtime/', - 'src/main/orcad/orcad-artifact-materializer.ts', - 'src/main/orcad/orcad-host-unavailable.ts', + 'src/main/orcad/artifact-slots/orcad-artifact-materializer.ts', + 'src/main/orcad/diagnostics/orcad-host-unavailable.ts', 'src/main/providers/', 'src/wsl-guest/' ] diff --git a/config/scripts/node-server/qualification/node-server-test-paths.mjs b/config/scripts/node-server/qualification/node-server-test-paths.mjs index 7ec2eeb38a5..29e3d5979f6 100644 --- a/config/scripts/node-server/qualification/node-server-test-paths.mjs +++ b/config/scripts/node-server/qualification/node-server-test-paths.mjs @@ -1,11 +1,11 @@ -/** Mirrors ORCA_REQUIRED_TEST_INPUTS_ENV in src/main/orcad/orcad-node-slot-fixture.ts. */ +/** Mirrors ORCA_REQUIRED_TEST_INPUTS_ENV in src/main/orcad/testing/native-slots/orcad-node-slot-fixture.ts. */ export const REQUIRED_TEST_INPUTS_ENV = 'ORCA_REQUIRED_TEST_INPUTS' export const CROSS_RUNTIME_TEST_PATHS = [] // Need the built desktop server template; CI runs them by path after build-orcad-template.mjs. export const TEMPLATE_TEST_PATHS = [ - 'src/main/orcad/orcad-packaged-structured-chat.integration.test.ts' + 'src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts' ] export function nodeServerTestPaths({ @@ -18,10 +18,10 @@ export function nodeServerTestPaths({ 'src/main/persistence/loading-store/profile-writing/profile-state', 'src/main/sqlite', // The orcad server's identity and stop path, which Windows SSH hosts rely on (W2). - 'src/main/orcad/orcad-instance-lock.test.ts', - 'src/main/orcad/orcad-process-start-time.test.ts', - 'src/main/orcad/orcad-managed-stop.test.ts', - 'src/main/orcad/orcad-managed-stop-cancellation.test.ts', + 'src/main/orcad/instance-lock/orcad-instance-lock.test.ts', + 'src/main/orcad/instance-lock/orcad-process-start-time.test.ts', + 'src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts', + 'src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts', // The directory, not a prefix: its siblings are POSIX-host unit tests pr.yml already runs. 'src/main/daemon/pty-subprocess/conpty-startup-input-reader.ts', 'src/main/daemon/pty-subprocess/daemon-pty-physical-owner.ts', @@ -35,22 +35,19 @@ export function nodeServerTestPaths({ 'src/main/daemon/pty-subprocess/spawn-environment.ts', 'src/main/daemon/pty-subprocess/spawn-file-child-processes.ts', 'src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts', - 'src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts', 'src/main/daemon/pty-subprocess/spawn-preflight.ts', 'src/main/daemon/pty-subprocess/subprocess-handle.ts', - 'src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts', - 'src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts', ...(artifact ? [ 'tests/e2e/daemon-running-work-probe.unit.test.ts', 'src/shared/terminal/pty/lifecycle/pty-running-work-probe.test.ts', - 'src/main/orcad/orcad-packaged-node-pty.integration.test.ts', - 'src/main/providers/agent-foreground-process-git-bash.win32.test.ts', - 'src/main/orcad/orcad-cli-launcher.integration.test.ts', - 'src/main/orcad/orcad-launcher-isolation.integration.test.ts', - 'src/main/orcad/orcad-stop-request-shutdown.integration.test.ts', - 'src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts', - 'src/main/orcad/orcad-serve-parity.integration.test.ts', + 'src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts', + 'src/main/daemon/pty-subprocess/testing/agent-foreground-process-git-bash.win32.test.ts', + 'src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts', + 'src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts', + 'src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts', + 'src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts', + 'src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts', 'config/scripts/archives/platform-command/zip-extractor-command.test.mjs' ] : []), diff --git a/config/scripts/orcad-distribution/prebuilds/merge-orcad-prebuilds.test.mjs b/config/scripts/orcad-distribution/prebuilds/merge-orcad-prebuilds.test.mjs index a87f1e9d793..c20259b4849 100644 --- a/config/scripts/orcad-distribution/prebuilds/merge-orcad-prebuilds.test.mjs +++ b/config/scripts/orcad-distribution/prebuilds/merge-orcad-prebuilds.test.mjs @@ -45,15 +45,6 @@ function laneTree(slot, { version = '1.1.0', nodeHeaders = '24.21.0', bytes = sl } describe('mergeOrcadPrebuildTrees', () => { - it('refuses a lane whose files no longer match its own manifest', () => { - const lane = laneTree('win32-x64') - writeFileSync(join(lane, 'win32-x64', 'pty.node'), 'tampered') - - expect(() => mergeOrcadPrebuildTrees([lane], join(temp(), 'out'))).toThrow( - 'win32-x64/pty.node: sha256 does not match the manifest' - ) - }) - it('refuses the same slot from two lanes instead of letting the last one win', () => { const out = join(temp(), 'out') expect(() => diff --git a/config/scripts/orcad-distribution/server-bundle/foreign-sqlite-reader-worker-smoke.test.mjs b/config/scripts/orcad-distribution/server-bundle/foreign-sqlite-reader-worker-smoke.test.mjs deleted file mode 100644 index 8e51b59ab5f..00000000000 --- a/config/scripts/orcad-distribution/server-bundle/foreign-sqlite-reader-worker-smoke.test.mjs +++ /dev/null @@ -1,43 +0,0 @@ -import { build } from 'esbuild' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { smokeForeignSqliteReaderWorker } from './foreign-sqlite-reader-worker-smoke.mjs' -import { ORCAD_CHILD_ENTRY_POINTS } from './orcad-entry-build.mjs' - -const ENTRY = 'foreign-sqlite-reader-entry.js' -const directories = [] -let builtDirectory - -function fixtureDirectory() { - const directory = mkdtempSync(join(tmpdir(), 'orca-foreign-sqlite-smoke-test-')) - directories.push(directory) - return directory -} - -beforeAll(async () => { - builtDirectory = fixtureDirectory() - await build({ - entryPoints: [resolve(ORCAD_CHILD_ENTRY_POINTS.foreignSqliteReader)], - outfile: join(builtDirectory, ENTRY), - bundle: true, - platform: 'node', - target: 'node18', - format: 'cjs', - external: ['electron'], - logLevel: 'silent' - }) -}, 60_000) - -afterAll(() => { - for (const directory of directories) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -describe('foreign SQLite reader build smoke', () => { - it('passes against the built entry', () => { - expect(() => smokeForeignSqliteReaderWorker(builtDirectory)).not.toThrow() - }) -}) diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs index 116f01e391b..d08953600e9 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs @@ -22,6 +22,7 @@ export const ORCAD_CHILD_ENTRY_POINTS = { backup: 'src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts', sessionSearch: 'src/main/ai-vault-search/worker/session-search-worker-entry.ts', foreignSqliteReader: 'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts', + agentIdentityWorker: 'src/main/agent-hooks/identity/agent-identity-worker-entry.ts', portScanCommandWorker: 'src/main/ports/port-scan-command-worker-entry.ts', commandPathDirectoryWorker: 'src/main/ipc/command-path/command-path-directory-worker-entry.ts', sessionScanner: 'src/main/ai-vault/scan-service/session-scanner-service-entry.ts', @@ -29,7 +30,7 @@ export const ORCAD_CHILD_ENTRY_POINTS = { 'src/main/worker-thread-child-process/worker-thread-child-process-entry.ts', claudeProfileSetup: 'src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts', - claudeConversationFork: 'src/main/claude/claude-conversation-fork-worker-entry.ts', + claudeConversationFork: 'src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts', sttWorker: 'src/main/speech/stt-worker.ts', computerSidecar: 'src/main/computer/computer-sidecar.ts' } diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.test.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.test.mjs index 578e443dff9..319b6b6773c 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.test.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.test.mjs @@ -89,22 +89,19 @@ it('resolves bundle-relative requires after deployment to a path with URL-specia expect(loaded.stdout.trim()).toBe('deployed asset') }) -it.each(['import.meta', 'import.meta.dirname', 'import.meta.filename', 'import.meta.resolve'])( - 'rejects unsupported %s instead of silently replacing it with an empty object', - async (expression) => { - await expect( - build({ - ...ORCAD_COMMONJS_MODULE_OPTIONS, - stdin: { contents: `console.log(${expression})`, resolveDir: directory }, - bundle: true, - platform: 'node', - format: 'cjs', - write: false, - logLevel: 'silent' - }) - ).rejects.toThrow('"import.meta" is not available') - } -) +it('rejects unsupported import.meta.dirname instead of silently replacing it with an empty object', async () => { + await expect( + build({ + ...ORCAD_COMMONJS_MODULE_OPTIONS, + stdin: { contents: 'console.log(import.meta.dirname)', resolveDir: directory }, + bundle: true, + platform: 'node', + format: 'cjs', + write: false, + logLevel: 'silent' + }) + ).rejects.toThrow('"import.meta" is not available') +}) it('escapes only the trailing license comment, never code', () => { const code = 'a=/[\u2726]/;' diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-linear-sdk-package.test.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-linear-sdk-package.test.mjs index 6112ea6540b..d7e6983f97d 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-linear-sdk-package.test.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-linear-sdk-package.test.mjs @@ -4,7 +4,6 @@ import { join } from 'node:path' import { afterAll, beforeAll, expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' import { - ORCAD_ARTIFACTS, ORCAD_LINEAR_SDK_ENTRY, ORCAD_SERVER_ENTRY_FILENAME } from '../../../../src/shared/orcad-artifacts.ts' @@ -23,7 +22,6 @@ afterAll(() => { }) it("resolves linear-sdk.ts's lazy require from the deployed server under plain Node", () => { - expect(ORCAD_ARTIFACTS.map((artifact) => artifact.filename)).toContain(ORCAD_LINEAR_SDK_ENTRY) const server = join(deployment, ORCAD_SERVER_ENTRY_FILENAME) writeFileSync( server, diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.test.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.test.mjs deleted file mode 100644 index 4607ab7e923..00000000000 --- a/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.test.mjs +++ /dev/null @@ -1,43 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { ORCAD_MOBILE_WEB_MANIFEST } from '../../../../src/shared/orcad-artifacts.ts' -import { writeMobileWebBundleFixtureTree } from '../../build/mobile-web-app/mobile-web-bundle-fixture-tree.mjs' -import { - readOrcadMobileWebAssetFilenames, - stageOrcadMobileWebBundle -} from './orcad-mobile-web-bundle.mjs' - -let scratch -let bundleDir -let outputDir - -beforeEach(() => { - scratch = mkdtempSync(join(tmpdir(), 'orcad-mobile-web-')) - bundleDir = join(scratch, 'mobile-web') - outputDir = join(scratch, 'orcad') - vi.spyOn(console, 'log').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllEnvs() - rmSync(scratch, { recursive: true, force: true }) -}) - -it('stages the manifest and every asset it lists, byte for byte', async () => { - const { manifest } = await writeMobileWebBundleFixtureTree({ outDir: bundleDir }) - stageOrcadMobileWebBundle(outputDir, bundleDir) - - const staged = readOrcadMobileWebAssetFilenames(outputDir) - expect(staged).toHaveLength(manifest.assets.length) - for (const asset of manifest.assets) { - expect(readFileSync(join(outputDir, 'out', 'mobile-web', asset.path))).toEqual( - readFileSync(join(bundleDir, asset.path)) - ) - } - expect(readFileSync(join(outputDir, ORCAD_MOBILE_WEB_MANIFEST))).toEqual( - readFileSync(join(bundleDir, 'manifest.json')) - ) -}) diff --git a/config/scripts/orcad-distribution/server-bundle/session-scanner-service-smoke.test.mjs b/config/scripts/orcad-distribution/server-bundle/session-scanner-service-smoke.test.mjs deleted file mode 100644 index 60faa437f52..00000000000 --- a/config/scripts/orcad-distribution/server-bundle/session-scanner-service-smoke.test.mjs +++ /dev/null @@ -1,49 +0,0 @@ -import { build } from 'esbuild' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { smokeSessionScannerService } from './session-scanner-service-smoke.mjs' -import { - externalNativeAddons, - ORCAD_CHILD_ENTRY_POINTS, - ORCAD_EXTERNAL_MODULES, - orcadChildOutputFilename -} from './orcad-entry-build.mjs' - -const ENTRY = orcadChildOutputFilename(ORCAD_CHILD_ENTRY_POINTS.sessionScanner) -const directories = [] -let builtDirectory - -function fixtureDirectory() { - const directory = mkdtempSync(join(tmpdir(), 'orca-session-scanner-smoke-test-')) - directories.push(directory) - return directory -} - -beforeAll(async () => { - builtDirectory = fixtureDirectory() - await build({ - entryPoints: [resolve(ORCAD_CHILD_ENTRY_POINTS.sessionScanner)], - outfile: join(builtDirectory, ENTRY), - bundle: true, - platform: 'node', - target: 'node18', - format: 'cjs', - external: ORCAD_EXTERNAL_MODULES, - plugins: [externalNativeAddons], - logLevel: 'silent' - }) -}, 60_000) - -afterAll(() => { - for (const directory of directories) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -describe('session scanner service build smoke', () => { - it('lists a seeded session through the built entry', () => { - expect(() => smokeSessionScannerService(builtDirectory)).not.toThrow() - }, 60_000) -}) diff --git a/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs b/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs index b685476dd23..2313680fdd0 100644 --- a/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs +++ b/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs @@ -1,12 +1,12 @@ import { createHash } from 'node:crypto' -import { existsSync } from 'node:fs' -import { copyFile, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises' +import 'node:fs' +import { copyFile, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { basename, dirname, join } from 'node:path' +import { dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { assembleOrcadArtifact } from '../../../../src/main/orcad/orcad-artifact-materializer.ts' -import { readOrcadArtifactIdentity } from '../../../../src/main/orcad/orcad-artifact-identity.ts' +import '../../../../src/main/orcad/artifact-slots/orcad-artifact-materializer.ts' +import '../../../../src/main/orcad/artifact-slots/orcad-artifact-identity.ts' import { ORCAD_TEMPLATE_MANIFEST_FILENAME, orcadRipgrepArtifact @@ -46,63 +46,6 @@ async function fixture() { } describe('packaged ripgrep storage', () => { - it('preserves every deployed slot byte and version, including old schema 3 templates', async () => { - const f = await fixture() - const original = new Map() - const cacheRoot = join(f.appDir, 'cache') - for (const target of Object.keys(f.manifest.targets)) { - const slot = await assembleOrcadArtifact({ templateDir: f.templateDir, cacheRoot, target }) - original.set(target, basename(slot)) - } - expect(compactPackagedOrcadRipgrep(f.resourcesDir)).toBeGreaterThan(0) - expect(compactPackagedOrcadRipgrep(f.resourcesDir)).toBe(0) - for (const target of Object.keys(f.manifest.targets)) { - const slot = await assembleOrcadArtifact({ - templateDir: f.templateDir, - cacheRoot: join(f.appDir, 'fresh-cache'), - target - }) - expect(basename(slot)).toBe(original.get(target)) - expect(await readOrcadArtifactIdentity(slot)).toBe(original.get(target)) - const filename = orcadRipgrepArtifact(target) - expect(await readFile(join(slot, filename))).toEqual( - await readFile(join(f.resourcesDir, filename)) - ) - if (process.platform !== 'win32' && !target.startsWith('win32-')) { - expect((await stat(join(slot, filename))).mode & 0o777).toBe(0o755) - } - expect(existsSync(join(f.templateDir, 'targets', target, filename))).toBe( - target.startsWith('darwin-') - ) - } - // No template storage schema reaches the deployment slot. - expect( - existsSync( - join( - cacheRoot, - 'linux-x64-glibc', - original.get('linux-x64-glibc'), - ORCAD_TEMPLATE_MANIFEST_FILENAME - ) - ) - ).toBe(false) - }) - - it('keeps binaries that differ and never removes Darwin signing inputs', async () => { - const f = await fixture() - const desktop = join(f.resourcesDir, 'ripgrep/linux-arm64/rg') - await writeFile(desktop, 'different desktop bytes') - compactPackagedOrcadRipgrep(f.resourcesDir) - const manifest = JSON.parse(await readFile(f.manifestPath, 'utf8')) - expect(manifest.schemaVersion).toBe(4) - for (const [target, entry] of Object.entries(manifest.targets)) { - expect(entry.packagedRipgrep).toBe( - target.startsWith('darwin-') || target.startsWith('linux-arm64') ? undefined : true - ) - } - expect(await readFile(desktop, 'utf8')).toBe('different desktop bytes') - }) - it('does not launder corrupted target bytes while removing duplicates', async () => { const f = await fixture() await writeFile(join(f.templateDir, 'targets/linux-x64-glibc/ripgrep/linux-x64/rg'), 'tampered') diff --git a/config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs b/config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs deleted file mode 100644 index 85aa5737ee6..00000000000 --- a/config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs +++ /dev/null @@ -1,69 +0,0 @@ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { assembleOrcadArtifact } from '../../../../src/main/orcad/orcad-artifact-materializer.ts' -import { ORCAD_TEMPLATE_MANIFEST_FILENAME } from '../../../../src/shared/orcad-artifacts.ts' -import { writeOrcadTemplateTestFixture } from './orcad-template-test-fixture.mjs' - -const require = createRequire(import.meta.url) -const { - finalizePackagedOrcadTemplate, - resealSignedWindowsApp -} = require('./packaged-orcad-template.cjs') -const roots = [] - -afterEach(async () => { - vi.restoreAllMocks() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -async function packagedApp() { - vi.spyOn(console, 'log').mockImplementation(() => {}) - const appDir = await mkdtemp(join(tmpdir(), 'orca-packaged-browser-')) - roots.push(appDir) - const resourcesDir = join(appDir, 'resources') - const templateDir = await writeOrcadTemplateTestFixture(resourcesDir) - const driver = join(resourcesDir, 'agent-browser-win32-x64.exe') - await writeFile(driver, 'desktop driver') - await finalizePackagedOrcadTemplate(resourcesDir, { platform: 'win32', signMacBinary: vi.fn() }) - return { - appDir, - templateDir, - driver, - manifestPath: join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME) - } -} - -describe("packaged orcad uses the app's agent-browser driver (#33846)", () => { - it("materializes the host target's slot with the driver the app ships", async () => { - const app = await packagedApp() - const slot = await assembleOrcadArtifact({ - templateDir: app.templateDir, - cacheRoot: join(app.appDir, 'cache'), - target: 'win32-x64' - }) - expect(await readFile(join(slot, 'agent-browser-win32-x64.exe'), 'utf8')).toBe('desktop driver') - // A target that carries its own copy keeps it. - const manifest = JSON.parse(await readFile(app.manifestPath, 'utf8')) - expect(manifest.targets['linux-x64-glibc'].packagedBrowser).toBeUndefined() - expect(manifest.targets['win32-arm64'].browserName).toBeUndefined() - }) - - it('reseals the driver after SignPath rewrites it', async () => { - const app = await packagedApp() - await writeFile(app.driver, 'authenticode-signed driver') - const list = join(app.appDir, 'inner-signing-list.txt') - await writeFile(list, 'Orca.exe\r\nresources\\agent-browser-win32-x64.exe\r\n') - resealSignedWindowsApp(app.appDir, list) - const slot = await assembleOrcadArtifact({ - templateDir: app.templateDir, - cacheRoot: join(app.appDir, 'cache'), - target: 'win32-x64' - }) - expect(await readFile(join(slot, 'agent-browser-win32-x64.exe'), 'utf8')).toBe( - 'authenticode-signed driver' - ) - }) -}) diff --git a/config/scripts/performance/check-job-log/check-job-log-consumer-oracles.mjs b/config/scripts/performance/check-job-log/check-job-log-consumer-oracles.mjs index db333fd5888..9492a3be936 100644 --- a/config/scripts/performance/check-job-log/check-job-log-consumer-oracles.mjs +++ b/config/scripts/performance/check-job-log/check-job-log-consumer-oracles.mjs @@ -13,7 +13,7 @@ export async function loadAnsiConsumers(root = process.cwd()) { 'restoredSnapshotPaintsPrintableContent', 'renderer/src/components/terminal-pane/snapshots/restored-snapshot-coverage' ], - ['parseCodexLoginAuthUrl', 'main/codex-accounts/codex-login-auth-url'], + ['parseCodexLoginAuthUrl', 'main/codex-accounts/login/codex-login-auth-url'], ['TerminalCommandPaint', 'main/runtime/terminal/input/terminal-command-paint'], ['claudePermissionSubject', 'main/claude/claude-permission-presentation'], ['terminalSafe', 'shared/terminal/output/terminal-safe-text'] diff --git a/config/scripts/performance/measurement/benchmark-artifact-comparison.test.mjs b/config/scripts/performance/measurement/benchmark-artifact-comparison.test.mjs index 3abb570f748..dc83dc90144 100644 --- a/config/scripts/performance/measurement/benchmark-artifact-comparison.test.mjs +++ b/config/scripts/performance/measurement/benchmark-artifact-comparison.test.mjs @@ -1,5 +1,5 @@ import { spawnSync } 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 { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -37,26 +37,6 @@ afterEach(() => { }) describe('benchmark artifact comparison', () => { - it('rejects invalid benchmark artifacts before comparing partial metrics', () => { - const dir = makeTempDir() - const baselinePath = writeArtifact(dir, 'split-invalid.json', { - label: 'invalid split', - status: 'failed', - valid: false, - headlineMs: { shortcutToFocusP50: 0 } - }) - const candidatePath = writeArtifact(dir, 'split-valid.json', { - label: 'valid split', - status: 'passed', - valid: true, - headlineMs: { shortcutToFocusP50: 10 } - }) - - expect(() => comparePaths(baselinePath, candidatePath)).toThrow( - 'split-invalid.json: benchmark artifact is marked invalid' - ) - }) - it('aggregates duplicate Playwright scenario metrics before comparison', () => { const dir = makeTempDir() const baselinePath = writeArtifact(dir, 'baseline-playwright-duplicates.json', { @@ -181,47 +161,6 @@ describe('benchmark artifact comparison', () => { }) }) - it('writes Markdown and JSON reports from the CLI while printing Markdown', () => { - const dir = makeTempDir() - const baselinePath = writeArtifact(dir, 'baseline.json', { - label: 'baseline', - summaryMedianMs: { totalToDidFinishLoad: 100 } - }) - const candidatePath = writeArtifact(dir, 'candidate.json', { - label: 'candidate', - summaryMedianMs: { totalToDidFinishLoad: 40 } - }) - const markdownPath = join(dir, 'nested', 'comparison.md') - const jsonPath = join(dir, 'nested', 'comparison.json') - - const result = spawnSync( - process.execPath, - [ - scriptPath, - '--baseline', - baselinePath, - '--candidate', - candidatePath, - '--title', - 'Test Compare', - '--output', - markdownPath, - '--json-output', - jsonPath - ], - { cwd: process.cwd(), encoding: 'utf8' } - ) - - expect(result.status).toBe(0) - expect(result.stdout).toContain('| Metric | Baseline | Candidate | Delta | Delta % | Result |') - expect(result.stdout).toContain( - '| totalToDidFinishLoad | 100.0ms | 40.0ms | -60.0ms | -60.0% | improved |' - ) - expect(existsSync(markdownPath)).toBe(true) - expect(existsSync(jsonPath)).toBe(true) - expect(JSON.parse(readFileSync(jsonPath, 'utf8')).schemaVersion).toBe(1) - }) - it('redacts absolute input paths from generated reports', () => { const dir = makeTempDir() const baselinePath = writeArtifact(dir, 'absolute-baseline.json', { diff --git a/config/scripts/performance/mobile-projection/mobile-linear-group-sorted-benchmark.mjs b/config/scripts/performance/mobile-projection/mobile-linear-group-sorted-benchmark.mjs index fb4df6d2af7..9c68f0c1f56 100644 --- a/config/scripts/performance/mobile-projection/mobile-linear-group-sorted-benchmark.mjs +++ b/config/scripts/performance/mobile-projection/mobile-linear-group-sorted-benchmark.mjs @@ -14,7 +14,12 @@ if (!baseline) { } async function load(file, contents) { const result = await build({ - stdin: { contents, loader: 'ts', resolveDir: dirname(resolve(file)) }, + stdin: { + contents, + sourcefile: resolve(file), + loader: 'ts', + resolveDir: dirname(resolve(file)) + }, bundle: true, platform: 'node', format: 'esm', @@ -28,6 +33,23 @@ async function load(file, contents) { bundler.onResolve({ filter: /mobile-tasks-dependencies$/ }, () => ({ path: resolve('mobile/src/theme/mobile-theme.ts') })) + const relocatedImports = new Map([ + [ + resolve('mobile/src/tasks/mobile-tasks-hosted-review'), + resolve('mobile/src/tasks/hosted-review/mobile-tasks-hosted-review.ts') + ], + [ + resolve('mobile/src/tasks/mobile-tasks-item-mapping'), + resolve('mobile/src/tasks/item-detail/mobile-tasks-item-mapping.ts') + ] + ]) + bundler.onResolve({ filter: /^\./ }, (args) => { + if (args.importer !== resolve(originalFile)) { + return + } + const target = relocatedImports.get(resolve(args.resolveDir, args.path)) + return target ? { path: target } : undefined + }) } } ] @@ -36,17 +58,24 @@ async function load(file, contents) { `data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}` ) } -const file = 'mobile/src/tasks/mobile-tasks-reviewer-linear.ts' +const originalFile = 'mobile/src/tasks/mobile-tasks-reviewer-linear.ts' +const file = 'mobile/src/tasks/item-detail/mobile-tasks-reviewer-linear.ts' const original = await load( - file, - execFileSync('git', ['show', `${baseline}:${file}`], { encoding: 'utf8', windowsHide: true }) + originalFile, + execFileSync('git', ['show', `${baseline}:${originalFile}`], { + encoding: 'utf8', + windowsHide: true + }) ) const current = await load(file, readFileSync(file, 'utf8')) const sorterRef = process.argv[3] const sorter = sorterRef ? await load( - file, - execFileSync('git', ['show', `${sorterRef}:${file}`], { encoding: 'utf8', windowsHide: true }) + originalFile, + execFileSync('git', ['show', `${sorterRef}:${originalFile}`], { + encoding: 'utf8', + windowsHide: true + }) ) : original const results = [] diff --git a/config/scripts/performance/mobile-projection/mobile-linear-sort-benchmark.mjs b/config/scripts/performance/mobile-projection/mobile-linear-sort-benchmark.mjs index 7a9c0107f89..4c97acd0fa0 100644 --- a/config/scripts/performance/mobile-projection/mobile-linear-sort-benchmark.mjs +++ b/config/scripts/performance/mobile-projection/mobile-linear-sort-benchmark.mjs @@ -14,7 +14,12 @@ if (!baseline) { } async function load(file, contents) { const result = await build({ - stdin: { contents, loader: 'ts', resolveDir: dirname(resolve(file)) }, + stdin: { + contents, + sourcefile: resolve(file), + loader: 'ts', + resolveDir: dirname(resolve(file)) + }, bundle: true, platform: 'node', format: 'esm', @@ -28,6 +33,23 @@ async function load(file, contents) { bundler.onResolve({ filter: /mobile-tasks-dependencies$/ }, () => ({ path: resolve('mobile/src/theme/mobile-theme.ts') })) + const relocatedImports = new Map([ + [ + resolve('mobile/src/tasks/mobile-tasks-hosted-review'), + resolve('mobile/src/tasks/hosted-review/mobile-tasks-hosted-review.ts') + ], + [ + resolve('mobile/src/tasks/mobile-tasks-item-mapping'), + resolve('mobile/src/tasks/item-detail/mobile-tasks-item-mapping.ts') + ] + ]) + bundler.onResolve({ filter: /^\./ }, (args) => { + if (args.importer !== resolve(originalFile)) { + return + } + const target = relocatedImports.get(resolve(args.resolveDir, args.path)) + return target ? { path: target } : undefined + }) } } ] @@ -36,10 +58,11 @@ async function load(file, contents) { `data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}` ) } -const file = 'mobile/src/tasks/mobile-tasks-reviewer-linear.ts' +const originalFile = 'mobile/src/tasks/mobile-tasks-reviewer-linear.ts' +const file = 'mobile/src/tasks/item-detail/mobile-tasks-reviewer-linear.ts' const before = await load( - file, - execFileSync('git', ['show', `${baseline}:${file}`], { encoding: 'utf8' }) + originalFile, + execFileSync('git', ['show', `${baseline}:${originalFile}`], { encoding: 'utf8' }) ) const after = await load(file, readFileSync(file, 'utf8')) const results = [] diff --git a/config/scripts/performance/mobile-projection/mobile-source-control-collation-benchmark.mjs b/config/scripts/performance/mobile-projection/mobile-source-control-collation-benchmark.mjs index 68c2ea699a3..4c3c71ea332 100644 --- a/config/scripts/performance/mobile-projection/mobile-source-control-collation-benchmark.mjs +++ b/config/scripts/performance/mobile-projection/mobile-source-control-collation-benchmark.mjs @@ -4,6 +4,8 @@ import { readFileSync } from 'node:fs' import { dirname, resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { build } from 'esbuild' +import { runProcessSync } from '@orca/process-host' +import { describeProcessFailure } from '../../tool-invocation/process-failure-message.mjs' import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' const baseline = process.argv[2] @@ -20,7 +22,31 @@ async function load(file, contents, name) { format: 'esm', write: false, logLevel: 'silent', - tsconfigRaw: {} + tsconfigRaw: {}, + plugins: [ + { + name: 'historical-source-control-owners', + setup(plugin) { + plugin.onResolve( + { filter: /^\.\.\/(?:mobile-git-status|git-status-reply-schema)$/ }, + (args) => { + if ( + file !== 'mobile/src/source-control/review/mobile-diff-review-queue.ts' || + args.importer !== '' || + args.resolveDir !== dirname(resolve(file)) + ) { + return + } + const target = + args.path === '../mobile-git-status' + ? 'mobile/src/source-control/changes/mobile-git-status.ts' + : 'mobile/src/source-control/git/git-status-reply-schema.ts' + return { path: resolve(target) } + } + ) + } + } + ] }) return ( await import( @@ -34,18 +60,44 @@ const paths = execFileSync('git', ['ls-files', '-z'], { maxBuffer: 16 * 1024 * 1 .split('\0') .filter(Boolean) const results = [] -for (const [file, name] of [ - ['mobile/src/source-control/mobile-git-status.ts', 'buildMobileSourceControlSections'], - ['mobile/src/source-control/mobile-branch-compare.ts', 'buildMobileBranchCompareSection'], - ['mobile/src/source-control/review/mobile-diff-review-queue.ts', 'buildMobileDiffReviewQueue'] +for (const { baselineLegacy, current, name } of [ + { + baselineLegacy: 'mobile/src/source-control/mobile-git-status.ts', + current: 'mobile/src/source-control/changes/mobile-git-status.ts', + name: 'buildMobileSourceControlSections' + }, + { + baselineLegacy: 'mobile/src/source-control/mobile-branch-compare.ts', + current: 'mobile/src/source-control/branches/mobile-branch-compare.ts', + name: 'buildMobileBranchCompareSection' + }, + { + baselineLegacy: 'mobile/src/source-control/review/mobile-diff-review-queue.ts', + current: 'mobile/src/source-control/review/mobile-diff-review-queue.ts', + name: 'buildMobileDiffReviewQueue' + } ]) { + const historicalFile = [...new Set([current, baselineLegacy])].find((file) => { + const probe = runProcessSync({ + program: 'git', + args: ['cat-file', '-t', `${baseline}:${file}`], + cwd: process.cwd(), + timeoutMs: 30_000, + maxOutputBytes: 2 * 1024 * 1024 + }) + if (probe.timedOut || probe.outputTruncated || ![0, 128].includes(probe.code)) { + throw new Error(describeProcessFailure(probe)) + } + return probe.code === 0 && probe.stdout.trim() === 'blob' + }) + assert(historicalFile, `Missing baseline entry: ${baselineLegacy}`) const arms = { before: await load( - file, - execFileSync('git', ['show', `${baseline}:${file}`], { encoding: 'utf8' }), + historicalFile, + execFileSync('git', ['show', `${baseline}:${historicalFile}`], { encoding: 'utf8' }), name ), - after: await load(file, readFileSync(file, 'utf8'), name) + after: await load(current, readFileSync(current, 'utf8'), name) } for (const count of [0, 1, 17, 63, 1000]) { const step = Math.max(1, Math.floor(paths.length / Math.max(1, count))) diff --git a/config/scripts/performance/mobile-projection/mobile-task-sort-benchmark.mjs b/config/scripts/performance/mobile-projection/mobile-task-sort-benchmark.mjs index 2fc4788dc85..06c433cc7c1 100644 --- a/config/scripts/performance/mobile-projection/mobile-task-sort-benchmark.mjs +++ b/config/scripts/performance/mobile-projection/mobile-task-sort-benchmark.mjs @@ -14,7 +14,12 @@ if (!baseline) { } async function load(file, contents) { const result = await build({ - stdin: { contents, loader: 'ts', resolveDir: dirname(resolve(file)) }, + stdin: { + contents, + sourcefile: resolve(file), + loader: 'ts', + resolveDir: dirname(resolve(file)) + }, bundle: true, platform: 'node', format: 'esm', @@ -28,6 +33,19 @@ async function load(file, contents) { bundler.onResolve({ filter: /mobile-tasks-dependencies$/ }, () => ({ path: resolve('mobile/src/theme/mobile-theme.ts') })) + const relocatedImports = new Map([ + [ + resolve('mobile/src/tasks/mobile-tasks-item-mapping'), + resolve('mobile/src/tasks/item-detail/mobile-tasks-item-mapping.ts') + ] + ]) + bundler.onResolve({ filter: /^\./ }, (args) => { + if (args.importer !== resolve(originalFile)) { + return + } + const target = relocatedImports.get(resolve(args.resolveDir, args.path)) + return target ? { path: target } : undefined + }) } } ] @@ -36,10 +54,11 @@ async function load(file, contents) { `data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}` ) } -const file = 'mobile/src/tasks/mobile-tasks-repository-presentation.ts' +const originalFile = 'mobile/src/tasks/mobile-tasks-repository-presentation.ts' +const file = 'mobile/src/tasks/repositories/mobile-tasks-repository-presentation.ts' const before = await load( - file, - execFileSync('git', ['show', `${baseline}:${file}`], { encoding: 'utf8' }) + originalFile, + execFileSync('git', ['show', `${baseline}:${originalFile}`], { encoding: 'utf8' }) ) const after = await load(file, readFileSync(file, 'utf8')) const repos = new Map() diff --git a/config/scripts/performance/session-transcripts/session-dedup-batches-benchmark.mjs b/config/scripts/performance/session-transcripts/session-dedup-batches-benchmark.mjs index 44a0bbd187c..6dac3efbbf3 100644 --- a/config/scripts/performance/session-transcripts/session-dedup-batches-benchmark.mjs +++ b/config/scripts/performance/session-transcripts/session-dedup-batches-benchmark.mjs @@ -5,7 +5,7 @@ import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-ben const bundled = await build({ stdin: { - contents: "export * from './src/main/ai-vault/session-root-dedup.ts'", + contents: "export * from './src/main/ai-vault/parsing/session-root-dedup.ts'", resolveDir: process.cwd(), loader: 'ts' }, diff --git a/config/scripts/performance/session-transcripts/session-scan-cutoff-benchmark.mjs b/config/scripts/performance/session-transcripts/session-scan-cutoff-benchmark.mjs index b7311577324..07e54291087 100644 --- a/config/scripts/performance/session-transcripts/session-scan-cutoff-benchmark.mjs +++ b/config/scripts/performance/session-transcripts/session-scan-cutoff-benchmark.mjs @@ -32,10 +32,10 @@ async function load(contents) { return import(`data:text/javascript;base64,${encoded}`) } const [baselineModule, currentModule] = await Promise.all([ - load(`import { sessionSortTime } from './session-scanner-accumulator'; + load(`import { sessionSortTime } from './parsing/session-scanner-accumulator'; export ${baselineFunction.getText(baselineSource)}`), - load(`export { canStopParsingSessions } from './session-scan-cutoff'; -export { ScannedSessionCollection } from './session-root-dedup';`) + load(`export { canStopParsingSessions } from './parsing/session-scan-cutoff'; +export { ScannedSessionCollection } from './parsing/session-root-dedup';`) ]) const baseline = baselineModule.canStopParsingSessions const current = currentModule.canStopParsingSessions diff --git a/config/scripts/performance/session-transcripts/session-timeline-benchmark.mjs b/config/scripts/performance/session-transcripts/session-timeline-benchmark.mjs index 7e53173fcaf..71373dbab13 100644 --- a/config/scripts/performance/session-transcripts/session-timeline-benchmark.mjs +++ b/config/scripts/performance/session-transcripts/session-timeline-benchmark.mjs @@ -1,28 +1,81 @@ import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' -import { dirname, resolve } from 'node:path' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { build } from 'esbuild' import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' import { summarizeBenchmarkSamples } from '../measurement/benchmark-sample-summary.mjs' +import ts from 'typescript-api' + +const baselineSourcePathArgument = process.argv.find((arg) => + arg.startsWith('--baseline-source-path=') +) +const baselineSourcePath = resolve( + baselineSourcePathArgument?.slice('--baseline-source-path='.length) ?? + 'src/main/ai-vault/session-scanner-accumulator.ts' +) + +function retargetLegacyAccumulatorValueImports(source) { + const program = ts.createSourceFile(baselineSourcePath, source, ts.ScriptTarget.Latest, true) + assert.equal(program.parseDiagnostics.length, 0, 'Baseline source must parse') + const replacements = [] + for (const statement of program.statements) { + if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) { + continue + } + if ( + resolve(dirname(baselineSourcePath), statement.moduleSpecifier.text) !== + resolve('src/main/ai-vault/session-scanner-values') + ) { + continue + } + const clause = statement.importClause + assert( + clause && !clause.name && clause.namedBindings && ts.isNamedImports(clause.namedBindings) + ) + const imports = clause.namedBindings.elements.map((binding) => { + const name = (binding.propertyName ?? binding.name).text + const owner = + name === 'extractString' + ? 'src/shared/trimmed-string.ts' + : name === 'timestampMs' + ? 'src/main/ai-vault/parsing/session-record-time.ts' + : null + assert(owner, `Unsupported historical accumulator value import: ${name}`) + return `import ${clause.isTypeOnly ? 'type ' : ''}{ ${binding.getText(program)} } from ${JSON.stringify(resolve(owner))}` + }) + replacements.push({ + start: statement.getStart(program), + end: statement.end, + text: imports.join('\n') + }) + } + for (const replacement of replacements.toReversed()) { + source = source.slice(0, replacement.start) + replacement.text + source.slice(replacement.end) + } + return source +} // git show :src/main/ai-vault/session-scanner-accumulator.ts | node config/scripts/session-timeline-benchmark.mjs -const target = resolve('src/main/ai-vault/session-scanner-accumulator.ts') -async function load(source) { +const target = resolve('src/main/ai-vault/parsing/session-scanner-accumulator.ts') +async function load(source, sourcePath = target) { const result = await build({ stdin: { contents: ` export {createAccumulator, cloneSessionAccumulator, updateTimeline, finalizeSession} from './session-scanner-accumulator'; export {createClaudeSessionParseState, consumeClaudeSessionLine} - from './session-scanner-primary-parsers';`, + from '../scanners/claude/session-scanner-primary-parsers';`, loader: 'ts', resolveDir: dirname(target) }, bundle: true, write: false, platform: 'node', - format: 'esm', + format: 'cjs', plugins: [ { name: 'timeline-baseline', @@ -30,18 +83,26 @@ async function load(source) { plugin.onLoad({ filter: /session-scanner-accumulator\.ts$/ }, () => ({ contents: source, loader: 'ts', - resolveDir: dirname(target) + resolveDir: dirname(sourcePath) })) } } ] }) - return import( - `data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}` - ) + const directory = await mkdtemp(join(tmpdir(), 'orca-session-timeline-')) + try { + const file = join(directory, 'timeline.cjs') + await writeFile(file, result.outputFiles[0].text) + return createRequire(import.meta.url)(file) + } finally { + await rm(directory, { recursive: true, force: true }) + } } const implementations = { - before: await load(readFileSync(0, 'utf8')), + before: await load( + retargetLegacyAccumulatorValueImports(readFileSync(0, 'utf8')), + baselineSourcePath + ), after: await load(readFileSync(target, 'utf8')) } const file = { path: 'timeline.jsonl', mtimeMs: 0, modifiedAt: '2026-01-01T00:00:00.000Z' } diff --git a/config/scripts/performance/session-transcripts/transcript-stream-fragments-benchmark.mjs b/config/scripts/performance/session-transcripts/transcript-stream-fragments-benchmark.mjs index 786d1e8d047..28605ad332e 100644 --- a/config/scripts/performance/session-transcripts/transcript-stream-fragments-benchmark.mjs +++ b/config/scripts/performance/session-transcripts/transcript-stream-fragments-benchmark.mjs @@ -6,7 +6,7 @@ import { performance } from 'node:perf_hooks' import { build } from 'esbuild' import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' -const modulePath = 'src/main/native-chat/transcript-stream-lines.ts' +const modulePath = 'src/main/native-chat/transcript-streaming/transcript-stream-lines.ts' const baselineSource = readFileSync(0, 'utf8') assert.ok(baselineSource.includes('decodeTranscriptStream'), 'Pipe the baseline module on stdin') const arms = {} diff --git a/config/scripts/performance/source-control/git-diff-blob-concurrency-benchmark.mjs b/config/scripts/performance/source-control/git-diff-blob-concurrency-benchmark.mjs index 094372b3162..744c126a09f 100644 --- a/config/scripts/performance/source-control/git-diff-blob-concurrency-benchmark.mjs +++ b/config/scripts/performance/source-control/git-diff-blob-concurrency-benchmark.mjs @@ -70,7 +70,7 @@ const parent = `${head}~1` // Span file sizes to cover both fixed spawn and size-dependent read costs. const CANDIDATES = [ - 'src/main/git/source-control/file-diff.ts', + 'src/main/git/source-control/diffs/file-diff.ts', 'src/shared/agent-hook-listener/normalization/normalize-hook-payload.ts', 'src/renderer/src/components/task-page/TaskPage.tsx' ] diff --git a/config/scripts/performance/source-control/worktree-refresh-churn-benchmark.mjs b/config/scripts/performance/source-control/worktree-refresh-churn-benchmark.mjs index fe5d9eaf348..db1a7983c98 100644 --- a/config/scripts/performance/source-control/worktree-refresh-churn-benchmark.mjs +++ b/config/scripts/performance/source-control/worktree-refresh-churn-benchmark.mjs @@ -5,7 +5,7 @@ import { createJiti } from 'jiti' // Use jiti: Node type stripping cannot resolve graph’s extensionless imports. const jiti = createJiti(import.meta.url) const { planWorktreeSortOrderUpdates } = await jiti.import( - '../../../../src/shared/worktree/sort-order-update.ts' + '../../../../src/shared/worktree/metadata/sort-order-update.ts' ) const { reuseEqualCatalogRows } = await jiti.import( '../../../../src/renderer/src/lib/catalog-reconciliation/catalog-row-reconciliation.ts' diff --git a/config/scripts/performance/terminal-input/mobile-backspace-benchmark.mjs b/config/scripts/performance/terminal-input/mobile-backspace-benchmark.mjs index c5256e4fee2..11c7a7e2616 100644 --- a/config/scripts/performance/terminal-input/mobile-backspace-benchmark.mjs +++ b/config/scripts/performance/terminal-input/mobile-backspace-benchmark.mjs @@ -6,8 +6,8 @@ import { build } from 'esbuild' import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' import { summarizeBenchmarkSamples } from '../measurement/benchmark-sample-summary.mjs' -// git show :mobile/src/terminal/terminal-live-text-commit.ts | node config/scripts/mobile-backspace-benchmark.mjs -const target = resolve('mobile/src/terminal/terminal-live-text-commit.ts') +// git show :mobile/src/terminal/live-input/terminal-live-text-commit.ts | node config/scripts/mobile-backspace-benchmark.mjs +const target = resolve('mobile/src/terminal/live-input/terminal-live-text-commit.ts') async function load(source) { const result = await build({ stdin: { contents: source, loader: 'ts', resolveDir: dirname(target) }, diff --git a/config/scripts/performance/terminal-reporting/check-terminal-perf-report-budgets.test.mjs b/config/scripts/performance/terminal-reporting/check-terminal-perf-report-budgets.test.mjs deleted file mode 100644 index ca9bafeb674..00000000000 --- a/config/scripts/performance/terminal-reporting/check-terminal-perf-report-budgets.test.mjs +++ /dev/null @@ -1,79 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' - -const scriptPath = - 'config/scripts/performance/terminal-reporting/check-terminal-perf-report-budgets.mjs' -const tempDirs = [] - -function writeReport(annotationDescription, annotationType = 'opencode-test') { - const dir = mkdtempSync(join(tmpdir(), 'orca-terminal-perf-report-')) - tempDirs.push(dir) - const reportPath = join(dir, 'report.json') - writeFileSync( - reportPath, - JSON.stringify({ - suites: [ - { - specs: [ - { - tests: [ - { - annotations: [ - { - type: annotationType, - description: annotationDescription - } - ] - } - ] - } - ] - } - ] - }) - ) - return reportPath -} - -function runChecker(reportPath) { - return spawnSync(process.execPath, [scriptPath, reportPath], { - cwd: process.cwd(), - encoding: 'utf8' - }) -} - -afterEach(() => { - while (tempDirs.length > 0) { - rmSync(tempDirs.pop(), { force: true, recursive: true }) - } -}) - -describe('check-terminal-perf-report-budgets', () => { - // Redraw scenarios must not inherit the unloaded drift ceiling. - - // Historical outliers must not become the new latency baseline. - - it('fails malformed metric values instead of treating them as absent', () => { - const reportPath = writeReport('panes=1 median=999 worst=abcms rendererQueuedChars=wat') - - const result = runChecker(reportPath) - - expect(result.status).toBe(1) - expect(result.stderr).toContain('median value "999" is malformed') - expect(result.stderr).toContain('worst value "abcms" is malformed') - expect(result.stderr).toContain('rendererQueuedChars value "wat" is malformed') - expect(result.stderr).toContain('no recognized budget metrics found') - }) - - it('ignores non-OpenCode annotations but fails when no perf rows remain', () => { - const reportPath = writeReport('median=999.0ms', 'browser-unrelated') - - const result = runChecker(reportPath) - - expect(result.status).toBe(1) - expect(result.stderr).toContain('No OpenCode terminal perf annotations found.') - }) -}) diff --git a/config/scripts/performance/terminal-stream/relay-json-payload-benchmark.ts b/config/scripts/performance/terminal-stream/relay-json-payload-benchmark.ts index 6c4de9edf95..2db777f2c39 100644 --- a/config/scripts/performance/terminal-stream/relay-json-payload-benchmark.ts +++ b/config/scripts/performance/terminal-stream/relay-json-payload-benchmark.ts @@ -1,15 +1,14 @@ import assert from 'node:assert/strict' import { performance } from 'node:perf_hooks' import { platform, release } from 'node:os' +import { HEADER_LENGTH, MAX_MESSAGE_SIZE } from '../../../../src/shared/relay-frame-decoder' import { - HEADER_LENGTH, - MAX_MESSAGE_SIZE, MessageType, encodeFrame, encodePreparedJsonRpcFrame, prepareJsonRpcPayload, type JsonRpcNotification -} from '../../../../src/wsl-guest/protocol' +} from '../../../../src/wsl-guest/transport/wire/protocol' type BenchmarkCase = { name: string diff --git a/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs b/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs index 3869c703a5f..555e1bc69cb 100644 --- a/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs +++ b/config/scripts/performance/terminal-stream/terminal-output-frame-chunk-benchmark.mjs @@ -50,7 +50,10 @@ if (ROUNDS % 2 !== 0) { } const CHUNK_SOURCE = readFileSync( - new URL('../../../../src/main/runtime/rpc/terminal-output-frame-chunks.ts', import.meta.url), + new URL( + '../../../../src/main/runtime/rpc/terminal/terminal-output-frame-chunks.ts', + import.meta.url + ), 'utf8' ) @@ -101,7 +104,10 @@ const { TerminalStreamOpcode, encodeTerminalStreamJson, encodeTerminalStreamText .href ) const { exceedsTerminalStreamChunkBytes, iterateTerminalOutputFrameChunks } = await import( - new URL('../../../../src/main/runtime/rpc/terminal-output-frame-chunks.ts', import.meta.url).href + new URL( + '../../../../src/main/runtime/rpc/terminal/terminal-output-frame-chunks.ts', + import.meta.url + ).href ) function previousGate(data) { diff --git a/config/scripts/performance/terminal-stream/terminal-shutdown-byte-limit-benchmark.mjs b/config/scripts/performance/terminal-stream/terminal-shutdown-byte-limit-benchmark.mjs index 874600c3049..7eed0f984b9 100644 --- a/config/scripts/performance/terminal-stream/terminal-shutdown-byte-limit-benchmark.mjs +++ b/config/scripts/performance/terminal-stream/terminal-shutdown-byte-limit-benchmark.mjs @@ -44,7 +44,7 @@ const layoutFunctions = layoutAst.statements.filter( assert.equal(layoutFunctions.length, layoutNames.length) const layoutSubset = `import { isTerminalLeafId } from ${JSON.stringify(path.resolve('src/shared/workspace-layout/stable-pane-id.ts'))}; import { readSplitRatio } from '@/lib/pane-manager/pane-layout/pane-split-ratio'; -import { SPLIT_RATIO_TOLERANCE } from ${JSON.stringify(path.resolve('src/shared/workspace-layout/terminal-pane-tree.ts'))}; +import { SPLIT_RATIO_TOLERANCE } from ${JSON.stringify(path.resolve('src/shared/workspace-layout/terminal-topology/terminal-pane-tree.ts'))}; ${layoutFunctions.map((node) => node.getText(layoutAst)).join('\n')}` async function load(source) { @@ -65,6 +65,11 @@ async function load(source) { resolveDir: path.dirname(entry) })) // Historical inputs keep their bodies while imports select this checkout's defining owners. + builder.onResolve({ filter: /(?:^|[/\\])terminal-pane-layout-tree$/ }, () => ({ + path: path.resolve( + 'src/shared/workspace-layout/terminal-topology/terminal-pane-layout-tree.ts' + ) + })) builder.onResolve({ filter: /^(?:\.\.\/)+shared\// }, (args) => { const target = path.resolve('src/shared', args.path.split('/shared/')[1]) return { path: existsSync(target) ? target : `${target}.ts` } diff --git a/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs b/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs index 85d0ce1da1d..493290c7b11 100644 --- a/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs +++ b/config/scripts/performance/terminal-stream/terminal-stream-byte-length-benchmark.mjs @@ -68,7 +68,10 @@ const { measureTerminalStreamByteLength, terminalStreamByteLengthExceeds } = await import( - new URL('../../../../src/main/runtime/rpc/terminal-stream-byte-length.ts', import.meta.url).href + new URL( + '../../../../src/main/runtime/rpc/terminal/terminal-stream-byte-length.ts', + import.meta.url + ).href ) const REQUESTED_SNAPSHOT_BYTE_BUDGET = (() => { diff --git a/config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs b/config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs deleted file mode 100644 index 21e3e86cabc..00000000000 --- a/config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env node -// Compare real CLI emits before/after deferring RuntimeClient’s Zod/ws/tweetnacl/store graph until after flag validation. -// Restore seven baseline files; use fresh processes to measure cold graphs, alternate arm order, and verify output/exit equality before timing. -import { execFileSync, spawnSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { performance } from 'node:perf_hooks' -import { fileURLToPath } from 'node:url' - -const REPO = fileURLToPath(new URL('../../../..', import.meta.url)) - -const ROUNDS = Number(process.env.ORCA_CLI_DEFER_BENCH_ROUNDS ?? '30') -const WARMUP = Number(process.env.ORCA_CLI_DEFER_BENCH_WARMUP ?? '3') - -for (const [name, value] of [ - ['ORCA_CLI_DEFER_BENCH_ROUNDS', ROUNDS], - ['ORCA_CLI_DEFER_BENCH_WARMUP', WARMUP] -]) { - if (!Number.isSafeInteger(value) || value <= 0) { - throw new Error(`${name} must be a positive integer, received ${value}`) - } -} -if (ROUNDS % 2 !== 0) { - // Why: arms alternate which one leads; an odd count biases one arm. - throw new Error(`ORCA_CLI_DEFER_BENCH_ROUNDS must be even, received ${ROUNDS}`) -} - -const TOUCHED = [ - 'src/cli/args.ts', - 'src/cli/dispatch.ts', - 'src/cli/flags.ts', - 'src/cli/format.ts', - 'src/cli/index.ts', - 'src/cli/runtime/client.ts', - 'src/cli/selectors.ts' -] - -// Re-read production call forms so reverting deferral cannot make both arms identical; prose mentions must not satisfy the guard. -function assertMarkersFresh() { - const checks = [ - ['src/cli/index.ts', "await import('./runtime-client.js')"], - ['src/cli/index.ts', 'await loadRuntimeClientClass()'], - ['src/cli/index.ts', "import type { RuntimeClient } from './runtime-client'"], - ['src/cli/runtime/client.ts', "await import('./websocket-transport.js')"], - ['src/cli/runtime/client.ts', 'await loadSendWebSocketRequest()'], - ['src/cli/args.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/flags.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/dispatch.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/selectors.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/format.ts', "} from './runtime/types'"] - ] - for (const [file, marker] of checks) { - if (!readFileSync(join(REPO, file), 'utf8').includes(marker)) { - throw new Error( - `${file} no longer contains \`${marker}\` — cli-runtime-client-deferral-benchmark.mjs is stale` - ) - } - } -} - -function buildArm(label, baselineRev) { - // Build inside repo so emitted modules resolve its node_modules. - const outDir = join(REPO, `.bench-out-${label}`) - rmSync(outDir, { recursive: true, force: true }) - const restore = [] - try { - if (baselineRev) { - for (const file of TOUCHED) { - const path = join(REPO, file) - restore.push([path, readFileSync(path)]) - writeFileSync( - path, - execFileSync('git', ['show', `${baselineRev}:${file}`], { - cwd: REPO, - maxBuffer: 64 * 1024 * 1024 - }) - ) - } - } - execFileSync( - 'npx', - [ - 'tsc', - '-p', - 'config/tsconfig.cli.json', - '--outDir', - outDir, - '--composite', - 'false', - '--incremental', - 'false' - ], - { cwd: REPO, stdio: 'inherit' } - ) - } finally { - for (const [path, contents] of restore) { - writeFileSync(path, contents) - } - } - return join(outDir, 'cli/index.js') -} - -function run(entry, argv, env) { - const result = spawnSync(process.execPath, [entry, ...argv], { - cwd: REPO, - env: { ...process.env, ...env }, - encoding: 'buffer' - }) - if (result.error) { - throw result.error - } - return { - status: result.status, - stdout: result.stdout.toString('utf8'), - stderr: result.stderr.toString('utf8') - } -} - -// Count eager CJS graph in a child via Module._load, measuring the graph deferral actually moves. -function countEagerModules(entry) { - const probe = ` - const Module = require('module') - const original = Module._load - const seen = new Set() - Module._load = function (request, parent, isMain) { - try { seen.add(Module._resolveFilename(request, parent, isMain)) } catch { seen.add(request) } - return original.apply(this, arguments) - } - require(${JSON.stringify(entry)}) - const all = [...seen] - process.stdout.write(JSON.stringify({ - total: all.length, - nodeModules: all.filter((p) => p.includes('node_modules')).length - })) - ` - const result = spawnSync(process.execPath, ['-e', probe], { cwd: REPO, encoding: 'utf8' }) - if (result.status !== 0) { - throw new Error(`module probe failed: ${result.stderr}`) - } - return JSON.parse(result.stdout) -} - -const median = (values) => { - const sorted = [...values].sort((a, b) => a - b) - return sorted[Math.floor(sorted.length / 2)] -} - -const baselineIndex = process.argv.indexOf('--baseline') -const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] - -assertMarkersFresh() - -const userDataPath = mkdtempSync(join(REPO, '.bench-userdata-')) - -try { - console.log(`Building eager baseline (${baselineRev}) …`) - const eagerEntry = buildArm('eager', baselineRev) - console.log('Building deferred (working tree) …') - const deferredEntry = buildArm('deferred', null) - - const eagerGraph = countEagerModules(eagerEntry) - const deferredGraph = countEagerModules(deferredEntry) - console.log( - `\nEager modules at process load: ${eagerGraph.total} -> ${deferredGraph.total} ` + - `(node_modules ${eagerGraph.nodeModules} -> ${deferredGraph.nodeModules})` - ) - if (deferredGraph.total >= eagerGraph.total) { - throw new Error( - 'deferred arm loads no fewer modules — the fixture does not exercise the change' - ) - } - - // Use empty user-data dirs for deterministic runtime-dependent cases. - const isolated = { ORCA_USER_DATA_PATH: userDataPath } - /** @type {Array<[string, string[], Record]>} */ - const cases = [ - ['orca --help', ['--help'], {}], - ['orca help worktree', ['help', 'worktree'], {}], - ['orca (no args)', [], {}], - ['unknown command', ['no-such-command'], {}], - ['unknown flag', ['worktree', 'list', '--nope'], {}], - ['orca agent-context --json', ['agent-context', '--json'], {}], - ['orca status --json', ['status', '--json'], isolated], - ['orca worktree list --json', ['worktree', 'list', '--json'], isolated] - ] - - // Compare output/exit before timing or a broken arm printing nothing appears fastest. - for (const [label, argv, env] of cases) { - const before = run(eagerEntry, argv, env) - const after = run(deferredEntry, argv, env) - if ( - before.status !== after.status || - before.stdout !== after.stdout || - before.stderr !== after.stderr - ) { - throw new Error(`arms disagree for "${label}" — refusing to report a timing`) - } - if (before.stdout.length + before.stderr.length === 0) { - throw new Error(`"${label}" produced no output on either arm; it proves nothing`) - } - } - - const pad = (value, width) => String(value).padStart(width) - console.log('\nFresh process per sample, wall clock. Lower is better.') - console.log(`rounds=${ROUNDS} warmup=${WARMUP} (per-arm median, arms alternate lead)`) - console.log(`${pad('case', 26)} ${pad('eager', 10)} ${pad('deferred', 10)} ${pad('speedup', 9)}`) - - // Accumulated so V8 cannot treat the spawn loop as dead code. - let consumed = 0 - - for (const [label, argv, env] of cases) { - for (let index = 0; index < WARMUP; index += 1) { - consumed += run(eagerEntry, argv, env).stdout.length - consumed += run(deferredEntry, argv, env).stdout.length - } - const samples = { eager: [], deferred: [] } - for (let round = 0; round < ROUNDS; round += 1) { - // Alternate which arm leads so a drifting machine load cannot be - // attributed to one arm. - const order = - round % 2 === 0 - ? [ - ['eager', eagerEntry], - ['deferred', deferredEntry] - ] - : [ - ['deferred', deferredEntry], - ['eager', eagerEntry] - ] - for (const [arm, entry] of order) { - const started = performance.now() - const result = run(entry, argv, env) - samples[arm].push(performance.now() - started) - consumed += result.stdout.length - } - } - const eagerMs = median(samples.eager) - const deferredMs = median(samples.deferred) - console.log( - `${pad(label, 26)} ${pad(`${eagerMs.toFixed(1)} ms`, 10)} ${pad(`${deferredMs.toFixed(1)} ms`, 10)} ${pad(`${(eagerMs / deferredMs).toFixed(2)}x`, 9)}` - ) - } - - if (consumed === 0) { - throw new Error('no output consumed — the timing loop was optimised away') - } - console.log( - '\nThe help and error rows are the ones the change targets: they return\n' + - 'before any client construction, so they drop the whole graph. `status` and\n' + - '`worktree list` still construct a client, so they only save the eager parse\n' + - 'of the parts the local path never uses (ws/tweetnacl via websocket-transport).' - ) -} finally { - rmSync(userDataPath, { recursive: true, force: true }) - for (const label of ['eager', 'deferred']) { - rmSync(join(REPO, `.bench-out-${label}`), { recursive: true, force: true }) - } -} diff --git a/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs b/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs deleted file mode 100644 index a3d06d5f9d6..00000000000 --- a/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs +++ /dev/null @@ -1,446 +0,0 @@ -#!/usr/bin/env node -// Compare stdout/stderr/exit byte-for-byte across two real CLI emits: current tree and selected files restored from baseline (default HEAD~). -// Usage: node config/scripts/cli-runtime-client-deferral-equivalence.mjs [--baseline ] -import { execFileSync, spawnSync } from 'node:child_process' -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs' -import { join, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' - -const REPO = fileURLToPath(new URL('../../../..', import.meta.url)) - -// Restore only these baseline files; remove baseline-absent files (e.g. cli-error.ts), then restore the working tree. -const TOUCHED = [ - 'src/cli/args.ts', - 'src/cli/cli-error.ts', - 'src/cli/dispatch.ts', - 'src/cli/flags.ts', - 'src/cli/format.ts', - 'src/cli/index.ts', - 'src/cli/runtime/client.ts', - 'src/cli/selectors.ts' -] - -// Fail if real deferral call shapes change or baseline/current could become identical and pass vacuously. -function assertMarkersFresh() { - const index = readFileSync(join(REPO, 'src/cli/index.ts'), 'utf8') - const client = readFileSync(join(REPO, 'src/cli/runtime/client.ts'), 'utf8') - const checks = [ - ['src/cli/index.ts', index, 'await loadRuntimeClientClass()'], - ['src/cli/index.ts', index, "await import('./runtime-client.js')"], - ['src/cli/index.ts', index, "import type { RuntimeClient } from './runtime-client'"], - ['src/cli/runtime/client.ts', client, 'await loadSendWebSocketRequest()'], - ['src/cli/runtime/client.ts', client, "await import('./websocket-transport.js')"] - ] - for (const [file, source, marker] of checks) { - // Match calls so prose mentions cannot satisfy the guard. - if (!source.includes(marker)) { - throw new Error( - `${file} no longer contains \`${marker}\` — cli-runtime-client-deferral-equivalence.mjs is stale` - ) - } - } - const repointed = ['src/cli/args.ts', 'src/cli/flags.ts', 'src/cli/dispatch.ts'] - for (const file of repointed) { - const source = readFileSync(join(REPO, file), 'utf8') - if (!source.includes("import { RuntimeClientError } from './runtime/types'")) { - throw new Error(`${file} no longer repoints RuntimeClientError at ./runtime/types — stale`) - } - } -} - -function buildTree(label, baselineRev) { - // Build inside repo so emitted modules resolve its node_modules. - const outDir = join(REPO, `.equiv-out-${label}`) - rmSync(outDir, { recursive: true, force: true }) - const restored = [] - try { - if (baselineRev) { - for (const file of TOUCHED) { - const path = join(REPO, file) - restored.push([path, existsSync(path) ? readFileSync(path) : null]) - const old = spawnSync('git', ['show', `${baselineRev}:${file}`], { - cwd: REPO, - maxBuffer: 64 * 1024 * 1024 - }) - if (old.status === 0) { - writeFileSync(path, old.stdout) - } else { - rmSync(path, { force: true }) - } - } - } - execFileSync( - 'npx', - [ - 'tsc', - '-p', - 'config/tsconfig.cli.json', - '--outDir', - outDir, - '--composite', - 'false', - '--incremental', - 'false' - ], - { cwd: REPO, stdio: 'inherit' } - ) - } finally { - for (const [path, contents] of restored) { - if (contents === null) { - rmSync(path, { force: true }) - } else { - writeFileSync(path, contents) - } - } - } - return join(outDir, 'cli/index.js') -} - -// Every case must exit itself; bound spawnSync so reaching a blocking command fails instead of stalling forever. -const RUN_TIMEOUT_MS = 30_000 - -function run(entry, argv, env) { - const result = spawnSync(process.execPath, [entry, ...argv], { - cwd: REPO, - env: { ...process.env, ...env }, - encoding: 'buffer', - timeout: RUN_TIMEOUT_MS, - killSignal: 'SIGKILL' - }) - if (result.error) { - if (result.error.code === 'ETIMEDOUT') { - throw new Error( - `orca ${argv.join(' ')} did not exit within ${RUN_TIMEOUT_MS} ms — it reached a blocking command` - ) - } - throw result.error - } - return { - status: result.status, - stdout: result.stdout.toString('utf8'), - stderr: result.stderr.toString('utf8') - } -} - -// Require identical bytes; empty user-data dirs make runtime-dependent cases deterministically report not running. -function buildCases(isolatedUserData) { - const isolated = { ORCA_USER_DATA_PATH: isolatedUserData } - const cases = [ - // Paths that must never load the runtime client at all. - [[], {}], - [['--help'], {}], - [['help'], {}], - [['help', 'worktree'], {}], - [['help', 'browser'], {}], - [['worktree', '--help'], {}], - [['help', 'no-such-command'], {}], - [['no-such-command'], {}], - [['no-such-command'], { ORCA_PAIRING_CODE: 'garbage' }], - [['wrktree', 'list'], {}], - [['agent-context'], {}], - [['agent-context', '--json'], {}], - // Flag validation must still fire before any runtime lookup. - [['worktree', 'list', '--nonexistent-flag'], {}], - [['worktree', 'list', '--nonexistent-flag', '--json'], {}], - [['browser', 'snapshot', '--nonexistent-flag'], {}], - // resolveRemotePairing throws from the RuntimeClient CONSTRUCTOR. - [['status', '--pairing-code', 'x', '--environment', 'y'], isolated], - [['status', '--pairing-code', 'x', '--environment', 'y', '--json'], isolated], - [['status', '--pairing-code', 'not-a-pairing-code'], isolated], - [['status', '--pairing-code', 'not-a-pairing-code', '--json'], isolated], - [['status', '--pairing-code', 'orca://pair?code=zzzz'], isolated], - [['status', '--environment', 'no-such-environment'], isolated], - [['status', '--environment', 'no-such-environment', '--json'], isolated], - [['worktree', 'list', '--environment', 'no-such-environment', '--json'], isolated], - // The env-var fallback must stay live for non-suppressed commands... - [['status', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }], - [['status', '--json'], { ...isolated, ORCA_REMOTE_PAIRING: 'not-a-pairing-code' }], - [['status', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }], - // Keep suppression for local-only groups. Do not invoke agent hooks on/off: they modify real ~/.claude configuration outside ORCA_USER_DATA_PATH. - [['environment', 'list', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }], - [['environment', 'list', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }], - [['agent-context', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }], - // Runtime-unavailable reporting (RuntimeClientError formatting). - [['status'], isolated], - [['status', '--json'], isolated], - [['worktree', 'list', '--json'], isolated], - [['terminal', 'list', '--json'], isolated] - ] - // Seed fuzzing for reproducibility; all pool tokens must be safe to execute, checked against UNSAFE_TOKENS before running any case. - const tokens = [ - 'worktree', - 'list', - 'status', - 'browser', - 'snapshot', - 'terminal', - 'environment', - 'agent', - 'agent-context', - 'vm', - '--json', - '--help', - '--pairing-code', - '--environment', - '--worktree', - 'orca://pair?code=!!!', - '', - '-', - '--', - '--=', - 'a'.repeat(300), - 'näme-ünicode', - '💥', - '../..', - 'x\ty' - ] - let seed = 0x9e3779b9 - const next = () => { - seed ^= seed << 13 - seed ^= seed >>> 17 - seed ^= seed << 5 - return (seed >>> 0) / 0x100000000 - } - // Check entire pool, not just sampled cases: serve once survived review here and escaped the per-case scan by chance. - assertTokensSafe(tokens, 'fuzz token pool') - assertFuzzPoolDeclaredReadOnly(tokens) - for (let index = 0; index < 400; index += 1) { - const length = 1 + Math.floor(next() * 4) - const argv = [] - for (let part = 0; part < length; part += 1) { - argv.push(tokens[Math.floor(next() * tokens.length)]) - } - cases.push([argv, isolated]) - } - for (const [argv] of cases) { - assertTokensSafe(argv, `argv ${JSON.stringify(argv)}`) - } - return cases -} - -// Cases run real CLI with developer HOME/PATH: deny foreground commands, surviving children, config/registry writes and real UI input. -// Deny mixed read/write groups (capture/intercept/label/relation) wholesale; fuzzing cannot distinguish their subcommands. -const FOREGROUND_TOKENS = ['serve', 'open', 'claude-teams', 'exec', 'eval', 'launch', 'attach'] -const MUTATING_TOKENS = [ - // persistent config and registry state - 'on', - 'off', - 'hooks', - 'create', - 'remove', - 'rm', - 'delete', - 'add', - 'edit', - 'set', - 'set-value', - 'set-base-ref', - 'setup-clone', - 'setup-create', - 'setup-update', - 'setup-delete', - 'setup-existing-folder', - 'install', - 'uninstall', - 'reinstall', - 'update', - 'clone', - 'apply', - 'write', - 'reset', - 'clear', - 'enable', - 'disable', - 'use-default', - 'permissions', - // process and pane lifecycle - 'run', - 'run-stop', - 'start', - 'stop', - 'kill', - 'shutdown', - 'close', - 'split', - 'switch', - 'rename', - 'focus', - // orchestration writes - 'send', - 'reply', - 'dispatch', - 'task-create', - 'task-update', - 'gate-create', - 'gate-resolve', - // issue-tracker writes - 'save-issue', - 'comment', - 'label', - 'relation', - 'assignee', - 'priority', - 'estimate', - 'due-date', - // browser / computer / emulator input and navigation - 'goto', - 'back', - 'forward', - 'reload', - 'click', - 'dblclick', - 'hover', - 'fill', - 'type', - 'type-text', - 'select', - 'select-all', - 'uncheck', - 'keypress', - 'press-key', - 'inserttext', - 'hotkey', - 'paste-text', - 'perform-secondary-action', - 'drag', - 'scroll', - 'scrollintoview', - 'wheel', - 'move', - 'up', - 'down', - 'tap', - 'gesture', - 'button', - 'rotate', - 'upload', - 'download', - 'dismiss', - 'accept', - 'highlight', - 'viewport', - 'geolocation', - 'headers', - 'credentials', - 'offline', - 'media', - 'device', - 'capture', - 'intercept' -] - -const UNSAFE_TOKENS = new Map([ - ...FOREGROUND_TOKENS.map((token) => [token, 'runs in the foreground or spawns a process']), - ...MUTATING_TOKENS.map((token) => [token, 'can write outside ORCA_USER_DATA_PATH']) -]) - -// Deny lists miss new verbs (serve once escaped); require explicit read-only allowlisting for every pool token too. -const READ_ONLY_FUZZ_TOKENS = new Set([ - // command tokens: every path they can form is a list/show or a parse error - 'agent', - 'agent-context', - 'browser', - 'environment', - 'list', - 'snapshot', - 'status', - 'terminal', - 'vm', - 'worktree', - // global flags and hostile strings, which reach no handler at all - '--json', - '--help', - '--pairing-code', - '--environment', - '--worktree', - 'orca://pair?code=!!!', - '', - '-', - '--', - '--=', - 'a'.repeat(300), - 'näme-ünicode', - '💥', - '../..', - 'x\ty' -]) - -function assertTokensSafe(tokens, context) { - for (const token of tokens) { - const reason = UNSAFE_TOKENS.get(token) - if (reason) { - throw new Error(`Refusing to run ${context}: "${token}" ${reason}`) - } - } -} - -// Reject neither/both-list membership before any case runs; sampling cannot prove pool safety. -function assertFuzzPoolDeclaredReadOnly(tokens) { - for (const token of tokens) { - if (!READ_ONLY_FUZZ_TOKENS.has(token)) { - throw new Error( - `Fuzz token ${JSON.stringify(token)} is not declared in READ_ONLY_FUZZ_TOKENS — declare it read-only or drop it` - ) - } - } - for (const token of READ_ONLY_FUZZ_TOKENS) { - if (UNSAFE_TOKENS.has(token)) { - throw new Error( - `Token ${JSON.stringify(token)} is declared both read-only and unsafe — the two lists disagree` - ) - } - } -} - -const baselineIndex = process.argv.indexOf('--baseline') -const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] - -assertMarkersFresh() - -const isolatedUserData = mkdtempSync(join(REPO, '.equiv-userdata-')) -mkdirSync(join(isolatedUserData, 'empty'), { recursive: true }) - -let oldEntry -let newEntry -try { - // Build cases and check safety before expensive tsc compiles so unsafe tokens fail immediately. - const cases = buildCases(isolatedUserData) - - console.log(`Building baseline (${baselineRev}) …`) - oldEntry = buildTree('old', baselineRev) - console.log('Building working tree …') - newEntry = buildTree('new', null) - - console.log(`Comparing ${cases.length} invocations byte for byte …`) - let mismatches = 0 - for (const [argv, env] of cases) { - const before = run(oldEntry, argv, env) - const after = run(newEntry, argv, env) - if ( - before.status !== after.status || - before.stdout !== after.stdout || - before.stderr !== after.stderr - ) { - mismatches += 1 - console.error(`\nMISMATCH argv=${JSON.stringify(argv)} env=${JSON.stringify(env)}`) - console.error(` exit before=${before.status} after=${after.status}`) - if (before.stdout !== after.stdout) { - console.error(` stdout before=${JSON.stringify(before.stdout.slice(0, 400))}`) - console.error(` after =${JSON.stringify(after.stdout.slice(0, 400))}`) - } - if (before.stderr !== after.stderr) { - console.error(` stderr before=${JSON.stringify(before.stderr.slice(0, 400))}`) - console.error(` after =${JSON.stringify(after.stderr.slice(0, 400))}`) - } - } - } - if (mismatches > 0) { - throw new Error(`${mismatches} of ${cases.length} invocations differ`) - } - console.log(`\nAll ${cases.length} invocations byte-identical (stdout, stderr, exit code).`) -} finally { - rmSync(isolatedUserData, { recursive: true, force: true }) - for (const label of ['old', 'new']) { - rmSync(resolve(REPO, `.equiv-out-${label}`), { recursive: true, force: true }) - } -} diff --git a/config/scripts/performance/windows-security/windows-security-reuse-benchmark.test.mjs b/config/scripts/performance/windows-security/windows-security-reuse-benchmark.test.mjs index d2e3971fa31..0320fa8f03f 100644 --- a/config/scripts/performance/windows-security/windows-security-reuse-benchmark.test.mjs +++ b/config/scripts/performance/windows-security/windows-security-reuse-benchmark.test.mjs @@ -1,16 +1,8 @@ import { createHash } from 'node:crypto' -import { - mkdirSync, - mkdtempSync, - readFileSync, - statSync, - symlinkSync, - writeFileSync, - rmSync -} from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it } from 'vitest' import { peImage } from '../../native-build/windows/windows-pe-image-fixture.mjs' import { withInvalidSecurityCandidate } from './benchmark-windows-security-reuse.mjs' @@ -28,47 +20,17 @@ function fixture(arch = 'x64') { return { root, candidate } } -it.each(['success', 'rejection'])( - 'restores exact candidate bytes and permissions after %s', - async (outcome) => { - const f = fixture() - const original = readFileSync(f.candidate) - const before = statSync(f.candidate) - const action = async () => { - expect(readFileSync(f.candidate)).not.toEqual(original) - if (outcome === 'rejection') { - throw new Error('failed sample') - } - return 'proof' - } - const operation = withInvalidSecurityCandidate(f.candidate, f.root, digest(original), action) - if (outcome === 'rejection') { - await expect(operation).rejects.toThrow('failed sample') - } else { - expect(await operation).toBe('proof') - } - expect(readFileSync(f.candidate)).toEqual(original) - expect(statSync(f.candidate).mode).toBe(before.mode) - expect(statSync(f.candidate).mtimeMs).toBeCloseTo(before.mtimeMs, 0) - } -) - -it('refuses a changed candidate, symlink and preexisting backup before invalidating', async () => { +it('restores exact candidate bytes and permissions after a rejected sample', async () => { const f = fixture() - const bytes = readFileSync(f.candidate) - const action = vi.fn() - await expect( - withInvalidSecurityCandidate(f.candidate, f.root, 'wrong hash', action) - ).rejects.toThrow() - writeFileSync(join(f.root, 'prepared-security-backup.node'), 'occupied') - await expect( - withInvalidSecurityCandidate(f.candidate, f.root, digest(bytes), action) - ).rejects.toThrow() - const link = join(f.root, 'link.node') - symlinkSync(dirname(f.candidate), link, 'junction') - await expect(withInvalidSecurityCandidate(link, f.root, digest(bytes), action)).rejects.toThrow( - 'regular file' - ) - expect(readFileSync(f.candidate)).toEqual(bytes) - expect(action).not.toHaveBeenCalled() + const original = readFileSync(f.candidate) + const before = statSync(f.candidate) + const action = async () => { + expect(readFileSync(f.candidate)).not.toEqual(original) + throw new Error('failed sample') + } + const operation = withInvalidSecurityCandidate(f.candidate, f.root, digest(original), action) + await expect(operation).rejects.toThrow('failed sample') + expect(readFileSync(f.candidate)).toEqual(original) + expect(statSync(f.candidate).mode).toBe(before.mode) + expect(statSync(f.candidate).mtimeMs).toBeCloseTo(before.mtimeMs, 0) }) diff --git a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.mjs b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.mjs index bbdb13719aa..45164a171a7 100644 --- a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.mjs +++ b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.mjs @@ -17,11 +17,12 @@ const { validatePluginFile, pluginManifestWarnings } = loadPluginSchemaModule( const { parsePluginManifest } = loadPluginSchemaModule('manifest/plugin-manifest.ts') // Why the CLI's main entry: `orca plugin validate` and `release-entry` run these same checks, and // the printed contentHash must be what Orca computes at install. -const { - pluginCatalogReleaseForHead, - validateDeclaredPluginArtifacts, - validatePluginInstallContent -} = loadPluginSchemaModule('../../main/plugins/plugin-authoring-checks.ts') +const { pluginCatalogReleaseForHead } = loadPluginSchemaModule( + '../../main/plugins/plugin-catalog-release-entry.ts' +) +const { validateDeclaredPluginArtifacts, validatePluginInstallContent } = loadPluginSchemaModule( + '../../main/plugins/plugin-artifact-validation.ts' +) // Why shared: `orca plugin validate` runs these same strict artifact checks. const { strictPluginArtifactErrors, strictPluginArtifactWarnings } = loadPluginSchemaModule( 'authoring/plugin-strict-artifact-checks.ts' diff --git a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs b/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs deleted file mode 100644 index f9ddb0587af..00000000000 --- a/config/scripts/plugin-authoring/content-validation/validate-plugin-files.test.mjs +++ /dev/null @@ -1,39 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import path from 'node:path' -import process from 'node:process' -import { runProcess } from '@orca/process-host' -import { afterEach, describe, expect, it } from 'vitest' -import { createPluginFromTemplate } from '../../../../src/cli/plugin-authoring/plugin-create' - -const SCRIPT = path.join(import.meta.dirname, './validate-plugin-files.mjs') -const roots = [] - -async function tempRoot() { - const root = await mkdtemp(path.join(tmpdir(), 'orca-validate-plugin-files-')) - roots.push(root) - return root -} - -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -function validate(...targets) { - return runProcess({ - program: process.execPath, - args: [SCRIPT, ...targets], - timeoutMs: 60_000 - }) -} - -describe('validate-plugin-files', () => { - it('fails with exit 1 when a file the manifest names is missing', async () => { - const dir = path.join(await tempRoot(), 'panel') - await createPluginFromTemplate({ dir, template: 'panel', publisher: 'acme' }) - await rm(path.join(dir, 'panel', 'index.html')) - const result = await validate(dir) - expect(result.code).toBe(1) - expect(result.stderr).toContain('panel/index.html') - }, 60_000) -}) diff --git a/config/scripts/plugin-authoring/rpc-catalog/generate-rpc-params-catalog.mjs b/config/scripts/plugin-authoring/rpc-catalog/generate-rpc-params-catalog.mjs index a1b05beffd5..b5f4fbb5c8b 100644 --- a/config/scripts/plugin-authoring/rpc-catalog/generate-rpc-params-catalog.mjs +++ b/config/scripts/plugin-authoring/rpc-catalog/generate-rpc-params-catalog.mjs @@ -32,16 +32,25 @@ function scratchDir(prefix) { const posix = (value) => value.split(path.sep).join('/') const repoPath = (absolute) => posix(path.relative(REPO_ROOT, absolute)) +function isProductionModule(file) { + const value = posix(file) + return ( + !/(?:^|\/)(?:test-support|testing|__tests__|fixtures)(?:\/|$)/.test(value) && + !/\.(?:test|spec|test-fixture|fixture)\.[cm]?tsx?$/.test(value) && + !/\.d\.[cm]?ts$/.test(value) + ) +} + function indexableModules() { // Exclude tests or catalog’s CJS bundle requires Vitest and throws. const modules = new Set( - globSync('*.ts', { cwd: CONTRACT_DIR }) - .filter((name) => !name.endsWith('.test.ts')) + globSync('**/*.ts', { cwd: CONTRACT_DIR }) + .filter(isProductionModule) .map((name) => path.join(CONTRACT_DIR, name)) ) modules.delete(OUTPUT_PATH) for (const file of globSync('**/*.ts', { cwd: RPC_DIR })) { - if (file.endsWith('.test.ts')) { + if (!isProductionModule(file)) { continue } const source = readFileSync(path.join(RPC_DIR, file), 'utf8') @@ -50,6 +59,7 @@ function indexableModules() { // Exclude generator output even when params import its types; stale catalog bundling would break regeneration precisely when needed. if ( resolved !== OUTPUT_PATH && + isProductionModule(resolved) && resolved.startsWith(`${SHARED_DIR}${path.sep}`) && existsSync(resolved) ) { diff --git a/config/scripts/preflight/changed-checks/check-changed-code-quality.mjs b/config/scripts/preflight/changed-checks/check-changed-code-quality.mjs index 8cd2d6cf97d..2052fc083a1 100644 --- a/config/scripts/preflight/changed-checks/check-changed-code-quality.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-code-quality.mjs @@ -76,8 +76,8 @@ const SUPPRESSED_REACT_DOCTOR_DIAGNOSTICS = new Map([ [ 'react-doctor(no-adjust-state-on-prop-change)', new Set([ - 'src/renderer/src/components/task-page/github/use-task-page-github-issue-draft.ts', - 'src/renderer/src/components/task-page/jira/use-task-page-jira-creation-state.ts' + 'src/renderer/src/components/task-page/github/issue-creation/use-task-page-github-issue-draft.ts', + 'src/renderer/src/components/task-page/jira/creation/use-task-page-jira-creation-state.ts' ]) ], [ diff --git a/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs b/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs index f6b7806fd7f..a431458a26d 100644 --- a/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-code-quality.test.mjs @@ -3,11 +3,7 @@ import { tmpdir } from 'node:os' import path from 'node:path' import { describe, expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' -import { - collectBaseLineBlocks, - collectAddedLineRanges, - isUnloadedPluginDirectiveUnusedWarning -} from './check-changed-code-quality.mjs' +import { collectBaseLineBlocks, collectAddedLineRanges } from './check-changed-code-quality.mjs' describe('changed-code quality line matching', () => { it.each(['edit', 'rename'])('treats bracketed filenames literally after %s', (change) => { @@ -104,34 +100,3 @@ describe('moved-code exemption', () => { } }) }) - -describe('secondary-scan directive exemption', () => { - it('exempts type-aware and import-plugin directives from the root scan alone', () => { - const root = mkdtempSync(path.join(tmpdir(), 'changed-code-quality-type-aware-')) - try { - writeFileSync( - path.join(root, 'a.ts'), - [ - '// oxlint-disable-next-line typescript/return-await -- catch must not cover this', - '// oxlint-disable-next-line typescript/return-await-extra -- unknown rule', - '// oxlint-disable-next-line no-console -- root rule', - '// oxlint-disable-next-line import/no-cycle -- singleton hub' - ].join('\n') - ) - const unused = (line) => ({ - message: 'Unused oxlint-disable directive (no problems were reported).', - filename: 'a.ts', - labels: [{ span: { line } }] - }) - const exempt = (line, scan) => - isUnloadedPluginDirectiveUnusedWarning(unused(line), root, scan) - expect(exempt(1, 'code quality')).toBe(true) - expect(exempt(1, 'type-aware code quality')).toBe(false) - expect(exempt(2, 'code quality')).toBe(false) - expect(exempt(3, 'code quality')).toBe(false) - expect(exempt(4, 'code quality')).toBe(true) - } finally { - rmSync(root, { recursive: true, force: true }) - } - }) -}) diff --git a/config/scripts/release/javascript-artifacts/release-javascript-artifact.test.mjs b/config/scripts/release/javascript-artifacts/release-javascript-artifact.test.mjs index 107fd7a1a4f..1f3dec92aa7 100644 --- a/config/scripts/release/javascript-artifacts/release-javascript-artifact.test.mjs +++ b/config/scripts/release/javascript-artifacts/release-javascript-artifact.test.mjs @@ -110,18 +110,6 @@ describe('release JavaScript configuration', () => { }) describe('release JavaScript transfer', () => { - it('restores development bundles and rejects them for an official build', () => { - const options = fixture() - const devConfiguration = { ...configuration, identity: 'dev', telemetryKeySha256: null } - packReleaseJavascript({ ...options, configuration: devConfiguration }) - expect(() => restoreReleaseJavascript(options)).toThrow( - 'JavaScript build configuration differs' - ) - expect( - restoreReleaseJavascript({ ...options, configuration: devConfiguration }).configuration - ).toEqual(devConfiguration) - }) - it('rejects a damaged archive before replacing the current build', () => { const options = fixture() packReleaseJavascript(options) diff --git a/config/scripts/release/publication/mirror-release-to-r2.sh b/config/scripts/release/publication/mirror-release-to-r2.sh index f32992eaafd..38ef2ea83f9 100755 --- a/config/scripts/release/publication/mirror-release-to-r2.sh +++ b/config/scripts/release/publication/mirror-release-to-r2.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Needs bash 4+ (mapfile); on macOS use Homebrew bash. # Mirror Orca release assets from GitHub Releases to the public R2 bucket -# served at https://downloads.onorca.dev. onorca.dev's "Download started" page +# served at https://downloads.orca.dev. orca.dev's "Download started" page # offers these as an opt-in "mirror link" for when GitHub returns 5xx. # Run by .github/workflows/release-mirror-r2.yml after each published release. # @@ -29,7 +29,7 @@ set -euo pipefail REPO="${REPO:-stablyai/orca}" BUCKET="${BUCKET:-orca-downloads}" -PUBLIC_BASE="${PUBLIC_BASE:-https://downloads.onorca.dev}" +PUBLIC_BASE="${PUBLIC_BASE:-https://downloads.orca.dev}" WEBSITE_ASSETS=(orca-macos-arm64.dmg orca-macos-x64.dmg orca-windows-setup.exe orca-linux.AppImage) CLOUDFLARE_ACCOUNT_ID="${CLOUDFLARE_ACCOUNT_ID:-57e6ddd3bb755dbf8e8dc7ff557e9014}" R2_ENDPOINT="https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com" diff --git a/config/scripts/release/workflow-contracts/qualified-orcad-template.test.mjs b/config/scripts/release/workflow-contracts/qualified-orcad-template.test.mjs index d433ee9d563..9f773650d92 100644 --- a/config/scripts/release/workflow-contracts/qualified-orcad-template.test.mjs +++ b/config/scripts/release/workflow-contracts/qualified-orcad-template.test.mjs @@ -8,41 +8,28 @@ import { writeOrcadTemplateTestFixture } from '../../orcad-distribution/template const workflow = parse(readFileSync('.github/workflows/qualified-orcad-template.yml', 'utf8')) -it.each(['valid', 'corrupt', 'dark'])( - 'validates restored bytes and requalifies an unsafe template: %s', - async (kind) => { - const root = mkdtempSync(join(tmpdir(), 'qualified-template-restore-')) - const output = join(root, 'output') - try { - symlinkSync( - resolve('config'), - join(root, 'config'), - process.platform === 'win32' ? 'junction' : 'dir' - ) - const template = await writeOrcadTemplateTestFixture(join(root, 'out')) - if (kind === 'corrupt') { - writeFileSync(join(template, 'out/mobile-web/index.html'), 'mutated') - } else if (kind === 'dark') { - writeFileSync(join(template, 'ORCA_LAYOUT_OWNER_MAIN'), 'dark build') - } - const validate = workflow.jobs.cache.steps.find((step) => step.id === 'validate') - const result = runProcessSync({ - program: 'bash', - args: ['-e', '-c', validate.run], - cwd: root, - env: { ...process.env, GITHUB_OUTPUT: output } - }) - expect(result.code, result.stderr).toBe(0) - if (kind === 'valid') { - expect(readFileSync(output, 'utf8').trim()).toBe('valid=true') - expect(existsSync(template)).toBe(true) - } else { - expect(existsSync(output)).toBe(false) - expect(existsSync(template)).toBe(false) - expect(result.stdout).toContain('qualifying a fresh build') - } - } finally { - rmSync(root, { recursive: true, force: true }) - } +it('removes corrupted cached bytes without marking them reusable', async () => { + const root = mkdtempSync(join(tmpdir(), 'qualified-template-restore-')) + const output = join(root, 'output') + try { + symlinkSync( + resolve('config'), + join(root, 'config'), + process.platform === 'win32' ? 'junction' : 'dir' + ) + const template = await writeOrcadTemplateTestFixture(join(root, 'out')) + writeFileSync(join(template, 'out/mobile-web/index.html'), 'mutated') + const validate = workflow.jobs.cache.steps.find((step) => step.id === 'validate') + const result = runProcessSync({ + program: 'bash', + args: ['-e', '-c', validate.run], + cwd: root, + env: { ...process.env, GITHUB_OUTPUT: output } + }) + expect(result.code, result.stderr).toBe(0) + expect(existsSync(output)).toBe(false) + expect(existsSync(template)).toBe(false) + } finally { + rmSync(root, { recursive: true, force: true }) } -) +}) diff --git a/config/scripts/release/workflow-contracts/release-mac-build-workflow-dispatch.test.mjs b/config/scripts/release/workflow-contracts/release-mac-build-workflow-dispatch.test.mjs index 417074d1e11..5ce36b1091c 100644 --- a/config/scripts/release/workflow-contracts/release-mac-build-workflow-dispatch.test.mjs +++ b/config/scripts/release/workflow-contracts/release-mac-build-workflow-dispatch.test.mjs @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { executeReleaseMacBuildMode } from '../operations/run-release-mac-build-workflow.mjs' const splitEnvironment = { @@ -28,16 +28,8 @@ const splitRun = { } describe('release mac build split dispatch and verification', () => { - it.each([ - ['id', 124], - ['head_sha', 'b'.repeat(40)], - ['head_branch', 'other'], - ['run_attempt', 2], - ['event', 'pull_request'], - ['path', '.github/workflows/other.yml'], - ['display_title', 'Mac release build v1.2.4 (777)'] - ])('rejects a changed %s before inspecting success', async (field, value) => { - const { fetch } = createGitHubFetch([jsonResponse(200, { ...splitRun, [field]: value })]) + it('rejects a completed run from another commit', async () => { + const fetch = async () => jsonResponse(200, { ...splitRun, head_sha: 'b'.repeat(40) }) await expect( executeReleaseMacBuildMode('wait', splitEnvironment, { fetch, @@ -47,30 +39,6 @@ describe('release mac build split dispatch and verification', () => { }) }) -function createGitHubFetch(responses) { - const requests = [] - const fetch = vi.fn(async (rawUrl, init) => { - const url = new URL(rawUrl) - const response = responses.shift() - - if (response == null) { - throw new Error(`Unexpected request: ${init.method} ${rawUrl}`) - } - - requests.push({ - body: init.body == null ? undefined : JSON.parse(init.body), - method: init.method, - headers: init.headers, - path: url.pathname, - query: url.searchParams - }) - - return response - }) - - return { fetch, requests } -} - function jsonResponse(status, body) { return { ok: status >= 200 && status < 300, diff --git a/config/scripts/runtime-verification/daemon-lifecycle/run-headless-linux-pairing-docker.mjs b/config/scripts/runtime-verification/daemon-lifecycle/run-headless-linux-pairing-docker.mjs index 799b8d73ab1..b0d79937213 100644 --- a/config/scripts/runtime-verification/daemon-lifecycle/run-headless-linux-pairing-docker.mjs +++ b/config/scripts/runtime-verification/daemon-lifecycle/run-headless-linux-pairing-docker.mjs @@ -4,10 +4,8 @@ import { existsSync } from 'node:fs' import { resolve } from 'node:path' const STARTUP_TIMEOUT_MS = 20_000 -const APPIMAGE_EXTRACTION_TIMEOUT_MS = 60_000 const commandArgs = process.argv.slice(2) const appImageArg = valueAfter('--appimage') -const pairingOnly = commandArgs.includes('--pairing-only') if (!appImageArg) { fail('Usage: run-headless-linux-pairing-docker.mjs --appimage /path/to/orca.AppImage') } @@ -32,28 +30,17 @@ const images = [ tag: 'orca-headless-pairing:debian-13', base: 'debian@sha256:020c0d20b9880058cbe785a9db107156c3c75c2ac944a6aa7ab59f2add76a7bd', libasound: 'libasound2t64' - }, - { - name: 'ubuntu-22.04-baseline', - tag: 'orca-headless-pairing:ubuntu-22.04', - base: 'ubuntu@sha256:0e0a0fc6d18feda9db1590da249ac93e8d5abfea8f4c3c0c849ce512b5ef8982', - libasound: 'libasound2' } ] try { docker(['volume', 'create', artifactVolume]) docker(['network', 'create', network]) - for (const image of pairingOnly ? images.slice(0, 2) : images) { + for (const image of images) { buildImage(image) } extractAppImage(images[0].tag) - if (!pairingOnly) { - await validateStartupMatrix() - await validateUnavailableContracts() - } await validateAuthenticatedPairing() - await validateUnreachableOffer() console.log('Headless Linux pairing Docker validation passed.') } finally { for (const container of containers) { @@ -111,71 +98,6 @@ function extractAppImage(image) { ]) } -async function validateStartupMatrix() { - const required = images.slice(0, 2) - for (const image of required) { - for (const launch of ['direct', 'xvfb', 'dbus-xvfb', 'journal']) { - for (const mode of ['human', 'json']) { - const result = await startAndWait({ image, launch, mode, address: 'pair-host.test' }) - validateReady(result.stdout, mode, 'pair-host.test', { - allowStdoutNoise: launch !== 'direct' - }) - stopContainer(result.name) - console.log(`PASS ${image.name} ${launch} ${mode}`) - } - } - } - const baseline = await startAndWait({ - image: images[2], - launch: 'xvfb', - mode: 'json', - address: '127.0.0.1' - }) - validateReady(baseline.stdout, 'json', '127.0.0.1', { allowStdoutNoise: true }) - stopContainer(baseline.name) - console.log(`PASS ${images[2].name} xvfb json`) - - const publicEntry = await startAndWait({ - image: images[0], - launch: 'direct', - mode: 'json', - address: '127.0.0.1', - appPath: '/artifacts/orca.AppImage', - startupTimeoutMs: APPIMAGE_EXTRACTION_TIMEOUT_MS - }) - validateReady(publicEntry.stdout, 'json', '127.0.0.1', { allowStdoutNoise: true }) - stopContainer(publicEntry.name) - console.log('PASS AppImage --appimage-extract-and-run --no-sandbox serve') -} - -async function validateUnavailableContracts() { - const invalid = await startAndWait({ - image: images[0], - launch: 'direct', - mode: 'json', - address: '0.0.0.0' - }) - const invalidPayload = readyJson(invalid.stdout) - assert(invalidPayload.pairing?.available === false, 'wildcard pairing must be unavailable') - assert( - invalidPayload.pairing.reason === 'invalid_advertised_endpoint', - 'wildcard pairing must expose invalid_advertised_endpoint' - ) - stopContainer(invalid.name) - - const disabled = await startAndWait({ - image: images[1], - launch: 'journal', - mode: 'json', - address: '127.0.0.1', - noPairing: true - }) - const disabledPayload = readyJson(disabled.stdout) - assert(disabledPayload.pairing?.reason === 'disabled_by_operator', 'disabled reason is missing') - stopContainer(disabled.name) - console.log('PASS explicit unavailable pairing contracts') -} - async function validateAuthenticatedPairing() { const server = await startAndWait({ image: images[0], @@ -220,22 +142,6 @@ async function validateAuthenticatedPairing() { console.log('PASS paired E2EE updater inventory and manual-service fallback') } -async function validateUnreachableOffer() { - const server = await startAndWait({ - image: images[0], - launch: 'direct', - mode: 'json', - address: 'orca-pairing-server:6769', - port: '6768', - networkAlias: 'orca-pairing-server' - }) - const payload = readyJson(server.stdout) - const client = runPairingClient(payload.pairing.url) - assert(client.status !== 0, 'a deliberately mismatched advertised port unexpectedly connected') - stopContainer(server.name) - console.log('PASS unreachable advertised endpoint fails the real client probe') -} - async function startAndWait({ image, launch, @@ -318,39 +224,6 @@ function hasCompleteReadyContract(stdout) { return readyJsonObjects(stdout).length > 0 } -function validateReady(logs, mode, expectedHost, options = {}) { - if (mode === 'human') { - assert( - (logs.match(/^Orca server ready$/gm) ?? []).length === 1, - 'human ready marker is not exact-once' - ) - assert(logs.includes('Bound endpoint: ws://0.0.0.0:'), 'human bound endpoint is missing') - assert( - logs.includes(`Advertised endpoint: ws://${expectedHost}:`), - 'human advertised endpoint is missing' - ) - assert(logs.includes('Pairing URL: orca://pair?code='), 'human pairing URL is missing') - return - } - if (!options.allowStdoutNoise) { - const stdoutLines = logs.split(/\r?\n/).filter(Boolean) - assert( - stdoutLines.length === 1, - `JSON stdout must contain exactly one line, found ${stdoutLines.length}:\n${logs}` - ) - } - const payload = readyJson(logs) - assert(payload.schemaVersion === 1, 'ready JSON schemaVersion is missing') - assert(payload.endpoint === payload.boundEndpoint, 'legacy JSON endpoint alias is inconsistent') - assert(payload.boundEndpoint?.startsWith('ws://0.0.0.0:'), 'JSON bound endpoint is invalid') - assert(payload.advertisedEndpoint?.includes(expectedHost), 'JSON advertised endpoint is invalid') - assert(payload.pairing?.available === true, 'JSON pairing offer is unavailable') - assert( - new URL(payload.boundEndpoint).port === new URL(payload.advertisedEndpoint).port, - 'an advertised host without a port must use the actual bound port' - ) -} - function readyJson(logs) { const matches = readyJsonObjects(logs) assert(matches.length === 1, `expected one ready JSON object, found ${matches.length}`) diff --git a/config/scripts/runtime-verification/desktop-transport/run-linux-cli-launch-contract-docker.mjs b/config/scripts/runtime-verification/desktop-transport/run-linux-cli-launch-contract-docker.mjs index d0c3c54c4d5..d577caf6c7c 100755 --- a/config/scripts/runtime-verification/desktop-transport/run-linux-cli-launch-contract-docker.mjs +++ b/config/scripts/runtime-verification/desktop-transport/run-linux-cli-launch-contract-docker.mjs @@ -24,18 +24,6 @@ const CLEANUP_TIMEOUT_MS = 30_000 // Exact statuses reject silent no-op launches as well as crashes. const CASES = [ - { - name: 'nofuse-userns-bundled-help', - expectStatus: 0, - expectOutput: 'Usage: orca ', - why: 'The bundled launcher must run with no FUSE, no display, and userns restricted (#11609, #12530).' - }, - { - name: 'nofuse-userns-bundled-version', - expectStatus: 0, - expectOutput: /^\d+\.\d+\.\d+/m, - why: 'A deployment must be able to read the installed version without a display (#13719).' - }, { name: 'nofuse-userns-bundled-status', // No runtime is running; the CLI must report that itself. @@ -43,32 +31,12 @@ const CASES = [ expectOutput: 'appRunning', why: 'A command that needs the runtime must report its absence, not abort.' }, - { - name: 'nofuse-userns-bundled-skills', - expectStatus: 0, - // Why: the rendered help header, not a bare 'skills' — the case name contains that word. - expectOutput: 'Usage: orca skills', - why: 'skills is a pure-text command that must never need Chromium (#14229).' - }, - { - name: 'nofuse-userns-bundled-worktree', - expectStatus: 1, - expectOutput: "Orca is not running. Run 'orca open' first.", - why: 'A runtime-dependent command must report the missing runtime, not abort.' - }, { name: 'nofuse-nosandbox-direct-binary-skills', expectStatus: 0, expectOutput: 'Usage: orca skills', why: 'A direct binary launch that reaches JavaScript must run the command, not boot a GUI (#14229).' }, - { - name: 'nofuse-nosandbox-direct-binary-gui', - // A missing display is an expected diagnosis, not a crash. - expectStatus: 1, - expectOutput: 'needs a usable display server', - why: 'A desktop launch with no display must diagnose it instead of dying in uv_close (#13719).' - }, { name: 'stale-display-nosandbox-direct-binary-gui', expectStatus: 1, diff --git a/config/scripts/runtime-verification/headless-detector/headless-detector-compiler-cache.test.mjs b/config/scripts/runtime-verification/headless-detector/headless-detector-compiler-cache.test.mjs deleted file mode 100644 index 82b1144a8d8..00000000000 --- a/config/scripts/runtime-verification/headless-detector/headless-detector-compiler-cache.test.mjs +++ /dev/null @@ -1,73 +0,0 @@ -import { - appendFileSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - symlinkSync, - writeFileSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import { - activateCompilerCache, - compilerCacheIdentity, - packCompilerCache -} from './headless-detector-compiler-cache.mjs' - -const temporary = [] -afterEach(() => { - for (const dir of temporary.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) -function fixture() { - const directory = mkdtempSync(join(tmpdir(), 'headless-compiler-cache-')) - temporary.push(directory) - const root = join(directory, 'checkout') - mkdirSync(root) - writeFileSync(join(root, 'package.json'), '{"type":"module"}') - const identity = compilerCacheIdentity({ policyHash: 'policy', cacheRoot: directory }) - packCompilerCache({ identity }) - return { root, identity } -} - -it.each(['modified', 'missing', 'extra', 'symlink', 'malformed'])( - 'falls back on %s cache contents before loading code', - async (kind) => { - const { root, identity } = fixture() - const compiler = join(identity.path, 'node_modules', 'esbuild', 'lib', 'main.js') - if (kind === 'modified') { - appendFileSync(compiler, '\nthrow Error("must not load")') - } - if (kind === 'missing') { - rmSync(compiler) - } - if (kind === 'extra') { - writeFileSync(join(identity.path, 'unexpected'), 'extra') - } - if (kind === 'symlink') { - rmSync(compiler) - symlinkSync(join(root, 'package.json'), compiler) - } - if (kind === 'malformed') { - writeFileSync(join(identity.path, 'manifest.json'), '{') - } - expect((await activateCompilerCache({ root, identity })).available).toBe(false) - expect(existsSync(join(root, 'node_modules'))).toBe(false) - } -) - -it('leaves existing dependencies alone and falls back on an absent archive', async () => { - const { root, identity } = fixture() - mkdirSync(join(root, 'node_modules')) - writeFileSync(join(root, 'node_modules', 'retained'), 'retained') - expect((await activateCompilerCache({ root, identity })).available).toBe(false) - expect(readFileSync(join(root, 'node_modules', 'retained'), 'utf8')).toBe('retained') - rmSync(join(root, 'node_modules'), { recursive: true }) - rmSync(identity.path, { recursive: true }) - expect((await activateCompilerCache({ root, identity })).available).toBe(false) - expect(existsSync(join(root, 'node_modules'))).toBe(false) -}) diff --git a/config/scripts/runtime-verification/skills-cli/verify-skills-cli-runtime.test.mjs b/config/scripts/runtime-verification/skills-cli/verify-skills-cli-runtime.test.mjs index 60980d25ff1..a34d97f1c42 100644 --- a/config/scripts/runtime-verification/skills-cli/verify-skills-cli-runtime.test.mjs +++ b/config/scripts/runtime-verification/skills-cli/verify-skills-cli-runtime.test.mjs @@ -31,29 +31,6 @@ describe('skills CLI runtime closure', () => { } }) - it('rejects bare imports resolved outside the artifact', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-skills-cli-closure-')) - try { - const artifactRoot = join(root, 'artifact') - const outDir = join(artifactRoot, 'out') - const externalPackageDir = join(root, 'node_modules', 'external-package') - await mkdir(externalPackageDir, { recursive: true }) - await writeSkillsCliFixture(outDir, "require('external-package')\n") - await writeFile( - join(externalPackageDir, 'package.json'), - JSON.stringify({ main: 'index.js' }), - 'utf8' - ) - await writeFile(join(externalPackageDir, 'index.js'), '', 'utf8') - - expect(() => collectRuntimeClosure(outDir, artifactRoot)).toThrow( - /external-package.*resolved outside/s - ) - } finally { - await rm(root, { recursive: true, force: true }) - } - }) - it("resolves a linked package's imports from its store slot, as Node does", async () => { const root = await mkdtemp(join(tmpdir(), 'orca-skills-cli-closure-')) try { diff --git a/config/scripts/skills/bundle-generation/generate-bundled-skill-guides.mjs b/config/scripts/skills/bundle-generation/generate-bundled-skill-guides.mjs index 40056f21e91..7cb75b19306 100644 --- a/config/scripts/skills/bundle-generation/generate-bundled-skill-guides.mjs +++ b/config/scripts/skills/bundle-generation/generate-bundled-skill-guides.mjs @@ -179,7 +179,7 @@ function serializeEmbeddedModule(guides) { }) .join(',\n') - return `// Generated by config/scripts/generate-bundled-skill-guides.mjs. Do not edit.\n\nexport type BundledSkillGuideReference = {\n readonly name: string\n readonly markdown: string\n}\n\nexport type BundledSkillGuide = {\n readonly name: string\n readonly description: string\n readonly markdown: string\n readonly aliases: readonly string[]\n readonly references: readonly BundledSkillGuideReference[]\n}\n\n${markdownConstants}\n\n// oxfmt-ignore\nexport const BUNDLED_SKILL_GUIDES = [\n${guideEntries}\n] as const satisfies readonly BundledSkillGuide[]\n` + return `// Generated by config/scripts/skills/bundle-generation/generate-bundled-skill-guides.mjs. Do not edit.\n\nexport type BundledSkillGuideReference = {\n readonly name: string\n readonly markdown: string\n}\n\nexport type BundledSkillGuide = {\n readonly name: string\n readonly description: string\n readonly markdown: string\n readonly aliases: readonly string[]\n readonly references: readonly BundledSkillGuideReference[]\n}\n\n${markdownConstants}\n\n// oxfmt-ignore\nexport const BUNDLED_SKILL_GUIDES = [\n${guideEntries}\n] as const satisfies readonly BundledSkillGuide[]\n` } async function readGuideReferences(repoRoot, guideName) { @@ -317,7 +317,7 @@ async function buildArtifacts(repoRoot = REPO_ROOT) { return [ { - path: path.join(repoRoot, 'src', 'cli', 'bundled-skill-guides.ts'), + path: path.join(repoRoot, 'src', 'cli', 'skills', 'bundled-skill-guides.ts'), content: serializeEmbeddedModule(guides) }, ...projections diff --git a/config/scripts/skills/bundle-generation/generate-plugin-authoring-skill-references.mjs b/config/scripts/skills/bundle-generation/generate-plugin-authoring-skill-references.mjs index 3c656d5530b..8f5a05f3495 100644 --- a/config/scripts/skills/bundle-generation/generate-plugin-authoring-skill-references.mjs +++ b/config/scripts/skills/bundle-generation/generate-plugin-authoring-skill-references.mjs @@ -208,12 +208,15 @@ function hookLines({ hooks, hookContribution, typeText }) { function renderHostApi(sources, { frame, worker }) { const { hostApi, hostDoc, capabilities } = sources - const names = hostApi.PLUGIN_HOST_METHOD_NAMES + const names = hostApi.PLUGIN_STABLE_HOST_METHOD_NAMES const methodsFor = (surface) => hostApi.pluginHostMethodsFor(surface).map(code).join(', ') const methods = names.map((name) => { const spec = hostApi.PLUGIN_HOST_API[name] const facts = [ spec.capability ? `capability ${code(spec.capability)}` : 'no capability', + ...Object.entries(spec.paramCapabilities ?? {}).map( + ([param, kind]) => `${code(param)} also needs ${code(kind)}` + ), spec.surfaces.join(', '), `since ${hostVersion(sources, spec.since)}`, ...(spec.deprecatedSince === undefined diff --git a/config/scripts/skills/bundle-generation/generate-skill-bundle-manifest.test.mjs b/config/scripts/skills/bundle-generation/generate-skill-bundle-manifest.test.mjs index e3c242f0f1a..dd8b8596d0a 100644 --- a/config/scripts/skills/bundle-generation/generate-skill-bundle-manifest.test.mjs +++ b/config/scripts/skills/bundle-generation/generate-skill-bundle-manifest.test.mjs @@ -1,7 +1,6 @@ import { createHash } from 'node:crypto' import { execFileSync } from 'node:child_process' import { - chmod, copyFile, mkdir, mkdtemp, @@ -114,29 +113,6 @@ describe('skill bundle manifest generator', () => { expect(digests).toHaveLength(2) }) - it.runIf(process.platform !== 'win32')( - 'rejects executable files in shipped skill packages', - async () => { - const packageRoot = await createPackage() - await writeFile(path.join(packageRoot, 'SKILL.md'), 'skill\n') - await writeFile(path.join(packageRoot, 'run.sh'), '#!/bin/sh\necho ok\n') - await chmod(path.join(packageRoot, 'run.sh'), 0o755) - - await expect(collectPackageFiles(packageRoot)).rejects.toThrow( - 'Executable file is not allowed in a shipped skill: run.sh' - ) - } - ) - - it.runIf(process.platform === 'linux')('rejects case-colliding paths', async () => { - const packageRoot = await createPackage() - await writeFile(path.join(packageRoot, 'SKILL.md'), 'skill') - await writeFile(path.join(packageRoot, 'Readme.md'), 'one') - await writeFile(path.join(packageRoot, 'README.md'), 'two') - - await expect(collectPackageFiles(packageRoot)).rejects.toThrow('Case-colliding skill paths') - }) - it('keeps guarding a directory or link that only wears an OS metadata name', async () => { const packageRoot = await createPackage() await writeFile(path.join(packageRoot, 'SKILL.md'), 'demo skill\n') diff --git a/config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs b/config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs index 5576704bba0..ce751af1651 100644 --- a/config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs +++ b/config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs @@ -20,40 +20,6 @@ function lintSources(sources) { } const sources = { - // The subscription and post-render memo from the typing-lag regression. - historicalHotMap: ` - import { useAppStore } from '@/store' -export function useStructuredAgentSessionHostCapabilityState( - target: RuntimeClientTarget | null, - capability: RuntimeCapability -): StructuredAgentSessionHostCapabilityState { - const environmentId = target?.kind === 'environment' ? target.environmentId : null - const statuses = useAppStore((state) => state.runtimeStatusByEnvironmentId) - const remote = useMemo((): StructuredAgentSessionHostCapabilityState => { - if (environmentId === null) { - return 'unknown' - } - const entry = statuses.get(environmentId) - const status = isRuntimeHostContactRevoked(entry) ? null : lastVerifiedRuntimeStatus(entry) - return status - ? status.capabilities?.includes(capability) - ? 'supported' - : 'unsupported' - : 'unknown' - }, [statuses, environmentId, capability]) - const local = useSyncExternalStore( - subscribeLocalRuntimeCapabilityObservation, - () => localCapabilityState(capability), - () => 'unknown' as const - ) - useEffect(() => { - if (target?.kind === 'local') { - void ensureLocalRuntimeCapabilities() - } - }, [target?.kind]) - return !target ? 'unknown' : environmentId === null ? local : remote -} - `, hotMapReturns: ` import { useAppStore as useStore } from '@/store' import { useRuntimeStore } from '@/store/runtime' @@ -82,59 +48,6 @@ export function useStructuredAgentSessionHostCapabilityState( function ShadowedHook(useAppStore) { return useAppStore(s => s.runtimeStatusByEnvironmentId) } const ShadowedParameter = () => useAppStore(s => { { const s = other; return s.runtimeStatusByEnvironmentId } }) `, - fixedHostCapability: ` - import { useAppStore } from '@/store' -export function useStructuredAgentSessionOwnPermissionState( - target: RuntimeClientTarget | null -): StructuredAgentSessionHostCapabilityState { - const capability = AGENT_SESSION_PERMISSION_OWN_RUNTIME_CAPABILITY - const environmentId = target?.kind === 'environment' ? target.environmentId : null - // Select the verdict, not the map: unrelated host flips must not rerender every chat. - const remote = useAppStore((state): StructuredAgentSessionHostCapabilityState => { - if (environmentId === null) { - return 'unknown' - } - const entry = state.runtimeStatusByEnvironmentId.get(environmentId) - const status = isRuntimeHostContactRevoked(entry) ? null : lastVerifiedRuntimeStatus(entry) - return status - ? status.capabilities?.includes(capability) - ? 'supported' - : 'unsupported' - : 'unknown' - }) - const local = useSyncExternalStore( - subscribeLocalRuntimeCapabilityObservation, - () => localCapabilityState(capability), - () => 'unknown' as const - ) - useEffect(() => { - if (target?.kind === 'local') { - void ensureLocalRuntimeCapabilities() - } - }, [target?.kind]) - return !target ? 'unknown' : environmentId === null ? local : remote -} - - `, - parkingProjection: ` - import { useAppStore } from '@/store' -export function selectPairedRuntimeParkingEnvironmentIdsFromState(state: { - runtimeStatusByEnvironmentId: PairedRuntimeParkingCapabilityStatuses -}): ReadonlySet { - return selectPairedRuntimeParkingEnvironmentIds(state.runtimeStatusByEnvironmentId) -} - - const Parking = () => useAppStore(selectPairedRuntimeParkingEnvironmentIdsFromState) - `, - globalHotMapConsumer: ` - import { useAppStore } from '@/store' - // oxlint-disable-next-line app-store-performance/no-whole-hot-map-selector -- Fleet picker needs every host's current status. - const Fleet = () => useAppStore(s => s.runtimeStatusByEnvironmentId) - `, - escapedImport: String.raw` - import { use\u0041ppStore as useStore } from '@/store' - export const WholeStore = () => useStore() - `, subscriptions: ` import { useAppStore as useStore } from '@/store' const WholeStore = () => useStore() @@ -146,14 +59,6 @@ export function selectPairedRuntimeParkingEnvironmentIdsFromState(state: { return state.items }) `, - focusedSelectors: ` - import { useAppStore } from '@/store' - import { useShallow as shallow } from 'zustand/react/shallow' - const selectActive = (state) => state.active - const Focused = () => useAppStore(selectActive) - const Cached = () => useAppStore((state) => state.cachedProjection) - const Shallow = () => useAppStore(shallow((state) => ({ active: state.active }))) - `, namedSelectors: ` import { useAppStore } from '@/store' const EarlyFresh = () => useAppStore(selectFreshRows) @@ -161,22 +66,6 @@ export function selectPairedRuntimeParkingEnvironmentIdsFromState(state: { const Stable = () => useAppStore(selectActiveId) const selectActiveId = (state) => state.activeId `, - importedSelector: ` - import { useAppStore } from '@/store' - import { selectRows } from './selectors' - const Other = () => { - const selectRows = (state) => state.rows.map((row) => row.id) - return selectRows - } - const Imported = () => useAppStore(selectRows) - `, - siblingStores: ` - import { usePluginPanelsStore } from '@/store/plugin-panels' - import { useSyncExternalStore } from 'react' - const WholePanels = () => usePluginPanelsStore() - const FreshPanels = () => usePluginPanelsStore((state) => ({ open: state.open })) - const External = () => useSyncExternalStore(subscribe, () => ({ open: true })) - `, nestedShallow: ` import { useAppStore } from '@/store' import { useShallow } from 'zustand/react/shallow' @@ -233,22 +122,14 @@ beforeAll(() => { }) describe('app store performance Oxlint plugin', () => { - it.each([ - ['historicalHotMap', 1], - ['hotMapReturns', 9] - ])('reports whole hot-map results in %s', (name, count) => { - expect(diagnosticsBySource.get(sources[name]).map((diagnostic) => diagnostic.code)).toEqual( - Array(count).fill('app-store-performance(no-whole-hot-map-selector)') - ) + it('reports whole hot-map returns through local bindings', () => { + expect( + diagnosticsBySource.get(sources.hotMapReturns).map((diagnostic) => diagnostic.code) + ).toEqual(Array(9).fill('app-store-performance(no-whole-hot-map-selector)')) }) - it.each([ - 'focusedHotMapReads', - 'fixedHostCapability', - 'parkingProjection', - 'globalHotMapConsumer' - ])('allows stable projections and justified global consumers in %s', (name) => { - expect(diagnosticsBySource.get(sources[name])).toEqual([]) + it('allows stable projections of hot-map fields', () => { + expect(diagnosticsBySource.get(sources.focusedHotMapReads)).toEqual([]) }) it.each(['lexicalBindings', 'shadowedImports'])('respects lexical bindings in %s', (name) => { diff --git a/config/scripts/static-analysis/oxlint-contracts/ime-enter-guard-plugin.test.mjs b/config/scripts/static-analysis/oxlint-contracts/ime-enter-guard-plugin.test.mjs index 654a42e7076..76440924965 100644 --- a/config/scripts/static-analysis/oxlint-contracts/ime-enter-guard-plugin.test.mjs +++ b/config/scripts/static-analysis/oxlint-contracts/ime-enter-guard-plugin.test.mjs @@ -18,14 +18,6 @@ const violations = [ 'inline Enter on a raw input', "export const X = () => { if (e.key === 'Enter') go() }} />" ], - [ - 'Enter on a raw textarea', - "export const X = () => ' : + '') + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const win = new BrowserWindow({ show: false, width: 960, height: 640, + webPreferences: { offscreen: true, webviewTag: true } }) + const attached = new Promise(resolve => win.webContents.once('did-attach-webview', (_event, guest) => resolve(guest))) + await win.loadURL('data:text/html,' + encodeURIComponent('' + + '')) + const guest = await attached + if (guest.isLoading()) await new Promise(resolve => guest.once('did-finish-load', resolve)) + let crashed = false + guest.on('render-process-gone', () => { crashed = true }) + guest.debugger.attach('1.3') + const send = (method, params, sessionId) => guest.debugger.sendCommand(method, params, sessionId) + const insert = async text => (await routePageTextInsertion(guest, send)).deliver({ text }) + await guest.executeJavaScript('field.focus()') + if (scenario.startsWith('child-')) { + const childServer = createServer((_req,res) => { + res.setHeader('Content-Type','text/html') + res.end('') + }) + await new Promise(resolve => childServer.listen(0,'127.0.0.1',resolve)) + const loaded = new Promise(resolve => guest.once('did-frame-finish-load',resolve)) + await guest.executeJavaScript('document.querySelector("iframe").src="http://127.0.0.1:' + childServer.address().port + '/";void 0') + await loaded + const { frameTree } = await send('Page.getFrameTree',{}) + const frameId = frameTree.childFrames[0].frame.id + const { executionContextId } = await send('Page.createIsolatedWorld',{frameId,worldName:'fixture-child'}) + const child = expression => send('Runtime.evaluate',{expression,contextId:executionContextId,returnByValue:true}) + const { targetInfos } = await send('Target.getTargets',{}) + if (targetInfos.some(target => target.type === 'iframe' && target.targetId === frameId)) throw Error('Fixture child must share the root renderer') + await child('field.focus()') + if (scenario === 'child-focus-race') await child("document.designMode='on';document.body.innerHTML='';document.body.focus()") + await win.webContents.executeJavaScript('draft.focus()') + const route = await routePageTextInsertion(guest,send) + if (scenario === 'child-focus-race') await guest.executeJavaScript('field.focus()') + if (scenario === 'child-detached') await guest.executeJavaScript('document.querySelector("iframe").remove()') + if (scenario === 'child-navigation') { + const reloaded = new Promise(resolve => guest.once('did-frame-finish-load',resolve)) + await guest.executeJavaScript('document.querySelector("iframe").src+="?new";void 0') + await reloaded + } + if (scenario === 'child-expired') { + const busy = new Promise(resolve => guest.once('console-message',resolve)) + void child("console.log('busy');{const end=performance.now()+11000;while(performance.now(){inputText=field.value})") + await insert('First\nSecond 🙏') + const selection = await guest.executeJavaScript('field.value') + const inputText = await guest.executeJavaScript('inputText') + await guest.executeJavaScript("document.execCommand('undo')") + const undo = await guest.executeJavaScript('field.value') + await guest.executeJavaScript("field.addEventListener('beforeinput', e => e.preventDefault(), {once:true})") + await insert('Cancelled') + const cancelled = await guest.executeJavaScript('field.value') + await guest.executeJavaScript("const rich=document.createElement('div');rich.id='rich';rich.contentEditable='true';document.body.append(rich);rich.focus()") + await insert('Rich 🙏') + const rich = await guest.executeJavaScript('rich.textContent') + await guest.executeJavaScript("const host=document.createElement('div');host.id='shadow';document.body.append(host);host.attachShadow({mode:'open'}).innerHTML='';host.shadowRoot.firstChild.focus()") + await insert('Shadow') + const shadow = await guest.executeJavaScript('shadow.shadowRoot.firstChild.value') + await guest.executeJavaScript("const frame=document.createElement('iframe');frame.id='local';document.body.append(frame);frame.contentDocument.body.innerHTML='';frame.contentDocument.querySelector('textarea').focus();Date.now=()=>0;Document.prototype.execCommand=()=>{throw Error('page hook ran')};frame.contentWindow.Document.prototype.execCommand=()=>{throw Error('child hook ran')};void 0") + await insert('Local 🙏') + const local = await guest.executeJavaScript('local.contentDocument.querySelector("textarea").value') + await guest.executeJavaScript("local.contentDocument.designMode='on';local.contentDocument.body.innerHTML='';local.contentWindow.focus()") + await insert('Design') + const design = await guest.executeJavaScript('local.contentDocument.body.textContent') + await guest.executeJavaScript("field.focus();field.addEventListener('beforeinput',()=>shadow.shadowRoot.firstChild.focus(),{once:true})") + let moved = 'ok' + try { await insert('Wrong target') } catch(error) { moved=error.code } + await guest.executeJavaScript("document.body.innerHTML='';document.body.contentEditable='true';document.body.focus()") + await insert('Body 🙏') + const body = await guest.executeJavaScript('document.body.textContent') + answer({ selection, inputText, undo, cancelled, rich, shadow, local, design, moved, body, + host: await win.webContents.executeJavaScript('draft.value') }) + return + } + if (scenario === 'detached') { + await guest.executeJavaScript("const frame=document.createElement('iframe');frame.id='local';document.body.append(frame);frame.contentDocument.body.innerHTML='';frame.contentDocument.querySelector('textarea').focus()") + } + const route = await routePageTextInsertion(guest, send) + if (scenario === 'focus-race') { + const { targetInfos } = await send('Target.getTargets', {}) + const target = targetInfos.find(info => info.type === 'iframe') + if (!target) throw new Error('Cross-site frame target missing') + const { sessionId } = await send('Target.attachToTarget', { targetId: target.targetId, flatten: true }) + const { root } = await send('DOM.getDocument', {}, sessionId) + const { nodeId } = await send('DOM.querySelector', { nodeId: root.nodeId, selector: '#field' }, sessionId) + await send('DOM.focus', { nodeId }, sessionId) + } else if (scenario === 'navigation') { + await guest.loadURL('http://127.0.0.1:' + server.address().port + '/') + await guest.executeJavaScript('field.focus()') + } else if (scenario === 'detached') { + await guest.executeJavaScript('local.remove()') + } else if (scenario === 'handler-expired') { + await guest.executeJavaScript("field.addEventListener('beforeinput',()=>{const end=performance.now()+11000;while(performance.now() guest.once('console-message', resolve)) + void guest.executeJavaScript("Date.now=()=>0;console.log('busy');{const end=performance.now()+11000;while(performance.now() {}) + await busy + } + let outcome = 'ok' + const delivered = route.deliver({ text: 'LATE' }) + if (scenario === 'renderer-dies') guest.forcefullyCrashRenderer() + try { await delivered } catch (error) { outcome = error.code } + if (scenario === 'renderer-dies') { + answer({ outcome, host: await win.webContents.executeJavaScript('draft.value') }) + return + } + if (crashed) { answer({ crashed, outcome }); return } + const after = await guest.executeJavaScript('field.value') + await guest.executeJavaScript('field.focus()') + const next = await routePageTextInsertion(guest, send) + await next.deliver({ text: 'Next 🙏' }) + answer({ crashed, outcome, after, next: await guest.executeJavaScript('field.value'), + host: await win.webContents.executeJavaScript('draft.value') }) +}).catch(error => answer({ error: String(error.stack || error) })) +` + +it.each([ + 'focus-race', + 'expired', + 'navigation', + 'detached', + 'editing', + 'handler-expired', + 'renderer-dies', + 'child-insert', + 'child-focus-race', + 'child-expired', + 'child-navigation', + 'child-detached' +])( + 'handles %s input without leaking or replaying abandoned text', + async (scenario) => { + const root = mkdtempSync(join(tmpdir(), 'orca-guest-text-')) + try { + const mainPath = join(root, 'main.cjs') + await build({ + stdin: { contents: MAIN, resolveDir: process.cwd(), loader: 'ts' }, + outfile: mainPath, + bundle: true, + platform: 'node', + format: 'cjs', + external: ['electron', '*.node'] + }) + writeFileSync( + join(root, 'config.json'), + JSON.stringify({ resultPath: join(root, 'result.json'), scenario }) + ) + const result = await runBrowserRouteEgressElectron(root, mainPath) + if (scenario.startsWith('child-')) { + expect(result).toEqual({ + outcome: + scenario === 'child-insert' + ? 'ok' + : scenario === 'child-expired' + ? 'browser_timeout' + : 'browser_input_target_unavailable', + after: + scenario === 'child-insert' ? 'Child 🙏' : scenario === 'child-detached' ? null : '', + root: 'Next 🙏', + host: 'Unsent draft', + hostFocus: 'draft' + }) + return + } + if (scenario === 'editing') { + expect(result).toEqual({ + selection: 'First\nSecond 🙏', + inputText: 'First\nSecond 🙏', + undo: 'Replace me', + cancelled: 'Replace me', + rich: 'Rich 🙏', + shadow: 'Shadow', + local: 'Local 🙏', + design: 'Design', + moved: 'browser_input_target_unavailable', + body: 'Body 🙏', + host: 'Unsent draft' + }) + return + } + if (scenario === 'renderer-dies') { + expect(result).toEqual({ outcome: 'browser_error', host: 'Unsent draft' }) + return + } + expect(result).toEqual({ + crashed: false, + outcome: scenario.endsWith('expired') + ? 'browser_timeout' + : 'browser_input_target_unavailable', + after: '', + next: 'Next 🙏', + host: 'Unsent draft' + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }, + 45_000 +) diff --git a/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts b/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts index b9b3c1f037d..b1fc9ee6400 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts @@ -12,6 +12,7 @@ import type { } from './browser-screencast-stream-types' import { positiveInteger, scaleSnapshotToFit } from './browser-screencast-viewport-fit' import { withTimeout } from '../../../../shared/promise-timeout-fallback' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' // Bound capture time so queued viewport updates and stop can proceed. const SNAPSHOT_CAPTURE_TIMEOUT_MS = 10_000 @@ -22,6 +23,8 @@ type BrowserScreencastSnapshotCaptureDeps = { options: BrowserScreencastOptions isClosed: () => boolean isStopping: () => boolean + // Stop must not wait out a capturePage a non-drawing guest leaves pending; its result is stale anyway. + stopSignal: AbortSignal getSeq: () => number queueFrame: (frame: PendingScreencastFrame) => void applyDeviceMetricsOverride: () => Promise @@ -37,7 +40,7 @@ export type BrowserScreencastSnapshotCapture = { export function createBrowserScreencastSnapshotCapture( deps: BrowserScreencastSnapshotCaptureDeps ): BrowserScreencastSnapshotCapture { - const { webContents, dbg, options, isClosed, isStopping, getSeq, queueFrame } = deps + const { webContents, dbg, options, isClosed, isStopping, stopSignal, getSeq, queueFrame } = deps const { applyDeviceMetricsOverride } = deps const { holdPaint } = options @@ -86,8 +89,16 @@ export function createBrowserScreencastSnapshotCapture( try { // Prefer capturePage to avoid CDP tiling; stopped compositing can leave it pending. const nativeImage = await withTimeout( - holdPaintUntilSettled(holdPaint, () => - webContents.capturePage({ x: 0, y: 0, width: viewportWidth, height: viewportHeight }) + waitForPromiseWithSignal( + holdPaintUntilSettled(holdPaint, () => + webContents.capturePage({ + x: 0, + y: 0, + width: viewportWidth, + height: viewportHeight + }) + ), + stopSignal ), SNAPSHOT_CAPTURE_TIMEOUT_MS, null @@ -125,6 +136,7 @@ export function createBrowserScreencastSnapshotCapture( : {}), captureBeyondViewport: false } + // Not raced with stop: a clipped capture Chromium finishes late re-applies the phone metrics after the clear. const result = await runDebuggerCommandWithTimeout('Page.captureScreenshot', () => holdPaintUntilCdpCaptureSettles(webContents, holdPaint, () => dbg.sendCommand('Page.captureScreenshot', screenshotParams) diff --git a/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts b/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts index 456ff1f213c..14a37aa07b3 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts @@ -162,4 +162,38 @@ describe('startBrowserScreencast', () => { await session.done expect(answer).toHaveBeenCalledExactlyOnceWith(false, '') }) + + it('clears the phone viewport on stop without waiting for a capture the guest never draws', async () => { + vi.useFakeTimers() + const capturePage = vi.fn(() => new Promise(() => {})) + const webContents = { ...createMockWebContents(), capturePage } + const session = await startBrowserScreencast(webContents as never, { + format: 'jpeg', + quality: 70, + maxWidth: 780, + maxHeight: 1688, + everyNthFrame: 1, + minFrameIntervalMs: 0, + viewportWidth: 390, + viewportHeight: 844, + deviceScaleFactor: 2, + mobile: true, + holdPaint: () => () => {}, + onFrame: vi.fn() + }) + try { + await vi.advanceTimersByTimeAsync(0) + expect(capturePage).toHaveBeenCalled() + session.stop() + await vi.advanceTimersByTimeAsync(0) + expect(webContents.debugger.sendCommand).toHaveBeenCalledWith( + 'Emulation.clearDeviceMetricsOverride', + {} + ) + } finally { + await vi.runAllTimersAsync() + await session.done + vi.useRealTimers() + } + }) }) diff --git a/src/main/browser/cdp/screencast/browser-screencast-stream.ts b/src/main/browser/cdp/screencast/browser-screencast-stream.ts index 130031924ae..d78c49b42c1 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-stream.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-stream.ts @@ -57,6 +57,7 @@ export async function startBrowserScreencast( }) const isClosed = (): boolean => closed const isStopping = (): boolean => stopping + const stopRequested = new AbortController() // Preserve the client request so the viewport can grow back after the guest view limit shrinks it. const embedderSizedGuest = isEmbedderSizedScreencastGuest(webContents) @@ -88,6 +89,7 @@ export async function startBrowserScreencast( options, isClosed, isStopping, + stopSignal: stopRequested.signal, getSeq: framePacer.getSeq, queueFrame: framePacer.queueFrame, applyDeviceMetricsOverride: () => { @@ -225,6 +227,7 @@ export async function startBrowserScreencast( return } stopping = true + stopRequested.abort() snapshotCapture.bumpGeneration() snapshotCapture.clearNavigationCaptureTimer() framePacer.clearPending(true) diff --git a/src/main/browser/cdp/transport/cdp-client-response-writer.test.ts b/src/main/browser/cdp/transport/cdp-client-response-writer.test.ts deleted file mode 100644 index 1b4411450c9..00000000000 --- a/src/main/browser/cdp/transport/cdp-client-response-writer.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { once } from 'node:events' -import { setImmediate as nextTurn } from 'node:timers/promises' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WebSocket, WebSocketServer } from 'ws' -import { CdpClientResponseWriter } from './cdp-client-response-writer' - -const MiB = 1024 * 1024 - -describe('CDP outbound backpressure', () => { - let server: WebSocketServer - let peer: WebSocket - let socket: WebSocket - let writer: CdpClientResponseWriter - - beforeEach(async () => { - server = new WebSocketServer({ host: '127.0.0.1', port: 0 }) - await once(server, 'listening') - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('Expected TCP address') - } - const accepted = new Promise((resolve) => server.once('connection', resolve)) - peer = new WebSocket(`ws://127.0.0.1:${address.port}`) - await once(peer, 'open') - socket = await accepted - writer = new CdpClientResponseWriter(() => socket) - }) - - afterEach(async () => { - writer.forgetClient(socket) - vi.useRealTimers() - vi.restoreAllMocks() - socket.terminate() - peer.terminate() - await new Promise((resolve) => server.close(() => resolve())) - }) - - it('drains replies and events in order with their original session correlation', () => { - vi.useFakeTimers() - const buffered = vi.spyOn(socket, 'bufferedAmount', 'get').mockReturnValue(9 * MiB) - const send = vi.spyOn(socket, 'send').mockImplementation(() => {}) - writer.recordRequestSessionId(socket, 7, { sessionId: 'session-one' }) - writer.sendResult(7, { ok: true }) - writer.send({ method: 'Page.loadEventFired', sessionId: 'session-one' }) - writer.recordRequestSessionId(socket, 8, { sessionId: 'session-two' }) - writer.sendError(8, 'failed') - expect(send).not.toHaveBeenCalled() - - buffered.mockReturnValue(0) - vi.advanceTimersByTime(25) - expect(send.mock.calls.map(([frame]) => JSON.parse(String(frame)))).toEqual([ - { id: 7, result: { ok: true }, sessionId: 'session-one' }, - { method: 'Page.loadEventFired', sessionId: 'session-one' }, - { id: 8, error: { code: -32000, message: 'failed' }, sessionId: 'session-two' } - ]) - expect(vi.getTimerCount()).toBe(0) - }) - - it.each(['forget', 'close'] as const)('releases a parked queue on %s', (boundary) => { - vi.useFakeTimers() - const initialCloseListeners = socket.listenerCount('close') - const buffered = vi.spyOn(socket, 'bufferedAmount', 'get').mockReturnValue(9 * MiB) - const send = vi.spyOn(socket, 'send').mockImplementation(() => {}) - writer.sendResult(1, { value: 'abandoned' }) - expect(vi.getTimerCount()).toBe(1) - if (boundary === 'forget') { - writer.forgetClient(socket) - } else { - socket.emit('close', 1000, Buffer.alloc(0)) - } - buffered.mockReturnValue(0) - vi.advanceTimersByTime(100) - expect(send).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - expect(socket.listenerCount('close')).toBeLessThanOrEqual(initialCloseListeners) - }) - - it('terminates a real stalled reader before native buffering follows all produced bytes', async () => { - peer.pause() - const payload = 'x'.repeat(64 * 1024) - let peakBuffered = 0 - for (let index = 0; index < 2048; index++) { - writer.send({ method: 'Runtime.consoleAPICalled', params: { data: payload } }) - peakBuffered = Math.max(peakBuffered, socket.bufferedAmount) - if (index % 16 === 0) { - await nextTurn() - } - if (socket.readyState !== WebSocket.OPEN) { - break - } - } - expect(peakBuffered).toBeLessThan(9 * MiB) - expect(socket.readyState).not.toBe(WebSocket.OPEN) - }) - - it('delivers a transient burst completely to a reading client', async () => { - const frames: string[] = [] - const allReceived = new Promise((resolve) => { - peer.on('message', (frame) => { - frames.push(frame.toString()) - if (frames.length === 192) { - resolve() - } - }) - }) - const payload = 'y'.repeat(64 * 1024) - for (let index = 0; index < 192; index++) { - writer.sendResult(index, { data: payload }) - } - await allReceived - expect(frames).toEqual( - Array.from({ length: 192 }, (_, id) => JSON.stringify({ id, result: { data: payload } })) - ) - expect(socket.readyState).toBe(WebSocket.OPEN) - }) -}) diff --git a/src/main/browser/cdp/transport/cdp-ws-proxy-first-paint.test.ts b/src/main/browser/cdp/transport/cdp-ws-proxy-first-paint.test.ts deleted file mode 100644 index 5644db0ed29..00000000000 --- a/src/main/browser/cdp/transport/cdp-ws-proxy-first-paint.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi } from 'vitest' -import { CdpWsProxy } from './cdp-ws-proxy' -import { - connect, - createMockWebContents, - getSendCommandMethods, - mockAsWebContents, - sendAndReceive -} from './cdp-ws-proxy-test-harness' - -vi.mock('electron', () => ({ - webContents: { fromId: vi.fn() } -})) - -describe('CdpWsProxy first-paint gate', () => { - it('lets an unpainted page paint before input reaches it, once per document', async () => { - const guest = createMockWebContents() - guest.webContents.getType.mockReturnValue('webview') - let paintFrame = (): void => {} - // A blank document: frames run, but no paint entry is ever recorded. - guest.webContents.debugger.sendCommand.mockImplementation( - async (method?: string, params?: Record) => { - if (method !== 'Runtime.evaluate') { - return {} - } - if (params?.returnByValue) { - return { result: { value: [false, 1234.5] } } - } - await new Promise((resolve) => { - paintFrame = resolve - }) - return {} - } - ) - const releasePaint = vi.fn() - const holdPaint = vi.fn(() => releasePaint) - const guestProxy = new CdpWsProxy(mockAsWebContents(guest), holdPaint) - const client = await connect(await guestProxy.start()) - const move = (id: number): Promise> => - sendAndReceive(client, { - id, - method: 'Input.dispatchMouseEvent', - params: { type: 'mouseMoved', x: 1, y: 1 } - }) - - const first = move(33) - await vi.waitFor(() => expect(holdPaint).toHaveBeenCalledTimes(1)) - expect(getSendCommandMethods(guest)).not.toContain('Input.dispatchMouseEvent') - paintFrame() - await first - await move(34) - - expect(getSendCommandMethods(guest).filter((m) => m.startsWith('Input.'))).toHaveLength(2) - expect(holdPaint).toHaveBeenCalledTimes(1) - expect(releasePaint).toHaveBeenCalledTimes(1) - client.close() - await guestProxy.stop() - }) -}) diff --git a/src/main/browser/cdp/transport/cdp-ws-proxy-input-focus.test.ts b/src/main/browser/cdp/transport/cdp-ws-proxy-input-focus.test.ts deleted file mode 100644 index a1db6a0d123..00000000000 --- a/src/main/browser/cdp/transport/cdp-ws-proxy-input-focus.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, it, expect, vi } from 'vitest' -import { CdpWsProxy } from './cdp-ws-proxy' -import { - connect, - createMockWebContents, - getSendCommandMethods, - mockAsWebContents, - sendAndReceive -} from './cdp-ws-proxy-test-harness' - -vi.mock('electron', () => ({ - webContents: { fromId: vi.fn() } -})) - -describe('CdpWsProxy agent input focus guard', () => { - it('refuses a press when the user’s focus cannot be guarded', async () => { - const mock = createMockWebContents() - mock.webContents.getType.mockReturnValue('webview') - const proxy = new CdpWsProxy( - mockAsWebContents(mock), - () => () => {}, - async () => { - throw new Error('focus guard unavailable') - } - ) - const client = await connect(await proxy.start()) - - const response = await sendAndReceive(client, { - id: 81, - method: 'Input.dispatchMouseEvent', - params: { type: 'mousePressed', x: 1, y: 1 } - }) - - expect(response.error).toMatchObject({ message: 'focus guard unavailable' }) - expect(getSendCommandMethods(mock)).not.toContain('Input.dispatchMouseEvent') - client.close() - await proxy.stop() - }) -}) diff --git a/src/main/browser/cdp/transport/cdp-ws-proxy-malformed-messages.test.ts b/src/main/browser/cdp/transport/cdp-ws-proxy-malformed-messages.test.ts deleted file mode 100644 index f56fc4b51c0..00000000000 --- a/src/main/browser/cdp/transport/cdp-ws-proxy-malformed-messages.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { once } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type WebSocket from 'ws' -import { CdpWsProxy } from './cdp-ws-proxy' -import { - connect, - createMockWebContents, - getSendCommandMethods, - mockAsWebContents, - sendAndReceive, - type MockWebContents -} from './cdp-ws-proxy-test-harness' - -vi.mock('electron', () => ({ webContents: { fromId: vi.fn() } })) - -function nextMessage(client: WebSocket): Promise> { - return new Promise((resolve) => { - client.once('message', (data) => resolve(JSON.parse(data.toString()))) - }) -} - -describe('CdpWsProxy malformed client messages', () => { - let mock: MockWebContents - let proxy: CdpWsProxy - let endpoint: string - - beforeEach(async () => { - mock = createMockWebContents() - proxy = new CdpWsProxy(mockAsWebContents(mock), () => () => {}) - endpoint = await proxy.start() - }) - - afterEach(async () => { - await proxy.stop() - }) - - it.each([ - '{"id":1,"method":42}', - '{"id":1,"method":"DOM.enable","params":[]}', - '{"id":1,"method":"DOM.enable","sessionId":42}' - ])('answers malformed command %s with an error and keeps the client usable', async (raw) => { - const client = await connect(endpoint) - try { - const reply = nextMessage(client) - client.send(raw) - expect(await reply).toEqual({ - id: 1, - error: { code: -32000, message: 'Invalid CDP request' } - }) - expect(getSendCommandMethods(mock)).not.toContain('DOM.enable') - - const next = await sendAndReceive(client, { id: 2, method: 'Browser.getVersion' }) - expect(next).toMatchObject({ id: 2, result: expect.any(Object) }) - } finally { - client.close() - } - }) - - it('contains an invalid UTF-8 frame and serves the next client', async () => { - const malformed = await connect(endpoint) - const closed = once(malformed, 'close') - malformed.send(Buffer.from([0xff]), { binary: false }) - await closed - - const next = await connect(endpoint) - try { - expect(await sendAndReceive(next, { id: 1, method: 'Browser.getVersion' })).toMatchObject({ - id: 1, - result: expect.any(Object) - }) - } finally { - next.close() - } - }) -}) diff --git a/src/main/browser/cdp/transport/cdp-ws-proxy-startup-lifetime.test.ts b/src/main/browser/cdp/transport/cdp-ws-proxy-startup-lifetime.test.ts index dfb9f7a18af..9e38e6c5e22 100644 --- a/src/main/browser/cdp/transport/cdp-ws-proxy-startup-lifetime.test.ts +++ b/src/main/browser/cdp/transport/cdp-ws-proxy-startup-lifetime.test.ts @@ -1,7 +1,6 @@ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CdpWsProxy } from './cdp-ws-proxy' -import { acquireElectronDebugger } from '../debugger/electron-debugger-lease' import { createMockWebContents, mockAsWebContents } from './cdp-ws-proxy-test-harness' const { createServerMock, webSocketServerMock } = vi.hoisted(() => ({ @@ -53,15 +52,6 @@ function pendingEnable(mock: ReturnType) { return { finish, fail } } -function invalidateNativeHandle(mock: ReturnType): void { - mock.destroy() - Object.defineProperty(mock.webContents, 'debugger', { - get() { - throw new Error('Object has been destroyed') - } - }) -} - describe('CdpWsProxy startup ownership', () => { let servers: ProxyServer[] let socketServers: ProxyWebSocketServer[] @@ -100,72 +90,6 @@ describe('CdpWsProxy startup ownership', () => { expect(mock.listeners.get('detach') ?? []).toHaveLength(0) } - it('tolerates Page.enable rejection on a live shared attachment', async () => { - const mock = createMockWebContents() - const debuggerHandle = mock.webContents.debugger - const lease = acquireElectronDebugger(mockAsWebContents(mock)) - debuggerHandle.sendCommand.mockRejectedValueOnce(new Error('Page domain is not ready')) - const proxy = makeProxy(mock) - - await expect(proxy.start()).resolves.toMatch(/^ws:\/\/127\.0\.0\.1:9222\//) - await proxy.stop() - - expectNoListeners(mock) - expect(debuggerHandle.isAttached()).toBe(true) - expect(debuggerHandle.detach).not.toHaveBeenCalled() - lease.release() - expect(debuggerHandle.attach).toHaveBeenCalledTimes(1) - expect(debuggerHandle.detach).toHaveBeenCalledTimes(1) - }) - - it.each([false, true])( - 'refuses server admission after native detach during Page.enable (destroyed: %s)', - async (destroyed) => { - const mock = createMockWebContents() - const debuggerHandle = mock.webContents.debugger - const enable = pendingEnable(mock) - const proxy = makeProxy(mock) - const starting = proxy.start() - debuggerHandle.isAttached.mockReturnValue(false) - if (destroyed) { - invalidateNativeHandle(mock) - } - mock.emit('detach', {}, 'target closed') - enable.fail(new Error('target closed while handling command')) - - await expect(starting).rejects.toThrow('detached during startup') - expect(proxy.getPort()).toBe(0) - expect(servers).toHaveLength(0) - expect(socketServers).toHaveLength(0) - expectNoListeners(mock) - } - ) - - it('cleans a destroyed startup even when no native detach event arrives', async () => { - const mock = createMockWebContents() - const enable = pendingEnable(mock) - const proxy = makeProxy(mock) - const starting = proxy.start() - invalidateNativeHandle(mock) - enable.fail(new Error('target closed while handling command')) - - await expect(starting).rejects.toThrow('no longer available') - expect(servers).toHaveLength(0) - expectNoListeners(mock) - }) - - it('refuses server admission when stopped after attachment completes', async () => { - const mock = createMockWebContents() - const proxy = makeProxy(mock) - const starting = proxy.start() - await Promise.resolve() - await proxy.stop() - - await expect(starting).rejects.toThrow('stopped') - expect(servers).toHaveLength(0) - expectNoListeners(mock) - }) - it('does not detach a successor when stopped Page.enable completes late', async () => { const mock = createMockWebContents() const debuggerHandle = mock.webContents.debugger @@ -187,30 +111,4 @@ describe('CdpWsProxy startup ownership', () => { expect(debuggerHandle.detach).toHaveBeenCalledTimes(2) expectNoListeners(mock) }) - - it('retires an established proxy without reading a destroyed native handle', async () => { - const mock = createMockWebContents() - const proxy = makeProxy(mock) - await proxy.start() - invalidateNativeHandle(mock) - - await expect(proxy.stop()).resolves.toBeUndefined() - expectNoListeners(mock) - expect(servers[0].listening).toBe(false) - expect(socketServers[0].closed).toBe(true) - }) - - it('closes server resources even if debugger cleanup throws', async () => { - const mock = createMockWebContents() - const proxy = makeProxy(mock) - await proxy.start() - mock.webContents.debugger.removeListener.mockImplementationOnce(() => { - throw new Error('debugger cleanup failed') - }) - - await expect(proxy.stop()).rejects.toThrow('debugger cleanup failed') - expect(servers[0].listening).toBe(false) - expect(socketServers[0].closed).toBe(true) - expect(mock.webContents.debugger.detach).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/browser/client-hosts/commands/browser-host-command-result-staging.ts b/src/main/browser/client-hosts/commands/browser-host-command-result-staging.ts new file mode 100644 index 00000000000..b13539501c4 --- /dev/null +++ b/src/main/browser/client-hosts/commands/browser-host-command-result-staging.ts @@ -0,0 +1,80 @@ +import type { BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' +import { + BROWSER_CLIENT_AUTOMATION_RESULT_CHUNK_MAX_BYTES, + BROWSER_CLIENT_AUTOMATION_RESULT_MAX_BYTES, + BROWSER_CLIENT_AUTOMATION_STAGED_RESULT_MAX_BYTES, + truncateBrowserClientAutomationErrorMessage, + type BrowserClientAutomationResult as BrowserClientHostCommandResult +} from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' +import { browserHostCommandResultIdentity } from './browser-host-command-result-submission' + +const BROWSER_HOST_COMMAND_RESULT_TOO_LARGE_CODE = 'browser_host_command_result_too_large' + +/** Sends an automation value too big for one result frame to the host ahead of its settlement. */ +export async function stageBrowserHostCommandResult( + command: BrowserClientHostCommandEvent, + result: BrowserClientHostCommandResult, + sendChunk: (params: unknown) => Promise, + signal: AbortSignal +): Promise { + if ( + result.status !== 'completed' || + result.value === undefined || + command.command.type !== 'automation' + ) { + return result + } + const bytes = Buffer.from(JSON.stringify(result.value), 'utf8') + const hostStages = command.command.stagedResults === true + if ( + bytes.byteLength <= BROWSER_CLIENT_AUTOMATION_RESULT_CHUNK_MAX_BYTES || + (!hostStages && bytes.byteLength <= BROWSER_CLIENT_AUTOMATION_RESULT_MAX_BYTES) + ) { + return result + } + if (!hostStages || bytes.byteLength > BROWSER_CLIENT_AUTOMATION_STAGED_RESULT_MAX_BYTES) { + const limit = hostStages + ? BROWSER_CLIENT_AUTOMATION_STAGED_RESULT_MAX_BYTES + : BROWSER_CLIENT_AUTOMATION_RESULT_MAX_BYTES + return failed( + BROWSER_HOST_COMMAND_RESULT_TOO_LARGE_CODE, + `The result (${formatMegabytes(bytes.byteLength)}) is larger than the ${formatMegabytes(limit)} this server accepts from a page on this device. Use --format jpeg, a selector, or a smaller viewport${hostStages ? '' : ', or update the server'}.` + ) + } + const identity = browserHostCommandResultIdentity(command) + try { + for ( + let offset = 0; + offset < bytes.byteLength; + offset += BROWSER_CLIENT_AUTOMATION_RESULT_CHUNK_MAX_BYTES + ) { + if (signal.aborted) { + return failed('browser_client_page_command_aborted') + } + const chunk = bytes.subarray( + offset, + offset + BROWSER_CLIENT_AUTOMATION_RESULT_CHUNK_MAX_BYTES + ) + await sendChunk({ ...identity, offset, contentBase64: chunk.toString('base64') }) + } + } catch (error) { + // Keep the host or transport code (e.g. too large, unavailable) so the agent sees why. + return failed( + error instanceof RemoteRuntimeClientError + ? error.code + : 'browser_host_command_result_staging_failed', + error instanceof Error ? error.message : String(error) + ) + } + return { status: 'completed', stagedValueBytes: bytes.byteLength } +} + +function failed(errorCode: string, message?: string): BrowserClientHostCommandResult { + const errorMessage = message ? truncateBrowserClientAutomationErrorMessage(message) : undefined + return { status: 'failed', errorCode, ...(errorMessage ? { errorMessage } : {}) } +} + +function formatMegabytes(bytes: number): string { + return `${(bytes / (1024 * 1024)).toFixed(1)} MB` +} diff --git a/src/main/browser/client-hosts/commands/browser-host-command-result-submission.ts b/src/main/browser/client-hosts/commands/browser-host-command-result-submission.ts index 3364bba5f94..a75d8cfe90b 100644 --- a/src/main/browser/client-hosts/commands/browser-host-command-result-submission.ts +++ b/src/main/browser/client-hosts/commands/browser-host-command-result-submission.ts @@ -18,21 +18,7 @@ export async function submitBrowserHostCommandResult( const result = BrowserClientHostCommandResult.parse(candidate) const response = await sendRequest( 'browser.clientHost.commandResult', - { - pageCommandProtocolVersion: command.pageCommandProtocolVersion, - ...(command.pageReconciliationProtocolVersion - ? { pageReconciliationProtocolVersion: command.pageReconciliationProtocolVersion } - : {}), - authorityRuntimeId: command.authorityRuntimeId, - authorityEpoch: command.authorityEpoch, - browserHostClientId: command.browserHostClientId, - browserHostGeneration: command.browserHostGeneration, - browserPageId: command.browserPageId, - pageHostGeneration: command.pageHostGeneration, - commandSequence: command.commandSequence, - commandId: command.commandId, - result - }, + { ...browserHostCommandResultIdentity(command), result }, timeoutMs ) if (!response.ok) { @@ -45,3 +31,21 @@ export async function submitBrowserHostCommandResult( throw new Error('Invalid browser host command result acknowledgement') } } + +/** The command identity a result, or a chunk of one, is filed under. */ +export function browserHostCommandResultIdentity(command: BrowserClientHostCommandEvent) { + return { + pageCommandProtocolVersion: command.pageCommandProtocolVersion, + ...(command.pageReconciliationProtocolVersion + ? { pageReconciliationProtocolVersion: command.pageReconciliationProtocolVersion } + : {}), + authorityRuntimeId: command.authorityRuntimeId, + authorityEpoch: command.authorityEpoch, + browserHostClientId: command.browserHostClientId, + browserHostGeneration: command.browserHostGeneration, + browserPageId: command.browserPageId, + pageHostGeneration: command.pageHostGeneration, + commandSequence: command.commandSequence, + commandId: command.commandId + } +} diff --git a/src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.ts b/src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.ts index 4d8dd54a953..852cc235165 100644 --- a/src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.ts +++ b/src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.ts @@ -6,7 +6,6 @@ import { BrowserClientAutomationResult as BrowserClientHostCommandResult, type BrowserClientAutomationResult as BrowserClientHostCommandResultType } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' -import { BROWSER_CLIENT_PAGE_METADATA_METHOD } from '../../../../shared/browser/client-hosting/browser-client-page-metadata-protocol' import { assertBrowserClientHostAttachOptions } from '../lifecycle/browser-client-host-attach-request' import { BrowserHostReconnectDelay, @@ -79,12 +78,12 @@ export class PairedRuntimeBrowserHostLease { } /** Unversioned, unlike the file channel: an older runtime answers with a reportable error. */ - sendPageMetadataRequest(params: unknown, timeoutMs: number) { + sendHostRequest(method: string, params: unknown, timeoutMs: number) { // close drops the connection synchronously. return requireBrowserHostLeaseSendRequest( this.connection?.sendRequest, 'Remote runtime browser host lease is unavailable.' - )(BROWSER_CLIENT_PAGE_METADATA_METHOD, params, timeoutMs) + )(method, params, timeoutMs) } sendFileChannelRequest(method: string, params: unknown, timeoutMs: number) { diff --git a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host.ts b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host.ts index d26053a63dc..937f2045a25 100644 --- a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host.ts +++ b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host.ts @@ -3,7 +3,12 @@ import type { BrowserClientHostCommandEvent, BrowserClientHostLeaseAuthority } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' -import type { BrowserClientAutomationResult as BrowserClientHostCommandResult } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' +import { + BROWSER_CLIENT_HOST_COMMAND_RESULT_CHUNK_METHOD, + type BrowserClientAutomationResult as BrowserClientHostCommandResult +} from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' +import { BROWSER_CLIENT_PAGE_METADATA_METHOD } from '../../../../shared/browser/client-hosting/browser-client-page-metadata-protocol' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import type { RemoteRuntimeSubscriptionOptions } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' @@ -14,6 +19,7 @@ import type { DispatcherOptions } from '../commands/browser-client-host-command-state' import { PairedRuntimeBrowserHostLease } from '../leases/paired-runtime-browser-host-lease' +import { stageBrowserHostCommandResult } from '../commands/browser-host-command-result-staging' type DispatcherLimits = Omit @@ -124,7 +130,7 @@ export class PairedRuntimeBrowserClientHost { params: unknown, timeoutMs: number ): Promise> { - return this.lease.sendPageMetadataRequest(params, timeoutMs) + return this.lease.sendHostRequest(BROWSER_CLIENT_PAGE_METADATA_METHOD, params, timeoutMs) } refreshPageInventory(): Promise { @@ -150,11 +156,28 @@ export class PairedRuntimeBrowserClientHost { this.options.onAuthority?.(authority) this.dispatcher = new BrowserClientHostCommandDispatcher({ authority, - handler: this.options.handler, + handler: async (command, signal) => + stageBrowserHostCommandResult( + command, + await this.options.handler(command, signal), + (params) => this.sendCommandResultChunk(params), + signal + ), ...this.options.dispatcher }) } + private async sendCommandResultChunk(params: unknown): Promise { + const response = await this.lease.sendHostRequest( + BROWSER_CLIENT_HOST_COMMAND_RESULT_CHUNK_METHOD, + params, + this.options.timeoutMs ?? 15_000 + ) + if (!response.ok) { + throw new RemoteRuntimeClientError(response.error.code, response.error.message) + } + } + private dispatch( command: BrowserClientHostCommandEvent ): Promise { diff --git a/src/main/browser/client-pages/execution/browser-client-page-command-failure.ts b/src/main/browser/client-pages/execution/browser-client-page-command-failure.ts index 1d73355598f..e168e9f75d0 100644 --- a/src/main/browser/client-pages/execution/browser-client-page-command-failure.ts +++ b/src/main/browser/client-pages/execution/browser-client-page-command-failure.ts @@ -1,15 +1,21 @@ -import type { BrowserClientAutomationResult as BrowserClientHostCommandResult } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' +import { + truncateBrowserClientAutomationErrorMessage, + type BrowserClientAutomationResult as BrowserClientHostCommandResult +} from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' import type { BrowserExpectedUrlMismatch } from '../../../../shared/browser/client-hosting/browser-expected-url' export class BrowserClientPageCommandError extends Error { readonly expectedUrlMismatch?: BrowserExpectedUrlMismatch + /** The browser command's own message, so the host can show it with the code. */ + readonly detail?: string constructor( message: string, - options?: ErrorOptions & { expectedUrlMismatch?: BrowserExpectedUrlMismatch } + options?: ErrorOptions & { expectedUrlMismatch?: BrowserExpectedUrlMismatch; detail?: string } ) { super(message, options) this.expectedUrlMismatch = options?.expectedUrlMismatch + this.detail = options?.detail } } @@ -28,9 +34,14 @@ export function browserClientPageCommandFailure( ): BrowserClientHostCommandResult { const mismatch = error instanceof BrowserClientPageCommandError ? error.expectedUrlMismatch : undefined + const errorMessage = + error instanceof BrowserClientPageCommandError && error.detail + ? truncateBrowserClientAutomationErrorMessage(error.detail) + : undefined return { status: 'failed', errorCode: browserClientPageCommandFailureCode(error, signal), + ...(errorMessage ? { errorMessage } : {}), ...(mismatch ? { expectedUrlMismatch: mismatch } : {}) } } diff --git a/src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts b/src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts deleted file mode 100644 index 0df19a5489a..00000000000 --- a/src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts +++ /dev/null @@ -1,217 +0,0 @@ -import type { Session, WebContents } from 'electron' -import { describe, expect, it, vi } from 'vitest' -import type { BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' -import { BrowserClientHostCommandDispatcher } from '../../client-hosts/commands/browser-client-host-command-dispatcher' -import { BrowserClientPageCommandExecutor } from './browser-client-page-command-executor' -import { createBrowserRoutePartitionBindingStoreFake } from '../../routing/partitions/browser-route-partition-binding-store-fake' -import { BrowserRouteSessionRegistry } from '../../routing/sessions/browser-route-session-registry' -import { BrowserRouteWebContentsRegistry } from '../../routing/guest-authority/browser-route-webcontents-registry' - -const partition = `persist:orca-browser-v1-${'b'.repeat(64)}` - -describe('BrowserClientPageCommandExecutor integration', () => { - it('composes exact route, Session, navigation, and spontaneous destroyed cleanup', async () => { - const routeSession = { - setProxy: vi.fn(async () => {}), - closeAllConnections: vi.fn(async () => {}), - resolveProxy: vi.fn(async () => 'SOCKS5 127.0.0.1:43123') - } - const clearPolicies = vi.fn() - let webContentsRegistry: BrowserRouteWebContentsRegistry | null = null - const sessionRegistry = new BrowserRouteSessionRegistry({ - derivePartition: () => ({ partition, bindingFingerprint: 'binding-a' }), - validateProfile: vi.fn(), - getSession: () => routeSession, - setupPolicies: vi.fn(), - clearPolicies, - retirePageAuthority: (retirement) => - webContentsRegistry?.retirePageAuthority(retirement) ?? false, - bindingStore: createBrowserRoutePartitionBindingStoreFake() - }) - webContentsRegistry = new BrowserRouteWebContentsRegistry({ - getPartitionForSession: (session) => sessionRegistry.getPartitionForSession(session), - getPreparedPageAuthority: (page) => sessionRegistry.getPreparedPageAuthority(page), - rekeyPreparedPage: (previous, next) => sessionRegistry.rekeyPreparedPage(previous, next), - retirePreparedPage: (page) => sessionRegistry.retirePreparedPage(page), - retirePreparedPagesOwnedByRenderer: (rendererWebContentsId) => - sessionRegistry.retirePreparedPagesOwnedByRenderer(rendererWebContentsId) - }) - const rekeyGuestLifecycle = vi.spyOn(webContentsRegistry, 'rekeyGuestLifecycle') - const grantReconciledNavigation = vi.spyOn(webContentsRegistry, 'grantReconciledNavigation') - const guest = createGuest(routeSession as unknown as Session) - const routeRelease = vi.fn() - const rendererRetire = vi.fn(async () => { - guest.destroy() - }) - const rendererRekey = vi.fn(async () => {}) - const executor = new BrowserClientPageCommandExecutor({ - orcaProfileId: 'orca-profile-a', - authorityConnectionIdentity: 'authority-record-a', - pairingAuthorityConnectionIdentity: 'pairing-authority-record-a', - legacyAuthorityConnectionIdentity: 'legacy-authority-record-a', - storageScope: 'a'.repeat(64), - retainNetworkRoute: vi.fn(async () => ({ - key: 'execution-host-a', - executionHostIdentity: 'execution-host-record-a', - legacyExecutionHostIdentity: 'legacy-execution-host-record-a', - proxyEndpoint: { host: '127.0.0.1' as const, port: 43123 }, - release: routeRelease - })), - selectRenderer: () => ({ - rendererWebContentsId: 11, - isCurrent: () => true, - mountPage: async () => { - expect(webContentsRegistry?.attachGuest(guest.webContents)).toBe(true) - return { webContentsId: 41 } - }, - rekeyPage: rendererRekey, - retirePage: rendererRetire - }), - routeSessions: sessionRegistry, - executeAutomation: vi.fn(async () => undefined), - retireAutomation: vi.fn(async () => {}), - guestBinding: { bind: vi.fn(), release: vi.fn() }, - routeWebContents: webContentsRegistry - }) - - await expect(executor.handle(createCommand('createPage'), signal())).resolves.toEqual({ - status: 'completed' - }) - expect(guest.webContents.setWebRTCIPHandlingPolicy).toHaveBeenCalledWith( - 'disable_non_proxied_udp' - ) - expect(sessionRegistry.isAllowedPartition(partition)).toBe(true) - expect(guest.url()).toBe('about:blank') - await expect(executor.handle(createCommand('navigate'), signal())).resolves.toEqual({ - status: 'completed' - }) - expect(guest.url()).toBe('https://example.internal/path') - - const reclaim = createCommand('reclaimPage') - const dispatcher = new BrowserClientHostCommandDispatcher({ - authority: reclaim, - handler: (event, commandSignal) => executor.handle(event, commandSignal) - }) - const reclaimed = await dispatcher.dispatch(reclaim) - expect(rekeyGuestLifecycle).toHaveReturnedWith(expect.any(Object)) - expect(grantReconciledNavigation).toHaveReturnedWith(true) - expect(reclaimed).toEqual({ status: 'completed' }) - expect(rendererRekey).toHaveBeenCalledOnce() - expect(executor.hasPage('page-a', 7)).toBe(false) - expect(executor.hasPage('page-a', 8)).toBe(true) - expect(executor.snapshotPageInventory()).toEqual([ - expect.objectContaining({ - authorityEpoch: 'epoch-new', - pageHostGeneration: 8, - currentUrl: 'https://example.internal/path', - state: 'active' - }) - ]) - - guest.destroy() - expect(executor.snapshotPageInventory()).toEqual([ - expect.objectContaining({ browserPageId: 'page-a', state: 'outcomeUnknown' }) - ]) - await expect(executor.retirePage('page-a', 8)).resolves.toBe(true) - expect(guest.webContents.close).not.toHaveBeenCalled() - expect(rendererRetire).toHaveBeenCalledOnce() - expect(routeRelease).toHaveBeenCalledOnce() - expect(clearPolicies).toHaveBeenCalledOnce() - expect(sessionRegistry.isAllowedPartition(partition)).toBe(false) - }) -}) - -function createCommand( - type: 'createPage' | 'navigate' | 'reclaimPage' -): BrowserClientHostCommandEvent { - const previousAuthority = { - authorityRuntimeId: 'runtime-a', - authorityEpoch: 'epoch-a', - browserHostClientId: 'client-a', - browserHostGeneration: 3, - pageHostGeneration: 7 - } - return { - type: 'command', - authorityRuntimeId: 'runtime-a', - authorityEpoch: type === 'reclaimPage' ? 'epoch-new' : 'epoch-a', - browserHostClientId: 'client-a', - browserHostGeneration: type === 'reclaimPage' ? 4 : 3, - pageCommandProtocolVersion: 1, - pageReconciliationProtocolVersion: 1, - browserPageId: 'page-a', - pageHostGeneration: type === 'reclaimPage' ? 8 : 7, - commandSequence: type === 'createPage' || type === 'reclaimPage' ? 1 : 2, - commandId: `${type}-a`, - command: - type === 'createPage' - ? { - type: 'createPage', - browserProfileId: 'profile-a', - executionHostKey: 'execution-host-a' - } - : type === 'navigate' - ? { type: 'navigate', url: 'example.internal/path' } - : { - type: 'reclaimPage', - previousAuthority, - browserProfileId: 'profile-a', - executionHostKey: 'execution-host-a' - } - } -} - -function createGuest(routeSession: Session) { - const listeners = new Map void>>() - let destroyed = false - let url = 'about:blank' - const emit = (event: string, ...args: unknown[]): void => { - for (const listener of listeners.get(event) ?? []) { - listener(...args) - } - } - const webContents = { - id: 41, - session: routeSession, - hostWebContents: { id: 11 }, - getType: () => 'webview', - getURL: () => url, - isDestroyed: () => destroyed, - close: vi.fn(() => { - destroyed = true - emit('destroyed') - }), - loadURL: vi.fn(async (nextUrl: string) => { - const event = { preventDefault: vi.fn() } - emit('will-navigate', event, nextUrl) - if (event.preventDefault.mock.calls.length > 0) { - throw new Error('navigation denied') - } - url = nextUrl - }), - setWebRTCIPHandlingPolicy: vi.fn(), - setWindowOpenHandler: vi.fn(), - on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { - const eventListeners = listeners.get(event) ?? new Set() - eventListeners.add(listener) - listeners.set(event, eventListeners) - }), - off: vi.fn((event: string, listener: (...args: unknown[]) => void) => { - listeners.get(event)?.delete(listener) - }) - } as unknown as WebContents - return { - webContents, - url: () => url, - destroy: () => { - if (!destroyed) { - destroyed = true - emit('destroyed') - } - } - } -} - -function signal(): AbortSignal { - return new AbortController().signal -} diff --git a/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts b/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts index eaa68d7e2ce..137b4712532 100644 --- a/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts +++ b/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts @@ -228,7 +228,12 @@ async function runFixture(): Promise { const resultPath = join(root, 'result.json') writeFileSync( preloadSource, - preloadEntry(join(process.cwd(), 'src/preload/browser-client-page-renderer-requests.ts')) + preloadEntry( + join( + process.cwd(), + 'src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts' + ) + ) ) writeFileSync( rendererSource, diff --git a/src/main/browser/document-preview/doc-preview-file-reader.test.ts b/src/main/browser/document-preview/doc-preview-file-reader.test.ts index c4557857ddb..047c7ae0e0d 100644 --- a/src/main/browser/document-preview/doc-preview-file-reader.test.ts +++ b/src/main/browser/document-preview/doc-preview-file-reader.test.ts @@ -4,10 +4,10 @@ const mocks = vi.hoisted(() => ({ callRuntimeEnvironment: vi.fn() })) -vi.mock('../../ipc/runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../../ipc/runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: mocks.callRuntimeEnvironment })) -vi.mock('../../ipc/runtime-environments/runtime-environment-registry-root', () => ({ +vi.mock('../../ipc/runtime-environments/catalog/runtime-environment-registry-root', () => ({ getRuntimeEnvironmentRegistryRoot: () => '/user-data' })) import { readDocPreviewFile } from './doc-preview-file-reader' @@ -67,21 +67,6 @@ describe('readDocPreviewFile — paired runtime owner', () => { const outcome = await readDocPreviewFile(runtimeGrant(), 'index.html') expect(outcome).toEqual({ ok: true, bytes: html, contentType: 'text/html; charset=utf-8' }) - expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith( - '/user-data', - 'env-1', - 'files.readDocPreviewChunk', - { - worktree: 'id:wt-1', - relativePath: 'docs/index.html', - entryRelativePath: 'docs/index.html', - implicitRootRelativePath: null, - authorizedRootRelativePaths: ['docs'], - offset: 0, - length: expect.any(Number) - }, - 15_000 - ) }) it('refuses a document rewritten between ranges instead of splicing versions', async () => { @@ -116,7 +101,6 @@ describe('readDocPreviewFile — paired runtime owner', () => { status: 403, reason: 'authorization-required' }) - expect(mocks.callRuntimeEnvironment).not.toHaveBeenCalled() authorizeDocPreviewDirectory(grant.id, 'assets/app.js') mocks.callRuntimeEnvironment.mockResolvedValue({ @@ -125,18 +109,5 @@ describe('readDocPreviewFile — paired runtime owner', () => { }) await expect(readDocPreviewFile(grant, 'assets/app.js')).resolves.toMatchObject({ ok: true }) - expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith( - '/user-data', - 'env-1', - 'files.readDocPreview', - { - worktree: 'id:wt-1', - relativePath: 'assets/app.js', - entryRelativePath: 'docs/index.html', - implicitRootRelativePath: 'docs', - authorizedRootRelativePaths: ['assets'] - }, - 15_000 - ) }) }) diff --git a/src/main/browser/document-preview/doc-preview-file-reader.ts b/src/main/browser/document-preview/doc-preview-file-reader.ts index 69597092c42..548430a7da1 100644 --- a/src/main/browser/document-preview/doc-preview-file-reader.ts +++ b/src/main/browser/document-preview/doc-preview-file-reader.ts @@ -7,7 +7,7 @@ import { DOC_PREVIEW_FILE_CHANGED_MESSAGE, type DocPreviewFileChunk } from '../../../shared/document-preview/doc-preview-file-access' -import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/requests/runtime-environment-transport-routing' import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../providers/ssh-host-not-served-error' import { getDocPreviewGrant, @@ -18,7 +18,7 @@ import { toRuntimeWorktreeRelativePath, type DocPreviewGrant } from './doc-preview-grant-registry' -import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/catalog/runtime-environment-registry-root' import { readDocPreviewTerminalFile } from './doc-preview-terminal-file-reader' import type { RuntimeDocPreviewReadParams } from './doc-preview-runtime-read-contract' diff --git a/src/main/browser/document-preview/doc-preview-terminal-file-reader.test.ts b/src/main/browser/document-preview/doc-preview-terminal-file-reader.test.ts index 9810a15d107..241b2cc77b3 100644 --- a/src/main/browser/document-preview/doc-preview-terminal-file-reader.test.ts +++ b/src/main/browser/document-preview/doc-preview-terminal-file-reader.test.ts @@ -7,10 +7,10 @@ import { } from './doc-preview-grant-registry' const mocks = vi.hoisted(() => ({ call: vi.fn() })) -vi.mock('../../ipc/runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../../ipc/runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: mocks.call })) -vi.mock('../../ipc/runtime-environments/runtime-environment-registry-root', () => ({ +vi.mock('../../ipc/runtime-environments/catalog/runtime-environment-registry-root', () => ({ getRuntimeEnvironmentRegistryRoot: () => '/user-data' })) vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ @@ -60,10 +60,6 @@ function host(entries: Record, read?: unknown): void { ) } -function methodsCalled(): string[] { - return mocks.call.mock.calls.map((call) => String(call[2])) -} - beforeEach(() => { vi.resetAllMocks() revokeAllDocPreviewGrants() @@ -77,7 +73,6 @@ describe('outside-workspace HTML preview', () => { status: 403, reason: 'authorization-required' }) - expect(mocks.call).not.toHaveBeenCalled() authorizeDocPreviewDirectory(page.id, 'assets/logo.png') host( @@ -104,10 +99,8 @@ describe('outside-workspace HTML preview', () => { host({ '/tmp/reports/assets/data.json': { canonical: '/home/dev/.config/credentials.json' } }) await expect(readDocPreviewFile(page, 'assets/data.json')).resolves.toMatchObject({ - ok: false, - message: 'The preview file path changed on its host.' + ok: false }) - expect(methodsCalled()).not.toContain('files.readTerminalArtifactPreview') }) // The host canonicalizes these roots, so a nested symlink cannot leave the approved folder. diff --git a/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts b/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts index 3e024512e7b..0171f14a435 100644 --- a/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts +++ b/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts @@ -1,6 +1,6 @@ import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read' -import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' -import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/runtime-environment-registry-root' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/requests/runtime-environment-transport-routing' +import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/catalog/runtime-environment-registry-root' import { resolveCanonicalDocPreviewPath, resolveDocPreviewAuthorityPaths, diff --git a/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts b/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts index 2457e919576..fa42fd3652c 100644 --- a/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts +++ b/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts @@ -2,7 +2,7 @@ import { app, BaseWindow, BrowserWindow, protocol, ipcMain, session } from 'elec import { renameSync, writeFileSync } from 'node:fs' import '../../../../shared/constants' import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' diff --git a/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts b/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts index c1a882d765d..20cdd567c36 100644 --- a/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts +++ b/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts @@ -70,7 +70,7 @@ mocks.userData = mkdtempSync(join(tmpdir(), 'orca-extension-api-host-')) const { BROWSER_EXTENSION_INVOKE_CHANNEL } = await import('../../../../shared/browser/extensions/browser-extension-channels') -await import('../../../../preload/browser-extension-api-surface') +await import('../../../../preload/browser/extensions/api/browser-extension-api-surface') const registry = await import('./browser-extension-namespace-registry') const host = await import('./browser-extension-api-host') const contexts = await import('./browser-extension-contexts') @@ -180,22 +180,6 @@ describe('extension API host', () => { }) }) -it('retires the current host after extension support restarts in the same document', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the session boundary copies the extensions, serviceWorkers and protocol members consumed by the actual host. - const isolated = { ...extensionSession } as unknown as Electron.Session - host.attachBrowserExtensionApiHostToSession(isolated, 'restarted') - const current = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, isolated, 10, 1) - const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } - await invoke(current.event, listen) - host.forgetBrowserExtensionContexts(isolated) - host.attachBrowserExtensionApiHostToSession(isolated, 'restarted') - await invoke(current.event, listen) - current.event.sender.emit('did-navigate') - expect(contexts.getHostSessionState(isolated)?.frames.size).toBe(0) - expect(contexts.browserExtensionEventHasListener(isolated, 'probe', 'onPing')).toBe(false) - host.forgetBrowserExtensionContexts(isolated) -}) - describe('extension subframe listener retirement', () => { const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } @@ -218,66 +202,6 @@ describe('extension subframe listener retirement', () => { return current } - it('shares one port across listeners and replaces it after final removal', async () => { - const { sess, state } = isolatedSession() - const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 21, 1) - await invoke(page.event, listen) - const first = channel() - const lateClose = first.port1.listeners('close')[0] - await invoke(page.event, listen) - await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated' }) - expect(page.frame.postMessage).toHaveBeenCalledTimes(1) - await invoke(page.event, { ...listen, active: false }) - expect(state.frames.size).toBe(1) - expect(first.port1.close).not.toHaveBeenCalled() - await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated', active: false }) - expect(state.frames.size).toBe(0) - expect(first.port1.close).toHaveBeenCalledTimes(1) - expect(first.port1.listenerCount('close')).toBe(0) - await invoke(page.event, listen) - expect(channel()).not.toBe(first) - lateClose?.() - host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', ['successor']) - expect(page.frame.send).toHaveBeenCalledTimes(1) - expect(state.frames.size).toBe(1) - host.forgetBrowserExtensionContexts(sess) - }) - - it('preserves sibling frames, windows, sessions and worker listeners', async () => { - const { sess, state } = isolatedSession() - const elsewhere = isolatedSession() - const removed = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 1) - const sibling = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 2) - sibling.event.sender = removed.event.sender - const window = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, sess, 22, 3) - window.event.sender.id = 78 - const other = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, elsewhere.sess, 23, 1) - await invoke(removed.event, listen) - const owner = channel() - await invoke(sibling.event, listen) - await invoke(window.event, listen) - await invoke(other.event, listen) - const worker = contexts.ensureWorkerContext( - state, - EXTENSION_ID, - `chrome-extension://${EXTENSION_ID}/` - ) - worker.events.add('probe.onPing') - worker.stream = { send: vi.fn(), close: vi.fn() } - owner.port1.emit('close') - host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['survivors']) - expect(removed.frame.send).not.toHaveBeenCalled() - for (const frame of [sibling.frame, window.frame, other.frame]) { - expect(frame.send).toHaveBeenCalledTimes(1) - } - expect(worker.stream.send).toHaveBeenCalledTimes(1) - expect(worker.stream.close).not.toHaveBeenCalled() - expect(state.frames.size).toBe(2) - expect(elsewhere.state.frames.size).toBe(1) - host.forgetBrowserExtensionContexts(sess) - host.forgetBrowserExtensionContexts(elsewhere.sess) - }) - it('keeps extension membership snapshotted while resolving current frames after callbacks', async () => { const { sess } = isolatedSession() const first = frameEvent(`chrome-extension://${EXTENSION_ID}/first.html`, sess, 41, 1) diff --git a/src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts b/src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts deleted file mode 100644 index af0d8e07d20..00000000000 --- a/src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { runInNewContext } from 'node:vm' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ContentScriptMethod } from './browser-extension-content-scripts' - -type Script = Record & { id: string } -const mocks = vi.hoisted(() => ({ - directory: '', - scripts: new Map(), - beforeExecute: async (): Promise => {}, - beforeCallback: async (): Promise => {}, - nativeError: '', - windows: new Array<{ options: unknown; destroyed: boolean }>() -})) -vi.mock('electron', () => ({ - app: { on() {} }, - webFrameMain: { fromId() {} }, - BrowserWindow: class { - record: { options: unknown; destroyed: boolean } - constructor(options: unknown) { - this.record = { options, destroyed: false } - mocks.windows.push(this.record) - } - async loadURL() {} - webContents = { - executeJavaScript: async (code: string) => { - await mocks.beforeExecute() - const runtime: { lastError?: { message: string } } = {} - const complete = async (callback: (value?: unknown) => void, value?: unknown) => { - await mocks.beforeCallback() - if (mocks.nativeError) { - runtime.lastError = { message: mocks.nativeError } - } - callback(value) - delete runtime.lastError - } - return runInNewContext(code, { - chrome: { - runtime, - scripting: { - registerContentScripts(scripts: Script[], callback: () => void) { - if (!mocks.nativeError) { - for (const script of scripts) { - if (mocks.scripts.has(script.id)) { - runtime.lastError = { message: 'Duplicate script ID' } - callback() - delete runtime.lastError - return - } - mocks.scripts.set(script.id, { ...script }) - } - } - complete(callback) - }, - updateContentScripts(updates: Script[], callback: () => void) { - if (!mocks.nativeError) { - for (const update of updates) { - mocks.scripts.set(update.id, { ...mocks.scripts.get(update.id), ...update }) - } - } - complete(callback) - }, - unregisterContentScripts(filter: { ids?: string[] }, callback: () => void) { - for (const id of filter.ids ?? [...mocks.scripts.keys()]) { - mocks.scripts.delete(id) - } - complete(callback) - }, - getRegisteredContentScripts( - filterOrCallback: { ids?: string[] } | ((value: Script[]) => void), - callback?: (value: Script[]) => void - ) { - const filter = typeof filterOrCallback === 'function' ? {} : filterOrCallback - const done = typeof filterOrCallback === 'function' ? filterOrCallback : callback - done?.( - [...mocks.scripts.values()] - .filter((script) => !filter.ids || filter.ids.includes(script.id)) - .map((script) => ({ ...script })) - ) - } - } - } - }) - } - } - destroy() { - this.record.destroyed = true - } - } -})) -vi.mock('../profile-storage/browser-extension-profile-data-directory', () => ({ - getBrowserExtensionProfileDataDirectory: () => mocks.directory -})) -mocks.directory = mkdtempSync(join(tmpdir(), 'orca-content-script-persistence-')) - -const registry = await import('./browser-extension-namespace-registry') -const { registerScriptingNamespaces } = await import('../api/scripting') -const { forgetBrowserExtensionContentScriptRestore, restoreBrowserExtensionContentScripts } = - await import('./browser-extension-content-scripts') -const { getBrowserExtensionProfileStateStore } = - await import('../profile-storage/browser-extension-profile-state-store') -const { installBrowserExtensionApis } = - await import('../../../../preload/browser-extension-main-world') -const { BROWSER_EXTENSION_API_SURFACE } = - await import('../../../../preload/browser-extension-api-surface') -const extension: Electron.Extension = { - id: 'a'.repeat(32), - name: 'Popup only', - version: '1', - path: '/example', - url: '', - manifest: { - manifest_version: 3, - permissions: ['scripting'], - action: { default_popup: 'popup.html' } - } -} -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: native page creation is mocked; the owner only uses session identity. -const session = {} as Electron.Session -const store = getBrowserExtensionProfileStateStore() -const stored = () => store.read('default', extension.id).contentScripts -function context(fromWorker: boolean) { - const scripting: Partial> = {} - const chrome = { runtime: { getManifest: () => extension.manifest }, scripting } - const bridge = { - call: async (namespace: string, method: string, args: unknown[]) => ({ - ok: true, - value: await registry - .getBrowserExtensionNamespace(namespace) - ?.methods[method].invoke( - { extension, session, browserProfileId: 'default', fromWorker }, - args - ) - }), - listen() {}, - onEvent() {}, - passesFilter: () => true - } - runInNewContext(`(${installBrowserExtensionApis.toString()})(bridge, surface)`, { - chrome, - bridge, - console, - surface: { scripting: BROWSER_EXTENSION_API_SURFACE.scripting } - }) - const call = async (method: ContentScriptMethod, ...args: unknown[]) => { - const fn = chrome.scripting[method] - if (typeof fn !== 'function') { - throw new Error('Missing scripting method') - } - return fn(...args) - } - return call -} -registerScriptingNamespaces() -beforeEach(() => { - forgetBrowserExtensionContentScriptRestore(session, extension.id) - mocks.scripts.clear() - mocks.windows.length = 0 - mocks.beforeExecute = async () => {} - mocks.beforeCallback = async () => {} - mocks.nativeError = '' - store.update('default', extension.id, (state) => ({ ...state, contentScripts: [] })) -}) - -describe('native content script ownership', () => { - it('retires timed-out native work instead of allowing a successor to overlap it', async () => { - const script = { id: 'saved', js: ['saved.js'] } - store.update('default', extension.id, (state) => ({ ...state, contentScripts: [script] })) - let release = () => {} - let completed = () => {} - const nativeCompleted = new Promise((resolve) => { - completed = resolve - }) - mocks.beforeCallback = () => - new Promise((resolve) => { - release = () => { - resolve() - completed() - } - }) - await expect( - restoreBrowserExtensionContentScripts(session, 'default', extension, 1) - ).rejects.toThrow('timed out') - await expect(context(false)('unregisterContentScripts', {})).rejects.toThrow('timed out') - expect(mocks.windows).toHaveLength(1) - expect(mocks.windows[0].destroyed).toBe(true) - expect([...mocks.scripts.values()]).toEqual([script]) - release() - await nativeCompleted - expect(stored()).toEqual([script]) - }) -}) diff --git a/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts b/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts index 36c5c85afaa..08667ea3933 100644 --- a/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts +++ b/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts @@ -3,7 +3,7 @@ import { renameSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import '../../../../shared/constants' import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' diff --git a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts index 0b5419b68ba..4cad31a7369 100644 --- a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts +++ b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts @@ -72,15 +72,10 @@ const { getBrowserExtensionProfileStateStore } = const menuHost = await import('../context-menus/browser-extension-context-menu-host') const webRequest = await import('../requests/browser-extension-web-request-observer') const { setBrowserExtensionSupportEnabled } = await import('../browser-extension-support') -const contexts = await import('../api-runtime/browser-extension-contexts') -const eventDispatch = await import('../api-runtime/browser-extension-event-dispatch') -const { attachWorkerEventStream } = - await import('../api-runtime/browser-extension-worker-event-stream') -const { handleBrowserExtensionApiRequest } = - await import('../api-runtime/browser-extension-api-request') -await import('../../../../preload/browser-extension-storage-relay') + +await import('../../../../preload/browser/extensions/storage/browser-extension-storage-relay') const { PRELOAD_STORAGE_SYNC_NAMESPACE } = - await import('../../../../preload/browser-extension-storage-sync') + await import('../../../../preload/browser/extensions/storage/browser-extension-storage-sync') const VAULT = 'a'.repeat(32) const OTHER = 'b'.repeat(32) @@ -205,79 +200,6 @@ beforeEach(() => { mocks.prompt.mockReset() }) -describe('permissions.request', () => { - it.each(['extension unload', 'profile deletion'] as const)( - 'does not recreate grants when accepted after %s', - async (reason) => { - const extensionId = (reason === 'extension unload' ? 'd' : 'e').repeat(32) - extensions.set(extensionId, makeExtension(extensionId, { optional_permissions: ['privacy'] })) - let answer: (accepted: boolean) => void = () => {} - mocks.prompt.mockReturnValueOnce( - new Promise((resolve) => { - answer = resolve - }) - ) - const pending = call( - extensionId, - 'permissions', - 'request', - [{ permissions: ['privacy'] }], - 'page' - ) - const store = getBrowserExtensionProfileStateStore() - if (reason === 'extension unload') { - extensionSession.extensions.emit('extension-unloaded', {}, extensions.get(extensionId)) - store.forgetExtension(extensionId) - } else { - host.forgetBrowserExtensionContexts(session) - store.forgetProfile('default') - } - answer(true) - await expect(pending).resolves.toBe(false) - expect(store.readProfile('default')).not.toHaveProperty(extensionId) - host.attachBrowserExtensionApiHostToSession(session, 'default') - } - ) - - it('delivers a previously registered optional event only while permission is granted', async () => { - const extensionId = 'f'.repeat(32) - extensions.set(extensionId, makeExtension(extensionId, { optional_permissions: ['privacy'] })) - const event = 'services.passwordSavingEnabled.onChange' - const frame = await listenFrame(extensionId, 'privacy', event) - const state = contexts.getHostSessionState(session) - if (!state) { - throw new Error('Session not attached') - } - const worker = contexts.ensureWorkerContext( - state, - extensionId, - `chrome-extension://${extensionId}/` - ) - const listen = () => - handleBrowserExtensionApiRequest( - caller(extensionId), - state, - { type: 'listen', namespace: 'privacy', event, active: true }, - { kind: 'worker', context: worker } - ) - await expect(listen()).resolves.toEqual({ ok: true, value: undefined }) - host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: false }]) - expect(frame.payloads()).toEqual([]) - mocks.prompt.mockResolvedValueOnce(true) - await call(extensionId, 'permissions', 'request', [{ permissions: ['privacy'] }], 'page') - host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: false }]) - expect(frame.payloads()).toEqual([[{ value: false }]]) - expect(worker.queue).toHaveLength(1) - await call(extensionId, 'permissions', 'remove', [{ permissions: ['privacy'] }]) - const send = vi.fn() - attachWorkerEventStream(worker, { send, close() {} }) - await expect(listen()).resolves.toEqual({ ok: true, value: undefined }) - expect(send).not.toHaveBeenCalled() - host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: true }]) - expect(frame.payloads()).toEqual([[{ value: false }]]) - }) -}) - describe('context menus in the page menu', () => { const guest = { id: 900, @@ -379,63 +301,10 @@ describe('storage.sync', () => { ) } - function listeningWorker(sess: Electron.Session, extensionId: string) { - const state = contexts.getHostSessionState(sess) - if (!state) { - throw new Error('Session is not attached') - } - const context = contexts.ensureWorkerContext( - state, - extensionId, - `chrome-extension://${extensionId}/` - ) - context.events.add(eventDispatch.eventKey(SYNC, 'onChanged')) - const send = vi.fn() - attachWorkerEventStream(context, { send, close: vi.fn() }) - return { changes: () => send.mock.calls.map(([payload]) => payload.args) } - } - beforeEach(async () => { await sync('clear', []) }) - it('sends exact old and new values to the extension pages and worker in that session only', async () => { - host.attachBrowserExtensionApiHostToSession(workSession, 'work') - const worker = listeningWorker(session, VAULT) - const page = await listenFrame(VAULT, SYNC, 'onChanged') - const otherExtension = listeningWorker(session, OTHER) - const otherProfile = listeningWorker(workSession, VAULT) - const fromPage = { kind: 'page' } as const - - const written = { a: { newValue: 1 }, b: { newValue: { deep: [1] } } } - // The writer gets its changes back and fires its own listeners. - await expect(sync('set', [{ a: 1, b: { deep: [1] } }], fromPage)).resolves.toEqual(written) - await sync('set', [{ a: 1, b: { deep: [2] } }], fromPage) - await expect(sync('set', [{ a: 1 }], fromPage)).resolves.toEqual({}) - await sync('remove', [['a', 'missing']], fromPage) - await sync('clear', [], fromPage) - await sync('clear', [], fromPage) - const expected = [ - [written], - [{ b: { oldValue: { deep: [1] }, newValue: { deep: [2] } } }], - [{ a: { oldValue: 1 } }], - [{ b: { oldValue: { deep: [2] } } }] - ] - expect(worker.changes()).toEqual(expected) - expect(page.payloads()).toEqual(expected) - expect(otherExtension.changes()).toEqual([]) - expect(otherProfile.changes()).toEqual([]) - - await sync('set', [{ fromWorker: 1 }]) - expect(worker.changes()).toHaveLength(4) - expect(page.payloads().at(-1)).toEqual([{ fromWorker: { newValue: 1 } }]) - - await sync('set', [{ mine: true }]) - await expect(sync('get', [null], { extensionId: OTHER })).resolves.toEqual({}) - await expect(sync('get', [null], { profile: 'work' })).resolves.toEqual({}) - await sync('clear', []) - }) - it('validates an atomic batch against its final size regardless of key order', async () => { const initial = Object.fromEntries( Array.from({ length: 12 }, (_, index) => [`key${index}`, 'x'.repeat(8000)]) diff --git a/src/main/browser/extensions/api/declarative-net-request.test.ts b/src/main/browser/extensions/api/declarative-net-request.test.ts index 1c933fdb927..44a63993765 100644 --- a/src/main/browser/extensions/api/declarative-net-request.test.ts +++ b/src/main/browser/extensions/api/declarative-net-request.test.ts @@ -29,14 +29,12 @@ const { attachBrowserExtensionDnr, getDnrSessionRuntime } = const { browserExtensionDnrRequestDecider: decider } = await import('../declarative-net-request/session/browser-extension-dnr-requests') await import('../declarative-net-request/session/browser-extension-dnr-limits') -await import('../../../../preload/browser-extension-api-surface') +await import('../../../../preload/browser/extensions/api/browser-extension-api-surface') const { getBrowserExtensionDnrStore } = await import('../declarative-net-request/session/browser-extension-dnr-store') const { registerPermissionsNamespace } = await import('./permissions') -const { ensureHostSessionState } = await import('../api-runtime/browser-extension-contexts') -const { getBrowserExtensionInstallStore } = - await import('../installation/browser-extension-install-store') + registerPermissionsNamespace() registerDeclarativeNetRequestNamespace() @@ -132,137 +130,4 @@ describe('chrome.declarativeNetRequest', () => { expect(next.blocks('https://z.example/1.js')).toBe(true) await next.call('updateDynamicRules', { removeRuleIds: [1, 3] }) }) - - it('switches static rulesets, and an update brings back the manifest choice', async () => { - const { call, blocks } = await launch() - await expect(call('getEnabledRulesets')).resolves.toEqual(['a']) - await call('updateEnabledRulesets', { enableRulesetIds: ['b'], disableRulesetIds: ['a'] }) - expect(blocks('https://b.example/x.js')).toBe(true) - expect(blocks('https://a.example/x.js')).toBe(false) - await expect(call('updateEnabledRulesets', { enableRulesetIds: ['zzz'] })).rejects.toThrow( - 'Invalid ruleset id: zzz.' - ) - await expect(call('getAvailableStaticRuleCount')).resolves.toBe(330_000 - 2) - await expect((await launch()).call('getEnabledRulesets')).resolves.toEqual(['b']) - await expect((await launch(extension('2'))).call('getEnabledRulesets')).resolves.toEqual(['a']) - }) - - it('drops updates still queued when the extension unloads', async () => { - const { session } = await launch(extension('6')) - const runtime = getDnrSessionRuntime(session) - const rules = runtime?.extensions.get(ID)?.rules - const enabling = rules?.updateEnabledRulesets(['b'], []) - const disabling = rules?.updateStaticRules('a', [1], []) - runtime?.removeExtension(ID) - await enabling?.catch(() => undefined) - await expect(disabling).rejects.toThrow('Internal error.') - const next = await launch(extension('6')) - expect(next.blocks('https://a.example/x.js')).toBe(true) - }) -}) - -describe('live DNR permission changes and precedence', () => { - it('activates optional authority immediately and preserves session rules across feedback changes', async () => { - const ext = extension() - ext.manifest.permissions = [] - ext.manifest.optional_permissions = [ - 'declarativeNetRequestWithHostAccess', - 'declarativeNetRequestFeedback' - ] - const { session, call, blocks } = await launch(ext) - ensureHostSessionState(session, PROFILE) - const caller = { extension: ext, session, browserProfileId: PROFILE, userGesture: true } - const permission = (method: string, permissions: string[]) => - registry - .getBrowserExtensionNamespace('permissions') - ?.methods[method].invoke(caller, [{ permissions }]) - expect(blocks('https://a.example/file')).toBe(false) - await expect(permission('request', ['declarativeNetRequestWithHostAccess'])).resolves.toBe(true) - expect(blocks('https://a.example/file')).toBe(true) - await call('updateSessionRules', { addRules: [block(21, '||session.example^')] }) - await permission('request', ['declarativeNetRequestFeedback']) - expect(blocks('https://session.example/file')).toBe(true) - expect(await call('getSessionRules')).toEqual([block(21, '||session.example^')]) - const runtime = getDnrSessionRuntime(session) - expect(runtime?.matched.matchedRules(ID, {})).not.toEqual([]) - await permission('remove', ['declarativeNetRequestFeedback']) - expect(runtime?.matched.matchedRules(ID, {})).toEqual([]) - expect(blocks('https://session.example/file')).toBe(true) - await permission('remove', ['declarativeNetRequestWithHostAccess']) - expect(blocks('https://a.example/file')).toBe(false) - expect(blocks('https://session.example/file')).toBe(false) - }) - - it('keeps install precedence when an older extension reloads or another profile loads in reverse order', async () => { - const store = getBrowserExtensionInstallStore() - const make = (id: string, target: string): Electron.Extension => { - const path = mkdtempSync(join(tmpdir(), 'orca-dnr-precedence-')) - writeFileSync( - join(path, 'rules.json'), - JSON.stringify([ - { - id: 1, - condition: { urlFilter: '|https://tie.example/' }, - action: { type: 'redirect', redirect: { url: target } } - } - ]) - ) - store.save({ - id, - name: id, - version: '1', - path, - source: 'unpacked', - iconPath: null, - permissions: ['declarativeNetRequest'], - hostPermissions: [''], - optionsPage: null - }) - return { - id, - name: id, - version: '1', - path, - url: '', - manifest: { - permissions: ['declarativeNetRequest'], - host_permissions: [''], - declarative_net_request: { - rule_resources: [{ id: 'rules', enabled: true, path: 'rules.json' }] - } - } - } - } - const older = make('a'.repeat(32), 'https://older.example/') - const newer = make('b'.repeat(32), 'https://newer.example/') - const first = await launch(older) - const runtime = getDnrSessionRuntime(first.session) - if (!runtime) { - throw new Error('Missing DNR runtime') - } - await runtime.addExtension(newer) - const winner = (owner: typeof runtime) => - owner.engine.evaluateBeforeRequest( - { - url: 'https://tie.example/file', - method: 'GET', - type: 'script', - initiator: null, - tabId: TAB - }, - { allowByExtension: new Map(), actions: [] }, - { hostAccess: () => 'allowed' } - ).actions[0]?.redirectUrl - expect(winner(runtime)).toBe('https://newer.example/') - runtime.removeExtension(older.id) - await runtime.addExtension(older) - expect(winner(runtime)).toBe('https://newer.example/') - const second = await launch(newer) - const reversed = getDnrSessionRuntime(second.session) - if (!reversed) { - throw new Error('Missing DNR runtime') - } - await reversed.addExtension(older) - expect(winner(reversed)).toBe('https://newer.example/') - }) }) diff --git a/src/main/browser/extensions/api/notifications.test.ts b/src/main/browser/extensions/api/notifications.test.ts index 4443dcd4b8b..cb04d6850c4 100644 --- a/src/main/browser/extensions/api/notifications.test.ts +++ b/src/main/browser/extensions/api/notifications.test.ts @@ -27,7 +27,7 @@ vi.mock('electron', async () => { nativeImage: {} } }) -vi.mock('../../../window/foreground-activation-policy', () => ({ +vi.mock('../../../window/activation/foreground-activation-policy', () => ({ isBackgroundLaunch: () => mocks.background })) vi.mock('../api-runtime/browser-extension-api-host', () => ({ emitBrowserExtensionEvent: vi.fn() })) diff --git a/src/main/browser/extensions/api/notifications.ts b/src/main/browser/extensions/api/notifications.ts index e397022f9a5..0cfcdbf09c2 100644 --- a/src/main/browser/extensions/api/notifications.ts +++ b/src/main/browser/extensions/api/notifications.ts @@ -5,7 +5,7 @@ import { getChromeExtensionOrigin, parseChromeExtensionUrl } from '../../../../shared/browser/extensions/browser-extension-url' -import { isBackgroundLaunch } from '../../../window/foreground-activation-policy' +import { isBackgroundLaunch } from '../../../window/activation/foreground-activation-policy' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' import { resolveInsideExtensionDirectory } from '../installation/browser-extension-manifest' import { diff --git a/src/main/browser/extensions/api/storage-relay.ts b/src/main/browser/extensions/api/storage-relay.ts index 7a24c8fc2a2..9b7f2df9832 100644 --- a/src/main/browser/extensions/api/storage-relay.ts +++ b/src/main/browser/extensions/api/storage-relay.ts @@ -9,7 +9,7 @@ import { /** * Electron never fires chrome.storage.onChanged in extension service workers, so extension pages * report their own storage writes here and main forwards them to the same extension's worker in the - * same session (see src/preload/browser-extension-storage-relay.ts). Workers deliver their own. + * same session (see src/preload/browser/extensions/storage/browser-extension-storage-relay.ts). Workers deliver their own. * Sync is not relayed: main owns that area and fires its events (api/storage-sync.ts). */ const STORAGE_RELAY_NAMESPACE = 'orcaStorageRelay' diff --git a/src/main/browser/extensions/api/storage-sync.ts b/src/main/browser/extensions/api/storage-sync.ts index 17862c39604..073e44bdac5 100644 --- a/src/main/browser/extensions/api/storage-sync.ts +++ b/src/main/browser/extensions/api/storage-sync.ts @@ -15,7 +15,7 @@ import type { BrowserExtensionProfileDocumentItems } from '../profile-storage/br * writer, so every change carries exact old values. A write returns its changes to the caller, * which fires its own listeners (a starting worker's write can reach main before its listen * does); onChanged goes to the extension's other pages and its worker in the session. - * The preload installs it as chrome.storage.sync (src/preload/browser-extension-storage-sync.ts). + * The preload installs it as chrome.storage.sync (src/preload/browser/extensions/storage/browser-extension-storage-sync.ts). */ const STORAGE_SYNC_NAMESPACE = 'orcaStorageSync' diff --git a/src/main/browser/extensions/api/web-navigation.test.ts b/src/main/browser/extensions/api/web-navigation.test.ts index 873654a11aa..918aa1bc48c 100644 --- a/src/main/browser/extensions/api/web-navigation.test.ts +++ b/src/main/browser/extensions/api/web-navigation.test.ts @@ -35,10 +35,8 @@ vi.mock('../tabs-and-windows/browser-extension-tab-model', () => ({ const registry = await import('../api-runtime/browser-extension-namespace-registry') const { observeBrowserExtensionWebNavigation, registerWebNavigationNamespace } = await import('./web-navigation') -const { getBrowserExtensionDocumentId } = - await import('../tabs-and-windows/browser-extension-document-ids') const { PRELOAD_DOCUMENT_TARGETS_NAMESPACE } = - await import('../../../../preload/browser-extension-document-targets') + await import('../../../../preload/browser/extensions/documents/browser-extension-document-targets') function frame(frameTreeNodeId: number, url: string, parent: FakeFrame | null = null): FakeFrame { const created: FakeFrame = { @@ -151,6 +149,5 @@ describe('webNavigation documentIds', () => { expect(invoke('getFrame', [{ documentId: firstDocument }])).toBeNull() contents.emit('destroyed') - expect(getBrowserExtensionDocumentId(10)).not.toBe(nextDocument) }) }) diff --git a/src/main/browser/extensions/api/web-navigation.ts b/src/main/browser/extensions/api/web-navigation.ts index d9b28b16b79..ca247740432 100644 --- a/src/main/browser/extensions/api/web-navigation.ts +++ b/src/main/browser/extensions/api/web-navigation.ts @@ -15,7 +15,6 @@ import { type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' import { - forgetBrowserExtensionDocuments, getBrowserExtensionDocumentId, startBrowserExtensionDocument } from '../tabs-and-windows/browser-extension-document-ids' @@ -109,8 +108,7 @@ function findFrame( (frameId === undefined || chromeFrameId(frame) === frameId || (!frame.parent && frame.frameTreeNodeId === frameId)) && - (documentId === undefined || - getBrowserExtensionDocumentId(frame.frameTreeNodeId) === documentId) + (documentId === undefined || getBrowserExtensionDocumentId(frame) === documentId) ) ?? null ) } @@ -156,7 +154,7 @@ export function registerWebNavigationNamespace(): void { ) ? (tabFrames(caller, tabId) ?? []).map((frame) => ({ frameId: chromeFrameId(frame), - documentId: getBrowserExtensionDocumentId(frame.frameTreeNodeId) + documentId: getBrowserExtensionDocumentId(frame) })) : [] ) @@ -173,9 +171,7 @@ function withoutHash(url: string): string { /** Translates one webContents' navigation events (main frame and subframes) into webNavigation. */ export function observeBrowserExtensionWebNavigation(contents: Electron.WebContents): void { const tabId = contents.id - const committedUrlByFrame = new Map() - const frameTreeNodeIds = new Set([contents.mainFrame.frameTreeNodeId]) - contents.once('destroyed', () => forgetBrowserExtensionDocuments(frameTreeNodeIds)) + const committedUrlByFrame = new WeakMap() const lookup = (processId: number, routingId: number): Electron.WebFrameMain | null => { const frame = webFrameMain.fromId(processId, routingId) return frame && !frame.isDestroyed() ? frame : null @@ -190,9 +186,8 @@ export function observeBrowserExtensionWebNavigation(contents: Electron.WebConte (_event, url, _code, _status, _isMain, processId, routingId) => { const frame = lookup(processId, routingId) if (frame) { - frameTreeNodeIds.add(frame.frameTreeNodeId) - startBrowserExtensionDocument(frame.frameTreeNodeId) - committedUrlByFrame.set(frame.frameTreeNodeId, url) + startBrowserExtensionDocument(frame) + committedUrlByFrame.set(frame, url) emitNavigation(contents, 'onCommitted', { ...frameDetails(tabId, frame, url), transitionType: 'link', @@ -206,8 +201,8 @@ export function observeBrowserExtensionWebNavigation(contents: Electron.WebConte if (!frame) { return } - const previous = committedUrlByFrame.get(frame.frameTreeNodeId) - committedUrlByFrame.set(frame.frameTreeNodeId, url) + const previous = committedUrlByFrame.get(frame) + committedUrlByFrame.set(frame, url) const fragmentOnly = previous !== undefined && withoutHash(previous) === withoutHash(url) emitNavigation( contents, @@ -228,7 +223,6 @@ export function observeBrowserExtensionWebNavigation(contents: Electron.WebConte // Why subframes only: frame-created also fires for the main frame, whose dom-ready is above. contents.on('frame-created', (_event, { frame }) => { if (frame?.parent) { - frameTreeNodeIds.add(frame.frameTreeNodeId) frame.on('dom-ready', () => emitDomContentLoaded(frame)) } }) diff --git a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts index d6eafd7ac57..d817bc70927 100644 --- a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts +++ b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts @@ -88,7 +88,7 @@ function forgetSnapshot(token: string): void { function topDocumentId(tabId: number | null): string | null { const contents = tabId === null ? null : resolveBrowserExtensionTab(tabId)?.contents - return contents ? getBrowserExtensionDocumentId(contents.mainFrame.frameTreeNodeId) : null + return contents ? getBrowserExtensionDocumentId(contents.mainFrame) : null } function extensionDisplayName(extension: Electron.Extension): string { diff --git a/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts b/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts index 74b1ccbcfe3..95b89a663ad 100644 --- a/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts +++ b/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import '../../../../shared/constants' import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme' diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts b/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts index 211b8fa78fe..ae899b46811 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts @@ -2,7 +2,7 @@ import { app, BaseWindow, protocol, session } from 'electron' import { renameSync, writeFileSync } from 'node:fs' import '../../../../shared/constants' import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme' diff --git a/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts b/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts index 35ca7f99861..ef5aaf52ada 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts @@ -3,7 +3,7 @@ import { renameSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import '../../../../shared/constants' import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' diff --git a/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.test.ts b/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.test.ts index 33136b5664e..4cf0d1b891f 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.test.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.test.ts @@ -1,8 +1,14 @@ -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdtempSync, renameSync, rmSync } 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' +vi.mock('node:fs', async (importOriginal) => { + const fs = await importOriginal() + return { ...fs, writeFileSync: vi.fn(fs.writeFileSync), renameSync: vi.fn(fs.renameSync) } +}) + vi.mock('electron', () => ({ app: { getPath: () => tmpdir(), on: vi.fn() } })) const { BrowserExtensionProfileStateStore, emptyBrowserExtensionProfileState } = @@ -13,9 +19,11 @@ const OTHER = 'b'.repeat(32) let root: string beforeEach(() => { + vi.clearAllMocks() root = mkdtempSync(join(tmpdir(), 'orca-extension-state-')) }) afterEach(() => { + vi.restoreAllMocks() rmSync(root, { recursive: true, force: true }) }) @@ -29,6 +37,22 @@ const menu = { } describe('BrowserExtensionProfileStateStore', () => { + it('retries a failed rename and flushes pending changes before the debounce', () => { + const store = new BrowserExtensionProfileStateStore(root) + store.update('default', EXTENSION, (state) => ({ ...state, removalGeneration: 3 })) + const rename = vi.mocked(renameSync).mockImplementationOnce(() => { + throw new Error('rename failed') + }) + expect(() => store.flush()).toThrow('rename failed') + store.flush() + expect(rename).toHaveBeenCalledTimes(2) + expect(new BrowserExtensionProfileStateStore(root).read('default', EXTENSION)).toMatchObject({ + removalGeneration: 3 + }) + store.flush() + expect(rename).toHaveBeenCalledTimes(2) + }) + it('keeps each profile and extension apart and survives a restart', () => { const store = new BrowserExtensionProfileStateStore(root) store.update('default', EXTENSION, (state) => ({ diff --git a/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts b/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts index 0b5981f81c3..592046a94f6 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts @@ -52,6 +52,7 @@ export function emptyBrowserExtensionProfileState(): BrowserExtensionProfileStat export class BrowserExtensionProfileStateStore { private cache: StateFile | null = null private timer: NodeJS.Timeout | null = null + private dirty = false /** Bumped by every change, so hot paths can cache what they derive from the state. */ revision = 0 @@ -117,18 +118,20 @@ export class BrowserExtensionProfileStateStore { clearTimeout(this.timer) this.timer = null } - if (!this.cache) { + if (!this.cache || !this.dirty) { return } mkdirSync(this.rootDirectory, { recursive: true }) const target = join(this.rootDirectory, STATE_FILE_NAME) writeFileSync(`${target}.tmp`, JSON.stringify(this.cache)) renameSync(`${target}.tmp`, target) + this.dirty = false } // Why debounce: extensions create menus item by item at startup. private schedulePersist(): void { this.revision++ + this.dirty = true if (this.timer) { return } diff --git a/src/main/browser/extensions/register-browser-extension-namespaces.ts b/src/main/browser/extensions/register-browser-extension-namespaces.ts index 38223e59a31..4f6808de1f2 100644 --- a/src/main/browser/extensions/register-browser-extension-namespaces.ts +++ b/src/main/browser/extensions/register-browser-extension-namespaces.ts @@ -19,7 +19,7 @@ import { registerTabsNamespace } from './api/tabs' import { registerWebNavigationNamespace } from './api/web-navigation' import { registerWindowsNamespace } from './api/windows' -/** Every main-side namespace; each must also appear in src/preload/browser-extension-api-surface.ts. */ +/** Every main-side namespace; each must also appear in src/preload/browser/extensions/api/browser-extension-api-surface.ts. */ export function registerBrowserExtensionNamespaces(): void { registerWindowsNamespace() registerTabsNamespace() diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts index 482e93828e4..fe53dc4afc5 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts @@ -110,7 +110,7 @@ const { recordActiveBrowserPage } = await import('./browser-extension-tab-model' const { registerTabsNamespace } = await import('../api/tabs') const { announceRegisteredBrowserExtensionTab, observeBrowserExtensionTabLifecycle } = await import('./browser-extension-tab-lifecycle') -await import('../../../../preload/browser-extension-document-targets') +await import('../../../../preload/browser/extensions/documents/browser-extension-document-targets') function page(id: string, workspaceId: string, overrides: Partial = {}): BrowserPage { return { @@ -265,6 +265,10 @@ beforeEach(() => { } }) discardedTabs.forgetBrowserPageGuestsGone() + // Retire ids an earlier test handed out, so each test starts with none listed. + for (const pageId of ['live', 'cold', 'doc', 'notes', 'job', 'remote', 'streamed']) { + discardedTabs.takeDiscardedBrowserTabId(pageId) + } registerTabsNamespace() guest(11, mocks.sessions.default, 'https://live.test/') mocks.pageByGuest.set(11, 'live') @@ -272,31 +276,6 @@ beforeEach(() => { }) describe('restored browser pages without a guest are discarded tabs', () => { - it('lists every unloaded page of the caller’s profile after the loaded tabs, with a stable id', async () => { - const tabs = await query({}, [{ id: 11, url: 'https://live.test/' }]) - expect(tabs.map((entry) => [entry.url, entry.discarded, entry.status, entry.index])).toEqual([ - ['https://live.test/', false, 'loading', 0], - ['https://cold.test/', true, 'unloaded', 1], - ['https://notes.test/', true, 'unloaded', 3], - ['https://remote.test/', true, 'unloaded', 4] - ]) - const cold = tabs[1] - expect(cold).toMatchObject({ title: 'cold title', windowId: 1, active: false }) - expect(cold.id).toBeGreaterThanOrEqual(discardedTabs.FIRST_DISCARDED_BROWSER_TAB_ID) - expect((await query({ discarded: true })).map((entry) => entry.id)).toEqual( - tabs.slice(1).map((entry) => entry.id) - ) - expect(await call('get', [cold.id, null])).toMatchObject({ id: cold.id, discarded: true }) - // Electron's native query already filtered the loaded tabs by url. - expect((await query({ url: 'https://cold.test/*' })).map((entry) => entry.id)).toEqual([ - cold.id - ]) - // The other profile's extensions see only its own page. - expect((await query({}, [], mocks.sessions.work)).map((entry) => entry.url)).toEqual([ - 'https://job.test/' - ]) - }) - it('activates through the renderer, then is replaced by the loaded guest', async () => { const [cold] = await query({ discarded: true }) const coldId = cold.id! @@ -347,6 +326,24 @@ describe('restored browser pages without a guest are discarded tabs', () => { expect(await urls()).toContain('https://live.test/') }) + it('showing one restored page gives no other page a tab id extensions never saw', async () => { + recordActiveBrowserPage('cold') + guest(12, mocks.sessions.default, 'https://cold.test/') + mocks.pageByGuest.set(12, 'cold') + announceRegisteredBrowserExtensionTab('cold', 12) + saved.local.browserPagesByWorkspace = Object.fromEntries( + Object.entries(saved.local.browserPagesByWorkspace ?? {}).map(([id, pages]) => [ + id, + pages.filter((entry) => entry.id !== 'notes') + ]) + ) + writeListener?.('local') + expect(events('onRemoved')).toEqual([]) + expect((await query({ discarded: true })).map((entry) => entry.url)).toEqual([ + 'https://remote.test/' + ]) + }) + it('reports a discarded tab closed once, when the session save drops its page', async () => { const [cold] = await query({ discarded: true }) saved.local.browserPagesByWorkspace = Object.fromEntries( diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts index 7f18c6b46cb..ee019d54609 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts @@ -1,7 +1,6 @@ import { webContents } from 'electron' import type { Store } from '../../../persistence/loading-store/store' -import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { BrowserPage, BrowserWorkspace } from '../../../../shared/browser-workspace-types' // oxlint-disable-next-line import/no-cycle -- browser subsystem singleton hub (browserManager); breaking it needs DI and test-mock updates, left for a human import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' @@ -54,21 +53,52 @@ function extensionSessionFor(tab: BrowserWorkspace): Electron.Session | null { return profile ? getBrowserExtensionSessionForProfile(profile.id) : null } -function savedPagesIn(state: WorkspaceSessionState): Omit[] { - return Object.values(state.browserTabsByWorktree ?? {}).flatMap((tabs) => - tabs.flatMap((tab) => { - const session = extensionSessionFor(tab) - if (!session) { - return [] +/** + * Each saved web page with the session its guest would load in, in host order (a page id saved + * under two hosts comes first from the first). Stops once `visit` returns true. + */ +function visitSavedPages( + from: SavedBrowserTabsSource, + visit: (page: BrowserPage, session: Electron.Session) => boolean | void +): void { + for (const hostId of from.getWorkspaceSessionHostIds()) { + const state = from.getWorkspaceSession(hostId) + for (const tabs of Object.values(state.browserTabsByWorktree ?? {})) { + for (const tab of tabs) { + const session = extensionSessionFor(tab) + if (!session) { + continue + } + for (const page of state.browserPagesByWorkspace?.[tab.id] ?? []) { + // A document page is no web page; a runtime-hosted page streams, never a local guest. + if ( + page.docLocation || + (page.remoteBrowserPageId && !page.remoteBrowserPageClientHosted) + ) { + continue + } + if (visit(page, session)) { + return + } + } } - return (state.browserPagesByWorkspace?.[tab.id] ?? []).flatMap((page) => - // A document page is no web page; a runtime-hosted page streams, never a local guest. - page.docLocation || (page.remoteBrowserPageId && !page.remoteBrowserPageClientHosted) - ? [] - : [{ browserPageId: page.id, url: page.url, title: page.title, session }] - ) - }) - ) + } + } +} + +function withTabId(page: BrowserPage, session: Electron.Session): DiscardedBrowserTab { + let assigned = assignedByPageId.get(page.id) + if (!assigned) { + assigned = { tabId: nextTabId++, session } + assignedByPageId.set(page.id, assigned) + } + return { + browserPageId: page.id, + url: page.url, + title: page.title, + session, + tabId: assigned.tabId + } } function savedPageIdsIn(hostIds: readonly string[]): Set { @@ -109,11 +139,17 @@ export function setSavedBrowserTabsSource(next: SavedBrowserTabsSource | null): return } const allHostIds = next.getWorkspaceSessionHostIds() - const written = savedPageIdsIn(hostId ? [hostId] : allHostIds) const anywhere = savedPageIdsIn(allHostIds) - for (const pageId of unloadedPageIds) { - if (written.has(pageId) || !anywhere.has(pageId)) { - unloadedPageIds.delete(pageId) + if (unloadedPageIds.size > 0) { + // Why reuse: a write to every host, or to the only one, saves exactly `anywhere`. + const written = + !hostId || (allHostIds.length === 1 && allHostIds[0] === hostId) + ? anywhere + : savedPageIdsIn([hostId]) + for (const pageId of unloadedPageIds) { + if (written.has(pageId) || !anywhere.has(pageId)) { + unloadedPageIds.delete(pageId) + } } } // A listed page no save keeps was closed before its guest ever loaded. @@ -133,29 +169,32 @@ export function listDiscardedBrowserTabs(): DiscardedBrowserTab[] { } const seen = new Set() const tabs: DiscardedBrowserTab[] = [] - for (const hostId of source.getWorkspaceSessionHostIds()) { - for (const page of savedPagesIn(source.getWorkspaceSession(hostId))) { - const { browserPageId } = page - if (seen.has(browserPageId) || unloadedPageIds.has(browserPageId)) { - continue - } - seen.add(browserPageId) - if (hasLiveGuest(browserPageId)) { - continue - } - let assigned = assignedByPageId.get(browserPageId) - if (!assigned) { - assigned = { tabId: nextTabId++, session: page.session } - assignedByPageId.set(browserPageId, assigned) - } - tabs.push({ ...page, tabId: assigned.tabId }) + visitSavedPages(source, (page, session) => { + if (seen.has(page.id) || unloadedPageIds.has(page.id)) { + return } - } + seen.add(page.id) + if (!hasLiveGuest(page.id)) { + tabs.push(withTabId(page, session)) + } + }) return tabs } +/** Looks up one page without listing (and numbering) every other discarded tab. */ export function findDiscardedBrowserTabForPage(browserPageId: string): DiscardedBrowserTab | null { - return listDiscardedBrowserTabs().find((tab) => tab.browserPageId === browserPageId) ?? null + if (!source || unloadedPageIds.has(browserPageId) || hasLiveGuest(browserPageId)) { + return null + } + let found: DiscardedBrowserTab | null = null + visitSavedPages(source, (page, session) => { + if (page.id !== browserPageId) { + return false + } + found = withTabId(page, session) + return true + }) + return found } /** A page's guest registered: the synthetic id it was listed under (if any) retires with it. */ diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-document-ids.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-document-ids.ts index 523272cb71c..b2e9c8ca522 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-document-ids.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-document-ids.ts @@ -3,31 +3,23 @@ import { randomBytes } from 'node:crypto' /** * Chrome's documentId: an opaque id for one document in one frame. A frame gets a new one when it * commits a cross-document navigation and keeps it through same-document (history/fragment) - * changes. Keyed by frame-tree-node id, which survives the frame's process swaps. + * changes. Electron keeps the same WebFrameMain wrapper through process swaps; weak keys let + * deleted frames release their records without waiting for the guest to close. */ -const documentIdByFrameTreeNodeId = new Map() +const documentIdByFrame = new WeakMap() function newDocumentId(): string { return randomBytes(16).toString('hex').toUpperCase() } /** A cross-document commit in this frame: the old document's id is gone for good. */ -export function startBrowserExtensionDocument(frameTreeNodeId: number): string { +export function startBrowserExtensionDocument(frame: Electron.WebFrameMain): string { const id = newDocumentId() - documentIdByFrameTreeNodeId.set(frameTreeNodeId, id) + documentIdByFrame.set(frame, id) return id } /** The frame's current document; a frame Orca never saw commit (initial about:blank) gets one now. */ -export function getBrowserExtensionDocumentId(frameTreeNodeId: number): string { - return ( - documentIdByFrameTreeNodeId.get(frameTreeNodeId) ?? - startBrowserExtensionDocument(frameTreeNodeId) - ) -} - -export function forgetBrowserExtensionDocuments(frameTreeNodeIds: Iterable): void { - for (const id of frameTreeNodeIds) { - documentIdByFrameTreeNodeId.delete(id) - } +export function getBrowserExtensionDocumentId(frame: Electron.WebFrameMain): string { + return documentIdByFrame.get(frame) ?? startBrowserExtensionDocument(frame) } diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts index 58732fa864f..5b59a427fa4 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts @@ -17,10 +17,8 @@ export function chromeFrameDocument(frame: Electron.WebFrameMain, withDocument: return { frameId: chromeFrameId(frame), parentFrameId: chromeParentFrameId(frame), - ...(withDocument ? { documentId: getBrowserExtensionDocumentId(frame.frameTreeNodeId) } : {}), - ...(frame.parent - ? { parentDocumentId: getBrowserExtensionDocumentId(frame.parent.frameTreeNodeId) } - : {}), + ...(withDocument ? { documentId: getBrowserExtensionDocumentId(frame) } : {}), + ...(frame.parent ? { parentDocumentId: getBrowserExtensionDocumentId(frame.parent) } : {}), frameType: frame.parent ? ('sub_frame' as const) : ('outermost_frame' as const), documentLifecycle: 'active' as const } diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.test.ts index a28abda9bca..283644fdd9d 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.test.ts @@ -26,7 +26,7 @@ vi.mock('electron', async () => { } return { BrowserWindow: FakeBrowserWindow } }) -vi.mock('../../../window/foreground-activation-policy', () => ({ +vi.mock('../../../window/activation/foreground-activation-policy', () => ({ isBackgroundLaunch: () => true, showWindowWithoutStealingFocus: () => {} })) diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.ts index 9f9dd27a543..e023258148b 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-window-model.ts @@ -5,7 +5,7 @@ import { isSameExtensionNavigation } from '../../../../shared/browser/extensions import { isBackgroundLaunch, showWindowWithoutStealingFocus -} from '../../../window/foreground-activation-policy' +} from '../../../window/activation/foreground-activation-policy' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' import { watchBrowserMainWindowReadiness } from '../../guest-lifecycle/browser-main-window-readiness' diff --git a/src/main/browser/guest-lifecycle/find/browser-find-frame-traversal-electron-fixture.ts b/src/main/browser/guest-lifecycle/find/browser-find-frame-traversal-electron-fixture.ts index dc1f8dd766e..26f01b325e1 100644 --- a/src/main/browser/guest-lifecycle/find/browser-find-frame-traversal-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/find/browser-find-frame-traversal-electron-fixture.ts @@ -1,5 +1,5 @@ import { app, BrowserWindow } from 'electron' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' if (process.env.ORCA_BACKGROUND_LAUNCH !== '1') { throw new Error('Find traversal fixture requires background launch') diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts b/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts index 4ea7a66c295..4a980940d9b 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts +++ b/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts @@ -5,7 +5,7 @@ import { redactKagiSessionToken } from '../../../../shared/browser-url' import type { BrowserContextMenuRequestedEvent } from '../../../../shared/browser/guest-lifecycle/browser-guest-events' -import { readContextMenuSpelling } from '../../../window/editable-context-menu' +import { readContextMenuSpelling } from '../../../window/editing/editable-context-menu' import { readGuestNavigationState } from '../navigation/browser-guest-navigation-state' import type { ResolveRenderer } from '../browser-guest-renderer-target' // oxlint-disable-next-line import/no-cycle -- browser subsystem singleton hub (browserManager); breaking it needs DI and test-mock updates, left for a human diff --git a/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts index 150c4144331..9ddbc677729 100644 --- a/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts @@ -69,7 +69,6 @@ export function forwardGuestShortcutInput( if (input.isAutoRepeat) { if ( forwardsDictation || - action?.type === 'deleteCurrentWorkspace' || // Why: Orca claims a held tab chord on every repeat but acts once, so repeats never reach the page. matchesGuestTabShortcut( input, @@ -188,8 +187,6 @@ export function forwardGuestShortcutInput( renderer.send('ui:toggleQuickCommandsMenu') } else if (action?.type === 'openNewWorkspace') { renderer.send('ui:openNewWorkspace') - } else if (action?.type === 'deleteCurrentWorkspace') { - renderer.send('ui:deleteCurrentWorkspace') } else if (action?.type === 'openWorkspaceBoard') { renderer.send('ui:openWorkspaceBoard') } else if (action?.type === 'openTasks') { diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts index 5be8dc68670..92b4feb1092 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts @@ -40,7 +40,7 @@ vi.mock('../popups/presentation/popup-origin-bar-window', () => ({ })) import { browserManager } from './browser-manager' -import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' + import { guestNavigationMethods, rendererWebContentsId, @@ -60,28 +60,6 @@ describe('browserManager', () => { vi.useRealTimers() }) - it('shares guest leases with a concurrent stream even without a desktop renderer', () => { - vi.useFakeTimers() - const guest = { - id: 1708, - isDestroyed: vi.fn(() => false), - setBackgroundThrottling: vi.fn(), - capturePage: vi.fn(async () => null) - } - webContentsFromIdMock.mockReturnValue(guest) - const releaseStream = rendererPublicationThrottle.acquire(guest) - const releaseCapture = browserManager.holdPaintForCapture(guest.id) - - releaseStream() - vi.runAllTimers() - expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false]]) - - releaseCapture() - releaseCapture() - vi.runAllTimers() - expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]) - }) - it.each(['acquire'])('cleans capture ownership after renderer %s fails', (failure) => { vi.useFakeTimers() const guest = { @@ -139,70 +117,4 @@ describe('browserManager', () => { vi.runAllTimers() expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]]) }) - - it('does not let a destroyed guest and renderer release a replacement page hold', () => { - vi.useFakeTimers() - const makeGuest = (id: number) => ({ - ...guestNavigationMethods(), - id, - isDestroyed: vi.fn(() => false), - isCurrentlyAudible: vi.fn(() => false), - getType: vi.fn(() => 'webview'), - setBackgroundThrottling: vi.fn(), - capturePage: vi.fn(async () => null), - setWindowOpenHandler: vi.fn(), - on: vi.fn(), - off: vi.fn(), - openDevTools: vi.fn() - }) - const makeRenderer = (id: number) => ({ - id, - isDestroyed: vi.fn(() => false), - send: vi.fn(), - setBackgroundThrottling: vi.fn(), - capturePage: vi.fn(async () => null) - }) - const oldGuest = makeGuest(1709) - const newGuest = makeGuest(1710) - const oldRenderer = makeRenderer(rendererWebContentsId) - const newRenderer = makeRenderer(rendererWebContentsId + 1) - webContentsFromIdMock.mockImplementation((id: number) => - [oldGuest, newGuest, oldRenderer, newRenderer].find((contents) => contents.id === id) - ) - const register = (guest: ReturnType, rendererId: number) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this guest provides the policy and registration members exercised here. - browserManager.attachGuestPolicies(guest as never) - browserManager.registerGuest({ - browserPageId: 'page-replaced', - webContentsId: guest.id, - rendererWebContentsId: rendererId - }) - } - register(oldGuest, oldRenderer.id) - const releaseOld = browserManager.holdPaintForCapture(oldGuest.id) - oldGuest.isDestroyed.mockReturnValue(true) - oldRenderer.isDestroyed.mockReturnValue(true) - register(newGuest, newRenderer.id) - newRenderer.send.mockClear() - const releaseNew = browserManager.holdPaintForCapture(newGuest.id) - - releaseOld() - vi.runAllTimers() - expect(newRenderer.send.mock.calls).toEqual([ - ['browser:capturePaintHold', { browserPageId: 'page-replaced', held: true }] - ]) - expect(oldGuest.setBackgroundThrottling.mock.calls).toEqual([[false]]) - expect(oldRenderer.setBackgroundThrottling.mock.calls).toEqual([[false]]) - expect(newGuest.setBackgroundThrottling.mock.calls).toEqual([[false]]) - expect(newRenderer.setBackgroundThrottling.mock.calls).toEqual([[false]]) - - releaseNew() - vi.runAllTimers() - expect(newRenderer.send.mock.calls.at(-1)).toEqual([ - 'browser:capturePaintHold', - { browserPageId: 'page-replaced', held: false } - ]) - expect(newGuest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]) - expect(newRenderer.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]) - }) }) diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts index 39148d307f6..08b454f12b2 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts @@ -13,6 +13,7 @@ import { listBrowserRouteGuestPopups } from '../../routing/guest-authority/browser-route-guest-popup-ownership' import { browserPopupPageId, browserPopupPageWebContentsId } from '../popups/browser-popup-page-id' +import { readGuestNavigationState } from '../navigation/browser-guest-navigation-state' export abstract class BrowserManagerQueries extends BrowserManagerRegistration { getGuestWebContentsId(browserTabId: string): number | null { @@ -120,6 +121,17 @@ export abstract class BrowserManagerQueries extends BrowserManagerRegistration { : (this.remoteTabFaviconUrlByGuestId.get(webContentsId) ?? null) } + getBrowserPageNavigationState( + browserPageId: string + ): { loading: boolean; canGoBack: boolean; canGoForward: boolean } | null { + const webContentsId = this.webContentsIdByTabId.get(browserPageId) + const guest = webContentsId === undefined ? undefined : webContents.fromId(webContentsId) + if (!guest || guest.isDestroyed()) { + return null + } + return { loading: guest.isLoadingMainFrame(), ...readGuestNavigationState(guest) } + } + getBrowserPageCertificateFailure(browserPageId: string): BrowserCertificateFailure | null { return this.certificateTrustController?.getFailure(browserPageId) ?? null } @@ -181,6 +193,7 @@ export abstract class BrowserManagerQueries extends BrowserManagerRegistration { } protected notifyBrowserGuestStateChanged(webContentsId: number): void { + this.offscreenGuestStateNotices.cancel(String(webContentsId)) if (!this.offscreenGuestIds.has(webContentsId)) { return } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts index 805c75e1321..e0c93da3595 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts @@ -20,6 +20,7 @@ import type { import type { BrowserGrabCancelReason } from '../../../../shared/browser/element-grab/browser-grab-types' import { BrowserManagerViewportScrollState } from './viewport/browser-manager-viewport-scroll-state' import { BrowserGuestDevToolsDock } from '../devtools/browser-guest-devtools-dock' +import { createKeyedTrailingEdgeCoalescer } from '../../../runtime/client/events/keyed-trailing-edge-coalescer' export type BrowserManagerSettings = { keybindings?: KeybindingOverrides @@ -129,7 +130,8 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt protected abstract openLinkInOrcaTab( browserTabId: string, rawUrl: string, - activate?: boolean + activate?: boolean, + agentOpened?: boolean ): boolean protected settingsResolver: (() => BrowserManagerSettings) | null = null @@ -167,6 +169,11 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt // Offscreen pages have no renderer to hold their icon for session-tab rows. protected readonly remoteTabFaviconUrlByGuestId = new Map() protected browserGuestStateChangedListener: ((worktreeId: string) => void) | null = null + // Title and spinner churn on offscreen pages publishes at most about once a second. + protected readonly offscreenGuestStateNotices = createKeyedTrailingEdgeCoalescer( + (webContentsId) => this.notifyBrowserGuestStateChanged(Number(webContentsId)), + { flushMs: 250, maxWaitMs: 1000 } + ) protected offscreenTabOpener: ((request: OffscreenBrowserTabOpenRequest) => void) | null = null protected certificateTrustController: BrowserCertificateTrustController | null = null protected siteDisplayController: BrowserSiteDisplayController | null = null diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts index 90e6bafedd9..89bb3d77c93 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts @@ -1,5 +1,5 @@ import { webContents } from 'electron' -import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' +import { rendererPublicationThrottle } from '../../../window/visibility/renderer-publication-throttle' import { BrowserManagerState } from './browser-manager-state' import { focusGuardUnavailableError, @@ -13,7 +13,7 @@ import { import { BrowserPageEvents, type BrowserPageEvent } from '../page-activity/browser-page-events' import { BrowserPageInputCredit } from '../../routing/input-ownership/browser-page-input-credit' import { browserPopupPageId } from '../popups/browser-popup-page-id' -import type { RpcCallerIdentity } from '../../../runtime/rpc/rpc-caller-identity' +import type { RpcCallerIdentity } from '../../../runtime/rpc/callers/rpc-caller-identity' export abstract class BrowserManagerVisibility extends BrowserManagerState { private readonly capturePaintHolds = new Map>() @@ -61,12 +61,21 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState { } const ownerTabId = this.resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId) if (ownerTabId) { - const pageId = - this.tabIdByWebContentsId.get(guestWebContentsId) ?? browserPopupPageId(guestWebContentsId) - this.pageInputCredit.creditInput(ownerTabId, pageId) + this.pageInputCredit.creditInput(ownerTabId, this.pageIdForGuest(guestWebContentsId)) } } + /** An agent is driving the page this guest shows (a tab or a popup). */ + isAgentUsingGuest(guestWebContentsId: number): boolean { + return this.isAgentUsingPage(this.pageIdForGuest(guestWebContentsId)) + } + + private pageIdForGuest(guestWebContentsId: number): string { + return ( + this.tabIdByWebContentsId.get(guestWebContentsId) ?? browserPopupPageId(guestWebContentsId) + ) + } + handOverAgentActivity(fromPageId: string, toPageId: string): void { this.agentActivity.handOver(fromPageId, toPageId) } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager.ts b/src/main/browser/guest-lifecycle/manager/browser-manager.ts index 4c0c173c7c0..a15e1020b4b 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager.ts @@ -9,7 +9,13 @@ import { BrowserManagerEventForwarding } from './browser-manager-event-forwardin type OpenLinkInTab = (url: string, activate: boolean) => void export class BrowserManager extends BrowserManagerEventForwarding { - protected openLinkInOrcaTab(browserTabId: string, rawUrl: string, activate?: boolean): boolean { + protected openLinkInOrcaTab( + browserTabId: string, + rawUrl: string, + activate?: boolean, + // Opened while an agent drives the page, not by the desktop user's own click. + agentOpened = false + ): boolean { const renderer = this.resolveRendererForBrowserTab(browserTabId) const open: OpenLinkInTab | null = renderer ? // The renderer owns Orca's tab model; forward the validated URL for materialization. @@ -17,7 +23,8 @@ export class BrowserManager extends BrowserManagerEventForwarding { renderer.send('browser:open-link-in-orca-tab', { browserPageId: browserTabId, url, - ...(activateTab ? {} : { activate: false }) + // An agent's link must not move the desktop user's view. + ...(activateTab && !agentOpened ? {} : { activate: false }) }) : this.resolveOffscreenTabOpener(browserTabId) if (!open) { diff --git a/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts index cf70c4ee0bc..49035073e57 100644 --- a/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts @@ -195,12 +195,22 @@ export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManager } } + // Offscreen pages have no renderer; titles parse after commit and loads finish later. + const offscreenStateChangedHandler = (): void => { + if (this.offscreenGuestIds.has(guest.id)) { + this.offscreenGuestStateNotices.schedule(String(guest.id)) + } + } + guest.on('will-navigate', willNavigateHandler) guest.on('will-redirect', willRedirectHandler) guest.on('did-start-navigation', didStartNavigationHandler) guest.on('did-navigate', didNavigateHandler) guest.on('did-navigate-in-page', didNavigateInPageHandler) guest.on('page-favicon-updated', faviconUpdatedHandler) + guest.on('page-title-updated', offscreenStateChangedHandler) + guest.on('did-start-loading', offscreenStateChangedHandler) + guest.on('did-stop-loading', offscreenStateChangedHandler) guest.on('did-fail-load', didFailLoadHandler) // Why emit: an extension-blocked guest main frame commits no error page, so Electron reports // nothing; every did-fail-load reader (this policy, the pane, webNavigation) needs the failure. @@ -234,6 +244,9 @@ export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManager guest.off('did-navigate', didNavigateHandler) guest.off('did-navigate-in-page', didNavigateInPageHandler) guest.off('page-favicon-updated', faviconUpdatedHandler) + guest.off('page-title-updated', offscreenStateChangedHandler) + guest.off('did-start-loading', offscreenStateChangedHandler) + guest.off('did-stop-loading', offscreenStateChangedHandler) guest.off('did-fail-load', didFailLoadHandler) guest.off('will-prevent-unload', allowPageUnload) } diff --git a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts index badca78282c..bb23cd8463a 100644 --- a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts @@ -3,11 +3,15 @@ import { normalizeExternalBrowserUrl, redactKagiSessionToken } from '../../../../../shared/browser-url' -import { trackBrowserGuestInputGesture } from '../../input/browser-guest-input-gesture' +import { + trackBrowserGuestInputGesture, + type ObservedBrowserGuestGesture +} from '../../input/browser-guest-input-gesture' import { isNewBrowserTabPopupIntent, isBrowserTabPopupRequest, - normalizeBrowserPopupUrl + normalizeBrowserPopupUrl, + type NewBrowserTabPopupRequest } from '../../popups/browser-popup-new-tab-intent' import { SAFE_POPUP_WINDOW_OPTIONS } from '../../popups/presentation/browser-popup-window-policy' import { safeOrigin } from '../../browser-event-origin' @@ -37,47 +41,16 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig guest.setWindowOpenHandler(({ url, frameName, disposition, postBody, features, referrer }) => { // Spend activation even on popups so it cannot fund a later tab. const observed = gesture.consume() + if (this.openNewTabPopup(guest, { url, frameName, disposition, postBody }, observed)) { + return { action: 'deny' } + } const clicked = observed !== null // Only the desktop user's own click may bring a popup forward; agents and late opens wait. const showWhenAppActive = observed?.byAgent !== false - const ownerContext = this.resolvePopupOwnerContext(guest.id) - const browserTabId = ownerContext?.browserTabId ?? null + const activateTab = disposition !== 'background-tab' + const agentOpened = observed?.byAgent !== false && this.isAgentUsingGuest(guest.id) + const browserTabId = this.resolvePopupOwnerContext(guest.id)?.browserTabId ?? null const externalUrl = normalizeExternalBrowserUrl(url) - const newTabUrl = externalUrl ?? (isLocalFileLinkFromLocalPage(guest, url) ? url : null) - // Opener-dependent requests retain a child window instead of becoming tabs. - if ( - ownerContext && - newTabUrl && - isNewBrowserTabPopupIntent({ url, frameName, disposition, postBody }) - ) { - // Scripted opens persist as tabs, so opens without observed input consume a budget. - if (!clicked && !this.tryConsumePageInitiatedTab(ownerContext.rootGuestWebContentsId)) { - this.forwardOrQueuePopupEvent(guest.id, { - origin: safeOrigin(newTabUrl), - action: 'blocked' - }) - return { action: 'deny' } - } - // A new tab's download would miss the agent's `download` claim, so save the link here. - if (this.isAwaitingDownloadFrom(guest.id, ownerContext.rootGuestWebContentsId)) { - guest.downloadURL(newTabUrl) - return { action: 'deny' } - } - if ( - this.openLinkInOrcaTab( - ownerContext.browserTabId, - newTabUrl, - disposition !== 'background-tab' - ) - ) { - this.forwardOrQueuePopupEvent(guest.id, { - origin: safeOrigin(newTabUrl), - action: 'opened-in-orca' - }) - } - // A vanished renderer must not turn new-tab intent into a native popup. - return { action: 'deny' } - } // Native popups must not target local files. const canOpenAsChild = normalizeBrowserPopupUrl(url) !== null @@ -93,7 +66,8 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig tabUrl && !(options.nativeWindow?.webContents ?? options.webContents)?.opener ? this.openPopupAsBrowserTab(guest, tabUrl, options, { clicked, - activate: disposition !== 'background-tab' + activate: activateTab, + agentOpened }) : null if (isNativeBrowserPopupRequest({ disposition, features, frameName })) { @@ -149,6 +123,47 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig } } + /** Answers a new-tab request as an Orca tab; false leaves opener-dependent requests to a child window. */ + openNewTabPopup( + guest: Electron.WebContents, + request: NewBrowserTabPopupRequest, + observed: ObservedBrowserGuestGesture | null + ): boolean { + const ownerContext = this.resolvePopupOwnerContext(guest.id) + const newTabUrl = + normalizeExternalBrowserUrl(request.url) ?? + (isLocalFileLinkFromLocalPage(guest, request.url) ? request.url : null) + if (!ownerContext || !newTabUrl || !isNewBrowserTabPopupIntent(request)) { + return false + } + // Scripted opens persist as tabs, so opens without observed input consume a budget. + if (!observed && !this.tryConsumePageInitiatedTab(ownerContext.rootGuestWebContentsId)) { + this.forwardOrQueuePopupEvent(guest.id, { origin: safeOrigin(newTabUrl), action: 'blocked' }) + return true + } + // A new tab's download would miss the agent's `download` claim, so save the link here. + if (this.isAwaitingDownloadFrom(guest.id, ownerContext.rootGuestWebContentsId)) { + guest.downloadURL(newTabUrl) + return true + } + const agentOpened = observed?.byAgent !== false && this.isAgentUsingGuest(guest.id) + if ( + this.openLinkInOrcaTab( + ownerContext.browserTabId, + newTabUrl, + request.disposition !== 'background-tab', + agentOpened + ) + ) { + this.forwardOrQueuePopupEvent(guest.id, { + origin: safeOrigin(newTabUrl), + action: 'opened-in-orca' + }) + } + // A vanished renderer must not turn new-tab intent into a native popup. + return true + } + requestExternalAppLaunch( guest: Electron.WebContents, rawUrl: string | undefined, @@ -168,13 +183,13 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig opener: Electron.WebContents, url: string, options: PopupChildWindowOptions, - tab: { clicked: boolean; activate: boolean } + tab: { clicked: boolean; activate: boolean; agentOpened: boolean } ): Electron.WebContents { const owner = this.resolvePopupOwnerContext(opener.id) const opened = owner !== null && (tab.clicked || this.tryConsumePageInitiatedTab(owner.rootGuestWebContentsId)) && - this.openLinkInOrcaTab(owner.browserTabId, url, tab.activate) + this.openLinkInOrcaTab(owner.browserTabId, url, tab.activate, tab.agentOpened) this.forwardOrQueuePopupEvent(opener.id, { origin: safeOrigin(url), action: opened ? 'opened-in-orca' : 'blocked' diff --git a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts index 2b30397497a..49d9a894e79 100644 --- a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts @@ -42,10 +42,8 @@ vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ })) import { browserManager } from '../browser-manager' -import { - MAX_PAGE_INITIATED_TABS_PER_WINDOW, - PAGE_INITIATED_TAB_WINDOW_MS -} from '../../popups/browser-page-initiated-tab-budget' +import { withAgentInputInjection } from '../../../cdp/input/agent-input-injection' +import { runWithActiveRpcCaller } from '../../../../runtime/rpc/callers/active-call' import { guestNavigationMethods, rendererWebContentsId, @@ -59,8 +57,7 @@ const { guestSetBackgroundThrottlingMock, guestSetWindowOpenHandlerMock, guestOpenDevToolsMock, - webContentsFromIdMock, - openPopupWithOriginBarMock + webContentsFromIdMock } = browserMocks describe('browserManager', () => { @@ -76,17 +73,17 @@ describe('browserManager', () => { // #36804: headless serve pages have no renderer to own Orca's tab model. // orcad's Electron browser registers pages without a workspace, so there is no tab list to open into. - it('opens a tab for every clicked link but caps scripted opens', () => { - vi.useFakeTimers() + it("opens an agent's link behind the user's tab, and the user's own click in front", async () => { const rendererSendMock = vi.fn() const guest = { ...guestNavigationMethods(), - id: 144, + id: 145, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), getType: vi.fn(() => 'webview'), setBackgroundThrottling: guestSetBackgroundThrottlingMock, setWindowOpenHandler: guestSetWindowOpenHandlerMock, + setIgnoreMenuShortcuts: vi.fn(), on: guestOnMock, prependListener: vi.fn(), off: guestOffMock, @@ -97,172 +94,49 @@ describe('browserManager', () => { return guest } if (id === rendererWebContentsId) { - return { isDestroyed: vi.fn(() => false), send: rendererSendMock } + return { id, isDestroyed: vi.fn(() => false), send: rendererSendMock } } return null }) - browserManager.attachGuestPolicies(guest as never) browserManager.registerGuest({ browserPageId: 'browser-1', webContentsId: guest.id, rendererWebContentsId }) - - const handler = guestSetWindowOpenHandlerMock.mock.calls[0][0] as (details: { + const handler: (details: { url: string frameName: string features: string disposition: string - }) => { action: 'allow' | 'deny' } + }) => unknown = guestSetWindowOpenHandlerMock.mock.calls[0][0] const inputEventHandler = guestOnMock.mock.calls.find(([event]) => event === 'input-event')?.[1] - const open = (index: number): void => { - handler({ - url: `https://docs.example.com/${index}`, - frameName: '', - features: '', - disposition: 'background-tab' - }) + const openLink = (url: string): void => { + handler({ url, frameName: '', features: '', disposition: 'foreground-tab' }) } - const routedTabCount = (): number => - rendererSendMock.mock.calls.filter(([channel]) => channel === 'browser:open-link-in-orca-tab') - .length - - const clicks = MAX_PAGE_INITIATED_TABS_PER_WINDOW * 2 - for (let index = 0; index < clicks; index++) { - inputEventHandler({}, { type: 'mouseUp' }) - open(index) - } - expect(routedTabCount()).toBe(clicks) - - // Each observed input bypasses the budget once. - inputEventHandler({}, { type: 'mouseUp' }) - for (let index = 0; index < MAX_PAGE_INITIATED_TABS_PER_WINDOW * 2; index++) { - open(clicks + index) - } - expect(routedTabCount()).toBe(clicks + 1 + MAX_PAGE_INITIATED_TABS_PER_WINDOW) - - // Spending activation on a popup cannot fund a later tab. - vi.advanceTimersByTime(PAGE_INITIATED_TAB_WINDOW_MS) - inputEventHandler({}, { type: 'mouseUp' }) - expect( - handler({ - url: 'https://sso.example.com/auth', - frameName: 'sso', - features: 'width=500,height=600', - disposition: 'new-window' - }) - ).toMatchObject({ action: 'allow' }) - const tabsBeforeScriptedLoop = routedTabCount() - for (let index = 0; index < MAX_PAGE_INITIATED_TABS_PER_WINDOW * 2; index++) { - open(clicks * 2 + index) - } - expect(routedTabCount()).toBe(tabsBeforeScriptedLoop + MAX_PAGE_INITIATED_TABS_PER_WINDOW) - expect(rendererSendMock).toHaveBeenCalledWith('browser:popup', { - browserPageId: 'browser-1', - origin: 'https://docs.example.com', - action: 'blocked' - }) - }) - - it('shares the page-initiated tab budget across the whole opener popup tree', () => { - const rendererSendMock = vi.fn() - const guest = { - ...guestNavigationMethods(), - id: 150, - isDestroyed: vi.fn(() => false), - isCurrentlyAudible: vi.fn(() => false), - getType: vi.fn(() => 'webview'), - setBackgroundThrottling: guestSetBackgroundThrottlingMock, - setWindowOpenHandler: guestSetWindowOpenHandlerMock, - on: guestOnMock, - once: vi.fn(), - off: guestOffMock, - openDevTools: guestOpenDevToolsMock - } - const guestsById = new Map([[guest.id, guest]]) - webContentsFromIdMock.mockImplementation((id: number) => { - if (id === rendererWebContentsId) { - return { isDestroyed: vi.fn(() => false), send: rendererSendMock } - } - return guestsById.get(id) ?? null - }) - - browserManager.attachGuestPolicies(guest as never) - browserManager.registerGuest({ - browserPageId: 'browser-1', - webContentsId: guest.id, - rendererWebContentsId - }) - - type WindowOpenHandler = (details: { - url: string - frameName: string - features: string - disposition: string - }) => { - action: 'allow' | 'deny' - createWindow?: (options: Record) => unknown - } - const handler = guestSetWindowOpenHandlerMock.mock.calls[0][0] as WindowOpenHandler - - // Named child popups must share the root opener budget. - const openNamedChild = (index: number): WindowOpenHandler => { - const childSetWindowOpenHandlerMock = vi.fn() - const child = { - ...guestNavigationMethods(), - id: 1500 + index, - isDestroyed: vi.fn(() => false), - isCurrentlyAudible: vi.fn(() => false), - getType: vi.fn(() => 'webview'), - setBackgroundThrottling: vi.fn(), - setWindowOpenHandler: childSetWindowOpenHandlerMock, - on: vi.fn(), - once: vi.fn(), - off: vi.fn(), - openDevTools: vi.fn() - } - guestsById.set(child.id, child) - openPopupWithOriginBarMock.mockReturnValueOnce({ - contentWebContents: child, - close: vi.fn(), - onClosed: vi.fn() - }) - const result = handler({ - url: `https://sso.example.com/child-${index}`, - frameName: `child-${index}`, - features: '', - disposition: 'new-window' - }) - expect(result).toMatchObject({ action: 'allow' }) - result.createWindow?.({ webContents: child }) - openPopupWithOriginBarMock.mock.calls.at(-1)?.[2](child) - return childSetWindowOpenHandlerMock.mock.calls[0][0] as WindowOpenHandler - } - - const childHandlers = [openNamedChild(0), openNamedChild(1), openNamedChild(2)] - for (const [childIndex, childHandler] of childHandlers.entries()) { - for (let openIndex = 0; openIndex < MAX_PAGE_INITIATED_TABS_PER_WINDOW; openIndex++) { - expect( - childHandler({ - url: `https://docs.example.com/${childIndex}-${openIndex}`, - frameName: '', - features: '', - disposition: 'foreground-tab' - }) - ).toEqual({ action: 'deny' }) - } - } - - const routedTabs = rendererSendMock.mock.calls.filter( - ([channel]) => channel === 'browser:open-link-in-orca-tab' + const command = runWithActiveRpcCaller({ kind: 'local-cli' }, () => + browserManager.beginAgentCommand('browser-1') ) - expect(routedTabs).toHaveLength(MAX_PAGE_INITIATED_TABS_PER_WINDOW) - expect(rendererSendMock).toHaveBeenCalledWith('browser:popup', { - browserPageId: 'browser-1', - origin: 'https://docs.example.com', - action: 'blocked' + + await withAgentInputInjection(guest as never, async () => { + inputEventHandler({}, { type: 'mouseUp' }) }) - expect(openPopupWithOriginBarMock).toHaveBeenCalledTimes(childHandlers.length) + openLink('https://docs.example.com/agent') + inputEventHandler({}, { type: 'mouseUp' }) + openLink('https://docs.example.com/user') + command.end() + + expect( + rendererSendMock.mock.calls.filter(([channel]) => channel === 'browser:open-link-in-orca-tab') + ).toEqual([ + [ + 'browser:open-link-in-orca-tab', + { browserPageId: 'browser-1', url: 'https://docs.example.com/agent', activate: false } + ], + [ + 'browser:open-link-in-orca-tab', + { browserPageId: 'browser-1', url: 'https://docs.example.com/user' } + ] + ]) }) }) diff --git a/src/main/browser/guest-lifecycle/navigation/browser-link-materialization-electron-fixture.ts b/src/main/browser/guest-lifecycle/navigation/browser-link-materialization-electron-fixture.ts index 78fc3d6f9ac..4c0af0e1229 100644 --- a/src/main/browser/guest-lifecycle/navigation/browser-link-materialization-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/navigation/browser-link-materialization-electron-fixture.ts @@ -1,6 +1,6 @@ import { app, BrowserWindow, ipcMain, session, webContents } from 'electron' import { join } from 'node:path' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy' if (process.env.ORCA_BACKGROUND_LAUNCH !== '1') { throw new Error('Popup identity probes require a background launch') diff --git a/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts index 1b7f56d82af..c9d0c01974f 100644 --- a/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts +++ b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts @@ -21,8 +21,7 @@ vi.mock('electron', () => ({ })) import { BrowserAgentActivity } from './browser-agent-activity' -import { runWithActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' -import { runInRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { runWithActiveRpcCaller } from '../../../runtime/rpc/callers/active-call' import { BROWSER_AGENT_CURSOR_ARRIVED_CHANNEL, BROWSER_AGENT_CURSOR_CHANNEL, @@ -80,50 +79,6 @@ describe('BrowserAgentActivity', () => { vi.useRealTimers() }) - it("names the SSH host driving a page, and clears only that host's pages when it is stopped", async () => { - const { activity, sent } = setup() - const host = { targetId: 'ssh-1', hostLabel: 'build-box' } - const lease = await runWithActiveRpcCaller({ kind: 'local-cli' }, () => - runInRemoteCliBrowserScope( - 'wt-1', - async () => activity.beginCommand(PAGE), - undefined, - undefined, - undefined, - host - ) - ) - runWithActiveRpcCaller({ kind: 'local-cli' }, () => activity.beginCommand('local-page')).end() - expect(sent[0]?.data).toEqual({ - browserPageId: PAGE, - worktreeId: 'wt-1', - active: true, - controllerHostLabel: 'build-box' - }) - expect(sent[1]?.data).toEqual({ browserPageId: 'local-page', worktreeId: 'wt-1', active: true }) - - activity.endForController('ssh-1') - expect(activity.isActive(PAGE)).toBe(false) - expect(activity.isActive('local-page')).toBe(true) - expect(sent.at(-1)?.data).toEqual({ browserPageId: PAGE, worktreeId: 'wt-1', active: false }) - lease.end() - }) - - it('hands an agent claim to the page it continues on with a fresh idle window', () => { - const { activity, agentCommand } = setup() - activity.handOver('opener', PAGE) - expect(activity.isActive(PAGE)).toBe(false) - - agentCommand().end() - vi.advanceTimersByTime(15_000) - runWithActiveRpcCaller({ kind: 'local-cli' }, () => activity.beginCommand('popup')).end() - activity.handOver('popup', PAGE) - vi.advanceTimersByTime(19_000) - expect(activity.isActive(PAGE)).toBe(true) - vi.advanceTimersByTime(1_000) - expect(activity.isActive(PAGE)).toBe(false) - }) - it('holds a fresh move until the renderer reports the cursor landed', async () => { const { agentCommand, cursorEvents, arrive, show } = setup() let landed = false diff --git a/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts index 33bd6cf2ef6..ca3bbe1a79a 100644 --- a/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts +++ b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts @@ -1,7 +1,7 @@ import { BrowserWindow, ipcMain, type WebContents } from 'electron' -import { isResourceWindowVisible } from '../../../window/resource-view-admission' +import { isResourceWindowVisible } from '../../../window/visibility/resource-view-admission' import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' -import { isAgentRpcCaller } from '../../../runtime/rpc/rpc-caller-identity' +import { isAgentRpcCaller } from '../../../runtime/rpc/callers/rpc-caller-identity' import { BROWSER_AGENT_ACTIVITY_CHANNEL, BROWSER_AGENT_CURSOR_ARRIVED_CHANNEL, @@ -12,7 +12,7 @@ import { import { getActiveRpcAgentSessionId, getActiveRpcCaller -} from '../../../runtime/rpc/rpc-active-caller' +} from '../../../runtime/rpc/callers/active-call' import { remoteCliBrowserScopeController, type RemoteCliBrowserController diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-new-tab-intent.ts b/src/main/browser/guest-lifecycle/popups/browser-popup-new-tab-intent.ts index c22e66e4092..dbc7bcee9d1 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-new-tab-intent.ts +++ b/src/main/browser/guest-lifecycle/popups/browser-popup-new-tab-intent.ts @@ -1,10 +1,12 @@ -// Keep named and OAuth popups attached to their opener; tab conversion returns null to the page. -export function isNewBrowserTabPopupIntent(details: { +export type NewBrowserTabPopupRequest = { url: string frameName: string disposition: string postBody?: Electron.PostBody | null -}): boolean { +} + +// Keep named and OAuth popups attached to their opener; tab conversion returns null to the page. +export function isNewBrowserTabPopupIntent(details: NewBrowserTabPopupRequest): boolean { return ( isBrowserTabPopupRequest(details) && !isBlankBrowserPopupUrl(details.url) && diff --git a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts index bfd564a762f..e44319d6ee7 100644 --- a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts @@ -9,7 +9,7 @@ import { } from 'electron' import { writeFileSync } from 'node:fs' import { renameFileWithWindowsRetry } from '../../../../../shared/windows-retry-file-operations' -import { applyBackgroundActivationPolicy } from '../../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../../window/activation/foreground-activation-policy' import { BrowserPopupCompatibilityManager } from './browser-popup-compatibility-manager-fixture' import { BrowserRouteWebContentsRegistry } from '../../../routing/guest-authority/browser-route-webcontents-registry' import { initializeBrowserProcessUserAgent } from '../../../identity/browser-process-user-agent' diff --git a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts index 81389d6d001..c88457c6f88 100644 --- a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts @@ -16,10 +16,15 @@ export class BrowserPopupCompatibilityManager extends BrowserManager { security: ReturnType permission?: string }[] = [] - protected override openLinkInOrcaTab(pageId: string, url: string, activate?: boolean): boolean { + protected override openLinkInOrcaTab( + pageId: string, + url: string, + activate?: boolean, + agentOpened?: boolean + ): boolean { this.tabOpens.push({ url, activate }) this.writeStatus() - return super.openLinkInOrcaTab(pageId, url, activate) + return super.openLinkInOrcaTab(pageId, url, activate, agentOpened) } protected override createPopupChildWindowWithOriginBar( opener: WebContents, diff --git a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts deleted file mode 100644 index 506af3c6687..00000000000 --- a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - browser, - closeChildren, - guest, - origin, - receipts, - status -} from './browser-popup-compatibility-cdp-fixture' - -describe('hidden Chromium popup compatibility', () => { - it.each(['local', 'route'])( - 'keeps POST bodies, headers, referrers and cookie jars: %s', - async (name) => { - for (const id of ['post', 'multipart', 'empty']) { - const before = receipts.length - await guest(name).locator(`#${id}`).click() - await expect - .poll(() => receipts.slice(before).find((receipt) => receipt.path === `/${id}`)) - .toMatchObject({ - method: 'POST', - referrer: `${origin}/${name}`, - cookie: `synthetic_session=${name}`, - proxied: name === 'route', - origin, - fetchSite: 'same-origin' - }) - const receipt = receipts.slice(before).find((receipt) => receipt.path === `/${id}`) - expect(receipt?.body).toEqual( - id === 'post' - ? 'code=synthetic%2Bvalue' - : id === 'empty' - ? '' - : expect.stringContaining('synthetic-multipart') - ) - expect(receipt?.contentType).toMatch( - id === 'multipart' - ? /^multipart\/form-data; boundary=/ - : /^application\/x-www-form-urlencoded/ - ) - await closeChildren(guest(name)) - } - } - ) - - it('retains remote no-gesture, stale-gesture, scheme and four-window guards', async () => { - const page = guest('route') - expect(await page.evaluate('window.open("about:blank")===null')).toBe(true) - await page.locator('#invalid').click() - expect(await page.locator('body').getAttribute('data-handle')).toBe('false') - await page.locator('#stale').click() - await expect - .poll(() => page.locator('body').getAttribute('data-handle'), { timeout: 4_000 }) - .toBe('false') - await page.locator('#burst').click() - expect(await page.locator('body').getAttribute('data-handles')).toBe( - '[true,false,false,false,false]' - ) - await closeChildren(page) - for (let index = 0; index < 3; index += 1) { - await page.locator('#blank').click() - } - await page.locator('#shift').evaluate((link) => link.setAttribute('href', '/native-owned')) - await page.locator('#shift').click({ modifiers: ['Shift'] }) - await expect - .poll(() => - browser - ?.contexts() - .flatMap((context) => context.pages()) - .some((candidate) => candidate.url() === `${origin}/native-owned`) - ) - .toBe(true) - const native = browser - ?.contexts() - .flatMap((context) => context.pages()) - .find((candidate) => candidate.url() === `${origin}/native-owned`) - if (!native) { - throw new Error('Missing owned native child') - } - expect(await native.evaluate('window.open("about:blank")===null')).toBe(true) - await page.evaluate('window.livePopup=window.popup') - expect(await page.locator('body').getAttribute('data-handle')).toBe('true') - await page.locator('#blank').click() - expect(await page.locator('body').getAttribute('data-handle')).toBe('false') - expect(status().blocked.length).toBeGreaterThanOrEqual(7) - expect(status().windowsHidden).toBe(true) - expect(await page.evaluate('Notification.requestPermission()')).toBe('denied') - await page.evaluate('console.log("orca-popup-fixture:fence")') - await expect.poll(() => status().routeGranted).toBe(false) - await expect.poll(() => page.evaluate('window.livePopup.closed')).toBe(true) - await expect.poll(() => native.isClosed()).toBe(true) - await page.locator('#blank').click() - expect(await page.locator('body').getAttribute('data-handle')).toBe('false') - await page.evaluate('console.log("orca-popup-fixture:grant")') - await expect.poll(() => status().routeGranted).toBe(true) - await page.locator('#blank').click() - expect(await page.locator('body').getAttribute('data-handle')).toBe('true') - const child = browser - ?.contexts() - .flatMap((context) => context.pages()) - .find((candidate) => candidate.url() === 'about:blank#state') - if (!child) { - throw new Error('Missing child for opener-close check') - } - await page.locator('#shift').click({ modifiers: ['Shift'] }) - await expect - .poll(() => - browser - ?.contexts() - .flatMap((context) => context.pages()) - .some((candidate) => candidate.url() === `${origin}/native-owned`) - ) - .toBe(true) - const regrantedNative = browser - ?.contexts() - .flatMap((context) => context.pages()) - .find((candidate) => candidate.url() === `${origin}/native-owned`) - if (!regrantedNative) { - throw new Error('Missing regranted native child') - } - await page.evaluate('console.log("orca-popup-fixture:close")') - await expect.poll(() => child.isClosed()).toBe(true) - await expect.poll(() => regrantedNative.isClosed()).toBe(true) - }) -}) diff --git a/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts index f8b19f879ff..c52c67c8e3a 100644 --- a/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts @@ -3,7 +3,7 @@ import type { BrowserWindow, WebContents } from 'electron' import { isBackgroundLaunch, showWhenAppActive -} from '../../../../window/foreground-activation-policy' +} from '../../../../window/activation/foreground-activation-policy' import type { PopupChildWindowOptions, PopupOriginBarWindow } from './browser-popup-window-contract' import { isNativeBrowserPopupWindow, diff --git a/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts index b8edf83ca38..1e947aaf060 100644 --- a/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts @@ -1,8 +1,9 @@ import { BaseWindow, WebContentsView } from 'electron' import { isBackgroundLaunch, + revealWindowsAwaitingAppActive, showWhenAppActive -} from '../../../../window/foreground-activation-policy' +} from '../../../../window/activation/foreground-activation-policy' import { discardBrowserPopupContents, prepareNativeBrowserPopup @@ -147,6 +148,8 @@ export function openPopupWithOriginBar( // Re-pin on explicit fullscreen events; resize alone does not cover every platform. window.on('enter-full-screen', layoutViews) window.on('leave-full-screen', layoutViews) + // Off macOS, a return to Orca through this popup alone raises no app event. + window.on('focus', revealWindowsAwaitingAppActive) layoutViews() const contentWebContents = contentView.webContents diff --git a/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts index 68cff07d9fa..13037781fd1 100644 --- a/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts @@ -3,7 +3,7 @@ import { mkdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { openPopupWithOriginBar } from './popup-origin-bar-window' import { prepareNativeBrowserPopup } from './browser-popup-native-window' -import { applyBackgroundActivationPolicy } from '../../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../../window/activation/foreground-activation-policy' if (process.env.ORCA_BACKGROUND_LAUNCH !== '1') { throw new Error('Popup identity probes require a background launch') diff --git a/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts b/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts index 2c48482178e..ebe0199e4bd 100644 --- a/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts +++ b/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts @@ -3,11 +3,15 @@ import '../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { isBlankBrowserPopupUrl, - normalizeBrowserPopupUrl + normalizeBrowserPopupUrl, + type NewBrowserTabPopupRequest } from '../../guest-lifecycle/popups/browser-popup-new-tab-intent' import { enforceBrowserRouteWebRtcPolicy } from '../../network/egress/browser-route-webrtc-policy' import { trackBrowserGuestInputGesture } from '../../guest-lifecycle/input/browser-guest-input-gesture' -import type { BrowserGuestInputGesture } from '../../guest-lifecycle/input/browser-guest-input-gesture' +import type { + BrowserGuestInputGesture, + ObservedBrowserGuestGesture +} from '../../guest-lifecycle/input/browser-guest-input-gesture' import { registerBrowserRouteGuestPopup, releaseBrowserRouteGuestPopup @@ -28,6 +32,12 @@ export type BrowserRouteGuestPopupDependencies = { getPartitionForSession: (session: Session) => string | null /** Route guests replace the manager's popup handler, so a denial is otherwise entirely silent. */ reportBlockedPopup?: (input: { openerWebContentsId: number; url: string }) => void + /** The manager's new-tab policy; true when it answered the request. */ + openNewTabPopup?: ( + source: WebContents, + request: NewBrowserTabPopupRequest, + observed: ObservedBrowserGuestGesture | null + ) => boolean openPopupWindow?: ( options: PopupChildWindowOptions, targetUrl: string, @@ -172,13 +182,23 @@ export function createBrowserRouteGuestPopupController(input: { return (details) => { const observed = gesture.consume() const normalized = normalizeBrowserPopupUrl(details?.url) + const permitted = !disposed && normalized !== null && navigationAllowed(normalized) if ( - disposed || - !normalized || - popups.size >= MAX_BROWSER_ROUTE_GUEST_POPUPS || - !navigationAllowed(normalized) || - !observed + permitted && + input.dependencies.openNewTabPopup?.( + source, + { + url: details?.url ?? normalized, + frameName: details?.frameName ?? '', + disposition: details?.disposition ?? '', + postBody: details?.postBody + }, + observed + ) ) { + return { action: 'deny' } + } + if (!permitted || popups.size >= MAX_BROWSER_ROUTE_GUEST_POPUPS || !observed) { if (!disposed) { reportBlockedPopup(details?.url) } diff --git a/src/main/browser/routing/guest-authority/browser-route-webcontents-registry-dependencies.ts b/src/main/browser/routing/guest-authority/browser-route-webcontents-registry-dependencies.ts index 43d0ab555cf..c0c3be335b0 100644 --- a/src/main/browser/routing/guest-authority/browser-route-webcontents-registry-dependencies.ts +++ b/src/main/browser/routing/guest-authority/browser-route-webcontents-registry-dependencies.ts @@ -4,6 +4,7 @@ import type { BrowserRoutePageOwnerIdentity } from './browser-route-page-authority' import type { BrowserRouteSessionRekey } from '../sessions/browser-route-session-state' +import type { BrowserRouteGuestPopupDependencies } from './browser-route-guest-popups' export type BrowserRouteWebContentsRegistryDependencies = { getPartitionForSession(session: Session): string | null @@ -16,5 +17,6 @@ export type BrowserRouteWebContentsRegistryDependencies = { retirePreparedPagesOwnedByRenderer(rendererWebContentsId: number): number /** Route-guest popup denials need an explicit notice on the owning page. */ reportBlockedPopup?(input: { openerWebContentsId: number; url: string }): void + openNewTabPopup?: BrowserRouteGuestPopupDependencies['openNewTabPopup'] maxGuests?: number } diff --git a/src/main/browser/routing/guest-authority/browser-route-webcontents-registry.ts b/src/main/browser/routing/guest-authority/browser-route-webcontents-registry.ts index 044ac5e099b..4aeded40a01 100644 --- a/src/main/browser/routing/guest-authority/browser-route-webcontents-registry.ts +++ b/src/main/browser/routing/guest-authority/browser-route-webcontents-registry.ts @@ -73,6 +73,7 @@ export class BrowserRouteWebContentsRegistry { getPartitionForSession: (routeSession) => this.dependencies.getPartitionForSession(routeSession), reportBlockedPopup: (blocked) => this.dependencies.reportBlockedPopup?.(blocked), + openNewTabPopup: this.dependencies.openNewTabPopup, isPopupNavigationAllowed: (url) => this.navigationAllowed(state, url, false) }) } catch { diff --git a/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts b/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts index 6197600b35a..58db3ac263a 100644 --- a/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts +++ b/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' -import { BROWSER_GUEST_INPUT_GESTURE_WINDOW_MS } from '../../guest-lifecycle/input/browser-guest-input-gesture' import { BrowserPageInputCredit } from './browser-page-input-credit' -import { LOCAL_CLI_RPC_CALLER } from '../../../runtime/rpc/rpc-caller-identity' +import type { LOCAL_CLI_RPC_CALLER } from '../../../runtime/rpc/callers/rpc-caller-identity' const desktop = { kind: 'paired-device', deviceId: 'desk-1' } as const @@ -23,27 +22,4 @@ describe('BrowserPageInputCredit', () => { expect(credit.consume('tab-1')).toBe('desk-1') expect(credit.consume('tab-1')).toBeNull() }) - - it('leaves the credit alone for commands that deliver no activating input', async () => { - const { credit, click } = setup() - await click(desktop) - await credit.during('page-1', LOCAL_CLI_RPC_CALLER, async () => undefined) - - expect(credit.consume('tab-1')).toBe('desk-1') - }) - - it('credits no client for an agent click, input outside any command, or after the window', async () => { - const { credit, click, advance } = setup() - await click(desktop) - await click(LOCAL_CLI_RPC_CALLER) - expect(credit.consume('tab-1')).toBeNull() - - await click(desktop) - credit.creditInput('tab-1', 'page-1') - expect(credit.consume('tab-1')).toBeNull() - - await click(desktop) - advance(BROWSER_GUEST_INPUT_GESTURE_WINDOW_MS + 1) - expect(credit.consume('tab-1')).toBeNull() - }) }) diff --git a/src/main/browser/routing/input-ownership/browser-page-input-credit.ts b/src/main/browser/routing/input-ownership/browser-page-input-credit.ts index 6d65953fe02..39ff41c4958 100644 --- a/src/main/browser/routing/input-ownership/browser-page-input-credit.ts +++ b/src/main/browser/routing/input-ownership/browser-page-input-credit.ts @@ -1,5 +1,5 @@ import { isRecentBrowserGuestInput } from '../../guest-lifecycle/input/browser-guest-input-gesture' -import type { RpcCallerIdentity } from '../../../runtime/rpc/rpc-caller-identity' +import type { RpcCallerIdentity } from '../../../runtime/rpc/callers/rpc-caller-identity' type Runner = { pairedDeviceId: string | null } diff --git a/src/main/browser/routing/partitions/browser-route-partition-storage-runtime.ts b/src/main/browser/routing/partitions/browser-route-partition-storage-runtime.ts index 4d1b2ab8f97..76c985ec4d1 100644 --- a/src/main/browser/routing/partitions/browser-route-partition-storage-runtime.ts +++ b/src/main/browser/routing/partitions/browser-route-partition-storage-runtime.ts @@ -21,7 +21,7 @@ import { currentBrowserRoutePartitionBindingFilePath } from './browser-route-partition-binding-runtime' import { browserRoutePartitionStorageDependencies } from './browser-route-partition-storage-dependencies' -import { getRuntimeEnvironmentRegistryRoot } from '../../../ipc/runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from '../../../ipc/runtime-environments/catalog/runtime-environment-registry-root' export type BrowserRoutePartitionStorageClear = { clearedPartitions: string[] diff --git a/src/main/browser/routing/sessions/browser-route-session-runtime.ts b/src/main/browser/routing/sessions/browser-route-session-runtime.ts index 9ec15ac14fc..34b376641a3 100644 --- a/src/main/browser/routing/sessions/browser-route-session-runtime.ts +++ b/src/main/browser/routing/sessions/browser-route-session-runtime.ts @@ -88,7 +88,9 @@ export const browserRouteWebContentsRegistry = new BrowserRouteWebContentsRegist retirePreparedPage: (page) => browserRouteSessionRegistry.retirePreparedPage(page), retirePreparedPagesOwnedByRenderer: (rendererWebContentsId) => browserRouteSessionRegistry.retirePreparedPagesOwnedByRenderer(rendererWebContentsId), - reportBlockedPopup: (blocked) => browserManager.reportRouteGuestPopupBlocked(blocked) + reportBlockedPopup: (blocked) => browserManager.reportRouteGuestPopupBlocked(blocked), + openNewTabPopup: (source, request, observed) => + browserManager.openNewTabPopup(source, request, observed) }) routeWebContentsRegistryRef.current = browserRouteWebContentsRegistry diff --git a/src/main/claude-accounts/claude-account-service.test.ts b/src/main/claude-accounts/claude-account-service.test.ts index 944c48015d8..defc0da2de8 100644 --- a/src/main/claude-accounts/claude-account-service.test.ts +++ b/src/main/claude-accounts/claude-account-service.test.ts @@ -11,6 +11,12 @@ import type { ClaudeCommandConfig, ClaudeCommandOptions } from './sign-in/claude import type { ClaudeAccountSelectionTarget } from './selection/runtime-selection' import { ClaudeAccountService } from './service' +// Selection checks must never reach the real Keychain. +vi.mock('../macos-keychain/generic-password', async (importOriginal) => ({ + ...(await importOriginal()), + readKeychainPassword: async () => null +})) + const roots: string[] = [] afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))) @@ -190,4 +196,19 @@ describe('ClaudeAccountService', () => { expect(f.runtimeAuth.removeAccountFolder).not.toHaveBeenCalled() expect(f.settings().claudeManagedAccounts.map((entry) => entry.id)).toEqual(['a', 'b']) }) + + it('refuses to select an account that has its identity but no login to start Claude with', async () => { + const f = fixture() + f.signIn('b', 'b@example.test') + await expect(f.service.selectAccount('b')).rejects.toThrow( + 'Sign in to this Claude account again before selecting it.' + ) + expect(f.settings().activeClaudeManagedAccountId).toBe('a') + + writeFileSync( + join(f.home('b'), '.credentials.json'), + JSON.stringify({ claudeAiOauth: { refreshToken: 'refresh' } }) + ) + await expect(f.service.selectAccount('b')).resolves.toMatchObject({ activeAccountId: 'b' }) + }) }) diff --git a/src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts b/src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts index b2351a46e6d..4bfa9ba7ea0 100644 --- a/src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts @@ -38,7 +38,7 @@ const command = vi.hoisted(() => ({ path: '/unused-claude' })) vi.mock('../../../codex-cli/command', () => ({ resolveClaudeCommand: () => command.path })) const shell = vi.hoisted(() => ({ hang: false })) -vi.mock('../../../startup/login-shell-environment', () => ({ +vi.mock('../../../startup/shell-environment/login-shell-environment', () => ({ resolveLoginShellEnvironment: () => shell.hang ? new Promise(() => {}) @@ -233,30 +233,6 @@ describe('ClaudeProfileRouter', () => { expect(existsSync(f.router.pointerPath)).toBe(false) }) - it("launches a set-up, signed-in account without waiting for the login shell's env", async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - shell.hang = true - const f = fixture() - mkdirSync(f.home('a'), { recursive: true }) - prepareClaudeProfileDirectory( - f.dataRoot, - describeClaudeProfile(f.dataRoot, 'a', { - executionHostId: 'local', - runtime: 'host' - }), - f.userHome - )() - signIn(f.home('a'), 'a@example.test') - const router = new ClaudeProfileRouter({ - getSettings: () => f.settings, - dataRoot: f.dataRoot, - userHome: f.userHome - }) - const launch = router.prepareLaunch() - await advanceRefreshDeadline(launch, 5_000) - await expect(launch).resolves.toMatchObject({ configDir: f.home('a') }) - }) - it('requires concurrent launches to finish rebuilding a home whose marker survived', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) const f = fixture() diff --git a/src/main/claude-accounts/profiles/routing/claude-profile-router.ts b/src/main/claude-accounts/profiles/routing/claude-profile-router.ts index c101c1aa7c1..eeaf341e6e7 100644 --- a/src/main/claude-accounts/profiles/routing/claude-profile-router.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-router.ts @@ -15,7 +15,7 @@ import { import { claudeProfileMissing } from './claude-profile-launch-errors' import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { ClaudeManagedAccount } from '../../../../shared/managed-account-types' -import { probeRecentClaudeCliVersion } from '../../../claude/claude-hook-event-versions' +import { probeRecentClaudeCliVersion } from '../../../claude/cli-capabilities/claude-hook-event-versions' import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' import { resolveClaudeCommand } from '../../../codex-cli/command' import { @@ -43,7 +43,7 @@ import { isSameClaudeLogin, type ClaudeFolderLogin } from '../../sign-in/claude-account-folder' -import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment' +import { resolveLoginShellEnvironment } from '../../../startup/shell-environment/login-shell-environment' export type ClaudeProfileRouterSettings = Pick< GlobalSettings, diff --git a/src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts b/src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts index 076a9ed5253..345284e11d5 100644 --- a/src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts @@ -1,5 +1,5 @@ import type { ClaudeProfileRouter, ClaudeProfileRouterSettings } from './claude-profile-router' -import { claudeLaunchDestinationHome } from '../../../claude/claude-launch-destination-home' +import { claudeLaunchDestinationHome } from '../../../claude/structured/launch/claude-launch-destination-home' /** Every native switcher destination, even an account whose setup has not created its home. */ export async function claudeProfileSelectionHomes( diff --git a/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts b/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts index 3d27f2ac77b..b02cd2fb031 100644 --- a/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts @@ -5,7 +5,7 @@ import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-ab import { resolveClaudeGlobalConfigFile, updateClaudeGlobalConfig -} from '../../../claude/claude-folder-trust-file' +} from '../../../claude/configuration/claude-folder-trust-file' import { publishFileWithoutOverwrite } from '../../../filesystem/atomic-file-publication' import { CLAUDE_PROFILE_HISTORY_DIRS, mergeClaudeProfileDirectory } from './claude-profile-history' import { readClaudeProfileObject, resolveClaudeDefaultHome } from '../claude-profile-paths' diff --git a/src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts b/src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts index e4bea6e70d7..cb7c7367fad 100644 --- a/src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts @@ -5,7 +5,6 @@ import { readFileSync, realpathSync, rmSync, - symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -115,12 +114,4 @@ describe('Claude account profile setup', () => { runtime: 'host' }) }) - - itLinks('refuses a data root linked into the default home before writing there', async () => { - const f = fixture() - mkdirSync(join(f.defaultHome, 'inner')) - symlinkSync(join(f.defaultHome, 'inner'), join(f.dataRoot, 'claude-profiles')) - expect((await f.setup()).outcome).toBe('refused') - expect(existsSync(join(f.defaultHome, 'inner', 'a'))).toBe(false) - }) }) diff --git a/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts index 863eaa8ff15..972f601bd11 100644 --- a/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts @@ -45,8 +45,13 @@ vi.mock('../../../wsl/execution/wsl-runner', () => ({ if (guest.failure) { return { ...guest.failure, stderr: '', timedOut: false } } + // Real wsl.exe --exec refuses an empty argument before the guest runs. + if (spec.args?.some((arg) => arg === '')) { + return { code: 1, stdout: '', stderr: 'Wsl/Service/E_INVALIDARG', timedOut: false } + } const result = spawnSync('/bin/sh', ['-c', spec.script ?? '', 'sh', ...(spec.args ?? [])], { - encoding: 'utf8' + encoding: 'utf8', + input: spec.input }) return { code: result.status, stdout: result.stdout, stderr: result.stderr, timedOut: false } } @@ -141,6 +146,17 @@ describe.skipIf(!posixHost)('ClaudeWslProfileRouter', () => { expect(readFileSync(f.pointer, 'utf8')).toBe(homeB) }) + it('launches on System default while a managed WSL account still exists', async () => { + const f = fixture() + mkdirSync(join(f.pointer, '..'), { recursive: true }) + writeFileSync(f.pointer, f.profileHome) + f.wsl.Ubuntu = null + await expect(f.router.prepareLaunch('Ubuntu')).resolves.toMatchObject({ + provenance: 'wsl:Ubuntu:system' + }) + expect(readFileSync(f.pointer, 'utf8')).toBe('') + }) + it("runs an account with no login of its own on the guest's ~/.claude while that is signed in to it", async () => { const f = fixture() mkdirSync(f.profileHome, { recursive: true }) diff --git a/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts index 4964813369c..42fb95f7571 100644 --- a/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts @@ -262,10 +262,11 @@ async function writePointer(distro: string, pointer: string, home: string): Prom if (current === home) { return } + // wsl.exe --exec rejects an empty argument (E_INVALIDARG), and System default writes ''; pass content on stdin. await runGuest(distro, { - script: - 'umask 077; mkdir -p -- "${1%/*}" && printf %s "$2" > "$1.tmp" && mv -f -- "$1.tmp" "$1"', - args: [pointer, home], + script: 'umask 077; mkdir -p -- "${1%/*}" && cat > "$1.tmp" && mv -f -- "$1.tmp" "$1"', + args: [pointer], + input: home, loginPath: 'none' }) } diff --git a/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts b/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts deleted file mode 100644 index b5bf34dc7cc..00000000000 --- a/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import type { ClaudeManagedAccount } from '../../../shared/managed-account-types' -import { isHostManagedClaudeAccount } from './environment' - -import { claudeStructuredAuthPolicyForSettings } from './claude-structured-auth-policy' - -const HOST_ACCOUNT = { id: 'host-a', managedAuthRuntime: 'host' } as ClaudeManagedAccount -const WSL_ACCOUNT = { id: 'wsl-b', managedAuthRuntime: 'wsl' } as ClaudeManagedAccount -const LEGACY_ACCOUNT = { id: 'legacy-c' } as ClaudeManagedAccount - -function settings( - overrides: Partial< - Pick< - GlobalSettings, - | 'claudeManagedAccounts' - | 'activeClaudeManagedAccountId' - | 'activeClaudeManagedAccountIdsByRuntime' - > - > -): Parameters[0] { - return { - claudeManagedAccounts: [HOST_ACCOUNT, WSL_ACCOUNT, LEGACY_ACCOUNT], - activeClaudeManagedAccountId: null, - ...overrides - } as Parameters[0] -} - -describe('isHostManagedClaudeAccount', () => { - it('is true for a selected id no account list explains', () => { - expect(isHostManagedClaudeAccount([HOST_ACCOUNT], 'deleted-d')).toBe(true) - expect(isHostManagedClaudeAccount(undefined, 'deleted-d')).toBe(true) - expect(isHostManagedClaudeAccount([], 'deleted-d')).toBe(true) - }) -}) - -describe('claudeStructuredAuthPolicyForSettings', () => { - it('reads the host runtime selection, not the legacy flat field alone', () => { - expect( - claudeStructuredAuthPolicyForSettings( - settings({ - activeClaudeManagedAccountId: 'host-a', - activeClaudeManagedAccountIdsByRuntime: { host: null, wsl: {} } - }) - ) - ).toEqual({ account: 'managed' }) - }) - - it('ignores a WSL-only selection: the structured child is always a native host process', () => { - expect( - claudeStructuredAuthPolicyForSettings( - settings({ - activeClaudeManagedAccountIdsByRuntime: { host: null, wsl: { Ubuntu: 'wsl-b' } } - }) - ) - ).toEqual({ account: 'system' }) - }) -}) diff --git a/src/main/claude-accounts/selection/claude-account-selection.ts b/src/main/claude-accounts/selection/claude-account-selection.ts index f1867ab0005..7fb0f91260e 100644 --- a/src/main/claude-accounts/selection/claude-account-selection.ts +++ b/src/main/claude-accounts/selection/claude-account-selection.ts @@ -6,6 +6,8 @@ import type { import type { GlobalSettings } from '../../../shared/global-settings-types' import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' import { claudeStateFile, readClaudeFolderLogin } from '../sign-in/claude-account-folder' +import { readClaudeOAuthCredentials } from '../../rate-limits/providers/claude/claude-oauth-credentials' +import { resolveLoginShellEnvironment } from '../../startup/shell-environment/login-shell-environment' import { savedWslClaudeAccountHome } from '../profiles/wsl/claude-profile-wsl-paths' import type { ClaudeRuntimeAuthService } from '../runtime-auth-service' import { @@ -193,8 +195,13 @@ export class ClaudeAccountSelection { ) { throw new Error('That Claude account belongs to a different runtime.') } - // CLI and paired clients bypass the renderer's sign-in check. - if (this.summarize(account).needsSignIn) { + // CLI and paired clients bypass the renderer's sign-in check. An identity file alone can't + // start Claude, and chats follow the selection on their next start. + const summary = this.summarize(account) + if ( + summary.needsSignIn || + (summary.home && !summary.runsOnSystemDefault && (await accountHoldsNoLogin(summary.home))) + ) { throw new Error(CLAUDE_ACCOUNT_NEEDS_SIGN_IN_MESSAGE) } effectiveTarget = accountTarget @@ -271,3 +278,16 @@ export class ClaudeAccountSelection { } } } + +/** The read usage already makes for this account; an unreadable store is no answer. */ +async function accountHoldsNoLogin(home: string): Promise { + // Claude then keeps every login elsewhere, so an empty account folder proves nothing. + if ((await resolveLoginShellEnvironment()).CLAUDE_SECURESTORAGE_CONFIG_DIR !== undefined) { + return false + } + const login = await readClaudeOAuthCredentials({ + credentialsFileConfigDir: home, + keychainConfigDir: home + }) + return !login.token && !login.hasRefreshableCredentials && !login.unavailable +} diff --git a/src/main/claude-accounts/sign-in/claude-account-folder.ts b/src/main/claude-accounts/sign-in/claude-account-folder.ts index 562a14c70ba..ee99171b86c 100644 --- a/src/main/claude-accounts/sign-in/claude-account-folder.ts +++ b/src/main/claude-accounts/sign-in/claude-account-folder.ts @@ -11,7 +11,7 @@ import { readFile, stat } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, join } from 'node:path' import { z } from 'zod' -import { resolveClaudeGlobalConfigFile } from '../../claude/claude-folder-trust-file' +import { resolveClaudeGlobalConfigFile } from '../../claude/configuration/claude-folder-trust-file' import { execSecurityCommand } from '../../macos-keychain/generic-password' import { describeClaudeProfile, readClaudeProfileObject } from '../profiles/claude-profile-paths' import { claudeConfigDirSpellings, claudeKeychainService } from '../runtime-auth/keychain' diff --git a/src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts b/src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts deleted file mode 100644 index a41f4460f23..00000000000 --- a/src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { EventEmitter } from 'node:events' -import { PassThrough } from 'node:stream' -import { afterEach, expect, it, vi } from 'vitest' - -const state = vi.hoisted(() => { - const resolved: string[] = [] - const programs: string[] = [] - return { resolved, programs } -}) - -vi.mock('@orca/process-host', () => ({ - spawnProcess: (spec: { program: string }) => { - state.programs.push(spec.program) - const child = Object.assign(new EventEmitter(), { - stdin: new PassThrough(), - stdout: new PassThrough(), - stderr: new PassThrough(), - pid: undefined, - kill: vi.fn() - }) - queueMicrotask(() => - spec.program.startsWith('/proc/') - ? child.emit( - 'error', - Object.assign(new Error(`spawn ${spec.program} ENOENT`), { code: 'ENOENT' }) - ) - : child.emit('close', 0) - ) - return child - } -})) -vi.mock('../../codex-cli/command', () => ({ - resolveClaudeCommand: () => state.resolved.shift() ?? '/home/me/.local/bin/claude' -})) - -import { runClaudeCommandProcess } from './claude-command-process' - -const WINDOWS_ONLY = '/proc/orca-agent-cli-installed-only-on-windows/claude' -const config = { windowsPath: '/home/me/.claude', linuxPath: null, wslDistro: null } -const originalPlatform = process.platform -afterEach(() => { - state.resolved.length = 0 - state.programs.length = 0 - Object.defineProperty(process, 'platform', { value: originalPlatform }) -}) - -it('never keeps the Windows-only answer, so a Claude installed in WSL since is used', async () => { - Object.defineProperty(process, 'platform', { value: 'linux' }) - // The first lookup sees only the Windows copy; every later one finds the new WSL install. - state.resolved.push(WINDOWS_ONLY) - await expect(runClaudeCommandProcess(['auth', 'status'], config, 1000)).rejects.toThrow( - 'installed only on Windows' - ) - await runClaudeCommandProcess(['auth', 'status'], config, 1000) - expect(state.programs).toEqual([WINDOWS_ONLY, '/home/me/.local/bin/claude']) -}) diff --git a/src/main/claude-usage/persisted-source-cache.ts b/src/main/claude-usage/persisted-source-cache.ts index 1dbe3f126ef..12fb712fc83 100644 --- a/src/main/claude-usage/persisted-source-cache.ts +++ b/src/main/claude-usage/persisted-source-cache.ts @@ -1,20 +1,18 @@ -import { readFile } from 'node:fs/promises' import type { ClaudeUsagePersistedFile, ClaudeUsagePersistedState } from './types' import { encodeClaudeUsagePersistedFiles } from './persisted-token-columns' -import { - compressClaudeUsageSourceText, - decodeClaudeUsageSourceText -} from './source-cache-compression' +import { writeClaudeUsageJson, readClaudeUsageJson } from './source-cache-compression' import { hasClaudeUsageProtectedCheckpoint, normalizeClaudeUsageSourceFiles, type ClaudeUsageVerifiedSources } from './persisted-projection-validation' -import { parseClaudeUsageReport, serializeClaudeUsageReport } from './persisted-usage-report' -import { sealUsageCacheJson, verifyUsageCacheJson } from '../usage/cache/usage-cache-json-integrity' +import { + parseClaudeUsageReport, + readClaudeUsageReportFile, + serializeClaudeUsageReport +} from './persisted-usage-report' import { usageSourceCachePath, - writeUsageSourceCacheData, type UsageCacheSplitRequest, type UsageCacheSplitResult, type UsageSourceCacheRef @@ -39,9 +37,12 @@ export async function readClaudeUsageSourceCache( return { sources: [] } } try { - const text = await decodeClaudeUsageSourceText(await readFile(cacheRef.path)) - const parsed = JSON.parse(text) - const verified = verifyUsageCacheJson(text, parsed?.usageIntegrity, SOURCE_DOMAIN) + const { parsed, verified } = await readClaudeUsageJson<{ + usageIntegrity?: string + schemaVersion: number + worktreeFingerprint: string | null + sources: ClaudeUsagePersistedFile[] + }>(cacheRef.path, SOURCE_DOMAIN) if ( (parsed?.schemaVersion !== cacheRef.schemaVersion && !(cacheRef.schemaVersion === 7 && parsed?.schemaVersion === 6)) || @@ -100,41 +101,40 @@ export async function writeClaudeUsageSourceCache( sources: readonly ClaudeUsagePersistedFile[] ): Promise { const cacheRef = { ...ref } - const material = JSON.stringify({ - schemaVersion: cacheRef.schemaVersion, - worktreeFingerprint: cacheRef.worktreeFingerprint, - sources: encodeClaudeUsagePersistedFiles(sources) - }) - await writeUsageSourceCacheData( + await writeClaudeUsageJson( cacheRef, - await compressClaudeUsageSourceText( - cacheRef.schemaVersion === 6 ? material : sealUsageCacheJson(material, SOURCE_DOMAIN) - ) + { + schemaVersion: cacheRef.schemaVersion, + worktreeFingerprint: cacheRef.worktreeFingerprint, + sources: encodeClaudeUsagePersistedFiles(sources) + }, + SOURCE_DOMAIN, + cacheRef.schemaVersion !== 6 ) } export async function splitClaudeUsageCacheFile( request: UsageCacheSplitRequest ): Promise { - let text: string + let loaded: Awaited> try { - text = await readFile(request.cacheFile, 'utf8') + loaded = await readClaudeUsageReportFile(request.cacheFile) } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return { reportText: null, migrated: false } } throw error } - const parsed: ClaudeUsagePersistedState = JSON.parse(text) + const parsed: ClaudeUsagePersistedState = loaded.state if (!Array.isArray(parsed.processedFiles) || parsed.processedFiles.length === 0) { - const validated = await parseClaudeUsageReport(text, parsed) + const validated = await parseClaudeUsageReport('', parsed, loaded.integrityVerified) return { - reportText: validated === parsed ? text : serializeClaudeUsageReport(validated), + reportText: serializeClaudeUsageReport(validated), migrated: false, reportIntegrityVerified: validated.schemaVersion === 7 } } - const validated = await parseClaudeUsageReport(text, parsed) + const validated = await parseClaudeUsageReport('', parsed, loaded.integrityVerified) const protectedInline = parsed.processedFiles.some(hasClaudeUsageProtectedCheckpoint) const state = protectedInline ? { ...validated, schemaVersion: 7 } : validated const ref = { diff --git a/src/main/claude-usage/persisted-source-migration.test.ts b/src/main/claude-usage/persisted-source-migration.test.ts new file mode 100644 index 00000000000..df5bc301bed --- /dev/null +++ b/src/main/claude-usage/persisted-source-migration.test.ts @@ -0,0 +1,40 @@ +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { + createPersistedUsageTestFixture, + type PersistedUsageTestFixture +} from './persisted-usage-test-fixture' + +vi.mock('./transcript-file-discovery', () => ({ listClaudeTranscriptFiles: vi.fn() })) +vi.mock('../usage/scan-worker/usage-scan-worker-spawn', () => ({ + scanClaudeUsageFilesViaWorker: vi.fn(), + splitUsageCacheFileViaWorker: vi.fn() +})) +let fixture: PersistedUsageTestFixture +beforeEach(async () => { + fixture = await createPersistedUsageTestFixture() +}) +afterEach(async () => { + await fixture.cleanup() +}) + +it('preserves protected inline ownership through failed migration, toggle and retry', async () => { + const source = await fixture.writeResumable() + await writeFile(fixture.reportPath, JSON.stringify(fixture.state([source]))) + await mkdir(fixture.sourceRef.path) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const first = fixture.createStore() + await first.whenLoaded() + await first.setEnabled(false) + await first.flush() + const retained = JSON.parse(await readFile(fixture.reportPath, 'utf8')) + expect(retained.processedFiles).toEqual([source]) + expect(retained.scanState.enabled).toBe(false) + await rm(fixture.sourceRef.path, { recursive: true }) + const retried = fixture.createStore() + await retried.whenLoaded() + await retried.flush() + expect(retried.getScanState()).toMatchObject({ enabled: false, hasAnyClaudeData: true }) + expect(await fixture.decodedSources()).toEqual([source]) + expect(JSON.parse(await readFile(fixture.reportPath, 'utf8')).processedFiles).toBeUndefined() +}) diff --git a/src/main/claude-usage/persisted-usage-report.ts b/src/main/claude-usage/persisted-usage-report.ts index 29e661494bd..955b6789cc6 100644 --- a/src/main/claude-usage/persisted-usage-report.ts +++ b/src/main/claude-usage/persisted-usage-report.ts @@ -1,3 +1,4 @@ +import { readClaudeUsageJson } from './source-cache-compression' import type { ClaudeUsagePersistedState } from './types' import { hasClaudeUsageProtectedCheckpoint, @@ -54,3 +55,15 @@ export function parseClaudeUsageReport( return invalidateReport(state) } } + +export async function readClaudeUsageReportFile(path: string): Promise<{ + state: ClaudeUsagePersistedState + integrityVerified: boolean +}> { + const { parsed, verified } = await readClaudeUsageJson( + path, + REPORT_DOMAIN, + false + ) + return { state: parsed, integrityVerified: verified } +} diff --git a/src/main/claude-usage/source-cache-compression.test.ts b/src/main/claude-usage/source-cache-compression.test.ts index 29e9f12c0d3..057d46693fe 100644 --- a/src/main/claude-usage/source-cache-compression.test.ts +++ b/src/main/claude-usage/source-cache-compression.test.ts @@ -1,36 +1,67 @@ -import { gzipSync } from 'node:zlib' -import { expect, it } from 'vitest' -import { - compressClaudeUsageSourceText, - decodeClaudeUsageSourceText -} from './source-cache-compression' +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { gzipSync, gunzipSync } from 'node:zlib' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { sealUsageCacheJson, verifyUsageCacheJson } from '../usage/cache/usage-cache-json-integrity' +import { readClaudeUsageJson, writeClaudeUsageJson } from './source-cache-compression' -const source = JSON.stringify({ sources: ['Unicode: 日本語 🌊'.repeat(10_000)] }) - -it('keeps small and existing plain caches readable without changing them', async () => { - const small = '{"schemaVersion":7,"sources":[]}' - expect(await compressClaudeUsageSourceText(small)).toBe(small) - expect(await decodeClaudeUsageSourceText(Buffer.from(small))).toBe(small) - expect(await decodeClaudeUsageSourceText(source)).toBe(source) +let directory: string +const domain = 'claude-usage-sources-v1' +const source = { + schemaVersion: 7, + sources: [{ path: `${'a'.repeat(4095)}😀é\ud800`, ownedDedupeKeys: ['日本語 🌊'.repeat(10_000)] }] +} +const ref = () => ({ + path: join(directory, 'sources.json'), + schemaVersion: 7, + worktreeFingerprint: null, + reuse: true +}) +beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-claude-stream-')) +}) +afterEach(async () => { + await rm(directory, { recursive: true, force: true }) }) -it.each([0, 70_001, 129 * 1024 * 1024])( - 'rejects inconsistent or excessive decoded length %i', - async (declared) => { - const saved = gzipSync('x'.repeat(70_000)) - saved.writeUInt32LE(declared, saved.length - 4) - await expect(decodeClaudeUsageSourceText(saved)).rejects.toThrow() +it('cross-reads existing protected plain and gzip text and emits the same verified material', async () => { + const original = sealUsageCacheJson(JSON.stringify(source), domain) + for (const saved of [Buffer.from(original), gzipSync(original)]) { + await writeFile(ref().path, saved) + const loaded = await readClaudeUsageJson(ref().path, domain) + expect(loaded.verified).toBe(true) + expect(loaded.parsed).toMatchObject(source) } -) - -it('bounds decompression to a forged smaller length', async () => { - const saved = gzipSync('x'.repeat(500_000)) - saved.writeUInt32LE(70_000, saved.length - 4) - await expect(decodeClaudeUsageSourceText(saved)).rejects.toThrow() + await writeClaudeUsageJson(ref(), source, domain, true) + const saved = await readFile(ref().path) + const text = saved[0] === 0x1f ? gunzipSync(saved).toString('utf8') : saved.toString('utf8') + const parsed = JSON.parse(text) + expect(verifyUsageCacheJson(text, parsed.usageIntegrity, domain)).toBe(true) + expect(parsed.sources).toEqual(source.sources) + expect((await readClaudeUsageJson(ref().path, domain)).parsed).toEqual(parsed) }) -it('rejects concatenated streams rather than accepting a partial generation', async () => { - const first = gzipSync('x'.repeat(70_000)) - const second = gzipSync('y'.repeat(70_000)) - await expect(decodeClaudeUsageSourceText(Buffer.concat([first, second]))).rejects.toThrow() +it('rejects corruption and partial generations before returning sources', async () => { + const original = sealUsageCacheJson(JSON.stringify(source), domain) + const gzip = gzipSync(original) + const forged = Buffer.from(gzip) + forged.writeUInt32LE(70_000, forged.length - 4) + for (const saved of [ + Buffer.from(original.replace('日本語', '日木語')), + Buffer.from(`${original} null`), + gzip.subarray(0, -7), + forged, + Buffer.concat([gzip, gzip]) + ]) { + await writeFile(ref().path, saved) + await expect(readClaudeUsageJson(ref().path, domain)).rejects.toThrow() + } +}) + +it('removes only its staging file when compressed publication fails', async () => { + const { mkdir } = await import('node:fs/promises') + await mkdir(ref().path) + await expect(writeClaudeUsageJson(ref(), source, domain, true)).rejects.toThrow() + expect(await readdir(directory)).toEqual(['sources.json']) }) diff --git a/src/main/claude-usage/source-cache-compression.ts b/src/main/claude-usage/source-cache-compression.ts index 71b667dd3df..d34566f4e0f 100644 --- a/src/main/claude-usage/source-cache-compression.ts +++ b/src/main/claude-usage/source-cache-compression.ts @@ -1,41 +1,126 @@ -import { promisify } from 'node:util' -import { gunzip, gzip } from 'node:zlib' +import { open, mkdir, rm, stat } from 'node:fs/promises' +import { threadId } from 'node:worker_threads' +import { dirname } from 'node:path' +import { Readable } from 'node:stream' +import { StringDecoder } from 'node:string_decoder' +import { createGzip, createGunzip } from 'node:zlib' +import { + durableWriteTempPath, + renameDurable, + removeStaleDurableWriteTempFiles, + writeTempFileDurable +} from '../filesystem/durable-file-write' +import { + protectedUsageCacheJson, + readProtectedUsageCacheJson +} from '../usage/cache/usage-cache-protected-json' +import { + writeUsageSourceCacheData, + type UsageSourceCacheRef +} from '../usage/cache/usage-source-cache-file' -const gzipAsync = promisify(gzip) -const gunzipAsync = promisify(gunzip) const MIN_COMPRESSED_BYTES = 64 * 1024 const MAX_COMPRESSED_BYTES = 128 * 1024 * 1024 -const ZLIB_CHUNK_BYTES = 256 * 1024 +const CHUNK_BYTES = 256 * 1024 -export async function compressClaudeUsageSourceText(text: string): Promise { - const bytes = Buffer.byteLength(text) - if (bytes < MIN_COMPRESSED_BYTES || bytes > MAX_COMPRESSED_BYTES) { - return text +/** Keep magic, declared length and body on the same opened generation. */ +async function* decodedSourceText(path: string): AsyncGenerator { + const handle = await open(path, 'r') + try { + const magic = Buffer.alloc(2) + await handle.read(magic, 0, 2, 0) + const gzip = magic[0] === 0x1f && magic[1] === 0x8b + let expected = 0 + if (gzip) { + const { size } = await handle.stat() + if (size < 18) { + throw new Error('Saved Claude usage gzip stream is truncated.') + } + const footer = Buffer.alloc(4) + await handle.read(footer, 0, 4, size - 4) + expected = footer.readUInt32LE(0) + if (expected < MIN_COMPRESSED_BYTES || expected > MAX_COMPRESSED_BYTES) { + throw new Error('Saved Claude usage gzip length is invalid.') + } + } + const input = handle.createReadStream({ + start: 0, + autoClose: false, + highWaterMark: CHUNK_BYTES + }) + const expanded = gzip ? input.pipe(createGunzip({ chunkSize: CHUNK_BYTES })) : input + input.on('error', (error) => expanded.destroy(error)) + const decoder = new StringDecoder('utf8') + let bytes = 0 + try { + for await (const chunk of expanded) { + bytes += chunk.byteLength + if (gzip && (bytes > expected || bytes > MAX_COMPRESSED_BYTES)) { + throw new Error('Saved Claude usage compression length is invalid.') + } + yield decoder.write(chunk) + } + if (gzip && bytes !== expected) { + throw new Error('Saved Claude usage compression length is invalid.') + } + const remaining = decoder.end() + if (remaining) { + yield remaining + } + } finally { + input.destroy() + expanded.destroy() + } + } finally { + await handle.close() } - const compressed = await gzipAsync(text, { level: 1, chunkSize: ZLIB_CHUNK_BYTES }) - return compressed.byteLength < bytes ? compressed : text } -export async function decodeClaudeUsageSourceText(saved: string | Buffer): Promise { - if (typeof saved === 'string') { - return saved +export async function readClaudeUsageJson( + path: string, + domain: string, + strict = true +): Promise<{ parsed: T; verified: boolean }> { + return readProtectedUsageCacheJson(decodedSourceText(path), domain, strict) +} + +export async function writeClaudeUsageJson( + ref: UsageSourceCacheRef, + value: unknown, + domain: string, + sealed: boolean +): Promise { + const material = protectedUsageCacheJson(value, domain, sealed) + if (material.bytes < MIN_COMPRESSED_BYTES || material.bytes > MAX_COMPRESSED_BYTES) { + await writeUsageSourceCacheData(ref, material.encode()) + return } - if (saved[0] !== 0x1f || saved[1] !== 0x8b) { - return saved.toString('utf8') + await mkdir(dirname(ref.path), { recursive: true }) + await removeStaleDurableWriteTempFiles(ref.path) + const candidate = durableWriteTempPath(ref.path, threadId > 0 ? String(threadId) : undefined) + async function* gzipChunks(): AsyncGenerator { + const input = Readable.from(material.encode()) + const compressed = input.pipe(createGzip({ level: 1, chunkSize: CHUNK_BYTES })) + input.on('error', (error) => compressed.destroy(error)) + try { + yield* compressed + } finally { + input.destroy() + compressed.destroy() + } } - if (saved.length < 18) { - throw new Error('Saved Claude usage gzip stream is truncated.') + let published = false + try { + await writeTempFileDurable(candidate, gzipChunks(), 0o600) + if ((await stat(candidate)).size < material.bytes) { + await renameDurable(candidate, ref.path) + published = true + } else { + await writeUsageSourceCacheData(ref, material.encode()) + } + } finally { + if (!published) { + await rm(candidate, { force: true }).catch(() => {}) + } } - const bytes = saved.readUInt32LE(saved.length - 4) - if (bytes < MIN_COMPRESSED_BYTES || bytes > MAX_COMPRESSED_BYTES) { - throw new Error('Saved Claude usage gzip length is invalid.') - } - const decoded = await gunzipAsync(saved, { - maxOutputLength: bytes, - chunkSize: ZLIB_CHUNK_BYTES - }) - if (decoded.byteLength !== bytes) { - throw new Error('Saved Claude usage compression length is invalid.') - } - return decoded.toString('utf8') } diff --git a/src/main/claude-usage/store.ts b/src/main/claude-usage/store.ts index a6cda7d260b..e634443983c 100644 --- a/src/main/claude-usage/store.ts +++ b/src/main/claude-usage/store.ts @@ -22,7 +22,11 @@ import { buildBreakdown, buildDaily, buildSummary } from './claude-usage-report- import { buildRecentSessions } from './claude-usage-session-rows' import type { AutomationUsageLookupInput } from './claude-usage-automation-attribution' import { resolveAutomationRunUsage } from './claude-usage-automation-attribution' -import { parseClaudeUsageReport, serializeClaudeUsageReport } from './persisted-usage-report' +import { + parseClaudeUsageReport, + readClaudeUsageReportFile, + serializeClaudeUsageReport +} from './persisted-usage-report' // Pre-v6 totals lack stable fork ownership or the 1-hour cache-write split and must be rescanned. // v7 stores protected column checkpoints on the worker and a separately protected report. @@ -75,6 +79,7 @@ export class ClaudeUsageStore extends UsageProviderStoreLifecycle< createDefaultState: getDefaultState, normalizeState: normalizePersistedState, parseReport: parseClaudeUsageReport, + readFallbackCache: readClaudeUsageReportFile, serializeReport: serializeClaudeUsageReport, providerId: 'claude', sourceKey: 'processedFiles', diff --git a/src/main/claude/agent-view/agent-view-service.test.ts b/src/main/claude/agent-view/agent-view-service.test.ts index b0f56f08e6a..a3ba01c8832 100644 --- a/src/main/claude/agent-view/agent-view-service.test.ts +++ b/src/main/claude/agent-view/agent-view-service.test.ts @@ -10,7 +10,7 @@ import { captureLoginShellEnvironment, resetLoginShellEnvironmentCacheForTests, resolveLoginShellEnvironment -} from '../../startup/login-shell-environment' +} from '../../startup/shell-environment/login-shell-environment' const roots: string[] = [] afterEach(async () => { diff --git a/src/main/claude/agent-view/agent-view-service.ts b/src/main/claude/agent-view/agent-view-service.ts index 3cb6e66cd35..7d8945fc4f1 100644 --- a/src/main/claude/agent-view/agent-view-service.ts +++ b/src/main/claude/agent-view/agent-view-service.ts @@ -7,7 +7,7 @@ import { getAgentLaunchExecutableName } from '../../../shared/agent-launch/start import { withTimeout } from '../../../shared/promise-timeout-fallback' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { listClaudeProfileHomesAsync } from '../../claude-accounts/profiles/claude-profile-homes' -import { resolveLoginShellEnvironment } from '../../startup/login-shell-environment' +import { resolveLoginShellEnvironment } from '../../startup/shell-environment/login-shell-environment' import { reconcileClaudeAgentViewConfig } from './agent-view-config' import { ensureClaudeAgentViewPluginAsync } from './agent-view-plugin' diff --git a/src/main/claude/claude-background-task-frames.ts b/src/main/claude/background-tasks/claude-background-task-frames.ts similarity index 91% rename from src/main/claude/claude-background-task-frames.ts rename to src/main/claude/background-tasks/claude-background-task-frames.ts index c2948a166e9..2527794906b 100644 --- a/src/main/claude/claude-background-task-frames.ts +++ b/src/main/claude/background-tasks/claude-background-task-frames.ts @@ -1,15 +1,13 @@ -import { classifyClaudeBackgroundTaskKind } from '../../shared/claude-background-task-kind' import type { AgentSessionBackgroundTask, AgentSessionBackgroundTaskRunState -} from '../../shared/agent-session/agent-session-background-task-wire' -import { ownRetainedString } from '../../shared/own-retained-string' +} from '../../../shared/agent-session/agent-session-background-task-wire' +import { ownRetainedString } from '../../../shared/own-retained-string' const MAX_TASK_ID_LENGTH = 512 const MAX_TASK_TEXT_LENGTH = 512 export type ClaudeBackgroundTaskKind = AgentSessionBackgroundTask['kind'] -export { classifyClaudeBackgroundTaskKind } export function record(value: unknown): Record | null { return typeof value === 'object' && value !== null ? (value as Record) : null diff --git a/src/main/claude/claude-background-task-identity.ts b/src/main/claude/background-tasks/claude-background-task-identity.ts similarity index 85% rename from src/main/claude/claude-background-task-identity.ts rename to src/main/claude/background-tasks/claude-background-task-identity.ts index 2d19b843dde..a9eed16b4b2 100644 --- a/src/main/claude/claude-background-task-identity.ts +++ b/src/main/claude/background-tasks/claude-background-task-identity.ts @@ -1,8 +1,8 @@ -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' -import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' -import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types' +import { isBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types' +import type { StructuredAgentSessionLifecycleJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' export type ClaudeBackgroundTaskDescriptor = { identity: AgentJournalItemIdentity diff --git a/src/main/claude/claude-background-task-memory.ts b/src/main/claude/background-tasks/claude-background-task-memory.ts similarity index 97% rename from src/main/claude/claude-background-task-memory.ts rename to src/main/claude/background-tasks/claude-background-task-memory.ts index 39996ab903d..b9f64dec4f4 100644 --- a/src/main/claude/claude-background-task-memory.ts +++ b/src/main/claude/background-tasks/claude-background-task-memory.ts @@ -1,4 +1,4 @@ -import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row' +import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row' import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle' const MAX_GENERATION_ENTRIES = 512 diff --git a/src/main/claude/claude-background-task-resume.test.ts b/src/main/claude/background-tasks/claude-background-task-resume.test.ts similarity index 100% rename from src/main/claude/claude-background-task-resume.test.ts rename to src/main/claude/background-tasks/claude-background-task-resume.test.ts diff --git a/src/main/claude/claude-background-task-roster-merge.ts b/src/main/claude/background-tasks/claude-background-task-roster-merge.ts similarity index 100% rename from src/main/claude/claude-background-task-roster-merge.ts rename to src/main/claude/background-tasks/claude-background-task-roster-merge.ts diff --git a/src/main/claude/claude-background-task-roster.ts b/src/main/claude/background-tasks/claude-background-task-roster.ts similarity index 87% rename from src/main/claude/claude-background-task-roster.ts rename to src/main/claude/background-tasks/claude-background-task-roster.ts index 80e89a514e6..39eeb12c58f 100644 --- a/src/main/claude/claude-background-task-roster.ts +++ b/src/main/claude/background-tasks/claude-background-task-roster.ts @@ -1,12 +1,7 @@ import type { ClaudeTaskInvocations } from './claude-task-invocations' -import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row' -import { - classifyClaudeBackgroundTaskKind, - record, - taskDescription, - taskId, - taskName -} from './claude-background-task-frames' +import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row' +import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind' +import { record, taskDescription, taskId, taskName } from './claude-background-task-frames' import type { ClaudeBackgroundTaskChange, ClaudeBackgroundTaskRow diff --git a/src/main/claude/claude-background-task-row-journal.ts b/src/main/claude/background-tasks/claude-background-task-row-journal.ts similarity index 83% rename from src/main/claude/claude-background-task-row-journal.ts rename to src/main/claude/background-tasks/claude-background-task-row-journal.ts index 3ea4197ff06..a7dca1e29e6 100644 --- a/src/main/claude/claude-background-task-row-journal.ts +++ b/src/main/claude/background-tasks/claude-background-task-row-journal.ts @@ -1,29 +1,23 @@ -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { backgroundTaskJournalBody } from '../../shared/native-chat/input/native-chat-background-task-row' -import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import { backgroundTaskJournalBody as claudeBackgroundTaskBody } from '../../../shared/native-chat/input/native-chat-background-task-row' +import { isBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types' import type { StructuredAgentSessionEventSink, StructuredAgentSessionSinkAdmission -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' +} from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { StructuredAgentSessionLifecycleJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate' +import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' +import { estimateStructuredAgentSessionItemBytes } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate' import { claudeBackgroundTaskIdentity, resolveClaudeBackgroundTaskIdentity } from './claude-background-task-identity' -export { - claudeBackgroundTaskIdentity, - resolveClaudeBackgroundTaskIdentity -} from './claude-background-task-identity' const MAX_RESOLVED_TASK_IDENTITIES = 512 const ADMITTED: StructuredAgentSessionSinkAdmission = { accepted: true } -export const claudeBackgroundTaskBody = backgroundTaskJournalBody - export class ClaudeBackgroundTaskIdentityResolver { private journal: StructuredAgentSessionLifecycleJournal | null = null private epoch: string | null = null diff --git a/src/main/claude/claude-background-task-row-lifecycle.ts b/src/main/claude/background-tasks/claude-background-task-row-lifecycle.ts similarity index 94% rename from src/main/claude/claude-background-task-row-lifecycle.ts rename to src/main/claude/background-tasks/claude-background-task-row-lifecycle.ts index 112157ec7d7..b3772d0b8c7 100644 --- a/src/main/claude/claude-background-task-row-lifecycle.ts +++ b/src/main/claude/background-tasks/claude-background-task-row-lifecycle.ts @@ -1,13 +1,13 @@ import type { ClaudeTaskInvocation } from './claude-task-invocations' -import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types' import { canReplaceBackgroundTaskState, isSettledBackgroundTaskState -} from '../../shared/native-chat/input/native-chat-background-task-row' -import type { NativeChatBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' -import type { ClaudeSubagentIds } from './claude-subagent-id-aliases' +} from '../../../shared/native-chat/input/native-chat-background-task-row' +import type { NativeChatBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types' +import type { ClaudeSubagentIds } from '../subagents/claude-subagent-id-aliases' +import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind' import { - classifyClaudeBackgroundTaskKind, liveClaudeTaskRunState, record, taskAliasId, diff --git a/src/main/claude/claude-background-task-row-test-support.ts b/src/main/claude/background-tasks/claude-background-task-row-test-support.ts similarity index 84% rename from src/main/claude/claude-background-task-row-test-support.ts rename to src/main/claude/background-tasks/claude-background-task-row-test-support.ts index 000a8cd21c8..f5e809e701e 100644 --- a/src/main/claude/claude-background-task-row-test-support.ts +++ b/src/main/claude/background-tasks/claude-background-task-row-test-support.ts @@ -1,10 +1,10 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session/journal/agent-session-journal-types' import { vi } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { NativeChatBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import type { NativeChatBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types' +import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { ClaudeBackgroundTaskRows } from './claude-background-task-rows' /** Lifecycle frames captured from the reported failure. */ diff --git a/src/main/claude/claude-background-task-row-writer.ts b/src/main/claude/background-tasks/claude-background-task-row-writer.ts similarity index 95% rename from src/main/claude/claude-background-task-row-writer.ts rename to src/main/claude/background-tasks/claude-background-task-row-writer.ts index b4551e1e480..df3bb012a16 100644 --- a/src/main/claude/claude-background-task-row-writer.ts +++ b/src/main/claude/background-tasks/claude-background-task-row-writer.ts @@ -1,11 +1,11 @@ import { CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES } from './claude-background-task-frames' import type { ClaudeTaskInvocations } from './claude-task-invocations' import { claudeBackgroundTaskToolUseId } from './claude-background-task-row-lifecycle' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' +import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope' import type { StructuredAgentSessionEventSink, StructuredAgentSessionSinkAdmission -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +} from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle' import { ClaudeBackgroundTaskIdentityResolver, diff --git a/src/main/claude/claude-background-task-rows.ts b/src/main/claude/background-tasks/claude-background-task-rows.ts similarity index 96% rename from src/main/claude/claude-background-task-rows.ts rename to src/main/claude/background-tasks/claude-background-task-rows.ts index bc5dca47ebc..c76dda5258f 100644 --- a/src/main/claude/claude-background-task-rows.ts +++ b/src/main/claude/background-tasks/claude-background-task-rows.ts @@ -1,8 +1,8 @@ import { ClaudeTaskInvocations } from './claude-task-invocations' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { BoundedMap } from '../../shared/bounded-map' +import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row' +import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { BoundedMap } from '../../../shared/bounded-map' import { record, taskAliasId, @@ -31,7 +31,7 @@ import { } from './claude-background-task-row-writer' import { observeClaudeBackgroundTaskStart } from './claude-background-task-start' import { observeOwnedClaudeBackgroundTaskRoster } from './claude-background-task-roster' -import { ClaudeSubagentIds } from './claude-subagent-id-aliases' +import { ClaudeSubagentIds } from '../subagents/claude-subagent-id-aliases' import { ClaudeOverflowTerminalRows } from './claude-overflow-terminal-rows' const MAX_TASK_ROWS = 64 diff --git a/src/main/claude/claude-background-task-start.ts b/src/main/claude/background-tasks/claude-background-task-start.ts similarity index 91% rename from src/main/claude/claude-background-task-start.ts rename to src/main/claude/background-tasks/claude-background-task-start.ts index 76f6ad07b1b..4041d8d1147 100644 --- a/src/main/claude/claude-background-task-start.ts +++ b/src/main/claude/background-tasks/claude-background-task-start.ts @@ -1,5 +1,5 @@ -import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row' -import { classifyClaudeBackgroundTaskKind } from './claude-background-task-frames' +import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row' +import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind' import { claudeBackgroundTaskToolUseId, isClaudeBackgroundTranscriptTask, @@ -10,7 +10,7 @@ import { ensureClaudeBackgroundTaskRowSlot, type ClaudeBackgroundTaskLedgers } from './claude-background-task-memory' -import { isClaudeSubagentTask } from './claude-subagent-task-frames' +import { isClaudeSubagentTask } from '../subagents/claude-subagent-task-frames' type ClaudeBackgroundTaskStartInput = { id: string diff --git a/src/main/claude/background-tasks/claude-background-task-terminal-frames.test.ts b/src/main/claude/background-tasks/claude-background-task-terminal-frames.test.ts new file mode 100644 index 00000000000..65ade3bc1e6 --- /dev/null +++ b/src/main/claude/background-tasks/claude-background-task-terminal-frames.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { + FORWARDED_TOOL, + harness, + ORPHAN_FAILED_NOTIFICATION, + START_BASH +} from './claude-background-task-row-test-support' + +describe('claude background task terminal frames', () => { + it('does not resurrect an orphan outcome that named its own parent tool', () => { + const { rows, items, latest } = harness([ + FORWARDED_TOOL, + ORPHAN_FAILED_NOTIFICATION.tool_use_id + ]) + rows.observe(ORPHAN_FAILED_NOTIFICATION) + rows.observe({ + ...START_BASH, + task_id: ORPHAN_FAILED_NOTIFICATION.task_id, + tool_use_id: ORPHAN_FAILED_NOTIFICATION.tool_use_id + }) + expect(items).toHaveLength(1) + expect(latest()).toMatchObject({ state: 'blocked' }) + }) +}) diff --git a/src/main/claude/claude-background-task-tracker.ts b/src/main/claude/background-tasks/claude-background-task-tracker.ts similarity index 96% rename from src/main/claude/claude-background-task-tracker.ts rename to src/main/claude/background-tasks/claude-background-task-tracker.ts index 6b215b6ad9d..0d96e10072e 100644 --- a/src/main/claude/claude-background-task-tracker.ts +++ b/src/main/claude/background-tasks/claude-background-task-tracker.ts @@ -2,9 +2,9 @@ import type { AgentSessionBackgroundTask, AgentSessionBackgroundTaskRunState, AgentSessionBackgroundTaskState -} from '../../shared/agent-session/agent-session-background-task-wire' +} from '../../../shared/agent-session/agent-session-background-task-wire' +import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind' import { - classifyClaudeBackgroundTaskKind, liveClaudeTaskRunState, record, taskDescription, @@ -21,14 +21,6 @@ import { } from './claude-settled-background-tasks' import { combineClaudeBackgroundTaskRoster } from './claude-background-task-roster-merge' -export { - classifyClaudeBackgroundTaskKind, - isBoundedClaudeTaskId, - taskDescription as claudeTaskDescription, - taskId as claudeTaskId -} from './claude-background-task-frames' -export type { ClaudeBackgroundTaskKind } from './claude-background-task-frames' - // Bound terminal IDs without evicting live tasks. const MAX_TERMINAL_TASK_IDS = 256 export type ClaudeGoalBackgroundWork = 'live' | 'unverifiable' | 'exited' diff --git a/src/main/claude/claude-overflow-terminal-rows.ts b/src/main/claude/background-tasks/claude-overflow-terminal-rows.ts similarity index 100% rename from src/main/claude/claude-overflow-terminal-rows.ts rename to src/main/claude/background-tasks/claude-overflow-terminal-rows.ts diff --git a/src/main/claude/claude-settled-background-tasks.ts b/src/main/claude/background-tasks/claude-settled-background-tasks.ts similarity index 98% rename from src/main/claude/claude-settled-background-tasks.ts rename to src/main/claude/background-tasks/claude-settled-background-tasks.ts index 80feadc3d07..1add242b3d8 100644 --- a/src/main/claude/claude-settled-background-tasks.ts +++ b/src/main/claude/background-tasks/claude-settled-background-tasks.ts @@ -3,7 +3,7 @@ import type { AgentSessionBackgroundTask, AgentSessionBackgroundTaskRunState -} from '../../shared/agent-session/agent-session-background-task-wire' +} from '../../../shared/agent-session/agent-session-background-task-wire' const MAX_RETAINED_TASKS = 256 diff --git a/src/main/claude/claude-task-invocations.ts b/src/main/claude/background-tasks/claude-task-invocations.ts similarity index 100% rename from src/main/claude/claude-task-invocations.ts rename to src/main/claude/background-tasks/claude-task-invocations.ts diff --git a/src/main/claude/claude-agent-sdk-exit-proof.ts b/src/main/claude/child-process/claude-agent-sdk-exit-proof.ts similarity index 96% rename from src/main/claude/claude-agent-sdk-exit-proof.ts rename to src/main/claude/child-process/claude-agent-sdk-exit-proof.ts index 7587f8798fa..19801279fb8 100644 --- a/src/main/claude/claude-agent-sdk-exit-proof.ts +++ b/src/main/claude/child-process/claude-agent-sdk-exit-proof.ts @@ -2,15 +2,15 @@ import type { ChildProcess } from 'node:child_process' import { terminateDescendantSnapshotWithVerdict, type DescendantTreeVerdict -} from '../pty/process-retirement/pty-descendant-exit-verification' +} from '../../pty/process-retirement/pty-descendant-exit-verification' import { captureDescendantSnapshot, type DescendantSnapshot -} from '../pty/process-retirement/pty-descendant-termination' -import { terminateWindowsProcessTree } from '../pty/process-retirement/windows-process-tree-kill' +} from '../../pty/process-retirement/pty-descendant-termination' +import { terminateWindowsProcessTree } from '../../pty/process-retirement/windows-process-tree-kill' import { mergeClaudeDescendantSnapshots } from './claude-child-tree-snapshot' import { terminateClaudeRoot } from './claude-child-root-termination' -import { killProviderWriter } from '../provider-process/provider-process-teardown' +import { killProviderWriter } from '../../provider-process/provider-process-teardown' import { proveClaudeChildExitWithReaper, type ClaudeChildExitProofInput diff --git a/src/main/claude/child-process/claude-agent-sdk-process-spawn.test.ts b/src/main/claude/child-process/claude-agent-sdk-process-spawn.test.ts new file mode 100644 index 00000000000..289fbe4367e --- /dev/null +++ b/src/main/claude/child-process/claude-agent-sdk-process-spawn.test.ts @@ -0,0 +1,72 @@ +import { createFakePipedChild } from '../../../shared/__fixtures__/fake-spawned-child' +import { describe, expect, it, vi } from 'vitest' +import type { SpawnOptions as SdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' +import type { PipedProcessSpawner, ProcessSpec } from '@orca/process-host/process-spec' + +import type * as ProviderSupervisor from '../../provider-process/provider-process-supervisor' + +import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn' + +vi.mock('../../provider-process/provider-process-supervisor', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, createProviderSpawnSpec: vi.fn(actual.createProviderSpawnSpec) } +}) + +function fakeSpawn() { + const child = createFakePipedChild() + const specs: ProcessSpec[] = [] + const spawnImpl: PipedProcessSpawner = (spec) => { + specs.push(spec) + return child + } + return { child, spawnImpl, specs } +} + +function sdkOptions(overrides: Partial = {}): SdkSpawnOptions { + return { + command: '/usr/local/bin/claude', + args: ['--output-format', 'stream-json'], + cwd: '/work/repo', + env: { PATH: '/usr/bin', CLAUDE_CONFIG_DIR: '/accounts/one', UNSET: undefined }, + signal: new AbortController().signal, + ...overrides + } +} + +describe('claude agent SDK process spawn', () => { + it('keeps native chat identity after SDK and configured environment defaults', () => { + const process = fakeSpawn() + createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( + sdkOptions({ + env: { + CLAUDE_CODE_ENTRYPOINT: 'sdk-ts', + claude_code_entrypoint: 'account', + PATH: 'C:\\bin' + } + }) + ) + expect(process.specs[0]?.env).toMatchObject({ CLAUDE_CODE_ENTRYPOINT: 'orca', PATH: 'C:\\bin' }) + expect( + Object.keys(process.specs[0]?.env ?? {}).filter( + (key) => key.toUpperCase() === 'CLAUDE_CODE_ENTRYPOINT' + ) + ).toEqual(['CLAUDE_CODE_ENTRYPOINT']) + }) + + it('preserves a Windows .cmd shim and its arguments for the host spawner', () => { + const process = fakeSpawn() + createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( + sdkOptions({ + command: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd', + args: ['--setting-sources=user,project,local', '--session-id', 'a b&c'] + }) + ) + + expect(process.specs).toEqual([ + expect.objectContaining({ + program: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd', + args: ['--setting-sources=user,project,local', '--session-id', 'a b&c'] + }) + ]) + }) +}) diff --git a/src/main/claude/claude-agent-sdk-process-spawn.ts b/src/main/claude/child-process/claude-agent-sdk-process-spawn.ts similarity index 95% rename from src/main/claude/claude-agent-sdk-process-spawn.ts rename to src/main/claude/child-process/claude-agent-sdk-process-spawn.ts index 71b6adcd9e3..68d3fe0a1e5 100644 --- a/src/main/claude/claude-agent-sdk-process-spawn.ts +++ b/src/main/claude/child-process/claude-agent-sdk-process-spawn.ts @@ -1,4 +1,4 @@ -import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' +import { withOrcaClaudeChatEntrypoint } from '../../../shared/agent-launch/startup/claude-chat-entrypoint' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type { SpawnOptions as ClaudeAgentSdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' @@ -6,7 +6,7 @@ import { spawnProcess } from '@orca/process-host' import { spawnManagedProviderProcess, type ManagedProviderProcess -} from '../provider-process/managed-provider-process' +} from '../../provider-process/managed-provider-process' import { claudeChildClosePolicy, claudeChildCloseProven } from './claude-child-exit-proof-ladder' export type ClaudeCodeProcessSpawn = { diff --git a/src/main/claude/claude-child-exit-proof-ladder.ts b/src/main/claude/child-process/claude-child-exit-proof-ladder.ts similarity index 84% rename from src/main/claude/claude-child-exit-proof-ladder.ts rename to src/main/claude/child-process/claude-child-exit-proof-ladder.ts index e62fc260e8f..50bdbf2817c 100644 --- a/src/main/claude/claude-child-exit-proof-ladder.ts +++ b/src/main/claude/child-process/claude-child-exit-proof-ladder.ts @@ -1,9 +1,9 @@ -import type { ManagedProviderProcess } from '../provider-process/managed-provider-process' -import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../provider-process/provider-process-supervisor' +import type { ManagedProviderProcess } from '../../provider-process/managed-provider-process' +import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../../provider-process/provider-process-supervisor' import type { ProviderProcessClosePolicy, ProviderProcessCloseResult -} from '../provider-process/provider-process-close' +} from '../../provider-process/provider-process-close' import type { ClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof' export const GRACEFUL_EXIT_MS = 1_500 diff --git a/src/main/claude/claude-child-process-environment.test.ts b/src/main/claude/child-process/claude-child-process-environment.test.ts similarity index 100% rename from src/main/claude/claude-child-process-environment.test.ts rename to src/main/claude/child-process/claude-child-process-environment.test.ts diff --git a/src/main/claude/claude-child-process-environment.ts b/src/main/claude/child-process/claude-child-process-environment.ts similarity index 89% rename from src/main/claude/claude-child-process-environment.ts rename to src/main/claude/child-process/claude-child-process-environment.ts index 1df9100bef9..5272d7e00a1 100644 --- a/src/main/claude/claude-child-process-environment.ts +++ b/src/main/claude/child-process/claude-child-process-environment.ts @@ -1,12 +1,12 @@ import { CLAUDE_AUTH_ENV_VARS, applyClaudeEnvPatch -} from '../claude-accounts/runtime-auth/environment' -import { stripInheritedAgentSessionEnv } from '../../shared/agent-launch/startup/parent-agent-session-env' +} from '../../claude-accounts/runtime-auth/environment' +import { stripInheritedAgentSessionEnv } from '../../../shared/agent-launch/startup/parent-agent-session-env' import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, NATIVE_CHAT_SCRATCH_DIR_ENV -} from '../native-chat/native-chat-visuals-delivery' +} from '../../native-chat/conversation-files/native-chat-visuals-delivery' function cloneProcessEnv(source: NodeJS.ProcessEnv): Record { const env: Record = {} diff --git a/src/main/claude/claude-child-root-termination.ts b/src/main/claude/child-process/claude-child-root-termination.ts similarity index 100% rename from src/main/claude/claude-child-root-termination.ts rename to src/main/claude/child-process/claude-child-root-termination.ts diff --git a/src/main/claude/claude-child-tree-snapshot.ts b/src/main/claude/child-process/claude-child-tree-snapshot.ts similarity index 96% rename from src/main/claude/claude-child-tree-snapshot.ts rename to src/main/claude/child-process/claude-child-tree-snapshot.ts index 632e1ef2829..6a080d87bd1 100644 --- a/src/main/claude/claude-child-tree-snapshot.ts +++ b/src/main/claude/child-process/claude-child-tree-snapshot.ts @@ -1,4 +1,4 @@ -import type { DescendantSnapshot } from '../pty/process-retirement/pty-descendant-termination' +import type { DescendantSnapshot } from '../../pty/process-retirement/pty-descendant-termination' // Non-atomic scans may omit live rows; retain them, but reject any PID whose identity changed. function mergeRowsByPid( diff --git a/src/main/claude/claude-startup-answer-observation.ts b/src/main/claude/child-process/claude-startup-answer-observation.ts similarity index 95% rename from src/main/claude/claude-startup-answer-observation.ts rename to src/main/claude/child-process/claude-startup-answer-observation.ts index ec460aa09eb..25c9bf23a05 100644 --- a/src/main/claude/claude-startup-answer-observation.ts +++ b/src/main/claude/child-process/claude-startup-answer-observation.ts @@ -1,5 +1,5 @@ import { StringDecoder } from 'node:string_decoder' -import { createIncrementalNdjsonFramer } from '../../shared/main-process-ndjson-framer' +import { createIncrementalNdjsonFramer } from '../../../shared/main-process-ndjson-framer' // Unescaped quotes occur only as JSON structure, so other records skip this second parse. const FAILED_RESULT_TOKENS = [/"type"\s*:\s*"result"/, /"is_error"\s*:\s*true/] diff --git a/src/main/claude/claude-agent-wait-calls.ts b/src/main/claude/child-work/claude-agent-wait-calls.ts similarity index 81% rename from src/main/claude/claude-agent-wait-calls.ts rename to src/main/claude/child-work/claude-agent-wait-calls.ts index 62ab8fb5184..2814176fde7 100644 --- a/src/main/claude/claude-agent-wait-calls.ts +++ b/src/main/claude/child-work/claude-agent-wait-calls.ts @@ -1,10 +1,10 @@ -import { BoundedMap } from '../../shared/bounded-map' -import { runsOrcaOrchestrationWait } from '../../shared/orca-cli-invocations' +import { BoundedMap } from '../../../shared/bounded-map' +import { runsOrcaOrchestrationWait } from '../../../shared/orca-cli-invocations' import { claudeRecord, claudeToolUses, readClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' +} from '../structured/journal/claude-structured-item-translation' /** Bash calls that block on `orca orchestration check --wait`, by tool_use_id, until their background task starts. */ export class ClaudeAgentWaitCalls { diff --git a/src/main/claude/claude-child-work-decoder.test.ts b/src/main/claude/child-work/claude-child-work-decoder.test.ts similarity index 100% rename from src/main/claude/claude-child-work-decoder.test.ts rename to src/main/claude/child-work/claude-child-work-decoder.test.ts diff --git a/src/main/claude/claude-child-work-decoder.ts b/src/main/claude/child-work/claude-child-work-decoder.ts similarity index 96% rename from src/main/claude/claude-child-work-decoder.ts rename to src/main/claude/child-work/claude-child-work-decoder.ts index d155db75b49..6de7eebff81 100644 --- a/src/main/claude/claude-child-work-decoder.ts +++ b/src/main/claude/child-work/claude-child-work-decoder.ts @@ -1,9 +1,9 @@ // Roster changes, turn endings and spawn results cannot settle a child. -import { ClaudeTaskInvocations } from './claude-task-invocations' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { ClaudeTaskInvocations } from '../background-tasks/claude-task-invocations' +import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind' import { - classifyClaudeBackgroundTaskKind, liveClaudeTaskRunState, record, taskAliasId, @@ -13,8 +13,8 @@ import { taskText, taskUsageTotalTokens, terminalClaudeTaskRunState -} from './claude-background-task-frames' -import { claudeStartedTaskKind } from './claude-subagent-task-frames' +} from '../background-tasks/claude-background-task-frames' +import { claudeStartedTaskKind } from '../subagents/claude-subagent-task-frames' import { ClaudeAgentWaitCalls } from './claude-agent-wait-calls' import { claudeChildWorkOutcome, diff --git a/src/main/claude/child-work/claude-child-work-evidence.test.ts b/src/main/claude/child-work/claude-child-work-evidence.test.ts new file mode 100644 index 00000000000..d54119516ce --- /dev/null +++ b/src/main/claude/child-work/claude-child-work-evidence.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { claudeChildOperation } from './claude-child-work-evidence' + +describe('Claude child operation evidence', () => { + it("carries the model the subagent's own message ran on", () => { + const frame = { + type: 'assistant', + session_id: 'provider-1', + uuid: 'uuid-1', + parent_tool_use_id: 'toolu_spawn', + message: { + role: 'assistant', + model: 'claude-sonnet-5-5', + content: [{ type: 'tool_use', id: 'toolu_read', name: 'Read', input: {} }] + } + } + const evidence = claudeChildOperation( + frame, + () => ({ agentId: 'agent-1', openTool: null }), + 100 + ) + expect(evidence).toEqual([ + expect.objectContaining({ type: 'operation', childId: 'agent-1', model: 'claude-sonnet-5-5' }) + ]) + }) +}) diff --git a/src/main/claude/claude-child-work-evidence.ts b/src/main/claude/child-work/claude-child-work-evidence.ts similarity index 84% rename from src/main/claude/claude-child-work-evidence.ts rename to src/main/claude/child-work/claude-child-work-evidence.ts index 7110cd50489..25d20f281e2 100644 --- a/src/main/claude/claude-child-work-evidence.ts +++ b/src/main/claude/child-work/claude-child-work-evidence.ts @@ -1,26 +1,24 @@ -import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../shared/orca-cli-invocations' +import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../../shared/orca-cli-invocations' import type { AgentChildWorkKind, AgentChildWorkOperation, AgentChildWorkOutcome -} from '../../shared/agent-status/child-work/agent-status-child-work' +} from '../../../shared/agent-status/child-work/agent-status-child-work' import type { AgentChildWorkEvidence, AgentChildWorkLiveObservation -} from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { taskText, taskUsageTotalTokens } from './claude-background-task-frames' -import type { - ClaudeSession, - ClaudeStructuredSessionEvent -} from './structured/claude-structured-session-state' -import { deriveToolInputPreview } from '../../shared/agent-hook-listener/tool-input-preview' +} from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { taskText, taskUsageTotalTokens } from '../background-tasks/claude-background-task-frames' +import type { ClaudeSession } from '../structured/claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../structured/claude-structured-session-event' +import { deriveToolInputPreview } from '../../../shared/agent-hook-listener/tool-input-preview' import { claudeRecord, claudeToolResultId, claudeToolUses, readClaudeMessageEnvelope, type ClaudeToolUse -} from './structured/journal/claude-structured-item-translation' +} from '../structured/journal/claude-structured-item-translation' export type EndedClaudeTask = { run: string | undefined @@ -154,6 +152,7 @@ export function claudeChildOperation( } const { agentId, openTool } = activityOf(parentRef) const input = openTool ? deriveToolInputPreview(openTool.name, openTool.input) : undefined + const model = claudeChildMessageModel(message) return [ { type: 'operation', @@ -161,11 +160,18 @@ export function claudeChildOperation( childId: agentId, operation: openTool ? { toolName: openTool.name, ...(input ? { input } : {}), basis: 'open', observedAt } - : null + : null, + ...(model ? { model } : {}) } ] } +/** Claude names the model on each assistant message; `` marks Claude Code's own repair text. */ +function claudeChildMessageModel(frame: Record): string | undefined { + const model = frame.type === 'assistant' ? claudeRecord(frame.message)?.model : undefined + return typeof model === 'string' && model.trim() && model !== '' ? model : undefined +} + /** Waiting requires both a written journal card and a registry request still awaiting an answer. */ function claudeWaitingChildIds( session: Pick diff --git a/src/main/claude/claude-agent-sdk-contract-pins.test.ts b/src/main/claude/claude-agent-sdk-contract-pins.test.ts deleted file mode 100644 index d48e13e014e..00000000000 --- a/src/main/claude/claude-agent-sdk-contract-pins.test.ts +++ /dev/null @@ -1,317 +0,0 @@ -import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { - query, - type CanUseTool, - type Options, - type SDKUserMessage, - type SpawnedProcess as SdkSpawnedProcess, - type SpawnOptions as SdkSpawnOptions -} from '@anthropic-ai/claude-agent-sdk' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { spawnProcess } from '@orca/process-host' -import { ClaudePromptRegistry } from './claude-prompt-registry' -import { claudeLaunchPermissions } from './structured/claude-structured-inbound-control' -import { claudeStructuredPermissionOptions } from './structured/launch/claude-structured-launch-resolution' - -// Exercise the real SDK against a scripted CLI to detect protocol and spawn-contract drift. - -const FAKE_CLI = join(__dirname, '__fixtures__', 'claude-agent-sdk-scripted-cli.mjs') -const SESSION_ID = '5348c19f-6a54-4c2e-9c68-9c2b1a3d4e5f' - -const RESULT_FRAME = { - type: 'result', - subtype: 'success', - is_error: false, - duration_ms: 1, - duration_api_ms: 1, - num_turns: 1, - result: 'ok', - session_id: SESSION_ID, - total_cost_usd: 0, - usage: { input_tokens: 1, output_tokens: 1 }, - uuid: 'uuid-result-1' -} - -type ScenarioStep = Record -type SpawnSeen = { - command: string - args: string[] - cwd: string | undefined - env: Record -} -type ScriptedCliReport = { - argv: string[] - execPath: string - controlRequests: { request_id: string; request: { subtype: string } }[] - controlResponses: { response: { request_id: string; response?: Record } }[] - userMessages: Record[] -} - -const scratchDirs: string[] = [] -afterEach(() => { - vi.unstubAllEnvs() - for (const dir of scratchDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function scriptScenario( - steps: ScenarioStep[], - controlResponses: Record = {}, - extra: Record = {} -): { - scenarioPath: string - reportPath: string - cwd: string - readReport: () => ScriptedCliReport -} { - const dir = mkdtempSync(join(tmpdir(), 'claude-sdk-contract-')) - scratchDirs.push(dir) - const scenarioPath = join(dir, 'scenario.json') - const reportPath = join(dir, 'report.json') - writeFileSync(scenarioPath, JSON.stringify({ steps, controlResponses, ...extra })) - return { - scenarioPath, - reportPath, - cwd: dir, - readReport: () => JSON.parse(readFileSync(reportPath, 'utf8')) as ScriptedCliReport - } -} - -function scenarioEnv(scenario: { scenarioPath: string; reportPath: string }) { - return { - PATH: process.env.PATH, - ORCA_SDK_CONTRACT_SCENARIO_PATH: scenario.scenarioPath, - ORCA_SDK_CONTRACT_REPORT_PATH: scenario.reportPath - } -} - -function recordingSpawner(spawns: SpawnSeen[]) { - return (opts: SdkSpawnOptions): SdkSpawnedProcess => { - spawns.push({ - command: opts.command, - args: [...opts.args], - cwd: opts.cwd, - env: { ...opts.env } - }) - return spawnProcess({ - program: opts.command, - args: opts.args, - cwd: opts.cwd, - env: opts.env as NodeJS.ProcessEnv, - signal: opts.signal - }) as unknown as SdkSpawnedProcess - } -} - -function singleUserTurn(): AsyncIterable { - return (async function* () { - yield { - type: 'user', - message: { role: 'user', content: [{ type: 'text', text: 'hello' }] }, - parent_tool_use_id: null, - session_id: SESSION_ID - } as SDKUserMessage - // Keep input open until the scripted CLI exits; an unresolved promise does not keep Node alive. - await new Promise(() => {}) - })() -} - -async function drainQuery(options: Options): Promise[]> { - const messages: Record[] = [] - for await (const message of query({ prompt: singleUserTurn(), options })) { - messages.push(message as unknown as Record) - } - return messages -} - -describe('Claude Agent SDK contract pins', () => { - it('gives canUseTool the wire request_id and fires its abort signal on control_cancel_request', async () => { - const scenario = scriptScenario([ - { awaitUserMessage: true }, - { - emit: { - type: 'control_request', - request_id: 'perm-421', - request: { - subtype: 'can_use_tool', - tool_name: 'Bash', - input: { command: 'echo hi' }, - tool_use_id: 'tool-use-9' - } - } - }, - { delayMs: 120 }, - { emit: { type: 'control_cancel_request', request_id: 'perm-421' } }, - { awaitControlResponse: 'perm-421' }, - { emit: RESULT_FRAME } - ]) - const seen: { toolName: string; requestId: string; toolUseID: string }[] = [] - let abortFired = false - const canUseTool: CanUseTool = (toolName, _input, { signal, requestId, toolUseID }) => { - seen.push({ toolName, requestId, toolUseID }) - return new Promise((resolve) => { - signal.addEventListener('abort', () => { - abortFired = true - resolve({ behavior: 'deny', message: 'cancelled by test' }) - }) - }) - } - const spawns: SpawnSeen[] = [] - await drainQuery({ - pathToClaudeCodeExecutable: FAKE_CLI, - cwd: scenario.cwd, - env: scenarioEnv(scenario), - canUseTool, - spawnClaudeCodeProcess: recordingSpawner(spawns) - }) - - expect(seen).toEqual([{ toolName: 'Bash', requestId: 'perm-421', toolUseID: 'tool-use-9' }]) - expect(abortFired).toBe(true) - const settled = scenario - .readReport() - .controlResponses.find((frame) => frame.response.request_id === 'perm-421') - expect(settled?.response.response?.behavior).toBe('deny') - expect(spawns).toHaveLength(1) - }) - - describe("Full access decisions keep each request's place in one stdout chunk", () => { - const status = (permissionMode: string) => ({ - type: 'system', - subtype: 'status', - status: null, - permissionMode, - session_id: SESSION_ID - }) - const ask = (id: string, extra: Record = {}) => ({ - type: 'control_request', - request_id: id, - request: { - subtype: 'can_use_tool', - tool_name: 'Bash', - input: { command: 'echo harmless' }, - tool_use_id: `tool-${id}`, - ...extra - } - }) - const cancel = (id: string) => ({ type: 'control_cancel_request', request_id: id }) - type WireFrame = ReturnType | ReturnType | ReturnType - const isAsk = (frame: WireFrame): frame is ReturnType => 'request' in frame - const many = (prefix: string) => - Array.from({ length: 300 }, (_, index) => ask(`${prefix}${index}`)) - const asked = (ids: string[], allowed: boolean) => - ids.map((requestId) => ({ requestId, allowed })) - const manyIds = (prefix: string) => many(prefix).map((frame) => frame.request_id) - - it.each([ - { - label: 'plan, then bypass, with the interaction flag', - frames: [ - status('plan'), - ask('A'), - status('bypassPermissions'), - ask('B'), - ask('flagged', { tool_name: 'mcp__forms__confirm', requires_user_interaction: true }) - ], - seen: [...asked(['A'], false), ...asked(['B'], true), ...asked(['flagged'], false)], - interaction: [true], - pending: [] - }, - { - label: 'a request initialize resends, then plan', - frames: [status('plan'), ask('A')], - seen: [...asked(['resent'], true), ...asked(['A'], false)], - interaction: [], - pending: [ask('resent')] - }, - { - label: 'a cancel in the same chunk', - frames: [status('plan'), ask('A'), cancel('A'), status('bypassPermissions'), ask('B')], - seen: [...asked(['A'], false), ...asked(['B'], true)], - interaction: [], - pending: [] - }, - { - label: 'a duplicate id after bypass', - frames: [status('plan'), ask('A'), status('bypassPermissions'), ask('A'), ask('B')], - seen: [...asked(['A', 'A'], false), ...asked(['B'], true)], - interaction: [], - pending: [] - }, - { - label: 'more than 256 unread requests in plan', - frames: [status('plan'), ...many('p'), status('bypassPermissions'), ask('B')], - seen: [...asked(manyIds('p'), false), ...asked(['B'], true)], - interaction: [], - pending: [] - }, - { - label: 'more than 256 unread requests in Full access', - frames: [status('bypassPermissions'), ...many('f'), status('plan'), ask('C')], - seen: [...asked(manyIds('f'), true), ...asked(['C'], false)], - interaction: [], - pending: [] - } - ])('$label', async ({ frames, seen: expected, interaction: flags, pending }) => { - const requestIds = [ - ...new Set([...pending, ...frames].filter(isAsk).map((frame) => frame.request_id)) - ] - const scenario = scriptScenario( - [ - { awaitUserMessage: true }, - { emitTogether: frames }, - ...requestIds.map((id) => ({ awaitControlResponse: id })), - { emit: RESULT_FRAME } - ], - {}, - { pendingPermissionRequests: { initialize: pending } } - ) - const prompts = new ClaudePromptRegistry() - const permissions = claudeLaunchPermissions( - { sessionId: 'session-1', prompts, emit: () => {} }, - { - providerSessionId: SESSION_ID, - options: claudeStructuredPermissionOptions('full-access') - } - ) - const seen: { requestId: string; allowed: boolean }[] = [] - const interaction: unknown[] = [] - const canUseTool: CanUseTool = async (toolName, input, options) => { - if ('requiresUserInteraction' in options) { - interaction.push(options.requiresUserInteraction) - } - const answer = permissions.handlers.canUseTool!(toolName, input, options) - // Answer any card at once so the scripted turn can finish. - prompts.find(options.requestId)?.prompt.settle({ - behavior: 'deny', - message: 'asked', - toolUseID: options.toolUseID - }) - const decision = { requestId: options.requestId, allowed: false } - seen.push(decision) - const result = await answer - decision.allowed = result?.behavior === 'allow' - return result ?? { behavior: 'deny', message: 'cancelled', toolUseID: options.toolUseID } - } - const spawner = createClaudeCodeProcessSpawn( - spawnProcess, - process.platform, - { pathToClaudeCodeExecutable: FAKE_CLI }, - permissions.handlers.onStdout - ) - await drainQuery({ - pathToClaudeCodeExecutable: FAKE_CLI, - cwd: scenario.cwd, - env: scenarioEnv(scenario), - canUseTool, - spawnClaudeCodeProcess: spawner.spawn - }) - - expect(seen).toEqual(expected) - expect(interaction).toEqual(flags) - }) - }) -}) diff --git a/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts b/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts deleted file mode 100644 index 893e32b960f..00000000000 --- a/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { collectDescendantRows } from '../pty/process-retirement/pty-descendant-termination' -import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof' - -describe('Claude child root identity', () => { - it('rejects mixed old and recycled root rows instead of making the tree killable', async () => { - const child = { pid: 100, kill: vi.fn(() => true) } - const terminateDescendants = vi.fn(async () => 'exited' as const) - const tree = createClaudeChildTreeReaper(child, { - site: 'claude-structured-child-close', - platform: 'linux', - captureDescendants: vi.fn(async () => - collectDescendantRows( - 100, - [ - { pid: 100, ppid: 1, pgid: 100, startedAt: 'Mon Jan 1 00:00:00 2026' }, - { pid: 100, ppid: 1, pgid: 101, startedAt: 'Mon Jan 1 00:00:01 2026' }, - { pid: 200, ppid: 100, pgid: 200, startedAt: 'Mon Jan 1 00:00:00 2026' } - ], - 1 - ) - ), - terminateDescendants - }) - - await expect(tree.reap()).resolves.toBe('unverifiable') - expect(terminateDescendants).not.toHaveBeenCalled() - expect(child.kill).toHaveBeenCalledWith('SIGKILL') - }) -}) diff --git a/src/main/claude/claude-agent-sdk-exit-proof.test.ts b/src/main/claude/claude-agent-sdk-exit-proof.test.ts deleted file mode 100644 index c71e8743aa6..00000000000 --- a/src/main/claude/claude-agent-sdk-exit-proof.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { execFileSync, type ChildProcessWithoutNullStreams } from 'node:child_process' -import { describe, expect, it } from 'vitest' -import { spawnProcess } from '@orca/process-host' -import { proveClaudeChildExit } from './claude-agent-sdk-exit-proof' -import { managedChild } from './claude-child-exit-proof-fixture' - -function childWithDescendantScript(input: { - rootTrapsSigterm: boolean - descendantTrapsSigterm: boolean -}): string { - const descendantScript = `${input.descendantTrapsSigterm ? 'process.on("SIGTERM", () => {}); ' : ''}setInterval(() => {}, 1000000)` - const rootBehaviour = input.rootTrapsSigterm - ? `process.on('SIGTERM', () => {}) -process.on('SIGINT', () => {}) -setInterval(() => {}, 1000000)` - : `process.stdin.on('end', () => process.exit(0)) -process.stdin.resume()` - return ` -const descendant = require('node:child_process').spawn( - process.execPath, - ['-e', ${JSON.stringify(descendantScript)}], - { stdio: 'ignore' } -) -descendant.unref() -process.stdout.write(JSON.stringify({ descendantPid: descendant.pid }) + '\\n') -${rootBehaviour} -` -} - -const COOPERATIVE_CHILD = ` -process.stdin.on('end', () => process.exit(0)) -process.stdin.resume() -process.stdout.write('ready\\n') -` - -/** Sample at the close boundary; zombies count as exited even though kill(pid, 0) finds them. */ -function descendantState(pid: number): 'running' | 'exited' { - let state: string - try { - state = execFileSync('ps', ['-o', 'state=', '-p', String(pid)], { - encoding: 'utf8', - env: { ...process.env, LANG: 'C', LC_ALL: 'C' } - }).trim() - } catch (error) { - // ps exits 1 when no process matches; anything else is a failed probe, not an answer. - if ((error as { status?: number }).status !== 1) { - throw error - } - return 'exited' - } - return state.startsWith('Z') ? 'exited' : 'running' -} - -// ps start times have second precision; cross that boundary so the snapshot permits forced signals. -function ageDescendantPastTheCaptureSecond(): Promise { - // ast-grep-ignore: test-no-wall-clock -- ps reports native process birth times on this clock. - return new Promise((resolve) => setTimeout(resolve, 1_000 - (Date.now() % 1_000) + 20)) -} - -// Model registry retries: slow process-table reads may leave one close attempt unproven. -async function proveExitWithRetries( - input: Parameters[0], - attempts = 3 -): Promise { - for (let attempt = 1; attempt < attempts; attempt += 1) { - if (await proveClaudeChildExit(input)) { - return true - } - } - return proveClaudeChildExit(input) -} - -function spawnScript(script: string): ChildProcessWithoutNullStreams { - const child = spawnProcess({ - program: process.execPath, - args: ['-e', script], - stdio: ['pipe', 'pipe', 'pipe'] - }) - managedChild(child) - return child -} - -function firstStdoutLine(child: ChildProcessWithoutNullStreams): Promise { - return new Promise((resolve) => { - child.stdout.setEncoding('utf8').once('data', (chunk: string) => resolve(chunk.trim())) - }) -} - -describe('claude child exit proof', () => { - it.runIf(process.platform !== 'win32')( - 'reports a proven exit only once a SIGTERM-resistant descendant is gone at the close boundary', - async () => { - const child = spawnScript( - childWithDescendantScript({ rootTrapsSigterm: true, descendantTrapsSigterm: true }) - ) - const { descendantPid } = JSON.parse(await firstStdoutLine(child)) as { - descendantPid: number - } - expect(descendantState(descendantPid)).toBe('running') - await ageDescendantPastTheCaptureSecond() - - try { - const proven = await proveExitWithRetries({ managed: managedChild(child) }) - // Assert at lease release; polling afterward could conceal a surviving descendant. - expect({ proven, descendant: descendantState(descendantPid) }).toEqual({ - proven: true, - descendant: 'exited' - }) - } finally { - try { - process.kill(descendantPid, 'SIGKILL') - } catch { - // Already gone. - } - } - }, - 20_000 - ) - - it.runIf(process.platform !== 'win32')( - 'proves a promptly exiting root only once its stubborn descendant is gone too', - async () => { - const child = spawnScript( - childWithDescendantScript({ rootTrapsSigterm: false, descendantTrapsSigterm: true }) - ) - const { descendantPid } = JSON.parse(await firstStdoutLine(child)) as { - descendantPid: number - } - expect(descendantState(descendantPid)).toBe('running') - await ageDescendantPastTheCaptureSecond() - - try { - const proven = await proveExitWithRetries({ managed: managedChild(child) }) - expect({ proven, descendant: descendantState(descendantPid) }).toEqual({ - proven: true, - descendant: 'exited' - }) - } finally { - try { - process.kill(descendantPid, 'SIGKILL') - } catch { - // Already gone. - } - } - }, - 20_000 - ) - - it.runIf(process.platform !== 'win32')( - 'still proves a stubborn child whose descendant honours SIGTERM', - async () => { - const child = spawnScript( - childWithDescendantScript({ rootTrapsSigterm: true, descendantTrapsSigterm: false }) - ) - const { descendantPid } = JSON.parse(await firstStdoutLine(child)) as { - descendantPid: number - } - try { - const proven = await proveExitWithRetries({ managed: managedChild(child) }) - expect({ proven, descendant: descendantState(descendantPid) }).toEqual({ - proven: true, - descendant: 'exited' - }) - } finally { - try { - process.kill(descendantPid, 'SIGKILL') - } catch { - // Already gone. - } - } - }, - 20_000 - ) - - it('proves a clean close of a childless root with one snapshot and no signal', async () => { - const child = spawnScript(COOPERATIVE_CHILD) - expect(await firstStdoutLine(child)).toBe('ready') - - await expect(proveClaudeChildExit({ managed: managedChild(child) })).resolves.toBe(true) - }, 20_000) -}) diff --git a/src/main/claude/claude-agent-sdk-process-spawn.test.ts b/src/main/claude/claude-agent-sdk-process-spawn.test.ts deleted file mode 100644 index 65dbbbfaddc..00000000000 --- a/src/main/claude/claude-agent-sdk-process-spawn.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child' -import { describe, expect, it, vi } from 'vitest' -import type { SpawnOptions as SdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' -import type { PipedProcessSpawner, ProcessSpec } from '@orca/process-host/process-spec' - -import type * as ProviderSupervisor from '../provider-process/provider-process-supervisor' -import { createProviderSpawnSpec } from '../provider-process/provider-process-supervisor' -import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn' -import { proveClaudeChildExitWithReaper } from './claude-child-exit-proof-ladder' - -vi.mock('../provider-process/provider-process-supervisor', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, createProviderSpawnSpec: vi.fn(actual.createProviderSpawnSpec) } -}) - -function fakeSpawn() { - const child = createFakePipedChild() - const specs: ProcessSpec[] = [] - const spawnImpl: PipedProcessSpawner = (spec) => { - specs.push(spec) - return child - } - return { child, spawnImpl, specs } -} - -function sdkOptions(overrides: Partial = {}): SdkSpawnOptions { - return { - command: '/usr/local/bin/claude', - args: ['--output-format', 'stream-json'], - cwd: '/work/repo', - env: { PATH: '/usr/bin', CLAUDE_CONFIG_DIR: '/accounts/one', UNSET: undefined }, - signal: new AbortController().signal, - ...overrides - } -} - -describe('claude agent SDK process spawn', () => { - it.each([ - { platform: 'darwin', specSupervised: false }, - { platform: 'win32', specSupervised: true } - ] as const)( - 'stops Claude by the spawn spec\u2019s supervision on $platform, never the platform', - async ({ platform, specSupervised }) => { - const actual = await vi.importActual( - '../provider-process/provider-process-supervisor' - ) - vi.mocked(createProviderSpawnSpec).mockImplementationOnce((...args) => ({ - ...actual.createProviderSpawnSpec(...args), - supervised: specSupervised - })) - const process = fakeSpawn() - const spawn = createClaudeCodeProcessSpawn(process.spawnImpl, platform) - spawn.spawn(sdkOptions()) - expect(spawn.supervised).toBe(specSupervised) - - const managed = spawn.managed - if (!managed) { - throw new Error('Claude spawner did not retain its managed child') - } - process.child.stdin.on('finish', () => - setTimeout(() => process.child.emit('exit', 0, null), 10) - ) - const tree = { - capture: vi.fn(async () => {}), - reap: vi.fn(async () => 'exited' as const), - treeVerdict: 'exited' as const, - forcedReapAttempted: false - } - await expect(proveClaudeChildExitWithReaper({ managed, tree }, () => tree)).resolves.toBe( - true - ) - if (specSupervised) { - expect(process.child.kill).toHaveBeenCalledWith('SIGTERM') - } else { - expect(process.child.kill).not.toHaveBeenCalled() - } - } - ) - - it('drains stderr into a bounded tail so an exit error still carries it', async () => { - const process = fakeSpawn() - const spawn = createClaudeCodeProcessSpawn(process.spawnImpl) - spawn.spawn(sdkOptions()) - - process.child.stderr.write('x'.repeat(9000)) - process.child.stderr.write('claude: not signed in') - await new Promise((resolve) => setImmediate(resolve)) - - expect(spawn.managed?.stderrTail()).toMatch(/claude: not signed in$/) - expect(spawn.managed?.stderrTail().length).toBe(8192) - }) - - it('keeps native chat identity after SDK and configured environment defaults', () => { - const process = fakeSpawn() - createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( - sdkOptions({ - env: { - CLAUDE_CODE_ENTRYPOINT: 'sdk-ts', - claude_code_entrypoint: 'account', - PATH: 'C:\\bin' - } - }) - ) - expect(process.specs[0]?.env).toMatchObject({ CLAUDE_CODE_ENTRYPOINT: 'orca', PATH: 'C:\\bin' }) - expect( - Object.keys(process.specs[0]?.env ?? {}).filter( - (key) => key.toUpperCase() === 'CLAUDE_CODE_ENTRYPOINT' - ) - ).toEqual(['CLAUDE_CODE_ENTRYPOINT']) - }) - - it('preserves a Windows .cmd shim and its arguments for the host spawner', () => { - const process = fakeSpawn() - createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( - sdkOptions({ - command: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd', - args: ['--setting-sources=user,project,local', '--session-id', 'a b&c'] - }) - ) - - expect(process.specs).toEqual([ - expect.objectContaining({ - program: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd', - args: ['--setting-sources=user,project,local', '--session-id', 'a b&c'] - }) - ]) - }) -}) diff --git a/src/main/claude/claude-agent-sdk-user-message-queue.test.ts b/src/main/claude/claude-agent-sdk-user-message-queue.test.ts deleted file mode 100644 index c2c1c818f3a..00000000000 --- a/src/main/claude/claude-agent-sdk-user-message-queue.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type { SDKUserMessage } from '@anthropic-ai/claude-agent-sdk' -import { describe, expect, it } from 'vitest' -import { - claudeUserMessageWasProvablyUnwritten, - createClaudeUserMessageQueue -} from './claude-agent-sdk-user-message-queue' - -// Model the SDK pump: it resumes only after transport.write and abandons the iterator on failure. -const frame = (text: string): SDKUserMessage => - ({ - type: 'user', - message: { role: 'user', content: [{ type: 'text', text }] } - }) as unknown as SDKUserMessage - -const settled = (promise: Promise): Promise<'settled' | 'pending'> => - Promise.race([ - promise.then( - () => 'settled' as const, - () => 'settled' as const - ), - new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 100)) - ]) - -describe('claude user message queue', () => { - it('treats a frame the SDK pulled and abandoned as write-outcome unknown', async () => { - const queue = createClaudeUserMessageQueue() - const pump = queue.messages[Symbol.asyncIterator]() - const sent = queue.push(frame('hello')) - - await pump.next() - await pump.return?.(undefined) - - await expect(settled(sent)).resolves.toBe('settled') - const error = await sent.catch((caught: unknown) => caught) - expect(error).toMatchObject({ - message: 'claude stream-json input ended before confirming the frame write' - }) - expect(claudeUserMessageWasProvablyUnwritten(error)).toBe(false) - }) - - it('marks only frames still queued in Orca as provably unwritten', async () => { - const queue = createClaudeUserMessageQueue() - const pump = queue.messages[Symbol.asyncIterator]() - const inFlight = queue.push(frame('first')).catch((caught: unknown) => caught) - await pump.next() - const queued = queue.push(frame('second')).catch((caught: unknown) => caught) - - queue.fail(new Error('claude stream-json exited: child died')) - - expect(claudeUserMessageWasProvablyUnwritten(await inFlight)).toBe(false) - expect(claudeUserMessageWasProvablyUnwritten(await queued)).toBe(true) - }) - - it('still settles a written frame only once the pump asks for the next one', async () => { - const queue = createClaudeUserMessageQueue() - const pump = queue.messages[Symbol.asyncIterator]() - const sent = queue.push(frame('hello')) - - const pulled = await pump.next() - expect(pulled.value).toMatchObject({ type: 'user' }) - await expect(settled(sent)).resolves.toBe('pending') - void pump.next() - await expect(sent).resolves.toBeUndefined() - }) -}) diff --git a/src/main/claude/claude-api-retry-row.test.ts b/src/main/claude/claude-api-retry-row.test.ts deleted file mode 100644 index 88ca734194b..00000000000 --- a/src/main/claude/claude-api-retry-row.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { openAgentSessionJournal } from '../native-chat/agent-session-journal/journal-store-factory' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('provider-1', 'leaf-1') -} - -function apiRetry(attempt: number, fields: Record = {}): Record { - return { - type: 'system', - subtype: 'api_retry', - attempt, - max_retries: 10, - retry_delay_ms: 622, - error_status: 429, - error: 'rate_limit', - session_id: 'provider-1', - uuid: `9b2f6a1e-0c4d-4e7a-8f3b-00000000000${attempt}`, - ...fields - } -} - -let root = '' - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-api-retry-')) -}) - -afterEach(async () => { - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -async function statusRowsFor(frames: Record[]) { - const journal = await openAgentSessionJournal({ - identity: IDENTITY, - database: openTestJournalHostDatabase(root), - now: () => 1_700_000_000_000, - mintEpoch: () => 'epoch-1' - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - deferred.bind({ journal, fence: 1, publish: vi.fn() }) - const translator = createClaudeJournalTranslator({ sink: deferred.sink, fallbackIdPrefix: '1' }) - for (const frame of frames) { - translator.handle({ type: 'message', sessionId: 'orca-session', message: frame }) - await deferred.drained() - } - return journal - .snapshot() - .items.flatMap((item): Extract[] => - item.body.kind === 'status' ? [item.body] : [] - ) -} - -describe('a Claude api_retry frame', () => { - it('writes one sentence row per retry run, revised by each attempt, not the frame', async () => { - const rows = await statusRowsFor([apiRetry(1), apiRetry(2), apiRetry(3)]) - - expect(rows).toHaveLength(1) - const [row] = rows - expect(row).toMatchObject({ - text: 'Claude is rate-limited and retrying. Retry 3 of 10.\nLast error: HTTP 429 rate limit.', - tone: 'warning', - failure: { - kind: 'providerRetrying', - retry: { error: 'rate_limit', status: 429, attempt: 3, maxRetries: 10 }, - detail: { audience: 'log' } - } - }) - expect(row).not.toHaveProperty('providerFrame') - expect(row.failure?.detail?.text).toContain('"attempt":3') - }) - - it('hides unmodeled system frames even when their payload names an error', async () => { - const unknown = { - type: 'system', - subtype: 'future_notice', - error: 'rate_limit', - session_id: 'provider-1', - uuid: 'future-1' - } - const rows = await statusRowsFor([unknown]) - expect(rows).toEqual([]) - }) -}) diff --git a/src/main/claude/claude-api-retry-row.ts b/src/main/claude/claude-api-retry-row.ts deleted file mode 100644 index d5f0ff4111c..00000000000 --- a/src/main/claude/claude-api-retry-row.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - agentSessionFailureFact, - providerDiagnostic, - readProviderRetry -} from '../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' -import type { AgentJournalStatusItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import { TUI_AGENT_DISPLAY_NAMES } from '../../shared/agent-launch/catalog/tui-agent-display-names' - -export const CLAUDE_API_RETRY_FRAME_KIND = 'message:system:api_retry' - -export function claudeApiRetryRowBody(message: Record): AgentJournalStatusItem { - const retry = readProviderRetry({ - error: message.error, - status: message.error_status, - attempt: message.attempt, - maxRetries: message.max_retries - }) - const words = agentSessionFailureWords( - agentSessionFailureFact('providerRetrying', { - detail: providerDiagnostic(JSON.stringify(message), 'log'), - ...(retry ? { retry } : {}) - }), - { surface: 'row', agentName: TUI_AGENT_DISPLAY_NAMES.claude } - ) - return { kind: 'status', tone: 'warning', ...words } -} - -// Missing or non-increasing attempt numbers start a new retry run. -export function createClaudeApiRetryRuns(): (message: Record) => number { - let run = 0 - let lastAttempt: number | null = null - return (message) => { - const attempt = typeof message.attempt === 'number' ? message.attempt : null - if (attempt === null || lastAttempt === null || attempt <= lastAttempt) { - run += 1 - } - lastAttempt = attempt - return run - } -} diff --git a/src/main/claude/claude-background-run-isolation-real-cli.test.ts b/src/main/claude/claude-background-run-isolation-real-cli.test.ts deleted file mode 100644 index 407e56d1cbe..00000000000 --- a/src/main/claude/claude-background-run-isolation-real-cli.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' -import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { claudeBackgroundArgs } from '../../shared/claude-background-run-isolation' -import { CLAUDE_MODEL_LIST_ARGS } from '../../shared/claude-model-list-probe' -import { realClaudeAvailable, realClaudeCommand } from './claude-real-cli-availability-test-support' - -// Probe real CLI control answers in a temporary account home without spending a turn. -const root = mkdtempSync(join(tmpdir(), 'orca-claude-isolation-')) -afterEach(() => rmSync(root, { recursive: true, force: true })) - -async function loaded(args: string[]): Promise<{ servers: unknown; hooksOff: unknown }> { - const request = (id: string) => - `${JSON.stringify({ type: 'control_request', request_id: id, request: { subtype: id } })}\n` - const { stdout } = await runProcess({ - program: realClaudeCommand, - args, - cwd: root, - input: request('mcp_status') + request('get_settings'), - timeoutMs: 60_000, - env: withCliRuntimeOnPath(realClaudeCommand, { - ...process.env, - HOME: root, - CLAUDE_CONFIG_DIR: join(root, 'config') - }) - }) - const answers = new Map( - stdout.split('\n').flatMap((line) => { - const response = line.startsWith('{') ? JSON.parse(line).response : undefined - return response?.request_id ? [[response.request_id, response.response]] : [] - }) - ) - return { - servers: answers.get('mcp_status')?.mcpServers?.map((server: { name: string }) => server.name), - hooksOff: answers.get('get_settings')?.effective?.disableAllHooks ?? false - } -} - -describe.skipIf(!realClaudeAvailable)('background Claude runs with the real CLI', () => { - it('load none of the user MCP servers or hooks, and keep a --mcp-config the user passed', async () => { - const server = { type: 'stdio', command: '/bin/cat', args: [] } - mkdirSync(join(root, 'config')) - writeFileSync( - join(root, 'config', '.claude.json'), - JSON.stringify({ mcpServers: { user: server } }) - ) - writeFileSync( - join(root, 'config', 'settings.json'), - JSON.stringify({ allowedMcpServers: [{ serverName: 'user' }, { serverName: 'explicit' }] }) - ) - writeFileSync(join(root, 'mcp.json'), JSON.stringify({ mcpServers: { explicit: server } })) - const listing = CLAUDE_MODEL_LIST_ARGS.slice(0, -claudeBackgroundArgs().length) - - expect(await loaded(listing)).toEqual({ servers: ['user'], hooksOff: false }) - expect(await loaded([...listing, ...claudeBackgroundArgs()])).toEqual({ - servers: [], - hooksOff: true - }) - expect( - await loaded([...listing, ...claudeBackgroundArgs(), '--mcp-config', join(root, 'mcp.json')]) - ).toEqual({ servers: ['explicit'], hooksOff: true }) - }, 180_000) -}) diff --git a/src/main/claude/claude-background-stop-records.test.ts b/src/main/claude/claude-background-stop-records.test.ts deleted file mode 100644 index 6d9e034bfd3..00000000000 --- a/src/main/claude/claude-background-stop-records.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - agentChildWorkStopEvidence, - agentChildWorkStopTargets, - type AgentChildWorkStopAcknowledgement -} from '../../shared/agent-status/child-work/agent-child-work-stop-targets' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { agentChildWorkLiveness } from '../../shared/agent-status/child-work/agent-status-child-work-liveness' -import { conversationCommandBlocked } from '../native-chat/agent-session-wire/operations/structured-conversation-command-admission' -import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' -import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture' -import { RESUMED_BY_MESSAGE } from './claude-captured-task-frames.test-fixture' -import { hostWithParent, parent, producer } from './claude-child-work-producer-harness.test-fixture' - -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) -afterEach(() => vi.restoreAllMocks()) - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: admission reads only the lease and the command/rewind records, all absent here. -const RECORD = { lease: {} } as unknown as AgentSessionRecord - -/** Host records retain live work after provider roster removal. */ -async function droppedFromRoster() { - const host = hostWithParent() - const run = await producer(host) - const launch: CapturedFrame[] = RESUMED_BY_MESSAGE.filter((captured) => captured.at < 5_077) - run.replay(launch) - run.replay([ - { at: 6_000, frame: { type: 'system', subtype: 'background_tasks_changed', tasks: [] } } - ]) - const records = () => host.getStructuredChildWorkViews(parent) - const blocked = () => - conversationCommandBlocked( - { - sessionId: 'session-1', - fence: 7, - journal: { - itemsRead: () => ({ items: [] }), - cursor: () => ({ epoch: 'e', sequence: 0 }), - item: () => null, - submissions: () => [], - inputOrder: { recoverableSubmissions: () => [] }, - runningTurn: () => null, - itemFence: () => undefined, - visitItems: () => undefined, - wroteBeforeOpen: () => false - }, - adapter: run.adapter - }, - RECORD, - { views: records(), open: agentChildWorkLiveness(records()) !== null } - ) - const stopCalls = () => - run.claude.connections[0]!.calls.filter((call) => call.subtype === 'stop_task') - expect(records()).toMatchObject([ - { membership: 'live', stoppable: true, providerId: 'agent-1', kind: 'agent' } - ]) - expect(blocked()?.message).toBe('Stop background tasks before using this command.') - // Snapshot stop targets before dispatch; settle only acknowledged records. - const stop = async (taskId?: string) => { - const targets = agentChildWorkStopTargets(records(), taskId) - const acknowledged: AgentChildWorkStopAcknowledgement[] = [] - const outcome = await run.adapter.stopBackgroundTasks({ - sessionId: 'session-1', - fence: 7, - taskIds: targets.map((target) => target.providerId), - acknowledge: (acknowledgement) => void acknowledged.push(acknowledgement) - }) - host.ingestStructuredChildWork( - parent, - agentChildWorkStopEvidence(targets, acknowledged, 6_500), - 'claude' - ) - return outcome - } - const basis = () => host.getStructuredChildWork(parent).map((record) => record.outcomeBasis) - return { run, records, blocked, stopCalls, stop, basis } -} - -describe('a background Stop acts on the host child records', () => { - it('keeps a stopped owner and its independently stoppable shell attached from real task frames', async () => { - const host = hostWithParent() - const run = await producer(host) - run.replay(PARENT_TASK_STOP.slice(0, 7)) - const owner = run.records().find((record) => record.kind === 'agent') - expect(owner).toMatchObject({ membership: 'settled', outcome: 'cancelled' }) - expect(run.records().find((record) => record.kind === 'command')).toMatchObject({ - membership: 'live', - stoppable: true, - parentChildWorkId: owner?.childWorkId - }) - const targets = agentChildWorkStopTargets( - host.getStructuredChildWorkViews(parent), - 'shell-child' - ) - expect(targets.map((target) => target.providerId)).toEqual(['shell-child']) - await run.adapter.stopBackgroundTasks({ - sessionId: 'session-1', - fence: 7, - taskIds: targets.map((target) => target.providerId) - }) - expect(run.claude.connections[0]!.calls.filter((call) => call.subtype === 'stop_task')).toEqual( - [{ subtype: 'stop_task', params: { taskId: 'shell-child' } }] - ) - run.replay(PARENT_TASK_STOP.slice(7)) - expect(run.records().find((record) => record.kind === 'command')).toMatchObject({ - membership: 'settled', - outcome: 'cancelled' - }) - - // Start-only delivery in reverse owner order must converge too; no original tool traffic is replayed. - const childFirst = await producer() - childFirst.replay([PARENT_TASK_STOP[3]!, PARENT_TASK_STOP[1]!]) - const resolvedOwner = childFirst.records().find((record) => record.kind === 'agent') - expect(childFirst.records().find((record) => record.kind === 'command')).toMatchObject({ - membership: 'live', - parentChildWorkId: resolvedOwner?.childWorkId - }) - }) - - it("stops the row's own task, which the records keep after the roster dropped it", async () => { - const { records, blocked, stopCalls, stop, basis } = await droppedFromRoster() - - const outcome = await stop('agent-1') - - expect(outcome).toMatchObject({ cancelled: true }) - expect(stopCalls()).toEqual([{ subtype: 'stop_task', params: { taskId: 'agent-1' } }]) - expect(records()).toMatchObject([{ membership: 'settled', outcome: 'cancelled' }]) - expect(basis()).toEqual(['stop-acknowledged']) - expect(blocked()).toBeNull() - }) - - it('leaves a task that ended on its own frame as it ended: its row offers no stop', async () => { - const { run, records, stopCalls, stop } = await droppedFromRoster() - run.replay([ - { - at: 7_000, - frame: { - type: 'system', - subtype: 'task_updated', - task_id: 'agent-1', - patch: { status: 'completed' } - } - }, - { - at: 7_000, - frame: { - type: 'system', - subtype: 'task_notification', - task_id: 'agent-1', - status: 'completed' - } - } - ]) - - const outcome = await stop('agent-1') - - expect(outcome).toMatchObject({ cancelled: false }) - expect(stopCalls()).toEqual([]) - expect(records()).toMatchObject([{ membership: 'settled', outcome: 'succeeded' }]) - }) - - it('lets the task’s own completion, written before the acknowledgement, replace the Stop', async () => { - const { run, records, stop } = await droppedFromRoster() - await stop('agent-1') - expect(records()).toMatchObject([{ membership: 'settled', outcome: 'cancelled' }]) - - // The completion the CLI wrote before its answer, which the SDK delivered after it. - run.replay([ - { - at: 7_000, - frame: { - type: 'system', - subtype: 'task_notification', - task_id: 'agent-1', - status: 'completed', - summary: 'Found 3 call sites' - } - } - ]) - expect(records()).toMatchObject([ - { membership: 'settled', outcome: 'succeeded', lastMessage: 'Found 3 call sites' } - ]) - }) -}) diff --git a/src/main/claude/claude-background-task-terminal-frames.test.ts b/src/main/claude/claude-background-task-terminal-frames.test.ts deleted file mode 100644 index 6f1754c36e9..00000000000 --- a/src/main/claude/claude-background-task-terminal-frames.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - FORWARDED_TOOL, - harness, - ORPHAN_FAILED_NOTIFICATION, - START_BASH -} from './claude-background-task-row-test-support' - -describe('claude background task terminal frames', () => { - it('reports a failure for a task it never saw admitted', () => { - const { rows, items, latest, latestTwin, turnOpens } = harness() - expect(rows.observe(ORPHAN_FAILED_NOTIFICATION)).toBe(true) - expect(items).toHaveLength(1) - expect(turnOpens).toHaveLength(1) - expect(latest()).toMatchObject({ - type: 'background-task', - taskId: 'bjzenpq13', - kind: 'unknown', - state: 'blocked', - summary: 'Locate the exact screenshot session', - parentToolUseId: 'toolu_01ASNfnDBEzt4w3ejLE12bGu' - }) - expect(latest()?.label).toBe('') - expect(latestTwin()).toBe('Locate the exact screenshot session') - }) - - it('does not resurrect an orphan outcome that named its own parent tool', () => { - const { rows, items, latest } = harness([ - FORWARDED_TOOL, - ORPHAN_FAILED_NOTIFICATION.tool_use_id - ]) - rows.observe(ORPHAN_FAILED_NOTIFICATION) - rows.observe({ - ...START_BASH, - task_id: ORPHAN_FAILED_NOTIFICATION.task_id, - tool_use_id: ORPHAN_FAILED_NOTIFICATION.tool_use_id - }) - expect(items).toHaveLength(1) - expect(latest()).toMatchObject({ state: 'blocked' }) - }) -}) diff --git a/src/main/claude/claude-background-task-turn-resumption.test.ts b/src/main/claude/claude-background-task-turn-resumption.test.ts deleted file mode 100644 index 13a2d59ba17..00000000000 --- a/src/main/claude/claude-background-task-turn-resumption.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import { hasUnansweredStructuredAgentSessionDispatch } from '../../shared/agent-session/requests/structured-agent-session-unanswered-dispatch' -import { projectStructuredAgentSessionStatus } from '../../shared/agent-session/view/structured-agent-session-projection' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' - -const SESSION = 'claude-session' -const TOOL = 'toolu_fwd' - -function harness() { - const appended: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity, body) => appended.push({ identity, body }), - appendTombstone: () => {}, - publish: vi.fn() - } - const translator = createClaudeJournalTranslator({ sink, fallbackIdPrefix: 'test' }) - const items = (): AgentJournalRenderItem[] => { - const byKey = new Map() - appended.forEach(({ identity, body }, index) => { - const key = agentJournalItemKey(identity) - const existing = byKey.get(key) - byKey.set(key, { - itemId: key, - revision: (existing?.revision ?? 0) + 1, - body, - sequence: existing?.sequence ?? index, - observedAt: index - }) - }) - return [...byKey.values()].sort((a, b) => a.sequence - b.sequence) - } - return { translator, items, appended } -} - -function projected(items: readonly AgentJournalRenderItem[]): string { - expect(hasUnansweredStructuredAgentSessionDispatch([], null)).toBe(false) - return projectStructuredAgentSessionStatus(items, [], null) -} - -function systemFrame(uuid: string, fields: Record) { - return { - type: 'message' as const, - sessionId: 'orca-session', - message: { type: 'system', uuid, session_id: SESSION, ...fields } - } -} - -function spawnToolCall(translator: ReturnType['translator']) { - translator.handle({ - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'assistant', - uuid: 'a1', - session_id: SESSION, - parent_tool_use_id: null, - message: { - role: 'assistant', - content: [{ type: 'tool_use', id: TOOL, name: 'Bash', input: { command: 'wait' } }] - } - } - }) -} - -function settleTurn(translator: ReturnType['translator']) { - translator.handle({ - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'result', - subtype: 'success', - uuid: 'r1', - session_id: SESSION, - parent_tool_use_id: null, - duration_ms: 1000 - } - }) -} - -describe('a typed background-task row opens the turn it resumes', () => { - it('reports working, not idle, when a task notification wakes the agent', () => { - const { translator, items } = harness() - spawnToolCall(translator) - translator.handle( - systemFrame('s1', { - subtype: 'task_started', - task_id: 'byjnee2no', - tool_use_id: TOOL, - task_type: 'local_bash', - description: 'Wait for the verification verdict', - is_backgrounded: true - }) - ) - settleTurn(translator) - expect(projected(items())).toBe('idle') - - translator.handle( - systemFrame('s2', { - subtype: 'task_notification', - task_id: 'byjnee2no', - tool_use_id: TOOL, - status: 'failed', - summary: 'Background command "Wait" failed with exit code 1' - }) - ) - - const taskRow = items().find((item) => item.itemId.includes('byjnee2no')) - expect(taskRow).toBeDefined() - const running = items().filter((item) => readAgentJournalTurn(item.body)?.state === 'running') - expect(running).toHaveLength(1) - expect(projected(items())).toBe('working') - }) - - it('does not reopen a completed turn when an overflow terminal row is enriched', () => { - const { translator, items } = harness() - for (let index = 0; index < 64; index += 1) { - translator.handle( - systemFrame(`start-${index}`, { - subtype: 'task_started', - task_id: `live-${index}`, - task_type: 'local_bash', - is_backgrounded: true - }) - ) - } - translator.handle( - systemFrame('overflow-start', { - subtype: 'task_started', - task_id: 'overflow-turn', - task_type: 'local_bash', - is_backgrounded: true - }) - ) - translator.handle( - systemFrame('overflow-update', { - subtype: 'task_updated', - task_id: 'overflow-turn', - patch: { status: 'failed' } - }) - ) - settleTurn(translator) - expect(projected(items())).toBe('idle') - - translator.handle( - systemFrame('overflow-notification', { - subtype: 'task_notification', - task_id: 'overflow-turn', - status: 'stopped', - summary: 'No completion record was found' - }) - ) - - expect(projected(items())).toBe('idle') - }) -}) - -it('keeps an alias-only owned notification idle even when its alias was forwarded at the root', () => { - const { translator, items } = harness() - spawnToolCall(translator) - translator.handle( - systemFrame('owned-start', { - subtype: 'task_started', - task_id: 'owned', - tool_use_id: TOOL, - parent_task_id: 'owner', - task_type: 'local_bash', - is_backgrounded: true - }) - ) - settleTurn(translator) - translator.handle( - systemFrame('owned-terminal', { - subtype: 'task_notification', - tool_use_id: TOOL, - status: 'completed', - summary: 'Finished child' - }) - ) - expect(items().find((item) => item.itemId.includes('owned'))?.body).toMatchObject({ - kind: 'message', - blocks: expect.arrayContaining([ - expect.objectContaining({ type: 'background-task', taskId: 'owned', state: 'done' }) - ]) - }) - expect(projected(items())).toBe('idle') - translator.dispose() -}) - -it('keeps owned terminal overflow writes idle without a retained row invocation', () => { - const { translator, items } = harness() - for (let index = 0; index < 65; index += 1) { - translator.handle( - systemFrame(`owned-start-${index}`, { - subtype: 'task_started', - task_id: `owned-${index}`, - parent_task_id: 'owner', - task_type: 'local_bash', - is_backgrounded: true - }) - ) - } - settleTurn(translator) - translator.handle( - systemFrame('overflow-owned-patch', { - subtype: 'task_updated', - task_id: 'owned-64', - patch: { status: 'failed' } - }) - ) - translator.handle( - systemFrame('overflow-owned-orphan', { - subtype: 'task_notification', - task_id: 'owned-terminal-only', - parent_task_id: 'owner', - status: 'completed' - }) - ) - const terminal = items().filter( - (item) => - item.body.kind === 'message' && - item.body.blocks.some( - (block) => - block.type === 'background-task' && - ['owned-64', 'owned-terminal-only'].includes(block.taskId) - ) - ) - expect(terminal).toHaveLength(2) - expect(projected(items())).toBe('idle') - translator.dispose() -}) diff --git a/src/main/claude/claude-background-wake-retention.test.ts b/src/main/claude/claude-background-wake-retention.test.ts deleted file mode 100644 index 1cb8b52af79..00000000000 --- a/src/main/claude/claude-background-wake-retention.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalSubmission } from '../../shared/agent-session/journal/agent-session-journal-types' -import { structuredRunningChildWork } from '../../shared/agent-status/child-work/agent-child-work-listing' -import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' -import type { StructuredAgentSessionJournalProjections } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection' -import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' -import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' -import { backgroundWakeCapture } from './claude-captured-fold-steer-frames.test-fixture' -import { MOVED_TO_BACKGROUND } from './claude-captured-task-frames.test-fixture' -import { hostWithParent, parent, producer } from './claude-child-work-producer-harness.test-fixture' -import { PROVIDER_SESSION_ID } from './structured/claude-structured-session-test-support' -import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' - -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) -afterEach(() => vi.restoreAllMocks()) - -type Journal = Parameters[0] - -async function wiredSession() { - const host: AgentHookServer = hostWithParent() - const run = await producer(host) - const submissions: AgentJournalSubmission[] = [] - let sequence = 0 - const journal = { - cursor: () => ({ epoch: 'epoch-1', sequence: ++sequence }), - lastActivityAt: () => 1, - submissions: (): ReturnType => - submissions.map((submission) => ({ ...submission })), - item: (itemId: string): ReturnType => { - const item = run.journalItems.get(itemId) - return item ? { ...item, revision: 1, observedAt: run.now() } : null - }, - statusRead(): ReturnType { - return this.snapshot() - }, - inputOrder: { - inputCount: () => submissions.length, - inputOrdinal: (id: string) => submissions.findIndex((s) => s.clientMessageId === id), - recoverableSubmissions: () => - submissions.filter((s) => s.dispatchState === 'pending' || s.dispatchState === 'unknown') - }, - context: { floor: () => null }, - stopMarks: { latest: () => null, revision: () => 0 }, - itemFence: () => undefined, - wroteBeforeOpen: () => false, - runningTurn: () => null, - snapshot: () => ({ - items: [...run.journalItems.values()] - .sort((a, b) => a.sequence - b.sequence) - .map((item) => ({ ...item, revision: 1, observedAt: run.now() })), - submissions: submissions.map((submission) => ({ ...submission })) - }) - } - const feed = new StructuredAgentSessionStatusFeed({ - logger: createStructuredAgentSessionLogger(), - sessions: new Map([ - [ - parent.sessionId, - { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies the feed's cursor, clock, Stop marks, context floor, snapshot, submissions, item and provenance reads. - journal: journal as unknown as Journal, - params: { - location: { - executionHostId: parent.executionHostId, - wslDistro: parent.wslDistro, - workspaceId: parent.workspaceId, - workspaceKind: parent.workspaceKind - }, - provider: 'claude' as const - } - } - ] - ]), - getConversation: () => null, - now: () => Date.now(), - statusSink: () => ({ - publish: (summary, subject) => host.ingestStructuredStatus(summary, subject), - forget: (subject) => host.dropStructuredStatus(subject), - publishChildWork: (subject, evidence, provider) => - host.ingestStructuredChildWork(subject, evidence, provider), - readChildWork: (subject) => host.getStructuredChildWorkViews(subject) - }) - }) - const describe = (views: ReturnType) => - views.map((view) => `${view.description}:${view.membership}:${view.outcome ?? ''}`) - const records = () => describe(host.getStructuredChildWorkViews(parent)) - const running = () => - describe(structuredRunningChildWork(host.getStructuredChildWorkViews(parent))) - const replay = (frames: readonly CapturedFrame[]) => { - for (const captured of frames) { - run.replay([captured]) - feed.publish(parent.sessionId) - } - } - const send = (clientMessageId: string): AgentJournalSubmission => { - const submission: AgentJournalSubmission = { - clientMessageId, - fence: 7, - payloadFingerprint: clientMessageId, - dispatchState: 'pending', - providerItemId: null, - reason: null, - submittedAt: run.now(), - resolvedAt: null - } - submissions.push(submission) - feed.publish(parent.sessionId) - return submission - } - const accept = (submission: AgentJournalSubmission) => { - submission.dispatchState = 'accepted' - feed.publish(parent.sessionId) - } - const rootTurns = () => - [...run.journalItems.values()].filter((item) => !item.agentId && item.body.kind === 'turn') - return { run, feed, records, running, replay, send, accept, rootTurns } -} - -describe("a finished child's record stays until the user's next turn", () => { - it("keeps a background agent through Claude's own wake turn, then retires it at the next send", async () => { - const session = await wiredSession() - session.replay(MOVED_TO_BACKGROUND) - expect(session.rootTurns()).toHaveLength(2) - expect(session.records()).toContain('Run 45s sleep command:settled:succeeded') - expect(session.running()).toEqual([]) - - const next = session.send('next-send') - // Submitting is not acceptance; a refused send must not retire retained work. - expect(session.records()).toContain('Run 45s sleep command:settled:succeeded') - session.accept(next) - expect(session.records()).toEqual([]) - }) - - it('keeps a background shell through the wake its completion opens, and a steer into that wake retires it', async () => { - const session = await wiredSession() - const { firstTurn, wake } = backgroundWakeCapture({ - sessionId: PROVIDER_SESSION_ID, - first: 'first-uuid', - steer: 'steer-uuid' - }) - session.accept(session.send('first-uuid')) - session.replay(firstTurn) - expect(session.running()).toEqual(['Sleep then print marker:live:']) - - const wakeInit = wake.findIndex((captured) => captured.frame.subtype === 'init') - session.replay(wake.slice(0, wakeInit + 1)) - expect(session.rootTurns()).toHaveLength(2) - expect(session.records()).toEqual(['Sleep then print marker:settled:succeeded']) - expect(session.running()).toEqual([]) - - session.accept(session.send('steer-uuid')) - expect(session.records()).toEqual([]) - session.replay(wake.slice(wakeInit + 1)) - expect(session.records()).toEqual([]) - }) -}) diff --git a/src/main/claude/claude-captured-fold-steer-frames.test-fixture.ts b/src/main/claude/claude-captured-fold-steer-frames.test-fixture.ts deleted file mode 100644 index 978ca55e122..00000000000 --- a/src/main/claude/claude-captured-fold-steer-frames.test-fixture.ts +++ /dev/null @@ -1,254 +0,0 @@ -// CLI 2.1.280 captures: sanitized IDs/paths/prompts; original frame order and send-relative times. - -import { - assistant, - assistantText, - assistantToolUse, - initFrame, - resultFrame, - sessionIdle, - taskFrame, - toolResult, - userReplay, - type CapturedFoldFrame, - type FoldCaptureIds -} from './claude-fold-steer-frame-builders.test-fixture' - -export type { CapturedFoldFrame, FoldCaptureIds } - -export const FIRST_PROMPT = 'Run the sleep command three times, then reply: FIRST DONE' -export const STEER_PROMPT = 'Also say the word banana at the end of your reply.' -export const SECOND_STEER_PROMPT = 'And also say the word mango at the very end.' - -export const FOLD_FRESH_SEND_AT = { first: 12, steer: 3_878 } -export function foldFreshCapture({ sessionId, first, steer }: FoldCaptureIds): CapturedFoldFrame[] { - return [ - initFrame(222, sessionId), - userReplay(2_094, sessionId, first, FIRST_PROMPT), - assistantToolUse(2_676, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]), - toolResult(7_890, sessionId, 'tool-result-1', 'toolu_sleep_1'), - userReplay(7_892, sessionId, steer, STEER_PROMPT), - assistantToolUse(9_725, sessionId, 'reply-tool-2', 'toolu_sleep_2'), - toolResult(14_740, sessionId, 'tool-result-2', 'toolu_sleep_2'), - assistantText(23_039, sessionId, 'reply-text-1', 'FIRST DONE banana'), - resultFrame(23_048, sessionId, 'result-1', { - userMessageUuids: [first, steer], - durationMs: 22_845, - numTurns: 4 - }), - sessionIdle(23_049, sessionId) - ] -} - -export const FOLD_RESUMED_SEND_AT = { first: 12, steer: 4_458 } -export function foldResumedCapture({ - sessionId, - first, - steer -}: FoldCaptureIds): CapturedFoldFrame[] { - return [ - initFrame(218, sessionId), - userReplay(2_057, sessionId, first, FIRST_PROMPT), - assistant( - 3_229, - sessionId, - 'reply-thinking-1', - [{ type: 'thinking', thinking: 'plan' }], - [first] - ), - assistantToolUse(3_258, sessionId, 'reply-tool-1', 'toolu_sleep_1'), - toolResult(8_464, sessionId, 'tool-result-1', 'toolu_sleep_1'), - userReplay(8_467, sessionId, steer, STEER_PROMPT), - assistantToolUse(10_318, sessionId, 'reply-tool-2', 'toolu_sleep_2'), - toolResult(15_373, sessionId, 'tool-result-2', 'toolu_sleep_2'), - assistantText(23_587, sessionId, 'reply-text-1', 'FIRST DONE banana'), - resultFrame(23_628, sessionId, 'result-1', { - userMessageUuids: [first, steer], - durationMs: 23_367, - numTurns: 4 - }), - sessionIdle(23_640, sessionId) - ] -} - -export const TWO_STEERS_SEND_AT = { first: 31, steer: 3_630, secondSteer: 5_031 } -export function twoSteersCapture({ - sessionId, - first, - steer, - secondSteer -}: Required): CapturedFoldFrame[] { - return [ - initFrame(351, sessionId), - userReplay(1_169, sessionId, first, FIRST_PROMPT), - assistantToolUse(2_412, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]), - toolResult(7_949, sessionId, 'tool-result-1', 'toolu_sleep_1'), - userReplay(7_963, sessionId, steer, STEER_PROMPT), - userReplay(7_967, sessionId, secondSteer, SECOND_STEER_PROMPT), - assistantToolUse(9_806, sessionId, 'reply-tool-2', 'toolu_sleep_2'), - toolResult(14_835, sessionId, 'tool-result-2', 'toolu_sleep_2'), - assistantText(22_210, sessionId, 'reply-text-1', 'FIRST DONE banana mango'), - resultFrame(22_317, sessionId, 'result-1', { - userMessageUuids: [first, steer, secondSteer], - durationMs: 21_859, - numTurns: 4 - }), - sessionIdle(22_341, sessionId) - ] -} - -/** A steer replayed after the first result runs in its own turn. */ -export const MISS_SEND_AT = { first: 30, steer: 23_384 } -export function missCapture({ sessionId, first, steer }: FoldCaptureIds): { - beforeSteerSend: CapturedFoldFrame[] - afterSteerSend: CapturedFoldFrame[] -} { - return { - beforeSteerSend: [ - initFrame(333, sessionId), - userReplay(2_118, sessionId, first, FIRST_PROMPT), - assistantToolUse(2_793, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]), - toolResult(8_258, sessionId, 'tool-result-1', 'toolu_sleep_1'), - assistantToolUse(11_019, sessionId, 'reply-tool-2', 'toolu_sleep_2'), - toolResult(15_961, sessionId, 'tool-result-2', 'toolu_sleep_2'), - assistantToolUse(18_362, sessionId, 'reply-tool-3', 'toolu_sleep_3'), - toolResult(23_375, sessionId, 'tool-result-3', 'toolu_sleep_3') - ], - afterSteerSend: [ - assistantText(25_550, sessionId, 'reply-text-1', 'FIRST DONE'), - resultFrame(25_556, sessionId, 'result-1', { - userMessageUuids: [first], - durationMs: 25_241, - numTurns: 4 - }), - initFrame(25_584, sessionId), - userReplay(28_703, sessionId, steer, STEER_PROMPT), - assistantText(29_239, sessionId, 'reply-text-2', 'banana'), - resultFrame(29_275, sessionId, 'result-2', { - userMessageUuids: [steer], - durationMs: 3_711, - numTurns: 1 - }), - sessionIdle(29_306, sessionId) - ] - } -} - -/** Cancelled steer has no replay; the synthetic interrupt text is not a send. */ -export const CANCEL_SEND_AT = { first: 18, steer: 3_578 } -export function cancelCapture({ sessionId, first, steer: _steer }: FoldCaptureIds): { - beforeSteerSend: CapturedFoldFrame[] - afterInterrupt: CapturedFoldFrame[] -} { - return { - beforeSteerSend: [ - initFrame(354, sessionId), - userReplay(1_329, sessionId, first, FIRST_PROMPT), - assistantToolUse(2_366, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]) - ], - afterInterrupt: [ - toolResult( - 3_889, - sessionId, - 'tool-result-1', - 'toolu_sleep_1', - "The user doesn't want to proceed with this tool use.", - true - ), - { - at: 3_900, - frame: { - type: 'user', - session_id: sessionId, - parent_tool_use_id: null, - uuid: 'interrupt-notice-1', - message: { - role: 'user', - content: [{ type: 'text', text: '[Request interrupted by user for tool use]' }] - } - } - }, - resultFrame(3_926, sessionId, 'result-1', { - userMessageUuids: [first], - durationMs: 3_573, - numTurns: 3, - subtype: 'error_during_execution', - isError: true, - terminalReason: 'aborted_tools' - }), - sessionIdle(3_941, sessionId) - ] - } -} - -/** A steer before the first replay still folds into one result naming both sends. */ -export const EARLY_STEER_SEND_AT = { first: 11, steer: 312 } -export function earlySteerCapture({ - sessionId, - first, - steer -}: FoldCaptureIds): CapturedFoldFrame[] { - return [ - initFrame(205, sessionId), - userReplay(1_208, sessionId, first, FIRST_PROMPT), - assistantToolUse(2_190, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]), - toolResult(6_316, sessionId, 'tool-result-1', 'toolu_sleep_1'), - userReplay(6_318, sessionId, steer, STEER_PROMPT), - assistantText(7_336, sessionId, 'reply-text-1', 'FIRST DONE banana'), - resultFrame(7_340, sessionId, 'result-1', { - userMessageUuids: [first, steer], - durationMs: 7_155, - numTurns: 2 - }), - sessionIdle(7_341, sessionId) - ] -} - -/** Completion precedes wake init; the new cycle has no user replay or result send IDs. */ -export function backgroundWakeCapture({ sessionId, first }: FoldCaptureIds): { - firstTurn: CapturedFoldFrame[] - wake: CapturedFoldFrame[] -} { - return { - firstTurn: [ - initFrame(252, sessionId), - userReplay(1_193, sessionId, first, FIRST_PROMPT), - assistantToolUse(2_372, sessionId, 'reply-tool-1', 'toolu_bg_1', [first]), - taskFrame(2_530, sessionId, 'task_started', { - task_id: 'task_bg_1', - tool_use_id: 'toolu_bg_1', - description: 'Sleep then print marker', - is_backgrounded: true, - task_type: 'local_bash' - }), - toolResult(2_532, sessionId, 'tool-result-1', 'toolu_bg_1'), - assistantText(3_403, sessionId, 'reply-text-1', 'STARTED'), - resultFrame(3_406, sessionId, 'result-1', { - userMessageUuids: [first], - durationMs: 3_177, - numTurns: 2 - }), - sessionIdle(3_407, sessionId) - ], - wake: [ - taskFrame(17_547, sessionId, 'task_updated', { - task_id: 'task_bg_1', - patch: { status: 'completed' } - }), - taskFrame(17_547, sessionId, 'task_notification', { - task_id: 'task_bg_1', - tool_use_id: 'toolu_bg_1', - status: 'completed', - summary: 'Background command completed (exit code 0)' - }), - initFrame(17_626, sessionId), - assistantText(19_721, sessionId, 'wake-text-1', 'The background command finished.'), - resultFrame(19_729, sessionId, 'result-2', { - userMessageUuids: [], - durationMs: 2_105, - numTurns: 1 - }), - sessionIdle(19_730, sessionId) - ] - } -} diff --git a/src/main/claude/claude-captured-foreground-frames.test-fixture.ts b/src/main/claude/claude-captured-foreground-frames.test-fixture.ts deleted file mode 100644 index 161bc7642d2..00000000000 --- a/src/main/claude/claude-captured-foreground-frames.test-fixture.ts +++ /dev/null @@ -1,145 +0,0 @@ -// CLI 2.1.280 captures: sanitized IDs/paths/prompts; original frame order and send-relative times. - -import { - result, - spawn, - system, - toolResult, - type CapturedFrame -} from './claude-captured-frame-builders.test-fixture' - -const interruptedAgentStart = (at: number, toolUseId: string): CapturedFrame[] => [ - { - at, - frame: spawn(toolUseId, 'Agent', { description: 'Run sleep command and report' }, null) - }, - { - at: at + 16, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: toolUseId, - description: 'Run sleep command and report', - subagent_type: 'general-purpose', - is_backgrounded: false, - task_type: 'local_agent' - }) - }, - { - at: at + 4_357, - frame: system('task_progress', { - task_id: 'agent-1', - tool_use_id: toolUseId, - usage: { total_tokens: 18_844, tool_uses: 1, duration_ms: 4_342 }, - last_tool_name: 'Bash' - }) - } -] - -const REJECTED = "The user doesn't want to proceed with this tool use. The tool use was rejected." - -/** An interrupt while the foreground agent sits between tools: its own stop comes first. */ -export const INTERRUPTED_BETWEEN_TOOLS: CapturedFrame[] = [ - ...interruptedAgentStart(5_000, 'toolu_agent'), - { - at: 11_019, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'killed' } }) - }, - { - at: 11_019, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'stopped', - summary: 'Run sleep command and report' - }) - }, - { at: 11_020, frame: toolResult('toolu_agent', REJECTED, null, true) }, - { at: 11_026, frame: result('error_during_execution') } -] - -/** An interrupt while the foreground agent's own shell runs: the spawn result precedes its stop. */ -export const INTERRUPTED_IN_OWN_SHELL: CapturedFrame[] = [ - ...interruptedAgentStart(2_876, 'toolu_agent'), - { - at: 6_317, - frame: spawn('toolu_shell', 'Bash', { command: 'sleep 45; echo 1' }, 'toolu_agent') - }, - { - at: 9_424, - frame: system('task_started', { - task_id: 'shell-1', - owned_by_subagent: true, - tool_use_id: 'toolu_shell', - description: 'Sleep 45 seconds then print 1', - is_backgrounded: false, - task_type: 'local_bash' - }) - }, - { - at: 11_321, - frame: system('task_notification', { - task_id: 'shell-1', - tool_use_id: 'toolu_shell', - status: 'stopped', - summary: 'Sleep 45 seconds then print 1' - }) - }, - { at: 11_324, frame: toolResult('toolu_agent', REJECTED, null, true) }, - { - at: 11_325, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'killed' } }) - }, - { - at: 11_325, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'stopped', - summary: 'Run sleep command and report' - }) - }, - { at: 11_328, frame: result('error_during_execution') } -] - -/** A foreground agent that finishes: its own ending, then its summary, then the spawn result. */ -export const FOREGROUND_SUCCESS: CapturedFrame[] = [ - { at: 3_695, frame: spawn('toolu_agent', 'Agent', { description: 'Run echo hi command' }, null) }, - { - at: 3_709, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - description: 'Run echo hi command', - subagent_type: 'general-purpose', - is_backgrounded: false, - task_type: 'local_agent' - }) - }, - { - at: 5_501, - frame: system('task_progress', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - usage: { total_tokens: 14_576, tool_uses: 1, duration_ms: 1_792 }, - last_tool_name: 'Bash' - }) - }, - { at: 5_505, frame: spawn('toolu_echo', 'Bash', { command: 'echo hi' }, 'toolu_agent') }, - { at: 5_652, frame: toolResult('toolu_echo', 'hi', 'toolu_agent', false) }, - { - at: 7_101, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } }) - }, - { - at: 7_101, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'completed', - summary: 'The command executed successfully. Output: `hi`', - usage: { total_tokens: 16_908, tool_uses: 1, duration_ms: 3_393 } - }) - }, - { at: 7_113, frame: toolResult('toolu_agent', 'hi', null) }, - { at: 8_952, frame: result('success') } -] diff --git a/src/main/claude/claude-captured-frame-builders.test-fixture.ts b/src/main/claude/claude-captured-frame-builders.test-fixture.ts deleted file mode 100644 index a090fb0198b..00000000000 --- a/src/main/claude/claude-captured-frame-builders.test-fixture.ts +++ /dev/null @@ -1,59 +0,0 @@ -export type CapturedFrame = { at: number; frame: Record } - -export function spawn( - id: string, - name: string, - input: Record, - parent: string | null -) { - return { - type: 'assistant', - parent_tool_use_id: parent, - message: { - id: `msg-${id}`, - role: 'assistant', - content: [{ type: 'tool_use', id, name, input }] - } - } -} - -export function toolResult( - toolUseId: string, - content: string, - parent: string | null, - isError?: boolean -) { - return { - type: 'user', - parent_tool_use_id: parent, - message: { - role: 'user', - content: [ - { - type: 'tool_result', - tool_use_id: toolUseId, - content, - ...(isError === undefined ? {} : { is_error: isError }) - } - ] - } - } -} - -export function says(id: string, text: string, parent: string | null) { - return { - type: 'assistant', - parent_tool_use_id: parent, - message: { id: `msg-${id}`, role: 'assistant', content: [{ type: 'text', text }] } - } -} - -export function system(subtype: string, fields: Record) { - return { type: 'system', subtype, ...fields } -} - -export const result = (subtype: string) => ({ - type: 'result', - subtype, - is_error: subtype !== 'success' -}) diff --git a/src/main/claude/claude-captured-task-frames.test-fixture.ts b/src/main/claude/claude-captured-task-frames.test-fixture.ts deleted file mode 100644 index 42dc0337d96..00000000000 --- a/src/main/claude/claude-captured-task-frames.test-fixture.ts +++ /dev/null @@ -1,224 +0,0 @@ -// CLI 2.1.280 captures: sanitized IDs/paths/prompts; original frame order and send-relative times. - -import { - result, - says, - spawn, - system, - toolResult, - type CapturedFrame -} from './claude-captured-frame-builders.test-fixture' - -/** Parent finishes while the backgrounded agent's shell keeps running. */ -export const MOVED_TO_BACKGROUND: CapturedFrame[] = [ - { - at: 3_259, - frame: spawn( - 'toolu_agent', - 'Agent', - { description: 'Run 45s sleep command', run_in_background: false }, - null - ) - }, - { - at: 3_275, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - description: 'Run 45s sleep command', - subagent_type: 'general-purpose', - is_backgrounded: false, - task_type: 'local_agent' - }) - }, - { - at: 6_126, - frame: system('task_progress', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - description: 'Running Sleep 45 seconds then print 1', - usage: { total_tokens: 18_837, tool_uses: 1, duration_ms: 2_852 }, - last_tool_name: 'Bash' - }) - }, - { - at: 6_127, - frame: spawn( - 'toolu_shell', - 'Bash', - { command: 'sleep 45; echo 1', description: 'Sleep 45 seconds then print 1' }, - 'toolu_agent' - ) - }, - { - at: 9_249, - frame: system('task_started', { - task_id: 'shell-1', - owned_by_subagent: true, - tool_use_id: 'toolu_shell', - description: 'Sleep 45 seconds then print 1', - is_backgrounded: false, - task_type: 'local_bash' - }) - }, - { - at: 11_128, - frame: system('background_tasks_changed', { - tasks: [ - { task_id: 'agent-1', task_type: 'local_agent', description: 'Run 45s sleep command' } - ] - }) - }, - { - at: 11_128, - frame: system('task_updated', { task_id: 'agent-1', patch: { is_backgrounded: true } }) - }, - { - at: 11_139, - frame: toolResult('toolu_agent', 'Async agent launched successfully.', null) - }, - { at: 12_563, frame: says('parent-1', 'The agent has been launched.', null) }, - { at: 12_610, frame: result('success') }, - { - at: 51_275, - frame: system('task_notification', { - task_id: 'shell-1', - tool_use_id: 'toolu_shell', - status: 'completed', - summary: 'Sleep 45 seconds then print 1' - }) - }, - { at: 51_292, frame: toolResult('toolu_shell', '1', 'toolu_agent', false) }, - { at: 52_398, frame: says('agent-1-final', 'Exact stdout: `1`', 'toolu_agent') }, - { at: 52_441, frame: system('background_tasks_changed', { tasks: [] }) }, - { - at: 52_441, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } }) - }, - { - at: 52_441, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'completed', - summary: 'The command completed after ~45 seconds. Exact stdout: `1`', - usage: { total_tokens: 22_160, tool_uses: 1, duration_ms: 49_167 } - }) - }, - { at: 54_303, frame: says('parent-2', 'The agent ran the command.', null) }, - { at: 54_450, frame: result('success') } -] - -/** Messaging a finished agent resumes it under the message call, after its roster entry. */ -export const RESUMED_BY_MESSAGE: CapturedFrame[] = [ - { - at: 3_279, - frame: spawn( - 'toolu_agent', - 'Agent', - { description: 'Run echo first-run command', run_in_background: true }, - null - ) - }, - { - at: 3_320, - frame: system('background_tasks_changed', { - tasks: [ - { task_id: 'agent-1', task_type: 'local_agent', description: 'Run echo first-run command' } - ] - }) - }, - { - at: 3_322, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - description: 'Run echo first-run command', - subagent_type: 'general-purpose', - is_backgrounded: true, - task_type: 'local_agent' - }) - }, - { at: 3_349, frame: toolResult('toolu_agent', 'Async agent launched successfully.', null) }, - { at: 4_765, frame: result('success') }, - { - at: 5_077, - frame: system('task_progress', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - usage: { total_tokens: 13_615, tool_uses: 1, duration_ms: 1_759 }, - last_tool_name: 'Bash' - }) - }, - { at: 7_427, frame: system('background_tasks_changed', { tasks: [] }) }, - { - at: 7_427, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } }) - }, - { - at: 7_427, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'completed', - summary: 'The command executed successfully. Output: `first-run`', - usage: { total_tokens: 15_971, tool_uses: 1, duration_ms: 4_110 } - }) - }, - { at: 10_960, frame: result('success') }, - { - at: 16_118, - frame: spawn( - 'toolu_message', - 'SendMessage', - { to: 'agent-1', message: 'Run echo second-run and report.' }, - null - ) - }, - { - at: 16_142, - frame: system('background_tasks_changed', { - tasks: [ - { task_id: 'agent-1', task_type: 'local_agent', description: 'Run echo first-run command' } - ] - }) - }, - { - at: 16_143, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: 'toolu_message', - description: 'Run echo first-run command', - subagent_type: 'general-purpose', - is_backgrounded: true, - task_type: 'local_agent' - }) - }, - { at: 16_166, frame: toolResult('toolu_message', '{"success":true}', null) }, - { at: 17_420, frame: result('success') }, - { - at: 17_889, - frame: system('task_progress', { - task_id: 'agent-1', - tool_use_id: 'toolu_message', - usage: { total_tokens: 16_064, tool_uses: 2, duration_ms: 14_568 }, - last_tool_name: 'Bash' - }) - }, - { at: 19_568, frame: system('background_tasks_changed', { tasks: [] }) }, - { - at: 19_568, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } }) - }, - { - at: 19_568, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_message', - status: 'completed', - summary: 'The command executed successfully. Output: `second-run`', - usage: { total_tokens: 16_259, tool_uses: 2, duration_ms: 16_249 } - }) - }, - { at: 20_956, frame: result('success') } -] diff --git a/src/main/claude/claude-captured-wake-frames.test-fixture.ts b/src/main/claude/claude-captured-wake-frames.test-fixture.ts deleted file mode 100644 index 8b76c4cdecd..00000000000 --- a/src/main/claude/claude-captured-wake-frames.test-fixture.ts +++ /dev/null @@ -1,121 +0,0 @@ -// CLI 2.1.280 capture: sanitized IDs/prompts; original frame order and spawn-relative times. - -import { - result, - says, - spawn, - system, - toolResult, - type CapturedFrame -} from './claude-captured-frame-builders.test-fixture' - -/** Shell completion resumes the same agent under its original spawn call. */ -export const WAKES_AFTER_ITS_SHELL: CapturedFrame[] = [ - { - at: 0, - frame: spawn( - 'toolu_agent', - 'Agent', - { description: 'Sleep 40 seconds then reply', run_in_background: true }, - null - ) - }, - { - at: 15, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - description: 'Sleep 40 seconds then reply', - subagent_type: 'general-purpose', - is_backgrounded: true, - task_type: 'local_agent' - }) - }, - { at: 30, frame: toolResult('toolu_agent', 'Async agent launched successfully.', null) }, - { at: 1_944, frame: result('success') }, - { - at: 4_343, - frame: spawn( - 'toolu_shell', - 'Bash', - { - command: 'sleep 40', - description: 'Wait 40 seconds in background', - run_in_background: true - }, - 'toolu_agent' - ) - }, - { - at: 4_431, - frame: system('task_started', { - task_id: 'shell-1', - owned_by_subagent: true, - tool_use_id: 'toolu_shell', - description: 'Wait 40 seconds in background', - is_backgrounded: true, - task_type: 'local_bash' - }) - }, - { - at: 4_441, - frame: toolResult( - 'toolu_shell', - 'Command running in background with ID: shell-1.', - 'toolu_agent' - ) - }, - { - at: 11_913, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } }) - }, - { - at: 11_913, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'completed', - summary: '`sleep 40` is still running in the background.', - usage: { total_tokens: 17_928, tool_uses: 2, duration_ms: 11_901 } - }) - }, - { - at: 44_454, - frame: system('task_updated', { task_id: 'shell-1', patch: { status: 'completed' } }) - }, - { - at: 44_454, - frame: system('task_notification', { - task_id: 'shell-1', - tool_use_id: 'toolu_shell', - status: 'completed', - summary: 'Background command "Wait 40 seconds in background" completed (exit code 0)' - }) - }, - { - at: 44_460, - frame: system('task_started', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - description: 'Sleep 40 seconds then reply', - subagent_type: 'general-purpose', - is_backgrounded: true, - task_type: 'local_agent' - }) - }, - { at: 46_198, frame: says('agent-1-final', 'DONE', 'toolu_agent') }, - { - at: 46_198, - frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } }) - }, - { - at: 46_199, - frame: system('task_notification', { - task_id: 'agent-1', - tool_use_id: 'toolu_agent', - status: 'completed', - summary: 'DONE', - usage: { total_tokens: 18_181, tool_uses: 2, duration_ms: 46_184 } - }) - } -] diff --git a/src/main/claude/claude-child-exit-proof-fixture.ts b/src/main/claude/claude-child-exit-proof-fixture.ts deleted file mode 100644 index f157807d036..00000000000 --- a/src/main/claude/claude-child-exit-proof-fixture.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import { - spawnManagedProviderProcess, - type ManagedProviderProcess -} from '../provider-process/managed-provider-process' -import { claudeChildClosePolicy, claudeChildCloseProven } from './claude-child-exit-proof-ladder' - -const managedChildren = new WeakMap() - -/** `closePlatform` picks the close rules; the spawn itself always skips the POSIX supervisor. */ -export function managedChild( - child: ChildProcessWithoutNullStreams, - closePlatform: NodeJS.Platform = 'linux' -): ManagedProviderProcess { - const existing = managedChildren.get(child) - if (existing) { - return existing - } - const managed = spawnManagedProviderProcess( - { command: 'fixture-provider', args: [] }, - { - spawnImpl: () => child, - platform: 'win32', - site: 'claude-proof-fixture', - policy: (supervised) => claudeChildClosePolicy(supervised, closePlatform), - acceptClose: claudeChildCloseProven - } - ) - managedChildren.set(child, managed) - return managed -} diff --git a/src/main/claude/claude-child-work-producer-harness.test-fixture.ts b/src/main/claude/claude-child-work-producer-harness.test-fixture.ts deleted file mode 100644 index 68009ae669c..00000000000 --- a/src/main/claude/claude-child-work-producer-harness.test-fixture.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { expect } from 'vitest' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission' -import type { AgentChildWorkRecord } from '../../shared/agent-status/child-work/agent-status-child-work' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation' -import type { AgentChildWorkReconcileOutcome } from '../../shared/agent-status/child-work/agent-status-child-work-evidence-admission' -import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store' -import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' -import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter' -import { - fakeClaude, - identityFor, - PROVIDER_SESSION_ID -} from './structured/claude-structured-session-test-support' - -export const parent = makeStructuredAgentStatusSubject( - { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - 'session-1' -) - -let uuid = 0 -export function frame(fields: Record): Record { - return { session_id: PROVIDER_SESSION_ID, uuid: `frame-${++uuid}`, ...fields } -} -export function system(subtype: string, fields: Record) { - return frame({ type: 'system', subtype, ...fields }) -} -export function toolUse( - id: string, - name: string, - input: unknown, - parentToolUseId: string | null = null -) { - return frame({ - type: 'assistant', - parent_tool_use_id: parentToolUseId, - message: { - id: `msg-${id}`, - role: 'assistant', - content: [{ type: 'tool_use', id, name, input }] - } - }) -} -export function toolResult( - toolUseId: string, - text: string, - parentToolUseId: string | null = null, - isError = false -) { - return frame({ - type: 'user', - parent_tool_use_id: parentToolUseId, - message: { - role: 'user', - content: [{ type: 'tool_result', tool_use_id: toolUseId, content: text, is_error: isError }] - } - }) -} - -type Delivery = { kind: 'journal' | 'publish' | 'evidence'; detail: string } - -export type JournaledItem = Pick - -export const T0 = 1_700_000_000_500 - -export function hostWithParent(): AgentHookServer { - const host = new AgentHookServer() - host.ingestStructuredStatus( - { - sessionId: parent.sessionId, - workspaceId: parent.workspaceId, - agent: 'claude', - status: 'working', - hostExecutionOwned: true, - latestPrompt: 'find the flaky tests', - updatedAt: 100 - }, - parent - ) - return host -} - -/** With `host`, evidence goes through the host's own ingest instead of straight to reconciliation. */ -export async function producer(host?: AgentHookServer) { - const claude = fakeClaude() - const store = createAgentStatusStore({ epoch: 'epoch-1', mode: 'authority' }) - expect(store.applyMutation({ parent: { subject: parent } })).not.toBeNull() - const admission = createAgentChildWorkAdmission(store, { - mintChildWorkId: (() => { - let minted = 0 - return () => `child-${++minted}` - })() - }) - let clock = T0 - const deliveries: Delivery[] = [] - /** The producer linkage the journal stamped on each child row. */ - const stamps: { providerParentRef?: string; attempt?: number }[] = [] - const evidenceLog: AgentChildWorkEvidence[][] = [] - const ingested: (AgentChildWorkReconcileOutcome | null)[] = [] - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - now: () => clock, - persistHandle: async () => {}, - onChildWorkEvidence: (sessionId, evidence) => { - expect(sessionId).toBe('session-1') - deliveries.push({ kind: 'evidence', detail: evidence.map((edge) => edge.type).join(',') }) - evidenceLog.push(evidence) - if (host) { - ingested.push(host.ingestStructuredChildWork(parent, evidence, 'claude')) - } else { - reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence }) - } - } - }) - const journalItems = new Map() - const journal: StructuredAgentSessionEventSink = { - appendItem: (identity, body, options) => { - deliveries.push({ kind: 'journal', detail: JSON.stringify(identity) }) - const itemId = agentJournalItemKey(identity) - journalItems.set(itemId, { - itemId, - body, - sequence: journalItems.get(itemId)?.sequence ?? journalItems.size + 1, - ...(options?.agentId ? { agentId: options.agentId } : {}) - }) - if (options?.agentId !== undefined) { - stamps.push(options) - } - }, - appendTombstone: () => {}, - // Production's journal publication is what republishes the parent's own row. - publish: () => deliveries.push({ kind: 'publish', detail: '' }) - } - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: journal - }) - const send = (message: Record): Delivery[] => { - const from = deliveries.length - claude.connections[0]!.handlers.onMessage?.(message) - return deliveries.slice(from) - } - const replay = (frames: readonly CapturedFrame[]) => { - for (const { at, frame: captured } of frames) { - clock = T0 + at - send(frame(captured)) - } - } - const records = (): AgentChildWorkRecord[] => - host ? host.getStructuredChildWork(parent) : store.getChildren(parent) - const byDescription = (description: string) => - records().find((record) => record.description === description) - return { - adapter, - claude, - now: () => clock, - store, - send, - replay, - records, - byDescription, - evidenceLog, - stamps, - ingested, - journalItems - } -} diff --git a/src/main/claude/claude-cli-conversations.ts b/src/main/claude/claude-cli-conversations.ts index 6a83df22ef2..3932bd830e0 100644 --- a/src/main/claude/claude-cli-conversations.ts +++ b/src/main/claude/claude-cli-conversations.ts @@ -8,7 +8,7 @@ import { type StructuredAgentResumeInvocation, type StructuredAgentCliConversations, type StructuredAgentSessionHistory -} from '../native-chat/structured-agent-cli-conversations' +} from '../native-chat/conversation-adoption/structured-agent-cli-conversations' const CLAUDE_TRANSCRIPT_IMPORT = directoryTranscriptImport({ conversationStore: ({ accountHomePath }) => join(accountHomePath, 'projects'), diff --git a/src/main/claude/claude-close-turn-end.test.ts b/src/main/claude/claude-close-turn-end.test.ts deleted file mode 100644 index 8dd69e3cbaa..00000000000 --- a/src/main/claude/claude-close-turn-end.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Close supplies no turn outcome; a prior observed exit keeps its own cause. - -import { describe, expect, it } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalTurnLifecycle -} from '../../shared/agent-session/journal/agent-session-journal-types' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state' -import { - PROVIDER_SESSION_ID, - adapterFor, - fakeClaude, - identityFor, - tick -} from './structured/claude-structured-session-test-support' - -function turnSink() { - const turns: AgentJournalTurnLifecycle[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (_identity, body: AgentJournalItemBody) => { - const turn = readAgentJournalTurn(body) - if (turn) { - turns.push(turn) - } - }, - appendTombstone: () => {}, - publish: () => {} - } - return { sink, turns } -} - -async function childInsideTurn() { - const claude = fakeClaude() - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = adapterFor(claude, {}, events) - const { sink, turns } = turnSink() - await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9', events: sink }) - const connection = claude.connections[0]! - connection.handlers.onMessage?.({ - session_id: PROVIDER_SESSION_ID, - type: 'assistant', - uuid: 'assistant-1', - parent_tool_use_id: null, - message: { role: 'assistant', content: [{ type: 'text', text: 'working' }] } - }) - await tick() - expect(turns.at(-1)).toMatchObject({ state: 'running' }) - return { adapter, connection, events, turns } -} - -describe('a Claude close settles the open turn with no verdict of its own', () => { - it('ends it interrupted, with no outcome', async () => { - const { adapter, turns } = await childInsideTurn() - - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - - expect(turns.at(-1)).toMatchObject({ state: 'interrupted' }) - expect(turns.at(-1)).not.toHaveProperty('outcome') - }) - - it('settles a crash it saw before the close once, as that exit', async () => { - const { adapter, connection, events, turns } = await childInsideTurn() - connection.handlers.onExit?.(new Error('provider exited')) - - await adapter.closeSession('session-1') - await tick() - - const settled = turns.filter((turn) => turn.state !== 'running') - expect(settled).toEqual([expect.objectContaining({ state: 'interrupted' })]) - expect(settled[0]).not.toHaveProperty('outcome') - expect(events.filter((event) => event.type === 'ended')).toEqual([ - expect.objectContaining({ cause: 'unexpected-exit' }) - ]) - }) -}) diff --git a/src/main/claude/claude-command-lifecycle.test.ts b/src/main/claude/claude-command-lifecycle.test.ts deleted file mode 100644 index 312dcfccedc..00000000000 --- a/src/main/claude/claude-command-lifecycle.test.ts +++ /dev/null @@ -1,345 +0,0 @@ -// Recorded CLI 2.1.280 lifecycle frames replay regardless of control-request success or loss. - -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import { DISPATCH_REJECTED_CANCELLED } from '../../shared/agent-session/requests/structured-agent-session-dispatch-rejection' -import { DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED } from '../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons' -import { ClaudeControlRequestError } from './claude-agent-sdk-control-requests' -import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter' -import type { ClaudeLateDispatchOutcome } from './structured/claude-structured-session-state' -import { - fakeClaude, - identityFor, - PROVIDER_SESSION_ID, - type FakeConnection -} from './structured/claude-structured-session-test-support' -import { claudeStartupSettled } from './structured/claude-structured-startup-settled-test-support' - -type CapturedEvent = - | { kind: 'meta'; providerSessionId: string } - | { kind: 'frame'; frame: Record } - | { kind: 'dispatch'; clientMessageId: string; sentUuid: string; text: string } - | { kind: 'control'; request: Record } - | { kind: 'control-answer'; response: Record } - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function decodeCapturedEvent(value: unknown): CapturedEvent { - if (!isRecord(value)) { - throw new Error('capture line is not a recorded event') - } - if (value.kind === 'meta' && typeof value.providerSessionId === 'string') { - return { kind: 'meta', providerSessionId: value.providerSessionId } - } - if (value.kind === 'frame' && isRecord(value.frame)) { - return { kind: 'frame', frame: value.frame } - } - if ( - value.kind === 'dispatch' && - typeof value.clientMessageId === 'string' && - typeof value.sentUuid === 'string' && - typeof value.text === 'string' - ) { - return { - kind: 'dispatch', - clientMessageId: value.clientMessageId, - sentUuid: value.sentUuid, - text: value.text - } - } - if (value.kind === 'control' && isRecord(value.request)) { - return { kind: 'control', request: value.request } - } - if (value.kind === 'control-answer' && isRecord(value.response)) { - return { kind: 'control-answer', response: value.response } - } - throw new Error(`capture line has unknown kind: ${String(value.kind)}`) -} - -function loadCapture(name: string): CapturedEvent[] { - const path = join(__dirname, '__fixtures__', `claude-lifecycle-capture-${name}.jsonl`) - return readFileSync(path, 'utf8') - .trim() - .split('\n') - .map((line) => decodeCapturedEvent(JSON.parse(line))) -} - -type Settlement = { sessionId: string } & ClaudeLateDispatchOutcome - -type ControlPoint = { - request: Record - /** Captured answer with UUIDs mapped to this replay. */ - answer: Record - deliverInFlight: () => void - adapter: ClaudeStructuredSessionAdapter - connection: FakeConnection - routes: ReturnType['routes'] - liveUuid: (clientMessageId: string) => string -} - -async function replayCapture( - name: string, - options: { - /** Defaults to replaying in-flight frames without a host control action. */ - atControl?: (point: ControlPoint) => Promise - /** Remove capabilities to simulate older CLIs. */ - withoutCapabilities?: string[] - omitFrame?: (frame: Record) => boolean - /** Added frames use captured UUIDs. */ - afterFrame?: (frame: Record) => Record[] - rewriteFrame?: (frame: Record) => Record - /** Capture tails answer the CLI's original control request. */ - stopAfterControl?: boolean - } = {} -) { - const capture = loadCapture(name) - const settlements: Settlement[] = [] - const turnStates = new Map() - const claude = fakeClaude({ initProof: 'none', replayUuid: null }) - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1, - now: () => 1_700_000_200_000, - persistHandle: async () => {}, - onDispatchSettledLate: (settlement) => settlements.push(settlement) - }) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: { - appendItem: (_identity, body: AgentJournalItemBody) => { - const turn = readAgentJournalTurn(body) - if (turn) { - turnStates.set(turn.turnId, turn.state) - } - }, - appendTombstone: () => {}, - publish: () => {} - } - }) - const connection = claude.connections[0]! - - const uuidMap = new Map() - const capturedSessionId = capture.flatMap((event) => - event.kind === 'meta' ? [event.providerSessionId] : [] - )[0]! - const mapUuids = (value: Record): Record => { - let text = JSON.stringify(value).replaceAll(capturedSessionId, PROVIDER_SESSION_ID) - for (const [captured, live] of uuidMap) { - text = text.replaceAll(captured, live) - } - const mapped: unknown = JSON.parse(text) - if (!isRecord(mapped)) { - throw new Error('mapped frame is not a record') - } - return mapped - } - const deliver = (frame: Record): void => { - if (options.omitFrame?.(frame)) { - return - } - const mapped = mapUuids(options.rewriteFrame?.(frame) ?? frame) - if (Array.isArray(mapped.capabilities) && options.withoutCapabilities) { - mapped.capabilities = mapped.capabilities.filter( - (capability) => !options.withoutCapabilities!.includes(String(capability)) - ) - } - connection.handlers.onMessage?.(mapped) - for (const extra of options.afterFrame?.(frame) ?? []) { - connection.handlers.onMessage?.(mapUuids(extra)) - } - } - const liveUuid = (clientMessageId: string): string => { - const dispatch = capture.find( - (event) => event.kind === 'dispatch' && event.clientMessageId === clientMessageId - ) - return dispatch?.kind === 'dispatch' ? (uuidMap.get(dispatch.sentUuid) ?? '') : '' - } - - let proofDelivered = false - for (let index = 0; index < capture.length; index++) { - const event = capture[index]! - if (event.kind === 'frame') { - deliver(event.frame) - proofDelivered = true - } else if (event.kind === 'dispatch') { - if (proofDelivered) { - await claudeStartupSettled(adapter, 'session-1') - } - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: event.clientMessageId, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: event.text }] }, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - uuidMap.set(event.sentUuid, String(connection.sent.at(-1)!.uuid)) - } else if (event.kind === 'control') { - const answerAt = capture.findIndex( - (candidate, at) => at > index && candidate.kind === 'control-answer' - ) - if (answerAt === -1) { - throw new Error('capture recorded no answer for its control request') - } - const inFlight = capture.slice(index + 1, answerAt) - const answer = capture[answerAt] - let delivered = false - const deliverInFlight = (): void => { - if (!delivered) { - delivered = true - for (const frameEvent of inFlight) { - if (frameEvent.kind === 'frame') { - deliver(frameEvent.frame) - } - } - } - } - const atControl = options.atControl ?? (async (point) => point.deliverInFlight()) - await atControl({ - request: mapUuids(event.request), - answer: answer?.kind === 'control-answer' ? mapUuids(answer.response) : {}, - deliverInFlight, - adapter, - connection, - routes: claude.routes, - liveUuid - }) - deliverInFlight() - if (options.stopAfterControl) { - break - } - index = answerAt - } - } - const settlementsFor = (clientMessageId: string) => - settlements - .filter((settlement) => settlement.clientMessageId === clientMessageId) - .map(({ sessionId: _sessionId, clientMessageId: _id, ...outcome }) => outcome) - return { settlementsFor, turnStates, liveUuid, connection, adapter } -} - -const WITHDRAWN = { - state: 'rejected', - unrun: true, - reason: DISPATCH_REJECTED_CANCELLED, - rejection: { kind: 'cancelled' } -} - -function acceptedAs(uuid: string) { - return { providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid } } -} - -function stopWithInterruptAnswer(answer: 'recorded' | 'lost') { - return async (point: ControlPoint): Promise => { - point.routes.interrupt = () => { - point.deliverInFlight() - if (answer === 'lost') { - throw new ClaudeControlRequestError('interrupt', 'Control request timed out') - } - return point.answer - } - await point.adapter.cancelTurn({ sessionId: 'session-1', fence: 7 }) - } -} - -describe('a Stop whose interrupt cancelled a queued follow-up (cancel_queued)', () => { - it.each(['recorded', 'lost'] as const)( - 'withdraws the follow-up once when the interrupt answer is %s, and leaves the stopped turn’s message accepted', - async (answer) => { - const replay = await replayCapture('interrupt-lost', { - atControl: stopWithInterruptAnswer(answer) - }) - - expect(replay.connection.calls.filter((call) => call.subtype === 'interrupt')).toEqual([ - { subtype: 'interrupt', params: { cancelQueued: true } } - ]) - expect(replay.settlementsFor('client-B')).toEqual([WITHDRAWN]) - expect(replay.settlementsFor('client-A')).toEqual([acceptedAs(replay.liveUuid('client-A'))]) - } - ) -}) - -describe('a queued send the CLI withdraws without Orca hearing why', () => { - it('withdraws only the batch lead; the send behind it runs as its own turn and is accepted', async () => { - const replay = await replayCapture('batch-lead') - - expect(replay.settlementsFor('client-B')).toEqual([WITHDRAWN]) - expect(replay.settlementsFor('client-A')).toEqual([acceptedAs(replay.liveUuid('client-A'))]) - expect(replay.settlementsFor('client-C')).toEqual([acceptedAs(replay.liveUuid('client-C'))]) - expect([...replay.turnStates.entries()]).toEqual([ - [replay.liveUuid('client-A'), 'completed'], - [replay.liveUuid('client-C'), 'completed'] - ]) - }) -}) - -function isTurnOutput(frame: Record): boolean { - return frame.type === 'user' || frame.type === 'assistant' || frame.type === 'result' -} - -function isLifecycleFrame(frame: Record, state?: string): boolean { - return frame.type === 'command_lifecycle' && (state === undefined || frame.state === state) -} - -const ENDED_IN_DOUBT = { state: 'unknown', reason: DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED } - -describe('a send the CLI started, then cancelled', () => { - it('stays started when a redelivered command re-emits queued before its cancelled frame', async () => { - const replay = await replayCapture('auth-failed', { - omitFrame: isTurnOutput, - afterFrame: (frame) => - isLifecycleFrame(frame, 'started') ? [{ ...frame, state: 'queued' }] : [] - }) - - expect(replay.settlementsFor('client-A')).toEqual([ENDED_IN_DOUBT]) - }) - - it('is still accepted when its echo lands after the doubt', async () => { - const replay = await replayCapture('auth-failed', { omitFrame: isTurnOutput }) - const uuid = replay.liveUuid('client-A') - - replay.connection.handlers.onMessage?.({ - type: 'user', - message: { role: 'user', content: [{ type: 'text', text: 'late echo' }] }, - parent_tool_use_id: null, - session_id: PROVIDER_SESSION_ID, - uuid - }) - - expect(replay.settlementsFor('client-A')).toEqual([ENDED_IN_DOUBT, acceptedAs(uuid)]) - }) -}) - -describe('a send the CLI holds', () => { - // CLI 2.1.280 can report idle before rereading its queue. - - it('holds the child for a send the CLI has only queued, and does not release it at idle', async () => { - const replay = await replayCapture('auth-failed', { - omitFrame: (frame) => - isTurnOutput(frame) || - isLifecycleFrame(frame, 'started') || - isLifecycleFrame(frame, 'cancelled') - }) - - expect(replay.adapter.holdsDispatch('session-1')).toBe(true) - expect(replay.settlementsFor('client-A')).toEqual([]) - }) -}) diff --git a/src/main/claude/claude-command-turn.test.ts b/src/main/claude/claude-command-turn.test.ts deleted file mode 100644 index cd55f33d809..00000000000 --- a/src/main/claude/claude-command-turn.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' -import { - CAPTURED_COMPACT_SESSION_ID, - CAPTURED_COMPACT_STOPPED_THEN_SEND, - type CapturedCompactEvent -} from './claude-captured-compact-frames.test-fixture' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' - -const COMMAND_IDENTITY: AgentJournalItemIdentity = { - provider: 'orca', - clientMessageId: 'command-turn:cmd-1' -} -const COMMAND_KEY = agentJournalItemKey(COMMAND_IDENTITY) -const NOW = 1_800_000_000_000 -const IN_COMMAND: AgentJournalTurnScope = { kind: 'turn', turnItemId: COMMAND_KEY } -const RUNNING = { - kind: 'turn' as const, - turnId: 'compact:cmd-1', - state: 'running' as const, - userItemId: 'orca:submission:cmd-1', - requestedAt: 900, - startedAt: 1_000 -} - -// Usage limits expire by the system clock; pin it so the quota reset stays an hour ahead. -beforeEach(() => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(NOW) -}) -afterEach(() => { - vi.useRealTimers() -}) - -type Row = { key: string; body: AgentJournalItemBody; turnScope?: AgentJournalTurnScope } - -function harness() { - const rows = new Map([[COMMAND_KEY, { key: COMMAND_KEY, body: RUNNING }]]) - const writes: Row[] = [] - const write = ( - identity: AgentJournalItemIdentity, - body: AgentJournalItemBody, - turnScope?: AgentJournalTurnScope - ) => { - const row = { key: agentJournalItemKey(identity), body, ...(turnScope ? { turnScope } : {}) } - rows.set(row.key, row) - writes.push(row) - } - const journal: StructuredAgentSessionRevisionJournal = { - item: () => null, - epoch: 'epoch-1', - itemBody: (itemId) => rows.get(itemId)?.body ?? null, - visitItems: (visit) => { - let sequence = 0 - for (const row of rows.values()) { - visit(row.key, sequence++, row.body) - } - } - } - const revise: NonNullable = ( - _bytes, - resolve, - options - ) => { - const resolved = resolve(journal) - if (resolved) { - write(resolved.identity, resolved.body, options.turnScope) - } - return { accepted: true } - } - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity, body, options) => write(identity, body, options.turnScope), - appendTombstone: vi.fn(), - publish: vi.fn(), - tryReviseResolvedItem: revise, - tryReviseResolvedItemAndPublish: revise - } - const translator = createClaudeJournalTranslator({ sink, fallbackIdPrefix: 'test' }) - const frame = (message: Record, extra: Record = {}) => - translator.handle({ - type: 'message', - sessionId: 'orca-session', - message: { session_id: CAPTURED_COMPACT_SESSION_ID, ...message }, - observedAt: 5_000, - ...extra - }) - const begin = (sentUuid: string) => - translator.beginCommand({ - clientMessageId: 'cmd-1', - turnId: RUNNING.turnId, - identity: COMMAND_IDENTITY, - resultIdentity: { provider: 'orca', clientMessageId: 'command-result:cmd-1' }, - running: RUNNING, - providerSessionId: CAPTURED_COMPACT_SESSION_ID, - sentUuid - }) - const replay = (events: readonly CapturedCompactEvent[]) => { - for (const event of events) { - if ('sent' in event) { - if (event.sent.text === '/compact') { - begin(event.sent.uuid) - } - } else if ('interrupt' in event) { - translator.commandInterruptRequested(RUNNING.turnId) - } else { - frame(event.frame) - } - } - } - const commandTurn = () => readAgentJournalTurn(rows.get(COMMAND_KEY)?.body) - const drawn = () => - [...rows.values()].filter((row) => row.key !== COMMAND_KEY && row.body.kind !== 'turn') - return { translator, rows, writes, frame, begin, replay, commandTurn, drawn } -} - -describe('a captured /compact as the open Claude turn', () => { - it("ends a stopped compaction as the user's cancellation, then answers the next send in its own turn", () => { - const { replay, commandTurn, drawn, rows } = harness() - replay(CAPTURED_COMPACT_STOPPED_THEN_SEND) - - expect(commandTurn()).toMatchObject({ state: 'interrupted', outcome: 'cancellation' }) - const answer = drawn().find((row) => row.body.kind === 'message') - expect(answer?.body).toMatchObject({ role: 'assistant' }) - expect(answer?.turnScope).not.toEqual(IN_COMMAND) - const answered = readAgentJournalTurn( - answer?.turnScope?.kind === 'turn' ? rows.get(answer.turnScope.turnItemId)?.body : undefined - ) - expect(answered).toMatchObject({ state: 'completed', outcome: 'success' }) - expect(drawn().filter((row) => row.body.kind === 'status')).toEqual([]) - }) - - it('leaves the command running at a result that names another input', () => { - const { begin, frame, commandTurn, translator } = harness() - begin('compact-input') - frame({ type: 'system', subtype: 'compact_boundary', uuid: 'boundary' }) - frame({ type: 'result', subtype: 'success', is_error: false, user_message_uuid: 'earlier' }) - expect(commandTurn()?.state).toBe('running') - expect(translator.commandTurnId).toBe(RUNNING.turnId) - - frame({ - type: 'result', - subtype: 'success', - is_error: false, - user_message_uuid: 'compact-input' - }) - expect(commandTurn()).toMatchObject({ state: 'completed', outcome: 'success' }) - }) -}) diff --git a/src/main/claude/claude-context-model-switch.test.ts b/src/main/claude/claude-context-model-switch.test.ts deleted file mode 100644 index 9da11ba40c0..00000000000 --- a/src/main/claude/claude-context-model-switch.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectStructuredAgentContextUsage } from '../../shared/agent-session/structured-agent-session-context-usage' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import { bindClaudeContextUsageCapture } from './claude-context-usage' -import { - assistantFrame, - initFrame, - resultFrame, - setup, - userFrame -} from './claude-context-usage-test-support' - -const SONNET = 'claude-sonnet-5' -const OPUS = 'claude-opus-5-5' -// Shape measured from Claude Code 2.1.280: plan mode under `opusplan` keys Opus with `[1m]`. -const PLAN_USAGE = { - [SONNET]: { contextWindow: 200_000 }, - [`${OPUS}[1m]`]: { contextWindow: 1_000_000 } -} - -const answer = (model: string, totalTokens: number, rawMaxTokens: number) => ({ - model, - totalTokens, - rawMaxTokens, - categories: [] -}) - -function session(init: string) { - const t = setup({ init }) - const pending: ((value: unknown) => void)[] = [] - bindClaudeContextUsageCapture( - { getContextUsage: () => new Promise((resolve) => pending.push(resolve)) }, - t.translator, - { now: () => 90_000 } - ) - const settle = async (): Promise => { - for (let index = 0; index < 4; index += 1) { - await Promise.resolve() - } - } - const reply = async (value: unknown, request = pending.length - 1): Promise => { - pending[request]?.(value) - await settle() - } - const ring = () => selectStructuredAgentContextUsage(t.items()) - const unknownWrites = () => - t.appends.filter( - (entry) => readAgentJournalTurn(entry.body)?.contextUsage?.used?.kind === 'unknown' - ).length - return { ...t, pending, reply, ring, unknownWrites } -} - -describe('the context ring across a model change', () => { - it('holds estimates from the moment an approved plan hands the turn to another model', async () => { - const s = session(SONNET) - s.handle(userFrame('turn-a', 1_000)) - s.handle(assistantFrame('reply-a', 2_000, 100_000, undefined, OPUS)) - s.handle(resultFrame(3_000, PLAN_USAGE)) - await s.reply(answer(`${OPUS}[1m]`, 101_000, 1_000_000)) - s.handle(initFrame(SONNET, 3_900)) - s.handle(userFrame('turn-b', 4_000)) - s.handle(assistantFrame('reply-b1', 5_000, 110_000, undefined, OPUS)) - expect(s.ring()).toMatchObject({ usedTokens: 110_000, windowTokens: 1_000_000 }) - - const requests = s.pending.length - s.handle(assistantFrame('reply-b2', 6_000, 120_000, undefined, SONNET)) - expect(s.ring()).toBeNull() - expect(s.unknownWrites()).toBe(1) - expect(s.pending).toHaveLength(requests + 1) - s.handle(assistantFrame('reply-b3', 7_000, 130_000, undefined, SONNET)) - expect(s.unknownWrites()).toBe(1) - expect(s.turnRow('turn-b')?.body).toMatchObject({ contextUsage: { used: { kind: 'unknown' } } }) - await s.reply(answer(SONNET, 121_000, 200_000), requests) - expect(s.turnRow('turn-b')?.body).toMatchObject({ - contextUsage: { window: { tokens: 200_000 }, used: { kind: 'unknown' } } - }) - s.handle(assistantFrame('reply-b4', 7_500, 140_000, undefined, SONNET)) - expect(s.ring()).toMatchObject({ usedTokens: 140_000, windowTokens: 200_000, percentage: 70 }) - - s.handle(resultFrame(8_000, PLAN_USAGE)) - expect(s.ring()).toMatchObject({ usedTokens: 140_000, windowTokens: 200_000 }) - await s.reply(answer(SONNET, 141_000, 200_000)) - expect(s.ring()).toMatchObject({ usedTokens: 141_000, windowTokens: 200_000, estimated: false }) - s.translator.dispose() - }) - - it('does not let a turn result undo the window a mid-turn switch between 1M and 200k reported', async () => { - const s = session(`${SONNET}[1m]`) - s.handle(userFrame('turn-a', 1_000)) - s.handle(assistantFrame('reply-a', 2_000, 140_000, undefined, SONNET)) - s.handle(resultFrame(3_000, { [`${SONNET}[1m]`]: { contextWindow: 1_000_000 } })) - await s.reply(answer(`${SONNET}[1m]`, 141_000, 1_000_000)) - s.handle(initFrame(`${SONNET}[1m]`, 3_900)) - s.handle(userFrame('turn-b', 4_000)) - s.handle(assistantFrame('reply-b1', 5_000, 145_000, undefined, SONNET)) - - s.translator.modelMayHaveChanged() - const switched = s.pending.length - 1 - s.handle(assistantFrame('reply-b2', 6_000, 150_000, undefined, SONNET)) - await s.reply(answer(SONNET, 151_000, 200_000), switched) - s.handle(assistantFrame('reply-b3', 7_000, 160_000, undefined, SONNET)) - expect(s.ring()).toMatchObject({ usedTokens: 160_000, windowTokens: 200_000, percentage: 80 }) - - s.handle( - resultFrame(8_000, { - [`${SONNET}[1m]`]: { contextWindow: 1_000_000 }, - [SONNET]: { contextWindow: 200_000 } - }) - ) - expect(s.ring()).toMatchObject({ usedTokens: 160_000, windowTokens: 200_000, percentage: 80 }) - s.translator.markContextActivity() - await s.reply(answer(SONNET, 161_000, 200_000)) - s.handle(initFrame(SONNET, 8_900)) - s.handle(userFrame('turn-c', 9_000)) - s.handle(assistantFrame('reply-c', 10_000, 170_000, undefined, SONNET)) - expect(s.ring()).toMatchObject({ usedTokens: 170_000, windowTokens: 200_000, percentage: 85 }) - s.translator.dispose() - }) -}) diff --git a/src/main/claude/claude-context-usage-restart.test.ts b/src/main/claude/claude-context-usage-restart.test.ts deleted file mode 100644 index 2abe111ab79..00000000000 --- a/src/main/claude/claude-context-usage-restart.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { selectStructuredAgentContextUsage } from '../../shared/agent-session/structured-agent-session-context-usage' -import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import '../native-chat/agent-session-wire/termination/structured-agent-session-dead-generation-settlement' -import { settleStaleStructuredAgentSessionState } from '../native-chat/agent-session-wire/termination/structured-agent-session-stale-state-settlement' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import { bindClaudeContextUsageCapture } from './claude-context-usage' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-context-restart-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -function frame(message: Record, observedAt: number, startsTurn = false) { - return { - type: 'message' as const, - sessionId: 'orca-session', - observedAt, - ...(startsTurn ? { startsTurn: true as const } : {}), - message: { session_id: 'claude-session', parent_tool_use_id: null, ...message } - } -} - -const initFrame = (at: number) => - frame({ type: 'system', subtype: 'init', uuid: `init-${at}`, model: 'claude-fable-5-1[1m]' }, at) - -const userFrame = (uuid: string, at: number) => - frame( - { type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text: 'go' }] } }, - at, - true - ) - -const assistantFrame = (uuid: string, at: number, input: number, model = 'claude-fable-5-1') => - frame( - { - type: 'assistant', - uuid, - message: { - role: 'assistant', - model, - content: [{ type: 'text', text: uuid }], - usage: { - input_tokens: input, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0, - output_tokens: 4 - } - } - }, - at - ) - -const resultFrame = (at: number, contextWindow = 1_000_000) => - frame( - { - type: 'result', - subtype: 'success', - is_error: false, - result: 'done', - duration_ms: 10, - uuid: `result-${at}`, - modelUsage: { 'claude-fable-5-1[1m]': { contextWindow } } - }, - at - ) - -const compactBoundary = (at: number) => - frame( - { - type: 'system', - subtype: 'compact_boundary', - uuid: `compact-${at}`, - compact_metadata: { trigger: 'manual', pre_tokens: 150_000 } - }, - at - ) - -const postCompactionReport = { - model: 'claude-fable-5-1[1m]', - totalTokens: 40_000, - rawMaxTokens: 1_000_000, - percentage: 4, - categories: [{ name: 'Messages', tokens: 30_000 }] -} - -async function openJournal(): Promise { - return journals.open({ - identity: { - sessionId: 'orca-session', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('claude-session', null) - }, - now: () => 9_000, - stateDirectory: join(root, 'orca-session') - }) -} - -function acquire(journal: AgentSessionJournal) { - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) - deferred.bind({ journal, fence: 1, publish: () => {} }) - const answers: ((value: unknown) => void)[] = [] - const unbind = bindClaudeContextUsageCapture( - { - getContextUsage: () => new Promise((resolve) => answers.push(resolve)) - }, - translator, - { now: () => 20_000 } - ) - const settle = async (): Promise => { - for (let index = 0; index < 4; index += 1) { - await Promise.resolve() - } - await expect(deferred.drained()).resolves.toEqual({ ok: true }) - } - const detach = (): void => deferred.unbind() - const reattach = (): void => deferred.bind({ journal, fence: 1, publish: () => {} }) - const release = (): void => { - unbind?.() - translator.dispose() - deferred.close() - } - return { translator, answers, settle, detach, reattach, release } -} - -const ring = (journal: AgentSessionJournal) => - selectStructuredAgentContextUsage(journal.snapshot().items) - -describe('context usage across a restart', () => { - it('resets the ring at a /compact that is the first thing after a restart, then reads the fresh report', async () => { - const journal = await openJournal() - const before = acquire(journal) - before.translator.handle(initFrame(900)) - before.translator.handle(userFrame('turn-a', 1_000)) - before.translator.handle(assistantFrame('reply-a', 2_000, 150_000)) - before.translator.handle(resultFrame(3_000)) - await before.settle() - expect(ring(journal)).toMatchObject({ usedTokens: 150_000, windowTokens: 1_000_000 }) - before.release() - - const after = acquire(journal) - after.translator.handle(compactBoundary(10_000)) - await after.settle() - expect(ring(journal)).toBeNull() - - after.translator.handle(resultFrame(11_000)) - await after.settle() - expect(ring(journal)).toBeNull() - after.answers.at(-1)?.(postCompactionReport) - await after.settle() - expect(ring(journal)).toMatchObject({ - usedTokens: 40_000, - windowTokens: 1_000_000, - estimated: false, - categories: [{ name: 'Messages', tokens: 30_000 }] - }) - after.release() - }) - - it('never brings a settled turn back to running with a context write that ran late', async () => { - const journal = await openJournal() - const live = acquire(journal) - live.translator.handle(initFrame(900)) - live.translator.handle(userFrame('turn-a', 1_000)) - live.translator.handle(assistantFrame('reply-a', 2_000, 20_000)) - await live.settle() - live.detach() - live.translator.handle(assistantFrame('reply-a2', 3_000, 30_000)) - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'orca-session', - fence: 1, - acquisitionGeneration: 'next', - deathEvidence: null - }) - live.reattach() - await live.settle() - const turn = journal - .snapshot() - .items.map((item) => readAgentJournalTurn(item.body)) - .find(Boolean) - expect(turn).toMatchObject({ - state: 'unverifiable', - contextUsage: { used: { kind: 'estimate', usage: { inputTokens: 30_000 } } } - }) - live.release() - }) -}) diff --git a/src/main/claude/claude-context-usage-test-support.ts b/src/main/claude/claude-context-usage-test-support.ts deleted file mode 100644 index 684317e4a8e..00000000000 --- a/src/main/claude/claude-context-usage-test-support.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { vi } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' -import { createJournalReducerState } from '../native-chat/agent-session-journal/projection/journal-reducer' -import { personStopDecidesTurn } from '../native-chat/agent-session-journal/context-epochs/journal-stop-turn-end' -import type { ClaudeContextReportTarget } from './claude-context-facts' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { claudeTurnLifecycleIdentity } from './claude-turn-lifecycle-item' - -export function journal({ deferred = false } = {}) { - const queued: (() => void)[] = [] - const run = (write: () => void): void => { - if (deferred) { - queued.push(write) - } else { - write() - } - } - const flush = (): void => { - while (queued.length) { - queued.shift()!() - } - } - const clock = { now: 0 } - const appends: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] - const rows = new Map() - const appendItem: StructuredAgentSessionEventSink['appendItem'] = (identity, body, options) => { - appends.push({ identity, body }) - const itemId = agentJournalItemKey(identity) - const existing = rows.get(itemId) - rows.set(itemId, { - itemId, - revision: (existing?.revision ?? 0) + 1, - sequence: existing?.sequence ?? rows.size + 1, - observedAt: existing?.observedAt ?? options?.observedAt ?? clock.now, - ...options, - turnScope: existing?.turnScope ?? options.turnScope, - body - }) - } - const scans = { count: 0 } - const bound: StructuredAgentSessionRevisionJournal = { - item: (itemId) => rows.get(itemId) ?? null, - epoch: 'test', - visitItems: (visit) => { - scans.count += 1 - for (const row of rows.values()) { - visit(row.itemId, row.sequence, row.body) - } - }, - itemBody: (itemId) => rows.get(itemId)?.body ?? null - } - const revise: NonNullable = ( - _reservedBytes, - resolve, - options - ) => { - run(() => { - const resolved = resolve(bound) - if (resolved) { - appendItem(resolved.identity, resolved.body, options) - } - }) - return { accepted: true } - } - const stopState = createJournalReducerState('orca-session', 'test') - const queueStop = (turnId: string, at: number): void => - run(() => { - stopState.queuePauseMarks.latestStop = { - sequence: rows.size + 1, - event: { reason: 'user-stop', turnId, at } - } - }) - const sink: StructuredAgentSessionEventSink = { - journalStopDecidesTurn: (turnId, at) => personStopDecidesTurn(stopState, turnId, at), - appendItem: (...args) => run(() => appendItem(...args)), - tryReviseResolvedItem: revise, - tryReviseResolvedItemAndPublish: revise, - appendTombstone: () => {}, - publish: vi.fn() - } - const turnRow = (turnId: string) => - rows.get(agentJournalItemKey(claudeTurnLifecycleIdentity('claude-session', turnId))) - const items = () => [...rows.values()].sort((left, right) => left.sequence - right.sequence) - return { sink, clock, appends, rows, turnRow, items, scans, flush, queueStop } -} - -export function frame(message: Record, observedAt: number, startsTurn = false) { - return { - type: 'message' as const, - sessionId: 'orca-session', - observedAt, - ...(startsTurn ? { startsTurn: true as const } : {}), - message: { session_id: 'claude-session', parent_tool_use_id: null, ...message } - } -} - -export const userFrame = (uuid: string, at: number) => - frame( - { type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text: 'go' }] } }, - at, - true - ) - -export function assistantFrame( - uuid: string, - at: number, - input: number, - parentToolUseId?: string, - model = 'claude-fable-5-1', - content: unknown[] = [{ type: 'text', text: uuid }] -) { - return frame( - { - type: 'assistant', - uuid, - ...(parentToolUseId ? { parent_tool_use_id: parentToolUseId } : {}), - message: { - role: 'assistant', - model, - content, - usage: { - input_tokens: input, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0, - output_tokens: 4 - } - } - }, - at - ) -} - -export const resultFrame = (at: number, modelUsage: Record = {}) => - frame( - { - type: 'result', - subtype: 'success', - is_error: false, - result: 'done', - duration_ms: 10, - uuid: `result-${at}`, - modelUsage - }, - at - ) - -export const initFrame = (model: string, at: number) => - frame({ type: 'system', subtype: 'init', uuid: `init-${at}`, model }, at) - -export const compactBoundary = (at: number) => - frame( - { - type: 'system', - subtype: 'compact_boundary', - uuid: `compact-${at}`, - compact_metadata: { trigger: 'auto', pre_tokens: 150_000 } - }, - at - ) - -export const turnIdentity = (turnId: string) => - claudeTurnLifecycleIdentity('claude-session', turnId) - -export function setup({ - init = 'claude-fable-5-1[1m]', - deferred = false -}: { init?: string | null; deferred?: boolean } = {}) { - const state = journal({ deferred }) - const translator = createClaudeJournalTranslator({ sink: state.sink, coalesceMs: 0 }) - const requests: ClaudeContextReportTarget[] = [] - translator.subscribeContextUsageRequests((target) => requests.push(target)) - const handle = (event: Parameters[0]): void => { - state.clock.now = event.type === 'message' ? (event.observedAt ?? 0) : 0 - translator.handle(event) - } - if (init) { - handle(initFrame(init, 500)) - } - return { ...state, translator, requests, handle } -} diff --git a/src/main/claude/claude-context-usage-unloaded-turn.test.ts b/src/main/claude/claude-context-usage-unloaded-turn.test.ts deleted file mode 100644 index fcfcffed4aa..00000000000 --- a/src/main/claude/claude-context-usage-unloaded-turn.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { AgentSessionHistoryPage } from '../../shared/agent-session/agent-session-wire' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import { MAX_RETAINED_OWN_ITEMS } from '../../shared/agent-session/view/structured-agent-session-item-retention' -import { selectStructuredAgentContextUsage } from '../../shared/agent-session/structured-agent-session-context-usage' -import { - EMPTY_STRUCTURED_AGENT_SESSION, - reduceStructuredAgentSession, - type StructuredAgentSessionState -} from '../../shared/agent-session/structured-agent-session-reducer' -import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { readAgentSessionHistory } from '../native-chat/agent-session-wire/publication/history/agent-session-history-page' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { StructuredAgentSessionMutationContext } from '../native-chat/agent-session-wire/operations/structured-agent-session-mutation-context' -import { readStructuredAgentSessionOptions } from '../native-chat/agent-session-wire/options/structured-agent-session-options-read' -import { - assistantFrame, - initFrame, - resultFrame, - userFrame -} from './claude-context-usage-test-support' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { claudeAndCodexAgents } from '../native-chat/agent-session-wire/providers/testing/structured-agent-session-adapter-router-test-support' -import type { StructuredAgentRegistry } from '../native-chat/agent-session-wire/providers/structured-agent-registry' - -const SESSION = 'orca-session' -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-context-unloaded-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -async function openJournal(): Promise { - return journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('claude-session', null) - }, - now: () => 9_000, - stateDirectory: join(root, SESSION) - }) -} - -function translate(journal: AgentSessionJournal) { - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) - deferred.bind({ journal, fence: 1, publish: () => {} }) - const settle = async (): Promise => { - await expect(deferred.drained()).resolves.toEqual({ ok: true }) - } - return { translator, settle } -} - -function runTurn( - translator: ReturnType['translator'], - turnId: string, - at: number, - sizes: number[] -): void { - translator.handle(initFrame('claude-fable-5-1[1m]', at - 100)) - translator.handle(userFrame(turnId, at)) - sizes.forEach((size, index) => { - translator.handle(assistantFrame(`${turnId}-reply-${index}`, at + 100 * (index + 1), size)) - }) -} - -function readOptions(journal: AgentSessionJournal, agents: StructuredAgentRegistry) { - const running = { - journal, - child: { fence: 1, generation: 'generation-1' }, - params: { provider: 'claude' } - } - const record = { - ...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: SESSION, runtimeFence: 1 })), - options: { model: 'opus' } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the options read touches only these members. - const context = { - deps: { - adapter: { - readOptions: async () => ({ models: [], current: { model: 'opus' } }) - }, - agents, - store: { - requireWritableRecord: () => record, - getConversation: () => agentSessionConversationView(record) - } - }, - serialize: (_sessionId: string, task: () => Promise) => task(), - openConversation: async () => running, - conversation: async () => running, - sessions: new Map([[SESSION, running]]) - } as unknown as StructuredAgentSessionMutationContext - return readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true }) -} - -function attachTail(journal: AgentSessionJournal, limit: number): StructuredAgentSessionState { - const read = readAgentSessionHistory(journal, { sessionId: SESSION, direction: 'tail', limit }) - if (!read.ok) { - throw new Error('tail read failed') - } - return reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { - type: 'event', - event: { type: 'snapshot', sessionId: SESSION, fence: 1, page: read.page } - }) -} - -function applyLive( - journal: AgentSessionJournal, - state: StructuredAgentSessionState -): StructuredAgentSessionState { - const read = readAgentSessionHistory(journal, { - sessionId: SESSION, - direction: 'after', - cursor: state.cursor ?? undefined - }) - if (!read.ok) { - throw new Error('live read failed') - } - const page: AgentSessionHistoryPage = read.page - return reduceStructuredAgentSession(state, { - type: 'event', - event: { - type: 'batch', - sessionId: SESSION, - batch: { - cursor: page.window.nextCursor, - items: page.items, - removedItemIds: page.removedItemIds, - submissions: page.submissions - } - } - }) -} - -const hasTurnRow = (state: StructuredAgentSessionState): boolean => - state.items.some((item) => readAgentJournalTurn(item.body) !== null) - -function catchUp( - journal: AgentSessionJournal, - state: StructuredAgentSessionState -): StructuredAgentSessionState { - let next = applyLive(journal, state) - while (next.cursor?.sequence !== state.cursor?.sequence) { - state = next - next = applyLive(journal, state) - } - return next -} - -describe('context usage for a turn row outside the loaded page', () => { - it('marks a live context write on a turn row the window cannot take, and the host answer carries it', async () => { - const journal = await openJournal() - const { translator, settle } = translate(journal) - runTurn(translator, 'turn-a', 1_000, [120_000, 130_000, 140_000, 150_000]) - translator.handle(resultFrame(2_000, { 'claude-fable-5-1[1m]': { contextWindow: 1_000_000 } })) - runTurn(translator, 'turn-b', 3_000, [200_000, 210_000, 220_000, 230_000]) - await settle() - const attached = attachTail(journal, 3) - expect(hasTurnRow(attached)).toBe(false) - expect(attached.unloadedTurnRevisions).toBeUndefined() - - translator.handle(assistantFrame('turn-b-reply-late', 4_000, 250_000)) - await settle() - const live = applyLive(journal, attached) - - expect(hasTurnRow(live)).toBe(false) - expect(live.unloadedTurnRevisions).toBe(1) - const options = await readOptions(journal, claudeAndCodexAgents()) - expect( - selectStructuredAgentContextUsage(live.items, options.contextUsage?.current) - ).toMatchObject({ usedTokens: 250_000, windowTokens: 1_000_000 }) - }) - - it('keeps the ring on the newest facts while a live turn outgrows the retained window', async () => { - const journal = await openJournal() - const { translator, settle } = translate(journal) - runTurn(translator, 'turn-a', 1_000, [120_000]) - translator.handle(resultFrame(2_000, { 'claude-fable-5-1[1m]': { contextWindow: 1_000_000 } })) - runTurn(translator, 'turn-b', 3_000, []) - await settle() - const hostAnswer = async () => - (await readOptions(journal, claudeAndCodexAgents())).contextUsage?.current - let state = attachTail(journal, 200) - let host = await hostAnswer() - const respond = (index: number): void => { - translator.handle(assistantFrame(`turn-b-reply-${index}`, 4_000 + index, 200_000 + index)) - } - let index = 0 - for (; index < MAX_RETAINED_OWN_ITEMS - 20; index += 1) { - respond(index) - if (index % 100 === 99) { - await settle() - } - } - await settle() - state = catchUp(journal, state) - expect(hasTurnRow(state)).toBe(true) - - let stepsAfterTrim = 0 - while (stepsAfterTrim < 5 && index < 3_000) { - respond(index++) - await settle() - const seen = state.unloadedTurnRevisions - state = catchUp(journal, state) - if (state.unloadedTurnRevisions !== seen) { - host = await hostAnswer() - } - expect(selectStructuredAgentContextUsage(state.items, host)).toEqual( - selectStructuredAgentContextUsage(journal.snapshot().items) - ) - stepsAfterTrim += hasTurnRow(state) ? 0 : 1 - } - expect(hasTurnRow(state)).toBe(false) - }) -}) diff --git a/src/main/claude/claude-descendant-escalation-boundary.test.ts b/src/main/claude/claude-descendant-escalation-boundary.test.ts deleted file mode 100644 index 590a3fd45cf..00000000000 --- a/src/main/claude/claude-descendant-escalation-boundary.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { terminateDescendantSnapshotWithVerdict } from '../pty/process-retirement/pty-descendant-exit-verification' -import { - collectDescendantRows, - type DescendantSnapshot -} from '../pty/process-retirement/pty-descendant-termination' -import type { ProcessTableRow } from '../pty/process-retirement/pty-process-table-parser' -import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof' - -const ROOT_PID = 500 -const ORCA_PGID = 400 -const ROOT_STARTED_AT = 'Thu Sep 3 18:04:50 2026' -const WALK_SECOND = 'Thu Sep 3 18:05:04 2026' -const WALK_MS = Date.parse(WALK_SECOND) -const EARLIER_SECOND = 'Thu Sep 3 18:05:03 2026' - -/** The measured split: `s20` at :03.946 died, `s21` at :04.042 leaked. */ -const EARLIER_BORN = [700, 701, 702] -const WALK_SECOND_BORN = [721, 722, 723, 724] - -type Cohort = { pids: number[]; startedAt: string } - -const LIVE_TREE: Cohort[] = [ - { pids: EARLIER_BORN, startedAt: EARLIER_SECOND }, - { pids: WALK_SECOND_BORN, startedAt: WALK_SECOND } -] - -function rowsFor(cohorts: Cohort[]): ProcessTableRow[] { - return [ - { pid: ROOT_PID, ppid: 1, pgid: ORCA_PGID, startedAt: ROOT_STARTED_AT }, - ...cohorts.flatMap((cohort) => - cohort.pids.map((pid) => ({ - pid, - ppid: ROOT_PID, - pgid: ORCA_PGID, - startedAt: cohort.startedAt - })) - ) - ] -} - -function walk(capturedAtMs: number, cohorts: Cohort[] = LIVE_TREE): DescendantSnapshot { - return collectDescendantRows(ROOT_PID, rowsFor(cohorts), capturedAtMs) -} - -function killedPids(calls: [number, NodeJS.Signals][]): number[] { - return calls.flatMap(([pid, signal]) => (signal === 'SIGKILL' ? [pid] : [])).sort((a, b) => a - b) -} - -function signalledPids(calls: [number, NodeJS.Signals][]): number[] { - return calls.flatMap(([pid, signal]) => (signal === 'SIGTERM' ? [pid] : [])).sort((a, b) => a - b) -} - -/** Descendants survive SIGTERM in the mock table, forcing the real verifier to escalate. */ -async function sweep( - captures: DescendantSnapshot[], - liveTree: Cohort[] = LIVE_TREE -): Promise<[number, NodeJS.Signals][]> { - const calls: [number, NodeJS.Signals][] = [] - const captureDescendants = vi.fn() - for (const capture of captures) { - captureDescendants.mockResolvedValueOnce(capture) - } - const tree = createClaudeChildTreeReaper( - { pid: ROOT_PID, kill: vi.fn(() => true) }, - { - site: 'claude-structured-child-close', - platform: 'linux', - exited: () => false, - captureDescendants, - terminateDescendants: (snapshot) => - terminateDescendantSnapshotWithVerdict(snapshot, { - requireIdentityBeforeSignal: true, - graceMs: 0, - verifyMs: 120, - sendSignal: (pid, signal) => calls.push([pid, signal]), - readTable: async () => ({ rows: rowsFor(liveTree), capturedAtMs: Date.now() }) - }) - } - ) - await tree.capture() - await tree.refresh?.() - await tree.reap() - return calls -} - -describe('Claude descendant forced-sweep fence', () => { - it('escalates a descendant forked in the same second as both close walks', async () => { - const calls = await sweep([walk(WALK_MS + 42), walk(WALK_MS + 140)]) - - expect(signalledPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN]) - expect(killedPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN]) - }) - - it('withholds the sweep from a row no walk re-derived, on its start second alone', async () => { - const retained = { pids: [900], startedAt: WALK_SECOND } - const firstWalk = walk(WALK_MS + 42, [...LIVE_TREE, retained]) - const refresh = walk(WALK_MS + 140) - - const calls = await sweep([firstWalk, refresh], [...LIVE_TREE, retained]) - - expect(signalledPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN, 900]) - expect(killedPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN]) - }) -}) diff --git a/src/main/claude/claude-fold-steer-frame-builders.test-fixture.ts b/src/main/claude/claude-fold-steer-frame-builders.test-fixture.ts deleted file mode 100644 index 39e966eed21..00000000000 --- a/src/main/claude/claude-fold-steer-frame-builders.test-fixture.ts +++ /dev/null @@ -1,177 +0,0 @@ -// Rebuild fold-steer captures with only dispatch and turn fields. - -export type CapturedFoldFrame = { at: number; frame: Record } - -export type FoldCaptureIds = { - sessionId: string - /** Turn-opening client UUID adopted by the replay. */ - first: string - steer: string - /** Present only for two-steer captures. */ - secondSteer?: string -} - -export function userReplay( - at: number, - sessionId: string, - uuid: string, - text: string -): CapturedFoldFrame { - return { - at, - frame: { - type: 'user', - session_id: sessionId, - parent_tool_use_id: null, - uuid, - isReplay: true, - message: { role: 'user', content: [{ type: 'text', text }] } - } - } -} - -export function assistant( - at: number, - sessionId: string, - uuid: string, - content: unknown[], - userMessageUuids?: string[] -): CapturedFoldFrame { - return { - at, - frame: { - type: 'assistant', - session_id: sessionId, - parent_tool_use_id: null, - uuid, - message: { id: `msg-${uuid}`, role: 'assistant', content }, - ...(userMessageUuids && userMessageUuids.length > 0 - ? { user_message_uuid: userMessageUuids[0], user_message_uuids: userMessageUuids } - : {}) - } - } -} - -export function assistantToolUse( - at: number, - sessionId: string, - uuid: string, - toolUseId: string, - userMessageUuids?: string[] -): CapturedFoldFrame { - return assistant( - at, - sessionId, - uuid, - [{ type: 'tool_use', id: toolUseId, name: 'Bash', input: { command: 'sleep 5' } }], - userMessageUuids - ) -} - -export function assistantText( - at: number, - sessionId: string, - uuid: string, - text: string, - userMessageUuids?: string[] -): CapturedFoldFrame { - return assistant(at, sessionId, uuid, [{ type: 'text', text }], userMessageUuids) -} - -export function toolResult( - at: number, - sessionId: string, - uuid: string, - toolUseId: string, - content = '(Bash completed with no output)', - isError = false -): CapturedFoldFrame { - return { - at, - frame: { - type: 'user', - session_id: sessionId, - parent_tool_use_id: null, - uuid, - message: { - role: 'user', - content: [{ type: 'tool_result', tool_use_id: toolUseId, content, is_error: isError }] - } - } - } -} - -export function resultFrame( - at: number, - sessionId: string, - uuid: string, - fields: { - userMessageUuids: string[] - durationMs: number - numTurns: number - subtype?: string - isError?: boolean - terminalReason?: string - } -): CapturedFoldFrame { - return { - at, - frame: { - type: 'result', - subtype: fields.subtype ?? 'success', - session_id: sessionId, - uuid, - is_error: fields.isError ?? false, - terminal_reason: fields.terminalReason ?? 'completed', - duration_ms: fields.durationMs, - num_turns: fields.numTurns, - result: 'FIRST DONE', - ...(fields.userMessageUuids.length > 0 - ? { - user_message_uuid: fields.userMessageUuids[0], - user_message_uuids: fields.userMessageUuids - } - : {}) - } - } -} - -export function sessionIdle(at: number, sessionId: string): CapturedFoldFrame { - return { - at, - frame: { - type: 'system', - subtype: 'session_state_changed', - state: 'idle', - session_id: sessionId, - uuid: `ssc-idle-${at}` - } - } -} - -/** Root init marks each request cycle, including background wakes and manual compaction (p3 captures). */ -export function initFrame(at: number, sessionId: string): CapturedFoldFrame { - return { - at, - frame: { - type: 'system', - subtype: 'init', - session_id: sessionId, - uuid: `init-${at}`, - model: 'claude-sonnet-5', - apiKeySource: 'none' - } - } -} - -export function taskFrame( - at: number, - sessionId: string, - subtype: string, - fields: Record -): CapturedFoldFrame { - return { - at, - frame: { type: 'system', subtype, session_id: sessionId, uuid: `${subtype}-${at}`, ...fields } - } -} diff --git a/src/main/claude/claude-fold-steer-receipt.test.ts b/src/main/claude/claude-fold-steer-receipt.test.ts deleted file mode 100644 index 334c307736d..00000000000 --- a/src/main/claude/claude-fold-steer-receipt.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -// Replay orders captured from Claude CLI 2.1.280; synthetic boundary cases are labeled separately. - -import { describe, expect, it, vi, type Mock } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalMessageItem -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter' -import type { - ClaudeStructuredSessionAdapterDeps, - ClaudeStructuredSessionEvent -} from './structured/claude-structured-session-state' -import type { ClaudeStructuredLaunch } from './structured/launch/claude-structured-launch-resolution' -import { - fakeClaude, - identityFor, - PROVIDER_SESSION_ID -} from './structured/claude-structured-session-test-support' -import { claudeStartupSettled } from './structured/claude-structured-startup-settled-test-support' -import { - assistantText, - initFrame, - resultFrame, - userReplay, - type CapturedFoldFrame -} from './claude-fold-steer-frame-builders.test-fixture' -import { - FIRST_PROMPT, - SECOND_STEER_PROMPT, - STEER_PROMPT, - twoSteersCapture, - TWO_STEERS_SEND_AT -} from './claude-captured-fold-steer-frames.test-fixture' - -const T0 = 1_700_000_100_000 - -type Rig = { - adapter: ClaudeStructuredSessionAdapter - claude: ReturnType - events: ClaudeStructuredSessionEvent[] - settled: Mock - turns: () => NonNullable>[] - deliver: (captured: CapturedFoldFrame) => void - /** Dispatch at the capture offset and return the client UUID adopted by the CLI. */ - dispatchAt: (at: number, clientMessageId: string, text: string) => Promise -} - -async function riggedAdapter( - launch: Partial = {}, - claudeOptions: Parameters[0] = {} -): Promise { - let nowMs = T0 - const appended: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity, body) => appended.push({ identity, body }), - appendTombstone: () => {}, - publish: () => {} - } - const events: ClaudeStructuredSessionEvent[] = [] - const settled = vi.fn() - const claude = fakeClaude({ replayUuid: null, ...claudeOptions }) - const deps: ClaudeStructuredSessionAdapterDeps = { - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false, - ...launch - }), - onEvent: (event) => events.push(event), - openConnection: claude.openConnection, - readProcessStartTime: async () => T0 - 1_000, - now: () => nowMs, - persistHandle: async () => {}, - onDispatchSettledLate: settled - } - const adapter = new ClaudeStructuredSessionAdapter(deps) - await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9', events: sink }) - await claudeStartupSettled(adapter, 'session-1') - return { - adapter, - claude, - events, - settled, - turns: () => - appended.flatMap((item) => { - const turn = readAgentJournalTurn(item.body) - return turn ? [turn] : [] - }), - deliver: (captured) => { - nowMs = T0 + captured.at - claude.connections[0]!.handlers.onMessage?.(captured.frame) - }, - dispatchAt: async (at, clientMessageId, text) => { - nowMs = T0 + at - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text }] - } - const outcome = await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body, - requestedAt: nowMs, - fence: 7 - }) - expect(outcome).toMatchObject({ state: 'admitted' }) - const sentUuid = claude.connections[0]!.sent.at(-1)?.uuid - if (typeof sentUuid !== 'string') { - throw new Error('the fake connection recorded no sent uuid') - } - return sentUuid - } - } -} - -function replayEventFor(events: ClaudeStructuredSessionEvent[], uuid: string) { - return events.find( - (event) => - event.type === 'message' && event.message.type === 'user' && event.message.uuid === uuid - ) -} - -describe('Claude fold receipt for a mid-turn send (captured orders)', () => { - it('two-steers: both folded sends settle individually inside the one turn', async () => { - const rig = await riggedAdapter() - const first = await rig.dispatchAt(TWO_STEERS_SEND_AT.first, 'client-first', FIRST_PROMPT) - const framesFor = (steerUuid: string, secondSteerUuid: string) => - twoSteersCapture({ - sessionId: PROVIDER_SESSION_ID, - first, - steer: steerUuid, - secondSteer: secondSteerUuid - }) - for (const captured of framesFor('pending', 'pending-2')) { - if (captured.at < TWO_STEERS_SEND_AT.steer) { - rig.deliver(captured) - } - } - const steer = await rig.dispatchAt(TWO_STEERS_SEND_AT.steer, 'client-steer', STEER_PROMPT) - const secondSteer = await rig.dispatchAt( - TWO_STEERS_SEND_AT.secondSteer, - 'client-steer-2', - SECOND_STEER_PROMPT - ) - for (const captured of framesFor(steer, secondSteer)) { - if (captured.at > TWO_STEERS_SEND_AT.secondSteer) { - rig.deliver(captured) - } - } - - expect([...new Set(rig.turns().map((turn) => turn.turnId))]).toEqual([first]) - expect(rig.turns().every((turn) => turn.state !== 'interrupted')).toBe(true) - expect(rig.settled).toHaveBeenCalledWith({ - sessionId: 'session-1', - clientMessageId: 'client-steer', - providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: steer } - }) - expect(rig.settled).toHaveBeenCalledWith({ - sessionId: 'session-1', - clientMessageId: 'client-steer-2', - providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: secondSteer } - }) - }) - - it('mid-turn auto-compaction emits no root init, so a steer after the boundary still folds', async () => { - // Captured with forced auto-compaction (p4): compacting, boundary, and synthetic continuation have no root init. - const rig = await riggedAdapter() - const first = await rig.dispatchAt(14, 'client-first', FIRST_PROMPT) - rig.deliver(initFrame(234, PROVIDER_SESSION_ID)) - rig.deliver(userReplay(2_437, PROVIDER_SESSION_ID, first, FIRST_PROMPT)) - rig.deliver(assistantText(2_864, PROVIDER_SESSION_ID, 'reply-1', 'reading files')) - rig.deliver({ - at: 11_518, - frame: { - type: 'system', - subtype: 'status', - status: 'compacting', - session_id: PROVIDER_SESSION_ID, - uuid: 'status-compacting-1' - } - }) - rig.deliver({ - at: 26_584, - frame: { - type: 'system', - subtype: 'compact_boundary', - session_id: PROVIDER_SESSION_ID, - uuid: 'compact-boundary-1', - compact_metadata: { trigger: 'auto', pre_tokens: 69_960, post_tokens: 9_311 } - } - }) - rig.deliver({ - at: 26_585, - frame: { - type: 'user', - session_id: PROVIDER_SESSION_ID, - parent_tool_use_id: null, - uuid: 'continuation-1', - isSynthetic: true, - message: { - role: 'user', - content: [{ type: 'text', text: 'This session is being continued.' }] - } - } - }) - const steer = await rig.dispatchAt(26_987, 'client-steer', STEER_PROMPT) - rig.deliver(userReplay(34_601, PROVIDER_SESSION_ID, steer, STEER_PROMPT)) - rig.deliver(assistantText(37_824, PROVIDER_SESSION_ID, 'reply-2', 'FIRST DONE banana')) - rig.deliver( - resultFrame(37_828, PROVIDER_SESSION_ID, 'result-1', { - userMessageUuids: [first, steer], - durationMs: 37_616, - numTurns: 6 - }) - ) - - expect([...new Set(rig.turns().map((turn) => turn.turnId))]).toEqual([first]) - expect(rig.turns().every((turn) => turn.state !== 'interrupted')).toBe(true) - expect(replayEventFor(rig.events, steer)).not.toHaveProperty('startsTurn') - expect(rig.settled).toHaveBeenCalledWith({ - sessionId: 'session-1', - clientMessageId: 'client-steer', - providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: steer } - }) - }) -}) - -describe('Claude fold receipt boundaries (synthetic orders)', () => { - it('a fresh replay uuid with user_message_uuid correlation keeps the opener path, not a fold receipt', async () => { - const rig = await riggedAdapter() - const uuidA = await rig.dispatchAt(10, 'client-a', 'first prompt') - rig.deliver(userReplay(1_000, PROVIDER_SESSION_ID, uuidA, 'first prompt')) - const uuidB = await rig.dispatchAt(1_500, 'client-b', STEER_PROMPT) - const fresh = userReplay(2_000, PROVIDER_SESSION_ID, 'fresh-turn-2', STEER_PROMPT) - rig.deliver({ ...fresh, frame: { ...fresh.frame, user_message_uuid: uuidB } }) - - expect([...new Set(rig.turns().map((turn) => turn.turnId))]).toEqual([uuidA, 'fresh-turn-2']) - expect(replayEventFor(rig.events, 'fresh-turn-2')).toMatchObject({ startsTurn: true }) - expect(rig.settled).toHaveBeenCalledWith({ - sessionId: 'session-1', - clientMessageId: 'client-b', - providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: 'fresh-turn-2' } - }) - }) - - it('plural result uuids: a result naming only settled sends does not claim an unnamed live waiter by queue order', async () => { - const rig = await riggedAdapter() - const uuidA = await rig.dispatchAt(10, 'client-a', 'first prompt') - rig.deliver(userReplay(1_000, PROVIDER_SESSION_ID, uuidA, 'first prompt')) - await rig.dispatchAt(1_500, 'client-b', STEER_PROMPT) - rig.deliver( - resultFrame(5_000, PROVIDER_SESSION_ID, 'result-1', { - userMessageUuids: [uuidA], - durationMs: 4_990, - numTurns: 1 - }) - ) - expect(rig.settled).not.toHaveBeenCalledWith( - expect.objectContaining({ clientMessageId: 'client-b' }) - ) - }) -}) diff --git a/src/main/claude/claude-folder-trust-file.test.ts b/src/main/claude/claude-folder-trust-file.test.ts deleted file mode 100644 index b72e2de9d32..00000000000 --- a/src/main/claude/claude-folder-trust-file.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { - chmodSync, - existsSync, - lstatSync, - mkdirSync, - mkdtempSync, - readdirSync, - readFileSync, - realpathSync, - rmSync, - statSync, - symlinkSync, - utimesSync, - writeFileSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { grantClaudeFolderTrust, grantClaudeWorkspaceTrust } from './claude-folder-trust-file' - -let root: string - -beforeEach(() => { - root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-claude-trust-'))) -}) - -afterEach(() => { - rmSync(root, { recursive: true, force: true }) -}) - -function writeConfig(file: string, value: unknown, mode = 0o600): void { - writeFileSync(file, JSON.stringify(value), { mode }) - chmodSync(file, mode) -} - -function readConfig(file: string): Record { - return JSON.parse(readFileSync(file, 'utf-8')) -} - -describe('grantClaudeFolderTrust', () => { - it('merges the key and keeps every other field', async () => { - const file = join(root, '.claude.json') - writeConfig(file, { - oauthAccount: { emailAddress: 'x' }, - mcpServers: { a: {} }, - projects: { '/elsewhere': { hasTrustDialogAccepted: true, allowedTools: [] } } - }) - await expect(grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] })).resolves.toBe( - 'granted' - ) - expect(readConfig(file)).toEqual({ - oauthAccount: { emailAddress: 'x' }, - mcpServers: { a: {} }, - projects: { - '/elsewhere': { hasTrustDialogAccepted: true, allowedTools: [] }, - '/wt': { hasTrustDialogAccepted: true } - } - }) - }) - - it('keeps an owner-only mode through the rewrite', async () => { - const file = join(root, '.claude.json') - writeConfig(file, {}, 0o600) - await grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] }) - expect(statSync(file).mode & 0o777).toBe(0o600) - }) - - it('leaves a corrupt file byte-for-byte untouched', async () => { - const file = join(root, '.claude.json') - writeFileSync(file, '{"oauthAccount": ', { mode: 0o600 }) - await expect(grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] })).resolves.toBe( - 'unreadable' - ) - expect(readFileSync(file, 'utf-8')).toBe('{"oauthAccount": ') - }) - - it('does nothing while Claude holds its lock, and leaves the lock in place', async () => { - const file = join(root, '.claude.json') - writeConfig(file, {}) - const lockDir = `${file}.lock` - mkdirSync(lockDir) - const oldTime = new Date(Date.now() - 60_000) - // Exceed Claude's 10-second stale window to verify Orca leaves its lock intact. - utimesSync(lockDir, oldTime, oldTime) - await expect(grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] })).resolves.toBe( - 'locked' - ) - expect(readConfig(file)).toEqual({}) - expect(existsSync(lockDir)).toBe(true) - expect(readdirSync(root).sort()).toEqual(['.claude.json', '.claude.json.lock']) - }) - - it('updates a symlinked config through its target and keeps the link', async () => { - const target = join(root, 'dotfiles-claude.json') - const link = join(root, '.claude.json') - writeConfig(target, { theme: 'dark' }) - symlinkSync(target, link) - await grantClaudeFolderTrust({ configFile: link, folderKeys: ['/wt'] }) - expect(lstatSync(link).isSymbolicLink()).toBe(true) - expect(readConfig(target)).toEqual({ - theme: 'dark', - projects: { '/wt': { hasTrustDialogAccepted: true } } - }) - }) - - it('grants every folder of a launch burst instead of losing some to its own lock', async () => { - const file = join(root, '.claude.json') - writeConfig(file, {}) - const keys = Array.from({ length: 12 }, (_, index) => `/wt-${index}`) - const outcomes = await Promise.all( - keys.map((key) => grantClaudeFolderTrust({ configFile: file, folderKeys: [key] })) - ) - expect(outcomes).toEqual(keys.map(() => 'granted')) - expect(readConfig(file).projects).toEqual( - Object.fromEntries(keys.map((key) => [key, { hasTrustDialogAccepted: true }])) - ) - }) -}) - -describe('grantClaudeWorkspaceTrust', () => { - it('writes the given folder and its realpath form, whatever kind of folder it is', async () => { - const real = join(root, 'real-folder') - mkdirSync(real) - const link = join(root, 'linked-folder') - symlinkSync(real, link) - const file = join(root, '.claude.json') - writeConfig(file, {}) - await expect( - grantClaudeWorkspaceTrust({ configFile: file, keyStyle: 'posix' }, link) - ).resolves.toBe('granted') - expect(readConfig(file)).toEqual({ - projects: { - [link]: { hasTrustDialogAccepted: true }, - [real]: { hasTrustDialogAccepted: true } - } - }) - }) -}) diff --git a/src/main/claude/claude-hook-event-versions.test.ts b/src/main/claude/claude-hook-event-versions.test.ts deleted file mode 100644 index 477c7b795bc..00000000000 --- a/src/main/claude/claude-hook-event-versions.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { runProcess } from '@orca/process-host' -import { readManagedHookDetectionResult } from '../agent-hooks/installation/managed-hook-detection-commands' -import { getClaudeManagedHookPlan } from './claude-managed-hook-events' - -vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() })) - -import { parseClaudeCliVersionOutput, probeClaudeCliVersion } from './claude-hook-event-versions' - -describe('identified Claude version output', () => { - // Recorded macOS 2.1.310 / Windows 2.1.221 probes; historical releases' CLI source - // registers the same suffix (1.0.23, 1.0.64, 2.0.0 and 2.1.100). - it.each([ - ['2.1.310 (Claude Code)\n', '', '2.1.310', 16, 0], - ['2.1.221 (Claude Code)\n', '', '2.1.221', 15, 1], - ['1.0.23 (Claude Code)', '', '1.0.23', 2, 14], - ['1.0.64 (Claude Code)', '', '1.0.64', 6, 10], - ['2.0.0 (Claude Code)', '', '2.0.0', 6, 10], - ['2.1.100 (Claude Code)', '', '2.1.100', 14, 2], - ['launcher 11.17.0\n1.0.64 (Claude Code)', '', '1.0.64', 6, 10], - ['launcher 0.1.0\n2.1.310 (Claude Code)', '', '2.1.310', 16, 0], - ['launcher 0.1.0', '2.1.310 (Claude Code)\n', '2.1.310', 16, 0], - ['', '2.1.310 (Claude Code)\n', '2.1.310', 16, 0], - ['2.1.94-rc.1+build.2 (Claude Code)', '', '2.1.94-rc.1+build.2', 14, 2], - ['11.17.0\n', '', null, 6, 0], - ['2.30.0', '', null, 6, 0], - ['2.1.310\nwrapper for (Claude Code)', '', null, 6, 0], - ['2.1.310\n(Claude Code)', '', null, 6, 0], - ['2.1 (Claude Code)', '', null, 6, 0] - ] as const)( - 'uses the identified version and hook plan for stdout=%s stderr=%s', - async (stdout, stderr, expected, installs, retirements) => { - vi.mocked(runProcess).mockResolvedValue({ - stdout, - stderr, - code: 0, - signal: null, - timedOut: false - }) - const local = await probeClaudeCliVersion('/bin/claude') - // Older guests send combined raw output, not canonical stored semver. - const remote = readManagedHookDetectionResult({ - agents: ['claude'], - versions: { claude: `${stdout}\n${stderr}` } - }) - expect(remote.agents).toEqual(['claude']) - expect(parseClaudeCliVersionOutput(`${stdout}\n${stderr}`)).toBe(expected) - for (const version of [local, remote.claudeVersion]) { - expect(version).toBe(expected) - const plan = getClaudeManagedHookPlan(version) - expect(plan.install).toHaveLength(installs) - expect(plan.retire).toHaveLength(retirements) - expect(plan.statusLine).toBe(expected === '1.0.23' ? 'retire' : 'install') - } - } - ) - - it('does not accept marked output from a failed probe', async () => { - vi.mocked(runProcess).mockResolvedValue({ - stdout: '2.1.310 (Claude Code)\n', - stderr: '', - code: 1, - signal: null, - timedOut: false - }) - expect(await probeClaudeCliVersion('/bin/claude')).toBeNull() - }) -}) diff --git a/src/main/claude/claude-journal-bound-delivery.test.ts b/src/main/claude/claude-journal-bound-delivery.test.ts deleted file mode 100644 index 6c14507c9cf..00000000000 --- a/src/main/claude/claude-journal-bound-delivery.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' -import { bindClaudeJournalReadingControl } from './structured/journal/claude-structured-session-journal-control' -import type { - StructuredAgentSessionEventSink, - StructuredAgentSessionReadingControl -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' - -function unboundSink() { - let notify: (() => void) | undefined - let control: StructuredAgentSessionReadingControl | undefined - let bound = false - const sink: StructuredAgentSessionEventSink = { - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {}, - onJournalBound: (listener) => { - notify = listener - return () => { - notify = undefined - } - }, - journalLinkage: () => - bound - ? { - epoch: 'test', - visitItemsWithLinkage: () => {}, - threadGoal: () => null, - threadGoalSource: () => ({ goal: null, row: null }) - } - : null, - bindReadingControl: (next) => { - control = next - return () => {} - } - } - return { - sink, - bind: () => { - bound = true - notify?.() - }, - pressure: (paused: boolean) => control?.[paused ? 'pauseReading' : 'resumeReading']() - } -} - -it('holds ordered interpretation until binding while preserving independent sink pressure', () => { - const state = unboundSink() - let published = false - const delivery = new ClaudeJournalBoundDelivery(state.sink, () => published) - const connection = { pauseReading: vi.fn(), resumeReading: vi.fn() } - bindClaudeJournalReadingControl(state.sink, connection, null, delivery) - const observed: string[] = [] - delivery.deliver(() => { - observed.push('start') - delivery.deliver(() => observed.push('later')) - }) - delivery.deliver(() => observed.push('terminal')) - published = true - delivery.flush() - state.pressure(true) - expect(observed).toEqual([]) - state.bind() - expect(observed).toEqual(['start', 'terminal', 'later']) - expect(connection.resumeReading).not.toHaveBeenCalled() - state.pressure(false) - expect(connection.resumeReading).toHaveBeenCalledOnce() -}) - -it('terminates the uncommitted prefix on disposal and ignores a late binding', () => { - const state = unboundSink() - const delivery = new ClaudeJournalBoundDelivery(state.sink) - const interpret = vi.fn() - delivery.deliver(interpret) - delivery.dispose() - state.bind() - delivery.deliver(interpret) - expect(interpret).not.toHaveBeenCalled() -}) - -it('fails a bounded unbound prefix instead of silently losing or replaying observations', () => { - const state = unboundSink() - const delivery = new ClaudeJournalBoundDelivery(state.sink) - const failure = vi.fn() - const interpret = vi.fn() - delivery.onFailure = failure - const payload = 'x'.repeat(1024 * 1024) - expect(() => { - for (let index = 0; index < 33; index++) { - delivery.deliver(interpret, payload) - } - }).toThrow('capacity exceeded') - state.bind() - expect(failure).toHaveBeenCalledOnce() - expect(interpret).not.toHaveBeenCalled() -}) - -it('reports binding interpretation failure through its owning failure path', () => { - const state = unboundSink() - const delivery = new ClaudeJournalBoundDelivery(state.sink) - const failure = vi.fn() - delivery.onFailure = failure - const error = new Error('invalid saved identity') - delivery.deliver(() => { - throw error - }) - const later = vi.fn() - delivery.deliver(later) - expect(() => state.bind()).not.toThrow() - expect(failure).toHaveBeenCalledWith(error) - expect(later).not.toHaveBeenCalled() -}) diff --git a/src/main/claude/claude-journal-translator-contract.ts b/src/main/claude/claude-journal-translator-contract.ts deleted file mode 100644 index 21f4057ca02..00000000000 --- a/src/main/claude/claude-journal-translator-contract.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { ClaudeTaskInvocations } from './claude-task-invocations' -import type { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' -import type { AgentSessionContextReport } from '../../shared/agent-session/agent-session-context-usage' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import type { - StructuredAgentSessionEventSink, - StructuredAgentSessionSinkAdmission -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudeChildToolQueries } from './claude-child-tool-queries' -import type { ClaudeContextReportPart, ClaudeContextReportTarget } from './claude-context-facts' -import type { ClaudeJournalPrompts } from './structured/journal/claude-structured-journal-prompts' -import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state' -import type { ClaudeCommandStart } from './claude-command-turn' - -import type { AgentSessionDeltaCoalescerDeps } from '../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' -import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker' -import type { AgentSessionAccountKind } from '../../shared/agent-session/agent-session-availability' - -export type ClaudeJournalTranslatorDeps = { - sink: StructuredAgentSessionEventSink - delivery?: ClaudeJournalBoundDelivery - bindPromptItemId?: (journalItemId: string, promptKey: string) => void - coalesceMs?: number - schedule?: AgentSessionDeltaCoalescerDeps['schedule'] - fallbackIdPrefix?: string - onBackgroundTaskJournalFailure?: (error: Error) => void - account?: () => AgentSessionAccountKind | undefined - model?: () => string | undefined - goalBackgroundWork?: () => ClaudeGoalBackgroundWork - /** True when this acquisition's pending startup took a turnless failure result and will fail with it. */ - acceptStartupFailure?: (message: Record) => boolean -} - -export type ClaudeJournalTranslator = { - readonly taskInvocations: ClaudeTaskInvocations - handle: (event: ClaudeStructuredSessionEvent) => void - journalPrompts: Pick< - ClaudeJournalPrompts, - 'resolve' | 'handOver' | 'cancel' | 'openCards' | 'whenWritten' - > - /** Canonical provider turn ID used by the journal row and client Stop requests. */ - readonly currentTurnId: string | null - readonly currentTurnScope: () => AgentJournalTurnScope - readonly commandTurnId: string | null - beginCommand: (start: ClaudeCommandStart) => void - forgetCommand: (turnId: string) => void - commandInterruptRequested: (turnId: string) => void - /** Root work since cycle init makes the open turn eligible for folded sends. */ - readonly openTurnInLiveProviderCycle: boolean - readonly openTurnHasInputWork: boolean - flush: () => void - childTaskParent?: (taskId: string, run?: string) => string | undefined - childToolOwner?: ClaudeChildToolQueries['childToolOwner'] - childActivity?: ClaudeChildToolQueries['childActivity'] - retryPendingTaskRows?: () => StructuredAgentSessionSinkAdmission - retryPendingCancellations?: () => StructuredAgentSessionSinkAdmission - /** Streamed blocks awaiting final frames; settlement clears them. */ - readonly pendingStreamedBlocks: number - /** Advances on conversation activity and accepted sends, invalidating older context requests. */ - readonly contextActivity: number - /** Every final snapshot and turn settlement this acquisition tried was admitted. */ - readonly finalOutputAdmitted: boolean - markContextActivity: () => void - subscribeContextUsageRequests: ( - listener: (target: ClaudeContextReportTarget) => void - ) => () => void - recordContextReport: ( - target: ClaudeContextReportTarget, - report: AgentSessionContextReport, - part: ClaudeContextReportPart - ) => void - /** Defer context estimates until a model change yields a new window. */ - modelMayHaveChanged: () => void - /** Size interim estimates with the applied model until its window is measured. */ - modelWritten: (model: string) => void - dispose: () => void -} diff --git a/src/main/claude/claude-launch-account.ts b/src/main/claude/claude-launch-account.ts deleted file mode 100644 index 02969a655d7..00000000000 --- a/src/main/claude/claude-launch-account.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { ClaudeAccountRecipe } from '../../shared/agent-session/lifecycle/agent-session-acquired-account' -import type { ClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-router' -import { applyClaudeEnvPatch } from '../claude-accounts/runtime-auth/environment' -import { resolveStructuredClaudeAccountHomePath } from '../runtime/agent-session/environment/structured-agent-account-home' - -/** The account a launch runs under is the current selection; the receipt records what it used. */ -export async function prepareClaudeLaunchAccount( - router: ClaudeProfileRouter | undefined, - env: Record, - recordHome: string -): Promise { - if (!router) { - return { route: 'system', home: recordHome, configDir: env.CLAUDE_CONFIG_DIR ?? null } - } - const preparation = await router.prepareLaunch() - const home = - preparation.provenance === 'system' - ? await resolveStructuredClaudeAccountHomePath({ - launchEnv: env, - wslDistro: null, - getClaudeConfigDirectory: () => router.systemDefaultHome() - }) - : preparation.configDir - applyClaudeEnvPatch(env, preparation.envPatch) - return preparation.provenance.startsWith('profile:') - ? { route: 'managed', accountId: preparation.provenance.slice('profile:'.length), home } - : { route: 'system', home, configDir: env.CLAUDE_CONFIG_DIR ?? null } -} diff --git a/src/main/claude/claude-model-catalog-probe.test.ts b/src/main/claude/claude-model-catalog-probe.test.ts deleted file mode 100644 index e807112bf26..00000000000 --- a/src/main/claude/claude-model-catalog-probe.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { PROVIDER_STDIN_END_GRACE_MS } from '../provider-process/provider-process-supervisor' -import { createClaudeModelCatalogProbe } from './claude-model-catalog-probe' -import { resolveStructuredAgentCommand } from '../native-chat/structured-agent-command-resolution' -import type { runAgentModelCatalogListing } from '../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' - -type ListingCall = Parameters - -const AUTH_POLICY = { account: 'system' } as const - -const HOME = (path: string): { variable: string; path: string } => ({ - variable: 'CLAUDE_CONFIG_DIR', - path -}) - -function probeDeps(command = `"${process.execPath}"`): { - resolveCommand: () => { command: string; prefixArgs: string[] } - resolveEnv: () => Record - resolveInheritedEnv: () => Promise> - resolveAuthPolicy: () => typeof AUTH_POLICY -} { - return { - resolveCommand: () => - resolveStructuredAgentCommand('claude', { - agentCmdOverrides: { claude: command } - }), - resolveEnv: () => ({ ANTHROPIC_MODEL_GATEWAY: 'https://gateway.example' }), - resolveInheritedEnv: async () => ({ PATH: '/resolved/bin', HOME: '/homes/user' }), - resolveAuthPolicy: () => AUTH_POLICY - } -} - -const LISTED = `${JSON.stringify({ - type: 'control_response', - response: { - subtype: 'success', - request_id: 'orca-model-discovery', - response: { - models: [ - { - value: 'sonnet', - displayName: 'Sonnet', - supportsEffort: true, - supportedEffortLevels: ['low'] - } - ] - } - } -})}\n` - -describe('claude model catalog probe', () => { - it.each([ - [[], [], ['/orca-probe', '/orca-probe'], 'user,project,local'], - [['node_modules/claude/cli.js'], [], ['/chat-a', '/chat-b'], 'user'], - [[], ['--settings', 'settings.json'], ['/chat-a', '/chat-b'], 'user'] - ])( - 'lists prefix %j with arguments %j from %j, reading %s settings', - async (prefixArgs, launchArgs, listedIn, sources) => { - // A user command line may name files in the chat's folder, so it runs there, but reads only - // user settings there so the project's own settings never narrow the account's list. - const calls: ListingCall[] = [] - const probe = createClaudeModelCatalogProbe({ - ...probeDeps(), - resolveCommand: () => ({ command: process.execPath, prefixArgs }), - resolveLaunchArgs: async () => launchArgs, - runListing: async (...call) => { - calls.push(call) - return LISTED - } - }) - const identities: unknown[] = [] - for (const folder of ['/chat-a', '/chat-b']) { - const resolved = await probe.resolve?.( - HOME('/homes/a'), - '/orca-probe', - 'snapshot', - undefined, - folder - ) - identities.push(resolved?.identity) - await resolved?.run() - } - expect(calls.map(([launch]) => launch.cwd)).toEqual(listedIn) - const args = calls[0]?.[0].args ?? [] - expect(args.slice(0, prefixArgs.length)).toEqual(prefixArgs) - expect(args.slice(args.length - launchArgs.length)).toEqual(launchArgs) - expect(args[args.indexOf('--setting-sources') + 1]).toBe(sources) - expect(JSON.stringify(identities[0]) === JSON.stringify(identities[1])).toBe( - listedIn[0] === listedIn[1] - ) - } - ) - - it.runIf(process.platform !== 'win32')( - 'lists through a supervised one-shot that answers after its input ends', - async () => { - const folder = mkdtempSync(join(tmpdir(), 'orca-claude-probe-')) - try { - const parentFile = join(folder, 'parent-pid') - const standIn = join(folder, 'claude') - // Delay beyond the stdin-end grace to verify supervised one-shot lifetime. - writeFileSync( - standIn, - `#!${process.execPath} -let input = '' -process.stdin.on('data', (chunk) => (input += chunk)) -process.stdin.on('end', () => setTimeout(() => { - require('node:fs').writeFileSync(${JSON.stringify(parentFile)}, String(process.ppid)) - const request = JSON.parse(input.trim().split('\\n').find(line => line.includes('list_models'))) - if (request.request.subtype !== 'list_models') process.exit(2) - console.log(JSON.stringify({ type: 'control_response', response: { subtype: 'success', - request_id: request.request_id, response: { models: [{ value: 'sonnet', displayName: 'Sonnet' }] } } })) -}, ${PROVIDER_STDIN_END_GRACE_MS * 1.5})) -` - ) - chmodSync(standIn, 0o755) - const probe = createClaudeModelCatalogProbe({ - ...probeDeps(), - resolveCommand: () => ({ command: standIn, prefixArgs: [] }), - resolveInheritedEnv: async () => ({ PATH: process.env.PATH ?? '', HOME: folder }) - }) - - await expect(probe(HOME(join(folder, 'account')))).resolves.toMatchObject({ - origin: 'probe', - models: [{ id: 'sonnet', label: 'Sonnet' }] - }) - expect(Number(readFileSync(parentFile, 'utf8'))).not.toBe(process.pid) - } finally { - rmSync(folder, { recursive: true, force: true }) - } - } - ) -}) - -describe('Claude catalog availability', () => { - it('says the CLI is missing when the resolved executable is not there', async () => { - const folder = mkdtempSync(join(tmpdir(), 'orca-claude-missing-')) - try { - const missing = join(folder, 'claude with spaces', 'claude') - const probe = createClaudeModelCatalogProbe({ - ...probeDeps(), - resolveCommand: () => ({ command: missing, prefixArgs: [] }) - }) - await expect(probe(HOME('/homes/a'))).rejects.toMatchObject({ - unavailable: { reason: 'cliMissing' } - }) - } finally { - rmSync(folder, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/claude/claude-naming-invocation.test.ts b/src/main/claude/claude-naming-invocation.test.ts deleted file mode 100644 index 3e5fd87360d..00000000000 --- a/src/main/claude/claude-naming-invocation.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, it, vi } from 'vitest' -import { ClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-router' -import * as installedRouter from '../claude-accounts/profiles/routing/claude-profile-installed-router' -import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' -import type { StructuredAgentLaunchSources } from '../runtime/agent-session/launch/structured-agent-launch-composition' -import { claudeNamingInvocation } from './claude-naming-invocation' - -it('captures configured command, overlay and pure selected-account policy before awaited input resolution', async ({ - onTestFinished -}) => { - const root = await mkdtemp(join(tmpdir(), 'orca-naming-inputs-')) - onTestFinished(async () => { - vi.restoreAllMocks() - await rm(root, { recursive: true, force: true }) - }) - const router = new ClaudeProfileRouter({ - getSettings: () => ({ - claudeManagedAccounts: [], - activeClaudeManagedAccountId: null, - agentStatusHooksEnabled: false, - disabledTuiAgents: [] - }), - dataRoot: root, - userHome: root, - env: {} - }) - const selected = join(root, 'selected-account') - const later = join(root, 'later-account') - const preparation = vi.spyOn(router, 'preparation').mockReturnValue({ - configDir: selected, - runtime: 'host', - wslDistro: null, - wslLinuxConfigDir: null, - envPatch: { CLAUDE_CONFIG_DIR: selected }, - provenance: 'profile:a' - }) - const prepareLaunch = vi.spyOn(router, 'prepareLaunch') - vi.spyOn(installedRouter, 'getClaudeProfileRouter').mockReturnValue(router) - const record = agentSessionRecordFixture({ - sessionId: 'chat', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'saved-account') } - }) - const inherited = Promise.withResolvers>() - const settings = { agentCmdOverrides: { claude: `"${process.execPath}"` } } - const overlay = { CLAUDE_CONFIG_DIR: join(root, 'overlay-account'), NAMING_INPUT: 'accepted' } - const sources: StructuredAgentLaunchSources = { - store: { - selectWritableRecord: () => ({ kind: 'writable', record }), - requireWritableRecord: () => record, - pinLaunchDirectory: async () => record - }, - resolveWorkspacePath: async () => root, - resolveBaseEnvironment: () => inherited.promise, - resolveAgentEnvironment: async () => overlay, - resolveAgentLaunchEnv: () => overlay, - resolveCommandSettings: () => settings - } - const snapshot = claudeNamingInvocation(sources, () => []) - const pending = snapshot(record) - settings.agentCmdOverrides.claude = 'does-not-exist-orca-naming' - overlay.NAMING_INPUT = 'changed' - preparation.mockReturnValue({ - configDir: later, - runtime: 'host', - wslDistro: null, - wslLinuxConfigDir: null, - envPatch: { CLAUDE_CONFIG_DIR: later }, - provenance: 'profile:b' - }) - inherited.resolve({ HOME: root, PATH: process.env.PATH ?? '' }) - expect(await pending).toMatchObject({ - command: process.execPath, - home: selected, - cwd: root, - env: { CLAUDE_CONFIG_DIR: selected, NAMING_INPUT: 'accepted' } - }) - expect(prepareLaunch).not.toHaveBeenCalled() - await expect(snapshot(record)).rejects.toThrow() - expect(prepareLaunch).not.toHaveBeenCalled() -}) diff --git a/src/main/claude/claude-naming-invocation.ts b/src/main/claude/claude-naming-invocation.ts deleted file mode 100644 index dc077bf6e34..00000000000 --- a/src/main/claude/claude-naming-invocation.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' -import { applyClaudeEnvPatch } from '../claude-accounts/runtime-auth/environment' -import { agentSessionPinnedLaunchDirectory } from '../runtime/agent-session/records/agent-session-record-launch-directory' -import type { StructuredAgentLaunchSources } from '../runtime/agent-session/launch/structured-agent-launch-composition' -import { resolveStructuredAgentCommand } from '../native-chat/structured-agent-command-resolution' -import { - claudeChildEnv, - resolveClaudeChildEnvSources, - type ClaudeEnvDeps -} from './structured/launch/claude-structured-child-env' -import { claudeStructuredLaunchArgs } from './structured/launch/claude-structured-launch-args' -import { claudeConfigDirEnvPatch, withoutInheritedClaudeConfigDir } from './claude-config-dir-pin' -import { buildClaudeChildProcessEnv } from './claude-child-process-environment' -import type { ClaudeStructuredLaunch } from './structured/launch/claude-structured-launch-resolution' -import { resolve } from 'node:path' - -export type ClaudeNamingInputs = { - command: string - cwd: string - home: string - env: Readonly> - extraArgs: Readonly> -} - -/** Capture the selected policy now; only its independent I/O remains on the naming task. */ -export function claudeNamingInvocation( - sources: StructuredAgentLaunchSources, - resolveArgs: () => Promise | string[], - resolveCommand?: ClaudeEnvDeps['resolveCommand'] -): (record: AgentSessionRecord) => Promise { - return (record) => { - const configured = sources.resolveCommandSettings?.() - const settings = configured ? structuredClone(configured) : undefined - const overlay = { ...sources.resolveAgentLaunchEnv?.('claude') } - const args = Promise.resolve(resolveArgs()).then((value) => claudeStructuredLaunchArgs(value)) - const inherited = sources.resolveBaseEnvironment().then((value) => ({ ...value })) - const pinned = agentSessionPinnedLaunchDirectory(record) - const directory = pinned - ? Promise.resolve(pinned) - : sources.resolveWorkspacePath(record.location.workspaceId) - const router = getClaudeProfileRouter() - const policy = router?.preparation() - const systemHome = router?.systemDefaultHome() - const savedHome = requireLegacyAgentSessionAccountHome(record.accountHome).path - return (async () => { - const [cwd, baseEnv, configuredArgs] = await Promise.all([directory, inherited, args]) - const resolved = await resolveClaudeChildEnvSources({ - resolveEnv: () => overlay, - resolveInheritedEnv: () => Promise.resolve(baseEnv), - resolveWorkingDirectory: () => cwd, - ...(settings - ? { - resolveCommand: (options) => - resolveStructuredAgentCommand('claude', settings, options) - } - : resolveCommand - ? { resolveCommand } - : {}) - }) - const env = claudeChildEnv(resolved, undefined, { runtimeOnPath: false }) - const home = policy - ? policy.provenance === 'system' - ? env.CLAUDE_CONFIG_DIR?.trim() || systemHome || policy.configDir - : policy.configDir - : savedHome - if (policy) { - applyClaudeEnvPatch(env, policy.envPatch) - } - Object.assign(env, claudeConfigDirEnvPatch(home, { env })) - return { - command: resolved.command, - cwd, - home: resolve(cwd, home), - env, - extraArgs: configuredArgs.extraArgs - } - })() - } -} - -/** Owned contexts always use their actual launch, including its account and configured args. */ -export function claudeNamingLaunchInputs(launch: ClaudeStructuredLaunch): ClaudeNamingInputs { - const env = buildClaudeChildProcessEnv( - { - ...launch.env, - ...claudeConfigDirEnvPatch(launch.claudeConfigDir, { env: launch.env }) - }, - { - inheritedEnv: withoutInheritedClaudeConfigDir(process.env) - } - ) - for (const key of launch.envToDelete ?? []) { - delete env[key] - } - return { - command: launch.pathToClaudeCodeExecutable, - cwd: launch.cwd, - home: resolve(launch.cwd, launch.claudeConfigDir), - env, - extraArgs: { ...launch.options.extraArgs } - } -} diff --git a/src/main/claude/claude-parent-task-frames.test-fixture.ts b/src/main/claude/claude-parent-task-frames.test-fixture.ts deleted file mode 100644 index a90897291da..00000000000 --- a/src/main/claude/claude-parent-task-frames.test-fixture.ts +++ /dev/null @@ -1,11 +0,0 @@ -// CLI 2.1.319, isolated real run: parent Stop, live child roster, then separate child Stop; IDs/paths sanitized. -import { readFileSync } from 'node:fs' -import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' - -export const PARENT_TASK_STOP: CapturedFrame[] = readFileSync( - new URL('./__fixtures__/claude-parent-task-stop-2.1.319.jsonl', import.meta.url), - 'utf8' -) - .trim() - .split('\n') - .map((line) => JSON.parse(line)) diff --git a/src/main/claude/claude-plan-approval-mode.test.ts b/src/main/claude/claude-plan-approval-mode.test.ts deleted file mode 100644 index 09992646b69..00000000000 --- a/src/main/claude/claude-plan-approval-mode.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { invokeCanUseTool } from './claude-can-use-tool-test-support' -import { - PROVIDER_SESSION_ID, - USER_MESSAGE, - acquired, - claudeFrame, - fakeClaude, - tick, - type FakeConnection -} from './structured/claude-structured-session-test-support' -import { claudeStructuredPermissionOptions } from './structured/launch/claude-structured-launch-resolution' - -async function pendingPlanApproval( - input: Record, - initPermissionMode?: string, - requested?: 'full-access' -) { - const claude = fakeClaude({ replayUuid: 'turn-1', initPermissionMode }) - const adapter = await acquired( - claude, - requested ? { options: claudeStructuredPermissionOptions(requested) } : {} - ) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-turn-1', - body: USER_MESSAGE, - fence: 7 - }) - const connection = claude.connections[0] - if (!connection) { - throw new Error('expected Claude connection') - } - claudeFrame(connection, { type: 'system', subtype: 'status', permissionMode: 'plan' }) - if (requested) { - for (const frame of [ - { - type: 'system', - subtype: 'status', - status: null, - permissionMode: 'plan', - session_id: PROVIDER_SESSION_ID - }, - { - type: 'control_request', - request_id: 'permission-plan', - request: { - subtype: 'can_use_tool', - tool_name: 'ExitPlanMode', - input, - tool_use_id: 'tool-plan' - } - } - ]) { - connection.handlers.onStdout?.(`${JSON.stringify(frame)}\n`) - } - } - const request = new AbortController() - const answered = invokeCanUseTool(connection, 'ExitPlanMode', 'permission-plan', 'tool-plan', { - input, - signal: request.signal - }) - adapter.bindPromptItemId('session-1', 'journal-plan', 'permission-plan') - return { adapter, connection, answered, request } -} - -describe('leaving Claude plan mode on an approved plan', () => { - it.each(['failed commit', 'lost ownership'])( - 'does not change mode when approval has %s', - async (failure) => { - const { adapter, connection, answered, request } = await pendingPlanApproval({}) - const setMode = vi.spyOn(connection, 'setPermissionMode') - await expect( - adapter.answerPrompt({ - sessionId: 'session-1', - itemId: 'journal-plan', - kind: 'approval', - response: { kind: 'option', optionId: 'allow' }, - fence: 7, - commit: async () => { - expect(setMode).not.toHaveBeenCalled() - expect(answered.settled()).toBe(false) - if (failure === 'failed commit') { - throw new Error('journal write failed') - } - request.abort() - } - }) - ).rejects.toThrow() - expect(setMode).not.toHaveBeenCalled() - if (failure === 'lost ownership') { - await expect(answered.promise).resolves.toBeNull() - } else { - expect(answered.settled()).toBe(false) - // The failed write released its claim, so a later approval still works. - await adapter.answerPrompt({ - sessionId: 'session-1', - itemId: 'journal-plan', - kind: 'approval', - response: { kind: 'option', optionId: 'allow' }, - fence: 7, - commit: async () => {} - }) - await expect(answered.promise).resolves.toMatchObject({ behavior: 'allow' }) - expect(setMode).toHaveBeenCalledOnce() - } - setMode.mockRestore() - } - ) - - it('restores Full access from the plan Claude reported on the wire, before presentation reads it', async () => { - // Init reported bypassPermissions through presentation; the later plan status is still unread there. - const claude = fakeClaude({ replayUuid: 'turn-1', initPermissionMode: 'bypassPermissions' }) - const adapter = await acquired(claude, { - options: claudeStructuredPermissionOptions('full-access') - }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-turn-1', - body: USER_MESSAGE, - fence: 7 - }) - const connection = claude.connections[0]! - const raw = (target: FakeConnection, frame: Record): void => - target.handlers.onStdout?.(`${JSON.stringify(frame)}\n`) - const request = (id: string, toolName: string, input: Record) => { - raw(connection, { - type: 'control_request', - request_id: id, - request: { subtype: 'can_use_tool', tool_name: toolName, input, tool_use_id: `tool-${id}` } - }) - return invokeCanUseTool(connection, toolName, id, `tool-${id}`, { input }) - } - const status = (permissionMode: string) => ({ - type: 'system', - subtype: 'status', - status: null, - permissionMode, - session_id: PROVIDER_SESSION_ID - }) - raw(connection, status('plan')) - const plan = request('permission-plan', 'ExitPlanMode', { plan: '# Plan' }) - adapter.bindPromptItemId('session-1', 'journal-plan', 'permission-plan') - const order: string[] = [] - const setMode = vi.spyOn(connection, 'setPermissionMode').mockImplementation((mode) => { - order.push(`set_permission_mode:${mode}`) - // Never resolves: the approval must not wait for Claude to confirm the mode. - return new Promise(() => {}) - }) - const answered = plan.promise.then((result) => { - order.push('control_response') - return result - }) - - await adapter.answerPrompt({ - sessionId: 'session-1', - itemId: 'journal-plan', - kind: 'approval', - response: { kind: 'option', optionId: 'allow' }, - fence: 7, - commit: async () => {} - }) - await expect(answered).resolves.toMatchObject({ - behavior: 'allow', - toolUseID: 'tool-permission-plan' - }) - expect(order).toEqual(['set_permission_mode:bypassPermissions', 'control_response']) - expect(setMode).toHaveBeenCalledOnce() - - // Sending the restore grants nothing; Claude's own bypass report does. - const beforeReport = request('before-report', 'Bash', { command: 'ls' }) - await tick() - expect(beforeReport.settled()).toBe(false) - raw(connection, status('bypassPermissions')) - const afterReport = request('after-report', 'Bash', { command: 'ls' }) - await expect(afterReport.promise).resolves.toEqual({ - behavior: 'allow', - updatedInput: { command: 'ls' }, - toolUseID: 'tool-after-report' - }) - setMode.mockRestore() - }) -}) - -it.each([true, false])( - 'uses the approved Build policy only after successful native restoration: %s', - async (restored) => { - const { adapter, connection, answered } = await pendingPlanApproval( - {}, - 'default', - 'full-access' - ) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const setMode = vi.spyOn(connection, 'setPermissionMode').mockImplementationOnce(async () => { - if (!restored) { - throw new Error('native restoration failed') - } - }) - try { - await adapter.answerPrompt({ - sessionId: 'session-1', - itemId: 'journal-plan', - kind: 'approval', - response: { kind: 'option', optionId: 'allow' }, - fence: 7, - commit: async () => {} - }) - await expect(answered.promise).resolves.toMatchObject({ behavior: 'allow' }) - await tick() - expect(setMode).toHaveBeenCalledWith('bypassPermissions') - for (const clientMessageId of ['build-first', 'build-second']) { - claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) - await adapter.readOptions({ sessionId: 'session-1', fence: 7 }) - expect( - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body: USER_MESSAGE, - fence: 7, - executionOptions: { interactionMode: 'default' } - }) - ).toMatchObject({ state: 'admitted' }) - expect(setMode).toHaveBeenLastCalledWith(restored ? 'bypassPermissions' : 'default', { - timeoutMs: undefined - }) - } - } finally { - warn.mockRestore() - await adapter.closeAll() - } - } -) diff --git a/src/main/claude/claude-plugin-input-failure-journal.ts b/src/main/claude/claude-plugin-input-failure-journal.ts deleted file mode 100644 index 06209841ec8..00000000000 --- a/src/main/claude/claude-plugin-input-failure-journal.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { agentJournalSubmissionKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { PROVIDER_EXIT_ROW_PREFIX } from '../../shared/agent-session/lifecycle/agent-session-stop-row-identity' -import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudeOpenTurn } from './claude-open-turn' -import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state' - -export function journalClaudePluginInputFailure({ - event, - turn, - sink, - finish -}: { - event: Extract - turn: ClaudeOpenTurn - sink: StructuredAgentSessionEventSink - finish: (observedAt: number, failed: boolean) => void -}): void { - if (!turn.isOpen && event.unopenedSend) { - // A failed dispatched action needs a turn outcome without claiming a provider echo or acceptance. - turn.open( - { - sessionId: event.providerSessionId, - turnId: `plugin-input:${event.unopenedSend.clientMessageId}`, - userItemId: agentJournalSubmissionKey(event.unopenedSend.clientMessageId), - startedAt: event.unopenedSend.requestedAt ?? event.observedAt, - ...(event.unopenedSend.requestedAt === undefined - ? {} - : { - requestedAt: event.unopenedSend.requestedAt - }) - }, - event.observedAt - ) - } - const scope = turn.turnScope - const stopped = turn.id !== null && sink.journalStopDecidesTurn?.(turn.id, event.observedAt) - finish(event.observedAt, !stopped) - if (stopped) { - return - } - // Physical-exit settlement revises this same row after proof; it must not add another notice. - sink.appendItem( - { - provider: 'orca', - clientMessageId: `${PROVIDER_EXIT_ROW_PREFIX}${event.sessionId}:${event.fence}:${event.acquisitionGeneration}` - }, - { - kind: 'status', - tone: 'error', - ...agentSessionFailureWords(event.failure, { surface: 'row', agentName: 'Claude' }) - }, - { turnScope: scope, lifecycle: true, observedAt: event.observedAt } - ) - sink.publish({ lifecycle: true }) -} - -export function settleClaudeInterruptedTurn( - turn: ClaudeOpenTurn, - observedAt: number, - failed: boolean -): void { - turn.settle({ - state: 'interrupted', - ...(failed ? { outcome: 'failure' as const } : {}), - completedAt: observedAt - }) - turn.suppressReopen() -} diff --git a/src/main/claude/claude-provider-session-rename.test.ts b/src/main/claude/claude-provider-session-rename.test.ts deleted file mode 100644 index 29d434c5c2d..00000000000 --- a/src/main/claude/claude-provider-session-rename.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { listSessions } from '@anthropic-ai/claude-agent-sdk' -import { randomUUID } from 'node:crypto' -import * as fs from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import * as transcriptFs from '../native-chat/wsl-transcript-fs-access' -import { renameClaudeTranscript } from './claude-provider-session-rename' - -let home: string -let conversation: string -let transcript: string -beforeEach(async () => { - home = await fs.mkdtemp(join(tmpdir(), 'orca-claude-rename-')) - conversation = randomUUID() - const project = join(home, 'projects', 'workspace') - await fs.mkdir(project, { recursive: true }) - transcript = join(project, `${conversation}.jsonl`) -}) -afterEach(async () => { - vi.restoreAllMocks() - await fs.rm(home, { recursive: true, force: true }) -}) - -it.each([false, true])( - 'appends both native names after a torn tail (earlier agent-name=%s)', - async (earlierName) => { - const user = { - type: 'user', - uuid: randomUUID(), - sessionId: conversation, - message: { role: 'user', content: 'ship it' } - } - const oldName = earlierName - ? `${JSON.stringify({ type: 'agent-name', agentName: 'Earlier native name', sessionId: conversation })}\n` - : '' - const prefix = `${JSON.stringify(user)}\n${oldName}{"type":"assistant","mess` - await fs.writeFile(transcript, prefix) - const otherAccount = join(home, 'other-account', 'projects', 'workspace') - await fs.mkdir(otherAccount, { recursive: true }) - const otherTranscript = join(otherAccount, `${conversation}.jsonl`) - await fs.writeFile(otherTranscript, 'another account\n') - const source = join(home, 'projects', 'workspace', `${randomUUID()}.jsonl`) - await fs.writeFile(source, 'unrelated source\n') - const inventory = vi.spyOn(transcriptFs, 'wslGatedReaddir') - const stat = vi.spyOn(transcriptFs, 'wslGatedStat') - const append = vi.spyOn(fs, 'appendFile') - const originalOpen = fs.open - const open = vi.spyOn(fs, 'open').mockImplementation(async (...args) => { - const handle = await originalOpen(...args) - vi.spyOn(handle, 'read') - return handle - }) - await renameClaudeTranscript(home, conversation, ' Release notes ') - const result = await fs.readFile(transcript, 'utf8') - expect(result.slice(0, prefix.length + 1)).toBe(`${prefix}\n`) - const lines = result - .slice(prefix.length + 1) - .trim() - .split('\n') - expect(lines).toHaveLength(2) - const title = JSON.parse(lines[0] ?? '') - expect(title).toMatchObject({ - type: 'custom-title', - sessionId: conversation, - customTitle: 'Release notes' - }) - expect(title.uuid).toEqual(expect.any(String)) - expect(title.timestamp).toEqual(expect.any(String)) - expect(JSON.parse(lines[1] ?? '')).toEqual({ - type: 'agent-name', - agentName: 'Release notes', - sessionId: conversation - }) - expect(inventory).toHaveBeenCalledTimes(1) - expect(stat).toHaveBeenCalledTimes(1) - expect(open).toHaveBeenCalledExactlyOnceWith(transcript, 'r') - const handle = await open.mock.results[0]?.value - expect(handle?.read).toHaveBeenCalledExactlyOnceWith( - expect.any(Buffer), - 0, - 1, - Buffer.byteLength(prefix) - 1 - ) - expect(append).toHaveBeenCalledExactlyOnceWith(transcript, `\n${lines.join('\n')}\n`, { - flag: 'a' - }) - expect(await fs.readFile(otherTranscript, 'utf8')).toBe('another account\n') - expect(await fs.readFile(source, 'utf8')).toBe('unrelated source\n') - const listed = await listSessions({ - sessionStore: { - load: async () => [user, title], - append: async () => {}, - listSessions: async () => [{ sessionId: conversation, mtime: 1_700_000_000_000 }] - } - }) - expect(listed[0]?.customTitle).toBe('Release notes') - } -) - -it('refuses missing, empty, multiple and incomplete inventories without mutating another candidate', async () => { - await expect(renameClaudeTranscript(home, conversation, 'Missing')).rejects.toThrow( - 'no transcript' - ) - await fs.writeFile(transcript, '') - await expect(renameClaudeTranscript(home, conversation, 'Empty')).rejects.toThrow('no transcript') - await fs.writeFile(transcript, 'old\n') - const second = join(home, 'projects', 'hash-or-worktree') - await fs.mkdir(second) - const duplicate = join(second, `${conversation}.jsonl`) - await fs.writeFile(duplicate, 'other\n') - await expect(renameClaudeTranscript(home, conversation, 'Ambiguous')).rejects.toThrow( - 'multiple transcripts' - ) - expect(await fs.readFile(transcript, 'utf8')).toBe('old\n') - expect(await fs.readFile(duplicate, 'utf8')).toBe('other\n') - const denied = Object.assign(new Error('denied'), { code: 'EACCES' }) - vi.spyOn(transcriptFs, 'wslGatedStat').mockRejectedValue(denied) - await expect(renameClaudeTranscript(home, conversation, 'Denied')).rejects.toBe(denied) - expect(await fs.readFile(transcript, 'utf8')).toBe('old\n') -}) diff --git a/src/main/claude/claude-provisional-row-corrections.test.ts b/src/main/claude/claude-provisional-row-corrections.test.ts deleted file mode 100644 index 9ed34e3e17f..00000000000 --- a/src/main/claude/claude-provisional-row-corrections.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' -import { describe, expect, it } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { StructuredAgentSessionAppendOptions } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { ClaudeProvisionalRowCorrections } from './claude-provisional-row-corrections' -import type { ClaudeSubagentLinkageVerdict } from './claude-subagent-linkage' - -function identityOf(toolUseId: string): AgentJournalItemIdentity { - return { provider: 'orca', clientMessageId: `claude-tool:claude-session:${toolUseId}` } -} - -const RUNNING: AgentJournalItemBody = { - kind: 'tool-call', - callId: 'toolu_2', - name: 'Task', - input: null, - state: 'running' -} -const COMPLETED: AgentJournalItemBody = { ...RUNNING, state: 'completed' } - -function ledger(initial: Record = {}) { - const verdicts = new Map(Object.entries(initial)) - const rewrites: { - identity: AgentJournalItemIdentity - body: AgentJournalItemBody - options: StructuredAgentSessionAppendOptions - }[] = [] - let published = 0 - let refuse = false - const settledFor = (ref: string): ClaudeSubagentLinkageVerdict => { - const verdict = verdicts.get(ref) - return verdict && verdict.kind !== 'pending' - ? verdict - : { kind: 'linked', linkage: { agentId: ref, providerParentRef: ref, producerKind: 'agent' } } - } - const corrections = new ClaudeProvisionalRowCorrections({ - turnScope: () => AGENT_JOURNAL_THREAD_SCOPE, - linkageFor: (ref) => verdicts.get(ref) ?? { kind: 'pending' }, - settledLinkageFor: (ref) => { - const verdict = settledFor(ref) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: `settledFor` returns only the linked arm, never `pending`. - return verdict as Exclude - }, - rewrite: (identity, body, options) => { - if (refuse) { - return false - } - rewrites.push({ identity, body, options }) - return true - }, - publish: () => { - published += 1 - } - }) - return { - corrections, - rewrites, - announce: (ref: string, agentId: string) => - verdicts.set(ref, { - kind: 'linked', - linkage: { agentId, providerParentRef: ref, producerKind: 'agent' } - }), - publishes: () => published, - setRefusing: (value: boolean) => { - refuse = value - } - } -} - -describe('ClaudeProvisionalRowCorrections', () => { - it('stamps a provisional row at once and re-attributes it on the announcement', () => { - const { corrections, rewrites, announce } = ledger() - const stamped = corrections.stampFor('toolu_1')(identityOf('toolu_2'), RUNNING) - - expect(stamped).toMatchObject({ agentId: 'toolu_1' }) - expect(corrections.pending).toBe(1) - - announce('toolu_1', 'task-1') - corrections.retry() - - expect(rewrites).toEqual([ - { - identity: identityOf('toolu_2'), - body: RUNNING, - options: expect.objectContaining({ agentId: 'task-1' }) - } - ]) - expect(corrections.pending).toBe(0) - }) - - it('lets a settled write supersede the correction owed to that row', () => { - const { corrections, rewrites, announce } = ledger() - corrections.stampFor('toolu_1')(identityOf('toolu_2'), RUNNING) - expect(corrections.pending).toBe(1) - - announce('toolu_other', 'task-other') - corrections.stampFor('toolu_other')(identityOf('toolu_2'), COMPLETED) - - expect(corrections.pending).toBe(0) - announce('toolu_1', 'task-1') - corrections.retry() - expect(rewrites).toEqual([]) - }) - - it('keeps a correction owed when the sink refuses it, and retries at abandon', () => { - const { corrections, rewrites, announce, setRefusing } = ledger() - corrections.stampFor('toolu_1')(identityOf('toolu_2'), RUNNING) - announce('toolu_1', 'task-1') - - setRefusing(true) - corrections.retry() - expect(rewrites).toEqual([]) - expect(corrections.pending).toBe(1) - - setRefusing(false) - corrections.retry() - expect(rewrites).toHaveLength(1) - expect(corrections.pending).toBe(0) - }) - - it('carries the NEWEST body when a row is written provisionally twice', () => { - const { corrections, rewrites, announce } = ledger() - const stamp = corrections.stampFor('toolu_1') - stamp(identityOf('toolu_2'), RUNNING) - stamp(identityOf('toolu_2'), COMPLETED) - - announce('toolu_1', 'task-1') - corrections.retry() - - expect(rewrites).toHaveLength(1) - expect(rewrites[0]?.body).toEqual(COMPLETED) - }) - - it('gives up on a producer WHOLESALE past the bound, never half of it', () => { - const { corrections, rewrites, announce } = ledger() - const stamp = corrections.stampFor('toolu_1') - for (let index = 0; index < 129; index += 1) { - stamp(identityOf(`toolu_row_${index}`), RUNNING) - } - expect(corrections.pending).toBe(0) - - announce('toolu_1', 'task-1') - corrections.retry() - - expect(rewrites).toEqual([]) - }) -}) diff --git a/src/main/claude/claude-real-cli-availability-test-support.ts b/src/main/claude/claude-real-cli-availability-test-support.ts deleted file mode 100644 index 22150adc1cd..00000000000 --- a/src/main/claude/claude-real-cli-availability-test-support.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { homedir } from 'node:os' -import { join } from 'node:path' -import { runProcessSync } from '@orca/process-host' -import type { ProcessResult } from '@orca/process-host/process-spec' -import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { CLAUDE_AUTH_ENV_VARS } from '../claude-accounts/runtime-auth/environment' -import { resolveClaudeCommand } from '../codex-cli/command' -import { resolveRealClaudeCliGate } from './claude-real-cli-test-gate' - -export const realClaudeCommand = resolveClaudeCommand() - -// Match structured launches by using the CLI's paired Node runtime. -function probeRealClaude(args: string[]): ProcessResult | null { - try { - return runProcessSync({ - program: realClaudeCommand, - args, - env: withCliRuntimeOnPath(realClaudeCommand, process.env), - stdio: ['ignore', 'pipe', 'pipe'], - timeoutMs: 5_000 - }) - } catch { - return null - } -} - -export const realClaudeCliGate = resolveRealClaudeCliGate(process.env, (args) => { - const result = probeRealClaude([...args]) - return { status: result?.code ?? null, stdout: result?.stdout ?? '' } -}) - -export const realClaudeAvailable = realClaudeCliGate.skipReason === null - -/** Use the CLI's account report as an independent oracle for transcript paths. */ -export const realClaudeAuthStatus = realClaudeCliGate.authStatus - -export const realClaudeAuthenticated = realClaudeAuthStatus?.loggedIn === true - -/** Restore the probed home and auth explicitly: connections strip inherited account state. */ -export function realClaudeLaunchHome(): { claudeConfigDir: string; env: Record } { - const env: Record = {} - for (const key of CLAUDE_AUTH_ENV_VARS) { - const value = process.env[key] - if (value) { - env[key] = value - } - } - return { - claudeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude'), - env - } -} diff --git a/src/main/claude/claude-real-cli-test-gate.ts b/src/main/claude/claude-real-cli-test-gate.ts deleted file mode 100644 index 745ede2733b..00000000000 --- a/src/main/claude/claude-real-cli-test-gate.ts +++ /dev/null @@ -1,63 +0,0 @@ -/** Opt-in for tests that drive the real `claude` CLI on this machine's signed-in account. */ -export const REAL_CLAUDE_CLI_TEST_ENV = 'ORCA_REAL_CLAUDE_CLI_TEST' - -export type ClaudeCliProbeResult = { status: number | null; stdout: string } - -export type RealClaudeAuthStatus = { loggedIn?: boolean; projectsDirectory?: string } - -export type RealClaudeCliGate = { - /** Null permits the real-CLI suite to run. */ - skipReason: string | null - authStatus: RealClaudeAuthStatus | null -} - -function parseAuthStatus(stdout: string): RealClaudeAuthStatus | null { - const start = stdout.search(/[[{]/) - if (start === -1) { - return null - } - // CLI warnings may precede the report, but another JSON value makes it ambiguous. - for (const line of stdout.slice(0, start).split('\n')) { - try { - JSON.parse(line) - return null - } catch { - continue - } - } - let parsed: unknown - try { - parsed = JSON.parse(stdout.slice(start)) - } catch { - return null - } - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - return null - } - const status: RealClaudeAuthStatus = {} - if ('loggedIn' in parsed && typeof parsed.loggedIn === 'boolean') { - status.loggedIn = parsed.loggedIn - } - if ('projectsDirectory' in parsed && typeof parsed.projectsDirectory === 'string') { - status.projectsDirectory = parsed.projectsDirectory - } - return status -} - -export function resolveRealClaudeCliGate( - env: NodeJS.ProcessEnv, - runClaude: (args: readonly string[]) => ClaudeCliProbeResult -): RealClaudeCliGate { - // Require opt-in before probing an account whose tests spend turns and write transcripts. - if (env[REAL_CLAUDE_CLI_TEST_ENV] !== '1') { - return { - skipReason: `set ${REAL_CLAUDE_CLI_TEST_ENV}=1 to run against the real claude CLI`, - authStatus: null - } - } - if (runClaude(['--version']).status !== 0) { - return { skipReason: '`claude --version` failed', authStatus: null } - } - const auth = runClaude(['auth', 'status', '--json']) - return { skipReason: null, authStatus: auth.status === 0 ? parseAuthStatus(auth.stdout) : null } -} diff --git a/src/main/claude/claude-request-end-wait.test.ts b/src/main/claude/claude-request-end-wait.test.ts deleted file mode 100644 index 5cadb80089d..00000000000 --- a/src/main/claude/claude-request-end-wait.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - awaitClaudeRequestEnd, - CLAUDE_STOP_GRACE_MS, - claudeStoppedRequestEndWait, - settleClaudeTurnEndWaiters -} from './claude-request-end-wait' -import type { ClaudeSession } from './structured/claude-structured-session-state' - -type InFlight = { translator: { currentTurnId: string | null }; dispatchWaiters: unknown[] } - -function claudeWith( - currentTurnId: string | null = 'turn-1', - unanswered = 0 -): { claude: ClaudeSession; state: InFlight } { - const state: InFlight = { - translator: { currentTurnId }, - dispatchWaiters: Array.from({ length: unanswered }, () => ({})) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the wait reads only `translator.currentTurnId` and `dispatchWaiters`, and keys its waiters by the session's identity. - return { claude: state as unknown as ClaudeSession, state } -} - -function session(currentTurnId: string | null = 'turn-1'): ClaudeSession { - return claudeWith(currentTurnId).claude -} - -async function settledWithin(promise: Promise, ms: number): Promise { - let settled = false - void promise.then(() => { - settled = true - }) - await vi.advanceTimersByTimeAsync(ms) - return settled -} - -describe("a Stop's wait for Claude to wind down what it has in flight", () => { - beforeEach(() => { - vi.useFakeTimers() - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('waits on a send Claude has not echoed, through its turn, to that turn’s end', async () => { - const { claude, state } = claudeWith(null, 1) - const waiting = awaitClaudeRequestEnd(claude, CLAUDE_STOP_GRACE_MS) - state.dispatchWaiters.length = 0 - state.translator.currentTurnId = 'turn-1' - settleClaudeTurnEndWaiters(claude) - expect(await settledWithin(waiting, 0)).toBe(false) - - state.translator.currentTurnId = null - settleClaudeTurnEndWaiters(claude) - expect(await settledWithin(waiting, 0)).toBe(true) - }) - - it('waits only what the interrupt left of the grace, and nothing for a session that is gone', async () => { - const sessions = new Map([['session-1', session()]]) - const wait = claudeStoppedRequestEndWait(sessions) - const stoppedAt = Date.now() - await vi.advanceTimersByTimeAsync(CLAUDE_STOP_GRACE_MS - 1_000) - const waiting = wait('session-1', stoppedAt) - - expect(await settledWithin(waiting, 999)).toBe(false) - expect(await settledWithin(waiting, 1)).toBe(true) - expect(await settledWithin(wait('session-2', Date.now()), 0)).toBe(true) - }) -}) diff --git a/src/main/claude/claude-rewind-transcript.test.ts b/src/main/claude/claude-rewind-transcript.test.ts deleted file mode 100644 index 9e56548cac5..00000000000 --- a/src/main/claude/claude-rewind-transcript.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import './claude-conversation-worker.test-fixture' -import { randomUUID } from 'node:crypto' -import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { AgentSessionRewindRecordSchema } from '../../shared/agent-session/lifecycle/agent-session-rewind' -import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' -import { createClaudeStructuredLaunchResolver } from '../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { resolveClaudeRewindFork } from './claude-rewind-fork' -import { claudeSessionIdForRewind } from './structured/claude-structured-session-id' - -let root: string -let home: string -let project: string -let source: string -let path: string -let original: string -let sourceRows: ReturnType - -function transcriptRows(contents: string) { - return contents - .trim() - .split('\n') - .map((line) => JSON.parse(line)) -} - -async function recordedTranscript(kind: 'hook' | 'informational') { - return readFile(new URL(`./__fixtures__/claude-rewind-${kind}.jsonl`, import.meta.url), 'utf8') -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-rewind-transcript-')) - home = join(root, 'account') - project = join(home, 'projects', 'workspace') - await mkdir(project, { recursive: true }) - original = await recordedTranscript('hook') - sourceRows = transcriptRows(original) - source = sourceRows[6].sessionId - path = join(project, `${source}.jsonl`) - await writeFile(path, original) -}) - -afterEach(async () => { - await rm(root, { recursive: true, force: true }) -}) - -function forkBefore(uuid: string, rewindOperationId = randomUUID()) { - return resolveClaudeRewindFork({ - orcaSessionId: 'orca-chat', - rewindOperationId, - head: claudeProviderHandle(source, sourceRows.at(-1)?.uuid), - prompt: { sessionId: source, uuid }, - claudeConfigDirs: [join(root, 'other-account'), home] - }) -} - -describe('durable Claude rewind transcripts', () => { - it.each([ - { promptRow: 35, parentRow: 28, cursorRole: 'user' }, - { promptRow: 55, parentRow: 51, cursorRole: 'assistant' } - ])( - 'keeps the exact $cursorRole cursor before recorded prompt $promptRow', - async ({ promptRow, parentRow, cursorRole }) => { - const prompt = sourceRows[promptRow - 1] - const fork = await forkBefore(prompt.uuid) - expect(fork).toMatchObject({ - materialized: true, - sourceSessionId: source, - throughEntryId: sourceRows[parentRow - 1].uuid - }) - if (!fork) { - throw new Error('fork missing') - } - const forkPath = join(project, `${fork.sessionId}.jsonl`) - const contents = await readFile(forkPath, 'utf8') - const conversation = (rows: typeof sourceRows) => - rows.filter((row) => row.type === 'user' || row.type === 'assistant') - const kept = conversation(transcriptRows(contents)) - const expected = conversation(sourceRows.slice(0, parentRow)) - expect(kept.map((row) => row.forkedFrom.messageUuid)).toEqual(expected.map((row) => row.uuid)) - expect(kept.at(-1)).toMatchObject({ type: cursorRole, uuid: fork.resumeCursor }) - expect(fork.resumeCursor).toBeTruthy() - expect(fork.resumeCursor).not.toBe(expected.at(-1)?.uuid) - expect(contents).not.toContain(prompt.uuid) - expect(await readFile(path, 'utf8')).toBe(original) - expect((await readdir(project)).sort()).toEqual( - [`${source}.jsonl`, `${fork.sessionId}.jsonl`].sort() - ) - if (process.platform !== 'win32') { - expect((await stat(forkPath)).mode & 0o777).toBe(0o600) - } - } - ) - - it.each(['hook', 'informational', 'null'] as const)( - 'starts and reloads an empty fork after a %s parent', - async (kind) => { - original = await recordedTranscript(kind === 'informational' ? 'informational' : 'hook') - sourceRows = transcriptRows(original) - const prompt = sourceRows.find((row) => row.type === 'user') - if (kind === 'null') { - prompt.parentUuid = null - original = `${sourceRows.map((row) => JSON.stringify(row)).join('\n')}\n` - } - await writeFile(path, original) - const operationId = randomUUID() - const fork = await forkBefore(prompt.uuid, operationId) - expect(fork).toStrictEqual({ - sessionId: claudeSessionIdForRewind('orca-chat', operationId), - sourceSessionId: source, - replacesSessionId: source, - materialized: true, - coverage: [] - }) - if (!fork) { - throw new Error('fork missing') - } - expect(await readdir(project)).toEqual([`${source}.jsonl`]) - const launchers = [true, false].map((prepared) => { - const handle = claudeProviderHandle( - prepared ? source : fork.sessionId, - prepared ? prompt.uuid : null - ) - const record = agentSessionRecordFixture({ - sessionId: 'orca-chat', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: home }, - providerHandleChain: [ - { linkId: 'head', origin: 'created', mintedAtFence: 1, observedAt: 1, handle } - ], - rewind: AgentSessionRewindRecordSchema.parse( - JSON.parse( - JSON.stringify({ - operationId, - callerKey: 'desktop', - itemId: 'item-1', - expectedEpoch: 'epoch-1', - phase: prepared ? 'prepared' : 'completed', - providerFork: fork - }) - ) - ) - }) - const resolve = createClaudeStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveLaunchArgs: () => [], - resolveWorkspacePath: async () => project, - resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }), - resolveInheritedEnv: async () => ({ PATH: '/usr/bin' }), - resolveAuthPolicy: () => ({ account: 'system' }) - }) - return () => - resolve({ - identity: { - sessionId: record.sessionId, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: handle - } - }) - }) - for (const launch of launchers) { - const fresh = await launch() - expect(fresh.options.sessionId).toBe(fork.sessionId) - expect(fresh.resumesTranscript).toBe(false) - for (const key of ['resume', 'resumeSessionAt', 'forkSession']) { - expect(fresh.options).not.toHaveProperty(key) - } - } - await writeFile( - join(project, `${fork.sessionId}.jsonl`), - `${JSON.stringify({ ...prompt, sessionId: fork.sessionId, parentUuid: null })}\n` - ) - for (const launch of launchers) { - const resumed = await launch() - expect(resumed.options.resume).toBe(fork.sessionId) - expect(resumed.options).not.toHaveProperty('resumeSessionAt') - expect(resumed.options).not.toHaveProperty('forkSession') - } - expect(await readFile(path, 'utf8')).toBe(original) - } - ) - - it('drops the local-command caveat when rewinding to a local command', async () => { - const turn = sourceRows[50] - const row = (uuid: string, parentUuid: string, content: string, isMeta?: true) => ({ - ...sourceRows[54], - uuid, - parentUuid, - isMeta, - message: { role: 'user', content } - }) - const caveat = row( - randomUUID(), - turn.uuid, - 'The command below was run directly in Claude Code.', - true - ) - const command = row(randomUUID(), caveat.uuid, '/usage') - const stdout = row( - randomUUID(), - command.uuid, - 'ok' - ) - await writeFile( - path, - `${[...sourceRows.slice(0, 54), caveat, command, stdout].map((r) => JSON.stringify(r)).join('\n')}\n` - ) - const fork = await forkBefore(command.uuid) - expect(fork).toMatchObject({ materialized: true, throughEntryId: turn.uuid }) - const contents = await readFile(join(project, `${fork?.sessionId}.jsonl`), 'utf8') - expect(contents).not.toContain('local-command-caveat') - }) - - it('skips a torn transcript line instead of failing the rewind', async () => { - const damaged = `{broken-json}\n${original}{"type":` - await writeFile(path, damaged) - const fork = await forkBefore(sourceRows[34].uuid) - expect(fork).toMatchObject({ materialized: true, throughEntryId: sourceRows[27].uuid }) - const contents = await readFile(join(project, `${fork?.sessionId}.jsonl`), 'utf8') - expect(contents).not.toContain(sourceRows[34].uuid) - expect(await readFile(path, 'utf8')).toBe(damaged) - }) -}) diff --git a/src/main/claude/claude-scripted-child.test-fixture.ts b/src/main/claude/claude-scripted-child.test-fixture.ts deleted file mode 100644 index 9672c1f17ba..00000000000 --- a/src/main/claude/claude-scripted-child.test-fixture.ts +++ /dev/null @@ -1,164 +0,0 @@ -// Registration fixture uses the real Claude adapter over scripted stream-json, including initialize handshake. - -import { randomUUID } from 'node:crypto' -import { mkdirSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import type { - ClaudeStreamJsonConnection, - ClaudeStreamJsonLaunch, - openClaudeStreamJsonConnection -} from './claude-stream-json-connection' -import type { - ScriptedAgentChild, - ScriptedAgentChildFactory -} from '../runtime/agent-session/installation/structured-agent-scripted-child.test-fixture' -import { scriptedClaudeExitError } from '../runtime/agent-session/installation/structured-claude-scripted-runtime-test-support' -import { result, says } from './claude-captured-frame-builders.test-fixture' - -type Spawned = { - connection: Omit & { - closed: boolean - exitVerdict: ClaudeStreamJsonConnection['exitVerdict'] - } - answer: () => void - fail: (message: string) => void -} - -function promptText(message: Record): string { - const inner = message.message - const content = - inner && typeof inner === 'object' && 'content' in inner ? inner.content : undefined - const blocks = Array.isArray(content) ? content : [] - return blocks - .map((block: unknown) => - block && typeof block === 'object' && 'text' in block ? String(block.text) : '' - ) - .join('') -} - -/** The CLI writes its transcript as a conversation's first message lands; a later start resumes it. */ -function writeTranscript(launch: ClaudeStreamJsonLaunch, providerSessionId: string): void { - const home = launch.env?.CLAUDE_CONFIG_DIR - if (!home) { - return - } - const folder = join(home, 'projects', 'scripted') - mkdirSync(folder, { recursive: true }) - writeFileSync(join(folder, `${providerSessionId}.jsonl`), '{}\n') -} - -export const claudeScriptedChild: ScriptedAgentChildFactory = () => { - const spawned: Spawned[] = [] - const prompts: string[] = [] - let resumes = 0 - let closes = 0 - const openConnection: typeof openClaudeStreamJsonConnection = async (launch, handlers = {}) => { - if (launch.options.resume !== undefined) { - resumes += 1 - } - const providerSessionId = String(launch.options.sessionId ?? launch.options.resume) - const initialized = { models: [{ value: 'sonnet', displayName: 'Sonnet' }] } - let answer = (): void => {} - let reject = (_error: Error): void => {} - const init = new Promise((resolve, fail) => { - answer = () => { - handlers.onMessage?.({ - type: 'system', - subtype: 'init', - session_id: providerSessionId, - model: 'claude-sonnet-5', - apiKeySource: 'none' - }) - resolve(initialized) - } - reject = fail - }) - if (!child.holdHandshakes) { - answer() - } - const connection: Spawned['connection'] = { - pid: 7000 + spawned.length, - closed: false, - exitVerdict: { root: 'live', tree: 'unverifiable' }, - initializationResult: () => init, - getContextUsage: async () => ({}), - renameSession: async () => {}, - getSettings: async () => ({ effective: {} }), - supportedModels: async () => [{ value: 'sonnet', displayName: 'Sonnet' }], - setModel: async () => {}, - setPermissionMode: async () => {}, - applyFlagSettings: async () => {}, - interrupt: async () => undefined, - cancelAsyncMessage: async () => false, - stopTask: async () => {}, - send: async (message, beforeDispatch) => { - await beforeDispatch?.() - prompts.push(promptText(message)) - writeTranscript(launch, providerSessionId) - // The CLI echoes each message it takes under the client's uuid: Orca's proof of delivery. - handlers.onMessage?.({ - type: 'user', - session_id: providerSessionId, - parent_tool_use_id: null, - uuid: message.uuid, - isReplay: true, - message: message.message - }) - if (child.completeTurns) { - const id = randomUUID() - handlers.onMessage?.({ ...says(id, 'done', null), session_id: providerSessionId }) - handlers.onMessage?.({ ...result('success'), session_id: providerSessionId, uuid: id }) - } - }, - close: async () => { - if (!connection.closed) { - connection.closed = true - closes += 1 - connection.exitVerdict = { root: 'exited', tree: 'exited' } - handlers.onExit?.(new Error('closed by Orca')) - } - return true - } - } - spawned.push({ - connection, - answer, - fail: (message) => { - const error = scriptedClaudeExitError(message) - connection.closed = true - connection.exitVerdict = { root: 'exited', tree: 'unverifiable' } - reject(error) - handlers.onExit?.(error) - } - }) - return connection - } - const newest = (): Spawned => { - const latest = spawned.at(-1) - if (!latest) { - throw new Error('no Claude child was spawned') - } - return latest - } - const child: ScriptedAgentChild = { - deps: { - openClaudeConnection: openConnection, - readProcessStartTime: async (pid) => - spawned.find((entry) => entry.connection.pid === pid)?.connection.exitVerdict.root === - 'exited' - ? null - : pid * 10, - resolveClaudeCommand: () => ({ command: '/nonexistent/scripted-claude', prefixArgs: [] }), - resolveClaudeAuthPolicy: () => ({ account: 'system' }) - }, - holdHandshakes: true, - releaseHandshake: () => newest().answer(), - failHandshake: (message) => newest().fail(message), - completeTurns: true, - prompts: () => prompts, - spawns: () => spawned.length, - resumes: () => resumes, - closes: () => closes - } - return child -} diff --git a/src/main/claude/claude-settings-schema-install.test.ts b/src/main/claude/claude-settings-schema-install.test.ts deleted file mode 100644 index 76c01011f47..00000000000 --- a/src/main/claude/claude-settings-schema-install.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import fixture from './__fixtures__/claude-hook-event-enums.json' - -vi.mock('electron', () => ({ - app: { - getPath: () => '/tmp/userData' - } -})) - -import { ClaudeHookService } from './hook-service' - -const enums: Record = fixture.enums -const topLevelSettings: Record = - fixture.topLevelSettings -const strictReleases = Object.keys(topLevelSettings).filter( - (version) => topLevelSettings[version].strict -) - -describe('Claude settings written for a strict settings schema', () => { - let tmpHome: string - let settingsPath: string - - beforeEach(() => { - tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-settings-schema-')) - settingsPath = join(tmpHome, '.claude', 'settings.json') - vi.stubEnv('HOME', tmpHome) - vi.stubEnv('USERPROFILE', tmpHome) - }) - - afterEach(() => { - vi.unstubAllEnvs() - rmSync(tmpHome, { recursive: true, force: true }) - }) - - function expectAcceptedBy(version: string): void { - const written = JSON.parse(readFileSync(settingsPath, 'utf-8')) - const { keys } = topLevelSettings[version] - expect(Object.keys(written).filter((key) => !keys.includes(key))).toEqual([]) - expect( - Object.keys(written.hooks ?? {}).filter((event) => !enums[version].includes(event)) - ).toEqual([]) - } - - it.each(strictReleases)('a fresh install writes only what Claude %s accepts', (version) => { - new ClaudeHookService().install({ claudeVersion: version }) - expectAcceptedBy(version) - }) - - it.each(strictReleases)('a downgrade to Claude %s leaves only what it accepts', (version) => { - const service = new ClaudeHookService() - service.install({ claudeVersion: '2.1.261' }) - service.install({ claudeVersion: version }) - expectAcceptedBy(version) - }) -}) diff --git a/src/main/claude/claude-status-line-windows.test.ts b/src/main/claude/claude-status-line-windows.test.ts deleted file mode 100644 index 95fdf8313d1..00000000000 --- a/src/main/claude/claude-status-line-windows.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type * as osModule from 'node:os' -import { runProcess } from '@orca/process-host' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { parseClaudeStatusLineBody } from '../../shared/claude-statusline-rate-limits' - -const { homedirMock } = vi.hoisted(() => ({ - homedirMock: vi.fn<() => string>() -})) - -vi.mock('electron', () => ({ app: { getPath: () => '/tmp/orca-user-data' } })) - -vi.mock('os', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, homedir: homedirMock.mockImplementation(actual.homedir) } -}) - -import { findGitBash } from '../agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture' -import { ClaudeHookService } from './hook-service' -import { getManagedCommand } from './hook-settings' - -const CURRENT_CLAUDE = { claudeVersion: '2.1.261 (Claude Code)' } -const PAYLOAD = JSON.stringify({ - session_id: 'statusline-delivery', - model: { id: 'claude-opus-5-5', display_name: 'Opus' }, - rate_limits: { - five_hour: { used_percentage: 42, resets_at: 1790000000 }, - seven_day: { used_percentage: 7, resets_at: 1790500000 } - } -}) -const EXPECTED_RATE_LIMITS = { - configDir: null, - fiveHour: { used_percentage: 42, resets_at: 1790000000 }, - sevenDay: { used_percentage: 7, resets_at: 1790500000 } -} -const HOOK_TOKEN = 'statusline-delivery-token' -// Match Claude.exe's PowerShell flags. -const POWERSHELL_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command'] - -const LEGACY_COMMAND = getManagedCommand('claude-statusline.cmd') - -type StatusLineSettings = { statusLine?: { type: string; command: string } } - -function settingsPath(home: string): string { - return join(home, '.claude', 'settings.json') -} - -function powershellPath(): string { - const systemRoot = process.env.SystemRoot ?? 'C:\\Windows' - return join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') -} - -async function startStatusLineListener(): Promise<{ - server: Server - port: number - posts: Record[] -}> { - const posts: Record[] = [] - const server = createServer((req, res) => { - let body = '' - req.setEncoding('utf8') - req.on('data', (chunk) => { - body += chunk - }) - req.on('end', () => { - posts.push({ ...Object.fromEntries(new URLSearchParams(body)), path: req.url ?? '' }) - res.writeHead(200) - res.end() - }) - }) - const port = await new Promise((resolve) => { - server.listen(0, '127.0.0.1', () => { - const address = server.address() - resolve(typeof address === 'object' && address ? address.port : 0) - }) - }) - return { server, port, posts } -} - -describe.skipIf(process.platform !== 'win32')('Claude statusLine delivery on Windows', () => { - let home = '' - let server: Server | null = null - - afterEach(() => { - server?.close() - server = null - homedirMock.mockReset() - if (home) { - removeTreeSync(home) - home = '' - } - }) - - async function installInto(prefix: string, seed?: StatusLineSettings) { - home = mkdtempSync(join(tmpdir(), prefix)) - homedirMock.mockReturnValue(home) - // Satisfy developer cmd AutoRun entries that reference this file. - writeFileSync(join(home, '.cmd_aliases.cmd'), '@rem\r\n', 'utf8') - if (seed) { - mkdirSync(join(home, '.claude'), { recursive: true }) - writeFileSync(settingsPath(home), JSON.stringify(seed)) - } - new ClaudeHookService().install(CURRENT_CLAUDE) - const settings: StatusLineSettings = JSON.parse(readFileSync(settingsPath(home), 'utf-8')) - const command = settings.statusLine?.command - if (!command) { - throw new Error('Missing managed statusLine command') - } - - const listener = await startStatusLineListener() - server = listener.server - const baseEnv = Object.fromEntries( - // Isolate live Orca endpoints and inherited daemon-worker guards. - Object.entries(process.env).filter(([key]) => !/^(ORCA|CLAUDE)_/.test(key)) - ) - const run = (program: string, args: string[], paneId: number) => - runProcess({ - program, - args, - input: PAYLOAD, - timeoutMs: 15_000, - env: { - ...baseEnv, - USERPROFILE: home, - HOME: home, - // Keep throttle stamps inside the fixture. - TEMP: home, - TMP: home, - ORCA_BACKGROUND_LAUNCH: '1', - ORCA_AGENT_HOOK_PORT: String(listener.port), - ORCA_AGENT_HOOK_TOKEN: HOOK_TOKEN, - ORCA_PANE_KEY: `tab-1:00000000-0000-4000-8000-00000000000${paneId}` - } - }) - return { command, posts: listener.posts, run } - } - - it('upgrades the runtime-home entry to one Windows PowerShell 5.1 and Git Bash both post through', async () => { - const { command, posts, run } = await installInto('orca-claude-statusline-run-', { - statusLine: { type: 'command', command: LEGACY_COMMAND } - }) - expect(command).toBe( - join(home, '.orca', 'agent-hooks', 'claude-statusline.cmd').replaceAll('\\', '/') - ) - - const legacy = await run(powershellPath(), [...POWERSHELL_ARGS, LEGACY_COMMAND], 0) - expect(legacy.code).not.toBe(0) - expect(posts).toHaveLength(0) - - const shells = [ - { - name: 'Windows PowerShell', - program: powershellPath(), - args: [...POWERSHELL_ARGS, command] - }, - { name: 'Git Bash', program: findGitBash(), args: ['-c', command] } - ] - for (const [index, shell] of shells.entries()) { - const result = await run(shell.program, shell.args, index + 1) - expect(result.timedOut, `${shell.name} timed out`).toBe(false) - expect(result.code, `${shell.name} exit code`).toBe(0) - expect(result.stdout, `${shell.name} stdout`).toBe('') - expect(result.stderr, `${shell.name} stderr`).toBe('') - expect(posts[index]?.path, `${shell.name} posted`).toBe('/statusline/claude') - expect(parseClaudeStatusLineBody(posts[index])).toEqual(EXPECTED_RATE_LIMITS) - } - expect(posts).toHaveLength(shells.length) - }, 60_000) - - it('starts no PowerShell per tick for a profile path with a space', async () => { - const { command, posts, run } = await installInto('orca claude statusline space ') - expect(command).toBe(LEGACY_COMMAND) - - const result = await run(findGitBash(), ['-xc', command], 1) - expect(result.code).toBe(0) - expect(result.stdout).toBe('') - expect(result.stderr).not.toMatch(/powershell|-EncodedCommand/i) - expect(posts).toHaveLength(1) - expect(parseClaudeStatusLineBody(posts[0])).toEqual(EXPECTED_RATE_LIMITS) - - // PowerShell-only hosts with unsafe paths rely on OAuth polling. - await run(powershellPath(), [...POWERSHELL_ARGS, command], 2) - expect(posts).toHaveLength(1) - }, 60_000) -}) diff --git a/src/main/claude/claude-stop-ack-race.test.ts b/src/main/claude/claude-stop-ack-race.test.ts deleted file mode 100644 index 7d2f8319d50..00000000000 --- a/src/main/claude/claude-stop-ack-race.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -// SDK control replies can overtake queued frames even when the CLI wrote task completion first. - -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { spawnProcess } from '@orca/process-host' -import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation' -import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store' -import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { ClaudeChildWorkDecoder } from './claude-child-work-decoder' -import { - openClaudeStreamJsonConnection, - type ClaudeStreamJsonConnection -} from './claude-stream-json-connection' -import { stopClaudeBackgroundTasks } from './structured/claude-structured-control-actions' -import { CLAUDE_STRUCTURED_BASE_OPTIONS } from './structured/launch/claude-structured-launch-resolution' -import type { ClaudeSession } from './structured/claude-structured-session-state' - -const FAKE_CLI = join(__dirname, '__fixtures__', 'claude-agent-sdk-scripted-cli.mjs') -const SESSION_ID = '5348c19f-6a54-4c2e-9c68-9c2b1a3d4e5f' -const parent = makeStructuredAgentStatusSubject( - { executionHostId: 'local', wslDistro: null, workspaceId: 'ws-1', workspaceKind: 'folder' }, - 'session-1' -) -const STARTED = { - type: 'system', - subtype: 'task_started', - task_id: 'task-1', - tool_use_id: 'toolu_1', - task_type: 'local_bash', - is_backgrounded: true, - description: 'npm test', - session_id: SESSION_ID, - uuid: 'started-1' -} -const COMPLETED = { - type: 'system', - subtype: 'task_notification', - task_id: 'task-1', - tool_use_id: 'toolu_1', - status: 'completed', - summary: 'all 12 tests passed', - session_id: SESSION_ID, - uuid: 'completed-1' -} - -const scratch: string[] = [] -const connections: ClaudeStreamJsonConnection[] = [] -afterEach(async () => { - for (const connection of connections.splice(0)) { - await connection.close() - } - for (const dir of scratch.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function streamed(count: number): Record[] { - return Array.from({ length: count }, (_, index) => ({ - type: 'stream_event', - event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x' } }, - session_id: SESSION_ID, - uuid: `stream-${index}` - })) -} - -async function until(done: () => boolean): Promise { - for (let attempt = 0; attempt < 500 && !done(); attempt += 1) { - await new Promise((resolve) => setTimeout(resolve, 10)) - } - expect(done()).toBe(true) -} - -/** Emit streamed frames and task completion before the stop reply in one write. */ -async function stoppedAsItCompleted(ahead: number) { - const dir = mkdtempSync(join(tmpdir(), 'claude-stop-ack-race-')) - scratch.push(dir) - const scenarioPath = join(dir, 'scenario.json') - writeFileSync( - scenarioPath, - JSON.stringify({ - steps: [{ emit: STARTED }, { delayMs: 10_000 }], - controlResponses: { stop_task: {} }, - controlResponseLeadingFrames: { stop_task: [...streamed(ahead), COMPLETED] } - }) - ) - const decoder = new ClaudeChildWorkDecoder() - const evidence: AgentChildWorkEvidence[] = [] - const seen: string[] = [] - const connection = await openClaudeStreamJsonConnection( - { - pathToClaudeCodeExecutable: FAKE_CLI, - options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, sessionId: SESSION_ID }, - cwd: dir, - env: { - PATH: process.env.PATH ?? '', - ORCA_SDK_CONTRACT_SCENARIO_PATH: scenarioPath, - ORCA_SDK_CONTRACT_REPORT_PATH: join(dir, 'report.json') - } - }, - { - onMessage: (message) => { - seen.push(`${String(message.type)}:${String(message.subtype ?? '')}`) - decoder.observe(message) - evidence.push(...decoder.drain(seen.length)) - } - }, - spawnProcess - ) - connections.push(connection) - await until(() => seen.includes('system:task_started')) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a background stop reads only the session's connection and its child-work decoder. - const session = { connection, childWork: decoder } as unknown as ClaudeSession - await stopClaudeBackgroundTasks(session, 5_000, () => true, ['task-1']) - evidence.push(...decoder.drain(seen.length)) - await until(() => seen.includes('system:task_notification')) - - const store = createAgentStatusStore({ epoch: 'epoch-1', mode: 'authority' }) - store.applyMutation({ parent: { subject: parent } }) - let minted = 0 - const admission = createAgentChildWorkAdmission(store, { - mintChildWorkId: () => `child-${++minted}` - }) - reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence }) - return store.getChildren(parent) -} - -describe('a Stop acknowledged ahead of the task’s own earlier completion', () => { - for (const ahead of [0, 1, 5, 50]) { - it(`keeps the task's own outcome and summary with ${ahead} frames ahead of it`, async () => { - expect(await stoppedAsItCompleted(ahead)).toMatchObject([ - { membership: 'settled', outcome: 'succeeded', lastMessage: 'all 12 tests passed' } - ]) - }, 20_000) - } -}) diff --git a/src/main/claude/claude-stream-json-connection-close.test.ts b/src/main/claude/claude-stream-json-connection-close.test.ts deleted file mode 100644 index ff888801f42..00000000000 --- a/src/main/claude/claude-stream-json-connection-close.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { EventEmitter } from 'node:events' -import { PassThrough } from 'node:stream' -import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import { describe, expect, it, vi } from 'vitest' -import type * as ManagedProviderProcessModule from '../provider-process/managed-provider-process' -import type { query } from '@anthropic-ai/claude-agent-sdk' -import { - CLAUDE_READER_DRAIN_AFTER_EXIT_MS, - openClaudeStreamJsonConnection -} from './claude-stream-json-connection' - -const mocks = vi.hoisted(() => { - const refresh = vi.fn() - const closeWriter = vi.fn() - const tree = { - capture: vi.fn(async () => {}), - refresh: (...args: unknown[]) => refresh(...args), - reap: vi.fn(async () => 'exited' as const), - treeVerdict: 'unverifiable' as const, - forcedReapAttempted: false - } - return { closeWriter, refresh, tree } -}) - -vi.mock('./claude-agent-sdk-exit-proof', () => ({ - createClaudeChildTreeReaper: vi.fn(() => mocks.tree) -})) - -vi.mock('../provider-process/managed-provider-process', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - spawnManagedProviderProcess: ( - ...args: Parameters - ) => { - const managed = original.spawnManagedProviderProcess(...args) - managed.closeWriter = async () => - (await mocks.closeWriter()) - ? { root: 'exited', tree: 'exited' } - : { root: 'live', tree: 'unverifiable' } - return managed - } - } -}) - -function fakeChild( - streams: { stdout: PassThrough; stderr: PassThrough } = { - stdout: new PassThrough(), - stderr: new PassThrough() - } -): ChildProcessWithoutNullStreams { - const child = new EventEmitter() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The connection reads only pid, the three pipes and kill, which this fake carries. - return Object.assign(child, { - pid: 424242, - stdin: new PassThrough(), - stdout: streams.stdout, - stderr: streams.stderr, - kill: vi.fn() - }) as unknown as ChildProcessWithoutNullStreams -} - -describe('Claude stream-json close ordering', () => { - it('stops pulling SDK messages until reading resumes', async () => { - mocks.refresh.mockReset() - mocks.closeWriter.mockReset() - mocks.refresh.mockResolvedValue(undefined) - mocks.closeWriter.mockResolvedValue(true) - const child = fakeChild() - const first = Promise.withResolvers>() - const next = vi - .fn<() => Promise>>>() - .mockImplementationOnce(async () => ({ value: await first.promise, done: false })) - .mockResolvedValueOnce({ value: { type: 'second' }, done: false }) - .mockResolvedValue({ value: undefined, done: true }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This injected query exercises only the async iterator used by the connection. - const queryImpl = ((params: Parameters[0]) => { - params.options?.spawnClaudeCodeProcess?.({ - command: 'claude', - args: [], - env: {}, - signal: new AbortController().signal - }) - return { - [Symbol.asyncIterator]: () => ({ next }) - } - }) as unknown as typeof query - const seen: string[] = [] - let connection: Awaited> - connection = await openClaudeStreamJsonConnection( - { pathToClaudeCodeExecutable: 'claude', options: {}, cwd: '/work/repo' }, - { - onMessage: (message) => { - seen.push(String(message.type)) - if (message.type === 'first') { - connection.pauseReading?.() - } - } - }, - () => child, - queryImpl - ) - - first.resolve({ type: 'first' }) - await vi.waitFor(() => expect(seen).toEqual(['first'])) - await new Promise((resolve) => setImmediate(resolve)) - expect(next).toHaveBeenCalledOnce() - - connection.resumeReading?.() - await vi.waitFor(() => expect(seen).toEqual(['first', 'second'])) - expect(next).toHaveBeenCalledTimes(3) - await expect(connection.close()).resolves.toBe(true) - }) - - it('releases a pulled frame when provider exit is reported', async () => { - mocks.refresh.mockReset() - mocks.closeWriter.mockReset() - mocks.refresh.mockResolvedValue(undefined) - mocks.closeWriter.mockResolvedValue(true) - const child = fakeChild() - const first = Promise.withResolvers>() - const next = vi - .fn<() => Promise>>>() - .mockImplementationOnce(async () => ({ value: await first.promise, done: false })) - .mockResolvedValue({ value: undefined, done: true }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This injected query exercises only the async iterator used by the connection. - const queryImpl = ((params: Parameters[0]) => { - params.options?.spawnClaudeCodeProcess?.({ - command: 'claude', - args: [], - env: {}, - signal: new AbortController().signal - }) - return { - [Symbol.asyncIterator]: () => ({ next }) - } - }) as unknown as typeof query - const events: string[] = [] - const connection = await openClaudeStreamJsonConnection( - { pathToClaudeCodeExecutable: 'claude', options: {}, cwd: '/work/repo' }, - { - onMessage: (message) => events.push(`message:${String(message.type)}`), - onExit: () => events.push('exit') - }, - () => child, - queryImpl - ) - - connection.pauseReading?.() - first.resolve({ type: 'task_notification' }) - await vi.waitFor(() => expect(next).toHaveBeenCalledOnce()) - expect(events).toEqual([]) - - child.emit('exit', 1, null) - await vi.waitFor(() => expect(events).toEqual(['exit', 'message:task_notification'])) - await expect(connection.close()).resolves.toBe(true) - }) - - // Inherited pipes must not keep sends and Stops waiting after proven exit. - it('resolves a proven close though the output never ends', async () => { - mocks.refresh.mockReset() - mocks.closeWriter.mockReset() - mocks.refresh.mockResolvedValue(undefined) - mocks.closeWriter.mockResolvedValue(true) - const child = fakeChild() - const next = vi.fn(() => new Promise>>(() => {})) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This injected query exercises only the async iterator used by the connection. - const queryImpl = ((params: Parameters[0]) => { - params.options?.spawnClaudeCodeProcess?.({ - command: 'claude', - args: [], - env: {}, - signal: new AbortController().signal - }) - return { - [Symbol.asyncIterator]: () => ({ next }) - } - }) as unknown as typeof query - const connection = await openClaudeStreamJsonConnection( - { pathToClaudeCodeExecutable: 'claude', options: {}, cwd: '/work/repo' }, - {}, - () => child, - queryImpl - ) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.useFakeTimers() - try { - let closed: boolean | undefined - void connection.close().then((value) => { - closed = value - }) - await vi.advanceTimersByTimeAsync(CLAUDE_READER_DRAIN_AFTER_EXIT_MS - 1) - expect(closed).toBeUndefined() - await vi.advanceTimersByTimeAsync(1) - expect(closed).toBe(true) - expect(warn).toHaveBeenCalledWith( - '[claude-stream-json] output still open after the proven exit:', - expect.anything() - ) - } finally { - vi.useRealTimers() - warn.mockRestore() - } - }) -}) diff --git a/src/main/claude/claude-stream-json-connection.test.ts b/src/main/claude/claude-stream-json-connection.test.ts deleted file mode 100644 index d3f7443d0ad..00000000000 --- a/src/main/claude/claude-stream-json-connection.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { execFileSync, type ChildProcess } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { spawnProcess } from '@orca/process-host' -import type { ProcessSpec } from '@orca/process-host/process-spec' - -import { - openClaudeStreamJsonConnection, - type ClaudeStreamJsonConnection, - type ClaudeStreamJsonLaunch -} from './claude-stream-json-connection' -import { CLAUDE_STRUCTURED_BASE_OPTIONS } from './structured/launch/claude-structured-launch-resolution' - -// Exercise the real SDK against a scripted child CLI. -const FAKE_CLI = join(__dirname, '__fixtures__', 'claude-agent-sdk-scripted-cli.mjs') -const SESSION_ID = '5348c19f-6a54-4c2e-9c68-9c2b1a3d4e5f' -const HOLD_OPEN = { delayMs: 10_000 } - -type ScriptedCliReport = { - argv: string[] - controlRequests: { request_id: string; request: { subtype: string } }[] - controlResponses: { response: { request_id: string; response?: unknown } }[] - userMessages: Record[] - descendantPid: number | null -} - -const scratchDirs: string[] = [] -const openConnections: ClaudeStreamJsonConnection[] = [] -const childClosures: Promise[] = [] - -afterEach(async () => { - for (const connection of openConnections.splice(0)) { - await connection.close() - } - await Promise.all(childClosures.splice(0)) - for (const dir of scratchDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }) - } - spawned.splice(0) - spawnedChildren.splice(0) - vi.unstubAllEnvs() -}) - -function scriptScenario( - steps: Record[], - controlResponses: Record = {} -) { - const dir = mkdtempSync(join(tmpdir(), 'claude-sdk-connection-')) - scratchDirs.push(dir) - const scenarioPath = join(dir, 'scenario.json') - const reportPath = join(dir, 'report.json') - writeFileSync(scenarioPath, JSON.stringify({ steps, controlResponses })) - return { - cwd: dir, - env: { - PATH: process.env.PATH ?? '', - ORCA_SDK_CONTRACT_SCENARIO_PATH: scenarioPath, - ORCA_SDK_CONTRACT_REPORT_PATH: reportPath - }, - readReport: () => JSON.parse(readFileSync(reportPath, 'utf8')) as ScriptedCliReport - } -} - -function launchFor( - scenario: { cwd: string; env: Record }, - env: Record = {} -): ClaudeStreamJsonLaunch { - return { - pathToClaudeCodeExecutable: FAKE_CLI, - options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, sessionId: SESSION_ID }, - cwd: scenario.cwd, - env: { ...scenario.env, ...env } - } -} - -const spawned: ProcessSpec[] = [] -const spawnedChildren: ChildProcess[] = [] - -async function open( - launch: ClaudeStreamJsonLaunch, - handlers: Parameters[1] = {} -): Promise { - const connection = await openClaudeStreamJsonConnection(launch, handlers, (spec) => { - spawned.push(spec) - const child = spawnProcess(spec) - spawnedChildren.push(child) - childClosures.push(new Promise((resolve) => child.once('close', () => resolve()))) - return child - }) - openConnections.push(connection) - return connection -} - -async function until(read: () => T | null | undefined, label: string): Promise { - for (let attempt = 0; attempt < 400; attempt++) { - const value = read() - if (value !== null && value !== undefined) { - return value - } - await new Promise((resolve) => setTimeout(resolve, 25)) - } - throw new Error(`timed out waiting for ${label}`) -} - -function readReportSafely(scenario: { readReport: () => ScriptedCliReport }) { - try { - return scenario.readReport() - } catch { - return null - } -} - -function processState(pid: number): 'running' | 'exited' { - try { - const state = execFileSync('ps', ['-o', 'state=', '-p', String(pid)], { - encoding: 'utf8', - env: { ...process.env, LANG: 'C', LC_ALL: 'C' } - }).trim() - return state.startsWith('Z') ? 'exited' : 'running' - } catch (error) { - if ((error as { status?: number }).status === 1) { - return 'exited' - } - throw error - } -} - -describe('Claude stream-json connection', () => { - it('completes task Stop through the real SDK while semantic reading is paused', async () => { - const scenario = scriptScenario([HOLD_OPEN]) - const connection = await open(launchFor(scenario)) - await connection.initializationResult() - connection.pauseReading?.() - await connection.stopTask('owned-shell') - expect(scenario.readReport().controlRequests).toContainEqual( - expect.objectContaining({ - request: expect.objectContaining({ subtype: 'stop_task', task_id: 'owned-shell' }) - }) - ) - connection.resumeReading?.() - }) - - it.runIf(process.platform !== 'win32')( - 'proves a natural SDK exit and cleans up its descendant before recovery', - async () => { - const scenario = scriptScenario([ - { stderr: 'claude: natural exit\n' }, - { delayMs: 500 }, - { exit: 1 } - ]) - let exit: Error | null = null - const connection = await open( - { - ...launchFor(scenario), - env: { ...launchFor(scenario).env, ORCA_SDK_CONTRACT_DESCENDANT: '1' } - }, - { onExit: (error) => (exit = error) } - ) - const report = await until(() => { - const current = readReportSafely(scenario) - return current?.descendantPid ? current : null - }, 'the descendant report') - await until(() => exit, 'the natural exit error') - try { - await expect(connection.close()).resolves.toBe(true) - expect(connection.exitVerdict).toEqual({ root: 'exited', tree: 'exited' }) - expect(processState(report.descendantPid as number)).toBe('exited') - } finally { - try { - process.kill(report.descendantPid as number, 'SIGKILL') - } catch { - // Already gone. - } - } - }, - 20_000 - ) -}) diff --git a/src/main/claude/claude-stream-json-connection.ts b/src/main/claude/claude-stream-json-connection.ts index ae39fdfb007..492b021361e 100644 --- a/src/main/claude/claude-stream-json-connection.ts +++ b/src/main/claude/claude-stream-json-connection.ts @@ -1,34 +1,31 @@ import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' -import { claudeStartupAnswerObservation } from './claude-startup-answer-observation' +import { claudeStartupAnswerObservation } from './child-process/claude-startup-answer-observation' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type * as ClaudeAgentSdk from '@anthropic-ai/claude-agent-sdk' import type { CanUseTool, OnUserDialog, SDKUserMessage } from '@anthropic-ai/claude-agent-sdk' import { spawnProcess } from '@orca/process-host' -import { buildClaudeChildProcessEnv } from './claude-child-process-environment' -import { withoutInheritedClaudeConfigDir } from './claude-config-dir-pin' -import { withoutRejectedClaudeApiKey } from './claude-rejected-api-key' +import { buildClaudeChildProcessEnv } from './child-process/claude-child-process-environment' +import { withoutInheritedClaudeConfigDir } from './structured/launch/claude-config-dir-pin' +import { withoutRejectedClaudeApiKey } from './configuration/claude-rejected-api-key' import { - ClaudeControlRequestError, createClaudeControlSurface, type ClaudeControlSurface -} from './claude-agent-sdk-control-requests' -import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof' +} from './sdk-transport/claude-agent-sdk-control-requests' +import { createClaudeChildTreeReaper } from './child-process/claude-agent-sdk-exit-proof' import { withTimeout } from '../../shared/promise-timeout-fallback' import type { DescendantTreeVerdict } from '../pty/process-retirement/pty-descendant-exit-verification' -import { claudeChildCloseProven } from './claude-child-exit-proof-ladder' -import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn' +import { claudeChildCloseProven } from './child-process/claude-child-exit-proof-ladder' +import { createClaudeCodeProcessSpawn } from './child-process/claude-agent-sdk-process-spawn' import { claudeUnwrittenUserMessageError, createClaudeUserMessageQueue -} from './claude-agent-sdk-user-message-queue' +} from './sdk-transport/claude-agent-sdk-user-message-queue' import type { ClaudeStructuredSdkOptions } from './structured/launch/claude-structured-launch-resolution' import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing' -import { claudeStreamJsonExitError } from './claude-stream-json-exit-error' +import { claudeStreamJsonExitError } from './sdk-transport/claude-stream-json-exit-error' import { withObservedProviderExit } from '../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' import type { ProviderProcessCloseOptions } from '../provider-process/provider-process-close' -export { ClaudeControlRequestError } - /** Bound output draining after proven exit so inherited pipes cannot hold close open. */ export const CLAUDE_READER_DRAIN_AFTER_EXIT_MS = 2_000 diff --git a/src/main/claude/claude-streamed-text-checkpoints.test.ts b/src/main/claude/claude-streamed-text-checkpoints.test.ts deleted file mode 100644 index 0f532403a63..00000000000 --- a/src/main/claude/claude-streamed-text-checkpoints.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { StructuredAgentSessionAppendOptions } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeStreamedTextCheckpoints } from './claude-streamed-text-checkpoints' -import type { - ClaudeSubagentLinkageSource, - ClaudeSubagentLinkageVerdict -} from './claude-subagent-linkage' - -function identityOf(uuid: string): AgentJournalItemIdentity { - return { provider: 'claude', sessionId: 'claude-session', uuid } -} - -/** Scopeless blocks are root-owned and must never consult the child resolver. */ -const unconsultedProducer: ClaudeSubagentLinkageSource = { - linkageFor: () => { - throw new Error('resolver consulted for a block with no scope') - }, - settledLinkageFor: () => { - throw new Error('resolver consulted for a block with no scope') - } -} - -const CHILD_LINKAGE: AgentJournalProducerLinkage = { - agentId: 'task-1', - providerParentRef: 'toolu_1', - producerKind: 'agent' -} - -/** Resolve announcements mid-stream; use the raw reference if no announcement arrives. */ -function scriptedProducer() { - let verdict: ClaudeSubagentLinkageVerdict = { kind: 'pending' } - const settledFallback: Extract = { - kind: 'linked', - linkage: { agentId: 'toolu_1', providerParentRef: 'toolu_1', producerKind: 'agent' } - } - return { - source: { - linkageFor: () => verdict, - settledLinkageFor: () => (verdict.kind === 'pending' ? settledFallback : verdict) - } satisfies ClaudeSubagentLinkageSource, - resolve: (linkage: AgentJournalProducerLinkage) => { - verdict = { kind: 'linked', linkage } - } - } -} - -function checkpoints(producer: ClaudeSubagentLinkageSource = unconsultedProducer) { - const rows: { uuid: string; text: string }[] = [] - const stamps: StructuredAgentSessionAppendOptions[] = [] - let scheduled: (() => void) | null = null - const store = createClaudeStreamedTextCheckpoints({ - producer, - persist: (identity, text, options) => { - rows.push({ uuid: 'uuid' in identity ? identity.uuid : '', text }) - stamps.push(options) - }, - schedule: (run) => { - scheduled = run - return () => { - scheduled = null - } - } - }) - return { - store, - rows, - stamps, - runWindow: () => { - const run = scheduled as (() => void) | null - run?.() - } - } -} - -describe('claude streamed text checkpoints', () => { - it('rewrites a block row with the full text accumulated so far', () => { - const { store, rows, runWindow } = checkpoints() - - store.append(identityOf('block-1'), 'hel') - store.append(identityOf('block-1'), 'lo') - runWindow() - - expect(rows).toEqual([{ uuid: 'block-1', text: 'hello' }]) - expect(store.pending).toBe(1) - }) - - it('drops every block still awaiting its final frame at settlement', () => { - const { store, rows, runWindow } = checkpoints() - - store.append(identityOf('block-1'), 'partial answer') - runWindow() - store.settle() - - expect(store.pending).toBe(0) - store.flush() - expect(rows).toEqual([{ uuid: 'block-1', text: 'partial answer' }]) - }) - - it('writes a checkpoint at once while the producing agent is provisional', () => { - const producer = scriptedProducer() - const { store, rows, stamps, runWindow } = checkpoints(producer.source) - - store.append(identityOf('block-1'), 'partial', 'toolu_1') - runWindow() - expect(rows).toEqual([{ uuid: 'block-1', text: 'partial' }]) - expect(stamps.at(-1)).toMatchObject({ agentId: 'toolu_1' }) - - // Flush advances text; reattribute corrects linkage even when text is unchanged. - producer.resolve(CHILD_LINKAGE) - store.flush() - expect(stamps.at(-1)).toMatchObject({ agentId: 'toolu_1' }) - - store.reattribute() - - expect(rows.at(-1)).toEqual({ uuid: 'block-1', text: 'partial' }) - expect(stamps.at(-1)).toEqual(CHILD_LINKAGE) - }) - - it('stops persisting once disposed', () => { - const { store, rows, runWindow } = checkpoints() - - store.append(identityOf('block-1'), 'text') - store.dispose() - runWindow() - store.flush() - - expect(rows).toEqual([]) - expect(store.pending).toBe(0) - }) -}) diff --git a/src/main/claude/claude-structured-result-control-overlap.test.ts b/src/main/claude/claude-structured-result-control-overlap.test.ts deleted file mode 100644 index aceb32b543a..00000000000 --- a/src/main/claude/claude-structured-result-control-overlap.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { ClaudeControlRequestTimeoutError } from './claude-agent-sdk-control-requests' -import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state' -import { - acquired, - claudeFrame, - fakeClaude, - tick, - USER_MESSAGE -} from './structured/claude-structured-session-test-support' - -it.each(['before-settlement', 'after-settlement'])( - 'retires result settings begun during an uncertain control: %s', - async (release) => { - const control = Promise.withResolvers() - const report = Promise.withResolvers() - const events: ClaudeStructuredSessionEvent[] = [] - const native = fakeClaude({ routes: { set_model: () => control.promise } }) - const adapter = await acquired(native, {}, events) - const connection = native.connections[0]! - const session = adapter['sessions'].get('session-1')! - const read = () => adapter.readOptions({ sessionId: 'session-1', fence: 7 }) - const finishTurn = () => - claudeFrame(connection, { - type: 'result', - subtype: 'success', - result: 'previous turn completed', - is_error: false - }) - try { - await adapter.setOption({ sessionId: 'session-1', fence: 7, key: 'fastMode', value: 'true' }) - await tick() - await adapter.dispatch({ - sessionId: 'session-1', - fence: 7, - clientMessageId: 'first', - body: USER_MESSAGE - }) - finishTurn() - await tick() - const writing = adapter.dispatch({ - sessionId: 'session-1', - fence: 7, - clientMessageId: 'next', - body: USER_MESSAGE, - executionOptions: { model: 'claude-opus-5' } - }) - await vi.waitFor(() => - expect(connection.calls.some((call) => call.subtype === 'set_model')).toBe(true) - ) - const settings = vi.spyOn(connection, 'getSettings').mockReturnValueOnce(report.promise) - finishTurn() - await vi.waitFor(() => expect(settings).toHaveBeenCalledOnce()) - const stale = { - applied: { model: 'claude-sonnet-5', effort: 'low' }, - effective: { effortLevel: 'low', fastMode: false } - } - if (release === 'before-settlement') { - report.resolve(stale) - await tick() - expect((await read()).current.fastMode).toBe(true) - expect(session.appliedOptions).toBeUndefined() - } - control.reject(new ClaudeControlRequestTimeoutError('set_model')) - expect(await writing).toMatchObject({ state: 'rejected' }) - report.resolve(stale) - await tick() - const current = (await read()).current - expect(current).toMatchObject({ effort: 'high', fastMode: true }) - expect(current.confirmed ?? []).not.toContain('fastMode') - expect(session.appliedOptions).toBeUndefined() - expect(Object.fromEntries(session.appliedInputOptions)).toEqual({}) - expect( - events.some( - (event) => event.type === 'options-reported' && event.reportedOptions.effort === 'low' - ) - ).toBe(false) - - native.routes.set_model = () => undefined - await adapter.setOption({ sessionId: 'session-1', fence: 7, key: 'model', value: 'opus' }) - settings.mockResolvedValueOnce({ - applied: { model: 'claude-opus-5', effort: 'medium' }, - effective: { effortLevel: 'medium', fastMode: true } - }) - finishTurn() - await vi.waitFor(async () => - expect((await read()).current).toMatchObject({ effort: 'medium', fastMode: true }) - ) - expect(session.appliedInputOptions.get('model')).toBe('opus') - expect(session.appliedOptions).toEqual({ model: 'claude-opus-5', effort: 'medium' }) - } finally { - report.resolve(null) - control.resolve() - await adapter.closeSession('session-1') - } - } -) diff --git a/src/main/claude/claude-subagent-permission-request.test.ts b/src/main/claude/claude-subagent-permission-request.test.ts deleted file mode 100644 index 59dd7c9b91e..00000000000 --- a/src/main/claude/claude-subagent-permission-request.test.ts +++ /dev/null @@ -1,398 +0,0 @@ -// Real CLI captures verify waiting children have durable cards and child waits do not alter parent status. - -import { readFileSync } from 'node:fs' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { isDeepStrictEqual } from 'node:util' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { - AgentJournalRenderItem, - AgentJournalResolution -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import type { AgentStatusStructuredSessionSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' -import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { StructuredAgentSessionCurrentWork } from '../native-chat/agent-session-wire/observations/structured-agent-session-current-work' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' -import { indexedStatusFeedSession } from '../native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-test-session' -import { invokeCanUseTool } from './claude-can-use-tool-test-support' -import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state' -import { - fakeClaude, - identityFor, - PROVIDER_SESSION_ID -} from './structured/claude-structured-session-test-support' -import { claudeStartupSettled } from './structured/claude-structured-startup-settled-test-support' - -const SESSION = 'session-1' -const FENCE = 7 - -type Captured = { from: 'cli' | 'orca'; frame: Record } - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function text(value: unknown): string { - return typeof value === 'string' ? value : '' -} - -function captured(name: string): Captured[] { - const path = join(__dirname, '__fixtures__', 'claude-subagent-permission-frames.json') - const parsed: unknown = JSON.parse(readFileSync(path, 'utf8')) - const events = isRecord(parsed) && isRecord(parsed.scenarios) ? parsed.scenarios[name] : null - if (!Array.isArray(events)) { - throw new Error(`no captured scenario ${name}`) - } - return events.flatMap((event) => - isRecord(event) && (event.from === 'cli' || event.from === 'orca') && isRecord(event.frame) - ? [{ from: event.from, frame: event.frame }] - : [] - ) -} - -function askerOf(name: string): string { - return text(captured(name).find((event) => event.frame.subtype === 'task_started')?.frame.task_id) -} - -const ASKER = askerOf('fg-allow') - -function withoutWaits(evidence: AgentChildWorkEvidence[]): AgentChildWorkEvidence[] { - return evidence.map((edge) => - edge.type === 'live' && edge.child.state === 'waiting' - ? { ...edge, child: { ...edge.child, state: 'working' } } - : edge - ) -} - -function parentRow(server: AgentHookServer) { - const row = server.getStatusSnapshot()[0] - return ( - row && { - state: row.state, - workingMode: row.workingMode, - mainAgent: row.mainAgent, - stateStartedAt: row.stateStartedAt - } - ) -} - -function pendingCards(items: readonly AgentJournalRenderItem[]): AgentJournalRenderItem[] { - return items.filter( - (item) => - (item.body.kind === 'approval' || item.body.kind === 'question') && - item.body.resolution.state === 'pending' - ) -} - -const journals = createTrackedJournalOpener() -let root: string -const hooks: { onEvent?: (event: ClaudeStructuredSessionEvent) => void } = {} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-subagent-request-')) -}) - -afterEach(async () => { - hooks.onEvent = undefined - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -type Publish = { waiting: string[]; askers: string[]; row: unknown; unwaited: unknown } - -async function pipeline() { - let clock = 1_700_000_000_000 - const now = () => (clock += 1) - const journal: AgentSessionJournal = await journals.open({ - identity: identityFor(SESSION), - now, - stateDirectory: join(root, SESSION) - }) - const server = new AgentHookServer() - const unwaited = new AgentHookServer() - const publishes: Publish[] = [] - let published: AgentStatusStructuredSessionSubject | undefined - const viewOf = (providerId: string) => - published && - server.getStructuredChildWorkViews(published).find((view) => view.providerId === providerId) - const record = (subject: AgentStatusStructuredSessionSubject): void => { - published = subject - const cards = pendingCards(journal.snapshot().items) - publishes.push({ - waiting: server - .getStructuredChildWorkViews(subject) - .flatMap((view) => - view.state === 'waiting' && view.membership === 'live' ? [view.providerId ?? '?'] : [] - ), - askers: cards.flatMap((card) => (card.agentId ? [card.agentId] : [])), - row: parentRow(server), - unwaited: parentRow(unwaited) - }) - } - const feed = new StructuredAgentSessionStatusFeed({ - logger: createStructuredAgentSessionLogger(), - sessions: new Map([ - [ - SESSION, - indexedStatusFeedSession({ - journal, - child: { generation: 'spawn-9', fence: FENCE, phase: 'ready' }, - provider: 'claude' - }) - ] - ]), - getConversation: () => null, - now, - statusSink: () => ({ - publish: (summary, subject) => { - server.ingestStructuredStatus(summary, subject) - unwaited.ingestStructuredStatus(summary, subject) - record(subject) - }, - forget: (subject) => { - server.dropStructuredStatus(subject) - unwaited.dropStructuredStatus(subject) - }, - publishChildWork: (subject, evidence, provider) => { - server.ingestStructuredChildWork(subject, evidence, provider) - unwaited.ingestStructuredChildWork(subject, withoutWaits(evidence), provider) - }, - readChildWork: (subject) => server.getStructuredChildWorkViews(subject) - }) - }) - // Match host publication on sink publish and deferred journal commits. - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging(SESSION)) - const publishStatus = () => feed.publish(SESSION, journal) - const target = { journal, fence: FENCE, publish: publishStatus } - deferred.bind(target) - let queued = false - journal.observeCommits(() => { - if (!queued) { - queued = true - queueMicrotask(() => { - queued = false - feed.publish(SESSION, journal) - }) - } - }) - const claude = fakeClaude() - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - now, - persistHandle: async () => {}, - onChildWorkEvidence: (sessionId, evidence) => feed.publishChildWork(sessionId, evidence), - onEvent: (event) => hooks.onEvent?.(event) - }) - await adapter.acquire({ - identity: identityFor(SESSION), - fence: FENCE, - spawnToken: 'spawn-9', - events: deferred.sink - }) - await claudeStartupSettled(adapter, SESSION) - const settle = async (): Promise => { - for (let round = 0; round < 3; round += 1) { - expect(await deferred.drained()).toEqual({ ok: true }) - await new Promise((resolve) => setTimeout(resolve, 0)) - } - } - const hostRecords = - (resolution: Pick, itemId = cardId()) => - async (): Promise => { - await deferred.drained() - const card = pendingCards(journal.snapshot().items).find((item) => item.itemId === itemId) - const identity = card && parseAgentJournalItemKey(card.itemId) - if (card?.body.kind !== 'approval' || !identity) { - throw new Error('no pending card to record') - } - await journal.appendItem( - identity, - { ...card.body, resolution: { ...resolution, resolvedBy: 'client-1', resolvedAt: now() } }, - { - fence: FENCE, - turnScope: new StructuredAgentSessionCurrentWork(journal, FENCE).turnScope() - } - ) - } - const cardId = (): string => { - const card = pendingCards(journal.snapshot().items)[0] - if (!card) { - throw new Error('no pending card') - } - return card.itemId - } - const connection = claude.connections[0]! - const aborts = new Map() - const step = async ( - { from, frame }: Captured, - options: { withoutAgentId?: boolean } = {} - ): Promise => { - const request = isRecord(frame.request) ? frame.request : null - if (frame.type === 'control_request' && request?.subtype === 'can_use_tool') { - const controller = new AbortController() - aborts.set(text(frame.request_id), controller) - const agentId = options.withoutAgentId ? '' : text(request.agent_id) - invokeCanUseTool( - connection, - text(request.tool_name), - text(frame.request_id), - text(request.tool_use_id), - { - input: isRecord(request.input) ? request.input : {}, - signal: controller.signal, - ...(agentId ? { agentID: agentId } : {}) - } - ) - } else if (from === 'cli') { - connection.handlers.onMessage?.({ ...frame, session_id: PROVIDER_SESSION_ID }) - } - await settle() - } - const ask = async (name: string, options: { withoutAgentId?: boolean } = {}): Promise => { - const events = captured(name) - const at = events.findIndex((event) => event.frame.type === 'control_request') - for (const event of events.slice(0, at + 1)) { - await step(event, options) - } - } - const violations = () => - publishes.filter( - (entry) => - entry.waiting.some((id) => !entry.askers.includes(id)) || - !isDeepStrictEqual(entry.row, entry.unwaited) - ) - const raise = (requestId: string, toolUseId: string, agentId?: string): void => { - const controller = new AbortController() - aborts.set(requestId, controller) - invokeCanUseTool(connection, 'Bash', requestId, toolUseId, { - input: { command: `echo ${requestId}` }, - signal: controller.signal, - ...(agentId ? { agentID: agentId } : {}) - }) - } - return { - adapter, - journal, - deferred, - target, - publishStatus, - connection, - now, - raise, - publishes, - violations, - viewOf, - settle, - step, - ask, - cardId, - hostRecords, - aborts - } -} - -type Pipeline = Awaited> - -function answer( - run: Pipeline, - optionId: 'allow' | 'deny', - commit = run.hostRecords({ state: 'resolved', selectedOptionId: optionId }), - itemId = run.cardId() -) { - return run.adapter.answerPrompt({ - sessionId: SESSION, - itemId, - kind: 'approval', - response: { kind: 'option', optionId }, - fence: FENCE, - commit - }) -} - -describe("a Claude subagent's permission request", () => { - it('waits only once its card is written, though the write waits for the journal', async () => { - const run = await pipeline() - const events = captured('fg-allow') - const at = events.findIndex((event) => event.frame.type === 'control_request') - for (const event of events.slice(0, at)) { - await run.step(event) - } - run.deferred.unbind() - run.raise('req-late', 'toolu_late', ASKER) - await new Promise((resolve) => setTimeout(resolve, 0)) - run.publishStatus() - expect(run.publishes.at(-1)?.waiting).toEqual([]) - run.deferred.bind(run.target) - await run.settle() - expect(run.publishes.at(-1)?.waiting).toEqual([ASKER]) - expect(run.violations()).toEqual([]) - }) - - it('waits again, beside its card, when the host fails to record the answer', async () => { - const run = await pipeline() - await run.ask('fg-allow') - await expect( - answer(run, 'allow', async () => { - throw new Error('journal write failed') - }) - ).rejects.toThrow('journal write failed') - await run.settle() - expect(run.publishes.at(-1)?.waiting).toEqual([ASKER]) - expect(run.violations()).toEqual([]) - }) - - it('waits each asking subagent beside its own card, and only those', async () => { - const run = await pipeline() - await run.ask('fg-allow') - const started = captured('fg-allow').find((event) => event.frame.subtype === 'task_started') - await run.step({ - from: 'cli', - frame: { ...started?.frame, task_id: 'agent-two', uuid: 'u-two', tool_use_id: 'toolu_two' } - }) - run.raise('req-two', 'toolu_two_bash', 'agent-two') - await run.settle() - expect([...(run.publishes.at(-1)?.waiting ?? [])].sort()).toEqual([ASKER, 'agent-two'].sort()) - const cardOf = (agentId: string) => - pendingCards(run.journal.snapshot().items).find((card) => card.agentId === agentId)?.itemId - const first = cardOf(ASKER) - await answer( - run, - 'allow', - run.hostRecords({ state: 'resolved', selectedOptionId: 'allow' }, first), - first - ) - await run.settle() - expect(run.publishes.at(-1)?.waiting).toEqual(['agent-two']) - const second = cardOf('agent-two') - await answer( - run, - 'allow', - run.hostRecords({ state: 'resolved', selectedOptionId: 'allow' }, second), - second - ) - await run.settle() - expect(run.publishes.at(-1)?.waiting).toEqual([]) - expect(run.violations()).toEqual([]) - }) -}) diff --git a/src/main/claude/claude-subagent-resume-after-restart.test.ts b/src/main/claude/claude-subagent-resume-after-restart.test.ts deleted file mode 100644 index 049cc308d76..00000000000 --- a/src/main/claude/claude-subagent-resume-after-restart.test.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture' -import { blockOf } from './claude-background-task-row-test-support' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -// Captured restart order: resumed frames retain original spawn IDs while announcements name new resume calls. - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-subagent-restart-')) -}) - -afterEach(async () => { - vi.useRealTimers() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -function frame(message: Record, startsTurn = false) { - return { - type: 'message' as const, - sessionId: 'orca-session', - ...(startsTurn ? { startsTurn: true as const } : {}), - message: { session_id: 'claude-session', parent_tool_use_id: null, ...message } - } -} - -const userTurn = (uuid: string) => - frame( - { type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text: 'go' }] } }, - true - ) - -const toolCall = (uuid: string, id: string, name: string, input: Record) => - frame({ - type: 'assistant', - uuid, - message: { role: 'assistant', content: [{ type: 'tool_use', id, name, input }] } - }) - -const toolResult = (uuid: string, toolUseId: string, content: string) => - frame({ - type: 'user', - uuid, - message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseId, content }] } - }) - -const taskStarted = (taskId: string, toolUseId: string, description: string) => - frame({ - type: 'system', - subtype: 'task_started', - uuid: `started-${toolUseId}`, - task_id: taskId, - tool_use_id: toolUseId, - description, - subagent_type: 'general-purpose', - is_backgrounded: true, - task_type: 'local_agent' - }) - -const taskFailed = (taskId: string, toolUseId: string) => - frame({ - type: 'system', - subtype: 'task_notification', - uuid: `failed-${taskId}`, - task_id: taskId, - tool_use_id: toolUseId, - status: 'failed' - }) - -const childSays = (uuid: string, parentToolUseId: string, text: string) => - frame({ - type: 'assistant', - uuid, - parent_tool_use_id: parentToolUseId, - message: { role: 'assistant', content: [{ type: 'text', text }] } - }) - -const result = (uuid: string) => - frame({ type: 'result', subtype: 'success', is_error: false, result: 'done', uuid }) - -async function openJournal(): Promise { - return journals.open({ - identity: { - sessionId: 'orca-session', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('claude-session', null) - }, - now: () => 9_000, - stateDirectory: root - }) -} - -function acquire(journal: AgentSessionJournal, delayed = false) { - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) - const bind = () => deferred.bind({ journal, fence: 1, publish: () => {} }) - if (!delayed) { - bind() - } - const settle = async (): Promise => { - await expect(deferred.drained()).resolves.toEqual({ ok: true }) - } - const exit = async (): Promise => { - translator.handle({ type: 'ended', sessionId: 'orca-session', reason: 'closed' }) - await settle() - translator.dispose() - deferred.close() - } - return { translator, settle, exit, bind } -} - -const proseRow = (journal: AgentSessionJournal, text: string): AgentJournalRenderItem | undefined => - journal - .snapshot() - .items.find( - (item) => - item.body.kind === 'message' && - item.body.blocks.some((block) => block.type === 'text' && block.text === text) - ) - -describe('a Claude subagent resumed after its provider restarted', () => { - it.each(['terminal-only', 'roster-first', 'unbound-roster-first', 'parent-omitting-roster'])( - 'retains one owned shell across close/reopen: %s', - async (order) => { - let journal = await openJournal() - const first = acquire(journal) - first.translator.handle(userTurn('parent-task-turn')) - // Contract: a parentless admission can learn ownership from a later roster without a body change. - first.translator.handle( - frame({ ...PARENT_TASK_STOP[3]!.frame, parent_task_id: undefined, tool_use_id: undefined }) - ) - await first.settle() - const beforeOwnership = journal - .snapshot() - .items.find((item) => blockOf(item.body)?.taskId === 'shell-child') - expect(beforeOwnership?.agentId).toBeUndefined() - first.translator.handle(frame(PARENT_TASK_STOP[2]!.frame)) - await first.settle() - expect(journal.item(beforeOwnership!.itemId)).toMatchObject({ - agentId: 'shell-child', - parentAgentId: 'agent-parent' - }) - first.translator.handle(frame(PARENT_TASK_STOP[3]!.frame)) - await first.settle() - const shell = journal - .snapshot() - .items.find((item) => blockOf(item.body)?.taskId === 'shell-child') - expect(shell).toMatchObject({ - agentId: 'shell-child', - parentAgentId: 'agent-parent', - producerKind: 'background', - providerParentRef: 'toolu_shell' - }) - await first.exit() - expect(blockOf(journal.item(shell!.itemId)?.body)?.state).toBe('unverifiable') - await journals.closeAll() - - journal = await openJournal() - const delayed = order === 'unbound-roster-first' - const resumed = acquire(journal, delayed) - if (!delayed) { - expect(resumed.translator.childTaskParent?.('shell-child')).toBe('agent-parent') - } - if (order === 'parent-omitting-roster') { - resumed.translator.handle( - frame({ - type: 'system', - subtype: 'background_tasks_changed', - tasks: [{ task_id: 'shell-child', task_type: 'local_bash' }] - }) - ) - await resumed.settle() - expect(journal.item(shell!.itemId)).toMatchObject({ parentAgentId: 'agent-parent' }) - expect(blockOf(journal.item(shell!.itemId)?.body)?.state).toBe('working') - } else if (order !== 'terminal-only') { - resumed.translator.handle(frame(PARENT_TASK_STOP[2]!.frame)) - resumed.translator.handle(frame(PARENT_TASK_STOP[3]!.frame)) - } - if (delayed) { - resumed.bind() - } - // Contract: a terminal revision must retain saved ownership even without a repeated start. - resumed.translator.handle(frame(PARENT_TASK_STOP[8]!.frame)) - await resumed.settle() - const shells = journal - .snapshot() - .items.filter((item) => blockOf(item.body)?.taskId === 'shell-child') - expect(shells).toHaveLength(1) - expect(shells[0]).toMatchObject({ - itemId: shell!.itemId, - agentId: 'shell-child', - parentAgentId: 'agent-parent', - producerKind: 'background', - providerParentRef: 'toolu_shell' - }) - expect(blockOf(shells[0]?.body)?.state).toBe('idle') - await resumed.exit() - } - ) - - it('keeps the canonical id its first run was given, so one child stays one child', async () => { - const journal = await openJournal() - - const first = acquire(journal) - first.translator.handle(userTurn('turn-a')) - first.translator.handle( - toolCall('spawn-a', 'toolu_spawn_a', 'Agent', { - description: 'Follow-up A', - run_in_background: true - }) - ) - first.translator.handle(taskStarted('agent-a', 'toolu_spawn_a', 'Follow-up A')) - first.translator.handle(toolResult('spawned-a', 'toolu_spawn_a', 'Async agent launched.')) - first.translator.handle(childSays('a-1', 'toolu_spawn_a', 'A reads the rig recipes')) - first.translator.handle( - toolCall('spawn-b', 'toolu_spawn_b', 'Agent', { - description: 'Follow-up B', - run_in_background: true - }) - ) - first.translator.handle(taskStarted('agent-b', 'toolu_spawn_b', 'Follow-up B')) - first.translator.handle(toolResult('spawned-b', 'toolu_spawn_b', 'Async agent launched.')) - first.translator.handle(childSays('b-1', 'toolu_spawn_b', 'B inspects the worktree')) - first.translator.handle(taskFailed('agent-b', 'toolu_spawn_b')) - first.translator.handle(taskFailed('agent-a', 'toolu_spawn_a')) - first.translator.handle(result('result-a')) - await first.exit() - expect(proseRow(journal, 'A reads the rig recipes')).toMatchObject({ agentId: 'agent-a' }) - - const second = acquire(journal) - second.translator.handle(userTurn('turn-b')) - second.translator.handle( - toolCall('resume-a', 'toolu_message_a', 'SendMessage', { to: 'agent-a', message: 'go on' }) - ) - second.translator.handle(taskStarted('agent-a', 'toolu_message_a', 'Follow-up A')) - second.translator.handle(toolResult('resumed-a', 'toolu_message_a', '{"success":true}')) - second.translator.handle( - toolCall('resume-b', 'toolu_message_b', 'SendMessage', { to: 'agent-b', message: 'go on' }) - ) - second.translator.handle(taskStarted('agent-b', 'toolu_message_b', 'Follow-up B')) - second.translator.handle(toolResult('resumed-b', 'toolu_message_b', '{"success":true}')) - // Preserve captured interleaving to catch cross-child identity swaps. - second.translator.handle(childSays('a-2', 'toolu_spawn_a', 'A restarts the receiver')) - second.translator.handle(childSays('b-2', 'toolu_spawn_b', 'B checks the rig')) - await second.settle() - - expect(proseRow(journal, 'A restarts the receiver')).toMatchObject({ - agentId: 'agent-a', - providerParentRef: 'toolu_spawn_a', - producerKind: 'agent' - }) - expect(proseRow(journal, 'B checks the rig')).toMatchObject({ - agentId: 'agent-b', - providerParentRef: 'toolu_spawn_b' - }) - expect(proseRow(journal, 'A reads the rig recipes')?.attempt).toBeUndefined() - expect(proseRow(journal, 'A restarts the receiver')?.attempt).toBe(2) - expect(proseRow(journal, 'B checks the rig')?.attempt).toBe(2) - await second.exit() - }) -}) diff --git a/src/main/claude/claude-supervised-stop-real-cli.test.ts b/src/main/claude/claude-supervised-stop-real-cli.test.ts deleted file mode 100644 index e64788518a2..00000000000 --- a/src/main/claude/claude-supervised-stop-real-cli.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { randomUUID } from 'node:crypto' -import { afterEach, describe, expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' -import { resolveSessionFilePath } from '../native-chat/session-file-resolver' -import { SUPERVISED_GRACEFUL_EXIT_MS } from './claude-child-exit-proof-ladder' -import { claudeConfigDirEnvPatch } from './claude-config-dir-pin' -import { realClaudeLaunchHome } from './claude-real-cli-availability-test-support' -import { - openClaudeStreamJsonConnection, - type ClaudeStreamJsonConnection -} from './claude-stream-json-connection' -import { - CLAUDE_STRUCTURED_BASE_OPTIONS, - claudeStructuredPermissionOptions -} from './structured/launch/claude-structured-launch-resolution' - -// Opt-in spends real turns; ORCA_REAL_CLAUDE_SETTINGS supports auth outside the Claude home. -const CLAUDE_BIN = process.env.ORCA_REAL_CLAUDE_BIN ?? '' -const enabled = - process.env.ORCA_REAL_CLAUDE_SUPERVISED_STOP === '1' && - process.platform !== 'win32' && - CLAUDE_BIN.length > 0 -const FRAMES_OUT = process.env.ORCA_REAL_CLAUDE_FRAMES_OUT -const home = realClaudeLaunchHome() -const TOOL_MARKER = 'orca_supervised_stop_probe' -const TOOL_PROMPT = `Use the Bash tool to run exactly this command, with no timeout argument, and nothing else: python3 -c "import time; time.sleep(120) # ${TOOL_MARKER}"` - -type Frame = { at: number; message: Record } -type Row = { pid: number; ppid: number; command: string } - -const recordedPids = new Set() -const tempDirs: string[] = [] -const connections: ClaudeStreamJsonConnection[] = [] - -function alive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch (error) { - return !(error instanceof Error && 'code' in error && error.code === 'ESRCH') - } -} - -async function processTable(): Promise { - const result = await runProcess({ program: 'ps', args: ['-axo', 'pid=,ppid=,command='] }) - return result.stdout.split('\n').flatMap((line) => { - const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line) - return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }] : [] - }) -} - -async function descendantsOf(rootPid: number): Promise { - const rows = await processTable() - const found: Row[] = [] - const frontier = [rootPid] - while (frontier.length > 0) { - const parent = frontier.pop() - for (const row of rows.filter((candidate) => candidate.ppid === parent)) { - found.push(row) - frontier.push(row.pid) - } - } - return found -} - -async function until(read: () => Promise | T | null, what: string, ms = 90_000) { - const deadline = Date.now() + ms - for (;;) { - const value = await read() - if (value !== null) { - return value - } - if (Date.now() >= deadline) { - throw new Error(`timed out waiting for ${what}`) - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } -} - -async function open(sessionId: string, cwd: string, resume: boolean, frames: Frame[]) { - const settings = process.env.ORCA_REAL_CLAUDE_SETTINGS - const permission = claudeStructuredPermissionOptions('full-access') - const connection = await openClaudeStreamJsonConnection( - { - pathToClaudeCodeExecutable: CLAUDE_BIN, - options: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS, - model: 'haiku', - extraArgs: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS.extraArgs, - ...permission.extraArgs, - ...(settings ? { settings } : {}) - }, - ...(resume ? { resume: sessionId } : { sessionId }) - }, - cwd, - env: { ...home.env, ...claudeConfigDirEnvPatch(home.claudeConfigDir, { env: home.env }) } - }, - { onMessage: (message) => frames.push({ at: Date.now(), message }) } - ) - connections.push(connection) - recordedPids.add(connection.pid!) - return connection -} - -function userMessage(text: string): Record { - return { - type: 'user', - message: { role: 'user', content: [{ type: 'text', text }] }, - parent_tool_use_id: null, - session_id: '' - } -} - -async function transcriptLines(sessionId: string): Promise { - const path = await until( - () => - resolveSessionFilePath('claude', sessionId, { - claudeProjectsDir: join(home.claudeConfigDir, 'projects') - }), - 'the transcript', - 15_000 - ) - return readFileSync(path, 'utf8') -} - -function expectLineAtomic(contents: string): void { - expect(contents.length).toBeGreaterThan(0) - expect(contents.endsWith('\n')).toBe(true) - for (const line of contents.split('\n').filter((entry) => entry.trim())) { - expect(() => JSON.parse(line)).not.toThrow() - } -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function summarize(frames: Frame[], since: number): string[] { - return frames - .filter((frame) => frame.at >= since) - .map(({ at, message }) => { - const inner = isRecord(message.message) ? message.message.content : undefined - const blocks = (Array.isArray(inner) ? inner : []) - .filter(isRecord) - .map((block) => - block.type === 'tool_result' - ? `tool_result(is_error=${String(block.is_error)}:${JSON.stringify(block.content).slice(0, 80)})` - : String(block.type) - ) - return `+${at - since}ms ${String(message.type)}/${String(message.subtype ?? '')}${ - message.type === 'result' ? `(is_error=${String(message.is_error)})` : '' - } ${blocks.join(',')}`.trim() - }) -} - -async function resumeAndAsk(sessionId: string, cwd: string): Promise { - const frames: Frame[] = [] - const resumed = await open(sessionId, cwd, true, frames) - await resumed.send(userMessage('In one short line: what command did I ask you to run?')) - const result = await until( - () => frames.find((frame) => frame.message.type === 'result')?.message ?? null, - 'the resumed turn result' - ) - expect(result.subtype).toBe('success') - await expect(resumed.close()).resolves.toBe(true) -} - -type StopCase = 'close mid-tool' | 'SIGTERM to the supervisor mid-tool' | 'close while idle' - -afterEach(async () => { - for (const pid of recordedPids) { - if (alive(pid)) { - process.kill(pid, 'SIGKILL') - } - } - recordedPids.clear() - connections.splice(0) - for (const dir of tempDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -describe.runIf(enabled)('real Claude stopped through the POSIX supervisor', () => { - it.each(['close mid-tool', 'SIGTERM to the supervisor mid-tool', 'close while idle'])( - '%s: stops Claude and its tool, keeps the transcript line-atomic, and resumes', - async (stopCase) => { - const cwd = mkdtempSync(join(tmpdir(), 'orca-real-claude-stop-')) - tempDirs.push(cwd) - const sessionId = randomUUID() - const frames: Frame[] = [] - const connection = await open(sessionId, cwd, false, frames) - const supervisor = connection.pid! - const midTool = stopCase !== 'close while idle' - await connection.send(userMessage(midTool ? TOOL_PROMPT : 'Reply with the single word: ok')) - const descendants = midTool - ? await until(async () => { - const rows = await descendantsOf(supervisor) - return rows.some((row) => row.command.includes(TOOL_MARKER)) ? rows : null - }, 'the Bash tool').catch((error: unknown) => { - console.log('[no tool] frames so far:', summarize(frames, 0)) - throw error - }) - : await until( - async () => - frames.some((frame) => frame.message.type === 'result') - ? await descendantsOf(supervisor) - : null, - 'the idle turn' - ) - for (const row of descendants) { - recordedPids.add(row.pid) - } - - const signalledAt = Date.now() - if (stopCase === 'SIGTERM to the supervisor mid-tool') { - process.kill(supervisor, 'SIGTERM') - } else { - await expect(connection.close()).resolves.toBe(true) - } - const gone = await until( - () => ([supervisor, ...descendants.map((row) => row.pid)].some(alive) ? null : true), - 'the supervisor, Claude and its tools to exit', - SUPERVISED_GRACEFUL_EXIT_MS + 2_000 - ) - const stoppedMs = Date.now() - signalledAt - const after = summarize(frames, signalledAt) - console.log(`[${stopCase}] stopped in ${stoppedMs} ms; frames after the stop:`, after) - if (FRAMES_OUT) { - writeFileSync( - `${FRAMES_OUT}.${stopCase.replaceAll(' ', '-')}.json`, - JSON.stringify({ stoppedMs, after }, null, 2) - ) - } - expect(gone).toBe(true) - - expectLineAtomic(await transcriptLines(sessionId)) - await resumeAndAsk(sessionId, cwd) - expectLineAtomic(await transcriptLines(sessionId)) - }, - 180_000 - ) -}) diff --git a/src/main/claude/claude-supervised-stop.integration.test.ts b/src/main/claude/claude-supervised-stop.integration.test.ts deleted file mode 100644 index 17155f59f56..00000000000 --- a/src/main/claude/claude-supervised-stop.integration.test.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { spawn, type ChildProcess } from 'node:child_process' -import { existsSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import type { SpawnOptions as SdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' -import { spawnProcess } from '@orca/process-host' -import type { ProcessSpec } from '@orca/process-host/process-spec' -import { - PROVIDER_SIGTERM_GRACE_MS, - PROVIDER_STDIN_END_GRACE_MS, - PROVIDER_SUPERVISOR_MAX_STOP_MS -} from '../provider-process/provider-process-supervisor' -import { createClaudeChildTreeReaper, proveClaudeChildExit } from './claude-agent-sdk-exit-proof' -import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn' - -// EOF leaves the turn running; SIGTERM reaps a detached tool but preserves a double-forked daemon. -const FAKE_CLAUDE = String.raw` - const { spawn } = require('node:child_process') - const { writeFileSync } = require('node:fs') - process.stdin.resume() - process.stdout.on('error', () => {}) - const tool = spawn(process.execPath, ['-e', 'setInterval(() => {}, 60000)'], { - detached: true, - stdio: 'ignore' - }) - const forker = spawn( - process.execPath, - ['-e', "const d = require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 60000)'], { detached: true, stdio: 'ignore' }); d.unref(); process.stdout.write(String(d.pid))"], - { stdio: ['ignore', 'pipe', 'ignore'] } - ) - let daemon = '' - forker.stdout.on('data', (chunk) => { daemon += chunk }) - forker.once('exit', () => { - process.stdout.write(JSON.stringify({ claude: process.pid, tool: tool.pid, daemon: Number(daemon) }) + '\n') - }) - process.on('SIGTERM', () => { - if (process.env.ORCA_TEST_CLAUDE_IGNORES_SIGTERM) return - try { process.kill(-tool.pid, 'SIGKILL') } catch {} - writeFileSync(process.env.ORCA_TEST_SIGTERM_MARKER, 'reaped') - process.exit(143) - }) - setInterval(() => {}, 60000) -` - -// A killable stand-in for Orca's main launches the production spawn spec. -const OWNER = String.raw` - const { spawn } = require('node:child_process') - const spec = JSON.parse(process.env.ORCA_TEST_SPAWN_SPEC) - const env = { ...spec.env } - if (env.ORCA_PROVIDER_SUPERVISOR_SPEC) { - const supervisor = JSON.parse(Buffer.from(env.ORCA_PROVIDER_SUPERVISOR_SPEC, 'base64').toString()) - supervisor.ownerPid = process.pid - env.ORCA_PROVIDER_SUPERVISOR_SPEC = Buffer.from(JSON.stringify(supervisor)).toString('base64') - } - const child = spawn(spec.program, spec.args, { - cwd: spec.cwd, - env, - detached: spec.detached, - stdio: ['pipe', 'pipe', 'ignore'] - }) - process.stdout.write(JSON.stringify({ root: child.pid }) + '\n') - child.stdout.pipe(process.stdout) - setInterval(() => {}, 60000) -` - -const recordedPids = new Set() -const tempDirs: string[] = [] - -function alive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch (error) { - return !(error instanceof Error && 'code' in error && error.code === 'ESRCH') - } -} - -async function waitFor(predicate: () => boolean, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs - while (!predicate()) { - if (Date.now() >= deadline) { - return false - } - await new Promise((resolve) => setTimeout(resolve, 25)) - } - return true -} - -function readPids(child: ChildProcess, keys: readonly string[]): Promise> { - return new Promise((resolve, reject) => { - const pids: Record = {} - let buffered = '' - const timeout = setTimeout(() => reject(new Error(`no ${keys.join('/')} pids`)), 10_000) - const onData = (chunk: Buffer): void => { - buffered += chunk.toString() - const lines = buffered.split('\n') - buffered = lines.pop() ?? '' - for (const line of lines) { - const parsed: unknown = JSON.parse(line) - for (const [key, pid] of Object.entries(parsed ?? {})) { - if (typeof pid === 'number' && pid > 0) { - pids[key] = pid - recordedPids.add(pid) - } - } - } - if (keys.every((key) => key in pids)) { - clearTimeout(timeout) - child.stdout!.off('data', onData) - child.stdout!.resume() - resolve(pids) - } - } - child.stdout!.on('data', onData) - }) -} - -function sdkOptions(env: Record): SdkSpawnOptions { - const dir = mkdtempSync(join(tmpdir(), 'orca-claude-supervised-')) - tempDirs.push(dir) - return { - command: process.execPath, - args: ['-e', FAKE_CLAUDE], - cwd: dir, - env: { - ...process.env, - ORCA_TEST_SIGTERM_MARKER: join(dir, 'sigterm-reap'), - ...env - }, - signal: new AbortController().signal - } -} - -async function spawnClaude(env: Record = {}) { - const spawner = createClaudeCodeProcessSpawn(spawnProcess) - const options = sdkOptions(env) - const child = spawner.spawn(options) - recordedPids.add(child.pid!) - const managed = spawner.managed - if (!managed) { - throw new Error('Claude spawner did not retain its managed child') - } - const exit = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => - managed.onExit(resolve) - ) - const pids = await readPids(child, ['claude', 'tool', 'daemon']) - const close = (): Promise => proveClaudeChildExit({ managed }) - return { child, managed, exit, pids, close, marker: String(options.env.ORCA_TEST_SIGTERM_MARKER) } -} - -afterEach(() => { - for (const pid of recordedPids) { - if (alive(pid)) { - process.kill(pid, 'SIGKILL') - } - } - recordedPids.clear() - for (const dir of tempDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -describe.runIf(process.platform !== 'win32')('Claude under the POSIX provider supervisor', () => { - it('stops a mid-turn Claude on close instead of letting stdin end finish its turn', async () => { - const { child, managed, exit, pids, close, marker } = await spawnClaude() - expect(child.pid).not.toBe(pids.claude) - - const startedAt = Date.now() - await expect(close()).resolves.toBe(true) - expect(managed.lastCloseResult).toEqual({ root: 'exited', tree: 'exited' }) - await expect(close()).resolves.toBe(true) - - expect(Date.now() - startedAt).toBeLessThan(PROVIDER_STDIN_END_GRACE_MS) - expect(existsSync(marker)).toBe(true) - await expect(exit).resolves.toEqual({ code: null, signal: 'SIGTERM', processless: false }) - expect(alive(pids.claude)).toBe(false) - expect(alive(pids.tool)).toBe(false) - }) - - it('lets the supervisor escalate a Claude that ignores SIGTERM, and exits only after it', async () => { - const { managed, exit, pids, close } = await spawnClaude({ - ORCA_TEST_CLAUDE_IGNORES_SIGTERM: '1' - }) - - const startedAt = Date.now() - await expect(close()).resolves.toBe(true) - expect(managed.lastCloseResult).toEqual({ root: 'exited', tree: 'exited' }) - await expect(close()).resolves.toBe(true) - - const elapsed = Date.now() - startedAt - expect(elapsed).toBeGreaterThanOrEqual(PROVIDER_SIGTERM_GRACE_MS) - expect(elapsed).toBeLessThan(PROVIDER_SUPERVISOR_MAX_STOP_MS + 1_000) - await expect(exit).resolves.toEqual({ code: null, signal: 'SIGTERM', processless: false }) - expect(alive(pids.claude)).toBe(false) - }) - - it('forces a Claude that ignores SIGTERM soon after a brief close, with its exit proven', async () => { - const { managed, exit, pids } = await spawnClaude({ ORCA_TEST_CLAUDE_IGNORES_SIGTERM: '1' }) - const tree = createClaudeChildTreeReaper(managed.child, { - site: 'claude-structured-child-close', - exited: () => managed.rootVerdict === 'exited' - }) - - // ast-grep-ignore: test-no-wall-clock -- the brief grace is the behaviour under test - const startedAt = Date.now() - await expect(managed.close(tree, { grace: 'brief' })).resolves.toEqual({ - root: 'exited', - tree: 'exited' - }) - - // ast-grep-ignore: test-no-wall-clock -- the full SIGTERM grace is 3 s; a brief close must not wait it out - expect(Date.now() - startedAt).toBeLessThan(2_500) - await expect(exit).resolves.toEqual({ code: null, signal: 'SIGTERM', processless: false }) - expect(alive(pids.claude)).toBe(false) - expect(alive(pids.tool)).toBe(false) - }) - - it("stops Claude and its tool when Orca's main dies, and leaves a daemon that left its tree alone", async () => { - const specs: ProcessSpec[] = [] - createClaudeCodeProcessSpawn((spec) => { - specs.push(spec) - return spawnProcess({ program: 'true' }) - }).spawn(sdkOptions({})) - const owner = spawn(process.execPath, ['-e', OWNER], { - env: { ...process.env, ORCA_TEST_SPAWN_SPEC: JSON.stringify(specs[0]) }, - stdio: ['ignore', 'pipe', 'ignore'] - }) - recordedPids.add(owner.pid!) - const pids = await readPids(owner, ['root', 'claude', 'tool', 'daemon']) - - owner.kill('SIGKILL') - - expect(await waitFor(() => !alive(pids.claude), PROVIDER_SUPERVISOR_MAX_STOP_MS)).toBe(true) - expect(await waitFor(() => !alive(pids.root), PROVIDER_SUPERVISOR_MAX_STOP_MS)).toBe(true) - // The tool's separate group requires Claude's SIGTERM handler to reap it. - expect(alive(pids.tool)).toBe(false) - // A daemon that left the tree has no proven ownership. - expect(alive(pids.daemon)).toBe(true) - }) -}) diff --git a/src/main/claude/claude-transcript-duration.test.ts b/src/main/claude/claude-transcript-duration.test.ts deleted file mode 100644 index 23b672ad9b3..00000000000 --- a/src/main/claude/claude-transcript-duration.test.ts +++ /dev/null @@ -1,329 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { selectStructuredAgentSettledTurns } from '../../shared/agent-session/view/structured-agent-session-turn-timing' -import { isStructuredRewindTarget } from '../native-chat/agent-session-wire/rewind/structured-rewind-cut' -import { SID, chat, chatTurn } from './claude-transcript-catch-up-test-support' - -// Captured CLI 2.1.308 ancestry: retain source identities, clocks, content and cycle boundaries. -// Only the session and first parent are rebound to the shared disk/journal fixture below. -const capturedDurationRows: Record[] = [ - { - type: 'user', - uuid: '2d5c5bfb-2fb5-4d6e-9ad1-88e68f302f90', - parentUuid: '55b46dc4-c498-4048-a31e-49484f80bf41', - timestamp: '2026-10-22T23:31:49.253Z', - isSidechain: false, - promptSource: 'typed', - message: { - role: 'user', - content: 'Reply exactly CLAUDE-AFTER-RECOVERY HARBOUR-1489 and CLI-REWIND-1552' - } - }, - { - type: 'attachment', - uuid: '600bd4b1-fbb0-4ef5-b9ab-13133119cf9d', - parentUuid: '2d5c5bfb-2fb5-4d6e-9ad1-88e68f302f90', - timestamp: '2026-10-22T23:31:49.253Z', - isSidechain: false, - attachment: { - type: 'environment' - } - }, - { - type: 'attachment', - uuid: 'adb98c53-b869-4fb3-8e69-8a789c44a6ed', - parentUuid: '600bd4b1-fbb0-4ef5-b9ab-13133119cf9d', - timestamp: '2026-10-22T23:31:49.253Z', - isSidechain: false, - attachment: { - type: 'agent_listing_delta' - } - }, - { - type: 'attachment', - uuid: '42c32240-2529-4d45-a2cf-c6d20e7a7495', - parentUuid: 'adb98c53-b869-4fb3-8e69-8a789c44a6ed', - timestamp: '2026-10-22T23:31:49.253Z', - isSidechain: false, - attachment: { - type: 'total_tokens_reminder' - } - }, - { - type: 'assistant', - uuid: 'ab494260-8c70-4383-a859-e726caf272cf', - parentUuid: '42c32240-2529-4d45-a2cf-c6d20e7a7495', - timestamp: '2026-10-22T23:31:51.148Z', - isSidechain: false, - apiBlockIndex: 0, - message: { - id: 'msg_011CgJ9Xf5dhTUW23wbCZ1Yn', - role: 'assistant', - content: [ - { - type: 'text', - text: 'CLAUDE-AFTER-RECOVERY HARBOUR-1489 CLI-REWIND-1552' - } - ] - } - }, - { - type: 'system', - subtype: 'turn_duration', - uuid: 'f47f4e0a-9816-473c-b80d-8ed90d0a21e2', - parentUuid: 'ab494260-8c70-4383-a859-e726caf272cf', - timestamp: '2026-10-22T23:31:51.167Z', - isMeta: false, - isSidechain: false, - durationMs: 1938 - }, - { - type: 'user', - uuid: '37adf9f0-c934-4a98-8a8f-34cfacb53fce', - parentUuid: 'f47f4e0a-9816-473c-b80d-8ed90d0a21e2', - timestamp: '2026-10-22T23:32:10.885Z', - isSidechain: false, - promptSource: 'typed', - message: { - role: 'user', - content: 'Use your Bash tool to run sleep 20, then reply exactly QUEUE-REWRITE-OPEN-1552.' - } - }, - { - type: 'attachment', - uuid: 'f11c17a7-5c52-43d6-9881-aed7b0092489', - parentUuid: '37adf9f0-c934-4a98-8a8f-34cfacb53fce', - timestamp: '2026-10-22T23:32:10.885Z', - isSidechain: false, - attachment: { - type: 'total_tokens_reminder' - } - }, - { - type: 'assistant', - uuid: '47f13407-55d3-4226-91f2-431383ec38d5', - parentUuid: 'f11c17a7-5c52-43d6-9881-aed7b0092489', - timestamp: '2026-10-22T23:32:12.581Z', - isSidechain: false, - apiBlockIndex: 0, - message: { - id: 'msg_011CgJ9ZFsSZTgTX12zBVFp2', - role: 'assistant', - content: [ - { - type: 'tool_use', - id: 'toolu_01MoAGs3MB32fco3kjkHRF5B', - name: 'Bash', - input: { - command: 'sleep 20', - description: 'Wait 20 seconds' - }, - caller: { - type: 'direct' - } - } - ] - } - }, - { - type: 'user', - uuid: '76d04699-d585-45f3-b04f-de029ec2afe7', - parentUuid: '47f13407-55d3-4226-91f2-431383ec38d5', - timestamp: '2026-10-22T23:32:32.660Z', - isSidechain: false, - message: { - role: 'user', - content: [ - { - tool_use_id: 'toolu_01MoAGs3MB32fco3kjkHRF5B', - type: 'tool_result', - content: '(Bash completed with no output)', - is_error: false - } - ] - } - }, - { - type: 'attachment', - uuid: '282e98b1-5a75-46ff-be81-ebad78e28563', - parentUuid: '76d04699-d585-45f3-b04f-de029ec2afe7', - timestamp: '2026-10-22T23:32:21.679Z', - isSidechain: false, - attachment: { - type: 'queued_command', - prompt: 'Include QUEUE-BEFORE-EDIT-1552 in your reply. Also include QUEUE-AFTER-EDIT-1552.', - source_uuid: '080f8253-c2a1-41e1-b5e6-b6083f15c62d', - delivery_id: 'ae32f76f-8553-4989-bbdc-b230447648e4', - commandMode: 'prompt', - origin: { - kind: 'human' - }, - timestamp: '2026-10-22T23:32:21.679Z', - humanTurn: true - } - }, - { - type: 'attachment', - uuid: '7cbffe1d-5bde-4f7b-84d5-26c8cc3b55a8', - parentUuid: '282e98b1-5a75-46ff-be81-ebad78e28563', - timestamp: '2026-10-22T23:32:32.665Z', - isSidechain: false, - attachment: { - type: 'total_tokens_reminder' - } - }, - { - type: 'assistant', - uuid: '6869216c-9a65-4acc-87e0-140b280200bf', - parentUuid: '7cbffe1d-5bde-4f7b-84d5-26c8cc3b55a8', - timestamp: '2026-10-22T23:32:37.224Z', - isSidechain: false, - apiBlockIndex: 0, - message: { - id: 'msg_011CgJ9asNQ7ZS2EUrFAGTtS', - role: 'assistant', - content: [ - { - type: 'text', - text: 'QUEUE-REWRITE-OPEN-1552 QUEUE-BEFORE-EDIT-1552 QUEUE-AFTER-EDIT-1552' - } - ] - } - }, - { - type: 'system', - subtype: 'turn_duration', - uuid: '876beb5e-a4e4-4c4a-b842-6af45cfcf20b', - parentUuid: '6869216c-9a65-4acc-87e0-140b280200bf', - timestamp: '2026-10-22T23:32:37.231Z', - isMeta: false, - isSidechain: false, - durationMs: 26349 - }, - { - type: 'user', - uuid: '0ad4bb3c-e775-496a-b4f2-f43f6a47446d', - parentUuid: '876beb5e-a4e4-4c4a-b842-6af45cfcf20b', - timestamp: '2026-10-22T23:33:10.191Z', - isMeta: true, - isSidechain: false, - message: { - role: 'user', - content: - "The command below was run directly in Claude Code, not sent to you as a request, and its output goes straight to the user. It's recorded here as context for later messages." - } - }, - { - type: 'user', - uuid: 'e9a0b4a2-082c-42c4-9f09-e054d6f83921', - parentUuid: '0ad4bb3c-e775-496a-b4f2-f43f6a47446d', - timestamp: '2026-10-22T23:33:10.190Z', - isSidechain: false, - message: { - role: 'user', - content: - '/exit\n exit\n ' - } - }, - { - type: 'user', - uuid: '8422612e-3899-4058-b3f8-b0b960ed86fc', - parentUuid: 'e9a0b4a2-082c-42c4-9f09-e054d6f83921', - timestamp: '2026-10-22T23:33:10.190Z', - isSidechain: false, - message: { - role: 'user', - content: 'See ya!' - } - } -] - -const key = (uuid: string) => agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid }) - -describe('Claude historical cycle duration', () => { - it('ends captured work at its boundary before later idle, next prompt and exit', async () => { - const c = await chat() - await c.live() - const before = c.journal.snapshot() - const handle = structuredClone(c.identity.providerHandle) - const alias = key('p1') - const canonical = c.journal.canonicalItemId(alias) - await c.write([ - ...chatTurn, - ...capturedDurationRows.map((row, i) => ({ - ...row, - sessionId: SID, - ...(i === 0 ? { parentUuid: 'a1' } : {}) - })) - ]) - expect(await c.open('a1')).toBe(true) - const snapshot = c.journal.snapshot() - const turns = snapshot.items.filter((item) => item.body.kind === 'turn') - const first = turns.find( - (item) => - item.body.kind === 'turn' && item.body.turnId === '2d5c5bfb-2fb5-4d6e-9ad1-88e68f302f90' - )! - const second = turns.find( - (item) => - item.body.kind === 'turn' && item.body.turnId === '37adf9f0-c934-4a98-8a8f-34cfacb53fce' - )! - const settled = selectStructuredAgentSettledTurns(snapshot.items, snapshot.submissions) - const seconds = [first, second].map( - (item) => settled.get(item.body.kind === 'turn' ? item.body.userItemId! : '')?.workedSeconds - ) - console.info('captured historical seconds', seconds) - expect(seconds).toEqual([1, 26]) - expect(first).toMatchObject({ - observedAt: 1792711909253, - body: { - startedAt: 1792711909253, - completedAt: 1792711911167, - state: 'completed' - } - }) - expect(second).toMatchObject({ - observedAt: 1792711930885, - body: { - startedAt: 1792711930885, - completedAt: 1792711957231, - state: 'completed' - } - }) - for (const turn of turns.slice(1)) { - expect(turn.body).not.toHaveProperty('outcome') - expect(turn.body).not.toHaveProperty('durationMs') - } - const queuedItem = c.journal.item(key('080f8253-c2a1-41e1-b5e6-b6083f15c62d'))! - expect(queuedItem).toMatchObject({ - observedAt: 1792711941679, - turnScope: { - kind: 'turn', - turnItemId: second.itemId - } - }) - expect(isStructuredRewindTarget(c.journal, queuedItem.itemId)).toBe(false) - expect(isStructuredRewindTarget(c.journal, key('37adf9f0-c934-4a98-8a8f-34cfacb53fce'))).toBe( - true - ) - for (const item of before.items) { - expect(c.journal.item(item.itemId)).toEqual(item) - } - expect(snapshot.submissions).toEqual(before.submissions) - expect(c.identity.providerHandle).toEqual(handle) - expect(c.journal.canonicalItemId(alias)).toBe(canonical) - expect(c.rows()).toContain('user:See ya!') - const exits = turns.filter( - (item) => - item !== first && - item !== second && - !before.items.some((saved) => saved.itemId === item.itemId) - ) - expect(exits).toHaveLength(2) - for (const item of exits) { - expect(item.body).not.toHaveProperty('completedAt') - } - expect(await c.open('a1')).toBe(true) - expect(c.journal.snapshot()).toEqual(snapshot) - expect(c.warn).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/claude/claude-turn-activity.ts b/src/main/claude/claude-turn-activity.ts deleted file mode 100644 index 0f767ba68fa..00000000000 --- a/src/main/claude/claude-turn-activity.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { claudeProviderFrameActivity } from '../native-chat/agent-session-wire/providers/provider-frame-activity' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { claudeProviderFrameKind } from './structured/launch/claude-structured-provider-fallback' -import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state' -import type { ClaudeOpenTurn } from './claude-open-turn' -import { claudeStreamTurnSource, isRootClaudeFrame } from './claude-turn-opening' - -export function publishClaudeTurnActivity( - turn: ClaudeOpenTurn, - sink: StructuredAgentSessionEventSink, - event: Extract -): void { - const text = - event.type === 'message' - ? claudeProviderFrameActivity(claudeProviderFrameKind(event.message), event.message) - : claudeProviderFrameActivity(event.kind, event.payload) - if (event.type === 'message' && event.startedSend && isRootClaudeFrame(event.message) && text) { - turn.ensureOpen( - event.message, - claudeStreamTurnSource(event.message), - event.observedAt ?? Date.now() - ) - } - const turnId = turn.id - if (turnId !== null && text !== undefined) { - sink.setActivity?.(text ? { turnId, text } : null) - } -} diff --git a/src/main/claude/claude-cli-flag-prewarm.ts b/src/main/claude/cli-capabilities/claude-cli-flag-prewarm.ts similarity index 85% rename from src/main/claude/claude-cli-flag-prewarm.ts rename to src/main/claude/cli-capabilities/claude-cli-flag-prewarm.ts index bdebc1be852..0c480e47269 100644 --- a/src/main/claude/claude-cli-flag-prewarm.ts +++ b/src/main/claude/cli-capabilities/claude-cli-flag-prewarm.ts @@ -1,12 +1,12 @@ import { homedir } from 'node:os' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import type { AgentSessionRecordStore } from '../runtime/agent-session/records/agent-session-record-store' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import type { AgentSessionRecordStore } from '../../runtime/agent-session/records/agent-session-record-store' import type { ClaudeCliFlagSupport } from './claude-cli-flag-support' import { claudeProbeEnv, resolveClaudeChildEnvSources, type ClaudeEnvDeps -} from './structured/launch/claude-structured-child-env' +} from '../structured/launch/claude-structured-child-env' const MAX_PREWARMED_FOLDERS = 4 diff --git a/src/main/claude/claude-cli-flag-support.ts b/src/main/claude/cli-capabilities/claude-cli-flag-support.ts similarity index 100% rename from src/main/claude/claude-cli-flag-support.ts rename to src/main/claude/cli-capabilities/claude-cli-flag-support.ts diff --git a/src/main/claude/cli-capabilities/claude-hook-event-versions.test.ts b/src/main/claude/cli-capabilities/claude-hook-event-versions.test.ts new file mode 100644 index 00000000000..392f1c76457 --- /dev/null +++ b/src/main/claude/cli-capabilities/claude-hook-event-versions.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it, vi } from 'vitest' +import { runProcess } from '@orca/process-host' + +vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() })) + +import { probeClaudeCliVersion } from './claude-hook-event-versions' + +describe('identified Claude version output', () => { + // Recorded macOS 2.1.310 / Windows 2.1.221 probes; historical releases' CLI source + // registers the same suffix (1.0.23, 1.0.64, 2.0.0 and 2.1.100). + + it('does not accept marked output from a failed probe', async () => { + vi.mocked(runProcess).mockResolvedValue({ + stdout: '2.1.310 (Claude Code)\n', + stderr: '', + code: 1, + signal: null, + timedOut: false + }) + expect(await probeClaudeCliVersion('/bin/claude')).toBeNull() + }) +}) diff --git a/src/main/claude/claude-hook-event-versions.ts b/src/main/claude/cli-capabilities/claude-hook-event-versions.ts similarity index 98% rename from src/main/claude/claude-hook-event-versions.ts rename to src/main/claude/cli-capabilities/claude-hook-event-versions.ts index 3321a3703d1..27910729429 100644 --- a/src/main/claude/claude-hook-event-versions.ts +++ b/src/main/claude/cli-capabilities/claude-hook-event-versions.ts @@ -1,4 +1,4 @@ -import { hasReachedAppVersion, isValidAppVersion } from '../../shared/app-version' +import { hasReachedAppVersion, isValidAppVersion } from '../../../shared/app-version' import { runProcess } from '@orca/process-host' import path from 'node:path' diff --git a/src/main/claude/claude-at-rest-commands.ts b/src/main/claude/command-catalog/claude-at-rest-commands.ts similarity index 80% rename from src/main/claude/claude-at-rest-commands.ts rename to src/main/claude/command-catalog/claude-at-rest-commands.ts index 165d870fdc3..45133fd7631 100644 --- a/src/main/claude/claude-at-rest-commands.ts +++ b/src/main/claude/command-catalog/claude-at-rest-commands.ts @@ -1,26 +1,24 @@ -import type { AtRestCommandDemand } from '../native-chat/agent-session-wire/options/at-rest-command-demand' -import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' -import { PrioritySemaphore } from '../../shared/priority-semaphore' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { AtRestCommandDemand } from '../../native-chat/agent-session-wire/options/at-rest-command-demand' +import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' +import { PrioritySemaphore } from '../../../shared/priority-semaphore' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' import { isLegacyAgentSessionAccountHome, requireLegacyAgentSessionAccountHome, type AgentSessionAccountHome -} from '../../shared/agent-session/lifecycle/agent-session-account-home' -import type { AgentSessionSlashCommand } from '../../shared/agent-session/agent-session-wire' -import { structuredSlashCommands } from '../../shared/agent-session/view/structured-agent-session-composer' -import { discoverSkills } from '../skills/discovery/skill-native-discovery' +} from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import type { AgentSessionSlashCommand } from '../../../shared/agent-session/agent-session-wire' +import { structuredSlashCommands } from '../../../shared/agent-session/view/structured-agent-session-composer' +import { discoverSkills } from '../../skills/discovery/skill-native-discovery' import { scanClaudeCommandFolders } from './claude-command-folder-scan' -import { supportsClaudeStructuredLocation } from './structured/launch/claude-structured-location-support' +import { supportsClaudeStructuredLocation } from '../structured/launch/claude-structured-location-support' import type { ClaudeCommandCatalogProbe } from './claude-command-catalog-probe' import { - AT_REST_COMMANDS_TTL_MS, AtRestCommandCatalog, type AtRestCommandScan -} from '../native-chat/agent-session-wire/options/at-rest-command-catalog' +} from '../../native-chat/agent-session-wire/options/at-rest-command-catalog' import { join } from 'node:path' -export const CLAUDE_AT_REST_COMMANDS_TTL_MS = AT_REST_COMMANDS_TTL_MS // Older clients eagerly discover commands; retain their bounded admission. const MAX_PROBES_RUNNING = 2 diff --git a/src/main/claude/claude-command-catalog-probe.ts b/src/main/claude/command-catalog/claude-command-catalog-probe.ts similarity index 82% rename from src/main/claude/claude-command-catalog-probe.ts rename to src/main/claude/command-catalog/claude-command-catalog-probe.ts index c13a4459e27..2db61b4e6b3 100644 --- a/src/main/claude/claude-command-catalog-probe.ts +++ b/src/main/claude/command-catalog/claude-command-catalog-probe.ts @@ -1,7 +1,10 @@ -import type { AgentSessionSlashCommand } from '../../shared/agent-session/agent-session-wire' -import { runClaudeListing, type ClaudeModelCatalogProbeDeps } from './claude-model-catalog-probe' +import type { AgentSessionSlashCommand } from '../../../shared/agent-session/agent-session-wire' +import { + runClaudeListing, + type ClaudeModelCatalogProbeDeps +} from '../model-catalog/claude-model-catalog-probe' import { ClaudeSlashCommandCatalog } from './claude-slash-command-catalog' -import { readClaudeControlResponses } from './claude-control-responses' +import { readClaudeControlResponses } from '../sdk-transport/claude-control-responses' const REQUEST_ID = 'orca-command-discovery' diff --git a/src/main/claude/claude-command-folder-scan.ts b/src/main/claude/command-catalog/claude-command-folder-scan.ts similarity index 94% rename from src/main/claude/claude-command-folder-scan.ts rename to src/main/claude/command-catalog/claude-command-folder-scan.ts index 15a5f0a2c8a..fec4dadd914 100644 --- a/src/main/claude/claude-command-folder-scan.ts +++ b/src/main/claude/command-catalog/claude-command-folder-scan.ts @@ -1,8 +1,8 @@ import type { Dirent } from 'node:fs' import { opendir, readFile } from 'node:fs/promises' import { join, relative, sep } from 'node:path' -import type { AgentSessionSlashCommand } from '../../shared/agent-session/agent-session-wire' -import { summarizeSkillMarkdown } from '../../shared/skill-metadata' +import type { AgentSessionSlashCommand } from '../../../shared/agent-session/agent-session-wire' +import { summarizeSkillMarkdown } from '../../../shared/skill-metadata' const MARKDOWN_EXTENSION = '.md' const MAX_SCAN_DEPTH = 24 diff --git a/src/main/claude/claude-slash-command-catalog.ts b/src/main/claude/command-catalog/claude-slash-command-catalog.ts similarity index 98% rename from src/main/claude/claude-slash-command-catalog.ts rename to src/main/claude/command-catalog/claude-slash-command-catalog.ts index 2ecf7947716..6859e195152 100644 --- a/src/main/claude/claude-slash-command-catalog.ts +++ b/src/main/claude/command-catalog/claude-slash-command-catalog.ts @@ -1,4 +1,4 @@ -import type { AgentSessionSlashCommand } from '../../shared/agent-session/agent-session-wire' +import type { AgentSessionSlashCommand } from '../../../shared/agent-session/agent-session-wire' // Stream init carries name arrays; control initialization and reloads carry descriptors. const MAX_COMMANDS = 512 diff --git a/src/main/claude/claude-diff-panel-auto-open.test.ts b/src/main/claude/configuration/claude-diff-panel-auto-open.test.ts similarity index 100% rename from src/main/claude/claude-diff-panel-auto-open.test.ts rename to src/main/claude/configuration/claude-diff-panel-auto-open.test.ts diff --git a/src/main/claude/claude-diff-panel-auto-open.ts b/src/main/claude/configuration/claude-diff-panel-auto-open.ts similarity index 94% rename from src/main/claude/claude-diff-panel-auto-open.ts rename to src/main/claude/configuration/claude-diff-panel-auto-open.ts index 496f1ea5634..48a4c4995b8 100644 --- a/src/main/claude/claude-diff-panel-auto-open.ts +++ b/src/main/claude/configuration/claude-diff-panel-auto-open.ts @@ -4,8 +4,8 @@ import { readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' import { resolveClaudeGlobalConfigFile } from './claude-folder-trust-file' -import { claudeVersionReaches } from './claude-hook-event-versions' -import { isRecord } from '../../shared/agent-status/child-work/agent-status-child-work-value-guards' +import { claudeVersionReaches } from '../cli-capabilities/claude-hook-event-versions' +import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' export const CLAUDE_DIFF_PANEL_FIRST_VERSION = '2.1.260' diff --git a/src/main/claude/configuration/claude-folder-trust-file.test.ts b/src/main/claude/configuration/claude-folder-trust-file.test.ts new file mode 100644 index 00000000000..64aaa3d9a3a --- /dev/null +++ b/src/main/claude/configuration/claude-folder-trust-file.test.ts @@ -0,0 +1,106 @@ +import { + chmodSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + statSync, + symlinkSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { grantClaudeFolderTrust, grantClaudeWorkspaceTrust } from './claude-folder-trust-file' + +let root: string + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-claude-trust-'))) +}) + +afterEach(() => { + rmSync(root, { recursive: true, force: true }) +}) + +function writeConfig(file: string, value: unknown, mode = 0o600): void { + writeFileSync(file, JSON.stringify(value), { mode }) + chmodSync(file, mode) +} + +function readConfig(file: string): Record { + return JSON.parse(readFileSync(file, 'utf-8')) +} + +describe('grantClaudeFolderTrust', () => { + it('merges the key and keeps every other field', async () => { + const file = join(root, '.claude.json') + writeConfig(file, { + oauthAccount: { emailAddress: 'x' }, + mcpServers: { a: {} }, + projects: { '/elsewhere': { hasTrustDialogAccepted: true, allowedTools: [] } } + }) + await expect(grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] })).resolves.toBe( + 'granted' + ) + expect(readConfig(file)).toEqual({ + oauthAccount: { emailAddress: 'x' }, + mcpServers: { a: {} }, + projects: { + '/elsewhere': { hasTrustDialogAccepted: true, allowedTools: [] }, + '/wt': { hasTrustDialogAccepted: true } + } + }) + }) + + it('keeps an owner-only mode through the rewrite', async () => { + const file = join(root, '.claude.json') + writeConfig(file, {}, 0o600) + await grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] }) + expect(statSync(file).mode & 0o777).toBe(0o600) + }) + + it('leaves a corrupt file byte-for-byte untouched', async () => { + const file = join(root, '.claude.json') + writeFileSync(file, '{"oauthAccount": ', { mode: 0o600 }) + await expect(grantClaudeFolderTrust({ configFile: file, folderKeys: ['/wt'] })).resolves.toBe( + 'unreadable' + ) + expect(readFileSync(file, 'utf-8')).toBe('{"oauthAccount": ') + }) + + it('updates a symlinked config through its target and keeps the link', async () => { + const target = join(root, 'dotfiles-claude.json') + const link = join(root, '.claude.json') + writeConfig(target, { theme: 'dark' }) + symlinkSync(target, link) + await grantClaudeFolderTrust({ configFile: link, folderKeys: ['/wt'] }) + expect(lstatSync(link).isSymbolicLink()).toBe(true) + expect(readConfig(target)).toEqual({ + theme: 'dark', + projects: { '/wt': { hasTrustDialogAccepted: true } } + }) + }) +}) + +describe('grantClaudeWorkspaceTrust', () => { + it('writes the given folder and its realpath form, whatever kind of folder it is', async () => { + const real = join(root, 'real-folder') + mkdirSync(real) + const link = join(root, 'linked-folder') + symlinkSync(real, link) + const file = join(root, '.claude.json') + writeConfig(file, {}) + await expect( + grantClaudeWorkspaceTrust({ configFile: file, keyStyle: 'posix' }, link) + ).resolves.toBe('granted') + expect(readConfig(file)).toEqual({ + projects: { + [link]: { hasTrustDialogAccepted: true }, + [real]: { hasTrustDialogAccepted: true } + } + }) + }) +}) diff --git a/src/main/claude/claude-folder-trust-file.ts b/src/main/claude/configuration/claude-folder-trust-file.ts similarity index 96% rename from src/main/claude/claude-folder-trust-file.ts rename to src/main/claude/configuration/claude-folder-trust-file.ts index 42d3fdbf709..478f2cfd809 100644 --- a/src/main/claude/claude-folder-trust-file.ts +++ b/src/main/claude/configuration/claude-folder-trust-file.ts @@ -12,12 +12,12 @@ import { import { dirname, join, posix, resolve, win32 } from 'node:path' import { homedir } from 'node:os' import { lock } from 'proper-lockfile' -import '../filesystem/atomic-file-publication' -import { renameFileWithWindowsRetry } from '../../shared/windows-retry-file-operations' -import { runKeyedSerializedOperation } from '../../shared/concurrency/keyed-serialized-operations' -import { parseWslUncPath } from '../../shared/wsl-paths' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' +import '../../filesystem/atomic-file-publication' +import { renameFileWithWindowsRetry } from '../../../shared/windows-retry-file-operations' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' +import { parseWslUncPath } from '../../../shared/wsl-paths' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' export type ClaudeTrustPathStyle = 'posix' | 'win32' diff --git a/src/main/claude/claude-rejected-api-key.ts b/src/main/claude/configuration/claude-rejected-api-key.ts similarity index 100% rename from src/main/claude/claude-rejected-api-key.ts rename to src/main/claude/configuration/claude-rejected-api-key.ts diff --git a/src/main/claude/claude-context-facts.ts b/src/main/claude/context-usage/claude-context-facts.ts similarity index 78% rename from src/main/claude/claude-context-facts.ts rename to src/main/claude/context-usage/claude-context-facts.ts index cdcbae70fdf..7d8aa2c9256 100644 --- a/src/main/claude/claude-context-facts.ts +++ b/src/main/claude/context-usage/claude-context-facts.ts @@ -4,9 +4,9 @@ import { type AgentSessionContextReport, type AgentSessionContextUsage, type AgentSessionContextWindow -} from '../../shared/agent-session/agent-session-context-usage' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +} from '../../../shared/agent-session/agent-session-context-usage' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { claudeContextResetKind, claudeContextWindowFromResult, @@ -14,26 +14,32 @@ import { claudeTokenUsage, type ClaudeMainThreadModel } from './claude-context-usage' -import type { ClaudeOpenTurn } from './claude-open-turn' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' -import type { ClaudeTurnEnd } from './claude-turn-lifecycle-item' -import { isRootClaudeFrame } from './claude-turn-opening' +import type { ClaudeOpenTurn } from '../structured/turns/claude-open-turn' +import { claudeRecord, claudeText } from '../structured/journal/claude-structured-item-translation' +import type { ClaudeTurnEnd } from '../structured/turns/claude-turn-lifecycle-item' +import { isRootClaudeFrame } from '../structured/turns/claude-turn-opening' import { writeAgentJournalTurnRow, type AgentJournalTurnRowTarget -} from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' +} from '../../native-chat/agent-session-timeline/agent-journal-turn-row-revision' const CONVERSATION_FRAME_TYPES = new Set(['assistant', 'user', 'stream_event']) /** Null targets the newest journal turn when no turn was open at request time. */ export type ClaudeContextReportTarget = AgentJournalItemIdentity | null -export type ClaudeContextReportPart = 'report' | 'window' +/** `askedAt` returns with the answer to `recordReport`. */ +export type ClaudeContextReportListener = ( + target: ClaudeContextReportTarget, + askedAt: number +) => void const STALE = Symbol('stale-window') export class ClaudeContextFacts { private activity = 0 + /** Advances on every newer used count, written or held back; a report asked for earlier must not replace it. */ + private usedCounts = 0 private mainModel: ClaudeMainThreadModel = { initModel: null, responseModel: null } /** Null adopts the next response model; STALE blocks estimates until a fresh window arrives. */ private servedModel: string | null | typeof STALE = null @@ -44,7 +50,7 @@ export class ClaudeContextFacts { /** Check the journal before seeding a configured window hint. */ private journalMayLackWindow = true private lastResponse: string | null = null - private readonly requestListeners = new Set<(target: ClaudeContextReportTarget) => void>() + private readonly requestListeners = new Set() constructor( private readonly turn: ClaudeOpenTurn, @@ -111,6 +117,7 @@ export class ClaudeContextFacts { if (this.servedModel === STALE) { // After a model change, only a configured hint can serve estimates before the report. if (!hint) { + this.usedCounts += 1 return } window = hint @@ -157,28 +164,25 @@ export class ClaudeContextFacts { this.requestReport(settled) } - /** Reports overtaken by activity retain only the window; full reports also replace usage. */ + /** A report asked for before a newer used count retains only the window; otherwise it also replaces usage. */ recordReport( target: ClaudeContextReportTarget, report: AgentSessionContextReport, - part: ClaudeContextReportPart + askedAt: number ): void { const window = { tokens: report.windowTokens, capturedAt: report.capturedAt } this.servedModel = null this.windowReported = true // Before the first turn exists, retain the report's window for the first response. this.windowHint = report.windowTokens - const contextUsage: AgentSessionContextUsage = - part === 'report' ? { used: { kind: 'report', ...report }, window } : { window } - writeAgentJournalTurnRow( - this.sink, - target === null ? { newest: true } : { identity: target }, - { contextUsage }, - { publish: true } + this.write( + askedAt === this.usedCounts ? { used: { kind: 'report', ...report }, window } : { window }, + undefined, + target ) } - subscribeReportRequests(listener: (target: ClaudeContextReportTarget) => void): () => void { + subscribeReportRequests(listener: ClaudeContextReportListener): () => void { this.requestListeners.add(listener) return () => this.requestListeners.delete(listener) } @@ -189,9 +193,12 @@ export class ClaudeContextFacts { private write( contextUsage: AgentSessionContextUsage, - windowIfNoneHeld?: AgentSessionContextWindow + windowIfNoneHeld?: AgentSessionContextWindow, + identity: ClaudeContextReportTarget = this.turn.identity ): void { - const identity = this.turn.identity + if (contextUsage.used) { + this.usedCounts += 1 + } const target: AgentJournalTurnRowTarget = identity ? { identity } : { newest: true } // No later frame may arrive to publish this fact. writeAgentJournalTurnRow( @@ -213,7 +220,7 @@ export class ClaudeContextFacts { private requestReport(target: ClaudeContextReportTarget): void { for (const listener of this.requestListeners) { - listener(target) + listener(target, this.usedCounts) } } } diff --git a/src/main/claude/context-usage/claude-context-usage.test.ts b/src/main/claude/context-usage/claude-context-usage.test.ts new file mode 100644 index 00000000000..49769b469fd --- /dev/null +++ b/src/main/claude/context-usage/claude-context-usage.test.ts @@ -0,0 +1,121 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { selectStructuredAgentContextUsage } from '../../../shared/agent-session/structured-agent-session-context-usage' +import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { createTrackedJournalOpener } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { testEventSinkLogging } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' +import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' +import { bindClaudeContextUsageCapture } from './claude-context-usage' + +const journals = createTrackedJournalOpener() +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-claude-context-usage-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function frame(message: Record, observedAt: number, startsTurn = false) { + return { + type: 'message' as const, + sessionId: 'orca-session', + observedAt, + ...(startsTurn ? { startsTurn: true as const } : {}), + message: { session_id: 'claude-session', parent_tool_use_id: null, ...message } + } +} + +// Gateways that convert OpenAI streams send usage only in message_delta, so Claude's frames carry zeros. +const responseWithoutUsage = (uuid: string, at: number) => + frame( + { + type: 'assistant', + uuid, + message: { + role: 'assistant', + model: 'deepseek-v4.1-flash', + content: [{ type: 'text', text: uuid }], + usage: { input_tokens: 0, output_tokens: 0 } + } + }, + at + ) + +it('shows the report after a compaction when responses carry no usage', async () => { + const journal = await journals.open({ + identity: { + sessionId: 'orca-session', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-session', null) + }, + now: () => 9_000, + stateDirectory: join(root, 'orca-session') + }) + const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) + deferred.bind({ journal, fence: 1, publish: () => {} }) + const answers: ((value: unknown) => void)[] = [] + const unbind = bindClaudeContextUsageCapture( + { getContextUsage: () => new Promise((resolve) => answers.push(resolve)) }, + translator, + { now: () => 20_000 } + ) + const settle = async (): Promise => { + for (let index = 0; index < 4; index += 1) { + await Promise.resolve() + } + await expect(deferred.drained()).resolves.toEqual({ ok: true }) + } + const ring = () => selectStructuredAgentContextUsage(journal.snapshot().items) + + translator.handle( + frame({ type: 'system', subtype: 'init', uuid: 'init', model: 'deepseek-v4.1-flash' }, 900) + ) + translator.handle( + frame( + { + type: 'user', + uuid: 'turn-a', + message: { role: 'user', content: [{ type: 'text', text: 'go' }] } + }, + 1_000, + true + ) + ) + translator.handle(responseWithoutUsage('reply-a', 2_000)) + translator.handle( + frame( + { + type: 'system', + subtype: 'compact_boundary', + uuid: 'compact', + compact_metadata: { trigger: 'auto' } + }, + 3_000 + ) + ) + translator.handle(responseWithoutUsage('reply-a2', 4_000)) + await settle() + expect(ring()).toBeNull() + + answers.at(-1)?.({ + model: 'deepseek-v4.1-flash', + totalTokens: 40_000, + rawMaxTokens: 200_000, + categories: [] + }) + await settle() + expect(ring()).toMatchObject({ usedTokens: 40_000, windowTokens: 200_000, estimated: false }) + unbind?.() + translator.dispose() + deferred.close() +}) diff --git a/src/main/claude/claude-context-usage.ts b/src/main/claude/context-usage/claude-context-usage.ts similarity index 90% rename from src/main/claude/claude-context-usage.ts rename to src/main/claude/context-usage/claude-context-usage.ts index 8ce61a16c17..faf8510cf6c 100644 --- a/src/main/claude/claude-context-usage.ts +++ b/src/main/claude/context-usage/claude-context-usage.ts @@ -5,9 +5,9 @@ import { type AgentSessionContextReport, type AgentSessionContextUsageCategory, type AgentSessionTokenUsage -} from '../../shared/agent-session/agent-session-context-usage' -import type { ClaudeStreamJsonConnection } from './claude-stream-json-connection' -import type { ClaudeJournalTranslator } from './claude-journal-translator-contract' +} from '../../../shared/agent-session/agent-session-context-usage' +import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' +import type { ClaudeJournalTranslator } from '../structured/journal/claude-journal-translator-contract' export const CLAUDE_CONTEXT_USAGE_TIMEOUT_MS = 5_000 @@ -175,10 +175,10 @@ export type ClaudeContextUsageReader = Pick -/** Newer requests discard old answers; conversation activity invalidates only usage, not the window. */ +/** Newer requests discard old answers; the translator decides whether a late answer still replaces usage. */ export function bindClaudeContextUsageCapture( connection: ClaudeContextUsageReader, translator: ClaudeContextUsageTarget | null, @@ -189,9 +189,8 @@ export function bindClaudeContextUsageCapture( } let bound = true let requests = 0 - const unsubscribe = translator.subscribeContextUsageRequests((target) => { + const unsubscribe = translator.subscribeContextUsageRequests((target, askedAt) => { const request = ++requests - const activity = translator.contextActivity void connection .getContextUsage({ timeoutMs: options.timeoutMs ?? CLAUDE_CONTEXT_USAGE_TIMEOUT_MS }) .then( @@ -203,11 +202,7 @@ export function bindClaudeContextUsageCapture( if (!report) { return } - if (activity !== translator.contextActivity) { - translator.recordContextReport(target, report, 'window') - return - } - translator.recordContextReport(target, report, 'report') + translator.recordContextReport(target, report, askedAt) }, () => {} ) diff --git a/src/main/claude/claude-conversation-naming.ts b/src/main/claude/conversation-naming/claude-conversation-naming.ts similarity index 95% rename from src/main/claude/claude-conversation-naming.ts rename to src/main/claude/conversation-naming/claude-conversation-naming.ts index 04709778785..dc9736bb34b 100644 --- a/src/main/claude/claude-conversation-naming.ts +++ b/src/main/claude/conversation-naming/claude-conversation-naming.ts @@ -1,13 +1,13 @@ -import { activeProviderContext } from '../../shared/agent-session/agent-session-provider-context' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { claudeSessionIdForOrcaSession } from './structured/claude-structured-session-id' +import { activeProviderContext } from '../../../shared/agent-session/agent-session-provider-context' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import { claudeSessionIdForOrcaSession } from '../structured/claude-structured-session-id' import { createClaudeNamingGeneration, type ClaudeNamingGeneration } from './claude-naming-generation' import type { ClaudeNamingInputs } from './claude-naming-invocation' -import { renameClaudeTranscript } from './claude-provider-session-rename' -import type { StructuredAgentSessionAcquireInput } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { renameClaudeTranscript } from '../transcripts/claude-provider-session-rename' +import type { StructuredAgentSessionAcquireInput } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' type Intent = { record: AgentSessionRecord diff --git a/src/main/claude/claude-naming-generation.ts b/src/main/claude/conversation-naming/claude-naming-generation.ts similarity index 93% rename from src/main/claude/claude-naming-generation.ts rename to src/main/claude/conversation-naming/claude-naming-generation.ts index 2edde684fd4..6dc7a120bf7 100644 --- a/src/main/claude/claude-naming-generation.ts +++ b/src/main/claude/conversation-naming/claude-naming-generation.ts @@ -1,5 +1,5 @@ -import type { ClaudeStreamJsonConnection } from './claude-stream-json-connection' -import type { ClaudeStructuredLaunch } from './structured/launch/claude-structured-launch-resolution' +import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' +import type { ClaudeStructuredLaunch } from '../structured/launch/claude-structured-launch-resolution' import { claudeNamingLaunchInputs, type ClaudeNamingInputs } from './claude-naming-invocation' type Phase = 'acquiring' | 'initializing' | 'ready' | 'closing' | 'exited' | 'unproven' diff --git a/src/main/claude/conversation-naming/claude-naming-invocation.ts b/src/main/claude/conversation-naming/claude-naming-invocation.ts new file mode 100644 index 00000000000..5c60d24d90a --- /dev/null +++ b/src/main/claude/conversation-naming/claude-naming-invocation.ts @@ -0,0 +1,107 @@ +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import { requireLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' +import { applyClaudeEnvPatch } from '../../claude-accounts/runtime-auth/environment' +import { agentSessionPinnedLaunchDirectory } from '../../runtime/agent-session/records/agent-session-record-launch-directory' +import type { StructuredAgentLaunchSources } from '../../runtime/agent-session/launch/structured-agent-launch-composition' +import { resolveStructuredAgentCommand } from '../../native-chat/agent-launch/structured-agent-command-resolution' +import { + claudeChildEnv, + resolveClaudeChildEnvSources, + type ClaudeEnvDeps +} from '../structured/launch/claude-structured-child-env' +import { claudeStructuredLaunchArgs } from '../structured/launch/claude-structured-launch-args' +import { + claudeConfigDirEnvPatch, + withoutInheritedClaudeConfigDir +} from '../structured/launch/claude-config-dir-pin' +import { buildClaudeChildProcessEnv } from '../child-process/claude-child-process-environment' +import type { ClaudeStructuredLaunch } from '../structured/launch/claude-structured-launch-resolution' +import { resolve } from 'node:path' + +export type ClaudeNamingInputs = { + command: string + cwd: string + home: string + env: Readonly> + extraArgs: Readonly> +} + +/** Capture the selected policy now; only its independent I/O remains on the naming task. */ +export function claudeNamingInvocation( + sources: StructuredAgentLaunchSources, + resolveArgs: () => Promise | string[], + resolveCommand?: ClaudeEnvDeps['resolveCommand'] +): (record: AgentSessionRecord) => Promise { + return (record) => { + const configured = sources.resolveCommandSettings?.() + const settings = configured ? structuredClone(configured) : undefined + const overlay = { ...sources.resolveAgentLaunchEnv?.('claude') } + const args = Promise.resolve(resolveArgs()).then((value) => claudeStructuredLaunchArgs(value)) + const inherited = sources.resolveBaseEnvironment().then((value) => ({ ...value })) + const pinned = agentSessionPinnedLaunchDirectory(record) + const directory = pinned + ? Promise.resolve(pinned) + : sources.resolveWorkspacePath(record.location.workspaceId) + const router = getClaudeProfileRouter() + const policy = router?.preparation() + const systemHome = router?.systemDefaultHome() + const savedHome = requireLegacyAgentSessionAccountHome(record.accountHome).path + return (async () => { + const [cwd, baseEnv, configuredArgs] = await Promise.all([directory, inherited, args]) + const resolved = await resolveClaudeChildEnvSources({ + resolveEnv: () => overlay, + resolveInheritedEnv: () => Promise.resolve(baseEnv), + resolveWorkingDirectory: () => cwd, + ...(settings + ? { + resolveCommand: (options) => + resolveStructuredAgentCommand('claude', settings, options) + } + : resolveCommand + ? { resolveCommand } + : {}) + }) + const env = claudeChildEnv(resolved, undefined, { runtimeOnPath: false }) + const home = policy + ? policy.provenance === 'system' + ? env.CLAUDE_CONFIG_DIR?.trim() || systemHome || policy.configDir + : policy.configDir + : savedHome + if (policy) { + applyClaudeEnvPatch(env, policy.envPatch) + } + Object.assign(env, claudeConfigDirEnvPatch(home, { env })) + return { + command: resolved.command, + cwd, + home: resolve(cwd, home), + env, + extraArgs: configuredArgs.extraArgs + } + })() + } +} + +/** Owned contexts always use their actual launch, including its account and configured args. */ +export function claudeNamingLaunchInputs(launch: ClaudeStructuredLaunch): ClaudeNamingInputs { + const env = buildClaudeChildProcessEnv( + { + ...launch.env, + ...claudeConfigDirEnvPatch(launch.claudeConfigDir, { env: launch.env }) + }, + { + inheritedEnv: withoutInheritedClaudeConfigDir(process.env) + } + ) + for (const key of launch.envToDelete ?? []) { + delete env[key] + } + return { + command: launch.pathToClaudeCodeExecutable, + cwd: launch.cwd, + home: resolve(launch.cwd, launch.claudeConfigDir), + env, + extraArgs: { ...launch.options.extraArgs } + } +} diff --git a/src/main/claude/claude-captured-compact-frames.test-fixture.ts b/src/main/claude/fixtures/claude-captured-compact-frames.test-fixture.ts similarity index 100% rename from src/main/claude/claude-captured-compact-frames.test-fixture.ts rename to src/main/claude/fixtures/claude-captured-compact-frames.test-fixture.ts diff --git a/src/main/claude/hook-service.test.ts b/src/main/claude/hook-service.test.ts deleted file mode 100644 index 7cd3920a2f5..00000000000 --- a/src/main/claude/hook-service.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { vi, describe, expect, it } from 'vitest' -import type * as GitBashModule from '../pty/shell-startup/git-bash' - -vi.mock('electron', () => ({ - app: { - getPath: () => '/tmp/userData' - } -})) - -const { gitBashAvailableMock } = vi.hoisted(() => ({ gitBashAvailableMock: { value: true } })) -vi.mock('../pty/shell-startup/git-bash', async (importOriginal) => ({ - ...(await importOriginal()), - isGitBashAvailable: () => gitBashAvailableMock.value -})) - -import { ClaudeHookService } from './hook-service' - -const CURRENT_CLAUDE = { claudeVersion: '2.1.261 (Claude Code)' } - -describe('ClaudeHookService.install', () => { - it('keeps newer Orca events and reports installed when a later probe cannot resolve the version', () => { - const tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-unknown-version-')) - vi.stubEnv('HOME', tmpHome) - vi.stubEnv('USERPROFILE', tmpHome) - try { - const service = new ClaudeHookService() - const settingsPath = join(tmpHome, '.claude', 'settings.json') - expect(service.install(CURRENT_CLAUDE).state).toBe('installed') - const known = JSON.parse(readFileSync(settingsPath, 'utf-8')) - - expect(service.install().state).toBe('installed') - - const unknown = JSON.parse(readFileSync(settingsPath, 'utf-8')) - expect(unknown.hooks).toEqual(known.hooks) - expect(service.getStatus().state).toBe('installed') - } finally { - vi.unstubAllEnvs() - rmSync(tmpHome, { recursive: true, force: true }) - } - }) - - it('does not re-install a managed statusLine the user deleted, until remove() resets the opt-out', () => { - const tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-statusline-optout-')) - vi.stubEnv('HOME', tmpHome) - vi.stubEnv('USERPROFILE', tmpHome) - try { - const settingsPath = join(tmpHome, '.claude', 'settings.json') - new ClaudeHookService().install() - expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeTruthy() - - const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) - delete settings.statusLine - writeFileSync(settingsPath, JSON.stringify(settings)) - - new ClaudeHookService().install() - expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeUndefined() - - new ClaudeHookService().remove() - new ClaudeHookService().install() - expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeTruthy() - } finally { - vi.unstubAllEnvs() - rmSync(tmpHome, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts index 433eb1b1ad6..b741945d9fb 100644 --- a/src/main/claude/hook-service.ts +++ b/src/main/claude/hook-service.ts @@ -20,7 +20,7 @@ import { } from '../agent-hooks/installation/configuration/hooks-json-remote' import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' -import { getManagedScript } from './hook-script' +import { getManagedScript } from './hooks/hook-script' import { removeClaudeAgentViewRemote, refreshClaudeAgentView, @@ -32,12 +32,12 @@ import { installWindowsClaudeHookExecutable, installWindowsClaudeHookFiles, refreshWindowsClaudeHookFiles -} from './windows-hook-files' +} from './hooks/windows-hook-files' -export { getManagedScript } -import { getManagedStatusLineScript } from './statusline-script' -import { installClaudeManagedStatusLine, retireClaudeManagedStatusLine } from './statusline-install' -import { refuseProfileAtDefaultHome } from './claude-profile-hook-target' +import { getManagedStatusLineScript } from './hooks/statusline-script' +// oxfmt-ignore +import { installClaudeManagedStatusLine, retireClaudeManagedStatusLine } from './hooks/statusline-install' +import { refuseProfileAtDefaultHome } from './hooks/claude-profile-hook-target' import { applyManagedHooks, CLAUDE_HOOK_SETTINGS, @@ -54,14 +54,14 @@ import { removeManagedHooks, removeManagedStatusLine, type ClaudeCompatibleHookSettings -} from './hook-settings' -import { claudeAcceptsExecFormHooks } from './claude-hook-event-versions' -import { getManagedEventHook } from './claude-managed-event-hook' +} from './hooks/hook-settings' +import { claudeAcceptsExecFormHooks } from './cli-capabilities/claude-hook-event-versions' +import { getManagedEventHook } from './hooks/claude-managed-event-hook' import { getClaudeManagedHookPlan, OPENCLAUDE_MANAGED_HOOK_PLAN, type ClaudeManagedHookPlan -} from './claude-managed-hook-events' +} from './hooks/claude-managed-hook-events' type ClaudeHookServiceOptions = { agent: AgentHookInstallStatus['agent'] diff --git a/src/main/claude/claude-async-permission-request.ts b/src/main/claude/hooks/claude-async-permission-request.ts similarity index 94% rename from src/main/claude/claude-async-permission-request.ts rename to src/main/claude/hooks/claude-async-permission-request.ts index 13a6c83e51a..5c287cd219b 100644 --- a/src/main/claude/claude-async-permission-request.ts +++ b/src/main/claude/hooks/claude-async-permission-request.ts @@ -1,7 +1,7 @@ import { MANAGED_HOOK_TIMEOUT_SECONDS, type HookCommandConfig -} from '../agent-hooks/installation/configuration/hook-config-schema' +} from '../../agent-hooks/installation/configuration/hook-config-schema' // Read by the hook script: this entry runs async, so Claude ignores its output and nothing waits on it. const ASYNC_FLAG = 'export ORCA_HOOK_ASYNC=1; ' diff --git a/src/main/claude/claude-hook-decision-script.ts b/src/main/claude/hooks/claude-hook-decision-script.ts similarity index 92% rename from src/main/claude/claude-hook-decision-script.ts rename to src/main/claude/hooks/claude-hook-decision-script.ts index 721c1f0d601..928e22d4e71 100644 --- a/src/main/claude/claude-hook-decision-script.ts +++ b/src/main/claude/hooks/claude-hook-decision-script.ts @@ -1,5 +1,5 @@ -import { CLAUDE_PRE_TOOL_USE_DECISION } from '../agent-hooks/tool-events/agent-tool-plugin-hooks' -import { CLAUDE_PERMISSION_REQUEST_DECISION } from '../agent-hooks/server/claude-permission-hook-hold' +import { CLAUDE_PRE_TOOL_USE_DECISION } from '../../agent-hooks/tool-events/agent-tool-plugin-hooks' +import { CLAUDE_PERMISSION_REQUEST_DECISION } from '../../agent-hooks/server/claude-permission-hook-hold' /** * Lets Claude Code's PreToolUse hook print Orca's answer (plugins' `agent.tool.before`), and its diff --git a/src/main/claude/claude-managed-event-hook.ts b/src/main/claude/hooks/claude-managed-event-hook.ts similarity index 81% rename from src/main/claude/claude-managed-event-hook.ts rename to src/main/claude/hooks/claude-managed-event-hook.ts index d68b110b690..136d9ab607d 100644 --- a/src/main/claude/claude-managed-event-hook.ts +++ b/src/main/claude/hooks/claude-managed-event-hook.ts @@ -1,5 +1,5 @@ -import { buildManagedCommandHook } from '../agent-hooks/installation/configuration/hook-config-schema' -import type { HookCommandConfig } from '../agent-hooks/installation/configuration/hook-config-schema' +import { buildManagedCommandHook } from '../../agent-hooks/installation/configuration/hook-config-schema' +import type { HookCommandConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' import { CLAUDE_HOOK_SETTINGS, getManagedLifecycleHook, diff --git a/src/main/claude/claude-managed-hook-events.ts b/src/main/claude/hooks/claude-managed-hook-events.ts similarity index 96% rename from src/main/claude/claude-managed-hook-events.ts rename to src/main/claude/hooks/claude-managed-hook-events.ts index 9894f5b4227..550411a20ea 100644 --- a/src/main/claude/claude-managed-hook-events.ts +++ b/src/main/claude/hooks/claude-managed-hook-events.ts @@ -1,10 +1,10 @@ -import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' +import type { HookDefinition } from '../../agent-hooks/installation/configuration/hook-config-schema' import { claudeKnowsHookEvent, claudeKnowsStatusLine, claudeVersionReaches, parseClaudeCliVersion -} from './claude-hook-event-versions' +} from '../cli-capabilities/claude-hook-event-versions' export const CLAUDE_EVENTS = [ // SessionStart creates sidebar rows for resumed or idle sessions before the first prompt. diff --git a/src/main/claude/claude-profile-hook-target.ts b/src/main/claude/hooks/claude-profile-hook-target.ts similarity index 87% rename from src/main/claude/claude-profile-hook-target.ts rename to src/main/claude/hooks/claude-profile-hook-target.ts index 19baf9a379e..c868576cc07 100644 --- a/src/main/claude/claude-profile-hook-target.ts +++ b/src/main/claude/hooks/claude-profile-hook-target.ts @@ -1,7 +1,7 @@ import { statSync } from 'node:fs' import { dirname, resolve } from 'node:path' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' import { getConfigPath, type ClaudeCompatibleHookSettings } from './hook-settings' function sameFile(left: string, right: string): boolean { diff --git a/src/main/claude/claude-profile-hooks.test.ts b/src/main/claude/hooks/claude-profile-hooks.test.ts similarity index 95% rename from src/main/claude/claude-profile-hooks.test.ts rename to src/main/claude/hooks/claude-profile-hooks.test.ts index d7e885f5c30..e9680c78f74 100644 --- a/src/main/claude/claude-profile-hooks.test.ts +++ b/src/main/claude/hooks/claude-profile-hooks.test.ts @@ -17,8 +17,8 @@ vi.mock('node:os', async (original) => ({ homedir: () => state.home })) vi.mock('electron', () => ({ app: { getPath: () => state.home } })) -import { ClaudeHookService } from './hook-service' -import { provisionClaudeProfile } from '../claude-accounts/profiles/setup/claude-profile-provisioning' +import { ClaudeHookService } from '../hook-service' +import { provisionClaudeProfile } from '../../claude-accounts/profiles/setup/claude-profile-provisioning' const caseInsensitive = (() => { const dir = mkdtempSync(join(tmpdir(), 'claude-case-probe-')) diff --git a/src/main/claude/claude-status-line-install.test.ts b/src/main/claude/hooks/claude-status-line-install.test.ts similarity index 98% rename from src/main/claude/claude-status-line-install.test.ts rename to src/main/claude/hooks/claude-status-line-install.test.ts index c8069aea660..4d0d362783b 100644 --- a/src/main/claude/claude-status-line-install.test.ts +++ b/src/main/claude/hooks/claude-status-line-install.test.ts @@ -20,7 +20,7 @@ vi.mock('electron', () => ({ } })) -import { ClaudeHookService } from './hook-service' +import { ClaudeHookService } from '../hook-service' const USER_STATUS_LINE = { type: 'command', command: '/usr/local/bin/my-statusline' } diff --git a/src/main/claude/hook-script.ts b/src/main/claude/hooks/hook-script.ts similarity index 85% rename from src/main/claude/hook-script.ts rename to src/main/claude/hooks/hook-script.ts index a12c2812f2e..c6cc7275d99 100644 --- a/src/main/claude/hook-script.ts +++ b/src/main/claude/hooks/hook-script.ts @@ -1,28 +1,28 @@ -import { buildHookProcessCapture } from '../agent-hooks/installation/scripts/hook-process-capture' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { buildHookProcessCapture } from '../../agent-hooks/installation/scripts/hook-process-capture' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { buildWindowsAgentHookCurlPostCommand } from '../../agent-hooks/installation/commands/windows-agent-hook-post-command' import { buildPosixAgentHookPostCommand, buildPosixHookMetadataCacheLines -} from '../agent-hooks/installation/scripts/hook-post-command' +} from '../../agent-hooks/installation/scripts/hook-post-command' import { buildPosixScrubSafeEnvRestoreLines, buildWindowsScrubSafeEnvRestoreLines -} from '../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' +} from '../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' import { buildPosixCursorReplayGuardLines, buildWindowsCursorReplayGuardLines -} from '../agent-hooks/installation/scripts/cursor-replay-guard' +} from '../../agent-hooks/installation/scripts/cursor-replay-guard' import { buildPosixGrokReplayGuardLines, buildWindowsGrokReplayGuardLines -} from '../agent-hooks/installation/scripts/grok-replay-guard' +} from '../../agent-hooks/installation/scripts/grok-replay-guard' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines, POSIX_HOOK_STDIN_EXEC -} from '../agent-hooks/installation/scripts/hook-stdin-contract' +} from '../../agent-hooks/installation/scripts/hook-stdin-contract' import { buildPosixClaudeDecisionModeLines, buildPosixClaudeDecisionPreludeLines, @@ -31,7 +31,7 @@ import { import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../agent-hooks/installation/scripts/claude-background-job-guard' +} from '../../agent-hooks/installation/scripts/claude-background-job-guard' export function getManagedScript( target: 'local' | 'posix' = 'local', diff --git a/src/main/claude/hooks/hook-service.test.ts b/src/main/claude/hooks/hook-service.test.ts new file mode 100644 index 00000000000..de9d7bdc01c --- /dev/null +++ b/src/main/claude/hooks/hook-service.test.ts @@ -0,0 +1,46 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { vi, describe, expect, it } from 'vitest' +import type * as GitBashModule from '../../pty/shell-startup/git-bash' + +vi.mock('electron', () => ({ + app: { + getPath: () => '/tmp/userData' + } +})) + +const { gitBashAvailableMock } = vi.hoisted(() => ({ gitBashAvailableMock: { value: true } })) +vi.mock('../../pty/shell-startup/git-bash', async (importOriginal) => ({ + ...(await importOriginal()), + isGitBashAvailable: () => gitBashAvailableMock.value +})) + +import { ClaudeHookService } from '../hook-service' + +describe('ClaudeHookService.install', () => { + it('does not re-install a managed statusLine the user deleted, until remove() resets the opt-out', () => { + const tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-statusline-optout-')) + vi.stubEnv('HOME', tmpHome) + vi.stubEnv('USERPROFILE', tmpHome) + try { + const settingsPath = join(tmpHome, '.claude', 'settings.json') + new ClaudeHookService().install() + expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeTruthy() + + const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) + delete settings.statusLine + writeFileSync(settingsPath, JSON.stringify(settings)) + + new ClaudeHookService().install() + expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeUndefined() + + new ClaudeHookService().remove() + new ClaudeHookService().install() + expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeTruthy() + } finally { + vi.unstubAllEnvs() + rmSync(tmpHome, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/claude/hook-settings.ts b/src/main/claude/hooks/hook-settings.ts similarity index 92% rename from src/main/claude/hook-settings.ts rename to src/main/claude/hooks/hook-settings.ts index f97b98bbd3f..b40595af4f3 100644 --- a/src/main/claude/hook-settings.ts +++ b/src/main/claude/hooks/hook-settings.ts @@ -5,23 +5,23 @@ import { MANAGED_HOOK_TIMEOUT_SECONDS, type HookCommandConfig, type HooksConfig -} from '../agent-hooks/installation/configuration/hook-config-schema' +} from '../../agent-hooks/installation/configuration/hook-config-schema' import { createManagedCommandMatcher, removeManagedCommands, withPreviousManagedAsync -} from '../agent-hooks/installation/commands/managed-hook-command-matching' -import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' -import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' -import { isSafeUnicodeWindowsBatchHookPath } from '../agent-hooks/installation/commands/windows-hook-command' -import { wrapWindowsPowerShellEncodedCommand } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' -import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' -import { getWindowsNativeHookAgent } from '../agent-hooks/installation/commands/windows-native-hook-executable' +} from '../../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../../agent-hooks/installation/configuration/hooks-json-read' +import { isSafeUnicodeWindowsBatchHookPath } from '../../agent-hooks/installation/commands/windows-hook-command' +import { wrapWindowsPowerShellEncodedCommand } from '../../agent-hooks/installation/commands/windows-powershell-hook-launcher' +import { quotePowerShellLiteral } from '../../../shared/powershell-native-argument' +import { getWindowsNativeHookAgent } from '../../agent-hooks/installation/commands/windows-native-hook-executable' import { wrapRuntimeHomeHookCommand, wrapRuntimeHomePosixHookCommand -} from '../agent-hooks/installation/commands/runtime-home-hook-command' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +} from '../../agent-hooks/installation/commands/runtime-home-hook-command' +import { wrapWindowsDirectCmdHookCommand } from '../../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import type { ClaudeManagedHookPlan } from './claude-managed-hook-events' import { claudeManagedHookForms, diff --git a/src/main/claude/post-compact-hook-command.test.ts b/src/main/claude/hooks/post-compact-hook-command.test.ts similarity index 100% rename from src/main/claude/post-compact-hook-command.test.ts rename to src/main/claude/hooks/post-compact-hook-command.test.ts diff --git a/src/main/claude/statusline-install.ts b/src/main/claude/hooks/statusline-install.ts similarity index 89% rename from src/main/claude/statusline-install.ts rename to src/main/claude/hooks/statusline-install.ts index 30d793113f2..890fd7198c2 100644 --- a/src/main/claude/statusline-install.ts +++ b/src/main/claude/hooks/statusline-install.ts @@ -1,6 +1,6 @@ import { existsSync, rmSync, writeFileSync } from 'node:fs' -import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' -import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' +import { writeManagedScript } from '../../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' import { getManagedStatusLineCommand, getManagedStatusLineScript } from './statusline-script' import { applyManagedStatusLine, diff --git a/src/main/claude/hooks/statusline-script.test.ts b/src/main/claude/hooks/statusline-script.test.ts new file mode 100644 index 00000000000..9c71c6fdad6 --- /dev/null +++ b/src/main/claude/hooks/statusline-script.test.ts @@ -0,0 +1,105 @@ +import { spawn } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { getManagedStatusLineScript } from './statusline-script' + +const ORIGINAL_PLATFORM = process.platform + +afterEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: ORIGINAL_PLATFORM }) +}) + +describe.skipIf(process.platform === 'win32')('statusline curl throttle (posix behavioral)', () => { + const PANE_KEY = 'tab-1:00000000-0000-4000-8000-000000000000' + const dirs: string[] = [] + + afterEach(() => { + for (const dir of dirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } + }) + + function rateLimitPayload(durationMs: number): string { + return JSON.stringify({ + cost: { total_duration_ms: durationMs }, + rate_limits: { five_hour: { used_percentage: 12 } } + }) + } + + function makeHarness(): { + scriptPath: string + dir: string + curlLog: string + payloadLog: string + dateLog: string + catLog: string + } { + const dir = mkdtempSync(join(tmpdir(), 'orca-statusline-throttle-')) + dirs.push(dir) + const curlLog = join(dir, 'curl.log') + const payloadLog = join(dir, 'payload.log') + const dateLog = join(dir, 'date.log') + const catLog = join(dir, 'cat.log') + const scriptPath = join(dir, 'statusline.sh') + writeFileSync(scriptPath, getManagedStatusLineScript('posix')) + const binDir = join(dir, 'stub-bin') + mkdirSync(binDir, { recursive: true }) + writeFileSync( + join(binDir, 'curl'), + `#!/bin/sh\n/bin/cat > "${payloadLog}"\nprintf 'x\\n' >> "${curlLog}"\nexit 0\n`, + { mode: 0o755 } + ) + writeFileSync( + join(binDir, 'date'), + `#!/bin/sh\nprintf 'x\\n' >> "${dateLog}"\nprintf '2000000000\\n'\n`, + { mode: 0o755 } + ) + writeFileSync(join(binDir, 'cat'), `#!/bin/sh\nprintf 'x\\n' >> "${catLog}"\n/bin/cat "$@"\n`, { + mode: 0o755 + }) + return { scriptPath, dir, curlLog, payloadLog, dateLog, catLog } + } + + function runScript( + scriptPath: string, + dir: string, + payload: string, + paneKey = PANE_KEY + ): Promise { + return new Promise((resolve, reject) => { + const child = spawn('sh', [scriptPath], { + env: { + PATH: `${join(dir, 'stub-bin')}:${process.env.PATH ?? ''}`, + TMPDIR: dir, + ORCA_AGENT_HOOK_PORT: '65535', + ORCA_AGENT_HOOK_TOKEN: 'test-token', + ORCA_PANE_KEY: paneKey + }, + stdio: ['pipe', 'ignore', 'pipe'] + }) + let stderr = '' + child.stderr.on('data', (chunk: Buffer) => { + stderr += chunk.toString() + }) + child.on('error', reject) + child.on('close', (code) => { + if (code === 0) { + resolve() + } else { + reject(new Error(`statusline script exited ${code}: ${stderr}`)) + } + }) + child.stdin.write(payload) + child.stdin.end() + }) + } + + it('preserves multiline payloads while capturing stdin with shell builtins', async () => { + const { scriptPath, dir, payloadLog } = makeHarness() + const payload = JSON.stringify(JSON.parse(rateLimitPayload(1_000)), null, 2) + await runScript(scriptPath, dir, payload) + expect(readFileSync(payloadLog, 'utf8')).toBe(payload) + }) +}) diff --git a/src/main/claude/statusline-script.ts b/src/main/claude/hooks/statusline-script.ts similarity index 95% rename from src/main/claude/statusline-script.ts rename to src/main/claude/hooks/statusline-script.ts index 0d11d0e4344..72d457e84ba 100644 --- a/src/main/claude/statusline-script.ts +++ b/src/main/claude/hooks/statusline-script.ts @@ -1,14 +1,14 @@ import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../agent-hooks/installation/scripts/claude-background-job-guard' -import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' -import { WINDOWS_HOOK_STDIN_READER } from '../agent-hooks/installation/scripts/hook-stdin-contract' +} from '../../agent-hooks/installation/scripts/claude-background-job-guard' +import { posixCurlCommand } from '../../agent-hooks/installation/scripts/hook-post-command' +import { WINDOWS_HOOK_STDIN_READER } from '../../agent-hooks/installation/scripts/hook-stdin-contract' import { CLAUDE_STATUSLINE_MIN_POST_INTERVAL_SECONDS, CLAUDE_STATUSLINE_PATHNAME -} from '../../shared/claude-statusline-rate-limits' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +} from '../../../shared/claude-statusline-rate-limits' +import { wrapWindowsDirectCmdHookCommand } from '../../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { getManagedCommand } from './hook-settings' const STATUSLINE_CLEANUP_LABEL = 'orca_statusline_cleanup' diff --git a/src/main/claude/hooks/windows-hook-files.test.ts b/src/main/claude/hooks/windows-hook-files.test.ts new file mode 100644 index 00000000000..84afb9f2bfc --- /dev/null +++ b/src/main/claude/hooks/windows-hook-files.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import type * as osModule from 'node:os' +import { join } from 'node:path' +import * as refresh from '../../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' +import { ClaudeHookService } from '../hook-service' +import { getWindowsManagedLifecycleHook } from './hook-settings' +import { getWindowsClaudeHookPayloadPath } from './windows-hook-files' + +const { home } = vi.hoisted(() => ({ home: { path: '' } })) +vi.mock('node:os', async (original) => ({ + ...(await original()), + homedir: () => home.path +})) +vi.mock('electron', () => ({ app: { getPath: () => home.path } })) + +const platform = Object.getOwnPropertyDescriptor(process, 'platform')! +let entry: string +let payload: string +let settings: string +const service = new ClaudeHookService() + +beforeEach(() => { + home.path = mkdtempSync(join(tmpdir(), 'claude-windows-files-')) + entry = join(home.path, '.orca', 'agent-hooks', 'claude-hook.cmd') + payload = getWindowsClaudeHookPayloadPath(entry) + settings = join(home.path, '.claude', 'settings.json') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) +}) + +afterEach(() => { + Object.defineProperty(process, 'platform', platform) + vi.restoreAllMocks() + rmSync(home.path, { recursive: true, force: true }) +}) + +describe('Windows Claude hook files', () => { + it('leaves the old single-file entry intact when payload publication fails', async () => { + mkdirSync(join(home.path, '.orca', 'agent-hooks'), { recursive: true }) + const oldEntry = '@echo off\r\necho {}\r\nexit /b 0\r\n' + writeFileSync(entry, oldEntry) + vi.spyOn(refresh, 'restoreManagedScript').mockRejectedValueOnce(new Error('disk full')) + await expect(service.refreshManagedScripts()).rejects.toThrow('disk full') + expect(readFileSync(entry, 'utf8')).toBe(oldEntry) + expect(existsSync(payload)).toBe(false) + }) + + it('migrates old command forms while preserving user hooks', () => { + const encoded = getWindowsManagedLifecycleHook( + 'C:\\Users\\%name%\\.orca\\agent-hooks\\claude-hook.cmd' + ) + writeHooksJson(settings, { + hooks: { + Stop: [{ hooks: [encoded, { type: 'command', command: 'echo user-hook' }] }], + PreToolUse: [ + { + hooks: [ + { type: 'command', command: 'C:/old/.orca/agent-hooks/claude-hook.cmd || echo {}' } + ] + } + ] + } + }) + service.install() + const config = JSON.stringify(readHooksJson(settings)) + expect(config).not.toContain('|| echo {}') + expect(config).not.toContain('C:/old/') + expect(config).toContain('echo user-hook') + expect(service.getStatus().state).toBe('installed') + }) +}) diff --git a/src/main/claude/windows-hook-files.ts b/src/main/claude/hooks/windows-hook-files.ts similarity index 85% rename from src/main/claude/windows-hook-files.ts rename to src/main/claude/hooks/windows-hook-files.ts index 7b7c9620cf2..7fbc42a5777 100644 --- a/src/main/claude/windows-hook-files.ts +++ b/src/main/claude/hooks/windows-hook-files.ts @@ -1,23 +1,23 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' -import { getLockedExecutableAsidePath } from '../agent-hooks/installation/scripts/locked-executable-rename' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { writeManagedScript } from '../../agent-hooks/installation/scripts/managed-hook-script-write' +import { getLockedExecutableAsidePath } from '../../agent-hooks/installation/scripts/locked-executable-rename' import { refreshManagedScriptIfPresent, restoreManagedScript, scriptStillExists -} from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +} from '../../agent-hooks/installation/scripts/managed-hook-script-refresh' import { buildWindowsHookEnvironmentGuardLines, WINDOWS_HOOK_STDIN_DRAIN_COMMAND -} from '../agent-hooks/installation/scripts/hook-stdin-contract' +} from '../../agent-hooks/installation/scripts/hook-stdin-contract' import { resolveBundledWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME -} from '../agent-hooks/installation/commands/windows-native-hook-executable' -import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD } from '../agent-hooks/installation/scripts/claude-background-job-guard' +} from '../../agent-hooks/installation/commands/windows-native-hook-executable' +import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD } from '../../agent-hooks/installation/scripts/claude-background-job-guard' const PAYLOAD_FILE_NAME = 'claude-hook-impl.cmd' diff --git a/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts b/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts new file mode 100644 index 00000000000..667762251d4 --- /dev/null +++ b/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts @@ -0,0 +1,49 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +import { createClaudeModelCatalogProbe } from './claude-model-catalog-probe' +import { resolveStructuredAgentCommand } from '../../native-chat/agent-launch/structured-agent-command-resolution' + +const AUTH_POLICY = { account: 'system' } as const + +const HOME = (path: string): { variable: string; path: string } => ({ + variable: 'CLAUDE_CONFIG_DIR', + path +}) + +function probeDeps(command = `"${process.execPath}"`): { + resolveCommand: () => { command: string; prefixArgs: string[] } + resolveEnv: () => Record + resolveInheritedEnv: () => Promise> + resolveAuthPolicy: () => typeof AUTH_POLICY +} { + return { + resolveCommand: () => + resolveStructuredAgentCommand('claude', { + agentCmdOverrides: { claude: command } + }), + resolveEnv: () => ({ ANTHROPIC_MODEL_GATEWAY: 'https://gateway.example' }), + resolveInheritedEnv: async () => ({ PATH: '/resolved/bin', HOME: '/homes/user' }), + resolveAuthPolicy: () => AUTH_POLICY + } +} + +describe('Claude catalog availability', () => { + it('says the CLI is missing when the resolved executable is not there', async () => { + const folder = mkdtempSync(join(tmpdir(), 'orca-claude-missing-')) + try { + const missing = join(folder, 'claude with spaces', 'claude') + const probe = createClaudeModelCatalogProbe({ + ...probeDeps(), + resolveCommand: () => ({ command: missing, prefixArgs: [] }) + }) + await expect(probe(HOME('/homes/a'))).rejects.toMatchObject({ + unavailable: { reason: 'cliMissing' } + }) + } finally { + rmSync(folder, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/claude/claude-model-catalog-probe.ts b/src/main/claude/model-catalog/claude-model-catalog-probe.ts similarity index 85% rename from src/main/claude/claude-model-catalog-probe.ts rename to src/main/claude/model-catalog/claude-model-catalog-probe.ts index cac6371c9d1..fee0027363d 100644 --- a/src/main/claude/claude-model-catalog-probe.ts +++ b/src/main/claude/model-catalog/claude-model-catalog-probe.ts @@ -1,52 +1,53 @@ -import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' -import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import { withOrcaClaudeChatEntrypoint } from '../../../shared/agent-launch/startup/claude-chat-entrypoint' +import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { assertStructuredAgentResolutionCurrent, type StructuredAgentResolutionOperation -} from '../native-chat/structured-agent-command-resolution' +} from '../../native-chat/agent-launch/structured-agent-command-resolution' import { buildClaudeModelListArgs, CLAUDE_MODEL_LIST_STDIN -} from '../../shared/claude-model-list-probe' -import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { runClaudeBackgroundAttempts } from '../../shared/claude-background-run-isolation' +} from '../../../shared/claude-model-list-probe' +import { requireLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import { runClaudeBackgroundAttempts } from '../../../shared/claude-background-run-isolation' import { isCompleteClaudeModelListing, listedModels, record -} from './structured/launch/claude-structured-model-catalog' +} from '../structured/launch/claude-structured-model-catalog' import { claudeCatalogSignedOut } from './claude-model-catalog-signed-out' import { claudeFastModeSupport, wireClaudeModels -} from './structured/launch/claude-structured-catalog-listing' -import { readClaudeSettingsApplied } from './structured/launch/claude-structured-session-options' -import { readClaudeControlResponses } from './claude-control-responses' -import { claudeStructuredLaunchArgs } from './structured/launch/claude-structured-launch-args' -import { AgentModelCatalogUnavailableError } from '../native-chat/agent-model-catalog/agent-model-catalog-unavailable' -import { claudeConfigDirEnvPatch } from './claude-config-dir-pin' +} from '../structured/launch/claude-structured-catalog-listing' +import { readClaudeSettingsApplied } from '../structured/launch/claude-structured-session-options' +import { readClaudeControlResponses } from '../sdk-transport/claude-control-responses' +import { claudeStructuredLaunchArgs } from '../structured/launch/claude-structured-launch-args' +import { AgentModelCatalogUnavailableError } from '../../native-chat/agent-model-catalog/agent-model-catalog-unavailable' +import { claudeConfigDirEnvPatch } from '../structured/launch/claude-config-dir-pin' import { envWithPathRelativeTo, catalogListingDirectory -} from '../../shared/node-cli-command-resolution' +} from '../../../shared/node-cli-command-resolution' import { CLAUDE_DEFAULT_SETTING_SOURCES, resolveClaudeStructuredInvocation, type ClaudeStructuredLaunchPartDeps -} from './structured/launch/claude-structured-launch-resolution' +} from '../structured/launch/claude-structured-launch-resolution' import { resolveClaudeChildEnvSources, type ClaudeEnvDeps -} from './structured/launch/claude-structured-child-env' +} from '../structured/launch/claude-structured-child-env' import type { AgentModelCatalogProbe, - AgentModelCatalogSuccess -} from '../native-chat/agent-model-catalog/agent-model-catalog-store' -import type { AgentModelCatalogLookup } from '../native-chat/agent-model-catalog/agent-model-catalog-discovery' + AgentModelCatalogLookup +} from '../../native-chat/agent-model-catalog/agent-model-catalog-discovery' +import type { AgentModelCatalogSuccess } from '../../native-chat/agent-model-catalog/agent-model-catalog-entry' + import { AgentModelCatalogProbeError, runAgentModelCatalogListing -} from '../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' +} from '../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' export type ClaudeModelCatalogProbeDeps = ClaudeEnvDeps & Pick & { diff --git a/src/main/claude/claude-model-catalog-signed-out.ts b/src/main/claude/model-catalog/claude-model-catalog-signed-out.ts similarity index 92% rename from src/main/claude/claude-model-catalog-signed-out.ts rename to src/main/claude/model-catalog/claude-model-catalog-signed-out.ts index 5d9cbabbccd..a7834e42a27 100644 --- a/src/main/claude/claude-model-catalog-signed-out.ts +++ b/src/main/claude/model-catalog/claude-model-catalog-signed-out.ts @@ -1,4 +1,4 @@ -import { record } from './structured/launch/claude-structured-model-catalog' +import { record } from '../structured/launch/claude-structured-model-catalog' /** A first-party CLI with no credential and no other provider or endpoint is signed out. */ export function claudeCatalogSignedOut( diff --git a/src/main/claude/claude-agent-sdk-control-requests.ts b/src/main/claude/sdk-transport/claude-agent-sdk-control-requests.ts similarity index 100% rename from src/main/claude/claude-agent-sdk-control-requests.ts rename to src/main/claude/sdk-transport/claude-agent-sdk-control-requests.ts diff --git a/src/main/claude/claude-agent-sdk-import-boundary.test.ts b/src/main/claude/sdk-transport/claude-agent-sdk-import-boundary.test.ts similarity index 86% rename from src/main/claude/claude-agent-sdk-import-boundary.test.ts rename to src/main/claude/sdk-transport/claude-agent-sdk-import-boundary.test.ts index d2ec78f6ac9..538268b5b33 100644 --- a/src/main/claude/claude-agent-sdk-import-boundary.test.ts +++ b/src/main/claude/sdk-transport/claude-agent-sdk-import-boundary.test.ts @@ -5,7 +5,7 @@ describe('claude agent SDK import boundary', () => { it('leaves the Windows executable-search environment alone when the runtime loads', async () => { // Remove any shell-provided value before checking this isolated test process. delete process.env.NoDefaultCurrentDirectoryInExePath - await import('../runtime/agent-session/structured-agent-session-runtime') + await import('../../runtime/agent-session/structured-agent-session-runtime') expect(process.env.NoDefaultCurrentDirectoryInExePath).toBeUndefined() }) diff --git a/src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.test.ts b/src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.test.ts new file mode 100644 index 00000000000..37379ed2972 --- /dev/null +++ b/src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.test.ts @@ -0,0 +1,28 @@ +import type { SDKUserMessage } from '@anthropic-ai/claude-agent-sdk' +import { describe, expect, it } from 'vitest' +import { + claudeUserMessageWasProvablyUnwritten, + createClaudeUserMessageQueue +} from './claude-agent-sdk-user-message-queue' + +// Model the SDK pump: it resumes only after transport.write and abandons the iterator on failure. +const frame = (text: string): SDKUserMessage => + ({ + type: 'user', + message: { role: 'user', content: [{ type: 'text', text }] } + }) as unknown as SDKUserMessage + +describe('claude user message queue', () => { + it('marks only frames still queued in Orca as provably unwritten', async () => { + const queue = createClaudeUserMessageQueue() + const pump = queue.messages[Symbol.asyncIterator]() + const inFlight = queue.push(frame('first')).catch((caught: unknown) => caught) + await pump.next() + const queued = queue.push(frame('second')).catch((caught: unknown) => caught) + + queue.fail(new Error('claude stream-json exited: child died')) + + expect(claudeUserMessageWasProvablyUnwritten(await inFlight)).toBe(false) + expect(claudeUserMessageWasProvablyUnwritten(await queued)).toBe(true) + }) +}) diff --git a/src/main/claude/claude-agent-sdk-user-message-queue.ts b/src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.ts similarity index 100% rename from src/main/claude/claude-agent-sdk-user-message-queue.ts rename to src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.ts diff --git a/src/main/claude/claude-control-responses.ts b/src/main/claude/sdk-transport/claude-control-responses.ts similarity index 90% rename from src/main/claude/claude-control-responses.ts rename to src/main/claude/sdk-transport/claude-control-responses.ts index 0a5b6da70f9..df1f7ab318c 100644 --- a/src/main/claude/claude-control-responses.ts +++ b/src/main/claude/sdk-transport/claude-control-responses.ts @@ -1,4 +1,4 @@ -import { assertJsonTextStructureWithinLimits } from '../../shared/json-stream/json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../../shared/json-stream/json-text-structure-limit' const CONTROL_JSON_LIMITS = { structuralTokens: 64 * 1024, nestingDepth: 16 } as const diff --git a/src/main/claude/claude-plugin-ui.ts b/src/main/claude/sdk-transport/claude-plugin-ui.ts similarity index 80% rename from src/main/claude/claude-plugin-ui.ts rename to src/main/claude/sdk-transport/claude-plugin-ui.ts index bbe4bd73474..9797894973e 100644 --- a/src/main/claude/claude-plugin-ui.ts +++ b/src/main/claude/sdk-transport/claude-plugin-ui.ts @@ -2,9 +2,9 @@ import { agentSessionFailureFact, providerDiagnostic, type SubmissionRejectionFact -} from '../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureSentence } from '../../shared/agent-session/failures/agent-session-failure-words' -import { isProviderRecord } from '../provider-process/provider-json-record' +} from '../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureSentence } from '../../../shared/agent-session/failures/agent-session-failure-words' +import { isProviderRecord } from '../../provider-process/provider-json-record' function nonemptyString(value: unknown): string | null { return typeof value === 'string' && value.trim() ? value.trim() : null diff --git a/src/main/claude/claude-startup-failure.ts b/src/main/claude/sdk-transport/claude-startup-failure.ts similarity index 90% rename from src/main/claude/claude-startup-failure.ts rename to src/main/claude/sdk-transport/claude-startup-failure.ts index d0beb47eb94..3db152e61c9 100644 --- a/src/main/claude/claude-startup-failure.ts +++ b/src/main/claude/sdk-transport/claude-startup-failure.ts @@ -1,4 +1,4 @@ -import { findInErrorChain } from '../provider-process/provider-error-chain' +import { findInErrorChain } from '../../provider-process/provider-error-chain' import { ClaudeControlRequestError } from './claude-agent-sdk-control-requests' import { agentSessionAcquireFailure, @@ -6,7 +6,7 @@ import { providerResourcePressure, type AgentSessionStartAnswer, type AgentSessionStartFailure -} from '../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' +} from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' /** SDK runtime tags are not in its public Error declaration. */ export function claudeStartupErrorClass(error: Error): string | undefined { diff --git a/src/main/claude/sdk-transport/claude-stream-json-connection.test.ts b/src/main/claude/sdk-transport/claude-stream-json-connection.test.ts new file mode 100644 index 00000000000..333fbd25cb8 --- /dev/null +++ b/src/main/claude/sdk-transport/claude-stream-json-connection.test.ts @@ -0,0 +1,110 @@ +import type { ChildProcess } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { spawnProcess } from '@orca/process-host' +import type { ProcessSpec } from '@orca/process-host/process-spec' + +import { + openClaudeStreamJsonConnection, + type ClaudeStreamJsonConnection, + type ClaudeStreamJsonLaunch +} from '../claude-stream-json-connection' +import { CLAUDE_STRUCTURED_BASE_OPTIONS } from '../structured/launch/claude-structured-launch-resolution' + +// Exercise the real SDK against a scripted child CLI. +const FAKE_CLI = join(__dirname, '../__fixtures__', 'claude-agent-sdk-scripted-cli.mjs') +const SESSION_ID = '5348c19f-6a54-4c2e-9c68-9c2b1a3d4e5f' +const HOLD_OPEN = { delayMs: 10_000 } + +type ScriptedCliReport = { + argv: string[] + controlRequests: { request_id: string; request: { subtype: string } }[] + controlResponses: { response: { request_id: string; response?: unknown } }[] + userMessages: Record[] + descendantPid: number | null +} + +const scratchDirs: string[] = [] +const openConnections: ClaudeStreamJsonConnection[] = [] +const childClosures: Promise[] = [] + +afterEach(async () => { + for (const connection of openConnections.splice(0)) { + await connection.close() + } + await Promise.all(childClosures.splice(0)) + for (const dir of scratchDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }) + } + spawned.splice(0) + spawnedChildren.splice(0) + vi.unstubAllEnvs() +}) + +function scriptScenario( + steps: Record[], + controlResponses: Record = {} +) { + const dir = mkdtempSync(join(tmpdir(), 'claude-sdk-connection-')) + scratchDirs.push(dir) + const scenarioPath = join(dir, 'scenario.json') + const reportPath = join(dir, 'report.json') + writeFileSync(scenarioPath, JSON.stringify({ steps, controlResponses })) + return { + cwd: dir, + env: { + PATH: process.env.PATH ?? '', + ORCA_SDK_CONTRACT_SCENARIO_PATH: scenarioPath, + ORCA_SDK_CONTRACT_REPORT_PATH: reportPath + }, + readReport: () => JSON.parse(readFileSync(reportPath, 'utf8')) as ScriptedCliReport + } +} + +function launchFor( + scenario: { cwd: string; env: Record }, + env: Record = {} +): ClaudeStreamJsonLaunch { + return { + pathToClaudeCodeExecutable: FAKE_CLI, + options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, sessionId: SESSION_ID }, + cwd: scenario.cwd, + env: { ...scenario.env, ...env } + } +} + +const spawned: ProcessSpec[] = [] +const spawnedChildren: ChildProcess[] = [] + +async function open( + launch: ClaudeStreamJsonLaunch, + handlers: Parameters[1] = {} +): Promise { + const connection = await openClaudeStreamJsonConnection(launch, handlers, (spec) => { + spawned.push(spec) + const child = spawnProcess(spec) + spawnedChildren.push(child) + childClosures.push(new Promise((resolve) => child.once('close', () => resolve()))) + return child + }) + openConnections.push(connection) + return connection +} + +describe('Claude stream-json connection', () => { + it('completes task Stop through the real SDK while semantic reading is paused', async () => { + const scenario = scriptScenario([HOLD_OPEN]) + const connection = await open(launchFor(scenario)) + await connection.initializationResult() + connection.pauseReading?.() + await connection.stopTask('owned-shell') + expect(scenario.readReport().controlRequests).toContainEqual( + expect.objectContaining({ + request: expect.objectContaining({ subtype: 'stop_task', task_id: 'owned-shell' }) + }) + ) + connection.resumeReading?.() + }) +}) diff --git a/src/main/claude/claude-stream-json-exit-error.ts b/src/main/claude/sdk-transport/claude-stream-json-exit-error.ts similarity index 82% rename from src/main/claude/claude-stream-json-exit-error.ts rename to src/main/claude/sdk-transport/claude-stream-json-exit-error.ts index 8f8ec98980f..eea66222633 100644 --- a/src/main/claude/claude-stream-json-exit-error.ts +++ b/src/main/claude/sdk-transport/claude-stream-json-exit-error.ts @@ -1,12 +1,12 @@ import { providerDiagnostic, withProviderDiagnostic -} from '../../shared/agent-session/failures/agent-session-failure' -import type { ProviderProcessExit } from '../provider-process/managed-provider-process' -import { providerExitStatusText } from '../provider-process/provider-process-exit-status' -import { providerStderrForDisplay } from '../provider-process/provider-spawn-failure-report' -import '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { AgentSessionAcquisitionRefusal } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' +} from '../../../shared/agent-session/failures/agent-session-failure' +import type { ProviderProcessExit } from '../../provider-process/managed-provider-process' +import { providerExitStatusText } from '../../provider-process/provider-process-exit-status' +import { providerStderrForDisplay } from '../../provider-process/provider-spawn-failure-report' +import '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { AgentSessionAcquisitionRefusal } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' import { ClaudeControlRequestError } from './claude-agent-sdk-control-requests' // Claude Code's own startup refusal: as root it exits before initialize rather than skip permissions. diff --git a/src/main/claude/statusline-script.test.ts b/src/main/claude/statusline-script.test.ts deleted file mode 100644 index 73b56bf650e..00000000000 --- a/src/main/claude/statusline-script.test.ts +++ /dev/null @@ -1,186 +0,0 @@ -import { spawn } from 'node:child_process' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { getManagedStatusLineScript } from './statusline-script' - -const ORIGINAL_PLATFORM = process.platform - -afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: ORIGINAL_PLATFORM }) -}) - -describe.skipIf(process.platform === 'win32')('statusline curl throttle (posix behavioral)', () => { - const LEAF_ID = '00000000-0000-4000-8000-000000000000' - const PANE_KEY = 'tab-1:00000000-0000-4000-8000-000000000000' - const dirs: string[] = [] - - afterEach(() => { - for (const dir of dirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } - }) - - function rateLimitPayload(durationMs: number): string { - return JSON.stringify({ - cost: { total_duration_ms: durationMs }, - rate_limits: { five_hour: { used_percentage: 12 } } - }) - } - - function makeHarness(): { - scriptPath: string - dir: string - curlLog: string - payloadLog: string - dateLog: string - catLog: string - } { - const dir = mkdtempSync(join(tmpdir(), 'orca-statusline-throttle-')) - dirs.push(dir) - const curlLog = join(dir, 'curl.log') - const payloadLog = join(dir, 'payload.log') - const dateLog = join(dir, 'date.log') - const catLog = join(dir, 'cat.log') - const scriptPath = join(dir, 'statusline.sh') - writeFileSync(scriptPath, getManagedStatusLineScript('posix')) - const binDir = join(dir, 'stub-bin') - mkdirSync(binDir, { recursive: true }) - writeFileSync( - join(binDir, 'curl'), - `#!/bin/sh\n/bin/cat > "${payloadLog}"\nprintf 'x\\n' >> "${curlLog}"\nexit 0\n`, - { mode: 0o755 } - ) - writeFileSync( - join(binDir, 'date'), - `#!/bin/sh\nprintf 'x\\n' >> "${dateLog}"\nprintf '2000000000\\n'\n`, - { mode: 0o755 } - ) - writeFileSync(join(binDir, 'cat'), `#!/bin/sh\nprintf 'x\\n' >> "${catLog}"\n/bin/cat "$@"\n`, { - mode: 0o755 - }) - return { scriptPath, dir, curlLog, payloadLog, dateLog, catLog } - } - - function runScript( - scriptPath: string, - dir: string, - payload: string, - paneKey = PANE_KEY - ): Promise { - return new Promise((resolve, reject) => { - const child = spawn('sh', [scriptPath], { - env: { - PATH: `${join(dir, 'stub-bin')}:${process.env.PATH ?? ''}`, - TMPDIR: dir, - ORCA_AGENT_HOOK_PORT: '65535', - ORCA_AGENT_HOOK_TOKEN: 'test-token', - ORCA_PANE_KEY: paneKey - }, - stdio: ['pipe', 'ignore', 'pipe'] - }) - let stderr = '' - child.stderr.on('data', (chunk: Buffer) => { - stderr += chunk.toString() - }) - child.on('error', reject) - child.on('close', (code) => { - if (code === 0) { - resolve() - } else { - reject(new Error(`statusline script exited ${code}: ${stderr}`)) - } - }) - child.stdin.write(payload) - child.stdin.end() - }) - } - - function lineCount(logPath: string): number { - try { - return readFileSync(logPath, 'utf8').split('\n').filter(Boolean).length - } catch { - return 0 - } - } - - function stampPathFor(dir: string, leafId = LEAF_ID): string { - return join(dir, `orca-claude-statusline-last-${leafId}`) - } - - it('spawns one curl and no capture or clock subprocesses across 30 rapid ticks', async () => { - const { scriptPath, dir, curlLog, dateLog, catLog } = makeHarness() - for (let index = 0; index < 30; index += 1) { - await runScript(scriptPath, dir, rateLimitPayload(1_000 + index * 100)) - } - expect(lineCount(curlLog)).toBe(1) - expect(lineCount(dateLog)).toBe(0) - expect(lineCount(catLog)).toBe(0) - expect(readFileSync(stampPathFor(dir), 'utf8')).toMatch(/^[0-9]+$/) - }) - - it('posts again once the interval has elapsed', async () => { - const { scriptPath, dir, curlLog } = makeHarness() - await runScript(scriptPath, dir, rateLimitPayload(1_000)) - await runScript(scriptPath, dir, rateLimitPayload(16_000)) - expect(lineCount(curlLog)).toBe(2) - }) - - it('stays bounded and keeps a valid stamp under overlapping same-pane ticks', async () => { - const { scriptPath, dir, curlLog } = makeHarness() - // Lock-free stamps fail open: overlapping ticks may post more than once but must throttle subsequent ticks. - await Promise.all( - Array.from({ length: 10 }, () => runScript(scriptPath, dir, rateLimitPayload(1_000))) - ) - const burstPosts = lineCount(curlLog) - expect(burstPosts).toBeGreaterThanOrEqual(1) - expect(readFileSync(stampPathFor(dir), 'utf8')).toBe('1') - for (let index = 0; index < 5; index += 1) { - await runScript(scriptPath, dir, rateLimitPayload(2_000 + index * 100)) - } - expect(lineCount(curlLog)).toBe(burstPosts) - }) - - it('preserves multiline payloads while capturing stdin with shell builtins', async () => { - const { scriptPath, dir, payloadLog } = makeHarness() - const payload = JSON.stringify(JSON.parse(rateLimitPayload(1_000)), null, 2) - await runScript(scriptPath, dir, payload) - expect(readFileSync(payloadLog, 'utf8')).toBe(payload) - }) - - it('fails open and repairs a leading-zero stamp instead of dying in arithmetic', async () => { - const { scriptPath, dir, curlLog } = makeHarness() - // 008 is invalid octal in dash arithmetic and must not prevent stamp repair. - writeFileSync(stampPathFor(dir), '008') - await runScript(scriptPath, dir, rateLimitPayload(1_000)) - expect(lineCount(curlLog)).toBe(1) - expect(readFileSync(stampPathFor(dir), 'utf8')).toBe('1') - }) - - it('uses only the stable leaf id for temp files', async () => { - const { scriptPath, dir, curlLog } = makeHarness() - const paneKey = `${'path/segment/'.repeat(30)}tab:${LEAF_ID}` - await runScript(scriptPath, dir, rateLimitPayload(1_000), paneKey) - await runScript(scriptPath, dir, rateLimitPayload(2_000), paneKey) - expect(lineCount(curlLog)).toBe(1) - expect(readFileSync(stampPathFor(dir), 'utf8')).toBe('1') - }) - - it('keeps legacy numeric pane ids isolated by tab', async () => { - const { scriptPath, dir, curlLog } = makeHarness() - await runScript(scriptPath, dir, rateLimitPayload(1_000), 'legacy-tab-a:1') - await runScript(scriptPath, dir, rateLimitPayload(1_000), 'legacy-tab-b:1') - expect(lineCount(curlLog)).toBe(2) - expect(readFileSync(stampPathFor(dir, 'legacy-tab-a_1'), 'utf8')).toBe('1') - expect(readFileSync(stampPathFor(dir, 'legacy-tab-b_1'), 'utf8')).toBe('1') - }) - - it('never touches curl or the stamp for payloads without rate_limits', async () => { - const { scriptPath, dir, curlLog, dateLog } = makeHarness() - await runScript(scriptPath, dir, '{"model":{"id":"claude-fable-5"}}') - expect(lineCount(curlLog)).toBe(0) - expect(lineCount(dateLog)).toBe(0) - expect(() => readFileSync(stampPathFor(dir), 'utf8')).toThrow() - }) -}) diff --git a/src/main/claude/structured/claude-conversation-title-owner.test.ts b/src/main/claude/structured/claude-conversation-title-owner.test.ts deleted file mode 100644 index b6e29f72b51..00000000000 --- a/src/main/claude/structured/claude-conversation-title-owner.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { acquired, fakeClaude, PROVIDER_SESSION_ID } from './claude-structured-session-test-support' -import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' - -afterEach(() => vi.restoreAllMocks()) - -it('retains retirement knowledge when the optional title method is missing', async () => { - const cli = fakeClaude() - const adapter = await acquired(cli) - try { - const record = agentSessionRecordFixture() - record.sessionId = 'session-1' - record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID - const owner = adapter.captureConversationTitleOwner(record)! - expect(owner.isCurrent(record)).toBe(true) - expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBeNull() - await adapter.closeAll() - expect(owner.isCurrent(record)).toBe(false) - } finally { - await adapter.closeAll() - cli.dispose() - } -}) diff --git a/src/main/claude/structured/claude-conversation-title-owner.ts b/src/main/claude/structured/claude-conversation-title-owner.ts index b7e4c11091a..db0809be950 100644 --- a/src/main/claude/structured/claude-conversation-title-owner.ts +++ b/src/main/claude/structured/claude-conversation-title-owner.ts @@ -1,8 +1,8 @@ import { resolve } from 'node:path' import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' import { agentSessionAccountHomesEqual } from '../../../shared/agent-session/lifecycle/agent-session-account-home' -import { claudeNamingContextId } from '../claude-conversation-naming' -import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS } from '../claude-cli-flag-support' +import { claudeNamingContextId } from '../conversation-naming/claude-conversation-naming' +import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS } from '../cli-capabilities/claude-cli-flag-support' import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import type { ClaudeSession } from './claude-structured-session-state' diff --git a/src/main/claude/structured/claude-full-access-policy.ts b/src/main/claude/structured/claude-full-access-policy.ts index 7482b266156..8bfd7c0a19a 100644 --- a/src/main/claude/structured/claude-full-access-policy.ts +++ b/src/main/claude/structured/claude-full-access-policy.ts @@ -1,5 +1,5 @@ import { StringDecoder } from 'node:string_decoder' -import { isRootClaudeFrame } from '../claude-turn-opening' +import { isRootClaudeFrame } from './turns/claude-turn-opening' import { readClaudeFrameString, readClaudeReportedPermissionMode diff --git a/src/main/claude/structured/claude-owned-task-send.test.ts b/src/main/claude/structured/claude-owned-task-send.test.ts deleted file mode 100644 index 1f842127849..00000000000 --- a/src/main/claude/structured/claude-owned-task-send.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { expect, it } from 'vitest' -import { - adapterFor, - claudeFrame, - fakeClaude, - identityFor -} from './claude-structured-session-test-support' -import { PARENT_TASK_STOP } from '../claude-parent-task-frames.test-fixture' -import { createQueuedMessageTestRig } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' -import { eventually } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture' -import { HOST_TEST_SESSION as SESSION } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' - -it('delivers an ordinary send after an owned roster/start refresh without inventing root work', async () => { - const claude = fakeClaude() - const evidence: AgentChildWorkEvidence[] = [] - const rig = await createQueuedMessageTestRig({ agent: 'claude' }) - const adapter = adapterFor( - claude, - {}, - [], - [], - undefined, - undefined, - (_sessionId, batch) => evidence.push(...batch), - (outcome) => { - void rig.host.settleLateDispatch({ ...outcome, sessionId: SESSION }) - } - ) - let acquired = false - try { - rig.dispatch.mockImplementation(async (input) => { - if (!acquired) { - await adapter.acquire({ - identity: identityFor(SESSION), - fence: 1, - spawnToken: 'spawn-1', - events: rig.providerEvents() - }) - acquired = true - } - return adapter.dispatch({ ...input, sessionId: SESSION, fence: 1 }) - }) - const first = rig.send('start the work') - expect(await first.result).toMatchObject({ ok: true }) - await eventually(async () => - expect((await rig.submission(first.id))?.dispatchState).toBe('accepted') - ) - const connection = claude.connections[0]! - claudeFrame(connection, { - type: 'assistant', - uuid: 'root-answer', - parent_tool_use_id: null, - message: { role: 'assistant', content: [{ type: 'text', text: 'Started.' }] } - }) - claudeFrame(connection, { - type: 'result', - subtype: 'success', - uuid: 'root-result', - parent_tool_use_id: null, - duration_ms: 1000 - }) - await rig.host.collaboratorsForTests().runtimeState.flushAllEventSinks() - expect(rig.host.currentWork(SESSION)!.working()).toBe(false) - - // Recorded CLI roster has no tool alias; the following start enriches that same task. - const roster = PARENT_TASK_STOP[2]!.frame - claudeFrame(connection, { - ...roster, - tasks: Array.isArray(roster.tasks) ? roster.tasks.slice(1) : [] - }) - claudeFrame(connection, PARENT_TASK_STOP[3]!.frame) - await rig.host.collaboratorsForTests().runtimeState.flushAllEventSinks() - const snapshot = await rig.host.journalSnapshot(SESSION) - const children = snapshot.items.filter( - (item) => - item.body.kind === 'message' && - item.body.blocks.some( - (block) => block.type === 'background-task' && block.taskId === 'shell-child' - ) - ) - expect(children).toHaveLength(1) - expect(children[0]).toMatchObject({ agentId: 'shell-child', parentAgentId: 'agent-parent' }) - expect(evidence).toContainEqual( - expect.objectContaining({ - type: 'live', - child: expect.objectContaining({ - handle: expect.objectContaining({ id: 'shell-child' }), - ownerId: 'agent-parent', - stoppable: true - }) - }) - ) - const rootAfterChild = rig.host - .collaboratorsForTests() - .sessions.get(SESSION)! - .journal.runningTurn() - - const followup = rig.send('continue normally') - expect(await followup.result).toMatchObject({ ok: true }) - await eventually(async () => - expect((await rig.submission(followup.id))?.handedOverAt).toBeDefined() - ) - expect(rootAfterChild).toBeNull() - expect(connection.sent).toHaveLength(2) - expect(connection.sent[1]).toMatchObject({ - message: { - content: [{ type: 'text', text: 'continue normally' }] - } - }) - } finally { - await adapter.closeAll() - await rig.dispose() - claude.dispose() - } -}) diff --git a/src/main/claude/structured/claude-structured-agent-definition.ts b/src/main/claude/structured/claude-structured-agent-definition.ts index d0bab52ff35..c1bef215b6c 100644 --- a/src/main/claude/structured/claude-structured-agent-definition.ts +++ b/src/main/claude/structured/claude-structured-agent-definition.ts @@ -12,6 +12,7 @@ export const CLAUDE_STRUCTURED_AGENT: DirectoryAccountAgentDefinition = { fork: 'checkpoint', compact: true, compactInstructions: true, + compactBesideBackgroundTasks: true, threadGoal: false, contextUsage: true, imagePrompts: true, diff --git a/src/main/claude/structured/claude-structured-control-actions.ts b/src/main/claude/structured/claude-structured-control-actions.ts index f26d63b1ec3..e99d00ae7e7 100644 --- a/src/main/claude/structured/claude-structured-control-actions.ts +++ b/src/main/claude/structured/claude-structured-control-actions.ts @@ -1,14 +1,14 @@ import type { PermissionResult } from '@anthropic-ai/claude-agent-sdk' import type { AgentChildWorkStopAcknowledgement } from '../../../shared/agent-status/child-work/agent-child-work-stop-targets' -import type { ClaudePromptClaim } from '../claude-prompt-registry' +import type { ClaudePromptClaim } from './permissions/claude-prompt-registry' import { ClaudeControlRequestError, ClaudeControlRequestTimeoutError -} from '../claude-agent-sdk-control-requests' +} from '../sdk-transport/claude-agent-sdk-control-requests' import { settleCancelledClaudeDispatchWaiters } from './claude-structured-dispatch' -import type { ClaudeLateDispatchSettlement } from '../claude-replay-turn-resolution' +import type { ClaudeLateDispatchSettlement } from './turns/claude-replay-turn-resolution' import type { ClaudeSession } from './claude-structured-session-state' -import { CLAUDE_STOP_GRACE_MS } from '../claude-request-end-wait' +import { CLAUDE_STOP_GRACE_MS } from './turns/claude-request-end-wait' const INTERRUPT_CANCEL_QUEUED_CAPABILITY = 'interrupt_cancel_queued_v1' diff --git a/src/main/claude/structured/claude-structured-dispatch-admission.test.ts b/src/main/claude/structured/claude-structured-dispatch-admission.test.ts deleted file mode 100644 index 3e7129c86cb..00000000000 --- a/src/main/claude/structured/claude-structured-dispatch-admission.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { dispatchClaudeTurn } from './claude-structured-dispatch' -import { resolveClaudeReplayTurn } from '../claude-replay-turn-resolution' -import { sessionFor, userMessage, userReplayFrame } from './claude-structured-dispatch-test-support' - -function resolveClaudeReplayWaiter(...args: Parameters): boolean { - return resolveClaudeReplayTurn(...args) !== null -} - -describe('Claude structured dispatch admission', () => { - it('opens queued exact replays with the origin and the send owned by each send', async () => { - const session = sessionFor() - await dispatchClaudeTurn(session, { - clientMessageId: 'client-a', - body: userMessage([{ type: 'text', text: 'a' }]), - requestedAt: 100 - }) - const aUuid = session.dispatchWaiters[0]!.sentUuid - expect(resolveClaudeReplayTurn(session, userReplayFrame(aUuid, 'a'))).toEqual({ - requestedAt: 100, - clientMessageId: 'client-a' - }) - - await dispatchClaudeTurn(session, { - clientMessageId: 'client-b', - body: userMessage([{ type: 'text', text: 'b' }]), - requestedAt: 200 - }) - await dispatchClaudeTurn(session, { - clientMessageId: 'client-c', - body: userMessage([{ type: 'text', text: 'c' }]), - requestedAt: 300 - }) - const [b, c] = session.dispatchWaiters - - expect(resolveClaudeReplayTurn(session, userReplayFrame(b!.sentUuid, 'b'))).toEqual({ - requestedAt: 200, - clientMessageId: 'client-b' - }) - expect(resolveClaudeReplayTurn(session, userReplayFrame(c!.sentUuid, 'c'))).toEqual({ - requestedAt: 300, - clientMessageId: 'client-c' - }) - }) - - it('settles a send queued behind a running turn when that turn starts, with no doubt in between', async () => { - vi.useFakeTimers() - try { - const session = sessionFor() - const settled = vi.fn() - const running = await dispatchClaudeTurn(session, { - clientMessageId: 'client-1', - body: userMessage([{ type: 'text', text: 'one' }]) - }) - const runningUuid = session.dispatchWaiters[0]!.sentUuid - expect(resolveClaudeReplayWaiter(session, userReplayFrame(runningUuid, 'one'), settled)).toBe( - true - ) - - const queued = await dispatchClaudeTurn(session, { - clientMessageId: 'client-2', - body: userMessage([{ type: 'text', text: 'two' }]) - }) - const queuedUuid = session.dispatchWaiters[0]!.sentUuid - expect(running).toEqual({ state: 'admitted' }) - expect(queued).toEqual({ state: 'admitted' }) - - await vi.advanceTimersByTimeAsync(10 * 60_000) - expect(session.dispatchWaiters).toHaveLength(1) - expect(session.retiredDispatchWaiters).toHaveLength(0) - expect(settled).toHaveBeenCalledTimes(1) - - expect(resolveClaudeReplayWaiter(session, userReplayFrame(queuedUuid, 'two'), settled)).toBe( - true - ) - expect(settled).toHaveBeenLastCalledWith({ - clientMessageId: 'client-2', - providerIdentity: { provider: 'claude', sessionId: 'provider-session', uuid: queuedUuid } - }) - expect(session.dispatchWaiters).toHaveLength(0) - } finally { - vi.useRealTimers() - } - }) - - it('bounds pending replay identities instead of retaining an unbounded queue', async () => { - const session = sessionFor() - for (let index = 0; index < 64; index += 1) { - await expect( - dispatchClaudeTurn(session, { - clientMessageId: `client-${index}`, - body: userMessage([{ type: 'text', text: String(index) }]) - }) - ).resolves.toEqual({ state: 'admitted' }) - } - - await expect( - dispatchClaudeTurn(session, { - clientMessageId: 'client-over-capacity', - body: userMessage([{ type: 'text', text: 'one too many' }]) - }) - ).resolves.toEqual({ - state: 'rejected', - reason: 'claude structured dispatch queue is full', - rejection: { kind: 'queueFull' } - }) - expect(session.dispatchWaiters).toHaveLength(64) - expect(session.connection.send).toHaveBeenCalledTimes(64) - }) -}) diff --git a/src/main/claude/structured/claude-structured-dispatch-attachment-rejection.test.ts b/src/main/claude/structured/claude-structured-dispatch-attachment-rejection.test.ts index 813559ff937..678dd26d2a8 100644 --- a/src/main/claude/structured/claude-structured-dispatch-attachment-rejection.test.ts +++ b/src/main/claude/structured/claude-structured-dispatch-attachment-rejection.test.ts @@ -1,4 +1,3 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' @@ -6,79 +5,6 @@ import { dispatchClaudeTurn } from './claude-structured-dispatch' import { sessionFor, userMessage } from './claude-structured-dispatch-test-support' describe('Claude structured dispatch attachment rejections', () => { - it('rejects more than twenty URL images before sending', async () => { - const session = sessionFor() - const body = userMessage( - Array.from({ length: 21 }, (_, index) => ({ - type: 'image-ref' as const, - url: `https://example.test/${index}.png` - })) - ) - - await expect( - dispatchClaudeTurn(session, { clientMessageId: 'client-1', body }) - ).resolves.toEqual({ - state: 'rejected', - reason: 'Claude accepts at most 20 images in one message, so this message was not sent.', - rejection: { kind: 'attachmentInvalid', attachment: { reason: 'tooMany', limit: 20 } } - }) - expect(session.connection.send).not.toHaveBeenCalled() - }) - - it('rejects local images whose aggregate size exceeds twenty MiB', async () => { - const directory = await mkdtemp(join(tmpdir(), 'orca-claude-images-')) - try { - const paths = await Promise.all( - Array.from({ length: 5 }, async (_, index) => { - const path = join(directory, `${index}.png`) - await writeFile(path, Buffer.alloc(5 * 1024 * 1024)) - return path - }) - ) - const session = sessionFor() - const body = userMessage(paths.map((path) => ({ type: 'image-ref' as const, path }))) - - await expect( - dispatchClaudeTurn(session, { clientMessageId: 'client-1', body }) - ).resolves.toEqual({ - state: 'rejected', - reason: - 'The images on this message add up to more than 20 MB, so the message was not sent.', - rejection: { - kind: 'attachmentInvalid', - attachment: { reason: 'totalTooLarge', limit: 20 * 1024 * 1024 } - } - }) - expect(session.connection.send).not.toHaveBeenCalled() - } finally { - await rm(directory, { recursive: true, force: true }) - } - }) - - it('rejects a local image by actual bytes read beyond the per-image cap', async () => { - const directory = await mkdtemp(join(tmpdir(), 'orca-claude-image-')) - try { - const path = join(directory, 'oversized.png') - await writeFile(path, Buffer.alloc(5 * 1024 * 1024 + 1)) - const session = sessionFor() - const body = userMessage([{ type: 'image-ref', path }]) - - await expect( - dispatchClaudeTurn(session, { clientMessageId: 'client-1', body }) - ).resolves.toEqual({ - state: 'rejected', - reason: 'An image on this message is larger than 5 MB, so the message was not sent.', - rejection: { - kind: 'attachmentInvalid', - attachment: { reason: 'tooLarge', limit: 5 * 1024 * 1024 } - } - }) - expect(session.connection.send).not.toHaveBeenCalled() - } finally { - await rm(directory, { recursive: true, force: true }) - } - }) - it('rejects an attachment it cannot read with the generic sentence and no path', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const session = sessionFor() diff --git a/src/main/claude/structured/claude-structured-dispatch-content.test.ts b/src/main/claude/structured/claude-structured-dispatch-content.test.ts index d6d19c1e42b..8853e02215c 100644 --- a/src/main/claude/structured/claude-structured-dispatch-content.test.ts +++ b/src/main/claude/structured/claude-structured-dispatch-content.test.ts @@ -1,3 +1,6 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it } from 'vitest' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' import { claudeDispatchMessageContent } from './claude-structured-dispatch-content' @@ -19,4 +22,27 @@ describe('claudeDispatchMessageContent', () => { { type: 'text', text: '/goal ship the parser' } ]) }) + + it('sends a local image over the API per-image limit for Claude to shrink', async () => { + const directory = await mkdtemp(join(tmpdir(), 'orca-claude-image-')) + try { + const path = join(directory, 'retina-screenshot.png') + await writeFile(path, Buffer.alloc(6 * 1024 * 1024, 1)) + + const content = await claudeDispatchMessageContent(userMessage([{ type: 'image-ref', path }])) + + expect(content).toEqual([ + { + type: 'image', + source: { + type: 'base64', + media_type: 'image/png', + data: Buffer.alloc(6 * 1024 * 1024, 1).toString('base64') + } + } + ]) + } finally { + await rm(directory, { recursive: true, force: true }) + } + }) }) diff --git a/src/main/claude/structured/claude-structured-dispatch-content.ts b/src/main/claude/structured/claude-structured-dispatch-content.ts index 3d3f691bbef..5f28bf4a20f 100644 --- a/src/main/claude/structured/claude-structured-dispatch-content.ts +++ b/src/main/claude/structured/claude-structured-dispatch-content.ts @@ -13,6 +13,12 @@ import { type AgentJournalDispatchRejection } from '../../../shared/agent-session/failures/agent-session-failure-words' import { TUI_AGENT_DISPLAY_NAMES } from '../../../shared/agent-launch/catalog/tui-agent-display-names' +import { + AGENT_SESSION_ATTACHMENT_MAX_BYTES, + AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT, + AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES +} from '../../../shared/agent-session/agent-session-attachments' +import { agentInlineImageMimeType } from '../../../shared/agent-inline-image-types' import { claudeRecord } from './journal/claude-structured-item-translation' export class ClaudeDispatchContentError extends Error { @@ -51,10 +57,6 @@ export function claudeDispatchContentRejection(error: unknown): AgentJournalDisp return claudeDispatchRejection(agentSessionFailureFact('attachmentUnreadable')) } -const BYTES_PER_MB = 1024 * 1024 -const MAX_IMAGE_BYTES = 5 * BYTES_PER_MB -const MAX_IMAGE_COUNT = 20 -const MAX_TOTAL_IMAGE_BYTES = 20 * BYTES_PER_MB const MAX_REPLAY_CONTENT_KEY_BYTES = 256 type ImageBudget = { @@ -62,19 +64,23 @@ type ImageBudget = { localBytes: number } -export async function readClaudeImage(path: string, openImpl: typeof open = open): Promise { +export async function readClaudeImage( + path: string, + maxBytes = AGENT_SESSION_ATTACHMENT_MAX_BYTES, + openImpl: typeof open = open +): Promise { const file = await openImpl(path, 'r') try { const tooLarge = (): Error => - attachmentError(`Claude image must be no larger than ${MAX_IMAGE_BYTES} bytes`, { + attachmentError(`Claude image must be no larger than ${maxBytes} bytes`, { reason: 'tooLarge', - limit: MAX_IMAGE_BYTES + limit: maxBytes }) const info = await file.stat() if (!info.isFile()) { throw attachmentError('Claude image must be a file', { reason: 'notAFile' }) } - if (info.size > MAX_IMAGE_BYTES) { + if (info.size > maxBytes) { throw tooLarge() } const buffer = Buffer.allocUnsafe(info.size + 1) @@ -88,7 +94,7 @@ export async function readClaudeImage(path: string, openImpl: typeof open = open } // A file can grow after EOF; verify the open descriptor still matches the bytes read. const finalInfo = await file.stat() - if (bytesRead > MAX_IMAGE_BYTES) { + if (bytesRead > maxBytes) { throw tooLarge() } if (finalInfo.size !== bytesRead) { @@ -103,24 +109,19 @@ export async function readClaudeImage(path: string, openImpl: typeof open = open } } -const IMAGE_MIME_BY_EXTENSION: Record = { - '.gif': 'image/gif', - '.jpeg': 'image/jpeg', - '.jpg': 'image/jpeg', - '.png': 'image/png', - '.webp': 'image/webp' -} - async function imageContent( block: Extract, budget: ImageBudget ): Promise { budget.count += 1 - if (budget.count > MAX_IMAGE_COUNT) { - throw attachmentError(`Claude messages support at most ${MAX_IMAGE_COUNT} images`, { - reason: 'tooMany', - limit: MAX_IMAGE_COUNT - }) + if (budget.count > AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT) { + throw attachmentError( + `Claude messages support at most ${AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT} images`, + { + reason: 'tooMany', + limit: AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT + } + ) } if (block.url) { return { type: 'image', source: { type: 'url', url: block.url } } @@ -130,13 +131,16 @@ async function imageContent( } const data = await readClaudeImage(block.path) budget.localBytes += data.byteLength - if (budget.localBytes > MAX_TOTAL_IMAGE_BYTES) { - throw attachmentError(`Claude images must total no more than ${MAX_TOTAL_IMAGE_BYTES} bytes`, { - reason: 'totalTooLarge', - limit: MAX_TOTAL_IMAGE_BYTES - }) + if (budget.localBytes > AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES) { + throw attachmentError( + `Claude images must total no more than ${AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES} bytes`, + { + reason: 'totalTooLarge', + limit: AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES + } + ) } - const mediaType = IMAGE_MIME_BY_EXTENSION[extname(block.path).toLowerCase()] + const mediaType = agentInlineImageMimeType(block.path) if (!mediaType) { throw attachmentError(`Claude does not support the image type ${extname(block.path)}`, { reason: 'unsupportedType' diff --git a/src/main/claude/structured/claude-structured-dispatch-queue-boundary.test.ts b/src/main/claude/structured/claude-structured-dispatch-queue-boundary.test.ts deleted file mode 100644 index 3ab5f1668a1..00000000000 --- a/src/main/claude/structured/claude-structured-dispatch-queue-boundary.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { AgentSessionPreDispatchError } from '../../native-chat/agent-session-wire/operations/structured-agent-session-operation-settlement' -import { createClaudeUserMessageQueue } from '../claude-agent-sdk-user-message-queue' -import { dispatchClaudeTurn } from './claude-structured-dispatch' -import { sessionFor } from './claude-structured-dispatch-test-support' -import { USER_MESSAGE } from './claude-structured-session-test-support' - -it('refuses stale continuation work after waiting for the SDK input pump', async () => { - const queue = createClaudeUserMessageQueue() - const queued = Promise.withResolvers() - const send = vi.fn((_message, beforeDispatch?: () => Promise) => { - const result = queue.push( - { - type: 'user', - session_id: 'provider-session', - parent_tool_use_id: null, - message: { role: 'user', content: 'continue' } - }, - beforeDispatch - ) - queued.resolve() - return result - }) - const session = sessionFor(send) - session.connection.send = send - let superseded = false - const refusal = new AgentSessionPreDispatchError('agent_session_restart_work_superseded') - const beforeDispatch = vi.fn(async () => { - if (superseded) { - throw refusal - } - }) - const result = dispatchClaudeTurn(session, { body: USER_MESSAGE }, beforeDispatch).catch( - (error: unknown) => error - ) - await queued.promise - expect(beforeDispatch).not.toHaveBeenCalled() - expect(session.dispatchWaiters).toEqual([]) - superseded = true - queue.end() - const pump = queue.messages[Symbol.asyncIterator]() - const handedOff = await pump.next() - await pump.return?.() - expect(handedOff.done).toBe(true) - expect(await result).toBe(refusal) - expect(beforeDispatch).toHaveBeenCalledOnce() - expect(session.dispatchWaiters).toEqual([]) - expect(session.retiredDispatchWaiters).toEqual([]) -}) - -it.each(['exit', 'capacity'] as const)( - 'refuses %s during authorization without leaked correlation', - async (failure) => { - const queue = createClaudeUserMessageQueue() - const authorizing = Promise.withResolvers() - const authorized = Promise.withResolvers() - const queued = Promise.withResolvers() - const session = sessionFor() - session.connection.send = (_message, beforeDispatch) => { - const result = queue.push( - { - type: 'user', - session_id: 'provider-session', - parent_tool_use_id: null, - message: { role: 'user', content: 'continue' } - }, - beforeDispatch - ) - queued.resolve() - return result - } - const beforeDispatch = vi.fn(() => { - authorizing.resolve() - return authorized.promise - }) - const result = dispatchClaudeTurn(session, { body: USER_MESSAGE }, beforeDispatch) - await queued.promise - const pump = queue.messages[Symbol.asyncIterator]() - const handedOff = pump.next() - await authorizing.promise - if (failure === 'exit') { - queue.fail(new Error('provider exited')) - } else { - session.connection.send = vi.fn().mockResolvedValue(undefined) - for (let index = 0; index < 64; index += 1) { - await dispatchClaudeTurn(session, { - body: USER_MESSAGE, - clientMessageId: `ordinary-${index}` - }) - } - queue.end() - } - authorized.resolve() - expect((await handedOff).done).toBe(true) - expect(await result).toMatchObject({ state: 'rejected' }) - expect(beforeDispatch).toHaveBeenCalledOnce() - expect(session.dispatchWaiters).toHaveLength(failure === 'exit' ? 0 : 64) - expect(session.retiredDispatchWaiters).toEqual([]) - } -) diff --git a/src/main/claude/structured/claude-structured-dispatch-test-support.ts b/src/main/claude/structured/claude-structured-dispatch-test-support.ts index 28964e3371a..02e3dab8dff 100644 --- a/src/main/claude/structured/claude-structured-dispatch-test-support.ts +++ b/src/main/claude/structured/claude-structured-dispatch-test-support.ts @@ -1,11 +1,11 @@ -import { ClaudeJournalBoundDelivery } from '../claude-journal-bound-delivery' +import { ClaudeJournalBoundDelivery } from './journal/claude-journal-bound-delivery' import { vi, type Mock } from 'vitest' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' import { retireClaudeDispatchWaiters } from './claude-structured-dispatch' import type { ClaudeSession } from './claude-structured-session-state' -import { ClaudeBackgroundTaskTracker } from '../claude-background-task-tracker' -import { ClaudeChildWorkDecoder } from '../claude-child-work-decoder' -import { ClaudeSlashCommandCatalog } from '../claude-slash-command-catalog' +import { ClaudeBackgroundTaskTracker } from '../background-tasks/claude-background-task-tracker' +import { ClaudeChildWorkDecoder } from '../child-work/claude-child-work-decoder' +import { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' import { createClaudeInitProof } from './claude-structured-init-proof' import { createClaudeStartupOutcome } from './claude-structured-startup-outcome' import { claudeProviderHandleLink } from './claude-structured-owner-identity' diff --git a/src/main/claude/structured/claude-structured-dispatch.ts b/src/main/claude/structured/claude-structured-dispatch.ts index 12a38877d34..7f06dba903e 100644 --- a/src/main/claude/structured/claude-structured-dispatch.ts +++ b/src/main/claude/structured/claude-structured-dispatch.ts @@ -11,7 +11,7 @@ import { import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' import type { AgentSessionDispatchOutcome } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import type { ClaudeDispatchWaiter, ClaudeSession } from './claude-structured-session-state' -import type { ClaudeLateDispatchSettlement } from '../claude-replay-turn-resolution' +import type { ClaudeLateDispatchSettlement } from './turns/claude-replay-turn-resolution' import { claudeDispatchContentKey, claudeDispatchContentRejection, @@ -30,13 +30,13 @@ import type { AgentJournalDispatchRejection } from '../../../shared/agent-sessio import { claudeUnwrittenUserMessageError, claudeUserMessageWasProvablyUnwritten -} from '../claude-agent-sdk-user-message-queue' +} from '../sdk-transport/claude-agent-sdk-user-message-queue' import { AgentSessionPreDispatchError } from '../../native-chat/agent-session-wire/operations/structured-agent-session-operation-settlement' import { ClaudeEffortValidationError, isAgentSessionOptionRejectedError } from '../../native-chat/agent-session-wire/options/structured-agent-session-option-error' -import { ClaudeControlRequestError } from '../claude-agent-sdk-control-requests' +import { ClaudeControlRequestError } from '../sdk-transport/claude-agent-sdk-control-requests' import { admitStructuredAgentSessionInput, StructuredAgentSessionInputNotAdmitted, @@ -154,8 +154,6 @@ export async function dispatchClaudeTurn( : randomUUID()) const arm = () => { ++session.dispatchSequence - // Invalidate context reports requested before this send. - session.translator?.markContextActivity() return waitForReplay( session, acceptsResult, diff --git a/src/main/claude/structured/claude-structured-effort-reporting.test.ts b/src/main/claude/structured/claude-structured-effort-reporting.test.ts deleted file mode 100644 index c407b60cc8b..00000000000 --- a/src/main/claude/structured/claude-structured-effort-reporting.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - readClaudeSettingsEffort, - readClaudeSettingsApplied -} from './launch/claude-structured-session-options' -import { ClaudeControlRequestTimeoutError } from '../claude-agent-sdk-control-requests' -import recordedUltracodeSettings from '../__fixtures__/ultracode-settings.json' -import { - USER_MESSAGE, - adapterFor, - claudeFrame, - fakeClaude, - identityFor, - recordingJournalSink -} from './claude-structured-session-test-support' - -describe('Claude effort reporting', () => { - it('distinguishes old CLI omissions from native no-effort and malformed responses', () => { - expect(readClaudeSettingsEffort({ effective: { effortLevel: 'high' } })).toBe('high') - expect(readClaudeSettingsEffort({ applied: {}, effective: { effortLevel: 'high' } })).toBe( - 'high' - ) - expect( - readClaudeSettingsEffort({ applied: { effort: null }, effective: { effortLevel: 'high' } }) - ).toBeNull() - expect( - readClaudeSettingsEffort({ applied: { effort: 42 }, effective: { effortLevel: 'high' } }) - ).toBeUndefined() - expect( - readClaudeSettingsEffort({ applied: null, effective: { effortLevel: 'high' } }) - ).toBeUndefined() - expect(readClaudeSettingsApplied(recordedUltracodeSettings.configured)?.effort).toBe('xhigh') - expect(readClaudeSettingsEffort(recordedUltracodeSettings.configured)).toBe('ultracode') - }) - - it('keeps a configured workflow at launch without confirming saved ordinary XHigh', async () => { - const claude = fakeClaude({ - settings: { applied: { effort: 'xhigh', ultracode: true }, effective: {} } - }) - const adapter = adapterFor(claude) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'configured-workflow', - options: { effort: 'xhigh' }, - events: recordingJournalSink() - }) - const current = (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current - expect(current.effort).toBe('xhigh') - expect(current.confirmed ?? []).not.toContain('effort') - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'configured-workflow', - body: USER_MESSAGE, - executionOptions: { effort: 'xhigh' }, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted', ranOptions: { effort: 'ultracode' } }) - expect(claude.connections[0]!.calls.map(({ subtype }) => subtype)).not.toContain( - 'apply_flag_settings' - ) - const connection = claude.connections[0]! - connection.getSettings = async () => recordedUltracodeSettings.configured - claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) - for (const clientMessageId of ['fast-on', 'after-fast']) { - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body: USER_MESSAGE, - executionOptions: { effort: 'xhigh', fastMode: 'true' }, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) - } - expect( - connection.calls - .filter(({ subtype }) => subtype === 'apply_flag_settings') - .map(({ params }) => params?.settings) - ).toEqual([{ fastMode: true }, { effortLevel: 'xhigh' }]) - await adapter.closeAll() - }) - - it('leaves an attempted workflow after lost enable and exit acknowledgements', async () => { - const claude = fakeClaude() - const adapter = adapterFor(claude) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'uncertain-workflow', - options: { effort: 'xhigh' }, - events: recordingJournalSink() - }) - const connection = claude.connections[0]! - connection.getSettings = async () => null - const settings: unknown[] = [] - connection.applyFlagSettings = async (input) => { - settings.push(input) - if (settings.length < 3) { - throw new ClaudeControlRequestTimeoutError('apply_flag_settings') - } - } - for (const [clientMessageId, effort, state] of [ - ['enable', 'ultracode', 'rejected'], - ['exit-unanswered', 'xhigh', 'rejected'], - ['exit-retry', 'xhigh', 'admitted'] - ] as const) { - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body: USER_MESSAGE, - executionOptions: { effort }, - fence: 7 - }) - ).resolves.toMatchObject({ state }) - } - expect(settings).toEqual([ - { effortLevel: 'xhigh', ultracode: true }, - { effortLevel: 'xhigh', ultracode: false }, - { effortLevel: 'xhigh', ultracode: false } - ]) - expect(connection.sent).toHaveLength(1) - await adapter.closeAll() - }) -}) diff --git a/src/main/claude/structured/claude-structured-event-delivery.ts b/src/main/claude/structured/claude-structured-event-delivery.ts index 0bd7e9189bf..6d8b79378b3 100644 --- a/src/main/claude/structured/claude-structured-event-delivery.ts +++ b/src/main/claude/structured/claude-structured-event-delivery.ts @@ -1,5 +1,5 @@ -import { ClaudePluginInputError } from '../claude-plugin-ui' -import { claudePromptCardWritten } from '../claude-child-work-evidence' +import { ClaudePluginInputError } from '../sdk-transport/claude-plugin-ui' +import { claudePromptCardWritten } from '../child-work/claude-child-work-evidence' import type { ClaudeAcquisitionAttempt, ClaudeSessionExit, diff --git a/src/main/claude/structured/claude-structured-execution-observations.ts b/src/main/claude/structured/claude-structured-execution-observations.ts index 60f7a34ecaf..a390ca9cc4f 100644 --- a/src/main/claude/structured/claude-structured-execution-observations.ts +++ b/src/main/claude/structured/claude-structured-execution-observations.ts @@ -1,8 +1,4 @@ import { claudeObservedEffort } from './launch/claude-structured-session-options' -import { claudeRecord, claudeText } from './journal/claude-structured-item-translation' -import { claudeMatchingInitModel } from '../claude-context-usage' -import { isRootClaudeFrame } from '../claude-turn-opening' -import { MAX_CONTEXT_MODEL_ID_CHARS } from '../../../shared/agent-session/agent-session-context-usage' import type { ClaudeSession } from './claude-structured-session-state' /** Fast routing reports precede this input and cannot vouch for its execution. */ @@ -27,8 +23,6 @@ export function beginClaudeOptionMutation(session: ClaudeSession, key: string): const sequence = session.optionMutationSequence if (key === 'model') { delete session.appliedOptions - delete session.reportedOptions.reportedModel - session.modelMutationDispatch = session.dispatchSequence } else { if (session.reportedModelMutation === previous) { session.reportedModelMutation = sequence @@ -41,87 +35,19 @@ export function beginClaudeOptionMutation(session: ClaudeSession, key: string): return sequence } -/** Until a turn carries the pick, the running process's answers name the model it replaced. */ -export function noteClaudeModelPick(session: ClaudeSession, model: string): void { - session.modelPickAwaitingTurn = model - delete session.reportedOptions.reportedModel -} - /** An init names execution; a control answer only acknowledges its input. */ -export function observeClaudeExecutionModel(session: ClaudeSession, model: string): boolean { - const previous = claudeExecutionObservations(session).model - const previousResponse = session.reportedOptions.reportedModel - if (!session.modelPickAwaitingTurn) { - session.reportedOptions.reportedModel = model +export function observeClaudeExecutionModel( + session: ClaudeSession | null, + model: string | null | undefined +): { model: string } | null { + if (!session || !model) { + return null } + const previous = claudeExecutionObservations(session).model if (previous !== model) { delete session.appliedOptions } session.reportedOptions.model = model session.reportedModelMutation = session.optionMutationSequence - return previous !== model || previousResponse !== model -} - -/** Main-thread response metadata names the model that answered, including provider fallback. */ -function readClaudeResponseModel(frame: Record): string | null { - if (!isRootClaudeFrame(frame)) { - return null - } - const event = claudeRecord(frame.event) - const message = - frame.type === 'assistant' - ? claudeRecord(frame.message) - : frame.type === 'stream_event' && event?.type === 'message_start' - ? claudeRecord(event.message) - : null - const model = message?.role === 'assistant' ? claudeText(message.model)?.trim() : null - return model && model !== '' && model.length <= MAX_CONTEXT_MODEL_ID_CHARS - ? model - : null -} - -function observeClaudeResponseModel( - session: ClaudeSession, - frame: Record -): boolean { - const response = readClaudeResponseModel(frame) - // Why: a turn running at a model pick keeps answering on the old model; it must not unseat the pick. - if ( - !response || - (session.modelMutationDispatch === session.dispatchSequence && - session.reportedModelMutation !== session.optionMutationSequence) - ) { - return false - } - const model = - claudeMatchingInitModel({ - initModel: - session.reportedModelMutation === session.optionMutationSequence - ? (session.reportedOptions.model ?? null) - : null, - responseModel: response - }) ?? response - if (session.modelPickAwaitingTurn || model === session.reportedOptions.reportedModel) { - return false - } - session.reportedOptions.reportedModel = model - return true -} - -export function observeClaudeFrameModels( - session: ClaudeSession | null, - frame: Record, - initModel: string | null | undefined -): Partial | null { - if (!session) { - return null - } - const initChanged = initModel ? observeClaudeExecutionModel(session, initModel) : false - const responseChanged = observeClaudeResponseModel(session, frame) - return initChanged || responseChanged - ? { - ...(initChanged && initModel ? { model: initModel } : {}), - reportedModel: session.reportedOptions.reportedModel - } - : null + return previous !== model ? { model } : null } diff --git a/src/main/claude/structured/claude-structured-in-turn-stop.test.ts b/src/main/claude/structured/claude-structured-in-turn-stop.test.ts deleted file mode 100644 index 1a40b7e2e2b..00000000000 --- a/src/main/claude/structured/claude-structured-in-turn-stop.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' -import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record' -import { personStopDecidesTurn } from '../../native-chat/agent-session-journal/context-epochs/journal-stop-turn-end' -import { createJournalReducerState } from '../../native-chat/agent-session-journal/projection/journal-reducer' -import { ClaudeControlRequestError } from '../claude-agent-sdk-control-requests' -import { - PROVIDER_SESSION_ID, - USER_MESSAGE, - adapterFor, - fakeClaude, - identityFor, - type FakeConnection -} from './claude-structured-session-test-support' - -// Claude before 2.1.91 omitted terminal_reason; the journal Stop determines the outcome. -const CUT_SHORT = { - type: 'result', - subtype: 'error_during_execution', - is_error: true, - session_id: PROVIDER_SESSION_ID, - parent_tool_use_id: null -} - -async function runningChat(claude: ReturnType): Promise<{ - adapter: ReturnType - bodies: Map - connection: FakeConnection - turnId: string - stopEvent: (turnId: string) => void -}> { - const bodies = new Map() - const journal = createJournalReducerState('session-1', 'epoch-1') - const adapter = adapterFor(claude) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: { - appendItem: (identity, body) => bodies.set(agentJournalItemKey(identity), body), - appendTombstone: (identity) => bodies.delete(agentJournalItemKey(identity)), - publish: vi.fn(), - journalStopDecidesTurn: (turnId, endedAt) => personStopDecidesTurn(journal, turnId, endedAt) - } - }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-a', - body: USER_MESSAGE, - fence: 7 - }) - const connection = claude.connections[0]! - connection.handlers.onMessage?.({ ...connection.sent.at(-1)! }) - const turnId = [...bodies.values()] - .map((body) => readAgentJournalTurn(body)) - .find((turn) => turn?.state === 'running')?.turnId - if (!turnId) { - throw new Error('expected a running turn') - } - const stopEvent = (stoppedTurnId: string) => { - journal.queuePauseMarks.latestStop = { - sequence: 9, - event: { reason: 'user-stop', turnId: stoppedTurnId, at: 1 } - } - } - return { adapter, bodies, connection, turnId, stopEvent } -} - -function settled(bodies: Map, turnId: string) { - return [...bodies.values()] - .map((body) => readAgentJournalTurn(body)) - .find((turn) => turn?.turnId === turnId && turn.state !== 'running') -} - -function providerRows(bodies: Map): string[] { - return [...bodies.keys()].filter((key) => key.includes('provider-frame')) -} - -describe("a user's Stop inside a live Claude chat", () => { - it('leaves the turn the interrupt cut to the Stop when the CLI names no reason', async () => { - const claude = fakeClaude({ - routes: { - interrupt: () => { - claude.connections[0]!.handlers.onMessage?.(CUT_SHORT) - return undefined - } - } - }) - const { adapter, bodies, turnId, stopEvent } = await runningChat(claude) - stopEvent(turnId) - - await expect(adapter.cancelTurn({ sessionId: 'session-1', turnId, fence: 7 })).resolves.toEqual( - { cancelled: true } - ) - - expect(settled(bodies, turnId)).toMatchObject({ state: 'interrupted' }) - expect(settled(bodies, turnId)).not.toHaveProperty('outcome') - expect(providerRows(bodies)).toEqual([]) - }) - - it('leaves the open turn a Stop naming no turn cut to that Stop', async () => { - const claude = fakeClaude({ - routes: { - interrupt: () => { - claude.connections[0]!.handlers.onMessage?.(CUT_SHORT) - return undefined - } - } - }) - const { adapter, bodies, turnId, stopEvent } = await runningChat(claude) - // The host records the target even when the adapter request omits it. - stopEvent(turnId) - - await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ - cancelled: true - }) - - expect(settled(bodies, turnId)).toMatchObject({ state: 'interrupted' }) - expect(settled(bodies, turnId)).not.toHaveProperty('outcome') - expect(providerRows(bodies)).toEqual([]) - }) - - it('reads the same result with no Stop as a failure', async () => { - const { bodies, connection, turnId } = await runningChat(fakeClaude()) - - connection.handlers.onMessage?.(CUT_SHORT) - - expect(settled(bodies, turnId)).toMatchObject({ state: 'completed', outcome: 'failure' }) - expect(providerRows(bodies)).toHaveLength(1) - }) - - it('keeps a Stop naming no turn off the turn after it', async () => { - const claude = fakeClaude({ - replayUuids: ['user-uuid-0', 'user-uuid-1'], - routes: { - interrupt: () => { - claude.connections[0]!.handlers.onMessage?.(CUT_SHORT) - return undefined - } - } - }) - const { adapter, bodies, connection, turnId, stopEvent } = await runningChat(claude) - stopEvent(turnId) - await adapter.cancelTurn({ sessionId: 'session-1', fence: 7 }) - - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-b', - body: USER_MESSAGE, - fence: 7 - }) - connection.handlers.onMessage?.({ ...connection.sent.at(-1)! }) - const nextTurnId = [...bodies.values()] - .map((body) => readAgentJournalTurn(body)) - .find((turn) => turn?.state === 'running')?.turnId - if (!nextTurnId) { - throw new Error('expected the next turn running') - } - connection.handlers.onMessage?.(CUT_SHORT) - - expect(settled(bodies, nextTurnId)).toMatchObject({ state: 'completed', outcome: 'failure' }) - }) - - it.each([ - ['naming the turn', true], - ['naming no turn', false] - ] as const)( - 'leaves a turn the CLI refused to interrupt to the Stop, %s', - async (_label, named) => { - const claude = fakeClaude({ - routes: { - interrupt: () => { - throw new ClaudeControlRequestError('interrupt', 'not running') - } - } - }) - const { adapter, bodies, connection, turnId, stopEvent } = await runningChat(claude) - stopEvent(turnId) - - await expect( - adapter.cancelTurn({ sessionId: 'session-1', ...(named ? { turnId } : {}), fence: 7 }) - ).resolves.toEqual({ cancelled: false }) - connection.handlers.onMessage?.(CUT_SHORT) - - expect(settled(bodies, turnId)).toMatchObject({ state: 'interrupted' }) - expect(settled(bodies, turnId)).not.toHaveProperty('outcome') - expect(providerRows(bodies)).toHaveLength(0) - } - ) -}) diff --git a/src/main/claude/structured/claude-structured-inbound-control.test.ts b/src/main/claude/structured/claude-structured-inbound-control.test.ts index d218b479698..0444b4a350b 100644 --- a/src/main/claude/structured/claude-structured-inbound-control.test.ts +++ b/src/main/claude/structured/claude-structured-inbound-control.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { CanUseTool } from '@anthropic-ai/claude-agent-sdk' -import { ClaudePromptRegistry } from '../claude-prompt-registry' +import { ClaudePromptRegistry } from './permissions/claude-prompt-registry' import { buildClaudePermissionCallbacks } from './claude-structured-inbound-control' type CanUseToolOptions = Parameters[2] diff --git a/src/main/claude/structured/claude-structured-inbound-control.ts b/src/main/claude/structured/claude-structured-inbound-control.ts index b1fa8e47ebc..5252e0c2217 100644 --- a/src/main/claude/structured/claude-structured-inbound-control.ts +++ b/src/main/claude/structured/claude-structured-inbound-control.ts @@ -1,5 +1,5 @@ import type { CanUseTool, OnUserDialog, PermissionResult } from '@anthropic-ai/claude-agent-sdk' -import type { ClaudePromptRegistry } from '../claude-prompt-registry' +import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' import type { ClaudeStreamJsonConnectionHandlers } from '../claude-stream-json-connection' import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' @@ -8,7 +8,7 @@ import { createClaudeFullAccessPolicy } from './claude-full-access-policy' import { claudePermissionPresentation, claudePermissionSubject -} from '../claude-permission-presentation' +} from './permissions/claude-permission-presentation' export type ClaudePermissionCallbackDeps = { sessionId: string diff --git a/src/main/claude/structured/claude-structured-plugin-ui-recovery.ts b/src/main/claude/structured/claude-structured-plugin-ui-recovery.ts index c57e3ef9d81..2a6b1015456 100644 --- a/src/main/claude/structured/claude-structured-plugin-ui-recovery.ts +++ b/src/main/claude/structured/claude-structured-plugin-ui-recovery.ts @@ -1,4 +1,4 @@ -import { claudeFocusedPlugin, ClaudePluginInputError } from '../claude-plugin-ui' +import { claudeFocusedPlugin, ClaudePluginInputError } from '../sdk-transport/claude-plugin-ui' import type { ClaudeAcquisitionAttempt, ClaudeAcquireCallbacks, diff --git a/src/main/claude/structured/claude-structured-real-cli-fold.test.ts b/src/main/claude/structured/claude-structured-real-cli-fold.test.ts deleted file mode 100644 index 50cd1d9cc6c..00000000000 --- a/src/main/claude/structured/claude-structured-real-cli-fold.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdtemp } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { CLAUDE_STRUCTURED_BASE_OPTIONS } from './launch/claude-structured-launch-resolution' -import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { - realClaudeAuthenticated, - realClaudeAvailable, - realClaudeCommand, - realClaudeLaunchHome -} from '../claude-real-cli-availability-test-support' -import { claudeStartupSettled } from './claude-structured-startup-settled-test-support' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const SESSION_ID = 'real-cli-fold' -// Force SessionStart-before-init ordering and avoid prompts during the fold window. -const FOLD_SESSION_SETTINGS = JSON.stringify({ - hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'echo' }] }] }, - permissions: { allow: ['Bash(sleep:*)'] } -}) - -function identity(providerSessionId: string): AgentSessionJournalIdentity { - return { - sessionId: SESSION_ID, - workspaceId: 'real-cli-fold-workspace', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(providerSessionId, null) - } -} - -async function until(check: () => boolean, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs - while (Date.now() < deadline) { - if (check()) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 200)) - } - return check() -} - -describe.skipIf(!realClaudeAvailable)('Claude structured real CLI fold', () => { - it.skipIf(!realClaudeAuthenticated)( - 'keeps one turn row when the CLI folds a mid-turn send', - async () => { - const providerSessionId = randomUUID() - const { claudeConfigDir, env } = realClaudeLaunchHome() - const cwd = await mkdtemp(join(tmpdir(), 'orca-real-fold-')) - const events: ClaudeStructuredSessionEvent[] = [] - const turnRows: NonNullable>[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (_identity, body: AgentJournalItemBody) => { - const turn = readAgentJournalTurn(body) - if (turn) { - turnRows.push(turn) - } - }, - appendTombstone: () => {}, - publish: () => {} - } - const settled = vi.fn() - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: realClaudeCommand, - options: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS, - extraArgs: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS.extraArgs, - settings: FOLD_SESSION_SETTINGS - }, - sessionId: providerSessionId - }, - cwd, - env, - claudeConfigDir, - providerSessionId, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - onEvent: (event) => events.push(event), - onDispatchSettledLate: settled, - readProcessStartTime: async () => 1 - }) - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-fold', - events: sink - }) - await claudeStartupSettled(adapter, SESSION_ID) - expect( - events.some( - (event) => - event.type === 'message' && - event.message.type === 'system' && - event.message.subtype === 'init' - ) - ).toBe(false) - - await expect( - adapter.dispatch({ - sessionId: SESSION_ID, - clientMessageId: 'client-A', - body: { - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: 'Use the Bash tool to run `sleep 8` two separate times, one call at a time, waiting for each. Then reply exactly: FIRST DONE' - } - ] - }, - requestedAt: Date.now(), - fence: 1 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - - // The sleep prompt keeps A running while B is sent. - expect( - await until( - () => events.some((event) => event.type === 'message' && event.startsTurn === true), - 30_000 - ) - ).toBe(true) - await new Promise((resolve) => setTimeout(resolve, 2_000)) - await expect( - adapter.dispatch({ - sessionId: SESSION_ID, - clientMessageId: 'client-B', - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'Also say the word banana at the end of your reply.' }] - }, - requestedAt: Date.now(), - fence: 1 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - - const results = () => - events.flatMap((event) => - event.type === 'message' && event.message.type === 'result' ? [event.message] : [] - ) - expect(await until(() => results().length > 0, 90_000)).toBe(true) - - // A single send means B missed the fold window. - const named = results().flatMap((message) => - Array.isArray(message.user_message_uuids) ? [message.user_message_uuids] : [] - ) - expect(named[0]).toHaveLength(2) - - expect(turnRows.every((turn) => turn.state !== 'interrupted')).toBe(true) - expect([...new Set(turnRows.map((turn) => turn.turnId))]).toHaveLength(1) - expect(turnRows.at(-1)).toMatchObject({ state: 'completed' }) - expect(settled).toHaveBeenCalledWith( - expect.objectContaining({ - sessionId: SESSION_ID, - clientMessageId: 'client-B', - providerIdentity: expect.objectContaining({ provider: 'claude' }) - }) - ) - } finally { - await adapter.closeAll() - } - }, - 150_000 - ) -}) diff --git a/src/main/claude/structured/claude-structured-real-cli-rewind.test.ts b/src/main/claude/structured/claude-structured-real-cli-rewind.test.ts deleted file mode 100644 index 3de328e0f6e..00000000000 --- a/src/main/claude/structured/claude-structured-real-cli-rewind.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdtemp, readFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { resolveSessionFilePath } from '../../native-chat/session-file-resolver' -import { - realClaudeAuthenticated, - realClaudeAvailable, - realClaudeCommand, - realClaudeLaunchHome -} from '../claude-real-cli-availability-test-support' -import { readClaudePromptParentUuid, resolveClaudeRewindFork } from '../claude-rewind-fork' -import { - CLAUDE_STRUCTURED_BASE_OPTIONS, - type ClaudeStructuredSdkOptions -} from './launch/claude-structured-launch-resolution' -import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { claudeStartupSettled } from './claude-structured-startup-settled-test-support' - -const SESSION_ID = 'real-cli-rewind' - -const identity = (providerSessionId: string): AgentSessionJournalIdentity => ({ - sessionId: SESSION_ID, - workspaceId: 'real-cli-rewind-workspace', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(providerSessionId, null) -}) - -async function transcript(providerSessionId: string, claudeConfigDir: string): Promise { - const path = await resolveSessionFilePath('claude', providerSessionId, { - claudeProjectsDir: join(claudeConfigDir, 'projects') - }) - return readFile(path ?? '', 'utf8') -} - -describe.skipIf(!realClaudeAvailable)('Claude structured real CLI rewind', () => { - it.skipIf(!realClaudeAuthenticated)( - 'forks the conversation at the rewound prompt and forgets the undone turn', - async () => { - const source = randomUUID() - const { claudeConfigDir, env } = realClaudeLaunchHome() - const cwd = await mkdtemp(join(tmpdir(), 'orca-real-rewind-')) - const results: string[] = [] - // Replay supplies transcript prompt IDs after dispatch resolves. - const promptIds: string[] = [] - const adapterFor = (providerSessionId: string, launch: ClaudeStructuredSdkOptions) => - new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: realClaudeCommand, - options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, ...launch }, - cwd, - env, - claudeConfigDir, - providerSessionId, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - onEvent: (event: ClaudeStructuredSessionEvent) => { - if (event.type === 'message' && event.message.type === 'result') { - results.push(String(event.message.result)) - } - }, - onDispatchSettledLate: (settled) => { - if ('providerIdentity' in settled && settled.providerIdentity.provider === 'claude') { - promptIds.push(settled.providerIdentity.uuid) - } - }, - readProcessStartTime: async () => 1 - }) - const send = async (adapter: ClaudeStructuredSessionAdapter, text: string, n: number) => { - await adapter.dispatch({ - sessionId: SESSION_ID, - clientMessageId: `real-cli-rewind-${n}`, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }, - requestedAt: Date.now(), - fence: 1 - }) - await vi.waitFor(() => expect(results).toHaveLength(n), { timeout: 90_000, interval: 250 }) - return promptIds[n - 1] - } - - const first = adapterFor(source, { sessionId: source }) - let promptUuid: string | undefined - try { - await first.acquire({ identity: identity(source), fence: 1, spawnToken: 'rewind-source' }) - await claudeStartupSettled(first, SESSION_ID) - await send(first, 'Reply with the single word ALPHA and nothing else.', 1) - promptUuid = await send(first, 'Reply with the single word BRAVO and nothing else.', 2) - } finally { - await first.closeAll() - } - - const sourceBefore = await transcript(source, claudeConfigDir) - expect(sourceBefore).toContain(`"uuid":"${promptUuid}"`) - const throughEntryId = await readClaudePromptParentUuid({ - providerSessionId: source, - promptUuid: promptUuid ?? '', - claudeConfigDir - }) - - const fork = await resolveClaudeRewindFork({ - orcaSessionId: SESSION_ID, - rewindOperationId: randomUUID(), - head: claudeProviderHandle(source, null), - prompt: { sessionId: source, uuid: promptUuid ?? '' }, - claudeConfigDirs: [claudeConfigDir] - }) - expect(fork).toMatchObject({ materialized: true, throughEntryId }) - if (!fork) { - throw new Error('rewind fork was not created') - } - const beforeSend = await transcript(fork.sessionId, claudeConfigDir) - expect(beforeSend).toContain(throughEntryId) - expect(beforeSend).not.toContain(promptUuid) - const rewound = adapterFor(fork.sessionId, { resume: fork.sessionId }) - try { - await rewound.acquire({ - identity: identity(fork.sessionId), - fence: 1, - spawnToken: 'rewind-fork' - }) - await claudeStartupSettled(rewound, SESSION_ID) - await send( - rewound, - 'List every word I have asked you to reply with in this conversation, in capitals.', - 3 - ) - } finally { - await rewound.closeAll() - } - - const answer = results[2] ?? '' - expect(answer).toContain('ALPHA') - expect(answer).not.toContain('BRAVO') - // Forked entries retain original UUIDs in provenance. - const forked = await transcript(fork.sessionId, claudeConfigDir) - expect(forked).toContain(`"messageUuid":"${throughEntryId}"`) - expect(forked).not.toContain(promptUuid) - expect(await transcript(source, claudeConfigDir)).toBe(sourceBefore) - }, - 240_000 - ) -}) diff --git a/src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts b/src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts deleted file mode 100644 index 952135ab827..00000000000 --- a/src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdtemp } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { CLAUDE_STRUCTURED_BASE_OPTIONS } from './launch/claude-structured-launch-resolution' -import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { - realClaudeAuthenticated, - realClaudeAvailable, - realClaudeCommand, - realClaudeLaunchHome -} from '../claude-real-cli-availability-test-support' -import { claudeStartupSettled } from './claude-structured-startup-settled-test-support' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const SESSION_ID = 'real-cli-stop-task' -const SETTINGS = JSON.stringify({ permissions: { allow: ['Bash(sleep:*)'] } }) - -function identity(providerSessionId: string): AgentSessionJournalIdentity { - return { - sessionId: SESSION_ID, - workspaceId: 'real-cli-stop-task-workspace', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(providerSessionId, null) - } -} - -async function until(check: () => boolean, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs - while (Date.now() < deadline) { - if (check()) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 200)) - } - return check() -} - -function taskFrames(events: readonly ClaudeStructuredSessionEvent[], taskId: string) { - return events.flatMap((event) => - event.type === 'message' && - event.message.type === 'system' && - typeof event.message.subtype === 'string' && - event.message.subtype.startsWith('task_') && - event.message.task_id === taskId - ? [event.message] - : [] - ) -} - -describe.skipIf(!realClaudeAvailable)('Claude structured real CLI targeted stop', () => { - it.skipIf(!realClaudeAuthenticated)( - 'acknowledges stop_task on one live background agent', - async () => { - const providerSessionId = randomUUID() - const { claudeConfigDir, env } = realClaudeLaunchHome() - const cwd = await mkdtemp(join(tmpdir(), 'orca-real-stop-task-')) - const events: ClaudeStructuredSessionEvent[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {} - } - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: realClaudeCommand, - options: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS, - extraArgs: { ...CLAUDE_STRUCTURED_BASE_OPTIONS.extraArgs, settings: SETTINGS }, - sessionId: providerSessionId - }, - cwd, - env, - claudeConfigDir, - providerSessionId, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - onEvent: (event) => events.push(event), - readProcessStartTime: async () => 1 - }) - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-stop-task', - events: sink - }) - await claudeStartupSettled(adapter, SESSION_ID) - await expect( - adapter.dispatch({ - sessionId: SESSION_ID, - clientMessageId: 'client-A', - body: { - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: 'Use the Agent tool once, with run_in_background set to true and description "Sleeper", asking the subagent to run `sleep 120` with the Bash tool. Do not wait for it. Then reply exactly: LAUNCHED' - } - ] - }, - requestedAt: Date.now(), - fence: 1 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - - const started = () => - events.flatMap((event) => - event.type === 'message' && - event.message.type === 'system' && - event.message.subtype === 'task_started' && - event.message.task_type === 'local_agent' && - typeof event.message.task_id === 'string' - ? [event.message.task_id] - : [] - ) - expect(await until(() => started().length > 0, 90_000)).toBe(true) - const [taskId] = started() - // Give the subagent time to reach its sleep, so the stop lands on a live run. - await new Promise((resolve) => setTimeout(resolve, 5_000)) - - const acknowledged: unknown[] = [] - const outcome = await adapter.stopBackgroundTasks({ - sessionId: SESSION_ID, - fence: 1, - taskIds: [taskId], - acknowledge: (acknowledgement) => void acknowledged.push(acknowledgement) - }) - expect(outcome).toMatchObject({ cancelled: true }) - expect(acknowledged).toEqual([{ taskId }]) - - const ended = await until( - () => - taskFrames(events, taskId).some( - (frame) => - frame.subtype === 'task_notification' || - (frame.subtype === 'task_updated' && - typeof frame.patch === 'object' && - frame.patch !== null && - 'status' in frame.patch) - ), - 30_000 - ) - expect(ended).toBe(true) - const frames = taskFrames(events, taskId).map((frame) => ({ - subtype: frame.subtype, - status: - frame.status ?? - (typeof frame.patch === 'object' && frame.patch !== null && 'status' in frame.patch - ? frame.patch.status - : undefined) - })) - console.info('[real-cli stop_task] task frames', JSON.stringify(frames)) - const endings = frames.filter((frame) => frame.status !== undefined) - expect(endings.length).toBeGreaterThan(0) - expect( - endings.every((frame) => - ['stopped', 'killed', 'cancelled'].includes(String(frame.status)) - ) - ).toBe(true) - } finally { - await adapter.closeAll() - } - }, - 180_000 - ) -}) diff --git a/src/main/claude/structured/claude-structured-real-cli-visuals.test.ts b/src/main/claude/structured/claude-structured-real-cli-visuals.test.ts deleted file mode 100644 index 92b8d52201f..00000000000 --- a/src/main/claude/structured/claude-structured-real-cli-visuals.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { createClaudeStructuredLaunchResolver } from '../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { mkdir, mkdtemp, rm } from 'node:fs/promises' -import { homedir, tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { agentSessionRecordFixture } from '../../native-chat/agent-session-record-test-fixture' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { createNativeChatVisualsDelivery } from '../../native-chat/native-chat-visuals-delivery' -import { nativeChatScratchFolderFor } from '../../native-chat/native-chat-scratch-folder' -import { NATIVE_CHAT_VISUALS_SKILL_NAME } from '../../native-chat/native-chat-visuals-skill-location' -import { createClaudeCliFlagSupport } from '../claude-cli-flag-support' -import { readClaudeInit } from './claude-structured-init-proof' -import { - realClaudeAuthenticated, - realClaudeAvailable, - realClaudeCliGate, - realClaudeCommand, - realClaudeLaunchHome -} from '../claude-real-cli-availability-test-support' -import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' - -const SESSION_ID = 'real-cli-visuals' -const listed = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) -const suiteTitle = `Claude real CLI chat visuals${realClaudeCliGate.skipReason ? ` (skipped: ${realClaudeCliGate.skipReason})` : ''}` - -describe.skipIf(!realClaudeAvailable)(suiteTitle, () => { - it.skipIf(!realClaudeAuthenticated)( - "loads the visuals skill through Orca's launch and grants the chat folder", - async () => { - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const scratch = await mkdtemp(join(tmpdir(), 'orca-real-cli-visuals-')) - const cwd = join(scratch, 'workspace') - const stateDirectory = join(scratch, 'state') - const record = agentSessionRecordFixture({ - sessionId: SESSION_ID, - location: { workspaceId: 'real-cli-visuals-workspace' }, - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: claudeConfigDir }, - launchDirectory: cwd - }) - const logger = { warn: vi.fn(), error: vi.fn() } - const resolveLaunch = createClaudeStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveWorkspacePath: async () => cwd, - resolveCommand: () => ({ command: realClaudeCommand, prefixArgs: [] }), - resolveLaunchArgs: () => [], - resolveEnv: () => realClaudeLaunchHome().env, - resolveAuthPolicy: () => ({ account: 'system' }), - hasTranscript: async () => false, - cliFlags: createClaudeCliFlagSupport(), - prepareVisuals: createNativeChatVisualsDelivery({ stateDirectory, logger }) - }) - const identity: AgentSessionJournalIdentity = { - sessionId: SESSION_ID, - workspaceId: 'real-cli-visuals-workspace', - hostId: 'local', - agent: 'claude', - providerHandle: null - } - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch, - onEvent: (event) => events.push(event), - readProcessStartTime: async () => 1, - now: () => 2 - }) - const frames = (): Record[] => - events.flatMap((event) => (event.type === 'message' ? [event.message] : [])) - try { - await mkdir(cwd, { recursive: true }) - const launch = await resolveLaunch({ identity }) - const folder = nativeChatScratchFolderFor(stateDirectory, SESSION_ID) - expect(launch.options.additionalDirectories).toEqual([folder]) - expect(launch.options.plugins).toHaveLength(1) - await adapter.acquire({ - identity: { - ...identity, - providerHandle: claudeProviderHandle(launch.providerSessionId, null) - }, - fence: 1, - spawnToken: 'real-cli-visuals' - }) - await adapter.dispatch({ - sessionId: SESSION_ID, - clientMessageId: 'real-cli-visuals-1', - body: { - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: 'Without using any tool, reply with only the exact names of the skills available to you whose name contains "visuals", comma separated, or NONE.' - } - ] - }, - fence: 1 - }) - await vi.waitFor( - () => expect(frames()).toContainEqual(expect.objectContaining({ type: 'result' })), - { timeout: 120_000, interval: 200 } - ) - const init = frames().find( - (frame) => readClaudeInit(frame) !== null && frame.subtype === 'init' - ) - // The model sees the skill even though the / menu and init lists hide it. - const answer = frames().find((frame) => frame.type === 'result')?.result - expect(String(answer)).toContain(NATIVE_CHAT_VISUALS_SKILL_NAME) - expect( - [...listed(init?.skills), ...listed(init?.slash_commands)].some( - (name) => typeof name === 'string' && name.endsWith(NATIVE_CHAT_VISUALS_SKILL_NAME) - ) - ).toBe(false) - expect(init?.plugins).toEqual( - expect.arrayContaining([ - expect.objectContaining({ path: launch.options.plugins?.[0]?.path }) - ]) - ) - expect(logger.warn).not.toHaveBeenCalled() - } finally { - await adapter.closeAll() - await rm(scratch, { recursive: true, force: true }) - } - }, - 150_000 - ) -}) diff --git a/src/main/claude/structured/claude-structured-real-cli.test.ts b/src/main/claude/structured/claude-structured-real-cli.test.ts deleted file mode 100644 index 9c9a3a56670..00000000000 --- a/src/main/claude/structured/claude-structured-real-cli.test.ts +++ /dev/null @@ -1,605 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { homedir, tmpdir } from 'node:os' -import { basename, join, relative } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { resolveSessionFilePath } from '../../native-chat/session-file-resolver' -import { - CLAUDE_STRUCTURED_BASE_OPTIONS, - claudeStructuredPermissionOptions -} from './launch/claude-structured-launch-resolution' -import { readClaudeInit } from './claude-structured-init-proof' -import { - realClaudeAuthenticated, - realClaudeAuthStatus, - realClaudeAvailable, - realClaudeCliGate, - realClaudeCommand, - realClaudeLaunchHome -} from '../claude-real-cli-availability-test-support' -import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' -import type { - ClaudeStructuredSessionEvent, - ClaudeStructuredSessionAdapterDeps -} from './claude-structured-session-state' - -import { - claudeOpened, - claudeStartupSettled -} from './claude-structured-startup-settled-test-support' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const command = realClaudeCommand -const suiteTitle = `Claude structured real CLI handshake${realClaudeCliGate.skipReason ? ` (skipped: ${realClaudeCliGate.skipReason})` : ''}` - -function realAdapter( - providerSessionId: string, - claudeConfigDir: string, - events: ClaudeStructuredSessionEvent[] = [], - cwd = process.cwd(), - onDispatchSettledLate?: ClaudeStructuredSessionAdapterDeps['onDispatchSettledLate'], - env = realClaudeLaunchHome().env, - waitsForStartup = true -): ClaudeStructuredSessionAdapter { - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async ({ permissionMode }) => { - const permission = claudeStructuredPermissionOptions(permissionMode ?? 'ask') - return { - pathToClaudeCodeExecutable: command, - options: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS, - ...permission, - extraArgs: { ...CLAUDE_STRUCTURED_BASE_OPTIONS.extraArgs, ...permission.extraArgs }, - sessionId: providerSessionId - }, - cwd, - env, - claudeConfigDir, - providerSessionId, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - } - }, - onEvent: (event) => events.push(event), - ...(onDispatchSettledLate ? { onDispatchSettledLate } : {}), - readProcessStartTime: async () => 1, - now: () => 2 - }) - if (!waitsForStartup) { - return adapter - } - // These proofs read startup facts, which land after the session is published. - const acquire = adapter.acquire - adapter.acquire = async (input) => { - const acquisition = await acquire(input) - await claudeStartupSettled(adapter, input.identity.sessionId) - return acquisition - } - return adapter -} - -/** Isolate SessionStart proof from the machine's hook settings. */ -async function projectWithStartHook( - prefix: string, - settings: Record = {} -): Promise { - const cwd = await mkdtemp(join(tmpdir(), prefix)) - await mkdir(join(cwd, '.claude'), { recursive: true }) - await writeFile( - join(cwd, '.claude', 'settings.json'), - JSON.stringify({ - ...settings, - hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'true' }] }] } - }) - ) - return cwd -} - -function identity(providerSessionId: string): AgentSessionJournalIdentity { - return { - sessionId: 'real-cli-handshake', - workspaceId: 'real-cli-workspace', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(providerSessionId, null) - } -} - -/** The CLI flushes its transcript on its own schedule; poll rather than race it. */ -async function waitForResolvedTranscript( - providerSessionId: string, - timeoutMs = 15_000 -): Promise { - const deadline = Date.now() + timeoutMs - for (;;) { - // Match mobile lookup: no project-root override. - const resolved = await resolveSessionFilePath('claude', providerSessionId) - if (resolved || Date.now() >= deadline) { - return resolved - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } -} - -describe.skipIf(!realClaudeAvailable)(suiteTitle, () => { - it.skipIf(!realClaudeAuthenticated)( - 'proves a pre-minted session before the first user message', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const events: ClaudeStructuredSessionEvent[] = [] - const cwd = await projectWithStartHook('orca-command-init-') - await mkdir(join(cwd, '.claude', 'commands'), { recursive: true }) - await writeFile( - join(cwd, '.claude', 'commands', 'orca-init-catalog-proof.md'), - '---\ndescription: Initialization catalog proof\n---\nReply with OK.\n' - ) - const adapter = realAdapter(providerSessionId, claudeConfigDir, events, cwd) - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - const observedSubtypes = events.flatMap((event) => - event.type === 'message' ? [event.message.subtype] : [] - ) - - // Startup frame UUIDs are not resumable transcript leaves. - expect((await claudeOpened(adapter, 'real-cli-handshake')).link?.handle).toEqual( - claudeProviderHandle(providerSessionId, null) - ) - expect(observedSubtypes).toContain('hook_started') - expect(adapter.readCommands('real-cli-handshake')).toContainEqual( - expect.objectContaining({ - name: 'orca-init-catalog-proof', - kind: 'command', - kindUnspecified: true - }) - ) - expect( - adapter.readCommands('real-cli-handshake')?.some(({ name }) => name === 'help') - ).toBe(false) - } finally { - await adapter.closeAll() - await rm(cwd, { recursive: true, force: true }) - } - }, - 10_000 - ) - - it.skipIf(!realClaudeAuthenticated)( - 'reports the current effort through get_settings and never on the init frame', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const events: ClaudeStructuredSessionEvent[] = [] - const cwd = await projectWithStartHook('orca-effort-readback-', { effortLevel: 'low' }) - const adapter = realAdapter(providerSessionId, claudeConfigDir, events, cwd) - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-effort' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - const published = events.flatMap((event) => - event.type === 'message' ? [event.message] : [] - ) - const options = await adapter.readOptions({ sessionId: 'real-cli-handshake', fence: 1 }) - - expect(published.length).toBeGreaterThan(0) - // Startup proof varies by host, so inspect every published frame. - expect(published.filter((frame) => 'effortLevel' in frame)).toEqual([]) - expect(options.current.effort).toBe('low') - } finally { - await adapter.closeAll() - await rm(cwd, { recursive: true, force: true }) - } - }, - 15_000 - ) - - // Use the CLI-reported project root so resolver and expectation cannot share a path bug. - it.skipIf(!realClaudeAuthenticated || !realClaudeAuthStatus?.projectsDirectory)( - 'writes its transcript where the mobile session-file resolver looks for it', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const adapter = realAdapter(providerSessionId, claudeConfigDir) - const cliProjectsDir = realClaudeAuthStatus?.projectsDirectory as string - - let transcriptPath: string | null = null - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-transcript' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - await adapter.dispatch({ - sessionId: 'real-cli-handshake', - clientMessageId: 'real-cli-transcript-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hi' }] }, - fence: 1 - }) - transcriptPath = await waitForResolvedTranscript(providerSessionId) - } finally { - await adapter.closeAll() - } - - expect(transcriptPath).not.toBeNull() - expect(basename(transcriptPath ?? '')).toBe(`${providerSessionId}.jsonl`) - expect(relative(cliProjectsDir, transcriptPath ?? '').split(/[\\/]/)).toHaveLength(2) - expect(join(claudeConfigDir, 'projects')).toBe(cliProjectsDir) - }, - 45_000 - ) - - // set_model accepts nonexistent IDs; only a later init proves the model was adopted. - it.skipIf(!realClaudeAuthenticated)( - 'reports the model it adopted on the init frame that opens each turn', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = realAdapter(providerSessionId, claudeConfigDir, events) - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-model' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - await adapter.setOption({ - sessionId: 'real-cli-handshake', - key: 'model', - value: 'haiku', - fence: 1 - }) - const before = events.length - await adapter.dispatch({ - sessionId: 'real-cli-handshake', - clientMessageId: 'real-cli-model-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Say ok' }] }, - fence: 1 - }) - const deadline = Date.now() + 60_000 - let frames: Record[] = [] - for (;;) { - frames = events - .slice(before) - .flatMap((event) => - event.type === 'message' && - event.message.type === 'system' && - event.message.subtype === 'init' - ? [event.message] - : [] - ) - if (frames.length > 0 || Date.now() >= deadline) { - break - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } - - expect(frames).not.toHaveLength(0) - expect(frames[0]?.model).toEqual(expect.any(String)) - expect(frames[0]?.model).toMatch(/^claude-haiku-/) - await expect( - adapter.readOptions({ sessionId: 'real-cli-handshake', fence: 1 }) - ).resolves.toMatchObject({ - current: { model: 'haiku', confirmed: expect.arrayContaining(['model']) } - }) - } finally { - await adapter.closeAll() - } - }, - 90_000 - ) - - it.skipIf(!realClaudeAuthenticated).each([ - ['accept-edits', 'acceptEdits'], - ['auto', 'auto'], - ['full-access', 'bypassPermissions'] - ] as const)( - 'runs a message after open with saved options and %s', - async (permissionMode, cliPermissionMode) => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const cwd = await mkdtemp(join(tmpdir(), 'orca-claude-permissions-')) - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = realAdapter( - providerSessionId, - claudeConfigDir, - events, - cwd, - undefined, - realClaudeLaunchHome().env, - false - ) - const messages = (): Record[] => - events.flatMap((event) => (event.type === 'message' ? [event.message] : [])) - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-saved-options', - options: { model: 'sonnet', effort: 'low' }, - permissionMode - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - const dispatched = await adapter.dispatch({ - sessionId: 'real-cli-handshake', - clientMessageId: 'real-cli-saved-options-1', - body: { - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: - permissionMode === 'auto' - ? 'Use tools to write auto-mode-proof.txt containing exactly AUTO_MODE_OK, then read it back. Reply with exactly: OK.' - : 'Reply with exactly: OK. Do not use any tools.' - } - ] - }, - fence: 1 - }) - expect(dispatched).toMatchObject({ state: 'admitted' }) - const deadline = Date.now() + 90_000 - while (!messages().some((m) => m.type === 'result') && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 250)) - } - - expect(messages()).toContainEqual(expect.objectContaining({ type: 'user', isReplay: true })) - expect(messages().find((m) => m.type === 'result')).toMatchObject({ is_error: false }) - expect(messages().find((m) => m.type === 'system' && m.subtype === 'init')).toMatchObject({ - model: expect.stringMatching(/^claude-sonnet-/), - permissionMode: cliPermissionMode - }) - if (permissionMode === 'auto') { - expect((await readFile(join(cwd, 'auto-mode-proof.txt'), 'utf8')).trim()).toBe( - 'AUTO_MODE_OK' - ) - } - } finally { - await adapter.closeAll() - await rm(cwd, { recursive: true, force: true }) - } - }, - 120_000 - ) - - it.skipIf(!realClaudeAuthenticated)( - 'stops a message interrupted before its reply starts, and takes the next one', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = realAdapter(providerSessionId, claudeConfigDir, events) - const frames = (from: number) => - events.slice(from).flatMap((event) => (event.type === 'message' ? [event.message] : [])) - const replyStarted = (from: number) => - frames(from).some( - (frame) => - frame.type === 'stream_event' && - typeof frame.event === 'object' && - frame.event !== null && - 'type' in frame.event && - frame.event.type === 'message_start' - ) - const result = async (from: number) => { - const deadline = Date.now() + 60_000 - for (;;) { - const found = frames(from).find((frame) => frame.type === 'result') - if (found || Date.now() >= deadline) { - return found - } - await new Promise((resolve) => setTimeout(resolve, 100)) - } - } - const send = (clientMessageId: string, text: string) => - adapter.dispatch({ - sessionId: 'real-cli-handshake', - clientMessageId, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }, - fence: 1 - }) - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-stop' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - const first = events.length - await expect( - send('real-cli-stop-1', 'Count from 1 to 300, one number per line, and nothing else.') - ).resolves.toMatchObject({ state: 'admitted' }) - const startedBeforeStop = replyStarted(first) - - await expect( - adapter.cancelTurn({ sessionId: 'real-cli-handshake', fence: 1 }) - ).resolves.toEqual({ - cancelled: true - }) - const stopped = await result(first) - - expect(startedBeforeStop).toBe(false) - // Claude 2.1.280 echoes the message, then ends that turn as interrupted without replying. - expect(stopped).toMatchObject({ subtype: 'error_during_execution' }) - expect(replyStarted(first)).toBe(false) - - const second = events.length - await expect( - send('real-cli-stop-2', 'Reply with the single word ok.') - ).resolves.toMatchObject({ - state: 'admitted' - }) - await expect(result(second)).resolves.toMatchObject({ subtype: 'success' }) - } finally { - await adapter.closeAll() - } - }, - 150_000 - ) - - // SessionStart can prove startup before system/init advertises queue-cancellation support. - it.skipIf(!realClaudeAuthenticated)( - 'withdraws a follow-up queued behind a turn that is stopped, behind a SessionStart hook', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const cwd = await projectWithStartHook('orca-queued-stop-') - const events: ClaudeStructuredSessionEvent[] = [] - const settlements: unknown[] = [] - const adapter = realAdapter(providerSessionId, claudeConfigDir, events, cwd, (settlement) => - settlements.push(settlement) - ) - const send = (clientMessageId: string, text: string) => - adapter.dispatch({ - sessionId: 'real-cli-handshake', - clientMessageId, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }, - fence: 1 - }) - const waitFor = async (found: () => boolean): Promise => { - const deadline = Date.now() + 60_000 - while (!found() && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 100)) - } - return found() - } - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-queued-stop' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - await send('real-cli-queued-stop-a', 'Count from 1 to 400, one number per line.') - await expect( - waitFor(() => - events.some( - (event) => - event.type === 'message' && - event.message.type === 'stream_event' && - JSON.stringify(event.message).includes('text_delta') - ) - ) - ).resolves.toBe(true) - await send('real-cli-queued-stop-b', 'Say the word banana.') - - await expect( - adapter.cancelTurn({ - sessionId: 'real-cli-handshake', - turnId: 'turn-a', - fence: 1, - resolveLiveTurnId: () => 'turn-a', - dispatchStatus: { state: 'pending', recovered: false } - }) - ).resolves.toEqual({ cancelled: true }) - - expect(settlements).toContainEqual({ - sessionId: 'real-cli-handshake', - clientMessageId: 'real-cli-queued-stop-b', - state: 'rejected', - reason: 'provider_cancelled_before_start', - rejection: { kind: 'cancelled' }, - unrun: true - }) - } finally { - await adapter.closeAll() - await rm(cwd, { recursive: true, force: true }) - } - }, - 150_000 - ) - - it.skipIf(!realClaudeAuthenticated)( - 'starts and answers with every hook disabled, so no start frame precedes the turn', - async () => { - const providerSessionId = randomUUID() - const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') - const cwd = await mkdtemp(join(tmpdir(), 'orca-no-hooks-')) - await mkdir(join(cwd, '.claude'), { recursive: true }) - await writeFile( - join(cwd, '.claude', 'settings.json'), - JSON.stringify({ disableAllHooks: true }) - ) - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = realAdapter(providerSessionId, claudeConfigDir, events, cwd) - const frames = (): Record[] => - events.flatMap((event) => (event.type === 'message' ? [event.message] : [])) - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-no-hooks' - }) - await claudeStartupSettled(adapter, 'real-cli-handshake') - expect(frames().filter((frame) => readClaudeInit(frame) !== null)).toEqual([]) - await expect( - adapter.dispatch({ - sessionId: 'real-cli-handshake', - clientMessageId: 'real-cli-no-hooks-1', - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'Reply with the single word ok.' }] - }, - fence: 1 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - await vi.waitFor( - () => expect(frames()).toContainEqual(expect.objectContaining({ type: 'result' })), - { timeout: 120_000, interval: 200 } - ) - } finally { - await adapter.closeAll() - await rm(cwd, { recursive: true, force: true }) - } - }, - 150_000 - ) - - it('turns a real silent unauthenticated startup into sign-in guidance', async () => { - const claudeConfigDir = await mkdtemp(join(tmpdir(), 'orca-claude-no-auth-')) - const providerSessionId = randomUUID() - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = realAdapter( - providerSessionId, - claudeConfigDir, - events, - process.cwd(), - undefined, - {}, - false - ) - - try { - await adapter.acquire({ - identity: identity(providerSessionId), - fence: 1, - spawnToken: 'real-cli-no-auth' - }) - await expect(claudeStartupSettled(adapter, 'real-cli-handshake')).rejects.toThrow( - /not signed in.*Claude CLI.*CLAUDE_CONFIG_DIR/s - ) - } finally { - await adapter.closeAll() - await rm(claudeConfigDir, { recursive: true, force: true }) - } - }, 10_000) -}) diff --git a/src/main/claude/structured/claude-structured-response-model.test.ts b/src/main/claude/structured/claude-structured-response-model.test.ts index de462de8316..922eb6d2b0d 100644 --- a/src/main/claude/structured/claude-structured-response-model.test.ts +++ b/src/main/claude/structured/claude-structured-response-model.test.ts @@ -5,157 +5,42 @@ import { fakeClaude, USER_MESSAGE } from './claude-structured-session-test-support' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -it('publishes the main response model after fallback and restoration, ignoring child, foreign and synthetic frames', async () => { - const claude = fakeClaude({ initModel: 'claude-opus-5-5' }) - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = await acquired(claude, {}, events) - const connection = claude.connections[0]! - const read = () => adapter.readOptions({ sessionId: 'session-1', fence: 7 }) +it('keeps ordinary answer metadata out of the model options exposed to clients', async () => { + const claude = fakeClaude({ + initModel: 'claude-opus-5-5', + initModels: [{ value: 'claude-opus-5-5', displayName: 'Opus 5.5' }] + }) + const adapter = await acquired(claude) try { - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' }) - expect((await read()).current.model).toBe('claude-opus-5-5') - for (const patch of [ - { parent_tool_use_id: 'child-tool' }, - { session_id: 'another-session' }, - { message: { role: 'assistant', model: '', content: [] } } - ]) { - claudeFrame(connection, { - type: 'assistant', - uuid: 'ignore', - message: { role: 'assistant', model: 'claude-opus-4-8', content: [] }, - ...patch - }) - expect((await read()).current.model).toBe('claude-opus-5-5') - expect((await read()).current.reportedModel).toBe('claude-opus-5-5') - } - claudeFrame(connection, { - type: 'assistant', - uuid: 'fallback', - message: { - role: 'assistant', - model: 'claude-opus-4-8', - content: [ - { type: 'fallback', from: { model: 'claude-opus-5-5' }, to: { model: 'claude-opus-4-8' } } - ] - } - }) - expect((await read()).current).toMatchObject({ - model: 'claude-opus-5-5', - reportedModel: 'claude-opus-4-8', - confirmed: expect.arrayContaining(['model']) - }) - expect(events).toContainEqual( - expect.objectContaining({ - type: 'options-reported', - reportedOptions: expect.objectContaining({ reportedModel: 'claude-opus-4-8' }) - }) - ) - claudeFrame(connection, { type: 'system', subtype: 'status', permissionMode: 'plan' }) - expect(events.findLast((event) => event.type === 'options-reported')).toMatchObject({ - reportedOptions: { reportedModel: 'claude-opus-4-8', reportedPermissionMode: 'plan' } + await adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'first', + body: USER_MESSAGE, + fence: 7 }) + const connection = claude.connections[0]! claudeFrame(connection, { type: 'stream_event', - uuid: 'restored', - event: { type: 'message_start', message: { role: 'assistant', model: 'claude-opus-5-5' } } + parent_tool_use_id: null, + event: { + type: 'message_start', + message: { id: 'answer', role: 'assistant', model: 'claude-opus-4-8', content: [] } + } }) - expect((await read()).current.reportedModel).toBe('claude-opus-5-5') - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-4-8' }) - expect((await read()).current).toMatchObject({ - model: 'claude-opus-4-8', - reportedModel: 'claude-opus-4-8' + claudeFrame(connection, { + type: 'assistant', + parent_tool_use_id: null, + message: { + id: 'answer', + role: 'assistant', + model: 'claude-opus-4-8', + content: [{ type: 'text', text: 'Finished.' }] + } }) - await adapter.setOption({ sessionId: 'session-1', fence: 7, key: 'model', value: 'sonnet' }) - expect((await read()).current.reportedModel).toBeUndefined() - } finally { - await adapter.closeAll() - } -}) - -it('retains the init context suffix when the response reports the same bare model', async () => { - const claude = fakeClaude({ initModel: 'claude-opus-5-5[1m]' }) - const adapter = await acquired(claude) - const connection = claude.connections[0]! - try { - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'first-response', - body: USER_MESSAGE, - fence: 7 - }) - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5[1m]' }) - claudeFrame(connection, { - type: 'assistant', - uuid: 'first-response', - message: { role: 'assistant', model: 'claude-opus-5-5', content: [] } - }) - expect( - (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current.reportedModel - ).toBe('claude-opus-5-5[1m]') - await adapter.setOption({ sessionId: 'session-1', fence: 7, key: 'model', value: 'opus' }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'after-context-pick', - body: USER_MESSAGE, - fence: 7 - }) - claudeFrame(connection, { - type: 'assistant', - uuid: 'after-context-pick', - message: { role: 'assistant', model: 'claude-opus-5-5', content: [] } - }) - expect( - (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current.reportedModel - ).toBe('claude-opus-5-5') - } finally { - await adapter.closeAll() - } -}) - -it('retires the answered model on a saved pick until a turn carries that pick', async () => { - const claude = fakeClaude({ initModel: 'claude-opus-5-5' }) - const adapter = await acquired(claude) - const connection = claude.connections[0]! - const read = async () => (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current - const answer = (uuid: string, model: string) => - claudeFrame(connection, { - type: 'assistant', - uuid, - message: { role: 'assistant', model, content: [] } - }) - const turn = async (clientMessageId: string, model: string) => { - claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body: USER_MESSAGE, - executionOptions: { model }, - fence: 7 - }) - } - try { - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' }) - answer('fallback', 'claude-opus-4-8') - expect((await read()).reportedModel).toBe('claude-opus-4-8') - - adapter.noteOptionPick({ sessionId: 'session-1', fence: 7, key: 'model', value: 'sonnet' }) - answer('same-turn', 'claude-opus-4-8') - expect((await read()).reportedModel).toBeUndefined() - expect((await read()).confirmed ?? []).not.toContain('model') - - // A message accepted before the pick runs the model it captured. - await turn('queued-before-pick', 'opus') - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' }) - answer('queued-answer', 'claude-opus-5-5') - expect((await read()).reportedModel).toBeUndefined() - - await turn('carries-pick', 'sonnet') - expect(connection.calls).toContainEqual({ subtype: 'set_model', params: { model: 'sonnet' } }) - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-sonnet-5-5' }) - answer('next-fallback', 'claude-opus-4-8') - expect((await read()).reportedModel).toBe('claude-opus-4-8') + const { current } = await adapter.readOptions({ sessionId: 'session-1', fence: 7 }) + expect(current.model).toBe('claude-opus-5-5') + expect(current).not.toHaveProperty('reportedModel') } finally { await adapter.closeAll() } diff --git a/src/main/claude/structured/claude-structured-resume-point.ts b/src/main/claude/structured/claude-structured-resume-point.ts index 1d6f01857de..286bf9d70f2 100644 --- a/src/main/claude/structured/claude-structured-resume-point.ts +++ b/src/main/claude/structured/claude-structured-resume-point.ts @@ -2,8 +2,8 @@ import type { ClaudeSession, ClaudeStructuredSessionAdapterDeps } from './claude-structured-session-state' -import { settleClaudeTurnEndWaiters } from '../claude-request-end-wait' -import { isRootClaudeFrame } from '../claude-turn-opening' +import { settleClaudeTurnEndWaiters } from './turns/claude-request-end-wait' +import { isRootClaudeFrame } from './turns/claude-turn-opening' export function claudeTurnResumePointWriter( sessionId: string, diff --git a/src/main/claude/structured/claude-structured-session-acquisition.ts b/src/main/claude/structured/claude-structured-session-acquisition.ts index 68dc786dbb0..b8af7323531 100644 --- a/src/main/claude/structured/claude-structured-session-acquisition.ts +++ b/src/main/claude/structured/claude-structured-session-acquisition.ts @@ -4,16 +4,16 @@ import { claudeLaunchPermissions } from './claude-structured-inbound-control' import { resolveClaudeReplayTurn, withClaudeReplaySettlements -} from '../claude-replay-turn-resolution' -import { claudeStartedUnechoedSend } from '../claude-command-lifecycle' -import { claudeSessionStateEndsTurn } from '../claude-session-state-turn-over' -import { settleClaudeTurnEndWaiters } from '../claude-request-end-wait' +} from './turns/claude-replay-turn-resolution' +import { claudeStartedUnechoedSend } from './turns/claude-command-lifecycle' +import { claudeSessionStateEndsTurn } from './turns/claude-session-state-turn-over' +import { settleClaudeTurnEndWaiters } from './turns/claude-request-end-wait' import * as proof from './claude-structured-init-proof' -import { claudeConfigDirEnvPatch } from '../claude-config-dir-pin' +import { claudeConfigDirEnvPatch } from './launch/claude-config-dir-pin' import { claudeProcessIdentity } from './claude-structured-owner-identity' -import { ClaudePromptRegistry } from '../claude-prompt-registry' +import { ClaudePromptRegistry } from './permissions/claude-prompt-registry' import { adoptClaudeStructuredSpawnOptions } from './launch/claude-structured-spawn-options' -import { observeClaudeFrameModels } from './claude-structured-execution-observations' +import { observeClaudeExecutionModel } from './claude-structured-execution-observations' import { observeClaudeFastModeFacts } from './launch/claude-structured-session-options' import { createClaudeSessionPublication, @@ -23,14 +23,14 @@ import { import type * as sessionState from './claude-structured-session-state' import { resolveClaudeAcquisitionError } from './claude-structured-session-close' import { claudeStartupError, claudeStartupExit } from './claude-structured-session-startup-exit' -import { readClaudeTranscriptEntryUuid } from '../claude-transcript-entry-uuid' +import { readClaudeTranscriptEntryUuid } from '../transcripts/claude-transcript-entry-uuid' import { claudeTurnResumePointWriter } from './claude-structured-resume-point' import { withAgentSessionCreatePhase } from '../../observability/agent-session-instrumentation' import { resolveClaudeAcquisitionLaunch } from './launch/claude-structured-acquisition-launch' import * as journal from './journal/claude-structured-session-journal-control' -import { isRootClaudeFrame } from '../claude-turn-opening' +import { isRootClaudeFrame } from './turns/claude-turn-opening' import { createClaudeStartupOutcome, endsClaudeStartup } from './claude-structured-startup-outcome' -import { claudeStartupResultError } from '../claude-stream-json-exit-error' +import { claudeStartupResultError } from '../sdk-transport/claude-stream-json-exit-error' import { claudePluginUiRecovery, ignoresClaudeRetiredConnection @@ -106,7 +106,7 @@ export async function acquireClaudeSession({ } } const permissionChanged = proof.observeClaudeReportedPermissionMode(observedOptions, message) - const modelReport = observeClaudeFrameModels(liveSession, message, init?.model) + const modelReport = observeClaudeExecutionModel(liveSession, init?.model) if (init) { initProof.resolve(init) if (liveSession) { @@ -152,7 +152,6 @@ export async function acquireClaudeSession({ acquisitionGeneration: liveSession.acquisitionGeneration, reportedOptions: { ...modelReport, - reportedModel: liveSession.reportedOptions.reportedModel, reportedPermissionMode: observedOptions.reportedPermissionMode } }) diff --git a/src/main/claude/structured/claude-structured-session-adapter.test.ts b/src/main/claude/structured/claude-structured-session-adapter.test.ts deleted file mode 100644 index 9b45fff46e1..00000000000 --- a/src/main/claude/structured/claude-structured-session-adapter.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { acquired, fakeClaude, tick } from './claude-structured-session-test-support' -import { invokeCanUseTool } from '../claude-can-use-tool-test-support' - -describe('ClaudeStructuredSessionAdapter prompts', () => { - it('leaves a prompt cancelled and unanswerable once the SDK abort signal fires', async () => { - const claude = fakeClaude() - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = await acquired(claude, {}, events) - const controller = new AbortController() - const answered = invokeCanUseTool(claude.connections[0], 'Bash', 'permission-9', 'tool-9', { - input: { command: 'rm -rf /' }, - signal: controller.signal - }) - adapter.bindPromptItemId('session-1', 'journal-9', 'permission-9') - - controller.abort() - await expect(answered.promise).resolves.toBeNull() - expect(events.at(-1)).toMatchObject({ type: 'prompt-cancelled', promptKey: 'permission-9' }) - await expect( - adapter.answerPrompt({ - sessionId: 'session-1', - itemId: 'journal-9', - kind: 'approval', - response: { kind: 'option', optionId: 'allow' }, - fence: 7, - commit: async () => undefined - }) - ).rejects.toThrow(/no longer waiting/) - }) - - it('settles an in-flight permission callback when the session closes, leaving no dangling promise', async () => { - const claude = fakeClaude() - const adapter = await acquired(claude) - const answered = invokeCanUseTool(claude.connections[0], 'Bash', 'permission-close', 'tool-c', { - input: { command: 'ls' } - }) - await tick() - expect(answered.settled()).toBe(false) - - await adapter.closeSession('session-1') - - await expect(answered.promise).resolves.toBeNull() - }) -}) diff --git a/src/main/claude/structured/claude-structured-session-adapter.ts b/src/main/claude/structured/claude-structured-session-adapter.ts index e9369cceb69..8667d913b70 100644 --- a/src/main/claude/structured/claude-structured-session-adapter.ts +++ b/src/main/claude/structured/claude-structured-session-adapter.ts @@ -1,6 +1,6 @@ import { dispatchClaudeCommand } from './claude-structured-command-dispatch' import { isKillDeliveredExitReceipt } from './claude-kill-delivered-exit-receipt' -import { claudeAcquireFailure } from '../claude-startup-failure' +import { claudeAcquireFailure } from '../sdk-transport/claude-startup-failure' import { claudeStartPublication, openClaudeStart } from './claude-structured-start-ending' import { AgentSessionStartEndings } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' import type { @@ -8,7 +8,7 @@ import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { stopCurrentClaudeBackgroundTasks } from './claude-structured-control-actions' -import { claudeHeldSends, claudeHoldsDispatch } from '../claude-command-lifecycle' +import { claudeHeldSends, claudeHoldsDispatch } from './turns/claude-command-lifecycle' import { releaseClaudeAcquisition, type ClaudeReleaseRequest @@ -18,7 +18,6 @@ import { supportsClaudeStructuredLocation } from './launch/claude-structured-loc import * as claudeOptions from './launch/claude-structured-options' import { dispatchClaudeMessage } from './launch/claude-structured-message-options' import { readClaudeStructuredSessionOptions } from './launch/claude-structured-session-options' -import { noteClaudeModelPick } from './claude-structured-execution-observations' import { ClaudeAcquisitionRegistry, type ClaudeSession, @@ -27,7 +26,7 @@ import { type ClaudeStructuredSessionEvent } from './claude-structured-session-state' import { closeAllClaudeSessions } from './claude-structured-session-close' -import { claudeStoppedRequestEndWait } from '../claude-request-end-wait' +import { claudeStoppedRequestEndWait } from './turns/claude-request-end-wait' import { finishClaudeCloseAfterExit, drainClaudeObservedExits, @@ -36,7 +35,7 @@ import { settleClaudeUnexpectedExit, type ClaudeExitLifecycle } from './claude-structured-session-exit-lifecycle' -import { drainClaudeChildWork } from '../claude-child-work-evidence' +import { drainClaudeChildWork } from '../child-work/claude-child-work-evidence' import { deliverClaudeConnectionEvent, emitClaudeStructuredSessionEvent @@ -48,9 +47,9 @@ import { settleClaudePromptFreeingChild } from './journal/claude-structured-prompt-ownership' import { claudePromptCancelRoute } from './journal/claude-structured-prompt-replies' -import { claudeForkForRewind } from '../claude-rewind-fork' -import { copyClaudeConversation } from '../claude-conversation-copy' -import { ClaudeConversationNaming } from '../claude-conversation-naming' +import { claudeForkForRewind } from '../transcripts/claude-rewind-fork' +import { copyClaudeConversation } from '../transcripts/claude-conversation-copy' +import { ClaudeConversationNaming } from '../conversation-naming/claude-conversation-naming' import { captureClaudeConversationTitleOwner } from './claude-conversation-title-owner' export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAdapter { @@ -232,12 +231,6 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda deps: this.deps, emit: (session, event) => this.emit(session, event) }) - noteOptionPick: NonNullable = (input) => { - const session = this.sessions.get(input.sessionId) - if (session?.fence === input.fence && input.key === 'model' && input.value) { - noteClaudeModelPick(session, input.value) - } - } readOptions = (input: { sessionId: string; fence: number }) => readClaudeStructuredSessionOptions(this.session(input.sessionId)) releaseAcquisition = (input: ClaudeReleaseRequest): Promise => { diff --git a/src/main/claude/structured/claude-structured-session-close.ts b/src/main/claude/structured/claude-structured-session-close.ts index ff1154cdca3..7cc681140ad 100644 --- a/src/main/claude/structured/claude-structured-session-close.ts +++ b/src/main/claude/structured/claude-structured-session-close.ts @@ -13,13 +13,13 @@ import { } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' import { AgentSessionPreSpawnError } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import type { ClaudeJournalTranslator } from '../claude-journal-translator-contract' -import type { ClaudePromptRegistry } from '../claude-prompt-registry' +import type { ClaudeJournalTranslator } from './journal/claude-journal-translator-contract' +import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' import { closeProcessRegistry } from '@orca/process-host/close-process-registry' import { retireClaudeDispatchWaiters } from './claude-structured-dispatch' -import { claudeHeldSends } from '../claude-command-lifecycle' +import { claudeHeldSends } from './turns/claude-command-lifecycle' import { settledClaudeTurnEndLeaf } from './claude-structured-resume-point' -import { settleClaudeTurnEndWaiters } from '../claude-request-end-wait' +import { settleClaudeTurnEndWaiters } from './turns/claude-request-end-wait' import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' import type { ProviderProcessCloseOptions } from '../../provider-process/provider-process-close' diff --git a/src/main/claude/structured/claude-structured-session-event.ts b/src/main/claude/structured/claude-structured-session-event.ts index ce72b47a418..a0b7a15dfd5 100644 --- a/src/main/claude/structured/claude-structured-session-event.ts +++ b/src/main/claude/structured/claude-structured-session-event.ts @@ -1,6 +1,6 @@ import type { SubmissionRejectionFact } from '../../../shared/agent-session/failures/agent-session-failure' import type * as SessionAdapter from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import type { ClaudePendingPrompt } from '../claude-prompt-registry' +import type { ClaudePendingPrompt } from './permissions/claude-prompt-registry' import type { ClaudeStartedSend } from './claude-structured-session-state' export type ClaudeAuthDiagnostic = { diff --git a/src/main/claude/structured/claude-structured-session-exit-blame.test.ts b/src/main/claude/structured/claude-structured-session-exit-blame.test.ts deleted file mode 100644 index 2aeb0529f8f..00000000000 --- a/src/main/claude/structured/claude-structured-session-exit-blame.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { - adapterFor, - fakeClaude, - identityFor, - PROVIDER_SESSION_ID -} from './claude-structured-session-test-support' -import { claudeStreamJsonExitError } from '../claude-stream-json-exit-error' -import { structuredAgentSessionStartFailureFact } from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' -import { - providerSpawnAbsence, - withProviderSpawnAbsence -} from '../../provider-process/provider-executable-missing' -import { - PROVIDER_SPAWN_FAILURE_MARKER, - supervisedProviderSpawnFailure -} from '../../provider-process/provider-spawn-failure-report' - -/** The exit error a supervised Claude connection raises when the supervisor cannot spawn `claude`. */ -function supervisedSpawnEnoentExit(): Error { - const stderr = `${PROVIDER_SPAWN_FAILURE_MARKER}${JSON.stringify({ - thrown: false, - code: 'ENOENT', - message: 'spawn claude ENOENT' - })}\n` - const status = { code: 127, signal: null, processless: false } - const reported = supervisedProviderSpawnFailure(status.code, stderr) - return withProviderSpawnAbsence( - claudeStreamJsonExitError(stderr, status), - providerSpawnAbsence(reported?.error, 'claude') - ) -} - -async function startedClaude(sink: StructuredAgentSessionEventSink) { - const claude = fakeClaude() - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = adapterFor(claude, {}, events) - await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9', events: sink }) - const ended = async () => { - await vi.waitFor(() => expect(events.some((event) => event.type === 'ended')).toBe(true)) - return events.find((event) => event.type === 'ended') - } - return { connection: claude.connections[0], ended } -} - -describe('what a started Claude session says ended it', () => { - it('says Claude stopped when the child exits on its own', async () => { - const { connection, ended } = await startedClaude({ - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {} - }) - - connection.handlers.onExit?.(new Error('claude stream-json exited (code 1): killed')) - - expect(await ended()).toMatchObject({ - cause: 'unexpected-exit', - failure: { kind: 'providerExited' } - }) - }) - - it("names Claude's root refusal of Full access rather than a bare exit", async () => { - const { connection, ended } = await startedClaude({ - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {} - }) - const refusal = - '--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons' - - connection.handlers.onExit?.( - claudeStreamJsonExitError(refusal, { code: 1, signal: null, processless: false }) - ) - - expect(await ended()).toMatchObject({ - cause: 'unexpected-exit', - failure: { kind: 'fullAccessAsRoot', detail: { text: `(code 1)\n${refusal}` } } - }) - }) - - it('says the CLI was not found when the supervisor could not spawn it', async () => { - const { connection, ended } = await startedClaude({ - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {} - }) - - connection.handlers.onExit?.(supervisedSpawnEnoentExit()) - - const event = await ended() - expect(event).toMatchObject({ cause: 'unexpected-exit', failure: { kind: 'cliMissing' } }) - // An exit during startup is worded through the start-failure path, which must keep it. - expect( - event?.type === 'ended' && structuredAgentSessionStartFailureFact({ exit: event.failure }) - ).toMatchObject({ kind: 'cliMissing' }) - }) - - it('blames Orca when a journal fault makes Orca close the child', async () => { - const { connection, ended } = await startedClaude({ - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {}, - tryAppendResolvedItemAndPublish: () => ({ accepted: false, reason: 'failed' }) - }) - - connection.handlers.onMessage?.({ - type: 'system', - subtype: 'task_notification', - session_id: PROVIDER_SESSION_ID, - task_id: 'task-1', - status: 'failed', - summary: 'failed' - }) - - expect(await ended()).toMatchObject({ - reason: 'claude background task journal sink failed', - cause: 'unexpected-exit', - failure: { kind: 'hostFault' } - }) - expect(connection.closeCount).toBeGreaterThanOrEqual(1) - }) -}) diff --git a/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts b/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts index a2e09a80453..935e631b078 100644 --- a/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts +++ b/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts @@ -14,8 +14,8 @@ import { claudeSessionHasTurnWork, settledClaudeTurnEndLeaf } from './claude-structured-resume-point' -import { claudeHeldSends } from '../claude-command-lifecycle' -import { ClaudePluginInputError } from '../claude-plugin-ui' +import { claudeHeldSends } from './turns/claude-command-lifecycle' +import { ClaudePluginInputError } from '../sdk-transport/claude-plugin-ui' import type { AgentSessionStartEndings } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' import { claudeExitEnding } from './claude-structured-start-ending' import { diff --git a/src/main/claude/structured/claude-structured-session-open.ts b/src/main/claude/structured/claude-structured-session-open.ts index 96e8b8fbe73..1dd3c6a1948 100644 --- a/src/main/claude/structured/claude-structured-session-open.ts +++ b/src/main/claude/structured/claude-structured-session-open.ts @@ -6,7 +6,7 @@ import type { import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { readClaudeStructuredSessionSettings } from './launch/claude-structured-session-acquisition-options' import { openClaudeSession, readClaudeStartupFacts } from './claude-structured-session-startup' -import { catchUpClaudeTranscript } from '../claude-transcript-catch-up' +import { catchUpClaudeTranscript } from '../transcripts/claude-transcript-catch-up' import type { ClaudeSession, ClaudeStructuredSessionAdapterDeps, diff --git a/src/main/claude/structured/claude-structured-session-publication.ts b/src/main/claude/structured/claude-structured-session-publication.ts index 30aac7965ca..6ef5e4e2151 100644 --- a/src/main/claude/structured/claude-structured-session-publication.ts +++ b/src/main/claude/structured/claude-structured-session-publication.ts @@ -8,8 +8,8 @@ import type { StructuredAgentSessionAcquireInput } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { claudeProviderHandleLink } from './claude-structured-owner-identity' -import type { ClaudePromptRegistry } from '../claude-prompt-registry' -import type { ClaudeJournalTranslator } from '../claude-journal-translator-contract' +import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' +import type { ClaudeJournalTranslator } from './journal/claude-journal-translator-contract' import type { ClaudeSession, ClaudeSessionExit, @@ -18,12 +18,12 @@ import type { ClaudeStructuredSessionEvent, ClaudeStructuredSessionAdapterDeps } from './claude-structured-session-state' -import { ClaudeBackgroundTaskTracker } from '../claude-background-task-tracker' -import { ClaudeChildWorkDecoder } from '../claude-child-work-decoder' -import { ClaudeSlashCommandCatalog } from '../claude-slash-command-catalog' +import { ClaudeBackgroundTaskTracker } from '../background-tasks/claude-background-task-tracker' +import { ClaudeChildWorkDecoder } from '../child-work/claude-child-work-decoder' +import { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' import type { ClaudeAcquisitionLaunch } from './launch/claude-structured-acquisition-launch' -import type { ClaudeNamingGeneration } from '../claude-naming-generation' +import type { ClaudeNamingGeneration } from '../conversation-naming/claude-naming-generation' import { readClaudeStartupFacts } from './claude-structured-session-startup' function claudeSessionInitialization(input: { diff --git a/src/main/claude/structured/claude-structured-session-startup-exit.ts b/src/main/claude/structured/claude-structured-session-startup-exit.ts index 6b3f39ac45e..d872af65966 100644 --- a/src/main/claude/structured/claude-structured-session-startup-exit.ts +++ b/src/main/claude/structured/claude-structured-session-startup-exit.ts @@ -1,4 +1,4 @@ -import { isClaudeQueryClosed } from '../claude-agent-sdk-control-requests' +import { isClaudeQueryClosed } from '../sdk-transport/claude-agent-sdk-control-requests' import { withTimeout } from '../../../shared/promise-timeout-fallback' import { providerExitObserved, @@ -7,7 +7,7 @@ import { } from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { claudeStartFailure, claudeStartupAnswer } from '../claude-startup-failure' +import { claudeStartFailure, claudeStartupAnswer } from '../sdk-transport/claude-startup-failure' import type { AgentSessionStartFailure } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' /** A physical exit waits briefly for initialize's answer, which the start's verdict weighs diff --git a/src/main/claude/structured/claude-structured-session-startup.ts b/src/main/claude/structured/claude-structured-session-startup.ts index 27f5e8cd116..2e8e44d918b 100644 --- a/src/main/claude/structured/claude-structured-session-startup.ts +++ b/src/main/claude/structured/claude-structured-session-startup.ts @@ -1,5 +1,5 @@ -import { isClaudeQueryClosed } from '../claude-agent-sdk-control-requests' -import { claudeStartFailure } from '../claude-startup-failure' +import { isClaudeQueryClosed } from '../sdk-transport/claude-agent-sdk-control-requests' +import { claudeStartFailure } from '../sdk-transport/claude-startup-failure' import { startupAcquisitionRefusal, providerExitObserved @@ -9,7 +9,7 @@ import { import type { AgentSessionAccountKind } from '../../../shared/agent-session/agent-session-availability' import type { StructuredAgentSessionProviderOpenResult } from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import { ClaudeSlashCommandCatalog } from '../claude-slash-command-catalog' +import { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' import { claudeAuthDiagnostic, claudeInitializationAuthError, diff --git a/src/main/claude/structured/claude-structured-session-state.ts b/src/main/claude/structured/claude-structured-session-state.ts index 130bc0f0441..05bf5f46005 100644 --- a/src/main/claude/structured/claude-structured-session-state.ts +++ b/src/main/claude/structured/claude-structured-session-state.ts @@ -1,6 +1,9 @@ import type { StructuredAgentSessionChildWorkProducer } from '../../native-chat/agent-session-wire/observations/structured-agent-session-subagent-rows' import type { ClaudeStartupOutcome } from './claude-structured-startup-outcome' -import type { ClaudeCliFlagCheck, ClaudeCliFlagFact } from '../claude-cli-flag-support' +import type { + ClaudeCliFlagCheck, + ClaudeCliFlagFact +} from '../cli-capabilities/claude-cli-flag-support' import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' import type { AgentJournalDispatchRejection } from '../../../shared/agent-session/failures/agent-session-failure-words' import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' @@ -11,20 +14,20 @@ import type { } from '../claude-stream-json-connection' import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' import type { StructuredLaunchRequest } from '../../runtime/agent-session/launch/structured-agent-launch-composition' -import type { ClaudeJournalTranslator } from '../claude-journal-translator-contract' -import type { ClaudePromptRegistry } from '../claude-prompt-registry' -import { ClaudeJournalBoundDelivery } from '../claude-journal-bound-delivery' +import type { ClaudeJournalTranslator } from './journal/claude-journal-translator-contract' +import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' +import { ClaudeJournalBoundDelivery } from './journal/claude-journal-bound-delivery' import { cancelProcessAcquisition } from '@orca/process-host/cancel-process-acquisition' import type { AgentSessionFastModeState } from '../../../shared/agent-session/agent-session-wire' import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' -import type { ClaudeBackgroundTaskTracker } from '../claude-background-task-tracker' -import type { ClaudeChildWorkDecoder } from '../claude-child-work-decoder' -import type { ClaudeSlashCommandCatalog } from '../claude-slash-command-catalog' -import type { ClaudeAtRestCommandCatalog } from '../claude-at-rest-commands' +import type { ClaudeBackgroundTaskTracker } from '../background-tasks/claude-background-task-tracker' +import type { ClaudeChildWorkDecoder } from '../child-work/claude-child-work-decoder' +import type { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' +import type { ClaudeAtRestCommandCatalog } from '../command-catalog/claude-at-rest-commands' import type { ClaudeInitProof } from './claude-structured-init-proof' import type { AgentSessionProviderHandleLink } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import type { ClaudeNamingInputs } from '../claude-naming-invocation' +import type { ClaudeNamingInputs } from '../conversation-naming/claude-naming-invocation' import type { ClaudeInitializeFacts } from './claude-structured-session-startup' export type { @@ -121,7 +124,6 @@ export type ClaudeSession = { replayContentFallbackBlocked: boolean options: Map reportedOptions: { - reportedModel?: string model?: string effort?: string fastMode?: boolean @@ -135,10 +137,6 @@ export type ClaudeSession = { fastModePerSessionOptIn?: boolean /** Mutation sequence of the last model report; newer writes outrank it. */ reportedModelMutation: number - /** A saved model pick no turn of this process has carried; its reports predate the pick. */ - modelPickAwaitingTurn?: string - /** `dispatchSequence` at the last model write; that turn's replies predate the pick. */ - modelMutationDispatch?: number /** Options whose recorded value the provider reported, not merely accepted. */ confirmedOptions: Set /** Inputs carried by launch or accepted controls, independent of provider reports. */ diff --git a/src/main/claude/structured/claude-structured-start-ending.ts b/src/main/claude/structured/claude-structured-start-ending.ts index 58cf01ac006..8d7a102e96b 100644 --- a/src/main/claude/structured/claude-structured-start-ending.ts +++ b/src/main/claude/structured/claude-structured-start-ending.ts @@ -9,7 +9,7 @@ import type { StructuredAgentSessionProviderOpenResult } from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' import { openClaudeStructuredSession } from './claude-structured-session-open' -import { claudeStartFailure } from '../claude-startup-failure' +import { claudeStartFailure } from '../sdk-transport/claude-startup-failure' import type { ClaudeSession, ClaudeSessionExit } from './claude-structured-session-state' /** Publishes an acquisition's session with its start ending admitted first, so its exit is never diff --git a/src/main/claude/structured/journal/claude-api-retry-row.ts b/src/main/claude/structured/journal/claude-api-retry-row.ts new file mode 100644 index 00000000000..b9412a19734 --- /dev/null +++ b/src/main/claude/structured/journal/claude-api-retry-row.ts @@ -0,0 +1,41 @@ +import { + agentSessionFailureFact, + providerDiagnostic, + readProviderRetry +} from '../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import type { AgentJournalStatusItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { TUI_AGENT_DISPLAY_NAMES } from '../../../../shared/agent-launch/catalog/tui-agent-display-names' + +export const CLAUDE_API_RETRY_FRAME_KIND = 'message:system:api_retry' + +export function claudeApiRetryRowBody(message: Record): AgentJournalStatusItem { + const retry = readProviderRetry({ + error: message.error, + status: message.error_status, + attempt: message.attempt, + maxRetries: message.max_retries + }) + const words = agentSessionFailureWords( + agentSessionFailureFact('providerRetrying', { + detail: providerDiagnostic(JSON.stringify(message), 'log'), + ...(retry ? { retry } : {}) + }), + { surface: 'row', agentName: TUI_AGENT_DISPLAY_NAMES.claude } + ) + return { kind: 'status', tone: 'warning', ...words } +} + +// Missing or non-increasing attempt numbers start a new retry run. +export function createClaudeApiRetryRuns(): (message: Record) => number { + let run = 0 + let lastAttempt: number | null = null + return (message) => { + const attempt = typeof message.attempt === 'number' ? message.attempt : null + if (attempt === null || lastAttempt === null || attempt <= lastAttempt) { + run += 1 + } + lastAttempt = attempt + return run + } +} diff --git a/src/main/claude/claude-assistant-failures.ts b/src/main/claude/structured/journal/claude-assistant-failures.ts similarity index 86% rename from src/main/claude/claude-assistant-failures.ts rename to src/main/claude/structured/journal/claude-assistant-failures.ts index e7d81e487e2..4be03591e19 100644 --- a/src/main/claude/claude-assistant-failures.ts +++ b/src/main/claude/structured/journal/claude-assistant-failures.ts @@ -1,11 +1,11 @@ import { agentSessionFailureFact, providerDiagnostic -} from '../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' -import { BoundedMap } from '../../shared/bounded-map' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' -import type { AgentSessionAccountKind } from '../../shared/agent-session/agent-session-availability' +} from '../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import { BoundedMap } from '../../../../shared/bounded-map' +import { claudeRecord, claudeText } from './claude-structured-item-translation' +import type { AgentSessionAccountKind } from '../../../../shared/agent-session/agent-session-availability' /** Associates the assistant's typed error with its duplicate result, never with error text. */ export class ClaudeAssistantFailures { diff --git a/src/main/claude/claude-final-output-coverage.ts b/src/main/claude/structured/journal/claude-final-output-coverage.ts similarity index 94% rename from src/main/claude/claude-final-output-coverage.ts rename to src/main/claude/structured/journal/claude-final-output-coverage.ts index 416ab91c8d1..96eca1bc37e 100644 --- a/src/main/claude/claude-final-output-coverage.ts +++ b/src/main/claude/structured/journal/claude-final-output-coverage.ts @@ -1,7 +1,7 @@ import type { StructuredAgentSessionEventSink, StructuredAgentSessionSinkAdmission -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' /** A refused final snapshot makes this acquisition's leaf unsafe; the next open re-derives it. */ export function createClaudeFinalOutputCoverage(target: StructuredAgentSessionEventSink) { diff --git a/src/main/claude/claude-informational-row.ts b/src/main/claude/structured/journal/claude-informational-row.ts similarity index 83% rename from src/main/claude/claude-informational-row.ts rename to src/main/claude/structured/journal/claude-informational-row.ts index 049fddeb31e..2168a322249 100644 --- a/src/main/claude/claude-informational-row.ts +++ b/src/main/claude/structured/journal/claude-informational-row.ts @@ -3,10 +3,10 @@ import { hookOutcomeRowBody, type AgentSessionHookOutcome -} from '../../shared/agent-session/journal/agent-session-hook-outcome' -import { AGENT_SESSION_TURN_NOTICE_PRESENTATION } from '../../shared/agent-session/journal/agent-session-turn-notice' -import type { AgentJournalStatusItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' +} from '../../../../shared/agent-session/journal/agent-session-hook-outcome' +import { AGENT_SESSION_TURN_NOTICE_PRESENTATION } from '../../../../shared/agent-session/journal/agent-session-turn-notice' +import type { AgentJournalStatusItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { claudeRecord, claudeText } from './claude-structured-item-translation' export const CLAUDE_INFORMATIONAL_FRAME_KIND = 'message:system:informational' diff --git a/src/main/claude/claude-internal-message-content.ts b/src/main/claude/structured/journal/claude-internal-message-content.ts similarity index 96% rename from src/main/claude/claude-internal-message-content.ts rename to src/main/claude/structured/journal/claude-internal-message-content.ts index 45377a2bf1a..9a834efd669 100644 --- a/src/main/claude/claude-internal-message-content.ts +++ b/src/main/claude/structured/journal/claude-internal-message-content.ts @@ -1,4 +1,4 @@ -import { asRecord } from '../ai-vault/session-scanner-values' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' import type { ClaudeJournalTranslator } from './claude-journal-translator-contract' export function withClaudeConversationContent( diff --git a/src/main/claude/claude-journal-bound-delivery.ts b/src/main/claude/structured/journal/claude-journal-bound-delivery.ts similarity index 97% rename from src/main/claude/claude-journal-bound-delivery.ts rename to src/main/claude/structured/journal/claude-journal-bound-delivery.ts index f095cc7576d..2e8e256fcc8 100644 --- a/src/main/claude/claude-journal-bound-delivery.ts +++ b/src/main/claude/structured/journal/claude-journal-bound-delivery.ts @@ -1,7 +1,7 @@ import type { StructuredAgentSessionEventSink, StructuredAgentSessionReadingControl -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' /** Own provider observations until their saved identity input is available. */ export class ClaudeJournalBoundDelivery { diff --git a/src/main/claude/structured/journal/claude-journal-translator-contract.ts b/src/main/claude/structured/journal/claude-journal-translator-contract.ts new file mode 100644 index 00000000000..88cf38f72fa --- /dev/null +++ b/src/main/claude/structured/journal/claude-journal-translator-contract.ts @@ -0,0 +1,77 @@ +import type { ClaudeTaskInvocations } from '../../background-tasks/claude-task-invocations' +import type { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' +import type { AgentSessionContextReport } from '../../../../shared/agent-session/agent-session-context-usage' +import type { AgentJournalTurnScope } from '../../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionSinkAdmission +} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { ClaudeChildToolQueries } from '../../subagents/claude-child-tool-queries' +import type { + ClaudeContextReportListener, + ClaudeContextReportTarget +} from '../../context-usage/claude-context-facts' +import type { ClaudeJournalPrompts } from './claude-structured-journal-prompts' +import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-event' +import type { ClaudeCommandStart } from '../turns/claude-command-turn' + +import type { AgentSessionDeltaCoalescerDeps } from '../../../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' +import type { ClaudeGoalBackgroundWork } from '../../background-tasks/claude-background-task-tracker' +import type { AgentSessionAccountKind } from '../../../../shared/agent-session/agent-session-availability' + +export type ClaudeJournalTranslatorDeps = { + sink: StructuredAgentSessionEventSink + delivery?: ClaudeJournalBoundDelivery + bindPromptItemId?: (journalItemId: string, promptKey: string) => void + coalesceMs?: number + schedule?: AgentSessionDeltaCoalescerDeps['schedule'] + fallbackIdPrefix?: string + onBackgroundTaskJournalFailure?: (error: Error) => void + account?: () => AgentSessionAccountKind | undefined + model?: () => string | undefined + goalBackgroundWork?: () => ClaudeGoalBackgroundWork + /** True when this acquisition's pending startup took a turnless failure result and will fail with it. */ + acceptStartupFailure?: (message: Record) => boolean +} + +export type ClaudeJournalTranslator = { + readonly taskInvocations: ClaudeTaskInvocations + handle: (event: ClaudeStructuredSessionEvent) => void + journalPrompts: Pick< + ClaudeJournalPrompts, + 'resolve' | 'handOver' | 'cancel' | 'openCards' | 'whenWritten' + > + /** Canonical provider turn ID used by the journal row and client Stop requests. */ + readonly currentTurnId: string | null + readonly currentTurnScope: () => AgentJournalTurnScope + readonly commandTurnId: string | null + beginCommand: (start: ClaudeCommandStart) => void + forgetCommand: (turnId: string) => void + commandInterruptRequested: (turnId: string) => void + /** Root work since cycle init makes the open turn eligible for folded sends. */ + readonly openTurnInLiveProviderCycle: boolean + readonly openTurnHasInputWork: boolean + flush: () => void + childTaskParent?: (taskId: string, run?: string) => string | undefined + childToolOwner?: ClaudeChildToolQueries['childToolOwner'] + childActivity?: ClaudeChildToolQueries['childActivity'] + retryPendingTaskRows?: () => StructuredAgentSessionSinkAdmission + retryPendingCancellations?: () => StructuredAgentSessionSinkAdmission + /** Streamed blocks awaiting final frames; settlement clears them. */ + readonly pendingStreamedBlocks: number + /** Advances on conversation activity; history catch-up refuses to finish past it. */ + readonly contextActivity: number + /** Every final snapshot and turn settlement this acquisition tried was admitted. */ + readonly finalOutputAdmitted: boolean + subscribeContextUsageRequests: (listener: ClaudeContextReportListener) => () => void + recordContextReport: ( + target: ClaudeContextReportTarget, + report: AgentSessionContextReport, + askedAt: number + ) => void + /** Defer context estimates until a model change yields a new window. */ + modelMayHaveChanged: () => void + /** Size interim estimates with the applied model until its window is measured. */ + modelWritten: (model: string) => void + dispose: () => void +} diff --git a/src/main/claude/claude-journal-turn-scope.test.ts b/src/main/claude/structured/journal/claude-journal-turn-scope.test.ts similarity index 85% rename from src/main/claude/claude-journal-turn-scope.test.ts rename to src/main/claude/structured/journal/claude-journal-turn-scope.test.ts index 367959db5b8..bf5ec650614 100644 --- a/src/main/claude/claude-journal-turn-scope.test.ts +++ b/src/main/claude/structured/journal/claude-journal-turn-scope.test.ts @@ -1,11 +1,11 @@ import { expect, it, vi } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { StructuredAgentSessionEventSink, StructuredAgentSessionItemAppendOptions -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createClaudeJournalTranslator } from './claude-structured-journal-translation' function recorder() { const writes: { diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/structured/journal/claude-message-journaling.ts similarity index 90% rename from src/main/claude/claude-message-journaling.ts rename to src/main/claude/structured/journal/claude-message-journaling.ts index b25929a818a..6dca4ca3001 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/structured/journal/claude-message-journaling.ts @@ -1,12 +1,12 @@ import { writeClaudeTerminalFailure } from './claude-terminal-failure' -import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' import { agentJournalItemKey, agentJournalSubmissionKey -} from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudeBackgroundTaskRows } from './claude-background-task-rows' -import type { ClaudeToolOriginRegistry } from './claude-tool-origin-registry' +} from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { ClaudeBackgroundTaskRows } from '../../background-tasks/claude-background-task-rows' +import type { ClaudeToolOriginRegistry } from '../../subagents/claude-tool-origin-registry' import { claudeRecord, claudeMessageBody, @@ -18,24 +18,24 @@ import { claudeToolUses, readClaudeMessageEnvelope, type ClaudeToolUse -} from './structured/journal/claude-structured-item-translation' +} from './claude-structured-item-translation' import { claudeEnvelopeStopHookFeedbackRow } from './claude-stop-hook-feedback' import { appendUnmodeledContent, type ClaudeProviderFrameFallback -} from './structured/launch/claude-structured-provider-fallback' +} from '../launch/claude-structured-provider-fallback' import type { createClaudeStreamedBlockRegistry } from './claude-streamed-block-identity' import type { createClaudeStreamedTextCheckpoints } from './claude-streamed-text-checkpoints' import type { ClaudeStreamedThinking } from './claude-streamed-thinking' -import type { ClaudeProvisionalRowCorrections } from './claude-provisional-row-corrections' -import type { ClaudeSubagentIdentities } from './claude-subagent-identities' +import type { ClaudeProvisionalRowCorrections } from '../../subagents/claude-provisional-row-corrections' +import type { ClaudeSubagentIdentities } from '../../subagents/claude-subagent-identities' import { claudeStreamTurnSource, claudeStreamTurnStartSource, claudeTurnOpenedBySendEcho, type ClaudeTurnSource -} from './claude-turn-opening' -import type { ClaudeOpenTurn } from './claude-open-turn' +} from '../turns/claude-turn-opening' +import type { ClaudeOpenTurn } from '../turns/claude-open-turn' import type { ClaudeAssistantFailures } from './claude-assistant-failures' import type { ClaudeUsageLimits } from './claude-usage-limits' import type { ClaudeThreadGoal } from './claude-thread-goal' diff --git a/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts b/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts new file mode 100644 index 00000000000..6553c9a59a7 --- /dev/null +++ b/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts @@ -0,0 +1,69 @@ +import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { PROVIDER_EXIT_ROW_PREFIX } from '../../../../shared/agent-session/lifecycle/agent-session-stop-row-identity' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { ClaudeOpenTurn } from '../turns/claude-open-turn' +import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-event' + +export function journalClaudePluginInputFailure({ + event, + turn, + sink, + finish +}: { + event: Extract + turn: ClaudeOpenTurn + sink: StructuredAgentSessionEventSink + finish: (observedAt: number, failed: boolean) => void +}): void { + if (!turn.isOpen && event.unopenedSend) { + // A failed dispatched action needs a turn outcome without claiming a provider echo or acceptance. + turn.open( + { + sessionId: event.providerSessionId, + turnId: `plugin-input:${event.unopenedSend.clientMessageId}`, + userItemId: agentJournalSubmissionKey(event.unopenedSend.clientMessageId), + startedAt: event.unopenedSend.requestedAt ?? event.observedAt, + ...(event.unopenedSend.requestedAt === undefined + ? {} + : { + requestedAt: event.unopenedSend.requestedAt + }) + }, + event.observedAt + ) + } + const scope = turn.turnScope + const stopped = turn.id !== null && sink.journalStopDecidesTurn?.(turn.id, event.observedAt) + finish(event.observedAt, !stopped) + if (stopped) { + return + } + // Physical-exit settlement revises this same row after proof; it must not add another notice. + sink.appendItem( + { + provider: 'orca', + clientMessageId: `${PROVIDER_EXIT_ROW_PREFIX}${event.sessionId}:${event.fence}:${event.acquisitionGeneration}` + }, + { + kind: 'status', + tone: 'error', + ...agentSessionFailureWords(event.failure, { surface: 'row', agentName: 'Claude' }) + }, + { turnScope: scope, lifecycle: true, observedAt: event.observedAt } + ) + sink.publish({ lifecycle: true }) +} + +export function settleClaudeInterruptedTurn( + turn: ClaudeOpenTurn, + observedAt: number, + failed: boolean +): void { + turn.settle({ + state: 'interrupted', + ...(failed ? { outcome: 'failure' as const } : {}), + completedAt: observedAt + }) + turn.suppressReopen() +} diff --git a/src/main/claude/claude-plugin-ui-frames.test.ts b/src/main/claude/structured/journal/claude-plugin-ui-frames.test.ts similarity index 86% rename from src/main/claude/claude-plugin-ui-frames.test.ts rename to src/main/claude/structured/journal/claude-plugin-ui-frames.test.ts index 2013b1d4838..357a0ff6b13 100644 --- a/src/main/claude/claude-plugin-ui-frames.test.ts +++ b/src/main/claude/structured/journal/claude-plugin-ui-frames.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it, vi } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createClaudeJournalTranslator } from './claude-structured-journal-translation' function sinkState() { const items: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/structured/journal/claude-result-journaling.ts similarity index 90% rename from src/main/claude/claude-result-journaling.ts rename to src/main/claude/structured/journal/claude-result-journaling.ts index c2fade9f160..7955f7841b0 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/structured/journal/claude-result-journaling.ts @@ -1,16 +1,16 @@ import { writeClaudeTerminalFailure } from './claude-terminal-failure' -import type { ClaudeContextFacts } from './claude-context-facts' -import { claudeCommandEnd } from './claude-command-turn' +import type { ClaudeContextFacts } from '../../context-usage/claude-context-facts' +import { claudeCommandEnd } from '../turns/claude-command-turn' import type { ClaudeMessageJournalContext } from './claude-message-journaling' -import type { ClaudeJournalPrompts } from './structured/journal/claude-structured-journal-prompts' +import type { ClaudeJournalPrompts } from './claude-structured-journal-prompts' import { claudeProviderFrameKind, claudeResultFailure, isSettledClaudeResultKind -} from './structured/launch/claude-structured-provider-fallback' -import { claudeTurnEndForResult } from './claude-turn-lifecycle-item' -import { claudeFrameParentRef, isRootClaudeFrame } from './claude-turn-opening' -import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker' +} from '../launch/claude-structured-provider-fallback' +import { claudeTurnEndForResult } from '../turns/claude-turn-lifecycle-item' +import { claudeFrameParentRef, isRootClaudeFrame } from '../turns/claude-turn-opening' +import type { ClaudeGoalBackgroundWork } from '../../background-tasks/claude-background-task-tracker' import type { ClaudeJournalTranslatorDeps } from './claude-journal-translator-contract' export type ClaudeResultJournalContext = Pick< diff --git a/src/main/claude/claude-stop-hook-feedback.ts b/src/main/claude/structured/journal/claude-stop-hook-feedback.ts similarity index 80% rename from src/main/claude/claude-stop-hook-feedback.ts rename to src/main/claude/structured/journal/claude-stop-hook-feedback.ts index c889a15bf02..0b9f7086000 100644 --- a/src/main/claude/claude-stop-hook-feedback.ts +++ b/src/main/claude/structured/journal/claude-stop-hook-feedback.ts @@ -1,10 +1,10 @@ -import { hookOutcomeRowBody } from '../../shared/agent-session/journal/agent-session-hook-outcome' -import type { AgentJournalPlainStatusItem } from '../../shared/agent-session/journal/agent-session-journal-types' +import { hookOutcomeRowBody } from '../../../../shared/agent-session/journal/agent-session-hook-outcome' +import type { AgentJournalPlainStatusItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' import { claudeRecord, claudeText, type ClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' +} from './claude-structured-item-translation' // Claude injects a blocking Stop hook's reason as a meta user turn; exit-2 hooks prefix it with their command. const STOP_HOOK_FEEDBACK = /^Stop hook feedback:\n/ diff --git a/src/main/claude/claude-streamed-block-identity.ts b/src/main/claude/structured/journal/claude-streamed-block-identity.ts similarity index 95% rename from src/main/claude/claude-streamed-block-identity.ts rename to src/main/claude/structured/journal/claude-streamed-block-identity.ts index 1f42262db57..9bacee58599 100644 --- a/src/main/claude/claude-streamed-block-identity.ts +++ b/src/main/claude/structured/journal/claude-streamed-block-identity.ts @@ -1,5 +1,5 @@ -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import { claudeRecord, claudeText } from './claude-structured-item-translation' // Stream and final frames have different UUIDs; reconcile by message.id and block order to avoid duplicate rows. diff --git a/src/main/claude/structured/journal/claude-streamed-text-checkpoints.test.ts b/src/main/claude/structured/journal/claude-streamed-text-checkpoints.test.ts new file mode 100644 index 00000000000..2220f57d102 --- /dev/null +++ b/src/main/claude/structured/journal/claude-streamed-text-checkpoints.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalProducerLinkage } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { StructuredAgentSessionAppendOptions } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createClaudeStreamedTextCheckpoints } from './claude-streamed-text-checkpoints' +import type { + ClaudeSubagentLinkageSource, + ClaudeSubagentLinkageVerdict +} from '../../subagents/claude-subagent-linkage' + +function identityOf(uuid: string): AgentJournalItemIdentity { + return { provider: 'claude', sessionId: 'claude-session', uuid } +} + +/** Scopeless blocks are root-owned and must never consult the child resolver. */ +const unconsultedProducer: ClaudeSubagentLinkageSource = { + linkageFor: () => { + throw new Error('resolver consulted for a block with no scope') + }, + settledLinkageFor: () => { + throw new Error('resolver consulted for a block with no scope') + } +} + +const CHILD_LINKAGE: AgentJournalProducerLinkage = { + agentId: 'task-1', + providerParentRef: 'toolu_1', + producerKind: 'agent' +} + +/** Resolve announcements mid-stream; use the raw reference if no announcement arrives. */ +function scriptedProducer() { + let verdict: ClaudeSubagentLinkageVerdict = { kind: 'pending' } + const settledFallback: Extract = { + kind: 'linked', + linkage: { agentId: 'toolu_1', providerParentRef: 'toolu_1', producerKind: 'agent' } + } + return { + source: { + linkageFor: () => verdict, + settledLinkageFor: () => (verdict.kind === 'pending' ? settledFallback : verdict) + } satisfies ClaudeSubagentLinkageSource, + resolve: (linkage: AgentJournalProducerLinkage) => { + verdict = { kind: 'linked', linkage } + } + } +} + +function checkpoints(producer: ClaudeSubagentLinkageSource = unconsultedProducer) { + const rows: { uuid: string; text: string }[] = [] + const stamps: StructuredAgentSessionAppendOptions[] = [] + let scheduled: (() => void) | null = null + const store = createClaudeStreamedTextCheckpoints({ + producer, + persist: (identity, text, options) => { + rows.push({ uuid: 'uuid' in identity ? identity.uuid : '', text }) + stamps.push(options) + }, + schedule: (run) => { + scheduled = run + return () => { + scheduled = null + } + } + }) + return { + store, + rows, + stamps, + runWindow: () => { + const run = scheduled as (() => void) | null + run?.() + } + } +} + +describe('claude streamed text checkpoints', () => { + it('writes a checkpoint at once while the producing agent is provisional', () => { + const producer = scriptedProducer() + const { store, rows, stamps, runWindow } = checkpoints(producer.source) + + store.append(identityOf('block-1'), 'partial', 'toolu_1') + runWindow() + expect(rows).toEqual([{ uuid: 'block-1', text: 'partial' }]) + expect(stamps.at(-1)).toMatchObject({ agentId: 'toolu_1' }) + + // Flush advances text; reattribute corrects linkage even when text is unchanged. + producer.resolve(CHILD_LINKAGE) + store.flush() + expect(stamps.at(-1)).toMatchObject({ agentId: 'toolu_1' }) + + store.reattribute() + + expect(rows.at(-1)).toEqual({ uuid: 'block-1', text: 'partial' }) + expect(stamps.at(-1)).toEqual(CHILD_LINKAGE) + }) +}) diff --git a/src/main/claude/claude-streamed-text-checkpoints.ts b/src/main/claude/structured/journal/claude-streamed-text-checkpoints.ts similarity index 88% rename from src/main/claude/claude-streamed-text-checkpoints.ts rename to src/main/claude/structured/journal/claude-streamed-text-checkpoints.ts index 3345ea2e911..4713a2532bd 100644 --- a/src/main/claude/claude-streamed-text-checkpoints.ts +++ b/src/main/claude/structured/journal/claude-streamed-text-checkpoints.ts @@ -1,12 +1,12 @@ -import { agentJournalLinkageFields } from '../../shared/agent-session/journal/agent-session-journal-producer' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionAppendOptions } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { agentJournalLinkageFields } from '../../../../shared/agent-session/journal/agent-session-journal-producer' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { StructuredAgentSessionAppendOptions } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { createAgentSessionDeltaCoalescer, type AgentSessionDeltaCoalescerDeps -} from '../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' -import type { ClaudeSubagentLinkageSource } from './claude-subagent-linkage' +} from '../../../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' +import type { ClaudeSubagentLinkageSource } from '../../subagents/claude-subagent-linkage' export type ClaudeStreamedTextCheckpointDeps = { /** Rewrite accumulated text; ended marks the last write when no final frame will arrive. */ diff --git a/src/main/claude/claude-streamed-thinking.ts b/src/main/claude/structured/journal/claude-streamed-thinking.ts similarity index 82% rename from src/main/claude/claude-streamed-thinking.ts rename to src/main/claude/structured/journal/claude-streamed-thinking.ts index 9c147e7a362..675433bbf5d 100644 --- a/src/main/claude/claude-streamed-thinking.ts +++ b/src/main/claude/structured/journal/claude-streamed-thinking.ts @@ -1,13 +1,13 @@ -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalMessageItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalTurnScope } from '../../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' import { endedJournalReasoning, journalReasoningBody -} from '../native-chat/agent-session-journal/item-lifecycle/journal-reasoning-row' -import type { AgentSessionDeltaCoalescerDeps } from '../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +} from '../../../native-chat/agent-session-journal/item-lifecycle/journal-reasoning-row' +import type { AgentSessionDeltaCoalescerDeps } from '../../../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { createClaudeStreamedBlockRegistry } from './claude-streamed-block-identity' import { createClaudeStreamedTextCheckpoints, @@ -19,8 +19,8 @@ import { claudeThinkingIdentity, claudeThinkingText, type ClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' -import type { ClaudeSubagentLinkageSource } from './claude-subagent-linkage' +} from './claude-structured-item-translation' +import type { ClaudeSubagentLinkageSource } from '../../subagents/claude-subagent-linkage' function streamScope(frame: Record): string | null { const event = claudeRecord(frame.event) diff --git a/src/main/claude/structured/journal/claude-structured-item-translation.ts b/src/main/claude/structured/journal/claude-structured-item-translation.ts index 5b313f8194b..56b1c1f48c5 100644 --- a/src/main/claude/structured/journal/claude-structured-item-translation.ts +++ b/src/main/claude/structured/journal/claude-structured-item-translation.ts @@ -5,7 +5,7 @@ import type { import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { NativeChatBlock } from '../../../../shared/native-chat/native-chat-types' import { journalPayload } from '../../../native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds' -import { isClaudeInjectedUserMessage } from '../../claude-internal-message-content' +import { isClaudeInjectedUserMessage } from './claude-internal-message-content' import { isClaudeToolUseContent, isClaudeToolResultContent, diff --git a/src/main/claude/structured/journal/claude-structured-journal-prompt-retry.test.ts b/src/main/claude/structured/journal/claude-structured-journal-prompt-retry.test.ts deleted file mode 100644 index e1812986743..00000000000 --- a/src/main/claude/structured/journal/claude-structured-journal-prompt-retry.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import type { - StructuredAgentSessionEventSink, - StructuredAgentSessionReadingControl -} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudePendingPrompt } from '../../claude-prompt-registry' -import { createClaudeJournalTranslator } from './claude-structured-journal-translation' -import { bindClaudeJournalReadingControl } from './claude-structured-session-journal-control' - -function approval(promptKey: string): ClaudePendingPrompt { - return { - requestId: promptKey, - promptKey, - toolUseId: 'tool-retry', - toolName: 'Bash', - kind: 'approval', - input: { command: 'git status' }, - suggestions: [], - questionIds: [], - settle: () => {} - } -} - -function transientBackpressureSink( - refusedAt: 'append' | 'publish', - persistent = false -): { - sink: StructuredAgentSessionEventSink - durableApproval: () => AgentJournalItemBody | undefined - appendAttempts: () => number - publishAttempts: () => number - appliedSettlements: Set - release: () => void -} { - const staged = new Map() - const durable = new Map() - const appliedSettlements = new Set() - let lifecycleAppendAttempts = 0 - let lifecyclePublishAttempts = 0 - let released = false - const persist = (): void => { - durable.clear() - for (const [key, body] of staged) { - durable.set(key, body) - } - } - const applyItem = (identity: AgentJournalItemIdentity, body: AgentJournalItemBody): void => { - staged.set(agentJournalItemKey(identity), body) - } - return { - sink: { - appendItem: applyItem, - appendTombstone: (identity) => staged.delete(agentJournalItemKey(identity)), - publish: persist, - tryAppendLifecycleBatch: (settlementId, mutations) => { - lifecycleAppendAttempts += 1 - if (refusedAt === 'append' && (persistent ? !released : lifecycleAppendAttempts === 1)) { - return { accepted: false, reason: 'backpressure' } - } - if (!appliedSettlements.has(settlementId)) { - for (const mutation of mutations) { - if (mutation.kind === 'item') { - applyItem(mutation.identity, mutation.body) - } else { - staged.delete(agentJournalItemKey(mutation.identity)) - } - } - appliedSettlements.add(settlementId) - } - return { accepted: true } - }, - tryPublish: () => { - lifecyclePublishAttempts += 1 - if (refusedAt === 'publish' && (persistent ? !released : lifecyclePublishAttempts === 1)) { - return { accepted: false, reason: 'backpressure' } - } - persist() - return { accepted: true } - } - }, - durableApproval: () => [...durable.values()].find((body) => body.kind === 'approval'), - appendAttempts: () => lifecycleAppendAttempts, - publishAttempts: () => lifecyclePublishAttempts, - appliedSettlements, - release: () => { - released = true - } - } -} - -function rootResult() { - return { - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'result', - subtype: 'success', - uuid: 'result-success', - session_id: 'claude-session', - parent_tool_use_id: null, - is_error: false, - duration_ms: 1 - } - } -} - -function streamDelta(index: number) { - return { - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'stream_event', - uuid: `stream-${index}`, - session_id: 'claude-session', - parent_tool_use_id: null, - event: { - type: 'content_block_delta', - index: 0, - delta: { type: 'text_delta', text: 'x' } - } - } - } -} - -describe('Claude journal prompt cancellation retry', () => { - it.each(['append', 'publish'] as const)( - 'retries after transient lifecycle %s backpressure', - (refusedAt) => { - const state = transientBackpressureSink(refusedAt) - const translator = createClaudeJournalTranslator({ sink: state.sink }) - const prompt = approval('permission-retry') - - translator.handle({ type: 'prompt', sessionId: 'orca-session', prompt }) - translator.handle({ - type: 'prompt-cancelled', - sessionId: 'orca-session', - promptKey: prompt.promptKey - }) - expect(state.durableApproval()).toMatchObject({ resolution: { state: 'pending' } }) - - translator.handle(rootResult()) - expect(state.durableApproval()).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(state.appendAttempts()).toBe(2) - expect(state.publishAttempts()).toBe(refusedAt === 'publish' ? 2 : 1) - expect(state.appliedSettlements).toEqual(new Set(['prompt-cancelled:permission-retry'])) - - translator.handle(rootResult()) - expect(state.appendAttempts()).toBe(2) - expect(state.publishAttempts()).toBe(refusedAt === 'publish' ? 2 : 1) - } - ) - - it('keeps streaming frames off retry work and recovers at the next root result', () => { - const state = transientBackpressureSink('append', true) - const translator = createClaudeJournalTranslator({ sink: state.sink }) - const prompt = approval('permission-streaming') - - translator.handle({ type: 'prompt', sessionId: 'orca-session', prompt }) - translator.handle({ - type: 'prompt-cancelled', - sessionId: 'orca-session', - promptKey: prompt.promptKey - }) - expect(state.appendAttempts()).toBe(1) - - for (let index = 0; index < 100; index += 1) { - translator.handle(streamDelta(index)) - } - expect(state.appendAttempts()).toBe(1) - - state.release() - translator.handle(rootResult()) - expect(state.appendAttempts()).toBe(2) - expect(state.durableApproval()).toMatchObject({ resolution: { state: 'cancelled' } }) - }) - - it('closes the card on the sink drain when no later provider event comes', () => { - const state = transientBackpressureSink('append', true) - let control: StructuredAgentSessionReadingControl | undefined - const sink: StructuredAgentSessionEventSink = { - ...state.sink, - bindReadingControl: (next) => { - control = next - return () => {} - } - } - const translator = createClaudeJournalTranslator({ sink }) - const connection = { pauseReading: vi.fn(), resumeReading: vi.fn() } - bindClaudeJournalReadingControl(sink, connection, translator) - const prompt = approval('permission-drain') - - translator.handle({ type: 'prompt', sessionId: 'orca-session', prompt }) - control?.pauseReading() - translator.handle({ - type: 'prompt-cancelled', - sessionId: 'orca-session', - promptKey: prompt.promptKey - }) - control?.resumeReading() - expect(state.durableApproval()).toMatchObject({ resolution: { state: 'pending' } }) - expect(connection.resumeReading).not.toHaveBeenCalled() - - state.release() - control?.resumeReading() - expect(state.durableApproval()).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(connection.resumeReading).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/claude/structured/journal/claude-structured-journal-translation.test.ts b/src/main/claude/structured/journal/claude-structured-journal-translation.test.ts deleted file mode 100644 index f12bc3c1e4e..00000000000 --- a/src/main/claude/structured/journal/claude-structured-journal-translation.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import { openAgentSessionJournal } from '../../../native-chat/agent-session-journal/journal-store-factory' -import { createDeferredStructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudePendingPrompt } from '../../claude-prompt-registry' -import { createClaudeJournalTranslator } from './claude-structured-journal-translation' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { testEventSinkLogging } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -// Claude Code 2.1.258 / SDK 0.3.251 capture: only message.id links partial and final frames. -function streamEvent(uuid: string, event: Record) { - return { - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'stream_event', - uuid, - session_id: 'claude-session', - parent_tool_use_id: null, - event - } - } -} - -function resultFrame(subtype: string, fields: Record) { - return { - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'result', - subtype, - duration_ms: 1200, - duration_api_ms: 1100, - num_turns: 1, - session_id: 'claude-session', - uuid: `result-${subtype}`, - ...fields - } - } -} - -function streamedTextTurn(input: { - messageId: string - startUuid: string - finalUuid: string - chunks: string[] -}) { - const text = input.chunks.join('') - return { - start: [ - streamEvent(`${input.messageId}-message-start`, { - type: 'message_start', - message: { id: input.messageId, role: 'assistant', content: [] } - }), - streamEvent(input.startUuid, { - type: 'content_block_start', - index: 0, - content_block: { type: 'text', text: '' } - }) - ], - deltas: input.chunks.map((chunk, index) => - streamEvent(`${input.messageId}-delta-${index}`, { - type: 'content_block_delta', - index: 0, - delta: { type: 'text_delta', text: chunk } - }) - ), - final: { - type: 'message' as const, - sessionId: 'orca-session', - message: { - type: 'assistant', - uuid: input.finalUuid, - session_id: 'claude-session', - parent_tool_use_id: null, - message: { - id: input.messageId, - role: 'assistant', - content: [{ type: 'text', text }], - stop_reason: null - } - } - }, - stop: [ - streamEvent(`${input.messageId}-block-stop`, { type: 'content_block_stop', index: 0 }), - streamEvent(`${input.messageId}-message-delta`, { - type: 'message_delta', - delta: { stop_reason: 'end_turn' } - }), - streamEvent(`${input.messageId}-message-stop`, { type: 'message_stop' }), - resultFrame('success', { - is_error: false, - result: text, - stop_reason: 'end_turn', - terminal_reason: 'completed' - }) - ], - text - } -} - -function assistantMessages(items: T[]): T[] { - return items.filter((item) => item.body.kind === 'message' && item.body.role === 'assistant') -} - -function providerFrameKinds(items: { body: AgentJournalItemBody }[]): string[] { - return items.flatMap((item) => - item.body.kind === 'status' && item.body.providerFrame ? [item.body.providerFrame.kind] : [] - ) -} - -const JOURNAL_IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('claude-session', 'leaf-1') -} - -let journalRoot = '' - -beforeEach(async () => { - journalRoot = await mkdtemp(join(tmpdir(), 'orca-claude-journal-translation-')) -}) - -afterEach(async () => { - await closeTestJournalHostDatabases() - await rm(journalRoot, { recursive: true, force: true }) -}) - -describe('Claude structured journal translation', () => { - it('journals a count-to-200 stream as one assistant item carrying the complete reply', async () => { - const journal = await openAgentSessionJournal({ - identity: JOURNAL_IDENTITY, - database: openTestJournalHostDatabase(journalRoot), - now: () => 1_700_000_000_000, - mintEpoch: () => 'epoch-1' - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - deferred.bind({ journal, fence: 1, publish: vi.fn() }) - let scheduled: (() => void) | null = null - const translator = createClaudeJournalTranslator({ - sink: deferred.sink, - schedule: (run) => { - scheduled = run - return () => { - scheduled = null - } - } - }) - const numbers = Array.from({ length: 200 }, (_, index) => String(index + 1)) - // The chunk boundaries the real CLI produced for this prompt. - const boundaries = [0, 1, 45, 93, 141, 189, 200] - const chunks = boundaries.slice(1).map((end, index) => { - const slice = numbers.slice(boundaries[index], end).join('\n') - return index === 0 ? slice : `\n${slice}` - }) - const turn = streamedTextTurn({ - messageId: 'msg_count', - startUuid: 'count-start', - finalUuid: 'count-final', - chunks - }) - - for (const event of turn.start) { - translator.handle(event) - } - for (const delta of turn.deltas) { - translator.handle(delta) - // Each chunk lands in its own coalescing window, as it did on the wire. - const run = scheduled as (() => void) | null - run?.() - } - translator.handle(turn.final) - for (const event of turn.stop) { - translator.handle(event) - } - await deferred.drained() - - const items: AgentJournalRenderItem[] = journal.snapshot().items - const assistant = assistantMessages(items) - expect(assistant.map((item) => item.itemId)).toEqual([ - 'claude:claude-session:block%3Amsg_count%3A0' - ]) - expect(assistant[0]?.body).toEqual({ - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: numbers.join('\n') }] - }) - expect(providerFrameKinds(items)).toEqual([]) - }) - - it('restores a cancelled prompt as terminal history after reopening the journal', async () => { - const journal = await openAgentSessionJournal({ - identity: JOURNAL_IDENTITY, - database: openTestJournalHostDatabase(journalRoot), - now: () => 1_700_000_000_000, - mintEpoch: () => 'epoch-1' - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - deferred.bind({ journal, fence: 1, publish: vi.fn() }) - const translator = createClaudeJournalTranslator({ sink: deferred.sink }) - const approval = prompt({ - requestId: 'permission-1', - promptKey: 'permission-1', - toolUseId: 'tool-1', - toolName: 'Bash', - kind: 'approval', - input: { command: 'git status' }, - questionIds: [] - }) - - translator.handle({ type: 'prompt', sessionId: 'orca-session', prompt: approval }) - translator.handle({ - type: 'prompt-cancelled', - sessionId: 'orca-session', - promptKey: approval.promptKey - }) - await expect(deferred.drained()).resolves.toEqual({ ok: true }) - deferred.close() - await journal.close() - - const reopened = await openAgentSessionJournal({ - identity: JOURNAL_IDENTITY, - database: openTestJournalHostDatabase(journalRoot), - now: () => 1_700_000_000_000, - mintEpoch: () => 'epoch-2' - }) - expect(reopened.snapshot().items).toEqual([ - expect.objectContaining({ - body: expect.objectContaining({ - kind: 'approval', - resolution: expect.objectContaining({ state: 'cancelled' }) - }) - }) - ]) - await reopened.close() - }) -}) - -function prompt( - input: Pick< - ClaudePendingPrompt, - 'requestId' | 'promptKey' | 'toolUseId' | 'toolName' | 'kind' | 'input' | 'questionIds' - > -): ClaudePendingPrompt { - return { - ...input, - suggestions: [], - settle: () => {} - } -} diff --git a/src/main/claude/structured/journal/claude-structured-journal-translation.ts b/src/main/claude/structured/journal/claude-structured-journal-translation.ts index b9a7cd8de4e..685c7223bc6 100644 --- a/src/main/claude/structured/journal/claude-structured-journal-translation.ts +++ b/src/main/claude/structured/journal/claude-structured-journal-translation.ts @@ -1,48 +1,48 @@ -import { ClaudeTaskInvocations } from '../../claude-task-invocations' -import { ClaudeJournalBoundDelivery } from '../../claude-journal-bound-delivery' -import type * as contract from '../../claude-journal-translator-contract' +import { ClaudeTaskInvocations } from '../../background-tasks/claude-task-invocations' +import { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' +import type * as contract from './claude-journal-translator-contract' import { claudeStreamingMessageBody, type ClaudeToolUse } from './claude-structured-item-translation' -import { publishClaudeTurnActivity } from '../../claude-turn-activity' +import { publishClaudeTurnActivity } from '../turns/claude-turn-activity' import { claudeProviderFrameKind, createClaudeProviderFrameFallback, isClaudeProgressFrame } from '../launch/claude-structured-provider-fallback' -import { ClaudeBackgroundTaskRows } from '../../claude-background-task-rows' -import { ClaudeToolOriginRegistry } from '../../claude-tool-origin-registry' -import { ClaudeProvisionalRowCorrections } from '../../claude-provisional-row-corrections' -import { createClaudeStreamedThinking } from '../../claude-streamed-thinking' -import { ClaudeSubagentIdentities } from '../../claude-subagent-identities' -import { ClaudeJournaledSubagents } from '../../claude-subagent-journaled-identities' -import { createClaudeStreamedBlockRegistry } from '../../claude-streamed-block-identity' -import { createClaudeStreamedTextCheckpoints } from '../../claude-streamed-text-checkpoints' +import { ClaudeBackgroundTaskRows } from '../../background-tasks/claude-background-task-rows' +import { ClaudeToolOriginRegistry } from '../../subagents/claude-tool-origin-registry' +import { ClaudeProvisionalRowCorrections } from '../../subagents/claude-provisional-row-corrections' +import { createClaudeStreamedThinking } from './claude-streamed-thinking' +import { ClaudeSubagentIdentities } from '../../subagents/claude-subagent-identities' +import { ClaudeJournaledSubagents } from '../../subagents/claude-subagent-journaled-identities' +import { createClaudeStreamedBlockRegistry } from './claude-streamed-block-identity' +import { createClaudeStreamedTextCheckpoints } from './claude-streamed-text-checkpoints' import { claudeFrameParentRef, claudeStreamTurnSource, isRootClaudeFrame -} from '../../claude-turn-opening' -import { ClaudeOpenTurn } from '../../claude-open-turn' -import { absorbClaudeCommandFrame, claudeCommandCurrentTurn } from '../../claude-command-turn' -import { ClaudeContextFacts } from '../../claude-context-facts' -import { claudeSessionStateEndsTurn } from '../../claude-session-state-turn-over' +} from '../turns/claude-turn-opening' +import { ClaudeOpenTurn } from '../turns/claude-open-turn' +import { absorbClaudeCommandFrame, claudeCommandCurrentTurn } from '../turns/claude-command-turn' +import { ClaudeContextFacts } from '../../context-usage/claude-context-facts' +import { claudeSessionStateEndsTurn } from '../turns/claude-session-state-turn-over' import { ClaudeJournalPrompts } from './claude-structured-journal-prompts' -import { claudeChildToolQueries } from '../../claude-child-tool-queries' -import { journalClaudeMessage, journalClaudeStream } from '../../claude-message-journaling' -import type { ClaudeMessageJournalContext } from '../../claude-message-journaling' -import { journalClaudeResult } from '../../claude-result-journaling' -import type { ClaudeResultJournalContext } from '../../claude-result-journaling' -import { ClaudeAssistantFailures } from '../../claude-assistant-failures' -import { ClaudeUsageLimits } from '../../claude-usage-limits' -import { ClaudeThreadGoal } from '../../claude-thread-goal' -import { createClaudeFinalOutputCoverage } from '../../claude-final-output-coverage' -import { withClaudeConversationContent } from '../../claude-internal-message-content' +import { claudeChildToolQueries } from '../../subagents/claude-child-tool-queries' +import { journalClaudeMessage, journalClaudeStream } from './claude-message-journaling' +import type { ClaudeMessageJournalContext } from './claude-message-journaling' +import { journalClaudeResult } from './claude-result-journaling' +import type { ClaudeResultJournalContext } from './claude-result-journaling' +import { ClaudeAssistantFailures } from './claude-assistant-failures' +import { ClaudeUsageLimits } from './claude-usage-limits' +import { ClaudeThreadGoal } from './claude-thread-goal' +import { createClaudeFinalOutputCoverage } from './claude-final-output-coverage' +import { withClaudeConversationContent } from './claude-internal-message-content' import { journalClaudePluginInputFailure, settleClaudeInterruptedTurn -} from '../../claude-plugin-input-failure-journal' +} from './claude-plugin-input-failure-journal' export function createClaudeJournalTranslator( deps: contract.ClaudeJournalTranslatorDeps @@ -288,9 +288,8 @@ export function createClaudeJournalTranslator( get finalOutputAdmitted() { return coverage.admitted }, - markContextActivity: () => context.markActivity(), subscribeContextUsageRequests: (listener) => context.subscribeReportRequests(listener), - recordContextReport: (target, report, part) => context.recordReport(target, report, part), + recordContextReport: (target, report, askedAt) => context.recordReport(target, report, askedAt), modelMayHaveChanged: () => context.modelMayHaveChanged(), modelWritten: (model) => context.modelWritten(model), dispose: () => { diff --git a/src/main/claude/structured/journal/claude-structured-prompt-items.ts b/src/main/claude/structured/journal/claude-structured-prompt-items.ts index 094449be10b..ad4c5d3043e 100644 --- a/src/main/claude/structured/journal/claude-structured-prompt-items.ts +++ b/src/main/claude/structured/journal/claude-structured-prompt-items.ts @@ -14,7 +14,7 @@ import { askOptionPreview } from '../../../../shared/native-chat/input/native-ch import { boundJournalPromptBody } from '../../../native-chat/agent-session-journal/item-lifecycle/journal-prompt-body-bounds' import { claudeRecord, claudeText } from './claude-structured-item-translation' import { encodeClaudeQuestionOptionId } from './claude-structured-prompt-replies' -import type { ClaudePendingPrompt } from '../../claude-prompt-registry' +import type { ClaudePendingPrompt } from '../permissions/claude-prompt-registry' const APPROVAL_OPTIONS: readonly AgentJournalPromptOption[] = [ { id: 'allow', label: 'Allow', intent: 'allow_once' }, @@ -58,6 +58,7 @@ export function claudeApprovalItem(prompt: ClaudePendingPrompt): AgentJournalApp ...(prompt.blockedPath ? { blockedPath: prompt.blockedPath } : {}), ...(prompt.matchedAskRule ? { matchedAskRule: prompt.matchedAskRule } : {}), ...(prompt.subject ? { subject: prompt.subject } : {}), + ...(prompt.personOnly ? { personOnly: true } : {}), detail: detail || null, options: (planSubject ? PLAN_APPROVAL_OPTIONS : APPROVAL_OPTIONS).map((option) => ({ ...option diff --git a/src/main/claude/structured/journal/claude-structured-prompt-ownership.test.ts b/src/main/claude/structured/journal/claude-structured-prompt-ownership.test.ts deleted file mode 100644 index 35868580b36..00000000000 --- a/src/main/claude/structured/journal/claude-structured-prompt-ownership.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody -} from '../../../../shared/agent-session/journal/agent-session-journal-types' -import { describe, expect, it, vi } from 'vitest' -import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { - StructuredAgentSessionAppendOptions, - StructuredAgentSessionEventSink -} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { ClaudeJournalPrompts } from './claude-structured-journal-prompts' -import type { ClaudePendingPrompt } from '../../claude-prompt-registry' -import { - USER_MESSAGE, - type acquired, - adapterFor, - fakeClaude, - identityFor -} from '../claude-structured-session-test-support' -import { invokeCanUseTool } from '../../claude-can-use-tool-test-support' - -function lifecycleRecorder(acceptPromptCancellation = true): { - sink: StructuredAgentSessionEventSink - bodies: Map - tombstones: Set - order: string[] -} { - const bodies = new Map() - const tombstones = new Set() - const order: string[] = [] - const appendTombstone = ( - identity: Parameters[0], - options?: StructuredAgentSessionAppendOptions - ): void => { - const key = agentJournalItemKey(identity) - bodies.delete(key) - tombstones.add(key) - if (options?.lifecycle === true) { - order.push('prompt-lifecycle') - } - } - const appendItem = ( - identity: Parameters[0], - body: Parameters[1], - options?: StructuredAgentSessionAppendOptions - ): void => { - bodies.set(agentJournalItemKey(identity), body) - if (options?.lifecycle === true) { - order.push('prompt-lifecycle') - } - } - const sink: StructuredAgentSessionEventSink = { - appendItem, - appendTombstone, - tryAppendTombstone: (identity, options) => { - if (!acceptPromptCancellation) { - return { accepted: false, reason: 'backpressure' } - } - appendTombstone(identity, options) - return { accepted: true } - }, - tryAppendLifecycleBatch: (_settlementId, mutations, options) => { - if (!acceptPromptCancellation) { - return { accepted: false, reason: 'backpressure' } - } - for (const mutation of mutations) { - if (mutation.kind === 'tombstone') { - appendTombstone(mutation.identity, options) - } else { - appendItem(mutation.identity, mutation.body, options) - } - } - return { accepted: true } - }, - publish: (_options?: StructuredAgentSessionAppendOptions) => {}, - tryPublish: () => ({ accepted: true }) - } - return { sink, bodies, tombstones, order } -} - -async function startTurn( - adapter: Awaited>, - turnId = 'turn-1' -): Promise { - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: `client-${turnId}`, - body: USER_MESSAGE, - fence: 7 - }) -} - -describe('Claude live prompt ownership', () => { - it('hands the card back when the host fails to record it, so a withdrawal still closes it', async () => { - const claude = fakeClaude({ replayUuid: 'turn-1' }) - const recorded = lifecycleRecorder() - const adapter = adapterFor(claude) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: recorded.sink - }) - await startTurn(adapter) - const request = new AbortController() - invokeCanUseTool(claude.connections[0]!, 'AskUserQuestion', 'permission-1', 'tool-1', { - input: { questions: [{ question: 'Which branch?', options: [{ label: 'main' }] }] }, - signal: request.signal - }) - const [card] = [...recorded.bodies].find(([, body]) => body.kind === 'question') ?? [] - const dismiss = adapter.dismissPrompt - if (!card || !dismiss) { - throw new Error('expected the question card and a dismissal') - } - - await expect( - dismiss({ - sessionId: 'session-1', - itemId: card, - fence: 7, - answer: false, - commit: async () => { - request.abort() - throw new Error('journal write failed') - } - }) - ).rejects.toThrow('journal write failed') - - expect(recorded.bodies.get(card)).toMatchObject({ resolution: { state: 'cancelled' } }) - }) - - it('keeps every backpressured prompt cancellation retry in its owned entry', () => { - let backpressured = true - let lifecycleAttempts = 0 - const prompts = new ClaudeJournalPrompts({ - sink: { - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {}, - tryAppendLifecycleBatch: () => { - lifecycleAttempts += 1 - return backpressured ? { accepted: false, reason: 'backpressure' } : { accepted: true } - } - }, - turnScope: () => AGENT_JOURNAL_THREAD_SCOPE - }) - const registerCancellation = (index: number): void => { - const promptKey = `permission-${index}` - const prompt: ClaudePendingPrompt = { - requestId: promptKey, - promptKey, - toolUseId: `tool-${index}`, - toolName: 'Bash', - kind: 'approval', - input: { command: 'git status' }, - suggestions: [], - questionIds: [], - settle: vi.fn() - } - prompts.handle({ type: 'prompt', sessionId: 'session-1', prompt }) - prompts.cancel(promptKey) - } - - registerCancellation(0) - prompts.cancel('permission-0') - expect(prompts.pendingCancellationCount).toBe(1) - for (let index = 1; index < 65; index += 1) { - registerCancellation(index) - } - expect(prompts.pendingCancellationCount).toBe(65) - - backpressured = false - const attemptsBeforeRecovery = lifecycleAttempts - prompts.retryPendingCancellations() - expect(lifecycleAttempts - attemptsBeforeRecovery).toBe(65) - expect(prompts.pendingCancellationCount).toBe(0) - expect(prompts.size).toBe(0) - const attemptsAfterRecovery = lifecycleAttempts - prompts.retryPendingCancellations() - expect(lifecycleAttempts).toBe(attemptsAfterRecovery) - - backpressured = true - registerCancellation(65) - expect(prompts.pendingCancellationCount).toBe(1) - prompts.resolve('permission-65') - expect(prompts.pendingCancellationCount).toBe(0) - registerCancellation(66) - prompts.clear() - expect(prompts.pendingCancellationCount).toBe(0) - expect(prompts.size).toBe(0) - }) -}) diff --git a/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts b/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts index 1926810d6c9..c07c57d4a15 100644 --- a/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts +++ b/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts @@ -5,12 +5,12 @@ import { import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import type { StructuredAgentSessionAdapterStop } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-stop' import { answerClaudePrompt, cancelClaudeTurn } from '../claude-structured-control-actions' -import { leaveClaudePlanModeOnApproval } from '../../claude-plan-approval-mode' -import type { ClaudeLateDispatchSettlement } from '../../claude-replay-turn-resolution' +import { leaveClaudePlanModeOnApproval } from '../permissions/claude-plan-approval-mode' +import type { ClaudeLateDispatchSettlement } from '../turns/claude-replay-turn-resolution' import { buildClaudePromptReply, claudePromptDismissal } from './claude-structured-prompt-replies' import type { ClaudeSession } from '../claude-structured-session-state' -import type { ClaudePendingPrompt } from '../../claude-prompt-registry' -import { CLAUDE_STOP_GRACE_MS } from '../../claude-request-end-wait' +import type { ClaudePendingPrompt } from '../permissions/claude-prompt-registry' +import { CLAUDE_STOP_GRACE_MS } from '../turns/claude-request-end-wait' import type { PermissionResult } from '@anthropic-ai/claude-agent-sdk' type CancelInput = Parameters[0] diff --git a/src/main/claude/structured/journal/claude-structured-prompt-replies.ts b/src/main/claude/structured/journal/claude-structured-prompt-replies.ts index cdcd7e264e4..d5df7193646 100644 --- a/src/main/claude/structured/journal/claude-structured-prompt-replies.ts +++ b/src/main/claude/structured/journal/claude-structured-prompt-replies.ts @@ -9,7 +9,7 @@ import { isClaudePromptRecord, readClaudePromptString, type ClaudePendingPrompt -} from '../../claude-prompt-registry' +} from '../permissions/claude-prompt-registry' /** Keep `cancel` for older cards; it now means dismissal. */ export const CLAUDE_APPROVAL_DECISIONS = ['allow', 'allowForSession', 'deny', 'cancel'] as const diff --git a/src/main/claude/structured/journal/claude-structured-session-journal-control.ts b/src/main/claude/structured/journal/claude-structured-session-journal-control.ts index 374e73737dc..2cb0c99da7b 100644 --- a/src/main/claude/structured/journal/claude-structured-session-journal-control.ts +++ b/src/main/claude/structured/journal/claude-structured-session-journal-control.ts @@ -1,16 +1,16 @@ import { bindClaudeContextUsageCapture, type ClaudeContextUsageCaptureOptions -} from '../../claude-context-usage' +} from '../../context-usage/claude-context-usage' import type { StructuredAgentSessionEventSink, StructuredAgentSessionSinkAdmission } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connection' -import type { ClaudeJournalTranslator } from '../../claude-journal-translator-contract' +import type { ClaudeJournalTranslator } from './claude-journal-translator-contract' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' import type { ClaudeInitProof } from '../claude-structured-init-proof' -import type { ClaudeJournalBoundDelivery } from '../../claude-journal-bound-delivery' +import type { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' import type { ClaudeAcquisitionAttempt, ClaudeSession, diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/structured/journal/claude-terminal-failure.ts similarity index 80% rename from src/main/claude/claude-terminal-failure.ts rename to src/main/claude/structured/journal/claude-terminal-failure.ts index 0086baada02..caaf307587b 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/structured/journal/claude-terminal-failure.ts @@ -1,19 +1,19 @@ -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { isRootAgentJournalItem } from '../../shared/agent-session/journal/agent-session-journal-producer' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import { isRootAgentJournalItem } from '../../../../shared/agent-session/journal/agent-session-journal-producer' import { readAgentSessionFailureFact, providerDiagnostic -} from '../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' +} from '../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { StructuredAgentSessionRevisionJournal } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' import { agentJournalTurnRowReservedBytes, resolveAgentJournalTurnRowWrite, type AgentJournalTurnRowWrite -} from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' +} from '../../../native-chat/agent-session-timeline/agent-journal-turn-row-revision' function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity { return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` } diff --git a/src/main/claude/claude-thread-goal.ts b/src/main/claude/structured/journal/claude-thread-goal.ts similarity index 92% rename from src/main/claude/claude-thread-goal.ts rename to src/main/claude/structured/journal/claude-thread-goal.ts index ed094f4b168..12cd94e003e 100644 --- a/src/main/claude/claude-thread-goal.ts +++ b/src/main/claude/structured/journal/claude-thread-goal.ts @@ -3,11 +3,11 @@ import type { AgentJournalItemBody, AgentJournalThreadGoal -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' -import { isRootClaudeFrame } from './claude-turn-opening' -import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker' +} from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import { claudeRecord, claudeText } from './claude-structured-item-translation' +import { isRootClaudeFrame } from '../turns/claude-turn-opening' +import type { ClaudeGoalBackgroundWork } from '../../background-tasks/claude-background-task-tracker' const GOAL_SET = 'Goal set: ' const GOAL_ACTIVE = /^Goal active: ([\s\S]+) \((?:not yet evaluated|\d+ turns?)\)$/u diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/structured/journal/claude-usage-limits.ts similarity index 94% rename from src/main/claude/claude-usage-limits.ts rename to src/main/claude/structured/journal/claude-usage-limits.ts index 0ce1a106b03..af6b4935dde 100644 --- a/src/main/claude/claude-usage-limits.ts +++ b/src/main/claude/structured/journal/claude-usage-limits.ts @@ -2,18 +2,18 @@ import { agentSessionFailureFact, providerDiagnostic, type ProviderDiagnostic -} from '../../shared/agent-session/failures/agent-session-failure' +} from '../../../../shared/agent-session/failures/agent-session-failure' import { agentSessionFailureWords, type AgentSessionFailureRowWords -} from '../../shared/agent-session/failures/agent-session-failure-words' +} from '../../../../shared/agent-session/failures/agent-session-failure-words' import { usageLimitResetsAt, type AgentSessionUsageLimit, type AgentSessionUsageLimitWindow -} from '../../shared/agent-session/failures/agent-session-usage-limit' -import type { ClaudeOpenTurn } from './claude-open-turn' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' +} from '../../../../shared/agent-session/failures/agent-session-usage-limit' +import type { ClaudeOpenTurn } from '../turns/claude-open-turn' +import { claudeRecord, claudeText } from './claude-structured-item-translation' const CLAUDE_LIMIT_WINDOWS: Record = { five_hour: 'session', diff --git a/src/main/claude/claude-config-dir-pin.test.ts b/src/main/claude/structured/launch/claude-config-dir-pin.test.ts similarity index 100% rename from src/main/claude/claude-config-dir-pin.test.ts rename to src/main/claude/structured/launch/claude-config-dir-pin.test.ts diff --git a/src/main/claude/claude-config-dir-pin.ts b/src/main/claude/structured/launch/claude-config-dir-pin.ts similarity index 100% rename from src/main/claude/claude-config-dir-pin.ts rename to src/main/claude/structured/launch/claude-config-dir-pin.ts diff --git a/src/main/claude/structured/launch/claude-launch-account.ts b/src/main/claude/structured/launch/claude-launch-account.ts new file mode 100644 index 00000000000..65eb3194529 --- /dev/null +++ b/src/main/claude/structured/launch/claude-launch-account.ts @@ -0,0 +1,28 @@ +import type { ClaudeAccountRecipe } from '../../../../shared/agent-session/lifecycle/agent-session-acquired-account' +import type { ClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-router' +import { applyClaudeEnvPatch } from '../../../claude-accounts/runtime-auth/environment' +import { resolveStructuredClaudeAccountHomePath } from '../../../runtime/agent-session/environment/structured-agent-account-home' + +/** The account a launch runs under is the current selection; the receipt records what it used. */ +export async function prepareClaudeLaunchAccount( + router: ClaudeProfileRouter | undefined, + env: Record, + recordHome: string +): Promise { + if (!router) { + return { route: 'system', home: recordHome, configDir: env.CLAUDE_CONFIG_DIR ?? null } + } + const preparation = await router.prepareLaunch() + const home = + preparation.provenance === 'system' + ? await resolveStructuredClaudeAccountHomePath({ + launchEnv: env, + wslDistro: null, + getClaudeConfigDirectory: () => router.systemDefaultHome() + }) + : preparation.configDir + applyClaudeEnvPatch(env, preparation.envPatch) + return preparation.provenance.startsWith('profile:') + ? { route: 'managed', accountId: preparation.provenance.slice('profile:'.length), home } + : { route: 'system', home, configDir: env.CLAUDE_CONFIG_DIR ?? null } +} diff --git a/src/main/claude/claude-launch-destination-home.ts b/src/main/claude/structured/launch/claude-launch-destination-home.ts similarity index 80% rename from src/main/claude/claude-launch-destination-home.ts rename to src/main/claude/structured/launch/claude-launch-destination-home.ts index d03d72b03f9..8e58fc28119 100644 --- a/src/main/claude/claude-launch-destination-home.ts +++ b/src/main/claude/structured/launch/claude-launch-destination-home.ts @@ -1,4 +1,4 @@ -import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' +import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' /** System provenance preserves the explicit agent overlay; managed provenance pins its own home. */ export function claudeLaunchDestinationHome( diff --git a/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts b/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts index 3dc85bc33be..8bb259d3984 100644 --- a/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts +++ b/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts @@ -1,4 +1,4 @@ -import type { ClaudeNamingGeneration } from '../../claude-naming-generation' +import type { ClaudeNamingGeneration } from '../../conversation-naming/claude-naming-generation' import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import { AgentSessionAcquisitionExitUnprovenError } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' import { launchPreparationFailure } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' @@ -11,7 +11,7 @@ import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS, CLAUDE_CLI_FLAG_PROBE_KILL_AFTER_MS, CLAUDE_EFFORT_FLAG -} from '../../claude-cli-flag-support' +} from '../../cli-capabilities/claude-cli-flag-support' import { claudeStructuredSpawnOptions, type ClaudeStructuredSpawnOptions diff --git a/src/main/claude/structured/launch/claude-structured-child-env.test.ts b/src/main/claude/structured/launch/claude-structured-child-env.test.ts index b9c63b68c70..427888c2430 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.test.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' import { claudeChildEnv, resolveClaudeChildEnvSources } from './claude-structured-child-env' -import { resolveStructuredAgentCommand } from '../../../native-chat/structured-agent-command-resolution' +import { resolveStructuredAgentCommand } from '../../../native-chat/agent-launch/structured-agent-command-resolution' afterEach(() => { vi.unstubAllEnvs() diff --git a/src/main/claude/structured/launch/claude-structured-child-env.ts b/src/main/claude/structured/launch/claude-structured-child-env.ts index 46f29548a52..51f0b1cfcbe 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.ts @@ -5,14 +5,14 @@ import { resolveAgainAfterRefreshOnMissingProgram, type StructuredAgentCommand, type StructuredAgentResolutionOperation -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' // What a structured Claude child's environment is built from, shared by its launch and the // `--version` probe that runs the same binary. import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolution' import { applyClaudeEnvPatch } from '../../../claude-accounts/runtime-auth/environment' import { resolveClaudeCommand } from '../../../codex-cli/command' -import { withoutInheritedClaudeConfigDir } from '../../claude-config-dir-pin' +import { withoutInheritedClaudeConfigDir } from './claude-config-dir-pin' import { stripInheritedAgentSessionEnv } from '../../../../shared/agent-launch/startup/parent-agent-session-env' import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' diff --git a/src/main/claude/structured/launch/claude-structured-launch-args.ts b/src/main/claude/structured/launch/claude-structured-launch-args.ts index 69ec4b82e4c..0dba1385778 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-args.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-args.ts @@ -1,4 +1,4 @@ -import { StructuredAgentArgumentsError } from '../../../native-chat/structured-agent-arguments-error' +import { StructuredAgentArgumentsError } from '../../../native-chat/agent-launch/structured-agent-arguments-error' /** Flags supplied by the SDK or owned by Orca's structured transport. */ const OWNED_FLAGS = new Set([ diff --git a/src/main/claude/structured/launch/claude-structured-launch-flags.ts b/src/main/claude/structured/launch/claude-structured-launch-flags.ts index 38df557317b..de39f664019 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-flags.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-flags.ts @@ -1,7 +1,7 @@ import type { NativeChatVisualsLaunch, PrepareNativeChatVisuals -} from '../../../native-chat/native-chat-visuals-delivery' +} from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS, CLAUDE_CLI_FLAG_PROBE_KILL_AFTER_MS, @@ -11,7 +11,7 @@ import { type ClaudeCliFlagFact, type ClaudeCliFlagSupport, type ClaudeCliLaunch -} from '../../claude-cli-flag-support' +} from '../../cli-capabilities/claude-cli-flag-support' const THINKING_DISPLAY_ARGS: Readonly> = { 'thinking-display': 'summarized' } diff --git a/src/main/claude/structured/launch/claude-structured-launch-home.ts b/src/main/claude/structured/launch/claude-structured-launch-home.ts index 88df61b9e6f..1e9b50e99d7 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-home.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-home.ts @@ -2,7 +2,7 @@ import { join } from 'node:path' import type { ClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-router' import { AgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' import { resolveSessionFilePath } from '../../../native-chat/session-file-resolver' -import { prepareClaudeLaunchAccount } from '../../claude-launch-account' +import { prepareClaudeLaunchAccount } from './claude-launch-account' /** Follow the current account selection and pin its environment for this launch. */ export async function resolveClaudeStructuredLaunchHome( diff --git a/src/main/claude/structured/launch/claude-structured-launch-resolution.test.ts b/src/main/claude/structured/launch/claude-structured-launch-resolution.test.ts deleted file mode 100644 index 819f9564cf3..00000000000 --- a/src/main/claude/structured/launch/claude-structured-launch-resolution.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' -import { createClaudeStructuredLaunchResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const SESSION_ID = 'orca-session-1' -const IDENTITY = { sessionId: SESSION_ID } as Parameters< - ReturnType ->[0]['identity'] - -function record(overrides: Partial = {}): AgentSessionRecord { - return agentSessionRecordFixture({ - sessionId: SESSION_ID, - provider: 'claude', - location: { - executionHostId: LOCAL_EXECUTION_HOST_ID, - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/home/work/.claude' }, - providerHandleChain: [], - ...overrides - }) -} - -function identityAt(leafUuid: string | null): typeof IDENTITY { - return { - ...IDENTITY, - providerHandle: claudeProviderHandle('provider-current', leafUuid) - } -} - -function resolverFor( - value: AgentSessionRecord | null, - resolveEnv?: () => Record, - account: 'managed' | 'system' = 'system', - hasTranscript: () => Promise = async () => true, - resolveLaunchArgs?: () => string[], - attachmentDirectory?: string -) { - return createClaudeStructuredLaunchResolver({ - store: { getRecord: () => value, pinLaunchDirectory: vi.fn() }, - resolveWorkspacePath: async (id) => `/repos/${id}`, - resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }), - resolveAuthPolicy: () => ({ account }), - hasTranscript, - resolveLaunchArgs: resolveLaunchArgs ?? (() => value?.launchArgs ?? []), - ...(resolveEnv ? { resolveEnv } : {}), - ...(attachmentDirectory ? { attachmentDirectory } : {}) - }) -} - -const RESUMABLE = record({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only each link's handle, so the link's other fields stay unset. - providerHandleChain: [ - { handle: claudeProviderHandle('provider-current', 'leaf-current') } - ] as AgentSessionRecord['providerHandleChain'] -}) - -describe('claude structured launch resolution', () => { - it('launches when only the bookkeeping leaf moved, and refuses a changed session', async () => { - const resolve = resolverFor(RESUMABLE) - - // A failed turn-end or exit write leaves the identity's leaf behind the record's. - await expect(resolve({ identity: identityAt('leaf-stale') })).resolves.toMatchObject({ - providerSessionId: 'provider-current', - resumeLeafUuid: 'leaf-current' - }) - await expect( - resolve({ - identity: { - ...IDENTITY, - providerHandle: claudeProviderHandle('provider-other', 'leaf-current') - } - }) - ).rejects.toThrow('durable resume identity changed before spawn') - }) -}) diff --git a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts index e58f06c59e1..84ccd0f8eb2 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts @@ -1,6 +1,6 @@ import type { ClaudeAccountRecipe } from '../../../../shared/agent-session/lifecycle/agent-session-acquired-account' -import { prepareClaudeLaunchAccount } from '../../claude-launch-account' -import { assertStructuredAgentResolutionCurrent } from '../../../native-chat/structured-agent-command-resolution' +import { prepareClaudeLaunchAccount } from './claude-launch-account' +import { assertStructuredAgentResolutionCurrent } from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context' import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' @@ -26,9 +26,12 @@ import { type ClaudeEnvDeps } from './claude-structured-child-env' import { claudeStructuredLaunchArgs } from './claude-structured-launch-args' -import type { ClaudeCliFlagCheck, ClaudeCliFlagSupport } from '../../claude-cli-flag-support' +import type { + ClaudeCliFlagCheck, + ClaudeCliFlagSupport +} from '../../cli-capabilities/claude-cli-flag-support' import { resolveClaudeLaunchFlags } from './claude-structured-launch-flags' -import { withNativeChatVisualsEnv } from '../../../native-chat/native-chat-visuals-delivery' +import { withNativeChatVisualsEnv } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { claudeLaunchResumesTranscript } from './claude-structured-launch-home' import type { StructuredAgentLaunchPartResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition' import { claudeSessionIdForOrcaSession } from '../claude-structured-session-id' diff --git a/src/main/claude/structured/launch/claude-structured-launch-visuals.test.ts b/src/main/claude/structured/launch/claude-structured-launch-visuals.test.ts deleted file mode 100644 index b94903365ed..00000000000 --- a/src/main/claude/structured/launch/claude-structured-launch-visuals.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { createClaudeStructuredLaunchResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import type { NativeChatVisualsLaunch } from '../../../native-chat/native-chat-visuals-delivery' -import { - CLAUDE_PLUGIN_DIR_FLAG, - type ClaudeCliFlag, - type ClaudeCliFlagFact -} from '../../claude-cli-flag-support' - -const SESSION_ID = 'orca-session-visuals' -const VISUALS: NativeChatVisualsLaunch = { - folder: '/state/chat-scratch/abc', - skill: { pluginDir: '/app/native-chat-visuals', skillsRoot: '/app/native-chat-visuals/skills' } -} - -const record = agentSessionRecordFixture({ sessionId: SESSION_ID }) -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: SESSION_ID, - workspaceId: 'workspace-1', - hostId: LOCAL_EXECUTION_HOST_ID, - agent: 'claude', - providerHandle: null -} - -type Supports = (flag: ClaudeCliFlag, launch: unknown, budgetMs?: number) => Promise - -const checkOf = - (supports: Supports) => - async (...args: Parameters): Promise => - (await supports(...args)) ? 'supported' : 'unsupported' - -function launch(options: { - prepareVisuals?: (sessionId: string) => Promise - supports?: Supports - launchArgs?: string[] - env?: Record - attachmentDirectory?: string -}) { - return createClaudeStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveWorkspacePath: async (id) => `/repos/${id}`, - resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }), - resolveAuthPolicy: () => ({ account: 'system' }), - resolveLaunchArgs: () => options.launchArgs ?? [], - resolveEnv: () => options.env ?? {}, - hasTranscript: async () => false, - ...(options.attachmentDirectory ? { attachmentDirectory: options.attachmentDirectory } : {}), - ...(options.supports ? { cliFlags: { check: checkOf(options.supports) } } : {}), - ...(options.prepareVisuals ? { prepareVisuals: options.prepareVisuals } : {}) - })({ identity: IDENTITY }) -} - -describe('a Claude chat launch with inline visuals', () => { - it('asks for readable thinking again once the plugin check has learned the version', async () => { - let versionKnown = false - const supports = vi.fn(async (flag: ClaudeCliFlag, _launch: unknown, budgetMs?: number) => { - if (flag === CLAUDE_PLUGIN_DIR_FLAG) { - versionKnown = true - return true - } - // The first thinking check gave up at its short budget; the re-check reads the cached answer. - return versionKnown && budgetMs !== undefined - }) - const resolved = await launch({ prepareVisuals: async () => VISUALS, supports }) - expect(resolved.options.plugins).toHaveLength(1) - expect(resolved.options.extraArgs).toMatchObject({ 'thinking-display': 'summarized' }) - }) -}) diff --git a/src/main/claude/structured/launch/claude-structured-message-options.test.ts b/src/main/claude/structured/launch/claude-structured-message-options.test.ts deleted file mode 100644 index 9900850b95f..00000000000 --- a/src/main/claude/structured/launch/claude-structured-message-options.test.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { StructuredAgentSessionInputNotAdmitted } from '../../../native-chat/agent-session-wire/delivery/structured-agent-session-input-admission' -import { describe, expect, it, vi } from 'vitest' -import { - acquired, - adapterFor, - claudeFrame, - fakeClaude, - identityFor, - recordingJournalSink, - USER_MESSAGE -} from '../claude-structured-session-test-support' -import * as dispatchContent from '../claude-structured-dispatch-content' -import { ClaudeControlRequestError } from '../../claude-agent-sdk-control-requests' -import { claudeStructuredPermissionOptions } from './claude-structured-launch-resolution' - -/** Claude ends a turn; a message sent before this joins the running turn on its choices. */ -const claudeTurnEnds = (connection: Parameters[0]) => - claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) - -const MODELS = [ - { value: 'default', resolvedModel: 'claude-sonnet-5' }, - { - value: 'sonnet', - resolvedModel: 'claude-sonnet-5', - supportsEffort: true, - supportedEffortLevels: ['low', 'high'] - }, - { - value: 'opus', - resolvedModel: 'claude-opus-5', - supportsEffort: true, - supportedEffortLevels: ['low', 'high'] - } -] - -it('checks the latest permission after model preparation without admitting a stale frame', async () => { - const claude = fakeClaude() - const adapter = adapterFor(claude) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'permission-race', - events: recordingJournalSink() - }) - const connection = claude.connections[0]! - claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-sonnet-5' }) - const preparing = Promise.withResolvers() - const resume = Promise.withResolvers() - connection.setModel = async () => { - preparing.resolve() - await resume.promise - } - let changed = false - const admitted = vi.fn() - const sending = adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'permission-race', - body: USER_MESSAGE, - executionOptions: { model: 'custom[1m]' }, - fence: 7, - admitFreshInput: async (enqueue) => - changed ? { kind: 'acquire', reason: 'permission' } : enqueue('ask', false) - }) - const result = sending.then(admitted, (error) => error) - await preparing.promise - changed = true - resume.resolve() - expect(await result).toBeInstanceOf(StructuredAgentSessionInputNotAdmitted) - expect(admitted).not.toHaveBeenCalled() - expect(connection.sent).toHaveLength(0) - await adapter.closeAll() -}) - -describe('Claude accepted message choices', () => { - // --effort arrived in Claude Code 2.1.38 and the live control in 2.1.50; older CLIs reject the flag - // and never answer the control, so either one failed every resume of a chat with a saved effort. - - it('applies a held message A before its prompt, then message B on the existing child', async () => { - const order: string[] = [] - let currentEffort = 'high' - const claude = fakeClaude({ - routes: { - list_models: () => MODELS, - set_model: ({ model } = {}) => order.push(`model:${String(model)}`), - apply_flag_settings: ({ settings } = {}) => { - order.push(`effort:${JSON.stringify(settings)}`) - if ( - typeof settings === 'object' && - settings !== null && - 'effortLevel' in settings && - typeof settings.effortLevel === 'string' - ) { - currentEffort = settings.effortLevel - } - } - } - }) - const adapter = await acquired(claude) - const connection = claude.connections[0]! - connection.getSettings = async () => ({ effective: { effortLevel: currentEffort } }) - const send = connection.send - let release!: () => void - const held = new Promise((resolve) => { - release = resolve - }) - let entered!: () => void - const enteredSend = new Promise((resolve) => { - entered = resolve - }) - let first = true - connection.send = async (message, beforeDispatch) => { - if (first) { - first = false - entered() - await held - } - const result = await send(message, beforeDispatch) - order.push('prompt') - return result - } - - const a = adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'A', - body: USER_MESSAGE, - executionOptions: { model: 'sonnet', effort: 'low' }, - fence: 7 - }) - await enteredSend - await adapter.setOption({ sessionId: 'session-1', key: 'model', value: 'opus', fence: 7 }) - await adapter.setOption({ sessionId: 'session-1', key: 'effort', value: 'high', fence: 7 }) - order.length = 0 - release() - await expect(a).resolves.toMatchObject({ state: 'admitted' }) - expect(order).toEqual(['model:sonnet', 'effort:{"effortLevel":"low"}', 'prompt']) - claudeTurnEnds(connection) - - order.length = 0 - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'B', - body: USER_MESSAGE, - executionOptions: { model: 'opus', effort: 'high' }, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - expect(order).toEqual(['model:opus', 'effort:{"effortLevel":"high"}', 'prompt']) - }) - - // Host admission treats the original abort as never written. - it('surfaces a Stop while it applies a choice as the abort, and a refusal as a refusal', async () => { - let refuse = false - const claude = fakeClaude({ - initModels: MODELS, - routes: { - list_models: () => MODELS, - set_model: () => { - if (refuse) { - throw new ClaudeControlRequestError('set_model', 'unknown model') - } - return new Promise(() => {}) - } - } - }) - const adapter = await acquired(claude) - const stop = new AbortController() - const dispatch = (clientMessageId: string, signal?: AbortSignal) => - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body: USER_MESSAGE, - executionOptions: { model: 'opus' }, - fence: 7, - ...(signal ? { signal } : {}) - }) - const stopped = dispatch('stopped', stop.signal) - await vi.waitFor(() => - expect(claude.connections[0]!.calls.some((call) => call.subtype === 'set_model')).toBe(true) - ) - stop.abort(new Error('stopped while starting')) - await expect(stopped).rejects.toBe(stop.signal.reason) - refuse = true - await expect(dispatch('refused')).resolves.toMatchObject({ - state: 'rejected', - rejection: { kind: 'providerRejected' } - }) - expect(claude.connections[0]!.sent).toHaveLength(0) - }) - - it('keeps a running turn on its choices and applies new ones at the next turn', async () => { - const claude = fakeClaude({ - initModels: MODELS.map((model) => ({ ...model, supportsFastMode: true })), - routes: { list_models: () => MODELS } - }) - const adapter = await acquired(claude) - const connection = claude.connections[0]! - const send = (clientMessageId: string, model: string, body = USER_MESSAGE) => - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId, - body, - executionOptions: { - model, - effort: model === 'sonnet' ? 'high' : 'low', - fastMode: model === 'sonnet' ? 'false' : 'true' - }, - fence: 7 - }) - const models = () => - connection.calls.flatMap((call) => (call.subtype === 'set_model' ? [call.params?.model] : [])) - await expect(send('opens', 'sonnet')).resolves.toMatchObject({ state: 'admitted' }) - expect(models()).toEqual(['sonnet']) - const settings = () => connection.calls.filter((call) => call.subtype === 'apply_flag_settings') - const liveSettings = [...settings()] - // Typed while that turn runs, after the pick changed: it joins the turn as it is. - await expect(send('joins', 'opus')).resolves.toMatchObject({ state: 'admitted' }) - expect(models()).toEqual(['sonnet']) - expect(settings()).toEqual(liveSettings) - claudeTurnEnds(connection) - const mail = { - ...USER_MESSAGE, - from: { - kind: 'agent' as const, - senders: [], - orchestration: { - message: 'mail-notice' as const, - mailbox: 'agent:worker', - dispatchId: null, - messages: [] - } - } - } - await expect(send('mail', 'opus', mail)).resolves.toMatchObject({ state: 'admitted' }) - expect(models()).toEqual(['sonnet']) - expect(settings()).toEqual(liveSettings) - const held = Promise.withResolvers() - const entered = Promise.withResolvers() - const original = dispatchContent.claudeDispatchMessageContent - const content = vi - .spyOn(dispatchContent, 'claudeDispatchMessageContent') - .mockImplementationOnce(async (body) => { - entered.resolve() - await held.promise - return original(body) - }) - const delayed = send('next', 'opus') - try { - await entered.promise - claudeTurnEnds(connection) - held.resolve() - await expect(delayed).resolves.toMatchObject({ state: 'admitted' }) - } finally { - held.resolve() - content.mockRestore() - } - expect(models()).toEqual(['sonnet', 'opus']) - expect(settings()).toContainEqual({ - subtype: 'apply_flag_settings', - params: { settings: { effortLevel: 'low' } } - }) - expect(settings()).toContainEqual({ - subtype: 'apply_flag_settings', - params: { settings: { fastMode: true } } - }) - expect(connection.sent).toHaveLength(4) - claudeTurnEnds(connection) - const settingsAfterTurn = [...settings()] - const originalSend = connection.send - connection.send = async (message, prepare) => { - await prepare?.() - connection.sent.push(message) - } - try { - await expect(send('starts', 'opus')).resolves.toMatchObject({ state: 'admitted' }) - expect(models()).toEqual(['sonnet', 'opus', 'opus']) - expect(settings()).toEqual([ - ...settingsAfterTurn, - { subtype: 'apply_flag_settings', params: { settings: { effortLevel: 'low' } } }, - { subtype: 'apply_flag_settings', params: { settings: { fastMode: true } } } - ]) - const settingsAtStart = [...settings()] - claudeFrame(connection, { - type: 'command_lifecycle', - state: 'started', - command_uuid: connection.sent.at(-1)?.uuid - }) - await expect(send('before-echo', 'sonnet')).resolves.toMatchObject({ state: 'admitted' }) - expect(models()).toEqual(['sonnet', 'opus', 'opus']) - expect(settings()).toEqual(settingsAtStart) - } finally { - connection.send = originalSend - await adapter.closeAll() - } - }) -}) - -it('applies explicit planning at fresh turns, preserves startup permission fallback, and leaves steers alone', async () => { - const claude = fakeClaude({ initPermissionMode: 'default' }) - const adapter = await acquired(claude, { - options: claudeStructuredPermissionOptions('full-access') - }) - const connection = claude.connections[0]! - claudeFrame(connection, { - type: 'system', - subtype: 'init', - model: 'claude-opus-5-5', - permissionMode: 'default' - }) - const setMode = vi.spyOn(connection, 'setPermissionMode').mockResolvedValue(undefined) - const send = (id: string, mode?: 'plan' | 'default') => - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: id, - body: USER_MESSAGE, - fence: 7, - executionOptions: mode ? { interactionMode: mode } : {} - }) - await send('own') - expect(setMode).not.toHaveBeenCalled() - claudeTurnEnds(connection) - await send('plan', 'plan') - expect(setMode).toHaveBeenLastCalledWith('plan', { timeoutMs: undefined }) - await send('steer', 'default') - expect(setMode).toHaveBeenCalledTimes(1) - claudeTurnEnds(connection) - await send('build', 'default') - expect(setMode).toHaveBeenLastCalledWith('default', { timeoutMs: undefined }) - claudeTurnEnds(connection) - claudeFrame(connection, { type: 'system', subtype: 'status', permissionMode: 'plan' }) - await send('build-again', 'default') - expect(setMode).toHaveBeenCalledTimes(3) - await adapter.closeAll() -}) diff --git a/src/main/claude/structured/launch/claude-structured-message-options.ts b/src/main/claude/structured/launch/claude-structured-message-options.ts index abd34fe3d5b..573c77d2fea 100644 --- a/src/main/claude/structured/launch/claude-structured-message-options.ts +++ b/src/main/claude/structured/launch/claude-structured-message-options.ts @@ -1,5 +1,5 @@ -import { claudeBuildPermissionMode } from '../../claude-plan-approval-mode' -import { claudeStartedUnechoedSend } from '../../claude-command-lifecycle' +import { claudeBuildPermissionMode } from '../permissions/claude-plan-approval-mode' +import { claudeStartedUnechoedSend } from '../turns/claude-command-lifecycle' import { claudeExecutionObservations } from '../claude-structured-execution-observations' import { dispatchClaudeTurn } from '../claude-structured-dispatch' import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' @@ -30,10 +30,6 @@ export async function applyClaudeMessageOptions( ): Promise { throwIfSignalAborted(signal) const model = options.model - // Only a turn carrying the newest pick reports on it; earlier captured sends run the replaced model. - if (model === session.modelPickAwaitingTurn) { - delete session.modelPickAwaitingTurn - } if (model && session.appliedInputOptions.get('model') !== model) { await waitForPromiseWithSignal( setClaudeStructuredOption(session, { key: 'model', value: model }, timeoutMs), diff --git a/src/main/claude/structured/launch/claude-structured-model-catalog.ts b/src/main/claude/structured/launch/claude-structured-model-catalog.ts index 5d30474ff86..3fed716589f 100644 --- a/src/main/claude/structured/launch/claude-structured-model-catalog.ts +++ b/src/main/claude/structured/launch/claude-structured-model-catalog.ts @@ -65,8 +65,8 @@ function listedRow(row: Record, id: string, label: string): Lis } // Rows are keyed by the versioned model each entry runs, so a pick saves the -// same id the CLI reports after a turn. An alias that no row is keyed by stays -// selectable after them; the `default` entry only marks the default row. +// same id the CLI reports after a turn. An alias that no row is keyed by follows them, under +// the CLI's own name; the `default` entry only marks the default row. export function listedModels(value: unknown): ListedModel[] { const response = record(value) const rows = (Array.isArray(response?.models) ? response.models : []) @@ -95,7 +95,7 @@ export function listedModels(value: unknown): ListedModel[] { if (value === 'default' || [...primary, ...aliases].some((model) => model.id === value)) { continue } - aliases.push(listedRow(row, value, `${text(row.displayName) ?? value} alias`)) + aliases.push(listedRow(row, value, text(row.displayName) ?? value)) } return [ ...primary.map((model) => diff --git a/src/main/claude/structured/launch/claude-structured-options-context-window.test.ts b/src/main/claude/structured/launch/claude-structured-options-context-window.test.ts deleted file mode 100644 index ad87ada94a1..00000000000 --- a/src/main/claude/structured/launch/claude-structured-options-context-window.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { ClaudeControlRequestError } from '../../claude-agent-sdk-control-requests' -import { selectStructuredAgentContextUsage } from '../../../../shared/agent-session/structured-agent-session-context-usage' -import { assistantFrame, journal, userFrame } from '../../claude-context-usage-test-support' -import { sessionFor } from '../claude-structured-dispatch-test-support' -import { createClaudeJournalTranslator } from '../journal/claude-structured-journal-translation' -import { setClaudeStructuredOption } from './claude-structured-options' -import { adoptClaudeStructuredSpawnOptions } from './claude-structured-spawn-options' -import type { ClaudeSession } from '../claude-structured-session-state' - -function ringSession(catalog: unknown[] = []) { - const session = sessionFor() - const setModel = vi.fn(async () => undefined) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: supplies every connection member a model write and its catalog read call. - session.connection = { - ...session.connection, - setModel, - supportedModels: async () => catalog - } as ClaudeSession['connection'] - const state = journal() - const translator = createClaudeJournalTranslator({ sink: state.sink, coalesceMs: 0 }) - session.translator = translator - const write = (key: string, value: string) => - setClaudeStructuredOption(session, { key, value }, undefined) - const respond = (turnId: string, at: number) => { - translator.handle(userFrame(turnId, at)) - translator.handle(assistantFrame(`${turnId}-reply`, at + 1, 100_000)) - return selectStructuredAgentContextUsage(state.items()) - } - return { session, setModel, write, respond } -} - -describe('the context ring after a session option write', () => { - it('sizes a new session from the model it was launched with', () => { - const s = ringSession() - adoptClaudeStructuredSpawnOptions(s.session, { - sdkOptions: { model: 'opus[1m]' }, - options: new Map([['model', 'opus[1m]']]), - fastModeAtStart: false - }) - expect(s.respond('turn-a', 1_000)).toMatchObject({ windowTokens: 1_000_000, percentage: 10 }) - }) - - it('sizes estimates from a live model write straight away', async () => { - const s = ringSession() - await s.write('model', 'sonnet') - expect(s.respond('turn-a', 1_000)).toBeNull() - await s.write('model', 'sonnet[1m]') - expect(s.respond('turn-b', 2_000)).toMatchObject({ windowTokens: 1_000_000, percentage: 10 }) - }) - - it('implies no window for a model the child refused', async () => { - const refused = ringSession() - refused.setModel.mockRejectedValueOnce(new ClaudeControlRequestError('set_model', 'refused')) - await expect(refused.write('model', 'opus[1m]')).rejects.toThrow() - expect(refused.respond('turn-a', 1_000)).toBeNull() - }) -}) diff --git a/src/main/claude/structured/launch/claude-structured-options.test.ts b/src/main/claude/structured/launch/claude-structured-options.test.ts deleted file mode 100644 index 0caf086fbf8..00000000000 --- a/src/main/claude/structured/launch/claude-structured-options.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { ClaudeJournalBoundDelivery } from '../../claude-journal-bound-delivery' -import { describe, expect, it, vi } from 'vitest' -import { setClaudeStructuredOption } from './claude-structured-options' -import type { ClaudeSession } from '../claude-structured-session-state' -import { ClaudeBackgroundTaskTracker } from '../../claude-background-task-tracker' -import { ClaudeChildWorkDecoder } from '../../claude-child-work-decoder' -import { ClaudeSlashCommandCatalog } from '../../claude-slash-command-catalog' -import { createClaudeInitProof } from '../claude-structured-init-proof' -import { createClaudeStartupOutcome } from '../claude-structured-startup-outcome' -import { claudeProviderHandleLink } from '../claude-structured-owner-identity' - -vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() })) - -function sessionFor(setModel: ClaudeSession['connection']['setModel']): ClaudeSession { - return { - connection: { - setModel, - supportedModels: async (): Promise => [] - } as ClaudeSession['connection'], - providerSessionId: 'provider-session', - leafUuid: null, - turnEndLeafUuid: null, - fence: 1, - acquisitionGeneration: 'generation-1', - prompts: {} as ClaudeSession['prompts'], - dispatchWaiters: [], - retiredDispatchWaiters: [], - replayContentFallbackBlocked: false, - delivery: new ClaudeJournalBoundDelivery(), - backgroundTasks: new ClaudeBackgroundTaskTracker(), - childWork: new ClaudeChildWorkDecoder(), - commands: new ClaudeSlashCommandCatalog(), - dispatchSequence: 0, - optionMutationSequence: 0, - options: new Map(), - reportedOptions: {}, - reportedModelMutation: 0, - confirmedOptions: new Set(), - appliedInputOptions: new Map(), - fastModeAtStart: false, - capabilities: [], - events: undefined, - translator: null, - link: claudeProviderHandleLink({ - sessionId: 'provider-session', - leafUuid: null, - resumed: false, - fence: 1, - observedAt: 1 - }), - initialization: { - proof: createClaudeInitProof(), - account: undefined, - resumesTranscript: false, - claudeConfigDir: '/claude-home', - cwd: '/work', - history: { leafUuid: null, covered: true, contextActivity: 0 }, - onLateRefusal: () => {}, - startup: createClaudeStartupOutcome() - } - } -} - -describe('Claude structured option mutation fencing', () => { - it('does not let a delayed earlier apply overwrite a later option', async () => { - let releaseFirst!: () => void - const firstApply = new Promise((resolve) => { - releaseFirst = resolve - }) - const setModel = vi - .fn() - .mockReturnValueOnce(firstApply) - .mockResolvedValue(undefined) - const session = sessionFor(setModel) - - const first = setClaudeStructuredOption(session, { key: 'model', value: 'old' }, undefined) - await vi.waitFor(() => expect(setModel).toHaveBeenCalledTimes(1)) - const second = setClaudeStructuredOption(session, { key: 'model', value: 'new' }, undefined) - await expect(second).resolves.toEqual({ model: 'new' }) - - releaseFirst() - await expect(first).resolves.toEqual({ model: 'new' }) - expect(session.options).toEqual(new Map([['model', 'new']])) - }) -}) diff --git a/src/main/claude/structured/launch/claude-structured-options.ts b/src/main/claude/structured/launch/claude-structured-options.ts index d360ce78688..ea637485a7f 100644 --- a/src/main/claude/structured/launch/claude-structured-options.ts +++ b/src/main/claude/structured/launch/claude-structured-options.ts @@ -1,4 +1,4 @@ -import { ClaudeControlRequestError } from '../../claude-agent-sdk-control-requests' +import { ClaudeControlRequestError } from '../../sdk-transport/claude-agent-sdk-control-requests' import { AgentSessionOptionRejectedError, ClaudeEffortValidationError @@ -16,7 +16,7 @@ import { beginClaudeOptionMutation } from '../claude-structured-execution-observ import { CLAUDE_APPLY_FLAG_SETTINGS_CONTROL, CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS -} from '../../claude-cli-flag-support' +} from '../../cli-capabilities/claude-cli-flag-support' const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const diff --git a/src/main/claude/structured/launch/claude-structured-provider-fallback.ts b/src/main/claude/structured/launch/claude-structured-provider-fallback.ts index 8595432cc9f..f0fd7c56797 100644 --- a/src/main/claude/structured/launch/claude-structured-provider-fallback.ts +++ b/src/main/claude/structured/launch/claude-structured-provider-fallback.ts @@ -22,22 +22,22 @@ import { claudeText, type ClaudeMessageEnvelope } from '../journal/claude-structured-item-translation' -import { claudeResultOutcome } from '../../claude-result-outcome' +import { claudeResultOutcome } from '../turns/claude-result-outcome' import { isUnmodeledClaudeSystemFrame } from '../../../native-chat/agent-session-wire/providers/provider-frame-disposition' import { isClaudeToolUseContent, isClaudeToolResultContent } from '../../../../shared/claude-tool-content' -import type { ClaudeRowStamp } from '../../claude-provisional-row-corrections' +import type { ClaudeRowStamp } from '../../subagents/claude-provisional-row-corrections' import { CLAUDE_API_RETRY_FRAME_KIND, claudeApiRetryRowBody, createClaudeApiRetryRuns -} from '../../claude-api-retry-row' +} from '../journal/claude-api-retry-row' import { CLAUDE_INFORMATIONAL_FRAME_KIND, claudeInformationalRowBody -} from '../../claude-informational-row' +} from '../journal/claude-informational-row' export function claudeProviderFrameKind(message: Record): string { const type = claudeText(message.type) ?? 'unknown' diff --git a/src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts b/src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts deleted file mode 100644 index 6f0fb6ce0a2..00000000000 --- a/src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentSessionExecutionOptions } from '../../../../shared/agent-session/options/agent-session-execution-options' -import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/agent-session-turn-record' -import { - claudeProviderHandle, - claudeProviderHandleLeafUuid -} from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { - CLAUDE_STRUCTURED_BASE_OPTIONS, - claudeStructuredPermissionOptions -} from './claude-structured-launch-resolution' -import { listedModels } from './claude-structured-model-catalog' -import { ClaudeStructuredSessionAdapter } from '../claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-state' -import { - realClaudeAuthenticated, - realClaudeAvailable, - realClaudeCommand, - realClaudeLaunchHome -} from '../../claude-real-cli-availability-test-support' -import { claudeStartupSettled } from '../claude-structured-startup-settled-test-support' -import { journal } from '../../claude-context-usage-test-support' - -const SESSION_ID = 'real-cli-options' -// CLI effort order is unspecified. -const EFFORT_SCALE = ['low', 'medium', 'high', 'xhigh', 'max'] - -function identity(providerSessionId: string, leafUuid: string | null): AgentSessionJournalIdentity { - return { - sessionId: SESSION_ID, - workspaceId: 'real-cli-options-workspace', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(providerSessionId, leafUuid) - } -} - -async function until(check: () => boolean, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs - while (Date.now() < deadline) { - if (check()) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 200)) - } - return check() -} - -// Inits name a 1M-window model with `[1m]`; context reports and responses drop it. -const baseModelId = (model: string): string => - model - .replace(/\[[^\]]*\]$/u, '') - .trim() - .toLowerCase() - -describe.skipIf(!realClaudeAvailable)('Claude structured real CLI options', () => { - it.skipIf(!realClaudeAuthenticated)( - 'applies a message model and effort, reports context usage, and relaunches into a new permission mode', - async () => { - const providerSessionId = randomUUID() - const { claudeConfigDir, env } = realClaudeLaunchHome() - const cwd = await mkdtemp(join(tmpdir(), 'orca-real-options-')) - const events: ClaudeStructuredSessionEvent[] = [] - const record = journal() - const persisted: { leafUuid: string | null } = { leafUuid: null } - let launches = 0 - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async ({ identity: launchIdentity, permissionMode }) => { - const permission = claudeStructuredPermissionOptions(permissionMode ?? 'ask') - const resumes = launches++ > 0 - return { - pathToClaudeCodeExecutable: realClaudeCommand, - options: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS, - ...permission, - extraArgs: { ...CLAUDE_STRUCTURED_BASE_OPTIONS.extraArgs, ...permission.extraArgs }, - ...(resumes ? { resume: providerSessionId } : { sessionId: providerSessionId }) - }, - cwd, - env, - claudeConfigDir, - providerSessionId, - resumeLeafUuid: - resumes && launchIdentity.providerHandle - ? claudeProviderHandleLeafUuid(launchIdentity.providerHandle) - : null, - resumesTranscript: resumes, - cliFlag: async () => 'supported' as const, - continuesChain: resumes - } - }, - onEvent: (event) => events.push(event), - persistHandle: async (handle) => { - persisted.leafUuid = handle.leafUuid - }, - readProcessStartTime: async () => 1 - }) - const frames = (from: number) => - events.slice(from).flatMap((event) => (event.type === 'message' ? [event.message] : [])) - const inits = (from: number) => - frames(from).filter((message) => message.type === 'system' && message.subtype === 'init') - const results = (from: number) => frames(from).filter((message) => message.type === 'result') - const send = ( - clientMessageId: string, - text: string, - fence: number, - executionOptions?: AgentSessionExecutionOptions - ) => - adapter.dispatch({ - sessionId: SESSION_ID, - clientMessageId, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }, - requestedAt: Date.now(), - fence, - ...(executionOptions ? { executionOptions } : {}) - }) - const contextReport = () => - record - .items() - .flatMap((row) => { - const used = readAgentJournalTurn(row.body)?.contextUsage?.used - return used?.kind === 'report' ? [used] : [] - }) - .at(-1) - - try { - await adapter.acquire({ - identity: identity(providerSessionId, null), - fence: 1, - spawnToken: 'real-cli-options-1', - permissionMode: 'ask', - events: record.sink - }) - await claudeStartupSettled(adapter, SESSION_ID) - - // Missing resolved IDs disable admission, effort validation and model confirmation. - const connection = adapter['sessions'].get(SESSION_ID)?.connection - if (!connection) { - throw new Error('no live Claude connection') - } - const listed = listedModels({ models: await connection.supportedModels() }) - const rows = ['haiku', 'sonnet'].map((alias) => listed.find(({ id }) => id === alias)) - for (const row of rows) { - expect(row?.resolvedModel).toEqual(expect.stringMatching(/\S/u)) - } - const opened = await adapter.readOptions({ sessionId: SESSION_ID, fence: 1 }) - expect(opened.catalogListing?.models.map(({ id }) => id)).toContain('haiku') - - const pick = rows.find((row) => row !== undefined && row.efforts.length > 0) - const level = pick?.efforts - .map(({ value }) => value) - .filter((value) => EFFORT_SCALE.includes(value)) - .sort((left, right) => EFFORT_SCALE.indexOf(left) - EFFORT_SCALE.indexOf(right))[0] - if (!pick?.resolvedModel || !level) { - throw new Error('neither haiku nor sonnet lists an effort level') - } - - // ranOptions may omit an alias pick; message metadata retains the requested model. - const firstTurn = events.length - const outcome = await send( - 'real-cli-options-1', - 'Reply with exactly: OK. Do not use any tools.', - 1, - { model: pick.id, effort: level } - ) - expect(outcome).toMatchObject({ state: 'admitted', ranOptions: { effort: level } }) - expect([undefined, pick.id]).toContain( - 'ranOptions' in outcome ? outcome.ranOptions?.model : undefined - ) - expect(await until(() => results(firstTurn).length > 0, 90_000)).toBe(true) - expect(results(firstTurn)[0]).toMatchObject({ subtype: 'success', is_error: false }) - expect(inits(firstTurn)[0]?.model).toBe(pick.resolvedModel) - expect(frames(0).filter((frame) => 'effortLevel' in frame)).toEqual([]) - await expect( - adapter.readOptions({ sessionId: SESSION_ID, fence: 1 }) - ).resolves.toMatchObject({ - current: { - model: pick.id, - effort: level, - confirmed: expect.arrayContaining(['model', 'effort']) - } - }) - - expect(await until(() => contextReport() !== undefined, 10_000)).toBe(true) - const report = contextReport() - if (!report) { - throw new Error('no context report on any turn row') - } - expect(report.usedTokens).toBeGreaterThan(0) - expect(report.windowTokens).toBeGreaterThanOrEqual(report.usedTokens) - expect(report.model).toMatch(/\S/u) - expect(baseModelId(report.model)).toBe(baseModelId(pick.resolvedModel)) - - // Permission changes relaunch the child with saved options instead of a live control request. - await adapter.closeSession(SESSION_ID) - const resumedTurn = events.length - await adapter.acquire({ - identity: identity(providerSessionId, persisted.leafUuid), - fence: 2, - spawnToken: 'real-cli-options-2', - permissionMode: 'accept-edits', - options: { model: pick.id, effort: level }, - events: record.sink - }) - await claudeStartupSettled(adapter, SESSION_ID) - await expect( - send('real-cli-options-2', 'Reply with exactly: OK.', 2) - ).resolves.toMatchObject({ - state: 'admitted' - }) - expect(await until(() => results(resumedTurn).length > 0, 90_000)).toBe(true) - expect(results(resumedTurn)[0]).toMatchObject({ subtype: 'success', is_error: false }) - expect(inits(resumedTurn)[0]).toMatchObject({ - session_id: providerSessionId, - permissionMode: 'acceptEdits', - model: pick.resolvedModel - }) - await expect( - adapter.readOptions({ sessionId: SESSION_ID, fence: 2 }) - ).resolves.toMatchObject({ current: { effort: level } }) - } finally { - await adapter.closeAll() - await rm(cwd, { recursive: true, force: true }) - } - }, - 180_000 - ) -}) diff --git a/src/main/claude/structured/launch/claude-structured-session-options.ts b/src/main/claude/structured/launch/claude-structured-session-options.ts index b35843bd7c6..720eb25fc73 100644 --- a/src/main/claude/structured/launch/claude-structured-session-options.ts +++ b/src/main/claude/structured/launch/claude-structured-session-options.ts @@ -213,7 +213,6 @@ export function claudeStructuredSessionOptionsFrom( const discovered = listedModels(catalog ? { models: catalog } : null) const listed = discovered.length > 0 ? discovered : seedModels() const current = readClaudeCurrentModel(session) - const reportsPick = !session.modelPickAwaitingTurn const model = current.id === 'default' ? undefined : current.id const models = structuredAgentSessionOptionModels(listed, model, (row) => ({ ...row, @@ -231,7 +230,7 @@ export function claudeStructuredSessionOptionsFrom( session.reportedOptions.fastMode ?? (session.fastModeState === undefined ? undefined : session.fastModeState !== 'off') const confirmed = [ - ...(current.confirmed && reportsPick ? ['model'] : []), + ...(current.confirmed ? ['model'] : []), ...(effort && session.confirmedOptions.has('effort') ? ['effort'] : []), ...(fastMode !== undefined && (session.confirmedOptions.has('fastMode') || !session.options.has('fastMode')) @@ -244,7 +243,6 @@ export function claudeStructuredSessionOptionsFrom( ...(changesLive ? {} : { effortFixed: true as const }), current: { model, - reportedModel: reportsPick ? session.reportedOptions.reportedModel : undefined, reportedPermissionMode: session.reportedOptions.reportedPermissionMode, ...(effort ? { effort } : {}), ...(fastMode !== undefined ? { fastMode } : {}), diff --git a/src/main/claude/structured/launch/claude-structured-spawn-options.ts b/src/main/claude/structured/launch/claude-structured-spawn-options.ts index da37c5bfbff..f80019f5d3e 100644 --- a/src/main/claude/structured/launch/claude-structured-spawn-options.ts +++ b/src/main/claude/structured/launch/claude-structured-spawn-options.ts @@ -8,7 +8,7 @@ import { claudeEffortLevel, restoredClaudeStructuredSessionOptions } from './claude-structured-options' -import type { ClaudeCliFlagFact } from '../../claude-cli-flag-support' +import type { ClaudeCliFlagFact } from '../../cli-capabilities/claude-cli-flag-support' /** Saved choices replace configured flags so the CLI receives each flag once. */ function withoutConfiguredFlag( diff --git a/src/main/claude/claude-can-use-tool-test-support.ts b/src/main/claude/structured/permissions/claude-can-use-tool-test-support.ts similarity index 91% rename from src/main/claude/claude-can-use-tool-test-support.ts rename to src/main/claude/structured/permissions/claude-can-use-tool-test-support.ts index 99f0b18d001..23f912f5630 100644 --- a/src/main/claude/claude-can-use-tool-test-support.ts +++ b/src/main/claude/structured/permissions/claude-can-use-tool-test-support.ts @@ -1,5 +1,5 @@ import type { CanUseTool } from '@anthropic-ai/claude-agent-sdk' -import type { FakeConnection } from './structured/claude-structured-session-test-support' +import type { FakeConnection } from '../claude-structured-session-test-support' type CanUseToolOptions = Parameters[2] diff --git a/src/main/claude/claude-permission-presentation.ts b/src/main/claude/structured/permissions/claude-permission-presentation.ts similarity index 82% rename from src/main/claude/claude-permission-presentation.ts rename to src/main/claude/structured/permissions/claude-permission-presentation.ts index ec41d010791..43a6d415774 100644 --- a/src/main/claude/claude-permission-presentation.ts +++ b/src/main/claude/structured/permissions/claude-permission-presentation.ts @@ -1,9 +1,9 @@ import type { CanUseTool } from '@anthropic-ai/claude-agent-sdk' -import type { AgentJournalApprovalSubject } from '../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalApprovalSubject } from '../../../../shared/agent-session/journal/agent-session-journal-approval-subject' import { stripAnsiEscapeSequences, TERMINAL_CONTROL_CHARACTER_PATTERN -} from '../../shared/ansi-escape-sequences' +} from '../../../../shared/ansi-escape-sequences' import type { ClaudePromptPresentation } from './claude-prompt-registry' type ClaudePermissionOptions = Parameters[2] @@ -29,6 +29,9 @@ export function claudePermissionPresentation( const matchedSource = presentationText(options.matchedAskRule?.source) const matchedToolName = presentationText(options.matchedAskRule?.toolName) const matchedRuleContent = presentationText(options.matchedAskRule?.ruleContent) + // The SDK passes it at runtime without declaring it: one-tap answers must not be offered. + const personOnly = + 'requiresUserInteraction' in options && options.requiresUserInteraction === true return { ...(title ? { title } : {}), ...(displayName ? { displayName } : {}), @@ -43,7 +46,8 @@ export function claudePermissionPresentation( ...(matchedRuleContent ? { ruleContent: matchedRuleContent } : {}) } } - : {}) + : {}), + ...(personOnly ? { personOnly: true } : {}) } } diff --git a/src/main/claude/claude-plan-approval-mode.ts b/src/main/claude/structured/permissions/claude-plan-approval-mode.ts similarity index 97% rename from src/main/claude/claude-plan-approval-mode.ts rename to src/main/claude/structured/permissions/claude-plan-approval-mode.ts index 19270359907..4cdf7113e22 100644 --- a/src/main/claude/claude-plan-approval-mode.ts +++ b/src/main/claude/structured/permissions/claude-plan-approval-mode.ts @@ -1,6 +1,6 @@ import type { PermissionMode, PermissionResult } from '@anthropic-ai/claude-agent-sdk' import type { ClaudePendingPrompt } from './claude-prompt-registry' -import type { ClaudeSession } from './structured/claude-structured-session-state' +import type { ClaudeSession } from '../claude-structured-session-state' /** This process's requested mode, else its first init's; anything else asks for each edit. */ export function claudePlanApprovalMode( diff --git a/src/main/claude/claude-prompt-registry.ts b/src/main/claude/structured/permissions/claude-prompt-registry.ts similarity index 97% rename from src/main/claude/claude-prompt-registry.ts rename to src/main/claude/structured/permissions/claude-prompt-registry.ts index b87542e530a..ab121767958 100644 --- a/src/main/claude/claude-prompt-registry.ts +++ b/src/main/claude/structured/permissions/claude-prompt-registry.ts @@ -2,7 +2,7 @@ import type { PermissionResult, PermissionUpdate } from '@anthropic-ai/claude-ag import type { AgentJournalApprovalMatchedAskRule, AgentJournalApprovalSubject -} from '../../shared/agent-session/journal/agent-session-journal-types' +} from '../../../../shared/agent-session/journal/agent-session-journal-approval-subject' /** Settles the SDK's `canUseTool` promise; `null` writes no provider response. */ export type ClaudePromptSettle = (response: PermissionResult | null) => void @@ -15,6 +15,7 @@ export type ClaudePromptPresentation = { blockedPath?: string matchedAskRule?: AgentJournalApprovalMatchedAskRule subject?: AgentJournalApprovalSubject + personOnly?: true } export type ClaudePendingPrompt = ClaudePromptPresentation & { @@ -96,6 +97,7 @@ export class ClaudePromptRegistry { ...(registration.blockedPath ? { blockedPath: registration.blockedPath } : {}), ...(registration.matchedAskRule ? { matchedAskRule: registration.matchedAskRule } : {}), ...(registration.subject ? { subject: registration.subject } : {}), + ...(registration.personOnly ? { personOnly: true } : {}), questionIds: questions.map(questionId), settle: registration.settle, ...(agentId ? { agentId } : {}) diff --git a/src/main/claude/claude-command-lifecycle-frames.test.ts b/src/main/claude/structured/turns/claude-command-lifecycle-frames.test.ts similarity index 85% rename from src/main/claude/claude-command-lifecycle-frames.test.ts rename to src/main/claude/structured/turns/claude-command-lifecycle-frames.test.ts index bdd6b24c593..4a5761ed64a 100644 --- a/src/main/claude/claude-command-lifecycle-frames.test.ts +++ b/src/main/claude/structured/turns/claude-command-lifecycle-frames.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it, vi } from 'vitest' -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createClaudeJournalTranslator } from '../journal/claude-structured-journal-translation' function sinkState() { const items: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] diff --git a/src/main/claude/structured/turns/claude-command-lifecycle.test.ts b/src/main/claude/structured/turns/claude-command-lifecycle.test.ts new file mode 100644 index 00000000000..71ed654e0b9 --- /dev/null +++ b/src/main/claude/structured/turns/claude-command-lifecycle.test.ts @@ -0,0 +1,259 @@ +// Recorded CLI 2.1.280 lifecycle frames replay regardless of control-request success or loss. + +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/agent-session-turn-record' + +import { ClaudeStructuredSessionAdapter } from '../claude-structured-session-adapter' +import type { ClaudeLateDispatchOutcome } from '../claude-structured-session-state' +import { + fakeClaude, + identityFor, + PROVIDER_SESSION_ID, + type FakeConnection +} from '../claude-structured-session-test-support' +import { claudeStartupSettled } from '../claude-structured-startup-settled-test-support' + +type CapturedEvent = + | { kind: 'meta'; providerSessionId: string } + | { kind: 'frame'; frame: Record } + | { kind: 'dispatch'; clientMessageId: string; sentUuid: string; text: string } + | { kind: 'control'; request: Record } + | { kind: 'control-answer'; response: Record } + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function decodeCapturedEvent(value: unknown): CapturedEvent { + if (!isRecord(value)) { + throw new Error('capture line is not a recorded event') + } + if (value.kind === 'meta' && typeof value.providerSessionId === 'string') { + return { kind: 'meta', providerSessionId: value.providerSessionId } + } + if (value.kind === 'frame' && isRecord(value.frame)) { + return { kind: 'frame', frame: value.frame } + } + if ( + value.kind === 'dispatch' && + typeof value.clientMessageId === 'string' && + typeof value.sentUuid === 'string' && + typeof value.text === 'string' + ) { + return { + kind: 'dispatch', + clientMessageId: value.clientMessageId, + sentUuid: value.sentUuid, + text: value.text + } + } + if (value.kind === 'control' && isRecord(value.request)) { + return { kind: 'control', request: value.request } + } + if (value.kind === 'control-answer' && isRecord(value.response)) { + return { kind: 'control-answer', response: value.response } + } + throw new Error(`capture line has unknown kind: ${String(value.kind)}`) +} + +function loadCapture(name: string): CapturedEvent[] { + const path = join(__dirname, '../../__fixtures__', `claude-lifecycle-capture-${name}.jsonl`) + return readFileSync(path, 'utf8') + .trim() + .split('\n') + .map((line) => decodeCapturedEvent(JSON.parse(line))) +} + +type Settlement = { sessionId: string } & ClaudeLateDispatchOutcome + +type ControlPoint = { + request: Record + /** Captured answer with UUIDs mapped to this replay. */ + answer: Record + deliverInFlight: () => void + adapter: ClaudeStructuredSessionAdapter + connection: FakeConnection + routes: ReturnType['routes'] + liveUuid: (clientMessageId: string) => string +} + +async function replayCapture( + name: string, + options: { + /** Defaults to replaying in-flight frames without a host control action. */ + atControl?: (point: ControlPoint) => Promise + /** Remove capabilities to simulate older CLIs. */ + withoutCapabilities?: string[] + omitFrame?: (frame: Record) => boolean + /** Added frames use captured UUIDs. */ + afterFrame?: (frame: Record) => Record[] + rewriteFrame?: (frame: Record) => Record + /** Capture tails answer the CLI's original control request. */ + stopAfterControl?: boolean + } = {} +) { + const capture = loadCapture(name) + const settlements: Settlement[] = [] + const turnStates = new Map() + const claude = fakeClaude({ initProof: 'none', replayUuid: null }) + const adapter = new ClaudeStructuredSessionAdapter({ + resolveLaunch: async () => ({ + pathToClaudeCodeExecutable: 'claude', + options: {}, + cwd: '/work/repo', + claudeConfigDir: '/accounts/claude', + providerSessionId: PROVIDER_SESSION_ID, + resumeLeafUuid: null, + resumesTranscript: false, + cliFlag: async () => 'supported' as const, + continuesChain: false + }), + openConnection: claude.openConnection, + readProcessStartTime: async () => 1, + now: () => 1_700_000_200_000, + persistHandle: async () => {}, + onDispatchSettledLate: (settlement) => settlements.push(settlement) + }) + await adapter.acquire({ + identity: identityFor(), + fence: 7, + spawnToken: 'spawn-9', + events: { + appendItem: (_identity, body: AgentJournalItemBody) => { + const turn = readAgentJournalTurn(body) + if (turn) { + turnStates.set(turn.turnId, turn.state) + } + }, + appendTombstone: () => {}, + publish: () => {} + } + }) + const connection = claude.connections[0]! + + const uuidMap = new Map() + const capturedSessionId = capture.flatMap((event) => + event.kind === 'meta' ? [event.providerSessionId] : [] + )[0]! + const mapUuids = (value: Record): Record => { + let text = JSON.stringify(value).replaceAll(capturedSessionId, PROVIDER_SESSION_ID) + for (const [captured, live] of uuidMap) { + text = text.replaceAll(captured, live) + } + const mapped: unknown = JSON.parse(text) + if (!isRecord(mapped)) { + throw new Error('mapped frame is not a record') + } + return mapped + } + const deliver = (frame: Record): void => { + if (options.omitFrame?.(frame)) { + return + } + const mapped = mapUuids(options.rewriteFrame?.(frame) ?? frame) + if (Array.isArray(mapped.capabilities) && options.withoutCapabilities) { + mapped.capabilities = mapped.capabilities.filter( + (capability) => !options.withoutCapabilities!.includes(String(capability)) + ) + } + connection.handlers.onMessage?.(mapped) + for (const extra of options.afterFrame?.(frame) ?? []) { + connection.handlers.onMessage?.(mapUuids(extra)) + } + } + const liveUuid = (clientMessageId: string): string => { + const dispatch = capture.find( + (event) => event.kind === 'dispatch' && event.clientMessageId === clientMessageId + ) + return dispatch?.kind === 'dispatch' ? (uuidMap.get(dispatch.sentUuid) ?? '') : '' + } + + let proofDelivered = false + for (let index = 0; index < capture.length; index++) { + const event = capture[index]! + if (event.kind === 'frame') { + deliver(event.frame) + proofDelivered = true + } else if (event.kind === 'dispatch') { + if (proofDelivered) { + await claudeStartupSettled(adapter, 'session-1') + } + await expect( + adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: event.clientMessageId, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: event.text }] }, + fence: 7 + }) + ).resolves.toMatchObject({ state: 'admitted' }) + uuidMap.set(event.sentUuid, String(connection.sent.at(-1)!.uuid)) + } else if (event.kind === 'control') { + const answerAt = capture.findIndex( + (candidate, at) => at > index && candidate.kind === 'control-answer' + ) + if (answerAt === -1) { + throw new Error('capture recorded no answer for its control request') + } + const inFlight = capture.slice(index + 1, answerAt) + const answer = capture[answerAt] + let delivered = false + const deliverInFlight = (): void => { + if (!delivered) { + delivered = true + for (const frameEvent of inFlight) { + if (frameEvent.kind === 'frame') { + deliver(frameEvent.frame) + } + } + } + } + const atControl = options.atControl ?? (async (point) => point.deliverInFlight()) + await atControl({ + request: mapUuids(event.request), + answer: answer?.kind === 'control-answer' ? mapUuids(answer.response) : {}, + deliverInFlight, + adapter, + connection, + routes: claude.routes, + liveUuid + }) + deliverInFlight() + if (options.stopAfterControl) { + break + } + index = answerAt + } + } + const settlementsFor = (clientMessageId: string) => + settlements + .filter((settlement) => settlement.clientMessageId === clientMessageId) + .map(({ sessionId: _sessionId, clientMessageId: _id, ...outcome }) => outcome) + return { settlementsFor, turnStates, liveUuid, connection, adapter } +} + +function isTurnOutput(frame: Record): boolean { + return frame.type === 'user' || frame.type === 'assistant' || frame.type === 'result' +} + +function isLifecycleFrame(frame: Record, state?: string): boolean { + return frame.type === 'command_lifecycle' && (state === undefined || frame.state === state) +} + +describe('a send the CLI holds', () => { + // CLI 2.1.280 can report idle before rereading its queue. + + it('holds the child for a send the CLI has only queued, and does not release it at idle', async () => { + const replay = await replayCapture('auth-failed', { + omitFrame: (frame) => + isTurnOutput(frame) || + isLifecycleFrame(frame, 'started') || + isLifecycleFrame(frame, 'cancelled') + }) + + expect(replay.adapter.holdsDispatch('session-1')).toBe(true) + expect(replay.settlementsFor('client-A')).toEqual([]) + }) +}) diff --git a/src/main/claude/claude-command-lifecycle.ts b/src/main/claude/structured/turns/claude-command-lifecycle.ts similarity index 90% rename from src/main/claude/claude-command-lifecycle.ts rename to src/main/claude/structured/turns/claude-command-lifecycle.ts index 456b458e876..e08fa2c1b6d 100644 --- a/src/main/claude/claude-command-lifecycle.ts +++ b/src/main/claude/structured/turns/claude-command-lifecycle.ts @@ -3,18 +3,18 @@ import { agentSessionFailureFact, type SubmissionRejectionKind -} from '../../shared/agent-session/failures/agent-session-failure' +} from '../../../../shared/agent-session/failures/agent-session-failure' import { DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED, DISPATCH_DOUBT_PROVIDER_IDLE -} from '../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons' +} from '../../../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons' import { rejectClaudeDispatchWaiters, releaseClaudeDispatchWaitersInDoubt -} from './structured/claude-structured-dispatch' -import { readClaudeFrameString } from './structured/claude-structured-init-proof' +} from '../claude-structured-dispatch' +import { readClaudeFrameString } from '../claude-structured-init-proof' import type { ClaudeLateDispatchSettlement } from './claude-replay-turn-resolution' -import type { ClaudeSession, ClaudeStartedSend } from './structured/claude-structured-session-state' +import type { ClaudeSession, ClaudeStartedSend } from '../claude-structured-session-state' const UNSTARTED_VERDICT = { cancelled: 'cancelled', diff --git a/src/main/claude/structured/turns/claude-command-turn.test.ts b/src/main/claude/structured/turns/claude-command-turn.test.ts new file mode 100644 index 00000000000..6772166f9e9 --- /dev/null +++ b/src/main/claude/structured/turns/claude-command-turn.test.ts @@ -0,0 +1,138 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalTurnScope } from '../../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/agent-session-turn-record' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { StructuredAgentSessionRevisionJournal } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' +import { + CAPTURED_COMPACT_SESSION_ID, + type CapturedCompactEvent +} from '../../fixtures/claude-captured-compact-frames.test-fixture' +import { createClaudeJournalTranslator } from '../journal/claude-structured-journal-translation' + +const COMMAND_IDENTITY: AgentJournalItemIdentity = { + provider: 'orca', + clientMessageId: 'command-turn:cmd-1' +} +const COMMAND_KEY = agentJournalItemKey(COMMAND_IDENTITY) +const NOW = 1_800_000_000_000 + +const RUNNING = { + kind: 'turn' as const, + turnId: 'compact:cmd-1', + state: 'running' as const, + userItemId: 'orca:submission:cmd-1', + requestedAt: 900, + startedAt: 1_000 +} + +// Usage limits expire by the system clock; pin it so the quota reset stays an hour ahead. +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(NOW) +}) +afterEach(() => { + vi.useRealTimers() +}) + +type Row = { key: string; body: AgentJournalItemBody; turnScope?: AgentJournalTurnScope } + +function harness() { + const rows = new Map([[COMMAND_KEY, { key: COMMAND_KEY, body: RUNNING }]]) + const writes: Row[] = [] + const write = ( + identity: AgentJournalItemIdentity, + body: AgentJournalItemBody, + turnScope?: AgentJournalTurnScope + ) => { + const row = { key: agentJournalItemKey(identity), body, ...(turnScope ? { turnScope } : {}) } + rows.set(row.key, row) + writes.push(row) + } + const journal: StructuredAgentSessionRevisionJournal = { + item: () => null, + epoch: 'epoch-1', + itemBody: (itemId) => rows.get(itemId)?.body ?? null, + visitItems: (visit) => { + let sequence = 0 + for (const row of rows.values()) { + visit(row.key, sequence++, row.body) + } + } + } + const revise: NonNullable = ( + _bytes, + resolve, + options + ) => { + const resolved = resolve(journal) + if (resolved) { + write(resolved.identity, resolved.body, options.turnScope) + } + return { accepted: true } + } + const sink: StructuredAgentSessionEventSink = { + appendItem: (identity, body, options) => write(identity, body, options.turnScope), + appendTombstone: vi.fn(), + publish: vi.fn(), + tryReviseResolvedItem: revise, + tryReviseResolvedItemAndPublish: revise + } + const translator = createClaudeJournalTranslator({ sink, fallbackIdPrefix: 'test' }) + const frame = (message: Record, extra: Record = {}) => + translator.handle({ + type: 'message', + sessionId: 'orca-session', + message: { session_id: CAPTURED_COMPACT_SESSION_ID, ...message }, + observedAt: 5_000, + ...extra + }) + const begin = (sentUuid: string) => + translator.beginCommand({ + clientMessageId: 'cmd-1', + turnId: RUNNING.turnId, + identity: COMMAND_IDENTITY, + resultIdentity: { provider: 'orca', clientMessageId: 'command-result:cmd-1' }, + running: RUNNING, + providerSessionId: CAPTURED_COMPACT_SESSION_ID, + sentUuid + }) + const replay = (events: readonly CapturedCompactEvent[]) => { + for (const event of events) { + if ('sent' in event) { + if (event.sent.text === '/compact') { + begin(event.sent.uuid) + } + } else if ('interrupt' in event) { + translator.commandInterruptRequested(RUNNING.turnId) + } else { + frame(event.frame) + } + } + } + const commandTurn = () => readAgentJournalTurn(rows.get(COMMAND_KEY)?.body) + const drawn = () => + [...rows.values()].filter((row) => row.key !== COMMAND_KEY && row.body.kind !== 'turn') + return { translator, rows, writes, frame, begin, replay, commandTurn, drawn } +} + +describe('a captured /compact as the open Claude turn', () => { + it('leaves the command running at a result that names another input', () => { + const { begin, frame, commandTurn, translator } = harness() + begin('compact-input') + frame({ type: 'system', subtype: 'compact_boundary', uuid: 'boundary' }) + frame({ type: 'result', subtype: 'success', is_error: false, user_message_uuid: 'earlier' }) + expect(commandTurn()?.state).toBe('running') + expect(translator.commandTurnId).toBe(RUNNING.turnId) + + frame({ + type: 'result', + subtype: 'success', + is_error: false, + user_message_uuid: 'compact-input' + }) + expect(commandTurn()).toMatchObject({ state: 'completed', outcome: 'success' }) + }) +}) diff --git a/src/main/claude/claude-command-turn.ts b/src/main/claude/structured/turns/claude-command-turn.ts similarity index 80% rename from src/main/claude/claude-command-turn.ts rename to src/main/claude/structured/turns/claude-command-turn.ts index 16d722eda14..67791d6d8c2 100644 --- a/src/main/claude/claude-command-turn.ts +++ b/src/main/claude/structured/turns/claude-command-turn.ts @@ -1,23 +1,23 @@ // Command output stays off the reply timeline; only the command's result ends its turn. -import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' import { providerDiagnostic, type ProviderDiagnostic -} from '../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' -import { TUI_AGENT_DISPLAY_NAMES } from '../../shared/agent-launch/catalog/tui-agent-display-names' -import type { StructuredAgentSessionCommandRun } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { structuredCompactionOutcome } from '../native-chat/agent-session-wire/operations/structured-conversation-command-outcome' -import { claudeText } from './structured/journal/claude-structured-item-translation' -import { claudeResultFailure } from './structured/launch/claude-structured-provider-fallback' +} from '../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import { TUI_AGENT_DISPLAY_NAMES } from '../../../../shared/agent-launch/catalog/tui-agent-display-names' +import type { StructuredAgentSessionCommandRun } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { structuredCompactionOutcome } from '../../../native-chat/agent-session-wire/operations/structured-conversation-command-outcome' +import { claudeText } from '../journal/claude-structured-item-translation' +import { claudeResultFailure } from '../launch/claude-structured-provider-fallback' import type { ClaudeCurrentTurn, ClaudeTurnEnd } from './claude-turn-lifecycle-item' import { isRootClaudeFrame } from './claude-turn-opening' import type { ClaudeOpenTurn } from './claude-open-turn' -import type { ClaudeUsageLimits } from './claude-usage-limits' -import type { ClaudeAssistantFailures } from './claude-assistant-failures' +import type { ClaudeUsageLimits } from '../journal/claude-usage-limits' +import type { ClaudeAssistantFailures } from '../journal/claude-assistant-failures' export type ClaudeCommandTurn = { identity: AgentJournalItemIdentity diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/structured/turns/claude-open-turn.ts similarity index 86% rename from src/main/claude/claude-open-turn.ts rename to src/main/claude/structured/turns/claude-open-turn.ts index d4eb8a5d0e9..a213b8bd60e 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/structured/turns/claude-open-turn.ts @@ -1,21 +1,21 @@ -import type { AgentSessionContextUsage } from '../../shared/agent-session/agent-session-context-usage' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { AgentSessionContextUsage } from '../../../../shared/agent-session/agent-session-context-usage' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalTurnScope } from '../../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { claudeCurrentTurnIdentity, claudeTurnLifecycleItem, type ClaudeCurrentTurn, type ClaudeTurnEnd } from './claude-turn-lifecycle-item' -import { writeAgentJournalTurnRow } from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' +import { writeAgentJournalTurnRow } from '../../../native-chat/agent-session-timeline/agent-journal-turn-row-revision' import type { ClaudeCommandTurn } from './claude-command-turn' import { createClaudeTurnOpener, type ClaudeTurnSource } from './claude-turn-opening' -import { refineClaudeQuotaTurnEnd } from './claude-terminal-failure' -import type { ClaudeUsageLimitEvidence } from './claude-usage-limits' -import type { ClaudeStartedSend } from './structured/claude-structured-session-state' +import { refineClaudeQuotaTurnEnd } from '../journal/claude-terminal-failure' +import type { ClaudeUsageLimitEvidence } from '../journal/claude-usage-limits' +import type { ClaudeStartedSend } from '../claude-structured-session-state' export type ClaudeOpenTurnDeps = { sink: StructuredAgentSessionEventSink diff --git a/src/main/claude/claude-replay-turn-resolution.ts b/src/main/claude/structured/turns/claude-replay-turn-resolution.ts similarity index 95% rename from src/main/claude/claude-replay-turn-resolution.ts rename to src/main/claude/structured/turns/claude-replay-turn-resolution.ts index 50cb95df847..2700ec9b68a 100644 --- a/src/main/claude/claude-replay-turn-resolution.ts +++ b/src/main/claude/structured/turns/claude-replay-turn-resolution.ts @@ -3,18 +3,18 @@ import { releaseClaudeDispatchesUnansweredAtIdle } from './claude-command-lifecycle' import { claudeSessionStateEndsTurn } from './claude-session-state-turn-over' -import { forgetRetiredWaiter } from './structured/claude-structured-dispatch-waiters' +import { forgetRetiredWaiter } from '../claude-structured-dispatch-waiters' import { claudeHasReplayContent, readClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' +} from '../journal/claude-structured-item-translation' import type { ClaudeDispatchWaiter, ClaudeLateDispatchOutcome, ClaudeSession -} from './structured/claude-structured-session-state' -import { readClaudeFrameString } from './structured/claude-structured-init-proof' -import { claudeDispatchContentKey } from './structured/claude-structured-dispatch-content' +} from '../claude-structured-session-state' +import { readClaudeFrameString } from '../claude-structured-init-proof' +import { claudeDispatchContentKey } from '../claude-structured-dispatch-content' /** Settle provider-proven delivery independently of replay-row acceptance reconciliation. */ export type ClaudeLateDispatchSettlement = (input: ClaudeLateDispatchOutcome) => void diff --git a/src/main/claude/structured/turns/claude-request-end-wait.test.ts b/src/main/claude/structured/turns/claude-request-end-wait.test.ts new file mode 100644 index 00000000000..f88c771841d --- /dev/null +++ b/src/main/claude/structured/turns/claude-request-end-wait.test.ts @@ -0,0 +1,52 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + awaitClaudeRequestEnd, + CLAUDE_STOP_GRACE_MS, + settleClaudeTurnEndWaiters +} from './claude-request-end-wait' +import type { ClaudeSession } from '../claude-structured-session-state' + +type InFlight = { translator: { currentTurnId: string | null }; dispatchWaiters: unknown[] } + +function claudeWith( + currentTurnId: string | null = 'turn-1', + unanswered = 0 +): { claude: ClaudeSession; state: InFlight } { + const state: InFlight = { + translator: { currentTurnId }, + dispatchWaiters: Array.from({ length: unanswered }, () => ({})) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the wait reads only `translator.currentTurnId` and `dispatchWaiters`, and keys its waiters by the session's identity. + return { claude: state as unknown as ClaudeSession, state } +} + +async function settledWithin(promise: Promise, ms: number): Promise { + let settled = false + void promise.then(() => { + settled = true + }) + await vi.advanceTimersByTimeAsync(ms) + return settled +} + +describe("a Stop's wait for Claude to wind down what it has in flight", () => { + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('waits on a send Claude has not echoed, through its turn, to that turn’s end', async () => { + const { claude, state } = claudeWith(null, 1) + const waiting = awaitClaudeRequestEnd(claude, CLAUDE_STOP_GRACE_MS) + state.dispatchWaiters.length = 0 + state.translator.currentTurnId = 'turn-1' + settleClaudeTurnEndWaiters(claude) + expect(await settledWithin(waiting, 0)).toBe(false) + + state.translator.currentTurnId = null + settleClaudeTurnEndWaiters(claude) + expect(await settledWithin(waiting, 0)).toBe(true) + }) +}) diff --git a/src/main/claude/claude-request-end-wait.ts b/src/main/claude/structured/turns/claude-request-end-wait.ts similarity index 96% rename from src/main/claude/claude-request-end-wait.ts rename to src/main/claude/structured/turns/claude-request-end-wait.ts index d1ca6b61612..b9f7f952294 100644 --- a/src/main/claude/claude-request-end-wait.ts +++ b/src/main/claude/structured/turns/claude-request-end-wait.ts @@ -1,6 +1,6 @@ // Stop grace follows the provider request, including sends whose echo has not opened a turn yet. -import type { ClaudeSession } from './structured/claude-structured-session-state' +import type { ClaudeSession } from '../claude-structured-session-state' /** Interrupt acknowledgement and request wind-down share this budget. */ export const CLAUDE_STOP_GRACE_MS = 3_000 diff --git a/src/main/claude/claude-result-outcome.ts b/src/main/claude/structured/turns/claude-result-outcome.ts similarity index 78% rename from src/main/claude/claude-result-outcome.ts rename to src/main/claude/structured/turns/claude-result-outcome.ts index c9a07206414..3184382d1de 100644 --- a/src/main/claude/claude-result-outcome.ts +++ b/src/main/claude/structured/turns/claude-result-outcome.ts @@ -1,5 +1,5 @@ -import type { AgentJournalTurnOutcome } from '../../shared/agent-status/lifecycle/agent-turn-outcome' -import { claudeText } from './structured/journal/claude-structured-item-translation' +import type { AgentJournalTurnOutcome } from '../../../../shared/agent-status/lifecycle/agent-turn-outcome' +import { claudeText } from '../journal/claude-structured-item-translation' /** User stops are error results too; abort reasons distinguish cancellation from failure. */ const CLAUDE_ABORTED_TERMINAL_REASONS = new Set(['aborted_streaming', 'aborted_tools']) diff --git a/src/main/claude/claude-session-state-turn-over.ts b/src/main/claude/structured/turns/claude-session-state-turn-over.ts similarity index 83% rename from src/main/claude/claude-session-state-turn-over.ts rename to src/main/claude/structured/turns/claude-session-state-turn-over.ts index ad42c0d3ae4..7f16398cc10 100644 --- a/src/main/claude/claude-session-state-turn-over.ts +++ b/src/main/claude/structured/turns/claude-session-state-turn-over.ts @@ -1,7 +1,7 @@ // Idle ends turns even when results are missing; requires_action stays open for pending user input. -import { claudeText } from './structured/journal/claude-structured-item-translation' -import type { ClaudeJournalTranslator } from './claude-journal-translator-contract' +import { claudeText } from '../journal/claude-structured-item-translation' +import type { ClaudeJournalTranslator } from '../journal/claude-journal-translator-contract' function isClaudeSessionStateFrame(message: Record): boolean { return message.type === 'system' && message.subtype === 'session_state_changed' diff --git a/src/main/claude/structured/turns/claude-turn-activity.ts b/src/main/claude/structured/turns/claude-turn-activity.ts new file mode 100644 index 00000000000..45eecc1f561 --- /dev/null +++ b/src/main/claude/structured/turns/claude-turn-activity.ts @@ -0,0 +1,28 @@ +import { claudeProviderFrameActivity } from '../../../native-chat/agent-session-wire/providers/provider-frame-activity' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { claudeProviderFrameKind } from '../launch/claude-structured-provider-fallback' +import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-event' +import type { ClaudeOpenTurn } from './claude-open-turn' +import { claudeStreamTurnSource, isRootClaudeFrame } from './claude-turn-opening' + +export function publishClaudeTurnActivity( + turn: ClaudeOpenTurn, + sink: StructuredAgentSessionEventSink, + event: Extract +): void { + const text = + event.type === 'message' + ? claudeProviderFrameActivity(claudeProviderFrameKind(event.message), event.message) + : claudeProviderFrameActivity(event.kind, event.payload) + if (event.type === 'message' && event.startedSend && isRootClaudeFrame(event.message) && text) { + turn.ensureOpen( + event.message, + claudeStreamTurnSource(event.message), + event.observedAt ?? Date.now() + ) + } + const turnId = turn.id + if (turnId !== null && text !== undefined) { + sink.setActivity?.(text ? { turnId, text } : null) + } +} diff --git a/src/main/claude/claude-turn-lifecycle-item.ts b/src/main/claude/structured/turns/claude-turn-lifecycle-item.ts similarity index 82% rename from src/main/claude/claude-turn-lifecycle-item.ts rename to src/main/claude/structured/turns/claude-turn-lifecycle-item.ts index f0a57821309..63e24de44f8 100644 --- a/src/main/claude/claude-turn-lifecycle-item.ts +++ b/src/main/claude/structured/turns/claude-turn-lifecycle-item.ts @@ -1,9 +1,9 @@ -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalTurnItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnOutcome } from '../../shared/agent-status/lifecycle/agent-turn-outcome' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { agentJournalTurnBody } from '../../shared/agent-session/lifecycle/agent-session-turn-record' -import type { StructuredAgentSessionAppendOptions } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalTurnItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalTurnOutcome } from '../../../../shared/agent-status/lifecycle/agent-turn-outcome' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { agentJournalTurnBody } from '../../../../shared/agent-session/lifecycle/agent-session-turn-record' +import type { StructuredAgentSessionAppendOptions } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { claudeResultOutcome } from './claude-result-outcome' import type { ClaudeCommandTurn } from './claude-command-turn' diff --git a/src/main/claude/claude-turn-opening.ts b/src/main/claude/structured/turns/claude-turn-opening.ts similarity index 92% rename from src/main/claude/claude-turn-opening.ts rename to src/main/claude/structured/turns/claude-turn-opening.ts index 81a43519105..c8c32eba37b 100644 --- a/src/main/claude/claude-turn-opening.ts +++ b/src/main/claude/structured/turns/claude-turn-opening.ts @@ -3,9 +3,9 @@ import { claudeRecord, claudeText, type ClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' -import { agentJournalSubmissionKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import type { ClaudeStartedSend } from './structured/claude-structured-session-state' +} from '../journal/claude-structured-item-translation' +import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { ClaudeStartedSend } from '../claude-structured-session-state' import { claudeProviderResumedTurnTimingAnchor, type ClaudeCurrentTurn diff --git a/src/main/claude/claude-child-tool-queries.ts b/src/main/claude/subagents/claude-child-tool-queries.ts similarity index 86% rename from src/main/claude/claude-child-tool-queries.ts rename to src/main/claude/subagents/claude-child-tool-queries.ts index 42114ac4272..d42035bcd18 100644 --- a/src/main/claude/claude-child-tool-queries.ts +++ b/src/main/claude/subagents/claude-child-tool-queries.ts @@ -1,6 +1,6 @@ -import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { ClaudePendingPrompt } from './claude-prompt-registry' -import type { ClaudeToolUse } from './structured/journal/claude-structured-item-translation' +import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { ClaudePendingPrompt } from '../structured/permissions/claude-prompt-registry' +import type { ClaudeToolUse } from '../structured/journal/claude-structured-item-translation' import type { ClaudeAgentLinkageSource, ClaudeSubagentLinkageSource diff --git a/src/main/claude/subagents/claude-provisional-row-corrections.test.ts b/src/main/claude/subagents/claude-provisional-row-corrections.test.ts new file mode 100644 index 00000000000..c9ff7f239a3 --- /dev/null +++ b/src/main/claude/subagents/claude-provisional-row-corrections.test.ts @@ -0,0 +1,84 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session/journal/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import type { StructuredAgentSessionAppendOptions } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { ClaudeProvisionalRowCorrections } from './claude-provisional-row-corrections' +import type { ClaudeSubagentLinkageVerdict } from './claude-subagent-linkage' + +function identityOf(toolUseId: string): AgentJournalItemIdentity { + return { provider: 'orca', clientMessageId: `claude-tool:claude-session:${toolUseId}` } +} + +const RUNNING: AgentJournalItemBody = { + kind: 'tool-call', + callId: 'toolu_2', + name: 'Task', + input: null, + state: 'running' +} +const COMPLETED: AgentJournalItemBody = { ...RUNNING, state: 'completed' } + +function ledger(initial: Record = {}) { + const verdicts = new Map(Object.entries(initial)) + const rewrites: { + identity: AgentJournalItemIdentity + body: AgentJournalItemBody + options: StructuredAgentSessionAppendOptions + }[] = [] + let published = 0 + let refuse = false + const settledFor = (ref: string): ClaudeSubagentLinkageVerdict => { + const verdict = verdicts.get(ref) + return verdict && verdict.kind !== 'pending' + ? verdict + : { kind: 'linked', linkage: { agentId: ref, providerParentRef: ref, producerKind: 'agent' } } + } + const corrections = new ClaudeProvisionalRowCorrections({ + turnScope: () => AGENT_JOURNAL_THREAD_SCOPE, + linkageFor: (ref) => verdicts.get(ref) ?? { kind: 'pending' }, + settledLinkageFor: (ref) => { + const verdict = settledFor(ref) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: `settledFor` returns only the linked arm, never `pending`. + return verdict as Exclude + }, + rewrite: (identity, body, options) => { + if (refuse) { + return false + } + rewrites.push({ identity, body, options }) + return true + }, + publish: () => { + published += 1 + } + }) + return { + corrections, + rewrites, + announce: (ref: string, agentId: string) => + verdicts.set(ref, { + kind: 'linked', + linkage: { agentId, providerParentRef: ref, producerKind: 'agent' } + }), + publishes: () => published, + setRefusing: (value: boolean) => { + refuse = value + } + } +} + +describe('ClaudeProvisionalRowCorrections', () => { + it('carries the NEWEST body when a row is written provisionally twice', () => { + const { corrections, rewrites, announce } = ledger() + const stamp = corrections.stampFor('toolu_1') + stamp(identityOf('toolu_2'), RUNNING) + stamp(identityOf('toolu_2'), COMPLETED) + + announce('toolu_1', 'task-1') + corrections.retry() + + expect(rewrites).toHaveLength(1) + expect(rewrites[0]?.body).toEqual(COMPLETED) + }) +}) diff --git a/src/main/claude/claude-provisional-row-corrections.ts b/src/main/claude/subagents/claude-provisional-row-corrections.ts similarity index 90% rename from src/main/claude/claude-provisional-row-corrections.ts rename to src/main/claude/subagents/claude-provisional-row-corrections.ts index b229e8c6b65..b11a3341db4 100644 --- a/src/main/claude/claude-provisional-row-corrections.ts +++ b/src/main/claude/subagents/claude-provisional-row-corrections.ts @@ -1,14 +1,14 @@ // Publish before task_started using the spawn ID; correct attribution later without replacing content. -import { agentJournalLinkageFields } from '../../shared/agent-session/journal/agent-session-journal-producer' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import { agentJournalLinkageFields } from '../../../shared/agent-session/journal/agent-session-journal-producer' +import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' import type { AgentJournalItemBody, AgentJournalProducerLinkage -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import type { StructuredAgentSessionItemAppendOptions } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +} from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import type { StructuredAgentSessionItemAppendOptions } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import type { ClaudeSubagentLinkageSource } from './claude-subagent-linkage' export type ClaudeRowStamp = ( diff --git a/src/main/claude/claude-subagent-id-aliases.test.ts b/src/main/claude/subagents/claude-subagent-id-aliases.test.ts similarity index 100% rename from src/main/claude/claude-subagent-id-aliases.test.ts rename to src/main/claude/subagents/claude-subagent-id-aliases.test.ts diff --git a/src/main/claude/claude-subagent-id-aliases.ts b/src/main/claude/subagents/claude-subagent-id-aliases.ts similarity index 95% rename from src/main/claude/claude-subagent-id-aliases.ts rename to src/main/claude/subagents/claude-subagent-id-aliases.ts index 9a703790f6b..491498fca33 100644 --- a/src/main/claude/claude-subagent-id-aliases.ts +++ b/src/main/claude/subagents/claude-subagent-id-aliases.ts @@ -1,6 +1,6 @@ // Resumes change tool IDs but keep task IDs; retain aliases across restarts and remember non-agent exclusions. -import { isBoundedClaudeTaskId } from './claude-background-task-tracker' +import { isBoundedClaudeTaskId } from '../background-tasks/claude-background-task-frames' /** Bound event-accumulated aliases and exclusions. */ const MAX_TOOL_USE_ALIASES = 512 diff --git a/src/main/claude/claude-subagent-identities.ts b/src/main/claude/subagents/claude-subagent-identities.ts similarity index 95% rename from src/main/claude/claude-subagent-identities.ts rename to src/main/claude/subagents/claude-subagent-identities.ts index ebafff0d1da..b7ef0362d1f 100644 --- a/src/main/claude/claude-subagent-identities.ts +++ b/src/main/claude/subagents/claude-subagent-identities.ts @@ -1,5 +1,5 @@ -import { ClaudeTaskInvocations } from './claude-task-invocations' -import { BoundedMap } from '../../shared/bounded-map' +import { ClaudeTaskInvocations } from '../background-tasks/claude-task-invocations' +import { BoundedMap } from '../../../shared/bounded-map' import { ClaudeSubagentIds } from './claude-subagent-id-aliases' import type { ClaudeJournaledSubagents } from './claude-subagent-journaled-identities' import { diff --git a/src/main/claude/claude-subagent-journaled-identities.ts b/src/main/claude/subagents/claude-subagent-journaled-identities.ts similarity index 85% rename from src/main/claude/claude-subagent-journaled-identities.ts rename to src/main/claude/subagents/claude-subagent-journaled-identities.ts index 82b51b7d0f3..5b278a55251 100644 --- a/src/main/claude/claude-subagent-journaled-identities.ts +++ b/src/main/claude/subagents/claude-subagent-journaled-identities.ts @@ -3,12 +3,12 @@ import { selectClaudeBackgroundTask, type ClaudeBackgroundTaskIndex, type ClaudeBackgroundTaskDescriptor -} from './claude-background-task-identity' -import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' -import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' -import { namedSubagents } from '../../shared/native-chat/transcript/native-chat-subagent-items' -import type { StructuredAgentSessionLinkageJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' -import { isBoundedClaudeTaskId } from './claude-background-task-tracker' +} from '../background-tasks/claude-background-task-identity' +import { isBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types' +import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types' +import { namedSubagents } from '../../../shared/native-chat/transcript/native-chat-subagent-items' +import type { StructuredAgentSessionLinkageJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' +import { isBoundedClaudeTaskId } from '../background-tasks/claude-background-task-frames' type Reading = { canonicalByToolUse: Map diff --git a/src/main/claude/claude-subagent-linkage.ts b/src/main/claude/subagents/claude-subagent-linkage.ts similarity index 98% rename from src/main/claude/claude-subagent-linkage.ts rename to src/main/claude/subagents/claude-subagent-linkage.ts index ba8eed43498..bfd76edf32b 100644 --- a/src/main/claude/claude-subagent-linkage.ts +++ b/src/main/claude/subagents/claude-subagent-linkage.ts @@ -1,6 +1,6 @@ // Prefer canonical task IDs across resumes; write provisional child rows immediately and correct them in place. -import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types' import type { ClaudeSubagentIds } from './claude-subagent-id-aliases' export type ClaudeSubagentLinkageVerdict = diff --git a/src/main/claude/subagents/claude-subagent-resume-after-restart.test.ts b/src/main/claude/subagents/claude-subagent-resume-after-restart.test.ts new file mode 100644 index 00000000000..a28bd24858d --- /dev/null +++ b/src/main/claude/subagents/claude-subagent-resume-after-restart.test.ts @@ -0,0 +1,194 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionJournal } from '../../native-chat/agent-session-journal/journal-store' +import { createTrackedJournalOpener } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' +import { testEventSinkLogging } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' +import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' + +// Captured restart order: resumed frames retain original spawn IDs while announcements name new resume calls. + +const journals = createTrackedJournalOpener() +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-claude-subagent-restart-')) +}) + +afterEach(async () => { + vi.useRealTimers() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function frame(message: Record, startsTurn = false) { + return { + type: 'message' as const, + sessionId: 'orca-session', + ...(startsTurn ? { startsTurn: true as const } : {}), + message: { session_id: 'claude-session', parent_tool_use_id: null, ...message } + } +} + +const userTurn = (uuid: string) => + frame( + { type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text: 'go' }] } }, + true + ) + +const toolCall = (uuid: string, id: string, name: string, input: Record) => + frame({ + type: 'assistant', + uuid, + message: { role: 'assistant', content: [{ type: 'tool_use', id, name, input }] } + }) + +const toolResult = (uuid: string, toolUseId: string, content: string) => + frame({ + type: 'user', + uuid, + message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseId, content }] } + }) + +const taskStarted = (taskId: string, toolUseId: string, description: string) => + frame({ + type: 'system', + subtype: 'task_started', + uuid: `started-${toolUseId}`, + task_id: taskId, + tool_use_id: toolUseId, + description, + subagent_type: 'general-purpose', + is_backgrounded: true, + task_type: 'local_agent' + }) + +const taskFailed = (taskId: string, toolUseId: string) => + frame({ + type: 'system', + subtype: 'task_notification', + uuid: `failed-${taskId}`, + task_id: taskId, + tool_use_id: toolUseId, + status: 'failed' + }) + +const childSays = (uuid: string, parentToolUseId: string, text: string) => + frame({ + type: 'assistant', + uuid, + parent_tool_use_id: parentToolUseId, + message: { role: 'assistant', content: [{ type: 'text', text }] } + }) + +const result = (uuid: string) => + frame({ type: 'result', subtype: 'success', is_error: false, result: 'done', uuid }) + +async function openJournal(): Promise { + return journals.open({ + identity: { + sessionId: 'orca-session', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-session', null) + }, + now: () => 9_000, + stateDirectory: root + }) +} + +function acquire(journal: AgentSessionJournal, delayed = false) { + const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) + const bind = () => deferred.bind({ journal, fence: 1, publish: () => {} }) + if (!delayed) { + bind() + } + const settle = async (): Promise => { + await expect(deferred.drained()).resolves.toEqual({ ok: true }) + } + const exit = async (): Promise => { + translator.handle({ type: 'ended', sessionId: 'orca-session', reason: 'closed' }) + await settle() + translator.dispose() + deferred.close() + } + return { translator, settle, exit, bind } +} + +const proseRow = (journal: AgentSessionJournal, text: string): AgentJournalRenderItem | undefined => + journal + .snapshot() + .items.find( + (item) => + item.body.kind === 'message' && + item.body.blocks.some((block) => block.type === 'text' && block.text === text) + ) + +describe('a Claude subagent resumed after its provider restarted', () => { + it('keeps the canonical id its first run was given, so one child stays one child', async () => { + const journal = await openJournal() + + const first = acquire(journal) + first.translator.handle(userTurn('turn-a')) + first.translator.handle( + toolCall('spawn-a', 'toolu_spawn_a', 'Agent', { + description: 'Follow-up A', + run_in_background: true + }) + ) + first.translator.handle(taskStarted('agent-a', 'toolu_spawn_a', 'Follow-up A')) + first.translator.handle(toolResult('spawned-a', 'toolu_spawn_a', 'Async agent launched.')) + first.translator.handle(childSays('a-1', 'toolu_spawn_a', 'A reads the rig recipes')) + first.translator.handle( + toolCall('spawn-b', 'toolu_spawn_b', 'Agent', { + description: 'Follow-up B', + run_in_background: true + }) + ) + first.translator.handle(taskStarted('agent-b', 'toolu_spawn_b', 'Follow-up B')) + first.translator.handle(toolResult('spawned-b', 'toolu_spawn_b', 'Async agent launched.')) + first.translator.handle(childSays('b-1', 'toolu_spawn_b', 'B inspects the worktree')) + first.translator.handle(taskFailed('agent-b', 'toolu_spawn_b')) + first.translator.handle(taskFailed('agent-a', 'toolu_spawn_a')) + first.translator.handle(result('result-a')) + await first.exit() + expect(proseRow(journal, 'A reads the rig recipes')).toMatchObject({ agentId: 'agent-a' }) + + const second = acquire(journal) + second.translator.handle(userTurn('turn-b')) + second.translator.handle( + toolCall('resume-a', 'toolu_message_a', 'SendMessage', { to: 'agent-a', message: 'go on' }) + ) + second.translator.handle(taskStarted('agent-a', 'toolu_message_a', 'Follow-up A')) + second.translator.handle(toolResult('resumed-a', 'toolu_message_a', '{"success":true}')) + second.translator.handle( + toolCall('resume-b', 'toolu_message_b', 'SendMessage', { to: 'agent-b', message: 'go on' }) + ) + second.translator.handle(taskStarted('agent-b', 'toolu_message_b', 'Follow-up B')) + second.translator.handle(toolResult('resumed-b', 'toolu_message_b', '{"success":true}')) + // Preserve captured interleaving to catch cross-child identity swaps. + second.translator.handle(childSays('a-2', 'toolu_spawn_a', 'A restarts the receiver')) + second.translator.handle(childSays('b-2', 'toolu_spawn_b', 'B checks the rig')) + await second.settle() + + expect(proseRow(journal, 'A restarts the receiver')).toMatchObject({ + agentId: 'agent-a', + providerParentRef: 'toolu_spawn_a', + producerKind: 'agent' + }) + expect(proseRow(journal, 'B checks the rig')).toMatchObject({ + agentId: 'agent-b', + providerParentRef: 'toolu_spawn_b' + }) + expect(proseRow(journal, 'A reads the rig recipes')?.attempt).toBeUndefined() + expect(proseRow(journal, 'A restarts the receiver')?.attempt).toBe(2) + expect(proseRow(journal, 'B checks the rig')?.attempt).toBe(2) + await second.exit() + }) +}) diff --git a/src/main/claude/claude-subagent-task-frames.ts b/src/main/claude/subagents/claude-subagent-task-frames.ts similarity index 81% rename from src/main/claude/claude-subagent-task-frames.ts rename to src/main/claude/subagents/claude-subagent-task-frames.ts index 89602d480ce..943bb861ab8 100644 --- a/src/main/claude/claude-subagent-task-frames.ts +++ b/src/main/claude/subagents/claude-subagent-task-frames.ts @@ -1,13 +1,13 @@ -import type { AgentChildWorkKind } from '../../shared/agent-status/child-work/agent-status-child-work' +import type { AgentChildWorkKind } from '../../../shared/agent-status/child-work/agent-status-child-work' // Task IDs alone cannot distinguish agents from shells or workflows; task_type identifies the kind. +import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind' import { - classifyClaudeBackgroundTaskKind, - claudeTaskId, + taskId as claudeTaskId, isBoundedClaudeTaskId -} from './claude-background-task-tracker' -import { isAgentChildWorkKind } from '../../shared/agent-status/child-work/agent-status-child-work-liveness' -import { claudeRecord, claudeText } from './structured/journal/claude-structured-item-translation' +} from '../background-tasks/claude-background-task-frames' +import { isAgentChildWorkKind } from '../../../shared/agent-status/child-work/agent-status-child-work-liveness' +import { claudeRecord, claudeText } from '../structured/journal/claude-structured-item-translation' const TASK_SUBTYPES: ReadonlySet = new Set([ 'task_started', diff --git a/src/main/claude/claude-tool-origin-registry.ts b/src/main/claude/subagents/claude-tool-origin-registry.ts similarity index 100% rename from src/main/claude/claude-tool-origin-registry.ts rename to src/main/claude/subagents/claude-tool-origin-registry.ts diff --git a/src/main/claude/theme-sync/claude-code-theme-sync.test.ts b/src/main/claude/theme-sync/claude-code-theme-sync.test.ts index 39e71097e1c..8d1c19bd96d 100644 --- a/src/main/claude/theme-sync/claude-code-theme-sync.test.ts +++ b/src/main/claude/theme-sync/claude-code-theme-sync.test.ts @@ -2,9 +2,9 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ClaudeHookEventVersions from '../claude-hook-event-versions' +import type * as ClaudeHookEventVersions from '../cli-capabilities/claude-hook-event-versions' -vi.mock('../claude-hook-event-versions', async (importOriginal) => ({ +vi.mock('../cli-capabilities/claude-hook-event-versions', async (importOriginal) => ({ ...(await importOriginal()), probeRecentClaudeCliVersion: () => Promise.resolve(claudeVersion) })) diff --git a/src/main/claude/theme-sync/claude-code-theme-sync.ts b/src/main/claude/theme-sync/claude-code-theme-sync.ts index 1f9a224ef8f..e79c56586ec 100644 --- a/src/main/claude/theme-sync/claude-code-theme-sync.ts +++ b/src/main/claude/theme-sync/claude-code-theme-sync.ts @@ -4,14 +4,17 @@ import { dirname, join } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' import { readHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-read' import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' -import { defaultClaudeConfigDir } from '../claude-config-dir-pin' +import { defaultClaudeConfigDir } from '../structured/launch/claude-config-dir-pin' import { listClaudeProfileHomesAsync } from '../../claude-accounts/profiles/claude-profile-homes' import { getClaudeObservedConfigDirs, getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' import { resolveClaudeCommand } from '../../codex-cli/command' -import { claudeLoadsCustomThemes, probeRecentClaudeCliVersion } from '../claude-hook-event-versions' +import { + claudeLoadsCustomThemes, + probeRecentClaudeCliVersion +} from '../cli-capabilities/claude-hook-event-versions' import type { ClaudeCodeTheme } from './claude-code-theme' import { readClaudeThemeOwnership, diff --git a/src/main/claude/claude-conversation-copy.test.ts b/src/main/claude/transcripts/claude-conversation-copy.test.ts similarity index 95% rename from src/main/claude/claude-conversation-copy.test.ts rename to src/main/claude/transcripts/claude-conversation-copy.test.ts index 084c12488c4..9f850ffd52b 100644 --- a/src/main/claude/claude-conversation-copy.test.ts +++ b/src/main/claude/transcripts/claude-conversation-copy.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { copyClaudeConversation } from './claude-conversation-copy' const accounts = vi.hoisted((): { homes: string[] } => ({ homes: [] })) -vi.mock('../claude-accounts/profiles/routing/claude-profile-installed-router', () => ({ +vi.mock('../../claude-accounts/profiles/routing/claude-profile-installed-router', () => ({ getClaudeProfileRouter: () => ({ accountHomes: () => accounts.homes, systemDefaultHome: () => accounts.homes[0] @@ -34,7 +34,7 @@ beforeEach(async () => { await mkdir(project, { recursive: true }) sourcePath = join(project, `${SOURCE}.jsonl`) const source = await readFile( - new URL('./__fixtures__/claude-rewind-hook.jsonl', import.meta.url), + new URL('../__fixtures__/claude-rewind-hook.jsonl', import.meta.url), 'utf8' ) rows = parseRows(source) diff --git a/src/main/claude/claude-conversation-copy.ts b/src/main/claude/transcripts/claude-conversation-copy.ts similarity index 75% rename from src/main/claude/claude-conversation-copy.ts rename to src/main/claude/transcripts/claude-conversation-copy.ts index c659f4aad3e..52fde8eb027 100644 --- a/src/main/claude/claude-conversation-copy.ts +++ b/src/main/claude/transcripts/claude-conversation-copy.ts @@ -1,9 +1,9 @@ import { basename, dirname, join } from 'node:path' -import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' -import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' -import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { resolveSessionFilePath } from '../native-chat/session-file-resolver' +import { requireLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' +import { AgentConversationCopyError } from '../../native-chat/conversation-adoption/agent-conversation-copy-error' +import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { resolveSessionFilePath } from '../../native-chat/session-file-resolver' import { materializeClaudeConversationTranscript } from './claude-rewind-transcript' export const copyClaudeConversation: NonNullable< diff --git a/src/main/claude/claude-conversation-fork-boundary.ts b/src/main/claude/transcripts/claude-conversation-fork-boundary.ts similarity index 91% rename from src/main/claude/claude-conversation-fork-boundary.ts rename to src/main/claude/transcripts/claude-conversation-fork-boundary.ts index c13d47bee21..019a661cfae 100644 --- a/src/main/claude/claude-conversation-fork-boundary.ts +++ b/src/main/claude/transcripts/claude-conversation-fork-boundary.ts @@ -1,16 +1,16 @@ import type { SessionStoreEntry } from '@anthropic-ai/claude-agent-sdk' -import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' -import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { decodeClaudeTranscriptLine } from '../native-chat/transcript-line-decoders-claude' +import { AgentConversationCopyError } from '../../native-chat/conversation-adoption/agent-conversation-copy-error' +import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { decodeClaudeTranscriptLine } from '../../native-chat/transcript-decoding/transcript-line-decoders-claude' import { isLocalCommandCaveatRow } from './claude-rewind-fork' -import { claudeSourceBlockId } from './claude-streamed-block-identity' +import { claudeSourceBlockId } from '../structured/journal/claude-streamed-block-identity' import { isClaudeTranscriptRootPrompt } from './claude-transcript-root-prompt' import { claudeRecord, claudeToolUses, claudeToolResults, readClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' +} from '../structured/journal/claude-structured-item-translation' import { claudeTranscriptPrompt } from './claude-transcript-prompt' export type ClaudeForkCheckpoint = NonNullable< diff --git a/src/main/claude/claude-conversation-fork-worker-entry.ts b/src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts similarity index 97% rename from src/main/claude/claude-conversation-fork-worker-entry.ts rename to src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts index 682cf360079..f11eeb3ac96 100644 --- a/src/main/claude/claude-conversation-fork-worker-entry.ts +++ b/src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts @@ -8,7 +8,7 @@ import { createInterface } from 'node:readline' import { parentPort, workerData } from 'node:worker_threads' import { publishClaudeConversationTranscript } from './claude-conversation-transcript-publication' -import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' +import { AgentConversationCopyError } from '../../native-chat/conversation-adoption/agent-conversation-copy-error' import { claudeConversationForkBoundary, isClaudeConversationEntry, diff --git a/src/main/claude/claude-conversation-transcript-publication.test.ts b/src/main/claude/transcripts/claude-conversation-transcript-publication.test.ts similarity index 76% rename from src/main/claude/claude-conversation-transcript-publication.test.ts rename to src/main/claude/transcripts/claude-conversation-transcript-publication.test.ts index 08b095ebce4..08af616db8d 100644 --- a/src/main/claude/claude-conversation-transcript-publication.test.ts +++ b/src/main/claude/transcripts/claude-conversation-transcript-publication.test.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs' -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' @@ -52,15 +52,3 @@ it('removes an incomplete owned temp without publishing or replacing a destinati expect(existsSync(temporary)).toBe(false) expect(await readFile(destination, 'utf8')).toBe('existing transcript\n') }) - -it('removes the fsynced temp when publishing the copy fails', async () => { - const temporary = join(root, 'owned.tmp') - const destination = join(root, 'existing-directory') - await mkdir(destination) - await writeFile(join(destination, 'kept'), 'existing data') - await expect( - publishClaudeConversationTranscript(temporary, destination, [{ type: 'user', uuid: 'first' }]) - ).rejects.toThrow() - expect(existsSync(temporary)).toBe(false) - expect(await readFile(join(destination, 'kept'), 'utf8')).toBe('existing data') -}) diff --git a/src/main/claude/claude-conversation-transcript-publication.ts b/src/main/claude/transcripts/claude-conversation-transcript-publication.ts similarity index 91% rename from src/main/claude/claude-conversation-transcript-publication.ts rename to src/main/claude/transcripts/claude-conversation-transcript-publication.ts index ab0658d6ac9..37836f77426 100644 --- a/src/main/claude/claude-conversation-transcript-publication.ts +++ b/src/main/claude/transcripts/claude-conversation-transcript-publication.ts @@ -1,5 +1,5 @@ import { open, rm } from 'node:fs/promises' -import { renameDurable } from '../filesystem/durable-file-write' +import { renameDurable } from '../../filesystem/durable-file-write' /** Serialize one record at a time, then publish the fsynced file with Windows rename retries. */ export async function publishClaudeConversationTranscript( diff --git a/src/main/claude/claude-conversation-worker.test-fixture.ts b/src/main/claude/transcripts/claude-conversation-worker.test-fixture.ts similarity index 100% rename from src/main/claude/claude-conversation-worker.test-fixture.ts rename to src/main/claude/transcripts/claude-conversation-worker.test-fixture.ts diff --git a/src/main/claude/claude-conversation-worker.test-loader.mjs b/src/main/claude/transcripts/claude-conversation-worker.test-loader.mjs similarity index 100% rename from src/main/claude/claude-conversation-worker.test-loader.mjs rename to src/main/claude/transcripts/claude-conversation-worker.test-loader.mjs diff --git a/src/main/claude/transcripts/claude-provider-session-rename.test.ts b/src/main/claude/transcripts/claude-provider-session-rename.test.ts new file mode 100644 index 00000000000..e4f5aaffbcd --- /dev/null +++ b/src/main/claude/transcripts/claude-provider-session-rename.test.ts @@ -0,0 +1,44 @@ +import { randomUUID } from 'node:crypto' +import * as fs from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import * as transcriptFs from '../../native-chat/transcript-filesystem/wsl-transcript-fs-access' +import { renameClaudeTranscript } from './claude-provider-session-rename' + +let home: string +let conversation: string +let transcript: string +beforeEach(async () => { + home = await fs.mkdtemp(join(tmpdir(), 'orca-claude-rename-')) + conversation = randomUUID() + const project = join(home, 'projects', 'workspace') + await fs.mkdir(project, { recursive: true }) + transcript = join(project, `${conversation}.jsonl`) +}) +afterEach(async () => { + vi.restoreAllMocks() + await fs.rm(home, { recursive: true, force: true }) +}) + +it('refuses missing, empty, multiple and incomplete inventories without mutating another candidate', async () => { + await expect(renameClaudeTranscript(home, conversation, 'Missing')).rejects.toThrow( + 'no transcript' + ) + await fs.writeFile(transcript, '') + await expect(renameClaudeTranscript(home, conversation, 'Empty')).rejects.toThrow('no transcript') + await fs.writeFile(transcript, 'old\n') + const second = join(home, 'projects', 'hash-or-worktree') + await fs.mkdir(second) + const duplicate = join(second, `${conversation}.jsonl`) + await fs.writeFile(duplicate, 'other\n') + await expect(renameClaudeTranscript(home, conversation, 'Ambiguous')).rejects.toThrow( + 'multiple transcripts' + ) + expect(await fs.readFile(transcript, 'utf8')).toBe('old\n') + expect(await fs.readFile(duplicate, 'utf8')).toBe('other\n') + const denied = Object.assign(new Error('denied'), { code: 'EACCES' }) + vi.spyOn(transcriptFs, 'wslGatedStat').mockRejectedValue(denied) + await expect(renameClaudeTranscript(home, conversation, 'Denied')).rejects.toBe(denied) + expect(await fs.readFile(transcript, 'utf8')).toBe('old\n') +}) diff --git a/src/main/claude/claude-provider-session-rename.ts b/src/main/claude/transcripts/claude-provider-session-rename.ts similarity index 89% rename from src/main/claude/claude-provider-session-rename.ts rename to src/main/claude/transcripts/claude-provider-session-rename.ts index 40f97911495..5276737cb47 100644 --- a/src/main/claude/claude-provider-session-rename.ts +++ b/src/main/claude/transcripts/claude-provider-session-rename.ts @@ -1,9 +1,12 @@ import type { SessionStoreEntry } from '@anthropic-ai/claude-agent-sdk' import { appendFile, open } from 'node:fs/promises' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { wslGatedReaddir, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' -import { loadClaudeAgentSdk } from './claude-stream-json-connection' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import { + wslGatedReaddir, + wslGatedStat +} from '../../native-chat/transcript-filesystem/wsl-transcript-fs-access' +import { loadClaudeAgentSdk } from '../claude-stream-json-connection' export async function renameClaudeTranscript( home: string, diff --git a/src/main/claude/claude-rewind-fork.ts b/src/main/claude/transcripts/claude-rewind-fork.ts similarity index 85% rename from src/main/claude/claude-rewind-fork.ts rename to src/main/claude/transcripts/claude-rewind-fork.ts index 1c1f22a174b..b2d28ad6989 100644 --- a/src/main/claude/claude-rewind-fork.ts +++ b/src/main/claude/transcripts/claude-rewind-fork.ts @@ -1,16 +1,16 @@ import { createReadStream } from 'node:fs' import { basename, dirname, join } from 'node:path' -import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' +import { requireLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import { agentSessionProviderHandleChainHead, type AgentSessionProviderHandle -} from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import type { AgentSessionRewindFork } from '../../shared/agent-session/lifecycle/agent-session-rewind' -import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' -import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { resolveSessionFilePath } from '../native-chat/session-file-resolver' -import { splitTranscriptStreamLines } from '../native-chat/transcript-stream-lines' -import { claudeSessionIdForRewind } from './structured/claude-structured-session-id' +} from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AgentSessionRewindFork } from '../../../shared/agent-session/lifecycle/agent-session-rewind' +import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' +import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { resolveSessionFilePath } from '../../native-chat/session-file-resolver' +import { splitTranscriptStreamLines } from '../../native-chat/transcript-streaming/transcript-stream-lines' +import { claudeSessionIdForRewind } from '../structured/claude-structured-session-id' import { materializeClaudeRewindTranscript } from './claude-rewind-transcript' type TranscriptUserRow = { diff --git a/src/main/claude/transcripts/claude-rewind-transcript.test.ts b/src/main/claude/transcripts/claude-rewind-transcript.test.ts new file mode 100644 index 00000000000..391c42a7e1c --- /dev/null +++ b/src/main/claude/transcripts/claude-rewind-transcript.test.ts @@ -0,0 +1,97 @@ +import './claude-conversation-worker.test-fixture' +import { randomUUID } from 'node:crypto' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' + +import { resolveClaudeRewindFork } from './claude-rewind-fork' + +let root: string +let home: string +let project: string +let source: string +let path: string +let original: string +let sourceRows: ReturnType + +function transcriptRows(contents: string) { + return contents + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +async function recordedTranscript(kind: 'hook' | 'informational') { + return readFile(new URL(`../__fixtures__/claude-rewind-${kind}.jsonl`, import.meta.url), 'utf8') +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-rewind-transcript-')) + home = join(root, 'account') + project = join(home, 'projects', 'workspace') + await mkdir(project, { recursive: true }) + original = await recordedTranscript('hook') + sourceRows = transcriptRows(original) + source = sourceRows[6].sessionId + path = join(project, `${source}.jsonl`) + await writeFile(path, original) +}) + +afterEach(async () => { + await rm(root, { recursive: true, force: true }) +}) + +function forkBefore(uuid: string, rewindOperationId = randomUUID()) { + return resolveClaudeRewindFork({ + orcaSessionId: 'orca-chat', + rewindOperationId, + head: claudeProviderHandle(source, sourceRows.at(-1)?.uuid), + prompt: { sessionId: source, uuid }, + claudeConfigDirs: [join(root, 'other-account'), home] + }) +} + +describe('durable Claude rewind transcripts', () => { + it('drops the local-command caveat when rewinding to a local command', async () => { + const turn = sourceRows[50] + const row = (uuid: string, parentUuid: string, content: string, isMeta?: true) => ({ + ...sourceRows[54], + uuid, + parentUuid, + isMeta, + message: { role: 'user', content } + }) + const caveat = row( + randomUUID(), + turn.uuid, + 'The command below was run directly in Claude Code.', + true + ) + const command = row(randomUUID(), caveat.uuid, '/usage') + const stdout = row( + randomUUID(), + command.uuid, + 'ok' + ) + await writeFile( + path, + `${[...sourceRows.slice(0, 54), caveat, command, stdout].map((r) => JSON.stringify(r)).join('\n')}\n` + ) + const fork = await forkBefore(command.uuid) + expect(fork).toMatchObject({ materialized: true, throughEntryId: turn.uuid }) + const contents = await readFile(join(project, `${fork?.sessionId}.jsonl`), 'utf8') + expect(contents).not.toContain('local-command-caveat') + }) + + it('skips a torn transcript line instead of failing the rewind', async () => { + const damaged = `{broken-json}\n${original}{"type":` + await writeFile(path, damaged) + const fork = await forkBefore(sourceRows[34].uuid) + expect(fork).toMatchObject({ materialized: true, throughEntryId: sourceRows[27].uuid }) + const contents = await readFile(join(project, `${fork?.sessionId}.jsonl`), 'utf8') + expect(contents).not.toContain(sourceRows[34].uuid) + expect(await readFile(path, 'utf8')).toBe(damaged) + }) +}) diff --git a/src/main/claude/claude-rewind-transcript.ts b/src/main/claude/transcripts/claude-rewind-transcript.ts similarity index 91% rename from src/main/claude/claude-rewind-transcript.ts rename to src/main/claude/transcripts/claude-rewind-transcript.ts index 61e545e36bb..4fa975ff5f3 100644 --- a/src/main/claude/claude-rewind-transcript.ts +++ b/src/main/claude/transcripts/claude-rewind-transcript.ts @@ -1,14 +1,14 @@ -import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' +import { AgentConversationCopyError } from '../../native-chat/conversation-adoption/agent-conversation-copy-error' import { existsSync } from 'node:fs' import { rm } from 'node:fs/promises' import { dirname, join } from 'node:path' -import type { AgentSessionRewindFork } from '../../shared/agent-session/lifecycle/agent-session-rewind' -import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' +import type { AgentSessionRewindFork } from '../../../shared/agent-session/lifecycle/agent-session-rewind' +import { spawnWorkerThread } from '../../worker-threads/worker-thread-spawn' import { currentWorkerEntryLayout, resolveWorkerThreadEntryPath -} from '../worker-threads/worker-thread-entry-path' -import { durableWriteTempPath } from '../filesystem/durable-file-write' +} from '../../worker-threads/worker-thread-entry-path' +import { durableWriteTempPath } from '../../filesystem/durable-file-write' import type { ClaudeForkCheckpoint } from './claude-conversation-fork-boundary' import type { ClaudeConversationForkWork } from './claude-conversation-fork-worker-entry' diff --git a/src/main/claude/claude-transcript-catch-up-test-support.ts b/src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts similarity index 92% rename from src/main/claude/claude-transcript-catch-up-test-support.ts rename to src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts index cd64526f018..16ca3459c10 100644 --- a/src/main/claude/claude-transcript-catch-up-test-support.ts +++ b/src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts @@ -3,12 +3,12 @@ import { appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, type Mock, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { createTrackedJournalOpener } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { testEventSinkLogging } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' +import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' import { catchUpClaudeTranscript } from './claude-transcript-catch-up' export const SESSION = 'session-claude-catch-up' diff --git a/src/main/claude/claude-transcript-catch-up.test.ts b/src/main/claude/transcripts/claude-transcript-catch-up.test.ts similarity index 93% rename from src/main/claude/claude-transcript-catch-up.test.ts rename to src/main/claude/transcripts/claude-transcript-catch-up.test.ts index e27ba39f354..1340f8f29ea 100644 --- a/src/main/claude/claude-transcript-catch-up.test.ts +++ b/src/main/claude/transcripts/claude-transcript-catch-up.test.ts @@ -1,7 +1,7 @@ import './claude-conversation-worker.test-fixture' import { describe, expect, it, vi } from 'vitest' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' import { SESSION, diff --git a/src/main/claude/claude-transcript-catch-up.ts b/src/main/claude/transcripts/claude-transcript-catch-up.ts similarity index 87% rename from src/main/claude/claude-transcript-catch-up.ts rename to src/main/claude/transcripts/claude-transcript-catch-up.ts index cfcbaa2ef1f..853f3776795 100644 --- a/src/main/claude/claude-transcript-catch-up.ts +++ b/src/main/claude/transcripts/claude-transcript-catch-up.ts @@ -2,14 +2,14 @@ import { nativeCopyIds, usableJournalHistoryOrigin, type JournalHistoryOrigin -} from '../native-chat/agent-session-journal/context-epochs/journal-history-origin' +} from '../../native-chat/agent-session-journal/context-epochs/journal-history-origin' import { recoverClaudeTranscript } from './claude-transcript-recovery' import { join } from 'node:path' -import { isRootAgentJournalItem } from '../../shared/agent-session/journal/agent-session-journal-producer' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { runHistoryCatchUp } from '../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' -import type { StructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { resolveSessionFilePath } from '../native-chat/session-file-resolver' +import { isRootAgentJournalItem } from '../../../shared/agent-session/journal/agent-session-journal-producer' +import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { runHistoryCatchUp } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' +import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { resolveSessionFilePath } from '../../native-chat/session-file-resolver' import { createClaudeTranscriptImportPlan } from './claude-transcript-import-plan' import { readClaudeTranscriptTail } from './claude-transcript-tail' diff --git a/src/main/claude/claude-transcript-entry-uuid.test.ts b/src/main/claude/transcripts/claude-transcript-entry-uuid.test.ts similarity index 100% rename from src/main/claude/claude-transcript-entry-uuid.test.ts rename to src/main/claude/transcripts/claude-transcript-entry-uuid.test.ts diff --git a/src/main/claude/claude-transcript-entry-uuid.ts b/src/main/claude/transcripts/claude-transcript-entry-uuid.ts similarity index 100% rename from src/main/claude/claude-transcript-entry-uuid.ts rename to src/main/claude/transcripts/claude-transcript-entry-uuid.ts diff --git a/src/main/claude/claude-transcript-import-plan.ts b/src/main/claude/transcripts/claude-transcript-import-plan.ts similarity index 88% rename from src/main/claude/claude-transcript-import-plan.ts rename to src/main/claude/transcripts/claude-transcript-import-plan.ts index 4f555aecca1..dc9cf58a623 100644 --- a/src/main/claude/claude-transcript-import-plan.ts +++ b/src/main/claude/transcripts/claude-transcript-import-plan.ts @@ -2,32 +2,32 @@ import { isDeepStrictEqual } from 'node:util' import { agentJournalItemKey, parseAgentJournalItemKey -} from '../../shared/agent-session/journal/agent-session-journal-item-key' +} from '../../../shared/agent-session/journal/agent-session-journal-item-key' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import '../native-chat/agent-session-journal/writing/journal-row-builders' -import { journalLifecycleItemMutation } from '../native-chat/agent-session-journal/writing/journal-lifecycle-mutation' +} from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import '../../native-chat/agent-session-journal/writing/journal-row-builders' +import { journalLifecycleItemMutation } from '../../native-chat/agent-session-journal/writing/journal-lifecycle-mutation' import { continuedOutsideNotice, continuedOutsideRecordId, createHistoryCatchUpBatch, HISTORY_CATCH_UP_MAX_OPERATIONS, type HistoryCatchUpPlan -} from '../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' +} from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' import { legacyItemBody, LEGACY_IMPORT_BLOCK_LIMITS -} from '../native-chat/agent-session-journal/history-import/journal-legacy-import' +} from '../../native-chat/agent-session-journal/history-import/journal-legacy-import' import type { StructuredAgentSessionEventSink, StructuredAgentSessionItemAppendOptions -} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { StructuredAgentSessionTransitionJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-transition' -import { claudeSourceBlockId } from './claude-streamed-block-identity' +} from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import type { StructuredAgentSessionTransitionJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-transition' +import { claudeSourceBlockId } from '../structured/journal/claude-streamed-block-identity' import { claudeMessageIdentity, claudeRecord, @@ -37,14 +37,14 @@ import { claudeToolResults, claudeToolUses, readClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +} from '../structured/journal/claude-structured-item-translation' +import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' import { createClaudeTranscriptItemReader, claudeRestoredItemBody } from './claude-transcript-item-reader' -import { idleClaudeJournalTurn } from './claude-session-state-turn-over' -import { claudeMessageWithoutSyntheticText } from './claude-internal-message-content' +import { idleClaudeJournalTurn } from '../structured/turns/claude-session-state-turn-over' +import { claudeMessageWithoutSyntheticText } from '../structured/journal/claude-internal-message-content' import { claudeTranscriptPrompt } from './claude-transcript-prompt' export function createClaudeTranscriptImportPlan(input: { diff --git a/src/main/claude/claude-transcript-item-reader.ts b/src/main/claude/transcripts/claude-transcript-item-reader.ts similarity index 85% rename from src/main/claude/claude-transcript-item-reader.ts rename to src/main/claude/transcripts/claude-transcript-item-reader.ts index 8181b3b9592..ddaa8ad4d92 100644 --- a/src/main/claude/claude-transcript-item-reader.ts +++ b/src/main/claude/transcripts/claude-transcript-item-reader.ts @@ -2,12 +2,12 @@ import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody, type AgentJournalRenderItem -} from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { HISTORY_CATCH_UP_MAX_OPERATIONS } from '../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' -import type { StructuredAgentSessionTransitionJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-transition' -import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { claudePromptUuidForSubmission } from './structured/claude-structured-session-id' +} from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope' +import { HISTORY_CATCH_UP_MAX_OPERATIONS } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up' +import type { StructuredAgentSessionTransitionJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-transition' +import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' +import { claudePromptUuidForSubmission } from '../structured/claude-structured-session-id' /** Every saved item used by the projection is a conditional commit dependency, even if equal. */ export function createClaudeTranscriptItemReader( diff --git a/src/main/claude/claude-transcript-prompt.ts b/src/main/claude/transcripts/claude-transcript-prompt.ts similarity index 78% rename from src/main/claude/claude-transcript-prompt.ts rename to src/main/claude/transcripts/claude-transcript-prompt.ts index 51cc4712797..fa2417f7ef4 100644 --- a/src/main/claude/claude-transcript-prompt.ts +++ b/src/main/claude/transcripts/claude-transcript-prompt.ts @@ -1,11 +1,11 @@ -import { isClaudeToolResultContent } from '../../shared/claude-tool-content' -import { decodeClaudeTranscriptLine } from '../native-chat/transcript-line-decoders-claude' -import { claudeEnvelopeStopHookFeedbackRow } from './claude-stop-hook-feedback' +import { isClaudeToolResultContent } from '../../../shared/claude-tool-content' +import { decodeClaudeTranscriptLine } from '../../native-chat/transcript-decoding/transcript-line-decoders-claude' +import { claudeEnvelopeStopHookFeedbackRow } from '../structured/journal/claude-stop-hook-feedback' import { claudeRecord, claudeOutputEnvelope, type ClaudeMessageEnvelope -} from './structured/journal/claude-structured-item-translation' +} from '../structured/journal/claude-structured-item-translation' export function claudeTranscriptPrompt( row: Record, diff --git a/src/main/claude/claude-transcript-recovery.ts b/src/main/claude/transcripts/claude-transcript-recovery.ts similarity index 100% rename from src/main/claude/claude-transcript-recovery.ts rename to src/main/claude/transcripts/claude-transcript-recovery.ts diff --git a/src/main/claude/claude-transcript-root-prompt.ts b/src/main/claude/transcripts/claude-transcript-root-prompt.ts similarity index 86% rename from src/main/claude/claude-transcript-root-prompt.ts rename to src/main/claude/transcripts/claude-transcript-root-prompt.ts index f6a7cad41da..4049032caff 100644 --- a/src/main/claude/claude-transcript-root-prompt.ts +++ b/src/main/claude/transcripts/claude-transcript-root-prompt.ts @@ -1,5 +1,5 @@ import { claudeTranscriptPrompt } from './claude-transcript-prompt' -import { readClaudeMessageEnvelope } from './structured/journal/claude-structured-item-translation' +import { readClaudeMessageEnvelope } from '../structured/journal/claude-structured-item-translation' /** Attachments/queued steer and tool results continue the existing root. */ export function isClaudeTranscriptRootPrompt(row: Record): boolean { diff --git a/src/main/claude/claude-transcript-tail.ts b/src/main/claude/transcripts/claude-transcript-tail.ts similarity index 97% rename from src/main/claude/claude-transcript-tail.ts rename to src/main/claude/transcripts/claude-transcript-tail.ts index ed544f027d8..9235d9f655d 100644 --- a/src/main/claude/claude-transcript-tail.ts +++ b/src/main/claude/transcripts/claude-transcript-tail.ts @@ -1,6 +1,6 @@ import { isClaudeConversationEntry } from './claude-conversation-fork-boundary' import { open } from 'node:fs/promises' -import { claudeRecord } from './structured/journal/claude-structured-item-translation' +import { claudeRecord } from '../structured/journal/claude-structured-item-translation' // Read backward to the saved leaf so catch-up costs only the appended stretch, not the whole conversation. diff --git a/src/main/claude/windows-hook-files.test.ts b/src/main/claude/windows-hook-files.test.ts deleted file mode 100644 index 2a79cdb3fcf..00000000000 --- a/src/main/claude/windows-hook-files.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import type * as osModule from 'node:os' -import { join } from 'node:path' -import * as refresh from '../agent-hooks/installation/scripts/managed-hook-script-refresh' -import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' -import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' -import { ClaudeHookService } from './hook-service' -import { getWindowsManagedLifecycleHook } from './hook-settings' -import { getWindowsClaudeHookEntry, getWindowsClaudeHookPayloadPath } from './windows-hook-files' - -const { home } = vi.hoisted(() => ({ home: { path: '' } })) -vi.mock('node:os', async (original) => ({ - ...(await original()), - homedir: () => home.path -})) -vi.mock('electron', () => ({ app: { getPath: () => home.path } })) - -const platform = Object.getOwnPropertyDescriptor(process, 'platform')! -let entry: string -let payload: string -let settings: string -const service = new ClaudeHookService() - -beforeEach(() => { - home.path = mkdtempSync(join(tmpdir(), 'claude-windows-files-')) - entry = join(home.path, '.orca', 'agent-hooks', 'claude-hook.cmd') - payload = getWindowsClaudeHookPayloadPath(entry) - settings = join(home.path, '.claude', 'settings.json') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) -}) - -afterEach(() => { - Object.defineProperty(process, 'platform', platform) - vi.restoreAllMocks() - rmSync(home.path, { recursive: true, force: true }) -}) - -describe('Windows Claude hook files', () => { - it('repairs a missing payload from the surviving entry without touching settings', async () => { - service.install() - rmSync(payload) - expect(service.getStatus().state).toBe('partial') - const configBefore = readFileSync(settings, 'utf8') - await service.refreshManagedScripts() - expect(service.getStatus().state).toBe('installed') - expect(readFileSync(entry, 'utf8')).toBe(getWindowsClaudeHookEntry()) - expect(readFileSync(payload, 'utf8')).toContain('/hook/claude') - expect(readFileSync(settings, 'utf8')).toBe(configBefore) - }) - - it.each(['entry', 'both'])('leaves a missing %s to install()', async (missing) => { - service.install() - rmSync(entry) - if (missing === 'both') { - rmSync(payload) - } - await service.refreshManagedScripts() - expect(existsSync(entry)).toBe(false) - expect(service.getStatus().state).toBe('partial') - expect(service.install().state).toBe('installed') - expect(readFileSync(entry, 'utf8')).toBe(getWindowsClaudeHookEntry()) - expect(readFileSync(payload, 'utf8')).toContain('/hook/claude') - }) - - it('leaves the old single-file entry intact when payload publication fails', async () => { - mkdirSync(join(home.path, '.orca', 'agent-hooks'), { recursive: true }) - const oldEntry = '@echo off\r\necho {}\r\nexit /b 0\r\n' - writeFileSync(entry, oldEntry) - vi.spyOn(refresh, 'restoreManagedScript').mockRejectedValueOnce(new Error('disk full')) - await expect(service.refreshManagedScripts()).rejects.toThrow('disk full') - expect(readFileSync(entry, 'utf8')).toBe(oldEntry) - expect(existsSync(payload)).toBe(false) - }) - - it('publishes the payload before replacing a legacy entry', async () => { - mkdirSync(join(home.path, '.orca', 'agent-hooks'), { recursive: true }) - writeFileSync(entry, 'legacy payload') - const restore = refresh.restoreManagedScript - const writes: string[] = [] - vi.spyOn(refresh, 'restoreManagedScript').mockImplementation(async (path, content) => { - if (path === entry) { - expect(readFileSync(payload, 'utf8')).toContain('/hook/claude') - } - writes.push(path) - await restore(path, content) - }) - await service.refreshManagedScripts() - expect(writes).toEqual([payload, entry]) - expect(existsSync(settings)).toBe(false) - }) - - it('keeps inert scripts on uninstall and never creates an entry from an orphan payload', async () => { - service.install() - service.remove() - expect(JSON.stringify(readHooksJson(settings))).not.toContain('claude-hook.cmd') - // Keep scripts callable for sessions still holding the old hook settings. - expect(readFileSync(entry, 'utf8')).toBe(getWindowsClaudeHookEntry()) - rmSync(entry) - writeFileSync(payload, 'orphan payload') - await service.refreshManagedScripts() - expect(existsSync(entry)).toBe(false) - expect(readFileSync(payload, 'utf8')).toBe('orphan payload') - }) - - it('migrates old command forms while preserving user hooks', () => { - const encoded = getWindowsManagedLifecycleHook( - 'C:\\Users\\%name%\\.orca\\agent-hooks\\claude-hook.cmd' - ) - writeHooksJson(settings, { - hooks: { - Stop: [{ hooks: [encoded, { type: 'command', command: 'echo user-hook' }] }], - PreToolUse: [ - { - hooks: [ - { type: 'command', command: 'C:/old/.orca/agent-hooks/claude-hook.cmd || echo {}' } - ] - } - ] - } - }) - service.install() - const config = JSON.stringify(readHooksJson(settings)) - expect(config).not.toContain('|| echo {}') - expect(config).not.toContain('C:/old/') - expect(config).toContain('echo user-hook') - expect(service.getStatus().state).toBe('installed') - }) -}) diff --git a/src/main/claude/windows-native-hook-registration.test.ts b/src/main/claude/windows-native-hook-registration.test.ts deleted file mode 100644 index bf01e0fe34f..00000000000 --- a/src/main/claude/windows-native-hook-registration.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { spawnProcess } from '@orca/process-host' -import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import { once } from 'node:events' -import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import type * as NativeHookExecutableModule from '../agent-hooks/installation/commands/windows-native-hook-executable' - -vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) - -const { bundledHook } = vi.hoisted(() => { - const bundledHook: { path: string | null } = { path: null } - return { bundledHook } -}) -vi.mock( - '../agent-hooks/installation/commands/windows-native-hook-executable', - async (importOriginal) => ({ - ...(await importOriginal()), - resolveBundledWindowsNativeHookExecutable: () => bundledHook.path - }) -) - -import { - createManagedCommandMatcher, - removeManagedCommands -} from '../agent-hooks/installation/commands/managed-hook-command-matching' -import type { - HookCommandConfig, - HookDefinition -} from '../agent-hooks/installation/configuration/hook-config-schema' -import { - buildWindowsNativeHookExecutable, - WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from '../agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture' -import { ClaudeHookService } from './hook-service' - -const CURRENT_CLAUDE = { claudeVersion: '2.1.261 (Claude Code)' } -const EXE = 'orca-agent-hook.exe' - -describe.skipIf(process.platform !== 'win32')('ClaudeHookService native hook install', () => { - let home = '' - - afterEach(() => { - vi.unstubAllEnvs() - bundledHook.path = null - if (home) { - removeTreeSync(home) - home = '' - } - }) - - function useTempHome(prefix = 'orca-claude-native-hook-'): { - hooksDir: string - settingsPath: string - bundle: string - } { - home = mkdtempSync(join(tmpdir(), prefix)) - vi.stubEnv('HOME', home) - vi.stubEnv('USERPROFILE', home) - const bundle = join(home, 'bundled-agent-hook.exe') - writeFileSync(bundle, 'MZ stand-in for the signed bundle') - return { - hooksDir: join(home, '.orca', 'agent-hooks'), - settingsPath: join(home, '.claude', 'settings.json'), - bundle - } - } - - function managedHooks(settingsPath: string, event: string): HookCommandConfig[] { - const settings = JSON.parse(readFileSync(settingsPath, 'utf8')) - const definitions: HookDefinition[] = settings.hooks[event] - const isManaged = createManagedCommandMatcher('claude-hook.cmd') - return definitions - .flatMap((definition) => definition.hooks ?? []) - .filter((hook) => removeManagedCommands([{ hooks: [hook] }], isManaged).length === 0) - } - - function managedCommands(settingsPath: string, event: string): string[] { - return managedHooks(settingsPath, event).map((hook) => hook.command) - } - - const exeCommand = (hooksDir: string): string => - `${join(hooksDir, EXE).replaceAll('\\', '/')} claude` - - // Holding stdin open keeps the hook image mapped to exercise locked-executable replacement. - function startHeldHook(program: string): ChildProcessWithoutNullStreams { - return spawnProcess({ - program, - args: ['claude'], - env: { - SystemRoot: process.env.SystemRoot, - ORCA_AGENT_HOOK_PORT: '1', - ORCA_AGENT_HOOK_TOKEN: 'token', - ORCA_PANE_KEY: 'tab:leaf' - }, - stdio: ['pipe', 'pipe', 'pipe'] - }) - } - - it( - 'replaces a copy whose hook is still running by moving it aside, in install and refresh', - { timeout: WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS }, - async () => { - const { hooksDir, settingsPath } = useTempHome() - bundledHook.path = buildWindowsNativeHookExecutable() - const service = new ClaudeHookService() - expect(service.install(CURRENT_CLAUDE).state).toBe('installed') - const installed = join(hooksDir, EXE) - const built = readFileSync(installed) - const nextBuild = (tag: string): Buffer => { - const path = join(home, `${tag}.exe`) - writeFileSync(path, Buffer.concat([built, Buffer.from(tag)])) - bundledHook.path = path - return readFileSync(path) - } - - const held = startHeldHook(installed) - try { - await once(held.stdout, 'data') - const next = nextBuild('next') - expect(service.install(CURRENT_CLAUDE).state).toBe('installed') - expect(managedCommands(settingsPath, 'Stop')).toEqual([exeCommand(hooksDir)]) - expect(readFileSync(installed).equals(next)).toBe(true) - expect(readFileSync(`${installed}.old`).equals(built)).toBe(true) - } finally { - held.stdin.end() - await once(held, 'close') - } - - const refreshing = startHeldHook(installed) - try { - await once(refreshing.stdout, 'data') - const later = nextBuild('later') - await service.refreshManagedScripts() - expect(readFileSync(installed).equals(later)).toBe(true) - } finally { - refreshing.stdin.end() - await once(refreshing, 'close') - } - - expect(service.install(CURRENT_CLAUDE).state).toBe('installed') - expect(existsSync(`${installed}.old`)).toBe(false) - } - ) -}) diff --git a/src/main/codebuddy/hook-service.test.ts b/src/main/codebuddy/hook-service.test.ts deleted file mode 100644 index 54c99319d87..00000000000 --- a/src/main/codebuddy/hook-service.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import type * as OsModule from 'node:os' -import { join } from 'node:path' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -const sandbox = vi.hoisted(() => ({ home: '' })) -vi.mock('node:os', async (importOriginal) => ({ - ...(await importOriginal()), - homedir: () => sandbox.home -})) -vi.mock('electron', () => ({ app: { getPath: () => sandbox.home } })) -import { getManagedLifecycleHook, getWindowsManagedLifecycleHook } from '../claude/hook-settings' -import { codebuddyHookService, CODEBUDDY_HOOK_EVENTS } from './hook-service' - -beforeAll(() => { - sandbox.home = mkdtempSync(join(tmpdir(), 'orca-codebuddy-test-')) - mkdirSync(join(sandbox.home, '.codebuddy')) -}) -afterAll(() => rmSync(sandbox.home, { recursive: true, force: true })) - -describe('CodeBuddy managed hooks on Windows', () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform')! - afterEach(() => Object.defineProperty(process, 'platform', platform)) - - // CodeBuddy spawns `shell: 'powershell'` hooks as bare `pwsh`, which stock Windows lacks (#27182). - it('registers a shell-free command and replaces the legacy pwsh registration', () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const path = join(sandbox.home, '.codebuddy', 'settings.json') - const userHook = { type: 'command', command: 'echo user-hook' } - const scriptPath = join(sandbox.home, '.orca', 'agent-hooks', 'codebuddy-hook.cmd') - const legacyHook = getManagedLifecycleHook(scriptPath, { - configDirName: '.codebuddy', - scriptBaseName: 'codebuddy-hook', - usesWindowsCompatLauncher: true, - windowsHookShell: 'powershell' - }) - expect(legacyHook.shell).toBe('powershell') - writeFileSync( - path, - JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [legacyHook, userHook] }] } }) - ) - expect(codebuddyHookService.getStatus().state).not.toBe('installed') - - expect(codebuddyHookService.install().state).toBe('installed') - const installed = JSON.parse(readFileSync(path, 'utf8')) - const expected = getWindowsManagedLifecycleHook(scriptPath) - for (const event of CODEBUDDY_HOOK_EVENTS) { - const hooks = installed.hooks[event].flatMap((d: { hooks: unknown[] }) => d.hooks) - expect(hooks).toContainEqual(expected) - for (const hook of hooks) { - expect(hook).not.toHaveProperty('shell') - } - } - expect(JSON.stringify(installed)).toContain('echo user-hook') - expect(JSON.stringify(installed)).not.toContain(legacyHook.command) - }) -}) diff --git a/src/main/codebuddy/hook-service.ts b/src/main/codebuddy/hook-service.ts index 628d376ffbd..b12ed619f6b 100644 --- a/src/main/codebuddy/hook-service.ts +++ b/src/main/codebuddy/hook-service.ts @@ -1,4 +1,4 @@ -import type { ClaudeManagedHookPlan } from '../claude/claude-managed-hook-events' +import type { ClaudeManagedHookPlan } from '../claude/hooks/claude-managed-hook-events' import { ClaudeHookService } from '../claude/hook-service' export const CODEBUDDY_HOOK_EVENTS = [ diff --git a/src/main/codex-accounts/codex-account-registration.ts b/src/main/codex-accounts/account-management/codex-account-registration.ts similarity index 92% rename from src/main/codex-accounts/codex-account-registration.ts rename to src/main/codex-accounts/account-management/codex-account-registration.ts index a4ef5d1d240..32e0f7b7e29 100644 --- a/src/main/codex-accounts/codex-account-registration.ts +++ b/src/main/codex-accounts/account-management/codex-account-registration.ts @@ -1,35 +1,35 @@ import { randomUUID } from 'node:crypto' import { copyFileSync, mkdirSync, rmSync } from 'node:fs' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' import { WINDOWS_RM_MAX_RETRIES, WINDOWS_RM_RETRY_DELAY_MS -} from '../../shared/windows-transient-lock-removal' +} from '../../../shared/windows-transient-lock-removal' import type { CodexManagedAccount, CodexRateLimitAccountsState -} from '../../shared/managed-account-types' -import type { Store } from '../persistence/loading-store/store' -import type { RateLimitService } from '../rate-limits/service/rate-limit-service' -import type { CodexRuntimeHomeService } from './runtime-home-service' -import type { ResolvedCodexIdentity } from './codex-account-identity' +} from '../../../shared/managed-account-types' +import type { Store } from '../../persistence/loading-store/store' +import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' +import type { CodexRuntimeHomeService } from '../runtime-home-service' +import type { CodexAuthIdentity as ResolvedCodexIdentity } from '../credentials/codex-auth-identity' import type { CodexAccountAddTarget, CodexAccountReauthenticateOptions, ManagedCodexHomeLocation } from './codex-account-service-types' import type { CodexAccountSelection } from './codex-account-selection' -import type { CodexConfigMirror } from './codex-config-mirror' -import type { CodexManagedHomeLifecycle } from './codex-managed-home-lifecycle' -import type { CodexManagedHomePath } from './codex-managed-home-path' +import type { CodexConfigMirror } from '../managed-homes/codex-config-mirror' +import type { CodexManagedHomeLifecycle } from '../managed-homes/codex-managed-home-lifecycle' +import type { CodexManagedHomePath } from '../managed-homes/codex-managed-home-path' import { getCodexSelectionTargetForAccount, getSelectedCodexAccountIdForTarget, normalizeCodexRuntimeSelection, - setSelectedCodexAccountIdForTarget, - type CodexAccountSelectionTarget + setSelectedCodexAccountIdForTarget } from './runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' type CodexAccountRegistrationDependencies = { store: Store diff --git a/src/main/codex-accounts/codex-account-selection.ts b/src/main/codex-accounts/account-management/codex-account-selection.ts similarity index 92% rename from src/main/codex-accounts/codex-account-selection.ts rename to src/main/codex-accounts/account-management/codex-account-selection.ts index 232e9990a48..0cea136a5c9 100644 --- a/src/main/codex-accounts/codex-account-selection.ts +++ b/src/main/codex-accounts/account-management/codex-account-selection.ts @@ -2,26 +2,28 @@ import type { CodexManagedAccount, CodexRateLimitAccountsState, CodexSystemDefaultIdentity -} from '../../shared/managed-account-types' -import { parseWslUncPath } from '../../shared/wsl-paths' -import type { Store } from '../persistence/loading-store/store' -import type { RateLimitService } from '../rate-limits/service/rate-limit-service' -import type { CodexRuntimeHomeService } from './runtime-home-service' -import type { CodexConfigMirror } from './codex-config-mirror' -import type { ResolvedCodexIdentity } from './codex-account-identity' -import { codexAuthIdentityContradictsAccount } from './codex-auth-identity' +} from '../../../shared/managed-account-types' +import { parseWslUncPath } from '../../../shared/wsl-paths' +import type { Store } from '../../persistence/loading-store/store' +import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' +import type { CodexRuntimeHomeService } from '../runtime-home-service' +import type { CodexConfigMirror } from '../managed-homes/codex-config-mirror' +import type { CodexAuthIdentity as ResolvedCodexIdentity } from '../credentials/codex-auth-identity' +import { codexAuthIdentityContradictsAccount } from '../credentials/codex-auth-identity' import type { CodexAccountServiceLifecycle } from './codex-account-service-types' import { toCodexManagedAccountSummary } from './codex-account-service-types' import { getCodexSelectionTargetForAccount, getSelectedCodexAccountIdForTarget, - normalizeCodexAccountSelectionTarget, normalizeCodexRuntimeSelection, pruneInvalidCodexRuntimeSelection, removeCodexAccountIdFromSelection, - setSelectedCodexAccountIdForTarget, - type CodexAccountSelectionTarget + setSelectedCodexAccountIdForTarget } from './runtime-selection' +import { + normalizeCodexAccountSelectionTarget, + type CodexAccountSelectionTarget +} from '../../../shared/codex-selection-lane' type CodexAccountSelectionDependencies = { store: Store diff --git a/src/main/codex-accounts/codex-account-service-types.ts b/src/main/codex-accounts/account-management/codex-account-service-types.ts similarity index 92% rename from src/main/codex-accounts/codex-account-service-types.ts rename to src/main/codex-accounts/account-management/codex-account-service-types.ts index c77bdbdb3de..f84e2502db1 100644 --- a/src/main/codex-accounts/codex-account-service-types.ts +++ b/src/main/codex-accounts/account-management/codex-account-service-types.ts @@ -2,9 +2,9 @@ import type { CodexManagedAccount, CodexRateLimitAccountsState, CodexManagedAccountSummary -} from '../../shared/managed-account-types' -import type { CodexResetCreditExpectedScope } from '../../shared/codex-reset-credit-scope' -import type { CodexRateLimitResetOutcome, RateLimitState } from '../../shared/rate-limit-types' +} from '../../../shared/managed-account-types' +import type { CodexResetCreditExpectedScope } from '../../../shared/codex-reset-credit-scope' +import type { CodexRateLimitResetOutcome, RateLimitState } from '../../../shared/rate-limit-types' export type CodexAccountAddTarget = { runtime?: 'host' | 'wsl' diff --git a/src/main/codex-accounts/codex-account-settings-fixture.ts b/src/main/codex-accounts/account-management/codex-account-settings-fixture.ts similarity index 89% rename from src/main/codex-accounts/codex-account-settings-fixture.ts rename to src/main/codex-accounts/account-management/codex-account-settings-fixture.ts index 62ba1e22f4f..5df86ac326e 100644 --- a/src/main/codex-accounts/codex-account-settings-fixture.ts +++ b/src/main/codex-accounts/account-management/codex-account-settings-fixture.ts @@ -1,5 +1,5 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import { createGlobalSettingsFixture } from '../../shared/global-settings-test-fixture' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { createGlobalSettingsFixture } from '../../../shared/global-settings-test-fixture' // Preserve historical account-test defaults independently of current app defaults. export function createCodexAccountSettings( diff --git a/src/main/codex-accounts/runtime-selection.ts b/src/main/codex-accounts/account-management/runtime-selection.ts similarity index 89% rename from src/main/codex-accounts/runtime-selection.ts rename to src/main/codex-accounts/account-management/runtime-selection.ts index 1bbfeda2ca0..e0774fc3899 100644 --- a/src/main/codex-accounts/runtime-selection.ts +++ b/src/main/codex-accounts/account-management/runtime-selection.ts @@ -1,24 +1,14 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' import type { CodexManagedAccount, CodexManagedAccountRuntimeSelection -} from '../../shared/managed-account-types' +} from '../../../shared/managed-account-types' // Share lane keys so renderer switch guards agree with launch routing. import { getWslSelectionKey, normalizeCodexAccountSelectionTarget, type CodexAccountSelectionTarget -} from '../../shared/codex-selection-lane' - -export { - getCodexSelectionLaneKey, - getWslSelectionKey, - normalizeCodexAccountSelectionTarget -} from '../../shared/codex-selection-lane' -export type { - CodexAccountSelectionTarget, - NormalizedCodexAccountSelectionTarget -} from '../../shared/codex-selection-lane' +} from '../../../shared/codex-selection-lane' export function normalizeCodexRuntimeSelection( settings: Partial< diff --git a/src/main/codex-accounts/service-test-harness.ts b/src/main/codex-accounts/account-management/service-test-harness.ts similarity index 93% rename from src/main/codex-accounts/service-test-harness.ts rename to src/main/codex-accounts/account-management/service-test-harness.ts index 551b103d322..3b7f99bcafa 100644 --- a/src/main/codex-accounts/service-test-harness.ts +++ b/src/main/codex-accounts/account-management/service-test-harness.ts @@ -2,10 +2,10 @@ import { afterEach, beforeEach, vi, type Mock } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { GlobalSettings } from '../../shared/global-settings-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' import { createCodexAccountSettings } from './codex-account-settings-fixture' -import type { CodexResetCreditAttemptLedger } from '../../shared/codex-reset-credit-attempt-ledger' -import type { CodexRateLimitHomeResolution } from './runtime-home-service' +import type { CodexResetCreditAttemptLedger } from '../../../shared/codex-reset-credit-attempt-ledger' +import type { CodexRateLimitHomeResolution } from '../runtime-home/runtime-home-service-types' export const testState = { userDataDir: '', diff --git a/src/main/codex-accounts/service-wsl-test-results.ts b/src/main/codex-accounts/account-management/service-wsl-test-results.ts similarity index 93% rename from src/main/codex-accounts/service-wsl-test-results.ts rename to src/main/codex-accounts/account-management/service-wsl-test-results.ts index cc1443fabf5..70fa1d1a222 100644 --- a/src/main/codex-accounts/service-wsl-test-results.ts +++ b/src/main/codex-accounts/account-management/service-wsl-test-results.ts @@ -1,5 +1,5 @@ import { expect, vi } from 'vitest' -import type { WslResult, WslSpec } from '../wsl/execution/wsl-runner' +import type { WslResult, WslSpec } from '../../wsl/execution/wsl-runner' export function wslOk(stdout = ''): WslResult { return { environmentResolved: true, code: 0, stdout, stderr: '', timedOut: false } diff --git a/src/main/codex-accounts/sta-4734-login-rollback-deletes-authenticated-home.test.ts b/src/main/codex-accounts/account-management/sta-4734-login-rollback-deletes-authenticated-home.test.ts similarity index 78% rename from src/main/codex-accounts/sta-4734-login-rollback-deletes-authenticated-home.test.ts rename to src/main/codex-accounts/account-management/sta-4734-login-rollback-deletes-authenticated-home.test.ts index a3f5ba92089..5412436ffbe 100644 --- a/src/main/codex-accounts/sta-4734-login-rollback-deletes-authenticated-home.test.ts +++ b/src/main/codex-accounts/account-management/sta-4734-login-rollback-deletes-authenticated-home.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { EventEmitter } from 'node:events' import type * as NodeFs from 'node:fs' -import type * as HostCodexManagedHomeOwnership from './host-codex-managed-home-ownership' +import type * as HostCodexManagedHomeOwnership from '../managed-homes/host-codex-managed-home-ownership' import { PassThrough } from 'node:stream' import { join } from 'node:path' import { @@ -87,7 +87,7 @@ const { async function importTemporarilyUnavailableError(): Promise< typeof HostCodexManagedHomeOwnership.ManagedCodexHomeTemporarilyUnavailableError > { - return (await import('./host-codex-managed-home-ownership')) + return (await import('../managed-homes/host-codex-managed-home-ownership')) .ManagedCodexHomeTemporarilyUnavailableError } @@ -143,11 +143,11 @@ describe('STA-4734 a locked auth.json must not delete a just-authenticated home' } ) vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) + vi.doMock('../../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) try { const store = createStore(createSettings()) - const { CodexAccountService } = await import('./service') + const { CodexAccountService } = await import('../service') const service = new CodexAccountService( store as never, createRateLimits() as never, @@ -166,35 +166,7 @@ describe('STA-4734 a locked auth.json must not delete a just-authenticated home' } finally { authFaults.reset() vi.doUnmock('node:child_process') - vi.doUnmock('../codex-cli/command') - } - }) - - it('still deletes the managed home when the login genuinely fails', async () => { - vi.resetModules() - authFaults.reset() - - const spawnMock = vi.fn(() => { - const child = makeLoginChild() - queueMicrotask(() => child.emit('close', 1)) - return child - }) - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - - try { - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - createStore(createSettings()) as never, - createRateLimits() as never, - createRuntimeHome() as never - ) - - await expect(service.addAccount()).rejects.toThrow(/Codex login exited with code 1/) - expect(listManagedHomes().filter((home) => realExistsSync(home))).toHaveLength(0) - } finally { - vi.doUnmock('node:child_process') - vi.doUnmock('../codex-cli/command') + vi.doUnmock('../../codex-cli/command') } }) }) diff --git a/src/main/codex-accounts/codex-login-auth-url.test.ts b/src/main/codex-accounts/codex-login-auth-url.test.ts deleted file mode 100644 index d2bb24e6357..00000000000 --- a/src/main/codex-accounts/codex-login-auth-url.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseCodexLoginAuthUrl } from './codex-login-auth-url' - -const AUTH_URL = 'https://auth.openai.com/oauth/authorize?client_id=orca&state=abc123' - -describe('parseCodexLoginAuthUrl', () => { - it('waits for a chunk boundary rather than publishing a truncated link', () => { - const truncated = `If your browser did not open, navigate to this URL to authenticate:\n\n${AUTH_URL.slice(0, 40)}` - expect(parseCodexLoginAuthUrl(truncated)).toBe(null) - expect(parseCodexLoginAuthUrl(`${truncated}${AUTH_URL.slice(40)}\n`)).toBe(AUTH_URL) - }) - - it('offers no link at all rather than an unrelated one when the notice is missing', () => { - expect( - parseCodexLoginAuthUrl('A new version of codex is available: https://openai.com/codex\n') - ).toBe(null) - }) -}) diff --git a/src/main/codex-accounts/codex-login-session-wsl-open.test.ts b/src/main/codex-accounts/codex-login-session-wsl-open.test.ts deleted file mode 100644 index e49bcd72d10..00000000000 --- a/src/main/codex-accounts/codex-login-session-wsl-open.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { EventEmitter } from 'node:events' -import { rmSync } from 'node:fs' -import { PassThrough } from 'node:stream' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('../wsl/execution/wsl-runner', () => ({ - runWslProcess: vi.fn(async () => ({ - environmentResolved: true, - code: 0, - stdout: '', - stderr: '', - timedOut: false - })) -})) -vi.mock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - -import { runCodexLoginSession, type CodexLoginSpawnRequest } from './codex-login-session' - -const AUTH_URL = 'https://auth.openai.com/oauth/authorize?client_id=orca&state=abc' -const PRINTED = `If your browser did not open, navigate to this URL to authenticate:\n\n${AUTH_URL}\n` -const WSL_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\alice\\managed-home' -type FakeLogin = EventEmitter & { stdout: PassThrough; stderr: PassThrough } -const roots: string[] = [] -afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))) - -function loginThatPrints( - text: string, - stream: 'stdout' | 'stderr' | ((child: FakeLogin) => void) = 'stdout' -) { - const requests: CodexLoginSpawnRequest[] = [] - const spawn = vi.fn((request: CodexLoginSpawnRequest) => { - requests.push(request) - const child = Object.assign(new EventEmitter(), { - stdout: new PassThrough(), - stderr: new PassThrough(), - exitCode: null, - signalCode: null, - kill: () => true - }) - queueMicrotask(() => { - if (typeof stream === 'function') { - stream(child) - } else { - child[stream].write(text) - } - setTimeout(() => child.emit('close', 0), 10) - }) - return child - }) - return { spawn, requests } -} - -function run( - home: string, - login: ReturnType, - openWslAuthUrl?: (url: string) => void -) { - const onAuthUrl = vi.fn() - const done = runCodexLoginSession(home, { - wslCommand: 'wsl.exe', - spawn: login.spawn, - killProcessTree: vi.fn(), - setCancel: vi.fn(), - onAuthUrl, - openWslAuthUrl - }) - return { done, onAuthUrl } -} - -describe('runCodexLoginSession sign-in link opening', () => { - it('reads a link split across stderr chunks despite stdout output between them', async () => { - const half = PRINTED.length - 20 - const login = loginThatPrints('', (child) => { - child.stderr.write(PRINTED.slice(0, half)) - child.stdout.write('unrelated progress\n') - child.stderr.write(PRINTED.slice(half)) - }) - const open = vi.fn() - const { done, onAuthUrl } = run(WSL_HOME, login, open) - await done - expect(onAuthUrl).toHaveBeenCalledExactlyOnceWith(AUTH_URL) - expect(open).toHaveBeenCalledExactlyOnceWith(AUTH_URL) - }) -}) diff --git a/src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts b/src/main/codex-accounts/credentials/codex-account-identity-api-key-guard.test.ts similarity index 100% rename from src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts rename to src/main/codex-accounts/credentials/codex-account-identity-api-key-guard.test.ts diff --git a/src/main/codex-accounts/codex-account-identity.ts b/src/main/codex-accounts/credentials/codex-account-identity.ts similarity index 92% rename from src/main/codex-accounts/codex-account-identity.ts rename to src/main/codex-accounts/credentials/codex-account-identity.ts index ccf7bab9a29..5f6169ce693 100644 --- a/src/main/codex-accounts/codex-account-identity.ts +++ b/src/main/codex-accounts/credentials/codex-account-identity.ts @@ -1,12 +1,13 @@ import { readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import type { CodexSystemDefaultIdentity } from '../../shared/managed-account-types' -import { readCodexAuthIdentity, type CodexAuthIdentity } from './codex-auth-identity' -import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' - -export type ResolvedCodexIdentity = CodexAuthIdentity +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import type { CodexSystemDefaultIdentity } from '../../../shared/managed-account-types' +import { + readCodexAuthIdentity, + type CodexAuthIdentity as ResolvedCodexIdentity +} from './codex-auth-identity' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../managed-homes/host-codex-managed-home-ownership' const PROVIDERS_WITHOUT_OPENAI_AUTH = new Set([ 'amazon-bedrock', diff --git a/src/main/codex-accounts/codex-auth-identity.ts b/src/main/codex-accounts/credentials/codex-auth-identity.ts similarity index 99% rename from src/main/codex-accounts/codex-auth-identity.ts rename to src/main/codex-accounts/credentials/codex-auth-identity.ts index 1b2af49544d..41fc7132f0d 100644 --- a/src/main/codex-accounts/codex-auth-identity.ts +++ b/src/main/codex-accounts/credentials/codex-auth-identity.ts @@ -1,4 +1,4 @@ -import type { CodexManagedAccount } from '../../shared/managed-account-types' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' export type CodexAuthIdentity = { email: string | null diff --git a/src/main/codex-accounts/codex-credential-absence-grace.test.ts b/src/main/codex-accounts/credentials/codex-credential-absence-grace.test.ts similarity index 100% rename from src/main/codex-accounts/codex-credential-absence-grace.test.ts rename to src/main/codex-accounts/credentials/codex-credential-absence-grace.test.ts diff --git a/src/main/codex-accounts/codex-credential-absence-grace.ts b/src/main/codex-accounts/credentials/codex-credential-absence-grace.ts similarity index 95% rename from src/main/codex-accounts/codex-credential-absence-grace.ts rename to src/main/codex-accounts/credentials/codex-credential-absence-grace.ts index 47d206fba94..c7ea4e5dd6c 100644 --- a/src/main/codex-accounts/codex-credential-absence-grace.ts +++ b/src/main/codex-accounts/credentials/codex-credential-absence-grace.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs' import { dirname } from 'node:path' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { readStoredCodexCredentialState, type StoredCodexCredentialState diff --git a/src/main/codex-accounts/managed-codex-auth-readiness.test.ts b/src/main/codex-accounts/credentials/managed-codex-auth-readiness.test.ts similarity index 93% rename from src/main/codex-accounts/managed-codex-auth-readiness.test.ts rename to src/main/codex-accounts/credentials/managed-codex-auth-readiness.test.ts index 41a7eea7541..3b2de38b2d5 100644 --- a/src/main/codex-accounts/managed-codex-auth-readiness.test.ts +++ b/src/main/codex-accounts/credentials/managed-codex-auth-readiness.test.ts @@ -3,8 +3,8 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { CodexManagedAccount } from '../../shared/managed-account-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' import { readStoredCodexCredentialState, waitForManagedCodexAuthReady diff --git a/src/main/codex-accounts/managed-codex-auth-readiness.ts b/src/main/codex-accounts/credentials/managed-codex-auth-readiness.ts similarity index 96% rename from src/main/codex-accounts/managed-codex-auth-readiness.ts rename to src/main/codex-accounts/credentials/managed-codex-auth-readiness.ts index 0b372f03e76..faffc474c0f 100644 --- a/src/main/codex-accounts/managed-codex-auth-readiness.ts +++ b/src/main/codex-accounts/credentials/managed-codex-auth-readiness.ts @@ -1,9 +1,9 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { CodexAccountSelectionTarget } from './runtime-selection' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' const AUTH_READY_TIMEOUT_MS = 1_500 const AUTH_READY_RETRY_MS = 25 diff --git a/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-apply-script.test.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-apply-script.test.ts new file mode 100644 index 00000000000..25882eb0e78 --- /dev/null +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-apply-script.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import './legacy-wsl-runtime-auth-drain' +import { + RETIRED_SESSION, + SOURCE_AUTH, + isWindows +} from './legacy-wsl-runtime-auth-drain-script-fixtures' +import { runApplyScript } from './legacy-wsl-runtime-auth-drain-script-harness' + +describe.skipIf(isWindows)('legacy WSL auth drain apply script', () => { + it('rolls back a published session link after abrupt interruption', () => { + const outcome = runApplyScript({ + deleteSource: true, + killAfterSessionLink: true, + sourceSession: RETIRED_SESSION + }) + + expect(outcome.signal).toBe('SIGKILL') + expect(outcome.legacyAuth).toBe(SOURCE_AUTH) + expect(outcome.targetSession).toBeNull() + expect(outcome.markerExists).toBe(false) + }) + + it('finishes a durable session-link commit after abrupt interruption', () => { + const outcome = runApplyScript({ + deleteSource: true, + killDuringSessionCommit: true, + sourceSession: RETIRED_SESSION + }) + + expect(outcome.signal).toBe('SIGKILL') + expect(outcome.legacyAuth).toBe(SOURCE_AUTH) + expect(outcome.targetSession).toBe(RETIRED_SESSION) + expect(outcome.sessionCommitMarkerExists).toBe(false) + expect(outcome.markerExists).toBe(false) + }) +}) diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-exit-codes.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-exit-codes.ts similarity index 100% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-exit-codes.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-exit-codes.ts diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-interruption-source.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-interruption-source.ts similarity index 100% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-interruption-source.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-interruption-source.ts diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-rollback-script.test.ts similarity index 96% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-rollback-script.test.ts index 615c95cd599..52551cb9bd5 100644 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-rollback-script.test.ts @@ -12,7 +12,11 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { _internals } from './legacy-wsl-runtime-auth-drain' +import './legacy-wsl-runtime-auth-drain' +import { + INSPECT_LEGACY_AUTH_SCRIPT as inspectLegacyAuthScript, + APPLY_LEGACY_AUTH_SCRIPT as applyLegacyAuthScript +} from './legacy-wsl-runtime-auth-drain-scripts' const SOURCE_AUTH = '{"tokens":{"expires_at":2000}}\n' const TARGET_AUTH = '{"tokens":{"expires_at":1000}}\n' @@ -38,7 +42,7 @@ function runInspect(root: string, legacyHome: string, markerPath: string): numbe '/bin/sh', [ '-c', - _internals.inspectLegacyAuthScript, + inspectLegacyAuthScript, 'sh', legacyHome, join(root, 'absent-active-home'), @@ -87,7 +91,7 @@ describe.skipIf(process.platform === 'win32')('legacy WSL auth drain rollback re '/bin/sh', [ '-c', - _internals.applyLegacyAuthScript, + applyLegacyAuthScript, 'sh', legacyHome, join(root, 'absent-active-home'), diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-fixtures.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-fixtures.ts similarity index 84% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-fixtures.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-fixtures.ts index 05f65a48b7b..719d71992b4 100644 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-fixtures.ts +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-fixtures.ts @@ -8,8 +8,6 @@ export const NEWER_AUTH = '{"tokens":{"expires_at":3000}}\n' export const INTRUDER_AUTH = '{"tokens":{"expires_at":9000}}\n' export const TORN_AUTH = '{"tokens":{"exp' -export const SOURCE_CREDENTIALS = '{"server":{"access_token":"source"}}\n' -export const TORN_CREDENTIALS = '{"server":' export const RETIRED_SESSION = '{"session":"retired"}\n' export const RETIRED_SESSION_SEGMENTS = ['sessions', '2026', '08', '26', 'retired.jsonl'] diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-harness.ts similarity index 97% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-harness.ts index 3e4df3ad2c2..9bf16c8c265 100644 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-harness.ts @@ -29,7 +29,11 @@ import type { DrainApplyInterference, DrainApplyOutcome } from './legacy-wsl-runtime-auth-drain-script-run-types' -import { _internals } from './legacy-wsl-runtime-auth-drain' +import './legacy-wsl-runtime-auth-drain' +import { + APPLY_LEGACY_AUTH_SCRIPT as applyLegacyAuthScript, + INSPECT_LEGACY_AUTH_SCRIPT as inspectLegacyAuthScript +} from './legacy-wsl-runtime-auth-drain-scripts' export function runApplyScript(options: DrainApplyInterference = {}): DrainApplyOutcome { const root = mkdtempSync(join(tmpdir(), 'orca-drain-apply-')) @@ -150,7 +154,7 @@ process.exit(result.status ?? 1) '/bin/sh', [ '-c', - `ORCA_DRAIN_APPLY_PID=$$; export ORCA_DRAIN_APPLY_PID;\n${_internals.applyLegacyAuthScript}`, + `ORCA_DRAIN_APPLY_PID=$$; export ORCA_DRAIN_APPLY_PID;\n${applyLegacyAuthScript}`, 'sh', legacyHome, join(root, 'absent-active-home'), @@ -233,7 +237,7 @@ process.exit(result.status ?? 1) '/bin/sh', [ '-c', - _internals.inspectLegacyAuthScript, + inspectLegacyAuthScript, 'sh', legacyHome, join(root, 'absent-active-home'), diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-interference-shims.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-interference-shims.ts similarity index 100% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-interference-shims.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-interference-shims.ts diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-run-types.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-run-types.ts similarity index 100% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-run-types.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-script-run-types.ts diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-scripts.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-scripts.ts similarity index 98% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-scripts.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-scripts.ts index 6622aced9b3..36839f8cbd7 100644 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-scripts.ts +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-scripts.ts @@ -11,8 +11,7 @@ import { RETIRED_RECENT_SESSION_BRIDGE_COMMAND, ROLLBACK_SESSION_LINKS_FUNCTION } from './legacy-wsl-runtime-auth-drain-shell-commands' -export * from './legacy-wsl-runtime-auth-drain-exit-codes' -export { FINALIZE_ABSENT_AUTH_SCRIPT } from './legacy-wsl-runtime-auth-finalize-script' +import './legacy-wsl-runtime-auth-finalize-script' export const INSPECT_LEGACY_AUTH_SCRIPT = ` set -eu source_recovery_auth="$3.orca-drain-source" diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-shell-commands.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-shell-commands.ts similarity index 95% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain-shell-commands.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-shell-commands.ts index 259eb017464..ab6cec9c139 100644 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-shell-commands.ts +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-shell-commands.ts @@ -1,5 +1,5 @@ -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { WSL_CODEX_SESSION_BRIDGE_SCRIPT } from '../codex/history/bridges/wsl-codex-session-bridge-script' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { WSL_CODEX_SESSION_BRIDGE_SCRIPT } from '../../codex/history/bridges/wsl-codex-session-bridge-script' export const RETIRED_SESSION_BRIDGE_COMMAND = `bash -c ${quotePosixShell(WSL_CODEX_SESSION_BRIDGE_SCRIPT)} bash "$legacy_home/sessions" "$target_home/sessions" "$session_link_manifest" "$session_stage_root"` export const RETIRED_RECENT_SESSION_BRIDGE_COMMAND = `${RETIRED_SESSION_BRIDGE_COMMAND} recent "$session_scan_start" "$session_scan_day"` diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain.ts similarity index 90% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-drain.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain.ts index 0014897abd6..01c0d2d72e0 100644 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain.ts +++ b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain.ts @@ -1,19 +1,21 @@ import { createHash } from 'node:crypto' import { posix as pathPosix } from 'node:path' -import { wslCodexRuntimeHomeForGuestHome } from '../pty/shell-startup/codex-home-wsl-env' -import { WSL_SESSION_BRIDGE_TIMEOUT_MS } from '../codex/history/bridges/wsl-codex-session-bridge-script' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import { compareCodexAuthFreshness, codexAuthIsFresher } from './codex-auth-identity' +import { wslCodexRuntimeHomeForGuestHome } from '../../pty/shell-startup/codex-home-wsl-env' +import { WSL_SESSION_BRIDGE_TIMEOUT_MS } from '../../codex/history/bridges/wsl-codex-session-bridge-script' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import { compareCodexAuthFreshness, codexAuthIsFresher } from '../credentials/codex-auth-identity' import { APPLY_LEGACY_AUTH_SCRIPT, - FINALIZE_ABSENT_AUTH_SCRIPT, - INSPECT_LEGACY_AUTH_SCRIPT, + INSPECT_LEGACY_AUTH_SCRIPT +} from './legacy-wsl-runtime-auth-drain-scripts' +import { FINALIZE_ABSENT_AUTH_SCRIPT } from './legacy-wsl-runtime-auth-finalize-script' +import { LEGACY_HOME_ABSENT_EXIT, LEGACY_HOME_STILL_PRESENT_EXIT, MARKER_PRESENT_EXIT, SOURCE_AUTH_ABSENT_EXIT -} from './legacy-wsl-runtime-auth-drain-scripts' -import { decodeWslBase64Payload } from './wsl-codex-auth-batch-reader' +} from './legacy-wsl-runtime-auth-drain-exit-codes' +import { decodeWslBase64Payload } from '../runtime-home/wsl/wsl-codex-auth-batch-reader' const DRAIN_MARKER_NAME = 'direct-home-auth-drain-v1.json' @@ -279,18 +281,3 @@ function assertSuccessfulDrainStep( function sha256(contents: string): string { return createHash('sha256').update(contents).digest('hex') } - -export const _internals = { - applyLegacyAuthScript: APPLY_LEGACY_AUTH_SCRIPT, - finalizeAbsentAuthScript: FINALIZE_ABSENT_AUTH_SCRIPT, - inspectLegacyAuthScript: INSPECT_LEGACY_AUTH_SCRIPT, - resetDrainQueue: (): void => { - drainQueueByDistro.clear() - completedDistroKeys.clear() - pendingSessionBridgeRouteByDistro.clear() - }, - drainDistroStateCountsForTests: (): { completed: number; pendingRoutes: number } => ({ - completed: completedDistroKeys.size, - pendingRoutes: pendingSessionBridgeRouteByDistro.size - }) -} diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-finalize-script.ts b/src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-finalize-script.ts similarity index 100% rename from src/main/codex-accounts/legacy-wsl-runtime-auth-finalize-script.ts rename to src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-finalize-script.ts diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-apply-script.test.ts b/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-apply-script.test.ts deleted file mode 100644 index 7b81bf71741..00000000000 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-apply-script.test.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { _internals } from './legacy-wsl-runtime-auth-drain' -import { - NEWER_AUTH, - RETIRED_SESSION, - SOURCE_AUTH, - TARGET_AUTH, - isWindows -} from './legacy-wsl-runtime-auth-drain-script-fixtures' -import { runApplyScript } from './legacy-wsl-runtime-auth-drain-script-harness' -import { - runAbsentLegacyHomeScript, - runRecoveryScript -} from './legacy-wsl-runtime-auth-drain-recovery-script-harness' - -describe.skipIf(isWindows)('legacy WSL auth drain apply script', () => { - it('does not finalize while an authless legacy home still holds sessions', () => { - const outcome = runAbsentLegacyHomeScript({ - createLegacyHome: true, - script: _internals.finalizeAbsentAuthScript - }) - - expect(outcome.status).toBe(47) - expect(outcome.markerExists).toBe(false) - }) - - it('refuses torn bytes and leaves the account home intact', () => { - // Hash 1 checks the source before a rotation can change the bytes copied for promotion. - const outcome = runApplyScript({ rewriteAfterHashCall: 1 }) - expect(outcome.status).toBe(42) - expect(outcome.targetAuth).toBe(TARGET_AUTH) - }) - - it('refuses a symlinked live source before the destructive path can retire it', () => { - const result = runApplyScript({ deleteSource: true, sourceAuthSymlink: true }) - - expect(result.status).toBe(46) - expect(result.legacyAuth).toBe(SOURCE_AUTH) - expect(result.markerExists).toBe(false) - expect(result.targetAuth).toBe(TARGET_AUTH) - }) - - it('does not overwrite auth changed after the destination hash check', () => { - const outcome = runApplyScript({ - rewriteBytes: NEWER_AUTH, - rewriteAfterHashCall: 4, - rewriteTarget: 'target-auth' - }) - expect(outcome.status).toBe(39) - expect(outcome.targetAuth).toBe(NEWER_AUTH) - }) - - it('recovers the source and destination mode after abrupt interruption', () => { - const outcome = runApplyScript({ deleteSource: true, killAfterSourceRemoval: true }) - - expect(outcome.signal).toBe('SIGKILL') - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.targetAuth).toBe(SOURCE_AUTH) - expect(outcome.targetMode).toBe(0o600) - expect(outcome.markerExists).toBe(false) - }) - - it('retains verified destination recovery when the target inode changed after a crash', () => { - const outcome = runApplyScript({ - deleteSource: true, - killAfterSourceRemoval: true, - replaceTargetBeforeRecovery: true - }) - - expect(outcome.signal).toBe('SIGKILL') - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.targetAuth).toBe(NEWER_AUTH) - expect(outcome.destinationRecoveryAuth).toBe(SOURCE_AUTH) - expect(outcome.destinationRecoveryPathExists).toBe(true) - expect(outcome.markerExists).toBe(false) - }) - - it('rolls back retained-pane links when destination ownership changes during the bridge', () => { - const outcome = runApplyScript({ - deleteSource: false, - promoteAuth: false, - rewriteBytes: NEWER_AUTH, - rewriteTargetAfterSessionLink: true, - sourceSession: RETIRED_SESSION - }) - - expect(outcome.status).toBe(45) - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.targetAuth).toBe(NEWER_AUTH) - expect(outcome.targetSession).toBeNull() - expect(outcome.markerExists).toBe(false) - }) - - it('rolls back when an atomic rename replaces the destination during the bridge', () => { - const outcome = runApplyScript({ - deleteSource: true, - promoteAuth: false, - replaceTargetAfterSessionLink: true, - rewriteBytes: NEWER_AUTH, - sourceSession: RETIRED_SESSION - }) - - expect(outcome.status).toBe(45) - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.targetAuth).toBe(NEWER_AUTH) - expect(outcome.targetSession).toBeNull() - expect(outcome.markerExists).toBe(false) - }) - - it('restores the verified recovery when an open writer mutates the quarantined inode', () => { - const outcome = runApplyScript({ - deleteSource: true, - promoteAuth: false, - rewriteBytes: NEWER_AUTH, - rewriteQuarantineAfterSessionLink: true, - sourceSession: RETIRED_SESSION - }) - - expect(outcome.status).toBe(40) - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.sourceRecoveryAuth).toBeNull() - expect(outcome.sourceQuarantineAuth).toBe(NEWER_AUTH) - expect(outcome.targetSession).toBeNull() - expect(outcome.markerExists).toBe(false) - }) - - it('rolls back a published session link after abrupt interruption', () => { - const outcome = runApplyScript({ - deleteSource: true, - killAfterSessionLink: true, - sourceSession: RETIRED_SESSION - }) - - expect(outcome.signal).toBe('SIGKILL') - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.targetSession).toBeNull() - expect(outcome.markerExists).toBe(false) - }) - - it('finishes a durable session-link commit after abrupt interruption', () => { - const outcome = runApplyScript({ - deleteSource: true, - killDuringSessionCommit: true, - sourceSession: RETIRED_SESSION - }) - - expect(outcome.signal).toBe('SIGKILL') - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.targetSession).toBe(RETIRED_SESSION) - expect(outcome.sessionCommitMarkerExists).toBe(false) - expect(outcome.markerExists).toBe(false) - }) - - it('fails closed when destination recovery has no target-path metadata', () => { - const outcome = runRecoveryScript({ - markerPresent: false, - pathMetadata: false, - script: _internals.inspectLegacyAuthScript - }) - - expect(outcome.status).toBe(46) - expect(outcome.destinationRecoveryExists).toBe(true) - expect(outcome.destinationRecoveryPathExists).toBe(false) - }) - - it('refuses to retire the source when the destination is atomically replaced after the inode pin', () => { - // A pinned inode's matching hash cannot detect path replacement; -ef must guard source retirement. - const outcome = runApplyScript({ replaceTargetOnHashOf: '.orca-drain-destination-' }) - - expect(outcome.status).not.toBe(0) - expect(outcome.legacyAuth).toBe(SOURCE_AUTH) - expect(outcome.markerExists).toBe(false) - }) -}) diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-interruption-source.test.ts b/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-interruption-source.test.ts deleted file mode 100644 index 52e666928dd..00000000000 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-interruption-source.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { runInNewContext } from 'node:vm' -import { describe, expect, it, vi } from 'vitest' -import { DRAIN_APPLY_INTERRUPTION_JS } from './legacy-wsl-runtime-auth-drain-interruption-source' - -type CensusResult = { - status: number | null - stdout?: string - signal?: string - error?: Error -} - -function fixture(rows: CensusResult[], ownedPid = '100') { - const kill = vi.fn() - const census = vi.fn() - for (const row of rows) { - census.mockReturnValueOnce(row) - } - const context = { - process: { pid: 300, env: { ORCA_DRAIN_APPLY_PID: ownedPid }, kill }, - require: () => ({ spawnSync: census }) - } - return { - kill, - census, - interrupt: (depth = 2) => - runInNewContext(`${DRAIN_APPLY_INTERRUPTION_JS}\ninterruptDrainApply(${depth})`, context) - } -} - -describe('owned drain interruption', () => { - it.each([1, 2])('signals only the owned apply shell at ancestor depth %s', (depth) => { - const rows = depth === 1 ? ['100'] : ['200', '100'] - const target = fixture(rows.map((stdout) => ({ status: 0, stdout }))) - target.interrupt(depth) - expect(target.kill).toHaveBeenCalledExactlyOnceWith(100, 'SIGKILL') - expect(target.census.mock.calls.map(([, args]) => args)).toEqual( - depth === 1 - ? [['-o', 'ppid=', '-p', '300']] - : [ - ['-o', 'ppid=', '-p', '300'], - ['-o', 'ppid=', '-p', '200'] - ] - ) - }) - - it.each([ - { status: 0, stdout: '' }, - { status: 0, stdout: ' \n' }, - { status: 0, stdout: '0' }, - { status: 0, stdout: '-1' }, - { status: 0, stdout: '1' }, - { status: 0, stdout: '9007199254740992' }, - { status: 0, stdout: '100\n200' }, - { status: 1, stdout: '100' }, - { status: null, stdout: '100', signal: 'SIGTERM' }, - { status: 0, stdout: '100', error: new Error('census failed') }, - { status: 0 } - ])('refuses an invalid census without sending a signal: %j', (row) => { - const target = fixture([{ status: 0, stdout: '200' }, row]) - expect(() => target.interrupt()).toThrow() - expect(target.kill).not.toHaveBeenCalled() - }) - - it('refuses a valid ancestor that belongs to another process', () => { - const target = fixture([ - { status: 0, stdout: '200' }, - { status: 0, stdout: '99' } - ]) - expect(() => target.interrupt()).toThrow('Apply ancestor is not owned') - expect(target.kill).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts b/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts deleted file mode 100644 index 9840b285ac5..00000000000 --- a/src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { - linkSync, - mkdirSync, - mkdtempSync, - readFileSync, - writeFileSync, - existsSync, - statSync, - rmSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { - RETIRED_SESSION, - RETIRED_SESSION_SEGMENTS, - SOURCE_AUTH, - TARGET_AUTH -} from './legacy-wsl-runtime-auth-drain-script-fixtures' - -export function runRecoveryScript(options: { - destinationRecovery?: boolean - markerPresent: boolean - pathMetadata?: boolean - script: string -}): { - destinationMode: number - destinationRecoveryExists: boolean - destinationRecoveryPathExists: boolean - markerExists: boolean - sourceAuth: string | null - sourceRecoveryExists: boolean - status: number -} { - const root = mkdtempSync(join(tmpdir(), 'orca-drain-recovery-')) - try { - const legacyHome = join(root, 'legacy') - const targetHome = join(root, 'account') - mkdirSync(legacyHome) - mkdirSync(targetHome) - const markerPath = join(root, 'drain-marker.json') - const sourceRecoveryPath = `${markerPath}.orca-drain-source` - const destinationRecoveryPath = `${markerPath}.orca-drain-destination` - const destinationRecoveryTargetPath = `${markerPath}.orca-drain-destination-path` - const sourceAuthPath = join(legacyHome, 'auth.json') - const destinationAuthPath = join(targetHome, 'auth.json') - writeFileSync(sourceRecoveryPath, SOURCE_AUTH, { mode: 0o400 }) - writeFileSync(destinationAuthPath, TARGET_AUTH, { mode: 0o400 }) - if (options.destinationRecovery !== false) { - linkSync(destinationAuthPath, destinationRecoveryPath) - } - if (options.pathMetadata !== false) { - writeFileSync(destinationRecoveryTargetPath, `${destinationAuthPath}\0`, { mode: 0o600 }) - } - if (options.markerPresent) { - writeFileSync(markerPath, '{"completed":true}\n') - } - let status = 0 - try { - execFileSync( - '/bin/sh', - ['-c', options.script, 'sh', legacyHome, join(root, 'absent-active-home'), markerPath], - { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 20_000, windowsHide: true } - ) - } catch (error) { - status = (error as { status?: number }).status ?? -1 - } - return { - destinationMode: statSync(destinationAuthPath).mode & 0o777, - destinationRecoveryExists: existsSync(destinationRecoveryPath), - destinationRecoveryPathExists: existsSync(destinationRecoveryTargetPath), - markerExists: existsSync(markerPath), - sourceAuth: existsSync(sourceAuthPath) ? readFileSync(sourceAuthPath, 'utf8') : null, - sourceRecoveryExists: existsSync(sourceRecoveryPath), - status - } - } finally { - rmSync(root, { recursive: true, force: true }) - } -} - -export function runAbsentLegacyHomeScript(options: { - activeHomeOnly?: boolean - createLegacyHome: boolean - markerParentMissing?: boolean - script: string -}): { - markerExists: boolean - status: number -} { - const root = mkdtempSync(join(tmpdir(), 'orca-drain-absent-home-')) - try { - const legacyHome = join(root, 'legacy') - const activeHome = join(root, 'absent-active-home') - const markerPath = options.markerParentMissing - ? join(root, 'marker-parent', 'drain-marker.json') - : join(root, 'drain-marker.json') - if (options.createLegacyHome) { - const sessionHome = options.activeHomeOnly ? activeHome : legacyHome - mkdirSync(join(sessionHome, ...RETIRED_SESSION_SEGMENTS.slice(0, -1)), { recursive: true }) - writeFileSync(join(sessionHome, ...RETIRED_SESSION_SEGMENTS), RETIRED_SESSION) - } - let status = 0 - try { - execFileSync('/bin/sh', ['-c', options.script, 'sh', legacyHome, activeHome, markerPath], { - encoding: 'utf8', - windowsHide: true, - stdio: ['ignore', 'pipe', 'pipe'], - timeout: 20_000 - }) - } catch (error) { - status = (error as { status?: number }).status ?? -1 - } - return { markerExists: existsSync(markerPath), status } - } finally { - rmSync(root, { recursive: true, force: true }) - } -} diff --git a/src/main/codex-accounts/codex-device-auth-prompt.test.ts b/src/main/codex-accounts/login/codex-device-auth-prompt.test.ts similarity index 100% rename from src/main/codex-accounts/codex-device-auth-prompt.test.ts rename to src/main/codex-accounts/login/codex-device-auth-prompt.test.ts diff --git a/src/main/codex-accounts/codex-device-auth-prompt.ts b/src/main/codex-accounts/login/codex-device-auth-prompt.ts similarity index 92% rename from src/main/codex-accounts/codex-device-auth-prompt.ts rename to src/main/codex-accounts/login/codex-device-auth-prompt.ts index cb8cc41411d..9c35851d018 100644 --- a/src/main/codex-accounts/codex-device-auth-prompt.ts +++ b/src/main/codex-accounts/login/codex-device-auth-prompt.ts @@ -1,4 +1,4 @@ -import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' +import { stripAnsiEscapeSequences } from '../../../shared/ansi-escape-sequences' import { isCodexLoginAuthUrl } from './codex-login-auth-url' const CODE_MARKER = 'one-time code' diff --git a/src/main/codex-accounts/codex-login-auth-snapshot.ts b/src/main/codex-accounts/login/codex-login-auth-snapshot.ts similarity index 100% rename from src/main/codex-accounts/codex-login-auth-snapshot.ts rename to src/main/codex-accounts/login/codex-login-auth-snapshot.ts diff --git a/src/main/codex-accounts/login/codex-login-auth-url.test.ts b/src/main/codex-accounts/login/codex-login-auth-url.test.ts new file mode 100644 index 00000000000..c0bab37c023 --- /dev/null +++ b/src/main/codex-accounts/login/codex-login-auth-url.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from 'vitest' +import { parseCodexLoginAuthUrl } from './codex-login-auth-url' + +const AUTH_URL = 'https://auth.openai.com/oauth/authorize?client_id=orca&state=abc123' + +describe('parseCodexLoginAuthUrl', () => { + it('waits for a chunk boundary rather than publishing a truncated link', () => { + const truncated = `If your browser did not open, navigate to this URL to authenticate:\n\n${AUTH_URL.slice(0, 40)}` + expect(parseCodexLoginAuthUrl(truncated)).toBe(null) + expect(parseCodexLoginAuthUrl(`${truncated}${AUTH_URL.slice(40)}\n`)).toBe(AUTH_URL) + }) +}) diff --git a/src/main/codex-accounts/codex-login-auth-url.ts b/src/main/codex-accounts/login/codex-login-auth-url.ts similarity index 92% rename from src/main/codex-accounts/codex-login-auth-url.ts rename to src/main/codex-accounts/login/codex-login-auth-url.ts index 32a7bfe242e..1f5a8af81d4 100644 --- a/src/main/codex-accounts/codex-login-auth-url.ts +++ b/src/main/codex-accounts/login/codex-login-auth-url.ts @@ -1,4 +1,4 @@ -import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' +import { stripAnsiEscapeSequences } from '../../../shared/ansi-escape-sequences' const AUTH_URL_MARKER = 'navigate to this url to authenticate:' const CODEX_AUTH_HOST = 'auth.openai.com' diff --git a/src/main/codex-accounts/codex-login-session.ts b/src/main/codex-accounts/login/codex-login-session.ts similarity index 93% rename from src/main/codex-accounts/codex-login-session.ts rename to src/main/codex-accounts/login/codex-login-session.ts index 630305fe782..3c6b9b8876f 100644 --- a/src/main/codex-accounts/codex-login-session.ts +++ b/src/main/codex-accounts/login/codex-login-session.ts @@ -1,13 +1,13 @@ import { join } from 'node:path' -import type { WindowsHostInteractiveLoginSpawn } from '../../shared/windows-interactive-login-spawn' -import { buildWindowsHostInteractiveLoginSpawn } from '../../shared/windows-interactive-login-spawn' -import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { CODEX_LOGIN_CANCELLED_MESSAGE } from '../../shared/codex-auth-errors' -import { parseWslUncPath } from '../../shared/wsl-paths' -import { resolveCodexCommand } from '../codex-cli/command' -import { codexSpawnEnoent } from '../codex-cli/windows-only-agent-cli' -import { getSpawnArgsForWindows } from '../../shared/windows-batch-spawn' -import { runWslProcess } from '../wsl/execution/wsl-runner' +import type { WindowsHostInteractiveLoginSpawn } from '../../../shared/windows-interactive-login-spawn' +import { buildWindowsHostInteractiveLoginSpawn } from '../../../shared/windows-interactive-login-spawn' +import { withCliRuntimeOnPath } from '../../../shared/node-cli-command-resolution' +import { CODEX_LOGIN_CANCELLED_MESSAGE } from '../../../shared/codex-auth-errors' +import { parseWslUncPath } from '../../../shared/wsl-paths' +import { resolveCodexCommand } from '../../codex-cli/command' +import { codexSpawnEnoent } from '../../codex-cli/windows-only-agent-cli' +import { getSpawnArgsForWindows } from '../../../shared/windows-batch-spawn' +import { runWslProcess } from '../../wsl/execution/wsl-runner' import { parseCodexLoginAuthUrl } from './codex-login-auth-url' import { DEVICE_AUTH_TIMEOUT_MS, parseCodexDeviceAuthPrompt } from './codex-device-auth-prompt' import { loginAuthChanged, readLoginAuthSnapshot } from './codex-login-auth-snapshot' @@ -15,7 +15,7 @@ import { buildWslCodexAvailabilityScript, buildWslCodexLoginArgs, WSL_CODEX_AVAILABILITY_TIMEOUT_MS -} from './wsl-codex-command' +} from '../../codex-cli/wsl-codex-command' // Allow copied-link sign-ins to finish across browsers and password managers. const LOGIN_TIMEOUT_MS = 180_000 diff --git a/src/main/codex-accounts/codex-config-mirror.test.ts b/src/main/codex-accounts/managed-homes/codex-config-mirror.test.ts similarity index 80% rename from src/main/codex-accounts/codex-config-mirror.test.ts rename to src/main/codex-accounts/managed-homes/codex-config-mirror.test.ts index d614f21db1b..b61563e24c4 100644 --- a/src/main/codex-accounts/codex-config-mirror.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-config-mirror.test.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { getDefaultSettings } from '../../shared/constants' +import { getDefaultSettings } from '../../../shared/constants' const testState = vi.hoisted(() => ({ fakeHomeDir: '' })) @@ -65,22 +65,6 @@ describe('CodexConfigMirror without ~/.codex/config.toml', () => { expect(existsSync(join(testState.fakeHomeDir, '.codex'))).toBe(false) }) - it('leaves a WSL home to launch prep instead of running its blocking ownership check', async () => { - const assertManagedHomePath = vi.fn(async (path: string) => path) - const wslMirror = new CodexConfigMirror( - { getSettings: () => getDefaultSettings(testState.fakeHomeDir) }, - assertManagedHomePath - ) - - await wslMirror.safeSyncIntoManagedHome( - '\\\\wsl.localhost\\Ubuntu\\home\\u\\.local\\share\\orca\\codex-accounts\\acct\\home', - undefined, - 'acct' - ) - - expect(assertManagedHomePath).not.toHaveBeenCalled() - }) - it('adds the guard without touching settings already in the managed home', async () => { writeFileSync(join(managedHomePath, 'config.toml'), 'model = "gpt-5"\n') diff --git a/src/main/codex-accounts/codex-config-mirror.ts b/src/main/codex-accounts/managed-homes/codex-config-mirror.ts similarity index 90% rename from src/main/codex-accounts/codex-config-mirror.ts rename to src/main/codex-accounts/managed-homes/codex-config-mirror.ts index 1c19d71fdb9..cd5e5c0bb61 100644 --- a/src/main/codex-accounts/codex-config-mirror.ts +++ b/src/main/codex-accounts/managed-homes/codex-config-mirror.ts @@ -1,17 +1,17 @@ import { existsSync, readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { createIntegrationStateFileCache } from '../credentials/integration-state-file-cache' -import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import { createIntegrationStateFileCache } from '../../credentials/integration-state-file-cache' +import { parseWslUncPath, toWindowsWslPath } from '../../../shared/wsl-paths' import { ensureCodexDaemonSocketGuard, syncSystemConfigIntoManagedCodexHome -} from '../codex/configuration/settings/codex-config-mirror' -import { readCodexTopLevelModelProvider } from '../codex/structured/launch/codex-model-provider-config' -import type { Store } from '../persistence/loading-store/store' -import { wasWslDistroLastSeenRunningSettled } from '../wsl/discovery/wsl-background-distro-gate' -import { WSL_UNC_RUNNING_LEASE_MS } from '../wsl/filesystem/wsl-unc-access-gate' +} from '../../codex/configuration/settings/codex-config-mirror' +import { readCodexTopLevelModelProvider } from '../../codex/structured/launch/codex-model-provider-config' +import type { Store } from '../../persistence/loading-store/store' +import { wasWslDistroLastSeenRunningSettled } from '../../wsl/discovery/wsl-background-distro-gate' +import { WSL_UNC_RUNNING_LEASE_MS } from '../../wsl/filesystem/wsl-unc-access-gate' export type CanonicalCodexConfig = { contents: string diff --git a/src/main/codex-accounts/codex-managed-home-lifecycle.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts similarity index 93% rename from src/main/codex-accounts/codex-managed-home-lifecycle.ts rename to src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts index 0fdc8884b27..a319da2bba7 100644 --- a/src/main/codex-accounts/codex-managed-home-lifecycle.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-lifecycle.ts @@ -1,15 +1,18 @@ import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { dirname, join, resolve, sep } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' import { WINDOWS_RM_MAX_RETRIES, WINDOWS_RM_RETRY_DELAY_MS -} from '../../shared/windows-transient-lock-removal' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import type { CodexAccountAddTarget, ManagedCodexHomeLocation } from './codex-account-service-types' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' +} from '../../../shared/windows-transient-lock-removal' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { parseWslUncPath, toWindowsWslPath } from '../../../shared/wsl-paths' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import type { + CodexAccountAddTarget, + ManagedCodexHomeLocation +} from '../account-management/codex-account-service-types' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' import type { CodexManagedHomePath } from './codex-managed-home-path' diff --git a/src/main/codex-accounts/codex-managed-home-path-wsl-check.test.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-path-wsl-check.test.ts similarity index 75% rename from src/main/codex-accounts/codex-managed-home-path-wsl-check.test.ts rename to src/main/codex-accounts/managed-homes/codex-managed-home-path-wsl-check.test.ts index b2cdae593fb..608fc992cc5 100644 --- a/src/main/codex-accounts/codex-managed-home-path-wsl-check.test.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-path-wsl-check.test.ts @@ -1,10 +1,10 @@ -import type * as WslPaths from '../../shared/wsl-paths' +import type * as WslPaths from '../../../shared/wsl-paths' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { WslResult, WslSpec } from '../wsl/execution/wsl-runner' +import type { WslResult, WslSpec } from '../../wsl/execution/wsl-runner' const runWslProcess = vi.hoisted(() => vi.fn<(spec: WslSpec) => Promise>()) -vi.mock('../wsl/execution/wsl-runner', () => ({ runWslProcess })) -vi.mock('../../shared/wsl-paths', async (importOriginal) => ({ +vi.mock('../../wsl/execution/wsl-runner', () => ({ runWslProcess })) +vi.mock('../../../shared/wsl-paths', async (importOriginal) => ({ ...(await importOriginal()), ...(await (() => ({ toWindowsWslPath: (linuxPath: string, distro: string) => @@ -42,16 +42,6 @@ afterEach(() => { runWslProcess.mockReset() }) -it('reads only the fenced path, off the main thread and without the login shell', async () => { - runWslProcess.mockImplementation(async (spec) => answer(spec, LINUX_HOME)) - await expect(new CodexManagedHomePath().assert(UNC_HOME, 'acct')).resolves.toBe( - `\\\\wsl.localhost\\Ubuntu${LINUX_HOME}` - ) - expect(runWslProcess).toHaveBeenCalledWith( - expect.objectContaining({ distro: 'Ubuntu', loginPath: 'none', shell: 'bash' }) - ) -}) - it('refuses a home whose check failed in the distro', async () => { runWslProcess.mockImplementation(async (spec) => answer(spec, '', 35)) await expect(new CodexManagedHomePath().assert(UNC_HOME, 'acct')).rejects.toThrow( diff --git a/src/main/codex-accounts/codex-managed-home-path.ts b/src/main/codex-accounts/managed-homes/codex-managed-home-path.ts similarity index 93% rename from src/main/codex-accounts/codex-managed-home-path.ts rename to src/main/codex-accounts/managed-homes/codex-managed-home-path.ts index 4091f611933..fc136bef782 100644 --- a/src/main/codex-accounts/codex-managed-home-path.ts +++ b/src/main/codex-accounts/managed-homes/codex-managed-home-path.ts @@ -1,12 +1,12 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' -import { buildPosixStdoutFence } from '../../shared/posix-stdout-fence' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' -import { runWslProcess } from '../wsl/execution/wsl-runner' +import { getAppEnvironment } from '../../../shared/app-environment' +import { buildPosixStdoutFence } from '../../../shared/posix-stdout-fence' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { parseWslUncPath, toWindowsWslPath } from '../../../shared/wsl-paths' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' +import { getSystemCodexHomePath } from '../../codex/configuration/homes/codex-home-paths' +import { runWslProcess } from '../../wsl/execution/wsl-runner' import { assertOwnedHostCodexManagedHomePath } from './host-codex-managed-home-ownership' const WSL_MANAGED_HOME_TIMEOUT_MS = 5_000 diff --git a/src/main/codex-accounts/guest-codex-account-homes.test.ts b/src/main/codex-accounts/managed-homes/guest-codex-account-homes.test.ts similarity index 100% rename from src/main/codex-accounts/guest-codex-account-homes.test.ts rename to src/main/codex-accounts/managed-homes/guest-codex-account-homes.test.ts diff --git a/src/main/codex-accounts/guest-codex-account-homes.ts b/src/main/codex-accounts/managed-homes/guest-codex-account-homes.ts similarity index 95% rename from src/main/codex-accounts/guest-codex-account-homes.ts rename to src/main/codex-accounts/managed-homes/guest-codex-account-homes.ts index 89f2d5eb522..e48e9060814 100644 --- a/src/main/codex-accounts/guest-codex-account-homes.ts +++ b/src/main/codex-accounts/managed-homes/guest-codex-account-homes.ts @@ -1,7 +1,7 @@ import { readdirSync } from 'node:fs' import { homedir } from 'node:os' import { basename, dirname, join, resolve } from 'node:path' -import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' +import { getSystemCodexHomePath } from '../../codex/configuration/homes/codex-home-paths' import { resolveHostCodexManagedHomeVerdict } from './host-codex-managed-home-ownership' // Guest homes use $HOME///home with an account-ID ownership marker. diff --git a/src/main/codex-accounts/host-codex-managed-home-ownership.test.ts b/src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.test.ts similarity index 100% rename from src/main/codex-accounts/host-codex-managed-home-ownership.test.ts rename to src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.test.ts diff --git a/src/main/codex-accounts/host-codex-managed-home-ownership.ts b/src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.ts similarity index 98% rename from src/main/codex-accounts/host-codex-managed-home-ownership.ts rename to src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.ts index 2d6c9232e0d..23b433bc65a 100644 --- a/src/main/codex-accounts/host-codex-managed-home-ownership.ts +++ b/src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.ts @@ -1,6 +1,6 @@ import { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs' import { isAbsolute, join, relative, resolve, sep } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' type HostCodexManagedHomeOwnershipOptions = { candidatePath: string diff --git a/src/main/codex-accounts/codex-reset-credit-coordinator.ts b/src/main/codex-accounts/reset-credits/codex-reset-credit-coordinator.ts similarity index 92% rename from src/main/codex-accounts/codex-reset-credit-coordinator.ts rename to src/main/codex-accounts/reset-credits/codex-reset-credit-coordinator.ts index 7415676f089..fe1c9d38d26 100644 --- a/src/main/codex-accounts/codex-reset-credit-coordinator.ts +++ b/src/main/codex-accounts/reset-credits/codex-reset-credit-coordinator.ts @@ -3,26 +3,26 @@ import type { CodexManagedAccount, CodexManagedAccountSummary, CodexRateLimitAccountsState -} from '../../shared/managed-account-types' +} from '../../../shared/managed-account-types' import { buildCodexResetCreditExpectedScope, type CodexResetCreditExpectedScope -} from '../../shared/codex-reset-credit-scope' +} from '../../../shared/codex-reset-credit-scope' import type { CodexRateLimitResetResult, RateLimitState, RateLimitRuntimeTarget -} from '../../shared/rate-limit-types' -import type { Store } from '../persistence/loading-store/store' -import type { RateLimitService } from '../rate-limits/service/rate-limit-service' -import type { CodexRuntimeHomeService } from './runtime-home-service' -import { getSelectedCodexAccountIdForTarget } from './runtime-selection' -import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' +} from '../../../shared/rate-limit-types' +import type { Store } from '../../persistence/loading-store/store' +import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' +import type { CodexRuntimeHomeService } from '../runtime-home-service' +import { getSelectedCodexAccountIdForTarget } from '../account-management/runtime-selection' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../managed-homes/host-codex-managed-home-ownership' import type { CodexResetCreditConsumeResult, CodexResetCreditConsumedResult -} from './codex-account-service-types' -import type { CodexManagedHomePath } from './codex-managed-home-path' +} from '../account-management/codex-account-service-types' +import type { CodexManagedHomePath } from '../managed-homes/codex-managed-home-path' import { CodexResetCreditLedger, resetAccountScopeKey, diff --git a/src/main/codex-accounts/codex-reset-credit-ledger.test.ts b/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts similarity index 94% rename from src/main/codex-accounts/codex-reset-credit-ledger.test.ts rename to src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts index 944ebb7d956..a0adcb0de6d 100644 --- a/src/main/codex-accounts/codex-reset-credit-ledger.test.ts +++ b/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import type { CodexResetCreditAttemptLedger } from '../../shared/codex-reset-credit-attempt-ledger' -import type { CodexResetCreditExpectedScope } from '../../shared/codex-reset-credit-scope' -import { ProfileStateWriterError } from '../persistence/profile-state/writer/profile-state-writer-errors' +import type { CodexResetCreditAttemptLedger } from '../../../shared/codex-reset-credit-attempt-ledger' +import type { CodexResetCreditExpectedScope } from '../../../shared/codex-reset-credit-scope' +import { ProfileStateWriterError } from '../../persistence/profile-state/writer/profile-state-writer-errors' import { CodexResetCreditLedger } from './codex-reset-credit-ledger' function scope(accountId: string): CodexResetCreditExpectedScope { diff --git a/src/main/codex-accounts/codex-reset-credit-ledger.ts b/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.ts similarity index 95% rename from src/main/codex-accounts/codex-reset-credit-ledger.ts rename to src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.ts index e3b03b6303b..9ebfa93a8a5 100644 --- a/src/main/codex-accounts/codex-reset-credit-ledger.ts +++ b/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.ts @@ -1,15 +1,15 @@ -import type { CodexManagedAccount } from '../../shared/managed-account-types' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' import type { CodexResetCreditAttemptLedger, DurableCodexResetCreditAttempt -} from '../../shared/codex-reset-credit-attempt-ledger' -import type { CodexResetCreditExpectedScope } from '../../shared/codex-reset-credit-scope' +} from '../../../shared/codex-reset-credit-attempt-ledger' +import type { CodexResetCreditExpectedScope } from '../../../shared/codex-reset-credit-scope' import type { CodexRateLimitResetOutcome, RateLimitRuntimeTarget -} from '../../shared/rate-limit-types' -import type { Store } from '../persistence/loading-store/store' -import { profileStateWriterFailureOutcome } from '../persistence/profile-state/writer/profile-state-writer-errors' +} from '../../../shared/rate-limit-types' +import type { Store } from '../../persistence/loading-store/store' +import { profileStateWriterFailureOutcome } from '../../persistence/profile-state/writer/profile-state-writer-errors' export type CodexResetCreditAttempt = { expectedScope: CodexResetCreditExpectedScope diff --git a/src/main/codex-accounts/codex-reset-credit-scope-validation.ts b/src/main/codex-accounts/reset-credits/codex-reset-credit-scope-validation.ts similarity index 86% rename from src/main/codex-accounts/codex-reset-credit-scope-validation.ts rename to src/main/codex-accounts/reset-credits/codex-reset-credit-scope-validation.ts index 3798dd49605..6bcf9b5ce78 100644 --- a/src/main/codex-accounts/codex-reset-credit-scope-validation.ts +++ b/src/main/codex-accounts/reset-credits/codex-reset-credit-scope-validation.ts @@ -1,22 +1,22 @@ import type { CodexManagedAccount, CodexManagedAccountSummary -} from '../../shared/managed-account-types' +} from '../../../shared/managed-account-types' import { buildCodexResetCreditExpectedScope, type CodexResetCreditExpectedScope -} from '../../shared/codex-reset-credit-scope' -import type { RateLimitState, RateLimitRuntimeTarget } from '../../shared/rate-limit-types' -import type { Store } from '../persistence/loading-store/store' -import type { RateLimitService } from '../rate-limits/service/rate-limit-service' -import type { CodexResetCreditRejectedBeforeProviderReason } from './codex-account-service-types' -import type { CodexManagedHomePath } from './codex-managed-home-path' +} from '../../../shared/codex-reset-credit-scope' +import type { RateLimitState, RateLimitRuntimeTarget } from '../../../shared/rate-limit-types' +import type { Store } from '../../persistence/loading-store/store' +import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' +import type { CodexResetCreditRejectedBeforeProviderReason } from '../account-management/codex-account-service-types' +import type { CodexManagedHomePath } from '../managed-homes/codex-managed-home-path' import { resetScopeKey } from './codex-reset-credit-ledger' import { getCodexSelectionTargetForAccount, - getSelectedCodexAccountIdForTarget, - normalizeCodexAccountSelectionTarget -} from './runtime-selection' + getSelectedCodexAccountIdForTarget +} from '../account-management/runtime-selection' +import { normalizeCodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' export type CodexResetCreditScopeValidation = | { kind: 'settledReplay' } diff --git a/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts b/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts deleted file mode 100644 index 1709853ef38..00000000000 --- a/src/main/codex-accounts/runtime-home-catalog-account-key.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import type * as NodeOs from 'node:os' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import type { AgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createCodexAccountRecord, - createCodexAuthJson, - createManagedAuth, - createStore, - getRuntimeCodexHomePath, - getSystemCodexHomePath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -// Hook install and session bridges are launch chores outside the key; keep them off disk. -vi.mock('../codex/hooks/installation/hook-service', () => ({ - codexHookService: { prepareRuntimeHomeForLaunch: async () => ({ state: 'installed' }) } -})) -vi.mock('../codex/hooks/reconciliation/codex-hook-reconcile', () => ({ - reconcileCodexHooksForLaunch: async () => {} -})) -vi.mock('../codex/history/bridges/codex-session-bridge', () => ({ - startSystemCodexSessionBridgeInBackground: async () => {} -})) -vi.mock('../codex/history/bridges/codex-account-session-bridge', () => ({ - startCodexAccountSessionBridgeInBackground: async () => {} -})) - -// Use production wiring so catalog reads and launches cannot silently drift apart. -async function wireCodexAccountKey(settings: ReturnType) { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const { mainProcessState } = await import('../startup/main-process-state') - const { codexStructuredLaunchHomeResolvers } = await import('../startup/codex-launch-preparation') - const { structuredAgentRuntimeRegistration } = - await import('../runtime/agent-session/installation/structured-agent-runtime-registrations') - const { agentModelCatalogFingerprint } = - await import('../native-chat/agent-model-catalog/agent-model-catalog-fingerprint') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the harness store implements the settings read/update surface the service uses. - const runtimeHome = new CodexRuntimeHomeService(createStore(settings) as never) - mainProcessState.codexRuntimeHome = runtimeHome - const codex = structuredAgentRuntimeRegistration('codex')! - const services = { - getClaudeConfigDirectory: () => null, - prepareCodexLaunchHome: codexStructuredLaunchHomeResolvers.prepareCodexStructuredLaunch, - readCodexLaunchHome: codexStructuredLaunchHomeResolvers.resolveCodexStructuredLaunchHome, - workspaceTrustSettings: () => settings, - workspaceTrustRepoDecision: () => undefined, - stateDirectory: '/orca-data', - hostLaunchEnvironment: async () => ({}), - hostSettings: () => ({}) - } - const resolve = (purpose: 'launch' | 'read') => - codex.resolveAccountHome( - { launchEnv: {}, location: null, purpose, workspacePath: null }, - services - ) - const key = (accountHome: AgentSessionAccountHome) => - agentModelCatalogFingerprint({ agent: 'codex', accountHome, wslDistro: null }) - return { resolve, key, release: () => (mainProcessState.codexRuntimeHome = null) } -} - -describe('Codex catalog account key: picker read vs launch', () => { - let release: (() => void) | null = null - - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - release?.() - release = null - teardownRuntimeHomeTest() - }) - - async function expectOneKey(settings: ReturnType, expectedPath: string) { - const wired = await wireCodexAccountKey(settings) - release = wired.release - const before = await wired.resolve('read') - const launched = await wired.resolve('launch') - const after = await wired.resolve('read') - - expect(launched).toMatchObject({ variable: 'CODEX_HOME', path: expectedPath }) - expect(wired.key(before)).toBe(wired.key(launched)) - expect(wired.key(after)).toBe(wired.key(launched)) - } - - it('system account on the real ~/.codex', async () => { - await expectOneKey(createSettings({ realHomeRoutable: true }), getSystemCodexHomePath()) - }) - - it("system account on Orca's shared runtime home", async () => { - await expectOneKey(createSettings({ realHomeRoutable: false }), getRuntimeCodexHomePath()) - }) - - it('a managed account in its own home', async () => { - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - createCodexAuthJson('user@example.com', 'acct-1', 'refresh-1') - ) - await expectOneKey( - createSettings({ - realHomeRoutable: true, - codexManagedAccounts: [ - createCodexAccountRecord('account-1', 'user@example.com', 'acct-1', managedHomePath) - ], - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }), - managedHomePath - ) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-catalog-probe-prep.test.ts b/src/main/codex-accounts/runtime-home-catalog-probe-prep.test.ts deleted file mode 100644 index 3e70685c424..00000000000 --- a/src/main/codex-accounts/runtime-home-catalog-probe-prep.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { dirname } from 'node:path' -import type * as NodeOs from 'node:os' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createCodexAuthJson, - createStore, - getRuntimeCodexAuthPath, - getRuntimeCodexHomePath, - getSystemCodexAuthPath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' -import type { CodexRuntimeHomeService } from './runtime-home-service' - -vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', - async (importOriginal) => ({ - ...(await importOriginal()), - applyCodexDaemonSocketGuard: (config: string) => config - }) -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -const login = createCodexAuthJson('me@example.com', 'acct-me', 'external-login') - -async function mirrorRouteService(): Promise { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only getSettings/updateSettings, which the harness store implements. - return new CodexRuntimeHomeService(createStore(createSettings()) as never) -} - -function loginInSystemHome(): void { - mkdirSync(dirname(getSystemCodexAuthPath()), { recursive: true }) - writeFileSync(getSystemCodexAuthPath(), login, 'utf-8') -} - -describe("the catalog probe's home prep on the mirror route", () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it('brings a login made in ~/.codex into the mirror before the probe reads it', async () => { - const service = await mirrorRouteService() - expect(service.prepareForCodexLaunch()).toBe(getRuntimeCodexHomePath()) - expect(existsSync(getRuntimeCodexAuthPath())).toBe(false) - loginInSystemHome() - - service.prepareHostCodexHomeForReadOnlyAppServer(getRuntimeCodexHomePath()) - - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(login) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-per-account-homes.test.ts b/src/main/codex-accounts/runtime-home-per-account-homes.test.ts deleted file mode 100644 index 25dfe6019e6..00000000000 --- a/src/main/codex-accounts/runtime-home-per-account-homes.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createCodexAuthJson, - createManagedAuth, - createStore, - expectResourceLinkedOrCopied, - getRuntimeCodexAuthPath, - getSystemCodexAuthPath, - getSystemCodexHomePath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexRuntimeHomeService', () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it.each(['two@example.com', 'one@example.com'])( - 'isolates account homes when the second email is %s', - async (secondEmail) => { - writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') - const account1Auth = createCodexAuthJson('one@example.com', 'acct-1', 'one') - const account2Auth = createCodexAuthJson(secondEmail, 'acct-2', 'two') - const home1 = createManagedAuth(testState.userDataDir, 'account-1', account1Auth) - const home2 = createManagedAuth(testState.userDataDir, 'account-2', account2Auth) - const settings = createSettings({ - realHomeRoutable: true, - codexManagedAccounts: [ - { - id: 'account-1', - email: 'one@example.com', - managedHomePath: home1, - providerAccountId: 'acct-1', - workspaceLabel: null, - workspaceAccountId: 'acct-1', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - }, - { - id: 'account-2', - email: secondEmail, - managedHomePath: home2, - providerAccountId: 'acct-2', - workspaceLabel: null, - workspaceAccountId: 'acct-2', - createdAt: 2, - updatedAt: 2, - lastAuthenticatedAt: 2 - } - ], - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - expect(service.prepareForCodexLaunch()).toBe(home1) - settings.activeCodexManagedAccountId = 'account-2' - settings.activeCodexManagedAccountIdsByRuntime = { host: 'account-2', wsl: {} } - expect(service.prepareForCodexLaunch()).toBe(home2) - expect( - service.prepareForCodexLaunch(undefined, undefined, { - unavailableManagedHomePath: home1 - }) - ).toBe(home2) - expect(store.updateSettings).not.toHaveBeenCalled() - - expect(readFileSync(join(home1, 'auth.json'), 'utf-8')).toBe(account1Auth) - expect(readFileSync(join(home2, 'auth.json'), 'utf-8')).toBe(account2Auth) - expect(existsSync(getRuntimeCodexAuthPath())).toBe(false) - } - ) - - it('materializes resources and config into the per-account home on launch', async () => { - writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') - mkdirSync(join(getSystemCodexHomePath(), 'skills', 'review'), { recursive: true }) - writeFileSync( - join(getSystemCodexHomePath(), 'skills', 'review', 'SKILL.md'), - 'skill\n', - 'utf-8' - ) - writeFileSync( - join(getSystemCodexHomePath(), 'config.toml'), - 'approval_policy = "never"\n', - 'utf-8' - ) - const home1 = createManagedAuth( - testState.userDataDir, - 'account-1', - createCodexAuthJson('one@example.com', 'acct-1', 'one') - ) - const store = createStore( - createSettings({ - realHomeRoutable: true, - codexManagedAccounts: [ - { - id: 'account-1', - email: 'one@example.com', - managedHomePath: home1, - providerAccountId: 'acct-1', - workspaceLabel: null, - workspaceAccountId: 'acct-1', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ], - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - expect(service.prepareForCodexLaunch()).toBe(home1) - - expectResourceLinkedOrCopied(join(home1, 'skills'), join(getSystemCodexHomePath(), 'skills')) - expect(readFileSync(join(home1, 'skills', 'review', 'SKILL.md'), 'utf-8')).toBe('skill\n') - expect(readFileSync(join(home1, 'config.toml'), 'utf-8')).toContain('approval_policy = "never"') - - expect(readFileSync(getSystemCodexAuthPath(), 'utf-8')).toBe('{"account":"system"}\n') - }) - - it('does not read shared auth when polling observes a managed-to-real-home transition', async () => { - const runtimeAuthPath = getRuntimeCodexAuthPath() - const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') - const managedAuth = createCodexAuthJson('user@example.com', 'acct-user', 'managed', 1) - const refreshedManagedAuth = createCodexAuthJson( - 'user@example.com', - 'acct-user', - 'refreshed', - 2 - ) - writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') - const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', managedAuth) - const settings = createSettings({ - realHomeRoutable: true, - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - providerAccountId: 'acct-user', - workspaceLabel: null, - workspaceAccountId: 'acct-user', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ], - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - writeFileSync(runtimeAuthPath, refreshedManagedAuth, 'utf-8') - settings.activeCodexManagedAccountId = null - settings.activeCodexManagedAccountIdsByRuntime = { host: null, wsl: {} } - const syncSpy = vi.spyOn(service, 'syncForCurrentSelection') - - expect(service.prepareForRateLimitFetch()).toEqual({ - kind: 'ready', - codexHomePath: getSystemCodexHomePath() - }) - expect(readFileSync(join(managedHomePath, 'auth.json'), 'utf-8')).toBe(managedAuth) - expect(readFileSync(getSystemCodexAuthPath(), 'utf-8')).toBe(systemAuth) - expect(syncSpy).not.toHaveBeenCalled() - - expect(service.prepareForRateLimitFetch()).toEqual({ - kind: 'ready', - codexHomePath: getSystemCodexHomePath() - }) - expect(service.prepareForCodexLaunch()).toBeNull() - expect(syncSpy).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/codex-accounts/runtime-home-rate-limit-pinned-distro.test.ts b/src/main/codex-accounts/runtime-home-rate-limit-pinned-distro.test.ts deleted file mode 100644 index 19b74edb754..00000000000 --- a/src/main/codex-accounts/runtime-home-rate-limit-pinned-distro.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { join } from 'node:path' -import type { CodexAccountSelectionTarget } from '../../shared/codex-selection-lane' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createManagedAuth, - createStore, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -vi.mock('../wsl/discovery/wsl-background-exec-gate', () => ({ - blockedWslDistroForExec: async () => null -})) -vi.mock('electron', () => ({ app: { getPath: () => testState.userDataDir } })) -vi.mock(import('node:os'), async (importOriginal) => ({ - ...(await importOriginal()), - homedir: () => testState.fakeHomeDir -})) - -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - -function account(id: string, distro: string, managedHomePath: string) { - return { - id, - email: `${id}@example.com`, - managedHomePath, - managedHomeRuntime: 'wsl' as const, - wslDistro: distro, - wslLinuxHomePath: `/home/alice/.local/share/orca/codex-accounts/${id}/home`, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } -} - -async function serviceFor(wsl: Record, accounts: ReturnType[]) { - const store = createStore( - createSettings({ - codexManagedAccounts: accounts, - activeCodexManagedAccountId: null, - activeCodexManagedAccountIdsByRuntime: { host: null, wsl } - }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - // Launch's own home lookup, for its resolved (named) target. - class LaunchHomeProbe extends CodexRuntimeHomeService { - launchHome(target: CodexAccountSelectionTarget): string | null { - return this.getWslCodexHomePathForSelection(target) - } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the harness store implements every Store member this service reads. - return new LaunchHomeProbe(store as never) -} - -describe('Codex quota poll home with a gated, pinned WSL distro (E9)', () => { - let wslHome: string - - beforeEach(() => { - setupRuntimeHomeTest() - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ - getDefaultWslDistro: () => 'Ubuntu', - getWslHome: () => wslHome, - getWslHomeAsync: async () => wslHome - })) - }) - - afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - teardownRuntimeHomeTest() - }) - - it('reads the same home launch uses for a default-lane pick: the named lane, not __default__', async () => { - const defaultHome = createManagedAuth(testState.userDataDir, 'acc-default', '{"a":"d"}\n') - const service = await serviceFor({ __default__: 'acc-default' }, [ - account('acc-default', 'Ubuntu', defaultHome) - ]) - - const poll = service.prepareForRateLimitFetch({ runtime: 'wsl' }, 'Ubuntu') - const launch = service.launchHome({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - - expect(poll).toEqual({ kind: 'ready', codexHomePath: launch }) - expect(launch).not.toBe(defaultHome) - }) - - it('reads the same managed home launch uses for the pinned distro’s own pick', async () => { - const ubuntuHome = createManagedAuth(testState.userDataDir, 'acc-ubuntu', '{"a":"u"}\n') - const service = await serviceFor({ Ubuntu: 'acc-ubuntu' }, [ - account('acc-ubuntu', 'Ubuntu', ubuntuHome) - ]) - - expect(service.prepareForRateLimitFetch({ runtime: 'wsl' }, 'Ubuntu')).toEqual({ - kind: 'ready', - codexHomePath: ubuntuHome - }) - expect(service.launchHome({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe(ubuntuHome) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-real-home-lane-routing.test.ts b/src/main/codex-accounts/runtime-home-real-home-lane-routing.test.ts deleted file mode 100644 index 14beefe7018..00000000000 --- a/src/main/codex-accounts/runtime-home-real-home-lane-routing.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createCodexAuthJson, - createStore, - getRuntimeCodexAuthPath, - getRuntimeCodexHomePath, - getSharedRuntimeAuthProvenancePath, - getSystemCodexAuthPath, - getSystemCodexHomePath, - setRealHomeRoutableForTest, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState, - writePaneRegistry -} from './runtime-home-service-test-harness' - -// Keep asserted config bytes independent of platform socket-path limits. -vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', - async (importOriginal) => ({ - ...(await importOriginal()), - applyCodexDaemonSocketGuard: (config: string) => config - }) -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexRuntimeHomeService', () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it('seeds shared auth for a pane-local custom home on the real-home lane', async () => { - const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system-token') - writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') - const store = createStore(createSettings({ realHomeRoutable: true })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - const customHome = join(testState.fakeHomeDir, 'pane-custom-codex-home') - - expect(service.prepareForCodexLaunch(undefined, { CODEX_HOME: customHome })).toBe( - getRuntimeCodexHomePath() - ) - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(systemAuth) - }) - - it('skips retired-home reconciliation when no retained host pane can use it', async () => { - const syncLegacySharedCodexConfigForRetainedPanes = vi.fn() - vi.doMock('./legacy-shared-config-compatibility', () => ({ - syncLegacySharedCodexConfigForRetainedPanes - })) - const retainedAuth = createCodexAuthJson('system@example.com', 'acct-system', 'retained') - const currentAuth = createCodexAuthJson('system@example.com', 'acct-system', 'current') - const retainedConfig = 'model = "retained"\n' - writePaneRegistry({ - 'real-home-pane': { - selectionKey: 'host', - accountId: null, - homeRoute: 'real-home' - } - }) - writeFileSync(getRuntimeCodexAuthPath(), retainedAuth, 'utf-8') - writeFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), retainedConfig, 'utf-8') - writeFileSync(getSystemCodexAuthPath(), currentAuth, 'utf-8') - writeFileSync(join(getSystemCodexHomePath(), 'config.toml'), 'model = "current"\n', 'utf-8') - writeFileSync( - getSharedRuntimeAuthProvenancePath(), - `${JSON.stringify({ owner: 'system-default', authJson: retainedAuth })}\n`, - 'utf-8' - ) - const store = createStore(createSettings({ realHomeRoutable: true })) - try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - service.reconcileLegacySharedHomeForRetainedPanes() - expect(service.prepareForCodexLaunch()).toBeNull() - expect(service.prepareForRateLimitFetch()).toEqual({ - kind: 'ready', - codexHomePath: getSystemCodexHomePath() - }) - - expect(syncLegacySharedCodexConfigForRetainedPanes).not.toHaveBeenCalled() - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(retainedAuth) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toBe( - retainedConfig - ) - } finally { - vi.doUnmock('./legacy-shared-config-compatibility') - } - }) - - it('keeps pre-rollout shared-home panes authenticated on the real-home lane', async () => { - const oldSystemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'old-system') - const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') - const systemConfig = [ - 'model_provider = "codex-lb"', - '', - '[model_providers.codex-lb]', - 'base_url = "https://codex-lb.example.test/v1"', - 'requires_openai_auth = true', - '' - ].join('\n') - writeFileSync(getSystemCodexAuthPath(), oldSystemAuth, 'utf-8') - const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - new CodexRuntimeHomeService(store as never) - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(oldSystemAuth) - - setRealHomeRoutableForTest(true) - writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') - writeFileSync(join(getSystemCodexHomePath(), 'config.toml'), systemConfig, 'utf-8') - writeFileSync( - join(getRuntimeCodexHomePath(), 'config.toml'), - 'model_provider = "stale-provider"\n', - 'utf-8' - ) - - const service = new CodexRuntimeHomeService(store as never) - - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(oldSystemAuth) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toContain( - 'stale-provider' - ) - service.reconcileLegacySharedHomeForRetainedPanes() - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(systemAuth) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toBe(systemConfig) - expect(service.prepareForCodexLaunch()).toBeNull() - }) - - it('preserves retained managed auth across a real-home main-process restart', async () => { - const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') - const managedAuth = createCodexAuthJson('managed@example.com', 'acct-managed', 'managed') - writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') - const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - new CodexRuntimeHomeService(store as never) - writeFileSync(getRuntimeCodexAuthPath(), managedAuth, 'utf-8') - - setRealHomeRoutableForTest(true) - const restartedService = new CodexRuntimeHomeService(store as never) - - expect(restartedService.prepareForCodexLaunch()).toBeNull() - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(managedAuth) - expect(readFileSync(getSystemCodexAuthPath(), 'utf-8')).toBe(systemAuth) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts b/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts deleted file mode 100644 index 987b80d159e..00000000000 --- a/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts +++ /dev/null @@ -1,313 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import type * as NodeOs from 'node:os' -import { readHookTrustEntries } from '../codex/trust/toml/config-toml-trust' -import { writeCodexStateDbBackfillStatus } from '../codex/history/index/codex-state-db-test-fixture' - -const testState = { userData: '', home: '' } -const previousEnv: Record = {} - -vi.mock('../codex/trust/hooks/codex-hook-trust-derivation', async (importOriginal) => - ( - await import('../codex/trust/hooks/codex-hook-trust-derivation.test-fixture') - ).answeringCodexForTests(await importOriginal()) -) -vi.mock('electron', () => ({ app: { getPath: () => testState.userData } })) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userData })) -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { ...actual, homedir: () => testState.home } -}) -// Prevent the selection-triggered history bridge from spawning a real app-server. -vi.mock('../codex/history/index/codex-account-session-index-heal', () => { - const upToDate = async () => ({ - outcome: 'up-to-date', - healedThreads: 0, - missingThreads: 0, - failedThreads: 0 - }) - return { - createCodexAccountStateDb: async () => false, - healCodexAccountSessionIndex: upToDate, - healPendingCodexAccountThreads: upToDate - } -}) - -beforeEach(() => { - vi.resetModules() - testState.userData = mkdtempSync(join(tmpdir(), 'orca-codex-e-migration-')) - testState.home = mkdtempSync(join(tmpdir(), 'orca-codex-e-home-')) - for (const key of [ - 'ORCA_USER_DATA_PATH', - 'ORCA_DISABLE_CODEX_TRUST_RPC', - 'CODEX_HOME', - 'ORCA_CODEX_HOME' - ]) { - previousEnv[key] = process.env[key] - delete process.env[key] - } - process.env.ORCA_USER_DATA_PATH = testState.userData - process.env.ORCA_DISABLE_CODEX_TRUST_RPC = '1' - mkdirSync(systemHome(), { recursive: true }) - mkdirSync(sharedHome(), { recursive: true }) -}) - -afterEach(() => { - rmSync(testState.userData, { recursive: true, force: true }) - rmSync(testState.home, { recursive: true, force: true }) - for (const [key, value] of Object.entries(previousEnv)) { - if (value === undefined) { - delete process.env[key] - } else { - process.env[key] = value - } - } -}) - -describe('CodexRuntimeHomeService per-account takeover composition', () => { - it('upgrades a realistic two-account shared-home fixture without losing auth or sessions', async () => { - const accountOneStale = createAuth('one@example.com', 'acct-1', 'one-stale', 1_000) - const accountOneMigrated = createAuth('one@example.com', 'acct-1', 'one-migrated', 2_000) - const accountTwoAuth = createAuth('two@example.com', 'acct-2', 'two-current', 3_000) - const accountOne = createManagedAccount('account-1', 'acct-1', accountOneStale) - const accountTwo = createManagedAccount( - 'account-2', - 'acct-2', - accountTwoAuth, - 'two@example.com' - ) - const sharedSession = join(sharedHome(), 'sessions', '2026', '07', 'rollout.jsonl') - mkdirSync(join(systemHome(), 'skills', 'fixture-skill'), { recursive: true }) - mkdirSync(join(systemHome(), 'hooks'), { recursive: true }) - mkdirSync(join(sharedHome(), 'sessions', '2026', '07'), { recursive: true }) - writeFileSync(join(systemHome(), 'skills', 'fixture-skill', 'SKILL.md'), 'fixture skill\n') - writeFileSync(join(systemHome(), 'hooks', 'user-hook.sh'), '#!/bin/sh\n') - writeFileSync( - join(systemHome(), 'config.toml'), - 'model = "fixture-model"\n\n[hooks.state."stale-fixture"]\nenabled = true\n' - ) - writeFileSync(sharedSession, '{"session":"legacy-shared"}\n') - writeFileSync(sharedAuthPath(), accountOneMigrated) - const { settings, store } = createStore([accountOne, accountTwo], accountOne.id) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const [, { CodexHookService }] = await Promise.all([ - import('../codex/hooks/installation/hook-service'), - import('../codex/hooks/installation/codex-hook-service-implementation') - ]) - const { startCodexHookHashLookup } = await import('../codex/trust/hooks/codex-hook-hash-lookup') - startCodexHookHashLookup(Promise.resolve()) - const service = new CodexRuntimeHomeService(store as never) - const hookService = new CodexHookService() - - expect(readFileSync(join(accountOne.managedHomePath, 'auth.json'), 'utf8')).toBe( - accountOneMigrated - ) - expect(readFileSync(join(accountTwo.managedHomePath, 'auth.json'), 'utf8')).toBe(accountTwoAuth) - - for (const account of [accountOne, accountTwo]) { - selectManagedAccount(settings, account.id) - service.syncForCurrentSelection() - expect(service.prepareForCodexLaunch()).toBe(account.managedHomePath) - expect( - readFileSync(join(account.managedHomePath, 'skills', 'fixture-skill', 'SKILL.md'), 'utf8') - ).toBe('fixture skill\n') - expect(readFileSync(join(account.managedHomePath, 'hooks', 'user-hook.sh'), 'utf8')).toBe( - '#!/bin/sh\n' - ) - const config = readFileSync(join(account.managedHomePath, 'config.toml'), 'utf8') - expect(config).toContain('model = "fixture-model"') - expect(config).not.toContain('[hooks.state') - expect((await hookService.install(account.managedHomePath)).state).toBe('installed') - expect(readFileSync(join(account.managedHomePath, 'hooks.json'), 'utf8')).toContain( - process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh' - ) - expect( - readHookTrustEntries(join(account.managedHomePath, 'config.toml')).size - ).toBeGreaterThan(0) - } - - const discoveryHomes = service.getHostCodexHomePathsForSessionDiscovery() - expect(discoveryHomes).toEqual( - expect.arrayContaining([ - sharedHome(), - systemHome(), - accountOne.managedHomePath, - accountTwo.managedHomePath - ]) - ) - expect(new Set(discoveryHomes).size).toBe(discoveryHomes.length) - expect(readFileSync(sharedSession, 'utf8')).toBe('{"session":"legacy-shared"}\n') - - writeFileSync(sharedAuthPath(), createAuth('two@example.com', 'acct-2', 'later-shared', 4_000)) - expect(service.prepareForCodexLaunch()).toBe(accountTwo.managedHomePath) - expect(readFileSync(join(accountTwo.managedHomePath, 'auth.json'), 'utf8')).toBe(accountTwoAuth) - }) - - it('never continuously recovers a missing E auth from shared state after takeover', async () => { - const stale = createAuth('one@example.com', 'acct-1', 'stale', 1_000) - const takeover = createAuth('one@example.com', 'acct-1', 'takeover', 2_000) - const laterShared = createAuth('one@example.com', 'acct-1', 'later-shared', 3_000) - const account = createManagedAccount('account-1', 'acct-1', stale) - writeFileSync(sharedAuthPath(), takeover, 'utf-8') - writeFileSync(systemAuthPath(), 'system auth sentinel\n', 'utf-8') - const { settings, store } = createStore([account], account.id) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - const accountAuthPath = join(account.managedHomePath, 'auth.json') - expect(readFileSync(accountAuthPath, 'utf-8')).toBe(takeover) - - rmSync(accountAuthPath) - writeFileSync(sharedAuthPath(), laterShared, 'utf-8') - - expect(service.prepareForCodexLaunch()).toBe(account.managedHomePath) - expect(service.prepareForRateLimitFetch()).toEqual({ - kind: 'ready', - codexHomePath: account.managedHomePath - }) - expect(existsSync(accountAuthPath)).toBe(false) - expect(settings.activeCodexManagedAccountId).toBe(account.id) - expect(readFileSync(sharedAuthPath(), 'utf-8')).toBe(laterShared) - expect(readFileSync(systemAuthPath(), 'utf-8')).toBe('system auth sentinel\n') - }) - - it('bridges real-home and sibling-account history into the launched account home', async () => { - const accountOne = createManagedAccount( - 'account-1', - 'acct-1', - createAuth('one@example.com', 'acct-1', 'one', 1_000) - ) - const accountTwo = createManagedAccount( - 'account-2', - 'acct-2', - createAuth('two@example.com', 'acct-2', 'two', 2_000), - 'two@example.com' - ) - const systemRollout = join('2026', '07', '20', 'rollout-2026-07-20T10-00-00-aaaa.jsonl') - const siblingRollout = join('2026', '07', '21', 'rollout-2026-07-21T10-00-00-bbbb.jsonl') - writeRollout(systemHome(), systemRollout, '{"session":"real-home"}\n') - writeRollout(accountOne.managedHomePath, siblingRollout, '{"session":"account-one"}\n') - // History bridging requires the new home to be indexed first (#20669). - writeCodexStateDbBackfillStatus(accountTwo.managedHomePath, 'complete') - const { settings, store } = createStore([accountOne, accountTwo], accountOne.id) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const bridge = await import('../codex/history/bridges/codex-account-session-bridge') - const service = new CodexRuntimeHomeService(store as never) - - selectManagedAccount(settings, accountTwo.id) - service.syncForCurrentSelection() - expect(service.prepareForCodexLaunch()).toBe(accountTwo.managedHomePath) - await bridge.startCodexAccountSessionBridgeInBackground({ - targetCodexHomePath: accountTwo.managedHomePath, - sourceCodexHomePaths: [systemHome(), accountOne.managedHomePath] - }) - - expect(readFileSync(join(accountTwo.managedHomePath, 'sessions', systemRollout), 'utf-8')).toBe( - '{"session":"real-home"}\n' - ) - expect( - readFileSync(join(accountTwo.managedHomePath, 'sessions', siblingRollout), 'utf-8') - ).toBe('{"session":"account-one"}\n') - expect(existsSync(join(systemHome(), 'sessions', siblingRollout))).toBe(false) - }) -}) - -function createStore(accounts: CodexManagedAccount[], activeId: string | null) { - const settings = { - codexManagedAccounts: accounts, - activeCodexManagedAccountId: activeId, - activeCodexManagedAccountIdsByRuntime: { host: activeId, wsl: {} } - } as GlobalSettings - return { - settings, - store: { - getSettings: () => settings, - updateSettings: (updates: Partial) => Object.assign(settings, updates) - } - } -} - -function createManagedAccount( - id: string, - providerId: string, - auth: string, - email = 'one@example.com' -): CodexManagedAccount { - const home = join(testState.userData, 'codex-accounts', id, 'home') - mkdirSync(home, { recursive: true }) - writeFileSync(join(home, '.orca-managed-home'), `${id}\n`, 'utf-8') - writeFileSync(join(home, 'auth.json'), auth, 'utf-8') - return managedAccountRecord(id, providerId, home, email) -} - -function managedAccountRecord( - id: string, - providerAccountId: string, - managedHomePath: string, - email = 'one@example.com' -): CodexManagedAccount { - return { - id, - email, - managedHomePath, - providerAccountId, - workspaceLabel: null, - workspaceAccountId: providerAccountId, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } -} - -function selectManagedAccount(settings: GlobalSettings, accountId: string): void { - settings.activeCodexManagedAccountId = accountId - settings.activeCodexManagedAccountIdsByRuntime = { host: accountId, wsl: {} } -} - -function writeRollout(homePath: string, relativePath: string, contents: string): void { - const filePath = join(homePath, 'sessions', relativePath) - mkdirSync(join(filePath, '..'), { recursive: true }) - writeFileSync(filePath, contents, 'utf-8') -} - -function systemHome(): string { - return join(testState.home, '.codex') -} - -function systemAuthPath(): string { - return join(systemHome(), 'auth.json') -} - -function sharedHome(): string { - return join(testState.userData, 'codex-runtime-home', 'home') -} - -function sharedAuthPath(): string { - return join(sharedHome(), 'auth.json') -} - -function createAuth(email: string, accountId: string, token: string, expiresAt: number): string { - const header = Buffer.from('{}').toString('base64url') - const payload = Buffer.from( - JSON.stringify({ - email, - exp: expiresAt, - 'https://api.openai.com/auth': { - chatgpt_account_id: accountId, - workspace_account_id: accountId - } - }) - ).toString('base64url') - return `${JSON.stringify({ - tokens: { - id_token: `${header}.${payload}.`, - account_id: accountId, - refresh_token: token, - expires_at: expiresAt - } - })}\n` -} diff --git a/src/main/codex-accounts/runtime-home-service.ts b/src/main/codex-accounts/runtime-home-service.ts index af06a8f4fc1..019576f2b98 100644 --- a/src/main/codex-accounts/runtime-home-service.ts +++ b/src/main/codex-accounts/runtime-home-service.ts @@ -1,10 +1,5 @@ import type { Store } from '../persistence/loading-store/store' -import { CodexRuntimeHomeAuthSync } from './runtime-home-service-auth-sync' - -export type { - CodexMirroredHomeStatus, - CodexRateLimitHomeResolution -} from './runtime-home-service-types' +import { CodexRuntimeHomeAuthSync } from './runtime-home/credentials/runtime-home-service-auth-sync' export class CodexRuntimeHomeService extends CodexRuntimeHomeAuthSync { constructor(store: Store) { diff --git a/src/main/codex-accounts/runtime-home-session-discovery-read-only.test.ts b/src/main/codex-accounts/runtime-home-session-discovery-read-only.test.ts deleted file mode 100644 index 2e69857ecd2..00000000000 --- a/src/main/codex-accounts/runtime-home-session-discovery-read-only.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { existsSync, readdirSync, rmSync } from 'node:fs' -import type * as NodeOs from 'node:os' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createStore, - getRuntimeCodexHomePath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('Codex session discovery on a transcript lookup miss', () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it('creates no directories and reads no account ownership markers', async () => { - const accountHome = join(testState.userDataDir, 'codex-accounts', 'account-1', 'home') - const store = createStore( - createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath: accountHome, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] - }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only getSettings/updateSettings, which the harness store implements. - const service = new CodexRuntimeHomeService(store as never) - const { configureHostReadableTranscriptPathSources } = - await import('../native-chat/host-readable-transcript-path') - const { resolveSessionFilePath } = await import('../native-chat/session-file-resolver') - configureHostReadableTranscriptPathSources({ - getAdditionalCodexHomePaths: () => service.getHostCodexHomePathsForSessionDiscovery() - }) - - rmSync(join(testState.userDataDir, 'codex-runtime-home'), { recursive: true, force: true }) - rmSync(join(testState.userDataDir, 'codex-accounts'), { recursive: true, force: true }) - const before = readdirSync(testState.userDataDir).sort() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - try { - await expect(resolveSessionFilePath('codex', 'never-written-session')).resolves.toBeNull() - await expect(resolveSessionFilePath('codex', 'never-written-session')).resolves.toBeNull() - - expect(existsSync(getRuntimeCodexHomePath())).toBe(false) - expect(readdirSync(testState.userDataDir).sort()).toEqual(before) - - expect(warn).not.toHaveBeenCalled() - expect(service.getHostCodexHomePathsForSessionDiscovery()).toContain( - getRuntimeCodexHomePath() - ) - } finally { - warn.mockRestore() - configureHostReadableTranscriptPathSources({}) - } - }) -}) diff --git a/src/main/codex-accounts/runtime-home-session-migration-pass.test.ts b/src/main/codex-accounts/runtime-home-session-migration-pass.test.ts deleted file mode 100644 index 5eddf1dc90f..00000000000 --- a/src/main/codex-accounts/runtime-home-session-migration-pass.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import type * as NodeOs from 'node:os' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createStore, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' -import { getCodexSessionBackfillDate } from '../codex/history/backfill/codex-session-backfill-scan-dates' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -const CUSTOM_HISTORY_HOME = 'C:\\Users\\Me\\.codex' - -function getMarkerPath(): string { - return join(testState.userDataDir, 'codex-session-backfill', 'backfill-complete.json') -} - -function writeBaselineMarker(systemCodexHomePath: string, needsFullScan = false): void { - mkdirSync(join(testState.userDataDir, 'codex-session-backfill'), { recursive: true }) - writeFileSync( - getMarkerPath(), - `${JSON.stringify({ - version: 4, - systemSessionsRoot: join(systemCodexHomePath, 'sessions'), - coverage: 'full', - baselineScannedFiles: 5, - pendingScanDates: [], - needsFullScan, - summary: { scannedFiles: 5 } - })}\n`, - 'utf-8' - ) -} - -function readPendingScanDates(): unknown { - return (JSON.parse(readFileSync(getMarkerPath(), 'utf-8')) as { pendingScanDates?: unknown }) - .pendingScanDates -} - -describe('host system default session migration pass preparation', () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it('records the launch date and keeps the baseline instead of deleting it', async () => { - writeBaselineMarker(CUSTOM_HISTORY_HOME) - const store = createStore( - createSettings({ codexSessionSourceHome: { host: CUSTOM_HISTORY_HOME, wsl: {} } }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - expect(service.prepareHostSystemDefaultSessionMigrationPass()).toBe(false) - - expect(readPendingScanDates()).toEqual([getCodexSessionBackfillDate()]) - expect(JSON.parse(readFileSync(getMarkerPath(), 'utf-8'))).toMatchObject({ coverage: 'full' }) - }) - - it('does not demand a full scan when the same history home is spelled differently', async () => { - writeBaselineMarker(CUSTOM_HISTORY_HOME) - const store = createStore( - createSettings({ - codexSessionSourceHome: { host: CUSTOM_HISTORY_HOME, wsl: {} }, - realHomeRoutable: true - }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - expect(service.beginHostSystemDefaultSessionMigrationLaunch(null, { reattached: true })).toBe( - false - ) - - store.updateSettings({ - codexSessionSourceHome: { host: 'c:/users/me/.codex', wsl: {} } - }) - - expect(service.prepareHostSystemDefaultSessionMigrationPass()).toBe(false) - }) - - it('carries a full-scan demand persisted by an earlier launch into this pass', async () => { - writeBaselineMarker(CUSTOM_HISTORY_HOME, true) - const store = createStore( - createSettings({ codexSessionSourceHome: { host: CUSTOM_HISTORY_HOME, wsl: {} } }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - expect(service.prepareHostSystemDefaultSessionMigrationPass()).toBe(true) - - expect(JSON.parse(readFileSync(getMarkerPath(), 'utf-8'))).toMatchObject({ - needsFullScan: true - }) - }) - - it('still demands a full scan when the history home really moves', async () => { - writeBaselineMarker(CUSTOM_HISTORY_HOME) - const store = createStore( - createSettings({ - codexSessionSourceHome: { host: CUSTOM_HISTORY_HOME, wsl: {} }, - realHomeRoutable: true - }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - expect(service.beginHostSystemDefaultSessionMigrationLaunch(null, { reattached: true })).toBe( - false - ) - - store.updateSettings({ - codexSessionSourceHome: { host: 'C:\\Users\\Me\\moved-codex', wsl: {} } - }) - - expect(service.prepareHostSystemDefaultSessionMigrationPass()).toBe(true) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-settings-test-fixtures.ts b/src/main/codex-accounts/runtime-home-settings-test-fixtures.ts deleted file mode 100644 index 6f72382d583..00000000000 --- a/src/main/codex-accounts/runtime-home-settings-test-fixtures.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import { createCodexAccountSettings } from './codex-account-settings-fixture' -import { setRealHomeRoutableForTest, testState } from './runtime-home-service-test-harness' - -type TestSettingsOverrides = Partial & { - realHomeRoutable?: boolean -} - -export function createSettings(overrides: TestSettingsOverrides = {}): GlobalSettings { - // Default to the production custom-CODEX_HOME route for mirror-path assertions. - setRealHomeRoutableForTest(overrides.realHomeRoutable ?? false) - return createCodexAccountSettings(testState.fakeHomeDir, overrides) -} diff --git a/src/main/codex-accounts/runtime-home-status-hook-independence.test.ts b/src/main/codex-accounts/runtime-home-status-hook-independence.test.ts deleted file mode 100644 index 604531dc197..00000000000 --- a/src/main/codex-accounts/runtime-home-status-hook-independence.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import type * as NodeOs from 'node:os' -import type * as CodexCommand from '../codex-cli/command' -import type * as TrustDerivation from '../codex/trust/hooks/codex-hook-trust-derivation' -import type { CodexHookAnswer } from '../codex/trust/hooks/codex-hook-trust-derivation' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createStore, - getSystemCodexHomePath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -const mocks = vi.hoisted(() => ({ - codexPath: '', - probeCodexVersion: vi.fn<(codexPath: string) => Promise>(), - deriveCodexHookHashes: vi.fn() -})) - -vi.mock('electron', () => ({ app: { getPath: () => testState.userDataDir } })) -vi.mock('node:os', async (importOriginal) => ({ - ...(await importOriginal()), - homedir: () => testState.fakeHomeDir -})) -vi.mock('../codex-cli/command', async (importOriginal) => ({ - ...(await importOriginal()), - resolveCodexCommand: () => mocks.codexPath, - resolveCodexCommandForSpawn: async () => mocks.codexPath -})) -vi.mock('../codex/trust/hooks/codex-hook-trust-derivation', async (importOriginal) => ({ - ...(await importOriginal()), - probeCodexVersion: mocks.probeCodexVersion, - deriveCodexHookHashes: mocks.deriveCodexHookHashes -})) - -const hooksPath = (): string => join(getSystemCodexHomePath(), 'hooks.json') -const tomlPath = (): string => join(getSystemCodexHomePath(), 'config.toml') - -const HOOK_PROBLEMS: readonly [string, () => void][] = [ - [ - 'Codex is too old to approve hooks', - () => { - const failure = 'Codex 0.120.0 is too old for Orca status; update Codex' - mocks.deriveCodexHookHashes.mockResolvedValue({ - kind: 'refused', - codexVersion: 'codex-cli 0.120.0', - failure - } satisfies CodexHookAnswer) - } - ], - ['Codex is not installed', () => (mocks.codexPath = join(testState.fakeHomeDir, 'no-codex'))], - ['~/.codex/hooks.json does not parse', () => writeFileSync(hooksPath(), '{ not json')], - [ - '~/.codex/hooks.json has a root key Codex skips', - () => writeFileSync(hooksPath(), JSON.stringify({ hooks: {}, _managed: true })) - ], - [ - '~/.codex/config.toml keeps hook approvals inline', - () => writeFileSync(tomlPath(), 'model = "m"\nhooks = { state = {} }\n') - ] -] - -beforeEach(() => { - setupRuntimeHomeTest() - mocks.codexPath = join(testState.userDataDir, 'codex') - writeFileSync(mocks.codexPath, 'codex') - mocks.probeCodexVersion.mockResolvedValue('codex-cli 0.160.1') - mocks.deriveCodexHookHashes.mockResolvedValue({ - kind: 'hashes', - codexVersion: 'codex-cli 0.160.1', - hashes: { stop: 'sha256:codex-stop' } - } satisfies CodexHookAnswer) -}) - -afterEach(() => { - vi.restoreAllMocks() - teardownRuntimeHomeTest() -}) - -describe('a status-hook problem never moves the system default off ~/.codex', () => { - it.each(HOOK_PROBLEMS)('when %s', async (_case, arrange) => { - arrange() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const before = new Map( - [hooksPath(), tomlPath()].map((path) => [path, readOptional(path)] as const) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const { startCodexHooks, _internals } = - await import('../codex/hooks/reconciliation/codex-hook-reconcile') - const { readCurrentCodexHookStatus } = - await import('../codex/hooks/reconciliation/codex-hook-status') - const store = createStore(createSettings({ realHomeRoutable: true })) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only getSettings/updateSettings, which the harness store implements. - const service = new CodexRuntimeHomeService(store as never) - - startCodexHooks({ - pathReady: Promise.resolve(), - isEnabled: () => true, - resolveLaunchHome: () => service.resolveHostCodexHomePathForLaunchReadOnly() - }) - await _internals.settledForTesting() - - expect(service.isHostSystemDefaultRealHomeSelected()).toBe(true) - - expect(service.resolveHostCodexHomePathForLaunchReadOnly()).toBeNull() - await expect(service.prepareForCodexLaunchAsync()).resolves.toBeNull() - const status = readCurrentCodexHookStatus() - expect(status.configPath).toBe(hooksPath()) - expect(status.detail).toBeTruthy() - if (before.get(hooksPath()) !== null) { - expect(readOptional(hooksPath())).toBe(before.get(hooksPath())) - } - }) -}) - -function readOptional(path: string): string | null { - try { - return readFileSync(path, 'utf-8') - } catch { - return null - } -} diff --git a/src/main/codex-accounts/runtime-home-system-resource-materialization.test.ts b/src/main/codex-accounts/runtime-home-system-resource-materialization.test.ts deleted file mode 100644 index b968ccc00dc..00000000000 --- a/src/main/codex-accounts/runtime-home-system-resource-materialization.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - existsSync, - mkdirSync, - readFileSync, - realpathSync, - symlinkSync, - writeFileSync -} from 'node:fs' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createStore, - expectResourceLinkedOrCopied, - getRuntimeCodexHomePath, - getSystemCodexHomePath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -// Keep asserted config bytes independent of platform socket-path limits. -vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', - async (importOriginal) => ({ - ...(await importOriginal()), - applyCodexDaemonSocketGuard: (config: string) => config - }) -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexRuntimeHomeService', () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it('mirrors later system Codex config changes before launch', async () => { - const systemCodexHome = getSystemCodexHomePath() - mkdirSync(systemCodexHome, { recursive: true }) - writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "first"\n', 'utf-8') - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - service.prepareForCodexLaunch() - writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "second"\n', 'utf-8') - service.prepareForCodexLaunch() - - expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toBe( - 'model = "second"\n' - ) - }) - - it('rebases the bundled marketplace onto the canonical path of a symlinked managed home', async () => { - const systemMarketplace = join( - getSystemCodexHomePath(), - '.tmp', - 'bundled-marketplaces', - 'openai-bundled' - ) - mkdirSync(systemMarketplace, { recursive: true }) - writeFileSync( - join(getSystemCodexHomePath(), 'config.toml'), - `[marketplaces.openai-bundled]\nsource_type = "local"\nsource = '${systemMarketplace}'\n`, - 'utf-8' - ) - const linkedUserData = join(testState.fakeHomeDir, 'linked-user-data') - symlinkSync(testState.userDataDir, linkedUserData, 'junction') - process.env.ORCA_USER_DATA_PATH = linkedUserData - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - service.prepareForCodexLaunch() - - // Codex compares against its canonicalized CODEX_HOME, so the source must not keep the link. - const canonicalMarketplace = join( - realpathSync.native(testState.userDataDir), - 'codex-runtime-home', - 'home', - '.tmp', - 'bundled-marketplaces', - 'openai-bundled' - ) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toContain( - `source = '${canonicalMarketplace}'` - ) - expect(existsSync(canonicalMarketplace)).toBe(true) - }) - - it('starts the system Codex session bridge without replacing runtime sessions', async () => { - const systemMissingRuntimeSessionPath = join( - getSystemCodexHomePath(), - 'sessions', - '2026', - '05', - '26', - 'rollout-old.jsonl' - ) - const systemConflictSessionPath = join( - getSystemCodexHomePath(), - 'sessions', - '2026', - '05', - '26', - 'rollout-conflict.jsonl' - ) - const runtimeConflictSessionPath = join( - getRuntimeCodexHomePath(), - 'sessions', - '2026', - '05', - '26', - 'rollout-conflict.jsonl' - ) - mkdirSync(join(getSystemCodexHomePath(), 'sessions', '2026', '05', '26'), { recursive: true }) - mkdirSync(join(getRuntimeCodexHomePath(), 'sessions', '2026', '05', '26'), { - recursive: true - }) - writeFileSync(systemMissingRuntimeSessionPath, '{"id":"old"}\n', 'utf-8') - writeFileSync(systemConflictSessionPath, '{"id":"system-conflict"}\n', 'utf-8') - writeFileSync(runtimeConflictSessionPath, '{"id":"runtime-conflict"}\n', 'utf-8') - writeFileSync(join(getSystemCodexHomePath(), 'state_5.sqlite'), 'sqlite\n', 'utf-8') - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const { startSystemCodexSessionBridgeInBackground } = - await import('../codex/history/bridges/codex-session-bridge') - const service = new CodexRuntimeHomeService(store as never) - - service.prepareForCodexLaunch() - await startSystemCodexSessionBridgeInBackground() - - const runtimeMissingSessionPath = join( - getRuntimeCodexHomePath(), - 'sessions', - '2026', - '05', - '26', - 'rollout-old.jsonl' - ) - expect(readFileSync(runtimeMissingSessionPath, 'utf-8')).toBe('{"id":"old"}\n') - expectResourceLinkedOrCopied(runtimeMissingSessionPath, systemMissingRuntimeSessionPath) - expect(readFileSync(runtimeConflictSessionPath, 'utf-8')).toBe('{"id":"runtime-conflict"}\n') - expect(existsSync(join(getRuntimeCodexHomePath(), 'state_5.sqlite'))).toBe(false) - }) - - it('does not replace runtime-owned Codex files while linking user resources', async () => { - const systemCodexHome = getSystemCodexHomePath() - mkdirSync(join(systemCodexHome, 'sessions'), { recursive: true }) - mkdirSync(join(systemCodexHome, 'skills'), { recursive: true }) - writeFileSync(join(systemCodexHome, 'auth.json'), '{"account":"system"}\n', 'utf-8') - writeFileSync(join(systemCodexHome, 'hooks.json'), '{"hooks":{}}\n', 'utf-8') - writeFileSync(join(systemCodexHome, 'skills', 'system.md'), 'system\n', 'utf-8') - writeFileSync(join(getRuntimeCodexHomePath(), 'hooks.json'), '{"hooks":{"Stop":[]}}\n', 'utf-8') - writeFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), '{"id":"runtime"}\n', 'utf-8') - const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - service.prepareForCodexLaunch() - - expect(readFileSync(join(getRuntimeCodexHomePath(), 'auth.json'), 'utf-8')).toBe( - '{"account":"system"}\n' - ) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'hooks.json'), 'utf-8')).toBe( - '{"hooks":{"Stop":[]}}\n' - ) - expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( - '{"id":"runtime"}\n' - ) - expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions'))).toBe(false) - expectResourceLinkedOrCopied( - join(getRuntimeCodexHomePath(), 'skills'), - join(systemCodexHome, 'skills') - ) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-windows-profile-ownership.test.ts b/src/main/codex-accounts/runtime-home-windows-profile-ownership.test.ts deleted file mode 100644 index acfcc04e95c..00000000000 --- a/src/main/codex-accounts/runtime-home-windows-profile-ownership.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { __resetPowerShellProfileEnvCache } from '../pty/shell-startup/powershell-profile-env' -import { CodexRuntimeHomeService } from './runtime-home-service' - -// Keep the host's registry-named Documents directory outside the sandbox probe. -vi.mock('../windows/windows-native-registry', () => ({ - loadWindowsNativeRegistry: () => { - throw new Error('no registry in tests') - } -})) - -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') -const originalCodexHome = process.env.CODEX_HOME -const originalOrcaCodexHome = process.env.ORCA_CODEX_HOME -const temporaryProfiles: string[] = [] - -afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - restoreEnv('CODEX_HOME', originalCodexHome) - restoreEnv('ORCA_CODEX_HOME', originalOrcaCodexHome) - __resetPowerShellProfileEnvCache() - vi.unstubAllEnvs() - for (const path of temporaryProfiles.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } -}) - -describe('Windows System Default Codex home ownership', () => { - it('routes a user with no CODEX_HOME in any PowerShell profile to the real home', () => { - const service = createWindowsService() - - expect(service.isHostSystemDefaultRealHomeSelected({ USERPROFILE: createUserProfile() })).toBe( - true - ) - expect(service.isHostSystemDefaultSessionMigrationEligible()).toBe(true) - }) - - it('stays managed when a PowerShell profile points CODEX_HOME elsewhere (#9788)', () => { - const userProfile = createUserProfile() - const profileDir = join(userProfile, 'Documents', 'WindowsPowerShell') - mkdirSync(profileDir, { recursive: true }) - writeFileSync( - join(profileDir, 'Microsoft.PowerShell_profile.ps1'), - "$env:CODEX_HOME = 'C:\\custom-codex'\r\n" - ) - const service = createWindowsService() - - expect(service.isHostSystemDefaultRealHomeSelected({ USERPROFILE: userProfile })).toBe(false) - }) - - it('stays managed when a Git Bash login file exports CODEX_HOME elsewhere', () => { - const userProfile = createUserProfile() - writeFileSync(join(userProfile, '.bash_profile'), 'export CODEX_HOME="$HOME/custom-codex"\n') - const service = createWindowsService() - - expect(service.isHostSystemDefaultRealHomeSelected({ USERPROFILE: userProfile })).toBe(false) - }) -}) - -function createWindowsService(): CodexRuntimeHomeService { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - delete process.env.CODEX_HOME - delete process.env.ORCA_CODEX_HOME - const service = Object.create(CodexRuntimeHomeService.prototype) as CodexRuntimeHomeService - Object.defineProperty(service, 'store', { value: createStore() }) - return service -} - -function createUserProfile(): string { - const userProfile = mkdtempSync(join(tmpdir(), 'orca-win-profile-')) - temporaryProfiles.push(userProfile) - // Sandbox all-user profiles and process-wide path checks too. - vi.stubEnv('USERPROFILE', userProfile) - vi.stubEnv('SystemRoot', join(userProfile, 'Windows')) - vi.stubEnv('ProgramFiles', join(userProfile, 'Program Files')) - return userProfile -} - -function createStore() { - const settings = { - codexManagedAccounts: [], - activeCodexManagedAccountId: null, - activeCodexManagedAccountIdsByRuntime: { host: null, wsl: {} } - } as unknown as GlobalSettings - return { getSettings: () => settings } -} - -function restoreEnv(name: string, value: string | undefined): void { - if (value === undefined) { - delete process.env[name] - } else { - process.env[name] = value - } -} diff --git a/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts b/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts deleted file mode 100644 index 0c2a7b792c0..00000000000 --- a/src/main/codex-accounts/runtime-home-wsl-session-bridge.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { execFileSync } from 'node:child_process' -import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import type * as CodexConfigMirror from '../codex/configuration/settings/codex-config-mirror' -import type * as CodexHomePaths from '../codex/configuration/homes/codex-home-paths' -import type * as LegacyWslRuntimeAuthDrain from './legacy-wsl-runtime-auth-drain' -import type * as WslCodexAuthBatchReader from './wsl-codex-auth-batch-reader' -import type * as WslCodexSessionBridge from '../codex/history/bridges/wsl-codex-session-bridge' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createCodexAuthJson, - createManagedAuth, - createStore, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -// These launches are the user's own, so the E9 exec gate lets their prep run. -vi.mock('../wsl/discovery/wsl-background-exec-gate', () => ({ - blockedWslDistroForExec: async () => null -})) -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexRuntimeHomeService', () => { - beforeEach(() => { - setupRuntimeHomeTest() - }) - - afterEach(() => { - teardownRuntimeHomeTest() - }) - - it.skipIf(process.platform === 'win32')( - 'links retired WSL sessions only into the auth-matched direct home', - async () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const guestHome = join(testState.userDataDir, 'ubuntu-home') - const wslHome = `\\\\wsl.localhost\\Ubuntu${guestHome.replaceAll('/', '\\')}` - vi.doMock('../wsl/discovery/distro-catalog', () => ({ - getDefaultWslDistro: () => 'Ubuntu', - getWslHome: () => wslHome, - getWslHomeAsync: async () => wslHome - })) - const ownerAuth = createCodexAuthJson( - 'owner@example.com', - 'acct-owner', - 'owner-refresh', - 2_000 - ) - const selectedAuth = createCodexAuthJson( - 'selected@example.com', - 'acct-selected', - 'selected-refresh', - 2_000 - ) - const ownerHome = createManagedAuth(testState.userDataDir, 'owner', ownerAuth) - const selectedHome = createManagedAuth(testState.userDataDir, 'selected', selectedAuth) - vi.doMock('./wsl-codex-auth-batch-reader', async (importOriginal) => ({ - ...(await importOriginal()), - readWslCodexAuths: vi.fn(async (_distro: string, homes: string[]) => - homes.map((home) => { - if (home === ownerHome) { - return { kind: 'present' as const, contents: ownerAuth } - } - if (home === selectedHome) { - return { kind: 'present' as const, contents: selectedAuth } - } - return { kind: 'missing' as const } - }) - ) - })) - const drainTasks: Promise[] = [] - vi.doMock('../wsl/execution/wsl-runner', () => ({ - runWslProcess: vi.fn( - async (options: { args?: string[]; script: string; shell?: 'bash' }) => { - try { - const stdout = execFileSync(options.shell === 'bash' ? '/bin/bash' : '/bin/sh', [ - '-c', - options.script, - options.shell ?? 'sh', - ...(options.args ?? []) - ]).toString() - return { - code: 0, - stdout, - stderr: '', - timedOut: false, - environmentResolved: true - } - } catch (error) { - return { - code: (error as { status?: number }).status ?? 1, - stdout: (error as { stdout?: Buffer }).stdout?.toString() ?? '', - stderr: (error as { stderr?: Buffer }).stderr?.toString() ?? '', - timedOut: false, - environmentResolved: true - } - } - } - ) - })) - vi.doMock('./legacy-wsl-runtime-auth-drain', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - startLegacyWslRuntimeAuthDrain: ( - options: Parameters[0] - ) => { - const task = actual.startLegacyWslRuntimeAuthDrain(options) - drainTasks.push(task) - return task - } - } - }) - vi.doMock('../codex/configuration/homes/codex-home-paths', async (importOriginal) => ({ - ...(await importOriginal()), - syncCodexGlobalInstructionsIntoManagedHome: vi.fn() - })) - vi.doMock('../codex/configuration/settings/codex-config-mirror', async (importOriginal) => ({ - ...(await importOriginal()), - syncSystemConfigIntoManagedCodexHome: vi.fn() - })) - // Launch-time sibling bridging is covered elsewhere; this pins only the drain's own target. - vi.doMock('../codex/history/bridges/wsl-codex-session-bridge', async (importOriginal) => ({ - ...(await importOriginal()), - startWslCodexSessionBridgeInBackground: vi.fn(() => Promise.resolve()) - })) - const retiredHome = join(guestHome, '.local', 'share', 'orca', 'codex-runtime-home', 'home') - const relativeSessionPath = join('sessions', '2026', '08', '26', 'retired.jsonl') - const retiredSessionPath = join(retiredHome, relativeSessionPath) - mkdirSync(join(retiredSessionPath, '..'), { recursive: true }) - writeFileSync(join(retiredHome, 'auth.json'), ownerAuth, 'utf-8') - writeFileSync(retiredSessionPath, '{"session":"retired"}\n', 'utf-8') - const blockedTargetDirectory = join(ownerHome, 'sessions', '2026') - mkdirSync(join(blockedTargetDirectory, '..'), { recursive: true }) - writeFileSync(blockedTargetDirectory, 'not-a-directory\n', 'utf-8') - const store = createStore( - createSettings({ - codexManagedAccounts: [ - { - id: 'owner', - email: 'owner@example.com', - managedHomePath: ownerHome, - managedHomeRuntime: 'wsl', - wslDistro: 'Ubuntu', - wslLinuxHomePath: ownerHome, - providerAccountId: 'acct-owner', - workspaceLabel: null, - workspaceAccountId: 'acct-owner', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - }, - { - id: 'selected', - email: 'selected@example.com', - managedHomePath: selectedHome, - managedHomeRuntime: 'wsl', - wslDistro: 'Ubuntu', - wslLinuxHomePath: selectedHome, - providerAccountId: 'acct-selected', - workspaceLabel: null, - workspaceAccountId: 'acct-selected', - createdAt: 2, - updatedAt: 2, - lastAuthenticatedAt: 2 - } - ], - activeCodexManagedAccountIdsByRuntime: { - host: null, - wsl: { Ubuntu: 'selected' } - } - }) - ) - - try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - await Promise.all(drainTasks) - - const linkedSessionPath = join(ownerHome, relativeSessionPath) - expect(existsSync(linkedSessionPath)).toBe(false) - rmSync(blockedTargetDirectory) - - service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - await Promise.all(drainTasks) - expect(readFileSync(linkedSessionPath, 'utf-8')).toBe('{"session":"retired"}\n') - expect(statSync(linkedSessionPath).ino).toBe(statSync(retiredSessionPath).ino) - expect(existsSync(join(selectedHome, relativeSessionPath))).toBe(false) - - rmSync(linkedSessionPath) - rmSync(retiredHome, { recursive: true }) - service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - await Promise.all(drainTasks) - expect(existsSync(linkedSessionPath)).toBe(false) - } finally { - vi.doUnmock('../codex/history/bridges/wsl-codex-session-bridge') - vi.doUnmock('../codex/configuration/settings/codex-config-mirror') - vi.doUnmock('../codex/configuration/homes/codex-home-paths') - vi.doUnmock('./legacy-wsl-runtime-auth-drain') - vi.doUnmock('./wsl-codex-auth-batch-reader') - vi.doUnmock('../wsl/execution/wsl-runner') - vi.doUnmock('../wsl/discovery/distro-catalog') - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - } - } - ) -}) diff --git a/src/main/codex-accounts/runtime-home-managed-auth-recovery.test.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts similarity index 94% rename from src/main/codex-accounts/runtime-home-managed-auth-recovery.test.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts index a9a9be3edb7..57a0ba8a9bd 100644 --- a/src/main/codex-accounts/runtime-home-managed-auth-recovery.test.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAuthJson, createManagedAuth, @@ -12,11 +12,11 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' // Keep asserted config bytes independent of platform socket-path limits. vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', + '../../../codex/configuration/shared-server/codex-daemon-socket-path-guard', async (importOriginal) => ({ ...(await importOriginal()), applyCodexDaemonSocketGuard: (config: string) => config @@ -93,7 +93,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, account1Refreshed, 'utf-8') @@ -184,7 +184,7 @@ describe('CodexRuntimeHomeService', () => { }) ) const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(join(managedHomePath, 'auth.json'), '{"tokens":{"acc', 'utf-8') @@ -246,7 +246,7 @@ describe('CodexRuntimeHomeService', () => { activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, refreshedManagedAuth, 'utf-8') diff --git a/src/main/codex-accounts/runtime-home-mirror-login-copy.test.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-mirror-login-copy.test.ts similarity index 90% rename from src/main/codex-accounts/runtime-home-mirror-login-copy.test.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-mirror-login-copy.test.ts index 97b38d442fd..e1cf51df634 100644 --- a/src/main/codex-accounts/runtime-home-mirror-login-copy.test.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-mirror-login-copy.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createSettings } from './runtime-home-settings-test-fixtures' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAuthJson, createStore, @@ -11,12 +11,12 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' -import type { CodexRuntimeHomeService } from './runtime-home-service' -import type { GlobalSettings } from '../../shared/global-settings-types' +} from '../runtime-home-service-test-harness' +import type { CodexRuntimeHomeService } from '../../runtime-home-service' +import type { GlobalSettings } from '../../../../shared/global-settings-types' vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', + '../../../codex/configuration/shared-server/codex-daemon-socket-path-guard', async (importOriginal) => ({ ...(await importOriginal()), applyCodexDaemonSocketGuard: (config: string) => config @@ -42,7 +42,7 @@ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') const paneLogin = createCodexAuthJson('me@example.com', 'acct-me', 'pane-login') async function createService(settings: GlobalSettings): Promise { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only getSettings/updateSettings, which the harness store implements. return new CodexRuntimeHomeService(createStore(settings) as never) } diff --git a/src/main/codex-accounts/runtime-home-retained-auth-provenance.test.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-retained-auth-provenance.test.ts similarity index 80% rename from src/main/codex-accounts/runtime-home-retained-auth-provenance.test.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-retained-auth-provenance.test.ts index 5019348f5b5..10025f79c48 100644 --- a/src/main/codex-accounts/runtime-home-retained-auth-provenance.test.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-retained-auth-provenance.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' + +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAuthJson, createManagedAuth, @@ -15,11 +15,11 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' // Keep asserted config bytes independent of platform socket-path limits. vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', + '../../../codex/configuration/shared-server/codex-daemon-socket-path-guard', async (importOriginal) => ({ ...(await importOriginal()), applyCodexDaemonSocketGuard: (config: string) => config @@ -71,7 +71,7 @@ describe('CodexRuntimeHomeService', () => { ] }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) setRealHomeRoutableForTest(true) @@ -98,7 +98,7 @@ describe('CodexRuntimeHomeService', () => { ) writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(systemAuth) @@ -122,7 +122,7 @@ describe('CodexRuntimeHomeService', () => { ) writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: true })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(getRuntimeCodexAuthPath(), retainedAuth, 'utf-8') writeFileSync(getSystemCodexAuthPath(), refreshedSystemAuth, 'utf-8') @@ -140,7 +140,7 @@ describe('CodexRuntimeHomeService', () => { const retainedAuth = createCodexAuthJson('system@example.com', 'acct-system', 'retained-token') writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) setRealHomeRoutableForTest(true) @@ -164,7 +164,7 @@ describe('CodexRuntimeHomeService', () => { ) writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync( getSharedRuntimeAuthProvenancePath(), @@ -188,7 +188,7 @@ describe('CodexRuntimeHomeService', () => { const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) const runtimeAuthPath = getRuntimeCodexAuthPath() const heldAuthPath = `${runtimeAuthPath}.orca-guarded` @@ -206,7 +206,7 @@ describe('CodexRuntimeHomeService', () => { const retainedAuth = createCodexAuthJson('shared@example.com', 'acct-shared', 'retained') writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync( getSharedRuntimeAuthProvenancePath(), @@ -236,7 +236,7 @@ describe('CodexRuntimeHomeService', () => { ) writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(getSharedRuntimeAuthProvenancePath(), '{"owner":"pending"}\n') @@ -254,7 +254,7 @@ describe('CodexRuntimeHomeService', () => { const reloginAuth = createCodexAuthJson('system@example.com', 'acct-system', 'relogin-token') writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) setRealHomeRoutableForTest(true) @@ -273,41 +273,4 @@ describe('CodexRuntimeHomeService', () => { }) expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(reloginAuth) }) - - it.each([ - ['committed provenance', false], - ['pre-provenance migration', true] - ])( - 'recreates retained auth after a %s crash between logout deletion and metadata commit', - async (_label, removeProvenance) => { - const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'old-token') - const reloginAuth = createCodexAuthJson('system@example.com', 'acct-system', 'relogin-token') - writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') - const store = createStore(createSettings({ realHomeRoutable: false })) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - new CodexRuntimeHomeService(store as never) - - setRealHomeRoutableForTest(true) - rmSync(getSystemCodexAuthPath()) - rmSync(getRuntimeCodexAuthPath()) - if (removeProvenance) { - rmSync(getSharedRuntimeAuthProvenancePath()) - } - rmSync( - join(testState.userDataDir, 'codex-runtime-home', 'system-default-runtime-logout.json'), - { - force: true - } - ) - const restartedService = new CodexRuntimeHomeService(store as never) - - expect(existsSync(getRuntimeCodexAuthPath())).toBe(false) - writeFileSync(getSystemCodexAuthPath(), reloginAuth, 'utf-8') - expect(restartedService.prepareForRateLimitFetch()).toEqual({ - kind: 'ready', - codexHomePath: getSystemCodexHomePath() - }) - expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(reloginAuth) - } - ) }) diff --git a/src/main/codex-accounts/runtime-home-service-auth-core.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-core.ts similarity index 93% rename from src/main/codex-accounts/runtime-home-service-auth-core.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-core.ts index 334f037b67b..48220ce9bdd 100644 --- a/src/main/codex-accounts/runtime-home-service-auth-core.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-core.ts @@ -1,17 +1,17 @@ import { existsSync, chmodSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { writeFileAtomically, writeFileAtomicallyIfUnchanged -} from '../filesystem/atomic-file-publication' +} from '../../../filesystem/atomic-file-publication' import type { CodexRuntimeLogoutMarker, CodexRuntimeLogoutMarkerStatus, CodexSharedRuntimeAuthProvenance -} from './runtime-home-service-types' -import { CodexRuntimeHomeLegacyMigration } from './runtime-home-service-legacy-migration' +} from '../runtime-home-service-types' +import { CodexRuntimeHomeLegacyMigration } from '../legacy-host/runtime-home-service-legacy-migration' export abstract class CodexRuntimeHomeAuthCore extends CodexRuntimeHomeLegacyMigration { protected readSystemDefaultAuth(): string | null { diff --git a/src/main/codex-accounts/runtime-home-service-auth-provenance.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-provenance.ts similarity index 98% rename from src/main/codex-accounts/runtime-home-service-auth-provenance.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-provenance.ts index 3df992f3e44..150088855fd 100644 --- a/src/main/codex-accounts/runtime-home-service-auth-provenance.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-provenance.ts @@ -1,12 +1,12 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' import type { CodexSharedRuntimeAuthPendingProvenance, CodexSharedRuntimeAuthProvenance, CodexSharedRuntimeAuthProvenanceFile, CodexSharedRuntimeAuthProvenanceStatus, CodexSystemDefaultSnapshot -} from './runtime-home-service-types' +} from '../runtime-home-service-types' import { CodexRuntimeHomeAuthCore } from './runtime-home-service-auth-core' export abstract class CodexRuntimeHomeAuthProvenance extends CodexRuntimeHomeAuthCore { diff --git a/src/main/codex-accounts/runtime-home-service-auth-sync-identity.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync-identity.ts similarity index 93% rename from src/main/codex-accounts/runtime-home-service-auth-sync-identity.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync-identity.ts index d0fa50fa5ec..195fedf009f 100644 --- a/src/main/codex-accounts/runtime-home-service-auth-sync-identity.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync-identity.ts @@ -1,4 +1,4 @@ -import { codexAuthIsFresher } from './codex-auth-identity' +import { codexAuthIsFresher } from '../../credentials/codex-auth-identity' function readCodexLastRefresh(authJson: string): number | null { try { diff --git a/src/main/codex-accounts/runtime-home-service-auth-sync.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts similarity index 97% rename from src/main/codex-accounts/runtime-home-service-auth-sync.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts index 1b8c6b00e90..23047c780e2 100644 --- a/src/main/codex-accounts/runtime-home-service-auth-sync.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts @@ -1,13 +1,13 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { dirname, join } from 'node:path' -import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' +import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' import { removeFileAtomicallyIfUnchanged, writeFileAtomically, writeFileAtomicallyIfUnchanged -} from '../filesystem/atomic-file-publication' -import { CodexRuntimeHomeLaunch } from './runtime-home-service-launch' -import type { CodexSystemDefaultSnapshot } from './runtime-home-service-types' +} from '../../../filesystem/atomic-file-publication' +import { CodexRuntimeHomeLaunch } from '../routing/runtime-home-service-launch' +import type { CodexSystemDefaultSnapshot } from '../runtime-home-service-types' export abstract class CodexRuntimeHomeAuthSync extends CodexRuntimeHomeLaunch { protected captureSystemDefaultSnapshot(options: { force: boolean }): void { diff --git a/src/main/codex-accounts/runtime-home-service-wsl-core.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts similarity index 91% rename from src/main/codex-accounts/runtime-home-service-wsl-core.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts index bc09598e84a..70353705396 100644 --- a/src/main/codex-accounts/runtime-home-service-wsl-core.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts @@ -4,11 +4,11 @@ import { codexAuthCouldBelongToManagedAccount, codexAuthMatchesManagedAccount, codexAuthMatchesSystemDefaultIdentity -} from './codex-auth-identity' -import { parseWslUncPath } from '../../shared/wsl-paths' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import type { CodexReadBackMatch } from './runtime-home-service-types' -import type { WslCodexAuthRead } from './wsl-codex-auth-batch-reader' +} from '../../credentials/codex-auth-identity' +import { parseWslUncPath } from '../../../../shared/wsl-paths' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import type { CodexReadBackMatch } from '../runtime-home-service-types' +import type { WslCodexAuthRead } from '../wsl/wsl-codex-auth-batch-reader' import { CodexRuntimeHomeAuthProvenance } from './runtime-home-service-auth-provenance' export abstract class CodexRuntimeHomeWslCore extends CodexRuntimeHomeAuthProvenance { diff --git a/src/main/codex-accounts/runtime-home-system-default-mirror-readback.test.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-mirror-readback.test.ts similarity index 90% rename from src/main/codex-accounts/runtime-home-system-default-mirror-readback.test.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-mirror-readback.test.ts index d7e7f754d0c..44d87a44155 100644 --- a/src/main/codex-accounts/runtime-home-system-default-mirror-readback.test.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-mirror-readback.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { chmodSync, existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAuthJson, createManagedAuth, @@ -13,7 +13,7 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' vi.mock('electron', () => ({ app: { @@ -44,7 +44,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(runtimeAuthPath, '{"account":"original"}\n', 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, '{"account":"external-switch"}\n', 'utf-8') @@ -64,7 +64,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, refreshedAuth, 'utf-8') @@ -101,7 +101,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, refreshedAuth, 'utf-8') @@ -132,7 +132,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, staleRuntimeAuth, 'utf-8') @@ -150,7 +150,7 @@ describe('CodexRuntimeHomeService', () => { const settings = createSettings() const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) rmSync(runtimeAuthPath, { force: true }) @@ -171,7 +171,7 @@ describe('CodexRuntimeHomeService', () => { const settings = createSettings() const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) rmSync(runtimeAuthPath, { force: true }) @@ -193,7 +193,7 @@ describe('CodexRuntimeHomeService', () => { const settings = createSettings() const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) rmSync(getSystemCodexAuthPath(), { force: true }) @@ -210,7 +210,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) writeFileSync(runtimeAuthPath, refreshedAuth, 'utf-8') @@ -253,7 +253,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) settings.activeCodexManagedAccountId = 'account-1' @@ -277,7 +277,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) chmodSync(runtimeAuthPath, 0o644) service.syncForCurrentSelection() diff --git a/src/main/codex-accounts/runtime-home-system-default-snapshot.test.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-snapshot.test.ts similarity index 92% rename from src/main/codex-accounts/runtime-home-system-default-snapshot.test.ts rename to src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-snapshot.test.ts index dafddc6143f..6432bbc4593 100644 --- a/src/main/codex-accounts/runtime-home-system-default-snapshot.test.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-system-default-snapshot.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAccountRecord, createCodexAuthJson, @@ -15,7 +15,7 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' vi.mock('electron', () => ({ app: { @@ -81,7 +81,7 @@ describe('CodexRuntimeHomeService', () => { }) ) vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) expect(readFileSync(join(homeX2, 'auth.json'), 'utf-8')).toBe(authX) @@ -110,7 +110,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) settings.activeCodexManagedAccountId = null @@ -142,7 +142,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) settings.activeCodexManagedAccountId = 'account-1' service.syncForCurrentSelection() @@ -171,7 +171,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) expect(store.updateSettings).toHaveBeenCalledWith( @@ -206,7 +206,7 @@ describe('CodexRuntimeHomeService', () => { }) ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) expect(readFileSync(managedAuthPath, 'utf-8')).toBe(refreshedAuth) @@ -237,7 +237,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) settings.activeCodexManagedAccountId = 'account-1' @@ -277,7 +277,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) rmSync(runtimeAuthPath, { force: true }) @@ -313,7 +313,7 @@ describe('CodexRuntimeHomeService', () => { }) const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) settings.activeCodexManagedAccountId = null diff --git a/src/main/codex-accounts/legacy-shared-auth-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.test.ts similarity index 97% rename from src/main/codex-accounts/legacy-shared-auth-migration.test.ts rename to src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.test.ts index 4b55aee3113..358c5f548bd 100644 --- a/src/main/codex-accounts/legacy-shared-auth-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.test.ts @@ -11,14 +11,14 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import type * as CodexAccountFs from '../filesystem/atomic-file-publication' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import type * as CodexAccountFs from '../../../filesystem/atomic-file-publication' const writeFailure = vi.hoisted(() => ({ failNextAuthWrite: false })) -vi.mock('../filesystem/atomic-file-publication', async () => { +vi.mock('../../../filesystem/atomic-file-publication', async () => { const actual = await vi.importActual( - '../filesystem/atomic-file-publication' + '../../../filesystem/atomic-file-publication' ) return { ...actual, diff --git a/src/main/codex-accounts/legacy-shared-auth-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts similarity index 93% rename from src/main/codex-accounts/legacy-shared-auth-migration.ts rename to src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts index 9d279f26965..e26abea0ff0 100644 --- a/src/main/codex-accounts/legacy-shared-auth-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts @@ -1,9 +1,12 @@ import { lstatSync, readFileSync } from 'node:fs' import { join } from 'node:path' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { assertOwnedHostCodexManagedHomePath } from './host-codex-managed-home-ownership' -import { codexAuthMatchesManagedAccount, compareCodexAuthFreshness } from './codex-auth-identity' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { assertOwnedHostCodexManagedHomePath } from '../../managed-homes/host-codex-managed-home-ownership' +import { + codexAuthMatchesManagedAccount, + compareCodexAuthFreshness +} from '../../credentials/codex-auth-identity' export const LEGACY_SHARED_AUTH_MIGRATION_MARKER = 'per-account-auth-migration-v1.json' // MCP migration needs its own marker for upgrades that already completed auth-only migration (#8440). diff --git a/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.test.ts similarity index 88% rename from src/main/codex-accounts/legacy-shared-config-compatibility.test.ts rename to src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.test.ts index d4bb7857232..e83c1cefa6c 100644 --- a/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join } from 'node:path' import { syncLegacySharedCodexConfigForRetainedPanes } from './legacy-shared-config-compatibility' -import type * as FsUtils from '../filesystem/atomic-file-publication' +import type * as FsUtils from '../../../filesystem/atomic-file-publication' const generationRace = vi.hoisted(() => ({ path: null as string | null, @@ -12,14 +12,14 @@ const generationRace = vi.hoisted(() => ({ // Keep asserted config bytes independent of platform socket-path limits. vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', + '../../../codex/configuration/shared-server/codex-daemon-socket-path-guard', async (importOriginal) => ({ ...(await importOriginal()), applyCodexDaemonSocketGuard: (config: string) => config }) ) -vi.mock('../filesystem/atomic-file-publication', async (importOriginal) => { +vi.mock('../../../filesystem/atomic-file-publication', async (importOriginal) => { const actual = await importOriginal() return { ...actual, @@ -164,19 +164,4 @@ describe('legacy shared Codex config compatibility', () => { expect(readFileSync(runtimeConfigPath, 'utf-8')).toBe(concurrentConfig) }) - - it('does not block real-home launch when compatibility config refresh fails', () => { - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "canonical"\n', 'utf-8') - mkdirSync(join(sharedRuntimeHome, 'config.toml')) - - expect(() => - syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome }) - ).not.toThrow() - - expect(warnSpy).toHaveBeenCalledWith( - '[codex-runtime-home] Failed to refresh legacy shared config:', - expect.anything() - ) - }) }) diff --git a/src/main/codex-accounts/legacy-shared-config-compatibility.ts b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts similarity index 81% rename from src/main/codex-accounts/legacy-shared-config-compatibility.ts rename to src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts index bf388e546f1..69d1212c614 100644 --- a/src/main/codex-accounts/legacy-shared-config-compatibility.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts @@ -1,8 +1,8 @@ import { getOrcaManagedCodexHomePath, getSystemCodexHomePath -} from '../codex/configuration/homes/codex-home-paths' -import { syncSystemConfigIntoLegacySharedCodexHome } from '../codex/configuration/settings/codex-config-mirror' +} from '../../../codex/configuration/homes/codex-home-paths' +import { syncSystemConfigIntoLegacySharedCodexHome } from '../../../codex/configuration/settings/codex-config-mirror' type LegacySharedCodexConfigPaths = { sharedRuntimeHome: string diff --git a/src/main/codex-accounts/runtime-home-legacy-migration.test.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts similarity index 89% rename from src/main/codex-accounts/runtime-home-legacy-migration.test.ts rename to src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts index a5cc60d8fe5..df651083465 100644 --- a/src/main/codex-accounts/runtime-home-legacy-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-legacy-migration.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { existsSync, mkdirSync, @@ -9,7 +9,7 @@ import { writeFileSync } from 'node:fs' import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createManagedAuth, createStore, @@ -20,7 +20,7 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' vi.mock('electron', () => ({ app: { @@ -66,7 +66,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) expect(normalizeLinkTarget(readlinkSync(legacyActiveHomePath))).toBe( @@ -93,7 +93,7 @@ describe('CodexRuntimeHomeService', () => { ) const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) expect(readFileSync(runtimeHistoryPath, 'utf-8')).toBe( @@ -113,7 +113,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(join(managedHomePath, 'history.jsonl'), '{"id":"legacy-1"}\n', 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) const runtimeHistoryPath = join(getRuntimeCodexHomePath(), 'history.jsonl') @@ -126,7 +126,7 @@ describe('CodexRuntimeHomeService', () => { ) vi.resetModules() - const mod2 = await import('./runtime-home-service') + const mod2 = await import('../../runtime-home-service') new mod2.CodexRuntimeHomeService(store as never) expect(readFileSync(runtimeHistoryPath, 'utf-8')).not.toContain('legacy-2') @@ -150,7 +150,7 @@ describe('CodexRuntimeHomeService', () => { writeFileSync(join(legacySessionsDir, 'nested', 'session.json'), '{"turns":[2,3]}', 'utf-8') const store = createStore(createSettings()) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') new CodexRuntimeHomeService(store as never) expect(readFileSync(join(runtimeSessionsDir, 'session.json'), 'utf-8')).toBe('{"turns":[1]}') diff --git a/src/main/codex-accounts/runtime-home-service-legacy-migration.ts b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts similarity index 95% rename from src/main/codex-accounts/runtime-home-service-legacy-migration.ts rename to src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts index 393f63e6a04..860b7ca558d 100644 --- a/src/main/codex-accounts/runtime-home-service-legacy-migration.ts +++ b/src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts @@ -8,11 +8,11 @@ import { statSync } from 'node:fs' import { dirname, extname, join, parse, relative } from 'node:path' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' import { migrateLegacySharedAuthToPerAccountHome } from './legacy-shared-auth-migration' -import { normalizeCodexRuntimeSelection } from './runtime-selection' -import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' -import { CodexRuntimeHomePaths } from './runtime-home-service-paths' +import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' +import { getSystemCodexHomePath } from '../../../codex/configuration/homes/codex-home-paths' +import { CodexRuntimeHomePaths } from '../runtime-home-service-paths' export abstract class CodexRuntimeHomeLegacyMigration extends CodexRuntimeHomePaths { protected safeMigrateLegacySharedAuth(): void { diff --git a/src/main/codex-accounts/codex-history-sharing.ts b/src/main/codex-accounts/runtime-home/routing/codex-history-sharing.ts similarity index 78% rename from src/main/codex-accounts/codex-history-sharing.ts rename to src/main/codex-accounts/runtime-home/routing/codex-history-sharing.ts index 9474e377485..00b4aa9a0c9 100644 --- a/src/main/codex-accounts/codex-history-sharing.ts +++ b/src/main/codex-accounts/runtime-home/routing/codex-history-sharing.ts @@ -1,4 +1,4 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' /** Whether Orca may link Codex sessions between account homes and ~/.codex; absent means on. */ export function isCodexHistorySharedAcrossAccounts( diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-per-account-homes.test.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-per-account-homes.test.ts new file mode 100644 index 00000000000..49d25f5055a --- /dev/null +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-per-account-homes.test.ts @@ -0,0 +1,153 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { createSettings } from '../runtime-home-settings-test-fixtures' +import { + createCodexAuthJson, + createManagedAuth, + createStore, + getRuntimeCodexAuthPath, + getSystemCodexAuthPath, + getSystemCodexHomePath, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from '../runtime-home-service-test-harness' + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) +beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) + +vi.mock(import('node:os'), async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +describe('CodexRuntimeHomeService', () => { + beforeEach(() => { + setupRuntimeHomeTest() + }) + + afterEach(() => { + teardownRuntimeHomeTest() + }) + + it.each(['two@example.com', 'one@example.com'])( + 'isolates account homes when the second email is %s', + async (secondEmail) => { + writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') + const account1Auth = createCodexAuthJson('one@example.com', 'acct-1', 'one') + const account2Auth = createCodexAuthJson(secondEmail, 'acct-2', 'two') + const home1 = createManagedAuth(testState.userDataDir, 'account-1', account1Auth) + const home2 = createManagedAuth(testState.userDataDir, 'account-2', account2Auth) + const settings = createSettings({ + realHomeRoutable: true, + codexManagedAccounts: [ + { + id: 'account-1', + email: 'one@example.com', + managedHomePath: home1, + providerAccountId: 'acct-1', + workspaceLabel: null, + workspaceAccountId: 'acct-1', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + }, + { + id: 'account-2', + email: secondEmail, + managedHomePath: home2, + providerAccountId: 'acct-2', + workspaceLabel: null, + workspaceAccountId: 'acct-2', + createdAt: 2, + updatedAt: 2, + lastAuthenticatedAt: 2 + } + ], + activeCodexManagedAccountId: 'account-1', + activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } + }) + const store = createStore(settings) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + + expect(service.prepareForCodexLaunch()).toBe(home1) + settings.activeCodexManagedAccountId = 'account-2' + settings.activeCodexManagedAccountIdsByRuntime = { host: 'account-2', wsl: {} } + expect(service.prepareForCodexLaunch()).toBe(home2) + expect( + service.prepareForCodexLaunch(undefined, undefined, { + unavailableManagedHomePath: home1 + }) + ).toBe(home2) + expect(store.updateSettings).not.toHaveBeenCalled() + + expect(readFileSync(join(home1, 'auth.json'), 'utf-8')).toBe(account1Auth) + expect(readFileSync(join(home2, 'auth.json'), 'utf-8')).toBe(account2Auth) + expect(existsSync(getRuntimeCodexAuthPath())).toBe(false) + } + ) + + it('does not read shared auth when polling observes a managed-to-real-home transition', async () => { + const runtimeAuthPath = getRuntimeCodexAuthPath() + const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') + const managedAuth = createCodexAuthJson('user@example.com', 'acct-user', 'managed', 1) + const refreshedManagedAuth = createCodexAuthJson( + 'user@example.com', + 'acct-user', + 'refreshed', + 2 + ) + writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') + const managedHomePath = createManagedAuth(testState.userDataDir, 'account-1', managedAuth) + const settings = createSettings({ + realHomeRoutable: true, + codexManagedAccounts: [ + { + id: 'account-1', + email: 'user@example.com', + managedHomePath, + providerAccountId: 'acct-user', + workspaceLabel: null, + workspaceAccountId: 'acct-user', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } + ], + activeCodexManagedAccountId: 'account-1', + activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } + }) + const store = createStore(settings) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + writeFileSync(runtimeAuthPath, refreshedManagedAuth, 'utf-8') + settings.activeCodexManagedAccountId = null + settings.activeCodexManagedAccountIdsByRuntime = { host: null, wsl: {} } + const syncSpy = vi.spyOn(service, 'syncForCurrentSelection') + + expect(service.prepareForRateLimitFetch()).toEqual({ + kind: 'ready', + codexHomePath: getSystemCodexHomePath() + }) + expect(readFileSync(join(managedHomePath, 'auth.json'), 'utf-8')).toBe(managedAuth) + expect(readFileSync(getSystemCodexAuthPath(), 'utf-8')).toBe(systemAuth) + expect(syncSpy).not.toHaveBeenCalled() + + expect(service.prepareForRateLimitFetch()).toEqual({ + kind: 'ready', + codexHomePath: getSystemCodexHomePath() + }) + expect(service.prepareForCodexLaunch()).toBeNull() + expect(syncSpy).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-real-home-lane-routing.test.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-real-home-lane-routing.test.ts new file mode 100644 index 00000000000..572e7ffc7a5 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-real-home-lane-routing.test.ts @@ -0,0 +1,120 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { createSettings } from '../runtime-home-settings-test-fixtures' +import { + createCodexAuthJson, + createStore, + getRuntimeCodexAuthPath, + getRuntimeCodexHomePath, + getSystemCodexAuthPath, + getSystemCodexHomePath, + setRealHomeRoutableForTest, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from '../runtime-home-service-test-harness' + +// Keep asserted config bytes independent of platform socket-path limits. +vi.mock( + '../../../codex/configuration/shared-server/codex-daemon-socket-path-guard', + async (importOriginal) => ({ + ...(await importOriginal()), + applyCodexDaemonSocketGuard: (config: string) => config + }) +) + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) +beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) + +vi.mock(import('node:os'), async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +describe('CodexRuntimeHomeService', () => { + beforeEach(() => { + setupRuntimeHomeTest() + }) + + afterEach(() => { + teardownRuntimeHomeTest() + }) + + it('seeds shared auth for a pane-local custom home on the real-home lane', async () => { + const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system-token') + writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') + const store = createStore(createSettings({ realHomeRoutable: true })) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + const customHome = join(testState.fakeHomeDir, 'pane-custom-codex-home') + + expect(service.prepareForCodexLaunch(undefined, { CODEX_HOME: customHome })).toBe( + getRuntimeCodexHomePath() + ) + expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(systemAuth) + }) + + it('keeps pre-rollout shared-home panes authenticated on the real-home lane', async () => { + const oldSystemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'old-system') + const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') + const systemConfig = [ + 'model_provider = "codex-lb"', + '', + '[model_providers.codex-lb]', + 'base_url = "https://codex-lb.example.test/v1"', + 'requires_openai_auth = true', + '' + ].join('\n') + writeFileSync(getSystemCodexAuthPath(), oldSystemAuth, 'utf-8') + const store = createStore(createSettings({ realHomeRoutable: false })) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + new CodexRuntimeHomeService(store as never) + expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(oldSystemAuth) + + setRealHomeRoutableForTest(true) + writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') + writeFileSync(join(getSystemCodexHomePath(), 'config.toml'), systemConfig, 'utf-8') + writeFileSync( + join(getRuntimeCodexHomePath(), 'config.toml'), + 'model_provider = "stale-provider"\n', + 'utf-8' + ) + + const service = new CodexRuntimeHomeService(store as never) + + expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(oldSystemAuth) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toContain( + 'stale-provider' + ) + service.reconcileLegacySharedHomeForRetainedPanes() + expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(systemAuth) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toBe(systemConfig) + expect(service.prepareForCodexLaunch()).toBeNull() + }) + + it('preserves retained managed auth across a real-home main-process restart', async () => { + const systemAuth = createCodexAuthJson('system@example.com', 'acct-system', 'system') + const managedAuth = createCodexAuthJson('managed@example.com', 'acct-managed', 'managed') + writeFileSync(getSystemCodexAuthPath(), systemAuth, 'utf-8') + const store = createStore(createSettings({ realHomeRoutable: false })) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + new CodexRuntimeHomeService(store as never) + writeFileSync(getRuntimeCodexAuthPath(), managedAuth, 'utf-8') + + setRealHomeRoutableForTest(true) + const restartedService = new CodexRuntimeHomeService(store as never) + + expect(restartedService.prepareForCodexLaunch()).toBeNull() + expect(readFileSync(getRuntimeCodexAuthPath(), 'utf-8')).toBe(managedAuth) + expect(readFileSync(getSystemCodexAuthPath(), 'utf-8')).toBe(systemAuth) + }) +}) diff --git a/src/main/codex-accounts/runtime-home-service-home-routing.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts similarity index 89% rename from src/main/codex-accounts/runtime-home-service-home-routing.ts rename to src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts index 45b0fffad16..cf0d2bb0035 100644 --- a/src/main/codex-accounts/runtime-home-service-home-routing.ts +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts @@ -1,30 +1,30 @@ import { posix as pathPosix } from 'node:path' -import { parseWslUncPath, toLinuxPath, toWindowsWslUncPath } from '../../shared/wsl-paths' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import { getDefaultWslDistro, getWslHome } from '../wsl/discovery/distro-catalog' -import { getCachedWslHome } from '../wsl/discovery/wsl-home-cache' -import { isWslDistroRunning } from '../wsl/discovery/wsl-background-distro-gate' +import { parseWslUncPath, toLinuxPath, toWindowsWslUncPath } from '../../../../shared/wsl-paths' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' +import { getDefaultWslDistro, getWslHome } from '../../../wsl/discovery/distro-catalog' +import { getCachedWslHome } from '../../../wsl/discovery/wsl-home-cache' +import { isWslDistroRunning } from '../../../wsl/discovery/wsl-background-distro-gate' import { getSystemCodexHomePath, resolveOrcaManagedCodexHomePath, syncCodexGlobalInstructionsIntoManagedHome, syncSystemCodexResourcesIntoManagedHome -} from '../codex/configuration/homes/codex-home-paths' -import { syncSystemConfigIntoManagedCodexHome } from '../codex/configuration/settings/codex-config-mirror' +} from '../../../codex/configuration/homes/codex-home-paths' +import { syncSystemConfigIntoManagedCodexHome } from '../../../codex/configuration/settings/codex-config-mirror' +import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { getWslSelectionKey, - normalizeCodexRuntimeSelection, type CodexAccountSelectionTarget -} from './runtime-selection' -import { hasCustomCodexHomeOverrideForLaunch } from '../codex/configuration/homes/codex-real-home-path' +} from '../../../../shared/codex-selection-lane' +import { hasCustomCodexHomeOverrideForLaunch } from '../../../codex/configuration/homes/codex-real-home-path' import { hasRecordedLegacySharedCodexPane, getCodexPaneAccount -} from '../codex/configuration/homes/codex-pane-account-registry' -import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' -import { syncLegacySharedCodexConfigForRetainedPanes } from './legacy-shared-config-compatibility' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import type { CodexRateLimitHomeResolution } from './runtime-home-service-types' +} from '../../../codex/configuration/homes/codex-pane-account-registry' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../../managed-homes/host-codex-managed-home-ownership' +import { syncLegacySharedCodexConfigForRetainedPanes } from '../legacy-host/legacy-shared-config-compatibility' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import type { CodexRateLimitHomeResolution } from '../runtime-home-service-types' import { CodexRuntimeHomeManagedHome } from './runtime-home-service-managed-home' export abstract class CodexRuntimeHomeRouting extends CodexRuntimeHomeManagedHome { diff --git a/src/main/codex-accounts/runtime-home-service-launch.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts similarity index 84% rename from src/main/codex-accounts/runtime-home-service-launch.ts rename to src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts index e1a4dce2ea5..2aaa0987970 100644 --- a/src/main/codex-accounts/runtime-home-service-launch.ts +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts @@ -1,27 +1,25 @@ -import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { startSystemCodexSessionBridgeInBackground } from '../codex/history/bridges/codex-session-bridge' -import { startCodexAccountSessionBridgeInBackground } from '../codex/history/bridges/codex-account-session-bridge' +import { resolveHostCodexSessionSourceHome } from '../../../codex/history/rollouts/codex-session-source-home' +import { startSystemCodexSessionBridgeInBackground } from '../../../codex/history/bridges/codex-session-bridge' +import { startCodexAccountSessionBridgeInBackground } from '../../../codex/history/bridges/codex-account-session-bridge' import { isCodexHistorySharedAcrossAccounts } from './codex-history-sharing' import { getSystemCodexHomePath, resolveOrcaManagedCodexHomePath, syncSystemCodexResourcesIntoManagedHome -} from '../codex/configuration/homes/codex-home-paths' -import { syncSystemConfigIntoManagedCodexHome } from '../codex/configuration/settings/codex-config-mirror' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import { - normalizeCodexRuntimeSelection, - type CodexAccountSelectionTarget -} from './runtime-selection' -import { hasCustomCodexHomeOverrideForLaunch } from '../codex/configuration/homes/codex-real-home-path' -import { markCodexSessionBackfillMarkerPending } from '../codex/history/backfill/codex-session-backfill-marker' -import { getCodexSessionBackfillDate } from '../codex/history/backfill/codex-session-backfill-scan-dates' -import { resolveCodexSessionBackfillPaths } from '../codex/history/backfill/codex-session-backfill' -import type { CodexSessionBackfillDate } from '../codex/history/backfill/codex-session-backfill-types' -import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-managed-home-ownership' +} from '../../../codex/configuration/homes/codex-home-paths' +import { syncSystemConfigIntoManagedCodexHome } from '../../../codex/configuration/settings/codex-config-mirror' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' +import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' +import { hasCustomCodexHomeOverrideForLaunch } from '../../../codex/configuration/homes/codex-real-home-path' +import { markCodexSessionBackfillMarkerPending } from '../../../codex/history/backfill/codex-session-backfill-marker' +import { getCodexSessionBackfillDate } from '../../../codex/history/backfill/codex-session-backfill-scan-dates' +import { resolveCodexSessionBackfillPaths } from '../../../codex/history/backfill/codex-session-backfill' +import type { CodexSessionBackfillDate } from '../../../codex/history/backfill/codex-session-backfill-types' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../../managed-homes/host-codex-managed-home-ownership' import { CodexRuntimeHomeRouting } from './runtime-home-service-home-routing' -import { blockedWslDistroForExec } from '../wsl/discovery/wsl-background-exec-gate' -import { getWslHomeAsync } from '../wsl/discovery/distro-catalog' +import { blockedWslDistroForExec } from '../../../wsl/discovery/wsl-background-exec-gate' +import { getWslHomeAsync } from '../../../wsl/discovery/distro-catalog' export abstract class CodexRuntimeHomeLaunch extends CodexRuntimeHomeRouting { protected initializeLastSyncedState(): void { diff --git a/src/main/codex-accounts/runtime-home-service-managed-home.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts similarity index 89% rename from src/main/codex-accounts/runtime-home-service-managed-home.ts rename to src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts index 62c3a103084..df55786914b 100644 --- a/src/main/codex-accounts/runtime-home-service-managed-home.ts +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts @@ -1,36 +1,36 @@ import { statSync } from 'node:fs' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' import { syncSystemCodexResourcesIntoManagedHome, getSystemCodexHomePath, resolveOrcaManagedCodexHomePath -} from '../codex/configuration/homes/codex-home-paths' -import { syncSystemConfigIntoManagedCodexHome } from '../codex/configuration/settings/codex-config-mirror' -import { startCodexAccountSessionBridgeInBackground } from '../codex/history/bridges/codex-account-session-bridge' +} from '../../../codex/configuration/homes/codex-home-paths' +import { syncSystemConfigIntoManagedCodexHome } from '../../../codex/configuration/settings/codex-config-mirror' +import { startCodexAccountSessionBridgeInBackground } from '../../../codex/history/bridges/codex-account-session-bridge' import { isCodexHistorySharedAcrossAccounts } from './codex-history-sharing' import { resolveHostCodexSessionSourceHome, resolveWslCodexSessionSourceHome -} from '../codex/history/rollouts/codex-session-source-home' -import { parseWslUncPath } from '../../shared/wsl-paths' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import { normalizeCodexRuntimeSelection } from './runtime-selection' +} from '../../../codex/history/rollouts/codex-session-source-home' +import { parseWslUncPath } from '../../../../shared/wsl-paths' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' +import { normalizeCodexRuntimeSelection } from '../../account-management/runtime-selection' import { resolveHostCodexManagedHomeVerdict, ManagedCodexHomeTemporarilyUnavailableError -} from './host-codex-managed-home-ownership' -import { hasCustomCodexHomeOverrideForLaunch } from '../codex/configuration/homes/codex-real-home-path' -import { resolveCodexSessionBackfillPaths } from '../codex/history/backfill/codex-session-backfill' +} from '../../managed-homes/host-codex-managed-home-ownership' +import { hasCustomCodexHomeOverrideForLaunch } from '../../../codex/configuration/homes/codex-real-home-path' +import { resolveCodexSessionBackfillPaths } from '../../../codex/history/backfill/codex-session-backfill' import { hasCompletedCodexSessionBackfillMarker, markCodexSessionBackfillMarkerNeedsFullScan -} from '../codex/history/backfill/codex-session-backfill-marker' -import { getDefaultWslDistro } from '../wsl/discovery/distro-catalog' -import { startWslCodexSessionBridgeInBackground } from '../codex/history/bridges/wsl-codex-session-bridge' -import type { CodexAccountSelectionTarget } from './runtime-selection' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import { CodexRuntimeHomeSync } from './runtime-home-service-sync' +} from '../../../codex/history/backfill/codex-session-backfill-marker' +import { getDefaultWslDistro } from '../../../wsl/discovery/distro-catalog' +import { startWslCodexSessionBridgeInBackground } from '../../../codex/history/bridges/wsl-codex-session-bridge' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import { CodexRuntimeHomeSync } from '../runtime-home-service-sync' export abstract class CodexRuntimeHomeManagedHome extends CodexRuntimeHomeSync { // One WSL sibling-bridge loop per target home; keyed by distro and Linux path. diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts new file mode 100644 index 00000000000..5255450b258 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts @@ -0,0 +1,268 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import type * as NodeOs from 'node:os' +import { readHookTrustEntries } from '../../../codex/trust/toml/config-toml-trust' +import '../../../codex/history/index/codex-state-db-test-fixture' + +const testState = { userData: '', home: '' } +const previousEnv: Record = {} + +vi.mock('../../../codex/trust/hooks/codex-hook-trust-derivation', async (importOriginal) => + ( + await import('../../../codex/trust/hooks/codex-hook-trust-derivation.test-fixture') + ).answeringCodexForTests(await importOriginal()) +) +vi.mock('electron', () => ({ app: { getPath: () => testState.userData } })) +beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userData })) +vi.mock('node:os', async () => { + const actual = await vi.importActual('node:os') + return { ...actual, homedir: () => testState.home } +}) +// Prevent the selection-triggered history bridge from spawning a real app-server. +vi.mock('../../../codex/history/index/codex-account-session-index-heal', () => { + const upToDate = async () => ({ + outcome: 'up-to-date', + healedThreads: 0, + missingThreads: 0, + failedThreads: 0 + }) + return { + createCodexAccountStateDb: async () => false, + healCodexAccountSessionIndex: upToDate, + healPendingCodexAccountThreads: upToDate + } +}) + +beforeEach(() => { + vi.resetModules() + testState.userData = mkdtempSync(join(tmpdir(), 'orca-codex-e-migration-')) + testState.home = mkdtempSync(join(tmpdir(), 'orca-codex-e-home-')) + for (const key of [ + 'ORCA_USER_DATA_PATH', + 'ORCA_DISABLE_CODEX_TRUST_RPC', + 'CODEX_HOME', + 'ORCA_CODEX_HOME' + ]) { + previousEnv[key] = process.env[key] + delete process.env[key] + } + process.env.ORCA_USER_DATA_PATH = testState.userData + process.env.ORCA_DISABLE_CODEX_TRUST_RPC = '1' + mkdirSync(systemHome(), { recursive: true }) + mkdirSync(sharedHome(), { recursive: true }) +}) + +afterEach(() => { + rmSync(testState.userData, { recursive: true, force: true }) + rmSync(testState.home, { recursive: true, force: true }) + for (const [key, value] of Object.entries(previousEnv)) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } + } +}) + +describe('CodexRuntimeHomeService per-account takeover composition', () => { + it('upgrades a realistic two-account shared-home fixture without losing auth or sessions', async () => { + const accountOneStale = createAuth('one@example.com', 'acct-1', 'one-stale', 1_000) + const accountOneMigrated = createAuth('one@example.com', 'acct-1', 'one-migrated', 2_000) + const accountTwoAuth = createAuth('two@example.com', 'acct-2', 'two-current', 3_000) + const accountOne = createManagedAccount('account-1', 'acct-1', accountOneStale) + const accountTwo = createManagedAccount( + 'account-2', + 'acct-2', + accountTwoAuth, + 'two@example.com' + ) + const sharedSession = join(sharedHome(), 'sessions', '2026', '07', 'rollout.jsonl') + mkdirSync(join(systemHome(), 'skills', 'fixture-skill'), { recursive: true }) + mkdirSync(join(systemHome(), 'hooks'), { recursive: true }) + mkdirSync(join(sharedHome(), 'sessions', '2026', '07'), { recursive: true }) + writeFileSync(join(systemHome(), 'skills', 'fixture-skill', 'SKILL.md'), 'fixture skill\n') + writeFileSync(join(systemHome(), 'hooks', 'user-hook.sh'), '#!/bin/sh\n') + writeFileSync( + join(systemHome(), 'config.toml'), + 'model = "fixture-model"\n\n[hooks.state."stale-fixture"]\nenabled = true\n' + ) + writeFileSync(sharedSession, '{"session":"legacy-shared"}\n') + writeFileSync(sharedAuthPath(), accountOneMigrated) + const { settings, store } = createStore([accountOne, accountTwo], accountOne.id) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const [, { CodexHookService }] = await Promise.all([ + import('../../../codex/hooks/installation/hook-service'), + import('../../../codex/hooks/installation/codex-hook-service-implementation') + ]) + const { startCodexHookHashLookup } = + await import('../../../codex/trust/hooks/codex-hook-hash-lookup') + startCodexHookHashLookup(Promise.resolve()) + const service = new CodexRuntimeHomeService(store as never) + const hookService = new CodexHookService() + + expect(readFileSync(join(accountOne.managedHomePath, 'auth.json'), 'utf8')).toBe( + accountOneMigrated + ) + expect(readFileSync(join(accountTwo.managedHomePath, 'auth.json'), 'utf8')).toBe(accountTwoAuth) + + for (const account of [accountOne, accountTwo]) { + selectManagedAccount(settings, account.id) + service.syncForCurrentSelection() + expect(service.prepareForCodexLaunch()).toBe(account.managedHomePath) + expect( + readFileSync(join(account.managedHomePath, 'skills', 'fixture-skill', 'SKILL.md'), 'utf8') + ).toBe('fixture skill\n') + expect(readFileSync(join(account.managedHomePath, 'hooks', 'user-hook.sh'), 'utf8')).toBe( + '#!/bin/sh\n' + ) + const config = readFileSync(join(account.managedHomePath, 'config.toml'), 'utf8') + expect(config).toContain('model = "fixture-model"') + expect(config).not.toContain('[hooks.state') + expect((await hookService.install(account.managedHomePath)).state).toBe('installed') + expect(readFileSync(join(account.managedHomePath, 'hooks.json'), 'utf8')).toContain( + process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh' + ) + expect( + readHookTrustEntries(join(account.managedHomePath, 'config.toml')).size + ).toBeGreaterThan(0) + } + + const discoveryHomes = service.getHostCodexHomePathsForSessionDiscovery() + expect(discoveryHomes).toEqual( + expect.arrayContaining([ + sharedHome(), + systemHome(), + accountOne.managedHomePath, + accountTwo.managedHomePath + ]) + ) + expect(new Set(discoveryHomes).size).toBe(discoveryHomes.length) + expect(readFileSync(sharedSession, 'utf8')).toBe('{"session":"legacy-shared"}\n') + + writeFileSync(sharedAuthPath(), createAuth('two@example.com', 'acct-2', 'later-shared', 4_000)) + expect(service.prepareForCodexLaunch()).toBe(accountTwo.managedHomePath) + expect(readFileSync(join(accountTwo.managedHomePath, 'auth.json'), 'utf8')).toBe(accountTwoAuth) + }) + + it('never continuously recovers a missing E auth from shared state after takeover', async () => { + const stale = createAuth('one@example.com', 'acct-1', 'stale', 1_000) + const takeover = createAuth('one@example.com', 'acct-1', 'takeover', 2_000) + const laterShared = createAuth('one@example.com', 'acct-1', 'later-shared', 3_000) + const account = createManagedAccount('account-1', 'acct-1', stale) + writeFileSync(sharedAuthPath(), takeover, 'utf-8') + writeFileSync(systemAuthPath(), 'system auth sentinel\n', 'utf-8') + const { settings, store } = createStore([account], account.id) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + const accountAuthPath = join(account.managedHomePath, 'auth.json') + expect(readFileSync(accountAuthPath, 'utf-8')).toBe(takeover) + + rmSync(accountAuthPath) + writeFileSync(sharedAuthPath(), laterShared, 'utf-8') + + expect(service.prepareForCodexLaunch()).toBe(account.managedHomePath) + expect(service.prepareForRateLimitFetch()).toEqual({ + kind: 'ready', + codexHomePath: account.managedHomePath + }) + expect(existsSync(accountAuthPath)).toBe(false) + expect(settings.activeCodexManagedAccountId).toBe(account.id) + expect(readFileSync(sharedAuthPath(), 'utf-8')).toBe(laterShared) + expect(readFileSync(systemAuthPath(), 'utf-8')).toBe('system auth sentinel\n') + }) +}) + +function createStore(accounts: CodexManagedAccount[], activeId: string | null) { + const settings = { + codexManagedAccounts: accounts, + activeCodexManagedAccountId: activeId, + activeCodexManagedAccountIdsByRuntime: { host: activeId, wsl: {} } + } as GlobalSettings + return { + settings, + store: { + getSettings: () => settings, + updateSettings: (updates: Partial) => Object.assign(settings, updates) + } + } +} + +function createManagedAccount( + id: string, + providerId: string, + auth: string, + email = 'one@example.com' +): CodexManagedAccount { + const home = join(testState.userData, 'codex-accounts', id, 'home') + mkdirSync(home, { recursive: true }) + writeFileSync(join(home, '.orca-managed-home'), `${id}\n`, 'utf-8') + writeFileSync(join(home, 'auth.json'), auth, 'utf-8') + return managedAccountRecord(id, providerId, home, email) +} + +function managedAccountRecord( + id: string, + providerAccountId: string, + managedHomePath: string, + email = 'one@example.com' +): CodexManagedAccount { + return { + id, + email, + managedHomePath, + providerAccountId, + workspaceLabel: null, + workspaceAccountId: providerAccountId, + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } +} + +function selectManagedAccount(settings: GlobalSettings, accountId: string): void { + settings.activeCodexManagedAccountId = accountId + settings.activeCodexManagedAccountIdsByRuntime = { host: accountId, wsl: {} } +} + +function systemHome(): string { + return join(testState.home, '.codex') +} + +function systemAuthPath(): string { + return join(systemHome(), 'auth.json') +} + +function sharedHome(): string { + return join(testState.userData, 'codex-runtime-home', 'home') +} + +function sharedAuthPath(): string { + return join(sharedHome(), 'auth.json') +} + +function createAuth(email: string, accountId: string, token: string, expiresAt: number): string { + const header = Buffer.from('{}').toString('base64url') + const payload = Buffer.from( + JSON.stringify({ + email, + exp: expiresAt, + 'https://api.openai.com/auth': { + chatgpt_account_id: accountId, + workspace_account_id: accountId + } + }) + ).toString('base64url') + return `${JSON.stringify({ + tokens: { + id_token: `${header}.${payload}.`, + account_id: accountId, + refresh_token: token, + expires_at: expiresAt + } + })}\n` +} diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-session-migration-pass.test.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-session-migration-pass.test.ts new file mode 100644 index 00000000000..eb28c81a9b2 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-session-migration-pass.test.ts @@ -0,0 +1,101 @@ +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' +import { mkdirSync, writeFileSync } from 'node:fs' +import type * as NodeOs from 'node:os' +import { join } from 'node:path' +import { createSettings } from '../runtime-home-settings-test-fixtures' +import { + createStore, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from '../runtime-home-service-test-harness' +import '../../../codex/history/backfill/codex-session-backfill-scan-dates' + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) + +vi.mock('node:os', async () => { + const actual = await vi.importActual('node:os') + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +const CUSTOM_HISTORY_HOME = 'C:\\Users\\Me\\.codex' + +function getMarkerPath(): string { + return join(testState.userDataDir, 'codex-session-backfill', 'backfill-complete.json') +} + +function writeBaselineMarker(systemCodexHomePath: string, needsFullScan = false): void { + mkdirSync(join(testState.userDataDir, 'codex-session-backfill'), { recursive: true }) + writeFileSync( + getMarkerPath(), + `${JSON.stringify({ + version: 4, + systemSessionsRoot: join(systemCodexHomePath, 'sessions'), + coverage: 'full', + baselineScannedFiles: 5, + pendingScanDates: [], + needsFullScan, + summary: { scannedFiles: 5 } + })}\n`, + 'utf-8' + ) +} + +describe('host system default session migration pass preparation', () => { + beforeEach(() => { + setupRuntimeHomeTest() + }) + + afterEach(() => { + teardownRuntimeHomeTest() + }) + + it('does not demand a full scan when the same history home is spelled differently', async () => { + writeBaselineMarker(CUSTOM_HISTORY_HOME) + const store = createStore( + createSettings({ + codexSessionSourceHome: { host: CUSTOM_HISTORY_HOME, wsl: {} }, + realHomeRoutable: true + }) + ) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + expect(service.beginHostSystemDefaultSessionMigrationLaunch(null, { reattached: true })).toBe( + false + ) + + store.updateSettings({ + codexSessionSourceHome: { host: 'c:/users/me/.codex', wsl: {} } + }) + + expect(service.prepareHostSystemDefaultSessionMigrationPass()).toBe(false) + }) + + it('still demands a full scan when the history home really moves', async () => { + writeBaselineMarker(CUSTOM_HISTORY_HOME) + const store = createStore( + createSettings({ + codexSessionSourceHome: { host: CUSTOM_HISTORY_HOME, wsl: {} }, + realHomeRoutable: true + }) + ) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + expect(service.beginHostSystemDefaultSessionMigrationLaunch(null, { reattached: true })).toBe( + false + ) + + store.updateSettings({ + codexSessionSourceHome: { host: 'C:\\Users\\Me\\moved-codex', wsl: {} } + }) + + expect(service.prepareHostSystemDefaultSessionMigrationPass()).toBe(true) + }) +}) diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-system-resource-materialization.test.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-system-resource-materialization.test.ts new file mode 100644 index 00000000000..d98254a9815 --- /dev/null +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-system-resource-materialization.test.ts @@ -0,0 +1,121 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + existsSync, + mkdirSync, + readFileSync, + realpathSync, + symlinkSync, + writeFileSync +} from 'node:fs' +import { join } from 'node:path' +import { createSettings } from '../runtime-home-settings-test-fixtures' +import { + createStore, + expectResourceLinkedOrCopied, + getRuntimeCodexHomePath, + getSystemCodexHomePath, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from '../runtime-home-service-test-harness' + +// Keep asserted config bytes independent of platform socket-path limits. +vi.mock( + '../../../codex/configuration/shared-server/codex-daemon-socket-path-guard', + async (importOriginal) => ({ + ...(await importOriginal()), + applyCodexDaemonSocketGuard: (config: string) => config + }) +) + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) + +vi.mock(import('node:os'), async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +describe('CodexRuntimeHomeService', () => { + beforeEach(() => { + setupRuntimeHomeTest() + }) + + afterEach(() => { + teardownRuntimeHomeTest() + }) + + it('rebases the bundled marketplace onto the canonical path of a symlinked managed home', async () => { + const systemMarketplace = join( + getSystemCodexHomePath(), + '.tmp', + 'bundled-marketplaces', + 'openai-bundled' + ) + mkdirSync(systemMarketplace, { recursive: true }) + writeFileSync( + join(getSystemCodexHomePath(), 'config.toml'), + `[marketplaces.openai-bundled]\nsource_type = "local"\nsource = '${systemMarketplace}'\n`, + 'utf-8' + ) + const linkedUserData = join(testState.fakeHomeDir, 'linked-user-data') + symlinkSync(testState.userDataDir, linkedUserData, 'junction') + process.env.ORCA_USER_DATA_PATH = linkedUserData + const store = createStore(createSettings()) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + + service.prepareForCodexLaunch() + + // Codex compares against its canonicalized CODEX_HOME, so the source must not keep the link. + const canonicalMarketplace = join( + realpathSync.native(testState.userDataDir), + 'codex-runtime-home', + 'home', + '.tmp', + 'bundled-marketplaces', + 'openai-bundled' + ) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'config.toml'), 'utf-8')).toContain( + `source = '${canonicalMarketplace}'` + ) + expect(existsSync(canonicalMarketplace)).toBe(true) + }) + + it('does not replace runtime-owned Codex files while linking user resources', async () => { + const systemCodexHome = getSystemCodexHomePath() + mkdirSync(join(systemCodexHome, 'sessions'), { recursive: true }) + mkdirSync(join(systemCodexHome, 'skills'), { recursive: true }) + writeFileSync(join(systemCodexHome, 'auth.json'), '{"account":"system"}\n', 'utf-8') + writeFileSync(join(systemCodexHome, 'hooks.json'), '{"hooks":{}}\n', 'utf-8') + writeFileSync(join(systemCodexHome, 'skills', 'system.md'), 'system\n', 'utf-8') + writeFileSync(join(getRuntimeCodexHomePath(), 'hooks.json'), '{"hooks":{"Stop":[]}}\n', 'utf-8') + writeFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), '{"id":"runtime"}\n', 'utf-8') + const store = createStore(createSettings()) + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + + service.prepareForCodexLaunch() + + expect(readFileSync(join(getRuntimeCodexHomePath(), 'auth.json'), 'utf-8')).toBe( + '{"account":"system"}\n' + ) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'hooks.json'), 'utf-8')).toBe( + '{"hooks":{"Stop":[]}}\n' + ) + expect(readFileSync(join(getRuntimeCodexHomePath(), 'history.jsonl'), 'utf-8')).toBe( + '{"id":"runtime"}\n' + ) + expect(existsSync(join(getRuntimeCodexHomePath(), 'sessions'))).toBe(false) + expectResourceLinkedOrCopied( + join(getRuntimeCodexHomePath(), 'skills'), + join(systemCodexHome, 'skills') + ) + }) +}) diff --git a/src/main/codex-accounts/runtime-home-service-paths.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts similarity index 97% rename from src/main/codex-accounts/runtime-home-service-paths.ts rename to src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts index 2cb401190e4..e7c4d06fec9 100644 --- a/src/main/codex-accounts/runtime-home-service-paths.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts @@ -7,12 +7,12 @@ import { symlinkSync, unlinkSync } from 'node:fs' -import { getAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment } from '../../../shared/app-environment' import { dirname, isAbsolute, join, resolve } from 'node:path' import { getOrcaManagedCodexHomePath, getOrcaUserDataPath -} from '../codex/configuration/homes/codex-home-paths' +} from '../../codex/configuration/homes/codex-home-paths' import type { CodexMirroredHomeStatus } from './runtime-home-service-types' import { CodexRuntimeHomeState } from './runtime-home-service-state' diff --git a/src/main/codex-accounts/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts similarity index 95% rename from src/main/codex-accounts/runtime-home-service-state.ts rename to src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index 2ab5c439d61..4f72dc5a7d3 100644 --- a/src/main/codex-accounts/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -1,6 +1,6 @@ -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import type { Store } from '../persistence/loading-store/store' -import { CodexCredentialAbsenceGrace } from './codex-credential-absence-grace' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' +import type { Store } from '../../persistence/loading-store/store' +import { CodexCredentialAbsenceGrace } from '../credentials/codex-credential-absence-grace' import type { CodexMirroredHomeStatus, CodexRateLimitHomeResolution, @@ -14,10 +14,10 @@ import type { CodexSharedRuntimeAuthProvenanceStatus, CodexSystemDefaultSnapshot } from './runtime-home-service-types' -import type { CodexSessionBackfillDate } from '../codex/history/backfill/codex-session-backfill-types' -import type { CodexAccountSelectionTarget } from './runtime-selection' -import type { LegacyWslRuntimeAuthDestination } from './legacy-wsl-runtime-auth-drain' -import type { WslCodexAuthRead } from './wsl-codex-auth-batch-reader' +import type { CodexSessionBackfillDate } from '../../codex/history/backfill/codex-session-backfill-types' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' +import type { LegacyWslRuntimeAuthDestination } from '../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain' +import type { WslCodexAuthRead } from './wsl/wsl-codex-auth-batch-reader' export abstract class CodexRuntimeHomeState { // Mirror baseline owner; null means system default. diff --git a/src/main/codex-accounts/runtime-home-service-sync.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts similarity index 92% rename from src/main/codex-accounts/runtime-home-service-sync.ts rename to src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts index 92620d827e3..3271a144ece 100644 --- a/src/main/codex-accounts/runtime-home-service-sync.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts @@ -1,12 +1,10 @@ import { existsSync } from 'node:fs' -import { - normalizeCodexRuntimeSelection, - type CodexAccountSelectionTarget -} from './runtime-selection' -import { recoverInterruptedGuardedFileOperation } from '../filesystem/atomic-file-publication' +import { normalizeCodexRuntimeSelection } from '../account-management/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' +import { recoverInterruptedGuardedFileOperation } from '../../filesystem/atomic-file-publication' import type { CodexSharedRuntimeAuthProvenanceStatus } from './runtime-home-service-types' -import { codexAuthIsMonotonicallyFresher } from './runtime-home-service-auth-sync-identity' -import { CodexRuntimeHomeWsl } from './runtime-home-service-wsl' +import { codexAuthIsMonotonicallyFresher } from './credentials/runtime-home-service-auth-sync-identity' +import { CodexRuntimeHomeWsl } from './wsl/runtime-home-service-wsl' export abstract class CodexRuntimeHomeSync extends CodexRuntimeHomeWsl { syncForCurrentSelection( diff --git a/src/main/codex-accounts/runtime-home-service-test-harness.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-test-harness.ts similarity index 96% rename from src/main/codex-accounts/runtime-home-service-test-harness.ts rename to src/main/codex-accounts/runtime-home/runtime-home-service-test-harness.ts index f5b3f2b26af..5cc5c2b5865 100644 --- a/src/main/codex-accounts/runtime-home-service-test-harness.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-test-harness.ts @@ -13,8 +13,8 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { CodexManagedAccount } from '../../shared/managed-account-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' export const testState: { userDataDir: string @@ -169,7 +169,7 @@ export function setupRuntimeHomeTest(): void { testState.userDataDir = mkdtempSync(join(tmpdir(), 'orca-runtime-home-')) testState.fakeHomeDir = mkdtempSync(join(tmpdir(), 'orca-codex-home-')) // Keep Windows profile and registry path probes inside the fake home. - vi.doMock('../windows/windows-native-registry', () => ({ + vi.doMock('../../windows/windows-native-registry', () => ({ loadWindowsNativeRegistry: () => { throw new Error('no registry in runtime-home tests') } diff --git a/src/main/codex-accounts/runtime-home-service-types.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-types.ts similarity index 95% rename from src/main/codex-accounts/runtime-home-service-types.ts rename to src/main/codex-accounts/runtime-home/runtime-home-service-types.ts index afcfd37a41c..11c46534e2d 100644 --- a/src/main/codex-accounts/runtime-home-service-types.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-types.ts @@ -1,4 +1,4 @@ -import type { CodexManagedAccount } from '../../shared/managed-account-types' +import type { CodexManagedAccount } from '../../../shared/managed-account-types' export type CodexSystemDefaultSnapshot = { authJson: string | null diff --git a/src/main/codex-accounts/runtime-home/runtime-home-settings-test-fixtures.ts b/src/main/codex-accounts/runtime-home/runtime-home-settings-test-fixtures.ts new file mode 100644 index 00000000000..7fe08de406a --- /dev/null +++ b/src/main/codex-accounts/runtime-home/runtime-home-settings-test-fixtures.ts @@ -0,0 +1,13 @@ +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { createCodexAccountSettings } from '../account-management/codex-account-settings-fixture' +import { setRealHomeRoutableForTest, testState } from './runtime-home-service-test-harness' + +type TestSettingsOverrides = Partial & { + realHomeRoutable?: boolean +} + +export function createSettings(overrides: TestSettingsOverrides = {}): GlobalSettings { + // Default to the production custom-CODEX_HOME route for mirror-path assertions. + setRealHomeRoutableForTest(overrides.realHomeRoutable ?? false) + return createCodexAccountSettings(testState.fakeHomeDir, overrides) +} diff --git a/src/main/codex-accounts/runtime-home-service-wsl.ts b/src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts similarity index 91% rename from src/main/codex-accounts/runtime-home-service-wsl.ts rename to src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts index 2790b4c4c5e..6af5e529d4d 100644 --- a/src/main/codex-accounts/runtime-home-service-wsl.ts +++ b/src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts @@ -1,19 +1,19 @@ import { join, win32 as pathWin32 } from 'node:path' -import { parseWslUncPath, toLinuxPath, toWindowsWslUncPath } from '../../shared/wsl-paths' +import { parseWslUncPath, toLinuxPath, toWindowsWslUncPath } from '../../../../shared/wsl-paths' +import { getSelectedCodexAccountIdForTarget } from '../../account-management/runtime-selection' import { getCodexSelectionLaneKey, - getSelectedCodexAccountIdForTarget, type CodexAccountSelectionTarget -} from './runtime-selection' -import { getDefaultWslDistro, getWslHome } from '../wsl/discovery/distro-catalog' -import { hasRecordedLegacyWslCodexPane } from '../codex/configuration/homes/codex-pane-account-registry' +} from '../../../../shared/codex-selection-lane' +import { getDefaultWslDistro, getWslHome } from '../../../wsl/discovery/distro-catalog' +import { hasRecordedLegacyWslCodexPane } from '../../../codex/configuration/homes/codex-pane-account-registry' import { startLegacyWslRuntimeAuthDrain, type LegacyWslRuntimeAuthDestination -} from './legacy-wsl-runtime-auth-drain' +} from '../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain' import { readWslCodexAuths, type WslCodexAuthRead } from './wsl-codex-auth-batch-reader' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import { CodexRuntimeHomeWslCore } from './runtime-home-service-wsl-core' +import type { CodexManagedAccount } from '../../../../shared/managed-account-types' +import { CodexRuntimeHomeWslCore } from '../credentials/runtime-home-service-wsl-core' export abstract class CodexRuntimeHomeWsl extends CodexRuntimeHomeWslCore { protected getPreparedWslRateLimitHomePath( diff --git a/src/main/codex-accounts/runtime-home-wsl-managed-accounts.test.ts b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts similarity index 90% rename from src/main/codex-accounts/runtime-home-wsl-managed-accounts.test.ts rename to src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts index 9acecc09d91..bf806b77e0d 100644 --- a/src/main/codex-accounts/runtime-home-wsl-managed-accounts.test.ts +++ b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import type * as LegacyWslRuntimeAuthDrain from './legacy-wsl-runtime-auth-drain' -import type * as WslCodexSessionBridge from '../codex/history/bridges/wsl-codex-session-bridge' -import { createSettings } from './runtime-home-settings-test-fixtures' +import type * as LegacyWslRuntimeAuthDrain from '../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain' +import type * as WslCodexSessionBridge from '../../../codex/history/bridges/wsl-codex-session-bridge' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAuthJson, createManagedAuth, @@ -12,18 +12,18 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' // These launches are the user's own, so the E9 exec gate lets their prep run. -vi.mock('../wsl/discovery/wsl-background-exec-gate', () => ({ +vi.mock('../../../wsl/discovery/wsl-background-exec-gate', () => ({ blockedWslDistroForExec: async () => null })) // Background WSL drain/bridge spawn wsl.exe and warn after the file ends; these specs cover only routing. -vi.mock('./legacy-wsl-runtime-auth-drain', async (importOriginal) => ({ +vi.mock('../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain', async (importOriginal) => ({ ...(await importOriginal()), startLegacyWslRuntimeAuthDrain: async () => {} })) -vi.mock('../codex/history/bridges/wsl-codex-session-bridge', async (importOriginal) => ({ +vi.mock('../../../codex/history/bridges/wsl-codex-session-bridge', async (importOriginal) => ({ ...(await importOriginal()), startWslCodexSessionBridgeInBackground: async () => {} })) @@ -54,7 +54,7 @@ describe('CodexRuntimeHomeService', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu', getWslHome: () => wslHome, getWslHomeAsync: async () => wslHome @@ -89,7 +89,7 @@ describe('CodexRuntimeHomeService', () => { const store = createStore(settings) try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) const wslRuntimeHomePath = join( wslHome, @@ -125,7 +125,7 @@ describe('CodexRuntimeHomeService', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu', getWslHome: () => wslHome, getWslHomeAsync: async () => wslHome @@ -149,7 +149,7 @@ describe('CodexRuntimeHomeService', () => { const store = createStore(createSettings()) try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) const wslRuntimeHomePath = join( wslHome, @@ -184,7 +184,7 @@ describe('CodexRuntimeHomeService', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu', getWslHome: () => wslHome, getWslHomeAsync: async () => wslHome @@ -231,7 +231,7 @@ describe('CodexRuntimeHomeService', () => { ) try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) const target = { runtime: 'wsl' as const, wslDistro: 'Ubuntu' } const wslRuntimeHomePath = join( @@ -265,7 +265,7 @@ describe('CodexRuntimeHomeService', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu', getWslHome: () => wslHome, getWslHomeAsync: async () => wslHome @@ -323,7 +323,7 @@ describe('CodexRuntimeHomeService', () => { ) try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) expect(service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( diff --git a/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-session-bridge.test.ts b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-session-bridge.test.ts new file mode 100644 index 00000000000..7e1016eb55a --- /dev/null +++ b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-session-bridge.test.ts @@ -0,0 +1,235 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import type * as CodexConfigMirror from '../../../codex/configuration/settings/codex-config-mirror' +import type * as CodexHomePaths from '../../../codex/configuration/homes/codex-home-paths' +import type * as LegacyWslRuntimeAuthDrain from '../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain' +import type * as WslCodexAuthBatchReader from './wsl-codex-auth-batch-reader' +import type * as WslCodexSessionBridge from '../../../codex/history/bridges/wsl-codex-session-bridge' +import { createSettings } from '../runtime-home-settings-test-fixtures' +import { + createCodexAuthJson, + createManagedAuth, + createStore, + setupRuntimeHomeTest, + teardownRuntimeHomeTest, + testState +} from '../runtime-home-service-test-harness' + +// These launches are the user's own, so the E9 exec gate lets their prep run. +vi.mock('../../../wsl/discovery/wsl-background-exec-gate', () => ({ + blockedWslDistroForExec: async () => null +})) +vi.mock('electron', () => ({ + app: { + getPath: () => testState.userDataDir + } +})) + +vi.mock(import('node:os'), async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => testState.fakeHomeDir + } +}) + +describe('CodexRuntimeHomeService', () => { + beforeEach(() => { + setupRuntimeHomeTest() + }) + + afterEach(() => { + teardownRuntimeHomeTest() + }) + + it.skipIf(process.platform === 'win32')( + 'links retired WSL sessions only into the auth-matched direct home', + async () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + const guestHome = join(testState.userDataDir, 'ubuntu-home') + const wslHome = `\\\\wsl.localhost\\Ubuntu${guestHome.replaceAll('/', '\\')}` + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ + getDefaultWslDistro: () => 'Ubuntu', + getWslHome: () => wslHome, + getWslHomeAsync: async () => wslHome + })) + const ownerAuth = createCodexAuthJson( + 'owner@example.com', + 'acct-owner', + 'owner-refresh', + 2_000 + ) + const selectedAuth = createCodexAuthJson( + 'selected@example.com', + 'acct-selected', + 'selected-refresh', + 2_000 + ) + const ownerHome = createManagedAuth(testState.userDataDir, 'owner', ownerAuth) + const selectedHome = createManagedAuth(testState.userDataDir, 'selected', selectedAuth) + vi.doMock('./wsl-codex-auth-batch-reader', async (importOriginal) => ({ + ...(await importOriginal()), + readWslCodexAuths: vi.fn(async (_distro: string, homes: string[]) => + homes.map((home) => { + if (home === ownerHome) { + return { kind: 'present' as const, contents: ownerAuth } + } + if (home === selectedHome) { + return { kind: 'present' as const, contents: selectedAuth } + } + return { kind: 'missing' as const } + }) + ) + })) + const drainTasks: Promise[] = [] + vi.doMock('../../../wsl/execution/wsl-runner', () => ({ + runWslProcess: vi.fn( + async (options: { args?: string[]; script: string; shell?: 'bash' }) => { + try { + const stdout = execFileSync(options.shell === 'bash' ? '/bin/bash' : '/bin/sh', [ + '-c', + options.script, + options.shell ?? 'sh', + ...(options.args ?? []) + ]).toString() + return { + code: 0, + stdout, + stderr: '', + timedOut: false, + environmentResolved: true + } + } catch (error) { + return { + code: (error as { status?: number }).status ?? 1, + stdout: (error as { stdout?: Buffer }).stdout?.toString() ?? '', + stderr: (error as { stderr?: Buffer }).stderr?.toString() ?? '', + timedOut: false, + environmentResolved: true + } + } + } + ) + })) + vi.doMock( + '../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + startLegacyWslRuntimeAuthDrain: ( + options: Parameters[0] + ) => { + const task = actual.startLegacyWslRuntimeAuthDrain(options) + drainTasks.push(task) + return task + } + } + } + ) + vi.doMock('../../../codex/configuration/homes/codex-home-paths', async (importOriginal) => ({ + ...(await importOriginal()), + syncCodexGlobalInstructionsIntoManagedHome: vi.fn() + })) + vi.doMock( + '../../../codex/configuration/settings/codex-config-mirror', + async (importOriginal) => ({ + ...(await importOriginal()), + syncSystemConfigIntoManagedCodexHome: vi.fn() + }) + ) + // Launch-time sibling bridging is covered elsewhere; this pins only the drain's own target. + vi.doMock( + '../../../codex/history/bridges/wsl-codex-session-bridge', + async (importOriginal) => ({ + ...(await importOriginal()), + startWslCodexSessionBridgeInBackground: vi.fn(() => Promise.resolve()) + }) + ) + const retiredHome = join(guestHome, '.local', 'share', 'orca', 'codex-runtime-home', 'home') + const relativeSessionPath = join('sessions', '2026', '08', '26', 'retired.jsonl') + const retiredSessionPath = join(retiredHome, relativeSessionPath) + mkdirSync(join(retiredSessionPath, '..'), { recursive: true }) + writeFileSync(join(retiredHome, 'auth.json'), ownerAuth, 'utf-8') + writeFileSync(retiredSessionPath, '{"session":"retired"}\n', 'utf-8') + const blockedTargetDirectory = join(ownerHome, 'sessions', '2026') + mkdirSync(join(blockedTargetDirectory, '..'), { recursive: true }) + writeFileSync(blockedTargetDirectory, 'not-a-directory\n', 'utf-8') + const store = createStore( + createSettings({ + codexManagedAccounts: [ + { + id: 'owner', + email: 'owner@example.com', + managedHomePath: ownerHome, + managedHomeRuntime: 'wsl', + wslDistro: 'Ubuntu', + wslLinuxHomePath: ownerHome, + providerAccountId: 'acct-owner', + workspaceLabel: null, + workspaceAccountId: 'acct-owner', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + }, + { + id: 'selected', + email: 'selected@example.com', + managedHomePath: selectedHome, + managedHomeRuntime: 'wsl', + wslDistro: 'Ubuntu', + wslLinuxHomePath: selectedHome, + providerAccountId: 'acct-selected', + workspaceLabel: null, + workspaceAccountId: 'acct-selected', + createdAt: 2, + updatedAt: 2, + lastAuthenticatedAt: 2 + } + ], + activeCodexManagedAccountIdsByRuntime: { + host: null, + wsl: { Ubuntu: 'selected' } + } + }) + ) + + try { + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + await Promise.all(drainTasks) + + const linkedSessionPath = join(ownerHome, relativeSessionPath) + expect(existsSync(linkedSessionPath)).toBe(false) + rmSync(blockedTargetDirectory) + + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + await Promise.all(drainTasks) + expect(readFileSync(linkedSessionPath, 'utf-8')).toBe('{"session":"retired"}\n') + expect(statSync(linkedSessionPath).ino).toBe(statSync(retiredSessionPath).ino) + expect(existsSync(join(selectedHome, relativeSessionPath))).toBe(false) + + rmSync(linkedSessionPath) + rmSync(retiredHome, { recursive: true }) + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + await Promise.all(drainTasks) + expect(existsSync(linkedSessionPath)).toBe(false) + } finally { + vi.doUnmock('../../../codex/history/bridges/wsl-codex-session-bridge') + vi.doUnmock('../../../codex/configuration/settings/codex-config-mirror') + vi.doUnmock('../../../codex/configuration/homes/codex-home-paths') + vi.doUnmock('../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain') + vi.doUnmock('./wsl-codex-auth-batch-reader') + vi.doUnmock('../../../wsl/execution/wsl-runner') + vi.doUnmock('../../../wsl/discovery/distro-catalog') + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + } + } + ) +}) diff --git a/src/main/codex-accounts/runtime-home-wsl-system-default.test.ts b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-system-default.test.ts similarity index 92% rename from src/main/codex-accounts/runtime-home-wsl-system-default.test.ts rename to src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-system-default.test.ts index b5aa3f5c90e..155a411db51 100644 --- a/src/main/codex-accounts/runtime-home-wsl-system-default.test.ts +++ b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-system-default.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' +import { createSettings } from '../runtime-home-settings-test-fixtures' import { createCodexAuthJson, createManagedAuth, @@ -9,7 +9,7 @@ import { setupRuntimeHomeTest, teardownRuntimeHomeTest, testState -} from './runtime-home-service-test-harness' +} from '../runtime-home-service-test-harness' vi.mock('electron', () => ({ app: { @@ -38,7 +38,7 @@ describe('CodexRuntimeHomeService', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu', getWslHome: () => wslHome })) @@ -77,7 +77,7 @@ describe('CodexRuntimeHomeService', () => { ) try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) expect(service.prepareForRateLimitFetch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toEqual({ kind: 'ready', @@ -109,7 +109,7 @@ describe('CodexRuntimeHomeService', () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') - vi.doMock('../wsl/discovery/distro-catalog', () => ({ + vi.doMock('../../../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu', getWslHome: () => wslHome })) @@ -141,7 +141,7 @@ describe('CodexRuntimeHomeService', () => { ) try { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const { CodexRuntimeHomeService } = await import('../../runtime-home-service') const service = new CodexRuntimeHomeService(store as never) const target = { runtime: 'wsl' as const, wslDistro: 'Ubuntu' } diff --git a/src/main/codex-accounts/wsl-codex-auth-batch-reader.ts b/src/main/codex-accounts/runtime-home/wsl/wsl-codex-auth-batch-reader.ts similarity index 96% rename from src/main/codex-accounts/wsl-codex-auth-batch-reader.ts rename to src/main/codex-accounts/runtime-home/wsl/wsl-codex-auth-batch-reader.ts index 53805c060b7..f9954e2f39d 100644 --- a/src/main/codex-accounts/wsl-codex-auth-batch-reader.ts +++ b/src/main/codex-accounts/runtime-home/wsl/wsl-codex-auth-batch-reader.ts @@ -1,4 +1,4 @@ -import { runWslProcess } from '../wsl/execution/wsl-runner' +import { runWslProcess } from '../../../wsl/execution/wsl-runner' export type WslCodexAuthRead = | { kind: 'missing' | 'unreadable' } diff --git a/src/main/codex-accounts/service-abandoned-login-supersede.test.ts b/src/main/codex-accounts/service-abandoned-login-supersede.test.ts deleted file mode 100644 index e3a17ad42ac..00000000000 --- a/src/main/codex-accounts/service-abandoned-login-supersede.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { existsSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { - createCodexAuthJson, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the harness doubles implement every member the add-account login path reaches; this test drives the service only through addAccount, cancelPendingLogin and the login URL subscription. -const asServiceDouble = (double: unknown): T => double as T - -type StubLoginChild = EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => boolean - exitCode: number | null - signalCode: string | null -} - -function createStubLoginChild(): StubLoginChild { - const child: StubLoginChild = Object.assign(new EventEmitter(), { - stdout: new PassThrough(), - stderr: new PassThrough(), - exitCode: null, - signalCode: null, - kill: () => true - }) - - child.kill = vi.fn(() => { - child.exitCode = 143 - return true - }) - return child -} - -async function createServiceWithHangingLogin(): Promise<{ - service: { - addAccount: () => Promise<{ accounts: { email: string }[] }> - selectAccount: (accountId: string | null) => Promise - cancelPendingLogin: () => boolean - getPendingLoginUrl: () => string | null - onPendingLoginUrlChanged: (listener: (url: string | null) => void) => void - } - children: StubLoginChild[] - - loginHomes: string[] -}> { - vi.resetModules() - const children: StubLoginChild[] = [] - const loginHomes: string[] = [] - vi.doMock('node:child_process', () => ({ - execFileSync: vi.fn(), - spawn: vi.fn((_command: string, _args: string[], options: { env: NodeJS.ProcessEnv }) => { - loginHomes.push(options.env.CODEX_HOME ?? '') - const child = createStubLoginChild() - children.push(child) - return child - }) - })) - vi.doMock('../codex-cli/command', () => ({ - resolveCodexCommand: () => 'codex' - })) - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - asServiceDouble(createStore(createSettings())), - asServiceDouble(createRateLimits()), - asServiceDouble(createRuntimeHome()) - ) - return { service, children, loginHomes } -} - -describe('CodexAccountService abandoned login', () => { - registerCodexAccountsTestHomes() - - afterEach(() => { - vi.doUnmock('node:child_process') - vi.doUnmock('../codex-cli/command') - }) - - it('supersedes the login a closed Settings pane abandoned instead of queueing behind it', async () => { - const { service, children } = await createServiceWithHangingLogin() - const abandoned = service.addAccount() - const abandonedRejection = expect(abandoned).rejects.toThrow('Codex sign-in was cancelled.') - await vi.waitUntil(() => children.length === 1) - - const retry = service.addAccount() - const retryRejection = expect(retry).rejects.toThrow() - - await abandonedRejection - expect(children[0].kill).toHaveBeenCalledTimes(1) - - await vi.waitUntil(() => children.length === 2) - expect(children[1].kill).not.toHaveBeenCalled() - - service.cancelPendingLogin() - await retryRejection - }) - - it('frees the queue for a plain account switch too, not only for another add', async () => { - const { service, children } = await createServiceWithHangingLogin() - const abandoned = service.addAccount() - const abandonedRejection = expect(abandoned).rejects.toThrow('Codex sign-in was cancelled.') - await vi.waitUntil(() => children.length === 1) - - await service.selectAccount(null) - await abandonedRejection - expect(children[0].kill).toHaveBeenCalled() - }) - - it('refuses to cancel a sign-in that already wrote credentials, and keeps the account', async () => { - const { service, children, loginHomes } = await createServiceWithHangingLogin() - const pending = service.addAccount() - await vi.waitUntil(() => children.length === 1) - - writeFileSync( - join(loginHomes[0], 'auth.json'), - createCodexAuthJson('user@example.com', 'provider-account-1', 'refresh-token'), - 'utf-8' - ) - - expect(service.cancelPendingLogin()).toBe(false) - expect(children[0].kill).not.toHaveBeenCalled() - - children[0].emit('close', 0) - const accounts = await pending - expect(accounts.accounts.map((account) => account.email)).toEqual(['user@example.com']) - expect(existsSync(join(loginHomes[0], 'auth.json'))).toBe(true) - }) - - it('publishes the sign-in link codex prints and drops it when the login ends', async () => { - const { service, children } = await createServiceWithHangingLogin() - const published: (string | null)[] = [] - service.onPendingLoginUrlChanged((url) => published.push(url)) - - const pending = service.addAccount() - const rejection = expect(pending).rejects.toThrow('Codex sign-in was cancelled.') - await vi.waitUntil(() => children.length === 1) - - const authUrl = 'https://auth.openai.com/oauth/authorize?client_id=orca&state=abc' - children[0].stdout.write( - `Starting local login server on http://localhost:1455.\nIf your browser did not open, navigate to this URL to authenticate:\n\n${authUrl}\n` - ) - await vi.waitUntil(() => service.getPendingLoginUrl() === authUrl) - expect(published).toEqual([authUrl]) - - service.cancelPendingLogin() - await rejection - - expect(service.getPendingLoginUrl()).toBeNull() - expect(published).toEqual([authUrl, null]) - }) -}) diff --git a/src/main/codex-accounts/service-account-add-login.test.ts b/src/main/codex-accounts/service-account-add-login.test.ts deleted file mode 100644 index 09591a55959..00000000000 --- a/src/main/codex-accounts/service-account-add-login.test.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { EventEmitter } from 'node:events' -import { existsSync, readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { - createCodexAuthJson, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -// Keep asserted config bytes independent of platform socket-path limits. -vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', - async (importOriginal) => ({ - ...(await importOriginal()), - applyCodexDaemonSocketGuard: (config: string) => config - }) -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('seeds the managed home config before codex login runs', async () => { - vi.resetModules() - - const canonicalConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml') - const canonicalConfig = - 'model_provider = "openai"\napproval_policy = "never"\nsandbox_mode = "danger-full-access"\n' - writeFileSync(canonicalConfigPath, canonicalConfig, 'utf-8') - - const spawnMock = vi.fn( - (_command: string, _args: string[], options: { env: NodeJS.ProcessEnv }) => { - const child = new EventEmitter() as EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => void - } - child.stdout = new PassThrough() - child.stderr = new PassThrough() - child.kill = vi.fn() - - const loginHome = options.env.CODEX_HOME - expect(loginHome).toBeTruthy() - expect(readFileSync(join(loginHome!, 'config.toml'), 'utf-8')).toBe(canonicalConfig) - - const payload = Buffer.from(JSON.stringify({ email: 'user@example.com' })).toString( - 'base64url' - ) - writeFileSync( - join(loginHome!, 'auth.json'), - JSON.stringify({ - tokens: { - id_token: `header.${payload}.signature` - } - }), - 'utf-8' - ) - - queueMicrotask(() => child.emit('close', 0)) - return child - } - ) - - vi.doMock('node:child_process', () => ({ - // The teardown process-table reader binds execFile during module initialization. - execFile: vi.fn(), - execFileSync: vi.fn(), - spawn: spawnMock - })) - vi.doMock('../codex-cli/command', () => ({ - resolveCodexCommand: () => 'codex' - })) - - const settings = createSettings() - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - await service.addAccount() - - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledTimes(1) - - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledWith({ runtime: 'host' }) - }) - - it('rejects OAuth account add when canonical config pins a custom provider', async () => { - vi.resetModules() - - const canonicalConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml') - const canonicalConfig = [ - 'model_provider = "codex-lb"', - 'model = "gpt-5.2-codex"', - '', - '[model_providers.codex-lb]', - 'name = "Codex load balancer"', - 'base_url = "https://codex-lb.example.test/v1"', - 'env_key = "EXAMPLE_GATEWAY_TOKEN"', - '' - ].join('\n') - writeFileSync(canonicalConfigPath, canonicalConfig, 'utf-8') - - const spawnMock = vi.fn() - vi.doMock('node:crypto', () => ({ randomUUID: () => 'account-id-for-test' })) - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - - try { - const settings = createSettings() - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - await expect(service.addAccount()).rejects.toThrow( - 'Orca cannot add a Codex OAuth account while ~/.codex/config.toml pins the custom provider "codex-lb". Keep using the system-default account for this provider, or remove model_provider (or set it to "openai") before adding an OAuth account. Orca left your config unchanged.' - ) - - expect(spawnMock).not.toHaveBeenCalled() - expect(store.updateSettings).not.toHaveBeenCalled() - expect(runtimeHome.syncForCurrentSelection).not.toHaveBeenCalled() - expect(existsSync(join(testState.userDataDir, 'codex-accounts', 'account-id-for-test'))).toBe( - false - ) - expect(readFileSync(canonicalConfigPath, 'utf-8')).toBe(canonicalConfig) - } finally { - vi.doUnmock('node:crypto') - vi.doUnmock('node:child_process') - } - }) - - it('recreates the expected missing managed home before reauthenticating', async () => { - vi.resetModules() - - const canonicalConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml') - const canonicalConfig = 'sandbox_mode = "danger-full-access"\n' - writeFileSync(canonicalConfigPath, canonicalConfig, 'utf-8') - - const managedHomePath = join(testState.userDataDir, 'codex-accounts', 'account-1', 'home') - const spawnMock = vi.fn( - (_command: string, _args: string[], options: { env: NodeJS.ProcessEnv }) => { - const loginHome = options.env.CODEX_HOME - expect(loginHome).toMatch(/[\\/]account-1[\\/]home[\\/]\.orca-reauth-login$/) - expect(readFileSync(join(managedHomePath, '.orca-managed-home'), 'utf-8')).toBe( - 'account-1\n' - ) - expect(readFileSync(join(loginHome!, 'config.toml'), 'utf-8')).toBe(canonicalConfig) - - const child = new EventEmitter() as EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => void - } - child.stdout = new PassThrough() - child.stderr = new PassThrough() - child.kill = vi.fn() - writeFileSync( - join(loginHome!, 'auth.json'), - createCodexAuthJson('new@example.com', 'provider-account-1', 'refresh-token'), - 'utf-8' - ) - queueMicrotask(() => child.emit('close', 0)) - return child - } - ) - - vi.doMock('node:child_process', () => ({ - // The teardown process-table reader binds execFile during module initialization. - execFile: vi.fn(), - execFileSync: vi.fn(), - spawn: spawnMock - })) - vi.doMock('../codex-cli/command', () => ({ - resolveCodexCommand: () => 'codex' - })) - - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'old@example.com', - managedHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ], - activeCodexManagedAccountId: 'account-1' - }) - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.reauthenticateAccount('account-1') - - expect(result.accounts[0]).toMatchObject({ - email: 'new@example.com', - providerAccountId: 'provider-account-1' - }) - expect(existsSync(managedHomePath)).toBe(true) - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledTimes(1) - warnSpy.mockRestore() - }) -}) diff --git a/src/main/codex-accounts/service-account-selection-and-removal.test.ts b/src/main/codex-accounts/service-account-selection-and-removal.test.ts deleted file mode 100644 index 21bd1c987af..00000000000 --- a/src/main/codex-accounts/service-account-selection-and-removal.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { existsSync, readFileSync } from 'node:fs' -import { join } from 'node:path' -import { - createCodexAuthJson, - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('selectAccount switches managed accounts without routing auth through the shared mirror', async () => { - const firstAuth = createCodexAuthJson('one@example.com', 'acct-one', 'one') - const secondAuth = createCodexAuthJson('two@example.com', 'acct-two', 'two') - const firstManagedHomePath = createManagedHome( - testState.userDataDir, - 'account-1', - '', - firstAuth - ) - const secondManagedHomePath = createManagedHome( - testState.userDataDir, - 'account-2', - '', - secondAuth - ) - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'one@example.com', - managedHomePath: firstManagedHomePath, - providerAccountId: 'acct-one', - workspaceLabel: null, - workspaceAccountId: 'acct-one', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - }, - { - id: 'account-2', - email: 'two@example.com', - managedHomePath: secondManagedHomePath, - providerAccountId: 'acct-two', - workspaceLabel: null, - workspaceAccountId: 'acct-two', - createdAt: 2, - updatedAt: 2, - lastAuthenticatedAt: 2 - } - ], - activeCodexManagedAccountId: 'account-1' - }) - const store = createStore(settings) - const rateLimits = createRateLimits() - - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const runtimeHome = new CodexRuntimeHomeService(store as never) - const runtimeAuthPath = join(testState.userDataDir, 'codex-runtime-home', 'home', 'auth.json') - expect(existsSync(runtimeAuthPath)).toBe(false) - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - await service.selectAccount('account-2') - - expect(existsSync(runtimeAuthPath)).toBe(false) - expect(readFileSync(join(firstManagedHomePath, 'auth.json'), 'utf-8')).toBe(firstAuth) - expect(readFileSync(join(secondManagedHomePath, 'auth.json'), 'utf-8')).toBe(secondAuth) - expect(existsSync(join(testState.userDataDir, 'codex-runtime-home', 'launch'))).toBe(false) - expect(existsSync(join(testState.userDataDir, 'codex-runtime-home', 'active'))).toBe(false) - }) - - it.each(['healthy', 'unreadable'])( - 'removes an account with a %s credit ledger', - async (ledger) => { - const managedHomePath = createManagedHome( - testState.userDataDir, - 'account-1', - '', - '{"account":"managed"}\n' - ) - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ], - activeCodexManagedAccountId: 'account-1' - }) - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - - const ledgerError = new Error('credit ledger unreadable') - if (ledger === 'unreadable') { - store.getCodexResetCreditAttemptLedger.mockImplementation(() => { - throw ledgerError - }) - } - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.removeAccount('account-1') - - expect(result.accounts).toHaveLength(0) - expect(result.activeAccountId).toBe(null) - expect(existsSync(managedHomePath)).toBe(false) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalled() - expect(rateLimits.evictInactiveCodexCache).toHaveBeenCalledWith('account-1') - if (ledger === 'unreadable') { - expect(warn).toHaveBeenCalledWith( - '[codex-accounts] Removed account, but credit ledger cleanup failed:', - expect.any(Error) - ) - expect(store.replaceCodexResetCreditAttemptLedgerAndFlush).not.toHaveBeenCalled() - } - warn.mockRestore() - } - ) - - it('refuses to remove a managed home owned by a different account', async () => { - const otherAccountHome = createManagedHome( - testState.userDataDir, - 'account-2', - '', - '{"account":"other"}\n' - ) - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath: otherAccountHome, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] - }) - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - createStore(settings) as never, - createRateLimits() as never, - createRuntimeHome() as never - ) - - await service.removeAccount('account-1') - - expect(readFileSync(join(otherAccountHome, 'auth.json'), 'utf-8')).toBe('{"account":"other"}\n') - expect(warnSpy).toHaveBeenCalledWith( - '[codex-accounts] Refusing to remove untrusted managed home:', - expect.any(Error) - ) - warnSpy.mockRestore() - }) -}) diff --git a/src/main/codex-accounts/service-add-account-from-home.test.ts b/src/main/codex-accounts/service-add-account-from-home.test.ts deleted file mode 100644 index bb77a500123..00000000000 --- a/src/main/codex-accounts/service-add-account-from-home.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { - createCodexAuthJson, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService.addAccountFromHome', () => { - registerCodexAccountsTestHomes() - - it('imports and switches personal and enterprise accounts sharing an email independently', async () => { - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - const sourceHomes = [ - mkdtempSync(join(tmpdir(), 'orca-codex-personal-')), - mkdtempSync(join(tmpdir(), 'orca-codex-enterprise-')) - ] - const email = 'same@example.com' - const credentials = ['plus', 'enterprise'].map((plan) => { - const parsed = JSON.parse(createCodexAuthJson(email, `provider-${plan}`, `refresh-${plan}`)) - const payload = Buffer.from( - JSON.stringify({ - email, - 'https://api.openai.com/auth': { - chatgpt_account_id: `provider-${plan}`, - chatgpt_plan_type: plan - } - }) - ).toString('base64url') - parsed.tokens.id_token = `header.${payload}.signature` - return JSON.stringify(parsed) - }) - - try { - sourceHomes.forEach((home, index) => { - writeFileSync(join(home, 'auth.json'), credentials[index], 'utf-8') - }) - const store = createStore(createSettings()) - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - createRateLimits() as never, - runtimeHome as never - ) - - await service.addAccountFromHome(sourceHomes[0]) - const result = await service.addAccountFromHome(sourceHomes[1]) - const accounts = store.getSettings().codexManagedAccounts - expect(result.accounts).toHaveLength(2) - expect(new Set(accounts.map((account) => account.id)).size).toBe(2) - expect(new Set(accounts.map((account) => account.managedHomePath)).size).toBe(2) - expect(accounts.map((account) => account.email)).toEqual([email, email]) - expect(accounts.map((account) => account.workspaceLabel)).toEqual([ - 'Personal (Plus)', - 'Enterprise' - ]) - expect(accounts.map((account) => account.providerAccountId)).toEqual([ - 'provider-plus', - 'provider-enterprise' - ]) - - for (const account of accounts) { - const selected = await service.selectAccount(account.id) - expect(selected.activeAccountId).toBe(account.id) - expect(store.getSettings().activeCodexManagedAccountIdsByRuntime?.host).toBe(account.id) - accounts.forEach((entry, index) => { - expect(readFileSync(join(entry.managedHomePath, 'auth.json'), 'utf-8')).toBe( - credentials[index] - ) - }) - } - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledTimes(4) - } finally { - sourceHomes.forEach((home) => rmSync(home, { recursive: true, force: true })) - vi.doUnmock('../codex-cli/command') - } - }) - - it('restores settings and runtime selection when post-write activation fails', async () => { - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - const sourceHome = mkdtempSync(join(tmpdir(), 'orca-codex-source-rollback-')) - writeFileSync( - join(sourceHome, 'auth.json'), - createCodexAuthJson('new@example.com', 'provider-account-1', 'refresh-token'), - 'utf-8' - ) - - try { - const settings = createSettings() - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - let managedHomePath: string | null = null - runtimeHome.syncForCurrentSelection.mockImplementationOnce(() => { - managedHomePath = store.getSettings().codexManagedAccounts[0]?.managedHomePath ?? null - throw new Error('activation failed') - }) - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - await expect(service.addAccountFromHome(sourceHome)).rejects.toThrow('activation failed') - - expect(store.getSettings().codexManagedAccounts).toHaveLength(0) - expect(store.getSettings().activeCodexManagedAccountId).toBeNull() - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledTimes(2) - expect(managedHomePath).not.toBeNull() - expect(existsSync(managedHomePath!)).toBe(false) - } finally { - rmSync(sourceHome, { recursive: true, force: true }) - vi.doUnmock('../codex-cli/command') - } - }) -}) diff --git a/src/main/codex-accounts/service-hook-trust-test-fixtures.ts b/src/main/codex-accounts/service-hook-trust-test-fixtures.ts deleted file mode 100644 index 76ca11f09a8..00000000000 --- a/src/main/codex-accounts/service-hook-trust-test-fixtures.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { join } from 'node:path' -import { testState } from './service-test-harness' - -export type CanonicalHookTrustFixture = { - config: string - orcaKeys: string[] - userKey: string -} - -export async function createCanonicalHookTrustFixture(): Promise { - const { MANAGED_HOOK_TIMEOUT_SECONDS } = - await import('../agent-hooks/installation/configuration/hook-config-schema') - const [, { getCodexManagedHookInstallMaterial }] = await Promise.all([ - import('../codex/hooks/installation/hook-service'), - import('../codex/hooks/definitions/codex-hook-definition') - ]) - const [ - , - { - computeCodexTrustKey: computeTrustKey, - computeCodexTrustedHash: computeTrustedHash, - normalizeCodexHookTrustLookupKey: normalizeHookTrustKeyForLookup - }, - { escapeTomlBasicString: escapeTomlString } - ] = await Promise.all([ - import('../codex/trust/toml/config-toml-trust'), - import('../codex/trust/identity/codex-trust-identity'), - import('../codex/configuration/toml/config-toml-syntax') - ]) - const { getCodexHookTrustSignature } = - await import('../codex/hooks/definitions/codex-hook-identity') - const { writeCodexTrustGrantLedgerHome } = - await import('../codex/trust/grants/codex-trust-grant-ledger') - const sourceHomePath = join(testState.fakeHomeDir, '.codex') - const sourcePath = join(sourceHomePath, 'hooks.json') - const material = getCodexManagedHookInstallMaterial() - const expectedHashEntry = { - sourcePath, - eventLabel: 'stop' as const, - groupIndex: 0, - handlerIndex: 0, - command: material.command, - timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS - } - const ledgerHashEntry = { - ...expectedHashEntry, - eventLabel: 'session_start' as const, - groupIndex: 1 - } - const userEntry = { - ...expectedHashEntry, - groupIndex: 2, - command: 'user-authored-hook' - } - const expectedHashKey = computeTrustKey(expectedHashEntry) - const ledgerHashKey = computeTrustKey(ledgerHashEntry) - const userKey = computeTrustKey(userEntry) - const ledgerTrustedHash = 'sha256:codex-granted-orca-hook' - writeCodexTrustGrantLedgerHome(sourceHomePath, { - binary: null, - entries: { - [normalizeHookTrustKeyForLookup(ledgerHashKey)]: { - signature: getCodexHookTrustSignature(ledgerHashEntry), - trustedHash: ledgerTrustedHash - } - } - }) - const block = (key: string, trustedHash: string): string => - `[hooks.state."${escapeTomlString(key)}"]\ntrusted_hash = "${trustedHash}"\nenabled = true` - return { - config: [ - 'approval_policy = "never"', - block(expectedHashKey, computeTrustedHash(expectedHashEntry)), - block(ledgerHashKey, ledgerTrustedHash), - block(userKey, computeTrustedHash(userEntry)) - ].join('\n\n'), - orcaKeys: [expectedHashKey, ledgerHashKey], - userKey - } -} diff --git a/src/main/codex-accounts/service-login-process-teardown.test.ts b/src/main/codex-accounts/service-login-process-teardown.test.ts deleted file mode 100644 index 99321e2f9c2..00000000000 --- a/src/main/codex-accounts/service-login-process-teardown.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { - createCodexAuthJson, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('removes command listeners when Codex login times out', async () => { - vi.resetModules() - vi.useFakeTimers() - const child = new EventEmitter() as EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => void - } - child.stdout = new PassThrough() - child.stderr = new PassThrough() - child.kill = vi.fn() - const spawnMock = vi.fn(() => child) - vi.doMock('node:child_process', () => ({ - execFileSync: vi.fn(), - spawn: spawnMock - })) - vi.doMock('../codex-cli/command', () => ({ - resolveCodexCommand: () => 'codex' - })) - - try { - const settings = createSettings() - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - const loginPromise = ( - service as unknown as { - runCodexLogin(managedHomePath: string): Promise - } - ).runCodexLogin(testState.fakeHomeDir) - const rejection = expect(loginPromise).rejects.toThrow( - 'Codex sign-in took too long to finish.' - ) - - await vi.advanceTimersByTimeAsync(180_000) - - await rejection - expect(child.kill).toHaveBeenCalledTimes(1) - expect(child.stdout.listenerCount('data')).toBe(0) - expect(child.stderr.listenerCount('data')).toBe(0) - expect(child.listenerCount('error')).toBe(0) - expect(child.listenerCount('close')).toBe(0) - } finally { - vi.useRealTimers() - vi.doUnmock('node:child_process') - vi.doUnmock('../codex-cli/command') - } - }) - - it('waits for reauthentication to replace existing Windows auth before killing login', async () => { - vi.resetModules() - vi.useFakeTimers() - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! - Object.defineProperty(process, 'platform', { - value: 'win32', - configurable: true - }) - const child = new EventEmitter() as EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => void - pid: number - exitCode: number | null - signalCode: string | null - } - child.stdout = new PassThrough() - child.stderr = new PassThrough() - child.kill = vi.fn() - child.pid = 4343 - child.exitCode = null - child.signalCode = null - const execFileSyncMock = vi.fn() - vi.doMock('node:child_process', () => ({ - execFileSync: execFileSyncMock, - spawn: vi.fn(() => child) - })) - vi.doMock('../codex-cli/command', () => ({ - resolveCodexCommand: () => 'codex' - })) - const authPath = join(testState.fakeHomeDir, 'auth.json') - writeFileSync( - authPath, - createCodexAuthJson('user@example.com', 'provider-account-1', 'old-token'), - 'utf-8' - ) - - try { - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - createStore(createSettings()) as never, - createRateLimits() as never, - createRuntimeHome() as never - ) - const loginPromise = ( - service as unknown as { - runCodexLogin(managedHomePath: string): Promise - } - ).runCodexLogin(testState.fakeHomeDir) - - await vi.advanceTimersByTimeAsync(6_000) - expect(execFileSyncMock).not.toHaveBeenCalled() - - writeFileSync( - authPath, - createCodexAuthJson('user@example.com', 'provider-account-1', 'new-token'), - 'utf-8' - ) - await vi.advanceTimersByTimeAsync(6_000) - expect(execFileSyncMock).toHaveBeenCalledWith( - 'taskkill', - ['/pid', '4343', '/t', '/f'], - expect.objectContaining({ windowsHide: true, stdio: 'ignore' }) - ) - - child.emit('close', 1) - await expect(loginPromise).resolves.toBeUndefined() - } finally { - Object.defineProperty(process, 'platform', originalPlatform) - vi.useRealTimers() - vi.doUnmock('node:child_process') - vi.doUnmock('../codex-cli/command') - } - }) -}) diff --git a/src/main/codex-accounts/service-managed-home-identity.test.ts b/src/main/codex-accounts/service-managed-home-identity.test.ts deleted file mode 100644 index a59d004082c..00000000000 --- a/src/main/codex-accounts/service-managed-home-identity.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { EventEmitter } from 'node:events' -import { readFileSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { - createCodexAuthJson, - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -const accountIAuth = createCodexAuthJson('i@example.com', 'provider-i', 'refresh-i') - -function createAccountI() { - return { - id: 'account-i', - email: 'i@example.com', - managedHomePath: createManagedHome(testState.userDataDir, 'account-i', '', accountIAuth), - providerAccountId: 'provider-i', - workspaceLabel: null, - workspaceAccountId: 'provider-i', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } -} - -async function createService(settings: ReturnType) { - const store = createStore(settings) - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - createRateLimits() as never, - createRuntimeHome() as never - ) - return { service, store } -} - -describe('Codex managed home identity', () => { - registerCodexAccountsTestHomes() - - it('keeps the existing login when a reauthentication is abandoned', async () => { - vi.resetModules() - // Mirrors `codex login`, which deletes the home's auth before its login server starts. - const spawnMock = vi.fn( - (_command: string, _args: string[], options: { env: NodeJS.ProcessEnv }) => { - rmSync(join(options.env.CODEX_HOME!, 'auth.json'), { force: true }) - const child = Object.assign(new EventEmitter(), { - stdout: new PassThrough(), - stderr: new PassThrough(), - exitCode: null, - signalCode: null, - kill: vi.fn(() => true) - }) - return child - } - ) - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - const account = createAccountI() - const { service, store } = await createService( - createSettings({ - codexManagedAccounts: [account], - activeCodexManagedAccountId: 'account-i', - activeCodexManagedAccountIdsByRuntime: { host: 'account-i', wsl: {} } - }) - ) - - const reauth = service.reauthenticateAccount('account-i') - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce()) - expect(service.cancelPendingLogin()).toBe(true) - - await expect(reauth).rejects.toThrow() - expect(readFileSync(join(account.managedHomePath, 'auth.json'), 'utf-8')).toBe(accountIAuth) - expect(store.getSettings().activeCodexManagedAccountId).toBe('account-i') - }) -}) diff --git a/src/main/codex-accounts/service-quota-refresh-decoupling.test.ts b/src/main/codex-accounts/service-quota-refresh-decoupling.test.ts deleted file mode 100644 index 51f644a66e4..00000000000 --- a/src/main/codex-accounts/service-quota-refresh-decoupling.test.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { existsSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { - createCodexAuthJson, - createManagedHome, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - describe('quota refresh decoupling', () => { - function createAccountOneSettings(): GlobalSettings { - const managedHomePath = createManagedHome( - testState.userDataDir, - 'account-1', - '', - '{"account":"managed"}\n' - ) - return createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] - }) - } - - async function expectResolvesPromptly(promise: Promise, label: string): Promise { - let timer: NodeJS.Timeout | undefined - try { - return await Promise.race([ - promise, - new Promise((_, reject) => { - timer = setTimeout( - () => reject(new Error(`${label} blocked on the quota refresh`)), - 2_000 - ) - }) - ]) - } finally { - clearTimeout(timer) - } - } - - function createLoginSpawnMock() { - return vi.fn((_command: string, _args: string[], options: { env: NodeJS.ProcessEnv }) => { - const child = new EventEmitter() as EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => void - } - child.stdout = new PassThrough() - child.stderr = new PassThrough() - child.kill = vi.fn() - writeFileSync( - join(options.env.CODEX_HOME!, 'auth.json'), - createCodexAuthJson('user@example.com', 'provider-account-1', 'refresh-token'), - 'utf-8' - ) - queueMicrotask(() => child.emit('close', 0)) - return child - }) - } - - it('resolves selectAccount while the quota refresh never settles', async () => { - const store = createStore(createAccountOneSettings()) - const rateLimits = { - refreshForCodexAccountChange: vi.fn(() => new Promise(() => {})), - evictInactiveCodexCache: vi.fn() - } - const runtimeHome = createRuntimeHome() - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const state = await expectResolvesPromptly( - service.selectAccount('account-1'), - 'selectAccount' - ) - - expect(state.activeAccountId).toBe('account-1') - expect(rateLimits.refreshForCodexAccountChange).toHaveBeenCalledTimes(1) - }) - - it('resolves addAccount while the post-login quota refresh never settles', async () => { - vi.resetModules() - writeFileSync( - join(testState.fakeHomeDir, '.codex', 'config.toml'), - 'approval_policy = "never"\n', - 'utf-8' - ) - const spawnMock = createLoginSpawnMock() - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - - const store = createStore(createSettings()) - const rateLimits = { - refreshForCodexAccountChange: vi.fn(() => new Promise(() => {})), - evictInactiveCodexCache: vi.fn() - } - const runtimeHome = createRuntimeHome() - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const state = await expectResolvesPromptly(service.addAccount(), 'addAccount') - - expect(state.accounts).toHaveLength(1) - expect(state.accounts[0].email).toBe('user@example.com') - expect(rateLimits.refreshForCodexAccountChange).toHaveBeenCalledTimes(1) - }) - - it('keeps the new account and its managed home when the post-login quota refresh rejects', async () => { - vi.resetModules() - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - writeFileSync( - join(testState.fakeHomeDir, '.codex', 'config.toml'), - 'approval_policy = "never"\n', - 'utf-8' - ) - const spawnMock = createLoginSpawnMock() - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - - const store = createStore(createSettings()) - const rateLimits = { - refreshForCodexAccountChange: vi.fn().mockRejectedValue(new Error('cold probe failed')), - evictInactiveCodexCache: vi.fn() - } - const runtimeHome = createRuntimeHome() - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const state = await service.addAccount() - - expect(state.accounts).toHaveLength(1) - const account = store.getSettings().codexManagedAccounts[0] - expect(account.email).toBe('user@example.com') - - expect(existsSync(account.managedHomePath)).toBe(true) - expect(existsSync(join(account.managedHomePath, 'auth.json'))).toBe(true) - await vi.waitFor(() => expect(errorSpy).toHaveBeenCalled()) - errorSpy.mockRestore() - }) - }) -}) diff --git a/src/main/codex-accounts/service-reauthenticate-activation.test.ts b/src/main/codex-accounts/service-reauthenticate-activation.test.ts deleted file mode 100644 index bff99200a20..00000000000 --- a/src/main/codex-accounts/service-reauthenticate-activation.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { EventEmitter } from 'node:events' -import { writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { - createCodexAuthJson, - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -function createHostAccounts(): GlobalSettings['codexManagedAccounts'] { - return ['account-1', 'account-2'].map((id, index) => ({ - id, - email: `${id}@example.com`, - managedHomePath: createManagedHome( - testState.userDataDir, - id, - '', - createCodexAuthJson(`${id}@example.com`, `provider-${id}`, `refresh-${id}`) - ), - providerAccountId: `provider-${id}`, - workspaceLabel: null, - workspaceAccountId: `provider-${id}`, - createdAt: index + 1, - updatedAt: index + 1, - lastAuthenticatedAt: index + 1 - })) -} - -function createLoginSpawn(onLogin?: () => void) { - return vi.fn((_command: string, _args: string[], options: { env: NodeJS.ProcessEnv }) => { - const child = new EventEmitter() as EventEmitter & { - stdout: PassThrough - stderr: PassThrough - kill: () => void - } - child.stdout = new PassThrough() - child.stderr = new PassThrough() - child.kill = vi.fn() - onLogin?.() - writeFileSync( - join(options.env.CODEX_HOME!, 'auth.json'), - createCodexAuthJson('reauthenticated@example.com', 'provider-new', 'refresh-new'), - 'utf-8' - ) - queueMicrotask(() => child.emit('close', 0)) - return child - }) -} - -describe('CodexAccountService reauthenticate activation intent', () => { - registerCodexAccountsTestHomes() - - it('activates the re-authed account when the intent is set and nothing was selected', async () => { - vi.resetModules() - const spawnMock = createLoginSpawn() - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - - const settings = createSettings({ - codexManagedAccounts: createHostAccounts(), - activeCodexManagedAccountId: null, - activeCodexManagedAccountIdsByRuntime: { host: null, wsl: {} } - }) - const store = createStore(settings) - const runtimeHome = createRuntimeHome() - const rateLimits = createRateLimits() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.reauthenticateAccount('account-2', { - activateIfSelectionWasEmpty: true - }) - - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(result.accounts.find((account) => account.id === 'account-2')).toMatchObject({ - email: 'reauthenticated@example.com', - providerAccountId: 'provider-new' - }) - expect(result.activeAccountId).toBe('account-2') - expect(result.activeAccountIdsByRuntime).toEqual({ host: 'account-2', wsl: {} }) - expect(store.getSettings()).toMatchObject({ - activeCodexManagedAccountId: 'account-2', - activeCodexManagedAccountIdsByRuntime: { host: 'account-2', wsl: {} } - }) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledWith({ runtime: 'host' }) - }) - - it('keeps the previously selected account even when the selection is cleared during OAuth', async () => { - vi.resetModules() - // The poll can clear selection during OAuth outside the mutation queue; retain pre-login intent. - const spawnMock = createLoginSpawn(() => { - const current = store.getSettings() - store.updateSettings({ - activeCodexManagedAccountId: null, - activeCodexManagedAccountIdsByRuntime: { - ...current.activeCodexManagedAccountIdsByRuntime!, - host: null - } - }) - }) - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - - const settings = createSettings({ - codexManagedAccounts: createHostAccounts(), - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - const store = createStore(settings) - const runtimeHome = createRuntimeHome() - const rateLimits = createRateLimits() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.reauthenticateAccount('account-2', { - activateIfSelectionWasEmpty: true - }) - - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(store.updateSettings).toHaveBeenCalledWith( - expect.objectContaining({ activeCodexManagedAccountId: null }) - ) - expect(result.activeAccountId).toBe('account-1') - expect(result.activeAccountIdsByRuntime).toEqual({ host: 'account-1', wsl: {} }) - expect(store.getSettings()).toMatchObject({ - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - }) - - it('leaves the selection empty without the intent, as the settings pane expects', async () => { - vi.resetModules() - const spawnMock = createLoginSpawn() - vi.doMock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: spawnMock })) - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - - const settings = createSettings({ - codexManagedAccounts: createHostAccounts(), - activeCodexManagedAccountId: null, - activeCodexManagedAccountIdsByRuntime: { host: null, wsl: {} } - }) - const store = createStore(settings) - const runtimeHome = createRuntimeHome() - const rateLimits = createRateLimits() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.reauthenticateAccount('account-2') - - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(result.accounts.find((account) => account.id === 'account-2')).toMatchObject({ - email: 'reauthenticated@example.com' - }) - expect(result.activeAccountId).toBeNull() - expect(result.activeAccountIdsByRuntime).toEqual({ host: null, wsl: {} }) - expect(store.getSettings().activeCodexManagedAccountId).toBeNull() - }) -}) diff --git a/src/main/codex-accounts/service-reset-credit-home-ownership.test.ts b/src/main/codex-accounts/service-reset-credit-home-ownership.test.ts deleted file mode 100644 index 7b341fe4b27..00000000000 --- a/src/main/codex-accounts/service-reset-credit-home-ownership.test.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { join } from 'node:path' -import { realpathSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' -import type * as NodeFs from 'node:fs' -import { buildCodexResetCreditExpectedScope } from '../../shared/codex-reset-credit-scope' -import { - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' -import { - createResetCreditLimits, - createResetRateLimitState -} from './service-reset-credit-test-fixtures' - -const fsFaults = vi.hoisted(() => { - const held = new Set() - let heldReads = 0 - let mkdirCalls = 0 - return { - hold(path: string): void { - held.add(path) - }, - reset(): void { - held.clear() - heldReads = 0 - mkdirCalls = 0 - }, - heldReads(): number { - return heldReads - }, - resetMkdirCalls(): void { - mkdirCalls = 0 - }, - mkdirCalls(): number { - return mkdirCalls - }, - noteMkdir(): void { - mkdirCalls += 1 - }, - consumeLstat(path: unknown): void { - if (typeof path !== 'string' || !held.has(path)) { - return - } - heldReads += 1 - const error: NodeJS.ErrnoException = new Error(`EPERM: lstat '${path}'`) - error.code = 'EPERM' - throw error - } - } -}) - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - const patched = { - ...actual, - lstatSync: (...args: Parameters) => { - fsFaults.consumeLstat(args[0]) - return actual.lstatSync(...args) - }, - mkdirSync: (...args: Parameters) => { - fsFaults.noteMkdir() - return actual.mkdirSync(...args) - } - } - return { ...patched, default: patched } -}) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('Codex reset-credit managed-home ownership', () => { - registerCodexAccountsTestHomes() - - it.each([ - { - homeState: 'indeterminate', - expectedError: 'temporarily locked', - makeHomeUnsafe: (managedHomePath: string) => - fsFaults.hold(join(realpathSync(managedHomePath), '.orca-managed-home')) - }, - { - homeState: 'proven untrusted', - expectedError: 'ownership marker does not match', - makeHomeUnsafe: (managedHomePath: string) => - writeFileSync(join(managedHomePath, '.orca-managed-home'), 'someone-else\n', 'utf-8') - } - ])( - 'rechecks ownership for a durable providerPending retry when the home is $homeState', - async ({ expectedError, makeHomeUnsafe }) => { - const fixture = await createFixture() - const pendingLedger = { - version: 1 as const, - attempts: [ - { - idempotencyKey: fixture.idempotencyKey, - expectedScope: fixture.expectedScope, - state: 'providerPending' as const - } - ] - } - await fixture.store.replaceCodexResetCreditAttemptLedgerAndFlush(pendingLedger) - makeHomeUnsafe(fixture.managedHomePath) - - const settingsBefore = structuredClone(fixture.store.getSettings()) - const authPath = join(fixture.managedHomePath, 'auth.json') - const markerPath = join(fixture.managedHomePath, '.orca-managed-home') - const authBefore = readFileSync(authPath, 'utf-8') - const markerBefore = readFileSync(markerPath, 'utf-8') - const directoryEntriesBefore = readdirSync(fixture.managedHomePath).sort() - fixture.consume.mockClear() - fixture.store.getCodexResetCreditAttemptLedger.mockClear() - fixture.store.replaceCodexResetCreditAttemptLedgerAndFlush.mockClear() - fixture.store.updateSettings.mockClear() - const restarted = fixture.createService() - // Exclude constructor config mirroring from retry write assertions. - fsFaults.resetMkdirCalls() - - await expect( - restarted.consumeRateLimitResetCredit(fixture.idempotencyKey, fixture.expectedScope) - ).rejects.toThrow(expectedError) - - expect(fixture.store.getCodexResetCreditAttemptLedger).toHaveBeenCalledOnce() - expect(fixture.store.getCodexResetCreditAttemptLedger()).toEqual(pendingLedger) - expect(fixture.consume).not.toHaveBeenCalled() - expect(fixture.store.replaceCodexResetCreditAttemptLedgerAndFlush).not.toHaveBeenCalled() - expect(fixture.store.updateSettings).not.toHaveBeenCalled() - expect(fixture.store.getSettings()).toEqual(settingsBefore) - expect(fsFaults.mkdirCalls()).toBe(0) - expect(readFileSync(authPath, 'utf-8')).toBe(authBefore) - expect(readFileSync(markerPath, 'utf-8')).toBe(markerBefore) - expect(readdirSync(fixture.managedHomePath).sort()).toEqual(directoryEntriesBefore) - } - ) - - async function createFixture() { - fsFaults.reset() - const managedHomePath = createManagedHome(testState.userDataDir, 'account-1', '', 'auth-before') - const account = { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - managedHomeRuntime: 'host' as const, - wslDistro: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - const settings = createSettings({ - codexManagedAccounts: [account], - activeCodexManagedAccountId: account.id, - activeCodexManagedAccountIdsByRuntime: { host: account.id, wsl: {} } - }) - const store = createStore(settings) - const limits = createResetCreditLimits() - const state = createResetRateLimitState(limits) - const consume = vi.fn().mockResolvedValue({ outcome: 'reset', state }) - const rateLimits = { - ...createRateLimits(), - getState: vi.fn(() => state), - consumeCodexRateLimitResetCredit: consume - } - const expectedScope = buildCodexResetCreditExpectedScope({ - target: state.codexTarget, - account, - limits - })! - const { CodexAccountService } = await import('./service') - const createService = () => - new CodexAccountService(store as never, rateLimits as never, createRuntimeHome() as never) - return { - service: createService(), - createService, - store, - consume, - expectedScope, - managedHomePath, - idempotencyKey: '11111111-1111-4111-8111-111111111111' - } - } -}) diff --git a/src/main/codex-accounts/service-reset-credit-test-fixtures.ts b/src/main/codex-accounts/service-reset-credit-test-fixtures.ts deleted file mode 100644 index 39b52bf5d1f..00000000000 --- a/src/main/codex-accounts/service-reset-credit-test-fixtures.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { ProviderRateLimits, RateLimitState } from '../../shared/rate-limit-types' -import { createEmptyRateLimitState } from '../../shared/rate-limit-state-factory' - -export function createResetCreditLimits(updatedAt = 30): ProviderRateLimits { - return { - provider: 'codex', - session: { - usedPercent: 100, - windowMinutes: 300, - resetsAt: 1_000, - resetDescription: 'soon' - }, - weekly: null, - rateLimitResetCredits: { - availableCount: 1, - totalEarnedCount: 1, - nextExpiresAt: 2_000, - credits: [{ status: 'available', expiresAt: 2_000, grantedAt: 500 }] - }, - updatedAt, - error: null, - status: 'ok' - } -} - -export function createResetRateLimitState( - codex: ProviderRateLimits, - target: RateLimitState['codexTarget'] = { runtime: 'host', wslDistro: null } -): RateLimitState { - return createEmptyRateLimitState({ codex, codexTarget: target }) -} diff --git a/src/main/codex-accounts/service-system-default-identity.test.ts b/src/main/codex-accounts/service-system-default-identity.test.ts deleted file mode 100644 index 0a58973e9e5..00000000000 --- a/src/main/codex-accounts/service-system-default-identity.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { rmSync, writeFileSync } from 'node:fs' -import type * as FileSystem from 'node:fs' -import { getCodexAccountAuthWarning } from '../../renderer/src/components/settings/accounts/codex/codex-account-auth-warning' -import { join } from 'node:path' -import { - createCodexAuthJson, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -const configWork = vi.hoisted(() => ({ readPaths: new Array(), parses: 0 })) - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readFileSync: (...args: Parameters) => { - configWork.readPaths.push(args[0]) - return actual.readFileSync(...args) - } - } -}) - -vi.mock( - import('../codex/structured/launch/codex-model-provider-config'), - async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readCodexTopLevelModelProvider: ( - ...args: Parameters - ) => { - configWork.parses += 1 - return actual.readCodexTopLevelModelProvider(...args) - } - } - } -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - describe('system-default identity', () => { - const systemCodexHomeDir = () => join(testState.fakeHomeDir, '.codex') - const systemAuthPath = () => join(systemCodexHomeDir(), 'auth.json') - - async function newService() { - const store = createStore(createSettings()) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - return new CodexAccountService(store as never, rateLimits as never, runtimeHome as never) - } - - function withoutEnvApiKey(run: () => T): T { - const previous = process.env.OPENAI_API_KEY - delete process.env.OPENAI_API_KEY - try { - return run() - } finally { - if (previous === undefined) { - delete process.env.OPENAI_API_KEY - } else { - process.env.OPENAI_API_KEY = previous - } - } - } - - it('reports the real ~/.codex OAuth identity for the system default', async () => { - writeFileSync( - systemAuthPath(), - createCodexAuthJson('real@home.dev', 'acct-real', 'refresh-real'), - 'utf-8' - ) - const service = await newService() - - const state = withoutEnvApiKey(() => service.listAccounts()) - - expect(state.activeAccountId).toBeNull() - expect(state.systemDefault).toEqual({ - hasAuth: true, - authKind: 'oauth', - email: 'real@home.dev', - providerAccountId: 'acct-real', - workspaceLabel: null - }) - }) - - it.each(['amazon-bedrock-runtime', 'ollama'])( - 'recognizes %s without an auth.json file', - async (provider) => { - writeFileSync( - join(systemCodexHomeDir(), 'config.toml'), - `model_provider = "${provider}"\n`, - 'utf-8' - ) - const service = await newService() - - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ - hasAuth: false, - authKind: 'api-key', - email: null, - providerAccountId: null, - workspaceLabel: null - }) - expect( - getCodexAccountAuthWarning({ - limits: null, - target: { runtime: 'host', wslDistro: null }, - runtime: { runtime: 'host' }, - activeAccountId: null, - accountId: null, - authKind: withoutEnvApiKey(() => service.listAccounts()).systemDefault?.authKind - }) - ).toBeNull() - } - ) - - it('does not attribute Bedrock Mantle to a saved ChatGPT login', async () => { - writeFileSync( - join(systemCodexHomeDir(), 'config.toml'), - 'model_provider = "amazon-bedrock"\n', - 'utf-8' - ) - writeFileSync(systemAuthPath(), createCodexAuthJson('old@home.dev', 'old', 'refresh')) - const service = await newService() - - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ - hasAuth: true, - authKind: 'api-key', - email: null, - providerAccountId: null, - workspaceLabel: null - }) - - writeFileSync(join(systemCodexHomeDir(), 'config.toml'), 'model_provider = "openai"\n') - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ - hasAuth: true, - authKind: 'oauth', - email: 'old@home.dev', - providerAccountId: 'old', - workspaceLabel: null - }) - }) - - it.each(['bedrockApiKey', undefined])( - 'recognizes a saved Bedrock API key with mode %s instead of reporting OAuth', - async (mode) => { - writeFileSync( - systemAuthPath(), - JSON.stringify({ - ...JSON.parse(createCodexAuthJson('old@home.dev', 'old', 'refresh')), - auth_mode: mode, - bedrock_api_key: { api_key: 'bedrock-fixture-key', region: 'us-east-2' } - }) - ) - const service = await newService() - - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ - hasAuth: true, - authKind: 'api-key', - email: null, - providerAccountId: null, - workspaceLabel: null - }) - } - ) - - it('keeps backend auth status without attributing stale tokens to a personal access token', async () => { - writeFileSync( - systemAuthPath(), - JSON.stringify({ - ...JSON.parse(createCodexAuthJson('old@home.dev', 'old', 'refresh')), - personal_access_token: 'fixture-personal-access-token' - }) - ) - const service = await newService() - - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ - hasAuth: true, - authKind: 'oauth', - email: null, - providerAccountId: null, - workspaceLabel: null - }) - }) - - it.each([750, 7_500])( - 'reuses unchanged provider input across snapshots with %i saved projects', - async (projectCount) => { - const configPath = join(systemCodexHomeDir(), 'config.toml') - const projects = Array.from( - { length: projectCount }, - (_, index) => `[projects."/work/project-${index}"]\ntrust_level = "trusted"\n` - ).join('') - writeFileSync(configPath, `model_provider = "amazon-bedrock"\n${projects}`) - writeFileSync( - systemAuthPath(), - createCodexAuthJson('real@home.dev', 'acct-real', 'refresh') - ) - const service = await newService() - configWork.readPaths = [] - configWork.parses = 0 - const configReads = () => configWork.readPaths.filter((path) => path === configPath).length - - for (let update = 0; update < 20; update += 1) { - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault?.authKind).toBe( - 'api-key' - ) - } - // Usage updates do not invalidate the one current provider classification. - expect(configReads()).toBe(1) - expect(configWork.parses).toBe(1) - - rmSync(configPath) - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault?.authKind).toBe('oauth') - expect(configReads()).toBe(2) - service.listAccounts() - expect(configReads()).toBe(2) - - writeFileSync(configPath, `model_provider = "openai"\n${projects}`) - expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ - hasAuth: true, - authKind: 'oauth', - email: 'real@home.dev', - providerAccountId: 'acct-real', - workspaceLabel: null - }) - expect(configReads()).toBe(3) - expect(configWork.parses).toBe(2) - } - ) - - it('degrades safely when auth.json contains valid JSON with the wrong shape', async () => { - writeFileSync(systemAuthPath(), 'null', 'utf-8') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const service = await newService() - - try { - const state = withoutEnvApiKey(() => service.listAccounts()) - - expect(state.systemDefault).toEqual({ - hasAuth: true, - authKind: 'none', - email: null, - providerAccountId: null, - workspaceLabel: null - }) - expect(warn).toHaveBeenCalledWith( - '[codex-accounts] System-default Codex auth has an unexpected format' - ) - } finally { - warn.mockRestore() - } - }) - - it('does not log auth contents when auth.json is malformed', async () => { - const secret = 'sk-secret-review-never-log' - writeFileSync(systemAuthPath(), secret, 'utf-8') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const service = await newService() - - try { - const state = withoutEnvApiKey(() => service.listAccounts()) - - expect(state.systemDefault?.authKind).toBe('none') - expect(warn).toHaveBeenCalledWith( - '[codex-accounts] System-default Codex auth is not valid JSON' - ) - expect(JSON.stringify(warn.mock.calls)).not.toContain(secret) - } finally { - warn.mockRestore() - } - }) - }) -}) diff --git a/src/main/codex-accounts/service-wsl-accounts.test.ts b/src/main/codex-accounts/service-wsl-accounts.test.ts deleted file mode 100644 index 7952f25123e..00000000000 --- a/src/main/codex-accounts/service-wsl-accounts.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -// Keep asserted config bytes independent of platform socket-path limits. -vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', - async (importOriginal) => ({ - ...(await importOriginal()), - applyCodexDaemonSocketGuard: (config: string) => config - }) -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('preserves WSL account-home project trust while refreshing canonical settings', async () => { - const wslManagedHomePath = join(testState.userDataDir, 'wsl-account', 'home') - const wslCanonicalHomePath = join(testState.userDataDir, 'wsl-home', '.codex') - const wslLinuxHomePath = '/home/alice/.local/share/orca/codex-accounts/account-1/home' - const wslLinuxCanonicalHomePath = '/home/alice/.codex' - mkdirSync(wslManagedHomePath, { recursive: true }) - mkdirSync(wslCanonicalHomePath, { recursive: true }) - writeFileSync(join(wslManagedHomePath, '.orca-managed-home'), 'account-1\n', 'utf-8') - writeFileSync( - join(wslManagedHomePath, 'config.toml'), - 'approval_policy = "untrusted"\n[projects."/workspace"]\ntrust_level = "trusted"\n', - 'utf-8' - ) - writeFileSync( - join(wslCanonicalHomePath, 'config.toml'), - 'sandbox_mode = "danger-full-access"\n', - 'utf-8' - ) - - vi.doMock('../../shared/wsl-paths', () => ({ - parseWslUncPath: (path: string) => { - if (path === wslManagedHomePath) { - return { distro: 'Ubuntu', linuxPath: wslLinuxHomePath } - } - if (path === wslCanonicalHomePath) { - return { distro: 'Ubuntu', linuxPath: wslLinuxCanonicalHomePath } - } - return null - }, - toWindowsWslPath: (linuxPath: string) => - linuxPath === wslLinuxCanonicalHomePath || - linuxPath === `${wslLinuxCanonicalHomePath}/config.toml` - ? linuxPath.endsWith('/config.toml') - ? join(wslCanonicalHomePath, 'config.toml') - : wslCanonicalHomePath - : wslManagedHomePath - })) - // The distro runs: the config mirror may read its home. - vi.doMock('../wsl/discovery/wsl-background-distro-gate', () => ({ - wasWslDistroLastSeenRunningSettled: () => true - })) - - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'wsl@example.com', - managedHomePath: wslManagedHomePath, - managedHomeRuntime: 'wsl', - wslDistro: 'Ubuntu', - wslLinuxHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] - }) - - const { CodexAccountService } = await import('./service') - new CodexAccountService( - createStore(settings) as never, - createRateLimits() as never, - createRuntimeHome() as never - ) - - expect(readFileSync(join(wslManagedHomePath, 'config.toml'), 'utf-8')).toBe( - 'sandbox_mode = "danger-full-access"\n\n' + - '[projects."/workspace"]\ntrust_level = "trusted"\n' - ) - }) -}) diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts deleted file mode 100644 index 5d7d30c0cee..00000000000 --- a/src/main/codex-accounts/service.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' -import { createCanonicalHookTrustFixture } from './service-hook-trust-test-fixtures' - -// Keep asserted config bytes independent of platform socket-path limits. -vi.mock( - '../codex/configuration/shared-server/codex-daemon-socket-path-guard', - async (importOriginal) => ({ - ...(await importOriginal()), - applyCodexDaemonSocketGuard: (config: string) => config - }) -) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('syncs the canonical ~/.codex/config.toml into managed homes on startup', async () => { - const canonicalConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml') - const canonicalConfig = 'approval_policy = "never"\nsandbox_mode = "danger-full-access"\n' - writeFileSync(canonicalConfigPath, canonicalConfig, 'utf-8') - const managedHomePath = createManagedHome( - testState.userDataDir, - 'account-1', - 'approval_policy = "on-request"\n', - '{"account":"managed"}\n' - ) - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ], - activeCodexManagedAccountId: 'account-1' - }) - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - - const { CodexAccountService } = await import('./service') - new CodexAccountService(store as never, rateLimits as never, runtimeHome as never) - - expect(readFileSync(join(managedHomePath, 'config.toml'), 'utf-8')).toBe(canonicalConfig) - expect(readFileSync(join(managedHomePath, 'auth.json'), 'utf-8')).toBe( - '{"account":"managed"}\n' - ) - }) - - it('does not seed source-home hook trust into a self-contained account home', async () => { - const fixture = await createCanonicalHookTrustFixture() - const canonicalConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml') - writeFileSync(canonicalConfigPath, fixture.config, 'utf-8') - const managedHomePath = createManagedHome( - testState.userDataDir, - 'account-1', - 'approval_policy = "on-request"\n' - ) - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] - }) - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { readHookTrustEntries } = await import('../codex/trust/toml/config-toml-trust') - const { readCodexTrustGrantLedgerHome } = - await import('../codex/trust/grants/codex-trust-grant-ledger') - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - const expectSanitizedManagedConfig = (): void => { - const entries = readHookTrustEntries(join(managedHomePath, 'config.toml')) - for (const key of fixture.orcaKeys) { - expect(entries.has(key)).toBe(false) - } - - expect(entries.has(fixture.userKey)).toBe(false) - } - - expectSanitizedManagedConfig() - expect(readFileSync(canonicalConfigPath, 'utf-8')).toBe(fixture.config) - expect(readCodexTrustGrantLedgerHome(join(testState.fakeHomeDir, '.codex'))).not.toBeNull() - - writeFileSync(join(managedHomePath, 'config.toml'), 'approval_policy = "untrusted"\n', 'utf-8') - await service.selectAccount('account-1') - - expectSanitizedManagedConfig() - }) - - it('re-syncs config when selecting an account', async () => { - const canonicalConfigPath = join(testState.fakeHomeDir, '.codex', 'config.toml') - writeFileSync(canonicalConfigPath, 'sandbox_mode = "danger-full-access"\n', 'utf-8') - const managedHomePath = createManagedHome( - testState.userDataDir, - 'account-1', - 'approval_policy = "on-request"\n' - ) - const settings = createSettings({ - codexManagedAccounts: [ - { - id: 'account-1', - email: 'user@example.com', - managedHomePath, - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] - }) - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - writeFileSync(join(managedHomePath, 'config.toml'), 'approval_policy = "untrusted"\n', 'utf-8') - - await service.selectAccount('account-1') - - expect(readFileSync(join(managedHomePath, 'config.toml'), 'utf-8')).toBe( - 'sandbox_mode = "danger-full-access"\napproval_policy = "untrusted"\n' - ) - expect(rateLimits.refreshForCodexAccountChange).toHaveBeenCalledTimes(1) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/codex-accounts/service.ts b/src/main/codex-accounts/service.ts index dc7dd4eaa44..1727a8639ff 100644 --- a/src/main/codex-accounts/service.ts +++ b/src/main/codex-accounts/service.ts @@ -13,33 +13,25 @@ import type { CodexRuntimeHomeService } from './runtime-home-service' import type { Store } from '../persistence/loading-store/store' import type { RateLimitService } from '../rate-limits/service/rate-limit-service' import { admitSelfInitiatedTreeKill } from '../pty/process-retirement/own-chromium-tree-kill-guard' -import type { CodexAccountSelectionTarget } from './runtime-selection' -import { CodexAccountIdentity, type ResolvedCodexIdentity } from './codex-account-identity' -import { CodexConfigMirror } from './codex-config-mirror' -import { runCodexLoginSession, type CodexLoginChild } from './codex-login-session' -import { CodexManagedHomePath } from './codex-managed-home-path' -import { CodexManagedHomeLifecycle } from './codex-managed-home-lifecycle' -import { CodexResetCreditCoordinator } from './codex-reset-credit-coordinator' -import { CodexAccountSelection } from './codex-account-selection' -import { CodexAccountRegistration } from './codex-account-registration' +import type { CodexAccountSelectionTarget } from '../../shared/codex-selection-lane' +import { CodexAccountIdentity } from './credentials/codex-account-identity' +import type { CodexAuthIdentity as ResolvedCodexIdentity } from './credentials/codex-auth-identity' +import { CodexConfigMirror } from './managed-homes/codex-config-mirror' +import { runCodexLoginSession, type CodexLoginChild } from './login/codex-login-session' +import { CodexManagedHomePath } from './managed-homes/codex-managed-home-path' +import { CodexManagedHomeLifecycle } from './managed-homes/codex-managed-home-lifecycle' +import { CodexResetCreditCoordinator } from './reset-credits/codex-reset-credit-coordinator' +import { CodexAccountSelection } from './account-management/codex-account-selection' +import { CodexAccountRegistration } from './account-management/codex-account-registration' import type { CodexAccountAddTarget, CodexAccountReauthenticateOptions, CodexAccountServiceLifecycle, CodexResetCreditConsumeResult -} from './codex-account-service-types' -import { toCodexManagedAccountSummary } from './codex-account-service-types' +} from './account-management/codex-account-service-types' +import { toCodexManagedAccountSummary } from './account-management/codex-account-service-types' import { CODEX_LOGIN_CANCELLED_MESSAGE } from '../../shared/codex-auth-errors' import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' -export type { - CodexAccountAddTarget, - CodexAccountReauthenticateOptions, - CodexAccountServiceLifecycle, - CodexResetCreditConsumeResult, - CodexResetCreditConsumedResult, - CodexResetCreditRejectedBeforeProviderReason, - CodexResetCreditRejectedBeforeProviderResult -} from './codex-account-service-types' const WINDOWS_LOGIN_TREE_KILL_TIMEOUT_MS = 5_000 diff --git a/src/main/codex-accounts/sta-4735-unreadable-host-lane-writes.test.ts b/src/main/codex-accounts/sta-4735-unreadable-host-lane-writes.test.ts deleted file mode 100644 index 738b585beac..00000000000 --- a/src/main/codex-accounts/sta-4735-unreadable-host-lane-writes.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFs from 'node:fs' -import { join } from 'node:path' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createCodexAccountRecord, - createCodexAuthJson, - createManagedAuth, - createStore, - getRuntimeCodexAuthPath, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -const denials = vi.hoisted(() => { - const state = { - paths: new Set(), - reads: new Map(), - deny(path: string): void { - state.paths.add(path) - }, - release(path: string): void { - state.paths.delete(path) - }, - readsFor(path: string): number { - return state.reads.get(path) ?? 0 - }, - reset(): void { - state.paths.clear() - state.reads.clear() - }, - check(target: unknown, syscall: string): void { - if (typeof target !== 'string' || !state.paths.has(target)) { - return - } - state.reads.set(target, (state.reads.get(target) ?? 0) + 1) - const error: NodeJS.ErrnoException = new Error( - `EPERM: operation not permitted, ${syscall} '${target}'` - ) - error.code = 'EPERM' - error.errno = -4048 - error.syscall = syscall - error.path = target - throw error - } - } - return state -}) - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - const guard = (fn: unknown, syscall: string): unknown => { - const original = fn as (...args: unknown[]) => unknown - const wrapped = (...args: unknown[]): unknown => { - denials.check(args[0], syscall) - return original(...args) - } - return Object.assign(wrapped, original) - } - const patched: Record = { - ...actual, - readFileSync: guard(actual.readFileSync, 'read'), - lstatSync: guard(actual.lstatSync, 'lstat'), - statSync: guard(actual.statSync, 'stat'), - existsSync: Object.assign( - (...args: unknown[]): boolean => - typeof args[0] === 'string' && denials.paths.has(args[0]) - ? false - : actual.existsSync(args[0] as string), - actual.existsSync - ) - } - return { ...patched, default: patched } -}) - -vi.mock('electron', () => ({ app: { getPath: () => testState.userDataDir } })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, homedir: () => testState.fakeHomeDir } -}) - -const realFs = await vi.importActual('node:fs') - -type RuntimeAuthWriter = { - writeRuntimeAuth( - contents: string, - owner: { owner: 'system-default' } | { owner: 'managed'; accountId: string }, - options?: { expectedContents: string | null } - ): boolean -} - -describe('STA-4735 an unreadable runtime auth.json must not be written over', () => { - beforeEach(() => { - denials.reset() - setupRuntimeHomeTest() - }) - - afterEach(() => { - denials.reset() - teardownRuntimeHomeTest() - }) - - async function createService(): Promise { - const managedHomePath = createManagedAuth( - testState.userDataDir, - 'account-1', - createCodexAuthJson('user@example.com', 'acct-1', 'refresh-1') - ) - const store = createStore( - createSettings({ - codexManagedAccounts: [ - createCodexAccountRecord('account-1', 'user@example.com', 'acct-1', managedHomePath) - ], - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - ) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - return new CodexRuntimeHomeService(store as never) as unknown as RuntimeAuthWriter - } - - it('refuses the write instead of overwriting a token it could not read', async () => { - const service = await createService() - const runtimeAuthPath = getRuntimeCodexAuthPath() - const ROTATED = createCodexAuthJson('user@example.com', 'acct-1', 'refresh-rotated-by-codex') - const STALE = createCodexAuthJson('user@example.com', 'acct-1', 'refresh-stale-orca-copy') - realFs.mkdirSync(join(runtimeAuthPath, '..'), { recursive: true }) - realFs.writeFileSync(runtimeAuthPath, ROTATED, 'utf-8') - - denials.deny(runtimeAuthPath) - const wrote = service.writeRuntimeAuth(STALE, { owner: 'managed', accountId: 'account-1' }) - - expect(denials.readsFor(runtimeAuthPath)).toBeGreaterThan(0) - expect(wrote).toBe(false) - expect(realFs.readFileSync(runtimeAuthPath, 'utf-8')).toBe(ROTATED) - }) -}) diff --git a/src/main/codex-accounts/wsl-codex-command.ts b/src/main/codex-cli/wsl-codex-command.ts similarity index 100% rename from src/main/codex-accounts/wsl-codex-command.ts rename to src/main/codex-cli/wsl-codex-command.ts diff --git a/src/main/codex-usage/codex-usage-record-parser.ts b/src/main/codex-usage/codex-usage-record-parser.ts index e09c7fd21f7..9594162c767 100644 --- a/src/main/codex-usage/codex-usage-record-parser.ts +++ b/src/main/codex-usage/codex-usage-record-parser.ts @@ -1,4 +1,4 @@ -import { extractString } from '../usage/source-input/usage-record-coercion' +import { extractString } from '../../shared/trimmed-string' import { buildCodexUsageEventKey, normalizeRawUsage, diff --git a/src/main/codex/app-server/codex-app-server-connection-tree-unproven.test.ts b/src/main/codex/app-server/codex-app-server-connection-tree-unproven.test.ts index 379c8478551..1797e0fb31f 100644 --- a/src/main/codex/app-server/codex-app-server-connection-tree-unproven.test.ts +++ b/src/main/codex/app-server/codex-app-server-connection-tree-unproven.test.ts @@ -3,10 +3,8 @@ import { PassThrough } from 'node:stream' import { afterEach, describe, expect, it, vi } from 'vitest' import type { spawnProcess } from '@orca/process-host' import type { DescendantTreeVerdict } from '../../pty/process-retirement/pty-descendant-exit-verification' -import { providerRequestTimeoutOf } from '../../provider-process/provider-request-timeout' + import { openCodexAppServerConnection } from './codex-app-server-connection' -import { CodexAppServerTimeoutError } from './codex-app-server-session' -import { codexTurnLifecycleRig } from '../structured/turns/codex-structured-dispatch-test-support' const teardown = vi.hoisted(() => { const state: { verdict: DescendantTreeVerdict; rootExits: () => void } = { @@ -15,7 +13,7 @@ const teardown = vi.hoisted(() => { } return state }) -vi.mock('../../claude/claude-agent-sdk-exit-proof', () => ({ +vi.mock('../../claude/child-process/claude-agent-sdk-exit-proof', () => ({ createClaudeChildTreeReaper: () => ({ capture: async () => {}, refresh: async () => {}, @@ -50,83 +48,6 @@ function stubChild() { } describe('Codex process-tree diagnostic after a forced close', () => { - it.each([undefined, 'turn-1'])( - 'bounds unanswered Stop %s and ignores its late reply after replacement', - async (turnId) => { - const rig = await codexTurnLifecycleRig() - const session = rig.adapter['sessions'].get('session-1')! - session.activeTurnIds?.add('turn-1') - vi.useFakeTimers() - const { child, spawnImpl } = stubChild() - const connection = await openCodexAppServerConnection( - { command: 'codex', args: [] }, - {}, - spawnImpl - ) - const original = session.connection - session.connection = connection - const acceptedAt = Date.now() - const stopping = rig.adapter.cancelTurn({ - sessionId: 'session-1', - fence: 7, - turnId, - stoppedAt: Date.now() - 4_900 - }) - let settled = false - const observed = stopping.then((outcome) => { - settled = true - return outcome - }) - await vi.advanceTimersByTimeAsync(99) - expect(settled).toBe(false) - await vi.advanceTimersByTimeAsync(1) - const outcome = await observed - expect(Date.now() - acceptedAt).toBe(100) - expect(outcome).toMatchObject({ - cancelled: false, - stop: { - pause: 'unconfirmed', - interrupt: 'unconfirmed', - root: 'unproven', - workload: 'unproven' - } - }) - const timeouts = outcome.stop?.errors.flatMap((error) => - error instanceof CodexAppServerTimeoutError && 'providerRequestTimeout' in error - ? [error.providerRequestTimeout] - : [] - ) - expect(timeouts).toEqual([ - { method: 'thread/goal/get', timeoutMs: expect.closeTo(100 / 3, 3) }, - { method: 'turn/interrupt', timeoutMs: 67 } - ]) - expect(providerRequestTimeoutOf(outcome.stop?.errors[1])).toEqual({ - method: 'turn/interrupt', - timeoutMs: 67 - }) - expect(outcome.stop?.errors).toHaveLength(3) - expect(outcome.stop?.errors[2]).toEqual(new Error('codex Stop reconciliation unavailable')) - const replacement = { - ...session, - connection: original, - fence: 8, - abortedTurnIds: new Set() - } - rig.adapter['sessions'].set('session-1', replacement) - const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) - child.stdout.write(`${JSON.stringify({ id: 2, result: {} })}\n`) - await vi.advanceTimersByTimeAsync(0) - expect(replacement.abortedTurnIds.size).toBe(0) - expect(warning).toHaveBeenCalled() - warning.mockRestore() - teardown.rootExits = () => child.emit('exit', 0, null) - const closing = connection.close() - await vi.advanceTimersByTimeAsync(10_000) - await closing - await rig.adapter.closeAll() - } - ) - it('reports a root exit that arrives after an unproven close', async () => { vi.useFakeTimers() teardown.verdict = 'unverifiable' diff --git a/src/main/codex/app-server/codex-app-server-connection.ts b/src/main/codex/app-server/codex-app-server-connection.ts index cb5a536f5ee..213e5153ea6 100644 --- a/src/main/codex/app-server/codex-app-server-connection.ts +++ b/src/main/codex/app-server/codex-app-server-connection.ts @@ -1,7 +1,7 @@ import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import { spawnProcess } from '@orca/process-host' import { spawnManagedProviderProcess } from '../../provider-process/managed-provider-process' -import { createClaudeChildTreeReaper } from '../../claude/claude-agent-sdk-exit-proof' +import { createClaudeChildTreeReaper } from '../../claude/child-process/claude-agent-sdk-exit-proof' import type { ProviderProcessLaunch } from '../../provider-process/provider-process-launch' import { buildCodexAppServerExitError } from './codex-app-server-exit-error' import { withProviderSpawnAbsence } from '../../provider-process/provider-executable-missing' diff --git a/src/main/codex/codex-conversation-copy.test.ts b/src/main/codex/codex-conversation-copy.test.ts index 255afde830d..579f5e6560b 100644 --- a/src/main/codex/codex-conversation-copy.test.ts +++ b/src/main/codex/codex-conversation-copy.test.ts @@ -1,14 +1,14 @@ import type * as AppServerSession from './app-server/codex-app-server-session' -import type * as LocalHistory from '../native-chat/codex-local-history' -import type * as RolloutStream from '../native-chat/codex-rollout-history-stream' -import { readCodexLocalHistory } from '../native-chat/codex-local-history' -import { readCodexRolloutBytes } from '../native-chat/codex-rollout-history-stream' +import type * as LocalHistory from '../native-chat/transcript-history/codex/codex-local-history' +import type * as RolloutStream from '../native-chat/transcript-history/codex/codex-rollout-history-stream' +import { readCodexLocalHistory } from '../native-chat/transcript-history/codex/codex-local-history' +import { readCodexRolloutBytes } from '../native-chat/transcript-history/codex/codex-rollout-history-stream' import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../native-chat/testing/agent-session-record-test-fixture' import { copyCodexConversation } from './codex-conversation-copy' import { CodexAppServerTimeoutError } from './app-server/codex-app-server-session' import type { CodexAppServerRpc } from './app-server/codex-app-server-session' @@ -26,14 +26,17 @@ const state = vi.hoisted(() => { session } }) -vi.mock('../native-chat/codex-local-history', async (importOriginal) => { +vi.mock('../native-chat/transcript-history/codex/codex-local-history', async (importOriginal) => { const original = await importOriginal() return { ...original, readCodexLocalHistory: vi.fn(original.readCodexLocalHistory) } }) -vi.mock('../native-chat/codex-rollout-history-stream', async (importOriginal) => { - const original = await importOriginal() - return { ...original, readCodexRolloutBytes: vi.fn(original.readCodexRolloutBytes) } -}) +vi.mock( + '../native-chat/transcript-history/codex/codex-rollout-history-stream', + async (importOriginal) => { + const original = await importOriginal() + return { ...original, readCodexRolloutBytes: vi.fn(original.readCodexRolloutBytes) } + } +) vi.mock('../native-chat/session-file-resolver', () => ({ resolveSessionFilePath: async (_agent: string, id: string) => state.paths.get(id) ?? null })) diff --git a/src/main/codex/codex-conversation-copy.ts b/src/main/codex/codex-conversation-copy.ts index cb3b3a9adee..0feafb610c2 100644 --- a/src/main/codex/codex-conversation-copy.ts +++ b/src/main/codex/codex-conversation-copy.ts @@ -4,12 +4,12 @@ import { AgentConversationCopyError, AgentConversationCopyStartError, agentConversationCopyRefusal -} from '../native-chat/agent-conversation-copy-error' +} from '../native-chat/conversation-adoption/agent-conversation-copy-error' import { isAgentSessionRefusalError } from '../../shared/agent-session/failures/agent-session-wire-refusals' import { join } from 'node:path' import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { asRecord } from '../ai-vault/session-scanner-values' +import { asRecord } from '../ai-vault/parsing/session-record-fields' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' import { diff --git a/src/main/codex/codex-fork-history.ts b/src/main/codex/codex-fork-history.ts index 26d345e2693..194112e0cf3 100644 --- a/src/main/codex/codex-fork-history.ts +++ b/src/main/codex/codex-fork-history.ts @@ -1,9 +1,10 @@ -import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' +import { AgentConversationCopyError } from '../native-chat/conversation-adoption/agent-conversation-copy-error' import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { asRecord, parseJsonObject } from '../ai-vault/session-scanner-values' +import { asRecord } from '../ai-vault/parsing/session-record-fields' +import { parseJsonObject } from '../ai-vault/parsing/session-json-object' import { createLegacyIdentityTracker } from '../native-chat/agent-session-journal/history-import/journal-legacy-identity' -import { readCodexLocalHistory } from '../native-chat/codex-local-history' -import { decodeCodexTranscriptLine } from '../native-chat/transcript-line-decoders-codex' +import { readCodexLocalHistory } from '../native-chat/transcript-history/codex/codex-local-history' +import { decodeCodexTranscriptLine } from '../native-chat/transcript-decoding/transcript-line-decoders-codex' type Root = { id?: string; terminal: boolean; prompt: boolean } diff --git a/src/main/codex/configuration/homes/codex-pane-launch-account.ts b/src/main/codex/configuration/homes/codex-pane-launch-account.ts index cce19a18eed..f4d6ddf99d9 100644 --- a/src/main/codex/configuration/homes/codex-pane-launch-account.ts +++ b/src/main/codex/configuration/homes/codex-pane-launch-account.ts @@ -4,7 +4,7 @@ import { parseWslUncPath } from '../../../../shared/wsl-paths' import { getCodexSelectionTargetForAccount, getSelectedCodexAccountIdForTarget -} from '../../../codex-accounts/runtime-selection' +} from '../../../codex-accounts/account-management/runtime-selection' import { getCodexSelectionLaneKey, type CodexAccountSelectionTarget diff --git a/src/main/codex/configuration/homes/codex-stale-pane-accounts.ts b/src/main/codex/configuration/homes/codex-stale-pane-accounts.ts index d0f2f4562b6..b8aca42f3ef 100644 --- a/src/main/codex/configuration/homes/codex-stale-pane-accounts.ts +++ b/src/main/codex/configuration/homes/codex-stale-pane-accounts.ts @@ -1,5 +1,5 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { getSelectedCodexAccountIdForTarget } from '../../../codex-accounts/runtime-selection' +import { getSelectedCodexAccountIdForTarget } from '../../../codex-accounts/account-management/runtime-selection' import { forgetCodexPaneAccount, listRecordedCodexPaneAccounts diff --git a/src/main/codex/history/index/codex-session-index-heal.ts b/src/main/codex/history/index/codex-session-index-heal.ts index e7440e820e2..2c4e79b9b89 100644 --- a/src/main/codex/history/index/codex-session-index-heal.ts +++ b/src/main/codex/history/index/codex-session-index-heal.ts @@ -2,7 +2,7 @@ import { dirname, join } from 'node:path' import { resolveCodexCommand } from '../../../codex-cli/command' import { isTransientSqliteContention } from '../../../sqlite/sqlite-read-failure' import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../../../codex-cli/codex-read-only-app-server-args' -import { buildWslCodexAppServerArgs } from '../../../codex-accounts/wsl-codex-command' +import { buildWslCodexAppServerArgs } from '../../../codex-cli/wsl-codex-command' import { resolveWslExecutablePath } from '../../../wsl/execution/wsl-executable-path' import { getCodexSessionBackfillStateDirPath } from '../../configuration/homes/codex-home-paths' import { resolveCodexSessionBackfillPaths } from '../backfill/codex-session-backfill' diff --git a/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts b/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts index 270d1f4d972..c321b0b79e3 100644 --- a/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts +++ b/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts @@ -1,7 +1,7 @@ import type { ChildProcess } from 'node:child_process' import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolution' import { parseWslUncPath } from '../../../../shared/wsl-paths' -import { buildWslCodexAppServerArgs } from '../../../codex-accounts/wsl-codex-command' +import { buildWslCodexAppServerArgs } from '../../../codex-cli/wsl-codex-command' import { CODEX_READ_ONLY_APP_SERVER_ARGS } from '../../../codex-cli/codex-read-only-app-server-args' import { terminateCodexProbeChild } from '../../../codex-cli/codex-probe-termination' import { diff --git a/src/main/codex/history/journal-views/codex-cli-conversations.ts b/src/main/codex/history/journal-views/codex-cli-conversations.ts index 06e8d8de46e..ba47a93a8b1 100644 --- a/src/main/codex/history/journal-views/codex-cli-conversations.ts +++ b/src/main/codex/history/journal-views/codex-cli-conversations.ts @@ -1,12 +1,12 @@ import { join } from 'node:path' -import { configuredAdditionalCodexHomePaths } from '../../../ai-vault/cached-session-list' +import { configuredAdditionalCodexHomePaths } from '../../../ai-vault/discovery/ai-vault-scan-roots' import { resolveSessionFilePath } from '../../../native-chat/session-file-resolver' import { directoryTranscriptImport, resumeInvocationAfterMarker, type StructuredAgentCliConversations, type StructuredAgentSessionHistory -} from '../../../native-chat/structured-agent-cli-conversations' +} from '../../../native-chat/conversation-adoption/structured-agent-cli-conversations' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath diff --git a/src/main/codex/history/resume/codex-ai-vault-session-resume.test.ts b/src/main/codex/history/resume/codex-ai-vault-session-resume.test.ts index 0293fd8543b..e55f45352a6 100644 --- a/src/main/codex/history/resume/codex-ai-vault-session-resume.test.ts +++ b/src/main/codex/history/resume/codex-ai-vault-session-resume.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { linkSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/host-codex-managed-home-ownership' +import '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership' import { prepareCodexAiVaultSessionResume } from './codex-ai-vault-session-resume' import { getOrcaManagedCodexHomePath } from '../../configuration/homes/codex-home-paths' @@ -50,19 +50,6 @@ describe('prepareCodexAiVaultSessionResume', () => { rmSync(root, { recursive: true, force: true }) }) - it('refuses before falling through when selected-home trust is indeterminate', async () => { - const resolveSelectedHome = vi.fn((): string | null => { - throw new ManagedCodexHomeTemporarilyUnavailableError() - }) - const isSystemDefaultRealHome = vi.fn(() => true) - - await expect(prepare(resolveSelectedHome, isSystemDefaultRealHome)).rejects.toBeInstanceOf( - ManagedCodexHomeTemporarilyUnavailableError - ) - expect(resolveSelectedHome).toHaveBeenCalledOnce() - expect(isSystemDefaultRealHome).not.toHaveBeenCalled() - }) - it('repins an aliased rollout when the selected home is owned', async () => { await expect(prepare(() => selectedHome)).resolves.toEqual({ useRealCodexHome: false, diff --git a/src/main/codex/history/resume/codex-legacy-session-resume.test.ts b/src/main/codex/history/resume/codex-legacy-session-resume.test.ts index f3935fd8a4f..18572f29453 100644 --- a/src/main/codex/history/resume/codex-legacy-session-resume.test.ts +++ b/src/main/codex/history/resume/codex-legacy-session-resume.test.ts @@ -5,7 +5,7 @@ import { basename, join } from 'node:path' import type * as NodeFsPromises from 'node:fs/promises' import '../../../ai-vault/scanners/codex/codex-session-root-dedup' import { prepareLegacySharedCodexSessionResume } from './codex-legacy-session-resume' -import '../../../codex-accounts/host-codex-managed-home-ownership' +import '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership' const lstatFaults = vi.hoisted(() => ({ path: null as string | null, diff --git a/src/main/codex/history/resume/codex-legacy-session-resume.ts b/src/main/codex/history/resume/codex-legacy-session-resume.ts index 6670b15d4ab..de6cfa78889 100644 --- a/src/main/codex/history/resume/codex-legacy-session-resume.ts +++ b/src/main/codex/history/resume/codex-legacy-session-resume.ts @@ -21,7 +21,7 @@ import { } from '../backfill/codex-session-backfill-copy' import { resolveCodexSessionBackfillPaths } from '../backfill/codex-session-backfill' import { codexDatedRolloutRelativePath } from './codex-session-resume-home' -import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/host-codex-managed-home-ownership' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership' const RETRYABLE_RESUME_ERROR = 'Orca could not safely move this legacy Codex session into your system Codex home. Retry resume; if it still fails, check that both Codex session folders are readable and writable.' diff --git a/src/main/codex/history/resume/codex-session-resume-home.ts b/src/main/codex/history/resume/codex-session-resume-home.ts index 2d7e0b7cf2f..aca334454cd 100644 --- a/src/main/codex/history/resume/codex-session-resume-home.ts +++ b/src/main/codex/history/resume/codex-session-resume-home.ts @@ -6,7 +6,7 @@ import { relativePathInsideRoot } from '../../../../shared/cross-platform-path' import { listCodexSessionRolloutFilesIncrementally } from '../rollouts/codex-session-file-listing' -import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/host-codex-managed-home-ownership' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership' // Only the dated rollout layout may establish credential provenance. const CLAIMED_CODEX_ROLLOUT_TAIL = String.raw`\d{4}/\d{2}/\d{2}/rollout-[^/]+\.jsonl(?:\.zst)?` diff --git a/src/main/codex/history/resume/codex-session-resume-launch-preparation.ts b/src/main/codex/history/resume/codex-session-resume-launch-preparation.ts index 2834dfc6d69..f695b2cb788 100644 --- a/src/main/codex/history/resume/codex-session-resume-launch-preparation.ts +++ b/src/main/codex/history/resume/codex-session-resume-launch-preparation.ts @@ -9,7 +9,7 @@ import { prepareCodexAccountRestartResume, prepareLegacySharedCodexSessionResume } from './codex-legacy-session-resume' -import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/host-codex-managed-home-ownership' +import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership' import { codexHookService } from '../../hooks/installation/hook-service' import { reconcileCodexHooksForLaunch } from '../../hooks/reconciliation/codex-hook-reconcile' import { ensureCodexDaemonSocketGuard } from '../../configuration/settings/codex-config-mirror' diff --git a/src/main/codex/history/resume/codex-session-resume-wrong-account.test.ts b/src/main/codex/history/resume/codex-session-resume-wrong-account.test.ts index 5d72d3a148d..2acc160e880 100644 --- a/src/main/codex/history/resume/codex-session-resume-wrong-account.test.ts +++ b/src/main/codex/history/resume/codex-session-resume-wrong-account.test.ts @@ -80,7 +80,7 @@ vi.mock('node:fs/promises', async (importOriginal) => { const { findTrustedCodexSessionResume } = await import('./codex-session-resume-home') const { ManagedCodexHomeTemporarilyUnavailableError } = - await import('../../../codex-accounts/host-codex-managed-home-ownership') + await import('../../../codex-accounts/managed-homes/host-codex-managed-home-ownership') const tempRoots: string[] = [] const SESSION_ID = '11111111-2222-3333-4444-555555555555' @@ -107,42 +107,6 @@ afterEach(() => { }) describe('STA-4607 session resume under a briefly unreadable sessions tree', () => { - it('refuses rather than resuming the selected account under another account home', async () => { - const root = mkdtempSync(join(tmpdir(), 'orca-sta4607-')) - tempRoots.push(root) - const selectedHome = makeHomeWithRollout(root, 'account-a') - const otherHome = makeHomeWithRollout(root, 'account-b') - - const args = { - sessionId: SESSION_ID, - transcriptPath: undefined, - trustedCodexHomes: [selectedHome, otherHome], - getSelectedAccountCodexHome: (): string | null => selectedHome, - systemCodexHomePath: null, - sharedRuntimeCodexHomePath: null - } - - await expect(findTrustedCodexSessionResume(args)).resolves.toEqual({ - homePath: selectedHome, - transcriptPath: join( - selectedHome, - 'sessions', - '2026', - '07', - '20', - `rollout-${SESSION_ID}.jsonl` - ) - }) - - const selectedSessionsRoot = join(selectedHome, 'sessions') - statFaults.hold(selectedSessionsRoot) - - await expect(findTrustedCodexSessionResume(args)).rejects.toBeInstanceOf( - ManagedCodexHomeTemporarilyUnavailableError - ) - expect(statFaults.readsFor(selectedSessionsRoot)).toBeGreaterThan(0) - }) - it('still skips a definitively absent sessions tree', async () => { const root = mkdtempSync(join(tmpdir(), 'orca-sta4607-')) tempRoots.push(root) diff --git a/src/main/codex/history/rollouts/codex-account-home-discovery.ts b/src/main/codex/history/rollouts/codex-account-home-discovery.ts index 0174b98fb8f..2463429d137 100644 --- a/src/main/codex/history/rollouts/codex-account-home-discovery.ts +++ b/src/main/codex/history/rollouts/codex-account-home-discovery.ts @@ -4,7 +4,7 @@ import { getOrcaUserDataPath, getSystemCodexHomePath } from '../../configuration/homes/codex-home-paths' -import { assertOwnedHostCodexManagedHomePath } from '../../../codex-accounts/host-codex-managed-home-ownership' +import { assertOwnedHostCodexManagedHomePath } from '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership' // Enumerate disk to include retired accounts without a settings store; WSL scans its own homes. export function getCodexAccountHomeSessionDirectories(): string[] { diff --git a/src/main/codex/history/rollouts/codex-rollout-session-meta.ts b/src/main/codex/history/rollouts/codex-rollout-session-meta.ts index 74317f0f5de..a4c87ee826e 100644 --- a/src/main/codex/history/rollouts/codex-rollout-session-meta.ts +++ b/src/main/codex/history/rollouts/codex-rollout-session-meta.ts @@ -1,13 +1,13 @@ import { openTranscriptReadStream, readTranscriptSlice -} from '../../../native-chat/wsl-transcript-fs-access' +} from '../../../native-chat/transcript-filesystem/wsl-transcript-fs-access' import { isZstdTranscriptPath, readZstdTranscriptSlice, zstdTranscriptStream -} from '../../../native-chat/transcript-zstd-decompression' -import type { WslTranscriptFsTaskPriority } from '../../../native-chat/wsl-transcript-fs-gate' +} from '../../../native-chat/transcript-streaming/transcript-zstd-decompression' +import type { WslTranscriptFsTaskPriority } from '../../../native-chat/transcript-filesystem/wsl-transcript-fs-gate' const ROLLOUT_READ_LIMIT = 64 * 1024 diff --git a/src/main/codex/hooks/definitions/codex-hook-command-form.ts b/src/main/codex/hooks/definitions/codex-hook-command-form.ts index d39884dfb05..25fa64e95e3 100644 --- a/src/main/codex/hooks/definitions/codex-hook-command-form.ts +++ b/src/main/codex/hooks/definitions/codex-hook-command-form.ts @@ -1,8 +1,15 @@ // Shared HOME builds must freeze command bytes per form to avoid rewrite/trust loops. // Bump the form to change bytes; preserve entries from higher forms. -export const CODEX_HOOK_COMMAND_FORM = 1 +export const CODEX_HOOK_COMMAND_FORM = 2 const FORM_MARKER = /orca-agent-hook-form=(\d+)/ +const STATUS_MESSAGE_FORM = 2 + +/** Unmarked commands (Windows, SSH, WSL) cannot tell older builds the entry changed, so they stay unnamed. */ +export function codexHookCommandCarriesStatusMessage(command: string): boolean { + const marker = FORM_MARKER.exec(command) + return marker !== null && Number(marker[1]) >= STATUS_MESSAGE_FORM +} // Keep literals independent of shared hook constants to freeze these bytes. const POSIX_STDIN_DRAIN = '{ command -p cat 2>/dev/null || cat; } >/dev/null 2>&1 || :' diff --git a/src/main/codex/hooks/definitions/codex-hook-definition.ts b/src/main/codex/hooks/definitions/codex-hook-definition.ts index f59c2790cf1..942a9d32baa 100644 --- a/src/main/codex/hooks/definitions/codex-hook-definition.ts +++ b/src/main/codex/hooks/definitions/codex-hook-definition.ts @@ -13,7 +13,10 @@ import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from '../../configuration/homes/codex-home-paths' -import { buildCodexHookCommand as getManagedCommand } from './codex-hook-command-form' +import { + buildCodexHookCommand as getManagedCommand, + codexHookCommandCarriesStatusMessage +} from './codex-hook-command-form' import { CODEX_HOOK_EVENT_LABEL, getCodexManagedScriptFileName } from './codex-hook-identity' import { getManagedScript } from './codex-hook-script' import type { CodexEventLabel } from '../../trust/toml/config-toml-trust' @@ -68,15 +71,26 @@ export const CODEX_EVENT_LABEL: Record<(typeof CODEX_EVENTS)[number], CodexEvent Interrupt: CODEX_HOOK_EVENT_LABEL.Interrupt! } +// Codex's hook review lists unnamed hooks as "Hook N"; Codex hashes this, so changing it needs a new command form. +const CODEX_MANAGED_HOOK_STATUS_MESSAGE = 'Reporting status to Orca' + +export function getCodexManagedHookStatusMessage(command: string): string | undefined { + return codexHookCommandCarriesStatusMessage(command) + ? CODEX_MANAGED_HOOK_STATUS_MESSAGE + : undefined +} + // Clamp to Codex's per-event timeout caps (Interrupt: 3s) to avoid startup warnings. export function buildCodexManagedHook( command: string, eventName: (typeof CODEX_EVENTS)[number] ): HookCommandConfig { - return buildManagedCommandHook( + const hook = buildManagedCommandHook( command, normalizeCodexHookTimeoutSec(CODEX_EVENT_LABEL[eventName], MANAGED_HOOK_TIMEOUT_SECONDS) ) + const statusMessage = getCodexManagedHookStatusMessage(command) + return statusMessage ? { ...hook, statusMessage } : hook } export const CODEX_MANAGED_EVENT_LABELS = new Set( @@ -90,6 +104,7 @@ export function computeOrcaCodexHookHashes( return Object.fromEntries( CODEX_EVENTS.map((eventName) => { const eventLabel = CODEX_EVENT_LABEL[eventName] + const hook = buildCodexManagedHook(command, eventName) return [ eventLabel, computeCodexTrustedHash({ @@ -98,7 +113,8 @@ export function computeOrcaCodexHookHashes( groupIndex: 0, handlerIndex: 0, command, - timeoutSec: buildCodexManagedHook(command, eventName).timeout + timeoutSec: hook.timeout, + statusMessage: hook.statusMessage }) ] }) diff --git a/src/main/codex/hooks/installation/codex-hook-local-install.ts b/src/main/codex/hooks/installation/codex-hook-local-install.ts index 3f95b4ff1ea..5461aff822a 100644 --- a/src/main/codex/hooks/installation/codex-hook-local-install.ts +++ b/src/main/codex/hooks/installation/codex-hook-local-install.ts @@ -129,6 +129,7 @@ export async function installCodexHooksExclusively( handlerIndex: 0, command, timeoutSec: hook.timeout, + statusMessage: hook.statusMessage, trustedHash, // Orca's setting overrides Codex's /hooks off switch for this hook. enabled: true diff --git a/src/main/codex/hooks/installation/codex-hook-remote-install.ts b/src/main/codex/hooks/installation/codex-hook-remote-install.ts index c726d8ac979..bf9f4711143 100644 --- a/src/main/codex/hooks/installation/codex-hook-remote-install.ts +++ b/src/main/codex/hooks/installation/codex-hook-remote-install.ts @@ -89,6 +89,7 @@ export async function installCodexHooksRemote( handlerIndex: 0, command, timeoutSec: hook.timeout, + statusMessage: hook.statusMessage, // Orca's setting overrides Codex's /hooks off switch for this hook, as local installs do. enabled: true }) diff --git a/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts b/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts index d4d224e3ba2..483691dc63f 100644 --- a/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts +++ b/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts @@ -110,7 +110,8 @@ async function installManagedHooksIntoWslRuntimeExclusively( groupIndex: 0, handlerIndex: 0, command, - timeoutSec: hook.timeout + timeoutSec: hook.timeout, + statusMessage: hook.statusMessage }) } diff --git a/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts b/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts index 165e88a18eb..4e2eea199c6 100644 --- a/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts +++ b/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts @@ -46,11 +46,7 @@ vi.mock( import './hook-service' import { CodexHookService } from './codex-hook-service-implementation' -import { - _internals as lookupInternals, - startCodexHookHashLookup -} from '../../trust/hooks/codex-hook-hash-lookup' -import { memoizeCodexHookAnswer } from '../../trust/hooks/codex-hook-trust-memo' +import { startCodexHookHashLookup } from '../../trust/hooks/codex-hook-hash-lookup' import type { CodexHookAnswer } from '../../trust/hooks/codex-hook-trust-derivation' import { readHookTrustEntries, @@ -66,6 +62,7 @@ import { CODEX_EVENTS, CODEX_EVENT_LABEL, computeOrcaCodexHookHashes, + getCodexManagedHookStatusMessage, getManagedScriptPath } from '../definitions/codex-hook-definition' import { buildCodexHookCommand as getManagedCommand } from '../definitions/codex-hook-command-form' @@ -168,37 +165,6 @@ describe('managed-home Codex hook approval', () => { ).toBe(undefined) }) - it("leaves user trust byte-untouched while approving Orca's entries", async () => { - mkdirSync(managedHome(), { recursive: true }) - const userBlock = [ - '[hooks.state."/home/user/.codex/hooks.json:stop:3:1"]', - 'enabled = false', - 'trusted_hash = "sha256:user-owned-hash"' - ].join('\n') - writeFileSync(join(managedHome(), 'config.toml'), `${userBlock}\n`) - useCodexHashes() - - expect((await new CodexHookService().install()).state).toBe('installed') - expect(readFileSync(join(managedHome(), 'config.toml'), 'utf-8')).toContain(userBlock) - }) - - it("turning hooks off removes an approval from an older Codex version's hash", async () => { - useCodexHashes() - expect((await new CodexHookService().install()).state).toBe('installed') - lookupInternals.resetForTesting() - memoizeCodexHookAnswer(join(homes.userDataDir, 'codex'), 'codex-0.160', command(), { - kind: 'hashes', - codexVersion: 'codex-cli 0.160.0', - hashes: { stop: 'sha256:codex-0.160-stop' } - }) - - await new CodexHookService().remove() - - const trust = readHookTrustEntries(join(managedHome(), 'config.toml')) - expect(trust.get(managedKey('stop', 0))).toBeUndefined() - expect(trust.get(managedKey('session_start', 0))).toBeUndefined() - }) - it("keeps the managed config.toml loadable when hooks are off and the user's approvals are inline", async () => { const systemHome = join(homes.tmpHome, '.codex') mkdirSync(systemHome, { recursive: true }) @@ -291,7 +257,8 @@ describe('managed-home Codex hook approval', () => { groupIndex: 0, handlerIndex: 0, command: command(), - timeoutSec: 10 + timeoutSec: 10, + statusMessage: getCodexManagedHookStatusMessage(command()) } upsertHookTrustEntries(join(managedHome(), 'config.toml'), [ { ...entry, trustedHash: 'sha256:main-granted' } diff --git a/src/main/codex/hooks/installation/hook-service-trust-grant.test.ts b/src/main/codex/hooks/installation/hook-service-trust-grant.test.ts deleted file mode 100644 index 73a2fe45a15..00000000000 --- a/src/main/codex/hooks/installation/hook-service-trust-grant.test.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - chmodSync, - lstatSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - symlinkSync, - statSync, - writeFileSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import type * as Os from 'node:os' -import { join } from 'node:path' -import { - readHookTrustEntries, - upsertHookTrustEntries, - type CodexTrustEntry -} from '../../trust/toml/config-toml-trust' -import { - computeCodexTrustKey as computeTrustKey, - normalizeCodexHookTrustLookupKey as normalizeHookTrustKeyForLookup -} from '../../trust/identity/codex-trust-identity' -import { codexAppServerCapabilityCache } from '../../app-server/codex-app-server-capability-cache' -import { _internals as trustGrantInternals } from '../../trust/grants/codex-hook-trust-grant' -import { - readCodexTrustGrantLedgerHome, - writeCodexTrustGrantLedgerHome -} from '../../trust/grants/codex-trust-grant-ledger' -import { getCodexHookTrustSignature } from '../definitions/codex-hook-identity' - -const { getPathMock, homedirMock, resolveCodexCommandMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>(), - homedirMock: vi.fn<() => string>(), - resolveCodexCommandMock: vi.fn<() => string>() -})) - -vi.mock('electron', () => ({ app: { getPath: getPathMock } })) -vi.mock('os', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, homedir: homedirMock } -}) -vi.mock('../../../codex-cli/command', () => ({ resolveCodexCommand: resolveCodexCommandMock })) - -import './hook-service' -import { CodexHookService } from './codex-hook-service-implementation' -import { getCodexManagedHookInstallMaterial } from '../definitions/codex-hook-definition' - -let tmpHome: string -let userDataDir: string -let previousUserDataPath: string | undefined -let previousDisableTrustRpc: string | undefined - -beforeEach(() => { - previousDisableTrustRpc = process.env.ORCA_DISABLE_CODEX_TRUST_RPC - delete process.env.ORCA_DISABLE_CODEX_TRUST_RPC - tmpHome = mkdtempSync(join(tmpdir(), 'orca-codex-home-')) - userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-user-data-')) - previousUserDataPath = process.env.ORCA_USER_DATA_PATH - process.env.ORCA_USER_DATA_PATH = userDataDir - homedirMock.mockReturnValue(tmpHome) - resolveCodexCommandMock.mockReturnValue(process.execPath) - getPathMock.mockImplementation((name: string) => { - if (name === 'userData') { - return userDataDir - } - throw new Error(`unexpected app.getPath(${name})`) - }) - trustGrantInternals.resetDiagnostics() - codexAppServerCapabilityCache.clear() -}) - -afterEach(() => { - trustGrantInternals.setGrantSessionRunner(null) - trustGrantInternals.resetDiagnostics() - codexAppServerCapabilityCache.clear() - if (previousDisableTrustRpc === undefined) { - delete process.env.ORCA_DISABLE_CODEX_TRUST_RPC - } else { - process.env.ORCA_DISABLE_CODEX_TRUST_RPC = previousDisableTrustRpc - } - rmSync(tmpHome, { recursive: true, force: true }) - rmSync(userDataDir, { recursive: true, force: true }) - if (previousUserDataPath === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previousUserDataPath - } - vi.clearAllMocks() -}) - -function forbidGrantSessions(): ReturnType { - const runner = vi.fn(async () => { - throw new Error('opt-out must not run a Codex trust-grant session') - }) - trustGrantInternals.setGrantSessionRunner(runner) - return runner -} - -function prepareSystemHome(): void { - mkdirSync(join(tmpHome, '.codex'), { recursive: true }) -} - -describe('CodexHookService opt-out of the real-home entry', () => { - it('retries ledger-proven real-home trust cleanup on opt-out after the hook is already gone', async () => { - prepareSystemHome() - const systemHome = join(tmpHome, '.codex') - const hooksPath = join(systemHome, 'hooks.json') - const configPath = join(systemHome, 'config.toml') - const material = getCodexManagedHookInstallMaterial() - const trustedHash = 'sha256:codex-real-home-stop' - const entry: CodexTrustEntry = { - sourcePath: hooksPath, - eventLabel: 'stop', - groupIndex: 0, - handlerIndex: 0, - command: material.command, - timeoutSec: 10, - trustedHash - } - const trustKey = computeTrustKey(entry) - writeFileSync(hooksPath, `${JSON.stringify({ hooks: {} }, null, 2)}\n`) - upsertHookTrustEntries(configPath, [entry]) - writeCodexTrustGrantLedgerHome(systemHome, { - binary: null, - entries: { - [normalizeHookTrustKeyForLookup(trustKey)]: { - signature: getCodexHookTrustSignature(entry), - trustedHash - } - } - }) - const grantSession = forbidGrantSessions() - - await new CodexHookService().remove() - - expect(grantSession).not.toHaveBeenCalled() - - expect(readHookTrustEntries(configPath).has(trustKey)).toBe(false) - expect(readCodexTrustGrantLedgerHome(systemHome)).toBeNull() - }) - - // Windows CI requires Developer Mode for file symlinks. - it.skipIf(process.platform === 'win32')( - 'keeps a real-home symlink and moves later user trust during an explicit opt-out', - async () => { - prepareSystemHome() - const systemHome = join(tmpHome, '.codex') - const hooksPath = join(systemHome, 'hooks.json') - const targetPath = join(tmpHome, 'dotfiles-hooks.json') - const material = getCodexManagedHookInstallMaterial() - const userHook = { type: 'command' as const, command: 'after-orca.sh' } - writeFileSync( - targetPath, - `${JSON.stringify( - { - hooks: { - Stop: [ - { hooks: [{ type: 'command', command: material.command }] }, - { hooks: [userHook] } - ] - } - }, - null, - 2 - )}\n` - ) - symlinkSync(targetPath, hooksPath) - const grantSession = forbidGrantSessions() - - await new CodexHookService().remove() - - expect(grantSession).not.toHaveBeenCalled() - - expect(lstatSync(hooksPath).isSymbolicLink()).toBe(true) - expect(JSON.parse(readFileSync(targetPath, 'utf-8')).hooks.Stop).toEqual([ - { hooks: [userHook] } - ]) - } - ) - - it.skipIf(process.platform === 'win32')( - 'preserves restrictive real-home hooks permissions during an explicit opt-out', - async () => { - prepareSystemHome() - const hooksPath = join(tmpHome, '.codex', 'hooks.json') - const material = getCodexManagedHookInstallMaterial() - writeFileSync( - hooksPath, - `${JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: material.command }] }] } }, null, 2)}\n` - ) - chmodSync(hooksPath, 0o600) - const grantSession = forbidGrantSessions() - - await new CodexHookService().remove() - - expect(grantSession).not.toHaveBeenCalled() - - expect(statSync(hooksPath).mode & 0o777).toBe(0o600) - } - ) -}) diff --git a/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts index 4b1f1ae6cff..922ffdfef5f 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts @@ -281,26 +281,6 @@ describe('reconcileCodexHooks', () => { expect(readHooks().Stop).toEqual([{ hooks: [buildCodexManagedHook(command(), 'Stop')] }]) }) - it('writes nothing and spawns nothing across many concurrent launches when nothing changed', async () => { - await start() - const before = snapshot(codexHome()) - const memoBefore = snapshot(userData) - vi.clearAllMocks() - - await Promise.all( - Array.from({ length: 20 }, (_, index) => { - scheduleCodexHookReconcile() - return index % 2 === 0 ? reconcileCodexHooksForLaunch() : reconcileCodexHooks() - }) - ) - await settleSpawn() - - expect(snapshot(codexHome())).toEqual(before) - expect(snapshot(userData)).toEqual(memoBefore) - expect(mocks.probeCodexVersion).not.toHaveBeenCalled() - expect(mocks.deriveCodexHookHashes).not.toHaveBeenCalled() - }) - it('rechecks a spawn that lands while a run is still finding Codex, which may miss a fresh install', async () => { const installed = mocks.codexPath mocks.codexPath = join(userData, 'missing-codex') @@ -408,24 +388,6 @@ describe('while the lookup is still asking Codex', () => { await settleSpawn() expect(stopApproval()).toBe(CODEX_HASHES.stop) }) - - it('writes nothing while an entry is already in place', async () => { - await start() - const before = snapshot(codexHome()) - // A different size invalidates the binary fingerprint even within one filesystem clock tick. - writeFileSync(mocks.codexPath, 'codex 0.161.0 updated') - const release = holdDerivation() - - await finishHeldLookupWait(reconcileCodexHooksForLaunch, true) - expect(snapshot(codexHome())).toEqual(before) - - const runsBeforeAnswer = mocks.realHomeRuns - release() - await settleSpawn() - expect(mocks.realHomeRuns).toBe(runsBeforeAnswer + 1) - await _internals.settledForTesting() - expect(snapshot(codexHome())).toEqual(before) - }) }) describe('a ~/.codex/hooks.json Orca cannot add to', () => { @@ -454,22 +416,6 @@ describe('a ~/.codex/hooks.json Orca cannot add to', () => { ) }) -describe("a ~/.codex/hooks.json with Codex's description key", () => { - it('takes the entry and keeps the description verbatim', async () => { - mkdirSync(codexHome(), { recursive: true }) - writeFileSync(hooksPath(), JSON.stringify({ description: 'My hooks — keep me', hooks: {} })) - - await start() - - const written = JSON.parse(readFileSync(hooksPath(), 'utf-8')) - expect(written.description).toBe('My hooks — keep me') - expect( - written.hooks.Stop.map((group: Hooks[string][number]) => group.hooks[0]!.command) - ).toEqual([command()]) - expect(readRealHomeHooksFileProblem()).toBeNull() - }) -}) - describe('an app start whose lookup has not answered within its wait', () => { it("keeps the saved answer's entries, writing nothing, when the version probe is slow", async () => { const before0150 = Object.fromEntries( @@ -507,7 +453,8 @@ describe('an app start whose lookup has not answered within its wait', () => { groupIndex: 0, handlerIndex: 0, command: command(), - timeoutSec: 10 + timeoutSec: 10, + statusMessage: buildCodexManagedHook(command(), 'Stop').statusMessage } writeHooks({ Stop: [{ hooks: [buildCodexManagedHook(command(), 'Stop')] }] }) upsertHookTrustEntries(tomlPath(), [{ ...stop, trustedHash: 'sha256:main-granted' }]) diff --git a/src/main/codex/hooks/reconciliation/codex-hook-status.ts b/src/main/codex/hooks/reconciliation/codex-hook-status.ts index 06eeca77cad..d68180c5260 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-status.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-status.ts @@ -198,6 +198,7 @@ function describeInlineApprovals( const slots = findOrcaEntrySlots(hooks, command) const probes: CodexTrustEntry[] = CODEX_EVENTS.flatMap((eventName) => { const label = CODEX_EVENT_LABEL[eventName] + const hook = buildCodexManagedHook(command, eventName) const hash = answer?.kind === 'hashes' ? answer.hashes[label] : 'probe' const definitions = hooks?.[eventName] const slot = slots.get(eventName) ?? { @@ -210,7 +211,8 @@ function describeInlineApprovals( sourcePath: home.keySourcePaths[0], eventLabel: label, command, - timeoutSec: buildCodexManagedHook(command, eventName).timeout, + timeoutSec: hook.timeout, + statusMessage: hook.statusMessage, trustedHash: hash, enabled: true, ...slot diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts index bb17c069df0..47f023d2df6 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts @@ -234,8 +234,32 @@ describe('reconcileRealHomeCodexHookEntries', () => { expect(existsSync(configPath())).toBe(false) }) + it.skipIf(process.platform === 'win32')( + "names the previous form's unnamed entry at app start, never on a launch", + async () => { + // Exact bytes form-1 builds wrote, which they still rewrite when they differ. + const formOne = [ + ': orca-agent-hook-form=1;', + 'if [ -n "${ORCA_PANE_KEY-}" ] && [ -n "${ORCA_AGENT_HOOK_ROOT-}" ] && [ -f "${ORCA_AGENT_HOOK_ROOT-}/agent-hooks/codex-hook.sh" ]; then /bin/sh "${ORCA_AGENT_HOOK_ROOT-}/agent-hooks/codex-hook.sh" || :;', + 'elif [ -z "${ORCA_AGENT_HOOK_ROOT-}" ] && [ -n "${ORCA_PANE_KEY-}" ] && [ -n "${ORCA_AGENT_HOOK_PORT-}" ] && [ -f "${HOME-}/.orca/agent-hooks/codex-hook.sh" ]; then /bin/sh "${HOME-}/.orca/agent-hooks/codex-hook.sh" || :;', + 'else { command -p cat 2>/dev/null || cat; } >/dev/null 2>&1 || :; fi' + ].join(' ') + const formOneStop = { hooks: [{ type: 'command', command: formOne, timeout: 10 }] } + writeHooks({ hooks: { Stop: [formOneStop] } }) + + await reconcile({ convertOlderForms: false }) + expect(readHooks().hooks.Stop).toEqual([formOneStop]) + + await reconcile() + expect(readHooks().hooks.Stop?.[0]?.hooks?.[0]).toMatchObject({ + command: expect.stringMatching(/^: orca-agent-hook-form=2;/), + statusMessage: 'Reporting status to Orca' + }) + } + ) + it('never rewrites a newer build form or appends beside it', async () => { - const newer = `: orca-agent-hook-form=2; /bin/sh "\${HOME-}/.orca/agent-hooks/codex-hook.sh"` + const newer = `: orca-agent-hook-form=3; /bin/sh "\${HOME-}/.orca/agent-hooks/codex-hook.sh"` writeHooks({ hooks: { Stop: [orcaGroup(newer)] } }) await reconcile() @@ -381,20 +405,6 @@ describe('reconcileRealHomeCodexHookEntries', () => { expect(trustAt(stopEntryAt(1, orcaGroup()))).toBeUndefined() }) - it.each([ - ['unknown top-level fields Codex cannot load', { hooks: {}, _managed: true }], - ['an unparseable file', '{ not json'] - ])('leaves %s untouched and approves nothing', async (_case, content) => { - mkdirSync(join(home, '.codex'), { recursive: true }) - writeFileSync(hooksPath(), typeof content === 'string' ? content : JSON.stringify(content)) - const before = identity(hooksPath()) - - expect(await reconcile()).toBe('unchanged') - - expect(identity(hooksPath())).toEqual(before) - expect(existsSync(configPath())).toBe(false) - }) - it('writes nothing when config.toml keeps its approvals inline', async () => { const original = writeHooks({ hooks: { Stop: [USER_A] } }) const inline = 'model = "m"\nhooks = { state = {} }\n' @@ -440,15 +450,3 @@ describe('reconcileRealHomeCodexHookEntries', () => { } ) }) - -describe('until Codex answers', () => { - it("keeps an entry's existing approval, writing nothing", async () => { - writeHooks({ hooks: { Stop: [USER_A] } }) - await reconcile() - const before = { hooks: identity(hooksPath()), toml: identity(configPath()) } - - expect(await reconcile({ hashes: null })).toBe('unchanged') - - expect({ hooks: identity(hooksPath()), toml: identity(configPath()) }).toEqual(before) - }) -}) diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-removal.test.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-removal.test.ts index 9c55678f9e7..4aed17ec967 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-removal.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-removal.test.ts @@ -26,10 +26,14 @@ vi.mock('node:os', async () => { return { ...actual, homedir: homedirMock } }) +import type { HookCommandConfig } from '../../../agent-hooks/installation/configuration/hook-config-schema' import { removeRealHomeCodexHookForOptOut } from './codex-real-home-hook-install' import '../installation/hook-service' import { CodexHookService } from '../installation/codex-hook-service-implementation' -import { getCodexManagedHookInstallMaterial } from '../definitions/codex-hook-definition' +import { + buildCodexManagedHook, + getCodexManagedHookInstallMaterial +} from '../definitions/codex-hook-definition' import { memoizeCodexHookAnswer } from '../../trust/hooks/codex-hook-trust-memo' import { readCodexTrustGrantLedgerHome, @@ -47,8 +51,8 @@ function readHooks(): { hooks?: Record } { return JSON.parse(readFileSync(hooksJsonPath(), 'utf-8')) } -function orcaHandler(): { type: string; command: string; timeout: number } { - return { type: 'command', command: getCodexManagedHookInstallMaterial().command, timeout: 10 } +function orcaHandler(): HookCommandConfig { + return buildCodexManagedHook(getCodexManagedHookInstallMaterial().command, 'Stop') } function orcaStopAt(sourcePath: string, groupIndex = 0): CodexTrustEntry { @@ -114,7 +118,8 @@ describe('removeRealHomeCodexHookForOptOut', () => { groupIndex: 0, handlerIndex: 1, command: orcaHandler().command, - timeoutSec: 10 + timeoutSec: 10, + statusMessage: orcaHandler().statusMessage } ] writeFileSync(configTomlPath(), upsertHookTrustEntriesInContent('', entries), 'utf-8') @@ -155,17 +160,6 @@ describe('removeRealHomeCodexHookForOptOut', () => { expect(trust.get(computeTrustKey(afterAt(1)))?.trustedHash).toBe('sha256:user-approved') expect(trust.get(computeTrustKey(afterAt(2)))).toBeUndefined() }) - - it("removes approvals left after the entry is gone, by Codex's hash", async () => { - mkdirSync(join(home, '.codex')) - writeFileSync(hooksJsonPath(), `${JSON.stringify({ hooks: {} }, null, 2)}\n`) - const orcaAt = orcaStopAt(hooksJsonPath()) - upsertHookTrustEntries(configTomlPath(), [{ ...orcaAt, trustedHash: 'sha256:codex-stop' }]) - - expect(await removeRealHomeCodexHookForOptOut([{ stop: 'sha256:codex-stop' }])).toBe('removed') - - expect(readHookTrustEntries(configTomlPath()).has(computeTrustKey(orcaAt))).toBe(false) - }) }) describe('turning hooks off', () => { diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-shared-entry.test.ts b/src/main/codex/hooks/reconciliation/codex-real-home-shared-entry.test.ts deleted file mode 100644 index 59389909731..00000000000 --- a/src/main/codex/hooks/reconciliation/codex-real-home-shared-entry.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs' -import type * as Os from 'node:os' -import { join } from 'node:path' -import { upsertHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' -import { - computeCodexTrustKey as computeTrustKey, - normalizeCodexHookTrustLookupKey as normalizeHookTrustKeyForLookup -} from '../../trust/identity/codex-trust-identity' -import { writeCodexTrustGrantLedgerHome } from '../../trust/grants/codex-trust-grant-ledger' -import { getCodexHookTrustSignature } from '../definitions/codex-hook-identity' -import { setupCodexHookHomes } from '../installation/hook-service-test-harness' -import { _internals as lookupInternals } from '../../trust/hooks/codex-hook-hash-lookup' - -const { getPathMock, homedirMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>(), - homedirMock: vi.fn<() => string>() -})) - -vi.mock('electron', () => ({ app: { getPath: getPathMock } })) -vi.mock('os', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, homedir: homedirMock } -}) - -import '../installation/hook-service' -import { CodexHookService } from '../installation/codex-hook-service-implementation' -import { getCodexManagedHookInstallMaterial } from '../definitions/codex-hook-definition' -import { - _internals as reconcileInternals, - reconcileCodexHooks, - startCodexHooks -} from './codex-hook-reconcile' - -const homes = setupCodexHookHomes(homedirMock, getPathMock) -const USER_HOOK = { type: 'command', command: 'user-stop-hook.sh' } - -function systemCodexHome(): string { - return join(homes.tmpHome, '.codex') -} - -function seedSharedEntry(): void { - const material = getCodexManagedHookInstallMaterial() - const hooksPath = join(systemCodexHome(), 'hooks.json') - mkdirSync(systemCodexHome(), { recursive: true }) - writeFileSync( - hooksPath, - `${JSON.stringify( - { - hooks: { - Stop: [ - { hooks: [USER_HOOK] }, - { hooks: [{ type: 'command', command: material.command, timeout: 10 }] } - ] - } - }, - null, - 2 - )}\n` - ) - const entry: CodexTrustEntry = { - sourcePath: hooksPath, - eventLabel: 'stop', - groupIndex: 1, - handlerIndex: 0, - command: material.command, - timeoutSec: 10, - trustedHash: 'sha256:codex-granted-stop' - } - writeFileSync(join(systemCodexHome(), 'config.toml'), 'model = "user-model"\n') - upsertHookTrustEntries(join(systemCodexHome(), 'config.toml'), [entry]) - writeCodexTrustGrantLedgerHome(systemCodexHome(), { - binary: null, - entries: { - [normalizeHookTrustKeyForLookup(computeTrustKey(entry))]: { - signature: getCodexHookTrustSignature(entry), - trustedHash: 'sha256:codex-granted-stop' - } - } - }) -} - -function snapshotRealCodexHome(): Map { - return new Map( - readdirSync(systemCodexHome()).map((name) => { - const path = join(systemCodexHome(), name) - return [name, { bytes: readFileSync(path, 'utf-8'), mtimeMs: statSync(path).mtimeMs }] - }) - ) -} - -async function reconcileWithHooksOff(): Promise { - reconcileInternals.resetForTesting() - startCodexHooks({ - isEnabled: () => false, - resolveLaunchHome: () => null, - pathReady: Promise.resolve() - }) - await reconcileCodexHooks({ convertOlderForms: true, realHomeLaunch: true }) - // Cancel the startup lookup; this fixture supplies no Codex process. - reconcileInternals.resetForTesting() - lookupInternals.resetForTesting() -} - -describe('the shared real-home Codex entry', () => { - it('survives a pane spawn under a managed account, with no .bak', async () => { - seedSharedEntry() - const before = snapshotRealCodexHome() - const accountHome = join(homes.userDataDir, 'codex-accounts', 'account-1', 'home') - mkdirSync(accountHome, { recursive: true }) - - const status = await new CodexHookService().prepareRuntimeHomeForLaunch( - accountHome, - undefined, - () => true, - false - ) - - expect(status.state).toBe('installed') - expect(snapshotRealCodexHome()).toEqual(before) - }) - - it('survives a reconcile on the real-home lane with hooks off', async () => { - seedSharedEntry() - const before = snapshotRealCodexHome() - - await reconcileWithHooksOff() - - expect(snapshotRealCodexHome()).toEqual(before) - }) - - it("is removed, with Orca's trust, only by the user's explicit opt-out", async () => { - seedSharedEntry() - - await new CodexHookService().remove() - - const hooks = JSON.parse(readFileSync(join(systemCodexHome(), 'hooks.json'), 'utf-8')) - expect(hooks.hooks.Stop).toEqual([{ hooks: [USER_HOOK] }]) - const toml = readFileSync(join(systemCodexHome(), 'config.toml'), 'utf-8') - expect(toml).toContain('model = "user-model"') - expect(toml).not.toContain(':stop:1:0') - }) -}) diff --git a/src/main/codex/structured/background-work/codex-background-task-frames.ts b/src/main/codex/structured/background-work/codex-background-task-frames.ts index 8615697d5a3..da52972ec97 100644 --- a/src/main/codex/structured/background-work/codex-background-task-frames.ts +++ b/src/main/codex/structured/background-work/codex-background-task-frames.ts @@ -1,5 +1,5 @@ import type { NativeChatSubagentState } from '../../../../shared/native-chat/native-chat-types' -import { readCodexSubagentAnnouncements } from './codex-subagent-activity' +import { readCodexSubagentAnnouncements, type CodexChildLaunch } from './codex-subagent-activity' import { codexChildTurnState, type CodexSubagentExecutions } from './codex-subagent-executions' import { readRecord } from '../../app-server/codex-item-field-readers' import '../items/codex-structured-item-translation' @@ -11,6 +11,7 @@ export type CodexAnnouncedChild = { label: string | null /** Set only by spawn announcements, whose reporting thread is the spawner. */ spawnerThreadId: string | undefined + launch?: CodexChildLaunch } export type CodexBackgroundTaskFrame = @@ -78,7 +79,8 @@ export function readCodexBackgroundTaskFrame( agentThreadId: announcement.agentThreadId, label: announcement.label, // Only a spawn names the spawner: other announcements ride whichever agent acted. - spawnerThreadId: announcement.spawned ? event.threadId : undefined + spawnerThreadId: announcement.spawned ? event.threadId : undefined, + launch: announcement.launch }) ) return children.length > 0 ? { kind: 'subagents', children } : null @@ -92,7 +94,7 @@ export function observeCodexExecutionFrame( ): void { if (frame?.kind === 'subagents') { for (const child of frame.children) { - executions.register(child.agentThreadId, child.label, child.spawnerThreadId) + executions.register(child.agentThreadId, child.label, child.spawnerThreadId, child.launch) } } else if (frame?.kind === 'thread-closed') { executions.closeThread(frame.threadId) diff --git a/src/main/codex/structured/background-work/codex-child-work-evidence.ts b/src/main/codex/structured/background-work/codex-child-work-evidence.ts index 4c7bba71fab..91c422715da 100644 --- a/src/main/codex/structured/background-work/codex-child-work-evidence.ts +++ b/src/main/codex/structured/background-work/codex-child-work-evidence.ts @@ -266,6 +266,8 @@ export class CodexChildWorkEvidence { residency: 'background', state: facts.waiting ? 'waiting' : 'working', ...(child.label ? { description: child.label } : {}), + ...(child.model ? { model: child.model } : {}), + ...(child.effort ? { effort: child.effort } : {}), ...(facts.totalTokens !== undefined ? { totalTokens: facts.totalTokens } : {}), ...(lastMessage ? { lastMessage } : {}), ...(spawner && spawner !== this.primaryThreadId ? { ownerId: spawner } : {}), diff --git a/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts b/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts index 24cefaa1870..d54a61cea0d 100644 --- a/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts +++ b/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts @@ -198,6 +198,24 @@ describe('Codex structured child-work producer', () => { ]) }) + it('records the model and reasoning effort Codex resolved for the child', async () => { + const { send, records } = await producer() + send(turn('turn/started', THREAD_ID, 'p1')) + send( + item('item/completed', THREAD_ID, 'p1', { + type: 'subAgentActivity', + id: 'spawn-reviewer', + kind: 'started', + agentThreadId: REVIEWER, + agentPath: '/root/inspect_folder', + model: 'gpt-6.1-sol', + reasoning_effort: 'xhigh' + }) + ) + send(turn('turn/started', REVIEWER, 'r1')) + expect(records()).toEqual([expect.objectContaining({ model: 'gpt-6.1-sol', effort: 'xhigh' })]) + }) + it('ends an approval left unanswered when its turn ends: Codex never ran the command', async () => { const { adapter, codex, send, records, recordedLiveness, display, byDescription } = await producer() diff --git a/src/main/codex/structured/background-work/codex-subagent-activity.ts b/src/main/codex/structured/background-work/codex-subagent-activity.ts index 1098dd83f6a..4c8d3ba6d45 100644 --- a/src/main/codex/structured/background-work/codex-subagent-activity.ts +++ b/src/main/codex/structured/background-work/codex-subagent-activity.ts @@ -17,6 +17,8 @@ export type CodexSubagentActivity = { kind: string agentThreadId: string agentPath: string | null + /** What the child resolved to at creation, reported on `started`. */ + launch: CodexChildLaunch } function nonEmptyString(value: unknown): string | null { @@ -40,10 +42,18 @@ export function readCodexSubagentActivity(item: CodexThreadItem): CodexSubagentA return { kind: nonEmptyString(item.kind) ?? '', agentThreadId, - agentPath: nonEmptyString(item.agentPath) + agentPath: nonEmptyString(item.agentPath), + launch: codexChildLaunch( + nonEmptyString(item.model), + nonEmptyString(item.reasoningEffort) ?? nonEmptyString(item.reasoning_effort) + ) } } +function codexChildLaunch(model: string | null, effort: string | null): CodexChildLaunch { + return { ...(model ? { model } : {}), ...(effort ? { effort } : {}) } +} + const CODEX_ROOT_AGENT_SEGMENT = 'root' /** Normalize root paths like labels; missing paths remain children to avoid losing a real spawn. */ @@ -61,8 +71,12 @@ export type CodexSubagentAnnouncement = { label: string | null /** Only spawn items establish the carrying thread as the parent. */ spawned: boolean + launch?: CodexChildLaunch } +/** What a spawn asked the child to run on. */ +export type CodexChildLaunch = { model?: string; effort?: string } + /** Collab references recover compacted-out spawns; even failed spawns can name a runnable child. */ export function readCodexSubagentAnnouncements( item: CodexThreadItem, @@ -80,7 +94,8 @@ function readAnnouncements(item: CodexThreadItem): CodexSubagentAnnouncement[] { { agentThreadId: activity.agentThreadId, label: codexSubagentLabel(activity), - spawned: activity.kind === 'started' + spawned: activity.kind === 'started', + launch: activity.launch } ] } @@ -91,7 +106,8 @@ function readAnnouncements(item: CodexThreadItem): CodexSubagentAnnouncement[] { const spawned = call.tool === 'spawnAgent' // Follow-up prompts are messages, not the child's task label. const label = spawned ? codexCollabHelperLabel(call.prompt) : null - return call.helperThreadIds.map((agentThreadId) => ({ agentThreadId, label, spawned })) + const launch = spawned ? codexChildLaunch(call.model, call.reasoningEffort) : undefined + return call.helperThreadIds.map((agentThreadId) => ({ agentThreadId, label, spawned, launch })) } export type CodexThreadTokenTotal = { threadId: string; totalTokens: number } diff --git a/src/main/codex/structured/background-work/codex-subagent-executions.ts b/src/main/codex/structured/background-work/codex-subagent-executions.ts index ceb01772b8c..1a8983e112c 100644 --- a/src/main/codex/structured/background-work/codex-subagent-executions.ts +++ b/src/main/codex/structured/background-work/codex-subagent-executions.ts @@ -1,4 +1,5 @@ import type { NativeChatSubagentState } from '../../../../shared/native-chat/native-chat-types' +import type { CodexChildLaunch } from './codex-subagent-activity' import { MAX_SUBAGENT_FIELD_CHARS, canReplaceSubagentState @@ -20,6 +21,8 @@ export type CodexExecutionChild = { label: string | null /** Spawn announcements arrive on the parent's thread. */ spawnerThreadId: string | null + model: string | null + effort: string | null execution: CodexChildExecution | null turnOrdinals: Map turnCount: number @@ -37,12 +40,15 @@ export class CodexSubagentExecutions { register( agentThreadId: string, label: string | null, - spawnerThreadId?: string + spawnerThreadId?: string, + launch?: CodexChildLaunch ): CodexExecutionChild { const child = this.child(agentThreadId) - const previousLabel = child.label + const previous = [child.label, child.model, child.effort] // Keep the original spawner across duplicate announcement frames. child.spawnerThreadId ??= spawnerThreadId ?? null + child.model ??= launch?.model ?? null + child.effort ??= launch?.effort ?? null child.registered = true // Retain one overflow unit so the journal can append its per-row truncation marker. child.label ??= @@ -51,7 +57,9 @@ export class CodexSubagentExecutions { .replace(/\s+/g, ' ') .slice(0, MAX_SUBAGENT_FIELD_CHARS + 1) || null this.updateWorking(child) - if (previousLabel !== child.label) { + if ( + [child.label, child.model, child.effort].some((value, index) => value !== previous[index]) + ) { this.changed.add(agentThreadId) } return child @@ -210,6 +218,8 @@ export class CodexSubagentExecutions { observationOrder: this.children.size, registered: false, label: null, + model: null, + effort: null, spawnerThreadId: null, execution: null, turnOrdinals: new Map(), diff --git a/src/main/codex/structured/catalog/codex-at-rest-skills-probe.test.ts b/src/main/codex/structured/catalog/codex-at-rest-skills-probe.test.ts deleted file mode 100644 index 190d35548a0..00000000000 --- a/src/main/codex/structured/catalog/codex-at-rest-skills-probe.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type * as Files from 'node:fs/promises' -import { scanClaudeCommandFolders } from '../../../claude/claude-command-folder-scan' -import type * as Catalog from '../../../native-chat/agent-session-wire/options/at-rest-command-catalog' -import { afterEach, expect, it, vi } from 'vitest' - -const folders = vi.hoisted(() => ({ open: vi.fn(), read: vi.fn() })) -vi.mock('node:fs/promises', async (original) => ({ - ...(await original()), - opendir: folders.open, - readFile: folders.read, - stat: vi.fn(async () => ({ isDirectory: () => true })) -})) -afterEach(() => vi.useRealTimers()) - -const visits = vi.hoisted(() => vi.fn((current: boolean) => current)) -vi.mock( - '../../../native-chat/agent-session-wire/options/at-rest-command-catalog', - async (original) => { - const actual = await original() - return { - ...actual, - AtRestCommandCatalog: vi.fn(function (source: Catalog.AtRestCommandSource) { - return new actual.AtRestCommandCatalog({ - ...source, - scan: (record, cwd, current, ...rest) => - source.scan(record, cwd, () => visits(current()), ...rest) - }) - }) - } - } -) - -it('closes a directory opened after cancellation before any read or recursion', async () => { - const opened = Promise.withResolvers() - const next = vi.fn(() => new Promise>(() => {})) - const close = vi.fn(async () => undefined) - folders.open.mockReturnValueOnce(opened.promise) - const stop = new AbortController() - const reading = scanClaudeCommandFolders(['/commands'], stop.signal) - const rejected = expect(reading).rejects.toThrow('cancelled') - stop.abort(new Error('cancelled')) - opened.resolve({ close, [Symbol.asyncIterator]: () => ({ next }) }) - await rejected - expect(close).toHaveBeenCalledExactlyOnceWith() - expect(next).not.toHaveBeenCalled() - expect(folders.open).toHaveBeenCalledExactlyOnceWith('/commands') - expect(folders.read).not.toHaveBeenCalled() -}) diff --git a/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts b/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts index cee82300f28..2d8b3f72445 100644 --- a/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts +++ b/src/main/codex/structured/catalog/codex-at-rest-skills-probe.ts @@ -9,7 +9,7 @@ import { codexStructuredLaunchArgs } from '../launch/codex-structured-launch-arg import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, NATIVE_CHAT_SCRATCH_DIR_ENV -} from '../../../native-chat/native-chat-visuals-delivery' +} from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { AtRestCommandCatalog, type AtRestCommandScan diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts index 94c26ee190c..2bc912e2a13 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts @@ -1,7 +1,7 @@ import { assertStructuredAgentResolutionCurrent, type StructuredAgentResolutionOperation -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { codexStructuredLaunchArgs } from '../launch/codex-structured-launch-args' import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import { diff --git a/src/main/codex/structured/catalog/codex-structured-model-catalog.ts b/src/main/codex/structured/catalog/codex-structured-model-catalog.ts index b15e3e58291..55f15f01174 100644 --- a/src/main/codex/structured/catalog/codex-structured-model-catalog.ts +++ b/src/main/codex/structured/catalog/codex-structured-model-catalog.ts @@ -8,7 +8,7 @@ import type { CodexAppServerConnection } from '../../app-server/codex-app-server import { assertStructuredAgentResolutionCurrent, type StructuredAgentResolutionOperation -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { structuredAgentSessionOptionModels } from '../../../native-chat/agent-session-wire/options/structured-agent-session-option-models' import { CODEX_DEFAULT_SERVICE_TIER, diff --git a/src/main/codex/structured/items/codex-collab-agent-tool-call.ts b/src/main/codex/structured/items/codex-collab-agent-tool-call.ts index cf20a540329..77606f2ddd9 100644 --- a/src/main/codex/structured/items/codex-collab-agent-tool-call.ts +++ b/src/main/codex/structured/items/codex-collab-agent-tool-call.ts @@ -20,6 +20,9 @@ export type CodexCollabAgentToolCall = { /** The receivers that are helpers: every one but those the call reports `notFound`. */ helperThreadIds: string[] prompt: string | null + /** What a spawn asked the child to run on. */ + model: string | null + reasoningEffort: string | null /** Caller snapshots in receiverThreadIds order, excluding receivers with no snapshot. */ states: { threadId: string; status: string | null; message: string | null }[] } @@ -53,6 +56,8 @@ export function readCodexCollabAgentToolCall( (threadId) => readString(readRecord(snapshots[threadId]), 'status') !== 'notFound' ), prompt: readString(item, 'prompt'), + model: readString(item, 'model'), + reasoningEffort: readString(item, 'reasoningEffort'), states } } diff --git a/src/main/codex/structured/launch/codex-cli-installation-error.ts b/src/main/codex/structured/launch/codex-cli-installation-error.ts index f462c1454cd..273e54fdbdf 100644 --- a/src/main/codex/structured/launch/codex-cli-installation-error.ts +++ b/src/main/codex/structured/launch/codex-cli-installation-error.ts @@ -7,7 +7,7 @@ import { readAgentCliVersion, type AgentCliVersionReader } from '../../../agent-launch/preflight/agent-cli-version-probe' -import { AgentCliInstallationError } from '../../../native-chat/agent-cli-installation-error' +import { AgentCliInstallationError } from '../../../native-chat/agent-launch/agent-cli-installation-error' import type { StructuredAgentLaunchResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition' import { resolveProviderChildEnv, diff --git a/src/main/codex/structured/launch/codex-structured-child-environment.test.ts b/src/main/codex/structured/launch/codex-structured-child-environment.test.ts index dd75c5b7e2c..160895eae9e 100644 --- a/src/main/codex/structured/launch/codex-structured-child-environment.test.ts +++ b/src/main/codex/structured/launch/codex-structured-child-environment.test.ts @@ -5,7 +5,7 @@ import { delimiter, join } from 'node:path' import { openCodexAppServerConnection } from '../../app-server/codex-app-server-connection' import { sealStructuredSessionChild } from '../../../runtime/agent-session/environment/structured-session-child-env' import { createCodexStructuredLaunchResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' const DEV_CLI_BIN_FIRST = /^[^:;]*[\\/]cli[\\/]bin[:;]/ diff --git a/src/main/codex/structured/launch/codex-structured-launch-args.test.ts b/src/main/codex/structured/launch/codex-structured-launch-args.test.ts index bb33770e903..8dd64f65c43 100644 --- a/src/main/codex/structured/launch/codex-structured-launch-args.test.ts +++ b/src/main/codex/structured/launch/codex-structured-launch-args.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { codexStructuredLaunchArgs } from './codex-structured-launch-args' -import { StructuredAgentArgumentsError } from '../../../native-chat/structured-agent-arguments-error' +import { StructuredAgentArgumentsError } from '../../../native-chat/agent-launch/structured-agent-arguments-error' describe('codexStructuredLaunchArgs', () => { it('drops permission options and config overrides owned by Orca', () => { diff --git a/src/main/codex/structured/launch/codex-structured-launch-args.ts b/src/main/codex/structured/launch/codex-structured-launch-args.ts index 16a48d53662..17cfc15b19f 100644 --- a/src/main/codex/structured/launch/codex-structured-launch-args.ts +++ b/src/main/codex/structured/launch/codex-structured-launch-args.ts @@ -1,6 +1,6 @@ import { CODEX_PERMISSION_CONFIG_ROOTS } from '../../../../shared/agent-launch/permissions/agent-permission-args' import { parseTomlKeyPath } from '../../configuration/toml/config-toml-key-path' -import { StructuredAgentArgumentsError } from '../../../native-chat/structured-agent-arguments-error' +import { StructuredAgentArgumentsError } from '../../../native-chat/agent-launch/structured-agent-arguments-error' const VALUE_OPTIONS = new Set([ '-c', diff --git a/src/main/codex/structured/launch/codex-structured-launch-resolution.test.ts b/src/main/codex/structured/launch/codex-structured-launch-resolution.test.ts index e512dab1eba..a5bbb6d9c74 100644 --- a/src/main/codex/structured/launch/codex-structured-launch-resolution.test.ts +++ b/src/main/codex/structured/launch/codex-structured-launch-resolution.test.ts @@ -1,7 +1,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import { createCodexStructuredLaunchResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' import { describe, expect, it, vi } from 'vitest' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' diff --git a/src/main/codex/structured/launch/codex-structured-launch-resolution.ts b/src/main/codex/structured/launch/codex-structured-launch-resolution.ts index 3e6cc7fc1e4..b560bb8bc8f 100644 --- a/src/main/codex/structured/launch/codex-structured-launch-resolution.ts +++ b/src/main/codex/structured/launch/codex-structured-launch-resolution.ts @@ -5,7 +5,7 @@ import { resolveAgainAfterRefreshOnMissingProgram, type StructuredAgentCommand, type StructuredAgentResolutionOperation -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' // How a durable session record becomes a Codex process launch. // // Every input except the account is read back from the record the store already made durable, @@ -35,7 +35,7 @@ import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, NATIVE_CHAT_SCRATCH_DIR_ENV, withNativeChatVisualsEnv -} from '../../../native-chat/native-chat-visuals-delivery' +} from '../../../native-chat/conversation-files/native-chat-visuals-delivery' export type CodexStructuredLaunchPartDeps = { resolveLaunchArgs: () => Promise | string[] diff --git a/src/main/codex/structured/launch/codex-structured-real-cli-visuals.test.ts b/src/main/codex/structured/launch/codex-structured-real-cli-visuals.test.ts index 2c6f0c48070..861d30181df 100644 --- a/src/main/codex/structured/launch/codex-structured-real-cli-visuals.test.ts +++ b/src/main/codex/structured/launch/codex-structured-real-cli-visuals.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { resolveCodexCommand } from '../../../codex-cli/command' -import { NATIVE_CHAT_VISUALS_SKILL_NAME } from '../../../native-chat/native-chat-visuals-skill-location' +import { NATIVE_CHAT_VISUALS_SKILL_NAME } from '../../../native-chat/conversation-files/native-chat-visuals-skill-location' import { openCodexAppServerConnection } from '../../app-server/codex-app-server-connection' import { withCodexVisualsThreadConfig } from './codex-structured-visuals' import { codexStructuredPermissionPolicy } from '../../../../shared/codex-permission-policy' diff --git a/src/main/codex/structured/launch/codex-structured-visuals.test.ts b/src/main/codex/structured/launch/codex-structured-visuals.test.ts index d368ef26092..8f722c12e55 100644 --- a/src/main/codex/structured/launch/codex-structured-visuals.test.ts +++ b/src/main/codex/structured/launch/codex-structured-visuals.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { NativeChatVisualsLaunch } from '../../../native-chat/native-chat-visuals-delivery' +import type { NativeChatVisualsLaunch } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { CodexAppServerTimeoutError } from '../../app-server/codex-app-server-session' import { prepareCodexThreadForVisuals } from './codex-structured-visuals' diff --git a/src/main/codex/structured/launch/codex-structured-visuals.ts b/src/main/codex/structured/launch/codex-structured-visuals.ts index e98a2dad7f8..0595e96e70e 100644 --- a/src/main/codex/structured/launch/codex-structured-visuals.ts +++ b/src/main/codex/structured/launch/codex-structured-visuals.ts @@ -1,4 +1,4 @@ -import type { NativeChatVisualsLaunch } from '../../../native-chat/native-chat-visuals-delivery' +import type { NativeChatVisualsLaunch } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import type { CodexAppServerConnection } from '../../app-server/codex-app-server-connection-types' import { isCodexAppServerRequestError } from '../../app-server/codex-app-server-request-error' diff --git a/src/main/codex/structured/session-lifecycle/codex-provider-session-rename.ts b/src/main/codex/structured/session-lifecycle/codex-provider-session-rename.ts index db55f095538..5a039df6e15 100644 --- a/src/main/codex/structured/session-lifecycle/codex-provider-session-rename.ts +++ b/src/main/codex/structured/session-lifecycle/codex-provider-session-rename.ts @@ -20,7 +20,7 @@ import { import { NATIVE_CHAT_SCRATCH_DIR_ENV, LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV -} from '../../../native-chat/native-chat-visuals-delivery' +} from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../../../codex-cli/codex-read-only-app-server-args' import type { CodexSession } from './codex-structured-session-state' diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts index 54f6f9c7e86..42ca17db6ad 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts @@ -161,6 +161,7 @@ export class CodexStructuredSessionAdapter implements SessionAdapter { return admission } if (event.type === 'notification') { + turnEnd.publishCodexTurnOpened(session, event, this.sessions) // Only an admitted turn end settles; a refused one settles on the retry that lands. turnEnd.settleCodexSendsInEndedTurn(session, event) // Child records observe refused frames only after a retry reaches the journal. @@ -340,7 +341,6 @@ export class CodexStructuredSessionAdapter implements SessionAdapter { hasOwnedAcquisition = (sessionId: string): boolean => this.acquisitions.get(sessionId) !== undefined || this.sessions.has(sessionId) - private session(sessionId: string): CodexSession { - return requireLiveCodexSession(this.sessions, sessionId) - } + private session = (sessionId: string): CodexSession => + requireLiveCodexSession(this.sessions, sessionId) } diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-cancel.test.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-cancel.test.ts deleted file mode 100644 index 9fc92dcad26..00000000000 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-cancel.test.ts +++ /dev/null @@ -1,285 +0,0 @@ -import { acquireReadyCodexForTest } from './codex-structured-session-adapter-fixture' -import { describe, expect, it, vi } from 'vitest' - -// Termination probes never settle, exposing any unexpected process cleanup during Stop. -const processWork = vi.hoisted(() => { - const never = (): Promise => new Promise(() => {}) - return { - captureDescendantSnapshot: vi.fn(async () => ({ - rootPgid: null, - descendants: [], - capturedAtMs: 0 - })), - terminateDescendantSnapshotAndWait: vi.fn(never), - terminateDescendantSnapshotWithVerdict: vi.fn(never), - queryWindowsProcessDescendants: vi.fn(never), - terminateWindowsProcessTree: vi.fn(never) - } -}) -vi.mock('../../../pty/process-retirement/pty-descendant-termination', async (importOriginal) => ({ - ...(await importOriginal>()), - captureDescendantSnapshot: processWork.captureDescendantSnapshot -})) -vi.mock( - '../../../pty/process-retirement/pty-descendant-exit-verification', - async (importOriginal) => ({ - ...(await importOriginal>()), - terminateDescendantSnapshotAndWait: processWork.terminateDescendantSnapshotAndWait, - terminateDescendantSnapshotWithVerdict: processWork.terminateDescendantSnapshotWithVerdict - }) -) -vi.mock('../../../providers/windows-foreground-process-rows', async (importOriginal) => ({ - ...(await importOriginal>()), - queryWindowsProcessDescendants: processWork.queryWindowsProcessDescendants -})) -vi.mock('../../../pty/process-retirement/windows-process-tree-kill', async (importOriginal) => ({ - ...(await importOriginal>()), - terminateWindowsProcessTree: processWork.terminateWindowsProcessTree -})) -import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import { CodexAppServerRequestError } from '../../app-server/codex-app-server-request-error' -import type { - CodexAppServerConnection, - CodexAppServerConnectionHandlers -} from '../../app-server/codex-app-server-connection-types' -import type { - CodexAppServerLaunch, - openCodexAppServerConnection -} from '../../app-server/codex-app-server-connection' -import { CodexAppServerUnsupportedError } from '../../app-server/codex-app-server-session' -import { CodexStructuredSessionAdapter } from './codex-structured-session-adapter' -import type { - CodexStructuredSessionAdapterDeps, - CodexStructuredSessionEvent -} from './codex-structured-session-state' -import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const THREAD_ID = 'thread-abc' -const USER_MESSAGE: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'ship it' }] -} - -type Route = (params: Record | undefined) => unknown -type FakeConnection = Omit & { - closed: boolean - launch: CodexAppServerLaunch - handlers: CodexAppServerConnectionHandlers - calls: { method: string; params?: Record }[] -} - -function identity(): AgentSessionJournalIdentity { - return { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD_ID) - } -} - -function fakeCodex(): { - connections: FakeConnection[] - openConnection: typeof openCodexAppServerConnection - routes: Record -} { - const connections: FakeConnection[] = [] - const routes: Record = { - 'thread/resume': () => ({ thread: { id: THREAD_ID } }) - } - const openConnection = (async (launch, handlers = {}) => { - const connection: FakeConnection = { - launch, - handlers, - calls: [], - pid: 4321, - closed: false, - request: async (method, params) => { - connection.calls.push({ method, params }) - return routes[method]?.(params) ?? {} - }, - notify: () => {}, - respond: () => {}, - respondWithError: () => {}, - close: async () => { - connection.closed = true - return true - } - } - connections.push(connection) - return connection - }) as typeof openCodexAppServerConnection - return { connections, openConnection, routes } -} - -async function acquired( - codex: ReturnType, - events: CodexStructuredSessionEvent[] = [], - overrides: Partial> = {} -): Promise { - const adapter = new CodexStructuredSessionAdapter({ - resolveLaunch: async () => ({ - command: 'codex', - args: ['app-server'], - cwd: '/work/repo', - codexHome: null, - resumeThreadId: THREAD_ID - }), - onEvent: (event) => events.push(event), - openConnection: codex.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - ...overrides - }) - await acquireReadyCodexForTest(adapter, { identity: identity(), fence: 7, spawnToken: 'spawn-9' }) - return adapter -} - -function completeTurn(codex: ReturnType, turnId = 'turn-1'): void { - codex.connections[0].handlers.onNotification?.('turn/completed', { - threadId: THREAD_ID, - turn: { id: turnId, status: 'interrupted' } - }) -} - -describe('CodexStructuredSessionAdapter.cancelTurn', () => { - it('reports not-cancelled when Codex declines or lacks the method', async () => { - const declined = fakeCodex() - declined.routes['turn/interrupt'] = () => { - throw new CodexAppServerRequestError('turn/interrupt', -32602, 'no such turn') - } - const absent = fakeCodex() - absent.routes['turn/interrupt'] = () => { - throw new CodexAppServerUnsupportedError('no turn/interrupt') - } - - await expect( - (await acquired(declined)).cancelTurn({ - sessionId: 'session-1', - turnId: 'turn-1', - fence: 7 - }) - ).resolves.toEqual({ cancelled: false, refusal: {} }) - await expect( - (await acquired(absent)).cancelTurn({ - sessionId: 'session-1', - turnId: 'turn-1', - fence: 7 - }) - ).resolves.toEqual({ cancelled: false, refusal: {} }) - }) - - it('rethrows an unsettled interrupt so the turn is not shown as cancelled', async () => { - const codex = fakeCodex() - codex.routes['turn/interrupt'] = () => { - throw new Error('codex app-server turn/interrupt exceeded 30000ms') - } - - await expect( - (await acquired(codex)).cancelTurn({ - sessionId: 'session-1', - turnId: 'turn-1', - fence: 7 - }) - ).rejects.toThrow('exceeded 30000ms') - }) - - it('accepts an immediate resend after verified interruption', async () => { - let nextTurn = 0 - const codex = fakeCodex() - codex.routes['turn/start'] = () => { - const turnId = `turn-${++nextTurn}` - codex.connections[0].handlers.onNotification?.('turn/started', { - threadId: THREAD_ID, - turn: { id: turnId } - }) - return { turn: { id: turnId } } - } - codex.routes['turn/interrupt'] = () => { - completeTurn(codex) - return {} - } - const adapter = await acquired(codex) - - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) - await adapter.cancelTurn({ sessionId: 'session-1', turnId: 'turn-1', fence: 7 }) - - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-2', - body: USER_MESSAGE, - fence: 7 - }) - ).resolves.toMatchObject({ - state: 'admitted' - }) - }) - - it("publishes the turn's end when the interrupt receipt fails", async () => { - const events: CodexStructuredSessionEvent[] = [] - const codex = fakeCodex() - codex.routes['turn/interrupt'] = () => { - completeTurn(codex) - throw new Error('interrupt receipt lost') - } - const adapter = await acquired(codex, events) - - await expect( - adapter.cancelTurn({ sessionId: 'session-1', turnId: 'turn-1', fence: 7 }) - ).rejects.toThrow('interrupt receipt lost') - expect(events).toContainEqual(expect.objectContaining({ method: 'turn/completed' })) - }) -}) - -// Codex interrupts one-shot commands but retains background terminals. -describe('a Codex Stop is the interrupt alone', () => { - async function stopAfterASend() { - const events: CodexStructuredSessionEvent[] = [] - const answer = Promise.withResolvers() - const codex = fakeCodex() - codex.routes['turn/start'] = () => { - codex.connections[0].handlers.onNotification?.('turn/started', { - threadId: THREAD_ID, - turn: { id: 'turn-1' } - }) - return { turn: { id: 'turn-1' } } - } - codex.routes['turn/interrupt'] = () => answer.promise - const adapter = await acquired(codex, events) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) - const stopped = adapter.cancelTurn({ sessionId: 'session-1', turnId: 'turn-1', fence: 7 }) - await vi.waitFor(() => expect(codex.connections[0].calls.at(-1)?.method).toBe('turn/interrupt')) - // One read can carry both the interrupt reply and turn completion. - const answerThenEnd = (): void => { - answer.resolve({}) - completeTurn(codex) - } - return { events, stopped, answerThenEnd } - } - - it('reads and kills no processes, from the send through the Stop', async () => { - const { stopped, answerThenEnd } = await stopAfterASend() - - answerThenEnd() - - for (const work of Object.values(processWork)) { - expect(work).not.toHaveBeenCalled() - } - await expect(stopped).resolves.toEqual({ cancelled: true, turnId: 'turn-1' }) - for (const work of Object.values(processWork)) { - expect(work).not.toHaveBeenCalled() - } - }) -}) diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts index c52d281af5c..1b65ead9f71 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts @@ -21,12 +21,13 @@ import { codexProviderHandleLink } from '../acquisition/codex-structured-owner-i import { openCodexThread } from '../threads/codex-structured-thread-open' import { catchUpCodexThread } from '../threads/codex-structured-thread-catch-up' import { withCodexVisualsThreadConfig } from '../launch/codex-structured-visuals' -import { NATIVE_CHAT_SCRATCH_DIR_ENV } from '../../../native-chat/native-chat-visuals-delivery' +import { NATIVE_CHAT_SCRATCH_DIR_ENV } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { restoredCodexSessionOptions, reportedCodexSessionOptions } from '../catalog/codex-structured-session-options' import { CodexSkillReport } from '../catalog/codex-structured-skill-report' +import { codexMessageInputOptions } from '../turns/codex-structured-message-options' import { codexAcquireCatalogAccess } from '../catalog/codex-structured-acquire-catalog' import { CODEX_DEFAULT_SERVICE_TIER, @@ -183,6 +184,10 @@ export async function openCodexStructuredSession( ...(opened.effort ? { effort: opened.effort } : {}), ...(serviceTier ? { serviceTier } : {}) }, + appliedTurnInputOptions: codexMessageInputOptions(input.options ?? {}, { + serviceTier: CODEX_DEFAULT_SERVICE_TIER, + interactionMode: 'default' + }), appliedSettings: attempt.window.appliedSettings, ...(catalogAccess ? { catalogAccess } : {}), dispatchEchoes: start.dispatchEchoes, diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts index 6c7f91f90e3..24fb8378af3 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts @@ -28,7 +28,7 @@ import type { StructuredLaunchRequest } from '../../../runtime/agent-session/lau import type { AgentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' import type { AgentModelCatalogSessionAccess } from '../../../native-chat/agent-model-catalog/agent-model-catalog-lister' import type { StructuredAgentSessionProviderOpen } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' -import type { NativeChatVisualsLaunch } from '../../../native-chat/native-chat-visuals-delivery' +import type { NativeChatVisualsLaunch } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import type { AgentChatPermissionChoice } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' import type { CodexSandboxPolicy } from '../launch/codex-structured-sandbox-policy' import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' @@ -179,6 +179,8 @@ export type CodexSession = { nativeDefaults?: { personality?: string; serviceTier?: string } /** Acquisition facts overlaid by controls actually sent, independently of reports or saved picks. */ appliedTurnOptions?: Readonly> + /** Saved/start input choices before protocol shaping; later catalogs cannot change eligibility. */ + appliedTurnInputOptions?: Readonly> appliedSettings?: CodexAppliedSettings /** Optional for adapters without a host catalog store. */ catalogAccess?: CodexSessionCatalogAccess diff --git a/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts b/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts index 8881f19b90b..895a8ac0b96 100644 --- a/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts +++ b/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts @@ -4,7 +4,10 @@ import { CodexAppliedSettings } from '../catalog/codex-structured-applied-settin import { CodexAppServerRequestError } from '../../app-server/codex-app-server-request-error' import { changeCodexThreadGoal } from './codex-structured-thread-goal' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' -import { waitsForCodexTurnOptions } from '../../../native-chat/agent-session-wire/options/structured-agent-session-message-options' +import { + codexTurnOptionsDiffer, + waitsForCodexTurnOptions +} from '../../../native-chat/agent-session-wire/options/structured-agent-session-message-options' const THREAD = 'thread-1' @@ -89,31 +92,16 @@ describe('direct goal settings application', () => { threadId: 'thread-abc', threadSettings: { model, effort } }) - const goal = (model = 'gpt-live', effort?: string) => + const goal = (model = 'gpt-live', effort?: string, signal?: AbortSignal) => adapter.changeThreadGoal({ sessionId: 'session-1', fence: 7, change: { kind: 'status', status: 'active' }, replacesGoal: false, - executionOptions: { model, ...(effort ? { effort } : {}) } + executionOptions: { model, ...(effort ? { effort } : {}) }, + signal }) - const state = acquiredSettingsTestSeam(adapter) - return { codex, adapter, apply, goal, settings: state.settings, state, acquisition } - } - - it('keeps literal goal settings separate from exact applied turn proof and recovers on a successful turn', async () => { - const { codex, adapter, apply, goal, acquisition } = await fixture() - const choices = { model: 'unlisted-model-a', effort: 'high' } - const turnProof = { model: 'unlisted-model-a', effort: 'high', interactionMode: 'default' } - const dispatch = () => - adapter.dispatch({ - sessionId: 'session-1', - fence: 7, - clientMessageId: `message-${codex.connections[0].calls.length}`, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, - executionOptions: choices - }) - const held = (options = choices) => + const held = (options: Record) => waitsForCodexTurnOptions( { provider: 'codex', sessionId: 'session-1' }, { @@ -138,16 +126,37 @@ describe('direct goal settings application', () => { { fence: 7, generation: acquisition.acquisitionGeneration, phase: 'ready' }, adapter ) - const proof = () => - adapter.readAppliedInputOptions({ + return { + codex, + adapter, + apply, + goal, + held, + get settings() { + return acquiredSettingsTestSeam(adapter).settings + }, + get state() { + return acquiredSettingsTestSeam(adapter) + }, + acquisition + } + } + + it('preserves goal choice eligibility through readback, refusal and successful-turn recovery', async () => { + const { codex, adapter, apply, goal, held: heldOptions } = await fixture() + const choices = { model: 'unlisted-model-a', effort: 'high' } + const dispatch = () => + adapter.dispatch({ sessionId: 'session-1', fence: 7, - acquisitionGeneration: acquisition.acquisitionGeneration, - next: choices + clientMessageId: `message-${codex.connections[0].calls.length}`, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, + executionOptions: choices }) + const held = (options = choices) => heldOptions(options) try { expect(await dispatch()).toMatchObject({ state: 'admitted' }) - expect(proof()?.active).toEqual(turnProof) + expect(held()).toBe(false) codex.routes['thread/settings/update'] = (params) => { apply(String(params?.model), String(params?.effort)) return {} @@ -161,15 +170,18 @@ describe('direct goal settings application', () => { params: { threadId: 'thread-abc', model: 'unlisted-model-b', effort: 'low' } } ]) - const appliedGoal = { model: 'unlisted-model-b', effort: 'low', interactionMode: 'default' } - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) + const goalChoices = { model: 'unlisted-model-b', effort: 'low' } + expect(held(goalChoices)).toBe(false) + expect(held()).toBe(true) apply('observation-only', 'medium') - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) + expect(held(goalChoices)).toBe(false) + expect(held()).toBe(true) codex.routes['thread/settings/update'] = () => { throw new CodexAppServerRequestError('thread/settings/update', -32602, 'invalid model') } expect(await goal('refused-model', 'high')).toMatchObject({ ok: false }) - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) + expect(held(goalChoices)).toBe(false) + expect(held()).toBe(true) expect( codex.connections[0].calls.filter((call) => call.method === 'thread/goal/set') ).toHaveLength(1) @@ -178,8 +190,8 @@ describe('direct goal settings application', () => { (call) => call.method === 'thread/settings/update' ).length expect(await goal('observation-only-c', 'medium')).toEqual({ ok: true }) - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) - expect(held(appliedGoal)).toBe(false) + expect(held()).toBe(true) + expect(held(goalChoices)).toBe(false) expect(held({ model: 'observation-only-c', effort: 'medium' })).toBe(true) expect( codex.connections[0].calls.filter((call) => call.method === 'thread/settings/update') @@ -188,35 +200,150 @@ describe('direct goal settings application', () => { throw new Error('reply lost after settings enqueue') } expect(await goal('uncertain-model', 'low')).toMatchObject({ ok: false }) - expect(proof()).toEqual({ - active: { effort: 'low', interactionMode: 'default' }, - next: turnProof - }) expect(held()).toBe(true) expect(await dispatch()).toMatchObject({ state: 'admitted' }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) + expect(held()).toBe(false) codex.routes['thread/settings/update'] = () => { throw new CodexAppServerRequestError('thread/settings/update', -32601, 'method not found') } expect(await goal('unlisted-model-b', 'low')).toEqual({ ok: true }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) + expect(held()).toBe(false) const callsBeforeCached = codex.connections[0].calls.filter( (call) => call.method === 'thread/settings/update' ).length expect(await goal('unlisted-model-b', 'low')).toEqual({ ok: true }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) expect(held()).toBe(false) - expect(held(appliedGoal)).toBe(true) + expect(held(goalChoices)).toBe(true) expect( codex.connections[0].calls.filter((call) => call.method === 'thread/settings/update') ).toHaveLength(callsBeforeCached) expect(await dispatch()).toMatchObject({ state: 'admitted' }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) + expect(held()).toBe(false) } finally { await adapter.closeAll() } }) + it.each([ + ['success', false], + ['refusal', false], + ['success', true], + ['refusal', true] + ] as const)( + 'preserves a newer start after late goal %s (replaced acquisition: %s)', + async (outcome, replaceAcquisition) => { + const { codex, adapter, goal, acquisition } = await fixture() + let generation = acquisition.acquisitionGeneration + const dispatch = (model: string) => + adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: model, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, + executionOptions: { model, effort: 'high' } + }) + const answer = Promise.withResolvers() + const authority = new AbortController() + try { + expect(await dispatch('model-a')).toMatchObject({ state: 'admitted' }) + const request = vi.spyOn(codex.connections[0], 'request') + codex.routes['thread/settings/update'] = () => answer.promise + const pending = goal('model-b', 'high', authority.signal) + const rpc = request.mock.results.at(-1)?.value + expect(rpc).toBeInstanceOf(Promise) + authority.abort(new Error('stopped')) + expect(await pending).toMatchObject({ ok: false }) + if (replaceAcquisition) { + await adapter.closeSession('session-1') + const { acquireReadyCodexForTest, identityFor } = + await import('../session-lifecycle/codex-structured-session-adapter-fixture') + const replacement = await acquireReadyCodexForTest(adapter, { + identity: identityFor('session-1'), + fence: 7, + spawnToken: 'replacement' + }) + generation = replacement.acquisitionGeneration + expect( + adapter.readAppliedInputOptions({ + sessionId: 'session-1', + fence: 7, + acquisitionGeneration: acquisition.acquisitionGeneration, + next: {} + }) + ).toBeNull() + } + expect(await dispatch('model-c')).toMatchObject({ state: 'admitted' }) + if (outcome === 'success') { + answer.resolve({}) + } else { + answer.reject( + new CodexAppServerRequestError('thread/settings/update', -32602, 'invalid model') + ) + } + await Promise.allSettled([rpc]) + const differs = (model: string) => + codexTurnOptionsDiffer( + { provider: 'codex', sessionId: 'session-1' }, + { model, effort: 'high' }, + { fence: 7, generation, phase: 'ready' }, + adapter + ) + expect(differs('model-c')).toBe(false) + expect(differs('model-a')).toBe(true) + expect(differs('model-b')).toBe(true) + expect( + codex.connections + .flatMap((connection) => connection.calls) + .some((call) => call.method.startsWith('thread/goal/')) + ).toBe(false) + } finally { + await adapter.closeAll() + } + } + ) + + it.each(['success', 'refusal'] as const)( + 'settles an owned late %s after abort without resuming the goal', + async (outcome) => { + const { codex, adapter, goal, held } = await fixture() + const answer = Promise.withResolvers() + const authority = new AbortController() + try { + await adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: 'prior', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, + executionOptions: { model: 'model-a', effort: 'high' } + }) + const request = vi.spyOn(codex.connections[0], 'request') + codex.routes['thread/settings/update'] = () => answer.promise + const pending = goal('model-b', 'high', authority.signal) + const rpc = request.mock.results.at(-1)?.value + expect(rpc).toBeInstanceOf(Promise) + authority.abort(new Error('stopped')) + expect(await pending).toMatchObject({ ok: false }) + if (outcome === 'success') { + answer.resolve({}) + } else { + answer.reject( + new CodexAppServerRequestError('thread/settings/update', -32602, 'invalid model') + ) + } + await Promise.allSettled([rpc]) + expect(held({ model: 'model-b', effort: 'high' })).toBe(outcome !== 'success') + expect(held({ model: 'model-a', effort: 'high' })).toBe(outcome === 'success') + expect( + codex.connections + .flatMap((connection) => connection.calls) + .some((call) => call.method.startsWith('thread/goal/')) + ).toBe(false) + } finally { + await adapter.closeAll() + } + } + ) + it.each(['success', 'rejection', 'stale'] as const)( 'rechecks current application after its RPC reply, preserving pre-reply evidence (%s)', async (mode) => { diff --git a/src/main/codex/structured/threads/codex-structured-thread-goal.ts b/src/main/codex/structured/threads/codex-structured-thread-goal.ts index be5a3123528..48b65d0642e 100644 --- a/src/main/codex/structured/threads/codex-structured-thread-goal.ts +++ b/src/main/codex/structured/threads/codex-structured-thread-goal.ts @@ -120,7 +120,16 @@ export async function changeCodexThreadGoalWithSettings( try { if (startsWork) { const requested = resolvedCodexGoalSettings(session, input.executionOptions) - const previousApplied = session.appliedTurnOptions + let previousApplied = session.appliedTurnOptions + let previousInput = session.appliedTurnInputOptions + let invalidatedApplied: CodexSession['appliedTurnOptions'] + let invalidatedInput: CodexSession['appliedTurnInputOptions'] + const ownsAcquisition = () => + current() && + !session.ended && + !session.connection.closed && + session.fence === input.fence && + session.acquisitionGeneration === generation const installed = await session.appliedSettings?.install( session.connection, session.threadId, @@ -128,19 +137,44 @@ export async function changeCodexThreadGoalWithSettings( timeoutMs, input.signal, () => { - session.appliedTurnOptions = { ...session.appliedTurnOptions, ...requested } + if (!ownsAcquisition()) { + return + } + if (session.appliedTurnOptions === invalidatedApplied) { + session.appliedTurnOptions = { ...invalidatedApplied, ...requested } + } + if (session.appliedTurnInputOptions === invalidatedInput) { + session.appliedTurnInputOptions = { ...invalidatedInput, ...requested } + } }, () => { - session.appliedTurnOptions = previousApplied + if (!ownsAcquisition()) { + return + } + if (session.appliedTurnOptions === invalidatedApplied) { + session.appliedTurnOptions = previousApplied + } + if (session.appliedTurnInputOptions === invalidatedInput) { + session.appliedTurnInputOptions = previousInput + } }, () => { + previousApplied = session.appliedTurnOptions + previousInput = session.appliedTurnInputOptions const known = { ...previousApplied } + const knownInput = { ...previousInput } for (const key of ['model', 'effort'] as const) { if (requested[key] !== undefined && requested[key] !== known[key]) { delete known[key] } + if (requested[key] !== undefined && requested[key] !== knownInput[key]) { + delete knownInput[key] + } } - session.appliedTurnOptions = known + invalidatedApplied = known + invalidatedInput = knownInput + session.appliedTurnOptions = invalidatedApplied + session.appliedTurnInputOptions = invalidatedInput } ) if (installed && !installed.ok) { diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts b/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts index f9cf8c3b058..23e9fd67015 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts @@ -1,7 +1,13 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { + createDeferredStructuredAgentSessionEventSink, + type StructuredAgentSessionEventSink +} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createFixture } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-store-contract-test-fixture' +import { testEventSinkLogging } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' +import { StructuredAgentSessionCurrentWork } from '../../../native-chat/agent-session-wire/observations/structured-agent-session-current-work' import { MAX_CODEX_PENDING_DISPATCH_ECHOES } from './codex-structured-dispatch-echo' import { acquiredCodexAdapter, @@ -43,6 +49,26 @@ function lifecycleRecorder(): { } describe('codex dispatch admission', () => { + it('releases acknowledged steers without an echo and retains each late receipt', async () => { + const codex = fakeCodexAppServer({ 'turn/steer': () => ({ turnId: 'turn-1' }) }) + const settlements: LateSettlement[] = [] + const adapter = await acquiredCodexAdapter({ codex, settlements }) + const connection = codex.connections[0]! + startTurn(connection, 'turn-1') + expect(await send(adapter, 'client-1')).toMatchObject({ state: 'admitted' }) + expect(adapter.heldSends('session-1')).toEqual(new Set()) + expect(await send(adapter, 'client-2')).toMatchObject({ state: 'admitted' }) + expect(adapter.heldSends('session-1')).toEqual(new Set()) + echoUserMessage(connection, { turnId: 'turn-1', itemId: 'late-1', clientId: 'client-1' }) + echoUserMessage(connection, { turnId: 'turn-1', itemId: 'late-2', clientId: 'client-2' }) + expect(settlements.map(({ clientMessageId }) => clientMessageId)).toEqual([ + 'client-1', + 'client-2' + ]) + expect(connection.calls.filter(({ method }) => method === 'turn/steer')).toHaveLength(2) + await adapter.closeSession('session-1') + }) + it('correlates each send by client message id, not queue order', async () => { const codex = fakeCodexAppServer({ 'turn/steer': () => ({ turnId: 'turn-1' }) }) const settlements: LateSettlement[] = [] @@ -190,3 +216,73 @@ describe('codex dispatch admission', () => { expect(settlements).toEqual([]) }) }) + +describe('ordered Codex admission publication', () => { + const fixture = createFixture() + + it('holds a replied start through refused and delayed journal writes, then releases without an echo', async () => { + const journal = await fixture.open() + const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + deferred.bind({ journal, fence: 7, publish: () => {} }) + let refuse = true + const revise = deferred.sink.tryReviseResolvedItem! + deferred.sink.tryReviseResolvedItem = (...args) => + refuse ? { accepted: false, reason: 'backpressure' } : revise(...args) + const write = journal.appendResolvedItem.bind(journal) + const delay = Promise.withResolvers() + let delayed = false + vi.spyOn(journal, 'appendResolvedItem').mockImplementation(async (...args) => { + delayed = true + await delay.promise + return write(...args) + }) + const codex = fakeCodexAppServer({ 'turn/start': () => ({ turn: { id: 'ordered-turn' } }) }) + let work: StructuredAgentSessionCurrentWork | undefined + const observed: { active: string | null; working: boolean }[] = [] + const adapter = await acquiredCodexAdapter({ + codex, + settlements: [], + sink: deferred.sink, + onHeldSendsChanged: () => { + if (work) { + observed.push({ active: work.activeTurnId(), working: work.working() }) + } + } + }) + work = new StructuredAgentSessionCurrentWork(journal, 7, 0, undefined, undefined, false, () => + adapter.heldSends('session-1') + ) + await journal.appendSubmission({ + clientMessageId: 'ordered', + payloadFingerprint: 'ordered-input', + body: CODEX_TEST_USER_MESSAGE, + fence: 7 + }) + await send(adapter, 'ordered') + const submission = journal.submission('ordered')! + expect(work.publishedSubmission(submission)).toMatchObject({ dispatchState: 'pending' }) + expect(work.working()).toBe(true) + + startTurn(codex.connections[0]!, 'ordered-turn') + expect(work.activeTurnId()).toBeNull() + expect(work.working()).toBe(true) + refuse = false + await vi.waitFor(() => expect(delayed).toBe(true)) + expect(work.activeTurnId()).toBeNull() + expect(work.publishedSubmission(submission)).toMatchObject({ dispatchState: 'pending' }) + delay.resolve() + await deferred.sink.written!() + await vi.waitFor(() => + expect(work!.publishedSubmission(submission)).toMatchObject({ + dispatchState: 'unknown', + recovered: true, + reason: 'provider_write_outcome_unknown' + }) + ) + expect(work.activeTurnId()).toBe('ordered-turn') + expect(work.working()).toBe(true) + expect(observed).toEqual([{ active: 'ordered-turn', working: true }]) + await adapter.closeSession('session-1') + deferred.close() + }) +}) diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts b/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts index 447179d8496..1b5842ca410 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts @@ -73,7 +73,7 @@ it.each(['start', 'steer'] as const)( describe('the sends Codex holds', () => { const held = (echoes: ReturnType) => [...echoes.heldSends()] - it('holds a send from its write until the turn it was answered into ends, echo or not', () => { + it('holds a replied start until its turn is published without consuming its echo', () => { const changes: string[] = [] const echoes = createCodexDispatchEchoes(() => changes.push(held(echoes).join(','))) echoes.arm('sent') @@ -82,12 +82,34 @@ describe('the sends Codex holds', () => { echoes.bindTurn('sent', 'thread-1', 'turn-1', 'start', echoes.tick()) expect(held(echoes)).toEqual(['sent']) - // A hook can refuse input and complete the turn without echoing it. - echoes.endTurn('thread-1', 'turn-1', { status: 'completed' }) + echoes.opened('thread-1', 'turn-1') + expect(held(echoes)).toEqual(['sent']) + echoes.published('thread-1', 'turn-1') expect(held(echoes)).toEqual([]) expect(changes).toEqual(['']) }) + it('releases a replied steer into a published turn while retaining exact late correlation', () => { + const echoes = createCodexDispatchEchoes() + echoes.published('thread-1', 'turn-1') + echoes.arm('steered') + echoes.expect('steered', 'thread-1', 'steer', [], 'turn-1') + expect(held(echoes)).toEqual(['steered']) + echoes.bindTurn('steered', 'thread-1', 'turn-1', 'steer', echoes.tick()) + expect(held(echoes)).toEqual([]) + expect( + readCodexDispatchEcho( + { + type: 'userMessage', + id: 'late-user', + clientId: 'steered' + }, + CODEX_IDENTITY, + echoes + )?.clientMessageId + ).toBe('steered') + }) + it('holds a send answered into no turn only while a status read after its answer says running', () => { const echoes = createCodexDispatchEchoes() echoes.arm('timed-out') diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts b/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts index aa6bb41e05d..c469ba6a9d8 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts @@ -8,10 +8,7 @@ import type { ProviderDiagnostic } from '../../../../shared/agent-session/failur import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { AgentJournalTurnJoin } from '../../../../shared/agent-session/journal/agent-session-journal-types' -export { - MAX_CODEX_PENDING_DISPATCH_ECHOES, - MAX_CODEX_RECORDED_TURN_ENDS -} from './codex-dispatch-receipt-correlation' +export { MAX_CODEX_PENDING_DISPATCH_ECHOES, MAX_CODEX_RECORDED_TURN_ENDS } export type CodexTurnEnd = | { status: 'completed' } @@ -31,7 +28,7 @@ export type CodexDispatchEchoes = { answered: (clientMessageId: string, at: number) => void /** Only status received after a no-turn answer determines whether that send is held. */ observeStatus: (active: boolean) => void - /** Sends still executing; ended turns release them even without an echo. */ + /** Sends awaiting admission to a published turn; exact echoes remain independently armed. */ heldSends: () => ReadonlySet /** False at capacity preserves older pending sends. */ arm: (clientMessageId: string, requestedAt?: number) => boolean @@ -63,6 +60,8 @@ export type CodexDispatchEchoes = { /** Mark a timed-out open wait so later sends do not wait again. */ leftUnopened: (threadId: string, turnId: string) => void opened: (threadId: string, turnId: string) => void + /** The turn's admitted journal writes landed; receipt observation alone cannot release work. */ + published: (threadId: string, turnId: string) => void /** An error naming a never-opened turn counts as its end. */ hasOpened: (threadId: string, turnId: string) => boolean /** Latest answered turn still unopened after its wait was exhausted. */ @@ -105,12 +104,14 @@ export function createCodexDispatchEchoes( >() let clock = 0 let status: { active: boolean; at: number } | null = null + const publishedTurns = new Set() const heldSends = (): Set => new Set( [...armed].flatMap(([clientMessageId, entry]) => entry.answeredAt === undefined || (entry.turn - ? entry.turnEnded !== true + ? entry.turnEnded !== true && + !publishedTurns.has(turnKey(entry.turn.threadId, entry.turn.turnId)) : status?.active === true && status.at > entry.answeredAt) ? [clientMessageId] : [] @@ -224,6 +225,16 @@ export function createCodexDispatchEchoes( openedTurns.delete(oldest) } }, + published: (threadId, turnId) => + reporting(() => { + publishedTurns.add(turnKey(threadId, turnId)) + for (const oldest of publishedTurns) { + if (publishedTurns.size <= MAX_CODEX_RECORDED_TURN_ENDS) { + break + } + publishedTurns.delete(oldest) + } + }), hasOpened: (threadId, turnId) => openedTurns.has(turnKey(threadId, turnId)), endTurn: (threadId, turnId, end) => reporting(() => { @@ -286,6 +297,7 @@ export function createCodexDispatchEchoes( receiptCorrelation.clear() unopenedTurns.clear() openedTurns.clear() + publishedTurns.clear() nextSequence = 0 }, get size() { diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts b/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts index dc301fe56da..6c232e59d13 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts @@ -99,6 +99,7 @@ export async function acquiredCodexAdapter(input: { sink?: StructuredAgentSessionEventSink requestTimeoutMs?: number permissionMode?: AgentChatPermissionChoice + onHeldSendsChanged?: CodexStructuredSessionAdapterDeps['onHeldSendsChanged'] }): Promise { const adapter = new CodexStructuredSessionAdapter({ resolveLaunch: async () => ({ @@ -114,6 +115,7 @@ export async function acquiredCodexAdapter(input: { onDispatchSettledLate: (settlement) => { input.settlements.push(settlement) }, + ...(input.onHeldSendsChanged ? { onHeldSendsChanged: input.onHeldSendsChanged } : {}), ...(input.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: input.requestTimeoutMs }) }) const identity: AgentSessionJournalIdentity = { diff --git a/src/main/codex/structured/turns/codex-structured-message-options.test.ts b/src/main/codex/structured/turns/codex-structured-message-options.test.ts index 907fbc4b505..77ac386d2e3 100644 --- a/src/main/codex/structured/turns/codex-structured-message-options.test.ts +++ b/src/main/codex/structured/turns/codex-structured-message-options.test.ts @@ -9,11 +9,28 @@ import { claudeAndCodexAgents } from '../../../native-chat/agent-session-wire/pr import { describe, expect, it, vi } from 'vitest' import { AgentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' import { optionSession } from '../catalog/codex-structured-option-session.test-fixture' -import { resolvedCodexMessageOptions } from './codex-structured-message-options' +import { + readCodexAppliedInputOptions, + resolvedCodexMessageOptions +} from './codex-structured-message-options' +import { + codexTurnOptionsDiffer, + waitsForCodexTurnOptions +} from '../../../native-chat/agent-session-wire/options/structured-agent-session-message-options' import { startCodexTurn } from './codex-structured-turn-start' import { CodexAppServerRequestError } from '../../app-server/codex-app-server-request-error' +import { CodexAppliedSettings } from '../catalog/codex-structured-applied-settings' +import { changeCodexThreadGoalWithSettings } from '../threads/codex-structured-thread-goal' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' -import { USER_MESSAGE } from '../session-lifecycle/codex-structured-session-adapter-fixture' +import { + USER_MESSAGE, + fakeCodex, + adapterFor, + acquireReadyCodexForTest, + identityFor, + answerWithOpenedTurn +} from '../session-lifecycle/codex-structured-session-adapter-fixture' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' function seedMessageDefaults(session: CodexSession): void { const store = new AgentModelCatalogStore() @@ -29,7 +46,7 @@ function seedMessageDefaults(session: CodexSession): void { label: 'Model A', isDefault: false, defaultEffort: 'low', - serviceTiers: [{ value: 'priority', label: 'Priority' }], + serviceTiers: [{ value: 'priority', label: 'Fast' }], efforts: [ { value: 'low', label: 'Low' }, { value: 'high', label: 'High' } @@ -211,3 +228,237 @@ it('sends native Plan and Build on fresh turns while a steer keeps its running m expect(request.mock.calls.at(-1)?.[0]).toBe('turn/steer') expect(request.mock.calls.at(-1)?.[1]).not.toHaveProperty('collaborationMode') }) + +it.each(['priority', 'default'])( + 'keeps the same priority input eligible after an actual %s start and catalog change', + async (initialTier) => { + const request = vi.fn(async () => ({ turn: { id: 'tier-turn' } })) + const session = optionSession(request) + const store = new AgentModelCatalogStore() + const catalog = (priority: boolean) => + store.recordSuccess( + 'input-intent', + 'codex', + { + origin: 'probe', + models: [ + { + id: 'gpt-live', + label: 'GPT', + isDefault: true, + efforts: [{ value: 'high', label: 'High' }], + serviceTiers: priority ? [{ value: 'priority', label: 'Fast' }] : [] + } + ] + }, + 'discovery' + ) + session.catalogAccess = { store, fingerprint: 'input-intent', accountHomePath: '/test-account' } + session.reportedOptions = { model: 'gpt-live', effort: 'high', serviceTier: 'default' } + catalog(initialTier === 'priority') + const choices = { model: 'gpt-live', effort: 'high', serviceTier: 'priority' } + await startCodexTurn(session, { + clientMessageId: 'priority-input', + body: USER_MESSAGE, + executionOptions: choices, + turnOptions: await resolvedCodexMessageOptions(session, choices) + }) + expect(request).toHaveBeenCalledWith( + 'turn/start', + expect.objectContaining({ + serviceTier: initialTier + }), + expect.anything() + ) + catalog(false) + const differs = (next: Record) => + codexTurnOptionsDiffer( + { provider: 'codex', sessionId: 'session-1' }, + next, + { fence: 1, generation: 'generation-1', phase: 'ready' }, + { readAppliedInputOptions: (input) => readCodexAppliedInputOptions(session, input) } + ) + expect(differs(choices)).toBe(false) + expect(differs({ ...choices, serviceTier: 'default' })).toBe(true) + } +) + +it('holds Plan behind a successful sparse Default start, then starts Plan after completion', async () => { + const codex = fakeCodex() + const adapter = adapterFor(codex) + const bodies: AgentJournalItemBody[] = [] + const acquisition = await acquireReadyCodexForTest(adapter, { + identity: identityFor('session-1'), + fence: 7, + spawnToken: 'spawn', + events: { + appendItem: (_identity, body) => bodies.push(body), + appendTombstone: () => {}, + publish: () => {} + } + }) + const dispatch = (id: string, options: Record) => + adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: id, + body: USER_MESSAGE, + executionOptions: options + }) + const complete = (turnId: string) => + codex.connections[0].handlers.onNotification?.('turn/completed', { + threadId: 'thread-abc', + turn: { id: turnId, status: 'completed' } + }) + const held = (interactionMode: 'default' | 'plan') => + waitsForCodexTurnOptions( + { provider: 'codex', sessionId: 'session-1' }, + { + newestTurn: () => bodies.findLast((body) => body.kind === 'turn') ?? null, + itemBody: () => USER_MESSAGE + }, + { + clientMessageId: 'next-plan', + fence: 7, + payloadFingerprint: 'fingerprint', + dispatchState: 'pending', + providerItemId: null, + reason: null, + submittedAt: 1, + resolvedAt: null, + options: { interactionMode } + }, + { fence: 7, generation: acquisition.acquisitionGeneration, phase: 'ready' }, + adapter + ) + try { + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'plan-first') + expect(await dispatch('first', { interactionMode: 'plan' })).toMatchObject({ + state: 'admitted' + }) + complete('plan-first') + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'default-second') + expect(await dispatch('second', {})).toMatchObject({ state: 'admitted' }) + expect( + codex.connections[0].calls.findLast((call) => call.method === 'turn/start')?.params + ).toMatchObject({ collaborationMode: { mode: 'default' } }) + expect(held('plan')).toBe(true) + expect(held('default')).toBe(false) + complete('default-second') + expect(held('plan')).toBe(false) + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'plan-third') + expect(await dispatch('third', { interactionMode: 'plan' })).toMatchObject({ + state: 'admitted' + }) + expect( + codex.connections[0].calls.findLast((call) => call.method === 'turn/start')?.params + ).toMatchObject({ collaborationMode: { mode: 'plan' } }) + } finally { + await adapter.closeAll() + } +}) + +it('uses exact successful start controls when the first message omits model and effort', async () => { + const session = optionSession(vi.fn(async () => ({ turn: { id: 'first-turn' } }))) + await startCodexTurn(session, { + clientMessageId: 'first', + body: USER_MESSAGE, + executionOptions: {}, + turnOptions: {} + }) + const read = (next: Record) => + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next + }) + expect(read({ effort: 'high' })).toMatchObject({ + active: { model: 'gpt-live', effort: 'high' }, + next: { model: 'gpt-live', effort: 'high' } + }) + expect(read({ effort: 'low' })).toMatchObject({ + active: { effort: 'high' }, + next: { effort: 'low' } + }) +}) + +it('inherits retained sparse intent ahead of canonical execution controls', async () => { + const session = optionSession(vi.fn(async () => ({ turn: { id: 'sparse-turn' } }))) + session.appliedTurnOptions = { model: 'gpt-canonical', effort: 'high' } + session.appliedTurnInputOptions = { model: 'gpt-alias', effort: 'low' } + const choices = { model: 'gpt-alias' } + await startCodexTurn(session, { + clientMessageId: 'sparse', + body: USER_MESSAGE, + executionOptions: choices, + turnOptions: await resolvedCodexMessageOptions(session, choices) + }) + expect( + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next: { model: 'gpt-alias', effort: 'low' } + }) + ).toMatchObject({ + active: { model: 'gpt-alias', effort: 'low' }, + next: { model: 'gpt-alias', effort: 'low' } + }) +}) + +it('retains legacy fast intent as the successful native tier after a standard turn', async () => { + const session = optionSession(vi.fn(async () => ({ turn: { id: 'fast-turn' } }))) + seedMessageDefaults(session) + session.appliedTurnInputOptions = { model: 'model-a', serviceTier: 'default' } + const choices = { model: 'model-a', fastMode: 'true' as const } + await startCodexTurn(session, { + clientMessageId: 'legacy-fast', + body: USER_MESSAGE, + executionOptions: choices, + turnOptions: await resolvedCodexMessageOptions(session, choices) + }) + expect(Object.fromEntries(session.options)).toEqual({ model: 'model-a', serviceTier: 'priority' }) + expect( + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next: { serviceTier: 'priority' } + }) + ).toMatchObject({ active: { serviceTier: 'priority' }, next: { serviceTier: 'priority' } }) +}) + +it('invalidates uncertain goal choices independently from shaped execution evidence', async () => { + const session = optionSession( + vi.fn(async () => { + throw new Error('lost after write') + }) + ) + session.appliedSettings = new CodexAppliedSettings() + session.appliedSettings.observe({ model: 'gpt-canonical', effort: 'high' }) + session.appliedTurnOptions = { model: 'gpt-canonical', effort: 'high' } + session.appliedTurnInputOptions = { model: 'gpt-alias', effort: 'low', serviceTier: 'default' } + expect( + await changeCodexThreadGoalWithSettings( + session, + { + sessionId: 'session-1', + fence: 1, + change: { kind: 'set', objective: 'Ship it' }, + replacesGoal: false, + executionOptions: { model: 'gpt-canonical', effort: 'low' } + }, + 1000, + () => true + ) + ).toMatchObject({ ok: false }) + expect( + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next: {} + })?.active + ).toEqual({ effort: 'low', serviceTier: 'default' }) +}) diff --git a/src/main/codex/structured/turns/codex-structured-message-options.ts b/src/main/codex/structured/turns/codex-structured-message-options.ts index f2d2fa9532b..ed853b25734 100644 --- a/src/main/codex/structured/turns/codex-structured-message-options.ts +++ b/src/main/codex/structured/turns/codex-structured-message-options.ts @@ -37,8 +37,9 @@ export async function resolvedCodexMessageOptions( return compileCodexMessageOptions(session, choices) } -function compileCodexMessageOptions( - session: CodexSession, +export function compileCodexMessageOptions( + session: Pick & + Partial>, choices: Readonly> ): Readonly> { const compiled: Record = {} @@ -57,7 +58,29 @@ function compileCodexMessageOptions( return codexTurnRequestOptions(session, compiled) } -/** The same sparse controls as dispatch, compared under the exact acquisition that took them. */ +/** Compare retained input choices, without reinterpreting them through a later catalog. */ +export function codexMessageInputOptions( + choices: Readonly>, + inherited: Readonly> = {}, + applied: Readonly> = {} +): Readonly> { + const next = { ...inherited } + for (const key of ['model', 'effort', 'personality', 'serviceTier', 'interactionMode'] as const) { + if (choices[key] !== undefined) { + next[key] = choices[key] + } + } + if (choices.serviceTier === undefined && choices.fastMode !== undefined) { + const legacy = codexServiceTierOfFastMode(choices.fastMode, undefined) + const inheritedTier = inherited.serviceTier + const tier = + inheritedTier === 'priority' || inheritedTier === 'fast' ? inheritedTier : applied.serviceTier + next.serviceTier = legacy === 'fast' && (tier === 'priority' || tier === 'fast') ? tier : legacy + } + return next +} + +/** Intent belongs to this exact acquisition; catalog/readback differences are not send barriers. */ export function readCodexAppliedInputOptions( session: CodexSession | undefined, input: Parameters>[0] @@ -68,13 +91,13 @@ export function readCodexAppliedInputOptions( session.connection.closed || session.fence !== input.fence || session.acquisitionGeneration !== input.acquisitionGeneration || - !session.appliedTurnOptions + !session.appliedTurnInputOptions ) { return null } - const active = session.appliedTurnOptions + const active = session.appliedTurnInputOptions const requested = input.next ?? Object.fromEntries(session.options) - return { active, next: { ...active, ...compileCodexMessageOptions(session, requested) } } + return { active, next: codexMessageInputOptions(requested, active, session.appliedTurnOptions) } } /** Check the live binding after options settle and again whenever the provider is about to write. */ diff --git a/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts b/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts index 69513fc5251..a5a420758de 100644 --- a/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts +++ b/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts @@ -97,6 +97,36 @@ export function noteCodexTurnOpened( } } +export function publishCodexTurnOpened( + session: CodexSession, + frame: { sessionId: string; method: string; params: unknown }, + sessions: ReadonlyMap +): void { + const { method, params } = frame + const turnId = method === 'turn/started' ? readCodexTurnId(params) : null + if (!turnId || (readCodexThreadId(params) ?? session.threadId) !== session.threadId) { + return + } + const publish = (): void => { + if (!session.ended && sessions.get(frame.sessionId) === session) { + session.dispatchEchoes.published(session.threadId, turnId) + } + } + const written = session.events?.written?.() + if (written) { + void written.then( + (result) => { + if (result.ok) { + publish() + } + }, + () => {} + ) + } else { + publish() + } +} + export function settleCodexSendsInEndedTurn( session: Pick, frame: { sessionId: string; method: string; params: unknown } diff --git a/src/main/codex/structured/turns/codex-structured-turn-start.ts b/src/main/codex/structured/turns/codex-structured-turn-start.ts index 75a80fabc52..6da125a55d1 100644 --- a/src/main/codex/structured/turns/codex-structured-turn-start.ts +++ b/src/main/codex/structured/turns/codex-structured-turn-start.ts @@ -4,7 +4,11 @@ import { StructuredAgentSessionInputNotAdmitted, type StructuredAgentSessionAdmitFreshInput } from '../../../native-chat/agent-session-wire/delivery/structured-agent-session-input-admission' -import { turnInputFor } from './codex-structured-message-options' +import { + codexMessageInputOptions, + compileCodexMessageOptions, + turnInputFor +} from './codex-structured-message-options' import { reportedCodexPermissionMode } from '../threads/codex-structured-thread-open' import { admitCodexTurnPermission } from './codex-structured-turn-permission' import type { CodexSkillReport } from '../catalog/codex-structured-skill-report' @@ -23,7 +27,7 @@ import type { CodexAppServerConnection } from '../../app-server/codex-app-server import { isCodexAppServerUnsupportedError } from '../../app-server/codex-app-server-session' import type { CodexDispatchEchoes } from './codex-structured-dispatch-echo' import { readCodexTurnId } from '../../app-server/codex-structured-thread-facts' -import { codexTurnRequestOptions } from '../catalog/codex-structured-service-tier' +import type { AgentSessionExecutionOptions } from '../../../../shared/agent-session/options/agent-session-execution-options' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' import { codexRunningOrOpeningTurn, @@ -40,6 +44,7 @@ export type CodexTurnHost = { permissions?: CodexSession['permissions'] options: Map appliedTurnOptions?: Readonly> + appliedTurnInputOptions?: Readonly> appliedSettings?: CodexSession['appliedSettings'] reportedOptions?: CodexSession['reportedOptions'] catalogAccess?: CodexSession['catalogAccess'] @@ -50,18 +55,22 @@ export type CodexTurnHost = { turnOpenWaits: Pick } +type CodexTurnInput = { + clientMessageId: string + body: AgentJournalMessageItem + requestedAt?: number + turnOptions?: Readonly> + executionOptions?: AgentSessionExecutionOptions + signal?: AbortSignal + isCurrent?: () => boolean + admitFreshInput?: StructuredAgentSessionAdmitFreshInput +} + /** false means correlation capacity refused the send before writing; null turnId means an unnamed answer. */ export async function startCodexTurn( host: CodexTurnHost, - input: { - clientMessageId: string - body: AgentJournalMessageItem - requestedAt?: number + input: CodexTurnInput & { timeoutMs?: number - turnOptions?: Readonly> - signal?: AbortSignal - isCurrent?: () => boolean - admitFreshInput?: StructuredAgentSessionAdmitFreshInput onReply?: () => void } ): Promise<{ turnId: string | null; via: AgentJournalTurnJoin } | false> { @@ -90,8 +99,11 @@ export async function startCodexTurn( return steered } let previousApplied = host.appliedTurnOptions + let previousInput = host.appliedTurnInputOptions let previousOptions: Map | null | undefined let requested: Readonly> = {} + let inputChoices: Readonly> = {} + let requestControls: Record = {} let enqueued = false let discardSettingsAttempt: (() => void) | undefined const enqueue = ( @@ -110,14 +122,21 @@ export async function startCodexTurn( throw new StructuredAgentSessionInputNotAdmitted(undefined, 'permission') } previousApplied = host.appliedTurnOptions + previousInput = host.appliedTurnInputOptions + inputChoices = input.executionOptions ?? input.turnOptions ?? Object.fromEntries(host.options) previousOptions = input.turnOptions ? new Map(host.options) : null if (input.turnOptions) { host.options.clear() - for (const [key, value] of Object.entries(input.turnOptions)) { + for (const [key, value] of Object.entries( + codexMessageInputOptions(inputChoices, {}, input.turnOptions) + )) { host.options.set(key, value) } } - requested = { interactionMode: 'default', ...codexTurnRequestOptions(host) } + requested = { + interactionMode: 'default', + ...compileCodexMessageOptions(host, input.turnOptions ?? Object.fromEntries(host.options)) + } const { interactionMode, ...nativeOptions } = requested const collaborationMode = { mode: interactionMode, @@ -128,11 +147,21 @@ export async function startCodexTurn( developer_instructions: null } } + requestControls = { + ...requested, + ...(collaborationMode.settings.model ? { model: collaborationMode.settings.model } : {}), + ...(collaborationMode.settings.reasoning_effort + ? { effort: collaborationMode.settings.reasoning_effort } + : {}) + } const known = { ...previousApplied } - for (const key of Object.keys(requested)) { + const knownInput = { ...previousInput } + for (const key of new Set([...Object.keys(requested), ...Object.keys(inputChoices)])) { delete known[key] + delete knownInput[key] } host.appliedTurnOptions = known + host.appliedTurnInputOptions = knownInput discardSettingsAttempt = host.appliedSettings?.attempt(requested) enqueued = true host.dispatchEchoes.expect( @@ -202,9 +231,8 @@ export async function startCodexTurn( } if (isCodexAppServerRequestError(error) || isCodexAppServerUnsupportedError(error)) { discardSettingsAttempt?.() - } - if (isCodexAppServerRequestError(error) || isCodexAppServerUnsupportedError(error)) { host.appliedTurnOptions = previousApplied + host.appliedTurnInputOptions = previousInput if (previousOptions) { host.options.clear() for (const [key, value] of previousOptions) { @@ -215,22 +243,23 @@ export async function startCodexTurn( throw error } host.appliedTurnOptions = { ...previousApplied, ...requested } + host.appliedTurnInputOptions = codexMessageInputOptions( + inputChoices, + { + serviceTier: 'default', + ...requestControls, + ...previousInput, + interactionMode: requestControls.interactionMode + }, + requested + ) return { turnId: readCodexTurnId(answer), via: 'start' } } /** Replies establish admission; exact echoes establish identity. Timeouts cannot disprove delivery. */ export async function dispatchCodexTurn( session: CodexTurnHost, - input: { - sessionId: string - clientMessageId: string - body: AgentJournalMessageItem - requestedAt?: number - turnOptions?: Readonly> - signal?: AbortSignal - isCurrent?: () => boolean - admitFreshInput?: StructuredAgentSessionAdmitFreshInput - }, + input: CodexTurnInput & { sessionId: string }, timeoutMs: number | undefined ): Promise { let answer: { turnId: string | null; via: AgentJournalTurnJoin } | false @@ -270,12 +299,6 @@ export async function dispatchCodexTurn( return { state: 'rejected', ...codexDispatchRejection(agentSessionFailureFact('queueFull')) } } // An answer read after the turn it names already ended is settled by that end. - if (!answer.turnId) { - session.dispatchEchoes.answered( - input.clientMessageId, - answeredAt ?? session.dispatchEchoes.tick() - ) - } if (answer.turnId) { session.dispatchEchoes.bindTurn( input.clientMessageId, @@ -284,6 +307,11 @@ export async function dispatchCodexTurn( answer.via, answeredAt ) + } else { + session.dispatchEchoes.answered( + input.clientMessageId, + answeredAt ?? session.dispatchEchoes.tick() + ) } return { state: 'admitted', ranOptions: { ...session.appliedTurnOptions } } } diff --git a/src/main/codex/trust/grants/codex-managed-trust-reconciliation.ts b/src/main/codex/trust/grants/codex-managed-trust-reconciliation.ts index 8a5e7670634..1cc06b98a69 100644 --- a/src/main/codex/trust/grants/codex-managed-trust-reconciliation.ts +++ b/src/main/codex/trust/grants/codex-managed-trust-reconciliation.ts @@ -15,6 +15,7 @@ import { parseCodexTrustKey as parseTrustKey } from '../identity/codex-trust-identity' import { getCodexHookTrustSignature } from '../../hooks/definitions/codex-hook-identity' +import { getCodexManagedHookStatusMessage } from '../../hooks/definitions/codex-hook-definition' import { readCodexTrustGrantLedgerHome, removeCodexTrustGrantLedgerHome, @@ -70,7 +71,12 @@ export function readLedgerOrcaHashes( return [] } const hashes = new Set() - addLedgerRecognizedHashes(hashes, [ledgerHome], key, { ...parts, command, timeoutSec }) + addLedgerRecognizedHashes(hashes, [ledgerHome], key, { + ...parts, + command, + timeoutSec, + statusMessage: getCodexManagedHookStatusMessage(command) + }) return [...hashes].map((hash) => ({ [parts.eventLabel]: hash })) }) } @@ -116,7 +122,8 @@ function getCodexManagedHookTrustEntryKeys( groupIndex: parts.groupIndex, handlerIndex: parts.handlerIndex, command: options.command, - timeoutSec: options.timeoutSec + timeoutSec: options.timeoutSec, + statusMessage: getCodexManagedHookStatusMessage(options.command) } const recognizedHashes = new Set([ computeTrustedHash(expectedEntry), @@ -189,13 +196,15 @@ export function removeStaleWslCodexManagedHookTrustEntries(options: { continue } const linuxRuntimeHome = parts.sourcePath.slice(0, -'/hooks.json'.length) + const command = options.buildManagedCommand(linuxRuntimeHome) const expectedEntry: CodexTrustEntry = { sourcePath: parts.sourcePath, eventLabel: parts.eventLabel, groupIndex: parts.groupIndex, handlerIndex: parts.handlerIndex, - command: options.buildManagedCommand(linuxRuntimeHome), - timeoutSec: options.timeoutSec + command, + timeoutSec: options.timeoutSec, + statusMessage: getCodexManagedHookStatusMessage(command) } const recognizedHashes = new Set([ computeTrustedHash(expectedEntry), diff --git a/src/main/codex/trust/grants/codex-trust-grant-host.ts b/src/main/codex/trust/grants/codex-trust-grant-host.ts index 429c03cb3c2..f98ac04db7a 100644 --- a/src/main/codex/trust/grants/codex-trust-grant-host.ts +++ b/src/main/codex/trust/grants/codex-trust-grant-host.ts @@ -3,7 +3,7 @@ import { buildWslCodexAppServerArgs, buildWslCodexIdentityProbe, WSL_CODEX_AVAILABILITY_TIMEOUT_MS -} from '../../../codex-accounts/wsl-codex-command' +} from '../../../codex-cli/wsl-codex-command' import type { CodexHookTrustGrantRequest } from '../../app-server/codex-app-server-client' import { binaryStampsMatch, diff --git a/src/main/codex/trust/grants/codex-trust-grant-telemetry.ts b/src/main/codex/trust/grants/codex-trust-grant-telemetry.ts index a12abf842fc..f3ad03271f2 100644 --- a/src/main/codex/trust/grants/codex-trust-grant-telemetry.ts +++ b/src/main/codex/trust/grants/codex-trust-grant-telemetry.ts @@ -1,5 +1,5 @@ import type { CodexTrustGrantSessionVerifyClass } from '../../app-server/codex-app-server-client' -import { WSL_CODEX_NOT_FOUND_MESSAGE } from '../../../codex-accounts/wsl-codex-command' +import { WSL_CODEX_NOT_FOUND_MESSAGE } from '../../../codex-cli/wsl-codex-command' /** Retain legacy lanes for the telemetry schema and dashboards. */ export type CodexTrustGrantTelemetryLane = 'real-home' | 'managed' diff --git a/src/main/codex/codex-project-trust-ownership.test.ts b/src/main/codex/trust/toml/codex-project-trust-ownership.test.ts similarity index 99% rename from src/main/codex/codex-project-trust-ownership.test.ts rename to src/main/codex/trust/toml/codex-project-trust-ownership.test.ts index 92e7635d322..845865aa136 100644 --- a/src/main/codex/codex-project-trust-ownership.test.ts +++ b/src/main/codex/trust/toml/codex-project-trust-ownership.test.ts @@ -10,7 +10,7 @@ import { join } from 'node:path' import { removeOrcaCreatedProjectTrustEntries, upsertOrcaCreatedProjectTrustLevel -} from './trust/toml/config-toml-trust' +} from './config-toml-trust' const PROJECT = '/tmp/worktrees/feature-r1' const OTHER = '/tmp/worktrees/other-r1' diff --git a/src/main/computer/action-contracts/computer-blocked-key-combos.test.ts b/src/main/computer/action-contracts/computer-blocked-key-combos.test.ts new file mode 100644 index 00000000000..9e4974c5e0c --- /dev/null +++ b/src/main/computer/action-contracts/computer-blocked-key-combos.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { validateComputerProviderActionParams } from './computer-provider-action-validation' + +function sendKey( + method: 'hotkey' | 'pressKey', + key: string, + platform: NodeJS.Platform, + allowSystemShortcut?: boolean +): Promise { + return validateComputerProviderActionParams( + method, + { app: 'Target', key, ...(allowSystemShortcut ? { allowSystemShortcut } : {}) }, + platform + ) +} + +const BLOCKED: [NodeJS.Platform, 'hotkey' | 'pressKey', string][] = [ + ['darwin', 'hotkey', 'Cmd+Q'], + ['darwin', 'hotkey', 'CmdOrCtrl+q'], + ['darwin', 'hotkey', 'Shift+Command+Q'], + ['darwin', 'hotkey', 'Cmd+Option+Shift+Q'], + ['darwin', 'hotkey', 'Ctrl+Meta+Q'], + ['darwin', 'hotkey', 'Cmd+Alt+Esc'], + ['darwin', 'hotkey', 'Cmd+Shift+Delete'], + ['win32', 'hotkey', 'Alt+F4'], + ['win32', 'hotkey', 'Win+L'], + ['win32', 'hotkey', 'Ctrl+Shift+Escape'], + ['linux', 'hotkey', 'Ctrl+Q'], + ['linux', 'hotkey', 'CmdOrCtrl+Shift+Q'], + ['linux', 'hotkey', 'Alt+F4'], + ['linux', 'hotkey', 'Super+L'], + ['linux', 'hotkey', 'ctrl+alt+Delete'], + ['linux', 'hotkey', 'ctrl+alt+BackSpace'], + ['linux', 'hotkey', 'Ctrl+Alt+F2'], + ['linux', 'hotkey', 'Meta+F4'], + ['linux', 'hotkey', 'Ctrl+0x71'], + ['linux', 'hotkey', 'Alt+0xffc1'], + ['linux', 'hotkey', 'Alt+70'], + ['linux', 'hotkey', 'Alt+70suffix'], + ['linux', 'hotkey', 'Alt+70\rsuffix'], + ['linux', 'hotkey', 'Ctrl+Alt+L1'], + ['linux', 'hotkey', 'Ctrl+XF86Switch_VT_1'], + ['linux', 'pressKey', 'XF86_Switch_VT_2'], + ['linux', 'pressKey', 'Terminate_Server'], + ['linux', 'pressKey', 'XF86PowerOff'], + ['linux', 'pressKey', 'XF86_Sleep'], + ['linux', 'pressKey', 'ScreenSaver'], + ['linux', 'pressKey', '0x1008FF2A'] +] + +const ALLOWED: [NodeJS.Platform, 'hotkey' | 'pressKey', string][] = [ + ['darwin', 'hotkey', 'Cmd+A'], + ['darwin', 'hotkey', 'Ctrl+Q'], + ['darwin', 'hotkey', 'Cmd+ForwardDelete'], + ['darwin', 'pressKey', 'q'], + ['win32', 'hotkey', 'Ctrl+Q'], + ['win32', 'hotkey', 'Ctrl+Alt+Delete'], + ['linux', 'hotkey', 'Cmd+Q'], + ['linux', 'hotkey', 'Ctrl+Delete'], + ['linux', 'hotkey', 'Meta+L'], + ['linux', 'hotkey', 'Ctrl+u'], + ['linux', 'hotkey', 'Ctrl+1'], + ['linux', 'pressKey', 'Escape'] +] + +describe('blocked system shortcuts', () => { + it.each(BLOCKED)('refuses %s %s %s unless allowed', async (platform, method, key) => { + await expect(sendKey(method, key, platform)).rejects.toMatchObject({ + code: 'system_shortcut_blocked' + }) + await expect(sendKey(method, key, platform, true)).resolves.toBe('Target') + }) + + it.each(ALLOWED)('sends %s %s %s', async (platform, method, key) => { + await expect(sendKey(method, key, platform)).resolves.toBe('Target') + }) +}) diff --git a/src/main/computer/action-contracts/computer-blocked-key-combos.ts b/src/main/computer/action-contracts/computer-blocked-key-combos.ts new file mode 100644 index 00000000000..581f94a22aa --- /dev/null +++ b/src/main/computer/action-contracts/computer-blocked-key-combos.ts @@ -0,0 +1,177 @@ +import { RuntimeClientError } from '../runtime-client-error' + +// Design ported from vercel-labs/agent-desktop's per-platform blocked_combo lists (Apache-2.0). +type BlockedKeyCombo = { + modifiers: readonly string[] + keys: readonly string[] + effect: string +} + +type PlatformKeyRules = { + modifierAliases: Readonly> + keyAliases: Readonly> + canonicalKey?: (key: string) => string + // Most specific first so the error names what the combo would actually do. + blocked: readonly BlockedKeyCombo[] +} + +const SHARED_KEY_ALIASES = { esc: 'escape' } + +// Aliases mirror how each provider maps modifier names to physical keys. +const MACOS_RULES: PlatformKeyRules = { + modifierAliases: { + cmd: 'cmd', + command: 'cmd', + meta: 'cmd', + super: 'cmd', + win: 'cmd', + cmdorctrl: 'cmd', + commandorcontrol: 'cmd', + ctrl: 'ctrl', + control: 'ctrl', + alt: 'alt', + option: 'alt', + shift: 'shift' + }, + // The macOS provider sends both names as the same physical Delete key. + keyAliases: { ...SHARED_KEY_ALIASES, delete: 'backspace' }, + blocked: [ + { modifiers: ['cmd', 'ctrl'], keys: ['q'], effect: 'lock the screen' }, + { modifiers: ['cmd', 'shift'], keys: ['q'], effect: 'log out of macOS' }, + { modifiers: ['cmd', 'alt'], keys: ['escape'], effect: 'open the Force Quit window' }, + { modifiers: ['cmd', 'shift'], keys: ['backspace'], effect: 'empty the Trash' }, + { modifiers: ['cmd'], keys: ['q'], effect: 'quit the app' } + ] +} + +const WINDOWS_RULES: PlatformKeyRules = { + modifierAliases: { + ctrl: 'ctrl', + control: 'ctrl', + cmdorctrl: 'ctrl', + commandorcontrol: 'ctrl', + meta: 'win', + super: 'win', + win: 'win', + cmd: 'win', + command: 'win', + alt: 'alt', + option: 'alt', + shift: 'shift' + }, + keyAliases: SHARED_KEY_ALIASES, + // Ctrl+Alt+Delete is absent: Windows never honors a synthesized Secure Attention Sequence. + blocked: [ + { modifiers: ['alt'], keys: ['f4'], effect: 'close the app' }, + { modifiers: ['win'], keys: ['l'], effect: 'lock Windows' }, + { modifiers: ['ctrl', 'shift'], keys: ['escape'], effect: 'open Task Manager' } + ] +} + +const NUMERIC_KEYSYM = 'numeric keysym' + +const LINUX_RULES: PlatformKeyRules = { + modifierAliases: { + ctrl: 'ctrl', + control: 'ctrl', + cmdorctrl: 'ctrl', + commandorcontrol: 'ctrl', + // xdotool sends Meta_L, which default XKB layouts put on the Alt modifier. + meta: 'alt', + super: 'super', + win: 'super', + cmd: 'super', + command: 'super', + alt: 'alt', + option: 'alt', + shift: 'shift' + }, + // X11 names F11 and F12 L1 and L2 too. + keyAliases: { ...SHARED_KEY_ALIASES, l1: 'f11', l2: 'f12' }, + // Xlib and GDK resolve 0x/U hex keysyms and drop an optional XF86 prefix; xdotool reads any + // other token starting with a digit as a raw keycode (atoi ignores trailing text). + canonicalKey: (key) => + /^(\d[\s\S]+|u[0-9a-f]+)$/.test(key) ? NUMERIC_KEYSYM : key.replace(/^xf86_?/, ''), + blocked: [ + { + modifiers: [], + keys: [NUMERIC_KEYSYM], + effect: 'send a numeric keysym or keycode that computer use cannot check' + }, + { + modifiers: [], + keys: ['poweroff', 'powerdown', 'logoff', 'sleep', 'suspend', 'hibernate', 'standby'], + effect: 'power off, suspend or log out of the session' + }, + { modifiers: [], keys: ['screensaver'], effect: 'lock the screen' }, + { + modifiers: [], + keys: Array.from({ length: 12 }, (_, index) => `switch_vt_${index + 1}`), + effect: 'switch to another virtual terminal' + }, + { modifiers: [], keys: ['terminate_server'], effect: 'end the X session' }, + { + modifiers: ['ctrl', 'alt'], + keys: ['delete'], + effect: 'open the log out and power off dialog' + }, + { modifiers: ['ctrl', 'alt'], keys: ['backspace'], effect: 'end the X session' }, + { + modifiers: ['ctrl', 'alt'], + keys: ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12'], + effect: 'switch to another virtual terminal' + }, + { modifiers: ['ctrl', 'alt'], keys: ['l'], effect: 'lock the screen' }, + { modifiers: ['super'], keys: ['l'], effect: 'lock the screen' }, + { modifiers: ['alt'], keys: ['f4'], effect: 'close the window' }, + { modifiers: ['ctrl'], keys: ['q'], effect: 'quit the app' } + ] +} + +function platformKeyRules(platform: NodeJS.Platform): PlatformKeyRules { + if (platform === 'darwin') { + return MACOS_RULES + } + return platform === 'win32' ? WINDOWS_RULES : LINUX_RULES +} + +// Extra modifiers still match: Cmd+Alt+Shift+Q logs out just like Cmd+Shift+Q. +function findBlockedKeyCombo(key: string, platform: NodeJS.Platform): BlockedKeyCombo | null { + const rules = platformKeyRules(platform) + const parts = key === '+' ? ['+'] : key.split('+') + const modifiers = new Set() + let keyName = '' + for (const part of parts) { + const normalized = part.trim().toLowerCase() + const modifier = rules.modifierAliases[normalized.replace(/[\s_-]/g, '')] + if (modifier) { + modifiers.add(modifier) + } else { + const aliased = rules.keyAliases[normalized] ?? normalized + keyName = rules.canonicalKey ? rules.canonicalKey(aliased) : aliased + } + } + return ( + rules.blocked.find( + (combo) => + combo.keys.includes(keyName) && combo.modifiers.every((modifier) => modifiers.has(modifier)) + ) ?? null + ) +} + +export function assertComputerKeyComboAllowed( + params: Record, + key: string, + platform: NodeJS.Platform +): void { + if (params.allowSystemShortcut === true) { + return + } + const blocked = findBlockedKeyCombo(key, platform) + if (blocked) { + throw new RuntimeClientError( + 'system_shortcut_blocked', + `'${key}' would ${blocked.effect}, so computer use refuses it unless the caller passes --allow-system-shortcut` + ) + } +} diff --git a/src/main/computer/action-contracts/computer-provider-action-validation.ts b/src/main/computer/action-contracts/computer-provider-action-validation.ts index d6bc202b0a8..4c2df32046e 100644 --- a/src/main/computer/action-contracts/computer-provider-action-validation.ts +++ b/src/main/computer/action-contracts/computer-provider-action-validation.ts @@ -3,6 +3,7 @@ import { computerUseHotkeyValidationMessage, computerUsePressKeyValidationMessage } from '../../../shared/computer-use-key-spec' +import { assertComputerKeyComboAllowed } from './computer-blocked-key-combos' import { validateComputerClipboardPasteTextWithBoundedYield } from './computer-clipboard-paste-validation' import { RuntimeClientError } from '../runtime-client-error' @@ -19,7 +20,8 @@ type ComputerProviderActionMethod = export async function validateComputerProviderActionParams( method: ComputerProviderActionMethod, - params: Record + params: Record, + platform: NodeJS.Platform = process.platform ): Promise { const app = requireNonEmptyString(params, 'app') validateWindowTarget(params) @@ -43,16 +45,19 @@ export async function validateComputerProviderActionParams( validateDragTarget(params) return app case 'typeText': + if (params.elementIndex !== undefined) { + requireNonNegativeInteger(params, 'elementIndex') + } requireNonEmptyString(params, 'text') return app case 'pasteText': await validatePasteText(params) return app case 'pressKey': - validatePressKey(params) + validatePressKey(params, platform) return app case 'hotkey': - validateHotkey(params) + validateHotkey(params, platform) return app case 'setValue': requireNonNegativeInteger(params, 'elementIndex') @@ -182,20 +187,22 @@ function validateScrollDirection(params: Record): void { } } -function validatePressKey(params: Record): void { +function validatePressKey(params: Record, platform: NodeJS.Platform): void { const key = requireNonEmptyString(params, 'key') const message = computerUsePressKeyValidationMessage(key) if (message) { throw new RuntimeClientError('invalid_argument', message) } + assertComputerKeyComboAllowed(params, key, platform) } -function validateHotkey(params: Record): void { +function validateHotkey(params: Record, platform: NodeJS.Platform): void { const key = requireNonEmptyString(params, 'key') const message = computerUseHotkeyValidationMessage(key) if (message) { throw new RuntimeClientError('invalid_argument', message) } + assertComputerKeyComboAllowed(params, key, platform) } function validatePasteText(params: Record): Promise | void { diff --git a/src/main/computer/computer-sidecar.ts b/src/main/computer/computer-sidecar.ts index 58713795343..983f164c744 100644 --- a/src/main/computer/computer-sidecar.ts +++ b/src/main/computer/computer-sidecar.ts @@ -3,6 +3,7 @@ import { currentComputerProvider, shutdownComputerProviders } from './computer-p import { RuntimeClientError } from './runtime-client-error' import { ComputerTreeBaselines } from './computer-snapshot-tree-diff' import type { ComputerProviderCapabilities } from '../../shared/computer-use-runtime-types' +import { computerTypeTextTargetUnsupportedMessage } from '../../shared/computer-use-type-text-target' type SidecarRequest = { id: number @@ -77,6 +78,12 @@ async function dispatch(method: string, params: Record): Promis return treeBaselines.apply(params, await provider.action('drag', params)) } case 'typeText': { + if (params.elementIndex !== undefined) { + const unsupported = computerTypeTextTargetUnsupportedMessage(await provider.capabilities()) + if (unsupported) { + throw new RuntimeClientError('unsupported_capability', unsupported) + } + } return treeBaselines.apply(params, await provider.action('typeText', params)) } case 'pressKey': { diff --git a/src/main/computer/desktop-script/actions/desktop-script-action.ts b/src/main/computer/desktop-script/actions/desktop-script-action.ts index ca27e1e02cf..5c62cae9d3c 100644 --- a/src/main/computer/desktop-script/actions/desktop-script-action.ts +++ b/src/main/computer/desktop-script/actions/desktop-script-action.ts @@ -150,23 +150,41 @@ export function verifyDesktopAction( return action } const actual = refreshedElementValue(snapshot, targetElement, elementIndex) - if (actual === expected) { + if (actual === undefined || readbackCannotDecide(actual, expected)) { return { ...action, - verification: { state: 'verified', property: 'value', expected, actualPreview: actual } + verification: { + state: 'unverified', + reason: actual === undefined ? 'provider_unavailable' : 'readback_unsupported' + } } } + if (actual === expected) { + return { ...action, verification: { state: 'verified', property: 'value' } } + } return { ...action, - verification: { - state: 'unverified', - reason: actual === undefined ? 'provider_unavailable' : 'value_mismatch', - expected, - actualPreview: actual ?? null - } + verification: { state: 'unverified', reason: 'value_mismatch', actualPreview: actual } } } +// Why: runtime.ps1 and runtime.py show secure fields as "[redacted]" and cut values past 500 +// characters (UTF-16 units / code points) to a prefix plus "...", which can't prove or disprove the write. +const PROVIDER_VALUE_TEXT_LIMIT = 500 + +function readbackCannotDecide(actual: string, expected: string): boolean { + if (actual === '[redacted]') { + return true + } + const shown = actual.endsWith('...') ? actual.slice(0, -3) : undefined + return ( + shown !== undefined && + shown.length >= PROVIDER_VALUE_TEXT_LIMIT && + shown.length < expected.length && + expected.startsWith(shown) + ) +} + function refreshedElementValue( snapshot: BridgeSnapshot | undefined, targetElement: BridgeElement | undefined, diff --git a/src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts b/src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts index 2aae5399aca..c29f8c2faaf 100644 --- a/src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts +++ b/src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts @@ -49,13 +49,31 @@ describe('DesktopScriptProviderClient actions', () => { noScreenshot: true }) - expect(result.action).toMatchObject({ - verification: { - state: 'verified', - property: 'value', - expected: 'changed', - actualPreview: 'changed' - } + expect(result.action?.verification).toEqual({ state: 'verified', property: 'value' }) + }) + + it.each([ + ['a redacted secure field', 'hunter2', '[redacted]'], + ['a value cut at the provider text limit', 'x'.repeat(600), `${'x'.repeat(500)}...`], + ['a value cut at 500 code points', '😀'.repeat(600), `${'😀'.repeat(500)}...`] + ])('does not report %s as a failed set-value', async (_case, value, readback) => { + mockBridgeResponse({ ok: true, snapshot: sampleBridgeSnapshot('Login', 'initial') }) + mockBridgeResponse({ ok: true, capabilities: sampleCapabilities() }) + mockBridgeResponse({ ok: true, snapshot: sampleBridgeSnapshot('Login', readback) }) + + const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') + + await client.snapshot({ app: 'Login' }) + const result = await client.action('setValue', { + app: 'Login', + elementIndex: 0, + value, + noScreenshot: true + }) + + expect(result.action?.verification).toEqual({ + state: 'unverified', + reason: 'readback_unsupported' }) }) }) diff --git a/src/main/computer/desktop-script/desktop-script-provider-bridge.ts b/src/main/computer/desktop-script/desktop-script-provider-bridge.ts index f7de428387a..75cc71d6938 100644 --- a/src/main/computer/desktop-script/desktop-script-provider-bridge.ts +++ b/src/main/computer/desktop-script/desktop-script-provider-bridge.ts @@ -158,9 +158,12 @@ function runBridgeProcess( export function mapBridgeError(message: string): RuntimeClientError { const text = message.trim() || 'desktop provider failed' - if (/text_input_incomplete/i.test(text)) { + if (/text_input_incomplete|window_not_responding/i.test(text)) { return new RuntimeClientError('action_timeout', text) } + if (/target_elevated/i.test(text)) { + return new RuntimeClientError('permission_denied', text) + } if (/appNotFound|app not found/i.test(text)) { return new RuntimeClientError('app_not_found', text) } @@ -217,7 +220,7 @@ export function mapBridgeError(message: string): RuntimeClientError { return new RuntimeClientError('screenshot_failed', text) } if ( - /window_not_found|No top-level(?: AT-SPI| UI Automation)? window|has no (?:on-screen |accessibility )?window|could not match accessibility window|unknown window(?:_index| id)?/i.test( + /window_not_found|windowNotFound|No top-level(?: AT-SPI| UI Automation)? window|has no (?:on-screen |accessibility )?window|could not match accessibility window|unknown window(?:_index| id)?/i.test( text ) ) { diff --git a/src/main/computer/desktop-script/desktop-script-provider-client.ts b/src/main/computer/desktop-script/desktop-script-provider-client.ts index 1e00ec6f6aa..cb64132de77 100644 --- a/src/main/computer/desktop-script/desktop-script-provider-client.ts +++ b/src/main/computer/desktop-script/desktop-script-provider-client.ts @@ -40,6 +40,7 @@ import { isRuntimeHostUnavailable } from './runtime-host/desktop-script-runtime-host' import { DesktopScriptSnapshotStore } from './snapshots/desktop-script-snapshot-store' +import { readSubtreeSnapshot } from './snapshots/desktop-script-subtree-snapshot' import { normalizeBridgeApp, renderSnapshot } from './snapshots/desktop-script-snapshot-rendering' import { normalizeComputerActionResult } from '../action-contracts/computer-action-verification-normalization' import { RuntimeClientError } from '../runtime-client-error' @@ -119,6 +120,14 @@ export class DesktopScriptProviderClient { async snapshot(params: Record): Promise { const app = stringParam(params, 'app') + const rootElementIndex = optionalNumberParam(params, 'rootElementIndex') + if (rootElementIndex !== undefined) { + return await readSubtreeSnapshot(this.snapshotStore, (request) => this.callBridge(request), { + app, + rootElementIndex, + params + }) + } const response = await this.callBridge({ tool: 'get_app_state', app, diff --git a/src/main/computer/desktop-script/desktop-script-provider-types.ts b/src/main/computer/desktop-script/desktop-script-provider-types.ts index adcdb816766..8b57089c263 100644 --- a/src/main/computer/desktop-script/desktop-script-provider-types.ts +++ b/src/main/computer/desktop-script/desktop-script-provider-types.ts @@ -77,6 +77,12 @@ export type BridgeSnapshot = { focusedElementId?: number | null selectedText?: string | null elements?: BridgeElement[] + /** Set by the client when treeLines show only this element's subtree. */ + rootElementIndex?: number + /** Cache only: for elements a subtree read returned, the root of the latest read that returned them. */ + subtreeReadRoots?: ReadonlyMap + /** Cache only: the next index a subtree read may assign, so dropped indexes are never reused. */ + nextElementIndex?: number } export type BridgeWindow = { @@ -128,6 +134,8 @@ export type BridgeRequest = { requestId?: number app?: string element?: BridgeElement + /** get_app_state renders only this element's subtree. */ + root?: BridgeElement fromElement?: BridgeElement toElement?: BridgeElement x?: number diff --git a/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts b/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts index f16500f2fbe..7b32866b033 100644 --- a/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts +++ b/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts @@ -49,6 +49,9 @@ export function renderSnapshot( treeText, elementCount: snapshot.elements?.length ?? 0, focusedElementId, + ...(snapshot.rootElementIndex === undefined + ? {} + : { rootElementIndex: snapshot.rootElementIndex }), truncation: { truncated: snapshot.truncation?.truncated === true, maxNodes: snapshot.truncation?.maxNodes, @@ -125,6 +128,9 @@ function renderTreeText(snapshot: BridgeSnapshot): string { const lines = [ `App=${appRef} (pid ${snapshot.app.pid})`, `Window: "${sanitize(snapshot.windowTitle ?? snapshot.app.name)}", App: ${sanitize(snapshot.app.name)}.`, + ...(snapshot.rootElementIndex === undefined + ? [] + : [`Showing element ${snapshot.rootElementIndex} and its descendants.`]), '', ...(snapshot.treeLines ?? []) ] diff --git a/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts new file mode 100644 index 00000000000..d41bc05332e --- /dev/null +++ b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts @@ -0,0 +1,229 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + createDesktopScriptProviderClient, + mockBridgeResponse, + resetDesktopScriptProviderTestHarness, + sampleBridgeSnapshot, + sampleCapabilities +} from '../desktop-script-provider-test-harness' + +function bridgeSnapshot( + treeLines: string[], + elements: { index: number; runtimeId: number[]; name?: string }[] +) { + return { ...sampleBridgeSnapshot('Mail', ''), windowIndex: 0, treeLines, elements } +} + +describe('DesktopScriptProviderClient subtree reads', () => { + afterEach(resetDesktopScriptProviderTestHarness) + + it('keeps shown indexes, numbers hidden children after them, and resolves them for actions', async () => { + const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 frame Mail', '\t1 list Inbox', '\t\t2 button A', '\t\t... 1 more not shown'], + [ + { index: 0, runtimeId: [0] }, + { index: 1, runtimeId: [0, 0] }, + { index: 2, runtimeId: [0, 0, 0] } + ] + ) + }) + await client.snapshot({ app: 'Mail' }) + + let sentRoot: unknown + mockBridgeResponse( + { + ok: true, + snapshot: bridgeSnapshot( + ['0 list Inbox', '\t1 button A', '\t2 button B'], + [ + { index: 0, runtimeId: [0, 0] }, + { index: 1, runtimeId: [0, 0, 0] }, + { index: 2, runtimeId: [0, 0, 1] } + ] + ) + }, + (operation) => { + sentRoot = operation.root + } + ) + const subtree = await client.snapshot({ app: 'Mail', rootElementIndex: 1 }) + + expect(sentRoot).toMatchObject({ index: 1, runtimeId: [0, 0] }) + expect(subtree.snapshot.rootElementIndex).toBe(1) + expect(subtree.snapshot.treeText.split('\n').slice(2, 7)).toEqual([ + 'Showing element 1 and its descendants.', + '', + '1 list Inbox', + '\t2 button A', + '\t3 button B' + ]) + + let clicked: unknown + mockBridgeResponse({ ok: true, capabilities: sampleCapabilities() }) + mockBridgeResponse( + { ok: true, snapshot: bridgeSnapshot(['0 frame Mail'], [{ index: 0, runtimeId: [0] }]) }, + (operation) => { + clicked = operation.element + } + ) + await client.action('click', { app: 'Mail', elementIndex: 3 }) + expect(clicked).toMatchObject({ runtimeId: [0, 0, 1] }) + }) +}) + +describe('DesktopScriptProviderClient repeated subtree reads', () => { + afterEach(resetDesktopScriptProviderTestHarness) + + it('forgets children a live list replaced and keeps indexes outside the list', async () => { + const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 frame Mail', '\t1 list Inbox', '\t2 button Send'], + [ + { index: 0, runtimeId: [0] }, + { index: 1, runtimeId: [0, 0] }, + { index: 2, runtimeId: [0, 1] } + ] + ) + }) + await client.snapshot({ app: 'Mail' }) + + // The list recreates its child with a fresh runtime id on every read; each gets a never-used index. + let shownChild = '' + for (const generation of [1, 2]) { + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 list Inbox', '\t1 button A'], + [ + { index: 0, runtimeId: [0, 0] }, + { index: 1, runtimeId: [1, generation] } + ] + ) + }) + const read = await client.snapshot({ app: 'Mail', rootElementIndex: 1 }) + shownChild = read.snapshot.treeText.split('\n')[5] + } + expect(shownChild).toBe('\t4 button A') + + let sentRoot: unknown + mockBridgeResponse( + { + ok: true, + snapshot: bridgeSnapshot(['0 button Send'], [{ index: 0, runtimeId: [0, 1] }]) + }, + (operation) => { + sentRoot = operation.root + } + ) + await client.snapshot({ app: 'Mail', rootElementIndex: 2 }) + expect(sentRoot).toMatchObject({ runtimeId: [0, 1] }) + + // Answer the click in case the replaced child's index still resolves, so the assertion fails cleanly. + mockBridgeResponse({ ok: true, capabilities: sampleCapabilities() }) + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot(['0 frame Mail'], [{ index: 0, runtimeId: [0] }]) + }) + await expect(client.action('click', { app: 'Mail', elementIndex: 3 })).rejects.toMatchObject({ + code: 'element_not_found' + }) + }) + + it('renumbers a different element at a known runtime id but keeps the requested root', async () => { + const client = await createDesktopScriptProviderClient('windows', 'runtime.ps1') + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 window Inbox - Mail', '\t1 button Archive'], + [ + { index: 0, runtimeId: [42, 7], name: 'Inbox - Mail' }, + { index: 1, runtimeId: [42, 8], name: 'Archive' } + ] + ) + }) + await client.snapshot({ app: 'Mail' }) + + // Both renamed; only the root is known to be the same element, since the read started from it. + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 window Sent - Mail', '\t1 button Delete'], + [ + { index: 0, runtimeId: [42, 7], name: 'Sent - Mail' }, + { index: 1, runtimeId: [42, 8], name: 'Delete' } + ] + ) + }) + const read = await client.snapshot({ app: 'Mail', rootElementIndex: 0 }) + + expect(read.snapshot.treeText.split('\n').slice(4, 6)).toEqual([ + '0 window Sent - Mail', + '\t2 button Delete' + ]) + }) + + it('keeps an elided root readable under cache pressure and forgets its replaced children', async () => { + const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') + const outside = Array.from({ length: 1198 }, (_, index) => ({ + index: index + 2, + runtimeId: [10, index] + })) + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 frame Mail', '\t1 panel Pane', ...outside.map(({ index }) => `\t${index} list Other`)], + [{ index: 0, runtimeId: [0] }, { index: 1, runtimeId: [1] }, ...outside] + ) + }) + await client.snapshot({ app: 'Mail' }) + + const expanded = Array.from({ length: 1199 }, (_, index) => ({ + index: index + 1, + runtimeId: [20, index] + })) + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 list Other', ...expanded.map(({ index }) => `\t${index} button Other`)], + [{ index: 0, runtimeId: [10, 0] }, ...expanded] + ) + }) + await client.snapshot({ app: 'Mail', rootElementIndex: 2 }) + + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 list Items', '\t1 button A', '\t2 button B'], + [ + { index: 0, runtimeId: [30, 0] }, + { index: 1, runtimeId: [30, 1] }, + { index: 2, runtimeId: [30, 2] } + ] + ) + }) + await client.snapshot({ app: 'Mail', rootElementIndex: 1 }) + + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot(['0 panel Pane'], [{ index: 0, runtimeId: [1] }]) + }) + const repeated = await client.snapshot({ app: 'Mail', rootElementIndex: 1 }) + expect(repeated.snapshot.treeText.split('\n')[4]).toBe('1 panel Pane') + + mockBridgeResponse({ ok: true, capabilities: sampleCapabilities() }) + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot(['0 frame Mail'], [{ index: 0, runtimeId: [0] }]) + }) + await expect(client.action('click', { app: 'Mail', elementIndex: 2399 })).rejects.toMatchObject( + { + code: 'element_not_found' + } + ) + }) +}) diff --git a/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts new file mode 100644 index 00000000000..4d1b8407314 --- /dev/null +++ b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts @@ -0,0 +1,216 @@ +import type { ComputerSnapshotResult } from '../../../../shared/computer-use-runtime-types' +import { renumberComputerTreeLine } from '../../../../shared/computer-use-tree-text' +import { RuntimeClientError } from '../../runtime-client-error' +import { elementParam } from '../actions/desktop-script-action' +import { optionalNumberParam } from '../desktop-script-provider-params' +import type { + BridgeElement, + BridgeRequest, + BridgeResponse, + BridgeSnapshot +} from '../desktop-script-provider-types' +import type { DesktopScriptSnapshotStore } from './desktop-script-snapshot-store' +import { renderSnapshot } from './desktop-script-snapshot-rendering' + +/** Reads one element's subtree of the window the store last saw, the target of --element-index. */ +export async function readSubtreeSnapshot( + store: DesktopScriptSnapshotStore, + callBridge: (request: BridgeRequest) => Promise, + { + app, + rootElementIndex, + params + }: { app: string; rootElementIndex: number; params: Record } +): Promise { + const base = store.current(app, optionalNumberParam(params, 'windowId'), params) + if (!base) { + throw new RuntimeClientError( + 'element_not_found', + '--element-index needs a get-app-state snapshot of this app/window first' + ) + } + const response = await callBridge({ + tool: 'get_app_state', + app, + root: elementParam(base, rootElementIndex), + windowId: base.windowId ?? undefined, + windowIndex: base.windowIndex ?? undefined, + noScreenshot: params.noScreenshot === true, + restoreWindow: params.restoreWindow === true + }) + if (!response.snapshot) { + throw new RuntimeClientError('accessibility_error', 'desktop provider returned no snapshot') + } + const { shown, cached } = indexSubtreeSnapshot(base, response.snapshot, rootElementIndex) + store.remember(app, cached, params) + return renderSnapshot(shown, params.noScreenshot === true) +} + +// Two maximal provider walks: both providers stop at 1200 elements. +const MAX_CACHED_SUBTREE_SNAPSHOT_ELEMENTS = 2400 + +/** + * Gives a subtree read the indexes the window's cached snapshot already uses: elements it showed + * keep theirs, new ones get never-used indexes. Returns what to show and what to cache, where the + * cache keeps earlier elements so their indexes still resolve for actions, except those an earlier + * read of this root returned and this one did not, and the least recently returned beyond the cap. + */ +function indexSubtreeSnapshot( + base: BridgeSnapshot, + subtree: BridgeSnapshot, + rootElementIndex: number +): { shown: BridgeSnapshot; cached: BridgeSnapshot } { + const baseElements = base.elements ?? [] + const baseByRuntimeId = new Map>() + let nextIndex = base.nextElementIndex ?? 0 + let requestedRoot: BridgeElement | undefined + // Build backwards so duplicate candidates pop in their original order. + for (let position = baseElements.length - 1; position >= 0; position--) { + const element = baseElements[position] + nextIndex = Math.max(nextIndex, element.index + 1) + if (element.index === rootElementIndex) { + requestedRoot = element + } + const key = runtimeIdKey(element) + if (key === null) { + continue + } + const known = baseByRuntimeId.get(key) + if (!known) { + baseByRuntimeId.set(key, element) + continue + } + const signatures = + known instanceof Map ? known : new Map([[elementSignatureKey(known), [known]]]) + const signature = elementSignatureKey(element) + const candidates = signatures.get(signature) + if (candidates) { + candidates.push(element) + } else { + signatures.set(signature, [element]) + } + if (signatures !== known) { + baseByRuntimeId.set(key, signatures) + } + } + const requestedRootKey = requestedRoot ? runtimeIdKey(requestedRoot) : null + const indexes: number[] = [] + const claimed = new Set() + const subtreeElements = subtree.elements ?? [] + const walked: BridgeElement[] = [] + walked.length = subtreeElements.length + const subtreeReadRoots = new Map() + for (let position = 0; position < subtreeElements.length; position++) { + const element = subtreeElements[position] + const key = runtimeIdKey(element) + // Why: the provider resolved the rendered root from the requested handle, so it is that element + // even if its name changed; Windows resolves index 0 only as the window, never by runtime id. + const isRequestedRoot = position === 0 && key !== null && key === requestedRootKey + let known = isRequestedRoot ? requestedRoot : undefined + if (!isRequestedRoot) { + const candidate = key === null ? undefined : baseByRuntimeId.get(key) + if (candidate instanceof Map) { + const candidates = candidate.get(elementSignatureKey(element)) + known = candidates?.pop() + while (known && claimed.has(known.index)) { + known = candidates?.pop() + } + } else if ( + candidate && + !claimed.has(candidate.index) && + sameElementSignature(candidate, element) + ) { + known = candidate + } + } + const index = known?.index ?? nextIndex++ + claimed.add(index) + indexes[element.index] = index + walked[position] = { ...element, index } + if (index !== rootElementIndex) { + subtreeReadRoots.set(index, rootElementIndex) + } + } + const focusedElementId = + subtree.focusedElementId === null || subtree.focusedElementId === undefined + ? subtree.focusedElementId + : (indexes[subtree.focusedElementId] ?? null) + const indexLookup = { get: (index: number) => indexes[index] } + const shown: BridgeSnapshot = { + ...subtree, + treeLines: subtree.treeLines?.map((line) => renumberComputerTreeLine(line, indexLookup)), + focusedElementId, + elements: walked, + rootElementIndex + } + const baseReadRoots = base.subtreeReadRoots + const elidedRoot = requestedRoot && !claimed.has(rootElementIndex) ? requestedRoot : undefined + const retentionBudget = Math.max( + 0, + MAX_CACHED_SUBTREE_SNAPSHOT_ELEMENTS - walked.length - (elidedRoot ? 1 : 0) + ) + const retained: BridgeElement[] = [] + // Start at the newest cached elements and stop once the remaining budget is full. + for ( + let position = baseElements.length - 1; + position >= 0 && retained.length < retentionBudget; + position-- + ) { + const element = baseElements[position] + const readRoot = baseReadRoots?.get(element.index) + if ( + element.index !== rootElementIndex && + !claimed.has(element.index) && + readRoot !== rootElementIndex + ) { + retained.push(element) + if (readRoot !== undefined) { + subtreeReadRoots.set(element.index, readRoot) + } + } + } + retained.reverse() + const elements = retained.concat(walked) + if (elidedRoot) { + elements.push(elidedRoot) + } + const requestedReadRoot = baseReadRoots?.get(rootElementIndex) + if (requestedReadRoot !== undefined) { + subtreeReadRoots.set(rootElementIndex, requestedReadRoot) + } + const cached: BridgeSnapshot = { + ...shown, + elements, + subtreeReadRoots, + nextElementIndex: nextIndex + } + return { shown, cached } +} + +function runtimeIdKey(element: BridgeElement): string | null { + return Array.isArray(element.runtimeId) && element.runtimeId.length > 0 + ? JSON.stringify(element.runtimeId) + : null +} + +// Mirrors the Linux resolver's same_element_signature check. +function sameElementSignature(left: BridgeElement, right: BridgeElement): boolean { + const leftActions = left.actions ?? [] + const rightActions = right.actions ?? [] + return ( + (left.controlType ?? '') === (right.controlType ?? '') && + (left.name ?? '') === (right.name ?? '') && + (left.automationId ?? '') === (right.automationId ?? '') && + leftActions.length === rightActions.length && + leftActions.every((action, position) => action === rightActions[position]) + ) +} + +function elementSignatureKey(element: BridgeElement): string { + return JSON.stringify([ + element.controlType ?? '', + element.name ?? '', + element.automationId ?? '', + element.actions ?? [] + ]) +} diff --git a/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts b/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts index 48b187625e3..5123bca82ac 100644 --- a/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts +++ b/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts @@ -1,3 +1,4 @@ +import { setImmediate as settleTurn } from 'node:timers/promises' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ComputerUsePermissionStatusResult } from '../../../shared/computer-use-permissions-types' import type * as PermissionsModule from './macos-computer-use-permissions' @@ -5,10 +6,13 @@ import type * as PermissionsModule from './macos-computer-use-permissions' const mocks = vi.hoisted(() => ({ spawn: vi.fn(), spawnSync: vi.fn(), + runProcess: vi.fn(), + resetTcc: vi.fn(), peek: vi.fn(), readBundleId: vi.fn() })) +vi.mock('@orca/process-host', () => ({ runProcess: mocks.runProcess })) vi.mock('node:child_process', () => ({ spawn: mocks.spawn, spawnSync: mocks.spawnSync })) vi.mock('../macos-native/macos-native-provider-paths', () => ({ resolveMacOSComputerUseAppPath: () => '/Applications/Orca Computer Use.app' @@ -22,7 +26,7 @@ vi.mock('./macos-computer-use-permission-status-gate', () => ({ })) vi.mock('../../macos-permissions/macos-tcc-reset', () => ({ readMacosBundleId: mocks.readBundleId, - resetMacosTccPermission: async () => ({ ok: true }) + resetMacosTccPermission: mocks.resetTcc })) const denied: ComputerUsePermissionStatusResult = { @@ -52,6 +56,14 @@ function deferredStatus(): { return { promise, resolve } } +function cleanupGate(): { promise: Promise; resolve: () => void } { + let resolve = (): void => {} + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} + // Fresh modules per test: the shutdown flag and setup window are process-wide. async function loadModules(): Promise<{ permissions: typeof PermissionsModule @@ -67,9 +79,11 @@ describe('computer-use setup cancellation', () => { beforeEach(() => { vi.resetModules() - vi.useFakeTimers() + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) mocks.spawn.mockReset().mockReturnValue({ unref: () => {} }) mocks.spawnSync.mockReset() + mocks.runProcess.mockReset().mockResolvedValue({ exitCode: 0 }) + mocks.resetTcc.mockReset().mockResolvedValue({ ok: true }) mocks.peek.mockReset().mockResolvedValue(denied) mocks.readBundleId.mockReset().mockResolvedValue(null) Object.defineProperty(process, 'platform', { value: 'darwin' }) @@ -90,4 +104,151 @@ describe('computer-use setup cancellation', () => { await expect(open).rejects.toThrow('cancelled') expect(setupLaunches()).toEqual([]) }) + + it.each(['screenshots', 'accessibility'] as const)( + 'delivers the latest queued %s request after the active cleanup finishes', + async (latestPermission) => { + const cleanup = cleanupGate() + mocks.runProcess.mockImplementationOnce(() => cleanup.promise) + const { permissions } = await loadModules() + const first = permissions.openComputerUsePermissions('accessibility') + await settleTurn() + await permissions.openComputerUsePermissions('screenshots') + const queued = await permissions.openComputerUsePermissions(latestPermission) + expect(queued).toMatchObject({ + launchedHelper: true, + launchQueued: true, + openedSettings: false + }) + expect(setupLaunches()).toEqual([]) + cleanup.resolve() + await expect(first).resolves.toMatchObject({ + launchedHelper: true, + launchQueued: false, + openedSettings: true + }) + expect(setupLaunches()).toEqual([['--permission', 'accessibility']]) + await vi.advanceTimersByTimeAsync(5_000) + expect(setupLaunches()).toEqual( + latestPermission === 'screenshots' + ? [ + ['--permission', 'accessibility'], + ['--permission', 'screenshots'] + ] + : [['--permission', 'accessibility']] + ) + } + ) + + it('drains the complete old launch before reset and cancels older pending joiners', async () => { + const firstCleanup = cleanupGate() + const secondCleanup = cleanupGate() + const olderStatus = deferredStatus() + const events: string[] = [] + mocks.peek.mockImplementationOnce(() => olderStatus.promise) + mocks.runProcess + .mockImplementationOnce(async () => { + await firstCleanup.promise + events.push('old first closed') + }) + .mockImplementationOnce(async () => { + await secondCleanup.promise + events.push('old second closed') + }) + .mockImplementation(async () => { + events.push('cleanup closed') + }) + mocks.resetTcc.mockImplementation(async (service) => { + events.push(service) + return { ok: true } + }) + const { permissions } = await loadModules() + const older = permissions.openComputerUsePermissions('screenshots') + const current = permissions.openComputerUsePermissions('accessibility') + await settleTurn() + olderStatus.resolve() + await settleTurn() + const olderCancelled = expect(older).rejects.toThrow('cancelled') + const currentCancelled = expect(current).rejects.toThrow('cancelled') + const reset = permissions.resetComputerUsePermissions() + await settleTurn() + expect(events).toEqual([]) + firstCleanup.resolve() + await settleTurn() + expect(events).toEqual(['old first closed']) + expect(setupLaunches()).toEqual([]) + secondCleanup.resolve() + await Promise.all([olderCancelled, currentCancelled, reset]) + expect(events).toEqual([ + 'old first closed', + 'old second closed', + 'cleanup closed', + 'cleanup closed', + 'Accessibility', + 'ScreenCapture' + ]) + await expect(permissions.openComputerUsePermissions('screenshots')).resolves.toMatchObject({ + launchQueued: false + }) + expect(setupLaunches()).toEqual([['--permission', 'screenshots']]) + }) + + it('joins overlapping resets while cancelling an Open between the clicks', async () => { + const cleanup = cleanupGate() + const events: string[] = [] + mocks.runProcess + .mockImplementationOnce(async () => { + await cleanup.promise + events.push('reset first closed') + }) + .mockImplementation(async () => { + events.push('cleanup closed') + }) + mocks.resetTcc.mockImplementation(async (service) => { + events.push(service) + return { ok: true } + }) + const { permissions } = await loadModules() + const first = permissions.resetComputerUsePermissions() + const between = permissions.openComputerUsePermissions('accessibility') + const betweenCancelled = expect(between).rejects.toThrow('cancelled') + const second = permissions.resetComputerUsePermissions() + const after = permissions.openComputerUsePermissions('screenshots') + await settleTurn() + expect(setupLaunches()).toEqual([]) + cleanup.resolve() + await Promise.all([first, second, betweenCancelled, after]) + expect(events).toEqual([ + 'reset first closed', + 'cleanup closed', + 'Accessibility', + 'ScreenCapture', + 'cleanup closed', + 'cleanup closed' + ]) + expect(setupLaunches()).toEqual([['--permission', 'screenshots']]) + }) + + it('cancels a launch whose cleanup completes during shutdown', async () => { + const cleanup = cleanupGate() + mocks.runProcess.mockImplementationOnce(() => cleanup.promise) + const { permissions, markHostShuttingDown } = await loadModules() + const open = permissions.openComputerUsePermissions('accessibility') + await settleTurn() + markHostShuttingDown() + const cancelled = expect(open).rejects.toThrow('cancelled') + cleanup.resolve() + await cancelled + expect(setupLaunches()).toEqual([]) + }) + + it('still opens the helper when cleanup cannot start', async () => { + mocks.runProcess.mockRejectedValueOnce(new Error('spawn failed')) + const { permissions } = await loadModules() + await expect(permissions.openComputerUsePermissions('accessibility')).resolves.toMatchObject({ + launchedHelper: true, + launchQueued: false + }) + expect(setupLaunches()).toEqual([['--permission', 'accessibility']]) + }) }) diff --git a/src/main/computer/macos-permissions/macos-computer-use-permissions.ts b/src/main/computer/macos-permissions/macos-computer-use-permissions.ts index 861bbf7b773..4dbba0fdf65 100644 --- a/src/main/computer/macos-permissions/macos-computer-use-permissions.ts +++ b/src/main/computer/macos-permissions/macos-computer-use-permissions.ts @@ -1,4 +1,5 @@ -import { spawn, spawnSync } from 'node:child_process' +import { spawn } from 'node:child_process' +import { runProcess } from '@orca/process-host' import { RuntimeClientError } from '../runtime-client-error' import { isHostShuttingDown } from '../../startup/quit/host-shutdown-state' import { readMacosBundleId, resetMacosTccPermission } from '../../macos-permissions/macos-tcc-reset' @@ -18,6 +19,8 @@ const DEFAULT_COMPUTER_USE_BUNDLE_ID = 'com.stablyai.orca.computer-use' const SETUP_HELPER_LAUNCH_WINDOW_MS = 5_000 // Requests are numbered on arrival; a queued request loses to any later one (latest wins). type SetupLaunchRequest = { seq: number; helperAppPath: string; helperArgs: string[] } +type SetupLaunchOutcome = 'launched' | 'cancelled' +let setupLaunchInFlight: { seq: number; done: Promise } | null = null let setupRequestSeq = 0 let lastLaunch: { seq: number; coversSeq: number; argsKey: string; at: number } | null = null let queuedSetupLaunch: SetupLaunchRequest | null = null @@ -25,7 +28,7 @@ let queuedSetupTimer: ReturnType | null = null // Bumped by reset so Opens still waiting on status never launch afterwards. let setupGeneration = 0 // Opens that arrive mid-reset wait for it, so reset's helper cleanup can't kill what they open. -let resetInProgress: Promise | null = null +let resetInProgress: Promise | null = null /** `locale` comes from the desktop caller; orcad and CLI opens leave the helper on its default copy. */ export function openComputerUsePermissions( @@ -48,16 +51,18 @@ const setupWindowOpensAt = (): number => (lastLaunch?.at ?? Number.NEGATIVE_INFINITY) + SETUP_HELPER_LAUNCH_WINDOW_MS // Launches now, or queues for when the window reopens; a later request supersedes a queued one. -function requestSetupHelperLaunch( +async function requestSetupHelperLaunch( request: SetupLaunchRequest -): 'launched' | 'queued' | 'superseded' { +): Promise { // A newer request already spawned; showing this older one now would replace it. if (lastLaunch && request.seq <= lastLaunch.seq) { return 'superseded' } - if (performance.now() >= setupWindowOpensAt() && !queuedSetupLaunch) { - launchSetupHelper(request) - return 'launched' + if (setupLaunchInFlight && request.seq < setupLaunchInFlight.seq) { + return (await setupLaunchInFlight.done) === 'launched' ? 'superseded' : 'cancelled' + } + if (!setupLaunchInFlight && performance.now() >= setupWindowOpensAt() && !queuedSetupLaunch) { + return startSetupHelperLaunch(request) } if (!queuedSetupLaunch || request.seq > queuedSetupLaunch.seq) { queuedSetupLaunch = request @@ -67,7 +72,7 @@ function requestSetupHelperLaunch( } function armQueuedSetupTimer(): void { - if (queuedSetupTimer) { + if (queuedSetupTimer || setupLaunchInFlight || !queuedSetupLaunch) { return } queuedSetupTimer = setTimeout( @@ -88,11 +93,9 @@ function armQueuedSetupTimer(): void { (lastLaunch.argsKey === queued.helperArgs.join(' ') && queued.seq <= lastLaunch.coversSeq)) if (queued && !covered) { - try { - launchSetupHelper(queued) - } catch (error) { + void startSetupHelperLaunch(queued).catch((error) => { console.error('[computer-use] queued setup helper launch failed:', error) - } + }) } }, Math.max(0, Math.ceil(setupWindowOpensAt() - performance.now())) @@ -100,12 +103,36 @@ function armQueuedSetupTimer(): void { queuedSetupTimer.unref?.() } -function launchSetupHelper(request: SetupLaunchRequest): void { +function startSetupHelperLaunch(request: SetupLaunchRequest): Promise { + const generation = setupGeneration + // Publish the owner before cleanup can yield to another Open or Reset. + const launch = { + seq: request.seq, + done: Promise.resolve() + .then(() => launchSetupHelper(request, generation)) + .finally(() => { + if (setupLaunchInFlight === launch) { + setupLaunchInFlight = null + armQueuedSetupTimer() + } + }) + } + setupLaunchInFlight = launch + return launch.done +} + +async function launchSetupHelper( + request: SetupLaunchRequest, + generation: number +): Promise { if (isHostShuttingDown()) { - return + return 'cancelled' } // Kill and relaunch so a repeated click always brings the helper back to the front. - closeExistingPermissionHelpers() + await closeExistingPermissionHelpers() + if (generation !== setupGeneration || isHostShuttingDown()) { + return 'cancelled' + } const helper = spawn( '/usr/bin/open', ['-n', request.helperAppPath, '--args', ...request.helperArgs], @@ -119,6 +146,7 @@ function launchSetupHelper(request: SetupLaunchRequest): void { at: performance.now() } helper.unref() + return 'launched' } async function openComputerUsePermissionsAsync( @@ -179,7 +207,13 @@ async function openComputerUsePermissionsAsync( // Why: the helper renders permission copy in the app's UI language. helperArgs.push('--locale', locale) } - const launch = requestSetupHelperLaunch({ seq, helperAppPath, helperArgs }) + const launch = await requestSetupHelperLaunch({ seq, helperAppPath, helperArgs }) + if (launch === 'cancelled') { + throw new RuntimeClientError( + 'accessibility_error', + 'Computer Use setup was cancelled because permissions were reset or Orca is quitting' + ) + } return { platform: process.platform, @@ -195,6 +229,11 @@ async function openComputerUsePermissionsAsync( } export function resetComputerUsePermissions(): Promise { + // Every click cancels older Opens, including when joining an active reset. + cancelPendingSetupLaunches() + if (resetInProgress) { + return resetInProgress + } const reset = resetComputerUsePermissionsAsync().finally(() => { if (resetInProgress === reset) { resetInProgress = null @@ -205,8 +244,6 @@ export function resetComputerUsePermissions(): Promise { - // Before any await, so a queued or preflighting Open can't slip a helper in during the reset. - cancelPendingSetupLaunches() if (process.platform !== 'darwin') { return { platform: process.platform, @@ -231,7 +268,8 @@ async function resetComputerUsePermissionsAsync(): Promise {}) + await closeExistingPermissionHelpers() try { await resetTccPermission('Accessibility', bundleId) await resetTccPermission('ScreenCapture', bundleId) @@ -246,16 +284,20 @@ async function resetComputerUsePermissionsAsync(): Promise { // Preserve concurrent status probes when replacing permission-setup helpers. const setupHelperPatterns = [ 'orca-computer-use-macos[[:space:]]+--permission([[:space:]]|$)', 'orca-computer-use-macos[[:space:]]+--permissions([[:space:]]|$)' ] for (const pattern of setupHelperPatterns) { - spawnSync('/usr/bin/pkill', ['-f', pattern], { + // Only actual completion permits a later launch; a timeout can settle before child exit. + await runProcess({ + program: '/usr/bin/pkill', + args: ['-f', pattern], + timeoutMs: null, stdio: 'ignore' - }) + }).catch(() => undefined) } } diff --git a/src/main/connector-cloud/connector-places.ts b/src/main/connector-cloud/connector-places.ts index 3c184f8f874..155f63b129a 100644 --- a/src/main/connector-cloud/connector-places.ts +++ b/src/main/connector-cloud/connector-places.ts @@ -14,7 +14,7 @@ import { import { splitGitRemoteKey } from '../../shared/git/remotes/git-remote-identity' import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' import { isFolderRepo } from '../../shared/repo-kind' -import type { AgentLaunchParams } from '../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../shared/rpc-contract/agent-launch/agent-launch-params' import { parseWslUncPath } from '../../shared/wsl-paths' import { readAllWorktreeMetaForHost } from '../persistence/host-qualified-worktree-meta' import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' diff --git a/src/main/copilot/copilot-acp-launch-spec.ts b/src/main/copilot/copilot-acp-launch-spec.ts index 58526ad2795..668310ec331 100644 --- a/src/main/copilot/copilot-acp-launch-spec.ts +++ b/src/main/copilot/copilot-acp-launch-spec.ts @@ -7,7 +7,7 @@ import { resumeInvocationFromOptions, sessionFileResumeTargetMatches, type StructuredAgentSessionHistory -} from '../native-chat/structured-agent-cli-conversations' +} from '../native-chat/conversation-adoption/structured-agent-cli-conversations' // Chats and terminals share Copilot's session store; `--resume` also takes ID prefixes. const COPILOT_SESSION_HISTORY: StructuredAgentSessionHistory = { diff --git a/src/main/crash-reporting/process-exits/process-gone-diagnostics.ts b/src/main/crash-reporting/process-exits/process-gone-diagnostics.ts index 34e4be0e3e8..ecc8cbc81d6 100644 --- a/src/main/crash-reporting/process-exits/process-gone-diagnostics.ts +++ b/src/main/crash-reporting/process-exits/process-gone-diagnostics.ts @@ -2,7 +2,10 @@ import { app } from 'electron' import { sanitizeCrashReportDetails } from '../../../shared/crash-report-redaction' import type { CrashReportDetailValue } from '../../../shared/crash-reporting' import { getSystemMemoryDetails, memoryKBFieldMB } from '../memory/system-memory-details' -import { getStartupRtPrioOutcome, readZeroRtTimeLimit } from '../../startup/linux-rttime-limit' +import { + getStartupRtPrioOutcome, + readZeroRtTimeLimit +} from '../../startup/linux-runtime/linux-rttime-limit' import { PRE_GONE_SYSTEM_MEMORY_SAMPLE_INTERVAL_MS, preGoneSystemMemoryDetails, diff --git a/src/main/credentials/integration-state-file-cache.test.ts b/src/main/credentials/integration-state-file-cache.test.ts index 92673a31041..a2bb7cee926 100644 --- a/src/main/credentials/integration-state-file-cache.test.ts +++ b/src/main/credentials/integration-state-file-cache.test.ts @@ -28,23 +28,6 @@ afterEach(() => { }) describe('createIntegrationStateFileCache', () => { - it('memoizes while the file is unchanged', () => { - const path = tempFile() - writeFileSync(path, '1') - let reads = 0 - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => { - reads += 1 - return { reads } - } - }) - - expect(cache.get()).toEqual({ reads: 1 }) - expect(cache.get()).toEqual({ reads: 1 }) - expect(reads).toBe(1) - }) - it('notices a same-size atomic replacement with the original modification time', () => { const path = tempFile() writeFileSync(path, 'old') @@ -63,18 +46,6 @@ describe('createIntegrationStateFileCache', () => { expect(cache.get()).toBe('new') }) - it('distinguishes backing paths when both files are initially absent', () => { - let path = tempFile() - let reads = 0 - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => ++reads - }) - expect(cache.get()).toBe(1) - path = join(dir, 'another.json') - expect(cache.get()).toBe(2) - }) - it('reloads when a file appears after an absent first read', () => { const path = tempFile() const cache = createIntegrationStateFileCache({ @@ -101,37 +72,6 @@ describe('createIntegrationStateFileCache', () => { expect(cache.get()).toEqual({ present: false }) }) - - it('recovers when another process writes between the stamp and the read', () => { - const path = tempFile() - writeFileSync(path, 'v1') - let reads = 0 - let writeDuringRead = false - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => { - reads += 1 - if (writeDuringRead) { - writeDuringRead = false - writeFileSync(path, 'theirs') - } - return { body: readBody(path) } - } - }) - expect(cache.get()).toEqual({ body: 'v1' }) - - writeFileSync(path, 'ours') - cache.invalidate() - writeDuringRead = true - - // Content read after a concurrent write still carries the earlier stamp, forcing one more read. - expect(cache.get()).toEqual({ body: 'theirs' }) - expect(cache.get()).toEqual({ body: 'theirs' }) - expect(reads).toBe(3) - - expect(cache.get()).toEqual({ body: 'theirs' }) - expect(reads).toBe(3) - }) }) function readBody(path: string): string { diff --git a/src/main/credentials/integration-token-file-cache.test.ts b/src/main/credentials/integration-token-file-cache.test.ts index 3707dcae02b..143b6b03b26 100644 --- a/src/main/credentials/integration-token-file-cache.test.ts +++ b/src/main/credentials/integration-token-file-cache.test.ts @@ -29,50 +29,6 @@ function createCache() { } describe('integration token file cache', () => { - it('bounds decrypted credentials at 128 entries', () => { - const cache = createCache() - for (let index = 0; index < 132; index += 1) { - const id = `credential-${index}` - writeFileSync(filePath(id), `token-${index}`) - expect(cache.read(id)).toBe(`token-${index}`) - } - expect(cache.read('credential-131', false)).toBe('token-131') - expect(cache.read('credential-0', false)).toBeNull() - expect(decrypt).toHaveBeenCalledTimes(132) - }) - - it('keeps recently used credentials when the bound evicts the oldest entry', () => { - const cache = createCache() - for (let index = 0; index < 128; index += 1) { - writeFileSync(filePath(String(index)), `token-${index}`) - cache.read(String(index)) - } - expect(cache.read('0', false)).toBe('token-0') - writeFileSync(filePath('next'), 'token-next') - cache.read('next') - expect(cache.read('0', false)).toBe('token-0') - expect(cache.read('1', false)).toBeNull() - }) - - it('bounds errors, keeps status lazy, and permits retry after keychain approval', () => { - const cache = createCache() - decrypt.mockImplementation(() => { - throw new Error('Keychain access denied') - }) - for (let index = 0; index < 132; index += 1) { - const id = `credential-${index}` - writeFileSync(filePath(id), Buffer.from([0x76, 0x31, 0x30, 0xff, 0xfe])) - expect(() => cache.read(id)).toThrow('Could not decrypt') - } - expect(cache.error('credential-131')).toContain('Could not decrypt') - expect(cache.error('credential-0')).toBeUndefined() - expect(cache.has('credential-131')).toBe(true) - expect(decrypt).toHaveBeenCalledTimes(132) - decrypt.mockReturnValue('approved-token') - expect(cache.read('credential-131')).toBe('approved-token') - expect(cache.error('credential-131')).toBeUndefined() - }) - it('clears an old decryption error after external replacement without prompting on status', () => { const cache = createCache() writeFileSync(filePath('site'), Buffer.from([0xff, 0xfe])) diff --git a/src/main/credentials/protected-secret-persistence-concurrency.test.ts b/src/main/credentials/protected-secret-persistence-concurrency.test.ts index 5696287957f..c905b84c8a5 100644 --- a/src/main/credentials/protected-secret-persistence-concurrency.test.ts +++ b/src/main/credentials/protected-secret-persistence-concurrency.test.ts @@ -153,18 +153,6 @@ describe('protected secret acknowledgements', () => { expect(secrets.encrypt('remove', 'replacement').blob).toBe('') }) - it('does not accept a prepared update from a replaced persistence instance', () => { - const previous = new ProtectedSecretPersistence() - const current = new ProtectedSecretPersistence() - const older = prepare(previous, 'slot', 'older') - const newer = prepare(current, 'slot', 'newer') - - current.commitRetentionUpdates([older, newer]) - - cipherState.available = false - expect(current.encrypt('slot', 'replacement').blob).toBe(ciphertext('newer')) - }) - it('keeps the previous ciphertext and pending retry when a prepared save has no confirmed ack', () => { const secrets = new ProtectedSecretPersistence() const original = ciphertext('original') diff --git a/src/main/credentials/protected-secret-persistence.test.ts b/src/main/credentials/protected-secret-persistence.test.ts index a0fa87fccc7..81fea025bb6 100644 --- a/src/main/credentials/protected-secret-persistence.test.ts +++ b/src/main/credentials/protected-secret-persistence.test.ts @@ -44,34 +44,4 @@ describe('ProtectedSecretPersistence', () => { secrets.removeRetainedBlob(slot) expect(secrets.encrypt(slot, '')).toEqual({ blob: '', degraded: false }) }) - - it('keeps deferred encryption pending until its retention update commits', async () => { - const { ProtectedSecretPersistence } = await import('./protected-secret-persistence') - const secrets = new ProtectedSecretPersistence() - cipherState.available = false - secrets.encrypt('slot', 'pending') - expect(secrets.hasPendingEncryption()).toBe(true) - cipherState.available = true - const encrypted = secrets.encrypt('slot', 'pending') - expect(secrets.hasPendingEncryption()).toBe(true) - if (!encrypted.retentionUpdate) { - throw new Error('Expected a retention update') - } - secrets.commitRetentionUpdates([encrypted.retentionUpdate]) - expect(secrets.hasPendingEncryption()).toBe(false) - }) - - it('retires a deferred empty secret without retaining a phantom retry', async () => { - const { ProtectedSecretPersistence } = await import('./protected-secret-persistence') - const secrets = new ProtectedSecretPersistence() - cipherState.available = false - secrets.encrypt('slot', 'pending') - const cleared = secrets.encrypt('slot', '') - expect(secrets.hasPendingEncryption()).toBe(true) - if (!cleared.retentionUpdate) { - throw new Error('Expected a retention update') - } - secrets.commitRetentionUpdates([cleared.retentionUpdate]) - expect(secrets.hasPendingEncryption()).toBe(false) - }) }) diff --git a/src/main/credentials/saved-credential-readability.test.ts b/src/main/credentials/saved-credential-readability.test.ts index 6f5d23b6426..c4607cf8279 100644 --- a/src/main/credentials/saved-credential-readability.test.ts +++ b/src/main/credentials/saved-credential-readability.test.ts @@ -49,8 +49,7 @@ describe('savedCredentialUnreadable', () => { it.each([ ['an empty', ''], - ['a non-base64', 'not*base64!'], - ['a truncated base64', 'c2VhbGVkLWhlcmU6a2V5x'] + ['a non-base64', 'not*base64!'] ])('reports %s payload as unreadable, not sealed elsewhere', (_label, payload) => { expect(judge(`${PREFIX}encrypted:${payload}`)).toBe('unreadable') }) diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index 4c7d677d9a5..7fcbbd801d3 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -15,7 +15,7 @@ import { import { prepareMacosTccLoginShell, probeMacosLoginSessionAlive -} from '../providers/macos-tcc-login-shell' +} from '../providers/shell-launch/macos/tcc-login-shell' import { MacosLoginSessionDeathWatch } from './process-scopes/macos-login-session-death-watch' import { readCurrentProcessMacSystemResolverHealth } from '../network/macos-system-resolver-health' import { readCurrentDaemonReadyIdentity } from './endpoint/identity/daemon-ready-identity' diff --git a/src/main/daemon/endpoint/identity/daemon-pid-identity.ts b/src/main/daemon/endpoint/identity/daemon-pid-identity.ts index 3971d45ebaa..351348800b4 100644 --- a/src/main/daemon/endpoint/identity/daemon-pid-identity.ts +++ b/src/main/daemon/endpoint/identity/daemon-pid-identity.ts @@ -12,7 +12,7 @@ import { PROTOCOL_VERSION } from '../../protocol/daemon-protocol-version' import { isStartupDiagnosticsEnabled, logStartupDiagnostic -} from '../../../startup/startup-diagnostics' +} from '../../../startup/diagnostics/startup-diagnostics' // Windows OS creation precedes Node self-report; allow bootstrap delays from antivirus or disk pressure. const WIN32_START_TIME_TOLERANCE_MS = 10_000 diff --git a/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts b/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts index 531d87a36c0..39b1edb7820 100644 --- a/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts +++ b/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts @@ -32,13 +32,13 @@ import { import { buildDaemonSessionClient, type DaemonSessionClientResult -} from '../../../../orcad/orcad-daemon-session-client-fixture' +} from '../../../../orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' import { killAndAwaitExit, killProfileDaemons, removeTestRoot -} from '../../../../orcad/orcad-daemon-teardown-fixture' -import { locatePinnedNodeForTests } from '../../../../orcad/orcad-node-slot-fixture' +} from '../../../../orcad/testing/daemon-processes/orcad-daemon-teardown-fixture' +import { locatePinnedNodeForTests } from '../../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { resolveAppImageExtractedRoot } from '../../../../cli/appimage/appimage-extracted-root' const ENTRY_IN_APPDIR = 'resources/app.asar.unpacked/out/main/daemon-entry.js' diff --git a/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts b/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts index f9894a6f453..3fc87599c4b 100644 --- a/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts +++ b/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts @@ -6,7 +6,7 @@ import { LOCAL_BUILD_COMPATIBILITY_CONTRACT } from '../../../../shared/local-bui import { NODE_RUNTIME_DARWIN_MINIMUM_OS } from '../../../../shared/node-runtime-pin' import { runProcess } from '@orca/process-host' import { rm } from '../../../filesystem/asar-transparent-fs' -import { compareDottedVersions } from '../../../orcad/native-host-abi' +import { compareDottedVersions } from '../../../orcad/native-runtime/native-host-abi' import { DaemonClient } from '../../transport/client/daemon-client' import { DaemonEndpointOwnershipError, diff --git a/src/main/daemon/launch/daemon-out-of-process-launcher.ts b/src/main/daemon/launch/daemon-out-of-process-launcher.ts index d5ca5ad7bde..790da15cc41 100644 --- a/src/main/daemon/launch/daemon-out-of-process-launcher.ts +++ b/src/main/daemon/launch/daemon-out-of-process-launcher.ts @@ -8,7 +8,7 @@ import { holdDaemonAdoptionLease, reconcileDaemonPidOwnership } from './daemon-endpoint-adoption' -import { LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS } from '../../startup/first-window-startup-services' +import { LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS } from '../../startup/pty-startup/first-window-startup-services' import { DAEMON_CHILD_STARTUP_TIMEOUT_MS, DaemonEndpointUnavailableError, diff --git a/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts b/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts index 7e5d0276f9c..dc98a7c545e 100644 --- a/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts +++ b/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts @@ -18,13 +18,13 @@ import { import { buildDaemonSessionClient, type DaemonSessionClientResult -} from '../../../orcad/orcad-daemon-session-client-fixture' +} from '../../../orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' import { killAndAwaitExit, killProfileDaemons, removeTestRoot -} from '../../../orcad/orcad-daemon-teardown-fixture' -import { locatePinnedNodeForTests } from '../../../orcad/orcad-node-slot-fixture' +} from '../../../orcad/testing/daemon-processes/orcad-daemon-teardown-fixture' +import { locatePinnedNodeForTests } from '../../../orcad/testing/native-slots/orcad-node-slot-fixture' type Runtime = 'electron' | 'node' diff --git a/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts b/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts index 9a065fc8f78..47f46bc8a55 100644 --- a/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts +++ b/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts @@ -6,7 +6,7 @@ import { dirname, join } from 'node:path' import { spawnProcess } from '@orca/process-host' import { readDaemonPidRecord } from '../../endpoint/identity/daemon-endpoint-incarnation' import { getDaemonPidPath } from '../daemon-spawner' -import { killChildAndWait } from '../../../orcad/orcad-daemon-teardown-fixture' +import { killChildAndWait } from '../../../orcad/testing/daemon-processes/orcad-daemon-teardown-fixture' export type DaemonLauncherDriverResult = { adopted: boolean; mode: string | null } diff --git a/src/main/daemon/process-scopes/daemon-rttime-limit.ts b/src/main/daemon/process-scopes/daemon-rttime-limit.ts index 091c513b866..c45684068f0 100644 --- a/src/main/daemon/process-scopes/daemon-rttime-limit.ts +++ b/src/main/daemon/process-scopes/daemon-rttime-limit.ts @@ -1,4 +1,4 @@ -import { readZeroRtTimeLimit } from '../../startup/linux-rttime-limit' +import { readZeroRtTimeLimit } from '../../startup/linux-runtime/linux-rttime-limit' // Why: PTYs inherit the daemon's RLIMIT_RTTIME, so a zero limit can kill terminal jobs. export function warnWhenRealtimeTimeoutIsZero( diff --git a/src/main/daemon/process-scopes/macos-login-session-death-watch.ts b/src/main/daemon/process-scopes/macos-login-session-death-watch.ts index 6354e3c7e15..46542d991ee 100644 --- a/src/main/daemon/process-scopes/macos-login-session-death-watch.ts +++ b/src/main/daemon/process-scopes/macos-login-session-death-watch.ts @@ -1,4 +1,4 @@ -import type { LoginPreflightOutcome } from '../../providers/macos-tcc-login-shell' +import type { LoginPreflightOutcome } from '../../providers/shell-launch/macos/login-session-pty-probe' import type { DaemonFileLog } from '../observability/daemon-file-log' import { createLoginSessionWatchClock, diff --git a/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts b/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts deleted file mode 100644 index 7726e9927dd..00000000000 --- a/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { LoginPreflightOutcome } from '../../../providers/macos-tcc-login-shell' -import { createNoopDaemonFileLog } from '../../observability/daemon-file-log' -import { - MacosLoginSessionDeathWatch, - type MacosLoginSessionDeathWatchOptions -} from '../macos-login-session-death-watch' -import type { SystemResolverHealth } from '../../protocol/daemon-rpc-contract' - -const ACCEPTED: LoginPreflightOutcome = { ok: true, conclusive: true, reason: 'accepted' } -const REJECTED: LoginPreflightOutcome = { ok: false, conclusive: true, reason: 'rejected' } - -type FakeTimer = { at: number; callback: () => void; cleared: boolean } - -class FakeClock { - private timers: FakeTimer[] = [] - private nowMs = 0 - - setTimeout = (callback: () => void, delayMs: number): unknown => { - const timer: FakeTimer = { at: this.nowMs + delayMs, callback, cleared: false } - this.timers.push(timer) - return timer - } - - clearTimeout = (handle: unknown): void => { - ;(handle as FakeTimer).cleared = true - } - - now = (): number => this.nowMs - - async advance(ms: number): Promise { - const target = this.nowMs + ms - for (;;) { - const due = this.timers - .filter((t) => !t.cleared && t.at <= target) - .sort((a, b) => a.at - b.at)[0] - if (!due) { - break - } - this.nowMs = Math.max(this.nowMs, due.at) - due.cleared = true - due.callback() - // Settle async probes before advancing to the next timer. - await drainMicrotasks() - } - this.nowMs = target - } - - suspend(ms: number): void { - this.nowMs += ms - } - - pendingCount(): number { - return this.timers.filter((t) => !t.cleared).length - } -} - -async function drainMicrotasks(): Promise { - for (let i = 0; i < 10; i++) { - await Promise.resolve() - } -} - -function createWatch( - overrides: Partial & { - outcomes?: (LoginPreflightOutcome | null)[] - } = {} -): { - watch: MacosLoginSessionDeathWatch - clock: FakeClock - onRetire: ReturnType - probe: ReturnType - setResolverHealth: (health: SystemResolverHealth) => void -} { - const clock = new FakeClock() - const onRetire = vi.fn() - const outcomes = overrides.outcomes ?? [] - // Preserve explicit null outcomes that disable the watch. - const probe = vi.fn(async () => (outcomes.length ? outcomes.shift()! : ACCEPTED)) - let resolverHealth: SystemResolverHealth = 'unhealthy' - const watch = new MacosLoginSessionDeathWatch({ - probeLoginSession: overrides.probeLoginSession ?? probe, - readResolverHealth: overrides.readResolverHealth ?? (async () => resolverHealth), - onRetire: overrides.onRetire ?? onRetire, - log: overrides.log ?? createNoopDaemonFileLog(), - clock, - timing: { - periodicProbeMs: 120_000, - rejectionRecheckMs: 10_000, - minimumRejectionSpanMs: 120_000, - ptyExitDebounceMs: 2_000, - clientActivityMinGapMs: 30_000, - minProbeGapMs: 5_000, - ...overrides.timing - } - }) - return { - watch, - clock, - onRetire, - probe, - setResolverHealth: (health) => { - resolverHealth = health - } - } -} - -describe('MacosLoginSessionDeathWatch', () => { - it('preserves the daemon when a short PAM rejection burst recovers after wake', async () => { - const { watch, clock, onRetire, probe } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, ACCEPTED] - }) - watch.start() - await drainMicrotasks() - - await clock.advance(120_000) - await clock.advance(10_000) - await clock.advance(10_000) - - expect(probe).toHaveBeenCalledTimes(4) - expect(onRetire).not.toHaveBeenCalled() - - watch.notifyClientActivity() - watch.notifyPtyExit() - await clock.advance(99_999) - expect(probe).toHaveBeenCalledTimes(4) - await clock.advance(1) - expect(probe).toHaveBeenCalledTimes(5) - expect(onRetire).not.toHaveBeenCalled() - }) - - it('does not count a suspended timer gap as rejection evidence', async () => { - const { watch, clock, onRetire, probe } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, ACCEPTED] - }) - watch.start() - await drainMicrotasks() - - await clock.advance(120_000) - clock.suspend(60 * 60 * 1000) - await clock.advance(0) - - expect(probe).toHaveBeenCalledTimes(3) - expect(onRetire).not.toHaveBeenCalled() - - await clock.advance(119_999) - expect(probe).toHaveBeenCalledTimes(3) - await clock.advance(1) - expect(probe).toHaveBeenCalledTimes(4) - expect(onRetire).not.toHaveBeenCalled() - }) - - it('does not count suspension during an in-flight probe as rejection evidence', async () => { - let resolveProbe!: (outcome: LoginPreflightOutcome) => void - const deferredProbe = new Promise((resolve) => { - resolveProbe = resolve - }) - const probe = vi - .fn() - .mockResolvedValueOnce(ACCEPTED) - .mockResolvedValueOnce(REJECTED) - .mockReturnValueOnce(deferredProbe) - .mockResolvedValueOnce(ACCEPTED) - const { watch, clock, onRetire } = createWatch({ probeLoginSession: probe }) - watch.start() - await drainMicrotasks() - - await clock.advance(120_000) - await clock.advance(10_000) - clock.suspend(60 * 60 * 1000) - resolveProbe(REJECTED) - await drainMicrotasks() - - expect(probe).toHaveBeenCalledTimes(3) - expect(onRetire).not.toHaveBeenCalled() - - await clock.advance(119_999) - expect(probe).toHaveBeenCalledTimes(3) - await clock.advance(1) - expect(probe).toHaveBeenCalledTimes(4) - expect(onRetire).not.toHaveBeenCalled() - }) - - it('never retires when the session was never conclusively accepted', async () => { - const { watch, clock, onRetire } = createWatch({ - outcomes: [REJECTED, REJECTED, REJECTED, REJECTED, REJECTED] - }) - watch.start() - await drainMicrotasks() - for (let i = 0; i < 4; i++) { - await clock.advance(120_000) - } - expect(onRetire).not.toHaveBeenCalled() - }) - - it('retires a logged-out session three rejections and two minutes after the first one', async () => { - const { watch, clock, onRetire } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED] - }) - watch.start() - await drainMicrotasks() - await clock.advance(239_999) - expect(onRetire).not.toHaveBeenCalled() - await clock.advance(1) - expect(onRetire).toHaveBeenCalledTimes(1) - }) - - it('does not retire when DNS recovers before the retirement check', async () => { - const { watch, clock, onRetire, setResolverHealth } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED] - }) - watch.start() - await drainMicrotasks() - await clock.advance(140_000) - setResolverHealth('healthy') - await clock.advance(100_000) - expect(onRetire).not.toHaveBeenCalled() - }) - - it.each(['healthy', 'unknown'] as const)( - 'runs no login probe after arming while resolver health is %s', - async (resolverHealth) => { - const { watch, clock, probe, setResolverHealth } = createWatch() - setResolverHealth(resolverHealth) - watch.start() - await drainMicrotasks() - for (let i = 0; i < 5; i++) { - await clock.advance(120_000) - } - watch.notifyClientActivity() - watch.notifyPtyExit() - await clock.advance(10_000) - expect(probe).toHaveBeenCalledTimes(1) - } - ) - - it('keeps running the login probe after a rejection until PAM accepts again, even across sleep', async () => { - const { watch, clock, probe, setResolverHealth } = createWatch({ - outcomes: [ACCEPTED, REJECTED, ACCEPTED] - }) - watch.start() - await drainMicrotasks() - await clock.advance(120_000) - expect(probe).toHaveBeenCalledTimes(2) - - setResolverHealth('healthy') - clock.suspend(60 * 60 * 1000) - await clock.advance(0) // The sleep gap resets the rejection streak, not the rejected verdict. - expect(probe).toHaveBeenCalledTimes(3) - }) - - it('stop() prevents an in-flight resolver check from retiring the daemon', async () => { - let resolveHealth!: (health: SystemResolverHealth) => void - let resolverSignal: AbortSignal | undefined - const resolverHealth = new Promise((resolve) => { - resolveHealth = resolve - }) - const { watch, clock, onRetire } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED], - // The first read is the pre-probe gate; hold only the retirement read. - readResolverHealth: vi - .fn() - .mockResolvedValueOnce('unhealthy') - .mockImplementationOnce((signal) => { - resolverSignal = signal - return resolverHealth - }) - }) - watch.start() - await drainMicrotasks() - await clock.advance(120_000) - await clock.advance(10_000) - await clock.advance(10_000) - await clock.advance(100_000) // Retirement is waiting on the resolver result. - - watch.stop() - expect(resolverSignal?.aborted).toBe(true) - resolveHealth('unhealthy') - await drainMicrotasks() - - expect(onRetire).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/daemon/providers/adapter/daemon-pty-adapter.ts b/src/main/daemon/providers/adapter/daemon-pty-adapter.ts index 3512c3e1298..45f95d42b42 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-adapter.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-adapter.ts @@ -17,7 +17,7 @@ import type { DaemonPtyAdapterOptions } from './daemon-pty-adapter-options' import type { DaemonEvent } from '../../protocol/daemon-stream-events' import type { DaemonEndpointIdentity } from '../../protocol/daemon-hello-protocol' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { DeveloperPermissionStatus } from '../../../../shared/developer-permissions-types' import { AUTOMATIC_WORK_RESUME_UNSUPPORTED, diff --git a/src/main/daemon/providers/adapter/daemon-pty-daemon-recovery.ts b/src/main/daemon/providers/adapter/daemon-pty-daemon-recovery.ts index cbf0a76bcbb..b78e627f11c 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-daemon-recovery.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-daemon-recovery.ts @@ -10,7 +10,7 @@ import { import { DaemonPtyCheckpointPersistence } from '../checkpointing/daemon-pty-checkpoint-persistence' import type { DaemonRespawnReason } from './daemon-pty-adapter-options' import type { ListSessionsResult } from '../../protocol/daemon-rpc-contract' -import type { PtyBackgroundStreamEvent } from '../../../providers/pty-provider-contract' +import type { PtyBackgroundStreamEvent } from '../../../providers/pty/events' import type { TerminalLimitStatus, TerminalLimitUpdate diff --git a/src/main/daemon/providers/adapter/daemon-pty-event-subscriptions.ts b/src/main/daemon/providers/adapter/daemon-pty-event-subscriptions.ts index ed6c80aa49b..5f2d544c7db 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-event-subscriptions.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-event-subscriptions.ts @@ -6,7 +6,7 @@ import { DaemonPtySessionInventory } from './daemon-pty-session-inventory' import { CLEAN_DISCONNECT_PROTOCOL_VERSION } from '../../protocol/daemon-protocol-version' import type { ListSessionsResult, ShutdownIfIdleResult } from '../../protocol/daemon-rpc-contract' import type { DaemonIdleRetirementResult } from './daemon-pty-runtime-state' -import type { PtyBackgroundStreamEvent } from '../../../providers/pty-provider-contract' +import type { PtyBackgroundStreamEvent } from '../../../providers/pty/events' import { readDaemonWslQuitCwds } from '../wsl/daemon-wsl-sleep-cwd' export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInventory { diff --git a/src/main/daemon/providers/adapter/daemon-pty-process-inspection.ts b/src/main/daemon/providers/adapter/daemon-pty-process-inspection.ts index fa6bce3f717..0084116baec 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-process-inspection.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-process-inspection.ts @@ -10,7 +10,7 @@ import { parsePtySessionId } from '../../../../shared/terminal/pty/lifecycle/pty import type { ListSessionsResult } from '../../protocol/daemon-rpc-contract' import type { SessionInfo } from '../../protocol/daemon-session-info' -import type { PtyProcessInspectionOptions } from '../../../providers/pty-process-inspection' +import type { PtyProcessInspectionOptions } from '../../../providers/pty/process-inspection' import { type TerminalProcessInspection as PtyProcessInspection, diff --git a/src/main/daemon/providers/adapter/daemon-pty-provider-sequence.ts b/src/main/daemon/providers/adapter/daemon-pty-provider-sequence.ts index 3b36c057699..9393d04567c 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-provider-sequence.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-provider-sequence.ts @@ -1,5 +1,5 @@ import type { DaemonCreateOrAttachResult as CreateOrAttachResult } from '../../protocol/daemon-create-or-attach-result' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' export function providerSequenceFromCreateOrAttach( result: CreateOrAttachResult diff --git a/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts b/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts index b6df8de284a..69473513fb2 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts @@ -33,7 +33,7 @@ import { HistoryManager } from '../../history/storage/history-manager' import type { HistoryCheckpointResult } from '../../history/storage/terminal-history-manager-options' import type { HistoryRecoveryFreeze } from '../../history/storage/terminal-history-recovery-quarantine' import { HistoryReader } from '../../history/restoration/history-reader' -import type { PtyBackgroundStreamEvent } from '../../../providers/pty-provider-contract' +import type { PtyBackgroundStreamEvent } from '../../../providers/pty/events' import type { DaemonPtyRouterDataEvent, DaemonPtyRouterExitEvent diff --git a/src/main/daemon/providers/adapter/daemon-pty-session-control.ts b/src/main/daemon/providers/adapter/daemon-pty-session-control.ts index 4c006dd6fa9..b9e3f120c6e 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-session-control.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-session-control.ts @@ -15,8 +15,8 @@ import { logSleepFolderRead, readDaemonWslSleepCwdWithFacts } from '../wsl/daemo import * as unlistedSession from '../routing/daemon-unlisted-session' import { SessionNotFoundError } from '../../protocol/daemon-errors' import type { ListSessionsResult } from '../../protocol/daemon-rpc-contract' -import { resolveSafePtyDefaultCwd } from '../../../providers/pty-default-cwd' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import { resolveSafePtyDefaultCwd } from '../../../providers/working-directory/default-cwd' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' export const LIVENESS_PROBE_TIMEOUT_MS = 2_000 diff --git a/src/main/daemon/providers/adapter/daemon-pty-session-input.ts b/src/main/daemon/providers/adapter/daemon-pty-session-input.ts index 53ce72ee954..c63d5fadd7a 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-session-input.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-session-input.ts @@ -1,5 +1,5 @@ import { DaemonPtySessionSpawn } from './daemon-pty-session-spawn' -import { PtyWriteUnavailableError } from '../../../providers/pty-write-unavailable-error' +import { PtyWriteUnavailableError } from '../../../providers/pty/write-unavailable-error' import { writeRefused, type WriteSettlement diff --git a/src/main/daemon/providers/adapter/daemon-pty-session-inventory.ts b/src/main/daemon/providers/adapter/daemon-pty-session-inventory.ts index f053d3eb482..523064ccd99 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-session-inventory.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-session-inventory.ts @@ -14,8 +14,8 @@ import { remainingDaemonRequestTimeoutMs } from '../../launch/daemon-request-dea import { parsePtySessionId } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' import type { ListSessionsResult } from '../../protocol/daemon-rpc-contract' import type { SessionInfo } from '../../protocol/daemon-session-info' -import { PtyProcessListAdmission } from '../../../providers/pty-process-list-admission' -import type { PtyProcessInfo } from '../../../providers/pty-provider-contract' +import { PtyProcessListAdmission } from '../../../providers/pty/process-list-admission' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' export abstract class DaemonPtySessionInventory extends DaemonPtyProcessInspection { async listProcesses(opts?: { diff --git a/src/main/daemon/providers/adapter/daemon-pty-session-spawn.ts b/src/main/daemon/providers/adapter/daemon-pty-session-spawn.ts index a84a415ce52..0e9b694df57 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-session-spawn.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-session-spawn.ts @@ -22,10 +22,11 @@ import { getRecoveredHistorySeedSegments } from '../../history/seed-transfer/ter import type { DaemonCreateOrAttachResult as CreateOrAttachResult } from '../../protocol/daemon-create-or-attach-result' import { normalizeWslColdRestoreCwd } from '../wsl/wsl-cold-restore-cwd' import { resolveWslSessionContext } from '../../pty-subprocess/wsl-session-context' -import { resolveSafePtyDefaultCwd } from '../../../providers/pty-default-cwd' +import { resolveSafePtyDefaultCwd } from '../../../providers/working-directory/default-cwd' import { probeRecoveredStartupCwdDirectory } from '../../../ipc/pty/host-env/startup-cwd-directory-exists' import { resolveUnixShellPath } from '../../../providers/local-pty/local-pty-executable-spawn' -import type { PtySpawnOptions, PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { injectHistoryEnv, injectWslFishHistoryEnv, diff --git a/src/main/daemon/providers/adapter/daemon-pty-spawn-request.ts b/src/main/daemon/providers/adapter/daemon-pty-spawn-request.ts index a163067aabd..17767fce783 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-spawn-request.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-spawn-request.ts @@ -18,9 +18,10 @@ import { } from '../../history/seed-transfer/terminal-history-seed-chunks' import type { DaemonCreateOrAttachResult as CreateOrAttachResult } from '../../protocol/daemon-create-or-attach-result' import type { GetSnapshotResult } from '../../protocol/daemon-rpc-contract' -import type { PtySpawnOptions, PtySpawnResult } from '../../../providers/pty-provider-contract' -import { resolveSafePtyDefaultCwd } from '../../../providers/pty-default-cwd' -import { isMissingWorkingDirectoryError } from '../../../providers/working-directory-validation' +import type { PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' +import { resolveSafePtyDefaultCwd } from '../../../providers/working-directory/default-cwd' +import { isMissingWorkingDirectoryError } from '../../../providers/working-directory/validation' /** A daemon kept running across an update trusts `interactive` even for a claimed resume. */ function forwardedSpawnIntent(intent: SpawnIntent, claim: unknown): SpawnIntent { diff --git a/src/main/daemon/providers/adapter/daemon-pty-spawn-result.ts b/src/main/daemon/providers/adapter/daemon-pty-spawn-result.ts index be465582666..664486d22f8 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-spawn-result.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-spawn-result.ts @@ -8,7 +8,7 @@ import { takeHistoryRecoveryFreeze } from '../checkpointing/daemon-history-recov import { getRecoveredHistorySeedSegments } from '../../history/seed-transfer/terminal-history-seed-segments' import { SessionNotFoundError } from '../../protocol/daemon-errors' import type { DaemonCreateOrAttachResult as CreateOrAttachResult } from '../../protocol/daemon-create-or-attach-result' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest { protected async finishSpawn( diff --git a/src/main/daemon/providers/adapter/daemon-spawn-result-identity.ts b/src/main/daemon/providers/adapter/daemon-spawn-result-identity.ts index 2a8b1377504..801de996cfd 100644 --- a/src/main/daemon/providers/adapter/daemon-spawn-result-identity.ts +++ b/src/main/daemon/providers/adapter/daemon-spawn-result-identity.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { DaemonCreateOrAttachResult as CreateOrAttachResult } from '../../protocol/daemon-create-or-attach-result' export function daemonSpawnResultIdentity( diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-daemon-recovery.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-daemon-recovery.test.ts index 9bded39dda6..8a6e60448fb 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-daemon-recovery.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-daemon-recovery.test.ts @@ -1,11 +1,9 @@ import '../../../pty-subprocess/testing/mock-descendant-sweep' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { existsSync, rmSync } from 'node:fs' -import type { DaemonClient } from '../../../transport/client/daemon-client' +import { rmSync } from 'node:fs' import { DaemonPtyAdapter } from '../daemon-pty-adapter' import { DaemonServer } from '../../../server/daemon-server' import type { DaemonFileLog } from '../../../observability/daemon-file-log' -import { PtyWriteUnavailableError } from '../../../../providers/pty-write-unavailable-error' import { createMockSubprocess, startDaemonAdapterHarness, @@ -100,165 +98,6 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { }) } - it('rejects stale input until createOrAttach remounts the pane onto the new daemon', async () => { - let respawnServer: DaemonServer | undefined - let respawnSubprocess: ReturnType | undefined - const respawn = vi.fn(async () => { - respawnServer = new DaemonServer({ - socketPath, - tokenPath, - spawnSubprocess: () => { - respawnSubprocess = createMockSubprocess() - return respawnSubprocess - } - }) - await respawnServer.start() - }) - const healingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn }) - try { - const { id } = await healingAdapter.spawn({ cols: 80, rows: 24 }) - const internals = healingAdapter as unknown as { - sessionsAwaitingDaemonRecovery: Set - } - - await server.shutdown() - await waitFor(() => internals.sessionsAwaitingDaemonRecovery.has(id)) - - expect(() => healingAdapter.write(id, 'first')).toThrow(PtyWriteUnavailableError) - expect(() => healingAdapter.write(id, 'second')).toThrow(PtyWriteUnavailableError) - await waitFor(() => respawn.mock.calls.length === 1) - - expect(respawnSubprocess).toBeUndefined() - expect(() => healingAdapter.write(id, 'still-stale')).toThrow(PtyWriteUnavailableError) - - await healingAdapter.spawn({ sessionId: id, cols: 80, rows: 24 }) - expect(() => healingAdapter.write(id, 'rebound')).not.toThrow() - await waitFor( - () => - respawnSubprocess !== undefined && - vi.mocked(respawnSubprocess.write).mock.calls.length === 1 - ) - expect(respawnSubprocess?.write).toHaveBeenCalledWith('rebound') - expect(respawn).toHaveBeenCalledTimes(1) - } finally { - healingAdapter.dispose() - await respawnServer?.shutdown() - } - }) - - it('requires createOrAttach before writing to a session that survives a socket disconnect', async () => { - const respawn = vi.fn(async () => {}) - const healingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn }) - try { - const { id } = await healingAdapter.spawn({ cols: 80, rows: 24 }) - const client = (healingAdapter as unknown as { client: DaemonClient }).client - - client.disconnect() - expect(() => healingAdapter.write(id, 'stale')).toThrow(PtyWriteUnavailableError) - await waitFor(() => client.isConnected()) - expect(() => healingAdapter.write(id, 'still-stale')).toThrow(PtyWriteUnavailableError) - - await healingAdapter.spawn({ sessionId: id, cols: 80, rows: 24 }) - healingAdapter.write(id, 'rebound') - await waitFor(() => lastSubprocess.write.mock.calls.length > 0) - expect(lastSubprocess.write.mock.calls).toEqual([['rebound']]) - expect(healingAdapter.hasPty(id)).toBe(true) - expect(respawn).not.toHaveBeenCalled() - } finally { - healingAdapter.dispose() - } - }) - - it('respawns after a retired daemon regardless of how the connection ended', async () => { - // Explicit disconnect does not observe socket closure; endpoint failure must still permit recovery. - let respawnServer: DaemonServer | undefined - const respawn = vi.fn(async () => { - respawnServer = new DaemonServer({ - socketPath, - tokenPath, - spawnSubprocess: () => createMockSubprocess() - }) - await respawnServer.start() - }) - const healingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - const { id } = await healingAdapter.spawn({ cols: 80, rows: 24 }) - const client = (healingAdapter as unknown as { client: DaemonClient }).client - - client.disconnect() - await server.shutdown() - expect(existsSync(tokenPath)).toBe(false) - expect(client.hasObservedAuthenticatedDisconnect()).toBe(false) - - await expect( - healingAdapter.spawn({ sessionId: id, cols: 80, rows: 24 }) - ).resolves.toMatchObject({ id }) - expect(respawn).toHaveBeenCalledTimes(1) - } finally { - warn.mockRestore() - healingAdapter.dispose() - await respawnServer?.shutdown() - } - }) - - it('does not spawn a daemon per keystroke after respawn fails', async () => { - const respawn = vi.fn(async () => { - throw new Error('daemon unavailable') - }) - const healingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - const { id } = await healingAdapter.spawn({ cols: 80, rows: 24 }) - const client = (healingAdapter as unknown as { client: DaemonClient }).client - await server.shutdown() - await waitFor(() => !client.isConnected()) - - expect(() => healingAdapter.write(id, 'a')).toThrow(PtyWriteUnavailableError) - await waitFor(() => respawn.mock.calls.length === 1) - for (let i = 0; i < 100; i += 1) { - expect(() => healingAdapter.write(id, 'b')).toThrow(PtyWriteUnavailableError) - } - - expect(respawn).toHaveBeenCalledTimes(1) - } finally { - warn.mockRestore() - healingAdapter.dispose() - } - }) - - it('joins a request-path respawn instead of forking a second daemon', async () => { - let releaseRespawn!: () => void - const respawn = vi.fn(async () => { - await new Promise((resolve) => { - releaseRespawn = resolve - }) - restartServerOnRespawn() - await server.start() - }) - const healingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn }) - try { - const { id } = await healingAdapter.spawn({ cols: 80, rows: 24 }) - const client = (healingAdapter as unknown as { client: DaemonClient }).client - await server.shutdown() - await waitFor(() => !client.isConnected()) - - const newSpawn = healingAdapter.spawn({ - sessionId: 'request-path-session', - cols: 80, - rows: 24 - }) - await waitFor(() => releaseRespawn !== undefined) - expect(() => healingAdapter.write(id, 'queued')).toThrow(PtyWriteUnavailableError) - releaseRespawn() - - await expect(newSpawn).resolves.toMatchObject({ id: 'request-path-session' }) - expect(respawn).toHaveBeenCalledTimes(1) - } finally { - healingAdapter.dispose() - } - }) - it('signals every active pane and respawns as soon as the daemon dies, before any input', async () => { const respawn = vi.fn(async () => { restartServerOnRespawn() @@ -285,272 +124,5 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { healingAdapter.dispose() } }) - - it('re-arms recovery for a second daemon death when a background session never rebinds', async () => { - const respawn = vi.fn(async () => { - restartServerOnRespawn() - await server.start() - }) - const healingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn }) - const recovered: string[] = [] - healingAdapter.onWriteUnavailable(({ id }) => recovered.push(id)) - try { - await healingAdapter.spawn({ sessionId: 'pane-a', cols: 80, rows: 24 }) - // No mounted renderer will rebind this background session. - await healingAdapter.spawn({ sessionId: 'background-b', cols: 80, rows: 24 }) - const client = (healingAdapter as unknown as { client: DaemonClient }).client - - await server.shutdown() - await waitFor(() => respawn.mock.calls.length === 1) - expect(() => healingAdapter.write('pane-a', 'first-death')).toThrow( - PtyWriteUnavailableError - ) - await waitFor(() => client.isConnected()) - - // Rebind only the mounted pane, leaving background-b in the awaiting set. - await healingAdapter.spawn({ sessionId: 'pane-a', cols: 80, rows: 24 }) - recovered.length = 0 - - await server.shutdown() - await waitFor(() => recovered.includes('pane-a')) - - // Recovery must re-arm even when an unmounted sibling keeps the awaiting set nonempty. - expect(() => healingAdapter.write('pane-a', 'second-death')).toThrow( - PtyWriteUnavailableError - ) - expect(recovered).toContain('pane-a') - await waitFor(() => respawn.mock.calls.length === 2) - } finally { - healingAdapter.dispose() - } - }) - }) - - describe('respawn on daemon death', () => { - it('respawns the daemon and retries when the socket disappears', async () => { - let respawnServer: DaemonServer | undefined - const respawnFn = vi.fn(async () => { - respawnServer = new DaemonServer({ - socketPath, - tokenPath, - spawnSubprocess: () => createMockSubprocess() - }) - await respawnServer.start() - }) - - const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) - - const r1 = await respawnAdapter.spawn({ cols: 80, rows: 24 }) - expect(r1.id).toBeDefined() - - await server.shutdown() - - const r2 = await respawnAdapter.spawn({ cols: 80, rows: 24 }) - expect(r2.id).toBeDefined() - expect(respawnFn).toHaveBeenCalledTimes(1) - expect(respawnFn).toHaveBeenCalledWith('daemon_died') - - respawnAdapter.dispose() - await respawnServer?.shutdown() - }) - - it('propagates the error when no respawn callback is provided', async () => { - const noRespawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath }) - - await noRespawnAdapter.spawn({ cols: 80, rows: 24 }) - - await server.shutdown() - - await expect(noRespawnAdapter.spawn({ cols: 80, rows: 24 })).rejects.toThrow() - - noRespawnAdapter.dispose() - }) - - it('coalesces concurrent respawns so only one daemon is forked', async () => { - let respawnServer: DaemonServer | undefined - const respawnFn = vi.fn(async () => { - respawnServer = new DaemonServer({ - socketPath, - tokenPath, - spawnSubprocess: () => createMockSubprocess() - }) - await respawnServer.start() - }) - - const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) - - await respawnAdapter.spawn({ cols: 80, rows: 24 }) - - await server.shutdown() - - const [r1, r2] = await Promise.all([ - respawnAdapter.spawn({ cols: 80, rows: 24 }), - respawnAdapter.spawn({ cols: 80, rows: 24 }) - ]) - expect(r1.id).toBeDefined() - expect(r2.id).toBeDefined() - expect(respawnFn).toHaveBeenCalledTimes(1) - expect(respawnFn).toHaveBeenCalledWith('daemon_died') - - respawnAdapter.dispose() - await respawnServer?.shutdown() - }) - - it('preserves an unhealthy macOS resolver daemon when it owns live sessions', async () => { - const respawnFn = vi.fn() - const exits: { id: string; code: number }[] = [] - const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) - respawnAdapter.onExit((payload) => exits.push(payload)) - const existing = await respawnAdapter.spawn({ cols: 80, rows: 24 }) - getMacDaemonSystemResolverHealthMock.mockResolvedValueOnce('unhealthy') - - const next = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) - - expect(getMacDaemonSystemResolverHealthMock).toHaveBeenCalledWith( - socketPath, - tokenPath, - respawnAdapter.protocolVersion - ) - expect(respawnFn).not.toHaveBeenCalled() - expect(exits).toEqual([]) - expect(next.id).toBeDefined() - expect(next.id).not.toBe(existing.id) - - respawnAdapter.dispose() - }) - - it('preserves an unhealthy macOS resolver daemon when live sessions have not been reconciled locally', async () => { - const respawnFn = vi.fn() - const background = await adapter.spawn({ cols: 80, rows: 24 }) - const backgroundSubprocess = lastSubprocess - const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) - getMacDaemonSystemResolverHealthMock.mockResolvedValueOnce('unhealthy') - - const next = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) - - expect(getMacDaemonSystemResolverHealthMock).toHaveBeenCalledWith( - socketPath, - tokenPath, - respawnAdapter.protocolVersion - ) - expect(respawnFn).not.toHaveBeenCalled() - expect(next.id).toBeDefined() - expect(next.id).not.toBe(background.id) - expect(backgroundSubprocess.forceKill).not.toHaveBeenCalled() - - respawnAdapter.dispose() - }) - - it('replaces an unhealthy macOS resolver daemon before creating a fresh session when no sessions are active', async () => { - let respawnServer: DaemonServer | undefined - const respawnFn = vi.fn(async () => { - await server.shutdown() - rmSync(socketPath, { force: true }) - respawnServer = new DaemonServer({ - socketPath, - tokenPath, - spawnSubprocess: () => createMockSubprocess() - }) - await respawnServer.start() - }) - const exits: { id: string; code: number }[] = [] - const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) - respawnAdapter.onExit((payload) => exits.push(payload)) - getMacDaemonSystemResolverHealthMock.mockResolvedValueOnce('unhealthy') - - const replacement = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) - - expect(getMacDaemonSystemResolverHealthMock).toHaveBeenCalledWith( - socketPath, - tokenPath, - respawnAdapter.protocolVersion - ) - expect(respawnFn).toHaveBeenCalledTimes(1) - expect(respawnFn).toHaveBeenCalledWith('unhealthy_resolver') - expect(exits).toEqual([]) - expect(replacement.id).toBeDefined() - - respawnAdapter.dispose() - await respawnServer?.shutdown() - }) - - it('preserves a stale packaged daemon when its live session inventory is unavailable', async () => { - const respawnFn = vi.fn() - const respawnAdapter = new DaemonPtyAdapter({ - socketPath, - tokenPath, - runtimeDir: dir, - packagedAppVersion: '1.4.178', - respawn: respawnFn - }) - const internals = respawnAdapter as unknown as { - client: { request: (type: string, payload?: unknown) => Promise } - } - const originalRequest = internals.client.request.bind(internals.client) - vi.spyOn(internals.client, 'request').mockImplementation((type, payload) => { - if (type === 'listSessions') { - return Promise.reject(new Error('inventory unavailable')) - } - return originalRequest(type, payload) - }) - isDaemonStaleForCurrentBundleMock.mockResolvedValueOnce(true) - - const next = await respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) - - expect(respawnFn).not.toHaveBeenCalled() - expect(next.id).toBeDefined() - - respawnAdapter.dispose() - }) - - it('coalesces stale-bundle retirement before concurrent fresh sessions', async () => { - let respawnServer: DaemonServer | undefined - const respawnFn = vi.fn(async () => { - await server.shutdown() - rmSync(socketPath, { force: true }) - respawnServer = new DaemonServer({ - socketPath, - tokenPath, - spawnSubprocess: () => createMockSubprocess() - }) - await respawnServer.start() - }) - const respawnAdapter = new DaemonPtyAdapter({ - socketPath, - tokenPath, - runtimeDir: dir, - packagedAppVersion: '1.4.178', - respawn: respawnFn - }) - isDaemonStaleForCurrentBundleMock.mockResolvedValue(true) - - const replacements = await Promise.all([ - respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }), - respawnAdapter.spawn({ cols: 80, rows: 24, isNewSession: true }) - ]) - - expect(respawnFn).toHaveBeenCalledTimes(1) - expect(respawnFn).toHaveBeenCalledWith('stale_bundle') - expect(replacements.every((replacement) => replacement.id)).toBe(true) - - respawnAdapter.dispose() - await respawnServer?.shutdown() - }) - - it('propagates respawn failure to the caller', async () => { - const respawnFn = vi.fn(async () => { - throw new Error('Daemon entry file missing') - }) - - const respawnAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, respawn: respawnFn }) - await respawnAdapter.spawn({ cols: 80, rows: 24 }) - await server.shutdown() - - await expect(respawnAdapter.spawn({ cols: 80, rows: 24 })).rejects.toThrow( - 'Daemon entry file missing' - ) - - respawnAdapter.dispose() - }) }) }) diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts index d6f11128901..8a10177b2eb 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as pty from 'node-pty' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../../orcad/orcad-node-slot-fixture' +import { loadNodePtyForTests } from '../../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { DaemonPtyAdapter } from '../daemon-pty-adapter' import { startDaemonAdapterHarness, diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts index 131e992aa9a..9051d3b4d98 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as pty from 'node-pty' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../../orcad/orcad-node-slot-fixture' +import { loadNodePtyForTests } from '../../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { DaemonPtyAdapter } from '../daemon-pty-adapter' import { startDaemonAdapterHarness, diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.test.ts deleted file mode 100644 index 4a33409687a..00000000000 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import '../../../pty-subprocess/testing/mock-descendant-sweep' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { join } from 'node:path' -import { readFileSync, realpathSync, rmSync } from 'node:fs' -import { DaemonPtyAdapter } from '../daemon-pty-adapter' -import { DaemonClient } from '../../../transport/client/daemon-client' -import type { DaemonServer } from '../../../server/daemon-server' -import { getHistorySessionDirName } from '../../../history/storage/history-paths' -import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' -import type * as DaemonHealthModule from '../../../health/daemon-health' -import type * as DaemonTccAttributionModule from '../../../permissions/daemon-tcc-attribution' -import type * as ProcessCwdModule from '../../../../providers/process-cwd' - -const { - getMacDaemonSystemResolverHealthMock, - getMacDaemonTccAttributionHealthMock, - resolveProcessCwdSpy -} = vi.hoisted(() => ({ - resolveProcessCwdSpy: vi.fn(), - getMacDaemonSystemResolverHealthMock: vi.fn( - async (): Promise<'unknown' | 'unhealthy'> => 'unknown' - ), - getMacDaemonTccAttributionHealthMock: vi.fn( - async (): Promise<'intact' | 'severed' | 'unknown'> => 'unknown' - ) -})) - -vi.mock('../../../../providers/process-cwd', async (importOriginal) => { - const actual = await importOriginal() - resolveProcessCwdSpy.mockImplementation(actual.resolveProcessCwd) - return { ...actual, resolveProcessCwd: resolveProcessCwdSpy } -}) - -vi.mock('../../../health/daemon-health', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - getMacDaemonSystemResolverHealth: getMacDaemonSystemResolverHealthMock - } -}) - -vi.mock('../../../permissions/daemon-tcc-attribution', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - getMacDaemonTccAttributionHealth: getMacDaemonTccAttributionHealthMock - } -}) - -// verify-15b: a WSL host's pane (orcad on Linux, bash, no OSC 7) woke in the project root after `cd deep`. -describe('a native shell slept and woken', () => { - let dir: string - let socketPath: string - let tokenPath: string - let server: DaemonServer - let adapter: DaemonPtyAdapter - let spawnedCwds: (string | undefined)[] - let lastSubprocess: ReturnType - - beforeEach(async () => { - spawnedCwds = [] - const harness = await startDaemonAdapterHarness((opts) => { - spawnedCwds.push(opts.cwd) - // A real pid, so the daemon's cwd lookup reads this process's folder, as for a live shell. - lastSubprocess = Object.assign(createMockSubprocess(), { pid: process.pid }) - return lastSubprocess - }) - dir = harness.dir - socketPath = harness.socketPath - tokenPath = harness.tokenPath - server = harness.server - adapter = harness.adapter - getMacDaemonSystemResolverHealthMock.mockResolvedValue('unknown') - getMacDaemonTccAttributionHealthMock.mockResolvedValue('unknown') - }) - - afterEach(async () => { - resolveProcessCwdSpy.mockClear() - adapter?.dispose() - await server?.shutdown() - rmSync(dir, { recursive: true, force: true }) - }) - - it('wakes in the folder the shell was in at Sleep, not where it was spawned', async () => { - const historyDir = join(dir, 'history') - const sessionId = 'wt-1::/project@@sleep1' - const shellFolder = realpathSync(process.cwd()) - const history = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) - - await history.spawn({ cols: 80, rows: 24, cwd: dir, sessionId }) - lastSubprocess._simulateData('user@host:~/project$ cd deep\r\nuser@host:~/project/deep$ ') - await history.shutdown(sessionId, { immediate: true, keepHistory: true }) - - const saved = JSON.parse( - readFileSync(join(historyDir, getHistorySessionDirName(sessionId), 'checkpoint.json'), 'utf8') - ) - expect(realpathSync(saved.cwd)).toBe(shellFolder) - await history.spawn({ cols: 80, rows: 24, cwd: dir, sessionId }) - expect(realpathSync(spawnedCwds.at(-1)!)).toBe(shellFolder) - history.dispose() - }) - - // The process lookup execFile()s lsof, which Windows lacks; Sleep there keeps only the OSC 7 cwd. - - async function sleepAndWake(sessionId: string, deadlineMs?: number) { - const historyDir = join(dir, 'history') - const history = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) - await history.spawn({ cols: 80, rows: 24, cwd: dir, sessionId }) - lastSubprocess._simulateData('user@host:~/project$ ') - await history.shutdown(sessionId, { immediate: true, keepHistory: true, deadlineMs }) - const saved = JSON.parse( - readFileSync(join(historyDir, getHistorySessionDirName(sessionId), 'checkpoint.json'), 'utf8') - ) - await history.spawn({ cols: 80, rows: 24, cwd: dir, sessionId }) - history.dispose() - return { savedCwd: saved.cwd, wokeCwd: spawnedCwds.at(-1) } - } - - it('gives a hung folder read a quarter of the Sleep deadline, then checkpoints', async () => { - // Freeze only the clock, so the read's budget is exact while socket timers stay real. - vi.useFakeTimers({ toFake: ['Date'] }) - const requestSpy = vi.spyOn(DaemonClient.prototype, 'request') - try { - const now = Date.now() - resolveProcessCwdSpy.mockImplementationOnce(() => new Promise(() => {})) - const { savedCwd } = await sleepAndWake('wt-1::/project@@sleep-hung', now + 2_000) - expect(resolveProcessCwdSpy).toHaveBeenCalled() - const cwdTimeouts = requestSpy.mock.calls - .filter(([type]) => type === 'getCwd') - .map((c) => c[2]) - expect(cwdTimeouts).toEqual([500]) - expect(savedCwd).toBe(dir) - } finally { - requestSpy.mockRestore() - vi.useRealTimers() - } - }) -}) diff --git a/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts b/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts index 3786b13b3c0..f215b66a834 100644 --- a/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts +++ b/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts @@ -6,7 +6,7 @@ import { isUnknownRequestTypeError } from '../../endpoint/identity/daemon-endpoi import { focusLossReportSupport } from '../../protocol/daemon-protocol-version' import { DAEMON_SESSION_SCROLLBACK_ROWS } from '../../sessions/daemon-session-scrollback-window' import type { GetSnapshotResult } from '../../protocol/daemon-rpc-contract' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' const DURABLE_HISTORY_OVERLAY_DEADLINE_MS = 5_000 diff --git a/src/main/daemon/providers/lifecycle/daemon-automatic-work-resume.ts b/src/main/daemon/providers/lifecycle/daemon-automatic-work-resume.ts index 22d01c3da81..ae3902473d7 100644 --- a/src/main/daemon/providers/lifecycle/daemon-automatic-work-resume.ts +++ b/src/main/daemon/providers/lifecycle/daemon-automatic-work-resume.ts @@ -6,7 +6,7 @@ import type { AutomaticWorkResumeOutcome, AutomaticWorkStatus } from '../../../../shared/terminal/pty/admission/spawn-admission-contract' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import { DaemonPtyRouter } from '../routing/daemon-pty-router' import { DegradedDaemonPtyProvider } from '../routing/degraded-daemon-pty-provider' diff --git a/src/main/daemon/providers/lifecycle/daemon-provider-init.ts b/src/main/daemon/providers/lifecycle/daemon-provider-init.ts index 3d5cf86fc34..8475232834b 100644 --- a/src/main/daemon/providers/lifecycle/daemon-provider-init.ts +++ b/src/main/daemon/providers/lifecycle/daemon-provider-init.ts @@ -4,7 +4,7 @@ import { rebindLocalProviderListeners } from '../../../ipc/pty/provider/listener import { isStartupDiagnosticsEnabled, logStartupDiagnostic -} from '../../../startup/startup-diagnostics' +} from '../../../startup/diagnostics/startup-diagnostics' import { checkDaemonHealth } from '../../health/daemon-health' import { collectPinnedDaemonVersions, diff --git a/src/main/daemon/providers/lifecycle/daemon-provider-routing.ts b/src/main/daemon/providers/lifecycle/daemon-provider-routing.ts index b5b5d771fda..e9ee4168158 100644 --- a/src/main/daemon/providers/lifecycle/daemon-provider-routing.ts +++ b/src/main/daemon/providers/lifecycle/daemon-provider-routing.ts @@ -1,7 +1,7 @@ import { DegradedDaemonPtyProvider } from '../routing/degraded-daemon-pty-provider' import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import { DaemonPtyRouter } from '../routing/daemon-pty-router' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' export type DaemonProvider = DaemonPtyRouter | DaemonPtyAdapter | DegradedDaemonPtyProvider diff --git a/src/main/daemon/providers/routing/daemon-pty-adapter-subscription-fanout.ts b/src/main/daemon/providers/routing/daemon-pty-adapter-subscription-fanout.ts index 56a101197cc..129b95afe12 100644 --- a/src/main/daemon/providers/routing/daemon-pty-adapter-subscription-fanout.ts +++ b/src/main/daemon/providers/routing/daemon-pty-adapter-subscription-fanout.ts @@ -1,4 +1,4 @@ -import type { PtyBackgroundStreamEvent } from '../../../providers/pty-provider-contract' +import type { PtyBackgroundStreamEvent } from '../../../providers/pty/events' import { combineUnsubscribes } from './combine-unsubscribes' import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import type { diff --git a/src/main/daemon/providers/routing/daemon-pty-router.ts b/src/main/daemon/providers/routing/daemon-pty-router.ts index 4ba51fe9edf..ba3caec2aac 100644 --- a/src/main/daemon/providers/routing/daemon-pty-router.ts +++ b/src/main/daemon/providers/routing/daemon-pty-router.ts @@ -6,11 +6,11 @@ import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import { DaemonPtyAdapterSubscriptionFanout } from './daemon-pty-adapter-subscription-fanout' import type { IPtyProvider, - PtyBackgroundStreamEvent, PtyProviderBufferSnapshot, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' + PtySpawnOptions +} from '../../../providers/pty/provider-contract' +import type { PtyBackgroundStreamEvent } from '../../../providers/pty/events' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { TerminalProcessInspection as PtyProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' import { LegacyDaemonExitProof } from './daemon-legacy-exit-proof' import { shutdownRoutedDaemonSession } from './daemon-routed-session-shutdown' diff --git a/src/main/daemon/providers/routing/daemon-pty-target-inspection.ts b/src/main/daemon/providers/routing/daemon-pty-target-inspection.ts index 854f04078f5..71a82d42269 100644 --- a/src/main/daemon/providers/routing/daemon-pty-target-inspection.ts +++ b/src/main/daemon/providers/routing/daemon-pty-target-inspection.ts @@ -1,6 +1,6 @@ import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import type { PtyProcessInspectionOptions } from '../../../providers/pty-process-inspection' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtyProcessInspectionOptions } from '../../../providers/pty/process-inspection' /** Foreground reads go to the exact owner and never borrow the current daemon's default route. */ export class DaemonPtyTargetInspection { diff --git a/src/main/daemon/providers/routing/daemon-routed-session-shutdown.ts b/src/main/daemon/providers/routing/daemon-routed-session-shutdown.ts index d27f40833b0..53b5e7bfe17 100644 --- a/src/main/daemon/providers/routing/daemon-routed-session-shutdown.ts +++ b/src/main/daemon/providers/routing/daemon-routed-session-shutdown.ts @@ -1,5 +1,5 @@ import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { DaemonSessionOwnerResolver } from './daemon-session-owner-resolution' import { shouldHandoffDaemonHistory } from './daemon-history-handoff' diff --git a/src/main/daemon/providers/routing/daemon-router-legacy-owner.ts b/src/main/daemon/providers/routing/daemon-router-legacy-owner.ts index 2e158eb5d66..e8cc8e4b5b5 100644 --- a/src/main/daemon/providers/routing/daemon-router-legacy-owner.ts +++ b/src/main/daemon/providers/routing/daemon-router-legacy-owner.ts @@ -1,4 +1,4 @@ -import type { PtySpawnOptions } from '../../../providers/pty-provider-contract' +import type { PtySpawnOptions } from '../../../providers/pty/provider-contract' import { isDaemonEndpointGoneError, TerminalSessionOwnerUnverifiedError diff --git a/src/main/daemon/providers/routing/daemon-router-newer-daemon-hold.ts b/src/main/daemon/providers/routing/daemon-router-newer-daemon-hold.ts index 1dfa6b2f28d..298d3e47a3a 100644 --- a/src/main/daemon/providers/routing/daemon-router-newer-daemon-hold.ts +++ b/src/main/daemon/providers/routing/daemon-router-newer-daemon-hold.ts @@ -1,5 +1,5 @@ import { NEWER_DAEMON_HOLD_ERROR } from '../../../../shared/newer-daemon-hold' -import type { PtySpawnOptions } from '../../../providers/pty-provider-contract' +import type { PtySpawnOptions } from '../../../providers/pty/provider-contract' import { isHoldingForNewerProtocolDaemon } from './daemon-newer-protocol-hold' import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import type { DaemonSessionOwnerResolver } from './daemon-session-owner-resolution' diff --git a/src/main/daemon/providers/routing/daemon-session-owner-attach.ts b/src/main/daemon/providers/routing/daemon-session-owner-attach.ts index 9654cf9acf3..a52e48fc357 100644 --- a/src/main/daemon/providers/routing/daemon-session-owner-attach.ts +++ b/src/main/daemon/providers/routing/daemon-session-owner-attach.ts @@ -1,8 +1,5 @@ -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { SessionNotFoundError, TerminalSessionOwnerUnverifiedError diff --git a/src/main/daemon/providers/routing/daemon-session-owner-choice.ts b/src/main/daemon/providers/routing/daemon-session-owner-choice.ts index d15a5d3884c..f7c82342cc3 100644 --- a/src/main/daemon/providers/routing/daemon-session-owner-choice.ts +++ b/src/main/daemon/providers/routing/daemon-session-owner-choice.ts @@ -1,4 +1,4 @@ -import type { PtyProcessInfo } from '../../../providers/pty-provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' export type OwnerCandidate = { provider: T; process: PtyProcessInfo } diff --git a/src/main/daemon/providers/routing/daemon-session-owner-inventory.ts b/src/main/daemon/providers/routing/daemon-session-owner-inventory.ts index 5ea3eea0454..a12b6736eba 100644 --- a/src/main/daemon/providers/routing/daemon-session-owner-inventory.ts +++ b/src/main/daemon/providers/routing/daemon-session-owner-inventory.ts @@ -1,9 +1,10 @@ -import type { IPtyProvider, PtyProcessInfo } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' import type { DaemonSessionOwnerResolution } from './daemon-session-owner-resolution' import { TerminalSessionOwnerUnverifiedError } from '../../protocol/daemon-errors' import { chooseSessionOwner, type OwnerCandidate } from './daemon-session-owner-choice' import { randomUUID } from 'node:crypto' -import { worktreePtyOwnership } from '../../../providers/worktree-pty-ownership' +import { worktreePtyOwnership } from '../../../providers/pty/worktree-ownership' export type ProviderInventory = { provider: T diff --git a/src/main/daemon/providers/routing/daemon-session-owner-liveness.ts b/src/main/daemon/providers/routing/daemon-session-owner-liveness.ts index f49c4276df0..0b533bd5154 100644 --- a/src/main/daemon/providers/routing/daemon-session-owner-liveness.ts +++ b/src/main/daemon/providers/routing/daemon-session-owner-liveness.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { OwnerInventory } from './daemon-session-owner-inventory' export async function probeDaemonSessionOwner(opts: { diff --git a/src/main/daemon/providers/routing/daemon-session-owner-resolution.ts b/src/main/daemon/providers/routing/daemon-session-owner-resolution.ts index 8baf125f031..731acf2113f 100644 --- a/src/main/daemon/providers/routing/daemon-session-owner-resolution.ts +++ b/src/main/daemon/providers/routing/daemon-session-owner-resolution.ts @@ -6,12 +6,9 @@ import { type OwnerInventory, type ProviderInventory } from './daemon-session-owner-inventory' -import type { - IPtyProvider, - PtyProcessInfo, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { TerminalSessionOwnerUnverifiedError } from '../../protocol/daemon-errors' import { spawnDaemonAttachOnly } from './daemon-session-owner-attach' import { probeDaemonSessionOwner } from './daemon-session-owner-liveness' diff --git a/src/main/daemon/providers/routing/degraded-daemon-fallback-shutdown.ts b/src/main/daemon/providers/routing/degraded-daemon-fallback-shutdown.ts index 70b512eff34..ea740c4d319 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-fallback-shutdown.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-fallback-shutdown.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' export async function shutdownDegradedFallbackSessions( sessionProviders: Map, diff --git a/src/main/daemon/providers/routing/degraded-daemon-fresh-spawn-routing.ts b/src/main/daemon/providers/routing/degraded-daemon-fresh-spawn-routing.ts index b1ee6aefd02..9db9bcf5b39 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-fresh-spawn-routing.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-fresh-spawn-routing.ts @@ -1,8 +1,5 @@ -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' export const DEGRADED_DAEMON_RECOVERY_RETRY_MS = 30_000 diff --git a/src/main/daemon/providers/routing/degraded-daemon-listeners.ts b/src/main/daemon/providers/routing/degraded-daemon-listeners.ts index 8a6d78818d3..85a2740cc24 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-listeners.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-listeners.ts @@ -1,4 +1,5 @@ -import type { IPtyProvider, PtyDataEvent } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtyDataEvent } from '../../../providers/pty/events' type ExitListener = Parameters[0] type ExitEvent = Parameters[0] diff --git a/src/main/daemon/providers/routing/degraded-daemon-owner-recovery.ts b/src/main/daemon/providers/routing/degraded-daemon-owner-recovery.ts index aec0a22e774..6e8855e230c 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-owner-recovery.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-owner-recovery.ts @@ -1,9 +1,6 @@ -import type { - IPtyProvider, - PtyProcessInfo, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import { DaemonSessionOwnerResolver } from './daemon-session-owner-resolution' diff --git a/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts b/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts index 58164a96f2b..fe4ad27c754 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-pty-provider.ts @@ -5,16 +5,15 @@ import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import { combineUnsubscribes } from './combine-unsubscribes' import { DegradedDaemonListeners } from './degraded-daemon-listeners' import { shutdownDegradedFallbackSessions } from './degraded-daemon-fallback-shutdown' -import { inspectPtyProviderProcess } from '../../../providers/pty-process-inspection' +import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' import type { IPtyProvider, - PtyBackgroundStreamEvent, - PtyDataEvent, - PtyProcessInfo, PtyProviderBufferSnapshot, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' + PtySpawnOptions +} from '../../../providers/pty/provider-contract' +import type { PtyBackgroundStreamEvent, PtyDataEvent } from '../../../providers/pty/events' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { adoptOwningProvider, attachDaemonOwnedSession, diff --git a/src/main/daemon/providers/routing/degraded-daemon-session-routing.ts b/src/main/daemon/providers/routing/degraded-daemon-session-routing.ts index bde3a803271..dcc36c6179e 100644 --- a/src/main/daemon/providers/routing/degraded-daemon-session-routing.ts +++ b/src/main/daemon/providers/routing/degraded-daemon-session-routing.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { DaemonPtyAdapter } from '../adapter/daemon-pty-adapter' import { SessionNotFoundError } from '../../protocol/daemon-errors' diff --git a/src/main/daemon/providers/routing/testing/daemon-inventory-acquisition-budget.test.ts b/src/main/daemon/providers/routing/testing/daemon-inventory-acquisition-budget.test.ts deleted file mode 100644 index b730963a00e..00000000000 --- a/src/main/daemon/providers/routing/testing/daemon-inventory-acquisition-budget.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { IPtyProvider, PtyProcessInfo } from '../../../../providers/pty-provider-contract' -import { createAdapter } from './daemon-pty-router-test-fixture' -import { DaemonSessionOwnerResolver } from '../daemon-session-owner-resolution' -import { sweepProviderByPrefix } from '../../../../runtime/workspaces/removal/worktree-pty-surface-sweeps' - -const row = (id = 'shared', incarnationId = 'live'): PtyProcessInfo => ({ - id, - incarnationId, - cwd: '/project', - title: 'shell' -}) - -function adapter(listProcesses: IPtyProvider['listProcesses']) { - const provider = createAdapter('inventory') - vi.mocked(provider.listProcesses).mockImplementation(listProcesses) - return provider -} - -function delayedInventory( - delayMs: number, - processes: () => PtyProcessInfo[] -): IPtyProvider['listProcesses'] { - return (opts) => { - const deadlineMs = opts?.deadlineMs - if (deadlineMs === undefined) { - throw new Error('Inventory fixture requires the actual RPC deadline') - } - return new Promise((resolve, reject) => { - const success = setTimeout(() => { - clearTimeout(timeout) - resolve(processes()) - }, delayMs) - const timeout = setTimeout( - () => { - clearTimeout(success) - reject(new Error('Inventory RPC deadline exceeded')) - }, - Math.max(0, deadlineMs - Date.now()) - ) - }) - } -} - -describe('daemon inventory acquisition budget', () => { - afterEach(() => vi.useRealTimers()) - - it('refreshes cleanup after a timed-out restore and stops an externally created PTY', async () => { - vi.useFakeTimers() - const worktreeId = 'repo::/project' - const targetId = `${worktreeId}@@external` - let rows: PtyProcessInfo[] = [] - const fast = adapter(async () => [...rows]) - const slow = adapter( - vi - .fn() - .mockImplementationOnce(delayedInventory(3_000, () => [])) - .mockResolvedValue([]) - ) - const resolver = new DaemonSessionOwnerResolver([fast, slow], new Map()) - const restore = resolver.resolve('missing-restore-pane') - await vi.advanceTimersByTimeAsync(2_000) - await expect(restore).resolves.toEqual({ kind: 'unknown' }) - rows = [row(targetId)] - const facade = adapter((opts) => resolver.listProcesses(opts)) - vi.mocked(facade.shutdown).mockImplementation(async (id) => { - rows = rows.filter((process) => process.id !== id) - }) - - const sweep = sweepProviderByPrefix( - worktreeId, - facade, - Date.now() + 10_000, - async (_id, stop) => { - const stopped = await stop() - return { stopped, owner: stopped } - }, - undefined, - true - ) - await vi.advanceTimersByTimeAsync(1_000) - await expect(sweep).resolves.toBe(1) - expect(facade.shutdown).toHaveBeenCalledExactlyOnceWith(targetId, expect.anything()) - expect(rows).toEqual([]) - expect(fast.listProcesses).toHaveBeenCalledTimes(2) - expect(slow.listProcesses).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/daemon/providers/routing/testing/daemon-pty-router-test-fixture.ts b/src/main/daemon/providers/routing/testing/daemon-pty-router-test-fixture.ts index 24e3e3b1d1a..512ed7191f0 100644 --- a/src/main/daemon/providers/routing/testing/daemon-pty-router-test-fixture.ts +++ b/src/main/daemon/providers/routing/testing/daemon-pty-router-test-fixture.ts @@ -1,11 +1,9 @@ import { vi } from 'vitest' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' import type { DaemonPtyAdapter } from '../../adapter/daemon-pty-adapter' -import type { - PtyBackgroundStreamEvent, - PtySpawnOptions, - PtySpawnResult -} from '../../../../providers/pty-provider-contract' +import type { PtyBackgroundStreamEvent } from '../../../../providers/pty/events' +import type { PtySpawnOptions } from '../../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../../providers/pty/spawn-result' import { AGENT_SESSION_CLAIM_DAEMON_PROTOCOL_VERSION, AGENT_SESSION_CREATE_OPERATION_DAEMON_PROTOCOL_VERSION, diff --git a/src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts b/src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts deleted file mode 100644 index cd8f05f8618..00000000000 --- a/src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { createAdapter } from './daemon-pty-router-test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { DaemonPtyRouter } from '../daemon-pty-router' -import { TerminalSessionOwnerUnverifiedError } from '../../../protocol/daemon-errors' -import type { PtyProcessInfo } from '../../../../providers/pty-provider-contract' -import { - HISTORY_SEED_TRANSFER_PROTOCOL_VERSION, - PROTOCOL_VERSION -} from '../../../protocol/daemon-protocol-version' - -describe('DaemonPtyRouter', () => { - describe('idle retirement', () => { - it('retires every empty daemon generation and fences subsequent spawns', async () => { - const current = createAdapter('current', [], undefined, PROTOCOL_VERSION) - const legacy = createAdapter('legacy', [], undefined, PROTOCOL_VERSION) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) - - await expect(router.requestIdleRetirement()).resolves.toEqual({ state: 'retiring' }) - expect(current.requestIdleRetirement).toHaveBeenCalledOnce() - expect(legacy.requestIdleRetirement).toHaveBeenCalledOnce() - await expect(router.spawn({ sessionId: 'late', cols: 80, rows: 24 })).rejects.toThrow( - 'Terminal daemon is decommissioning' - ) - }) - - it('reports live inventory before retiring any generation and reopens admission', async () => { - const current = createAdapter('current', [], undefined, PROTOCOL_VERSION) - const legacy = createAdapter('legacy', ['legacy-live'], undefined, PROTOCOL_VERSION) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) - - await expect(router.requestIdleRetirement()).resolves.toEqual({ - state: 'busy', - liveSessions: 1, - admissionReopened: true - }) - expect(current.requestIdleRetirement).not.toHaveBeenCalled() - expect(legacy.requestIdleRetirement).not.toHaveBeenCalled() - await expect( - router.spawn({ sessionId: 'after-refusal', cols: 80, rows: 24 }) - ).resolves.toEqual({ - id: 'after-refusal' - }) - }) - - it('does not certify reopened admission when another generation retired beside live sessions', async () => { - const current = createAdapter('current', [], undefined, PROTOCOL_VERSION) - const legacy = createAdapter('legacy', [], undefined, PROTOCOL_VERSION) - vi.mocked(legacy.requestIdleRetirement).mockResolvedValueOnce({ - state: 'busy', - liveSessions: 1, - admissionReopened: true - }) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) - await expect(router.requestIdleRetirement()).resolves.toEqual({ - state: 'busy', - liveSessions: 1 - }) - await expect( - router.spawn({ sessionId: 'unsafe-partial', cols: 80, rows: 24 }) - ).rejects.toThrow('Terminal daemon is decommissioning') - }) - }) - - it.each([false, true])( - 'keeps newer spawn authority when an older listing completes (duplicate ids: %s)', - async (duplicateIds) => { - const current = createAdapter('current') - const legacy = createAdapter('legacy') - current.supportsFencedTermination = () => true - current.killFenced = vi.fn(async () => ({ outcome: 'ended' as const })) - legacy.supportsFencedTermination = () => false - legacy.killFenced = vi.fn(async () => ({ - outcome: 'refused' as const, - reason: 'unsupported' as const - })) - vi.mocked(current.spawn).mockResolvedValue({ id: 'raced', incarnationId: 'new' }) - vi.mocked(current.listProcesses).mockResolvedValue( - duplicateIds ? [{ id: 'raced', incarnationId: 'old-current', cwd: '', title: '' }] : [] - ) - const { promise: oldInventory, resolve: release } = Promise.withResolvers() - vi.mocked(legacy.listProcesses).mockReturnValue(oldInventory) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) - const oldListing = router.listProcesses() - expect(legacy.listProcesses).toHaveBeenCalledOnce() - await router.spawn({ sessionId: 'raced', isNewSession: true, cols: 80, rows: 24 }) - release([{ id: 'raced', incarnationId: 'old-legacy', cwd: '', title: '' }]) - await expect(oldListing).rejects.toBeInstanceOf(TerminalSessionOwnerUnverifiedError) - const request = { - id: 'raced', - expectedIncarnationId: 'new', - requireNoAgentOwner: true, - requireUnattached: true - } - - expect(router.supportsFencedTermination('raced')).toBe(true) - await expect(router.killFenced(request)).resolves.toEqual({ outcome: 'ended' }) - expect(current.killFenced).toHaveBeenCalledExactlyOnceWith(request) - expect(legacy.killFenced).not.toHaveBeenCalled() - expect(current.listProcesses).toHaveBeenCalledOnce() - expect(legacy.listProcesses).toHaveBeenCalledOnce() - } - ) - - it('does not let an older refresh overwrite a newer discovery route', async () => { - const current = createAdapter('current') - const legacy = createAdapter('legacy') - current.supportsFencedTermination = () => true - current.killFenced = vi.fn(async () => ({ outcome: 'ended' as const })) - legacy.supportsFencedTermination = () => false - const { promise: staleCurrent, resolve: releaseCurrent } = - Promise.withResolvers() - const { promise: staleLegacy, resolve: releaseLegacy } = - Promise.withResolvers() - vi.mocked(current.listProcesses) - .mockReturnValueOnce(staleCurrent) - .mockResolvedValueOnce([{ id: 'discovered', incarnationId: 'new', cwd: '', title: '' }]) - vi.mocked(legacy.listProcesses).mockReturnValueOnce(staleLegacy).mockResolvedValueOnce([]) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) - const staleRefresh = router.listProcesses() - await router.discoverLegacySessions() - releaseCurrent([]) - releaseLegacy([{ id: 'discovered', incarnationId: 'old', cwd: '', title: '' }]) - await expect(staleRefresh).rejects.toBeInstanceOf(TerminalSessionOwnerUnverifiedError) - const request = { - id: 'discovered', - expectedIncarnationId: 'new', - requireNoAgentOwner: true, - requireUnattached: true - } - - expect(router.supportsFencedTermination('discovered')).toBe(true) - await expect(router.killFenced(request)).resolves.toEqual({ outcome: 'ended' }) - expect(current.killFenced).toHaveBeenCalledExactlyOnceWith(request) - expect(current.listProcesses).toHaveBeenCalledTimes(2) - expect(legacy.listProcesses).toHaveBeenCalledTimes(2) - }) - - it('keeps the legacy route when checkpointed shutdown fails', async () => { - const current = createAdapter('current', [], undefined, HISTORY_SEED_TRANSFER_PROTOCOL_VERSION) - const legacy = createAdapter( - 'legacy', - ['legacy-session'], - undefined, - HISTORY_SEED_TRANSFER_PROTOCOL_VERSION - 1 - ) - vi.mocked(legacy.shutdown).mockRejectedValueOnce(new Error('checkpoint failed')) - const router = new DaemonPtyRouter({ current, legacy: [legacy] }) - await router.discoverLegacySessions() - - await expect(router.shutdown('legacy-session', { keepHistory: true })).rejects.toThrow( - 'checkpoint failed' - ) - await router.spawn({ sessionId: 'legacy-session', cols: 80, rows: 24 }) - - expect(legacy.spawn).toHaveBeenCalled() - expect(legacy.ackColdRestore).not.toHaveBeenCalled() - expect(current.spawn).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/daemon/providers/routing/testing/daemon-session-owner-resolution.test.ts b/src/main/daemon/providers/routing/testing/daemon-session-owner-resolution.test.ts deleted file mode 100644 index 2329bb38625..00000000000 --- a/src/main/daemon/providers/routing/testing/daemon-session-owner-resolution.test.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { - IPtyProvider, - PtyProcessInfo, - PtySpawnOptions, - PtySpawnResult -} from '../../../../providers/pty-provider-contract' -import { - SessionNotFoundError, - TerminalSessionOwnerUnverifiedError -} from '../../../protocol/daemon-errors' -import { DaemonSessionOwnerResolver } from '../daemon-session-owner-resolution' -import { terminateResolvedDaemonSession } from '../../../server/daemon-fenced-termination' - -function provider( - processes: () => Promise, - spawn: (opts: PtySpawnOptions) => Promise = async (opts) => ({ - id: opts.sessionId ?? 'new' - }) -): IPtyProvider { - return { - listProcesses: vi.fn(processes), - spawn: vi.fn(spawn) - } as unknown as IPtyProvider -} - -describe('DaemonSessionOwnerResolver', () => { - it('does not use cached absence as checked-termination proof for a newly discovered session', async () => { - const sessions = [{ id: 'existing', incarnationId: 'current', cwd: '', title: 'existing' }] - const owner = provider(async () => [...sessions]) - owner.supportsFencedTermination = () => true - owner.killFenced = vi.fn(async () => ({ outcome: 'ended' as const })) - const resolver = new DaemonSessionOwnerResolver([owner], new Map()) - await expect(resolver.resolve('existing', 'replaced', true)).resolves.toEqual({ - kind: 'unknown' - }) - sessions.push({ id: 'new-session', incarnationId: 'new', cwd: '', title: 'new' }) - const request = { - id: 'new-session', - expectedIncarnationId: 'new', - requireNoAgentOwner: true, - requireUnattached: true - } - - await expect( - terminateResolvedDaemonSession(request, () => resolver.resolveTermination(request.id, 'new')) - ).resolves.toEqual({ outcome: 'ended' }) - expect(owner.killFenced).toHaveBeenCalledExactlyOnceWith(request) - expect(owner.listProcesses).toHaveBeenCalledTimes(2) - }) - - it('dispatches to an exact spawn owner without accepting pre-spawn in-flight absence', async () => { - const { promise: gate, resolve: release } = Promise.withResolvers() - const owner = provider(() => gate) - owner.supportsFencedTermination = () => true - owner.killFenced = vi.fn(async () => ({ outcome: 'ended' as const })) - const resolver = new DaemonSessionOwnerResolver([owner], new Map()) - const oldInventory = resolver.resolve('unrelated') - resolver.recordRoute('new-session', owner, 'new') - const request = { - id: 'new-session', - expectedIncarnationId: 'new', - requireNoAgentOwner: true, - requireUnattached: true - } - const termination = terminateResolvedDaemonSession(request, () => - resolver.resolveTermination(request.id, 'new') - ) - release([]) - - await expect(termination).resolves.toEqual({ outcome: 'ended' }) - await expect(oldInventory).resolves.toEqual({ kind: 'unknown' }) - expect(owner.killFenced).toHaveBeenCalledExactlyOnceWith(request) - expect(owner.listProcesses).toHaveBeenCalledOnce() - }) - - it('requires post-spawn inventory when a new route has no exact incarnation proof', async () => { - const { promise: gate, resolve: release } = Promise.withResolvers() - const inventory = vi - .fn<() => Promise>() - .mockReturnValueOnce(gate) - .mockResolvedValueOnce([{ id: 'new-session', incarnationId: 'new', cwd: '', title: 'new' }]) - const owner = provider(inventory) - owner.supportsFencedTermination = () => true - owner.killFenced = vi.fn(async () => ({ outcome: 'ended' as const })) - const resolver = new DaemonSessionOwnerResolver([owner], new Map()) - const oldInventory = resolver.resolve('unrelated') - resolver.recordRoute('new-session', owner) - const request = { - id: 'new-session', - expectedIncarnationId: 'new', - requireNoAgentOwner: true, - requireUnattached: true - } - const termination = terminateResolvedDaemonSession(request, () => - resolver.resolveTermination(request.id, 'new') - ) - release([]) - - await expect(termination).resolves.toEqual({ outcome: 'ended' }) - await expect(oldInventory).resolves.toEqual({ kind: 'unknown' }) - expect(owner.killFenced).toHaveBeenCalledExactlyOnceWith(request) - expect(owner.listProcesses).toHaveBeenCalledTimes(2) - }) - - it('re-resolves a routed incarnation mismatch against every possible owner', async () => { - const staleRoute = provider( - async () => [{ id: 'session', incarnationId: 'other', cwd: '', title: 'stale' }], - async () => ({ id: 'session', incarnationId: 'other', isReattach: true }) - ) - const exactOwner = provider( - async () => [{ id: 'session', incarnationId: 'expected', cwd: '', title: 'exact' }], - async () => ({ id: 'session', incarnationId: 'expected', isReattach: true }) - ) - const resolver = new DaemonSessionOwnerResolver( - [staleRoute, exactOwner], - new Map([['session', staleRoute]]) - ) - - await expect( - resolver.spawnAttachOnly({ - sessionId: 'session', - expectedIncarnationId: 'expected', - expectedIncarnationIsAuthoritative: true, - attachOnly: true, - cols: 80, - rows: 24 - }) - ).resolves.toMatchObject({ incarnationId: 'expected' }) - expect(staleRoute.spawn).not.toHaveBeenCalled() - }) - - it('refreshes incomplete inventory when a routed owner refuses a moved session', async () => { - let firstOwnsSession = true - let secondOwnsSession = false - const first = provider( - async () => - firstOwnsSession - ? [{ id: 'session', incarnationId: 'runtime', cwd: '', title: 'first' }] - : [], - async () => { - throw new SessionNotFoundError('session') - } - ) - const second = provider( - async () => - secondOwnsSession - ? [{ id: 'session', incarnationId: 'runtime', cwd: '', title: 'second' }] - : [], - async () => ({ id: 'session', incarnationId: 'runtime', isReattach: true }) - ) - const unavailable = provider(async () => { - throw new Error('offline') - }) - const resolver = new DaemonSessionOwnerResolver([first, second, unavailable], new Map()) - - await expect(resolver.resolve('session', 'runtime', true)).resolves.toMatchObject({ - kind: 'owner', - provider: first - }) - firstOwnsSession = false - secondOwnsSession = true - - await expect( - resolver.spawnAttachOnly({ - sessionId: 'session', - expectedIncarnationId: 'runtime', - expectedIncarnationIsAuthoritative: true, - attachOnly: true, - cols: 80, - rows: 24 - }) - ).resolves.toMatchObject({ id: 'session', incarnationId: 'runtime', isReattach: true }) - expect(first.spawn).toHaveBeenCalledOnce() - expect(second.spawn).toHaveBeenCalledOnce() - expect(second.listProcesses).toHaveBeenCalledTimes(2) - }) - - it('fails closed across identity replacement then confirms absence on retry', async () => { - let releaseCurrent!: (processes: PtyProcessInfo[]) => void - let releaseLegacy!: (processes: PtyProcessInfo[]) => void - const currentGate = new Promise((resolve) => { - releaseCurrent = resolve - }) - const legacyGate = new Promise((resolve) => { - releaseLegacy = resolve - }) - const currentInventory = vi - .fn<() => Promise>() - .mockReturnValueOnce(currentGate) - .mockResolvedValueOnce([]) - const legacyInventory = vi - .fn<() => Promise>() - .mockReturnValueOnce(legacyGate) - .mockResolvedValueOnce([]) - const current = provider(currentInventory) - const legacy = provider(legacyInventory) - const resolver = new DaemonSessionOwnerResolver([current, legacy], new Map()) - const attach = { - sessionId: 'pty-persisted-after-identity-change', - expectedIncarnationId: 'incarnation-before-identity-change', - attachOnly: true, - cols: 80, - rows: 24 - } as const - - const staleAttempt = resolver.spawnAttachOnly(attach) - expect(currentInventory).toHaveBeenCalledOnce() - expect(legacyInventory).toHaveBeenCalledOnce() - resolver.invalidateProvider(current) - releaseCurrent([]) - releaseLegacy([]) - - await expect(staleAttempt).rejects.toBeInstanceOf(TerminalSessionOwnerUnverifiedError) - expect(current.spawn).not.toHaveBeenCalled() - expect(legacy.spawn).not.toHaveBeenCalled() - - await expect(resolver.spawnAttachOnly(attach)).rejects.toBeInstanceOf(SessionNotFoundError) - expect(currentInventory).toHaveBeenCalledTimes(2) - expect(legacyInventory).toHaveBeenCalledTimes(2) - expect(current.spawn).not.toHaveBeenCalled() - expect(legacy.spawn).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts b/src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts deleted file mode 100644 index 5ca07c087d0..00000000000 --- a/src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { DegradedDaemonPtyProvider } from '../degraded-daemon-pty-provider' -import { DEGRADED_DAEMON_RECOVERY_RETRY_MS } from '../degraded-daemon-fresh-spawn-routing' -import type { DaemonPtyAdapter } from '../../adapter/daemon-pty-adapter' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../../providers/pty-provider-contract' -import type { PtyProcessInspectionOptions } from '../../../../providers/pty-process-inspection' -import type { TerminalProcessInspection as PtyProcessInspection } from '../../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -import { readLaunchedAgentForeground } from '../../../../runtime/terminal/wait/launched-agent-foreground' -import { SessionNotFoundError } from '../../../protocol/daemon-errors' - -type ProviderMock = IPtyProvider & { - probePtyLiveness: (id: string) => Promise - inspectProcess: ( - id: string, - options?: PtyProcessInspectionOptions - ) => Promise - emitData: (id: string, data: string, sequenceChars?: number) => void - emitReplay: (id: string, data: string) => void - emitExit: (id: string, code: number) => void - onWriteUnavailable: (callback: (payload: { id: string }) => void) => () => void -} - -function createProvider( - label: string, - sessions: string[] = [], - authoritativeOwnerListings = false -): ProviderMock { - const dataListeners: ((payload: { id: string; data: string; sequenceChars?: number }) => void)[] = - [] - const replayListeners: ((payload: { id: string; data: string }) => void)[] = [] - const exitListeners: ((payload: { id: string; code: number }) => void)[] = [] - const writeUnavailableListeners: ((payload: { id: string }) => void)[] = [] - return { - spawn: vi.fn(async (opts: PtySpawnOptions): Promise => { - const id = opts.sessionId ?? `${label}-new` - sessions.push(id) - return { id } - }), - attach: vi.fn(async () => {}), - hasPty: vi.fn((id: string) => sessions.includes(id)), - probePtyLiveness: vi.fn(async (id: string) => sessions.includes(id)), - providesAgentSessionOwnerListings: vi.fn(() => authoritativeOwnerListings), - write: vi.fn(), - writeWithSettlement: vi.fn(settledWriteStub()), - resize: vi.fn(), - shutdown: vi.fn(async (id: string) => { - const idx = sessions.indexOf(id) - if (idx !== -1) { - sessions.splice(idx, 1) - } - }), - sendSignal: vi.fn(async () => {}), - getCwd: vi.fn(async () => ''), - getInitialCwd: vi.fn(async () => ''), - clearBuffer: vi.fn(async () => {}), - resetInputModes: vi.fn(async () => {}), - acknowledgeDataEvent: vi.fn(), - hasChildProcesses: vi.fn(async () => false), - getForegroundProcess: vi.fn(async () => null), - inspectProcess: vi.fn(async () => ({ foregroundProcess: null, hasChildProcesses: false })), - confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`), - serialize: vi.fn(async () => '{}'), - revive: vi.fn(async () => {}), - listProcesses: vi.fn(async () => sessions.map((id) => ({ id, cwd: '', title: label }))), - getDefaultShell: vi.fn(async () => '/bin/zsh'), - getProfiles: vi.fn(async () => []), - onData: vi.fn( - (callback: (payload: { id: string; data: string; sequenceChars?: number }) => void) => { - dataListeners.push(callback) - return () => { - const idx = dataListeners.indexOf(callback) - if (idx !== -1) { - dataListeners.splice(idx, 1) - } - } - } - ), - onReplay: vi.fn((callback: (payload: { id: string; data: string }) => void) => { - replayListeners.push(callback) - return () => { - const idx = replayListeners.indexOf(callback) - if (idx !== -1) { - replayListeners.splice(idx, 1) - } - } - }), - onExit: vi.fn((callback: (payload: { id: string; code: number }) => void) => { - exitListeners.push(callback) - return () => { - const idx = exitListeners.indexOf(callback) - if (idx !== -1) { - exitListeners.splice(idx, 1) - } - } - }), - emitData: (id: string, data: string, sequenceChars?: number) => { - for (const listener of dataListeners) { - listener({ id, data, ...(sequenceChars === undefined ? {} : { sequenceChars }) }) - } - }, - emitReplay: (id: string, data: string) => { - for (const listener of replayListeners) { - listener({ id, data }) - } - }, - emitExit: (id: string, code: number) => { - for (const listener of exitListeners) { - listener({ id, code }) - } - }, - onWriteUnavailable: vi.fn((callback: (payload: { id: string }) => void) => { - writeUnavailableListeners.push(callback) - return () => { - const idx = writeUnavailableListeners.indexOf(callback) - if (idx !== -1) { - writeUnavailableListeners.splice(idx, 1) - } - } - }) - } -} - -function createDaemonAdapter( - label: string, - sessions: string[] = [] -): DaemonPtyAdapter & ProviderMock { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the degraded router reaches only these adapter members. - return { - ...createProvider(label, sessions, true), - protocolVersion: 13, - supportsGitCredentialGuardHost: vi.fn(() => true), - canProvideAuthoritativeBufferSnapshot: vi.fn(() => true), - listSessions: vi.fn(async () => []), - ackColdRestore: vi.fn(), - clearTombstone: vi.fn(), - reportFocusLost: vi.fn(async () => {}), - reconcileOnStartup: vi.fn(async () => ({ alive: sessions, killed: [] })), - dispose: vi.fn(), - disconnectOnly: vi.fn(async () => {}), - getActiveSessionIds: vi.fn(() => []), - fanoutSyntheticExits: vi.fn() - } as unknown as DaemonPtyAdapter & ProviderMock -} - -it('reports focus lost to the daemon that owns the session', async () => { - const current = createDaemonAdapter('daemon') - const legacy = createDaemonAdapter('legacy', ['legacy-session']) - const provider = new DegradedDaemonPtyProvider({ - current, - legacy: [legacy], - fallback: createProvider('fallback') - }) - await provider.discoverDaemonSessions() - - await provider.reportFocusLost('legacy-session') - - expect(legacy.reportFocusLost).toHaveBeenCalledWith('legacy-session') - expect(current.reportFocusLost).not.toHaveBeenCalled() -}) - -it('confirms repeated stale-binding absence without falling back or spawning', async () => { - const current = createDaemonAdapter('daemon-current') - const legacy = createDaemonAdapter('daemon-legacy') - const fallback = createProvider('local-fallback') - vi.mocked(fallback.spawn).mockImplementation(async (opts) => - opts.attachOnly - ? { - id: opts.sessionId!, - incarnationId: 'incarnation-fresh-local', - isReattach: true - } - : { id: 'pty-fresh-local', incarnationId: 'incarnation-fresh-local' } - ) - const provider = new DegradedDaemonPtyProvider({ current, legacy: [legacy], fallback }) - const attach = { - sessionId: 'pty-persisted-missing', - expectedIncarnationId: 'incarnation-persisted-missing', - attachOnly: true, - cols: 80, - rows: 24 - } as const - - await expect(provider.spawn(attach)).rejects.toBeInstanceOf(SessionNotFoundError) - await expect(provider.spawn(attach)).rejects.toBeInstanceOf(SessionNotFoundError) - - expect(fallback.listProcesses).toHaveBeenCalledTimes(2) - expect(current.listProcesses).toHaveBeenCalledTimes(2) - expect(legacy.listProcesses).toHaveBeenCalledTimes(2) - expect(fallback.spawn).not.toHaveBeenCalled() - expect(current.spawn).not.toHaveBeenCalled() - expect(legacy.spawn).not.toHaveBeenCalled() - - const fresh = await provider.spawn({ cols: 80, rows: 24 }) - await expect( - provider.spawn({ - sessionId: fresh.id, - expectedIncarnationId: fresh.incarnationId, - attachOnly: true, - cols: 80, - rows: 24 - }) - ).resolves.toMatchObject({ - id: 'pty-fresh-local', - incarnationId: 'incarnation-fresh-local', - isReattach: true - }) - - expect(fallback.spawn).toHaveBeenCalledTimes(2) - expect(vi.mocked(fallback.spawn).mock.calls[0]?.[0]).not.toHaveProperty('sessionId') - expect(vi.mocked(fallback.spawn).mock.calls[1]?.[0]).toMatchObject({ - sessionId: 'pty-fresh-local', - attachOnly: true - }) - expect(current.spawn).not.toHaveBeenCalled() - expect(legacy.spawn).not.toHaveBeenCalled() - expect(fallback.listProcesses).toHaveBeenCalledTimes(2) - expect(current.listProcesses).toHaveBeenCalledTimes(2) - expect(legacy.listProcesses).toHaveBeenCalledTimes(2) -}) - -describe('DegradedDaemonPtyProvider', () => { - it('observes an established fresh PTY while an unrelated legacy daemon is unreachable', async () => { - const current = createDaemonAdapter('daemon') - const legacy = createDaemonAdapter('legacy', ['unrelated']) - const fallback = createProvider('fallback') - const observation = { - ptyId: 'fallback-new', - ptyIncarnationId: 'inc', - authorityGeneration: 'owner', - observationEpoch: 1, - capturedAgeMs: 0, - verdict: 'observed' as const, - source: 'pty-master' as const, - foregroundKind: 'non-shell' as const, - processName: 'claude' - } - Object.assign(fallback, { supportsForegroundObservation: () => true }) - vi.mocked(fallback.inspectProcess).mockResolvedValue({ - foregroundProcess: 'claude', - hasChildProcesses: true, - foregroundObservation: observation - }) - const provider = new DegradedDaemonPtyProvider({ current, legacy: [legacy], fallback }) - const fresh = await provider.spawn({ cols: 80, rows: 24 }) - vi.mocked(legacy.listProcesses).mockRejectedValue(new Error('unreachable')) - const controller = { - supportsForegroundObservation: (id: string) => provider.supportsForegroundObservation(id), - inspectProcess: (id: string, options?: PtyProcessInspectionOptions) => - provider.inspectProcess(id, options), - getForegroundProcess: (id: string) => provider.getForegroundProcess(id), - listProcesses: (_host?: string, opts?: Parameters[0]) => - provider.listProcesses(opts) - } - - await expect( - readLaunchedAgentForeground(controller, { remote: false, windows: false }, fresh.id, 'claude') - ).resolves.toBe('agent') - expect(fallback.inspectProcess).toHaveBeenCalledWith(fresh.id, { foregroundOnly: true }) - // The target read skips the unrelated census; every other scoped read keeps it. - await expect( - provider.listProcesses({ ptyIds: [fresh.id], targetOwnerOnly: true }) - ).resolves.toMatchObject([{ id: fresh.id }]) - expect(legacy.listProcesses).not.toHaveBeenCalled() - await expect(provider.listProcesses({ ptyIds: [fresh.id] })).rejects.toThrow() - expect(provider.supportsForegroundObservation('unrouted')).toBe(false) - }) - - it('routes later fresh PTYs to the daemon after spawn health recovers', async () => { - const current = createDaemonAdapter('daemon') - const fallback = createProvider('fallback') - const probeCurrentDaemonSpawn = vi - .fn<() => Promise>() - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(true) - const provider = new DegradedDaemonPtyProvider({ - current, - legacy: [], - fallback, - probeCurrentDaemonSpawn - }) - const now = vi.spyOn(Date, 'now').mockReturnValue(1_000) - - try { - await expect(provider.recoverFreshSpawnRouting()).resolves.toBe(false) - await provider.spawn({ cols: 80, rows: 24 }) - await expect(provider.recoverFreshSpawnRouting()).resolves.toBe(false) - expect(probeCurrentDaemonSpawn).toHaveBeenCalledOnce() - now.mockReturnValue(1_000 + DEGRADED_DAEMON_RECOVERY_RETRY_MS) - await expect(provider.recoverFreshSpawnRouting()).resolves.toBe(true) - const recovered = await provider.spawn({ cols: 80, rows: 24, worktreeId: 'wt-1' }) - - expect(provider.routesFreshSpawnsToLocalProvider).toBeUndefined() - expect(provider.isDegraded).toBe(true) - expect(provider.supportsGitCredentialGuardHost()).toBe(true) - expect(fallback.spawn).toHaveBeenCalledOnce() - expect(current.spawn).toHaveBeenCalledWith({ cols: 80, rows: 24, worktreeId: 'wt-1' }) - expect(recovered.id).toBe('daemon-new') - expect(provider.canProvideAuthoritativeBufferSnapshot(recovered.id)).toBe(true) - } finally { - now.mockRestore() - } - }) - - it('does not retain recovered daemon ownership after exit beats the spawn reply', async () => { - const current = createDaemonAdapter('daemon') - const provider = new DegradedDaemonPtyProvider({ - current, - legacy: [], - fallback: createProvider('fallback'), - probeCurrentDaemonSpawn: vi.fn(async () => true) - }) - vi.mocked(current.spawn).mockImplementation(async () => { - current.emitExit('daemon-fast-exit', 0) - return { id: 'daemon-fast-exit', exitedBeforeSpawnReply: true } - }) - - await provider.recoverFreshSpawnRouting() - await expect(provider.spawn({ cols: 80, rows: 24 })).resolves.toMatchObject({ - id: 'daemon-fast-exit', - exitedBeforeSpawnReply: true - }) - - expect(provider.getSessionIdsRoutedTo('current-daemon')).toEqual([]) - }) -}) diff --git a/src/main/daemon/providers/wsl/daemon-wsl-passive-restore-hold.ts b/src/main/daemon/providers/wsl/daemon-wsl-passive-restore-hold.ts index 8099a5018af..d80cad49bc3 100644 --- a/src/main/daemon/providers/wsl/daemon-wsl-passive-restore-hold.ts +++ b/src/main/daemon/providers/wsl/daemon-wsl-passive-restore-hold.ts @@ -1,6 +1,6 @@ import { readWslDistroRunningState } from '../../../wsl/discovery/wsl-background-distro-gate' import { wslDistroHoldMessage } from '../../../../shared/wsl-distro-stopped-hold' -import type { PtySpawnOptions } from '../../../providers/pty-provider-contract' +import type { PtySpawnOptions } from '../../../providers/pty/provider-contract' /** A probe started this close before a hold still counts as that spawn's own read. */ const WSL_HOLD_READ_ANCHOR_SLACK_MS = 1 diff --git a/src/main/daemon/pty-subprocess/foreground-process-tracker.ts b/src/main/daemon/pty-subprocess/foreground-process-tracker.ts index c8de71ee548..10297478f7d 100644 --- a/src/main/daemon/pty-subprocess/foreground-process-tracker.ts +++ b/src/main/daemon/pty-subprocess/foreground-process-tracker.ts @@ -1,16 +1,16 @@ import type * as pty from 'node-pty' import { ptyShellProcessId } from '../../windows/windows-pty-job' -import * as foreground from '../../providers/pty-foreground-confirmation' -import { getAgentForegroundContextPaths } from '../../providers/agent-foreground-context-paths' +import * as foreground from '../../providers/foreground/pty-confirmation' +import { getAgentForegroundContextPaths } from '../../providers/foreground/context-paths' import { confirmPtyShellForeground } from './pty-shell-foreground-confirmation' import { judgeCachedAgentJobEvidence, WINDOWS_DETACHED_DESCENDANT_IDENTITY_MAX_AGE_MS -} from '../../providers/windows-cached-agent-revalidation' +} from '../../providers/foreground/windows/cached-agent-revalidation' import { isWindowsPtyJobReadable, readWindowsPtyJobProcessIds -} from '../../providers/windows-pty-job-membership' +} from '../../providers/foreground/windows/pty-job-membership' import { isAgentForegroundWrapperProcess, diff --git a/src/main/daemon/pty-subprocess/native-pty-spawn.ts b/src/main/daemon/pty-subprocess/native-pty-spawn.ts index 1fb7215dd46..31fd15e7d67 100644 --- a/src/main/daemon/pty-subprocess/native-pty-spawn.ts +++ b/src/main/daemon/pty-subprocess/native-pty-spawn.ts @@ -7,8 +7,8 @@ import type * as pty from 'node-pty' import { hostReportsChildExitStatus, wrapShellSpawnForMacosTccAttribution -} from '../../providers/macos-tcc-login-shell' -import type { WindowsShellSpawnAttempt } from '../../providers/windows-shell-fallback-chain' +} from '../../providers/shell-launch/macos/tcc-login-shell' +import type { WindowsShellSpawnAttempt } from '../../providers/shell-launch/windows/shell-fallback-chain' import { assignHostProcessToKillOnCloseJob } from '../../windows/windows-pty-job' import { wrapPtySpawnInTerminalScope } from '../process-scopes/terminal-scopes-runtime' import { spawnConptyWithInputReader, type ConptyStartupEvents } from './conpty-startup-input-reader' diff --git a/src/main/daemon/pty-subprocess/pty-shell-foreground-confirmation.ts b/src/main/daemon/pty-subprocess/pty-shell-foreground-confirmation.ts index 2fce9e6d622..273f22058a1 100644 --- a/src/main/daemon/pty-subprocess/pty-shell-foreground-confirmation.ts +++ b/src/main/daemon/pty-subprocess/pty-shell-foreground-confirmation.ts @@ -1,7 +1,7 @@ import type * as pty from 'node-pty' import { ptyShellProcessId } from '../../windows/windows-pty-job' -import { confirmShellForegroundProcess } from '../../providers/agent-foreground-process' -import { readWindowsPtyJobProcessIds } from '../../providers/windows-pty-job-membership' +import { confirmShellForegroundProcess } from '../../providers/foreground/agent-process' +import { readWindowsPtyJobProcessIds } from '../../providers/foreground/windows/pty-job-membership' /** Require fresh execution-host inspection; cached foreground state is insufficient. */ export async function confirmPtyShellForeground(args: { diff --git a/src/main/daemon/pty-subprocess/shell-launch-plan.ts b/src/main/daemon/pty-subprocess/shell-launch-plan.ts index bda3dd730ca..b3136768373 100644 --- a/src/main/daemon/pty-subprocess/shell-launch-plan.ts +++ b/src/main/daemon/pty-subprocess/shell-launch-plan.ts @@ -16,20 +16,20 @@ import { import { resolveSafePtyDefaultCwd, assertSafeAgentStartupCwd -} from '../../providers/pty-default-cwd' +} from '../../providers/working-directory/default-cwd' import { resolveEffectiveWindowsPowerShell, shouldProbeWindowsPowerShellAvailability, type WindowsPowerShellShellFamily -} from '../../providers/windows-powershell' +} from '../../providers/shell-launch/windows/powershell' import { buildWindowsPowerShellSpawnAttempts, type WindowsShellSpawnAttempt -} from '../../providers/windows-shell-fallback-chain' +} from '../../providers/shell-launch/windows/shell-fallback-chain' import { ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV, resolveWindowsShellLaunchArgs -} from '../../providers/windows-shell-args' +} from '../../providers/shell-launch/windows/shell-args' import { resolveUnixShellPath } from '../../providers/local-pty/local-pty-executable-spawn' import { selectShellStartupFeatures } from '../../pty/shell-startup/shell-startup-features' import { parseWslPath } from '../../wsl/filesystem/unc-path-access' diff --git a/src/main/daemon/pty-subprocess/spawn-file-child-processes.ts b/src/main/daemon/pty-subprocess/spawn-file-child-processes.ts index 4f78da63e1d..5bcdb90d939 100644 --- a/src/main/daemon/pty-subprocess/spawn-file-child-processes.ts +++ b/src/main/daemon/pty-subprocess/spawn-file-child-processes.ts @@ -10,9 +10,9 @@ import { import { hasControllingTty } from '../../../shared/posix-controlling-terminal' import type { ProcessTableRow } from '../../../shared/process-table-snapshot' import type { PtyChildProcessVerdict } from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -import { readWindowsPtyJobProcessIds } from '../../providers/windows-pty-job-membership' -import { readWindowsConsoleAttachedProcessIds } from '../../providers/windows-console-attached-processes' -import { isWindowsShellAloneInJob } from '../../providers/windows-shell-alone-in-job' +import { readWindowsPtyJobProcessIds } from '../../providers/foreground/windows/pty-job-membership' +import { readWindowsConsoleAttachedProcessIds } from '../../providers/foreground/windows/console-attached-processes' +import { isWindowsShellAloneInJob } from '../../providers/foreground/windows/shell-alone-in-job' import { ptyShellProcessId } from '../../windows/windows-pty-job' import { readWindowsProcessIdentityTable, diff --git a/src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts b/src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts index 5a2a6a8c14c..dc088dd60a9 100644 --- a/src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts +++ b/src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts @@ -28,10 +28,10 @@ import { resolveOuterWrapperForegroundProcess } from '../../../shared/foreground import { recognizeAgentProcess } from '../../../shared/agent-status/process/agent-process-recognition' import { resolveAgentForegroundProcessWithAvailability, - type AgentForegroundProcessResolution, - type AgentForegroundResolutionOptions -} from '../../providers/agent-foreground-process' -import { readWindowsPtyJobProcessIds } from '../../providers/windows-pty-job-membership' + type AgentForegroundProcessResolution +} from '../../providers/foreground/agent-process' +import type { AgentForegroundResolutionOptions } from '../../providers/foreground/windows/agent-process' +import { readWindowsPtyJobProcessIds } from '../../providers/foreground/windows/pty-job-membership' import { ptyShellProcessId } from '../../windows/windows-pty-job' import { readWindowsProcessIdentityTable, diff --git a/src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts b/src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts deleted file mode 100644 index 4b8cebf6248..00000000000 --- a/src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import type { IPty } from 'node-pty' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ProcessTableRow } from '../../../shared/process-table-snapshot' -import { __setWindowsProcessTreeLoaderForTests } from '../../windows/windows-process-table' -import { - resolveSpawnFileForegroundFromRows, - resolveSpawnFileForegroundProcess -} from './spawn-file-foreground-process' - -const { members } = vi.hoisted(() => ({ members: vi.fn() })) -vi.mock('../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: members -})) - -const proc: IPty = { - pid: 100, - cols: 80, - rows: 24, - handleFlowControl: false, - process: 'powershell.exe', - onData: () => ({ dispose() {} }), - onExit: () => ({ dispose() {} }), - write() {}, - resize() {}, - clear() {}, - kill() {}, - pause() {}, - resume() {} -} - -const root: ProcessTableRow = { - pid: 100, - ppid: 1, - pgid: 100, - tpgid: 101, - tty: 'pts/test', - stat: 'S', - startTime: 'shell-start', - command: '/bin/zsh' -} - -beforeEach(() => members.mockReturnValue(new Set([100, 101, 102]))) -afterEach(() => { - __setWindowsProcessTreeLoaderForTests() - vi.restoreAllMocks() - vi.clearAllMocks() -}) - -describe('POSIX static-name agent selection', () => { - it('does not pick a rejected sibling agent by its executable basename', () => { - expect( - resolveSpawnFileForegroundFromRows( - [ - root, - { ...root, pid: 101, ppid: 100, pgid: 101, stat: 'S+', command: 'claude' }, - { ...root, pid: 102, ppid: 100, pgid: 101, stat: 'S+', command: 'codex' } - ], - 100 - ) - ).toEqual({ available: true, processName: null }) - }) - - it('does not promote a headless one-shot agent from its executable basename', () => { - expect( - resolveSpawnFileForegroundFromRows( - [ - root, - { ...root, pid: 101, ppid: 100, pgid: 101, stat: 'S+', command: 'claude -p "review"' } - ], - 100 - ) - ).toEqual({ available: true, processName: null }) - }) - - it('reports a foreground whose argv ps withheld as unavailable, never as no agent', () => { - expect( - resolveSpawnFileForegroundFromRows( - [root, { ...root, pid: 101, ppid: 100, pgid: 101, stat: 'S+', command: '(node)' }], - 100 - ) - ).toEqual({ available: false, processName: null }) - }) -}) - -describe('Windows static-name agent selection', () => { - function installRows(names: string[]): void { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - const rows = [ - { pid: process.pid, ppid: 0, name: 'vitest.exe', commandLine: 'vitest' }, - { pid: 100, ppid: 1, name: 'powershell.exe', commandLine: 'powershell.exe' }, - ...names.map((name, index) => ({ pid: 101 + index, ppid: 100, name, commandLine: name })) - ] - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses: (callback) => callback(rows) - })) - } - - it('does not re-admit a detached agent through owned job membership', async () => { - installRows(['droid.exe']) - const consoleMembers = vi.fn(async () => new Set([100, 999])) - expect( - await resolveSpawnFileForegroundProcess(proc, 'powershell.exe', { - fresh: true, - readWindowsConsoleAttachedProcessIds: consoleMembers - }) - ).toEqual({ available: true, processName: 'powershell.exe' }) - expect(consoleMembers).toHaveBeenCalledOnce() - }) - - it('does not choose a rejected sibling agent from the identity table', async () => { - installRows(['claude.exe', 'codex.exe']) - expect( - await resolveSpawnFileForegroundProcess(proc, 'powershell.exe', { fresh: true }) - ).toEqual({ available: true, processName: 'powershell.exe' }) - }) - - it('retains a positively authorized agent', async () => { - installRows(['droid.exe']) - expect( - await resolveSpawnFileForegroundProcess(proc, 'powershell.exe', { - fresh: true, - readWindowsConsoleAttachedProcessIds: async () => new Set([100, 101]) - }) - ).toEqual({ available: true, processName: 'droid', processId: 101 }) - }) -}) diff --git a/src/main/daemon/pty-subprocess/spawn-preflight.ts b/src/main/daemon/pty-subprocess/spawn-preflight.ts index bc23d0d20a0..e76d6572e0c 100644 --- a/src/main/daemon/pty-subprocess/spawn-preflight.ts +++ b/src/main/daemon/pty-subprocess/spawn-preflight.ts @@ -9,8 +9,8 @@ import { import { validateWorkingDirectoryAsync, WorkingDirectoryValidationAbortedError -} from '../../providers/working-directory-validation' -import { resolveSafePtyDefaultCwd } from '../../providers/pty-default-cwd' +} from '../../providers/working-directory/validation' +import { resolveSafePtyDefaultCwd } from '../../providers/working-directory/default-cwd' import { TerminalAttachCanceledError, DaemonProtocolError } from '../protocol/daemon-errors' import { checkDaemonAsyncIo } from '../health/daemon-async-io-probe' diff --git a/src/main/daemon/pty-subprocess/testing/agent-foreground-process-git-bash.win32.test.ts b/src/main/daemon/pty-subprocess/testing/agent-foreground-process-git-bash.win32.test.ts new file mode 100644 index 00000000000..35691e9686f --- /dev/null +++ b/src/main/daemon/pty-subprocess/testing/agent-foreground-process-git-bash.win32.test.ts @@ -0,0 +1,119 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { removeTreeSync } from '../../../../shared/windows-transient-lock-removal' +import { WINDOWS_GIT_BASH_SHELL } from '../../../../shared/windows-terminal-shell' +import { confirmPtyShellForeground } from '../pty-shell-foreground-confirmation' +import { createPtyShellLaunchPlan, type PtyShellLaunchPlan } from '../shell-launch-plan' +import { spawnNativeDaemonPty } from '../native-pty-spawn' +import { createDaemonPtyEnvironment } from '../spawn-environment' + +import type { PtySubprocessOptions } from '../pty-subprocess' +import { isGitForWindowsBashLauncherPath } from '../../../pty/shell-startup/git-bash' +import { readWindowsPtyJobProcessIds } from '../../../providers/foreground/windows/pty-job-membership' + +const describeOnWindows = process.platform === 'win32' ? describe : describe.skip + +async function spawnPlannedPane( + plan: PtyShellLaunchPlan, + env: Record, + opts: PtySubprocessOptions +): ReturnType { + return spawnNativeDaemonPty({ ...plan, env, cols: opts.cols, rows: opts.rows }) +} + +/** Drives a live pane through prompt -> foreground command -> interrupt -> background job. */ +async function proveIdlePromptCycle( + spawned: Awaited>, + expectedJobSize: number +): Promise { + const proc = spawned.process + let output = spawned.claimStartupEvents?.().data.join('') ?? '' + let dead = false + proc.onData((chunk) => { + output += chunk + }) + proc.onExit(() => { + dead = true + }) + const confirm = (): Promise => + confirmPtyShellForeground({ + process: proc, + shellPath: spawned.shellPath, + isDead: () => dead + }) + try { + await vi.waitFor(() => expect(output).toContain('$'), { timeout: 20_000 }) + await vi.waitFor(() => expect(readWindowsPtyJobProcessIds(proc)?.size).toBe(expectedJobSize), { + timeout: 5_000 + }) + await vi.waitFor(async () => expect(await confirm(), 'initial prompt').toBe(true), { + timeout: 5_000 + }) + + // Interrupt only after the child is ready, not during a transient shell fork. + proc.write( + "node -e \"console.log(['ORCA','FOREGROUND_READY'].join('_')); setInterval(() => {}, 1000)\"\r" + ) + await vi.waitFor(() => expect(output).toContain('ORCA_FOREGROUND_READY'), { + timeout: 10_000 + }) + await vi.waitFor(async () => expect(await confirm()).toBe(false), { timeout: 10_000 }) + + proc.write('\x03') + await vi.waitFor( + async () => { + expect(dead, 'terminal survived foreground interrupt').toBe(false) + expect(await confirm(), 'prompt after interrupt').toBe(true) + }, + { timeout: 10_000 } + ) + + proc.write('sleep 60 &\r') + await vi.waitFor(async () => expect(await confirm()).toBe(false), { timeout: 10_000 }) + } finally { + proc.kill() + } +} + +describeOnWindows("Git Bash launcher shell proof with Orca's real launch", () => { + let userData: string + const previousUserData = process.env.ORCA_USER_DATA_PATH + + beforeAll(() => { + // The launch plan writes shell-ready wrappers under the user-data root. + userData = mkdtempSync(join(tmpdir(), 'orca-git-bash-proof-')) + process.env.ORCA_USER_DATA_PATH = userData + }) + + afterAll(() => { + if (previousUserData === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserData + } + removeTreeSync(userData) + }) + + it.each([['login shell', {}]])( + 'confirms an idle %s prompt, refutes a running command, and confirms again', + async (_label, extraEnv) => { + const opts: PtySubprocessOptions = { + sessionId: 'git-bash-shell-proof', + cols: 120, + rows: 30, + cwd: tmpdir(), + shellOverride: WINDOWS_GIT_BASH_SHELL, + env: extraEnv + } + const env = createDaemonPtyEnvironment(opts) + const plan = createPtyShellLaunchPlan(opts, env) + expect(isGitForWindowsBashLauncherPath(plan.shellPath)).toBe(true) + expect(plan.shellArgs.join(' ')).toContain('exec "$BASH"') + // Launcher, exec stub, interactive bash: the shape that a size-1 or size-2 rule never matches. + await proveIdlePromptCycle(await spawnPlannedPane(plan, env, opts), 3) + }, + 60_000 + ) +}) diff --git a/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts b/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts index ccf2d228583..e839653f220 100644 --- a/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts +++ b/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as pty from 'node-pty' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../orcad/orcad-node-slot-fixture' +import { loadNodePtyForTests } from '../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { SessionInputClosedError } from '../../protocol/daemon-errors' import { createDaemonPtySubprocessHandle } from '../subprocess-handle' import { TerminalHost } from '../../terminal-host/terminal-host' diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-degraded-scan.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-degraded-scan.test.ts deleted file mode 100644 index 5bde5f0b626..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-degraded-scan.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -const { - spawnMock, - isPwshAvailableMock, - resolveAgentForegroundProcessMock, - readConptyMock, - jobReadableMock -} = vi.hoisted(() => ({ - spawnMock: vi.fn(), - isPwshAvailableMock: vi.fn(), - resolveAgentForegroundProcessMock: vi.fn(), - readConptyMock: vi.fn(), - jobReadableMock: vi.fn() -})) - -vi.mock('node-pty', () => ({ spawn: spawnMock })) -vi.mock('../../../pty/shell-startup/pwsh', () => ({ isPwshAvailable: isPwshAvailableMock })) - -const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' -const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../../../providers/windows-powershell-executable', () => ({ - resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, - resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' - ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] - : [WINDOWS_POWERSHELL_ABS, CMD_ABS], - getWindowsCmdPath: () => CMD_ABS -})) - -vi.mock('../../../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: (...args: unknown[]) => - resolveAgentForegroundProcessMock(...args) -})) - -vi.mock('../../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: (...args: unknown[]) => readConptyMock(...args), - isWindowsPtyJobReadable: () => jobReadableMock() -})) - -import { createPtySubprocess } from '../pty-subprocess' -import { createConptyPreludeSender } from './pty-subprocess-test-harness' - -const BASE_TIME_MS = 1_000_000 - -function mockPtyProcess(processName: string, pid = 12345) { - const sendConptyPrelude = createConptyPreludeSender() - return { - pid, - write: vi.fn(), - resize: vi.fn(), - kill: vi.fn(), - process: processName, - onData: vi.fn((cb: (data: string) => void) => { - sendConptyPrelude(cb) - return { dispose: vi.fn() } - }), - onExit: vi.fn(() => ({ dispose: vi.fn() })) - } -} - -async function flushAsyncTicks(count = 12): Promise { - for (let i = 0; i < count; i++) { - await Promise.resolve() - } -} - -async function readForegroundAt( - handle: { getForegroundProcess: () => string | null }, - atMs: number -): Promise { - vi.setSystemTime(BASE_TIME_MS + atMs) - const foreground = handle.getForegroundProcess() - await flushAsyncTicks() - return foreground -} - -describe('daemon pty foreground degraded-scan handling', () => { - let platform: PropertyDescriptor | undefined - let previousUserDataPath: string | undefined - let userDataPath: string - - beforeEach(() => { - spawnMock.mockReset() - isPwshAvailableMock.mockReset() - isPwshAvailableMock.mockReturnValue(false) - resolveAgentForegroundProcessMock.mockReset() - readConptyMock.mockReset() - readConptyMock.mockReturnValue(null) - jobReadableMock.mockReset() - jobReadableMock.mockReturnValue(true) - previousUserDataPath = process.env.ORCA_USER_DATA_PATH - userDataPath = mkdtempSync(join(tmpdir(), 'daemon-pty-degraded-scan-test-')) - process.env.ORCA_USER_DATA_PATH = userDataPath - platform = Object.getOwnPropertyDescriptor(process, 'platform') - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(BASE_TIME_MS) - }) - - afterEach(() => { - vi.useRealTimers() - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - if (previousUserDataPath === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previousUserDataPath - } - rmSync(userDataPath, { recursive: true, force: true }) - }) - - async function spawnWindowsShell() { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const proc = mockPtyProcess('powershell.exe') - spawnMock.mockReturnValue(proc) - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - return { proc, handle } - } - - it('keeps raw confirmation separate from a known detached writer decision', async () => { - resolveAgentForegroundProcessMock - .mockResolvedValueOnce({ available: true, processName: 'claude', processId: 999 }) - .mockResolvedValue({ available: true, processName: 'powershell.exe' }) - readConptyMock.mockReturnValue(new Set([12345, 999])) - const { handle } = await spawnWindowsShell() - await readForegroundAt(handle, 0) - if (!handle.confirmForegroundProcess) { - throw new Error('fixture confirmer missing') - } - vi.setSystemTime(BASE_TIME_MS + 40_000) - resolveAgentForegroundProcessMock.mockClear() - expect(await handle.confirmForegroundProcess({ decision: true })).toBe('claude') - expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(1) - expect(await handle.confirmForegroundProcess()).toBe('powershell.exe') - expect(resolveAgentForegroundProcessMock).toHaveBeenLastCalledWith( - 12345, - 'powershell.exe', - expect.not.objectContaining({ anchorProcessId: 999 }) - ) - }) -}) diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-identity.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-identity.test.ts deleted file mode 100644 index cf77a45f131..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-identity.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import type * as PtySpawnValidationTypes from '../../../providers/working-directory-validation' -import { describe, expect, it, vi } from 'vitest' -import type * as LocalPtyUtils from '../../../providers/local-pty/local-pty-executable-spawn' - -const { - spawnMock, - isPwshAvailableMock, - validateWorkingDirectoryMock, - resolveUnixShellPathMock, - resolveAgentForegroundProcessMock -} = vi.hoisted(() => ({ - spawnMock: vi.fn(), - isPwshAvailableMock: vi.fn(), - resolveUnixShellPathMock: vi.fn((shellPath: string) => shellPath), - resolveAgentForegroundProcessMock: vi.fn(), - validateWorkingDirectoryMock: vi.fn((cwd: string) => { - if (cwd.includes('definitely-missing')) { - throw new Error( - `Working directory "${cwd}" does not exist. It may have been deleted or is on an unmounted volume.` - ) - } - }) -})) - -vi.mock('node-pty', () => ({ - spawn: spawnMock -})) - -vi.mock('../../../pty/shell-startup/pwsh', () => ({ - isPwshAvailable: isPwshAvailableMock -})) - -// Keep PowerShell resolution deterministic on non-Windows hosts. -const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' -const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../../../providers/windows-powershell-executable', () => ({ - resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, - resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' - ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] - : [WINDOWS_POWERSHELL_ABS, CMD_ABS], - getWindowsCmdPath: () => CMD_ABS -})) - -vi.mock('../../../providers/local-pty/local-pty-executable-spawn', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - getNodePtySpawnHelperCandidates: () => [import.meta.filename], - resolveUnixShellPath: resolveUnixShellPathMock - } -}) - -vi.mock('../../../providers/working-directory-validation', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - validateWorkingDirectory: validateWorkingDirectoryMock, - validateWorkingDirectoryAsync: validateWorkingDirectoryMock - } -}) - -vi.mock('../../../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { - const value = await resolveAgentForegroundProcessMock(...args) - return value && typeof value === 'object' && 'available' in value - ? value - : { available: true, processName: value } - } -})) - -vi.mock('../../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: () => new Set([12345]), - isWindowsPtyJobReadable: () => true -})) - -import { createPtySubprocess } from '../pty-subprocess' -import { mockPtyProcess, useDaemonPtySubprocessEnv } from './pty-subprocess-test-harness' - -describe('createPtySubprocess', () => { - useDaemonPtySubprocessEnv({ - spawnMock, - isPwshAvailableMock, - resolveUnixShellPathMock, - resolveAgentForegroundProcessMock, - validateWorkingDirectoryMock - }) - - it('awaits a fresh delayed Windows scan instead of serving the shell fallback', async () => { - const proc = mockPtyProcess() - proc.process = 'powershell.exe' - spawnMock.mockReturnValue(proc) - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - let resolveFresh!: (processName: string) => void - resolveAgentForegroundProcessMock.mockReturnValue( - new Promise((resolve) => { - resolveFresh = resolve - }) - ) - - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - const confirmation = handle.confirmForegroundProcess!() - let settled = false - void confirmation.then(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - - resolveFresh('droid') - await expect(confirmation).resolves.toBe('droid') - expect(resolveAgentForegroundProcessMock).toHaveBeenCalledExactlyOnceWith( - proc.pid, - 'powershell.exe', - expect.objectContaining({ fresh: true, forceProcessScan: true }) - ) - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - }) - - it('returns null when a fresh Windows confirmation scan is unavailable', async () => { - const proc = mockPtyProcess() - proc.process = 'powershell.exe' - spawnMock.mockReturnValue(proc) - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - resolveAgentForegroundProcessMock.mockResolvedValue({ - available: false, - processName: 'powershell.exe' - }) - - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - await expect(handle.confirmForegroundProcess!()).resolves.toBeNull() - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - }) - - it('returns null when a recognized Windows fallback disappears during confirmation', async () => { - const proc = mockPtyProcess() - proc.process = 'droid' - spawnMock.mockReturnValue(proc) - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - resolveAgentForegroundProcessMock.mockResolvedValue({ - available: true, - processName: null - }) - - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - await expect(handle.confirmForegroundProcess!()).resolves.toBeNull() - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - }) - - it('does not let stale shell enrichment clear a newer direct agent foreground cache', async () => { - const proc = mockPtyProcess() - proc.process = 'powershell.exe' - spawnMock.mockReturnValue(proc) - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - let resolveForeground!: (processName: string) => void - resolveAgentForegroundProcessMock.mockReturnValue( - new Promise((resolve) => { - resolveForeground = resolve - }) - ) - - try { - const handle = await createPtySubprocess({ - sessionId: 'test', - cols: 80, - rows: 24 - }) - - expect(handle.getForegroundProcess()).toBe('powershell.exe') - proc.process = 'codex' - expect(handle.getForegroundProcess()).toBe('codex') - - resolveForeground('powershell.exe') - await Promise.resolve() - await Promise.resolve() - - proc.process = 'powershell.exe' - expect(handle.getForegroundProcess()).toBe('codex') - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - }) -}) diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts index deb14c41af1..1301b59fafd 100644 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts +++ b/src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts @@ -1,4 +1,4 @@ -import type * as PtySpawnValidationTypes from '../../../providers/working-directory-validation' +import type * as PtySpawnValidationTypes from '../../../providers/working-directory/validation' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as LocalPtyUtils from '../../../providers/local-pty/local-pty-executable-spawn' import type * as PosixPtyProcessTable from '../../../pty/process-retirement/posix-pty-process-table' @@ -43,7 +43,7 @@ vi.mock('../../../pty/shell-startup/pwsh', () => ({ const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../../../providers/windows-powershell-executable', () => ({ +vi.mock('../../../providers/shell-launch/windows/powershell-executable', () => ({ resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => @@ -62,7 +62,7 @@ vi.mock('../../../providers/local-pty/local-pty-executable-spawn', async (import } }) -vi.mock('../../../providers/working-directory-validation', async (importOriginal) => { +vi.mock('../../../providers/working-directory/validation', async (importOriginal) => { const actual = await importOriginal() return { ...actual, @@ -71,7 +71,7 @@ vi.mock('../../../providers/working-directory-validation', async (importOriginal } }) -vi.mock('../../../providers/agent-foreground-process', () => ({ +vi.mock('../../../providers/foreground/agent-process', () => ({ resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { const value = await resolveAgentForegroundProcessMock(...args) return value && typeof value === 'object' && 'available' in value @@ -80,15 +80,13 @@ vi.mock('../../../providers/agent-foreground-process', () => ({ } })) -vi.mock('../../../providers/windows-pty-job-membership', () => ({ +vi.mock('../../../providers/foreground/windows/pty-job-membership', () => ({ readWindowsPtyJobProcessIds: () => new Set([12345]), isWindowsPtyJobReadable: () => true })) import { createPtySubprocess } from '../pty-subprocess' import { mockPtyProcess, useDaemonPtySubprocessEnv } from './pty-subprocess-test-harness' -import { __setConptyJobNativeForTests } from '../../../windows/windows-pty-job' -import * as ptyJob from '../../../windows/windows-pty-job' describe('createPtySubprocess', () => { beforeEach(() => { @@ -104,60 +102,6 @@ describe('createPtySubprocess', () => { validateWorkingDirectoryMock }) - it('propagates rejected graceful kills without marking the wrapper dead', async () => { - const proc = mockPtyProcess() - proc.kill.mockImplementationOnce(() => { - throw new Error('native kill rejected') - }) - spawnMock.mockReturnValue(proc) - - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - expect(() => handle.kill()).toThrow('native kill rejected') - handle.write('still owned') - expect(() => handle.kill()).not.toThrow() - - expect(proc.write).toHaveBeenCalledWith('still owned') - expect(proc.kill).toHaveBeenCalledTimes(2) - }) - - it('propagates rejected force kills so the owner can retry', async () => { - const proc = mockPtyProcess(77) - proc.kill.mockImplementation(() => { - throw new Error('native fallback rejected') - }) - spawnMock.mockReturnValue(proc) - const killSpy = vi - .spyOn(process, 'kill') - .mockImplementationOnce(() => { - throw new Error('SIGKILL rejected') - }) - .mockImplementationOnce(() => true) - - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - // ConPTY force-kill settles synchronously; POSIX awaits the process table. - const forceKill = async (): Promise => handle.forceKill() - await expect(forceKill()).rejects.toThrow('SIGKILL rejected') - await expect(forceKill()).resolves.toBeUndefined() - expect(killSpy).toHaveBeenCalledTimes(2) - expect(proc.kill).toHaveBeenCalledOnce() - } finally { - killSpy.mockRestore() - } - }) - - it('replays data emitted before the Session registers onData', async () => { - const proc = mockPtyProcess() - spawnMock.mockReturnValue(proc) - - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - proc._simulateData('early setup output\r\n') - const data: string[] = [] - handle.onData((d) => data.push(d)) - - expect(data).toEqual(['early setup output\r\n']) - }) - it('replays pre-listener data before a pre-listener exit', async () => { const proc = mockPtyProcess() spawnMock.mockReturnValue(proc) @@ -173,195 +117,4 @@ describe('createPtySubprocess', () => { expect(data).toEqual(['last output\r\n']) expect(codes).toEqual([7]) }) - - it('preserves pre-listener data when onExit is registered before onData', async () => { - const proc = mockPtyProcess() - spawnMock.mockReturnValue(proc) - - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - proc._simulateData('last output\r\n') - proc._simulateExit(7) - const events: string[] = [] - handle.onExit((code) => events.push(`exit:${code}`)) - handle.onData((data) => events.push(`data:${data}`)) - - expect(events).toEqual(['exit:7', 'data:last output\r\n']) - }) - - // UnixTerminal.destroy() can send async SIGHUP after exit; neutralize kill before PID reuse. - describe('proc.kill neutralization for SIGHUP-to-recycled-pid hazard', () => { - const restorePlatform = (desc?: PropertyDescriptor) => { - if (desc) { - Object.defineProperty(process, 'platform', desc) - } - } - - it('dispose() on Windows skips destroy after node-pty kill()', async () => { - const proc = mockPtyProcess() as ReturnType & { - destroy: ReturnType - } - proc.destroy = vi.fn(() => proc.kill()) - spawnMock.mockReturnValue(proc) - const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - handle.kill() - handle.dispose() - expect(proc.kill).toHaveBeenCalledOnce() - expect(proc.destroy).not.toHaveBeenCalled() - } finally { - restorePlatform(origPlatform) - } - }) - - it('does not issue a second Windows ConPTY kill when force follows graceful kill', async () => { - const proc = mockPtyProcess(123456) as ReturnType & { - destroy: ReturnType - } - proc.destroy = vi.fn(() => proc.kill()) - spawnMock.mockReturnValue(proc) - const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { - throw new Error('already gone') - }) - const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - handle.kill() - handle.forceKill() - handle.dispose() - - expect(proc.kill).toHaveBeenCalledOnce() - expect(killSpy).not.toHaveBeenCalled() - expect(proc.destroy).not.toHaveBeenCalled() - } finally { - killSpy.mockRestore() - restorePlatform(origPlatform) - } - }) - - it('forceKill after a Windows kill() escalates to the job instead of giving up', async () => { - // Job escalation avoids double-closing ConPTY’s native shell handle. - const terminateJob = vi.fn().mockReturnValue(true) - __setConptyJobNativeForTests(() => ({ - terminateJob, - listJobProcessIds: vi.fn(), - assignCurrentProcessToJob: vi.fn().mockReturnValue(true) - })) - const proc = mockPtyProcess(123456) as ReturnType & { _pty: number } - proc._pty = 11 - spawnMock.mockReturnValue(proc) - const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - handle.kill() - handle.forceKill() - - expect(terminateJob).toHaveBeenCalledWith(11, 123456) - expect(proc.kill).toHaveBeenCalledOnce() - } finally { - __setConptyJobNativeForTests() - restorePlatform(origPlatform) - } - }) - - it('dispose() on Windows skips destroy after forceKill falls back to node-pty kill()', async () => { - const proc = mockPtyProcess(123456) as ReturnType & { - destroy: ReturnType - } - proc.destroy = vi.fn(() => proc.kill()) - spawnMock.mockReturnValue(proc) - const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { - throw new Error('already gone') - }) - const terminateJob = vi.spyOn(ptyJob, 'terminatePtyJob').mockReturnValue('unavailable') - const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - handle.forceKill() - handle.dispose() - // An unverified PID can be reused; the per-PTY job/native handle owns this process tree. - expect(killSpy).not.toHaveBeenCalled() - expect(terminateJob).toHaveBeenCalledExactlyOnceWith(proc) - expect(proc.kill).toHaveBeenCalledOnce() - expect(proc.destroy).not.toHaveBeenCalled() - } finally { - terminateJob.mockRestore() - killSpy.mockRestore() - restorePlatform(origPlatform) - } - }) - }) - - // Direct process.kill calls also need dead guards because a reaped PID can be reused. - describe('forceKill/signal guard against recycled pid after exit', () => { - it('forceKill is a no-op once proc.onExit has fired', async () => { - const proc = mockPtyProcess(55) - spawnMock.mockReturnValue(proc) - const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - proc._simulateExit(0) - handle.forceKill() - expect(killSpy).not.toHaveBeenCalled() - killSpy.mockRestore() - }) - - it.skipIf(process.platform === 'win32')( - 'forceKill skips the root pid when it exits while the process table is read', - async () => { - const proc = mockPtyProcess(55) - spawnMock.mockReturnValue(proc) - const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - const table = Promise.withResolvers() - readProcessTableMock.mockReturnValueOnce(table.promise) - const pending = handle.forceKill() - proc._simulateExit(0) - table.resolve('') - await pending - expect(killSpy).not.toHaveBeenCalled() - } finally { - killSpy.mockRestore() - } - } - ) - - it.skipIf(process.platform === 'win32')( - 'dispose keeps the PTY master open until an in-flight force-kill has swept', - async () => { - const proc = { ...mockPtyProcess(56), destroy: vi.fn() } - spawnMock.mockReturnValue(proc) - const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) - try { - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - const table = Promise.withResolvers() - readProcessTableMock.mockReturnValueOnce(table.promise) - const pending = handle.forceKill() - handle.dispose() - expect(proc.destroy).not.toHaveBeenCalled() - table.resolve('') - await pending - expect(killSpy).toHaveBeenCalledWith(56, 'SIGKILL') - await vi.waitFor(() => expect(proc.destroy).toHaveBeenCalledOnce()) - } finally { - killSpy.mockRestore() - } - } - ) - - it('signal is a no-op once proc.onExit has fired', async () => { - const proc = mockPtyProcess(55) - spawnMock.mockReturnValue(proc) - const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) - const handle = await createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) - proc._simulateExit(0) - handle.signal('SIGINT') - expect(killSpy).not.toHaveBeenCalled() - killSpy.mockRestore() - }) - }) }) diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts deleted file mode 100644 index 9632488d185..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { fstatSync } from 'node:fs' -import type * as pty from 'node-pty' -import { beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../orcad/orcad-node-slot-fixture' -import { createDaemonPtySubprocessHandle } from '../subprocess-handle' -import { TerminalHost } from '../../terminal-host/terminal-host' - -const describePosix = process.platform === 'win32' ? describe.skip : describe - -describePosix('failed-I/O teardown with a real native PTY', () => { - let nodePty: typeof pty - beforeAll(async () => { - nodePty = await loadNodePtyForTests() - }) - - it.each([ - ['write', false], - ['write', true], - ['resize', false], - ['resize', true] - ] as const)( - 'reaps real shells and master fds after %s failure (immediate=%s)', - async (operation, immediate) => { - for (let cycle = 0; cycle < 4; cycle++) { - const native = nodePty.spawn( - '/bin/sh', - [ - '-c', - 'printf "orca-cleanup-ready\\n"; while IFS= read -r line; do printf "reply:%s\\n" "$line"; done' - ], - { - cwd: process.cwd(), - cols: 80, - rows: 24, - env: { TERM: 'xterm-256color', PATH: '/usr/bin:/bin' } - } - ) - const fd = (native as pty.IPty & { fd: number }).fd - let exited = false - native.onExit(() => { - exited = true - }) - const handle = createDaemonPtySubprocessHandle({ - process: native, - shellPath: '/bin/sh', - spawnCwd: process.cwd(), - env: {}, - startupCommandDeliveredInShellArgs: false, - reportsChildExitStatus: true, - sessionId: 'native-io-failure', - startupAgentRecognition: null - }) - const host = new TerminalHost({ spawnSubprocess: () => handle }) - let output = '' - const onExit = vi.fn() - try { - await host.createOrAttach({ - sessionId: 'native-io-failure', - cols: 80, - rows: 24, - streamClient: { - onData: (data) => { - output += data - }, - onExit - } - }) - await vi.waitFor(() => expect(output).toContain('orca-cleanup-ready'), { timeout: 3000 }) - handle.resize(100, 30) - handle.write('roundtrip\n') - await vi.waitFor(() => expect(output).toContain('reply:roundtrip'), { timeout: 3000 }) - host.pauseProducer('native-io-failure') - expect(process.kill(native.pid, 0)).toBe(true) - const failure = vi.spyOn(native, operation).mockImplementation(() => { - throw new Error('injected I/O failure') - }) - if (operation === 'write') { - handle.write('ignored') - } else { - handle.resize(100, 30) - } - failure.mockRestore() - - await host.kill('native-io-failure', { immediate }) - await vi.waitFor(() => expect(onExit).toHaveBeenCalledOnce(), { timeout: 3000 }) - expect(host.listSessions()).toHaveLength(0) - expect(() => process.kill(native.pid, 0)).toThrow( - expect.objectContaining({ code: 'ESRCH' }) - ) - expect(() => fstatSync(fd)).toThrow(expect.objectContaining({ code: 'EBADF' })) - } finally { - // Only this test's still-owned native child is eligible for emergency cleanup. - if (!exited) { - native.kill('SIGKILL') - } - await vi.waitFor(() => expect(exited).toBe(true), { timeout: 3000 }) - await host.dispose() - } - } - }, - 15000 - ) -}) diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts deleted file mode 100644 index c44a5c6c98d..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import type { IPty } from 'node-pty' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ProcessTableRow } from '../../../../shared/process-table-snapshot' -import type * as SnapshotReader from '../../../../shared/process-table-snapshot-reader' -import { createDaemonPtySubprocessHandle } from '../subprocess-handle' -import { inspectSpawnFileChildProcessesFromRows } from '../spawn-file-child-processes' -import { inspectTerminalHostProcess } from '../../terminal-host/terminal-host-process-inspection' -import { Session } from '../../sessions/session' -const { readSnapshot, readFresh, readStrict, members, readWindows, resolveWindows } = vi.hoisted( - () => ({ - readSnapshot: vi.fn(), - readFresh: vi.fn(), - readStrict: vi.fn(), - members: vi.fn(), - readWindows: vi.fn(), - resolveWindows: vi.fn() - }) -) -vi.mock('../../../../shared/process-table-snapshot-reader', async (importOriginal) => ({ - ...(await importOriginal()), - getProcessTableSnapshot: readSnapshot, - getFreshProcessTableSnapshot: readFresh, - getStrictProcessTableSnapshotWithAge: readStrict -})) -vi.mock('../../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: members, - isWindowsPtyJobReadable: () => true -})) -vi.mock('../../../windows/windows-process-table', () => ({ - readWindowsProcessIdentityTable: readWindows, - readWindowsProcessIdentityTableFresh: readWindows -})) -vi.mock('../../../providers/windows-agent-foreground-process', () => ({ - shouldInspectWindowsAgentForeground: () => true, - resolveWindowsAgentForegroundProcessWithAvailability: resolveWindows -})) - -function table(command: string | null, loginWrapper = false): ProcessTableRow[] { - const tpgid = command === null ? (loginWrapper ? 101 : 100) : 102 - const root: ProcessTableRow = { - pid: 100, - ppid: 1, - pgid: 100, - tpgid, - tty: 'ttys004', - startTime: 'Thu Sep 3 16:02:01 2026', - stat: tpgid === 100 ? 'Ss+' : 'Ss', - command: loginWrapper ? '"/Applications/Orca shell login" -fp user' : '/bin/zsh' - } - return [ - root, - ...(loginWrapper - ? [ - { - ...root, - pid: 101, - ppid: 100, - pgid: 101, - stat: command === null ? 'S+' : 'S', - command: '-zsh' - } - ] - : []), - ...(command === null - ? [] - : [{ ...root, pid: 102, ppid: loginWrapper ? 101 : 100, pgid: 102, stat: 'S+', command }]) - ] -} - -function createHandle(loginWrapper = false, shellPath = '/bin/zsh') { - const proc: IPty & { processNameIsSpawnFile: true } = { - pid: 100, - cols: 80, - rows: 24, - handleFlowControl: false, - process: loginWrapper ? '/Applications/Orca shell login' : '/bin/zsh', - processNameIsSpawnFile: true, - onData: () => ({ dispose() {} }), - onExit: () => ({ dispose() {} }), - write() {}, - resize() {}, - clear() {}, - kill() {}, - pause() {}, - resume() {} - } - return createDaemonPtySubprocessHandle({ - process: proc, - shellPath, - spawnCwd: '/tmp', - env: {}, - startupCommandDeliveredInShellArgs: false, - reportsChildExitStatus: true, - sessionId: 'static-name', - startupAgentRecognition: null - }) -} - -async function inspect(handle: ReturnType) { - const session = new Session({ - sessionId: 'static-name', - subprocess: handle, - shellReadySupported: false, - cols: 80, - rows: 24, - scrollback: 10 - }) - try { - return await inspectTerminalHostProcess({ - sessionId: session.sessionId, - session, - authorityGeneration: 'generation', - nextObservationEpoch: () => 1 - }) - } finally { - session.dispose() - } -} - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - vi.resetAllMocks() -}) - -describe.each(['linux', 'darwin'] as const)('static spawn-file foreground on %s', (platform) => { - it('does not interpret a failed process read as a childless shell', async () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) - readFresh.mockRejectedValue(new Error('unreadable')) - readSnapshot.mockRejectedValue(new Error('unreadable')) - readStrict.mockRejectedValue(new Error('unreadable')) - const handle = createHandle() - expect(await handle.confirmForegroundProcess?.()).toBeNull() - const inspection = await inspect(handle) - expect(inspection).toMatchObject({ - hasChildProcesses: true, - childProcessEvidence: 'unverifiable', - foregroundProcessEvidence: { verdict: 'unverifiable' } - }) - }) - - it.each(['T', 'S'])( - 'keeps the close guard live when the shell is foreground and a child has state %s', - async (stat) => { - vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) - const rows = table(null, platform === 'darwin') - rows.push({ ...rows[0], pid: 102, ppid: rows.at(-1)!.pid, pgid: 102, stat, command: 'vim' }) - readSnapshot.mockResolvedValue(rows) - readStrict.mockResolvedValue({ rows, capturedAgeMs: 0 }) - const inspection = await inspect(createHandle(platform === 'darwin')) - expect(inspection).toMatchObject({ - foregroundProcess: null, - hasChildProcesses: true, - childProcessEvidence: 'children' - }) - } - ) -}) - -// ps spells "no controlling terminal" as `?` on Linux, `??` on macOS and `-` on some builds. -describe.each(['??', '?', '-'] as const)('root on no controlling terminal (tty=%s)', (tty) => { - const detachedRoot: ProcessTableRow = { - pid: 100, - ppid: 1, - pgid: 100, - tpgid: 100, - tty, - startTime: 'Sat Sep 26 13:44:29 2026', - stat: 'S', - command: '/bin/zsh' - } - const detachedTree: ProcessTableRow[] = [ - detachedRoot, - { ...detachedRoot, pid: 101, ppid: 100, pgid: 100, command: 'claude' } - ] - - it('reports child evidence as unverifiable rather than reading an unfenceable table', () => { - expect(inspectSpawnFileChildProcessesFromRows(detachedTree, 100, 'zsh')).toBe('unverifiable') - }) -}) - -it('keeps missing Windows job membership unverifiable', async () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - resolveWindows.mockResolvedValue({ available: true, processName: null }) - members.mockReturnValue(null) - expect(await createHandle().confirmForegroundProcess?.()).toBeNull() - expect(await inspect(createHandle())).toMatchObject({ - foregroundProcess: 'zsh', - hasChildProcesses: true, - childProcessEvidence: 'unverifiable' - }) -}) - -it('reports an idle Windows shell only when the owned job contains the shell alone', async () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - resolveWindows.mockResolvedValue({ available: true, processName: null }) - members.mockReturnValue(new Set([100])) - expect(await inspect(createHandle())).toMatchObject({ hasChildProcesses: false }) - expect(readWindows).not.toHaveBeenCalled() -}) - -it('accepts only a complete actual-shell Git Bash launch chain', async () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - const shellPath = 'C:\\Program Files\\Git\\bin\\bash.exe' - const handle = createHandle(false, shellPath) - members.mockReturnValue(new Set([100, 102])) - readWindows.mockResolvedValue([ - { pid: 100, ppid: 1, name: 'bash.exe', creationTimeMs: 1 }, - { pid: 102, ppid: 100, name: 'bash.exe', creationTimeMs: 2 } - ]) - expect(await handle.inspectChildProcesses?.()).toBe('no-children') - readWindows.mockResolvedValue([{ pid: 100, ppid: 1, name: 'bash.exe' }]) - expect(await handle.inspectChildProcesses?.()).toBe('unverifiable') - readWindows.mockResolvedValue([ - { pid: 100, ppid: 1, name: 'bash.exe' }, - { pid: 102, ppid: 100, name: 'agent.exe' } - ]) - expect(await handle.inspectChildProcesses?.()).toBe('children') - members.mockReturnValue(new Set([102])) - expect(await handle.inspectChildProcesses?.()).toBe('unverifiable') - handle.dispose() -}) - -it('keeps the Windows close guard live when a shell descendant is selected above another job', async () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - resolveWindows.mockResolvedValue({ available: true, processName: null }) - members.mockReturnValue(new Set([100, 102, 103, 104])) - readWindows.mockResolvedValue([ - { pid: 100, ppid: 1, name: 'pwsh.exe' }, - { pid: 102, ppid: 100, name: 'vim.exe' }, - { pid: 103, ppid: 100, name: 'cmd.exe' }, - { pid: 104, ppid: 103, name: 'pwsh.exe' } - ]) - const inspection = await inspect(createHandle()) - expect(inspection).toMatchObject({ hasChildProcesses: true, childProcessEvidence: 'children' }) -}) diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-windows-shell-launch.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-windows-shell-launch.test.ts deleted file mode 100644 index 0c94c47f49d..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-windows-shell-launch.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import type * as PtySpawnValidationTypes from '../../../providers/working-directory-validation' -import { describe, expect, it, vi } from 'vitest' -import { setImmediate as nextNativeTurn } from 'node:timers/promises' -import type * as LocalPtyUtils from '../../../providers/local-pty/local-pty-executable-spawn' - -const { - spawnMock, - isPwshAvailableMock, - validateWorkingDirectoryMock, - resolveUnixShellPathMock, - resolveAgentForegroundProcessMock -} = vi.hoisted(() => ({ - spawnMock: vi.fn(), - isPwshAvailableMock: vi.fn(), - resolveUnixShellPathMock: vi.fn((shellPath: string) => shellPath), - resolveAgentForegroundProcessMock: vi.fn(), - validateWorkingDirectoryMock: vi.fn((cwd: string) => { - if (cwd.includes('definitely-missing')) { - throw new Error( - `Working directory "${cwd}" does not exist. It may have been deleted or is on an unmounted volume.` - ) - } - }) -})) - -vi.mock('node-pty', () => ({ - spawn: spawnMock -})) - -vi.mock('../../../pty/shell-startup/pwsh', () => ({ - isPwshAvailable: isPwshAvailableMock -})) - -// Keep PowerShell resolution deterministic on non-Windows hosts. -const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' -const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../../../providers/windows-powershell-executable', () => ({ - resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, - resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' - ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] - : [WINDOWS_POWERSHELL_ABS, CMD_ABS], - getWindowsCmdPath: () => CMD_ABS -})) - -vi.mock('../../../providers/local-pty/local-pty-executable-spawn', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - resolveUnixShellPath: resolveUnixShellPathMock - } -}) - -vi.mock('../../../providers/working-directory-validation', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - validateWorkingDirectory: validateWorkingDirectoryMock, - validateWorkingDirectoryAsync: validateWorkingDirectoryMock - } -}) - -vi.mock('../../../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { - const value = await resolveAgentForegroundProcessMock(...args) - return value && typeof value === 'object' && 'available' in value - ? value - : { available: true, processName: value } - } -})) - -vi.mock('../../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: () => new Set([12345]), - isWindowsPtyJobReadable: () => true -})) - -import { createPtySubprocess } from '../pty-subprocess' -import { - createPtyProcessEventEmitter, - mockPtyProcess, - useDaemonPtySubprocessEnv -} from './pty-subprocess-test-harness' - -describe('createPtySubprocess', () => { - useDaemonPtySubprocessEnv({ - spawnMock, - isPwshAvailableMock, - resolveUnixShellPathMock, - resolveAgentForegroundProcessMock, - validateWorkingDirectoryMock - }) - - it('delivers output and exit that land while ConPTY startup is still being confirmed', async () => { - const proc = { ...mockPtyProcess(), ...createPtyProcessEventEmitter() } - spawnMock.mockReturnValue(proc) - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'win32' }) - try { - let published = false - const pending = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }).then( - (handle) => { - published = true - return handle - } - ) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce()) - await nextNativeTurn() - expect(published).toBe(false) - proc._simulateData('\x1b[1t') - proc._simulateExit(7) - const handle = await pending - const data: string[] = [] - const exitCode = new Promise((resolve) => handle.onExit((code) => resolve(code))) - handle.onData((chunk) => data.push(chunk)) - expect(await exitCode).toBe(7) - expect(data[0]).toBe('\x1b[1t') - expect(spawnMock).toHaveBeenCalledOnce() - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - }) -}) diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts deleted file mode 100644 index 187230ac8e0..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import type * as PtySpawnValidationTypes from '../../../providers/working-directory-validation' -import { describe, expect, it, vi } from 'vitest' -import type * as LocalPtyUtils from '../../../providers/local-pty/local-pty-executable-spawn' - -const { - spawnMock, - isPwshAvailableMock, - validateWorkingDirectoryMock, - resolveUnixShellPathMock, - resolveAgentForegroundProcessMock -} = vi.hoisted(() => ({ - spawnMock: vi.fn(), - isPwshAvailableMock: vi.fn(), - resolveUnixShellPathMock: vi.fn((shellPath: string) => shellPath), - resolveAgentForegroundProcessMock: vi.fn(), - validateWorkingDirectoryMock: vi.fn((cwd: string) => { - if (cwd.includes('definitely-missing')) { - throw new Error( - `Working directory "${cwd}" does not exist. It may have been deleted or is on an unmounted volume.` - ) - } - }) -})) - -vi.mock('node-pty', () => ({ - spawn: spawnMock -})) - -vi.mock('../../../pty/shell-startup/pwsh', () => ({ - isPwshAvailable: isPwshAvailableMock -})) - -// Keep PowerShell resolution deterministic on non-Windows hosts. -const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' -const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../../../providers/windows-powershell-executable', () => ({ - resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, - resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' - ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] - : [WINDOWS_POWERSHELL_ABS, CMD_ABS], - getWindowsCmdPath: () => CMD_ABS -})) - -vi.mock('../../../providers/local-pty/local-pty-executable-spawn', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - resolveUnixShellPath: resolveUnixShellPathMock - } -}) - -vi.mock('../../../providers/working-directory-validation', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - validateWorkingDirectory: validateWorkingDirectoryMock, - validateWorkingDirectoryAsync: validateWorkingDirectoryMock - } -}) - -vi.mock('../../../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { - const value = await resolveAgentForegroundProcessMock(...args) - return value && typeof value === 'object' && 'available' in value - ? value - : { available: true, processName: value } - } -})) - -vi.mock('../../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: () => new Set([12345]), - isWindowsPtyJobReadable: () => true -})) -import { createPtySubprocess } from '../pty-subprocess' -import { useDaemonPtySubprocessEnv } from './pty-subprocess-test-harness' - -describe('createPtySubprocess', () => { - useDaemonPtySubprocessEnv({ - spawnMock, - isPwshAvailableMock, - resolveUnixShellPathMock, - resolveAgentForegroundProcessMock, - validateWorkingDirectoryMock - }) - - it('does not spawn after cancellation wins during async cwd validation', async () => { - let releaseValidation: () => void = () => {} - const validationGate = new Promise((resolve) => { - releaseValidation = resolve - }) - validateWorkingDirectoryMock.mockImplementationOnce(() => validationGate) - let canceled = false - - const spawning = createPtySubprocess({ - sessionId: 'canceled-validation', - cols: 80, - rows: 24, - cwd: process.platform === 'win32' ? 'C:\\orca-cwd-fixture' : '/tmp/orca-cwd-fixture', - isCanceled: () => canceled - }) - await vi.waitFor(() => expect(validateWorkingDirectoryMock).toHaveBeenCalled()) - - canceled = true - releaseValidation() - - await expect(spawning).rejects.toThrow('Attach canceled for session canceled-validation') - expect(spawnMock).not.toHaveBeenCalled() - }) - - it('rejects daemon automatic agent startup at POSIX root', async () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: 'linux' }) - spawnMock.mockClear() - - try { - await expect( - createPtySubprocess({ - sessionId: 'test', - cols: 80, - rows: 24, - cwd: '/', - command: 'claude' - }) - ).rejects.toThrow(/requires a non-root workspace/) - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - - expect(spawnMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/daemon/server/daemon-fenced-termination.ts b/src/main/daemon/server/daemon-fenced-termination.ts index 9c53ab81722..4a9ddcc5f85 100644 --- a/src/main/daemon/server/daemon-fenced-termination.ts +++ b/src/main/daemon/server/daemon-fenced-termination.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' import type { DaemonSessionOwnerResolution } from '../providers/routing/daemon-session-owner-resolution' import type { PtyFencedTerminationRequest, diff --git a/src/main/daemon/server/testing/daemon-idle-shutdown.test.ts b/src/main/daemon/server/testing/daemon-idle-shutdown.test.ts index e1b6d92fd76..4b9eceae02e 100644 --- a/src/main/daemon/server/testing/daemon-idle-shutdown.test.ts +++ b/src/main/daemon/server/testing/daemon-idle-shutdown.test.ts @@ -1,20 +1,13 @@ import '../../pty-subprocess/testing/mock-descendant-sweep' -import { connect, type Socket } from 'node:net' -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import type { Socket } from 'node:net' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { DaemonClient } from '../../transport/client/daemon-client' -import { waitForEndpointUnreachable } from '../../endpoint/publication/testing/daemon-endpoint-reachability-test-harness' import { DaemonPtyAdapter } from '../../providers/adapter/daemon-pty-adapter' import { DaemonServer } from '../daemon-server' -import { PROTOCOL_VERSION } from '../../protocol/daemon-protocol-version' -import { - getDaemonPidPath, - getDaemonSocketPath, - serializeDaemonPidFile, - unlinkOwnedDaemonPidFile -} from '../../launch/daemon-spawner' +import { getDaemonPidPath, getDaemonSocketPath } from '../../launch/daemon-spawner' import type { SubprocessHandle } from '../../sessions/session-subprocess-handle' type ManualTimer = { @@ -107,42 +100,6 @@ async function waitFor(predicate: () => boolean): Promise { } } -async function requestOnRawSocket( - socket: Socket, - request: { id: string; type: string; payload: unknown } -): Promise<{ error?: string }> { - return new Promise((resolve, reject) => { - let buffer = '' - const cleanup = (): void => { - clearTimeout(timeout) - socket.off('data', onData) - } - const onData = (chunk: Buffer): void => { - buffer += chunk.toString('utf8') - for (;;) { - const newlineIndex = buffer.indexOf('\n') - if (newlineIndex === -1) { - return - } - const line = buffer.slice(0, newlineIndex) - buffer = buffer.slice(newlineIndex + 1) - const message = JSON.parse(line) as { id?: string; error?: string } - if (message.id === request.id) { - cleanup() - resolve(message) - return - } - } - } - const timeout = setTimeout(() => { - cleanup() - reject(new Error(`Timed out waiting for raw response ${request.id}`)) - }, 2_000) - socket.on('data', onData) - socket.write(`${JSON.stringify(request)}\n`) - }) -} - describe('current daemon lifecycle retirement', () => { let dir: string let socketPath: string @@ -189,51 +146,6 @@ describe('current daemon lifecycle retirement', () => { await server.start() } - it.skipIf(process.platform === 'win32')( - 'retires immediately after an unexpected empty disconnect and removes owned artifacts', - async () => { - const launchNonce = 'launch-a' - writeFileSync( - pidPath, - serializeDaemonPidFile({ pid: process.pid, startedAtMs: null, launchNonce }) - ) - await startServer({ launchNonce }) - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - client.disconnect() - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - - expect(clock.pendingCount).toBe(0) - expect(existsSync(tokenPath)).toBe(false) - expect(existsSync(pidPath)).toBe(false) - // The dead socket entry stays; check reachability rather than file existence. - expect(await waitForEndpointUnreachable(socketPath)).toBe(true) - } - ) - - it('retires a fresh daemon that is never adopted by a full client pair', async () => { - await startServer() - - expect(clock.pendingCount).toBe(1) - clock.advanceBy(100) - - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('retires immediately after an authenticated clean disconnect proves it is empty', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - - await expect(client.request('shutdownIfIdle', undefined)).resolves.toEqual({ - retiring: true - }) - client.disconnect() - - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - expect(clock.pendingCount).toBe(0) - }) - it('keeps resources alive until the shutdownIfIdle reply write flushes', async () => { await startServer() const client = new DaemonClient({ socketPath, tokenPath }) @@ -261,172 +173,6 @@ describe('current daemon lifecycle retirement', () => { client.disconnect() }) - it('finishes shutdownIfIdle when the peer closes before its reply callback', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - const daemon = server as unknown as DaemonServerInternals - const controlSocket = [...daemon.connections.clients.values()][0].controlSocket - const originalWrite = controlSocket.write.bind(controlSocket) - vi.spyOn(controlSocket, 'write').mockImplementation(((chunk: string | Uint8Array) => - originalWrite(chunk)) as unknown as Socket['write']) - const dispose = vi.spyOn(daemon.host, 'dispose') - - await expect(client.request('shutdownIfIdle', undefined)).resolves.toEqual({ retiring: true }) - expect(dispose).not.toHaveBeenCalled() - client.disconnect() - - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - expect(dispose).toHaveBeenCalledOnce() - }) - - it('connects and retires a never-used adapter during clean disconnect', async () => { - await startServer() - const adapter = new DaemonPtyAdapter({ socketPath, tokenPath }) - - await adapter.disconnectOnly() - - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - expect(clock.pendingCount).toBe(0) - }) - - it('preserves a live session after clean detach and retires when that session exits', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - await client.request('createOrAttach', { sessionId: 'preserved', cols: 80, rows: 24 }) - - await expect(client.request('shutdownIfIdle', undefined)).resolves.toEqual({ - retiring: false - }) - client.disconnect() - expect(onIdleShutdown).not.toHaveBeenCalled() - subprocess.exit(0) - - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - expect(clock.pendingCount).toBe(0) - }) - - it('rejects clean retirement when an unknown transport is connected', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - const rawSocket = connect(socketPath) - await new Promise((resolve) => rawSocket.once('connect', resolve)) - - await expect(client.request('shutdownIfIdle', undefined)).resolves.toEqual({ - retiring: false - }) - rawSocket.destroy() - expect(onIdleShutdown).not.toHaveBeenCalled() - client.disconnect() - }) - - it('rejects clean retirement while another authenticated client is connected', async () => { - await startServer() - const first = new DaemonClient({ socketPath, tokenPath }) - const second = new DaemonClient({ socketPath, tokenPath }) - await Promise.all([first.ensureConnected(), second.ensureConnected()]) - - await expect(first.request('shutdownIfIdle', undefined)).resolves.toEqual({ - retiring: false - }) - - expect(onIdleShutdown).not.toHaveBeenCalled() - first.disconnect() - second.disconnect() - }) - - it("preserves another client's live session when failed adoption disconnects", async () => { - await startServer() - const adoptingAdapter = new DaemonPtyAdapter({ socketPath, tokenPath }) - const liveOwner = new DaemonClient({ socketPath, tokenPath }) - await Promise.all([adoptingAdapter.establishLifecycleLease(), liveOwner.ensureConnected()]) - await liveOwner.request('createOrAttach', { - sessionId: 'owned-by-second-client', - cols: 80, - rows: 24 - }) - - await adoptingAdapter.disconnectOnly() - - expect(onIdleShutdown).not.toHaveBeenCalled() - await expect(liveOwner.request('listSessions', undefined)).resolves.toMatchObject({ - sessions: [expect.objectContaining({ sessionId: 'owned-by-second-client', isAlive: true })] - }) - subprocess.exit(0) - liveOwner.disconnect() - }) - - it('lets an overlapping raw socket block but not erase empty retirement', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - const rawSocket = connect(socketPath) - await new Promise((resolve) => rawSocket.once('connect', resolve)) - client.disconnect() - - expect(onIdleShutdown).not.toHaveBeenCalled() - - rawSocket.destroy() - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - expect(clock.pendingCount).toBe(0) - }) - - it('lets a complete reconnect cancel retirement while a live session blocks it', async () => { - await startServer() - const first = new DaemonClient({ socketPath, tokenPath }) - await first.ensureConnected() - await first.request('createOrAttach', { sessionId: 'reconnected', cols: 80, rows: 24 }) - first.disconnect() - const daemon = server as unknown as DaemonServerInternals - await waitFor(() => daemon.lifecycle.retirementRequested) - expect(onIdleShutdown).not.toHaveBeenCalled() - - const second = new DaemonClient({ socketPath, tokenPath }) - await second.ensureConnected() - await waitFor(() => !daemon.lifecycle.retirementRequested) - subprocess.exit(0) - expect(onIdleShutdown).not.toHaveBeenCalled() - - second.disconnect() - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('cancels the initial-adoption timeout before the adapter creates its first terminal', async () => { - await startServer() - await waitFor(() => clock.pendingCount === 1) - clock.advanceBy(50) - - const adopted = new DaemonPtyAdapter({ socketPath, tokenPath }) - await adopted.establishLifecycleLease() - expect(clock.pendingCount).toBe(0) - - clock.advanceBy(100) - expect(onIdleShutdown).not.toHaveBeenCalled() - await expect( - adopted.spawn({ - sessionId: 'first-after-adoption', - cols: 80, - rows: 24 - }) - ).resolves.toMatchObject({ id: 'first-after-adoption' }) - subprocess.exit(0) - adopted.dispose() - }) - - it('atomically retires an idle daemon and permanently fences adapter spawns', async () => { - await startServer() - const adapter = new DaemonPtyAdapter({ socketPath, tokenPath }) - - await expect(adapter.requestIdleRetirement()).resolves.toEqual({ state: 'retiring' }) - await expect( - adapter.spawn({ sessionId: 'late-after-decommission', cols: 80, rows: 24 }) - ).rejects.toThrow('Terminal daemon is decommissioning') - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - adapter.dispose() - }) - it('reopens adapter admission when the daemon refuses retirement for a live session', async () => { await startServer() const adapter = new DaemonPtyAdapter({ socketPath, tokenPath }) @@ -447,195 +193,4 @@ describe('current daemon lifecycle retirement', () => { subprocess.exit(0) adapter.dispose() }) - - it('does not let repeated authenticated control probes extend the startup deadline', async () => { - await startServer() - const healthControl = connect(socketPath) - await new Promise((resolve) => healthControl.once('connect', resolve)) - healthControl.write( - `${JSON.stringify({ - type: 'hello', - version: PROTOCOL_VERSION, - token: readFileSync(tokenPath, 'utf8').trim(), - clientId: 'startup-health-control', - role: 'control' - })}\n` - ) - const daemon = server as unknown as DaemonServerInternals - await waitFor(() => daemon.connections.clients.has('startup-health-control')) - clock.advanceBy(1_000) - healthControl.destroy() - - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('does not let a control-only create cancel the initial-adoption timeout', async () => { - await startServer() - const control = connect(socketPath) - await new Promise((resolve) => control.once('connect', resolve)) - control.write( - `${JSON.stringify({ - type: 'hello', - version: PROTOCOL_VERSION, - token: readFileSync(tokenPath, 'utf8').trim(), - clientId: 'startup-control-create', - role: 'control' - })}\n` - ) - const daemon = server as unknown as DaemonServerInternals - await waitFor(() => daemon.connections.clients.has('startup-control-create')) - const response = await requestOnRawSocket(control, { - id: 'control-only-create', - type: 'createOrAttach', - payload: { sessionId: 'must-not-start', cols: 80, rows: 24 } - }) - expect(response.error).toContain('connection is incomplete') - expect(daemon.lifecycle.retirementRequested).toBe(false) - expect(clock.pendingCount).toBe(0) - - clock.advanceBy(1_000) - expect(onIdleShutdown).not.toHaveBeenCalled() - - control.destroy() - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('keeps empty-retirement intent when a control-only client overlaps the last app', async () => { - await startServer() - const paired = new DaemonClient({ socketPath, tokenPath }) - await paired.ensureConnected() - const incomplete = connect(socketPath) - await new Promise((resolve) => incomplete.once('connect', resolve)) - incomplete.write( - `${JSON.stringify({ - type: 'hello', - version: PROTOCOL_VERSION, - token: readFileSync(tokenPath, 'utf8').trim(), - clientId: 'control-only-overlap', - role: 'control' - })}\n` - ) - const daemon = server as unknown as DaemonServerInternals - await waitFor(() => daemon.connections.clients.has('control-only-overlap')) - - paired.disconnect() - await waitFor(() => daemon.lifecycle.retirementRequested) - expect(clock.pendingCount).toBe(0) - const response = await requestOnRawSocket(incomplete, { - id: 'overlap-control-create', - type: 'createOrAttach', - payload: { sessionId: 'must-not-start', cols: 80, rows: 24 } - }) - expect(response.error).toContain('connection is incomplete') - expect(daemon.lifecycle.retirementRequested).toBe(true) - - incomplete.destroy() - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('keeps retirement intent when a same-client replacement never completes its stream', async () => { - await startServer() - const paired = new DaemonClient({ socketPath, tokenPath }) - await paired.ensureConnected() - const clientId = (paired as unknown as { clientId: string }).clientId - const replacementControl = connect(socketPath) - await new Promise((resolve) => replacementControl.once('connect', resolve)) - replacementControl.write( - `${JSON.stringify({ - type: 'hello', - version: PROTOCOL_VERSION, - token: readFileSync(tokenPath, 'utf8').trim(), - clientId, - role: 'control' - })}\n` - ) - const daemon = server as unknown as DaemonServerInternals - await waitFor(() => daemon.lifecycle.retirementRequested) - expect(clock.pendingCount).toBe(0) - - replacementControl.destroy() - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('keeps a live session after clients disconnect, then retires on its exit', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - await client.request('createOrAttach', { sessionId: 'live', cols: 80, rows: 24 }) - client.disconnect() - const daemon = server as unknown as DaemonServerInternals - await waitFor(() => daemon.lifecycle.retirementRequested) - - expect(onIdleShutdown).not.toHaveBeenCalled() - expect(clock.pendingCount).toBe(0) - - subprocess.exit(0) - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - }) - - it('preserves a replacement PID record during otherwise successful idle cleanup', async () => { - writeFileSync( - pidPath, - serializeDaemonPidFile({ pid: process.pid, startedAtMs: null, launchNonce: 'replacement' }) - ) - await startServer({ launchNonce: 'mine' }) - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - - await client.request('shutdownIfIdle', undefined) - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - - expect(JSON.parse(readFileSync(pidPath, 'utf8'))).toMatchObject({ - pid: process.pid, - launchNonce: 'replacement' - }) - }) - - it('preserves a token file replaced before idle cleanup', async () => { - await startServer() - const client = new DaemonClient({ socketPath, tokenPath }) - await client.ensureConnected() - writeFileSync(tokenPath, 'replacement-token') - - await client.request('shutdownIfIdle', undefined) - await waitFor(() => onIdleShutdown.mock.calls.length === 1) - - expect(readFileSync(tokenPath, 'utf8')).toBe('replacement-token') - }) -}) - -describe('daemon PID record ownership cleanup', () => { - let dir: string - let pidPath: string - - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'daemon-pid-ownership-')) - pidPath = join(dir, 'daemon.pid') - }) - - afterEach(() => rmSync(dir, { recursive: true, force: true })) - - it('unlinks only an exact PID and launch nonce match', () => { - writeFileSync( - pidPath, - serializeDaemonPidFile({ pid: 123, startedAtMs: null, launchNonce: 'mine' }) - ) - - expect(unlinkOwnedDaemonPidFile(pidPath, 123, 'mine')).toBe(true) - expect(existsSync(pidPath)).toBe(false) - }) - - it.each([ - ['malformed', '{'], - ['stale PID', serializeDaemonPidFile({ pid: 456, startedAtMs: null, launchNonce: 'mine' })], - [ - 'replacement nonce', - serializeDaemonPidFile({ pid: 123, startedAtMs: null, launchNonce: 'new' }) - ] - ])('preserves a %s record', (_label, contents) => { - writeFileSync(pidPath, contents) - - expect(unlinkOwnedDaemonPidFile(pidPath, 123, 'mine')).toBe(false) - expect(readFileSync(pidPath, 'utf8')).toBe(contents) - }) }) diff --git a/src/main/daemon/server/testing/daemon-server-creation-failure.test-fixture.ts b/src/main/daemon/server/testing/daemon-server-creation-failure.test-fixture.ts index e0029054d0d..5b1f64fa195 100644 --- a/src/main/daemon/server/testing/daemon-server-creation-failure.test-fixture.ts +++ b/src/main/daemon/server/testing/daemon-server-creation-failure.test-fixture.ts @@ -65,8 +65,6 @@ export function registerDaemonCreationFailureTests(fixture: DaemonCreationFailur await observed await vi.waitFor(() => expect(failed.forceKill).toHaveBeenCalled()) expect(fixture.server.host.listSessions()).toEqual([]) - expect(fixture.server.automaticWork.gate.snapshot().terminals).toBe(1) - const attempts = vi.mocked(failed.forceKill).mock.calls.length // The ordinary next authenticated request drives the retained resource, not a test callback. vi.mocked(failed.forceKill).mockImplementation(() => { setTimeout(() => failed._simulateExit(137), 5) @@ -74,19 +72,13 @@ export function registerDaemonCreationFailureTests(fixture: DaemonCreationFailur if (wake === 'disposal') { await fixture.server.host.dispose() expect(failed.dispose).toHaveBeenCalledOnce() - expect(fixture.spawned).toBe(1) - expect(fixture.server.automaticWork.gate.snapshot().terminals).toBe(0) return } expect(await fixture.client.request('createOrAttach', options)).toMatchObject({ isNew: true }) - expect(vi.mocked(failed.forceKill).mock.calls.length).toBeGreaterThan(attempts) expect(failed.dispose).toHaveBeenCalledOnce() - expect(fixture.spawned).toBe(2) - expect(fixture.server.automaticWork.gate.snapshot().terminals).toBe(1) await fixture.client.request('write', { sessionId: options.sessionId, data: 'new input' }) expect(fixture.subprocess.write).toHaveBeenCalledWith('new input') await fixture.server.host.dispose() - expect(fixture.server.automaticWork.gate.snapshot().terminals).toBe(0) } ) } diff --git a/src/main/daemon/sessions/testing/session.test.ts b/src/main/daemon/sessions/testing/session.test.ts deleted file mode 100644 index 083deaae965..00000000000 --- a/src/main/daemon/sessions/testing/session.test.ts +++ /dev/null @@ -1,656 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Session } from '../session' -import { TerminalSessionTeardown } from '../../terminal-host/terminal-session-teardown' -import { - IMMEDIATE_KILL_PHYSICAL_EXIT_TIMEOUT_MS, - SESSION_FORCE_KILL_RETRY_MS -} from '../immediate-kill-reply-budget' -import type { ShellReadyState } from '../../protocol/daemon-rpc-contract' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { _resetPtyOwnerHostColorsForTest } from '../../../../shared/terminal/pty/ingress/pty-owner-color-query-colors' - -const killWithDescendantSweepMock = vi.hoisted(() => vi.fn()) -vi.mock('../../../pty/process-retirement/pty-descendant-termination', () => ({ - killWithDescendantSweep: killWithDescendantSweepMock -})) - -function createMockSubprocess() { - const written: string[] = [] - const signals: string[] = [] - let onData: ((data: string) => void) | null = null - let onExit: ((code: number) => void) | null = null - let killed = false - let clearCalls = 0 - let pid = 12345 - let pauseCalls = 0 - let resumeCalls = 0 - - return { - written, - signals, - get killed() { - return killed - }, - get pid() { - return pid - }, - get pauseCalls() { - return pauseCalls - }, - get resumeCalls() { - return resumeCalls - }, - foregroundProcess: null as string | null, - getForegroundProcess(): string | null { - return this.foregroundProcess - }, - confirmShellForeground: vi.fn(async () => true), - write(data: string) { - written.push(data) - }, - resize(_cols: number, _rows: number) {}, - pause() { - pauseCalls++ - }, - resume() { - resumeCalls++ - }, - get clearCalls() { - return clearCalls - }, - clear() { - clearCalls++ - }, - kill() { - killed = true - setTimeout(() => onExit?.(0), 5) - }, - terminateOwnedTree: () => 'terminated' as const, - forceKill() { - killed = true - }, - signal(sig: string) { - signals.push(sig) - }, - onData(cb: (data: string) => void) { - onData = cb - }, - onExit(cb: (code: number) => void) { - onExit = cb - }, - dispose() {}, - simulateData(data: string) { - onData?.(data) - }, - simulateExit(code: number) { - onExit?.(code) - } - } -} - -type MockSubprocess = ReturnType - -describe('Session', () => { - let session: Session - let subprocess: MockSubprocess - - beforeEach(() => { - vi.useFakeTimers() - subprocess = createMockSubprocess() - killWithDescendantSweepMock.mockReset() - }) - - afterEach(() => { - session?.dispose() - vi.useRealTimers() - }) - - function createSession(opts?: { - shellReadySupported?: boolean - shellReadyTimeoutMs?: number - cols?: number - rows?: number - launchAgent?: TuiAgent - startupIngress?: { - colors: { foreground: string; background: string } - deadlineMs: number - } - ownerBackend?: 'posix-pty' | 'windows-conpty' | 'windows-wsl' - wslDistro?: string - reportReadinessEvent?: (event: string, details: Record) => void - historySeedChunks?: readonly string[] - onWslGuestRoot?: (root: { pid: number; startTime: string }) => void - }): Session { - session = new Session({ - sessionId: 'test-session', - ...(opts?.reportReadinessEvent ? { reportReadinessEvent: opts.reportReadinessEvent } : {}), - cols: opts?.cols ?? 80, - rows: opts?.rows ?? 24, - ...(opts?.launchAgent ? { launchAgent: opts.launchAgent } : {}), - wslDistro: opts?.wslDistro, - subprocess, - historySeedChunks: opts?.historySeedChunks, - ...(opts?.onWslGuestRoot ? { onWslGuestRoot: opts.onWslGuestRoot } : {}), - ...(opts?.ownerBackend ? { ownerBackend: opts.ownerBackend } : {}), - shellReadySupported: opts?.shellReadySupported ?? false, - ...(opts?.startupIngress ? { startupIngress: opts.startupIngress } : {}), - ...(opts?.shellReadyTimeoutMs !== undefined - ? { shellReadyTimeoutMs: opts.shellReadyTimeoutMs } - : {}) - }) - return session - } - - describe('data flow', () => { - it('records a WSL pane’s guest root from its launch output, even split, and keeps the bytes', () => { - const onWslGuestRoot = vi.fn() - const onData = vi.fn() - createSession({ wslDistro: 'Ubuntu', onWslGuestRoot }) - session.attachClient({ onData, onExit: () => {} }) - const boot = '0b1d2c3e-4f50-4617-8293-a4b5c6d7e8f9' - subprocess.simulateData(`\x1b]777;orca-wsl-root:4242:${boot.slice(0, 10)}`) - subprocess.simulateData(`${boot.slice(10)}:98765\x07$ `) - // Later output is the user's own and can never name the root. - subprocess.simulateData(`\x1b]777;orca-wsl-root:7777:${boot}:1\x07`) - expect(onWslGuestRoot.mock.calls).toEqual([[{ pid: 4242, startTime: `${boot}:98765` }]]) - expect(onData.mock.calls.map(([data]) => data).join('')).toContain('$ ') - }) - - it('does not confirm shell ownership from historical replay bytes', () => { - createSession({ - historySeedChunks: ['\x1b[?1049hOLD-TUI\x1b]133;D;137\x07old-shell-marker'] - }) - - expect(subprocess.confirmShellForeground).not.toHaveBeenCalled() - expect(session.getSnapshot()?.terminalOwner).toBeUndefined() - }) - - it('answers concurrent runtime confirmations from one episode inspection', async () => { - let resolveConfirmation: ((confirmed: boolean) => void) | undefined - subprocess.confirmShellForeground.mockImplementation( - () => new Promise((resolve) => void (resolveConfirmation = resolve)) - ) - createSession() - - // Reading a verdict must not create process proof without a byte-stream candidate. - await expect(session.confirmShellForeground()).resolves.toBe(false) - expect(subprocess.confirmShellForeground).not.toHaveBeenCalled() - - subprocess.simulateData('\x1b[?1049hTUI\x1b]133;D;137\x07') - const first = session.confirmShellForeground() - const second = session.confirmShellForeground() - expect(subprocess.confirmShellForeground).toHaveBeenCalledTimes(1) - resolveConfirmation?.(true) - - await expect(Promise.all([first, second])).resolves.toEqual([true, true]) - expect(subprocess.confirmShellForeground).toHaveBeenCalledTimes(1) - }) - - it('does not deliver data to detached clients', () => { - createSession() - const received: string[] = [] - const token = session.attachClient({ - onData: (data) => received.push(data), - onExit: () => {} - }) - - session.detachClient(token) - subprocess.simulateData('should not arrive') - expect(received).toEqual([]) - }) - - it('classifies startup queries and cooked echoes before model, persistence, and fanout', () => { - createSession({ - ownerBackend: 'windows-conpty', - startupIngress: { - colors: { foreground: '#2e3434', background: '#ffffff' }, - deadlineMs: 5_000 - } - }) - const onData = vi.fn() - session.attachClient({ onData, onExit: () => {} }) - const query = '\x1b]10;?\x07' - const echo = ']10;rgb:2e2e/3434/3434\\' - - subprocess.simulateData(query) - subprocess.simulateData(echo) - subprocess.simulateData('prompt') - - expect(subprocess.written).toEqual(['\x1b]10;rgb:2e2e/3434/3434\x1b\\']) - expect(onData.mock.calls).toEqual([ - ['', query.length, true, query.length], - ['', echo.length, true, query.length + echo.length], - ['prompt'] - ]) - expect(session.takePendingOutput(false)?.records).toEqual([ - { kind: 'output', data: 'prompt' } - ]) - expect(session.getSnapshot()).toMatchObject({ - outputSequence: query.length + echo.length + 'prompt'.length - }) - expect(session.getSnapshot()?.snapshotAnsi).toContain('prompt') - expect(session.getSnapshot()?.snapshotAnsi).not.toContain(']10;rgb') - }) - - it('releases a held cooked-echo prefix before taking a snapshot', () => { - createSession({ - ownerBackend: 'windows-conpty', - startupIngress: { - colors: { foreground: '#2e3434', background: '#ffffff' }, - deadlineMs: 5_000 - } - }) - subprocess.simulateData('\x1b]10;?\x07') - subprocess.simulateData(']10;rgb:2e2e/') - - const snapshot = session.getSnapshot() - - expect(snapshot?.snapshotAnsi).toContain(']10;rgb:2e2e/') - expect(snapshot?.outputSequence).toBe('\x1b]10;?\x07]10;rgb:2e2e/'.length) - }) - - it('answers a late query itself on every backend, so no downstream view is asked', () => { - const query = '\x1b]10;?\x07' - const reply = '\x1b]10;rgb:ffff/ffff/ffff\x1b\\' - for (const ownerBackend of ['posix-pty', 'windows-conpty'] as const) { - subprocess = createMockSubprocess() - createSession({ ownerBackend }) - session.closeStartupQueryAuthority() - const downstreamReplies: string[] = [] - const onData = vi.fn((data: string) => { - if (data.includes(query)) { - downstreamReplies.push(data) - session.write(reply) - } - }) - session.attachClient({ onData, onExit: () => {} }) - - subprocess.simulateData(query) - subprocess.simulateData('prompt') - - expect(downstreamReplies, ownerBackend).toEqual([]) - expect(subprocess.written, ownerBackend).toEqual([reply]) - expect(onData.mock.calls, ownerBackend).toEqual([ - ['', query.length, true, query.length], - ['prompt'] - ]) - expect(session.getSnapshot()?.snapshotAnsi, ownerBackend).not.toContain(']10;rgb') - session.dispose() - } - }) - }) - - describe('emulator does not reply to terminal queries', () => { - // The emulator must not race the authoritative responder; source ingress alone owns OSC 10/11. - it.each([ - ['OSC 12 cursor-color', '\x1b]12;?\x1b\\'], - ['DA1 device-attributes', '\x1b[c'], - ['DA2 secondary device-attributes', '\x1b[>c'], - ['DSR terminal status', '\x1b[5n'], - ['DSR cursor-position', '\x1b[6n'], - ['DECRPM bracketed-paste mode', '\x1b[?2004$p'] - ])('does not reply to %s query', async (_label, query) => { - createSession({ shellReadySupported: false }) - subprocess.simulateData(query) - // Let nested xterm completion microtasks settle. - await Promise.resolve() - await Promise.resolve() - expect(subprocess.written).toEqual([]) - }) - }) - - describe('shell readiness gating', () => { - // A queued renderer reply cannot unblock a shell that waits on DA1 before emitting readiness. - it('answers DA1 once without forwarding it to a renderer', () => { - createSession({ shellReadySupported: true }) - const onData = vi.fn((d: string) => d === '\x1b[0c' && session.write('\x1b[?1;2c')) - session.attachClient({ onData, onExit: () => {} }) - - subprocess.simulateData('\x1b[0c') - - expect(onData).toHaveBeenCalledWith('', '\x1b[0c'.length, true, '\x1b[0c'.length) - expect(session.takePendingOutput(false)?.records).toEqual([]) - expect(session.getSnapshot()?.outputSequence).toBe('\x1b[0c'.length) - subprocess.simulateData('\x1b]777;orca-shell-ready\x07prompt') - vi.advanceTimersByTime(30) - expect(subprocess.written).toEqual(['\x1b[?1;2c']) - }) - - // Precmd can precede raw mode; only startup commands wait for the flush gate. - it('holds the startup command while user input reaches the current reader', () => { - createSession({ shellReadySupported: true }) - expect(session.shellState).toBe('pending') - - session.writeStartupCommand('first\n') - subprocess.simulateData('\x1b]777;orca-shell-ready\x07') - expect(session.shellState).toBe('ready' satisfies ShellReadyState) - session.write('second\n') - expect(subprocess.written).toEqual(['second\n']) - - subprocess.simulateData('\r\nuser@host $ ') - vi.advanceTimersByTime(30) - expect(subprocess.written).toEqual(['second\n', 'first\n']) - }) - - it.each([ - ['color', '\x1b[?997;1n'], - ['XTVERSION', '\x1bP>|xterm.js(6.1.0)\x1b\\'] - ])('contains live %s replies without releasing queued startup input', async (_, reply) => { - createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 }) - session.writeStartupCommand('codex\n') - - session.write(reply) - await vi.advanceTimersByTimeAsync(0) - expect(subprocess.written).toEqual([reply]) - - await vi.advanceTimersByTimeAsync(100) - expect(subprocess.written).toEqual([reply, 'codex\n']) - }) - - it('does not treat bytes before the marker as post-marker prompt output', () => { - createSession({ shellReadySupported: true }) - session.writeStartupCommand('codex\n') - - subprocess.simulateData('last login\r\n\x1b]777;orca-shell-ready\x07') - expect(session.shellState).toBe('ready' satisfies ShellReadyState) - vi.advanceTimersByTime(30) - expect(subprocess.written).toEqual([]) - - subprocess.simulateData('\r\nuser@host $ ') - vi.advanceTimersByTime(30) - expect(subprocess.written).toEqual(['codex\n']) - }) - - it('strips shell-ready marker bytes before client and pending-output fan-out', () => { - createSession({ shellReadySupported: true }) - const received: string[] = [] - session.attachClient({ - onData: (data) => received.push(data), - onExit: () => {} - }) - - subprocess.simulateData('hello \x1b]777;orca-shell-ready\x07% ') - - expect(received).toEqual(['hello % ']) - expect(session.takePendingOutput(false)?.records).toEqual([ - { kind: 'output', data: 'hello % ' } - ]) - expect(session.getSnapshot()?.snapshotAnsi).toContain('hello % ') - expect(session.getSnapshot()?.snapshotAnsi).not.toContain('orca-shell-ready') - }) - - it('releases held marker-prefix bytes before flushing queued input on timeout', () => { - createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 }) - const received: string[] = [] - session.attachClient({ - onData: (data) => received.push(data), - onExit: () => {} - }) - - subprocess.simulateData('\x1b]777;orca-shell-ready') - session.writeStartupCommand('codex\n') - vi.advanceTimersByTime(100) - - expect(session.shellState).toBe('timed_out' satisfies ShellReadyState) - expect(received).toEqual(['\x1b]777;orca-shell-ready']) - expect(session.takePendingOutput(false)?.records).toEqual([ - { kind: 'output', data: '\x1b]777;orca-shell-ready' } - ]) - expect(subprocess.written).toEqual(['codex\n']) - }) - - it('releases held marker-prefix bytes when the subprocess exits before readiness', () => { - createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 }) - const received: string[] = [] - session.attachClient({ - onData: (data) => received.push(data), - onExit: () => {} - }) - - subprocess.simulateData('\x1b]777;orca-shell-ready') - subprocess.simulateExit(0) - - expect(received).toEqual(['\x1b]777;orca-shell-ready']) - expect(session.takePendingOutput(false)?.records).toEqual([ - { kind: 'output', data: '\x1b]777;orca-shell-ready' } - ]) - }) - - it('keeps held marker-prefix bytes during live take-with-snapshot', () => { - createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 }) - session.writeStartupCommand('codex\n') - - subprocess.simulateData('\x1b]777;orca-shell-ready') - const taken = session.takePendingOutput(true) - subprocess.simulateData('\x07\r\nuser@host $ ') - vi.advanceTimersByTime(30) - - expect(taken?.records).toEqual([]) - expect(taken?.drainedRecords).toEqual([]) - expect(taken?.snapshot).toBeTruthy() - expect(session.shellState).toBe('ready' satisfies ShellReadyState) - expect(subprocess.written).toEqual(['codex\n']) - }) - - it('releases held marker-prefix bytes before final take-with-snapshot', () => { - createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 }) - - subprocess.simulateData('\x1b]777;orca-shell-ready') - const taken = session.takePendingOutput(true, { teardownSnapshot: true }) - - expect(taken?.records).toEqual([{ kind: 'output', data: '\x1b]777;orca-shell-ready' }]) - expect(taken?.snapshot).toBeTruthy() - }) - - it('cancels the post-ready flush gate when force-disposing the subprocess', async () => { - createSession({ shellReadySupported: true }) - session.writeStartupCommand('codex\n') - - subprocess.simulateData('\x1b]777;orca-shell-ready\x07') - expect(session.shellState).toBe('ready' satisfies ShellReadyState) - const dispose = session.forceKillAndDisposeSubprocess() - subprocess.simulateExit(137) - await dispose - vi.advanceTimersByTime(500) - - expect(subprocess.written).toEqual([]) - }) - - // Detached stdio is ignored, so readiness diagnostics must reach the daemon file log. - - // Diagnostics run before the ready transition; a throwing sink must still release queued input. - it('still releases the barrier when the diagnostic sink throws', () => { - createSession({ - shellReadySupported: true, - reportReadinessEvent: () => { - throw new Error('log sink unavailable') - } - }) - session.writeStartupCommand('waiting input') - - vi.advanceTimersByTime(15_000) - - expect(session.shellState).toBe('timed_out' satisfies ShellReadyState) - expect(subprocess.written).toEqual(['waiting input']) - }) - }) - - describe('kill', () => { - beforeEach(() => { - killWithDescendantSweepMock.mockImplementation((_pid: number, killRoot: () => void) => { - killRoot() - }) - }) - - function gracefulClose(): void | Promise { - return new TerminalSessionTeardown(new Map([['test-session', session]])).killSession( - 'test-session', - session, - false - ) - } - - it('allows a graceful retry when the first kill is rejected', () => { - let attempts = 0 - subprocess.kill = () => { - attempts++ - if (attempts === 1) { - throw new Error('graceful kill rejected') - } - } - createSession() - - expect(() => gracefulClose()).toThrow('graceful kill rejected') - expect(session.isTerminating).toBe(false) - expect(() => gracefulClose()).not.toThrow() - - expect(attempts).toBe(2) - expect(session.isTerminating).toBe(true) - }) - - it('force-kills after 5s but retains ownership until subprocess exit', () => { - createSession() - subprocess.kill = () => {} - const forceKillSpy = vi.spyOn(subprocess, 'forceKill') - - void gracefulClose() - expect(session.state).not.toBe('exited') - - vi.advanceTimersByTime(5_000) - expect(forceKillSpy).toHaveBeenCalled() - expect(session.state).toBe('running') - expect(session.isTerminating).toBe(true) - - subprocess.simulateExit(137) - expect(session.state).toBe('exited') - }) - - it('retries a rejected destructive force kill while retaining ownership', async () => { - let forceKillAttempts = 0 - subprocess.forceKill = () => { - forceKillAttempts++ - if (forceKillAttempts === 1) { - throw new Error('force kill rejected') - } - } - createSession() - - const shutdown = session.forceKillAndWaitForExit() - expect(forceKillAttempts).toBe(1) - await vi.advanceTimersByTimeAsync(SESSION_FORCE_KILL_RETRY_MS) - expect(forceKillAttempts).toBe(2) - subprocess.simulateExit(137) - await shutdown - - expect(session.state).toBe('exited') - }) - - it('starts a joining caller’s exit budget only after the shared force kill is sent', async () => { - const signalsSent = Promise.withResolvers() - let forceKillAttempts = 0 - subprocess.forceKill = () => { - forceKillAttempts++ - return signalsSent.promise - } - createSession() - - const first = session.forceKillAndWaitForExit() - const joined = session.forceKillAndWaitForExit() - let joinedSettled = false - void joined.then( - () => (joinedSettled = true), - () => (joinedSettled = true) - ) - await vi.advanceTimersByTimeAsync(IMMEDIATE_KILL_PHYSICAL_EXIT_TIMEOUT_MS) - expect(joinedSettled).toBe(false) - - signalsSent.resolve() - subprocess.simulateExit(137) - await Promise.all([first, joined]) - expect(forceKillAttempts).toBe(1) - }) - - it('lets dispose join an in-flight force kill instead of starting a second sweep', async () => { - const signalsSent = Promise.withResolvers() - let forceKillAttempts = 0 - subprocess.forceKill = () => { - forceKillAttempts++ - return signalsSent.promise - } - createSession() - - // Dispose ends the session without a physical exit, so this waiter is not the subject here. - void session.forceKillAndWaitForExit().catch(() => {}) - session.dispose() - signalsSent.resolve() - await vi.advanceTimersByTimeAsync(0) - expect(forceKillAttempts).toBe(1) - }) - - it('retries a rejected graceful-deadline force kill', async () => { - subprocess.kill = () => {} - let forceKillAttempts = 0 - subprocess.forceKill = () => { - forceKillAttempts++ - if (forceKillAttempts === 1) { - throw new Error('transient graceful fallback failure') - } - } - createSession() - - void gracefulClose() - await vi.advanceTimersByTimeAsync(5_000) - expect(forceKillAttempts).toBe(1) - expect(session.isTerminating).toBe(true) - - await vi.advanceTimersByTimeAsync(SESSION_FORCE_KILL_RETRY_MS) - expect(forceKillAttempts).toBe(2) - subprocess.simulateExit(137) - expect(session.state).toBe('exited') - expect(vi.getTimerCount()).toBe(0) - }) - - it('keeps late data and the real exit code while attributing the requested stop', () => { - createSession() - subprocess.kill = () => {} - const onData = vi.fn() - const onExit = vi.fn() - session.attachClient({ onData, onExit }) - - void gracefulClose() - vi.advanceTimersByTime(5_000) - - subprocess.simulateData('late output') - subprocess.simulateExit(23) - - expect(onData).toHaveBeenCalledWith('late output') - expect(onExit).toHaveBeenCalledTimes(1) - expect(onExit).toHaveBeenCalledWith(23, session.incarnationId, { - kind: 'operator_close' - }) - expect(session.exitCode).toBe(23) - }) - }) - - describe('detach token guard', () => { - it('ignores stale detach with wrong token', () => { - createSession() - const received: string[] = [] - const token1 = session.attachClient({ - onData: (d) => received.push(d), - onExit: () => {} - }) - - session.attachClient({ - onData: (d) => received.push(d), - onExit: () => {} - }) - - session.detachClient(token1) - received.length = 0 - - subprocess.simulateData('after detach') - expect(received).toEqual(['after detach']) - }) - }) -}) diff --git a/src/main/daemon/sessions/testing/terminal-start-failure.test.ts b/src/main/daemon/sessions/testing/terminal-start-failure.test.ts deleted file mode 100644 index 18c7cb241a3..00000000000 --- a/src/main/daemon/sessions/testing/terminal-start-failure.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import '../../pty-subprocess/testing/mock-descendant-sweep' -import { Socket } from 'node:net' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { TerminalHost } from '../../terminal-host/terminal-host' -import { Session } from '../session' -import { DaemonTerminalAdmission } from '../../server/daemon-terminal-admission' -import { DaemonPtySpawnPreparations } from '../../server/daemon-pty-spawn-preparations' -import { answerDaemonControlRequest } from '../../server/daemon-control-request' -import { DaemonPendingRequests } from '../../transport/client/daemon-client-pending-requests' -import { DaemonClientConnections } from '../../server/daemon-client-connections' -import { DaemonEndpointLifecycle } from '../../endpoint/publication/daemon-endpoint-lifecycle' -import { DaemonSessionAttachments } from '../../server/daemon-session-attachments' -import { DaemonStreamDataBatcher } from '../../transport/stream/daemon-stream-data-batcher' -import { BackgroundTransientFactRelay } from '../../transport/stream/daemon-background-transient-facts' -import { TerminalHistorySeedTransferRegistry } from '../../history/seed-transfer/terminal-history-seed-transfer-registry' -import { createNoopDaemonFileLog } from '../../observability/daemon-file-log' -import type { SubprocessHandle } from '../session-subprocess-handle' -import type { TerminalExitCause } from '../../../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import { - formatTerminalStartFailure, - readTerminalStartFailure, - terminalStartError -} from '../../../../shared/terminal/pty/lifecycle/terminal-start-failure' -import { mapRuntimeError } from '../../../runtime/rpc/errors' - -const MARKER = 'too many consoles in use, max consoles is 128' -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') -afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - vi.restoreAllMocks() -}) - -function subprocess(cause?: TerminalExitCause): SubprocessHandle { - return { - pid: 12345, - shellPath: 'C:\\Program Files\\Git\\bin\\bash.exe', - getForegroundProcess: () => null, - write: vi.fn(), - resize: vi.fn(), - kill: vi.fn(), - terminateOwnedTree: () => 'unavailable', - forceKill: vi.fn(), - signal: vi.fn(), - dispose: vi.fn(), - onData: (cb) => { - cb('console allocation failure: too many consoles ') - cb('in use, max consoles is 128') - }, - onExit: (cb) => cb(256, cause) - } -} - -describe('process-owned terminal startup failure', () => { - it('rejects constructor-time death through the real daemon error reply without publishing a phantom terminal', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const events = vi.fn() - const sub = subprocess({ - kind: 'exited', - exitCode: 256, - initialOutputDiagnostic: 'git-bash-console-capacity' - }) - const host = new TerminalHost({ spawnSubprocess: () => sub, reportReadinessEvent: events }) - const socket = new Socket() - const write = vi.spyOn(socket, 'write').mockReturnValue(true) - try { - const preparations = new DaemonPtySpawnPreparations(async () => {}) - const finish = vi.spyOn(preparations, 'finish') - const attachments = new DaemonSessionAttachments(host) - const attach = vi.spyOn(attachments, 'attach') - const log = createNoopDaemonFileLog() - const unexpected = (): never => { - throw new Error('unexpected admission lifecycle callback') - } - const streamDataBatcher = new DaemonStreamDataBatcher(unexpected) - const connections = new DaemonClientConnections({ - token: 'test-token', - protocolVersion: 1, - identity: { - launchNonce: null, - startedAtMs: null, - entryPath: null, - appVersion: null, - spawnerExecPath: null - }, - log, - streamDataBatcher, - isAcceptingWork: () => true, - onTransportChanged: unexpected, - onConnectionAccepted: unexpected, - onAuthenticatedPair: unexpected, - onLastAuthenticatedClientDisconnected: unexpected, - onControlRequest: unexpected, - onControlReplaced: unexpected, - onClientDisconnected: unexpected, - onStreamDisconnected: unexpected - }) - vi.spyOn(connections, 'get').mockReturnValue({ - clientId: 'client', - authenticatedPairEstablished: true, - controlSocket: socket, - streamSocket: socket - }) - const options = { - host, - preparations, - connections, - endpoint: new DaemonEndpointLifecycle({ - socketPath: 'unused-test-endpoint', - tokenPath: 'unused-test-token', - pidPath: null, - launchNonce: null, - token: 'test-token', - publishEndpointOwnership: unexpected, - log, - isServing: () => false, - onOwnershipLost: unexpected - }), - attachments, - historySeedTransfers: new TerminalHistorySeedTransferRegistry(), - transientFactRelay: new BackgroundTransientFactRelay(unexpected), - streamDataBatcher, - log, - isAcceptingWork: () => true, - requestEndpointRetirement: unexpected, - reevaluateIdleShutdown: vi.fn() - } satisfies ConstructorParameters[0] - const admission = new DaemonTerminalAdmission(options) - const request = { - id: 'start', - type: 'createOrAttach', - payload: { - sessionId: 'capacity', - cols: 80, - rows: 24, - command: 'private-command-token' - } - } as const - await answerDaemonControlRequest( - socket, - request, - () => admission.createOrAttach('client', request), - vi.fn() - ) - expect(admission.inFlight).toBe(0) - expect(finish).toHaveBeenCalledOnce() - expect(attach).not.toHaveBeenCalled() - expect(write).toHaveBeenCalledOnce() - const payload = String(write.mock.calls[0]?.[0]) - const response = JSON.parse(payload) - expect(response).toMatchObject({ - ok: false, - error: 'agent_session_exited_during_start', - terminalStartFailure: { - incarnationId: expect.any(String), - cause: { - kind: 'exited', - exitCode: 256, - initialOutputDiagnostic: 'git-bash-console-capacity' - } - } - }) - const pending = new DaemonPendingRequests() - const rejection = Promise.withResolvers() - pending.add('start', { - resolve: rejection.resolve, - reject: rejection.resolve, - cancelDeadline: () => {} - }) - pending.settle(response) - const error = await rejection.promise - expect(mapRuntimeError('rpc', { runtimeId: 'runtime' }, error)).toMatchObject({ - error: { - code: 'agent_session_exited_during_start', - message: expect.stringContaining('Close some Git Bash terminals') - } - }) - expect(host.listSessions()).toEqual([]) - expect(sub.write).not.toHaveBeenCalled() - expect(sub.kill).not.toHaveBeenCalled() - expect(sub.forceKill).not.toHaveBeenCalled() - expect( - events.mock.calls.filter(([event]) => event === 'session-initial-output-diagnostic') - ).toHaveLength(1) - expect(payload + JSON.stringify(events.mock.calls)).not.toContain('private-command-token') - expect(payload).not.toContain(MARKER) - } finally { - socket.destroy() - await host.dispose() - } - }) - - it.each([ - { kind: 'operator_close' }, - { kind: 'signaled', signal: 9 }, - { kind: 'unknown', reason: 'host_status_unavailable' }, - { kind: 'exited', exitCode: 0 } - ] as const)('keeps $kind exits unclassified despite matching output', (cause) => { - const session = new Session({ - sessionId: 'control', - cols: 80, - rows: 24, - subprocess: subprocess(cause), - ownerBackend: 'windows-conpty', - shellReadySupported: false - }) - expect( - formatTerminalStartFailure( - terminalStartError('agent_session_exited_during_start', session.exitCause) - ) - ).toBeUndefined() - session.dispose() - }) - - it.each(['posix-pty', 'windows-wsl'] as const)('does not classify %s output', (ownerBackend) => { - const session = new Session({ - sessionId: 'control', - cols: 80, - rows: 24, - subprocess: subprocess({ kind: 'exited', exitCode: 256 }), - ownerBackend, - shellReadySupported: false - }) - expect( - readTerminalStartFailure( - terminalStartError('agent_session_exited_during_start', session.exitCause) - ) - ).toBeUndefined() - session.dispose() - }) -}) diff --git a/src/main/daemon/terminal-host/terminal-host-process-inspection.ts b/src/main/daemon/terminal-host/terminal-host-process-inspection.ts index 24f6e3280a6..669596550ce 100644 --- a/src/main/daemon/terminal-host/terminal-host-process-inspection.ts +++ b/src/main/daemon/terminal-host/terminal-host-process-inspection.ts @@ -7,8 +7,8 @@ import type { PtyChildProcessVerdict } from '../../../shared/terminal/pty/lifecy import type { RemoteForegroundEvidence } from '../../../shared/foreground-process-evidence' import { getCheapProcessTableSnapshot } from '../../../shared/cheap-process-table-snapshot-reader' import { getStrictProcessTableSnapshotWithAge } from '../../../shared/process-table-snapshot-reader' -import { resolveRemoteForegroundEvidence } from '../../providers/agent-foreground-process' -import { buildPaneProcessFingerprint } from '../../providers/posix-pane-foreground-fingerprint' +import { resolveRemoteForegroundEvidence } from '../../providers/foreground/agent-process-batch' +import { buildPaneProcessFingerprint } from '../../providers/foreground/posix-pane-fingerprint' import type { Session } from '../sessions/session' import { resolveSpawnFileForegroundFromRows } from '../pty-subprocess/spawn-file-foreground-process' import { inspectSpawnFileChildProcessesFromRows } from '../pty-subprocess/spawn-file-child-processes' @@ -18,7 +18,7 @@ import { rememberSteadyStateAnchor } from './terminal-host-steady-state-anchor' import { SessionNotFoundError } from '../protocol/daemon-errors' -import type { PtyProcessInspectionOptions } from '../../providers/pty-process-inspection' +import type { PtyProcessInspectionOptions } from '../../providers/pty/process-inspection' export type TerminalHostProcessInspection = { foregroundObservation?: TerminalForegroundObservation diff --git a/src/main/daemon/terminal-host/terminal-host-session-cwd.ts b/src/main/daemon/terminal-host/terminal-host-session-cwd.ts index aabdf5bdd54..4e81fd3abbc 100644 --- a/src/main/daemon/terminal-host/terminal-host-session-cwd.ts +++ b/src/main/daemon/terminal-host/terminal-host-session-cwd.ts @@ -1,4 +1,4 @@ -import { resolveProcessCwd } from '../../providers/process-cwd' +import { resolveProcessCwd } from '../../providers/working-directory/process-cwd' import type { Session } from '../sessions/session' export async function resolveTerminalHostSessionCwd(session: Session): Promise { diff --git a/src/main/daemon/terminal-host/terminal-host-steady-state-anchor.ts b/src/main/daemon/terminal-host/terminal-host-steady-state-anchor.ts index 5484fc6ebcf..8919c476ee1 100644 --- a/src/main/daemon/terminal-host/terminal-host-steady-state-anchor.ts +++ b/src/main/daemon/terminal-host/terminal-host-steady-state-anchor.ts @@ -1,6 +1,6 @@ import { recognizeAgentProcess } from '../../../shared/agent-status/process/agent-process-recognition' import type { RemoteForegroundEvidence } from '../../../shared/foreground-process-evidence' -import { buildPaneProcessFingerprint } from '../../providers/posix-pane-foreground-fingerprint' +import { buildPaneProcessFingerprint } from '../../providers/foreground/posix-pane-fingerprint' import type { Session } from '../sessions/session' /** Full-capture identity may be reused only while its pane fingerprint and raw foreground name match. */ diff --git a/src/main/daemon/terminal-host/terminal-host.ts b/src/main/daemon/terminal-host/terminal-host.ts index 970d51c97fc..d7d804d0826 100644 --- a/src/main/daemon/terminal-host/terminal-host.ts +++ b/src/main/daemon/terminal-host/terminal-host.ts @@ -4,7 +4,7 @@ import { runTerminalCreation, type PendingTerminalCreation } from './terminal-cr import { beginTerminalHostFencedTermination } from './terminal-host-fenced-termination' import type { PtyFencedTerminationRequest } from '../../../shared/terminal/pty/lifecycle/pty-fenced-termination' import type { Session } from '../sessions/session' -import type { PtyProcessInspectionOptions } from '../../providers/pty-process-inspection' +import type { PtyProcessInspectionOptions } from '../../providers/pty/process-inspection' import type { SessionInfo } from '../protocol/daemon-session-info' import type { TakePendingOutputResult } from '../protocol/daemon-rpc-contract' import type { TerminalSnapshot } from '../protocol/terminal-snapshot' diff --git a/src/main/daemon/terminal-host/testing/terminal-host-cwd-readability.test.ts b/src/main/daemon/terminal-host/testing/terminal-host-cwd-readability.test.ts deleted file mode 100644 index 5a1901a7958..00000000000 --- a/src/main/daemon/terminal-host/testing/terminal-host-cwd-readability.test.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { SubprocessHandle } from '../../sessions/session-subprocess-handle' -import { TerminalHost } from '../terminal-host' -import { validateWorkingDirectoryAsync } from '../../../providers/working-directory-validation' - -const { opendirMock, statMock } = vi.hoisted(() => ({ - opendirMock: vi.fn(), - statMock: vi.fn() -})) -// TCC directory enumeration can remain pending while a permission sheet is open. -vi.mock('node:fs/promises', async (importOriginal) => ({ - ...(await importOriginal>()), - opendir: opendirMock, - stat: statMock -})) - -vi.mock('../../../pty/process-retirement/pty-descendant-termination', () => ({ - killWithDescendantSweep: vi.fn() -})) - -const close = vi.fn(async () => {}) -const spawnSubprocess = vi.fn(() => createMockSubprocess()) - -function dirReading(read: () => unknown): { read: () => unknown; close: () => Promise } { - return { read, close } -} - -function stallEnumeration(stage: 'open' | 'read' | 'close') { - let release!: () => void - const pending = new Promise((resolve) => { - release = resolve - }) - const directory = { - read: async () => { - if (stage === 'read') { - await pending - } - return null - }, - close: vi.fn(async () => { - if (stage === 'close') { - await pending - } - }) - } - opendirMock.mockImplementation(async () => { - if (stage === 'open') { - await pending - } - return directory - }) - return { release, directory } -} - -function createMockSubprocess(): SubprocessHandle { - let onExitCb: ((code: number) => void) | null = null - return { - pid: 99999, - getForegroundProcess: vi.fn(() => null), - write: vi.fn(), - resize: vi.fn(), - kill: vi.fn(() => { - setTimeout(() => onExitCb?.(0), 5) - }), - terminateOwnedTree: () => 'unavailable' as const, - forceKill: vi.fn(() => onExitCb?.(137)), - signal: vi.fn(), - onData() {}, - onExit(cb) { - onExitCb = cb - }, - dispose: vi.fn() - } -} - -// Only the daemon can measure its own cwd permissions; other failures must not imply denial. -describe('TerminalHost cwd readability verdict', () => { - let host: TerminalHost - let platformDescriptor: PropertyDescriptor | undefined - - beforeEach(() => { - close.mockReset() - spawnSubprocess.mockClear() - statMock.mockReset() - opendirMock.mockReset().mockReturnValue(dirReading(() => ({ name: 'entry' }))) - platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - host = new TerminalHost({ spawnSubprocess }) - }) - - afterEach(async () => { - vi.useRealTimers() - await host.dispose() - if (platformDescriptor) { - Object.defineProperty(process, 'platform', platformDescriptor) - } - }) - - const create = (sessionId: string, cwd?: string, signal?: AbortSignal) => - host.createOrAttach({ - sessionId, - cols: 80, - rows: 24, - ...(cwd ? { cwd } : {}), - ...(signal ? { cancelSignal: signal, isCanceled: () => signal.aborted } : {}), - streamClient: { onData: vi.fn(), onExit: vi.fn() } - }) - - it('keeps native UNC creation within the validation lane while healthy creation proceeds', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - vi.useFakeTimers() - let release = () => {} - const unavailable = new Promise((resolve) => { - release = resolve - }) - opendirMock.mockImplementation(async () => { - await unavailable - return dirReading(() => null) - }) - const server = '\\\\unreachable-smb\\share' - let active = 0 - let peak = 0 - statMock.mockImplementation(async (cwd: string) => { - if (cwd.startsWith(server)) { - active += 1 - peak = Math.max(peak, active) - try { - await unavailable - } finally { - active -= 1 - } - } - return { isDirectory: () => true } - }) - await host.dispose() - host = new TerminalHost({ - spawnSubprocess: async (opts) => { - if (opts.cwd) { - try { - await validateWorkingDirectoryAsync(opts.cwd, { signal: opts.cancelSignal }) - } catch (error) { - opts.onCreationDisposition?.({ kind: 'no-fork' }) - throw error - } - } - return createMockSubprocess() - } - }) - const abort = new AbortController() - const firstPath = `${server}\\first` - const canceled = create('unc-canceled', firstPath, abort.signal) - void canceled.catch(() => {}) - const pending = [ - create('unc-second', `${server}\\second`), - create('unc-queued', `${server}\\third`) - ] - try { - await vi.advanceTimersByTimeAsync(1_100) - expect(active + opendirMock.mock.calls.length).toBe(2) - abort.abort() - await expect(canceled).rejects.toThrow('was canceled') - pending.push(create('unc-canceled', firstPath)) - await vi.advanceTimersByTimeAsync(1_100) - expect(statMock).toHaveBeenCalledTimes(2) - expect((await create('healthy', 'C:\\healthy')).isNew).toBe(true) - expect(active).toBe(2) - } finally { - release() - await vi.advanceTimersByTimeAsync(0) - await Promise.allSettled([canceled, ...pending]) - } - expect(peak).toBe(2) - expect(host.listSessions()).toHaveLength(4) - expect(statMock).toHaveBeenCalledTimes(4) - }) - - it.each(['open', 'read', 'close'] as const)( - 'starts a shell when the diagnostic directory %s remains pending', - async (stage) => { - vi.useFakeTimers() - const { release, directory } = stallEnumeration(stage) - const creation = create(`slow-${stage}`, `/work/slow-${stage}`) - try { - await vi.advanceTimersByTimeAsync(1_000) - expect(host.listSessions()).toHaveLength(1) - await expect(creation).resolves.toMatchObject({ isNew: true }) - expect((await creation).cwdReadableByDaemon).toBeUndefined() - } finally { - release() - await vi.advanceTimersByTimeAsync(0) - } - expect(directory.close).toHaveBeenCalledOnce() - } - ) - - it('cancels a pending probe without spawning and releases the session id for a retry', async () => { - vi.useFakeTimers() - const { release, directory } = stallEnumeration('open') - const abort = new AbortController() - const creation = create('canceled-prompt', '/work/canceled-prompt', abort.signal) - let error: unknown - void creation.catch((rejection: unknown) => { - error = rejection - }) - try { - abort.abort() - await vi.advanceTimersByTimeAsync(0) - expect(spawnSubprocess).not.toHaveBeenCalled() - expect(host.listSessions()).toEqual([]) - expect(error).toMatchObject({ message: 'Attach canceled for session canceled-prompt' }) - const retry = create('canceled-prompt', '/work/canceled-prompt') - await vi.advanceTimersByTimeAsync(1_000) - expect(host.listSessions()).toHaveLength(1) - await expect(retry).resolves.toMatchObject({ isNew: true }) - expect(opendirMock).toHaveBeenCalledOnce() - } finally { - release() - await vi.advanceTimersByTimeAsync(0) - } - expect(directory.close).toHaveBeenCalledOnce() - }) - - it('does not launch a shell when shutdown starts during a pending probe', async () => { - vi.useFakeTimers() - const { release } = stallEnumeration('open') - const creation = create('shutdown-prompt', '/work/shutdown-prompt') - let error: unknown - void creation.catch((rejection: unknown) => { - error = rejection - }) - const disposal = host.dispose() - try { - await vi.advanceTimersByTimeAsync(1_000) - expect(spawnSubprocess).not.toHaveBeenCalled() - expect(error).toMatchObject({ message: 'Terminal host is shutting down' }) - await disposal - expect(host.listSessions()).toEqual([]) - } finally { - release() - await vi.advanceTimersByTimeAsync(0) - } - }) -}) diff --git a/src/main/daemon/terminal-host/testing/terminal-host-process-inspection.test.ts b/src/main/daemon/terminal-host/testing/terminal-host-process-inspection.test.ts deleted file mode 100644 index 015b289c9af..00000000000 --- a/src/main/daemon/terminal-host/testing/terminal-host-process-inspection.test.ts +++ /dev/null @@ -1,248 +0,0 @@ -import type { TerminalForegroundSample } from '../../../../shared/terminal/pty/lifecycle/terminal-foreground-observation' -import '../../pty-subprocess/testing/mock-descendant-sweep' -import { describe, expect, it, vi } from 'vitest' -import type { SubprocessHandle } from '../../sessions/session-subprocess-handle' -import { TerminalHost } from '../terminal-host' - -import type { IPty } from 'node-pty' -import type { WindowsProcessRow } from '../../../windows/windows-process-table' -import { createPtyForegroundProcessTracker } from '../../pty-subprocess/foreground-process-tracker' -import { inspectSpawnFileWindowsChildProcesses } from '../../pty-subprocess/spawn-file-child-processes' -import { inspectionShowsShellAlone } from '../../../runtime/terminal/lifecycle/run-terminal-shell-alone' - -const { fullTable, identityTable, jobMembers, consoleMembers } = vi.hoisted(() => ({ - fullTable: vi.fn(), - identityTable: vi.fn(), - jobMembers: vi.fn(), - consoleMembers: vi.fn() -})) -vi.mock('../../../windows/windows-process-table', () => ({ - readWindowsProcessTable: fullTable, - readWindowsProcessTableFresh: fullTable, - readWindowsProcessIdentityTable: identityTable, - readWindowsProcessIdentityTableFresh: identityTable -})) -vi.mock('../../../providers/windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: jobMembers, - isWindowsPtyJobReadable: () => true -})) -vi.mock('../../../providers/windows-console-attached-processes', () => ({ - readWindowsConsoleAttachedProcessIds: consoleMembers -})) - -function createSubprocess(): SubprocessHandle { - let onExit: ((code: number) => void) | null = null - return { - pid: 99_999, - getForegroundProcess: vi.fn(() => null), - write: vi.fn(), - resize: vi.fn(), - kill: vi.fn(() => onExit?.(0)), - terminateOwnedTree: () => 'unavailable', - forceKill: vi.fn(() => onExit?.(137)), - signal: vi.fn(), - onData: vi.fn(), - onExit: (callback) => { - onExit = callback - }, - dispose: vi.fn() - } -} - -describe('TerminalHost process inspection', () => { - it.each([false, true])( - 'uses fresh anchored decisions through Session (static=%s)', - async (staticName) => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - vi.useFakeTimers({ toFake: ['Date'] }) - const nativeRow = ( - pid: number, - ppid: number, - name: string, - command = name - ): WindowsProcessRow => ({ pid, ppid, name, command }) - const shell = nativeRow(100, 1, 'powershell.exe') - const orphan = nativeRow(120, 999, 'claude.exe', 'claude.exe --resume conversation') - const daemon = nativeRow(130, 1, 'ssh-agent.exe', 'ssh-agent.exe -D') - const cases: [string, boolean, WindowsProcessRow[], boolean, string?][] = [ - ['D1', false, [shell, daemon], true], - ['known young', true, [shell, orphan], false], - ['known old', true, [shell, orphan], false, 'old'], - ['foreign anchor', true, [shell, { ...daemon, pid: 120 }], true], - ['anchor absent', true, [shell, daemon], true], - ['anchor exited', true, [shell], true], - ['degraded incomplete', false, [shell, daemon], false, 'both'], - ['Session exits during foreground read', false, [shell, daemon], false, 'exit'] - ] - try { - for (const [name, anchored, rows, admits, variant] of cases) { - vi.setSystemTime(1000) - let dead = false - const base = createSubprocess() - const proc: IPty = { - pid: 100, - cols: 80, - rows: 24, - process: 'powershell.exe', - handleFlowControl: false, - onData: () => ({ dispose() {} }), - onExit: () => ({ dispose() {} }), - resize: vi.fn(), - clear: vi.fn(), - write: vi.fn(), - kill: vi.fn(), - pause: vi.fn(), - resume: vi.fn() - } - Object.assign(proc, { processNameIsSpawnFile: staticName }) - const tracker = createPtyForegroundProcessTracker({ - process: proc, - shellPath: 'powershell.exe', - sessionId: 'decision', - startupAgentRecognition: null, - isDead: () => dead - }) - const getForegroundProcess = vi.fn(tracker.getForegroundProcess) - const host = new TerminalHost({ - spawnSubprocess: () => ({ - ...base, - pid: 100, - processNameIsSpawnFile: staticName, - getForegroundProcess, - confirmForegroundProcess: tracker.confirmForegroundProcess, - inspectChildProcesses: (fresh, ignoreDetached) => - inspectSpawnFileWindowsChildProcesses(proc, shell.name, fresh, ignoreDetached), - onExit: (callback) => - base.onExit((code) => { - dead = true - tracker.markDead() - callback(code) - }) - }) - }) - try { - const created = await host.createOrAttach({ - sessionId: 'decision', - cols: 80, - rows: 24, - streamClient: { onData: vi.fn(), onExit: vi.fn() } - }) - fullTable - .mockReset() - .mockResolvedValue([ - shell, - { ...orphan, ppid: 100 }, - ...(anchored ? [] : [nativeRow(121, 100, 'claude.exe')]) - ]) - consoleMembers.mockResolvedValue(new Set([100, 120, 121])) - expect(await host.confirmForegroundProcess('decision')).toBe('claude') - vi.setSystemTime(variant === 'old' ? 41_000 : 2000) - fullTable.mockReset().mockImplementation(async () => { - if (variant === 'both') { - throw new Error('denied') - } - if (variant === 'exit') { - base.kill() - } - return rows - }) - identityTable.mockReset().mockResolvedValue(variant === 'both' ? [shell] : rows) - jobMembers.mockReturnValue(new Set(rows.map((row) => row.pid))) - consoleMembers.mockResolvedValue(new Set([100])) - getForegroundProcess.mockClear() - const run = () => - host.inspectProcess('decision', { - expectedIncarnationId: created.incarnationId, - scanChildProcesses: true, - ignoreDetached: true - }) - expect(inspectionShowsShellAlone(await run()), name).toBe(admits) - expect(fullTable, name).toHaveBeenCalledTimes(1) - expect(getForegroundProcess, name).not.toHaveBeenCalled() - if (name === 'D1') { - for (const count of [2, 20]) { - fullTable.mockClear() - identityTable.mockClear() - for (let i = 0; i < count; i++) { - await run() - } - expect(fullTable).toHaveBeenCalledTimes(count) - expect(identityTable).toHaveBeenCalledTimes(count) - } - expect( - inspectionShowsShellAlone( - await host.inspectProcess('decision', { ignoreDetached: false }) - ) - ).toBe(false) - } - } finally { - await host.dispose() - } - } - } finally { - vi.useRealTimers() - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } - } - ) -}) - -describe('fresh foreground observation contract', () => { - it('returns no child-census proof and fences a session replaced during its read', async () => { - let finish!: (sample: TerminalForegroundSample) => void - const subprocess = createSubprocess() - subprocess.observeForeground = vi.fn( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const host = new TerminalHost({ spawnSubprocess: () => subprocess }) - const created = await host.createOrAttach({ - sessionId: 'foreground-contract', - cols: 80, - rows: 24, - streamClient: { onData: vi.fn(), onExit: vi.fn() } - }) - try { - const pending = host.inspectProcess('foreground-contract', { - foregroundOnly: true, - expectedIncarnationId: created.incarnationId - }) - finish({ - verdict: 'observed', - source: 'pty-master', - foregroundKind: 'non-shell', - processName: 'claude' - }) - expect(await pending).toMatchObject({ - foregroundProcess: 'claude', - hasChildProcesses: true, - childProcessEvidence: 'unverifiable', - foregroundObservation: { - ptyId: 'foreground-contract', - ptyIncarnationId: created.incarnationId, - verdict: 'observed' - } - }) - const late = host.inspectProcess('foreground-contract', { foregroundOnly: true }) - await host.kill('foreground-contract') - finish({ - verdict: 'observed', - source: 'pty-master', - foregroundKind: 'non-shell', - processName: 'claude' - }) - expect(await late).toMatchObject({ - foregroundProcess: null, - hasChildProcesses: true, - foregroundObservation: { verdict: 'unverifiable', reason: 'session_changed' } - }) - } finally { - await host.dispose() - } - }) -}) diff --git a/src/main/diagnostics/main-thread-churn-probe.ts b/src/main/diagnostics/main-thread-churn-probe.ts index e002190761a..57ad85d40fd 100644 --- a/src/main/diagnostics/main-thread-churn-probe.ts +++ b/src/main/diagnostics/main-thread-churn-probe.ts @@ -1,4 +1,4 @@ -import { writeStartupDiagnosticLine } from '../startup/startup-diagnostics' +import { writeStartupDiagnosticLine } from '../startup/diagnostics/startup-diagnostics' export const MAIN_THREAD_DIAGNOSTICS_ENV = 'ORCA_MAIN_THREAD_DIAGNOSTICS' diff --git a/src/main/ephemeral-vm/owned-runtime-cleanup.ts b/src/main/ephemeral-vm/owned-runtime-cleanup.ts index e15bc719d46..b8488abea13 100644 --- a/src/main/ephemeral-vm/owned-runtime-cleanup.ts +++ b/src/main/ephemeral-vm/owned-runtime-cleanup.ts @@ -7,7 +7,7 @@ import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtime import { ephemeralVmFailureFromError } from '../../shared/ephemeral-vm-failure-copy' import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' import { invalidateRuntimeEnvironmentTransport } from '../ipc/runtime-environments/runtime-environments' -import { retireRemovedRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-removal-cleanup' +import { retireRemovedRuntimeEnvironment } from '../ipc/runtime-environments/catalog/runtime-environment-removal-cleanup' import { releaseEphemeralVmRuntimeEnvironments } from './runtime-environment-release' import { cleanupEphemeralVmRuntime } from './runtime-service' import { removeEphemeralVmRuntimeSshTarget } from './runtime-ssh-cleanup' diff --git a/src/main/ephemeral-vm/provisioned-root-source.ts b/src/main/ephemeral-vm/provisioned-root-source.ts index 3c31ae95786..d507202fe23 100644 --- a/src/main/ephemeral-vm/provisioned-root-source.ts +++ b/src/main/ephemeral-vm/provisioned-root-source.ts @@ -4,7 +4,7 @@ import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { resolveDefaultBaseRefWithLocalGit } from '../git/refs/resolution/repo-default-base-ref' import { getLocalProjectGitExecOptions } from '../workspaces/execution-host/project-runtime-git-options' import { resolveWorktreeCreateBase } from '../workspaces/creation/worktree-create-base' -import { resolveWorktreeAddBaseRef } from '../../shared/worktree/base-ref' +import { resolveWorktreeAddBaseRef } from '../../shared/worktree/base-refs/base-ref' const PROVISIONED_ROOT_SOURCE_REF_TIMEOUT_MS = 15_000 diff --git a/src/main/ephemeral-vm/recipe-workspace-removal-wiring.ts b/src/main/ephemeral-vm/recipe-workspace-removal-wiring.ts index 9d2bd9dec80..3304526fe07 100644 --- a/src/main/ephemeral-vm/recipe-workspace-removal-wiring.ts +++ b/src/main/ephemeral-vm/recipe-workspace-removal-wiring.ts @@ -1,8 +1,8 @@ import type { Store } from '../persistence/loading-store/store' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { RECIPE_REMOVAL_REQUEST_TIMEOUT_MS } from '../../shared/recipe-host-removal' -import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' +import { callRuntimeEnvironment } from '../ipc/runtime-environments/requests/runtime-environment-transport-routing' +import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/catalog/runtime-environment-registry-root' import { cleanupOwnedEphemeralVmRuntime } from './owned-runtime-cleanup' import { describeRecipeWorkspaceEnvironments, diff --git a/src/main/ephemeral-vm/workspace-removal.test.ts b/src/main/ephemeral-vm/workspace-removal.test.ts index 730d48c0225..b28b3b0463d 100644 --- a/src/main/ephemeral-vm/workspace-removal.test.ts +++ b/src/main/ephemeral-vm/workspace-removal.test.ts @@ -10,13 +10,8 @@ import { import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' import { RecipeWorkspaceRemovalError } from '../../shared/recipe-host-removal' -import { mapRuntimeError } from '../runtime/rpc/errors' -import { - describeRecipeWorkspaceEnvironments, - ownsRecipeWorkspaceRemoval, - removeRecipeWorkspace, - type RecipeWorkspaceRemoveParams -} from './workspace-removal' +import { mapRuntimeError } from '../runtime/rpc/responses/rpc-response' +import { removeRecipeWorkspace, type RecipeWorkspaceRemoveParams } from './workspace-removal' let root: string const workspaceId = 'repo::/workspace/repo-task' @@ -93,15 +88,6 @@ beforeEach(() => { afterEach(() => removeTempDirs([root])) describe('recipe workspace removal on the provisioning host', () => { - it('handles only removals that asked to destroy the environment', () => { - seed() - expect(ownsRecipeWorkspaceRemoval(root, params)).toBe(true) - const { destroyHost: _destroyHost, ...withoutConsent } = params - expect(ownsRecipeWorkspaceRemoval(root, withoutConsent)).toBe(false) - expect(ownsRecipeWorkspaceRemoval(root, { ...params, hostId: 'runtime:env-b' })).toBe(false) - expect(ownsRecipeWorkspaceRemoval(root, { ...params, worktree: 'name:task' })).toBe(false) - }) - it('removes the checkout on the environment first, then destroys the empty environment', async () => { seed() const ports = makePorts() @@ -140,22 +126,6 @@ describe('recipe workspace removal on the provisioning host', () => { expect(ports.cleanup).not.toHaveBeenCalled() }) - it('reports a recipe with no destroy step as still running, never destroyed', async () => { - seed() - const ports = makePorts({}, 'disabled') - await expect(removeRecipeWorkspace(root, params, ports)).resolves.toMatchObject({ - host: { state: 'left-running' } - }) - }) - - it('destroys a provisioned root without attempting its protected Git deletion', async () => { - seed('provisioned-root') - const ports = makePorts() - await removeRecipeWorkspace(root, params, ports) - expect(ports.call).not.toHaveBeenCalled() - expect(ports.cleanup).toHaveBeenCalledWith('vm-a') - }) - it('keeps the environment code and data when its removal fails, and destroys nothing', async () => { seed() const ports = makePorts({ @@ -194,13 +164,6 @@ describe('recipe workspace removal on the provisioning host', () => { }) }) - it('asks for a wake instead of failing on an asleep environment', async () => { - seed('orca-worktree', { status: 'suspended' }) - const ports = makePorts() - await expect(removeRecipeWorkspace(root, params, ports)).rejects.toThrow('asleep') - expect(ports.call).not.toHaveBeenCalled() - }) - it('says the machine may still run when its destroy fails', async () => { seed('provisioned-root') const ports = makePorts() @@ -220,27 +183,6 @@ describe('recipe workspace removal on the provisioning host', () => { }) }) - it('names the environment for a phone and says whether deleting destroys it', () => { - seed('orca-worktree', { - recipe: { id: 'sandbox', name: 'Sandbox', create: './create.sh', destroy: './destroy.sh' } - }) - expect([...describeRecipeWorkspaceEnvironments(root, 'runtime:env-a')]).toEqual([ - [workspaceId, { name: 'task', destroys: true }] - ]) - expect(describeRecipeWorkspaceEnvironments(root, 'runtime:env-b').size).toBe(0) - seed('orca-worktree', { recipe: { id: 'sandbox', name: 'Sandbox', create: './create.sh' } }) - expect(describeRecipeWorkspaceEnvironments(root, 'runtime:env-a').get(workspaceId)).toEqual({ - name: 'task', - destroys: false - }) - }) - - it('names nothing when two records claim the same workspace', () => { - seed() - upsertEphemeralVmRuntime(root, { ...listEphemeralVmRuntimes(root)[0], id: 'vm-b' }) - expect(describeRecipeWorkspaceEnvironments(root, 'runtime:env-a').size).toBe(0) - }) - it('waits for an older environment that answers on acceptance, then destroys', async () => { seed() const ports = makePorts({ diff --git a/src/main/ephemeral-vm/workspace-removal.ts b/src/main/ephemeral-vm/workspace-removal.ts index 8d845dd68c3..628fff59855 100644 --- a/src/main/ephemeral-vm/workspace-removal.ts +++ b/src/main/ephemeral-vm/workspace-removal.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import type { WorktreeRemove } from '../../shared/rpc-contract/worktree-params' +import type { WorktreeRemove } from '../../shared/rpc-contract/workspaces/worktree-params' import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' import { findEphemeralVmWorkspaceOwner, diff --git a/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts b/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts deleted file mode 100644 index 71435f43eac..00000000000 --- a/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -// #34089: a VM its provider stopped or reclaimed stays recorded as running. Opening its workspace -// must run the recipe's resume instead of returning the dead record unchanged. -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { SshConnectionStatus } from '../../shared/ssh-types' - -type MockState = { - record: Record - sshStatus: SshConnectionStatus | undefined -} - -const UP_RECORD = { - id: 'vm-1', - status: 'running', - connectionMode: 'ssh', - sshTargetId: 'runtime-ssh-vm-1', - runtimeEnvironmentId: 'env-vm' -} - -const state = vi.hoisted((): MockState => ({ - record: { - id: 'vm-1', - status: 'running', - connectionMode: 'ssh', - sshTargetId: 'runtime-ssh-vm-1', - runtimeEnvironmentId: 'env-vm' - }, - sshStatus: undefined -})) -const mocks = vi.hoisted(() => ({ - resume: vi.fn(), - connect: vi.fn(async () => ({ targetId: 'runtime-ssh-vm-1', environmentId: 'env-vm' })), - reconnectControl: vi.fn(), - refreshStatus: vi.fn(async () => ({})), - updateStatus: vi.fn((_userDataPath: string, _id: string, patch: Record) => patch) -})) - -vi.mock('electron', () => ({ app: { getPath: () => '/user-data' } })) -vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ - updateEphemeralVmRuntimeStatus: mocks.updateStatus -})) -vi.mock('../../shared/ephemeral-vm-workspace-runtime', () => ({ - findWorkspaceEphemeralVmRuntime: () => state.record -})) -vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: () => ({ id: 'env-vm', pairingRevision: 9, createdAt: 0 }) -})) -vi.mock('../../shared/ephemeral-vm-recipes', () => ({ - getEphemeralVmRecipeResultConnection: () => ({ type: 'ssh', target: { host: 'vm' } }), - getEphemeralVmRecipeResultPairingCode: () => null -})) -vi.mock('../ipc/ephemeral-vm-recipe-context', () => ({ - getRuntimeRecipeContext: () => ({ repoPath: '/repo', recipe: { resume: './resume.sh' } }) -})) -vi.mock('../ipc/runtime-environments/runtime-environments', () => ({ - invalidateRuntimeEnvironmentTransport: vi.fn() -})) -vi.mock('../ipc/runtime-environments/runtime-environment-request-connections', () => ({ - getRuntimeEnvironmentStatusOwner: () => ({ refresh: mocks.refreshStatus }), - reconnectRemoteRuntimeSharedControlConnection: mocks.reconnectControl -})) -vi.mock('../ssh/targets/ssh-target-registry', () => ({ - getRegisteredSshState: () => (state.sshStatus ? { status: state.sshStatus } : undefined) -})) -vi.mock('./runtime-service', () => ({ resumeEphemeralVmRuntime: mocks.resume })) -vi.mock('./runtime-ssh', () => ({ - connectRuntimeOwnedSshTarget: mocks.connect, - refreshRuntimeOwnedSshTarget: vi.fn() -})) - -import type { Store } from '../persistence/loading-store/store' -import { resumeEphemeralVmWorkspace } from './workspace-resume' - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recipe context reader is mocked, so the resume never reads this store. -const STORE = {} as Store -const REQUEST = { sshHeld: false, sshUserDisconnects: 0 } - -const RESUMED = { - ok: true, - skipped: false, - runtime: { id: 'vm-1', status: 'running', recipeResult: {} } -} - -describe('opening a workspace whose VM host Orca gave up reaching', () => { - afterEach(() => { - vi.useRealTimers() - state.record = { ...UP_RECORD } - state.sshStatus = undefined - mocks.resume.mockReset() - mocks.connect.mockClear() - mocks.reconnectControl.mockClear() - mocks.refreshStatus.mockClear() - mocks.updateStatus.mockClear() - }) - - it('keeps the record as it was when the recovery fails, so reconnects go on', async () => { - state.sshStatus = 'reconnection-failed' - mocks.resume.mockResolvedValue({ - ok: false, - error: 'resume failed', - runtime: { id: 'vm-1', status: 'resume_failed' } - }) - - await expect(resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST)).rejects.toThrow( - 'resume failed' - ) - expect(mocks.updateStatus).toHaveBeenLastCalledWith('/user-data', 'vm-1', { - status: 'running' - }) - }) - - it('keeps a failed connect after recovery from parking the VM as asleep', async () => { - state.sshStatus = 'reconnection-failed' - state.record = { ...UP_RECORD, status: 'suspend_failed' } - mocks.resume.mockResolvedValue(RESUMED) - mocks.connect.mockRejectedValueOnce(new Error('ssh unreachable')) - - await expect(resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST)).rejects.toThrow( - 'ssh unreachable' - ) - expect(mocks.updateStatus).toHaveBeenLastCalledWith('/user-data', 'vm-1', { - status: 'suspend_failed' - }) - }) -}) diff --git a/src/main/ephemeral-vm/workspace-resume-paired-lost-contact.test.ts b/src/main/ephemeral-vm/workspace-resume-paired-lost-contact.test.ts index 4f770ffefb5..8e4d299aae8 100644 --- a/src/main/ephemeral-vm/workspace-resume-paired-lost-contact.test.ts +++ b/src/main/ephemeral-vm/workspace-resume-paired-lost-contact.test.ts @@ -41,7 +41,7 @@ vi.mock('../ipc/ephemeral-vm-recipe-context', () => ({ vi.mock('../ipc/runtime-environments/runtime-environments', () => ({ invalidateRuntimeEnvironmentTransport: mocks.invalidateTransport })) -vi.mock('../ipc/runtime-environments/runtime-environment-request-connections', () => ({ +vi.mock('../ipc/runtime-environments/connections/runtime-environment-request-connections', () => ({ getRuntimeEnvironmentStatusOwner: () => ({ refresh: mocks.refreshStatus }), reconnectRemoteRuntimeSharedControlConnection: mocks.reconnectControl, getRemoteRuntimeSharedControlDiagnostics: () => @@ -63,9 +63,7 @@ import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' import { generateKeyPair } from '../../shared/remote-runtime/e2ee/node/e2ee-crypto' import { addEnvironmentFromPairingCode, - listEnvironments, - resolveEnvironment, - resolveEnvironmentPairingOffer + resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' import { getPreferredPairedRuntimeConnection } from '../../shared/remote-runtime/host-catalog/runtime-environments' import { sendRemoteRuntimeRequestOnSocket } from '../../shared/remote-runtime/requests/remote-runtime-request-socket' @@ -78,15 +76,9 @@ import { isRuntimeEnvironmentContactLost, noteRuntimeEnvironmentStatusContact, RUNTIME_CONTACT_LOST_AFTER_MS -} from '../ipc/runtime-environments/runtime-environment-contact-loss' -import { - clearRuntimeEnvironmentManualDisconnect, - markRuntimeEnvironmentManuallyDisconnected -} from '../ipc/runtime-environments/runtime-environment-manual-disconnect' -import { - RECIPE_VM_UNREACHABLE_WITHOUT_RESUME_MESSAGE, - resumeEphemeralVmWorkspace -} from './workspace-resume' +} from '../ipc/runtime-environments/status/runtime-environment-contact-loss' +import { clearRuntimeEnvironmentManualDisconnect } from '../ipc/runtime-environments/connectivity/runtime-environment-manual-disconnect' +import { resumeEphemeralVmWorkspace } from './workspace-resume' // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recipe context reader is mocked, so the resume never reads this store. const STORE = {} as Store @@ -207,35 +199,19 @@ describe('opening a workspace whose paired VM server Orca could not reach for mi }) } - it('leaves a server that is only briefly unreachable to its own reconnects', async () => { - await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS / 2) - await expect(resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST)).resolves.toBe( - state.record - ) - expect(mocks.resume).not.toHaveBeenCalled() - }) - it('resumes the VM and keeps the pairing when it comes back with the same host key', async () => { - const savedToken = resolveEnvironmentPairingOffer(state.desktopDataPath, environmentId) await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS) expect(isRuntimeEnvironmentContactLost(environmentId)).toBe(true) resumeBoots(keyPair) await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - expect(mocks.resume).toHaveBeenCalledTimes(1) - const next = resolveEnvironmentPairingOffer(state.desktopDataPath, environmentId) - expect(next.endpoint).not.toBe(savedToken.endpoint) - expect(next.deviceToken).toBe(savedToken.deviceToken) - expect(listEnvironments(state.desktopDataPath)).toHaveLength(1) - expect(mocks.invalidateTransport).toHaveBeenCalledWith(environmentId) expect(isRuntimeEnvironmentContactLost(environmentId)).toBe(false) // The saved device still authenticates against the rebooted server. expect((await probe(environmentId)).ok).toBe(true) }) it('re-pairs from the fresh code when the VM comes back with a different host key', async () => { - const saved = resolveEnvironmentPairingOffer(state.desktopDataPath, environmentId) await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS) const rebuiltServerDataPath = mkdtempSync(join(tmpdir(), 'orca-lost-vm-rebuilt-')) const rotated = generateKeyPair() @@ -244,63 +220,9 @@ describe('opening a workspace whose paired VM server Orca could not reach for mi try { await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - const next = resolveEnvironmentPairingOffer(state.desktopDataPath, environmentId) - expect(next.deviceToken).not.toBe(saved.deviceToken) - expect(next.publicKeyB64).toBe(Buffer.from(rotated.publicKey).toString('base64')) - expect(listEnvironments(state.desktopDataPath)).toHaveLength(1) expect((await probe(environmentId)).ok).toBe(true) } finally { await removeTempDirs([rebuiltServerDataPath]) } }) - - it('keeps the record as it was when the resume fails, so reconnects go on', async () => { - await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS) - mocks.resume.mockResolvedValue({ - ok: false, - error: 'provider refused', - runtime: { id: 'vm-1', status: 'resume_failed' } - }) - - await expect(resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST)).rejects.toThrow( - 'provider refused' - ) - expect(mocks.updateStatus).toHaveBeenLastCalledWith(state.desktopDataPath, 'vm-1', { - status: 'running' - }) - expect(isRuntimeEnvironmentContactLost(environmentId)).toBe(true) - }) - - it('says to create the workspace again when its recipe has no resume, and destroys nothing', async () => { - await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS) - state.recipe = {} - - await expect(resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST)).rejects.toThrow( - RECIPE_VM_UNREACHABLE_WITHOUT_RESUME_MESSAGE - ) - expect(mocks.resume).not.toHaveBeenCalled() - expect(mocks.updateStatus).not.toHaveBeenCalled() - expect(listEnvironments(state.desktopDataPath)).toHaveLength(1) - }) - - it('leaves a server the user disconnected, or one ready now, alone', async () => { - await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS) - markRuntimeEnvironmentManuallyDisconnected(environmentId) - await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - clearRuntimeEnvironmentManualDisconnect(environmentId) - state.sharedControlState = 'ready' - await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - expect(mocks.resume).not.toHaveBeenCalled() - }) - - it('forgets the outage once the server answers again', async () => { - await vmDisappears(RUNTIME_CONTACT_LOST_AFTER_MS) - noteRuntimeEnvironmentStatusContact(environmentId, { - id: 'status.get', - ok: false, - error: { code: 'unauthorized', message: 'rejected' } - }) - await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - expect(mocks.resume).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ephemeral-vm/workspace-resume.ts b/src/main/ephemeral-vm/workspace-resume.ts index 10d07137160..d5854d973a0 100644 --- a/src/main/ephemeral-vm/workspace-resume.ts +++ b/src/main/ephemeral-vm/workspace-resume.ts @@ -29,12 +29,12 @@ import { getRemoteRuntimeSharedControlDiagnostics, getRuntimeEnvironmentStatusOwner, reconnectRemoteRuntimeSharedControlConnection -} from '../ipc/runtime-environments/runtime-environment-request-connections' +} from '../ipc/runtime-environments/connections/runtime-environment-request-connections' import { clearRuntimeEnvironmentContactLoss, isRuntimeEnvironmentContactLost -} from '../ipc/runtime-environments/runtime-environment-contact-loss' -import { isRuntimeEnvironmentManuallyDisconnected } from '../ipc/runtime-environments/runtime-environment-manual-disconnect' +} from '../ipc/runtime-environments/status/runtime-environment-contact-loss' +import { isRuntimeEnvironmentManuallyDisconnected } from '../ipc/runtime-environments/connectivity/runtime-environment-manual-disconnect' import { getRegisteredSshState } from '../ssh/targets/ssh-target-registry' import { isRecipeVmLostContact } from './recipe-vm-lost-contact' diff --git a/src/main/external-conversations/external-conversation-delivery-receipts.ts b/src/main/external-conversations/external-conversation-delivery-receipts.ts index 035624ffa84..71e96afa9a5 100644 --- a/src/main/external-conversations/external-conversation-delivery-receipts.ts +++ b/src/main/external-conversations/external-conversation-delivery-receipts.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import { CONNECTOR_SOURCES, type ConnectorSource } from '../../shared/external-conversation-link' import type { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db' import { OrchestrationError } from '../runtime/orchestration/orchestration-error' -import { hashCanonical } from '../runtime/rpc/orchestration-mutation-receipt' +import { hashCanonical } from '../runtime/rpc/orchestration/mutations/orchestration-mutation-receipt' import { refused, type ConversationKey, type Delivery } from './external-conversation-types' export type DeliveryReceiptDb = OrchestrationDb diff --git a/src/main/external-conversations/external-conversation-links.ts b/src/main/external-conversations/external-conversation-links.ts index 6b79d4863d9..6d41d06eb2a 100644 --- a/src/main/external-conversations/external-conversation-links.ts +++ b/src/main/external-conversations/external-conversation-links.ts @@ -17,7 +17,7 @@ import { readWorkspaceRecord, writeWorkspaceRecord, type WorkspaceRecordStore -} from '../runtime/sidebar-inputs/sort-stamp-records' +} from '../runtime/workspaces/metadata/workspace-activity-records' import { CONNECTOR_AGENTS } from './connector-agents' import type { ConversationKey } from './external-conversation-types' diff --git a/src/main/external-conversations/external-conversation-seam.test.ts b/src/main/external-conversations/external-conversation-seam.test.ts index 064404948dd..87b96a2ef49 100644 --- a/src/main/external-conversations/external-conversation-seam.test.ts +++ b/src/main/external-conversations/external-conversation-seam.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { hashCanonical } from '../runtime/rpc/orchestration-mutation-receipt' +import { hashCanonical } from '../runtime/rpc/orchestration/mutations/orchestration-mutation-receipt' import type { ConversationKey } from './external-conversation-types' import { fakeLauncher, @@ -7,7 +7,6 @@ import { fakeTerminal, launchResult, LOCAL_REPO, - PANE, WORKTREE } from './external-conversation.test-fixture' import { deferred, harness } from './external-conversation-seam.test-fixture' @@ -73,56 +72,9 @@ describe('ExternalConversationSeam start', () => { expect(launch).toHaveBeenCalledTimes(1) expect(terminal.writes).toEqual(['second']) }) - - it('answers a start rebuilt from a link alone as unknown, without launching', async () => { - const { seam, put } = harness() - put(WORKTREE, 'local', { - externalConversations: [{ ...KEY, paneKey: PANE, agent: 'claude', createdAt: 1 }] - }) - const { launcher, launch } = fakeLauncher(async () => launchResult('handed-to-terminal')) - expect( - (await seam.start({ launcher, terminal: fakeTerminal().terminal }, KEY, 'd1', START)).initial - ).toEqual(UNKNOWN) - expect(launch).not.toHaveBeenCalled() - }) }) describe('ExternalConversationSeam delivery ids', () => { - it.each([ - ['its workspace cannot be resolved', 'resolve'], - ['its link cannot be written', 'write'] - ] as const)( - 'keeps an unknown answer, across a restart too, when %s after the launch', - async (_label, failing) => { - const { seam, restart, store } = harness() - const { launcher, launch } = fakeLauncher(async () => launchResult('handed-to-terminal')) - if (failing === 'resolve') { - launcher.paneWorkspace = async () => { - throw new Error('scope lost') - } - } else { - store.setWorktreeMeta = () => { - throw new Error('disk full') - } - } - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect( - (await seam.start({ launcher, terminal: fakeTerminal().terminal }, KEY, 'd1', START)) - .initial - ).toEqual(UNKNOWN) - expect( - (await seam.start({ launcher, terminal: fakeTerminal().terminal }, KEY, 'd1', START)) - .initial - ).toEqual(UNKNOWN) - expect( - (await restart().start({ launcher, terminal: fakeTerminal().terminal }, KEY, 'd1', START)) - .initial - ).toEqual(UNKNOWN) - expect(launch).toHaveBeenCalledTimes(1) - warn.mockRestore() - } - ) - it('shares one answer for a repeated id and payload, and refuses another payload', async () => { const { seam } = harness() const { launcher, launch } = fakeLauncher(async () => launchResult('handed-to-terminal')) @@ -243,27 +195,6 @@ async function started() { } describe('ExternalConversationSeam send', () => { - it.each([ - ['before', false], - ['after', true] - ])( - 'answers a writer that throws %s the guarded write as writer_failed', - async (_when, guarded) => { - const { seam, host, terminal } = await started() - terminal.sendTerminalAgentPrompt.mockImplementationOnce(async (_handle, prompt, options) => { - if (guarded) { - await options.beforeWrite?.('pty-1') - terminal.writes.push(prompt) - } - throw new Error('agent_prompt_stalled') - }) - expect(await seam.send(host, KEY, 'd1', 'hello')).toEqual({ - outcome: 'unknown', - reason: 'writer_failed' - }) - } - ) - it('refuses when the agent’s pane is gone, or a new process took it before the write', async () => { const { seam, host, terminal } = await started() terminal.sendTerminalAgentPrompt.mockImplementationOnce(async () => { @@ -419,52 +350,8 @@ describe('ExternalConversationSeam twin removal', () => { }) describe('ExternalConversationSeam start-headed lanes', () => { - async function startHeaded(delayLink: boolean) { - const terminal = fakeTerminal() - const h = harness({}, undefined, undefined, terminal.terminal) - const launched = deferred() - const linkResolved = deferred() - const { launcher, launch } = fakeLauncher(async () => { - await launched.promise - return launchResult('handed-to-terminal') - }) - const resolveWorkspace = launcher.paneWorkspace - launcher.paneWorkspace = async (worktreeId) => { - if (delayLink) { - await linkResolved.promise - } - return resolveWorkspace(worktreeId) - } - const host = { launcher, terminal: terminal.terminal } - const start = h.seam.start(host, KEY, 'start', START) - await vi.waitFor(() => expect(launch).toHaveBeenCalled()) - return { ...h, terminal, host, start, launched, linkResolved } - } - const GONE = { outcome: 'refused', reason: 'agent_not_reachable' } - it.each([ - ['a new process on the same PTY id', false], - ['a new process on the same PTY id, link still resolving', true], - ['another PTY id', false], - ['another PTY id, link still resolving', true] - ])('keeps a follower queued behind the launch off %s', async (name, delayLink) => { - const { seam, host, terminal, start, launched, linkResolved } = await startHeaded(delayLink) - const follower = seam.send(host, KEY, 'd1', 'queued') - if (name.startsWith('another')) { - terminal.state.ptyId = 'pty-2' - } else { - terminal.replace() - } - launched.resolve() - linkResolved.resolve() - expect((await start).initial).toEqual({ outcome: 'accepted' }) - expect(await follower).toEqual(GONE) - expect(terminal.writes).toEqual([]) - expect(await seam.send(host, KEY, 'd2', 'later')).toEqual({ outcome: 'accepted' }) - expect(terminal.writes).toEqual(['later']) - }) - it('lets no follower adopt a process when the launch published none it can prove', async () => { const terminal = fakeTerminal() const { seam } = harness({}, undefined, undefined, terminal.terminal) diff --git a/src/main/external-conversations/external-conversation-start.ts b/src/main/external-conversations/external-conversation-start.ts index 86a6edcf787..a82952fa8d6 100644 --- a/src/main/external-conversations/external-conversation-start.ts +++ b/src/main/external-conversations/external-conversation-start.ts @@ -3,7 +3,7 @@ import type { AgentLaunchResult as AgentLaunchPublishedSurface } from '../../shared/agent-launch/contracts/agent-launch-intent' import type { ConnectorAgent } from '../../shared/external-conversation-link' -import type { AgentLaunchParams } from '../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../shared/rpc-contract/agent-launch/agent-launch-params' import { executeAgentLaunch } from '../agent-launch/agent-launch-executor' import { diff --git a/src/main/codex-accounts/async-file-rename.test.ts b/src/main/filesystem/async-file-rename.test.ts similarity index 76% rename from src/main/codex-accounts/async-file-rename.test.ts rename to src/main/filesystem/async-file-rename.test.ts index bd5da38b0e2..9cb84fed69a 100644 --- a/src/main/codex-accounts/async-file-rename.test.ts +++ b/src/main/filesystem/async-file-rename.test.ts @@ -3,7 +3,7 @@ import type * as NodeFsPromises from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import { writeFileDurable, writeFileDurableIfCurrent } from '../filesystem/durable-file-write' +import { writeFileDurable, writeFileDurableIfCurrent } from './durable-file-write' const rename = vi.hoisted(() => vi.fn()) vi.mock('node:fs/promises', async (importOriginal) => { @@ -32,27 +32,6 @@ function fixture() { return { root, target, temporary } } -it.each(['EPERM', 'EACCES', 'EBUSY'])( - 'retries a transient Windows %s without blocking the event loop', - async (code) => { - const { target, temporary } = fixture() - Object.defineProperty(process, 'platform', { value: 'win32' }) - rename.mockRejectedValueOnce(Object.assign(new Error('file busy'), { code })) - let ticked = false - const timer = setTimeout(() => { - ticked = true - }, 0) - try { - await writeFileDurable(temporary, target, 'new') - expect(readFileSync(target, 'utf8')).toBe('new') - expect(rename).toHaveBeenCalledTimes(2) - expect(ticked).toBe(true) - } finally { - clearTimeout(timer) - } - } -) - it.each([ ['win32', 'EPERM', 6], ['win32', 'ENOSPC', 1], diff --git a/src/main/filesystem/durable-file-write.ts b/src/main/filesystem/durable-file-write.ts index f03706cdb58..fe1ac6ff9c1 100644 --- a/src/main/filesystem/durable-file-write.ts +++ b/src/main/filesystem/durable-file-write.ts @@ -9,6 +9,12 @@ import { renameFileWithWindowsRetryAsync } from '../../shared/windows-retry-file-operations' +export type DurableFilePayload = + | string + | Uint8Array + | Iterable + | AsyncIterable + /** Persist directory changes where supported; Windows and some filesystems reject directory fsync. */ async function syncDirectory(directory: string): Promise { let handle: Awaited> | null = null @@ -64,7 +70,7 @@ export async function renameDurable(tmpPath: string, finalPath: string): Promise /** Make content durable without publishing, allowing backup rotation before replacement. */ export async function writeTempFileDurable( tmpPath: string, - payload: string | Uint8Array, + payload: DurableFilePayload, mode?: number ): Promise { const handle = await open(tmpPath, 'w', mode) @@ -79,7 +85,7 @@ export async function writeTempFileDurable( export async function writeFileDurable( tmpPath: string, finalPath: string, - payload: string | Uint8Array, + payload: DurableFilePayload, mode?: number ): Promise { await writeFileDurableIfCurrent(tmpPath, finalPath, payload, () => true, mode) @@ -89,7 +95,7 @@ export async function writeFileDurable( export async function writeFileDurableIfCurrent( tmpPath: string, finalPath: string, - payload: string | Uint8Array, + payload: DurableFilePayload, isCurrent: () => boolean, /** Creation mode for the new temp file, e.g. 0o600 for state other users must not read. */ mode?: number diff --git a/src/main/filesystem/host-tree-removal.ts b/src/main/filesystem/host-tree-removal.ts index 87d12eb9951..02eebd90f4b 100644 --- a/src/main/filesystem/host-tree-removal.ts +++ b/src/main/filesystem/host-tree-removal.ts @@ -1,7 +1,7 @@ // Host deletion needs bounded Windows lock retries and unpatched fs for Electron’s .asar handling. import { getErrorCode } from '../git/worktrees/worktree-operation-options' -import { unregisteredFolderRefusal } from '../../shared/worktree/removal' +import { unregisteredFolderRefusal } from '../../shared/worktree/removal/removal' import { join, win32 } from 'node:path' import { lstat, readdir, rm, rmdir, unlink } from './asar-transparent-fs' import { isWindowsAbsolutePathLike } from '../../shared/cross-platform-path' diff --git a/src/main/window/owned-temp-staging-root.ts b/src/main/filesystem/owned-temp-staging-root.ts similarity index 97% rename from src/main/window/owned-temp-staging-root.ts rename to src/main/filesystem/owned-temp-staging-root.ts index 1f582aa38bc..d95d6c113a4 100644 --- a/src/main/window/owned-temp-staging-root.ts +++ b/src/main/filesystem/owned-temp-staging-root.ts @@ -1,6 +1,6 @@ import type { Dir } from 'node:fs' import { isSafeOwnedDirectory } from '../../shared/owned-private-directory' -export { isSafeOwnedDirectory } from '../../shared/owned-private-directory' + import { lstat, mkdir, opendir } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { removeTree } from '../../shared/windows-transient-lock-removal' diff --git a/src/main/git/command-runner/admission/git-operation-executor.ts b/src/main/git/command-runner/admission/git-operation-executor.ts index 4af6c3e3be4..5bdbb7f0d24 100644 --- a/src/main/git/command-runner/admission/git-operation-executor.ts +++ b/src/main/git/command-runner/admission/git-operation-executor.ts @@ -1,5 +1,5 @@ import { AsyncLocalStorage } from 'node:async_hooks' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' const operations = new AsyncLocalStorage<{ tier: GitAdmissionTier; active: boolean }>() diff --git a/src/main/git/command-runner/git-environment/git-process-env.ts b/src/main/git/command-runner/git-environment/git-process-env.ts index cc233232983..376be6133a4 100644 --- a/src/main/git/command-runner/git-environment/git-process-env.ts +++ b/src/main/git/command-runner/git-environment/git-process-env.ts @@ -11,6 +11,21 @@ export function gitOptionalLocksDisabledEnv( } } +/** Git 2.44+ skips partial-clone lazy fetches; older Git is refused every transport. */ +export const OFFLINE_GIT_ENV = { GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: 'none' } + +/** For reads that must never reach a remote. */ +export function offlineGitEnv( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform +): NodeJS.ProcessEnv { + const next = { ...env, ...OFFLINE_GIT_ENV } + if (platform === 'win32') { + addWslEnvKeys(next, Object.keys(OFFLINE_GIT_ENV)) + } + return next +} + /** Pin Git diagnostics to English so parsers work under any user locale. */ export function untranslatedGitOutputEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { return { ...env, ...UNTRANSLATED_GIT_OUTPUT_ENV } diff --git a/src/main/git/command-runner/git-exec-admission-lifetime.test.ts b/src/main/git/command-runner/git-exec-admission-lifetime.test.ts index bd26cf55d00..28f6ede7e39 100644 --- a/src/main/git/command-runner/git-exec-admission-lifetime.test.ts +++ b/src/main/git/command-runner/git-exec-admission-lifetime.test.ts @@ -44,11 +44,11 @@ vi.mock('../../../shared/git/fetch/git-fetch-head-lock', async (importOriginal) }) import { execFileCapture } from './process-capture/exec-file-capture' +import * as captureModule from './process-capture/exec-file-capture' +import { gitExecFileAsync } from './git-exec-file' +import { GitCommandTimeoutError } from '../../../shared/git/commands/git-command-timeout' -import { - _gitAdmissionSnapshotForTests, - _resetGitAdmissionForTests -} from './admission/git-subprocess-admission' +import { _resetGitAdmissionForTests } from './admission/git-subprocess-admission' import { GitAdmissionScheduler } from '../../../shared/git/admission/git-admission-scheduler' describe('git exec admission lifetime', () => { @@ -63,6 +63,7 @@ describe('git exec admission lifetime', () => { afterEach(() => { vi.useRealTimers() vi.unstubAllEnvs() + vi.restoreAllMocks() _resetGitAdmissionForTests() }) @@ -80,4 +81,59 @@ describe('git exec admission lifetime', () => { expect(execFileMock).not.toHaveBeenCalled() expect(onChildTerminated).toHaveBeenCalledOnce() }) + + it('keeps a timed-out live checkout admitted until termination while reads proceed', async () => { + vi.useRealTimers() + const holders = Array.from({ length: 3 }, (_, index) => ({ + name: `holder-${index}`, + started: Promise.withResolvers(), + capture: Promise.withResolvers<{ stdout: string; stderr: string }>(), + terminate: () => {} + })) + let successorStarted = false + vi.spyOn(captureModule, 'execFileCapture').mockImplementation((_binary, args, options) => { + const holder = holders.find(({ name }) => args.includes(name)) + if (holder) { + holder.terminate = () => options.onChildTerminated?.() + holder.started.resolve() + return holder.capture.promise + } + if (args.includes('successor')) { + successorStarted = true + } + options.onChildTerminated?.() + return Promise.resolve({ stdout: 'read completed', stderr: '' }) + }) + const checkoutOptions = { + cwd: process.cwd(), + admissionClass: 'checkout' as const, + admissionTier: 'interactive' as const + } + const running = holders.map(({ name }) => + gitExecFileAsync(['worktree', 'add', name], checkoutOptions) + ) + const timeout = expect(running[0]).rejects.toBeInstanceOf(GitCommandTimeoutError) + await Promise.all(holders.map(({ started }) => started.promise)) + holders[0].capture.reject(new GitCommandTimeoutError(180_000)) + await timeout + const successor = gitExecFileAsync(['worktree', 'add', 'successor'], checkoutOptions) + try { + await expect( + gitExecFileAsync(['rev-parse', 'HEAD'], { cwd: process.cwd() }) + ).resolves.toEqual({ + stdout: 'read completed', + stderr: '' + }) + expect(successorStarted).toBe(false) + holders[0].terminate() + await successor + expect(successorStarted).toBe(true) + } finally { + holders.forEach((holder) => { + holder.capture.resolve({ stdout: '', stderr: '' }) + holder.terminate() + }) + await Promise.allSettled([...running, successor]) + } + }) }) diff --git a/src/main/git/command-runner/git-exec-file.ts b/src/main/git/command-runner/git-exec-file.ts index bdfa4412410..064307e999c 100644 --- a/src/main/git/command-runner/git-exec-file.ts +++ b/src/main/git/command-runner/git-exec-file.ts @@ -6,7 +6,7 @@ import { import { pendingWslDriveCheckoutGitRouting } from './host-routing/wsl-drive-checkout-git-routing' import type { ResolvedCommand } from './host-routing/wsl-command-resolution' import { annotateWslHostFailure, isTransientWslFailure } from './host-routing/wsl-host-failure' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import type { GitExecOptions } from './git-exec-options' import { execFileCapture, execFileCaptureToTermination } from './process-capture/exec-file-capture' import { @@ -30,6 +30,7 @@ import { createAbortError } from './process-capture/abort-error' import { readCapturedGitBuffer, readCapturedGitString } from './process-capture/captured-git-output' import { runUnlessGitCwdKnownMissing } from './host-routing/missing-git-spawn-cwd' import { trackGitWorktreeMutation } from './git-worktree-mutation-state' +import { trackGitRefMutation } from './git-ref-mutation-state' import { routeLocalGitOptions, runAdmittedWslGit } from './host-routing/local-git-runtime-route' import { gitRunsIn } from './host-routing/git-runs-in' @@ -74,6 +75,7 @@ async function gitExecFileAsyncUnlocked( cwd: options.cwd, wslDistro: options.wslDistro, tier: options.admissionTier, + admissionClass: options.admissionClass, signal: options.admissionSignal ?? options.signal }) span?.setAttribute('git.queue_wait_ms', grant.queueWaitMs) @@ -190,6 +192,7 @@ export function gitExecFileAsync( ): Promise<{ stdout: string; stderr: string }> { const options = routeLocalGitOptions(callerOptions) const releaseMutation = trackGitWorktreeMutation(args, options) + const releaseRefMutation = trackGitRefMutation(args) const terminationState: { current: Promise | null } = { current: null } const command = resolveGitFetchHeadCommand(args, options.cwd) // Missing folders start no child and must not record a git.exec span. @@ -209,8 +212,10 @@ export function gitExecFileAsync( // A timed-out caller can settle before its child exits. if (terminationState.current) { void terminationState.current.then(releaseMutation) + void terminationState.current.then(releaseRefMutation) } else { releaseMutation() + releaseRefMutation() } }) } diff --git a/src/main/git/command-runner/git-exec-options.ts b/src/main/git/command-runner/git-exec-options.ts index e98f02ca1f1..4bcb2e3dd13 100644 --- a/src/main/git/command-runner/git-exec-options.ts +++ b/src/main/git/command-runner/git-exec-options.ts @@ -1,7 +1,7 @@ // Bound output to avoid V8 string overflow; match the relay's MAX_GIT_BUFFER. export const DEFAULT_GIT_MAX_BUFFER = 10 * 1024 * 1024 -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' export type GitExecOptions = { cwd: string @@ -26,6 +26,8 @@ export type GitExecOptions = { observeChildTermination?: (terminated: Promise, writes: boolean) => void /** Scheduler priority for this child; status is the safe default. */ admissionTier?: GitAdmissionTier + /** File materialization during worktree creation has a separate concurrency budget. */ + admissionClass?: 'checkout' /** Skips general admission; only for a caller that bounds its own concurrency (worktree deletes). */ admissionExempt?: true /** Native macOS deletion spawns use the shared process worker. */ diff --git a/src/main/git/command-runner/git-ref-mutation-state.test.ts b/src/main/git/command-runner/git-ref-mutation-state.test.ts new file mode 100644 index 00000000000..ba65218930c --- /dev/null +++ b/src/main/git/command-runner/git-ref-mutation-state.test.ts @@ -0,0 +1,88 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type * as Capture from './process-capture/exec-file-capture' + +const io = vi.hoisted(() => ({ capture: vi.fn() })) +vi.mock('./process-capture/exec-file-capture', async (original) => ({ + ...(await original()), + execFileCapture: io.capture +})) +import { trackGitRefMutation } from './git-ref-mutation-state' +import { gitExecFileAsync } from './git-exec-file' +import { subscribeGitRefChanges } from '../refs/git-ref-change-signal' + +const disposers: (() => void)[] = [] +afterEach(() => { + disposers.splice(0).forEach((dispose) => dispose()) + io.capture.mockReset() +}) + +it('preserves warm refs for reads and proven object/index operations, and fences all for ref writes', () => { + const events: string[] = [] + disposers.push(subscribeGitRefChanges('/a/.git', () => events.push('a'))) + disposers.push(subscribeGitRefChanges('/b/.git', () => events.push('b'))) + for (const args of [ + ['for-each-ref'], + ['remote'], + ['config', '--get', 'remote.origin.url'], + ['worktree', 'list', '--porcelain'], + ['ls-remote'], + ['add', '.'], + ['update-index', '--refresh'], + ['hash-object', '-w', 'file'], + ['restore', '--staged', '.'], + ['apply', '--cached'], + ['merge-tree', '--write-tree'] + ]) { + trackGitRefMutation(args)() + } + expect(events).toEqual([]) + for (const args of [ + ['commit'], + ['push'], + ['pull'], + ['fetch'], + ['branch', 'topic'], + ['config', 'remote.origin.url', 'url'], + ['worktree', 'add', 'path'], + ['custom-alias'] + ]) { + const end = trackGitRefMutation(args) + expect(events.splice(0)).toEqual(['a', 'b']) + end() + end() + expect(events.splice(0)).toEqual(['a', 'b']) + } +}) + +it('keeps the runner completion fence at child termination after a timed-out caller settles', async () => { + const events: string[] = [] + disposers.push(subscribeGitRefChanges('/runner-a/.git', () => events.push('a'))) + disposers.push(subscribeGitRefChanges('/runner-b/.git', () => events.push('b'))) + let started!: () => void + const ready = new Promise((resolve) => { + started = resolve + }) + let terminated!: () => void + let rejectCapture!: (error: Error) => void + io.capture.mockImplementationOnce((_command, _args, options) => { + terminated = options.onChildTerminated + started() + return new Promise((_resolve, reject) => { + rejectCapture = reject + }) + }) + const result = gitExecFileAsync(['branch', 'topic'], { + cwd: process.cwd(), + admissionExempt: true + }) + expect(events.splice(0)).toEqual(['a', 'b']) + await ready + const failure = expect(result).rejects.toThrow('deadline') + rejectCapture(new Error('deadline')) + await failure + expect(events).toEqual([]) + disposers.push(subscribeGitRefChanges('/runner-new/.git', () => events.push('new'))) + terminated() + await new Promise(setImmediate) + expect(events).toEqual(['a', 'b', 'new']) +}) diff --git a/src/main/git/command-runner/git-ref-mutation-state.ts b/src/main/git/command-runner/git-ref-mutation-state.ts new file mode 100644 index 00000000000..06209798328 --- /dev/null +++ b/src/main/git/command-runner/git-ref-mutation-state.ts @@ -0,0 +1,23 @@ +import { + classifyGitCommand, + findGitSubcommandIndex +} from '../../../shared/git/commands/git-command-classification' +import { beginGitRefMutation } from '../refs/git-ref-change-signal' + +export function trackGitRefMutation(args: readonly string[]): () => void { + if (classifyGitCommand(args) === 'read') { + return () => {} + } + const index = findGitSubcommandIndex(args) + const command = args[index] + const flags = args.slice(index + 1) + if ( + ['ls-remote', 'add', 'update-index', 'hash-object'].includes(command) || + (command === 'restore' && flags.includes('--staged')) || + (command === 'apply' && flags.includes('--cached')) || + (command === 'merge-tree' && flags.includes('--write-tree')) + ) { + return () => {} + } + return beginGitRefMutation(null) +} diff --git a/src/main/git/command-runner/git-runtime-options.ts b/src/main/git/command-runner/git-runtime-options.ts index 3bf60eca45d..572063aa13f 100644 --- a/src/main/git/command-runner/git-runtime-options.ts +++ b/src/main/git/command-runner/git-runtime-options.ts @@ -1,4 +1,4 @@ -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' export type GitRuntimeOptions = { wslDistro?: string diff --git a/src/main/git/command-runner/git-spawn.ts b/src/main/git/command-runner/git-spawn.ts index 4c064a80ad0..af7ec64214f 100644 --- a/src/main/git/command-runner/git-spawn.ts +++ b/src/main/git/command-runner/git-spawn.ts @@ -6,7 +6,7 @@ import { resolveGitCommand } from './host-routing/git-command-resolution' import { pendingWslDriveCheckoutGitRouting } from './host-routing/wsl-drive-checkout-git-routing' import { untranslatedGitOutputEnv } from './git-environment/git-process-env' import { prepareWindowsHostGitEnvironment } from './host-routing/windows-host-git-environment' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { acquireGitAdmission } from './admission/git-subprocess-admission' import { classifyGitCommand } from '../../../shared/git/commands/git-command-classification' import { buildNetworkSshPolicyEnv } from './git-environment/git-ssh-policy-env' diff --git a/src/main/git/command-runner/git-stream-stdout.ts b/src/main/git/command-runner/git-stream-stdout.ts index d501e1c3eb0..61873b9602e 100644 --- a/src/main/git/command-runner/git-stream-stdout.ts +++ b/src/main/git/command-runner/git-stream-stdout.ts @@ -7,7 +7,7 @@ import { killSpawnedCommandTree } from './process-capture/spawned-command-tree-k import { pendingWslDriveCheckoutGitRouting } from './host-routing/wsl-drive-checkout-git-routing' import type { ResolvedCommand } from './host-routing/wsl-command-resolution' import { DEFAULT_GIT_MAX_BUFFER, type GitExecOptions } from './git-exec-options' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { pendingWslDirectGitReadEnvironment, @@ -41,6 +41,8 @@ export type GitStreamOptions = { signal?: AbortSignal /** Byte backstop; defaults to DEFAULT_GIT_MAX_BUFFER. */ maxBuffer?: number + /** Independent stderr cap for parsers that stream an arbitrarily large population. */ + maxStderrBuffer?: number /** Explicit wall-clock deadline; read commands default to the production backstop. */ timeoutMs?: number /** Overrides only the default read deadline in tests. */ @@ -212,7 +214,7 @@ function streamInSpan( } function onStderrData(chunk: Buffer): void { stderrBytes += chunk.byteLength - if (stderrBytes > maxBuffer) { + if (stderrBytes > (options.maxStderrBuffer ?? maxBuffer)) { void killSpawnedCommandTree(child) finish(new Error('git stderr exceeded maxBuffer.')) return diff --git a/src/main/git/command-runner/host-routing/git-command-resolution.ts b/src/main/git/command-runner/host-routing/git-command-resolution.ts index c712baf991d..b1761a362cd 100644 --- a/src/main/git/command-runner/host-routing/git-command-resolution.ts +++ b/src/main/git/command-runner/host-routing/git-command-resolution.ts @@ -13,7 +13,11 @@ import { } from './wsl-git-read-environment' import { usesHostGitForWslLinkedWorktree } from './wsl-linked-worktree-git-routing' import { withWslWindowsCheckoutGitConfig } from './wsl-windows-checkout-git-config' -import { resolveCommand, type ResolvedCommand } from './wsl-command-resolution' +import { + resolveCommand, + WSL_DIRECT_GIT_FORWARDED_ENV, + type ResolvedCommand +} from './wsl-command-resolution' import type { GitExecOptions } from '../git-exec-options' // Linux Git needs Windows-checkout settings; classify original args and inject only at spawn. @@ -66,7 +70,9 @@ function shouldAttemptWslDirectGit(args: string[], options: GitExecOptions): boo !options.useConfiguredSshCommandForNetwork && !Object.entries(options.env ?? {}).some( ([key, value]) => - key.startsWith('GIT_') && key !== 'GIT_OPTIONAL_LOCKS' && value !== process.env[key] + key.startsWith('GIT_') && + !WSL_DIRECT_GIT_FORWARDED_ENV.includes(key) && + value !== process.env[key] ) ) } diff --git a/src/main/git/command-runner/host-routing/local-git-runtime-route.ts b/src/main/git/command-runner/host-routing/local-git-runtime-route.ts index 941258ed923..5ebfce6fddd 100644 --- a/src/main/git/command-runner/host-routing/local-git-runtime-route.ts +++ b/src/main/git/command-runner/host-routing/local-git-runtime-route.ts @@ -5,7 +5,7 @@ * names its distro; a caller that must run the host's Git anyway says so with `hostGit: true`. */ import { isWslDistroNotFoundFailure } from '../../../wsl/discovery/wsl-distro-unsupported' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' type RoutableGitOptions = { cwd: string diff --git a/src/main/git/command-runner/host-routing/wsl-command-resolution.ts b/src/main/git/command-runner/host-routing/wsl-command-resolution.ts index 1d6c14ed6fd..a81174c16aa 100644 --- a/src/main/git/command-runner/host-routing/wsl-command-resolution.ts +++ b/src/main/git/command-runner/host-routing/wsl-command-resolution.ts @@ -18,6 +18,13 @@ import { import { translateArgForWsl, translateArgsForWsl } from './wsl-path-translation' import { resolveWslInteropSpawnCwd } from '../../../wsl/execution/wsl-interop-spawn-directory' import { noteWslDistroLaunched } from '../../../wsl/discovery/wsl-background-distro-gate' +import { OFFLINE_GIT_ENV } from '../git-environment/git-process-env' + +/** Git settings direct WSL reads pass on the command line, so they need no login shell to reach the distro. */ +export const WSL_DIRECT_GIT_FORWARDED_ENV: readonly string[] = [ + 'GIT_OPTIONAL_LOCKS', + ...Object.keys(OFFLINE_GIT_ENV) +] // Carry Git locale pins in the WSL command; these assignment values are shell-safe. const GIT_OUTPUT_LOCALE_SHELL_PREFIX = Object.entries(UNTRANSLATED_GIT_OUTPUT_ENV) @@ -132,7 +139,6 @@ export function resolveCommand( const shellCmd = `${enterCwd}${invocation}` if (command === 'git' && options.wslGitReadEnvironment) { - const optionalLocks = options.env?.GIT_OPTIONAL_LOCKS return withWslProcessGroupTermination( { binary: 'wsl.exe', @@ -147,7 +153,9 @@ export function resolveCommand( ...(options.env?.GIT_EDITOR !== undefined ? [`GIT_EDITOR=${options.env.GIT_EDITOR}`] : []), - ...(optionalLocks !== undefined ? [`GIT_OPTIONAL_LOCKS=${optionalLocks}`] : []), + ...WSL_DIRECT_GIT_FORWARDED_ENV.flatMap((key) => + options.env?.[key] !== undefined ? [`${key}=${options.env[key]}`] : [] + ), options.wslGitReadEnvironment.gitPath, ...(linuxCwd ? ['-C', linuxCwd] : []), ...translatedArgs diff --git a/src/main/git/command-runner/host-routing/wsl-drive-checkout-git-routing.ts b/src/main/git/command-runner/host-routing/wsl-drive-checkout-git-routing.ts index 09a3c985882..476594169e5 100644 --- a/src/main/git/command-runner/host-routing/wsl-drive-checkout-git-routing.ts +++ b/src/main/git/command-runner/host-routing/wsl-drive-checkout-git-routing.ts @@ -1,4 +1,4 @@ -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { isWslLinkedWorktreeGitRoutingCandidate, prepareWslLinkedWorktreeGitRouting, diff --git a/src/main/git/command-runner/host-routing/wsl-windows-checkout-git-probe.ts b/src/main/git/command-runner/host-routing/wsl-windows-checkout-git-probe.ts index c969f318ae3..13069c82cce 100644 --- a/src/main/git/command-runner/host-routing/wsl-windows-checkout-git-probe.ts +++ b/src/main/git/command-runner/host-routing/wsl-windows-checkout-git-probe.ts @@ -6,7 +6,7 @@ import { runWslProcess, type WslResult, type WslSpec } from '../../../wsl/execut import { translateArgForWsl } from './wsl-path-translation' import { acquireGitAdmission } from '../admission/git-subprocess-admission' import { nonInteractiveGitEnv } from '../git-environment/git-process-env' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { isWslDirectGitReadCommand } from '../../../../shared/git/commands/git-command-classification' import { classifyLineEndingSample, diff --git a/src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts b/src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts index d2d7766f430..cda087a5fd9 100644 --- a/src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts +++ b/src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts @@ -1,4 +1,4 @@ -import { normalizeGhAccountBinding } from '../../../../shared/github/account-binding' +import { normalizeGhAccountBinding } from '../../../../shared/github/accounts/account-binding' import type { GhExecOptions } from './gh-exec-file' import { collectGhArgvHostSignals } from './gh-host-args' import type { ResolvedCommand } from '../host-routing/wsl-command-resolution' @@ -38,7 +38,7 @@ export async function resolveBoundGhExecEnv( createGhBoundAccountHostMismatchError, createGhBoundAccountUnavailableError, resolveGhAccountToken - } = await import('../../../github/gh-account-token') + } = await import('../../../github/accounts/gh-account-token') const normalized = normalizeGhAccountBinding(binding) if (!normalized) { throw createGhBoundAccountUnavailableError(binding) diff --git a/src/main/git/command-runner/hosted-cli/gh-exec-file.ts b/src/main/git/command-runner/hosted-cli/gh-exec-file.ts index 26ad8aa4720..24172ebd368 100644 --- a/src/main/git/command-runner/hosted-cli/gh-exec-file.ts +++ b/src/main/git/command-runner/hosted-cli/gh-exec-file.ts @@ -53,7 +53,9 @@ export type GhExecOptions = Omit & { function nonInteractiveGhEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { return { ...env, - GH_PROMPT_DISABLED: env.GH_PROMPT_DISABLED ?? '1' + GH_PROMPT_DISABLED: env.GH_PROMPT_DISABLED ?? '1', + // Why: gh 2.91-2.92 detach `gh send-telemetry` without a console, so its tzutil child flashes a window on Windows. + GH_TELEMETRY: env.GH_TELEMETRY ?? 'false' } } diff --git a/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts b/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts index 7846adbede5..db8f2f7a331 100644 --- a/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts +++ b/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts @@ -1,5 +1,5 @@ +import type * as GhAccountTokenModule from '../../../github/accounts/gh-account-token' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createFakeSpawnedChild as mockChild } from '../../../../shared/__fixtures__/fake-spawned-child' const { spawnMock, @@ -28,9 +28,7 @@ vi.mock('node:child_process', async (importOriginal) => ({ spawn: spawnMock })) -import type * as GhAccountTokenModule from '../../../github/gh-account-token' - -vi.mock('../../../github/gh-account-token', async (importOriginal) => { +vi.mock('../../../github/accounts/gh-account-token', async (importOriginal) => { const actual = await importOriginal() return { ...actual, @@ -44,24 +42,6 @@ import { ghExecFileAsync } from './gh-exec-file' import { _resetGhRateLimitBreaker, recordGhPrimaryRateLimit } from './gh-rate-limit-breaker' /** Spawns a child that settles with `stdout`, capturing the env the runner handed it. */ -function spawnSettledChild(stdout: string): { - env: () => NodeJS.ProcessEnv | undefined -} { - let capturedEnv: NodeJS.ProcessEnv | undefined - spawnMock.mockImplementation( - (_cmd: string, _args: string[], opts: { env?: NodeJS.ProcessEnv }) => { - capturedEnv = opts.env - const child = mockChild() - queueMicrotask(() => { - child.stdout?.emit('data', Buffer.from(stdout)) - child.emit('exit', 0, null) - child.emit('close', 0, null) - }) - return child - } - ) - return { env: () => capturedEnv } -} describe('ghExecFileAsync account binding', () => { beforeEach(() => { @@ -93,19 +73,6 @@ describe('ghExecFileAsync account binding', () => { _resetGhRateLimitBreaker() }) - it('skips injection for auth probes', async () => { - const spawned = spawnSettledChild('') - - await ghExecFileAsync(['auth', 'status'], { - host: 'github.com', - ghAccount: { host: 'github.com', user: 'Alice' }, - env: { ...process.env, GH_TOKEN: 'ambient' } - }) - - expect(resolveGhAccountTokenMock).not.toHaveBeenCalled() - expect(spawned.env()?.GH_TOKEN).toBe('ambient') - }) - it('fails closed when argv host signals disagree with the binding', async () => { await expect( ghExecFileAsync(['pr', 'list', '--repo', 'github.acme.com/a/b'], { @@ -129,20 +96,6 @@ describe('ghExecFileAsync account binding', () => { } ) - it('still spawns the keyring token read while the core bucket is blocked', async () => { - recordGhPrimaryRateLimit('core', Date.now() + 60_000, 'native:github.com') - const spawned = spawnSettledChild('gho_bound\n') - - const { stdout } = await ghExecFileAsync( - ['auth', 'token', '--user', 'Alice', '--hostname', 'github.com'], - { host: 'github.com' } - ) - - expect(stdout.trim()).toBe('gho_bound') - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(spawned.env()).toBeDefined() - }) - it('fails a bound API call fast on a blocked bucket without resolving a token', async () => { recordGhPrimaryRateLimit('core', Date.now() + 60_000, 'native:github.com') diff --git a/src/main/git/command-runner/hosted-cli/runner-gh-host-args.test.ts b/src/main/git/command-runner/hosted-cli/runner-gh-host-args.test.ts index 3cde1d911d4..89d6368f03b 100644 --- a/src/main/git/command-runner/hosted-cli/runner-gh-host-args.test.ts +++ b/src/main/git/command-runner/hosted-cli/runner-gh-host-args.test.ts @@ -1,25 +1,6 @@ import { describe, expect, it } from 'vitest' -import { applyGhHostToArgs, collectGhArgvHostSignals } from './gh-host-args' - -describe('applyGhHostToArgs', () => { - it('does not rewrite free-text flag values that merely start with -R', () => { - expect( - applyGhHostToArgs( - ['pr', 'edit', '7', '--title', '-Refactor foo/bar', '--repo', 'a/b'], - 'github.acme-corp.com' - ) - ).toEqual([ - 'pr', - 'edit', - '7', - '--title', - '-Refactor foo/bar', - '--repo', - 'github.acme-corp.com/a/b' - ]) - }) -}) +import { collectGhArgvHostSignals } from './gh-host-args' describe('collectGhArgvHostSignals', () => { it('reads the attached -R forms gh accepts, so a bound call cannot drift hosts through them', () => { diff --git a/src/main/git/command-runner/process-capture/exec-file-capture.ts b/src/main/git/command-runner/process-capture/exec-file-capture.ts index 33befe475f3..8ab3429bcd4 100644 --- a/src/main/git/command-runner/process-capture/exec-file-capture.ts +++ b/src/main/git/command-runner/process-capture/exec-file-capture.ts @@ -7,7 +7,7 @@ import type { WslProcessGroupTermination } from './wsl-process-group-termination import { createAbortError } from './abort-error' import { killSpawnedCommandTree } from './spawned-command-tree-kill' import { DEFAULT_GIT_MAX_BUFFER } from '../git-exec-options' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { workerExecFile } from './worker-exec-file' import type { WorkerThreadChildProcess } from '../../../worker-thread-child-process/worker-thread-child-process' diff --git a/src/main/git/objects/local-git-object-quarantine.ts b/src/main/git/objects/local-git-object-quarantine.ts index 37d5187f525..dec9f09e89e 100644 --- a/src/main/git/objects/local-git-object-quarantine.ts +++ b/src/main/git/objects/local-git-object-quarantine.ts @@ -1,5 +1,5 @@ import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { createGitObjectQuarantine, inheritedObjectStore, diff --git a/src/main/git/objects/merge-tree-object-quarantine-real-git.test.ts b/src/main/git/objects/merge-tree-object-quarantine-real-git.test.ts index 1f0e35f8267..5716ff5e377 100644 --- a/src/main/git/objects/merge-tree-object-quarantine-real-git.test.ts +++ b/src/main/git/objects/merge-tree-object-quarantine-real-git.test.ts @@ -10,8 +10,8 @@ import { import { __resetPRConflictSummaryCachesForTests, getPRConflictSummary -} from '../../github/conflict-summary' -import { __resetPRConflictSummaryDerivationCachesForTests } from '../../github/conflict-summary-cache' +} from '../../github/pull-requests/conflicts/conflict-summary' +import { __resetPRConflictSummaryDerivationCachesForTests } from '../../github/pull-requests/conflicts/conflict-summary-cache' import { getLocalGitCapabilityCache } from '../command-runner/host-routing/git-capability-state' import { deleteBranchAfterWorktreeRemoval } from '../worktrees/removal/worktree-branch-removal' diff --git a/src/main/git/refs/git-ref-change-signal.ts b/src/main/git/refs/git-ref-change-signal.ts new file mode 100644 index 00000000000..9cd7f2c9e28 --- /dev/null +++ b/src/main/git/refs/git-ref-change-signal.ts @@ -0,0 +1,44 @@ +import { gitRepositoryPathKey } from '../../../shared/git/metadata/git-repository-path-key' +type Listener = () => void +const listeners = new Map>() + +export function subscribeGitRefChanges(commonDir: string, listener: Listener): () => void { + commonDir = gitRepositoryPathKey(commonDir) + const subscribers = listeners.get(commonDir) ?? new Set() + subscribers.add(listener) + listeners.set(commonDir, subscribers) + return () => { + subscribers.delete(listener) + if (subscribers.size === 0 && listeners.get(commonDir) === subscribers) { + listeners.delete(commonDir) + } + } +} + +/** Unknown checkout ownership fences every live reader without delaying the mutation for discovery. */ +export function publishGitRefChange(commonDir: string | null): void { + commonDir = commonDir === null ? null : gitRepositoryPathKey(commonDir) + const targets = commonDir === null ? [...listeners.values()] : [listeners.get(commonDir)] + for (const subscribers of targets) { + const callbacks = Array.from(subscribers ?? []) + for (const listener of callbacks) { + try { + listener() + } catch { + // Cache bookkeeping must never refuse a Git action. + } + } + } +} + +export function beginGitRefMutation(commonDir: string | null): () => void { + publishGitRefChange(commonDir) + let ended = false + return () => { + if (ended) { + return + } + ended = true + publishGitRefChange(commonDir) + } +} diff --git a/src/main/git/refs/maintenance/local-repo-ref-maintenance.ts b/src/main/git/refs/maintenance/local-repo-ref-maintenance.ts index ced6f231913..13e6e02a34c 100644 --- a/src/main/git/refs/maintenance/local-repo-ref-maintenance.ts +++ b/src/main/git/refs/maintenance/local-repo-ref-maintenance.ts @@ -154,7 +154,7 @@ export type LocalRepoRefMaintenanceTargetArgs = { readonly wslDistro?: string } -/** Restart the quiet period after a write; check the kill switch before arming timers. */ +/** Retain an idle opportunity after a write; check the kill switch before arming timers. */ export function armLocalRepoRefMaintenance(args: LocalRepoRefMaintenanceTargetArgs): void { if (isDisabled()) { return diff --git a/src/main/git/refs/resolution/base-ref-search-selector.test.ts b/src/main/git/refs/resolution/base-ref-search-selector.test.ts index 86b9adeca68..d5b94a9ae6b 100644 --- a/src/main/git/refs/resolution/base-ref-search-selector.test.ts +++ b/src/main/git/refs/resolution/base-ref-search-selector.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest' -import { parseAndFilterSearchRefDetails } from './repo-base-ref-search' import { resolveBaseRefSearchSelector } from './base-ref-search-selector' describe('base ref search selectors', () => { @@ -39,24 +38,4 @@ describe('base ref search selectors', () => { ])('preserves the identity of %s with short field %s', (full, short, expected) => { expect(resolveBaseRefSearchSelector(full, short)).toBe(expected) }) - - it('filters unsupported selectors before the page limit and deduplicates recovered full refs', () => { - const stdout = [ - 'refs/heads/feature/加\0feature/�', - 'refs/heads/feature/加\0feature/�', - 'refs/remotes/origin/feature/加\0origin/feature/�', - 'refs/heads/safe-one\0safe-one', - 'refs/heads/safe-two\0safe-two', - 'refs/heads/safe-three\0safe-three' - ].join('\n') - expect(parseAndFilterSearchRefDetails(stdout, 2, ['origin'], false)).toEqual([ - { refName: 'safe-one', localBranchName: 'safe-one' }, - { refName: 'safe-two', localBranchName: 'safe-two' } - ]) - expect(parseAndFilterSearchRefDetails(stdout, 3, ['origin'])).toEqual([ - { refName: 'refs/heads/feature/加', localBranchName: 'feature/加' }, - { refName: 'refs/remotes/origin/feature/加', localBranchName: 'feature/加' }, - { refName: 'safe-one', localBranchName: 'safe-one' } - ]) - }) }) diff --git a/src/main/git/refs/resolution/local-branch-merge-proof.ts b/src/main/git/refs/resolution/local-branch-merge-proof.ts new file mode 100644 index 00000000000..634c9795ced --- /dev/null +++ b/src/main/git/refs/resolution/local-branch-merge-proof.ts @@ -0,0 +1,55 @@ +import { + branchHasNoUnmergedChangesOnAnyTarget, + branchHasNoUnmergedChangesWithLazyTargetRefresh, + getBranchCleanupTargetRefs, + type GitBranchCleanupExecOptions +} from '../../../../shared/git/branches/git-branch-cleanup' +import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/host-routing/git-capability-state' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { offlineGitEnv } from '../../command-runner/git-environment/git-process-env' +import { routeLocalGitOptions } from '../../command-runner/host-routing/local-git-runtime-route' +import { createLocalGitObjectQuarantine } from '../../objects/local-git-object-quarantine' +import { + gitExecOptions, + type GitWorktreeExecOptions +} from '../../worktrees/worktree-operation-options' + +/** Git's proof that a local branch adds no changes to a target, squash and rebase merges included. */ +export async function localBranchHasNoUnmergedChanges(args: { + cwd: string + branchName: string + /** Defaults to the branch-cleanup targets, which include `cwd`'s HEAD: pass explicit refs from a linked worktree. */ + targetRefs?: string[] + /** Fetch stale remote targets before giving up; false keeps the proof offline, partial-clone blob fetches included. */ + refreshRemoteTargets: boolean + options?: GitWorktreeExecOptions +}): Promise { + const { cwd, branchName, refreshRemoteTargets } = args + // Settle the project's WSL route first so quarantine and capability caches match the Git that runs. + const options = routeLocalGitOptions({ ...args.options, cwd }) + const quarantine = createLocalGitObjectQuarantine(cwd, options) + const runGit = (argv: string[], execOptions?: GitBranchCleanupExecOptions) => { + const run = (quarantineEnv: NodeJS.ProcessEnv | undefined) => { + const env = refreshRemoteTargets ? quarantineEnv : offlineGitEnv(quarantineEnv) + return gitExecFileAsync(argv, { + ...gitExecOptions(cwd, options), + ...(execOptions?.stdin !== undefined ? { stdin: execOptions.stdin } : {}), + ...(env ? { env } : {}) + }) + } + return execOptions?.discardWrittenObjects ? quarantine.run(run) : run(undefined) + } + const targetRefs = args.targetRefs ?? (await getBranchCleanupTargetRefs(runGit, branchName)) + return withLocalGitCapabilityCacheForExecution( + { cwd, wslDistro: options.wslDistro, signal: options.signal }, + (capabilities) => + refreshRemoteTargets + ? branchHasNoUnmergedChangesWithLazyTargetRefresh( + runGit, + branchName, + targetRefs, + capabilities + ) + : branchHasNoUnmergedChangesOnAnyTarget(runGit, branchName, targetRefs, capabilities) + ) +} diff --git a/src/main/git/refs/resolution/repo-base-ref-search.ts b/src/main/git/refs/resolution/repo-base-ref-search.ts index 4aed3dd18f4..59e17cb9180 100644 --- a/src/main/git/refs/resolution/repo-base-ref-search.ts +++ b/src/main/git/refs/resolution/repo-base-ref-search.ts @@ -5,41 +5,9 @@ import { REPO_SEARCH_REFS_DEFAULT_LIMIT, isRepoSearchRefsRequestLimit } from '../../../../shared/repo-search-limits' -import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' -import { isRemoteHeadRef } from '../../../../shared/source-control/hosted-review/hosted-review-refs' -import { runSearchBaseRefsGit } from './repo-ref-search-command' - -import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { isQualifiedBaseRef, resolveBaseRefSearchSelector } from './base-ref-search-selector' - -type RefSearchPatternGroup = 'all' | 'segmented' | 'branchRoot' -function getRefSearchTokens(query: string) { - return query.split('/').filter(Boolean) -} - -export function mergeBaseRefSearchResultGroups( - groups: readonly BaseRefSearchResult[][], - limit: number -): BaseRefSearchResult[] { - const seen = new Set() - const merged: BaseRefSearchResult[] = [] - const maxLength = Math.max(0, ...groups.map((group) => group.length)) - for (let index = 0; index < maxLength && merged.length < limit; index += 1) { - for (const group of groups) { - const entry = group[index] - if (!entry || seen.has(entry.refName)) { - continue - } - seen.add(entry.refName) - merged.push(entry) - if (merged.length >= limit) { - break - } - } - } - return merged -} +import { searchBranchRefSnapshot, snapshotRemoteNames } from '../snapshot/branch-ref-snapshot' +import { searchLegacyBaseRefDetails } from './repo-legacy-ref-search' +import type { LocalGitExecOptions } from './repo-default-base-ref' export async function searchBaseRefs( path: string, @@ -63,42 +31,13 @@ export async function searchBaseRefDetails( if (!isRepoSearchRefsRequestLimit(limit)) { return [] } - const boundedScanLimit = clampRepoSearchRefsScanLimit(limit) - const normalizedQuery = normalizeRefSearchQuery(query) - + if (!includeQualifiedRefs) { + return searchLegacyBaseRefDetails(path, query, limit, git) + } try { - const remotes = await listRemoteNames(path, git) - const search = (patternGroup?: RefSearchPatternGroup): Promise<{ stdout: string }> => - runSearchBaseRefsGit(path, normalizedQuery, boundedScanLimit, { - remoteNames: remotes, - patternGroup, - git - }) - const tokens = getRefSearchTokens(normalizedQuery) - if (tokens.length > 1) { - const results = await Promise.all([search('segmented'), search('branchRoot')]) - return mergeBaseRefSearchResultGroups( - results.map((entry) => - parseAndFilterSearchRefDetails( - entry.stdout, - boundedScanLimit, - remotes, - includeQualifiedRefs - ) - ), - boundedScanLimit - ) - } - - const result = await search() - return parseAndFilterSearchRefDetails( - result.stdout, - boundedScanLimit, - remotes, - includeQualifiedRefs - ) + return await searchBranchRefSnapshot(path, query, clampRepoSearchRefsScanLimit(limit), git) } catch (err) { - console.warn('[searchBaseRefs] for-each-ref failed', { path, err }) + console.warn('[searchBaseRefs] branch snapshot failed', { path, err }) return [] } } @@ -108,91 +47,8 @@ export async function listRemoteNames( options: LocalGitExecOptions = {} ): Promise { try { - const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) - return stdout - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) + return await snapshotRemoteNames(path, options) } catch { return [] } } - -export function parseAndFilterSearchRefDetails( - stdout: string, - limit: number, - remotes: string[] = [], - includeQualifiedRefs = true -): BaseRefSearchResult[] { - const seen = new Set() - const sortedRemotes = [...remotes].sort((a, b) => b.length - a.length) - - return stdout - .split('\n') - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .map((line) => { - const nul = line.indexOf('\0') - if (nul === -1) { - return null - } - const full = line.slice(0, nul) - const gitShort = line.slice(nul + 1) - return { full, short: resolveBaseRefSearchSelector(full, gitShort) } - }) - .filter((entry): entry is { full: string; short: string } => entry !== null) - .filter(({ full }) => isSafeGitRefName(full) && !isRemoteHeadRef(full, sortedRemotes)) - .filter(({ short }) => includeQualifiedRefs || !isQualifiedBaseRef(short)) - .filter(({ short }) => { - if (seen.has(short)) { - return false - } - seen.add(short) - return true - }) - .map(({ full, short }) => ({ - refName: short, - localBranchName: resolveLocalBranchName(full, short, sortedRemotes) - })) - .slice(0, Math.max(0, limit)) -} - -export function resolveConfiguredRemoteBranchName( - fullRef: string, - longestFirstRemoteNames: readonly string[] -): string | null { - const remoteRefPrefix = 'refs/remotes/' - if (!fullRef.startsWith(remoteRefPrefix)) { - return null - } - const remoteAndBranch = fullRef.slice(remoteRefPrefix.length) - const remote = longestFirstRemoteNames.find((candidate) => - remoteAndBranch.startsWith(`${candidate}/`) - ) - return remote ? remoteAndBranch.slice(remote.length + 1) || null : null -} - -export function resolveLocalBranchName( - fullRef: string, - shortRef: string, - remotes: string[] -): string { - const localRefPrefix = 'refs/heads/' - if (fullRef.startsWith(localRefPrefix)) { - return fullRef.slice(localRefPrefix.length) || shortRef - } - const remoteRefPrefix = 'refs/remotes/' - if (!fullRef.startsWith(remoteRefPrefix)) { - return shortRef - } - const configuredBranch = resolveConfiguredRemoteBranchName(fullRef, remotes) - if (configuredBranch) { - return configuredBranch - } - const remoteAndBranch = fullRef.slice(remoteRefPrefix.length) - return remoteAndBranch.split('/').slice(1).join('/') || shortRef -} - -export function normalizeRefSearchQuery(query: string): string { - return query.trim().replace(/[*?[\]\\]/g, '') -} diff --git a/src/main/git/refs/resolution/repo-branch-conflict.ts b/src/main/git/refs/resolution/repo-branch-conflict.ts index 0d6efa0ca93..973e3225ae9 100644 --- a/src/main/git/refs/resolution/repo-branch-conflict.ts +++ b/src/main/git/refs/resolution/repo-branch-conflict.ts @@ -1,4 +1,4 @@ -import { resolveConfiguredRemoteBranchName } from './repo-base-ref-search' +import { resolveConfiguredRemoteBranchName } from '../snapshot/branch-ref-snapshot-data' import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' diff --git a/src/main/git/refs/resolution/repo-default-base-ref.ts b/src/main/git/refs/resolution/repo-default-base-ref.ts index b1592b3a736..f811ffd7bb4 100644 --- a/src/main/git/refs/resolution/repo-default-base-ref.ts +++ b/src/main/git/refs/resolution/repo-default-base-ref.ts @@ -1,4 +1,4 @@ -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { resolveDefaultBaseRefViaExec } from '../../../../shared/git/refs/git-default-base-ref' diff --git a/src/main/git/refs/resolution/repo-legacy-ref-search.ts b/src/main/git/refs/resolution/repo-legacy-ref-search.ts new file mode 100644 index 00000000000..ca952513b24 --- /dev/null +++ b/src/main/git/refs/resolution/repo-legacy-ref-search.ts @@ -0,0 +1,170 @@ +import { resolveLocalBranchName } from '../snapshot/branch-ref-snapshot-data' +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import { + clampRepoSearchRefsScanLimit, + REPO_SEARCH_REFS_DEFAULT_LIMIT, + isRepoSearchRefsRequestLimit +} from '../../../../shared/repo-search-limits' +import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' +import { isRemoteHeadRef } from '../../../../shared/source-control/hosted-review/hosted-review-refs' +import { runSearchBaseRefsGit } from './repo-ref-search-command' + +import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { isQualifiedBaseRef, resolveBaseRefSearchSelector } from './base-ref-search-selector' + +type RefSearchPatternGroup = 'all' | 'segmented' | 'branchRoot' +function getRefSearchTokens(query: string) { + return query.split('/').filter(Boolean) +} + +export function mergeBaseRefSearchResultGroups( + groups: readonly BaseRefSearchResult[][], + limit: number +): BaseRefSearchResult[] { + const seen = new Set() + const merged: BaseRefSearchResult[] = [] + const maxLength = Math.max(0, ...groups.map((group) => group.length)) + for (let index = 0; index < maxLength && merged.length < limit; index += 1) { + for (const group of groups) { + const entry = group[index] + if (!entry || seen.has(entry.refName)) { + continue + } + seen.add(entry.refName) + merged.push(entry) + if (merged.length >= limit) { + break + } + } + } + return merged +} + +export async function searchLegacyBaseRefDetails( + path: string, + query: string, + limit = REPO_SEARCH_REFS_DEFAULT_LIMIT, + git: LocalGitExecOptions = {} +): Promise { + if (!isRepoSearchRefsRequestLimit(limit)) { + return [] + } + const boundedScanLimit = clampRepoSearchRefsScanLimit(limit) + const normalizedQuery = normalizeRefSearchQuery(query) + + try { + const remotes = await listRemoteNames(path, git) + const search = (patternGroup?: RefSearchPatternGroup): Promise<{ stdout: string }> => + runSearchBaseRefsGit(path, normalizedQuery, boundedScanLimit, { + remoteNames: remotes, + patternGroup, + git + }) + const tokens = getRefSearchTokens(normalizedQuery) + if (tokens.length > 1) { + const results = await Promise.all([search('segmented'), search('branchRoot')]) + return mergeBaseRefSearchResultGroups( + results.map((entry) => + parseAndFilterSearchRefDetails(entry.stdout, boundedScanLimit, remotes, false) + ), + boundedScanLimit + ) + } + + const result = await search() + return parseAndFilterSearchRefDetails(result.stdout, boundedScanLimit, remotes, false) + } catch (err) { + console.warn('[searchBaseRefs] for-each-ref failed', { path, err }) + return [] + } +} + +export async function listRemoteNames( + path: string, + options: LocalGitExecOptions = {} +): Promise { + try { + const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) + return stdout + .split('\n') + .map((line) => line.trim()) + .filter(Boolean) + } catch { + return [] + } +} + +export function parseAndFilterSearchRefDetails( + stdout: string, + limit: number, + remotes: string[] = [], + includeQualifiedRefs = true +): BaseRefSearchResult[] { + const seen = new Set() + const sortedRemotes = [...remotes].sort((a, b) => b.length - a.length) + + return stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0) + .map((line) => { + const nul = line.indexOf('\0') + if (nul === -1) { + return null + } + const full = line.slice(0, nul) + const gitShort = line.slice(nul + 1) + return { full, short: resolveBaseRefSearchSelector(full, gitShort) } + }) + .filter((entry): entry is { full: string; short: string } => entry !== null) + .filter(({ full }) => isSafeGitRefName(full) && !isRemoteHeadRef(full, sortedRemotes)) + .filter(({ short }) => includeQualifiedRefs || !isQualifiedBaseRef(short)) + .filter(({ short }) => { + if (seen.has(short)) { + return false + } + seen.add(short) + return true + }) + .map(({ full, short }) => ({ + refName: short, + localBranchName: resolveLocalBranchName(full, short, sortedRemotes) + })) + .slice(0, Math.max(0, limit)) +} + +export function normalizeRefSearchQuery(query: string): string { + return query.trim().replace(/[*?[\]\\]/g, '') +} + +export async function searchLegacyRemoteRefPage( + path: string, + query: string, + limit: number +): Promise<{ refDetails: BaseRefSearchResult[]; truncated: boolean }> { + const { stdout } = await gitExecFileAsync(['remote'], { cwd: path }) + const remoteNames = stdout.split('\n').filter(Boolean) + const normalized = normalizeRefSearchQuery(query) + const groups: ('segmented' | 'branchRoot' | 'all')[] = + normalized.split('/').filter(Boolean).length > 1 ? ['segmented', 'branchRoot'] : ['all'] + const results = await Promise.all( + groups.map((patternGroup) => + runSearchBaseRefsGit(path, normalized, limit + 1, { + namespace: 'remote', + remoteNames, + patternGroup + }) + ) + ) + const candidates = mergeBaseRefSearchResultGroups( + results.map((result) => parseAndFilterSearchRefDetails(result.stdout, limit + 1, remoteNames)), + limit + 1 + ) + return { + refDetails: candidates.slice(0, limit), + truncated: + candidates.length > limit || + results.some((result) => result.stdout.split('\n').filter(Boolean).length >= (limit + 1) * 4) + } +} diff --git a/src/main/git/refs/resolution/repo-ref-search-command.ts b/src/main/git/refs/resolution/repo-ref-search-command.ts index cbbac206f7c..3aba9cf2542 100644 --- a/src/main/git/refs/resolution/repo-ref-search-command.ts +++ b/src/main/git/refs/resolution/repo-ref-search-command.ts @@ -7,6 +7,7 @@ import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstr import { getLocalGitCapabilityCache } from '../../command-runner/host-routing/git-capability-state' import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { withRepositoryGitCause } from '../../repository-git-cause' const REF_SEARCH_CANDIDATE_MULTIPLIER = 4 const REF_SEARCH_LEGACY_HEADROOM = 100 @@ -118,27 +119,33 @@ export async function runSearchBaseRefsGit( } ): Promise<{ stdout: string }> { const execOptions = gitExecOptions(path, options.git) - return getLocalGitCapabilityCache(execOptions).runWithFallback( - 'for-each-ref-exclude', + return withRepositoryGitCause( + path, + execOptions, + { family: 'refs', reason: 'branch-search', cache: 'uncached' }, () => - gitExecFileAsync( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - namespace: options.namespace, - remoteNames: options.remoteNames, - patternGroup: options.patternGroup - }), - execOptions - ), - () => - gitExecFileAsync( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - excludeRemoteHead: false, - namespace: options.namespace, - remoteNames: options.remoteNames, - patternGroup: options.patternGroup - }), - execOptions - ), - isForEachRefExcludeUnsupportedError + getLocalGitCapabilityCache(execOptions).runWithFallback( + 'for-each-ref-exclude', + () => + gitExecFileAsync( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + namespace: options.namespace, + remoteNames: options.remoteNames, + patternGroup: options.patternGroup + }), + execOptions + ), + () => + gitExecFileAsync( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + excludeRemoteHead: false, + namespace: options.namespace, + remoteNames: options.remoteNames, + patternGroup: options.patternGroup + }), + execOptions + ), + isForEachRefExcludeUnsupportedError + ) ) } diff --git a/src/main/git/refs/resolution/repo-remote-ref-search.ts b/src/main/git/refs/resolution/repo-remote-ref-search.ts index 59cece9edb9..45837f6359f 100644 --- a/src/main/git/refs/resolution/repo-remote-ref-search.ts +++ b/src/main/git/refs/resolution/repo-remote-ref-search.ts @@ -1,39 +1,30 @@ +import { searchLegacyRemoteRefPage } from './repo-legacy-ref-search' import type { BaseRefSearchResult } from '../../../../shared/repo-types' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { runSearchBaseRefsGit } from './repo-ref-search-command' import { - normalizeRefSearchQuery, - parseAndFilterSearchRefDetails, - mergeBaseRefSearchResultGroups -} from './repo-base-ref-search' + clampRepoSearchRefsLimit, + getRepoSearchRefsProbeLimit +} from '../../../../shared/repo-search-limits' +import { searchBranchRefSnapshot } from '../snapshot/branch-ref-snapshot' export async function searchRemoteRefPage( path: string, query: string, - limit: number + limit: number, + includeQualifiedRefs = true ): Promise<{ refDetails: BaseRefSearchResult[]; truncated: boolean }> { - const { stdout } = await gitExecFileAsync(['remote'], { cwd: path }) - const remoteNames = stdout.split('\n').filter(Boolean) - const normalized = normalizeRefSearchQuery(query) - const groups: ('segmented' | 'branchRoot' | 'all')[] = - normalized.split('/').filter(Boolean).length > 1 ? ['segmented', 'branchRoot'] : ['all'] - const results = await Promise.all( - groups.map((patternGroup) => - runSearchBaseRefsGit(path, normalized, limit + 1, { - namespace: 'remote', - remoteNames, - patternGroup - }) - ) - ) - const candidates = mergeBaseRefSearchResultGroups( - results.map((result) => parseAndFilterSearchRefDetails(result.stdout, limit + 1, remoteNames)), - limit + 1 + if (!includeQualifiedRefs) { + return searchLegacyRemoteRefPage(path, query, limit) + } + const bounded = clampRepoSearchRefsLimit(limit) + const candidates = await searchBranchRefSnapshot( + path, + query, + getRepoSearchRefsProbeLimit(bounded), + {}, + true ) return { - refDetails: candidates.slice(0, limit), - truncated: - candidates.length > limit || - results.some((result) => result.stdout.split('\n').filter(Boolean).length >= (limit + 1) * 4) + refDetails: candidates.slice(0, bounded), + truncated: limit > bounded || candidates.length > bounded } } diff --git a/src/main/git/refs/resolution/repo.test.ts b/src/main/git/refs/resolution/repo.test.ts index f8ad4c36890..2de4a6db922 100644 --- a/src/main/git/refs/resolution/repo.test.ts +++ b/src/main/git/refs/resolution/repo.test.ts @@ -3,7 +3,7 @@ import { execFileSync } from 'node:child_process' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' -import '../../../../shared/worktree/base-ref' +import '../../../../shared/worktree/base-refs/base-ref' import { searchBaseRefDetails } from './repo-base-ref-search' // Real Git exercises ref globs that mocks cannot validate. @@ -48,7 +48,6 @@ describe('searchBaseRefs (widened glob)', () => { git(tmpDir, ['remote', 'add', 'origin', 'https://example.invalid/repo.git']) createRemoteRef(tmpDir, `origin/${branch}`, sha) const results = await searchBaseRefDetails(tmpDir, '加') - expect(results).toHaveLength(2) const worktreeRoot = mkdtempSync(path.join(tmpdir(), 'orca-unicode-worktrees-')) try { for (const [index, result] of results.entries()) { @@ -71,8 +70,6 @@ describe('searchBaseRefs (widened glob)', () => { git(tmpDir, ['tag', branch]) const results = await searchBaseRefDetails(tmpDir, '运动记录') - - expect(results).toHaveLength(1) expect(results[0]?.refName).toBe(`refs/heads/${branch}`) expect(results[0]?.localBranchName).toBe(branch) expect(git(tmpDir, ['rev-parse', '--verify', results[0]?.refName ?? '']).trim()).toBe(branchSha) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-data.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-data.ts new file mode 100644 index 00000000000..758d8f95613 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-data.ts @@ -0,0 +1,117 @@ +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import { branchRefLabel } from '../../../../shared/git/refs/branch-ref-label' +import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' +import { isRemoteHeadRef } from '../../../../shared/source-control/hosted-review/hosted-review-refs' + +export type BranchRef = { + refName: string + oid: string + committedAt: number + symref: string + label: string + searchName: string +} + +export const BRANCH_REF_SNAPSHOT_ARGS = [ + 'for-each-ref', + '--sort=refname', + '--sort=-committerdate', + '--format=%(refname)%00%(objectname)%00%(committerdate:unix)%00%(symref)', + 'refs/heads', + 'refs/remotes' +] + +export function parseBranchRef(line: string): BranchRef | null { + const [refName, oid, timestamp, symref = ''] = line.replace(/\r$/, '').split('\0') + if (!refName || !oid || !isSafeGitRefName(refName) || !/^refs\/(heads|remotes)\//.test(refName)) { + return null + } + const label = branchRefLabel(refName) + return { + refName, + oid, + committedAt: Number.isFinite(Number(timestamp)) ? Number(timestamp) * 1000 : 0, + symref, + label, + searchName: label.toLowerCase() + } +} + +export function resolveConfiguredRemoteBranchName( + fullRef: string, + longestFirstRemoteNames: readonly string[] +): string | null { + if (!fullRef.startsWith('refs/remotes/')) { + return null + } + const remoteAndBranch = fullRef.slice('refs/remotes/'.length) + const remote = longestFirstRemoteNames.find((name) => remoteAndBranch.startsWith(`${name}/`)) + return remote ? remoteAndBranch.slice(remote.length + 1) || null : null +} + +export function resolveLocalBranchName( + fullRef: string, + fallback: string, + remotes: string[] +): string { + if (fullRef.startsWith('refs/heads/')) { + return fullRef.slice('refs/heads/'.length) || fallback + } + if (!fullRef.startsWith('refs/remotes/')) { + return fallback + } + return ( + (resolveConfiguredRemoteBranchName(fullRef, remotes) ?? + fullRef.slice('refs/remotes/'.length).split('/').slice(1).join('/')) || + fallback + ) +} + +export function matchesBranchRef(ref: BranchRef, query: string, remoteOnly: boolean): boolean { + return (!remoteOnly || ref.refName.startsWith('refs/remotes/')) && ref.searchName.includes(query) +} + +export function projectBranchRefs( + refs: Iterable, + remotes: string[], + query: string, + limit: number, + remoteOnly = false +): BaseRefSearchResult[] { + const results: BaseRefSearchResult[] = [] + const project = createBranchRefProjection(remotes, query, remoteOnly) + for (const ref of refs) { + const result = project(ref) + if (result) { + results.push(result) + } + if (results.length >= limit) { + break + } + } + return results +} + +export function createBranchRefProjection( + remotes: string[], + query: string, + remoteOnly = false +): (ref: BranchRef) => BaseRefSearchResult | null { + const normalized = query + .trim() + .replace(/[*?[\]\\]/g, '') + .toLowerCase() + const longestFirst = [...remotes].sort((left, right) => right.length - left.length) + return (ref) => { + if ( + !matchesBranchRef(ref, normalized, remoteOnly) || + isRemoteHeadRef(ref.refName, longestFirst) + ) { + return null + } + return { + refName: ref.refName, + localBranchName: resolveLocalBranchName(ref.refName, ref.label, longestFirst) + } + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-identity.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-identity.ts new file mode 100644 index 00000000000..b033ab634c9 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-identity.ts @@ -0,0 +1,61 @@ +import { realpath, stat } from 'node:fs/promises' +import { dirname } from 'node:path' +import { resolveGitCommonDirectory } from '../../../../shared/git/metadata/git-common-directory' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import { gitRepositoryPathKey } from '../../../../shared/git/metadata/git-repository-path-key' +import { wslDistroForCommand } from '../../../../shared/wsl-paths' +import { routeLocalGitOptions } from '../../command-runner/host-routing/local-git-runtime-route' +import { prepareWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import type { LocalGitExecOptions } from '../resolution/repo-default-base-ref' +import { resolveGitDir } from '../../source-control/resolve-git-dir' + +export type BranchSnapshotIdentity = { + key: string + commonDir: string + gitDir: string + checkoutKey: string + cwd: string + git: LocalGitExecOptions +} + +export async function resolveBranchSnapshotIdentity( + cwd: string, + git: LocalGitExecOptions +): Promise { + const routed = routeLocalGitOptions({ cwd, ...git }) + if (await blockedWslDistroForPath(cwd, routed.wslDistro)) { + throw new Error('The project Git runtime is not running') + } + const distro = (await prepareWslLinkedWorktreeGitRouting(cwd, routed.wslDistro)) + ? null + : wslDistroForCommand(cwd, routed.wslDistro) + const runtime = distro ? `wsl:${distro.toLowerCase()}` : 'host' + let hostRoot = await realpath(resolveWorktreeHostPath(cwd, routed) ?? cwd) + let commonDir = await resolveGitCommonDirectory(hostRoot, routed) + while (!commonDir) { + const parent = dirname(hostRoot) + if (parent === hostRoot) { + return null + } + hostRoot = parent + commonDir = await resolveGitCommonDirectory(hostRoot, routed) + } + const physicalCommonDir = await realpath(commonDir) + const commonStat = await stat(physicalCommonDir, { bigint: true }) + const checkoutGitDir = await resolveGitDir(hostRoot, routed) + const gitDir = await stat(checkoutGitDir).then( + (entry) => (entry.isDirectory() ? checkoutGitDir : commonDir), + () => commonDir + ) + const physicalGitDir = await realpath(gitDir) + const checkoutStat = await stat(physicalGitDir, { bigint: true }) + return { + key: `${runtime}\0${gitRepositoryPathKey(physicalCommonDir)}\0${commonStat.dev}:${commonStat.ino}:${commonStat.birthtimeNs}`, + commonDir: physicalCommonDir, + gitDir: physicalGitDir, + checkoutKey: `${gitRepositoryPathKey(physicalGitDir)}\0${checkoutStat.dev}:${checkoutStat.ino}:${checkoutStat.birthtimeNs}`, + cwd, + git: routed + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-metadata.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-metadata.ts new file mode 100644 index 00000000000..77c393f4bdd --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-metadata.ts @@ -0,0 +1,52 @@ +import type { BranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import type { BranchSnapshotOwners, Owner, Context } from './branch-ref-snapshot-owners' +import { readBranchRemoteNames } from './branch-ref-snapshot-read' + +const MAX_CONTEXTS = 64 + +export class BranchSnapshotMetadata { + constructor(private readonly cache: BranchSnapshotOwners) {} + + context(owner: Owner, identity: BranchSnapshotIdentity): Context { + const key = identity.checkoutKey + const existing = owner.contexts.get(key) + if (existing) { + return existing + } + if (owner.contexts.size >= MAX_CONTEXTS) { + const oldest = owner.contexts.keys().next().value + if (oldest !== undefined) { + this.cache.retireContext(owner, oldest, owner.contexts.get(oldest)!) + } + } + const context: Context = { + leases: new Set(), + remotes: Promise.resolve([]) + } + const current = () => !owner.disposed && owner.contexts.get(key) === context + const lease = this.cache.lease(owner, current) + owner.contexts.set(key, context) + context.remotes = readBranchRemoteNames(identity.cwd, identity.git) + .then(async (remotes) => { + await this.cache.validate(identity, owner) + if (lease.reserve(256 + remotes.reduce((sum, name) => sum + 48 + name.length * 2, 0))) { + context.leases.add(lease) + } else { + this.cache.retireContext(owner, key, context) + } + return remotes + }) + .catch((error: unknown) => { + this.cache.retireContext(owner, key, context) + throw error + }) + return context + } + + async remoteNames(identity: BranchSnapshotIdentity): Promise { + const owner = this.cache.owner(identity) + return owner + ? this.context(owner, identity).remotes + : readBranchRemoteNames(identity.cwd, identity.git) + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-owners.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-owners.ts new file mode 100644 index 00000000000..0d4685e46fd --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-owners.ts @@ -0,0 +1,174 @@ +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import { + resolveBranchSnapshotIdentity, + type BranchSnapshotIdentity +} from './branch-ref-snapshot-identity' +import type { BranchRef } from './branch-ref-snapshot-data' +import { + BRANCH_SNAPSHOT_MAX_BYTES, + type BranchRefSnapshot, + type BranchSnapshotRetention +} from './branch-ref-snapshot-read' + +export const BRANCH_SNAPSHOT_TTL_MS = 2 * 60_000 +const MAX_OWNERS = 64 +export class BranchSnapshotIdentityChanged extends Error {} + +export type Lease = BranchSnapshotRetention & { bytes: number } +export type Context = { + remotes: Promise + leases: Set +} +export type Capture = { + snapshot: BranchRefSnapshot | null + request: string + page: BaseRefSearchResult[] + locals: BranchRef[] | null +} +export type Owner = { + key: string + generation: number + expiresAt: number + disposed: boolean + unsubscribe: () => void + snapshot: BranchRefSnapshot | null + snapshotLease?: Lease + oversized: boolean + localRefs?: readonly BranchRef[] + localLease?: Lease + flight?: { generation: number; promise: Promise } + contexts: Map + base?: Lease +} +export type BranchSnapshotSignals = { + subscribe(commonDir: string, listener: () => void): () => void +} + +export class BranchSnapshotOwners { + private readonly owners = new Map() + private allocatedBytes = 0 + constructor(private readonly signals: BranchSnapshotSignals) {} + + lease(owner: Owner, valid = () => true): Lease { + const lease: Lease = { + bytes: 0, + reserve: (bytes) => { + if (owner.disposed || !valid()) { + return false + } + for (const candidate of this.owners.values()) { + if (this.allocatedBytes + bytes <= BRANCH_SNAPSHOT_MAX_BYTES) { + break + } + if (candidate !== owner && !candidate.flight) { + this.retire(candidate) + } + } + if (this.allocatedBytes + bytes > BRANCH_SNAPSHOT_MAX_BYTES) { + return false + } + this.allocatedBytes += bytes + lease.bytes += bytes + return true + }, + release: () => { + this.allocatedBytes -= lease.bytes + lease.bytes = 0 + } + } + return lease + } + + retireContext(owner: Owner, key: string, context: Context): void { + if (owner.contexts.get(key) === context) { + owner.contexts.delete(key) + } + for (const lease of context.leases) { + lease.release() + } + context.leases.clear() + } + + private invalidate(owner: Owner): void { + owner.generation++ + owner.expiresAt = Date.now() + BRANCH_SNAPSHOT_TTL_MS + owner.oversized = false + owner.snapshot = null + owner.localRefs = undefined + owner.snapshotLease?.release() + owner.localLease?.release() + for (const [key, context] of owner.contexts) { + this.retireContext(owner, key, context) + } + owner.contexts.clear() + } + + retire(owner: Owner): void { + if (owner.disposed) { + return + } + owner.disposed = true + if (this.owners.get(owner.key) === owner) { + this.owners.delete(owner.key) + } + owner.unsubscribe() + this.invalidate(owner) + owner.base?.release() + } + + owner(identity: BranchSnapshotIdentity): Owner | null { + const now = Date.now() + for (const candidate of this.owners.values()) { + if (!candidate.flight && candidate.expiresAt <= now) { + this.retire(candidate) + } + } + let owner = this.owners.get(identity.key) + if (owner) { + this.owners.delete(identity.key) + this.owners.set(identity.key, owner) + return owner + } + if (this.owners.size >= MAX_OWNERS) { + const oldest = [...this.owners.values()].find((entry) => !entry.flight) + if (!oldest) { + return null + } + this.retire(oldest) + } + owner = { + key: identity.key, + generation: 0, + expiresAt: now + BRANCH_SNAPSHOT_TTL_MS, + disposed: false, + unsubscribe: () => {}, + snapshot: null, + oversized: false, + contexts: new Map() + } + owner.base = this.lease(owner) + if (!owner.base.reserve(1024 + 2 * (identity.key.length + identity.commonDir.length))) { + return null + } + this.owners.set(identity.key, owner) + const created = owner + created.unsubscribe = this.signals.subscribe(identity.commonDir, () => this.invalidate(created)) + return created + } + + async validate(identity: BranchSnapshotIdentity, owner?: Owner): Promise { + const current = await resolveBranchSnapshotIdentity(identity.cwd, identity.git) + if (!current || current.key !== identity.key || current.checkoutKey !== identity.checkoutKey) { + if (owner) { + this.retire(owner) + } + throw new BranchSnapshotIdentityChanged() + } + } + + reset(): void { + for (const owner of this.owners.values()) { + this.retire(owner) + } + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-read.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-read.test.ts new file mode 100644 index 00000000000..419d56412a1 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-read.test.ts @@ -0,0 +1,39 @@ +import { afterEach, expect, it, vi } from 'vitest' +const stream = vi.hoisted(() => vi.fn()) +vi.mock('../../command-runner/git-stream-stdout', () => ({ gitStreamStdout: stream })) +import { readBranchRefSnapshot } from './branch-ref-snapshot-read' + +afterEach(() => stream.mockReset()) + +it('keeps raw output complete under aggregate pressure and distinguishes an intrinsic bound', async () => { + stream.mockImplementation(async (_args, options) => { + for (const name of ['first', 'second']) { + if (options.onStdout(`refs/heads/${name}\0${'a'.repeat(40)}\u00001\0\n`) === true) { + return { stoppedEarly: true } + } + } + return { stoppedEarly: false } + }) + const page: string[] = [] + const pressured = await readBranchRefSnapshot( + '/repo', + {}, + (ref) => { + page.push(ref.refName) + return page.length === 2 + }, + undefined, + { reserve: () => false, release: () => {} } + ) + expect(page).toEqual(['refs/heads/first', 'refs/heads/second']) + expect(pressured).toEqual({ snapshot: null, oversized: false }) + expect(await readBranchRefSnapshot('/repo', {}, () => true, 100)).toEqual({ + snapshot: null, + oversized: true + }) + const recovered = await readBranchRefSnapshot('/repo', {}, () => true) + expect(recovered.snapshot?.refs.map((ref) => ref.refName)).toEqual([ + 'refs/heads/first', + 'refs/heads/second' + ]) +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-read.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-read.ts new file mode 100644 index 00000000000..1ebae032216 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-read.ts @@ -0,0 +1,111 @@ +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitStreamStdout } from '../../command-runner/git-stream-stdout' +import type { LocalGitExecOptions } from '../resolution/repo-default-base-ref' +import { gitOptionsForWorktree as gitExecOptions } from '../../command-runner/git-runtime-options' +import { + BRANCH_REF_SNAPSHOT_ARGS, + parseBranchRef, + type BranchRef +} from './branch-ref-snapshot-data' + +export const BRANCH_SNAPSHOT_MAX_BYTES = 64 * 1024 * 1024 + +export type BranchRefSnapshot = { + refs: readonly BranchRef[] +} + +export type BranchSnapshotRetention = { + reserve(bytes: number): boolean + release(): void +} + +export async function readBranchRefSnapshot( + path: string, + git: LocalGitExecOptions, + onRef: (ref: BranchRef) => boolean | void, + maxRetainedBytes = BRANCH_SNAPSHOT_MAX_BYTES, + retention?: BranchSnapshotRetention +): Promise<{ snapshot: BranchRefSnapshot | null; oversized: boolean }> { + let refs: BranchRef[] | null = [] + let estimatedBytes = 256 + let oversized = false + if (retention && !retention.reserve(estimatedBytes)) { + refs = null + } + await readRefLines(BRANCH_REF_SNAPSHOT_ARGS, path, git, (line) => { + const ref = parseBranchRef(line) + if (!ref) { + return + } + const pageComplete = onRef(ref) + if (refs) { + const bytes = + 192 + + 2 * + (ref.refName.length + + ref.oid.length + + ref.symref.length + + ref.label.length + + ref.searchName.length) + estimatedBytes += bytes + if (estimatedBytes > maxRetainedBytes || (retention && !retention.reserve(bytes))) { + oversized = estimatedBytes > maxRetainedBytes && maxRetainedBytes > 0 + refs = null + retention?.release() + } else { + refs.push(ref) + } + } + return !refs && pageComplete === true + }).catch((error: unknown) => { + retention?.release() + throw error + }) + return { snapshot: refs ? { refs } : null, oversized } +} + +export async function readBranchRemoteNames( + path: string, + git: LocalGitExecOptions +): Promise { + const { stdout } = await gitExecFileAsync(['remote'], { + ...gitExecOptions(path, git), + maxBuffer: 1024 * 1024 + }) + return stdout + .split(/\r?\n/) + .map((name) => name.trim()) + .filter(Boolean) +} + +async function readRefLines( + args: string[], + path: string, + git: LocalGitExecOptions, + onLine: (line: string) => boolean | void +): Promise { + let carry = '' + await gitStreamStdout(args, { + ...gitExecOptions(path, git), + // The parser retains a bounded line/page when a population cannot be retained. + maxBuffer: Number.MAX_SAFE_INTEGER, + maxStderrBuffer: 64 * 1024, + onStdout: (chunk) => { + const lines = (carry + chunk).split('\n') + carry = lines.pop() ?? '' + if (carry.length > 64 * 1024) { + throw new Error('Git returned an oversized branch ref record') + } + for (const line of lines) { + if (onLine(line) === true) { + carry = '' + return true + } + } + return false + } + }) + if (carry) { + onLine(carry) + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-real-git.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-real-git.test.ts new file mode 100644 index 00000000000..65969258625 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-real-git.test.ts @@ -0,0 +1,302 @@ +import { mkdtemp, mkdir, realpath, rename, rm, symlink } from 'node:fs/promises' +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { listLocalBranches } from '../../worktrees/checkout/checkout' +import { _resetBranchRefSnapshotsForTests } from './branch-ref-snapshot' +import { searchBaseRefDetails } from '../resolution/repo-base-ref-search' +import { searchRemoteRefPage } from '../resolution/repo-remote-ref-search' +import { RuntimeRepositoryRefQueries } from '../../../runtime/repositories/runtime-repository-ref-queries' +import { + repoDispatcher, + makeRequest +} from '../../../runtime/rpc/methods/projects/repo-rpc.test-fixture' +import type { Repo } from '../../../../shared/repo-types' +import { drainSubprocessSpawnStats } from '../../../diagnostics/main-thread-churn-probe' +import { beginGitRefMutation, subscribeGitRefChanges } from '../git-ref-change-signal' +import { resolveBranchSnapshotIdentity } from './branch-ref-snapshot-identity' + +const roots: string[] = [] +const git = async (cwd: string, ...args: string[]) => + (await gitExecFileAsync(args, { cwd })).stdout.trim() + +afterEach(async () => { + vi.unstubAllEnvs() + _resetBranchRefSnapshotsForTests() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +it('discovers the physical parent of a symlink to a repository subdirectory', async () => { + const { root } = await fixture() + const parent = await mkdtemp(join(tmpdir(), 'orca-ref-alias-')) + roots.push(parent) + await mkdir(join(root, 'nested')) + await symlink(join(root, 'nested'), join(parent, 'alias'), 'junction') + expect(await searchBaseRefDetails(join(parent, 'alias'), 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) +}) + +it.each([10, 100])( + 'loads one population for %i refs and filters repeated entrypoint searches without children', + async (population) => { + const { root, tagOid } = await fixture() + await gitExecFileAsync(['update-ref', '--stdin'], { + cwd: root, + stdin: Array.from( + { length: population }, + (_, i) => `create refs/heads/scale-${i} ${tagOid}\n` + ).join('') + }) + const repo: Repo = { id: 'scale', path: root, displayName: 'scale', badgeColor: '', addedAt: 0 } + const runtime = new RuntimeRepositoryRefQueries({ resolveRepo: async () => repo }) + vi.stubEnv('ORCA_MAIN_THREAD_DIAGNOSTICS', '1') + drainSubprocessSpawnStats() + expect((await searchBaseRefDetails(root, 'scale-', 30)).length).toBe(Math.min(population, 30)) + expect(drainSubprocessSpawnStats()['git for-each-ref']?.count).toBe(1) + // Queries only need an existing generation; each surface's limit is a bounded projection. + for (let query = 0; query < 10; query++) { + await searchBaseRefDetails(root, `scale-${query}`, 30) + await runtime.search('scale', 'scale-', 20) + await runtime.search('scale', 'absent', 20, true, 'remote') + } + expect(drainSubprocessSpawnStats()).toEqual({}) + const identity = await resolveBranchSnapshotIdentity(root, {}) + const end = beginGitRefMutation(identity!.commonDir) + await searchBaseRefDetails(root, 'scale-', 30) + drainSubprocessSpawnStats() + await runtime.search('scale', 'scale-1', 20) + await searchBaseRefDetails(root, 'absent', 30) + expect(drainSubprocessSpawnStats()).toEqual({}) + end() + } +) + +async function fixture(): Promise<{ root: string; branchOid: string; tagOid: string }> { + const root = await mkdtemp(join(tmpdir(), 'orca-branch-snapshot-')) + roots.push(root) + await git(root, 'init', '-q', '-b', 'main') + const commit = () => + git( + root, + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.test', + 'commit', + '--allow-empty', + '-qm', + 'fixture' + ) + await commit() + const branchOid = await git(root, 'rev-parse', 'HEAD') + await git(root, 'branch', 'collision') + await commit() + const tagOid = await git(root, 'rev-parse', 'HEAD') + await git(root, 'tag', 'collision') + await git(root, 'remote', 'add', 'origin', 'https://example.invalid/repo.git') + await git(root, 'remote', 'add', 'team/fork', 'https://example.invalid/fork.git') + await gitExecFileAsync(['update-ref', '--stdin'], { + cwd: root, + stdin: [ + 'refs/heads/Feature/emoji😀', + 'refs/heads/origin/main', + 'refs/remotes/origin/main', + 'refs/remotes/origin/feature/HEAD', + 'refs/remotes/team/fork/release/topic' + ] + .map((ref) => `create ${ref} ${tagOid}\n`) + .join('') + }) + await git(root, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + return { root, branchOid, tagOid } +} + +it('searches readable branch names while keeping branch actions unambiguous', async () => { + const { root, branchOid, tagOid } = await fixture() + expect(branchOid).not.toBe(tagOid) + expect(await searchBaseRefDetails(root, 'feature/EMOJI', 30)).toEqual([ + { refName: 'refs/heads/Feature/emoji😀', localBranchName: 'Feature/emoji😀' } + ]) + expect(await searchBaseRefDetails(root, 'refs/heads', 30)).toEqual([]) + expect(await searchBaseRefDetails(root, 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) + expect(await git(root, 'rev-parse', 'refs/heads/collision')).toBe(branchOid) + expect(await searchBaseRefDetails(root, 'origin/main', 20)).toEqual([ + { refName: 'refs/heads/origin/main', localBranchName: 'origin/main' }, + { refName: 'refs/remotes/origin/main', localBranchName: 'main' } + ]) + expect(await searchRemoteRefPage(root, '', 2)).toEqual({ + refDetails: [ + { refName: 'refs/remotes/origin/feature/HEAD', localBranchName: 'feature/HEAD' }, + { refName: 'refs/remotes/origin/main', localBranchName: 'main' } + ], + truncated: true + }) +}) + +it('keeps ordinary branches available to a client without qualified-ref support', async () => { + const { root } = await fixture() + const repo: Repo = { + id: 'snapshot-test', + path: root, + displayName: 'fixture', + badgeColor: '', + addedAt: 0 + } + const queries = new RuntimeRepositoryRefQueries({ resolveRepo: async () => repo }) + const dispatcher = repoDispatcher({ + getRuntimeId: () => 'snapshot-test', + searchRepoRefs: (repo, query, limit, qualified, namespace) => + queries.search(repo, query, limit ?? 25, qualified, namespace) + }) + const response = await dispatcher.dispatch( + makeRequest('repo.searchRefs', { + repo: 'snapshot-test', + query: '', + limit: 20 + }), + { clientCapabilities: [] } + ) + const result = z + .object({ result: z.object({ refs: z.array(z.string()) }) }) + .parse(response).result + expect(result.refs).toContain('main') + expect(result.refs).not.toContain('collision') + expect(result.refs).not.toContain('refs/heads/collision') + expect(result.refs).not.toContain('refs/heads/Feature/emoji😀') + expect(result.refs.some((ref) => ref.startsWith('refs/'))).toBe(false) + await git(root, 'update-ref', 'refs/heads/origin/a', 'HEAD') + await git(root, 'update-ref', 'refs/remotes/origin/a', 'HEAD') + await git(root, 'update-ref', 'refs/remotes/origin/b', 'HEAD') + const remoteResponse = await dispatcher.dispatch( + makeRequest('repo.searchRefs', { + repo: 'snapshot-test', + query: '', + limit: 1, + namespace: 'remote' + }), + { clientCapabilities: [] } + ) + expect( + z + .object({ result: z.object({ refs: z.array(z.string()), truncated: z.boolean() }) }) + .parse(remoteResponse).result + ).toEqual({ refs: [], truncated: true }) +}) + +it('fences prior results even when our mutating command fails', async () => { + const { root } = await fixture() + expect(await searchBaseRefDetails(root, 'external', 20)).toEqual([]) + await promisify(execFile)('git', ['branch', 'external'], { cwd: root }) + await expect(git(root, 'branch', 'main')).rejects.toThrow() + expect(await searchBaseRefDetails(root, 'external', 20)).toEqual([ + { refName: 'refs/heads/external', localBranchName: 'external' } + ]) +}) + +it('shares linked checkout branches while reading current branch and occupancy per request', async () => { + const { root } = await fixture() + const linkedParent = await mkdtemp(join(tmpdir(), 'orca-branch-linked-')) + roots.push(linkedParent) + const linked = join(linkedParent, 'checkout') + await git(root, 'worktree', 'add', '-qb', 'other', linked) + const nested = join(linked, 'nested') + await mkdir(nested) + expect(await searchBaseRefDetails(nested, 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) + const mainBranches = await listLocalBranches(root) + const linkedBranches = await listLocalBranches(nested) + expect(mainBranches.current).toBe('main') + expect(mainBranches.branches[0]).toBe('main') + expect(linkedBranches.current).toBe('other') + expect(linkedBranches.branches[0]).toBe('other') + expect(linkedBranches.worktreePaths?.other).toBe(await realpath(linked)) + await git(root, 'branch', 'fresh') + expect(await searchBaseRefDetails(nested, 'fresh', 20)).toEqual([ + { refName: 'refs/heads/fresh', localBranchName: 'fresh' } + ]) +}) + +it('fences all live repositories for own writes from linked, known and unknown paths', async () => { + const { root } = await fixture() + const { root: other } = await fixture() + const linkedParent = await realpath(await mkdtemp(join(tmpdir(), 'orca-ref-scope-'))) + roots.push(linkedParent) + const linked = join(linkedParent, 'checkout') + await git(root, 'worktree', 'add', '-qb', 'linked-scope', linked) + expect((await listLocalBranches(root)).worktreePaths?.['linked-scope']).toBe(linked) + await searchBaseRefDetails(other, '', 20) + const a = await resolveBranchSnapshotIdentity(root, {}) + const b = await resolveBranchSnapshotIdentity(other, {}) + const events: string[] = [] + const offA = subscribeGitRefChanges(a!.commonDir, () => events.push('a')) + const offB = subscribeGitRefChanges(b!.commonDir, () => events.push('b')) + try { + await git(linked, 'branch', 'linked-one') + expect(events.splice(0)).toEqual(['a', 'b', 'a', 'b']) + await git(linked, 'branch', 'linked-two') + expect(events.splice(0)).toEqual(['a', 'b', 'a', 'b']) + await git(other, 'branch', 'other-one') + expect(events.splice(0)).toEqual(['a', 'b', 'a', 'b']) + const unknown = await mkdtemp(join(tmpdir(), 'orca-ref-unknown-')) + roots.push(unknown) + await expect(git(unknown, 'branch', 'fails')).rejects.toThrow() + expect(events).toEqual(['a', 'b', 'a', 'b']) + } finally { + offA() + offB() + } +}) + +it('uses each linked checkout effective remote config against the shared raw population', async () => { + const { root, tagOid } = await fixture() + const linkedParent = await mkdtemp(join(tmpdir(), 'orca-ref-config-')) + roots.push(linkedParent) + const linked = join(linkedParent, 'checkout') + await git(root, 'worktree', 'add', '-qb', 'config-context', linked) + await git(root, 'config', 'extensions.worktreeConfig', 'true') + await git( + linked, + 'config', + '--worktree', + 'remote.checkout/fork.url', + 'https://example.invalid/context.git' + ) + await git(root, 'update-ref', 'refs/remotes/checkout/fork/HEAD', tagOid) + expect(await searchBaseRefDetails(root, 'checkout/fork/HEAD', 20)).toEqual([ + { refName: 'refs/remotes/checkout/fork/HEAD', localBranchName: 'fork/HEAD' } + ]) + expect(await searchBaseRefDetails(linked, 'checkout/fork/HEAD', 20)).toEqual([]) +}) + +it('rebinds a repository replaced at the same common-directory path', async () => { + const { root } = await fixture() + expect(await searchBaseRefDetails(root, 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) + await rename(join(root, '.git'), join(root, '.git-old')) + const externalGit = (...args: string[]) => promisify(execFile)('git', args, { cwd: root }) + await externalGit('init', '-q', '-b', 'main') + await externalGit( + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.test', + 'commit', + '--allow-empty', + '-qm', + 'replacement' + ) + await externalGit('branch', 'replacement') + expect(await searchBaseRefDetails(root, 'collision', 20)).toEqual([]) + expect(await searchBaseRefDetails(root, 'replacement', 20)).toEqual([ + { refName: 'refs/heads/replacement', localBranchName: 'replacement' } + ]) +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-routing.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-routing.test.ts new file mode 100644 index 00000000000..f4947725675 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-routing.test.ts @@ -0,0 +1,105 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type * as FsPromises from 'node:fs/promises' +import type * as SnapshotReader from './branch-ref-snapshot-read' +import type * as DistroCatalog from '../../../wsl/discovery/distro-catalog' + +const cwd = String.raw`C:\repo-linked` +const commonDir = String.raw`C:\repo-main\.git` +const gitDir = String.raw`C:\repo-main\.git\worktrees\linked` +const io = vi.hoisted(() => ({ remote: vi.fn(), refs: vi.fn() })) +vi.mock('../../../wsl/discovery/distro-catalog', async (original) => ({ + ...(await original()), + listRunningWslDistrosAsync: async () => ['Ubuntu'] +})) +vi.mock('node:fs/promises', async (original) => ({ + ...(await original()), + realpath: async (path: string) => path, + stat: async (path: string) => ({ + isFile: () => path.endsWith('.git'), + isDirectory: () => !path.endsWith('.git'), + dev: 1n, + ino: 2n, + birthtimeNs: 3n + }), + readFile: async () => String.raw`gitdir: C:\repo-main\.git\worktrees\linked` +})) +vi.mock('../../../../shared/git/metadata/git-common-directory', () => ({ + resolveGitCommonDirectory: async () => String.raw`C:\repo-main\.git` +})) +vi.mock('../../source-control/resolve-git-dir', () => ({ + resolveGitDir: async () => String.raw`C:\repo-main\.git\worktrees\linked` +})) +vi.mock('./branch-ref-snapshot-read', async (original) => ({ + ...(await original()), + readBranchRemoteNames: io.remote, + readBranchRefSnapshot: io.refs +})) +import { searchBranchRefSnapshot, _resetBranchRefSnapshotsForTests } from './branch-ref-snapshot' +import { + prepareWslLinkedWorktreeGitRouting, + resetWslLinkedWorktreeGitRoutingForTests +} from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' +import { resolveBranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import { trackGitRefMutation } from '../../command-runner/git-ref-mutation-state' +import { subscribeGitRefChanges } from '../git-ref-change-signal' +import { _resetWslBackgroundDistroGateForTests } from '../../../wsl/discovery/wsl-background-distro-gate' + +const platform = process.platform +afterEach(() => { + _resetBranchRefSnapshotsForTests() + resetWslLinkedWorktreeGitRoutingForTests() + _resetWslBackgroundDistroGateForTests() + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + vi.restoreAllMocks() + io.remote.mockReset() + io.refs.mockReset() +}) + +it('keeps a live host snapshot across expiry of the filesystem-only linked-route proof', async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + const clock = vi.spyOn(Date, 'now').mockReturnValue(10_000) + // The reader boundary models execution's existing route settlement; it is not a real WSL benchmark. + io.remote.mockImplementation(async () => { + await prepareWslLinkedWorktreeGitRouting(cwd, 'Ubuntu') + return [] + }) + io.refs.mockResolvedValue({ + snapshot: { + refs: [ + { + refName: 'refs/heads/topic', + label: 'topic', + searchName: 'topic', + oid: 'a'.repeat(40), + committedAt: 0, + symref: '' + } + ] + }, + oversized: false + }) + expect(await searchBranchRefSnapshot(cwd, 'topic', 20, { wslDistro: 'Ubuntu' })).toEqual([ + { refName: 'refs/heads/topic', localBranchName: 'topic' } + ]) + clock.mockReturnValue(40_001) + expect(await resolveBranchSnapshotIdentity(cwd, { wslDistro: 'Ubuntu' })).toMatchObject({ + commonDir, + gitDir + }) + expect(await searchBranchRefSnapshot(cwd, 'topic', 20, { wslDistro: 'Ubuntu' })).toEqual([ + { refName: 'refs/heads/topic', localBranchName: 'topic' } + ]) + expect(io.remote).toHaveBeenCalledTimes(1) + expect(io.refs).toHaveBeenCalledTimes(1) + clock.mockReturnValue(70_002) + const events: string[] = [] + const offOwner = subscribeGitRefChanges(commonDir, () => events.push('owner')) + const offOther = subscribeGitRefChanges(String.raw`C:\other\.git`, () => events.push('other')) + try { + trackGitRefMutation(['commit'])() + expect(events).toEqual(['owner', 'other', 'owner', 'other']) + } finally { + offOwner() + offOther() + } +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-store.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-store.test.ts new file mode 100644 index 00000000000..d0bea0134d6 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-store.test.ts @@ -0,0 +1,321 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { BranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import type { BranchRefSnapshot } from './branch-ref-snapshot-read' +import type { BranchRef } from './branch-ref-snapshot-data' +import type * as SnapshotReader from './branch-ref-snapshot-read' + +const mocks = vi.hoisted(() => ({ + read: vi.fn(), + identity: vi.fn(), + remotes: vi.fn(async (): Promise => []) +})) +vi.mock('./branch-ref-snapshot-read', async (original) => ({ + ...(await original()), + readBranchRefSnapshot: mocks.read, + readBranchRemoteNames: mocks.remotes +})) +vi.mock('./branch-ref-snapshot-identity', () => ({ resolveBranchSnapshotIdentity: mocks.identity })) +import { BranchRefSnapshotStore } from './branch-ref-snapshot-store' +import { searchBaseRefDetails } from '../resolution/repo-base-ref-search' +import { _resetBranchRefSnapshotsForTests } from './branch-ref-snapshot' +import { trackGitRefMutation } from '../../command-runner/git-ref-mutation-state' +import { publishGitRefChange, subscribeGitRefChanges } from '../git-ref-change-signal' + +const identity: BranchSnapshotIdentity = { + key: 'host\0/repo/.git', + commonDir: '/repo/.git', + gitDir: '/repo/.git', + checkoutKey: '/repo/.git', + cwd: '/repo', + git: {} +} +const stores: BranchRefSnapshotStore[] = [] +function store() { + const result = new BranchRefSnapshotStore({ + subscribe: subscribeGitRefChanges + }) + stores.push(result) + mocks.identity.mockResolvedValue(identity) + return result +} +function snapshot(name: string): { snapshot: BranchRefSnapshot; oversized: boolean } { + const ref: BranchRef = { + refName: `refs/heads/${name}`, + label: name, + searchName: name.toLowerCase(), + oid: 'a'.repeat(40), + committedAt: 0, + symref: '' + } + return { snapshot: { refs: [ref] }, oversized: false } +} +function deferred() { + let resolve!: (value: T) => void + let reject!: (reason: unknown) => void + const promise = new Promise((done, fail) => { + resolve = done + reject = fail + }) + return { promise, resolve, reject } +} +afterEach(() => { + for (const value of stores.splice(0)) { + value.reset() + } + _resetBranchRefSnapshotsForTests() + vi.restoreAllMocks() + mocks.read.mockReset() + mocks.identity.mockReset() + mocks.remotes.mockReset().mockResolvedValue([]) +}) + +it('does not publish a capture that finishes after a ref change', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockResolvedValue(snapshot('new')) + const result = value.search(identity, '', 20) + await started.promise + publishGitRefChange(identity.commonDir) + old.resolve(snapshot('old')) + expect(await result).toEqual([{ refName: 'refs/heads/old', localBranchName: 'old' }]) + expect(await value.search(identity, 'OLD', 20)).toEqual([]) +}) + +it('serves a post-fence caller from the next physical read without making the earlier caller retry', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockImplementationOnce(() => { + // Another event during the successor read must not prevent its response from settling. + publishGitRefChange(identity.commonDir) + return Promise.resolve(snapshot('fresh')) + }) + const before = value.search(identity, '', 20) + await started.promise + publishGitRefChange(identity.commonDir) + const after = value.search(identity, '', 20) + old.resolve(snapshot('old')) + expect(await before).toEqual([{ refName: 'refs/heads/old', localBranchName: 'old' }]) + expect(await after).toEqual([{ refName: 'refs/heads/fresh', localBranchName: 'fresh' }]) +}) + +it('starts the new generation after an obsolete physical read fails', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockResolvedValue(snapshot('fresh')) + const before = expect(value.search(identity, '', 20)).rejects.toThrow('obsolete failure') + await started.promise + publishGitRefChange(identity.commonDir) + const after = value.search(identity, '', 20) + await new Promise(setImmediate) + old.reject(new Error('obsolete failure')) + await before + expect(await after).toEqual([{ refName: 'refs/heads/fresh', localBranchName: 'fresh' }]) +}) + +it('settles public searches across repeated ref publications without restarting the request', async () => { + mocks.identity.mockResolvedValue(identity) + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockImplementation(async () => { + publishGitRefChange(identity.commonDir) + return snapshot('successor') + }) + const before = searchBaseRefDetails(identity.cwd, '', 20) + await started.promise + publishGitRefChange(identity.commonDir) + const after = searchBaseRefDetails(identity.cwd, '', 20) + await new Promise(setImmediate) + old.resolve(snapshot('overlapping')) + expect(await before).toEqual([ + { refName: 'refs/heads/overlapping', localBranchName: 'overlapping' } + ]) + expect(await after).toEqual([{ refName: 'refs/heads/successor', localBranchName: 'successor' }]) +}) + +it('returns the initiating local-list output when the capture cannot be retained', async () => { + const value = store() + mocks.read.mockImplementationOnce(async (_cwd, _git, onRef) => { + for (const ref of snapshot('local').snapshot.refs) { + onRef(ref) + } + return { snapshot: null, oversized: true } + }) + expect((await value.localRefs(identity)).map((ref) => ref.refName)).toEqual(['refs/heads/local']) +}) + +it('bounds concurrent capture retention and admits a temporarily pressured repository again', async () => { + const value = store() + const other = { + ...identity, + key: 'host\0/other/.git', + cwd: '/other', + commonDir: '/other/.git', + checkoutKey: '/other/.git' + } + mocks.identity.mockImplementation(async (cwd) => (cwd === '/other' ? other : identity)) + const started = deferred() + const held = deferred() + mocks.read.mockImplementationOnce(async (_cwd, _git, _onRef, _max, lease) => { + expect(lease.reserve(40 * 1024 * 1024)).toBe(true) + started.resolve() + await held.promise + return snapshot('first') + }) + mocks.read.mockImplementationOnce(async (_cwd, _git, onRef, _max, lease) => { + expect(lease.reserve(40 * 1024 * 1024)).toBe(false) + onRef(snapshot('pressured').snapshot.refs[0]) + return { snapshot: null, oversized: false } + }) + const first = value.search(identity, '', 20) + await started.promise + expect(await value.search(other, '', 20)).toEqual([ + { refName: 'refs/heads/pressured', localBranchName: 'pressured' } + ]) + held.resolve() + await first + mocks.read.mockImplementationOnce(async (_cwd, _git, _onRef, _max, lease) => { + expect(lease.reserve(40 * 1024 * 1024)).toBe(true) + return snapshot('retained') + }) + expect(await value.search(other, '', 20)).toEqual([ + { refName: 'refs/heads/retained', localBranchName: 'retained' } + ]) + mocks.read.mockRejectedValue(new Error('a retained repeat must not reread')) + expect(await value.search(other, '', 20)).toEqual([ + { refName: 'refs/heads/retained', localBranchName: 'retained' } + ]) +}) + +it('shares a fill while independently projecting each caller query', async () => { + const value = store() + const started = deferred() + const fill = deferred>() + mocks.read.mockImplementation(() => { + started.resolve() + return fill.promise + }) + const matching = value.search(identity, 'TOPIC', 20) + const absent = value.search(identity, 'unmatched', 20) + await started.promise + fill.resolve(snapshot('topic')) + expect(await matching).toEqual([{ refName: 'refs/heads/topic', localBranchName: 'topic' }]) + expect(await absent).toEqual([]) +}) + +it('retries failed fills without extending the original metadata deadline', async () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(0) + const value = store() + expect(await value.remoteNames(identity)).toEqual([]) + clock.mockReturnValue(60_000) + mocks.read.mockRejectedValueOnce(new Error('temporary read error')) + await expect(value.search(identity, '', 20)).rejects.toThrow('temporary read error') + mocks.read.mockResolvedValue(snapshot('first')) + expect(await value.search(identity, '', 20)).toEqual([ + { refName: 'refs/heads/first', localBranchName: 'first' } + ]) + clock.mockReturnValue(120_001) + mocks.read.mockResolvedValue(snapshot('second')) + expect(await value.search(identity, '', 20)).toEqual([ + { refName: 'refs/heads/second', localBranchName: 'second' } + ]) +}) + +it('refreshes remote metadata and recovers retention after repeated oversized captures', async () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(0) + const value = store() + mocks.remotes.mockResolvedValue(['origin']) + const ref: BranchRef = { + refName: 'refs/remotes/team/fork/topic', + label: 'team/fork/topic', + searchName: 'team/fork/topic', + oid: 'a'.repeat(40), + committedAt: 0, + symref: '' + } + let oversized = true + mocks.read.mockImplementation( + async (...args: Parameters) => { + const [, , onRef, maxBytes = 0] = args + onRef(ref) + return { snapshot: !oversized && maxBytes > 0 ? { refs: [ref] } : null, oversized } + } + ) + expect(await value.search(identity, 'topic', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'fork/topic' } + ]) + mocks.remotes.mockResolvedValue(['origin', 'team/fork']) + for (const now of [60_000, 119_000]) { + clock.mockReturnValue(now) + expect(await value.search(identity, 'topic', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'fork/topic' } + ]) + } + clock.mockReturnValue(120_001) + oversized = false + expect(await value.search(identity, 'topic', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'topic' } + ]) + expect(await value.remoteNames(identity)).toEqual(['origin', 'team/fork']) + mocks.read.mockRejectedValue(new Error('retained queries must survive an unavailable reader')) + expect(await value.search(identity, 'TOPIC', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'topic' } + ]) +}) + +it('does not resurrect a retired fill after a store reset', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockResolvedValue(snapshot('fresh')) + const result = value.search(identity, '', 20) + await started.promise + value.reset() + old.resolve(snapshot('retired')) + expect(await result).toEqual([{ refName: 'refs/heads/retired', localBranchName: 'retired' }]) + expect(await value.search(identity, '', 20)).toEqual([ + { refName: 'refs/heads/fresh', localBranchName: 'fresh' } + ]) +}) + +it('keeps demanded captures warm during a mutation and invalidates late owners only on termination', async () => { + const other = { ...identity, key: 'host\0/late/.git', commonDir: '/late/.git', cwd: '/late' } + mocks.identity.mockImplementation(async (cwd: string) => (cwd === '/late' ? other : identity)) + mocks.read.mockResolvedValue(snapshot('topic')) + await searchBaseRefDetails(identity.cwd, 'topic', 20) + expect(mocks.read).toHaveBeenCalledTimes(1) + const end = trackGitRefMutation(['commit']) + expect(mocks.read).toHaveBeenCalledTimes(1) + await searchBaseRefDetails(identity.cwd, 'TOPIC', 20) + await searchBaseRefDetails(identity.cwd, 'absent', 20) + await searchBaseRefDetails(other.cwd, 'topic', 20) + await searchBaseRefDetails(other.cwd, 'absent', 20) + expect(mocks.read).toHaveBeenCalledTimes(3) + end() + expect(mocks.read).toHaveBeenCalledTimes(3) + await searchBaseRefDetails(identity.cwd, 'topic', 20) + await searchBaseRefDetails(other.cwd, 'topic', 20) + expect(mocks.read).toHaveBeenCalledTimes(5) +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-store.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-store.ts new file mode 100644 index 00000000000..09e30addd0e --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-store.ts @@ -0,0 +1,174 @@ +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import type { BranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import { + BranchSnapshotOwners, + BranchSnapshotIdentityChanged, + type Owner, + type Capture, + type BranchSnapshotSignals +} from './branch-ref-snapshot-owners' +import { BranchSnapshotMetadata } from './branch-ref-snapshot-metadata' +import { + createBranchRefProjection, + projectBranchRefs, + type BranchRef +} from './branch-ref-snapshot-data' +import { + BRANCH_SNAPSHOT_MAX_BYTES, + readBranchRefSnapshot, + readBranchRemoteNames +} from './branch-ref-snapshot-read' +export { BranchSnapshotIdentityChanged } from './branch-ref-snapshot-owners' + +/** One physical capture per owner; each caller projects its own page or local list. */ +export class BranchRefSnapshotStore { + private readonly cache: BranchSnapshotOwners + private readonly metadata: BranchSnapshotMetadata + constructor(signals: BranchSnapshotSignals) { + this.cache = new BranchSnapshotOwners(signals) + this.metadata = new BranchSnapshotMetadata(this.cache) + } + + private async capture( + owner: Owner | null, + identity: BranchSnapshotIdentity, + request: string, + onRef: (ref: BranchRef) => boolean | void, + page: BaseRefSearchResult[], + locals: BranchRef[] | null + ): Promise { + const admitted = owner?.generation + // A post-fence caller waits for the physical old read, but never consumes that generation. + if (owner?.flight && owner.flight.generation !== admitted) { + await owner.flight.promise.catch((error: unknown) => { + if (error instanceof BranchSnapshotIdentityChanged) { + throw error + } + }) + } + if (owner?.snapshot) { + return { snapshot: owner.snapshot, request, page, locals } + } + if (owner?.flight) { + return owner.flight.promise + } + const generation = owner?.generation + const lease = owner ? this.cache.lease(owner, () => owner.generation === generation) : undefined + const promise = readBranchRefSnapshot( + identity.cwd, + identity.git, + onRef, + !owner || owner.oversized ? 0 : BRANCH_SNAPSHOT_MAX_BYTES, + lease + ) + .then(async (result): Promise => { + await this.cache.validate(identity, owner ?? undefined) + if (owner && !owner.disposed && owner.generation === generation) { + owner.snapshot = result.snapshot + owner.oversized ||= result.oversized + if (result.snapshot) { + owner.snapshotLease = lease + } else { + lease?.release() + } + } else { + lease?.release() + } + return { snapshot: result.snapshot, request, page, locals } + }) + .catch((error: unknown) => { + lease?.release() + throw error + }) + .finally(() => { + if (owner?.flight?.promise === promise) { + owner.flight = undefined + } + }) + if (owner) { + owner.flight = { generation: generation!, promise } + } + return promise + } + + async localRefs(identity: BranchSnapshotIdentity): Promise { + const owner = this.cache.owner(identity) + const locals: BranchRef[] = [] + const collect = (ref: BranchRef): void => { + if (ref.refName.startsWith('refs/heads/')) { + locals.push(ref) + } + } + const capture = await this.capture(owner, identity, 'locals', collect, [], locals) + if (capture.snapshot && owner?.snapshot === capture.snapshot && owner.localRefs) { + return owner.localRefs + } + let refs = capture.snapshot + ? sortLocalRefs(capture.snapshot.refs) + : capture.locals + ? sortLocalRefs(capture.locals) + : null + if (!refs) { + // A different page initiated an unretainable capture; local output still requires the full population. + await readBranchRefSnapshot(identity.cwd, identity.git, collect, 0) + await this.cache.validate(identity) + refs = sortLocalRefs(locals) + } + if (owner && capture.snapshot && owner.snapshot === capture.snapshot) { + const lease = this.cache.lease(owner) + if (lease.reserve(64 + refs.length * 8)) { + owner.localRefs = refs + owner.localLease = lease + } + } + return refs + } + + async search( + identity: BranchSnapshotIdentity, + query: string, + limit: number, + remoteOnly = false + ): Promise { + const owner = this.cache.owner(identity) + const context = owner ? this.metadata.context(owner, identity) : undefined + const remotes = await (context?.remotes ?? readBranchRemoteNames(identity.cwd, identity.git)) + const request = JSON.stringify([identity.checkoutKey, query, limit, remoteOnly]) + const page: BaseRefSearchResult[] = [] + const project = createBranchRefProjection(remotes, query, remoteOnly) + const collect = (ref: BranchRef): boolean => { + if (page.length < limit) { + const row = project(ref) + if (row) { + page.push(row) + } + } + return page.length >= limit + } + const capture = await this.capture(owner, identity, request, collect, page, null) + if (capture.snapshot) { + return projectBranchRefs(capture.snapshot.refs, remotes, query, limit, remoteOnly) + } + if (capture.request === request) { + return capture.page + } + await readBranchRefSnapshot(identity.cwd, identity.git, collect, 0) + await this.cache.validate(identity, owner ?? undefined) + return page + } + + remoteNames(identity: BranchSnapshotIdentity) { + return this.metadata.remoteNames(identity) + } + reset(): void { + this.cache.reset() + } +} + +function sortLocalRefs(refs: readonly BranchRef[]): BranchRef[] { + const local = refs + .filter((ref) => ref.refName.startsWith('refs/heads/')) + .map((ref) => ({ ref, key: Buffer.from(ref.refName) })) + local.sort((left, right) => Buffer.compare(left.key, right.key)) + return local.map(({ ref }) => ref) +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot.ts b/src/main/git/refs/snapshot/branch-ref-snapshot.ts new file mode 100644 index 00000000000..71317810d8e --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot.ts @@ -0,0 +1,80 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import type { LocalGitExecOptions } from '../resolution/repo-default-base-ref' +import { + resolveBranchSnapshotIdentity, + type BranchSnapshotIdentity +} from './branch-ref-snapshot-identity' +import { BranchRefSnapshotStore, BranchSnapshotIdentityChanged } from './branch-ref-snapshot-store' +import { subscribeGitRefChanges } from '../git-ref-change-signal' +import { readTranslatedWorktreeGraph } from '../../worktrees/catalog/worktree-list-reader' + +const snapshots = new BranchRefSnapshotStore({ subscribe: subscribeGitRefChanges }) + +async function withIdentity( + path: string, + git: LocalGitExecOptions, + read: (identity: BranchSnapshotIdentity) => Promise +): Promise { + for (let attempt = 0; attempt < 2; attempt++) { + const identity = await resolveBranchSnapshotIdentity(path, git) + if (!identity) { + throw new Error('The project is not a Git repository') + } + try { + return await read(identity) + } catch (error) { + if (!(error instanceof BranchSnapshotIdentityChanged)) { + throw error + } + } + } + throw new Error('The Git repository changed while reading branches. Try again.') +} + +export function searchBranchRefSnapshot( + path: string, + query: string, + limit: number, + git: LocalGitExecOptions = {}, + remoteOnly = false +): Promise { + return withIdentity(path, git, (identity) => snapshots.search(identity, query, limit, remoteOnly)) +} + +export function snapshotRemoteNames( + path: string, + git: LocalGitExecOptions = {} +): Promise { + return withIdentity(path, git, (identity) => snapshots.remoteNames(identity)) +} + +export function snapshotLocalBranchMetadata(path: string, git: LocalGitExecOptions = {}) { + return withIdentity(path, git, async (identity) => { + const [refs, worktrees, head] = await Promise.all([ + snapshots.localRefs(identity), + readTranslatedWorktreeGraph(identity.cwd, identity.git), + readFile(join(identity.gitDir, 'HEAD'), 'utf8').catch(() => '') + ]) + const currentRef = /^ref: (refs\/heads\/[^\r\n]+)/.exec(head)?.[1] + const current = + currentRef && + worktrees.some( + (worktree) => worktree.branch === currentRef && /[1-9a-f]/i.test(worktree.head) + ) + ? currentRef.slice('refs/heads/'.length) + : null + const worktreePaths = new Map() + for (const worktree of worktrees) { + if (worktree.branch.startsWith('refs/heads/')) { + worktreePaths.set(worktree.branch.slice('refs/heads/'.length), worktree.path) + } + } + return { refs, worktreePaths, current } + }) +} + +export function _resetBranchRefSnapshotsForTests(): void { + snapshots.reset() +} diff --git a/src/main/git/remotes/remote-name-listing.test.ts b/src/main/git/remotes/remote-name-listing.test.ts index f66100cf5f6..4e5561dd971 100644 --- a/src/main/git/remotes/remote-name-listing.test.ts +++ b/src/main/git/remotes/remote-name-listing.test.ts @@ -9,16 +9,12 @@ vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../../github/local-git-config-signature', () => ({ +vi.mock('../../github/repositories/local-git-config-signature', () => ({ readLocalGitConfigSignature: readLocalGitConfigSignatureMock })) import { REMOTE_URL_PROBE_TIMEOUT_MS } from './remote-url-probe' -import { - _resetRemoteNameListingCache, - listCachedRemoteNames, - shouldProbeGitRemote -} from './remote-name-listing' +import { _resetRemoteNameListingCache, shouldProbeGitRemote } from './remote-name-listing' function remoteListCalls(): unknown[][] { return gitExecFileAsyncMock.mock.calls.filter( @@ -92,22 +88,6 @@ describe('cached git remote name listing', () => { expect(remoteListCalls()).toHaveLength(2) }) - it('coalesces concurrent listings onto one spawn', async () => { - gitExecFileAsyncMock.mockImplementation(async () => { - await Promise.resolve() - return { stdout: 'origin\n' } - }) - - await expect( - Promise.all([ - shouldProbeGitRemote('/repo', 'upstream'), - shouldProbeGitRemote('/repo', 'upstream'), - listCachedRemoteNames('/repo') - ]) - ).resolves.toEqual([false, false, ['origin']]) - expect(remoteListCalls()).toHaveLength(1) - }) - it('keeps host and WSL listings separate', async () => { gitExecFileAsyncMock.mockImplementation( async (_args: string[], options: { wslDistro?: string } = {}) => ({ diff --git a/src/main/git/remotes/remote-name-listing.ts b/src/main/git/remotes/remote-name-listing.ts index 03f2d723817..66d92e410a2 100644 --- a/src/main/git/remotes/remote-name-listing.ts +++ b/src/main/git/remotes/remote-name-listing.ts @@ -1,6 +1,6 @@ -import { readLocalGitConfigSignature } from '../../github/local-git-config-signature' +import { readLocalGitConfigSignature } from '../../github/repositories/local-git-config-signature' import { runCoalescedProbe, type CoalescedProbes } from './coalesced-probe' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { REMOTE_URL_PROBE_TIMEOUT_MS } from './remote-url-probe' import { gitExecFileAsync } from '../command-runner/git-exec-file' diff --git a/src/main/git/remotes/remote-ref-probe-cache.ts b/src/main/git/remotes/remote-ref-probe-cache.ts index 053f9658aec..b1cac7750d4 100644 --- a/src/main/git/remotes/remote-ref-probe-cache.ts +++ b/src/main/git/remotes/remote-ref-probe-cache.ts @@ -1,6 +1,6 @@ import { runCoalescedProbe, type CoalescedProbes } from './coalesced-probe' import { isTransientGitProbeError, readRemoteUrl } from './remote-url-probe' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' const REPO_REF_CACHE_MAX_ENTRIES = 512 diff --git a/src/main/git/remotes/remote-url-probe.ts b/src/main/git/remotes/remote-url-probe.ts index 8b0bb79c065..77b69665b5b 100644 --- a/src/main/git/remotes/remote-url-probe.ts +++ b/src/main/git/remotes/remote-url-probe.ts @@ -1,7 +1,7 @@ import { AsyncLocalStorage } from 'node:async_hooks' import { gitExecFileAsync } from '../command-runner/git-exec-file' import { isStableMissingGitRemoteError } from './stable-missing-git-remote-error' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { requireReachableGitRoute } from '../../providers/execution-host-provider-dispatch' import { getConnectionExecutionHostId } from '../../../shared/execution-host' diff --git a/src/main/git/remotes/repo-remote-queries.ts b/src/main/git/remotes/repo-remote-queries.ts index 4de9c4e5cef..fd66a1f14e8 100644 --- a/src/main/git/remotes/repo-remote-queries.ts +++ b/src/main/git/remotes/repo-remote-queries.ts @@ -1,3 +1,4 @@ +import { snapshotRemoteNames } from '../refs/snapshot/branch-ref-snapshot' import { parseGitRevListAheadBehindCounts } from '../../../shared/git/refs/git-rev-list-output' import { buildHostedRemoteCommitUrl, buildHostedRemoteFileUrl } from './hosted-remote-url' import { getRemoteFileTarget } from './repo-remote-file-target' @@ -72,18 +73,13 @@ export async function getRecentDriftSubjects( } } -function parseRemoteCount(stdout: string): number { - return stdout.split('\n').filter((line) => line.trim().length > 0).length -} - /** Count configured remotes; zero means either none or unavailable. */ export async function getRemoteCount( path: string, options: LocalGitExecOptions = {} ): Promise { try { - const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) - return parseRemoteCount(stdout) + return (await snapshotRemoteNames(path, options)).length } catch (err) { console.warn('[getRemoteCount] git remote failed', { path, err }) return 0 @@ -118,11 +114,7 @@ export async function getDefaultRemote( try { let remotes = knownRemoteNames if (remotes === undefined) { - const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) - remotes = stdout - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) + remotes = await snapshotRemoteNames(path, options) } if (remotes.includes('origin')) { return 'origin' diff --git a/src/main/git/remotes/task-repository-eligibility.ts b/src/main/git/remotes/task-repository-eligibility.ts index 5141c38343d..8da4e10707a 100644 --- a/src/main/git/remotes/task-repository-eligibility.ts +++ b/src/main/git/remotes/task-repository-eligibility.ts @@ -1,7 +1,7 @@ import { parseGitRemoteVerboseOutput } from '../../../shared/git/remotes/git-remote-identity' -import { isDefaultGitHubHost } from '../../../shared/github/repository-identity-key' -import { isGitHubHostAuthenticated } from '../../github/github-enterprise-repository' -import { parseGitHubRemoteIdentity } from '../../github/github-remote-identity-parsing' +import { isDefaultGitHubHost } from '../../../shared/github/repositories/repository-identity-key' +import { isGitHubHostAuthenticated } from '../../github/repositories/github-enterprise-repository' +import { parseGitHubRemoteIdentity } from '../../github/repositories/github-remote-identity-parsing' import { getGlabKnownHosts, getGlabPartialHosts diff --git a/src/main/git/remotes/worktree-push-target-cleanup.ts b/src/main/git/remotes/worktree-push-target-cleanup.ts index 036479d8d51..0bc4c94d404 100644 --- a/src/main/git/remotes/worktree-push-target-cleanup.ts +++ b/src/main/git/remotes/worktree-push-target-cleanup.ts @@ -3,7 +3,7 @@ import type { Store } from '../../persistence/loading-store/store' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import type { GitPushTarget } from '../../../shared/worktree/types' -import { parseGitHubOwnerRepo } from '../../github/github-remote-identity-parsing' +import { parseGitHubOwnerRepo } from '../../github/repositories/github-remote-identity-parsing' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import { iterateProcessOutputLines } from '../../../shared/process-output-field-scanner' diff --git a/src/main/git/repositories/canonical-repo-key.test.ts b/src/main/git/repositories/canonical-repo-key.test.ts deleted file mode 100644 index 731f25de71a..00000000000 --- a/src/main/git/repositories/canonical-repo-key.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const gitExecFileAsyncMock = vi.hoisted(() => vi.fn()) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ - ...((await importOriginal()) as Record), - gitExecFileAsync: gitExecFileAsyncMock -})) - -import { _resetCanonicalRepoKeyCacheForTests, readGitCommonDir } from './canonical-repo-key' - -beforeEach(() => { - _resetCanonicalRepoKeyCacheForTests() - gitExecFileAsyncMock.mockReset() -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('readGitCommonDir', () => { - it('drops the flag Git older than 2.31 echoes back, and resolves the relative answer', () => { - expect(readGitCommonDir('--path-format=absolute\n.git\n', '/repo')).toBe('/repo/.git') - }) - - it('resolves a WSL answer in Git execution space, not against the UNC path', () => { - expect(readGitCommonDir('.git\n', '//wsl$/Ubuntu/home/dev/repo')).toBe('/home/dev/repo/.git') - }) -}) diff --git a/src/main/git/repositories/canonical-repo-key.ts b/src/main/git/repositories/canonical-repo-key.ts index 49ce4f19dbf..0cfb67db695 100644 --- a/src/main/git/repositories/canonical-repo-key.ts +++ b/src/main/git/repositories/canonical-repo-key.ts @@ -1,6 +1,6 @@ import type { LocalGitExecOptions } from '../refs/resolution/repo-default-base-ref' import type { GitExecOptions } from '../command-runner/git-exec-options' -import { toWslExecutionSpace } from '../../../shared/wsl-paths' +import { parseWslUncPath, toWslExecutionSpace } from '../../../shared/wsl-paths' import { gitExecFileAsync } from '../command-runner/git-exec-file' import { resolveRevParsePath } from '../worktrees/catalog/worktree-path-comparison' @@ -10,7 +10,8 @@ export type CanonicalRepoKeyOptions = LocalGitExecOptions & Pick const CACHE_MAX = 512 -const cache = new Map() +type CachedRepoKey = { key: string; commonDir?: string } +const cache = new Map() /** Git < 2.31 echoes unsupported --path-format=absolute; resolve its relative answer to prevent key collisions. */ export function readGitCommonDir(stdout: string, repoPath: string): string | undefined { @@ -21,7 +22,7 @@ export function readGitCommonDir(stdout: string, repoPath: string): string | und return commonDir ? resolveRevParsePath(toWslExecutionSpace(repoPath), commonDir) : undefined } -function remember(cacheKey: string, value: string): string { +function remember(cacheKey: string, value: CachedRepoKey): string { cache.delete(cacheKey) cache.set(cacheKey, value) while (cache.size > CACHE_MAX) { @@ -31,7 +32,16 @@ function remember(cacheKey: string, value: string): string { } cache.delete(oldest.value) } - return value + return value.key +} + +/** A missing answer or caller-path fallback is not a verified shared repository identity. */ +export function peekGitCommonDir( + repoPath: string, + options: Pick = {} +): string | undefined { + const runtimeKey = options.wslDistro ? `wsl:${options.wslDistro}` : 'local' + return cache.get(`${runtimeKey}::${repoPath}`)?.commonDir } /** `${runtimeKey}::${gitCommonDir}`, falling back to the caller's path. */ @@ -52,7 +62,11 @@ export async function getCanonicalRepoKey( ) const commonDir = readGitCommonDir(stdout, repoPath) if (commonDir) { - return remember(cacheKey, `${runtimeKey}::${commonDir}`) + return remember(cacheKey, { + key: `${runtimeKey}::${commonDir}`, + // Drive-path routing may change Git hosts; only unambiguous namespaces prove provenance. + ...(process.platform !== 'win32' || parseWslUncPath(repoPath) ? { commonDir } : {}) + }) } } catch (error) { // Cancellation is unavailable identity, not a caller-path identity to cache. @@ -61,7 +75,7 @@ export async function getCanonicalRepoKey( } // The caller path remains a safe serialization key when canonicalization fails. } - return remember(cacheKey, cacheKey) + return remember(cacheKey, { key: cacheKey }) } export function _resetCanonicalRepoKeyCacheForTests(): void { diff --git a/src/main/git/repository-git-cause.ts b/src/main/git/repository-git-cause.ts new file mode 100644 index 00000000000..f21632ce380 --- /dev/null +++ b/src/main/git/repository-git-cause.ts @@ -0,0 +1,20 @@ +import { parseWslUncPath } from '../../shared/wsl-paths' +import { hasActiveTraceSink } from '../observability/tracer' +import { runWithGitCause, type GitOperationCause } from '../observability/git-operation-cause' +import { peekGitCommonDir } from './repositories/canonical-repo-key' + +/** Diagnostics only reuse identity already resolved by a repository owner. */ +export function withRepositoryGitCause( + repoPath: string, + options: { wslDistro?: string }, + cause: GitOperationCause, + run: () => Promise +): Promise { + if (!hasActiveTraceSink()) { + return run() + } + const commonDir = peekGitCommonDir(repoPath, options) + const distro = process.platform === 'win32' ? parseWslUncPath(repoPath)?.distro : undefined + const namespace = process.platform !== 'win32' ? 'local' : distro ? `wsl:${distro}` : undefined + return runWithGitCause(cause, commonDir && namespace ? { namespace, commonDir } : undefined, run) +} diff --git a/src/main/git/source-control/branch-change-entries.ts b/src/main/git/source-control/branch-change-entries.ts deleted file mode 100644 index dd3061a02f3..00000000000 --- a/src/main/git/source-control/branch-change-entries.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { GitBranchChangeEntry } from '../../../shared/git/diff/git-diff-compare-types' -import { gitChangeListArgs, parseGitChangeList } from '../../../shared/git/diff/git-change-list' - -import { - type GitRuntimeOptions, - gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' - -export async function loadBranchChanges( - worktreePath: string, - baseOid: string, - headOid: string, - options: GitRuntimeOptions = {} -): Promise { - return loadCommitChanges(worktreePath, baseOid, headOid, options) -} - -export async function loadCommitChanges( - worktreePath: string, - parentOid: string | null, - commitOid: string, - options: GitRuntimeOptions = {} -): Promise { - const { stdout } = await gitExecFileAsync(gitChangeListArgs(parentOid, commitOid), { - ...gitOptionsForWorktree(worktreePath, options), - maxBuffer: MAX_GIT_SHOW_BYTES - }) - return parseGitChangeList(stdout) -} diff --git a/src/main/git/source-control/comparisons/branch-change-entries.ts b/src/main/git/source-control/comparisons/branch-change-entries.ts new file mode 100644 index 00000000000..4bc55d51912 --- /dev/null +++ b/src/main/git/source-control/comparisons/branch-change-entries.ts @@ -0,0 +1,31 @@ +import type { GitBranchChangeEntry } from '../../../../shared/git/diff/git-diff-compare-types' +import { gitChangeListArgs, parseGitChangeList } from '../../../../shared/git/diff/git-change-list' + +import { + type GitRuntimeOptions, + gitOptionsForWorktree +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { MAX_GIT_SHOW_BYTES } from '../git-show-max-bytes' + +export async function loadBranchChanges( + worktreePath: string, + baseOid: string, + headOid: string, + options: GitRuntimeOptions = {} +): Promise { + return loadCommitChanges(worktreePath, baseOid, headOid, options) +} + +export async function loadCommitChanges( + worktreePath: string, + parentOid: string | null, + commitOid: string, + options: GitRuntimeOptions = {} +): Promise { + const { stdout } = await gitExecFileAsync(gitChangeListArgs(parentOid, commitOid), { + ...gitOptionsForWorktree(worktreePath, options), + maxBuffer: MAX_GIT_SHOW_BYTES + }) + return parseGitChangeList(stdout) +} diff --git a/src/main/git/source-control/branch-change-list-cache-real-git.test.ts b/src/main/git/source-control/comparisons/branch-change-list-cache-real-git.test.ts similarity index 91% rename from src/main/git/source-control/branch-change-list-cache-real-git.test.ts rename to src/main/git/source-control/comparisons/branch-change-list-cache-real-git.test.ts index 06a8bdda317..29c40d1ce5f 100644 --- a/src/main/git/source-control/branch-change-list-cache-real-git.test.ts +++ b/src/main/git/source-control/comparisons/branch-change-list-cache-real-git.test.ts @@ -4,7 +4,6 @@ import { tmpdir } from 'node:os' import * as path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { getBranchCompare } from './branch-compare' -import { settledBranchChangeListCache } from './branch-change-list-cache' // Old mtimes put every input past the racy-write margin, so only stamp contents decide reuse. const aged = new Date('2020-01-01T00:00:00Z') @@ -67,9 +66,6 @@ describe('branch compare changed-files reuse', () => { const counted = [{ path: 'docs/notes.txt', status: 'modified', added: 1, removed: 0 }] const binary = [{ path: 'docs/notes.txt', status: 'modified' }] expect((await getBranchCompare(repo, 'base')).entries).toEqual(counted) - const hitsBefore = settledBranchChangeListCache.stats().hits - expect((await getBranchCompare(repo, 'base')).entries).toEqual(counted) - expect(settledBranchChangeListCache.stats().hits).toBe(hitsBefore + 1) await writeFile(nestedAttributes, '*.txt -diff\n') await age(nestedAttributes) diff --git a/src/main/git/source-control/branch-change-list-cache.ts b/src/main/git/source-control/comparisons/branch-change-list-cache.ts similarity index 87% rename from src/main/git/source-control/branch-change-list-cache.ts rename to src/main/git/source-control/comparisons/branch-change-list-cache.ts index c0bd508277c..0b53be1bc81 100644 --- a/src/main/git/source-control/branch-change-list-cache.ts +++ b/src/main/git/source-control/comparisons/branch-change-list-cache.ts @@ -1,13 +1,13 @@ -import type { GitBranchChangeEntry } from '../../../shared/git/diff/git-diff-compare-types' -import { gitChangeListArgs } from '../../../shared/git/diff/git-change-list' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' +import type { GitBranchChangeEntry } from '../../../../shared/git/diff/git-diff-compare-types' +import { gitChangeListArgs } from '../../../../shared/git/diff/git-change-list' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' import { loadBranchChanges } from './branch-change-entries' import type { CommitPairScope } from './commit-pair-cache' -import { readStampWithinDeadline, type StampProbes } from './deadline-bounded-stamp' -import { addGitattributesStampPaths } from './gitattributes-stamp-paths' -import { SettledDiffCache, type SettledDiffCacheLimits } from './settled-diff-cache' -import { readStampedGitConfig } from './stamped-git-config' -import { readWorktreePathsDiffStamp } from './worktree-diff-stamp' +import { readStampWithinDeadline, type StampProbes } from '../input-stamps/deadline-bounded-stamp' +import { addGitattributesStampPaths } from '../input-stamps/gitattributes-stamp-paths' +import { SettledDiffCache, type SettledDiffCacheLimits } from '../settled-diff-cache' +import { readStampedGitConfig } from '../input-stamps/stamped-git-config' +import { readWorktreePathsDiffStamp } from '../input-stamps/worktree-diff-stamp' type CachedBranchChanges = { entries: GitBranchChangeEntry[] diff --git a/src/main/git/source-control/branch-compare.ts b/src/main/git/source-control/comparisons/branch-compare.ts similarity index 91% rename from src/main/git/source-control/branch-compare.ts rename to src/main/git/source-control/comparisons/branch-compare.ts index b4afdc7bff0..d35dcc87dd4 100644 --- a/src/main/git/source-control/branch-compare.ts +++ b/src/main/git/source-control/comparisons/branch-compare.ts @@ -1,11 +1,11 @@ import type { GitBranchCompareResult, GitBranchCompareSummary -} from '../../../shared/git/diff/git-diff-compare-types' -import { readBranchCompareHead } from '../../../shared/git/branches/git-branch-compare-head' -import { resolveWorktreeAddBaseRef } from '../../../shared/worktree/base-ref' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { resolveWorktreeBaseCommitOid } from '../worktrees/creation/worktree-base-ref-probe' +} from '../../../../shared/git/diff/git-diff-compare-types' +import { readBranchCompareHead } from '../../../../shared/git/branches/git-branch-compare-head' +import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-refs/base-ref' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { resolveWorktreeBaseCommitOid } from '../../worktrees/creation/worktree-base-ref-probe' import { loadBranchChangesThroughCache } from './branch-change-list-cache' import { commitPairDivergences, diff --git a/src/main/git/source-control/branch-diff.ts b/src/main/git/source-control/comparisons/branch-diff.ts similarity index 76% rename from src/main/git/source-control/branch-diff.ts rename to src/main/git/source-control/comparisons/branch-diff.ts index fc83e142efa..087e893d97d 100644 --- a/src/main/git/source-control/branch-diff.ts +++ b/src/main/git/source-control/comparisons/branch-diff.ts @@ -1,10 +1,10 @@ -import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import { stableInFlightKey } from '../../../shared/in-flight-promise-dedupe' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { gitRuntimeOptionsKey } from './git-runtime-options-cache-key' -import { gitDiffReadDedupe } from './git-read-cache-invalidation' -import { buildDiffResult } from './diff-result' -import { blobConversion, readGitBlobAtOidPath } from './git-blob-read' +import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' +import { stableInFlightKey } from '../../../../shared/in-flight-promise-dedupe' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { gitRuntimeOptionsKey } from '../git-runtime-options-cache-key' +import { gitDiffReadDedupe } from '../git-read-cache-invalidation' +import { buildDiffResult } from '../diffs/diff-result' +import { blobConversion, readGitBlobAtOidPath } from '../diffs/git-blob-read' export async function getBranchDiff( worktreePath: string, diff --git a/src/main/git/source-control/commit-compare.ts b/src/main/git/source-control/comparisons/commit-compare.ts similarity index 84% rename from src/main/git/source-control/commit-compare.ts rename to src/main/git/source-control/comparisons/commit-compare.ts index ad2e3615183..c4af6dce1e6 100644 --- a/src/main/git/source-control/commit-compare.ts +++ b/src/main/git/source-control/comparisons/commit-compare.ts @@ -1,11 +1,11 @@ -import type { GitCommitCompareResult } from '../../../shared/git/diff/git-diff-compare-types' -import { parseGitRevListFirstParentOid } from '../../../shared/git/refs/git-rev-list-output' +import type { GitCommitCompareResult } from '../../../../shared/git/diff/git-diff-compare-types' +import { parseGitRevListFirstParentOid } from '../../../../shared/git/refs/git-rev-list-output' import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { loadCommitChanges } from './branch-change-entries' import { resolveRefOid } from './compare-ref-oids' diff --git a/src/main/git/source-control/commit-diff.ts b/src/main/git/source-control/comparisons/commit-diff.ts similarity index 77% rename from src/main/git/source-control/commit-diff.ts rename to src/main/git/source-control/comparisons/commit-diff.ts index 6ffbf8ec524..bb113202b0d 100644 --- a/src/main/git/source-control/commit-diff.ts +++ b/src/main/git/source-control/comparisons/commit-diff.ts @@ -1,10 +1,14 @@ -import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import { stableInFlightKey } from '../../../shared/in-flight-promise-dedupe' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { gitRuntimeOptionsKey } from './git-runtime-options-cache-key' -import { gitDiffReadDedupe } from './git-read-cache-invalidation' -import { buildDiffResult } from './diff-result' -import { blobConversion, readGitBlobAtOidPath, type GitBlobReadResult } from './git-blob-read' +import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' +import { stableInFlightKey } from '../../../../shared/in-flight-promise-dedupe' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { gitRuntimeOptionsKey } from '../git-runtime-options-cache-key' +import { gitDiffReadDedupe } from '../git-read-cache-invalidation' +import { buildDiffResult } from '../diffs/diff-result' +import { + blobConversion, + readGitBlobAtOidPath, + type GitBlobReadResult +} from '../diffs/git-blob-read' export async function getCommitDiff( worktreePath: string, diff --git a/src/main/git/source-control/commit-pair-cache.ts b/src/main/git/source-control/comparisons/commit-pair-cache.ts similarity index 93% rename from src/main/git/source-control/commit-pair-cache.ts rename to src/main/git/source-control/comparisons/commit-pair-cache.ts index 60df2fb643f..28099258fd5 100644 --- a/src/main/git/source-control/commit-pair-cache.ts +++ b/src/main/git/source-control/comparisons/commit-pair-cache.ts @@ -1,9 +1,12 @@ import { readFile, stat } from 'node:fs/promises' import * as path from 'node:path' -import { resolveWorktreeHostPath } from '../../../shared/git/metadata/git-metadata-path' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { resolveGitCommonDir, resolveGitDir } from './resolve-git-dir' -import { canProveUnchangedByStamp, readFileStampComponent } from './worktree-diff-stamp' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { resolveGitCommonDir, resolveGitDir } from '../resolve-git-dir' +import { + canProveUnchangedByStamp, + readFileStampComponent +} from '../input-stamps/worktree-diff-stamp' /** Opaque object-store identity under which a commit pair's graph answers stay valid. */ export type CommitPairScope = string diff --git a/src/main/git/source-control/compare-ref-oids.ts b/src/main/git/source-control/comparisons/compare-ref-oids.ts similarity index 93% rename from src/main/git/source-control/compare-ref-oids.ts rename to src/main/git/source-control/comparisons/compare-ref-oids.ts index a21a21df521..4cb30419015 100644 --- a/src/main/git/source-control/compare-ref-oids.ts +++ b/src/main/git/source-control/comparisons/compare-ref-oids.ts @@ -1,8 +1,8 @@ import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' export async function resolveCompareRef( worktreePath: string, diff --git a/src/main/git/source-control/status-branch-compare-real-ref.test.ts b/src/main/git/source-control/comparisons/status-branch-compare-real-ref.test.ts similarity index 83% rename from src/main/git/source-control/status-branch-compare-real-ref.test.ts rename to src/main/git/source-control/comparisons/status-branch-compare-real-ref.test.ts index a5f40187594..60351448a1b 100644 --- a/src/main/git/source-control/status-branch-compare-real-ref.test.ts +++ b/src/main/git/source-control/comparisons/status-branch-compare-real-ref.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from 'node:child_process' -import { mkdtemp, readFile, readdir, realpath, rm, utimes, writeFile } from 'node:fs/promises' +import { mkdtemp, readdir, realpath, rm, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import * as path from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -136,21 +136,6 @@ describe('getBranchCompare real refs', () => { expect(await commitsAhead(repo)).toBe(1) }) - it('recounts after an existing loose replace ref is edited in place', async () => { - const { repo, oids } = await createChainRepo() - git(repo, ['replace', '--graft', oids.tip, oids.a]) - const replaceRef = path.join(repo, '.git', 'refs', 'replace', oids.tip) - const tipOntoA = await readFile(replaceRef, 'utf8') - git(repo, ['replace', '--force', '--graft', oids.tip, oids.root]) - await ageReplaceRefs(repo) - expect(await commitsAhead(repo)).toBe(1) - - await writeFile(replaceRef, tipOntoA) - await utimes(path.dirname(replaceRef), aged, aged) - - expect(await commitsAhead(repo)).toBe(2) - }) - it('recounts after a replace ref is packed away from refs/replace', async () => { const { repo, oids } = await createChainRepo() expect(await commitsAhead(repo)).toBe(3) @@ -163,20 +148,6 @@ describe('getBranchCompare real refs', () => { expect(await commitsAhead(repo)).toBe(1) }) - it('keeps per-worktree core.useReplaceRefs answers apart', async () => { - const { repo, oids } = await createChainRepo() - git(repo, ['replace', '--graft', oids.tip, oids.root]) - const linked = path.join(path.dirname(repo), `${path.basename(repo)}-linked`) - tempRoots.push(linked) - git(repo, ['worktree', 'add', '-q', '--detach', linked, oids.tip]) - git(repo, ['config', 'extensions.worktreeConfig', 'true']) - git(linked, ['config', '--worktree', 'core.useReplaceRefs', 'false']) - await ageReplaceRefs(repo) - - expect(await commitsAhead(repo)).toBe(1) - expect(await commitsAhead(linked)).toBe(3) - }) - it('honors a custom GIT_REPLACE_REF_BASE namespace', async () => { const { repo, oids } = await createChainRepo() const previous = process.env.GIT_REPLACE_REF_BASE @@ -211,9 +182,6 @@ describe('getBranchCompare real refs', () => { execFileSync('git', ['clone', '-q', source, client]) git(client, ['fetch', source, 'refs/tags/annotated:refs/remotes/origin/tagbase']) - expect(git(client, ['branch', '-r', '--format=%(refname:short)']).split(/\r?\n/)).toContain( - 'origin/tagbase' - ) const rawOid = git(client, ['rev-parse', '--verify', 'refs/remotes/origin/tagbase']) const peeledOid = git(client, [ 'rev-parse', diff --git a/src/main/git/source-control/blob-absence-real-git.test.ts b/src/main/git/source-control/diffs/blob-absence-real-git.test.ts similarity index 95% rename from src/main/git/source-control/blob-absence-real-git.test.ts rename to src/main/git/source-control/diffs/blob-absence-real-git.test.ts index 840c9de4fe3..3f42e48c372 100644 --- a/src/main/git/source-control/blob-absence-real-git.test.ts +++ b/src/main/git/source-control/diffs/blob-absence-real-git.test.ts @@ -6,10 +6,10 @@ import * as path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { readGitBlobAtIndexPath, readGitBlobAtOidPath } from './git-blob-read' -import { getCommitDiff } from './commit-diff' +import { getCommitDiff } from '../comparisons/commit-diff' import { getDiff } from './file-diff' -import { invalidateGitReadCaches, settledDiffCache } from './git-read-cache-invalidation' -import { readWorktreeDiffStamp } from './worktree-diff-stamp' +import { invalidateGitReadCaches, settledDiffCache } from '../git-read-cache-invalidation' +import { readWorktreeDiffStamp } from '../input-stamps/worktree-diff-stamp' function gitInit(dir: string): void { execFileSync('git', ['init'], { cwd: dir, stdio: 'pipe' }) diff --git a/src/main/git/source-control/diff-result.ts b/src/main/git/source-control/diffs/diff-result.ts similarity index 87% rename from src/main/git/source-control/diff-result.ts rename to src/main/git/source-control/diffs/diff-result.ts index 99a7a758e8d..c52c3d1b6e7 100644 --- a/src/main/git/source-control/diff-result.ts +++ b/src/main/git/source-control/diffs/diff-result.ts @@ -1,9 +1,9 @@ -import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import { getLargeDiffRenderLimit } from '../../../shared/large-diff-render-limit' +import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' +import { getLargeDiffRenderLimit } from '../../../../shared/large-diff-render-limit' import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES, filePreviewExtension -} from '../../../shared/file-preview/file-preview-kind' +} from '../../../../shared/file-preview/file-preview-kind' export function buildDiffResult( originalContent: string, diff --git a/src/main/git/source-control/diff-textconv-real-git.test.ts b/src/main/git/source-control/diffs/diff-textconv-real-git.test.ts similarity index 98% rename from src/main/git/source-control/diff-textconv-real-git.test.ts rename to src/main/git/source-control/diffs/diff-textconv-real-git.test.ts index 682654ada0d..b2e7b1fdc1d 100644 --- a/src/main/git/source-control/diff-textconv-real-git.test.ts +++ b/src/main/git/source-control/diffs/diff-textconv-real-git.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import * as path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { getDiff } from './file-diff' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' describe('diff drivers with textconv', () => { let repo: string diff --git a/src/main/git/source-control/diff-too-large-real-git.test.ts b/src/main/git/source-control/diffs/diff-too-large-real-git.test.ts similarity index 92% rename from src/main/git/source-control/diff-too-large-real-git.test.ts rename to src/main/git/source-control/diffs/diff-too-large-real-git.test.ts index 1dc261a3bd8..7ec2bce486a 100644 --- a/src/main/git/source-control/diff-too-large-real-git.test.ts +++ b/src/main/git/source-control/diffs/diff-too-large-real-git.test.ts @@ -5,8 +5,8 @@ import { tmpdir } from 'node:os' import * as path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { getDiff } from './file-diff' -import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import { MAX_GIT_SHOW_BYTES } from '../git-show-max-bytes' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' function git(dir: string, args: string[]): void { execFileSync('git', args, { cwd: dir, stdio: 'pipe' }) diff --git a/src/main/git/source-control/file-diff.ts b/src/main/git/source-control/diffs/file-diff.ts similarity index 91% rename from src/main/git/source-control/file-diff.ts rename to src/main/git/source-control/diffs/file-diff.ts index 9cac0c93646..c573b2dea75 100644 --- a/src/main/git/source-control/file-diff.ts +++ b/src/main/git/source-control/diffs/file-diff.ts @@ -1,11 +1,11 @@ import * as path from 'node:path' -import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import { resolveWorktreeHostPath } from '../../../shared/git/metadata/git-metadata-path' -import { stableInFlightKey } from '../../../shared/in-flight-promise-dedupe' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { gitRuntimeOptionsKey } from './git-runtime-options-cache-key' -import { gitDiffReadDedupe, settledDiffCache } from './git-read-cache-invalidation' -import { readWorktreeDiffStamp } from './worktree-diff-stamp' +import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import { stableInFlightKey } from '../../../../shared/in-flight-promise-dedupe' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { gitRuntimeOptionsKey } from '../git-runtime-options-cache-key' +import { gitDiffReadDedupe, settledDiffCache } from '../git-read-cache-invalidation' +import { readWorktreeDiffStamp } from '../input-stamps/worktree-diff-stamp' import { buildDiffResult } from './diff-result' import { blobConversion, @@ -19,13 +19,16 @@ import { findContainingSubmodule, listSubmodulePaths, resolveSubmoduleWorktreePath -} from './submodule-paths' +} from '../submodules/submodule-paths' import { readGitlinkOidFromIndex, readGitlinkOidFromTree, readWorkingSubmoduleHead -} from './submodule-gitlink-oid' -import { buildSubmoduleInnerCommitRangeDiff, buildSubmodulePointerDiff } from './submodule-diff' +} from '../submodules/submodule-gitlink-oid' +import { + buildSubmoduleInnerCommitRangeDiff, + buildSubmodulePointerDiff +} from '../submodules/submodule-diff' type FileDiffOptions = GitRuntimeOptions & { oldPath?: string } diff --git a/src/main/git/source-control/git-blob-read.ts b/src/main/git/source-control/diffs/git-blob-read.ts similarity index 91% rename from src/main/git/source-control/git-blob-read.ts rename to src/main/git/source-control/diffs/git-blob-read.ts index ebf0ae9f467..c24d392627d 100644 --- a/src/main/git/source-control/git-blob-read.ts +++ b/src/main/git/source-control/diffs/git-blob-read.ts @@ -1,16 +1,16 @@ import { readFile, stat } from 'node:fs/promises' -import { isBinaryBuffer } from '../../../shared/file-preview/binary-buffer' -import { isMissingGitBlobPath } from '../../../shared/git/diff/git-blob-absence' -import { readGitCommandFailureStderr } from '../../../shared/git/commands/git-command-failure-text' +import { isBinaryBuffer } from '../../../../shared/file-preview/binary-buffer' +import { isMissingGitBlobPath } from '../../../../shared/git/diff/git-blob-absence' +import { readGitCommandFailureStderr } from '../../../../shared/git/commands/git-command-failure-text' import { type GitRuntimeOptions, gitReadOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsyncBuffer } from '../command-runner/git-exec-file' -import { isMaxBufferOverflowError } from '../command-runner/process-capture/max-buffer-overflow' -import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' -import { literalPathspec } from './git-pathspec' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsyncBuffer } from '../../command-runner/git-exec-file' +import { isMaxBufferOverflowError } from '../../command-runner/process-capture/max-buffer-overflow' +import { MAX_GIT_SHOW_BYTES } from '../git-show-max-bytes' +import { literalPathspec } from '../git-pathspec' import { hasTextconvDriver, isImageOrPdfPreviewPath } from './textconv-driver' export type GitBlobReadResult = { diff --git a/src/main/git/source-control/staged-rename-diff-real-git.test.ts b/src/main/git/source-control/diffs/staged-rename-diff-real-git.test.ts similarity index 96% rename from src/main/git/source-control/staged-rename-diff-real-git.test.ts rename to src/main/git/source-control/diffs/staged-rename-diff-real-git.test.ts index 19625b87676..64693542a73 100644 --- a/src/main/git/source-control/staged-rename-diff-real-git.test.ts +++ b/src/main/git/source-control/diffs/staged-rename-diff-real-git.test.ts @@ -4,7 +4,7 @@ import * as path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { getDiff } from './file-diff' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' const OLD_PATH = 'old.txt' const NEW_PATH = 'new.txt' diff --git a/src/main/git/source-control/status-diff.test.ts b/src/main/git/source-control/diffs/status-diff.test.ts similarity index 79% rename from src/main/git/source-control/status-diff.test.ts rename to src/main/git/source-control/diffs/status-diff.test.ts index 3529b005198..6ff2d0d7c95 100644 --- a/src/main/git/source-control/status-diff.test.ts +++ b/src/main/git/source-control/diffs/status-diff.test.ts @@ -1,8 +1,8 @@ -import type * as GitExecFileModule from '../command-runner/git-exec-file' -import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-environment/git-process-env' +import type * as GitExecFileModule from '../../command-runner/git-exec-file' +import type * as GitStreamStdoutModule from '../../command-runner/git-stream-stdout' +import type * as GitProcessEnvModule from '../../command-runner/git-environment/git-process-env' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' +import type * as BoundedFileReader from '../../../../shared/file-content/node-bounded-file-reader' import path from 'node:path' import { @@ -35,17 +35,17 @@ const { existsSyncMock: vi.fn() })) -vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ...createGitExecFileModuleMock({ gitExecFileAsyncMock, gitExecFileAsyncBufferMock }) })) -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => ({ +vi.mock('../../command-runner/git-stream-stdout', async (importOriginal) => ({ ...(await importOriginal()), ...createGitStreamStdoutModuleMock({ gitExecFileAsyncMock, gitStreamOptionsMock }) })) -vi.mock('../command-runner/git-environment/git-process-env', async (importOriginal) => ({ +vi.mock('../../command-runner/git-environment/git-process-env', async (importOriginal) => ({ ...(await importOriginal()), ...createGitProcessEnvModuleMock() })) @@ -58,7 +58,7 @@ vi.mock('fs', () => ({ existsSync: existsSyncMock })) -vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => +vi.mock('../../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => createBoundedFileReaderModuleMock(await importOriginal(), { readFileMock, statMock diff --git a/src/main/git/source-control/status-test-harness.ts b/src/main/git/source-control/diffs/status-test-harness.ts similarity index 96% rename from src/main/git/source-control/status-test-harness.ts rename to src/main/git/source-control/diffs/status-test-harness.ts index 3d62cb019a2..41ce6eca20b 100644 --- a/src/main/git/source-control/status-test-harness.ts +++ b/src/main/git/source-control/diffs/status-test-harness.ts @@ -1,5 +1,5 @@ import type { Mock } from 'vitest' -import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' +import type * as BoundedFileReader from '../../../../shared/file-content/node-bounded-file-reader' type MockFn = Mock diff --git a/src/main/git/source-control/textconv-driver.ts b/src/main/git/source-control/diffs/textconv-driver.ts similarity index 88% rename from src/main/git/source-control/textconv-driver.ts rename to src/main/git/source-control/diffs/textconv-driver.ts index 1007804cc59..f784b6ff127 100644 --- a/src/main/git/source-control/textconv-driver.ts +++ b/src/main/git/source-control/diffs/textconv-driver.ts @@ -1,13 +1,13 @@ import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES, filePreviewExtension -} from '../../../shared/file-preview/file-preview-kind' +} from '../../../../shared/file-preview/file-preview-kind' import { type GitRuntimeOptions, gitReadOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' /** Image/PDF diffs preview the stored bytes, so a diff driver must not replace them. */ export function isImageOrPdfPreviewPath(filePath: string): boolean { diff --git a/src/main/git/source-control/drive-checkout-suspect-paths.test.ts b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts similarity index 95% rename from src/main/git/source-control/drive-checkout-suspect-paths.test.ts rename to src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts index a0c1427b75b..1ce9ae395a5 100644 --- a/src/main/git/source-control/drive-checkout-suspect-paths.test.ts +++ b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts @@ -25,7 +25,6 @@ describe('DriveCheckoutSuspectPaths', () => { const reinstalled = { rootPath: REPO } tracker.recordEvents(reinstalled, [event('new.ts')]) expect([...(tracker.beginPoll(reinstalled)?.keys() ?? [])]).toEqual(['new.ts']) - expect(tracker.lastDegradeReason).toBe('watcher-restart') }) it('keeps rechecked-dirty paths through overflow, interruption, restart, and a lost watcher', () => { @@ -33,7 +32,6 @@ describe('DriveCheckoutSuspectPaths', () => { tracker.recordEvents(root, [event('hidden.ts')]) tracker.confirmDirty('hidden.ts', tracker.beginPoll(root)?.get('hidden.ts') ?? 0) tracker.recordEvents(root, [event('a'), event('b'), event('c')]) - expect(tracker.lastDegradeReason).toBe('over-limit') tracker.recordInterruption(root) const reinstalled = { rootPath: REPO } expect([...(tracker.beginPoll(reinstalled)?.keys() ?? [])]).toEqual(['hidden.ts']) diff --git a/src/main/git/source-control/drive-checkout-suspect-paths.ts b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.ts similarity index 98% rename from src/main/git/source-control/drive-checkout-suspect-paths.ts rename to src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.ts index b328329568c..a88799829a9 100644 --- a/src/main/git/source-control/drive-checkout-suspect-paths.ts +++ b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.ts @@ -1,5 +1,5 @@ import * as path from 'node:path' -import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' +import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path' // Minimal checkStat can miss same-size writes preserving whole-second mtime; recheck watcher paths with default stat. diff --git a/src/main/git/source-control/drive-checkout-suspect-status.ts b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-status.ts similarity index 89% rename from src/main/git/source-control/drive-checkout-suspect-status.ts rename to src/main/git/source-control/drive-checkout/drive-checkout-suspect-status.ts index 58eff81613f..6367f5bbd7f 100644 --- a/src/main/git/source-control/drive-checkout-suspect-status.ts +++ b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-status.ts @@ -1,24 +1,24 @@ import * as path from 'node:path' import { lstat } from 'node:fs/promises' -import type { GitStatusEntry } from '../../../shared/git/status/git-status-types' -import { StatusPorcelainParser } from '../../../shared/git/status/git-status-porcelain-parser' -import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' -import { mapWithConcurrency } from '../../../shared/map-with-concurrency' +import type { GitStatusEntry } from '../../../../shared/git/status/git-status-types' +import { StatusPorcelainParser } from '../../../../shared/git/status/git-status-porcelain-parser' +import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path' +import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' import { findCoveringLocalWatchRoot, observeLocalWatcherEvents -} from '../../ipc/filesystem/watchers/local-watcher-event-observers' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { gitStreamStdout } from '../command-runner/git-stream-stdout' -import { usesHostGitForWslLinkedWorktree } from '../command-runner/host-routing/wsl-linked-worktree-git-routing' +} from '../../../ipc/filesystem/watchers/local-watcher-event-observers' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { gitStreamStdout } from '../../command-runner/git-stream-stdout' +import { usesHostGitForWslLinkedWorktree } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' import { withWslWindowsCheckoutGitConfig, wslWindowsCheckoutKey -} from '../command-runner/host-routing/wsl-windows-checkout-git-config' +} from '../../command-runner/host-routing/wsl-windows-checkout-git-config' import { DriveCheckoutSuspectPaths } from './drive-checkout-suspect-paths' -import { bulkPathspecCommands } from './git-pathspec' -import type { GetStatusOptions } from './get-status-options' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' +import { bulkPathspecCommands } from '../git-pathspec' +import type { GetStatusOptions } from '../status/get-status-options' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' // Why: the later `-c` overrides the injected `core.checkStat=minimal` for just these paths. const TARGETED_STATUS_ARGS = [ diff --git a/src/main/git/source-control/drive-checkout-suspect-writes.ts b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-writes.ts similarity index 92% rename from src/main/git/source-control/drive-checkout-suspect-writes.ts rename to src/main/git/source-control/drive-checkout/drive-checkout-suspect-writes.ts index 2c6a6dae98d..3976b88d0b0 100644 --- a/src/main/git/source-control/drive-checkout-suspect-writes.ts +++ b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-writes.ts @@ -1,10 +1,10 @@ import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { driveCheckoutSuspectsWithin } from './drive-checkout-suspect-status' -import { bulkPathspecCommands } from './git-pathspec' +import { bulkPathspecCommands } from '../git-pathspec' /** The write a path operation redoes for its suspects; pathspecs are appended after `--`. */ export type DriveCheckoutSuspectWrite = diff --git a/src/main/git/source-control/git-read-cache-invalidation.ts b/src/main/git/source-control/git-read-cache-invalidation.ts index ded54b4e7ed..1d226037f6c 100644 --- a/src/main/git/source-control/git-read-cache-invalidation.ts +++ b/src/main/git/source-control/git-read-cache-invalidation.ts @@ -8,13 +8,13 @@ import { } from '../../../shared/git/status/git-status-line-stats-cache' import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total' import { GitStatusReadLeaseOwner } from '../../../shared/git/status/git-status-read-lease-owner' -import { invalidateGitUpstreamStatusReads } from './upstream' -import { clearSubmodulePathsCache } from './submodule-paths' -import { resolvedUpstreamNameCache } from './resolved-upstream-name-cache' +import { invalidateGitUpstreamStatusReads } from './upstream/upstream' +import { clearSubmodulePathsCache } from './submodules/submodule-paths' +import { resolvedUpstreamNameCache } from './upstream/resolved-upstream-name-cache' import { getStatusLineStatsCacheKey, isStatusKeyForWorktreePath -} from './status-branch-line-total-input' +} from './status/status-branch-line-total-input' import { FILE_DIFF_CACHE_LIMITS, NUMSTAT_CACHE_LIMITS, diff --git a/src/main/git/source-control/git-upstream-status-read-owner.test.ts b/src/main/git/source-control/git-upstream-status-read-owner.test.ts deleted file mode 100644 index c044983529d..00000000000 --- a/src/main/git/source-control/git-upstream-status-read-owner.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { GitUpstreamStatus } from '../../../shared/git/status/git-status-types' -import type { GitPushTarget } from '../../../shared/worktree/types' -import { - GitUpstreamStatusReadOwner, - type GitUpstreamStatusExecutionIdentity -} from './git-upstream-status-read-owner' - -const upstreamStatus: GitUpstreamStatus = { - hasUpstream: true, - upstreamName: 'origin/main', - ahead: 1, - behind: 0 -} - -function deferredPromise(): { - promise: Promise - resolve: (value: T) => void - reject: (error: unknown) => void -} { - let resolve!: (value: T) => void - let reject!: (error: unknown) => void - const promise = new Promise((innerResolve, innerReject) => { - resolve = innerResolve - reject = innerReject - }) - return { promise, resolve, reject } -} - -describe('GitUpstreamStatusReadOwner', () => { - it('shares one live read across ten identical callers', async () => { - const owner = new GitUpstreamStatusReadOwner() - const pending = deferredPromise() - const load = vi.fn(() => pending.promise) - - const reads = Array.from({ length: 10 }, () => - owner.read({ kind: 'native' }, '/repo', undefined, load) - ) - await Promise.resolve() - - expect(load).toHaveBeenCalledTimes(1) - pending.resolve(upstreamStatus) - await expect(Promise.all(reads)).resolves.toEqual( - Array.from({ length: 10 }, () => upstreamStatus) - ) - }) - - it('isolates paths, execution hosts, and every explicit target field', async () => { - const owner = new GitUpstreamStatusReadOwner() - const load = vi.fn().mockResolvedValue(upstreamStatus) - const baseTarget: GitPushTarget = { - remoteName: 'fork', - branchName: 'feature' - } - const cases: [GitUpstreamStatusExecutionIdentity, string, GitPushTarget | undefined][] = [ - [{ kind: 'native' }, '/repo-a', undefined], - [{ kind: 'native' }, '/repo-b', undefined], - [{ kind: 'wsl', distro: 'Ubuntu' }, '/repo-a', undefined], - [{ kind: 'wsl', distro: 'Debian' }, '/repo-a', undefined], - [{ kind: 'native' }, '/repo-a', baseTarget], - [{ kind: 'native' }, '/repo-a', { ...baseTarget, remoteName: 'origin' }], - [{ kind: 'native' }, '/repo-a', { ...baseTarget, branchName: 'other' }], - [ - { kind: 'native' }, - '/repo-a', - { ...baseTarget, remoteUrl: 'https://github.com/example/fork.git' } - ], - [{ kind: 'native' }, '/repo-a', { ...baseTarget, remoteCreated: false }], - [{ kind: 'native' }, '/repo-a', { ...baseTarget, remoteCreated: true }], - [{ kind: 'ssh-provider' }, '/repo-a', baseTarget] - ] - - await Promise.all( - cases.map(([identity, worktreePath, target]) => - owner.read(identity, worktreePath, target, load) - ) - ) - - expect(load).toHaveBeenCalledTimes(cases.length) - }) - - it('runs fresh work after success and rejection', async () => { - const owner = new GitUpstreamStatusReadOwner() - const failure = new Error('upstream failed') - const load = vi - .fn<() => Promise>() - .mockResolvedValueOnce(upstreamStatus) - .mockRejectedValueOnce(failure) - .mockResolvedValueOnce(upstreamStatus) - - await expect(owner.read({ kind: 'native' }, '/repo', undefined, load)).resolves.toBe( - upstreamStatus - ) - await expect(owner.read({ kind: 'native' }, '/repo', undefined, load)).rejects.toBe(failure) - await expect(owner.read({ kind: 'native' }, '/repo', undefined, load)).resolves.toBe( - upstreamStatus - ) - expect(load).toHaveBeenCalledTimes(3) - }) - - it('fences before, during, and after mutation generations', async () => { - const owner = new GitUpstreamStatusReadOwner() - const pendingReads = Array.from({ length: 3 }, () => deferredPromise()) - const load = vi.fn(() => pendingReads[load.mock.calls.length - 1].promise) - - const before = owner.read({ kind: 'native' }, '/repo', undefined, load) - await Promise.resolve() - owner.invalidate() - const during = owner.read({ kind: 'native' }, '/repo', undefined, load) - await Promise.resolve() - owner.invalidate() - const after = owner.read({ kind: 'native' }, '/repo', undefined, load) - await Promise.resolve() - - pendingReads.forEach((pending) => pending.resolve(upstreamStatus)) - await expect(Promise.all([before, during, after])).resolves.toEqual( - Array.from({ length: 3 }, () => upstreamStatus) - ) - expect(load).toHaveBeenCalledTimes(3) - }) -}) diff --git a/src/main/git/source-control/huge-folder-ignore.test.ts b/src/main/git/source-control/huge-folder-ignore.test.ts deleted file mode 100644 index d4e09cd356b..00000000000 --- a/src/main/git/source-control/huge-folder-ignore.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import * as fs from 'node:fs/promises' -import { tmpdir } from 'node:os' -import * as path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { checkIgnoredPathsMock } = vi.hoisted(() => ({ - checkIgnoredPathsMock: vi.fn<(worktreePath: string, paths: string[]) => Promise>() -})) - -vi.mock('./check-ignored-paths', () => ({ - checkIgnoredPaths: checkIgnoredPathsMock -})) - -import { appendFolderToGitignore } from './huge-folder-ignore' - -describe('appendFolderToGitignore', () => { - let dir: string - - beforeEach(() => { - dir = mkdtempSync(path.join(tmpdir(), 'huge-folder-write-')) - }) - - afterEach(async () => { - await fs.rm(dir, { recursive: true, force: true }) - }) - - it('creates .gitignore with the folder pattern when absent', async () => { - const wrote = await appendFolderToGitignore(dir, 'node_modules') - expect(wrote).toBe(true) - const content = await fs.readFile(path.join(dir, '.gitignore'), 'utf-8') - expect(content).toContain('node_modules/') - }) - - it('appends with a leading newline when the file lacks a trailing one', async () => { - await fs.writeFile(path.join(dir, '.gitignore'), '*.log') - const wrote = await appendFolderToGitignore(dir, 'dist') - expect(wrote).toBe(true) - const content = await fs.readFile(path.join(dir, '.gitignore'), 'utf-8') - expect(content).toBe('*.log\ndist/\n') - }) - - it('rejects folder names outside the known allowlist (injection guard)', async () => { - await expect(appendFolderToGitignore(dir, 'node_modules\n/etc/passwd')).rejects.toThrow( - /Refusing to add/ - ) - await expect(appendFolderToGitignore(dir, '../escape')).rejects.toThrow(/Refusing to add/) - await expect(appendFolderToGitignore(dir, 'arbitrary')).rejects.toThrow(/Refusing to add/) - }) -}) diff --git a/src/main/git/source-control/check-ignored-paths.ts b/src/main/git/source-control/ignores/check-ignored-paths.ts similarity index 88% rename from src/main/git/source-control/check-ignored-paths.ts rename to src/main/git/source-control/ignores/check-ignored-paths.ts index 1b38e17ea52..fea9b4c9a55 100644 --- a/src/main/git/source-control/check-ignored-paths.ts +++ b/src/main/git/source-control/ignores/check-ignored-paths.ts @@ -1,15 +1,15 @@ import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { encodeGitCheckIgnorePaths, GIT_CHECK_IGNORE_STDIN_ARGS, GIT_CHECK_IGNORE_TIMEOUT_MS, parseGitCheckIgnorePaths, splitGitCheckIgnorePathsByStdinBytes -} from '../../../shared/git/paths/git-check-ignore-stdio' +} from '../../../../shared/git/paths/git-check-ignore-stdio' type GitExecError = Error & { stdout?: string; code?: number | string } diff --git a/src/main/git/source-control/ignores/huge-folder-ignore.test.ts b/src/main/git/source-control/ignores/huge-folder-ignore.test.ts new file mode 100644 index 00000000000..1f053dc2415 --- /dev/null +++ b/src/main/git/source-control/ignores/huge-folder-ignore.test.ts @@ -0,0 +1,41 @@ +import { mkdtempSync } from 'node:fs' +import * as fs from 'node:fs/promises' +import { tmpdir } from 'node:os' +import * as path from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { checkIgnoredPathsMock } = vi.hoisted(() => ({ + checkIgnoredPathsMock: vi.fn<(worktreePath: string, paths: string[]) => Promise>() +})) + +vi.mock('./check-ignored-paths', () => ({ + checkIgnoredPaths: checkIgnoredPathsMock +})) + +import { appendFolderToGitignore } from './huge-folder-ignore' + +describe('appendFolderToGitignore', () => { + let dir: string + + beforeEach(() => { + dir = mkdtempSync(path.join(tmpdir(), 'huge-folder-write-')) + }) + + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }) + }) + + it('appends with a leading newline when the file lacks a trailing one', async () => { + await fs.writeFile(path.join(dir, '.gitignore'), '*.log') + const wrote = await appendFolderToGitignore(dir, 'dist') + expect(wrote).toBe(true) + const content = await fs.readFile(path.join(dir, '.gitignore'), 'utf-8') + expect(content).toBe('*.log\ndist/\n') + }) + + it('rejects folder names outside the known allowlist (injection guard)', async () => { + await expect(appendFolderToGitignore(dir, 'node_modules\n/etc/passwd')).rejects.toThrow( + /Refusing to add/ + ) + }) +}) diff --git a/src/main/git/source-control/huge-folder-ignore.ts b/src/main/git/source-control/ignores/huge-folder-ignore.ts similarity index 96% rename from src/main/git/source-control/huge-folder-ignore.ts rename to src/main/git/source-control/ignores/huge-folder-ignore.ts index 927785a48dc..7143bd79d4a 100644 --- a/src/main/git/source-control/huge-folder-ignore.ts +++ b/src/main/git/source-control/ignores/huge-folder-ignore.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { appendFile, readFile, stat } from 'node:fs/promises' import * as path from 'node:path' import { checkIgnoredPaths } from './check-ignored-paths' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' // Offer common dependency/build folders when unignored content saturates status. const KNOWN_HUGE_FOLDER_NAMES = [ diff --git a/src/main/git/source-control/deadline-bounded-stamp.ts b/src/main/git/source-control/input-stamps/deadline-bounded-stamp.ts similarity index 82% rename from src/main/git/source-control/deadline-bounded-stamp.ts rename to src/main/git/source-control/input-stamps/deadline-bounded-stamp.ts index 4b83f7eb3bb..edaea098c72 100644 --- a/src/main/git/source-control/deadline-bounded-stamp.ts +++ b/src/main/git/source-control/input-stamps/deadline-bounded-stamp.ts @@ -1,5 +1,5 @@ -import { withTimeout } from '../../../shared/promise-timeout-fallback' -import { runCoalescedProbe, type CoalescedProbes } from '../remotes/coalesced-probe' +import { withTimeout } from '../../../../shared/promise-timeout-fallback' +import { runCoalescedProbe, type CoalescedProbes } from '../../remotes/coalesced-probe' import type { WorktreeDiffStamp } from './worktree-diff-stamp' // A dead home or network mount can stall stat; skip reuse after this instead of stalling the poll. diff --git a/src/main/git/source-control/gitattributes-stamp-paths.ts b/src/main/git/source-control/input-stamps/gitattributes-stamp-paths.ts similarity index 100% rename from src/main/git/source-control/gitattributes-stamp-paths.ts rename to src/main/git/source-control/input-stamps/gitattributes-stamp-paths.ts diff --git a/src/main/git/source-control/stamped-git-config.ts b/src/main/git/source-control/input-stamps/stamped-git-config.ts similarity index 93% rename from src/main/git/source-control/stamped-git-config.ts rename to src/main/git/source-control/input-stamps/stamped-git-config.ts index 52b50e9fcfd..6bfe9b7f22f 100644 --- a/src/main/git/source-control/stamped-git-config.ts +++ b/src/main/git/source-control/input-stamps/stamped-git-config.ts @@ -1,18 +1,18 @@ import { access } from 'node:fs/promises' import { homedir } from 'node:os' import * as path from 'node:path' -import { BoundedMap } from '../../../shared/bounded-map' -import { resolveWorktreeHostPath } from '../../../shared/git/metadata/git-metadata-path' -import { InFlightPromiseDedupe } from '../../../shared/in-flight-promise-dedupe' -import { iterateNulDelimitedFields } from '../../../shared/nul-delimited-fields' -import { wslDistroForCommand } from '../../../shared/wsl-paths' +import { BoundedMap } from '../../../../shared/bounded-map' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import { InFlightPromiseDedupe } from '../../../../shared/in-flight-promise-dedupe' +import { iterateNulDelimitedFields } from '../../../../shared/nul-delimited-fields' +import { wslDistroForCommand } from '../../../../shared/wsl-paths' import { gitReadOptionsForWorktree, type GitRuntimeOptions -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { readStampWithinDeadline, type StampProbes } from './deadline-bounded-stamp' -import { resolveGitCommonDir, resolveGitDir } from './resolve-git-dir' +import { resolveGitCommonDir, resolveGitDir } from '../resolve-git-dir' import { canProveUnchangedByStamp, readHostFilesStamp, diff --git a/src/main/git/source-control/worktree-diff-stamp.ts b/src/main/git/source-control/input-stamps/worktree-diff-stamp.ts similarity index 97% rename from src/main/git/source-control/worktree-diff-stamp.ts rename to src/main/git/source-control/input-stamps/worktree-diff-stamp.ts index 6d1dc50cc89..dd97a49d001 100644 --- a/src/main/git/source-control/worktree-diff-stamp.ts +++ b/src/main/git/source-control/input-stamps/worktree-diff-stamp.ts @@ -1,8 +1,8 @@ import { readFile, stat } from 'node:fs/promises' import * as path from 'node:path' -import { resolveWorktreeHostPath } from '../../../shared/git/metadata/git-metadata-path' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { resolveGitCommonDir, resolveGitDir } from './resolve-git-dir' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { resolveGitCommonDir, resolveGitDir } from '../resolve-git-dir' /** Stamp HEAD, index, routing metadata and working-file inputs without Git; null forbids caching. */ export type WorktreeDiffStamp = { diff --git a/src/main/git/source-control/commit-changes.ts b/src/main/git/source-control/mutations/commit-changes.ts similarity index 90% rename from src/main/git/source-control/commit-changes.ts rename to src/main/git/source-control/mutations/commit-changes.ts index 380e63b826b..cfb4fa6d454 100644 --- a/src/main/git/source-control/commit-changes.ts +++ b/src/main/git/source-control/mutations/commit-changes.ts @@ -1,10 +1,10 @@ import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { detectConflictOperation } from './git-conflict-operation' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' export function commitChanges( worktreePath: string, diff --git a/src/main/git/source-control/complete-merge-real-git.test.ts b/src/main/git/source-control/mutations/complete-merge-real-git.test.ts similarity index 100% rename from src/main/git/source-control/complete-merge-real-git.test.ts rename to src/main/git/source-control/mutations/complete-merge-real-git.test.ts diff --git a/src/main/git/source-control/discard-changes.ts b/src/main/git/source-control/mutations/discard-changes.ts similarity index 88% rename from src/main/git/source-control/discard-changes.ts rename to src/main/git/source-control/mutations/discard-changes.ts index 83c0713862c..e955663300a 100644 --- a/src/main/git/source-control/discard-changes.ts +++ b/src/main/git/source-control/mutations/discard-changes.ts @@ -2,18 +2,18 @@ import * as path from 'node:path' import { removeSafeUntrackedDiscardTarget, removeSafeUntrackedDiscardTargets -} from '../../../shared/git/paths/git-discard-path-safety' -import { partitionTrackedPathSpecs } from '../../../shared/git/paths/git-tracked-pathspecs' +} from '../../../../shared/git/paths/git-discard-path-safety' +import { partitionTrackedPathSpecs } from '../../../../shared/git/paths/git-tracked-pathspecs' import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' -import { bulkPathspecCommands, literalPathspec } from './git-pathspec' -import { encodeGitPathspecs } from '../../../shared/git/paths/git-pathspec-stdin' -import { redoWriteForDriveCheckoutSuspects } from './drive-checkout-suspect-writes' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' +import { bulkPathspecCommands, literalPathspec } from '../git-pathspec' +import { encodeGitPathspecs } from '../../../../shared/git/paths/git-pathspec-stdin' +import { redoWriteForDriveCheckoutSuspects } from '../drive-checkout/drive-checkout-suspect-writes' const DISCARD_WRITE = ['restore', '--worktree'] as const diff --git a/src/main/git/source-control/git-conflict-operation.ts b/src/main/git/source-control/mutations/git-conflict-operation.ts similarity index 85% rename from src/main/git/source-control/git-conflict-operation.ts rename to src/main/git/source-control/mutations/git-conflict-operation.ts index 549ea395f75..5a2dcade9f1 100644 --- a/src/main/git/source-control/git-conflict-operation.ts +++ b/src/main/git/source-control/mutations/git-conflict-operation.ts @@ -1,14 +1,14 @@ import { access } from 'node:fs/promises' import * as path from 'node:path' -import type { GitConflictOperation } from '../../../shared/git/status/git-status-types' +import type { GitConflictOperation } from '../../../../shared/git/status/git-status-types' import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { runWithGitReadCacheInvalidation } from './git-read-cache-invalidation' -import { resolveGitDir } from './resolve-git-dir' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { runWithGitReadCacheInvalidation } from '../git-read-cache-invalidation' +import { resolveGitDir } from '../resolve-git-dir' // HEAD detection races may yield unknown for one poll; rebase directories persist more reliably than REBASE_HEAD. export async function detectConflictOperation( diff --git a/src/main/git/source-control/stage-worktree-changes.test.ts b/src/main/git/source-control/mutations/stage-worktree-changes.test.ts similarity index 88% rename from src/main/git/source-control/stage-worktree-changes.test.ts rename to src/main/git/source-control/mutations/stage-worktree-changes.test.ts index 812439a0913..72110bd59d8 100644 --- a/src/main/git/source-control/stage-worktree-changes.test.ts +++ b/src/main/git/source-control/mutations/stage-worktree-changes.test.ts @@ -3,8 +3,8 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import * as path from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { DEFAULT_GIT_STATUS_LIMIT } from '../../../shared/git/status/git-status-limit' -import { getStatus } from './status-read' +import { DEFAULT_GIT_STATUS_LIMIT } from '../../../../shared/git/status/git-status-limit' +import { getStatus } from '../status/status-read' import { bulkStageFiles, stageWorktreeChanges } from './staging' const tempRoots: string[] = [] @@ -85,15 +85,6 @@ describe('stageWorktreeChanges', () => { expect(names(repo, ['diff', '--cached', '--name-only'])).toHaveLength(OVER_CAP + 1) }) - it('stages only tracked changes for the tracked scope', async () => { - const repo = await createOverCapRepo() - - await stageWorktreeChanges(repo, 'tracked') - - expect(names(repo, ['diff', '--name-only'])).toEqual([]) - expect(names(repo, ['ls-files', '--others', '--exclude-standard'])).toEqual(['zz-new.txt']) - }) - it('leaves unresolved conflicts unstaged', async () => { const repo = await createConflictRepo() @@ -177,15 +168,5 @@ describe('stageWorktreeChanges', () => { ]) }) }) - - it('still stages a regular file the user put at a shared name', async () => { - const repo = await createRepo() - git(repo, ['commit', '-q', '--allow-empty', '-m', 'initial']) - await writeFile(path.join(repo, 'node_modules'), 'not a link\n') - - await stageWorktreeChanges(repo, 'all', { sharedLinkPaths: ['node_modules'] }) - - expect(names(repo, ['diff', '--cached', '--name-only'])).toEqual(['node_modules']) - }) }) }) diff --git a/src/main/git/source-control/staged-commit-context.ts b/src/main/git/source-control/mutations/staged-commit-context.ts similarity index 80% rename from src/main/git/source-control/staged-commit-context.ts rename to src/main/git/source-control/mutations/staged-commit-context.ts index 4979bf7ff13..fae2dcfe6ef 100644 --- a/src/main/git/source-control/staged-commit-context.ts +++ b/src/main/git/source-control/mutations/staged-commit-context.ts @@ -1,15 +1,15 @@ -import type { CommitMessageDraftContext } from '../../../shared/source-control/ai/generation/commit-message-generation' +import type { CommitMessageDraftContext } from '../../../../shared/source-control/ai/generation/commit-message-generation' import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { describeMaxBufferOverflowError, isMaxBufferOverflowError -} from '../command-runner/process-capture/max-buffer-overflow' -import { MAX_STAGED_COMMIT_CONTEXT_BYTES } from './git-show-max-bytes' +} from '../../command-runner/process-capture/max-buffer-overflow' +import { MAX_STAGED_COMMIT_CONTEXT_BYTES } from '../git-show-max-bytes' export async function getStagedCommitContext( worktreePath: string, diff --git a/src/main/git/source-control/staging-discard-index-safety.test.ts b/src/main/git/source-control/mutations/staging-discard-index-safety.test.ts similarity index 86% rename from src/main/git/source-control/staging-discard-index-safety.test.ts rename to src/main/git/source-control/mutations/staging-discard-index-safety.test.ts index e966767ec53..95b8a7245dc 100644 --- a/src/main/git/source-control/staging-discard-index-safety.test.ts +++ b/src/main/git/source-control/mutations/staging-discard-index-safety.test.ts @@ -76,21 +76,6 @@ describe('staging and discard preserve index authority', () => { expect(await readFile(path.join(repo, 'selected.txt'), 'utf8')).toBe('selected\n') }) - it('discards a staged rename after unstaging both paths', async () => { - await writeFile(path.join(repo, 'old.txt'), 'rename content\n') - gitCommit(repo, 'initial') - await git(['mv', 'old.txt', 'new.txt']) - - await mutate({ bulk: true }, 'unstage', ['new.txt', 'old.txt']) - await mutate({ bulk: true }, 'discard', ['new.txt', 'old.txt']) - - expect(await git(['status', '--porcelain'])).toBe('') - expect(await readFile(path.join(repo, 'old.txt'), 'utf8')).toBe('rename content\n') - await expect(readFile(path.join(repo, 'new.txt'), 'utf8')).rejects.toMatchObject({ - code: 'ENOENT' - }) - }) - it.each(modes)('rejects an unresolved conflict on bulk=$bulk', async (mode) => { await writeFile(path.join(repo, 'file.txt'), 'base\n') gitCommit(repo, 'initial') diff --git a/src/main/git/source-control/staging.ts b/src/main/git/source-control/mutations/staging.ts similarity index 86% rename from src/main/git/source-control/staging.ts rename to src/main/git/source-control/mutations/staging.ts index 6a190acf676..aa999cf5178 100644 --- a/src/main/git/source-control/staging.ts +++ b/src/main/git/source-control/mutations/staging.ts @@ -1,24 +1,24 @@ import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' -import { gitReportedPath, literalPathspec } from './git-pathspec' -import { encodeGitPathspecs } from '../../../shared/git/paths/git-pathspec-stdin' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' +import { gitReportedPath, literalPathspec } from '../git-pathspec' +import { encodeGitPathspecs } from '../../../../shared/git/paths/git-pathspec-stdin' import { getConflictResolutions, type ConflictResolution -} from '../../../shared/source-control/listing/source-control-entry-actions' -import { parseUnmergedEntry } from '../../../shared/git/status/git-status-conflict-entries' +} from '../../../../shared/source-control/listing/source-control-entry-actions' +import { parseUnmergedEntry } from '../../../../shared/git/status/git-status-conflict-entries' import { stageGitWorktreeScope, type GitStageWorktreeScope, type GitStageWorktreeScopeReceipt -} from '../../../shared/git/paths/git-stage-worktree-scope' -import { findExistingWorktreeSymlinkPaths } from '../worktrees/content-paths/worktree-symlink-detection' -import { redoWriteForDriveCheckoutSuspects } from './drive-checkout-suspect-writes' -import { runWithGitWorktreeOperationLock } from '../../../shared/git/worktrees/git-worktree-operation-lock' +} from '../../../../shared/git/paths/git-stage-worktree-scope' +import { findExistingWorktreeSymlinkPaths } from '../../worktrees/content-paths/worktree-symlink-detection' +import { redoWriteForDriveCheckoutSuspects } from '../drive-checkout/drive-checkout-suspect-writes' +import { runWithGitWorktreeOperationLock } from '../../../../shared/git/worktrees/git-worktree-operation-lock' const STAGE_WRITE = ['add', '--update'] as const diff --git a/src/main/git/source-control/status-discard-symlink.test.ts b/src/main/git/source-control/mutations/status-discard-symlink.test.ts similarity index 87% rename from src/main/git/source-control/status-discard-symlink.test.ts rename to src/main/git/source-control/mutations/status-discard-symlink.test.ts index 611ccf73398..5eebbeac9b7 100644 --- a/src/main/git/source-control/status-discard-symlink.test.ts +++ b/src/main/git/source-control/mutations/status-discard-symlink.test.ts @@ -129,22 +129,6 @@ describe('discardChanges symlink safety', () => { await expect(readFile(path.join(repo, globMatchedFile), 'utf8')).resolves.toBe('keep modified') }) - it('treats bulk untracked discard paths with Git glob characters as literal paths', async () => { - const { repo } = await createRepoWithOutsideDirectory() - await writeFile(path.join(repo, '.gitignore'), 'ignored.log\n') - execFileSync('git', ['add', '.gitignore'], { cwd: repo }) - execFileSync('git', ['commit', '-q', '-m', 'ignore log fixture'], { cwd: repo }) - await writeFile(path.join(repo, globNamedFile), 'selected') - await writeFile(path.join(repo, globMatchedFile), 'unrelated') - await writeFile(path.join(repo, 'ignored.log'), 'ignored') - - await bulkDiscardChanges(repo, [globNamedFile]) - - await expect(access(path.join(repo, globNamedFile))).rejects.toThrow() - await expect(access(path.join(repo, globMatchedFile))).resolves.toBeUndefined() - await expect(access(path.join(repo, 'ignored.log'))).resolves.toBeUndefined() - }) - it('removes untracked nested git repos selected for discard', async () => { const { repo } = await createRepoWithOutsideDirectory() const nestedRepo = path.join(repo, 'nested') diff --git a/src/main/git/source-control/status-pathspec-literals.test.ts b/src/main/git/source-control/mutations/status-pathspec-literals.test.ts similarity index 100% rename from src/main/git/source-control/status-pathspec-literals.test.ts rename to src/main/git/source-control/mutations/status-pathspec-literals.test.ts diff --git a/src/main/git/source-control/porcelain-v1-records.test.ts b/src/main/git/source-control/porcelain-v1-records.test.ts deleted file mode 100644 index 3d6a8188873..00000000000 --- a/src/main/git/source-control/porcelain-v1-records.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { parsePorcelainV1Records } from './porcelain-v1-records' - -const tempRoots: string[] = [] - -const git = (args: string[], cwd: string): string => - execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) - -function createRepo(): string { - const repo = mkdtempSync(join(tmpdir(), 'orca-porcelain-v1-')) - tempRoots.push(repo) - git(['init', '-q', '-b', 'main'], repo) - git(['config', 'user.email', 'test@example.com'], repo) - git(['config', 'user.name', 'Test'], repo) - return repo -} - -afterEach(() => { - for (const root of tempRoots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -describe('parsePorcelainV1Records', () => { - it('keeps paths containing spaces and quotes intact', () => { - const repo = createRepo() - writeFileSync(join(repo, 'a file "quoted".txt'), 'x') - - const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) - - expect(records).toEqual([{ xy: '??', path: 'a file "quoted".txt' }]) - }) - - it('keeps non-ASCII paths raw rather than C-quoted', () => { - const repo = createRepo() - writeFileSync(join(repo, '日本語.txt'), 'x') - - expect(parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo))).toEqual([ - { xy: '??', path: '日本語.txt' } - ]) - }) - - // Rename origins are extra NUL fields; treating one as a record could invent an untracked status. - it('consumes the origin path of a rename instead of emitting it as a record', () => { - const repo = createRepo() - writeFileSync(join(repo, 'original.txt'), 'content\n') - git(['add', '-A'], repo) - git(['commit', '-qm', 'init'], repo) - git(['mv', 'original.txt', 'renamed.txt'], repo) - - const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) - - expect(records).toEqual([{ xy: 'R ', path: 'renamed.txt' }]) - }) - - it('reports a rename alongside a later untracked entry', () => { - const repo = createRepo() - writeFileSync(join(repo, 'original.txt'), 'content\n') - git(['add', '-A'], repo) - git(['commit', '-qm', 'init'], repo) - git(['mv', 'original.txt', 'renamed.txt'], repo) - mkdirSync(join(repo, 'node_modules')) - writeFileSync(join(repo, 'node_modules', 'pkg.js'), 'x') - - const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) - - expect(records).toEqual([ - { xy: 'R ', path: 'renamed.txt' }, - { xy: '??', path: 'node_modules/' } - ]) - }) -}) diff --git a/src/main/git/source-control/settled-diff-cache.ts b/src/main/git/source-control/settled-diff-cache.ts index fa4d2546c9f..a1474d88e23 100644 --- a/src/main/git/source-control/settled-diff-cache.ts +++ b/src/main/git/source-control/settled-diff-cache.ts @@ -5,7 +5,7 @@ import { canProveUnchangedByStamp, isDiffStampClockSkewed, type WorktreeDiffStamp -} from './worktree-diff-stamp' +} from './input-stamps/worktree-diff-stamp' /** Reuse diffs only with matching input stamps; decline unknown, recent, failed or mutation-overlapped reads. */ diff --git a/src/main/git/source-control/status-branch-line-total-exec-contract.test.ts b/src/main/git/source-control/status-branch-line-total-exec-contract.test.ts deleted file mode 100644 index c1e9f179989..00000000000 --- a/src/main/git/source-control/status-branch-line-total-exec-contract.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import type * as GitExecFileModule from '../command-runner/git-exec-file' -import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import { execFileSync } from 'node:child_process' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import * as path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total' - -import type * as BranchLineTotal from '../../../shared/git/status/git-branch-line-total' - -// Spy on real Git argv to validate opt-in and coalescing without stubbing results. -const { gitExecCalls, execHooks, coalescerJoins } = vi.hoisted(() => ({ - gitExecCalls: [] as string[][], - execHooks: { beforeExec: undefined as undefined | ((args: string[]) => Promise | void) }, - coalescerJoins: { count: 0, onJoin: undefined as undefined | (() => void) } -})) - -vi.mock('../../../shared/git/status/git-branch-line-total', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - computeGitBranchLineTotal: ( - input: Parameters[0] - ) => { - // Lease acquisition is synchronous, so a join is observable immediately after this call. - const total = actual.computeGitBranchLineTotal(input) - coalescerJoins.count += 1 - coalescerJoins.onJoin?.() - return total - } - } -}) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - gitExecFileAsync: async (...args: Parameters) => { - gitExecCalls.push(args[0]) - await execHooks.beforeExec?.(args[0]) - return actual.gitExecFileAsync(...args) - }, - gitExecFileAsyncBuffer: async (...args: Parameters) => { - gitExecCalls.push(args[0]) - return actual.gitExecFileAsyncBuffer(...args) - } - } -}) - -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - gitStreamStdout: async (...args: Parameters) => { - gitExecCalls.push(args[0]) - return actual.gitStreamStdout(...args) - } - } -}) - -import { clearEffectiveUpstreamStatusCacheForTests } from './effective-upstream-status-cache' -import { clearSubmodulePathsCacheForTests } from './submodule-paths' -import { getStatus } from './status-read' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' - -const BOGUS_MERGE_BASE = 'deadbeef'.repeat(5) -const NO_LINES = { added: 0, removed: 0 } -const tempRoots: string[] = [] - -function git(repo: string, args: string[]): string { - return execFileSync('git', args, { - cwd: repo, - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'pipe'] - }).trim() -} - -async function createFixtureRepo(): Promise<{ repo: string; mergeBase: string }> { - const root = await mkdtemp(path.join(tmpdir(), 'orca-branch-line-total-exec-')) - tempRoots.push(root) - const repo = path.join(root, 'repo') - execFileSync('git', ['init', '-q', repo]) - git(repo, ['config', 'user.email', 'test@example.com']) - git(repo, ['config', 'user.name', 'Test User']) - git(repo, ['config', 'commit.gpgSign', 'false']) - await write(repo, 'f.txt', 'a\nb\n') - git(repo, ['add', '-A']) - git(repo, ['commit', '-q', '-m', 'base']) - await write(repo, 'f.txt', 'a\nb\nc\n') - return { repo, mergeBase: git(repo, ['rev-parse', 'HEAD']) } -} - -async function write(repo: string, relativePath: string, contents: string): Promise { - const target = path.join(repo, relativePath) - await mkdir(path.dirname(target), { recursive: true }) - await writeFile(target, contents) -} - -/** The `mergeBase → worktree` diff, distinguished from the per-area numstats by its rev + `--`. */ -function rangedDiffCalls(): string[][] { - return gitExecCalls.filter((args) => args.includes('--numstat') && args.at(-1) === '--') -} - -/** Resolves once `count` status passes have entered the branch-total coalescer. */ -function waitForCoalescerJoins(count: number): Promise { - if (coalescerJoins.count >= count) { - return Promise.resolve() - } - return new Promise((resolve) => { - coalescerJoins.onJoin = () => { - if (coalescerJoins.count >= count) { - coalescerJoins.onJoin = undefined - resolve() - } - } - }) -} - -function resetGitReadCaches(): void { - clearEffectiveUpstreamStatusCacheForTests() - clearSubmodulePathsCacheForTests() - invalidateGitReadCaches() - invalidateGitBranchLineTotalInFlight() -} - -beforeEach(() => { - gitExecCalls.length = 0 - execHooks.beforeExec = undefined - coalescerJoins.count = 0 - coalescerJoins.onJoin = undefined - resetGitReadCaches() -}) - -afterEach(async () => { - execHooks.beforeExec = undefined - coalescerJoins.onJoin = undefined - resetGitReadCaches() - await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('branch line total completeness', () => { - it('omits the total when the status listing hit its limit', async () => { - const { repo, mergeBase } = await createFixtureRepo() - await write(repo, 'u1.txt', 'a\n') - await write(repo, 'u2.txt', 'b\n') - await write(repo, 'u3.txt', 'c\n') - - const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase, limit: 1 }) - - expect(result.didHitLimit).toBe(true) - expect(result.branchLineTotal).toBeUndefined() - expect(result.branchLineTotalUnavailable).toBeUndefined() - expect(rangedDiffCalls()).toEqual([]) - }) - - it('invalidates the total when the ranged numstat fails, rather than reporting zero', async () => { - const { repo } = await createFixtureRepo() - - const result = await getStatus(repo, { branchLineTotalMergeBase: BOGUS_MERGE_BASE }) - - expect(result.entries.length).toBeGreaterThan(0) - expect(result.branchLineTotal).toBeUndefined() - expect(result.branchLineTotalUnavailable).toBe(BOGUS_MERGE_BASE) - expect(rangedDiffCalls()).toHaveLength(1) - }) - - it('rejects with an AbortError when the pass is cancelled mid-diff', async () => { - const { repo, mergeBase } = await createFixtureRepo() - const controller = new AbortController() - execHooks.beforeExec = (args) => { - if (args.includes('--numstat') && args.at(-1) === '--') { - controller.abort() - } - } - - await expect( - getStatus(repo, { branchLineTotalMergeBase: mergeBase, signal: controller.signal }) - ).rejects.toMatchObject({ name: 'AbortError' }) - expect(rangedDiffCalls()).toHaveLength(1) - }) -}) - -describe('branch line total merge-base gate', () => { - it('never leaks a flag-shaped merge base into any git argv', async () => { - const { repo } = await createFixtureRepo() - - await getStatus(repo, { branchLineTotalMergeBase: '--upload-pack=/tmp/evil' }) - - for (const args of gitExecCalls) { - expect(args).not.toContain('--upload-pack=/tmp/evil') - } - }) -}) - -describe('branch line total exec budget', () => { - it('shares one ranged diff across status passes the status lease cannot merge', async () => { - const { repo, mergeBase } = await createFixtureRepo() - // Different limits require separate status leases; hold the diff until both join its shared lease. - execHooks.beforeExec = async (args) => { - if (args.includes('--numstat') && args.at(-1) === '--') { - await waitForCoalescerJoins(2) - } - } - - const [first, second] = await Promise.all([ - getStatus(repo, { branchLineTotalMergeBase: mergeBase, limit: 0 }), - getStatus(repo, { branchLineTotalMergeBase: mergeBase, limit: 4096 }) - ]) - - expect(first.branchLineTotal).toEqual({ - added: 1, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - expect(second.branchLineTotal).toEqual(first.branchLineTotal) - expect(gitExecCalls.filter((args) => args.includes('status'))).toHaveLength(2) - expect(rangedDiffCalls()).toHaveLength(1) - }) - - it('recomputes rather than reusing a total measured against another merge base', async () => { - const { repo, mergeBase } = await createFixtureRepo() - git(repo, ['add', '-A']) - git(repo, ['commit', '-q', '-m', 'second']) - const laterMergeBase = git(repo, ['rev-parse', 'HEAD']) - - await getStatus(repo, { branchLineTotalMergeBase: mergeBase, reuseLineStats: true }) - gitExecCalls.length = 0 - invalidateGitBranchLineTotalInFlight() - const result = await getStatus(repo, { - branchLineTotalMergeBase: laterMergeBase, - reuseLineStats: true - }) - - expect(result.branchLineTotal).toEqual({ - added: 0, - removed: 0, - mergeBase: laterMergeBase, - test: NO_LINES, - generated: NO_LINES - }) - expect(rangedDiffCalls()).toHaveLength(1) - }) -}) diff --git a/src/main/git/source-control/status-branch-line-total-real-git.test.ts b/src/main/git/source-control/status-branch-line-total-real-git.test.ts deleted file mode 100644 index 464a5be1fb1..00000000000 --- a/src/main/git/source-control/status-branch-line-total-real-git.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import * as path from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total' -import { getStatus } from './status-read' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' - -const tempRoots: string[] = [] - -function git(repo: string, args: string[]): string { - return execFileSync('git', args, { - cwd: repo, - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'pipe'] - }).trim() -} - -async function createFixtureRepo(): Promise { - const root = await mkdtemp(path.join(tmpdir(), 'orca-branch-line-total-')) - tempRoots.push(root) - const repo = path.join(root, 'repo') - execFileSync('git', ['init', '-q', repo]) - git(repo, ['config', 'user.email', 'test@example.com']) - git(repo, ['config', 'user.name', 'Test User']) - git(repo, ['config', 'commit.gpgSign', 'false']) - return repo -} - -async function write(repo: string, relativePath: string, contents: string | Buffer): Promise { - const target = path.join(repo, relativePath) - await mkdir(path.dirname(target), { recursive: true }) - await writeFile(target, contents) -} - -function commitAll(repo: string, message: string): string { - git(repo, ['add', '-A']) - git(repo, ['commit', '-q', '-m', message]) - return git(repo, ['rev-parse', 'HEAD']) -} - -const NO_LINES = { added: 0, removed: 0 } - -function rangedDiffTotal(repo: string, mergeBase: string): { added: number; removed: number } { - let added = 0 - let removed = 0 - for (const line of git(repo, ['diff', '--numstat', '-M', mergeBase, '--']).split(/\r?\n/)) { - if (!line) { - continue - } - const [rawAdded, rawRemoved] = line.split('\t') - added += rawAdded === '-' ? 0 : Number.parseInt(rawAdded ?? '0', 10) - removed += rawRemoved === '-' ? 0 : Number.parseInt(rawRemoved ?? '0', 10) - } - return { added, removed } -} - -beforeEach(() => { - invalidateGitReadCaches() - invalidateGitBranchLineTotalInFlight() -}) - -afterEach(async () => { - invalidateGitReadCaches() - invalidateGitBranchLineTotalInFlight() - await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('branch line total against a real repository', () => { - it('measures a partially staged line once, not once per status area', async () => { - const repo = await createFixtureRepo() - await write(repo, 'f.txt', 'line1\n') - const mergeBase = commitAll(repo, 'base') - // Per-area counts sum to +2/-1 here, while the merge-base diff contains just +1/-0. - await write(repo, 'f.txt', 'line1\nfoo\n') - git(repo, ['add', 'f.txt']) - await write(repo, 'f.txt', 'line1\nbar\n') - - const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - - expect(rangedDiffTotal(repo, mergeBase)).toEqual({ added: 1, removed: 0 }) - expect(result.branchLineTotal).toEqual({ - added: 1, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - expect(result.entries.map((entry) => [entry.area, entry.added, entry.removed])).toEqual([ - ['staged', 1, 0], - ['unstaged', 1, 1] - ]) - }) - - it('keeps the total across a commit and updates it on the next status call after an edit', async () => { - const repo = await createFixtureRepo() - await write(repo, 'f.txt', 'a\n') - const mergeBase = commitAll(repo, 'base') - await write(repo, 'f.txt', 'a\nb\nc\n') - - const beforeCommit = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - expect(beforeCommit.branchLineTotal).toEqual({ - added: 2, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - - commitAll(repo, 'commit the edit') - const afterCommit = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - expect(afterCommit.branchLineTotal).toEqual({ - added: 2, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - - await write(repo, 'f.txt', 'a\nb\nc\nd\n') - const afterSecondEdit = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - expect(afterSecondEdit.branchLineTotal).toEqual({ - added: 3, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - }) - - it('omits the total when a deleted base file is recreated as untracked', async () => { - const repo = await createFixtureRepo() - await write(repo, 'gone.txt', 'a\nb\nc\n') - const mergeBase = commitAll(repo, 'base') - git(repo, ['rm', '-q', 'gone.txt']) - commitAll(repo, 'delete gone.txt') - await write(repo, 'gone.txt', 'n1\nn2\n') - - const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - - expect(result.entries.map((entry) => [entry.area, entry.path])).toEqual([ - ['untracked', 'gone.txt'] - ]) - expect(rangedDiffTotal(repo, mergeBase)).toEqual({ added: 0, removed: 3 }) - expect(result.branchLineTotal).toBeUndefined() - }) -}) diff --git a/src/main/git/source-control/status-branch-line-total-untracked-base.test.ts b/src/main/git/source-control/status-branch-line-total-untracked-base.test.ts deleted file mode 100644 index ea242f4ae88..00000000000 --- a/src/main/git/source-control/status-branch-line-total-untracked-base.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { runProcess } from '@orca/process-host' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { getBranchCompare } from './branch-compare' -import { getStatus } from './status-read' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' - -const roots: string[] = [] - -async function git(repo: string, ...args: string[]): Promise { - const result = await runProcess({ program: 'git', args, cwd: repo }) - if (result.code !== 0) { - throw new Error(result.stderr) - } - return result.stdout.trim() -} - -async function createRepo(): Promise { - const repo = await mkdtemp(join(tmpdir(), 'orca-untracked-base-total-')) - roots.push(repo) - await git(repo, 'init', '-q') - await git(repo, 'config', 'user.email', 'test@example.com') - await git(repo, 'config', 'user.name', 'Test') - await git(repo, 'config', 'commit.gpgSign', 'false') - await git(repo, 'commit', '--allow-empty', '-qm', 'root') - await git(repo, 'branch', 'feature') - await git(repo, 'checkout', '-qb', 'base') - return repo -} - -beforeEach(() => invalidateGitReadCaches()) -afterEach(async () => { - invalidateGitReadCaches() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -it.each(['one\ntwo\n', 'one\nchanged\n'])( - 'withholds a merge-base total for a deleted tracked file recreated as untracked until staged: %j', - async (contents) => { - const repo = await createRepo() - await writeFile(join(repo, 'new.txt'), 'one\ntwo\n') - await git(repo, 'add', 'new.txt') - await git(repo, 'commit', '-qm', 'add upstream file') - await git(repo, 'checkout', '-B', 'feature', 'base') - await git(repo, 'rm', 'new.txt') - await git(repo, 'commit', '-qm', 'delete tracked file on feature') - const compare = await getBranchCompare(repo, 'base') - const comparisonBase = compare.summary.mergeBase - if (!comparisonBase) { - throw new Error('Missing comparison base') - } - const options = { branchLineTotalMergeBase: comparisonBase } - expect((await getStatus(repo, options)).branchLineTotal).toMatchObject({ added: 0, removed: 2 }) - - await writeFile(join(repo, 'new.txt'), contents) - const unavailable = await getStatus(repo, options) - expect(unavailable.branchLineTotal).toBeUndefined() - expect(unavailable.branchLineTotalUnavailable).toBe(comparisonBase) - const reused = await getStatus(repo, { ...options, reuseLineStats: true }) - expect(reused.branchLineTotal).toBeUndefined() - expect(reused.branchLineTotalUnavailable).toBe(comparisonBase) - - await git(repo, 'add', 'new.txt') - invalidateGitReadCaches() - const expected = contents === 'one\ntwo\n' ? 0 : 1 - expect((await getStatus(repo, options)).branchLineTotal).toMatchObject({ - added: expected, - removed: expected - }) - } -) - -it('detects untracked overlaps with the source of a rename, including unusual filenames', async () => { - const repo = await createRepo() - const oldPath = process.platform === 'win32' ? 'old name.txt' : 'old\tname.txt' - await writeFile(join(repo, oldPath), 'one\ntwo\n') - await git(repo, 'add', oldPath) - await git(repo, 'commit', '-qm', 'base file') - const baseOid = await git(repo, 'rev-parse', 'HEAD') - await git(repo, 'checkout', '-B', 'feature', 'base') - await git(repo, 'mv', oldPath, 'renamed.txt') - await git(repo, 'commit', '-qm', 'rename file') - await writeFile(join(repo, oldPath), 'different\n') - const options = { branchLineTotalMergeBase: baseOid } - - const unavailable = await getStatus(repo, options) - expect(unavailable.branchLineTotal).toBeUndefined() - expect(unavailable.branchLineTotalUnavailable).toBe(baseOid) - const reused = await getStatus(repo, { ...options, reuseLineStats: true }) - expect(reused.branchLineTotal).toBeUndefined() - expect(reused.branchLineTotalUnavailable).toBe(baseOid) - await git(repo, 'add', oldPath) - invalidateGitReadCaches() - expect((await getStatus(repo, options)).branchLineTotal).toMatchObject({ added: 3, removed: 2 }) -}) diff --git a/src/main/git/source-control/status-cquoted-paths.test.ts b/src/main/git/source-control/status-cquoted-paths.test.ts deleted file mode 100644 index 55ff7ebe166..00000000000 --- a/src/main/git/source-control/status-cquoted-paths.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import * as path from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { getStatus } from './status-read' -import { stageFile } from './staging' - -const tempRoots: string[] = [] - -async function createRepo(): Promise { - const repo = await mkdtemp(path.join(tmpdir(), 'orca-status-cquoted-')) - tempRoots.push(repo) - execFileSync('git', ['init', '-q'], { cwd: repo }) - execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: repo }) - execFileSync('git', ['config', 'user.name', 'Test User'], { cwd: repo }) - return repo -} - -function gitNames(repo: string, args: string[]): string[] { - const stdout = execFileSync('git', args, { cwd: repo, encoding: 'utf8' }) - return stdout.split('\0').filter(Boolean) -} - -afterEach(async () => { - await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('git status C-quoted paths', () => { - it('returns the real path for untracked UTF-8 filenames', async () => { - const repo = await createRepo() - const filePath = '日本語-file.txt' - await writeFile(path.join(repo, filePath), 'new file\n') - - const status = await getStatus(repo) - - expect(status.entries).toEqual([ - { path: filePath, status: 'untracked', area: 'untracked', added: 1 } - ]) - - await stageFile(repo, status.entries[0].path) - - expect(gitNames(repo, ['diff', '--cached', '--name-only', '-z'])).toEqual([filePath]) - }) -}) diff --git a/src/main/git/source-control/status-line-stats-host-paths.test.ts b/src/main/git/source-control/status-line-stats-host-paths.test.ts deleted file mode 100644 index fa775b98f3e..00000000000 --- a/src/main/git/source-control/status-line-stats-host-paths.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -// Untracked line counts use Node I/O, so WSL guest paths need Win32 spelling while host paths stay literal. -import * as path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as FsPromises from 'node:fs/promises' -import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' -import type { GitStatusEntry } from '../../../shared/git/status/git-status-types' -import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total' - -const { lstatPaths, untrackedFiles } = vi.hoisted(() => ({ - lstatPaths: [] as string[], - untrackedFiles: new Map() -})) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - lstat: async (target: string) => { - lstatPaths.push(target) - const contents = untrackedFiles.get(target) - if (contents === undefined) { - throw Object.assign(new Error(`ENOENT: ${target}`), { code: 'ENOENT' }) - } - return { - size: Buffer.byteLength(contents), - // Distinct per read so the stat-keyed untracked cache never serves another case's entry. - mtimeMs: lstatPaths.length, - ctimeMs: lstatPaths.length, - isSymbolicLink: () => false, - isFile: () => true - } - } - } -}) - -vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readNodeFileWithinLimit: async (target: string) => { - const contents = untrackedFiles.get(target) - if (contents === undefined) { - throw Object.assign(new Error(`ENOENT: ${target}`), { code: 'ENOENT' }) - } - return { buffer: Buffer.from(contents) } - } - } -}) - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: gitExecFileAsyncMock, - gitExecFileAsyncBuffer: vi.fn() -})) - -vi.mock('../command-runner/git-environment/git-process-env', async (importOriginal) => ({ - ...(await importOriginal>()), - gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => env -})) - -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => ({ - ...(await importOriginal>()), - gitStreamStdout: vi.fn() -})) - -import { attachLineStats } from './status-line-stats' -import { createBranchLineTotalInput } from './status-branch-line-total-input' - -const GUEST_WORKTREE = '/home/me/repo' -const UNC_WORKTREE = String.raw`\\wsl.localhost\Ubuntu\home\me\repo` -const MERGE_BASE = 'a'.repeat(40) - -function untrackedEntry(entryPath: string): GitStatusEntry { - return { path: entryPath, area: 'untracked', status: 'added' } -} - -describe('untracked line stats on a WSL worktree read by a Windows host', () => { - beforeEach(() => { - lstatPaths.length = 0 - untrackedFiles.clear() - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) - invalidateGitBranchLineTotalInFlight() - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('invalidates an overlapping untracked branch total through the WSL filesystem spelling', async () => { - const target = path.join(UNC_WORKTREE, 'fresh.txt') - untrackedFiles.set(target, 'one\ntwo\n') - gitExecFileAsyncMock.mockResolvedValue({ stdout: '0\t2\tfresh.txt\0', stderr: '' }) - const input = createBranchLineTotalInput( - GUEST_WORKTREE, - [untrackedEntry('fresh.txt')], - { wslDistro: 'Ubuntu', branchLineTotalMergeBase: MERGE_BASE }, - true - ) - - expect(await input?.compute()).toBeNull() - expect(lstatPaths).toEqual([target]) - }) - - it('re-spells the guest form only, leaving every host-openable spelling byte-identical', async () => { - const cases: { worktree: string; expected: string }[] = [ - { worktree: GUEST_WORKTREE, expected: UNC_WORKTREE }, - { worktree: UNC_WORKTREE, expected: UNC_WORKTREE }, - { - worktree: '//wsl.localhost/Ubuntu/home/me/repo', - expected: '//wsl.localhost/Ubuntu/home/me/repo' - }, - { worktree: '//wsl$/Ubuntu/home/me/repo', expected: '//wsl$/Ubuntu/home/me/repo' }, - { worktree: '/home/me/my repo ', expected: '/home/me/my repo ' } - ] - - for (const { worktree, expected } of cases) { - lstatPaths.length = 0 - untrackedFiles.clear() - const target = path.join(expected, 'fresh.txt') - untrackedFiles.set(target, 'one\ntwo\n') - const entries = [untrackedEntry('fresh.txt')] - - await attachLineStats(worktree, entries, { wslDistro: 'Ubuntu' }) - - expect(lstatPaths, worktree).toEqual([target]) - expect(entries[0].added, worktree).toBe(2) - } - }) -}) diff --git a/src/main/git/source-control/status-shared-symlinks.test.ts b/src/main/git/source-control/status-shared-symlinks.test.ts deleted file mode 100644 index 6bf5283d84d..00000000000 --- a/src/main/git/source-control/status-shared-symlinks.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { getStatus } from './status-read' - -// Directory-only ignore rules cannot hide shared symlinks; status must filter configured links. -const git = (args: string[], cwd: string): string => - execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) - -describe('getStatus shared symlink exclusion', () => { - let root: string - let primary: string - let worktree: string - - beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'orca-status-shared-')) - primary = join(root, 'primary') - worktree = join(root, 'worktree') - mkdirSync(primary) - git(['init', '-q', '-b', 'main'], primary) - git(['config', 'user.email', 'test@example.com'], primary) - git(['config', 'user.name', 'Test'], primary) - writeFileSync(join(primary, '.gitignore'), 'node_modules/\n') - writeFileSync(join(primary, 'README.md'), '# tracked\n') - writeFileSync(join(primary, 'OTHER.md'), '# other\n') - symlinkSync('README.md', join(primary, 'tracked-link')) - git(['add', '-A'], primary) - git(['commit', '-qm', 'init'], primary) - mkdirSync(join(primary, 'node_modules')) - git(['worktree', 'add', '-q', worktree, '-b', 'feature'], primary) - symlinkSync(join(primary, 'node_modules'), join(worktree, 'node_modules'), 'dir') - }) - - afterEach(() => { - rmSync(root, { recursive: true, force: true }) - }) - - it('Git reports the shared symlink as untracked, without a trailing slash', async () => { - const status = await getStatus(worktree) - - expect(status.entries).toEqual([ - expect.objectContaining({ path: 'node_modules', area: 'untracked' }) - ]) - }) - - it('drops the shared symlink when it is declared shared', async () => { - const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) - - expect(status.entries).toEqual([]) - }) - - it.each(['./node_modules', 'node_modules/'])( - 'drops the shared symlink when the setting spells it %s', - async (sharedPath) => { - const status = await getStatus(worktree, { sharedLinkPaths: [sharedPath] }) - - expect(status.entries).toEqual([]) - } - ) - - it('still reports a genuine untracked file alongside a shared symlink', async () => { - writeFileSync(join(worktree, 'scratch.txt'), 'unsaved work\n') - - const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) - - expect(status.entries).toEqual([ - expect.objectContaining({ path: 'scratch.txt', area: 'untracked' }) - ]) - }) - - it('still reports a modified tracked file alongside a shared symlink', async () => { - writeFileSync(join(worktree, 'README.md'), '# edited\n') - - const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) - - expect(status.entries).toEqual([ - expect.objectContaining({ path: 'README.md', area: 'unstaged' }) - ]) - }) - - it('keeps a regular directory the user created at a configured shared name', async () => { - mkdirSync(join(worktree, 'vendor')) - writeFileSync(join(worktree, 'vendor', 'real.txt'), 'user work\n') - - const status = await getStatus(worktree, { - sharedLinkPaths: ['node_modules', 'vendor'] - }) - - expect(status.entries).toEqual([ - expect.objectContaining({ path: 'vendor/real.txt', area: 'untracked' }) - ]) - }) - - it('keeps a regular file the user created at a configured shared name', async () => { - writeFileSync(join(worktree, 'notes'), 'user work\n') - - const status = await getStatus(worktree, { - sharedLinkPaths: ['node_modules', 'notes'] - }) - - expect(status.entries).toEqual([expect.objectContaining({ path: 'notes', area: 'untracked' })]) - }) - - it('keeps a modified tracked symlink at a declared shared path', async () => { - unlinkSync(join(worktree, 'tracked-link')) - symlinkSync('OTHER.md', join(worktree, 'tracked-link')) - - const status = await getStatus(worktree, { - sharedLinkPaths: ['node_modules', 'tracked-link'] - }) - - expect(status.entries).toEqual([ - expect.objectContaining({ path: 'tracked-link', area: 'unstaged' }) - ]) - }) - - it('drops shared symlinks whose names have a space or non-ASCII characters', async () => { - const names = ['my shared dir', 'ライブラリ'] - for (const name of names) { - symlinkSync(join(primary, 'node_modules'), join(worktree, name), 'dir') - } - - const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules', ...names] }) - - expect(status.entries).toEqual([]) - }) - - it('keeps a symlink at a path that was never declared shared', async () => { - symlinkSync(join(primary, 'node_modules'), join(worktree, 'vendor'), 'dir') - - const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) - - expect(status.entries).toEqual([expect.objectContaining({ path: 'vendor', area: 'untracked' })]) - }) -}) diff --git a/src/main/git/source-control/status-submodule.test.ts b/src/main/git/source-control/status-submodule.test.ts deleted file mode 100644 index fa2049f73c0..00000000000 --- a/src/main/git/source-control/status-submodule.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import type * as GitExecFileModule from '../command-runner/git-exec-file' -import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-environment/git-process-env' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' -import path from 'node:path' -import { - createBoundedFileReaderModuleMock, - createFsPromisesModuleMock, - createGitExecFileModuleMock, - createGitStreamStdoutModuleMock, - createGitProcessEnvModuleMock -} from './status-test-harness' - -const { - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock, - lstatMock, - realpathMock, - readFileMock, - statMock, - rmMock, - existsSyncMock -} = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - gitExecFileAsyncBufferMock: vi.fn(), - gitStreamOptionsMock: vi.fn(), - lstatMock: vi.fn(), - realpathMock: vi.fn(), - readFileMock: vi.fn(), - statMock: vi.fn(), - rmMock: vi.fn(), - existsSyncMock: vi.fn() -})) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ...createGitExecFileModuleMock({ gitExecFileAsyncMock, gitExecFileAsyncBufferMock }) -})) - -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => ({ - ...(await importOriginal()), - ...createGitStreamStdoutModuleMock({ gitExecFileAsyncMock, gitStreamOptionsMock }) -})) - -vi.mock('../command-runner/git-environment/git-process-env', async (importOriginal) => ({ - ...(await importOriginal()), - ...createGitProcessEnvModuleMock() -})) - -vi.mock('fs/promises', () => - createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) -) - -vi.mock('fs', () => ({ - existsSync: existsSyncMock -})) - -vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => - createBoundedFileReaderModuleMock(await importOriginal(), { - readFileMock, - statMock - }) -) -import { clearSubmodulePathsCacheForTests } from './submodule-paths' -import { getDiff } from './file-diff' - -describe('submodule diff routing', () => { - const OLD_OID = 'a'.repeat(40) - const NEW_OID = 'b'.repeat(40) - const PARENT = path.resolve('/repo-sm') - - beforeEach(() => { - clearSubmodulePathsCacheForTests() - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncBufferMock.mockReset() - lstatMock.mockReset() - readFileMock.mockReset() - statMock.mockReset() - existsSyncMock.mockReset() - statMock.mockResolvedValue({ isFile: () => true, size: 12 }) - gitExecFileAsyncMock.mockImplementation((args: string[], options?: { cwd?: string }) => { - if (args[0] === 'config' && args.includes('.gitmodules')) { - // Declare the submodule only in its parent so recursion terminates. - return Promise.resolve({ - stdout: options?.cwd === PARENT ? 'submodule.flutter_mine.path\nflutter_mine\0' : '' - }) - } - if (args[0] === 'ls-files') { - return Promise.resolve({ stdout: `160000 ${OLD_OID} 0\tflutter_mine\n` }) - } - if (args[0] === 'ls-tree') { - return Promise.resolve({ stdout: `160000 commit ${OLD_OID}\tflutter_mine\n` }) - } - if (args[0] === 'rev-parse') { - return Promise.resolve({ stdout: `${NEW_OID}\n` }) - } - return Promise.resolve({ stdout: '' }) - }) - }) - - it('rejects inner submodule diffs whose .gitmodules path escapes the worktree', async () => { - gitExecFileAsyncMock.mockImplementation((args: string[], options?: { cwd?: string }) => { - if (args[0] === 'config' && args.includes('.gitmodules')) { - return Promise.resolve({ - stdout: options?.cwd === PARENT ? 'submodule.evil.path\n../evil\0' : '' - }) - } - return Promise.resolve({ stdout: '' }) - }) - - await expect(getDiff(PARENT, '../evil/secret.txt', false)).rejects.toThrow('Access denied') - }) - - it('rejects gitlink pointer diffs whose .gitmodules path escapes the worktree', async () => { - gitExecFileAsyncMock.mockImplementation((args: string[], options?: { cwd?: string }) => { - if (args[0] === 'config' && args.includes('.gitmodules')) { - return Promise.resolve({ - stdout: options?.cwd === PARENT ? 'submodule.evil.path\n../evil\0' : '' - }) - } - return Promise.resolve({ stdout: '' }) - }) - - await expect(getDiff(PARENT, '../evil', false)).rejects.toThrow('Access denied') - }) -}) diff --git a/src/main/git/source-control/status-upstream-ref.test.ts b/src/main/git/source-control/status-upstream-ref.test.ts deleted file mode 100644 index 85071b37cc0..00000000000 --- a/src/main/git/source-control/status-upstream-ref.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { resolveGitStatusUpstreamRef } from './status-upstream-ref' - -const signal = (): AbortSignal => new AbortController().signal - -describe('resolveGitStatusUpstreamRef', () => { - it('preserves the exact namespace for a slash-containing remote name', async () => { - const execGit = vi.fn().mockResolvedValue({ - stdout: - 'refs/heads/feature/main\0refs/remotes/team/fork/feature/main\0team/fork/feature/main\n' - }) - - await expect( - resolveGitStatusUpstreamRef( - execGit, - '/repo', - 'refs/heads/feature/main', - 'team/fork/feature/main', - signal() - ) - ).resolves.toBe('refs/remotes/team/fork/feature/main') - expect(execGit).toHaveBeenCalledWith( - [ - 'for-each-ref', - '--format=%(refname)%00%(upstream)%00%(upstream:short)', - '--count=1', - 'refs/heads/feature/main' - ], - '/repo', - expect.any(AbortSignal) - ) - }) - - it('returns a slash-named local upstream for the binding validator to reject', async () => { - const execGit = vi.fn().mockResolvedValue({ - stdout: 'refs/heads/feature/topic\0refs/heads/feature/base\0feature/base\n' - }) - - await expect( - resolveGitStatusUpstreamRef( - execGit, - '/repo', - 'refs/heads/feature/topic', - 'feature/base', - signal() - ) - ).resolves.toBe('refs/heads/feature/base') - }) - - it('resolves an accepted effective upstream override explicitly', async () => { - const execGit = vi - .fn() - .mockResolvedValueOnce({ - stdout: 'refs/heads/feature/prompts\0refs/remotes/origin/main\0origin/main\n' - }) - .mockResolvedValueOnce({ - stdout: '--end-of-options\nrefs/remotes/origin/feature/prompts\n' - }) - - await expect( - resolveGitStatusUpstreamRef( - execGit, - '/repo', - 'refs/heads/feature/prompts', - 'origin/feature/prompts', - signal() - ) - ).resolves.toBe('refs/remotes/origin/feature/prompts') - expect(execGit).toHaveBeenNthCalledWith( - 2, - ['rev-parse', '--symbolic-full-name', '--end-of-options', 'origin/feature/prompts'], - '/repo', - expect.any(AbortSignal) - ) - }) - - it('fails safe when an effective override is ambiguous', async () => { - const execGit = vi - .fn() - .mockResolvedValueOnce({ - stdout: 'refs/heads/feature/main\0refs/remotes/origin/main\0origin/main\n' - }) - .mockResolvedValueOnce({ - stdout: 'refs/heads/origin/feature/main\nrefs/remotes/origin/feature/main\n' - }) - - await expect( - resolveGitStatusUpstreamRef( - execGit, - '/repo', - 'refs/heads/feature/main', - 'origin/feature/main', - signal() - ) - ).resolves.toBeUndefined() - }) -}) diff --git a/src/main/git/source-control/get-status-options.ts b/src/main/git/source-control/status/get-status-options.ts similarity index 87% rename from src/main/git/source-control/get-status-options.ts rename to src/main/git/source-control/status/get-status-options.ts index 1e8287e7895..a781c7694e8 100644 --- a/src/main/git/source-control/get-status-options.ts +++ b/src/main/git/source-control/status/get-status-options.ts @@ -1,4 +1,4 @@ -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' export type GetStatusOptions = GitRuntimeOptions & { includeIgnored?: boolean diff --git a/src/main/git/source-control/status/porcelain-v1-records.test.ts b/src/main/git/source-control/status/porcelain-v1-records.test.ts new file mode 100644 index 00000000000..f0d1cf82468 --- /dev/null +++ b/src/main/git/source-control/status/porcelain-v1-records.test.ts @@ -0,0 +1,45 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { parsePorcelainV1Records } from './porcelain-v1-records' + +const tempRoots: string[] = [] + +const git = (args: string[], cwd: string): string => + execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + +function createRepo(): string { + const repo = mkdtempSync(join(tmpdir(), 'orca-porcelain-v1-')) + tempRoots.push(repo) + git(['init', '-q', '-b', 'main'], repo) + git(['config', 'user.email', 'test@example.com'], repo) + git(['config', 'user.name', 'Test'], repo) + return repo +} + +afterEach(() => { + for (const root of tempRoots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +describe('parsePorcelainV1Records', () => { + it('reports a rename alongside a later untracked entry', () => { + const repo = createRepo() + writeFileSync(join(repo, 'original.txt'), 'content\n') + git(['add', '-A'], repo) + git(['commit', '-qm', 'init'], repo) + git(['mv', 'original.txt', 'renamed.txt'], repo) + mkdirSync(join(repo, 'node_modules')) + writeFileSync(join(repo, 'node_modules', 'pkg.js'), 'x') + + const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) + + expect(records).toEqual([ + { xy: 'R ', path: 'renamed.txt' }, + { xy: '??', path: 'node_modules/' } + ]) + }) +}) diff --git a/src/main/git/source-control/porcelain-v1-records.ts b/src/main/git/source-control/status/porcelain-v1-records.ts similarity index 100% rename from src/main/git/source-control/porcelain-v1-records.ts rename to src/main/git/source-control/status/porcelain-v1-records.ts diff --git a/src/main/git/source-control/status/status-branch-line-total-exec-contract.test.ts b/src/main/git/source-control/status/status-branch-line-total-exec-contract.test.ts new file mode 100644 index 00000000000..4811d84928f --- /dev/null +++ b/src/main/git/source-control/status/status-branch-line-total-exec-contract.test.ts @@ -0,0 +1,73 @@ +import { execFileSync } from 'node:child_process' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import * as path from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { invalidateGitBranchLineTotalInFlight } from '../../../../shared/git/status/git-branch-line-total' + +import { clearEffectiveUpstreamStatusCacheForTests } from '../upstream/effective-upstream-status-cache' +import { clearSubmodulePathsCacheForTests } from '../submodules/submodule-paths' +import { getStatus } from './status-read' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' + +const tempRoots: string[] = [] + +function git(repo: string, args: string[]): string { + return execFileSync('git', args, { + cwd: repo, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }).trim() +} + +async function createFixtureRepo(): Promise<{ repo: string; mergeBase: string }> { + const root = await mkdtemp(path.join(tmpdir(), 'orca-branch-line-total-exec-')) + tempRoots.push(root) + const repo = path.join(root, 'repo') + execFileSync('git', ['init', '-q', repo]) + git(repo, ['config', 'user.email', 'test@example.com']) + git(repo, ['config', 'user.name', 'Test User']) + git(repo, ['config', 'commit.gpgSign', 'false']) + await write(repo, 'f.txt', 'a\nb\n') + git(repo, ['add', '-A']) + git(repo, ['commit', '-q', '-m', 'base']) + await write(repo, 'f.txt', 'a\nb\nc\n') + return { repo, mergeBase: git(repo, ['rev-parse', 'HEAD']) } +} + +async function write(repo: string, relativePath: string, contents: string): Promise { + const target = path.join(repo, relativePath) + await mkdir(path.dirname(target), { recursive: true }) + await writeFile(target, contents) +} + +function resetGitReadCaches(): void { + clearEffectiveUpstreamStatusCacheForTests() + clearSubmodulePathsCacheForTests() + invalidateGitReadCaches() + invalidateGitBranchLineTotalInFlight() +} + +beforeEach(() => { + resetGitReadCaches() +}) + +afterEach(async () => { + resetGitReadCaches() + await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe('branch line total completeness', () => { + it('omits the total when the status listing hit its limit', async () => { + const { repo, mergeBase } = await createFixtureRepo() + await write(repo, 'u1.txt', 'a\n') + await write(repo, 'u2.txt', 'b\n') + await write(repo, 'u3.txt', 'c\n') + + const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase, limit: 1 }) + + expect(result.didHitLimit).toBe(true) + expect(result.branchLineTotal).toBeUndefined() + expect(result.branchLineTotalUnavailable).toBeUndefined() + }) +}) diff --git a/src/main/git/source-control/status-branch-line-total-input.ts b/src/main/git/source-control/status/status-branch-line-total-input.ts similarity index 85% rename from src/main/git/source-control/status-branch-line-total-input.ts rename to src/main/git/source-control/status/status-branch-line-total-input.ts index d19e5494571..01fb2dcc89c 100644 --- a/src/main/git/source-control/status-branch-line-total-input.ts +++ b/src/main/git/source-control/status/status-branch-line-total-input.ts @@ -1,20 +1,20 @@ import type { GitStatusEntry, GitBranchLineTotal -} from '../../../shared/git/status/git-status-types' +} from '../../../../shared/git/status/git-status-types' import { computeGitBranchLineTotal, readGitBranchLineTotalMergeBaseParam, GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS -} from '../../../shared/git/status/git-branch-line-total' +} from '../../../../shared/git/status/git-branch-line-total' import { type GitRuntimeOptions, gitReadOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { resolveWorktreeFilesystemPath } from './worktree-filesystem-path' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { resolveWorktreeFilesystemPath } from '../worktree-filesystem-path' import type { GetStatusOptions } from './get-status-options' export function createBranchLineTotalInput( diff --git a/src/main/git/source-control/status/status-branch-line-total-real-git.test.ts b/src/main/git/source-control/status/status-branch-line-total-real-git.test.ts new file mode 100644 index 00000000000..855f4e69e1c --- /dev/null +++ b/src/main/git/source-control/status/status-branch-line-total-real-git.test.ts @@ -0,0 +1,116 @@ +import { execFileSync } from 'node:child_process' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import * as path from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { invalidateGitBranchLineTotalInFlight } from '../../../../shared/git/status/git-branch-line-total' +import { getStatus } from './status-read' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' + +const tempRoots: string[] = [] + +function git(repo: string, args: string[]): string { + return execFileSync('git', args, { + cwd: repo, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }).trim() +} + +async function createFixtureRepo(): Promise { + const root = await mkdtemp(path.join(tmpdir(), 'orca-branch-line-total-')) + tempRoots.push(root) + const repo = path.join(root, 'repo') + execFileSync('git', ['init', '-q', repo]) + git(repo, ['config', 'user.email', 'test@example.com']) + git(repo, ['config', 'user.name', 'Test User']) + git(repo, ['config', 'commit.gpgSign', 'false']) + return repo +} + +async function write(repo: string, relativePath: string, contents: string | Buffer): Promise { + const target = path.join(repo, relativePath) + await mkdir(path.dirname(target), { recursive: true }) + await writeFile(target, contents) +} + +function commitAll(repo: string, message: string): string { + git(repo, ['add', '-A']) + git(repo, ['commit', '-q', '-m', message]) + return git(repo, ['rev-parse', 'HEAD']) +} + +const NO_LINES = { added: 0, removed: 0 } + +beforeEach(() => { + invalidateGitReadCaches() + invalidateGitBranchLineTotalInFlight() +}) + +afterEach(async () => { + invalidateGitReadCaches() + invalidateGitBranchLineTotalInFlight() + await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe('branch line total against a real repository', () => { + it('measures a partially staged line once, not once per status area', async () => { + const repo = await createFixtureRepo() + await write(repo, 'f.txt', 'line1\n') + const mergeBase = commitAll(repo, 'base') + // Per-area counts sum to +2/-1 here, while the merge-base diff contains just +1/-0. + await write(repo, 'f.txt', 'line1\nfoo\n') + git(repo, ['add', 'f.txt']) + await write(repo, 'f.txt', 'line1\nbar\n') + + const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) + + expect(result.branchLineTotal).toEqual({ + added: 1, + removed: 0, + mergeBase, + test: NO_LINES, + generated: NO_LINES + }) + expect(result.entries.map((entry) => [entry.area, entry.added, entry.removed])).toEqual([ + ['staged', 1, 0], + ['unstaged', 1, 1] + ]) + }) + + it('keeps the total across a commit and updates it on the next status call after an edit', async () => { + const repo = await createFixtureRepo() + await write(repo, 'f.txt', 'a\n') + const mergeBase = commitAll(repo, 'base') + await write(repo, 'f.txt', 'a\nb\nc\n') + + const beforeCommit = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) + expect(beforeCommit.branchLineTotal).toEqual({ + added: 2, + removed: 0, + mergeBase, + test: NO_LINES, + generated: NO_LINES + }) + + commitAll(repo, 'commit the edit') + const afterCommit = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) + expect(afterCommit.branchLineTotal).toEqual({ + added: 2, + removed: 0, + mergeBase, + test: NO_LINES, + generated: NO_LINES + }) + + await write(repo, 'f.txt', 'a\nb\nc\nd\n') + const afterSecondEdit = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) + expect(afterSecondEdit.branchLineTotal).toEqual({ + added: 3, + removed: 0, + mergeBase, + test: NO_LINES, + generated: NO_LINES + }) + }) +}) diff --git a/src/main/git/source-control/status/status-branch-line-total-untracked-base.test.ts b/src/main/git/source-control/status/status-branch-line-total-untracked-base.test.ts new file mode 100644 index 00000000000..4d6a32e016b --- /dev/null +++ b/src/main/git/source-control/status/status-branch-line-total-untracked-base.test.ts @@ -0,0 +1,60 @@ +import { runProcess } from '@orca/process-host' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { getStatus } from './status-read' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' + +const roots: string[] = [] + +async function git(repo: string, ...args: string[]): Promise { + const result = await runProcess({ program: 'git', args, cwd: repo }) + if (result.code !== 0) { + throw new Error(result.stderr) + } + return result.stdout.trim() +} + +async function createRepo(): Promise { + const repo = await mkdtemp(join(tmpdir(), 'orca-untracked-base-total-')) + roots.push(repo) + await git(repo, 'init', '-q') + await git(repo, 'config', 'user.email', 'test@example.com') + await git(repo, 'config', 'user.name', 'Test') + await git(repo, 'config', 'commit.gpgSign', 'false') + await git(repo, 'commit', '--allow-empty', '-qm', 'root') + await git(repo, 'branch', 'feature') + await git(repo, 'checkout', '-qb', 'base') + return repo +} + +beforeEach(() => invalidateGitReadCaches()) +afterEach(async () => { + invalidateGitReadCaches() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +it('detects untracked overlaps with the source of a rename, including unusual filenames', async () => { + const repo = await createRepo() + const oldPath = process.platform === 'win32' ? 'old name.txt' : 'old\tname.txt' + await writeFile(join(repo, oldPath), 'one\ntwo\n') + await git(repo, 'add', oldPath) + await git(repo, 'commit', '-qm', 'base file') + const baseOid = await git(repo, 'rev-parse', 'HEAD') + await git(repo, 'checkout', '-B', 'feature', 'base') + await git(repo, 'mv', oldPath, 'renamed.txt') + await git(repo, 'commit', '-qm', 'rename file') + await writeFile(join(repo, oldPath), 'different\n') + const options = { branchLineTotalMergeBase: baseOid } + + const unavailable = await getStatus(repo, options) + expect(unavailable.branchLineTotal).toBeUndefined() + expect(unavailable.branchLineTotalUnavailable).toBe(baseOid) + const reused = await getStatus(repo, { ...options, reuseLineStats: true }) + expect(reused.branchLineTotal).toBeUndefined() + expect(reused.branchLineTotalUnavailable).toBe(baseOid) + await git(repo, 'add', oldPath) + invalidateGitReadCaches() + expect((await getStatus(repo, options)).branchLineTotal).toMatchObject({ added: 3, removed: 2 }) +}) diff --git a/src/main/git/source-control/status-index-lock-wait.ts b/src/main/git/source-control/status/status-index-lock-wait.ts similarity index 89% rename from src/main/git/source-control/status-index-lock-wait.ts rename to src/main/git/source-control/status/status-index-lock-wait.ts index 7f7e52104fa..4a722241f5a 100644 --- a/src/main/git/source-control/status-index-lock-wait.ts +++ b/src/main/git/source-control/status/status-index-lock-wait.ts @@ -1,9 +1,9 @@ import { access, stat } from 'node:fs/promises' import * as path from 'node:path' -import { BoundedMap } from '../../../shared/bounded-map' -import { delayUnlessAborted } from '../../../shared/abort-aware-delay' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { resolveGitDir } from './resolve-git-dir' +import { BoundedMap } from '../../../../shared/bounded-map' +import { delayUnlessAborted } from '../../../../shared/abort-aware-delay' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { resolveGitDir } from '../resolve-git-dir' const INDEX_LOCK_POLL_MS = 50 // Commits and staging release the lock well within this; a crashed Git can leave it forever. diff --git a/src/main/git/source-control/status/status-line-stats-host-paths.test.ts b/src/main/git/source-control/status/status-line-stats-host-paths.test.ts new file mode 100644 index 00000000000..e9be6d37fdd --- /dev/null +++ b/src/main/git/source-control/status/status-line-stats-host-paths.test.ts @@ -0,0 +1,92 @@ +// Untracked line counts use Node I/O, so WSL guest paths need Win32 spelling while host paths stay literal. +import * as path from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as FsPromises from 'node:fs/promises' +import type * as BoundedFileReader from '../../../../shared/file-content/node-bounded-file-reader' +import type { GitStatusEntry } from '../../../../shared/git/status/git-status-types' + +const { lstatPaths, untrackedFiles } = vi.hoisted(() => ({ + lstatPaths: [] as string[], + untrackedFiles: new Map() +})) + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + lstat: async (target: string) => { + lstatPaths.push(target) + const contents = untrackedFiles.get(target) + if (contents === undefined) { + throw Object.assign(new Error(`ENOENT: ${target}`), { code: 'ENOENT' }) + } + return { + size: Buffer.byteLength(contents), + // Distinct per read so the stat-keyed untracked cache never serves another case's entry. + mtimeMs: lstatPaths.length, + ctimeMs: lstatPaths.length, + isSymbolicLink: () => false, + isFile: () => true + } + } + } +}) + +vi.mock('../../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readNodeFileWithinLimit: async (target: string) => { + const contents = untrackedFiles.get(target) + if (contents === undefined) { + throw Object.assign(new Error(`ENOENT: ${target}`), { code: 'ENOENT' }) + } + return { buffer: Buffer.from(contents) } + } + } +}) + +import { attachLineStats } from './status-line-stats' + +const GUEST_WORKTREE = '/home/me/repo' +const UNC_WORKTREE = String.raw`\\wsl.localhost\Ubuntu\home\me\repo` + +function untrackedEntry(entryPath: string): GitStatusEntry { + return { path: entryPath, area: 'untracked', status: 'added' } +} + +describe('untracked line stats on a WSL worktree read by a Windows host', () => { + beforeEach(() => { + lstatPaths.length = 0 + untrackedFiles.clear() + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('re-spells the guest form only, leaving every host-openable spelling byte-identical', async () => { + const cases: { worktree: string; expected: string }[] = [ + { worktree: GUEST_WORKTREE, expected: UNC_WORKTREE }, + { worktree: UNC_WORKTREE, expected: UNC_WORKTREE }, + { + worktree: '//wsl.localhost/Ubuntu/home/me/repo', + expected: '//wsl.localhost/Ubuntu/home/me/repo' + }, + { worktree: '/home/me/my repo ', expected: '/home/me/my repo ' } + ] + + for (const { worktree, expected } of cases) { + lstatPaths.length = 0 + untrackedFiles.clear() + const target = path.join(expected, 'fresh.txt') + untrackedFiles.set(target, 'one\ntwo\n') + const entries = [untrackedEntry('fresh.txt')] + + await attachLineStats(worktree, entries, { wslDistro: 'Ubuntu' }) + + expect(entries[0].added, worktree).toBe(2) + } + }) +}) diff --git a/src/main/git/source-control/status-line-stats-renames-real-git.test.ts b/src/main/git/source-control/status/status-line-stats-renames-real-git.test.ts similarity index 91% rename from src/main/git/source-control/status-line-stats-renames-real-git.test.ts rename to src/main/git/source-control/status/status-line-stats-renames-real-git.test.ts index 1107be7f120..358d77ceac3 100644 --- a/src/main/git/source-control/status-line-stats-renames-real-git.test.ts +++ b/src/main/git/source-control/status/status-line-stats-renames-real-git.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { runProcessSync } from '@orca/process-host' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getStatus } from './status-read' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' let root: string let repo: string @@ -38,8 +38,6 @@ afterEach(async () => { describe.each(['staged', 'unstaged'] as const)('%s rename line counts', (area) => { it.each([ - { diffRenames: 'true', statusRenames: undefined, renamed: true }, - { diffRenames: 'false', statusRenames: undefined, renamed: false }, { diffRenames: 'true', statusRenames: 'false', renamed: false }, { diffRenames: 'false', statusRenames: 'true', renamed: true } ])('matches status with $diffRenames diff / $statusRenames status', async (config) => { diff --git a/src/main/git/source-control/status-line-stats.ts b/src/main/git/source-control/status/status-line-stats.ts similarity index 86% rename from src/main/git/source-control/status-line-stats.ts rename to src/main/git/source-control/status/status-line-stats.ts index dbb9f365e25..23cb1d6edb5 100644 --- a/src/main/git/source-control/status-line-stats.ts +++ b/src/main/git/source-control/status/status-line-stats.ts @@ -1,23 +1,23 @@ -import type { GitStatusEntry } from '../../../shared/git/status/git-status-types' -import { collectGitStatusLineStatInputs } from '../../../shared/git/status/git-status-line-stat-inputs' +import type { GitStatusEntry } from '../../../../shared/git/status/git-status-types' +import { collectGitStatusLineStatInputs } from '../../../../shared/git/status/git-status-line-stat-inputs' import { applyLineStats, collectUntrackedAdditions, parseNumstat, type GitLineStats -} from '../../../shared/git/status/git-uncommitted-line-stats' +} from '../../../../shared/git/status/git-uncommitted-line-stats' import { type GitRuntimeOptions, gitReadOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { resolveWorktreeFilesystemPath } from './worktree-filesystem-path' -import { settledNumstatCache } from './git-read-cache-invalidation' -import { readStampedGitConfig, type StampedGitConfig } from './stamped-git-config' -import { addGitattributesStampPaths } from './gitattributes-stamp-paths' -import { readWorktreePathsDiffStamp } from './worktree-diff-stamp' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { resolveWorktreeFilesystemPath } from '../worktree-filesystem-path' +import { settledNumstatCache } from '../git-read-cache-invalidation' +import { readStampedGitConfig, type StampedGitConfig } from '../input-stamps/stamped-git-config' +import { addGitattributesStampPaths } from '../input-stamps/gitattributes-stamp-paths' +import { readWorktreePathsDiffStamp } from '../input-stamps/worktree-diff-stamp' async function runNumstat( worktreePath: string, diff --git a/src/main/git/source-control/status-porcelain-stream.ts b/src/main/git/source-control/status/status-porcelain-stream.ts similarity index 93% rename from src/main/git/source-control/status-porcelain-stream.ts rename to src/main/git/source-control/status/status-porcelain-stream.ts index 0ad274bcb35..5b9821a299c 100644 --- a/src/main/git/source-control/status-porcelain-stream.ts +++ b/src/main/git/source-control/status/status-porcelain-stream.ts @@ -1,7 +1,7 @@ -import { BoundedMap } from '../../../shared/bounded-map' -import { StatusPorcelainParser } from '../../../shared/git/status/git-status-porcelain-parser' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { gitStreamStdout } from '../command-runner/git-stream-stdout' +import { BoundedMap } from '../../../../shared/bounded-map' +import { StatusPorcelainParser } from '../../../../shared/git/status/git-status-porcelain-parser' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { gitStreamStdout } from '../../command-runner/git-stream-stdout' import type { GetStatusOptions } from './get-status-options' import { listUntrackedDirectoryFiles, readUntrackedScan } from './status-untracked-directories' diff --git a/src/main/git/source-control/status-read-failure-real-git.test.ts b/src/main/git/source-control/status/status-read-failure-real-git.test.ts similarity index 96% rename from src/main/git/source-control/status-read-failure-real-git.test.ts rename to src/main/git/source-control/status/status-read-failure-real-git.test.ts index f313c354d6e..7420477cbc2 100644 --- a/src/main/git/source-control/status-read-failure-real-git.test.ts +++ b/src/main/git/source-control/status/status-read-failure-real-git.test.ts @@ -4,7 +4,7 @@ import * as path from 'node:path' import { runProcessSync } from '@orca/process-host' import { afterEach, expect, it } from 'vitest' import { getStatus } from './status-read' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' let root: string | undefined diff --git a/src/main/git/source-control/status-read.ts b/src/main/git/source-control/status/status-read.ts similarity index 85% rename from src/main/git/source-control/status-read.ts rename to src/main/git/source-control/status/status-read.ts index fcfa3aa863d..243e158d761 100644 --- a/src/main/git/source-control/status-read.ts +++ b/src/main/git/source-control/status/status-read.ts @@ -3,39 +3,40 @@ import type { GitStatusEntry, GitStatusResult, GitUpstreamStatus -} from '../../../shared/git/status/git-status-types' -import { resolveGitStatusLimit } from '../../../shared/git/status/git-status-limit' -import { stableInFlightKey } from '../../../shared/in-flight-promise-dedupe' -import { beginGitStatusLineStatsCacheWrite } from '../../../shared/git/status/git-status-line-stats-write-token' +} from '../../../../shared/git/status/git-status-types' +import { resolveGitStatusLimit } from '../../../../shared/git/status/git-status-limit' +import { stableInFlightKey } from '../../../../shared/in-flight-promise-dedupe' +import { beginGitStatusLineStatsCacheWrite } from '../../../../shared/git/status/git-status-line-stats-write-token' import { clearGitStatusLineStatsCacheKey, reuseOrRecomputeGitStatusLineStats -} from '../../../shared/git/status/git-status-line-stats-cache' -import { resolveWorktreeHostPath } from '../../../shared/git/metadata/git-metadata-path' -import { readGitCommandFailureStderr } from '../../../shared/git/commands/git-command-failure-text' +} from '../../../../shared/git/status/git-status-line-stats-cache' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import { readGitCommandFailureStderr } from '../../../../shared/git/commands/git-command-failure-text' import { readStatusPorcelain } from './status-porcelain-stream' import { waitForIndexLockRelease } from './status-index-lock-wait' import { findExistingWorktreeSymlinkPaths, getSafeRelativePath -} from '../worktrees/content-paths/worktree-symlink-detection' +} from '../../worktrees/content-paths/worktree-symlink-detection' import type { GetStatusOptions } from './get-status-options' -import { statusReadLeaseOwner } from './git-read-cache-invalidation' -import { detectConflictOperation } from './git-conflict-operation' -import { parseUnmergedEntry } from '../../../shared/git/status/git-status-conflict-entries' -import { getEffectiveUpstreamStatusCacheKey } from './effective-upstream-status-cache' +import { statusReadLeaseOwner } from '../git-read-cache-invalidation' +import { detectConflictOperation } from '../mutations/git-conflict-operation' +import { parseUnmergedEntry } from '../../../../shared/git/status/git-status-conflict-entries' +import { getEffectiveUpstreamStatusCacheKey } from '../upstream/effective-upstream-status-cache' import { getShortBranchName, readOrProbeEffectiveUpstreamStatus, shouldProbeEffectiveUpstreamStatus -} from './effective-upstream-status-probe' +} from '../upstream/effective-upstream-status-probe' import { attachLineStats } from './status-line-stats' import { createBranchLineTotalInput, getStatusLineStatsCacheKey } from './status-branch-line-total-input' -import { reconcileDriveCheckoutSuspects } from './drive-checkout-suspect-status' -import { markRecursiveSubmoduleRestores } from './submodule-restore-recurse' +import { reconcileDriveCheckoutSuspects } from '../drive-checkout/drive-checkout-suspect-status' +import { markRecursiveSubmoduleRestores } from '../submodules/submodule-restore-recurse' +import { withRepositoryGitCause } from '../../repository-git-cause' export async function getStatus( worktreePath: string, @@ -44,7 +45,12 @@ export async function getStatus( // Reads preserve diff caches; mutations invalidate them and settled entries also validate input stamps. const cacheKey = getStatusReadKey(worktreePath, options) return statusReadLeaseOwner.lease(cacheKey, options.signal, (sharedSignal) => - runGetStatus(worktreePath, { ...options, signal: sharedSignal }) + withRepositoryGitCause( + worktreePath, + options, + { family: 'status', reason: 'status-read', cache: 'miss' }, + () => runGetStatus(worktreePath, { ...options, signal: sharedSignal }) + ) ) } diff --git a/src/main/git/source-control/status/status-shared-symlinks.test.ts b/src/main/git/source-control/status/status-shared-symlinks.test.ts new file mode 100644 index 00000000000..14644afadd8 --- /dev/null +++ b/src/main/git/source-control/status/status-shared-symlinks.test.ts @@ -0,0 +1,80 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { getStatus } from './status-read' + +// Directory-only ignore rules cannot hide shared symlinks; status must filter configured links. +const git = (args: string[], cwd: string): string => + execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + +describe('getStatus shared symlink exclusion', () => { + let root: string + let primary: string + let worktree: string + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-status-shared-')) + primary = join(root, 'primary') + worktree = join(root, 'worktree') + mkdirSync(primary) + git(['init', '-q', '-b', 'main'], primary) + git(['config', 'user.email', 'test@example.com'], primary) + git(['config', 'user.name', 'Test'], primary) + writeFileSync(join(primary, '.gitignore'), 'node_modules/\n') + writeFileSync(join(primary, 'README.md'), '# tracked\n') + writeFileSync(join(primary, 'OTHER.md'), '# other\n') + symlinkSync('README.md', join(primary, 'tracked-link')) + git(['add', '-A'], primary) + git(['commit', '-qm', 'init'], primary) + mkdirSync(join(primary, 'node_modules')) + git(['worktree', 'add', '-q', worktree, '-b', 'feature'], primary) + symlinkSync(join(primary, 'node_modules'), join(worktree, 'node_modules'), 'dir') + }) + + afterEach(() => { + rmSync(root, { recursive: true, force: true }) + }) + + it('still reports a genuine untracked file alongside a shared symlink', async () => { + writeFileSync(join(worktree, 'scratch.txt'), 'unsaved work\n') + + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'scratch.txt', area: 'untracked' }) + ]) + }) + + it('keeps a regular file the user created at a configured shared name', async () => { + writeFileSync(join(worktree, 'notes'), 'user work\n') + + const status = await getStatus(worktree, { + sharedLinkPaths: ['node_modules', 'notes'] + }) + + expect(status.entries).toEqual([expect.objectContaining({ path: 'notes', area: 'untracked' })]) + }) + + it('keeps a modified tracked symlink at a declared shared path', async () => { + unlinkSync(join(worktree, 'tracked-link')) + symlinkSync('OTHER.md', join(worktree, 'tracked-link')) + + const status = await getStatus(worktree, { + sharedLinkPaths: ['node_modules', 'tracked-link'] + }) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'tracked-link', area: 'unstaged' }) + ]) + }) + + it('keeps a symlink at a path that was never declared shared', async () => { + symlinkSync(join(primary, 'node_modules'), join(worktree, 'vendor'), 'dir') + + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) + + expect(status.entries).toEqual([expect.objectContaining({ path: 'vendor', area: 'untracked' })]) + }) +}) diff --git a/src/main/git/source-control/status-untracked-directories.ts b/src/main/git/source-control/status/status-untracked-directories.ts similarity index 94% rename from src/main/git/source-control/status-untracked-directories.ts rename to src/main/git/source-control/status/status-untracked-directories.ts index 18681b5a25b..bbaf6dc706d 100644 --- a/src/main/git/source-control/status-untracked-directories.ts +++ b/src/main/git/source-control/status/status-untracked-directories.ts @@ -1,8 +1,8 @@ -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { gitStreamStdout } from '../command-runner/git-stream-stdout' -import { readStampedGitConfig } from './stamped-git-config' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { gitStreamStdout } from '../../command-runner/git-stream-stdout' +import { readStampedGitConfig } from '../input-stamps/stamped-git-config' import type { GetStatusOptions } from './get-status-options' -import { bulkPathspecCommands } from './git-pathspec' +import { bulkPathspecCommands } from '../git-pathspec' /** * How to get every untracked file: `expand` lists configured-mode `? dir/` rows, `configured-all` needs nothing, diff --git a/src/main/git/source-control/submodules/status-submodule.test.ts b/src/main/git/source-control/submodules/status-submodule.test.ts new file mode 100644 index 00000000000..47d29365545 --- /dev/null +++ b/src/main/git/source-control/submodules/status-submodule.test.ts @@ -0,0 +1,95 @@ +import type * as GitExecFileModule from '../../command-runner/git-exec-file' +import type * as GitStreamStdoutModule from '../../command-runner/git-stream-stdout' +import type * as GitProcessEnvModule from '../../command-runner/git-environment/git-process-env' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as BoundedFileReader from '../../../../shared/file-content/node-bounded-file-reader' +import path from 'node:path' +import { + createBoundedFileReaderModuleMock, + createFsPromisesModuleMock, + createGitExecFileModuleMock, + createGitStreamStdoutModuleMock, + createGitProcessEnvModuleMock +} from '../diffs/status-test-harness' + +const { + gitExecFileAsyncMock, + gitExecFileAsyncBufferMock, + gitStreamOptionsMock, + lstatMock, + realpathMock, + readFileMock, + statMock, + rmMock, + existsSyncMock +} = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn(), + gitExecFileAsyncBufferMock: vi.fn(), + gitStreamOptionsMock: vi.fn(), + lstatMock: vi.fn(), + realpathMock: vi.fn(), + readFileMock: vi.fn(), + statMock: vi.fn(), + rmMock: vi.fn(), + existsSyncMock: vi.fn() +})) + +vi.mock('../../command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitExecFileModuleMock({ gitExecFileAsyncMock, gitExecFileAsyncBufferMock }) +})) + +vi.mock('../../command-runner/git-stream-stdout', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitStreamStdoutModuleMock({ gitExecFileAsyncMock, gitStreamOptionsMock }) +})) + +vi.mock('../../command-runner/git-environment/git-process-env', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitProcessEnvModuleMock() +})) + +vi.mock('fs/promises', () => + createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) +) + +vi.mock('fs', () => ({ + existsSync: existsSyncMock +})) + +vi.mock('../../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => + createBoundedFileReaderModuleMock(await importOriginal(), { + readFileMock, + statMock + }) +) +import { clearSubmodulePathsCacheForTests } from './submodule-paths' +import { getDiff } from '../diffs/file-diff' + +describe('submodule diff routing', () => { + const PARENT = path.resolve('/repo-sm') + + beforeEach(() => { + clearSubmodulePathsCacheForTests() + gitExecFileAsyncMock.mockReset() + gitExecFileAsyncBufferMock.mockReset() + lstatMock.mockReset() + readFileMock.mockReset() + statMock.mockReset() + existsSyncMock.mockReset() + statMock.mockResolvedValue({ isFile: () => true, size: 12 }) + }) + + it('rejects inner submodule diffs whose .gitmodules path escapes the worktree', async () => { + gitExecFileAsyncMock.mockImplementation((args: string[], options?: { cwd?: string }) => { + if (args[0] === 'config' && args.includes('.gitmodules')) { + return Promise.resolve({ + stdout: options?.cwd === PARENT ? 'submodule.evil.path\n../evil\0' : '' + }) + } + return Promise.resolve({ stdout: '' }) + }) + + await expect(getDiff(PARENT, '../evil/secret.txt', false)).rejects.toThrow('Access denied') + }) +}) diff --git a/src/main/git/source-control/submodule-diff.ts b/src/main/git/source-control/submodules/submodule-diff.ts similarity index 91% rename from src/main/git/source-control/submodule-diff.ts rename to src/main/git/source-control/submodules/submodule-diff.ts index c3986eef75f..3e2ab128dac 100644 --- a/src/main/git/source-control/submodule-diff.ts +++ b/src/main/git/source-control/submodules/submodule-diff.ts @@ -1,7 +1,7 @@ -import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { buildDiffResult } from './diff-result' -import { type BlobConversion, blobConversion, readGitBlobAtOidPath } from './git-blob-read' +import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { buildDiffResult } from '../diffs/diff-result' +import { type BlobConversion, blobConversion, readGitBlobAtOidPath } from '../diffs/git-blob-read' import { resolveSubmoduleWorktreePath } from './submodule-paths' import { readGitlinkOidFromIndex, diff --git a/src/main/git/source-control/submodule-gitlink-oid.ts b/src/main/git/source-control/submodules/submodule-gitlink-oid.ts similarity index 84% rename from src/main/git/source-control/submodule-gitlink-oid.ts rename to src/main/git/source-control/submodules/submodule-gitlink-oid.ts index b9272c04bba..25a70710ad2 100644 --- a/src/main/git/source-control/submodule-gitlink-oid.ts +++ b/src/main/git/source-control/submodules/submodule-gitlink-oid.ts @@ -1,10 +1,10 @@ import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { literalPathspec } from './git-pathspec' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { literalPathspec } from '../git-pathspec' export async function readGitlinkOidFromTree( worktreePath: string, diff --git a/src/main/git/source-control/submodule-gitlink-pathspec-real-git.test.ts b/src/main/git/source-control/submodules/submodule-gitlink-pathspec-real-git.test.ts similarity index 98% rename from src/main/git/source-control/submodule-gitlink-pathspec-real-git.test.ts rename to src/main/git/source-control/submodules/submodule-gitlink-pathspec-real-git.test.ts index edbd5460520..0ecf2950474 100644 --- a/src/main/git/source-control/submodule-gitlink-pathspec-real-git.test.ts +++ b/src/main/git/source-control/submodules/submodule-gitlink-pathspec-real-git.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' import { afterEach, describe, expect, it } from 'vitest' -import { getDiff } from './file-diff' +import { getDiff } from '../diffs/file-diff' import { getSubmoduleStatus } from './submodule-status' const directories: string[] = [] diff --git a/src/main/git/source-control/submodule-paths.ts b/src/main/git/source-control/submodules/submodule-paths.ts similarity index 92% rename from src/main/git/source-control/submodule-paths.ts rename to src/main/git/source-control/submodules/submodule-paths.ts index 7a9fc27c153..b4a39cfdb99 100644 --- a/src/main/git/source-control/submodule-paths.ts +++ b/src/main/git/source-control/submodules/submodule-paths.ts @@ -3,11 +3,11 @@ import * as path from 'node:path' import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import { gitRuntimeOptionsKey } from './git-runtime-options-cache-key' -import { iterateNulDelimitedFields } from '../../../shared/nul-delimited-fields' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import { gitRuntimeOptionsKey } from '../git-runtime-options-cache-key' +import { iterateNulDelimitedFields } from '../../../../shared/nul-delimited-fields' const SUBMODULE_PATHS_CACHE_TTL_MS = 5_000 export const MAX_SUBMODULE_PATHS_CACHE_ENTRIES = 512 diff --git a/src/main/git/source-control/submodule-restore-recurse-real-git.test.ts b/src/main/git/source-control/submodules/submodule-restore-recurse-real-git.test.ts similarity index 91% rename from src/main/git/source-control/submodule-restore-recurse-real-git.test.ts rename to src/main/git/source-control/submodules/submodule-restore-recurse-real-git.test.ts index 582c8b0fcdd..19534f1803b 100644 --- a/src/main/git/source-control/submodule-restore-recurse-real-git.test.ts +++ b/src/main/git/source-control/submodules/submodule-restore-recurse-real-git.test.ts @@ -3,9 +3,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' import { afterEach, describe, expect, it, vi } from 'vitest' -import { canDiscardStatusEntry } from '../../../shared/source-control/listing/source-control-entry-actions' -import { discardChanges } from './discard-changes' -import { getStatus } from './status-read' +import { canDiscardStatusEntry } from '../../../../shared/source-control/listing/source-control-entry-actions' +import { discardChanges } from '../mutations/discard-changes' +import { getStatus } from '../status/status-read' const directories: string[] = [] diff --git a/src/main/git/source-control/submodule-restore-recurse.ts b/src/main/git/source-control/submodules/submodule-restore-recurse.ts similarity index 76% rename from src/main/git/source-control/submodule-restore-recurse.ts rename to src/main/git/source-control/submodules/submodule-restore-recurse.ts index 8b449ad0378..767163be0b0 100644 --- a/src/main/git/source-control/submodule-restore-recurse.ts +++ b/src/main/git/source-control/submodules/submodule-restore-recurse.ts @@ -1,11 +1,11 @@ -import type { GitStatusEntry } from '../../../shared/git/status/git-status-types' -import { isWorktreeUndiscardableGitlink } from '../../../shared/source-control/listing/source-control-discard-all-sequence' +import type { GitStatusEntry } from '../../../../shared/git/status/git-status-types' +import { isWorktreeUndiscardableGitlink } from '../../../../shared/source-control/listing/source-control-discard-all-sequence' import { type GitRuntimeOptions, gitReadOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' /** Plain `git restore` recurses into submodules when submodule.recurse is on, so those gitlinks stay discardable. */ export async function markRecursiveSubmoduleRestores( diff --git a/src/main/git/source-control/submodule-status.ts b/src/main/git/source-control/submodules/submodule-status.ts similarity index 84% rename from src/main/git/source-control/submodule-status.ts rename to src/main/git/source-control/submodules/submodule-status.ts index fb6466764b3..9c3809672e1 100644 --- a/src/main/git/source-control/submodule-status.ts +++ b/src/main/git/source-control/submodules/submodule-status.ts @@ -1,18 +1,21 @@ -import type { GitStatusEntry, GitStatusResult } from '../../../shared/git/status/git-status-types' +import type { + GitStatusEntry, + GitStatusResult +} from '../../../../shared/git/status/git-status-types' import { capGitStatusEntries, resolveGitStatusLimit -} from '../../../shared/git/status/git-status-limit' -import { gitChangeListArgs, parseGitChangeList } from '../../../shared/git/diff/git-change-list' +} from '../../../../shared/git/status/git-status-limit' +import { gitChangeListArgs, parseGitChangeList } from '../../../../shared/git/diff/git-change-list' import { type GitRuntimeOptions, gitOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' -import type { GetStatusOptions } from './get-status-options' -import { getStatus } from './status-read' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import type { GetStatusOptions } from '../status/get-status-options' +import { getStatus } from '../status/status-read' import { resolveSubmoduleWorktreePath } from './submodule-paths' import { readGitlinkOidFromIndex, diff --git a/src/main/git/source-control/upstream.test.ts b/src/main/git/source-control/upstream.test.ts deleted file mode 100644 index 25dce884ec9..00000000000 --- a/src/main/git/source-control/upstream.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn() -})) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -import { getUpstreamStatus, invalidateGitUpstreamStatusReads } from './upstream' - -describe('getUpstreamStatus', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - invalidateGitUpstreamStatusReads() - }) - - it('does not hide git failures while checking an explicit publish target', async () => { - gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }).mockRejectedValueOnce( - Object.assign(new Error('fatal: not a git repository'), { - stderr: 'fatal: not a git repository' - }) - ) - - await expect( - getUpstreamStatus('/repo', { - remoteName: 'fork', - branchName: 'feature/fix' - }) - ).rejects.toThrow('fatal: not a git repository') - }) -}) diff --git a/src/main/git/source-control/effective-upstream-status-cache.ts b/src/main/git/source-control/upstream/effective-upstream-status-cache.ts similarity index 95% rename from src/main/git/source-control/effective-upstream-status-cache.ts rename to src/main/git/source-control/upstream/effective-upstream-status-cache.ts index cd71a3bcd3f..5c8fee54c5d 100644 --- a/src/main/git/source-control/effective-upstream-status-cache.ts +++ b/src/main/git/source-control/upstream/effective-upstream-status-cache.ts @@ -1,6 +1,6 @@ -import type { GitUpstreamStatus } from '../../../shared/git/status/git-status-types' -import type { GitRuntimeOptions } from '../command-runner/git-runtime-options' -import { invalidateGitReadCaches } from './git-read-cache-invalidation' +import type { GitUpstreamStatus } from '../../../../shared/git/status/git-status-types' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { invalidateGitReadCaches } from '../git-read-cache-invalidation' import { resolvedUpstreamNameCache } from './resolved-upstream-name-cache' const EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_TTL_MS = 5 * 60_000 diff --git a/src/main/git/source-control/effective-upstream-status-probe.ts b/src/main/git/source-control/upstream/effective-upstream-status-probe.ts similarity index 92% rename from src/main/git/source-control/effective-upstream-status-probe.ts rename to src/main/git/source-control/upstream/effective-upstream-status-probe.ts index f40fe5d527f..e0122e2f08b 100644 --- a/src/main/git/source-control/effective-upstream-status-probe.ts +++ b/src/main/git/source-control/upstream/effective-upstream-status-probe.ts @@ -1,15 +1,15 @@ -import type { GitUpstreamStatus } from '../../../shared/git/status/git-status-types' +import type { GitUpstreamStatus } from '../../../../shared/git/status/git-status-types' import { getEffectiveGitUpstreamStatus, getGitUpstreamStatusForUpstreamName -} from '../../../shared/git/remotes/git-effective-upstream' -import { splitRemoteBranchName } from '../../../shared/git/remotes/git-remote-branch-name' +} from '../../../../shared/git/remotes/git-effective-upstream' +import { splitRemoteBranchName } from '../../../../shared/git/remotes/git-remote-branch-name' import { type GitRuntimeOptions, gitReadOptionsForWorktree -} from '../command-runner/git-runtime-options' -import { gitExecFileAsync } from '../command-runner/git-exec-file' +} from '../../command-runner/git-runtime-options' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES, effectiveUpstreamStatusInFlight, diff --git a/src/main/git/source-control/git-upstream-status-read-owner.ts b/src/main/git/source-control/upstream/git-upstream-status-read-owner.ts similarity index 82% rename from src/main/git/source-control/git-upstream-status-read-owner.ts rename to src/main/git/source-control/upstream/git-upstream-status-read-owner.ts index d1712cbd6be..a1a0f8affaf 100644 --- a/src/main/git/source-control/git-upstream-status-read-owner.ts +++ b/src/main/git/source-control/upstream/git-upstream-status-read-owner.ts @@ -1,6 +1,9 @@ -import type { GitUpstreamStatus } from '../../../shared/git/status/git-status-types' -import type { GitPushTarget } from '../../../shared/worktree/types' -import { InFlightPromiseDedupe, stableInFlightKey } from '../../../shared/in-flight-promise-dedupe' +import type { GitUpstreamStatus } from '../../../../shared/git/status/git-status-types' +import type { GitPushTarget } from '../../../../shared/worktree/types' +import { + InFlightPromiseDedupe, + stableInFlightKey +} from '../../../../shared/in-flight-promise-dedupe' /** Fix key order for JSON.stringify and make new push-target fields fail the exhaustive type check. */ function pushTargetKeyParts(pushTarget: GitPushTarget): readonly unknown[] { diff --git a/src/main/git/source-control/resolved-upstream-name-cache.ts b/src/main/git/source-control/upstream/resolved-upstream-name-cache.ts similarity index 100% rename from src/main/git/source-control/resolved-upstream-name-cache.ts rename to src/main/git/source-control/upstream/resolved-upstream-name-cache.ts diff --git a/src/main/git/source-control/upstream/status-upstream-ref.test.ts b/src/main/git/source-control/upstream/status-upstream-ref.test.ts new file mode 100644 index 00000000000..5b4b05dcc34 --- /dev/null +++ b/src/main/git/source-control/upstream/status-upstream-ref.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest' +import { resolveGitStatusUpstreamRef } from './status-upstream-ref' + +const signal = (): AbortSignal => new AbortController().signal + +describe('resolveGitStatusUpstreamRef', () => { + it('resolves an accepted effective upstream override explicitly', async () => { + const execGit = vi + .fn() + .mockResolvedValueOnce({ + stdout: 'refs/heads/feature/prompts\0refs/remotes/origin/main\0origin/main\n' + }) + .mockResolvedValueOnce({ + stdout: '--end-of-options\nrefs/remotes/origin/feature/prompts\n' + }) + + await expect( + resolveGitStatusUpstreamRef( + execGit, + '/repo', + 'refs/heads/feature/prompts', + 'origin/feature/prompts', + signal() + ) + ).resolves.toBe('refs/remotes/origin/feature/prompts') + expect(execGit).toHaveBeenNthCalledWith( + 2, + ['rev-parse', '--symbolic-full-name', '--end-of-options', 'origin/feature/prompts'], + '/repo', + expect.any(AbortSignal) + ) + }) + + it('fails safe when an effective override is ambiguous', async () => { + const execGit = vi + .fn() + .mockResolvedValueOnce({ + stdout: 'refs/heads/feature/main\0refs/remotes/origin/main\0origin/main\n' + }) + .mockResolvedValueOnce({ + stdout: 'refs/heads/origin/feature/main\nrefs/remotes/origin/feature/main\n' + }) + + await expect( + resolveGitStatusUpstreamRef( + execGit, + '/repo', + 'refs/heads/feature/main', + 'origin/feature/main', + signal() + ) + ).resolves.toBeUndefined() + }) +}) diff --git a/src/main/git/source-control/status-upstream-ref.ts b/src/main/git/source-control/upstream/status-upstream-ref.ts similarity index 93% rename from src/main/git/source-control/status-upstream-ref.ts rename to src/main/git/source-control/upstream/status-upstream-ref.ts index 304c14686e2..d5caf98f8d0 100644 --- a/src/main/git/source-control/status-upstream-ref.ts +++ b/src/main/git/source-control/upstream/status-upstream-ref.ts @@ -1,4 +1,4 @@ -import { isSafeGitRefName } from '../../../shared/git/status/git-status-upstream-ref' +import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' type GitStatusUpstreamRefExec = ( args: string[], diff --git a/src/main/git/source-control/upstream-deferred-fork-remote-real.test.ts b/src/main/git/source-control/upstream/upstream-deferred-fork-remote-real.test.ts similarity index 96% rename from src/main/git/source-control/upstream-deferred-fork-remote-real.test.ts rename to src/main/git/source-control/upstream/upstream-deferred-fork-remote-real.test.ts index 6f59d317328..09ccaeb33e7 100644 --- a/src/main/git/source-control/upstream-deferred-fork-remote-real.test.ts +++ b/src/main/git/source-control/upstream/upstream-deferred-fork-remote-real.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import type { GitPushTarget } from '../../../shared/worktree/types' +import type { GitPushTarget } from '../../../../shared/worktree/types' import { getUpstreamStatus } from './upstream' // Real Git verifies missing-ref exit/stderr handling before a fork remote is materialized. diff --git a/src/main/git/source-control/upstream.ts b/src/main/git/source-control/upstream/upstream.ts similarity index 80% rename from src/main/git/source-control/upstream.ts rename to src/main/git/source-control/upstream/upstream.ts index de6a1f7383a..3c21d09aa89 100644 --- a/src/main/git/source-control/upstream.ts +++ b/src/main/git/source-control/upstream/upstream.ts @@ -1,16 +1,16 @@ -import type { GitUpstreamStatus } from '../../../shared/git/status/git-status-types' -import type { GitPushTarget } from '../../../shared/worktree/types' -import { upstreamOnlyCommitsArePatchEquivalent } from '../../../shared/git/remotes/git-upstream-status' +import type { GitUpstreamStatus } from '../../../../shared/git/status/git-status-types' +import type { GitPushTarget } from '../../../../shared/worktree/types' +import { upstreamOnlyCommitsArePatchEquivalent } from '../../../../shared/git/remotes/git-upstream-status' import { isNoUpstreamError, normalizeGitErrorMessage -} from '../../../shared/git/remotes/git-remote-error' -import { getEffectiveGitUpstreamStatus } from '../../../shared/git/remotes/git-effective-upstream' -import { getPublishTargetStatus } from '../../../shared/git/remotes/git-publish-target-status' -import { gitExecFileAsync } from '../command-runner/git-exec-file' -import { validateGitPushTarget } from '../remotes/push-target-validation' +} from '../../../../shared/git/remotes/git-remote-error' +import { getEffectiveGitUpstreamStatus } from '../../../../shared/git/remotes/git-effective-upstream' +import { getPublishTargetStatus } from '../../../../shared/git/remotes/git-publish-target-status' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { validateGitPushTarget } from '../../remotes/push-target-validation' import { nativeAndWslGitUpstreamStatusReadOwner } from './git-upstream-status-read-owner' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' type GitExecOptions = { wslDistro?: string diff --git a/src/main/git/worktrees/catalog/strict-true-empty-worktree-listing.ts b/src/main/git/worktrees/catalog/strict-true-empty-worktree-listing.ts new file mode 100644 index 00000000000..1f6433f1e02 --- /dev/null +++ b/src/main/git/worktrees/catalog/strict-true-empty-worktree-listing.ts @@ -0,0 +1,18 @@ +import type { GitWorktreeInfo } from '../../../../shared/worktree/types' +import type { GitWorktreeExecOptions } from '../worktree-operation-options' +import { isTrueEmptyWorktreeListing, listWorktreesStrict } from './worktree-listing' + +/** Reject scan failures to prevent pruning valid worktrees and tabs; confirmed missing/non-repos return []. */ +export async function listWorktreesStrictAllowingTrueEmpty( + repoPath: string, + options: GitWorktreeExecOptions = {} +): Promise { + try { + return await listWorktreesStrict(repoPath, options) + } catch (err) { + if (await isTrueEmptyWorktreeListing(repoPath, err)) { + return [] + } + throw err + } +} diff --git a/src/main/git/worktrees/catalog/worktree-git-path.ts b/src/main/git/worktrees/catalog/worktree-git-path.ts index b6d36731000..b22d354dbac 100644 --- a/src/main/git/worktrees/catalog/worktree-git-path.ts +++ b/src/main/git/worktrees/catalog/worktree-git-path.ts @@ -1,7 +1,6 @@ /** * `git rev-parse --git-path ` for a per-worktree file, read from the worktree's own `.git` - * instead of running Git: the setup runner needs it synchronously, and a synchronous Git in a WSL - * project would be a synchronous wsl.exe on the main thread. Null when the link isn't one this can + * instead of starting Git in a WSL project. Null when the link isn't one this can * read, so the caller falls back to Git. */ import { readFileSync, statSync } from 'node:fs' diff --git a/src/main/git/worktrees/catalog/worktree-listing.ts b/src/main/git/worktrees/catalog/worktree-listing.ts index 44f9dcc97d2..d0518e141eb 100644 --- a/src/main/git/worktrees/catalog/worktree-listing.ts +++ b/src/main/git/worktrees/catalog/worktree-listing.ts @@ -7,7 +7,7 @@ import { join } from 'node:path' import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' import { resolveGitMetadataPath } from '../../../../shared/git/metadata/git-metadata-path' import { parseGitdirMarkerPayload } from '../../../../shared/git/metadata/gitdir-marker-payload' -import { isWorktreeCreatePreparation } from '../../../../shared/worktree/create-preparation' +import { isWorktreeCreatePreparation } from '../../../../shared/worktree/creation/create-preparation' import { toWslExecutionSpace } from '../../../../shared/wsl-paths' import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import { @@ -68,7 +68,7 @@ export async function listWorktreesUnshared( } /** Only a missing path or confirmed non-repo permits an authoritative empty listing. */ -async function isTrueEmptyWorktreeListing(repoPath: string, err: unknown): Promise { +export async function isTrueEmptyWorktreeListing(repoPath: string, err: unknown): Promise { if (getErrorCode(err) === 'ENOENT') { try { await stat(repoPath) @@ -96,21 +96,6 @@ export async function listWorktreesStrict( return annotateSparseCheckoutStatus(repoPath, visibleWorktrees, options) } -/** Reject scan failures to prevent pruning valid worktrees and tabs; confirmed missing/non-repos return []. */ -export async function listWorktreesStrictAllowingTrueEmpty( - repoPath: string, - options: GitWorktreeExecOptions = {} -): Promise { - try { - return await listWorktreesStrict(repoPath, options) - } catch (err) { - if (await isTrueEmptyWorktreeListing(repoPath, err)) { - return [] - } - throw err - } -} - export async function annotateSparseCheckoutStatus( repoPath: string, worktrees: GitWorktreeInfo[], diff --git a/src/main/git/worktrees/catalog/worktree-scan-cache-annotation-reuse.test.ts b/src/main/git/worktrees/catalog/worktree-scan-cache-annotation-reuse.test.ts index 44ebd1b6c0f..b3ba536a06c 100644 --- a/src/main/git/worktrees/catalog/worktree-scan-cache-annotation-reuse.test.ts +++ b/src/main/git/worktrees/catalog/worktree-scan-cache-annotation-reuse.test.ts @@ -50,25 +50,6 @@ describe('graph and annotated worktree scans', () => { __resetSparseCheckoutStateCacheForTests() }) - it('does not probe sparse state for a graph scan', async () => { - const rows = await listWorktreeGraph(REPO, { wslDistro: 'Ubuntu' }) - - expect(rows[0]?.path).toBe('C:\\wt\\x') - expect(rows[0]?.isSparse).toBeUndefined() - expect(detectSparseCheckoutMock).not.toHaveBeenCalled() - }) - - it('reads the git listing once for an overlapping graph and annotated scan', async () => { - const [graphRows, annotatedRows] = await Promise.all([ - listWorktreeGraph(REPO, { wslDistro: 'Ubuntu' }), - listWorktrees(REPO, { wslDistro: 'Ubuntu' }) - ]) - - expect(readTranslatedWorktreeGraphMock).toHaveBeenCalledTimes(1) - expect(graphRows[0]?.isSparse).toBeUndefined() - expect(annotatedRows[0]?.isSparse).toBe(true) - }) - it('resolves a graph scan while the annotated scan is still probing', async () => { let releaseProbe!: () => void detectSparseCheckoutMock.mockImplementation( diff --git a/src/main/git/worktrees/catalog/worktree-scan-cache.ts b/src/main/git/worktrees/catalog/worktree-scan-cache.ts index fb7aa1473c9..fa2cfe03e97 100644 --- a/src/main/git/worktrees/catalog/worktree-scan-cache.ts +++ b/src/main/git/worktrees/catalog/worktree-scan-cache.ts @@ -2,12 +2,13 @@ import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import { annotateSparseCheckoutStatus, listWorktreeGraph as listWorktreeGraphUnshared, - listWorktreesStrict as listWorktreesStrictUnshared, - listWorktreesStrictAllowingTrueEmpty as listWorktreesStrictAllowingTrueEmptyUnshared + listWorktreesStrict as listWorktreesStrictUnshared } from './worktree-listing' +import { listWorktreesStrictAllowingTrueEmpty as listWorktreesStrictAllowingTrueEmptyUnshared } from './strict-true-empty-worktree-listing' import type { GitWorktreeExecOptions } from '../worktree-operation-options' import { WORKTREE_LIST_TIMEOUT_MS } from '../worktree-operation-options' import { resolveGitAdmissionTier } from '../../command-runner/admission/git-operation-executor' +import { withRepositoryGitCause } from '../../repository-git-cause' const inFlightWorktreeScans = new Map>() @@ -25,7 +26,17 @@ function hasInFlightWorktreeScanForRepo(repoPath: string): boolean { return false } +const scanGenerationBumpListeners = new Set<(repoPath: string) => void>() + +/** Settled catalog owners outlive in-flight scans, so mutations must reach them too. */ +export function onWorktreeScanGenerationBump(listener: (repoPath: string) => void): void { + scanGenerationBumpListeners.add(listener) +} + export function bumpWorktreeScanGeneration(repoPath: string): void { + for (const listener of scanGenerationBumpListeners) { + listener(repoPath) + } // Retain generations only while a pre-mutation scan can still be joined. if (!hasInFlightWorktreeScanForRepo(repoPath)) { return @@ -63,7 +74,12 @@ function shareWorktreeScan( run: (repoPath: string, options: GitWorktreeExecOptions) => Promise ): Promise { if (options.signal) { - return run(repoPath, options) + return withRepositoryGitCause( + repoPath, + options, + { family: 'catalog', reason: 'worktree-scan', cache: 'bypass-signal' }, + () => run(repoPath, options) + ) } const generation = worktreeScanGenerations.get(repoPath) ?? 0 const timeout = options.timeout ?? WORKTREE_LIST_TIMEOUT_MS @@ -73,7 +89,12 @@ function shareWorktreeScan( if (inFlight) { return inFlight } - const scan = run(repoPath, options).finally(() => { + const scan = withRepositoryGitCause( + repoPath, + options, + { family: 'catalog', reason: 'worktree-scan', cache: 'miss' }, + () => run(repoPath, options) + ).finally(() => { if (inFlightWorktreeScans.get(key) === scan) { inFlightWorktreeScans.delete(key) } diff --git a/src/main/git/worktrees/checkout/branch-switch-real-git.test.ts b/src/main/git/worktrees/checkout/branch-switch-real-git.test.ts index 76766ae2343..e9fc493d439 100644 --- a/src/main/git/worktrees/checkout/branch-switch-real-git.test.ts +++ b/src/main/git/worktrees/checkout/branch-switch-real-git.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { installRealWorkerThreadChildProcesses } from '../../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' import { switchBranchGuarded, type BranchSwitchDeps } from './branch-switch' import { checkoutBranch } from './checkout' -import { getStatus } from '../../source-control/status-read' +import { getStatus } from '../../source-control/status/status-read' let directory: string let initialHead: string diff --git a/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts b/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts index 1a2b1d22279..3e28878ada8 100644 --- a/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts +++ b/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts @@ -8,7 +8,7 @@ import { installRealWorkerThreadChildProcesses } from '../../../worker-thread-ch import { switchBranchGuarded } from './branch-switch' import { BranchSwitchCollisionError } from './branch-switch-target' import { checkoutBranch, listLocalBranches } from './checkout' -import { getStatus } from '../../source-control/status-read' +import { getStatus } from '../../source-control/status/status-read' import { searchRemoteRefPage } from '../../refs/resolution/repo-remote-ref-search' let directory: string @@ -233,11 +233,32 @@ it('reads live worktree occupancy and discovers remotes despite 50 local matches }) expect(transaction.code).toBe(0) const page = await searchRemoteRefPage(directory, 'topic', 50) - expect(page.refDetails).toEqual([{ refName: 'origin/topic', localBranchName: 'topic' }]) + expect(page.refDetails).toEqual([ + { refName: 'refs/remotes/origin/topic', localBranchName: 'topic' } + ]) const occupied = join(directory, '.git', 'checkout-test') await git('worktree', 'add', '-q', occupied, 'topic-0') expect((await listLocalBranches(directory)).worktreePaths?.['topic-0']).toBe(occupied) await git('worktree', 'remove', occupied) expect((await listLocalBranches(directory)).worktreePaths?.['topic-0']).toBeUndefined() + await git('worktree', 'add', '-q', occupied, 'topic-1') + await rm(occupied, { recursive: true }) + expect((await listLocalBranches(directory)).worktreePaths?.['topic-1']).toBe(occupied) + await git('checkout', '-qb', 'external-current') + const updated = await listLocalBranches(directory) + expect(updated.current).toBe('external-current') + expect(updated.branches[0]).toBe('external-current') + expect(updated.branches).toContain('topic-0') + expect(updated.branches).toContain('topic-9') +}) +it('does not overlay an unborn local branch over a remote branch', async () => { + await git('update-ref', 'refs/remotes/origin/main', initialHead) + await git('update-ref', '-d', 'refs/heads/main') + const local = await listLocalBranches(directory) + expect(local.current).toBeNull() + expect(local.branches).toEqual([]) + expect((await searchRemoteRefPage(directory, 'main', 30)).refDetails).toEqual([ + { refName: 'refs/remotes/origin/main', localBranchName: 'main' } + ]) }) installRealWorkerThreadChildProcesses() diff --git a/src/main/git/worktrees/checkout/checkout-skipped-paths.test.ts b/src/main/git/worktrees/checkout/checkout-skipped-paths.test.ts deleted file mode 100644 index 7a254816d79..00000000000 --- a/src/main/git/worktrees/checkout/checkout-skipped-paths.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseCheckoutSkippedPaths } from './checkout-skipped-paths' - -describe('parseCheckoutSkippedPaths', () => { - it('reads every path git could not replace, apostrophes included', () => { - const stderr = [ - "warning: unable to unlink 'public/logo.png': Permission denied", - "error: unable to unlink old ''draft.txt': Invalid argument", - "warning: unable to unlink 'it's.md': Permission denied", - "Switched to branch 'feature'" - ].join('\n') - - expect(parseCheckoutSkippedPaths(stderr)).toEqual(['public/logo.png', "'draft.txt", "it's.md"]) - }) -}) diff --git a/src/main/git/worktrees/checkout/checkout.ts b/src/main/git/worktrees/checkout/checkout.ts index bd1b0626701..9cc162159df 100644 --- a/src/main/git/worktrees/checkout/checkout.ts +++ b/src/main/git/worktrees/checkout/checkout.ts @@ -1,3 +1,4 @@ +import { snapshotLocalBranchMetadata } from '../../refs/snapshot/branch-ref-snapshot' import type { RuntimeGitLocalBranches } from '../../../../shared/runtime-worktree-contracts' import type { BranchSwitchCreation } from '../../../../shared/git/branch-switch-target' @@ -42,61 +43,33 @@ export async function checkoutBranch( return { skippedPaths: parseCheckoutSkippedPaths(stderr) } } -/** for-each-ref avoids localized branch decoration; return the current branch first. */ +/** Current checkout state stays request-specific while the shared branch population is reused. */ export async function listLocalBranches( worktreePath: string, options: GitRuntimeOptions = {} ): Promise { - const execution = gitOptionsForWorktree(worktreePath, options) - let extended = true - const { stdout } = await gitExecFileAsync( - [ - 'for-each-ref', - '--format=%(HEAD)%09%(refname:lstrip=2)%09%(committerdate:unix)%09%(worktreepath)', - 'refs/heads/' - ], - execution - ).catch((error) => { - if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) { - throw error + options.signal?.throwIfAborted() + const { + refs, + current, + worktreePaths: occupied + } = await snapshotLocalBranchMetadata(worktreePath, options) + options.signal?.throwIfAborted() + const branches = refs.map((ref) => ref.label) + if (current) { + const index = branches.indexOf(current) + if (index !== -1) { + branches.splice(index, 1) } - extended = false - return gitExecFileAsync( - ['for-each-ref', '--format=%(HEAD)%09%(refname:lstrip=2)', 'refs/heads/'], - execution - ) - }) - let current: string | null = null - const branches: string[] = [] + branches.unshift(current) + } const committedAt: Record = Object.create(null) const worktreePaths: Record = Object.create(null) - for (const line of stdout.split('\n')) { - if (line.length === 0) { - continue - } - const [marker, name, timestamp, occupiedPath] = line.split('\t') - if (!name) { - continue - } - if (marker === '*') { - current = name - } - branches.push(name) - if (timestamp && Number.isFinite(Number(timestamp))) { - committedAt[name] = Number(timestamp) * 1000 - } - if (occupiedPath) { - worktreePaths[name] = translateWorktreePath(occupiedPath, worktreePath, options) - } + for (const ref of refs) { + committedAt[ref.label] = ref.committedAt } - branches.sort((a, b) => { - if (a === current) { - return -1 - } - if (b === current) { - return 1 - } - return 0 - }) - return { current, branches, ...(extended ? { committedAt, worktreePaths } : {}) } + for (const [name, path] of occupied) { + worktreePaths[name] = translateWorktreePath(path, worktreePath, options) + } + return { current, branches, committedAt, worktreePaths } } diff --git a/src/main/git/worktrees/checkout/commit-actions-real-git.test.ts b/src/main/git/worktrees/checkout/commit-actions-real-git.test.ts index c04e582fa38..868e0e0ec84 100644 --- a/src/main/git/worktrees/checkout/commit-actions-real-git.test.ts +++ b/src/main/git/worktrees/checkout/commit-actions-real-git.test.ts @@ -1,5 +1,5 @@ import './create-branch' -import { detectConflictOperation } from '../../source-control/git-conflict-operation' +import { detectConflictOperation } from '../../source-control/mutations/git-conflict-operation' import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/git/worktrees/checkout/commit-actions.ts b/src/main/git/worktrees/checkout/commit-actions.ts index d964d0118c4..f62e8a7a274 100644 --- a/src/main/git/worktrees/checkout/commit-actions.ts +++ b/src/main/git/worktrees/checkout/commit-actions.ts @@ -1,6 +1,6 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { detectConflictOperation } from '../../source-control/git-conflict-operation' +import { detectConflictOperation } from '../../source-control/mutations/git-conflict-operation' import type { GitCommitAction, GitCommitActionResult diff --git a/src/main/git/worktrees/content-paths/worktree-include-file.ts b/src/main/git/worktrees/content-paths/worktree-include-file.ts index 3152fbae53c..7ed999e00ec 100644 --- a/src/main/git/worktrees/content-paths/worktree-include-file.ts +++ b/src/main/git/worktrees/content-paths/worktree-include-file.ts @@ -1,6 +1,6 @@ import { lstat, readFile } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' -import { checkIgnoredPaths } from '../../source-control/check-ignored-paths' +import { checkIgnoredPaths } from '../../source-control/ignores/check-ignored-paths' import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' diff --git a/src/main/git/worktrees/content-paths/worktree-shared-directories.ts b/src/main/git/worktrees/content-paths/worktree-shared-directories.ts index 793e854f9f8..19414431f3e 100644 --- a/src/main/git/worktrees/content-paths/worktree-shared-directories.ts +++ b/src/main/git/worktrees/content-paths/worktree-shared-directories.ts @@ -1,6 +1,6 @@ import { stat } from 'node:fs/promises' import { join } from 'node:path' -import { checkIgnoredPaths } from '../../source-control/check-ignored-paths' +import { checkIgnoredPaths } from '../../source-control/ignores/check-ignored-paths' import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' import { loadHooks } from '../../../workspace-hooks/hooks' import type { Repo } from '../../../../shared/repo-types' diff --git a/src/main/git/worktrees/creation/checkout-workers-git-args.ts b/src/main/git/worktrees/creation/checkout-workers-git-args.ts index f6d75b709e7..eba6eda4ea3 100644 --- a/src/main/git/worktrees/creation/checkout-workers-git-args.ts +++ b/src/main/git/worktrees/creation/checkout-workers-git-args.ts @@ -5,8 +5,8 @@ import { type GitWorktreeExecOptions } from '../worktree-operation-options' -// Git checks out with one worker by default; 0 means one per core (Git 2.32+; older Git ignores the key). -const PARALLEL_CHECKOUT_GIT_ARGS = ['-c', 'checkout.workers=0'] as const +// Bound default fan-out across simultaneous creates; older Git ignores the key (2.32+). +const PARALLEL_CHECKOUT_GIT_ARGS = ['-c', 'checkout.workers=4'] as const /** Parallel checkout args unless checkout.workers is configured at any scope for this repo and host. */ export async function checkoutWorkersGitArgs( diff --git a/src/main/git/worktrees/creation/create-event-repo-probe.ts b/src/main/git/worktrees/creation/create-event-repo-probe.ts index d92bf1fa678..33256fd0507 100644 --- a/src/main/git/worktrees/creation/create-event-repo-probe.ts +++ b/src/main/git/worktrees/creation/create-event-repo-probe.ts @@ -1,7 +1,7 @@ import { open, readFile, readdir, stat } from 'node:fs/promises' import path from 'node:path' import { getErrorCode } from '../worktree-operation-options' -import { parseWorktreePreparationOwnerPid } from '../../../../shared/worktree/create-preparation' +import { parseWorktreePreparationOwnerPid } from '../../../../shared/worktree/creation/create-preparation' /** Existence only: the hook's content is never read. */ export type PostCheckoutHookPresence = 'present' | 'absent' | 'custom_hooks_path' | 'unknown' diff --git a/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts b/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts index a45c2af7ff2..434c26bf11e 100644 --- a/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts +++ b/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts @@ -1,4 +1,8 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtemp } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' const { gitExecFileAsyncMock, gitExecFileSyncMock, translateWslOutputPathsMock } = vi.hoisted( () => ({ @@ -27,12 +31,16 @@ import { addWorktree } from './worktree-add' import { registerWorktreeSuiteHooks } from '../testing/worktree-test-harness' import { _resetPendingWorktreeRemovalsForTests, - startBackgroundWorktreeRemoval + _settlePendingWorktreeRemovalsForTests, + loadWorktreeRemovalRecords, + startBackgroundWorktreeRemoval, + stopBackgroundWorktreeRemovals, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' registerWorktreeSuiteHooks() -function startDeleting(): void { +async function startDeleting(): Promise { void startBackgroundWorktreeRemoval({ removal: { worktreeId: 'repo-1::/repo-feature', @@ -42,18 +50,27 @@ function startDeleting(): void { deleteBranch: true, force: false }, - run: () => new Promise(() => {}), + run: (signal) => new Promise((resolve) => signal.addEventListener('abort', () => resolve({}))), publish: () => {} }) + await waitForWorktreeRemovalAcceptance('repo-1::/repo-feature') } describe('addWorktree while Orca deletes a checkout in the background', () => { - afterEach(() => { + let directory = '' + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-add-pending-removal-')) + await loadWorktreeRemovalRecords(directory) + }) + afterEach(async () => { + stopBackgroundWorktreeRemovals() + await _settlePendingWorktreeRemovalsForTests() _resetPendingWorktreeRemovalsForTests() + await removeTree(directory) }) it('refuses the same path with a clear message and runs no git', async () => { - startDeleting() + await startDeleting() await expect(addWorktree('/repo', '/repo-feature', 'other-branch')).rejects.toThrow( 'Orca is still deleting the workspace at /repo-feature. Cleanup is pending; try again shortly.' ) @@ -61,7 +78,7 @@ describe('addWorktree while Orca deletes a checkout in the background', () => { }) it('refuses the same branch, which the delete removes when it finishes', async () => { - startDeleting() + await startDeleting() await expect( addWorktree('/repo', '/repo-elsewhere', 'feature/test', undefined, false, false, { checkoutExistingBranch: true diff --git a/src/main/git/worktrees/creation/worktree-add.ts b/src/main/git/worktrees/creation/worktree-add.ts index 02ffb4d41f7..e3f62108ad9 100644 --- a/src/main/git/worktrees/creation/worktree-add.ts +++ b/src/main/git/worktrees/creation/worktree-add.ts @@ -1,9 +1,9 @@ import { GitCommandTimeoutError } from '../../../../shared/git/commands/git-command-timeout' -import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref' +import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-refs/base-ref' import type { LocalBaseRefRefreshResult, LocalBaseRefUpdateSuggestion -} from '../../../../shared/worktree/base-ref-drift-types' +} from '../../../../shared/worktree/base-refs/base-ref-drift-types' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { withRepoRefMaintenancePaused } from '../../refs/maintenance/local-repo-ref-maintenance' @@ -271,6 +271,7 @@ async function performAddWorktree( try { await gitExecFileAsync([...(await checkoutWorkersArgs), ...args], { ...gitExecOptions(repoPath, options), + ...(!noCheckout ? { admissionClass: 'checkout' as const } : {}), // Resolve per call so later environment overrides take effect. timeout: resolveWorktreeAddTimeoutMs(), ...(checkoutProgress ? { onStderr: checkoutProgress.read } : {}) diff --git a/src/main/git/worktrees/creation/worktree-base-divergence.ts b/src/main/git/worktrees/creation/worktree-base-divergence.ts index 4d114893990..29a72bed00e 100644 --- a/src/main/git/worktrees/creation/worktree-base-divergence.ts +++ b/src/main/git/worktrees/creation/worktree-base-divergence.ts @@ -1,7 +1,7 @@ import { WSL_GIT_READ_ENVIRONMENT_WAIT_MS } from '../../command-runner/host-routing/wsl-git-read-environment' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { abortSignalWithTimeout } from '../../../lib/abort-signal-with-timeout' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' export type RetargetDivergenceOptions = { wslDistro?: string diff --git a/src/main/git/worktrees/creation/worktree-base-ref-probe.ts b/src/main/git/worktrees/creation/worktree-base-ref-probe.ts index 748eb448d29..8d0f1c6b10a 100644 --- a/src/main/git/worktrees/creation/worktree-base-ref-probe.ts +++ b/src/main/git/worktrees/creation/worktree-base-ref-probe.ts @@ -1,9 +1,9 @@ -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { isShowRefNoMatchError } from '../../../../shared/git/refs/git-show-ref-no-match' import { hasCommitObjectViaGitExec } from '../../refs/resolution/commit-object-ref' import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' -import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref' +import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-refs/base-ref' type GitExecOptions = { wslDistro?: string diff --git a/src/main/git/worktrees/creation/worktree-base-refresh.ts b/src/main/git/worktrees/creation/worktree-base-refresh.ts index 42860123029..b081d1f609f 100644 --- a/src/main/git/worktrees/creation/worktree-base-refresh.ts +++ b/src/main/git/worktrees/creation/worktree-base-refresh.ts @@ -1,7 +1,7 @@ import type { LocalBaseRefRefreshResult, LocalBaseRefUpdateSuggestion -} from '../../../../shared/worktree/base-ref-drift-types' +} from '../../../../shared/worktree/base-refs/base-ref-drift-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { createCoalescingKeyedRunner } from '../../../../shared/coalescing-keyed-runner' import { parseWorktreeList } from '../../../../shared/git/worktrees/git-worktree-porcelain-parser' @@ -11,8 +11,9 @@ import { toLocalBaseRefRefreshResult, type LocalBaseBranchFastForwardOutcome, type LocalBaseBranchGit -} from '../../../../shared/worktree/local-base-branch-fast-forward' +} from '../../../../shared/worktree/base-refs/local-base-branch-fast-forward' import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification' import { translateWslOutputPaths } from '../../command-runner/host-routing/wsl-path-translation' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' import type { AddWorktreeOptions, GitWorktreeExecOptions } from '../worktree-operation-options' @@ -115,11 +116,19 @@ function localBaseBranchGit(options: GitWorktreeExecOptions): LocalBaseBranchGit ...(options.admissionTier ? { admissionTier: options.admissionTier } : {}) }) return { - exec: (args, cwd) => gitExecFileAsync(args, execOptions(cwd)), + exec: (args, cwd) => + gitExecFileAsync(args, { + ...execOptions(cwd), + ...(args[findGitSubcommandIndex(args)] === 'merge' + ? { admissionClass: 'checkout' as const } + : {}) + }), listWorktrees: async (repoPath) => { - const { stdout } = await gitExecFileAsync( - ['worktree', 'list', '--porcelain'], - execOptions(repoPath) + const { stdout } = await withRepositoryGitCause( + repoPath, + options, + { family: 'catalog', reason: 'creation-base-refresh', cache: 'uncached' }, + () => gitExecFileAsync(['worktree', 'list', '--porcelain'], execOptions(repoPath)) ) return parseWorktreeList(translateWslOutputPaths(stdout, repoPath, options)) } @@ -135,3 +144,4 @@ function waitAtMost(promise: Promise, timeoutMs: number): Promise clearTimeout(timer)) } +import { withRepositoryGitCause } from '../../repository-git-cause' diff --git a/src/main/git/worktrees/creation/worktree-create-admission-real-git.test.ts b/src/main/git/worktrees/creation/worktree-create-admission-real-git.test.ts new file mode 100644 index 00000000000..ddb7d568c19 --- /dev/null +++ b/src/main/git/worktrees/creation/worktree-create-admission-real-git.test.ts @@ -0,0 +1,145 @@ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { GitAdmissionScheduler } from '../../../../shared/git/admission/git-admission-scheduler' +import type { GitAdmissionGrant } from '../../../../shared/git/admission/git-admission-state' +import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' +import { _resetGitAdmissionForTests } from '../../command-runner/admission/git-subprocess-admission' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { addWorktree } from './worktree-add' +import { addSparseWorktree } from './worktree-sparse-add' +import { + finalizePreparedWorktree, + prepareWorktreeCreateCheckout +} from './worktree-create-preparation' +import { refreshPreparedWorktreeTip } from './worktree-preparation-tip-refresh' +import { refreshLocalBaseRefForWorktreeCreate } from './worktree-base-refresh' + +let root: string +let repo: string +let admission: GitAdmissionScheduler + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-create-admission-')) + repo = join(root, 'repo') + admission = new GitAdmissionScheduler() + _resetGitAdmissionForTests(admission) + await gitExecFileAsync(['init', '-q', repo], { cwd: root }) + await gitExecFileAsync(['symbolic-ref', 'HEAD', 'refs/heads/main'], { cwd: repo }) + await mkdir(join(repo, 'included')) + await writeFile(join(repo, 'included', 'file.txt'), 'one\n') + await gitExecFileAsync(['add', '.'], { cwd: repo }) + await gitExecFileAsync( + ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture'], + { cwd: repo } + ) +}) + +afterEach(async () => { + vi.restoreAllMocks() + _resetGitAdmissionForTests() + await rm(root, { recursive: true, force: true }) +}) + +async function behindCheckoutBudget(command: string, run: () => Promise): Promise { + let held: GitAdmissionGrant[] = [] + const requested = Promise.withResolvers() + let admitted = false + const acquire = admission.acquire.bind(admission) + const spy = vi.spyOn(admission, 'acquire').mockImplementation(async (request) => { + if (request.args[findGitSubcommandIndex(request.args)] === command) { + held = await Promise.all( + Array.from({ length: 3 }, () => + acquire({ + args: ['worktree', 'add'], + cwd: repo, + admissionClass: 'checkout', + tier: 'interactive' + }) + ) + ) + const grant = acquire(request) + requested.resolve() + void grant.then(() => { + admitted = true + }) + return grant + } + return acquire(request) + }) + const operation = run() + try { + await requested.promise + const read = await gitExecFileAsync(['rev-parse', '--verify', 'HEAD'], { cwd: repo }) + expect(read.stdout.trim()).toMatch(/^[0-9a-f]{40}$/) + expect(admitted).toBe(false) + } finally { + held.forEach((grant) => grant.release()) + await operation + spy.mockRestore() + } +} + +it('isolates ordinary and sparse creates while honoring the execution host checkout config', async () => { + const { stdout } = await gitExecFileAsync(['--version'], { cwd: repo }) + const version = stdout.match(/git version (\d+)\.(\d+)/) + if (Number(version?.[1]) > 2 || (Number(version?.[1]) === 2 && Number(version?.[2]) >= 32)) { + await gitExecFileAsync(['config', 'checkout.workers', 'not-an-integer'], { cwd: repo }) + await expect(addWorktree(repo, join(root, 'invalid'), 'invalid', 'main')).rejects.toThrow() + } + await gitExecFileAsync(['config', 'checkout.workers', '0'], { cwd: repo }) + const ordinary = join(root, 'ordinary') + await behindCheckoutBudget('worktree', () => addWorktree(repo, ordinary, 'ordinary', 'main')) + expect(await readFile(join(ordinary, 'included', 'file.txt'), 'utf8')).toBe('one\n') + await gitExecFileAsync(['config', '--unset', 'checkout.workers'], { cwd: repo }) + const sparse = join(root, 'sparse') + await behindCheckoutBudget('checkout', () => + addSparseWorktree(repo, sparse, 'sparse', ['included'], 'main') + ) + expect(await readFile(join(sparse, 'included', 'file.txt'), 'utf8')).toBe('one\n') +}) + +it('isolates preparation, fetched-tip refresh and changed-head finalization materializations', async () => { + const prepared = join(root, 'prepared') + const reason = createWorktreePreparationLockReason('admission') + await behindCheckoutBudget('reset', () => + prepareWorktreeCreateCheckout(repo, prepared, 'main', reason) + ) + await writeFile(join(repo, 'included', 'file.txt'), 'two\n') + await gitExecFileAsync(['commit', '-qam', 'next', '--author=Test '], { + cwd: repo, + env: { ...process.env, GIT_COMMITTER_NAME: 'Test', GIT_COMMITTER_EMAIL: 'test@example.invalid' } + }) + await behindCheckoutBudget('reset', () => + refreshPreparedWorktreeTip(repo, prepared, 'main', reason) + ) + expect(await readFile(join(prepared, 'included', 'file.txt'), 'utf8')).toBe('two\n') + await writeFile(join(repo, 'included', 'file.txt'), 'three\n') + await gitExecFileAsync( + ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qam', 'third'], + { cwd: repo } + ) + const target = join(root, 'finalized') + await behindCheckoutBudget('reset', () => + finalizePreparedWorktree(repo, prepared, target, 'finalized', 'main', false, {}, reason) + ) + expect(await readFile(join(target, 'included', 'file.txt'), 'utf8')).toBe('three\n') +}) + +it('isolates the production base fast-forward with its leading Git config arguments', async () => { + const newer = join(root, 'newer') + await addWorktree(repo, newer, 'newer', 'main') + await writeFile(join(newer, 'included', 'file.txt'), 'remote\n') + await gitExecFileAsync( + ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qam', 'remote'], + { cwd: newer } + ) + const { stdout } = await gitExecFileAsync(['rev-parse', 'HEAD'], { cwd: newer }) + await gitExecFileAsync(['update-ref', 'refs/remotes/origin/main', stdout.trim()], { cwd: repo }) + await behindCheckoutBudget('merge', () => + refreshLocalBaseRefForWorktreeCreate(repo, 'origin/main', 'refs/remotes/origin/main') + ) + expect(await readFile(join(repo, 'included', 'file.txt'), 'utf8')).toBe('remote\n') +}) diff --git a/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts b/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts deleted file mode 100644 index 0ad8ff611e1..00000000000 --- a/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { execFileSync } from 'node:child_process' - -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import * as gitRunner from '../../command-runner/git-exec-file' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' - -import { - finalizePreparedWorktree, - prepareWorktreeCreateCheckout -} from './worktree-create-preparation' - -const tempRoots: string[] = [] - -function git(cwd: string, args: string[]): string { - return execFileSync('git', args, { - cwd, - encoding: 'utf8', - stdio: ['pipe', 'pipe', 'pipe'] - }).trim() -} - -async function createRepo(): Promise<{ repoPath: string; root: string }> { - const root = await mkdtemp(join(tmpdir(), 'orca-prepared-worktree-')) - tempRoots.push(root) - const repoPath = join(root, 'repo') - execFileSync('git', ['init', '--quiet', repoPath]) - git(repoPath, ['symbolic-ref', 'HEAD', 'refs/heads/main']) - git(repoPath, ['config', 'user.email', 'test@example.com']) - git(repoPath, ['config', 'user.name', 'Test User']) - git(repoPath, ['config', 'core.autocrlf', 'false']) - await writeFile(join(repoPath, 'version.txt'), 'one\n') - git(repoPath, ['add', 'version.txt']) - git(repoPath, ['commit', '--quiet', '-m', 'initial']) - return { repoPath, root } -} - -afterEach(async () => { - await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -it.each(['replacement', 'permission'])( - 'preserves the requested path when rollback loses %s authority', - async (kind) => { - const { repoPath, root } = await createRepo() - const prepared = join(root, 'prepared-rollback-authority') - const target = join(root, 'rollback-target') - const preserved = join(root, 'preserved-original') - const reason = createWorktreePreparationLockReason('rollback-authority') - await prepareWorktreeCreateCheckout(repoPath, prepared, 'main', reason) - const originalLock = git(prepared, ['rev-parse', '--git-path', 'locked']) - const failure = new Error('move rewrote pointers but rejected') - const run = gitRunner.gitExecFileAsync - let allowed = true - let replaced = false - vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - if (args.includes('move')) { - await run(args, options) - if (kind === 'permission') { - allowed = false - } - throw failure - } - if ( - kind === 'replacement' && - args[0] === 'symbolic-ref' && - options.cwd === target && - !replaced - ) { - replaced = true - git(repoPath, ['worktree', 'move', '-f', '-f', target, preserved]) - git(repoPath, ['worktree', 'add', '--detach', target, 'HEAD']) - git(repoPath, ['worktree', 'lock', '--reason', reason, target]) - await writeFile(join(target, 'user.txt'), 'preserve replacement\n') - } - return run(args, options) - }) - try { - await expect( - finalizePreparedWorktree( - repoPath, - prepared, - target, - 'rollback-authority', - 'main', - false, - { canStart: () => allowed }, - reason - ) - ).rejects.toBe(failure) - expect(await readFile(join(target, 'version.txt'), 'utf8')).toBe('one\n') - if (kind === 'replacement') { - expect(replaced).toBe(true) - expect(await readFile(join(target, 'user.txt'), 'utf8')).toBe('preserve replacement\n') - expect(await readFile(join(preserved, 'version.txt'), 'utf8')).toBe('one\n') - } - expect(await readFile(originalLock, 'utf8')).toBe(`${reason}\n`) - } finally { - vi.restoreAllMocks() - } - } -) diff --git a/src/main/git/worktrees/creation/worktree-create-preparation-real-wsl.test.ts b/src/main/git/worktrees/creation/worktree-create-preparation-real-wsl.test.ts index f13a78d6f98..67fb358bb0f 100644 --- a/src/main/git/worktrees/creation/worktree-create-preparation-real-wsl.test.ts +++ b/src/main/git/worktrees/creation/worktree-create-preparation-real-wsl.test.ts @@ -1,7 +1,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { expect, it } from 'vitest' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { finalizePreparedWorktree, @@ -36,9 +36,6 @@ it.skipIf(process.platform !== 'win32' || !wslDistro)( await git(repoPath, ['commit', '--quiet', '-m', 'initial']) const lockReason = createWorktreePreparationLockReason('real-wsl-test') await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason, options) - expect(await git(repoPath, ['worktree', 'list', '--porcelain'])).toContain( - 'locked orca-create-preparation:v1:' - ) await writeFile(join(repoPath, 'version.txt'), 'two\n') await git(repoPath, ['commit', '--quiet', '-am', 'advance base']) @@ -62,9 +59,6 @@ it.skipIf(process.platform !== 'win32' || !wslDistro)( ) expect(await git(repoPath, ['worktree', 'list', '--porcelain'])).not.toContain('locked ') await removeWorktree(repoPath, finalPath, true, options) - expect( - (await git(repoPath, ['worktree', 'list', '--porcelain'])).match(/^worktree /gm) - ).toHaveLength(1) } finally { await rm(root, { recursive: true, force: true }) } diff --git a/src/main/git/worktrees/creation/worktree-create-preparation.ts b/src/main/git/worktrees/creation/worktree-create-preparation.ts index e2318c2293b..d0c2c6e5207 100644 --- a/src/main/git/worktrees/creation/worktree-create-preparation.ts +++ b/src/main/git/worktrees/creation/worktree-create-preparation.ts @@ -2,7 +2,7 @@ import { runStandalonePreparation } from './worktree-preparation-standalone' import { performPreparedWorktreeFinalization } from './worktree-preparation-finalization-work' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' import { checkoutWorkersGitArgs } from './checkout-workers-git-args' -import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref' +import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-refs/base-ref' import type { AddWorktreeOptions, AddWorktreeResult, @@ -98,7 +98,11 @@ export async function prepareWorktreeCreateCheckout( '--hard', materializationBase ], - { ...gitExecOptions(worktreePath, options), timeout: resolveWorktreeAddTimeoutMs() } + { + ...gitExecOptions(worktreePath, options), + admissionClass: 'checkout', + timeout: resolveWorktreeAddTimeoutMs() + } ) await verifyWorktreePreparationLockAtPath(lockPath, lockReason, options.signal) }) diff --git a/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts b/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts index dc6901098aa..bb0ebfb175e 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts @@ -2,10 +2,9 @@ import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' import * as runner from '../../command-runner/git-exec-file' import { performDiscardPreparedWorktree } from './worktree-preparation-discard' -import { WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS } from '../worktree-operation-options' const roots: string[] = [] afterEach(async () => { @@ -48,52 +47,14 @@ it('removes only the owned registration after external deletion of its checkout' const { repo, prepared, lock, reason } = await fixture() await rm(prepared, { recursive: true }) expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) - const spy = vi.spyOn(runner, 'gitExecFileAsync') await performDiscardPreparedWorktree(repo, prepared, { signal: AbortSignal.abort() }, reason) - - expect(spy.mock.calls.map(([args]) => args)).toEqual([ - ['rev-parse', '--git-path', 'locked', '--git-common-dir'], - ['worktree', 'remove', '--force', '--force', prepared] - ]) - expect(spy.mock.calls[1]?.[1]).toMatchObject({ - cwd: repo, - timeout: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS - }) await expect(readFile(lock, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' }) expect( (await runner.gitExecFileAsync(['worktree', 'list', '--porcelain'], { cwd: repo })).stdout ).not.toContain(prepared) }) -it.each(['foreign', 'empty', 'missing', 'unterminated', 'CRLF'])( - 'preserves a missing checkout registration with a %s ownership marker', - async (kind) => { - const { repo, prepared, lock, reason } = await fixture() - const contents = - kind === 'foreign' - ? 'manual lock\n' - : kind === 'empty' - ? '' - : `${reason}${kind === 'CRLF' ? '\r\n' : ''}` - await (kind === 'missing' ? rm(lock) : writeFile(lock, contents)) - await rm(prepared, { recursive: true }) - const spy = vi.spyOn(runner, 'gitExecFileAsync') - - await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason)).rejects.toThrow( - 'lock owner changed' - ) - - expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false) - expect(await readFile(join(dirname(lock), 'gitdir'), 'utf8')).toBe( - `${join(prepared, '.git')}\n` - ) - if (kind !== 'missing') { - expect(await readFile(lock, 'utf8')).toBe(contents) - } - } -) - it('preserves a folder that reappears between ownership verification and Git removal', async () => { const { repo, prepared, lock, reason } = await fixture() await rm(prepared, { recursive: true }) @@ -118,7 +79,7 @@ it('rechecks an owner replaced after the checkout path query fails', async () => const { repo, prepared, lock, reason } = await fixture() await rm(prepared, { recursive: true }) const run = runner.gitExecFileAsync - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { try { return await run(args, options) } catch (error) { @@ -132,8 +93,6 @@ it('rechecks an owner replaced after the checkout path query fails', async () => await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason)).rejects.toThrow( 'lock owner changed' ) - - expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false) expect(await readFile(lock, 'utf8')).toBe('replacement during cleanup\n') }) @@ -142,13 +101,10 @@ it('does not borrow ownership from a different repository', async () => { const otherRepo = join(dirname(repo), 'other-repo') await runner.gitExecFileAsync(['init', '--quiet', otherRepo], { cwd: dirname(repo) }) await rm(prepared, { recursive: true }) - const spy = vi.spyOn(runner, 'gitExecFileAsync') await expect(performDiscardPreparedWorktree(otherRepo, prepared, {}, reason)).rejects.toThrow( 'lock owner changed' ) - - expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false) expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) }) @@ -159,13 +115,10 @@ it.runIf(process.platform !== 'win32')('does not follow a symlink ownership mark await rm(lock) await symlink(externalLock, lock) await rm(prepared, { recursive: true }) - const spy = vi.spyOn(runner, 'gitExecFileAsync') await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason)).rejects.toThrow( 'lock owner changed' ) - - expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false) expect(await readFile(externalLock, 'utf8')).toBe(`${reason}\n`) }) diff --git a/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts b/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts index aae73588661..658e6cabca0 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts @@ -1,10 +1,10 @@ import type * as FilePromises from 'node:fs/promises' import { existsSync } from 'node:fs' -import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' import { clearGitCapabilityStateForTests, getLocalGitCapabilityCache @@ -16,7 +16,6 @@ import { listPreparations, _resetPreparationPoolForTests } from '../../../workspaces/creation/preparation/worktree-create-preparation-pool' -import { WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS } from '../worktree-operation-options' const lockWrite = vi.hoisted((): { after: (() => void) | undefined } => ({ after: undefined })) vi.mock('node:fs/promises', async (importOriginal) => { @@ -33,7 +32,6 @@ vi.mock('node:fs/promises', async (importOriginal) => { }) const roots: string[] = [] -const unsupported = Object.assign(new Error("error: unknown option 'reason'"), { code: 129 }) beforeEach(() => { clearGitCapabilityStateForTests() @@ -73,149 +71,13 @@ async function fixture() { return { repo, prepared } } -it.each([ - ['first', 'cancellation'], - ['cached', 'cancellation'], - ['first', 'path probe'], - ['cached', 'path probe'] -])('reclaims its registered %s fallback after %s before locking', async (fallback, failureKind) => { - const { repo, prepared } = await fixture() - const reason = createWorktreePreparationLockReason('fallback-cleanup') - const controller = new AbortController() - const failure = new Error(`${failureKind} after completed add`) - const run = runner.gitExecFileAsync - let registered = false - if (fallback === 'cached') { - getLocalGitCapabilityCache().rememberUnsupported('worktree-add-lock-reason') - } - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - if (args.includes('--reason')) { - throw unsupported - } - const result = await run(args, options) - if (args.includes('--no-checkout')) { - registered = true - expect(existsSync(join(prepared, '.git'))).toBe(true) - } - if (registered && options?.cwd === prepared && args.includes('--git-path')) { - expect(existsSync(join(prepared, 'tracked.txt'))).toBe(false) - if (failureKind === 'cancellation') { - controller.abort(failure) - } - throw failure - } - return result - }) - await expect( - prepareWorktreeCreateCheckout(repo, prepared, 'main', reason, { - signal: controller.signal, - timeout: 180_000 - }) - ).rejects.toBe(failure) - const removals = spy.mock.calls.filter(([args]) => args.includes('remove')) - expect(removals).toHaveLength(1) - const [removeArgs, removeOptions] = removals[0]! - expect(removeArgs.filter((arg) => arg === '--force')).toHaveLength(1) - expect(removeOptions).toMatchObject({ - cwd: repo, - timeout: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS - }) - expect(removeOptions).not.toHaveProperty('signal') - expect(spy.mock.calls.some(([args]) => args.includes('reset'))).toBe(false) - expect(existsSync(prepared)).toBe(false) - expect((await run(['worktree', 'list', '--porcelain'], { cwd: repo })).stdout).not.toContain( - prepared - ) -}) - -it.each(['first', 'cached'])( - 'preserves another marker after a successful %s fallback add', - async (fallback) => { - const { repo, prepared } = await fixture() - const reason = createWorktreePreparationLockReason('competing-fallback') - const run = runner.gitExecFileAsync - let lock = '' - if (fallback === 'cached') { - getLocalGitCapabilityCache().rememberUnsupported('worktree-add-lock-reason') - } - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - if (args.includes('--reason')) { - throw unsupported - } - const result = await run(args, options) - if (args.includes('--no-checkout')) { - lock = (await run(['rev-parse', '--git-path', 'locked'], { cwd: prepared })).stdout.trim() - await writeFile(lock, 'manual competing owner\n') - await writeFile(join(prepared, 'user.txt'), 'preserve this file\n') - } - return result - }) - await expect(prepareWorktreeCreateCheckout(repo, prepared, 'main', reason)).rejects.toThrow( - 'lock owner changed' - ) - expect(await readFile(lock, 'utf8')).toBe('manual competing owner\n') - expect(await readFile(join(prepared, 'user.txt'), 'utf8')).toBe('preserve this file\n') - expect(spy.mock.calls.some(([args]) => args.includes('remove') || args.includes('reset'))).toBe( - false - ) - expect((await run(['worktree', 'list', '--porcelain'], { cwd: repo })).stdout).toContain( - prepared - ) - } -) - -it.each(['first', 'cached'])( - 'lets Git protect a competing lock from %s fallback cleanup after a generic probe failure', - async (fallback) => { - const { repo, prepared } = await fixture() - const reason = createWorktreePreparationLockReason('protected-fallback-cleanup') - const failure = new Error('lock path became unreadable') - const run = runner.gitExecFileAsync - let lock = '' - if (fallback === 'cached') { - getLocalGitCapabilityCache().rememberUnsupported('worktree-add-lock-reason') - } - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - if (args.includes('--reason')) { - throw unsupported - } - if (lock && options?.cwd === prepared && args.includes('--git-path')) { - throw failure - } - const result = await run(args, options) - if (args.includes('--no-checkout')) { - lock = (await run(['rev-parse', '--git-path', 'locked'], { cwd: prepared })).stdout.trim() - await writeFile(lock, 'manual protected owner\n') - await writeFile(join(prepared, 'user.txt'), 'preserve after cleanup attempt\n') - } - return result - }) - await expect(prepareWorktreeCreateCheckout(repo, prepared, 'main', reason)).rejects.toBe( - failure - ) - const removals = spy.mock.calls.filter(([args]) => args.includes('remove')) - expect(removals).toHaveLength(1) - expect(removals[0]![0].filter((arg) => arg === '--force')).toHaveLength(1) - expect(removals[0]![1]).not.toHaveProperty('signal') - expect(removals[0]![1]).toMatchObject({ timeout: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS }) - expect(await readFile(lock, 'utf8')).toBe('manual protected owner\n') - expect(await readFile(join(prepared, 'user.txt'), 'utf8')).toBe( - 'preserve after cleanup attempt\n' - ) - expect(spy.mock.calls.some(([args]) => args.includes('reset'))).toBe(false) - expect((await run(['worktree', 'list', '--porcelain'], { cwd: repo })).stdout).toContain( - prepared - ) - } -) - it('preserves a pre-existing empty target if its cached fallback lock-path probe fails', async () => { const { repo, prepared } = await fixture() await mkdir(prepared) getLocalGitCapabilityCache().rememberUnsupported('worktree-add-lock-reason') const failure = new Error('pre-existing target lock path unavailable') const run = runner.gitExecFileAsync - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { if (options?.cwd === prepared && args.includes('--git-path')) { throw failure } @@ -225,9 +87,6 @@ it('preserves a pre-existing empty target if its cached fallback lock-path probe failure ) expect(existsSync(join(prepared, '.git'))).toBe(true) - expect(spy.mock.calls.some(([args]) => args.includes('remove') || args.includes('reset'))).toBe( - false - ) expect((await run(['worktree', 'list', '--porcelain'], { cwd: repo })).stdout).toContain(prepared) }) diff --git a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts index eeb968453b0..cfccc9fa9fa 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts @@ -93,7 +93,7 @@ export async function performPreparedWorktreeFinalization( '--hard', targetHead ], - gitExecOptions(preparedPath, finalizeGitOptions) + { ...gitExecOptions(preparedPath, finalizeGitOptions), admissionClass: 'checkout' } ) } diff --git a/src/main/git/worktrees/creation/worktree-preparation-lock-real-git.test.ts b/src/main/git/worktrees/creation/worktree-preparation-lock-real-git.test.ts index b8f54c09722..e0c989021df 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-lock-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-lock-real-git.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, relative } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' import * as runner from '../../command-runner/git-exec-file' import { discardPreparedWorktree, @@ -10,13 +10,8 @@ import { prepareWorktreeCreateCheckout } from './worktree-create-preparation' import { unlockWorktreePreparation } from './worktree-preparation-lock' -import { readWorktreeList } from '../catalog/worktree-list-reader' -import { - _resetPreparationPoolForTests, - listPreparations, - startPreparation, - WORKTREE_CREATE_PREPARATION_TTL_MS -} from '../../../workspaces/creation/preparation/worktree-create-preparation-pool' + +import { _resetPreparationPoolForTests } from '../../../workspaces/creation/preparation/worktree-create-preparation-pool' const roots: string[] = [] afterEach(async () => { @@ -61,45 +56,14 @@ it.runIf(process.platform !== 'win32')( const lock = await git(prepared, ['rev-parse', '--git-path', 'locked']) expect(lock).toContain('\n') expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) - const spy = vi.spyOn(runner, 'gitExecFileAsync') await unlockWorktreePreparation(prepared, reason, {}) - expect(spy.mock.calls.map(([args]) => args)).toEqual([ - ['rev-parse', '--git-path', 'locked', '--git-common-dir'], - ['rev-parse', '--git-path', 'locked'], - ['rev-parse', '--git-common-dir'] - ]) await expect(readFile(lock, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' }) expect(await readFile(join(prepared, 'tracked.txt'), 'utf8')).toBe('original\n') expect(await git(prepared, ['status', '--porcelain'])).toBe('') } ) -it('has its exact ownership marker before the atomic add returns', async () => { - const { repo, prepared } = await fixture() - const reason = createWorktreePreparationLockReason('atomic-add') - const run = runner.gitExecFileAsync - let observed = false - vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - const result = await run(args, options) - if (args.includes('--reason')) { - const lock = ( - await run(['rev-parse', '--git-path', 'locked'], { cwd: prepared }) - ).stdout.trim() - expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) - await expect(readFile(join(prepared, 'tracked.txt'))).rejects.toMatchObject({ - code: 'ENOENT' - }) - observed = true - } - return result - }) - await prepareWorktreeCreateCheckout(repo, prepared, 'main', reason) - const version = await git(repo, ['--version']) - const minor = Number(version.match(/git version 2\.(\d+)/)?.[1]) - expect(observed).toBe(minor >= 33) -}) - it('cleans only its newly registered marker when cancellation follows atomic add', async ({ skip }) => { @@ -111,7 +75,7 @@ it('cleans only its newly registered marker when cancellation follows atomic add const reason = createWorktreePreparationLockReason('atomic-cancellation') const controller = new AbortController() const run = runner.gitExecFileAsync - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { const result = await run(args, options) if (args.includes('--no-checkout') && args.includes('--reason')) { controller.abort() @@ -122,23 +86,10 @@ it('cleans only its newly registered marker when cancellation follows atomic add await expect( prepareWorktreeCreateCheckout(repo, prepared, 'main', reason, { signal: controller.signal }) ).rejects.toMatchObject({ name: 'AbortError' }) - expect(spy.mock.calls.some(([args]) => args.includes('reset'))).toBe(false) await expect(readFile(join(prepared, '.git'))).rejects.toMatchObject({ code: 'ENOENT' }) expect(await git(repo, ['worktree', 'list', '--porcelain'])).not.toContain(prepared) }) -it('preserves an existing owned checkout when another add fails at its path', async () => { - const { repo, prepared } = await fixture() - const reason = createWorktreePreparationLockReason('existing-add') - await prepareWorktreeCreateCheckout(repo, prepared, 'main', reason) - const lock = await git(prepared, ['rev-parse', '--git-path', 'locked']) - const spy = vi.spyOn(runner, 'gitExecFileAsync') - await expect(prepareWorktreeCreateCheckout(repo, prepared, 'main', reason)).rejects.toThrow() - expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false) - expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) - expect(await readFile(join(prepared, 'tracked.txt'), 'utf8')).toBe('original\n') -}) - it('resolves a relative gitfile and retains a competing unlock marker', async () => { const { repo, prepared } = await fixture() const reason = createWorktreePreparationLockReason('relative') @@ -156,47 +107,12 @@ it('resolves a relative gitfile and retains a competing unlock marker', async () ) }) -it('preserves a competing marker and registration through preparation failure and pool reset', async () => { - const { root, repo } = await fixture() - let prepared = '' - let lock = '' - const run = runner.gitExecFileAsync - vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - const result = await run(args, options) - if (args.includes('reset') && options?.cwd) { - prepared = options.cwd - lock = (await run(['rev-parse', '--git-path', 'locked'], options)).stdout.trim() - await writeFile(lock, 'manual competing preparation\n') - } - return result - }) - await expect( - startPreparation({ - repoPath: repo, - workspaceRoot: root, - baseBranch: 'main', - canonicalBase: 'refs/heads/main', - options: {} - }) - ).rejects.toThrow('lock owner changed') - await _resetPreparationPoolForTests() - expect(await readFile(lock, 'utf8')).toBe('manual competing preparation\n') - expect(await readFile(join(prepared, 'tracked.txt'), 'utf8')).toBe('original\n') - expect(await readWorktreeList(repo)).toContainEqual( - expect.objectContaining({ - path: prepared, - locked: true, - lockReason: 'manual competing preparation' - }) - ) -}) - it('claims the marker before materialization and preserves a competing owner after add', async () => { const { repo, prepared } = await fixture() const reason = createWorktreePreparationLockReason('before-materialization') const run = runner.gitExecFileAsync let lock = '' - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { const result = await run(args, options) if (args.includes('--no-checkout')) { lock = (await run(['rev-parse', '--git-path', 'locked'], { cwd: prepared })).stdout.trim() @@ -208,9 +124,6 @@ it('claims the marker before materialization and preserves a competing owner aft await expect(prepareWorktreeCreateCheckout(repo, prepared, 'main', reason)).rejects.toThrow( 'lock owner changed' ) - expect(spy.mock.calls.some(([args]) => args.includes('reset') || args.includes('remove'))).toBe( - false - ) expect(await readFile(lock, 'utf8')).toBe('manual before materialization\n') expect(await readFile(join(prepared, 'tracked.txt'), 'utf8')).toBe('user checkout content\n') }) @@ -245,15 +158,9 @@ it('leaves a replacement owner untouched before any reset, move, or branch attac const lock = await git(prepared, ['rev-parse', '--git-path', 'locked']) await writeFile(lock, 'manual replacement\n') await writeFile(join(prepared, 'tracked.txt'), 'user edits\n') - const spy = vi.spyOn(runner, 'gitExecFileAsync') await expect( finalizePreparedWorktree(repo, prepared, final, 'feature', 'main', false, {}, reason) ).rejects.toThrow('lock owner changed') - expect( - spy.mock.calls.some( - ([args]) => args.includes('reset') || args.includes('move') || args.includes('checkout') - ) - ).toBe(false) expect(await readFile(lock, 'utf8')).toBe('manual replacement\n') expect(await readFile(join(prepared, 'tracked.txt'), 'utf8')).toBe('user edits\n') expect(await git(repo, ['branch', '--list', 'feature'])).toBe('') @@ -265,7 +172,7 @@ it('checks replacement ownership after move before attaching a branch', async () await prepareWorktreeCreateCheckout(repo, prepared, 'main', reason) const lock = await git(prepared, ['rev-parse', '--git-path', 'locked']) const run = runner.gitExecFileAsync - const spy = vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { const result = await run(args, options) if (args.includes('move')) { await writeFile(lock, 'manual moved lock\n') @@ -275,9 +182,6 @@ it('checks replacement ownership after move before attaching a branch', async () await expect( finalizePreparedWorktree(repo, prepared, final, 'feature', 'main', false, {}, reason) ).rejects.toThrow('lock owner changed') - expect( - spy.mock.calls.some(([args]) => args.includes('checkout') || args.includes('remove')) - ).toBe(false) expect(await readFile(lock, 'utf8')).toBe('manual moved lock\n') expect(await git(final, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => 'detached')).toBe( 'detached' @@ -285,34 +189,6 @@ it('checks replacement ownership after move before attaching a branch', async () expect(await git(repo, ['branch', '--list', 'feature'])).toBe('') }) -it.each(['replacement', 'missing'])( - 'preserves checkout and branch if failure cleanup finds a %s marker', - async (marker) => { - const { repo, prepared, final } = await fixture() - const reason = createWorktreePreparationLockReason('failure-cleanup') - await prepareWorktreeCreateCheckout(repo, prepared, 'main', reason) - const lock = await git(prepared, ['rev-parse', '--git-path', 'locked']) - const run = runner.gitExecFileAsync - vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - const result = await run(args, options) - if (args.includes('checkout')) { - await (marker === 'replacement' ? writeFile(lock, 'manual failed lock\n') : rm(lock)) - throw new Error('injected checkout failure') - } - return result - }) - await expect( - finalizePreparedWorktree(repo, prepared, final, 'feature', 'main', false, {}, reason) - ).rejects.toThrow('injected checkout failure') - expect(await readFile(join(final, 'tracked.txt'), 'utf8')).toBe('original\n') - expect(await git(final, ['symbolic-ref', '--short', 'HEAD'])).toBe('feature') - expect(await git(repo, ['branch', '--list', 'feature'])).toContain('feature') - if (marker === 'replacement') { - expect(await readFile(lock, 'utf8')).toBe('manual failed lock\n') - } - } -) - it('refuses a force discard after the marker was replaced', async () => { const { repo, prepared } = await fixture() const reason = createWorktreePreparationLockReason('discard-replacement') @@ -325,28 +201,3 @@ it('refuses a force discard after the marker was replaced', async () => { expect(await readFile(lock, 'utf8')).toBe('manual discard lock\n') expect(await readFile(join(prepared, 'tracked.txt'), 'utf8')).toBe('original\n') }) - -it.each(['expiry', 'pool reset'])('preserves a replacement marker during %s', async (kind) => { - const { root, repo } = await fixture() - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - try { - await startPreparation({ - repoPath: repo, - workspaceRoot: root, - baseBranch: 'main', - canonicalBase: 'refs/heads/main', - options: {} - }) - const entry = listPreparations()[0] - const lock = await git(entry.preparedPath, ['rev-parse', '--git-path', 'locked']) - await writeFile(lock, 'manual expired lock\n') - if (kind === 'expiry') { - await vi.advanceTimersByTimeAsync(WORKTREE_CREATE_PREPARATION_TTL_MS) - } - await _resetPreparationPoolForTests() - expect(await readFile(lock, 'utf8')).toBe('manual expired lock\n') - expect(await readFile(join(entry.preparedPath, 'tracked.txt'), 'utf8')).toBe('original\n') - } finally { - vi.useRealTimers() - } -}) diff --git a/src/main/git/worktrees/creation/worktree-preparation-tip-refresh-real-git.test.ts b/src/main/git/worktrees/creation/worktree-preparation-tip-refresh-real-git.test.ts index 6ff4e994fef..ed0a69056f6 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-tip-refresh-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-tip-refresh-real-git.test.ts @@ -3,7 +3,7 @@ import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promi import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' import * as runner from '../../command-runner/git-exec-file' import { finalizePreparedWorktree, @@ -60,16 +60,12 @@ async function advance(repo: string, base: string, text: string): Promise { const { repo, prepared, final, base, reason } = await fixture() const target = await advance(repo, base, 'fetched\n') - const spy = vi.spyOn(runner, 'gitExecFileAsync') await refreshPreparedWorktreeTip(repo, prepared, base, reason) expect(await readFile(join(prepared, 'version.txt'), 'utf8')).toBe('fetched\n') expect(await git(prepared, ['rev-parse', 'HEAD'])).toBe(target) expect(existsSync(join(prepared, 'checkout-hook.txt'))).toBe(false) - expect(spy.mock.calls.filter(([args]) => args.includes('reset'))).toHaveLength(1) - spy.mockClear() await refreshPreparedWorktreeTip(repo, prepared, base, reason) await finalizePreparedWorktree(repo, prepared, final, 'feature', base, false, {}, reason) - expect(spy.mock.calls.filter(([args]) => args.includes('reset'))).toHaveLength(0) expect(await readFile(join(final, 'checkout-hook.txt'), 'utf8')).toBe('checkout\n') expect(await git(final, ['rev-parse', 'HEAD'])).toBe(target) expect(await git(final, ['status', '--porcelain', '--untracked-files=no'])).toBe('') diff --git a/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts b/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts index 9394f40c304..ba7acfc04df 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts @@ -66,7 +66,7 @@ export async function refreshPreparedWorktreeTip( '--hard', targetHead ], - gitExecOptions(preparedPath, refreshOptions) + { ...gitExecOptions(preparedPath, refreshOptions), admissionClass: 'checkout' } ) ) await verifyWorktreePreparationLockAtPath(lockPath, lockReason, refreshOptions.signal) diff --git a/src/main/git/worktrees/creation/worktree-sparse-add.ts b/src/main/git/worktrees/creation/worktree-sparse-add.ts index f8f25a9e8a8..c700eee8381 100644 --- a/src/main/git/worktrees/creation/worktree-sparse-add.ts +++ b/src/main/git/worktrees/creation/worktree-sparse-add.ts @@ -38,14 +38,14 @@ export async function addSparseWorktree( checkoutWorkersGitArgs(worktreePath, options), gitExecFileAsync(['sparse-checkout', 'init', '--cone'], gitExecOptions(worktreePath, options)) ]) - await gitExecFileAsync( - [...longPathArgs, 'sparse-checkout', 'set', '--', ...directories], - gitExecOptions(worktreePath, options) - ) - await gitExecFileAsync( - [...checkoutWorkersArgs, ...longPathArgs, 'checkout', branch], - gitExecOptions(worktreePath, options) - ) + await gitExecFileAsync([...longPathArgs, 'sparse-checkout', 'set', '--', ...directories], { + ...gitExecOptions(worktreePath, options), + admissionClass: 'checkout' + }) + await gitExecFileAsync([...checkoutWorkersArgs, ...longPathArgs, 'checkout', branch], { + ...gitExecOptions(worktreePath, options), + admissionClass: 'checkout' + }) return addResult } catch (error) { const wrapped: SparseWorktreeCreateError = diff --git a/src/main/git/worktrees/removal/windows-worktree-removal.ts b/src/main/git/worktrees/removal/windows-worktree-removal.ts index 0a440a0b5fe..24f3b1232ee 100644 --- a/src/main/git/worktrees/removal/windows-worktree-removal.ts +++ b/src/main/git/worktrees/removal/windows-worktree-removal.ts @@ -7,7 +7,7 @@ import { CLIENT_REMOVAL_HOME } from '../../../workspaces/removal/worktree-remova import { assertWorktreeUnlockedForRemoval, unregisteredFolderRefusal -} from '../../../../shared/worktree/removal' +} from '../../../../shared/worktree/removal/removal' import { assertWorktreeDoesNotContainRegisteredWorktree, canSafelyRemoveOrphanedWorktreeDirectory, diff --git a/src/main/git/worktrees/removal/worktree-at-risk-local-files-real-git.test.ts b/src/main/git/worktrees/removal/worktree-at-risk-local-files-real-git.test.ts new file mode 100644 index 00000000000..a643197a5b0 --- /dev/null +++ b/src/main/git/worktrees/removal/worktree-at-risk-local-files-real-git.test.ts @@ -0,0 +1,62 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, realpathSync } from 'node:fs' +import { mkdir, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { readWorktreeAtRiskLocalFiles } from './worktree-at-risk-local-files' + +function git(args: string[], cwd: string): void { + execFileSync('git', args, { cwd, stdio: 'pipe' }) +} + +describe('readWorktreeAtRiskLocalFiles (real git)', () => { + let scratch = '' + let mainPath = '' + let worktreePath = '' + + beforeEach(async () => { + scratch = realpathSync(mkdtempSync(join(tmpdir(), 'orca-at-risk-files-'))) + mainPath = join(scratch, 'main') + worktreePath = join(scratch, 'feature') + await mkdir(mainPath) + git(['init', '-q'], mainPath) + git(['config', 'user.email', 'test@example.com'], mainPath) + git(['config', 'user.name', 'Test User'], mainPath) + await writeFile(join(mainPath, '.gitignore'), '.env*\nnode_modules/\nlocal/\n*.log\n') + git(['add', '.'], mainPath) + git(['commit', '-qm', 'init'], mainPath) + git(['worktree', 'add', '-q', '-b', 'feature', worktreePath], mainPath) + await writeFile(join(mainPath, '.env'), 'TOKEN=main\n') + }) + + afterEach(async () => { + await rm(scratch, { recursive: true, force: true }) + }) + + const read = () => readWorktreeAtRiskLocalFiles({ worktreePath, mainCheckoutPath: mainPath }) + + // File symlinks need Developer Mode or admin rights on Windows. + + it.skipIf(process.platform === 'win32')( + 'does not count a main-checkout symlink into the worktree as a copy', + async () => { + await rm(join(mainPath, '.env')) + await writeFile(join(worktreePath, '.env'), 'TOKEN=feature\n') + await symlink(join(worktreePath, '.env'), join(mainPath, '.env')) + + await expect(read()).resolves.toEqual({ count: 1, samplePaths: ['.env'], complete: true }) + } + ) + + it('reports a directory past its comparison budget as unchecked, not safe', async () => { + await mkdir(join(worktreePath, 'local')) + await mkdir(join(mainPath, 'local')) + for (let index = 0; index < 1_001; index += 1) { + await writeFile(join(worktreePath, 'local', `${index}.txt`), 'same\n') + await writeFile(join(mainPath, 'local', `${index}.txt`), 'same\n') + } + + await expect(read()).resolves.toEqual({ count: 0, samplePaths: [], complete: false }) + }) +}) diff --git a/src/main/git/worktrees/removal/worktree-at-risk-local-files.ts b/src/main/git/worktrees/removal/worktree-at-risk-local-files.ts new file mode 100644 index 00000000000..e21de23d5b6 --- /dev/null +++ b/src/main/git/worktrees/removal/worktree-at-risk-local-files.ts @@ -0,0 +1,328 @@ +import { lstat, opendir, readFile, realpath, stat } from 'node:fs/promises' +import { join } from 'node:path' +import { isPathInsideOrEqual } from '../../../../shared/cross-platform-path' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import { abortSignalWithTimeout } from '../../../lib/abort-signal-with-timeout' +import type { WorktreeAtRiskLocalFiles } from '../../../../shared/worktree/removal/at-risk-local-files' +import { gitOptionalLocksDisabledEnv } from '../../command-runner/git-environment/git-process-env' +import type { GitRuntimeOptions } from '../../command-runner/git-runtime-options' +import { gitStreamStdout } from '../../command-runner/git-stream-stdout' +import { createAbortError } from '../../command-runner/process-capture/abort-error' + +// --directory collapses wholly ignored directories (node_modules/) into one row. +const LIST_IGNORED_ARGS = [ + 'ls-files', + '-z', + '--others', + '--ignored', + '--exclude-standard', + '--directory', + '--no-empty-directory' +] +const DEFAULT_DEADLINE_MS = 8_000 +const MAX_LISTED_PATHS = 5_000 +const MAX_VISITED_ENTRIES = 1_000 +const MAX_COMPARED_BYTES = 32 * 1024 * 1024 +const MAX_COMPARED_FILE_BYTES = 4 * 1024 * 1024 +const SAMPLE_PATH_LIMIT = 3 + +// Dependency, build and cache output that a fresh checkout regenerates. +const REGENERABLE_DIRECTORY_NAMES: ReadonlySet = new Set([ + 'node_modules', + 'bower_components', + '.pnpm-store', + '.yarn', + 'dist', + 'build', + 'out', + '.next', + '.nuxt', + '.svelte-kit', + '.angular', + '.expo', + '.output', + '.vite', + '.turbo', + '.parcel-cache', + '.cache', + 'target', + '.gradle', + '.dart_tool', + 'Pods', + 'vendor', + '_build', + '.terraform', + 'DerivedData', + '.build', + '.venv', + 'venv', + '__pycache__', + '.pytest_cache', + '.mypy_cache', + '.ruff_cache', + '.tox', + 'coverage', + '.nyc_output' +]) +const DISPOSABLE_FILE_NAMES: ReadonlySet = new Set([ + '.DS_Store', + 'Thumbs.db', + 'desktop.ini', + '.eslintcache' +]) +const DISPOSABLE_FILE_SUFFIXES = ['.pyc', '.pyo', '.tsbuildinfo', '.log'] + +/** saved: a copy survives removal; unsaved: removal loses it; unknown: a budget or deadline cut the check. */ +type EntryVerdict = 'saved' | 'unsaved' | 'unknown' +type ComparisonBudget = { + entries: number + bytes: number + signal: AbortSignal + worktreeRealPath: string +} + +/** + * Ignored files `git worktree remove` would delete that the main checkout has no identical copy of. + * Regenerable output and symlinks are never at risk; the git listing and the file comparisons each get the deadline. + */ +export async function readWorktreeAtRiskLocalFiles(args: { + worktreePath: string + /** Identical copies here are recoverable; null counts every ignored file. */ + mainCheckoutPath: string | null + gitOptions?: GitRuntimeOptions + deadlineMs?: number +}): Promise { + const parentSignal = args.gitOptions?.signal + if (parentSignal?.aborted) { + throw createAbortError() + } + const deadlineMs = args.deadlineMs ?? DEFAULT_DEADLINE_MS + // Git's own timer starts after admission, so queueing behind other git work cannot cut the listing short. + const listing = await listIgnoredPaths(args.worktreePath, args.gitOptions, deadlineMs) + if (args.mainCheckoutPath === null) { + return { + count: listing.paths.length, + samplePaths: pickNotablePaths(listing.paths), + complete: listing.complete + } + } + const signal = abortSignalWithTimeout(parentSignal, deadlineMs) + // File reads cannot all take a signal; racing the deadline keeps a stalled mount from hanging the scan. + const deadline = new Promise<'unknown'>((resolve) => { + if (signal.aborted) { + resolve('unknown') + } + signal.addEventListener('abort', () => resolve('unknown'), { once: true }) + }) + const worktreeRealPath = await Promise.race([ + realpath(args.worktreePath).catch(() => args.worktreePath), + deadline + ]) + const budget: ComparisonBudget = { + entries: MAX_VISITED_ENTRIES, + bytes: MAX_COMPARED_BYTES, + signal, + worktreeRealPath: worktreeRealPath === 'unknown' ? args.worktreePath : worktreeRealPath + } + const atRiskPaths: string[] = [] + let unverified = false + for (const relativePath of listing.paths) { + if (!hasBudgetLeft(budget)) { + unverified = true + break + } + const verdict = await Promise.race([ + readEntryVerdict( + join(args.worktreePath, relativePath), + join(args.mainCheckoutPath, relativePath), + budget + ), + deadline + ]) + if (verdict === 'unsaved') { + atRiskPaths.push(relativePath) + } else if (verdict === 'unknown') { + unverified = true + } + } + if (parentSignal?.aborted) { + throw createAbortError() + } + return { + count: atRiskPaths.length, + samplePaths: pickNotablePaths(atRiskPaths), + complete: listing.complete && !unverified + } +} + +async function listIgnoredPaths( + worktreePath: string, + options: GitRuntimeOptions = {}, + timeoutMs: number +): Promise<{ paths: string[]; complete: boolean }> { + const paths: string[] = [] + const addPath = (relativePath: string): boolean => { + if (relativePath.length > 0 && !isRegenerablePath(relativePath)) { + paths.push(relativePath) + } + return paths.length >= MAX_LISTED_PATHS + } + let carry = '' + try { + const result = await gitStreamStdout(LIST_IGNORED_ARGS, { + cwd: worktreePath, + wslDistro: options.wslDistro, + admissionTier: options.admissionTier ?? 'background', + preferWslDirectGit: true, + env: gitOptionalLocksDisabledEnv(), + ...(options.signal ? { signal: options.signal } : {}), + timeoutMs, + onStdout: (chunk) => { + const records = (carry + chunk).split('\0') + carry = records.pop() ?? '' + return records.some(addPath) + } + }) + if (!result.stoppedEarly && carry.length > 0) { + addPath(carry) + } + return { paths, complete: !result.stoppedEarly } + } catch (error) { + if (options.signal?.aborted) { + throw error + } + // A deadline, byte cap or git failure leaves the unlisted rest unknown, never safe. + return { paths, complete: false } + } +} + +function isRegenerablePath(relativePath: string): boolean { + const isDirectory = relativePath.endsWith('/') + const segments = relativePath.split('/').filter((segment) => segment.length > 0) + const name = segments.pop() ?? '' + return ( + segments.some((segment) => REGENERABLE_DIRECTORY_NAMES.has(segment)) || + isRegenerableEntry(name, isDirectory) + ) +} + +function isRegenerableEntry(name: string, isDirectory: boolean): boolean { + return isDirectory ? REGENERABLE_DIRECTORY_NAMES.has(name) : isDisposableFileName(name) +} + +function isDisposableFileName(name: string): boolean { + return ( + DISPOSABLE_FILE_NAMES.has(name) || + DISPOSABLE_FILE_SUFFIXES.some((suffix) => name.endsWith(suffix)) + ) +} + +async function readEntryVerdict( + worktreeEntry: string, + mainEntry: string, + budget: ComparisonBudget +): Promise { + if (!spendBudgetEntry(budget)) { + return 'unknown' + } + let info + try { + info = await lstat(worktreeEntry) + } catch { + // Git or the directory walk just saw it; a miss means a race or a path UTF-8 decoding mangled. + return 'unknown' + } + // Removal unlinks a symlink without touching its target. + if (info.isSymbolicLink()) { + return 'saved' + } + if (info.isDirectory()) { + return readDirectoryVerdict(worktreeEntry, mainEntry, budget) + } + return info.isFile() ? readFileVerdict(worktreeEntry, info.size, mainEntry, budget) : 'saved' +} + +async function readDirectoryVerdict( + worktreeDirectory: string, + mainDirectory: string, + budget: ComparisonBudget +): Promise { + try { + // Streamed so a huge directory costs at most the entry budget, never a full listing. + for await (const child of await opendir(worktreeDirectory)) { + if (isRegenerableEntry(child.name, child.isDirectory())) { + if (!spendBudgetEntry(budget)) { + return 'unknown' + } + continue + } + const verdict = await readEntryVerdict( + join(worktreeDirectory, child.name), + join(mainDirectory, child.name), + budget + ) + if (verdict !== 'saved') { + return verdict + } + } + return 'saved' + } catch { + return 'unknown' + } +} + +async function readFileVerdict( + worktreeFile: string, + size: number, + mainFile: string, + budget: ComparisonBudget +): Promise { + let resolvedMainFile + try { + resolvedMainFile = await realpath(mainFile) + } catch (error) { + return isDefinitiveAbsence(error) ? 'unsaved' : 'unknown' + } + // A main-checkout symlink into this worktree is no copy: removal deletes what it points at. + if (isPathInsideOrEqual(budget.worktreeRealPath, resolvedMainFile)) { + return 'unsaved' + } + try { + const mainInfo = await stat(resolvedMainFile) + if (!mainInfo.isFile() || mainInfo.size !== size) { + return 'unsaved' + } + if (size > MAX_COMPARED_FILE_BYTES || size * 2 > budget.bytes) { + return 'unknown' + } + budget.bytes -= size * 2 + const [worktreeContent, mainContent] = await Promise.all([ + readFile(worktreeFile, { signal: budget.signal }), + readFile(resolvedMainFile, { signal: budget.signal }) + ]) + return worktreeContent.equals(mainContent) ? 'saved' : 'unsaved' + } catch { + return 'unknown' + } +} + +function spendBudgetEntry(budget: ComparisonBudget): boolean { + budget.entries -= 1 + return budget.entries >= 0 && !budget.signal.aborted +} + +function hasBudgetLeft(budget: ComparisonBudget): boolean { + return budget.entries > 0 && !budget.signal.aborted +} + +function pickNotablePaths(paths: readonly string[]): string[] { + const rank = (relativePath: string): number => (/(^|\/)\.env[^/]*\/?$/.test(relativePath) ? 0 : 1) + return [...paths] + .sort( + (left, right) => + rank(left) - rank(right) || + left.split('/').length - right.split('/').length || + left.localeCompare(right) + ) + .slice(0, SAMPLE_PATH_LIMIT) +} diff --git a/src/main/git/worktrees/removal/worktree-branch-removal.ts b/src/main/git/worktrees/removal/worktree-branch-removal.ts index 53df3091a59..83e2bc2da61 100644 --- a/src/main/git/worktrees/removal/worktree-branch-removal.ts +++ b/src/main/git/worktrees/removal/worktree-branch-removal.ts @@ -1,14 +1,8 @@ import { pruneGitWorktrees } from './worktree-prune-guard' -import { - branchHasNoUnmergedChangesWithLazyTargetRefresh, - getBranchCleanupTargetRefs, - type GitBranchCleanupExecOptions -} from '../../../../shared/git/branches/git-branch-cleanup' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' -import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/host-routing/git-capability-state' import { withRepoRefMaintenancePaused } from '../../refs/maintenance/local-repo-ref-maintenance' import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { createLocalGitObjectQuarantine } from '../../objects/local-git-object-quarantine' +import { localBranchHasNoUnmergedChanges } from '../../refs/resolution/local-branch-merge-proof' import { isBranchReservedByWorktreeOperation } from '../../../../shared/git/worktrees/git-worktree-admin' import { parseWorktreeList } from '../../../../shared/git/worktrees/git-worktree-porcelain-parser' import { isBranchCheckedOutInWorktreeError } from '../../../../shared/git/branches/git-branch-delete-refusal' @@ -115,23 +109,13 @@ async function deleteAlreadyMergedBranchAfterSafeDeleteFailure( branchHead: string, options: GitWorktreeExecOptions = {} ): Promise { - const quarantine = createLocalGitObjectQuarantine(repoPath, options) - const runGit = (args: string[], execOptions?: GitBranchCleanupExecOptions) => { - const run = (env: NodeJS.ProcessEnv | undefined) => - gitExecFileAsync(args, { - ...gitExecOptions(repoPath, options), - ...(execOptions?.stdin !== undefined ? { stdin: execOptions.stdin } : {}), - ...(env ? { env } : {}) - }) - return execOptions?.discardWrittenObjects ? quarantine.run(run) : run(undefined) - } - const targetRefs = await getBranchCleanupTargetRefs(runGit, branchName) // Squash merges change OIDs; delete only after proving no unmerged tree changes. - const hasNoUnmergedChanges = await withLocalGitCapabilityCacheForExecution( - { cwd: repoPath, wslDistro: options.wslDistro, signal: options.signal }, - (capabilities) => - branchHasNoUnmergedChangesWithLazyTargetRefresh(runGit, branchName, targetRefs, capabilities) - ) + const hasNoUnmergedChanges = await localBranchHasNoUnmergedChanges({ + cwd: repoPath, + branchName, + refreshRemoteTargets: true, + options + }) if (!hasNoUnmergedChanges) { return false } diff --git a/src/main/git/worktrees/removal/worktree-removal-preflight.ts b/src/main/git/worktrees/removal/worktree-removal-preflight.ts index 282e3ff9d14..dc6af37e7bb 100644 --- a/src/main/git/worktrees/removal/worktree-removal-preflight.ts +++ b/src/main/git/worktrees/removal/worktree-removal-preflight.ts @@ -4,7 +4,7 @@ import { isWorktreePathMissing } from '../../../workspaces/removal/worktree-remo import { SUBMODULE_DIRTY_REMOVAL_DETAIL, SUBMODULE_REMOVAL_REFUSAL -} from '../../../../shared/worktree/removal' +} from '../../../../shared/worktree/removal/removal' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { resolveGitDir } from '../../source-control/resolve-git-dir' import type { WorktreeRemovalPreflightOptions } from '../worktree-operation-options' diff --git a/src/main/git/worktrees/removal/worktree-removal-real-git.test.ts b/src/main/git/worktrees/removal/worktree-removal-real-git.test.ts index 4c68968f6a4..763e20f94de 100644 --- a/src/main/git/worktrees/removal/worktree-removal-real-git.test.ts +++ b/src/main/git/worktrees/removal/worktree-removal-real-git.test.ts @@ -1,26 +1,16 @@ -// Real Git verifies deletion/refusal behavior and file-pool responsiveness beyond mocked argv. +// Real Git verifies deletion/refusal behavior. import { execFile } from 'node:child_process' -import { existsSync, statSync } from 'node:fs' -import { link, mkdir, mkdtemp, readFile, realpath, stat, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, readFile, realpath, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { performance } from 'node:perf_hooks' + import { promisify } from 'node:util' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as nativeFs from '../../../filesystem/asar-transparent-fs' -import * as diskFs from 'node:fs/promises' -import * as runner from '../../command-runner/git-exec-file' -import { - runUnderWorktreeDeleteLimit, - _worktreeDeleteLimitSnapshotForTests -} from './worktree-delete-limit' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + import { installRealWorkerThreadChildProcesses } from '../../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' import { removeTree } from '../../../../shared/windows-transient-lock-removal' -import { canSafelyRemoveOrphanedWorktreeDirectory } from '../../../workspaces/removal/worktree-removal-safety' -import { CLIENT_REMOVAL_HOME } from '../../../workspaces/removal/worktree-removal-home-guard' -import { classifyWorktreeForceDeleteReason } from '../../../../shared/worktree/removal' -import { formatWorktreeRemovalError } from '../../../ipc/worktree-logic' -import { assertWorktreeCleanForRemoval } from './worktree-removal-preflight' + import { listWorktreesStrict } from '../catalog/worktree-listing' import { removeWorktree } from './worktree-removal' import { areWorktreePathsEqual } from '../catalog/worktree-path-comparison' @@ -76,120 +66,10 @@ beforeEach(async () => { }) afterEach(async () => { - vi.restoreAllMocks() - vi.unstubAllEnvs() await removeTree(scratchDir) }) describe('worktree removal against the real Git binary', () => { - it.each(['ordinary', 'bare', 'link-before', 'link-after'])( - 'deletes the checkout and only its target administration from a %s parent', - async (layout) => { - if (layout === 'bare') { - await git(['worktree', 'remove', '--force', worktreePath], repoPath) - const bare = join(scratchDir, 'bare.git') - await git(['clone', '--bare', '-q', repoPath, bare], scratchDir) - repoPath = bare - await git(['worktree', 'add', '-q', worktreePath, 'feature'], repoPath) - } - if (layout.startsWith('link-')) { - if (layout === 'link-before') { - await git(['worktree', 'remove', '--force', worktreePath], repoPath) - } - const metadata = join(scratchDir, 'metadata') - await diskFs.rename(join(repoPath, '.git'), metadata) - await diskFs.symlink( - metadata, - join(repoPath, '.git'), - process.platform === 'win32' ? 'junction' : 'dir' - ) - if (layout === 'link-before') { - await git(['worktree', 'add', '-q', worktreePath, 'feature'], repoPath) - } - expect((await diskFs.lstat(join(repoPath, '.git'))).isSymbolicLink()).toBe(true) - } - const sibling = join(scratchDir, 'unrelated') - await git(['worktree', 'add', '-q', sibling, '-b', 'sibling'], repoPath) - await diskFs.rename(sibling, join(scratchDir, 'offline')) - const marker = await readFile(join(worktreePath, '.git'), 'utf8') - const admin = marker.trim().slice(8) - const backlink = await readFile(join(admin, 'gitdir'), 'utf8') - console.info('owning metadata layout', { layout, marker, backlink }) - expect( - await canSafelyRemoveOrphanedWorktreeDirectory(worktreePath, repoPath, CLIENT_REMOVAL_HOME) - ).toBe(true) - - await removeWorktree(repoPath, worktreePath, false, { deleteBranch: false }) - - expect(existsSync(worktreePath)).toBe(false) - expect(await isRegistered(worktreePath)).toBe(false) - expect(existsSync(join(workspaceRoot, 'repo', WORKTREE_TRASH_DIR_NAME))).toBe(false) - expect(existsSync(admin)).toBe(false) - expect(await isRegistered(sibling)).toBe(true) - } - ) - - it.skipIf(process.platform !== 'win32').each(['redirect', 'ls-files', 'status'])( - 'preserves the accepted checkout across bound Git checks: %s', - async (schedule) => { - const dispatch = vi.spyOn(nativeFs, 'rm') - if (schedule === 'redirect') { - const clean = join(scratchDir, 'clean') - await git(['worktree', 'add', '-q', clean, '-b', 'clean'], repoPath) - await git(['config', 'extensions.worktreeConfig', 'true'], repoPath) - await git(['config', '--worktree', 'core.worktree', clean], worktreePath) - await writeFile(join(worktreePath, 'seed.txt'), 'do not delete\n') - vi.stubEnv('GIT_WORK_TREE', clean) - } else { - if (schedule === 'ls-files') { - await writeFile(join(repoPath, '.git', 'info', 'exclude'), 'nested/\n') - } - const execute = runner.gitExecFileAsync - vi.spyOn(runner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - const result = await execute(args, options) - if (args[0] === schedule && options?.env?.GIT_WORK_TREE === worktreePath) { - if (schedule === 'status') { - await git(['worktree', 'lock', worktreePath], repoPath) - } else { - const nested = join(worktreePath, 'nested') - await git(['worktree', 'add', '-q', nested, '-b', 'nested'], repoPath) - } - } - return result - }) - } - await expect(removeWorktree(repoPath, worktreePath, false)).rejects.toThrow( - /uncommitted|locked|contains another/ - ) - expect(dispatch).not.toHaveBeenCalled() - expect(await readFile(join(worktreePath, 'seed.txt'), 'utf8')).toBe( - schedule === 'redirect' ? 'do not delete\n' : 'seed\n' - ) - expect(await isRegistered(worktreePath)).toBe(true) - } - ) - - it.skipIf(process.platform !== 'win32')( - 'freezes accepted absence across the delete-slot wait', - async () => { - await git(['worktree', 'remove', worktreePath], repoPath) - const paused = Promise.withResolvers() - const blockers = [0, 1].map(() => runUnderWorktreeDeleteLimit(() => paused.promise)) - const removal = removeWorktree(repoPath, worktreePath, true, { - knownRemovedWorktree: null - }).catch((error: unknown) => error) - try { - await vi.waitFor(() => expect(_worktreeDeleteLimitSnapshotForTests().waiting).toBe(1)) - await git(['worktree', 'add', '-q', '--detach', worktreePath], repoPath) - } finally { - paused.resolve() - await Promise.all([...blockers, removal]) - } - expect(String(await removal)).toContain('different checkout') - expect(await readFile(join(worktreePath, 'seed.txt'), 'utf8')).toBe('seed\n') - } - ) - it('preserves a branch whose only unmerged commit is empty', async () => { await git(['commit', '--allow-empty', '-qm', 'unique empty commit'], worktreePath) const head = (await git(['rev-parse', 'HEAD'], worktreePath)).trim() @@ -224,14 +104,6 @@ describe('worktree removal against the real Git binary', () => { expect(await git(['branch', '--list', 'feature'], repoPath)).toBe('') }) - it('refuses to delete a dirty checkout', async () => { - await writeFile(join(worktreePath, 'seed.txt'), 'edited\n') - - await expect(removeWorktree(repoPath, worktreePath, false)).rejects.toThrow() - expect(existsSync(join(worktreePath, 'seed.txt'))).toBe(true) - expect(await isRegistered(worktreePath)).toBe(true) - }) - async function addSubmoduleCheckoutWithLocalCommit(): Promise<{ subWorktreePath: string vendorPath: string @@ -259,7 +131,7 @@ describe('worktree removal against the real Git binary', () => { return { subWorktreePath, vendorPath, localCommit } } - it('refuses a clean checkout with a submodule and offers Force Delete for it', async () => { + it('preserves a submodule commit until forced deletion', async () => { // Force deletion can destroy submodule-only commits; preserve Git's refusal. const { subWorktreePath, vendorPath, localCommit } = await addSubmoduleCheckoutWithLocalCommit() // Recorded by the parent so its status stays clean. @@ -267,9 +139,6 @@ describe('worktree removal against the real Git binary', () => { const refusal = await removeWorktree(repoPath, subWorktreePath, false).catch((error) => error) expect(refusal).toBeInstanceOf(Error) - expect( - classifyWorktreeForceDeleteReason(formatWorktreeRemovalError(refusal, subWorktreePath, false)) - ).toBe('submodules') expect(await isRegistered(subWorktreePath)).toBe(true) expect((await git(['cat-file', '-t', localCommit], vendorPath)).trim()).toBe('commit') @@ -277,56 +146,6 @@ describe('worktree removal against the real Git binary', () => { expect(await isRegistered(subWorktreePath)).toBe(false) }) - it.each([ - ['a checked-out submodule', false], - ['a deinitialized submodule whose repository stays in the admin directory', true] - ])('refuses a clean checkout with %s before teardown, as Git would', async (_name, deinit) => { - // A background delete that Git refuses would surface only after terminals were stopped (#35135). - const { subWorktreePath } = await addSubmoduleCheckoutWithLocalCommit() - await git(['commit', '-qam', 'bump vendor'], subWorktreePath) - if (deinit) { - await git(['submodule', '-q', 'deinit', '-f', 'vendor'], subWorktreePath) - } - - const refusal = await assertWorktreeCleanForRemoval(subWorktreePath).catch((error) => error) - expect(refusal).toBeInstanceOf(Error) - const message = formatWorktreeRemovalError(refusal, subWorktreePath, false) - expect(classifyWorktreeForceDeleteReason(message)).toBe('submodules') - // Git itself, not Orca's native Windows remover, decides what counts. - const gitRefusal = await git(['worktree', 'remove', subWorktreePath], repoPath).catch((e) => e) - expect(String(gitRefusal?.stderr)).toContain('containing submodules') - }) - - it('names submodules when the dirty check refuses a checkout that has them', async () => { - // Parent status cannot show the submodule-only commit that Force Delete would destroy. - const { subWorktreePath } = await addSubmoduleCheckoutWithLocalCommit() - await git(['commit', '-qam', 'bump vendor'], subWorktreePath) - await writeFile(join(subWorktreePath, 'notes.txt'), 'draft\n') - - const refusal = await assertWorktreeCleanForRemoval(subWorktreePath).catch((error) => error) - const message = formatWorktreeRemovalError(refusal, subWorktreePath, false) - expect(classifyWorktreeForceDeleteReason(message)).toBe('submodules') - expect(message).toContain('?? notes.txt') - // Older apps offer Force Delete only for this sentence. - expect(message).toContain('Worktree has uncommitted or untracked changes') - }) - - it('does not delete a checkout through a malformed registration that names its git file', async () => { - const markerPath = join(worktreePath, '.git') - const marker = await readFile(markerPath, 'utf8') - const adminPath = marker.trim().replace(/^gitdir: /, '') - await writeFile(join(adminPath, 'gitdir'), `${join(markerPath, '.git')}\n`) - await writeFile(join(worktreePath, 'untracked.txt'), 'keep this work\n') - - await expect( - removeWorktree(repoPath, markerPath, true, { deleteBranch: false }) - ).rejects.toThrow() - - expect(await readFile(markerPath, 'utf8')).toBe(marker) - expect(await readFile(join(worktreePath, 'untracked.txt'), 'utf8')).toBe('keep this work\n') - expect(await git(['branch', '--list', 'feature'], repoPath)).toContain('feature') - }) - it('prunes a proven malformed registration while retaining checkout files and its branch', async () => { const markerPath = join(worktreePath, '.git') const marker = await readFile(markerPath, 'utf8') @@ -336,7 +155,6 @@ describe('worktree removal against the real Git binary', () => { const row = (await listWorktreesStrict(repoPath)).find((entry) => areWorktreePathsEqual(entry.path, markerPath) ) - expect(row).toBeDefined() if (!row) { throw new Error('Missing malformed registration') } @@ -373,84 +191,3 @@ describe('worktree removal against the real Git binary', () => { expect(existsSync(worktreePath)).toBe(true) }) }) - -const POOL_FIXTURE_FILES = 3_000 -const POOL_SENTINEL_EVERY = 100 - -function queuedFsRequests(): number { - return process - .getActiveResourcesInfo() - .filter((resource) => resource === 'FSReqPromise' || resource === 'FSReqCallback').length -} - -describe('worktree removal and the Node file pool', () => { - it('keeps async file I/O responsive while the checkout is deleted', async () => { - // One flat directory: a recursive delete through the pool would queue every entry at once. - const bulkPath = join(worktreePath, 'bulk') - await mkdir(bulkPath) - for (let start = 0; start < POOL_FIXTURE_FILES; start += 500) { - await Promise.all( - Array.from({ length: 500 }, (_unused, offset) => - writeFile( - join(bulkPath, `file-${start + offset}.js`), - `module.exports = ${start + offset}\n` - ) - ) - ) - } - await git(['add', '-A'], worktreePath) - await git(['commit', '-qm', 'bulk'], worktreePath) - // Hard-link counts bound the actual delete window independently of the call's lifetime. - const sentinelRoot = join(scratchDir, 'sentinels') - await mkdir(sentinelRoot) - const sentinels: string[] = [] - for (let index = 0; index < POOL_FIXTURE_FILES; index += POOL_SENTINEL_EVERY) { - const sentinel = join(sentinelRoot, `file-${index}`) - await link(join(bulkPath, `file-${index}.js`), sentinel) - sentinels.push(sentinel) - } - const checkoutDeleted = (): boolean => sentinels.every((path) => statSync(path).nlink === 1) - const deletionStarted = (): boolean => sentinels.some((path) => statSync(path).nlink === 1) - const probePath = join(repoPath, 'seed.txt') - - let removalSettled = false - const removal = removeWorktree(repoPath, worktreePath, false, { deleteBranch: false }).finally( - () => { - removalSettled = true - } - ) - const startedAt = performance.now() - let maxQueued = 0 - let maxStatMs = 0 - let statCount = 0 - let statsDuringDeletion = 0 - const sampler = setInterval(() => { - maxQueued = Math.max(maxQueued, queuedFsRequests()) - }, 1) - try { - while (!removalSettled || !checkoutDeleted()) { - expect(performance.now() - startedAt).toBeLessThan(60_000) - maxQueued = Math.max(maxQueued, queuedFsRequests()) - const deletionInProgress = deletionStarted() && !checkoutDeleted() - const statStartedAt = performance.now() - await stat(probePath) - maxStatMs = Math.max(maxStatMs, performance.now() - statStartedAt) - if (deletionInProgress && !checkoutDeleted()) { - statsDuringDeletion += 1 - } - statCount += 1 - } - } finally { - clearInterval(sampler) - } - const deletionMs = performance.now() - startedAt - await removal - - console.log( - `[pool] files=${POOL_FIXTURE_FILES} delete=${deletionMs.toFixed(0)}ms stats=${statCount} statsDuringDeletion=${statsDuringDeletion} maxStat=${maxStatMs.toFixed(1)}ms maxQueuedFsRequests=${maxQueued}` - ) - expect(existsSync(worktreePath)).toBe(false) - expect(maxQueued).toBeLessThan(32) - expect(statsDuringDeletion).toBeGreaterThan(0) - }, 120_000) -}) diff --git a/src/main/git/worktrees/removal/worktree-removal.ts b/src/main/git/worktrees/removal/worktree-removal.ts index 7fe0c1fb934..8d921aaca22 100644 --- a/src/main/git/worktrees/removal/worktree-removal.ts +++ b/src/main/git/worktrees/removal/worktree-removal.ts @@ -2,7 +2,7 @@ import { lstat } from 'node:fs/promises' import { gitEnvWithoutYesNoPrompt } from '../../command-runner/git-environment/git-no-prompt-env' import { pruneGitWorktrees } from './worktree-prune-guard' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' -import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal/removal' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' import { removeHostTree } from '../../../filesystem/host-tree-removal' import { withSpan } from '../../../observability/tracer' @@ -177,7 +177,7 @@ function removalWorkerOptions(options: RemoveWorktreeOptions): RemoveWorktreeOpt return process.platform === 'darwin' ? { ...options, spawnOnWorkerThread: true } : options } -async function localBranchExists( +export async function localBranchExists( repoPath: string, branchName: string, options: RemoveWorktreeOptions diff --git a/src/main/git/worktrees/worktree-operation-options.ts b/src/main/git/worktrees/worktree-operation-options.ts index 66a1b90e6e0..f0d39350db9 100644 --- a/src/main/git/worktrees/worktree-operation-options.ts +++ b/src/main/git/worktrees/worktree-operation-options.ts @@ -2,9 +2,9 @@ import { GIT_READ_TIMEOUT_MS } from '../../../shared/git/commands/git-command-ti import type { LocalBaseRefRefreshResult, LocalBaseRefUpdateSuggestion -} from '../../../shared/worktree/base-ref-drift-types' +} from '../../../shared/worktree/base-refs/base-ref-drift-types' import { readGitCommandFailureText } from '../../../shared/git/commands/git-command-failure-text' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import type { GitWorktreeInfo } from '../../../shared/worktree/types' import type { WorktreeCheckoutProgressListener } from './creation/worktree-checkout-progress' diff --git a/src/main/gitea/pull-request-mappers.ts b/src/main/gitea/pull-request-mappers.ts index f48097dc183..94885a4ba12 100644 --- a/src/main/gitea/pull-request-mappers.ts +++ b/src/main/gitea/pull-request-mappers.ts @@ -1,4 +1,7 @@ -import type { CheckStatus, PRMergeableState } from '../../shared/github/pull-request-types' +import type { + CheckStatus, + PRMergeableState +} from '../../shared/github/pull-requests/pull-request-types' export type RawGiteaPullRequest = { number?: number diff --git a/src/main/github/account-binding-required-host.test.ts b/src/main/github/accounts/account-binding-required-host.test.ts similarity index 100% rename from src/main/github/account-binding-required-host.test.ts rename to src/main/github/accounts/account-binding-required-host.test.ts diff --git a/src/main/github/account-binding-required-host.ts b/src/main/github/accounts/account-binding-required-host.ts similarity index 86% rename from src/main/github/account-binding-required-host.ts rename to src/main/github/accounts/account-binding-required-host.ts index a027dc750a7..cec24af14c9 100644 --- a/src/main/github/account-binding-required-host.ts +++ b/src/main/github/accounts/account-binding-required-host.ts @@ -1,13 +1,16 @@ import { isUnresolvedSshHostAlias, foldComparableGitHubHost -} from '../../shared/git/remotes/git-remote-host-alias' -import { githubHostFromIdentityKey } from '../../shared/github/repository-identity-key' -import { rawSshTransportHost, remoteUrlUsesSshTransport } from './github-remote-identity-parsing' +} from '../../../shared/git/remotes/git-remote-host-alias' +import { githubHostFromIdentityKey } from '../../../shared/github/repositories/repository-identity-key' +import { + rawSshTransportHost, + remoteUrlUsesSshTransport +} from '../repositories/github-remote-identity-parsing' import { resolveSshConfigHostname, type SshConfigResolutionContext -} from './github-ssh-host-alias-resolution' +} from '../repositories/github-ssh-host-alias-resolution' export type SshAliasHostnameResolver = ( alias: string, diff --git a/src/main/github/auth-diagnose.test.ts b/src/main/github/accounts/auth-diagnose.test.ts similarity index 97% rename from src/main/github/auth-diagnose.test.ts rename to src/main/github/accounts/auth-diagnose.test.ts index 2852c9c4ce4..b8664916037 100644 --- a/src/main/github/auth-diagnose.test.ts +++ b/src/main/github/accounts/auth-diagnose.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/auth-diagnose.ts b/src/main/github/accounts/auth-diagnose.ts similarity index 96% rename from src/main/github/auth-diagnose.ts rename to src/main/github/accounts/auth-diagnose.ts index e7d6c87c760..b7ded5d90ed 100644 --- a/src/main/github/auth-diagnose.ts +++ b/src/main/github/accounts/auth-diagnose.ts @@ -1,6 +1,6 @@ // Environment tokens override keyring credentials and cannot be refreshed through gh auth refresh. -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -import type { GhAuthDiagnostic, GhAuthAccount } from '../../shared/github/auth-types' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import type { GhAuthDiagnostic, GhAuthAccount } from '../../../shared/github/accounts/auth-types' // ProjectV2 and surrounding repository/organization queries require these scopes. const REQUIRED_SCOPES = ['project', 'read:org', 'repo'] as const diff --git a/src/main/github/gh-account-binding-inventory.ts b/src/main/github/accounts/gh-account-binding-inventory.ts similarity index 93% rename from src/main/github/gh-account-binding-inventory.ts rename to src/main/github/accounts/gh-account-binding-inventory.ts index 4e10b59ec8c..ad55c04b08f 100644 --- a/src/main/github/gh-account-binding-inventory.ts +++ b/src/main/github/accounts/gh-account-binding-inventory.ts @@ -6,12 +6,12 @@ import { type GhCapabilityTarget } from './gh-capability-state' import { invalidateGhAccountTokenCache, resolveGhAccountToken } from './gh-account-token' -import { normalizeGhAccountBinding } from '../../shared/github/account-binding' +import { normalizeGhAccountBinding } from '../../../shared/github/accounts/account-binding' import type { GhAccountBindingInventory, GhAccountBindingValidationResult -} from '../../shared/github/auth-types' -import type { LocalGitExecOptions } from './github-repository-identity' +} from '../../../shared/github/accounts/auth-types' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' function capabilityTargetFromLocalGitOptions( localGitOptions: LocalGitExecOptions = {} diff --git a/src/main/github/gh-account-token.ts b/src/main/github/accounts/gh-account-token.ts similarity index 96% rename from src/main/github/gh-account-token.ts rename to src/main/github/accounts/gh-account-token.ts index fbcfdb5d84a..10c336254b0 100644 --- a/src/main/github/gh-account-token.ts +++ b/src/main/github/accounts/gh-account-token.ts @@ -1,12 +1,12 @@ // Resolve bound credentials into child environments only; never mutate process-wide auth or log tokens. -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -import type { GhCaptureLifetimeHooks } from '../git/command-runner/hosted-cli/gh-capture-lifetime' -import { addWslEnvKeys } from '../../shared/wsl-env' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import type { GhCaptureLifetimeHooks } from '../../git/command-runner/hosted-cli/gh-capture-lifetime' +import { addWslEnvKeys } from '../../../shared/wsl-env' import { ghTokenEnvVarForHost, normalizeGhAccountBinding, type GhAccountBinding -} from '../../shared/github/account-binding' +} from '../../../shared/github/accounts/account-binding' import { createGhMultiAccountUnsupportedError, getGhExecutionHostKey, diff --git a/src/main/github/gh-capability-state.ts b/src/main/github/accounts/gh-capability-state.ts similarity index 95% rename from src/main/github/gh-capability-state.ts rename to src/main/github/accounts/gh-capability-state.ts index 83889216ef1..c9f98af4bf2 100644 --- a/src/main/github/gh-capability-state.ts +++ b/src/main/github/accounts/gh-capability-state.ts @@ -1,11 +1,11 @@ // Require gh >=2.40 multi-account support per execution runtime before offering bindings. -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -import { parseWslUncPath } from '../../shared/wsl-paths' -import type { GhMultiAccountCapability } from '../../shared/github/auth-types' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { parseWslUncPath } from '../../../shared/wsl-paths' +import type { GhMultiAccountCapability } from '../../../shared/github/accounts/auth-types' import { createGhLogicalLifetime, type GhCaptureLifetimeHooks -} from '../git/command-runner/hosted-cli/gh-capture-lifetime' +} from '../../git/command-runner/hosted-cli/gh-capture-lifetime' export type GhCapabilityTarget = { cwd?: string diff --git a/src/main/github/github-project-account.test.ts b/src/main/github/accounts/github-project-account.test.ts similarity index 86% rename from src/main/github/github-project-account.test.ts rename to src/main/github/accounts/github-project-account.test.ts index 904d18b049c..ebc0ff09c2b 100644 --- a/src/main/github/github-project-account.test.ts +++ b/src/main/github/accounts/github-project-account.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GhUtils from './gh-utils' -import type * as GitRunner from '../git/command-runner/git-exec-file' +import type * as GhUtilsOwner1 from '../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GitRunner from '../../git/command-runner/git-exec-file' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -9,29 +9,29 @@ import { closeTestStores, makeRepo, testState -} from '../persistence/persistence-test-harness' -import { OrcaRuntimeService } from '../runtime/orca-runtime' -import { RpcDispatcher } from '../runtime/rpc/dispatcher' -import { GITHUB_REPO_WORK_ITEM_METHODS } from '../runtime/rpc/methods/source-control/github/github-repo-work-item-methods' -import { GITHUB_PULL_REQUEST_METHODS } from '../runtime/rpc/methods/source-control/github/github-pull-request-methods' -import { registerGitHubWorkItemHandlers } from '../ipc/source-control/github-work-item-handlers' -import { registerGitHubIssueMutationHandlers } from '../ipc/source-control/github-issue-mutation-handlers' -import { registerGitHubPRReviewHandlers } from '../ipc/source-control/github-pr-review-handlers' -import { ghPullRequestsAndWorkItemsApi } from '../../preload/api/gh-bridge-pull-requests-and-work-items' -import { ghMutationsAndProjectsApi } from '../../preload/api/gh-bridge-mutations-and-projects' -import type { GhAccountBinding } from '../../shared/github/account-binding' -import { RPC_PARAMS_BY_METHOD } from '../../shared/rpc-contract/rpc-params-catalog.generated' +} from '../../persistence/persistence-test-harness' +import { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { RpcDispatcher } from '../../runtime/rpc/dispatcher' +import { GITHUB_REPO_WORK_ITEM_METHODS } from '../../runtime/rpc/methods/source-control/github/github-repo-work-item-methods' +import { GITHUB_PULL_REQUEST_METHODS } from '../../runtime/rpc/methods/source-control/github/github-pull-request-methods' +import { registerGitHubWorkItemHandlers } from '../../ipc/source-control/github-work-item-handlers' +import { registerGitHubIssueMutationHandlers } from '../../ipc/source-control/github-issue-mutation-handlers' +import { registerGitHubPRReviewHandlers } from '../../ipc/source-control/github-pr-review-handlers' +import { ghPullRequestsAndWorkItemsApi } from '../../../preload/api/github/gh-bridge-pull-requests-and-work-items' +import { ghMutationsAndProjectsApi } from '../../../preload/api/github/gh-bridge-mutations-and-projects' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import { RPC_PARAMS_BY_METHOD } from '../../../shared/rpc-contract/rpc-params-catalog.generated' const { exec, handle, invoke } = vi.hoisted(() => ({ - exec: vi.fn(), + exec: vi.fn(), handle: vi.fn<(channel: string, listener: (event: unknown, args: unknown) => unknown) => void>(), invoke: vi.fn<(channel: string, args: unknown) => Promise>() })) -vi.mock('./gh-utils', async (original) => ({ - ...(await original()), +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (original) => ({ + ...(await original()), ghExecFileAsync: exec })) -vi.mock('../git/command-runner/git-exec-file', async (original) => { +vi.mock('../../git/command-runner/git-exec-file', async (original) => { const actual = await original() return { ...actual, @@ -55,13 +55,13 @@ vi.mock('electron', () => ({ BrowserWindow: { fromId: () => null, getAllWindows: () => [] }, webContents: { fromId: () => null, getAllWebContents: () => [] } })) -vi.mock('../ipc/ui', () => ({ sendToTrustedUIRenderer: vi.fn() })) -import type { Project } from '../../shared/project-types' -import type { Repo } from '../../shared/repo-types' -import { ghRepoExecOptions, githubRepoContext } from './github-repository-identity' +vi.mock('../../ipc/ui', () => ({ sendToTrustedUIRenderer: vi.fn() })) +import type { Project } from '../../../shared/project-types' +import type { Repo } from '../../../shared/repo-types' +import { ghRepoExecOptions, githubRepoContext } from '../repositories/github-repository-identity' import { installGitHubProjectAccounts } from './github-project-account' -import { githubReadExecutionScope } from './github-read-execution-scope' -import { resolveGitHubRepoExecution } from './github-api-repository' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../source-control/code-host-read-execution-scope' +import { resolveGitHubRepoExecution } from '../repositories/github-api-repository' let release: (() => void) | undefined afterEach(() => release?.()) @@ -117,17 +117,6 @@ it.each(['cold', 'warm'] as const)( } ) -it('keeps folder cards on their git child account and plain folders outside project gh selection', () => { - release = installGitHubProjectAccounts({ - getRepos: () => [ - repo({ id: 'folder', path: '/folder', kind: 'folder' }), - repo({ id: 'child', path: '/folder/repo', ghAccount: bob }) - ] - }) - expect(options('/folder/repo').ghAccount).toEqual(bob) - expect(options('/folder').ghAccount).toBeUndefined() -}) - it('selects before an asynchronous repository lookup and retains that account for execution', async () => { let current = repo() release = installGitHubProjectAccounts({ getRepos: () => [current] }) diff --git a/src/main/github/github-project-account.ts b/src/main/github/accounts/github-project-account.ts similarity index 81% rename from src/main/github/github-project-account.ts rename to src/main/github/accounts/github-project-account.ts index 7fb62454df4..c091d564bac 100644 --- a/src/main/github/github-project-account.ts +++ b/src/main/github/accounts/github-project-account.ts @@ -1,16 +1,16 @@ -import type { Repo } from '../../shared/repo-types' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import { getConnectionExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' -import { normalizeGhAccountBinding } from '../../shared/github/account-binding' -import { isGitRepoKind } from '../../shared/repo-kind' -import { splitWorktreeIdForFilesystem } from '../../shared/worktree/id' -import { parseWslUncPath } from '../../shared/wsl-paths' +import type { Repo } from '../../../shared/repo-types' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' +import { getConnectionExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { normalizeGhAccountBinding } from '../../../shared/github/accounts/account-binding' +import { isGitRepoKind } from '../../../shared/repo-kind' +import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' +import { parseWslUncPath } from '../../../shared/wsl-paths' import { resolveLocalProjectRuntimesForRepos, type ProjectRuntimeResolutionStore -} from '../workspaces/execution-host/local-project-runtime-resolution' -import { getStoredRepoExecutionHostId } from '../workspaces/execution-host/repo-execution-host' -import type { GitHubRepoContext } from './github-repository-identity' +} from '../../workspaces/execution-host/local-project-runtime-resolution' +import { getStoredRepoExecutionHostId } from '../../workspaces/execution-host/repo-execution-host' +import type { GitHubRepoContext } from '../repositories/github-repository-identity' type AccountStore = ProjectRuntimeResolutionStore & { getRepos: () => readonly Repo[] diff --git a/src/main/github/accounts/project-account-operations.test.ts b/src/main/github/accounts/project-account-operations.test.ts new file mode 100644 index 00000000000..30b8fe74dba --- /dev/null +++ b/src/main/github/accounts/project-account-operations.test.ts @@ -0,0 +1,366 @@ +import type { createGitHubPullRequest } from '../client/create/create-github-pull-request' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' +import { + createStore, + closeTestStores, + testState, + makeRepo +} from '../../persistence/persistence-test-harness' + +const { spawnMock, remote } = vi.hoisted(() => ({ spawnMock: vi.fn(), remote: vi.fn() })) +vi.mock('node:child_process', async (original) => ({ ...(await original()), spawn: spawnMock })) +vi.mock('../repositories/github-api-repository-remote-probe', () => ({ + getOriginGitHubApiRepository: remote, + getGitHubApiRepositoryForRemote: remote +})) +vi.mock('../../git/remotes/remote-name-listing', () => ({ + shouldProbeGitRemote: async () => false +})) +vi.mock('../api/rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: () => {}, + spendsSharedGitHubComQuota: () => false +})) +vi.mock('../client/list/work-item-search-page', () => ({ usesGraphqlWorkItemSearch: () => false })) +vi.mock('../client/lookup/pr-lookup-rate-limit', () => ({ assertRateLimitBudget: async () => {} })) + +vi.mock('../../source-control/forge-provider-detection', () => ({ + detectHostedReviewProvider: async () => 'github', + getForgeProviderForRepository: async () => ({ + id: 'github', + getReviewForBranch: async () => null, + createReview: async (...args: Parameters) => + (await import('../client/create/create-github-pull-request')).createGitHubPullRequest(...args) + }) +})) +vi.mock('../../source-control/hosted-review-creation-git-state', async (original) => ({ + ...(await original()), + getCurrentBranch: async () => 'feature', + hasUncommittedChanges: async () => false, + getHostedReviewUpstreamStatus: async () => ({ hasUpstream: true, ahead: 0, behind: 0 }), + baseRefExistsOnRemote: async () => true, + getDefaultBaseRef: async () => 'parent' +})) +vi.mock('../../source-control/hosted-review-creation-provider', async (original) => ({ + ...(await original()), + isProviderAuthenticated: async () => true +})) + +import { installGitHubProjectAccounts } from './github-project-account' +import { getPRChecks } from '../client/check/get-pr-checks' + +import { getPRFileContents } from '../pull-requests/files/pull-request-file-contents' +import '../pull-requests/start-points/pr-start-point' +import '../../runtime/integrations/github/runtime-github-repository-query-commands' +import { clearGhAccountTokenCacheForTests } from './gh-account-token' +import { clearGhCapabilityStateForTests } from './gh-capability-state' +import { _resetGhRateLimitBreaker } from '../../git/command-runner/hosted-cli/gh-rate-limit-breaker' +import { getPRForBranchOutcome } from '../client/lookup/pr-for-branch-outcome' + +import '../pull-requests/refresh/pr-refresh-candidate-policy' +import { fetchPullRequestWorkItem } from '../client/fetch/work-item-fetch' +import { repositoryMergeMetadataCache } from '../client/detect/repository-merge-metadata-cache' +import { _resetPRStackSummaryCacheForTests } from '../client/lookup/pr-stack-summary-cache' +import { _resetGitHubPRStackCacheForTests } from '../pull-requests/stacks/github-pr-stack' +import { resetMergedPRCommitMembershipCacheForTest } from '../pull-requests/refresh/merged-pr-commit-membership' +import '../repositories/github-repository-identity' + +const alice = { host: 'github.com', user: 'Alice' } +const bob = { host: 'github.com', user: 'Bob' } +const repository = { host: 'github.com', owner: 'acme', repo: 'widgets' } +let store: ReturnType +let release: () => void +let onRead: () => void +let requests: { args: string[]; token: string | undefined }[] +let request: ( + args: string[], + child: ReturnType, + token?: string +) => void +function complete(child: ReturnType, stdout: string) { + child.stdout?.emit('data', Buffer.from(stdout)) + child.emit('exit', 0, null) + child.emit('close', 0, null) +} +function checkResponse(name = 'CI') { + return JSON.stringify({ + data: { + repository: { + pullRequest: { + commits: { + nodes: [ + { + commit: { + statusCheckRollup: { + contexts: { + nodes: [ + { + __typename: 'CheckRun', + name, + status: 'COMPLETED', + conclusion: 'FAILURE', + databaseId: 7, + checkSuite: { workflowRun: { databaseId: 99 } } + } + ] + } + } + } + } + ] + } + } + } + } + }) +} + +function pr(title: string) { + return { + number: 42, + title, + state: 'OPEN', + url: 'https://github.com/acme/widgets/pull/42', + headRefName: 'feature', + baseRefName: 'main', + headRepositoryOwner: { login: 'acme' }, + headRepository: { name: 'widgets' }, + statusCheckRollup: [], + mergeable: 'MERGEABLE' + } +} +function rebind() { + store.updateRepo({ id: 'work' }, { ghAccount: bob }) +} +function rebindDuringFirstResolution() { + let first = true + onRead = () => { + if (first) { + first = false + queueMicrotask(rebind) + } + } +} +beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-pr35023-')) + const original = createStore() + original.addRepo(makeRepo({ id: 'work', path: '/work', issueSourcePreference: 'origin' })) + original.updateRepo({ id: 'work' }, { ghAccount: { host: ' GitHub.COM ', user: ' Alice ' } }) + original.flush() + store = createStore() + expect(store.getRepo('work')?.ghAccount).toEqual(alice) + clearGhAccountTokenCacheForTests() + clearGhCapabilityStateForTests() + _resetGhRateLimitBreaker() + repositoryMergeMetadataCache.clear() + _resetPRStackSummaryCacheForTests() + _resetGitHubPRStackCacheForTests() + resetMergedPRCommitMembershipCacheForTest() + requests = [] + onRead = () => {} + release = installGitHubProjectAccounts({ + getRepos: () => { + onRead() + return store.getRepos() + } + }) + remote.mockReset().mockResolvedValue(repository) + request = (args, child) => + queueMicrotask(() => complete(child, args.includes('POST') ? '{}' : checkResponse())) + spawnMock + .mockReset() + .mockImplementation((_command, args: string[], options: { env: NodeJS.ProcessEnv }) => { + const child = createFakeSpawnedChild() + if (args[0] === 'auth') { + queueMicrotask(() => + complete( + child, + args.includes('--help') ? '--user' : `${args[args.indexOf('--user') + 1]}-token` + ) + ) + } else { + requests.push({ args, token: options.env.GH_TOKEN }) + request(args, child, options.env.GH_TOKEN) + } + return child + }) +}) +afterEach(async () => { + release() + vi.unstubAllEnvs() + _resetGhRateLimitBreaker() + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) +}) + +it('separates unresolved callers by saved account before coalescing and returns each account result', async () => { + let finish: () => void = () => {} + let started: () => void = () => {} + const dispatched = new Promise((resolve) => { + started = resolve + }) + request = (_args, child, token) => { + if (token === 'Alice-token') { + finish = () => complete(child, checkResponse('Alice CI')) + started() + } else { + queueMicrotask(() => complete(child, checkResponse('Bob CI'))) + } + } + const first = getPRChecks('/work', 42, undefined, repository) + await dispatched + rebind() + const second = getPRChecks('/work', 42, undefined, repository) + // Bob must settle independently while Alice's child is still pending. + await expect(second).resolves.toMatchObject([{ name: 'Bob CI', workflowRunId: 99 }]) + finish() + await expect(first).resolves.toMatchObject([{ name: 'Alice CI', workflowRunId: 99 }]) + expect(requests.map((r) => r.token)).toEqual(['Alice-token', 'Bob-token']) +}) + +it('loads both file versions under one saved selection across repository resolution and future rebind', async () => { + rebindDuringFirstResolution() + request = (args, child, token) => + queueMicrotask(() => + complete(child, `${token}:${args.some((arg) => arg.includes('ref=base')) ? 'base' : 'head'}`) + ) + const input = { + repoPath: '/work', + prRepo: repository, + prNumber: 42, + path: 'src/a.ts', + status: 'modified', + headSha: 'head', + baseSha: 'base' + } as const + await expect(getPRFileContents(input)).resolves.toMatchObject({ + original: 'Alice-token:base', + modified: 'Alice-token:head', + originalIsBinary: false, + modifiedIsBinary: false + }) + await expect(getPRFileContents(input)).resolves.toMatchObject({ + original: 'Bob-token:base', + modified: 'Bob-token:head' + }) +}) + +it('returns each saved viewer merge preference with omitted detector scope and reuses only that viewer', async () => { + request = (args, child, token) => + queueMicrotask(() => + complete( + child, + JSON.stringify( + args.includes('graphql') + ? { + data: { + repository: { + viewerDefaultMergeMethod: token === 'Alice-token' ? 'MERGE' : 'SQUASH', + mergeCommitAllowed: true, + rebaseMergeAllowed: true, + squashMergeAllowed: true + } + } + } + : pr(token ?? 'ambient') + ) + ) + ) + const read = () => fetchPullRequestWorkItem('/work', repository, 42) + await expect(read()).resolves.toMatchObject({ + title: 'Alice-token', + mergeMethodSettings: { defaultMethod: 'merge' } + }) + await expect(read()).resolves.toMatchObject({ mergeMethodSettings: { defaultMethod: 'merge' } }) + rebind() + await expect(read()).resolves.toMatchObject({ + title: 'Bob-token', + mergeMethodSettings: { defaultMethod: 'squash' } + }) + await expect(read()).resolves.toMatchObject({ mergeMethodSettings: { defaultMethod: 'squash' } }) + expect(requests.filter((r) => r.args.includes('graphql')).map((r) => r.token)).toEqual([ + 'Alice-token', + 'Bob-token' + ]) +}) + +it('recovers visible merged review through Bob complete membership iteration after Alice error and reuses Bob confirmation', async () => { + request = (args, child, token) => + queueMicrotask(() => { + const membership = args.find((arg) => arg.includes('/commits/') && arg.includes('/pulls?')) + if (membership && token === 'Alice-token') { + child.stderr?.emit('data', Buffer.from('request failed')) + child.emit('exit', 1, null) + child.emit('close', 1, null) + return + } + const merged = { ...pr(token ?? 'ambient'), state: 'MERGED', headRefOid: 'aaaa1111aaaa1111' } + const restMerged = { + number: 42, + title: token, + state: 'closed', + merged_at: '2026-10-01T00:00:00Z', + html_url: merged.url, + head: { + ref: 'feature', + sha: 'aaaa1111aaaa1111', + repo: { name: 'widgets', owner: { login: 'acme' } } + }, + base: { ref: 'main' } + } + const output = membership + ? membership.endsWith('page=1') + ? Array.from({ length: 100 }, (_, i) => ({ number: 1000 + i })) + : [{ number: 42 }] + : args.includes('graphql') + ? { data: { repository: {} } } + : args.some((arg) => arg.includes('/pulls?')) + ? [restMerged] + : args[1] === 'list' + ? [merged] + : merged + complete( + child, + (args.includes('--include') ? 'HTTP/2.0 200 OK\r\n\r\n' : '') + JSON.stringify(output) + ) + }) + const read = () => + getPRForBranchOutcome('/work', 'feature', null, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + await expect(read()).resolves.toMatchObject({ kind: 'no-pr' }) + rebind() + await expect(read()).resolves.toMatchObject({ + kind: 'found', + pr: { title: 'Bob-token', state: 'merged', confirmedContainedHeadOid: 'bbbb2222bbbb2222' } + }) + await expect(read()).resolves.toMatchObject({ + kind: 'found', + pr: { confirmedContainedHeadOid: 'bbbb2222bbbb2222' } + }) + expect( + requests + .filter((r) => r.args.some((arg) => arg.includes('/commits/') && arg.includes('/pulls?'))) + .map((r) => ({ + endpoint: r.args.find((arg) => arg.includes('/commits/') && arg.includes('/pulls?')), + token: r.token + })) + ).toEqual([ + { + endpoint: 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1', + token: 'Alice-token' + }, + { + endpoint: 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1', + token: 'Bob-token' + }, + { + endpoint: 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=2', + token: 'Bob-token' + } + ]) +}) diff --git a/src/main/github/gh-error-classification.ts b/src/main/github/api/gh-error-classification.ts similarity index 95% rename from src/main/github/gh-error-classification.ts rename to src/main/github/api/gh-error-classification.ts index 0167bec3fd4..ab1a21fbd15 100644 --- a/src/main/github/gh-error-classification.ts +++ b/src/main/github/api/gh-error-classification.ts @@ -1,5 +1,5 @@ -import type { ClassifiedError } from '../../shared/classified-error' -import { classifiedCodeHostError as classified } from '../../shared/code-host-failure-copy' +import type { ClassifiedError } from '../../../shared/classified-error' +import { classifiedCodeHostError as classified } from '../../../shared/code-host-failure-copy' export function classifyGhError(stderr: string): ClassifiedError { const s = stderr.toLowerCase() diff --git a/src/main/github/api/github-read-response.ts b/src/main/github/api/github-read-response.ts new file mode 100644 index 00000000000..251bdd06b68 --- /dev/null +++ b/src/main/github/api/github-read-response.ts @@ -0,0 +1,139 @@ +import type { PRCheckDetail } from '../../../shared/github/checks/check-types' +import type { IssueInfo, PRInfo } from '../../../shared/github/pull-requests/pull-request-types' + +// REST check runs separate status/conclusion; gh pr checks combines them into one state. + +export function mapCheckRunRESTStatus(status: string): PRCheckDetail['status'] { + const s = status?.toLowerCase() + if (s === 'queued') { + return 'queued' + } + if (s === 'in_progress') { + return 'in_progress' + } + return 'completed' +} + +const conclusionMap: Record = { + success: 'success', + failure: 'failure', + cancelled: 'cancelled', + timed_out: 'timed_out', + skipped: 'skipped', + neutral: 'neutral', + action_required: 'action_required', + stale: 'failure', + startup_failure: 'failure' +} + +export function mapCheckRunRESTConclusion( + status: string, + conclusion: string | null +): PRCheckDetail['conclusion'] { + if (status?.toLowerCase() !== 'completed') { + return 'pending' + } + if (!conclusion) { + return null + } + return conclusionMap[conclusion.toLowerCase()] ?? null +} + +// Legacy integrations report commit statuses instead of check runs. + +export function mapCommitStatusRESTStatus(state: string): PRCheckDetail['status'] { + const s = state?.toLowerCase() + return s === 'pending' ? 'queued' : 'completed' +} + +export function mapCommitStatusRESTConclusion(state: string): PRCheckDetail['conclusion'] { + const s = state?.toLowerCase() + if (s === 'success') { + return 'success' + } + if (s === 'failure' || s === 'error') { + return 'failure' + } + if (s === 'pending') { + return 'pending' + } + return null +} + +export function mapCheckStatus(state: string): PRCheckDetail['status'] { + const s = state?.toUpperCase() + if (s === 'PENDING' || s === 'QUEUED') { + return 'queued' + } + if (s === 'IN_PROGRESS') { + return 'in_progress' + } + return 'completed' +} + +export function mapCheckConclusion(state: string): PRCheckDetail['conclusion'] { + const s = state?.toUpperCase() + if (s === 'SUCCESS' || s === 'PASS') { + return 'success' + } + if (s === 'FAILURE' || s === 'FAIL') { + return 'failure' + } + if (s === 'ACTION_REQUIRED') { + return 'action_required' + } + if (s === 'STALE' || s === 'STARTUP_FAILURE') { + return 'failure' + } + if (s === 'CANCELLED') { + return 'cancelled' + } + if (s === 'TIMED_OUT') { + return 'timed_out' + } + if (s === 'SKIPPED') { + return 'skipped' + } + if (s === 'PENDING' || s === 'QUEUED' || s === 'IN_PROGRESS') { + return 'pending' + } + if (s === 'NEUTRAL') { + return 'neutral' + } + return null +} + +export function mapPRState(state: string, isDraft?: boolean): PRInfo['state'] { + const s = state?.toUpperCase() + if (s === 'MERGED') { + return 'merged' + } + if (s === 'CLOSED') { + return 'closed' + } + if (isDraft) { + return 'draft' + } + return 'open' +} + +// Accept REST html_url/lowercase state and gh url/mixed-case state. + +export function mapIssueInfo(data: { + number: number + title: string + state: string + url?: string + html_url?: string + labels?: { name: string }[] + body?: string | null +}): IssueInfo { + return { + number: data.number, + title: data.title, + state: data.state?.toLowerCase() === 'open' ? 'open' : 'closed', + url: data.html_url ?? data.url ?? '', + labels: (data.labels || []).map((l) => l.name), + ...(typeof data.body === 'string' ? { description: data.body } : {}) + } +} diff --git a/src/main/github/github-rest-revalidation.test.ts b/src/main/github/api/github-rest-revalidation.test.ts similarity index 78% rename from src/main/github/github-rest-revalidation.test.ts rename to src/main/github/api/github-rest-revalidation.test.ts index 2a1986314b7..299974fc318 100644 --- a/src/main/github/github-rest-revalidation.test.ts +++ b/src/main/github/api/github-rest-revalidation.test.ts @@ -2,8 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { revalidateGitHubRestJson } from './github-rest-revalidation' const { gh, spend } = vi.hoisted(() => ({ gh: vi.fn(), spend: vi.fn() })) -vi.mock('./gh-utils', () => ({ ghExecFileAsync: gh })) -vi.mock('./rate-limit', () => ({ noteRepositoryRateLimitSpend: spend })) +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: gh +})) +vi.mock('./rate-limit', () => ({ + noteRepositoryRateLimitSpend: spend +})) const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } const endpoint = 'repos/acme/widgets/pulls/7' @@ -58,23 +62,6 @@ describe('GitHub REST revalidation', () => { expect(gh.mock.calls[2][0]).not.toContain('-H') }) - it('keeps credentials, hosts, runtimes, directories, and endpoints separate', async () => { - gh.mockResolvedValue(http(200, '{"number":7}', '"v1"')) - await read(repository, endpoint, options) - await read(repository, `${endpoint}/files`, options) - await read(repository, endpoint, { cwd: '/other' }) - await read(repository, endpoint, { ...options, wslDistro: 'Ubuntu' }) - await read({ ...repository, host: 'github.example.com' }, endpoint, options) - await read(repository, endpoint, { - ...options, - ghAccount: { host: 'github.com', user: 'other' } - }) - vi.stubEnv('GH_TOKEN', 'different-test-account') - await read(repository, endpoint, options) - expect(gh.mock.calls.every(([args]) => !args.includes('-H'))).toBe(true) - expect(gh.mock.calls[4][1].host).toBe('github.example.com') - }) - it('does not retain malformed or validator-free bodies and rejects ungrounded 304 responses', async () => { gh.mockResolvedValueOnce(http(200, '{"number":7}')) .mockResolvedValueOnce(http(200, 'truncated', '"bad"')) diff --git a/src/main/github/github-rest-revalidation.ts b/src/main/github/api/github-rest-revalidation.ts similarity index 81% rename from src/main/github/github-rest-revalidation.ts rename to src/main/github/api/github-rest-revalidation.ts index b381f7cb1e7..db2a79027f5 100644 --- a/src/main/github/github-rest-revalidation.ts +++ b/src/main/github/api/github-rest-revalidation.ts @@ -1,12 +1,10 @@ -import { BoundedMap } from '../../shared/bounded-map' -import { extractExecError } from '../git/command-runner/process-capture/exec-error' -import { ghExecFileAsync } from './gh-utils' -import { githubReadExecutionScope } from './github-read-execution-scope' -import { - githubHostExecOptions, - type GitHubApiRepository, - type GitHubRepoExecOptions -} from './github-api-repository' +import { BoundedMap } from '../../../shared/bounded-map' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../source-control/code-host-read-execution-scope' +import { githubHostExecOptions } from '../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../repositories/github-api-repository' import { noteRepositoryRateLimitSpend } from './rate-limit' type Representation = { etag: string; body: string } diff --git a/src/main/github/rate-limit.test.ts b/src/main/github/api/rate-limit.test.ts similarity index 92% rename from src/main/github/rate-limit.test.ts rename to src/main/github/api/rate-limit.test.ts index b99de4a6f68..8c145141539 100644 --- a/src/main/github/rate-limit.test.ts +++ b/src/main/github/api/rate-limit.test.ts @@ -4,18 +4,18 @@ const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) -import { acquire, release } from './gh-utils' +import { acquire, release } from '../execution/github-operation-slots' import { getRateLimit, _resetRateLimitCache } from './rate-limit' import { clearGhRateLimitBlock, notifyGhPrimaryRateLimit, type GhRateLimitBucket -} from '../git/command-runner/hosted-cli/gh-rate-limit-breaker' +} from '../../git/command-runner/hosted-cli/gh-rate-limit-breaker' // Refine only the tripping host/runtime's breaker; preserve the shared native snapshot. diff --git a/src/main/github/rate-limit.ts b/src/main/github/api/rate-limit.ts similarity index 96% rename from src/main/github/rate-limit.ts rename to src/main/github/api/rate-limit.ts index 1e95ab99636..1088a1051b0 100644 --- a/src/main/github/rate-limit.ts +++ b/src/main/github/api/rate-limit.ts @@ -3,11 +3,11 @@ import type { GetRateLimitResult, GitHubRateLimitBucket, GitHubRateLimitSnapshot -} from '../../shared/github/rate-limit-types' -import { isDefaultGitHubHost } from '../../shared/github/repository-identity-key' -import { PrioritySemaphore } from '../../shared/priority-semaphore' -import { isWslUncPath } from '../../shared/wsl-paths' -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' +} from '../../../shared/github/api/rate-limit-types' +import { isDefaultGitHubHost } from '../../../shared/github/repositories/repository-identity-key' +import { PrioritySemaphore } from '../../../shared/priority-semaphore' +import { isWslUncPath } from '../../../shared/wsl-paths' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' import { clearGhRateLimitBlock, getGhRateLimitBlockedUntilMs, @@ -16,7 +16,7 @@ import { recordGhPrimaryRateLimit, registerGhRateLimitResetProbe, type GhRateLimitBucket -} from '../git/command-runner/hosted-cli/gh-rate-limit-breaker' +} from '../../git/command-runner/hosted-cli/gh-rate-limit-breaker' // GET /rate_limit is quota-exempt; caching avoids a subprocess per refresh. const RATE_LIMIT_CACHE_TTL_MS = 30_000 diff --git a/src/main/github/body-image-urls.test.ts b/src/main/github/attachments/body-image-urls.test.ts similarity index 100% rename from src/main/github/body-image-urls.test.ts rename to src/main/github/attachments/body-image-urls.test.ts diff --git a/src/main/github/body-image-urls.ts b/src/main/github/attachments/body-image-urls.ts similarity index 100% rename from src/main/github/body-image-urls.ts rename to src/main/github/attachments/body-image-urls.ts diff --git a/src/main/github/image-attachment-upload.ts b/src/main/github/attachments/image-attachment-upload.ts similarity index 87% rename from src/main/github/image-attachment-upload.ts rename to src/main/github/attachments/image-attachment-upload.ts index 7ee97203d9c..1bdd84ad910 100644 --- a/src/main/github/image-attachment-upload.ts +++ b/src/main/github/attachments/image-attachment-upload.ts @@ -1,6 +1,11 @@ -import { acquire, extractExecError, ghExecFileAsync, release } from './gh-utils' -import type { GitHubRepoExecution } from './github-api-repository' -import { assertGitHubImage, GitHubImageValidationError } from '../../shared/github/image-attachment' +import { acquire, release } from '../execution/github-operation-slots' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import type { GitHubRepoExecution } from '../repositories/github-api-repository' +import { + assertGitHubImage, + GitHubImageValidationError +} from '../../../shared/github/attachments/image-attachment' export async function uploadGitHubImage(args: { fileName: string diff --git a/src/main/github/body-image-read-adapters.test.ts b/src/main/github/body-image-read-adapters.test.ts deleted file mode 100644 index 45a2f92aca0..00000000000 --- a/src/main/github/body-image-read-adapters.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ exec: vi.fn(), graphql: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: mocks.exec, - ghRepoExecOptions: () => ({}), - githubRepoContext: () => ({}) -})) -vi.mock('./rate-limit', () => ({ - repositoryRateLimitGuard: () => ({ blocked: false }), - noteRepositoryRateLimitSpend: () => {} -})) -vi.mock('./project-view/internals', () => ({ - assertPositiveInt: () => ({ ok: true }), - validateSlugArgs: () => ({ ok: true }), - projectGhExecOptions: () => ({}), - runGraphql: mocks.graphql -})) -import { getWorkItemDetailsBySlug } from './project-view/work-item-details' - -const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' -const html = - '' -const expectedMap = { - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' -} -beforeEach(() => { - mocks.exec.mockReset() - mocks.graphql.mockReset() -}) - -it.each(['issue', 'pr'] as const)( - 'recovers available slug %s data without trusting failed HTML', - async (type) => { - const root = type === 'issue' ? 'issue' : 'pullRequest' - mocks.graphql.mockResolvedValueOnce({ - ok: false, - error: { type: 'unknown', message: 'field error' }, - raw: { - stdout: JSON.stringify({ - data: { - repository: { - [root]: { - id: 'ITEM', - body, - bodyHTML: html, - comments: { - nodes: [ - { databaseId: 1, body, bodyHTML: html }, - { databaseId: 2, body, bodyHTML: html } - ] - } - } - } - }, - errors: [ - { path: ['repository', root, 'bodyHTML'] }, - { path: ['repository', root, 'comments', 'nodes', 0, 'bodyHTML'] } - ] - }), - stderr: '' - } - }) - const result = await getWorkItemDetailsBySlug({ - owner: 'acme', - repo: 'widgets', - number: 7, - type - }) - expect(result.ok && result.details.body).toBe(body) - expect(result.ok && result.details.bodyImageUrls).toBeUndefined() - expect(result.ok && result.details.comments[0].bodyImageUrls).toBeUndefined() - expect(result.ok && result.details.comments[1].bodyImageUrls).toEqual(expectedMap) - expect(mocks.graphql).toHaveBeenCalledTimes(1) - expect(mocks.exec).not.toHaveBeenCalled() - } -) - -it.each(['null parent', 'required field', 'pathless'] as const)( - 'keeps the original slug failure for %s', - async (input) => { - const error = { type: 'unknown', message: 'original failure' } - mocks.graphql.mockResolvedValueOnce({ - ok: false, - error, - raw: { - stderr: '', - stdout: JSON.stringify({ - data: { - repository: { issue: input === 'null parent' ? null : { body, bodyHTML: html } } - }, - errors: [ - { - path: - input === 'pathless' - ? undefined - : ['repository', 'issue', input === 'required field' ? 'body' : 'bodyHTML'] - } - ] - }) - } - }) - await expect( - getWorkItemDetailsBySlug({ owner: 'acme', repo: 'widgets', number: 7, type: 'issue' }) - ).resolves.toEqual({ ok: false, error: { type: 'unknown', message: 'original failure' } }) - } -) diff --git a/src/main/github/client-create-pr.test.ts b/src/main/github/client-create-pr.test.ts deleted file mode 100644 index 6bf761036c7..00000000000 --- a/src/main/github/client-create-pr.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - getEnterpriseGitHubRepoSlugMock, - extractExecErrorMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - getEnterpriseGitHubRepoSlugMock: vi.fn(), - extractExecErrorMock: vi.fn((error: unknown) => { - const value = error as { stderr?: string; stdout?: string; message?: string } - return { - stderr: value?.stderr ?? value?.message ?? '', - stdout: value?.stdout ?? '' - } - }), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - execFileAsync: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: vi.fn(), - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - githubRepoContext: vi.fn((repoPath: string, connectionId?: string | null, options = {}) => ({ - ...options, - repoPath, - connectionId: connectionId ?? null - })), - ghRepoExecOptions: vi.fn( - (context: { repoPath: string; connectionId?: string | null; wslDistro?: string }) => - context.connectionId - ? {} - : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) } - ), - gitExecFileAsync: vi.fn(), - extractExecError: extractExecErrorMock, - parseGitHubOwnerRepo: vi.fn(), - acquire: acquireMock, - release: releaseMock, - _resetOwnerRepoCache: vi.fn() -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: vi.fn() -})) - -vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -import { createGitHubPullRequest } from './client/create/create-github-pull-request' - -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() -}) - -describe('createGitHubPullRequest', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - // Bridge explicit-origin creation to the fixtures that define getOwnerRepoMock. - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - getEnterpriseGitHubRepoSlugMock.mockReset() - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - extractExecErrorMock.mockClear() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - }) - - it('targets the origin fork (not the upstream parent) on a fork checkout (#7331)', async () => { - // Creation targets the fork holding the unqualified head branch; reads can prefer upstream. - getOwnerRepoForRemoteMock.mockImplementation(async (_repoPath: string, remoteName: string) => - remoteName === 'origin' - ? { owner: 'fsdwen', repo: 'orca' } - : { owner: 'stablyai', repo: 'orca' } - ) - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 5, - url: 'https://github.com/fsdwen/orca/pull/5' - }) - }) - - await expect( - createGitHubPullRequest( - '/repo-root', - { - provider: 'github', - base: 'main', - head: 'my-branch', - title: 'Fork PR' - }, - 'local' - ) - ).resolves.toEqual({ - ok: true, - number: 5, - url: 'https://github.com/fsdwen/orca/pull/5' - }) - - const [args] = ghExecFileAsyncMock.mock.calls[0] - expect(args[args.indexOf('--repo') + 1]).toBe('fsdwen/orca') - expect(args[args.indexOf('--head') + 1]).toBe('my-branch') - }) - - it('returns the existing PR when gh reports an already-open pull request', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) - ghExecFileAsyncMock - .mockRejectedValueOnce({ stderr: 'a pull request already exists for feature/existing' }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 44, - url: 'https://github.com/acme/widgets/pull/44' - } - ]) - }) - - await expect( - createGitHubPullRequest( - '/repo-root', - { - provider: 'github', - base: 'main', - head: 'refs/remotes/origin/feature/existing', - title: 'Existing' - }, - 'local' - ) - ).resolves.toEqual({ - ok: false, - code: 'already_exists', - error: 'A pull request already exists for this branch.', - reason: 'existing_review', - existingReview: { - number: 44, - url: 'https://github.com/acme/widgets/pull/44' - } - }) - - expect(ghExecFileAsyncMock.mock.calls[1]).toEqual([ - [ - 'pr', - 'list', - '--repo', - 'acme/widgets', - '--head', - 'feature/existing', - '--base', - 'main', - '--state', - 'open', - '--limit', - '2', - '--json', - 'number,url' - ], - // Pin dotcom against process-level GH_HOST. - { cwd: '/repo-root', host: 'github.com' } - ]) - }) -}) diff --git a/src/main/github/client-issue-origin-preference.test.ts b/src/main/github/client-issue-origin-preference.test.ts deleted file mode 100644 index 570d7829856..00000000000 --- a/src/main/github/client-issue-origin-preference.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GhUtils from './gh-utils' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getIssueOwnerRepoMock, - getOwnerRepoForRemoteMock, - resolvePRRepositoryCandidatesMock, - resolveIssueSourceMock, - rateLimitGuardMock, - noteRateLimitSpendMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getIssueOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - resolvePRRepositoryCandidatesMock: vi.fn(), - resolveIssueSourceMock: vi.fn(), - rateLimitGuardMock: vi.fn(() => ({ blocked: false })), - noteRateLimitSpendMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', async () => { - const actual = await vi.importActual('./gh-utils') - return { - ...actual, - execFileAsync: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: getIssueOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - resolveIssueSource: resolveIssueSourceMock, - acquire: acquireMock, - release: releaseMock, - _resetOwnerRepoCache: vi.fn() - } -}) - -vi.mock('./rate-limit', () => ({ - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: noteRateLimitSpendMock, - getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn(), - spendsSharedGitHubComQuota: () => true -})) - -vi.mock('./github-api-repository', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - resolveIssueGitHubApiRepositorySource: ( - repoPath: string, - preference: unknown, - connectionId?: string | null, - localGitOptions?: unknown - ) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions), - getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) => - getIssueOwnerRepoMock(repoPath, connectionId), - getOriginGitHubApiRepository: ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => getOwnerRepoMock(repoPath, connectionId, localGitOptions), - getGitHubApiRepositoryForRemote: ( - repoPath: string, - remoteName: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => - remoteName === 'origin' - ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) - : getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions), - resolveGitHubApiRepositoryCandidates: ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => resolvePRRepositoryCandidatesMock(repoPath, connectionId, localGitOptions) - } -}) - -import { getWorkItem } from './client/fetch/get-work-item' -import { _resetOwnerRepoCache } from './gh-utils' - -describe('GitHub issue open-by-number origin preference', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getIssueOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - resolvePRRepositoryCandidatesMock.mockReset() - resolveIssueSourceMock.mockReset() - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - noteRateLimitSpendMock.mockReset() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => { - const origin = await getOwnerRepoMock(repoPath, connectionId) - const repository = origin ? { host: 'github.com', ...origin } : null - return { candidates: repository ? [repository] : [], headRepo: repository } - }) - _resetOwnerRepoCache() - }) - - it('does not run a bare issue lookup when explicit origin identity is unresolved', async () => { - resolveIssueSourceMock.mockResolvedValueOnce({ source: null, fellBack: false }) - - await expect(getWorkItem('/repo-root', 7, 'issue', null, {}, 'origin')).resolves.toBeNull() - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) - expect(getIssueOwnerRepoMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('skips the issue probe on untyped open when origin identity is unresolved', async () => { - const origin = { owner: 'fork', repo: 'orca', host: 'github.com' } - resolveIssueSourceMock.mockResolvedValueOnce({ source: null, fellBack: false }) - getOwnerRepoMock.mockResolvedValue(origin) - resolvePRRepositoryCandidatesMock.mockResolvedValue({ candidates: [origin], headRepo: origin }) - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 7, - title: 'Origin PR', - state: 'open', - labels: [], - isDraft: false, - url: 'https://github.com/fork/orca/pull/7', - baseRefName: 'main', - headRefName: 'origin/fix', - updatedAt: '2026-04-02T00:00:00Z', - author: { login: 'octocat' } - }) - }) - - const item = await getWorkItem('/repo-root', 7, undefined, null, {}, 'origin') - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) - expect(getIssueOwnerRepoMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock.mock.calls[0]?.[0]).toEqual( - expect.arrayContaining(['pr', 'view', '--repo', 'fork/orca']) - ) - expect(item).toMatchObject({ number: 7, type: 'pr' }) - }) -}) diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts deleted file mode 100644 index 9e157f3a097..00000000000 --- a/src/main/github/client-issue-source.test.ts +++ /dev/null @@ -1,324 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GhUtils from './gh-utils' - -// Keep legacy REST request/failure coverage; API-boundary suites exercise the GraphQL path. -vi.mock('./client/list/work-item-search-page', () => ({ usesGraphqlWorkItemSearch: () => false })) - -const { - execFileAsyncMock, - ghExecFileAsyncMock, - getOwnerRepoMock, - getIssueOwnerRepoMock, - getOwnerRepoForRemoteMock, - resolvePRRepositoryCandidatesMock, - resolveIssueSourceMock, - rateLimitGuardMock, - noteRateLimitSpendMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - execFileAsyncMock: vi.fn(), - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getIssueOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - resolvePRRepositoryCandidatesMock: vi.fn(), - resolveIssueSourceMock: vi.fn(), - rateLimitGuardMock: vi.fn(() => ({ blocked: false })), - noteRateLimitSpendMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', async () => { - const actual = await vi.importActual('./gh-utils') - return { - ...actual, - execFileAsync: execFileAsyncMock, - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: getIssueOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - resolveIssueSource: resolveIssueSourceMock, - acquire: acquireMock, - release: releaseMock, - _resetOwnerRepoCache: vi.fn() - } -}) - -vi.mock('./rate-limit', () => ({ - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: noteRateLimitSpendMock, - getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn(), - spendsSharedGitHubComQuota: () => true -})) - -vi.mock('./github-api-repository', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - // Bridge hosted source resolution to the existing gh-utils fixtures. - resolveIssueGitHubApiRepositorySource: ( - repoPath: string, - preference: unknown, - connectionId?: string | null, - localGitOptions?: unknown - ) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions), - getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) => - getIssueOwnerRepoMock(repoPath, connectionId), - getOriginGitHubApiRepository: ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => getOwnerRepoMock(repoPath, connectionId, localGitOptions), - getGitHubApiRepositoryForRemote: ( - repoPath: string, - remoteName: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => - remoteName === 'origin' - ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) - : getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions), - resolveGitHubApiRepositoryCandidates: ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => resolvePRRepositoryCandidatesMock(repoPath, connectionId, localGitOptions) - } -}) -import { getWorkItem } from './client/fetch/get-work-item' -import { listWorkItems } from './client/list/list-work-items' -import { _resetOwnerRepoCache } from './gh-utils' - -// Share origin fixtures while letting candidate tests opt into upstream. -function mockUpstreamCandidate(upstream: { owner: string; repo: string } | null): void { - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'upstream' ? upstream : getOwnerRepoMock(repoPath, connectionId, opts) - ) -} - -describe('GitHub issue source split', () => { - beforeEach(() => { - execFileAsyncMock.mockReset() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getIssueOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - resolvePRRepositoryCandidatesMock.mockReset() - resolveIssueSourceMock.mockReset() - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - noteRateLimitSpendMock.mockReset() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - // Preserve one source lookup per test while exercising the preference-aware resolver. - resolveIssueSourceMock.mockImplementation(async () => ({ - source: await getIssueOwnerRepoMock(), - fellBack: false - })) - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => { - const origin = await getOwnerRepoMock(repoPath, connectionId) - const repository = origin ? { host: 'github.com', ...origin } : null - return { candidates: repository ? [repository] : [], headRepo: repository } - }) - _resetOwnerRepoCache() - }) - - it.each(['is:issue', 'is:pr'])( - 'propagates GitHub outages for scoped %s queries', - async (query) => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) - ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 503: Service Unavailable')) - - await expect(listWorkItems('/repo-root', 10, query)).rejects.toThrow( - 'HTTP 503: Service Unavailable' - ) - - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - } - ) - - it('propagates an outage when both sides of a combined query are unavailable', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) - ghExecFileAsyncMock - .mockRejectedValueOnce(new Error('HTTP 503: Service Unavailable')) - .mockRejectedValueOnce(new Error('HTTP 502: Bad Gateway')) - - await expect(listWorkItems('/repo-root', 10, 'is:open')).rejects.toThrow( - 'HTTP 503: Service Unavailable' - ) - - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) - - it('pins typed PR metadata to explicit origin when upstream has the same number', async () => { - const upstream = { owner: 'stablyai', repo: 'orca', host: 'github.com' } - const origin = { owner: 'fork', repo: 'orca', host: 'github.com' } - getOwnerRepoMock.mockResolvedValue(origin) - mockUpstreamCandidate(upstream) - resolvePRRepositoryCandidatesMock.mockResolvedValue({ - candidates: [upstream, origin], - headRepo: origin - }) - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 42, - title: 'Origin PR', - state: 'open', - url: 'https://github.com/fork/orca/pull/42', - labels: [], - updatedAt: '2026-04-02T00:00:00Z', - author: { login: 'octocat' }, - isDraft: false, - headRefName: 'origin/fix', - baseRefName: 'main' - }) - }) - - const item = await getWorkItem('/repo-root', 42, 'pr', null, {}, 'origin') - - expect(resolvePRRepositoryCandidatesMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock.mock.calls[0]?.[0]).toEqual( - expect.arrayContaining(['pr', 'view', '--repo', 'fork/orca']) - ) - expect( - ghExecFileAsyncMock.mock.calls.some((call) => - (call[0] as string[]).some((arg) => arg.includes('upstream/orca')) - ) - ).toBe(false) - expect(item?.prRepo).toEqual(origin) - }) - - it('does not run a bare PR lookup when explicit origin identity is unresolved', async () => { - getOwnerRepoMock.mockResolvedValue(null) - mockUpstreamCandidate({ owner: 'stablyai', repo: 'orca' }) - - await expect(getWorkItem('/repo-root', 42, 'pr', null, {}, 'origin')).resolves.toBeNull() - - expect(resolvePRRepositoryCandidatesMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('does not run a bare gh lookup for an SSH repo without candidates', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ candidates: [], headRepo: null }) - - await expect(getWorkItem('/remote/repo', 42, 'pr', 'ssh-1')).resolves.toBeNull() - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('does not probe a second PR repository after a non-not-found failure', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ - candidates: [ - { owner: 'stablyai', repo: 'orca', host: 'github.com' }, - { owner: 'fork', repo: 'orca', host: 'github.com' } - ], - headRepo: { owner: 'fork', repo: 'orca', host: 'github.com' } - }) - ghExecFileAsyncMock - .mockRejectedValueOnce(new Error('HTTP 500: server error')) - .mockRejectedValueOnce(new Error('HTTP 500: server error')) - - await expect(getWorkItem('/repo-root', 42, 'pr')).resolves.toBeNull() - - // Only a confirmed 404 permits trying a same-number PR on another repository. - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) - expect( - ghExecFileAsyncMock.mock.calls.some(([args]) => - (args as string[]).some((arg) => arg.includes('fork/orca')) - ) - ).toBe(false) - }) - - it('raw number lookup tries upstream issue before origin PR', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - // Non-404 upstream failures must not route to an unrelated origin PR with the same number. - ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 404: Not Found')) - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 42, - title: 'Origin PR', - state: 'open', - html_url: 'https://github.com/fork/orca/pull/42', - labels: [], - updated_at: '2026-04-02T00:00:00Z', - user: { login: 'octocat' }, - draft: false - }) - }) - - const item = await getWorkItem('/repo-root', 42) - - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 1, - ['api', 'repos/stablyai/orca/issues/42'], - { cwd: '/repo-root' } - ) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 2, - [ - 'pr', - 'view', - '42', - '--repo', - 'fork/orca', - '--json', - expect.stringContaining('reviewDecision') - ], - { cwd: '/repo-root', host: 'github.com' } - ) - expect(item?.type).toBe('pr') - }) - - it('returns partial results when upstream issues fail but origin PRs succeed', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) - ghExecFileAsyncMock - .mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible by integration')) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 42, - title: 'Fork PR', - state: 'open', - html_url: 'https://github.com/fork/orca/pull/42', - labels: [], - updated_at: '2026-03-31T00:00:00Z', - user: { login: 'octocat' }, - draft: false, - head: { ref: 'feature' }, - base: { ref: 'main' } - } - ]) - }) - - const result = await listWorkItems('/repo-root', 10) - - expect(result.items.map((i) => i.id)).toEqual(['pr:42']) - expect(result.errors?.issues?.type).toBe('permission_denied') - }) - - it('raw number lookup does not fall through on transient upstream errors', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 500: server error')) - - const item = await getWorkItem('/repo-root', 42) - - expect(item).toBeNull() - expect(getOwnerRepoMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/github/client-merge-queue-auto-merge.test.ts b/src/main/github/client-merge-queue-auto-merge.test.ts deleted file mode 100644 index 296cadebdfe..00000000000 --- a/src/main/github/client-merge-queue-auto-merge.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('../git/objects/local-git-object-quarantine', () => - moduleMocks.localGitObjectQuarantineModuleMock() -) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) -import { getWorkItemByOwnerRepo } from './client/fetch/get-work-item' - -import { - installIndependentCheckFixtures, - resetGraphQLRateLimitGuardMocks -} from './client-test-harness' - -const { resolvePRRepositoryCandidatesMock } = clientMocks - -const metadataRequests = vi.fn() -const unexpectedChecks: string[][] = [] -afterEach(() => expect(unexpectedChecks).toEqual([])) - -describe('GitHub GraphQL rate-limit guard', () => { - beforeEach(() => { - resetGraphQLRateLimitGuardMocks(clientMocks) - installIndependentCheckFixtures(clientMocks, metadataRequests, unexpectedChecks) - }) - - afterEach(() => vi.restoreAllMocks()) - - it('lets a link preview read another repository only on a configured host', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValue({ - candidates: [{ owner: 'acme', repo: 'widgets', host: 'github.com' }], - headRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' } - }) - const other = { owner: 'other', repo: 'tools', host: 'github.com' } - const unknownHost = { owner: 'victim', repo: 'secrets', host: 'evil.example.test' } - - await expect(getWorkItemByOwnerRepo('/repo-root', other, 7, 'pr')).resolves.toBeNull() - await expect( - getWorkItemByOwnerRepo('/repo-root', unknownHost, 7, 'pr', undefined, {}, { preview: true }) - ).resolves.toBeNull() - expect(metadataRequests).not.toHaveBeenCalled() - - metadataRequests.mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 7, - title: 'Tools PR', - state: 'open', - html_url: 'https://github.com/other/tools/pull/7', - updated_at: '2026-04-01T00:00:00Z', - user: { login: 'someone' }, - labels: [], - head: { ref: 'feature', sha: 'head-oid' }, - base: { ref: 'main' } - }) - }) - await expect( - getWorkItemByOwnerRepo('/repo-root', other, 7, 'pr', undefined, {}, { preview: true }) - ).resolves.toMatchObject({ title: 'Tools PR' }) - expect(metadataRequests.mock.calls[0]?.[0]).toEqual(['api', 'repos/other/tools/pulls/7']) - }) -}) diff --git a/src/main/github/client-pr-check-details.test.ts b/src/main/github/client-pr-check-details.test.ts deleted file mode 100644 index 2ebbbf755b1..00000000000 --- a/src/main/github/client-pr-check-details.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { ghExecFileAsyncMock, getOwnerRepoMock, rateLimitGuardMock } = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - rateLimitGuardMock: vi.fn(() => ({ blocked: false })) -})) - -vi.mock('./gh-utils', () => ({ - execFileAsync: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, - githubRepoContext: (repoPath: string, connectionId?: string | null) => ({ - repoPath, - connectionId: connectionId ?? null - }), - ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }), - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: vi.fn(), - getOwnerRepoForRemote: ( - repoPath: string, - remoteName: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => - remoteName === 'origin' - ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) - : Promise.resolve(null), - extractExecError: vi.fn((err: unknown) => ({ stderr: String(err), stdout: '' })), - acquire: vi.fn(), - release: vi.fn(), - _resetOwnerRepoCache: vi.fn() -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: vi.fn() -})) - -vi.mock('./github-enterprise-repository', async (importOriginal) => ({ - ...(await importOriginal()), - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('./rate-limit', () => ({ - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: vi.fn(), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn(), - spendsSharedGitHubComQuota: vi.fn(() => true) -})) - -import { getPRCheckDetails } from './client/check/get-pr-check-details' -import { _resetOwnerRepoCache } from './gh-utils' - -describe('getPRCheckDetails', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - _resetOwnerRepoCache() - }) - - it('aborts host work at the cumulative check-details deadline', async () => { - vi.useFakeTimers() - try { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) - ghExecFileAsyncMock.mockImplementation( - (_args: string[], options: { signal?: AbortSignal }) => - new Promise((_resolve, reject) => { - options.signal?.addEventListener( - 'abort', - () => { - const error = new Error('aborted') - error.name = 'AbortError' - reject(error) - }, - { once: true } - ) - }) - ) - const request = getPRCheckDetails('/repo-root', { checkRunId: 88 }) - const rejection = expect(request).rejects.toThrow('Timed out loading check details.') - - await vi.advanceTimersByTimeAsync(25_000) - - await rejection - } finally { - vi.useRealTimers() - } - }) - - it('stops waiting for shared repository resolution at the host deadline', async () => { - vi.useFakeTimers() - try { - getOwnerRepoMock.mockImplementationOnce(() => new Promise(() => {})) - const request = getPRCheckDetails('/repo-root', { checkRunId: 88 }) - const rejection = expect(request).rejects.toThrow('Timed out loading check details.') - - await vi.advanceTimersByTimeAsync(25_000) - - await rejection - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - - it('reads a fine-grained token check from its Actions job when the check run is refused', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) - const job = { - id: 71, - run_id: 7, - name: 'pytest', - status: 'completed', - conclusion: 'success', - html_url: 'https://github.com/acme/widgets/actions/runs/7/job/71', - started_at: '2026-11-10T10:00:00Z', - completed_at: '2026-11-10T10:05:00Z', - steps: [] - } - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - const path = args.at(-1) ?? '' - if (path.includes('/check-runs/71')) { - throw Object.assign(new Error(`Command failed: gh api ${path}`), { - stderr: 'gh: Resource not accessible by personal access token (HTTP 403)\n', - stdout: '' - }) - } - if (path.endsWith('/actions/jobs/71')) { - return { stdout: JSON.stringify(job), stderr: '' } - } - if (path.includes('/actions/runs/7/jobs')) { - return { stdout: JSON.stringify({ jobs: [job] }), stderr: '' } - } - throw new Error(`unexpected ${path}`) - }) - - const details = await getPRCheckDetails('/repo-root', { - checkRunId: 71, - workflowRunId: 7, - checkName: 'pytest' - }) - - expect(details).toMatchObject({ - name: 'pytest', - status: 'completed', - conclusion: 'success', - url: 'https://github.com/acme/widgets/actions/runs/7/job/71', - startedAt: '2026-11-10T10:00:00Z', - completedAt: '2026-11-10T10:05:00Z', - jobs: [{ id: 71, name: 'pytest', status: 'completed', conclusion: 'success' }] - }) - }) -}) diff --git a/src/main/github/client-pr-local-runtime.test.ts b/src/main/github/client-pr-local-runtime.test.ts deleted file mode 100644 index 1b975b67916..00000000000 --- a/src/main/github/client-pr-local-runtime.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -type RateLimitGuardResult = - | { blocked: false } - | { blocked: true; remaining: number; limit: number; resetAt: number } - -const { - execFileAsyncMock, - ghExecFileAsyncMock, - getOwnerRepoMock, - getIssueOwnerRepoMock, - getOwnerRepoForRemoteMock, - getEnterpriseGitHubRepoSlugMock, - resolvePRRepositoryCandidatesMock, - getRemoteUrlForRepoMock, - gitExecFileAsyncMock, - getRateLimitMock, - rateLimitGuardMock, - noteRateLimitSpendMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - execFileAsyncMock: vi.fn(), - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getIssueOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - getEnterpriseGitHubRepoSlugMock: vi.fn(), - resolvePRRepositoryCandidatesMock: vi.fn(), - getRemoteUrlForRepoMock: vi.fn(), - gitExecFileAsyncMock: vi.fn(), - getRateLimitMock: vi.fn(), - rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })), - noteRateLimitSpendMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - execFileAsync: execFileAsyncMock, - ghExecFileAsync: ghExecFileAsyncMock, - gitExecFileAsync: gitExecFileAsyncMock, - extractExecError: (err: unknown) => ({ - stderr: err instanceof Error ? err.message : String(err), - stdout: '' - }), - acquire: acquireMock, - release: releaseMock, - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: getIssueOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - resolvePRRepositoryCandidates: resolvePRRepositoryCandidatesMock, - resolveIssueSource: vi.fn(), - classifyGhError: (message: string) => ({ type: 'unknown', message }), - classifyListIssuesError: (message: string) => ({ type: 'unknown', message }), - ghRepoExecOptions: (context: { - repoPath: string - connectionId?: string | null - wslDistro?: string - }) => - context.connectionId - ? {} - : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }, - githubRepoContext: ( - repoPath: string, - connectionId?: string | null, - localGitOptions: { wslDistro?: string } = {} - ) => ({ - repoPath, - connectionId: connectionId ?? null, - ...localGitOptions - }), - getRemoteUrlForRepo: getRemoteUrlForRepoMock, - _resetOwnerRepoCache: vi.fn() -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, - getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugMock, - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('./conflict-summary', () => ({ - getPRConflictSummary: vi.fn() -})) - -vi.mock('./rate-limit', () => ({ - getRateLimit: getRateLimitMock, - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: noteRateLimitSpendMock, - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn(), - spendsSharedGitHubComQuota: ( - repository?: { host?: string } | null, - executionOptions?: { wslDistro?: string } - ) => - (!repository?.host || repository.host.toLowerCase() === 'github.com') && - !executionOptions?.wslDistro -})) -import { - addPRReviewCommentReply, - getPRChecks, - getPRComments, - mergePR, - removePRReviewers, - requestPRReviewers, - resolveReviewThread, - setPRAutoMerge, - updatePRTitle -} from './client' - -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() -}) - -describe('GitHub PR local runtime routing', () => { - beforeEach(() => { - execFileAsyncMock.mockReset() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getIssueOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - getEnterpriseGitHubRepoSlugMock.mockReset() - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - resolvePRRepositoryCandidatesMock.mockReset() - getRemoteUrlForRepoMock.mockReset() - gitExecFileAsyncMock.mockReset() - getRateLimitMock.mockReset() - getRateLimitMock.mockResolvedValue({ resources: {} }) - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - noteRateLimitSpendMock.mockReset() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - }) - - it('never falls through to the default gh host for an unresolved SSH repository', async () => { - const legacyRepo = { owner: 'team', repo: 'orca' } - getOwnerRepoMock.mockResolvedValue(null) - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - - await expect(getPRComments('/remote/repo', 7, { prRepo: legacyRepo }, 'ssh-1')).rejects.toThrow( - 'GitHub remote' - ) - await expect( - getPRChecks('/remote/repo', 7, undefined, legacyRepo, undefined, 'ssh-1') - ).rejects.toThrow('GitHub remote') - await expect(mergePR('/remote/repo', 7, 'squash', 'ssh-1', legacyRepo)).resolves.toMatchObject({ - ok: false - }) - await expect( - setPRAutoMerge('/remote/repo', 7, true, 'squash', 'ssh-1', legacyRepo) - ).resolves.toMatchObject({ ok: false }) - await expect(updatePRTitle('/remote/repo', 7, 'New title', 'ssh-1', legacyRepo)).resolves.toBe( - false - ) - await expect(requestPRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toMatchObject({ - ok: false - }) - await expect(removePRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toMatchObject({ - ok: false - }) - await expect( - addPRReviewCommentReply( - '/remote/repo', - 7, - 11, - 'Reply', - undefined, - undefined, - undefined, - 'ssh-1', - legacyRepo - ) - ).resolves.toMatchObject({ ok: false }) - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('refuses unresolved local PR mutations instead of using ambient gh defaults', async () => { - const legacyRepo = { owner: 'team', repo: 'orca' } - getOwnerRepoMock.mockResolvedValue(null) - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - - await expect( - resolveReviewThread('/repo-root', 'thread-1', true, null, legacyRepo) - ).resolves.toBe(false) - await expect(updatePRTitle('/repo-root', 7, 'New title', null, legacyRepo)).resolves.toBe(false) - await expect( - requestPRReviewers('/repo-root', 7, ['octo'], null, legacyRepo) - ).resolves.toMatchObject({ ok: false }) - await expect( - removePRReviewers('/repo-root', 7, ['octo'], null, legacyRepo) - ).resolves.toMatchObject({ ok: false }) - await expect(mergePR('/repo-root', 7, 'squash', null, legacyRepo)).resolves.toMatchObject({ - ok: false - }) - await expect( - setPRAutoMerge('/repo-root', 7, true, 'squash', null, legacyRepo) - ).resolves.toMatchObject({ ok: false }) - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/client-pr-lookup-coalescing.test.ts b/src/main/github/client-pr-lookup-coalescing.test.ts deleted file mode 100644 index bc94f1a73e7..00000000000 --- a/src/main/github/client-pr-lookup-coalescing.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' -import type { GitHubRepoContext, LocalGitExecOptions } from './github-repository-identity' -import { getRepoExecutionHostId } from '../../shared/execution-host' -import { hostedReviewInfoFromGitHubPRInfo } from '../../shared/source-control/hosted-review/hosted-review-github' -import { makePR } from './pr-refresh-coordinator-test-harness' -import { - __resetHostedReviewBranchCacheForTests, - invalidateHostedReviewBranchCache, - withHostedReviewBranchCache -} from '../source-control/hosted-review-branch-cache' - -const mocks = vi.hoisted(() => ({ resolve: vi.fn(), acquire: vi.fn(), release: vi.fn() })) -vi.mock('./gh-utils', () => ({ - acquire: mocks.acquire, - release: mocks.release, - githubRepoContext: ( - repoPath: string, - connectionId: string | null, - options: LocalGitExecOptions - ) => ({ - repoPath, - connectionId, - ...options - }), - ghRepoExecOptions: (context: GitHubRepoContext) => context -})) -vi.mock('./client/lookup/branch-lookup-resolution', () => ({ - resolvePRForBranchOutcome: mocks.resolve -})) -vi.mock('./client', async () => ({ - getPRForBranchOutcome: (await import('./client/lookup/pr-for-branch-outcome')) - .getPRForBranchOutcome, - getRepoSlug: vi.fn(async () => ({ owner: 'acme', repo: 'orca' })), - getGitHubPRLookupRateLimitBlock: vi.fn(async () => null), - createGitHubPullRequest: vi.fn() -})) -vi.mock('../gitlab/merge-requests/merge-request-lookup', () => ({ - getProjectSlug: vi.fn(async () => null) -})) -import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' - -const outcome: PRRefreshOutcome = { kind: 'no-pr', fetchedAt: 1 } -beforeEach(() => { - vi.clearAllMocks() - mocks.resolve.mockReset() - __resetHostedReviewBranchCacheForTests() - mocks.acquire.mockResolvedValue(undefined) -}) -afterEach(() => { - vi.unstubAllEnvs() - vi.useRealTimers() -}) - -describe('PR lookup coalescing', () => { - it('cleans up errors so later reads can recover', async () => { - mocks.resolve.mockRejectedValueOnce(new Error('network down')).mockResolvedValue(outcome) - const results = await Promise.all([ - getPRForBranchOutcome('/repo', 'topic'), - getPRForBranchOutcome('/repo', 'topic') - ]) - expect(results.every((result) => result.kind === 'upstream-error')).toBe(true) - expect(mocks.resolve).toHaveBeenCalledTimes(1) - await expect(getPRForBranchOutcome('/repo', 'topic')).resolves.toEqual(outcome) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - }) - - it.each([ - { label: 'native', connectionId: null, options: {} }, - { label: 'WSL', connectionId: null, options: { localGitExecOptions: { wslDistro: 'Ubuntu' } } }, - { label: 'SSH', connectionId: 'host / encoded', options: {} } - ])( - 'does not adopt a pre-creation no-PR read after $label invalidation', - async ({ connectionId, options }) => { - const created: PRRefreshOutcome = { kind: 'found', pr: makePR({ number: 13 }), fetchedAt: 2 } - const createdReview = hostedReviewInfoFromGitHubPRInfo(created.pr) - let finish: (value: PRRefreshOutcome) => void = () => {} - mocks.resolve - .mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - .mockResolvedValue(created) - const executionHostId = getRepoExecutionHostId({ connectionId }) - const identity = { repoPath: '/repo', executionHostId, branch: 'topic', ...options } - const lookup = async () => { - const result = await getPRForBranchOutcome( - '/repo', - 'topic', - null, - connectionId, - null, - options - ) - if (result.kind === 'upstream-error') { - throw new Error(result.message) - } - return result.kind === 'found' ? hostedReviewInfoFromGitHubPRInfo(result.pr) : null - } - const beforeCreation = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - await vi.waitFor(() => expect(mocks.resolve).toHaveBeenCalledTimes(1)) - invalidateHostedReviewBranchCache('/repo', executionHostId) - const afterCreation = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - try { - await vi.waitFor(() => expect(mocks.resolve).toHaveBeenCalledTimes(2)) - await expect(afterCreation).resolves.toEqual(createdReview) - } finally { - finish(outcome) - await Promise.all([beforeCreation, afterCreation]) - } - await expect( - withHostedReviewBranchCache(identity, { headOid: null }, lookup) - ).resolves.toEqual(createdReview) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - } - ) -}) - -it.each([true, false])( - 'explicit host intent replaces the probe without losing its successor (old first: %s)', - async (oldFirst) => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(1_000) - const old = Promise.withResolvers() - const fresh = Promise.withResolvers() - const merged: PRRefreshOutcome = { - kind: 'found', - pr: makePR({ state: 'merged' }), - fetchedAt: 2 - } - mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) - const before = getPRForBranchOutcome('/repo', 'click', null, null, null) - await vi.waitFor(() => expect(mocks.resolve).toHaveBeenCalledTimes(1)) - const intent = { userRefresh: true } - const click = getPRForBranchOutcome('/repo', 'click', null, null, null, intent) - try { - await vi.waitFor(() => expect(mocks.resolve).toHaveBeenCalledTimes(2)) - if (oldFirst) { - old.resolve(outcome) - await before - } - const ordinary = getPRForBranchOutcome('/repo', 'click', null, null, null) - fresh.resolve(merged) - expect(await click).toEqual(merged) - expect(await ordinary).toEqual(merged) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - } finally { - old.resolve(outcome) - fresh.resolve(merged) - await Promise.all([before, click]) - } - } -) - -it('an explicit hosted GitHub read reaches a new lower probe through the real forge adapter', async () => { - const { readHostedReviewForBranch } = await import('../source-control/hosted-review') - const old = Promise.withResolvers() - const merged: PRRefreshOutcome = { - kind: 'found', - pr: makePR({ state: 'merged', headSha: 'new-head' }), - fetchedAt: 2 - } - mocks.resolve.mockReturnValueOnce(old.promise).mockResolvedValueOnce(merged) - const before = getPRForBranchOutcome('/repo', 'adapter', null, null, null) - await vi.waitFor(() => expect(mocks.resolve).toHaveBeenCalledTimes(1)) - const click = readHostedReviewForBranch({ - repoPath: '/repo', - executionHostId: 'local', - branch: 'adapter', - userRefresh: true - }) - try { - await vi.waitFor(() => expect(mocks.resolve).toHaveBeenCalledTimes(2)) - expect((await click).review).toMatchObject({ state: 'merged' }) - } finally { - old.resolve(outcome) - await Promise.all([before, click]) - } -}) diff --git a/src/main/github/client-pr-rest-revalidation.test.ts b/src/main/github/client-pr-rest-revalidation.test.ts deleted file mode 100644 index 66db57f8b64..00000000000 --- a/src/main/github/client-pr-rest-revalidation.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getRestPRForBranch } from './client/lookup/pr-branch-lookup' - -import { resetPRForBranchMocks } from './client-test-harness' - -const { ghExecFileAsyncMock } = clientMocks - -describe('PR lookup conditional REST reads', () => { - beforeEach(() => resetPRForBranchMocks(clientMocks)) - - it('revalidates both mixed and active discovery responses before falling back to history', async () => { - const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' } - const old = Array.from({ length: 10 }, (_, i) => ({ - number: i + 1, - state: 'closed', - title: 'Old', - head: { ref: 'feature' } - })) - const open = { number: 11, state: 'open', title: 'Active', head: { ref: 'feature' } } - const http = (data: unknown, etag: string) => ({ - stdout: `HTTP/2.0 200 OK\nEtag: "${etag}"\r\n\r\n${JSON.stringify(data)}` - }) - ghExecFileAsyncMock - .mockResolvedValueOnce(http(old, 'recent')) - .mockResolvedValueOnce(http([open], 'active')) - .mockRejectedValueOnce( - Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) - ) - .mockRejectedValueOnce( - Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) - ) - await expect( - getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' }) - ).resolves.toMatchObject({ number: 11 }) - await expect( - getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' }) - ).resolves.toMatchObject({ number: 11 }) - expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain('If-None-Match: "recent"') - expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain('If-None-Match: "active"') - }) -}) diff --git a/src/main/github/client-rate-limit-block.test.ts b/src/main/github/client-rate-limit-block.test.ts deleted file mode 100644 index 53c3d30b313..00000000000 --- a/src/main/github/client-rate-limit-block.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getGitHubPRLookupRateLimitBlock } from './client/lookup/pr-lookup-rate-limit' -import { _resetOwnerRepoCache } from './gh-utils' -import { resetOriginRepositoryCache } from './client-test-harness' -import type { RateLimitGuardResult } from './client-test-mocks' - -const { - execFileAsyncMock, - ghExecFileAsyncMock, - getOwnerRepoMock, - getRemoteUrlForRepoMock, - gitExecFileAsyncMock, - getRateLimitMock, - rateLimitGuardMock, - noteRateLimitSpendMock -} = clientMocks - -describe('getGitHubPRLookupRateLimitBlock', () => { - beforeEach(() => { - resetOriginRepositoryCache() - execFileAsyncMock.mockReset() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) - getRemoteUrlForRepoMock.mockReset() - gitExecFileAsyncMock.mockReset() - getRateLimitMock.mockReset() - getRateLimitMock.mockResolvedValue(undefined) - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - noteRateLimitSpendMock.mockReset() - _resetOwnerRepoCache() - }) - - it('reports a block when either lookup bucket is exhausted', async () => { - rateLimitGuardMock.mockImplementation(((bucket: string) => - bucket === 'graphql' - ? { blocked: true, remaining: 4, limit: 5000, resetAt: 1_800_000_000 } - : { blocked: false }) as () => RateLimitGuardResult) - - await expect(getGitHubPRLookupRateLimitBlock('/repo-root')).resolves.toEqual({ - resetAt: 1_800_000_000 - }) - }) - - it('reports the latest reset when both lookup buckets are exhausted', async () => { - rateLimitGuardMock.mockImplementation(((bucket: string) => ({ - blocked: true, - remaining: 4, - limit: 5000, - // Why: core resets first, so returning it would retry into graphql's block. - resetAt: bucket === 'core' ? 1_800_000_000 : 1_800_003_600 - })) as () => RateLimitGuardResult) - - await expect(getGitHubPRLookupRateLimitBlock('/repo-root')).resolves.toEqual({ - resetAt: 1_800_003_600 - }) - }) - - it('fails open when the exempt rate-limit probe itself fails', async () => { - getRateLimitMock.mockRejectedValue(new Error('probe offline')) - - await expect(getGitHubPRLookupRateLimitBlock('/repo-root')).resolves.toBeNull() - }) -}) diff --git a/src/main/github/client-stack-merge-guard.test.ts b/src/main/github/client-stack-merge-guard.test.ts deleted file mode 100644 index f21503882c4..00000000000 --- a/src/main/github/client-stack-merge-guard.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) -import { mergePR } from './client/merge/merge-pr' -import { - installIndependentCheckFixtures, - resetGraphQLRateLimitGuardMocks -} from './client-test-harness' - -const metadataRequests = vi.fn() -const unexpectedChecks: string[][] = [] -afterEach(() => expect(unexpectedChecks).toEqual([])) - -describe('GitHub GraphQL rate-limit guard', () => { - beforeEach(() => { - resetGraphQLRateLimitGuardMocks(clientMocks) - installIndependentCheckFixtures(clientMocks, metadataRequests, unexpectedChecks) - }) - - afterEach(() => vi.restoreAllMocks()) - - const validStackHeadSha = 'a'.repeat(40) - const validStackBaseSha = 'b'.repeat(40) - - it('never falls back to legacy merge after an async stack merge transport failure', async () => { - metadataRequests - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 202, - state: 'open', - head: { ref: 'stack/api', sha: validStackHeadSha }, - base: { ref: 'stack/models', sha: 'models-sha' }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ data: { repository: { mergeQueue: null } } }) - }) - .mockRejectedValueOnce(new Error('socket closed after request submission')) - - await expect( - mergePR('/repo-root', 202, 'squash', undefined, { - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - ).resolves.toEqual({ ok: false, error: 'socket closed after request submission' }) - expect( - metadataRequests.mock.calls.some(([args]) => args[0] === 'pr' && args[1] === 'merge') - ).toBe(false) - }) -}) diff --git a/src/main/github/client-tracked-upstream-default-branch.test.ts b/src/main/github/client-tracked-upstream-default-branch.test.ts deleted file mode 100644 index 01fd5e81a9f..00000000000 --- a/src/main/github/client-tracked-upstream-default-branch.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getPRForBranch } from './client/lookup/get-pr-for-branch' -import { resetPRForBranchMocks } from './client-test-harness' -import type { RestPullRequest } from './client/lookup/pull-request-lookup-data' -import type { OwnerRepo } from './gh-utils' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - resolvePRRepositoryCandidatesMock, - gitExecFileAsyncMock -} = clientMocks - -const ACME = { owner: 'acme', repo: 'widgets' } - -function primeGit( - trackedUpstream: string, - remoteHeads: Record = { origin: 'develop' } -): void { - gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[0] === 'for-each-ref' && args.includes('--format=%(refname)%00%(upstream)')) { - return { stdout: `refs/heads/feature/my-change\0${trackedUpstream}\n`, stderr: '' } - } - if (args[0] === 'for-each-ref' && args.includes('--format=%(refname)%00%(symref)')) { - const stdout = Object.entries(remoteHeads) - .filter(([remote]) => args.includes(`refs/remotes/${remote}/HEA[D]`)) - .map( - ([remote, branch]) => `refs/remotes/${remote}/HEAD\0refs/remotes/${remote}/${branch}\n` - ) - .join('') - return { stdout, stderr: '' } - } - if (args[0] === 'rev-parse' && args[1] === 'HEAD') { - return { stdout: 'feature-head-oid\n', stderr: '' } - } - throw new Error(`unexpected git call: ${args.join(' ')}`) - }) -} - -function restPR( - headRefName = 'develop', - headRepo: OwnerRepo = ACME, - prRepo: OwnerRepo = ACME -): RestPullRequest { - return { - number: 7, - title: 'Release develop', - state: 'closed', - merged_at: null, - html_url: `https://${prRepo.host ?? 'github.com'}/${prRepo.owner}/${prRepo.repo}/pull/7`, - updated_at: '2025-01-01T00:00:00Z', - draft: false, - mergeable: null, - base: { ref: 'release', sha: 'release-oid' }, - head: { - ref: headRefName, - sha: 'old-develop-oid', - repo: { name: headRepo.repo, owner: { login: headRepo.owner } } - } - } -} - -function primeGh( - listsByHead: Record, - exactPR: RestPullRequest | RestPullRequest[] = Object.values(listsByHead).flat()[0] ?? restPR() -): void { - const repositorySlug = (pr: RestPullRequest): string => - new URL(pr.html_url ?? '').pathname.split('/').slice(1, 3).join('/') - const repositoryHost = (pr: RestPullRequest): string => new URL(pr.html_url ?? '').host - const exactPRs = Array.isArray(exactPR) ? exactPR : [exactPR] - const prsByRepositoryAndNumber = new Map( - [...Object.values(listsByHead).flat(), ...exactPRs].map((pr) => [ - `${repositoryHost(pr)}/${repositorySlug(pr)}#${pr.number}`, - pr - ]) - ) - ghExecFileAsyncMock.mockImplementation( - async (args: string[], options: { host?: string } = {}) => { - const host = options.host ?? 'github.com' - const match = args[1]?.match(/^repos\/([^/]+\/[^/]+)\/pulls\?head=([^&]+)/) - if (args[0] === 'api' && match) { - const list = (listsByHead[decodeURIComponent(match[2])] ?? []).filter( - (pr) => repositoryHost(pr) === host && repositorySlug(pr) === match[1] - ) - return { stdout: JSON.stringify(list) } - } - const exactRestMatch = args[1]?.match(/^repos\/([^/]+\/[^/]+)\/pulls\/(\d+)$/) - if (args[0] === 'api' && exactRestMatch) { - const pr = prsByRepositoryAndNumber.get(`${host}/${exactRestMatch[1]}#${exactRestMatch[2]}`) - if (pr) { - return { stdout: JSON.stringify(pr) } - } - throw new Error('HTTP 404 Not Found') - } - const repoIndex = args.indexOf('--repo') - const exact = prsByRepositoryAndNumber.get(`${host}/${args[repoIndex + 1]}#${args[2]}`) - if (args[0] === 'pr' && args[1] === 'view') { - if (!exact) { - throw new Error('HTTP 404 Not Found') - } - return { - stdout: JSON.stringify({ - number: exact.number, - title: exact.title, - state: exact.merged_at ? 'MERGED' : exact.state.toUpperCase(), - url: exact.html_url, - statusCheckRollup: [], - updatedAt: exact.updated_at, - isDraft: exact.draft, - mergeable: 'UNKNOWN', - baseRefName: exact.base?.ref, - headRefName: exact.head?.ref, - baseRefOid: exact.base?.sha, - headRefOid: exact.head?.sha, - headRepositoryOwner: exact.head?.repo?.owner, - headRepository: exact.head?.repo ? { name: exact.head.repo.name } : null - }) - } - } - throw new Error(`gh unavailable: ${args.join(' ')}`) - } - ) -} - -describe('issue #26948: a branch tracking the default branch', () => { - beforeEach(() => { - resetPRForBranchMocks(clientMocks) - getOwnerRepoMock.mockResolvedValue(ACME) - }) - - it('does not query another GitHub server for a known public GitHub head', async () => { - const enterprise = { ...ACME, host: 'ghe.example' } - resolvePRRepositoryCandidatesMock.mockResolvedValue({ - candidates: [enterprise, ACME], - headRepo: ACME - }) - primeGit('') - primeGh({ - 'acme:feature/my-change': [ - { ...restPR('feature/my-change', enterprise, enterprise), state: 'open' } - ] - }) - expect(await getPRForBranch('/repo-root', 'feature/my-change')).toBeNull() - expect( - ghExecFileAsyncMock.mock.calls.some(([, options]) => options?.host === 'ghe.example') - ).toBe(false) - }) -}) diff --git a/src/main/github/client-tracked-upstream-fork-owner.test.ts b/src/main/github/client-tracked-upstream-fork-owner.test.ts deleted file mode 100644 index ab6bf241224..00000000000 --- a/src/main/github/client-tracked-upstream-fork-owner.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getPRForBranch } from './client/lookup/get-pr-for-branch' -import { resetPRForBranchMocks } from './client-test-harness' - -const { - ghExecFileAsyncMock, - getOwnerRepoForRemoteMock, - resolvePRRepositoryCandidatesMock, - gitExecFileAsyncMock -} = clientMocks - -describe('getPRForBranch', () => { - beforeEach(() => { - resetPRForBranchMocks(clientMocks) - }) - - it('uses the tracked upstream remote owner for fork branch lookup', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ - candidates: [ - { owner: 'stablyai', repo: 'orca' }, - { owner: 'origin-owner', repo: 'orca' } - ], - headRepo: { owner: 'origin-owner', repo: 'orca' } - }) - getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'fork-owner', repo: 'orca' }) - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 78, - title: 'Fork upstream branch PR', - state: 'open', - html_url: 'https://github.com/stablyai/orca/pull/78', - updated_at: '2026-03-28T00:00:00Z', - draft: false, - mergeable: true, - base: { ref: 'main', sha: 'base-oid' }, - head: { ref: 'contributor/original', sha: 'upstream-head-oid' } - } - ]) - }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 78, - title: 'Hydrated fork upstream branch PR', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/78', - statusCheckRollup: [], - updatedAt: '2026-03-28T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - baseRefName: 'main', - headRefName: 'contributor/original', - baseRefOid: 'base-oid', - headRefOid: 'upstream-head-oid' - }) - }) - gitExecFileAsyncMock.mockResolvedValueOnce({ - stdout: 'local-created-from-pr\0fork/contributor/original\n', - stderr: '' - }) - - const pr = await getPRForBranch('/repo-root', 'local-created-from-pr') - - expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/repo-root', 'fork', undefined) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 3, - [ - 'api', - 'repos/stablyai/orca/pulls?head=fork-owner%3Acontributor%2Foriginal&state=all&per_page=10', - '--include' - ], - { cwd: '/repo-root' } - ) - expect(pr).toMatchObject({ - number: 78, - title: 'Hydrated fork upstream branch PR', - prRepo: { owner: 'stablyai', repo: 'orca' }, - headRepo: { owner: 'fork-owner', repo: 'orca' } - }) - }) - - it('uses the tracked upstream remote owner when the fork branch name matches locally', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ - candidates: [ - { owner: 'stablyai', repo: 'orca' }, - { owner: 'origin-owner', repo: 'orca' } - ], - headRepo: { owner: 'origin-owner', repo: 'orca' } - }) - getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'brennanb2025', repo: 'orca' }) - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 6433, - title: 'Recover Windows worktree deletes from long paths', - state: 'open', - html_url: 'https://github.com/stablyai/orca/pull/6433', - updated_at: '2026-06-26T00:00:00Z', - draft: false, - mergeable: true, - base: { ref: 'main', sha: 'base-oid' }, - head: { - ref: 'brennanb2025/worktree-remove-fix', - sha: 'same-name-fork-head-oid' - } - } - ]) - }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 6433, - title: 'Recover Windows worktree deletes from long paths', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/6433', - statusCheckRollup: [], - updatedAt: '2026-06-26T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - baseRefName: 'main', - headRefName: 'brennanb2025/worktree-remove-fix', - baseRefOid: 'base-oid', - headRefOid: 'same-name-fork-head-oid' - }) - }) - gitExecFileAsyncMock.mockResolvedValueOnce({ - stdout: 'brennanb2025/worktree-remove-fix\0brennan/brennanb2025/worktree-remove-fix\n', - stderr: '' - }) - - const pr = await getPRForBranch('/repo-root', 'brennanb2025/worktree-remove-fix') - - expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/repo-root', 'brennan', undefined) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 3, - [ - 'api', - 'repos/stablyai/orca/pulls?head=brennanb2025%3Abrennanb2025%2Fworktree-remove-fix&state=all&per_page=10', - '--include' - ], - { cwd: '/repo-root' } - ) - expect(pr).toMatchObject({ - number: 6433, - prRepo: { owner: 'stablyai', repo: 'orca' }, - headRepo: { owner: 'brennanb2025', repo: 'orca' } - }) - }) -}) diff --git a/src/main/github/client-work-item-check-summary.test.ts b/src/main/github/client-work-item-check-summary.test.ts deleted file mode 100644 index 80a9351198e..00000000000 --- a/src/main/github/client-work-item-check-summary.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { ghExecFileAsyncMock, getOwnerRepoMock, rateLimitGuardMock } = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - rateLimitGuardMock: vi.fn(() => ({ blocked: false })) -})) - -vi.mock('./gh-utils', () => ({ - execFileAsync: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, - githubRepoContext: (repoPath: string, connectionId?: string | null) => ({ - repoPath, - connectionId: connectionId ?? null - }), - ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }), - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: vi.fn(), - getOwnerRepoForRemote: ( - repoPath: string, - remoteName: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => - remoteName === 'origin' - ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) - : Promise.resolve(null), - resolveIssueSource: vi.fn(), - extractExecError: vi.fn((err: unknown) => ({ stderr: String(err), stdout: '' })), - acquire: vi.fn(), - release: vi.fn(), - _resetOwnerRepoCache: vi.fn(), - classifyGhError: (stderr: string) => ({ type: 'unknown', message: stderr }), - classifyListIssuesError: (stderr: string) => ({ type: 'unknown', message: stderr }) -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: vi.fn() -})) - -vi.mock('./rate-limit', () => ({ - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: vi.fn(), - getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn(), - spendsSharedGitHubComQuota: vi.fn(() => true) -})) - -import { getWorkItem } from './client/fetch/get-work-item' -import { _resetMergeQueueCacheForTests } from './client/detect/repository-merge-metadata-cache' -import { _resetOwnerRepoCache } from './gh-utils' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -// Metadata and complete checks are independent provider responses. -function mockPullRequestDetail(payload: Record): void { - const head = 'a'.repeat(40) - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[0] === 'pr' && args[1] === 'view') { - return { stdout: JSON.stringify({ ...payload, headRefOid: head }) } - } - if (args.includes('graphql') && args.some((arg) => arg.includes('statusCheckRollup'))) { - return { - stdout: JSON.stringify({ - data: { - repository: { - pullRequest: { - number: payload.number, - headRefOid: head, - commits: { - nodes: [ - { - commit: { - oid: head, - statusCheckRollup: { - contexts: { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these test payloads contain object rollup rows only. - nodes: (payload.statusCheckRollup as Record[]).map( - (raw) => ({ - ...raw, - __typename: - raw.__typename ?? (raw.state ? 'StatusContext' : 'CheckRun'), - ...(!raw.state ? { checkSuite: { databaseId: 7 } } : {}) - }) - ), - pageInfo: { hasNextPage: false, endCursor: null } - } - }, - checkSuites: { - nodes: [], - pageInfo: { hasNextPage: false, endCursor: null } - } - } - } - ] - } - } - } - } - }) - } - } - throw new Error('unexpected gh call') - }) -} - -describe('work item checksSummary', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - _resetOwnerRepoCache() - _resetOriginGitHubApiRepositoryCache() - _resetMergeQueueCacheForTests() - getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) - }) - - it('counts a skipped run as passing and reads a StatusContext state as its conclusion', async () => { - mockPullRequestDetail({ - number: 42, - title: 'Add feature', - state: 'OPEN', - url: 'https://github.com/acme/widgets/pull/42', - updatedAt: '2026-04-01T00:00:00Z', - statusCheckRollup: [ - { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'SKIPPED' }, - // StatusContext supplies state instead of CheckRun's status/conclusion. - { __typename: 'StatusContext', state: 'SUCCESS' }, - { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'NEUTRAL' } - ] - }) - - const item = await getWorkItem('/repo-root', 42, 'pr', null, {}, 'origin') - - expect(item?.checksSummary).toEqual({ - state: 'success', - total: 3, - passed: 2, - failed: 0, - cancelled: 0, - pending: 0, - neutral: 1 - }) - }) -}) diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts deleted file mode 100644 index f42be8891cf..00000000000 --- a/src/main/github/client-work-items.test.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' - -// Keep legacy REST request/failure coverage; API-boundary suites exercise the GraphQL path. -vi.mock('./client/list/work-item-search-page', () => ({ usesGraphqlWorkItemSearch: () => false })) - -const { - execFileAsyncMock, - ghExecFileAsyncMock, - getOwnerRepoMock, - getIssueOwnerRepoMock, - getOwnerRepoForRemoteMock, - resolveIssueSourceMock, - gitExecFileAsyncMock, - rateLimitGuardMock, - noteRateLimitSpendMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - execFileAsyncMock: vi.fn(), - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getIssueOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - resolveIssueSourceMock: vi.fn(), - gitExecFileAsyncMock: vi.fn(), - rateLimitGuardMock: vi.fn((_bucket?: unknown) => ({ blocked: false })), - noteRateLimitSpendMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - execFileAsync: execFileAsyncMock, - ghExecFileAsync: ghExecFileAsyncMock, - githubRepoContext: ( - repoPath: string, - connectionId?: string | null, - localGitOptions: { wslDistro?: string } = {} - ) => ({ - repoPath, - connectionId: connectionId ?? null, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) - }), - ghRepoExecOptions: (context: { - repoPath: string - connectionId?: string | null - wslDistro?: string - }) => - context.connectionId - ? {} - : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }, - getOwnerRepo: getOwnerRepoMock, - getIssueOwnerRepo: getIssueOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - resolveIssueSource: resolveIssueSourceMock, - acquire: acquireMock, - release: releaseMock, - _resetOwnerRepoCache: vi.fn(), - classifyGhError: (stderr: string) => ({ type: 'unknown', message: stderr }), - classifyListIssuesError: (stderr: string) => ({ type: 'unknown', message: stderr }), - classifyListPrsError: (stderr: string) => ({ type: 'unknown', message: stderr }) -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('./rate-limit', () => ({ - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: noteRateLimitSpendMock, - getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), - repositoryRateLimitGuard: vi.fn((_repo: unknown, bucket: string) => rateLimitGuardMock(bucket)), - noteRepositoryRateLimitSpend: vi.fn((_repo: unknown, bucket: string, cost?: number) => - noteRateLimitSpendMock(bucket, cost) - ), - spendsSharedGitHubComQuota: () => true -})) - -vi.mock('./github-api-repository', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - // Bridge hosted source resolution to the suite's gh-utils fixtures. - resolveIssueGitHubApiRepositorySource: ( - repoPath: string, - preference: unknown, - connectionId?: string | null, - localGitOptions?: unknown - ) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions), - getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) => - getIssueOwnerRepoMock(repoPath, connectionId), - getOriginGitHubApiRepository: ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => getOwnerRepoMock(repoPath, connectionId, localGitOptions), - getGitHubApiRepositoryForRemote: ( - repoPath: string, - remoteName: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => - remoteName === 'origin' - ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) - : getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions) - } -}) -import { listWorkItems } from './client/list/list-work-items' -import { _resetMergeQueueCacheForTests } from './client/detect/repository-merge-metadata-cache' -import { _resetOwnerRepoCache } from './gh-utils' -import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' - -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() -}) - -describe('listWorkItems', () => { - beforeEach(() => { - execFileAsyncMock.mockReset() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getIssueOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - resolveIssueSourceMock.mockReset() - gitExecFileAsyncMock.mockReset() - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - noteRateLimitSpendMock.mockReset() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - // Preserve one source lookup through the preference-aware resolver. - resolveIssueSourceMock.mockImplementation(async () => ({ - source: await getIssueOwnerRepoMock(), - fellBack: false - })) - // Bridge explicit origin to getOwnerRepoMock; upstream candidates require opt-in fixtures. - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - _resetOwnerRepoCache() - _resetRemoteNameListingCache() - _resetMergeQueueCacheForTests() - }) - - it('does not run unscoped work-item queries when a local repository has no GitHub source', async () => { - getIssueOwnerRepoMock.mockResolvedValue(null) - getOwnerRepoMock.mockResolvedValue(null) - - // Null-source envelopes distinguish unavailable repository identity from successful empty work. - await expect(listWorkItems('/private-repo', 36)).resolves.toMatchObject({ - items: [], - sources: { issues: null, prs: null } - }) - await expect(listWorkItems('/private-repo', 36, 'is:open')).resolves.toMatchObject({ - items: [], - sources: { issues: null, prs: null } - }) - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('rejects unresolved SSH repositories without running unscoped GitHub work-item queries', async () => { - getIssueOwnerRepoMock.mockResolvedValue(null) - getOwnerRepoMock.mockResolvedValue(null) - getOwnerRepoForRemoteMock.mockResolvedValue(null) - - await expect( - listWorkItems('/remote/repo', 10, undefined, undefined, undefined, 'ssh-1') - ).rejects.toThrow('GitHub work items require a GitHub remote for SSH repositories') - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - - ghExecFileAsyncMock.mockClear() - getIssueOwnerRepoMock.mockResolvedValue(null) - getOwnerRepoMock.mockResolvedValue(null) - getOwnerRepoForRemoteMock.mockResolvedValue(null) - - await expect( - listWorkItems('/remote/repo', 10, 'is:open', undefined, undefined, 'ssh-1') - ).rejects.toThrow('GitHub work items require a GitHub remote for SSH repositories') - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/client.ts b/src/main/github/client.ts deleted file mode 100644 index b7a1d5bc1da..00000000000 --- a/src/main/github/client.ts +++ /dev/null @@ -1,49 +0,0 @@ -export { - _getMergeQueueCacheSizeForTests, - _resetMergeQueueCacheForTests -} from './client/detect/repository-merge-metadata-cache' -export { _resetPRStackSummaryCacheForTests } from './client/lookup/pr-stack-summary-cache' -export { - _getTrackedUpstreamBranchCacheSizesForTests, - __resetTrackedUpstreamBranchCacheForTests -} from './client/lookup/tracked-upstream-cache' -export { addPRReviewComment, addPRReviewCommentReply } from './client/create/add-pr-review-comment' -export { __resetOrcaStarCheckForTests, checkOrcaStarred, starOrca } from './client/fetch/orca-star' -export { countWorkItems } from './client/list/count-work-items' -export { createGitHubPullRequest } from './client/create/create-github-pull-request' -export { getAuthenticatedViewer } from './client/fetch/authenticated-viewer' -export { getGitHubPRLookupRateLimitBlock } from './client/lookup/pr-lookup-rate-limit' -export { getPRCheckDetails } from './client/check/get-pr-check-details' -export { getPRChecks } from './client/check/get-pr-checks' -export { getPRComments } from './client/fetch/get-pr-comments' -export { getPRForBranch } from './client/lookup/get-pr-for-branch' -export { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' -export { - getPullRequestPushTarget, - type PullRequestPushTarget -} from './client/lookup/pull-request-push-target' -export { getRepoSlug, getRepoUpstream } from './client/fetch/repo-slug-upstream' -export { - getWorkItem, - getWorkItemByOwnerRepo, - getWorkItemWithRepository -} from './client/fetch/get-work-item' -export { listWorkItems } from './client/list/list-work-items' -export { mergePR } from './client/merge/merge-pr' -export { removePRReviewers, requestPRReviewers } from './client/update/pr-reviewers' -export { rerunPRChecks } from './client/check/rerun-pr-checks' -export { resolveReviewThread } from './client/update/resolve-review-thread' -export { setPRAutoMerge } from './client/merge/pr-auto-merge' -export { setPRCommentReaction } from './client/update/pr-comment-reaction' -export { setPRFileViewed } from './client/update/pr-file-viewed' -export { updatePRDetails, updatePRTitle } from './client/update/pr-details' -export { markPRDraft, markPRReadyForReview } from './client/update/pr-ready' -export { updatePRState } from './client/update/pr-state' -export type { GitHubPRBranchLookupOptions } from './client/lookup/pull-request-lookup-data' -export type { MainWorkItem } from './client/map/work-item-field-coercion' -export { _resetOwnerRepoCache } from './gh-utils' -export { getIssue, listIssues } from './issues' -export { createIssue } from './issue-create' -export { updateIssue } from './issue-update' -export { addIssueComment } from './issue-comment' -export { listLabels, listAssignableUsers } from './issue-field-options' diff --git a/src/main/github/client/check/check-detail-field-mapping.ts b/src/main/github/client/check/check-detail-field-mapping.ts index a5ac7b7d5d5..cab277c6f8a 100644 --- a/src/main/github/client/check/check-detail-field-mapping.ts +++ b/src/main/github/client/check/check-detail-field-mapping.ts @@ -1,4 +1,4 @@ -import type { PRCheckRunDetails } from '../../../../shared/github/check-types' +import type { PRCheckRunDetails } from '../../../../shared/github/checks/check-types' export function nullableString(value: unknown): string | null { return typeof value === 'string' && value.length > 0 ? value : null } diff --git a/src/main/github/client/check/check-details-admission-lifetime.test.ts b/src/main/github/client/check/check-details-admission-lifetime.test.ts index dd648e7e407..3a1750d788e 100644 --- a/src/main/github/client/check/check-details-admission-lifetime.test.ts +++ b/src/main/github/client/check/check-details-admission-lifetime.test.ts @@ -17,11 +17,13 @@ vi.mock('@orca/process-host/process-tree-termination', () => ({ signalProcessTree: signalMock, forceTerminateProcessTree: forceMock })) -vi.mock('../../github-api-repository', () => ({ resolveGitHubRepoExecution: resolverMock })) +vi.mock('../../repositories/github-api-repository', () => ({ + resolveGitHubRepoExecution: resolverMock +})) import { getPRCheckDetails } from './get-pr-check-details' import { prCheckLogTailCache } from './check-job-log-tails' -import { clearGhCapabilityStateForTests } from '../../gh-capability-state' -import { clearGhAccountTokenCacheForTests } from '../../gh-account-token' +import { clearGhCapabilityStateForTests } from '../../accounts/gh-capability-state' +import { clearGhAccountTokenCacheForTests } from '../../accounts/gh-account-token' const repo = { owner: 'acme', repo: 'widgets' } const children: ChildProcess[] = [] @@ -143,28 +145,6 @@ describe('check details existing admission ownership', () => { expect(logChildren).toHaveLength(5) }) - it('prevents the jobs stage after a swallowed annotation PID error until close', async () => { - const controller = new AbortController() - const result = getPRCheckDetails( - '/folder', - { checkRunId: 1, workflowRunId: 2 }, - undefined, - {}, - controller.signal - ) - const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }) - await vi.advanceTimersByTimeAsync(0) - completeFakeSpawn(children[0], { stdout: '{"name":"loaded"}' }) - await vi.advanceTimersByTimeAsync(0) - children[1].emit('error', new Error('private-output')) - await vi.advanceTimersByTimeAsync(0) - expect(children).toHaveLength(2) - controller.abort() - await rejected - expect(children).toHaveLength(2) - expect(JSON.stringify(vi.mocked(console.warn).mock.calls)).not.toContain('private-output') - }) - it('retains all four creator permits through joined help and later token continuations after departure', async () => { const options: GhExecOptions = { cwd: '/folder', diff --git a/src/main/github/client/check/check-details-admission-snapshot.test.ts b/src/main/github/client/check/check-details-admission-snapshot.test.ts index b1975096fba..36d42b6a130 100644 --- a/src/main/github/client/check/check-details-admission-snapshot.test.ts +++ b/src/main/github/client/check/check-details-admission-snapshot.test.ts @@ -6,8 +6,8 @@ import { createFakeSpawnedChild } from '../../../../shared/__fixtures__/fake-spawned-child' import type { GhExecOptions } from '../../../git/command-runner/hosted-cli/gh-exec-file' -import { clearGhAccountTokenCacheForTests } from '../../gh-account-token' -import { clearGhCapabilityStateForTests } from '../../gh-capability-state' +import { clearGhAccountTokenCacheForTests } from '../../accounts/gh-account-token' +import { clearGhCapabilityStateForTests } from '../../accounts/gh-capability-state' import { getPRCheckDetails } from './get-pr-check-details' import { prCheckLogTailCache } from './check-job-log-tails' @@ -16,7 +16,9 @@ const { spawnMock, resolverMock } = vi.hoisted(() => ({ resolverMock: vi.fn() })) vi.mock('node:child_process', async (original) => ({ ...(await original()), spawn: spawnMock })) -vi.mock('../../github-api-repository', () => ({ resolveGitHubRepoExecution: resolverMock })) +vi.mock('../../repositories/github-api-repository', () => ({ + resolveGitHubRepoExecution: resolverMock +})) vi.mock('@orca/process-host', async (original) => { const actual = await original() return { diff --git a/src/main/github/client/check/check-details-capture-diagnostics.test.ts b/src/main/github/client/check/check-details-capture-diagnostics.test.ts index b794dd37fce..58400784e1c 100644 --- a/src/main/github/client/check/check-details-capture-diagnostics.test.ts +++ b/src/main/github/client/check/check-details-capture-diagnostics.test.ts @@ -10,7 +10,8 @@ import * as capture from '../../../git/command-runner/process-capture/exec-file- import { RpcDispatcher } from '../../../runtime/rpc/dispatcher' import { GITHUB_PULL_REQUEST_METHODS } from '../../../runtime/rpc/methods/source-control/github/github-pull-request-methods' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import * as ghUtils from '../../gh-utils' +import * as ghUtilsOwner1 from '../../execution/github-operation-slots' +import * as ghUtilsOwner2 from '../../../git/command-runner/hosted-cli/gh-exec-file' import { getPRCheckDetails } from './get-pr-check-details' import { prCheckLogTailCache } from './check-job-log-tails' @@ -22,7 +23,9 @@ const { spawnMock, resolverMock, signalMock, forceMock, captureCap } = vi.hoiste captureCap: { bytes: 4096, metadata: false } })) vi.mock('node:child_process', async (original) => ({ ...(await original()), spawn: spawnMock })) -vi.mock('../../github-api-repository', () => ({ resolveGitHubRepoExecution: resolverMock })) +vi.mock('../../repositories/github-api-repository', () => ({ + resolveGitHubRepoExecution: resolverMock +})) vi.mock('@orca/process-host/process-tree-termination', () => ({ signalProcessTree: signalMock, forceTerminateProcessTree: forceMock @@ -88,27 +91,27 @@ function serializeDiagnostics(value: unknown): string { ) } async function verifyAdmissionIsRestored(): Promise { - await Promise.all(Array.from({ length: 4 }, () => ghUtils.acquire())) + await Promise.all(Array.from({ length: 4 }, () => ghUtilsOwner1.acquire())) let fifthStarted = false - const fifth = ghUtils.acquire().then(() => { + const fifth = ghUtilsOwner1.acquire().then(() => { fifthStarted = true }) await vi.advanceTimersByTimeAsync(0) expect(fifthStarted).toBe(false) - ghUtils.release() + ghUtilsOwner1.release() await fifth for (let i = 0; i < 4; i++) { - ghUtils.release() + ghUtilsOwner1.release() } } async function verifyAdmissionIsRetained(): Promise { - await Promise.all(Array.from({ length: 3 }, () => ghUtils.acquire())) + await Promise.all(Array.from({ length: 3 }, () => ghUtilsOwner1.acquire())) const controller = new AbortController() let started = false - const waiting = ghUtils.acquire(controller.signal).then( + const waiting = ghUtilsOwner1.acquire(controller.signal).then( () => { started = true - ghUtils.release() + ghUtilsOwner1.release() }, () => {} ) @@ -117,7 +120,7 @@ async function verifyAdmissionIsRetained(): Promise { controller.abort() await waiting for (let i = 0; i < 3; i++) { - ghUtils.release() + ghUtilsOwner1.release() } } @@ -155,7 +158,7 @@ describe('real capture and gh diagnostics through check details RPC', () => { 'keeps %s raw capture fields internal and restores actual admission', async (mode) => { const captureSpy = vi.spyOn(capture, 'execFileCaptureToTermination') - const ghSpy = vi.spyOn(ghUtils, 'ghExecFileAsync') + const ghSpy = vi.spyOn(ghUtilsOwner2, 'ghExecFileAsync') if (mode === 'runner-timeout') { resolverMock.mockResolvedValue({ ownerRepo: { owner: 'acme', repo: 'widgets' }, diff --git a/src/main/github/client/check/check-job-log-cache-retention-child.mjs b/src/main/github/client/check/check-job-log-cache-retention-child.mjs index ca3851150ea..62d2bc788be 100644 --- a/src/main/github/client/check/check-job-log-cache-retention-child.mjs +++ b/src/main/github/client/check/check-job-log-cache-retention-child.mjs @@ -96,6 +96,7 @@ async function retained(count, bytes, offset) { for (let id = 0; id < 3; id++) { await cold(id + 1, 128 * 1024) } +assert.equal(host.downloadCount(), 3, 'Cold downloads bypassed the generated gh fixture') host.prCheckLogTailCache.clear() const pinnedBefore = memory() let pinned = Array.from({ length: 8 }, (_, index) => parent(8 * mib, index).slice(-limit)) diff --git a/src/main/github/client/check/check-job-log-download.test.ts b/src/main/github/client/check/check-job-log-download.test.ts index 8edbe29128f..d9dcf20ad3e 100644 --- a/src/main/github/client/check/check-job-log-download.test.ts +++ b/src/main/github/client/check/check-job-log-download.test.ts @@ -1,9 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import fixture from './__fixtures__/gh-api-unknown-escape-flag.json' + import { startCheckJobLogDownload } from './check-job-log-download' import type { GhCaptureLifetimeHooks } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' const { ghMock } = vi.hoisted(() => ({ ghMock: vi.fn() })) -vi.mock('../../gh-utils', () => ({ ghExecFileAsync: ghMock })) +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghMock +})) const diagnostic = 'unknown flag: --allow-escape-sequences' const repo = { owner: 'acme', repo: 'widgets' } function download(controller = new AbortController(), deadlineAt = Date.now() + 25_000) { @@ -36,92 +38,6 @@ describe('stateless captured diagnostic negotiation', () => { vi.useRealTimers() vi.restoreAllMocks() }) - it.each([ - fixture.stderr, - Buffer.from(fixture.stderr), - diagnostic, - `${diagnostic}\n`, - fixture.stderr.replaceAll('\n', '\r\n'), - fixture.stderr.replaceAll('\n', '\r'), - `USAGE changed\n${diagnostic}\nflags reordered`, - `help\n${diagnostic}`, - `${'changed usage\n'.repeat(500)}${diagnostic}`, - `${diagnostic}\n${diagnostic}`, - `HTTP 403\nDEBUG record\necho other text\n${diagnostic}\nauthentication failed`, - `unknown flag: --other\n${diagnostic}\nindependent failure` - ])('allows a complete diagnostic independently of surrounding output %#', async (stderr) => { - ghMock - .mockRejectedValueOnce(rejected({ stderr, stdout: 'nonempty output is irrelevant' })) - .mockResolvedValueOnce({ stdout: 'retrieved', stderr: '' }) - await expect(download().result).resolves.toBe('retrieved') - expect(ghMock).toHaveBeenCalledTimes(2) - expect(ghMock.mock.calls[1][0]).toEqual(['api', 'repos/acme/widgets/actions/jobs/77/logs']) - expect(ghMock.mock.calls[1][1]).toEqual(ghMock.mock.calls[0][1]) - }) - it.each([ - `prefix ${diagnostic}`, - `${diagnostic} suffix`, - ` ${diagnostic}`, - `${diagnostic} `, - diagnostic.toUpperCase(), - `\x1b[31m${diagnostic}`, - `${diagnostic}\x00`, - 'unknown flag: --other', - `${diagnostic}-suffix`, - `Error: ${diagnostic}`, - `$ printf '${diagnostic}'`, - `echo ${diagnostic}`, - `HTTP 403: ${diagnostic}`, - `DEBUG ${diagnostic}`, - JSON.stringify({ error: diagnostic }), - `"${diagnostic}"`, - 'authentication failed', - 'rate limit exceeded', - 'network unavailable' - ])('rejects framing or different text on the candidate line %#', async (stderr) => { - ghMock.mockRejectedValue(rejected({ stderr })) - await expect(download().result).rejects.toBeDefined() - expect(ghMock).toHaveBeenCalledOnce() - }) - it.each([ - { code: 0 }, - { code: undefined }, - { code: null }, - { code: '1' }, - { code: Number.NaN }, - { code: Infinity }, - { code: -Infinity }, - { stderr: undefined }, - { stderr: {} }, - { stderr: null }, - { stderr: '', stdout: diagnostic, message: diagnostic, cause: diagnostic }, - { outputTruncated: true, killed: false, signal: null }, - { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' }, - { code: 'ENOBUFS' }, - { name: 'AbortError' }, - { code: 'ABORT_ERR' }, - { code: 'ERR_ABORTED' }, - { code: 'ETIMEDOUT' }, - { timedOut: true }, - { killed: true }, - { signal: 'SIGTERM' }, - { signal: false } - ])('honors typed exclusions before exact stderr %#', async (metadata) => { - ghMock.mockRejectedValue(rejected(metadata)) - await expect(download().result).rejects.toBeDefined() - expect(ghMock).toHaveBeenCalledOnce() - }) - it('does not read inherited stderr or a getter as capture evidence', async () => { - const inherited = Object.assign(Object.create({ stderr: diagnostic }), { code: 1 }) - ghMock.mockRejectedValueOnce(inherited) - await expect(download().result).rejects.toBeDefined() - const getter = vi.fn(() => diagnostic) - const error = Object.defineProperty({ code: 1 }, 'stderr', { get: getter }) - ghMock.mockRejectedValueOnce(error) - await expect(download().result).rejects.toBeDefined() - expect(getter).not.toHaveBeenCalled() - expect(ghMock).toHaveBeenCalledTimes(2) - }) it('waits positive first termination and starts nothing after cancellation', async () => { let close = (): void => {} @@ -143,19 +59,7 @@ describe('stateless captured diagnostic negotiation', () => { await call.terminated expect(ghMock).toHaveBeenCalledOnce() }) - it('does not reset the original deadline for fallback and starts the next job flagged', async () => { - ghMock - .mockImplementationOnce(async () => { - vi.setSystemTime(Date.now() + 4_000) - throw rejected({}) - }) - .mockResolvedValueOnce({ stdout: 'ok', stderr: '' }) - await expect(download().result).resolves.toBe('ok') - expect(ghMock.mock.calls[1][1].timeout).toBe(21_000) - ghMock.mockResolvedValueOnce({ stdout: 'next', stderr: '' }) - await expect(download().result).resolves.toBe('next') - expect(ghMock.mock.calls[2][0]).toContain('--allow-escape-sequences') - }) + it('ends at the second failure and rejects expiry or pre-abort without a child', async () => { ghMock.mockRejectedValue(rejected({})) await expect(download().result).rejects.toBeDefined() diff --git a/src/main/github/client/check/check-job-log-download.ts b/src/main/github/client/check/check-job-log-download.ts index b8d3e662b82..33587f83bc2 100644 --- a/src/main/github/client/check/check-job-log-download.ts +++ b/src/main/github/client/check/check-job-log-download.ts @@ -1,8 +1,11 @@ -import { ghExecFileAsync } from '../../gh-utils' -import type { GitHubApiRepository } from '../../github-api-repository' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import type { GhExecOptions } from '../github-exec-scope' -import { createGhLogicalLifetime } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' -import type { GhCaptureLifetimeHooks } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' +import { + createGhLogicalLifetime, + type GhCaptureLifetimeHooks +} from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' + import { runCheckDetailsCall } from './check-details-admission-lifetime' import { createCheckDetailsAbortError, waitForCheckDetailsResolution } from './check-details-abort' diff --git a/src/main/github/client/check/check-job-log-execution.ts b/src/main/github/client/check/check-job-log-execution.ts index 1497dc4b705..b6f72a0be0d 100644 --- a/src/main/github/client/check/check-job-log-execution.ts +++ b/src/main/github/client/check/check-job-log-execution.ts @@ -1,7 +1,7 @@ -import { normalizeGhAccountBinding } from '../../../../shared/github/account-binding' +import { normalizeGhAccountBinding } from '../../../../shared/github/accounts/account-binding' import { parseWslPath } from '../../../wsl/filesystem/unc-path-access' -import { githubReadExecutionScope } from '../../github-read-execution-scope' -import type { GitHubApiRepository } from '../../github-api-repository' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import type { GhExecOptions } from '../github-exec-scope' function reusableHost(host: string): 'cloud' | 'enterprise' | null { diff --git a/src/main/github/client/check/check-job-log-host-measurement.mjs b/src/main/github/client/check/check-job-log-host-measurement.mjs index 60f735817d3..9d567c0d163 100644 --- a/src/main/github/client/check/check-job-log-host-measurement.mjs +++ b/src/main/github/client/check/check-job-log-host-measurement.mjs @@ -22,6 +22,9 @@ export async function ghExecFileAsync() { return { stdout: output, stderr: '' }; } ` +const ghExecFileSpecifier = '../../../git/command-runner/hosted-cli/gh-exec-file' +const ghExecFileSource = 'src/main/git/command-runner/hosted-cli/gh-exec-file.ts' +const ghExecFileFilter = /^\.\.\/\.\.\/\.\.\/git\/command-runner\/hosted-cli\/gh-exec-file$/ const scriptUrl = (name) => new URL(name, import.meta.url) const scriptRoot = fileURLToPath(scriptUrl('../../../../../')) const sourceName = (root, filename) => path.relative(root, filename).split(path.sep).join('/') @@ -34,12 +37,12 @@ const cpuDescriptors = [8, 63].map((size) => ({ export async function prepareHostMeasurement(root = process.cwd()) { const directory = await mkdtemp(path.join(tmpdir(), 'orca-check-host-retention-')) + let ghExecFileStubbed = false try { const bundle = await build({ absWorkingDir: root, stdin: { - contents: - "export { attachFailedJobLogTails, prCheckLogTailCache } from './check-job-log-tails'; export { setFixtureOutput, downloadCount } from '../../gh-utils';", + contents: `export { attachFailedJobLogTails, prCheckLogTailCache } from './check-job-log-tails'; export { setFixtureOutput, downloadCount } from '${ghExecFileSpecifier}';`, resolveDir: path.join(root, 'src', 'main', 'github', 'client', 'check'), loader: 'ts' }, @@ -52,10 +55,12 @@ export async function prepareHostMeasurement(root = process.cwd()) { { name: 'generated-gh-capture-result', setup(builder) { - builder.onResolve({ filter: /^\.\.\/\.\.\/gh-utils$/ }, () => ({ - path: 'generated-gh-result', - namespace: 'fixture' - })) + // Why: check-job-log-download.ts imports ghExecFileAsync by this exact + // specifier; stubbing any other path lets the bundle spawn the real gh. + builder.onResolve({ filter: ghExecFileFilter }, () => { + ghExecFileStubbed = true + return { path: 'generated-gh-result', namespace: 'fixture' } + }) builder.onLoad({ filter: /.*/, namespace: 'fixture' }, () => ({ contents: fixtureSource, loader: 'js' @@ -67,6 +72,11 @@ export async function prepareHostMeasurement(root = process.cwd()) { const bundleSources = Object.keys(bundle.metafile.inputs) .filter((name) => name !== '' && !name.startsWith('fixture:')) .sort() + assert(ghExecFileStubbed, 'Host measurement did not stub the gh downloader') + assert( + !bundleSources.includes(ghExecFileSource), + 'Host measurement bundle includes the real gh downloader' + ) const executedSources = [ import.meta.filename, fileURLToPath(scriptUrl('./check-job-log-cache-retention-child.mjs')), diff --git a/src/main/github/client/check/check-job-log-subscribers.test.ts b/src/main/github/client/check/check-job-log-subscribers.test.ts index 97b4113a3d2..eeaa43b1b1d 100644 --- a/src/main/github/client/check/check-job-log-subscribers.test.ts +++ b/src/main/github/client/check/check-job-log-subscribers.test.ts @@ -18,7 +18,9 @@ vi.mock('@orca/process-host/process-tree-termination', () => ({ signalProcessTree: signalMock, forceTerminateProcessTree: forceMock })) -vi.mock('../../github-api-repository', () => ({ resolveGitHubRepoExecution: resolverMock })) +vi.mock('../../repositories/github-api-repository', () => ({ + resolveGitHubRepoExecution: resolverMock +})) const children: ChildProcess[] = [] function spawn(): ChildProcess { const child = createFakeSpawnedChild(children.length + 100) diff --git a/src/main/github/client/check/check-job-log-tails.test.ts b/src/main/github/client/check/check-job-log-tails.test.ts deleted file mode 100644 index 263f705e4ad..00000000000 --- a/src/main/github/client/check/check-job-log-tails.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ChildProcess, SpawnOptions } from 'node:child_process' -import { - completeFakeSpawn, - createFakeSpawnedChild -} from '../../../../shared/__fixtures__/fake-spawned-child' -import { attachLogFixture, failedLogJob } from './check-job-log-test-fixture' -import { prCheckLogTailCache } from './check-job-log-tails' -import { clearGhCapabilityStateForTests } from '../../gh-capability-state' -import { clearGhAccountTokenCacheForTests } from '../../gh-account-token' -const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) -vi.mock('node:child_process', async (original) => ({ ...(await original()), spawn: spawnMock })) -const children: ChildProcess[] = [] -let raw = 'Error: retained diagnostic' -let active = 0 -let peak = 0 -function automaticSpawn(_program: string, argv: string[], _options: SpawnOptions): ChildProcess { - const child = createFakeSpawnedChild() - children.push(child) - active += 1 - peak = Math.max(peak, active) - const user = argv[argv.indexOf('--user') + 1] - const stdout = argv.includes('--help') ? '--user' : argv[0] === 'auth' ? `bound-${user}` : raw - queueMicrotask(() => { - active -= 1 - completeFakeSpawn(child, { stdout }) - }) - return child -} -describe('completed scoped excerpts through actual capture and runner', () => { - beforeEach(() => { - vi.useFakeTimers() - children.length = 0 - active = 0 - peak = 0 - raw = 'Error: retained diagnostic' - spawnMock.mockReset().mockImplementation(automaticSpawn) - prCheckLogTailCache.clear() - clearGhCapabilityStateForTests() - clearGhAccountTokenCacheForTests() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - afterEach(async () => { - for (const child of children) { - child.emit('close', 0, null) - } - await vi.advanceTimersByTimeAsync(0) - expect(vi.getTimerCount()).toBe(0) - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('bounds owned encoded cache content with FIFO eviction and five-job payload', async () => { - raw = '🙂'.repeat(6000) - for (let id = 1; id <= 129; id += 1) { - await attachLogFixture([failedLogJob(id)]) - } - expect(prCheckLogTailCache.size).toBe(128) - const tails = [...prCheckLogTailCache.values()].map((entry) => entry.logTail ?? '') - expect(tails.every((tail) => Buffer.byteLength(tail) <= 16 * 1024)).toBe(true) - expect(tails.reduce((bytes, tail) => bytes + Buffer.byteLength(tail), 0)).toBe(128 * 16 * 1024) - const jobs = Array.from({ length: 5 }, (_, i) => failedLogJob(i + 125)) - await attachLogFixture(jobs) - expect(jobs.reduce((bytes, job) => bytes + Buffer.byteLength(job.logTail ?? ''), 0)).toBe( - 80 * 1024 - ) - jobs[0].logTail = 'caller mutation' - await attachLogFixture([failedLogJob(125)]) - expect(spawnMock).toHaveBeenCalledTimes(129) - await attachLogFixture([failedLogJob(1)]) - expect(spawnMock).toHaveBeenCalledTimes(130) - }) -}) diff --git a/src/main/github/client/check/check-job-log-tails.ts b/src/main/github/client/check/check-job-log-tails.ts index 12baac336d1..d3070006caa 100644 --- a/src/main/github/client/check/check-job-log-tails.ts +++ b/src/main/github/client/check/check-job-log-tails.ts @@ -1,7 +1,7 @@ -import type { PRCheckRunDetails } from '../../../../shared/github/check-types' +import type { PRCheckRunDetails } from '../../../../shared/github/checks/check-types' import { sliceCheckLogTail } from '../../../../shared/source-control/checks/logs/check-job-log-tail-slice' -import type { GitHubApiRepository } from '../../github-api-repository' -import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' import type { GhExecOptions } from './../github-exec-scope' import { rethrowCheckDetailsAbort, waitForCheckDetailsResolution } from './check-details-abort' import { assertCheckLogActive, startCheckJobLogDownload } from './check-job-log-download' diff --git a/src/main/github/client/check/check-job-log-test-fixture.ts b/src/main/github/client/check/check-job-log-test-fixture.ts index a1ecbe4d319..50605cb696b 100644 --- a/src/main/github/client/check/check-job-log-test-fixture.ts +++ b/src/main/github/client/check/check-job-log-test-fixture.ts @@ -1,5 +1,5 @@ -import type { PRCheckJob } from '../../../../shared/github/check-types' -import type { GitHubApiRepository } from '../../github-api-repository' +import type { PRCheckJob } from '../../../../shared/github/checks/check-types' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import type { GhExecOptions } from '../github-exec-scope' import { snapshotCheckJobLogExecution } from './check-job-log-execution' import { attachFailedJobLogTails } from './check-job-log-tails' diff --git a/src/main/github/complete-pr-check-observation.test.ts b/src/main/github/client/check/complete-pr-check-observation.test.ts similarity index 93% rename from src/main/github/complete-pr-check-observation.test.ts rename to src/main/github/client/check/complete-pr-check-observation.test.ts index a0d7c16bc5b..0827a47b591 100644 --- a/src/main/github/complete-pr-check-observation.test.ts +++ b/src/main/github/client/check/complete-pr-check-observation.test.ts @@ -1,17 +1,17 @@ import { beforeEach, expect, it, vi } from 'vitest' const { exec } = vi.hoisted(() => ({ exec: vi.fn() })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (original) => ({ +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (original) => ({ ...(await original>()), ghExecFileAsync: exec })) -vi.mock('./rate-limit', () => ({ +vi.mock('../../api/rate-limit', () => ({ noteRepositoryRateLimitSpend: vi.fn(), repositoryRateLimitGuard: () => ({ blocked: false }), spendsSharedGitHubComQuota: () => false })) -import { readCompletePRCheckObservation } from './client/check/complete-pr-check-observation' -import { summarizePRCheckRollup } from '../../shared/source-control/checks/pr-check-status' +import { readCompletePRCheckObservation } from './complete-pr-check-observation' +import { summarizePRCheckRollup } from '../../../../shared/source-control/checks/pr-check-status' const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } const sha = 'a'.repeat(40) diff --git a/src/main/github/client/check/complete-pr-check-observation.ts b/src/main/github/client/check/complete-pr-check-observation.ts index c0e5eaab08f..df07831ba88 100644 --- a/src/main/github/client/check/complete-pr-check-observation.ts +++ b/src/main/github/client/check/complete-pr-check-observation.ts @@ -1,4 +1,4 @@ -import type { GitHubApiRepository } from '../../github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import type { GhExecOptions } from '../github-exec-scope' import { assertRateLimitBudget } from '../lookup/pr-lookup-rate-limit' import { readGraphQLPRCheckRollup } from './pr-check-rollup' diff --git a/src/main/github/client/check/get-pr-check-details.test.ts b/src/main/github/client/check/get-pr-check-details.test.ts new file mode 100644 index 00000000000..91ee402477b --- /dev/null +++ b/src/main/github/client/check/get-pr-check-details.test.ts @@ -0,0 +1,168 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GithubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { ghExecFileAsyncMock, getOwnerRepoMock, rateLimitGuardMock } = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })) +})) + +vi.mock('../../execution/github-legacy-command', () => ({ + execFileAsync: vi.fn() +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + githubRepoContext: (repoPath: string, connectionId?: string | null) => ({ + repoPath, + connectionId: connectionId ?? null + }), + ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }), + getOwnerRepoForRemote: ( + repoPath: string, + remoteName: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => + remoteName === 'origin' + ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) + : Promise.resolve(null), + _resetOwnerRepoCache: vi.fn() +})) + +vi.mock('../../repositories/github-owner-repo-selection', () => ({ + getOwnerRepo: getOwnerRepoMock +})) + +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: vi.fn(), + release: vi.fn() +})) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: vi.fn() +})) + +vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => ({ + ...(await importOriginal()), + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) +})) + +vi.mock('../../api/rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: vi.fn(), + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: vi.fn(), + spendsSharedGitHubComQuota: vi.fn(() => true) +})) + +import { getPRCheckDetails } from './get-pr-check-details' +import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity' + +describe('getPRCheckDetails', () => { + beforeEach(() => { + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + _resetOwnerRepoCache() + }) + + it('aborts host work at the cumulative check-details deadline', async () => { + vi.useFakeTimers() + try { + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockImplementation( + (_args: string[], options: { signal?: AbortSignal }) => + new Promise((_resolve, reject) => { + options.signal?.addEventListener( + 'abort', + () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }, + { once: true } + ) + }) + ) + const request = getPRCheckDetails('/repo-root', { checkRunId: 88 }) + const rejection = expect(request).rejects.toThrow('Timed out loading check details.') + + await vi.advanceTimersByTimeAsync(25_000) + + await rejection + } finally { + vi.useRealTimers() + } + }) + + it('stops waiting for shared repository resolution at the host deadline', async () => { + vi.useFakeTimers() + try { + getOwnerRepoMock.mockImplementationOnce(() => new Promise(() => {})) + const request = getPRCheckDetails('/repo-root', { checkRunId: 88 }) + const rejection = expect(request).rejects.toThrow('Timed out loading check details.') + + await vi.advanceTimersByTimeAsync(25_000) + + await rejection + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('reads a fine-grained token check from its Actions job when the check run is refused', async () => { + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + const job = { + id: 71, + run_id: 7, + name: 'pytest', + status: 'completed', + conclusion: 'success', + html_url: 'https://github.com/acme/widgets/actions/runs/7/job/71', + started_at: '2026-11-10T10:00:00Z', + completed_at: '2026-11-10T10:05:00Z', + steps: [] + } + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { + const path = args.at(-1) ?? '' + if (path.includes('/check-runs/71')) { + throw Object.assign(new Error(`Command failed: gh api ${path}`), { + stderr: 'gh: Resource not accessible by personal access token (HTTP 403)\n', + stdout: '' + }) + } + if (path.endsWith('/actions/jobs/71')) { + return { stdout: JSON.stringify(job), stderr: '' } + } + if (path.includes('/actions/runs/7/jobs')) { + return { stdout: JSON.stringify({ jobs: [job] }), stderr: '' } + } + throw new Error(`unexpected ${path}`) + }) + + const details = await getPRCheckDetails('/repo-root', { + checkRunId: 71, + workflowRunId: 7, + checkName: 'pytest' + }) + + expect(details).toMatchObject({ + name: 'pytest', + status: 'completed', + conclusion: 'success', + url: 'https://github.com/acme/widgets/actions/runs/7/job/71', + startedAt: '2026-11-10T10:00:00Z', + completedAt: '2026-11-10T10:05:00Z', + jobs: [{ id: 71, name: 'pytest', status: 'completed', conclusion: 'success' }] + }) + }) +}) diff --git a/src/main/github/client/check/get-pr-check-details.ts b/src/main/github/client/check/get-pr-check-details.ts index 94cd28a040f..bd891ca392f 100644 --- a/src/main/github/client/check/get-pr-check-details.ts +++ b/src/main/github/client/check/get-pr-check-details.ts @@ -1,10 +1,13 @@ -import type { PRCheckRunDetails } from '../../../../shared/github/check-types' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import type { PRCheckRunDetails } from '../../../../shared/github/checks/check-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { GITHUB_CHECK_DETAILS_HOST_TIMEOUT_MS, GITHUB_CHECK_DETAILS_TIMEOUT_MESSAGE -} from '../../../../shared/github/check-details-deadline' +} from '../../../../shared/github/checks/check-details-deadline' import type { GhExecOptions } from './../github-exec-scope' import { nullableString, diff --git a/src/main/github/client/check/get-pr-checks.ts b/src/main/github/client/check/get-pr-checks.ts index 71190923c8f..06184e27b1e 100644 --- a/src/main/github/client/check/get-pr-checks.ts +++ b/src/main/github/client/check/get-pr-checks.ts @@ -1,18 +1,22 @@ -import { normalizePRCheckHeadSha } from '../../../../shared/github/pr-check-head' +import { normalizePRCheckHeadSha } from '../../../../shared/github/checks/pr-check-head' import { withGitHubRepoExecution, githubRepoContext, - ghRepoExecOptions -} from '../../github-repository-identity' + ghRepoExecOptions, + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' -import { githubReadExecutionScope } from '../../github-read-execution-scope' -import type { PRCheckDetail } from '../../../../shared/github/check-types' -import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/github/work-item-ssh-error' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import type { PRCheckDetail } from '../../../../shared/github/checks/check-types' +import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/github/work-items/work-item-ssh-error' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' + import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' -import { mapCheckStatus, mapCheckConclusion } from '../../mappers' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { mapCheckStatus, mapCheckConclusion } from '../../api/github-read-response' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' import type { GhExecOptions } from './../github-exec-scope' import { assertRateLimitBudget } from './../lookup/pr-lookup-rate-limit' import { PR_CHECKS_ROLLUP_QUERY, type GraphQLPRChecksResponse } from './pr-checks-graphql-query' diff --git a/src/main/github/client/check/pr-check-rollup.ts b/src/main/github/client/check/pr-check-rollup.ts index 1a381e4b1b4..0ed6821d97a 100644 --- a/src/main/github/client/check/pr-check-rollup.ts +++ b/src/main/github/client/check/pr-check-rollup.ts @@ -1,7 +1,8 @@ import { z } from 'zod' -import { ghExecFileAsync } from '../../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' import type { GhExecOptions } from '../github-exec-scope' import { isPendingApprovalSuiteWithoutRuns } from './pr-checks-response-mapping' diff --git a/src/main/github/client/check/pr-checks-response-mapping.ts b/src/main/github/client/check/pr-checks-response-mapping.ts index 97c0ed3cde5..0b7591343b5 100644 --- a/src/main/github/client/check/pr-checks-response-mapping.ts +++ b/src/main/github/client/check/pr-checks-response-mapping.ts @@ -1,12 +1,13 @@ -import { normalizePRCheckHeadSha } from '../../../../shared/github/pr-check-head' -import type { PRCheckDetail } from '../../../../shared/github/check-types' -import { githubRepositoryWebHost, type GitHubApiRepository } from '../../github-api-repository' +import { normalizePRCheckHeadSha } from '../../../../shared/github/checks/pr-check-head' +import type { PRCheckDetail } from '../../../../shared/github/checks/check-types' +import { githubRepositoryWebHost } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { mapCheckRunRESTStatus, mapCheckRunRESTConclusion, mapCommitStatusRESTStatus, mapCommitStatusRESTConclusion -} from '../../mappers' +} from '../../api/github-read-response' import type { GraphQLPRChecksResponse, GraphQLCheckRunContext, diff --git a/src/main/github/client/check/rerun-pr-checks.ts b/src/main/github/client/check/rerun-pr-checks.ts index c107e1d7ec7..98e7994d200 100644 --- a/src/main/github/client/check/rerun-pr-checks.ts +++ b/src/main/github/client/check/rerun-pr-checks.ts @@ -1,10 +1,16 @@ -import { withGitHubRepoExecution } from '../../github-repository-identity' -import type { GitHubRerunPRChecksResult } from '../../../../shared/github/check-types' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' +import { + withGitHubRepoExecution, + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' +import type { GitHubRerunPRChecksResult } from '../../../../shared/github/checks/check-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' + // Keep real error parsing available when tests mock gh-utils. import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' -import { classifyRerunChecksError } from '../../gh-error-classification' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import { classifyRerunChecksError } from '../../api/gh-error-classification' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { getPRChecks } from './get-pr-checks' import { parseActionsRunId } from './check-detail-field-mapping' import { codeHostFailure, classifiedFailure } from '../../../../shared/code-host-failure-copy' diff --git a/src/main/github/client/check/rest-pr-check-pages.ts b/src/main/github/client/check/rest-pr-check-pages.ts index a8a9347b748..fa5aac9fdb6 100644 --- a/src/main/github/client/check/rest-pr-check-pages.ts +++ b/src/main/github/client/check/rest-pr-check-pages.ts @@ -1,8 +1,9 @@ import { z } from 'zod' import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' -import { ghExecFileAsync } from '../../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' import type { GhExecOptions } from '../github-exec-scope' import { assertRateLimitBudget } from '../lookup/pr-lookup-rate-limit' import { isPendingApprovalSuiteWithoutRuns } from './pr-checks-response-mapping' diff --git a/src/main/github/client-test-harness.ts b/src/main/github/client/client-test-harness.ts similarity index 89% rename from src/main/github/client-test-harness.ts rename to src/main/github/client/client-test-harness.ts index 424d0dc7157..01fa7484827 100644 --- a/src/main/github/client-test-harness.ts +++ b/src/main/github/client/client-test-harness.ts @@ -1,15 +1,15 @@ import type { Mock } from 'vitest' -import { completePRCheckGraphQLResponse } from '../../shared/github/complete-pr-check-test-fixture' +import { completePRCheckGraphQLResponse } from '../../../shared/github/checks/complete-pr-check-test-fixture' import type { GitHubClientMocks } from './client-test-mocks' -import { _resetOwnerRepoCache } from './gh-utils' -import { _resetMergeQueueCacheForTests } from './client/detect/repository-merge-metadata-cache' -import { _resetPRStackSummaryCacheForTests } from './client/lookup/pr-stack-summary-cache' -import { __resetTrackedUpstreamBranchCacheForTests } from './client/lookup/tracked-upstream-cache' -import { __resetPRConflictSummaryCachesForTests } from './conflict-summary' -import { resetMergedPRCommitMembershipCacheForTest } from './merged-pr-commit-membership' -import { __resetRepoDefaultBranchCacheForTests } from '../source-control/repo-default-branch' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' -import { _resetGitHubPRStackCacheForTests } from './github-pr-stack' +import { _resetOwnerRepoCache } from '../repositories/github-repository-identity' +import { _resetMergeQueueCacheForTests } from './detect/repository-merge-metadata-cache' +import { _resetPRStackSummaryCacheForTests } from './lookup/pr-stack-summary-cache' +import { __resetTrackedUpstreamBranchCacheForTests } from './lookup/tracked-upstream-cache' +import { __resetPRConflictSummaryCachesForTests } from '../pull-requests/conflicts/conflict-summary' +import { resetMergedPRCommitMembershipCacheForTest } from '../pull-requests/refresh/merged-pr-commit-membership' +import { __resetRepoDefaultBranchCacheForTests } from '../../source-control/repo-default-branch' +import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe' +import { _resetGitHubPRStackCacheForTests } from '../pull-requests/stacks/github-pr-stack' export function resetOriginRepositoryCache(): void { _resetOriginGitHubApiRepositoryCache() diff --git a/src/main/github/client-test-mocks.ts b/src/main/github/client/client-test-mocks.ts similarity index 83% rename from src/main/github/client-test-mocks.ts rename to src/main/github/client/client-test-mocks.ts index f04469b3a03..d6e1b1667e8 100644 --- a/src/main/github/client-test-mocks.ts +++ b/src/main/github/client/client-test-mocks.ts @@ -1,9 +1,13 @@ +import type * as GithubApiRepositoryRemoteProbeModule from '../repositories/github-api-repository-remote-probe' import { vi, type Mock } from 'vitest' -import type { ClassifiedError } from '../../shared/classified-error' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' -import type { ghRepoExecOptions, githubRepoContext } from './github-repository-identity' +import type { ClassifiedError } from '../../../shared/classified-error' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' +import type * as GithubApiRepositoryModule from '../repositories/github-api-repository' +import type * as GitHubEnterpriseRepositoryModule from '../repositories/github-enterprise-repository' +import type { + ghRepoExecOptions, + githubRepoContext +} from '../repositories/github-repository-identity' export type RateLimitGuardResult = | { blocked: false } @@ -65,25 +69,17 @@ export function createGitHubClientMocks(): GitHubClientMocks { } } -export type GhUtilsModuleMock = { +export function githubLegacyCommandModuleMock(mocks: GitHubClientMocks): { execFileAsync: Mock - ghExecFileAsync: Mock - getOwnerRepo: Mock - getIssueOwnerRepo: Mock - getOwnerRepoForRemote: Mock - resolvePRRepositoryCandidates: Mock - getRemoteUrlForRepo: Mock - gitExecFileAsync: Mock - ghRepoExecOptions: Mock - githubRepoContext: Mock - classifyGhError: (stderr: string) => ClassifiedError - parseGitHubOwnerRepo: (remoteUrl: string) => GitHubOwnerRepo | null - acquire: Mock - release: Mock - _resetOwnerRepoCache: Mock +} { + return { + execFileAsync: mocks.execFileAsyncMock + } } -export function ghUtilsModuleMock(mocks: GitHubClientMocks): GhUtilsModuleMock { +export function githubHostedCliModuleMock(mocks: GitHubClientMocks): { + ghExecFileAsync: Mock +} { const ghExecFileAsync = vi.fn(async (...args: unknown[]) => { const result = await mocks.ghExecFileAsyncMock(...args) const argv = args[0] @@ -101,16 +97,40 @@ export function ghUtilsModuleMock(mocks: GitHubClientMocks): GhUtilsModuleMock { return result }) return { - execFileAsync: mocks.execFileAsyncMock, - ghExecFileAsync, + ghExecFileAsync + } +} + +export function githubOwnerSelectionModuleMock(mocks: GitHubClientMocks): { + getOwnerRepo: Mock + resolvePRRepositoryCandidates: Mock +} { + return { getOwnerRepo: mocks.getOwnerRepoMock, - getIssueOwnerRepo: mocks.getIssueOwnerRepoMock, + resolvePRRepositoryCandidates: mocks.resolvePRRepositoryCandidatesMock + } +} + +export function githubRepositoryIdentityModuleMock(mocks: GitHubClientMocks): { + getOwnerRepoForRemote: Mock + getRemoteUrlForRepo: Mock + ghRepoExecOptions: Mock + githubRepoContext: Mock + _resetOwnerRepoCache: Mock +} { + return { getOwnerRepoForRemote: mocks.getOwnerRepoForRemoteMock, - resolvePRRepositoryCandidates: mocks.resolvePRRepositoryCandidatesMock, getRemoteUrlForRepo: mocks.getRemoteUrlForRepoMock, - gitExecFileAsync: mocks.gitExecFileAsyncMock, ghRepoExecOptions: mocks.ghRepoExecOptionsMock, githubRepoContext: mocks.githubRepoContextMock, + _resetOwnerRepoCache: vi.fn() + } +} + +export function githubErrorClassificationModuleMock(): { + classifyGhError: (stderr: string) => ClassifiedError +} { + return { classifyGhError: (stderr: string) => { const lower = stderr.toLowerCase() if (lower.includes('not found') || stderr.includes('HTTP 404')) { @@ -123,14 +143,28 @@ export function ghUtilsModuleMock(mocks: GitHubClientMocks): GhUtilsModuleMock { return { type: 'permission_denied', message: stderr } } return { type: 'unknown', message: stderr } - }, + } + } +} + +export function githubRemoteIdentityParsingModuleMock(): { + parseGitHubOwnerRepo: (remoteUrl: string) => GitHubOwnerRepo | null +} { + return { parseGitHubOwnerRepo: (remoteUrl: string) => { const match = remoteUrl.trim().match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/) return match ? { owner: match[1], repo: match[2] } : null - }, + } + } +} + +export function githubOperationSlotsModuleMock(mocks: GitHubClientMocks): { + acquire: Mock + release: Mock +} { + return { acquire: mocks.acquireMock, - release: mocks.releaseMock, - _resetOwnerRepoCache: vi.fn() + release: mocks.releaseMock } } @@ -210,6 +244,27 @@ export function githubApiRepositoryModuleMock( connectionId?: string | null, localGitOptions?: unknown ) => mocks.resolvePRRepositoryCandidatesMock(repoPath, connectionId, localGitOptions), + getIssueGitHubApiRepository: async (repoPath: string, connectionId?: string | null) => { + const slug = await mocks.getIssueOwnerRepoMock(repoPath, connectionId) + return slug ? { host: 'github.com', ...slug } : slug + }, + resolveIssueGitHubApiRepositorySource: async ( + repoPath: string, + _preference: unknown, + connectionId?: string | null + ) => { + const slug = await mocks.getIssueOwnerRepoMock(repoPath, connectionId) + return { source: slug ? { host: 'github.com', ...slug } : slug, fellBack: false } + } + } +} + +export function githubApiRepositoryRemoteProbeModuleMock( + mocks: GitHubClientMocks, + actual: typeof GithubApiRepositoryRemoteProbeModule +): typeof GithubApiRepositoryRemoteProbeModule { + return { + ...actual, getGitHubApiRepositoryForRemote: ( repoPath: string, remoteName: string, @@ -230,18 +285,6 @@ export function githubApiRepositoryModuleMock( const slug = fromRemote ?? (await mocks.getOwnerRepoMock(repoPath, connectionId, localGitOptions)) return slug ? { host: 'github.com', ...slug } : slug - }, - getIssueGitHubApiRepository: async (repoPath: string, connectionId?: string | null) => { - const slug = await mocks.getIssueOwnerRepoMock(repoPath, connectionId) - return slug ? { host: 'github.com', ...slug } : slug - }, - resolveIssueGitHubApiRepositorySource: async ( - repoPath: string, - _preference: unknown, - connectionId?: string | null - ) => { - const slug = await mocks.getIssueOwnerRepoMock(repoPath, connectionId) - return { source: slug ? { host: 'github.com', ...slug } : slug, fellBack: false } } } } diff --git a/src/main/github/client/create/add-pr-review-comment.ts b/src/main/github/client/create/add-pr-review-comment.ts index 25d298241ad..e359a3a5b6f 100644 --- a/src/main/github/client/create/add-pr-review-comment.ts +++ b/src/main/github/client/create/add-pr-review-comment.ts @@ -1,16 +1,14 @@ -import { githubBodyMediaHeaders } from '../../body-image-urls' +import { githubBodyMediaHeaders } from '../../attachments/body-image-urls' import type { GitHubCommentResult, GitHubPRReviewCommentInput -} from '../../../../shared/github/comment-types' -import { - ghExecFileAsync, - acquire, - release, - classifyGhError, - type LocalGitExecOptions -} from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +} from '../../../../shared/github/comments/comment-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import { classifyGhError } from '../../api/gh-error-classification' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { mapReviewCommentResponse } from './../map/review-comment-response' import { codeHostFailure, classifiedFailure } from '../../../../shared/code-host-failure-copy' export async function addPRReviewComment( diff --git a/src/main/github/client/create/create-github-pull-request.test.ts b/src/main/github/client/create/create-github-pull-request.test.ts new file mode 100644 index 00000000000..fb232381e88 --- /dev/null +++ b/src/main/github/client/create/create-github-pull-request.test.ts @@ -0,0 +1,155 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + ghExecFileAsyncMock, + getOwnerRepoMock, + getOwnerRepoForRemoteMock, + getEnterpriseGitHubRepoSlugMock, + extractExecErrorMock, + acquireMock, + releaseMock +} = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + getOwnerRepoForRemoteMock: vi.fn(), + getEnterpriseGitHubRepoSlugMock: vi.fn(), + extractExecErrorMock: vi.fn((error: unknown) => { + const value = error as { stderr?: string; stdout?: string; message?: string } + return { + stderr: value?.stderr ?? value?.message ?? '', + stdout: value?.stdout ?? '' + } + }), + acquireMock: vi.fn(), + releaseMock: vi.fn() +})) + +vi.mock('../../execution/github-legacy-command', () => ({ + execFileAsync: vi.fn() +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../../repositories/github-owner-repo-selection', () => ({ + getOwnerRepo: getOwnerRepoMock +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + getOwnerRepoForRemote: getOwnerRepoForRemoteMock, + githubRepoContext: vi.fn((repoPath: string, connectionId?: string | null, options = {}) => ({ + ...options, + repoPath, + connectionId: connectionId ?? null + })), + ghRepoExecOptions: vi.fn( + (context: { repoPath: string; connectionId?: string | null; wslDistro?: string }) => + context.connectionId + ? {} + : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) } + ), + _resetOwnerRepoCache: vi.fn() +})) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: vi.fn() +})) + +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: acquireMock, + release: releaseMock +})) + +vi.mock('../../repositories/github-enterprise-repository', () => ({ + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) +})) + +import { createGitHubPullRequest } from './create-github-pull-request' + +import { _resetOriginGitHubApiRepositoryCache } from '../../repositories/github-api-repository-remote-probe' + +beforeEach(() => { + _resetOriginGitHubApiRepositoryCache() +}) + +describe('createGitHubPullRequest', () => { + beforeEach(() => { + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getOwnerRepoForRemoteMock.mockReset() + // Bridge explicit-origin creation to the fixtures that define getOwnerRepoMock. + getOwnerRepoForRemoteMock.mockImplementation( + async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => + remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null + ) + getEnterpriseGitHubRepoSlugMock.mockReset() + getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) + extractExecErrorMock.mockClear() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + }) + + it('returns the existing PR when gh reports an already-open pull request', async () => { + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock + .mockRejectedValueOnce({ stderr: 'a pull request already exists for feature/existing' }) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 44, + url: 'https://github.com/acme/widgets/pull/44' + } + ]) + }) + + await expect( + createGitHubPullRequest( + '/repo-root', + { + provider: 'github', + base: 'main', + head: 'refs/remotes/origin/feature/existing', + title: 'Existing' + }, + 'local' + ) + ).resolves.toEqual({ + ok: false, + code: 'already_exists', + error: 'A pull request already exists for this branch.', + reason: 'existing_review', + existingReview: { + number: 44, + url: 'https://github.com/acme/widgets/pull/44' + } + }) + + expect(ghExecFileAsyncMock.mock.calls[1]).toEqual([ + [ + 'pr', + 'list', + '--repo', + 'acme/widgets', + '--head', + 'feature/existing', + '--base', + 'main', + '--state', + 'open', + '--limit', + '2', + '--json', + 'number,url' + ], + // Pin dotcom against process-level GH_HOST. + { cwd: '/repo-root', host: 'github.com' } + ]) + }) +}) diff --git a/src/main/github/client/create/create-github-pull-request.ts b/src/main/github/client/create/create-github-pull-request.ts index e92a6716cfb..33dfae27346 100644 --- a/src/main/github/client/create/create-github-pull-request.ts +++ b/src/main/github/client/create/create-github-pull-request.ts @@ -11,21 +11,22 @@ import { import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { tmpdir } from 'node:os' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' import { - ghExecFileAsync, - acquire, - release, ghRepoExecOptions, - githubRepoContext -} from '../../gh-utils' + githubRepoContext, + withGitHubRepoExecution +} from '../../repositories/github-repository-identity' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' -import { getOriginGitHubApiRepository, githubHostExecOptions } from '../../github-api-repository' +import { getOriginGitHubApiRepository } from '../../repositories/github-api-repository-remote-probe' +import { githubHostExecOptions } from '../../repositories/github-repository-host' import { classifyCreatePRError, parseCreatePRPayload } from './create-pr-error-classification' import { findOpenPRByHeadBase, readPullRequestTemplate } from './pull-request-template' -import { withGitHubRepoExecution } from '../../github-repository-identity' + export async function createGitHubPullRequest( repoPath: string, input: CreateHostedReviewInput, diff --git a/src/main/github/client/create/pull-request-template.ts b/src/main/github/client/create/pull-request-template.ts index e1659791c74..1f8f8fe9e5a 100644 --- a/src/main/github/client/create/pull-request-template.ts +++ b/src/main/github/client/create/pull-request-template.ts @@ -1,11 +1,13 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { ghExecFileAsync, ghRepoExecOptions, githubRepoContext } from '../../gh-utils' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { ghRepoExecOptions, githubRepoContext } from '../../repositories/github-repository-identity' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' export async function findOpenPRByHeadBase(args: { repoPath: string repo: GitHubApiRepository diff --git a/src/main/github/client/detect/hydrate-work-item-merge-metadata.ts b/src/main/github/client/detect/hydrate-work-item-merge-metadata.ts index f856603cc48..d7b3f51102c 100644 --- a/src/main/github/client/detect/hydrate-work-item-merge-metadata.ts +++ b/src/main/github/client/detect/hydrate-work-item-merge-metadata.ts @@ -1,4 +1,4 @@ -import type { OwnerRepo } from '../../gh-utils' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' import type { GhExecOptions } from './../github-exec-scope' import { detectRepositoryMergeMetadata } from './repository-merge-metadata' import type { MainWorkItem } from './../map/work-item-field-coercion' diff --git a/src/main/github/client/detect/repository-merge-metadata-cache.ts b/src/main/github/client/detect/repository-merge-metadata-cache.ts index 2e09fa243e0..e09ddafae5d 100644 --- a/src/main/github/client/detect/repository-merge-metadata-cache.ts +++ b/src/main/github/client/detect/repository-merge-metadata-cache.ts @@ -1,4 +1,4 @@ -import type { GitHubPRMergeMethodSettings } from '../../../../shared/github/pull-request-types' +import type { GitHubPRMergeMethodSettings } from '../../../../shared/github/pull-requests/pull-request-types' import type { CoalescedProbes } from '../../../git/remotes/coalesced-probe' export const MERGE_QUEUE_CACHE_TTL_MS = 10 * 60 * 1000 diff --git a/src/main/github/repository-merge-metadata-reuse.test.ts b/src/main/github/client/detect/repository-merge-metadata-reuse.test.ts similarity index 96% rename from src/main/github/repository-merge-metadata-reuse.test.ts rename to src/main/github/client/detect/repository-merge-metadata-reuse.test.ts index a981357ccd9..a7b8e56d7a8 100644 --- a/src/main/github/repository-merge-metadata-reuse.test.ts +++ b/src/main/github/client/detect/repository-merge-metadata-reuse.test.ts @@ -1,14 +1,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { exec, guard, spend } = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn(), spend: vi.fn() })) -vi.mock('./gh-utils', () => ({ ghExecFileAsync: exec })) -vi.mock('./rate-limit', () => ({ +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: exec +})) +vi.mock('../../api/rate-limit', () => ({ repositoryRateLimitGuard: guard, noteRepositoryRateLimitSpend: spend })) -import { detectRepositoryMergeMetadata } from './client/detect/repository-merge-metadata' -import { _resetMergeQueueCacheForTests } from './client/detect/repository-merge-metadata-cache' +import { detectRepositoryMergeMetadata } from './repository-merge-metadata' +import { _resetMergeQueueCacheForTests } from './repository-merge-metadata-cache' const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } const options = { cwd: '/repo' } diff --git a/src/main/github/client/detect/repository-merge-metadata.ts b/src/main/github/client/detect/repository-merge-metadata.ts index bfaad9c165f..44183eeaeda 100644 --- a/src/main/github/client/detect/repository-merge-metadata.ts +++ b/src/main/github/client/detect/repository-merge-metadata.ts @@ -1,11 +1,12 @@ import { posix, win32 } from 'node:path' -import { normalizeGitHubPRMergeMethodSettings } from '../../../../shared/github/pull-request-merge-methods' +import { normalizeGitHubPRMergeMethodSettings } from '../../../../shared/github/pull-requests/merge/pull-request-merge-methods' import { mergeCommandEnvironment } from '../../../../shared/command-environment' -import { ghExecFileAsync } from '../../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' -import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' -import { githubReadExecutionScope } from '../../github-read-execution-scope' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' import { runCoalescedProbe } from '../../../git/remotes/coalesced-probe' import { parseWslUncPath } from '../../../../shared/wsl-paths' import type { GhExecOptions } from './../github-exec-scope' diff --git a/src/main/github/client/fetch/authenticated-viewer.ts b/src/main/github/client/fetch/authenticated-viewer.ts index 92ebd0877b3..717875b9b0b 100644 --- a/src/main/github/client/fetch/authenticated-viewer.ts +++ b/src/main/github/client/fetch/authenticated-viewer.ts @@ -1,5 +1,6 @@ -import type { GitHubViewer } from '../../../../shared/github/pull-request-types' -import { ghExecFileAsync, acquire, release } from '../../gh-utils' +import type { GitHubViewer } from '../../../../shared/github/pull-requests/pull-request-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' /** Use the bounded runner so failed viewer probes return null without stranding a GitHub admission slot. */ export async function getAuthenticatedViewer(): Promise { await acquire() diff --git a/src/main/github/client/fetch/get-pr-comments.ts b/src/main/github/client/fetch/get-pr-comments.ts index 9984514b988..3dddd10d4ea 100644 --- a/src/main/github/client/fetch/get-pr-comments.ts +++ b/src/main/github/client/fetch/get-pr-comments.ts @@ -1,12 +1,15 @@ -import { GITHUB_BODY_MEDIA_TYPE } from '../../body-image-urls' -import type { PRComment } from '../../../../shared/github/comment-types' +import { GITHUB_BODY_MEDIA_TYPE } from '../../attachments/body-image-urls' +import type { PRComment } from '../../../../shared/github/comments/comment-types' import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' -import { githubReadExecutionScope } from '../../github-read-execution-scope' -import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/github/work-item-ssh-error' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/github/work-items/work-item-ssh-error' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' import { assertRateLimitBudget } from './../lookup/pr-lookup-rate-limit' import { REVIEW_THREADS_QUERY } from './pr-review-threads-query' diff --git a/src/main/github/client/fetch/get-work-item-check-summary.test.ts b/src/main/github/client/fetch/get-work-item-check-summary.test.ts new file mode 100644 index 00000000000..c130d488fe1 --- /dev/null +++ b/src/main/github/client/fetch/get-work-item-check-summary.test.ts @@ -0,0 +1,167 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { ghExecFileAsyncMock, getOwnerRepoMock, rateLimitGuardMock } = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })) +})) + +vi.mock('../../execution/github-legacy-command', () => ({ + execFileAsync: vi.fn() +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + githubRepoContext: (repoPath: string, connectionId?: string | null) => ({ + repoPath, + connectionId: connectionId ?? null + }), + ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }), + getOwnerRepoForRemote: ( + repoPath: string, + remoteName: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => + remoteName === 'origin' + ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) + : Promise.resolve(null), + _resetOwnerRepoCache: vi.fn() +})) + +vi.mock('../../repositories/github-owner-repo-selection', () => ({ + getOwnerRepo: getOwnerRepoMock, + resolveIssueSource: vi.fn() +})) + +vi.mock('../../../git/command-runner/process-capture/exec-error', async (importOriginal) => ({ + ...(await importOriginal>()), + extractExecError: vi.fn((err: unknown) => ({ stderr: String(err), stdout: '' })) +})) + +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: vi.fn(), + release: vi.fn() +})) + +vi.mock('../../api/gh-error-classification', () => ({ + classifyGhError: (stderr: string) => ({ type: 'unknown', message: stderr }), + classifyListIssuesError: (stderr: string) => ({ type: 'unknown', message: stderr }) +})) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: vi.fn() +})) + +vi.mock('../../api/rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: vi.fn(), + getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: vi.fn(), + spendsSharedGitHubComQuota: vi.fn(() => true) +})) + +import { getWorkItem } from './get-work-item' +import { _resetMergeQueueCacheForTests } from '../detect/repository-merge-metadata-cache' +import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity' +import { _resetOriginGitHubApiRepositoryCache } from '../../repositories/github-api-repository-remote-probe' + +// Metadata and complete checks are independent provider responses. +function mockPullRequestDetail(payload: Record): void { + const head = 'a'.repeat(40) + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'pr' && args[1] === 'view') { + return { stdout: JSON.stringify({ ...payload, headRefOid: head }) } + } + if (args.includes('graphql') && args.some((arg) => arg.includes('statusCheckRollup'))) { + return { + stdout: JSON.stringify({ + data: { + repository: { + pullRequest: { + number: payload.number, + headRefOid: head, + commits: { + nodes: [ + { + commit: { + oid: head, + statusCheckRollup: { + contexts: { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these test payloads contain object rollup rows only. + nodes: (payload.statusCheckRollup as Record[]).map( + (raw) => ({ + ...raw, + __typename: + raw.__typename ?? (raw.state ? 'StatusContext' : 'CheckRun'), + ...(!raw.state ? { checkSuite: { databaseId: 7 } } : {}) + }) + ), + pageInfo: { hasNextPage: false, endCursor: null } + } + }, + checkSuites: { + nodes: [], + pageInfo: { hasNextPage: false, endCursor: null } + } + } + } + ] + } + } + } + } + }) + } + } + throw new Error('unexpected gh call') + }) +} + +describe('work item checksSummary', () => { + beforeEach(() => { + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + _resetOwnerRepoCache() + _resetOriginGitHubApiRepositoryCache() + _resetMergeQueueCacheForTests() + getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) + }) + + it('counts a skipped run as passing and reads a StatusContext state as its conclusion', async () => { + mockPullRequestDetail({ + number: 42, + title: 'Add feature', + state: 'OPEN', + url: 'https://github.com/acme/widgets/pull/42', + updatedAt: '2026-04-01T00:00:00Z', + statusCheckRollup: [ + { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'SKIPPED' }, + // StatusContext supplies state instead of CheckRun's status/conclusion. + { __typename: 'StatusContext', state: 'SUCCESS' }, + { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'NEUTRAL' } + ] + }) + + const item = await getWorkItem('/repo-root', 42, 'pr', null, {}, 'origin') + + expect(item?.checksSummary).toEqual({ + state: 'success', + total: 3, + passed: 2, + failed: 0, + cancelled: 0, + pending: 0, + neutral: 1 + }) + }) +}) diff --git a/src/main/github/client/fetch/get-work-item-details-reuse.test.ts b/src/main/github/client/fetch/get-work-item-details-reuse.test.ts new file mode 100644 index 00000000000..a1ddd312fd4 --- /dev/null +++ b/src/main/github/client/fetch/get-work-item-details-reuse.test.ts @@ -0,0 +1,170 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import { beforeEach, expect, it, vi } from 'vitest' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' + +const mocks = vi.hoisted(() => ({ + exec: vi.fn(), + source: vi.fn(), + acquire: vi.fn(), + release: vi.fn() +})) +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: mocks.exec +})) + +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: mocks.acquire, + release: mocks.release +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ghRepoExecOptions: (context: { repoPath: string; connectionId?: string; wslDistro?: string }) => + context.connectionId + ? {} + : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }, + githubRepoContext: (repoPath: string, connectionId?: string, options = {}) => ({ + repoPath, + connectionId, + ...options + }) +})) + +vi.mock('../../api/gh-error-classification', () => ({ + classifyGhError: () => ({ type: 'not_found' }) +})) +vi.mock('../../repositories/github-api-repository', () => ({ + resolveIssueGitHubApiRepositorySource: mocks.source +})) + +vi.mock('../../repositories/github-repository-host', () => ({ + githubHostExecOptions: (repository?: GitHubApiRepository) => ({ host: repository?.host }) +})) +vi.mock('../check/get-pr-checks', async () => ({ + ...(await import('./get-work-item')), + getPRChecks: vi.fn() +})) + +vi.mock('./get-pr-comments', async () => ({ + ...(await import('./get-work-item')), + getPRComments: vi.fn() +})) +vi.mock('../../api/rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: vi.fn() +})) + +import { getWorkItemWithRepository } from './get-work-item' + +const repository = { owner: 'team', repo: 'widgets', host: 'github.example.com:8443' } +let issue: Record +beforeEach(() => { + vi.clearAllMocks() + mocks.source.mockResolvedValue({ source: repository, fellBack: false }) + issue = { + number: 5, + title: 'Closed issue', + state: 'CLOSED', + url: 'https://github.example.com:8443/team/widgets/issues/5', + updatedAt: '2026-10-01T00:00:00Z', + author: { __typename: 'User', login: 'author', avatarUrl: 'https://avatars.example/author' }, + labels: { nodes: [{ name: 'bug' }, { name: 'urgent' }], pageInfo: { hasNextPage: false } }, + body: 'Description', + assignees: { + pageInfo: { hasNextPage: false }, + nodes: [ + { login: 'assigned', name: 'Assigned User', avatarUrl: 'https://avatars.example/assigned' } + ] + }, + participants: { nodes: [] }, + comments: { + nodes: [ + { + databaseId: 10, + body: 'Comment', + createdAt: '2026-10-02T00:00:00Z', + url: 'https://example/comment', + author: { login: 'bot', __typename: 'Bot' } + } + ] + } + } + mocks.exec.mockImplementation(async (args: string[]) => ({ + stdout: JSON.stringify( + args.includes('graphql') + ? { data: { repository: { issue } } } + : args.some((arg) => arg.includes('/timeline?')) + ? [] + : { + number: 5, + title: 'REST issue', + state: 'open', + labels: [{ name: 'all labels' }], + assignees: [{ login: 'rest-assigned', name: 'REST Assigned User' }] + } + ) + })) +}) + +it.each(['incomplete labels', 'invalid metadata', 'partial errors'])( + 'retains the REST item fallback for %s', + async (reason) => { + if (reason === 'incomplete labels') { + issue.labels = { nodes: [{ name: 'partial' }], pageInfo: { hasNextPage: true } } + } + if (reason === 'invalid metadata') { + issue.number = 6 + } + if (reason === 'partial errors') { + mocks.exec.mockResolvedValueOnce({ + stdout: JSON.stringify({ + data: { repository: { issue } }, + errors: [{ message: 'Unavailable metadata' }] + }) + }) + } + const result = await getWorkItemWithRepository( + '/repo', + 5, + 'issue', + undefined, + {}, + 'origin', + true + ) + expect(result.item).toMatchObject({ title: 'REST issue', labels: ['all labels'] }) + if (reason === 'incomplete labels') { + expect(result.issueDetails).toMatchObject({ body: 'Description', timelineItems: [] }) + expect(mocks.exec).toHaveBeenCalledTimes(3) + } else { + expect(result.issueDetails).toBeNull() + expect(mocks.exec).toHaveBeenCalledTimes(2) + } + expect(mocks.exec.mock.calls.at(-1)?.[0]).toEqual(['api', 'repos/team/widgets/issues/5']) + } +) + +it.each([ + { reason: 'missing nodes', nodes: undefined }, + { reason: 'null nodes', nodes: null }, + { reason: 'null entry', nodes: [null] }, + { reason: 'missing login', nodes: [{}] }, + { reason: 'empty login', nodes: [{ login: '' }] } +])('retains conversation and recovers issue assignees for $reason', async ({ nodes }) => { + issue.assignees = { nodes, pageInfo: { hasNextPage: false } } + const result = await getWorkItemWithRepository('/repo', 5, 'issue', undefined, {}, 'origin', true) + expect(result.item).toMatchObject({ + title: 'REST issue', + assignees: [{ login: 'rest-assigned', name: 'REST Assigned User' }] + }) + expect(result.issueDetails).toMatchObject({ + body: 'Description', + comments: [{ id: 10, isBot: true }], + timelineItems: [] + }) + expect(mocks.exec.mock.calls.map(([args]) => args)).toEqual([ + expect.arrayContaining(['api', 'graphql', 'includeItem=true']), + expect.arrayContaining(['api', 'repos/team/widgets/issues/5/timeline?per_page=100&page=1']), + ['api', 'repos/team/widgets/issues/5'] + ]) +}) diff --git a/src/main/github/client/fetch/get-work-item-origin-preference.test.ts b/src/main/github/client/fetch/get-work-item-origin-preference.test.ts new file mode 100644 index 00000000000..3112a829da6 --- /dev/null +++ b/src/main/github/client/fetch/get-work-item-origin-preference.test.ts @@ -0,0 +1,203 @@ +import type * as GithubLegacyCommandModule from '../../execution/github-legacy-command' +import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubOwnerRepoSelectionModule from '../../repositories/github-owner-repo-selection' +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GithubOperationSlotsModule from '../../execution/github-operation-slots' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + ghExecFileAsyncMock, + getOwnerRepoMock, + getIssueOwnerRepoMock, + getOwnerRepoForRemoteMock, + resolvePRRepositoryCandidatesMock, + resolveIssueSourceMock, + rateLimitGuardMock, + noteRateLimitSpendMock, + acquireMock, + releaseMock +} = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + getIssueOwnerRepoMock: vi.fn(), + getOwnerRepoForRemoteMock: vi.fn(), + resolvePRRepositoryCandidatesMock: vi.fn(), + resolveIssueSourceMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), + acquireMock: vi.fn(), + releaseMock: vi.fn() +})) + +vi.mock('../../execution/github-legacy-command', async () => { + const actual = await vi.importActual( + '../../execution/github-legacy-command' + ) + return { + ...actual, + execFileAsync: vi.fn() + } +}) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async () => { + const actual = await vi.importActual( + '../../../git/command-runner/hosted-cli/gh-exec-file' + ) + return { + ...actual, + ghExecFileAsync: ghExecFileAsyncMock + } +}) + +vi.mock('../../repositories/github-owner-repo-selection', async () => { + const actual = await vi.importActual( + '../../repositories/github-owner-repo-selection' + ) + return { + ...actual, + getOwnerRepo: getOwnerRepoMock, + resolveIssueSource: resolveIssueSourceMock + } +}) + +vi.mock('../../repositories/github-repository-identity', async () => { + const actual = await vi.importActual( + '../../repositories/github-repository-identity' + ) + return { + ...actual, + getOwnerRepoForRemote: getOwnerRepoForRemoteMock, + _resetOwnerRepoCache: vi.fn() + } +}) + +vi.mock('../../execution/github-operation-slots', async () => { + const actual = await vi.importActual( + '../../execution/github-operation-slots' + ) + return { + ...actual, + acquire: acquireMock, + release: releaseMock + } +}) + +vi.mock('../../api/rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock, + getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: vi.fn(), + spendsSharedGitHubComQuota: () => true +})) + +vi.mock('../../repositories/github-api-repository', async (importOriginal) => { + return { + ...(await importOriginal()), + resolveIssueGitHubApiRepositorySource: ( + repoPath: string, + preference: unknown, + connectionId?: string | null, + localGitOptions?: unknown + ) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions), + getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) => + getIssueOwnerRepoMock(repoPath, connectionId), + resolveGitHubApiRepositoryCandidates: ( + repoPath: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => resolvePRRepositoryCandidatesMock(repoPath, connectionId, localGitOptions) + } +}) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => { + return { + ...(await importOriginal()), + getOriginGitHubApiRepository: ( + repoPath: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => getOwnerRepoMock(repoPath, connectionId, localGitOptions), + getGitHubApiRepositoryForRemote: ( + repoPath: string, + remoteName: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => + remoteName === 'origin' + ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) + : getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions) + } +}) + +import { getWorkItem } from './get-work-item' +import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity' + +describe('GitHub issue open-by-number origin preference', () => { + beforeEach(() => { + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getIssueOwnerRepoMock.mockReset() + getOwnerRepoForRemoteMock.mockReset() + resolvePRRepositoryCandidatesMock.mockReset() + resolveIssueSourceMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + getOwnerRepoForRemoteMock.mockImplementation( + async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => + remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null + ) + resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => { + const origin = await getOwnerRepoMock(repoPath, connectionId) + const repository = origin ? { host: 'github.com', ...origin } : null + return { candidates: repository ? [repository] : [], headRepo: repository } + }) + _resetOwnerRepoCache() + }) + + it('does not run a bare issue lookup when explicit origin identity is unresolved', async () => { + resolveIssueSourceMock.mockResolvedValueOnce({ source: null, fellBack: false }) + + await expect(getWorkItem('/repo-root', 7, 'issue', null, {}, 'origin')).resolves.toBeNull() + + expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) + expect(getIssueOwnerRepoMock).not.toHaveBeenCalled() + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('skips the issue probe on untyped open when origin identity is unresolved', async () => { + const origin = { owner: 'fork', repo: 'orca', host: 'github.com' } + resolveIssueSourceMock.mockResolvedValueOnce({ source: null, fellBack: false }) + getOwnerRepoMock.mockResolvedValue(origin) + resolvePRRepositoryCandidatesMock.mockResolvedValue({ candidates: [origin], headRepo: origin }) + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 7, + title: 'Origin PR', + state: 'open', + labels: [], + isDraft: false, + url: 'https://github.com/fork/orca/pull/7', + baseRefName: 'main', + headRefName: 'origin/fix', + updatedAt: '2026-04-02T00:00:00Z', + author: { login: 'octocat' } + }) + }) + + const item = await getWorkItem('/repo-root', 7, undefined, null, {}, 'origin') + + expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) + expect(getIssueOwnerRepoMock).not.toHaveBeenCalled() + expect(ghExecFileAsyncMock.mock.calls[0]?.[0]).toEqual( + expect.arrayContaining(['pr', 'view', '--repo', 'fork/orca']) + ) + expect(item).toMatchObject({ number: 7, type: 'pr' }) + }) +}) diff --git a/src/main/github/client/fetch/get-work-item-preview-host.test.ts b/src/main/github/client/fetch/get-work-item-preview-host.test.ts new file mode 100644 index 00000000000..d857a6a469e --- /dev/null +++ b/src/main/github/client/fetch/get-work-item-preview-host.test.ts @@ -0,0 +1,124 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' + +const { clientMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('../client-test-mocks') + return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } +}) + +vi.mock('../../execution/github-legacy-command', () => + moduleMocks.githubLegacyCommandModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-owner-repo-selection', () => + moduleMocks.githubOwnerSelectionModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks) +})) + +vi.mock('../../api/gh-error-classification', () => + moduleMocks.githubErrorClassificationModuleMock() +) + +vi.mock('../../execution/github-operation-slots', () => + moduleMocks.githubOperationSlotsModuleMock(clientMocks) +) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: clientMocks.gitExecFileAsyncMock +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubHostedCliModuleMock(clientMocks) +})) +vi.mock('../../../git/objects/local-git-object-quarantine', () => + moduleMocks.localGitObjectQuarantineModuleMock() +) +vi.mock('../../repositories/local-git-config-signature', () => + moduleMocks.localGitConfigSignatureModuleMock(clientMocks) +) +vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => + moduleMocks.githubEnterpriseRepositoryModuleMock( + await importOriginal() + ) +) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) +vi.mock('../../repositories/github-api-repository', async (importOriginal) => + moduleMocks.githubApiRepositoryModuleMock( + clientMocks, + await importOriginal() + ) +) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => + moduleMocks.githubApiRepositoryRemoteProbeModuleMock( + clientMocks, + await importOriginal() + ) +) +import { getWorkItemByOwnerRepo } from './get-work-item' + +import { + installIndependentCheckFixtures, + resetGraphQLRateLimitGuardMocks +} from '../client-test-harness' + +const { resolvePRRepositoryCandidatesMock } = clientMocks + +const metadataRequests = vi.fn() +const unexpectedChecks: string[][] = [] +afterEach(() => expect(unexpectedChecks).toEqual([])) + +describe('GitHub GraphQL rate-limit guard', () => { + beforeEach(() => { + resetGraphQLRateLimitGuardMocks(clientMocks) + installIndependentCheckFixtures(clientMocks, metadataRequests, unexpectedChecks) + }) + + afterEach(() => vi.restoreAllMocks()) + + it('lets a link preview read another repository only on a configured host', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValue({ + candidates: [{ owner: 'acme', repo: 'widgets', host: 'github.com' }], + headRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' } + }) + const other = { owner: 'other', repo: 'tools', host: 'github.com' } + const unknownHost = { owner: 'victim', repo: 'secrets', host: 'evil.example.test' } + + await expect(getWorkItemByOwnerRepo('/repo-root', other, 7, 'pr')).resolves.toBeNull() + await expect( + getWorkItemByOwnerRepo('/repo-root', unknownHost, 7, 'pr', undefined, {}, { preview: true }) + ).resolves.toBeNull() + expect(metadataRequests).not.toHaveBeenCalled() + + metadataRequests.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 7, + title: 'Tools PR', + state: 'open', + html_url: 'https://github.com/other/tools/pull/7', + updated_at: '2026-04-01T00:00:00Z', + user: { login: 'someone' }, + labels: [], + head: { ref: 'feature', sha: 'head-oid' }, + base: { ref: 'main' } + }) + }) + await expect( + getWorkItemByOwnerRepo('/repo-root', other, 7, 'pr', undefined, {}, { preview: true }) + ).resolves.toMatchObject({ title: 'Tools PR' }) + expect(metadataRequests.mock.calls[0]?.[0]).toEqual(['api', 'repos/other/tools/pulls/7']) + }) +}) diff --git a/src/main/github/client/fetch/get-work-item.ts b/src/main/github/client/fetch/get-work-item.ts index 3f3222036aa..7aedb398a8b 100644 --- a/src/main/github/client/fetch/get-work-item.ts +++ b/src/main/github/client/fetch/get-work-item.ts @@ -1,27 +1,27 @@ -import { withGitHubRepoExecution } from '../../github-repository-identity' -import type { IssueSourcePreference } from '../../../../shared/repo-types' import { - acquire, - release, - classifyGhError, - extractExecError, + withGitHubRepoExecution, type LocalGitExecOptions -} from '../../gh-utils' +} from '../../repositories/github-repository-identity' +import type { IssueSourcePreference } from '../../../../shared/repo-types' +import { acquire, release } from '../../execution/github-operation-slots' +import { classifyGhError } from '../../api/gh-error-classification' +import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' + import { resolveGitHubApiRepository, resolveGitHubApiRepositoryCandidates, - resolveIssueGitHubApiRepositorySource, - type GitHubApiRepository -} from '../../github-api-repository' + resolveIssueGitHubApiRepositorySource +} from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { githubRepoIdentityKey, isDefaultGitHubHost -} from '../../../../shared/github/repository-identity-key' +} from '../../../../shared/github/repositories/repository-identity-key' import type { MainWorkItem } from './../map/work-item-field-coercion' import { getIssueDetailsViaGraphQL, type CollapsedIssueDetails -} from '../../issue-work-item-details' +} from '../../issues/issue-work-item-details' import { fetchIssueWorkItem, fetchWorkItemPreview, diff --git a/src/main/github/client/fetch/orca-star.ts b/src/main/github/client/fetch/orca-star.ts index aa29d0007f1..d486b2ab667 100644 --- a/src/main/github/client/fetch/orca-star.ts +++ b/src/main/github/client/fetch/orca-star.ts @@ -1,4 +1,5 @@ -import { ghExecFileAsync, acquire, release } from '../../gh-utils' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' import { runAsDefaultWslCliUserAct } from '../../../git/command-runner/hosted-cli/default-wsl-cli-fallback' export const ORCA_REPO = 'stablyai/orca' diff --git a/src/main/github/client/fetch/pr-conversation-response.ts b/src/main/github/client/fetch/pr-conversation-response.ts index 4dd0a251d2e..0ab566f4b3d 100644 --- a/src/main/github/client/fetch/pr-conversation-response.ts +++ b/src/main/github/client/fetch/pr-conversation-response.ts @@ -1,11 +1,11 @@ -import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../../body-image-urls' +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../../attachments/body-image-urls' import type { Nodes } from 'mdast' import { z } from 'zod' import remarkParse from 'remark-parse' import { unified } from 'unified' -import type { PRComment } from '../../../../shared/github/comment-types' -import { mapGraphQLReactionGroups } from '../../comment-reactions' -import { tailDiffHunk } from '../../../../shared/github/pr-comment-diff-hunk' +import type { PRComment } from '../../../../shared/github/comments/comment-types' +import { mapGraphQLReactionGroups } from '../../comments/comment-reactions' +import { tailDiffHunk } from '../../../../shared/github/comments/pr-comment-diff-hunk' import { viewerAuthorship } from '../../../source-control/comment-viewer-authorship' const commentSchema = z.object({ diff --git a/src/main/github/client/fetch/repo-slug-upstream.ts b/src/main/github/client/fetch/repo-slug-upstream.ts index 4184817e685..17f4e5cd241 100644 --- a/src/main/github/client/fetch/repo-slug-upstream.ts +++ b/src/main/github/client/fetch/repo-slug-upstream.ts @@ -1,34 +1,37 @@ +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' import { - ghExecFileAsync, - acquire, - release, getRemoteUrlForRepo, - githubRepoContext, + githubRepoContext +} from '../../repositories/github-repository-identity' +import { parseGitHubRemoteIdentity, - type OwnerRepo -} from '../../gh-utils' + gitHubSshConfigHostAlias, + effectiveGitHubRemoteHost +} from '../../repositories/github-remote-identity-parsing' +import type { + GitHubRepositoryIdentity as OwnerRepo, + GitHubRepositoryIdentity as GitHubApiRepository +} from '../../../../shared/github/repositories/repository-identity' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' import { getGitHubApiRepositoryForRemote, - getOriginGitHubApiRepository, - githubRepositorySlugArg, - resolveGitHubRepoExecution, - type GitHubApiRepository -} from '../../github-api-repository' + getOriginGitHubApiRepository +} from '../../repositories/github-api-repository-remote-probe' +import { githubRepositorySlugArg } from '../../repositories/github-repository-host' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' + import { withSharedRemoteUrlReads } from '../../../git/remotes/remote-url-probe' import { isStableMissingGitRemoteError } from '../../../git/remotes/stable-missing-git-remote-error' import { normalizeForgeWebHost, foldWwwHostAlias } from '../../../../shared/git/remotes/git-remote-host-alias' -import { - gitHubSshConfigHostAlias, - effectiveGitHubRemoteHost -} from '../../github-remote-identity-parsing' -import { resolveSshConfigHostname } from '../../github-ssh-host-alias-resolution' + +import { resolveSshConfigHostname } from '../../repositories/github-ssh-host-alias-resolution' import { hostedReviewLocalGitOptionArgs, sameOwnerRepo } from './../github-exec-scope' export async function getRepoSlug( repoPath: string, diff --git a/src/main/github/client/fetch/work-item-fetch.ts b/src/main/github/client/fetch/work-item-fetch.ts index fc03ece6b16..bb0cf7daeac 100644 --- a/src/main/github/client/fetch/work-item-fetch.ts +++ b/src/main/github/client/fetch/work-item-fetch.ts @@ -1,12 +1,13 @@ import type { IssueSourcePreference } from '../../../../shared/repo-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { classifyGhError } from '../../api/gh-error-classification' import { - ghExecFileAsync, - classifyGhError, ghRepoExecOptions, githubRepoContext, type LocalGitExecOptions -} from '../../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' +} from '../../repositories/github-repository-identity' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { githubPRStackExecutionScope, type GhExecOptions } from './../github-exec-scope' import { resolvePullRequestLookupCandidates } from './../pull-request-lookup-candidates' import { detectRepositoryMergeMetadata } from './../detect/repository-merge-metadata' diff --git a/src/main/github/client/gh-error-predicates.ts b/src/main/github/client/gh-error-predicates.ts index 96ed27e0ced..6e8b78fa41d 100644 --- a/src/main/github/client/gh-error-predicates.ts +++ b/src/main/github/client/gh-error-predicates.ts @@ -1,9 +1,9 @@ -import type { PRRefreshOutcome } from '../../../shared/github/pull-request-refresh-types' +import type { PRRefreshOutcome } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { classifyPRRefreshError, safePRRefreshErrorMessage -} from '../pr-refresh-error-classification' -import { classifyGhError } from '../gh-utils' +} from '../pull-requests/refresh/pr-refresh-error-classification' +import { classifyGhError } from '../api/gh-error-classification' // Keep real error parsing available when tests mock gh-utils. import { extractExecError, diff --git a/src/main/github/client/github-exec-scope.ts b/src/main/github/client/github-exec-scope.ts index 44683ecea6a..e2e0bc315d7 100644 --- a/src/main/github/client/github-exec-scope.ts +++ b/src/main/github/client/github-exec-scope.ts @@ -1,11 +1,13 @@ -import type { LocalGitExecOptions, OwnerRepo } from '../gh-utils' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../shared/github/repositories/repository-identity' import { hasHostedReviewLocalGitOptions, - getHostedReviewLocalGitOptions + getHostedReviewLocalGitOptions, + type HostedReviewExecutionOptions } from '../../source-control/hosted-review-git-options' -import type { HostedReviewExecutionOptions } from '../../source-control/hosted-review-git-options' -import type { GitHubRepoExecOptions } from '../github-api-repository' -import { githubRepoIdentityKey } from '../../../shared/github/repository-identity-key' + +import type { GitHubRepoExecOptions } from '../repositories/github-api-repository' +import { githubRepoIdentityKey } from '../../../shared/github/repositories/repository-identity-key' export type GhExecOptions = GitHubRepoExecOptions & { signal?: AbortSignal } export type HostedReviewLocalGitOptions = ReturnType diff --git a/src/main/github/client/list/count-work-items.ts b/src/main/github/client/list/count-work-items.ts index c7d75b9b5be..54423354641 100644 --- a/src/main/github/client/list/count-work-items.ts +++ b/src/main/github/client/list/count-work-items.ts @@ -1,27 +1,27 @@ -import { withGitHubRepoExecution } from '../../github-repository-identity' -import type { IssueSourcePreference } from '../../../../shared/repo-types' -import { isGitHubWorkItemsQueryTooLarge } from '../../../../shared/github/work-items-query-bounds' -import { parseTaskQuery, type ParsedTaskQuery } from '../../../../shared/work-items/task-query' import { - ghExecFileAsync, - acquire, - release, + withGitHubRepoExecution, ghRepoExecOptions, githubRepoContext, - type LocalGitExecOptions, - type OwnerRepo -} from '../../gh-utils' + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' +import type { IssueSourcePreference } from '../../../../shared/repo-types' +import { isGitHubWorkItemsQueryTooLarge } from '../../../../shared/github/work-items/work-items-query-bounds' +import { parseTaskQuery, type ParsedTaskQuery } from '../../../../shared/work-items/task-query' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' + +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { githubHostExecOptions } from '../../repositories/github-repository-host' import { - githubHostExecOptions, resolveIssueGitHubApiRepositorySource, type GitHubRepoExecOptions -} from '../../github-api-repository' +} from '../../repositories/github-api-repository' import { getRateLimit, noteRepositoryRateLimitSpend, repositoryRateLimitGuard, spendsSharedGitHubComQuota -} from '../../rate-limit' +} from '../../api/rate-limit' import { sameOwnerRepo } from './../github-exec-scope' import { buildWorkItemListRequest, resolvePrWorkItemSource } from './work-item-list-request' import { buildSearchQueryString, defaultOpenWorkItemQuery } from './work-item-search-query' diff --git a/src/main/github/client/list/list-work-items-source-guard.test.ts b/src/main/github/client/list/list-work-items-source-guard.test.ts new file mode 100644 index 00000000000..6b90e956408 --- /dev/null +++ b/src/main/github/client/list/list-work-items-source-guard.test.ts @@ -0,0 +1,211 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +// Keep legacy REST request/failure coverage; API-boundary suites exercise the GraphQL path. +vi.mock('./work-item-search-page', () => ({ usesGraphqlWorkItemSearch: () => false })) + +const { + execFileAsyncMock, + ghExecFileAsyncMock, + getOwnerRepoMock, + getIssueOwnerRepoMock, + getOwnerRepoForRemoteMock, + resolveIssueSourceMock, + gitExecFileAsyncMock, + rateLimitGuardMock, + noteRateLimitSpendMock, + acquireMock, + releaseMock +} = vi.hoisted(() => ({ + execFileAsyncMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + getIssueOwnerRepoMock: vi.fn(), + getOwnerRepoForRemoteMock: vi.fn(), + resolveIssueSourceMock: vi.fn(), + gitExecFileAsyncMock: vi.fn(), + rateLimitGuardMock: vi.fn((_bucket?: unknown) => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), + acquireMock: vi.fn(), + releaseMock: vi.fn() +})) + +vi.mock('../../execution/github-legacy-command', () => ({ + execFileAsync: execFileAsyncMock +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + githubRepoContext: ( + repoPath: string, + connectionId?: string | null, + localGitOptions: { wslDistro?: string } = {} + ) => ({ + repoPath, + connectionId: connectionId ?? null, + ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) + }), + ghRepoExecOptions: (context: { + repoPath: string + connectionId?: string | null + wslDistro?: string + }) => + context.connectionId + ? {} + : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }, + getOwnerRepoForRemote: getOwnerRepoForRemoteMock, + _resetOwnerRepoCache: vi.fn() +})) + +vi.mock('../../repositories/github-owner-repo-selection', () => ({ + getOwnerRepo: getOwnerRepoMock, + resolveIssueSource: resolveIssueSourceMock +})) + +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: acquireMock, + release: releaseMock +})) + +vi.mock('../../api/gh-error-classification', () => ({ + classifyGhError: (stderr: string) => ({ type: 'unknown', message: stderr }), + classifyListIssuesError: (stderr: string) => ({ type: 'unknown', message: stderr }), + classifyListPrsError: (stderr: string) => ({ type: 'unknown', message: stderr }) +})) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: gitExecFileAsyncMock +})) + +vi.mock('../../api/rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock, + getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), + repositoryRateLimitGuard: vi.fn((_repo: unknown, bucket: string) => rateLimitGuardMock(bucket)), + noteRepositoryRateLimitSpend: vi.fn((_repo: unknown, bucket: string, cost?: number) => + noteRateLimitSpendMock(bucket, cost) + ), + spendsSharedGitHubComQuota: () => true +})) + +vi.mock('../../repositories/github-api-repository', async (importOriginal) => { + return { + ...(await importOriginal()), + resolveIssueGitHubApiRepositorySource: ( + repoPath: string, + preference: unknown, + connectionId?: string | null, + localGitOptions?: unknown + ) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions), + getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) => + getIssueOwnerRepoMock(repoPath, connectionId) + } +}) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => { + return { + ...(await importOriginal()), + getOriginGitHubApiRepository: ( + repoPath: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => getOwnerRepoMock(repoPath, connectionId, localGitOptions), + getGitHubApiRepositoryForRemote: ( + repoPath: string, + remoteName: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => + remoteName === 'origin' + ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) + : getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions) + } +}) +import { listWorkItems } from './list-work-items' +import { _resetMergeQueueCacheForTests } from '../detect/repository-merge-metadata-cache' +import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity' +import { _resetRemoteNameListingCache } from '../../../git/remotes/remote-name-listing' + +import { _resetOriginGitHubApiRepositoryCache } from '../../repositories/github-api-repository-remote-probe' + +beforeEach(() => { + _resetOriginGitHubApiRepositoryCache() +}) + +describe('listWorkItems', () => { + beforeEach(() => { + execFileAsyncMock.mockReset() + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getIssueOwnerRepoMock.mockReset() + getOwnerRepoForRemoteMock.mockReset() + resolveIssueSourceMock.mockReset() + gitExecFileAsyncMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + // Preserve one source lookup through the preference-aware resolver. + resolveIssueSourceMock.mockImplementation(async () => ({ + source: await getIssueOwnerRepoMock(), + fellBack: false + })) + // Bridge explicit origin to getOwnerRepoMock; upstream candidates require opt-in fixtures. + getOwnerRepoForRemoteMock.mockImplementation( + async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => + remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null + ) + _resetOwnerRepoCache() + _resetRemoteNameListingCache() + _resetMergeQueueCacheForTests() + }) + + it('does not run unscoped work-item queries when a local repository has no GitHub source', async () => { + getIssueOwnerRepoMock.mockResolvedValue(null) + getOwnerRepoMock.mockResolvedValue(null) + + // Null-source envelopes distinguish unavailable repository identity from successful empty work. + await expect(listWorkItems('/private-repo', 36)).resolves.toMatchObject({ + items: [], + sources: { issues: null, prs: null } + }) + await expect(listWorkItems('/private-repo', 36, 'is:open')).resolves.toMatchObject({ + items: [], + sources: { issues: null, prs: null } + }) + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('rejects unresolved SSH repositories without running unscoped GitHub work-item queries', async () => { + getIssueOwnerRepoMock.mockResolvedValue(null) + getOwnerRepoMock.mockResolvedValue(null) + getOwnerRepoForRemoteMock.mockResolvedValue(null) + + await expect( + listWorkItems('/remote/repo', 10, undefined, undefined, undefined, 'ssh-1') + ).rejects.toThrow('GitHub work items require a GitHub remote for SSH repositories') + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + + ghExecFileAsyncMock.mockClear() + getIssueOwnerRepoMock.mockResolvedValue(null) + getOwnerRepoMock.mockResolvedValue(null) + getOwnerRepoForRemoteMock.mockResolvedValue(null) + + await expect( + listWorkItems('/remote/repo', 10, 'is:open', undefined, undefined, 'ssh-1') + ).rejects.toThrow('GitHub work items require a GitHub remote for SSH repositories') + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/github/client/list/list-work-items.ts b/src/main/github/client/list/list-work-items.ts index 61930f2ce4e..dc1ec451630 100644 --- a/src/main/github/client/list/list-work-items.ts +++ b/src/main/github/client/list/list-work-items.ts @@ -1,10 +1,14 @@ -import { withGitHubRepoExecution } from '../../github-repository-identity' -import type { ListWorkItemsResult } from '../../../../shared/github/work-item-types' +import { + withGitHubRepoExecution, + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' +import type { ListWorkItemsResult } from '../../../../shared/github/work-items/work-item-types' import type { IssueSourcePreference } from '../../../../shared/repo-types' -import { isGitHubWorkItemsQueryTooLarge } from '../../../../shared/github/work-items-query-bounds' +import { isGitHubWorkItemsQueryTooLarge } from '../../../../shared/github/work-items/work-items-query-bounds' import { parseTaskQuery } from '../../../../shared/work-items/task-query' -import { acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveIssueGitHubApiRepositorySource } from '../../github-api-repository' +import { acquire, release } from '../../execution/github-operation-slots' + +import { resolveIssueGitHubApiRepositorySource } from '../../repositories/github-api-repository' import type { MainWorkItem } from './../map/work-item-field-coercion' import { normalizeWorkItemPage, resolvePrWorkItemSource } from './work-item-list-request' import { listRecentWorkItems, listQueriedWorkItems } from './work-item-pages' diff --git a/src/main/github/client/list/work-item-issue-page.ts b/src/main/github/client/list/work-item-issue-page.ts index 2d66ecb9319..e90dd53e880 100644 --- a/src/main/github/client/list/work-item-issue-page.ts +++ b/src/main/github/client/list/work-item-issue-page.ts @@ -1,8 +1,10 @@ import { z } from 'zod' import type { ParsedTaskQuery } from '../../../../shared/work-items/task-query' -import { ghExecFileAsync, type LocalGitExecOptions, type OwnerRepo } from '../../gh-utils' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' -import type { GitHubRepoExecOptions } from '../../github-api-repository' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' import { fetchIssueWorkItem } from '../fetch/work-item-fetch' import { mapIssueWorkItem } from '../map/work-item' import { restIssueActor } from '../map/issue-actor' diff --git a/src/main/github/client/list/work-item-list-request.ts b/src/main/github/client/list/work-item-list-request.ts index d8ebe0592b1..51a90d79c66 100644 --- a/src/main/github/client/list/work-item-list-request.ts +++ b/src/main/github/client/list/work-item-list-request.ts @@ -1,13 +1,14 @@ import type { ClassifiedError } from '../../../../shared/classified-error' import type { IssueSourcePreference } from '../../../../shared/repo-types' import type { ParsedTaskQuery } from '../../../../shared/work-items/task-query' -import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/github/work-item-ssh-error' +import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/github/work-items/work-item-ssh-error' import { shouldProbeGitRemote } from '../../../git/remotes/remote-name-listing' -import type { LocalGitExecOptions, OwnerRepo } from '../../gh-utils' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' import { getGitHubApiRepositoryForRemote, getOriginGitHubApiRepository -} from '../../github-api-repository' +} from '../../repositories/github-api-repository-remote-probe' import { WORK_ITEM_PR_LIST_JSON_FIELDS, type MainWorkItem } from './../map/work-item-field-coercion' import { WORK_ITEM_NUMBER_SORT_QUALIFIER, quoteGitHubSearchValue } from './work-item-search-query' export type WorkItemListRequest = { diff --git a/src/main/github/client/list/work-item-pages.ts b/src/main/github/client/list/work-item-pages.ts index 4e85ab8195e..05a78d2c8bd 100644 --- a/src/main/github/client/list/work-item-pages.ts +++ b/src/main/github/client/list/work-item-pages.ts @@ -1,16 +1,15 @@ import type { ClassifiedError } from '../../../../shared/classified-error' -import { classifyGitHubUnavailable } from '../../../../shared/github/api-availability' +import { classifyGitHubUnavailable } from '../../../../shared/github/api/api-availability' import { parseTaskQuery, type ParsedTaskQuery } from '../../../../shared/work-items/task-query' import { sortWorkItemsByNumber } from '../../../../shared/work-items/work-item-order' +import { classifyListIssuesError, classifyListPrsError } from '../../api/gh-error-classification' import { - classifyListIssuesError, - classifyListPrsError, ghRepoExecOptions, githubRepoContext, - type LocalGitExecOptions, - type OwnerRepo -} from '../../gh-utils' -import { githubHostExecOptions } from '../../github-api-repository' + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { githubHostExecOptions } from '../../repositories/github-repository-host' import { githubPRStackExecutionScope } from './../github-exec-scope' import { hydrateWorkItemRepositoryMergeMetadata } from './../detect/hydrate-work-item-merge-metadata' import type { MainWorkItem } from './../map/work-item-field-coercion' diff --git a/src/main/github/client/list/work-item-pr-page.ts b/src/main/github/client/list/work-item-pr-page.ts index dc63d8b50aa..5bc80c7a9bb 100644 --- a/src/main/github/client/list/work-item-pr-page.ts +++ b/src/main/github/client/list/work-item-pr-page.ts @@ -1,7 +1,8 @@ import { z } from 'zod' import type { ParsedTaskQuery } from '../../../../shared/work-items/task-query' -import { ghExecFileAsync, type OwnerRepo } from '../../gh-utils' -import type { GitHubRepoExecOptions } from '../../github-api-repository' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' import { mapPullRequestWorkItem } from '../map/work-item' import type { MainWorkItem } from '../map/work-item-field-coercion' import { buildWorkItemListRequest } from './work-item-list-request' diff --git a/src/main/github/client/list/work-item-search-batch.ts b/src/main/github/client/list/work-item-search-batch.ts index d3730c27ceb..a92ba728328 100644 --- a/src/main/github/client/list/work-item-search-batch.ts +++ b/src/main/github/client/list/work-item-search-batch.ts @@ -1,12 +1,13 @@ import { z } from 'zod' -import { githubReadExecutionScope as workItemSearchScope } from '../../github-read-execution-scope' -export { githubReadExecutionScope as workItemSearchScope } from '../../github-read-execution-scope' +import { codeHostReadExecutionScope as workItemSearchScope } from '../../../source-control/code-host-read-execution-scope' + import { BoundedMap } from '../../../../shared/bounded-map' import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' import { createGhRateLimitBlockedError } from '../../../git/command-runner/hosted-cli/gh-rate-limit-breaker' -import { extractExecError, ghExecFileAsync } from '../../gh-utils' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' -import type { GitHubRepoExecOptions } from '../../github-api-repository' +import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' const envelopeSchema = z.object({ data: z.record(z.string(), z.unknown()).nullish(), diff --git a/src/main/github/client/list/work-item-search-fallback-environment.test.ts b/src/main/github/client/list/work-item-search-fallback-environment.test.ts new file mode 100644 index 00000000000..7514420d8b7 --- /dev/null +++ b/src/main/github/client/list/work-item-search-fallback-environment.test.ts @@ -0,0 +1,27 @@ +import { expect, it, vi } from 'vitest' +import { api, capture } from '../../work-items/work-item-search-test-harness' +import { listWorkItems } from './list-work-items' +import './count-work-items' +import metadata from '../../__fixtures__/work-item-search-metadata.json' + +it('hydrates oversized associations with the preferred page credential', async () => { + vi.stubEnv('GH_TOKEN', 'fixture-original-credential') + const row = structuredClone(metadata[0].graphql) + api.specialNodes = [{ ...row, labels: { ...row.labels, pageInfo: { hasNextPage: true } } }] + capture.mockImplementation(async (binary, args, options) => { + if (args.includes('graphql')) { + vi.stubEnv('GH_TOKEN', 'fixture-later-credential') + } + return api.capture(binary, args, options) + }) + const result = await listWorkItems('fixture/repo', 24, 'is:issue') + expect(result.items[0].labels).toHaveLength(125) + const queries = api.calls.filter( + (call) => + call.args.includes('graphql') || call.args.some((arg) => /^repos\/.+\/issues\/\d+$/.test(arg)) + ) + expect(queries.map((call) => call.fixtureCredential)).toEqual([ + 'fixture-original-credential', + 'fixture-original-credential' + ]) +}) diff --git a/src/main/github/client/list/work-item-search-isolation.test.ts b/src/main/github/client/list/work-item-search-isolation.test.ts new file mode 100644 index 00000000000..25929ff66e9 --- /dev/null +++ b/src/main/github/client/list/work-item-search-isolation.test.ts @@ -0,0 +1,17 @@ +import { expect, it } from 'vitest' +import { api } from '../../work-items/work-item-search-test-harness' +import { listWorkItems } from './list-work-items' +import { countWorkItems } from './count-work-items' +import './work-item-search-page' +import '../../../git/command-runner/hosted-cli/gh-rate-limit-breaker' + +it('keeps count/list search usable when REST Search is exhausted and reports both-bucket failures', async () => { + api.searchAvailable = false + expect(await countWorkItems('fixture/repo', 'is:issue')).toBe(120) + expect((await listWorkItems('fixture/repo', 24, 'is:issue')).items).toHaveLength(24) + expect(api.restSearches).toBe(0) + api.graphqlAvailable = false + await expect( + listWorkItems('fixture/repo', 24, 'is:issue', 1, undefined, undefined, true) + ).rejects.toThrow(/rate limit exceeded/) +}) diff --git a/src/main/github/client/list/work-item-search-page.ts b/src/main/github/client/list/work-item-search-page.ts index b22fb90c3d5..65fb8175e8d 100644 --- a/src/main/github/client/list/work-item-search-page.ts +++ b/src/main/github/client/list/work-item-search-page.ts @@ -1,13 +1,13 @@ import { BoundedMap } from '../../../../shared/bounded-map' -import { isDefaultGitHubHost } from '../../../../shared/github/repository-identity-key' -import type { OwnerRepo } from '../../gh-utils' -import type { GitHubRepoExecOptions } from '../../github-api-repository' +import { isDefaultGitHubHost } from '../../../../shared/github/repositories/repository-identity-key' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' import { requestWorkItemSearch, - workItemSearchScope, WORK_ITEM_SEARCH_CACHE_MS, type WorkItemSearchType } from './work-item-search-batch' +import { codeHostReadExecutionScope as workItemSearchScope } from '../../../source-control/code-host-read-execution-scope' type PageInfo = { endCursor: string | null; hasNextPage: boolean } export type SearchConnection = { issueCount: number; pageInfo: PageInfo; nodes: T[] } diff --git a/src/main/github/client/lookup/branch-lookup-derived-data.ts b/src/main/github/client/lookup/branch-lookup-derived-data.ts index 295b55ef630..db38754a3f4 100644 --- a/src/main/github/client/lookup/branch-lookup-derived-data.ts +++ b/src/main/github/client/lookup/branch-lookup-derived-data.ts @@ -1,6 +1,7 @@ -import { getPRConflictSummary } from '../../conflict-summary' -import type { ghRepoExecOptions, OwnerRepo } from '../../gh-utils' -import { hydrateGitHubPRStack } from '../../github-pr-stack' +import { getPRConflictSummary } from '../../pull-requests/conflicts/conflict-summary' +import type { ghRepoExecOptions } from '../../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { hydrateGitHubPRStack } from '../../pull-requests/stacks/github-pr-stack' import { detectRepositoryMergeMetadata } from './../detect/repository-merge-metadata' import { derivePullRequestMergeable, type PullRequestLookupData } from './pull-request-lookup-data' import { getCachedGitHubPRStackSummary } from './pr-stack-summary-cache' @@ -14,6 +15,7 @@ export async function derivePRRefreshData(args: { ghOptions: ReturnType executionScope: string usedExactNumberLookup: boolean + includeDerivedData?: boolean }): Promise<{ mergeable: ReturnType stack: PullRequestLookupData['stack'] @@ -22,6 +24,15 @@ export async function derivePRRefreshData(args: { }> { const { data, dataRepo, repoPath, connectionId, localGitOptions, ghOptions, executionScope } = args + const mergeable = derivePullRequestMergeable(data) + if (args.includeDerivedData === false) { + return { + mergeable, + stack: undefined, + stackMergeQueueRequired: undefined, + conflictSummary: undefined + } + } if (!data.stackMetadataChecked && dataRepo && args.usedExactNumberLookup) { try { data.stack = await getCachedGitHubPRStackSummary( @@ -35,7 +46,6 @@ export async function derivePRRefreshData(args: { // Stack metadata is additive; exact PR lookup remains usable without it. } } - const mergeable = derivePullRequestMergeable(data) const stack = data.stack && dataRepo ? await hydrateGitHubPRStack( diff --git a/src/main/github/client/lookup/branch-lookup-resolution.ts b/src/main/github/client/lookup/branch-lookup-resolution.ts index de51fcf630a..6483362fb30 100644 --- a/src/main/github/client/lookup/branch-lookup-resolution.ts +++ b/src/main/github/client/lookup/branch-lookup-resolution.ts @@ -1,17 +1,17 @@ -import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' -import type { ghRepoExecOptions, OwnerRepo } from '../../gh-utils' -import { - isCommitPartOfMergedPR, - type MergedPRCommitMembership -} from '../../merged-pr-commit-membership' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { ghRepoExecOptions } from '../../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { mergedPRHeadMembership } from '../../pull-requests/refresh/merged-pr-head-membership' +import type { MergedReviewCommitMembership as MergedPRCommitMembership } from '../../../source-control/merged-review-membership-memo' import { shouldHideNonOpenReviewOnDefaultBranch } from '../../../source-control/repo-default-branch' -import { - getGitHubApiRepositoryForRemote, - resolveGitHubApiRepositoryCandidates -} from '../../github-api-repository' +import { getGitHubApiRepositoryForRemote } from '../../repositories/github-api-repository-remote-probe' +import { resolveGitHubApiRepositoryCandidates } from '../../repositories/github-api-repository' import { exactRepositoryCandidates } from '../pull-request-lookup-candidates' -import { mapPRState } from '../../mappers' -import { ownerRepoFromPullRequestUrl } from './../github-exec-scope' +import { mapPRState } from '../../api/github-read-response' +import { + ownerRepoFromPullRequestUrl, + type HostedReviewLocalGitOptions +} from './../github-exec-scope' import { prRefreshUpstreamError } from './../gh-error-predicates' import { isMergedImplicitPR, @@ -32,7 +32,7 @@ import { createImplicitDefaultBranchPRPolicy, type ImplicitDefaultBranchPRContext } from './implicit-default-branch-pr' -import type { HostedReviewLocalGitOptions } from './../github-exec-scope' + export async function resolvePRForBranchOutcome(input: { repoPath: string branchName: string @@ -99,11 +99,16 @@ export async function resolvePRForBranchOutcome(input: { if (!candidateRepo || !headOid) { return 'unknown' } - const membership = await isCommitPartOfMergedPR({ + const membership = await mergedPRHeadMembership({ ownerRepo: candidateRepo, prNumber: candidate.number, - commitOid: headOid, - ghOptions + prHeadOid: candidate.headRefOid, + baseRefName: candidate.baseRefName, + headOid, + ghOptions, + repoPath, + connectionId, + localGitOptions }) if (membership === 'contained') { confirmedContainedHeadOid = headOid @@ -289,7 +294,8 @@ export async function resolvePRForBranchOutcome(input: { localGitOptions, ghOptions, executionScope, - usedExactNumberLookup + usedExactNumberLookup, + includeDerivedData: options.includeDerivedData }) return assemblePRRefreshFoundOutcome({ diff --git a/src/main/github/client/lookup/get-pr-for-branch-host-scope.test.ts b/src/main/github/client/lookup/get-pr-for-branch-host-scope.test.ts new file mode 100644 index 00000000000..b35dd255cf2 --- /dev/null +++ b/src/main/github/client/lookup/get-pr-for-branch-host-scope.test.ts @@ -0,0 +1,215 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file' + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' + +const { clientMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('../client-test-mocks') + return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } +}) + +vi.mock('../../execution/github-legacy-command', () => + moduleMocks.githubLegacyCommandModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-owner-repo-selection', () => + moduleMocks.githubOwnerSelectionModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks) +})) + +vi.mock('../../api/gh-error-classification', () => + moduleMocks.githubErrorClassificationModuleMock() +) + +vi.mock('../../execution/github-operation-slots', () => + moduleMocks.githubOperationSlotsModuleMock(clientMocks) +) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: clientMocks.gitExecFileAsyncMock +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubHostedCliModuleMock(clientMocks) +})) +vi.mock('../../repositories/local-git-config-signature', () => + moduleMocks.localGitConfigSignatureModuleMock(clientMocks) +) +vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => + moduleMocks.githubEnterpriseRepositoryModuleMock( + await importOriginal() + ) +) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) +vi.mock('../../repositories/github-api-repository', async (importOriginal) => + moduleMocks.githubApiRepositoryModuleMock( + clientMocks, + await importOriginal() + ) +) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => + moduleMocks.githubApiRepositoryRemoteProbeModuleMock( + clientMocks, + await importOriginal() + ) +) + +import { getPRForBranch } from './get-pr-for-branch' +import { resetPRForBranchMocks } from '../client-test-harness' +import type { RestPullRequest } from './pull-request-lookup-data' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' + +const { + ghExecFileAsyncMock, + getOwnerRepoMock, + resolvePRRepositoryCandidatesMock, + gitExecFileAsyncMock +} = clientMocks + +const ACME = { owner: 'acme', repo: 'widgets' } + +function primeGit( + trackedUpstream: string, + remoteHeads: Record = { origin: 'develop' } +): void { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'for-each-ref' && args.includes('--format=%(refname)%00%(upstream)')) { + return { stdout: `refs/heads/feature/my-change\0${trackedUpstream}\n`, stderr: '' } + } + if (args[0] === 'for-each-ref' && args.includes('--format=%(refname)%00%(symref)')) { + const stdout = Object.entries(remoteHeads) + .filter(([remote]) => args.includes(`refs/remotes/${remote}/HEA[D]`)) + .map( + ([remote, branch]) => `refs/remotes/${remote}/HEAD\0refs/remotes/${remote}/${branch}\n` + ) + .join('') + return { stdout, stderr: '' } + } + if (args[0] === 'rev-parse' && args[1] === 'HEAD') { + return { stdout: 'feature-head-oid\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) +} + +function restPR( + headRefName = 'develop', + headRepo: OwnerRepo = ACME, + prRepo: OwnerRepo = ACME +): RestPullRequest { + return { + number: 7, + title: 'Release develop', + state: 'closed', + merged_at: null, + html_url: `https://${prRepo.host ?? 'github.com'}/${prRepo.owner}/${prRepo.repo}/pull/7`, + updated_at: '2025-01-01T00:00:00Z', + draft: false, + mergeable: null, + base: { ref: 'release', sha: 'release-oid' }, + head: { + ref: headRefName, + sha: 'old-develop-oid', + repo: { name: headRepo.repo, owner: { login: headRepo.owner } } + } + } +} + +function primeGh( + listsByHead: Record, + exactPR: RestPullRequest | RestPullRequest[] = Object.values(listsByHead).flat()[0] ?? restPR() +): void { + const repositorySlug = (pr: RestPullRequest): string => + new URL(pr.html_url ?? '').pathname.split('/').slice(1, 3).join('/') + const repositoryHost = (pr: RestPullRequest): string => new URL(pr.html_url ?? '').host + const exactPRs = Array.isArray(exactPR) ? exactPR : [exactPR] + const prsByRepositoryAndNumber = new Map( + [...Object.values(listsByHead).flat(), ...exactPRs].map((pr) => [ + `${repositoryHost(pr)}/${repositorySlug(pr)}#${pr.number}`, + pr + ]) + ) + ghExecFileAsyncMock.mockImplementation( + async (args: string[], options: { host?: string } = {}) => { + const host = options.host ?? 'github.com' + const match = args[1]?.match(/^repos\/([^/]+\/[^/]+)\/pulls\?head=([^&]+)/) + if (args[0] === 'api' && match) { + const list = (listsByHead[decodeURIComponent(match[2])] ?? []).filter( + (pr) => repositoryHost(pr) === host && repositorySlug(pr) === match[1] + ) + return { stdout: JSON.stringify(list) } + } + const exactRestMatch = args[1]?.match(/^repos\/([^/]+\/[^/]+)\/pulls\/(\d+)$/) + if (args[0] === 'api' && exactRestMatch) { + const pr = prsByRepositoryAndNumber.get(`${host}/${exactRestMatch[1]}#${exactRestMatch[2]}`) + if (pr) { + return { stdout: JSON.stringify(pr) } + } + throw new Error('HTTP 404 Not Found') + } + const repoIndex = args.indexOf('--repo') + const exact = prsByRepositoryAndNumber.get(`${host}/${args[repoIndex + 1]}#${args[2]}`) + if (args[0] === 'pr' && args[1] === 'view') { + if (!exact) { + throw new Error('HTTP 404 Not Found') + } + return { + stdout: JSON.stringify({ + number: exact.number, + title: exact.title, + state: exact.merged_at ? 'MERGED' : exact.state.toUpperCase(), + url: exact.html_url, + statusCheckRollup: [], + updatedAt: exact.updated_at, + isDraft: exact.draft, + mergeable: 'UNKNOWN', + baseRefName: exact.base?.ref, + headRefName: exact.head?.ref, + baseRefOid: exact.base?.sha, + headRefOid: exact.head?.sha, + headRepositoryOwner: exact.head?.repo?.owner, + headRepository: exact.head?.repo ? { name: exact.head.repo.name } : null + }) + } + } + throw new Error(`gh unavailable: ${args.join(' ')}`) + } + ) +} + +describe('issue #26948: a branch tracking the default branch', () => { + beforeEach(() => { + resetPRForBranchMocks(clientMocks) + getOwnerRepoMock.mockResolvedValue(ACME) + }) + + it('does not query another GitHub server for a known public GitHub head', async () => { + const enterprise = { ...ACME, host: 'ghe.example' } + resolvePRRepositoryCandidatesMock.mockResolvedValue({ + candidates: [enterprise, ACME], + headRepo: ACME + }) + primeGit('') + primeGh({ + 'acme:feature/my-change': [ + { ...restPR('feature/my-change', enterprise, enterprise), state: 'open' } + ] + }) + expect(await getPRForBranch('/repo-root', 'feature/my-change')).toBeNull() + expect( + ghExecFileAsyncMock.mock.calls.some(([, options]) => options?.host === 'ghe.example') + ).toBe(false) + }) +}) diff --git a/src/main/github/client/lookup/get-pr-for-branch-upstream-owner.test.ts b/src/main/github/client/lookup/get-pr-for-branch-upstream-owner.test.ts new file mode 100644 index 00000000000..2abf0e4c200 --- /dev/null +++ b/src/main/github/client/lookup/get-pr-for-branch-upstream-owner.test.ts @@ -0,0 +1,221 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file' + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' + +const { clientMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('../client-test-mocks') + return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } +}) + +vi.mock('../../execution/github-legacy-command', () => + moduleMocks.githubLegacyCommandModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-owner-repo-selection', () => + moduleMocks.githubOwnerSelectionModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks) +})) + +vi.mock('../../api/gh-error-classification', () => + moduleMocks.githubErrorClassificationModuleMock() +) + +vi.mock('../../execution/github-operation-slots', () => + moduleMocks.githubOperationSlotsModuleMock(clientMocks) +) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: clientMocks.gitExecFileAsyncMock +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubHostedCliModuleMock(clientMocks) +})) +vi.mock('../../repositories/local-git-config-signature', () => + moduleMocks.localGitConfigSignatureModuleMock(clientMocks) +) +vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => + moduleMocks.githubEnterpriseRepositoryModuleMock( + await importOriginal() + ) +) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) +vi.mock('../../repositories/github-api-repository', async (importOriginal) => + moduleMocks.githubApiRepositoryModuleMock( + clientMocks, + await importOriginal() + ) +) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => + moduleMocks.githubApiRepositoryRemoteProbeModuleMock( + clientMocks, + await importOriginal() + ) +) + +import { getPRForBranch } from './get-pr-for-branch' +import { resetPRForBranchMocks } from '../client-test-harness' + +const { + ghExecFileAsyncMock, + getOwnerRepoForRemoteMock, + resolvePRRepositoryCandidatesMock, + gitExecFileAsyncMock +} = clientMocks + +describe('getPRForBranch', () => { + beforeEach(() => { + resetPRForBranchMocks(clientMocks) + }) + + it('uses the tracked upstream remote owner for fork branch lookup', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ + candidates: [ + { owner: 'stablyai', repo: 'orca' }, + { owner: 'origin-owner', repo: 'orca' } + ], + headRepo: { owner: 'origin-owner', repo: 'orca' } + }) + getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'fork-owner', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) + .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 78, + title: 'Fork upstream branch PR', + state: 'open', + html_url: 'https://github.com/stablyai/orca/pull/78', + updated_at: '2026-03-28T00:00:00Z', + draft: false, + mergeable: true, + base: { ref: 'main', sha: 'base-oid' }, + head: { ref: 'contributor/original', sha: 'upstream-head-oid' } + } + ]) + }) + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 78, + title: 'Hydrated fork upstream branch PR', + state: 'OPEN', + url: 'https://github.com/stablyai/orca/pull/78', + statusCheckRollup: [], + updatedAt: '2026-03-28T00:00:00Z', + isDraft: false, + mergeable: 'MERGEABLE', + baseRefName: 'main', + headRefName: 'contributor/original', + baseRefOid: 'base-oid', + headRefOid: 'upstream-head-oid' + }) + }) + gitExecFileAsyncMock.mockResolvedValueOnce({ + stdout: 'local-created-from-pr\0fork/contributor/original\n', + stderr: '' + }) + + const pr = await getPRForBranch('/repo-root', 'local-created-from-pr') + + expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/repo-root', 'fork', undefined) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 3, + [ + 'api', + 'repos/stablyai/orca/pulls?head=fork-owner%3Acontributor%2Foriginal&state=all&per_page=10', + '--include' + ], + { cwd: '/repo-root' } + ) + expect(pr).toMatchObject({ + number: 78, + title: 'Hydrated fork upstream branch PR', + prRepo: { owner: 'stablyai', repo: 'orca' }, + headRepo: { owner: 'fork-owner', repo: 'orca' } + }) + }) + + it('uses the tracked upstream remote owner when the fork branch name matches locally', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ + candidates: [ + { owner: 'stablyai', repo: 'orca' }, + { owner: 'origin-owner', repo: 'orca' } + ], + headRepo: { owner: 'origin-owner', repo: 'orca' } + }) + getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'brennanb2025', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) + .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 6433, + title: 'Recover Windows worktree deletes from long paths', + state: 'open', + html_url: 'https://github.com/stablyai/orca/pull/6433', + updated_at: '2026-06-26T00:00:00Z', + draft: false, + mergeable: true, + base: { ref: 'main', sha: 'base-oid' }, + head: { + ref: 'brennanb2025/worktree-remove-fix', + sha: 'same-name-fork-head-oid' + } + } + ]) + }) + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 6433, + title: 'Recover Windows worktree deletes from long paths', + state: 'OPEN', + url: 'https://github.com/stablyai/orca/pull/6433', + statusCheckRollup: [], + updatedAt: '2026-06-26T00:00:00Z', + isDraft: false, + mergeable: 'MERGEABLE', + baseRefName: 'main', + headRefName: 'brennanb2025/worktree-remove-fix', + baseRefOid: 'base-oid', + headRefOid: 'same-name-fork-head-oid' + }) + }) + gitExecFileAsyncMock.mockResolvedValueOnce({ + stdout: 'brennanb2025/worktree-remove-fix\0brennan/brennanb2025/worktree-remove-fix\n', + stderr: '' + }) + + const pr = await getPRForBranch('/repo-root', 'brennanb2025/worktree-remove-fix') + + expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/repo-root', 'brennan', undefined) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 3, + [ + 'api', + 'repos/stablyai/orca/pulls?head=brennanb2025%3Abrennanb2025%2Fworktree-remove-fix&state=all&per_page=10', + '--include' + ], + { cwd: '/repo-root' } + ) + expect(pr).toMatchObject({ + number: 6433, + prRepo: { owner: 'stablyai', repo: 'orca' }, + headRepo: { owner: 'brennanb2025', repo: 'orca' } + }) + }) +}) diff --git a/src/main/github/client/lookup/get-pr-for-branch.ts b/src/main/github/client/lookup/get-pr-for-branch.ts index 0d4a98197b8..1f29685be64 100644 --- a/src/main/github/client/lookup/get-pr-for-branch.ts +++ b/src/main/github/client/lookup/get-pr-for-branch.ts @@ -1,4 +1,4 @@ -import type { PRInfo } from '../../../../shared/github/pull-request-types' +import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types' import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' import { getPRForBranchOutcome } from './pr-for-branch-outcome' /** Linked PR numbers are authoritative; fallback numbers apply only after branch lookup misses. */ diff --git a/src/main/github/client/lookup/implicit-default-branch-pr.ts b/src/main/github/client/lookup/implicit-default-branch-pr.ts index dbe3ace70c3..210df496dfa 100644 --- a/src/main/github/client/lookup/implicit-default-branch-pr.ts +++ b/src/main/github/client/lookup/implicit-default-branch-pr.ts @@ -1,11 +1,15 @@ -import type { OwnerRepo } from '../../gh-utils' -import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' import { getRemoteHeadBranchName, getRepoDefaultBranchName } from '../../../source-control/repo-default-branch' -import type { GhExecOptions, HostedReviewLocalGitOptions } from './../github-exec-scope' -import { ownerRepoFromPullRequestUrl } from './../github-exec-scope' +import { + type GhExecOptions, + type HostedReviewLocalGitOptions, + ownerRepoFromPullRequestUrl +} from './../github-exec-scope' + import type { TrackedUpstreamBranch } from './tracked-upstream-cache' import { pullRequestHeadRepository, diff --git a/src/main/github/client/lookup/pr-branch-lookup-revalidation.test.ts b/src/main/github/client/lookup/pr-branch-lookup-revalidation.test.ts new file mode 100644 index 00000000000..7e241c67528 --- /dev/null +++ b/src/main/github/client/lookup/pr-branch-lookup-revalidation.test.ts @@ -0,0 +1,108 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file' + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' + +const { clientMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('../client-test-mocks') + return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } +}) + +vi.mock('../../execution/github-legacy-command', () => + moduleMocks.githubLegacyCommandModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-owner-repo-selection', () => + moduleMocks.githubOwnerSelectionModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks) +})) + +vi.mock('../../api/gh-error-classification', () => + moduleMocks.githubErrorClassificationModuleMock() +) + +vi.mock('../../execution/github-operation-slots', () => + moduleMocks.githubOperationSlotsModuleMock(clientMocks) +) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: clientMocks.gitExecFileAsyncMock +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubHostedCliModuleMock(clientMocks) +})) +vi.mock('../../repositories/local-git-config-signature', () => + moduleMocks.localGitConfigSignatureModuleMock(clientMocks) +) +vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => + moduleMocks.githubEnterpriseRepositoryModuleMock( + await importOriginal() + ) +) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) +vi.mock('../../repositories/github-api-repository', async (importOriginal) => + moduleMocks.githubApiRepositoryModuleMock( + clientMocks, + await importOriginal() + ) +) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => + moduleMocks.githubApiRepositoryRemoteProbeModuleMock( + clientMocks, + await importOriginal() + ) +) + +import { getRestPRForBranch } from './pr-branch-lookup' + +import { resetPRForBranchMocks } from '../client-test-harness' + +const { ghExecFileAsyncMock } = clientMocks + +describe('PR lookup conditional REST reads', () => { + beforeEach(() => resetPRForBranchMocks(clientMocks)) + + it('revalidates both mixed and active discovery responses before falling back to history', async () => { + const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' } + const old = Array.from({ length: 10 }, (_, i) => ({ + number: i + 1, + state: 'closed', + title: 'Old', + head: { ref: 'feature' } + })) + const open = { number: 11, state: 'open', title: 'Active', head: { ref: 'feature' } } + const http = (data: unknown, etag: string) => ({ + stdout: `HTTP/2.0 200 OK\nEtag: "${etag}"\r\n\r\n${JSON.stringify(data)}` + }) + ghExecFileAsyncMock + .mockResolvedValueOnce(http(old, 'recent')) + .mockResolvedValueOnce(http([open], 'active')) + .mockRejectedValueOnce( + Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) + ) + .mockRejectedValueOnce( + Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) + ) + await expect( + getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' }) + ).resolves.toMatchObject({ number: 11 }) + await expect( + getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' }) + ).resolves.toMatchObject({ number: 11 }) + expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain('If-None-Match: "recent"') + expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain('If-None-Match: "active"') + }) +}) diff --git a/src/main/github/client/lookup/pr-branch-lookup.ts b/src/main/github/client/lookup/pr-branch-lookup.ts index c77460698a7..dc432b33021 100644 --- a/src/main/github/client/lookup/pr-branch-lookup.ts +++ b/src/main/github/client/lookup/pr-branch-lookup.ts @@ -1,12 +1,16 @@ import { assertRateLimitBudget } from './pr-lookup-rate-limit' import { selectBranchReview } from '../../../source-control/branch-review-selection' -import { ghExecFileAsync } from '../../gh-utils' -import type { OwnerRepo, ghRepoExecOptions } from '../../gh-utils' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type { + GitHubRepositoryIdentity as OwnerRepo, + GitHubRepositoryIdentity as GitHubApiRepository +} from '../../../../shared/github/repositories/repository-identity' +import type { ghRepoExecOptions } from '../../repositories/github-repository-identity' import { githubHostExecOptions, - githubRepositoryWebHost, - type GitHubApiRepository -} from '../../github-api-repository' + githubRepositoryWebHost +} from '../../repositories/github-repository-host' + import type { GhExecOptions } from './../github-exec-scope' import { isNoPullRequestError } from './../gh-error-predicates' import { @@ -22,8 +26,8 @@ import { import { getPRByNumber } from './pr-number-lookup' import { hydratePullRequestLookupData } from './pull-request-lookup-hydration' import type { PRProviderReadOptions } from './shared-pr-provider-reads' -import { revalidateGitHubRestJson } from '../../github-rest-revalidation' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' +import { revalidateGitHubRestJson } from '../../api/github-rest-revalidation' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' import { ownerRepoFromPullRequestUrl } from '../github-exec-scope' const BRANCH_PR_LOOKUP_PAGE_SIZE = 10 diff --git a/src/main/github/client/lookup/pr-for-branch-outcome-coalescing.test.ts b/src/main/github/client/lookup/pr-for-branch-outcome-coalescing.test.ts new file mode 100644 index 00000000000..06e499b401e --- /dev/null +++ b/src/main/github/client/lookup/pr-for-branch-outcome-coalescing.test.ts @@ -0,0 +1,77 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { + GitHubRepoContext, + LocalGitExecOptions +} from '../../repositories/github-repository-identity' + +import { __resetHostedReviewBranchCacheForTests } from '../../../source-control/hosted-review-branch-cache' + +const mocks = vi.hoisted(() => ({ resolve: vi.fn(), acquire: vi.fn(), release: vi.fn() })) +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: mocks.acquire, + release: mocks.release +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + githubRepoContext: ( + repoPath: string, + connectionId: string | null, + options: LocalGitExecOptions + ) => ({ + repoPath, + connectionId, + ...options + }), + ghRepoExecOptions: (context: GitHubRepoContext) => context +})) +vi.mock('./branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: mocks.resolve +})) +vi.mock('./pr-for-branch-outcome', async () => ({ + getPRForBranchOutcome: (await import('./pr-for-branch-outcome')).getPRForBranchOutcome +})) + +vi.mock('../fetch/repo-slug-upstream', async () => ({ + getRepoSlug: vi.fn(async () => ({ owner: 'acme', repo: 'orca' })) +})) + +vi.mock('./pr-lookup-rate-limit', async () => ({ + getGitHubPRLookupRateLimitBlock: vi.fn(async () => null) +})) + +vi.mock('../create/create-github-pull-request', async () => ({ + createGitHubPullRequest: vi.fn() +})) +vi.mock('../../../gitlab/merge-requests/merge-request-lookup', () => ({ + getProjectSlug: vi.fn(async () => null) +})) +import { getPRForBranchOutcome } from './pr-for-branch-outcome' + +const outcome: PRRefreshOutcome = { kind: 'no-pr', fetchedAt: 1 } +beforeEach(() => { + vi.clearAllMocks() + mocks.resolve.mockReset() + __resetHostedReviewBranchCacheForTests() + mocks.acquire.mockResolvedValue(undefined) +}) +afterEach(() => { + vi.unstubAllEnvs() + vi.useRealTimers() +}) + +describe('PR lookup coalescing', () => { + it('cleans up errors so later reads can recover', async () => { + mocks.resolve.mockRejectedValueOnce(new Error('network down')).mockResolvedValue(outcome) + const results = await Promise.all([ + getPRForBranchOutcome('/repo', 'topic'), + getPRForBranchOutcome('/repo', 'topic') + ]) + expect(results.every((result) => result.kind === 'upstream-error')).toBe(true) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + await expect(getPRForBranchOutcome('/repo', 'topic')).resolves.toEqual(outcome) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/github/client/lookup/pr-for-branch-outcome.ts b/src/main/github/client/lookup/pr-for-branch-outcome.ts index 34bf63bc8ef..a1d4bc779a5 100644 --- a/src/main/github/client/lookup/pr-for-branch-outcome.ts +++ b/src/main/github/client/lookup/pr-for-branch-outcome.ts @@ -1,13 +1,18 @@ -import { withGitHubRepoExecution } from '../../github-repository-identity' +import { + withGitHubRepoExecution, + ghRepoExecOptions, + githubRepoContext +} from '../../repositories/github-repository-identity' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { hostedReviewRepoScope, scopeGeneration } from '../../../source-control/hosted-review-scope-generations' import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' -import { githubReadExecutionScope } from '../../github-read-execution-scope' -import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' -import { acquire, release, ghRepoExecOptions, githubRepoContext } from '../../gh-utils' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { acquire, release } from '../../execution/github-operation-slots' + import { hostedReviewLocalGitOptionArgs, githubPRStackExecutionScope } from './../github-exec-scope' import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' import { prRefreshUpstreamError } from './../gh-error-predicates' @@ -114,6 +119,7 @@ export async function getPRForBranchOutcome( options.currentHeadOid ?? null, options.checkPageLimit ?? null, options.exactRepository ?? null, + options.includeDerivedData !== false, scope.readScope ]) return runCoalescedProbe( @@ -140,7 +146,10 @@ export async function getPRForBranchOutcome( } finally { release() } - const narrowed = options.checkPageLimit !== undefined || options.exactRepository + const narrowed = + options.checkPageLimit !== undefined || + options.exactRepository || + options.includeDerivedData === false recordPRLastOutcome(lastOutcomeKey(repoPath, branchName, scope), { start, linkedPRNumber: linkedPRNumber ?? null, diff --git a/src/main/github/client/lookup/pr-last-outcome.ts b/src/main/github/client/lookup/pr-last-outcome.ts index f5c7cb383be..7d6dec32aac 100644 --- a/src/main/github/client/lookup/pr-last-outcome.ts +++ b/src/main/github/client/lookup/pr-last-outcome.ts @@ -1,4 +1,4 @@ -import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' // A phone's re-read right after the desktop's own lookup reuses it instead of asking GitHub again. const PHONE_REUSE_MAX_AGE_MS = 30_000 diff --git a/src/main/github/client/lookup/pr-lookup-rate-limit.test.ts b/src/main/github/client/lookup/pr-lookup-rate-limit.test.ts new file mode 100644 index 00000000000..c710f135f93 --- /dev/null +++ b/src/main/github/client/lookup/pr-lookup-rate-limit.test.ts @@ -0,0 +1,121 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' +import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe' +import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file' + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' + +const { clientMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('../client-test-mocks') + return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } +}) + +vi.mock('../../execution/github-legacy-command', () => + moduleMocks.githubLegacyCommandModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-owner-repo-selection', () => + moduleMocks.githubOwnerSelectionModuleMock(clientMocks) +) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks) +})) + +vi.mock('../../api/gh-error-classification', () => + moduleMocks.githubErrorClassificationModuleMock() +) + +vi.mock('../../execution/github-operation-slots', () => + moduleMocks.githubOperationSlotsModuleMock(clientMocks) +) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: clientMocks.gitExecFileAsyncMock +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...moduleMocks.githubHostedCliModuleMock(clientMocks) +})) +vi.mock('../../repositories/local-git-config-signature', () => + moduleMocks.localGitConfigSignatureModuleMock(clientMocks) +) +vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => + moduleMocks.githubEnterpriseRepositoryModuleMock( + await importOriginal() + ) +) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) +vi.mock('../../repositories/github-api-repository', async (importOriginal) => + moduleMocks.githubApiRepositoryModuleMock( + clientMocks, + await importOriginal() + ) +) + +vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) => + moduleMocks.githubApiRepositoryRemoteProbeModuleMock( + clientMocks, + await importOriginal() + ) +) + +import { getGitHubPRLookupRateLimitBlock } from './pr-lookup-rate-limit' +import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity' +import { resetOriginRepositoryCache } from '../client-test-harness' +import type { RateLimitGuardResult } from '../client-test-mocks' + +const { + execFileAsyncMock, + ghExecFileAsyncMock, + getOwnerRepoMock, + getRemoteUrlForRepoMock, + gitExecFileAsyncMock, + getRateLimitMock, + rateLimitGuardMock, + noteRateLimitSpendMock +} = clientMocks + +describe('getGitHubPRLookupRateLimitBlock', () => { + beforeEach(() => { + resetOriginRepositoryCache() + execFileAsyncMock.mockReset() + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) + getRemoteUrlForRepoMock.mockReset() + gitExecFileAsyncMock.mockReset() + getRateLimitMock.mockReset() + getRateLimitMock.mockResolvedValue(undefined) + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() + _resetOwnerRepoCache() + }) + + it('reports the latest reset when both lookup buckets are exhausted', async () => { + rateLimitGuardMock.mockImplementation(((bucket: string) => ({ + blocked: true, + remaining: 4, + limit: 5000, + // Why: core resets first, so returning it would retry into graphql's block. + resetAt: bucket === 'core' ? 1_800_000_000 : 1_800_003_600 + })) as () => RateLimitGuardResult) + + await expect(getGitHubPRLookupRateLimitBlock('/repo-root')).resolves.toEqual({ + resetAt: 1_800_003_600 + }) + }) + + it('fails open when the exempt rate-limit probe itself fails', async () => { + getRateLimitMock.mockRejectedValue(new Error('probe offline')) + + await expect(getGitHubPRLookupRateLimitBlock('/repo-root')).resolves.toBeNull() + }) +}) diff --git a/src/main/github/client/lookup/pr-lookup-rate-limit.ts b/src/main/github/client/lookup/pr-lookup-rate-limit.ts index 60d9c30d403..9f5352e0d20 100644 --- a/src/main/github/client/lookup/pr-lookup-rate-limit.ts +++ b/src/main/github/client/lookup/pr-lookup-rate-limit.ts @@ -1,11 +1,16 @@ -import { ghRepoExecOptions, githubRepoContext, type LocalGitExecOptions } from '../../gh-utils' -import { getOriginGitHubApiRepository, type GitHubApiRepository } from '../../github-api-repository' +import { + ghRepoExecOptions, + githubRepoContext, + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' +import { getOriginGitHubApiRepository } from '../../repositories/github-api-repository-remote-probe' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { getRateLimit, repositoryRateLimitGuard, spendsSharedGitHubComQuota, type RateLimitBucketKind -} from '../../rate-limit' +} from '../../api/rate-limit' import type { GhExecOptions } from './../github-exec-scope' // REST branch lookup can fall back to GraphQL-backed gh commands; guard and debit both buckets. export const PR_BRANCH_LOOKUP_BUCKETS = ['core', 'graphql'] as const diff --git a/src/main/github/client/lookup/pr-number-lookup.ts b/src/main/github/client/lookup/pr-number-lookup.ts index c64a510aedd..db3eb3df8ec 100644 --- a/src/main/github/client/lookup/pr-number-lookup.ts +++ b/src/main/github/client/lookup/pr-number-lookup.ts @@ -1,7 +1,12 @@ -import { classifyPRRefreshError } from '../../pr-refresh-error-classification' -import { ghExecFileAsync } from '../../gh-utils' -import type { OwnerRepo, ghRepoExecOptions } from '../../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' +import { classifyPRRefreshError } from '../../pull-requests/refresh/pr-refresh-error-classification' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type { + GitHubRepositoryIdentity as OwnerRepo, + GitHubRepositoryIdentity as GitHubApiRepository +} from '../../../../shared/github/repositories/repository-identity' +import type { ghRepoExecOptions } from '../../repositories/github-repository-identity' +import { githubHostExecOptions } from '../../repositories/github-repository-host' + import { isNoPullRequestError, isNotFoundGhError, @@ -17,8 +22,8 @@ import { } from './pull-request-lookup-data' import { hydratePullRequestLookupData } from './pull-request-lookup-hydration' import { isGitObjectId, isUsableRestStackMetadata } from './rest-stack-metadata-validation' -import { revalidateGitHubRestJson } from '../../github-rest-revalidation' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' +import { revalidateGitHubRestJson } from '../../api/github-rest-revalidation' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' import { ownerRepoFromPullRequestUrl, sameOwnerRepo } from '../github-exec-scope' import { readSharedPullRequestSidebarQuery, diff --git a/src/main/github/client/lookup/pr-refresh-outcome-assembly.ts b/src/main/github/client/lookup/pr-refresh-outcome-assembly.ts index 60c23b2ce56..7ccbac47fc7 100644 --- a/src/main/github/client/lookup/pr-refresh-outcome-assembly.ts +++ b/src/main/github/client/lookup/pr-refresh-outcome-assembly.ts @@ -2,14 +2,14 @@ import { classifyPRCheckRollupResult, summarizePRCheckRollup } from '../../../../shared/source-control/checks/pr-check-status' -import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { PRConflictSummary, PRMergeableState, GitHubPRStack -} from '../../../../shared/github/pull-request-types' -import { mapPRState } from '../../mappers' -import type { OwnerRepo } from '../../gh-utils' +} from '../../../../shared/github/pull-requests/pull-request-types' +import { mapPRState } from '../../api/github-read-response' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' import type { PullRequestLookupData } from './pull-request-lookup-data' // Main-only: the full rollup stays off the renderer broadcast, beside the outcome it was read for. diff --git a/src/main/github/client/lookup/pr-stack-summary-cache.ts b/src/main/github/client/lookup/pr-stack-summary-cache.ts index c21baa63106..0021509620b 100644 --- a/src/main/github/client/lookup/pr-stack-summary-cache.ts +++ b/src/main/github/client/lookup/pr-stack-summary-cache.ts @@ -1,8 +1,9 @@ -import type { GitHubPRStack } from '../../../../shared/github/pull-request-types' -import type { ghRepoExecOptions } from '../../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' -import { githubReadExecutionScope } from '../../github-read-execution-scope' -import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key' +import type { GitHubPRStack } from '../../../../shared/github/pull-requests/pull-request-types' +import type { ghRepoExecOptions } from '../../repositories/github-repository-identity' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' import { getRestPRByNumber } from './pr-number-lookup' export const PR_STACK_SUMMARY_CACHE_TTL_MS = 60_000 diff --git a/src/main/github/client/lookup/pull-request-lookup-data.ts b/src/main/github/client/lookup/pull-request-lookup-data.ts index 4442f4965fc..62f23ec8f95 100644 --- a/src/main/github/client/lookup/pull-request-lookup-data.ts +++ b/src/main/github/client/lookup/pull-request-lookup-data.ts @@ -1,24 +1,28 @@ import { readCurrentReviewHead } from '../../../source-control/review-current-head' import { shouldHideMergedImplicitReview } from '../../../source-control/branch-review-selection' import type { - GitHubOwnerRepo, + GitHubRepositoryIdentity as GitHubOwnerRepo, + GitHubRepositoryIdentity as OwnerRepo +} from '../../../../shared/github/repositories/repository-identity' +import type { GitHubPRMergeMethodSettings, GitHubPRStack, PRMergeableState, PRReviewDecision -} from '../../../../shared/github/pull-request-types' -import { gitExecFileAsync, type OwnerRepo } from '../../gh-utils' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +} from '../../../../shared/github/pull-requests/pull-request-types' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' + +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import type { HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' -import { mapPRState } from '../../mappers' -import type { MergedPRCommitMembership } from '../../merged-pr-commit-membership' +import { mapPRState } from '../../api/github-read-response' +import type { MergedReviewCommitMembership as MergedPRCommitMembership } from '../../../source-control/merged-review-membership-memo' import { normalizePRMergeable, normalizeReviewDecision, isAutoMergeEnabled } from './../map/work-item-field-coercion' import { ownerRepoFromPullRequestUrl, sameOwnerRepo } from '../github-exec-scope' -import { githubRepositoryWebHost } from '../../github-repository-host' +import { githubRepositoryWebHost } from '../../repositories/github-repository-host' export type PullRequestLookupData = { number: number title: string @@ -89,6 +93,8 @@ export const PR_BRANCH_LIST_JSON_FIELDS = export type GitHubPRBranchLookupOptions = HostedReviewExecutionOptions & { userRefresh?: boolean + /** CI watches need provider status, without local conflict or stack enrichment. */ + includeDerivedData?: boolean acceptMergedFallbackPR?: boolean // Supply the actual worktree head without probing a different main-repo checkout. currentHeadOid?: string | null diff --git a/src/main/github/client/lookup/pull-request-lookup-hydration.ts b/src/main/github/client/lookup/pull-request-lookup-hydration.ts index 4a24491569f..7ef03d7b33c 100644 --- a/src/main/github/client/lookup/pull-request-lookup-hydration.ts +++ b/src/main/github/client/lookup/pull-request-lookup-hydration.ts @@ -1,7 +1,7 @@ -import type { OwnerRepo } from '../../gh-utils' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' import type { GhExecOptions } from './../github-exec-scope' import { detectRepositoryMergeMetadata } from './../detect/repository-merge-metadata' -import { mapPRState } from '../../mappers' +import { mapPRState } from '../../api/github-read-response' import { normalizePullRequestLookupData, type PullRequestLookupData diff --git a/src/main/github/client/lookup/pull-request-push-target.ts b/src/main/github/client/lookup/pull-request-push-target.ts index be96c55dfb1..0812cb51005 100644 --- a/src/main/github/client/lookup/pull-request-push-target.ts +++ b/src/main/github/client/lookup/pull-request-push-target.ts @@ -1,21 +1,19 @@ -import { withGitHubRepoExecution } from '../../github-repository-identity' -import type { IssueSourcePreference } from '../../../../shared/repo-types' -import type { GitPushTarget } from '../../../../shared/worktree/types' import { - ghExecFileAsync, - acquire, - release, + withGitHubRepoExecution, ghRepoExecOptions, githubRepoContext, getRemoteUrlForRepo, type LocalGitExecOptions -} from '../../gh-utils' -import { - getGitHubApiRepositoryForRemote, - githubHostExecOptions, - type GitHubApiRepository -} from '../../github-api-repository' -import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key' +} from '../../repositories/github-repository-identity' +import type { IssueSourcePreference } from '../../../../shared/repo-types' +import type { GitPushTarget } from '../../../../shared/worktree/types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' + +import { getGitHubApiRepositoryForRemote } from '../../repositories/github-api-repository-remote-probe' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' import { isNotFoundGhError } from './../gh-error-predicates' import { resolvePullRequestLookupCandidates } from './../pull-request-lookup-candidates' export function pickPushRemoteUrl(args: { diff --git a/src/main/github/client/lookup/pull-request-sidebar-query.test.ts b/src/main/github/client/lookup/pull-request-sidebar-query.test.ts new file mode 100644 index 00000000000..1eedfb87fa6 --- /dev/null +++ b/src/main/github/client/lookup/pull-request-sidebar-query.test.ts @@ -0,0 +1,208 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { exec, spend } = vi.hoisted(() => ({ exec: vi.fn(), spend: vi.fn() })) +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + ghExecFileAsync: exec +})) + +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: vi.fn() +})) +vi.mock('../../api/rate-limit', () => ({ + noteRepositoryRateLimitSpend: spend, + repositoryRateLimitGuard: () => ({ blocked: false }), + spendsSharedGitHubComQuota: () => false +})) + +import { getPRByNumber, lookupPRByNumber } from './pr-number-lookup' +import { _resetPRStackSummaryCacheForTests } from './pr-stack-summary-cache' +import { _resetMergeQueueCacheForTests } from '../detect/repository-merge-metadata-cache' +import { readPullRequestSidebarQuery } from './pull-request-sidebar-query' +import { createImplicitDefaultBranchPRPolicy } from './implicit-default-branch-pr' +import { derivePRCheckStatusFromRollup as deriveCheckStatus } from '../../../../shared/source-control/checks/pr-check-status' + +const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } +const options = { cwd: '/folder-workspace' } +const successCheck = { __typename: 'StatusContext', state: 'SUCCESS' } + +function commits(checks: unknown[] = [successCheck], endCursor?: string, oid = 'b'.repeat(40)) { + return { + nodes: [ + { + commit: { + oid, + checkSuites: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } }, + statusCheckRollup: { + contexts: { + nodes: checks.map((raw) => + raw && + typeof raw === 'object' && + '__typename' in raw && + raw.__typename === 'CheckRun' + ? { ...raw, checkSuite: { databaseId: 7 } } + : raw + ), + pageInfo: { hasNextPage: Boolean(endCursor), endCursor: endCursor ?? null } + } + } + } + } + ] + } +} +const fields = { + number: 42, + title: 'Keep sidebar metadata together', + state: 'CLOSED', + url: 'https://github.com/acme/widgets/pull/42', + updatedAt: '2026-10-28T00:00:00Z', + isDraft: false, + mergeable: 'UNKNOWN', + reviewDecision: null, + mergeStateStatus: 'UNKNOWN', + autoMergeRequest: null, + baseRefName: 'main', + headRefName: 'feature/sidebar', + baseRefOid: 'a'.repeat(40), + headRefOid: 'b'.repeat(40), + headRepositoryOwner: { login: 'contributor' }, + headRepository: { name: 'widgets' }, + commits: commits(), + stack: null, + stackEntry: null +} + +function response(pr: Record = fields, errors?: unknown[]) { + return { stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }) } +} + +beforeEach(() => { + vi.resetAllMocks() + _resetPRStackSummaryCacheForTests() + _resetMergeQueueCacheForTests() +}) + +describe('sidebar PR query', () => { + it('rejects a deleted fork from the parsed number query when head identity is unknown', async () => { + exec.mockResolvedValueOnce( + response({ ...fields, isCrossRepository: true, headRepository: null }) + ) + const policy = createImplicitDefaultBranchPRPolicy({ + originHeadRepo: null, + trackedUpstream: null, + branchName: fields.headRefName, + repoPath: '/folder-workspace', + localGitOptions: {}, + ghOptions: options + }) + expect( + await lookupPRByNumber({ + candidates: [repository], + number: 42, + ghOptions: options, + executionScope: 'local:host', + policy + }) + ).toEqual({ data: null, dataRepo: null }) + expect([...policy.rejectedPRUrls]).toEqual([fields.url]) + expect(exec).toHaveBeenCalledTimes(1) + }) + + it('retains PR metadata but never certifies a successful prefix after continuation failure', async () => { + exec + .mockResolvedValueOnce(response({ ...fields, commits: commits([successCheck], 'next') })) + .mockRejectedValue(new Error('Unavailable')) + await expect( + getPRByNumber(repository, 42, options, 'local:host', undefined, { includeStackSummary: true }) + ).resolves.toMatchObject({ + number: 42, + title: fields.title, + checksUnavailable: true, + statusCheckRollup: [] + }) + }) + + it('keeps a failure beyond the first 100 checks and reuses the first page', async () => { + const failingCheck = { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'FAILURE' } + exec + .mockResolvedValueOnce( + response({ + ...fields, + commits: commits( + Array.from({ length: 100 }, () => successCheck), + 'next' + ) + }) + ) + .mockResolvedValueOnce( + response({ number: 42, headRefOid: fields.headRefOid, commits: commits([failingCheck]) }) + ) + const data = await getPRByNumber(repository, 42, options, 'local:host', undefined, { + includeStackSummary: true + }) + expect(data?.statusCheckRollup).toHaveLength(101) + expect(deriveCheckStatus(data?.statusCheckRollup)).toBe('failure') + expect(exec).toHaveBeenCalledTimes(2) + expect(exec.mock.calls[1][0]).toContain('checksCursor=next') + expect(exec.mock.calls[1][0].join(' ')).not.toContain('stackEntry') + }) + + it.each([ + { number: 42, headRefOid: fields.headRefOid, commits: commits([], 'next') }, + { number: 42, headRefOid: fields.headRefOid, commits: commits([], undefined, 'c'.repeat(40)) } + ])( + 'keeps metadata without a certified summary when checks pagination stops advancing or the commit changes', + async (nextPage) => { + exec + .mockResolvedValueOnce(response({ ...fields, commits: commits([successCheck], 'next') })) + .mockResolvedValueOnce(response(nextPage)) + .mockRejectedValue(new Error('Unavailable')) + const data = await getPRByNumber(repository, 42, options, 'local:host', undefined, { + includeStackSummary: true + }) + expect(data).toMatchObject({ + number: 42, + title: fields.title, + checksUnavailable: true, + statusCheckRollup: [] + }) + } + ) +}) + +it.each([ + { checks: [null], errors: undefined }, + { + checks: [{ __typename: 'CheckRun', status: 'FUTURE_STATUS', conclusion: null }], + errors: undefined + }, + { + checks: [successCheck], + errors: [ + { path: ['repository', 'pullRequest', 'commits', 'nodes', 0, 'commit', 'statusCheckRollup'] } + ] + } +])( + 'keeps valid metadata and stack when strict checks are unavailable: %j', + async ({ checks, errors }) => { + exec.mockResolvedValueOnce( + response( + { + ...fields, + commits: commits(checks), + stack: { number: 7, size: 2, baseRefName: 'main' }, + stackEntry: { position: 1 } + }, + errors + ) + ) + await expect(readPullRequestSidebarQuery(repository, 42, options)).resolves.toMatchObject({ + title: fields.title, + checksUnavailable: true, + stackMetadataChecked: true, + stack: { number: 7, size: 2, position: 1 } + }) + } +) diff --git a/src/main/github/client/lookup/pull-request-sidebar-query.ts b/src/main/github/client/lookup/pull-request-sidebar-query.ts index c8d3cfe0952..0ab2afc50ce 100644 --- a/src/main/github/client/lookup/pull-request-sidebar-query.ts +++ b/src/main/github/client/lookup/pull-request-sidebar-query.ts @@ -1,8 +1,9 @@ import { z } from 'zod' -import { ghExecFileAsync } from '../../gh-utils' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' -import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository' -import { noteRepositoryRateLimitSpend } from '../../rate-limit' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend } from '../../api/rate-limit' import type { GhExecOptions } from '../github-exec-scope' import type { PullRequestLookupData } from './pull-request-lookup-data' import { diff --git a/src/main/github/client/lookup/shared-pr-provider-reads.ts b/src/main/github/client/lookup/shared-pr-provider-reads.ts index fd6c923e7a4..4202c2aa046 100644 --- a/src/main/github/client/lookup/shared-pr-provider-reads.ts +++ b/src/main/github/client/lookup/shared-pr-provider-reads.ts @@ -3,8 +3,8 @@ import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' -import type { GitHubApiRepository } from '../../github-api-repository' -import { githubReadExecutionScope } from '../../github-read-execution-scope' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' import { readCompletePRCheckObservation } from '../check/complete-pr-check-observation' import type { GhExecOptions } from '../github-exec-scope' import type { PullRequestLookupData } from './pull-request-lookup-data' diff --git a/src/main/github/client/lookup/tracked-upstream-branch.ts b/src/main/github/client/lookup/tracked-upstream-branch.ts index 9fd4a838e34..a01b56d4e5c 100644 --- a/src/main/github/client/lookup/tracked-upstream-branch.ts +++ b/src/main/github/client/lookup/tracked-upstream-branch.ts @@ -2,9 +2,9 @@ import { readGitReviewBranchSources, type GitReviewBranchSource } from '../../../../shared/git/remotes/git-review-branch-source' -import { gitExecFileAsync } from '../../gh-utils' -import { readLocalGitConfigSignature } from '../../local-git-config-signature' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' +import { readLocalGitConfigSignature } from '../../repositories/local-git-config-signature' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { TRACKED_UPSTREAM_SNAPSHOT_CACHE_TTL_MS, trackedUpstreamSnapshotCache, diff --git a/src/main/github/client/lookup/tracked-upstream-cache.ts b/src/main/github/client/lookup/tracked-upstream-cache.ts index 7a0f37d06d7..1e3452a9151 100644 --- a/src/main/github/client/lookup/tracked-upstream-cache.ts +++ b/src/main/github/client/lookup/tracked-upstream-cache.ts @@ -1,8 +1,8 @@ import type { GitReviewBranchSource } from '../../../../shared/git/remotes/git-review-branch-source' import { splitRemoteBranchName } from '../../../../shared/git/remotes/git-remote-branch-name' -import type { OwnerRepo } from '../../gh-utils' -import { readLocalGitConfigSignature } from '../../local-git-config-signature' -import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import { readLocalGitConfigSignature } from '../../repositories/local-git-config-signature' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' export type TrackedUpstreamBranch = { remoteName: string branchName: string diff --git a/src/main/github/client/map/review-comment-response.ts b/src/main/github/client/map/review-comment-response.ts index f17f653ba0e..6ea746f4853 100644 --- a/src/main/github/client/map/review-comment-response.ts +++ b/src/main/github/client/map/review-comment-response.ts @@ -1,5 +1,5 @@ -import { githubBodyImageUrls } from '../../body-image-urls' -import type { PRComment } from '../../../../shared/github/comment-types' +import { githubBodyImageUrls } from '../../attachments/body-image-urls' +import type { PRComment } from '../../../../shared/github/comments/comment-types' export function mapReviewCommentResponse( data: { id?: number diff --git a/src/main/github/client/map/work-item-field-coercion.ts b/src/main/github/client/map/work-item-field-coercion.ts index 592c84b6ca1..d586e173a30 100644 --- a/src/main/github/client/map/work-item-field-coercion.ts +++ b/src/main/github/client/map/work-item-field-coercion.ts @@ -1,8 +1,8 @@ import type { PRMergeableState, PRReviewDecision -} from '../../../../shared/github/pull-request-types' -import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' +} from '../../../../shared/github/pull-requests/pull-request-types' +import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' import { summarizeProviderChecks } from '../../../../shared/source-control/checks/provider-check-summary' // The renderer supplies repoId after IPC; main knows only the repository path. export type MainWorkItem = Omit diff --git a/src/main/github/client/map/work-item.ts b/src/main/github/client/map/work-item.ts index f2018edcf00..bb5c1218b1b 100644 --- a/src/main/github/client/map/work-item.ts +++ b/src/main/github/client/map/work-item.ts @@ -1,4 +1,4 @@ -import type { OwnerRepo } from '../../gh-utils' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' import { authorFieldsFromUnknown, extractHeadOwnerLogin, diff --git a/src/main/github/client/merge/merge-pr.ts b/src/main/github/client/merge/merge-pr.ts index 801a736a870..12d28d225e7 100644 --- a/src/main/github/client/merge/merge-pr.ts +++ b/src/main/github/client/merge/merge-pr.ts @@ -1,9 +1,12 @@ -import { invalidateReviewLookupsAfterPRMutation } from '../../pr-mutation-review-invalidation' -import type { PRConflictSummary } from '../../../../shared/github/pull-request-types' -import { getPRConflictSummary } from '../../conflict-summary' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' -import { mergeGitHubPRStack } from '../../github-pr-stack' +import { invalidateReviewLookupsAfterPRMutation } from '../../pull-requests/refresh/pr-mutation-review-invalidation' +import type { PRConflictSummary } from '../../../../shared/github/pull-requests/pull-request-types' +import { getPRConflictSummary } from '../../pull-requests/conflicts/conflict-summary' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { mergeGitHubPRStack } from '../../pull-requests/stacks/github-pr-stack-async-merge' import { githubPRStackExecutionScope, type GhExecOptions } from './../github-exec-scope' import { detectRepositoryMergeMetadata } from './../detect/repository-merge-metadata' import type { PullRequestLookupData } from './../lookup/pull-request-lookup-data' diff --git a/src/main/github/client/merge/pr-auto-merge.ts b/src/main/github/client/merge/pr-auto-merge.ts index d0224544860..cb770163301 100644 --- a/src/main/github/client/merge/pr-auto-merge.ts +++ b/src/main/github/client/merge/pr-auto-merge.ts @@ -1,8 +1,11 @@ -import { invalidateReviewLookupsAfterPRMutation } from '../../pr-mutation-review-invalidation' -import type { GitHubPRMergeMethod } from '../../../../shared/github/pull-request-types' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { classifyPullRequestUpdateError } from '../../gh-error-classification' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import { invalidateReviewLookupsAfterPRMutation } from '../../pull-requests/refresh/pr-mutation-review-invalidation' +import type { GitHubPRMergeMethod } from '../../../../shared/github/pull-requests/pull-request-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { classifyPullRequestUpdateError } from '../../api/gh-error-classification' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { githubPRStackExecutionScope, type GhExecOptions } from './../github-exec-scope' import { detectRepositoryMergeMetadata } from './../detect/repository-merge-metadata' import { getRestPRByNumber } from './../lookup/pr-number-lookup' diff --git a/src/main/github/client/pull-request-lookup-candidates.ts b/src/main/github/client/pull-request-lookup-candidates.ts index 05e6ca8e090..394ddb705b4 100644 --- a/src/main/github/client/pull-request-lookup-candidates.ts +++ b/src/main/github/client/pull-request-lookup-candidates.ts @@ -1,10 +1,8 @@ import type { IssueSourcePreference } from '../../../shared/repo-types' -import type { LocalGitExecOptions } from '../gh-utils' -import { - getOriginGitHubApiRepository, - resolveGitHubApiRepositoryCandidates, - type GitHubApiRepository -} from '../github-api-repository' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' +import { getOriginGitHubApiRepository } from '../repositories/github-api-repository-remote-probe' +import { resolveGitHubApiRepositoryCandidates } from '../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' export async function resolvePullRequestLookupCandidates( repoPath: string, preference: IssueSourcePreference | undefined, diff --git a/src/main/github/client/update/pr-comment-reaction.ts b/src/main/github/client/update/pr-comment-reaction.ts index 872ba463eb9..d847f34d0ed 100644 --- a/src/main/github/client/update/pr-comment-reaction.ts +++ b/src/main/github/client/update/pr-comment-reaction.ts @@ -1,8 +1,11 @@ -import type { GitHubReactionContent } from '../../../../shared/github/comment-types' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' -import { toGraphQLReactionContent } from '../../comment-reactions' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' +import type { GitHubReactionContent } from '../../../../shared/github/comments/comment-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { toGraphQLReactionContent } from '../../comments/comment-reactions' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' export async function setPRCommentReaction( repoPath: string, reactionSubjectId: string, diff --git a/src/main/github/client/update/pr-details.ts b/src/main/github/client/update/pr-details.ts index 47a7c377fec..99b4e899ed5 100644 --- a/src/main/github/client/update/pr-details.ts +++ b/src/main/github/client/update/pr-details.ts @@ -1,16 +1,13 @@ -import { invalidateReviewLookupsAfterPRMutation } from '../../pr-mutation-review-invalidation' -import { - ghExecFileAsync, - acquire, - release, - classifyPullRequestUpdateError, - type LocalGitExecOptions -} from '../../gh-utils' +import { invalidateReviewLookupsAfterPRMutation } from '../../pull-requests/refresh/pr-mutation-review-invalidation' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import { classifyPullRequestUpdateError } from '../../api/gh-error-classification' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' import { resolveGitHubRepoExecution, - type GitHubApiRepository, type GitHubRepoExecOptions -} from '../../github-api-repository' +} from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { codeHostFailure, classifiedFailure } from '../../../../shared/code-host-failure-copy' async function patchPullRequest( diff --git a/src/main/github/client/update/pr-file-viewed.ts b/src/main/github/client/update/pr-file-viewed.ts index 6caa223e7e2..66c54695e9c 100644 --- a/src/main/github/client/update/pr-file-viewed.ts +++ b/src/main/github/client/update/pr-file-viewed.ts @@ -1,7 +1,10 @@ -import type { GhAccountBinding } from '../../../../shared/github/account-binding' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' +import type { GhAccountBinding } from '../../../../shared/github/accounts/account-binding' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' export async function setPRFileViewed(args: { repoPath: string connectionId?: string | null diff --git a/src/main/github/client/update/pr-ready.ts b/src/main/github/client/update/pr-ready.ts index e9aceaa068a..1c33e389039 100644 --- a/src/main/github/client/update/pr-ready.ts +++ b/src/main/github/client/update/pr-ready.ts @@ -1,12 +1,10 @@ -import { invalidateReviewLookupsAfterPRMutation } from '../../pr-mutation-review-invalidation' -import { - acquire, - classifyPullRequestUpdateError, - ghExecFileAsync, - release, - type LocalGitExecOptions -} from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import { invalidateReviewLookupsAfterPRMutation } from '../../pull-requests/refresh/pr-mutation-review-invalidation' +import { acquire, release } from '../../execution/github-operation-slots' +import { classifyPullRequestUpdateError } from '../../api/gh-error-classification' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { codeHostFailure, classifiedFailure } from '../../../../shared/code-host-failure-copy' export function markPRReadyForReview( diff --git a/src/main/github/client/update/pr-reviewers.ts b/src/main/github/client/update/pr-reviewers.ts index 39ffa1f2420..aafba3a26f1 100644 --- a/src/main/github/client/update/pr-reviewers.ts +++ b/src/main/github/client/update/pr-reviewers.ts @@ -1,6 +1,9 @@ -import { invalidateReviewLookupsAfterPRMutation } from '../../pr-mutation-review-invalidation' -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import { invalidateReviewLookupsAfterPRMutation } from '../../pull-requests/refresh/pr-mutation-review-invalidation' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { codeHostFailure } from '../../../../shared/code-host-failure-copy' function reviewerUpdateArgs( diff --git a/src/main/github/client/update/pr-state.ts b/src/main/github/client/update/pr-state.ts index 1253fa592b7..866502b9a75 100644 --- a/src/main/github/client/update/pr-state.ts +++ b/src/main/github/client/update/pr-state.ts @@ -1,13 +1,11 @@ -import { invalidateReviewLookupsAfterPRMutation } from '../../pr-mutation-review-invalidation' +import { invalidateReviewLookupsAfterPRMutation } from '../../pull-requests/refresh/pr-mutation-review-invalidation' import type { GitHubPullRequestStateUpdate } from '../../../../shared/issue-mutation-types' -import { - ghExecFileAsync, - acquire, - release, - classifyPullRequestUpdateError, - type LocalGitExecOptions -} from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import { classifyPullRequestUpdateError } from '../../api/gh-error-classification' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { codeHostFailure, classifiedFailure } from '../../../../shared/code-host-failure-copy' export async function updatePRState( repoPath: string, diff --git a/src/main/github/client/update/resolve-review-thread.ts b/src/main/github/client/update/resolve-review-thread.ts index ad55844c9ad..e1b75999fe7 100644 --- a/src/main/github/client/update/resolve-review-thread.ts +++ b/src/main/github/client/update/resolve-review-thread.ts @@ -1,6 +1,9 @@ -import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' export async function resolveReviewThread( repoPath: string, threadId: string, diff --git a/src/main/github/client/work-item-source-selection.test.ts b/src/main/github/client/work-item-source-selection.test.ts new file mode 100644 index 00000000000..be8fd94011e --- /dev/null +++ b/src/main/github/client/work-item-source-selection.test.ts @@ -0,0 +1,298 @@ +import type * as GithubLegacyCommandModule from '../execution/github-legacy-command' +import type * as GhExecFileModule from '../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubOwnerRepoSelectionModule from '../repositories/github-owner-repo-selection' +import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity' +import type * as GithubOperationSlotsModule from '../execution/github-operation-slots' +import type * as GithubApiRepositoryModule from '../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../repositories/github-api-repository-remote-probe' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +// Keep legacy REST request/failure coverage; API-boundary suites exercise the GraphQL path. +vi.mock('./list/work-item-search-page', () => ({ usesGraphqlWorkItemSearch: () => false })) + +const { + execFileAsyncMock, + ghExecFileAsyncMock, + getOwnerRepoMock, + getIssueOwnerRepoMock, + getOwnerRepoForRemoteMock, + resolvePRRepositoryCandidatesMock, + resolveIssueSourceMock, + rateLimitGuardMock, + noteRateLimitSpendMock, + acquireMock, + releaseMock +} = vi.hoisted(() => ({ + execFileAsyncMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + getIssueOwnerRepoMock: vi.fn(), + getOwnerRepoForRemoteMock: vi.fn(), + resolvePRRepositoryCandidatesMock: vi.fn(), + resolveIssueSourceMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), + acquireMock: vi.fn(), + releaseMock: vi.fn() +})) + +vi.mock('../execution/github-legacy-command', async () => { + const actual = await vi.importActual( + '../execution/github-legacy-command' + ) + return { + ...actual, + execFileAsync: execFileAsyncMock + } +}) + +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async () => { + const actual = await vi.importActual( + '../../git/command-runner/hosted-cli/gh-exec-file' + ) + return { + ...actual, + ghExecFileAsync: ghExecFileAsyncMock + } +}) + +vi.mock('../repositories/github-owner-repo-selection', async () => { + const actual = await vi.importActual( + '../repositories/github-owner-repo-selection' + ) + return { + ...actual, + getOwnerRepo: getOwnerRepoMock, + resolveIssueSource: resolveIssueSourceMock + } +}) + +vi.mock('../repositories/github-repository-identity', async () => { + const actual = await vi.importActual( + '../repositories/github-repository-identity' + ) + return { + ...actual, + getOwnerRepoForRemote: getOwnerRepoForRemoteMock, + _resetOwnerRepoCache: vi.fn() + } +}) + +vi.mock('../execution/github-operation-slots', async () => { + const actual = await vi.importActual( + '../execution/github-operation-slots' + ) + return { + ...actual, + acquire: acquireMock, + release: releaseMock + } +}) + +vi.mock('../api/rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock, + getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: vi.fn(), + spendsSharedGitHubComQuota: () => true +})) + +vi.mock('../repositories/github-api-repository', async (importOriginal) => { + return { + ...(await importOriginal()), + resolveIssueGitHubApiRepositorySource: ( + repoPath: string, + preference: unknown, + connectionId?: string | null, + localGitOptions?: unknown + ) => resolveIssueSourceMock(repoPath, preference, connectionId, localGitOptions), + getIssueGitHubApiRepository: (repoPath: string, connectionId?: string | null) => + getIssueOwnerRepoMock(repoPath, connectionId), + resolveGitHubApiRepositoryCandidates: ( + repoPath: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => resolvePRRepositoryCandidatesMock(repoPath, connectionId, localGitOptions) + } +}) + +vi.mock('../repositories/github-api-repository-remote-probe', async (importOriginal) => { + return { + ...(await importOriginal()), + getOriginGitHubApiRepository: ( + repoPath: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => getOwnerRepoMock(repoPath, connectionId, localGitOptions), + getGitHubApiRepositoryForRemote: ( + repoPath: string, + remoteName: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => + remoteName === 'origin' + ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) + : getOwnerRepoForRemoteMock(repoPath, remoteName, connectionId, localGitOptions) + } +}) +import { getWorkItem } from './fetch/get-work-item' +import { listWorkItems } from './list/list-work-items' +import { _resetOwnerRepoCache } from '../repositories/github-repository-identity' + +// Share origin fixtures while letting candidate tests opt into upstream. +function mockUpstreamCandidate(upstream: { owner: string; repo: string } | null): void { + getOwnerRepoForRemoteMock.mockImplementation( + async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => + remoteName === 'upstream' ? upstream : getOwnerRepoMock(repoPath, connectionId, opts) + ) +} + +describe('GitHub issue source split', () => { + beforeEach(() => { + execFileAsyncMock.mockReset() + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getIssueOwnerRepoMock.mockReset() + getOwnerRepoForRemoteMock.mockReset() + resolvePRRepositoryCandidatesMock.mockReset() + resolveIssueSourceMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + // Preserve one source lookup per test while exercising the preference-aware resolver. + resolveIssueSourceMock.mockImplementation(async () => ({ + source: await getIssueOwnerRepoMock(), + fellBack: false + })) + getOwnerRepoForRemoteMock.mockImplementation( + async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => + remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null + ) + resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => { + const origin = await getOwnerRepoMock(repoPath, connectionId) + const repository = origin ? { host: 'github.com', ...origin } : null + return { candidates: repository ? [repository] : [], headRepo: repository } + }) + _resetOwnerRepoCache() + }) + + it.each(['is:issue', 'is:pr'])( + 'propagates GitHub outages for scoped %s queries', + async (query) => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 503: Service Unavailable')) + + await expect(listWorkItems('/repo-root', 10, query)).rejects.toThrow( + 'HTTP 503: Service Unavailable' + ) + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + } + ) + + it('propagates an outage when both sides of a combined query are unavailable', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock + .mockRejectedValueOnce(new Error('HTTP 503: Service Unavailable')) + .mockRejectedValueOnce(new Error('HTTP 502: Bad Gateway')) + + await expect(listWorkItems('/repo-root', 10, 'is:open')).rejects.toThrow( + 'HTTP 503: Service Unavailable' + ) + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + }) + + it('does not run a bare PR lookup when explicit origin identity is unresolved', async () => { + getOwnerRepoMock.mockResolvedValue(null) + mockUpstreamCandidate({ owner: 'stablyai', repo: 'orca' }) + + await expect(getWorkItem('/repo-root', 42, 'pr', null, {}, 'origin')).resolves.toBeNull() + + expect(resolvePRRepositoryCandidatesMock).not.toHaveBeenCalled() + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('does not run a bare gh lookup for an SSH repo without candidates', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ candidates: [], headRepo: null }) + + await expect(getWorkItem('/remote/repo', 42, 'pr', 'ssh-1')).resolves.toBeNull() + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('raw number lookup tries upstream issue before origin PR', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + // Non-404 upstream failures must not route to an unrelated origin PR with the same number. + ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 404: Not Found')) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 42, + title: 'Origin PR', + state: 'open', + html_url: 'https://github.com/fork/orca/pull/42', + labels: [], + updated_at: '2026-04-02T00:00:00Z', + user: { login: 'octocat' }, + draft: false + }) + }) + + const item = await getWorkItem('/repo-root', 42) + + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 1, + ['api', 'repos/stablyai/orca/issues/42'], + { cwd: '/repo-root' } + ) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + [ + 'pr', + 'view', + '42', + '--repo', + 'fork/orca', + '--json', + expect.stringContaining('reviewDecision') + ], + { cwd: '/repo-root', host: 'github.com' } + ) + expect(item?.type).toBe('pr') + }) + + it('returns partial results when upstream issues fail but origin PRs succeed', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock + .mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible by integration')) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 42, + title: 'Fork PR', + state: 'open', + html_url: 'https://github.com/fork/orca/pull/42', + labels: [], + updated_at: '2026-03-31T00:00:00Z', + user: { login: 'octocat' }, + draft: false, + head: { ref: 'feature' }, + base: { ref: 'main' } + } + ]) + }) + + const result = await listWorkItems('/repo-root', 10) + + expect(result.items.map((i) => i.id)).toEqual(['pr:42']) + expect(result.errors?.issues?.type).toBe('permission_denied') + }) +}) diff --git a/src/main/github/comment-reactions.ts b/src/main/github/comments/comment-reactions.ts similarity index 95% rename from src/main/github/comment-reactions.ts rename to src/main/github/comments/comment-reactions.ts index 89ee5ee8d6b..c2d38f10667 100644 --- a/src/main/github/comment-reactions.ts +++ b/src/main/github/comments/comment-reactions.ts @@ -1,4 +1,7 @@ -import type { GitHubReaction, GitHubReactionContent } from '../../shared/github/comment-types' +import type { + GitHubReaction, + GitHubReactionContent +} from '../../../shared/github/comments/comment-types' type GitHubGraphQLReactionContent = | 'THUMBS_UP' diff --git a/src/main/github/execution/github-legacy-command.ts b/src/main/github/execution/github-legacy-command.ts new file mode 100644 index 00000000000..531c59d0911 --- /dev/null +++ b/src/main/github/execution/github-legacy-command.ts @@ -0,0 +1,5 @@ +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' + +// Repo-scoped operations need the WSL-aware runner; this legacy wrapper serves generic commands. +export const execFileAsync = promisify(execFile) diff --git a/src/main/github/execution/github-operation-slots.test.ts b/src/main/github/execution/github-operation-slots.test.ts new file mode 100644 index 00000000000..8914024c27e --- /dev/null +++ b/src/main/github/execution/github-operation-slots.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { acquire, release } from './github-operation-slots' + +describe('GitHub concurrency', () => { + it('removes aborted waiters without consuming a permit', async () => { + await Promise.all([acquire(), acquire(), acquire(), acquire()]) + const controller = new AbortController() + const queued = acquire(controller.signal) + + controller.abort() + + await expect(queued).rejects.toMatchObject({ name: 'AbortError' }) + release() + await expect(acquire()).resolves.toBeUndefined() + + release() + release() + release() + release() + }) +}) diff --git a/src/main/github/execution/github-operation-slots.ts b/src/main/github/execution/github-operation-slots.ts new file mode 100644 index 00000000000..af63b9cc983 --- /dev/null +++ b/src/main/github/execution/github-operation-slots.ts @@ -0,0 +1,54 @@ +const MAX_CONCURRENT = 4 + +let running = 0 + +type QueueEntry = { + signal?: AbortSignal + start: () => void + reject: (error: Error) => void +} + +const queue: QueueEntry[] = [] + +function githubOperationAbortError(): Error { + const error = new Error('GitHub operation aborted') + error.name = 'AbortError' + return error +} + +export function acquire(signal?: AbortSignal): Promise { + if (signal?.aborted) { + return Promise.reject(githubOperationAbortError()) + } + if (running < MAX_CONCURRENT) { + running += 1 + return Promise.resolve() + } + return new Promise((resolve, reject) => { + const entry: QueueEntry = { + signal, + reject, + start: () => { + signal?.removeEventListener('abort', onAbort) + running += 1 + resolve() + } + } + const onAbort = (): void => { + const index = queue.indexOf(entry) + if (index === -1) { + return + } + queue.splice(index, 1) + reject(githubOperationAbortError()) + } + signal?.addEventListener('abort', onAbort, { once: true }) + queue.push(entry) + }) +} + +export function release(): void { + running -= 1 + const next = queue.shift() + next?.start() +} diff --git a/src/main/github/gh-capability-state.test.ts b/src/main/github/gh-capability-state.test.ts deleted file mode 100644 index a3cd51ec396..00000000000 --- a/src/main/github/gh-capability-state.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { ghExecFileAsyncMock } = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn() -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - ghExecFileAsync: ghExecFileAsyncMock -})) - -import { - clearGhCapabilityStateForTests, - getGhMultiAccountCapability, - invalidateGhMultiAccountCapability -} from './gh-capability-state' - -describe('gh-capability-state', () => { - beforeEach(() => { - clearGhCapabilityStateForTests() - ghExecFileAsyncMock.mockReset() - }) - - afterEach(() => { - clearGhCapabilityStateForTests() - }) - - it('caches per runtime and invalidates on request', async () => { - ghExecFileAsyncMock.mockResolvedValue({ - stdout: 'Usage: gh auth token [--user login]', - stderr: '' - }) - await getGhMultiAccountCapability({ wslDistro: 'Ubuntu' }) - await getGhMultiAccountCapability({ wslDistro: 'Ubuntu' }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - - invalidateGhMultiAccountCapability({ wslDistro: 'Ubuntu' }) - await getGhMultiAccountCapability({ wslDistro: 'Ubuntu' }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/github/gh-utils-concurrency.test.ts b/src/main/github/gh-utils-concurrency.test.ts deleted file mode 100644 index de6389d260a..00000000000 --- a/src/main/github/gh-utils-concurrency.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { acquire, release } from './gh-utils' - -describe('GitHub concurrency', () => { - it('removes aborted waiters without consuming a permit', async () => { - await Promise.all([acquire(), acquire(), acquire(), acquire()]) - const controller = new AbortController() - const queued = acquire(controller.signal) - - controller.abort() - - await expect(queued).rejects.toMatchObject({ name: 'AbortError' }) - release() - await expect(acquire()).resolves.toBeUndefined() - - release() - release() - release() - release() - }) -}) diff --git a/src/main/github/gh-utils.test.ts b/src/main/github/gh-utils.test.ts deleted file mode 100644 index 032c9411a5e..00000000000 --- a/src/main/github/gh-utils.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn() -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - ghExecFileAsync: vi.fn() -})) - -import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' -import { - _getOwnerRepoCacheSize, - _resetOwnerRepoCache, - getOwnerRepo, - getOwnerRepoForRemote -} from './gh-utils' -import { __resetLocalGitConfigSignatureCacheForTests } from './local-git-config-signature' - -function gitRemoteGetUrlCalls(remoteName: string): unknown[][] { - return gitExecFileAsyncMock.mock.calls.filter( - ([args]) => - Array.isArray(args) && args[0] === 'remote' && args[1] === 'get-url' && args[2] === remoteName - ) -} - -describe('github owner/repo resolution', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - _resetOwnerRepoCache() - _resetRemoteNameListingCache() - __resetLocalGitConfigSignatureCacheForTests() - }) - - it('keeps local host and local WSL owner/repo cache entries separate for the same path', async () => { - gitExecFileAsyncMock.mockImplementation( - async (args: string[], options: { wslDistro?: string } = {}) => { - if (args[0] === 'remote' && args[1] !== 'get-url') { - return { stdout: 'origin\n' } - } - if (args[2] === 'upstream') { - throw new Error("fatal: No such remote 'upstream'") - } - return { - stdout: options.wslDistro - ? 'git@github.com:wsl/orca.git\n' - : 'git@github.com:host/orca.git\n' - } - } - ) - - await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'host', repo: 'orca' }) - await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({ - owner: 'wsl', - repo: 'orca' - }) - await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({ - owner: 'wsl', - repo: 'orca' - }) - - // 2 runtimes x (1 remote list + 1 origin hit); repeat WSL call is cached. - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(4) - expect(gitRemoteGetUrlCalls('upstream')).toHaveLength(0) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo', - timeout: 30_000 - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo', - timeout: 30_000, - wslDistro: 'Ubuntu' - }) - }) - - it('does not apply the long negative TTL when git remote get-url fails transiently', async () => { - const repoPath = await mkdtemp(join(tmpdir(), 'orca-gh-utils-')) - await mkdir(join(repoPath, '.git')) - await writeFile(join(repoPath, '.git', 'config'), '[core]\n\trepositoryformatversion = 0\n') - try { - gitExecFileAsyncMock - .mockRejectedValueOnce(new Error('fatal: cannot lock ref')) - .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) - - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toBeNull() - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toEqual({ - owner: 'acme', - repo: 'widgets' - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) - } finally { - await rm(repoPath, { recursive: true, force: true }) - } - }) - - it('invalidates a cached local missing remote when an included git config changes', async () => { - const repoPath = await mkdtemp(join(tmpdir(), 'orca-gh-utils-')) - await mkdir(join(repoPath, '.git')) - const includedConfigPath = join(repoPath, 'remote.inc') - await writeFile( - join(repoPath, '.git', 'config'), - `[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = ${includedConfigPath}\n` - ) - await writeFile(includedConfigPath, '') - vi.useFakeTimers() - try { - vi.setSystemTime(1_000) - gitExecFileAsyncMock - .mockRejectedValueOnce(new Error("error: No such remote 'origin'")) - .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) - - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toBeNull() - await writeFile( - includedConfigPath, - '[remote "origin"]\n\turl = git@github.com:acme/widgets.git\n' - ) - vi.setSystemTime(32_000) - - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toEqual({ - owner: 'acme', - repo: 'widgets' - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) - } finally { - vi.useRealTimers() - await rm(repoPath, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts deleted file mode 100644 index 25776bc0346..00000000000 --- a/src/main/github/gh-utils.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { execFile } from 'node:child_process' -import { promisify } from 'node:util' -import { gitExecFileAsync } from '../git/command-runner/git-exec-file' -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -// Import pure parsing outside runner so runner-mocked tests retain the real implementation. -import { - extractExecError, - parseRetryAfterMs -} from '../git/command-runner/process-capture/exec-error' - -// Repo-scoped operations need the WSL-aware runner; this legacy wrapper serves generic commands. -export const execFileAsync = promisify(execFile) -export { ghExecFileAsync, gitExecFileAsync, extractExecError, parseRetryAfterMs } -export { - classifyGhError, - classifyListIssuesError, - classifyListPrsError, - classifyPullRequestUpdateError -} from './gh-error-classification' -export { - _getOwnerRepoCacheSize, - _resetOwnerRepoCache, - getOwnerRepoForRemote, - getRemoteUrlForRepo, - ghRepoExecOptions, - githubRepoContext, - parseGitHubOwnerRepo, - parseGitHubRemoteIdentity -} from './github-repository-identity' -export type { - GitHubRemoteIdentity, - GitHubRemoteIdentityProbeOptions, - GitHubRepoContext, - LocalGitExecOptions, - OwnerRepo -} from './github-repository-identity' -export { - getIssueOwnerRepo, - getOwnerRepo, - resolveIssueSource, - resolvePRRepositoryCandidates -} from './github-owner-repo-selection' -export type { PRRepositoryCandidates, ResolvedIssueSource } from './github-owner-repo-selection' - -const MAX_CONCURRENT = 4 -let running = 0 -type QueueEntry = { - signal?: AbortSignal - start: () => void - reject: (error: Error) => void -} -const queue: QueueEntry[] = [] - -function githubOperationAbortError(): Error { - const error = new Error('GitHub operation aborted') - error.name = 'AbortError' - return error -} - -export function acquire(signal?: AbortSignal): Promise { - if (signal?.aborted) { - return Promise.reject(githubOperationAbortError()) - } - if (running < MAX_CONCURRENT) { - running += 1 - return Promise.resolve() - } - return new Promise((resolve, reject) => { - const entry: QueueEntry = { - signal, - reject, - start: () => { - signal?.removeEventListener('abort', onAbort) - running += 1 - resolve() - } - } - const onAbort = (): void => { - const index = queue.indexOf(entry) - if (index === -1) { - return - } - queue.splice(index, 1) - reject(githubOperationAbortError()) - } - signal?.addEventListener('abort', onAbort, { once: true }) - queue.push(entry) - }) -} - -export function release(): void { - running -= 1 - const next = queue.shift() - next?.start() -} diff --git a/src/main/github/github-api-repository-remote-probe.test.ts b/src/main/github/github-api-repository-remote-probe.test.ts deleted file mode 100644 index ecd8f8ab7a4..00000000000 --- a/src/main/github/github-api-repository-remote-probe.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn<(args: string[]) => Promise<{ stdout: string; stderr: string }>>() -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -import { _resetOwnerRepoCache } from './gh-utils' -import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' -import { - _resetOriginGitHubApiRepositoryCache, - getGitHubApiRepositoryForRemote -} from './github-api-repository-remote-probe' - -// Why: no real .git config means no config signature, so caches use their short unsigned TTLs. -const REPO_PATH = '/does-not-exist/orca-remote-probe-fixture' - -function mockRemotes(remotes: Record): void { - gitExecFileAsyncMock.mockImplementation((args) => { - if (args[0] === 'remote' && args.length === 1) { - return Promise.resolve({ stdout: Object.keys(remotes).join('\n'), stderr: '' }) - } - if (args[0] === 'remote' && args[1] === 'get-url') { - const url = remotes[args[2]] - if (url) { - return Promise.resolve({ stdout: `${url}\n`, stderr: '' }) - } - return Promise.reject( - Object.assign(new Error(`git remote get-url ${args[2]}`), { - stderr: `error: No such remote '${args[2]}'` - }) - ) - } - return Promise.reject(new Error(`unexpected git exec: ${JSON.stringify(args)}`)) - }) -} - -function getUrlCalls(remoteName: string): number { - return gitExecFileAsyncMock.mock.calls.filter( - ([args]) => args[0] === 'remote' && args[1] === 'get-url' && args[2] === remoteName - ).length -} - -beforeEach(() => { - vi.useFakeTimers() - gitExecFileAsyncMock.mockReset() - _resetOriginGitHubApiRepositoryCache() - _resetOwnerRepoCache() - _resetRemoteNameListingCache() -}) - -afterEach(() => { - vi.useRealTimers() -}) - -describe('getGitHubApiRepositoryForRemote', () => { - it('does not run get-url for a non-origin remote the listing says is absent', async () => { - mockRemotes({ origin: 'https://github.com/acme/widgets.git' }) - - for (let poll = 0; poll < 3; poll += 1) { - await expect(getGitHubApiRepositoryForRemote(REPO_PATH, 'upstream')).resolves.toBeNull() - await vi.advanceTimersByTimeAsync(60_000) - } - - expect(getUrlCalls('upstream')).toBe(0) - }) - - it('still resolves a configured upstream remote', async () => { - mockRemotes({ - origin: 'https://github.com/acme/orca.git', - upstream: 'https://github.com/stablyai/orca.git' - }) - - await expect(getGitHubApiRepositoryForRemote(REPO_PATH, 'upstream')).resolves.toEqual({ - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - }) - - it('probes origin even when the listing omits it', async () => { - mockRemotes({}) - - await expect(getGitHubApiRepositoryForRemote(REPO_PATH, 'origin')).resolves.toBeNull() - expect(getUrlCalls('origin')).toBeGreaterThan(0) - }) -}) diff --git a/src/main/github/github-api-repository.test.ts b/src/main/github/github-api-repository.test.ts deleted file mode 100644 index fb3da271755..00000000000 --- a/src/main/github/github-api-repository.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GitHubEnterpriseRepository from './github-enterprise-repository' -import type * as GhUtils from './gh-utils' - -const { - getEnterpriseGitHubRepoSlugMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - isGitHubHostAuthenticatedMock, - shouldProbeGitRemoteMock -} = vi.hoisted(() => ({ - getEnterpriseGitHubRepoSlugMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - isGitHubHostAuthenticatedMock: vi.fn(), - shouldProbeGitRemoteMock: vi.fn(async () => true) -})) - -vi.mock('./gh-utils', async (importOriginal) => ({ - ...(await importOriginal()), - getOwnerRepo: getOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock -})) - -vi.mock('./github-enterprise-repository', async (importOriginal) => ({ - ...(await importOriginal()), - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, - isGitHubHostAuthenticated: isGitHubHostAuthenticatedMock -})) - -vi.mock('../git/remotes/remote-name-listing', () => ({ - shouldProbeGitRemote: shouldProbeGitRemoteMock -})) -import { - _resetOriginGitHubApiRepositoryCache, - getGitHubApiRepositoryForRemote, - getOriginGitHubApiRepository, - resolveGitHubApiRepository, - resolveGitHubApiRepositoryCandidates, - resolveGitHubRepoExecution -} from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() - getEnterpriseGitHubRepoSlugMock.mockReset().mockResolvedValue(null) - getOwnerRepoMock.mockReset().mockResolvedValue(null) - getOwnerRepoForRemoteMock.mockReset().mockResolvedValue(null) - isGitHubHostAuthenticatedMock.mockReset().mockResolvedValue(false) - shouldProbeGitRemoteMock.mockReset().mockResolvedValue(true) -}) - -describe('resolveGitHubRepoExecution', () => { - it('rejects an explicit Enterprise host absent from the local gh auth inventory', async () => { - await expect( - resolveGitHubApiRepository( - '/remote/repo', - { - owner: 'acme', - repo: 'widgets', - host: 'evil.example.test' - }, - 'ssh-1' - ) - ).resolves.toBeNull() - - expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith( - 'evil.example.test', - '/remote/repo', - 'ssh-1', - {} - ) - }) - - it.each([ - { owner: 'acme%2Fadmin', repo: 'widgets' }, - { owner: 'acme', repo: '..' } - ])('rejects repository overrides that could alter a gh REST path: %o', async (repository) => { - await expect( - resolveGitHubApiRepository('/repo', { - ...repository, - host: 'github.com' - }) - ).resolves.toBeNull() - - expect(isGitHubHostAuthenticatedMock).not.toHaveBeenCalled() - }) - - it('rejects a host-less caller-specific resolver for a connection-backed repository', async () => { - await expect( - resolveGitHubRepoExecution( - '/remote/repo', - async () => ({ owner: 'upstream', repo: 'widgets' }), - 'ssh-1' - ) - ).resolves.toEqual({ ownerRepo: null, ghOptions: {} }) - }) - - it('preserves an authoritative null from a caller-specific resolver', async () => { - getOwnerRepoMock.mockResolvedValue({ owner: 'origin', repo: 'widgets' }) - - await expect(resolveGitHubRepoExecution('/repo', async () => null)).resolves.toEqual({ - ownerRepo: null, - ghOptions: { cwd: '/repo' } - }) - - expect(getOwnerRepoMock).not.toHaveBeenCalled() - }) -}) - -describe('origin repository cache', () => { - it('keeps an indeterminate auth inventory unverifiable during candidate discovery', async () => { - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(undefined) - - await expect( - getGitHubApiRepositoryForRemote( - '/remote/repo', - 'origin', - 'ssh-1', - {}, - { - requireVerifiedSshProbe: true - } - ) - ).rejects.toThrow('GitHub repository identity is unverifiable.') - }) - - it('does not reuse a tolerant SSH miss for verified candidate discovery', async () => { - const enterprise = { - owner: 'acme', - repo: 'widgets', - host: 'github.acme-corp.com' - } - getEnterpriseGitHubRepoSlugMock.mockResolvedValueOnce(null).mockResolvedValueOnce(enterprise) - - await expect(getOriginGitHubApiRepository('/remote/repo', 'ssh-1')).resolves.toBeNull() - await expect( - getGitHubApiRepositoryForRemote( - '/remote/repo', - 'origin', - 'ssh-1', - {}, - { - requireVerifiedSshProbe: true - } - ) - ).resolves.toEqual(enterprise) - expect(getEnterpriseGitHubRepoSlugMock).toHaveBeenCalledTimes(2) - }) -}) - -describe('skip missing upstream remote probes', () => { - it('observes and propagates a verified origin probe failure while listing remotes', async () => { - let releaseRemoteProbe: (value: boolean) => void = () => undefined - shouldProbeGitRemoteMock.mockReturnValue( - new Promise((resolve) => { - releaseRemoteProbe = resolve - }) - ) - const originError = new Error('origin probe failed') - getOwnerRepoForRemoteMock.mockImplementation(async (_path, remote) => { - if (remote === 'origin') { - throw originError - } - return { owner: 'stablyai', repo: 'orca' } - }) - - const resultPromise = resolveGitHubApiRepositoryCandidates('/repo') - await vi.waitFor(() => - expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith( - '/repo', - 'origin', - undefined, - {}, - { requireVerifiedSshProbe: true } - ) - ) - releaseRemoteProbe(true) - - await expect(resultPromise).rejects.toBe(originError) - }) -}) diff --git a/src/main/github/github-read-execution-scope.ts b/src/main/github/github-read-execution-scope.ts deleted file mode 100644 index 0731cf4ed48..00000000000 --- a/src/main/github/github-read-execution-scope.ts +++ /dev/null @@ -1 +0,0 @@ -export { codeHostReadExecutionScope as githubReadExecutionScope } from '../source-control/code-host-read-execution-scope' diff --git a/src/main/github/github-repository-identity.signed-cache.test.ts b/src/main/github/github-repository-identity.signed-cache.test.ts deleted file mode 100644 index 2cd8252f856..00000000000 --- a/src/main/github/github-repository-identity.signed-cache.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GitRunner from '../git/command-runner/git-exec-file' - -const { gitExecFileAsyncMock, readLocalGitConfigSignatureMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - readLocalGitConfigSignatureMock: vi.fn<() => Promise>(async () => 'sig-1') -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('./local-git-config-signature', () => ({ - readLocalGitConfigSignature: readLocalGitConfigSignatureMock -})) - -import { getOwnerRepoForRemote, _resetOwnerRepoCache } from './github-repository-identity' - -const REPO = '/tmp/signed-cache-repo' -const THIRTY_SECONDS = 30_000 -const FOUR_MINUTES = 4 * 60_000 - -let remoteUrl = 'https://github.com/stablyai/orca.git' - -const remoteGetUrlCalls = (): number => - gitExecFileAsyncMock.mock.calls.filter(([args]) => (args as string[])[1] === 'get-url').length - -beforeEach(() => { - _resetOwnerRepoCache() - vi.useRealTimers() - gitExecFileAsyncMock.mockReset() - remoteUrl = 'https://github.com/stablyai/orca.git' - readLocalGitConfigSignatureMock.mockReset() - readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-1') - gitExecFileAsyncMock.mockImplementation(async () => ({ stdout: remoteUrl })) -}) - -describe('owner/repo identity cache', () => { - it('holds a signed identity past the unsigned TTL instead of re-spawning git', async () => { - vi.useFakeTimers() - await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toEqual({ - owner: 'stablyai', - repo: 'orca' - }) - expect(remoteGetUrlCalls()).toBe(1) - - // Advance beyond unsigned TTL while remaining within the signed entry lifetime. - vi.setSystemTime(Date.now() + FOUR_MINUTES) - await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toEqual({ - owner: 'stablyai', - repo: 'orca' - }) - expect(remoteGetUrlCalls()).toBe(1) - vi.useRealTimers() - }) - - it('re-probes as soon as the git config signature changes', async () => { - vi.useFakeTimers() - await getOwnerRepoForRemote(REPO, 'origin') - expect(remoteGetUrlCalls()).toBe(1) - - remoteUrl = 'https://github.com/other-org/orca.git' - readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-2') - vi.setSystemTime(Date.now() + THIRTY_SECONDS) - - await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toEqual({ - owner: 'other-org', - repo: 'orca' - }) - expect(remoteGetUrlCalls()).toBe(2) - vi.useRealTimers() - }) - - it('keeps the short TTL when no signature can be read', async () => { - vi.useFakeTimers() - readLocalGitConfigSignatureMock.mockImplementation(async () => undefined) - await getOwnerRepoForRemote(REPO, 'origin') - expect(remoteGetUrlCalls()).toBe(1) - - vi.setSystemTime(Date.now() + THIRTY_SECONDS + 1) - await getOwnerRepoForRemote(REPO, 'origin') - expect(remoteGetUrlCalls()).toBe(2) - vi.useRealTimers() - }) - - it('still coalesces concurrent lookups onto one probe', async () => { - const [first, second] = await Promise.all([ - getOwnerRepoForRemote(REPO, 'origin'), - getOwnerRepoForRemote(REPO, 'origin') - ]) - expect(first).toEqual({ owner: 'stablyai', repo: 'orca' }) - expect(second).toEqual(first) - expect(remoteGetUrlCalls()).toBe(1) - }) -}) diff --git a/src/main/github/issue-comment.ts b/src/main/github/issue-comment.ts deleted file mode 100644 index 7f3c2a11f98..00000000000 --- a/src/main/github/issue-comment.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' -import type { GitHubCommentResult, PRComment } from '../../shared/github/comment-types' -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { LocalGitExecOptions, OwnerRepo } from './gh-utils' -import { - resolveGitHubRepoExecution, - resolveIssueGitHubApiRepositorySource -} from './github-api-repository' -import { acquire, classifyGhError, ghExecFileAsync, release } from './gh-utils' -import { codeHostFailure, classifiedFailure } from '../../shared/code-host-failure-copy' - -// An explicit target keeps replies bound to the conversation; otherwise use the selected source. -export async function addIssueComment( - repoPath: string, - issueNumber: number, - body: string, - connectionId?: string | null, - ownerRepoOverride?: OwnerRepo | null, - localGitOptions: LocalGitExecOptions = {}, - preference?: IssueSourcePreference -): Promise { - const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( - repoPath, - ownerRepoOverride ?? - (async () => - ( - await resolveIssueGitHubApiRepositorySource( - repoPath, - preference, - connectionId, - localGitOptions - ) - ).source), - connectionId, - localGitOptions - ) - if (!ownerRepo) { - return codeHostFailure('github.repoUnresolved') - } - await acquire() - try { - const { stdout } = await ghExecFileAsync( - [ - 'api', - ...githubBodyMediaHeaders(body), - '-X', - 'POST', - `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`, - '--input', - '-' - ], - { ...ghOptions, stdin: JSON.stringify({ body }) } - ) - const data: { - id?: number - node_id?: string | null - user: { login: string; avatar_url: string; type?: string } | null - body?: string - body_html?: string | null - created_at?: string - html_url?: string - } = JSON.parse(stdout) - if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) { - return codeHostFailure('github.unexpectedResponse') - } - const comment: PRComment = { - id: data.id, - reactionSubjectId: data.node_id?.trim() || undefined, - author: data.user?.login ?? 'You', - authorAvatarUrl: data.user?.avatar_url ?? '', - body: data.body ?? body, - bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html), - createdAt: data.created_at ?? new Date().toISOString(), - url: data.html_url ?? '', - isBot: data.user?.type === 'Bot' - } - return { ok: true, comment } - } catch (err) { - const stderr = err instanceof Error ? err.message : String(err) - return classifiedFailure(classifyGhError(stderr)) - } finally { - release() - } -} diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts deleted file mode 100644 index 3beaf260cd7..00000000000 --- a/src/main/github/issues.test.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GithubEnterpriseRepositoryModule from './github-enterprise-repository' -import type * as GhUtils from './gh-utils' - -const { - ghExecFileAsyncMock, - getIssueOwnerRepoMock, - resolveIssueSourceMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getIssueOwnerRepoMock: vi.fn(), - resolveIssueSourceMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', async () => { - const actual = await vi.importActual('./gh-utils') - return { - ...actual, - ghExecFileAsync: ghExecFileAsyncMock, - getIssueOwnerRepo: getIssueOwnerRepoMock, - resolveIssueSource: resolveIssueSourceMock, - acquire: acquireMock, - release: releaseMock - } -}) - -vi.mock('./github-enterprise-repository', async (importOriginal) => ({ - ...(await importOriginal()), - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('./github-api-repository', async (importOriginal) => { - const actual = await importOriginal() - const withDotComHost = (repo: T) => - repo ? { host: 'github.com' as const, ...repo } : repo - return { - ...actual, - // Bridge hosted source resolution to the suite fixtures and retain explicit github.com host pinning. - getIssueGitHubApiRepository: async ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => withDotComHost(await getIssueOwnerRepoMock(repoPath, connectionId, localGitOptions)), - resolveIssueGitHubApiRepositorySource: async ( - repoPath: string, - preference: unknown, - connectionId?: string | null, - localGitOptions?: unknown - ) => { - const result = await resolveIssueSourceMock( - repoPath, - preference, - connectionId, - localGitOptions - ) - return { - ...result, - source: withDotComHost(result?.source) - } - } - } -}) -import { createIssue } from './issue-create' -import { updateIssue } from './issue-update' - -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() -}) - -describe('issue source operations', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getIssueOwnerRepoMock.mockReset() - resolveIssueSourceMock.mockReset() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - // Share the preference-aware resolver with the issue-owner fixtures. - resolveIssueSourceMock.mockImplementation(async () => ({ - source: await getIssueOwnerRepoMock(), - fellBack: false - })) - }) - - it.each(['stderr', 'stdout'])('recovers a long issue body reported on %s', async (stream) => { - const imagePrefix = 'data:image/png;base64,' - const body = imagePrefix + 'x'.repeat(133596 - imagePrefix.length) - expect(body).toContain('data:image') - expect(body).toHaveLength(133596) - - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock - .mockRejectedValueOnce( - Object.assign(new Error('gh failed'), { - stderr: 'gh: Validation Failed (HTTP 422)', - [stream]: 'body is too long (maximum is 65536 characters)' - }) - ) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 926, - html_url: 'https://github.com/stablyai/orca/issues/926' - }) - }) - .mockResolvedValueOnce({ stdout: '' }) - - await expect( - createIssue('/repo-root', 'Image issue', body, undefined, undefined, { - labels: ['bug'], - assignees: ['octo'] - }) - ).resolves.toEqual({ - ok: true, - number: 926, - url: 'https://github.com/stablyai/orca/issues/926' - }) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 1, - ['api', '-X', 'POST', 'repos/stablyai/orca/issues', '--input', '-'], - { - cwd: '/repo-root', - host: 'github.com', - stdin: JSON.stringify({ - title: 'Image issue', - body, - labels: ['bug'], - assignees: ['octo'] - }) - } - ) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 2, - ['api', '-X', 'POST', 'repos/stablyai/orca/issues', '--input', '-'], - { - cwd: '/repo-root', - host: 'github.com', - stdin: JSON.stringify({ - title: 'Image issue', - body: '', - labels: ['bug'], - assignees: ['octo'] - }) - } - ) - expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( - 3, - ['api', '-X', 'PATCH', 'repos/stablyai/orca/issues/926', '--input', '-'], - { cwd: '/repo-root', host: 'github.com', stdin: JSON.stringify({ body }) } - ) - }) - - it('does not retry unrelated create failures', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 422: assignees is invalid')) - - await expect(createIssue('/repo-root', 'Invalid issue', 'Body')).resolves.toEqual({ - ok: false, - error: 'HTTP 422: assignees is invalid' - }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) - - it('stops when placeholder create fails during oversized-body recovery', async () => { - const body = `data:image/png;base64,${'x'.repeat(100)}` - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock - .mockRejectedValueOnce(new Error('body is too long (maximum is 65536 characters)')) - .mockRejectedValueOnce(new Error('HTTP 500: create failed')) - - await expect(createIssue('/repo-root', 'Placeholder failure', body)).resolves.toEqual({ - ok: false, - error: 'HTTP 500: create failed' - }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) - - it('reports partial success when oversized-body patch fails', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock - .mockRejectedValueOnce(new Error('body is too long (maximum is 65536 characters)')) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 928, - html_url: 'https://github.com/stablyai/orca/issues/928' - }) - }) - .mockRejectedValueOnce(new Error('HTTP 500: update failed')) - - await expect(createIssue('/repo-root', 'Partial issue', 'data:image')).resolves.toEqual({ - ok: true, - number: 928, - url: 'https://github.com/stablyai/orca/issues/928', - bodySaveWarning: - 'Issue https://github.com/stablyai/orca/issues/928 was created, but saving its body failed: HTTP 500: update failed' - }) - }) - - it('sends large issue bodies over stdin through the REST issue endpoint', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) - const body = `Screenshot:\ndata:image/png;base64,${'A'.repeat(40_000)}` - - await expect(updateIssue('/repo-root', 924, { body })).resolves.toEqual({ - ok: true - }) - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['api', '-X', 'PATCH', 'repos/stablyai/orca/issues/924', '--input', '-'], - { cwd: '/repo-root', host: 'github.com', stdin: JSON.stringify({ body }) } - ) - }) - - it('keeps the accepted issue body representation through a compound metadata edit', async () => { - const body = - '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - body, - body_html: - '' - }) - }) - .mockResolvedValueOnce({ stdout: '' }) - await expect(updateIssue('/repo-root', 924, { body, title: 'Updated' })).resolves.toEqual({ - ok: true, - bodyImageUrls: { - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - } - }) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( - 'Accept: application/vnd.github.full+json' - ) - expect(ghExecFileAsyncMock.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) - }) - - it.each([ - '', - 'not JSON', - JSON.stringify({ - body: 'different ![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)', - body_html: - '' - }) - ])( - 'keeps an accepted issue edit successful without a usable paired response (%s)', - async (stdout) => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout }) - await expect( - updateIssue('/repo-root', 924, { - body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - }) - ).resolves.toEqual({ - ok: true, - bodyImageUrls: undefined - }) - } - ) - - it('reports a failed close whose gh error mentions "already"', async () => { - getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockRejectedValueOnce( - new Error('GraphQL: API rate limit already exceeded for user ID 1.') - ) - - await expect(updateIssue('/repo-root', 924, { state: 'closed' })).resolves.toMatchObject({ - ok: false, - error: 'GitHub rate limit hit. Try again in a few minutes.' - }) - }) -}) diff --git a/src/main/github/issues/issue-comment.ts b/src/main/github/issues/issue-comment.ts new file mode 100644 index 00000000000..4e3fa1d9a2b --- /dev/null +++ b/src/main/github/issues/issue-comment.ts @@ -0,0 +1,87 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls' +import type { GitHubCommentResult, PRComment } from '../../../shared/github/comments/comment-types' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../shared/github/repositories/repository-identity' +import { + resolveGitHubRepoExecution, + resolveIssueGitHubApiRepositorySource +} from '../repositories/github-api-repository' +import { acquire, release } from '../execution/github-operation-slots' +import { classifyGhError } from '../api/gh-error-classification' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { codeHostFailure, classifiedFailure } from '../../../shared/code-host-failure-copy' + +// An explicit target keeps replies bound to the conversation; otherwise use the selected source. +export async function addIssueComment( + repoPath: string, + issueNumber: number, + body: string, + connectionId?: string | null, + ownerRepoOverride?: OwnerRepo | null, + localGitOptions: LocalGitExecOptions = {}, + preference?: IssueSourcePreference +): Promise { + const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( + repoPath, + ownerRepoOverride ?? + (async () => + ( + await resolveIssueGitHubApiRepositorySource( + repoPath, + preference, + connectionId, + localGitOptions + ) + ).source), + connectionId, + localGitOptions + ) + if (!ownerRepo) { + return codeHostFailure('github.repoUnresolved') + } + await acquire() + try { + const { stdout } = await ghExecFileAsync( + [ + 'api', + ...githubBodyMediaHeaders(body), + '-X', + 'POST', + `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`, + '--input', + '-' + ], + { ...ghOptions, stdin: JSON.stringify({ body }) } + ) + const data: { + id?: number + node_id?: string | null + user: { login: string; avatar_url: string; type?: string } | null + body?: string + body_html?: string | null + created_at?: string + html_url?: string + } = JSON.parse(stdout) + if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) { + return codeHostFailure('github.unexpectedResponse') + } + const comment: PRComment = { + id: data.id, + reactionSubjectId: data.node_id?.trim() || undefined, + author: data.user?.login ?? 'You', + authorAvatarUrl: data.user?.avatar_url ?? '', + body: data.body ?? body, + bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html), + createdAt: data.created_at ?? new Date().toISOString(), + url: data.html_url ?? '', + isBot: data.user?.type === 'Bot' + } + return { ok: true, comment } + } catch (err) { + const stderr = err instanceof Error ? err.message : String(err) + return classifiedFailure(classifyGhError(stderr)) + } finally { + release() + } +} diff --git a/src/main/github/issue-create.ts b/src/main/github/issues/issue-create.ts similarity index 86% rename from src/main/github/issue-create.ts rename to src/main/github/issues/issue-create.ts index 54f5bb74ac3..0efb38f3704 100644 --- a/src/main/github/issue-create.ts +++ b/src/main/github/issues/issue-create.ts @@ -1,15 +1,17 @@ import type { GitHubCreateIssueFields, GitHubCreateIssueResult -} from '../../shared/issue-mutation-types' -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { LocalGitExecOptions } from './gh-utils' +} from '../../../shared/issue-mutation-types' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' import { resolveGitHubRepoExecution, resolveIssueGitHubApiRepositorySource -} from './github-api-repository' -import { acquire, extractExecError, ghExecFileAsync, release } from './gh-utils' -import { codeHostFailure } from '../../shared/code-host-failure-copy' +} from '../repositories/github-api-repository' +import { acquire, release } from '../execution/github-operation-slots' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { codeHostFailure } from '../../../shared/code-host-failure-copy' function githubIssueErrorMessage(error: unknown): string { const { stderr, stdout } = extractExecError(error) diff --git a/src/main/github/issue-details-query.ts b/src/main/github/issues/issue-details-query.ts similarity index 96% rename from src/main/github/issue-details-query.ts rename to src/main/github/issues/issue-details-query.ts index 5d6921884f0..c63c42c5c3c 100644 --- a/src/main/github/issue-details-query.ts +++ b/src/main/github/issues/issue-details-query.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import type { GitHubAssignableUser } from '../../shared/github/pull-request-types' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $includeItem: Boolean!) { repository(owner: $owner, name: $repo) { diff --git a/src/main/github/issue-field-options.ts b/src/main/github/issues/issue-field-options.ts similarity index 81% rename from src/main/github/issue-field-options.ts rename to src/main/github/issues/issue-field-options.ts index 8e54a8a2759..5e5c362c14b 100644 --- a/src/main/github/issue-field-options.ts +++ b/src/main/github/issues/issue-field-options.ts @@ -1,12 +1,14 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' -import type { GitHubAssignableUser, GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { LocalGitExecOptions } from './gh-utils' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' import { resolveGitHubRepoExecution, resolveIssueGitHubApiRepositorySource -} from './github-api-repository' -import { acquire, ghExecFileAsync, release } from './gh-utils' +} from '../repositories/github-api-repository' +import { acquire, release } from '../execution/github-operation-slots' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' export async function listLabels( repoPath: string, diff --git a/src/main/github/issue-timeline.ts b/src/main/github/issues/issue-timeline.ts similarity index 92% rename from src/main/github/issue-timeline.ts rename to src/main/github/issues/issue-timeline.ts index 09e577fdcc2..42214855a51 100644 --- a/src/main/github/issue-timeline.ts +++ b/src/main/github/issues/issue-timeline.ts @@ -1,11 +1,12 @@ import type { GitHubIssueTimelineItem, GitHubIssueTimelineTarget -} from '../../shared/github/comment-types' -import { ghExecFileAsync } from './gh-utils' -import type { GitHubApiRepository, GitHubRepoExecOptions } from './github-api-repository' -import { githubHostExecOptions } from './github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' +} from '../../../shared/github/comments/comment-types' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../repositories/github-api-repository' +import { githubHostExecOptions } from '../repositories/github-repository-host' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit' const MAX_ISSUE_TIMELINE_ITEMS = 300 const GITHUB_REST_PAGE_SIZE = 100 diff --git a/src/main/github/issue-update.ts b/src/main/github/issues/issue-update.ts similarity index 82% rename from src/main/github/issue-update.ts rename to src/main/github/issues/issue-update.ts index 4a5fbe0bb63..7f5deb97994 100644 --- a/src/main/github/issue-update.ts +++ b/src/main/github/issues/issue-update.ts @@ -1,15 +1,17 @@ -import type { GitHubIssueUpdate } from '../../shared/issue-mutation-types' -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { LocalGitExecOptions } from './gh-utils' +import type { GitHubIssueUpdate } from '../../../shared/issue-mutation-types' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' import { resolveGitHubRepoExecution, - resolveIssueGitHubApiRepositorySource, - type GitHubApiRepository -} from './github-api-repository' -import { acquire, classifyGhError, ghExecFileAsync, release } from './gh-utils' -import { codeHostFailure, combinedClassifiedFailure } from '../../shared/code-host-failure-copy' -import type { ClassifiedError } from '../../shared/classified-error' -import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' + resolveIssueGitHubApiRepositorySource +} from '../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import { acquire, release } from '../execution/github-operation-slots' +import { classifyGhError } from '../api/gh-error-classification' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { codeHostFailure, combinedClassifiedFailure } from '../../../shared/code-host-failure-copy' +import type { ClassifiedError } from '../../../shared/classified-error' +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls' export async function updateIssue( repoPath: string, diff --git a/src/main/github/issue-work-item-details-fresh.test.ts b/src/main/github/issues/issue-work-item-details-fresh.test.ts similarity index 89% rename from src/main/github/issue-work-item-details-fresh.test.ts rename to src/main/github/issues/issue-work-item-details-fresh.test.ts index 8d735c87693..6a66462e75d 100644 --- a/src/main/github/issue-work-item-details-fresh.test.ts +++ b/src/main/github/issues/issue-work-item-details-fresh.test.ts @@ -1,11 +1,16 @@ +import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: mocks.exec, +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: mocks.exec +})) + +vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), ghRepoExecOptions: () => ({}), githubRepoContext: () => ({}) })) -vi.mock('./rate-limit', () => ({ +vi.mock('../api/rate-limit', () => ({ repositoryRateLimitGuard: mocks.guard, noteRepositoryRateLimitSpend: vi.fn() })) @@ -66,33 +71,7 @@ describe('explicit task refresh conversation reads', () => { ['me', true] ]) }) - it.each(['body', 'comments', 'timeline'] as const)( - 'fails the whole explicit read if required %s fails', - async (field) => { - mocks.exec.mockImplementation(async (args: string[]) => { - const route = args.find((arg) => arg.startsWith('repos/')) ?? '' - const actual = route.includes('/comments?') - ? 'comments' - : route.includes('/timeline?') - ? 'timeline' - : 'body' - if (actual === field) { - throw new Error('request failed') - } - return { - stdout: - actual === 'body' - ? JSON.stringify({ body: 'current' }) - : actual === 'comments' - ? '[]' - : '' - } - }) - await expect( - getIssueBodyAndComments('/repo', 42, repository, null, {}, true) - ).rejects.toThrow('request failed') - } - ) + it('retains ordinary fallback behavior but does not report an explicit rate-limited read as success', async () => { mocks.guard.mockReturnValue({ blocked: true }) expect(await getIssueBodyAndComments('/repo', 42, repository)).toEqual({ diff --git a/src/main/github/issue-work-item-details.ts b/src/main/github/issues/issue-work-item-details.ts similarity index 89% rename from src/main/github/issue-work-item-details.ts rename to src/main/github/issues/issue-work-item-details.ts index 677c628d562..8d843126e60 100644 --- a/src/main/github/issue-work-item-details.ts +++ b/src/main/github/issues/issue-work-item-details.ts @@ -2,30 +2,34 @@ import { GITHUB_BODY_MEDIA_TYPE, githubBodyImageUrls, removeFailedGitHubBodyHtml -} from './body-image-urls' -import { extractExecError } from '../git/command-runner/process-capture/exec-error' -import type { GitHubIssueTimelineItem, PRComment } from '../../shared/github/comment-types' -import type { GitHubAssignableUser } from '../../shared/github/pull-request-types' +} from '../attachments/body-image-urls' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import type { + GitHubIssueTimelineItem, + PRComment +} from '../../../shared/github/comments/comment-types' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' import { ISSUE_DETAILS_QUERY, issueItemSchema, type GraphQLIssueDetailsResponse } from './issue-details-query' -import { mapIssueWorkItem } from './client/map/work-item' -import { restIssueActor } from './client/map/issue-actor' -import type { MainWorkItem } from './client/map/work-item-field-coercion' +import { mapIssueWorkItem } from '../client/map/work-item' +import { restIssueActor } from '../client/map/issue-actor' +import type { MainWorkItem } from '../client/map/work-item-field-coercion' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' import { - ghExecFileAsync, ghRepoExecOptions, githubRepoContext, type LocalGitExecOptions -} from './gh-utils' +} from '../repositories/github-repository-identity' -import { githubHostExecOptions, type GitHubApiRepository } from './github-api-repository' +import { githubHostExecOptions } from '../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' import { getIssueTimelineItems } from './issue-timeline' -import { readViewerLogin } from './client/fetch/authenticated-viewer' -import { viewerAuthorship } from '../source-control/comment-viewer-authorship' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' +import { readViewerLogin } from '../client/fetch/authenticated-viewer' +import { viewerAuthorship } from '../../source-control/comment-viewer-authorship' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit' export type CollapsedIssueDetails = { item?: MainWorkItem diff --git a/src/main/github/issues/issues.test.ts b/src/main/github/issues/issues.test.ts new file mode 100644 index 00000000000..ecb17adb769 --- /dev/null +++ b/src/main/github/issues/issues.test.ts @@ -0,0 +1,195 @@ +import type * as GhExecFileModule from '../../git/command-runner/hosted-cli/gh-exec-file' +import type * as GithubOwnerRepoSelectionModule from '../repositories/github-owner-repo-selection' +import type * as GithubOperationSlotsModule from '../execution/github-operation-slots' +import type * as GithubEnterpriseRepositoryModule from '../repositories/github-enterprise-repository' +import type * as GithubApiRepositoryModule from '../repositories/github-api-repository' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + ghExecFileAsyncMock, + getIssueOwnerRepoMock, + resolveIssueSourceMock, + acquireMock, + releaseMock +} = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn(), + getIssueOwnerRepoMock: vi.fn(), + resolveIssueSourceMock: vi.fn(), + acquireMock: vi.fn(), + releaseMock: vi.fn() +})) + +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async () => { + const actual = await vi.importActual( + '../../git/command-runner/hosted-cli/gh-exec-file' + ) + return { + ...actual, + ghExecFileAsync: ghExecFileAsyncMock + } +}) + +vi.mock('../repositories/github-owner-repo-selection', async () => { + const actual = await vi.importActual( + '../repositories/github-owner-repo-selection' + ) + return { + ...actual, + getOwnerRepo: getIssueOwnerRepoMock, + resolveIssueSource: resolveIssueSourceMock + } +}) + +vi.mock('../execution/github-operation-slots', async () => { + const actual = await vi.importActual( + '../execution/github-operation-slots' + ) + return { + ...actual, + acquire: acquireMock, + release: releaseMock + } +}) + +vi.mock('../repositories/github-enterprise-repository', async (importOriginal) => ({ + ...(await importOriginal()), + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) +})) + +vi.mock('../repositories/github-api-repository', async (importOriginal) => { + const actual = await importOriginal() + const withDotComHost = (repo: T) => + repo ? { host: 'github.com' as const, ...repo } : repo + return { + ...actual, + getIssueGitHubApiRepository: async ( + repoPath: string, + connectionId?: string | null, + localGitOptions?: unknown + ) => withDotComHost(await getIssueOwnerRepoMock(repoPath, connectionId, localGitOptions)), + resolveIssueGitHubApiRepositorySource: async ( + repoPath: string, + preference: unknown, + connectionId?: string | null, + localGitOptions?: unknown + ) => { + const result = await resolveIssueSourceMock( + repoPath, + preference, + connectionId, + localGitOptions + ) + return { + ...result, + source: withDotComHost(result?.source) + } + } + } +}) +import { createIssue } from './issue-create' +import { updateIssue } from './issue-update' + +import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe' + +beforeEach(() => { + _resetOriginGitHubApiRepositoryCache() +}) + +describe('issue source operations', () => { + beforeEach(() => { + ghExecFileAsyncMock.mockReset() + getIssueOwnerRepoMock.mockReset() + resolveIssueSourceMock.mockReset() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + // Share the preference-aware resolver with the issue-owner fixtures. + resolveIssueSourceMock.mockImplementation(async () => ({ + source: await getIssueOwnerRepoMock(), + fellBack: false + })) + }) + + it('reports partial success when oversized-body patch fails', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockRejectedValueOnce(new Error('body is too long (maximum is 65536 characters)')) + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 928, + html_url: 'https://github.com/stablyai/orca/issues/928' + }) + }) + .mockRejectedValueOnce(new Error('HTTP 500: update failed')) + + await expect(createIssue('/repo-root', 'Partial issue', 'data:image')).resolves.toEqual({ + ok: true, + number: 928, + url: 'https://github.com/stablyai/orca/issues/928', + bodySaveWarning: + 'Issue https://github.com/stablyai/orca/issues/928 was created, but saving its body failed: HTTP 500: update failed' + }) + }) + + it('keeps the accepted issue body representation through a compound metadata edit', async () => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + body, + body_html: + '' + }) + }) + .mockResolvedValueOnce({ stdout: '' }) + await expect(updateIssue('/repo-root', 924, { body, title: 'Updated' })).resolves.toEqual({ + ok: true, + bodyImageUrls: { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + } + }) + expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( + 'Accept: application/vnd.github.full+json' + ) + expect(ghExecFileAsyncMock.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) + }) + + it.each([ + '', + 'not JSON', + JSON.stringify({ + body: 'different ![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)', + body_html: + '' + }) + ])( + 'keeps an accepted issue edit successful without a usable paired response (%s)', + async (stdout) => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout }) + await expect( + updateIssue('/repo-root', 924, { + body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + }) + ).resolves.toEqual({ + ok: true, + bodyImageUrls: undefined + }) + } + ) + + it('reports a failed close whose gh error mentions "already"', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock.mockRejectedValueOnce( + new Error('GraphQL: API rate limit already exceeded for user ID 1.') + ) + + await expect(updateIssue('/repo-root', 924, { state: 'closed' })).resolves.toMatchObject({ + ok: false, + error: 'GitHub rate limit hit. Try again in a few minutes.' + }) + }) +}) diff --git a/src/main/github/issues.ts b/src/main/github/issues/issues.ts similarity index 85% rename from src/main/github/issues.ts rename to src/main/github/issues/issues.ts index 02c6ead5c5e..41e7c553450 100644 --- a/src/main/github/issues.ts +++ b/src/main/github/issues/issues.ts @@ -1,15 +1,17 @@ -import type { ClassifiedError } from '../../shared/classified-error' -import type { IssueInfo } from '../../shared/github/pull-request-types' -import type { IssueSourcePreference } from '../../shared/repo-types' -import { mapIssueInfo } from './mappers' -import type { LocalGitExecOptions } from './gh-utils' +import type { ClassifiedError } from '../../../shared/classified-error' +import type { IssueInfo } from '../../../shared/github/pull-requests/pull-request-types' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import { mapIssueInfo } from '../api/github-read-response' +import type { LocalGitExecOptions } from '../repositories/github-repository-identity' import { getIssueGitHubApiRepository, resolveGitHubRepoExecution, resolveIssueGitHubApiRepositorySource -} from './github-api-repository' +} from '../repositories/github-api-repository' // prettier-ignore -import { ghExecFileAsync, acquire, release, classifyListIssuesError } from './gh-utils' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../execution/github-operation-slots' +import { classifyListIssuesError } from '../api/gh-error-classification' // Keep successful-empty and failed listings distinguishable; fallback toasts belong to the Tasks envelope. export type IssueListResult = { diff --git a/src/main/github/mappers.ts b/src/main/github/mappers.ts deleted file mode 100644 index cbaecf02315..00000000000 --- a/src/main/github/mappers.ts +++ /dev/null @@ -1,144 +0,0 @@ -import type { PRCheckDetail } from '../../shared/github/check-types' -import type { CheckStatus, IssueInfo, PRInfo } from '../../shared/github/pull-request-types' -import { derivePRCheckStatusFromRollup } from '../../shared/source-control/checks/pr-check-status' - -// REST check runs separate status/conclusion; gh pr checks combines them into one state. - -export function mapCheckRunRESTStatus(status: string): PRCheckDetail['status'] { - const s = status?.toLowerCase() - if (s === 'queued') { - return 'queued' - } - if (s === 'in_progress') { - return 'in_progress' - } - return 'completed' -} - -const conclusionMap: Record = { - success: 'success', - failure: 'failure', - cancelled: 'cancelled', - timed_out: 'timed_out', - skipped: 'skipped', - neutral: 'neutral', - action_required: 'action_required', - stale: 'failure', - startup_failure: 'failure' -} - -export function mapCheckRunRESTConclusion( - status: string, - conclusion: string | null -): PRCheckDetail['conclusion'] { - if (status?.toLowerCase() !== 'completed') { - return 'pending' - } - if (!conclusion) { - return null - } - return conclusionMap[conclusion.toLowerCase()] ?? null -} - -// Legacy integrations report commit statuses instead of check runs. - -export function mapCommitStatusRESTStatus(state: string): PRCheckDetail['status'] { - const s = state?.toLowerCase() - return s === 'pending' ? 'queued' : 'completed' -} - -export function mapCommitStatusRESTConclusion(state: string): PRCheckDetail['conclusion'] { - const s = state?.toLowerCase() - if (s === 'success') { - return 'success' - } - if (s === 'failure' || s === 'error') { - return 'failure' - } - if (s === 'pending') { - return 'pending' - } - return null -} - -export function mapCheckStatus(state: string): PRCheckDetail['status'] { - const s = state?.toUpperCase() - if (s === 'PENDING' || s === 'QUEUED') { - return 'queued' - } - if (s === 'IN_PROGRESS') { - return 'in_progress' - } - return 'completed' -} - -export function mapCheckConclusion(state: string): PRCheckDetail['conclusion'] { - const s = state?.toUpperCase() - if (s === 'SUCCESS' || s === 'PASS') { - return 'success' - } - if (s === 'FAILURE' || s === 'FAIL') { - return 'failure' - } - if (s === 'ACTION_REQUIRED') { - return 'action_required' - } - if (s === 'STALE' || s === 'STARTUP_FAILURE') { - return 'failure' - } - if (s === 'CANCELLED') { - return 'cancelled' - } - if (s === 'TIMED_OUT') { - return 'timed_out' - } - if (s === 'SKIPPED') { - return 'skipped' - } - if (s === 'PENDING' || s === 'QUEUED' || s === 'IN_PROGRESS') { - return 'pending' - } - if (s === 'NEUTRAL') { - return 'neutral' - } - return null -} - -export function mapPRState(state: string, isDraft?: boolean): PRInfo['state'] { - const s = state?.toUpperCase() - if (s === 'MERGED') { - return 'merged' - } - if (s === 'CLOSED') { - return 'closed' - } - if (isDraft) { - return 'draft' - } - return 'open' -} - -// Accept REST html_url/lowercase state and gh url/mixed-case state. - -export function mapIssueInfo(data: { - number: number - title: string - state: string - url?: string - html_url?: string - labels?: { name: string }[] - body?: string | null -}): IssueInfo { - return { - number: data.number, - title: data.title, - state: data.state?.toLowerCase() === 'open' ? 'open' : 'closed', - url: data.html_url ?? data.url ?? '', - labels: (data.labels || []).map((l) => l.name), - ...(typeof data.body === 'string' ? { description: data.body } : {}) - } -} - -export function deriveCheckStatus(rollup: unknown[] | null | undefined): CheckStatus { - return derivePRCheckStatusFromRollup(rollup) -} diff --git a/src/main/github/pr-mutation-review-invalidation.ts b/src/main/github/pr-mutation-review-invalidation.ts deleted file mode 100644 index d1cde03cc86..00000000000 --- a/src/main/github/pr-mutation-review-invalidation.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { getRepoExecutionHostId } from '../../shared/execution-host' -import { invalidateHostedReviewBranchCache } from '../source-control/hosted-review-branch-cache' - -// A post-mutation refresh must not join an older lookup or reuse its cached answer. -export function invalidateReviewLookupsAfterPRMutation( - repoPath: string, - connectionId: string | null | undefined -): void { - invalidateHostedReviewBranchCache(repoPath, getRepoExecutionHostId({ connectionId })) -} diff --git a/src/main/github/pr-refresh-coordinator-completion-order.test.ts b/src/main/github/pr-refresh-coordinator-completion-order.test.ts deleted file mode 100644 index 2eea735fbe3..00000000000 --- a/src/main/github/pr-refresh-coordinator-completion-order.test.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' -import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe' -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -const { getPRForBranchOutcomeMock, getOriginGitHubApiRepositoryMock, sendMock } = coordinatorMocks - -function found(state: 'open' | 'closed' | 'merged'): PRRefreshOutcome { - return { kind: 'found', pr: makePR({ state, checksStatus: 'success' }), fetchedAt: Date.now() } -} - -describe('main refresh completion ordering', () => { - beforeEach(() => moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks)) - afterEach(() => vi.useRealTimers()) - - it.each([ - { older: 'open', newer: 'merged' }, - { older: 'closed', newer: 'open' } - ] as const)( - 'ignores expired coalesced $older reads after a newer $newer result', - async ({ older, newer }) => { - const reads: CoalescedProbes = new Map() - let finishOlder: (outcome: PRRefreshOutcome) => void = () => {} - const provider = vi.fn<() => Promise>() - provider - .mockImplementationOnce( - () => new Promise((resolve) => (finishOlder = resolve)) - ) - .mockImplementation(async () => found(newer)) - getPRForBranchOutcomeMock.mockImplementation(() => - runCoalescedProbe(reads, 'same-provider-lookup', provider, 120_000) - ) - const { - reportVisiblePRRefreshCandidates, - refreshPRNow, - addPRRefreshOutcomeObserver, - _getPRRefreshQueueSizeForTests - } = await import('./pr-refresh-coordinator') - const observer = vi.fn() - addPRRefreshOutcomeObserver(observer) - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(120_000) - await refreshPRNow(candidate) - expect(provider).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1_000) - finishOlder(found(older)) - await vi.advanceTimersByTimeAsync(0) - expect(observer).toHaveBeenCalledTimes(1) - expect(observer.mock.calls[0]?.[1]).toMatchObject({ pr: { state: newer } }) - expect(_getPRRefreshQueueSizeForTests()).toBe(newer === 'merged' ? 0 : 1) - await vi.advanceTimersByTimeAsync(59_000) - expect(provider).toHaveBeenCalledTimes(newer === 'merged' ? 2 : 3) - if (newer === 'merged') { - await vi.advanceTimersByTimeAsync(900_000) - expect(provider).toHaveBeenCalledTimes(2) - } - } - ) - - it.each(['network', 'rate_limited'] as const)( - 'ignores a late %s error after a newer settled result', - async (errorType) => { - let finishOlder: (outcome: PRRefreshOutcome) => void = () => {} - getPRForBranchOutcomeMock - .mockImplementationOnce( - () => new Promise((resolve) => (finishOlder = resolve)) - ) - .mockImplementation(async () => found('merged')) - const { - reportVisiblePRRefreshCandidates, - refreshPRNow, - _getPRRefreshErrorBackoffCountForTests, - _getPRRefreshQueueSizeForTests - } = await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - await refreshPRNow(candidate) - finishOlder({ - kind: 'upstream-error', - errorType, - message: 'old failure', - fetchedAt: Date.now(), - retryDisabledUntil: Date.now() + 300_000 - }) - await vi.advanceTimersByTimeAsync(0) - expect(_getPRRefreshErrorBackoffCountForTests()).toBe(0) - expect(_getPRRefreshQueueSizeForTests()).toBe(0) - await refreshPRNow(candidate) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) - } - ) - - it('fences older direct refresh completions without suppressing their caller result', async () => { - let finishOlder: (outcome: PRRefreshOutcome) => void = () => {} - getPRForBranchOutcomeMock - .mockImplementationOnce( - () => new Promise((resolve) => (finishOlder = resolve)) - ) - .mockImplementation(async () => found('merged')) - const { refreshPRNow, addPRRefreshOutcomeObserver } = await import('./pr-refresh-coordinator') - const observer = vi.fn() - addPRRefreshOutcomeObserver(observer) - const candidate = makeCandidate() - const older = refreshPRNow(candidate) - await vi.advanceTimersByTimeAsync(0) - await refreshPRNow(candidate) - finishOlder(found('closed')) - await expect(older).resolves.toMatchObject({ pr: { state: 'closed' } }) - expect(observer).toHaveBeenCalledTimes(1) - expect(sendMock.mock.calls.filter(([, event]) => event.outcome)).toHaveLength(2) - }) - - it('preserves a newer failure gate when an older successful lookup completes', async () => { - let finishOlder: (outcome: PRRefreshOutcome) => void = () => {} - getPRForBranchOutcomeMock - .mockImplementationOnce( - () => new Promise((resolve) => (finishOlder = resolve)) - ) - .mockImplementation(async () => ({ - kind: 'upstream-error', - errorType: 'rate_limited', - message: 'wait', - fetchedAt: Date.now(), - retryDisabledUntil: Date.now() + 300_000 - })) - const { reportVisiblePRRefreshCandidates, refreshPRNow } = - await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - await refreshPRNow(candidate) - finishOlder(found('open')) - await vi.advanceTimersByTimeAsync(60_000) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - await expect(refreshPRNow(candidate)).resolves.toMatchObject({ errorType: 'rate_limited' }) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - }) - - it('keeps a shared provider read coalesced while only the newest caller adopts it', async () => { - const reads: CoalescedProbes = new Map() - let finish: (outcome: PRRefreshOutcome) => void = () => {} - const provider = vi.fn(() => new Promise((resolve) => (finish = resolve))) - getPRForBranchOutcomeMock.mockImplementation(() => - runCoalescedProbe(reads, 'same-provider-lookup', provider, 120_000) - ) - const { reportVisiblePRRefreshCandidates, refreshPRNow, addPRRefreshOutcomeObserver } = - await import('./pr-refresh-coordinator') - const observer = vi.fn() - addPRRefreshOutcomeObserver(observer) - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - const manual = refreshPRNow(candidate) - await vi.advanceTimersByTimeAsync(0) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - expect(provider).toHaveBeenCalledTimes(1) - finish(found('merged')) - await manual - await vi.advanceTimersByTimeAsync(900_000) - expect(observer).toHaveBeenCalledTimes(1) - expect(provider).toHaveBeenCalledTimes(1) - }) - - it('does not start an older queued read when admission finishes after a newer direct read', async () => { - let finishAdmission: () => void = () => {} - getOriginGitHubApiRepositoryMock.mockImplementationOnce( - () => - new Promise((resolve) => { - finishAdmission = () => resolve(null) - }) - ) - getPRForBranchOutcomeMock.mockImplementation(async () => found('merged')) - const { reportVisiblePRRefreshCandidates, refreshPRNow } = - await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - await refreshPRNow(candidate) - finishAdmission() - await vi.advanceTimersByTimeAsync(900_000) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts b/src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts deleted file mode 100644 index d6a4dc88c29..00000000000 --- a/src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) - -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { getPRForBranchOutcomeMock } = coordinatorMocks - -describe('foreground refresh pacing', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'found', - pr: makePR({ checksStatus: 'success' }), - fetchedAt: Date.now() - })) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('limits five selected admissions to three starts until 30 seconds, including deselected queued rows', async () => { - const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = - await import('./pr-refresh-coordinator') - const cards = Array.from({ length: 5 }, (_, index) => - makeCandidate({ - cacheKey: `/repo::feature/${index}`, - branch: `feature/${index}`, - worktreeId: `wt-${index}`, - cachedPRState: 'open', - cachedChecksStatus: 'success', - cachedHasPR: true, - cachedFetchedAt: Date.now() - }) - ) - - for (let index = 0; index < cards.length; index += 1) { - const candidates = cards.map((card, cardIndex) => ({ - ...card, - cachedFetchedAt: cardIndex === index ? null : card.cachedFetchedAt, - isSelected: cardIndex === index - })) - reportVisiblePRRefreshCandidates(candidates, index + 1, 1) - enqueuePRRefresh(candidates[index], 'visible', 80, 1) - await vi.advanceTimersByTimeAsync(0) - } - - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) - await vi.advanceTimersByTimeAsync(29_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toEqual([ - 'feature/0', - 'feature/1', - 'feature/2', - 'feature/4', - 'feature/3' - ]) - }) - - it('uses the list budget for ordinary priority-80 periodic follow-ups', async () => { - const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = - await import('./pr-refresh-coordinator') - coordinatorMocks.getAllWebContentsMock.mockReturnValue( - Array.from({ length: 5 }, (_, index) => ({ id: index + 1, isDestroyed: () => false })) - ) - const candidates = Array.from({ length: 5 }, (_, index) => - makeCandidate({ - cacheKey: `/repo::feature/${index}`, - branch: `feature/${index}`, - worktreeId: `wt-${index}`, - isSelected: true - }) - ) - // Independent windows can expose different selected rows in the same runtime. - for (const [index, candidate] of candidates.entries()) { - reportVisiblePRRefreshCandidates([candidate], 1, index + 1) - enqueuePRRefresh(candidate, 'visible', 80, index + 1) - } - await vi.advanceTimersByTimeAsync(0) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5) - - await vi.advanceTimersByTimeAsync(60_000) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(6) - await vi.advanceTimersByTimeAsync(9_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(6) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(7) - }) - - it('keeps the explicit manual mergeability follow-up outside the foreground burst budget', async () => { - const { enqueuePRRefresh, refreshPRNow, reportVisiblePRRefreshCandidates } = - await import('./pr-refresh-coordinator') - for (let index = 0; index < 3; index += 1) { - enqueuePRRefresh( - makeCandidate({ branch: `active/${index}`, cacheKey: `/repo::active/${index}` }), - 'active', - 80, - 1 - ) - } - await vi.advanceTimersByTimeAsync(0) - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - getPRForBranchOutcomeMock.mockResolvedValue({ - kind: 'found', - pr: makePR({ mergeable: 'UNKNOWN' }), - fetchedAt: Date.now() - }) - await refreshPRNow(candidate) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4) - await vi.advanceTimersByTimeAsync(2_500) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5) - }) -}) diff --git a/src/main/github/pr-refresh-coordinator-refresh-events.test.ts b/src/main/github/pr-refresh-coordinator-refresh-events.test.ts deleted file mode 100644 index 175cc151a10..00000000000 --- a/src/main/github/pr-refresh-coordinator-refresh-events.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) - -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { sendMock, getPRForBranchOutcomeMock } = coordinatorMocks - -describe('pr-refresh-coordinator', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('ignores a stale visibility generation before it can replace queued work', async () => { - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - getPRForBranchOutcomeMock.mockResolvedValue({ kind: 'no-pr', fetchedAt: Date.now() }) - - reportVisiblePRRefreshCandidates( - [makeCandidate({ branch: 'feature/current', cacheKey: '/repo::feature/current' })], - 2, - 1 - ) - reportVisiblePRRefreshCandidates( - [makeCandidate({ branch: 'feature/stale', cacheKey: '/repo::feature/stale' })], - 1, - 1 - ) - await vi.advanceTimersByTimeAsync(0) - - expect(getPRForBranchOutcomeMock).toHaveBeenCalledOnce() - expect(getPRForBranchOutcomeMock.mock.calls[0]?.[1]).toBe('feature/current') - }) - - it('keeps each manual outcome on its request sequence when completions race', async () => { - const { refreshPRNow } = await import('./pr-refresh-coordinator') - let resolveFirst!: (outcome: ReturnType) => void - let resolveSecond!: (outcome: ReturnType) => void - const first = new Promise>((resolve) => { - resolveFirst = resolve - }) - const second = new Promise>((resolve) => { - resolveSecond = resolve - }) - getPRForBranchOutcomeMock - .mockImplementationOnce(async () => ({ - kind: 'found', - pr: await first, - fetchedAt: Date.now() - })) - .mockImplementationOnce(async () => ({ - kind: 'found', - pr: await second, - fetchedAt: Date.now() - })) - - const firstRefresh = refreshPRNow(makeCandidate()) - const secondRefresh = refreshPRNow(makeCandidate()) - await vi.advanceTimersByTimeAsync(0) - resolveSecond(makePR({ number: 22 })) - await secondRefresh - resolveFirst(makePR({ number: 11 })) - await firstRefresh - - const events = sendMock.mock.calls.map(([, event]) => event) - const inFlight = events.filter((event) => event.status === 'in-flight') - const outcomes = events.filter((event) => event.outcome) - const firstOutcome = outcomes.find((event) => event.outcome.pr?.number === 11) - const secondOutcome = outcomes.find((event) => event.outcome.pr?.number === 22) - expect(firstOutcome?.sequence).toBe(inFlight[0]?.sequence) - expect(secondOutcome?.sequence).toBe(inFlight[1]?.sequence) - expect(firstOutcome?.sequence).toBeLessThan(secondOutcome?.sequence) - }) -}) diff --git a/src/main/github/pr-refresh-coordinator-visibility-policy.test.ts b/src/main/github/pr-refresh-coordinator-visibility-policy.test.ts deleted file mode 100644 index b0ddb66b70e..00000000000 --- a/src/main/github/pr-refresh-coordinator-visibility-policy.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' -const { getPRForBranchOutcomeMock, sendMock } = coordinatorMocks -function found(state: 'open' | 'merged' = 'open'): PRRefreshOutcome { - return { kind: 'found', pr: makePR({ state, checksStatus: 'success' }), fetchedAt: Date.now() } -} - -describe('visibility-aware coordinator scheduling', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - getPRForBranchOutcomeMock.mockImplementation(async () => found()) - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('does not resurrect periodic work after every window hides during a lookup', async () => { - let resolve: (outcome: PRRefreshOutcome) => void = () => {} - getPRForBranchOutcomeMock.mockImplementationOnce( - () => - new Promise((done) => { - resolve = done - }) - ) - const { reportVisiblePRRefreshCandidates, _getPRRefreshQueueSizeForTests } = - await import('./pr-refresh-coordinator') - reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) - await vi.advanceTimersByTimeAsync(0) - reportVisiblePRRefreshCandidates([], 2, 1) - resolve(found()) - await vi.advanceTimersByTimeAsync(600_000) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - expect(_getPRRefreshQueueSizeForTests()).toBe(0) - }) - - it('retains stale PR state and error backoff across reports and hiding', async () => { - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'upstream-error', - errorType: 'network', - message: 'offline', - fetchedAt: Date.now() - })) - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ - cachedHasPR: true, - cachedPRState: 'open', - cachedHeadOid: 'old', - currentHeadOid: 'new' - }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - reportVisiblePRRefreshCandidates([], 2, 1) - reportVisiblePRRefreshCandidates([candidate], 3, 1) - reportVisiblePRRefreshCandidates([{ ...candidate, isSelected: true }], 4, 1) - await vi.advanceTimersByTimeAsync(119_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - reportVisiblePRRefreshCandidates([candidate], 5, 1) - await vi.advanceTimersByTimeAsync(119_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) - expect(sendMock.mock.calls.map(([, event]) => event.outcome?.kind).filter(Boolean)).toEqual([ - 'upstream-error', - 'upstream-error', - 'upstream-error' - ]) - }) - - it('keeps an in-flight head change behind the lookup failure backoff', async () => { - let resolve: (outcome: PRRefreshOutcome) => void = () => {} - getPRForBranchOutcomeMock.mockImplementationOnce( - () => - new Promise((done) => { - resolve = done - }) - ) - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ currentHeadOid: 'old' }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - reportVisiblePRRefreshCandidates([{ ...candidate, currentHeadOid: 'new' }], 2, 1) - resolve({ - kind: 'upstream-error', - errorType: 'network', - message: 'offline', - fetchedAt: Date.now() - }) - await vi.advanceTimersByTimeAsync(119_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - expect(getPRForBranchOutcomeMock.mock.calls[1][5]?.currentHeadOid).toBe('new') - }) - - it.each([true, false])( - 'preserves a rate-limit gate across selected reports (hidden=%s)', - async (hidden) => { - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'upstream-error', - errorType: 'rate_limited', - message: 'wait', - fetchedAt: Date.now(), - retryDisabledUntil: 301_000 - })) - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - const candidate = makeCandidate() - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - if (hidden) { - reportVisiblePRRefreshCandidates([], 2, 1) - } - await vi.advanceTimersByTimeAsync(10_000) - reportVisiblePRRefreshCandidates([{ ...candidate, isSelected: true }], 3, 1) - await vi.advanceTimersByTimeAsync(289_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - } - ) -}) diff --git a/src/main/github/pr-refresh-coordinator-visible-follow-up.test.ts b/src/main/github/pr-refresh-coordinator-visible-follow-up.test.ts deleted file mode 100644 index aafff0a7311..00000000000 --- a/src/main/github/pr-refresh-coordinator-visible-follow-up.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) - -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { getPRForBranchOutcomeMock } = coordinatorMocks - -describe('pr-refresh-coordinator', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('clears visible follow-ups when the owning window is destroyed', async () => { - const { - _getVisiblePRRefreshWindowCountForTests, - clearVisiblePRRefreshWindow, - reportVisiblePRRefreshCandidates - } = await import('./pr-refresh-coordinator') - getPRForBranchOutcomeMock.mockResolvedValue({ - kind: 'found', - pr: makePR({ checksStatus: 'pending', mergeable: 'MERGEABLE' }), - fetchedAt: Date.now() - }) - - reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) - await vi.runOnlyPendingTimersAsync() - - expect(_getVisiblePRRefreshWindowCountForTests()).toBe(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - - clearVisiblePRRefreshWindow(1) - await vi.advanceTimersByTimeAsync(90_000) - - expect(_getVisiblePRRefreshWindowCountForTests()).toBe(0) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - }) - - it('stops polling settled merged PRs, including repeated visibility reports', async () => { - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'found', - pr: makePR({ checksStatus: 'success', state: 'merged' }), - fetchedAt: Date.now() - })) - reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) - await vi.advanceTimersByTimeAsync(0) - const merged = makeCandidate({ - cachedFetchedAt: Date.now(), - cachedHasPR: true, - cachedPRState: 'merged', - cachedChecksStatus: 'success' - }) - await vi.advanceTimersByTimeAsync(31 * 60_000) - reportVisiblePRRefreshCandidates([merged], 2, 1) - await vi.advanceTimersByTimeAsync(0) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(24 * 60 * 60_000 - 31 * 60_000) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/github/pr-refresh-queue-growth-bound.test.ts b/src/main/github/pr-refresh-queue-growth-bound.test.ts deleted file mode 100644 index be7cd287da6..00000000000 --- a/src/main/github/pr-refresh-queue-growth-bound.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitHubPRRefreshCandidate } from '../../shared/github/pull-request-refresh-types' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) - -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { getPRForBranchOutcomeMock } = coordinatorMocks -const LINKED_PR_KEY = 'local::runtime:host::/repo::pr::42' - -describe('pr-refresh queue growth bounds', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'found' as const, - pr: makePR({ checksStatus: 'pending' as const }), - fetchedAt: Date.now() - })) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('keeps the newer alias when a branch switch lands mid-request', async () => { - const { reportVisiblePRRefreshCandidates, _getPRRefreshAliasCountForTests } = - await import('./pr-refresh-coordinator') - - const churnCandidate = (index: number): GitHubPRRefreshCandidate => - makeCandidate({ - cacheKey: `/repo::churn/${index}`, - branch: `churn/${index}`, - worktreeId: 'wt-churn', - linkedPRNumber: 42, - cachedFetchedAt: null - }) - - let switched = false - getPRForBranchOutcomeMock.mockImplementation(async () => { - if (!switched) { - switched = true - // Re-enqueue after dequeue so the older in-flight snapshot merges into a newer queued entry. - reportVisiblePRRefreshCandidates([churnCandidate(2)], 2, 1) - } - return { - kind: 'found' as const, - pr: makePR({ checksStatus: 'pending' as const }), - fetchedAt: Date.now() - } - }) - - reportVisiblePRRefreshCandidates([churnCandidate(1)], 1, 1) - await vi.advanceTimersByTimeAsync(120_000) - - expect(_getPRRefreshAliasCountForTests(LINKED_PR_KEY)).toBe(1) - const broadcasts = coordinatorMocks.sendMock.mock.calls.filter( - (call) => call[0] === 'gh:prRefreshEvent' - ) as [string, { aliases: { cacheKey: string }[] }][] - const lastBroadcast = broadcasts.at(-1) - expect(lastBroadcast?.[1].aliases.map((alias) => alias.cacheKey)).toEqual(['/repo::churn/2']) - }) - - it('does not restore an older candidate over a fresher branch switch', async () => { - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - const first = makeCandidate({ - cacheKey: '/repo::churn/1', - branch: 'churn/1', - worktreeId: 'wt-churn', - linkedPRNumber: 42, - cachedFetchedAt: null - }) - const switched = makeCandidate({ - cacheKey: '/repo::churn/2', - branch: 'churn/2', - worktreeId: 'wt-churn', - linkedPRNumber: 42, - cachedFetchedAt: Date.now(), - cachedHasPR: true, - cachedPRState: 'open', - cachedChecksStatus: 'success' - }) - - let didSwitch = false - getPRForBranchOutcomeMock.mockImplementation(async () => { - if (!didSwitch) { - didSwitch = true - reportVisiblePRRefreshCandidates([switched], 2, 1) - } - return { - kind: 'found' as const, - pr: makePR({ checksStatus: 'pending' as const }), - fetchedAt: Date.now() - } - }) - - reportVisiblePRRefreshCandidates([first], 1, 1) - await vi.advanceTimersByTimeAsync(119_999) - - expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toEqual(['churn/1']) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toEqual([ - 'churn/1', - 'churn/2' - ]) - }) -}) diff --git a/src/main/github/pr-refresh-rate-limit-gate.ts b/src/main/github/pr-refresh-rate-limit-gate.ts deleted file mode 100644 index 19cee2e215d..00000000000 --- a/src/main/github/pr-refresh-rate-limit-gate.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { GitHubPRRefreshCandidate } from '../../shared/github/pull-request-refresh-types' -import { getOriginGitHubApiRepository } from './github-api-repository' -import { ghRepoExecOptions, githubRepoContext } from './gh-utils' -import { getRateLimit, repositoryRateLimitGuard, spendsSharedGitHubComQuota } from './rate-limit' - -const BUCKETS = ['core', 'graphql'] as const - -export async function prRefreshRateLimitPausedUntil( - candidate: GitHubPRRefreshCandidate, - warmSharedSnapshot: boolean -): Promise { - const executionOptions = ghRepoExecOptions( - githubRepoContext(candidate.repoPath, candidate.connectionId, candidate.localGitOptions) - ) - const repository = await getOriginGitHubApiRepository( - candidate.repoPath, - candidate.connectionId, - executionOptions - ) - if (warmSharedSnapshot && spendsSharedGitHubComQuota(repository, executionOptions)) { - await getRateLimit() - } - const blockedGuard = BUCKETS.map((bucket) => - repositoryRateLimitGuard(repository, bucket, executionOptions) - ).find((guard) => guard.blocked) - return blockedGuard?.blocked ? blockedGuard.resetAt * 1000 : null -} diff --git a/src/main/github/pr-refresh-validation-backoff.test.ts b/src/main/github/pr-refresh-validation-backoff.test.ts deleted file mode 100644 index a67436916ac..00000000000 --- a/src/main/github/pr-refresh-validation-backoff.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { recordCoalescedCrashBreadcrumbMock } = vi.hoisted(() => ({ - recordCoalescedCrashBreadcrumbMock: vi.fn() -})) - -vi.mock('../crash-reporting/breadcrumbs/crash-breadcrumb-store', () => ({ - recordCoalescedCrashBreadcrumb: recordCoalescedCrashBreadcrumbMock -})) - -import { - clearPRRefreshValidationBackoffForTests, - notePRRefreshValidationDenial -} from './pr-refresh-validation-backoff' - -describe('PR refresh validation backoff', () => { - beforeEach(() => { - clearPRRefreshValidationBackoffForTests() - recordCoalescedCrashBreadcrumbMock.mockReset() - }) - - it('backs off repeated automatic validation denials until the TTL expires', () => { - const identity = { - repoId: 'repo-1', - repoPath: '/workspace/missing', - reason: 'unknown-repo' as const - } - - expect(notePRRefreshValidationDenial(identity, 0)).toBe('validation-denied') - expect(notePRRefreshValidationDenial(identity, 60_000)).toBe('validation-backoff') - expect(notePRRefreshValidationDenial(identity, 5 * 60_000 + 1)).toBe('validation-denied') - }) - - it('records path-safe diagnostic breadcrumbs', () => { - notePRRefreshValidationDenial( - { - repoId: 'repo-1', - repoPath: '/Users/alice/private/project', - reason: 'repo-path-mismatch' - }, - 0 - ) - - expect(recordCoalescedCrashBreadcrumbMock).toHaveBeenCalledWith( - expect.objectContaining({ - name: 'pr_refresh_validation_skip', - data: expect.objectContaining({ - reason: 'repo-path-mismatch', - result: 'recorded', - token: expect.any(String) - }) - }) - ) - const payload = recordCoalescedCrashBreadcrumbMock.mock.calls[0]?.[0] - expect(JSON.stringify(payload)).not.toContain('/Users/alice/private/project') - }) -}) diff --git a/src/main/github/pr-watch/pr-chat-action-recorder.test.ts b/src/main/github/pr-watch/pr-chat-action-recorder.test.ts index 7aefc97dac9..f01912a30d8 100644 --- a/src/main/github/pr-watch/pr-chat-action-recorder.test.ts +++ b/src/main/github/pr-watch/pr-chat-action-recorder.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { AgentJournalToolCallItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' import { finishedShellCall, pushedPullRequestHead, diff --git a/src/main/github/pr-watch/pr-chat-action-recorder.ts b/src/main/github/pr-watch/pr-chat-action-recorder.ts index 461d9d94838..b3308b66742 100644 --- a/src/main/github/pr-watch/pr-chat-action-recorder.ts +++ b/src/main/github/pr-watch/pr-chat-action-recorder.ts @@ -1,5 +1,5 @@ import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' import { pullRequestsOpenedBy } from '../../../shared/native-chat/tools/native-chat-opened-pull-requests' import { nativeChatToolCallScript } from '../../../shared/native-chat/tools/native-chat-tool-call-script' import { gitPushUpdates, runsGitPush, type GitPushUpdate } from './git-push-update-lines' diff --git a/src/main/github/pr-watch/pr-earlier-head-jobs.ts b/src/main/github/pr-watch/pr-earlier-head-jobs.ts index bde0fb46cd0..fd4980ebee9 100644 --- a/src/main/github/pr-watch/pr-earlier-head-jobs.ts +++ b/src/main/github/pr-watch/pr-earlier-head-jobs.ts @@ -1,8 +1,8 @@ import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-request-refresh-types' +import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { JournalHostDatabase } from '../../native-chat/agent-session-journal/database/journal-host-database' -import { schedulePRWatchRead } from '../pr-refresh-coordinator' -import { prWatchQueueKey, type PRWatchJob } from '../pr-refresh-watch-jobs' +import { schedulePRWatchRead } from '../pull-requests/refresh/pr-refresh-coordinator' +import { prWatchQueueKey, type PRWatchJob } from '../pull-requests/refresh/pr-refresh-watch-jobs' import { deletePRPendingHead, readPRPendingHeads } from './pr-check-event-tables' import { readPRHeadCheckRollup } from './pr-head-check-read' import { parsePRKey } from './pr-watch-types' diff --git a/src/main/github/pr-watch/pr-head-check-read.ts b/src/main/github/pr-watch/pr-head-check-read.ts index 823e65d9a0c..ed3ac8698b4 100644 --- a/src/main/github/pr-watch/pr-head-check-read.ts +++ b/src/main/github/pr-watch/pr-head-check-read.ts @@ -1,16 +1,17 @@ -import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-request-refresh-types' +import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { PR_CHECK_PAGE_LIMIT } from '../client/check/pr-check-rollup' import { readRestPRCheckRollup } from '../client/check/rest-pr-check-pages' import type { GhExecOptions } from '../client/github-exec-scope' import { assertRateLimitBudget } from '../client/lookup/pr-lookup-rate-limit' -import { ghExecFileAsync } from '../gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from '../github-api-repository' -import { noteRepositoryRateLimitSpend } from '../rate-limit' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { githubHostExecOptions } from '../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend } from '../api/rate-limit' import { ghRepoExecOptions, githubRepoContext, withGitHubRepoExecution -} from '../github-repository-identity' +} from '../repositories/github-repository-identity' type PRRepository = { host: string; owner: string; repo: string } diff --git a/src/main/github/pr-watch/pr-pending-action-resume.ts b/src/main/github/pr-watch/pr-pending-action-resume.ts index 9f3f9fd154b..4da326c3805 100644 --- a/src/main/github/pr-watch/pr-pending-action-resume.ts +++ b/src/main/github/pr-watch/pr-pending-action-resume.ts @@ -2,8 +2,8 @@ // ones fixed at capture; a restart resumes the same row and never renews them. Each obligation is // saved as decided on its own, so a sibling still resolving never holds back or loses it. -import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-request-refresh-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' +import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' import { pushedPullRequestHead, type PushRemote } from './pr-chat-action-recorder' import { PRPendingActionDrain } from './pr-pending-action-drain' import type { PRPendingActionResumeDeps, PRVerifiedAction } from './pr-pending-action-types' diff --git a/src/main/github/pr-watch/pr-pending-action-types.ts b/src/main/github/pr-watch/pr-pending-action-types.ts index f2d174565f3..9f1abeb1aff 100644 --- a/src/main/github/pr-watch/pr-pending-action-types.ts +++ b/src/main/github/pr-watch/pr-pending-action-types.ts @@ -1,5 +1,5 @@ import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-request-refresh-types' +import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { JournalHostDatabase } from '../../native-chat/agent-session-journal/database/journal-host-database' import type { PushRemote } from './pr-chat-action-recorder' import type { PRPendingActionRow, PRPendingObligation } from './pr-pending-actions' diff --git a/src/main/github/pr-watch/pr-push-remote-resolution.ts b/src/main/github/pr-watch/pr-push-remote-resolution.ts index 6299b290c16..654fdfdb2e4 100644 --- a/src/main/github/pr-watch/pr-push-remote-resolution.ts +++ b/src/main/github/pr-watch/pr-push-remote-resolution.ts @@ -1,4 +1,4 @@ -import { classifyGitHubOwnerRepoFromRemoteUrl } from '../github-ssh-host-alias-resolution' +import { classifyGitHubOwnerRepoFromRemoteUrl } from '../repositories/github-ssh-host-alias-resolution' import type { PushRemote } from './pr-chat-action-recorder' import type { PRPendingObligation } from './pr-pending-actions' import type { PRWatchWorkspace } from './pr-watch-types' diff --git a/src/main/github/pr-watch/pr-watch-service.test.ts b/src/main/github/pr-watch/pr-watch-service.test.ts index 355747d1573..ffe1b13ee17 100644 --- a/src/main/github/pr-watch/pr-watch-service.test.ts +++ b/src/main/github/pr-watch/pr-watch-service.test.ts @@ -7,13 +7,13 @@ import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/age import type { GitHubPRRefreshCandidate, PRRefreshOutcome -} from '../../../shared/github/pull-request-refresh-types' +} from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { createTrackedJournalOpener, openTestJournalHostDatabase } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { assemblePRRefreshFoundOutcome } from '../client/lookup/pr-refresh-outcome-assembly' -import type { PRWatchJob } from '../pr-refresh-watch-jobs' +import type { PRWatchJob } from '../pull-requests/refresh/pr-refresh-watch-jobs' import { readPRPendingDeliveryChatIds, readPRPendingHeads } from './pr-check-event-tables' import { readPRHeadCheckRollup } from './pr-head-check-read' import { capturePRPendingActions } from './pr-pending-actions' @@ -36,7 +36,7 @@ const queue = vi.hoisted(() => { return state }) -vi.mock('../pr-refresh-coordinator', () => ({ +vi.mock('../pull-requests/refresh/pr-refresh-coordinator', () => ({ addPRRefreshOutcomeObserver: (observer: QueueObserver) => { queue.observers.add(observer) return () => queue.observers.delete(observer) @@ -53,7 +53,7 @@ vi.mock('./pr-head-check-read', () => ({ resolvePRCommitSha: async () => null, isCommitInPRHead: async () => false })) -vi.mock('../github-api-repository', () => ({ +vi.mock('../repositories/github-api-repository', () => ({ resolveGitHubApiRepositoryCandidates: async () => ({ candidates: [{ owner: 'acme', repo: 'repo', host: 'github.com' }] }) diff --git a/src/main/github/pr-watch/pr-watch-service.ts b/src/main/github/pr-watch/pr-watch-service.ts index ba3f88fbc86..dfce5235d09 100644 --- a/src/main/github/pr-watch/pr-watch-service.ts +++ b/src/main/github/pr-watch/pr-watch-service.ts @@ -4,12 +4,12 @@ import type { GitHubPRRefreshCandidate, PRRefreshOutcome -} from '../../../shared/github/pull-request-refresh-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' +} from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' import { pullRequestKey } from '../../../shared/native-chat/native-chat-pull-request-event' import type { JournalRow } from '../../native-chat/agent-session-journal/durable-rows/journal-row-schema' import type { AgentSessionJournal } from '../../native-chat/agent-session-journal/journal-store' -import { resolveGitHubApiRepositoryCandidates } from '../github-api-repository' +import { resolveGitHubApiRepositoryCandidates } from '../repositories/github-api-repository' import { observedPRCheckRollup } from '../client/lookup/pr-refresh-outcome-assembly' import { addPRRefreshOutcomeObserver, @@ -17,8 +17,12 @@ import { enqueuePRRefresh, schedulePRWatchRead, setPRWatchJobHooks -} from '../pr-refresh-coordinator' -import { prChecksDone, prWatchNextDueAt, type PRWatchJob } from '../pr-refresh-watch-jobs' +} from '../pull-requests/refresh/pr-refresh-coordinator' +import { + prChecksDone, + prWatchNextDueAt, + type PRWatchJob +} from '../pull-requests/refresh/pr-refresh-watch-jobs' import { deletePRMovedHeads, endPRWatchState } from './pr-check-event-tables' import { PREarlierHeadJobs } from './pr-earlier-head-jobs' import { PREventDeliveryTrigger } from './pr-event-delivery' diff --git a/src/main/github/pr-watch/pr-watch-test-fixtures.ts b/src/main/github/pr-watch/pr-watch-test-fixtures.ts index 30d9bfb87b3..07c862dff02 100644 --- a/src/main/github/pr-watch/pr-watch-test-fixtures.ts +++ b/src/main/github/pr-watch/pr-watch-test-fixtures.ts @@ -1,5 +1,5 @@ import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' import type { JournalItemRow } from '../../native-chat/agent-session-journal/durable-rows/journal-row-schema' /** An open PR; the fields a watch reads come from `fields`. */ diff --git a/src/main/github/pr-watch/pr-watch-types.ts b/src/main/github/pr-watch/pr-watch-types.ts index 1a2ea58d77c..3ddc7b38623 100644 --- a/src/main/github/pr-watch/pr-watch-types.ts +++ b/src/main/github/pr-watch/pr-watch-types.ts @@ -1,6 +1,6 @@ import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-request-refresh-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' +import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' import { pullRequestKey } from '../../../shared/native-chat/native-chat-pull-request-event' import type { RepoKind } from '../../../shared/repo-types' import type { JournalHostDatabase } from '../../native-chat/agent-session-journal/database/journal-host-database' diff --git a/src/main/github/project-account-operations.test.ts b/src/main/github/project-account-operations.test.ts deleted file mode 100644 index b0901ecc271..00000000000 --- a/src/main/github/project-account-operations.test.ts +++ /dev/null @@ -1,429 +0,0 @@ -import type { createGitHubPullRequest } from './client/create/create-github-pull-request' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { createFakeSpawnedChild } from '../../shared/__fixtures__/fake-spawned-child' -import { - createStore, - closeTestStores, - testState, - makeRepo -} from '../persistence/persistence-test-harness' - -const { spawnMock, remote } = vi.hoisted(() => ({ spawnMock: vi.fn(), remote: vi.fn() })) -vi.mock('node:child_process', async (original) => ({ ...(await original()), spawn: spawnMock })) -vi.mock('./github-api-repository-remote-probe', () => ({ - getOriginGitHubApiRepository: remote, - getGitHubApiRepositoryForRemote: remote -})) -vi.mock('../git/remotes/remote-name-listing', () => ({ shouldProbeGitRemote: async () => false })) -vi.mock('./rate-limit', () => ({ - repositoryRateLimitGuard: () => ({ blocked: false }), - noteRepositoryRateLimitSpend: () => {}, - spendsSharedGitHubComQuota: () => false -})) -vi.mock('./client/list/work-item-search-page', () => ({ usesGraphqlWorkItemSearch: () => false })) -vi.mock('./client/lookup/pr-lookup-rate-limit', () => ({ assertRateLimitBudget: async () => {} })) - -vi.mock('../source-control/forge-provider-detection', () => ({ - detectHostedReviewProvider: async () => 'github', - getForgeProviderForRepository: async () => ({ - id: 'github', - getReviewForBranch: async () => null, - createReview: async (...args: Parameters) => - (await import('./client/create/create-github-pull-request')).createGitHubPullRequest(...args) - }) -})) -vi.mock('../source-control/hosted-review-creation-git-state', async (original) => ({ - ...(await original()), - getCurrentBranch: async () => 'feature', - hasUncommittedChanges: async () => false, - getHostedReviewUpstreamStatus: async () => ({ hasUpstream: true, ahead: 0, behind: 0 }), - baseRefExistsOnRemote: async () => true, - getDefaultBaseRef: async () => 'parent' -})) -vi.mock('../source-control/hosted-review-creation-provider', async (original) => ({ - ...(await original()), - isProviderAuthenticated: async () => true -})) - -import { installGitHubProjectAccounts } from './github-project-account' -import { getPRChecks } from './client/check/get-pr-checks' -import { rerunPRChecks } from './client/check/rerun-pr-checks' -import { getPRFileContents } from './work-item-details' -import './pr-start-point' -import '../runtime/integrations/github/runtime-github-repository-query-commands' -import { clearGhAccountTokenCacheForTests } from './gh-account-token' -import { clearGhCapabilityStateForTests } from './gh-capability-state' -import { _resetGhRateLimitBreaker } from '../git/command-runner/hosted-cli/gh-rate-limit-breaker' -import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' -import { createStackedHostedReview } from '../source-control/stacked-hosted-review-creation' -import './pr-refresh-candidate-policy' -import { fetchPullRequestWorkItem } from './client/fetch/work-item-fetch' -import { repositoryMergeMetadataCache } from './client/detect/repository-merge-metadata-cache' -import { _resetPRStackSummaryCacheForTests } from './client/lookup/pr-stack-summary-cache' -import { _resetGitHubPRStackCacheForTests } from './github-pr-stack' -import { resetMergedPRCommitMembershipCacheForTest } from './merged-pr-commit-membership' -import './github-repository-identity' - -const alice = { host: 'github.com', user: 'Alice' } -const bob = { host: 'github.com', user: 'Bob' } -const repository = { host: 'github.com', owner: 'acme', repo: 'widgets' } -let store: ReturnType -let release: () => void -let onRead: () => void -let requests: { args: string[]; token: string | undefined }[] -let request: ( - args: string[], - child: ReturnType, - token?: string -) => void -function complete(child: ReturnType, stdout: string) { - child.stdout?.emit('data', Buffer.from(stdout)) - child.emit('exit', 0, null) - child.emit('close', 0, null) -} -function checkResponse(name = 'CI') { - return JSON.stringify({ - data: { - repository: { - pullRequest: { - commits: { - nodes: [ - { - commit: { - statusCheckRollup: { - contexts: { - nodes: [ - { - __typename: 'CheckRun', - name, - status: 'COMPLETED', - conclusion: 'FAILURE', - databaseId: 7, - checkSuite: { workflowRun: { databaseId: 99 } } - } - ] - } - } - } - } - ] - } - } - } - } - }) -} - -function pr(title: string) { - return { - number: 42, - title, - state: 'OPEN', - url: 'https://github.com/acme/widgets/pull/42', - headRefName: 'feature', - baseRefName: 'main', - headRepositoryOwner: { login: 'acme' }, - headRepository: { name: 'widgets' }, - statusCheckRollup: [], - mergeable: 'MERGEABLE' - } -} -function rebind() { - store.updateRepo({ id: 'work' }, { ghAccount: bob }) -} -function rebindDuringFirstResolution() { - let first = true - onRead = () => { - if (first) { - first = false - queueMicrotask(rebind) - } - } -} -beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-pr35023-')) - const original = createStore() - original.addRepo(makeRepo({ id: 'work', path: '/work', issueSourcePreference: 'origin' })) - original.updateRepo({ id: 'work' }, { ghAccount: { host: ' GitHub.COM ', user: ' Alice ' } }) - original.flush() - store = createStore() - expect(store.getRepo('work')?.ghAccount).toEqual(alice) - clearGhAccountTokenCacheForTests() - clearGhCapabilityStateForTests() - _resetGhRateLimitBreaker() - repositoryMergeMetadataCache.clear() - _resetPRStackSummaryCacheForTests() - _resetGitHubPRStackCacheForTests() - resetMergedPRCommitMembershipCacheForTest() - requests = [] - onRead = () => {} - release = installGitHubProjectAccounts({ - getRepos: () => { - onRead() - return store.getRepos() - } - }) - remote.mockReset().mockResolvedValue(repository) - request = (args, child) => - queueMicrotask(() => complete(child, args.includes('POST') ? '{}' : checkResponse())) - spawnMock - .mockReset() - .mockImplementation((_command, args: string[], options: { env: NodeJS.ProcessEnv }) => { - const child = createFakeSpawnedChild() - if (args[0] === 'auth') { - queueMicrotask(() => - complete( - child, - args.includes('--help') ? '--user' : `${args[args.indexOf('--user') + 1]}-token` - ) - ) - } else { - requests.push({ args, token: options.env.GH_TOKEN }) - request(args, child, options.env.GH_TOKEN) - } - return child - }) -}) -afterEach(async () => { - release() - vi.unstubAllEnvs() - _resetGhRateLimitBreaker() - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) -}) - -it('separates unresolved callers by saved account before coalescing and returns each account result', async () => { - let finish: () => void = () => {} - let started: () => void = () => {} - const dispatched = new Promise((resolve) => { - started = resolve - }) - request = (_args, child, token) => { - if (token === 'Alice-token') { - finish = () => complete(child, checkResponse('Alice CI')) - started() - } else { - queueMicrotask(() => complete(child, checkResponse('Bob CI'))) - } - } - const first = getPRChecks('/work', 42, undefined, repository) - await dispatched - rebind() - const second = getPRChecks('/work', 42, undefined, repository) - // Bob must settle independently while Alice's child is still pending. - await expect(second).resolves.toMatchObject([{ name: 'Bob CI', workflowRunId: 99 }]) - finish() - await expect(first).resolves.toMatchObject([{ name: 'Alice CI', workflowRunId: 99 }]) - expect(requests.map((r) => r.token)).toEqual(['Alice-token', 'Bob-token']) -}) - -it('settles the full rerun read/write on the initial account and uses the rebind on the next operation', async () => { - rebindDuringFirstResolution() - await expect( - rerunPRChecks('/work', 42, { prRepo: repository, failedOnly: true }, null, { ghAccount: bob }) - ).resolves.toEqual({ ok: true, count: 1 }) - expect(requests.map((r) => ({ post: r.args.includes('POST'), token: r.token }))).toEqual([ - { post: false, token: 'Alice-token' }, - { post: true, token: 'Alice-token' } - ]) - await expect( - rerunPRChecks('/work', 42, { prRepo: repository, failedOnly: true }) - ).resolves.toEqual({ ok: true, count: 1 }) - expect(requests.slice(2).map((r) => r.token)).toEqual(['Bob-token', 'Bob-token']) -}) - -it('loads both file versions under one saved selection across repository resolution and future rebind', async () => { - rebindDuringFirstResolution() - request = (args, child, token) => - queueMicrotask(() => - complete(child, `${token}:${args.some((arg) => arg.includes('ref=base')) ? 'base' : 'head'}`) - ) - const input = { - repoPath: '/work', - prRepo: repository, - prNumber: 42, - path: 'src/a.ts', - status: 'modified', - headSha: 'head', - baseSha: 'base' - } as const - await expect(getPRFileContents(input)).resolves.toMatchObject({ - original: 'Alice-token:base', - modified: 'Alice-token:head', - originalIsBinary: false, - modifiedIsBinary: false - }) - await expect(getPRFileContents(input)).resolves.toMatchObject({ - original: 'Bob-token:base', - modified: 'Bob-token:head' - }) -}) - -it('settles stack prepare/create/register with one saved selection after a pending rebind', async () => { - let finish: () => void = () => {} - let started: () => void = () => {} - const resolving = new Promise((resolve) => { - started = resolve - }) - remote.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = () => resolve(repository) - started() - }) - ) - request = (args, child) => { - let output: unknown = [] - if (args[0] === 'pr' && args[1] === 'create') { - output = { number: 43, url: 'https://github.com/acme/widgets/pull/43' } - } else if (args.some((arg) => arg.includes('pulls?') && arg.includes('%3Aparent'))) { - output = [ - { - number: 42, - html_url: 'https://github.com/acme/widgets/pull/42', - head: { ref: 'parent' }, - base: { ref: 'main' } - } - ] - } else if (args.includes('POST')) { - output = { number: 50 } - } - queueMicrotask(() => complete(child, JSON.stringify(output))) - } - const pending = createStackedHostedReview( - '/work', - { provider: 'github', base: 'parent', head: 'feature', title: 'Change' }, - 'local' - ) - await resolving - rebind() - finish() - await expect(pending).resolves.toMatchObject({ - ok: true, - number: 43, - stackNumber: 50, - parentReview: { number: 42 } - }) - expect(requests.some((r) => r.args[0] === 'pr' && r.args[1] === 'create')).toBe(true) - expect(requests.some((r) => r.args.includes('POST'))).toBe(true) - expect(requests.every((r) => r.token === 'Alice-token')).toBe(true) -}) - -it('returns each saved viewer merge preference with omitted detector scope and reuses only that viewer', async () => { - request = (args, child, token) => - queueMicrotask(() => - complete( - child, - JSON.stringify( - args.includes('graphql') - ? { - data: { - repository: { - viewerDefaultMergeMethod: token === 'Alice-token' ? 'MERGE' : 'SQUASH', - mergeCommitAllowed: true, - rebaseMergeAllowed: true, - squashMergeAllowed: true - } - } - } - : pr(token ?? 'ambient') - ) - ) - ) - const read = () => fetchPullRequestWorkItem('/work', repository, 42) - await expect(read()).resolves.toMatchObject({ - title: 'Alice-token', - mergeMethodSettings: { defaultMethod: 'merge' } - }) - await expect(read()).resolves.toMatchObject({ mergeMethodSettings: { defaultMethod: 'merge' } }) - rebind() - await expect(read()).resolves.toMatchObject({ - title: 'Bob-token', - mergeMethodSettings: { defaultMethod: 'squash' } - }) - await expect(read()).resolves.toMatchObject({ mergeMethodSettings: { defaultMethod: 'squash' } }) - expect(requests.filter((r) => r.args.includes('graphql')).map((r) => r.token)).toEqual([ - 'Alice-token', - 'Bob-token' - ]) -}) - -it('recovers visible merged review through Bob complete membership iteration after Alice error and reuses Bob confirmation', async () => { - request = (args, child, token) => - queueMicrotask(() => { - const membership = args.find((arg) => arg.includes('/commits/') && arg.includes('/pulls?')) - if (membership && token === 'Alice-token') { - child.stderr?.emit('data', Buffer.from('request failed')) - child.emit('exit', 1, null) - child.emit('close', 1, null) - return - } - const merged = { ...pr(token ?? 'ambient'), state: 'MERGED', headRefOid: 'aaaa1111aaaa1111' } - const restMerged = { - number: 42, - title: token, - state: 'closed', - merged_at: '2026-10-01T00:00:00Z', - html_url: merged.url, - head: { - ref: 'feature', - sha: 'aaaa1111aaaa1111', - repo: { name: 'widgets', owner: { login: 'acme' } } - }, - base: { ref: 'main' } - } - const output = membership - ? membership.endsWith('page=1') - ? Array.from({ length: 100 }, (_, i) => ({ number: 1000 + i })) - : [{ number: 42 }] - : args.includes('graphql') - ? { data: { repository: {} } } - : args.some((arg) => arg.includes('/pulls?')) - ? [restMerged] - : args[1] === 'list' - ? [merged] - : merged - complete( - child, - (args.includes('--include') ? 'HTTP/2.0 200 OK\r\n\r\n' : '') + JSON.stringify(output) - ) - }) - const read = () => - getPRForBranchOutcome('/work', 'feature', null, null, null, { - currentHeadOid: 'bbbb2222bbbb2222' - }) - await expect(read()).resolves.toMatchObject({ kind: 'no-pr' }) - rebind() - await expect(read()).resolves.toMatchObject({ - kind: 'found', - pr: { title: 'Bob-token', state: 'merged', confirmedContainedHeadOid: 'bbbb2222bbbb2222' } - }) - await expect(read()).resolves.toMatchObject({ - kind: 'found', - pr: { confirmedContainedHeadOid: 'bbbb2222bbbb2222' } - }) - expect( - requests - .filter((r) => r.args.some((arg) => arg.includes('/commits/') && arg.includes('/pulls?'))) - .map((r) => ({ - endpoint: r.args.find((arg) => arg.includes('/commits/') && arg.includes('/pulls?')), - token: r.token - })) - ).toEqual([ - { - endpoint: 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1', - token: 'Alice-token' - }, - { - endpoint: 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1', - token: 'Bob-token' - }, - { - endpoint: 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=2', - token: 'Bob-token' - } - ]) -}) diff --git a/src/main/github/project-bound-gh-requests.test.ts b/src/main/github/project-bound-gh-requests.test.ts deleted file mode 100644 index b81e9bd8f6e..00000000000 --- a/src/main/github/project-bound-gh-requests.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createFakeSpawnedChild } from '../../shared/__fixtures__/fake-spawned-child' -import type { Repo } from '../../shared/repo-types' - -const { spawnMock, requestMock } = vi.hoisted(() => ({ spawnMock: vi.fn(), requestMock: vi.fn() })) - -vi.mock('node:child_process', async (importOriginal) => ({ - ...(await importOriginal()), - spawn: spawnMock -})) -vi.mock('./github-api-repository', () => ({ - getOriginGitHubApiRepository: vi.fn(async () => ({ - owner: 'acme', - repo: 'widgets', - host: 'github.com' - })), - githubHostExecOptions: () => ({ host: 'github.com' }) -})) - -import { _resetGhRateLimitBreaker } from '../git/command-runner/hosted-cli/gh-rate-limit-breaker' -import { installGitHubProjectAccounts } from './github-project-account' -import { createGitHubPullRequest } from './client/create/create-github-pull-request' -import { clearGhAccountTokenCacheForTests } from './gh-account-token' -import { clearGhCapabilityStateForTests } from './gh-capability-state' -import { runGraphql } from './project-view/internals' - -let releaseAccounts: (() => void) | undefined -let repo: Repo -beforeEach(() => { - _resetGhRateLimitBreaker() - clearGhAccountTokenCacheForTests() - clearGhCapabilityStateForTests() - requestMock.mockReset() - spawnMock.mockReset() - spawnMock.mockImplementation((_command, args: string[], options: { env: NodeJS.ProcessEnv }) => { - if (args[0] !== 'auth') { - return requestMock(args, options) - } - const child = createFakeSpawnedChild() - const output = args.includes('--help') ? '--user' : `${args[args.indexOf('--user') + 1]}-token` - queueMicrotask(() => complete(child, output)) - return child - }) - repo = { - id: 'work', - displayName: 'Work', - path: '/work', - badgeColor: '#000000', - addedAt: 0, - ghAccount: { host: 'github.com', user: 'Alice' } - } - releaseAccounts = installGitHubProjectAccounts({ getRepos: () => [repo] }) -}) -afterEach(() => { - releaseAccounts?.() - _resetGhRateLimitBreaker() - vi.unstubAllEnvs() -}) - -function complete(child: ReturnType, stdout: string): void { - child.stdout?.emit('data', Buffer.from(stdout)) - child.emit('exit', 0, null) - child.emit('close', 0, null) -} - -it('keeps Project View ambient even with a bound project cwd', async () => { - vi.stubEnv('GH_TOKEN', 'personal-token') - let selectedPersonal = false - requestMock.mockImplementation((_args, options: { env: NodeJS.ProcessEnv }) => { - selectedPersonal = options.env.GH_TOKEN === 'personal-token' - const child = createFakeSpawnedChild() - queueMicrotask(() => complete(child, '{"data":{"viewer":{"login":"personal"}}}')) - return child - }) - await expect( - runGraphql('query { viewer { login } }', {}, { cwd: repo.path, host: 'github.com' }) - ).resolves.toMatchObject({ ok: true, data: { viewer: { login: 'personal' } } }) - expect(selectedPersonal).toBe(true) - expect(spawnMock.mock.calls.some(([, args]) => args[0] === 'auth')).toBe(false) -}) - -it('keeps creation recovery on its original account while the next operation reads a rebind', async () => { - const tokens: (string | undefined)[] = [] - let startCreate: (finish: () => void) => void = () => {} - const started = new Promise<() => void>((resolve) => { - startCreate = resolve - }) - let firstCreate = true - requestMock.mockImplementation((args: string[], options: { env: NodeJS.ProcessEnv }) => { - tokens.push(options.env.GH_TOKEN) - const child = createFakeSpawnedChild() - if (args[0] === 'pr' && args[1] === 'create' && firstCreate) { - firstCreate = false - startCreate(() => complete(child, 'unconfirmed')) - } else { - queueMicrotask(() => - complete( - child, - JSON.stringify( - args[1] === 'list' - ? [{ number: 42, url: 'https://github.com/acme/widgets/pull/42' }] - : { number: 43, url: 'https://github.com/acme/widgets/pull/43' } - ) - ) - ) - } - return child - }) - const input = { provider: 'github', base: 'main', head: 'feature', title: 'Change' } as const - const pending = createGitHubPullRequest(repo.path, input, 'local') - const finish = await started - repo = { ...repo, ghAccount: { host: 'github.com', user: 'Bob' } } - finish() - await expect(pending).resolves.toMatchObject({ ok: true, number: 42 }) - expect(tokens).toEqual(['Alice-token', 'Alice-token']) - await expect(createGitHubPullRequest(repo.path, input, 'local')).resolves.toMatchObject({ - ok: true, - number: 43 - }) - expect(tokens.at(-1)).toBe('Bob-token') -}) diff --git a/src/main/github/project-view-host-auth.test.ts b/src/main/github/project-view-host-auth.test.ts deleted file mode 100644 index f202dce4edb..00000000000 --- a/src/main/github/project-view-host-auth.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - acquireMock, - releaseMock, - ghExecFileAsyncMock, - hostAuthenticatedMock, - noteRepositoryRateLimitSpendMock -} = vi.hoisted(() => ({ - acquireMock: vi.fn(), - releaseMock: vi.fn(), - ghExecFileAsyncMock: vi.fn(), - hostAuthenticatedMock: vi.fn(), - noteRepositoryRateLimitSpendMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - acquire: acquireMock, - release: releaseMock -})) - -vi.mock('../git/command-runner/process-capture/exec-error', async (importOriginal) => ({ - ...(await importOriginal>()), - extractExecError: vi.fn(() => ({ stdout: '', stderr: '' })) -})) - -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - ghExecFileAsync: ghExecFileAsyncMock -})) - -vi.mock('./rate-limit', () => ({ - rateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRateLimitSpend: vi.fn(), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock -})) - -vi.mock('./github-enterprise-repository', () => ({ - isGitHubHostAuthenticatedForGlobalCli: hostAuthenticatedMock -})) - -import { runGraphql, runRest } from './project-view/internals' -import { _resetProjectViewCachesForTests } from './project-view' - -describe('project view host authentication boundary', () => { - beforeEach(() => { - acquireMock.mockReset().mockResolvedValue(undefined) - releaseMock.mockReset() - ghExecFileAsyncMock.mockReset() - hostAuthenticatedMock.mockReset() - noteRepositoryRateLimitSpendMock.mockReset() - _resetProjectViewCachesForTests() - }) - - it('does not send GraphQL or REST requests to an unconfigured host', async () => { - hostAuthenticatedMock.mockResolvedValue(false) - - const [graphql, rest] = await Promise.all([ - runGraphql('query { viewer { login } }', {}, { host: 'evil.example.test' }), - runRest(['user'], undefined, 'core', { host: 'evil.example.test' }) - ]) - - expect(graphql).toMatchObject({ ok: false, error: { type: 'auth_required' } }) - expect(rest).toMatchObject({ ok: false, error: { type: 'auth_required' } }) - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - expect(acquireMock).not.toHaveBeenCalled() - expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/project-view.test.ts b/src/main/github/project-view.test.ts deleted file mode 100644 index b5dac755d7d..00000000000 --- a/src/main/github/project-view.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - GITHUB_PROJECT_REF_INPUT_MAX_BYTES, - GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR -} from '../../shared/github/project-ref-input' -import { - _getProjectViewCacheSizesForTests, - _getProjectViewOwnerTypeForTests, - _hasProjectViewParentFieldRetriedForTests, - _hasProjectViewParentFieldWarningLoggedForTests, - _markProjectViewParentFieldRetriedForTests, - _markProjectViewParentFieldWarningLoggedForTests, - _rememberProjectViewOwnerTypeForTests, - _resetProjectViewCachesForTests, - parseProjectPaste, - resolveProjectRef -} from './project-view' - -describe('parseProjectPaste', () => { - it('accepts enterprise-host URLs only when that host is provided (GHES)', () => { - const url = 'https://github.corp.example/orgs/acme/projects/7/views/2' - expect(parseProjectPaste(url, 'github.corp.example')).toEqual({ - kind: 'org', - owner: 'acme', - number: 7, - host: 'github.corp.example', - viewNumber: 2 - }) - expect(parseProjectPaste(url)).toBeNull() - expect( - parseProjectPaste('https://github.com/orgs/acme/projects/7', 'github.corp.example') - ).toEqual({ kind: 'org', owner: 'acme', number: 7, host: 'github.com' }) - }) - - it('rejects credentials and paths that only begin like a Project URL', () => { - expect(parseProjectPaste('https://user:token@github.com/orgs/acme/projects/1')).toBeNull() - expect(parseProjectPaste('https://github.com/orgs/acme/projects/1evil')).toBeNull() - expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/views/2evil')).toBeNull() - expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/files')).toBeNull() - }) -}) - -describe('resolveProjectRef', () => { - it('rejects oversized project refs with a metadata-only validation error', async () => { - const secret = 'project-url-secret' - const input = [ - 'https://github.com/orgs/acme/projects/42?', - secret, - 'x'.repeat(GITHUB_PROJECT_REF_INPUT_MAX_BYTES) - ].join('') - - await expect(resolveProjectRef({ input })).resolves.toEqual({ - ok: false, - error: { - type: 'validation_error', - message: GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR, - reason: 'input_too_large' - } - }) - await expect(resolveProjectRef({ input })).resolves.not.toMatchObject({ - error: { message: expect.stringContaining(secret) } - }) - }) -}) diff --git a/src/main/github/project-view.ts b/src/main/github/project-view.ts deleted file mode 100644 index 3abe1bcebdd..00000000000 --- a/src/main/github/project-view.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Preserve the public import entry point across the internal module split. -export { isValidOwnerSlug, isValidRepoSlug } from './project-view/internals' -export { classifyProjectError } from './project-view/project-error-classification' -export { updateIssueBySlug } from './project-view/mutations' -export { - updateProjectItemFieldValue, - clearProjectItemFieldValue -} from './project-view/project-field-mutations' -export { updatePullRequestBySlug } from './project-view/pull-request-mutation' -export { - addIssueCommentBySlug, - updateIssueCommentBySlug, - deleteIssueCommentBySlug -} from './project-view/issue-comment-mutations' -export { - listLabelsBySlug, - listAssignableUsersBySlug, - listIssueTypesBySlug -} from './project-view/repository-field-options' -export { updateIssueTypeBySlug } from './project-view/issue-type-mutation' -export { getWorkItemDetailsBySlug } from './project-view/work-item-details' -export { - PROJECT_VIEW_OWNER_CACHE_MAX_ENTRIES, - _resetProjectViewCachesForTests, - _getProjectViewCacheSizesForTests, - _rememberProjectViewOwnerTypeForTests, - _getProjectViewOwnerTypeForTests, - _markProjectViewParentFieldRetriedForTests, - _hasProjectViewParentFieldRetriedForTests, - _markProjectViewParentFieldWarningLoggedForTests, - _hasProjectViewParentFieldWarningLoggedForTests -} from './project-view/project-view-cache' -export { - normalizeField, - normalizeFieldValue -} from './project-view/project-view-field-normalization' -export { normalizeItem } from './project-view/project-view-item-normalization' -export { getProjectViewTable } from './project-view/project-view-table' -export { listAccessibleProjects } from './project-view/project-view-discovery' -export { parseProjectPaste, resolveProjectRef } from './project-view/project-view-reference' -export { listProjectViews } from './project-view/project-view-listing' diff --git a/src/main/github/project-view/internals.ts b/src/main/github/project-view/internals.ts deleted file mode 100644 index f5a7688fa49..00000000000 --- a/src/main/github/project-view/internals.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { acquire, release } from '../gh-utils' -import { isGitHubOwnerSlug } from '../../../shared/github/owner-slug' -import { extractExecError } from '../../git/command-runner/process-capture/exec-error' -import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' -import { - repositoryRateLimitGuard, - noteRepositoryRateLimitSpend, - type RateLimitBucketKind -} from '../rate-limit' -import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' -import { githubProjectHost } from '../../../shared/github/project-identity' -import { isDefaultGitHubHost } from '../../../shared/github/repository-identity-key' -import { isGitHubHostAuthenticatedForGlobalCli } from '../github-enterprise-repository' -import { - classifyProjectError, - driftError, - rateLimitedError, - type GhGraphqlError -} from './project-error-classification' - -export { - acquire, - release, - extractExecError, - ghExecFileAsync, - repositoryRateLimitGuard, - noteRepositoryRateLimitSpend -} -export type { RateLimitBucketKind } - -/** Project View uses ambient login, independently of Repo.ghAccount; pin Enterprise hosts explicitly. */ -export type ProjectGhExecOptions = { cwd?: string; host?: string } - -// Owner/project calls have no repository slug, so pin their host directly. -export function projectGhExecOptions(host: string | undefined): ProjectGhExecOptions { - return { host: githubProjectHost(host) } -} - -export async function projectHostAuthenticationError( - host: string | undefined -): Promise { - const selectedHost = githubProjectHost(host) - if ( - isDefaultGitHubHost(selectedHost) || - (await isGitHubHostAuthenticatedForGlobalCli(selectedHost)) - ) { - return null - } - // Verify pasted hosts before sending ambient Enterprise credentials. - return { - type: 'auth_required', - message: `GitHub CLI is not authenticated to ${selectedHost}. Run gh auth login --hostname ${selectedHost}.`, - host: selectedHost - } -} - -// Shared owner rules differ from repo names; validate both before interpolating authenticated REST paths. -const REPO_SLUG_RE = /^[A-Za-z0-9._-]+$/ -const REPO_SLUG_RESERVED = new Set(['.', '..']) - -export function isValidOwnerSlug(value: unknown): value is string { - return isGitHubOwnerSlug(value) -} - -export function isValidRepoSlug(value: unknown): value is string { - return ( - typeof value === 'string' && - value.length > 0 && - REPO_SLUG_RE.test(value) && - !REPO_SLUG_RESERVED.has(value) - ) -} - -export function assertSlug( - value: unknown, - field: 'owner' | 'repo' -): { ok: true; slug: string } | { ok: false; error: GitHubProjectViewError } { - const valid = field === 'owner' ? isValidOwnerSlug(value) : isValidRepoSlug(value) - if (!valid) { - return { - ok: false, - error: { - type: 'validation_error', - message: `Invalid ${field}: "${String(value)}" is not a valid GitHub slug.`, - reason: 'invalid_slug', - detail: field, - value: String(value) - } - } - } - return { ok: true, slug: value as string } -} - -export function assertPositiveInt( - value: unknown, - field: string -): { ok: true; n: number } | { ok: false; error: GitHubProjectViewError } { - if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) { - return { - ok: false, - error: { - type: 'validation_error', - message: `Invalid ${field}: must be a positive integer.`, - reason: 'invalid_positive_integer', - detail: field - } - } - } - return { ok: true, n: value } -} - -export function validateSlugArgs( - owner: unknown, - repo: unknown -): { ok: true } | { ok: false; error: GitHubProjectViewError } { - const o = assertSlug(owner, 'owner') - if (!o.ok) { - return { ok: false, error: o.error } - } - const r = assertSlug(repo, 'repo') - if (!r.ok) { - return { ok: false, error: r.error } - } - return { ok: true } -} - -export type GraphqlVars = Record - -export async function runGraphql( - query: string, - vars: GraphqlVars, - exec?: ProjectGhExecOptions -): Promise< - | { ok: true; data: T } - | { ok: false; error: GitHubProjectViewError; raw: { stderr: string; stdout: string } } -> { - const authError = await projectHostAuthenticationError(exec?.host) - if (authError) { - return { ok: false, error: authError, raw: { stderr: '', stdout: '' } } - } - // Enterprise traffic has separate quota from the shared github.com snapshot. - const guard = repositoryRateLimitGuard({ host: exec?.host }, 'graphql') - if (guard.blocked) { - return { ok: false, error: rateLimitedError(guard), raw: { stderr: '', stdout: '' } } - } - // Use typed -F for numbers/booleans and literal -f for strings, including empty strings. - const args: string[] = ['api', 'graphql', '-f', `query=${query}`] - for (const [k, v] of Object.entries(vars)) { - if (typeof v === 'number' || typeof v === 'boolean') { - args.push('-F', `${k}=${String(v)}`) - } else { - args.push('-f', `${k}=${v}`) - } - } - await acquire() - noteRepositoryRateLimitSpend({ host: exec?.host }, 'graphql') - try { - const { stdout, stderr } = await ghExecFileAsync(args, { - encoding: 'utf-8', - ...(exec?.cwd ? { cwd: exec.cwd } : {}), - ...(exec?.host ? { host: exec.host } : {}) - }) - try { - const parsed: { data?: T; errors?: GhGraphqlError[] } = JSON.parse(stdout) - if (parsed.errors && parsed.errors.length > 0) { - return { - ok: false, - error: classifyProjectError(stderr, stdout, exec?.host), - raw: { stderr, stdout } - } - } - if (parsed.data === undefined) { - return { - ok: false, - error: driftError('response missing data'), - raw: { stderr, stdout } - } - } - return { ok: true, data: parsed.data } - } catch (parseErr) { - return { - ok: false, - error: driftError( - `failed to parse response (${parseErr instanceof Error ? parseErr.message : String(parseErr)})` - ), - raw: { stderr, stdout } - } - } - } catch (err) { - // Explicit streams preserve diagnostics that Error.message may truncate. - const { stderr, stdout: maybeStdout } = extractExecError(err) - return { - ok: false, - error: classifyProjectError(stderr, maybeStdout, exec?.host), - raw: { stderr, stdout: maybeStdout } - } - } finally { - release() - } -} - -export async function runRest( - args: string[], - cwd?: string, - bucket: RateLimitBucketKind = 'core', - options?: { expectEmpty?: boolean; host?: string } -): Promise<{ ok: true; data: T } | { ok: false; error: GitHubProjectViewError }> { - const authError = await projectHostAuthenticationError(options?.host) - if (authError) { - return { ok: false, error: authError } - } - // Enterprise traffic has separate quota from the shared github.com snapshot. - const guard = repositoryRateLimitGuard({ host: options?.host }, bucket) - if (guard.blocked) { - return { ok: false, error: rateLimitedError(guard) } - } - await acquire() - noteRepositoryRateLimitSpend({ host: options?.host }, bucket) - try { - const { stdout, stderr } = await ghExecFileAsync(['api', ...args], { - encoding: 'utf-8', - ...(cwd ? { cwd } : {}), - ...(options?.host ? { host: options.host } : {}) - }) - // Successful DELETE endpoints can return no body; do not misclassify empty stdout as a parse failure. - if (options?.expectEmpty && stdout.trim() === '') { - return { ok: true, data: undefined as T } - } - try { - return { ok: true, data: JSON.parse(stdout) as T } - } catch { - return { - ok: false, - error: { - type: 'unknown', - message: `Unexpected REST response: ${stderr.trim()}`, - reason: 'unexpected_rest_response', - detail: stderr.trim() - } - } - } - } catch (err) { - const { stderr, stdout: maybeStdout } = extractExecError(err) - return { ok: false, error: classifyProjectError(stderr, maybeStdout, options?.host) } - } finally { - release() - } -} diff --git a/src/main/github/project-view/issue-comment-mutations.ts b/src/main/github/project-view/issue-comment-mutations.ts index 61dd68d32b9..6e6339e4ae4 100644 --- a/src/main/github/project-view/issue-comment-mutations.ts +++ b/src/main/github/project-view/issue-comment-mutations.ts @@ -1,15 +1,17 @@ -import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' -import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' -import type { PRComment } from '../../../shared/github/comment-types' +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls' +import { assertPositiveInt, validateSlugArgs } from './project-argument-validation' +import { projectGhExecOptions } from './project-host-execution' +import { runRest } from './project-rest' +import type { PRComment } from '../../../shared/github/comments/comment-types' import type { GitHubProjectCommentMutationResult, GitHubProjectMutationResult -} from '../../../shared/github/project-result-types' +} from '../../../shared/github/projects/project-result-types' import type { AddIssueCommentBySlugArgs, DeleteIssueCommentBySlugArgs, UpdateIssueCommentBySlugArgs -} from '../../../shared/github/project-request-types' +} from '../../../shared/github/projects/project-request-types' type RawIssueCommentResponse = { id?: number diff --git a/src/main/github/project-view/issue-type-mutation.ts b/src/main/github/project-view/issue-type-mutation.ts index 30f9fb6c59b..f49665ff2f2 100644 --- a/src/main/github/project-view/issue-type-mutation.ts +++ b/src/main/github/project-view/issue-type-mutation.ts @@ -1,12 +1,8 @@ -import { - assertPositiveInt, - projectGhExecOptions, - runGraphql, - validateSlugArgs, - type GraphqlVars -} from './internals' -import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' -import type { UpdateIssueTypeBySlugArgs } from '../../../shared/github/project-request-types' +import { assertPositiveInt, validateSlugArgs } from './project-argument-validation' +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql, type GraphqlVars } from './project-graphql' +import type { GitHubProjectMutationResult } from '../../../shared/github/projects/project-result-types' +import type { UpdateIssueTypeBySlugArgs } from '../../../shared/github/projects/project-request-types' export async function updateIssueTypeBySlug( args: UpdateIssueTypeBySlugArgs diff --git a/src/main/github/project-view/mutations.ts b/src/main/github/project-view/mutations.ts index 4c31ac3a522..f47e9924914 100644 --- a/src/main/github/project-view/mutations.ts +++ b/src/main/github/project-view/mutations.ts @@ -1,20 +1,14 @@ -import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' -import { - acquire, - assertPositiveInt, - extractExecError, - ghExecFileAsync, - noteRepositoryRateLimitSpend, - projectGhExecOptions, - projectHostAuthenticationError, - release, - repositoryRateLimitGuard, - runRest, - validateSlugArgs -} from './internals' +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls' +import { acquire, release } from '../execution/github-operation-slots' +import { assertPositiveInt, validateSlugArgs } from './project-argument-validation' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit' +import { projectGhExecOptions, projectHostAuthenticationError } from './project-host-execution' +import { runRest } from './project-rest' import { classifyProjectError, rateLimitedError } from './project-error-classification' -import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' -import type { UpdateIssueBySlugArgs } from '../../../shared/github/project-request-types' +import type { GitHubProjectMutationResult } from '../../../shared/github/projects/project-result-types' +import type { UpdateIssueBySlugArgs } from '../../../shared/github/projects/project-request-types' export async function updateIssueBySlug( args: UpdateIssueBySlugArgs diff --git a/src/main/github/project-view/project-argument-validation.ts b/src/main/github/project-view/project-argument-validation.ts new file mode 100644 index 00000000000..1ec43dc7c77 --- /dev/null +++ b/src/main/github/project-view/project-argument-validation.ts @@ -0,0 +1,69 @@ +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { isGitHubOwnerSlug as isValidOwnerSlug } from '../../../shared/github/repositories/owner-slug' + +// Shared owner rules differ from repo names; validate both before interpolating authenticated REST paths. +const REPO_SLUG_RE = /^[A-Za-z0-9._-]+$/ + +const REPO_SLUG_RESERVED = new Set(['.', '..']) + +export function isValidRepoSlug(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + REPO_SLUG_RE.test(value) && + !REPO_SLUG_RESERVED.has(value) + ) +} + +export function assertSlug( + value: unknown, + field: 'owner' | 'repo' +): { ok: true; slug: string } | { ok: false; error: GitHubProjectViewError } { + const valid = field === 'owner' ? isValidOwnerSlug(value) : isValidRepoSlug(value) + if (!valid) { + return { + ok: false, + error: { + type: 'validation_error', + message: `Invalid ${field}: "${String(value)}" is not a valid GitHub slug.`, + reason: 'invalid_slug', + detail: field, + value: String(value) + } + } + } + return { ok: true, slug: value as string } +} + +export function assertPositiveInt( + value: unknown, + field: string +): { ok: true; n: number } | { ok: false; error: GitHubProjectViewError } { + if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) { + return { + ok: false, + error: { + type: 'validation_error', + message: `Invalid ${field}: must be a positive integer.`, + reason: 'invalid_positive_integer', + detail: field + } + } + } + return { ok: true, n: value } +} + +export function validateSlugArgs( + owner: unknown, + repo: unknown +): { ok: true } | { ok: false; error: GitHubProjectViewError } { + const o = assertSlug(owner, 'owner') + if (!o.ok) { + return { ok: false, error: o.error } + } + const r = assertSlug(repo, 'repo') + if (!r.ok) { + return { ok: false, error: r.error } + } + return { ok: true } +} diff --git a/src/main/github/project-view/project-error-classification.ts b/src/main/github/project-view/project-error-classification.ts index 4b0df5977e3..f1e7b1aef42 100644 --- a/src/main/github/project-view/project-error-classification.ts +++ b/src/main/github/project-view/project-error-classification.ts @@ -1,6 +1,6 @@ import type { OptionalProjectItemField } from './project-view-cache' -import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' -import { githubProjectHost } from '../../../shared/github/project-identity' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' export type GhGraphqlError = { type?: string diff --git a/src/main/github/project-view/project-field-mutations.ts b/src/main/github/project-view/project-field-mutations.ts index 69130f7197b..22d2a80ae4d 100644 --- a/src/main/github/project-view/project-field-mutations.ts +++ b/src/main/github/project-view/project-field-mutations.ts @@ -1,10 +1,11 @@ -import { projectGhExecOptions, runGraphql, type GraphqlVars } from './internals' -import type { GitHubProjectFieldMutationValue } from '../../../shared/github/project-types' -import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql, type GraphqlVars } from './project-graphql' +import type { GitHubProjectFieldMutationValue } from '../../../shared/github/projects/project-types' +import type { GitHubProjectMutationResult } from '../../../shared/github/projects/project-result-types' import type { ClearProjectItemFieldArgs, UpdateProjectItemFieldArgs -} from '../../../shared/github/project-request-types' +} from '../../../shared/github/projects/project-request-types' class UnknownFieldMutationKindError extends Error { constructor(kind: string) { diff --git a/src/main/github/project-view/project-graphql.ts b/src/main/github/project-view/project-graphql.ts new file mode 100644 index 00000000000..33a5c12bbb4 --- /dev/null +++ b/src/main/github/project-view/project-graphql.ts @@ -0,0 +1,87 @@ +import { acquire, release } from '../execution/github-operation-slots' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { repositoryRateLimitGuard, noteRepositoryRateLimitSpend } from '../api/rate-limit' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { + classifyProjectError, + driftError, + rateLimitedError, + type GhGraphqlError +} from './project-error-classification' +import { type ProjectGhExecOptions, projectHostAuthenticationError } from './project-host-execution' + +export type GraphqlVars = Record + +export async function runGraphql( + query: string, + vars: GraphqlVars, + exec?: ProjectGhExecOptions +): Promise< + | { ok: true; data: T } + | { ok: false; error: GitHubProjectViewError; raw: { stderr: string; stdout: string } } +> { + const authError = await projectHostAuthenticationError(exec?.host) + if (authError) { + return { ok: false, error: authError, raw: { stderr: '', stdout: '' } } + } + // Enterprise traffic has separate quota from the shared github.com snapshot. + const guard = repositoryRateLimitGuard({ host: exec?.host }, 'graphql') + if (guard.blocked) { + return { ok: false, error: rateLimitedError(guard), raw: { stderr: '', stdout: '' } } + } + // Use typed -F for numbers/booleans and literal -f for strings, including empty strings. + const args: string[] = ['api', 'graphql', '-f', `query=${query}`] + for (const [k, v] of Object.entries(vars)) { + if (typeof v === 'number' || typeof v === 'boolean') { + args.push('-F', `${k}=${String(v)}`) + } else { + args.push('-f', `${k}=${v}`) + } + } + await acquire() + noteRepositoryRateLimitSpend({ host: exec?.host }, 'graphql') + try { + const { stdout, stderr } = await ghExecFileAsync(args, { + encoding: 'utf-8', + ...(exec?.cwd ? { cwd: exec.cwd } : {}), + ...(exec?.host ? { host: exec.host } : {}) + }) + try { + const parsed: { data?: T; errors?: GhGraphqlError[] } = JSON.parse(stdout) + if (parsed.errors && parsed.errors.length > 0) { + return { + ok: false, + error: classifyProjectError(stderr, stdout, exec?.host), + raw: { stderr, stdout } + } + } + if (parsed.data === undefined) { + return { + ok: false, + error: driftError('response missing data'), + raw: { stderr, stdout } + } + } + return { ok: true, data: parsed.data } + } catch (parseErr) { + return { + ok: false, + error: driftError( + `failed to parse response (${parseErr instanceof Error ? parseErr.message : String(parseErr)})` + ), + raw: { stderr, stdout } + } + } + } catch (err) { + // Explicit streams preserve diagnostics that Error.message may truncate. + const { stderr, stdout: maybeStdout } = extractExecError(err) + return { + ok: false, + error: classifyProjectError(stderr, maybeStdout, exec?.host), + raw: { stderr, stdout: maybeStdout } + } + } finally { + release() + } +} diff --git a/src/main/github/project-view/project-host-execution.ts b/src/main/github/project-view/project-host-execution.ts new file mode 100644 index 00000000000..9cfa2645ed9 --- /dev/null +++ b/src/main/github/project-view/project-host-execution.ts @@ -0,0 +1,30 @@ +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' +import { isDefaultGitHubHost } from '../../../shared/github/repositories/repository-identity-key' +import { isGitHubHostAuthenticatedForGlobalCli } from '../repositories/github-enterprise-repository' + +/** Project View uses ambient login, independently of Repo.ghAccount; pin Enterprise hosts explicitly. */ +export type ProjectGhExecOptions = { cwd?: string; host?: string } + +// Owner/project calls have no repository slug, so pin their host directly. +export function projectGhExecOptions(host: string | undefined): ProjectGhExecOptions { + return { host: githubProjectHost(host) } +} + +export async function projectHostAuthenticationError( + host: string | undefined +): Promise { + const selectedHost = githubProjectHost(host) + if ( + isDefaultGitHubHost(selectedHost) || + (await isGitHubHostAuthenticatedForGlobalCli(selectedHost)) + ) { + return null + } + // Verify pasted hosts before sending ambient Enterprise credentials. + return { + type: 'auth_required', + message: `GitHub CLI is not authenticated to ${selectedHost}. Run gh auth login --hostname ${selectedHost}.`, + host: selectedHost + } +} diff --git a/src/main/github/project-view/project-request-host-auth.test.ts b/src/main/github/project-view/project-request-host-auth.test.ts new file mode 100644 index 00000000000..cda50edfdb7 --- /dev/null +++ b/src/main/github/project-view/project-request-host-auth.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + acquireMock, + releaseMock, + ghExecFileAsyncMock, + hostAuthenticatedMock, + noteRepositoryRateLimitSpendMock +} = vi.hoisted(() => ({ + acquireMock: vi.fn(), + releaseMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + hostAuthenticatedMock: vi.fn(), + noteRepositoryRateLimitSpendMock: vi.fn() +})) + +vi.mock('../execution/github-operation-slots', () => ({ + acquire: acquireMock, + release: releaseMock +})) + +vi.mock('../../git/command-runner/process-capture/exec-error', async (importOriginal) => ({ + ...(await importOriginal>()), + extractExecError: vi.fn(() => ({ stdout: '', stderr: '' })) +})) + +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../api/rate-limit', () => ({ + rateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRateLimitSpend: vi.fn(), + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock +})) + +vi.mock('../repositories/github-enterprise-repository', () => ({ + isGitHubHostAuthenticatedForGlobalCli: hostAuthenticatedMock +})) + +import { runGraphql } from './project-graphql' +import { runRest } from './project-rest' +import { _resetProjectViewCachesForTests } from './project-view-cache' + +describe('project view host authentication boundary', () => { + beforeEach(() => { + acquireMock.mockReset().mockResolvedValue(undefined) + releaseMock.mockReset() + ghExecFileAsyncMock.mockReset() + hostAuthenticatedMock.mockReset() + noteRepositoryRateLimitSpendMock.mockReset() + _resetProjectViewCachesForTests() + }) + + it('does not send GraphQL or REST requests to an unconfigured host', async () => { + hostAuthenticatedMock.mockResolvedValue(false) + + const [graphql, rest] = await Promise.all([ + runGraphql('query { viewer { login } }', {}, { host: 'evil.example.test' }), + runRest(['user'], undefined, 'core', { host: 'evil.example.test' }) + ]) + + expect(graphql).toMatchObject({ ok: false, error: { type: 'auth_required' } }) + expect(rest).toMatchObject({ ok: false, error: { type: 'auth_required' } }) + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + expect(acquireMock).not.toHaveBeenCalled() + expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/github/project-view/project-rest.ts b/src/main/github/project-view/project-rest.ts new file mode 100644 index 00000000000..4a037e66cb1 --- /dev/null +++ b/src/main/github/project-view/project-rest.ts @@ -0,0 +1,59 @@ +import { acquire, release } from '../execution/github-operation-slots' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { + repositoryRateLimitGuard, + noteRepositoryRateLimitSpend, + type RateLimitBucketKind +} from '../api/rate-limit' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { classifyProjectError, rateLimitedError } from './project-error-classification' +import { projectHostAuthenticationError } from './project-host-execution' + +export async function runRest( + args: string[], + cwd?: string, + bucket: RateLimitBucketKind = 'core', + options?: { expectEmpty?: boolean; host?: string } +): Promise<{ ok: true; data: T } | { ok: false; error: GitHubProjectViewError }> { + const authError = await projectHostAuthenticationError(options?.host) + if (authError) { + return { ok: false, error: authError } + } + // Enterprise traffic has separate quota from the shared github.com snapshot. + const guard = repositoryRateLimitGuard({ host: options?.host }, bucket) + if (guard.blocked) { + return { ok: false, error: rateLimitedError(guard) } + } + await acquire() + noteRepositoryRateLimitSpend({ host: options?.host }, bucket) + try { + const { stdout, stderr } = await ghExecFileAsync(['api', ...args], { + encoding: 'utf-8', + ...(cwd ? { cwd } : {}), + ...(options?.host ? { host: options.host } : {}) + }) + // Successful DELETE endpoints can return no body; do not misclassify empty stdout as a parse failure. + if (options?.expectEmpty && stdout.trim() === '') { + return { ok: true, data: undefined as T } + } + try { + return { ok: true, data: JSON.parse(stdout) as T } + } catch { + return { + ok: false, + error: { + type: 'unknown', + message: `Unexpected REST response: ${stderr.trim()}`, + reason: 'unexpected_rest_response', + detail: stderr.trim() + } + } + } + } catch (err) { + const { stderr, stdout: maybeStdout } = extractExecError(err) + return { ok: false, error: classifyProjectError(stderr, maybeStdout, options?.host) } + } finally { + release() + } +} diff --git a/src/main/github/project-view/project-view-cache.ts b/src/main/github/project-view/project-view-cache.ts index 7f1bad822cd..49858975a6d 100644 --- a/src/main/github/project-view/project-view-cache.ts +++ b/src/main/github/project-view/project-view-cache.ts @@ -1,5 +1,5 @@ -import type { GitHubProjectOwnerType } from '../../../shared/github/project-types' -import { githubProjectHost } from '../../../shared/github/project-identity' +import type { GitHubProjectOwnerType } from '../../../shared/github/projects/project-types' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' export const PROJECT_VIEW_OWNER_CACHE_MAX_ENTRIES = 512 diff --git a/src/main/github/project-view/project-view-config.test.ts b/src/main/github/project-view/project-view-config.test.ts deleted file mode 100644 index 2ec9dfa3081..00000000000 --- a/src/main/github/project-view/project-view-config.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - fetchProjectViewsPage, - resetVerticalGroupByCapabilityForTests -} from './project-view-config' -import { runGraphql } from './internals' -import type * as Internals from './internals' - -vi.mock('./internals', async (importOriginal) => ({ - ...(await importOriginal()), - runGraphql: vi.fn() -})) - -const args = { - owner: 'acme', - ownerType: 'organization', - projectNumber: 1, - host: 'ghes.acme.test', - after: null -} as const - -function okPage() { - return { - ok: true as const, - data: { - organization: { - projectV2: { - id: 'PVT_1', - title: 'Plan', - url: 'https://ghes.acme.test/orgs/acme/projects/1', - views: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] } - } - } - } - } -} - -function unknownFieldFailure() { - return { - ok: false as const, - error: { type: 'schema_drift' as const, message: 'Could not read this project view.' }, - raw: { - stderr: '', - stdout: JSON.stringify({ - errors: [ - { - message: "Field 'verticalGroupByFields' doesn't exist on type 'ProjectV2View'" - } - ] - }) - } - } -} - -beforeEach(() => { - vi.resetAllMocks() - resetVerticalGroupByCapabilityForTests() -}) - -describe('verticalGroupByFields capability fallback', () => { - it('memoizes the incapability per host and keeps other hosts unaffected', async () => { - vi.mocked(runGraphql).mockResolvedValueOnce(unknownFieldFailure()).mockResolvedValue(okPage()) - await fetchProjectViewsPage(args) - await fetchProjectViewsPage(args) - expect(vi.mocked(runGraphql).mock.calls[2]?.[0]).not.toContain('verticalGroupByFields') - await fetchProjectViewsPage({ ...args, host: 'github.com' }) - expect(vi.mocked(runGraphql).mock.calls[3]?.[0]).toContain('verticalGroupByFields') - }) - - it('does not cache authorization or transient errors that mention the field', async () => { - vi.mocked(runGraphql) - .mockResolvedValueOnce({ - ok: false, - error: { type: 'scope_missing', message: 'Not authorized' }, - raw: { - stderr: '', - stdout: JSON.stringify({ - errors: [{ message: 'Not authorized to access verticalGroupByFields' }] - }) - } - }) - .mockResolvedValue(okPage()) - expect((await fetchProjectViewsPage(args)).ok).toBe(false) - expect(runGraphql).toHaveBeenCalledTimes(1) - await fetchProjectViewsPage(args) - expect(vi.mocked(runGraphql).mock.calls[1]?.[0]).toContain('verticalGroupByFields') - }) - - it('does not treat the field name inside partial-error DATA as incapability', async () => { - // Partial-error data can echo a healthy field name; only schema errors prove it unsupported. - vi.mocked(runGraphql).mockResolvedValueOnce({ - ok: false, - error: { type: 'schema_drift', message: 'Could not read this project view.' }, - raw: { - stderr: '', - stdout: JSON.stringify({ - data: { - organization: { projectV2: { views: { nodes: [{ verticalGroupByFields: {} }] } } } - }, - errors: [{ message: 'SAML enforcement: resource protected by organization policy' }] - }) - } - }) - const result = await fetchProjectViewsPage(args) - expect(result.ok).toBe(false) - expect(vi.mocked(runGraphql)).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/github/project-view/project-view-config.ts b/src/main/github/project-view/project-view-config.ts index da828e1c278..ea8296615bd 100644 --- a/src/main/github/project-view/project-view-config.ts +++ b/src/main/github/project-view/project-view-config.ts @@ -4,11 +4,12 @@ import type { GitHubProjectSort, GitHubProjectView, GitHubProjectViewLayout -} from '../../../shared/github/project-types' -import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' -import { githubProjectHost } from '../../../shared/github/project-identity' +} from '../../../shared/github/projects/project-types' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' import { driftError, extractGraphqlErrors } from './project-error-classification' -import { projectGhExecOptions, runGraphql, type GraphqlVars } from './internals' +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql, type GraphqlVars } from './project-graphql' import { normalizeField, type RawProjectV2Field } from './project-view-field-normalization' import { FIELD_CONFIG_FRAGMENT } from './project-view-query-fragments' diff --git a/src/main/github/project-view/project-view-discovery.ts b/src/main/github/project-view/project-view-discovery.ts index cfb43588b39..795e7e433b5 100644 --- a/src/main/github/project-view/project-view-discovery.ts +++ b/src/main/github/project-view/project-view-discovery.ts @@ -1,11 +1,12 @@ -import type { ListAccessibleProjectsArgs } from '../../../shared/github/project-request-types' -import type { ListAccessibleProjectsResult } from '../../../shared/github/project-result-types' +import type { ListAccessibleProjectsArgs } from '../../../shared/github/projects/project-request-types' +import type { ListAccessibleProjectsResult } from '../../../shared/github/projects/project-result-types' import type { GitHubProjectOwnerType, GitHubProjectSummary -} from '../../../shared/github/project-types' -import { githubProjectHost } from '../../../shared/github/project-identity' -import { projectGhExecOptions, runGraphql, type GraphqlVars } from './internals' +} from '../../../shared/github/projects/project-types' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql, type GraphqlVars } from './project-graphql' import { driftError } from './project-error-classification' import { rememberOwnerType } from './project-view-cache' diff --git a/src/main/github/project-view/project-view-field-normalization.ts b/src/main/github/project-view/project-view-field-normalization.ts index 33fc6044cd5..6adcda473c7 100644 --- a/src/main/github/project-view/project-view-field-normalization.ts +++ b/src/main/github/project-view/project-view-field-normalization.ts @@ -6,7 +6,7 @@ import type { GitHubProjectLabel, GitHubProjectSingleSelectOption, GitHubProjectUser -} from '../../../shared/github/project-types' +} from '../../../shared/github/projects/project-types' export type RawProjectV2Field = { __typename?: string diff --git a/src/main/github/project-view/project-view-item-normalization.ts b/src/main/github/project-view/project-view-item-normalization.ts index cb966e5aeda..69e03d51ae4 100644 --- a/src/main/github/project-view/project-view-item-normalization.ts +++ b/src/main/github/project-view/project-view-item-normalization.ts @@ -5,8 +5,8 @@ import type { GitHubProjectRow, GitHubProjectRowItemType, GitHubProjectUser -} from '../../../shared/github/project-types' -import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' +} from '../../../shared/github/projects/project-types' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' import { driftError } from './project-error-classification' import { normalizeFieldValue, diff --git a/src/main/github/project-view/project-view-item-page.ts b/src/main/github/project-view/project-view-item-page.ts index 61c0c6911b7..210eb0b6573 100644 --- a/src/main/github/project-view/project-view-item-page.ts +++ b/src/main/github/project-view/project-view-item-page.ts @@ -1,16 +1,11 @@ import type { OptionalProjectItemField } from './project-view-cache' -import type { GitHubProjectOwnerType } from '../../../shared/github/project-types' -import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' -import { - acquire, - extractExecError, - ghExecFileAsync, - noteRepositoryRateLimitSpend, - projectGhExecOptions, - projectHostAuthenticationError, - release, - repositoryRateLimitGuard -} from './internals' +import type { GitHubProjectOwnerType } from '../../../shared/github/projects/project-types' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { acquire, release } from '../execution/github-operation-slots' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit' +import { projectGhExecOptions, projectHostAuthenticationError } from './project-host-execution' import { classifyProjectError, driftError, diff --git a/src/main/github/project-view/project-view-items.ts b/src/main/github/project-view/project-view-items.ts index 3c55cf0819c..99a66a41fbf 100644 --- a/src/main/github/project-view/project-view-items.ts +++ b/src/main/github/project-view/project-view-items.ts @@ -1,6 +1,10 @@ -import type { GitHubProjectOwnerType, GitHubProjectRow } from '../../../shared/github/project-types' -import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' -import { projectGhExecOptions, runGraphql } from './internals' +import type { + GitHubProjectOwnerType, + GitHubProjectRow +} from '../../../shared/github/projects/project-types' +import type { GitHubProjectViewError } from '../../../shared/github/projects/project-result-types' +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql } from './project-graphql' import { driftError, unsupportedItemFieldsFromErrors } from './project-error-classification' import { getUnsupportedItemFields, diff --git a/src/main/github/project-view/project-view-listing.ts b/src/main/github/project-view/project-view-listing.ts index aeacb4d5e69..429e9cd6734 100644 --- a/src/main/github/project-view/project-view-listing.ts +++ b/src/main/github/project-view/project-view-listing.ts @@ -1,10 +1,10 @@ -import type { ListProjectViewsArgs } from '../../../shared/github/project-request-types' -import type { ListProjectViewsResult } from '../../../shared/github/project-result-types' +import type { ListProjectViewsArgs } from '../../../shared/github/projects/project-request-types' +import type { ListProjectViewsResult } from '../../../shared/github/projects/project-result-types' import type { GitHubProjectViewLayout, GitHubProjectViewSummary -} from '../../../shared/github/project-types' -import { assertPositiveInt, assertSlug } from './internals' +} from '../../../shared/github/projects/project-types' +import { assertPositiveInt, assertSlug } from './project-argument-validation' import { fetchProjectViewsPage } from './project-view-config' export async function listProjectViews( diff --git a/src/main/github/project-view/project-view-reference.test.ts b/src/main/github/project-view/project-view-reference.test.ts new file mode 100644 index 00000000000..b6b9f5809da --- /dev/null +++ b/src/main/github/project-view/project-view-reference.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import { + GITHUB_PROJECT_REF_INPUT_MAX_BYTES, + GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR +} from '../../../shared/github/projects/project-ref-input' +import { + _getProjectViewCacheSizesForTests, + _getProjectViewOwnerTypeForTests, + _hasProjectViewParentFieldRetriedForTests, + _hasProjectViewParentFieldWarningLoggedForTests, + _markProjectViewParentFieldRetriedForTests, + _markProjectViewParentFieldWarningLoggedForTests, + _rememberProjectViewOwnerTypeForTests, + _resetProjectViewCachesForTests +} from './project-view-cache' +import { parseProjectPaste, resolveProjectRef } from './project-view-reference' + +describe('parseProjectPaste', () => { + it('accepts enterprise-host URLs only when that host is provided (GHES)', () => { + const url = 'https://github.corp.example/orgs/acme/projects/7/views/2' + expect(parseProjectPaste(url, 'github.corp.example')).toEqual({ + kind: 'org', + owner: 'acme', + number: 7, + host: 'github.corp.example', + viewNumber: 2 + }) + expect(parseProjectPaste(url)).toBeNull() + expect( + parseProjectPaste('https://github.com/orgs/acme/projects/7', 'github.corp.example') + ).toEqual({ kind: 'org', owner: 'acme', number: 7, host: 'github.com' }) + }) + + it('rejects credentials and paths that only begin like a Project URL', () => { + expect(parseProjectPaste('https://user:token@github.com/orgs/acme/projects/1')).toBeNull() + expect(parseProjectPaste('https://github.com/orgs/acme/projects/1evil')).toBeNull() + expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/views/2evil')).toBeNull() + expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/files')).toBeNull() + }) +}) + +describe('resolveProjectRef', () => { + it('rejects oversized project refs with a metadata-only validation error', async () => { + const secret = 'project-url-secret' + const input = [ + 'https://github.com/orgs/acme/projects/42?', + secret, + 'x'.repeat(GITHUB_PROJECT_REF_INPUT_MAX_BYTES) + ].join('') + + await expect(resolveProjectRef({ input })).resolves.toEqual({ + ok: false, + error: { + type: 'validation_error', + message: GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR, + reason: 'input_too_large' + } + }) + await expect(resolveProjectRef({ input })).resolves.not.toMatchObject({ + error: { message: expect.stringContaining(secret) } + }) + }) +}) diff --git a/src/main/github/project-view/project-view-reference.ts b/src/main/github/project-view/project-view-reference.ts index 02815daf698..34c244d56c7 100644 --- a/src/main/github/project-view/project-view-reference.ts +++ b/src/main/github/project-view/project-view-reference.ts @@ -1,16 +1,21 @@ -import type { ResolveProjectRefArgs } from '../../../shared/github/project-request-types' -import { GITHUB_OWNER_NUMBER_SHORTHAND_RE } from '../../../shared/github/owner-slug' +import type { ResolveProjectRefArgs } from '../../../shared/github/projects/project-request-types' +import { + GITHUB_OWNER_NUMBER_SHORTHAND_RE, + isGitHubOwnerSlug as isValidOwnerSlug +} from '../../../shared/github/repositories/owner-slug' import type { GitHubProjectViewError, ResolveProjectRefResult -} from '../../../shared/github/project-result-types' -import type { GitHubProjectOwnerType } from '../../../shared/github/project-types' +} from '../../../shared/github/projects/project-result-types' +import type { GitHubProjectOwnerType } from '../../../shared/github/projects/project-types' import { GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR, isGitHubProjectRefInputTooLarge -} from '../../../shared/github/project-ref-input' -import { githubProjectHost } from '../../../shared/github/project-identity' -import { isValidOwnerSlug, projectGhExecOptions, runGraphql, type GraphqlVars } from './internals' +} from '../../../shared/github/projects/project-ref-input' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' + +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql, type GraphqlVars } from './project-graphql' import { getCachedOwnerType, rememberOwnerType } from './project-view-cache' import { ownerQueryRoot } from './project-view-config' diff --git a/src/main/github/project-view/project-view-table.ts b/src/main/github/project-view/project-view-table.ts index 8c69f7a2d30..2e295205ba8 100644 --- a/src/main/github/project-view/project-view-table.ts +++ b/src/main/github/project-view/project-view-table.ts @@ -1,9 +1,12 @@ -import type { GetProjectViewTableArgs } from '../../../shared/github/project-request-types' -import type { GetProjectViewTableResult } from '../../../shared/github/project-result-types' -import type { GitHubProjectTable } from '../../../shared/github/project-types' -import { githubProjectHost } from '../../../shared/github/project-identity' -import { isRenderableProjectViewLayout } from '../../../shared/github/project-types' -import { assertPositiveInt, assertSlug } from './internals' +import type { GetProjectViewTableArgs } from '../../../shared/github/projects/project-request-types' +import type { GetProjectViewTableResult } from '../../../shared/github/projects/project-result-types' +import { githubProjectHost } from '../../../shared/github/projects/project-identity' +import { + type GitHubProjectTable, + isRenderableProjectViewLayout +} from '../../../shared/github/projects/project-types' + +import { assertPositiveInt, assertSlug } from './project-argument-validation' import { fetchProjectViewsPage, fetchViewFieldsContinuation, diff --git a/src/main/github/project-view/pull-request-mutation.ts b/src/main/github/project-view/pull-request-mutation.ts index def6756c126..daa30172fc1 100644 --- a/src/main/github/project-view/pull-request-mutation.ts +++ b/src/main/github/project-view/pull-request-mutation.ts @@ -1,7 +1,9 @@ -import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' -import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' -import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' -import type { UpdatePullRequestBySlugArgs } from '../../../shared/github/project-request-types' +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls' +import { assertPositiveInt, validateSlugArgs } from './project-argument-validation' +import { projectGhExecOptions } from './project-host-execution' +import { runRest } from './project-rest' +import type { GitHubProjectMutationResult } from '../../../shared/github/projects/project-result-types' +import type { UpdatePullRequestBySlugArgs } from '../../../shared/github/projects/project-request-types' export async function updatePullRequestBySlug( args: UpdatePullRequestBySlugArgs diff --git a/src/main/github/project-view/repository-field-options.ts b/src/main/github/project-view/repository-field-options.ts index ce1d80cfbf6..4e796212e8a 100644 --- a/src/main/github/project-view/repository-field-options.ts +++ b/src/main/github/project-view/repository-field-options.ts @@ -1,27 +1,22 @@ -import { - acquire, - extractExecError, - ghExecFileAsync, - noteRepositoryRateLimitSpend, - projectGhExecOptions, - projectHostAuthenticationError, - release, - repositoryRateLimitGuard, - runGraphql, - validateSlugArgs -} from './internals' +import { acquire, release } from '../execution/github-operation-slots' +import { extractExecError } from '../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit' +import { projectGhExecOptions, projectHostAuthenticationError } from './project-host-execution' +import { runGraphql } from './project-graphql' +import { validateSlugArgs } from './project-argument-validation' import { classifyProjectError, rateLimitedError } from './project-error-classification' -import type { GitHubAssignableUser } from '../../../shared/github/pull-request-types' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' import type { ListAssignableUsersBySlugResult, ListIssueTypesBySlugResult, ListLabelsBySlugResult -} from '../../../shared/github/project-result-types' +} from '../../../shared/github/projects/project-result-types' import type { ListAssignableUsersBySlugArgs, ListIssueTypesBySlugArgs, ListLabelsBySlugArgs -} from '../../../shared/github/project-request-types' +} from '../../../shared/github/projects/project-request-types' export async function listLabelsBySlug( args: ListLabelsBySlugArgs diff --git a/src/main/github/project-view/work-item-details-body-image-adapters.test.ts b/src/main/github/project-view/work-item-details-body-image-adapters.test.ts new file mode 100644 index 00000000000..0cebd926583 --- /dev/null +++ b/src/main/github/project-view/work-item-details-body-image-adapters.test.ts @@ -0,0 +1,119 @@ +import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity' +import { beforeEach, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn(), graphql: vi.fn() })) +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: mocks.exec +})) + +vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + ghRepoExecOptions: () => ({}), + githubRepoContext: () => ({}) +})) +vi.mock('../api/rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: () => {} +})) +vi.mock('./project-argument-validation', () => ({ + assertPositiveInt: () => ({ ok: true }), + validateSlugArgs: () => ({ ok: true }) +})) + +vi.mock('./project-host-execution', () => ({ + projectGhExecOptions: () => ({}) +})) + +vi.mock('./project-graphql', () => ({ + runGraphql: mocks.graphql +})) +import { getWorkItemDetailsBySlug } from './work-item-details' + +const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' +const html = + '' +const expectedMap = { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' +} +beforeEach(() => { + mocks.exec.mockReset() + mocks.graphql.mockReset() +}) + +it.each(['issue', 'pr'] as const)( + 'recovers available slug %s data without trusting failed HTML', + async (type) => { + const root = type === 'issue' ? 'issue' : 'pullRequest' + mocks.graphql.mockResolvedValueOnce({ + ok: false, + error: { type: 'unknown', message: 'field error' }, + raw: { + stdout: JSON.stringify({ + data: { + repository: { + [root]: { + id: 'ITEM', + body, + bodyHTML: html, + comments: { + nodes: [ + { databaseId: 1, body, bodyHTML: html }, + { databaseId: 2, body, bodyHTML: html } + ] + } + } + } + }, + errors: [ + { path: ['repository', root, 'bodyHTML'] }, + { path: ['repository', root, 'comments', 'nodes', 0, 'bodyHTML'] } + ] + }), + stderr: '' + } + }) + const result = await getWorkItemDetailsBySlug({ + owner: 'acme', + repo: 'widgets', + number: 7, + type + }) + expect(result.ok && result.details.body).toBe(body) + expect(result.ok && result.details.bodyImageUrls).toBeUndefined() + expect(result.ok && result.details.comments[0].bodyImageUrls).toBeUndefined() + expect(result.ok && result.details.comments[1].bodyImageUrls).toEqual(expectedMap) + expect(mocks.graphql).toHaveBeenCalledTimes(1) + expect(mocks.exec).not.toHaveBeenCalled() + } +) + +it.each(['null parent', 'required field', 'pathless'] as const)( + 'keeps the original slug failure for %s', + async (input) => { + const error = { type: 'unknown', message: 'original failure' } + mocks.graphql.mockResolvedValueOnce({ + ok: false, + error, + raw: { + stderr: '', + stdout: JSON.stringify({ + data: { + repository: { issue: input === 'null parent' ? null : { body, bodyHTML: html } } + }, + errors: [ + { + path: + input === 'pathless' + ? undefined + : ['repository', 'issue', input === 'required field' ? 'body' : 'bodyHTML'] + } + ] + }) + } + }) + await expect( + getWorkItemDetailsBySlug({ owner: 'acme', repo: 'widgets', number: 7, type: 'issue' }) + ).resolves.toEqual({ ok: false, error: { type: 'unknown', message: 'original failure' } }) + } +) diff --git a/src/main/github/project-view/work-item-details.ts b/src/main/github/project-view/work-item-details.ts index 6323f722a13..e3f22800254 100644 --- a/src/main/github/project-view/work-item-details.ts +++ b/src/main/github/project-view/work-item-details.ts @@ -1,10 +1,12 @@ -import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../body-image-urls' -import { assertPositiveInt, projectGhExecOptions, runGraphql, validateSlugArgs } from './internals' -import type { PRComment } from '../../../shared/github/comment-types' -import type { GitHubAssignableUser } from '../../../shared/github/pull-request-types' -import type { GitHubWorkItemDetails } from '../../../shared/github/work-item-types' -import type { ProjectWorkItemDetailsBySlugResult } from '../../../shared/github/project-result-types' -import type { ProjectWorkItemDetailsBySlugArgs } from '../../../shared/github/project-request-types' +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../attachments/body-image-urls' +import { assertPositiveInt, validateSlugArgs } from './project-argument-validation' +import { projectGhExecOptions } from './project-host-execution' +import { runGraphql } from './project-graphql' +import type { PRComment } from '../../../shared/github/comments/comment-types' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' +import type { GitHubWorkItemDetails } from '../../../shared/github/work-items/work-item-types' +import type { ProjectWorkItemDetailsBySlugResult } from '../../../shared/github/projects/project-result-types' +import type { ProjectWorkItemDetailsBySlugArgs } from '../../../shared/github/projects/project-request-types' type RawUser = { login?: string; name?: string | null; avatarUrl?: string | null } type RawLabel = { name?: string; color?: string } diff --git a/src/main/github/pull-request-sidebar-query.test.ts b/src/main/github/pull-request-sidebar-query.test.ts deleted file mode 100644 index 68a1d887b27..00000000000 --- a/src/main/github/pull-request-sidebar-query.test.ts +++ /dev/null @@ -1,287 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { exec, spend } = vi.hoisted(() => ({ exec: vi.fn(), spend: vi.fn() })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - ghExecFileAsync: exec -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: vi.fn() -})) -vi.mock('./rate-limit', () => ({ - noteRepositoryRateLimitSpend: spend, - repositoryRateLimitGuard: () => ({ blocked: false }), - spendsSharedGitHubComQuota: () => false -})) - -import { getPRByNumber, lookupPRByNumber } from './client/lookup/pr-number-lookup' -import { _resetPRStackSummaryCacheForTests } from './client/lookup/pr-stack-summary-cache' -import { _resetMergeQueueCacheForTests } from './client/detect/repository-merge-metadata-cache' -import { readPullRequestSidebarQuery } from './client/lookup/pull-request-sidebar-query' -import { createImplicitDefaultBranchPRPolicy } from './client/lookup/implicit-default-branch-pr' -import { deriveCheckStatus } from './mappers' - -const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } -const options = { cwd: '/folder-workspace' } -const successCheck = { __typename: 'StatusContext', state: 'SUCCESS' } - -function commits(checks: unknown[] = [successCheck], endCursor?: string, oid = 'b'.repeat(40)) { - return { - nodes: [ - { - commit: { - oid, - checkSuites: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } }, - statusCheckRollup: { - contexts: { - nodes: checks.map((raw) => - raw && - typeof raw === 'object' && - '__typename' in raw && - raw.__typename === 'CheckRun' - ? { ...raw, checkSuite: { databaseId: 7 } } - : raw - ), - pageInfo: { hasNextPage: Boolean(endCursor), endCursor: endCursor ?? null } - } - } - } - } - ] - } -} -const fields = { - number: 42, - title: 'Keep sidebar metadata together', - state: 'CLOSED', - url: 'https://github.com/acme/widgets/pull/42', - updatedAt: '2026-10-28T00:00:00Z', - isDraft: false, - mergeable: 'UNKNOWN', - reviewDecision: null, - mergeStateStatus: 'UNKNOWN', - autoMergeRequest: null, - baseRefName: 'main', - headRefName: 'feature/sidebar', - baseRefOid: 'a'.repeat(40), - headRefOid: 'b'.repeat(40), - headRepositoryOwner: { login: 'contributor' }, - headRepository: { name: 'widgets' }, - commits: commits(), - stack: null, - stackEntry: null -} - -function response(pr: Record = fields, errors?: unknown[]) { - return { stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }) } -} - -beforeEach(() => { - vi.resetAllMocks() - _resetPRStackSummaryCacheForTests() - _resetMergeQueueCacheForTests() -}) - -describe('sidebar PR query', () => { - it('rejects a deleted fork from the parsed number query when head identity is unknown', async () => { - exec.mockResolvedValueOnce( - response({ ...fields, isCrossRepository: true, headRepository: null }) - ) - const policy = createImplicitDefaultBranchPRPolicy({ - originHeadRepo: null, - trackedUpstream: null, - branchName: fields.headRefName, - repoPath: '/folder-workspace', - localGitOptions: {}, - ghOptions: options - }) - expect( - await lookupPRByNumber({ - candidates: [repository], - number: 42, - ghOptions: options, - executionScope: 'local:host', - policy - }) - ).toEqual({ data: null, dataRepo: null }) - expect([...policy.rejectedPRUrls]).toEqual([fields.url]) - expect(exec).toHaveBeenCalledTimes(1) - }) - - it('retains PR metadata but never certifies a successful prefix after continuation failure', async () => { - exec - .mockResolvedValueOnce(response({ ...fields, commits: commits([successCheck], 'next') })) - .mockRejectedValue(new Error('Unavailable')) - await expect( - getPRByNumber(repository, 42, options, 'local:host', undefined, { includeStackSummary: true }) - ).resolves.toMatchObject({ - number: 42, - title: fields.title, - checksUnavailable: true, - statusCheckRollup: [] - }) - }) - - it('keeps a failure beyond the first 100 checks and reuses the first page', async () => { - const failingCheck = { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'FAILURE' } - exec - .mockResolvedValueOnce( - response({ - ...fields, - commits: commits( - Array.from({ length: 100 }, () => successCheck), - 'next' - ) - }) - ) - .mockResolvedValueOnce( - response({ number: 42, headRefOid: fields.headRefOid, commits: commits([failingCheck]) }) - ) - const data = await getPRByNumber(repository, 42, options, 'local:host', undefined, { - includeStackSummary: true - }) - expect(data?.statusCheckRollup).toHaveLength(101) - expect(deriveCheckStatus(data?.statusCheckRollup)).toBe('failure') - expect(exec).toHaveBeenCalledTimes(2) - expect(exec.mock.calls[1][0]).toContain('checksCursor=next') - expect(exec.mock.calls[1][0].join(' ')).not.toContain('stackEntry') - }) - - it.each([ - { number: 42, headRefOid: fields.headRefOid, commits: commits([], 'next') }, - { number: 42, headRefOid: fields.headRefOid, commits: commits([], undefined, 'c'.repeat(40)) } - ])( - 'keeps metadata without a certified summary when checks pagination stops advancing or the commit changes', - async (nextPage) => { - exec - .mockResolvedValueOnce(response({ ...fields, commits: commits([successCheck], 'next') })) - .mockResolvedValueOnce(response(nextPage)) - .mockRejectedValue(new Error('Unavailable')) - const data = await getPRByNumber(repository, 42, options, 'local:host', undefined, { - includeStackSummary: true - }) - expect(data).toMatchObject({ - number: 42, - title: fields.title, - checksUnavailable: true, - statusCheckRollup: [] - }) - } - ) - - it.each([ - { data: { repository: { pullRequest: { ...fields, number: 99 } } } }, - { - data: { repository: { pullRequest: fields } }, - errors: [{ path: ['repository', 'pullRequest', 'headRefOid'] }] - }, - { data: { repository: { pullRequest: fields } }, errors: [{ message: 'Unscoped failure' }] } - ])('falls back to the rich CLI read for an unusable response', async (envelope) => { - exec.mockResolvedValueOnce({ stdout: JSON.stringify(envelope) }).mockResolvedValueOnce({ - stdout: JSON.stringify({ ...fields, title: 'CLI fallback', statusCheckRollup: [] }) - }) - await expect( - getPRByNumber(repository, 42, options, 'local:host', undefined, { includeStackSummary: true }) - ).resolves.toMatchObject({ - title: 'CLI fallback' - }) - expect(exec.mock.calls[1][0].slice(0, 2)).toEqual(['pr', 'view']) - }) -}) - -it.each([ - { checks: [null], errors: undefined }, - { - checks: [{ __typename: 'CheckRun', status: 'FUTURE_STATUS', conclusion: null }], - errors: undefined - }, - { - checks: [successCheck], - errors: [ - { path: ['repository', 'pullRequest', 'commits', 'nodes', 0, 'commit', 'statusCheckRollup'] } - ] - } -])( - 'keeps valid metadata and stack when strict checks are unavailable: %j', - async ({ checks, errors }) => { - exec.mockResolvedValueOnce( - response( - { - ...fields, - commits: commits(checks), - stack: { number: 7, size: 2, baseRefName: 'main' }, - stackEntry: { position: 1 } - }, - errors - ) - ) - await expect(readPullRequestSidebarQuery(repository, 42, options)).resolves.toMatchObject({ - title: fields.title, - checksUnavailable: true, - stackMetadataChecked: true, - stack: { number: 7, size: 2, position: 1 } - }) - } -) - -it.each([1, 10])( - 'reuses combined exact hydration with independent context and suite populations at N=%i', - async (n) => { - const contextPages = 2 * n - const suitePages = 3 * n - exec.mockImplementation(async (args: string[]) => { - const contextCursor = args.find((arg) => arg.startsWith('checksCursor=')) - const suiteCursor = args.find((arg) => arg.startsWith('suitesCursor=')) - const contextIndex = contextCursor ? Number(contextCursor.split('=')[1]) : 0 - const suiteIndex = suiteCursor ? Number(suiteCursor.split('=')[1]) : 0 - const lastContext = contextIndex === contextPages - 1 - const commit = { - oid: fields.headRefOid, - ...(!suiteCursor - ? { - statusCheckRollup: { - contexts: { - nodes: [ - lastContext ? { __typename: 'StatusContext', state: 'FAILURE' } : successCheck - ], - pageInfo: { - hasNextPage: !lastContext, - endCursor: lastContext ? null : String(contextIndex + 1) - } - } - } - } - : {}), - ...(!contextCursor - ? { - checkSuites: { - nodes: [{ databaseId: suiteIndex + 1, conclusion: 'SUCCESS' }], - pageInfo: { - hasNextPage: suiteIndex < suitePages - 1, - endCursor: suiteIndex < suitePages - 1 ? String(suiteIndex + 1) : null - } - } - } - : {}) - } - return response({ ...fields, commits: { nodes: [{ commit }] } }) - }) - const known = { - ...fields, - stack: undefined, - statusCheckRollup: [], - headDefaultBranchName: 'trunk' - } - const observed = await getPRByNumber(repository, 42, options, 'local:host', known) - expect(observed).toMatchObject({ headDefaultBranchName: 'trunk', checksUnavailable: false }) - expect(observed?.statusCheckRollup).toHaveLength(contextPages) - expect(observed?.statusCheckRollup?.at(-1)).toEqual({ - __typename: 'StatusContext', - state: 'FAILURE' - }) - expect(exec).toHaveBeenCalledTimes(1 + (contextPages - 1) + (suitePages - 1)) - expect(exec.mock.calls.every(([args]) => args[0] === 'api' && args[1] === 'graphql')).toBe(true) - } -) diff --git a/src/main/github/conflict-summary-cache.ts b/src/main/github/pull-requests/conflicts/conflict-summary-cache.ts similarity index 95% rename from src/main/github/conflict-summary-cache.ts rename to src/main/github/pull-requests/conflicts/conflict-summary-cache.ts index 38da459528b..84b290a8044 100644 --- a/src/main/github/conflict-summary-cache.ts +++ b/src/main/github/pull-requests/conflicts/conflict-summary-cache.ts @@ -1,5 +1,5 @@ -import type { PRConflictSummary } from '../../shared/github/pull-request-types' -import { dedupeInFlightRun } from '../runtime/concurrency/in-flight-run-dedupe' +import type { PRConflictSummary } from '../../../../shared/github/pull-requests/pull-request-types' +import { dedupeInFlightRun } from '../../../runtime/concurrency/in-flight-run-dedupe' // Throttle even manual refreshes to one base fetch per minute; GitHub recomputes mergeability asynchronously. export const CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS = 60_000 diff --git a/src/main/github/conflict-summary.test.ts b/src/main/github/pull-requests/conflicts/conflict-summary.test.ts similarity index 81% rename from src/main/github/conflict-summary.test.ts rename to src/main/github/pull-requests/conflicts/conflict-summary.test.ts index 31f20c4ceef..d1881deb6cb 100644 --- a/src/main/github/conflict-summary.test.ts +++ b/src/main/github/pull-requests/conflicts/conflict-summary.test.ts @@ -9,7 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const gitExecFileAsyncMock = vi.hoisted(() => vi.fn()) const scratchFolderPrefixes = vi.hoisted((): string[] => []) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) @@ -28,8 +28,8 @@ vi.mock('node:fs/promises', async (importOriginal) => { } }) -import { findGitSubcommandIndex } from '../../shared/git/commands/git-command-classification' -import { GIT_CAPABILITY_RETRY_INTERVAL_MS } from '../../shared/git/commands/git-capability-cache' +import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification' + import { __resetPRConflictSummaryCachesForTests, getPRConflictSummary } from './conflict-summary' type GitResult = { stdout: string } @@ -112,24 +112,6 @@ describe('getPRConflictSummary caching', () => { await expect(summary).resolves.toEqual(expectedSummary) }) - it('makes no scratch folder for a Git that rejects merge-tree --write-tree, retries included', async () => { - // Git 2.25's exact rejection of both argument shapes. - const rejected = Object.assign(new Error('Command failed: git merge-tree --write-tree'), { - code: 129, - stdout: '', - stderr: 'usage: git merge-tree \n' - }) - mockGitDispatch({ 'merge-tree': () => Promise.reject(rejected) }) - - await expect(deriveSummary('head-oid-1')).resolves.toBeUndefined() - vi.setSystemTime(1_750_000_000_000 + GIT_CAPABILITY_RETRY_INTERVAL_MS + 1_000) - await expect(deriveSummary('head-oid-2')).resolves.toBeUndefined() - - expect(spawnCount('merge-tree')).toBe(2) - expect(scratchFolderPrefixes).toEqual([]) - expect(gitExecFileAsyncMock.mock.calls.filter(([, options]) => options?.env)).toEqual([]) - }) - it('runs the legacy merge-tree fallback against the scratch object store too', async () => { const commonDir = join( realpathSync(mkdtempSync(join(tmpdir(), 'orca-conflict-summary-'))), diff --git a/src/main/github/conflict-summary.ts b/src/main/github/pull-requests/conflicts/conflict-summary.ts similarity index 93% rename from src/main/github/conflict-summary.ts rename to src/main/github/pull-requests/conflicts/conflict-summary.ts index 81901981c8d..808ded34973 100644 --- a/src/main/github/conflict-summary.ts +++ b/src/main/github/pull-requests/conflicts/conflict-summary.ts @@ -1,20 +1,20 @@ -import type { PRConflictSummary } from '../../shared/github/pull-request-types' +import type { PRConflictSummary } from '../../../../shared/github/pull-requests/pull-request-types' import { isUnsupportedMergeTreeMergeBaseError, isUnsupportedMergeTreeWriteTreeError -} from '../../shared/git/branches/git-merge-tree-capability' -import { gitExecFileAsync } from '../git/command-runner/git-exec-file' +} from '../../../../shared/git/branches/git-merge-tree-capability' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { gitOptionsForWorktree, type GitRuntimeOptions -} from '../git/command-runner/git-runtime-options' -import { createLocalGitObjectQuarantine } from '../git/objects/local-git-object-quarantine' -import { _resetCanonicalRepoKeyCacheForTests } from '../git/repositories/canonical-repo-key' -import { RuntimeRemoteFetchController } from '../runtime/repositories/runtime-remote-fetch-controller' +} from '../../../git/command-runner/git-runtime-options' +import { createLocalGitObjectQuarantine } from '../../../git/objects/local-git-object-quarantine' +import { _resetCanonicalRepoKeyCacheForTests } from '../../../git/repositories/canonical-repo-key' +import { RuntimeRemoteFetchController } from '../../../runtime/repositories/runtime-remote-fetch-controller' import { clearGitCapabilityStateForTests, withLocalGitCapabilityCacheForExecution -} from '../git/command-runner/host-routing/git-capability-state' +} from '../../../git/command-runner/host-routing/git-capability-state' import { __resetPRConflictSummaryDerivationCachesForTests, buildConflictSummaryCacheKey, diff --git a/src/main/github/pr-review-comment-lines.test.ts b/src/main/github/pull-requests/files/pr-review-comment-lines.test.ts similarity index 100% rename from src/main/github/pr-review-comment-lines.test.ts rename to src/main/github/pull-requests/files/pr-review-comment-lines.test.ts diff --git a/src/main/github/pr-review-comment-lines.ts b/src/main/github/pull-requests/files/pr-review-comment-lines.ts similarity index 100% rename from src/main/github/pr-review-comment-lines.ts rename to src/main/github/pull-requests/files/pr-review-comment-lines.ts diff --git a/src/main/github/pull-request-detail-context.test.ts b/src/main/github/pull-requests/files/pull-request-detail-context.test.ts similarity index 83% rename from src/main/github/pull-request-detail-context.test.ts rename to src/main/github/pull-requests/files/pull-request-detail-context.test.ts index 064883e4f31..ffa4ae31a1e 100644 --- a/src/main/github/pull-request-detail-context.test.ts +++ b/src/main/github/pull-requests/files/pull-request-detail-context.test.ts @@ -1,9 +1,14 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { LocalGitExecOptions } from './gh-utils' +import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' const { exec, guard, spend } = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn(), spend: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: exec, +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: exec +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), githubRepoContext: ( repoPath: string, connectionId: string | null, @@ -14,7 +19,7 @@ vi.mock('./gh-utils', () => ({ ...options }) })) -vi.mock('./rate-limit', () => ({ +vi.mock('../../api/rate-limit', () => ({ repositoryRateLimitGuard: guard, noteRepositoryRateLimitSpend: spend })) @@ -123,20 +128,6 @@ describe('PR detail context requests', () => { expect(graphqlCalls()).toHaveLength(2) }) - it('keeps the three-page file bound without resending participants', async () => { - mockReads( - [1, 2, 3].map((page) => - response(undefined, { - id: 'PR_42', - files: { ...files, pageInfo: { hasNextPage: true, endCursor: `cursor-${page}` } } - }) - ) - ) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.viewedStates?.pullRequestId).toBe('PR_42') - expect(graphqlCalls()).toHaveLength(3) - }) - it('recovers participants after a failed query without retrying unavailable viewed state', async () => { mockReads([new Error('Query failed'), response()]) const result = await getPRDetailContext('/repo', 42, repository) @@ -144,12 +135,4 @@ describe('PR detail context requests', () => { expect(result.viewedStates).toBeNull() expect(graphqlCalls()).toHaveLength(2) }) - - it('loads GraphQL context with no remaining REST quota', async () => { - guard.mockImplementation((_, bucket: string) => ({ blocked: bucket === 'core' })) - mockReads([response()]) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.viewedStates?.pullRequestId).toBe('PR_42') - expect(exec).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/github/pull-request-detail-context.ts b/src/main/github/pull-requests/files/pull-request-detail-context.ts similarity index 90% rename from src/main/github/pull-request-detail-context.ts rename to src/main/github/pull-requests/files/pull-request-detail-context.ts index f99da036473..53949f5524b 100644 --- a/src/main/github/pull-request-detail-context.ts +++ b/src/main/github/pull-requests/files/pull-request-detail-context.ts @@ -2,18 +2,19 @@ import { z } from 'zod' import type { GitHubAssignableUser, GitHubPRFileViewedState -} from '../../shared/github/pull-request-types' -import { extractExecError } from '../git/command-runner/process-capture/exec-error' +} from '../../../../shared/github/pull-requests/pull-request-types' +import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' import { - ghExecFileAsync, ghRepoExecOptions, githubRepoContext, type LocalGitExecOptions -} from './gh-utils' +} from '../../repositories/github-repository-identity' -import { githubHostExecOptions, type GitHubApiRepository } from './github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' -import { getWorkItemParticipants } from './work-item-participants' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' +import { getWorkItemParticipants } from '../../work-items/work-item-participants' function detailContextQuery(includeContext: boolean): string { const context = includeContext diff --git a/src/main/github/pull-request-file-contents.ts b/src/main/github/pull-requests/files/pull-request-file-contents.ts similarity index 83% rename from src/main/github/pull-request-file-contents.ts rename to src/main/github/pull-requests/files/pull-request-file-contents.ts index 1c4ffd88ba9..333a7eaed73 100644 --- a/src/main/github/pull-request-file-contents.ts +++ b/src/main/github/pull-requests/files/pull-request-file-contents.ts @@ -1,21 +1,21 @@ -import { withGitHubRepoExecution } from './github-repository-identity' -import type { GitHubPRFile, GitHubPRFileContents } from '../../shared/github/pull-request-types' import { - acquire, - ghExecFileAsync, + withGitHubRepoExecution, ghRepoExecOptions, githubRepoContext, - release, type LocalGitExecOptions -} from './gh-utils' +} from '../../repositories/github-repository-identity' +import type { + GitHubPRFile, + GitHubPRFileContents +} from '../../../../shared/github/pull-requests/pull-request-types' +import { acquire, release } from '../../execution/github-operation-slots' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' -import { - githubHostExecOptions, - resolveGitHubRepoExecution, - type GitHubApiRepository -} from './github-api-repository' -import { isMaxBufferOverflowError } from '../git/command-runner/process-capture/max-buffer-overflow' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import { resolveGitHubRepoExecution } from '../../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import { isMaxBufferOverflowError } from '../../../git/command-runner/process-capture/max-buffer-overflow' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' const GITHUB_RAW_CONTENT_MAX_BUFFER_BYTES = 8 * 1024 * 1024 diff --git a/src/main/github/pull-request-file-data.ts b/src/main/github/pull-requests/files/pull-request-file-data.ts similarity index 86% rename from src/main/github/pull-request-file-data.ts rename to src/main/github/pull-requests/files/pull-request-file-data.ts index e4406581f91..4e177475a30 100644 --- a/src/main/github/pull-request-file-data.ts +++ b/src/main/github/pull-requests/files/pull-request-file-data.ts @@ -1,11 +1,17 @@ -import { GITHUB_BODY_MEDIA_TYPE, githubBodyImageUrls } from './body-image-urls' -import type { GitHubPRFile } from '../../shared/github/pull-request-types' +import { GITHUB_BODY_MEDIA_TYPE, githubBodyImageUrls } from '../../attachments/body-image-urls' +import type { GitHubPRFile } from '../../../../shared/github/pull-requests/pull-request-types' import type { PRFileViewedStatesResult } from './pull-request-detail-context' -import { ghExecFileAsync, ghRepoExecOptions, githubRepoContext } from './gh-utils' -import type { LocalGitExecOptions } from './gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from './github-api-repository' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { + ghRepoExecOptions, + githubRepoContext, + type LocalGitExecOptions +} from '../../repositories/github-repository-identity' + +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { getPRReviewCommentLineNumbersFromPatch } from './pr-review-comment-lines' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' const MAX_PR_FILES = 300 diff --git a/src/main/github/merged-pr-commit-membership.ts b/src/main/github/pull-requests/refresh/merged-pr-commit-membership.ts similarity index 77% rename from src/main/github/merged-pr-commit-membership.ts rename to src/main/github/pull-requests/refresh/merged-pr-commit-membership.ts index 6432356e33d..a37471dae35 100644 --- a/src/main/github/merged-pr-commit-membership.ts +++ b/src/main/github/pull-requests/refresh/merged-pr-commit-membership.ts @@ -1,18 +1,17 @@ -import { ghExecFileAsync } from './gh-utils' -import { githubReadExecutionScope } from './github-read-execution-scope' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' -import { githubHostExecOptions, type GitHubRepoExecOptions } from './github-api-repository' -import { githubRepoIdentityKey } from '../../shared/github/repository-identity-key' -import type { OwnerRepo } from './github-repository-identity' - +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' import { - MergedReviewMembershipMemo, - type MergedReviewCommitMembership -} from '../source-control/merged-review-membership-memo' + type MergedReviewCommitMembership as MergedPRCommitMembership, + MergedReviewMembershipMemo +} from '../../../source-control/merged-review-membership-memo' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' const COMMIT_PULLS_PAGE_SIZE = 100 const COMMIT_PULLS_MAX_PAGES = 5 -export type MergedPRCommitMembership = MergedReviewCommitMembership const membershipMemo = new MergedReviewMembershipMemo() export function resetMergedPRCommitMembershipCacheForTest(): void { diff --git a/src/main/github/pull-requests/refresh/merged-pr-head-membership.ts b/src/main/github/pull-requests/refresh/merged-pr-head-membership.ts new file mode 100644 index 00000000000..26a9d1da6bd --- /dev/null +++ b/src/main/github/pull-requests/refresh/merged-pr-head-membership.ts @@ -0,0 +1,38 @@ +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' +import type { HostedReviewLocalGitOptions } from '../../../source-control/hosted-review-git-options' +import { isCommitPartOfMergedPR } from './merged-pr-commit-membership' +import type { MergedReviewCommitMembership as MergedPRCommitMembership } from '../../../source-control/merged-review-membership-memo' +import { mergedReviewHeadIsEquivalent } from '../../../source-control/merged-review-head-equivalence' + +/** PR-history membership, or a local proof that HEAD is an equivalent rebase GitHub never saw. */ +export async function mergedPRHeadMembership(args: { + ownerRepo: OwnerRepo + prNumber: number + prHeadOid: string | undefined + baseRefName: string | undefined + headOid: string + ghOptions: GitHubRepoExecOptions + repoPath: string + connectionId?: string | null + localGitOptions: HostedReviewLocalGitOptions +}): Promise { + const membership = await isCommitPartOfMergedPR({ + ownerRepo: args.ownerRepo, + prNumber: args.prNumber, + commitOid: args.headOid, + ghOptions: args.ghOptions + }) + if (membership === 'contained') { + return membership + } + const equivalent = await mergedReviewHeadIsEquivalent({ + repoPath: args.repoPath, + connectionId: args.connectionId, + localGitOptions: args.localGitOptions, + reviewHeadOid: args.prHeadOid, + baseBranchName: args.baseRefName, + headOid: args.headOid + }) + return equivalent ? 'contained' : membership +} diff --git a/src/main/github/pull-requests/refresh/pr-mutation-review-invalidation.ts b/src/main/github/pull-requests/refresh/pr-mutation-review-invalidation.ts new file mode 100644 index 00000000000..71aeef45960 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-mutation-review-invalidation.ts @@ -0,0 +1,10 @@ +import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { invalidateHostedReviewBranchCache } from '../../../source-control/hosted-review-branch-cache' + +// A post-mutation refresh must not join an older lookup or reuse its cached answer. +export function invalidateReviewLookupsAfterPRMutation( + repoPath: string, + connectionId: string | null | undefined +): void { + invalidateHostedReviewBranchCache(repoPath, getRepoExecutionHostId({ connectionId })) +} diff --git a/src/main/github/pr-refresh-candidate-policy.ts b/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts similarity index 87% rename from src/main/github/pr-refresh-candidate-policy.ts rename to src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts index cb82cfe9e36..de532e3d8ad 100644 --- a/src/main/github/pr-refresh-candidate-policy.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts @@ -1,15 +1,15 @@ -import { shouldAcceptMergedFallbackPR } from '../../shared/github/pr-branch-fallback-rule' -import { reviewRefreshIntervalMs } from '../../shared/review-refresh-policy' +import { shouldAcceptMergedFallbackPR } from '../../../../shared/github/pull-requests/refresh/pr-branch-fallback-rule' +import { reviewRefreshIntervalMs } from '../../../../shared/review-refresh-policy' import type { GitHubPRRefreshAlias, GitHubPRRefreshCandidate, GitHubPRRefreshReason, GitHubPRRefreshSkippedReason, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' -import type { GitHubPRBranchLookupOptions } from './client' -import { PR_CHECK_PAGE_LIMIT } from './client/check/pr-check-rollup' -import { parsePRKey } from './pr-watch/pr-watch-types' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { GitHubPRBranchLookupOptions } from '../../client/lookup/pull-request-lookup-data' +import { PR_CHECK_PAGE_LIMIT } from '../../client/check/pr-check-rollup' +import { parsePRKey } from '../../pr-watch/pr-watch-types' export const MANUAL_MERGEABILITY_PENDING_REFRESH_MS = 2_500 export const POST_PUSH_DELAY_MS = 2_500 @@ -36,6 +36,7 @@ export function hostedReviewOptionArgs( options.acceptMergedFallbackPR = true } if (reason === 'watch') { + options.includeDerivedData = false options.checkPageLimit = PR_CHECK_PAGE_LIMIT // A watch knows its PR's repository; probing another remote by number could read another PR. const pr = requestOptions.watchPRKey ? parsePRKey(requestOptions.watchPRKey) : null @@ -166,6 +167,19 @@ export function visibleCandidateAfterOutcome( } } +const SELECTED_VISIBLE_PRIORITY = 80 +const LIST_VISIBLE_PRIORITY = 40 + +/** The selected workspace's follow-up wins the next list-budget slot; a deselected one rejoins list order. */ +export function visibleFollowUpPriority( + candidate: GitHubPRRefreshCandidate, + priority: number +): number { + return candidate.isSelected === true + ? Math.max(priority, SELECTED_VISIBLE_PRIORITY) + : Math.min(priority, LIST_VISIBLE_PRIORITY) +} + export function hasStaleHead(candidate: GitHubPRRefreshCandidate): boolean { return ( candidate.currentHeadOid != null && diff --git a/src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts similarity index 82% rename from src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts rename to src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts index af419d443a6..14c258f2d5c 100644 --- a/src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PRInfo } from '../../shared/github/pull-request-types' +import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types' const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') @@ -7,11 +7,17 @@ const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) +vi.mock('../../client/lookup/pr-for-branch-outcome', () => { + return { + getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock + } +}) +vi.mock('../../repositories/github-api-repository-remote-probe', () => { + return { + getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock + } +}) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' diff --git a/src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts similarity index 91% rename from src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts rename to src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts index 62bf28d8e2c..db6f0138965 100644 --- a/src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts @@ -6,11 +6,17 @@ const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) +vi.mock('../../client/lookup/pr-for-branch-outcome', () => { + return { + getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock + } +}) +vi.mock('../../repositories/github-api-repository-remote-probe', () => { + return { + getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock + } +}) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts new file mode 100644 index 00000000000..f5470dd7ad2 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' + +import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' + +const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') + return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } +}) +vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) +vi.mock('../../client/lookup/pr-for-branch-outcome', () => { + return { + getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock + } +}) +vi.mock('../../repositories/github-api-repository-remote-probe', () => { + return { + getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock + } +}) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) + +const { getPRForBranchOutcomeMock } = coordinatorMocks + +function found(state: 'open' | 'closed' | 'merged'): PRRefreshOutcome { + return { kind: 'found', pr: makePR({ state, checksStatus: 'success' }), fetchedAt: Date.now() } +} + +describe('main refresh completion ordering', () => { + beforeEach(() => moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks)) + afterEach(() => vi.useRealTimers()) + + it('preserves a newer failure gate when an older successful lookup completes', async () => { + let finishOlder: (outcome: PRRefreshOutcome) => void = () => {} + getPRForBranchOutcomeMock + .mockImplementationOnce( + () => new Promise((resolve) => (finishOlder = resolve)) + ) + .mockImplementation(async () => ({ + kind: 'upstream-error', + errorType: 'rate_limited', + message: 'wait', + fetchedAt: Date.now(), + retryDisabledUntil: Date.now() + 300_000 + })) + const { reportVisiblePRRefreshCandidates, refreshPRNow } = + await import('./pr-refresh-coordinator') + const candidate = makeCandidate({ isSelected: true }) + reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + await refreshPRNow(candidate) + finishOlder(found('open')) + await vi.advanceTimersByTimeAsync(60_000) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + await expect(refreshPRNow(candidate)).resolves.toMatchObject({ errorType: 'rate_limited' }) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/github/pr-refresh-coordinator-test-harness.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-harness.ts similarity index 75% rename from src/main/github/pr-refresh-coordinator-test-harness.ts rename to src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-harness.ts index 7ee455bd205..61206270714 100644 --- a/src/main/github/pr-refresh-coordinator-test-harness.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-harness.ts @@ -1,5 +1,5 @@ -import type { GitHubPRRefreshCandidate } from '../../shared/github/pull-request-refresh-types' -import type { PRInfo } from '../../shared/github/pull-request-types' +import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types' export function makeCandidate( overrides: Partial = {} diff --git a/src/main/github/pr-refresh-coordinator-test-mocks.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts similarity index 98% rename from src/main/github/pr-refresh-coordinator-test-mocks.ts rename to src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts index 2414b8514a8..cc79d26e1ea 100644 --- a/src/main/github/pr-refresh-coordinator-test-mocks.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts @@ -1,6 +1,6 @@ import type { PRRefreshRendererPort } from './pr-refresh-renderer-port' import { vi, type Mock } from 'vitest' -import { isWslUncPath } from '../../shared/wsl-paths' +import { isWslUncPath } from '../../../../shared/wsl-paths' type PRRefreshWebContentsMock = { id: number diff --git a/src/main/github/pr-refresh-coordinator-wsl-stopped-distro.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts similarity index 77% rename from src/main/github/pr-refresh-coordinator-wsl-stopped-distro.test.ts rename to src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts index 54060557c91..ae9ffdc3d13 100644 --- a/src/main/github/pr-refresh-coordinator-wsl-stopped-distro.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as WslUncAccessGateModule from '../wsl/filesystem/wsl-unc-access-gate' +import type * as WslUncAccessGateModule from '../../../wsl/filesystem/wsl-unc-access-gate' const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') @@ -12,12 +12,18 @@ const gate = vi.hoisted(() => ({ })) vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) -vi.mock('../wsl/filesystem/wsl-unc-access-gate', async (importOriginal) => ({ +vi.mock('../../client/lookup/pr-for-branch-outcome', () => { + return { + getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock + } +}) +vi.mock('../../repositories/github-api-repository-remote-probe', () => { + return { + getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock + } +}) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) +vi.mock('../../../wsl/filesystem/wsl-unc-access-gate', async (importOriginal) => ({ ...(await importOriginal()), blockedWslDistroForPath: gate.blockedWslDistroForPath, wslDistroForPath: gate.wslDistroForPath @@ -49,7 +55,8 @@ describe('PR refresh for a stopped WSL distro (E9)', () => { it("drains outside a user act that scheduled it, so a stopped distro's queue is not admitted", async () => { const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - const { isWslUserActFor, runAsWslUserAct } = await import('../wsl/discovery/wsl-user-act-scope') + const { isWslUserActFor, runAsWslUserAct } = + await import('../../../wsl/discovery/wsl-user-act-scope') const drainedInsideAct: boolean[] = [] gate.blockedWslDistroForPath.mockImplementation(async () => { drainedInsideAct.push(isWslUserActFor('Ubuntu')) diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts similarity index 97% rename from src/main/github/pr-refresh-coordinator.ts rename to src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts index 2fbb0d816ef..231f2911d74 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts @@ -2,8 +2,8 @@ import type { GitHubPRRefreshCandidate, GitHubPRRefreshReason, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' -import { getPRForBranchOutcome } from './client' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { getPRForBranchOutcome } from '../../client/lookup/pr-for-branch-outcome' import { aliasFromCandidate, hostedReviewOptionArgs, @@ -29,7 +29,10 @@ import { import { prRefreshRateLimitPausedUntil } from './pr-refresh-rate-limit-gate' import { PRRefreshRetryState } from './pr-refresh-retry-state' import { PRRefreshVisibility } from './pr-refresh-visibility' -import { blockedWslDistroForPath, wslDistroForPath } from '../wsl/filesystem/wsl-unc-access-gate' +import { + blockedWslDistroForPath, + wslDistroForPath +} from '../../../wsl/filesystem/wsl-unc-access-gate' const retry = new PRRefreshRetryState() const queue = new PRRefreshQueue((key) => retry.reset(key)) diff --git a/src/main/github/pr-refresh-error-classification.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-error-classification.test.ts similarity index 100% rename from src/main/github/pr-refresh-error-classification.test.ts rename to src/main/github/pull-requests/refresh/pr-refresh-error-classification.test.ts diff --git a/src/main/github/pr-refresh-error-classification.ts b/src/main/github/pull-requests/refresh/pr-refresh-error-classification.ts similarity index 93% rename from src/main/github/pr-refresh-error-classification.ts rename to src/main/github/pull-requests/refresh/pr-refresh-error-classification.ts index f44090b5a4f..c9f2f152db4 100644 --- a/src/main/github/pr-refresh-error-classification.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-error-classification.ts @@ -1,6 +1,6 @@ -import type { PRRefreshErrorType } from '../../shared/github/pull-request-refresh-types' -import { classifyGitHubUnavailable } from '../../shared/github/api-availability' -import { extractExecError } from '../git/command-runner/process-capture/exec-error' +import type { PRRefreshErrorType } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { classifyGitHubUnavailable } from '../../../../shared/github/api/api-availability' +import { extractExecError } from '../../../git/command-runner/process-capture/exec-error' /** Classify runner failures before UI rendering; rate-limit 403s precede permissions, and repo 404s precede network heuristics. */ export function classifyPRRefreshError(err: unknown): PRRefreshErrorType { diff --git a/src/main/github/pr-refresh-event-publisher.ts b/src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts similarity index 93% rename from src/main/github/pr-refresh-event-publisher.ts rename to src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts index 8dc831b7950..28af9df1b82 100644 --- a/src/main/github/pr-refresh-event-publisher.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts @@ -5,8 +5,8 @@ import type { GitHubPRRefreshReason, GitHubPRRefreshSkippedReason, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' -import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { recordCoalescedCrashBreadcrumb } from '../../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { prRefreshRenderers } from './pr-refresh-renderer-port' // `aliases`: every checkout the read stood for (one read can serve several linked to the same PR). diff --git a/src/main/github/pr-refresh-pacing.ts b/src/main/github/pull-requests/refresh/pr-refresh-pacing.ts similarity index 84% rename from src/main/github/pr-refresh-pacing.ts rename to src/main/github/pull-requests/refresh/pr-refresh-pacing.ts index 1644d9c7f16..2013a5e05ae 100644 --- a/src/main/github/pr-refresh-pacing.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-pacing.ts @@ -19,6 +19,7 @@ export class PRRefreshPacing { private readonly backgroundStarts: number[] = [] private readonly activeStartsByScope = new Map() private lastBackgroundStartAt = 0 + private lastBudgetedStartWasSelected = false clearActiveBurstWindow(windowId: number): void { const windowPrefix = `${windowId}::` @@ -29,7 +30,9 @@ export class PRRefreshPacing { } } - noteBackgroundStart(): void { + noteBackgroundStart(entry: PRRefreshQueueEntry): void { + this.lastBudgetedStartWasSelected = + entry.reason === 'visible' && entry.candidate.isSelected === true const now = Date.now() this.lastBackgroundStartAt = now this.backgroundStarts.push(now) @@ -50,7 +53,11 @@ export class PRRefreshPacing { return Math.max(spacingDelay, windowDelay) } - activeOrder(a: PRRefreshQueueEntry, b: PRRefreshQueueEntry): number { + order(a: PRRefreshQueueEntry, b: PRRefreshQueueEntry): number { + const priority = this.priority(b) - this.priority(a) + if (priority !== 0) { + return priority + } if (!usesActiveRefreshPacing(a) || !usesActiveRefreshPacing(b)) { return 0 } @@ -60,6 +67,16 @@ export class PRRefreshPacing { return b.queuedAt - a.queuedAt } + private priority(entry: PRRefreshQueueEntry): number { + // Reserve the next budgeted slot for other ready reviews after a selected list read. + return this.lastBudgetedStartWasSelected && + entry.reason === 'visible' && + entry.candidate.isSelected === true && + entry.bypassBackgroundBudget !== true + ? 0 + : entry.priority + } + entryDelay(entry: PRRefreshQueueEntry): number { const activeDelay = usesActiveRefreshPacing(entry) ? this.nextActiveBurstDelay(entry) : 0 if (activeDelay > 0) { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-aliases.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-aliases.ts new file mode 100644 index 00000000000..52641c52914 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-aliases.ts @@ -0,0 +1,47 @@ +import type { GitHubPRRefreshAlias } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' + +/** Retire old-branch aliases when a linked-PR key survives worktree branch changes. */ +export function setLiveAlias( + aliases: Map, + alias: GitHubPRRefreshAlias +): void { + if (alias.worktreeId) { + for (const [cacheKey, existing] of aliases) { + if (cacheKey !== alias.cacheKey && existing.worktreeId === alias.worktreeId) { + aliases.delete(cacheKey) + } + } + } + aliases.set(alias.cacheKey, alias) +} + +/** Queued aliases are newer than request-time follow-ups; preserve them with their matching candidate. */ +export function mergeFollowUpAlias( + aliases: Map, + alias: GitHubPRRefreshAlias +): GitHubPRRefreshAlias | undefined { + if (alias.worktreeId) { + for (const existing of aliases.values()) { + if (existing.worktreeId === alias.worktreeId) { + return existing + } + } + } + setLiveAlias(aliases, alias) + return undefined +} + +/** Manual refresh writes copied maps back; keep the latest branch per worktree on re-entry too. */ +export function dropSupersededWorktreeAliases(aliases: Map): void { + const liveCacheKeyByWorktree = new Map() + for (const [cacheKey, alias] of aliases) { + if (!alias.worktreeId) { + continue + } + const superseded = liveCacheKeyByWorktree.get(alias.worktreeId) + if (superseded !== undefined) { + aliases.delete(superseded) + } + liveCacheKeyByWorktree.set(alias.worktreeId, cacheKey) + } +} diff --git a/src/main/github/pr-refresh-queue-drainer.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts similarity index 94% rename from src/main/github/pr-refresh-queue-drainer.ts rename to src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts index 9f77729381f..17d3712655f 100644 --- a/src/main/github/pr-refresh-queue-drainer.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts @@ -2,8 +2,8 @@ import type { GitHubPRRefreshAlias, GitHubPRRefreshCandidate, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' -import { getPRForBranchOutcome } from './client' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { getPRForBranchOutcome } from '../../client/lookup/pr-for-branch-outcome' import { aliasFromCandidate, freshRetryAt, @@ -13,15 +13,19 @@ import { isMergeabilityPendingOutcome, sameAliasRequestIdentity, validateCandidate, - visibleCandidateAfterOutcome + visibleCandidateAfterOutcome, + visibleFollowUpPriority } from './pr-refresh-candidate-policy' import type { PRRefreshEventPublisher } from './pr-refresh-event-publisher' import { type PRRefreshPacing, usesActiveRefreshPacing } from './pr-refresh-pacing' import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' import { PRWatchJobRunner } from './pr-refresh-watch-jobs' import { prRefreshRateLimitPausedUntil } from './pr-refresh-rate-limit-gate' -import { blockedWslDistroForPath, wslDistroForPath } from '../wsl/filesystem/wsl-unc-access-gate' -import { outsideWslUserAct } from '../wsl/discovery/wsl-user-act-scope' +import { + blockedWslDistroForPath, + wslDistroForPath +} from '../../../wsl/filesystem/wsl-unc-access-gate' +import { outsideWslUserAct } from '../../../wsl/discovery/wsl-user-act-scope' import type { PRRefreshRetryState } from './pr-refresh-retry-state' import type { PRRefreshVisibility } from './pr-refresh-visibility' @@ -30,7 +34,6 @@ export type PRRefreshRegistrationCheck = (candidate: GitHubPRRefreshCandidate) = export class PRRefreshQueueDrainer { private draining = false private timer: ReturnType | null = null - // Why: queued work can outlive its project; re-check on every removal path before Git runs. private registrationCheck: PRRefreshRegistrationCheck | null = null readonly watchJobs: PRWatchJobRunner @@ -49,9 +52,7 @@ export class PRRefreshQueueDrainer { } schedule(delay = 0): void { - if (this.timer) { - clearTimeout(this.timer) - } + clearTimeout(this.timer ?? undefined) this.timer = setTimeout(() => { this.timer = null // The drain serves every queued repo; a scheduling call inside a WSL user act must not lend it that act. @@ -122,7 +123,7 @@ export class PRRefreshQueueDrainer { candidate: followUpCandidate, aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), reason: 'visible', - priority, + priority: visibleFollowUpPriority(followUpCandidate, priority), dueAt, queuedAt: this.queue.nextOrder(), bypassBackgroundBudget: pendingDueAt !== null, @@ -134,7 +135,7 @@ export class PRRefreshQueueDrainer { private ordered(): PRRefreshQueueEntry[] { this.watchJobs.age(this.queue.values(), Date.now()) - return this.queue.ordered((a, b) => this.pacing.activeOrder(a, b)) + return this.queue.ordered((a, b) => this.pacing.order(a, b)) } private nextQueuedWakeDelay(excludedKey: string): number | null { @@ -234,7 +235,7 @@ export class PRRefreshQueueDrainer { continue } if (next.bypassBackgroundBudget !== true && isBudgetedBackground(next.reason)) { - this.pacing.noteBackgroundStart() + this.pacing.noteBackgroundStart(next) this.watchJobs.noteBudgetedStart(next) } if (usesActiveRefreshPacing(next)) { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts new file mode 100644 index 00000000000..980557b97bc --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' + +const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') + return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } +}) + +vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) +vi.mock('../../client/lookup/pr-for-branch-outcome', () => { + return { + getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock + } +}) +vi.mock('../../repositories/github-api-repository-remote-probe', () => { + return { + getOriginGitHubApiRepository: coordinatorMocks.getOriginGitHubApiRepositoryMock + } +}) +vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) + +import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' + +const { getPRForBranchOutcomeMock } = coordinatorMocks +const LINKED_PR_KEY = 'local::runtime:host::/repo::pr::42' + +describe('pr-refresh queue growth bounds', () => { + beforeEach(() => { + moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) + getPRForBranchOutcomeMock.mockImplementation(async () => ({ + kind: 'found' as const, + pr: makePR({ checksStatus: 'pending' as const }), + fetchedAt: Date.now() + })) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('keeps the newer alias when a branch switch lands mid-request', async () => { + const { reportVisiblePRRefreshCandidates, _getPRRefreshAliasCountForTests } = + await import('./pr-refresh-coordinator') + + const churnCandidate = (index: number): GitHubPRRefreshCandidate => + makeCandidate({ + cacheKey: `/repo::churn/${index}`, + branch: `churn/${index}`, + worktreeId: 'wt-churn', + linkedPRNumber: 42, + cachedFetchedAt: null + }) + + let switched = false + getPRForBranchOutcomeMock.mockImplementation(async () => { + if (!switched) { + switched = true + // Re-enqueue after dequeue so the older in-flight snapshot merges into a newer queued entry. + reportVisiblePRRefreshCandidates([churnCandidate(2)], 2, 1) + } + return { + kind: 'found' as const, + pr: makePR({ checksStatus: 'pending' as const }), + fetchedAt: Date.now() + } + }) + + reportVisiblePRRefreshCandidates([churnCandidate(1)], 1, 1) + await vi.advanceTimersByTimeAsync(120_000) + + expect(_getPRRefreshAliasCountForTests(LINKED_PR_KEY)).toBe(1) + const broadcasts = coordinatorMocks.sendMock.mock.calls.filter( + (call) => call[0] === 'gh:prRefreshEvent' + ) as [string, { aliases: { cacheKey: string }[] }][] + const lastBroadcast = broadcasts.at(-1) + expect(lastBroadcast?.[1].aliases.map((alias) => alias.cacheKey)).toEqual(['/repo::churn/2']) + }) +}) diff --git a/src/main/github/pr-refresh-queue.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue.ts similarity index 83% rename from src/main/github/pr-refresh-queue.ts rename to src/main/github/pull-requests/refresh/pr-refresh-queue.ts index 57d4bfcf5b6..00caf6e68ae 100644 --- a/src/main/github/pr-refresh-queue.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue.ts @@ -1,9 +1,9 @@ -import { REVIEW_REFRESH_COOLDOWN_MS } from '../../shared/review-refresh-policy' +import { REVIEW_REFRESH_COOLDOWN_MS } from '../../../../shared/review-refresh-policy' import type { GitHubPRRefreshAlias, GitHubPRRefreshCandidate, GitHubPRRefreshReason -} from '../../shared/github/pull-request-refresh-types' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { aliasFromCandidate, bypassesFreshnessDelay, @@ -12,7 +12,8 @@ import { refreshKey, sameAliasRequestIdentity, refreshIntervalForCandidate, - shouldSkipFresh + shouldSkipFresh, + visibleFollowUpPriority } from './pr-refresh-candidate-policy' export type PRRefreshQueueEntry = { @@ -40,51 +41,11 @@ export type PRRefreshEnqueue = { type PRRefreshRequestState = { until: number; requestSequence?: number } -/** Retire old-branch aliases when a linked-PR key survives worktree branch changes. */ -function setLiveAlias( - aliases: Map, - alias: GitHubPRRefreshAlias -): void { - if (alias.worktreeId) { - for (const [cacheKey, existing] of aliases) { - if (cacheKey !== alias.cacheKey && existing.worktreeId === alias.worktreeId) { - aliases.delete(cacheKey) - } - } - } - aliases.set(alias.cacheKey, alias) -} - -/** Queued aliases are newer than request-time follow-ups; preserve them with their matching candidate. */ -function mergeFollowUpAlias( - aliases: Map, - alias: GitHubPRRefreshAlias -): GitHubPRRefreshAlias | undefined { - if (alias.worktreeId) { - for (const existing of aliases.values()) { - if (existing.worktreeId === alias.worktreeId) { - return existing - } - } - } - setLiveAlias(aliases, alias) - return undefined -} - -/** Manual refresh writes copied maps back; keep the latest branch per worktree on re-entry too. */ -function dropSupersededWorktreeAliases(aliases: Map): void { - const liveCacheKeyByWorktree = new Map() - for (const [cacheKey, alias] of aliases) { - if (!alias.worktreeId) { - continue - } - const superseded = liveCacheKeyByWorktree.get(alias.worktreeId) - if (superseded !== undefined) { - aliases.delete(superseded) - } - liveCacheKeyByWorktree.set(alias.worktreeId, cacheKey) - } -} +import { + setLiveAlias, + mergeFollowUpAlias, + dropSupersededWorktreeAliases +} from './pr-refresh-queue-aliases' export class PRRefreshQueue { private readonly entries = new Map() @@ -155,6 +116,7 @@ export class PRRefreshQueue { continue } entry.candidate = candidateFor(entry.key, entry.candidate) + entry.priority = visibleFollowUpPriority(entry.candidate, entry.priority) entry.dueAt = Math.max( freshRetryAt(entry.candidate) ?? Date.now(), this.backgroundNotBefore.get(entry.key)?.until ?? 0 @@ -313,14 +275,14 @@ export class PRRefreshQueue { } ordered( - activeOrder: (a: PRRefreshQueueEntry, b: PRRefreshQueueEntry) => number + pacingOrder: (a: PRRefreshQueueEntry, b: PRRefreshQueueEntry) => number ): PRRefreshQueueEntry[] { const now = Date.now() return Array.from(this.entries.values()).sort((a, b) => { const aReady = a.dueAt <= now const bReady = b.dueAt <= now if (aReady && bReady) { - return b.priority - a.priority || activeOrder(a, b) || a.dueAt - b.dueAt + return pacingOrder(a, b) || b.priority - a.priority || a.dueAt - b.dueAt } if (aReady !== bReady) { return aReady ? -1 : 1 diff --git a/src/main/github/pull-requests/refresh/pr-refresh-rate-limit-gate.ts b/src/main/github/pull-requests/refresh/pr-refresh-rate-limit-gate.ts new file mode 100644 index 00000000000..1b23645c2da --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-rate-limit-gate.ts @@ -0,0 +1,31 @@ +import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { getOriginGitHubApiRepository } from '../../repositories/github-api-repository-remote-probe' +import { ghRepoExecOptions, githubRepoContext } from '../../repositories/github-repository-identity' +import { + getRateLimit, + repositoryRateLimitGuard, + spendsSharedGitHubComQuota +} from '../../api/rate-limit' + +const BUCKETS = ['core', 'graphql'] as const + +export async function prRefreshRateLimitPausedUntil( + candidate: GitHubPRRefreshCandidate, + warmSharedSnapshot: boolean +): Promise { + const executionOptions = ghRepoExecOptions( + githubRepoContext(candidate.repoPath, candidate.connectionId, candidate.localGitOptions) + ) + const repository = await getOriginGitHubApiRepository( + candidate.repoPath, + candidate.connectionId, + executionOptions + ) + if (warmSharedSnapshot && spendsSharedGitHubComQuota(repository, executionOptions)) { + await getRateLimit() + } + const blockedGuard = BUCKETS.map((bucket) => + repositoryRateLimitGuard(repository, bucket, executionOptions) + ).find((guard) => guard.blocked) + return blockedGuard?.blocked ? blockedGuard.resetAt * 1000 : null +} diff --git a/src/main/github/pr-refresh-renderer-port.ts b/src/main/github/pull-requests/refresh/pr-refresh-renderer-port.ts similarity index 100% rename from src/main/github/pr-refresh-renderer-port.ts rename to src/main/github/pull-requests/refresh/pr-refresh-renderer-port.ts diff --git a/src/main/github/pr-refresh-retry-state.ts b/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts similarity index 90% rename from src/main/github/pr-refresh-retry-state.ts rename to src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts index b4999b9c04d..13a29365156 100644 --- a/src/main/github/pr-refresh-retry-state.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts @@ -1,8 +1,8 @@ import type { GitHubPRRefreshCandidate, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' -import { lookupBackoffDelayMs } from '../source-control/hosted-review-refresh-pacing' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { lookupBackoffDelayMs } from '../../../source-control/hosted-review-refresh-pacing' import { refreshIntervalForCandidate } from './pr-refresh-candidate-policy' export class PRRefreshRetryState { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-validation-backoff.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-validation-backoff.test.ts new file mode 100644 index 00000000000..4fc489afcda --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-validation-backoff.test.ts @@ -0,0 +1,45 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { recordCoalescedCrashBreadcrumbMock } = vi.hoisted(() => ({ + recordCoalescedCrashBreadcrumbMock: vi.fn() +})) + +vi.mock('../../../crash-reporting/breadcrumbs/crash-breadcrumb-store', () => ({ + recordCoalescedCrashBreadcrumb: recordCoalescedCrashBreadcrumbMock +})) + +import { + clearPRRefreshValidationBackoffForTests, + notePRRefreshValidationDenial +} from './pr-refresh-validation-backoff' + +describe('PR refresh validation backoff', () => { + beforeEach(() => { + clearPRRefreshValidationBackoffForTests() + recordCoalescedCrashBreadcrumbMock.mockReset() + }) + + it('records path-safe diagnostic breadcrumbs', () => { + notePRRefreshValidationDenial( + { + repoId: 'repo-1', + repoPath: '/Users/alice/private/project', + reason: 'repo-path-mismatch' + }, + 0 + ) + + expect(recordCoalescedCrashBreadcrumbMock).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'pr_refresh_validation_skip', + data: expect.objectContaining({ + reason: 'repo-path-mismatch', + result: 'recorded', + token: expect.any(String) + }) + }) + ) + const payload = recordCoalescedCrashBreadcrumbMock.mock.calls[0]?.[0] + expect(JSON.stringify(payload)).not.toContain('/Users/alice/private/project') + }) +}) diff --git a/src/main/github/pr-refresh-validation-backoff.ts b/src/main/github/pull-requests/refresh/pr-refresh-validation-backoff.ts similarity index 96% rename from src/main/github/pr-refresh-validation-backoff.ts rename to src/main/github/pull-requests/refresh/pr-refresh-validation-backoff.ts index 768b65c0bc6..c4d095037de 100644 --- a/src/main/github/pr-refresh-validation-backoff.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-validation-backoff.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import { resolve } from 'node:path' -import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordCoalescedCrashBreadcrumb } from '../../../crash-reporting/breadcrumbs/crash-breadcrumb-store' const VALIDATION_BACKOFF_TTL_MS = 5 * 60_000 const MAX_VALIDATION_BACKOFF_ENTRIES = 256 diff --git a/src/main/github/pr-refresh-visibility.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-visibility.test.ts similarity index 100% rename from src/main/github/pr-refresh-visibility.test.ts rename to src/main/github/pull-requests/refresh/pr-refresh-visibility.test.ts diff --git a/src/main/github/pr-refresh-visibility.ts b/src/main/github/pull-requests/refresh/pr-refresh-visibility.ts similarity index 96% rename from src/main/github/pr-refresh-visibility.ts rename to src/main/github/pull-requests/refresh/pr-refresh-visibility.ts index 1ed101de164..d46cf26cefa 100644 --- a/src/main/github/pr-refresh-visibility.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-visibility.ts @@ -1,4 +1,4 @@ -import type { GitHubPRRefreshCandidate } from '../../shared/github/pull-request-refresh-types' +import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { refreshKey } from './pr-refresh-candidate-policy' import { prRefreshRenderers } from './pr-refresh-renderer-port' diff --git a/src/main/github/pull-requests/refresh/pr-refresh-watch-derived-data.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-watch-derived-data.test.ts new file mode 100644 index 00000000000..9d47254c3bc --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-watch-derived-data.test.ts @@ -0,0 +1,128 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PullRequestLookupData } from '../../client/lookup/pull-request-lookup-data' +import { makeCandidate } from './pr-refresh-coordinator-test-harness' + +const fixture = vi.hoisted(() => ({ + lookup: vi.fn(), + conflict: vi.fn(), + stack: { number: 2, position: 1, size: 2, baseRefName: 'main', baseSha: 'base-sha' } +})) +vi.mock('../../repositories/github-api-repository', () => ({ + resolveGitHubApiRepositoryCandidates: async () => ({ + candidates: [{ owner: 'acme', repo: 'widgets' }], + headRepo: { owner: 'acme', repo: 'widgets' } + }) +})) + +vi.mock('../../repositories/github-api-repository-remote-probe', () => ({ + getOriginGitHubApiRepository: async () => ({ owner: 'acme', repo: 'widgets' }) +})) +vi.mock('../../api/rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + spendsSharedGitHubComQuota: () => false +})) +vi.mock('../../client/lookup/pr-number-lookup', () => ({ lookupPRByNumber: fixture.lookup })) +vi.mock('../../client/lookup/pr-stack-summary-cache', () => ({ + getCachedGitHubPRStackSummary: async () => fixture.stack +})) +vi.mock('../stacks/github-pr-stack', () => ({ + hydrateGitHubPRStack: async () => fixture.stack +})) +vi.mock('../../client/detect/repository-merge-metadata', () => ({ + detectRepositoryMergeMetadata: async () => ({ mergeQueueRequired: true }) +})) +vi.mock('../conflicts/conflict-summary', () => ({ + getPRConflictSummary: fixture.conflict +})) + +const data: PullRequestLookupData = { + number: 12, + title: 'Conflicting change', + state: 'OPEN', + url: 'https://github.com/acme/widgets/pull/12', + updatedAt: '2026-11-11T00:00:00Z', + mergeable: 'CONFLICTING', + baseRefName: 'main', + baseRefOid: 'base-sha', + headRefName: 'topic', + headRefOid: 'head-sha', + checksUnavailable: false, + statusCheckRollup: [{ __typename: 'CheckRun', name: 'build', status: 'IN_PROGRESS' }] +} +const summary = { baseRef: 'main', baseCommit: 'base-sh', commitsBehind: 1, files: ['a.ts'] } + +afterEach(() => vi.useRealTimers()) + +it('watches preserve provider checks while full and phone reads retain derived details', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + fixture.lookup.mockImplementation(async () => ({ + data: { ...data }, + dataRepo: { owner: 'acme', repo: 'widgets' } + })) + fixture.conflict.mockResolvedValue(summary) + const { addPRRefreshOutcomeObserver, schedulePRWatchRead } = + await import('./pr-refresh-coordinator') + const { getPRForBranchOutcome, readRecentPhonePROutcome } = + await import('../../client/lookup/pr-for-branch-outcome') + const candidate = makeCandidate({ branch: 'topic', linkedPRNumber: 12 }) + const watched = Promise.withResolvers() + const unsubscribe = addPRRefreshOutcomeObserver((_, outcome) => watched.resolve(outcome)) + schedulePRWatchRead({ prKey: 'github.com/acme/widgets#12' }, candidate, Date.now()) + await vi.advanceTimersByTimeAsync(0) + const watch = await watched.promise + unsubscribe() + expect(watch).toMatchObject({ + kind: 'found', + pr: { number: 12, headSha: 'head-sha', state: 'open', checksStatus: 'pending' } + }) + if (watch.kind !== 'found') { + throw new Error('watch did not find the PR') + } + expect(watch.pr.conflictSummary).toBeUndefined() + expect(watch.pr.stack).toBeUndefined() + expect(watch.pr.mergeQueueRequired).toBeUndefined() + + // An uncapped partial read must also stay separate from a concurrent full read. + const provider = Promise.withResolvers() + const entered = Promise.withResolvers() + const conflict = Promise.withResolvers() + fixture.lookup.mockImplementation(async () => { + entered.resolve() + await provider.promise + return { data: { ...data }, dataRepo: { owner: 'acme', repo: 'widgets' } } + }) + fixture.conflict.mockReturnValue(conflict.promise) + const partial = getPRForBranchOutcome('/repo', 'topic', 12, null, null, { + includeDerivedData: false + }) + await entered.promise + const full = getPRForBranchOutcome('/repo', 'topic', 12, null, null) + provider.resolve() + try { + expect(await partial).toMatchObject({ kind: 'found', pr: { conflictSummary: undefined } }) + expect( + await readRecentPhonePROutcome('/repo', 'topic', 12, null, null, { + currentHeadOid: 'head-sha' + }) + ).toBeNull() + } finally { + conflict.resolve(summary) + } + const complete = await full + expect(complete).toMatchObject({ + kind: 'found', + pr: { + number: 12, + headSha: 'head-sha', + checksStatus: 'pending', + conflictSummary: { files: ['a.ts'], commitsBehind: 1 }, + stack: { number: 2, baseRefName: 'main' }, + mergeQueueRequired: true + } + }) + expect( + await readRecentPhonePROutcome('/repo', 'topic', 12, null, null, { currentHeadOid: 'head-sha' }) + ).toEqual(complete) +}) diff --git a/src/main/github/pr-refresh-watch-jobs.ts b/src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts similarity index 91% rename from src/main/github/pr-refresh-watch-jobs.ts rename to src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts index 861f60efcd1..9551d0e28a0 100644 --- a/src/main/github/pr-refresh-watch-jobs.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts @@ -1,9 +1,9 @@ import type { GitHubPRRefreshCandidate, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' -import type { PRInfo } from '../../shared/github/pull-request-types' -import { reviewRefreshIntervalMs } from '../../shared/review-refresh-policy' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types' +import { reviewRefreshIntervalMs } from '../../../../shared/review-refresh-policy' import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' import type { PRRefreshRetryState } from './pr-refresh-retry-state' @@ -103,7 +103,10 @@ export class PRWatchJobRunner { } noteBudgetedStart(entry: PRRefreshQueueEntry): void { - this.lastBudgetedStartWasWatch = entry.watch !== undefined + // Selected list reads have their own reserved turn; preserve the watch/list alternation. + if (entry.reason !== 'visible' || entry.candidate.isSelected !== true) { + this.lastBudgetedStartWasWatch = entry.watch !== undefined + } } /** Re-ranks watch entries before each pick, so aging needs no change to the queue's order. */ diff --git a/src/main/github/pull-request-changed-events.test.ts b/src/main/github/pull-requests/refresh/pull-request-changed-events.test.ts similarity index 93% rename from src/main/github/pull-request-changed-events.test.ts rename to src/main/github/pull-requests/refresh/pull-request-changed-events.test.ts index 2f846d7612a..e7e56edb336 100644 --- a/src/main/github/pull-request-changed-events.test.ts +++ b/src/main/github/pull-requests/refresh/pull-request-changed-events.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { GitHubPRRefreshCandidate } from '../../shared/github/pull-request-refresh-types' -import type { PRInfo } from '../../shared/github/pull-request-types' +import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types' import { pullRequestChangeObserver, type PullRequestChange } from './pull-request-changed-events' const candidate: GitHubPRRefreshCandidate = { diff --git a/src/main/github/pull-request-changed-events.ts b/src/main/github/pull-requests/refresh/pull-request-changed-events.ts similarity index 89% rename from src/main/github/pull-request-changed-events.ts rename to src/main/github/pull-requests/refresh/pull-request-changed-events.ts index a7171c3a76d..d334e7be290 100644 --- a/src/main/github/pull-request-changed-events.ts +++ b/src/main/github/pull-requests/refresh/pull-request-changed-events.ts @@ -1,6 +1,6 @@ -import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' -import type { CheckStatus } from '../../shared/github/pull-request-types' -import type { RuntimeClientEvent } from '../../shared/runtime-client-events' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { CheckStatus } from '../../../../shared/github/pull-requests/pull-request-types' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' import type { PRRefreshOutcomeObserver } from './pr-refresh-event-publisher' export type PullRequestChange = Omit< diff --git a/src/main/github/github-pr-stack-async-merge.ts b/src/main/github/pull-requests/stacks/github-pr-stack-async-merge.ts similarity index 86% rename from src/main/github/github-pr-stack-async-merge.ts rename to src/main/github/pull-requests/stacks/github-pr-stack-async-merge.ts index 9f999484e5f..5d91a577ee8 100644 --- a/src/main/github/github-pr-stack-async-merge.ts +++ b/src/main/github/pull-requests/stacks/github-pr-stack-async-merge.ts @@ -1,12 +1,10 @@ -import type { GitHubPRMergeMethod } from '../../shared/github/pull-request-types' -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -import { acquire, release } from './gh-utils' -import { - githubHostExecOptions, - type GitHubApiRepository, - type GitHubRepoExecOptions -} from './github-api-repository' -import { codeHostFailure } from '../../shared/code-host-failure-copy' +import type { GitHubPRMergeMethod } from '../../../../shared/github/pull-requests/pull-request-types' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { acquire, release } from '../../execution/github-operation-slots' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' +import { codeHostFailure } from '../../../../shared/code-host-failure-copy' const POLL_INTERVAL_MS = 1_000 const MAX_POLLS = 180 diff --git a/src/main/github/github-pr-stack.test.ts b/src/main/github/pull-requests/stacks/github-pr-stack.test.ts similarity index 85% rename from src/main/github/github-pr-stack.test.ts rename to src/main/github/pull-requests/stacks/github-pr-stack.test.ts index 0447ca3b7df..402fca60bf5 100644 --- a/src/main/github/github-pr-stack.test.ts +++ b/src/main/github/pull-requests/stacks/github-pr-stack.test.ts @@ -6,15 +6,16 @@ const { ghExecFileAsyncMock, rateLimitGuardMock, noteRateLimitSpendMock } = vi.h noteRateLimitSpendMock: vi.fn() })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) -vi.mock('./rate-limit', () => ({ +vi.mock('../../api/rate-limit', () => ({ repositoryRateLimitGuard: rateLimitGuardMock, noteRepositoryRateLimitSpend: noteRateLimitSpendMock })) -import { _resetGitHubPRStackCacheForTests, mergeGitHubPRStack } from './github-pr-stack' +import { _resetGitHubPRStackCacheForTests } from './github-pr-stack' +import { mergeGitHubPRStack } from './github-pr-stack-async-merge' const repository = { owner: 'stablyai', repo: 'orca', host: 'github.com' } diff --git a/src/main/github/github-pr-stack.ts b/src/main/github/pull-requests/stacks/github-pr-stack.ts similarity index 91% rename from src/main/github/github-pr-stack.ts rename to src/main/github/pull-requests/stacks/github-pr-stack.ts index fac1742b00f..e20b8a64bb0 100644 --- a/src/main/github/github-pr-stack.ts +++ b/src/main/github/pull-requests/stacks/github-pr-stack.ts @@ -5,16 +5,14 @@ import type { PRMergeableState, PRReviewDecision, PRState -} from '../../shared/github/pull-request-types' -import { githubRepoIdentityKey } from '../../shared/github/repository-identity-key' -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -import { githubReadExecutionScope } from './github-read-execution-scope' -import { - githubHostExecOptions, - type GitHubApiRepository, - type GitHubRepoExecOptions -} from './github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' +} from '../../../../shared/github/pull-requests/pull-request-types' +import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit' const STACK_CACHE_TTL_MS = 30_000 const STACK_CACHE_MAX_ENTRIES = 256 @@ -281,5 +279,3 @@ export async function hydrateGitHubPRStack( } } } - -export { mergeGitHubPRStack } from './github-pr-stack-async-merge' diff --git a/src/main/github/github-stack-api-responses.ts b/src/main/github/pull-requests/stacks/github-stack-api-responses.ts similarity index 93% rename from src/main/github/github-stack-api-responses.ts rename to src/main/github/pull-requests/stacks/github-stack-api-responses.ts index 6d312db90d6..dc80b86ca80 100644 --- a/src/main/github/github-stack-api-responses.ts +++ b/src/main/github/pull-requests/stacks/github-stack-api-responses.ts @@ -1,4 +1,4 @@ -import type { HostedReviewSummary } from '../../shared/source-control/hosted-review/hosted-review-contracts' +import type { HostedReviewSummary } from '../../../../shared/source-control/hosted-review/hosted-review-contracts' export type NumberedHostedReviewSummary = Omit & { number: number } diff --git a/src/main/github/stacked-pr-creation.test.ts b/src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts similarity index 88% rename from src/main/github/stacked-pr-creation.test.ts rename to src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts index 5c7a800bf37..138059d4e61 100644 --- a/src/main/github/stacked-pr-creation.test.ts +++ b/src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts @@ -1,3 +1,4 @@ +import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' import { beforeEach, describe, expect, it, vi } from 'vitest' const { ghExecFileAsyncMock, repositoryMock } = vi.hoisted(() => ({ @@ -5,10 +6,17 @@ const { ghExecFileAsyncMock, repositoryMock } = vi.hoisted(() => ({ repositoryMock: vi.fn() })) -vi.mock('./gh-utils', () => ({ +vi.mock('../../execution/github-operation-slots', () => ({ acquire: vi.fn(), - release: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, + release: vi.fn() +})) + +vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), ghRepoExecOptions: (context: { repoPath: string; connectionId?: string | null }) => context.connectionId ? {} : { cwd: context.repoPath }, githubRepoContext: ( @@ -18,8 +26,11 @@ vi.mock('./gh-utils', () => ({ ) => ({ repoPath, connectionId, localGitOptions }) })) -vi.mock('./github-api-repository', () => ({ - getOriginGitHubApiRepository: repositoryMock, +vi.mock('../../repositories/github-api-repository-remote-probe', () => ({ + getOriginGitHubApiRepository: repositoryMock +})) + +vi.mock('../../repositories/github-repository-host', () => ({ githubHostExecOptions: (repository: { host?: string }) => ({ host: repository.host }) })) diff --git a/src/main/github/stacked-pr-creation.ts b/src/main/github/pull-requests/stacks/stacked-pr-creation.ts similarity index 88% rename from src/main/github/stacked-pr-creation.ts rename to src/main/github/pull-requests/stacks/stacked-pr-creation.ts index 025b3c0cb8b..aaf54d9d4c2 100644 --- a/src/main/github/stacked-pr-creation.ts +++ b/src/main/github/pull-requests/stacks/stacked-pr-creation.ts @@ -1,24 +1,24 @@ -import type { ExecutionHostId } from '../../shared/execution-host' -import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { hostedReviewSshConnectionId } from '../../../source-control/hosted-review-execution-host' import type { CreateStackedHostedReviewInput, CreateStackedHostedReviewResult -} from '../../shared/source-control/hosted-review/hosted-review-contracts' -import { isDefaultGitHubHost } from '../../shared/github/repository-identity-key' +} from '../../../../shared/source-control/hosted-review/hosted-review-contracts' +import { isDefaultGitHubHost } from '../../../../shared/github/repositories/repository-identity-key' import { normalizeHostedReviewBaseRef, normalizeHostedReviewHeadRef -} from '../../shared/source-control/hosted-review/hosted-review-refs' -import { acquire, ghExecFileAsync, ghRepoExecOptions, githubRepoContext, release } from './gh-utils' -import { - getOriginGitHubApiRepository, - githubHostExecOptions, - type GitHubApiRepository -} from './github-api-repository' +} from '../../../../shared/source-control/hosted-review/hosted-review-refs' +import { acquire, release } from '../../execution/github-operation-slots' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { ghRepoExecOptions, githubRepoContext } from '../../repositories/github-repository-identity' +import { getOriginGitHubApiRepository } from '../../repositories/github-api-repository-remote-probe' +import { githubHostExecOptions } from '../../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../../shared/github/repositories/repository-identity' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions -} from '../source-control/hosted-review-git-options' +} from '../../../source-control/hosted-review-git-options' import { parseGitHubStackPullRequests, parseGitHubStacks, @@ -26,7 +26,7 @@ import { type GitHubStackPullRequest, type NumberedHostedReviewSummary } from './github-stack-api-responses' -import { stackedReviewFailure } from '../../shared/source-control/hosted-review/stacked-hosted-review-failure-copy' +import { stackedReviewFailure } from '../../../../shared/source-control/hosted-review/stacked-hosted-review-failure-copy' type StackedPullRequestPlan = | { diff --git a/src/main/github/pr-head-tracking-ref.test.ts b/src/main/github/pull-requests/start-points/pr-head-tracking-ref.test.ts similarity index 91% rename from src/main/github/pr-head-tracking-ref.test.ts rename to src/main/github/pull-requests/start-points/pr-head-tracking-ref.test.ts index 1a49de8278d..f1680f37592 100644 --- a/src/main/github/pr-head-tracking-ref.test.ts +++ b/src/main/github/pull-requests/start-points/pr-head-tracking-ref.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) diff --git a/src/main/github/pr-head-tracking-ref.ts b/src/main/github/pull-requests/start-points/pr-head-tracking-ref.ts similarity index 83% rename from src/main/github/pr-head-tracking-ref.ts rename to src/main/github/pull-requests/start-points/pr-head-tracking-ref.ts index f49ce5ae2da..ce8c4739afc 100644 --- a/src/main/github/pr-head-tracking-ref.ts +++ b/src/main/github/pull-requests/start-points/pr-head-tracking-ref.ts @@ -1,17 +1,17 @@ -import { gitExecFileAsync } from '../git/command-runner/git-exec-file' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { githubPullRequestHeadLocalRef, isSafeReviewHeadFetchRemote, isValidReviewHeadNumber, REVIEW_HEAD_FETCH_TIMEOUT_MS -} from '../../shared/review-head-tracking-ref' -import { getReviewHeadRemoteComponent } from '../git/remotes/review-head-remote-identity' +} from '../../../../shared/review-head-tracking-ref' +import { getReviewHeadRemoteComponent } from '../../../git/remotes/review-head-remote-identity' import { SSH_GIT_RECONNECT_MESSAGE, SshHostNotServedError -} from '../providers/ssh-host-not-served-error' -import { getRepoRoutingConnectionId } from '../../shared/execution-host' -import type { Repo } from '../../shared/repo-types' +} from '../../../providers/ssh-host-not-served-error' +import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' +import type { Repo } from '../../../../shared/repo-types' type LocalGitExecOptions = { cwd: string diff --git a/src/main/github/pr-start-point-wsl-gate.ts b/src/main/github/pull-requests/start-points/pr-start-point-wsl-gate.ts similarity index 81% rename from src/main/github/pr-start-point-wsl-gate.ts rename to src/main/github/pull-requests/start-points/pr-start-point-wsl-gate.ts index 7cd1665c67a..0bd2d02a041 100644 --- a/src/main/github/pr-start-point-wsl-gate.ts +++ b/src/main/github/pull-requests/start-points/pr-start-point-wsl-gate.ts @@ -1,10 +1,10 @@ -import { wslDistroStoppedMessage } from '../../shared/wsl-distro-not-running-refusal' -import type { ReviewStartPointFailure } from '../../shared/review-start-point-failure-copy' +import { wslDistroStoppedMessage } from '../../../../shared/wsl-distro-not-running-refusal' +import type { ReviewStartPointFailure } from '../../../../shared/review-start-point-failure-copy' import { guardWslUncPathAccess, WslDistroStoppedError, WslDistroUnverifiableError -} from '../wsl/filesystem/wsl-unc-access-gate' +} from '../../../wsl/filesystem/wsl-unc-access-gate' /** * Resolves a PR start point unless its repo's WSL distro is stopped (E9): a background push-target diff --git a/src/main/github/pr-start-point.test.ts b/src/main/github/pull-requests/start-points/pr-start-point.test.ts similarity index 96% rename from src/main/github/pr-start-point.test.ts rename to src/main/github/pull-requests/start-points/pr-start-point.test.ts index f3bab273c52..0284bf81769 100644 --- a/src/main/github/pr-start-point.test.ts +++ b/src/main/github/pull-requests/start-points/pr-start-point.test.ts @@ -5,13 +5,16 @@ const { getPullRequestPushTargetMock, getWorkItemMock } = vi.hoisted(() => ({ getWorkItemMock: vi.fn() })) -vi.mock('./client', () => ({ - getPullRequestPushTarget: getPullRequestPushTargetMock, +vi.mock('../../client/lookup/pull-request-push-target', () => ({ + getPullRequestPushTarget: getPullRequestPushTargetMock +})) + +vi.mock('../../client/fetch/get-work-item', () => ({ getWorkItem: getWorkItemMock })) import { resolveGitHubPrStartPoint } from './pr-start-point' -import { reviewHeadRemoteRefComponent } from '../../shared/review-head-tracking-ref' +import { reviewHeadRemoteRefComponent } from '../../../../shared/review-head-tracking-ref' const ORIGIN_URL = 'git@github.com:acme/orca.git' const ORIGIN_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_URL) diff --git a/src/main/github/pr-start-point.ts b/src/main/github/pull-requests/start-points/pr-start-point.ts similarity index 90% rename from src/main/github/pr-start-point.ts rename to src/main/github/pull-requests/start-points/pr-start-point.ts index 9428809d5c3..7f20de2c027 100644 --- a/src/main/github/pr-start-point.ts +++ b/src/main/github/pull-requests/start-points/pr-start-point.ts @@ -1,16 +1,17 @@ -import { withGitHubRepoExecution } from './github-repository-identity' -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { GhAccountBinding } from '../../shared/github/account-binding' -import type { GitHubPrStartPoint, GitPushTarget } from '../../shared/worktree/types' -import { fetchCompareBaseRefWithLocalFallback } from '../git/remotes/compare-base-ref-fetch' -import { isMissingRemoteRefGitError } from '../../shared/git/refs/git-missing-remote-ref' -import { isTransientReviewHeadFetchError } from '../git/remotes/fetch-error-classification' -import { getPullRequestPushTarget, getWorkItem } from './client' +import { withGitHubRepoExecution } from '../../repositories/github-repository-identity' +import type { IssueSourcePreference } from '../../../../shared/repo-types' +import type { GhAccountBinding } from '../../../../shared/github/accounts/account-binding' +import type { GitHubPrStartPoint, GitPushTarget } from '../../../../shared/worktree/types' +import { fetchCompareBaseRefWithLocalFallback } from '../../../git/remotes/compare-base-ref-fetch' +import { isMissingRemoteRefGitError } from '../../../../shared/git/refs/git-missing-remote-ref' +import { isTransientReviewHeadFetchError } from '../../../git/remotes/fetch-error-classification' +import { getPullRequestPushTarget } from '../../client/lookup/pull-request-push-target' +import { getWorkItem } from '../../client/fetch/get-work-item' import { githubPullRequestHeadLocalRef, reviewHeadRemoteRefComponent -} from '../../shared/review-head-tracking-ref' -import { reviewStartPointFailure } from '../../shared/review-start-point-failure-copy' +} from '../../../../shared/review-head-tracking-ref' +import { reviewStartPointFailure } from '../../../../shared/review-start-point-failure-copy' type GitExec = (args: string[]) => Promise<{ stdout: string; stderr: string }> diff --git a/src/main/github/review-head-remote.ts b/src/main/github/pull-requests/start-points/review-head-remote.ts similarity index 77% rename from src/main/github/review-head-remote.ts rename to src/main/github/pull-requests/start-points/review-head-remote.ts index 7089a78bec5..89c4dc1069e 100644 --- a/src/main/github/review-head-remote.ts +++ b/src/main/github/pull-requests/start-points/review-head-remote.ts @@ -1,8 +1,8 @@ -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { GhAccountBinding } from '../../shared/github/account-binding' -import { pickPreferredGitRemote } from '../../shared/preferred-git-remote' -import { getDefaultRemote } from '../git/remotes/repo-remote-queries' -import { getGitHubApiRepositoryForRemote } from './github-api-repository' +import type { IssueSourcePreference } from '../../../../shared/repo-types' +import type { GhAccountBinding } from '../../../../shared/github/accounts/account-binding' +import { pickPreferredGitRemote } from '../../../../shared/preferred-git-remote' +import { getDefaultRemote } from '../../../git/remotes/repo-remote-queries' +import { getGitHubApiRepositoryForRemote } from '../../repositories/github-api-repository-remote-probe' type GitExec = (args: string[]) => Promise<{ stdout: string; stderr: string }> diff --git a/src/main/github/github-api-repository-probe.ts b/src/main/github/repositories/github-api-repository-probe.ts similarity index 100% rename from src/main/github/github-api-repository-probe.ts rename to src/main/github/repositories/github-api-repository-probe.ts diff --git a/src/main/github/repositories/github-api-repository-remote-probe.test.ts b/src/main/github/repositories/github-api-repository-remote-probe.test.ts new file mode 100644 index 00000000000..fe39dadd3a9 --- /dev/null +++ b/src/main/github/repositories/github-api-repository-remote-probe.test.ts @@ -0,0 +1,68 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as GitExecFileModule from '../../git/command-runner/git-exec-file' + +const { gitExecFileAsyncMock } = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn<(args: string[]) => Promise<{ stdout: string; stderr: string }>>() +})) + +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: gitExecFileAsyncMock +})) + +import { _resetOwnerRepoCache } from './github-repository-identity' +import { _resetRemoteNameListingCache } from '../../git/remotes/remote-name-listing' +import { + _resetOriginGitHubApiRepositoryCache, + getGitHubApiRepositoryForRemote +} from './github-api-repository-remote-probe' + +// Why: no real .git config means no config signature, so caches use their short unsigned TTLs. +const REPO_PATH = '/does-not-exist/orca-remote-probe-fixture' + +function mockRemotes(remotes: Record): void { + gitExecFileAsyncMock.mockImplementation((args) => { + if (args[0] === 'remote' && args.length === 1) { + return Promise.resolve({ stdout: Object.keys(remotes).join('\n'), stderr: '' }) + } + if (args[0] === 'remote' && args[1] === 'get-url') { + const url = remotes[args[2]] + if (url) { + return Promise.resolve({ stdout: `${url}\n`, stderr: '' }) + } + return Promise.reject( + Object.assign(new Error(`git remote get-url ${args[2]}`), { + stderr: `error: No such remote '${args[2]}'` + }) + ) + } + return Promise.reject(new Error(`unexpected git exec: ${JSON.stringify(args)}`)) + }) +} + +beforeEach(() => { + vi.useFakeTimers() + gitExecFileAsyncMock.mockReset() + _resetOriginGitHubApiRepositoryCache() + _resetOwnerRepoCache() + _resetRemoteNameListingCache() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('getGitHubApiRepositoryForRemote', () => { + it('still resolves a configured upstream remote', async () => { + mockRemotes({ + origin: 'https://github.com/acme/orca.git', + upstream: 'https://github.com/stablyai/orca.git' + }) + + await expect(getGitHubApiRepositoryForRemote(REPO_PATH, 'upstream')).resolves.toEqual({ + owner: 'stablyai', + repo: 'orca', + host: 'github.com' + }) + }) +}) diff --git a/src/main/github/github-api-repository-remote-probe.ts b/src/main/github/repositories/github-api-repository-remote-probe.ts similarity index 94% rename from src/main/github/github-api-repository-remote-probe.ts rename to src/main/github/repositories/github-api-repository-remote-probe.ts index b7c59ed52d0..0ebec3d2603 100644 --- a/src/main/github/github-api-repository-remote-probe.ts +++ b/src/main/github/repositories/github-api-repository-remote-probe.ts @@ -1,11 +1,12 @@ -import { withGitHubRepoExecution } from './github-repository-identity' -import type { GitHubApiRepository } from './github-api-repository' -import { shouldProbeGitRemote } from '../git/remotes/remote-name-listing' import { + withGitHubRepoExecution, getOwnerRepoForRemote, type GitHubRemoteIdentityProbeOptions, type LocalGitExecOptions -} from './gh-utils' +} from './github-repository-identity' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import { shouldProbeGitRemote } from '../../git/remotes/remote-name-listing' + import { getEnterpriseGitHubRepoSlug, getEnterpriseGitHubRepoSlugForRemote diff --git a/src/main/github/github-api-repository-validation.ts b/src/main/github/repositories/github-api-repository-validation.ts similarity index 81% rename from src/main/github/github-api-repository-validation.ts rename to src/main/github/repositories/github-api-repository-validation.ts index f0edbafb865..c7eb0956367 100644 --- a/src/main/github/github-api-repository-validation.ts +++ b/src/main/github/repositories/github-api-repository-validation.ts @@ -1,5 +1,5 @@ -import { GITHUB_OWNER_SLUG_RE } from '../../shared/github/owner-slug' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' +import { GITHUB_OWNER_SLUG_RE } from '../../../shared/github/repositories/owner-slug' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' export type GitHubApiRepositoryResolution = | GitHubOwnerRepo diff --git a/src/main/github/repositories/github-api-repository.test.ts b/src/main/github/repositories/github-api-repository.test.ts new file mode 100644 index 00000000000..023ff616841 --- /dev/null +++ b/src/main/github/repositories/github-api-repository.test.ts @@ -0,0 +1,128 @@ +import type * as GithubOwnerRepoSelectionModule from './github-owner-repo-selection' +import type * as GithubRepositoryIdentityModule from './github-repository-identity' +import type * as GithubEnterpriseRepositoryModule from './github-enterprise-repository' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + getEnterpriseGitHubRepoSlugMock, + getOwnerRepoMock, + getOwnerRepoForRemoteMock, + isGitHubHostAuthenticatedMock, + shouldProbeGitRemoteMock +} = vi.hoisted(() => ({ + getEnterpriseGitHubRepoSlugMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + getOwnerRepoForRemoteMock: vi.fn(), + isGitHubHostAuthenticatedMock: vi.fn(), + shouldProbeGitRemoteMock: vi.fn(async () => true) +})) + +vi.mock('./github-owner-repo-selection', async (importOriginal) => ({ + ...(await importOriginal()), + getOwnerRepo: getOwnerRepoMock +})) + +vi.mock('./github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + getOwnerRepoForRemote: getOwnerRepoForRemoteMock +})) + +vi.mock('./github-enterprise-repository', async (importOriginal) => ({ + ...(await importOriginal()), + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, + isGitHubHostAuthenticated: isGitHubHostAuthenticatedMock +})) + +vi.mock('../../git/remotes/remote-name-listing', () => ({ + shouldProbeGitRemote: shouldProbeGitRemoteMock +})) +import { + _resetOriginGitHubApiRepositoryCache, + getGitHubApiRepositoryForRemote +} from './github-api-repository-remote-probe' +import { resolveGitHubApiRepository, resolveGitHubRepoExecution } from './github-api-repository' + +beforeEach(() => { + _resetOriginGitHubApiRepositoryCache() + getEnterpriseGitHubRepoSlugMock.mockReset().mockResolvedValue(null) + getOwnerRepoMock.mockReset().mockResolvedValue(null) + getOwnerRepoForRemoteMock.mockReset().mockResolvedValue(null) + isGitHubHostAuthenticatedMock.mockReset().mockResolvedValue(false) + shouldProbeGitRemoteMock.mockReset().mockResolvedValue(true) +}) + +describe('resolveGitHubRepoExecution', () => { + it('rejects an explicit Enterprise host absent from the local gh auth inventory', async () => { + await expect( + resolveGitHubApiRepository( + '/remote/repo', + { + owner: 'acme', + repo: 'widgets', + host: 'evil.example.test' + }, + 'ssh-1' + ) + ).resolves.toBeNull() + + expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith( + 'evil.example.test', + '/remote/repo', + 'ssh-1', + {} + ) + }) + + it.each([ + { owner: 'acme%2Fadmin', repo: 'widgets' }, + { owner: 'acme', repo: '..' } + ])('rejects repository overrides that could alter a gh REST path: %o', async (repository) => { + await expect( + resolveGitHubApiRepository('/repo', { + ...repository, + host: 'github.com' + }) + ).resolves.toBeNull() + + expect(isGitHubHostAuthenticatedMock).not.toHaveBeenCalled() + }) + + it('rejects a host-less caller-specific resolver for a connection-backed repository', async () => { + await expect( + resolveGitHubRepoExecution( + '/remote/repo', + async () => ({ owner: 'upstream', repo: 'widgets' }), + 'ssh-1' + ) + ).resolves.toEqual({ ownerRepo: null, ghOptions: {} }) + }) + + it('preserves an authoritative null from a caller-specific resolver', async () => { + getOwnerRepoMock.mockResolvedValue({ owner: 'origin', repo: 'widgets' }) + + await expect(resolveGitHubRepoExecution('/repo', async () => null)).resolves.toEqual({ + ownerRepo: null, + ghOptions: { cwd: '/repo' } + }) + + expect(getOwnerRepoMock).not.toHaveBeenCalled() + }) +}) + +describe('origin repository cache', () => { + it('keeps an indeterminate auth inventory unverifiable during candidate discovery', async () => { + getEnterpriseGitHubRepoSlugMock.mockResolvedValue(undefined) + + await expect( + getGitHubApiRepositoryForRemote( + '/remote/repo', + 'origin', + 'ssh-1', + {}, + { + requireVerifiedSshProbe: true + } + ) + ).rejects.toThrow('GitHub repository identity is unverifiable.') + }) +}) diff --git a/src/main/github/github-api-repository.ts b/src/main/github/repositories/github-api-repository.ts similarity index 90% rename from src/main/github/github-api-repository.ts rename to src/main/github/repositories/github-api-repository.ts index 10177d912e0..7e33081061f 100644 --- a/src/main/github/github-api-repository.ts +++ b/src/main/github/repositories/github-api-repository.ts @@ -1,13 +1,19 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' -import { withGitHubRepoExecution } from './github-repository-identity' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import type { IssueSourcePreference } from '../../shared/repo-types' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import { + withGitHubRepoExecution, + ghRepoExecOptions, + githubRepoContext, + type LocalGitExecOptions +} from './github-repository-identity' + +import type { IssueSourcePreference } from '../../../shared/repo-types' import { githubRepoIdentityKey, isDefaultGitHubHost -} from '../../shared/github/repository-identity-key' -import { shouldProbeGitRemote } from '../git/remotes/remote-name-listing' -import { ghRepoExecOptions, githubRepoContext, type LocalGitExecOptions } from './gh-utils' +} from '../../../shared/github/repositories/repository-identity-key' +import { shouldProbeGitRemote } from '../../git/remotes/remote-name-listing' + import { isGitHubHostAuthenticated } from './github-enterprise-repository' import { githubHostExecOptions } from './github-repository-host' import { @@ -19,13 +25,6 @@ import { getGitHubApiRepositoryForRemote, getOriginGitHubApiRepository } from './github-api-repository-remote-probe' - -export { - githubHostExecOptions, - githubRepositorySlugArg, - githubRepositoryWebHost -} from './github-repository-host' -export type GitHubApiRepository = GitHubOwnerRepo export type GitHubRepoExecOptions = ReturnType & { host?: string env?: NodeJS.ProcessEnv @@ -34,11 +33,6 @@ export type GitHubRepoExecution = { ownerRepo: GitHubApiRepository | null ghOptions: GitHubRepoExecOptions } -export { - _resetOriginGitHubApiRepositoryCache, - getGitHubApiRepositoryForRemote, - getOriginGitHubApiRepository -} /** Hosted mirror of getIssueOwnerRepo: issues prefer `upstream` over `origin`. */ export async function getIssueGitHubApiRepository( diff --git a/src/main/github/github-enterprise-repository.test.ts b/src/main/github/repositories/github-enterprise-repository.test.ts similarity index 94% rename from src/main/github/github-enterprise-repository.test.ts rename to src/main/github/repositories/github-enterprise-repository.test.ts index ca4770a740d..1b066f87cad 100644 --- a/src/main/github/github-enterprise-repository.test.ts +++ b/src/main/github/repositories/github-enterprise-repository.test.ts @@ -9,22 +9,22 @@ const { commandExecFileAsyncMock, ghExecFileAsyncMock, gitExecFileAsyncMock, res })) // Mock only execution so identity, runtime and auth-status parsing remain real. -vi.mock('../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), commandExecFileAsync: commandExecFileAsyncMock })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../ssh/config/ssh-g-config-resolution', () => ({ +vi.mock('../../ssh/config/ssh-g-config-resolution', () => ({ resolveWithSshG: resolveWithSshGMock })) import { @@ -33,7 +33,7 @@ import { isGitHubHostAuthenticated } from './github-enterprise-repository' import { _resetSshHostnameResolutionCache } from './github-ssh-host-alias-resolution' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' +import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository-remote-probe' function mockOriginRemote(url: string): void { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { diff --git a/src/main/github/github-enterprise-repository.ts b/src/main/github/repositories/github-enterprise-repository.ts similarity index 91% rename from src/main/github/github-enterprise-repository.ts rename to src/main/github/repositories/github-enterprise-repository.ts index d17ca6bb6c3..2f2ef2c6dfd 100644 --- a/src/main/github/github-enterprise-repository.ts +++ b/src/main/github/repositories/github-enterprise-repository.ts @@ -1,28 +1,29 @@ -import { githubReadExecutionScope } from './github-read-execution-scope' -import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../source-control/code-host-read-execution-scope' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions -} from '../source-control/hosted-review-git-options' -import { parseAuthStatus } from './auth-diagnose' +} from '../../source-control/hosted-review-git-options' +import { parseAuthStatus } from '../accounts/auth-diagnose' import { ghRepoExecOptions, getRemoteUrlForRepo, githubRepoContext, - parseGitHubRemoteIdentity, type LocalGitExecOptions } from './github-repository-identity' import { + parseGitHubRemoteIdentity, effectiveGitHubRemoteHost, gitHubSshConfigHostAlias } from './github-remote-identity-parsing' + import { resolveSshConfigHostname } from './github-ssh-host-alias-resolution' -import { parseWslPath } from '../wsl/filesystem/unc-path-access' -import { isStableMissingGitRemoteError } from '../git/remotes/stable-missing-git-remote-error' -import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch' -import { getConnectionExecutionHostId } from '../../shared/execution-host' -import { getPublicForgeProviderForHost } from '../../shared/git/remotes/public-forge-host' +import { parseWslPath } from '../../wsl/filesystem/unc-path-access' +import { isStableMissingGitRemoteError } from '../../git/remotes/stable-missing-git-remote-error' +import { requireReachableGitRoute } from '../../providers/execution-host-provider-dispatch' +import { getConnectionExecutionHostId } from '../../../shared/execution-host' +import { getPublicForgeProviderForHost } from '../../../shared/git/remotes/public-forge-host' export type GitHubEnterpriseRepoSlug = GitHubOwnerRepo & { host: string } diff --git a/src/main/github/github-owner-repo-selection.ts b/src/main/github/repositories/github-owner-repo-selection.ts similarity index 83% rename from src/main/github/github-owner-repo-selection.ts rename to src/main/github/repositories/github-owner-repo-selection.ts index e41aadad2d7..1d44f2b2969 100644 --- a/src/main/github/github-owner-repo-selection.ts +++ b/src/main/github/repositories/github-owner-repo-selection.ts @@ -1,11 +1,8 @@ -import type { IssueSourcePreference } from '../../shared/repo-types' -import { githubRepoIdentityKey } from '../../shared/github/repository-identity-key' -import { shouldProbeGitRemote } from '../git/remotes/remote-name-listing' -import { - getOwnerRepoForRemote, - type LocalGitExecOptions, - type OwnerRepo -} from './github-repository-identity' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import { githubRepoIdentityKey } from '../../../shared/github/repositories/repository-identity-key' +import { shouldProbeGitRemote } from '../../git/remotes/remote-name-listing' +import { getOwnerRepoForRemote, type LocalGitExecOptions } from './github-repository-identity' +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../shared/github/repositories/repository-identity' export async function getOwnerRepo( repoPath: string, @@ -28,8 +25,6 @@ export async function getOwnerRepo( return originPromise } -export const getIssueOwnerRepo = getOwnerRepo - export type PRRepositoryCandidates = { candidates: OwnerRepo[] headRepo: OwnerRepo | null @@ -103,7 +98,7 @@ export async function resolveIssueSource( } } return { - source: await getIssueOwnerRepo(repoPath, connectionId, localGitOptions), + source: await getOwnerRepo(repoPath, connectionId, localGitOptions), fellBack: false } } diff --git a/src/main/github/github-remote-identity-parsing.ts b/src/main/github/repositories/github-remote-identity-parsing.ts similarity index 94% rename from src/main/github/github-remote-identity-parsing.ts rename to src/main/github/repositories/github-remote-identity-parsing.ts index 613d9e0f1a0..6ee2eeae8f6 100644 --- a/src/main/github/github-remote-identity-parsing.ts +++ b/src/main/github/repositories/github-remote-identity-parsing.ts @@ -1,5 +1,5 @@ -import { normalizeGitHubRemoteHost } from '../../shared/git/remotes/git-remote-host-alias' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' +import { normalizeGitHubRemoteHost } from '../../../shared/git/remotes/git-remote-host-alias' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' export type GitHubRemoteIdentity = GitHubOwnerRepo & { host: string } diff --git a/src/main/github/repositories/github-repository-client-refusal.test.ts b/src/main/github/repositories/github-repository-client-refusal.test.ts new file mode 100644 index 00000000000..5b74697b056 --- /dev/null +++ b/src/main/github/repositories/github-repository-client-refusal.test.ts @@ -0,0 +1,234 @@ +import type * as GitExecFileModule from '../../git/command-runner/git-exec-file' +import type * as GithubRepositoryIdentityModule from './github-repository-identity' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +type RateLimitGuardResult = + | { blocked: false } + | { blocked: true; remaining: number; limit: number; resetAt: number } + +const { + execFileAsyncMock, + ghExecFileAsyncMock, + getOwnerRepoMock, + getIssueOwnerRepoMock, + getOwnerRepoForRemoteMock, + getEnterpriseGitHubRepoSlugMock, + resolvePRRepositoryCandidatesMock, + getRemoteUrlForRepoMock, + gitExecFileAsyncMock, + getRateLimitMock, + rateLimitGuardMock, + noteRateLimitSpendMock, + acquireMock, + releaseMock +} = vi.hoisted(() => ({ + execFileAsyncMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + getIssueOwnerRepoMock: vi.fn(), + getOwnerRepoForRemoteMock: vi.fn(), + getEnterpriseGitHubRepoSlugMock: vi.fn(), + resolvePRRepositoryCandidatesMock: vi.fn(), + getRemoteUrlForRepoMock: vi.fn(), + gitExecFileAsyncMock: vi.fn(), + getRateLimitMock: vi.fn(), + rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), + acquireMock: vi.fn(), + releaseMock: vi.fn() +})) + +vi.mock('../execution/github-legacy-command', () => ({ + execFileAsync: execFileAsyncMock +})) + +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: gitExecFileAsyncMock +})) + +vi.mock('../../git/command-runner/process-capture/exec-error', async (importOriginal) => ({ + ...(await importOriginal>()), + extractExecError: (err: unknown) => ({ + stderr: err instanceof Error ? err.message : String(err), + stdout: '' + }) +})) + +vi.mock('../execution/github-operation-slots', () => ({ + acquire: acquireMock, + release: releaseMock +})) + +vi.mock('./github-owner-repo-selection', () => ({ + getOwnerRepo: getOwnerRepoMock, + resolvePRRepositoryCandidates: resolvePRRepositoryCandidatesMock, + resolveIssueSource: vi.fn() +})) + +vi.mock('./github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), + getOwnerRepoForRemote: getOwnerRepoForRemoteMock, + ghRepoExecOptions: (context: { + repoPath: string + connectionId?: string | null + wslDistro?: string + }) => + context.connectionId + ? {} + : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }, + githubRepoContext: ( + repoPath: string, + connectionId?: string | null, + localGitOptions: { wslDistro?: string } = {} + ) => ({ + repoPath, + connectionId: connectionId ?? null, + ...localGitOptions + }), + getRemoteUrlForRepo: getRemoteUrlForRepoMock, + _resetOwnerRepoCache: vi.fn() +})) + +vi.mock('../api/gh-error-classification', async (importOriginal) => ({ + ...(await importOriginal>()), + classifyGhError: (message: string) => ({ type: 'unknown', message }), + classifyListIssuesError: (message: string) => ({ type: 'unknown', message }) +})) + +vi.mock('./github-enterprise-repository', () => ({ + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, + getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugMock, + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) +})) + +vi.mock('../pull-requests/conflicts/conflict-summary', () => ({ + getPRConflictSummary: vi.fn() +})) + +vi.mock('../api/rate-limit', () => ({ + getRateLimit: getRateLimitMock, + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock, + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: vi.fn(), + spendsSharedGitHubComQuota: ( + repository?: { host?: string } | null, + executionOptions?: { wslDistro?: string } + ) => + (!repository?.host || repository.host.toLowerCase() === 'github.com') && + !executionOptions?.wslDistro +})) +import { addPRReviewCommentReply } from '../client/create/add-pr-review-comment' +import { getPRChecks } from '../client/check/get-pr-checks' +import { getPRComments } from '../client/fetch/get-pr-comments' +import { mergePR } from '../client/merge/merge-pr' +import { removePRReviewers, requestPRReviewers } from '../client/update/pr-reviewers' +import { resolveReviewThread } from '../client/update/resolve-review-thread' +import { setPRAutoMerge } from '../client/merge/pr-auto-merge' +import { updatePRTitle } from '../client/update/pr-details' + +import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository-remote-probe' + +beforeEach(() => { + _resetOriginGitHubApiRepositoryCache() +}) + +describe('GitHub PR local runtime routing', () => { + beforeEach(() => { + execFileAsyncMock.mockReset() + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getIssueOwnerRepoMock.mockReset() + getOwnerRepoForRemoteMock.mockReset() + getOwnerRepoForRemoteMock.mockImplementation( + async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => + remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null + ) + getEnterpriseGitHubRepoSlugMock.mockReset() + getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) + resolvePRRepositoryCandidatesMock.mockReset() + getRemoteUrlForRepoMock.mockReset() + gitExecFileAsyncMock.mockReset() + getRateLimitMock.mockReset() + getRateLimitMock.mockResolvedValue({ resources: {} }) + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + }) + + it('never falls through to the default gh host for an unresolved SSH repository', async () => { + const legacyRepo = { owner: 'team', repo: 'orca' } + getOwnerRepoMock.mockResolvedValue(null) + getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) + + await expect(getPRComments('/remote/repo', 7, { prRepo: legacyRepo }, 'ssh-1')).rejects.toThrow( + 'GitHub remote' + ) + await expect( + getPRChecks('/remote/repo', 7, undefined, legacyRepo, undefined, 'ssh-1') + ).rejects.toThrow('GitHub remote') + await expect(mergePR('/remote/repo', 7, 'squash', 'ssh-1', legacyRepo)).resolves.toMatchObject({ + ok: false + }) + await expect( + setPRAutoMerge('/remote/repo', 7, true, 'squash', 'ssh-1', legacyRepo) + ).resolves.toMatchObject({ ok: false }) + await expect(updatePRTitle('/remote/repo', 7, 'New title', 'ssh-1', legacyRepo)).resolves.toBe( + false + ) + await expect(requestPRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toMatchObject({ + ok: false + }) + await expect(removePRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toMatchObject({ + ok: false + }) + await expect( + addPRReviewCommentReply( + '/remote/repo', + 7, + 11, + 'Reply', + undefined, + undefined, + undefined, + 'ssh-1', + legacyRepo + ) + ).resolves.toMatchObject({ ok: false }) + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('refuses unresolved local PR mutations instead of using ambient gh defaults', async () => { + const legacyRepo = { owner: 'team', repo: 'orca' } + getOwnerRepoMock.mockResolvedValue(null) + getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) + + await expect( + resolveReviewThread('/repo-root', 'thread-1', true, null, legacyRepo) + ).resolves.toBe(false) + await expect(updatePRTitle('/repo-root', 7, 'New title', null, legacyRepo)).resolves.toBe(false) + await expect( + requestPRReviewers('/repo-root', 7, ['octo'], null, legacyRepo) + ).resolves.toMatchObject({ ok: false }) + await expect( + removePRReviewers('/repo-root', 7, ['octo'], null, legacyRepo) + ).resolves.toMatchObject({ ok: false }) + await expect(mergePR('/repo-root', 7, 'squash', null, legacyRepo)).resolves.toMatchObject({ + ok: false + }) + await expect( + setPRAutoMerge('/repo-root', 7, true, 'squash', null, legacyRepo) + ).resolves.toMatchObject({ ok: false }) + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/github/github-repository-host.ts b/src/main/github/repositories/github-repository-host.ts similarity index 84% rename from src/main/github/github-repository-host.ts rename to src/main/github/repositories/github-repository-host.ts index 250f71d38c3..54aebb5d056 100644 --- a/src/main/github/github-repository-host.ts +++ b/src/main/github/repositories/github-repository-host.ts @@ -1,4 +1,4 @@ -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' export function githubHostExecOptions(repository: GitHubOwnerRepo | null | undefined): { host?: string diff --git a/src/main/github/repositories/github-repository-identity-cache.test.ts b/src/main/github/repositories/github-repository-identity-cache.test.ts new file mode 100644 index 00000000000..63bba89f548 --- /dev/null +++ b/src/main/github/repositories/github-repository-identity-cache.test.ts @@ -0,0 +1,138 @@ +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { gitExecFileAsyncMock } = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn() +})) + +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: gitExecFileAsyncMock +})) + +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + ghExecFileAsync: vi.fn() +})) + +import { _resetRemoteNameListingCache } from '../../git/remotes/remote-name-listing' +import { + _getOwnerRepoCacheSize, + _resetOwnerRepoCache, + getOwnerRepoForRemote +} from './github-repository-identity' +import { getOwnerRepo } from './github-owner-repo-selection' +import { __resetLocalGitConfigSignatureCacheForTests } from './local-git-config-signature' + +function gitRemoteGetUrlCalls(remoteName: string): unknown[][] { + return gitExecFileAsyncMock.mock.calls.filter( + ([args]) => + Array.isArray(args) && args[0] === 'remote' && args[1] === 'get-url' && args[2] === remoteName + ) +} + +describe('github owner/repo resolution', () => { + beforeEach(() => { + gitExecFileAsyncMock.mockReset() + _resetOwnerRepoCache() + _resetRemoteNameListingCache() + __resetLocalGitConfigSignatureCacheForTests() + }) + + it('keeps local host and local WSL owner/repo cache entries separate for the same path', async () => { + gitExecFileAsyncMock.mockImplementation( + async (args: string[], options: { wslDistro?: string } = {}) => { + if (args[0] === 'remote' && args[1] !== 'get-url') { + return { stdout: 'origin\n' } + } + if (args[2] === 'upstream') { + throw new Error("fatal: No such remote 'upstream'") + } + return { + stdout: options.wslDistro + ? 'git@github.com:wsl/orca.git\n' + : 'git@github.com:host/orca.git\n' + } + } + ) + + await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'host', repo: 'orca' }) + await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({ + owner: 'wsl', + repo: 'orca' + }) + await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({ + owner: 'wsl', + repo: 'orca' + }) + + // 2 runtimes x (1 remote list + 1 origin hit); repeat WSL call is cached. + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(4) + expect(gitRemoteGetUrlCalls('upstream')).toHaveLength(0) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { + cwd: '/repo', + timeout: 30_000 + }) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { + cwd: '/repo', + timeout: 30_000, + wslDistro: 'Ubuntu' + }) + }) + + it('does not apply the long negative TTL when git remote get-url fails transiently', async () => { + const repoPath = await mkdtemp(join(tmpdir(), 'orca-gh-utils-')) + await mkdir(join(repoPath, '.git')) + await writeFile(join(repoPath, '.git', 'config'), '[core]\n\trepositoryformatversion = 0\n') + try { + gitExecFileAsyncMock + .mockRejectedValueOnce(new Error('fatal: cannot lock ref')) + .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) + + await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toBeNull() + await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toEqual({ + owner: 'acme', + repo: 'widgets' + }) + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) + } finally { + await rm(repoPath, { recursive: true, force: true }) + } + }) + + it('invalidates a cached local missing remote when an included git config changes', async () => { + const repoPath = await mkdtemp(join(tmpdir(), 'orca-gh-utils-')) + await mkdir(join(repoPath, '.git')) + const includedConfigPath = join(repoPath, 'remote.inc') + await writeFile( + join(repoPath, '.git', 'config'), + `[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = ${includedConfigPath}\n` + ) + await writeFile(includedConfigPath, '') + vi.useFakeTimers() + try { + vi.setSystemTime(1_000) + gitExecFileAsyncMock + .mockRejectedValueOnce(new Error("error: No such remote 'origin'")) + .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) + + await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toBeNull() + await writeFile( + includedConfigPath, + '[remote "origin"]\n\turl = git@github.com:acme/widgets.git\n' + ) + vi.setSystemTime(32_000) + + await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toEqual({ + owner: 'acme', + repo: 'widgets' + }) + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + await rm(repoPath, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/github/github-repository-identity.fork-owner-repo.test.ts b/src/main/github/repositories/github-repository-identity.fork-owner-repo.test.ts similarity index 82% rename from src/main/github/github-repository-identity.fork-owner-repo.test.ts rename to src/main/github/repositories/github-repository-identity.fork-owner-repo.test.ts index 20c8bf454f3..96ab146ab3b 100644 --- a/src/main/github/github-repository-identity.fork-owner-repo.test.ts +++ b/src/main/github/repositories/github-repository-identity.fork-owner-repo.test.ts @@ -1,5 +1,5 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' +import type * as GitExecFileModule from '../../git/command-runner/git-exec-file' +import type * as GhExecFileModule from '../../git/command-runner/hosted-cli/gh-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { gitExecFileAsyncMock, ghExecFileAsyncMock, readLocalGitConfigSignatureMock } = vi.hoisted( @@ -10,12 +10,12 @@ const { gitExecFileAsyncMock, ghExecFileAsyncMock, readLocalGitConfigSignatureMo }) ) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: ghExecFileAsyncMock })) @@ -24,11 +24,11 @@ vi.mock('./local-git-config-signature', () => ({ readLocalGitConfigSignature: readLocalGitConfigSignatureMock })) -import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' +import { _resetRemoteNameListingCache } from '../../git/remotes/remote-name-listing' import { _resetOwnerRepoCache } from './github-repository-identity' -import { probeRepoUpstream } from './client/fetch/repo-slug-upstream' +import { probeRepoUpstream } from '../client/fetch/repo-slug-upstream' -import { acquire, release } from './gh-utils' +import { acquire, release } from '../execution/github-operation-slots' afterEach(() => vi.useRealTimers()) diff --git a/src/main/github/repositories/github-repository-identity.signed-cache.test.ts b/src/main/github/repositories/github-repository-identity.signed-cache.test.ts new file mode 100644 index 00000000000..adc4d5e20dd --- /dev/null +++ b/src/main/github/repositories/github-repository-identity.signed-cache.test.ts @@ -0,0 +1,55 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as GitRunner from '../../git/command-runner/git-exec-file' + +const { gitExecFileAsyncMock, readLocalGitConfigSignatureMock } = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn(), + readLocalGitConfigSignatureMock: vi.fn<() => Promise>(async () => 'sig-1') +})) + +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync: gitExecFileAsyncMock +})) + +vi.mock('./local-git-config-signature', () => ({ + readLocalGitConfigSignature: readLocalGitConfigSignatureMock +})) + +import { getOwnerRepoForRemote, _resetOwnerRepoCache } from './github-repository-identity' + +const REPO = '/tmp/signed-cache-repo' +const THIRTY_SECONDS = 30_000 + +let remoteUrl = 'https://github.com/stablyai/orca.git' + +const remoteGetUrlCalls = (): number => + gitExecFileAsyncMock.mock.calls.filter(([args]) => (args as string[])[1] === 'get-url').length + +beforeEach(() => { + _resetOwnerRepoCache() + vi.useRealTimers() + gitExecFileAsyncMock.mockReset() + remoteUrl = 'https://github.com/stablyai/orca.git' + readLocalGitConfigSignatureMock.mockReset() + readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-1') + gitExecFileAsyncMock.mockImplementation(async () => ({ stdout: remoteUrl })) +}) + +describe('owner/repo identity cache', () => { + it('re-probes as soon as the git config signature changes', async () => { + vi.useFakeTimers() + await getOwnerRepoForRemote(REPO, 'origin') + expect(remoteGetUrlCalls()).toBe(1) + + remoteUrl = 'https://github.com/other-org/orca.git' + readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-2') + vi.setSystemTime(Date.now() + THIRTY_SECONDS) + + await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toEqual({ + owner: 'other-org', + repo: 'orca' + }) + expect(remoteGetUrlCalls()).toBe(2) + vi.useRealTimers() + }) +}) diff --git a/src/main/github/github-repository-identity.ssh-host-alias.test.ts b/src/main/github/repositories/github-repository-identity.ssh-host-alias.test.ts similarity index 91% rename from src/main/github/github-repository-identity.ssh-host-alias.test.ts rename to src/main/github/repositories/github-repository-identity.ssh-host-alias.test.ts index 5ebf41be4b7..ae219555fe9 100644 --- a/src/main/github/github-repository-identity.ssh-host-alias.test.ts +++ b/src/main/github/repositories/github-repository-identity.ssh-host-alias.test.ts @@ -1,5 +1,5 @@ -import type * as CommandExecFileModule from '../git/command-runner/process-capture/command-exec-file' -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' +import type * as CommandExecFileModule from '../../git/command-runner/process-capture/command-exec-file' +import type * as GitExecFileModule from '../../git/command-runner/git-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -14,12 +14,12 @@ const { readLocalGitConfigSignatureMock: vi.fn(async () => 'sig-10284') })) -vi.mock('../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ ...(await importOriginal()), commandExecFileAsync: commandExecFileAsyncMock })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: gitExecFileAsyncMock })) @@ -28,7 +28,7 @@ vi.mock('./local-git-config-signature', () => ({ readLocalGitConfigSignature: readLocalGitConfigSignatureMock })) -vi.mock('../ssh/config/ssh-g-config-resolution', () => ({ +vi.mock('../../ssh/config/ssh-g-config-resolution', () => ({ resolveWithSshG: resolveWithSshGMock })) diff --git a/src/main/github/github-repository-identity.ts b/src/main/github/repositories/github-repository-identity.ts similarity index 90% rename from src/main/github/github-repository-identity.ts rename to src/main/github/repositories/github-repository-identity.ts index 03a5ae8d5b4..360bdd7d285 100644 --- a/src/main/github/github-repository-identity.ts +++ b/src/main/github/repositories/github-repository-identity.ts @@ -1,29 +1,21 @@ +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../shared/github/repositories/repository-identity' import { AsyncLocalStorage } from 'node:async_hooks' -import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe' -import { readRemoteUrl } from '../git/remotes/remote-url-probe' +import { runCoalescedProbe, type CoalescedProbes } from '../../git/remotes/coalesced-probe' +import { readRemoteUrl } from '../../git/remotes/remote-url-probe' import { ghAccountBindingsEqual, normalizeGhAccountBinding, type GhAccountBinding -} from '../../shared/github/account-binding' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' +} from '../../../shared/github/accounts/account-binding' + import { readLocalGitConfigSignature } from './local-git-config-signature' -import { - parseGitHubOwnerRepo, - parseGitHubRemoteIdentity, - type GitHubRemoteIdentity -} from './github-remote-identity-parsing' + import { classifyGitHubOwnerRepoFromRemoteUrl } from './github-ssh-host-alias-resolution' -import { isStableMissingGitRemoteError } from '../git/remotes/stable-missing-git-remote-error' -import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' -import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch' -import { getConnectionExecutionHostId } from '../../shared/execution-host' -import { resolveGitHubProjectAccount } from './github-project-account' - -export type OwnerRepo = GitHubOwnerRepo - -export type { GitHubRemoteIdentity } -export { parseGitHubOwnerRepo, parseGitHubRemoteIdentity } +import { isStableMissingGitRemoteError } from '../../git/remotes/stable-missing-git-remote-error' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' +import { requireReachableGitRoute } from '../../providers/execution-host-provider-dispatch' +import { getConnectionExecutionHostId } from '../../../shared/execution-host' +import { resolveGitHubProjectAccount } from '../accounts/github-project-account' export type GitHubRepoContext = { repoPath: string diff --git a/src/main/github/github-ssh-host-alias-resolution.ts b/src/main/github/repositories/github-ssh-host-alias-resolution.ts similarity index 93% rename from src/main/github/github-ssh-host-alias-resolution.ts rename to src/main/github/repositories/github-ssh-host-alias-resolution.ts index 5432a6f8c90..769c5e59cf4 100644 --- a/src/main/github/github-ssh-host-alias-resolution.ts +++ b/src/main/github/repositories/github-ssh-host-alias-resolution.ts @@ -1,7 +1,7 @@ -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import { commandExecFileAsync } from '../git/command-runner/process-capture/command-exec-file' -import { parseWslPath } from '../wsl/filesystem/unc-path-access' -import { resolveWithSshG } from '../ssh/config/ssh-g-config-resolution' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' +import { commandExecFileAsync } from '../../git/command-runner/process-capture/command-exec-file' +import { parseWslPath } from '../../wsl/filesystem/unc-path-access' +import { resolveWithSshG } from '../../ssh/config/ssh-g-config-resolution' import { gitHubSshConfigHostAlias, parseGitHubOwnerRepo, diff --git a/src/main/github/local-git-config-signature.ts b/src/main/github/repositories/local-git-config-signature.ts similarity index 98% rename from src/main/github/local-git-config-signature.ts rename to src/main/github/repositories/local-git-config-signature.ts index 7d20e2e2b66..b67d31f4ca1 100644 --- a/src/main/github/local-git-config-signature.ts +++ b/src/main/github/repositories/local-git-config-signature.ts @@ -1,7 +1,7 @@ import { readFile, stat } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, isAbsolute, join, resolve } from 'node:path' -import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe' +import { runCoalescedProbe, type CoalescedProbes } from '../../git/remotes/coalesced-probe' import type { GitHubRepoContext } from './github-repository-identity' type LocalGitConfigPaths = { diff --git a/src/main/github/work-item-details-enterprise-host.test.ts b/src/main/github/work-item-details-enterprise-host.test.ts deleted file mode 100644 index e0e1647be75..00000000000 --- a/src/main/github/work-item-details-enterprise-host.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -type RateLimitGuardResult = - | { blocked: false } - | { blocked: true; remaining: number; limit: number; resetAt: number } - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getEnterpriseGitHubRepoSlugMock, - getWorkItemMock, - getWorkItemByOwnerRepoMock, - getPRChecksMock, - getPRCommentsMock, - repositoryRateLimitGuardMock, - noteRepositoryRateLimitSpendMock -} = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getEnterpriseGitHubRepoSlugMock: vi.fn(), - getWorkItemMock: vi.fn(), - getWorkItemByOwnerRepoMock: vi.fn(), - getPRChecksMock: vi.fn(), - getPRCommentsMock: vi.fn(), - repositoryRateLimitGuardMock: vi.fn< - ( - repository: { host?: string } | null | undefined, - bucket: 'core' | 'graphql' | 'search', - options?: { cwd?: string; host?: string; wslDistro?: string } - ) => RateLimitGuardResult - >(() => ({ blocked: false })), - noteRepositoryRateLimitSpendMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, - getOwnerRepoForRemote: vi.fn(), - ghRepoExecOptions: vi.fn((context: { connectionId?: string | null; repoPath: string }) => - context.connectionId ? {} : { cwd: context.repoPath } - ), - githubRepoContext: vi.fn((repoPath: string, connectionId?: string | null) => ({ - repoPath, - connectionId: connectionId ?? null - })), - acquire: vi.fn().mockResolvedValue(undefined), - release: vi.fn() -})) - -vi.mock('./client', async () => ({ - getWorkItem: getWorkItemMock, - getWorkItemWithRepository: ( - await vi.importActual('./work-item-details-test-lookup') - ).makeWorkItemDetailsLookupMock(getWorkItemMock), - getWorkItemByOwnerRepo: getWorkItemByOwnerRepoMock, - getPRChecks: getPRChecksMock, - getPRComments: getPRCommentsMock -})) - -vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, - getEnterpriseGitHubRepoSlugForRemote: vi.fn().mockResolvedValue(null), - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('./rate-limit', () => ({ - repositoryRateLimitGuard: repositoryRateLimitGuardMock, - noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock -})) - -import { getWorkItemDetails } from './work-item-details' - -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() -}) - -describe('getWorkItemDetails Enterprise host routing', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getEnterpriseGitHubRepoSlugMock.mockReset() - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - getWorkItemMock.mockReset() - getWorkItemByOwnerRepoMock.mockReset() - getPRChecksMock.mockReset() - getPRCommentsMock.mockReset() - repositoryRateLimitGuardMock.mockReset() - repositoryRateLimitGuardMock.mockReturnValue({ blocked: false }) - noteRepositoryRateLimitSpendMock.mockReset() - }) - - it('surfaces a found SSH PR without any default-host gh call when the repository is unresolved', async () => { - // A found PR without a resolved Enterprise host must not fall back to github.com. - getWorkItemMock.mockResolvedValueOnce({ - id: 'pr:7', - type: 'pr', - number: 7, - title: 'Unresolved Enterprise PR', - state: 'open', - url: 'https://github.acme-corp.com/team/orca/pull/7', - labels: [], - updatedAt: '2026-07-16T00:00:00Z', - author: 'pr-author' - }) - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - - const details = await getWorkItemDetails('/remote/repo', 7, 'pr', 'ssh-1') - - expect(details?.item.id).toBe('pr:7') - expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/work-item-details-query-reuse.test.ts b/src/main/github/work-item-details-query-reuse.test.ts deleted file mode 100644 index ece68e0e3ef..00000000000 --- a/src/main/github/work-item-details-query-reuse.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import type { GitHubApiRepository } from './github-api-repository' - -const mocks = vi.hoisted(() => ({ - exec: vi.fn(), - source: vi.fn(), - acquire: vi.fn(), - release: vi.fn() -})) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: mocks.exec, - acquire: mocks.acquire, - release: mocks.release, - ghRepoExecOptions: (context: { repoPath: string; connectionId?: string; wslDistro?: string }) => - context.connectionId - ? {} - : { cwd: context.repoPath, ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) }, - githubRepoContext: (repoPath: string, connectionId?: string, options = {}) => ({ - repoPath, - connectionId, - ...options - }), - classifyGhError: () => ({ type: 'not_found' }) -})) -vi.mock('./github-api-repository', () => ({ - resolveIssueGitHubApiRepositorySource: mocks.source, - githubHostExecOptions: (repository?: GitHubApiRepository) => ({ host: repository?.host }) -})) -vi.mock('./client', async () => ({ - ...(await import('./client/fetch/get-work-item')), - getPRChecks: vi.fn(), - getPRComments: vi.fn() -})) -vi.mock('./rate-limit', () => ({ - repositoryRateLimitGuard: () => ({ blocked: false }), - noteRepositoryRateLimitSpend: vi.fn() -})) - -import { getWorkItemWithRepository } from './client/fetch/get-work-item' - -const repository = { owner: 'team', repo: 'widgets', host: 'github.example.com:8443' } -let issue: Record -beforeEach(() => { - vi.clearAllMocks() - mocks.source.mockResolvedValue({ source: repository, fellBack: false }) - issue = { - number: 5, - title: 'Closed issue', - state: 'CLOSED', - url: 'https://github.example.com:8443/team/widgets/issues/5', - updatedAt: '2026-10-01T00:00:00Z', - author: { __typename: 'User', login: 'author', avatarUrl: 'https://avatars.example/author' }, - labels: { nodes: [{ name: 'bug' }, { name: 'urgent' }], pageInfo: { hasNextPage: false } }, - body: 'Description', - assignees: { - pageInfo: { hasNextPage: false }, - nodes: [ - { login: 'assigned', name: 'Assigned User', avatarUrl: 'https://avatars.example/assigned' } - ] - }, - participants: { nodes: [] }, - comments: { - nodes: [ - { - databaseId: 10, - body: 'Comment', - createdAt: '2026-10-02T00:00:00Z', - url: 'https://example/comment', - author: { login: 'bot', __typename: 'Bot' } - } - ] - } - } - mocks.exec.mockImplementation(async (args: string[]) => ({ - stdout: JSON.stringify( - args.includes('graphql') - ? { data: { repository: { issue } } } - : args.some((arg) => arg.includes('/timeline?')) - ? [] - : { - number: 5, - title: 'REST issue', - state: 'open', - labels: [{ name: 'all labels' }], - assignees: [{ login: 'rest-assigned', name: 'REST Assigned User' }] - } - ) - })) -}) - -it.each(['incomplete labels', 'invalid metadata', 'partial errors'])( - 'retains the REST item fallback for %s', - async (reason) => { - if (reason === 'incomplete labels') { - issue.labels = { nodes: [{ name: 'partial' }], pageInfo: { hasNextPage: true } } - } - if (reason === 'invalid metadata') { - issue.number = 6 - } - if (reason === 'partial errors') { - mocks.exec.mockResolvedValueOnce({ - stdout: JSON.stringify({ - data: { repository: { issue } }, - errors: [{ message: 'Unavailable metadata' }] - }) - }) - } - const result = await getWorkItemWithRepository( - '/repo', - 5, - 'issue', - undefined, - {}, - 'origin', - true - ) - expect(result.item).toMatchObject({ title: 'REST issue', labels: ['all labels'] }) - if (reason === 'incomplete labels') { - expect(result.issueDetails).toMatchObject({ body: 'Description', timelineItems: [] }) - expect(mocks.exec).toHaveBeenCalledTimes(3) - } else { - expect(result.issueDetails).toBeNull() - expect(mocks.exec).toHaveBeenCalledTimes(2) - } - expect(mocks.exec.mock.calls.at(-1)?.[0]).toEqual(['api', 'repos/team/widgets/issues/5']) - } -) - -it.each([ - { reason: 'missing nodes', nodes: undefined }, - { reason: 'null nodes', nodes: null }, - { reason: 'null entry', nodes: [null] }, - { reason: 'missing login', nodes: [{}] }, - { reason: 'empty login', nodes: [{ login: '' }] } -])('retains conversation and recovers issue assignees for $reason', async ({ nodes }) => { - issue.assignees = { nodes, pageInfo: { hasNextPage: false } } - const result = await getWorkItemWithRepository('/repo', 5, 'issue', undefined, {}, 'origin', true) - expect(result.item).toMatchObject({ - title: 'REST issue', - assignees: [{ login: 'rest-assigned', name: 'REST Assigned User' }] - }) - expect(result.issueDetails).toMatchObject({ - body: 'Description', - comments: [{ id: 10, isBot: true }], - timelineItems: [] - }) - expect(mocks.exec.mock.calls.map(([args]) => args)).toEqual([ - expect.arrayContaining(['api', 'graphql', 'includeItem=true']), - expect.arrayContaining(['api', 'repos/team/widgets/issues/5/timeline?per_page=100&page=1']), - ['api', 'repos/team/widgets/issues/5'] - ]) -}) diff --git a/src/main/github/work-item-search-fallback-environment.test.ts b/src/main/github/work-item-search-fallback-environment.test.ts deleted file mode 100644 index 503d9f28ec7..00000000000 --- a/src/main/github/work-item-search-fallback-environment.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { api, capture } from './work-item-search-test-harness' -import { listWorkItems } from './client/list/list-work-items' -import './client/list/count-work-items' -import metadata from './__fixtures__/work-item-search-metadata.json' - -it('keeps REST fallback on the credential captured for the failed preferred search', async () => { - vi.stubEnv('GH_TOKEN', 'fixture-original-credential') - api.aliasErrorRepo = 'fixture/repo' - capture.mockImplementation(async (binary, args, options) => { - if (args.includes('graphql')) { - vi.stubEnv('GH_TOKEN', 'fixture-later-credential') - } - return api.capture(binary, args, options) - }) - expect((await listWorkItems('fixture/repo', 24, 'is:issue')).items).toHaveLength(24) - const queries = api.calls.filter( - (call) => - call.args.includes('graphql') || call.args.some((arg) => arg.startsWith('search/issues?')) - ) - expect(queries.map((call) => call.fixtureCredential)).toEqual([ - 'fixture-original-credential', - 'fixture-original-credential' - ]) -}) - -it('hydrates oversized associations with the preferred page credential', async () => { - vi.stubEnv('GH_TOKEN', 'fixture-original-credential') - const row = structuredClone(metadata[0].graphql) - api.specialNodes = [{ ...row, labels: { ...row.labels, pageInfo: { hasNextPage: true } } }] - capture.mockImplementation(async (binary, args, options) => { - if (args.includes('graphql')) { - vi.stubEnv('GH_TOKEN', 'fixture-later-credential') - } - return api.capture(binary, args, options) - }) - const result = await listWorkItems('fixture/repo', 24, 'is:issue') - expect(result.items[0].labels).toHaveLength(125) - const queries = api.calls.filter( - (call) => - call.args.includes('graphql') || call.args.some((arg) => /^repos\/.+\/issues\/\d+$/.test(arg)) - ) - expect(queries.map((call) => call.fixtureCredential)).toEqual([ - 'fixture-original-credential', - 'fixture-original-credential' - ]) -}) diff --git a/src/main/github/work-item-search-isolation.test.ts b/src/main/github/work-item-search-isolation.test.ts deleted file mode 100644 index 6dfd05f8a60..00000000000 --- a/src/main/github/work-item-search-isolation.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { expect, it } from 'vitest' -import { api } from './work-item-search-test-harness' -import { listWorkItems } from './client/list/list-work-items' -import { countWorkItems } from './client/list/count-work-items' -import './client/list/work-item-search-page' -import '../git/command-runner/hosted-cli/gh-rate-limit-breaker' - -it('keeps count/list search usable when REST Search is exhausted and reports both-bucket failures', async () => { - api.searchAvailable = false - expect(await countWorkItems('fixture/repo', 'is:issue')).toBe(120) - expect((await listWorkItems('fixture/repo', 24, 'is:issue')).items).toHaveLength(24) - expect(api.restSearches).toBe(0) - api.graphqlAvailable = false - await expect( - listWorkItems('fixture/repo', 24, 'is:issue', 1, undefined, undefined, true) - ).rejects.toThrow(/rate limit exceeded/) -}) diff --git a/src/main/github/work-item-search-test-harness.ts b/src/main/github/work-item-search-test-harness.ts deleted file mode 100644 index 1ef5aebb783..00000000000 --- a/src/main/github/work-item-search-test-harness.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { afterEach, beforeEach, vi, type Mock } from 'vitest' - -import { randomUUID } from 'node:crypto' -import { basename } from 'node:path' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import { WorkItemSearchApi } from './__fixtures__/work-item-search-api' - -const { - capture, - sourceContext -}: { - capture: Mock - sourceContext: { host: string; available: boolean } -} = vi.hoisted(() => ({ - capture: vi.fn(), - sourceContext: { host: 'github.com', available: true } -})) -const gitExecFileAsync = vi.hoisted(() => vi.fn()) -vi.mock('../git/command-runner/process-capture/exec-file-capture', () => ({ - execFileCaptureToTermination: capture -})) -vi.mock('../git/command-runner/host-routing/wsl-command-resolution', () => ({ - resolveCommand: (binary: string, args: string[], cwd?: string, distro?: string) => ({ - binary, - args, - cwd, - wsl: distro ? { distro } : null, - wslMode: null - }), - resolveDefaultWslCli: () => null -})) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync -})) -vi.mock('./github-api-repository', async (importOriginal) => { - const actual = await importOriginal() - const source = (repoPath: string) => - sourceContext.available - ? { owner: 'fixture', repo: basename(repoPath), host: sourceContext.host } - : null - return { - ...actual, - resolveIssueGitHubApiRepositorySource: async (repoPath: string) => ({ - source: source(repoPath), - fellBack: false - }), - getOriginGitHubApiRepository: async (repoPath: string) => source(repoPath), - getGitHubApiRepositoryForRemote: async () => null - } -}) - -import { _resetRateLimitCache } from './rate-limit' -import { - clearGhRateLimitBlock, - ghRateLimitScopeKey -} from '../git/command-runner/hosted-cli/gh-rate-limit-breaker' -export let api: WorkItemSearchApi -beforeEach(() => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(0) - vi.stubEnv('GH_HOST', 'github.com') - vi.stubEnv('ORCA_WORK_ITEM_SEARCH_FIXTURE', randomUUID()) - _resetRateLimitCache() - for (const runtime of ['native', 'wsl:ubuntu', 'wsl:debian']) { - for (const host of ['github.com', 'github.example.com']) { - for (const bucket of ['core', 'graphql', 'search'] as const) { - clearGhRateLimitBlock(bucket, ghRateLimitScopeKey(runtime, host)) - } - } - } - sourceContext.host = 'github.com' - sourceContext.available = true - api = new WorkItemSearchApi() - capture.mockReset().mockImplementation(api.capture.bind(api)) -}) -afterEach(() => { - vi.useRealTimers() - vi.unstubAllEnvs() -}) - -export { capture, sourceContext } diff --git a/src/main/github/work-item-details-pr-files.test.ts b/src/main/github/work-items/work-item-details-pr-files.test.ts similarity index 86% rename from src/main/github/work-item-details-pr-files.test.ts rename to src/main/github/work-items/work-item-details-pr-files.test.ts index ff94be71d4e..485054a2f4d 100644 --- a/src/main/github/work-item-details-pr-files.test.ts +++ b/src/main/github/work-items/work-item-details-pr-files.test.ts @@ -1,3 +1,4 @@ +import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity' import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -39,36 +40,52 @@ const { >(() => ({ blocked: false })) })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: ghExecFileAsyncMock, +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), getOwnerRepoForRemote: getOwnerRepoMock, - getIssueOwnerRepo: vi.fn(), ghRepoExecOptions: vi.fn((context) => ({ cwd: context.repoPath })), githubRepoContext: vi.fn((repoPath, connectionId, localGitOptions) => ({ repoPath, connectionId: connectionId ?? null, ...localGitOptions - })), + })) +})) + +vi.mock('../repositories/github-owner-repo-selection', () => ({ + getOwnerRepo: vi.fn() +})) + +vi.mock('../execution/github-operation-slots', () => ({ acquire: vi.fn(), release: vi.fn() })) -vi.mock('./client', async () => ({ +vi.mock('../client/fetch/get-work-item', async () => ({ getWorkItem: getWorkItemMock, getWorkItemWithRepository: ( await vi.importActual('./work-item-details-test-lookup') ).makeWorkItemDetailsLookupMock(getWorkItemMock), - getWorkItemByOwnerRepo: vi.fn(), - getPRChecks: getPRChecksMock, + getWorkItemByOwnerRepo: vi.fn() +})) + +vi.mock('../client/check/get-pr-checks', async () => ({ + getPRChecks: getPRChecksMock +})) + +vi.mock('../client/fetch/get-pr-comments', async () => ({ getPRComments: getPRCommentsMock })) -vi.mock('./github-enterprise-repository', () => ({ +vi.mock('../repositories/github-enterprise-repository', () => ({ getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) -vi.mock('./rate-limit', () => ({ +vi.mock('../api/rate-limit', () => ({ rateLimitGuard: vi.fn(() => ({ blocked: false })), noteRateLimitSpend: vi.fn(), repositoryRateLimitGuard: repositoryRateLimitGuardMock, @@ -76,7 +93,7 @@ vi.mock('./rate-limit', () => ({ })) import { getWorkItemDetails } from './work-item-details' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' +import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe' beforeEach(() => { _resetOriginGitHubApiRepositoryCache() diff --git a/src/main/github/work-item-details-test-lookup.ts b/src/main/github/work-items/work-item-details-test-lookup.ts similarity index 76% rename from src/main/github/work-item-details-test-lookup.ts rename to src/main/github/work-items/work-item-details-test-lookup.ts index c2532854c35..fd76d6f7f7f 100644 --- a/src/main/github/work-item-details-test-lookup.ts +++ b/src/main/github/work-items/work-item-details-test-lookup.ts @@ -1,6 +1,5 @@ -import { resolveIssueGitHubApiRepositorySource } from './github-api-repository' -import type { getWorkItem } from './client' -import type { WorkItemRepositoryLookup } from './client/fetch/get-work-item' +import { resolveIssueGitHubApiRepositorySource } from '../repositories/github-api-repository' +import type { getWorkItem, WorkItemRepositoryLookup } from '../client/fetch/get-work-item' // Why: detail tests replace item lookup; retain its selected-source metadata. export function makeWorkItemDetailsLookupMock(lookup: typeof getWorkItem) { diff --git a/src/main/github/work-item-details.test.ts b/src/main/github/work-items/work-item-details.test.ts similarity index 86% rename from src/main/github/work-item-details.test.ts rename to src/main/github/work-items/work-item-details.test.ts index 3beee4e9554..b500e0db06c 100644 --- a/src/main/github/work-item-details.test.ts +++ b/src/main/github/work-items/work-item-details.test.ts @@ -1,3 +1,4 @@ +import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity' import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -53,40 +54,56 @@ const { releaseMock: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../repositories/github-owner-repo-selection', () => ({ + getOwnerRepo: getOwnerRepoMock +})) + +vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), getOwnerRepoForRemote: getOwnerRepoForRemoteMock, ghRepoExecOptions: ghRepoExecOptionsMock, - githubRepoContext: githubRepoContextMock, + githubRepoContext: githubRepoContextMock +})) + +vi.mock('../execution/github-operation-slots', () => ({ acquire: acquireMock, release: releaseMock })) -vi.mock('./client', async () => ({ +vi.mock('../client/fetch/get-work-item', async () => ({ getWorkItem: getWorkItemMock, getWorkItemWithRepository: ( await vi.importActual('./work-item-details-test-lookup') ).makeWorkItemDetailsLookupMock(getWorkItemMock), - getWorkItemByOwnerRepo: getWorkItemByOwnerRepoMock, - getPRChecks: getPRChecksMock, + getWorkItemByOwnerRepo: getWorkItemByOwnerRepoMock +})) + +vi.mock('../client/check/get-pr-checks', async () => ({ + getPRChecks: getPRChecksMock +})) + +vi.mock('../client/fetch/get-pr-comments', async () => ({ getPRComments: getPRCommentsMock })) -vi.mock('./github-enterprise-repository', () => ({ +vi.mock('../repositories/github-enterprise-repository', () => ({ getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugForRemoteMock, isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) -vi.mock('./rate-limit', () => ({ +vi.mock('../api/rate-limit', () => ({ repositoryRateLimitGuard: repositoryRateLimitGuardMock, noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock })) import { getWorkItemDetails } from './work-item-details' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' +import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe' beforeEach(() => { _resetOriginGitHubApiRepositoryCache() diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-items/work-item-details.ts similarity index 83% rename from src/main/github/work-item-details.ts rename to src/main/github/work-items/work-item-details.ts index 3db15194c9e..60eeaa99e98 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-items/work-item-details.ts @@ -1,22 +1,31 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' -import { withGitHubRepoExecution } from './github-repository-identity' -import type { PRCheckDetail } from '../../shared/github/check-types' -import type { GitHubPRFile, GitHubPRFileContents } from '../../shared/github/pull-request-types' -import type { GitHubWorkItemDetails } from '../../shared/github/work-item-types' -import type { IssueSourcePreference } from '../../shared/repo-types' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' import { - getPRChecks, - getPRComments, - getWorkItemWithRepository, - getWorkItemByOwnerRepo -} from './client' -import { acquire, release, type LocalGitExecOptions } from './gh-utils' -import { resolveGitHubRepoExecution, type GitHubApiRepository } from './github-api-repository' -import { isValidGitHubApiRepository } from './github-api-repository-validation' -import { getIssueBodyAndComments, getIssueDetailsViaGraphQL } from './issue-work-item-details' -import { getPRFiles, getPRMetadata, mergePRFileViewedStates } from './pull-request-file-data' -import { getPRDetailContext } from './pull-request-detail-context' -import { getPRFileContents as loadPRFileContents } from './pull-request-file-contents' + withGitHubRepoExecution, + type LocalGitExecOptions +} from '../repositories/github-repository-identity' +import type { PRCheckDetail } from '../../../shared/github/checks/check-types' + +import type { GitHubWorkItemDetails } from '../../../shared/github/work-items/work-item-types' +import type { IssueSourcePreference } from '../../../shared/repo-types' +import { getPRChecks } from '../client/check/get-pr-checks' +import { getPRComments } from '../client/fetch/get-pr-comments' +import { getWorkItemWithRepository, getWorkItemByOwnerRepo } from '../client/fetch/get-work-item' +import { acquire, release } from '../execution/github-operation-slots' + +import { resolveGitHubRepoExecution } from '../repositories/github-api-repository' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import { isValidGitHubApiRepository } from '../repositories/github-api-repository-validation' +import { + getIssueBodyAndComments, + getIssueDetailsViaGraphQL +} from '../issues/issue-work-item-details' +import { + getPRFiles, + getPRMetadata, + mergePRFileViewedStates +} from '../pull-requests/files/pull-request-file-data' +import { getPRDetailContext } from '../pull-requests/files/pull-request-detail-context' + import { enrichItemDisplayAvatars, getMentionParticipants, @@ -273,18 +282,3 @@ export async function getWorkItemDetails( expectedGhAccount ) } - -export async function getPRFileContents(args: { - repoPath: string - connectionId?: string | null - localGitOptions?: LocalGitExecOptions - prRepo?: GitHubApiRepository | null - prNumber: number - path: string - oldPath?: string - status: GitHubPRFile['status'] - headSha: string - baseSha: string -}): Promise { - return loadPRFileContents(args) -} diff --git a/src/main/github/work-item-participants.ts b/src/main/github/work-items/work-item-participants.ts similarity index 91% rename from src/main/github/work-item-participants.ts rename to src/main/github/work-items/work-item-participants.ts index d7bfc1f33f5..e016b557114 100644 --- a/src/main/github/work-item-participants.ts +++ b/src/main/github/work-items/work-item-participants.ts @@ -1,10 +1,16 @@ -import type { PRComment } from '../../shared/github/comment-types' -import type { GitHubAssignableUser } from '../../shared/github/pull-request-types' -import type { GitHubWorkItem } from '../../shared/github/work-item-types' -import { ghExecFileAsync, ghRepoExecOptions, githubRepoContext } from './gh-utils' -import type { LocalGitExecOptions } from './gh-utils' -import { githubHostExecOptions, type GitHubApiRepository } from './github-api-repository' -import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' +import type { PRComment } from '../../../shared/github/comments/comment-types' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' +import type { GitHubWorkItem } from '../../../shared/github/work-items/work-item-types' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' +import { + ghRepoExecOptions, + githubRepoContext, + type LocalGitExecOptions +} from '../repositories/github-repository-identity' + +import { githubHostExecOptions } from '../repositories/github-repository-host' +import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity' +import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit' const WORK_ITEM_PARTICIPANTS_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $isPr: Boolean!) { repository(owner: $owner, name: $repo) { diff --git a/src/main/github/work-items/work-item-search-test-harness.ts b/src/main/github/work-items/work-item-search-test-harness.ts new file mode 100644 index 00000000000..4cbc5993d06 --- /dev/null +++ b/src/main/github/work-items/work-item-search-test-harness.ts @@ -0,0 +1,97 @@ +import type * as GithubApiRepositoryModule from '../repositories/github-api-repository' +import type * as GithubApiRepositoryRemoteProbeModule from '../repositories/github-api-repository-remote-probe' +import { afterEach, beforeEach, vi, type Mock } from 'vitest' + +import { randomUUID } from 'node:crypto' +import { basename } from 'node:path' + +import type * as GitExecFileModule from '../../git/command-runner/git-exec-file' +import { WorkItemSearchApi } from '../__fixtures__/work-item-search-api' + +const { + capture, + sourceContext +}: { + capture: Mock + sourceContext: { host: string; available: boolean } +} = vi.hoisted(() => ({ + capture: vi.fn(), + sourceContext: { host: 'github.com', available: true } +})) +const gitExecFileAsync = vi.hoisted(() => vi.fn()) +vi.mock('../../git/command-runner/process-capture/exec-file-capture', () => ({ + execFileCaptureToTermination: capture +})) +vi.mock('../../git/command-runner/host-routing/wsl-command-resolution', () => ({ + resolveCommand: (binary: string, args: string[], cwd?: string, distro?: string) => ({ + binary, + args, + cwd, + wsl: distro ? { distro } : null, + wslMode: null + }), + resolveDefaultWslCli: () => null +})) + +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + gitExecFileAsync +})) +vi.mock('../repositories/github-api-repository', async (importOriginal) => { + const actual = await importOriginal() + const source = (repoPath: string) => + sourceContext.available + ? { owner: 'fixture', repo: basename(repoPath), host: sourceContext.host } + : null + return { + ...actual, + resolveIssueGitHubApiRepositorySource: async (repoPath: string) => ({ + source: source(repoPath), + fellBack: false + }) + } +}) + +vi.mock('../repositories/github-api-repository-remote-probe', async (importOriginal) => { + const actual = await importOriginal() + const source = (repoPath: string) => + sourceContext.available + ? { owner: 'fixture', repo: basename(repoPath), host: sourceContext.host } + : null + return { + ...actual, + getOriginGitHubApiRepository: async (repoPath: string) => source(repoPath), + getGitHubApiRepositoryForRemote: async () => null + } +}) + +import { _resetRateLimitCache } from '../api/rate-limit' +import { + clearGhRateLimitBlock, + ghRateLimitScopeKey +} from '../../git/command-runner/hosted-cli/gh-rate-limit-breaker' +export let api: WorkItemSearchApi +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(0) + vi.stubEnv('GH_HOST', 'github.com') + vi.stubEnv('ORCA_WORK_ITEM_SEARCH_FIXTURE', randomUUID()) + _resetRateLimitCache() + for (const runtime of ['native', 'wsl:ubuntu', 'wsl:debian']) { + for (const host of ['github.com', 'github.example.com']) { + for (const bucket of ['core', 'graphql', 'search'] as const) { + clearGhRateLimitBlock(bucket, ghRateLimitScopeKey(runtime, host)) + } + } + } + sourceContext.host = 'github.com' + sourceContext.available = true + api = new WorkItemSearchApi() + capture.mockReset().mockImplementation(api.capture.bind(api)) +}) +afterEach(() => { + vi.useRealTimers() + vi.unstubAllEnvs() +}) + +export { capture, sourceContext } diff --git a/src/main/github/github-issue-link-title-fill.test.ts b/src/main/github/workspace-links/github-issue-link-title-fill.test.ts similarity index 89% rename from src/main/github/github-issue-link-title-fill.test.ts rename to src/main/github/workspace-links/github-issue-link-title-fill.test.ts index 596fe38be6f..c55a9b90c70 100644 --- a/src/main/github/github-issue-link-title-fill.test.ts +++ b/src/main/github/workspace-links/github-issue-link-title-fill.test.ts @@ -8,17 +8,17 @@ import { makeRepo, testState, writeDataFile -} from '../persistence/persistence-test-harness' -import { getWorkspaceAttachments } from '../../shared/workspace-attachments/workspace-attachments' -import { hostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' +} from '../../persistence/persistence-test-harness' +import { getWorkspaceAttachments } from '../../../shared/workspace-attachments/workspace-attachments' +import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' import { installGitHubIssueLinkTitleFill } from './github-issue-link-title-fill' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, safeStorage: { isEncryptionAvailable: () => false } })) -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) const target = hostWorktreeTarget({ id: 'repo::/work', hostId: 'local' }) diff --git a/src/main/github/github-issue-link-title-fill.ts b/src/main/github/workspace-links/github-issue-link-title-fill.ts similarity index 83% rename from src/main/github/github-issue-link-title-fill.ts rename to src/main/github/workspace-links/github-issue-link-title-fill.ts index f3551b91b0f..b9a7b25cfa2 100644 --- a/src/main/github/github-issue-link-title-fill.ts +++ b/src/main/github/workspace-links/github-issue-link-title-fill.ts @@ -1,18 +1,18 @@ -import type { ExecutionHostId } from '../../shared/execution-host' -import type { Repo } from '../../shared/repo-types' -import type { WorktreeMeta } from '../../shared/worktree/meta-types' -import type { WorkspaceAttachment } from '../../shared/worktree/types' -import type { WorkspaceAttachmentMutation } from '../../shared/workspace-attachments/workspace-attachment-mutation' -import { getWorkspaceAttachments } from '../../shared/workspace-attachments/workspace-attachments' -import { WORKSPACE_ATTACHMENT_NUMBER_SLOTS } from '../../shared/workspace-attachments/workspace-attachment-legacy' -import { getWorkspaceReferenceIdentity } from '../../shared/workspace-attachments/workspace-reference-identity' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import type { WorkspaceAttachment } from '../../../shared/worktree/types' +import type { WorkspaceAttachmentMutation } from '../../../shared/workspace-attachments/workspace-attachment-mutation' +import { getWorkspaceAttachments } from '../../../shared/workspace-attachments/workspace-attachments' +import { WORKSPACE_ATTACHMENT_NUMBER_SLOTS } from '../../../shared/workspace-attachments/workspace-attachment-legacy' +import { getWorkspaceReferenceIdentity } from '../../../shared/workspace-attachments/workspace-reference-identity' import { hostWorktreeTarget, type HostWorktreeTarget -} from '../../shared/worktree/host-qualified-identity' -import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' -import type { WorktreeMetaWriteListener } from '../persistence/loading-store/profile-writing/write-scheduling' -import { findRepoRowForHostScopedWrite } from '../persistence/tracking-repos/repo-update-operations' +} from '../../../shared/worktree/host-qualified-identity' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' +import type { WorktreeMetaWriteListener } from '../../persistence/loading-store/profile-writing/write-scheduling' +import { findRepoRowForHostScopedWrite } from '../../persistence/tracking-repos/repo-update-operations' export type GitHubIssueLinkTitleFillStore = { onWorktreeMetaWritten: (listener: WorktreeMetaWriteListener) => () => void diff --git a/src/main/github/github-issue-link-title-wiring.ts b/src/main/github/workspace-links/github-issue-link-title-wiring.ts similarity index 78% rename from src/main/github/github-issue-link-title-wiring.ts rename to src/main/github/workspace-links/github-issue-link-title-wiring.ts index 0c22857efcf..dda69ec8103 100644 --- a/src/main/github/github-issue-link-title-wiring.ts +++ b/src/main/github/workspace-links/github-issue-link-title-wiring.ts @@ -1,18 +1,18 @@ -import type { Repo } from '../../shared/repo-types' -import { composeWorktreeHostIdentity } from '../../shared/worktree/host-qualified-identity' -import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' +import type { Repo } from '../../../shared/repo-types' +import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import { workspaceMetadataSetRow, type WorkspaceMetadataSet -} from '../../shared/worktree/workspace-metadata-set' -import type { WorkspaceAttachment } from '../../shared/worktree/types' -import { getRepoRoutingConnectionId } from '../../shared/execution-host' -import type { Store } from '../persistence/loading-store/store' -import { getLocalProjectGhExecOptions } from '../workspaces/execution-host/project-runtime-git-options' -import { getIssue } from './issues' -import { getWorkItemByOwnerRepo } from './client/fetch/get-work-item' +} from '../../../shared/worktree/metadata/workspace-metadata-set' +import type { WorkspaceAttachment } from '../../../shared/worktree/types' +import { getRepoRoutingConnectionId } from '../../../shared/execution-host' +import type { Store } from '../../persistence/loading-store/store' +import { getLocalProjectGhExecOptions } from '../../workspaces/execution-host/project-runtime-git-options' +import { getIssue } from '../issues/issues' +import { getWorkItemByOwnerRepo } from '../client/fetch/get-work-item' import { installGitHubIssueLinkTitleFill } from './github-issue-link-title-fill' -import { readGitHubRepoUnlessWslStopped } from '../ipc/source-control/github-repo-routing' +import { readGitHubRepoUnlessWslStopped } from '../../ipc/source-control/github-repo-routing' const GITHUB_ISSUE_PATH = /^\/([^/]+)\/([^/]+)\/issues\/(\d+)$/ diff --git a/src/main/gitlab/issues/gitlab-issue-source-resolution.ts b/src/main/gitlab/issues/gitlab-issue-source-resolution.ts index 51ea83f57c1..22a799e5ff2 100644 --- a/src/main/gitlab/issues/gitlab-issue-source-resolution.ts +++ b/src/main/gitlab/issues/gitlab-issue-source-resolution.ts @@ -1,6 +1,6 @@ import { listCachedRemoteNames, shouldProbeGitRemote } from '../../git/remotes/remote-name-listing' import type { IssueSourcePreference } from '../../../shared/repo-types' -import { readLocalGitConfigSignature } from '../../github/local-git-config-signature' +import { readLocalGitConfigSignature } from '../../github/repositories/local-git-config-signature' import { getProjectRefForRemoteWithSignature } from '../projects/gitlab-project-ref-resolution' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/gitlab/merge-requests/merge-request-lookup.ts b/src/main/gitlab/merge-requests/merge-request-lookup.ts index 339e5ba436d..bb946ecc0e6 100644 --- a/src/main/gitlab/merge-requests/merge-request-lookup.ts +++ b/src/main/gitlab/merge-requests/merge-request-lookup.ts @@ -81,6 +81,10 @@ export async function getMergeRequest( head_pipeline?: { status?: string } | null pipeline?: { status?: string } | null } + // glab serializes GitLab's null changes_count as ''. + if (data.changes_count === '') { + data.changes_count = null + } // Why: older GitLab instances expose `pipeline` instead of `head_pipeline`; try both. const pipelineStatus = derivePipelineStatus(data.head_pipeline ?? data.pipeline ?? null) return mapMRInfo(data, pipelineStatus) @@ -226,6 +230,7 @@ export async function getMergeRequestForBranch( iid: info.number, headOid: currentHead, revisionHeadSha: info.headSha, + baseRefName: info.baseRefName, diffRefs: raw.diff_refs, connectionId, localGitOptions, diff --git a/src/main/gitlab/merge-requests/merge-request-state-mutations.ts b/src/main/gitlab/merge-requests/merge-request-state-mutations.ts index f573bd83486..7a044923083 100644 --- a/src/main/gitlab/merge-requests/merge-request-state-mutations.ts +++ b/src/main/gitlab/merge-requests/merge-request-state-mutations.ts @@ -6,7 +6,7 @@ import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { withProjectRef } from './merge-request-project-resolution' import { codeHostFailure } from '../../../shared/code-host-failure-copy' -import { invalidateReviewLookupsAfterPRMutation } from '../../github/pr-mutation-review-invalidation' +import { invalidateReviewLookupsAfterPRMutation } from '../../github/pull-requests/refresh/pr-mutation-review-invalidation' // Why: glab's MRCheckErrors refuses a no-op close/reopen with these fixed texts; every other // failure, including "has already been merged", must surface. diff --git a/src/main/gitlab/merge-requests/merge-request-update.ts b/src/main/gitlab/merge-requests/merge-request-update.ts index 0b6862004ba..6384692890b 100644 --- a/src/main/gitlab/merge-requests/merge-request-update.ts +++ b/src/main/gitlab/merge-requests/merge-request-update.ts @@ -11,7 +11,7 @@ import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' import { withProjectRef } from './merge-request-project-resolution' import { tryMarkMRReady } from './merge-request-ready' import { codeHostFailure, classifiedFailure } from '../../../shared/code-host-failure-copy' -import { invalidateReviewLookupsAfterPRMutation } from '../../github/pr-mutation-review-invalidation' +import { invalidateReviewLookupsAfterPRMutation } from '../../github/pull-requests/refresh/pr-mutation-review-invalidation' export async function updateMR( repoPath: string, diff --git a/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts b/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts index 864f846944e..ca6ed0095d8 100644 --- a/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts +++ b/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts @@ -11,6 +11,7 @@ import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-projec import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' +import { mergedReviewHeadIsEquivalent } from '../../source-control/merged-review-head-equivalence' const membershipMemo = new MergedReviewMembershipMemo>({ weight: (ids) => 1024 + 256 * ids.size, @@ -87,6 +88,7 @@ export async function mergedMRContainsHead( iid: number headOid: string revisionHeadSha?: string + baseRefName?: string diffRefs?: unknown userRefresh?: boolean } @@ -142,5 +144,17 @@ export async function mergedMRContainsHead( load, { refreshFailed: args.userRefresh } ) - return ids.has(args.headOid.toLowerCase()) ? 'contained' : 'not-contained' + if (ids.has(args.headOid.toLowerCase())) { + return 'contained' + } + // A local rebase mints a SHA GitLab never saw; prove it adds nothing beyond the merged MR. + const equivalent = await mergedReviewHeadIsEquivalent({ + repoPath: args.repoPath, + connectionId: args.connectionId, + localGitOptions: args.localGitOptions, + reviewHeadOid: args.revisionHeadSha, + baseBranchName: args.baseRefName, + headOid: args.headOid + }) + return equivalent ? 'contained' : 'not-contained' } diff --git a/src/main/gitlab/merge-requests/review-project-identity.ts b/src/main/gitlab/merge-requests/review-project-identity.ts index babb85d7926..de8026c692f 100644 --- a/src/main/gitlab/merge-requests/review-project-identity.ts +++ b/src/main/gitlab/merge-requests/review-project-identity.ts @@ -1,12 +1,11 @@ import { runCoalescedProbe, type CoalescedProbes } from '../../git/remotes/coalesced-probe' import { codeHostReadExecutionScope } from '../../source-control/code-host-read-execution-scope' -import { readLocalGitConfigSignature } from '../../github/local-git-config-signature' +import { readLocalGitConfigSignature } from '../../github/repositories/local-git-config-signature' import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' -import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' -import { normalizeGitLabHost } from '../projects/project-ref-parser' +import { type ProjectRef, normalizeGitLabHost } from '../projects/project-ref-parser' type ProjectIdentity = { id: number; path: string } type CachedIdentity = { value: ProjectIdentity; expiresAt: number; configSignature?: string } diff --git a/src/main/gitlab/projects/gitlab-known-host-probe.ts b/src/main/gitlab/projects/gitlab-known-host-probe.ts index b587dd8941c..affc49d6fde 100644 --- a/src/main/gitlab/projects/gitlab-known-host-probe.ts +++ b/src/main/gitlab/projects/gitlab-known-host-probe.ts @@ -4,7 +4,7 @@ import { extractExecError } from '../../git/command-runner/process-capture/exec- import { NEGATIVE_ENTRY_TTL_MS } from '../../git/remotes/remote-ref-probe-cache' import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { DEFAULT_GITLAB_HOSTS, normalizeGitLabHost } from './project-ref-parser' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' export type LocalGitExecOptions = { wslDistro?: string diff --git a/src/main/gitlab/projects/gitlab-project-ref-resolution.ts b/src/main/gitlab/projects/gitlab-project-ref-resolution.ts index 26f419c84a6..9dbae92e469 100644 --- a/src/main/gitlab/projects/gitlab-project-ref-resolution.ts +++ b/src/main/gitlab/projects/gitlab-project-ref-resolution.ts @@ -1,9 +1,9 @@ import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { addWslEnvKeys } from '../../../shared/wsl-env' import { isTransientGitProbeError, readRemoteUrl } from '../../git/remotes/remote-url-probe' import { NEGATIVE_ENTRY_TTL_MS } from '../../git/remotes/remote-ref-probe-cache' -import { readLocalGitConfigSignature } from '../../github/local-git-config-signature' +import { readLocalGitConfigSignature } from '../../github/repositories/local-git-config-signature' import { clearProjectRefInFlight, runProjectRefProbeOnce } from './project-ref-inflight' import { _resetGlabUnauthenticatedHosts, diff --git a/src/main/gitlab/requests/gitlab-response-mapping.ts b/src/main/gitlab/requests/gitlab-response-mapping.ts index cacb4150846..578b255d175 100644 --- a/src/main/gitlab/requests/gitlab-response-mapping.ts +++ b/src/main/gitlab/requests/gitlab-response-mapping.ts @@ -1,5 +1,5 @@ import { gitLabPipelineJobOutcome } from '../../../shared/source-control/checks/gitlab/gitlab-pipeline-checks' -import type { CheckStatus } from '../../../shared/github/pull-request-types' +import type { CheckStatus } from '../../../shared/github/pull-requests/pull-request-types' import type { GitLabIssueInfo, GitLabWorkItem, MRInfo, MRState } from '../../../shared/gitlab-types' import { summarizeProviderChecks } from '../../../shared/source-control/checks/provider-check-summary' @@ -65,6 +65,8 @@ type GitLabMRRaw = { updatedAt?: string sha?: string has_conflicts?: boolean + /** Absent from list responses; null until GitLab persists a diff with commits. */ + changes_count?: string | null detailed_merge_status?: string /** Deprecated since GitLab 15.6, but the only merge signal older instances return. */ merge_status?: string @@ -110,14 +112,20 @@ export function settleManualPipelineStatus( } function deriveMergeable(data: GitLabMRRaw): MRInfo['mergeable'] { - if (data.has_conflicts === true) { + // GitLab marks merge requests without commits unmergeable (has_conflicts, broken_status), but + // with no diff there is nothing to conflict. + const noDiff = data.changes_count === null + if (data.has_conflicts === true && !noDiff) { return 'CONFLICTING' } // Only positive mergeable is stable enough to enable merging; pending prerequisites remain unknown. if (data.detailed_merge_status === 'mergeable') { return 'MERGEABLE' } - if (data.detailed_merge_status === 'broken_status' || data.detailed_merge_status === 'conflict') { + if ( + (data.detailed_merge_status === 'broken_status' || data.detailed_merge_status === 'conflict') && + !noDiff + ) { return 'CONFLICTING' } // GitLab <15.6 supplies only legacy merge_status; trust its positive value while conflicts use has_conflicts. @@ -184,6 +192,7 @@ type GitLabMRRawForWorkItem = { source_project_id?: number target_project_id?: number has_conflicts?: boolean + changes_count?: string | null detailed_merge_status?: string } diff --git a/src/main/gitlab/requests/glab-request-admission.test.ts b/src/main/gitlab/requests/glab-request-admission.test.ts index 6846251a84a..fb086d75f78 100644 --- a/src/main/gitlab/requests/glab-request-admission.test.ts +++ b/src/main/gitlab/requests/glab-request-admission.test.ts @@ -18,7 +18,7 @@ vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', async (importOrigi glabExecFileAsync: glabExecFileAsyncMock })) -vi.mock('../../github/local-git-config-signature', () => ({ +vi.mock('../../github/repositories/local-git-config-signature', () => ({ readLocalGitConfigSignature: readLocalGitConfigSignatureMock })) import { _resetProjectRefCache, getProjectRef } from '../projects/gitlab-project-ref-resolution' diff --git a/src/main/grok/grok-session-history.ts b/src/main/grok/grok-session-history.ts index 52dbecd6203..925e3ef53f5 100644 --- a/src/main/grok/grok-session-history.ts +++ b/src/main/grok/grok-session-history.ts @@ -2,7 +2,7 @@ import { ownOptionsInclude, resumeInvocationFromOptions, type StructuredAgentSessionHistory -} from '../native-chat/structured-agent-cli-conversations' +} from '../native-chat/conversation-adoption/structured-agent-cli-conversations' const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i diff --git a/src/main/grok/grok-text-task.ts b/src/main/grok/grok-text-task.ts index 3f497293a64..7d953b44d66 100644 --- a/src/main/grok/grok-text-task.ts +++ b/src/main/grok/grok-text-task.ts @@ -3,9 +3,9 @@ import { resolveProviderChildEnv, type ProviderProcessLaunch } from '../provider-process/provider-process-launch' -import { runLocalSourceControlPlan } from '../text-generation/source-control-local-process' -import { spawnSourceControlAgent } from '../text-generation/source-control-agent-launch' -import { cancelLocalGeneration } from '../text-generation/source-control-generation-lanes' +import { runLocalSourceControlPlan } from '../text-generation/execution/source-control-local-process' +import { spawnSourceControlAgent } from '../text-generation/execution/source-control-agent-launch' +import { cancelLocalGeneration } from '../text-generation/execution/source-control-generation-lanes' export const GROK_TEXT_TASK_ENV = { GROK_STORAGE_MODE: 'local' } as const diff --git a/src/main/grok/grok-transcript-import.ts b/src/main/grok/grok-transcript-import.ts index 5a40aa6744b..927e6505ce1 100644 --- a/src/main/grok/grok-transcript-import.ts +++ b/src/main/grok/grok-transcript-import.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' import { findGrokChatHistoryByCwd, resolveGrokHomeDir } from '../../shared/grok-session-paths' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' -import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-conversations' +import { directoryTranscriptImport } from '../native-chat/conversation-adoption/structured-agent-cli-conversations' export const GROK_TRANSCRIPT_IMPORT = directoryTranscriptImport({ conversationStore: ({ accountHomePath }) => join(accountHomePath, 'sessions'), diff --git a/src/main/hang-watchdog/hang-capture-codec.ts b/src/main/hang-watchdog/hang-capture-codec.ts new file mode 100644 index 00000000000..d3fa0feca63 --- /dev/null +++ b/src/main/hang-watchdog/hang-capture-codec.ts @@ -0,0 +1,128 @@ +import { parseHangStacks, type MainJsCapture, type NativeHangCapture } from './hang-stacks' +import type { HangObservation } from './hang-observation-schema' + +export function parseMainJsCapture(value: unknown): MainJsCapture | undefined { + const stacks = parseHangStacks(value) + if (!stacks || !value || typeof value !== 'object') { + return undefined + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding branch excludes null and non-objects before reading unknown properties. + const data = value as Record + if ( + !['collecting', 'stop-pending', 'completed', 'failed', 'not-started'].includes( + String(data.state) + ) + ) { + return undefined + } + const result: MainJsCapture = { + ...stacks, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixed state allowlist above validates this string union. + state: data.state as MainJsCapture['state'], + cleanup: data.cleanup === 'drain-complete' ? 'drain-complete' : 'pending', + samplingIntervalUs: 10_000, + requestedCaptureMs: 5_000, + budgetBasis: 'detection', + overlap: data.overlap === 'post-recovery' ? 'post-recovery' : 'unconfirmed' + } + for (const key of [ + 'startPostedAfterDetectionMs', + 'startAcknowledgedAfterDetectionMs', + 'stopRequestedAfterDetectionMs', + 'stopPostedAfterDetectionMs', + 'stopAcknowledgedAfterDetectionMs', + 'stopAckDelayMs', + 'profileDurationMs' + ] as const) { + if (typeof data[key] === 'number' && Number.isFinite(data[key]) && data[key] >= 0) { + result[key] = Math.min(data[key], Number.MAX_SAFE_INTEGER) + } + } + if (['recovery', 'deadline', 'shutdown'].includes(String(data.stopReason))) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixed stop-reason allowlist validates this value. + result.stopReason = data.stopReason as MainJsCapture['stopReason'] + } + return result +} + +export function parseNativeHangCapture(value: unknown): NativeHangCapture | undefined { + const stacks = parseHangStacks(value) + if (!stacks || !value || typeof value !== 'object') { + return undefined + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding branch excludes null and non-objects before reading unknown properties. + const data = value as Record + if ( + !['collecting', 'completed', 'failed'].includes(String(data.state)) || + typeof data.startedAt !== 'number' || + !Number.isFinite(data.startedAt) || + data.startedAt < 0 + ) { + return undefined + } + return { + ...stacks, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixed state allowlist above validates this string union. + state: data.state as NativeHangCapture['state'], + startedAt: data.startedAt, + ...(typeof data.completedAt === 'number' && + Number.isFinite(data.completedAt) && + data.completedAt >= data.startedAt + ? { completedAt: data.completedAt } + : {}), + mainThreadIdentified: data.mainThreadIdentified === true, + mainSectionComplete: data.mainSectionComplete === true, + reportTruncated: data.reportTruncated === true, + timedOut: data.timedOut === true, + cleanup: + data.cleanup === 'terminated' + ? 'terminated' + : data.cleanup === 'unverified' + ? 'unverified' + : 'pending', + ...(typeof data.exitCode === 'number' && Number.isSafeInteger(data.exitCode) + ? { exitCode: data.exitCode } + : {}) + } +} + +export function admitHangObservation(record: HangObservation): HangObservation { + const candidate: HangObservation = { + ...record, + ...(record.mainJs ? { mainJs: structuredClone(record.mainJs) } : {}), + ...(record.native ? { native: structuredClone(record.native) } : {}) + } + const bytes = (): number => Buffer.byteLength(JSON.stringify(candidate)) + if (bytes() <= 7 * 1024) { + return candidate + } + candidate.completedSpans = null + for (const capture of [candidate.mainJs, candidate.native]) { + if (!capture) { + continue + } + while (bytes() > 7 * 1024 && capture.stacks.length > 1) { + capture.stacks.pop() + capture.truncated = true + } + } + for (const capture of [candidate.mainJs, candidate.native]) { + if (!capture) { + continue + } + while (bytes() > 7 * 1024 && capture.stacks[0]?.frames.length > 1) { + capture.stacks[0].frames.pop() + capture.truncated = true + } + if (bytes() > 7 * 1024) { + for (const stack of capture.stacks) { + for (const frame of stack.frames) { + frame.name = frame.name.slice(0, 24) + frame.module = frame.module.slice(0, 24) + capture.truncated = true + } + } + } + } + return candidate +} diff --git a/src/main/hang-watchdog/hang-capture-details.ts b/src/main/hang-watchdog/hang-capture-details.ts new file mode 100644 index 00000000000..7a4a0237376 --- /dev/null +++ b/src/main/hang-watchdog/hang-capture-details.ts @@ -0,0 +1,23 @@ +import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' +import type { HangStacks } from './hang-stacks' + +export function hangCaptureDetails( + prefix: string, + capture: HangStacks & object +): CrashReportBreadcrumbData { + const details: CrashReportBreadcrumbData = {} + for (const [key, value] of Object.entries(capture)) { + if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') { + details[`${prefix}_${key}`] = value + } + } + for (const [index, stack] of capture.stacks.entries()) { + details[`${prefix}${index}_count`] = stack.count + details[`${prefix}${index}_hot`] = stack.hot + for (const [frameIndex, frame] of stack.frames.entries()) { + details[`${prefix}${index}_frame${frameIndex}`] = + `${frame.name} [${frame.module}${frame.line !== undefined ? `:${frame.line}:${frame.column ?? 0}` : ''}]` + } + } + return details +} diff --git a/src/main/hang-watchdog/hang-detection-marker.test.ts b/src/main/hang-watchdog/hang-detection-marker.test.ts index 462035c146f..cc34fa55617 100644 --- a/src/main/hang-watchdog/hang-detection-marker.test.ts +++ b/src/main/hang-watchdog/hang-detection-marker.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync, statSync } from 'node:fs' +import { mkdtempSync, rmSync, existsSync, readFileSync, statSync, renameSync } from 'node:fs' import type * as FileSystem from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -14,7 +14,8 @@ vi.mock('node:fs', async (importOriginal) => { return { ...actual, readFileSync: vi.fn(actual.readFileSync), - statSync: vi.fn(actual.statSync) + statSync: vi.fn(actual.statSync), + renameSync: vi.fn(actual.renameSync) } }) @@ -29,6 +30,19 @@ describe('hang detection marker', () => { rmSync(dir, { recursive: true, force: true }) }) + it('retains the complete baseline if publishing enrichment is interrupted', () => { + const markerPath = hangDetectionMarkerPath(dir) + const baseline = { detectedAt: 1, parentPid: 2, unresponsiveMs: 45_000, selfRecovered: false } + writeHangDetectionMarker(markerPath, baseline) + vi.mocked(renameSync).mockImplementationOnce(() => { + throw new Error('interrupted replacement') + }) + expect(() => + writeHangDetectionMarker(markerPath, { ...baseline, selfRecovered: true }) + ).toThrow() + expect(consumeHangDetectionMarker(markerPath)).toEqual(baseline) + }) + it.each(['stat', 'read'])('retains a real marker after a transient %s failure', (operation) => { const markerPath = hangDetectionMarkerPath(dir) const marker = { detectedAt: 1, parentPid: 2, unresponsiveMs: 45000, selfRecovered: false } @@ -46,13 +60,4 @@ describe('hang detection marker', () => { expect(consumeHangDetectionMarker(markerPath)).toEqual(marker) expect(existsSync(markerPath)).toBe(false) }) - - it('deletes an oversized marker without reading its contents', () => { - const markerPath = hangDetectionMarkerPath(dir) - writeFileSync(markerPath, 'x'.repeat(64 * 1024 + 1)) - vi.mocked(readFileSync).mockClear() - expect(consumeHangDetectionMarker(markerPath)).toBeNull() - expect(readFileSync).not.toHaveBeenCalled() - expect(existsSync(markerPath)).toBe(false) - }) }) diff --git a/src/main/hang-watchdog/hang-detection-marker.ts b/src/main/hang-watchdog/hang-detection-marker.ts index c01dc4dc948..c53ff65eca7 100644 --- a/src/main/hang-watchdog/hang-detection-marker.ts +++ b/src/main/hang-watchdog/hang-detection-marker.ts @@ -1,66 +1,81 @@ -import { readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { + closeSync, + fchmodSync, + openSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync +} from 'node:fs' import { join } from 'node:path' +import { + asHangObservations, + latestHangMarker, + parseLegacyHangMarker, + type HangDetectionMarker, + type HangObservationCollection +} from './hang-observations' -// The next launch consumes detection/resolution markers; selfRecovered distinguishes cleared stalls from unresolved hangs. -export type HangDetectionMarker = { - detectedAt: number - parentPid: number - unresponsiveMs: number - selfRecovered: boolean -} +export type { HangDetectionMarker } from './hang-observations' +export type StoredHangMarker = HangDetectionMarker | HangObservationCollection export function hangDetectionMarkerPath(userDataPath: string): string { return join(userDataPath, 'main-thread-hang.json') } -export function writeHangDetectionMarker(markerPath: string, marker: HangDetectionMarker): void { - writeFileSync(markerPath, JSON.stringify(marker), { mode: 0o600 }) +export function writeHangDetectionMarker(markerPath: string, marker: StoredHangMarker): void { + const collection = 'version' in marker ? asHangObservations(marker) : null + if ( + 'version' in marker && + (!collection || collection.observations.length !== marker.observations.length) + ) { + throw new Error('Invalid hang observations') + } + const text = JSON.stringify( + collection ? { ...latestHangMarker(collection), ...collection } : marker + ) + if (Buffer.byteLength(text) > 32 * 1024) { + throw new Error('Hang observations exceed byte bound') + } + const temporaryPath = `${markerPath}.tmp` + const fd = openSync(temporaryPath, 'w', 0o600) + try { + fchmodSync(fd, 0o600) + writeFileSync(fd, text) + } finally { + closeSync(fd) + } + renameSync(temporaryPath, markerPath) } -function readAvailableHangDetectionMarker( +export function readAvailableHangDetectionMarker( markerPath: string -): HangDetectionMarker | null | undefined { +): StoredHangMarker | null | undefined { let raw: string try { if (statSync(markerPath).size > 64 * 1024) { return null } raw = readFileSync(markerPath, 'utf8') - } catch { - return undefined + } catch (error) { + return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT' + ? null + : undefined } try { const parsed: unknown = JSON.parse(raw) - if ( - typeof parsed !== 'object' || - !parsed || - !('detectedAt' in parsed) || - typeof parsed.detectedAt !== 'number' || - !Number.isFinite(parsed.detectedAt) || - !('parentPid' in parsed) || - typeof parsed.parentPid !== 'number' || - !Number.isInteger(parsed.parentPid) || - parsed.parentPid <= 0 || - !('unresponsiveMs' in parsed) || - typeof parsed.unresponsiveMs !== 'number' || - !Number.isFinite(parsed.unresponsiveMs) || - parsed.unresponsiveMs < 0 - ) { - return null - } - return { - detectedAt: parsed.detectedAt, - parentPid: parsed.parentPid, - unresponsiveMs: parsed.unresponsiveMs, - // Missing recovery evidence leaves the stall unresolved. - selfRecovered: 'selfRecovered' in parsed && parsed.selfRecovered === true + if (typeof parsed === 'object' && parsed && 'version' in parsed && parsed.version === 1) { + const collection = Buffer.byteLength(raw) <= 32 * 1024 ? asHangObservations(parsed) : null + return collection ? { ...latestHangMarker(collection), ...collection } : null } + return parseLegacyHangMarker(parsed) } catch { return null } } -export function consumeHangDetectionMarker(markerPath: string): HangDetectionMarker | null { +export function consumeHangDetectionMarker(markerPath: string): StoredHangMarker | null { const marker = readAvailableHangDetectionMarker(markerPath) // Retry unavailable reads next startup; only successfully inspected files are consumable. if (marker === undefined) { diff --git a/src/main/hang-watchdog/hang-incident-snapshot.ts b/src/main/hang-watchdog/hang-incident-snapshot.ts new file mode 100644 index 00000000000..76c20ced683 --- /dev/null +++ b/src/main/hang-watchdog/hang-incident-snapshot.ts @@ -0,0 +1,149 @@ +import { closeSync, fstatSync, openSync, readSync } from 'node:fs' +import { freemem, loadavg, totalmem } from 'node:os' +import { sanitizeCrashReportString } from '../../shared/crash-report-redaction' +import { redactString } from '../observability/redactor' +import type { CompletedHangContext, HangMachineSnapshot } from './hang-observations' + +function numberMatch(text: string, expression: RegExp): number | null { + const match = expression.exec(text) + const value = match ? Number(match[1]) : Number.NaN + return Number.isFinite(value) && value >= 0 ? value : null +} +export function parseMacHangPressure( + sysctl: string, + vmStat: string +): Pick< + HangMachineSnapshot, + | 'systemMemorySwapTotalMB' + | 'systemMemorySwapUsedMB' + | 'systemMemoryCompressorMB' + | 'systemMemoryPressureLevel' + | 'systemMemoryStatusLevel' +> { + const swap = (key: string): number | null => { + const match = new RegExp(`\\b${key} = ([\\d.]+)([KMGT])\\b`).exec(sysctl) + if (!match) { + return null + } + const factor = { K: 1 / 1024, M: 1, G: 1024, T: 1024 * 1024 }[match[2]] + const value = Number(match[1]) * (factor ?? Number.NaN) + return Number.isFinite(value) && value >= 0 ? value : null + } + const pageSize = numberMatch(vmStat, /page size of (\d+) bytes/) + const compressor = numberMatch(vmStat, /^Pages occupied by compressor:\s+(\d+)\.?\s*$/m) + const compressorMB = + pageSize !== null && compressor !== null ? (pageSize * compressor) / 1024 / 1024 : null + return { + systemMemorySwapTotalMB: swap('total'), + systemMemorySwapUsedMB: swap('used'), + systemMemoryCompressorMB: + compressorMB !== null && Number.isFinite(compressorMB) ? compressorMB : null, + systemMemoryPressureLevel: numberMatch( + sysctl, + /^kern\.memorystatus_vm_pressure_level:\s+(\d+)\s*$/m + ), + systemMemoryStatusLevel: numberMatch(sysctl, /^kern\.memorystatus_level:\s+(\d+)\s*$/m) + } +} + +export async function collectHangMachineSnapshot( + signal: AbortSignal +): Promise { + const loads = loadavg() + const snapshot: HangMachineSnapshot = { + startedAt: Date.now(), + completedAt: null, + systemMemoryTotalMB: totalmem() / 1024 / 1024, + systemMemoryFreeMB: freemem() / 1024 / 1024, + systemMemorySwapTotalMB: null, + systemMemorySwapUsedMB: null, + systemMemoryCompressorMB: null, + systemMemoryPressureLevel: null, + systemMemoryStatusLevel: null, + load1: process.platform === 'win32' ? null : loads[0], + load5: process.platform === 'win32' ? null : loads[1], + load15: process.platform === 'win32' ? null : loads[2] + } + if (process.platform === 'darwin' && !signal.aborted) { + const { runProcess } = await import('@orca/process-host') + const commands = await Promise.allSettled([ + runProcess({ + program: '/usr/sbin/sysctl', + args: ['vm.swapusage', 'kern.memorystatus_level', 'kern.memorystatus_vm_pressure_level'], + timeoutMs: 2_000, + maxOutputBytes: 32 * 1024, + signal + }), + runProcess({ + program: '/usr/bin/vm_stat', + timeoutMs: 2_000, + maxOutputBytes: 32 * 1024, + signal + }) + ]) + const outputs = commands.map((result) => + result.status === 'fulfilled' && !result.value.timedOut && !result.value.outputTruncated + ? result.value.stdout + : '' + ) + Object.assign(snapshot, parseMacHangPressure(outputs[0], outputs[1])) + } + snapshot.completedAt = Date.now() + return snapshot +} + +export function readCompletedHangContext( + tracePath: string | undefined +): CompletedHangContext[] | null { + if (!tracePath) { + return null + } + let fd: number | undefined + try { + fd = openSync(tracePath, 'r') + const size = fstatSync(fd).size + const offset = Math.max(0, size - 32 * 1024) + const buffer = Buffer.allocUnsafe(Math.min(size, 32 * 1024)) + const bytes = readSync(fd, buffer, 0, buffer.length, offset) + const lines = buffer.subarray(0, bytes).toString('utf8').split('\n') + lines.pop() + if (offset > 0) { + lines.shift() + } + const spans: CompletedHangContext[] = [] + for (let index = lines.length - 1; index >= 0 && spans.length < 8; index--) { + try { + const data = JSON.parse(lines[index]) + if ( + data?.type !== 'effect-span' || + typeof data.name !== 'string' || + typeof data.startTimeUnixNano !== 'string' || + !/^\d{1,24}$/.test(data.startTimeUnixNano) || + typeof data.endTimeUnixNano !== 'string' || + !/^\d{1,24}$/.test(data.endTimeUnixNano) + ) { + continue + } + const startedAt = Number(data.startTimeUnixNano) / 1_000_000 + const completedAt = Number(data.endTimeUnixNano) / 1_000_000 + if (startedAt > completedAt) { + continue + } + spans.push({ + name: sanitizeCrashReportString(redactString(data.name), 120).slice(0, 120), + startedAt, + completedAt + }) + } catch { + // Concurrent appends and interrupted writes can leave incomplete records. + } + } + return spans.toReversed() + } catch { + return null + } finally { + if (fd !== undefined) { + closeSync(fd) + } + } +} diff --git a/src/main/hang-watchdog/hang-observation-ownership.test.ts b/src/main/hang-watchdog/hang-observation-ownership.test.ts new file mode 100644 index 00000000000..c3cbf6c7668 --- /dev/null +++ b/src/main/hang-watchdog/hang-observation-ownership.test.ts @@ -0,0 +1,190 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import type * as FileSystem from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { HangMachineSnapshot } from './hang-observations' +import type { MainToHangWatchdogWorkerMessage } from './hang-watchdog-worker-protocol' +import { asHangObservations } from './hang-observations' +import { consumeHangDetectionMarker, writeHangDetectionMarker } from './hang-detection-marker' +import { runWatchdog } from './main-thread-hang-watchdog-entry' +import { preservePreviousHangDetection } from './previous-hang-detection' + +const probes = vi.hoisted<{ pending: ((value: HangMachineSnapshot) => void)[] }>(() => ({ + pending: [] +})) +const files = vi.hoisted<{ unavailablePath: string | null }>(() => ({ unavailablePath: null })) +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readFileSync: (...args: Parameters) => { + if (args[0] === files.unavailablePath) { + throw Object.assign(new Error('temporarily unreadable'), { code: 'EIO' }) + } + return actual.readFileSync(...args) + } + } +}) +vi.mock('../observability', () => ({ + resolveObservabilityConsent: () => ({ localFileEnabled: true }) +})) +vi.mock('./hang-incident-snapshot', () => ({ + readCompletedHangContext: () => [], + collectHangMachineSnapshot: () => + new Promise((resolve) => probes.pending.push(resolve)) +})) +const staleMachine: HangMachineSnapshot = { + startedAt: 125, + completedAt: 250, + systemMemoryTotalMB: 64_000, + systemMemoryFreeMB: 8_000, + systemMemorySwapTotalMB: 1024, + systemMemorySwapUsedMB: 100, + systemMemoryCompressorMB: 500, + systemMemoryPressureLevel: 2, + systemMemoryStatusLevel: 40, + load1: 2, + load5: 3, + load15: 4 +} +beforeEach(() => { + probes.pending = [] + files.unavailablePath = null + vi.useFakeTimers() + vi.setSystemTime(0) +}) +afterEach(() => { + files.unavailablePath = null + for (const resolve of probes.pending) { + resolve(staleMachine) + } + vi.useRealTimers() +}) + +it('cannot let a retired pressure read replace a newer stall or undo recovery', async () => { + const dir = mkdtempSync(join(tmpdir(), 'hang-ownership-')) + const markerPath = join(dir, 'marker.json') + let send: (message: MainToHangWatchdogWorkerMessage) => void = () => {} + runWatchdog( + { parentPid: process.pid, markerPath, timeoutMs: 100, checkIntervalMs: 25 }, + { + on: (_event, listener) => { + send = listener + }, + close() {} + } + ) + try { + vi.advanceTimersByTime(125) + await vi.dynamicImportSettled() + send({ type: 'heartbeat' }) + vi.advanceTimersByTime(125) + probes.pending[0](staleMachine) + await vi.dynamicImportSettled() + const records = asHangObservations(consumeHangDetectionMarker(markerPath))?.observations + expect( + records?.map(({ kind, selfRecovered, machine }) => ({ kind, selfRecovered, machine })) + ).toEqual([ + { kind: 'heartbeat-stall', selfRecovered: true, machine: null }, + { kind: 'heartbeat-stall', selfRecovered: false, machine: null } + ]) + expect(records?.[0].snapshot).not.toBeNull() + expect(records?.[0].resolution).not.toBeNull() + expect(records?.[1].resolution).toBeNull() + } finally { + send({ type: 'shutdown' }) + rmSync(dir, { recursive: true, force: true }) + } +}) + +it.each([ + { scenario: 'open suspend across a normal tick', suspendAt: 0, resumeAt: null, expected: true }, + { scenario: 'completed sleep before a normal tick', suspendAt: 0, resumeAt: 0, expected: false }, + { scenario: 'resume before the overdue tick', suspendAt: 0, resumeAt: 1000, expected: true }, + { scenario: 'suspend at the gap end', suspendAt: 1000, resumeAt: null, expected: false } +])('retains honest sleep association for $scenario', ({ suspendAt, resumeAt, expected }) => { + const dir = mkdtempSync(join(tmpdir(), 'hang-power-gap-')) + const markerPath = join(dir, 'marker.json') + let send: (message: MainToHangWatchdogWorkerMessage) => void = () => {} + runWatchdog( + { parentPid: process.pid, markerPath, timeoutMs: 100, checkIntervalMs: 25 }, + { + on: (_event, listener) => { + send = listener + }, + close() {} + } + ) + try { + if (suspendAt === 0) { + send({ type: 'power-event', event: 'suspend', observedAt: 0 }) + } + if (resumeAt === 0) { + send({ type: 'power-event', event: 'resume', observedAt: 0 }) + } + vi.advanceTimersByTime(25) + send({ type: 'heartbeat' }) + vi.setSystemTime(1000) + if (suspendAt === 1000) { + send({ type: 'power-event', event: 'suspend', observedAt: 1000 }) + } + if (resumeAt === 1000) { + send({ type: 'power-event', event: 'resume', observedAt: 1000 }) + } + vi.advanceTimersByTime(25) + const collection = asHangObservations(consumeHangDetectionMarker(markerPath)) + expect(collection?.observations).toMatchObject([ + { kind: 'watchdog-gap', initialSleepAssociated: expected, resolution: null } + ]) + if (suspendAt === 1000) { + for (let index = 0; index < 5; index++) { + send({ type: 'power-event', event: 'resume', observedAt: Date.now() }) + send({ type: 'heartbeat' }) + send({ type: 'power-event', event: 'suspend', observedAt: Date.now() }) + vi.advanceTimersByTime(25) + vi.setSystemTime(Date.now() + 1000) + vi.advanceTimersByTime(25) + } + expect( + asHangObservations(consumeHangDetectionMarker(markerPath))?.observations + ).toContainEqual(expect.objectContaining({ detectedAt: 1025, initialSleepAssociated: false })) + } + } finally { + send({ type: 'shutdown' }) + rmSync(dir, { recursive: true, force: true }) + } +}) + +it('keeps unavailable startup bytes until a later observation can safely merge them', () => { + const dir = mkdtempSync(join(tmpdir(), 'hang-unavailable-')) + const markerPath = join(dir, 'main-thread-hang.json') + const original = { detectedAt: 1, parentPid: 999, unresponsiveMs: 45_000, selfRecovered: false } + writeHangDetectionMarker(markerPath, original) + const originalBytes = readFileSync(markerPath, 'utf8') + files.unavailablePath = markerPath + preservePreviousHangDetection(dir) + let send: (message: MainToHangWatchdogWorkerMessage) => void = () => {} + runWatchdog( + { parentPid: process.pid, markerPath, timeoutMs: 100, checkIntervalMs: 25 }, + { + on: (_event, listener) => { + send = listener + }, + close() {} + } + ) + try { + vi.advanceTimersByTime(125) + files.unavailablePath = null + expect(readFileSync(markerPath, 'utf8')).toBe(originalBytes) + send({ type: 'heartbeat' }) + expect(asHangObservations(consumeHangDetectionMarker(markerPath))?.observations).toMatchObject([ + { parentPid: 999, detectedAt: 1, selfRecovered: false }, + { parentPid: process.pid, detectedAt: 125, selfRecovered: true } + ]) + } finally { + send({ type: 'shutdown' }) + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/src/main/hang-watchdog/hang-observation-schema.ts b/src/main/hang-watchdog/hang-observation-schema.ts new file mode 100644 index 00000000000..475b984c633 --- /dev/null +++ b/src/main/hang-watchdog/hang-observation-schema.ts @@ -0,0 +1,61 @@ +export const SNAPSHOT_FIELDS = [ + 'wallMs', + 'monotonicMs', + 'uptimeSeconds', + 'processUserUs', + 'processSystemUs', + 'watchdogUserUs', + 'watchdogSystemUs' +] as const +export type HangSnapshot = Record<(typeof SNAPSHOT_FIELDS)[number], number | null> + +export const MACHINE_FIELDS = [ + 'startedAt', + 'completedAt', + 'systemMemoryTotalMB', + 'systemMemoryFreeMB', + 'systemMemorySwapTotalMB', + 'systemMemorySwapUsedMB', + 'systemMemoryCompressorMB', + 'systemMemoryPressureLevel', + 'systemMemoryStatusLevel', + 'load1', + 'load5', + 'load15' +] as const +export type HangMachineSnapshot = Record<(typeof MACHINE_FIELDS)[number], number | null> +export type HangPowerReceipt = { + event: 'suspend' | 'resume' | 'lock-screen' | 'unlock-screen' + observedAt: number + receivedAt: number +} +export type CompletedHangContext = { name: string; startedAt: number; completedAt: number } +export type HangObservation = { + id: string + kind: 'heartbeat-stall' | 'watchdog-gap' + detectedAt: number + parentPid: number + durationMs: number + selfRecovered: boolean + initialSleepAssociated: boolean + snapshot: HangSnapshot | null + resolution: HangSnapshot | null + machine: HangMachineSnapshot | null + completedSpans: CompletedHangContext[] | null + powerEvents: HangPowerReceipt[] + mainJs?: MainJsCapture + native?: NativeHangCapture + watchdogGap?: { observedAt: number; durationMs: number; snapshot: HangSnapshot | null } +} +export type HangObservationCollection = { + version: 1 + observations: HangObservation[] + omitted: number +} +export type HangDetectionMarker = { + detectedAt: number + parentPid: number + unresponsiveMs: number + selfRecovered: boolean +} +import type { MainJsCapture, NativeHangCapture } from './hang-stacks' diff --git a/src/main/hang-watchdog/hang-observations.test.ts b/src/main/hang-watchdog/hang-observations.test.ts new file mode 100644 index 00000000000..77a2aeb1cf5 --- /dev/null +++ b/src/main/hang-watchdog/hang-observations.test.ts @@ -0,0 +1,125 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { consumeHangDetectionMarker, writeHangDetectionMarker } from './hang-detection-marker' +import { + asHangObservations, + emptyHangObservations, + mergeHangObservations, + retainHangObservation, + type HangObservation +} from './hang-observations' +import { parseMacHangPressure, readCompletedHangContext } from './hang-incident-snapshot' + +function observation(id: string, kind: HangObservation['kind'], sleep = false): HangObservation { + return { + id, + kind, + detectedAt: 10_000, + parentPid: 7, + durationMs: 162_000, + selfRecovered: false, + initialSleepAssociated: sleep, + snapshot: null, + resolution: null, + machine: null, + completedSpans: null, + powerEvents: [] + } +} + +it('keeps the original unexplained gap and recovered stall through subsequent ordinary sleeps', () => { + const dir = mkdtempSync(join(tmpdir(), 'hang-retention-')) + try { + const gap = observation('7:1:1', 'watchdog-gap') + const stall = observation('7:2:1', 'heartbeat-stall') + let collection = retainHangObservation( + retainHangObservation(emptyHangObservations(), gap), + stall + ) + collection = retainHangObservation(collection, { + ...gap, + initialSleepAssociated: true, + powerEvents: [{ event: 'resume', observedAt: 172_000, receivedAt: 172_001 }] + }) + collection = retainHangObservation(collection, { ...stall, selfRecovered: true }) + for (const id of ['7:3:1', '7:4:1', '7:5:1', '7:6:1', '7:7:1']) { + collection = retainHangObservation(collection, observation(id, 'watchdog-gap', true)) + } + collection = mergeHangObservations( + collection, + retainHangObservation(emptyHangObservations(), stall) + ) + const markerPath = join(dir, 'marker.json') + writeHangDetectionMarker(markerPath, collection) + const persisted = asHangObservations(consumeHangDetectionMarker(markerPath)) + expect( + persisted?.observations.map(({ id, selfRecovered, initialSleepAssociated }) => ({ + id, + selfRecovered, + initialSleepAssociated + })) + ).toEqual([ + { id: '7:1:1', selfRecovered: false, initialSleepAssociated: false }, + { id: '7:2:1', selfRecovered: true, initialSleepAssociated: false }, + { id: '7:6:1', selfRecovered: false, initialSleepAssociated: true }, + { id: '7:7:1', selfRecovered: false, initialSleepAssociated: true } + ]) + expect(persisted?.observations[0].powerEvents).toEqual([ + { event: 'resume', observedAt: 172_000, receivedAt: 172_001 } + ]) + expect(persisted?.omitted).toBe(3) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +it('parses actual macOS units and page size without inventing missing measurements', () => { + expect( + parseMacHangPressure( + 'vm.swapusage: total = 1.50G used = 512.00M free = 1024.00M\nkern.memorystatus_level: 48\nkern.memorystatus_vm_pressure_level: 2\n', + 'Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages occupied by compressor: 42.\n' + ) + ).toEqual({ + systemMemorySwapTotalMB: 1536, + systemMemorySwapUsedMB: 512, + systemMemoryCompressorMB: 0.65625, + systemMemoryPressureLevel: 2, + systemMemoryStatusLevel: 48 + }) + expect(parseMacHangPressure('', 'Pages occupied by compressor: 42.')).toEqual({ + systemMemorySwapTotalMB: null, + systemMemorySwapUsedMB: null, + systemMemoryCompressorMB: null, + systemMemoryPressureLevel: null, + systemMemoryStatusLevel: null + }) +}) + +it('keeps only complete recent context and sanitizes complete names before truncating', () => { + const dir = mkdtempSync(join(tmpdir(), 'hang-context-')) + try { + const path = join(dir, 'trace.ndjson') + writeFileSync( + path, + `${JSON.stringify({ + type: 'effect-span', + name: 'old-span', + startTimeUnixNano: '1000000', + endTimeUnixNano: '2000000' + })}\n${'x'.repeat(40_000)}\n${JSON.stringify({ + type: 'effect-span', + name: `git.exec password=${'a'.repeat(200)}`, + startTimeUnixNano: '3000000', + endTimeUnixNano: '4000000', + attributes: { private: 'discard' } + })}\n{"type":"effect-span","name":"incomplete` + ) + expect(readCompletedHangContext(path)).toEqual([ + { name: 'git.exec [redacted:labeled-kv]', startedAt: 3, completedAt: 4 } + ]) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/src/main/hang-watchdog/hang-observations.ts b/src/main/hang-watchdog/hang-observations.ts new file mode 100644 index 00000000000..d101f56f227 --- /dev/null +++ b/src/main/hang-watchdog/hang-observations.ts @@ -0,0 +1,291 @@ +import { + MACHINE_FIELDS, + SNAPSHOT_FIELDS, + type HangPowerReceipt, + type CompletedHangContext, + type HangObservation, + type HangObservationCollection, + type HangDetectionMarker +} from './hang-observation-schema' +import { + admitHangObservation, + parseMainJsCapture, + parseNativeHangCapture +} from './hang-capture-codec' +export { MACHINE_FIELDS, SNAPSHOT_FIELDS } from './hang-observation-schema' +export type { + HangSnapshot, + HangMachineSnapshot, + HangPowerReceipt, + CompletedHangContext, + HangObservation, + HangObservationCollection, + HangDetectionMarker +} from './hang-observation-schema' + +function object(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the branch excludes null, primitives and arrays before reading unknown properties. + (value as Record) + : null +} +function finite(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 +} +function numericFields( + value: unknown, + keys: readonly K[] +): Record | null { + const data = object(value) + if (!data) { + return null + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: every supplied key is emitted once with a finite number or null. + return Object.fromEntries( + keys.map((key) => [key, finite(data[key]) ? data[key] : null]) + ) as Record +} +export function parsePowerReceipt(value: unknown): HangPowerReceipt | null { + const data = object(value) + if ( + !data || + !['suspend', 'resume', 'lock-screen', 'unlock-screen'].includes(String(data.event)) || + !finite(data.observedAt) || + !finite(data.receivedAt) + ) { + return null + } + return { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixed event allowlist above validates this string union. + event: data.event as HangPowerReceipt['event'], + observedAt: data.observedAt, + receivedAt: data.receivedAt + } +} +export function parseLegacyHangMarker(value: unknown): HangDetectionMarker | null { + const data = object(value) + if ( + !data || + !finite(data.detectedAt) || + !finite(data.parentPid) || + !Number.isInteger(data.parentPid) || + data.parentPid <= 0 || + !finite(data.unresponsiveMs) + ) { + return null + } + return { + detectedAt: data.detectedAt, + parentPid: data.parentPid, + unresponsiveMs: data.unresponsiveMs, + selfRecovered: data.selfRecovered === true + } +} +function parseObservation(value: unknown): HangObservation | null { + const data = object(value) + if ( + !data || + typeof data.id !== 'string' || + !/^[\d:.-]{1,80}$/.test(data.id) || + !['heartbeat-stall', 'watchdog-gap'].includes(String(data.kind)) || + !finite(data.detectedAt) || + !finite(data.parentPid) || + !Number.isInteger(data.parentPid) || + data.parentPid <= 0 || + !finite(data.durationMs) + ) { + return null + } + const completedSpans: CompletedHangContext[] = [] + if (Array.isArray(data.completedSpans) && data.completedSpans.length <= 8) { + for (const item of data.completedSpans) { + const span = object(item) + if ( + span && + typeof span.name === 'string' && + span.name.length <= 120 && + finite(span.startedAt) && + finite(span.completedAt) && + span.startedAt <= span.completedAt + ) { + completedSpans.push({ + name: span.name, + startedAt: span.startedAt, + completedAt: span.completedAt + }) + } + } + } + const gap = object(data.watchdogGap) + return { + id: data.id, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixed observation-kind allowlist above validates this string union. + kind: data.kind as HangObservation['kind'], + detectedAt: data.detectedAt, + parentPid: data.parentPid, + durationMs: data.durationMs, + selfRecovered: data.selfRecovered === true, + initialSleepAssociated: data.initialSleepAssociated === true, + snapshot: numericFields(data.snapshot, SNAPSHOT_FIELDS), + resolution: numericFields(data.resolution, SNAPSHOT_FIELDS), + machine: numericFields(data.machine, MACHINE_FIELDS), + completedSpans: Array.isArray(data.completedSpans) ? completedSpans : null, + powerEvents: Array.isArray(data.powerEvents) + ? data.powerEvents + .slice(-4) + .map(parsePowerReceipt) + .filter((v): v is HangPowerReceipt => v !== null) + : [], + ...(data.mainJs ? { mainJs: parseMainJsCapture(data.mainJs) } : {}), + ...(data.native ? { native: parseNativeHangCapture(data.native) } : {}), + ...(gap && finite(gap.observedAt) && finite(gap.durationMs) + ? { + watchdogGap: { + observedAt: gap.observedAt, + durationMs: gap.durationMs, + snapshot: numericFields(gap.snapshot, SNAPSHOT_FIELDS) + } + } + : {}) + } +} +export function emptyHangObservations(): HangObservationCollection { + return { version: 1, observations: [], omitted: 0 } +} +export function asHangObservations(value: unknown): HangObservationCollection | null { + const data = object(value) + if (data?.version === 1) { + if (!Array.isArray(data.observations) || data.observations.length > 4) { + return null + } + return { + version: 1, + observations: data.observations + .map(parseObservation) + .filter((v): v is HangObservation => v !== null), + omitted: finite(data.omitted) ? Math.min(2_147_483_647, Math.floor(data.omitted)) : 0 + } + } + const legacy = parseLegacyHangMarker(value) + if (!legacy) { + return null + } + return { + version: 1, + omitted: 0, + observations: [ + { + id: `${legacy.parentPid}:${legacy.detectedAt}:0`, + kind: 'heartbeat-stall', + detectedAt: legacy.detectedAt, + parentPid: legacy.parentPid, + durationMs: legacy.unresponsiveMs, + selfRecovered: legacy.selfRecovered, + initialSleepAssociated: false, + snapshot: null, + resolution: null, + machine: null, + completedSpans: null, + powerEvents: [] + } + ] + } +} +function priority(record: HangObservation): number { + return record.kind === 'heartbeat-stall' ? 3 : record.initialSleepAssociated ? 1 : 2 +} +export function retainHangObservation( + collection: HangObservationCollection, + record: HangObservation +): HangObservationCollection { + record = admitHangObservation(record) + const existing = collection.observations.findIndex((item) => item.id === record.id) + if (existing !== -1) { + const old = collection.observations[existing] + const observations = collection.observations.slice() + const receipts = new Map( + [...old.powerEvents, ...record.powerEvents].map( + (item) => [`${item.event}:${item.observedAt}:${item.receivedAt}`, item] as const + ) + ) + observations[existing] = admitHangObservation({ + ...record, + kind: old.kind, + id: old.id, + detectedAt: old.detectedAt, + parentPid: old.parentPid, + durationMs: old.durationMs, + initialSleepAssociated: old.initialSleepAssociated, + snapshot: old.snapshot, + selfRecovered: old.selfRecovered || record.selfRecovered, + resolution: old.resolution ?? record.resolution, + machine: old.machine ?? record.machine, + completedSpans: old.completedSpans ?? record.completedSpans, + mainJs: record.mainJs + ? { + ...record.mainJs, + stacks: record.mainJs.stacks.length ? record.mainJs.stacks : (old.mainJs?.stacks ?? []) + } + : old.mainJs, + native: record.native + ? { + ...record.native, + stacks: record.native.stacks.length ? record.native.stacks : (old.native?.stacks ?? []) + } + : old.native, + powerEvents: [...receipts.values()].slice(-4), + watchdogGap: + old.watchdogGap && old.watchdogGap.durationMs > (record.watchdogGap?.durationMs ?? -1) + ? old.watchdogGap + : (record.watchdogGap ?? old.watchdogGap) + }) + return { ...collection, observations } + } + const candidates = [...collection.observations, record] + const anchors = new Set( + [ + candidates.find((item) => item.kind === 'heartbeat-stall'), + candidates.find((item) => item.kind === 'watchdog-gap' && !item.initialSleepAssociated) + ].filter((item): item is HangObservation => !!item) + ) + const selected = new Set(anchors) + const ranked = candidates + .map((item, index) => ({ item, index })) + .filter(({ item }) => !anchors.has(item)) + .sort((a, b) => priority(b.item) - priority(a.item) || b.index - a.index) + for (const { item } of ranked) { + if (selected.size < 4) { + selected.add(item) + } + } + return { + version: 1, + observations: candidates.filter((item) => selected.has(item)), + omitted: Math.min(2_147_483_647, collection.omitted + candidates.length - selected.size) + } +} +export function mergeHangObservations( + first: HangObservationCollection, + second: HangObservationCollection +): HangObservationCollection { + let result = { ...first, omitted: Math.min(2_147_483_647, first.omitted + second.omitted) } + for (const record of second.observations) { + result = retainHangObservation(result, record) + } + return result +} +export function latestHangMarker( + collection: HangObservationCollection +): HangDetectionMarker | null { + const record = collection.observations.findLast((item) => item.kind === 'heartbeat-stall') + return record + ? { + detectedAt: record.detectedAt, + parentPid: record.parentPid, + unresponsiveMs: + record.durationMs + + Math.max(0, (record.resolution?.wallMs ?? record.detectedAt) - record.detectedAt), + selfRecovered: record.selfRecovered + } + : null +} diff --git a/src/main/hang-watchdog/hang-profile-reducer.ts b/src/main/hang-watchdog/hang-profile-reducer.ts new file mode 100644 index 00000000000..9e9cf625aa1 --- /dev/null +++ b/src/main/hang-watchdog/hang-profile-reducer.ts @@ -0,0 +1,78 @@ +import type { Profiler } from 'node:inspector' +import { + hangLabel, + hangModule, + topHangStacks, + type HangStacks, + type HangFrame, + type HangStack +} from './hang-stacks' + +export function reduceHangProfile(profile: Profiler.Profile): HangStacks { + const nodes = new Map() + const parents = new Map() + let edgeBudget = 20_000 + let truncated = profile.nodes.length > 10_000 || (profile.samples?.length ?? 0) > 100_000 + for (let i = 0; i < Math.min(profile.nodes.length, 10_000); i++) { + const node = profile.nodes[i] + nodes.set(node.id, node) + for (const child of node.children ?? []) { + if (parents.size >= 10_000 || edgeBudget-- <= 0) { + truncated = true + break + } + parents.set(child, node.id) + } + } + const counts = new Map() + let validSamples = 0 + const samples = profile.samples ?? [] + for (let i = 0; i < Math.min(samples.length, 100_000); i++) { + const id = samples[i] + const frame = nodes.get(id)?.callFrame + if ( + !frame || + ['(root)', '(idle)', '(program)', '(garbage collector)'].includes(frame.functionName) + ) { + continue + } + counts.set(id, (counts.get(id) ?? 0) + 1) + validSamples++ + } + const selected: { id: number; count: number }[] = [] + for (const [id, count] of counts) { + if (selected.length === 3 && count <= selected[2].count) { + continue + } + selected.push({ id, count }) + selected.sort((a, b) => b.count - a.count) + selected.splice(3) + } + const top: HangStack[] = [] + for (const { id, count } of selected) { + const frames: HangFrame[] = [] + const seen = new Set() + let current: number | undefined = id + while (current !== undefined && frames.length < 8 && !seen.has(current)) { + seen.add(current) + const node = nodes.get(current) + if (!node) { + truncated = true + break + } + const frame = node.callFrame + if (!['(root)', '(idle)', '(program)'].includes(frame.functionName)) { + frames.push({ + name: hangLabel(frame.functionName || '(anonymous)'), + module: hangModule(frame.url), + ...(frame.lineNumber >= 0 ? { line: frame.lineNumber + 1 } : {}), + ...(frame.columnNumber >= 0 ? { column: frame.columnNumber + 1 } : {}) + }) + } + current = parents.get(current) + } + const ranked = topHangStacks([...top, { frames, count, hot: false }], validSamples) + top.splice(0, top.length, ...ranked) + } + return { stacks: top, samples: samples.length, validSamples, truncated } +} diff --git a/src/main/hang-watchdog/hang-snapshot.ts b/src/main/hang-watchdog/hang-snapshot.ts new file mode 100644 index 00000000000..65f1096c3e8 --- /dev/null +++ b/src/main/hang-watchdog/hang-snapshot.ts @@ -0,0 +1,22 @@ +import { uptime } from 'node:os' +import type { HangSnapshot } from './hang-observations' + +export function captureHangSnapshot(): HangSnapshot { + const cpu = process.cpuUsage() + let watchdog: NodeJS.CpuUsage | null = null + try { + const read = process.threadCpuUsage + watchdog = read?.call(process) ?? null + } catch { + // Some Electron runtimes do not expose per-thread CPU counters. + } + return { + wallMs: Date.now(), + monotonicMs: performance.now(), + uptimeSeconds: uptime(), + processUserUs: cpu.user, + processSystemUs: cpu.system, + watchdogUserUs: watchdog?.user ?? null, + watchdogSystemUs: watchdog?.system ?? null + } +} diff --git a/src/main/hang-watchdog/hang-stack-evidence.test.ts b/src/main/hang-watchdog/hang-stack-evidence.test.ts new file mode 100644 index 00000000000..4f52e632fcd --- /dev/null +++ b/src/main/hang-watchdog/hang-stack-evidence.test.ts @@ -0,0 +1,122 @@ +import { expect, it } from 'vitest' +import { reduceHangProfile } from './hang-profile-reducer' +import { reduceNativeHangSample } from './native-hang-capture' +import { retainHangObservation, emptyHangObservations } from './hang-observations' +import { writeHangDetectionMarker, readAvailableHangDetectionMarker } from './hang-detection-marker' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { HangObservation } from './hang-observations' + +it('retains observed stacks when five equal callers have no stack above twenty percent', () => { + const result = reduceHangProfile({ + startTime: 0, + endTime: 100, + samples: [1, 2, 3, 4, 5], + nodes: [1, 2, 3, 4, 5].map((id) => ({ + id, + callFrame: { + functionName: `caller${id}`, + scriptId: '1', + url: '/private/user/app.js', + lineNumber: 4, + columnNumber: 2 + } + })) + }) + expect(result.stacks.map((item) => [item.frames[0].name, item.count, item.hot])).toEqual([ + ['caller1', 1, false], + ['caller2', 1, false], + ['caller3', 1, false] + ]) + expect(result.stacks[0].frames[0]).toEqual({ + name: 'caller1', + module: 'app.js', + line: 5, + column: 3 + }) +}) + +it('requires a main section terminator independently of report truncation', () => { + const prefix = + ' 12 Thread_10 DispatchQueue_1: com.apple.main-thread (serial)\n + 12 appMain (in Orca) + 1\n + 12 kevent (in libsystem_kernel.dylib) + 2\n' + expect(reduceNativeHangSample(prefix)).toMatchObject({ + mainThreadIdentified: true, + mainSectionComplete: false, + stacks: [ + { + frames: [ + { name: 'kevent', module: 'libsystem_kernel.dylib' }, + { name: 'appMain', module: 'Orca' } + ], + count: 12 + } + ] + }) + expect(reduceNativeHangSample(`${prefix} 12 Thread_11\n`)).toMatchObject({ + mainSectionComplete: true + }) + expect( + reduceNativeHangSample(prefix.replace('com.apple.main-thread', 'background')) + ).toMatchObject({ mainThreadIdentified: false, stacks: [] }) +}) + +it('admits escaped multibyte evidence before committing history so recovery can still be written', () => { + const folder = mkdtempSync(join(tmpdir(), 'hang-stack-admission-')) + try { + let collection = emptyHangObservations() + for (let id = 1; id <= 4; id++) { + const record: HangObservation = { + id: `1:${id}:1`, + parentPid: 1, + kind: 'heartbeat-stall', + detectedAt: id, + durationMs: 45_000, + selfRecovered: false, + initialSleepAssociated: false, + snapshot: null, + resolution: null, + machine: null, + completedSpans: null, + powerEvents: [], + mainJs: { + state: 'completed', + cleanup: 'pending', + samplingIntervalUs: 10_000, + requestedCaptureMs: 5000, + budgetBasis: 'detection', + overlap: 'unconfirmed', + samples: 10, + validSamples: 10, + truncated: false, + stacks: [1, 2, 3].map(() => ({ + count: 10, + hot: true, + frames: Array.from({ length: 8 }, () => ({ + name: '\\"界'.repeat(24), + module: '\\"界'.repeat(16) + })) + })) + } + } + collection = retainHangObservation(collection, record) + } + const path = join(folder, 'main-thread-hang.json') + writeHangDetectionMarker(path, collection) + collection = retainHangObservation(collection, { + ...collection.observations[0], + selfRecovered: true + }) + writeHangDetectionMarker(path, collection) + expect(readAvailableHangDetectionMarker(path)).toMatchObject({ + observations: [ + expect.objectContaining({ selfRecovered: true }), + expect.anything(), + expect.anything(), + expect.anything() + ] + }) + } finally { + rmSync(folder, { recursive: true, force: true }) + } +}) diff --git a/src/main/hang-watchdog/hang-stacks.ts b/src/main/hang-watchdog/hang-stacks.ts new file mode 100644 index 00000000000..58b136c26bd --- /dev/null +++ b/src/main/hang-watchdog/hang-stacks.ts @@ -0,0 +1,134 @@ +import { sanitizeCrashReportString } from '../../shared/crash-report-redaction' +import { redactString } from '../observability/redactor' + +export type HangFrame = { name: string; module: string; line?: number; column?: number } +export type HangStack = { frames: HangFrame[]; count: number; hot: boolean } +export type HangStacks = { + stacks: HangStack[] + samples: number + validSamples: number + truncated: boolean +} +export type MainJsCapture = HangStacks & { + state: 'collecting' | 'stop-pending' | 'completed' | 'failed' | 'not-started' + cleanup: 'pending' | 'drain-complete' + samplingIntervalUs: number + requestedCaptureMs: number + budgetBasis: 'detection' + stopReason?: 'recovery' | 'deadline' | 'shutdown' + startPostedAfterDetectionMs?: number + startAcknowledgedAfterDetectionMs?: number + stopRequestedAfterDetectionMs?: number + stopPostedAfterDetectionMs?: number + stopAcknowledgedAfterDetectionMs?: number + stopAckDelayMs?: number + profileDurationMs?: number + overlap: 'unconfirmed' | 'post-recovery' +} +export type NativeHangCapture = HangStacks & { + state: 'collecting' | 'completed' | 'failed' + startedAt: number + completedAt?: number + mainThreadIdentified: boolean + mainSectionComplete: boolean + reportTruncated: boolean + timedOut: boolean + cleanup: 'pending' | 'terminated' | 'unverified' + exitCode?: number +} + +export const emptyHangStacks = (): HangStacks => ({ + stacks: [], + samples: 0, + validSamples: 0, + truncated: false +}) + +export function hangLabel(value: unknown, limit = 96): string { + // Reject whole oversized fields before redaction so a cut secret cannot escape matching. + if (typeof value !== 'string' || value.length > 512) { + return '' + } + return sanitizeCrashReportString(redactString(value), limit).slice(0, limit) +} + +export function hangModule(value: unknown): string { + if (typeof value !== 'string' || value.length > 2048) { + return '' + } + const path = value.split(/[?#]/, 1)[0] + const basename = path.split(/[/\\]/).at(-1) ?? '' + return hangLabel(basename, 64) +} + +export function topHangStacks(candidates: HangStack[], validSamples: number): HangStack[] { + const top: HangStack[] = [] + for (const candidate of candidates) { + if (!candidate.frames.length || candidate.count <= 0) { + continue + } + const rank = top.findIndex((item) => item.count < candidate.count) + if (rank !== -1) { + top.splice(rank, 0, candidate) + } else if (top.length < 3) { + top.push(candidate) + } + if (top.length > 3) { + top.pop() + } + } + return top.map((item) => ({ ...item, hot: item.count > validSamples * 0.2 })) +} + +export function parseHangStacks(value: unknown): HangStacks | null { + if (!value || typeof value !== 'object') { + return null + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding branch excludes null and non-objects before reading unknown properties. + const data = value as Record + if (!Array.isArray(data.stacks) || data.stacks.length > 3) { + return null + } + const stacks: HangStack[] = [] + for (const item of data.stacks) { + if ( + !item || + !Array.isArray(item.frames) || + item.frames.length > 8 || + !Number.isSafeInteger(item.count) || + item.count <= 0 + ) { + continue + } + const frames: HangFrame[] = [] + for (const frame of item.frames) { + if (!frame || typeof frame.name !== 'string' || typeof frame.module !== 'string') { + continue + } + frames.push({ + name: hangLabel(frame.name), + module: hangLabel(frame.module, 64), + ...(Number.isSafeInteger(frame.line) && frame.line >= 0 ? { line: frame.line } : {}), + ...(Number.isSafeInteger(frame.column) && frame.column >= 0 ? { column: frame.column } : {}) + }) + } + if (frames.length) { + stacks.push({ frames, count: item.count, hot: false }) + } + } + const validSamples = + typeof data.validSamples === 'number' && + Number.isSafeInteger(data.validSamples) && + data.validSamples >= 0 + ? data.validSamples + : 0 + return { + stacks: topHangStacks(stacks, validSamples), + validSamples, + samples: + typeof data.samples === 'number' && Number.isSafeInteger(data.samples) && data.samples >= 0 + ? data.samples + : 0, + truncated: data.truncated === true + } +} diff --git a/src/main/hang-watchdog/hang-watchdog-detection-loop.ts b/src/main/hang-watchdog/hang-watchdog-detection-loop.ts index a91b8297532..52904fe1887 100644 --- a/src/main/hang-watchdog/hang-watchdog-detection-loop.ts +++ b/src/main/hang-watchdog/hang-watchdog-detection-loop.ts @@ -5,6 +5,7 @@ export type HangWatchdogDetectionLoopConfig = { onHangDetected: (unresponsiveMs: number) => void /** Heartbeats resumed after a detected hang — the main thread was stalled, not deadlocked. */ onHangResolved: (unresponsiveMs: number) => void + onWatchdogGap?: (gapMs: number, startedAt: number) => void } export type HangWatchdogDetectionLoop = { @@ -32,12 +33,17 @@ export function createHangWatchdogDetectionLoop( const tickGap = now - lastTickAt // Advance while hung so recovery cannot be misclassified as a long system-sleep gap. lastTickAt = now - if (detected) { + // Sleep, process suspension and observer starvation are indistinguishable here. + if (tickGap > config.checkIntervalMs * 3) { + if (tickGap > config.timeoutMs) { + config.onWatchdogGap?.(tickGap, now - tickGap) + } + if (!detected) { + lastHeartbeatAt = now + } return } - // System sleep suspends the watchdog too; restart the silence window after large tick gaps. - if (tickGap > config.checkIntervalMs * 3) { - lastHeartbeatAt = now + if (detected) { return } const unresponsiveMs = now - lastHeartbeatAt diff --git a/src/main/hang-watchdog/hang-watchdog-worker-protocol.ts b/src/main/hang-watchdog/hang-watchdog-worker-protocol.ts index 14e6d007796..b731d1fa6d2 100644 --- a/src/main/hang-watchdog/hang-watchdog-worker-protocol.ts +++ b/src/main/hang-watchdog/hang-watchdog-worker-protocol.ts @@ -7,6 +7,29 @@ export type HangWatchdogWorkerData = { markerPath: string timeoutMs: number checkIntervalMs: number + tracePath?: string } -export type MainToHangWatchdogWorkerMessage = { type: 'heartbeat' } | { type: 'shutdown' } +export type MainToHangWatchdogWorkerMessage = + | { type: 'heartbeat' } + | { type: 'shutdown' } + | { type: 'capture-drain-ack'; token: string } + | { type: 'power-event'; event: HangPowerReceipt['event']; observedAt: number } +import type { HangPowerReceipt } from './hang-observations' + +export type HangWatchdogToMainMessage = { type: 'capture-drain'; token: string } + +export function isHangWatchdogWorkerData(value: unknown): value is HangWatchdogWorkerData { + const data = value as Partial | null + return ( + !!data && + Number.isInteger(data.parentPid) && + (data.parentPid ?? 0) > 0 && + typeof data.markerPath === 'string' && + (data.tracePath === undefined || typeof data.tracePath === 'string') && + Number.isFinite(data.timeoutMs) && + (data.timeoutMs ?? 0) > 0 && + Number.isFinite(data.checkIntervalMs) && + (data.checkIntervalMs ?? 0) > 0 + ) +} diff --git a/src/main/hang-watchdog/main-js-hang-capture.test.ts b/src/main/hang-watchdog/main-js-hang-capture.test.ts new file mode 100644 index 00000000000..5f52c1a1eb2 --- /dev/null +++ b/src/main/hang-watchdog/main-js-hang-capture.test.ts @@ -0,0 +1,91 @@ +import { expect, it, vi } from 'vitest' +import { captureMainJsHang } from './main-js-hang-capture' +import type { MainJsCapture } from './hang-stacks' + +function fixture() { + let callback: ((error: Error | null, result?: unknown) => void) | undefined + const commands: string[] = [] + const disconnect = vi.fn() + let finishDrain: (() => void) | undefined + const records: MainJsCapture[] = [] + const capture = captureMainJsHang({ + session: { + connectToMainThread: () => {}, + disconnect, + post: (method, _params, response) => { + commands.push(method) + callback = response + } + }, + detectedAt: 0, + now: () => 100, + publish: (record) => records.push(record), + drain: () => + new Promise((resolve) => { + finishDrain = resolve + }) + }) + const acknowledge = async (result?: unknown, error: Error | null = null): Promise => { + const response = callback + callback = undefined + response?.(error, result) + await Promise.resolve() + await Promise.resolve() + } + return { capture, commands, disconnect, records, acknowledge, drain: () => finishDrain?.() } +} + +it('does not start after recovery while enable is pending, and drains only after disable acknowledgement', async () => { + const f = fixture() + f.capture.stop('recovery') + expect(f.disconnect).not.toHaveBeenCalled() + await f.acknowledge() + expect(f.commands).toEqual(['Profiler.enable', 'Profiler.disable']) + expect(f.disconnect).not.toHaveBeenCalled() + await f.acknowledge() + expect(f.disconnect).toHaveBeenCalledOnce() + expect(f.records.at(-1)?.cleanup).toBe('pending') + f.drain() + await f.capture.done + expect(f.records.at(-1)).toMatchObject({ + state: 'not-started', + cleanup: 'drain-complete', + stopReason: 'recovery' + }) +}) + +it('owns a posted start and its stop through shutdown without racing disconnect', async () => { + const f = fixture() + await f.acknowledge() + await f.acknowledge() + expect(f.commands).toEqual(['Profiler.enable', 'Profiler.setSamplingInterval', 'Profiler.start']) + f.capture.stop('shutdown') + await f.acknowledge() + expect(f.commands.at(-1)).toBe('Profiler.stop') + expect(f.disconnect).not.toHaveBeenCalled() + await f.acknowledge({ profile: { nodes: [], samples: [], startTime: 1000, endTime: 3000 } }) + expect(f.commands.at(-1)).toBe('Profiler.disable') + expect(f.disconnect).not.toHaveBeenCalled() + await f.acknowledge() + f.drain() + await f.capture.done + expect(f.records.at(-1)).toMatchObject({ + state: 'completed', + profileDurationMs: 2, + cleanup: 'drain-complete', + stopReason: 'shutdown' + }) +}) + +it('does not disconnect or release an owner after stop fails', async () => { + const f = fixture() + await f.acknowledge() + await f.acknowledge() + await f.acknowledge() + f.capture.stop('recovery') + await Promise.resolve() + await f.acknowledge(undefined, new Error('stop rejected')) + expect(f.commands.at(-1)).toBe('Profiler.stop') + expect(f.disconnect).not.toHaveBeenCalled() + expect(f.records.at(-1)).toMatchObject({ state: 'failed', cleanup: 'pending' }) +}) diff --git a/src/main/hang-watchdog/main-js-hang-capture.ts b/src/main/hang-watchdog/main-js-hang-capture.ts new file mode 100644 index 00000000000..243144e6630 --- /dev/null +++ b/src/main/hang-watchdog/main-js-hang-capture.ts @@ -0,0 +1,165 @@ +import { reduceHangProfile } from './hang-profile-reducer' +import type { Profiler, Session } from 'node:inspector' +import { emptyHangStacks, type MainJsCapture } from './hang-stacks' + +type ProfilerCommandParameters = { interval?: number } +type CaptureSession = Pick & { + post: ( + method: string, + params: ProfilerCommandParameters, + callback: (error: Error | null, result?: unknown) => void + ) => void +} +type StopReason = NonNullable + +function reduceStopResult(value: unknown): Partial | null { + if (!value || typeof value !== 'object' || !('profile' in value)) { + return null + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a successful Profiler.stop response supplies the inspector's typed profile. + const profile = value.profile as Profiler.Profile + const reduced = reduceHangProfile(profile) + const duration = (profile.endTime - profile.startTime) / 1000 + return { + ...reduced, + state: 'completed', + ...(Number.isFinite(duration) && duration >= 0 ? { profileDurationMs: duration } : {}) + } +} + +export function captureMainJsHang(options: { + session: CaptureSession + now: () => number + detectedAt: number + publish: (capture: MainJsCapture) => void + drain: () => Promise +}): { stop: (reason: StopReason) => void; done: Promise } { + let intent: StopReason | undefined + let wake: (() => void) | undefined + let transportUncertain = false + let capture: MainJsCapture = { + ...emptyHangStacks(), + state: 'collecting', + cleanup: 'pending', + samplingIntervalUs: 10_000, + requestedCaptureMs: 5_000, + budgetBasis: 'detection', + overlap: 'unconfirmed' + } + const elapsed = (): number => Math.max(0, options.now() - options.detectedAt) + const publish = (change: Partial): void => { + capture = { ...capture, ...change } + options.publish(capture) + } + const stop = (reason: StopReason): void => { + if (intent) { + return + } + intent = reason + publish({ stopReason: reason, stopRequestedAfterDetectionMs: elapsed(), state: 'stop-pending' }) + wake?.() + } + const canStart = (): boolean => { + if (elapsed() >= 5_000) { + stop('deadline') + } + return !intent + } + const deadline = setTimeout(() => stop('deadline'), Math.max(0, 5_000 - elapsed())) + publish({}) + const post = ( + method: string, + params: ProfilerCommandParameters = {} + ): Promise<{ ok: boolean; result?: unknown }> => + new Promise((resolve) => { + // Exactly one caller awaits each response before the next command or disconnect. + try { + options.session.post(method, params, (error, result) => resolve({ ok: !error, result })) + } catch { + transportUncertain = true + resolve({ ok: false }) + } + }) + const done = (async (): Promise => { + let connected = false + let enabled = false + let started = false + let cleanupSafe = true + try { + options.session.connectToMainThread() + connected = true + enabled = (await post('Profiler.enable')).ok + if (!enabled) { + publish({ state: 'failed' }) + } + if (enabled && canStart()) { + const interval = await post('Profiler.setSamplingInterval', { interval: 10_000 }) + if (!interval.ok) { + stop('deadline') + publish({ state: 'failed' }) + } + if (interval.ok && canStart()) { + publish({ startPostedAfterDetectionMs: elapsed() }) + started = (await post('Profiler.start')).ok + publish({ + startAcknowledgedAfterDetectionMs: elapsed(), + ...(!started ? { state: 'failed' as const } : {}) + }) + } + } + if (started) { + canStart() + if (!intent) { + await new Promise((resolve) => { + wake = resolve + }) + } + publish({ stopPostedAfterDetectionMs: elapsed() }) + const result = await post('Profiler.stop') + const acknowledged = elapsed() + publish({ + stopAcknowledgedAfterDetectionMs: acknowledged, + stopAckDelayMs: acknowledged - (capture.stopPostedAfterDetectionMs ?? acknowledged) + }) + const reduced = result.ok ? reduceStopResult(result.result) : null + result.result = undefined + if (reduced) { + publish(reduced) + started = false + } else { + cleanupSafe = false + publish({ state: 'failed' }) + } + } else if (capture.state !== 'failed') { + publish({ state: 'not-started' }) + } + if (enabled && !started) { + cleanupSafe = (await post('Profiler.disable')).ok + if (!cleanupSafe) { + publish({ state: 'failed' }) + } + } + if (transportUncertain) { + cleanupSafe = false + } + if (connected && cleanupSafe && !started) { + options.session.disconnect() + await options.drain() + publish({ cleanup: 'drain-complete' }) + } + if (!cleanupSafe || started) { + // Keep the physical owner; an error is not proof the profiler stopped. + await new Promise(() => {}) + } + } catch { + publish({ state: 'failed' }) + if (connected) { + await new Promise(() => {}) + } + } finally { + clearTimeout(deadline) + wake = undefined + } + })() + return { stop, done } +} diff --git a/src/main/hang-watchdog/main-thread-hang-capture.test.ts b/src/main/hang-watchdog/main-thread-hang-capture.test.ts new file mode 100644 index 00000000000..3d8bb430345 --- /dev/null +++ b/src/main/hang-watchdog/main-thread-hang-capture.test.ts @@ -0,0 +1,155 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { MainToHangWatchdogWorkerMessage } from './hang-watchdog-worker-protocol' + +const state = vi.hoisted(() => ({ + clock: 0, + delayedWrite: false, + rejectRunner: false, + commands: new Array(), + terminations: new Array<() => void>(), + records: new Array() +})) +vi.mock('node:worker_threads', () => ({ isMainThread: false, parentPort: null, workerData: null })) +vi.mock('node:inspector', () => ({ + Session: class { + connectToMainThread() {} + disconnect() {} + post(method: string, _params: unknown, response: (error: null, result?: unknown) => void) { + state.commands.push(method) + response( + null, + method === 'Profiler.stop' + ? { profile: { nodes: [], samples: [], startTime: 0, endTime: 1 } } + : undefined + ) + } + } +})) +vi.mock('@orca/process-host', () => ({ + runProcess: async (options: { onChildTerminated: () => void }) => { + state.terminations.push(options.onChildTerminated) + if (state.rejectRunner) { + throw new Error('runner rejected after possible acquisition') + } + return { stdout: '', stderr: '', code: null, timedOut: true } + } +})) +vi.mock('./hang-detection-marker', () => ({ + readAvailableHangDetectionMarker: () => null, + writeHangDetectionMarker: (_path: string, record: unknown) => { + state.records.push(structuredClone(record)) + if (state.delayedWrite) { + state.clock = 6000 + } + } +})) +vi.mock('./hang-incident-snapshot', () => ({ + readCompletedHangContext: () => null, + collectHangMachineSnapshot: async () => null +})) +import { runWatchdog } from './main-thread-hang-watchdog-entry' + +beforeEach(() => { + state.clock = 0 + state.delayedWrite = false + state.rejectRunner = false + state.commands = [] + state.terminations = [] + state.records = [] + vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + vi.useFakeTimers() + vi.setSystemTime(0) + vi.spyOn(performance, 'now').mockImplementation(() => state.clock) +}) +afterEach(() => { + for (const terminate of state.terminations.splice(0)) { + terminate() + } + vi.clearAllTimers() + vi.useRealTimers() + vi.restoreAllMocks() +}) +function watchdog() { + let message: (value: MainToHangWatchdogWorkerMessage) => void = () => {} + runWatchdog( + { + parentPid: 123, + markerPath: '/qa/main-thread-hang.json', + timeoutMs: 100, + checkIntervalMs: 25 + }, + { + on: (_event, listener) => { + message = listener + }, + close: () => {}, + postMessage: (value) => message({ type: 'capture-drain-ack', token: value.token }) + } + ) + return { send: (value: MainToHangWatchdogWorkerMessage) => message(value) } +} +it('does not start a profiler after baseline publication has exhausted the detection budget', async () => { + state.delayedWrite = true + const owner = watchdog() + await vi.advanceTimersByTimeAsync(125) + await vi.dynamicImportSettled() + expect(state.commands).toEqual(['Profiler.enable', 'Profiler.disable']) + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.objectContaining({ + mainJs: expect.objectContaining({ + state: 'not-started', + stopReason: 'deadline', + stopRequestedAfterDetectionMs: 6000 + }) + }) + ] + }) + owner.send({ type: 'shutdown' }) +}) +it.each([false, true])( + 'retains possible native ownership until a late termination receipt (runner rejects: %s)', + async (rejectRunner) => { + state.rejectRunner = rejectRunner + const owner = watchdog() + await vi.advanceTimersByTimeAsync(125) + await vi.dynamicImportSettled() + owner.send({ type: 'heartbeat' }) + await vi.dynamicImportSettled() + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.objectContaining({ native: expect.objectContaining({ cleanup: 'unverified' }) }) + ] + }) + await vi.advanceTimersByTimeAsync(125) + await vi.dynamicImportSettled() + expect(state.records.at(-1)).toMatchObject({ + observations: [expect.anything(), expect.not.objectContaining({ mainJs: expect.anything() })] + }) + owner.send({ type: 'heartbeat' }) + state.terminations.shift()?.() + await vi.dynamicImportSettled() + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.objectContaining({ native: expect.objectContaining({ cleanup: 'terminated' }) }), + expect.anything() + ] + }) + await vi.advanceTimersByTimeAsync(125) + await vi.dynamicImportSettled() + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.anything(), + expect.anything(), + expect.objectContaining({ + mainJs: expect.objectContaining({ state: 'collecting' }), + native: expect.objectContaining({ + state: rejectRunner ? 'failed' : 'completed', + cleanup: 'unverified' + }) + }) + ] + }) + owner.send({ type: 'shutdown' }) + } +) diff --git a/src/main/hang-watchdog/main-thread-hang-import-failure.test.ts b/src/main/hang-watchdog/main-thread-hang-import-failure.test.ts new file mode 100644 index 00000000000..df91d489ca5 --- /dev/null +++ b/src/main/hang-watchdog/main-thread-hang-import-failure.test.ts @@ -0,0 +1,109 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { MainToHangWatchdogWorkerMessage } from './hang-watchdog-worker-protocol' + +const state = vi.hoisted(() => ({ records: new Array() })) +vi.mock('node:worker_threads', () => ({ isMainThread: false, parentPort: null, workerData: null })) +vi.mock('node:inspector', () => ({ + Session: class { + connectToMainThread() {} + disconnect() {} + post(method: string, _params: unknown, response: (error: null, result?: unknown) => void) { + response( + null, + method === 'Profiler.stop' + ? { profile: { nodes: [], samples: [], startTime: 0, endTime: 1 } } + : undefined + ) + } + } +})) +vi.mock('@orca/process-host', () => { + throw new Error('native dependency unavailable before runner acquisition') +}) +vi.mock('./hang-detection-marker', () => ({ + readAvailableHangDetectionMarker: () => null, + writeHangDetectionMarker: (_path: string, record: unknown) => { + state.records.push(structuredClone(record)) + } +})) +vi.mock('./hang-incident-snapshot', () => ({ + readCompletedHangContext: () => null, + collectHangMachineSnapshot: async () => null +})) +import { runWatchdog } from './main-thread-hang-watchdog-entry' + +beforeEach(() => { + state.records = [] + vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + vi.useFakeTimers() + vi.setSystemTime(0) +}) +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +it('preserves later JS capture and waits for its drain when the native module cannot load', async () => { + let send: (message: MainToHangWatchdogWorkerMessage) => void = () => {} + let token = '' + let closed = false + runWatchdog( + { + parentPid: 123, + markerPath: '/qa/main-thread-hang.json', + timeoutMs: 100, + checkIntervalMs: 25 + }, + { + on: (_event, listener) => { + send = listener + }, + close: () => { + closed = true + }, + postMessage: (message) => { + token = message.token + } + } + ) + await vi.advanceTimersByTimeAsync(125) + await vi.dynamicImportSettled() + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.objectContaining({ + mainJs: expect.objectContaining({ state: 'collecting' }), + native: expect.objectContaining({ state: 'failed', cleanup: 'unverified', stacks: [] }) + }) + ] + }) + send({ type: 'heartbeat' }) + await vi.dynamicImportSettled() + send({ type: 'capture-drain-ack', token }) + await vi.dynamicImportSettled() + await vi.advanceTimersByTimeAsync(125) + await vi.dynamicImportSettled() + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.anything(), + expect.objectContaining({ + mainJs: expect.objectContaining({ state: 'collecting' }), + native: expect.objectContaining({ state: 'failed', cleanup: 'unverified', stacks: [] }) + }) + ] + }) + send({ type: 'shutdown' }) + await vi.dynamicImportSettled() + expect(closed).toBe(false) + expect(state.records.at(-1)).toMatchObject({ + observations: [ + expect.anything(), + expect.objectContaining({ + mainJs: expect.objectContaining({ cleanup: 'pending', stopReason: 'shutdown' }) + }) + ] + }) + send({ type: 'capture-drain-ack', token }) + await vi.dynamicImportSettled() + expect(closed).toBe(true) +}) diff --git a/src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts b/src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts index 0d95d3ac6f9..94cc8e897db 100644 --- a/src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts +++ b/src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts @@ -1,6 +1,17 @@ +import { isHangWatchdogWorkerData } from './hang-watchdog-worker-protocol' import { isMainThread, parentPort, workerData } from 'node:worker_threads' import { createHangWatchdogDetectionLoop } from './hang-watchdog-detection-loop' -import { writeHangDetectionMarker } from './hang-detection-marker' +import { readAvailableHangDetectionMarker, writeHangDetectionMarker } from './hang-detection-marker' +import { + asHangObservations, + emptyHangObservations, + mergeHangObservations, + parsePowerReceipt, + retainHangObservation, + type HangObservation, + type HangPowerReceipt +} from './hang-observations' +import { captureHangSnapshot } from './hang-snapshot' import type { HangWatchdogWorkerData, MainToHangWatchdogWorkerMessage @@ -9,28 +20,14 @@ import type { type HangWatchdogPort = { on: (event: 'message', listener: (message: MainToHangWatchdogWorkerMessage) => void) => unknown close: () => void + postMessage?: (message: { type: 'capture-drain'; token: string }) => void } - -// Observation only: a false positive must never kill a live main thread mid-write. -export function recordHangObservation(options: { - parentPid: number - markerPath: string - unresponsiveMs: number - selfRecovered: boolean -}): void { - if (!options.markerPath) { - return - } - try { - writeHangDetectionMarker(options.markerPath, { - detectedAt: Date.now(), - parentPid: options.parentPid, - unresponsiveMs: options.unresponsiveMs, - selfRecovered: options.selfRecovered - }) - } catch { - // Diagnostic write failures must not terminate the watchdog. - } +type CaptureOwner = { + id: string + reason?: 'recovery' | 'shutdown' + stopJs?: (reason: 'recovery' | 'shutdown') => void + stopNative?: () => void + done?: Promise } export function runWatchdog( @@ -40,56 +37,259 @@ export function runWatchdog( if (!port) { return } + const initial = readAvailableHangDetectionMarker(config.markerPath) + let observations = asHangObservations(initial) ?? emptyHangObservations() + let existingUnavailable = initial === undefined + let sequence = 0 + let activeStallId: string | null = null + let stopped = false + let captureOwner: CaptureOwner | null = null + let drain: { token: string; acknowledge: () => void } | null = null + let collector: AbortController | null = null + let recentPower: HangPowerReceipt[] = [] + let sleepPeriod: { suspend: HangPowerReceipt; resumeAt: number | null } | null = null + let receiptWindow: { id: string; until: number; remaining: number } | null = null + const save = (): void => { + if (!config.markerPath) { + return + } + try { + if (existingUnavailable) { + const existing = readAvailableHangDetectionMarker(config.markerPath) + if (existing === undefined) { + return + } + observations = mergeHangObservations( + asHangObservations(existing) ?? emptyHangObservations(), + observations + ) + existingUnavailable = false + } + writeHangDetectionMarker(config.markerPath, observations) + } catch { + // Optional diagnostics must not terminate the independent observer. + } + } + const find = (id: string): HangObservation | undefined => + observations.observations.find((item) => item.id === id) + const update = (id: string, change: Partial): void => { + const record = find(id) + if (!record) { + return + } + observations = retainHangObservation(observations, { ...record, ...change }) + save() + } + const capture = (record: HangObservation, detectedAt: number): void => { + if (isMainThread || captureOwner || stopped || record.kind !== 'heartbeat-stall') { + return + } + const owner: CaptureOwner = { id: record.id } + captureOwner = owner + owner.done = (async () => { + const [inspector, js, native] = await Promise.all([ + import('node:inspector'), + import('./main-js-hang-capture'), + import('./native-hang-capture') + ]) + const mainJs = js.captureMainJsHang({ + session: new inspector.Session(), + detectedAt, + now: () => performance.now(), + publish: (mainJs) => update(record.id, { mainJs }), + drain: () => + new Promise((resolve) => { + drain = { token: record.id, acknowledge: resolve } + port.postMessage?.({ type: 'capture-drain', token: record.id }) + }) + }) + owner.stopJs = mainJs.stop + if (owner.reason) { + mainJs.stop(owner.reason) + } + const nativeCapture = + !owner.reason && process.platform === 'darwin' + ? native.captureNativeHang({ + pid: config.parentPid, + publish: (native) => update(record.id, { native }) + }) + : null + owner.stopNative = nativeCapture?.stop + await Promise.all([mainJs.done, nativeCapture?.done]) + })() + .catch(() => { + // A published baseline remains useful if an optional collector cannot initialize. + }) + .finally(() => { + if (captureOwner === owner) { + captureOwner = null + } + if (stopped) { + port.close() + } + }) + } + const openReceiptWindow = (id: string): void => { + receiptWindow = { id, until: Date.now() + config.checkIntervalMs, remaining: 4 } + } + const enrich = (record: HangObservation): void => { + if (!find(record.id)) { + return + } + if (collector) { + collector.abort() + return + } + const controller = new AbortController() + collector = controller + void import('./hang-incident-snapshot') + .then(async (incident) => { + if (controller.signal.aborted || stopped) { + return + } + if (record.kind === 'heartbeat-stall') { + update(record.id, { completedSpans: incident.readCompletedHangContext(config.tracePath) }) + } + const machine = await incident.collectHangMachineSnapshot(controller.signal) + if (!controller.signal.aborted && !stopped) { + update(record.id, { machine }) + } + }) + .catch(() => { + // The durable baseline already records unavailable optional evidence as unknown. + }) + .finally(() => { + if (collector === controller) { + collector = null + } + }) + } + const observe = (kind: HangObservation['kind'], durationMs: number, startedAt: number): void => { + const detectedAt = performance.now() + const snapshot = captureHangSnapshot() + const now = snapshot.wallMs ?? Date.now() + const suspend = sleepPeriod?.suspend + const initialSleepAssociated = + kind === 'watchdog-gap' && + !!suspend && + suspend.observedAt <= startedAt + config.checkIntervalMs && + suspend.receivedAt <= startedAt + config.checkIntervalMs && + suspend.receivedAt < now - config.checkIntervalMs && + suspend.receivedAt >= suspend.observedAt && + suspend.receivedAt - suspend.observedAt <= config.checkIntervalMs && + (sleepPeriod?.resumeAt ?? Infinity) > startedAt + let powerEvents = recentPower + .filter((item) => item.observedAt >= startedAt && item.receivedAt <= now) + .slice(-4) + if (initialSleepAssociated && suspend) { + powerEvents = [suspend, ...powerEvents.filter((item) => item !== suspend).slice(-3)] + } + const record: HangObservation = { + id: `${config.parentPid}:${now}:${++sequence}`, + kind, + detectedAt: now, + parentPid: config.parentPid, + durationMs, + selfRecovered: false, + snapshot, + resolution: null, + machine: null, + completedSpans: null, + powerEvents, + initialSleepAssociated + } + observations = retainHangObservation(observations, record) + if (kind === 'heartbeat-stall') { + activeStallId = record.id + } + openReceiptWindow(record.id) + save() + capture(record, detectedAt) + enrich(record) + } const loop = createHangWatchdogDetectionLoop({ timeoutMs: config.timeoutMs, checkIntervalMs: config.checkIntervalMs, now: () => Date.now(), - onHangDetected: (unresponsiveMs) => - recordHangObservation({ - parentPid: config.parentPid, - markerPath: config.markerPath, - unresponsiveMs, - selfRecovered: false - }), - // Update one marker per stall so resolution does not require reconciling a second record. - onHangResolved: (unresponsiveMs) => - recordHangObservation({ - parentPid: config.parentPid, - markerPath: config.markerPath, - unresponsiveMs, - selfRecovered: true - }) + onHangDetected: (durationMs) => observe('heartbeat-stall', durationMs, Date.now() - durationMs), + onHangResolved: () => { + if (!activeStallId) { + return + } + const id = activeStallId + activeStallId = null + if (captureOwner?.id === id) { + captureOwner.reason ??= 'recovery' + captureOwner.stopJs?.('recovery') + } + update(id, { selfRecovered: true, resolution: captureHangSnapshot() }) + openReceiptWindow(id) + }, + onWatchdogGap: (durationMs, startedAt) => { + const overlapping = observations.observations.findLast( + (item) => + item.kind === 'heartbeat-stall' && + (item.id === activeStallId || (item.resolution?.wallMs ?? -1) >= startedAt) + ) + if (overlapping) { + update(overlapping.id, { + watchdogGap: { observedAt: Date.now(), durationMs, snapshot: captureHangSnapshot() } + }) + openReceiptWindow(overlapping.id) + } else { + observe('watchdog-gap', durationMs, startedAt) + } + } }) - - let checkTimer: ReturnType | null = setInterval( - () => loop.tick(), - config.checkIntervalMs - ) - port.on('message', (message: MainToHangWatchdogWorkerMessage) => { + const checkTimer = setInterval(() => loop.tick(), config.checkIntervalMs) + port.on('message', (message) => { + if (message.type === 'capture-drain-ack' && drain?.token === message.token) { + const pending = drain + drain = null + pending.acknowledge() + return + } + if (stopped) { + return + } if (message.type === 'heartbeat') { loop.recordHeartbeat() + } else if (message.type === 'power-event') { + const receipt = parsePowerReceipt({ ...message, receivedAt: Date.now() }) + if (!receipt) { + return + } + recentPower = [...recentPower, receipt].slice(-4) + if (receipt.event === 'suspend') { + sleepPeriod = { suspend: receipt, resumeAt: null } + } else if (receipt.event === 'resume' && sleepPeriod) { + sleepPeriod.resumeAt = receipt.observedAt + } + if ( + receiptWindow && + receiptWindow.remaining > 0 && + receipt.receivedAt <= receiptWindow.until + ) { + const record = find(receiptWindow.id) + if (record) { + receiptWindow.remaining-- + update(record.id, { powerEvents: [...record.powerEvents, receipt].slice(-4) }) + } + } } else if (message.type === 'shutdown') { - if (checkTimer) { - clearInterval(checkTimer) - checkTimer = null + stopped = true + receiptWindow = null + clearInterval(checkTimer) + collector?.abort() + if (captureOwner) { + captureOwner.reason ??= 'shutdown' + captureOwner.stopJs?.('shutdown') + captureOwner.stopNative?.() + } else { + port.close() } - port.close() } }) -} - -export function isHangWatchdogWorkerData(value: unknown): value is HangWatchdogWorkerData { - const data = value as Partial | null - return ( - !!data && - Number.isInteger(data.parentPid) && - (data.parentPid ?? 0) > 0 && - typeof data.markerPath === 'string' && - Number.isFinite(data.timeoutMs) && - (data.timeoutMs ?? 0) > 0 && - Number.isFinite(data.checkIntervalMs) && - (data.checkIntervalMs ?? 0) > 0 - ) } if (!isMainThread && isHangWatchdogWorkerData(workerData)) { diff --git a/src/main/hang-watchdog/main-thread-hang-watchdog.ts b/src/main/hang-watchdog/main-thread-hang-watchdog.ts index cbe3ee374c6..502a133639f 100644 --- a/src/main/hang-watchdog/main-thread-hang-watchdog.ts +++ b/src/main/hang-watchdog/main-thread-hang-watchdog.ts @@ -1,14 +1,15 @@ import type { Worker } from 'node:worker_threads' import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' -import { app } from 'electron' +import { app, powerMonitor } from 'electron' import { hangDetectionMarkerPath } from './hang-detection-marker' import { resolveHangWatchdogWorkerPath } from './hang-watchdog-worker-path' -import { resolveObservabilityConsent } from '../observability' +import { getTraceFilePath, resolveObservabilityConsent } from '../observability' import { HANG_WATCHDOG_CHECK_INTERVAL_MS, HANG_WATCHDOG_HEARTBEAT_INTERVAL_MS, HANG_WATCHDOG_TIMEOUT_MS, type HangWatchdogWorkerData, + type HangWatchdogToMainMessage, type MainToHangWatchdogWorkerMessage } from './hang-watchdog-worker-protocol' @@ -39,6 +40,7 @@ export function installMainThreadHangWatchdog(options: { const workerData: HangWatchdogWorkerData = { parentPid: process.pid, markerPath: hangDetectionMarkerPath(options.userDataPath), + tracePath: getTraceFilePath(), timeoutMs: positiveTiming(process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS, HANG_WATCHDOG_TIMEOUT_MS), checkIntervalMs: positiveTiming( process.env.ORCA_HANG_WATCHDOG_CHECK_INTERVAL_MS, @@ -57,7 +59,7 @@ export function installMainThreadHangWatchdog(options: { } let stopped = false const postMessage = (message: MainToHangWatchdogWorkerMessage): void => { - if (stopped && message.type === 'heartbeat') { + if (stopped && message.type !== 'shutdown' && message.type !== 'capture-drain-ack') { return } try { @@ -66,6 +68,29 @@ export function installMainThreadHangWatchdog(options: { // The worker already exited. } } + worker.on('message', (message: HangWatchdogToMainMessage) => { + if ( + message?.type === 'capture-drain' && + typeof message.token === 'string' && + message.token.length <= 80 + ) { + setImmediate(() => postMessage({ type: 'capture-drain-ack', token: message.token })) + } + }) + const powerEvents: NodeJS.EventEmitter = powerMonitor + const powerListeners = (['suspend', 'resume', 'lock-screen', 'unlock-screen'] as const).map( + (event) => { + const listener = (): void => + postMessage({ type: 'power-event', event, observedAt: Date.now() }) + powerEvents.on(event, listener) + return { event, listener } + } + ) + const removePowerListeners = (): void => { + for (const { event, listener } of powerListeners) { + powerEvents.off(event, listener) + } + } const heartbeatTimer = setInterval(() => { postMessage({ type: 'heartbeat' }) }, HANG_WATCHDOG_HEARTBEAT_INTERVAL_MS) @@ -76,6 +101,7 @@ export function installMainThreadHangWatchdog(options: { stopped = true // Drop the app listener immediately so retired workers are not retained by its closure. app.off('will-quit', stop) + removePowerListeners() clearInterval(heartbeatTimer) postMessage({ type: 'shutdown' }) } @@ -86,6 +112,7 @@ export function installMainThreadHangWatchdog(options: { worker.once('exit', () => { stopped = true app.off('will-quit', stop) + removePowerListeners() clearInterval(heartbeatTimer) }) worker.unref() diff --git a/src/main/hang-watchdog/native-hang-capture.ts b/src/main/hang-watchdog/native-hang-capture.ts new file mode 100644 index 00000000000..3ab8b3cadfe --- /dev/null +++ b/src/main/hang-watchdog/native-hang-capture.ts @@ -0,0 +1,188 @@ +import type { runProcess as runNativeProcess } from '@orca/process-host' +import { + emptyHangStacks, + hangLabel, + hangModule, + topHangStacks, + type HangFrame, + type HangStack, + type NativeHangCapture +} from './hang-stacks' + +export function reduceNativeHangSample( + text: string +): Pick< + NativeHangCapture, + | 'stacks' + | 'samples' + | 'validSamples' + | 'truncated' + | 'mainThreadIdentified' + | 'mainSectionComplete' +> { + let identified = false + let complete = false + let invalid = false + let samples = 0 + let top: HangStack[] = [] + const path: { depth: number; frame: HangFrame; count: number }[] = [] + const acceptPath = (): void => { + if (!path.length) { + return + } + top = topHangStacks( + [ + ...top, + { + count: path.at(-1)!.count, + frames: path + .slice(-8) + .map((item) => item.frame) + .toReversed(), + hot: false + } + ], + samples + ) + } + const lines = text.slice(0, 128 * 1024).split('\n') + lines.pop() // A cut/unterminated line never establishes a frame or section boundary. + for (const line of lines.slice(0, 4096)) { + if (line.length > 1024) { + if (identified) { + invalid = true + break + } + continue + } + const thread = /^\s{4}(\d+) Thread_\S+/.exec(line) + if (!identified) { + if (thread && /\b(?:DispatchQueue_\d+: )?com\.apple\.main-thread\b/.test(line)) { + identified = true + samples = Number(thread[1]) + } + continue + } + if (thread || /^(?:Binary Images:|Total number in stack|Sort by top of stack)/.test(line)) { + acceptPath() + complete = !invalid + break + } + const frame = /^([\s+|!:]*)(\d+) (.+?)\s+\(in ([^)]+)\)(?:\s+.*)?$/.exec(line) + if (!frame) { + if (line.trim()) { + invalid = true + break + } + continue + } + const depth = frame[1].length + const count = Number(frame[2]) + if (!Number.isSafeInteger(count) || count <= 0 || count > samples) { + invalid = true + break + } + if (path.length && depth <= path.at(-1)!.depth) { + acceptPath() + } + while (path.length && path.at(-1)!.depth >= depth) { + path.pop() + } + if (path.length >= 256) { + invalid = true + break + } + path.push({ + depth, + count, + frame: { + name: hangLabel(frame[3].replace(/\s+\+\s+\d+.*$/, '')), + module: hangModule(frame[4]) + } + }) + } + if (!complete) { + acceptPath() + } + return { + stacks: top, + samples, + validSamples: samples, + truncated: invalid || !complete, + mainThreadIdentified: identified, + mainSectionComplete: complete + } +} + +export function captureNativeHang(options: { + pid: number + publish: (capture: NativeHangCapture) => void +}): { stop: () => void; done: Promise } { + const abort = new AbortController() + const baseline: NativeHangCapture = { + ...emptyHangStacks(), + state: 'collecting', + startedAt: Date.now(), + mainThreadIdentified: false, + mainSectionComplete: false, + reportTruncated: false, + timedOut: false, + cleanup: 'pending' + } + options.publish(baseline) + let latest = baseline + const publish = (capture: NativeHangCapture): void => { + latest = capture + options.publish(capture) + } + const done = (async (): Promise => { + let runProcess: typeof runNativeProcess + try { + runProcess = (await import('@orca/process-host')).runProcess + } catch { + publish({ ...baseline, state: 'failed', completedAt: Date.now(), cleanup: 'unverified' }) + return + } + let terminated = false + let release: () => void = () => {} + const termination = new Promise((resolve) => { + release = resolve + }) + try { + const result = await runProcess({ + program: '/usr/bin/sample', + args: [String(options.pid), '1', '10', '-file', '/dev/stdout'], + timeoutMs: 2500, + maxOutputBytes: 128 * 1024, + killOnOutputLimit: true, + signal: abort.signal, + onChildTerminated: () => { + terminated = true + release() + } + }) + publish({ + ...baseline, + ...reduceNativeHangSample(result.stdout), + state: 'completed', + completedAt: Date.now(), + reportTruncated: result.outputTruncated === true, + timedOut: result.timedOut, + cleanup: terminated ? 'terminated' : 'unverified', + ...(result.code !== null ? { exitCode: result.code } : {}) + }) + } catch { + publish({ + ...baseline, + state: 'failed', + completedAt: Date.now(), + cleanup: terminated ? 'terminated' : 'unverified' + }) + } + if (!terminated) { + await termination + publish({ ...latest, cleanup: 'terminated' }) + } + })() + return { stop: () => abort.abort(), done } +} diff --git a/src/main/hang-watchdog/previous-hang-detection.test.ts b/src/main/hang-watchdog/previous-hang-detection.test.ts index 59825f93704..bb277618cad 100644 --- a/src/main/hang-watchdog/previous-hang-detection.test.ts +++ b/src/main/hang-watchdog/previous-hang-detection.test.ts @@ -3,7 +3,19 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { setActiveSink } from '../observability/tracer' +import { createLocalFileSink } from '../observability/local-file-sink' +import { collectBundle } from '../observability/bundle' +import { + emptyHangObservations, + retainHangObservation, + type HangObservation +} from './hang-observations' import { hangDetectionMarkerPath, writeHangDetectionMarker } from './hang-detection-marker' +import { + publishRendererHang, + preservePreviousRendererHangs, + reportPreviousRendererHangs +} from './renderer-hang-records' import { preservePreviousHangDetection, reportPreviousHangDetection @@ -32,6 +44,7 @@ beforeEach(() => { afterEach(() => { setActiveSink(null) vi.unstubAllEnvs() + vi.useRealTimers() rmSync(dir, { recursive: true, force: true }) }) @@ -41,6 +54,28 @@ const marker = { unresponsiveMs: 10_000, selfRecovered: true } +const gap: HangObservation = { + id: '789:200:1', + kind: 'watchdog-gap', + detectedAt: 200, + parentPid: 789, + durationMs: 162_000, + selfRecovered: false, + initialSleepAssociated: false, + snapshot: { + wallMs: 200, + monotonicMs: 100, + uptimeSeconds: 1000, + processUserUs: 500, + processSystemUs: 200, + watchdogUserUs: null, + watchdogSystemUs: null + }, + resolution: null, + machine: null, + completedSpans: null, + powerEvents: [] +} describe('previous hang detection', () => { it('retains the previous run across startup and writes it only after a sink exists', () => { @@ -52,8 +87,7 @@ describe('previous hang detection', () => { expect(existsSync(`${markerPath}.previous`)).toBe(true) writeHangDetectionMarker(markerPath, { ...marker, parentPid: 789 }) const records: unknown[] = [] - const flush = vi.fn() - setActiveSink({ push: (record) => records.push(record), flush, close() {} }) + setActiveSink({ push: (record) => records.push(record), flush() {}, close() {} }) expect(reportPreviousHangDetection(dir)).toEqual(marker) expect(records).toEqual([ expect.objectContaining({ @@ -65,7 +99,6 @@ describe('previous hang detection', () => { }) }) ]) - expect(flush).toHaveBeenCalledOnce() expect(existsSync(`${markerPath}.previous`)).toBe(false) expect(JSON.parse(readFileSync(markerPath, 'utf8')).parentPid).toBe(789) expect(reportPreviousHangDetection(dir)).toBeNull() @@ -75,12 +108,112 @@ describe('previous hang detection', () => { const markerPath = hangDetectionMarkerPath(dir) writeHangDetectionMarker(markerPath, marker) preservePreviousHangDetection(dir) + writeHangDetectionMarker(markerPath, retainHangObservation(emptyHangObservations(), gap)) preservePreviousHangDetection(dir) expect(existsSync(`${markerPath}.previous`)).toBe(true) setActiveSink({ push() {}, flush() {}, close() {} }) expect(reportPreviousHangDetection(dir)).toEqual(marker) }) + it('carries gap and overlapping-stall evidence through the real trace and bundle', () => { + const traceFilePath = join(dir, 'logs', 'main.trace.ndjson') + const sink = createLocalFileSink({ filePath: traceFilePath, maxFiles: 1 }) + try { + writeHangDetectionMarker( + hangDetectionMarkerPath(dir), + retainHangObservation(emptyHangObservations(), gap) + ) + preservePreviousHangDetection(dir) + setActiveSink(sink) + expect(reportPreviousHangDetection(dir)).toBeNull() + const stall: HangObservation = { + ...gap, + id: '789:300:2', + kind: 'heartbeat-stall', + detectedAt: 300, + durationMs: 45_000, + selfRecovered: true, + snapshot: { ...gap.snapshot!, wallMs: 300, processUserUs: 100 }, + resolution: { ...gap.snapshot!, wallMs: 500, processUserUs: 900 }, + watchdogGap: { + observedAt: 400, + durationMs: 162_000, + snapshot: { ...gap.snapshot!, wallMs: 400, processUserUs: 600, watchdogUserUs: 3 } + }, + machine: { + startedAt: 301, + completedAt: 302, + systemMemoryTotalMB: 64_000, + systemMemoryFreeMB: 8_000, + systemMemorySwapTotalMB: 1024, + systemMemorySwapUsedMB: 100, + systemMemoryCompressorMB: 500, + systemMemoryPressureLevel: 2, + systemMemoryStatusLevel: 40, + load1: 2, + load5: 3, + load15: 4 + } + } + writeHangDetectionMarker( + hangDetectionMarkerPath(dir), + retainHangObservation(emptyHangObservations(), stall) + ) + preservePreviousHangDetection(dir) + expect(reportPreviousHangDetection(dir)).toEqual({ + detectedAt: 300, + parentPid: 789, + unresponsiveMs: 45_200, + selfRecovered: true + }) + const bundle = collectBundle({ + traceFilePath, + maxFiles: 1, + appVersion: 'test', + platform: 'darwin', + arch: 'arm64', + osRelease: 'test', + orcaChannel: 'dev' + }) + const records = bundle.payload + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + .filter((record) => record.type === 'effect-span') + const gapRecord = records.find( + (record) => record.attributes['breadcrumb.name'] === 'main_thread_watchdog_gap' + ) + const stallRecord = records.find( + (record) => record.attributes['breadcrumb.name'] === 'main_thread_hang_detected' + ) + expect(gapRecord?.attributes['breadcrumb.data']).toMatchObject({ + watchdogGapMs: 162_000, + cause: 'unknown', + activeMainActivity: 'unknown', + detection_processUserUs: 500, + preGapCpuDeltaUs: null, + watchdogCpuDetectionToResolutionUs: null, + machineEvidence: 'unknown' + }) + expect(stallRecord?.attributes['breadcrumb.data']).toMatchObject({ + detection_wallMs: 300, + detection_processUserUs: 100, + gapEnd_wallMs: 400, + gapEnd_processUserUs: 600, + gapEnd_watchdogUserUs: 3, + resolution_wallMs: 500, + resolution_processUserUs: 900, + machine_startedAt: 301, + machine_completedAt: 302, + machine_systemMemorySwapUsedMB: 100 + }) + expect(stallRecord?.attributes['breadcrumb.data']).not.toHaveProperty('startedAt') + } finally { + setActiveSink(null) + sink.close() + } + }) + it('does not mutate marker files when local diagnostics are disabled', () => { const markerPath = hangDetectionMarkerPath(dir) writeHangDetectionMarker(markerPath, marker) @@ -91,3 +224,114 @@ describe('previous hang detection', () => { expect(reportPreviousHangDetection(dir)).toBeNull() }) }) + +it('replays an old renderer capture into the current trace before consuming it so the default bundle includes it', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-11T12:00:00Z')) + const detectedAt = 1794391200000 + await publishRendererHang(dir, { + id: `456:${detectedAt}:3`, + parentPid: 456, + windowId: 3, + detectedAt, + status: 'captured', + samples: 1, + validSamples: 1, + truncated: false, + stacks: [ + { + count: 1, + hot: true, + frames: [{ name: 'busyCaller', module: 'app.js', line: 7, column: 3 }] + } + ] + }) + preservePreviousRendererHangs(dir) + reportPreviousRendererHangs(dir) + expect(existsSync(join(dir, 'renderer-hang.json.previous'))).toBe(true) + const traceFilePath = join(dir, 'logs', 'main.trace.ndjson') + const sink = createLocalFileSink({ filePath: traceFilePath, maxFiles: 1 }) + try { + setActiveSink(sink) + reportPreviousRendererHangs(dir) + expect(existsSync(join(dir, 'renderer-hang.json.previous'))).toBe(false) + const bundle = collectBundle({ + traceFilePath, + maxFiles: 1, + appVersion: 'test', + platform: 'darwin', + arch: 'arm64', + osRelease: 'test', + orcaChannel: 'dev' + }) + const records = bundle.payload + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + const capture = records.find( + (record) => record.attributes?.['breadcrumb.name'] === 'renderer_hang_capture' + ) + expect(capture?.attributes['breadcrumb.data']).toMatchObject({ + detectedAt, + previousPid: 456, + rendererJs0_frame0: 'busyCaller [app.js:7:3]', + rendererJs0_count: 1 + }) + } finally { + setActiveSink(null) + sink.close() + } +}) + +it('puts renderer completion into the current bundle while retaining next-launch evidence', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-11T12:00:00Z')) + const traceFilePath = join(dir, 'logs', 'main.trace.ndjson') + const sink = createLocalFileSink({ filePath: traceFilePath, maxFiles: 1 }) + try { + setActiveSink(sink) + await publishRendererHang(dir, { + id: '123:1000:3', + parentPid: 123, + windowId: 3, + detectedAt: 1000, + completedAt: 2000, + status: 'captured', + samples: 1, + validSamples: 1, + truncated: false, + stacks: [ + { + count: 1, + hot: true, + frames: [{ name: 'rendererBusy', module: 'app.js', line: 9, column: 2 }] + } + ] + }) + const bundle = collectBundle({ + traceFilePath, + maxFiles: 1, + appVersion: 'test', + platform: 'darwin', + arch: 'arm64', + osRelease: 'test', + orcaChannel: 'dev' + }) + const capture = bundle.payload + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + .find((record) => record.attributes?.['breadcrumb.name'] === 'renderer_hang_capture') + expect(capture?.attributes['breadcrumb.data']).toMatchObject({ + detectedAt: 1000, + completedAt: 2000, + rendererJs0_frame0: 'rendererBusy [app.js:9:2]' + }) + expect(JSON.parse(readFileSync(join(dir, 'renderer-hang.json'), 'utf8'))).toMatchObject({ + records: [expect.objectContaining({ completedAt: 2000 })] + }) + } finally { + setActiveSink(null) + sink.close() + } +}) diff --git a/src/main/hang-watchdog/previous-hang-detection.ts b/src/main/hang-watchdog/previous-hang-detection.ts index 1c2abcaffd7..8def03b0f7f 100644 --- a/src/main/hang-watchdog/previous-hang-detection.ts +++ b/src/main/hang-watchdog/previous-hang-detection.ts @@ -1,40 +1,153 @@ -import { renameSync } from 'node:fs' +import { preservePreviousRendererHangs, reportPreviousRendererHangs } from './renderer-hang-records' +import { rmSync } from 'node:fs' +import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' import { resolveObservabilityConsent } from '../observability' import { hasActiveTraceSink } from '../observability/tracer' import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { hangCaptureDetails } from './hang-capture-details' import { consumeHangDetectionMarker, hangDetectionMarkerPath, + readAvailableHangDetectionMarker, + writeHangDetectionMarker, type HangDetectionMarker } from './hang-detection-marker' +import { + asHangObservations, + emptyHangObservations, + latestHangMarker, + mergeHangObservations, + type HangObservation +} from './hang-observations' function previousMarkerPath(userDataPath: string): string { return `${hangDetectionMarkerPath(userDataPath)}.previous` } export function preservePreviousHangDetection(userDataPath: string): void { + preservePreviousRendererHangs(userDataPath) if (!resolveObservabilityConsent().localFileEnabled) { return } try { - // Keep the previous run's note safe from a new startup hang until its trace sink opens. - renameSync(hangDetectionMarkerPath(userDataPath), previousMarkerPath(userDataPath)) + const currentPath = hangDetectionMarkerPath(userDataPath) + const pendingPath = previousMarkerPath(userDataPath) + const current = asHangObservations(readAvailableHangDetectionMarker(currentPath)) + if (!current) { + return + } + const pending = readAvailableHangDetectionMarker(pendingPath) + if (pending === undefined) { + return + } + const merged = mergeHangObservations( + asHangObservations(pending) ?? emptyHangObservations(), + current + ) + writeHangDetectionMarker(pendingPath, merged) + rmSync(currentPath, { force: true }) } catch { // Missing or inaccessible markers must not prevent startup; retain any earlier pending note. } } +function observationDetails(record: HangObservation, omitted: number): CrashReportBreadcrumbData { + const details: CrashReportBreadcrumbData = { + previousPid: record.parentPid, + detectedAt: record.detectedAt, + observationKind: record.kind, + omittedObservations: omitted, + activeMainActivity: record.mainJs?.stacks.length + ? 'sampled-js-window' + : record.native?.stacks.length + ? 'sampled-native-window' + : 'unknown', + cause: 'unknown', + cpuScope: 'process-all-threads', + machineEvidence: record.machine ? 'sampled' : 'unknown' + } + if (record.mainJs) { + Object.assign(details, hangCaptureDetails('mainJs', record.mainJs)) + } + if (record.native) { + Object.assign(details, hangCaptureDetails('native', record.native)) + } + if (record.kind === 'heartbeat-stall') { + details.unresponsiveMs = + latestHangMarker({ version: 1, observations: [record], omitted: 0 })?.unresponsiveMs ?? + record.durationMs + details.detectedUnresponsiveMs = record.durationMs + details.selfRecovered = record.selfRecovered + } else { + details.watchdogGapMs = record.durationMs + details.preGapCpuDeltaUs = null + } + for (const [prefix, snapshot] of [ + ['detection', record.snapshot], + ['resolution', record.resolution], + ['gapEnd', record.watchdogGap?.snapshot] + ] as const) { + if (snapshot) { + for (const [key, value] of Object.entries(snapshot)) { + details[`${prefix}_${key}`] = value + } + } + } + const before = record.snapshot + const after = record.resolution + for (const scope of ['process', 'watchdog'] as const) { + const firstUser = before?.[`${scope}UserUs`] + const firstSystem = before?.[`${scope}SystemUs`] + const lastUser = after?.[`${scope}UserUs`] + const lastSystem = after?.[`${scope}SystemUs`] + const delta = + typeof firstUser === 'number' && + typeof firstSystem === 'number' && + typeof lastUser === 'number' && + typeof lastSystem === 'number' + ? lastUser + lastSystem - firstUser - firstSystem + : null + details[`${scope}CpuDetectionToResolutionUs`] = delta !== null && delta >= 0 ? delta : null + } + if (record.machine) { + for (const [key, value] of Object.entries(record.machine)) { + details[`machine_${key}`] = value + } + } + if (record.watchdogGap) { + details.overlappingWatchdogGapMs = record.watchdogGap.durationMs + details.overlappingWatchdogGapAt = record.watchdogGap.observedAt + } + for (const [index, receipt] of record.powerEvents.entries()) { + details[`power${index}_event`] = receipt.event + details[`power${index}_mainReceiptAt`] = receipt.observedAt + details[`power${index}_watchdogReceiptAt`] = receipt.receivedAt + } + details.completedContextEvidence = + record.completedSpans === null ? 'unknown' : 'completed-spans-on-disk' + for (const [index, span] of (record.completedSpans ?? []).entries()) { + details[`completed${index}_name`] = span.name + details[`completed${index}_startedAt`] = span.startedAt + details[`completed${index}_endedAt`] = span.completedAt + } + return details +} + export function reportPreviousHangDetection(userDataPath: string): HangDetectionMarker | null { - if (!hasActiveTraceSink()) { + reportPreviousRendererHangs(userDataPath) + if (!resolveObservabilityConsent().localFileEnabled || !hasActiveTraceSink()) { return null } const marker = consumeHangDetectionMarker(previousMarkerPath(userDataPath)) - if (marker) { - recordDurableCrashBreadcrumb('main_thread_hang_detected', { - unresponsiveMs: marker.unresponsiveMs, - previousPid: marker.parentPid, - selfRecovered: marker.selfRecovered - }) + const collection = asHangObservations(marker) + if (!collection) { + return null } - return marker + for (const record of collection.observations) { + recordDurableCrashBreadcrumb( + record.kind === 'heartbeat-stall' ? 'main_thread_hang_detected' : 'main_thread_watchdog_gap', + observationDetails(record, collection.omitted) + ) + } + return latestHangMarker(collection) } diff --git a/src/main/hang-watchdog/renderer-hang-capture.test.ts b/src/main/hang-watchdog/renderer-hang-capture.test.ts new file mode 100644 index 00000000000..8fee90d754b --- /dev/null +++ b/src/main/hang-watchdog/renderer-hang-capture.test.ts @@ -0,0 +1,158 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { BrowserWindow } from 'electron' + +const state = vi.hoisted(() => ({ + contents: new Map(), + metrics: [{ pid: 50, creationTime: 100 }], + records: new Array(), + publication: Promise.resolve() +})) +vi.mock('electron', async () => { + const { EventEmitter } = await import('node:events') + return { + app: Object.assign(new EventEmitter(), { getAppMetrics: () => state.metrics }), + webContents: { fromId: (id: number) => state.contents.get(id) } + } +}) +vi.mock('../observability', () => ({ + resolveObservabilityConsent: () => ({ localFileEnabled: true }) +})) +vi.mock('../persistence/loading-store/user-data-path', () => ({ + getCanonicalUserDataPath: () => '/qa' +})) +vi.mock('./renderer-hang-records', () => ({ + publishRendererHang: (_path: string, record: unknown) => { + state.records.push(structuredClone(record)) + return state.publication + } +})) +import { startRendererHangCapture } from './renderer-hang-capture' + +const handles: { stop: () => void }[] = [] +const responses: (() => void)[] = [] +beforeEach(() => { + state.contents.clear() + state.records = [] + state.publication = Promise.resolve() + state.metrics = [{ pid: 50, creationTime: 100 }] + vi.useFakeTimers() + vi.setSystemTime(1000) +}) +afterEach(async () => { + for (const handle of handles.splice(0)) { + handle.stop() + } + for (const respond of responses.splice(0)) { + respond() + } + await Promise.resolve() + vi.clearAllTimers() + vi.useRealTimers() +}) +function window(id: number, pid = 50) { + let reply: (stack: string) => void = () => {} + let requested = false + const frame = { + processId: 7, + osProcessId: pid, + collectJavaScriptCallStack: () => { + requested = true + return new Promise((resolve) => { + reply = resolve + responses.push(() => resolve('')) + }) + } + } + const contents = { id, mainFrame: frame, isDestroyed: () => false, isDevToolsOpened: () => false } + state.contents.set(id, contents) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this Electron test double supplies the members used by the collector; unused native members are never accessed. + const target = { id, webContents: contents, isDestroyed: () => false } as unknown as BrowserWindow + return { + requested: () => requested, + start: async () => { + const handle = startRendererHangCapture(target) + if (handle) { + handles.push(handle) + } + await Promise.resolve() + return handle + }, + reply: async () => { + reply('at busy (file:///private/qa/app.js:7:3)') + await Promise.resolve() + await Promise.resolve() + } + } +} + +it('keeps a shared-process request owned across window death and drops its stale result', async () => { + const old = window(1) + ;(await old.start())?.stop() + state.contents.delete(1) + const replacement = window(2) + await replacement.start() + expect(state.records.at(-1)).toMatchObject({ + windowId: 2, + status: 'process-capture-pending', + stacks: [] + }) + await old.reply() + expect( + state.records.some( + (record) => + record !== null && + typeof record === 'object' && + 'status' in record && + record.status === 'captured' + ) + ).toBe(false) + vi.setSystemTime(2000) + await replacement.start() + await replacement.reply() + expect(state.records.at(-1)).toMatchObject({ + windowId: 2, + status: 'captured', + stacks: [{ frames: [{ name: 'busy', module: 'app.js', line: 7, column: 3 }], count: 1 }] + }) +}) + +it('reconciles a dead generation before admission and an old reply cannot clear its successor', async () => { + const old = window(3) + ;(await old.start())?.stop() + state.contents.delete(3) + state.metrics = [{ pid: 50, creationTime: 200 }] + const successor = window(4) + await successor.start() + await old.reply() + const shared = window(5) + await shared.start() + expect(state.records.at(-1)).toMatchObject({ windowId: 5, status: 'process-capture-pending' }) + await successor.reply() + expect(state.records.at(-1)).toMatchObject({ windowId: 4, status: 'captured' }) +}) + +it('awaits baseline publication before requesting a stack and cannot start after cancellation during the write', async () => { + let finishPublication: () => void = () => {} + state.publication = new Promise((resolve) => { + finishPublication = resolve + }) + const cancelled = window(8) + const handle = await cancelled.start() + expect(cancelled.requested()).toBe(false) + handle?.stop() + finishPublication() + await Promise.resolve() + expect(cancelled.requested()).toBe(false) + + state.publication = new Promise((resolve) => { + finishPublication = resolve + }) + const live = window(9) + await live.start() + expect(live.requested()).toBe(false) + finishPublication() + await Promise.resolve() + expect(live.requested()).toBe(true) + await live.reply() + expect(state.records.at(-1)).toMatchObject({ windowId: 9, status: 'captured' }) +}) diff --git a/src/main/hang-watchdog/renderer-hang-capture.ts b/src/main/hang-watchdog/renderer-hang-capture.ts new file mode 100644 index 00000000000..a418d230355 --- /dev/null +++ b/src/main/hang-watchdog/renderer-hang-capture.ts @@ -0,0 +1,274 @@ +import { app, webContents, type BrowserWindow, type WebFrameMain } from 'electron' +import { resolveObservabilityConsent } from '../observability' +import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' +import { + emptyHangStacks, + hangLabel, + hangModule, + topHangStacks, + type HangStack +} from './hang-stacks' +import { publishRendererHang, type RendererHangRecord } from './renderer-hang-records' + +type Episode = { + record: RendererHangRecord + deadline: number + attempts: number + candidates: HangStack[] + timer?: ReturnType + deadlineTimer?: ReturnType + identity?: { rph: number; pid: number; creationTime: number } +} +type Pending = { + requestId: number + contentsId: number + episodeId: string + rph: number + pid: number + creationTime: number + anchor: WebFrameMain +} +const episodes = new Map() +const pending = new Map() +let requestSequence = 0 +let listening = false + +function snapshotProcesses(): Map | null { + try { + const metrics = app.getAppMetrics() + return new Map(metrics.map((item) => [item.pid, item.creationTime])) + } catch { + return null + } +} +function reconcile(snapshot: Map | null): void { + if (!snapshot) { + return + } + for (const [key, owner] of pending) { + const current = snapshot.get(owner.pid) + if (current === undefined || (current > 0 && current !== owner.creationTime)) { + pending.delete(key) + } + } +} +function publish(episode: Episode, status: RendererHangRecord['status']): Promise { + const stacks = topHangStacks(episode.candidates, episode.record.validSamples) + episode.record = { ...episode.record, stacks, status } + return publishRendererHang(getCanonicalUserDataPath(), episode.record) +} +function stopEpisode(contentsId: number, id: string): void { + const episode = episodes.get(contentsId) + if (!episode || episode.record.id !== id) { + return + } + if (episode.timer) { + clearTimeout(episode.timer) + } + if (episode.deadlineTimer) { + clearTimeout(episode.deadlineTimer) + } + episode.record.completedAt = Date.now() + publish( + episode, + episode.record.stacks.length + ? 'captured' + : [...pending.values()].some((owner) => owner.episodeId === id) + ? 'request-pending' + : episode.record.status === 'collecting' + ? 'stopped' + : episode.record.status + ) + episodes.delete(contentsId) +} + +export function reduceRendererHangStack(raw: unknown): { + frames: HangStack['frames'] + status: RendererHangRecord['status'] + truncated: boolean +} { + if (typeof raw !== 'string' || !raw) { + return { frames: [], status: 'unavailable', truncated: false } + } + if (raw === 'Website owner has not opted in for JS call stacks in crash reports.') { + return { frames: [], status: 'policy-missing', truncated: false } + } + const ingress = Buffer.from(raw.slice(0, 16 * 1024)) + .subarray(0, 16 * 1024) + .toString('utf8') + const truncated = ingress.length !== raw.length + const lines = ingress.split('\n') + if (truncated) { + lines.pop() + } + const frames: HangStack['frames'] = [] + for (const line of lines.slice(0, 128)) { + if (line.length > 512) { + continue + } + const match = /^\s*at (?:(.+?) )?\(?(.*?):(\d+):(\d+)\)?\s*$/.exec(line) + if (!match) { + continue + } + const lineNumber = Number(match[3]) + const column = Number(match[4]) + if (!Number.isSafeInteger(lineNumber) || !Number.isSafeInteger(column)) { + continue + } + frames.push({ + name: hangLabel(match[1] || '(anonymous)'), + module: hangModule(match[2]), + line: lineNumber, + column + }) + if (frames.length === 8) { + break + } + } + return { frames, status: frames.length ? 'captured' : 'unavailable', truncated } +} + +function settle(key: string, requestId: number, raw: unknown, rejected: boolean): void { + const owner = pending.get(key) + if (!owner || owner.requestId !== requestId) { + return + } + pending.delete(key) + const episode = episodes.get(owner.contentsId) + if (!episode || episode.record.id !== owner.episodeId) { + return + } + if (!resolveObservabilityConsent().localFileEnabled || performance.now() >= episode.deadline) { + stopEpisode(owner.contentsId, owner.episodeId) + return + } + const result = rejected + ? { frames: [], status: 'failed' as const, truncated: false } + : reduceRendererHangStack(raw) + episode.record.samples++ + episode.record.truncated ||= result.truncated + if (result.frames.length) { + episode.record.validSamples++ + const signature = JSON.stringify(result.frames) + const existing = episode.candidates.find((stack) => JSON.stringify(stack.frames) === signature) + if (existing) { + existing.count++ + } else { + episode.candidates.push({ frames: result.frames, count: 1, hot: false }) + } + } + publish(episode, result.status) + if (episode.attempts < 5) { + episode.timer = setTimeout(() => request(owner.contentsId, owner.episodeId), 1000) + } else { + stopEpisode(owner.contentsId, owner.episodeId) + } +} + +function request(contentsId: number, episodeId: string): void { + const episode = episodes.get(contentsId) + if (!episode || episode.record.id !== episodeId) { + return + } + if ( + episode.attempts >= 5 || + performance.now() >= episode.deadline || + !resolveObservabilityConsent().localFileEnabled + ) { + stopEpisode(contentsId, episodeId) + return + } + const contents = webContents.fromId(contentsId) + if (!contents || contents.isDestroyed() || contents.isDevToolsOpened()) { + stopEpisode(contentsId, episodeId) + return + } + let frame: WebFrameMain + let rph: number + let pid: number + try { + frame = contents.mainFrame + rph = frame.processId + pid = frame.osProcessId + } catch { + stopEpisode(contentsId, episodeId) + return + } + const metrics = episode.identity ? null : snapshotProcesses() + if (!episode.identity) { + reconcile(metrics) + } + if (episode.identity && (episode.identity.rph !== rph || episode.identity.pid !== pid)) { + stopEpisode(contentsId, episodeId) + return + } + const creationTime = episode.identity?.creationTime ?? metrics?.get(pid) + if (!creationTime || !Number.isFinite(creationTime) || creationTime <= 0) { + publish(episode, 'unavailable') + stopEpisode(contentsId, episodeId) + return + } + const key = `${rph}:${pid}:${creationTime}` + episode.identity = { rph, pid, creationTime } + if (pending.has(key) || [...pending.values()].some((owner) => owner.contentsId === contentsId)) { + publish(episode, 'process-capture-pending') + stopEpisode(contentsId, episodeId) + return + } + const requestId = ++requestSequence + pending.set(key, { requestId, contentsId, episodeId, rph, pid, creationTime, anchor: frame }) + episode.attempts++ + try { + void frame.collectJavaScriptCallStack().then( + (raw) => settle(key, requestId, raw, false), + () => settle(key, requestId, undefined, true) + ) + } catch { + settle(key, requestId, undefined, true) + } +} + +export function startRendererHangCapture(window: BrowserWindow): { stop: () => void } | null { + if (!resolveObservabilityConsent().localFileEnabled || window.isDestroyed()) { + return null + } + const contents = window.webContents + if (contents.isDestroyed() || contents.isDevToolsOpened()) { + return null + } + const contentsId = contents.id + if (episodes.has(contentsId)) { + return null + } + if (!listening) { + listening = true + app.on('render-process-gone', (_event, contents) => { + if ([...pending.values()].some((owner) => owner.contentsId === contents.id)) { + reconcile(snapshotProcesses()) + } + }) + } + const detectedAt = Date.now() + const id = `${process.pid}:${detectedAt}:${contentsId}` + const episode: Episode = { + record: { + ...emptyHangStacks(), + id, + parentPid: process.pid, + windowId: window.id, + detectedAt, + status: 'collecting' + }, + deadline: performance.now() + 5000, + attempts: 0, + candidates: [] + } + episodes.set(contentsId, episode) + void publish(episode, 'collecting').then(() => request(contentsId, id)) + // Logical expiry leaves the single physical request/anchor owned until settlement or death. + if (episodes.get(contentsId) === episode) { + episode.deadlineTimer = setTimeout(() => stopEpisode(contentsId, id), 5000) + episode.deadlineTimer.unref() + } + return { stop: () => stopEpisode(contentsId, id) } +} diff --git a/src/main/hang-watchdog/renderer-hang-records.ts b/src/main/hang-watchdog/renderer-hang-records.ts new file mode 100644 index 00000000000..59183eb0471 --- /dev/null +++ b/src/main/hang-watchdog/renderer-hang-records.ts @@ -0,0 +1,285 @@ +import { + closeSync, + fchmodSync, + openSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync +} from 'node:fs' +import { open, readFile, rename, stat } from 'node:fs/promises' +import { join } from 'node:path' +import { parseHangStacks, type HangStacks } from './hang-stacks' +import { resolveObservabilityConsent } from '../observability' +import { hasActiveTraceSink } from '../observability/tracer' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { hangCaptureDetails } from './hang-capture-details' + +export type RendererHangRecord = HangStacks & { + id: string + parentPid: number + windowId: number + detectedAt: number + completedAt?: number + status: + | 'collecting' + | 'captured' + | 'unavailable' + | 'policy-missing' + | 'failed' + | 'process-capture-pending' + | 'request-pending' + | 'stopped' +} +const validStatus = [ + 'collecting', + 'captured', + 'unavailable', + 'policy-missing', + 'failed', + 'process-capture-pending', + 'request-pending', + 'stopped' +] +type RendererHangWriter = { + path: string + records: RendererHangRecord[] + initialized: boolean + revision: number + running?: Promise +} +let writer: RendererHangWriter | undefined + +function pathFor(userDataPath: string, previous = false): string { + return join(userDataPath, `renderer-hang.json${previous ? '.previous' : ''}`) +} +function parseRecord(value: unknown): RendererHangRecord | null { + if (!value || typeof value !== 'object') { + return null + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding branch excludes null and non-objects before reading unknown properties. + const data = value as Record + const stacks = parseHangStacks(data) + if ( + !stacks || + typeof data.id !== 'string' || + !/^[\d:.-]{1,80}$/.test(data.id) || + !validStatus.includes(String(data.status)) + ) { + return null + } + for (const key of ['parentPid', 'windowId', 'detectedAt'] as const) { + if (typeof data[key] !== 'number' || !Number.isSafeInteger(data[key]) || data[key] < 0) { + return null + } + } + return { + ...stacks, + id: data.id, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding numeric-field loop validates these finite nonnegative integer fields. + parentPid: data.parentPid as number, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding numeric-field loop validates these finite nonnegative integer fields. + windowId: data.windowId as number, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding numeric-field loop validates these finite nonnegative integer fields. + detectedAt: data.detectedAt as number, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixed state allowlist above validates this string union. + status: data.status as RendererHangRecord['status'], + ...(typeof data.completedAt === 'number' && + Number.isSafeInteger(data.completedAt) && + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preceding numeric-field loop validates these finite nonnegative integer fields. + data.completedAt >= (data.detectedAt as number) + ? { completedAt: data.completedAt } + : {}) + } +} +function parseRecords(data: unknown): RendererHangRecord[] { + if ( + !data || + typeof data !== 'object' || + !('version' in data) || + data.version !== 1 || + !('records' in data) || + !Array.isArray(data.records) || + data.records.length > 4 + ) { + return [] + } + return data.records.map(parseRecord).filter((item): item is RendererHangRecord => item !== null) +} +function read(path: string): RendererHangRecord[] | undefined { + try { + if (statSync(path).size > 16 * 1024) { + return [] + } + const data: unknown = JSON.parse(readFileSync(path, 'utf8')) + return parseRecords(data) + } catch (error) { + return error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT' + ? [] + : undefined + } +} +function admit(record: RendererHangRecord): RendererHangRecord { + const candidate = structuredClone(record) + const bytes = (): number => Buffer.byteLength(JSON.stringify(candidate)) + while (bytes() > 3 * 1024 && candidate.stacks.length > 1) { + candidate.stacks.pop() + candidate.truncated = true + } + while (bytes() > 3 * 1024 && candidate.stacks[0]?.frames.length > 1) { + candidate.stacks[0].frames.pop() + candidate.truncated = true + } + if (bytes() > 3 * 1024) { + for (const frame of candidate.stacks[0]?.frames ?? []) { + frame.name = frame.name.slice(0, 24) + frame.module = frame.module.slice(0, 24) + candidate.truncated = true + } + } + return candidate +} +function merge(first: RendererHangRecord[], second: RendererHangRecord[]): RendererHangRecord[] { + const records = new Map() + for (const item of [...first, ...second]) { + const key = `${item.parentPid}:${item.windowId}` + const old = records.get(key) + if (!old || item.detectedAt >= old.detectedAt) { + records.set(key, admit(item)) + } + } + return [...records.values()].sort((a, b) => a.detectedAt - b.detectedAt).slice(-4) +} +function write(path: string, records: RendererHangRecord[]): void { + const text = JSON.stringify({ version: 1, records }) + if (Buffer.byteLength(text) > 16 * 1024) { + throw new Error('Renderer hang records exceed byte bound') + } + const fd = openSync(`${path}.tmp`, 'w', 0o600) + try { + fchmodSync(fd, 0o600) + writeFileSync(fd, text) + } finally { + closeSync(fd) + } + renameSync(`${path}.tmp`, path) +} + +async function persist(owner: RendererHangWriter): Promise { + try { + if (!owner.initialized) { + let disk: RendererHangRecord[] = [] + try { + if ((await stat(owner.path)).size <= 16 * 1024) { + disk = parseRecords(JSON.parse(await readFile(owner.path, 'utf8'))) + } + } catch (error) { + if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 'ENOENT') { + return + } + } + owner.records = merge(disk, owner.records) + owner.initialized = true + } + let committed = -1 + while (committed !== owner.revision) { + const revision = owner.revision + const text = JSON.stringify({ version: 1, records: owner.records }) + if (Buffer.byteLength(text) > 16 * 1024) { + return + } + const file = await open(`${owner.path}.tmp`, 'w', 0o600) + try { + await file.chmod(0o600) + await file.writeFile(text) + } finally { + await file.close() + } + await rename(`${owner.path}.tmp`, owner.path) + committed = revision + } + } catch { + // Keep the admitted snapshot for a later incident publication to retry. + } finally { + owner.running = undefined + } +} +function recordCapture(record: RendererHangRecord): void { + recordDurableCrashBreadcrumb('renderer_hang_capture', { + previousPid: record.parentPid, + windowId: record.windowId, + detectedAt: record.detectedAt, + completedAt: record.completedAt ?? null, + ...hangCaptureDetails('rendererJs', record) + }) +} +export function publishRendererHang( + userDataPath: string, + record: RendererHangRecord +): Promise { + if (!resolveObservabilityConsent().localFileEnabled) { + return Promise.resolve() + } + const normalized = parseRecord(record) + if (!normalized) { + return Promise.resolve() + } + const path = pathFor(userDataPath) + if (!writer || writer.path !== path) { + writer = { path, records: [], initialized: false, revision: 0 } + } + const admitted = admit(normalized) + writer.records = merge(writer.records, [admitted]) + writer.revision++ + if (admitted.completedAt !== undefined) { + try { + recordCapture(admitted) + } catch { + // A failed trace flush must not prevent the independent pending-file write. + } + } + const owner = writer + owner.running ??= Promise.resolve().then(() => persist(owner)) + return owner.running +} + +export function preservePreviousRendererHangs(userDataPath: string): void { + if (!resolveObservabilityConsent().localFileEnabled) { + return + } + try { + const records = read(pathFor(userDataPath)) + if (!records?.length) { + return + } + const previous = read(pathFor(userDataPath, true)) + if (!previous) { + return + } + write(pathFor(userDataPath, true), merge(previous, records)) + rmSync(pathFor(userDataPath), { force: true }) + writer = undefined + } catch { + /* Keep the original pending file if preservation failed. */ + } +} + +export function reportPreviousRendererHangs(userDataPath: string): void { + if (!resolveObservabilityConsent().localFileEnabled || !hasActiveTraceSink()) { + return + } + try { + const records = read(pathFor(userDataPath, true)) + if (!records) { + return + } + for (const record of records) { + recordCapture(record) + } + // Each breadcrumb synchronously requests a trace flush before pending data is consumed. + rmSync(pathFor(userDataPath, true), { force: true }) + } catch { + /* A failed replay remains pending for next launch. */ + } +} diff --git a/src/main/hang-watchdog/renderer-hang-stack-policy.test.ts b/src/main/hang-watchdog/renderer-hang-stack-policy.test.ts new file mode 100644 index 00000000000..4f4429db22e --- /dev/null +++ b/src/main/hang-watchdog/renderer-hang-stack-policy.test.ts @@ -0,0 +1,75 @@ +import { expect, it, vi } from 'vitest' +import { EventEmitter } from 'node:events' +import type { WebContents } from 'electron' +vi.mock('../observability', () => ({ + resolveObservabilityConsent: () => ({ localFileEnabled: true }) +})) +import { installRendererHangStackPolicy } from './renderer-hang-stack-policy' + +it('opts in only the owned main document and preserves unrelated response policy', () => { + let listener: (details: unknown, callback: (value: unknown) => void) => void = () => {} + const onHeadersReceived = vi.fn((_filter, callback) => { + listener = callback + }) + const contents = Object.assign(new EventEmitter(), { + id: 4, + session: { webRequest: { onHeadersReceived } } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this Electron test double supplies the members used by the collector; unused native members are never accessed. + installRendererHangStackPolicy(contents as unknown as WebContents, 'file:///app/index.html') + const answer = vi.fn() + listener( + { + url: 'file:///app/index.html', + resourceType: 'mainFrame', + webContentsId: 4, + responseHeaders: { + 'Content-Security-Policy': ["default-src 'self'"], + 'document-policy': ['sync-xhr=?0, include-js-call-stacks-in-crash-reports=?0'] + } + }, + answer + ) + expect(answer).toHaveBeenLastCalledWith({ + responseHeaders: { + 'Content-Security-Policy': ["default-src 'self'"], + 'document-policy': ['sync-xhr=?0', 'include-js-call-stacks-in-crash-reports'] + } + }) + listener({ url: 'file:///app/index.html', resourceType: 'mainFrame', webContentsId: 9 }, answer) + expect(answer).toHaveBeenLastCalledWith({}) + contents.emit('destroyed') + listener({ url: 'file:///app/index.html', resourceType: 'mainFrame', webContentsId: 4 }, answer) + expect(answer).toHaveBeenLastCalledWith({}) +}) + +it('normalizes the development document URL for both the filter and response identity', () => { + let listener: (details: unknown, callback: (value: unknown) => void) => void = () => {} + const onHeadersReceived = vi.fn((_filter, callback) => { + listener = callback + }) + const contents = Object.assign(new EventEmitter(), { + id: 8, + session: { webRequest: { onHeadersReceived } } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this Electron test double supplies the members used by the policy; unused native members are never accessed. + installRendererHangStackPolicy(contents as unknown as WebContents, 'http://localhost:5173') + expect(onHeadersReceived).toHaveBeenCalledWith( + { urls: ['http://localhost:5173/'], types: ['mainFrame'] }, + expect.any(Function) + ) + const answer = vi.fn() + listener( + { + url: 'http://localhost:5173/', + resourceType: 'mainFrame', + webContentsId: 8, + responseHeaders: {} + }, + answer + ) + expect(answer).toHaveBeenLastCalledWith({ + responseHeaders: { 'Document-Policy': ['include-js-call-stacks-in-crash-reports'] } + }) + contents.emit('destroyed') +}) diff --git a/src/main/hang-watchdog/renderer-hang-stack-policy.ts b/src/main/hang-watchdog/renderer-hang-stack-policy.ts new file mode 100644 index 00000000000..24ab7e846f3 --- /dev/null +++ b/src/main/hang-watchdog/renderer-hang-stack-policy.ts @@ -0,0 +1,58 @@ +import type { WebContents, Session } from 'electron' +import { resolveObservabilityConsent } from '../observability' + +const owners = new WeakMap>() + +export function installRendererHangStackPolicy(contents: WebContents, documentUrl: string): void { + try { + installPolicy(contents, new URL(documentUrl).href) + } catch { + // A rejected diagnostic policy must not prevent the main document from loading. + } +} + +function installPolicy(contents: WebContents, documentUrl: string): void { + if (!resolveObservabilityConsent().localFileEnabled) { + return + } + const session = contents.session + let documents = owners.get(session) + if (!documents) { + documents = new Map() + const owned = documents + // The default session has one header owner; browser profile sessions use their own policy. + session.webRequest.onHeadersReceived( + { urls: [documentUrl], types: ['mainFrame'] }, + (details, callback) => { + if ( + !resolveObservabilityConsent().localFileEnabled || + details.resourceType !== 'mainFrame' || + details.webContentsId === undefined || + owned.get(details.webContentsId) !== details.url + ) { + callback({}) + return + } + const headers = { ...details.responseHeaders } + const key = + Object.keys(headers).find((name) => name.toLowerCase() === 'document-policy') ?? + 'Document-Policy' + headers[key] = [ + ...(headers[key] ?? []) + .flatMap((value) => value.split(',')) + .filter( + (value) => !/^\s*include-js-call-stacks-in-crash-reports(?:\s|=|$)/.test(value) + ), + 'include-js-call-stacks-in-crash-reports' + ] + callback({ responseHeaders: headers }) + } + ) + owners.set(session, documents) + } + if (!documents.has(contents.id)) { + const id = contents.id + contents.on('destroyed', () => documents?.delete(id)) + } + documents.set(contents.id, documentUrl) +} diff --git a/src/main/host-repo-catalog-snapshot/host-repo-catalog-snapshot.test.ts b/src/main/host-repo-catalog-snapshot/host-repo-catalog-snapshot.test.ts index f5c58ce5416..af63d7bae13 100644 --- a/src/main/host-repo-catalog-snapshot/host-repo-catalog-snapshot.test.ts +++ b/src/main/host-repo-catalog-snapshot/host-repo-catalog-snapshot.test.ts @@ -11,7 +11,7 @@ import { } from './host-repo-catalog-snapshot-recorder' import { ProfileStateSqliteAuthority } from '../persistence/profile-state/profile-state-sqlite-authority' import { Store } from '../persistence/loading-store/store' -import { retireRemovedRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-removal-cleanup' +import { retireRemovedRuntimeEnvironment } from '../ipc/runtime-environments/catalog/runtime-environment-removal-cleanup' vi.mock('electron', () => ({ app: { diff --git a/src/main/host/deferred-secret-protection-report.ts b/src/main/host/deferred-secret-protection-report.ts index 4ba4e1dcf56..de695613e3d 100644 --- a/src/main/host/deferred-secret-protection-report.ts +++ b/src/main/host/deferred-secret-protection-report.ts @@ -1,4 +1,4 @@ -import { runAfterFirstWindowShown } from '../startup/first-window-deferral' +import { runAfterFirstWindowShown } from '../startup/main-window/first-window-deferral' import { reportSecretProtectionGap } from './secret-protection-report' /** Defer diagnostic keyring probes: locked Linux keyrings can block startup for 76s (STA-5765). */ diff --git a/src/main/host/electron-pr-refresh-renderer.ts b/src/main/host/electron-pr-refresh-renderer.ts index b29a4fd5f74..279e14b8ffb 100644 --- a/src/main/host/electron-pr-refresh-renderer.ts +++ b/src/main/host/electron-pr-refresh-renderer.ts @@ -1,5 +1,5 @@ import { webContents } from 'electron' -import type { PRRefreshRendererPort } from '../github/pr-refresh-renderer-port' +import type { PRRefreshRendererPort } from '../github/pull-requests/refresh/pr-refresh-renderer-port' import { sendToTrustedUIRenderer } from '../ipc/ui' export const electronPRRefreshRenderer: PRRefreshRendererPort = { diff --git a/src/main/host/electron-runtime-desktop-surface.ts b/src/main/host/electron-runtime-desktop-surface.ts index 532c1270cb6..410a94a3ce5 100644 --- a/src/main/host/electron-runtime-desktop-surface.ts +++ b/src/main/host/electron-runtime-desktop-surface.ts @@ -1,4 +1,4 @@ -import { isResourceWindowVisible } from '../window/resource-view-admission' +import { isResourceWindowVisible } from '../window/visibility/resource-view-admission' import { BrowserWindow, ipcMain, Notification, powerMonitor } from 'electron' import { readDesktopAwayState } from '../notifications/desktop-away-state' import type { RuntimeDesktopSurface } from '../runtime/construction/runtime-desktop-surface' diff --git a/src/main/host/native-chat-visual-guest-theme.test.ts b/src/main/host/native-chat-visual-guest-theme.test.ts index da4fe5cd0d2..5fbbb7ec2e7 100644 --- a/src/main/host/native-chat-visual-guest-theme.test.ts +++ b/src/main/host/native-chat-visual-guest-theme.test.ts @@ -1,14 +1,8 @@ import { EventEmitter } from 'node:events' -import { mkdtempSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' + import { beforeEach, describe, expect, it, vi } from 'vitest' import type { BrowserWindow, IpcMainEvent } from 'electron' -import type * as SiteDisplayController from '../browser/site-settings/display/browser-site-display-controller' -import { - configureBrowserSiteDisplayStore, - updateBrowserSiteDisplay -} from '../browser/site-settings/display/browser-site-display-store' + import { NATIVE_CHAT_VISUAL_GUEST_THEME_PUBLISH as PUBLISH, NATIVE_CHAT_VISUAL_GUEST_THEME_READ as READ @@ -30,10 +24,10 @@ vi.mock('electron', () => ({ ipcMain: ipc })) vi.mock('../orca-profiles/profile-storage-paths', () => ({ getProfileUserDataPath: () => '/profile' })) -vi.mock('../native-chat/native-chat-scratch-folder', () => ({ +vi.mock('../native-chat/conversation-files/native-chat-scratch-folder', () => ({ nativeChatScratchRootFor: () => '/profile/chat-scratch' })) -vi.mock('../native-chat/native-chat-visual-guest-location', () => ({ +vi.mock('../native-chat/conversation-files/native-chat-visual-guest-location', () => ({ isNativeChatVisualGuestLocation: classify })) vi.mock('../browser/site-settings/display/browser-site-display-controller', () => ({ @@ -47,9 +41,7 @@ vi.mock('../browser/routing/local-host-partitions/local-ssh-browser-partitions', })) import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme' -const { BrowserSiteDisplayController } = await vi.importActual( - '../browser/site-settings/display/browser-site-display-controller' -) +await vi.importActual('../browser/site-settings/display/browser-site-display-controller') function contents(id: number, hostWebContents: EventEmitter | null = null) { return Object.assign(new EventEmitter(), { @@ -118,49 +110,4 @@ describe('visual guest theme handoff', () => { read(ordinary) expect(ordinary.returnValue).toBeNull() }) - - it('applies saved media at the authenticated frame URL before every synchronous reply', () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-visual-media-')) - configureBrowserSiteDisplayStore(directory) - updateBrowserSiteDisplay('work', 'file://', { colorScheme: 'light' }) - const controller = new BrowserSiteDisplayController() - display.onGuestDocumentStart.mockImplementation( - controller.onGuestDocumentStart.bind(controller) - ) - const { host, guest, event, publish, read } = setup() - const sent: string[] = [] - const debuggerEvents = new EventEmitter() - Object.assign(guest, { - getURL: () => '', - debugger: Object.assign(debuggerEvents, { - isAttached: () => true, - sendCommand: (_method: string, params: { features: { value: string }[] }) => { - sent.push(params.features[0].value) - return Promise.resolve({}) - } - }) - }) - profileForSession.mockReturnValue('work') - try { - publish(event(host), dark) - for (let document = 1; document <= 2; document++) { - read( - event(guest, guest.mainFrame, () => expect(sent).toEqual(Array(document).fill('light'))) - ) - } - } finally { - controller.onGuestRetired(guest.id) - rmSync(directory, { recursive: true, force: true }) - } - }) - - it('does not overwrite another window’s synchronous answer', () => { - const first = setup() - const second = setup() - first.publish(first.event(first.host), dark) - const request = first.event() - first.read(request) - second.read(request) - expect(request.returnValue).toMatchObject({ colorScheme: 'dark' }) - }) }) diff --git a/src/main/host/native-chat-visual-guest-theme.ts b/src/main/host/native-chat-visual-guest-theme.ts index 944ff287bcc..46379f90791 100644 --- a/src/main/host/native-chat-visual-guest-theme.ts +++ b/src/main/host/native-chat-visual-guest-theme.ts @@ -8,9 +8,9 @@ import { type NativeChatVisualGuestTheme } from '../../shared/native-chat/native-chat-visual-shell' import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' -import { nativeChatScratchRootFor } from '../native-chat/native-chat-scratch-folder' +import { nativeChatScratchRootFor } from '../native-chat/conversation-files/native-chat-scratch-folder' import { browserSiteDisplayController } from '../browser/site-settings/display/browser-site-display-controller' -import { isNativeChatVisualGuestLocation } from '../native-chat/native-chat-visual-guest-location' +import { isNativeChatVisualGuestLocation } from '../native-chat/conversation-files/native-chat-visual-guest-location' import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { localSshBrowserProfileIdForSession } from '../browser/routing/local-host-partitions/local-ssh-browser-partitions' diff --git a/src/main/index.ts b/src/main/index.ts index 0c82953abbc..50254b4c1b8 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,24 +1,30 @@ import { app, clipboard, dialog, type BrowserWindow } from 'electron' -import { isRoutedOrcaDeepLink } from './startup/orca-deep-link-url' -import { createMacAppActivationHandler } from './window/macos-app-activation' -import { isBackgroundLaunch, isOrcadSidecarLaunch } from './window/foreground-activation-policy' -import { createDesktopHandoff, desktopHandoffArguments } from './window/macos-desktop-handoff' +import { isRoutedOrcaDeepLink } from './startup/open-routing/orca-deep-link-url' +import { createMacAppActivationHandler } from './window/activation/macos-app-activation' +import { + isBackgroundLaunch, + isOrcadSidecarLaunch +} from './window/activation/foreground-activation-policy' +import { + createDesktopHandoff, + desktopHandoffArguments +} from './window/activation/macos-desktop-handoff' import { focusExistingWindow as focusExistingWindowAction, setMainWindowOpener -} from './startup/main-window-actions' -import { openMainWindow as openMainWindowController } from './startup/main-window-controller' +} from './startup/main-window/main-window-actions' +import { openMainWindow as openMainWindowController } from './startup/main-window/main-window-controller' import { mainProcessState as state } from './startup/main-process-state' import { runMainProcessPreflight } from './startup/main-process-preflight' -import { runWslHolderUninstallPreflight } from './startup/wsl-holder-uninstall-preflight' -import { runAgentHooksUninstallPreflight } from './startup/agent-hooks-uninstall-preflight' -import { enableLinearRegexpFallback } from './startup/linear-regexp-fallback' -import { ensureWindowsRendererRuntimeFiles } from './startup/windows-renderer-runtime-files' +import { runWslHolderUninstallPreflight } from './startup/uninstall/wsl-holder-uninstall-preflight' +import { runAgentHooksUninstallPreflight } from './startup/uninstall/agent-hooks-uninstall-preflight' +import { enableLinearRegexpFallback } from './startup/chromium-policy/linear-regexp-fallback' +import { ensureWindowsRendererRuntimeFiles } from './startup/windows-startup/windows-renderer-runtime-files' import { registerMainProcessIpcHandlers } from './startup/main-process-ipc-bootstrap' import { initializeMainProcessReady } from './startup/main-process-ready' -import { installMainProcessQuitHandlers } from './startup/main-process-quit' -import { shouldActivateDesktopForSecondInstance } from './startup/single-instance-lock' -import { resolveOsOpenedDocuments } from './startup/os-opened-documents' +import { installMainProcessQuitHandlers } from './startup/quit/main-process-quit' +import { shouldActivateDesktopForSecondInstance } from './startup/profile-startup/single-instance-lock' +import { resolveOsOpenedDocuments } from './startup/open-routing/os-opened-documents' import { formatProfileStateStartupFailure, isDivergedProfileStateFailure, @@ -31,7 +37,7 @@ import { presentProfileStateStartupRecoveryDialog, readProfileStateCopySavedTimes } from './persistence/profile-state/startup/profile-state-startup-recovery-dialog' -import { profileStateDesktopRecoveryArgs } from './startup/profile-state-recovery-preflight' +import { profileStateDesktopRecoveryArgs } from './startup/profile-startup/profile-state-recovery-preflight' import { profileStateRepairSectionApproval } from '../shared/profile-state-recovery-command' import { prepareEarlyMainUiLanguage, translateMain } from './i18n/main-i18n' import { ProfileStateRecoveryRequiredError } from './persistence/profile-state/recovery/profile-state-recovery-required' @@ -41,10 +47,10 @@ import { deleteLegacyWslHostWakeList } from './wsl/host-lifecycle/wsl-host-early import { configureWslHostsGateFromDisk } from './wsl/host-lifecycle/wsl-host-gate-startup' import { configureRemoteRuntimeE2EEV2HostLatch } from '../shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch' import { ignoreInheritedWslHostsGateState } from '../shared/wsl-host-internal-gate' -import { registerOrcaProtocolClient } from './startup/orca-protocol-registration' -import { clearWindowsStdHandleInheritance } from './startup/windows-std-handle-inheritance' -import { installWindowsIsolatedSpawner } from './startup/windows-isolated-spawner' -import { dropE2eSpawnLogOutsideE2e } from './startup/e2e-spawn-log-env' +import { registerOrcaProtocolClient } from './startup/open-routing/orca-protocol-registration' +import { clearWindowsStdHandleInheritance } from './startup/windows-startup/windows-std-handle-inheritance' +import { installWindowsIsolatedSpawner } from './startup/windows-startup/windows-isolated-spawner' +import { dropE2eSpawnLogOutsideE2e } from './startup/testing/e2e-spawn-log-env' // Before anything spawns, so no daemon, PTY or agent inherits it outside e2e. dropE2eSpawnLogOutsideE2e() diff --git a/src/main/ipc/account-sign-in-link-opener.ts b/src/main/ipc/account-sign-in-link-opener.ts index 2048023a288..d0b2873e8a4 100644 --- a/src/main/ipc/account-sign-in-link-opener.ts +++ b/src/main/ipc/account-sign-in-link-opener.ts @@ -1,6 +1,6 @@ import { shell } from 'electron' import { isClaudeLocalSignInLink } from '../claude-accounts/sign-in/claude-sign-in-browser' -import { isCodexLoginAuthUrl } from '../codex-accounts/codex-login-auth-url' +import { isCodexLoginAuthUrl } from '../codex-accounts/login/codex-login-auth-url' export type AccountSignInProvider = 'claude' | 'codex' diff --git a/src/main/ipc/agent-session-attachment-upload.test.ts b/src/main/ipc/agent-session-attachment-upload.test.ts index 57c8b21c8cf..ec9de490d12 100644 --- a/src/main/ipc/agent-session-attachment-upload.test.ts +++ b/src/main/ipc/agent-session-attachment-upload.test.ts @@ -5,30 +5,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' type CallOptions = { expectedEnvironmentRuntimeId?: string; signal?: AbortSignal } -type Call = { - method: string - params: Record - revision?: number - options?: CallOptions -} - -const calls: Call[] = [] let serverStore: AgentSessionAttachmentStore let failMethod: string | null = null // Use the real paired-server store behind the RPC seam. -vi.mock('./runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('./runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: async ( _userDataPath: string, _environmentId: string, method: string, params: Record, _timeoutMs?: number, - revision?: number, + _revision?: number, _envelope?: unknown, - options?: CallOptions + _options?: CallOptions ) => { - calls.push({ method, params, revision, options }) if (method === failMethod) { return { ok: false, error: { code: 'internal', message: `${method} failed` } } } @@ -79,7 +70,6 @@ beforeEach(async () => { join(workDir, 'server', 'agent-session-attachments'), { hasSession: () => true } ) - calls.length = 0 failMethod = null }) @@ -119,8 +109,5 @@ describe('uploadBufferToAgentSessionAttachments', () => { const stored = await uploadBufferToAgentSessionAttachments(context(), 'orca-paste-1.png', png) expect(stored.name).toBe('orca-paste-1.png') expect((await readFile(stored.path)).equals(png)).toBe(true) - expect( - calls.filter((call) => call.method === 'agentSessionAttachment.uploadAppend') - ).toHaveLength(3) }) }) diff --git a/src/main/ipc/agent-session-attachment-upload.ts b/src/main/ipc/agent-session-attachment-upload.ts index 17d7b0985f0..18401263821 100644 --- a/src/main/ipc/agent-session-attachment-upload.ts +++ b/src/main/ipc/agent-session-attachment-upload.ts @@ -14,11 +14,11 @@ import { type AgentSessionAttachmentUploadTarget } from '../../shared/agent-session/agent-session-attachments' import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from './runtime-environments/requests/runtime-environment-transport-routing' import { isRuntimeEnvironmentManuallyDisconnected, RUNTIME_MANUALLY_DISCONNECTED_MESSAGE -} from './runtime-environments/runtime-environment-manual-disconnect' +} from './runtime-environments/connectivity/runtime-environment-manual-disconnect' import { stageOneSourceForRuntimeUpload } from './filesystem/filesystem-runtime-upload-staging' import { streamExternalFileSlices } from './runtime-upload-file-stream' import { formatByteCeiling } from './runtime-import-limits' diff --git a/src/main/ipc/agent-status-ipc-boundary.ts b/src/main/ipc/agent-status-ipc-boundary.ts index 6c314baf534..437f8ce9f46 100644 --- a/src/main/ipc/agent-status-ipc-boundary.ts +++ b/src/main/ipc/agent-status-ipc-boundary.ts @@ -4,7 +4,7 @@ import { type FleetAgentStatusEvidence, type FleetEvidenceBinding } from '../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' -import { isValidTerminalTabId } from '../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import type { OrcaRuntimeService } from '../runtime/orca-runtime' export type AgentStatusRuntimeEnrichment = Pick< diff --git a/src/main/ipc/ai-vault/ai-vault-all-host-timeouts.ts b/src/main/ipc/ai-vault/ai-vault-all-host-timeouts.ts index baddbe84fa9..b7f30d65f62 100644 --- a/src/main/ipc/ai-vault/ai-vault-all-host-timeouts.ts +++ b/src/main/ipc/ai-vault/ai-vault-all-host-timeouts.ts @@ -1,4 +1,4 @@ -import type { RuntimeAiVaultHostInfo } from '../../ai-vault/ai-vault-runtime-scan' +import type { RuntimeAiVaultHostInfo } from '../../ai-vault/runtime-hosts/ai-vault-runtime-scan' // Per-leg bounds for the all-hosts fan-outs, so one slow host cannot hold a merge open. export const AI_VAULT_ALL_HOST_TIMEOUT_MS = { diff --git a/src/main/ipc/ai-vault/ai-vault-delete.ts b/src/main/ipc/ai-vault/ai-vault-delete.ts index 36ea782e146..67cb10409ae 100644 --- a/src/main/ipc/ai-vault/ai-vault-delete.ts +++ b/src/main/ipc/ai-vault/ai-vault-delete.ts @@ -2,7 +2,7 @@ import { ipcMain, shell } from 'electron' import { configureRemoteAiVaultSessionDelete, deleteHostAiVaultSession -} from '../../ai-vault/host-session-delete' +} from '../../ai-vault/deletion/host-session-delete' import { parseRoutableExecutionHostId } from '../../../shared/execution-host' import type { AiVaultDeleteSessionArgs, diff --git a/src/main/ipc/ai-vault/ai-vault-handoff.ts b/src/main/ipc/ai-vault/ai-vault-handoff.ts index ac9f7f53b27..b6c13693ba4 100644 --- a/src/main/ipc/ai-vault/ai-vault-handoff.ts +++ b/src/main/ipc/ai-vault/ai-vault-handoff.ts @@ -6,8 +6,8 @@ import { type AiVaultSessionHandoffResult } from '../../../shared/ai-vault/contracts/ai-vault-session-handoff' import { writeAiVaultSessionHandoffSnapshot } from '../../ai-vault/session-handoff-snapshot' -import { callRuntimeEnvironment } from '../runtime-environments/runtime-environment-transport-routing' -import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/runtime-environment-registry-root' +import { callRuntimeEnvironment } from '../runtime-environments/requests/runtime-environment-transport-routing' +import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/catalog/runtime-environment-registry-root' /** The snapshot is written on the session's own host, where the hand-off agent starts. */ export async function prepareAiVaultSessionHandoff( diff --git a/src/main/ipc/ai-vault/ai-vault-host-discovery.ts b/src/main/ipc/ai-vault/ai-vault-host-discovery.ts index bd318f88d22..f8c0395ebe1 100644 --- a/src/main/ipc/ai-vault/ai-vault-host-discovery.ts +++ b/src/main/ipc/ai-vault/ai-vault-host-discovery.ts @@ -1,5 +1,5 @@ import type { AiVaultListResult } from '../../../shared/ai-vault/contracts/ai-vault-types' -import { aiVaultScanIssueResult } from '../../ai-vault/session-list-results' +import { aiVaultScanIssueResult } from '../../ai-vault/listing/session-list-results' export type AiVaultHostDiscoveryResult = { hostInfos: readonly T[] diff --git a/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts b/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts index ad298f4fea9..8abc67db1e6 100644 --- a/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts +++ b/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts @@ -1,7 +1,7 @@ import type { AiVaultProjectionDependency } from './ai-vault-projection-dependency' import { MAX_TIMER_DELAY_MS } from '../../../shared/timer-delay' -import { AiVaultScanCoordinator } from '../../ai-vault/ai-vault-scan-coordinator' -import { aiVaultSessionListCacheGeneration } from '../../ai-vault/cached-session-list' +import { AiVaultScanCoordinator } from '../../ai-vault/scan-lifecycle/ai-vault-scan-coordinator' +import { aiVaultSessionListCacheGeneration } from '../../ai-vault/listing/cached-session-list' import type { AiVaultListResult } from '../../../shared/ai-vault/contracts/ai-vault-types' import { aiVaultCachedDepthServes, diff --git a/src/main/ipc/ai-vault/ai-vault-projection-dependency.ts b/src/main/ipc/ai-vault/ai-vault-projection-dependency.ts index 6d644cee73f..ceb02bd02ae 100644 --- a/src/main/ipc/ai-vault/ai-vault-projection-dependency.ts +++ b/src/main/ipc/ai-vault/ai-vault-projection-dependency.ts @@ -1,6 +1,6 @@ import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { AgentSessionAssociationObservation } from '../../../shared/agent-session/view/agent-session-status-snapshot-fold' -import { getRuntimeEnvironmentTransportGeneration } from '../runtime-environments/runtime-environment-transport-generation' +import { getRuntimeEnvironmentTransportGeneration } from '../runtime-environments/connections/runtime-environment-transport-generation' type Authority = { identity: string; revision: number; references: number } const authorities = new Map() diff --git a/src/main/ipc/ai-vault/ai-vault-resume.test.ts b/src/main/ipc/ai-vault/ai-vault-resume.test.ts index 5822bf7c52d..ae130438f9b 100644 --- a/src/main/ipc/ai-vault/ai-vault-resume.test.ts +++ b/src/main/ipc/ai-vault/ai-vault-resume.test.ts @@ -3,12 +3,12 @@ import { setStructuredAgentSessionHost } from '../../native-chat/agent-session-w import { installCopyingChat, PROVIDER_SESSION -} from '../../ai-vault/structured-session-ownership.test-support' +} from '../../ai-vault/structured-sessions/structured-session-ownership.test-support' import { prepareAiVaultSessionResume } from './ai-vault-resume' vi.mock('electron', () => ({ ipcMain: { handle: vi.fn() } })) const wakeMock = vi.hoisted(() => vi.fn(async (_distro: string | null) => {})) -vi.mock('../../native-chat/native-chat-open-wake', () => ({ +vi.mock('../../native-chat/transcript-discovery/native-chat-open-wake', () => ({ wakeNativeChatTranscriptDistro: wakeMock })) afterEach(() => setStructuredAgentSessionHost(null)) @@ -52,28 +52,3 @@ it('refuses the native owner while preserving forks and other execution hosts', }) // Resuming is a user act: its stopped distro must start before the transcript's gated reads. -it('starts the session file distro before preparing a WSL resume', async () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - try { - const prepareSessionResume = vi.fn(async () => { - expect(wakeMock).toHaveBeenCalledWith('Ubuntu') - return { useRealCodexHome: false } - }) - await prepareAiVaultSessionResume( - { - agent: 'claude', - sessionId: 'sess-1', - filePath: String.raw`\\wsl.localhost\Ubuntu\home\qa\session.jsonl`, - codexHome: null, - executionHostId: 'local' - }, - { prepareSessionResume } - ) - expect(prepareSessionResume).toHaveBeenCalledOnce() - } finally { - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - } -}) diff --git a/src/main/ipc/ai-vault/ai-vault-resume.ts b/src/main/ipc/ai-vault/ai-vault-resume.ts index 3d556fbe14a..87c47400aa7 100644 --- a/src/main/ipc/ai-vault/ai-vault-resume.ts +++ b/src/main/ipc/ai-vault/ai-vault-resume.ts @@ -1,5 +1,5 @@ -import { AiVaultPrepareSessionResumeParams } from '../../../shared/rpc-contract/ai-vault-params' -import { prepareStructuredChatCliFork } from '../../ai-vault/structured-chat-cli-fork' +import { AiVaultPrepareSessionResumeParams } from '../../../shared/rpc-contract/ai-vault/ai-vault-params' +import { prepareStructuredChatCliFork } from '../../ai-vault/structured-sessions/structured-chat-cli-fork' import { ipcMain } from 'electron' import type { AiVaultPrepareSessionResumeRequest, @@ -8,10 +8,10 @@ import type { } from '../../../shared/ai-vault/resume/ai-vault-resume-preparation' import { isUnresolvedOwnerHostId, parseExecutionHostId } from '../../../shared/execution-host' import { isWslUncPath } from '../../../shared/wsl-paths' -import { assertLegacyAiVaultResumeAllowed } from '../../ai-vault/structured-session-ownership' +import { assertLegacyAiVaultResumeAllowed } from '../../ai-vault/structured-sessions/structured-session-ownership' import { tryEnsureStructuredAgentSessionHostForResume } from '../../runtime/agent-session/structured-agent-session-host-refusal' -import { copyStructuredChatConversation } from '../../ai-vault/structured-chat-conversation-copy' -import { wakeNativeChatTranscriptDistro } from '../../native-chat/native-chat-open-wake' +import { copyStructuredChatConversation } from '../../ai-vault/structured-sessions/structured-chat-conversation-copy' +import { wakeNativeChatTranscriptDistro } from '../../native-chat/transcript-discovery/native-chat-open-wake' import { wslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' import { prepareAiVaultSessionHandoff } from './ai-vault-handoff' import type { AiVaultSessionHandoffArgs } from '../../../shared/ai-vault/contracts/ai-vault-session-handoff' diff --git a/src/main/ipc/ai-vault/ai-vault-scan-coalescing.test.ts b/src/main/ipc/ai-vault/ai-vault-scan-coalescing.test.ts deleted file mode 100644 index caaaecc59ec..00000000000 --- a/src/main/ipc/ai-vault/ai-vault-scan-coalescing.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AiVaultListResult } from '../../../shared/ai-vault/contracts/ai-vault-types' - -const mocks = vi.hoisted(() => ({ - scanAiVaultSessionsInService: vi.fn(), - resolveAiVaultSessionTitlesInService: vi.fn(), - scanRuntimeAiVaultSessions: vi.fn(), - ipcHandle: vi.fn(), - subscribe: vi.fn() -})) - -vi.mock('electron', () => ({ - app: { on: vi.fn() }, - ipcMain: { handle: mocks.ipcHandle, on: vi.fn() }, - BrowserWindow: { getAllWindows: () => [] } -})) -vi.mock('../../ai-vault/scan-service/session-scanner-service-spawn', async (importOriginal) => ({ - ...(await importOriginal()), - scanAiVaultSessionsInService: mocks.scanAiVaultSessionsInService, - resolveAiVaultSessionTitlesInService: mocks.resolveAiVaultSessionTitlesInService -})) -vi.mock('../runtime-environments/runtime-environment-transport-routing', () => ({ - subscribeRuntimeEnvironment: mocks.subscribe -})) -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: (_path: string, id: string) => ({ - id, - runtimeId: id, - pairingRevision: 1, - createdAt: 1 - }) -})) -import { createAiVaultAssociationObserver } from './ai-vault-projection-dependency' -import { invalidateAiVaultHostLegCache } from './ai-vault-host-leg-cache' -import { invalidateAiVaultSessionListCache } from '../../ai-vault/cached-session-list' -import { registerRuntimeEnvironmentSubscriptionHandlers } from '../runtime-environments/runtime-environment-subscription-handlers' -import { advanceRuntimeEnvironmentTransportGeneration } from '../runtime-environments/runtime-environment-transport-generation' -import type { subscribeRuntimeEnvironment } from '../runtime-environments/runtime-environment-transport-routing' -vi.mock('../../wsl/discovery/distro-catalog', () => ({ - listRunningWslHomeDirsAsync: vi.fn().mockResolvedValue([]), - hasCachedWslDistros: vi.fn(() => false) -})) -vi.mock('../../wsl/filesystem/wsl-running-path-filter', () => ({ - filterPathsToRunningWslDistrosAsync: vi.fn(async (paths: readonly string[]) => [...paths]) -})) -const { _internals, registerAiVaultHandlers } = await import('./ai-vault') -const EMPTY_RESULT: AiVaultListResult = { - sessions: [], - issues: [], - scannedAt: '2026-07-27T00:00:00.000Z' -} - -beforeEach(() => { - vi.clearAllMocks() - _internals.resetAiVaultCacheForTests() - mocks.scanAiVaultSessionsInService.mockResolvedValue(EMPTY_RESULT) - mocks.resolveAiVaultSessionTitlesInService.mockResolvedValue({ titles: [] }) - mocks.scanRuntimeAiVaultSessions.mockResolvedValue(EMPTY_RESULT) -}) - -describe('Agent Session History scan coalescing', () => { - it('never shares a compact reply with a caller missing its exact baseline', async () => { - registerRuntimeHost() - const fingerprint = 'a'.repeat(64) - mocks.scanRuntimeAiVaultSessions.mockImplementation(async (_host, args) => { - await Promise.resolve() - return args.afterFingerprint === fingerprint - ? { ...EMPTY_RESULT, fingerprint, unchanged: true } - : { ...EMPTY_RESULT, scannedAt: 'full' } - }) - const [conditional, legacy] = await Promise.all([ - _internals.listAiVaultSessions({ - executionHostScope: 'runtime:remote-server', - afterFingerprint: fingerprint - }), - _internals.listAiVaultSessions({ executionHostScope: 'runtime:remote-server' }) - ]) - expect(conditional.unchanged).toBe(true) - expect(legacy.unchanged).toBeUndefined() - expect(legacy.scannedAt).toBe('full') - expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledTimes(2) - }) - - it.each([ - ['local', mocks.scanAiVaultSessionsInService], - ['runtime:remote-server', mocks.scanRuntimeAiVaultSessions] - ] as const)('coalesces %s scans while isolating caller cancellation', async (scope, scan) => { - let resolveScan: ((result: AiVaultListResult) => void) | undefined - scan.mockImplementation( - () => - new Promise((resolve) => { - resolveScan = resolve - }) - ) - registerRuntimeHost() - const firstController = new AbortController() - const first = _internals.listAiVaultSessions( - { executionHostScope: scope }, - { signal: firstController.signal } - ) - const second = _internals.listAiVaultSessions({ executionHostScope: scope }) - await vi.waitFor(() => expect(resolveScan).toBeDefined()) - - firstController.abort() - - await expect(first).rejects.toMatchObject({ name: 'AbortError' }) - expect(scan).toHaveBeenCalledTimes(1) - resolveScan?.(EMPTY_RESULT) - await expect(second).resolves.toMatchObject(EMPTY_RESULT) - }) - - it.each([ - ['local', 'desktop', mocks.scanAiVaultSessionsInService], - ['local', 'remote-client', mocks.scanAiVaultSessionsInService], - ['runtime:remote-server', 'desktop', mocks.scanRuntimeAiVaultSessions] - ] as const)( - 'does not let a %s read after a %s delete join a scan that began before it', - async (scope, deleter, scan) => { - registerRuntimeHost() - let finishBeforeDelete = (_result: AiVaultListResult): void => {} - scan - .mockReturnValueOnce(new Promise((resolve) => (finishBeforeDelete = resolve))) - .mockResolvedValueOnce({ ...EMPTY_RESULT, scannedAt: '2026-07-28T00:00:00.000Z' }) - const beforeDelete = _internals.listAiVaultSessions({ executionHostScope: scope }) - await vi.waitFor(() => expect(scan).toHaveBeenCalledTimes(1)) - - // Remote-client deletes skip the desktop host-leg cache. - if (deleter === 'desktop') { - invalidateAiVaultHostLegCache() - } - invalidateAiVaultSessionListCache() - const afterDelete = _internals.listAiVaultSessions({ executionHostScope: scope }) - finishBeforeDelete(EMPTY_RESULT) - - await expect(afterDelete).resolves.toMatchObject({ scannedAt: '2026-07-28T00:00:00.000Z' }) - await expect(beforeDelete).resolves.toMatchObject({ scannedAt: EMPTY_RESULT.scannedAt }) - } - ) -}) - -function registerRuntimeHost(): void { - registerAiVaultHandlers({ - getActiveRuntimeAiVaultHostInfos: () => [ - { environmentId: 'remote-server', executionHostId: 'runtime:remote-server' } - ], - scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions - }) -} - -function ipcHandler(channel: string): (...args: unknown[]) => unknown { - const registration = mocks.ipcHandle.mock.calls.find(([registered]) => registered === channel) - if (!registration) { - throw new Error(`${channel} was not registered`) - } - return registration[1] -} - -afterEach(() => { - _internals.resetAiVaultCacheForTests() - vi.useRealTimers() -}) - -it('orders forwarded association edges before new remote/All admissions and fences other-window work', async () => { - vi.useFakeTimers() - const retained = new Map() - const pending = new Map() - const forwarding: (() => Promise)[] = [] - const sender = Object.assign(new EventEmitter(), { - id: 91, - isDestroyed: () => false, - send: vi.fn(() => { - forwarding.push(() => list('runtime:a')) - }) - }) - let callbacks: Parameters[5] | undefined - mocks.subscribe.mockImplementation( - async (...args: Parameters) => { - callbacks = args[5] - return { requestId: 'status', sendBinary: () => true, close: () => {} } - } - ) - let observerThrows = false - const recordLayoutFrame = vi.fn() - registerRuntimeEnvironmentSubscriptionHandlers({ - getUserDataPath: () => '/profile', - remoteRuntimeSubscriptions: retained, - pendingSubscriptions: pending, - createAssociationObserver: (host, identity) => { - const observer = createAiVaultAssociationObserver( - host, - identity, - invalidateAiVaultHostLegCache - ) - return { - ...observer, - observe: (frame) => { - if (observerThrows) { - throw new Error('observer') - } - observer.observe(frame) - } - } - }, - recordLayoutFrame - }) - registerAiVaultHandlers({ - getUserDataPath: () => '/profile', - getActiveRuntimeAiVaultHostInfos: () => [ - { environmentId: 'a', executionHostId: 'runtime:a' }, - { environmentId: 'b', executionHostId: 'runtime:b' } - ], - scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions - }) - const list = (executionHostScope: 'runtime:a' | 'runtime:b' | 'all', scopePaths: string[] = []) => - _internals.listAiVaultSessions({ executionHostScope, scopePaths, limit: 250 }) - await ipcHandler('runtimeEnvironments:subscribe')( - { sender }, - { selector: 'a', method: 'agentSession.subscribeStatus', subscriptionId: 'association' } - ) - const summary = { - sessionId: 'native', - workspaceId: 'workspace', - agent: 'pi', - providerSession: { key: 'session_id', id: '/old-provider' } - } - const frame = (result: unknown) => - callbacks?.onEvent({ - type: 'response', - response: { id: 'status', ok: true, result, _meta: { runtimeId: 'a' } } - }) - frame({ type: 'snapshot', sessions: [summary] }) - forwarding.length = 0 - let detached = false - const answer = (host: string): AiVaultListResult => ({ - ...EMPTY_RESULT, - fingerprint: detached ? 'detached' : 'owned', - sessions: [ - { - id: `runtime:${host}:codex:host-session:/host/transcript.jsonl`, - executionHostId: `runtime:${host}`, - agent: 'codex', - sessionId: 'host-session', - cwd: '/host/folder', - branch: null, - model: null, - filePath: '/host/transcript.jsonl', - codexHome: '/host/codex', - createdAt: null, - updatedAt: null, - modifiedAt: '', - messageCount: 2, - totalTokens: 0, - previewMessages: [], - queuedMessageCount: 0, - subagentTranscriptCount: 0, - resumeCommand: 'host-resume-command', - subagent: null, - title: detached ? 'Provider title' : 'Manual name', - ...(detached - ? {} - : { structuredSession: { sessionId: 'native', workspaceId: 'workspace' } }) - } - ] - }) - mocks.scanRuntimeAiVaultSessions.mockImplementation(async (host) => answer(host)) - await list('runtime:a') - await list('runtime:b') - await list('all') - const baseline = mocks.scanRuntimeAiVaultSessions.mock.calls.length - for (const n of [10, 100]) { - for (let i = 0; i < n; i++) { - frame({ type: 'status', session: { ...summary, updatedAt: i, conversationName: `${i}` } }) - frame({ type: 'snapshot', sessions: [], namingActiveSessionIds: [], conversationNames: [] }) - frame({ type: 'snapshot', sessions: [] }) - } - await list('runtime:a') - await list('runtime:b') - await list('all') - expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledTimes(baseline) - } - const held: (() => void)[] = [] - mocks.scanRuntimeAiVaultSessions.mockImplementation((host, args) => { - const result = answer(host) - return args.scopePaths?.includes('/race') && !detached - ? new Promise((resolve) => held.push(() => resolve(result))) - : Promise.resolve(result) - }) - const oldA = list('runtime:a', ['/race']) - const oldAll = list('all', ['/race']) - const oldB = list('runtime:b', ['/race']) - await vi.waitFor(() => expect(held).toHaveLength(4)) - const warmRaceScannerStarts = mocks.scanAiVaultSessionsInService.mock.calls.length - forwarding.length = 0 - detached = true - frame({ type: 'status', session: { ...summary, providerSession: undefined } }) - // invoke admits these after the forwarding callback has returned, as Electron does. - expect((await forwarding[0]!()).sessions[0]?.structuredSession).toBeUndefined() - const currentA = await list('runtime:a', ['/race']) - const currentAll = await list('all', ['/race']) - expect(currentA.sessions[0]?.title).toBe('Provider title') - expect(currentAll.sessions.every((row) => row.structuredSession === undefined)).toBe(true) - const bCalls = mocks.scanRuntimeAiVaultSessions.mock.calls.filter(([host]) => host === 'b').length - const bWaiter = list('runtime:b', ['/race']) - held.forEach((finish) => finish()) - await Promise.all([oldA, oldAll, oldB, bWaiter]) - expect(mocks.scanRuntimeAiVaultSessions.mock.calls.filter(([host]) => host === 'b')).toHaveLength( - bCalls - ) - expect((await list('runtime:b', ['/race'])).sessions[0]?.title).toBe('Manual name') - expect((await list('runtime:a', ['/race'])).sessions[0]?.title).toBe('Provider title') - expect((await list('all', ['/race'])).sessions).toEqual(currentAll.sessions) - // Expired projected caches must not resurrect the pre-edge last-full answer. - await vi.advanceTimersByTimeAsync(15_000) - mocks.scanRuntimeAiVaultSessions.mockResolvedValueOnce({ - ...EMPTY_RESULT, - fingerprint: 'owned', - unchanged: true - }) - expect((await list('runtime:a')).sessions).toEqual([]) - expect(mocks.scanAiVaultSessionsInService).toHaveBeenCalledTimes(warmRaceScannerStarts) - expect(mocks.scanRuntimeAiVaultSessions.mock.calls.every(([, args]) => args.force !== true)).toBe( - true - ) - const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) - observerThrows = true - frame({ type: 'snapshot', sessions: [] }) - expect(warning).toHaveBeenCalled() - await forwarding.at(-1)!() - warning.mockRestore() - const sends = sender.send.mock.calls.length - advanceRuntimeEnvironmentTransportGeneration('a') - frame({ type: 'snapshot', sessions: [] }) - expect(sender.send).toHaveBeenCalledTimes(sends) - await ipcHandler('runtimeEnvironments:unsubscribe')({ sender }, { subscriptionId: 'association' }) - expect(retained.size).toBe(0) - await ipcHandler('runtimeEnvironments:subscribe')( - { sender }, - { selector: 'a', method: 'agentSession.subscribeStatus', subscriptionId: 'renewed' } - ) - observerThrows = false - await list('runtime:a') - frame({ type: 'status', session: { ...summary, providerSession: undefined } }) - await list('runtime:a') - const beforeRenewal = mocks.scanRuntimeAiVaultSessions.mock.calls.length - frame({ type: 'snapshot', sessions: [] }) - await list('runtime:a') - expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledTimes(beforeRenewal + 1) - await ipcHandler('runtimeEnvironments:unsubscribe')({ sender }, { subscriptionId: 'renewed' }) - const disposedSends = sender.send.mock.calls.length - frame({ type: 'status', session: summary }) - expect(sender.send).toHaveBeenCalledTimes(disposedSends) - expect(retained.size).toBe(0) -}) diff --git a/src/main/ipc/ai-vault/ai-vault-scan-progress-broadcast.ts b/src/main/ipc/ai-vault/ai-vault-scan-progress-broadcast.ts index 9d97401fc1f..bdf14b3ceec 100644 --- a/src/main/ipc/ai-vault/ai-vault-scan-progress-broadcast.ts +++ b/src/main/ipc/ai-vault/ai-vault-scan-progress-broadcast.ts @@ -3,7 +3,7 @@ import { AI_VAULT_SCAN_PROGRESS_CHANNEL } from '../../../shared/ai-vault/scannin import { localAiVaultScanProgress, onLocalAiVaultScanProgress -} from '../../ai-vault/ai-vault-local-scan-progress' +} from '../../ai-vault/scan-lifecycle/ai-vault-local-scan-progress' let unsubscribe: (() => void) | null = null diff --git a/src/main/ipc/ai-vault/ai-vault-search.test.ts b/src/main/ipc/ai-vault/ai-vault-search.test.ts index 0970ae51edb..f03341e43cf 100644 --- a/src/main/ipc/ai-vault/ai-vault-search.test.ts +++ b/src/main/ipc/ai-vault/ai-vault-search.test.ts @@ -24,7 +24,7 @@ vi.mock('../ssh/ssh', () => ({ import { createChildSessionSearchService } from '../../ai-vault-search/session-search-child-service' import { registerAiVaultSearchHandlers } from './ai-vault-search' -import { aiVaultApi } from '../../../preload/api/ai-vault-bridge' +import { aiVaultApi } from '../../../preload/api/ai-vault/ai-vault-bridge' import { setSessionSearchService } from '../../ai-vault-search/session-search-service-registry' import { fakeSearchService } from '../../../shared/ai-vault/search/ai-vault-search-test-fixture' import { setStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' diff --git a/src/main/ipc/ai-vault/ai-vault-search.ts b/src/main/ipc/ai-vault/ai-vault-search.ts index dde935592a5..f314894e9f7 100644 --- a/src/main/ipc/ai-vault/ai-vault-search.ts +++ b/src/main/ipc/ai-vault/ai-vault-search.ts @@ -32,7 +32,7 @@ import { AI_VAULT_ALL_HOST_TIMEOUT_MS } from './ai-vault-all-host-timeouts' import { OPENS_EVERY_STRUCTURED_CHAT, searchWithStructuredOwners -} from '../../ai-vault/structured-session-ownership' +} from '../../ai-vault/structured-sessions/structured-session-ownership' export type RuntimeSessionSearchCall = ( environmentId: string, diff --git a/src/main/ipc/ai-vault/ai-vault-subagent-list.ts b/src/main/ipc/ai-vault/ai-vault-subagent-list.ts index f6240190457..6e9f43493c2 100644 --- a/src/main/ipc/ai-vault/ai-vault-subagent-list.ts +++ b/src/main/ipc/ai-vault/ai-vault-subagent-list.ts @@ -1,8 +1,8 @@ import { resolve } from 'node:path' -import { getAiVaultWslHomeDirs } from '../../ai-vault/cached-session-list' +import { getAiVaultWslHomeDirs } from '../../ai-vault/discovery/ai-vault-scan-roots' import { listAiVaultSubagentSessionsInBackground } from '../../ai-vault/scan-service/session-scanner-background' -import { claudeProjectsRootDirs } from '../../ai-vault/session-scanner-roots' -import { sessionRowRootDirs } from '../../ai-vault/session-scanner-agent-sources' +import { claudeProjectsRootDirs } from '../../ai-vault/discovery/session-scanner-roots' +import { sessionRowRootDirs } from '../../ai-vault/discovery/session-scanner-agent-sources' import { isPathInsideOrEqual } from '../../../shared/cross-platform-path' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import type { diff --git a/src/main/ipc/ai-vault/ai-vault-unresolved-owner.test.ts b/src/main/ipc/ai-vault/ai-vault-unresolved-owner.test.ts index ecf2580d3bd..fde7e54ca54 100644 --- a/src/main/ipc/ai-vault/ai-vault-unresolved-owner.test.ts +++ b/src/main/ipc/ai-vault/ai-vault-unresolved-owner.test.ts @@ -1,5 +1,7 @@ /** Unresolved-owner sentinels have no environment: return unavailable instead of dialing a paired runtime (#18097). */ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { resetLocalAiVaultScanProgressForTests } from '../../ai-vault/scan-lifecycle/ai-vault-local-scan-progress' const mocks = vi.hoisted(() => ({ scanLocalSessions: vi.fn(), @@ -38,6 +40,8 @@ beforeEach(() => { _internals.resetAiVaultCacheForTests() }) +afterEach(resetLocalAiVaultScanProgressForTests) + describe('AI Vault never routes the unresolved-owner sentinel (#18097)', () => { it('answers a list with a host issue and no runtime or local scan', async () => { registerAiVaultHandlers({ scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions }) diff --git a/src/main/ipc/ai-vault/ai-vault.ts b/src/main/ipc/ai-vault/ai-vault.ts index 303166c2cf8..63685c661f1 100644 --- a/src/main/ipc/ai-vault/ai-vault.ts +++ b/src/main/ipc/ai-vault/ai-vault.ts @@ -3,20 +3,20 @@ import { type AiVaultProjectionDependency } from './ai-vault-projection-dependency' import { app, ipcMain } from 'electron' +import { configureAiVaultSessionSources } from '../../ai-vault/discovery/ai-vault-scan-roots' import { - configureAiVaultSessionSources, listAiVaultSessions as listCachedLocalAiVaultSessions, AiVaultLocalScanError, - resetAiVaultSessionListCacheForTests, - type AiVaultSessionSources -} from '../../ai-vault/cached-session-list' + resetAiVaultSessionListCacheForTests +} from '../../ai-vault/listing/cached-session-list' +import type { AiVaultSessionSources } from '../../ai-vault/discovery/ai-vault-scan-roots' import { deleteAiVaultSession, registerAiVaultDeleteHandler } from './ai-vault-delete' import { listAiVaultSubagentSessions } from './ai-vault-subagent-list' import { aiVaultScanIssueResult, cancelledAiVaultListResult, mergeAiVaultListResults -} from '../../ai-vault/session-list-results' +} from '../../ai-vault/listing/session-list-results' import type { AiVaultDeleteSessionArgs } from '../../../shared/ai-vault/contracts/ai-vault-session-deletion' import { classifyAiVaultScanError } from '../../../shared/ai-vault/scanning/ai-vault-scan-error-message' import { @@ -28,7 +28,7 @@ import { type AiVaultSubagentListArgs, type AiVaultSubagentListResult } from '../../../shared/ai-vault/contracts/ai-vault-types' -import { handleAiVaultGetFirstUserPrompt } from '../../ai-vault/session-first-user-prompt-handler' +import { handleAiVaultGetFirstUserPrompt } from '../../ai-vault/prompts/session-first-user-prompt-handler' import { registerAiVaultResumeHandler, type AiVaultResumeHandlerOptions } from './ai-vault-resume' import { LOCAL_EXECUTION_HOST_ID, @@ -43,7 +43,7 @@ import { scanRuntimeAiVaultSessions, type RuntimeAiVaultHostInfo, type RuntimeAiVaultScanner -} from '../../ai-vault/ai-vault-runtime-scan' +} from '../../ai-vault/runtime-hosts/ai-vault-runtime-scan' import { createAiVaultListScanCoordinator, invalidateAiVaultHostLegCache, @@ -62,7 +62,7 @@ import { import { OPENS_EVERY_STRUCTURED_CHAT, projectStructuredAiVaultSessions -} from '../../ai-vault/structured-session-ownership' +} from '../../ai-vault/structured-sessions/structured-session-ownership' import { allHostsRuntimeScanTimeoutMs } from './ai-vault-all-host-timeouts' import { registerAiVaultScanProgressBroadcast } from './ai-vault-scan-progress-broadcast' diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index d44b677b5ca..48cc7d326fc 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -9,12 +9,12 @@ import type { AppIdentity } from '../../shared/app-identity' import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { FloatingTerminalCwdRequest } from '../../shared/ui-chrome-types' import { relaunchApp, runBeforeRelaunchCleanup } from '../startup/quit/app-relaunch' -import { setWindowMaterialSuppressed } from '../window/window-material-suppression' +import { setWindowMaterialSuppressed } from '../window/presentation/window-material-suppression' import { isTrustedUIRenderer } from './ui' import { prepareWindowsAdministratorRestart } from '../windows/windows-administrator-restart' -import { quitProcess } from '../startup/process-quit-request' +import { quitProcess } from '../startup/quit/process-quit-request' import type { Store } from '../persistence/loading-store/store' -import { getDevInstanceIdentity } from '../startup/dev-instance-identity' +import { getDevInstanceIdentity } from '../startup/profile-startup/dev-instance-identity' import { isPwshAvailableAsync } from '../pty/shell-startup/pwsh' import { isWslAvailableAsync } from '../wsl/discovery/wsl-availability' import { listWslDistrosAsync } from '../wsl/discovery/distro-catalog' @@ -37,7 +37,7 @@ import { } from './renderer-shutdown-checkpoint' import { readMacKeyboardLayoutSnapshot } from './macos-keyboard-layout-snapshot' import { registerMacKeyboardLayoutChangeNotifications } from './macos-keyboard-layout-change-notifications' -import { isProfileStateSaveDelayed } from '../startup/profile-state-save-delay' +import { isProfileStateSaveDelayed } from '../startup/profile-startup/profile-state-save-delay' import { readCommandStdout, readKeyboardInputSourceId } from './macos-keyboard-input-source' import { getWindowsAdministratorStatus } from '../windows/windows-administrator-status' import { getMacosUpgradeSupport } from '../macos-update-requirement/macos-upgrade-support' diff --git a/src/main/ipc/automations.ts b/src/main/ipc/automations.ts index 4ef5d9d095b..940ffda2e95 100644 --- a/src/main/ipc/automations.ts +++ b/src/main/ipc/automations.ts @@ -2,13 +2,13 @@ import { parseExecutionHostId } from '../../shared/execution-host' import { hostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' import { ipcMain } from 'electron' import type { Store } from '../persistence/loading-store/store' -import type { AutomationService } from '../automations/service' -import { createScopedExternalAutomations } from '../automations/external-manager' +import type { AutomationService } from '../automations/automation-service' +import { createScopedExternalAutomations } from '../automations/external-managers/scoped-external-automations' import { ExternalAutomationManagerCache, type ExternalAutomationManagerCacheEntry -} from '../automations/external-automation-manager-cache' -import { ExternalAutomationProbeScheduler } from '../automations/external-automation-probe-scheduler' +} from '../automations/external-managers/external-automation-manager-cache' +import { ExternalAutomationProbeScheduler } from '../automations/external-managers/external-automation-probe-scheduler' import { ownerKey } from '../../shared/automations/ownership/automation-owner-key' import type { AutomationOwnerRef } from '../../shared/automations/ownership/automation-owner-ref' import type { diff --git a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts index cd40d4ad535..70024275cca 100644 --- a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts +++ b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts @@ -32,8 +32,8 @@ import { ALL_RPC_METHODS } from '../../runtime/rpc/methods/rpc-method-registry' import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' -import { getRuntimeEnvironmentStatus } from '../runtime-environments/runtime-environment-status-probe' -import { isRuntimeEnvironmentManuallyDisconnected } from '../runtime-environments/runtime-environment-manual-disconnect' +import { getRuntimeEnvironmentStatus } from '../runtime-environments/status/runtime-environment-status-probe' +import { isRuntimeEnvironmentManuallyDisconnected } from '../runtime-environments/connectivity/runtime-environment-manual-disconnect' import { isDesktopBrowserBridgeHostStopped, setDesktopBrowserBridgeControl diff --git a/src/main/ipc/cli.ts b/src/main/ipc/cli.ts index e5d175e85ce..a765a62d0d7 100644 --- a/src/main/ipc/cli.ts +++ b/src/main/ipc/cli.ts @@ -17,7 +17,10 @@ import { } from '../cli/wsl/wsl-cli-status' import { runSerializedWslCliRegistrationOperation } from '../cli/wsl/wsl-cli-registration-operation' import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' -import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' +import { + hydrateShellPath, + mergePathSegments +} from '../startup/shell-environment/hydrate-shell-path' import { getDefaultWslDistro } from '../wsl/discovery/distro-catalog' import { blockedWslDistroForExec, diff --git a/src/main/ipc/codex-accounts.ts b/src/main/ipc/codex-accounts.ts index f6be30d7f95..f86f1c31c98 100644 --- a/src/main/ipc/codex-accounts.ts +++ b/src/main/ipc/codex-accounts.ts @@ -1,6 +1,7 @@ import { ipcMain } from 'electron' -import type { CodexAccountAddTarget, CodexAccountService } from '../codex-accounts/service' -import type { CodexAccountSelectionTarget } from '../codex-accounts/runtime-selection' +import type { CodexAccountService } from '../codex-accounts/service' +import type { CodexAccountAddTarget } from '../codex-accounts/account-management/codex-account-service-types' +import type { CodexAccountSelectionTarget } from '../../shared/codex-selection-lane' import { broadcastCodexPendingLoginUrl } from './codex-pending-login-url-broadcast' import { openAccountSignInLink } from './account-sign-in-link-opener' import { listRecordedCodexPaneLanes } from '../codex/configuration/homes/codex-pane-account-registry' diff --git a/src/main/ipc/codex-config-sync.ts b/src/main/ipc/codex-config-sync.ts index e599d50375d..32fb57eefc3 100644 --- a/src/main/ipc/codex-config-sync.ts +++ b/src/main/ipc/codex-config-sync.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' import { getCodexConfigSyncStatus } from '../codex/configuration/settings/config-sync-stall' import type { CodexConfigSyncStatus } from '../../shared/codex-config-sync-types' -import type { CodexMirroredHomeStatus } from '../codex-accounts/runtime-home-service' +import type { CodexMirroredHomeStatus } from '../codex-accounts/runtime-home/runtime-home-service-types' /** The read-only slice of the runtime home service this channel needs. */ type CodexMirroredHomeResolver = { diff --git a/src/main/ipc/command-path/agent-detection-shell-path.ts b/src/main/ipc/command-path/agent-detection-shell-path.ts index 39d86810067..4ac38225db2 100644 --- a/src/main/ipc/command-path/agent-detection-shell-path.ts +++ b/src/main/ipc/command-path/agent-detection-shell-path.ts @@ -1,4 +1,7 @@ -import { hydrateShellPath, mergePathSegments } from '../../startup/hydrate-shell-path' +import { + hydrateShellPath, + mergePathSegments +} from '../../startup/shell-environment/hydrate-shell-path' import { getPreflightWslTarget, type PreflightRuntimeContext } from '../preflight-runtime-target' export async function hydrateShellPathForAgentDetection( diff --git a/src/main/ipc/dashboard-popout.ts b/src/main/ipc/dashboard-popout.ts index 715b6abf7fb..28a0acd02d4 100644 --- a/src/main/ipc/dashboard-popout.ts +++ b/src/main/ipc/dashboard-popout.ts @@ -9,8 +9,8 @@ import { isDashboardPopoutRenderer, onDashboardPopoutOpenChanged } from '../window/dashboard-popout-window' -import { safelyRevealWindow } from '../window/focus-existing-window' -import { isBackgroundLaunch } from '../window/foreground-activation-policy' +import { safelyRevealWindow } from '../window/activation/focus-existing-window' +import { isBackgroundLaunch } from '../window/activation/foreground-activation-policy' import { getTrustedUIRendererWindow, isTrustedUIRenderer, sendToTrustedUIRenderer } from './ui' import { admitDashboardSnapshot, diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index e322668b02e..94c73b4d66e 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -39,7 +39,7 @@ import { registerEphemeralVmRuntimeHandlers } from './ephemeral-vm-runtime-handl import type { PluginService } from '../plugins/plugin-service' import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' import { resolveProvisionedRootSource } from '../ephemeral-vm/provisioned-root-source' -import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/catalog/runtime-environment-registry-root' import { ephemeralVmFailure, pickEphemeralVmFailureCode, diff --git a/src/main/ipc/feedback-request.ts b/src/main/ipc/feedback-request.ts index ec44fef3f9a..0a756c9f663 100644 --- a/src/main/ipc/feedback-request.ts +++ b/src/main/ipc/feedback-request.ts @@ -6,7 +6,7 @@ import type { } from '../../shared/feedback-submit-contract' // Main-process HTTP avoids CORS preflights rejected by feedback when packaged renderers use file origins. -export const FEEDBACK_API_URL = 'https://www.onorca.dev/v1/feedback' +export const FEEDBACK_API_URL = 'https://orca.dev/v1/feedback' const FEEDBACK_REQUEST_TIMEOUT_MS = 10_000 const DIAGNOSTIC_BUNDLE_CONTENT_TYPE = 'application/x-ndjson' diff --git a/src/main/ipc/filesystem/filesystem-git-commit-generation-handlers.ts b/src/main/ipc/filesystem/filesystem-git-commit-generation-handlers.ts index d11ac6319d3..fba3d8d737b 100644 --- a/src/main/ipc/filesystem/filesystem-git-commit-generation-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-commit-generation-handlers.ts @@ -8,17 +8,17 @@ import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/so import { cancelGenerateCommitMessageLocal, generateCommitMessageFromContext, - resolveCommitMessageSettings, - type GenerateCommitMessageResult + resolveCommitMessageSettings } from '../../text-generation/commit-message-text-generation' +import type { GenerateCommitMessageResult } from '../../text-generation/source-control-text-generation-types' import { getCommitMessageModelDiscoveryHostKey } from '../../../shared/source-control/ai/generation/commit-message-host-key' -import { getStagedCommitContext } from '../../git/source-control/staged-commit-context' +import { getStagedCommitContext } from '../../git/source-control/mutations/staged-commit-context' import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../providers/ssh-host-not-served-error' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' import { withLinkedIssueDraftContext } from '../../../shared/source-control/ai/recipes/source-control-ai-action-variables' import { resolveSourceControlAiLinkedIssue } from '../source-control/source-control-ai-linked-issue' -import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/commit-message-agent-environment' +import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/execution/commit-message-agent-environment' import type { FilesystemHandlerContext } from './filesystem-handler-context' import { getLocalAgentRuntimeTarget, diff --git a/src/main/ipc/filesystem/filesystem-git-commit-handlers.ts b/src/main/ipc/filesystem/filesystem-git-commit-handlers.ts index b2c270d8d7b..bb608f9f274 100644 --- a/src/main/ipc/filesystem/filesystem-git-commit-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-commit-handlers.ts @@ -2,7 +2,7 @@ import type { GitCommitAction } from '../../../shared/git/commands/git-commit-ac import { applyCommit, recoverSequencer } from '../../git/worktrees/checkout/commit-actions' import { createBranch } from '../../git/worktrees/checkout/create-branch' import { ipcMain } from 'electron' -import { commitChanges, completeMerge } from '../../git/source-control/commit-changes' +import { commitChanges, completeMerge } from '../../git/source-control/mutations/commit-changes' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' import type { FilesystemHandlerContext } from './filesystem-handler-context' diff --git a/src/main/ipc/filesystem/filesystem-git-diff-handlers.ts b/src/main/ipc/filesystem/filesystem-git-diff-handlers.ts index e0b4f243bae..fc7a610e49c 100644 --- a/src/main/ipc/filesystem/filesystem-git-diff-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-diff-handlers.ts @@ -1,7 +1,7 @@ import { ipcMain } from 'electron' import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import { getBranchDiff } from '../../git/source-control/branch-diff' -import { getCommitDiff } from '../../git/source-control/commit-diff' +import { getBranchDiff } from '../../git/source-control/comparisons/branch-diff' +import { getCommitDiff } from '../../git/source-control/comparisons/commit-diff' import { validateFullGitObjectId, validateGitRelativeFilePath diff --git a/src/main/ipc/filesystem/filesystem-git-index-handlers.ts b/src/main/ipc/filesystem/filesystem-git-index-handlers.ts index a86b2c674db..764faf455ef 100644 --- a/src/main/ipc/filesystem/filesystem-git-index-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-index-handlers.ts @@ -6,8 +6,11 @@ import { bulkStageFiles, bulkUnstageFiles, stageWorktreeChanges -} from '../../git/source-control/staging' -import { discardChanges, bulkDiscardChanges } from '../../git/source-control/discard-changes' +} from '../../git/source-control/mutations/staging' +import { + discardChanges, + bulkDiscardChanges +} from '../../git/source-control/mutations/discard-changes' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree, diff --git a/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts b/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts index 03ea1c0ebff..a9e0c655b08 100644 --- a/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts @@ -1,11 +1,9 @@ import { ipcMain } from 'electron' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import type { CommitMessageAgentRuntimeTarget } from '../../text-generation/commit-message-agent-environment' -import { - discoverCommitMessageModelsLocal, - type DiscoverCommitMessageModelsResult -} from '../../text-generation/commit-message-text-generation' -import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentRuntimeTarget } from '../../text-generation/execution/commit-message-agent-environment' +import { discoverCommitMessageModelsLocal } from '../../text-generation/commit-message-text-generation' +import type { DiscoverCommitMessageModelsResult } from '../../text-generation/source-control-text-generation-types' +import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/execution/commit-message-agent-environment' import { parseWslPath } from '../../wsl/filesystem/unc-path-access' import { resolveModelDiscoveryLocalPath, diff --git a/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts b/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts index 1b0f45c9732..be2c6ea08ae 100644 --- a/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts @@ -13,8 +13,8 @@ import { type GeneratePullRequestFieldsResult } from '../../text-generation/commit-message-text-generation' import { getCommitMessageModelDiscoveryHostKey } from '../../../shared/source-control/ai/generation/commit-message-host-key' -import { getPullRequestDraftContext } from '../../text-generation/pull-request-context' -import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/commit-message-agent-environment' +import { getPullRequestDraftContext } from '../../text-generation/pull-request-context/pull-request-context' +import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/execution/commit-message-agent-environment' import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../providers/ssh-host-not-served-error' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' diff --git a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts index 994063a9db8..81779a5a33b 100644 --- a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts @@ -6,23 +6,25 @@ import type { } from '../../../shared/git/status/git-status-types' import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' import type { GitStatusRefBindingRequest as GitStatusUpstreamRefWatchRequest } from '../worktrees/git/worktree-git-status-ref-watch' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' -import { getStatus } from '../../git/source-control/status-read' -import { getSubmoduleStatus } from '../../git/source-control/submodule-status' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' +import { getStatus } from '../../git/source-control/status/status-read' +import { getSubmoduleStatus } from '../../git/source-control/submodules/submodule-status' import { abortMerge, abortRebase, detectConflictOperation -} from '../../git/source-control/git-conflict-operation' -import { getDiff } from '../../git/source-control/file-diff' +} from '../../git/source-control/mutations/git-conflict-operation' +import { getDiff } from '../../git/source-control/diffs/file-diff' import { registerFilesystemGitHistoryHandlers } from './filesystem-git-history-handlers' import { isGitWorktreeMutationInFlight } from '../../git/command-runner/git-worktree-mutation-state' import type { GitMutationInFlight } from '../../../shared/git/commands/git-mutation-in-flight' -import { checkIgnoredPaths } from '../../git/source-control/check-ignored-paths' +import { checkIgnoredPaths } from '../../git/source-control/ignores/check-ignored-paths' +import { readWorktreeAtRiskLocalFiles } from '../../git/worktrees/removal/worktree-at-risk-local-files' +import type { WorktreeAtRiskLocalFiles } from '../../../shared/worktree/removal/at-risk-local-files' import { appendFolderToGitignore, findKnownHugeFolderPathsToIgnore -} from '../../git/source-control/huge-folder-ignore' +} from '../../git/source-control/ignores/huge-folder-ignore' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { validateGitRelativeFilePath } from './access/filesystem-path-containment' import { @@ -171,6 +173,29 @@ export function registerFilesystemGitStatusHandlers(context: FilesystemHandlerCo } ) + ipcMain.handle( + 'git:atRiskLocalFiles', + async ( + _event, + args: { worktreePath: string; connectionId?: string } + ): Promise => { + requireReachableGitRoute(getConnectionExecutionHostId(args.connectionId)) + return readWorktreeGitUnlessWslStopped( + store, + args.worktreePath, + false, + (worktreePath, gitOptions) => + readWorktreeAtRiskLocalFiles({ + worktreePath, + mainCheckoutPath: + getLocalRepoForRegisteredWorktree(store, args.worktreePath, worktreePath)?.path ?? + null, + gitOptions + }) + ) + } + ) + ipcMain.handle( 'git:findHugeFoldersToIgnore', async (_event, args: { worktreePath: string }): Promise => diff --git a/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts b/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts index 0c36980e9e5..0e319889d32 100644 --- a/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts +++ b/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts @@ -40,44 +40,44 @@ vi.mock( '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) -vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/commit-changes', async (importOriginal) => ({ ...(await importOriginal>()), commitChanges: (await import('./filesystem-test-harness')).commitChangesMock })) -vi.mock('../../git/source-control/status-read', async (importOriginal) => ({ +vi.mock('../../git/source-control/status/status-read', async (importOriginal) => ({ ...(await importOriginal>()), getStatus: (await import('./filesystem-test-harness')).getStatusMock })) -vi.mock('../../git/source-control/git-conflict-operation', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/git-conflict-operation', async (importOriginal) => ({ ...(await importOriginal>()), detectConflictOperation: (await import('./filesystem-test-harness')).detectConflictOperationMock, abortMerge: (await import('./filesystem-test-harness')).abortMergeMock, abortRebase: (await import('./filesystem-test-harness')).abortRebaseMock })) -vi.mock('../../git/source-control/file-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/diffs/file-diff', async (importOriginal) => ({ ...(await importOriginal>()), getDiff: (await import('./filesystem-test-harness')).getDiffMock })) -vi.mock('../../git/source-control/branch-compare', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-compare', async (importOriginal) => ({ ...(await importOriginal>()), getBranchCompare: (await import('./filesystem-test-harness')).getBranchCompareMock })) -vi.mock('../../git/source-control/branch-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-diff', async (importOriginal) => ({ ...(await importOriginal>()), getBranchDiff: (await import('./filesystem-test-harness')).getBranchDiffMock })) -vi.mock('../../git/source-control/staged-commit-context', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staged-commit-context', async (importOriginal) => ({ ...(await importOriginal>()), getStagedCommitContext: (await import('./filesystem-test-harness')).getStagedCommitContextMock })) -vi.mock('../../git/source-control/staging', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staging', async (importOriginal) => ({ ...(await importOriginal>()), stageFile: (await import('./filesystem-test-harness')).stageFileMock, bulkStageFiles: (await import('./filesystem-test-harness')).bulkStageFilesMock, @@ -86,13 +86,13 @@ vi.mock('../../git/source-control/staging', async (importOriginal) => ({ bulkUnstageFiles: (await import('./filesystem-test-harness')).bulkUnstageFilesMock })) -vi.mock('../../git/source-control/discard-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/discard-changes', async (importOriginal) => ({ ...(await importOriginal>()), bulkDiscardChanges: (await import('./filesystem-test-harness')).bulkDiscardChangesMock, discardChanges: (await import('./filesystem-test-harness')).discardChangesMock })) vi.mock( - '../../git/source-control/check-ignored-paths', + '../../git/source-control/ignores/check-ignored-paths', async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock ) @@ -101,7 +101,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).textGenerationModuleMock ) vi.mock( - '../../text-generation/pull-request-context', + '../../text-generation/pull-request-context/pull-request-context', async () => (await import('./filesystem-test-harness')).pullRequestContextMock ) vi.mock( diff --git a/src/main/ipc/filesystem/filesystem-handler-context.ts b/src/main/ipc/filesystem/filesystem-handler-context.ts index 025fbc2d6ad..6c0b3b8b145 100644 --- a/src/main/ipc/filesystem/filesystem-handler-context.ts +++ b/src/main/ipc/filesystem/filesystem-handler-context.ts @@ -1,7 +1,7 @@ import type { ChildProcess } from 'node:child_process' import type { FileHandle } from 'node:fs/promises' import type { Store } from '../../persistence/loading-store/store' -import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/execution/commit-message-agent-environment' import type { SenderScopedRequestCancellations } from '../sender-scoped-request-cancellation' import { cleanupLocalTransferPath } from './filesystem-download-promotion' diff --git a/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts b/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts index 7af180afb3a..6b2734c80ba 100644 --- a/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts +++ b/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts @@ -42,44 +42,44 @@ vi.mock( '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) -vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/commit-changes', async (importOriginal) => ({ ...(await importOriginal>()), commitChanges: (await import('./filesystem-test-harness')).commitChangesMock })) -vi.mock('../../git/source-control/status-read', async (importOriginal) => ({ +vi.mock('../../git/source-control/status/status-read', async (importOriginal) => ({ ...(await importOriginal>()), getStatus: (await import('./filesystem-test-harness')).getStatusMock })) -vi.mock('../../git/source-control/git-conflict-operation', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/git-conflict-operation', async (importOriginal) => ({ ...(await importOriginal>()), detectConflictOperation: (await import('./filesystem-test-harness')).detectConflictOperationMock, abortMerge: (await import('./filesystem-test-harness')).abortMergeMock, abortRebase: (await import('./filesystem-test-harness')).abortRebaseMock })) -vi.mock('../../git/source-control/file-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/diffs/file-diff', async (importOriginal) => ({ ...(await importOriginal>()), getDiff: (await import('./filesystem-test-harness')).getDiffMock })) -vi.mock('../../git/source-control/branch-compare', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-compare', async (importOriginal) => ({ ...(await importOriginal>()), getBranchCompare: (await import('./filesystem-test-harness')).getBranchCompareMock })) -vi.mock('../../git/source-control/branch-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-diff', async (importOriginal) => ({ ...(await importOriginal>()), getBranchDiff: (await import('./filesystem-test-harness')).getBranchDiffMock })) -vi.mock('../../git/source-control/staged-commit-context', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staged-commit-context', async (importOriginal) => ({ ...(await importOriginal>()), getStagedCommitContext: (await import('./filesystem-test-harness')).getStagedCommitContextMock })) -vi.mock('../../git/source-control/staging', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staging', async (importOriginal) => ({ ...(await importOriginal>()), stageFile: (await import('./filesystem-test-harness')).stageFileMock, bulkStageFiles: (await import('./filesystem-test-harness')).bulkStageFilesMock, @@ -88,13 +88,13 @@ vi.mock('../../git/source-control/staging', async (importOriginal) => ({ bulkUnstageFiles: (await import('./filesystem-test-harness')).bulkUnstageFilesMock })) -vi.mock('../../git/source-control/discard-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/discard-changes', async (importOriginal) => ({ ...(await importOriginal>()), bulkDiscardChanges: (await import('./filesystem-test-harness')).bulkDiscardChangesMock, discardChanges: (await import('./filesystem-test-harness')).discardChangesMock })) vi.mock( - '../../git/source-control/check-ignored-paths', + '../../git/source-control/ignores/check-ignored-paths', async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock ) @@ -103,7 +103,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).textGenerationModuleMock ) vi.mock( - '../../text-generation/pull-request-context', + '../../text-generation/pull-request-context/pull-request-context', async () => (await import('./filesystem-test-harness')).pullRequestContextMock ) vi.mock( diff --git a/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts b/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts index cb8ef6369e7..f701b84607e 100644 --- a/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts +++ b/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts @@ -7,7 +7,10 @@ import { constants } from 'node:fs' import { lstat, open, readdir, realpath, type FileHandle } from 'node:fs/promises' import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { classifyImportSource } from './filesystem-import-source-stat' -import { detectImageFileSignature, IMAGE_SIGNATURE_BYTES } from '../../media/image-file-signature' +import { + detectImageFileSignature, + IMAGE_SIGNATURE_BYTES +} from '../../../shared/image-file-signature' import type { StagedRuntimeUploadEntry as StagedExternalImportEntry, StagedRuntimeUploadSource as StagedExternalImportSource diff --git a/src/main/ipc/filesystem/filesystem-source-control-ai-targets.ts b/src/main/ipc/filesystem/filesystem-source-control-ai-targets.ts index c6989cd5318..ce081af348a 100644 --- a/src/main/ipc/filesystem/filesystem-source-control-ai-targets.ts +++ b/src/main/ipc/filesystem/filesystem-source-control-ai-targets.ts @@ -4,8 +4,8 @@ import { getLocalProjectWorktreeGitOptions, type LocalProjectWorktreeGitOptions } from '../../workspaces/execution-host/project-runtime-git-options' -import type { CommitMessageAgentRuntimeTarget } from '../../text-generation/commit-message-agent-environment' -import type { CommitMessageGenerationTarget } from '../../text-generation/commit-message-text-generation' +import type { CommitMessageAgentRuntimeTarget } from '../../text-generation/execution/commit-message-agent-environment' +import type { CommitMessageGenerationTarget } from '../../text-generation/source-control-text-generation-types' import { resolve } from 'node:path' import { listRepoWorktreeGraph } from '../../workspaces/catalog/repo-worktrees' import { resolveAuthorizedPath } from './access/filesystem-auth' diff --git a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts index a4e9e31742a..8849a669fae 100644 --- a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts +++ b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts @@ -52,44 +52,44 @@ vi.mock( '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) -vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/commit-changes', async (importOriginal) => ({ ...(await importOriginal>()), commitChanges: (await import('./filesystem-test-harness')).commitChangesMock })) -vi.mock('../../git/source-control/status-read', async (importOriginal) => ({ +vi.mock('../../git/source-control/status/status-read', async (importOriginal) => ({ ...(await importOriginal>()), getStatus: (await import('./filesystem-test-harness')).getStatusMock })) -vi.mock('../../git/source-control/git-conflict-operation', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/git-conflict-operation', async (importOriginal) => ({ ...(await importOriginal>()), detectConflictOperation: (await import('./filesystem-test-harness')).detectConflictOperationMock, abortMerge: (await import('./filesystem-test-harness')).abortMergeMock, abortRebase: (await import('./filesystem-test-harness')).abortRebaseMock })) -vi.mock('../../git/source-control/file-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/diffs/file-diff', async (importOriginal) => ({ ...(await importOriginal>()), getDiff: (await import('./filesystem-test-harness')).getDiffMock })) -vi.mock('../../git/source-control/branch-compare', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-compare', async (importOriginal) => ({ ...(await importOriginal>()), getBranchCompare: (await import('./filesystem-test-harness')).getBranchCompareMock })) -vi.mock('../../git/source-control/branch-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-diff', async (importOriginal) => ({ ...(await importOriginal>()), getBranchDiff: (await import('./filesystem-test-harness')).getBranchDiffMock })) -vi.mock('../../git/source-control/staged-commit-context', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staged-commit-context', async (importOriginal) => ({ ...(await importOriginal>()), getStagedCommitContext: (await import('./filesystem-test-harness')).getStagedCommitContextMock })) -vi.mock('../../git/source-control/staging', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staging', async (importOriginal) => ({ ...(await importOriginal>()), stageFile: (await import('./filesystem-test-harness')).stageFileMock, bulkStageFiles: (await import('./filesystem-test-harness')).bulkStageFilesMock, @@ -98,13 +98,13 @@ vi.mock('../../git/source-control/staging', async (importOriginal) => ({ bulkUnstageFiles: (await import('./filesystem-test-harness')).bulkUnstageFilesMock })) -vi.mock('../../git/source-control/discard-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/discard-changes', async (importOriginal) => ({ ...(await importOriginal>()), bulkDiscardChanges: (await import('./filesystem-test-harness')).bulkDiscardChangesMock, discardChanges: (await import('./filesystem-test-harness')).discardChangesMock })) vi.mock( - '../../git/source-control/check-ignored-paths', + '../../git/source-control/ignores/check-ignored-paths', async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock ) @@ -113,7 +113,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).textGenerationModuleMock ) vi.mock( - '../../text-generation/pull-request-context', + '../../text-generation/pull-request-context/pull-request-context', async () => (await import('./filesystem-test-harness')).pullRequestContextMock ) vi.mock( diff --git a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts index e37577bb026..3ff31e0fbc1 100644 --- a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts +++ b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts @@ -48,44 +48,44 @@ vi.mock( '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) -vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/commit-changes', async (importOriginal) => ({ ...(await importOriginal>()), commitChanges: (await import('./filesystem-test-harness')).commitChangesMock })) -vi.mock('../../git/source-control/status-read', async (importOriginal) => ({ +vi.mock('../../git/source-control/status/status-read', async (importOriginal) => ({ ...(await importOriginal>()), getStatus: (await import('./filesystem-test-harness')).getStatusMock })) -vi.mock('../../git/source-control/git-conflict-operation', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/git-conflict-operation', async (importOriginal) => ({ ...(await importOriginal>()), detectConflictOperation: (await import('./filesystem-test-harness')).detectConflictOperationMock, abortMerge: (await import('./filesystem-test-harness')).abortMergeMock, abortRebase: (await import('./filesystem-test-harness')).abortRebaseMock })) -vi.mock('../../git/source-control/file-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/diffs/file-diff', async (importOriginal) => ({ ...(await importOriginal>()), getDiff: (await import('./filesystem-test-harness')).getDiffMock })) -vi.mock('../../git/source-control/branch-compare', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-compare', async (importOriginal) => ({ ...(await importOriginal>()), getBranchCompare: (await import('./filesystem-test-harness')).getBranchCompareMock })) -vi.mock('../../git/source-control/branch-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-diff', async (importOriginal) => ({ ...(await importOriginal>()), getBranchDiff: (await import('./filesystem-test-harness')).getBranchDiffMock })) -vi.mock('../../git/source-control/staged-commit-context', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staged-commit-context', async (importOriginal) => ({ ...(await importOriginal>()), getStagedCommitContext: (await import('./filesystem-test-harness')).getStagedCommitContextMock })) -vi.mock('../../git/source-control/staging', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staging', async (importOriginal) => ({ ...(await importOriginal>()), stageFile: (await import('./filesystem-test-harness')).stageFileMock, bulkStageFiles: (await import('./filesystem-test-harness')).bulkStageFilesMock, @@ -94,13 +94,13 @@ vi.mock('../../git/source-control/staging', async (importOriginal) => ({ bulkUnstageFiles: (await import('./filesystem-test-harness')).bulkUnstageFilesMock })) -vi.mock('../../git/source-control/discard-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/discard-changes', async (importOriginal) => ({ ...(await importOriginal>()), bulkDiscardChanges: (await import('./filesystem-test-harness')).bulkDiscardChangesMock, discardChanges: (await import('./filesystem-test-harness')).discardChangesMock })) vi.mock( - '../../git/source-control/check-ignored-paths', + '../../git/source-control/ignores/check-ignored-paths', async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock ) @@ -109,7 +109,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).textGenerationModuleMock ) vi.mock( - '../../text-generation/pull-request-context', + '../../text-generation/pull-request-context/pull-request-context', async () => (await import('./filesystem-test-harness')).pullRequestContextMock ) vi.mock( diff --git a/src/main/ipc/filesystem/filesystem.test.ts b/src/main/ipc/filesystem/filesystem.test.ts index a8bbce81e38..159c295902e 100644 --- a/src/main/ipc/filesystem/filesystem.test.ts +++ b/src/main/ipc/filesystem/filesystem.test.ts @@ -46,44 +46,44 @@ vi.mock( '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) -vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/commit-changes', async (importOriginal) => ({ ...(await importOriginal>()), commitChanges: (await import('./filesystem-test-harness')).commitChangesMock })) -vi.mock('../../git/source-control/status-read', async (importOriginal) => ({ +vi.mock('../../git/source-control/status/status-read', async (importOriginal) => ({ ...(await importOriginal>()), getStatus: (await import('./filesystem-test-harness')).getStatusMock })) -vi.mock('../../git/source-control/git-conflict-operation', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/git-conflict-operation', async (importOriginal) => ({ ...(await importOriginal>()), detectConflictOperation: (await import('./filesystem-test-harness')).detectConflictOperationMock, abortMerge: (await import('./filesystem-test-harness')).abortMergeMock, abortRebase: (await import('./filesystem-test-harness')).abortRebaseMock })) -vi.mock('../../git/source-control/file-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/diffs/file-diff', async (importOriginal) => ({ ...(await importOriginal>()), getDiff: (await import('./filesystem-test-harness')).getDiffMock })) -vi.mock('../../git/source-control/branch-compare', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-compare', async (importOriginal) => ({ ...(await importOriginal>()), getBranchCompare: (await import('./filesystem-test-harness')).getBranchCompareMock })) -vi.mock('../../git/source-control/branch-diff', async (importOriginal) => ({ +vi.mock('../../git/source-control/comparisons/branch-diff', async (importOriginal) => ({ ...(await importOriginal>()), getBranchDiff: (await import('./filesystem-test-harness')).getBranchDiffMock })) -vi.mock('../../git/source-control/staged-commit-context', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staged-commit-context', async (importOriginal) => ({ ...(await importOriginal>()), getStagedCommitContext: (await import('./filesystem-test-harness')).getStagedCommitContextMock })) -vi.mock('../../git/source-control/staging', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/staging', async (importOriginal) => ({ ...(await importOriginal>()), stageFile: (await import('./filesystem-test-harness')).stageFileMock, bulkStageFiles: (await import('./filesystem-test-harness')).bulkStageFilesMock, @@ -92,13 +92,13 @@ vi.mock('../../git/source-control/staging', async (importOriginal) => ({ bulkUnstageFiles: (await import('./filesystem-test-harness')).bulkUnstageFilesMock })) -vi.mock('../../git/source-control/discard-changes', async (importOriginal) => ({ +vi.mock('../../git/source-control/mutations/discard-changes', async (importOriginal) => ({ ...(await importOriginal>()), bulkDiscardChanges: (await import('./filesystem-test-harness')).bulkDiscardChangesMock, discardChanges: (await import('./filesystem-test-harness')).discardChangesMock })) vi.mock( - '../../git/source-control/check-ignored-paths', + '../../git/source-control/ignores/check-ignored-paths', async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock ) @@ -107,7 +107,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).textGenerationModuleMock ) vi.mock( - '../../text-generation/pull-request-context', + '../../text-generation/pull-request-context/pull-request-context', async () => (await import('./filesystem-test-harness')).pullRequestContextMock ) vi.mock( diff --git a/src/main/ipc/filesystem/filesystem.ts b/src/main/ipc/filesystem/filesystem.ts index 014f16a429a..742810fe10e 100644 --- a/src/main/ipc/filesystem/filesystem.ts +++ b/src/main/ipc/filesystem/filesystem.ts @@ -1,5 +1,5 @@ import type { Store } from '../../persistence/loading-store/store' -import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/execution/commit-message-agent-environment' import { registerLocalLogTailHandlers } from '../local-log-tail' import { createSenderScopedRequestCancellations } from '../sender-scoped-request-cancellation' import { diff --git a/src/main/ipc/filesystem/git-remote/compare-handlers.ts b/src/main/ipc/filesystem/git-remote/compare-handlers.ts index 818c5970a99..4baa7ed7a5a 100644 --- a/src/main/ipc/filesystem/git-remote/compare-handlers.ts +++ b/src/main/ipc/filesystem/git-remote/compare-handlers.ts @@ -3,13 +3,13 @@ import type { GitBranchCompareResult, GitCommitCompareResult } from '../../../../shared/git/diff/git-diff-compare-types' -import { getBranchCompare } from '../../../git/source-control/branch-compare' -import { getCommitCompare } from '../../../git/source-control/commit-compare' +import { getBranchCompare } from '../../../git/source-control/comparisons/branch-compare' +import { getCommitCompare } from '../../../git/source-control/comparisons/commit-compare' import { resolveRegisteredWorktreePath } from '../../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../../local-worktree-runtime-options' import { validateFullGitObjectId } from '../access/filesystem-path-containment' import type { FilesystemHandlerContext } from '../filesystem-handler-context' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { requireReachableGitRoute } from '../../../providers/execution-host-provider-dispatch' import { getConnectionExecutionHostId } from '../../../../shared/execution-host' import { assertWslUncPathRunning } from '../../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/ipc/filesystem/git-remote/sync-handlers.ts b/src/main/ipc/filesystem/git-remote/sync-handlers.ts index 14f89b72e65..cb0328590eb 100644 --- a/src/main/ipc/filesystem/git-remote/sync-handlers.ts +++ b/src/main/ipc/filesystem/git-remote/sync-handlers.ts @@ -4,7 +4,7 @@ import type { GitPushTarget } from '../../../../shared/worktree/types' import type { GitUpstreamStatus } from '../../../../shared/git/status/git-status-types' import { gitFetch } from '../../../git/remotes/remote' import { gitSyncForkDefaultBranch } from '../../../git/remotes/fork-sync' -import { getUpstreamStatus } from '../../../git/source-control/upstream' +import { getUpstreamStatus } from '../../../git/source-control/upstream/upstream' import { validateGitPushTarget } from '../../../git/remotes/push-target-validation' import { resolveRegisteredWorktreePath } from '../../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../../local-worktree-runtime-options' diff --git a/src/main/ipc/filesystem/local-disk-write-precondition.test.ts b/src/main/ipc/filesystem/local-disk-write-precondition.test.ts index 54018c902cc..dc83e60e184 100644 --- a/src/main/ipc/filesystem/local-disk-write-precondition.test.ts +++ b/src/main/ipc/filesystem/local-disk-write-precondition.test.ts @@ -1,86 +1,10 @@ -import { link, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { link, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' -import { createLocalFilesystemProvider } from '../../providers/local-filesystem-provider' -import type * as LocalRegularFileRead from './local-regular-file-read' -import type * as NodeFsPromises from 'node:fs/promises' - -const fileRead = vi.hoisted(() => { - const state: { - understateSizeBy: number - blockedRead: { path: string; entered: () => void; wait: Promise } | null - openError: Error | null - } = { - understateSizeBy: 0, - blockedRead: null, - openError: null - } - return state -}) -const realpathFailure = vi.hoisted(() => { - const state: { path: string | null } = { path: null } - return state -}) -const zeroInodes = vi.hoisted(() => { - const state: { enabled: boolean } = { enabled: false } - return state -}) -const writeGates = vi.hoisted( - () => new Map void; release: Promise }>() -) -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - // Some RAM/subst/network/WSL volumes cannot resolve realpath. - realpath: async (path: string) => { - if (path === realpathFailure.path) { - throw Object.assign(new Error(`EIO: i/o error, realpath '${path}'`), { code: 'EIO' }) - } - return actual.realpath(path) - }, - // 9P and some SMB mounts expose inode zero for every file. - stat: async (path: string, options?: { bigint?: boolean }) => { - if (options?.bigint !== true) { - return actual.stat(path) - } - const stats = await actual.stat(path, { bigint: true }) - return zeroInodes.enabled ? Object.assign(stats, { ino: 0n }) : stats - }, - // Hold a save after comparison so competing saves must wait before checking. - writeFile: vi.fn(async (...args: Parameters) => { - const gate = typeof args[1] === 'string' ? writeGates.get(args[1]) : undefined - if (gate) { - gate.entered() - await gate.release - } - return actual.writeFile(...args) - }) - } -}) -vi.mock('./local-regular-file-read', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - // Model stat observing size just before a concurrent append. - openLocalRegularFile: async (filePath: string) => { - if (fileRead.openError) { - throw fileRead.openError - } - const blockedRead = fileRead.blockedRead - if (blockedRead?.path === filePath) { - blockedRead.entered() - await blockedRead.wait - } - const opened = await actual.openLocalRegularFile(filePath) - opened.stats.size -= fileRead.understateSizeBy - return opened - } - } -}) +import { createLocalFilesystemProvider } from '../../providers/filesystem/local-provider' let base: string @@ -89,12 +13,6 @@ beforeEach(async () => { }) afterEach(async () => { - fileRead.understateSizeBy = 0 - fileRead.blockedRead = null - fileRead.openError = null - realpathFailure.path = null - writeGates.clear() - zeroInodes.enabled = false await rm(base, { recursive: true, force: true }) }) @@ -107,31 +25,6 @@ describe('local provider guarded write', () => { resolveAuthorizedPath: vi.fn(async (path: string) => path) }) - it('writes when disk matches and refuses without writing when it does not', async () => { - const filePath = join(base, 'a.ts') - await writeFile(filePath, 'original') - - await expect( - provider().writeFileWithDiskPrecondition(filePath, 'edited', { - expectedSignature: getDiskBaselineSignature('original') - }) - ).resolves.toEqual({ ok: true }) - expect(await readFile(filePath, 'utf8')).toBe('edited') - - await expect( - provider().writeFileWithDiskPrecondition(filePath, 'stale', { - expectedSignature: getDiskBaselineSignature('original') - }) - ).resolves.toEqual({ ok: false, diskConflict: 'changed' }) - expect(await readFile(filePath, 'utf8')).toBe('edited') - - await expect( - provider().writeFileWithDiskPrecondition(filePath, 'edited', { - expectedSignature: getDiskBaselineSignature('original') - }) - ).resolves.toEqual({ ok: true, unchanged: true }) - }) - // Windows symlink creation requires elevated rights or Developer Mode. it.skipIf(process.platform === 'win32').each([ ['a symlink', (target: string, alias: string) => symlink(target, alias)], @@ -153,81 +46,4 @@ describe('local provider guarded write', () => { expect(results.filter((result) => result.ok)).toHaveLength(1) } ) - - it.skipIf(process.platform === 'win32')( - 'lets only one save create a missing file reached through a dangling symlink', - async () => { - const target = join(base, 'target.ts') - const link = join(base, 'link.ts') - await symlink(target, link) - const createIfMissing = { - expectedSignature: getDiskBaselineSignature('original'), - allowMissing: true - } - - const results = await Promise.all([ - provider().writeFileWithDiskPrecondition(target, 'through target', createIfMissing), - provider().writeFileWithDiskPrecondition(link, 'through link', createIfMissing) - ]) - - expect(results.filter((result) => result.ok)).toHaveLength(1) - } - ) - - it.skipIf(process.platform === 'win32')( - 'refuses a guarded save through a symlink loop instead of failing', - async () => { - const a = join(base, 'a.ts') - const b = join(base, 'b.ts') - await symlink(b, a) - await symlink(a, b) - - await expect( - provider().writeFileWithDiskPrecondition(a, 'edited', { - expectedSignature: getDiskBaselineSignature('original'), - allowMissing: true - }) - ).resolves.toEqual({ ok: false, diskConflict: 'changed' }) - } - ) - - it.skipIf(process.platform === 'win32')( - 'resolves a relative dangling link from its real folder, not the symlinked path to it', - async () => { - // base/alias -> base/real/sub, and sub/link.ts -> ../target.ts, so the target is base/real/target.ts. - await mkdir(join(base, 'real', 'sub'), { recursive: true }) - await symlink(join(base, 'real', 'sub'), join(base, 'alias')) - await symlink('../target.ts', join(base, 'real', 'sub', 'link.ts')) - const createIfMissing = { - expectedSignature: getDiskBaselineSignature('original'), - allowMissing: true - } - - const results = await Promise.all([ - provider().writeFileWithDiskPrecondition( - join(base, 'alias', 'link.ts'), - 'through alias', - createIfMissing - ), - provider().writeFileWithDiskPrecondition( - join(base, 'real', 'target.ts'), - 'through target', - createIfMissing - ) - ]) - - expect(results.filter((result) => result.ok)).toHaveLength(1) - } - ) - - it('does not resurrect a deleted file without allowMissing', async () => { - const filePath = join(base, 'gone.ts') - - await expect( - provider().writeFileWithDiskPrecondition(filePath, 'edited', { - expectedSignature: getDiskBaselineSignature('original') - }) - ).resolves.toEqual({ ok: false, diskConflict: 'missing' }) - await expect(readFile(filePath, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' }) - }) }) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts index f911df1044a..886196ca8fb 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts @@ -175,47 +175,6 @@ describe('subscribeViaWatcherProcess', () => { await secondPromise }) - it('shares healthy runtime roots and recovers the shard after a crash', async () => { - const firstInterruption = vi.fn() - const secondInterruption = vi.fn() - const firstPromise = subscribeViaRuntimeWatcherProcess( - '/repo-a', - vi.fn(), - {}, - { - onInterruption: firstInterruption - } - ) - const firstChild = currentChild() - ackSubscribe(firstChild) - await firstPromise - - const secondPromise = subscribeViaRuntimeWatcherProcess( - '/repo-b', - vi.fn(), - {}, - { - onInterruption: secondInterruption - } - ) - const secondChild = currentChild() - expect(secondChild).toBe(firstChild) - ackSubscribe(secondChild) - await secondPromise - expect(forkMock).toHaveBeenCalledTimes(1) - - firstChild.connected = false - firstChild.emit('exit', null, 'SIGSEGV') - - const replacement = currentChild() - expect(replacement).not.toBe(firstChild) - expect(replacement.sent.filter((message) => message.op === 'subscribe')).toHaveLength(2) - ackSubscribe(replacement, 0) - ackSubscribe(replacement, 1) - expect(firstInterruption).toHaveBeenCalledTimes(1) - expect(secondInterruption).toHaveBeenCalledTimes(1) - }) - it('completes an in-flight subscribe across a crash-respawn', async () => { const onInterruption = vi.fn() const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}, { onInterruption }) @@ -572,25 +531,6 @@ describe('subscribeViaWatcherProcess', () => { await expect(respawnPromise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) }) - it('kills the idle child when the last pending subscribe fails', async () => { - const promise = subscribeViaWatcherProcess('/gone', vi.fn(), {}) - const first = currentChild() - first.emit('message', { - op: 'subscribe-failed', - id: first.sent[0].id, - message: 'Error opening directory' - }) - await expect(promise).rejects.toThrow('Error opening directory') - expect(first.kill).toHaveBeenCalledTimes(1) - first.emit('exit', 0, null) - await new Promise((resolve) => setImmediate(resolve)) - - const respawnPromise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) - expect(forkMock).toHaveBeenCalledTimes(2) - ackSubscribe(currentChild()) - await expect(respawnPromise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) - }) - it('keeps the child alive while other subscriptions remain', async () => { const firstPromise = subscribeViaWatcherProcess('/a', vi.fn(), {}) const child = currentChild() @@ -631,71 +571,4 @@ describe('subscribeViaWatcherProcess', () => { ).rejects.toMatchObject({ code: 'supervisor_disposed' }) expect(forkMock).toHaveBeenCalledTimes(1) }) - - it('releases a late in-process subscription after pending setup is aborted', async () => { - vi.stubEnv('VITEST', 'true') - const unsubscribe = vi.fn().mockResolvedValue(undefined) - let resolveSubscription!: (subscription: { unsubscribe: typeof unsubscribe }) => void - parcelSubscribeMock.mockReturnValue( - new Promise((resolve) => { - resolveSubscription = resolve - }) - ) - const controller = new AbortController() - const pending = subscribeViaWatcherProcess('/repo', vi.fn(), {}, { signal: controller.signal }) - - await vi.waitFor(() => expect(parcelSubscribeMock).toHaveBeenCalledTimes(1)) - controller.abort() - await expect(pending).rejects.toThrow('aborted') - resolveSubscription({ unsubscribe }) - - await vi.waitFor(() => expect(unsubscribe).toHaveBeenCalledTimes(1)) - }) - - it('fails closed when the isolated watcher entry is absent outside tests', async () => { - existsSyncMock.mockReturnValue(false) - - await expect(subscribeViaWatcherProcess('/repo', vi.fn(), {})).rejects.toThrow( - 'watcher process entry is missing' - ) - expect(forkMock).not.toHaveBeenCalled() - expect(parcelSubscribeMock).not.toHaveBeenCalled() - }) - - it('keeps independently-created supervisors in separate crash-fuse domains', async () => { - const firstSupervisor = createWatcherProcessSupervisor() - const secondSupervisor = createWatcherProcessSupervisor() - const firstCallback = vi.fn() - const secondCallback = vi.fn() - - const firstPromise = firstSupervisor.subscribe('/faulting', firstCallback, {}) - const firstChild = currentChild() - ackSubscribe(firstChild) - await firstPromise - - const secondPromise = secondSupervisor.subscribe('/healthy', secondCallback, {}) - const secondChild = currentChild() - ackSubscribe(secondChild) - await secondPromise - - let faultingChild = firstChild - for (let crash = 0; crash < 2; crash++) { - faultingChild.connected = false - faultingChild.emit('exit', null, 'SIGSEGV') - faultingChild = currentChild() - ackSubscribe(faultingChild) - } - faultingChild.connected = false - faultingChild.emit('exit', null, 'SIGSEGV') - - expect(firstCallback).toHaveBeenCalledWith( - expect.objectContaining({ message: expect.stringContaining('crashed repeatedly') }), - [] - ) - expect(secondCallback).not.toHaveBeenCalled() - expect(secondChild.connected).toBe(true) - - firstSupervisor.dispose() - secondSupervisor.dispose() - }) }) diff --git a/src/main/ipc/jira/issue-summary-generation.ts b/src/main/ipc/jira/issue-summary-generation.ts index 07d1df0a864..224a82ed0f6 100644 --- a/src/main/ipc/jira/issue-summary-generation.ts +++ b/src/main/ipc/jira/issue-summary-generation.ts @@ -2,13 +2,13 @@ import { ipcMain } from 'electron' import { GenerateIssueSummary, CancelGenerateIssueSummary -} from '../../../shared/rpc-contract/jira-params' +} from '../../../shared/rpc-contract/jira/jira-params' import type { Store } from '../../persistence/loading-store/store' -import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/execution/commit-message-agent-environment' import { cancelJiraIssueSummaryRequest, generateJiraIssueSummaryRequest -} from '../../text-generation/jira-issue-summary-requests' +} from '../../text-generation/requests/jira-issue-summary-requests' import { addFanoutListener } from '../../runtime/events/event-listener-fanout' export function registerJiraIssueSummaryGenerationHandlers( diff --git a/src/main/ipc/jira/register-handlers.ts b/src/main/ipc/jira/register-handlers.ts index 5832e81cc45..23032b0a1bc 100644 --- a/src/main/ipc/jira/register-handlers.ts +++ b/src/main/ipc/jira/register-handlers.ts @@ -1,6 +1,6 @@ import { taskProviderFailure } from '../../../shared/work-items/task-provider-failure' -import { JiraIssueListFiltersParam } from '../../../shared/rpc-contract/jira-quick-filter-params' -import { JiraFavouriteFilterParams } from '../../../shared/rpc-contract/jira-favourite-filter-params' +import { JiraIssueListFiltersParam } from '../../../shared/rpc-contract/jira/jira-quick-filter-params' +import { JiraFavouriteFilterParams } from '../../../shared/rpc-contract/jira/jira-favourite-filter-params' import { ipcMain } from 'electron' import type { JiraMediaFormat } from '../../../shared/jira/jira-attachment-image' import { connect, disconnect, getStatus, selectSite, testConnection } from '../../jira/client' diff --git a/src/main/ipc/memory.ts b/src/main/ipc/memory.ts index e9de80a1eae..8bf6348d93a 100644 --- a/src/main/ipc/memory.ts +++ b/src/main/ipc/memory.ts @@ -6,7 +6,7 @@ import { collectMemorySnapshot } from '../memory/collector' import { assertResourceViewVisible, isResourceWindowVisible -} from '../window/resource-view-admission' +} from '../window/visibility/resource-view-admission' import type { ResourceViewAdmission } from '../../shared/resource-view-admission' export function registerMemoryHandlers(store: Store): void { diff --git a/src/main/ipc/native-chat.ts b/src/main/ipc/native-chat.ts index f5f8461e647..1ea5a8d749b 100644 --- a/src/main/ipc/native-chat.ts +++ b/src/main/ipc/native-chat.ts @@ -1,4 +1,4 @@ -import { DESKTOP_READ_WINDOW } from '../native-chat/transcript-watch-contract' +import { DESKTOP_READ_WINDOW } from '../native-chat/transcript-watching/transcript-watch-contract' import { ipcMain, type IpcMainEvent, type WebContents } from 'electron' import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' import type { @@ -7,15 +7,15 @@ import type { } from '../../shared/native-chat/native-chat-types' import { clearNativeChatTranscriptCache } from '../native-chat/transcript-read-cache' import type { ReadTranscriptResult } from '../native-chat/transcript-reader' -import { - subscribeNativeChatTranscript, - readNativeChatTranscriptTail, - type NativeChatTranscriptSubscription, - type SubscribeNativeChatTranscriptArgs -} from '../native-chat/transcript-watch' +import { subscribeNativeChatTranscript } from '../native-chat/transcript-watch' +import { readNativeChatTranscriptTail } from '../native-chat/transcript-tail-reader' +import type { + NativeChatTranscriptSubscription, + SubscribeNativeChatTranscriptArgs +} from '../native-chat/transcript-watching/transcript-watch-contract' import { abortWhenRendererGone } from './renderer-lifetime-abort' import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { openNativeChatTranscript } from '../native-chat/native-chat-open-wake' +import { openNativeChatTranscript } from '../native-chat/transcript-discovery/native-chat-open-wake' export { clearNativeChatTranscriptCache } diff --git a/src/main/ipc/native-notification-delivery.ts b/src/main/ipc/native-notification-delivery.ts index 99d86e4a4d9..11f9c11a3d4 100644 --- a/src/main/ipc/native-notification-delivery.ts +++ b/src/main/ipc/native-notification-delivery.ts @@ -4,8 +4,8 @@ import type { NotificationDispatchResult, NotificationSettings } from '../../shared/notification-settings-types' -import { safelyRevealWindow } from '../window/focus-existing-window' -import { isBackgroundLaunch } from '../window/foreground-activation-policy' +import { safelyRevealWindow } from '../window/activation/focus-existing-window' +import { isBackgroundLaunch } from '../window/activation/foreground-activation-policy' import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' import { parsePaneKey } from '../../shared/workspace-layout/stable-pane-id' import type { buildNotificationOptions } from './notification-options' diff --git a/src/main/ipc/notifications-custom-sound.test.ts b/src/main/ipc/notifications-custom-sound.test.ts deleted file mode 100644 index 5734d78e8cf..00000000000 --- a/src/main/ipc/notifications-custom-sound.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { getLoadSoundHandler, resetNotificationDispatchMocks } from './notifications-test-harness' - -vi.mock('electron', async () => - (await import('./notifications-test-harness')).createElectronModuleMock() -) - -vi.mock('./notification-authorization-status', async () => - (await import('./notifications-test-harness')).createNotificationAuthorizationModuleMock() -) - -vi.mock('./ui', async () => - (await import('./notifications-test-harness')).createTrustedUIRendererModuleMock() -) - -vi.mock('../tray/system-tray', async () => - (await import('./notifications-test-harness')).createSystemTrayModuleMock() -) - -import { registerNotificationHandlers } from './notifications' - -describe('registerNotificationHandlers', () => { - let tempDir: string - - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-03-28T16:00:00Z')) - tempDir = mkdtempSync(join(tmpdir(), 'orca-notification-test-')) - resetNotificationDispatchMocks() - }) - - afterEach(() => { - rmSync(tempDir, { recursive: true, force: true }) - }) - - it('loads allowed custom sound files for preload playback', async () => { - const soundPath = join(tempDir, 'sound.ogg') - writeFileSync(soundPath, Buffer.from([1, 2, 3])) - registerNotificationHandlers({ - getSettings: () => ({ - notifications: { - enabled: true, - agentTaskComplete: true, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: soundPath - } - }) - } as never) - - const handler = getLoadSoundHandler() - await expect(handler({})).resolves.toMatchObject({ - ok: true, - data: new Uint8Array([1, 2, 3]), - mimeType: 'audio/ogg' - }) - }) -}) diff --git a/src/main/ipc/notifications-message-formatting.test.ts b/src/main/ipc/notifications-message-formatting.test.ts index aba396c89d4..6bd6325919a 100644 --- a/src/main/ipc/notifications-message-formatting.test.ts +++ b/src/main/ipc/notifications-message-formatting.test.ts @@ -65,46 +65,4 @@ describe('registerNotificationHandlers', () => { body: 'Claude finished.' }) }) - - it('normalizes custom agent labels and re-bounds multiline assistant previews', async () => { - registerNotificationHandlers({ - getSettings: () => ({ - notifications: { - enabled: true, - agentTaskComplete: true, - terminalBell: false, - suppressWhenFocused: false - } - }) - } as never) - - const longAssistantMessage = `Line one\n\n${'x'.repeat(400)}` - const handler = getDispatchHandler() - expect( - await handler( - {}, - { - source: 'agent-task-complete', - worktreeId: 'repo::wt1', - worktreeLabel: 'feat/notis', - agentType: 'builder\nagent', - agentState: 'done', - agentLastAssistantMessage: longAssistantMessage - } - ) - ).toEqual({ delivered: true }) - - const options = ( - notificationCtorMock.mock.calls as unknown as [{ title: string; body: string }][] - )[0]?.[0] - if (!options) { - throw new Error('Expected notification options') - } - expect(options).toMatchObject({ - title: 'feat/notis - builder agent finished' - }) - expect(options.body).toMatch(/^Line one x+/) - expect(options.body).not.toContain('\n') - expect(options.body.length).toBeLessThanOrEqual(180) - }) }) diff --git a/src/main/ipc/notifications-test-harness.ts b/src/main/ipc/notifications-test-harness.ts index edf956e93b3..1a8ded900ee 100644 --- a/src/main/ipc/notifications-test-harness.ts +++ b/src/main/ipc/notifications-test-harness.ts @@ -131,10 +131,6 @@ export function getOpenSystemSettingsHandler(): (event: unknown) => unknown { return findRegisteredHandler('notifications:openSystemSettings') as (event: unknown) => unknown } -export function getLoadSoundHandler(): (event: unknown) => Promise { - return findRegisteredHandler('notifications:loadSound') as (event: unknown) => Promise -} - export function getResolveSoundPathHandler(): (event: unknown) => unknown { return findRegisteredHandler('notifications:resolveSoundPath') as (event: unknown) => unknown } diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.ts index c8dc097a415..759923097ed 100644 --- a/src/main/ipc/notifications.ts +++ b/src/main/ipc/notifications.ts @@ -14,7 +14,7 @@ import { isNotificationAttentionAcknowledgement } from '../../shared/notificatio import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { readNotificationAuthorizationStatus } from './notification-authorization-status' import { setTrayAttention } from '../tray/system-tray' -import { isMainWindowVisible } from '../window/main-window-visibility' +import { isMainWindowVisible } from '../window/visibility/main-window-visibility' import { activeNotificationsById } from './native-notification-lifecycle' import { deliverNativeNotification } from './native-notification-delivery' import { removeReadMacosNotifications } from './macos-notification-center' diff --git a/src/main/ipc/profiles/orca-profiles.ts b/src/main/ipc/profiles/orca-profiles.ts index 78ee337a66a..62a30b5a677 100644 --- a/src/main/ipc/profiles/orca-profiles.ts +++ b/src/main/ipc/profiles/orca-profiles.ts @@ -1,7 +1,7 @@ import { ipcMain, type WebContents } from 'electron' import type { Store } from '../../persistence/loading-store/store' import { relaunchApp, type AppRelaunchReason } from '../../startup/quit/app-relaunch' -import { quitProcess } from '../../startup/process-quit-request' +import { quitProcess } from '../../startup/quit/process-quit-request' import type { CreateLocalOrcaProfileArgs, CreateLocalOrcaProfileResult, diff --git a/src/main/ipc/pty/delivery/attached-pty-size.ts b/src/main/ipc/pty/delivery/attached-pty-size.ts index 2277d3fa79a..921c364043f 100644 --- a/src/main/ipc/pty/delivery/attached-pty-size.ts +++ b/src/main/ipc/pty/delivery/attached-pty-size.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { ptySizes } from './visibility-state' export type PtyGrid = { cols: number; rows: number } diff --git a/src/main/ipc/pty/host-env/codex-home.ts b/src/main/ipc/pty/host-env/codex-home.ts index 5a41f26e58d..d3ca9e07c0c 100644 --- a/src/main/ipc/pty/host-env/codex-home.ts +++ b/src/main/ipc/pty/host-env/codex-home.ts @@ -3,8 +3,8 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import { isCodexHomeAuthReadyForLaunch, waitForManagedCodexAuthReady -} from '../../../codex-accounts/managed-codex-auth-readiness' -import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' +} from '../../../codex-accounts/credentials/managed-codex-auth-readiness' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import { forgetCodexPaneAccount, getCodexPaneAccount, diff --git a/src/main/ipc/pty/host-env/codex-resume.ts b/src/main/ipc/pty/host-env/codex-resume.ts index 1dd0b13c4fe..c6d961787da 100644 --- a/src/main/ipc/pty/host-env/codex-resume.ts +++ b/src/main/ipc/pty/host-env/codex-resume.ts @@ -5,7 +5,7 @@ import { } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import { SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV } from '../../../../shared/agent-launch/startup/setup-agent-sequencing' import { dropAgentResumeArgvFromCommand } from '../../../../shared/agent-launch/startup/agent-resume-argv-drop' -import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import { dropUnverifiedCodexResumeArgv } from '../../../codex/history/resume/codex-unverified-resume-launch' import type { CodexSessionResumePreparation } from '../../../codex/history/resume/codex-session-resume-home' import { CODEX_RESUME_AUTH_UNAVAILABLE_MESSAGE, codexHomePathsEqual } from './codex-home' diff --git a/src/main/ipc/pty/host-env/fresh-spawn-routing.ts b/src/main/ipc/pty/host-env/fresh-spawn-routing.ts index 1da17da0a69..d5d4bf71e33 100644 --- a/src/main/ipc/pty/host-env/fresh-spawn-routing.ts +++ b/src/main/ipc/pty/host-env/fresh-spawn-routing.ts @@ -1,6 +1,6 @@ import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { beginTerminalInstall } from '../../../workspaces/removal/watcher-removal-gate' export function isClaudeLaunchCommand(command: string | undefined): boolean { diff --git a/src/main/ipc/pty/host-env/omp-launch-environment.ts b/src/main/ipc/pty/host-env/omp-launch-environment.ts index e562c5dd218..b5f76dd598f 100644 --- a/src/main/ipc/pty/host-env/omp-launch-environment.ts +++ b/src/main/ipc/pty/host-env/omp-launch-environment.ts @@ -1,7 +1,7 @@ import { addWslEnvKeys } from '../../../../shared/wsl-env' import { detectExplicitPiAgentKindFromCommand } from '../../../../shared/pi-agent-kind' import { resolveSetupAgentSequenceLaunchCommand } from '../../../../shared/agent-launch/startup/setup-agent-sequencing' -import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment' +import { resolveLoginShellEnvironment } from '../../../startup/shell-environment/login-shell-environment' const OMP_DIRECTORY_ENV_KEYS = [ 'XDG_CONFIG_HOME', diff --git a/src/main/ipc/pty/host-env/saved-resume-admission.ts b/src/main/ipc/pty/host-env/saved-resume-admission.ts index a96c8a5548b..ea38fcd398f 100644 --- a/src/main/ipc/pty/host-env/saved-resume-admission.ts +++ b/src/main/ipc/pty/host-env/saved-resume-admission.ts @@ -21,7 +21,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import { keysMayMatch, terminalConversationKey -} from '../../../native-chat/structured-conversation-key' +} from '../../../native-chat/conversation-adoption/structured-conversation-key' export type ResumeSpawnArgs = { connectionId?: string | null diff --git a/src/main/ipc/pty/host-env/types.ts b/src/main/ipc/pty/host-env/types.ts index b2325de5a67..2faa60b790b 100644 --- a/src/main/ipc/pty/host-env/types.ts +++ b/src/main/ipc/pty/host-env/types.ts @@ -3,7 +3,7 @@ import type { AgentProviderSessionMetadata } from '../../../../shared/agent-sess import type { NetworkProxySettings } from '../../../../shared/network-proxy' import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' import type { ClaudeAccountSelectionTarget } from '../../../claude-accounts/selection/runtime-selection' -import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import type { CodexPaneHomeRoute } from '../../../codex/configuration/homes/codex-pane-account-registry-types' import type { CodexSessionResumePreparation } from '../../../codex/history/resume/codex-session-resume-home' diff --git a/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts b/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts index 0a7d931857d..9a659bd7146 100644 --- a/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts +++ b/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts @@ -1,9 +1,9 @@ import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { getPtyIpc } from '../pty-host-bindings' -import { parseAppSshPtyId } from '../../../providers/ssh-pty-id' -import { claudeDiffPanelMayAutoOpen } from '../../../claude/claude-diff-panel-auto-open' -import { probeRecentClaudeCliVersion } from '../../../claude/claude-hook-event-versions' +import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' +import { claudeDiffPanelMayAutoOpen } from '../../../claude/configuration/claude-diff-panel-auto-open' +import { probeRecentClaudeCliVersion } from '../../../claude/cli-capabilities/claude-hook-event-versions' import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { resolveClaudeCommand } from '../../../codex-cli/command' import { ptyOwnership } from '../provider/ownership-state' diff --git a/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts b/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts index 4e783168de2..e292b849803 100644 --- a/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts +++ b/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts @@ -1,6 +1,6 @@ -import { isClosedPaneFenced } from '../../../persistence/terminal-topology/closed-pane-binding-fence' +import { isClosedPaneFenced } from '../../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' import type { Store } from '../../../persistence/loading-store/store' -import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' /** Refuse closed/reclaimed panes before spawning; a later binding refusal cannot undo a startup command. */ export function refuseClosedPaneSpawn( diff --git a/src/main/ipc/pty/ipc/codex-shared-server.ts b/src/main/ipc/pty/ipc/codex-shared-server.ts index c9ef1b39668..94c331dbfb2 100644 --- a/src/main/ipc/pty/ipc/codex-shared-server.ts +++ b/src/main/ipc/pty/ipc/codex-shared-server.ts @@ -1,6 +1,6 @@ import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { getPtyIpc } from '../pty-host-bindings' -import { parseAppSshPtyId } from '../../../providers/ssh-pty-id' +import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' import { findPaneCodexOnSharedServer, resolveCodexPaneHome diff --git a/src/main/ipc/pty/ipc/inspect.ts b/src/main/ipc/pty/ipc/inspect.ts index bf2a4743ef5..a6b5c6d2d7c 100644 --- a/src/main/ipc/pty/ipc/inspect.ts +++ b/src/main/ipc/pty/ipc/inspect.ts @@ -1,6 +1,6 @@ import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { getPtyIpc } from '../pty-host-bindings' -import { inspectPtyProviderProcessForRenderer } from '../../../providers/pty-process-inspection' +import { inspectPtyProviderProcessForRenderer } from '../../../providers/pty/process-inspection' import { clientOnlyUnverifiableInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' import { getProviderForPty, diff --git a/src/main/ipc/pty/ipc/leaf-move.ts b/src/main/ipc/pty/ipc/leaf-move.ts index cac6f04230f..7cee39f9e93 100644 --- a/src/main/ipc/pty/ipc/leaf-move.ts +++ b/src/main/ipc/pty/ipc/leaf-move.ts @@ -2,12 +2,12 @@ import { getPtyIpc } from '../pty-host-bindings' import type { Store } from '../../../persistence/loading-store/store' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { rekeyMovedPaneOwners } from '../../../runtime/terminal/identity/moved-pane-owner-rekey' -import { commitRelayedPaneMove } from '../../../window/terminal-pane-move-commit-fence' +import { commitRelayedPaneMove } from '../../../window/renderer-relays/terminal-pane-move-commit-fence' import { isTerminalLeafMoveRequest, type TerminalLeafMoveRequest, type TerminalLeafMoveResult -} from '../../../../shared/workspace-layout/terminal-leaf-move' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' /** Durable move first; agent-status and orchestration keys follow only a committed move. */ export async function commitLeafMoveAndRekey( diff --git a/src/main/ipc/pty/ipc/renderer-kill.ts b/src/main/ipc/pty/ipc/renderer-kill.ts index 360f7e76ded..a7b6e6ad92e 100644 --- a/src/main/ipc/pty/ipc/renderer-kill.ts +++ b/src/main/ipc/pty/ipc/renderer-kill.ts @@ -8,7 +8,7 @@ import { getPtyIpc } from '../pty-host-bindings' import type { Store } from '../../../persistence/loading-store/store' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import type { TerminalIntentionalStopKind } from '../../../runtime/terminal/stop/terminal-intentional-stops' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import { ptyIncarnationById } from '../provider/ownership-state' import { diff --git a/src/main/ipc/pty/ipc/session-listing.ts b/src/main/ipc/pty/ipc/session-listing.ts index 83a099fa3d9..e27ea94ad92 100644 --- a/src/main/ipc/pty/ipc/session-listing.ts +++ b/src/main/ipc/pty/ipc/session-listing.ts @@ -1,10 +1,10 @@ import type { ResourceViewAdmission } from '../../../../shared/resource-view-admission' -import { assertResourceViewVisible } from '../../../window/resource-view-admission' +import { assertResourceViewVisible } from '../../../window/visibility/resource-view-admission' import { getPtyIpc } from '../pty-host-bindings' import { PtyProcessListAdmission, visitPtyProcessListingsInBatches -} from '../../../providers/pty-process-list-admission' +} from '../../../providers/pty/process-list-admission' import { ptySessionIdentity, type PtyListedSession, diff --git a/src/main/ipc/pty/ipc/spawn-agent-launch.ts b/src/main/ipc/pty/ipc/spawn-agent-launch.ts index fa5b6e395ef..e3a2568ae33 100644 --- a/src/main/ipc/pty/ipc/spawn-agent-launch.ts +++ b/src/main/ipc/pty/ipc/spawn-agent-launch.ts @@ -1,7 +1,7 @@ import { randomUUID } from 'node:crypto' -import { AgentLaunch } from '../../../../shared/rpc-contract/agent-launch-params' +import { AgentLaunch } from '../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { toAgentLaunchPreferences } from '../../../../shared/agent-launch/choices/agent-launch-preferences' -import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { AgentLaunchTabClosedError } from '../../../../shared/agent-launch/contracts/agent-launch-tab-closed' import { trackRunningAgentLaunchPane } from '../../../agent-launch/agent-launch-pane-attachment' diff --git a/src/main/ipc/pty/ipc/spawn-commit.ts b/src/main/ipc/pty/ipc/spawn-commit.ts index 2225817b67a..7735ea7334c 100644 --- a/src/main/ipc/pty/ipc/spawn-commit.ts +++ b/src/main/ipc/pty/ipc/spawn-commit.ts @@ -8,7 +8,7 @@ import { startupCwdFallbackOutcome } from '../spawn-startup-target' import { commitPtySpawn } from '../spawn-commit-assembly' import type { PtySpawnPaneBinding } from '../spawn-commit-binding' import { spawnCommitBindingOrigin } from '../../../persistence/loading-store/terminal-bindings/pty-binding-span' -import { parseTerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' +import { parseTerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' import { commitPtyWithOpenCodePromptIntent } from '../../../opencode/startup-prompts/opencode-startup-prompt-owner' import { resumeSpawnRefusal, savedResumeResult } from '../host-env/saved-resume-admission' diff --git a/src/main/ipc/pty/ipc/spawn-env.ts b/src/main/ipc/pty/ipc/spawn-env.ts index 034bc8359e6..38e22f94b77 100644 --- a/src/main/ipc/pty/ipc/spawn-env.ts +++ b/src/main/ipc/pty/ipc/spawn-env.ts @@ -4,7 +4,7 @@ import { parseLegacyNumericPaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { isOpaqueRemintedPaneKey } from '../../../../shared/pane-key-alias' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' import { resolvePathEnvKey } from '../../../pty/environment/windows-path-segment-merge' import { routesFreshSpawnsToLocalProvider } from '../host-env/fresh-spawn-routing' diff --git a/src/main/ipc/pty/ipc/spawn-state.ts b/src/main/ipc/pty/ipc/spawn-state.ts index aca96356115..bc2275b79b5 100644 --- a/src/main/ipc/pty/ipc/spawn-state.ts +++ b/src/main/ipc/pty/ipc/spawn-state.ts @@ -2,13 +2,10 @@ import type { PtySpawnSizeSeed } from '../spawn-options-assembly' import type { StartupCwdFallback } from '../../../../shared/startup-cwd-fallback' import type { PtyRegistrationClaim } from '../../../runtime/terminal/records/runtime-terminal-state-records' import type { PaneSpawnOperation } from '../pane/pane-spawn-operation' -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { CodexPaneHomeRoute } from '../../../codex/configuration/homes/codex-pane-account-registry-types' -import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import type { ResumeSpawnAdmission } from '../host-env/saved-resume-admission' import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' diff --git a/src/main/ipc/pty/ipc/spawn-types.ts b/src/main/ipc/pty/ipc/spawn-types.ts index 08bd61db360..399d9489c8c 100644 --- a/src/main/ipc/pty/ipc/spawn-types.ts +++ b/src/main/ipc/pty/ipc/spawn-types.ts @@ -12,7 +12,7 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { TerminalStartupCwdMissingDirFallback } from '../../../../shared/shell/launch/terminal-startup-cwd' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import type { Store } from '../../../persistence/loading-store/store' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { CodexHomePtySpawnedLifecycleArgs, GetSelectedCodexHomePath, diff --git a/src/main/ipc/pty/ipc/write-input.ts b/src/main/ipc/pty/ipc/write-input.ts index a659c9c1bee..030e7acbc76 100644 --- a/src/main/ipc/pty/ipc/write-input.ts +++ b/src/main/ipc/pty/ipc/write-input.ts @@ -2,8 +2,8 @@ import { isTerminalInputPaused } from '../../../runtime/terminal/input/terminal- import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron' import type { PtyRendererDelivery } from '../session' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { isPtyWriteUnavailableError } from '../../../providers/pty-write-unavailable-error' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import { isPtyWriteUnavailableError } from '../../../providers/pty/write-unavailable-error' import { isTerminalInputTooLargeWithDeferredMeasurement, iterateTerminalInputChunks diff --git a/src/main/ipc/pty/pane/adopt-stable.ts b/src/main/ipc/pty/pane/adopt-stable.ts index cc4a57b15a2..5a9a73c9b95 100644 --- a/src/main/ipc/pty/pane/adopt-stable.ts +++ b/src/main/ipc/pty/pane/adopt-stable.ts @@ -1,6 +1,6 @@ import type { PtySpawnOutcome } from '../spawn-outcome' -import { isClosedPaneFenced } from '../../../persistence/terminal-topology/closed-pane-binding-fence' -import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { isClosedPaneFenced } from '../../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' +import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { toSshExecutionHostId, getConnectionExecutionHostId diff --git a/src/main/ipc/pty/pane/agent-session-owners.ts b/src/main/ipc/pty/pane/agent-session-owners.ts index 9e50410df8e..acbdbf6beef 100644 --- a/src/main/ipc/pty/pane/agent-session-owners.ts +++ b/src/main/ipc/pty/pane/agent-session-owners.ts @@ -6,7 +6,7 @@ import type { AgentSessionOwnerBinding } from '../../../../shared/agent-session/ import { ClaimedAgentPtyOwnerRegistry } from '../../../../shared/claimed-agent-pty-owner' import { isPtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { ptyIncarnationById, ptyOwnership } from '../provider/ownership-state' import type { ExecutionHostId } from '../../../../shared/execution-host' import { registeredPtyProviders, tryGetProviderForPty } from '../provider/registry' diff --git a/src/main/ipc/pty/pane/attach-only-view.ts b/src/main/ipc/pty/pane/attach-only-view.ts index 7425a5fd5b7..b2f8fb03032 100644 --- a/src/main/ipc/pty/pane/attach-only-view.ts +++ b/src/main/ipc/pty/pane/attach-only-view.ts @@ -8,11 +8,8 @@ import { markRuntimeOwnedHiddenRendererPty } from '../delivery/pty-hidden-delivery-gate' import { attachingRendererViewPtys } from '../delivery/visibility-state' -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' /** A view with no recorded owner may attach only to its named terminal; main owns fresh starts. */ export async function attachViewWithoutOwner( diff --git a/src/main/ipc/pty/pane/resume-launch-identity.ts b/src/main/ipc/pty/pane/resume-launch-identity.ts index 34603b6057a..4d96de10afd 100644 --- a/src/main/ipc/pty/pane/resume-launch-identity.ts +++ b/src/main/ipc/pty/pane/resume-launch-identity.ts @@ -3,7 +3,7 @@ import { isResumableTuiAgent, normalizeAgentProviderSession } from '../../../../shared/agent-session/lifecycle/agent-session-resume' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' /** Both spawn entry points seed resume identity before the first hook so phone/chat/process readers can address its transcript. */ export function seedResumeLaunchIdentityFromSpawn(args: { diff --git a/src/main/ipc/pty/pane/spawn-registration.test.ts b/src/main/ipc/pty/pane/spawn-registration.test.ts deleted file mode 100644 index 8aaf09841f0..00000000000 --- a/src/main/ipc/pty/pane/spawn-registration.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { afterEach, describe, expect, it, vi, type Mock } from 'vitest' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import type { IPtyProvider, PtySpawnResult } from '../../../providers/pty-provider-contract' -import { ptyIncarnationById, ptyOwnership } from '../provider/ownership-state' -import { TerminalIntentionalStops } from '../../../runtime/terminal/stop/terminal-intentional-stops' -import { admitPtySpawnOwnership, discardUnpersistedPtySpawn } from './spawn-registration' - -type MarkUnverifiable = (ptyId: string, reason: string) => void -const PTY_ID = 'unpersisted-spawn' -const result: PtySpawnResult = { id: PTY_ID, incarnationId: 'inc-1' } - -function providerWhoseShutdown(shutdown: () => Promise): IPtyProvider { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: discard calls only shutdown. - return { shutdown } as unknown as IPtyProvider -} - -describe('discarding a spawn whose binding failed to save', () => { - afterEach(() => { - ptyOwnership.delete(PTY_ID) - ptyIncarnationById.delete(PTY_ID) - }) - - function discard( - shutdown: () => Promise, - runtime: { - markPtyLivenessUnverifiable: Mock - intentionalPtyStops?: TerminalIntentionalStops - } = { markPtyLivenessUnverifiable: vi.fn() } - ): Promise { - admitPtySpawnOwnership(undefined, result) - return discardUnpersistedPtySpawn(providerWhoseShutdown(shutdown), result, runtime).then( - () => runtime - ) - } - - it('keeps tracking the PTY and reads unverifiable when the shutdown fails', async () => { - const runtime = await discard(() => Promise.reject(new Error('shutdown timed out'))) - - expect(ptyOwnership.get(PTY_ID)).toBe(LOCAL_EXECUTION_HOST_ID) - expect(ptyIncarnationById.get(PTY_ID)).toBe('inc-1') - expect(runtime.markPtyLivenessUnverifiable).toHaveBeenCalledWith( - PTY_ID, - expect.stringContaining('shutdown timed out') - ) - }) - - // Unmarked cleanup exits once looked like agent completion and removed the user's tab (QA687). - it('retires the PTY once the host acknowledged the shutdown, as a stop that keeps the tab', async () => { - const intentionalPtyStops = new TerminalIntentionalStops() - const runtime = await discard(() => Promise.resolve(), { - markPtyLivenessUnverifiable: vi.fn(), - intentionalPtyStops - }) - - expect(ptyOwnership.has(PTY_ID)).toBe(false) - expect(runtime.markPtyLivenessUnverifiable).not.toHaveBeenCalled() - expect(intentionalPtyStops.claimExit(PTY_ID, 'inc-1')).toEqual(['replaced']) - }) - - it('leaves a same-id replacement that arrived during the shutdown alone', async () => { - await discard(async () => { - ptyOwnership.set(PTY_ID, 'ssh:successor') - ptyIncarnationById.set(PTY_ID, 'inc-2') - }) - - expect(ptyOwnership.get(PTY_ID)).toBe('ssh:successor') - expect(ptyIncarnationById.get(PTY_ID)).toBe('inc-2') - }) - - it('does not mark a same-id replacement unverifiable when the predecessor shutdown fails', async () => { - const runtime = await discard(async () => { - ptyIncarnationById.set(PTY_ID, 'inc-2') - throw new Error('shutdown response lost') - }) - - expect(ptyIncarnationById.get(PTY_ID)).toBe('inc-2') - expect(runtime.markPtyLivenessUnverifiable).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/pty/pane/spawn-registration.ts b/src/main/ipc/pty/pane/spawn-registration.ts index a9842c737db..550abd9bb5c 100644 --- a/src/main/ipc/pty/pane/spawn-registration.ts +++ b/src/main/ipc/pty/pane/spawn-registration.ts @@ -3,7 +3,8 @@ import type { PtyRegistrationClaim } from '../../../runtime/terminal/records/run import { PaneOwnerContentionError } from './pane-spawn-operation' import type { Store } from '../../../persistence/loading-store/store' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import type { IPtyProvider, PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { isCurrentPtyExit, ptyIncarnationById, diff --git a/src/main/ipc/pty/pane/spawn-reservation.ts b/src/main/ipc/pty/pane/spawn-reservation.ts index 7322fb79d3b..18678927030 100644 --- a/src/main/ipc/pty/pane/spawn-reservation.ts +++ b/src/main/ipc/pty/pane/spawn-reservation.ts @@ -1,5 +1,5 @@ import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { isWorktreeTerminalsSleepingError } from '../../../../shared/workspace-sleep' import type { PtySpawnOutcome } from '../spawn-outcome' import type { PaneSpawnOperation } from './pane-spawn-operation' diff --git a/src/main/ipc/pty/pane/stable-owner.ts b/src/main/ipc/pty/pane/stable-owner.ts index 206f685a886..609ee10af96 100644 --- a/src/main/ipc/pty/pane/stable-owner.ts +++ b/src/main/ipc/pty/pane/stable-owner.ts @@ -6,11 +6,8 @@ import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/s import type { Store } from '../../../persistence/loading-store/store' import { retireTerminalSurfaceFromPersistence } from '../../../runtime/terminal/surface/mobile-session-terminal-persistence-retirement' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { getPtySshConnectionId } from '../provider/registry' import { ptyIncarnationById } from '../provider/ownership-state' import type { ReplacedPaneOwner } from './replaced-pane-owner' diff --git a/src/main/ipc/pty/pane/stable-pane-absence-death-certificate.test.ts b/src/main/ipc/pty/pane/stable-pane-absence-death-certificate.test.ts index b1711b541dd..4e8c60ed47e 100644 --- a/src/main/ipc/pty/pane/stable-pane-absence-death-certificate.test.ts +++ b/src/main/ipc/pty/pane/stable-pane-absence-death-certificate.test.ts @@ -4,7 +4,7 @@ import { withDurableRuntimeStore } from '../../../runtime/orca-runtime-tests/run import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { Store } from '../../../persistence/loading-store/store' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { adoptStablePane } from './adopt-stable' import * as providers from '../provider/registry' diff --git a/src/main/ipc/pty/pane/stable-pane-attach.ts b/src/main/ipc/pty/pane/stable-pane-attach.ts index 53718a602fd..ae42df399e3 100644 --- a/src/main/ipc/pty/pane/stable-pane-attach.ts +++ b/src/main/ipc/pty/pane/stable-pane-attach.ts @@ -5,7 +5,7 @@ import { TerminalHostGoneError, TerminalSessionOwnerUnverifiedError } from '../../../daemon/protocol/daemon-errors' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { keepAbsentPaneBindingForSwap, releaseAbsentPaneOwner } from './absent-pane-owner' import { excludeReplacedPaneOwner } from './replaced-pane-owner' import { PANE_NOT_LIVE_ERROR } from '../../../../shared/pane-attach-only-view' diff --git a/src/main/ipc/pty/pane/terminal-spawn-restore.test.ts b/src/main/ipc/pty/pane/terminal-spawn-restore.test.ts index 08f8647e00e..b71f752a050 100644 --- a/src/main/ipc/pty/pane/terminal-spawn-restore.test.ts +++ b/src/main/ipc/pty/pane/terminal-spawn-restore.test.ts @@ -1,7 +1,7 @@ // verify-15b: a WSL host pane's wake joined the new prompt onto the restored one. import { Terminal } from '@xterm/headless' import { describe, expect, it, vi } from 'vitest' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore' diff --git a/src/main/ipc/pty/pane/terminal-spawn-restore.ts b/src/main/ipc/pty/pane/terminal-spawn-restore.ts index 52254555946..20fdb54401b 100644 --- a/src/main/ipc/pty/pane/terminal-spawn-restore.ts +++ b/src/main/ipc/pty/pane/terminal-spawn-restore.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { pendingByPaneKey, rendererSerializerReadiness } from './serializer-state' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' diff --git a/src/main/ipc/pty/provider/liveness.ts b/src/main/ipc/pty/provider/liveness.ts index a17ad742787..cdd508f2391 100644 --- a/src/main/ipc/pty/provider/liveness.ts +++ b/src/main/ipc/pty/provider/liveness.ts @@ -2,7 +2,7 @@ import type { AgentSessionOwnerBinding } from '../../../../shared/agent-session/ import { agentSessionOwnerBindingsEqual } from '../../../../shared/claimed-agent-pty-owner' import { addNodePtyRecoveryHint } from '../../../daemon/pty-subprocess/node-pty-error-hints' import type { Store } from '../../../persistence/loading-store/store' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { isCurrentPtyExit, ptyIncarnationById, ptyOwnership } from './ownership-state' import { getRelayPtyId, tryGetProviderForPty } from './registry' import { diff --git a/src/main/ipc/pty/provider/local-configure.ts b/src/main/ipc/pty/provider/local-configure.ts index 0126e7d6053..60a2629292e 100644 --- a/src/main/ipc/pty/provider/local-configure.ts +++ b/src/main/ipc/pty/provider/local-configure.ts @@ -12,7 +12,7 @@ import { addOrcaWslInteropEnv, stampWslOrchestrationCompatibilityHost } from '../../../pty/shell-startup/wsl-orca-env' -import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import { buildPtyHostEnv } from '../host-env/assembly' import { stampRuntimeSourceEnv } from '../../../../shared/runtime-source-env' import { getRuntimeSourceStamp } from '../../../runtime/hosts/platform-probe/host-descriptor' diff --git a/src/main/ipc/pty/provider/registry.ts b/src/main/ipc/pty/provider/registry.ts index 23bdde3af13..19491dff9b9 100644 --- a/src/main/ipc/pty/provider/registry.ts +++ b/src/main/ipc/pty/provider/registry.ts @@ -1,6 +1,6 @@ import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { parseAppSshPtyId, toAppSshPtyId, toRelaySshPtyId } from '../../../providers/ssh-pty-id' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import { parseAppSshPtyId, toAppSshPtyId, toRelaySshPtyId } from '../../../../shared/ssh-pty-id' import { ptyOwnership } from './ownership-state' import type { TerminalOscColorQueryReplyColors } from '../../../../shared/terminal/protocol/queries/terminal-osc-color-reply' import { colorQueryReplyColorsEqual } from '../../../../shared/terminal/pty/ingress/pty-owner-color-query-colors' diff --git a/src/main/ipc/pty/provider/shutdown-detect.ts b/src/main/ipc/pty/provider/shutdown-detect.ts index b43928355ac..62d0421f8d3 100644 --- a/src/main/ipc/pty/provider/shutdown-detect.ts +++ b/src/main/ipc/pty/provider/shutdown-detect.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { ptyIncarnationById } from './ownership-state' export async function shutdownProviderAndDetectExit( diff --git a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts index f19b228919b..e8b12909c8b 100644 --- a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts +++ b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts @@ -6,7 +6,7 @@ import { _resetClosedPaneFencesForTests, fencedIfLayoutOwner, partitionsFence -} from '../../persistence/terminal-topology/closed-pane-binding-fence' +} from '../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' import { Store } from '../../persistence/loading-store/store' import { spawnMock } from './pty-ipc-mock-registry' import { setupPtyIpcSuite } from './pty-ipc-test-harness' diff --git a/src/main/ipc/pty/pty-ipc-test-constants.ts b/src/main/ipc/pty/pty-ipc-test-constants.ts index 3118a932c5a..a434b8f2592 100644 --- a/src/main/ipc/pty/pty-ipc-test-constants.ts +++ b/src/main/ipc/pty/pty-ipc-test-constants.ts @@ -2,7 +2,7 @@ import { it, vi, type Mock } from 'vitest' import { join, posix } from 'node:path' import { getBundledLauncherPath } from '../../cli/packaged-assets/bundled-cli-launcher-path' -import { resolveWindowsShellLaunchArgs } from '../../providers/windows-shell-args' +import { resolveWindowsShellLaunchArgs } from '../../providers/shell-launch/windows/shell-args' export type PlatformGatedTest = ( name: string, diff --git a/src/main/ipc/pty/runtime/attach-hermes-mailbox.test.ts b/src/main/ipc/pty/runtime/attach-hermes-mailbox.test.ts deleted file mode 100644 index 0560479dd33..00000000000 --- a/src/main/ipc/pty/runtime/attach-hermes-mailbox.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import '../../../runtime/rpc/unused-default-rpc-methods.test-fixture' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { settledWriteStub } from '../../../providers/settled-pty-write-stub' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' -import { createRootDispatch } from '../../../runtime/orchestration/db/root-dispatch-test-fixture' -import { - createRuntime, - PANE_KEY, - PTY_ID, - TERMINAL_HANDLE -} from '../../../runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness' -import { ptySizes } from '../delivery/visibility-state' -import { getLocalPtyProvider, setLocalPtyProvider } from '../provider/registry' -import { attachPtyFromRuntimeController, getSizeFromRuntimeController } from './operations' -import type { PtyRuntimeControllerDeps } from './controller-deps' - -const originalProvider = getLocalPtyProvider() - -afterEach(() => { - setLocalPtyProvider(originalProvider) - ptySizes.delete(PTY_ID) - vi.useRealTimers() -}) - -describe('mail to a Hermes terminal attached without a renderer', () => { - it.each([ - ['status', '─ ready │ grok 4.7 │ 150k tokens\r\n❯', true], - ['reply', '─ ready │ grok 4.7 │ 150k tokens\r\n❯', true], - ['draft', '─ ready │ grok 4.7 │ 150k tokens\r\n❯ unsent draft', false], - ['busy', '─ thinking │ grok 4.7 │ 150k tokens\r\n❯ Ctrl+C to interrupt…', false] - ] as const)( - 'handles %s mail after attach without submitting a draft or busy composer', - async (kind, screen, ready) => { - vi.useFakeTimers() - const db = new OrchestrationDb(':memory:') - try { - const { runtime } = createRuntime(db, { headless: true, launchAgent: 'hermes' }) - const write = vi.fn((_id: string, data: string) => { - if (data.includes('You have')) { - runtime.onPtyData( - PTY_ID, - '\x1b]1;✓ Run Orca dispatched worker …\x07\x1b]2;✓ Run Orca dispatched worker … · grok-4.7 · ~/workspace\x07', - Date.now() - ) - } - return true - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach reads only this provider's attach method. - const provider = { - attach: async () => ({ - id: PTY_ID, - isReattach: true, - snapshot: screen, - snapshotCols: 120, - snapshotRows: 40 - }) - } as unknown as IPtyProvider - setLocalPtyProvider(provider) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: () => true, - getForegroundProcess: async () => 'hermes', - getSize: getSizeFromRuntimeController - }) - const run = db.createRun({ - objective: 'wake attached worker', - coordinatorHandle: 'term_coordinator', - coordinatorPaneKey: 'coordinator:leaf' - }) - const task = db.createTask({ spec: 'Wait for guidance', runId: run.id }) - const dispatch = createRootDispatch(db, task.id, TERMINAL_HANDLE, PANE_KEY) - const mailbox = `dispatch:${dispatch.id}` - const message = - kind === 'reply' - ? db.answerQuestion({ - messageId: db.createQuestion({ - runId: run.id, - dispatchId: dispatch.id, - askerHandle: TERMINAL_HANDLE, - question: 'Ready?' - }).message.id, - runId: run.id, - consumerGeneration: run.consumer_generation, - body: 'Continue' - }).message - : db.insertMessage({ - from: 'term_coordinator', - to: mailbox, - subject: 'Continue', - runId: run.id - }) - - // Only attach and restored output: no renderer spawn or resize populates the size cache. - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach needs runtime; its delivery callbacks are optional. - const deps = { runtime } as unknown as PtyRuntimeControllerDeps - expect(await attachPtyFromRuntimeController(deps, PTY_ID)).toBe(true) - expect(ptySizes.get(PTY_ID)).toEqual({ cols: 120, rows: 40 }) - await runtime.serializeMainTerminalBuffer(PTY_ID) - runtime.notifyMessageArrived(mailbox, 'status') - await vi.advanceTimersByTimeAsync(1000) - - if (ready) { - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - expect(db.getMessageById(message.id)?.delivered_at).toEqual(expect.any(String)) - } else { - expect(write).not.toHaveBeenCalled() - expect(db.getMessageById(message.id)?.delivered_at).toBeNull() - } - } finally { - db.close() - } - } - ) -}) diff --git a/src/main/ipc/pty/runtime/attach-quiet-agent-mailbox.test.ts b/src/main/ipc/pty/runtime/attach-quiet-agent-mailbox.test.ts deleted file mode 100644 index 3dab1eea59c..00000000000 --- a/src/main/ipc/pty/runtime/attach-quiet-agent-mailbox.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import '../../../runtime/rpc/unused-default-rpc-methods.test-fixture' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { settledWriteStub } from '../../../providers/settled-pty-write-stub' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' -import { createRootDispatch } from '../../../runtime/orchestration/db/root-dispatch-test-fixture' -import { - createRuntime, - PANE_KEY, - PTY_ID, - TERMINAL_HANDLE -} from '../../../runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness' -import { ptySizes } from '../delivery/visibility-state' -import { getLocalPtyProvider, setLocalPtyProvider } from '../provider/registry' -import { attachPtyFromRuntimeController, getSizeFromRuntimeController } from './operations' -import type { PtyRuntimeControllerDeps } from './controller-deps' - -const originalProvider = getLocalPtyProvider() - -afterEach(() => { - setLocalPtyProvider(originalProvider) - ptySizes.delete(PTY_ID) - vi.useRealTimers() -}) - -const HERMES_READY = - '\x1b]2;\u2713 Coordinate dispatched worker \u2026 \u00b7 gpt-6.1-sol \u00b7 ~/ws\x07' + - '\u2500 ready \u2502 gpt 6.1 sol \u2502 7k/500k \u2502 4m 45s\r\n\u276f' -const RULE = '\u2500'.repeat(40) -const CLINE_READY = `${RULE}\r\n\u276f What can I do for you?\r\n${RULE}\r\n\u25cb Plan \u25cf Act (Tab)` - -async function mailAfterQuietAttach( - agent: 'hermes' | 'cline', - snapshot: string, - afterAttach: (runtime: ReturnType['runtime']) => Promise -): Promise<{ writes: string[]; delivered: boolean }> { - vi.useFakeTimers() - const db = new OrchestrationDb(':memory:') - try { - const { runtime } = createRuntime(db, { headless: true, launchAgent: agent }) - const write = vi.fn((_id: string, _data: string) => true) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach reads only this provider's attach method. - const provider = { - attach: async () => ({ - id: PTY_ID, - isReattach: true, - snapshot, - snapshotCols: 120, - snapshotRows: 40 - }) - } as unknown as IPtyProvider - setLocalPtyProvider(provider) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: () => true, - getForegroundProcess: async () => agent, - getSize: getSizeFromRuntimeController - }) - const run = db.createRun({ - objective: 'wake quiet worker', - coordinatorHandle: 'term_coordinator', - coordinatorPaneKey: 'coordinator:leaf' - }) - const task = db.createTask({ spec: 'Wait for guidance', runId: run.id }) - const dispatch = createRootDispatch(db, task.id, TERMINAL_HANDLE, PANE_KEY) - const mailbox = `dispatch:${dispatch.id}` - const message = db.insertMessage({ - from: 'term_coordinator', - to: mailbox, - subject: 'Continue', - runId: run.id - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach needs runtime; its delivery callbacks are optional. - const deps = { runtime } as unknown as PtyRuntimeControllerDeps - expect(await attachPtyFromRuntimeController(deps, PTY_ID)).toBe(true) - await runtime.serializeMainTerminalBuffer(PTY_ID) - await afterAttach(runtime) - runtime.notifyMessageArrived(mailbox, 'status') - await vi.advanceTimersByTimeAsync(60_000) - return { - writes: write.mock.calls.map(([, data]) => data), - delivered: typeof db.getMessageById(message.id)?.delivered_at === 'string' - } - } finally { - db.close() - } -} - -describe('mail to a quiet idle agent after a runtime restart', () => { - // Real Hermes 0.23 writes its OSC title only on a state change, so a worker idle before the - // restart sends no title after reattach; only its ready screen and seeded title are known. - it('types and submits the pointer to Hermes without a fresh title', async () => { - expect(await mailAfterQuietAttach('hermes', HERMES_READY, async () => {})).toEqual({ - writes: [expect.stringContaining('You have 1 orchestration message'), '\r'], - delivered: true - }) - }) - - // A quiet-gated ready rule must still settle once a redraw soon after attach has gone quiet. - it('submits to Cline once its ready screen is quiet after a redraw', async () => { - const result = await mailAfterQuietAttach('cline', CLINE_READY, async (runtime) => { - await vi.advanceTimersByTimeAsync(2_000) - runtime.onPtyData(PTY_ID, '\x1b[H', Date.now()) - }) - expect(result).toEqual({ - writes: [expect.stringContaining('You have 1 orchestration message'), '\r'], - delivered: true - }) - }) -}) diff --git a/src/main/ipc/pty/runtime/controller-deps.ts b/src/main/ipc/pty/runtime/controller-deps.ts index f8b0421a3b0..129abceeccc 100644 --- a/src/main/ipc/pty/runtime/controller-deps.ts +++ b/src/main/ipc/pty/runtime/controller-deps.ts @@ -1,7 +1,7 @@ import type { PtyRendererDelivery } from '../session' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import type { Store } from '../../../persistence/loading-store/store' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { TerminalStartupCwdMissingDirFallback } from '../../../../shared/shell/launch/terminal-startup-cwd' import type { diff --git a/src/main/ipc/pty/runtime/inventory-operations.ts b/src/main/ipc/pty/runtime/inventory-operations.ts index 5a4880e82f5..9dcc89f4eb9 100644 --- a/src/main/ipc/pty/runtime/inventory-operations.ts +++ b/src/main/ipc/pty/runtime/inventory-operations.ts @@ -1,7 +1,7 @@ import { getPtyIdsForHost } from '../provider/ownership-state' import { getProvider, localProvider, registeredPtyProviders } from '../provider/registry' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' import type { PtyRuntimeControllerDeps } from './controller-deps' function markSshInventoryUnverifiable( diff --git a/src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts b/src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts deleted file mode 100644 index d85f9585a08..00000000000 --- a/src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { stopRendererOwnedPty, type PtyKillIpcDeps } from '../ipc/renderer-kill' -import { finishPtyShutdown } from '../provider/liveness' -import { ptyIncarnationById, ptyOwnership } from '../provider/ownership-state' -import { getLocalPtyProvider, setLocalPtyProvider } from '../provider/registry' -import type { PtyRuntimeControllerDeps } from './controller-deps' -import { stopAndWaitPtyFromRuntimeController } from './kill' - -const PTY_ID = 'respawned-pty' - -function providerWhose(duringShutdown: () => void, listed: { id: string }[]): IPtyProvider { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the stops call only shutdown and listProcesses. - return { - shutdown: async () => duringShutdown(), - listProcesses: async () => listed - } as unknown as IPtyProvider -} - -function harness() { - const runtime = { - markPtyStopRequested: vi.fn(), - markPtyLivenessUnverifiable: vi.fn(), - markPtyLivenessLive: vi.fn(), - onPtyExit: vi.fn() - } - const ports = { - runtime, - getLocalPtyProviderStartupPromise: () => undefined, - shutdownProviderAndDetectExit: async (provider: IPtyProvider, id: string) => { - await provider.shutdown(id, { immediate: true }) - return false - }, - rememberSyntheticKillExit: vi.fn(), - sendPtyExitToRenderer: vi.fn(), - finishPtyShutdown, - retiredRejectedPtyIds: new Map() - } - return { runtime, ports } -} - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the stops read only these ports and an optional store. -const asControllerDeps = (ports: unknown) => ports as PtyRuntimeControllerDeps -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the tab-close stop reads only these ports and an optional store. -const asKillIpcDeps = (ports: unknown) => ports as PtyKillIpcDeps - -const original = getLocalPtyProvider() -afterEach(() => { - setLocalPtyProvider(original) - ptyOwnership.delete(PTY_ID) - ptyIncarnationById.delete(PTY_ID) -}) - -describe('a stop whose shutdown lands after a same-id respawn', () => { - function respawn(): void { - ptyOwnership.set(PTY_ID, LOCAL_EXECUTION_HOST_ID) - ptyIncarnationById.set(PTY_ID, 'inc-respawn') - } - function start(): ReturnType { - setLocalPtyProvider(providerWhose(respawn, [{ id: PTY_ID }])) - ptyOwnership.set(PTY_ID, LOCAL_EXECUTION_HOST_ID) - ptyIncarnationById.set(PTY_ID, 'inc-stopped') - return harness() - } - - function expectRespawnUntouched({ runtime, ports }: ReturnType): void { - expect(ptyOwnership.get(PTY_ID)).toBe(LOCAL_EXECUTION_HOST_ID) - expect(ptyIncarnationById.get(PTY_ID)).toBe('inc-respawn') - expect(runtime.onPtyExit).not.toHaveBeenCalled() - expect(ports.sendPtyExitToRenderer).not.toHaveBeenCalled() - } - - it('reports the listed respawn live after a stop-and-wait', async () => { - const h = start() - await expect( - stopAndWaitPtyFromRuntimeController(asControllerDeps(h.ports), PTY_ID) - ).resolves.toBe(false) - expect(h.runtime.markPtyLivenessLive).toHaveBeenCalledWith(PTY_ID) - expectRespawnUntouched(h) - }) - - it('leaves the respawn alone after a renderer tab close', async () => { - const h = start() - await stopRendererOwnedPty(asKillIpcDeps(h.ports), { id: PTY_ID }) - expectRespawnUntouched(h) - }) -}) - -describe('a stop of a PTY whose incarnation was stamped mid-stop', () => { - // Owner reconciliation can discover this same process's incarnation while shutdown is pending. - function start(): ReturnType { - setLocalPtyProvider(providerWhose(() => ptyIncarnationById.set(PTY_ID, 'inc-same'), [])) - ptyOwnership.set(PTY_ID, LOCAL_EXECUTION_HOST_ID) - return harness() - } - - function expectRetired({ ports }: ReturnType): void { - expect(ptyOwnership.has(PTY_ID)).toBe(false) - expect(ports.sendPtyExitToRenderer).toHaveBeenCalledWith( - expect.objectContaining({ id: PTY_ID }) - ) - } - - it('retires it after a renderer tab close', async () => { - const h = start() - await stopRendererOwnedPty(asKillIpcDeps(h.ports), { id: PTY_ID }) - expectRetired(h) - }) -}) diff --git a/src/main/ipc/pty/runtime/kill.ts b/src/main/ipc/pty/runtime/kill.ts index 5a4265aea40..5710e582161 100644 --- a/src/main/ipc/pty/runtime/kill.ts +++ b/src/main/ipc/pty/runtime/kill.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import { isCurrentPtyExit, ptyOwnership, ptyIncarnationById } from '../provider/ownership-state' import { diff --git a/src/main/ipc/pty/runtime/operations.ts b/src/main/ipc/pty/runtime/operations.ts index 2c8d627c2d8..9df8a743473 100644 --- a/src/main/ipc/pty/runtime/operations.ts +++ b/src/main/ipc/pty/runtime/operations.ts @@ -1,6 +1,6 @@ import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' import { ptyOwnership } from '../provider/ownership-state' import { isRendererViewShowingPty, ptySizes } from '../delivery/visibility-state' @@ -9,7 +9,7 @@ import { hideRuntimeOwnedRendererDelivery } from './spawn-hidden-delivery' import { seedAttachedRuntimeTerminal } from './seed-attached-runtime-terminal' import { rendererSerializerReadiness } from '../pane/serializer-state' import { getProviderForPty, localProvider, resolvePtyExecutionHost } from '../provider/registry' -import { inspectPtyProviderProcess } from '../../../providers/pty-process-inspection' +import { inspectPtyProviderProcess } from '../../../providers/pty/process-inspection' import type { PtyRuntimeControllerDeps } from './controller-deps' import { writeRefused, diff --git a/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts b/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts index e60f68e1f56..fa1c3b54c47 100644 --- a/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts +++ b/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { commitRuntimeAttachedPtySize, type PtyGrid } from '../delivery/attached-pty-size' import { ptySizes } from '../delivery/visibility-state' diff --git a/src/main/ipc/pty/runtime/spawn-commit-response.ts b/src/main/ipc/pty/runtime/spawn-commit-response.ts index 2ea9dcfc435..6cb308a5133 100644 --- a/src/main/ipc/pty/runtime/spawn-commit-response.ts +++ b/src/main/ipc/pty/runtime/spawn-commit-response.ts @@ -1,6 +1,6 @@ import type { RuntimePtySpawnState } from './spawn-state' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' type RuntimeResumeOutcomeState = Pick< RuntimePtySpawnState, diff --git a/src/main/ipc/pty/runtime/spawn-options.ts b/src/main/ipc/pty/runtime/spawn-options.ts index 8deecb90019..d74994c375b 100644 --- a/src/main/ipc/pty/runtime/spawn-options.ts +++ b/src/main/ipc/pty/runtime/spawn-options.ts @@ -1,7 +1,8 @@ -import type { IPtyProvider, PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' import { makePaneKey, isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { routesFreshSpawnsToLocalProvider, beginPtySpawnForWorktree diff --git a/src/main/ipc/pty/runtime/spawn-preflight.ts b/src/main/ipc/pty/runtime/spawn-preflight.ts index 750ceb88d58..7707a63e2bb 100644 --- a/src/main/ipc/pty/runtime/spawn-preflight.ts +++ b/src/main/ipc/pty/runtime/spawn-preflight.ts @@ -1,7 +1,7 @@ import { withClaudeProfileTerminalEnv } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' -import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' import { getProvider } from '../provider/registry' import { diff --git a/src/main/ipc/pty/runtime/spawn-state.ts b/src/main/ipc/pty/runtime/spawn-state.ts index 6ba02a090ec..f2f649cd9df 100644 --- a/src/main/ipc/pty/runtime/spawn-state.ts +++ b/src/main/ipc/pty/runtime/spawn-state.ts @@ -5,19 +5,16 @@ import type { PtyRegistrationClaim } from '../../../runtime/terminal/records/run import type { PaneSpawnOperation } from '../pane/pane-spawn-operation' import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' import type { SpawnIntent } from '../../../../shared/terminal/pty/admission/spawn-admission-contract' -import type { - IPtyProvider, - PtySpawnOptions, - PtySpawnResult -} from '../../../providers/pty-provider-contract' +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { CodexPaneHomeRoute } from '../../../codex/configuration/homes/codex-pane-account-registry-types' -import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' import type { StablePaneOwner } from '../pane/stable-owner' import type { PaneSpawnReservation } from '../pane/spawn-reservation' import type { AdoptStablePaneResult } from '../ipc/spawn-types' import type { PtyBindingSourceExpectation } from '../../../persistence/loading-store/store' -import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' import type { ResumeSpawnAdmission } from '../host-env/saved-resume-admission' import type { PtyRuntimeControllerDeps } from './controller-deps' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' @@ -31,7 +28,7 @@ import type { AgentSessionSurfaceBinding } from '../../../../shared/agent-session/agent-session-host-authority' import { localProvider } from '../provider/registry' -import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import type { StartupCwdFallback } from '../../../../shared/startup-cwd-fallback' import type { TerminalWorkspaceLaunchScope } from '../../../runtime/orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' diff --git a/src/main/ipc/pty/session.ts b/src/main/ipc/pty/session.ts index 755a129cec0..379126d5536 100644 --- a/src/main/ipc/pty/session.ts +++ b/src/main/ipc/pty/session.ts @@ -2,7 +2,7 @@ import type { BrowserWindow, WebContents } from 'electron' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import type { Store } from '../../persistence/loading-store/store' import type { GlobalSettings } from '../../../shared/global-settings-types' -import type { IPtyProvider } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' import type { PtyModelRestoreReason } from '../../../shared/terminal/replay/pty-model-restore-marker' import type { PtyDeliveryWriteOff, diff --git a/src/main/ipc/pty/spawn-agent-launch-plugin-hook.ts b/src/main/ipc/pty/spawn-agent-launch-plugin-hook.ts index 26177eee322..b8850dbc3f8 100644 --- a/src/main/ipc/pty/spawn-agent-launch-plugin-hook.ts +++ b/src/main/ipc/pty/spawn-agent-launch-plugin-hook.ts @@ -3,7 +3,7 @@ import { isRestoreSpawnIntent } from '../../../shared/terminal/pty/admission/spa import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { workspaceKindForWorktreeId } from '../../../shared/agent-launch/contracts/workspace-launch-kind' import { pluginHookWanted, runPluginHook } from '../../plugins/hooks/plugin-hook-dispatch' -import { assertLegacyAiVaultResumeCommandAllowed } from '../../ai-vault/structured-session-ownership' +import { assertLegacyAiVaultResumeCommandAllowed } from '../../ai-vault/structured-sessions/structured-session-ownership' import { addWslEnvKeys } from '../../../shared/wsl-env' type AgentSpawnArgs = { diff --git a/src/main/ipc/pty/spawn-commit-assembly.ts b/src/main/ipc/pty/spawn-commit-assembly.ts index 09df9060ebe..cfe09a9d4d3 100644 --- a/src/main/ipc/pty/spawn-commit-assembly.ts +++ b/src/main/ipc/pty/spawn-commit-assembly.ts @@ -1,6 +1,6 @@ import { readTerminalStartFailure } from '../../../shared/terminal/pty/lifecycle/terminal-start-failure' import type { PtySpawnSizeSeed } from './spawn-options-assembly' -import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import type { AgentSessionClaimedSpawnResult } from '../../../shared/agent-session/agent-session-host-authority' import type { GlobalSettings } from '../../../shared/global-settings-types' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' @@ -8,9 +8,10 @@ import type { Store, PtyBindingSourceExpectation } from '../../persistence/loadi import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import type { PtyRegistrationClaim } from '../../runtime/terminal/records/runtime-terminal-state-records' import { markNativeWindowsConptyPty } from '../../runtime/terminal/output/terminal-model-query-authority' -import type { IPtyProvider, PtySpawnResult } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import type { CodexPaneHomeRoute } from '../../codex/configuration/homes/codex-pane-account-registry-types' -import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' import type { PtySpawnTiming } from './pty-spawn-timing' import type { CodexHomePtySpawnedLifecycleArgs } from './host-env/types' import { diff --git a/src/main/ipc/pty/spawn-commit-binding.ts b/src/main/ipc/pty/spawn-commit-binding.ts index 05a6cd7b381..a02ea98fc6c 100644 --- a/src/main/ipc/pty/spawn-commit-binding.ts +++ b/src/main/ipc/pty/spawn-commit-binding.ts @@ -2,7 +2,8 @@ import type { Store } from '../../persistence/loading-store/store' import type { PersistPtyBindingArgs } from '../../persistence/loading-store/terminal-bindings/pty-binding-persistence' import { createTerminalSessionStateSaveFailureMessage } from '../../../shared/workspace-session/terminal-session-state-save-failure' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import type { IPtyProvider, PtySpawnResult } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import { PaneOwnerContentionError, type AbsentPaneBinding } from './pane/pane-spawn-operation' import { persistFreshPaneBinding } from './pane/fresh-pane-binding' import { swapReplacedPaneBinding } from './pane/pane-owner-replacement' diff --git a/src/main/ipc/pty/spawn-commit-publication.ts b/src/main/ipc/pty/spawn-commit-publication.ts index e7ea0595e92..92df926a6c8 100644 --- a/src/main/ipc/pty/spawn-commit-publication.ts +++ b/src/main/ipc/pty/spawn-commit-publication.ts @@ -1,7 +1,7 @@ import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { clearMigrationUnsupportedPtysForPaneKey } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { registerPty } from '../../memory/pty-registry' -import type { PtySpawnResult } from '../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import { codexReattachedHomeRouteField, recordCodexPaneAccountForSpawn diff --git a/src/main/ipc/pty/spawn-execute-failure.ts b/src/main/ipc/pty/spawn-execute-failure.ts index 6b7ba6fbd9d..70a15f9d3a4 100644 --- a/src/main/ipc/pty/spawn-execute-failure.ts +++ b/src/main/ipc/pty/spawn-execute-failure.ts @@ -1,5 +1,5 @@ import type { PtyRegistrationClaim } from '../../runtime/terminal/records/runtime-terminal-state-records' -import type { PtySpawnResult } from '../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { classifyError } from '../../telemetry/classify-error' import { track } from '../../telemetry/client' diff --git a/src/main/ipc/pty/spawn-execute.ts b/src/main/ipc/pty/spawn-execute.ts index fe9fd40396a..47d480f7c27 100644 --- a/src/main/ipc/pty/spawn-execute.ts +++ b/src/main/ipc/pty/spawn-execute.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import { ptyIncarnationById } from './provider/ownership-state' import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' import { diff --git a/src/main/ipc/pty/spawn-host-env.ts b/src/main/ipc/pty/spawn-host-env.ts index 34f34419955..51d4d8129ea 100644 --- a/src/main/ipc/pty/spawn-host-env.ts +++ b/src/main/ipc/pty/spawn-host-env.ts @@ -11,9 +11,9 @@ import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/c import { awaitExplicitAgentPluginGuestReadiness } from '../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness' import { ensureCodexStateDbBackfillRecoveryStarted } from '../../codex/history/index/codex-state-db-backfill-recovery' import type { CodexSessionResumePreparation } from '../../codex/history/resume/codex-session-resume-home' -import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' import { isSafePtySessionId } from '../../daemon/sessions/pty-session-id' -import type { IPtyProvider } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' import { stampWslOrchestrationCompatibilityHost } from '../../pty/shell-startup/wsl-orca-env' import { getRuntimeSourceStamp } from '../../runtime/hosts/platform-probe/host-descriptor' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' diff --git a/src/main/ipc/pty/spawn-options-assembly.ts b/src/main/ipc/pty/spawn-options-assembly.ts index 43724648de1..2715d717136 100644 --- a/src/main/ipc/pty/spawn-options-assembly.ts +++ b/src/main/ipc/pty/spawn-options-assembly.ts @@ -11,8 +11,8 @@ import { LEGACY_TERMINAL_SHIM_REMOTE_ENV_KEYS } from '../../pty/shell-startup/le import { PI_PROCESS_OWNER_ENV_KEYS } from '../../pty/shell-startup/pi-process-owner-env' import { planCodexNoDaemonLaunch } from '../../pty/shell-startup/codex-no-daemon-launch-command' import { applyAgentWorkspaceTrustToSpawn } from '../../agent-launch/trust/agent-workspace-trust-spawn' -import type { PtySpawnOptions } from '../../providers/pty-provider-contract' -import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' +import type { PtySpawnOptions } from '../../providers/pty/provider-contract' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' import { getStartupTerminalIngressIntent } from '../terminal-startup-color-query-replies' import { CODEX_HOME_ENV_KEYS } from './host-env/codex-home' import { diff --git a/src/main/ipc/pty/spawn-outcome.ts b/src/main/ipc/pty/spawn-outcome.ts index f9f04bd30bf..76fdd10ea11 100644 --- a/src/main/ipc/pty/spawn-outcome.ts +++ b/src/main/ipc/pty/spawn-outcome.ts @@ -8,7 +8,7 @@ import type { AdoptStablePaneResult } from './ipc/spawn-types' import type { StartupCwdFallback } from '../../../shared/startup-cwd-fallback' import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { StablePaneOwner } from './pane/stable-owner' -import type { PtySpawnResult } from '../../providers/pty-provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' /** One host result; reply adapters never decide how the owning operation settles. */ export type PtySpawnOutcome = { diff --git a/src/main/ipc/pty/spawn-pane-coordinates.ts b/src/main/ipc/pty/spawn-pane-coordinates.ts index 8c7fb062bc1..0fe4de6d343 100644 --- a/src/main/ipc/pty/spawn-pane-coordinates.ts +++ b/src/main/ipc/pty/spawn-pane-coordinates.ts @@ -1,5 +1,5 @@ import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { makePaneSpawnReservationKey } from './pane/spawn-reservation' type PtySpawnPaneCoordinates = { diff --git a/src/main/ipc/pty/spawn-pane-env.ts b/src/main/ipc/pty/spawn-pane-env.ts index 60fb748d041..6ab715e0f8e 100644 --- a/src/main/ipc/pty/spawn-pane-env.ts +++ b/src/main/ipc/pty/spawn-pane-env.ts @@ -5,7 +5,7 @@ import { } from '../../../shared/jcode-runtime-dir' import { applyScrubSafeAgentEnvAliases } from '../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' export type PtySpawnPane = { paneKey: string diff --git a/src/main/ipc/pty/spawn-startup-target.ts b/src/main/ipc/pty/spawn-startup-target.ts index 56e85e89948..9fb625ab379 100644 --- a/src/main/ipc/pty/spawn-startup-target.ts +++ b/src/main/ipc/pty/spawn-startup-target.ts @@ -10,7 +10,7 @@ import { } from '../../../shared/shell/launch/terminal-startup-cwd' import type { TerminalWorkspaceLaunchScope } from '../../runtime/orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' import { isWslUncPath, toWindowsWslPath } from '../../../shared/wsl-paths' -import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' +import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' import { resolveWslSessionContext } from '../../daemon/pty-subprocess/wsl-session-context' import { resolvePlainTerminalWorkspace, @@ -18,12 +18,13 @@ import { type LaunchScopeRuntimeStore } from '../../workspaces/execution-host/local-project-runtime-resolution' import { resolveLocalPtyOptions } from '../../workspaces/execution-host/local-project-runtime-pty-options' -import type { PtySpawnOptions, PtySpawnResult } from '../../providers/pty-provider-contract' +import type { PtySpawnOptions } from '../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import { holdPassiveRestoreOfStoppedWslDistro, wslHoldReadAnchor as wslHoldReadAnchorNow } from '../../daemon/providers/wsl/daemon-wsl-passive-restore-hold' -import { normalizeWindowsTerminalCwd } from '../../providers/windows-shell-args' +import { msysDrivePathToWindows } from '../../../shared/cross-platform-path' import { wslUncDirectoryExistsAsync } from '../../wsl/filesystem/unc-path-access' import { getCodexSelectionTargetForPty } from './host-env/codex-home' import { probeLocalStartupCwdDirectory } from './host-env/startup-cwd-directory-exists' @@ -240,7 +241,7 @@ async function resolveStartupCwdWithFallback( onFallbackToWorkspaceRoot?: () => void ): TerminalStartupCwdMissingDirFallback => ({ directoryExists: (path) => { - const probePath = process.platform === 'win32' ? normalizeWindowsTerminalCwd(path) : path + const probePath = process.platform === 'win32' ? msysDrivePathToWindows(path) : path const verdict = startupWslContext && path === initiallyResolvedStartupCwd ? wslStartupCwdExists diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 7bf4a77b0e8..eef112f8d2d 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -10,7 +10,7 @@ import type { Store } from '../../persistence/loading-store/store' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import type { StatsCollector } from '../../stats/collector' import { registerFilesystemHandlers } from '../filesystem/filesystem' -import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/execution/commit-message-agent-environment' import { registerFilesystemWatcherHandlers } from '../filesystem/watchers/filesystem-watcher-handlers' import { registerGitHubHandlers } from '../source-control/github' import { registerGitLabHandlers } from '../source-control/gitlab' @@ -78,16 +78,14 @@ import { registerMiniMaxCredentialsHandlers } from '../minimax-credentials' import { registerZcodePlanCredentialsHandlers } from '../zcode-plan-credentials' import { registerGrokAccountHandlers } from '../grok-accounts' import { registerCursorAccountHandlers } from '../cursor-accounts' -import { registerUpdaterHandlers } from '../../window/attach-main-window-services' -import { - registerClipboardHandlers, - setTrustedClipboardRendererWebContentsId -} from '../../window/clipboard-ipc-handlers' +import { registerUpdaterHandlers } from '../../updater/lifecycle/main-window-updater' +import { registerClipboardHandlers } from '../../window/clipboard/clipboard-ipc-handlers' +import { setTrustedClipboardRendererWebContentsId } from '../../window/clipboard/clipboard-ipc-sender-trust' import { isDashboardPopoutRenderer } from '../../window/dashboard-popout-window' import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' import type { CodexAccountService } from '../../codex-accounts/service' import type { ClaudeAccountService } from '../../claude-accounts/service' -import type { AutomationService } from '../../automations/service' +import type { AutomationService } from '../../automations/automation-service' import type { AgentAwakeService } from '../../power/agent-awake-service' import type { CrashReportStore } from '../../crash-reporting/reports/crash-report-store' import type { KeybindingService } from '../../keybindings/keybinding-service' @@ -101,15 +99,15 @@ import { prepareRuntimeAiVaultSessionResume, resolveRuntimeAiVaultSessionTitles, scanRuntimeAiVaultSessions -} from '../../ai-vault/runtime-session-scanner' -import { callRuntimeSessionSearch } from '../../ai-vault/runtime-session-search-call' +} from '../../ai-vault/runtime-hosts/runtime-session-scanner' +import { callRuntimeSessionSearch } from '../../ai-vault/runtime-hosts/runtime-session-search-call' import { configureRuntimeAiVaultSessionDelete } from '../ai-vault/ai-vault-delete' import { ensureStructuredAgentSessionHostUnlessRefused } from '../../runtime/agent-session/structured-agent-session-host-refusal' import { getAgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import type { PluginService } from '../../plugins/plugin-service' import type { PluginMarketplaceHandlerServices } from '../plugin-marketplaces' import { settleWithinMs } from '../../startup/quit/quit-teardown-deadline' -import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/catalog/runtime-environment-registry-root' let registered = false // Same cap as the restart path's auth preservation: bookkeeping must not hold Restart on a stalled disk. @@ -296,5 +294,5 @@ export function registerCoreHandlers( } }) registerUpdaterHandlers(store) - registerSpeechHandlers(store) + registerSpeechHandlers(store, commitMessageAgentEnv) } diff --git a/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts b/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts index 86d22fac5dd..4605065bb42 100644 --- a/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts +++ b/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts @@ -8,7 +8,7 @@ import { emptySession, GIT_KEY, leaf -} from '../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import type { SleepingAgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-resume' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' diff --git a/src/main/ipc/renderer-shutdown-checkpoint.ts b/src/main/ipc/renderer-shutdown-checkpoint.ts index ba7e49055cc..1a8f736c51b 100644 --- a/src/main/ipc/renderer-shutdown-checkpoint.ts +++ b/src/main/ipc/renderer-shutdown-checkpoint.ts @@ -5,7 +5,7 @@ import { type ExecutionHostId } from '../../shared/execution-host' import type { SleepingAgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-resume' -import { applyCommandToSession } from '../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' import type { Store } from '../persistence/loading-store/store' diff --git a/src/main/ipc/repos-remote-client-events.test.ts b/src/main/ipc/repos-remote-client-events.test.ts deleted file mode 100644 index 68fc3acc186..00000000000 --- a/src/main/ipc/repos-remote-client-events.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -/** Paired clients refetch only on reposChanged; broadcast failures must not reject committed mutations. */ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ReposChangedNotificationModule from './repos/repos-changed-notification' - -const { handleMock, mockStore } = vi.hoisted(() => ({ - handleMock: vi.fn(), - mockStore: { - getRepos: vi.fn().mockReturnValue([]), - getRepo: vi.fn(), - addRepo: vi.fn(), - updateRepo: vi.fn(), - removeProjectForHost: vi.fn(), - reorderRepos: vi.fn().mockReturnValue(true) - } -})) - -vi.mock('electron', () => ({ - dialog: { showOpenDialog: vi.fn() }, - ipcMain: { handle: handleMock, removeHandler: vi.fn() } -})) - -vi.mock('../git/repositories/discovery/repo-detection', () => ({ - isGitRepo: vi.fn().mockReturnValue(true) -})) -vi.mock('../git/repositories/repository-name', () => ({ - getRepoName: vi.fn().mockImplementation((path: string) => path.split('/').pop()) -})) -vi.mock('../git/refs/resolution/repo-default-base-ref', () => ({ - getDefaultBaseRefAsync: vi.fn().mockResolvedValue('origin/main') -})) -vi.mock('../git/refs/resolution/repo-base-ref-search', () => ({ - searchBaseRefs: vi.fn().mockResolvedValue([]) -})) - -vi.mock('./worktrees/removal/registered-worktree-roots-cache', () => ({ - invalidateAuthorizedRootsCache: vi.fn(), - invalidateAuthorizedRootsCacheForRepo: vi.fn() -})) - -type HandlerMap = Map unknown> - -const handlers: HandlerMap = new Map() -const mainWindow = { isDestroyed: () => false, webContents: { send: vi.fn() } } - -/** Fresh module instance per test so the module-scoped notifier holder starts unset. */ -async function registerHandlersWithoutNotifier(): Promise { - vi.resetModules() - const repos = await import('./repos') - repos.registerRepoHandlers(mainWindow as never, mockStore as never, {} as never) - return import('./repos/repos-changed-notification') -} - -async function registerHandlersWithNotifier( - notifyReposChangedForRemoteClients: () => void -): Promise { - const notification = await registerHandlersWithoutNotifier() - notification.setRepoRemoteClientNotifier({ notifyReposChangedForRemoteClients } as never) -} - -beforeEach(() => { - handlers.clear() - handleMock.mockReset() - handleMock.mockImplementation((channel: string, handler: (...a: unknown[]) => unknown) => { - handlers.set(channel, handler) - }) - mainWindow.webContents.send.mockReset() - mockStore.removeProjectForHost.mockReset() - mockStore.reorderRepos.mockReset().mockReturnValue(true) -}) - -describe('repo IPC mutations notify paired clients', () => { - it('does not reject the handler when the notifier throws', async () => { - await registerHandlersWithNotifier(() => { - throw new Error('client event stream exploded') - }) - - await expect( - handlers.get('repos:removeForHost')!(null, { repoId: 'repo-1', hostId: 'local' }) - ).resolves.toBeUndefined() - }) -}) diff --git a/src/main/ipc/repos/repo-catalog-handlers.ts b/src/main/ipc/repos/repo-catalog-handlers.ts index 1b8caa4b0ac..965dcd69c46 100644 --- a/src/main/ipc/repos/repo-catalog-handlers.ts +++ b/src/main/ipc/repos/repo-catalog-handlers.ts @@ -25,7 +25,7 @@ import { import { listWslMovedProjects } from '../../persistence/moving-wsl-projects/desktop-state/wsl-moved-projects' import { listHostRepoCatalogSnapshots } from '../../host-repo-catalog-snapshot/host-repo-catalog-snapshot-recorder' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from '../runtime-environments/catalog/runtime-environment-registry-root' import { isGatedOffWslHost } from '../../wsl/host-lifecycle/wsl-host-gate' export function registerRepoCatalogHandlers( diff --git a/src/main/ipc/repos/repo-update-handler.ts b/src/main/ipc/repos/repo-update-handler.ts index ed2d613fa08..bffb73a42a6 100644 --- a/src/main/ipc/repos/repo-update-handler.ts +++ b/src/main/ipc/repos/repo-update-handler.ts @@ -14,13 +14,13 @@ import { sanitizeRepoIcon } from '../../../shared/repo-icon' import { normalizeGhAccountBinding, type GhAccountBinding -} from '../../../shared/github/account-binding' +} from '../../../shared/github/accounts/account-binding' import { normalizeRepoSourceControlAiOverrides } from '../../../shared/source-control/ai/settings/source-control-ai-repo-settings' import { normalizeCustomWorktreeVisibilitySources, normalizeWorktreeVisibilitySourcePreferences -} from '../../../shared/worktree/visibility-sources' +} from '../../../shared/worktree/visibility/visibility-sources' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { commitProvenRepoKindChange } from '../../workspaces/catalog/folder-repo-git-conversion' import { normalizeDictationTerms } from '../../../shared/dictation-dictionary' @@ -68,9 +68,11 @@ export function registerRepoUpdateHandler(mainWindow: BrowserWindow, store: Stor externalWorktreeVisibility?: Repo['externalWorktreeVisibility'] | null agentWorktreeVisibility?: Repo['agentWorktreeVisibility'] | null sourceControlAi?: Repo['sourceControlAi'] | null + workspaceCleanupPolicy?: Repo['workspaceCleanupPolicy'] | null externalWorktreeDiscoverySuppressedAt?: | Repo['externalWorktreeDiscoverySuppressedAt'] | null + hiddenAt?: Repo['hiddenAt'] | null ghAccount?: GhAccountBinding | null } } @@ -211,6 +213,15 @@ export function registerRepoUpdateHandler(mainWindow: BrowserWindow, store: Stor ) { delete updates.externalWorktreeDiscoverySuppressedAt } + if ('hiddenAt' in updates && updates.hiddenAt === null) { + updates.hiddenAt = undefined + } else if ( + 'hiddenAt' in updates && + updates.hiddenAt !== undefined && + (typeof updates.hiddenAt !== 'number' || !Number.isFinite(updates.hiddenAt)) + ) { + delete updates.hiddenAt + } if ( 'externalWorktreeInboxBaselinePaths' in updates && updates.externalWorktreeInboxBaselinePaths !== undefined diff --git a/src/main/ipc/repos/sparse-preset-handlers.ts b/src/main/ipc/repos/sparse-preset-handlers.ts index 4be0a9eaf02..aa7165884c2 100644 --- a/src/main/ipc/repos/sparse-preset-handlers.ts +++ b/src/main/ipc/repos/sparse-preset-handlers.ts @@ -9,7 +9,7 @@ import { import { SparsePresetValidationError, type SparsePresetFailure -} from '../../../shared/worktree/sparse-preset-failure' +} from '../../../shared/worktree/creation/sparse-preset-failure' import { assertWslMoveProjectWritable } from '../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' export function registerSparsePresetHandlers(mainWindow: BrowserWindow, store: Store): void { diff --git a/src/main/ipc/repos/sparse-preset-validation.ts b/src/main/ipc/repos/sparse-preset-validation.ts index e1bd57f59c7..02ebc947ad2 100644 --- a/src/main/ipc/repos/sparse-preset-validation.ts +++ b/src/main/ipc/repos/sparse-preset-validation.ts @@ -1,4 +1,4 @@ -import { SparsePresetValidationError } from '../../../shared/worktree/sparse-preset-failure' +import { SparsePresetValidationError } from '../../../shared/worktree/creation/sparse-preset-failure' import { InvalidSparseDirectoryError, normalizeSparseDirectories diff --git a/src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts b/src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts similarity index 89% rename from src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts rename to src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts index 477e51d0146..0067afc6706 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts +++ b/src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import '../../../shared/protocol-version' +import '../../../../shared/protocol-version' import { BROWSER_CLIENT_AUTOMATION_RUNTIME_CAPABILITY, BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY, @@ -7,8 +7,8 @@ import { BROWSER_NETWORK_EXECUTION_HOSTS_RUNTIME_CAPABILITY, BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY, BROWSER_SCREENCAST_RUNTIME_CAPABILITY -} from '../../../shared/browser/runtime/browser-runtime-capabilities' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../../shared/browser/runtime/browser-runtime-capabilities' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' const { handleMock, @@ -27,23 +27,26 @@ const { })) vi.mock('electron', () => ({ ipcMain: { handle: handleMock } })) -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ +vi.mock('../../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ resolveEnvironment: resolveEnvironmentMock })) -vi.mock('./runtime-environment-status-probe', () => ({ +vi.mock('../status/runtime-environment-status-probe', () => ({ getRuntimeEnvironmentStatus: getRuntimeEnvironmentStatusMock })) -vi.mock('../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime', () => ({ - startPairedRuntimeBrowserClientHost: startHostMock, - closePairedRuntimeBrowserClientHostEnvironment: closeHostMock -})) -vi.mock('./runtime-environment-manual-disconnect', () => ({ +vi.mock( + '../../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime', + () => ({ + startPairedRuntimeBrowserClientHost: startHostMock, + closePairedRuntimeBrowserClientHostEnvironment: closeHostMock + }) +) +vi.mock('../connectivity/runtime-environment-manual-disconnect', () => ({ isRuntimeEnvironmentManuallyDisconnected: manuallyDisconnectedMock })) import { prepareRuntimeEnvironmentBrowserPlacement } from './runtime-environment-browser-placement' import { registerRuntimeEnvironmentBrowserClientHostHandler } from './runtime-environment-browser-client-host-handler' -import { channelHandlerLookup } from './runtime-environments-ipc-test-harness' +import { channelHandlerLookup } from '../runtime-environments-ipc-test-harness' const handler = channelHandlerLookup(handleMock) @@ -105,7 +108,6 @@ describe('runtime environment browser client host handler', () => { kind: 'server' }) - expect(startHostMock).toHaveBeenCalledOnce() expect(closeHostMock).not.toHaveBeenCalled() }) diff --git a/src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.ts b/src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.ts similarity index 85% rename from src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.ts rename to src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.ts index beb33c207f1..2416ba6ce1a 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.ts +++ b/src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.ts @@ -2,8 +2,8 @@ import { ipcMain } from 'electron' import { BrowserClientHostPlacementPreparationRequest, type BrowserPageCreationPlacement -} from '../../../shared/browser/client-hosting/browser-client-host-placement' -import type { GlobalSettings } from '../../../shared/global-settings-types' +} from '../../../../shared/browser/client-hosting/browser-client-host-placement' +import type { GlobalSettings } from '../../../../shared/global-settings-types' import { prepareRuntimeEnvironmentBrowserPlacement } from './runtime-environment-browser-placement' export function registerRuntimeEnvironmentBrowserClientHostHandler(options: { diff --git a/src/main/ipc/runtime-environments/runtime-environment-browser-placement.ts b/src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-placement.ts similarity index 75% rename from src/main/ipc/runtime-environments/runtime-environment-browser-placement.ts rename to src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-placement.ts index 417a43dc15b..79acb5aa693 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-browser-placement.ts +++ b/src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-placement.ts @@ -1,12 +1,12 @@ -import type { BrowserClientHostPlacementPreference } from '../../../shared/browser/client-hosting/browser-client-host-placement' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { BrowserClientHostPlacementPreference } from '../../../../shared/browser/client-hosting/browser-client-host-placement' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import { closePairedRuntimeBrowserClientHostEnvironment, startPairedRuntimeBrowserClientHost -} from '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' -import { prepareBrowserClientHostPlacement } from '../../browser/client-hosts/lifecycle/browser-client-host-placement-preparation' -import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' -import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' +} from '../../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' +import { prepareBrowserClientHostPlacement } from '../../../browser/client-hosts/lifecycle/browser-client-host-placement-preparation' +import { isRuntimeEnvironmentManuallyDisconnected } from '../connectivity/runtime-environment-manual-disconnect' +import { getRuntimeEnvironmentStatus } from '../status/runtime-environment-status-probe' export async function prepareRuntimeEnvironmentBrowserPlacement( userDataPath: string, diff --git a/src/main/ipc/runtime-environments/runtime-environment-catalog-broadcast.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-catalog-broadcast.ts similarity index 85% rename from src/main/ipc/runtime-environments/runtime-environment-catalog-broadcast.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-catalog-broadcast.ts index afb27c7af1a..ac5adf1619e 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-catalog-broadcast.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-catalog-broadcast.ts @@ -1,5 +1,5 @@ import { BrowserWindow } from 'electron' -import { RUNTIME_ENVIRONMENT_CATALOG_CHANGED_CHANNEL } from '../../../shared/remote-runtime/host-catalog/runtime-environment-catalog-channel' +import { RUNTIME_ENVIRONMENT_CATALOG_CHANGED_CHANNEL } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-catalog-channel' export function publishRuntimeEnvironmentCatalogChanged(): void { for (const window of BrowserWindow.getAllWindows()) { diff --git a/src/main/ipc/runtime-environments/catalog/runtime-environment-host-key.test.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-host-key.test.ts new file mode 100644 index 00000000000..77d0c453781 --- /dev/null +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-host-key.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key' + +function environment(publicKeyB64: string): KnownRuntimeEnvironment { + return { + id: 'env-1', + name: 'Box', + createdAt: 1, + updatedAt: 1, + lastUsedAt: null, + runtimeId: null, + preferredEndpointId: 'ws', + endpoints: [ + { + id: 'ws', + kind: 'websocket', + label: 'Box', + endpoint: 'ws://127.0.0.1:46768/', + deviceToken: 'secret-token', + publicKeyB64 + } + ] + } +} + +describe('the public runtime environment record', () => { + it('never exposes the host key or device token', () => { + const first = publicRuntimeEnvironmentWithHostKey(environment('key-a')) + + expect(JSON.stringify(first)).not.toMatch(/key-a|secret-token/) + }) +}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-host-key.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-host-key.ts similarity index 89% rename from src/main/ipc/runtime-environments/runtime-environment-host-key.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-host-key.ts index 07b408aabd1..a24e84191de 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-host-key.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-host-key.ts @@ -4,7 +4,7 @@ import { redactRuntimeEnvironment, type KnownRuntimeEnvironment, type PublicKnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' /** Compare a digest of the persistent E2EE host key without exposing the key to the renderer. */ export function publicRuntimeEnvironmentWithHostKey( diff --git a/src/main/ipc/runtime-environments/runtime-environment-preference.test.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-preference.test.ts similarity index 80% rename from src/main/ipc/runtime-environments/runtime-environment-preference.test.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-preference.test.ts index 5a30a95b92b..53752289b97 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-preference.test.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-preference.test.ts @@ -2,14 +2,14 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../shared/constants' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' +import { getDefaultSettings } from '../../../../shared/constants' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' import { addEnvironmentFromPairingCode, removeEnvironment -} from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getEnvironmentStorePath } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' -import type { Store } from '../../persistence/loading-store/store' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getEnvironmentStorePath } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' +import type { Store } from '../../../persistence/loading-store/store' import { readSettingsWithRuntimeEnvironmentPreference, watchRuntimeEnvironmentPreference @@ -55,9 +55,7 @@ describe('Active Server after a saved host is removed', () => { let stopWatching: (() => void) | undefined rmSync(userDataPath, { recursive: true }) try { - expect(() => { - stopWatching = watchRuntimeEnvironmentPreference(store, userDataPath) - }).not.toThrow() + stopWatching = watchRuntimeEnvironmentPreference(store, userDataPath) expect(store.getSettings().activeRuntimeEnvironmentId).toBe(environment.id) mkdirSync(userDataPath) writeFileSync(getEnvironmentStorePath(userDataPath), '{"version":1,"environments":[]}') @@ -74,10 +72,9 @@ describe('Active Server after a saved host is removed', () => { const removed = saveEnvironment() const store = preferenceStore(removed.id) removeEnvironment(userDataPath, removed.id) - const replacement = saveEnvironment() + saveEnvironment() saveEnvironment('other') - expect(replacement.id).not.toBe(removed.id) expect( readSettingsWithRuntimeEnvironmentPreference(store, userDataPath).activeRuntimeEnvironmentId ).toBeNull() diff --git a/src/main/ipc/runtime-environments/runtime-environment-preference.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-preference.ts similarity index 85% rename from src/main/ipc/runtime-environments/runtime-environment-preference.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-preference.ts index 67692106bbb..7ab3d8b17d5 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-preference.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-preference.ts @@ -1,8 +1,8 @@ -import type { GlobalSettings } from '../../../shared/global-settings-types' -import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getEnvironmentStorePath } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' -import type { Store } from '../../persistence/loading-store/store' -import { watchFileAcrossReplacement } from '../filesystem/watcher-process/native-subscriptions/rebinding-file-watch' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getEnvironmentStorePath } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' +import type { Store } from '../../../persistence/loading-store/store' +import { watchFileAcrossReplacement } from '../../filesystem/watcher-process/native-subscriptions/rebinding-file-watch' type PreferenceStore = Pick diff --git a/src/main/ipc/runtime-environments/catalog/runtime-environment-redundant-managed-removal.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-redundant-managed-removal.ts new file mode 100644 index 00000000000..e9fec7e6ddd --- /dev/null +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-redundant-managed-removal.ts @@ -0,0 +1,30 @@ +import { + redactRuntimeEnvironment, + type KnownRuntimeEnvironment, + type RuntimeEnvironmentRemoval +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { findManagedSshTwin } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-host-key-match' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getManagedServerActions } from '../../../runtime/hosts/management/managed-server-actions-registry' + +/** + * Removes one of two saved entries for a managed server reached through two SSH aliases. + * The other entry still manages that server, so this entry is unlinked here without touching the host. + * Null when no other entry manages the same server; the store's guard then keeps the pairing. + */ +export function removeRedundantManagedPairing( + userDataPath: string, + environment: KnownRuntimeEnvironment +): Promise | null { + const actions = getManagedServerActions() + if (!actions || !findManagedSshTwin(listEnvironments(userDataPath), environment)) { + return null + } + // Forget is the managed removal: it also closes this entry's tunnel and releases its SSH claims. + return actions.forgetRedundant(environment.id).then((result) => { + if (result.outcome === 'refused') { + throw new Error(result.reason) + } + return { removed: redactRuntimeEnvironment(environment) } + }) +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-registry-root.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-registry-root.ts similarity index 84% rename from src/main/ipc/runtime-environments/runtime-environment-registry-root.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-registry-root.ts index 62c6537347d..74369835b3d 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-registry-root.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-registry-root.ts @@ -1,5 +1,5 @@ import { app } from 'electron' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' /** Where the paired-runtime registry lives; read per call, after `app.setName` settles the casing. */ export function getRuntimeEnvironmentRegistryRoot(): string { diff --git a/src/main/ipc/runtime-environments/catalog/runtime-environment-removal-cleanup.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-removal-cleanup.ts new file mode 100644 index 00000000000..4c0cc4632fa --- /dev/null +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-removal-cleanup.ts @@ -0,0 +1,50 @@ +import { desktopChatCreationHistory } from '../../../runtime/client/navigation/desktop-chat-creation-history' +import '../../../media/media-preview-protocol' +import { revokeRemoteFilePreviewGrants } from '../../../media/preview-grant-registry' +import { clearBrowserRoutePartitionStorageForEnvironment } from '../../../browser/routing/partitions/browser-route-partition-storage-runtime' +import { retireBrowserRoutePartitionStorageForEnvironment } from '../../../browser/routing/partitions/browser-route-partition-storage-retirement' +import { clearRuntimeEnvironmentCapabilityEvidence } from '../connections/runtime-environment-capability-evidence' +import { clearRuntimeEnvironmentManualDisconnect } from '../connectivity/runtime-environment-manual-disconnect' +import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { + forgetRemoteLayoutSnapshot, + type RemoteLayoutSnapshotStore +} from '../../../remote-layout-snapshot/remote-layout-snapshot-recorder' +import type { HostRepoCatalogSnapshotStore } from '../../../host-repo-catalog-snapshot/host-repo-catalog-snapshot-recorder' + +export type RemovedServerStore = RemoteLayoutSnapshotStore & + Pick & { + removeWorkspaceSessionHost: (hostId: ExecutionHostId) => void + } + +/** Retires a removed server's client-side state; resolves once its transport is invalidated. */ +export function retireRemovedRuntimeEnvironment( + environmentId: string, + invalidateTransport: (environmentId: string) => Promise | void, + store: RemovedServerStore, + userDataPath?: string +): Promise { + if (userDataPath) { + void desktopChatCreationHistory(userDataPath).removeEnvironment(environmentId) + } + clearRuntimeEnvironmentCapabilityEvidence(environmentId) + revokeRemoteFilePreviewGrants(environmentId) + // Retained session partitions make listings advertise the removed server as a known host. + store.removeWorkspaceSessionHost(toRuntimeExecutionHostId(environmentId)) + forgetRemoteLayoutSnapshot(store, environmentId) + store.setHostRepoCatalogSnapshot(environmentId, null) + clearRuntimeEnvironmentManualDisconnect(environmentId) + const retiring = Promise.resolve(invalidateTransport(environmentId)) + // Explicit removal retires browser storage after client hosts release their live partitions. + void retireBrowserRoutePartitionStorageForEnvironment({ + environmentId, + whenClientHostClosed: retiring, + clearStorage: clearBrowserRoutePartitionStorageForEnvironment, + onError: (error) => { + console.warn('[runtime-environments] browser partition storage clear failed:', error) + } + }).catch((error) => { + console.warn('[runtime-environments] browser partition storage clear failed:', error) + }) + return retiring +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-session-reconcile.test.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.test.ts similarity index 78% rename from src/main/ipc/runtime-environments/runtime-environment-session-reconcile.test.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.test.ts index b5fd6e7434b..ebda92046f1 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-session-reconcile.test.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.test.ts @@ -3,12 +3,12 @@ import * as fs from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ExecutionHostId } from '../../../shared/execution-host' -import { addEnvironmentFromPairingCode } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import '../../../shared/remote-runtime/host-store/runtime-environment-store-file' -import { getEnvironmentStorePath } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' -import { getRuntimeEnvironmentSidecarPath } from '../../../shared/remote-runtime/host-store/runtime-environment-sidecar' -import { pairingCode } from './runtime-environments-ipc-test-harness' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { addEnvironmentFromPairingCode } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import '../../../../shared/remote-runtime/host-store/runtime-environment-store-file' +import { getEnvironmentStorePath } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' +import { getRuntimeEnvironmentSidecarPath } from '../../../../shared/remote-runtime/host-store/runtime-environment-sidecar' +import { pairingCode } from '../runtime-environments-ipc-test-harness' import { reconcileOrphanedRuntimeSessions } from './runtime-environment-session-reconcile' // Lets a test make the registry vanish between a presence check and its read. @@ -50,8 +50,6 @@ describe('reconciling orphaned runtime sessions at startup', () => { 'runtime:removed-env' ]) expect(reconcileOrphanedRuntimeSessions(store, userDataPath)).toEqual(['runtime:removed-env']) - expect(store.removeWorkspaceSessionHost).toHaveBeenCalledTimes(1) - expect(store.removeWorkspaceSessionHost).toHaveBeenCalledWith('runtime:removed-env') }) it('deletes nothing when the environment store is missing or unreadable', () => { @@ -63,7 +61,6 @@ describe('reconciling orphaned runtime sessions at startup', () => { writeFileSync(getEnvironmentStorePath(corrupt), '{not json', { mode: 0o600 }) vi.spyOn(console, 'warn').mockImplementation(() => undefined) expect(reconcileOrphanedRuntimeSessions(store, corrupt)).toEqual([]) - expect(store.removeWorkspaceSessionHost).not.toHaveBeenCalled() }) it('keeps sessions of saved servers this build cannot read or currently hides', () => { @@ -90,6 +87,5 @@ describe('reconciling orphaned runtime sessions at startup', () => { ]) expect(reconcileOrphanedRuntimeSessions(store, userDataPath)).toEqual(['runtime:removed-env']) - expect(store.removeWorkspaceSessionHost).toHaveBeenCalledTimes(1) }) }) diff --git a/src/main/ipc/runtime-environments/runtime-environment-session-reconcile.ts b/src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.ts similarity index 90% rename from src/main/ipc/runtime-environments/runtime-environment-session-reconcile.ts rename to src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.ts index fd3dcf7194d..0362285fbf6 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-session-reconcile.ts +++ b/src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.ts @@ -1,6 +1,6 @@ /** Crashes and older unlink flows can leave runtime session partitions that listings advertise as orphaned hosts. */ -import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { readEnvironmentStoreRecords } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' +import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { readEnvironmentStoreRecords } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' type SessionHostStore = { getWorkspaceSessionHostIds: () => ExecutionHostId[] diff --git a/src/main/ipc/runtime-environments/runtime-environment-capability-evidence.test.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.test.ts similarity index 94% rename from src/main/ipc/runtime-environments/runtime-environment-capability-evidence.test.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.test.ts index 7cbfc0833c8..205297c751d 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-capability-evidence.test.ts +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.test.ts @@ -1,6 +1,6 @@ -import { pairedRuntimeConnectionFromOffer } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' +import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import { beforeEach, describe, expect, it } from 'vitest' -import type { PairingOffer } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' import { advanceRuntimeEnvironmentCapabilityIncarnation, applyRuntimeEnvironmentCapabilityVerdict, diff --git a/src/main/ipc/runtime-environments/runtime-environment-capability-evidence.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.ts similarity index 97% rename from src/main/ipc/runtime-environments/runtime-environment-capability-evidence.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.ts index 67e3cdc1e48..ac3a589c354 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-capability-evidence.ts +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.ts @@ -1,4 +1,4 @@ -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' +import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' export type RuntimeEnvironmentCapabilityVerdict = 'capable' | 'absent' diff --git a/src/main/ipc/runtime-environments/connections/runtime-environment-request-connections.test.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-request-connections.test.ts new file mode 100644 index 00000000000..48cdfb1e44c --- /dev/null +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-request-connections.test.ts @@ -0,0 +1,92 @@ +import { RemoteRuntimeSharedControlConnection } from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-connection' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + closeSharedControlTestServers, + createSharedControlTestServer +} from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' +import { resetRuntimeEnvironmentCapabilityEvidence } from './runtime-environment-capability-evidence' +import { clearRuntimeEnvironmentManualDisconnect } from '../connectivity/runtime-environment-manual-disconnect' +import { + closeRemoteRuntimeRequestConnection, + sendRemoteRuntimeSharedControlRequestOnRuntime +} from './runtime-environment-request-connections' + +const ENVIRONMENT_ID = 'standing-intent-test' + +afterEach(async () => { + vi.restoreAllMocks() + closeRemoteRuntimeRequestConnection(ENVIRONMENT_ID) + clearRuntimeEnvironmentManualDisconnect(ENVIRONMENT_ID) + resetRuntimeEnvironmentCapabilityEvidence() + await closeSharedControlTestServers() +}) + +describe('runtime environment shared-control connection cache', () => { + it.each([ + ['the probed runtime', 'runtime-a', true], + ['a replacement runtime behind the same endpoint', 'runtime-b', false] + ])( + 'sends a runtime-pinned call only when its socket reached %s', + async (_label, reached, sent) => { + const server = await createSharedControlTestServer({ + resultForRequest: (method) => + method === 'status.get' ? { runtimeId: reached } : { method } + }) + + const response = await sendRemoteRuntimeSharedControlRequestOnRuntime( + ENVIRONMENT_ID, + server.pairing, + { method: 'files.write', params: { relativePath: 'a.ts' }, timeoutMs: 1000 }, + 'runtime-a' + ) + + expect(response === null).toBe(!sent) + expect(server.requests.some((request) => request.method === 'files.write')).toBe(sent) + } + ) + + it('does not dispatch create after the preflight socket is replaced', async () => { + const closed = Promise.withResolvers() + const server = await createSharedControlTestServer({ + onClientClose: () => closed.resolve(), + resultForRequest: (method) => (method === 'status.get' ? { runtimeId: 'runtime-a' } : {}) + }) + const original = RemoteRuntimeSharedControlConnection.prototype.request + vi.spyOn(RemoteRuntimeSharedControlConnection.prototype, 'request').mockImplementation( + function ( + this: RemoteRuntimeSharedControlConnection, + ...args: Parameters + ): Promise> { + const invoke = original.bind(this) + const response = invoke(...args) + if (args[0] !== 'status.get') { + return response + } + return response.then(async (status) => { + server.closeClients() + await closed.promise + this.reconnectNow() + return status + }) + } + ) + await expect( + sendRemoteRuntimeSharedControlRequestOnRuntime( + ENVIRONMENT_ID, + server.pairing, + { + method: 'agentSession.create', + params: { + forkFrom: { sessionId: 'child', throughItemId: 'legacy:opencode:source:reply-1' } + }, + timeoutMs: 1000 + }, + 'runtime-a' + ) + ).resolves.toBeNull() + expect(server.requests.filter((request) => request.method === 'agentSession.create')).toEqual( + [] + ) + }) +}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-request-connections.ts similarity index 86% rename from src/main/ipc/runtime-environments/runtime-environment-request-connections.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-request-connections.ts index 60217af8047..74886ba98c8 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-request-connections.ts @@ -1,26 +1,26 @@ import { runtimeEnvironmentConnectionPairingKey as getPairingKey } from './runtime-environment-capability-evidence' -import type { RuntimeEnvironmentCall } from './runtime-environment-call' -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeHostStatusOwner } from '../../../shared/remote-runtime/host-status/runtime-host-status-owner' -import type { RuntimeStatus } from '../../../shared/runtime-types' -import { createRuntimeEnvironmentStatusOwner } from './runtime-environment-status-owner' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' +import type { RuntimeEnvironmentCall } from '../requests/runtime-environment-call' +import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getPreferredPairedRuntimeConnection } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { RuntimeHostStatusOwner } from '../../../../shared/remote-runtime/host-status/runtime-host-status-owner' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' +import { createRuntimeEnvironmentStatusOwner } from '../status/runtime-environment-status-owner' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' import type { RuntimeOrchestrationEnvelope, RuntimeRequestPreparation, RuntimeRpcResponse -} from '../../../shared/runtime-rpc-envelope' -import { RemoteRuntimeRequestConnection } from '../../../shared/remote-runtime/requests/remote-runtime-request-connection' -import { RemoteRuntimeSharedControlConnection } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-connection' -import { probeAllRemoteRuntimeSocketsNow } from '../../../shared/remote-runtime/remote-runtime-socket-liveness' +} from '../../../../shared/runtime-rpc-envelope' +import { RemoteRuntimeRequestConnection } from '../../../../shared/remote-runtime/requests/remote-runtime-request-connection' +import { RemoteRuntimeSharedControlConnection } from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-connection' +import { probeAllRemoteRuntimeSocketsNow } from '../../../../shared/remote-runtime/remote-runtime-socket-liveness' import type { RemoteRuntimeSharedConnectionDiagnostics, RemoteRuntimeSharedSubscription -} from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' -import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' -import { publishRuntimeEnvironmentDiagnostics } from './runtime-environment-diagnostics-broadcast' +} from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-types' +import { isRuntimeEnvironmentManuallyDisconnected } from '../connectivity/runtime-environment-manual-disconnect' +import { publishRuntimeEnvironmentDiagnostics } from '../status/runtime-environment-diagnostics-broadcast' import { sharedControlEnvironmentPolicy } from './runtime-environment-shared-control-policy' import { clearSharedControlAnswerSource, @@ -30,8 +30,8 @@ import { advanceRuntimeEnvironmentTransportGeneration, getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' -import { noteRuntimeEnvironmentSharedControlContact } from './runtime-environment-contact-loss' -import { declareWslHostClient } from '../../wsl/host-lifecycle/wsl-host-client-declaration' +import { noteRuntimeEnvironmentSharedControlContact } from '../status/runtime-environment-contact-loss' +import { declareWslHostClient } from '../../../wsl/host-lifecycle/wsl-host-client-declaration' type CachedRuntimeConnection = { pairingKey: string diff --git a/src/main/ipc/runtime-environments/runtime-environment-shared-control-answers.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-answers.ts similarity index 100% rename from src/main/ipc/runtime-environments/runtime-environment-shared-control-answers.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-answers.ts diff --git a/src/main/ipc/runtime-environments/runtime-environment-shared-control-envelope.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-envelope.ts similarity index 78% rename from src/main/ipc/runtime-environments/runtime-environment-shared-control-envelope.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-envelope.ts index 1895e27e6ac..e6ea898b06b 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-shared-control-envelope.ts +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-envelope.ts @@ -1,5 +1,5 @@ -import { isOrchestrationMutation } from '../../../shared/orchestration/orchestration-rpc-contract' -import type { RuntimeOrchestrationEnvelope } from '../../../shared/runtime-rpc-envelope' +import { isOrchestrationMutation } from '../../../../shared/orchestration/orchestration-rpc-contract' +import type { RuntimeOrchestrationEnvelope } from '../../../../shared/runtime-rpc-envelope' // Relay mutations safe on shared control: synchronous, idempotent by request id and cursor. Long-running ones (workerStart) stay one-shot for keepalive timeouts and host abort. const SHARED_CONTROL_RELAY_MUTATIONS = [ diff --git a/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-policy.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-policy.ts new file mode 100644 index 00000000000..4274e00409d --- /dev/null +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-policy.ts @@ -0,0 +1,26 @@ +import type { RemoteRuntimeSharedControlConnectionOptions } from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-types' +import { isRuntimeEnvironmentCapabilityPaused } from './runtime-environment-capability-evidence' +import { isRuntimeEnvironmentManuallyDisconnected } from '../connectivity/runtime-environment-manual-disconnect' +import { handleSharedControlRefusal } from '../pairing/runtime-environment-pairing-refusal-registry' +import { traceSharedControlSocketClose } from '../status/runtime-environment-control-socket-close-trace' +import { isRecipeVmServerAsleep } from '../../../ephemeral-vm/recipe-vm-asleep' + +/** When a shared control socket may reconnect, who answers a refused token, and where closes go. */ +export function sharedControlEnvironmentPolicy( + environmentId: string +): Pick< + RemoteRuntimeSharedControlConnectionOptions, + | 'isManuallyDisconnected' + | 'isCapabilityPaused' + | 'isAsleep' + | 'onAuthenticationRejected' + | 'onSocketClosed' +> { + return { + isManuallyDisconnected: () => isRuntimeEnvironmentManuallyDisconnected(environmentId), + isCapabilityPaused: () => isRuntimeEnvironmentCapabilityPaused(environmentId), + isAsleep: () => isRecipeVmServerAsleep(environmentId), + onAuthenticationRejected: () => handleSharedControlRefusal(environmentId), + onSocketClosed: (record) => traceSharedControlSocketClose(environmentId, record) + } +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-shared-control-support.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-support.ts similarity index 79% rename from src/main/ipc/runtime-environments/runtime-environment-shared-control-support.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-support.ts index 036704beb13..06480578cfb 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-shared-control-support.ts +++ b/src/main/ipc/runtime-environments/connections/runtime-environment-shared-control-support.ts @@ -1,6 +1,6 @@ -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' +import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' import { getAcceptedRuntimeEnvironmentCapabilityOutcome, resetRuntimeEnvironmentCapabilityEvidence, diff --git a/src/main/ipc/runtime-environments/runtime-environment-transport-generation.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-transport-generation.ts similarity index 100% rename from src/main/ipc/runtime-environments/runtime-environment-transport-generation.ts rename to src/main/ipc/runtime-environments/connections/runtime-environment-transport-generation.ts diff --git a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts b/src/main/ipc/runtime-environments/connectivity/runtime-environment-connectivity-handlers.ts similarity index 84% rename from src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts rename to src/main/ipc/runtime-environments/connectivity/runtime-environment-connectivity-handlers.ts index 3fb21a36fee..7b8f9636387 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts +++ b/src/main/ipc/runtime-environments/connectivity/runtime-environment-connectivity-handlers.ts @@ -1,62 +1,63 @@ import { manuallyDisconnectedResponse, runtimeEnvironmentCallFailure -} from './runtime-environment-call-failure' -import { desktopChatCreationHistory } from '../../runtime/client/navigation/desktop-chat-creation-history' +} from '../requests/runtime-environment-call-failure' +import { desktopChatCreationHistory } from '../../../runtime/client/navigation/desktop-chat-creation-history' import { ipcMain } from 'electron' import { addEnvironmentFromPairingCode, listEnvironments, removeEnvironment, resolveEnvironment -} from '../../../shared/remote-runtime/host-store/runtime-environment-store' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import { redactRuntimeEnvironment, type PublicKnownRuntimeEnvironment, type RuntimeEnvironmentRemoval -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' import { connectThroughOwningService, removeThroughOwningService } from './runtime-environment-host-service-ops' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' -import type { Store } from '../../persistence/loading-store/store' -import { retireRemovedRuntimeEnvironment } from './runtime-environment-removal-cleanup' -import { removeRedundantManagedPairing } from './runtime-environment-redundant-managed-removal' -import { readSettingsWithRuntimeEnvironmentPreference } from './runtime-environment-preference' -import { verifyAndAddRuntimeEnvironmentFromPairingCode } from './runtime-environment-pairing-verification' -import { publishVerifiedPairing } from './runtime-environment-verified-pairing-publish' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' +import type { Store } from '../../../persistence/loading-store/store' +import { retireRemovedRuntimeEnvironment } from '../catalog/runtime-environment-removal-cleanup' +import { removeRedundantManagedPairing } from '../catalog/runtime-environment-redundant-managed-removal' +import { readSettingsWithRuntimeEnvironmentPreference } from '../catalog/runtime-environment-preference' +import { verifyAndAddRuntimeEnvironmentFromPairingCode } from '../pairing/runtime-environment-pairing-verification' +import { publishVerifiedPairing } from '../pairing/runtime-environment-verified-pairing-publish' import { closeRemoteRuntimeRequestConnection, getRuntimeEnvironmentStatusSnapshots -} from './runtime-environment-request-connections' +} from '../connections/runtime-environment-request-connections' import { clearRuntimeEnvironmentManualDisconnect, isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' -import { callRuntimeEnvironment } from './runtime-environment-transport-routing' -import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' -import { noteRuntimeEnvironmentConnectRequested } from './runtime-environment-pairing-refusal-registry' -import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key' -import { withWslOrcadAccountEnv } from '../../wsl/orcad/wsl-orcad-account-env' -import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline' +import { callRuntimeEnvironment } from '../requests/runtime-environment-transport-routing' +import { getRuntimeEnvironmentStatus } from '../status/runtime-environment-status-probe' +import { noteRuntimeEnvironmentConnectRequested } from '../pairing/runtime-environment-pairing-refusal-registry' +import { publicRuntimeEnvironmentWithHostKey } from '../catalog/runtime-environment-host-key' +import { withWslOrcadAccountEnv } from '../../../wsl/orcad/wsl-orcad-account-env' +import { clearSshCredentialDeclinedForEnvironment } from '../../../ssh/authentication/ssh-credential-decline' import { disconnectManagedHostOfEnvironmentForUser, disconnectRuntimeEnvironmentForUser, liftSshUserDisconnectForEnvironment -} from '../ssh/ssh-host-user-disconnect' +} from '../../ssh/ssh-host-user-disconnect' import { observeWslOrcadHostResponse, wslOrcadHostSupports -} from '../../wsl/orcad/wsl-orcad-host-environments' -import { assertWslHostReachable, isGatedOffWslHost } from '../../wsl/host-lifecycle/wsl-host-gate' +} from '../../../wsl/orcad/wsl-orcad-host-environments' +import { + assertWslHostReachable, + isGatedOffWslHost +} from '../../../wsl/host-lifecycle/wsl-host-gate' import { isHostSpawnFencedForWslMoveUndo, wslMoveUndoSpawnFencedResponse -} from '../../persistence/moving-wsl-projects/cutover-recovery/wsl-move-undo-spawn-fence' - -export { isRuntimeEnvironmentManuallyDisconnected } +} from '../../../persistence/moving-wsl-projects/cutover-recovery/wsl-move-undo-spawn-fence' type ConnectivityHandlerOptions = { store: Store diff --git a/src/main/ipc/runtime-environments/connectivity/runtime-environment-host-service-ops.ts b/src/main/ipc/runtime-environments/connectivity/runtime-environment-host-service-ops.ts new file mode 100644 index 00000000000..26378000419 --- /dev/null +++ b/src/main/ipc/runtime-environments/connectivity/runtime-environment-host-service-ops.ts @@ -0,0 +1,34 @@ +import { classifyRuntimeEnvironmentHost } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { WslHostServerStop } from '../../../../shared/wsl-host-types' +import { getWslHostService } from '../../../wsl/host-lifecycle/wsl-host-service-instance' + +/** Explicit connection may boot the WSL distro. */ +export async function connectThroughOwningService( + environment: KnownRuntimeEnvironment +): Promise { + const host = classifyRuntimeEnvironmentHost(environment) + switch (host.kind) { + case 'wsl': + await getWslHostService()?.connect(environment.id) + break + case 'network': + case 'ssh': + break + } +} + +/** Null delegates removal to the generic store path. */ +export function removeThroughOwningService( + environment: KnownRuntimeEnvironment +): Promise | null { + const host = classifyRuntimeEnvironmentHost(environment) + switch (host.kind) { + case 'wsl': + // Also releases the distro's holder and drops the WSL record. + return getWslHostService()?.remove(environment.id) ?? null + case 'network': + case 'ssh': + return null + } +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-manual-disconnect.ts b/src/main/ipc/runtime-environments/connectivity/runtime-environment-manual-disconnect.ts similarity index 96% rename from src/main/ipc/runtime-environments/runtime-environment-manual-disconnect.ts rename to src/main/ipc/runtime-environments/connectivity/runtime-environment-manual-disconnect.ts index ea9b2aa67f7..e45b4e330fc 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-manual-disconnect.ts +++ b/src/main/ipc/runtime-environments/connectivity/runtime-environment-manual-disconnect.ts @@ -1,7 +1,7 @@ import { requestDesktopBrowserBridgeReconcile, resetDesktopBrowserBridgeEnvironment -} from '../browser/desktop-browser-bridge-reconcile' +} from '../../browser/desktop-browser-bridge-reconcile' export const RUNTIME_MANUALLY_DISCONNECTED_MESSAGE = 'Runtime environment is manually disconnected.' diff --git a/src/main/ipc/runtime-environments/runtime-environment-recovery-handler.ts b/src/main/ipc/runtime-environments/connectivity/runtime-environment-recovery-handler.ts similarity index 78% rename from src/main/ipc/runtime-environments/runtime-environment-recovery-handler.ts rename to src/main/ipc/runtime-environments/connectivity/runtime-environment-recovery-handler.ts index 2ce3b9e65a1..49f18f4cf93 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-recovery-handler.ts +++ b/src/main/ipc/runtime-environments/connectivity/runtime-environment-recovery-handler.ts @@ -1,6 +1,6 @@ import { ipcMain } from 'electron' -import { retryRemoteRuntimeSharedControlConnectionsNow } from './runtime-environment-request-connections' -import { retrySshConnectionsAfterNetworkReturn } from '../ssh/ssh-host-sleep-reconnect' +import { retryRemoteRuntimeSharedControlConnectionsNow } from '../connections/runtime-environment-request-connections' +import { retrySshConnectionsAfterNetworkReturn } from '../../ssh/ssh-host-sleep-reconnect' const RETRY_CONNECTIONS_NOW_CHANNEL = 'runtimeEnvironments:retryConnectionsNow' diff --git a/src/main/ipc/runtime-environments/managed-orcad-actions.ts b/src/main/ipc/runtime-environments/managed-orcad/managed-orcad-actions.ts similarity index 81% rename from src/main/ipc/runtime-environments/managed-orcad-actions.ts rename to src/main/ipc/runtime-environments/managed-orcad/managed-orcad-actions.ts index f56124684a0..bae5718b2eb 100644 --- a/src/main/ipc/runtime-environments/managed-orcad-actions.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/managed-orcad-actions.ts @@ -3,33 +3,33 @@ import { forgetManagedOrcadEnvironment, forgetRedundantManagedOrcadEnvironment, stopManagedOrcadEnvironment -} from '../../managed-server/lifecycle/orcad-runtime-decommission' -import { getManagedOrcadRuntimeStatus } from '../../managed-server/lifecycle/orcad-runtime-status' -import { recoverManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-managed-recovery' -import { rollbackManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-managed-rollback' -import { updateManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-runtime-maintenance' -import { getOrcadSshDeployment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +} from '../../../managed-server/lifecycle/orcad-runtime-decommission' +import { getManagedOrcadRuntimeStatus } from '../../../managed-server/lifecycle/orcad-runtime-status' +import { recoverManagedOrcadEnvironment } from '../../../managed-server/lifecycle/orcad-managed-recovery' +import { rollbackManagedOrcadEnvironment } from '../../../managed-server/lifecycle/orcad-managed-rollback' +import { updateManagedOrcadEnvironment } from '../../../managed-server/lifecycle/orcad-runtime-maintenance' +import { getOrcadSshDeployment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import type { OrcadManagedRestartResult, OrcadManagedStaleLockReclaimRequest, OrcadManagedStaleLockReclaimResult -} from '../../../shared/orcad-managed-runtime' -import { restartManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-managed-launch-session' -import { forgetManagedOrcadAutomaticFailures } from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { runManagedOrcadStaleLockReclaim } from '../../managed-server/lifecycle/orcad-managed-stale-lock-reclaim' +} from '../../../../shared/orcad-managed-runtime' +import { restartManagedOrcadEnvironment } from '../../../managed-server/lifecycle/orcad-managed-launch-session' +import { forgetManagedOrcadAutomaticFailures } from '../../../managed-server/lifecycle/orcad-managed-tunnel' +import { runManagedOrcadStaleLockReclaim } from '../../../managed-server/lifecycle/orcad-managed-stale-lock-reclaim' import { clearLaunchSessionNote } from './runtime-environment-managed-tunnel' -import { forgetLaunchSessionVerdict } from '../ssh/ssh-host-launch-session-note' +import { forgetLaunchSessionVerdict } from '../../ssh/ssh-host-launch-session-note' import { liftUserHoldsForServerAction, resumeRuntimeEnvironmentStatus -} from '../ssh/ssh-host-user-disconnect' -import { releaseUnlinkedHostTransport } from '../ssh/ssh-session-teardown' -import type { ManagedServerActions } from '../../runtime/hosts/management/managed-server-actions-registry' +} from '../../ssh/ssh-host-user-disconnect' +import { releaseUnlinkedHostTransport } from '../../ssh/ssh-session-teardown' +import type { ManagedServerActions } from '../../../runtime/hosts/management/managed-server-actions-registry' import { retireRemovedRuntimeEnvironment, type RemovedServerStore -} from './runtime-environment-removal-cleanup' +} from '../catalog/runtime-environment-removal-cleanup' export type ManagedOrcadActionOptions = { getUserDataPath: () => string diff --git a/src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts b/src/main/ipc/runtime-environments/managed-orcad/orcad-delta-move-handlers.ts similarity index 78% rename from src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts rename to src/main/ipc/runtime-environments/managed-orcad/orcad-delta-move-handlers.ts index 8db09eafd25..71d2009b623 100644 --- a/src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/orcad-delta-move-handlers.ts @@ -3,24 +3,24 @@ import { ipcMain } from 'electron' import type { OrcadDeltaMovePreview, OrcadDeltaMoveResult -} from '../../../shared/orcad-managed-runtime' -import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { requireManagedOrcadInfrastructure } from '../../managed-server/lifecycle/orcad-managed-runtime-context' -import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' +} from '../../../../shared/orcad-managed-runtime' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { requireManagedOrcadInfrastructure } from '../../../managed-server/lifecycle/orcad-managed-runtime-context' +import { ensureOrcadManagedTunnel } from '../../../managed-server/lifecycle/orcad-managed-tunnel' import { keepOrcadServerVersion, runOrcadDeltaMove -} from '../../managed-server/migration/cutover/orcad-migration-delta-move' -import { planOrcadDeltaMove } from '../../managed-server/migration/cutover/orcad-migration-delta-plan' -import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target' +} from '../../../managed-server/migration/cutover/orcad-migration-delta-move' +import { planOrcadDeltaMove } from '../../../managed-server/migration/cutover/orcad-migration-delta-plan' +import { censusHostRelayTerminalsFor } from '../../../ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target' import { orcadMigrationDestinationFor, orcadServerAutomationEnablerFor -} from '../../managed-server/lifecycle/orcad-runtime-conversion-wiring' -import { enableMovedOrcadAutomationsForTarget } from '../../persistence/migrating-orcad-catalog/retained-source/orcad-migration-moved-automations' +} from '../../../managed-server/lifecycle/orcad-runtime-conversion-wiring' +import { enableMovedOrcadAutomationsForTarget } from '../../../persistence/migrating-orcad-catalog/retained-source/orcad-migration-moved-automations' import { requiredString } from './orcad-runtime-lifecycle-handlers' import { publishResolvedChangedHostStatus } from './runtime-environment-managed-tunnel' -import { runTargetLifecycle } from '../ssh/ssh-target-lifecycle-queue' +import { runTargetLifecycle } from '../../ssh/ssh-target-lifecycle-queue' export function registerOrcadDeltaMoveHandlers(getUserDataPath: () => string): void { ipcMain.handle( diff --git a/src/main/ipc/runtime-environments/orcad-leave-behind-handlers.ts b/src/main/ipc/runtime-environments/managed-orcad/orcad-leave-behind-handlers.ts similarity index 90% rename from src/main/ipc/runtime-environments/orcad-leave-behind-handlers.ts rename to src/main/ipc/runtime-environments/managed-orcad/orcad-leave-behind-handlers.ts index 780cdade1b3..9b60a86ad13 100644 --- a/src/main/ipc/runtime-environments/orcad-leave-behind-handlers.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/orcad-leave-behind-handlers.ts @@ -1,6 +1,6 @@ /** IPC for "Move anyway": the user confirms that saved state a move can't carry stays on this desktop. */ import { ipcMain } from 'electron' -import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' +import { getSshTargetRegistryStore } from '../../../ssh/targets/ssh-target-registry' import { requiredString } from './orcad-runtime-lifecycle-handlers' export function registerOrcadLeaveBehindHandlers(): void { diff --git a/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-conversion-handlers.ts b/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-conversion-handlers.ts new file mode 100644 index 00000000000..4e3cb314d67 --- /dev/null +++ b/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-conversion-handlers.ts @@ -0,0 +1,29 @@ +import { ipcMain } from 'electron' +import type { + OrcadManagedConversionResult, + OrcadManagedPendingMigrationRow +} from '../../../../shared/orcad-managed-runtime' +import { listPendingManagedOrcadMigrations } from '../../../managed-server/lifecycle/orcad-managed-migration-status' +import { convertSshTargetToManagedOrcad } from '../../../managed-server/lifecycle/orcad-runtime-conversion' +import { conversionCollaborators } from '../../../managed-server/lifecycle/orcad-runtime-conversion-wiring' +import { requiredString } from './orcad-runtime-lifecycle-handlers' + +export function registerOrcadRuntimeConversionHandlers(getUserDataPath: () => string): void { + ipcMain.handle( + 'runtimeEnvironments:convertSshHostToManagedOrcad', + ( + _event, + args: { sshTargetId: string; name: string } + ): Promise => { + return convertSshTargetToManagedOrcad(getUserDataPath(), { + sshTargetId: requiredString(args?.sshTargetId, 'SSH target'), + name: requiredString(args?.name, 'Server name'), + ...conversionCollaborators() + }) + } + ) + ipcMain.handle( + 'runtimeEnvironments:listPendingOrcadMigrations', + (): OrcadManagedPendingMigrationRow[] => listPendingManagedOrcadMigrations(getUserDataPath()) + ) +} diff --git a/src/main/ipc/runtime-environments/orcad-runtime-lifecycle-handlers.ts b/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-lifecycle-handlers.ts similarity index 76% rename from src/main/ipc/runtime-environments/orcad-runtime-lifecycle-handlers.ts rename to src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-lifecycle-handlers.ts index 7b49728998f..da4346f197d 100644 --- a/src/main/ipc/runtime-environments/orcad-runtime-lifecycle-handlers.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-lifecycle-handlers.ts @@ -1,7 +1,7 @@ import { ipcMain } from 'electron' -import type { OrcadManagedRuntimeStatus } from '../../../shared/orcad-managed-runtime' -import { createManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-runtime-deployment' -import { getManagedOrcadRuntimeStatus } from '../../managed-server/lifecycle/orcad-runtime-status' +import type { OrcadManagedRuntimeStatus } from '../../../../shared/orcad-managed-runtime' +import { createManagedOrcadEnvironment } from '../../../managed-server/lifecycle/orcad-runtime-deployment' +import { getManagedOrcadRuntimeStatus } from '../../../managed-server/lifecycle/orcad-runtime-status' export function registerOrcadRuntimeLifecycleHandlers(options: { getUserDataPath: () => string diff --git a/src/main/ipc/runtime-environments/orcad-runtime-maintenance-handlers.ts b/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-maintenance-handlers.ts similarity index 96% rename from src/main/ipc/runtime-environments/orcad-runtime-maintenance-handlers.ts rename to src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-maintenance-handlers.ts index 0dd3de7bc49..28163e475b8 100644 --- a/src/main/ipc/runtime-environments/orcad-runtime-maintenance-handlers.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/orcad-runtime-maintenance-handlers.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import { registerManagedServerActions } from '../../runtime/hosts/management/managed-server-actions-registry' +import { registerManagedServerActions } from '../../../runtime/hosts/management/managed-server-actions-registry' import { createManagedOrcadActions, reclaimManagedOrcadStaleLock, diff --git a/src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts b/src/main/ipc/runtime-environments/managed-orcad/runtime-environment-managed-tunnel.ts similarity index 85% rename from src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts rename to src/main/ipc/runtime-environments/managed-orcad/runtime-environment-managed-tunnel.ts index 21c7d4622f8..9a003ec40b0 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/runtime-environment-managed-tunnel.ts @@ -1,48 +1,48 @@ -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import { getOrcadSshDeployment, type KnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { classifyRuntimeEnvironmentHost } from '../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { classifyRuntimeEnvironmentHost } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' import type { SshManagedServerStatus, SshManagedServerUpdateNote, SshTarget -} from '../../../shared/ssh-types' -import { managedServerUpdateDeps } from '../../ssh/host-server/managed-server-update-deps' +} from '../../../../shared/ssh-types' +import { managedServerUpdateDeps } from '../../../ssh/host-server/managed-server-update-deps' import { ensureOrcadManagedTunnel, rebuildOrcadManagedTunnel -} from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { verifyOrcadManagedServing } from '../../managed-server/lifecycle/orcad-managed-serving-verify' +} from '../../../managed-server/lifecycle/orcad-managed-tunnel' +import { verifyOrcadManagedServing } from '../../../managed-server/lifecycle/orcad-managed-serving-verify' import { getManagedOrcadCrashLoopBrake, OrcadCrashLoopError -} from '../../managed-server/lifecycle/orcad-managed-crash-loop' +} from '../../../managed-server/lifecycle/orcad-managed-crash-loop' import { MANAGED_ORCAD_NOT_ACTIVATED_DETAIL, setManagedOrcadStartListener, type OrcadManagedServing -} from '../../managed-server/lifecycle/orcad-managed-serving' +} from '../../../managed-server/lifecycle/orcad-managed-serving' import { redeployStoppedManagedOrcad, updateManagedOrcadOnRestore -} from '../../managed-server/lifecycle/orcad-managed-update-on-restore' +} from '../../../managed-server/lifecycle/orcad-managed-update-on-restore' import { getSshHostServerStatus, setSshHostServerStatus -} from '../../ssh/host-server/ssh-host-server-status' -import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' -import { connectionManager, getCurrentMainWindow } from '../ssh/ssh-ipc-context' +} from '../../../ssh/host-server/ssh-host-server-status' +import { getSshTargetRegistryStore } from '../../../ssh/targets/ssh-target-registry' +import { connectionManager, getCurrentMainWindow } from '../../ssh/ssh-ipc-context' import { getWslHostPhoneGate, getWslHostService -} from '../../wsl/host-lifecycle/wsl-host-service-instance' -import { assertWslHostReachable } from '../../wsl/host-lifecycle/wsl-host-gate' -import { wslHostPhoneRefusal } from '../../wsl/host-lifecycle/wsl-host-phone-reach' -import { broadcastSshState } from '../ssh/ssh-renderer-broadcast' -import { restoreManagedHostPortForwards } from '../ssh/ssh-managed-port-forward-restore' -import { recipeVmWakeIntentFor } from '../../../shared/remote-runtime/recipe-vm-wake' +} from '../../../wsl/host-lifecycle/wsl-host-service-instance' +import { assertWslHostReachable } from '../../../wsl/host-lifecycle/wsl-host-gate' +import { wslHostPhoneRefusal } from '../../../wsl/host-lifecycle/wsl-host-phone-reach' +import { broadcastSshState } from '../../ssh/ssh-renderer-broadcast' +import { restoreManagedHostPortForwards } from '../../ssh/ssh-managed-port-forward-restore' +import { recipeVmWakeIntentFor } from '../../../../shared/remote-runtime/recipe-vm-wake' import { prepareRecipeVm } from './runtime-environment-recipe-vm-wake' /** `wslStart: 'never'` serves a WSL host only while it runs: a paired phone never boots a distro. @@ -175,7 +175,7 @@ async function prepareNetworkServerForCall( if (targetId) { // Publish the warning after update status settles; import lazily to break the publishing cycle. void Promise.resolve(update) - .then(() => import('../ssh/ssh-host-launch-session-note')) + .then(() => import('../../ssh/ssh-host-launch-session-note')) .then(({ noteEndedLaunchSshSession }) => noteEndedLaunchSshSession(targetId, environment.id) ) @@ -194,7 +194,7 @@ function restoreForwardsOverTunnel(environment: KnownRuntimeEnvironment): void { async function forgetLaunchSessionVerdictLazily(targetId: string): Promise { // Import lazily because the note module publishes through this module. - const { forgetLaunchSessionVerdict } = await import('../ssh/ssh-host-launch-session-note') + const { forgetLaunchSessionVerdict } = await import('../../ssh/ssh-host-launch-session-note') forgetLaunchSessionVerdict(targetId) } diff --git a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts b/src/main/ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake.test.ts similarity index 80% rename from src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts rename to src/main/ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake.test.ts index 365f916716a..dfce1a07551 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake.test.ts @@ -3,38 +3,29 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { removeTempDirs } from '../../../shared/testing/remove-temp-dirs.test-support' +import { removeTempDirs } from '../../../../shared/testing/remove-temp-dirs.test-support' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { upsertEphemeralVmRuntime } from '../../../shared/ephemeral-vm-runtime-store' -import type { EphemeralVmRuntimeStatus } from '../../../shared/ephemeral-vm-runtimes' -import { registerRecipeVmWaker } from '../../runtime/workspaces/sleep/recipe-vm-waker-registry' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { upsertEphemeralVmRuntime } from '../../../../shared/ephemeral-vm-runtime-store' +import type { EphemeralVmRuntimeStatus } from '../../../../shared/ephemeral-vm-runtimes' +import { registerRecipeVmWaker } from '../../../runtime/workspaces/sleep/recipe-vm-waker-registry' import type { RecipeVmOpening, RecipeVmState -} from '../../runtime/workspaces/sleep/recipe-vm-operations' +} from '../../../runtime/workspaces/sleep/recipe-vm-operations' import { prepareRecipeVm } from './runtime-environment-recipe-vm-wake' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' import { forgetRecipeVmWakePairingsForTests, noteRecipeVmWakePairing -} from '../../ephemeral-vm/recipe-vm-wake-pairings' +} from '../../../ephemeral-vm/recipe-vm-wake-pairings' import { clearRuntimeEnvironmentManualDisconnect, markRuntimeEnvironmentManuallyDisconnected -} from './runtime-environment-manual-disconnect' +} from '../connectivity/runtime-environment-manual-disconnect' const VM_ENVIRONMENT = { id: 'env-vm', source: 'ephemeral-vm' as const } -const SSH_VM_ENVIRONMENT = { - id: 'env-ssh-vm', - orcadDeployment: { - sshTargetId: 'runtime-ssh-vm-2', - sshTargetGeneration: 1, - localPort: 41_000, - remotePort: 6768 - } -} let userDataPath = '' @@ -115,8 +106,6 @@ describe('a request to a recipe VM environment', () => { async (status) => { recordVm(status) await expect(codeOf('none')).resolves.toBe('runtime_environment_asleep') - expect(state).toHaveBeenCalledWith('workspace-of-vm-1', true) - expect(holdOpen).not.toHaveBeenCalled() } ) @@ -140,7 +129,6 @@ describe('a request to a recipe VM environment', () => { markRuntimeEnvironmentManuallyDisconnected(VM_ENVIRONMENT.id) try { await expect(codeOf('wake')).resolves.toBe('runtime_manually_disconnected') - expect(holdOpen).not.toHaveBeenCalled() } finally { clearRuntimeEnvironmentManualDisconnect(VM_ENVIRONMENT.id) } @@ -198,15 +186,8 @@ describe('a request to a recipe VM environment', () => { } }) - it("finds an SSH-connected VM by its runtime-owned target's environment", async () => { - recordVm('suspended', SSH_VM_ENVIRONMENT.id, 'vm-2') - await expect(codeOf('wake', SSH_VM_ENVIRONMENT)).resolves.toBeNull() - expect(holdOpen).toHaveBeenCalledWith('workspace-of-vm-2', true, 180_000, undefined) - }) - it('never treats a user-paired server as a VM, even under a recorded id', async () => { recordVm('suspended', 'env-manual') await expect(codeOf('none', { id: 'env-manual', source: 'manual' })).resolves.toBeNull() - expect(state).not.toHaveBeenCalled() }) }) diff --git a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts b/src/main/ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake.ts similarity index 87% rename from src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts rename to src/main/ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake.ts index f906a8612f9..86d72053ac2 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts +++ b/src/main/ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake.ts @@ -1,10 +1,10 @@ import { findEnvironmentEphemeralVmRuntime, isEphemeralVmSuspended -} from '../../../shared/ephemeral-vm-environment-sleep' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' +} from '../../../../shared/ephemeral-vm-environment-sleep' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' import { RECIPE_VM_OPEN_HOLD_MS, RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE, @@ -15,18 +15,18 @@ import { RUNTIME_ENVIRONMENT_WAKING_ERROR_CODE, RUNTIME_ENVIRONMENT_WAKING_MESSAGE, type RecipeVmWakeIntent -} from '../../../shared/remote-runtime/recipe-vm-wake' -import { getRecipeVmWaker } from '../../runtime/workspaces/sleep/recipe-vm-waker-registry' -import { latestRecipeVmWake } from '../../ephemeral-vm/recipe-vm-wake-pairings' +} from '../../../../shared/remote-runtime/recipe-vm-wake' +import { getRecipeVmWaker } from '../../../runtime/workspaces/sleep/recipe-vm-waker-registry' +import { latestRecipeVmWake } from '../../../ephemeral-vm/recipe-vm-wake-pairings' import { isRuntimeEnvironmentManuallyDisconnected, runtimeEnvironmentManualDisconnectCount, runtimeEnvironmentManualDisconnectReason -} from './runtime-environment-manual-disconnect' +} from '../connectivity/runtime-environment-manual-disconnect' import type { RecipeVmOpening, RecipeVmState -} from '../../runtime/workspaces/sleep/recipe-vm-operations' +} from '../../../runtime/workspaces/sleep/recipe-vm-operations' type RecipeVmEnvironment = Pick diff --git a/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts b/src/main/ipc/runtime-environments/mobile-relay/runtime-environment-mobile-relay-hosts.ts similarity index 83% rename from src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts rename to src/main/ipc/runtime-environments/mobile-relay/runtime-environment-mobile-relay-hosts.ts index f2203bafd2b..318f04c0852 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts +++ b/src/main/ipc/runtime-environments/mobile-relay/runtime-environment-mobile-relay-hosts.ts @@ -1,54 +1,54 @@ import { pairedRuntimeBrowserClientHostId, pairedRuntimeBrowserClientHostsPage -} from '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' -import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { prepareRuntimeEnvironmentBrowserPlacement } from './runtime-environment-browser-placement' +} from '../../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { prepareRuntimeEnvironmentBrowserPlacement } from '../browser-hosting/runtime-environment-browser-placement' import { getPreferredPairingOffer, type KnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { classifyRuntimeEnvironmentHost } from '../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { classifyRuntimeEnvironmentHost } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' import { runtimeEnvironmentStatusFromSnapshot, type RuntimeEnvironmentStatus -} from '../../../shared/remote-runtime/host-status/runtime-host-status' +} from '../../../../shared/remote-runtime/host-status/runtime-host-status' import type { MobileDesktopRelayHosts, MobileDesktopRelayHostWatch -} from '../../runtime/mobile-desktop-relay/mobile-desktop-relay-hosts' +} from '../../../runtime/mobile-desktop-relay/mobile-desktop-relay-hosts' import { prepareManagedRuntimeRequest, type ManagedRuntimeCallPreparation -} from './runtime-environment-managed-tunnel' -import { wslHostsGateOpen } from '../../wsl/host-lifecycle/wsl-host-gate' -import type { WslHostPhoneReach } from '../../wsl/host-lifecycle/wsl-host-phone-reach' +} from '../managed-orcad/runtime-environment-managed-tunnel' +import { wslHostsGateOpen } from '../../../wsl/host-lifecycle/wsl-host-gate' +import type { WslHostPhoneReach } from '../../../wsl/host-lifecycle/wsl-host-phone-reach' import { getWslHostPhoneGate, onWslHostStatusesChanged -} from '../../wsl/host-lifecycle/wsl-host-service-instance' -import type { SshConnectionState } from '../../../shared/ssh-types' +} from '../../../wsl/host-lifecycle/wsl-host-service-instance' +import type { SshConnectionState } from '../../../../shared/ssh-types' import { getRegisteredSshState, listRegisteredSshTargets -} from '../../ssh/targets/ssh-target-registry' -import { getRuntimeEnvironmentStatusSnapshots } from './runtime-environment-request-connections' +} from '../../../ssh/targets/ssh-target-registry' +import { getRuntimeEnvironmentStatusSnapshots } from '../connections/runtime-environment-request-connections' import { callRuntimeEnvironment, subscribeRuntimeEnvironment -} from './runtime-environment-transport-routing' -import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' -import { isRuntimeSubscriptionReplayResponse } from '../../../shared/runtime-subscription-replay' +} from '../requests/runtime-environment-transport-routing' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import { isRuntimeSubscriptionReplayResponse } from '../../../../shared/runtime-subscription-replay' import { isRuntimeEnvironmentManuallyDisconnected, runtimeEnvironmentManualDisconnectCount -} from './runtime-environment-manual-disconnect' -import { onRuntimeEnvironmentStatusPublished } from './runtime-environment-status-owner' -import { watchRuntimeEnvironmentRegistry } from './runtime-environment-preference' -import { getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' -import { getRuntimeEnvironmentRegistryRoot } from './runtime-environment-registry-root' -import { recipeVmServerState } from './runtime-environment-recipe-vm-wake' -import { RECIPE_VM_PHONE_OPEN_HOLD_MS } from '../../../shared/remote-runtime/recipe-vm-wake' +} from '../connectivity/runtime-environment-manual-disconnect' +import { onRuntimeEnvironmentStatusPublished } from '../status/runtime-environment-status-owner' +import { watchRuntimeEnvironmentRegistry } from '../catalog/runtime-environment-preference' +import { getRuntimeEnvironmentTransportGeneration } from '../connections/runtime-environment-transport-generation' +import { getRuntimeEnvironmentRegistryRoot } from '../catalog/runtime-environment-registry-root' +import { recipeVmServerState } from '../managed-orcad/runtime-environment-recipe-vm-wake' +import { RECIPE_VM_PHONE_OPEN_HOLD_MS } from '../../../../shared/remote-runtime/recipe-vm-wake' const retirementListeners = new Set<(environmentId: string) => void>() diff --git a/src/main/ipc/runtime-environments/orcad-runtime-conversion-handlers.ts b/src/main/ipc/runtime-environments/orcad-runtime-conversion-handlers.ts deleted file mode 100644 index 514945350c0..00000000000 --- a/src/main/ipc/runtime-environments/orcad-runtime-conversion-handlers.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { ipcMain } from 'electron' -import type { - OrcadManagedConversionResult, - OrcadManagedPendingMigrationRow -} from '../../../shared/orcad-managed-runtime' -import { listPendingManagedOrcadMigrations } from '../../managed-server/lifecycle/orcad-managed-migration-status' -import { convertSshTargetToManagedOrcad } from '../../managed-server/lifecycle/orcad-runtime-conversion' -import { conversionCollaborators } from '../../managed-server/lifecycle/orcad-runtime-conversion-wiring' -import { requiredString } from './orcad-runtime-lifecycle-handlers' - -export function registerOrcadRuntimeConversionHandlers(getUserDataPath: () => string): void { - ipcMain.handle( - 'runtimeEnvironments:convertSshHostToManagedOrcad', - ( - _event, - args: { sshTargetId: string; name: string } - ): Promise => { - return convertSshTargetToManagedOrcad(getUserDataPath(), { - sshTargetId: requiredString(args?.sshTargetId, 'SSH target'), - name: requiredString(args?.name, 'Server name'), - ...conversionCollaborators() - }) - } - ) - ipcMain.handle( - 'runtimeEnvironments:listPendingOrcadMigrations', - (): OrcadManagedPendingMigrationRow[] => listPendingManagedOrcadMigrations(getUserDataPath()) - ) -} diff --git a/src/main/ipc/runtime-environments/pairing/runtime-environment-managed-pairing-refusal.test.ts b/src/main/ipc/runtime-environments/pairing/runtime-environment-managed-pairing-refusal.test.ts new file mode 100644 index 00000000000..7f2e7a72c31 --- /dev/null +++ b/src/main/ipc/runtime-environments/pairing/runtime-environment-managed-pairing-refusal.test.ts @@ -0,0 +1,42 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { OrcadManagedIdentityError } from '../../../managed-server/lifecycle/orcad-managed-tunnel-identity' + +const mocks = vi.hoisted(() => ({ authenticationRejected: vi.fn() })) + +vi.mock('../../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ + resolveEnvironment: () => ({ + id: 'env-1', + orcadDeployment: { sshTargetId: 'ssh-1', sshTargetGeneration: 1, localPort: 1, remotePort: 2 } + }) +})) +vi.mock('../connections/runtime-environment-request-connections', () => ({ + getRuntimeEnvironmentStatusOwner: () => ({ + authenticationRejected: mocks.authenticationRejected + }) +})) +vi.mock('../../../managed-server/lifecycle/orcad-managed-tunnel', () => ({ + managedOrcadPairingFailureStands: vi.fn(), + recoverRefusedManagedOrcadPairing: vi.fn() +})) + +const { handleManagedSharedControlRefusal } = + await import('./runtime-environment-managed-pairing-refusal') + +describe('handleManagedSharedControlRefusal', () => { + beforeEach(() => mocks.authenticationRejected.mockReset()) + + it('stops retrying a pairing whose host now serves another server key (#37766)', async () => { + const refusal = OrcadManagedIdentityError.replacedServer( + { id: 'env-1', name: 'dev box' }, + 'a different key' + ) + await expect( + handleManagedSharedControlRefusal( + '/profile', + 'env-1', + () => Promise.reject(refusal), + () => true + ) + ).resolves.toBe('stop') + }) +}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-managed-pairing-refusal.ts b/src/main/ipc/runtime-environments/pairing/runtime-environment-managed-pairing-refusal.ts similarity index 79% rename from src/main/ipc/runtime-environments/runtime-environment-managed-pairing-refusal.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environment-managed-pairing-refusal.ts index ec561f363bf..a215ded6ad6 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-managed-pairing-refusal.ts +++ b/src/main/ipc/runtime-environments/pairing/runtime-environment-managed-pairing-refusal.ts @@ -1,12 +1,12 @@ -import { errorMessage } from '../../../shared/error-message' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getOrcadSshDeployment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { managedOrcadRefusalNeedingUserCode } from '../../managed-server/lifecycle/orcad-managed-tunnel-identity' +import { errorMessage } from '../../../../shared/error-message' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getOrcadSshDeployment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { managedOrcadRefusalNeedingUserCode } from '../../../managed-server/lifecycle/orcad-managed-tunnel-identity' import { managedOrcadPairingFailureStands, recoverRefusedManagedOrcadPairing -} from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { getRuntimeEnvironmentStatusOwner } from './runtime-environment-request-connections' +} from '../../../managed-server/lifecycle/orcad-managed-tunnel' +import { getRuntimeEnvironmentStatusOwner } from '../connections/runtime-environment-request-connections' /** Null leaves user-managed pairing recovery to the caller. */ export function recoverRefusedManagedPairing( diff --git a/src/main/ipc/runtime-environments/runtime-environment-pairing-refusal-registry.ts b/src/main/ipc/runtime-environments/pairing/runtime-environment-pairing-refusal-registry.ts similarity index 100% rename from src/main/ipc/runtime-environments/runtime-environment-pairing-refusal-registry.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environment-pairing-refusal-registry.ts diff --git a/src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts b/src/main/ipc/runtime-environments/pairing/runtime-environment-pairing-verification.ts similarity index 87% rename from src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environment-pairing-verification.ts index 8be6b2b0b06..4e89031d980 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts +++ b/src/main/ipc/runtime-environments/pairing/runtime-environment-pairing-verification.ts @@ -1,33 +1,33 @@ -import { pairedRuntimeConnectionFromOffer } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' +import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import { addOrUpdateEnvironmentFromPairingCode, resolveEnvironment, updateEnvironmentFromPairingCode -} from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { RuntimeEnvironmentStoreError } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { RuntimeEnvironmentStoreError } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' import { parseHostAccessLink, type ParsedHostAccessLink -} from '../../../shared/remote-runtime/pairing/remote-pairing-address' +} from '../../../../shared/remote-runtime/pairing/remote-pairing-address' import { verifyRemotePairingRuntimeStatus, type RemotePairingFailure, type VerifyAndAddRuntimeEnvironmentResult -} from '../../../shared/remote-runtime/pairing/remote-pairing-verification' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import { exchangeRemotePairingTicket } from '../../../shared/remote-runtime/pairing/remote-pairing-ticket-exchange' -import { sendRemoteRuntimeRequestOnSocket } from '../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' +} from '../../../../shared/remote-runtime/pairing/remote-pairing-verification' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' +import { exchangeRemotePairingTicket } from '../../../../shared/remote-runtime/pairing/remote-pairing-ticket-exchange' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' import { getPreferredPairingOffer, isEphemeralVmRuntimeEnvironment, redactRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' import { remoteServerPairingFailureText, type RemoteServerPairingFailureCode -} from '../../../shared/remote-runtime/pairing/remote-server-pairing-failure-copy' +} from '../../../../shared/remote-runtime/pairing/remote-server-pairing-failure-copy' type VerifyAndAddRuntimeEnvironmentArgs = { name: string diff --git a/src/main/ipc/runtime-environments/runtime-environment-repair-handler.ts b/src/main/ipc/runtime-environments/pairing/runtime-environment-repair-handler.ts similarity index 93% rename from src/main/ipc/runtime-environments/runtime-environment-repair-handler.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environment-repair-handler.ts index b83f5beb35f..ce7d8c48f2b 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-repair-handler.ts +++ b/src/main/ipc/runtime-environments/pairing/runtime-environment-repair-handler.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import type { VerifyAndAddRuntimeEnvironmentResult } from '../../../shared/remote-runtime/pairing/remote-pairing-verification' +import type { VerifyAndAddRuntimeEnvironmentResult } from '../../../../shared/remote-runtime/pairing/remote-pairing-verification' import { verifyAndRepairRuntimeEnvironmentFromPairingCode } from './runtime-environment-pairing-verification' import { publishVerifiedPairing } from './runtime-environment-verified-pairing-publish' diff --git a/src/main/ipc/runtime-environments/runtime-environment-verified-pairing-publish.ts b/src/main/ipc/runtime-environments/pairing/runtime-environment-verified-pairing-publish.ts similarity index 78% rename from src/main/ipc/runtime-environments/runtime-environment-verified-pairing-publish.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environment-verified-pairing-publish.ts index e306b6acdc3..d0f1d4db5dd 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-verified-pairing-publish.ts +++ b/src/main/ipc/runtime-environments/pairing/runtime-environment-verified-pairing-publish.ts @@ -1,7 +1,7 @@ -import type { VerifyAndAddRuntimeEnvironmentResult } from '../../../shared/remote-runtime/pairing/remote-pairing-verification' -import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getRuntimeEnvironmentStatusOwner } from './runtime-environment-request-connections' -import { clearRuntimeEnvironmentManualDisconnect } from './runtime-environment-manual-disconnect' +import type { VerifyAndAddRuntimeEnvironmentResult } from '../../../../shared/remote-runtime/pairing/remote-pairing-verification' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getRuntimeEnvironmentStatusOwner } from '../connections/runtime-environment-request-connections' +import { clearRuntimeEnvironmentManualDisconnect } from '../connectivity/runtime-environment-manual-disconnect' type VerifiedPairing = Extract diff --git a/src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts b/src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts similarity index 88% rename from src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts index 38930572d08..03ea376b9ed 100644 --- a/src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts +++ b/src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts @@ -1,9 +1,9 @@ -import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' +import { resetRuntimeEnvironmentStatusOwners } from '../connections/runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as environmentStore from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import * as environmentStore from '../../../../shared/remote-runtime/host-store/runtime-environment-store' const { handleMock, @@ -48,15 +48,15 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ sendRemoteRuntimeRequestOnSocket: sendRemoteRuntimeRequestMock })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', () => ({ subscribeRemoteRuntimeTransport: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', async () => { - const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') +vi.mock('../connections/runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('../runtime-environments-ipc-test-harness') return withRuntimeStatusOwners({ sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, @@ -72,8 +72,8 @@ vi.mock('./runtime-environment-request-connections', async () => { }) }) -import { registerRuntimeEnvironmentHandlers } from './runtime-environments' -import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' +import { registerRuntimeEnvironmentHandlers } from '../runtime-environments' +import { channelHandlerLookup, pairingCode } from '../runtime-environments-ipc-test-harness' const handler = channelHandlerLookup(handleMock) @@ -148,7 +148,6 @@ describe('registerRuntimeEnvironmentHandlers', () => { ok: false, kind: 'host-unreachable' }) - expect(sendRemoteRuntimeRequestMock).not.toHaveBeenCalled() expect(environmentStore.listEnvironments(userDataPath)).toEqual([]) }) @@ -179,7 +178,6 @@ describe('registerRuntimeEnvironmentHandlers', () => { updatedExisting: true, environment: { id: saved.id, name: 'desk' } }) - expect(environmentStore.listEnvironments(userDataPath)).toHaveLength(1) expect(environmentStore.resolveEnvironmentPairingOffer(userDataPath, saved.id)).toMatchObject({ endpoint: 'ws://192.0.2.10:6768', deviceToken: 'second-token' diff --git a/src/main/ipc/runtime-environments/runtime-environments-repair.test.ts b/src/main/ipc/runtime-environments/pairing/runtime-environments-repair.test.ts similarity index 86% rename from src/main/ipc/runtime-environments/runtime-environments-repair.test.ts rename to src/main/ipc/runtime-environments/pairing/runtime-environments-repair.test.ts index 37e8847e92e..f4fe17452e5 100644 --- a/src/main/ipc/runtime-environments/runtime-environments-repair.test.ts +++ b/src/main/ipc/runtime-environments/pairing/runtime-environments-repair.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as environmentStore from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' +import * as environmentStore from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' const { handleMock, getPathMock, sendRemoteRuntimeRequestMock } = vi.hoisted(() => ({ handleMock: vi.fn(), @@ -22,15 +22,15 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ sendRemoteRuntimeRequestOnSocket: sendRemoteRuntimeRequestMock })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', () => ({ subscribeRemoteRuntimeTransport: vi.fn() })) -vi.mock('./runtime-environment-request-connections', async () => { - const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') +vi.mock('../connections/runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('../runtime-environments-ipc-test-harness') return withRuntimeStatusOwners({ sendRemoteRuntimeConnectionRequest: vi.fn(), sendRemoteRuntimeSharedControlRequest: vi.fn(() => new Promise(() => {})), @@ -44,13 +44,13 @@ vi.mock('./runtime-environment-request-connections', async () => { }) }) -import { registerRuntimeEnvironmentHandlers } from './runtime-environments' +import { registerRuntimeEnvironmentHandlers } from '../runtime-environments' import { getRuntimeEnvironmentStatusOwner, getRuntimeEnvironmentStatusSnapshots, resetRuntimeEnvironmentStatusOwners -} from './runtime-environment-request-connections' -import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' +} from '../connections/runtime-environment-request-connections' +import { channelHandlerLookup, pairingCode } from '../runtime-environments-ipc-test-harness' const handler = channelHandlerLookup(handleMock) const ENDPOINT = 'ws://192.168.1.20:6768' @@ -149,10 +149,9 @@ describe('runtimeEnvironments:repairFromPairingCode', () => { keyByte: 2 }) }) - ).resolves.toEqual({ + ).resolves.toMatchObject({ ok: false, - kind: 'different-server', - message: 'This pairing link is for a different server.' + kind: 'different-server' }) expect(savedToken()).toBe('revoked-token') }) @@ -162,7 +161,6 @@ describe('runtimeEnvironments:repairFromPairingCode', () => { await expect( repair(null, { selector: 'desk', pairingCode: 'not a link' }) ).resolves.toMatchObject({ ok: false, kind: 'access-link-invalid' }) - expect(sendRemoteRuntimeRequestMock).not.toHaveBeenCalled() sendRemoteRuntimeRequestMock.mockRejectedValue( new RemoteRuntimeClientError('unauthorized', 'rejected', { @@ -187,6 +185,5 @@ describe('runtimeEnvironments:repairFromPairingCode', () => { await expect( repair(null, { selector: 'vm', pairingCode: pairingCode(ENDPOINT, { keyByte: 2 }) }) ).resolves.toMatchObject({ ok: false, kind: 'environment-save-failed' }) - expect(sendRemoteRuntimeRequestMock).not.toHaveBeenCalled() }) }) diff --git a/src/main/ipc/runtime-environments/orchestration-environment-transport.ts b/src/main/ipc/runtime-environments/requests/orchestration-environment-transport.ts similarity index 83% rename from src/main/ipc/runtime-environments/orchestration-environment-transport.ts rename to src/main/ipc/runtime-environments/requests/orchestration-environment-transport.ts index 721ccd156c3..c20f4fc060a 100644 --- a/src/main/ipc/runtime-environments/orchestration-environment-transport.ts +++ b/src/main/ipc/runtime-environments/requests/orchestration-environment-transport.ts @@ -1,13 +1,13 @@ -import { getAppEnvironment } from '../../../shared/app-environment' -import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import { getAppEnvironment } from '../../../../shared/app-environment' +import { getPreferredPairedRuntimeConnection } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' import { listEnvironments, resolveEnvironment -} from '../../../shared/remote-runtime/host-store/runtime-environment-store' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import { pairedOrchestrationPeers, type OrchestrationEnvironmentTransport -} from '../../runtime/orchestration/federation/environment-transport' +} from '../../../runtime/orchestration/federation/environment-transport' /** Dials this host's paired servers for cross-server orchestration; host-free, so desktop and orcad share it. */ export function createOrchestrationEnvironmentTransport(): OrchestrationEnvironmentTransport { diff --git a/src/main/ipc/runtime-environments/runtime-environment-abortable-requests.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-abortable-requests.ts similarity index 86% rename from src/main/ipc/runtime-environments/runtime-environment-abortable-requests.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-abortable-requests.ts index c0123165250..75a1ce93b7d 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-abortable-requests.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-abortable-requests.ts @@ -1,15 +1,15 @@ -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' -import type { RuntimeCapability } from '../../../shared/protocol-version' -import { sendRemoteRuntimeRequestOnSocket } from '../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' +import type { RuntimeCapability } from '../../../../shared/protocol-version' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' import type { RuntimeRequestPreparation, RuntimeOrchestrationEnvelope, RuntimeRpcResponse -} from '../../../shared/runtime-rpc-envelope' +} from '../../../../shared/runtime-rpc-envelope' import { sendRemoteRuntimeConnectionRequest, sendRemoteRuntimeSharedControlRequest -} from './runtime-environment-request-connections' +} from '../connections/runtime-environment-request-connections' export function sendRemoteRuntimeRequestAbortable( connection: PairedRuntimeConnection, diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-call-failure.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-call-failure.ts new file mode 100644 index 00000000000..414e468a24e --- /dev/null +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-call-failure.ts @@ -0,0 +1,38 @@ +import type { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' +import { RuntimeRpcCallQueueOverloadError } from '../../../../shared/runtime-rpc-call-queue' +import type { RuntimeRpcFailure, RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import { runtimeEnvironmentManualDisconnectReason } from '../connectivity/runtime-environment-manual-disconnect' + +export function manuallyDisconnectedResponse( + environment: ReturnType +): RuntimeRpcResponse { + return { + id: 'runtime.manualDisconnect', + ok: false, + error: { + code: 'runtime_manually_disconnected', + message: runtimeEnvironmentManualDisconnectReason(environment.id) + }, + _meta: { runtimeId: environment.runtimeId } + } +} + +export function runtimeEnvironmentCallFailure( + environment: ReturnType, + method: string, + error: unknown +): RuntimeRpcFailure | null { + if ( + !(error instanceof RemoteRuntimeClientError) && + !(error instanceof RuntimeRpcCallQueueOverloadError) + ) { + return null + } + return { + id: method, + ok: false, + error: { code: error.code, message: error.message }, + _meta: { runtimeId: environment.runtimeId } + } +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-call-queue.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts similarity index 76% rename from src/main/ipc/runtime-environments/runtime-environment-call-queue.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts index 558fa9e21d5..e8cb219318e 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-call-queue.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts @@ -1,4 +1,4 @@ -import { RuntimeRpcCallQueuePool } from '../../../shared/runtime-rpc-call-queue' +import { RuntimeRpcCallQueuePool } from '../../../../shared/runtime-rpc-call-queue' const runtimeCallQueuePool = new RuntimeRpcCallQueuePool() diff --git a/src/main/ipc/runtime-environments/runtime-environment-call.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-call.ts similarity index 88% rename from src/main/ipc/runtime-environments/runtime-environment-call.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-call.ts index fedd8658d72..311e743348a 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-call.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-call.ts @@ -1,7 +1,7 @@ import type { RuntimeOrchestrationEnvelope, RuntimeRequestPreparation -} from '../../../shared/runtime-rpc-envelope' +} from '../../../../shared/runtime-rpc-envelope' /** One RPC as the runtime-environment routes send it, whichever socket carries it. */ export type RuntimeEnvironmentCall = { diff --git a/src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-federated-read-routing.test.ts similarity index 77% rename from src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-federated-read-routing.test.ts index b0598fa39e7..f1931eb68ca 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-federated-read-routing.test.ts @@ -1,4 +1,4 @@ -import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' +import { resetRuntimeEnvironmentStatusOwners } from '../connections/runtime-environment-request-connections' vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -7,13 +7,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createSharedControlTestServer, closeSharedControlTestServers -} from '../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' -import type { sendRemoteRuntimeRequestOnSocket } from '../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' +} from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' +import type { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' import { addEnvironmentFromPairingCode, markEnvironmentUsed -} from '../../../shared/remote-runtime/host-store/runtime-environment-store' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' const { sendRemoteRuntimeRequestOnSocketMock, sendRemoteRuntimeSharedControlRequestMock } = vi.hoisted(() => ({ @@ -21,12 +21,12 @@ const { sendRemoteRuntimeRequestOnSocketMock, sendRemoteRuntimeSharedControlRequ sendRemoteRuntimeSharedControlRequestMock: vi.fn() })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ sendRemoteRuntimeRequestOnSocket: sendRemoteRuntimeRequestOnSocketMock })) -vi.mock('./runtime-environment-request-connections', async () => { - const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') +vi.mock('../connections/runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('../runtime-environments-ipc-test-harness') return withRuntimeStatusOwners({ sendRemoteRuntimeConnectionRequest: vi.fn(), sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, @@ -37,11 +37,11 @@ vi.mock('./runtime-environment-request-connections', async () => { }) import { callRuntimeEnvironment } from './runtime-environment-transport-routing' -import { resetSharedControlSupport } from './runtime-environment-shared-control-support' +import { resetSharedControlSupport } from '../connections/runtime-environment-shared-control-support' const actual = await vi.importActual<{ sendRemoteRuntimeRequestOnSocket: typeof sendRemoteRuntimeRequestOnSocket -}>('../../../shared/remote-runtime/requests/remote-runtime-request-socket') +}>('../../../../shared/remote-runtime/requests/remote-runtime-request-socket') describe('federated read RPC transport routing', () => { let userDataPath: string diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.test.ts similarity index 90% rename from src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.test.ts index 18e6360355c..864b78df3ea 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.test.ts @@ -13,9 +13,11 @@ type Prepared = { } const prepared = vi.hoisted((): { current: Prepared | null } => ({ current: null })) const prepare = vi.hoisted(() => vi.fn(async () => prepared.current)) -vi.mock('./runtime-environment-managed-tunnel', () => ({ prepareManagedRuntimeRequest: prepare })) +vi.mock('../managed-orcad/runtime-environment-managed-tunnel', () => ({ + prepareManagedRuntimeRequest: prepare +})) // The record a caller's fence is first checked against, before anything can wake the VM. -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ +vi.mock('../../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ resolveEnvironment: () => prepared.current?.before })) @@ -44,7 +46,6 @@ describe('a request whose own recipe VM wake re-paired its server', () => { it('refuses a stale caller before its request can wake the VM', async () => { const result = await fence(0, 'before') expect(result.failure).toMatchObject({ ok: false }) - expect(prepare).not.toHaveBeenCalled() }) it('refuses an unrelated re-pair after its own wake', async () => { diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-preparation.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.ts similarity index 87% rename from src/main/ipc/runtime-environments/runtime-environment-request-preparation.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.ts index 5c5cc54739a..b25d370a9c4 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-preparation.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.ts @@ -1,11 +1,11 @@ -import type * as Rpc from '../../../shared/runtime-rpc-envelope' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type * as Rpc from '../../../../shared/runtime-rpc-envelope' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' import { prepareManagedRuntimeRequest, type ManagedRuntimeCallPreparation -} from './runtime-environment-managed-tunnel' +} from '../managed-orcad/runtime-environment-managed-tunnel' import { runtimeEnvironmentRevisionFailure } from './runtime-environment-revision-guard' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' type Expected = { pairingRevision: number | undefined; runtimeId: string | undefined } diff --git a/src/main/ipc/runtime-environments/runtime-environment-revision-guard.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-revision-guard.ts similarity index 85% rename from src/main/ipc/runtime-environments/runtime-environment-revision-guard.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-revision-guard.ts index e4f24c0fa55..6db3ef20bd1 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-revision-guard.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-revision-guard.ts @@ -1,5 +1,5 @@ -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' export function runtimeEnvironmentRevisionFailure( environment: KnownRuntimeEnvironment, diff --git a/src/main/ipc/runtime-environments/runtime-environment-runtime-pinned-send.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-runtime-pinned-send.ts similarity index 84% rename from src/main/ipc/runtime-environments/runtime-environment-runtime-pinned-send.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-runtime-pinned-send.ts index 983abd27969..7a80522a12b 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-runtime-pinned-send.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-runtime-pinned-send.ts @@ -1,10 +1,10 @@ -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' -import { sendRemoteRuntimeRequestOnSocket } from '../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' import { sendRemoteRuntimeRequestAbortable } from './runtime-environment-abortable-requests' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' -import { sendRemoteRuntimeSharedControlRequestOnRuntime } from './runtime-environment-request-connections' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import { sendRemoteRuntimeSharedControlRequestOnRuntime } from '../connections/runtime-environment-request-connections' import type { RuntimeEnvironmentCall } from './runtime-environment-call' import { runtimeEnvironmentChangedFailure } from './runtime-environment-revision-guard' diff --git a/src/main/ipc/runtime-environments/runtime-environment-support-routing.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-support-routing.ts similarity index 89% rename from src/main/ipc/runtime-environments/runtime-environment-support-routing.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-support-routing.ts index 59b39d5ce21..fcebb2663bd 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-support-routing.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-support-routing.ts @@ -1,31 +1,31 @@ -import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import type { PairedRuntimeConnection } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import type { RuntimeOrchestrationEnvelope, RuntimeRequestPreparation, RuntimeRpcResponse -} from '../../../shared/runtime-rpc-envelope' +} from '../../../../shared/runtime-rpc-envelope' import { type KnownRuntimeEnvironment, getPreferredPairedRuntimeConnection -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { recordRuntimeEnvironmentUsage } from '../../../shared/remote-runtime/host-store/runtime-environment-usage-record' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' -import '../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { recordRuntimeEnvironmentUsage } from '../../../../shared/remote-runtime/host-store/runtime-environment-usage-record' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint' import { isRuntimeEnvironmentCapabilityOutcomeCurrent, type RuntimeEnvironmentCapabilityOutcome -} from './runtime-environment-capability-evidence' +} from '../connections/runtime-environment-capability-evidence' import { runtimeEnvironmentChangedFailure, runtimeEnvironmentRevisionFailure } from './runtime-environment-revision-guard' -import { supportsSharedControl } from './runtime-environment-shared-control-support' +import { supportsSharedControl } from '../connections/runtime-environment-shared-control-support' import { sendRemoteRuntimeRequestAbortable, sendRemoteRuntimeSharedControlRequestAbortable @@ -33,7 +33,7 @@ import { import { getRemoteRuntimeSharedControlDiagnostics, subscribeRemoteRuntimeSharedControlRequest -} from './runtime-environment-request-connections' +} from '../connections/runtime-environment-request-connections' import { sendSupportRoutedCallOnRuntime } from './runtime-environment-runtime-pinned-send' type SupportRoute = { diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-tailscale-response.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-tailscale-response.ts new file mode 100644 index 00000000000..a95cf1616ce --- /dev/null +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-tailscale-response.ts @@ -0,0 +1,20 @@ +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint' + +export function withTailscaleHintForResponse( + response: RuntimeRpcResponse, + endpoint: string, + environment: Pick +): RuntimeRpcResponse { + if (response.ok === true) { + return response + } + return { + ...response, + error: { + ...response.error, + message: withRuntimeUnreachableHint(environment, response.error.message, endpoint) + } + } +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-transport-routing.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts similarity index 86% rename from src/main/ipc/runtime-environments/runtime-environment-transport-routing.ts rename to src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts index 0a4fcce7984..8190d290334 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-transport-routing.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts @@ -1,27 +1,27 @@ -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import { throwIfSignalAborted } from '../../../shared/abort-signal-reason' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' +import { throwIfSignalAborted } from '../../../../shared/abort-signal-reason' import { type RuntimeEnvironmentSetupFailure, runtimeEnvironmentSetupFailure -} from '../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' -import { assertCrewSourceCurrent } from './runtime-environment-subscription-setup' -import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' -import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +import { assertCrewSourceCurrent } from '../subscriptions/runtime-environment-subscription-setup' +import { getRuntimeEnvironmentStatus } from '../status/runtime-environment-status-probe' +import { getPreferredPairedRuntimeConnection } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import { prepareFencedRuntimeRequest } from './runtime-environment-request-preparation' import { requireWslHostWithoutStart, resolveManagedRuntimeEnvironment, type ManagedRuntimeCallPreparation -} from './runtime-environment-managed-tunnel' -import { recordRuntimeEnvironmentUsage } from '../../../shared/remote-runtime/host-store/runtime-environment-usage-record' -import type * as Rpc from '../../../shared/runtime-rpc-envelope' -import '../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +} from '../managed-orcad/runtime-environment-managed-tunnel' +import { recordRuntimeEnvironmentUsage } from '../../../../shared/remote-runtime/host-store/runtime-environment-usage-record' +import type * as Rpc from '../../../../shared/runtime-rpc-envelope' +import '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint' -import { decodeRuntimeEnvironmentSubscriptionEvents } from './runtime-environment-subscription-events' +import { decodeRuntimeEnvironmentSubscriptionEvents } from '../subscriptions/runtime-environment-subscription-events' import { enqueueRuntimeCall } from './runtime-environment-call-queue' import { sendRemoteRuntimeConnectionRequestAbortable, @@ -34,7 +34,7 @@ import { shouldRouteSubscriptionBySupport, subscribeSupportRoutedRuntimeEnvironment } from './runtime-environment-support-routing' -import { shouldUseSharedControlEnvelope } from './runtime-environment-shared-control-envelope' +import { shouldUseSharedControlEnvelope } from '../connections/runtime-environment-shared-control-envelope' import { sendEnvelopedOneShotCall } from './runtime-environment-runtime-pinned-send' const DEFAULT_REMOTE_RUNTIME_TIMEOUT_MS = 15_000 diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-unreachable-hint.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-unreachable-hint.ts new file mode 100644 index 00000000000..0e0c354b739 --- /dev/null +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-unreachable-hint.ts @@ -0,0 +1,26 @@ +import { withRemoteRuntimeTailscaleHint } from '../../../../shared/remote-runtime/remote-runtime-tailscale-hint' +import { classifyRuntimeEnvironmentHost } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' + +const UNREACHABLE_RE = + /could not connect to the remote orca runtime|remote orca runtime closed the connection|timed out (?:waiting for|while connecting to) the remote orca runtime/i + +export function withRuntimeUnreachableHint( + environment: Pick, + message: string, + endpoint: string | null | undefined +): string { + const host = classifyRuntimeEnvironmentHost(environment) + switch (host.kind) { + case 'network': + return withRemoteRuntimeTailscaleHint(message, endpoint) + case 'ssh': + // An SSH tunnel already crosses networks; Tailscale cannot help it. + return message + case 'wsl': + // WSL is reached locally through wsl.exe; a Tailscale hint cannot help. + return UNREACHABLE_RE.test(message) + ? `${message} The Orca server in the WSL distro ${host.deployment.distro} isn’t answering; connect it again in Settings → Remote Orca Servers → WSL hosts.` + : message + } +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-call-failure.ts b/src/main/ipc/runtime-environments/runtime-environment-call-failure.ts deleted file mode 100644 index bfaa24a7903..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-call-failure.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import { RuntimeRpcCallQueueOverloadError } from '../../../shared/runtime-rpc-call-queue' -import type { RuntimeRpcFailure, RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import { runtimeEnvironmentManualDisconnectReason } from './runtime-environment-manual-disconnect' - -export function manuallyDisconnectedResponse( - environment: ReturnType -): RuntimeRpcResponse { - return { - id: 'runtime.manualDisconnect', - ok: false, - error: { - code: 'runtime_manually_disconnected', - message: runtimeEnvironmentManualDisconnectReason(environment.id) - }, - _meta: { runtimeId: environment.runtimeId } - } -} - -export function runtimeEnvironmentCallFailure( - environment: ReturnType, - method: string, - error: unknown -): RuntimeRpcFailure | null { - if ( - !(error instanceof RemoteRuntimeClientError) && - !(error instanceof RuntimeRpcCallQueueOverloadError) - ) { - return null - } - return { - id: method, - ok: false, - error: { code: error.code, message: error.message }, - _meta: { runtimeId: environment.runtimeId } - } -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-cli-removal-routing.test.ts b/src/main/ipc/runtime-environments/runtime-environment-cli-removal-routing.test.ts deleted file mode 100644 index 4d11dfe38e2..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-cli-removal-routing.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { pairedRuntimeConnectionFromOffer } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' - -import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' -import { - addEnvironmentFromPairingCode, - removeEnvironment -} from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getEnvironmentStorePath } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' -import { - getPreferredPairingOffer, - type KnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import { - applyRuntimeEnvironmentCapabilityVerdict, - captureRuntimeEnvironmentCapabilityEvidence, - resetRuntimeEnvironmentCapabilityEvidence, - runtimeEnvironmentCapabilityOutcome -} from './runtime-environment-capability-evidence' - -type ResponseCallbacks = { - onResponse: (response: RuntimeRpcResponse) => void -} - -const { subscribeMock, supportsMock } = vi.hoisted(() => ({ - subscribeMock: vi.fn(), - supportsMock: vi.fn() -})) - -vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) -vi.mock( - '../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', - async (importOriginal) => ({ - ...(await importOriginal()), - subscribeRemoteRuntimeTransport: subscribeMock - }) -) -vi.mock('./runtime-environment-shared-control-support', async (importOriginal) => ({ - ...(await importOriginal()), - supportsSharedControl: supportsMock -})) - -import { subscribeRuntimeEnvironment } from './runtime-environment-transport-routing' - -let userDataPath: string - -beforeEach(() => { - userDataPath = mkdtempSync(join(tmpdir(), 'orca-cli-removal-routing-')) - resetRuntimeEnvironmentCapabilityEvidence() - subscribeMock.mockReset() - supportsMock.mockReset() -}) - -afterEach(() => { - rmSync(userDataPath, { recursive: true, force: true }) -}) - -describe('runtime responses the app can no longer attribute to a saved server', () => { - it.each([ - ['direct subscription', 'browser.screencast'], - ['support-routed subscription on a host without shared control', 'files.watch'] - ])('forwards a %s response after `orca environment rm`', async (_label, method) => { - const { deliver, onEvent, environment } = await subscribed(method) - // Mirrors the CLI: it edits the store without telling the running app. - removeEnvironment(userDataPath, environment.id) - const response = { - id: method, - ok: true as const, - result: {}, - _meta: { runtimeId: 'r' } - } - - expect(() => deliver(response)).not.toThrow() - expect(onEvent).toHaveBeenCalledWith({ type: 'response', response }) - }) - - it.each([ - ['direct subscription', 'browser.screencast'], - ['support-routed subscription on a host without shared control', 'files.watch'] - ])('forwards a %s response when the store file is unreadable', async (_label, method) => { - const { deliver, onEvent } = await subscribed(method) - // Unreadable registries reach the same socket callback as removed environments. - writeFileSync(getEnvironmentStorePath(userDataPath), '{not json') - const response = { - id: method, - ok: true as const, - result: {}, - _meta: { runtimeId: 'r' } - } - - expect(() => deliver(response)).not.toThrow() - expect(onEvent).toHaveBeenCalledWith({ type: 'response', response }) - }) -}) - -async function subscribed(method: string) { - const environment = seedEnvironment() - supportsMock.mockResolvedValue(absentOutcome(environment)) - let callbacks: ResponseCallbacks | null = null - subscribeMock.mockImplementation( - async (_pairing, _method, _params, _timeoutMs, received: ResponseCallbacks) => { - callbacks = received - return { close: () => {} } satisfies Partial - } - ) - const onEvent = vi.fn() - await subscribeRuntimeEnvironment(userDataPath, environment.id, method, {}, 1000, { - onEvent, - onClose: () => {} - }) - return { - deliver: (response: RuntimeRpcResponse) => callbacks?.onResponse(response), - onEvent, - environment - } -} - -function seedEnvironment(): KnownRuntimeEnvironment { - return addEnvironmentFromPairingCode(userDataPath, { - name: 'dev box', - pairingCode: encodePairingOffer({ - v: 2, - endpoint: 'ws://127.0.0.1:6768', - deviceToken: 'device-token', - publicKeyB64: Buffer.from(new Uint8Array(32).fill(1)).toString('base64') - }) - }) -} - -function absentOutcome(environment: KnownRuntimeEnvironment) { - const evidence = captureRuntimeEnvironmentCapabilityEvidence( - environment.id, - pairedRuntimeConnectionFromOffer(getPreferredPairingOffer(environment)) - ) - applyRuntimeEnvironmentCapabilityVerdict({ - evidence, - verdict: 'absent', - runtimeId: 'r' - }) - return runtimeEnvironmentCapabilityOutcome(evidence, 'absent', 'r') -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-control-socket-close-trace.ts b/src/main/ipc/runtime-environments/runtime-environment-control-socket-close-trace.ts deleted file mode 100644 index 3a03bfea175..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-control-socket-close-trace.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { startSpan } from '../../observability/tracer' -import type { SharedControlSocketCloseRecord } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' - -/** One trace span per closed control socket, so a support bundle shows why a host reconnected. */ -export function traceSharedControlSocketClose( - environmentId: string, - record: SharedControlSocketCloseRecord -): void { - startSpan('remote-runtime.control-socket-close', { - kind: 'client', - attributes: { environmentId, ...record } - }).end() -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-diagnostics-broadcast.ts b/src/main/ipc/runtime-environments/runtime-environment-diagnostics-broadcast.ts deleted file mode 100644 index f730d00d460..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-diagnostics-broadcast.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' -import { RUNTIME_ENVIRONMENT_DIAGNOSTICS_CHANNEL } from '../../../shared/remote-runtime/host-catalog/runtime-environment-diagnostics' -import { getRuntimeDesktopSurface } from '../../runtime/construction/runtime-desktop-surface' - -export type RuntimeEnvironmentDiagnosticsEvent = { - environmentId: string - transportGeneration: number - diagnostics: RemoteRuntimeSharedConnectionDiagnostics -} - -export function publishRuntimeEnvironmentDiagnostics( - event: RuntimeEnvironmentDiagnosticsEvent -): void { - getRuntimeDesktopSurface().sendToRenderers?.(RUNTIME_ENVIRONMENT_DIAGNOSTICS_CHANNEL, event) -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-host-key.test.ts b/src/main/ipc/runtime-environments/runtime-environment-host-key.test.ts deleted file mode 100644 index 3f17deb6c81..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-host-key.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key' - -function environment(publicKeyB64: string): KnownRuntimeEnvironment { - return { - id: 'env-1', - name: 'Box', - createdAt: 1, - updatedAt: 1, - lastUsedAt: null, - runtimeId: null, - preferredEndpointId: 'ws', - endpoints: [ - { - id: 'ws', - kind: 'websocket', - label: 'Box', - endpoint: 'ws://127.0.0.1:46768/', - deviceToken: 'secret-token', - publicKeyB64 - } - ] - } -} - -describe('the public runtime environment record', () => { - it('carries a stable host key digest but never the key or the device token', () => { - const first = publicRuntimeEnvironmentWithHostKey(environment('key-a')) - const again = publicRuntimeEnvironmentWithHostKey(environment('key-a')) - const other = publicRuntimeEnvironmentWithHostKey(environment('key-b')) - - expect(first.hostKeyFingerprint).toMatch(/^[0-9a-f]{32}$/) - expect(again.hostKeyFingerprint).toBe(first.hostKeyFingerprint) - expect(other.hostKeyFingerprint).not.toBe(first.hostKeyFingerprint) - expect(JSON.stringify(first)).not.toMatch(/key-a|secret-token/) - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-host-service-ops.ts b/src/main/ipc/runtime-environments/runtime-environment-host-service-ops.ts deleted file mode 100644 index 379f0e0320a..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-host-service-ops.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { classifyRuntimeEnvironmentHost } from '../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { WslHostServerStop } from '../../../shared/wsl-host-types' -import { getWslHostService } from '../../wsl/host-lifecycle/wsl-host-service-instance' - -/** Explicit connection may boot the WSL distro. */ -export async function connectThroughOwningService( - environment: KnownRuntimeEnvironment -): Promise { - const host = classifyRuntimeEnvironmentHost(environment) - switch (host.kind) { - case 'wsl': - await getWslHostService()?.connect(environment.id) - break - case 'network': - case 'ssh': - break - } -} - -/** Null delegates removal to the generic store path. */ -export function removeThroughOwningService( - environment: KnownRuntimeEnvironment -): Promise | null { - const host = classifyRuntimeEnvironmentHost(environment) - switch (host.kind) { - case 'wsl': - // Also releases the distro's holder and drops the WSL record. - return getWslHostService()?.remove(environment.id) ?? null - case 'network': - case 'ssh': - return null - } -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-managed-pairing-refusal.test.ts b/src/main/ipc/runtime-environments/runtime-environment-managed-pairing-refusal.test.ts deleted file mode 100644 index e5584717def..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-managed-pairing-refusal.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { OrcadManagedIdentityError } from '../../managed-server/lifecycle/orcad-managed-tunnel-identity' - -const mocks = vi.hoisted(() => ({ authenticationRejected: vi.fn() })) - -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: () => ({ - id: 'env-1', - orcadDeployment: { sshTargetId: 'ssh-1', sshTargetGeneration: 1, localPort: 1, remotePort: 2 } - }) -})) -vi.mock('./runtime-environment-request-connections', () => ({ - getRuntimeEnvironmentStatusOwner: () => ({ - authenticationRejected: mocks.authenticationRejected - }) -})) -vi.mock('../../managed-server/lifecycle/orcad-managed-tunnel', () => ({ - managedOrcadPairingFailureStands: vi.fn(), - recoverRefusedManagedOrcadPairing: vi.fn() -})) - -const { handleManagedSharedControlRefusal } = - await import('./runtime-environment-managed-pairing-refusal') - -describe('handleManagedSharedControlRefusal', () => { - beforeEach(() => mocks.authenticationRejected.mockReset()) - - it('stops retrying a pairing whose host now serves another server key (#37766)', async () => { - const refusal = OrcadManagedIdentityError.replacedServer( - { id: 'env-1', name: 'dev box' }, - 'a different key' - ) - await expect( - handleManagedSharedControlRefusal( - '/profile', - 'env-1', - () => Promise.reject(refusal), - () => true - ) - ).resolves.toBe('stop') - expect(mocks.authenticationRejected).toHaveBeenCalledWith( - refusal.message, - 'orcad_server_replaced' - ) - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-pairing-ticket-exchange.test.ts b/src/main/ipc/runtime-environments/runtime-environment-pairing-ticket-exchange.test.ts deleted file mode 100644 index 1134563825b..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-pairing-ticket-exchange.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { - MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - RUNTIME_PROTOCOL_VERSION -} from '../../../shared/protocol-version' -import { resolveEnvironmentPairingOffer } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' -import { PAIRING_TICKET_EXCHANGE_RUNTIME_CAPABILITY } from '../../../shared/remote-runtime/pairing/ticket-exchange-capability' -import { verifyAndAddRuntimeEnvironmentFromPairingCode } from './runtime-environment-pairing-verification' - -const { sendMock } = vi.hoisted(() => ({ sendMock: vi.fn() })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ - sendRemoteRuntimeRequestOnSocket: sendMock -})) - -const pairingCode = encodePairingOffer({ - v: 2, - endpoint: 'ws://192.168.1.10:6768', - deviceToken: 'link-token', - publicKeyB64: 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBA=' -}) - -function status(capabilities: string[]) { - return { - runtimeId: 'remote-runtime', - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, - minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - capabilities - } -} - -describe('Add server with a pairing link', () => { - it.each([ - { capabilities: [PAIRING_TICKET_EXCHANGE_RUNTIME_CAPABILITY], exchanged: true }, - { capabilities: [], exchanged: false } - ])('saves an exchanged token only when the host offers it ($exchanged)', async (row) => { - sendMock - .mockReset() - .mockImplementation(async (_connection: unknown, method: string) => - method === 'status.get' - ? { ok: true, result: status(row.capabilities) } - : { ok: true, result: { deviceId: 'desktop' } } - ) - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-add-server-exchange-')) - - const result = await verifyAndAddRuntimeEnvironmentFromPairingCode(userDataPath, { - name: 'Studio', - pairingCode - }) - - expect(result.ok).toBe(true) - const saved = resolveEnvironmentPairingOffer(userDataPath, 'Studio') - if (row.exchanged) { - expect(saved.deviceToken).toMatch(/^[0-9a-f]{48}$/) - expect(sendMock).toHaveBeenCalledWith( - expect.anything(), - 'pairing.exchangeTicket', - { deviceToken: saved.deviceToken }, - expect.any(Number), - undefined, - undefined, - undefined, - undefined, - undefined, - undefined - ) - } else { - expect(saved.deviceToken).toBe('link-token') - expect(sendMock).toHaveBeenCalledTimes(1) - } - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-prompt-telemetry.test.ts b/src/main/ipc/runtime-environments/runtime-environment-prompt-telemetry.test.ts deleted file mode 100644 index 5ce10cfd948..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-prompt-telemetry.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { decodeRuntimeEnvironmentSubscriptionEvents } from './runtime-environment-subscription-events' -import { - cleanupTelemetryClientTest, - setupTelemetryClientTest, - type TelemetryClientTestState -} from '../../telemetry/client-test-harness' - -let state: TelemetryClientTestState -beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-11-08T23:58:00Z')) - state = setupTelemetryClientTest({ - optedIn: true, - installId: '00000000-0000-4000-8000-000000000000', - existedBeforeTelemetryRelease: false, - protectedMilestones: { installCohort: 'fresh' } - }) -}) -afterEach(() => { - cleanupTelemetryClientTest(state.envStash) - vi.useRealTimers() -}) - -const prompt = (client: 'desktop' | 'mobile' = 'desktop') => ({ - type: 'structuredChatPromptAccepted', - id: randomUUID(), - agent_kind: 'codex', - client -}) -const frame = (result: unknown) => ({ - type: 'response' as const, - response: { id: 'events-1', ok: true as const, result, _meta: { runtimeId: 'remote-runtime' } } -}) -const cursor = () => state.settings.telemetry?.protectedMilestones -const captured = (name: string) => - state.mock.capture.mock.calls.map(([event]) => event).filter((event) => event.event === name) - -it('consumes live accepted observations in desktop main once, without exposing their IDs to analytics', () => { - const delivered: unknown[] = [] - let current = false - const observe = decodeRuntimeEnvironmentSubscriptionEvents( - 'runtime.clientEvents.subscribe', - (event) => delivered.push(event), - () => current - ) - const event = prompt() - observe(frame(event)) - expect(cursor()).toEqual({ installCohort: 'fresh' }) - current = true - observe(frame(event)) - expect(cursor()).toEqual({ - installCohort: 'fresh', - firstAgentInteractionDay: 20_765, - meaningfulActivityDay: 20_765 - }) - expect(captured('first_agent_interaction')[0].properties).toMatchObject({ - source: 'native_chat', - agent_kind: 'codex' - }) - expect(captured('meaningful_activity_day')[0].properties.trigger).toBe('native_chat') - expect(delivered).toEqual([frame(event)]) - expect(JSON.stringify(state.mock.capture.mock.calls)).not.toContain(event.id) - - vi.setSystemTime(new Date('2026-11-09T00:01:00Z')) - observe(frame(event)) - expect(cursor()?.meaningfulActivityDay).toBe(20_765) - observe(frame(prompt('mobile'))) - expect(cursor()?.meaningfulActivityDay).toBe(20_766) - expect(captured('meaningful_activity_day').map((entry) => entry.properties.trigger)).toEqual([ - 'native_chat', - 'mobile_chat' - ]) -}) - -it('drops opted-out observations permanently and rejects unbounded or content-bearing facts', () => { - const observe = decodeRuntimeEnvironmentSubscriptionEvents( - 'runtime.clientEvents.subscribe', - () => {}, - () => true - ) - const event = prompt('mobile') - state.settings.telemetry!.optedIn = false - observe(frame(event)) - expect(cursor()).toEqual({ installCohort: 'fresh' }) - state.settings.telemetry!.optedIn = true - observe(frame(event)) - observe(frame({ ...prompt(), body: 'private prompt must never reach analytics' })) - observe(frame({ ...prompt(), agent_kind: 'arbitrary-agent-name' })) - const wrongMethod = decodeRuntimeEnvironmentSubscriptionEvents( - 'agentSession.subscribe', - () => {}, - () => true - ) - wrongMethod(frame(prompt())) - expect(cursor()).toEqual({ installCohort: 'fresh' }) - - observe(frame(prompt('mobile'))) - expect(cursor()).toEqual({ - installCohort: 'fresh', - firstAgentInteractionDay: 20_765, - meaningfulActivityDay: 20_765 - }) - expect(captured('first_agent_interaction')[0].properties.source).toBe('mobile_chat') -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-redundant-managed-removal.ts b/src/main/ipc/runtime-environments/runtime-environment-redundant-managed-removal.ts deleted file mode 100644 index ac8d27dea7a..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-redundant-managed-removal.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - redactRuntimeEnvironment, - type KnownRuntimeEnvironment, - type RuntimeEnvironmentRemoval -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { findManagedSshTwin } from '../../../shared/remote-runtime/host-catalog/runtime-environment-host-key-match' -import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { getManagedServerActions } from '../../runtime/hosts/management/managed-server-actions-registry' - -/** - * Removes one of two saved entries for a managed server reached through two SSH aliases. - * The other entry still manages that server, so this entry is unlinked here without touching the host. - * Null when no other entry manages the same server; the store's guard then keeps the pairing. - */ -export function removeRedundantManagedPairing( - userDataPath: string, - environment: KnownRuntimeEnvironment -): Promise | null { - const actions = getManagedServerActions() - if (!actions || !findManagedSshTwin(listEnvironments(userDataPath), environment)) { - return null - } - // Forget is the managed removal: it also closes this entry's tunnel and releases its SSH claims. - return actions.forgetRedundant(environment.id).then((result) => { - if (result.outcome === 'refused') { - throw new Error(result.reason) - } - return { removed: redactRuntimeEnvironment(environment) } - }) -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts b/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts deleted file mode 100644 index 38d96c12287..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { desktopChatCreationHistory } from '../../runtime/client/navigation/desktop-chat-creation-history' -import { revokeRemoteFilePreviewGrants } from '../../media/media-preview-protocol' -import { clearBrowserRoutePartitionStorageForEnvironment } from '../../browser/routing/partitions/browser-route-partition-storage-runtime' -import { retireBrowserRoutePartitionStorageForEnvironment } from '../../browser/routing/partitions/browser-route-partition-storage-retirement' -import { clearRuntimeEnvironmentCapabilityEvidence } from './runtime-environment-capability-evidence' -import { clearRuntimeEnvironmentManualDisconnect } from './runtime-environment-manual-disconnect' -import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { - forgetRemoteLayoutSnapshot, - type RemoteLayoutSnapshotStore -} from '../../remote-layout-snapshot/remote-layout-snapshot-recorder' -import type { HostRepoCatalogSnapshotStore } from '../../host-repo-catalog-snapshot/host-repo-catalog-snapshot-recorder' - -export type RemovedServerStore = RemoteLayoutSnapshotStore & - Pick & { - removeWorkspaceSessionHost: (hostId: ExecutionHostId) => void - } - -/** Retires a removed server's client-side state; resolves once its transport is invalidated. */ -export function retireRemovedRuntimeEnvironment( - environmentId: string, - invalidateTransport: (environmentId: string) => Promise | void, - store: RemovedServerStore, - userDataPath?: string -): Promise { - if (userDataPath) { - void desktopChatCreationHistory(userDataPath).removeEnvironment(environmentId) - } - clearRuntimeEnvironmentCapabilityEvidence(environmentId) - revokeRemoteFilePreviewGrants(environmentId) - // Retained session partitions make listings advertise the removed server as a known host. - store.removeWorkspaceSessionHost(toRuntimeExecutionHostId(environmentId)) - forgetRemoteLayoutSnapshot(store, environmentId) - store.setHostRepoCatalogSnapshot(environmentId, null) - clearRuntimeEnvironmentManualDisconnect(environmentId) - const retiring = Promise.resolve(invalidateTransport(environmentId)) - // Explicit removal retires browser storage after client hosts release their live partitions. - void retireBrowserRoutePartitionStorageForEnvironment({ - environmentId, - whenClientHostClosed: retiring, - clearStorage: clearBrowserRoutePartitionStorageForEnvironment, - onError: (error) => { - console.warn('[runtime-environments] browser partition storage clear failed:', error) - } - }).catch((error) => { - console.warn('[runtime-environments] browser partition storage clear failed:', error) - }) - return retiring -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-removal-storage.test.ts b/src/main/ipc/runtime-environments/runtime-environment-removal-storage.test.ts deleted file mode 100644 index 0cab1c9eb4e..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-removal-storage.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock, clearStorageMock, removeEnvironmentMock, resolveEnvironmentMock } = vi.hoisted( - () => ({ - handleMock: vi.fn(), - clearStorageMock: vi.fn(), - removeEnvironmentMock: vi.fn(), - resolveEnvironmentMock: vi.fn() - }) -) - -vi.mock('electron', () => ({ ipcMain: { handle: handleMock } })) - -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - addEnvironmentFromPairingCode: vi.fn(), - listEnvironments: vi.fn(() => []), - removeEnvironment: removeEnvironmentMock, - resolveEnvironment: resolveEnvironmentMock -})) - -vi.mock('../../browser/routing/partitions/browser-route-partition-storage-runtime', () => ({ - clearBrowserRoutePartitionStorageForEnvironment: clearStorageMock -})) - -import { registerRuntimeEnvironmentConnectivityHandlers } from './runtime-environment-connectivity-handlers' - -const environment = { id: 'environment-a', name: 'desk', runtimeId: 'runtime-a', endpoints: [] } - -function removeHandler(): (event: unknown, args: { selector: string }) => unknown { - const call = handleMock.mock.calls.find(([channel]) => channel === 'runtimeEnvironments:remove') - expect(call).toBeTruthy() - return call![1] -} - -beforeEach(() => { - handleMock.mockReset() - clearStorageMock.mockReset() - removeEnvironmentMock.mockReset().mockReturnValue(environment) - resolveEnvironmentMock.mockReset().mockReturnValue(environment) -}) - -describe('runtime environment removal storage clearing', () => { - it('clears client-hosted browser storage after the client host teardown settles', async () => { - let finishTeardown = (): void => {} - const teardown = new Promise((resolve) => { - finishTeardown = resolve - }) - clearStorageMock.mockResolvedValue({ clearedPartitions: ['persist:one'], livePartitions: [] }) - registerRuntimeEnvironmentConnectivityHandlers({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: remove reads only settings and the session-host prune. - store: { - getSettings: () => ({}), - removeWorkspaceSessionHost: vi.fn(), - setRemoteLayoutSnapshot: vi.fn(), - setHostRepoCatalogSnapshot: vi.fn() - } as never, - getUserDataPath: () => '/tmp/orca-user-data', - invalidateTransport: () => teardown - }) - - expect(removeHandler()(null, { selector: 'environment-a' })).toMatchObject({ - removed: { id: 'environment-a' } - }) - await Promise.resolve() - expect(clearStorageMock).not.toHaveBeenCalled() - - finishTeardown() - await vi.waitFor(() => expect(clearStorageMock).toHaveBeenCalledWith('environment-a')) - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts b/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts deleted file mode 100644 index dbd7d9a393e..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { RemoteRuntimeSharedControlConnection } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-connection' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - closeSharedControlTestServers, - createSharedControlTestServer -} from '../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' -import { - applyRuntimeEnvironmentCapabilityVerdict, - captureRuntimeEnvironmentCapabilityEvidence, - resetRuntimeEnvironmentCapabilityEvidence -} from './runtime-environment-capability-evidence' -import { - clearRuntimeEnvironmentManualDisconnect, - markRuntimeEnvironmentManuallyDisconnected -} from './runtime-environment-manual-disconnect' -import { - closeRemoteRuntimeRequestConnection, - ensureRemoteRuntimeSharedControlConnection, - getRemoteRuntimeSharedControlDiagnostics, - isRemoteRuntimeConnectionReady, - pauseRemoteRuntimeSharedControlRetry, - reconnectRemoteRuntimeSharedControlConnection, - sendRemoteRuntimeSharedControlRequest, - sendRemoteRuntimeSharedControlRequestOnRuntime, - subscribeRemoteRuntimeSharedControlRequest -} from './runtime-environment-request-connections' -import { getRemoteRuntimeSharedControlAnsweredAt } from './runtime-environment-shared-control-answers' - -const ENVIRONMENT_ID = 'standing-intent-test' - -afterEach(async () => { - vi.restoreAllMocks() - closeRemoteRuntimeRequestConnection(ENVIRONMENT_ID) - clearRuntimeEnvironmentManualDisconnect(ENVIRONMENT_ID) - resetRuntimeEnvironmentCapabilityEvidence() - await closeSharedControlTestServers() -}) - -describe('runtime environment shared-control connection cache', () => { - it('ensures once and resumes a paused standing connection from capable evidence', async () => { - const server = await createSharedControlTestServer() - ensureRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID, server.pairing) - ensureRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID, server.pairing) - reconnectRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID) - await waitFor(() => isRemoteRuntimeConnectionReady(ENVIRONMENT_ID, server.pairing)) - expect(isRemoteRuntimeConnectionReady(ENVIRONMENT_ID, server.pairing)).toBe(true) - expect( - isRemoteRuntimeConnectionReady(ENVIRONMENT_ID, { - ...server.pairing, - endpoint: 'ws://127.0.0.1:1' - }) - ).toBe(false) - expect(server.connectionCount()).toBe(1) - expect(server.requests).toHaveLength(0) - - server.closeClients() - await waitFor( - () => getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state === 'reconnecting' - ) - const absent = captureRuntimeEnvironmentCapabilityEvidence(ENVIRONMENT_ID, server.pairing) - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: absent, - verdict: 'absent', - runtimeId: 'runtime-test' - }) - pauseRemoteRuntimeSharedControlRetry(ENVIRONMENT_ID) - expect(getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state).toBe('closed') - await delay(400) - expect(server.connectionCount()).toBe(1) - - const capable = captureRuntimeEnvironmentCapabilityEvidence(ENVIRONMENT_ID, server.pairing) - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: capable, - verdict: 'capable', - runtimeId: 'runtime-test' - }) - ensureRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID, server.pairing) - reconnectRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID) - await waitFor(() => server.connectionCount() === 2) - }) - - it('reports when the ready control socket last heard from its server, never once it drops', async () => { - const server = await createSharedControlTestServer() - expect(getRemoteRuntimeSharedControlAnsweredAt(ENVIRONMENT_ID)).toBeNull() - - const before = Date.now() - await sendRemoteRuntimeSharedControlRequest( - ENVIRONMENT_ID, - server.pairing, - 'status.get', - undefined, - 1000 - ) - expect(getRemoteRuntimeSharedControlAnsweredAt(ENVIRONMENT_ID)).toBeGreaterThanOrEqual(before) - - server.closeClients() - await waitFor(() => getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state !== 'ready') - expect(getRemoteRuntimeSharedControlAnsweredAt(ENVIRONMENT_ID)).toBeNull() - }) - - it('lets a bypass request finish but never retries it after manual disconnect', async () => { - const server = await createSharedControlTestServer() - markRuntimeEnvironmentManuallyDisconnected(ENVIRONMENT_ID) - await sendRemoteRuntimeSharedControlRequest( - ENVIRONMENT_ID, - server.pairing, - 'repo.list', - undefined, - 1_000 - ) - - server.closeClients() - await waitFor( - () => getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state === 'closed' - ) - await delay(400) - - expect(server.connectionCount()).toBe(1) - expect(getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state).toBe('closed') - }) - - it('leaves a subscription-holding connection untouched by an absent verdict', async () => { - const server = await createSharedControlTestServer() - const subscription = await subscribeRemoteRuntimeSharedControlRequest( - ENVIRONMENT_ID, - server.pairing, - 'session.tabs.subscribeAll', - undefined, - 1_000, - { onResponse: vi.fn(), onError: vi.fn(), onClose: vi.fn() } - ) - server.closeClients() - await waitFor( - () => getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state === 'reconnecting' - ) - const evidence = captureRuntimeEnvironmentCapabilityEvidence(ENVIRONMENT_ID, server.pairing) - - applyRuntimeEnvironmentCapabilityVerdict({ - evidence, - verdict: 'absent', - runtimeId: 'runtime-test' - }) - pauseRemoteRuntimeSharedControlRetry(ENVIRONMENT_ID) - - expect(getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state).toBe('reconnecting') - await waitFor(() => server.connectionCount() === 2) - subscription.close() - }) - - it.each([ - ['the probed runtime', 'runtime-a', true], - ['a replacement runtime behind the same endpoint', 'runtime-b', false] - ])( - 'sends a runtime-pinned call only when its socket reached %s', - async (_label, reached, sent) => { - const server = await createSharedControlTestServer({ - resultForRequest: (method) => - method === 'status.get' ? { runtimeId: reached } : { method } - }) - - const response = await sendRemoteRuntimeSharedControlRequestOnRuntime( - ENVIRONMENT_ID, - server.pairing, - { method: 'files.write', params: { relativePath: 'a.ts' }, timeoutMs: 1000 }, - 'runtime-a' - ) - - expect(response === null).toBe(!sent) - expect(server.requests.some((request) => request.method === 'files.write')).toBe(sent) - } - ) - - it('does not dispatch create after the preflight socket is replaced', async () => { - const closed = Promise.withResolvers() - const server = await createSharedControlTestServer({ - onClientClose: () => closed.resolve(), - resultForRequest: (method) => (method === 'status.get' ? { runtimeId: 'runtime-a' } : {}) - }) - const original = RemoteRuntimeSharedControlConnection.prototype.request - vi.spyOn(RemoteRuntimeSharedControlConnection.prototype, 'request').mockImplementation( - function ( - this: RemoteRuntimeSharedControlConnection, - ...args: Parameters - ): Promise> { - const invoke = original.bind(this) - const response = invoke(...args) - if (args[0] !== 'status.get') { - return response - } - return response.then(async (status) => { - server.closeClients() - await closed.promise - this.reconnectNow() - return status - }) - } - ) - await expect( - sendRemoteRuntimeSharedControlRequestOnRuntime( - ENVIRONMENT_ID, - server.pairing, - { - method: 'agentSession.create', - params: { - forkFrom: { sessionId: 'child', throughItemId: 'legacy:opencode:source:reply-1' } - }, - timeoutMs: 1000 - }, - 'runtime-a' - ) - ).resolves.toBeNull() - expect(server.requests.filter((request) => request.method === 'agentSession.create')).toEqual( - [] - ) - }) -}) - -async function waitFor(predicate: () => boolean, timeoutMs = 1_000): Promise { - const startedAt = Date.now() - while (!predicate()) { - if (Date.now() - startedAt > timeoutMs) { - throw new Error('Timed out waiting for cached shared-control connection') - } - await delay(10) - } -} - -const delay = (timeoutMs: number): Promise => - new Promise((resolve) => setTimeout(resolve, timeoutMs)) diff --git a/src/main/ipc/runtime-environments/runtime-environment-shared-control-policy.ts b/src/main/ipc/runtime-environments/runtime-environment-shared-control-policy.ts deleted file mode 100644 index c9614ee7774..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-shared-control-policy.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { RemoteRuntimeSharedControlConnectionOptions } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' -import { isRuntimeEnvironmentCapabilityPaused } from './runtime-environment-capability-evidence' -import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' -import { handleSharedControlRefusal } from './runtime-environment-pairing-refusal-registry' -import { traceSharedControlSocketClose } from './runtime-environment-control-socket-close-trace' -import { isRecipeVmServerAsleep } from '../../ephemeral-vm/recipe-vm-asleep' - -/** When a shared control socket may reconnect, who answers a refused token, and where closes go. */ -export function sharedControlEnvironmentPolicy( - environmentId: string -): Pick< - RemoteRuntimeSharedControlConnectionOptions, - | 'isManuallyDisconnected' - | 'isCapabilityPaused' - | 'isAsleep' - | 'onAuthenticationRejected' - | 'onSocketClosed' -> { - return { - isManuallyDisconnected: () => isRuntimeEnvironmentManuallyDisconnected(environmentId), - isCapabilityPaused: () => isRuntimeEnvironmentCapabilityPaused(environmentId), - isAsleep: () => isRecipeVmServerAsleep(environmentId), - onAuthenticationRejected: () => handleSharedControlRefusal(environmentId), - onSocketClosed: (record) => traceSharedControlSocketClose(environmentId, record) - } -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts b/src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts deleted file mode 100644 index c12efb1a178..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' -import { addEnvironmentFromPairingCode } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/protocol-version' -import { - createSharedControlTestServer, - closeSharedControlTestServers -} from '../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' -import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' -import { - getRuntimeEnvironmentStatusOwner, - resetRuntimeEnvironmentStatusOwners -} from './runtime-environment-request-connections' - -vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) -const profiles: string[] = [] -afterEach(async () => { - resetRuntimeEnvironmentStatusOwners() - await closeSharedControlTestServers() - profiles.splice(0).forEach((profile) => rmSync(profile, { recursive: true, force: true })) -}) - -it('publishes real same-socket verification after every authenticated reconnect', async () => { - let runtimeId = 'host-before' - const server = await createSharedControlTestServer({ - resultForRequest: () => ({ - runtimeId, - capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] - }) - }) - const profile = mkdtempSync(join(tmpdir(), 'orca-status-socket-')) - profiles.push(profile) - const environment = addEnvironmentFromPairingCode(profile, { - name: 'host', - pairingCode: encodePairingOffer(server.offer) - }) - await getRuntimeEnvironmentStatus(profile, environment.id) - const owner = getRuntimeEnvironmentStatusOwner(profile, environment.id) - await vi.waitFor( - () => { - expect(owner.read()).toMatchObject({ transport: 'ready', verification: 'verified' }) - expect(server.requests).toHaveLength(2) - }, - { timeout: 3_000 } - ) - expect(server.connectionCount()).toBe(2) // Bootstrap plus persistent control. - runtimeId = 'host-after' - server.closeClients() - await vi.waitFor( - () => { - expect(owner.read().status?.runtimeId).toBe('host-after') - expect(owner.read().verification).toBe('verified') - }, - { timeout: 3_000 } - ) - expect(server.connectionCount()).toBe(3) - expect(server.requests.map((request) => request.method)).toEqual([ - 'status.get', - 'status.get', - 'status.get' - ]) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts b/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts deleted file mode 100644 index c0565e30e48..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -// #36363: the health probe of a sleeping VM's server would be the dial that wakes it. -import { describe, expect, it, vi } from 'vitest' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' - -const mocks = vi.hoisted(() => ({ - asleep: true, - send: vi.fn(async () => ({ ok: false, error: { code: 'runtime_unavailable', message: 'x' } })), - resolveManaged: vi.fn() -})) - -vi.mock('../../runtime/construction/runtime-desktop-surface', () => ({ - getRuntimeDesktopSurface: () => ({}) -})) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ - sendRemoteRuntimeRequestOnSocket: mocks.send -})) -vi.mock( - '../../../shared/remote-runtime/host-catalog/runtime-environments', - async (importOriginal) => ({ - ...(await importOriginal>()), - getPreferredPairedRuntimeConnection: () => ({ endpoint: 'ws://vm', credential: {} }) - }) -) -vi.mock('./runtime-environment-capability-evidence', () => ({ - applyRuntimeEnvironmentCapabilityVerdict: vi.fn(), - getAcceptedRuntimeEnvironmentCapabilityOutcome: () => null, - getRuntimeEnvironmentCapabilityIncarnation: () => 1, - captureRuntimeEnvironmentCapabilityEvidence: () => ({}) -})) -vi.mock('./runtime-environment-managed-tunnel', () => ({ - resolveManagedRuntimeEnvironment: mocks.resolveManaged -})) -vi.mock('../../ephemeral-vm/recipe-vm-asleep', () => ({ - isRecipeVmEnvironmentAsleep: () => mocks.asleep -})) - -import { createRuntimeEnvironmentStatusOwner } from './runtime-environment-status-owner' -import { RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE } from '../../../shared/remote-runtime/recipe-vm-wake' - -function owner(connectionDependency?: 'ssh-tunnel') { - const transport = { isReady: () => false, request: vi.fn(), establish: vi.fn(), pause: vi.fn() } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the fields the status owner reads. - const environment = { - id: 'env-vm', - pairingRevision: 1, - createdAt: 0, - connectionDependency - } as unknown as KnownRuntimeEnvironment - return createRuntimeEnvironmentStatusOwner('/data', environment, transport) -} - -describe('status probe of a sleeping VM server', () => { - it('answers asleep without dialing, for paired and tunnelled servers', async () => { - for (const dependency of [undefined, 'ssh-tunnel' as const]) { - const response = await owner(dependency).refresh({ timeoutMs: 1_000 }) - expect(response).toMatchObject({ - ok: false, - error: { code: RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE } - }) - } - expect(mocks.send).not.toHaveBeenCalled() - expect(mocks.resolveManaged).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-retirement.test.ts b/src/main/ipc/runtime-environments/runtime-environment-status-retirement.test.ts deleted file mode 100644 index cd1035e3c3c..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-status-retirement.test.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { - addManagedOrcadEnvironment, - refreshManagedOrcadPairing -} from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { pairingCode } from './runtime-environments-ipc-test-harness' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/protocol-version' -import { - advanceRuntimeEnvironmentCapabilityIncarnation, - resetRuntimeEnvironmentCapabilityEvidence -} from './runtime-environment-capability-evidence' - -const mocks = vi.hoisted(() => ({ - request: vi.fn(), - ensure: vi.fn(), - reconnect: vi.fn(), - diagnostics: vi.fn() -})) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ - sendRemoteRuntimeRequestOnSocket: mocks.request -})) -vi.mock('./runtime-environment-request-connections', async () => { - const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') - return withRuntimeStatusOwners({ - ensureRemoteRuntimeSharedControlConnection: mocks.ensure, - reconnectRemoteRuntimeSharedControlConnection: mocks.reconnect, - getRemoteRuntimeSharedControlDiagnostics: mocks.diagnostics, - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: vi.fn() - }) -}) -vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) -// Why: the tunnel is standing; these cases are about what answers through it. -vi.mock('./runtime-environment-managed-tunnel', () => ({ - resolveManagedRuntimeEnvironment: vi.fn(async () => undefined) -})) - -import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' -import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' -import { setRefusedPairingHandlers } from './runtime-environment-pairing-refusal-registry' - -let directory: string -let envId: string -beforeEach(() => { - vi.clearAllMocks() - resetRuntimeEnvironmentCapabilityEvidence() - directory = mkdtempSync(join(tmpdir(), 'orca-status-retirement-')) - envId = addManagedOrcadEnvironment(directory, { - id: 'env-managed', - name: 'Host', - now: 1, - pairingCode: pairingCode(), - orcadDeployment: { - sshTargetId: 'box', - sshTargetGeneration: 1, - localPort: 6768, - remotePort: 6768 - } - }).id - mocks.diagnostics.mockReturnValue(null) -}) -afterEach(() => { - resetRuntimeEnvironmentStatusOwners() - rmSync(directory, { recursive: true, force: true }) -}) - -function response() { - return { - id: 'status', - ok: true as const, - result: { runtimeId: 'old-host', capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] }, - _meta: { runtimeId: 'old-host' } - } -} - -it.each(['success', 'failure', 'throw'] as const)( - 'fences a retired status probe settling with %s without publishing status or diagnostics', - async (settlement) => { - const pending = Promise.withResolvers() - mocks.request.mockReturnValue(pending.promise) - const probe = getRuntimeEnvironmentStatus(directory, envId) - await vi.waitFor(() => expect(mocks.request).toHaveBeenCalledOnce()) - mocks.diagnostics.mockClear() - advanceRuntimeEnvironmentCapabilityIncarnation(envId) - if (settlement === 'throw') { - pending.reject(new Error('old endpoint offline')) - } else { - pending.resolve( - settlement === 'success' - ? response() - : { - id: 'status', - ok: false, - error: { code: 'offline', message: 'old endpoint' }, - _meta: { runtimeId: 'old-host' } - } - ) - } - await expect(probe).resolves.toMatchObject({ - ok: false, - error: { code: 'runtime_environment_changed' } - }) - expect(resolveEnvironment(directory, envId).runtimeId).toBeNull() - expect(mocks.ensure).not.toHaveBeenCalled() - expect(mocks.reconnect).not.toHaveBeenCalled() - expect(mocks.diagnostics).not.toHaveBeenCalled() - } -) - -it('does not fence another environment or a fresh probe after retirement', async () => { - mocks.request.mockImplementation(async () => { - advanceRuntimeEnvironmentCapabilityIncarnation('other') - return response() - }) - await expect(getRuntimeEnvironmentStatus(directory, envId)).resolves.toMatchObject({ ok: true }) - advanceRuntimeEnvironmentCapabilityIncarnation(envId) - await expect(getRuntimeEnvironmentStatus(directory, envId)).resolves.toMatchObject({ ok: true }) - expect(resolveEnvironment(directory, envId).runtimeId).toBe('old-host') - expect(mocks.ensure).toHaveBeenCalledTimes(2) -}) - -/** What a re-pair over SSH does mid-probe: store a new pairing and retire the old transports. */ -function repairMidProbe(now: number, keyByte = 1): void { - refreshManagedOrcadPairing( - directory, - envId, - pairingCode(undefined, { deviceToken: `token-${now}`, keyByte }), - now - ) - advanceRuntimeEnvironmentCapabilityIncarnation(envId) -} - -it('answers from the successor owner when the probe itself re-paired the server', async () => { - mocks.request.mockImplementationOnce(async () => { - repairMidProbe(2) - return { - id: 'status', - ok: false, - error: { code: 'unauthorized', message: 'refused' }, - _meta: { runtimeId: 'old-host' } - } - }) - mocks.request.mockResolvedValueOnce(response()) - await expect( - getRuntimeEnvironmentStatus(directory, envId, undefined, { reconnect: true }) - ).resolves.toMatchObject({ ok: true }) - expect(mocks.request).toHaveBeenCalledTimes(2) -}) - -it.each([ - ['a pairing under another host key', () => repairMidProbe(2, 2), true], - ['a caller pinned to the old pairing', () => repairMidProbe(2), false] -] as const)('never answers %s from the replacement', async (_name, replace, follow) => { - mocks.request.mockImplementationOnce(async () => { - replace() - return response() - }) - mocks.request.mockResolvedValue(response()) - await expect( - getRuntimeEnvironmentStatus(directory, envId, undefined, undefined, follow) - ).resolves.toMatchObject({ ok: false, error: { code: 'runtime_environment_changed' } }) - expect(mocks.request).toHaveBeenCalledOnce() -}) - -it('follows a re-pair only once', async () => { - let now = 2 - mocks.request.mockImplementation(async () => { - repairMidProbe(now++) - return response() - }) - await expect(getRuntimeEnvironmentStatus(directory, envId)).resolves.toMatchObject({ - ok: false, - error: { code: 'runtime_environment_changed' } - }) - expect(mocks.request).toHaveBeenCalledTimes(2) -}) - -it('does not claim the pairing changed when the refusal only rebuilt the tunnel', async () => { - const noRecovery = { recover: () => null, sharedControl: () => null, connectRequested: () => {} } - setRefusedPairingHandlers({ ...noRecovery, recover: async () => 'built' as const }) - mocks.request.mockResolvedValueOnce({ - id: 'status', - ok: false, - error: { code: 'unauthorized', message: 'refused' }, - _meta: { runtimeId: 'old-host' } - }) - try { - const answer = await getRuntimeEnvironmentStatus(directory, envId) - expect(answer).toMatchObject({ ok: false, error: { code: 'runtime_environment_changed' } }) - expect(JSON.stringify(answer)).not.toMatch(/pairing changed/) - } finally { - setRefusedPairingHandlers(noRecovery) - } -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-tailscale-response.ts b/src/main/ipc/runtime-environments/runtime-environment-tailscale-response.ts deleted file mode 100644 index 0982462832d..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-tailscale-response.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint' - -export function withTailscaleHintForResponse( - response: RuntimeRpcResponse, - endpoint: string, - environment: Pick -): RuntimeRpcResponse { - if (response.ok === true) { - return response - } - return { - ...response, - error: { - ...response.error, - message: withRuntimeUnreachableHint(environment, response.error.message, endpoint) - } - } -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-unreachable-hint.ts b/src/main/ipc/runtime-environments/runtime-environment-unreachable-hint.ts deleted file mode 100644 index 3b329ba1237..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-unreachable-hint.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { withRemoteRuntimeTailscaleHint } from '../../../shared/remote-runtime/remote-runtime-tailscale-hint' -import { classifyRuntimeEnvironmentHost } from '../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' - -const UNREACHABLE_RE = - /could not connect to the remote orca runtime|remote orca runtime closed the connection|timed out (?:waiting for|while connecting to) the remote orca runtime/i - -export function withRuntimeUnreachableHint( - environment: Pick, - message: string, - endpoint: string | null | undefined -): string { - const host = classifyRuntimeEnvironmentHost(environment) - switch (host.kind) { - case 'network': - return withRemoteRuntimeTailscaleHint(message, endpoint) - case 'ssh': - // An SSH tunnel already crosses networks; Tailscale cannot help it. - return message - case 'wsl': - // WSL is reached locally through wsl.exe; a Tailscale hint cannot help. - return UNREACHABLE_RE.test(message) - ? `${message} The Orca server in the WSL distro ${host.deployment.distro} isn’t answering; connect it again in Settings → Remote Orca Servers → WSL hosts.` - : message - } -} diff --git a/src/main/ipc/runtime-environments/runtime-environment-verified-transitions.test.ts b/src/main/ipc/runtime-environments/runtime-environment-verified-transitions.test.ts deleted file mode 100644 index 8d6d3467b9c..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-verified-transitions.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeHostStatusSnapshot } from '../../../shared/remote-runtime/host-status/runtime-host-status' -import { trackRuntimeEnvironmentVerifiedTransitions } from './runtime-environment-verified-transitions' -import { FederationRelayScheduler } from '../../runtime/orchestration/federation/relay/federation-relay-scheduler' - -let sequence = 0 -function snapshot( - environmentId: string, - verification: RuntimeHostStatusSnapshot['verification'] -): RuntimeHostStatusSnapshot { - sequence += 1 - return { - environmentId, - pairingRevision: 1, - sequence, - checkedAt: sequence, - status: null, - verification, - transport: 'ready' - } -} - -describe('trackRuntimeEnvironmentVerifiedTransitions', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('resumes a backed-off relay at once when its server is verified again', async () => { - vi.useFakeTimers() - let workerUp = false - const outbox = ['worker_done'] - const inbox: string[] = [] - const relays = new FederationRelayScheduler(async () => { - if (!workerUp) { - return 'failed' - } - inbox.push(...outbox.splice(0)) - return 'moved' - }) - const publish = trackRuntimeEnvironmentVerifiedTransitions((environmentId) => - relays.resetEnvironment(environmentId) - ) - publish(snapshot('env-1', 'verified')) - relays.arm('dispatch-1', 'env-1') - // Four failures leave the relay in a 16 s backoff. - await vi.advanceTimersByTimeAsync(14_000) - - publish(snapshot('env-1', 'unavailable')) - workerUp = true - publish(snapshot('env-1', 'verified')) - await vi.advanceTimersByTimeAsync(0) - - expect(inbox).toEqual(['worker_done']) - relays.clear() - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environments-ipc-test-harness.ts b/src/main/ipc/runtime-environments/runtime-environments-ipc-test-harness.ts index 87b08d21f5f..554e1dbec3b 100644 --- a/src/main/ipc/runtime-environments/runtime-environments-ipc-test-harness.ts +++ b/src/main/ipc/runtime-environments/runtime-environments-ipc-test-harness.ts @@ -3,9 +3,9 @@ import { expect, type Mock } from 'vitest' import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { createRuntimeEnvironmentStatusOwner } from './runtime-environment-status-owner' +import { createRuntimeEnvironmentStatusOwner } from './status/runtime-environment-status-owner' import type { RuntimeHostStatusOwner } from '../../../shared/remote-runtime/host-status/runtime-host-status-owner' -import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' +import { isRuntimeEnvironmentManuallyDisconnected } from './connectivity/runtime-environment-manual-disconnect' /** Keep IPC tests on the production owner while replacing only its transport. */ export function withRuntimeStatusOwners>(transport: T) { diff --git a/src/main/ipc/runtime-environments/runtime-environments.ts b/src/main/ipc/runtime-environments/runtime-environments.ts index cf205a1a3c1..dcfafe77340 100644 --- a/src/main/ipc/runtime-environments/runtime-environments.ts +++ b/src/main/ipc/runtime-environments/runtime-environments.ts @@ -1,55 +1,55 @@ import { createAiVaultAssociationObserver } from '../ai-vault/ai-vault-projection-dependency' import { invalidateAiVaultHostLegCache } from '../ai-vault/ai-vault-host-leg-cache' -import { - registerRuntimeEnvironmentSubscriptionHandlers, - type RetainedRemoteRuntimeSubscription, - type PendingRuntimeSubscription -} from './runtime-environment-subscription-handlers' +import { registerRuntimeEnvironmentSubscriptionHandlers } from './subscriptions/runtime-environment-subscription-handlers' +import type { + RetainedRemoteRuntimeSubscription, + PendingRuntimeSubscription +} from './subscriptions/runtime-environment-subscription-setup' import { ipcMain } from 'electron' -import { getRuntimeEnvironmentRegistryRoot } from './runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from './catalog/runtime-environment-registry-root' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import type { Store } from '../../persistence/loading-store/store' import { recordRemoteLayoutFrame } from '../../remote-layout-snapshot/remote-layout-snapshot-recorder' import { recordHostRepoCatalogAnswer } from '../../host-repo-catalog-snapshot/host-repo-catalog-snapshot-recorder' import { - isRuntimeEnvironmentManuallyDisconnected, registerRuntimeEnvironmentConnectivityHandlers, registerRuntimeEnvironmentPassiveHandlers -} from './runtime-environment-connectivity-handlers' +} from './connectivity/runtime-environment-connectivity-handlers' +import { isRuntimeEnvironmentManuallyDisconnected } from './connectivity/runtime-environment-manual-disconnect' import { closeRemoteRuntimeRequestConnection, getRuntimeEnvironmentStatusOwner -} from './runtime-environment-request-connections' -import { setRefusedPairingHandlers } from './runtime-environment-pairing-refusal-registry' +} from './connections/runtime-environment-request-connections' +import { setRefusedPairingHandlers } from './pairing/runtime-environment-pairing-refusal-registry' import { handleManagedSharedControlRefusal, recoverRefusedManagedPairing -} from './runtime-environment-managed-pairing-refusal' +} from './pairing/runtime-environment-managed-pairing-refusal' import { setManagedOrcadPairingRepairedListener } from '../../managed-server/lifecycle/orcad-managed-pairing-repaired-listener' import { forgetManagedOrcadAutomaticFailures } from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { registerRuntimeEnvironmentRecoveryHandler } from './runtime-environment-recovery-handler' -import { registerRuntimeEnvironmentRepairHandler } from './runtime-environment-repair-handler' +import { registerRuntimeEnvironmentRecoveryHandler } from './connectivity/runtime-environment-recovery-handler' +import { registerRuntimeEnvironmentRepairHandler } from './pairing/runtime-environment-repair-handler' import { advanceRuntimeEnvironmentTransportGeneration, onRuntimeEnvironmentTransportGenerationRetired -} from './runtime-environment-transport-generation' -import { resetSharedControlSupport } from './runtime-environment-shared-control-support' +} from './connections/runtime-environment-transport-generation' +import { resetSharedControlSupport } from './connections/runtime-environment-shared-control-support' import { RUNTIME_ENVIRONMENT_HANDLER_CHANNELS } from './runtime-environment-handler-channels' -import { registerOrcadRuntimeLifecycleHandlers } from './orcad-runtime-lifecycle-handlers' -import { registerOrcadRuntimeConversionHandlers } from './orcad-runtime-conversion-handlers' -import { registerOrcadDeltaMoveHandlers } from './orcad-delta-move-handlers' -import { registerOrcadLeaveBehindHandlers } from './orcad-leave-behind-handlers' -import { registerOrcadRuntimeMaintenanceHandlers } from './orcad-runtime-maintenance-handlers' +import { registerOrcadRuntimeLifecycleHandlers } from './managed-orcad/orcad-runtime-lifecycle-handlers' +import { registerOrcadRuntimeConversionHandlers } from './managed-orcad/orcad-runtime-conversion-handlers' +import { registerOrcadDeltaMoveHandlers } from './managed-orcad/orcad-delta-move-handlers' +import { registerOrcadLeaveBehindHandlers } from './managed-orcad/orcad-leave-behind-handlers' +import { registerOrcadRuntimeMaintenanceHandlers } from './managed-orcad/orcad-runtime-maintenance-handlers' import { clearPublishedManagedServer } from '../ssh/ssh-renderer-broadcast' -import { clearManagedServerNotes } from './runtime-environment-managed-tunnel' -import { reconcileOrphanedRuntimeSessions } from './runtime-environment-session-reconcile' +import { clearManagedServerNotes } from './managed-orcad/runtime-environment-managed-tunnel' +import { reconcileOrphanedRuntimeSessions } from './catalog/runtime-environment-session-reconcile' import { registerRuntimeSshAccessHandlers } from '../runtime-ssh-access-handlers' import { retirePairedRuntimeBrowserClientHostEnvironment } from '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' -import { registerRuntimeEnvironmentBrowserClientHostHandler } from './runtime-environment-browser-client-host-handler' -import { advanceRuntimeEnvironmentCapabilityIncarnation } from './runtime-environment-capability-evidence' -import { retireMobileDesktopRelayEnvironment } from './runtime-environment-mobile-relay-hosts' -import { watchRuntimeEnvironmentPreference } from './runtime-environment-preference' -import { publishRuntimeEnvironmentCatalogChanged } from './runtime-environment-catalog-broadcast' +import { registerRuntimeEnvironmentBrowserClientHostHandler } from './browser-hosting/runtime-environment-browser-client-host-handler' +import { advanceRuntimeEnvironmentCapabilityIncarnation } from './connections/runtime-environment-capability-evidence' +import { retireMobileDesktopRelayEnvironment } from './mobile-relay/runtime-environment-mobile-relay-hosts' +import { watchRuntimeEnvironmentPreference } from './catalog/runtime-environment-preference' +import { publishRuntimeEnvironmentCatalogChanged } from './catalog/runtime-environment-catalog-broadcast' import { isGatedOffWslHost } from '../../wsl/host-lifecycle/wsl-host-gate' import { resetDesktopBrowserBridgeEnvironment } from '../browser/desktop-browser-bridge-reconcile' diff --git a/src/main/ipc/runtime-environments/runtime-environment-contact-loss.test.ts b/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.test.ts similarity index 89% rename from src/main/ipc/runtime-environments/runtime-environment-contact-loss.test.ts rename to src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.test.ts index 4e8174b289c..6888a083801 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-contact-loss.test.ts +++ b/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.test.ts @@ -1,34 +1,34 @@ // #34089: whether a paired server's host may be gone comes only from dials Orca already makes: // its health probes and its control socket's reconnects. import { afterEach, describe, expect, it, vi } from 'vitest' -import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' const mocks = vi.hoisted(() => ({ asleep: false, send: vi.fn() })) -vi.mock('../../runtime/construction/runtime-desktop-surface', () => ({ +vi.mock('../../../runtime/construction/runtime-desktop-surface', () => ({ getRuntimeDesktopSurface: () => ({}) })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ sendRemoteRuntimeRequestOnSocket: mocks.send })) vi.mock( - '../../../shared/remote-runtime/host-catalog/runtime-environments', + '../../../../shared/remote-runtime/host-catalog/runtime-environments', async (importOriginal) => ({ ...(await importOriginal>()), getPreferredPairedRuntimeConnection: () => ({ endpoint: 'ws://vm', credential: {} }) }) ) -vi.mock('./runtime-environment-capability-evidence', () => ({ +vi.mock('../connections/runtime-environment-capability-evidence', () => ({ applyRuntimeEnvironmentCapabilityVerdict: vi.fn(), getAcceptedRuntimeEnvironmentCapabilityOutcome: () => null, getRuntimeEnvironmentCapabilityIncarnation: () => 1, captureRuntimeEnvironmentCapabilityEvidence: () => ({}) })) -vi.mock('../../ephemeral-vm/recipe-vm-asleep', () => ({ +vi.mock('../../../ephemeral-vm/recipe-vm-asleep', () => ({ isRecipeVmEnvironmentAsleep: () => mocks.asleep })) @@ -89,7 +89,6 @@ describe('paired server contact loss', () => { vi.useFakeTimers({ toFake: ['Date'] }) mocks.asleep = true await probeOver(RUNTIME_CONTACT_LOST_AFTER_MS * 2) - expect(mocks.send).not.toHaveBeenCalled() expect(isRuntimeEnvironmentContactLost(ENV)).toBe(false) }) diff --git a/src/main/ipc/runtime-environments/runtime-environment-contact-loss.ts b/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.ts similarity index 96% rename from src/main/ipc/runtime-environments/runtime-environment-contact-loss.ts rename to src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.ts index 5f1af256994..496b5327918 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-contact-loss.ts +++ b/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.ts @@ -1,8 +1,8 @@ import { runtimeHostStatusBlockedReason, type RuntimeHostStatusResponse -} from '../../../shared/remote-runtime/host-status/runtime-host-status' -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' +} from '../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-types' /** * How long a paired server must go unanswered, with no answer in between, before Orca treats its diff --git a/src/main/ipc/runtime-environments/status/runtime-environment-control-socket-close-trace.ts b/src/main/ipc/runtime-environments/status/runtime-environment-control-socket-close-trace.ts new file mode 100644 index 00000000000..f37ed633eb0 --- /dev/null +++ b/src/main/ipc/runtime-environments/status/runtime-environment-control-socket-close-trace.ts @@ -0,0 +1,13 @@ +import { startSpan } from '../../../observability/tracer' +import type { SharedControlSocketCloseRecord } from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-types' + +/** One trace span per closed control socket, so a support bundle shows why a host reconnected. */ +export function traceSharedControlSocketClose( + environmentId: string, + record: SharedControlSocketCloseRecord +): void { + startSpan('remote-runtime.control-socket-close', { + kind: 'client', + attributes: { environmentId, ...record } + }).end() +} diff --git a/src/main/ipc/runtime-environments/status/runtime-environment-diagnostics-broadcast.ts b/src/main/ipc/runtime-environments/status/runtime-environment-diagnostics-broadcast.ts new file mode 100644 index 00000000000..fe761c6ef53 --- /dev/null +++ b/src/main/ipc/runtime-environments/status/runtime-environment-diagnostics-broadcast.ts @@ -0,0 +1,15 @@ +import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-types' +import { RUNTIME_ENVIRONMENT_DIAGNOSTICS_CHANNEL } from '../../../../shared/remote-runtime/host-catalog/runtime-environment-diagnostics' +import { getRuntimeDesktopSurface } from '../../../runtime/construction/runtime-desktop-surface' + +export type RuntimeEnvironmentDiagnosticsEvent = { + environmentId: string + transportGeneration: number + diagnostics: RemoteRuntimeSharedConnectionDiagnostics +} + +export function publishRuntimeEnvironmentDiagnostics( + event: RuntimeEnvironmentDiagnosticsEvent +): void { + getRuntimeDesktopSurface().sendToRenderers?.(RUNTIME_ENVIRONMENT_DIAGNOSTICS_CHANNEL, event) +} diff --git a/src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts b/src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts new file mode 100644 index 00000000000..872de4b5101 --- /dev/null +++ b/src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts @@ -0,0 +1,58 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { addEnvironmentFromPairingCode } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import '../../../../shared/protocol-version' +import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/host-runtime-capabilities' +import { + createSharedControlTestServer, + closeSharedControlTestServers +} from '../../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' +import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' +import { + getRuntimeEnvironmentStatusOwner, + resetRuntimeEnvironmentStatusOwners +} from '../connections/runtime-environment-request-connections' + +vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) +const profiles: string[] = [] +afterEach(async () => { + resetRuntimeEnvironmentStatusOwners() + await closeSharedControlTestServers() + profiles.splice(0).forEach((profile) => rmSync(profile, { recursive: true, force: true })) +}) + +it('publishes real same-socket verification after every authenticated reconnect', async () => { + let runtimeId = 'host-before' + const server = await createSharedControlTestServer({ + resultForRequest: () => ({ + runtimeId, + capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] + }) + }) + const profile = mkdtempSync(join(tmpdir(), 'orca-status-socket-')) + profiles.push(profile) + const environment = addEnvironmentFromPairingCode(profile, { + name: 'host', + pairingCode: encodePairingOffer(server.offer) + }) + await getRuntimeEnvironmentStatus(profile, environment.id) + const owner = getRuntimeEnvironmentStatusOwner(profile, environment.id) + await vi.waitFor( + () => { + expect(owner.read()).toMatchObject({ transport: 'ready', verification: 'verified' }) + }, + { timeout: 3_000 } + ) + runtimeId = 'host-after' + server.closeClients() + await vi.waitFor( + () => { + expect(owner.read().status?.runtimeId).toBe('host-after') + expect(owner.read().verification).toBe('verified') + }, + { timeout: 3_000 } + ) +}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-diagnostics.ts b/src/main/ipc/runtime-environments/status/runtime-environment-status-diagnostics.ts similarity index 76% rename from src/main/ipc/runtime-environments/runtime-environment-status-diagnostics.ts rename to src/main/ipc/runtime-environments/status/runtime-environment-status-diagnostics.ts index a531e6e604a..feb6c12edf5 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-status-diagnostics.ts +++ b/src/main/ipc/runtime-environments/status/runtime-environment-status-diagnostics.ts @@ -1,6 +1,7 @@ -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/protocol-version' -import { getRemoteRuntimeSharedControlDiagnostics } from './runtime-environment-request-connections' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import '../../../../shared/protocol-version' +import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/host-runtime-capabilities' +import { getRemoteRuntimeSharedControlDiagnostics } from '../connections/runtime-environment-request-connections' export function attachRemoteControlDiagnostics( response: RuntimeRpcResponse, diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-owner.ts b/src/main/ipc/runtime-environments/status/runtime-environment-status-owner.ts similarity index 80% rename from src/main/ipc/runtime-environments/runtime-environment-status-owner.ts rename to src/main/ipc/runtime-environments/status/runtime-environment-status-owner.ts index 21ab49cded1..50d2d240e8c 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-status-owner.ts +++ b/src/main/ipc/runtime-environments/status/runtime-environment-status-owner.ts @@ -1,38 +1,39 @@ -import { getRuntimeDesktopSurface } from '../../runtime/construction/runtime-desktop-surface' -import { sendRemoteRuntimeRequestOnSocket } from '../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/protocol-version' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' +import { getRuntimeDesktopSurface } from '../../../runtime/construction/runtime-desktop-surface' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import '../../../../shared/protocol-version' +import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/host-runtime-capabilities' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' import { getPreferredPairedRuntimeConnection, type KnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { managedOrcadRefusalNeedingUserCode } from '../../managed-server/lifecycle/orcad-managed-tunnel-identity' -import { recoverRefusedPairing } from './runtime-environment-pairing-refusal-registry' -import { recordRuntimeEnvironmentUsage } from '../../../shared/remote-runtime/host-store/runtime-environment-usage-record' -import { RuntimeHostStatusOwner } from '../../../shared/remote-runtime/host-status/runtime-host-status-owner' -import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { managedOrcadRefusalNeedingUserCode } from '../../../managed-server/lifecycle/orcad-managed-tunnel-identity' +import { recoverRefusedPairing } from '../pairing/runtime-environment-pairing-refusal-registry' +import { recordRuntimeEnvironmentUsage } from '../../../../shared/remote-runtime/host-store/runtime-environment-usage-record' +import { RuntimeHostStatusOwner } from '../../../../shared/remote-runtime/host-status/runtime-host-status-owner' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' import { RUNTIME_HOST_STATUS_CHANNEL, type RuntimeHostStatusSnapshot, runtimeHostStatusError, runtimeHostStatusFailure, type RuntimeHostStatusResponse -} from '../../../shared/remote-runtime/host-status/runtime-host-status' +} from '../../../../shared/remote-runtime/host-status/runtime-host-status' import { applyRuntimeEnvironmentCapabilityVerdict, getAcceptedRuntimeEnvironmentCapabilityOutcome, getRuntimeEnvironmentCapabilityIncarnation, captureRuntimeEnvironmentCapabilityEvidence -} from './runtime-environment-capability-evidence' -import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' -import { runtimeEnvironmentChangedFailure } from './runtime-environment-revision-guard' -import { resolveManagedRuntimeEnvironment } from './runtime-environment-managed-tunnel' -import { isRecipeVmEnvironmentAsleep } from '../../ephemeral-vm/recipe-vm-asleep' +} from '../connections/runtime-environment-capability-evidence' +import { isRuntimeEnvironmentManuallyDisconnected } from '../connectivity/runtime-environment-manual-disconnect' +import { runtimeEnvironmentChangedFailure } from '../requests/runtime-environment-revision-guard' +import { resolveManagedRuntimeEnvironment } from '../managed-orcad/runtime-environment-managed-tunnel' +import { isRecipeVmEnvironmentAsleep } from '../../../ephemeral-vm/recipe-vm-asleep' import { noteRuntimeEnvironmentStatusContact } from './runtime-environment-contact-loss' import { RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE, RUNTIME_ENVIRONMENT_ASLEEP_MESSAGE -} from '../../../shared/remote-runtime/recipe-vm-wake' +} from '../../../../shared/remote-runtime/recipe-vm-wake' const statusListeners = new Set<(snapshot: RuntimeHostStatusSnapshot) => void>() diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-probe.ts b/src/main/ipc/runtime-environments/status/runtime-environment-status-probe.ts similarity index 75% rename from src/main/ipc/runtime-environments/runtime-environment-status-probe.ts rename to src/main/ipc/runtime-environments/status/runtime-environment-status-probe.ts index 3abcaef4af5..fe904407590 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-status-probe.ts +++ b/src/main/ipc/runtime-environments/status/runtime-environment-status-probe.ts @@ -1,21 +1,21 @@ -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' import { getOrcadSshDeployment, getPreferredPairedRuntimeConnection, getPreferredPairingOffer, type KnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { RuntimeStatus } from '../../../shared/runtime-types' -import { getRuntimeEnvironmentCapabilityIncarnation } from './runtime-environment-capability-evidence' -import { getRuntimeEnvironmentStatusOwner } from './runtime-environment-request-connections' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' +import { getRuntimeEnvironmentCapabilityIncarnation } from '../connections/runtime-environment-capability-evidence' +import { getRuntimeEnvironmentStatusOwner } from '../connections/runtime-environment-request-connections' import { isRuntimeEnvironmentManuallyDisconnected, runtimeEnvironmentManualDisconnectReason -} from './runtime-environment-manual-disconnect' -import { runtimeEnvironmentChangedFailure } from './runtime-environment-revision-guard' +} from '../connectivity/runtime-environment-manual-disconnect' +import { runtimeEnvironmentChangedFailure } from '../requests/runtime-environment-revision-guard' import { attachRemoteControlDiagnostics } from './runtime-environment-status-diagnostics' -import { withTailscaleHintForResponse } from './runtime-environment-tailscale-response' +import { withTailscaleHintForResponse } from '../requests/runtime-environment-tailscale-response' export async function getRuntimeEnvironmentStatus( userDataPath: string, diff --git a/src/main/ipc/runtime-environments/status/runtime-environment-status-retirement.test.ts b/src/main/ipc/runtime-environments/status/runtime-environment-status-retirement.test.ts new file mode 100644 index 00000000000..c1647ebf5fb --- /dev/null +++ b/src/main/ipc/runtime-environments/status/runtime-environment-status-retirement.test.ts @@ -0,0 +1,160 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { + addManagedOrcadEnvironment, + refreshManagedOrcadPairing +} from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { pairingCode } from '../runtime-environments-ipc-test-harness' +import '../../../../shared/protocol-version' +import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/host-runtime-capabilities' +import { + advanceRuntimeEnvironmentCapabilityIncarnation, + resetRuntimeEnvironmentCapabilityEvidence +} from '../connections/runtime-environment-capability-evidence' + +const mocks = vi.hoisted(() => ({ + request: vi.fn(), + ensure: vi.fn(), + reconnect: vi.fn(), + diagnostics: vi.fn() +})) +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ + sendRemoteRuntimeRequestOnSocket: mocks.request +})) +vi.mock('../connections/runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('../runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + ensureRemoteRuntimeSharedControlConnection: mocks.ensure, + reconnectRemoteRuntimeSharedControlConnection: mocks.reconnect, + getRemoteRuntimeSharedControlDiagnostics: mocks.diagnostics, + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: vi.fn() + }) +}) +vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) +// Why: the tunnel is standing; these cases are about what answers through it. +vi.mock('../managed-orcad/runtime-environment-managed-tunnel', () => ({ + resolveManagedRuntimeEnvironment: vi.fn(async () => undefined) +})) + +import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' +import { resetRuntimeEnvironmentStatusOwners } from '../connections/runtime-environment-request-connections' +import { setRefusedPairingHandlers } from '../pairing/runtime-environment-pairing-refusal-registry' + +let directory: string +let envId: string +beforeEach(() => { + vi.clearAllMocks() + resetRuntimeEnvironmentCapabilityEvidence() + directory = mkdtempSync(join(tmpdir(), 'orca-status-retirement-')) + envId = addManagedOrcadEnvironment(directory, { + id: 'env-managed', + name: 'Host', + now: 1, + pairingCode: pairingCode(), + orcadDeployment: { + sshTargetId: 'box', + sshTargetGeneration: 1, + localPort: 6768, + remotePort: 6768 + } + }).id + mocks.diagnostics.mockReturnValue(null) +}) +afterEach(() => { + resetRuntimeEnvironmentStatusOwners() + rmSync(directory, { recursive: true, force: true }) +}) + +function response() { + return { + id: 'status', + ok: true as const, + result: { runtimeId: 'old-host', capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] }, + _meta: { runtimeId: 'old-host' } + } +} + +it('does not fence another environment or a fresh probe after retirement', async () => { + mocks.request.mockImplementation(async () => { + advanceRuntimeEnvironmentCapabilityIncarnation('other') + return response() + }) + await expect(getRuntimeEnvironmentStatus(directory, envId)).resolves.toMatchObject({ ok: true }) + advanceRuntimeEnvironmentCapabilityIncarnation(envId) + await expect(getRuntimeEnvironmentStatus(directory, envId)).resolves.toMatchObject({ ok: true }) + expect(resolveEnvironment(directory, envId).runtimeId).toBe('old-host') +}) + +/** What a re-pair over SSH does mid-probe: store a new pairing and retire the old transports. */ +function repairMidProbe(now: number, keyByte = 1): void { + refreshManagedOrcadPairing( + directory, + envId, + pairingCode(undefined, { deviceToken: `token-${now}`, keyByte }), + now + ) + advanceRuntimeEnvironmentCapabilityIncarnation(envId) +} + +it('answers from the successor owner when the probe itself re-paired the server', async () => { + mocks.request.mockImplementationOnce(async () => { + repairMidProbe(2) + return { + id: 'status', + ok: false, + error: { code: 'unauthorized', message: 'refused' }, + _meta: { runtimeId: 'old-host' } + } + }) + mocks.request.mockResolvedValueOnce(response()) + await expect( + getRuntimeEnvironmentStatus(directory, envId, undefined, { reconnect: true }) + ).resolves.toMatchObject({ ok: true }) +}) + +it.each([ + ['a pairing under another host key', () => repairMidProbe(2, 2), true], + ['a caller pinned to the old pairing', () => repairMidProbe(2), false] +] as const)('never answers %s from the replacement', async (_name, replace, follow) => { + mocks.request.mockImplementationOnce(async () => { + replace() + return response() + }) + mocks.request.mockResolvedValue(response()) + await expect( + getRuntimeEnvironmentStatus(directory, envId, undefined, undefined, follow) + ).resolves.toMatchObject({ ok: false, error: { code: 'runtime_environment_changed' } }) +}) + +it('follows a re-pair only once', async () => { + let now = 2 + mocks.request.mockImplementation(async () => { + repairMidProbe(now++) + return response() + }) + await expect(getRuntimeEnvironmentStatus(directory, envId)).resolves.toMatchObject({ + ok: false, + error: { code: 'runtime_environment_changed' } + }) +}) + +it('does not claim the pairing changed when the refusal only rebuilt the tunnel', async () => { + const noRecovery = { recover: () => null, sharedControl: () => null, connectRequested: () => {} } + setRefusedPairingHandlers({ ...noRecovery, recover: async () => 'built' as const }) + mocks.request.mockResolvedValueOnce({ + id: 'status', + ok: false, + error: { code: 'unauthorized', message: 'refused' }, + _meta: { runtimeId: 'old-host' } + }) + try { + const answer = await getRuntimeEnvironmentStatus(directory, envId) + expect(answer).toMatchObject({ ok: false, error: { code: 'runtime_environment_changed' } }) + } finally { + setRefusedPairingHandlers(noRecovery) + } +}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-verified-transitions.ts b/src/main/ipc/runtime-environments/status/runtime-environment-verified-transitions.ts similarity index 83% rename from src/main/ipc/runtime-environments/runtime-environment-verified-transitions.ts rename to src/main/ipc/runtime-environments/status/runtime-environment-verified-transitions.ts index 4f7cc8e5d8c..bc7193c9f85 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-verified-transitions.ts +++ b/src/main/ipc/runtime-environments/status/runtime-environment-verified-transitions.ts @@ -1,4 +1,4 @@ -import type { RuntimeHostStatusSnapshot } from '../../../shared/remote-runtime/host-status/runtime-host-status' +import type { RuntimeHostStatusSnapshot } from '../../../../shared/remote-runtime/host-status/runtime-host-status' /** Reports a server only when it newly turns verified; repeat publishes of a healthy server stay silent. */ export function trackRuntimeEnvironmentVerifiedTransitions( diff --git a/src/main/ipc/runtime-environments/runtime-environment-session-tabs-delta-decoding.ts b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-session-tabs-delta-decoding.ts similarity index 90% rename from src/main/ipc/runtime-environments/runtime-environment-session-tabs-delta-decoding.ts rename to src/main/ipc/runtime-environments/subscriptions/runtime-environment-session-tabs-delta-decoding.ts index a96508fa8d5..9f876be996a 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-session-tabs-delta-decoding.ts +++ b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-session-tabs-delta-decoding.ts @@ -1,5 +1,5 @@ -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import { createSessionTabsTabDeltaDecoder } from '../../../shared/session-tabs-tab-delta' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import { createSessionTabsTabDeltaDecoder } from '../../../../shared/session-tabs-tab-delta' type SubscriptionEvent = | { type: 'response'; response: RuntimeRpcResponse } diff --git a/src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-events.ts similarity index 90% rename from src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts rename to src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-events.ts index 3a6ea4b428f..10bc9193e1f 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts +++ b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-events.ts @@ -1,4 +1,4 @@ -import { recordRemoteStructuredChatTelemetry } from '../../telemetry/structured-chat-dispatch' +import { recordRemoteStructuredChatTelemetry } from '../../../telemetry/structured-chat-dispatch' import { decodeSessionTabsDeltaEvents } from './runtime-environment-session-tabs-delta-decoding' export function decodeRuntimeEnvironmentSubscriptionEvents( diff --git a/src/main/ipc/runtime-environments/runtime-environment-subscription-handlers.ts b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-handlers.ts similarity index 94% rename from src/main/ipc/runtime-environments/runtime-environment-subscription-handlers.ts rename to src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-handlers.ts index a1c77d5322a..f16b3610377 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-subscription-handlers.ts +++ b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-handlers.ts @@ -9,17 +9,12 @@ import { type RuntimeEnvironmentSubscriptionHandlerDependencies, assertSubscriptionPairingCurrent } from './runtime-environment-subscription-setup' -import type * as SubscriptionSetup from '../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +import type * as SubscriptionSetup from '../../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' import { ipcMain } from 'electron' -import { abortWhenRendererGone } from '../renderer-lifetime-abort' -import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' -import { getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' -import { subscribeRuntimeEnvironment } from './runtime-environment-transport-routing' - -export type { - RetainedRemoteRuntimeSubscription, - PendingRuntimeSubscription -} from './runtime-environment-subscription-setup' +import { abortWhenRendererGone } from '../../renderer-lifetime-abort' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import { getRuntimeEnvironmentTransportGeneration } from '../connections/runtime-environment-transport-generation' +import { subscribeRuntimeEnvironment } from '../requests/runtime-environment-transport-routing' export function registerRuntimeEnvironmentSubscriptionHandlers( args: RuntimeEnvironmentSubscriptionHandlerDependencies diff --git a/src/main/ipc/runtime-environments/runtime-environment-subscription-setup.ts b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-setup.ts similarity index 90% rename from src/main/ipc/runtime-environments/runtime-environment-subscription-setup.ts rename to src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-setup.ts index cfd77429755..13c0368c3cc 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-subscription-setup.ts +++ b/src/main/ipc/runtime-environments/subscriptions/runtime-environment-subscription-setup.ts @@ -1,21 +1,21 @@ import { randomUUID } from 'node:crypto' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import type { IpcMainInvokeEvent, WebContents } from 'electron' -import { isAbortSignalReason, throwIfSignalAborted } from '../../../shared/abort-signal-reason' -import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' +import { isAbortSignalReason, throwIfSignalAborted } from '../../../../shared/abort-signal-reason' +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' import { RuntimeEnvironmentSetupGuardError, runtimeEnvironmentSetupFailure, type CrewSubscriptionSetupResult, type RuntimeEnvironmentSetupFailure -} from '../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' -import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { RuntimeEnvironmentStoreError } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' -import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' -import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { getAcceptedRuntimeEnvironmentCapabilityOutcome } from './runtime-environment-capability-evidence' -import { getRuntimeEnvironmentStatusSnapshot } from './runtime-environment-request-connections' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { RuntimeEnvironmentStoreError } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' +import { isRuntimeEnvironmentManuallyDisconnected } from '../connectivity/runtime-environment-manual-disconnect' +import { getPreferredPairedRuntimeConnection } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { getAcceptedRuntimeEnvironmentCapabilityOutcome } from '../connections/runtime-environment-capability-evidence' +import { getRuntimeEnvironmentStatusSnapshot } from '../connections/runtime-environment-request-connections' export type RuntimeEnvironmentSubscribeArgs = { selector: string diff --git a/src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts b/src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts similarity index 91% rename from src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts rename to src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts index 8e09a9237d2..9f6a0fcbc9c 100644 --- a/src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts +++ b/src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts @@ -1,5 +1,5 @@ -import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' -import { advanceRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' +import { resetRuntimeEnvironmentStatusOwners } from '../connections/runtime-environment-request-connections' +import { advanceRuntimeEnvironmentTransportGeneration } from '../connections/runtime-environment-transport-generation' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -48,15 +48,15 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ sendRemoteRuntimeRequestOnSocket: sendRemoteRuntimeRequestMock })) -vi.mock('../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', () => ({ +vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport', () => ({ subscribeRemoteRuntimeTransport: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', async () => { - const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') +vi.mock('../connections/runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('../runtime-environments-ipc-test-harness') return withRuntimeStatusOwners({ sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, @@ -71,8 +71,8 @@ vi.mock('./runtime-environment-request-connections', async () => { closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock }) }) -import { registerRuntimeEnvironmentHandlers } from './runtime-environments' -import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' +import { registerRuntimeEnvironmentHandlers } from '../runtime-environments' +import { channelHandlerLookup, pairingCode } from '../runtime-environments-ipc-test-harness' const handler = channelHandlerLookup(handleMock) diff --git a/src/main/ipc/runtime-upload-file-stream.test.ts b/src/main/ipc/runtime-upload-file-stream.test.ts index 459f3f2f58c..6b05e63932d 100644 --- a/src/main/ipc/runtime-upload-file-stream.test.ts +++ b/src/main/ipc/runtime-upload-file-stream.test.ts @@ -31,7 +31,7 @@ const callRuntimeEnvironment = ) => unknown >() -vi.mock('./runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('./runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: (...args: Parameters) => callRuntimeEnvironment(...args) })) @@ -43,7 +43,7 @@ vi.mock('./runtime-import-limits', async (importOriginal) => ({ const { RUNTIME_UPLOAD_SLICE_BYTES, streamExternalFileToRuntime } = await import('./runtime-upload-file-stream') -await import('./runtime-environments/runtime-environment-manual-disconnect') +await import('./runtime-environments/connectivity/runtime-environment-manual-disconnect') let workDir: string diff --git a/src/main/ipc/runtime-upload-file-stream.ts b/src/main/ipc/runtime-upload-file-stream.ts index 0569cb502c4..b6760bb2c44 100644 --- a/src/main/ipc/runtime-upload-file-stream.ts +++ b/src/main/ipc/runtime-upload-file-stream.ts @@ -9,8 +9,8 @@ import { formatByteCeiling, REMOTE_IMPORT_MAX_FILE_BYTES } from './runtime-impor import { isRuntimeEnvironmentManuallyDisconnected, RUNTIME_MANUALLY_DISCONNECTED_MESSAGE -} from './runtime-environments/runtime-environment-manual-disconnect' -import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' +} from './runtime-environments/connectivity/runtime-environment-manual-disconnect' +import { callRuntimeEnvironment } from './runtime-environments/requests/runtime-environment-transport-routing' // Base64 expands 384 KiB into the established 512 KiB wire chunk. export const RUNTIME_UPLOAD_SLICE_BYTES = 384 * 1024 diff --git a/src/main/ipc/runtime-upload-temp-sweep.ts b/src/main/ipc/runtime-upload-temp-sweep.ts index 5637740fbda..e2cfa1e2e2a 100644 --- a/src/main/ipc/runtime-upload-temp-sweep.ts +++ b/src/main/ipc/runtime-upload-temp-sweep.ts @@ -1,6 +1,6 @@ import { setTimeout } from 'node:timers/promises' import type { RuntimeUploadFileStreamRequest } from '../../shared/file-import/runtime-upload-staging-contract' -import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from './runtime-environments/requests/runtime-environment-transport-routing' const RUNTIME_UPLOAD_SWEEP_ATTEMPTS = 2 const RUNTIME_UPLOAD_SWEEP_SETTLE_MS = 250 diff --git a/src/main/ipc/runtime.test.ts b/src/main/ipc/runtime.test.ts index fbce1377ade..af14dd74303 100644 --- a/src/main/ipc/runtime.test.ts +++ b/src/main/ipc/runtime.test.ts @@ -108,3 +108,53 @@ describe('registerRuntimeHandlers', () => { expect(runtime.syncWindowGraph).not.toHaveBeenCalled() }) }) + +it('cancels the GitHub host handler through the existing local subscription boundary', async () => { + handleMock.mockClear() + onMock.mockClear() + const entered = Promise.withResolvers() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture supplies every runtime method reached by this upload subscription. + registerRuntimeHandlers({ + getRuntimeId: () => 'local', + uploadGitHubAttachment: (_params: unknown, _bytes: Buffer, signal: AbortSignal) => { + entered.resolve(signal) + return new Promise((_resolve, reject) => + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + ) + } + } as never) + const frame = {} + const sender = { + mainFrame: frame, + id: 14237, + once: vi.fn(), + on: vi.fn(), + send: vi.fn(), + isDestroyed: () => false + } + const event = { senderFrame: frame, sender } + const handler = (channel: string) => handleMock.mock.calls.find(([name]) => name === channel)![1] + const started = await handler('runtime:call')(event, { + method: 'clipboard.startImageUpload', + params: { expectedBase64Length: 8, fileName: 'image.png' } + }) + expect(started.ok).toBe(true) + await handler('runtime:call')(event, { + method: 'clipboard.appendImageUploadChunk', + params: { uploadId: started.result.uploadId, offset: 0, contentBase64: 'aW1hZ2U=' } + }) + handler('runtime:subscribe')(event, { + subscriptionId: 'image-cancel', + method: 'github.uploadAttachment', + params: { + uploadId: started.result.uploadId, + target: { kind: 'repo', repo: 'repo', source: 'origin' }, + fileName: 'image.png', + contentType: 'image/png' + } + }) + const signal = await entered.promise + const unsubscribe = onMock.mock.calls.find(([name]) => name === 'runtime:unsubscribe')![1] + unsubscribe(event, { subscriptionId: 'image-cancel' }) + expect(signal.aborted).toBe(true) +}) diff --git a/src/main/ipc/runtime.ts b/src/main/ipc/runtime.ts index 531e379fa12..16fda71e5a8 100644 --- a/src/main/ipc/runtime.ts +++ b/src/main/ipc/runtime.ts @@ -11,12 +11,12 @@ import type { ClientHostedBrowserRowsEvent } from '../../shared/client-hosted-br import { TERMINAL_FIT_RESTORE_DEADLINE_MS } from '../../shared/terminal/viewport/terminal-fit-restore-deadline' import { DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES } from './desktop-renderer-runtime-capabilities' import { RpcDispatcher } from '../runtime/rpc/dispatcher' -import { DESKTOP_RPC_CALLER } from '../runtime/rpc/rpc-caller-identity' +import { DESKTOP_RPC_CALLER } from '../runtime/rpc/callers/rpc-caller-identity' import { ORCHESTRATION_CONTRACT_VERSION } from '../../shared/orchestration/orchestration-runtime-capabilities' import { ALL_RPC_METHODS } from '../runtime/rpc/methods/rpc-method-registry' import { DesktopRuntimeSenderLifecycle } from './desktop-runtime-sender-lifecycle' import { toWorkspaceLifecycleResult } from '../ephemeral-vm/workspace-lifecycle-result' -import { publishMobileProjectSections } from '../runtime/sidebar-inputs/mobile-project-sections-snapshot' +import { publishMobileProjectSections } from '../runtime/sidebar-inputs/catalog/mobile-project-sections-snapshot' function boundTerminalFitRestore(pending: Promise): Promise { let timer: ReturnType | undefined diff --git a/src/main/ipc/session-window-view-save.test.ts b/src/main/ipc/session-window-view-save.test.ts index 8917d81a623..ac286503b9f 100644 --- a/src/main/ipc/session-window-view-save.test.ts +++ b/src/main/ipc/session-window-view-save.test.ts @@ -8,7 +8,7 @@ import { emptySession, GIT_KEY, leaf -} from '../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' const { handlers } = vi.hoisted(() => ({ diff --git a/src/main/ipc/session.ts b/src/main/ipc/session.ts index ea719873f26..e5beba5daaa 100644 --- a/src/main/ipc/session.ts +++ b/src/main/ipc/session.ts @@ -1,7 +1,7 @@ import { ipcMain } from 'electron' import type { Store } from '../persistence/loading-store/store' import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { parseTerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' +import { parseTerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surfaces/terminal-surface-close-target' import { isFrozenOrcadSourceSessionPartition } from '../persistence/migrating-orcad-catalog/source/catalog/orcad-source-visibility' import { isWslMoveWindowWriteHeld } from '../persistence/moving-wsl-projects/quiescence/wsl-move-window-write-hold' import { visibleSessionHostIds } from '../persistence/migrating-orcad-catalog/retained-source/orcad-retained-source-session' @@ -95,20 +95,9 @@ export function registerSessionHandlers(store: Store, runtime: OrcaRuntimeServic return store.flushPendingOrThrowAsync() }) - ipcMain.on( - 'session:read-terminal-scrollback-sync', - (event, args: { ref?: unknown } | undefined) => { - event.returnValue = - typeof args?.ref === 'string' ? store.readTerminalScrollbackSnapshot(args.ref) : null - } - ) - - // Why: render-time planning only needs to know a local copy exists; a stat never reads bytes. - ipcMain.on( - 'session:has-terminal-scrollback-sync', - (event, args: { ref?: unknown } | undefined) => { - event.returnValue = - typeof args?.ref === 'string' ? store.hasTerminalScrollbackSnapshot(args.ref) : false - } + ipcMain.handle( + 'session:read-terminal-scrollback', + (_event, args: { ref?: unknown } | undefined) => + typeof args?.ref === 'string' ? store.readTerminalScrollbackSnapshotAsync(args.ref) : null ) } diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts index d5cd6411e85..a3bdd6a14ea 100644 --- a/src/main/ipc/settings.ts +++ b/src/main/ipc/settings.ts @@ -33,7 +33,7 @@ import { prepareLocalWorktreeRootsForRepos } from '../workspaces/creation/worktr import { scheduleCurrentWorktreeBaseDirectoryWatcherSync } from './worktrees/creation/worktree-base-directory-watcher' import { applyPRBotAuthorOverride } from '../../shared/source-control/review-comments/pr-bot-author-overrides' import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { readSettingsWithRuntimeEnvironmentPreference } from './runtime-environments/runtime-environment-preference' +import { readSettingsWithRuntimeEnvironmentPreference } from './runtime-environments/catalog/runtime-environment-preference' import { haveSameDisabledTuiAgents } from '../../shared/agent-launch/catalog/tui-agent-selection' import { normalizeMobilePairingCustomAddress, @@ -45,7 +45,7 @@ import { } from '../../shared/computer-awake-mode' import { resolveAiVaultSearchSettings } from '../../shared/ai-vault/search/ai-vault-search-settings' import { applySessionSearchSettingsChange } from '../ai-vault-search/session-search-enablement' -import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/catalog/runtime-environment-registry-root' const SETTINGS_CHANGED_WHITELIST_SET = new Set(SETTINGS_CHANGED_WHITELIST) const registryRoot = getRuntimeEnvironmentRegistryRoot diff --git a/src/main/ipc/skill-cloud-ipc-handlers.test.ts b/src/main/ipc/skill-cloud-ipc-handlers.test.ts index 5b27d2b2776..c7d1f7162c3 100644 --- a/src/main/ipc/skill-cloud-ipc-handlers.test.ts +++ b/src/main/ipc/skill-cloud-ipc-handlers.test.ts @@ -50,12 +50,11 @@ vi.mock('./skill-install-progress-ipc', () => ({ sendBundleInstallProgress: vi.fn(), sendSkillInstallProgress: vi.fn() })) -vi.mock('./runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('./runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: vi.fn() })) import { registerSkillCloudIpcHandlers } from './skill-cloud-ipc-handlers' -import { SkillSharePreparationService } from '../skills/sharing/skill-share-preparation' describe('skill cloud IPC', () => { beforeEach(() => { @@ -101,14 +100,12 @@ describe('skill cloud IPC', () => { } ) ).rejects.toThrow('skill-package-version-mismatch') - expect(installSkillCloudGrantMock).not.toHaveBeenCalled() }) const preparationId = 'cf38dbdc-bff0-4e87-a7ea-ef81b7edaa1a' it('rejects share publication from an unrelated renderer before starting it', () => { - const publish = vi.spyOn(SkillSharePreparationService.prototype, 'publish') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration captures the runtime; the publish spy never accesses it. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration captures the runtime; sender refusal never accesses it. registerSkillCloudIpcHandlers({} as never, vi.fn()) expect(() => @@ -117,8 +114,5 @@ describe('skill cloud IPC', () => { { preparationId, releaseNotes: 'Reviewed release' } ) ).toThrow('Unauthorized skill IPC sender') - expect(publish).not.toHaveBeenCalled() - expect(mainRenderer.send).not.toHaveBeenCalled() - expect(otherRenderer.send).not.toHaveBeenCalled() }) }) diff --git a/src/main/ipc/skill-cloud-ipc-handlers.ts b/src/main/ipc/skill-cloud-ipc-handlers.ts index 8311254e497..e6f810f982f 100644 --- a/src/main/ipc/skill-cloud-ipc-handlers.ts +++ b/src/main/ipc/skill-cloud-ipc-handlers.ts @@ -20,7 +20,7 @@ import { supportsSkillRuntimeCancellation, supportsSkillRuntimeInstall } from '../skills/runtime-transfer/skill-runtime-capability' -import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from './runtime-environments/requests/runtime-environment-transport-routing' import { registerSkillInstallManagementIpcHandlers } from './skill-install-management-ipc-handlers' import { handleMainWindowSkillIpc } from './skill-ipc-main-window' import { sendBundleInstallProgress, sendSkillInstallProgress } from './skill-install-progress-ipc' @@ -35,7 +35,7 @@ import { skillSharePrepareIpcSchema, skillSharePublishIpcSchema } from './skill-share-publishing-ipc-schemas' -import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/catalog/runtime-environment-registry-root' /** Discovery for Share; `skillDirectories` limits which stopped WSL roots it may read. */ export type SkillShareDiscover = ( diff --git a/src/main/ipc/skill-install-management-ipc-handlers.ts b/src/main/ipc/skill-install-management-ipc-handlers.ts index 5a85cca937a..6dfb7dd19f4 100644 --- a/src/main/ipc/skill-install-management-ipc-handlers.ts +++ b/src/main/ipc/skill-install-management-ipc-handlers.ts @@ -19,9 +19,9 @@ import { supportsSkillRuntimeManagement } from '../skills/runtime-transfer/skill-runtime-capability' import { listWslDistrosAsync } from '../wsl/discovery/distro-catalog' -import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from './runtime-environments/requests/runtime-environment-transport-routing' import { handleMainWindowSkillIpc } from './skill-ipc-main-window' -import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/catalog/runtime-environment-registry-root' const environmentIdSchema = z.string().min(1).max(128) const skillNameSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/) diff --git a/src/main/ipc/source-control/github-account-handlers.ts b/src/main/ipc/source-control/github-account-handlers.ts index 6c7ea9aa0aa..57bba84d257 100644 --- a/src/main/ipc/source-control/github-account-handlers.ts +++ b/src/main/ipc/source-control/github-account-handlers.ts @@ -1,14 +1,14 @@ import { ipcMain } from 'electron' import { appStarSourceSchema } from '../../../shared/gh-star-source' -import { resolveGhAccountRequiredHost } from '../../github/account-binding-required-host' -import { diagnoseGhAuth } from '../../github/auth-diagnose' +import { resolveGhAccountRequiredHost } from '../../github/accounts/account-binding-required-host' +import { diagnoseGhAuth } from '../../github/accounts/auth-diagnose' import { checkOrcaStarred, starOrca } from '../../github/client/fetch/orca-star' import { getAuthenticatedViewer } from '../../github/client/fetch/authenticated-viewer' import { listGhAccountBindingInventory, validateGhAccountBinding -} from '../../github/gh-account-binding-inventory' -import { getRateLimit } from '../../github/rate-limit' +} from '../../github/accounts/gh-account-binding-inventory' +import { getRateLimit } from '../../github/api/rate-limit' import type { Store } from '../../persistence/loading-store/store' import { getCohortAtEmit } from '../../telemetry/cohort-classifier' import { track } from '../../telemetry/client' diff --git a/src/main/ipc/source-control/github-ipc-test-harness.ts b/src/main/ipc/source-control/github-ipc-test-harness.ts index 7089875262b..6b501ccd03a 100644 --- a/src/main/ipc/source-control/github-ipc-test-harness.ts +++ b/src/main/ipc/source-control/github-ipc-test-harness.ts @@ -1,5 +1,5 @@ import { vi } from 'vitest' -import { clearPRRefreshValidationBackoffForTests } from '../../github/pr-refresh-validation-backoff' +import { clearPRRefreshValidationBackoffForTests } from '../../github/pull-requests/refresh/pr-refresh-validation-backoff' import { type GitHubIpcMocks, listGitHubIpcMockFns } from './github-ipc-module-mocks' const ORIGINAL_PLATFORM = process.platform diff --git a/src/main/ipc/source-control/github-issue-mutation-handlers.ts b/src/main/ipc/source-control/github-issue-mutation-handlers.ts index 161693b50ef..e8fa1096445 100644 --- a/src/main/ipc/source-control/github-issue-mutation-handlers.ts +++ b/src/main/ipc/source-control/github-issue-mutation-handlers.ts @@ -1,12 +1,12 @@ -import type { GhAccountBinding } from '../../../shared/github/account-binding' -import { OptionalGhAccountExpectation } from '../../../shared/rpc-contract/github-repo-target-params' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import { OptionalGhAccountExpectation } from '../../../shared/rpc-contract/github/github-repo-target-params' import { ipcMain } from 'electron' -import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { GitHubIssueUpdate } from '../../../shared/issue-mutation-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' -import { addIssueComment } from '../../github/issue-comment' -import { listAssignableUsers, listLabels } from '../../github/issue-field-options' -import { updateIssue } from '../../github/issue-update' +import { addIssueComment } from '../../github/issues/issue-comment' +import { listAssignableUsers, listLabels } from '../../github/issues/issue-field-options' +import { updateIssue } from '../../github/issues/issue-update' import type { Store } from '../../persistence/loading-store/store' import { assertRegisteredGitHubRepo, diff --git a/src/main/ipc/source-control/github-pr-mutation-handlers.ts b/src/main/ipc/source-control/github-pr-mutation-handlers.ts index 4cafab2daf9..b7407b358d5 100644 --- a/src/main/ipc/source-control/github-pr-mutation-handlers.ts +++ b/src/main/ipc/source-control/github-pr-mutation-handlers.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { GitHubPullRequestStateUpdate } from '../../../shared/issue-mutation-types' import { markPRReadyForReview } from '../../github/client/update/pr-ready' import { mergePR } from '../../github/client/merge/merge-pr' diff --git a/src/main/ipc/source-control/github-pr-read-handlers.ts b/src/main/ipc/source-control/github-pr-read-handlers.ts index 9ecb2bfc438..72650b65903 100644 --- a/src/main/ipc/source-control/github-pr-read-handlers.ts +++ b/src/main/ipc/source-control/github-pr-read-handlers.ts @@ -1,6 +1,6 @@ import { ipcMain } from 'electron' -import type { GitHubReactionContent } from '../../../shared/github/comment-types' -import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' +import type { GitHubReactionContent } from '../../../shared/github/comments/comment-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import { getPRCheckDetails } from '../../github/client/check/get-pr-check-details' import { getPRChecks } from '../../github/client/check/get-pr-checks' diff --git a/src/main/ipc/source-control/github-pr-refresh-handlers.ts b/src/main/ipc/source-control/github-pr-refresh-handlers.ts index 7ddae33d2f8..6fd54453d72 100644 --- a/src/main/ipc/source-control/github-pr-refresh-handlers.ts +++ b/src/main/ipc/source-control/github-pr-refresh-handlers.ts @@ -5,7 +5,7 @@ import type { GitHubPRRefreshEnqueueResult, GitHubPRRefreshReason, PRRefreshOutcome -} from '../../../shared/github/pull-request-refresh-types' +} from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { Repo } from '../../../shared/repo-types' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { getPRForBranch } from '../../github/client/lookup/get-pr-for-branch' @@ -17,9 +17,9 @@ import { reportVisiblePRRefreshCandidates, addPRRefreshOutcomeObserver, setPRRefreshRegistrationCheck -} from '../../github/pr-refresh-coordinator' -import { setPRRefreshRendererPort } from '../../github/pr-refresh-renderer-port' -import { pullRequestChangeObserver } from '../../github/pull-request-changed-events' +} from '../../github/pull-requests/refresh/pr-refresh-coordinator' +import { setPRRefreshRendererPort } from '../../github/pull-requests/refresh/pr-refresh-renderer-port' +import { pullRequestChangeObserver } from '../../github/pull-requests/refresh/pull-request-changed-events' import { electronPRRefreshRenderer } from '../../host/electron-pr-refresh-renderer' import type { Store } from '../../persistence/loading-store/store' import type { StatsCollector } from '../../stats/collector' diff --git a/src/main/ipc/source-control/github-pr-review-handlers.ts b/src/main/ipc/source-control/github-pr-review-handlers.ts index 6e7adb3e12a..3e261ae5896 100644 --- a/src/main/ipc/source-control/github-pr-review-handlers.ts +++ b/src/main/ipc/source-control/github-pr-review-handlers.ts @@ -1,7 +1,7 @@ -import type { GhAccountBinding } from '../../../shared/github/account-binding' -import { OptionalGhAccountExpectation } from '../../../shared/rpc-contract/github-repo-target-params' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import { OptionalGhAccountExpectation } from '../../../shared/rpc-contract/github/github-repo-target-params' import { ipcMain } from 'electron' -import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import { addPRReviewComment, diff --git a/src/main/ipc/source-control/github-project-view-handlers.ts b/src/main/ipc/source-control/github-project-view-handlers.ts index ac0247be431..f56d9b6f6a6 100644 --- a/src/main/ipc/source-control/github-project-view-handlers.ts +++ b/src/main/ipc/source-control/github-project-view-handlers.ts @@ -18,7 +18,7 @@ import type { UpdateProjectItemFieldArgs, UpdatePullRequestBySlugArgs, WakeWslDistroArg -} from '../../../shared/github/project-request-types' +} from '../../../shared/github/projects/project-request-types' import { addIssueCommentBySlug, deleteIssueCommentBySlug, diff --git a/src/main/ipc/source-control/github-repo-access-guards.test.ts b/src/main/ipc/source-control/github-repo-access-guards.test.ts index 36550af5e22..5ade4e1d7a2 100644 --- a/src/main/ipc/source-control/github-repo-access-guards.test.ts +++ b/src/main/ipc/source-control/github-repo-access-guards.test.ts @@ -1,28 +1,28 @@ -import type * as OrcaStarModule from '../../github/client/fetch/orca-star' -import type * as AuthenticatedViewerModule from '../../github/client/fetch/authenticated-viewer' -import type * as IssueCommentModule from '../../github/issue-comment' -import type * as IssueFieldOptionsModule from '../../github/issue-field-options' -import type * as IssueUpdateModule from '../../github/issue-update' -import type * as PrReadyModule from '../../github/client/update/pr-ready' -import type * as MergePrModule from '../../github/client/merge/merge-pr' -import type * as PrReviewersModule from '../../github/client/update/pr-reviewers' -import type * as RerunPrChecksModule from '../../github/client/check/rerun-pr-checks' -import type * as PrAutoMergeModule from '../../github/client/merge/pr-auto-merge' -import type * as PrStateModule from '../../github/client/update/pr-state' -import type * as PrDetailsModule from '../../github/client/update/pr-details' -import type * as GetPrCheckDetailsModule from '../../github/client/check/get-pr-check-details' -import type * as GetPrChecksModule from '../../github/client/check/get-pr-checks' -import type * as GetPrCommentsModule from '../../github/client/fetch/get-pr-comments' -import type * as ResolveReviewThreadModule from '../../github/client/update/resolve-review-thread' -import type * as PrCommentReactionModule from '../../github/client/update/pr-comment-reaction' import type * as GetPrForBranchModule from '../../github/client/lookup/get-pr-for-branch' -import type * as AddPrReviewCommentModule from '../../github/client/create/add-pr-review-comment' -import type * as PrFileViewedModule from '../../github/client/update/pr-file-viewed' -import type * as CountWorkItemsModule from '../../github/client/list/count-work-items' -import type * as IssueCreateModule from '../../github/issue-create' -import type * as IssuesModule from '../../github/issues' +import type * as IssuesModule from '../../github/issues/issues' import type * as GetWorkItemModule from '../../github/client/fetch/get-work-item' import type * as ListWorkItemsModule from '../../github/client/list/list-work-items' +import type * as CountWorkItemsModule from '../../github/client/list/count-work-items' +import type * as IssueCreateModule from '../../github/issues/issue-create' +import type * as IssueUpdateModule from '../../github/issues/issue-update' +import type * as IssueCommentModule from '../../github/issues/issue-comment' +import type * as IssueFieldOptionsModule from '../../github/issues/issue-field-options' +import type * as AuthenticatedViewerModule from '../../github/client/fetch/authenticated-viewer' +import type * as GetPrChecksModule from '../../github/client/check/get-pr-checks' +import type * as GetPrCheckDetailsModule from '../../github/client/check/get-pr-check-details' +import type * as GetPrCommentsModule from '../../github/client/fetch/get-pr-comments' +import type * as PrCommentReactionModule from '../../github/client/update/pr-comment-reaction' +import type * as ResolveReviewThreadModule from '../../github/client/update/resolve-review-thread' +import type * as PrFileViewedModule from '../../github/client/update/pr-file-viewed' +import type * as AddPrReviewCommentModule from '../../github/client/create/add-pr-review-comment' +import type * as PrDetailsModule from '../../github/client/update/pr-details' +import type * as MergePrModule from '../../github/client/merge/merge-pr' +import type * as PrAutoMergeModule from '../../github/client/merge/pr-auto-merge' +import type * as PrStateModule from '../../github/client/update/pr-state' +import type * as PrReadyModule from '../../github/client/update/pr-ready' +import type * as RerunPrChecksModule from '../../github/client/check/rerun-pr-checks' +import type * as PrReviewersModule from '../../github/client/update/pr-reviewers' +import type * as OrcaStarModule from '../../github/client/fetch/orca-star' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = await vi.hoisted(async () => { @@ -31,125 +31,12 @@ const mocks = await vi.hoisted(async () => { }) vi.mock('electron', () => mocks.electron) -vi.mock('../../github/client', () => mocks.client) - -vi.mock('../../github/client/fetch/orca-star', async (importOriginal) => ({ - ...(await importOriginal()), - checkOrcaStarred: mocks.client.checkOrcaStarred, - starOrca: mocks.client.starOrca -})) - -vi.mock('../../github/client/fetch/authenticated-viewer', async (importOriginal) => ({ - ...(await importOriginal()), - getAuthenticatedViewer: mocks.client.getAuthenticatedViewer -})) - -vi.mock('../../github/issue-comment', async (importOriginal) => ({ - ...(await importOriginal()), - addIssueComment: mocks.client.addIssueComment -})) - -vi.mock('../../github/issue-field-options', async (importOriginal) => ({ - ...(await importOriginal()), - listAssignableUsers: mocks.client.listAssignableUsers, - listLabels: mocks.client.listLabels -})) - -vi.mock('../../github/issue-update', async (importOriginal) => ({ - ...(await importOriginal()), - updateIssue: mocks.client.updateIssue -})) - -vi.mock('../../github/client/update/pr-ready', async (importOriginal) => ({ - ...(await importOriginal()), - markPRReadyForReview: mocks.client.markPRReadyForReview -})) - -vi.mock('../../github/client/merge/merge-pr', async (importOriginal) => ({ - ...(await importOriginal()), - mergePR: mocks.client.mergePR -})) - -vi.mock('../../github/client/update/pr-reviewers', async (importOriginal) => ({ - ...(await importOriginal()), - removePRReviewers: mocks.client.removePRReviewers, - requestPRReviewers: mocks.client.requestPRReviewers -})) - -vi.mock('../../github/client/check/rerun-pr-checks', async (importOriginal) => ({ - ...(await importOriginal()), - rerunPRChecks: mocks.client.rerunPRChecks -})) - -vi.mock('../../github/client/merge/pr-auto-merge', async (importOriginal) => ({ - ...(await importOriginal()), - setPRAutoMerge: mocks.client.setPRAutoMerge -})) - -vi.mock('../../github/client/update/pr-state', async (importOriginal) => ({ - ...(await importOriginal()), - updatePRState: mocks.client.updatePRState -})) - -vi.mock('../../github/client/update/pr-details', async (importOriginal) => ({ - ...(await importOriginal()), - updatePRTitle: mocks.client.updatePRTitle -})) - -vi.mock('../../github/client/check/get-pr-check-details', async (importOriginal) => ({ - ...(await importOriginal()), - getPRCheckDetails: mocks.client.getPRCheckDetails -})) - -vi.mock('../../github/client/check/get-pr-checks', async (importOriginal) => ({ - ...(await importOriginal()), - getPRChecks: mocks.client.getPRChecks -})) - -vi.mock('../../github/client/fetch/get-pr-comments', async (importOriginal) => ({ - ...(await importOriginal()), - getPRComments: mocks.client.getPRComments -})) - -vi.mock('../../github/client/fetch/repo-slug-upstream', () => ({})) - -vi.mock('../../github/client/update/resolve-review-thread', async (importOriginal) => ({ - ...(await importOriginal()), - resolveReviewThread: mocks.client.resolveReviewThread -})) - -vi.mock('../../github/client/update/pr-comment-reaction', async (importOriginal) => ({ - ...(await importOriginal()), - setPRCommentReaction: mocks.client.setPRCommentReaction -})) - vi.mock('../../github/client/lookup/get-pr-for-branch', async (importOriginal) => ({ ...(await importOriginal()), getPRForBranch: mocks.client.getPRForBranch })) -vi.mock('../../github/client/create/add-pr-review-comment', async (importOriginal) => ({ - ...(await importOriginal()), - addPRReviewComment: mocks.client.addPRReviewComment, - addPRReviewCommentReply: mocks.client.addPRReviewCommentReply -})) - -vi.mock('../../github/client/update/pr-file-viewed', async (importOriginal) => ({ - ...(await importOriginal()), - setPRFileViewed: mocks.client.setPRFileViewed -})) - -vi.mock('../../github/client/list/count-work-items', async (importOriginal) => ({ - ...(await importOriginal()), - countWorkItems: mocks.client.countWorkItems -})) - -vi.mock('../../github/issue-create', async (importOriginal) => ({ - ...(await importOriginal()), - createIssue: mocks.client.createIssue -})) - -vi.mock('../../github/issues', async (importOriginal) => ({ +vi.mock('../../github/issues/issues', async (importOriginal) => ({ ...(await importOriginal()), getIssue: mocks.client.getIssue, listIssues: mocks.client.listIssues @@ -165,8 +52,131 @@ vi.mock('../../github/client/list/list-work-items', async (importOriginal) => ({ ...(await importOriginal()), listWorkItems: mocks.client.listWorkItems })) -vi.mock('../../github/work-item-details', () => mocks.workItemDetails) -vi.mock('../../github/pr-refresh-coordinator', () => mocks.prRefresh) + +vi.mock('../../github/client/list/count-work-items', async (importOriginal) => ({ + ...(await importOriginal()), + countWorkItems: mocks.client.countWorkItems +})) + +vi.mock('../../github/issues/issue-create', async (importOriginal) => ({ + ...(await importOriginal()), + createIssue: mocks.client.createIssue +})) + +vi.mock('../../github/issues/issue-update', async (importOriginal) => ({ + ...(await importOriginal()), + updateIssue: mocks.client.updateIssue +})) + +vi.mock('../../github/issues/issue-comment', async (importOriginal) => ({ + ...(await importOriginal()), + addIssueComment: mocks.client.addIssueComment +})) + +vi.mock('../../github/issues/issue-field-options', async (importOriginal) => ({ + ...(await importOriginal()), + listLabels: mocks.client.listLabels, + listAssignableUsers: mocks.client.listAssignableUsers +})) + +vi.mock('../../github/client/fetch/authenticated-viewer', async (importOriginal) => ({ + ...(await importOriginal()), + getAuthenticatedViewer: mocks.client.getAuthenticatedViewer +})) + +vi.mock('../../github/client/check/get-pr-checks', async (importOriginal) => ({ + ...(await importOriginal()), + getPRChecks: mocks.client.getPRChecks +})) + +vi.mock('../../github/client/check/get-pr-check-details', async (importOriginal) => ({ + ...(await importOriginal()), + getPRCheckDetails: mocks.client.getPRCheckDetails +})) + +vi.mock('../../github/client/fetch/get-pr-comments', async (importOriginal) => ({ + ...(await importOriginal()), + getPRComments: mocks.client.getPRComments +})) + +vi.mock('../../github/client/update/pr-comment-reaction', async (importOriginal) => ({ + ...(await importOriginal()), + setPRCommentReaction: mocks.client.setPRCommentReaction +})) + +vi.mock('../../github/client/update/resolve-review-thread', async (importOriginal) => ({ + ...(await importOriginal()), + resolveReviewThread: mocks.client.resolveReviewThread +})) + +vi.mock('../../github/client/update/pr-file-viewed', async (importOriginal) => ({ + ...(await importOriginal()), + setPRFileViewed: mocks.client.setPRFileViewed +})) + +vi.mock('../../github/client/create/add-pr-review-comment', async (importOriginal) => ({ + ...(await importOriginal()), + addPRReviewComment: mocks.client.addPRReviewComment, + addPRReviewCommentReply: mocks.client.addPRReviewCommentReply +})) + +vi.mock('../../github/client/update/pr-details', async (importOriginal) => ({ + ...(await importOriginal()), + updatePRTitle: mocks.client.updatePRTitle +})) + +vi.mock('../../github/client/merge/merge-pr', async (importOriginal) => ({ + ...(await importOriginal()), + mergePR: mocks.client.mergePR +})) + +vi.mock('../../github/client/merge/pr-auto-merge', async (importOriginal) => ({ + ...(await importOriginal()), + setPRAutoMerge: mocks.client.setPRAutoMerge +})) + +vi.mock('../../github/client/update/pr-state', async (importOriginal) => ({ + ...(await importOriginal()), + updatePRState: mocks.client.updatePRState +})) + +vi.mock('../../github/client/update/pr-ready', async (importOriginal) => ({ + ...(await importOriginal()), + markPRReadyForReview: mocks.client.markPRReadyForReview, + markPRDraft: mocks.client.markPRDraft +})) + +vi.mock('../../github/client/check/rerun-pr-checks', async (importOriginal) => ({ + ...(await importOriginal()), + rerunPRChecks: mocks.client.rerunPRChecks +})) + +vi.mock('../../github/client/update/pr-reviewers', async (importOriginal) => ({ + ...(await importOriginal()), + requestPRReviewers: mocks.client.requestPRReviewers, + removePRReviewers: mocks.client.removePRReviewers +})) + +vi.mock('../../github/client/fetch/orca-star', async (importOriginal) => ({ + ...(await importOriginal()), + checkOrcaStarred: mocks.client.checkOrcaStarred, + starOrca: mocks.client.starOrca +})) + +vi.mock('../../github/client/fetch/repo-slug-upstream', () => ({})) + +vi.mock('../../github/work-items/work-item-details', () => { + return { + getWorkItemDetails: mocks.workItemDetails.getWorkItemDetails + } +}) + +vi.mock('../../github/pull-requests/files/pull-request-file-contents', () => { + return { + getPRFileContents: mocks.workItemDetails.getPRFileContents + } +}) +vi.mock('../../github/pull-requests/refresh/pr-refresh-coordinator', () => mocks.prRefresh) vi.mock('../../telemetry/client', () => mocks.telemetry) vi.mock('../../telemetry/cohort-classifier', () => mocks.cohort) vi.mock('../ui', () => mocks.ui) diff --git a/src/main/ipc/source-control/github-repo-routing-twin-host.test.ts b/src/main/ipc/source-control/github-repo-routing-twin-host.test.ts index a0ab3c86c12..7f5d6964ba0 100644 --- a/src/main/ipc/source-control/github-repo-routing-twin-host.test.ts +++ b/src/main/ipc/source-control/github-repo-routing-twin-host.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-request-refresh-types' +import type { GitHubPRRefreshCandidate } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { Repo } from '../../../shared/repo-types' import type { Store } from '../../persistence/loading-store/store' diff --git a/src/main/ipc/source-control/github-repo-routing.ts b/src/main/ipc/source-control/github-repo-routing.ts index ee6037c0304..815b3b7fadb 100644 --- a/src/main/ipc/source-control/github-repo-routing.ts +++ b/src/main/ipc/source-control/github-repo-routing.ts @@ -3,13 +3,13 @@ import { getRepoExecutionHostId } from '../../../shared/execution-host' import type { GitHubPRRefreshCandidate, GitHubPRRefreshEnqueueResult -} from '../../../shared/github/pull-request-refresh-types' +} from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { Repo } from '../../../shared/repo-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import { notePRRefreshValidationDenial, type PRRefreshValidationDenialReason -} from '../../github/pr-refresh-validation-backoff' +} from '../../github/pull-requests/refresh/pr-refresh-validation-backoff' import type { Store } from '../../persistence/loading-store/store' import { getLocalProjectGhExecOptions, diff --git a/src/main/ipc/source-control/github-work-item-handlers.ts b/src/main/ipc/source-control/github-work-item-handlers.ts index d6eef4b6c6f..d30ca48352a 100644 --- a/src/main/ipc/source-control/github-work-item-handlers.ts +++ b/src/main/ipc/source-control/github-work-item-handlers.ts @@ -1,15 +1,17 @@ -import type { GhAccountBinding } from '../../../shared/github/account-binding' -import { OptionalGhAccountExpectation } from '../../../shared/rpc-contract/github-repo-target-params' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import { OptionalGhAccountExpectation } from '../../../shared/rpc-contract/github/github-repo-target-params' import { ipcMain } from 'electron' -import type { GitHubOwnerRepo, GitHubPRFile } from '../../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' +import type { GitHubPRFile } from '../../../shared/github/pull-requests/pull-request-types' import type { GitHubCreateIssueFields } from '../../../shared/issue-mutation-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import { countWorkItems } from '../../github/client/list/count-work-items' -import { createIssue } from '../../github/issue-create' -import { getIssue, listIssues } from '../../github/issues' +import { createIssue } from '../../github/issues/issue-create' +import { getIssue, listIssues } from '../../github/issues/issues' import { getWorkItem, getWorkItemByOwnerRepo } from '../../github/client/fetch/get-work-item' import { listWorkItems } from '../../github/client/list/list-work-items' -import { getPRFileContents, getWorkItemDetails } from '../../github/work-item-details' +import { getPRFileContents } from '../../github/pull-requests/files/pull-request-file-contents' +import { getWorkItemDetails } from '../../github/work-items/work-item-details' import type { Store } from '../../persistence/loading-store/store' import { dispatchWorkItem, type WorkItemArgs } from './github-work-item-args' import { diff --git a/src/main/ipc/source-control/gitlab-ipc-repository-fixture.ts b/src/main/ipc/source-control/gitlab-ipc-repository-fixture.ts deleted file mode 100644 index 4889730a966..00000000000 --- a/src/main/ipc/source-control/gitlab-ipc-repository-fixture.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Repo } from '../../../shared/repo-types' - -export function repo(overrides: Partial = {}): Repo { - return { - id: 'repo-local', - path: '/local/orca', - displayName: 'Orca', - badgeColor: '#737373', - addedAt: 1, - ...overrides - } -} diff --git a/src/main/ipc/source-control/gitlab.test.ts b/src/main/ipc/source-control/gitlab.test.ts deleted file mode 100644 index 5bee45859bc..00000000000 --- a/src/main/ipc/source-control/gitlab.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { repo } from './gitlab-ipc-repository-fixture' -import type * as PipelineJobMutationsModule from '../../gitlab/pipelines/pipeline-job-mutations' -import type * as IssuesModule from '../../gitlab/issues/gitlab-issue-queries' -import type * as ProjectLabelAndMemberLookupModule from '../../gitlab/projects/project-label-and-member-lookup' -import type * as IssueUpdateModule from '../../gitlab/issues/issue-update' -import type * as MergeRequestReviewMutationsModule from '../../gitlab/merge-requests/merge-request-review-mutations' -import type * as MergeRequestStateMutationsModule from '../../gitlab/merge-requests/merge-request-state-mutations' -import type * as MergeRequestUpdateModule from '../../gitlab/merge-requests/merge-request-update' -import type * as MergeRequestLookupModule from '../../gitlab/merge-requests/merge-request-lookup' -import type * as MergeRequestListModule from '../../gitlab/merge-requests/merge-request-list' -import type * as WorkItemQueriesModule from '../../gitlab/work-items/work-item-queries' - -import type * as GitlabAuthAndRateLimitModule from '../../gitlab/requests/gitlab-auth-and-rate-limit' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../../persistence/loading-store/store' -import type { Repo } from '../../../shared/repo-types' -import { toSshExecutionHostId } from '../../../shared/execution-host' - -const ORIGINAL_PLATFORM = process.platform - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { - configurable: true, - value: platform - }) -} - -const { - ipcHandlers, - listMergeRequestsMock, - getIssueMock, - listIssuesMock, - createIssueMock, - updateIssueMock, - addIssueCommentMock, - closeMRMock, - reopenMRMock, - mergeMRMock, - updateMRMock, - updateMRReviewersMock, - addMRCommentMock, - addMRInlineCommentMock, - resolveMRDiscussionMock, - getJobTraceMock, - retryJobMock, - listLabelsMock, - listAssignableUsersMock, - listTodosMock, - listWorkItemsMock, - getWorkItemDetailsMock, - getWorkItemByProjectRefMock, - getMergeRequestMock, - getMergeRequestForBranchMock, - getProjectSlugMock -} = vi.hoisted(() => ({ - ipcHandlers: new Map unknown>(), - listMergeRequestsMock: vi.fn(), - getIssueMock: vi.fn(), - listIssuesMock: vi.fn(), - createIssueMock: vi.fn(), - updateIssueMock: vi.fn(), - addIssueCommentMock: vi.fn(), - closeMRMock: vi.fn(), - reopenMRMock: vi.fn(), - mergeMRMock: vi.fn(), - updateMRMock: vi.fn(), - updateMRReviewersMock: vi.fn(), - addMRCommentMock: vi.fn(), - addMRInlineCommentMock: vi.fn(), - resolveMRDiscussionMock: vi.fn(), - getJobTraceMock: vi.fn(), - retryJobMock: vi.fn(), - listLabelsMock: vi.fn(), - listAssignableUsersMock: vi.fn(), - listTodosMock: vi.fn(), - listWorkItemsMock: vi.fn(), - getWorkItemDetailsMock: vi.fn(), - getWorkItemByProjectRefMock: vi.fn(), - getMergeRequestMock: vi.fn(), - getMergeRequestForBranchMock: vi.fn(), - getProjectSlugMock: vi.fn() -})) -const readWslDistroRunningStateMock = vi.hoisted(() => vi.fn()) -vi.mock('../../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => ({ - ...(await importOriginal>()), - readWslDistroRunningState: readWslDistroRunningStateMock -})) - -vi.mock('electron', () => ({ - ipcMain: { - handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => { - ipcHandlers.set(channel, handler) - }) - } -})) - -vi.mock('../../gitlab/pipelines/pipeline-job-mutations', async (importOriginal) => ({ - ...(await importOriginal()), - getJobTrace: getJobTraceMock, - retryJob: retryJobMock -})) - -vi.mock('../../gitlab/issues/gitlab-issue-queries', async (importOriginal) => ({ - ...(await importOriginal()), - addIssueComment: addIssueCommentMock, - createIssue: createIssueMock, - getIssue: getIssueMock, - listIssues: listIssuesMock -})) - -vi.mock('../../gitlab/projects/project-label-and-member-lookup', async (importOriginal) => ({ - ...(await importOriginal()), - listAssignableUsers: listAssignableUsersMock, - listLabels: listLabelsMock -})) - -vi.mock('../../gitlab/issues/issue-update', async (importOriginal) => ({ - ...(await importOriginal()), - updateIssue: updateIssueMock -})) - -vi.mock('../../gitlab/merge-requests/merge-request-review-mutations', async (importOriginal) => ({ - ...(await importOriginal()), - addMRComment: addMRCommentMock, - addMRInlineComment: addMRInlineCommentMock, - resolveMRDiscussion: resolveMRDiscussionMock, - updateMRReviewers: updateMRReviewersMock -})) - -vi.mock('../../gitlab/merge-requests/merge-request-state-mutations', async (importOriginal) => ({ - ...(await importOriginal()), - closeMR: closeMRMock, - mergeMR: mergeMRMock, - reopenMR: reopenMRMock -})) - -vi.mock('../../gitlab/merge-requests/merge-request-update', async (importOriginal) => ({ - ...(await importOriginal()), - updateMR: updateMRMock -})) - -vi.mock('../../gitlab/merge-requests/merge-request-lookup', async (importOriginal) => ({ - ...(await importOriginal()), - getMergeRequest: getMergeRequestMock, - getMergeRequestForBranch: getMergeRequestForBranchMock, - getProjectSlug: getProjectSlugMock -})) - -vi.mock('../../gitlab/merge-requests/merge-request-list', async (importOriginal) => ({ - ...(await importOriginal()), - listMergeRequests: listMergeRequestsMock -})) - -vi.mock('../../gitlab/work-items/work-item-queries', async (importOriginal) => ({ - ...(await importOriginal()), - getWorkItemByProjectRef: getWorkItemByProjectRefMock, - listWorkItems: listWorkItemsMock, - listTodos: listTodosMock -})) - -vi.mock('../../gitlab/requests/gitlab-auth-and-rate-limit', async (importOriginal) => { - return { - ...(await importOriginal()), - diagnoseAuth: vi.fn(), - getAuthenticatedViewer: vi.fn(), - getRateLimit: vi.fn() - } -}) - -vi.mock('../../gitlab/work-items/work-item-details', () => ({ - getWorkItemDetails: getWorkItemDetailsMock -})) - -vi.mock('../../gitlab/projects/gitlab-project-recents', () => ({ - recordGitLabProjectRecent: vi.fn() -})) - -import { registerGitLabHandlers } from './gitlab' - -function storeWithRepos( - repos: Repo[], - projects: ReturnType = [] -): Pick { - return { - getRepos: () => repos, - getRepo: (id: string) => repos.find((candidate) => candidate.id === id), - getProjects: () => projects, - getSettings: () => - ({ - localWindowsRuntimeDefault: { kind: 'windows-host' } - }) as ReturnType - } -} - -describe('GitLab IPC handlers', () => { - beforeEach(() => { - setPlatform(ORIGINAL_PLATFORM) - ipcHandlers.clear() - for (const mock of [ - listMergeRequestsMock, - getIssueMock, - listIssuesMock, - createIssueMock, - updateIssueMock, - addIssueCommentMock, - closeMRMock, - reopenMRMock, - mergeMRMock, - updateMRMock, - updateMRReviewersMock, - addMRCommentMock, - addMRInlineCommentMock, - resolveMRDiscussionMock, - getJobTraceMock, - retryJobMock, - listLabelsMock, - listAssignableUsersMock, - listTodosMock, - listWorkItemsMock, - getWorkItemDetailsMock, - getWorkItemByProjectRefMock, - getMergeRequestMock, - getMergeRequestForBranchMock, - getProjectSlugMock - ]) { - mock.mockReset() - } - readWslDistroRunningStateMock.mockReset().mockResolvedValue('running') - }) - - it('rejects source context for a different host', async () => { - registerGitLabHandlers( - storeWithRepos([repo({ id: 'repo-local', path: '/local/orca' })]) as Store - ) - - const handler = ipcHandlers.get('gitlab:listWorkItems') - await expect( - handler?.(null, { - repoPath: '/local/orca', - repoId: 'repo-local', - sourceContext: { - kind: 'task-source', - provider: 'gitlab', - projectId: 'gitlab:stablyai/orca', - hostId: toSshExecutionHostId('builder'), - repoId: 'repo-local' - } - }) - ).rejects.toThrow('source host does not match') - }) - - // Bound raw CI traces before they exceed the runtime frame cap (#7732). -}) diff --git a/src/main/ipc/speech.ts b/src/main/ipc/speech.ts index 98f7f52f9b0..284a731a74a 100644 --- a/src/main/ipc/speech.ts +++ b/src/main/ipc/speech.ts @@ -7,6 +7,7 @@ import { } from 'electron' import { abortWhenRendererGone } from './renderer-lifetime-abort' import { dictationTermsFor } from '../../shared/dictation-dictionary' +import { dictationTextSettingsFor } from '../../shared/dictation-cleanup' import { SPEECH_MODEL_CATALOG } from '../speech/model-catalog' import { deleteLocalSpeechModel } from '../speech/speech-model-deletion' import { getSpeechModelManager, getSpeechSttService } from '../speech/speech-runtime-service' @@ -25,8 +26,49 @@ import { } from '../speech/openai-compatible-speech-provider-store' import type { DictationContext, OpenAiCompatibleSpeechProvider } from '../../shared/speech-types' import type { Store } from '../persistence/loading-store/store' +import type { DictationCleanupResult } from '../../shared/dictation-cleanup' +import { cancelDictationCleanup, cleanUpDictatedText } from '../speech/dictation-cleanup-service' +import type { CommitMessageAgentEnvironmentResolvers } from '../text-generation/execution/commit-message-agent-environment' + +// Ten minutes of fast speech is under 20,000 characters; anything far past it isn't dictation. +const MAX_CLEANUP_TEXT_LENGTH = 100_000 + +export function registerSpeechHandlers( + store: Store, + agentEnvResolvers?: CommitMessageAgentEnvironmentResolvers +): void { + ipcMain.handle( + 'speech:cleanUpDictation', + ( + _event, + args: { text: string; context?: DictationContext; requestId: string } + ): Promise => { + if (typeof args?.text !== 'string' || args.text.length > MAX_CLEANUP_TEXT_LENGTH) { + return Promise.resolve({ + status: 'failed', + reason: 'Dictated text is too long to clean up.' + }) + } + return cleanUpDictatedText( + { + text: args.text, + terms: dictationTermsFor(store.getSettings().voice, { + dictationTerms: args.context?.repoTerms, + displayName: args.context?.repoName + }), + requestId: typeof args.requestId === 'string' ? args.requestId : undefined + }, + { getSettings: () => store.getSettings(), getAgentEnvResolvers: () => agentEnvResolvers } + ) + } + ) + + ipcMain.handle('speech:cancelDictationCleanup', (_event, requestId: unknown) => { + if (typeof requestId === 'string') { + cancelDictationCleanup(requestId) + } + }) -export function registerSpeechHandlers(store: Store): void { ipcMain.handle('speech:getCatalog', () => { return SPEECH_MODEL_CATALOG }) @@ -225,7 +267,7 @@ export function registerSpeechHandlers(store: Store): void { displayName: context?.repoName }), owner, - store.getSettings().voice + dictationTextSettingsFor(store.getSettings()) ) // Coalesced starts install no sink; only an accepted start supersedes the close hook. if (sessionReady) { diff --git a/src/main/ipc/ssh/ssh-connect-flow.ts b/src/main/ipc/ssh/ssh-connect-flow.ts index d25e049bd38..b26b81e7159 100644 --- a/src/main/ipc/ssh/ssh-connect-flow.ts +++ b/src/main/ipc/ssh/ssh-connect-flow.ts @@ -12,7 +12,7 @@ import { } from '../../ssh/connection/ssh-connection-attribution' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' -import { noteRuntimeEnvironmentConnectRequested } from '../runtime-environments/runtime-environment-pairing-refusal-registry' +import { noteRuntimeEnvironmentConnectRequested } from '../runtime-environments/pairing/runtime-environment-pairing-refusal-registry' import { decideHostServer, recheckWhenManagedFenceClears, diff --git a/src/main/ipc/ssh/ssh-host-launch-session-note.ts b/src/main/ipc/ssh/ssh-host-launch-session-note.ts index f5fa43272bd..fa5a0923a3c 100644 --- a/src/main/ipc/ssh/ssh-host-launch-session-note.ts +++ b/src/main/ipc/ssh/ssh-host-launch-session-note.ts @@ -8,7 +8,7 @@ import { connectionManager } from './ssh-ipc-context' import { clearLaunchSessionNote, publishHostServerStatus -} from '../runtime-environments/runtime-environment-managed-tunnel' +} from '../runtime-environments/managed-orcad/runtime-environment-managed-tunnel' // Restores run on every runtime call; cache only within the same environment and SSH session. const checked = new WeakMap< diff --git a/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts b/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts index 1287943e670..e9da4cd3c9d 100644 --- a/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts +++ b/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts @@ -8,8 +8,8 @@ import { findOrcadMigrationSourceCutoverForTarget } from '../../persistence/migr import { abandonOrcadConversion } from '../../managed-server/migration/cutover/orcad-conversion-abandon' import { retainOrcadMigrationSource } from '../../persistence/migrating-orcad-catalog/retained-source/orcad-migration-source-retention' import { enableMovedOrcadAutomationsForTarget } from '../../persistence/migrating-orcad-catalog/retained-source/orcad-migration-moved-automations' -import { hasOrcadTemplate } from '../../orcad/orcad-artifact-materializer' -import { isOrcadHostUnavailableFixableOnHost } from '../../orcad/orcad-host-unavailable' +import { hasOrcadTemplate } from '../../orcad/artifact-slots/orcad-artifact-materializer' +import { isOrcadHostUnavailableFixableOnHost } from '../../orcad/diagnostics/orcad-host-unavailable' import { managedServerUpdateDeps } from '../../ssh/host-server/managed-server-update-deps' import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' import { verifyOrcadManagedServing } from '../../managed-server/lifecycle/orcad-managed-serving-verify' diff --git a/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts b/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts index a6ab2753254..67829674b6e 100644 --- a/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts +++ b/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts @@ -25,7 +25,7 @@ vi.mock( }) ) vi.mock( - '../runtime-environments/runtime-environment-request-connections', + '../runtime-environments/connections/runtime-environment-request-connections', async (importOriginal) => ({ ...(await importOriginal()), getRuntimeEnvironmentStatusOwner: runtime.getStatusOwner @@ -35,7 +35,7 @@ vi.mock('../runtime-environments/runtime-environments', () => ({ invalidateRuntimeEnvironmentTransport: runtime.invalidate })) import type { SshTarget } from '../../../shared/ssh-types' -import { clearRuntimeEnvironmentManualDisconnect } from '../runtime-environments/runtime-environment-manual-disconnect' +import { clearRuntimeEnvironmentManualDisconnect } from '../runtime-environments/connectivity/runtime-environment-manual-disconnect' import { isSshUserDisconnected } from '../../ssh/connection/ssh-user-disconnect' import { createSshIpcHarness } from './ssh-ipc-test-harness' import { runTargetLifecycle } from './ssh-target-lifecycle-queue' @@ -91,7 +91,6 @@ describe('a user Disconnect of an SSH host', () => { await expect( handlers.get('ssh:connect')!(null, { targetId: target.id, automatic: true }) ).rejects.toThrow('Server was disconnected. Connect to use it again.') - expect(mockConnectionManager.connect).not.toHaveBeenCalled() expect(isSshUserDisconnected(target.id)).toBe(true) }) }) @@ -108,7 +107,6 @@ describe('a host whose managed server the user stopped and removed', () => { await harness.reset() runtime.environments = [otherServer] mockSshStore.getTarget.mockReturnValue(removed) - vi.mocked((await import('./ssh-host-server-connect')).decideHostServer).mockClear() }) it('holds a reconnect that queued behind the Stop that wrote the hold', async () => { @@ -126,7 +124,5 @@ describe('a host whose managed server the user stopped and removed', () => { await stopping await expect(reconnect).rejects.toThrow('Server was disconnected. Connect to use it again.') - const { decideHostServer } = await import('./ssh-host-server-connect') - expect(decideHostServer).not.toHaveBeenCalled() }) }) diff --git a/src/main/ipc/ssh/ssh-host-user-disconnect.ts b/src/main/ipc/ssh/ssh-host-user-disconnect.ts index 64f67dd2820..7c5e85fe5de 100644 --- a/src/main/ipc/ssh/ssh-host-user-disconnect.ts +++ b/src/main/ipc/ssh/ssh-host-user-disconnect.ts @@ -21,10 +21,10 @@ import { clearRuntimeEnvironmentManualDisconnect, isRuntimeEnvironmentManuallyDisconnected, markRuntimeEnvironmentManuallyDisconnected -} from '../runtime-environments/runtime-environment-manual-disconnect' -import { getRuntimeEnvironmentStatusOwner } from '../runtime-environments/runtime-environment-request-connections' +} from '../runtime-environments/connectivity/runtime-environment-manual-disconnect' +import { getRuntimeEnvironmentStatusOwner } from '../runtime-environments/connections/runtime-environment-request-connections' import { disconnectRegisteredSshTarget } from './ssh-session-teardown' -import { noteRuntimeEnvironmentConnectRequested } from '../runtime-environments/runtime-environment-pairing-refusal-registry' +import { noteRuntimeEnvironmentConnectRequested } from '../runtime-environments/pairing/runtime-environment-pairing-refusal-registry' import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline' /** Managed server and SSH host share user disconnect intent; only explicit Connect may restore either. */ diff --git a/src/main/ipc/ssh/ssh.ts b/src/main/ipc/ssh/ssh.ts index f06b7f3454a..24ee76dd014 100644 --- a/src/main/ipc/ssh/ssh.ts +++ b/src/main/ipc/ssh/ssh.ts @@ -25,7 +25,7 @@ import { resetSshConnectionGenerations } from '../../ssh/connection/authority/ssh-connection-generation' import { resetSshProviderAuthorities } from '../../ssh/connection/authority/ssh-provider-authority' -import { installManagedOrcadStartStatus } from '../runtime-environments/runtime-environment-managed-tunnel' +import { installManagedOrcadStartStatus } from '../runtime-environments/managed-orcad/runtime-environment-managed-tunnel' import { connectInFlight, credentialRequestedForTarget, diff --git a/src/main/ipc/ui.ts b/src/main/ipc/ui.ts index a35b9a5c907..0f47f802993 100644 --- a/src/main/ipc/ui.ts +++ b/src/main/ipc/ui.ts @@ -1,10 +1,10 @@ import { normalizeJiraQuickFilterState } from '../../shared/jira/jira-quick-filters' -import { JiraQuickFilterStateParam } from '../../shared/rpc-contract/jira-quick-filter-params' +import { JiraQuickFilterStateParam } from '../../shared/rpc-contract/jira/jira-quick-filter-params' import { normalizeJiraSavedFilterState, mutateJiraSavedFilterState } from '../../shared/jira/jira-saved-filters' -import { JiraSavedFilterMutationParam } from '../../shared/rpc-contract/jira-saved-filter-params' +import { JiraSavedFilterMutationParam } from '../../shared/rpc-contract/jira/jira-saved-filter-params' import { BrowserWindow, ipcMain, webContents, type WebContents } from 'electron' import type { Store } from '../persistence/loading-store/store' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-activity.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-activity.ts index 93283df7045..a1567b7e471 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-activity.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-activity.ts @@ -4,6 +4,11 @@ import type { Worktree } from '../../../shared/worktree/types' import { resolveGitMetadataPath } from '../../../shared/git/metadata/git-metadata-path' import { getPersistedWorkspaceCleanupActivityAt } from '../../../shared/workspace-cleanup/workspace-cleanup' import type { WorkspaceCleanupGitRoute } from './workspace-cleanup-git-route' +import { + WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, + WorkspaceCleanupScanCancelledError, + withWorkspaceCleanupTimeout +} from './workspace-cleanup-scan-primitives' type StatPath = (targetPath: string) => Promise<{ mtimeMs: number }> type ReadTextFile = (targetPath: string, options?: { tailBytes?: number }) => Promise @@ -179,3 +184,34 @@ async function readMtime(targetPath: string, statPath: StatPath): Promise void, + signal?: AbortSignal, + fsActivityCache?: WorkspaceCleanupFsActivityCache +): Promise { + try { + return await withWorkspaceCleanupTimeout( + () => + resolveWorkspaceCleanupActivityWorktree( + route, + worktree, + undefined, + undefined, + fsActivityCache + ), + WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, + 'Timed out reading worktree activity.', + signal + ) + } catch (error) { + if (error instanceof WorkspaceCleanupScanCancelledError) { + throw error + } + onActivityStatsUnavailable() + console.warn('Workspace cleanup activity scan failed', error) + return resolvePersistedWorkspaceCleanupActivityWorktree(worktree) + } +} diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts index 060e3235188..d6ed55f0e99 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts @@ -2,11 +2,16 @@ import { isFolderRepo } from '../../../shared/repo-kind' import type { Repo } from '../../../shared/repo-types' import type { Worktree } from '../../../shared/worktree/types' import { getWorktreeExecutionHostId } from '../../../shared/execution-host' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' +import type { PRCacheView } from '../../../shared/sidebar-list/workspace-review-facts' import { - applyWorkspaceCleanupPolicy, createWorkspaceCleanupFingerprint, + getWorkspaceCleanupAutomationRunReasons, getWorkspaceCleanupInactivityReasons, + getWorkspaceCleanupMergeReasons, + getWorkspaceCleanupOrchestrationWorkerReasons, isWorkspaceOldForCleanup, + type WorkspaceCleanupAutomationRunLookup, type WorkspaceCleanupBlocker, type WorkspaceCleanupCandidate, type WorkspaceCleanupReason @@ -16,20 +21,42 @@ import { readWorkspaceCleanupGitEvidence } from './workspace-cleanup-git-evidence' import { appendWorkspaceCleanupItems } from './workspace-cleanup-scan-primitives' +import { + getNewestWorkspaceCleanupDiffCommentAt, + shortWorkspaceCleanupBranchName +} from '../../../shared/workspace-cleanup/workspace-cleanup-candidate-fields' import type { WorkspaceCleanupGitRoute } from './workspace-cleanup-git-route' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import type { WorkspaceCleanupReleasedWorker } from './workspace-cleanup-orchestration-workers' +import type { WorkspaceCleanupRepoRefs } from './workspace-cleanup-merge-evidence' export async function buildWorkspaceCleanupCandidate(args: { repo: Repo worktree: Worktree scannedAt: number route: WorkspaceCleanupGitRoute + prCache: PRCacheView skipGit: boolean forceGitCheck: boolean + findAutomationRun: WorkspaceCleanupAutomationRunLookup + releasedWorker?: WorkspaceCleanupReleasedWorker signal?: AbortSignal + repoRefs: WorkspaceCleanupRepoRefs }): Promise { - const { repo, worktree, scannedAt, route, skipGit, forceGitCheck, signal } = args + const { + repo, + worktree, + scannedAt, + route, + prCache, + skipGit, + forceGitCheck, + releasedWorker, + signal, + repoRefs + } = args const blockers: WorkspaceCleanupBlocker[] = [] - const reasons = getWorkspaceCleanupInactivityReasonsForWorkspace(worktree, scannedAt) + const reasons = getWorkspaceCleanupWorkspaceReasons(worktree, scannedAt, args.findAutomationRun) const repoIsFolder = isFolderRepo(repo) if (worktree.isMainWorktree) { @@ -53,8 +80,21 @@ export async function buildWorkspaceCleanupCandidate(args: { const gitEvidence = !shouldReadGit ? createEmptyWorkspaceCleanupGitEvidence() - : await readWorkspaceCleanupGitEvidence(worktree, repo, route, signal) + : await readWorkspaceCleanupGitEvidence( + worktree, + repo, + route, + prCache, + repoRefs, + signal, + releasedWorker?.coordinatorBranch + ) appendWorkspaceCleanupItems(blockers, gitEvidence.blockers) + appendWorkspaceCleanupItems(reasons, getWorkspaceCleanupMergeReasons(gitEvidence.merge)) + appendWorkspaceCleanupItems( + reasons, + getWorkspaceCleanupOrchestrationWorkerReasons(releasedWorker !== undefined, gitEvidence.merge) + ) const candidateWithoutFingerprint: WorkspaceCleanupCandidate = { worktreeId: worktree.id, @@ -62,11 +102,9 @@ export async function buildWorkspaceCleanupCandidate(args: { repoName: repo.displayName, connectionId: repo.connectionId ?? null, executionHostId: getWorktreeExecutionHostId(worktree, repo), - displayName: worktree.displayName, + displayName: worktree.displayName ?? '', branch: shortWorkspaceCleanupBranchName(worktree.branch), path: worktree.path, - tier: 'review', - selectedByDefault: false, reasons, blockers: uniqueWorkspaceCleanupBlockers(blockers), lastActivityAt: worktree.lastActivityAt, @@ -76,7 +114,9 @@ export async function buildWorkspaceCleanupCandidate(args: { clean: gitEvidence.clean, upstreamAhead: gitEvidence.upstreamAhead, upstreamBehind: gitEvidence.upstreamBehind, - checkedAt: gitEvidence.checkedAt + checkedAt: gitEvidence.checkedAt, + ...(gitEvidence.merge ? { merge: gitEvidence.merge } : {}), + atRiskLocalFiles: gitEvidence.atRiskLocalFiles }, fingerprint: '' } @@ -88,12 +128,12 @@ export async function buildWorkspaceCleanupCandidate(args: { lastActivityAt: worktree.lastActivityAt }) - return applyWorkspaceCleanupPolicy({ + return { ...candidateWithoutFingerprint, reasons: uniqueWorkspaceCleanupReasons(reasons), blockers: uniqueWorkspaceCleanupBlockers(blockers), fingerprint - }) + } } export function buildWorkspaceCleanupCandidateFromError( @@ -101,17 +141,15 @@ export function buildWorkspaceCleanupCandidateFromError( worktree: Worktree, scannedAt: number ): WorkspaceCleanupCandidate { - return applyWorkspaceCleanupPolicy({ + return { worktreeId: worktree.id, repoId: repo.id, repoName: repo.displayName, connectionId: repo.connectionId ?? null, executionHostId: getWorktreeExecutionHostId(worktree, repo), - displayName: worktree.displayName, + displayName: worktree.displayName ?? '', branch: shortWorkspaceCleanupBranchName(worktree.branch), path: worktree.path, - tier: 'protected', - selectedByDefault: false, reasons: getWorkspaceCleanupInactivityReasonsForWorkspace(worktree, scannedAt), blockers: ['git-status-error'], lastActivityAt: worktree.lastActivityAt, @@ -129,7 +167,7 @@ export function buildWorkspaceCleanupCandidateFromError( gitClean: null, lastActivityAt: worktree.lastActivityAt }) - }) + } } export function buildWorkspaceCleanupLocalContext( @@ -145,23 +183,6 @@ export function buildWorkspaceCleanupLocalContext( } } -export function getNewestWorkspaceCleanupDiffCommentAt( - diffComments: Worktree['diffComments'] | undefined -): number | null { - if (!diffComments || diffComments.length === 0) { - return null - } - // Large persisted note arrays can exceed JavaScript's spread argument limit. - let newest = diffComments[0]?.createdAt ?? null - for (let index = 1; index < diffComments.length; index += 1) { - const createdAt = diffComments[index]?.createdAt - if (createdAt !== undefined && (newest === null || createdAt > newest)) { - newest = createdAt - } - } - return newest -} - export function isWorkspaceInactiveForCleanup( workspace: Pick, scannedAt: number @@ -176,8 +197,23 @@ export function getWorkspaceCleanupInactivityReasonsForWorkspace( return getWorkspaceCleanupInactivityReasons(workspace, scannedAt) } -export function shortWorkspaceCleanupBranchName(branch: string): string { - return branch.replace(/^refs\/heads\//, '') || 'HEAD' +/** One run snapshot per scan; a store that keeps no automations finds no runs. */ +export function createWorkspaceCleanupAutomationRunLookup( + store: Pick +): WorkspaceCleanupAutomationRunLookup { + const runsById = new Map((store.listAutomationRuns?.() ?? []).map((run) => [run.id, run])) + return (runId) => runsById.get(runId) +} + +function getWorkspaceCleanupWorkspaceReasons( + worktree: Worktree, + scannedAt: number, + findAutomationRun: WorkspaceCleanupAutomationRunLookup +): WorkspaceCleanupReason[] { + return [ + ...getWorkspaceCleanupInactivityReasonsForWorkspace(worktree, scannedAt), + ...getWorkspaceCleanupAutomationRunReasons(worktree.automationProvenance, findAutomationRun) + ] } function shouldReadWorkspaceCleanupGitEvidence(args: { diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-disconnected-ssh.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-disconnected-ssh.ts index a63cf0ff993..65bfc177f3b 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-disconnected-ssh.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-disconnected-ssh.ts @@ -1,19 +1,11 @@ import { basename } from 'node:path' import { getRepoExecutionHostId, normalizeExecutionHostId } from '../../../shared/execution-host' -import type { Store } from '../../persistence/loading-store/store' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' import type { Repo } from '../../../shared/repo-types' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { - applyWorkspaceCleanupPolicy, - createWorkspaceCleanupFingerprint, - type WorkspaceCleanupCandidate -} from '../../../shared/workspace-cleanup/workspace-cleanup' +import type { WorkspaceCleanupCandidate } from '../../../shared/workspace-cleanup/workspace-cleanup' +import { createUnreachableHostCleanupCandidate } from '../../../shared/workspace-cleanup/workspace-cleanup-unreachable-host-candidate' import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' -import { - getNewestWorkspaceCleanupDiffCommentAt, - getWorkspaceCleanupInactivityReasonsForWorkspace, - isWorkspaceInactiveForCleanup -} from './workspace-cleanup-candidate' import { getRepoOwnedWorktreeMeta, isWorktreeMetaOwnedByRepo @@ -24,7 +16,7 @@ import { } from '../../persistence/host-qualified-worktree-meta' export function synthesizeDisconnectedSshCleanupCandidates( - store: Store, + store: RuntimeStore, repo: Repo, scannedAt: number, repoOwnerCount: number, @@ -58,24 +50,15 @@ export function synthesizeDisconnectedSshCleanupCandidates( if (!Object.hasOwn(allMeta, worktreeId) || !worktreeId.startsWith(repoWorktreePrefix)) { continue } - const owned = getRepoOwnedWorktreeMeta(repo, worktreeId, allMeta, repoOwnerCount) - const meta = owned && withTerminalUse(owned) - if (!meta || (!includeAllWorkspaces && !isWorkspaceInactiveForCleanup(meta, scannedAt))) { - continue + const meta = getRepoOwnedWorktreeMeta(repo, worktreeId, allMeta, repoOwnerCount) + const candidate = meta && createDisconnectedSshCandidate(repo, scannedAt, worktreeId, meta) + if (candidate && (includeAllWorkspaces || candidate.reasons.length > 0)) { + candidates.push(candidate) } - candidates.push(createDisconnectedSshCandidate(repo, scannedAt, worktreeId, meta)) } return candidates } -// A terminal used on any device counts, even while its host is unreachable. Unlike the live scan, createdAt is not counted here. -function withTerminalUse(meta: WorktreeMeta): WorktreeMeta { - const usedAt = meta.lastTerminalUseAt - return usedAt !== undefined && Number.isFinite(usedAt) && usedAt > meta.lastActivityAt - ? { ...meta, lastActivityAt: usedAt } - : meta -} - function createDisconnectedSshCandidate( repo: Repo, scannedAt: number, @@ -84,39 +67,16 @@ function createDisconnectedSshCandidate( ): WorkspaceCleanupCandidate { const parsed = splitWorktreeIdForFilesystem(worktreeId) const path = parsed?.worktreePath ?? worktreeId - const reasons = getWorkspaceCleanupInactivityReasonsForWorkspace(meta, scannedAt) - return applyWorkspaceCleanupPolicy({ - worktreeId, - repoId: repo.id, - repoName: repo.displayName, - connectionId: repo.connectionId ?? null, - executionHostId: normalizeExecutionHostId(meta.hostId) ?? getRepoExecutionHostId(repo), - displayName: meta.displayName || basename(path), - branch: basename(path), - path, - reasons, - blockers: ['ssh-disconnected'], - lastActivityAt: meta.lastActivityAt, - ...(meta.createdAt !== undefined ? { createdAt: meta.createdAt } : {}), - localContext: { - terminalTabCount: 0, - cleanEditorTabCount: 0, - browserTabCount: 0, - diffCommentCount: meta.diffComments?.length ?? 0, - newestDiffCommentAt: getNewestWorkspaceCleanupDiffCommentAt(meta.diffComments), - retainedDoneAgentCount: 0 + return createUnreachableHostCleanupCandidate( + repo, + normalizeExecutionHostId(meta.hostId) ?? getRepoExecutionHostId(repo), + { + ...meta, + worktreeId, + path, + displayName: meta.displayName || basename(path), + branch: basename(path) }, - git: { - clean: null, - upstreamAhead: null, - upstreamBehind: null, - checkedAt: null - }, - fingerprint: createWorkspaceCleanupFingerprint({ - branch: basename(path), - head: '', - gitClean: null, - lastActivityAt: meta.lastActivityAt - }) - }) + scannedAt + ) } diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-document-lifetime.test.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-document-lifetime.test.ts index be985c90e77..7fa3793d420 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-document-lifetime.test.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-document-lifetime.test.ts @@ -27,7 +27,7 @@ vi.mock('../../workspaces/catalog/repo-worktrees', async (importOriginal) => ({ ...(await importOriginal()), listRepoWorktrees: boundary.list })) -vi.mock('../../git/source-control/status-read', () => ({ getStatus: boundary.status })) +vi.mock('../../git/source-control/status/status-read', () => ({ getStatus: boundary.status })) vi.mock('../../git/command-runner/git-exec-file', () => ({ gitExecFileAsync: vi.fn(async () => ({ stdout: '0\n', stderr: '' })) })) diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-execution-host-routing.test.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-execution-host-routing.test.ts index 701b75b0cbd..55f1993a49c 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-execution-host-routing.test.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-execution-host-routing.test.ts @@ -33,7 +33,7 @@ vi.mock('../../workspaces/catalog/repo-worktrees', () => ({ createFolderWorktree: vi.fn() })) -vi.mock('../../git/source-control/status-read', () => ({ getStatus: getStatusMock })) +vi.mock('../../git/source-control/status/status-read', () => ({ getStatus: getStatusMock })) vi.mock('../../git/command-runner/git-exec-file', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) @@ -117,28 +117,6 @@ describe('workspace cleanup execution-host routing', () => { vi.useRealTimers() }) - it('never lists or reads an executionHostId-only SSH repo on this machine', async () => { - const store = makeStore([makeRepo({ executionHostId: 'ssh:alpha' })], { - [WORKTREE_ID]: makeMeta() - }) - - await scanWorkspaceCleanup(store) - - expect(listRepoWorktreesMock).not.toHaveBeenCalled() - expect(getStatusMock).not.toHaveBeenCalled() - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('never stats a remote workspace path on this client', async () => { - const store = makeStore([makeRepo({ executionHostId: 'ssh:alpha' })], { - [WORKTREE_ID]: makeMeta({ lastActivityAt: INACTIVE_AT }) - }) - - await scanWorkspaceCleanup(store, { refreshActivity: true }) - - expect(lstatMock).not.toHaveBeenCalled() - }) - it('refuses a runtime host that carries no nested SSH target instead of scanning locally', async () => { const store = makeStore([makeRepo({ executionHostId: 'runtime:env-a' })], { [WORKTREE_ID]: makeMeta() diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-folder-workspaces.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-folder-workspaces.ts index 220be8cd1ec..849c1dc28ed 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-folder-workspaces.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-folder-workspaces.ts @@ -1,4 +1,4 @@ -import type { Store } from '../../persistence/loading-store/store' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' import { createFolderWorktree } from '../../workspaces/catalog/repo-worktrees' import type { Repo } from '../../../shared/repo-types' import type { Worktree } from '../../../shared/worktree/types' @@ -11,7 +11,7 @@ import { mergeWorktree } from '../worktree-metadata-merge' import { getRepoOwnedWorktreeMeta } from '../../workspaces/catalog/worktree-metadata-ownership' export function listWorkspaceCleanupFolderWorkspaces( - store: Store, + store: RuntimeStore, repo: Repo, repoOwnerCount: number ): Worktree[] { diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-git-evidence.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-git-evidence.ts index 44dcdcf198f..07fca96ca0c 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-git-evidence.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-git-evidence.ts @@ -1,12 +1,28 @@ -import { getStatus } from '../../git/source-control/status-read' +import { getStatus } from '../../git/source-control/status/status-read' import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' import type { GitStatusResult } from '../../../shared/git/status/git-status-types' import type { Repo } from '../../../shared/repo-types' import type { Worktree } from '../../../shared/worktree/types' -import type { WorkspaceCleanupBlocker } from '../../../shared/workspace-cleanup/workspace-cleanup' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' +import type { PRCacheView } from '../../../shared/sidebar-list/workspace-review-facts' +import { + isWorkspaceCleanupHeadLanded, + type WorkspaceCleanupBlocker, + type WorkspaceCleanupMergeEvidence +} from '../../../shared/workspace-cleanup/workspace-cleanup' +import { + readWorkspaceCleanupMergeEvidence, + type WorkspaceCleanupRepoRefs +} from './workspace-cleanup-merge-evidence' +import { + hasWorktreeAtRiskLocalFiles, + type WorktreeAtRiskLocalFiles +} from '../../../shared/worktree/removal/at-risk-local-files' +import { readWorktreeAtRiskLocalFiles } from '../../git/worktrees/removal/worktree-at-risk-local-files' import { WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, WorkspaceCleanupScanCancelledError, + throwIfWorkspaceCleanupScanAborted, withWorkspaceCleanupTimeout } from './workspace-cleanup-scan-primitives' import { getWorktreeSharedLinkPaths } from '../../git/worktrees/content-paths/worktree-shared-directories' @@ -20,6 +36,8 @@ export type WorkspaceCleanupGitEvidence = { upstreamAhead: number | null upstreamBehind: number | null checkedAt: number | null + merge?: WorkspaceCleanupMergeEvidence + atRiskLocalFiles: WorktreeAtRiskLocalFiles | null blockers: WorkspaceCleanupBlocker[] } @@ -29,6 +47,7 @@ export function createEmptyWorkspaceCleanupGitEvidence(): WorkspaceCleanupGitEvi upstreamAhead: null, upstreamBehind: null, checkedAt: null, + atRiskLocalFiles: null, blockers: [] } } @@ -37,7 +56,10 @@ export async function readWorkspaceCleanupGitEvidence( worktree: Worktree, repo: Repo, repoRoute: WorkspaceCleanupGitRoute, - signal?: AbortSignal + prCache: PRCacheView, + repoRefs: WorkspaceCleanupRepoRefs, + signal?: AbortSignal, + coordinatorBranch?: string | null ): Promise { const blockers: WorkspaceCleanupBlocker[] = [] let status: GitStatusResult @@ -95,10 +117,20 @@ export async function readWorkspaceCleanupGitEvidence( const upstreamAhead = status.upstreamStatus.hasUpstream ? status.upstreamStatus.ahead : null const upstreamBehind = status.upstreamStatus.hasUpstream ? status.upstreamStatus.behind : null - if (upstreamAhead !== null && upstreamAhead > 0) { + const merge = await readWorkspaceCleanupMergeEvidence( + worktree, + repo, + prCache, + repoRefs, + signal, + coordinatorBranch + ) + // Commits already in the base, a merged review or the coordinator's branch are not at risk, even after a squash rewrote them. + const headLanded = isWorkspaceCleanupHeadLanded(merge) + if (!headLanded && upstreamAhead !== null && upstreamAhead > 0) { blockers.push('unpushed-commits') - } - if (clean && upstreamAhead === null) { + } else if (!headLanded && clean) { + // A deleted remote branch still reads as an upstream 0 ahead; only `--remotes` proves the commits exist there. const unpushedCommitCount = await readUnpushedCommitCount(worktree, signal) if (unpushedCommitCount === null) { blockers.push('unknown-base') @@ -107,15 +139,40 @@ export async function readWorkspaceCleanupGitEvidence( } } + const atRiskLocalFiles = await readCleanupAtRiskLocalFiles(worktree, repo, signal) + if (hasWorktreeAtRiskLocalFiles(atRiskLocalFiles)) { + blockers.push('ignored-files') + } + return { clean, upstreamAhead, upstreamBehind, checkedAt, + ...(merge ? { merge } : {}), + atRiskLocalFiles, blockers: uniqueWorkspaceCleanupGitBlockers(blockers) } } +async function readCleanupAtRiskLocalFiles( + worktree: Worktree, + repo: Repo, + signal?: AbortSignal +): Promise { + try { + return await readWorktreeAtRiskLocalFiles({ + worktreePath: worktree.path, + mainCheckoutPath: repo.path, + gitOptions: signal ? { signal } : {}, + deadlineMs: WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS + }) + } catch (error) { + throwIfWorkspaceCleanupScanAborted(signal) + throw error + } +} + async function readUnpushedCommitCount( worktree: Worktree, signal?: AbortSignal diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-merge-evidence-real-git.test.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-merge-evidence-real-git.test.ts new file mode 100644 index 00000000000..e19ba0d4bc6 --- /dev/null +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-merge-evidence-real-git.test.ts @@ -0,0 +1,224 @@ +// Real Git: squash merges and deleted remote branches are what mocked argv cannot model. +import { execFile } from 'node:child_process' +import { mkdtemp, realpath, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { promisify } from 'node:util' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { installRealWorkerThreadChildProcesses } from '../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' +import { removeTree } from '../../../shared/windows-transient-lock-removal' +import type { Repo } from '../../../shared/repo-types' +import type { Worktree } from '../../../shared/worktree/types' +import { getWorkspaceCleanupMergeReasons } from '../../../shared/workspace-cleanup/workspace-cleanup' +import { readWorkspaceCleanupGitEvidence } from './workspace-cleanup-git-evidence' +import { createWorkspaceCleanupRepoRefs } from './workspace-cleanup-merge-evidence' + +const execFileAsync = promisify(execFile) + +installRealWorkerThreadChildProcesses() + +let scratchDir = '' +let clonePath = '' +let worktreePath = '' + +async function git(args: string[], cwd: string): Promise { + const { stdout } = await execFileAsync('git', args, { cwd }) + return stdout.trim() +} + +async function commitFile(cwd: string, name: string): Promise { + await writeFile(join(cwd, name), `${name}\n`) + await git(['add', name], cwd) + await git(['commit', '-qm', name], cwd) +} + +async function readEvidence(baseRef?: string, branch = 'feature') { + const repo: Repo = { + id: 'repo', + path: clonePath, + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: git evidence reads only these fields of the listed worktree. + const worktree = { + id: `repo::${worktreePath}`, + repoId: 'repo', + path: worktreePath, + branch: `refs/heads/${branch}`, + head: await git(['rev-parse', 'HEAD'], worktreePath), + isMainWorktree: false, + ...(baseRef ? { baseRef } : {}) + } as Worktree + const evidence = await readWorkspaceCleanupGitEvidence( + worktree, + repo, + { kind: 'local', hostId: 'local' }, + {}, + createWorkspaceCleanupRepoRefs(repo) + ) + return { + blockers: evidence.blockers, + merge: evidence.merge, + reasons: getWorkspaceCleanupMergeReasons(evidence.merge) + } +} + +beforeEach(async () => { + scratchDir = await realpath(await mkdtemp(join(tmpdir(), 'orca-cleanup-merge-'))) + const origin = join(scratchDir, 'origin.git') + const seed = join(scratchDir, 'seed') + clonePath = join(scratchDir, 'clone') + worktreePath = join(scratchDir, 'feature') + await git(['init', '-q', '--bare', '-b', 'main', origin], scratchDir) + await git(['init', '-q', '-b', 'main', seed], scratchDir) + await git(['config', 'user.email', 'cleanup@example.invalid'], seed) + await git(['config', 'user.name', 'Cleanup'], seed) + await commitFile(seed, 'seed.txt') + await git(['push', '-q', origin, 'main'], seed) + await git(['clone', '-q', origin, clonePath], scratchDir) + await git(['config', 'user.email', 'cleanup@example.invalid'], clonePath) + await git(['config', 'user.name', 'Cleanup'], clonePath) + await git(['config', 'maintenance.auto', 'false'], clonePath) + await git(['config', 'gc.auto', '0'], clonePath) + await git( + ['worktree', 'add', '-q', '--no-track', '-b', 'feature', worktreePath, 'origin/main'], + clonePath + ) +}) + +afterEach(async () => { + await removeTree(scratchDir) +}) + +describe('workspace cleanup merge evidence against real Git', () => { + it('calls a squash-merged branch whose remote was deleted merged, with no unpushed risk', async () => { + await commitFile(worktreePath, 'a.txt') + await commitFile(worktreePath, 'b.txt') + await git(['push', '-q', '-u', 'origin', 'feature'], worktreePath) + // Squash on main the way a forge does, then delete the remote branch. + await git(['merge', '-q', '--squash', 'feature'], clonePath) + await git(['commit', '-qm', 'squash feature'], clonePath) + await git(['push', '-q', 'origin', 'main', ':feature'], clonePath) + await git(['fetch', '-q', '--prune', 'origin'], clonePath) + + expect(await readEvidence()).toEqual({ + blockers: [], + merge: { headInDefaultBranch: true, aheadOfDefault: 2 }, + reasons: ['merged'] + }) + }) + + it('calls a branch with no commits beyond its base unchanged', async () => { + expect(await readEvidence()).toEqual({ + blockers: [], + merge: { headInDefaultBranch: true, aheadOfDefault: 0 }, + reasons: ['unchanged'] + }) + }) + + it('gives a pushed but unmerged branch neither reason', async () => { + await commitFile(worktreePath, 'a.txt') + await git(['push', '-q', '-u', 'origin', 'feature'], worktreePath) + + expect(await readEvidence()).toEqual({ + blockers: [], + merge: { headInDefaultBranch: false, aheadOfDefault: 1 }, + reasons: [] + }) + }) + + it('keeps unpushed risk when the remote branch was deleted without merging', async () => { + await commitFile(worktreePath, 'a.txt') + await git(['push', '-q', '-u', 'origin', 'feature'], worktreePath) + await git(['push', '-q', 'origin', ':feature'], clonePath) + await git(['fetch', '-q', '--prune', 'origin'], clonePath) + + expect(await readEvidence()).toEqual({ + blockers: ['unpushed-commits'], + merge: { headInDefaultBranch: false, aheadOfDefault: 1 }, + reasons: [] + }) + }) + + it('ignores a base that is the reused branch itself', async () => { + await commitFile(worktreePath, 'a.txt') + + expect((await readEvidence('feature')).blockers).toEqual(['unpushed-commits']) + }) + + it('ignores a default branch that is the workspace branch itself', async () => { + await git(['checkout', '-q', '--detach'], clonePath) + await git(['branch', '-q', '-m', 'main', 'old-main'], clonePath) + await git(['update-ref', '-d', 'refs/remotes/origin/HEAD'], clonePath) + await git(['update-ref', '-d', 'refs/remotes/origin/main'], clonePath) + await git(['branch', '-q', '-m', 'feature', 'main'], worktreePath) + await commitFile(worktreePath, 'a.txt') + + expect((await readEvidence(undefined, 'main')).blockers).toEqual(['unpushed-commits']) + }) + + it('never takes a tag as the base', async () => { + await commitFile(worktreePath, 'a.txt') + await git(['tag', 'release'], worktreePath) + + expect(await readEvidence('release')).toEqual({ + blockers: ['unpushed-commits'], + merge: { headInDefaultBranch: false, aheadOfDefault: 1 }, + reasons: [] + }) + }) + + it('never downloads missing blobs from a partial clone to prove a merge', async () => { + const origin = join(scratchDir, 'origin.git') + await git(['config', 'uploadpack.allowFilter', 'true'], origin) + await writeFile(join(clonePath, 'lines.txt'), 'a\nb\nc\nd\ne\n') + await git(['add', 'lines.txt'], clonePath) + await git(['commit', '-qm', 'lines'], clonePath) + await git(['push', '-q', 'origin', 'main'], clonePath) + const fullClonePath = clonePath + clonePath = join(scratchDir, 'partial') + worktreePath = join(scratchDir, 'partial-feature') + await git( + ['clone', '-q', '--filter=blob:none', pathToFileURL(origin).href, clonePath], + scratchDir + ) + await git(['config', 'user.email', 'cleanup@example.invalid'], clonePath) + await git(['config', 'user.name', 'Cleanup'], clonePath) + await git(['worktree', 'add', '-q', '-b', 'feature', worktreePath, 'origin/main'], clonePath) + await writeFile(join(worktreePath, 'lines.txt'), 'a\nb\nc\nd\nfeature\n') + await git(['commit', '-qam', 'feature'], worktreePath) + await git(['push', '-q', '-u', 'origin', 'feature'], worktreePath) + // Main edits the same file again, so only its new blobs could prove the squash. + await git(['pull', '-q', 'origin', 'main'], fullClonePath) + await writeFile(join(fullClonePath, 'lines.txt'), 'main\nb\nc\nd\ne\n') + await git(['commit', '-qam', 'main edit'], fullClonePath) + await git(['fetch', '-q', 'origin', 'feature'], fullClonePath) + await git(['merge', '-q', '--squash', 'FETCH_HEAD'], fullClonePath) + await git(['commit', '-qm', 'squash feature'], fullClonePath) + await git(['push', '-q', 'origin', 'main'], fullClonePath) + await git(['fetch', '-q', 'origin'], clonePath) + const countMissingObjects = async () => + (await git(['rev-list', '--objects', '--missing=print', '--all'], clonePath)) + .split('\n') + .filter((line) => line.startsWith('?')).length + const missingBefore = await countMissingObjects() + expect(missingBefore).toBeGreaterThan(0) + + const evidence = await readEvidence() + + expect(await countMissingObjects()).toBe(missingBefore) + expect(evidence.merge).toEqual({ headInDefaultBranch: false, aheadOfDefault: 1 }) + }) + + it('keeps unpushed risk for local commits that never landed', async () => { + await commitFile(worktreePath, 'a.txt') + + expect(await readEvidence()).toEqual({ + blockers: ['unpushed-commits'], + merge: { headInDefaultBranch: false, aheadOfDefault: 1 }, + reasons: [] + }) + }) +}) diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-merge-evidence.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-merge-evidence.ts new file mode 100644 index 00000000000..0bcec01113c --- /dev/null +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-merge-evidence.ts @@ -0,0 +1,201 @@ +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' +import { offlineGitEnv } from '../../git/command-runner/git-environment/git-process-env' +import { resolveDefaultBaseRefViaExec } from '../../../shared/git/refs/git-default-base-ref' +import { localBranchHasNoUnmergedChanges } from '../../git/refs/resolution/local-branch-merge-proof' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' +import type { Repo } from '../../../shared/repo-types' +import { + readWorkspaceReviewPR, + type PRCacheView +} from '../../../shared/sidebar-list/workspace-review-facts' +import { isFullGitObjectId } from '../../git/refs/resolution/commit-object-ref' +import { + resolveWorktreeAddBaseRef, + worktreeBaseRefFamily +} from '../../../shared/worktree/base-refs/base-ref' +import type { Worktree } from '../../../shared/worktree/types' +import type { WorkspaceCleanupMergeEvidence } from '../../../shared/workspace-cleanup/workspace-cleanup' +import { + WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, + WorkspaceCleanupScanCancelledError, + withWorkspaceCleanupTimeout +} from './workspace-cleanup-scan-primitives' + +type CleanupGit = (argv: string[]) => Promise<{ stdout: string }> + +/** One scan's branch lookups for a repo: `refs/heads` and `refs/remotes` are shared by all of its worktrees. */ +export type WorkspaceCleanupRepoRefs = { + defaultBaseRef: () => Promise + commitOid: (qualifiedRef: string) => Promise +} + +function cleanupGit(cwd: string, signal: AbortSignal | undefined): CleanupGit { + const env = offlineGitEnv() + return (argv) => gitExecFileAsync(argv, { cwd, env, ...(signal ? { signal } : {}) }) +} + +/** Runs under the scan's signal, not a row's deadline, so one slow row cannot leave a cancelled answer for the rest. */ +export function createWorkspaceCleanupRepoRefs( + repo: Repo, + signal?: AbortSignal +): WorkspaceCleanupRepoRefs { + const git = cleanupGit(repo.path, signal) + let defaultBaseRef: Promise | undefined + const commitOids = new Map>() + return { + defaultBaseRef: () => (defaultBaseRef ??= resolveDefaultBaseRefViaExec(git)), + commitOid: (qualifiedRef) => { + let oid = commitOids.get(qualifiedRef) + if (!oid) { + oid = resolveCommitOid(git, qualifiedRef) + commitOids.set(qualifiedRef, oid) + } + return oid + } + } +} + +/** Offline: local refs and the cached PR only, so a stale cache can miss a merge but never invent one. */ +export async function readWorkspaceCleanupMergeEvidence( + worktree: Worktree, + repo: Repo, + prCache: PRCacheView, + repoRefs: WorkspaceCleanupRepoRefs, + signal?: AbortSignal, + coordinatorBranch?: string | null +): Promise { + try { + return await withWorkspaceCleanupTimeout( + (signal) => readMergeEvidence(worktree, repoRefs, repo, prCache, signal, coordinatorBranch), + WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, + 'Timed out reading merge evidence.', + signal + ) + } catch (error) { + if (error instanceof WorkspaceCleanupScanCancelledError) { + throw error + } + return undefined + } +} + +async function readMergeEvidence( + worktree: Worktree, + repoRefs: WorkspaceCleanupRepoRefs, + repo: Repo, + prCache: PRCacheView, + signal: AbortSignal, + coordinatorBranch: string | null | undefined +): Promise { + const git = cleanupGit(worktree.path, signal) + const baseOid = await resolveWorkspaceCleanupBaseOid(worktree, repo, repoRefs) + // Read HEAD now: the listing's head can predate an agent's newest commit. + const headOid = await resolveCommitOid(git, 'HEAD') + if (!baseOid || !headOid) { + return undefined + } + const aheadOfDefault = Number.parseInt( + (await git(['rev-list', '--count', `${baseOid}..${headOid}`])).stdout.trim(), + 10 + ) + if (!Number.isFinite(aheadOfDefault)) { + return undefined + } + const branchName = worktree.branch.replace(/^refs\/heads\//, '') + // The proof reads the branch ref, so it only speaks for HEAD while HEAD is still that branch. + // Prove against the target alone: the default target list includes the worktree's HEAD, the branch itself. + let branchAtHead: Promise | undefined + const headLandedIn = async (targetOid: string): Promise => + branchName.length > 0 && + (await (branchAtHead ??= resolveCommitOid(git, `refs/heads/${branchName}`).then( + (oid) => oid === headOid + ))) && + localBranchHasNoUnmergedChanges({ + cwd: worktree.path, + branchName, + targetRefs: [targetOid], + refreshRemoteTargets: false, + options: { signal } + }) + const headInDefaultBranch = aheadOfDefault === 0 || (await headLandedIn(baseOid)) + const review = readWorkspaceReviewPR(worktree, repo, prCache) + const head = headOid.toLowerCase() + const mergedReview = + review?.state === 'merged' + ? { + number: review.number, + provider: 'github' as const, + containsHead: [review.headSha, review.confirmedContainedHeadOid].some( + (oid) => oid?.trim().toLowerCase() === head + ) + } + : undefined + // Only worth proving when HEAD has not already landed another way. + const coordinatorOid = + coordinatorBranch && !headInDefaultBranch && mergedReview?.containsHead !== true + ? await repoRefs.commitOid(`refs/heads/${coordinatorBranch}`) + : null + const headInCoordinatorBranch = + coordinatorOid === null + ? undefined + : (await git(['rev-list', '--count', `${coordinatorOid}..${headOid}`])).stdout.trim() === + '0' || (await headLandedIn(coordinatorOid)) + return { + headInDefaultBranch, + aheadOfDefault, + ...(headInCoordinatorBranch !== undefined ? { headInCoordinatorBranch } : {}), + ...(mergedReview ? { mergedReview } : {}) + } +} + +/** First resolvable of worktree base, project base, repo default; a pinned OID is not a branch the work could land in. */ +async function resolveWorkspaceCleanupBaseOid( + worktree: Worktree, + repo: Repo, + repoRefs: WorkspaceCleanupRepoRefs +): Promise { + const branchName = worktree.branch.replace(/^refs\/heads\//, '') + for (const candidate of [worktree.baseRef, repo.worktreeBaseRef]) { + const ref = candidate?.trim() + if (!ref || isFullGitObjectId(ref)) { + continue + } + const oid = await resolveBranchBaseOid(repoRefs, ref, branchName) + if (oid) { + return oid + } + } + const defaultRef = await repoRefs.defaultBaseRef() + return defaultRef ? resolveBranchBaseOid(repoRefs, defaultRef, branchName) : null +} + +/** Qualified so a tag cannot shadow the branch; a reused branch records itself (or its remote copy) as base, which would make every commit look landed. */ +async function resolveBranchBaseOid( + repoRefs: WorkspaceCleanupRepoRefs, + ref: string, + branchName: string +): Promise { + const qualified = await resolveWorktreeAddBaseRef( + ref, + async (candidate) => (await repoRefs.commitOid(candidate)) !== null + ) + const family = worktreeBaseRefFamily(qualified) + // Only a branch can hold landed work; a tag or a name that resolves to nothing is not a base. + if (family === null || family === branchName) { + return null + } + return repoRefs.commitOid(qualified) +} + +async function resolveCommitOid(git: CleanupGit, ref: string): Promise { + if (ref.startsWith('-')) { + return null + } + try { + return ( + (await git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])).stdout.trim() || null + ) + } catch { + return null + } +} diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-orchestration-workers.test.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-orchestration-workers.test.ts new file mode 100644 index 00000000000..cddf29a4415 --- /dev/null +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-orchestration-workers.test.ts @@ -0,0 +1,221 @@ +// Real Git and a real orchestration database: squash proofs and release rows are what mocks cannot model. +import { execFile } from 'node:child_process' +import { mkdtemp, realpath, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { installRealWorkerThreadChildProcesses } from '../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' +import { removeTree } from '../../../shared/windows-transient-lock-removal' +import type { Repo } from '../../../shared/repo-types' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import type { WorktreeLineage } from '../../../shared/worktree/lineage-types' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' +import '../../runtime/orchestration/db/contract-constants' +import '../../runtime/orchestration/db/messages/mailbox-routing-page' +import '../../runtime/orchestration/db/dispatch-row-writer' +import '../../runtime/orchestration/db/attempt-outcome-projection' +import { scanWorkspaceCleanup } from './workspace-cleanup-scan' + +const execFileAsync = promisify(execFile) +// Before any worker the tests start, whose terminals SQLite stamps with the real time. +const WORKSPACE_CREATED_AT = Date.parse('2026-01-01T00:00:00Z') + +installRealWorkerThreadChildProcesses() + +let scratchDir = '' +let repoPath = '' +let db: OrchestrationDb +const meta: Record = {} +const lineage: Record = {} + +async function git(args: string[], cwd: string): Promise { + const { stdout } = await execFileAsync('git', args, { cwd }) + return stdout.trim() +} + +async function commitFile(cwd: string, name: string): Promise { + await writeFile(join(cwd, name), `${name}\n`) + await git(['add', name], cwd) + await git(['commit', '-qm', name], cwd) +} + +async function addWorktree(name: string, from: string): Promise<{ id: string; path: string }> { + const path = join(scratchDir, name) + await git(['worktree', 'add', '-q', '-b', name, path, from], repoPath) + const id = `repo::${path}` + meta[id] = { + instanceId: `${name}-instance`, + displayName: name, + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: WORKSPACE_CREATED_AT, + createdAt: WORKSPACE_CREATED_AT + } + return { id, path } +} + +async function addChild( + name: string, + coordinatorId: string +): Promise<{ id: string; path: string }> { + const child = await addWorktree(name, 'coordinator') + lineage[child.id] = { + worktreeId: child.id, + worktreeInstanceId: `${name}-instance`, + parentWorktreeId: coordinatorId, + parentWorktreeInstanceId: 'coordinator-instance', + origin: 'cli', + capture: { source: 'explicit-cli-flag', confidence: 'explicit' }, + createdAt: WORKSPACE_CREATED_AT + } + return child +} + +/** Starts a worker on the workspace and settles its report; follow-ups reuse the same terminal. */ +function startWorker( + worktreeId: string, + handle: string, + options: { + action?: 'created_child' | 'reused' + terminalOwnership?: 'created' | 'external' + hostScope?: string + } = {} +): string { + const task = db.createTask({ runId: 'run_legacy_local', spec: handle }) + const dispatchId = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: 9, + taskId: task.id, + startOptions: {} + }).dispatch.id + db.prepareStartingWorkerAuthority({ + dispatchId, + handle, + paneKey: `tab_${handle}:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa`, + processIncarnation: `pty:${handle}:1`, + worktreeId, + effects: [{ kind: 'worktree', action: options.action ?? 'created_child', id: worktreeId }], + setupState: 'not_applicable', + terminalOwnership: options.terminalOwnership ?? 'created', + ...(options.hostScope ? { hostScope: options.hostScope } : {}) + }) + db.markWorkerDispatchReady(dispatchId) + db.settleWorkerReport({ taskId: task.id, dispatchId, outcome: 'succeeded', result: 'done' }) + return dispatchId +} + +function releaseWorker(dispatchId: string): void { + const requested = db.requestWorkerTerminalRelease(dispatchId) + if (requested.disposition !== 'requested') { + throw new Error(`release was ${requested.disposition}`) + } + db.settleWorkerTerminalRelease(requested.resource.id) +} + +async function scan(worktreeIds: string[]) { + const repo: Repo = { + id: 'repo', + path: repoPath, + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the scan reads only these store fields for a local repo. + const store = { + getRepos: () => [repo], + getWorktreeMeta: (id: string) => meta[id], + getAllWorktreeMeta: () => meta, + getWorktreeLineage: (id: string) => lineage[id], + getGitHubCache: () => ({ pr: {}, issue: {} }) + } as unknown as RuntimeStore + const result = await scanWorkspaceCleanup( + store, + { worktreeIds }, + { getOrchestrationDb: () => db } + ) + return new Map( + result.candidates.map((candidate) => [ + candidate.worktreeId, + { reasons: candidate.reasons, blockers: candidate.blockers } + ]) + ) +} + +beforeEach(async () => { + // Only Date: real timers keep Git subprocess timeouts working. A day after creation keeps rows active. + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(WORKSPACE_CREATED_AT + 24 * 60 * 60 * 1000) + scratchDir = await realpath(await mkdtemp(join(tmpdir(), 'orca-cleanup-workers-'))) + repoPath = join(scratchDir, 'repo') + await git(['init', '-q', '-b', 'main', repoPath], scratchDir) + await git(['config', 'user.email', 'cleanup@example.invalid'], repoPath) + await git(['config', 'user.name', 'Cleanup'], repoPath) + await git(['config', 'maintenance.auto', 'false'], repoPath) + await git(['config', 'gc.auto', '0'], repoPath) + await commitFile(repoPath, 'seed.txt') + db = new OrchestrationDb(':memory:') +}) + +afterEach(async () => { + vi.useRealTimers() + db.close() + for (const key of Object.keys(meta)) { + delete meta[key] + } + for (const key of Object.keys(lineage)) { + delete lineage[key] + } + await removeTree(scratchDir) +}) + +describe('workspace cleanup for released orchestration workers', () => { + it('suggests a released worker whose work its coordinator squash-merged, and keeps the rest', async () => { + const coordinator = await addWorktree('coordinator', 'main') + const landed = await addChild('landed', coordinator.id) + const unreleased = await addChild('unreleased', coordinator.id) + const unlanded = await addChild('unlanded', coordinator.id) + await commitFile(landed.path, 'landed.txt') + await commitFile(unreleased.path, 'unreleased.txt') + await commitFile(unlanded.path, 'unlanded.txt') + // The coordinator squashes landed's and unreleased's work, never unlanded's. + await git(['merge', '-q', '--squash', 'landed'], coordinator.path) + await git(['commit', '-qm', 'squash landed'], coordinator.path) + await git(['merge', '-q', '--squash', 'unreleased'], coordinator.path) + await git(['commit', '-qm', 'squash unreleased'], coordinator.path) + releaseWorker(startWorker(landed.id, 'term_landed')) + startWorker(unreleased.id, 'term_unreleased') + releaseWorker(startWorker(unlanded.id, 'term_unlanded')) + + const candidates = await scan([landed.id, unreleased.id, unlanded.id]) + + expect(candidates.get(landed.id)).toEqual({ reasons: ['orchestration-worker'], blockers: [] }) + expect(candidates.get(unreleased.id)).toEqual({ reasons: [], blockers: ['unpushed-commits'] }) + expect(candidates.get(unlanded.id)).toEqual({ reasons: [], blockers: ['unpushed-commits'] }) + }) + + it('suggests a worker workspace once the follow-up that took over its terminal is released', async () => { + const coordinator = await addWorktree('coordinator', 'main') + const child = await addChild('child', coordinator.id) + startWorker(child.id, 'term_child') + const followUp = startWorker(child.id, 'term_child', { + action: 'reused', + terminalOwnership: 'external' + }) + expect((await scan([child.id])).get(child.id)?.reasons).toEqual(['unchanged']) + + releaseWorker(followUp) + + expect((await scan([child.id])).get(child.id)?.reasons).toEqual([ + 'unchanged', + 'orchestration-worker' + ]) + }) +}) diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-orchestration-workers.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-orchestration-workers.ts new file mode 100644 index 00000000000..fda9ede5dff --- /dev/null +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-orchestration-workers.ts @@ -0,0 +1,74 @@ +import type { Worktree } from '../../../shared/worktree/types' +import { isValidResolvedWorktreeLineageEdge } from '../../../shared/resolved-worktree-lineage' +import { normalizeLocalBranchName } from '../../runtime/workspaces/catalog/runtime-worktree-selection' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import type { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' +import { + listWorkerCreatedWorktrees, + type WorkerCreatedWorktree +} from '../../runtime/orchestration/db/worker-dispatch/worker-created-worktrees' + +/** A workspace a worker start created whose worker has been released. */ +export type WorkspaceCleanupReleasedWorker = { + /** The coordinator's branch, when the coordinator's workspace is in the same repo; work landed there is not lost. */ + coordinatorBranch: string | null +} + +export type WorkspaceCleanupReleasedWorkerLookup = ( + worktree: Worktree, + repoWorktrees: readonly Worktree[] +) => WorkspaceCleanupReleasedWorker | undefined + +/** Reads the host's workers at most once per scan; a host that never ran orchestration has none. */ +export function createWorkspaceCleanupReleasedWorkerLookup( + store: RuntimeStore, + getOrchestrationDb: (() => OrchestrationDb | null) | undefined +): WorkspaceCleanupReleasedWorkerLookup { + let workerCreatedWorktrees: ReadonlyMap | undefined + return (worktree, repoWorktrees) => { + workerCreatedWorktrees ??= readWorkerCreatedWorktrees(getOrchestrationDb) + return resolveReleasedWorker(worktree, repoWorktrees, workerCreatedWorktrees, store) + } +} + +function readWorkerCreatedWorktrees( + getOrchestrationDb: (() => OrchestrationDb | null) | undefined +): ReadonlyMap { + try { + const db = getOrchestrationDb?.() + return db ? listWorkerCreatedWorktrees(db) : new Map() + } catch (error) { + console.warn('Workspace cleanup could not read orchestration workers', error) + return new Map() + } +} + +function resolveReleasedWorker( + worktree: Worktree, + repoWorktrees: readonly Worktree[], + workerCreatedWorktrees: ReadonlyMap, + store: RuntimeStore +): WorkspaceCleanupReleasedWorker | undefined { + const worker = workerCreatedWorktrees.get(worktree.id) + // SQLite stamps whole seconds. A workspace made after the worker started reuses the path; it is not the worker's. + if ( + !worker?.released || + worktree.createdAt === undefined || + worktree.createdAt >= worker.workerStartedAt + 1000 + ) { + return undefined + } + const lineage = store.getWorktreeLineage?.(worktree.id) + const coordinator = lineage + ? repoWorktrees.find((candidate) => + isValidResolvedWorktreeLineageEdge(worktree, candidate, lineage) + ) + : undefined + const coordinatorBranch = normalizeLocalBranchName(coordinator?.branch) + return { + coordinatorBranch: + coordinatorBranch && coordinatorBranch !== normalizeLocalBranchName(worktree.branch) + ? coordinatorBranch + : null + } +} diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-progress-emitter.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-progress-emitter.ts index 027db458edf..3e5316a8612 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-progress-emitter.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-progress-emitter.ts @@ -4,12 +4,15 @@ import type { WorkspaceCleanupScanProgress } from '../../../shared/workspace-cleanup/workspace-cleanup' import { appendWorkspaceCleanupItems } from './workspace-cleanup-scan-primitives' +import type { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' const WORKSPACE_CLEANUP_PROGRESS_EMIT_INTERVAL_MS = 100 export type WorkspaceCleanupScanOptions = { onProgress?: (progress: WorkspaceCleanupScanProgress) => void signal?: AbortSignal + /** The scanning host's orchestration database, so released workers' workspaces can be classified. */ + getOrchestrationDb?: () => OrchestrationDb | null } export type WorkspaceCleanupProgressEmitter = { diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-scan.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-scan.ts index 6d9c940f90b..44b80c4cfc5 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-scan.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-scan.ts @@ -1,10 +1,13 @@ -import type { Store } from '../../persistence/loading-store/store' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' import { isFolderRepo } from '../../../shared/repo-kind' +import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' +import type { PRCacheView } from '../../../shared/sidebar-list/workspace-review-facts' import { readWorktreeMetaForHost } from '../../persistence/host-qualified-worktree-meta' import type { Repo } from '../../../shared/repo-types' -import type { GitWorktreeInfo, Worktree } from '../../../shared/worktree/types' +import type { GitWorktreeInfo } from '../../../shared/worktree/types' import { mergeWorktree } from '../worktree-metadata-merge' import type { + WorkspaceCleanupAutomationRunLookup, WorkspaceCleanupCandidate, WorkspaceCleanupScanArgs, WorkspaceCleanupScanError, @@ -18,24 +21,24 @@ import type { WorkspaceCleanupGitRoute } from './workspace-cleanup-git-route' import { shouldScanBroadWorkspaceCleanupWorktree } from './workspace-cleanup-scan-eligibility' import { resolvePersistedWorkspaceCleanupActivityWorktree, - resolveWorkspaceCleanupActivityWorktree, + resolveWorkspaceCleanupActivityWithTimeout, type WorkspaceCleanupFsActivityCache } from './workspace-cleanup-activity' import { buildWorkspaceCleanupCandidate, buildWorkspaceCleanupCandidateFromError, + createWorkspaceCleanupAutomationRunLookup, isWorkspaceInactiveForCleanup } from './workspace-cleanup-candidate' import { synthesizeDisconnectedSshCleanupCandidates } from './workspace-cleanup-disconnected-ssh' import { - WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, WorkspaceCleanupScanCancelledError, appendWorkspaceCleanupItems, mapWorkspaceCleanupWithConcurrency, - throwIfWorkspaceCleanupScanAborted, - withWorkspaceCleanupTimeout + throwIfWorkspaceCleanupScanAborted } from './workspace-cleanup-scan-primitives' import { listWorkspaceCleanupFolderWorkspaces } from './workspace-cleanup-folder-workspaces' +import { createWorkspaceCleanupRepoRefs } from './workspace-cleanup-merge-evidence' import { createWorkspaceCleanupProgressEmitter, type WorkspaceCleanupScanOptions @@ -45,6 +48,11 @@ import { hasTargetedWorkspaceCleanupScan } from './workspace-cleanup-scan-targets' import { isWorktreeMetaOwnedByRepo } from '../../workspaces/catalog/worktree-metadata-ownership' +import { runtimeVisibleRepos } from '../../runtime/workspaces/catalog/runtime-visible-catalog' +import { + createWorkspaceCleanupReleasedWorkerLookup, + type WorkspaceCleanupReleasedWorkerLookup +} from './workspace-cleanup-orchestration-workers' const WORKTREE_SCAN_CONCURRENCY = 3 // Overlap repo scans to avoid summing SSH listing round-trip latency. @@ -57,7 +65,7 @@ type WorkspaceCleanupScanRepoProgress = { } export async function scanWorkspaceCleanup( - store: Store, + store: RuntimeStore, args: WorkspaceCleanupScanArgs = {}, options: WorkspaceCleanupScanOptions = {} ): Promise { @@ -68,14 +76,23 @@ export async function scanWorkspaceCleanup( return { scannedAt, candidates: [], errors: [] } } const allRepos = store.getRepos() + // Hidden source rows (an SSH host now served by its own orcad) are that server's to scan. + const visibleRepos = runtimeVisibleRepos(store) const repos = targetWorktreeIdsByRepo.size > 0 - ? allRepos.filter((repo) => targetWorktreeIdsByRepo.has(repo.id)) - : allRepos + ? visibleRepos.filter((repo) => targetWorktreeIdsByRepo.has(repo.id)) + : visibleRepos const repoOwnerCountById = new Map() for (const repo of allRepos) { repoOwnerCountById.set(repo.id, (repoOwnerCountById.get(repo.id) ?? 0) + 1) } + // One snapshot per scan: merged-review evidence reads it without the network. + const prCache = store.getGitHubCache().pr + const findAutomationRun = createWorkspaceCleanupAutomationRunLookup(store) + const findReleasedWorker = createWorkspaceCleanupReleasedWorkerLookup( + store, + options.getOrchestrationDb + ) const progress = createWorkspaceCleanupProgressEmitter(args.scanId, scannedAt, options) const errors: WorkspaceCleanupScanResult['errors'] = [] const candidates: WorkspaceCleanupCandidate[] = [] @@ -91,6 +108,9 @@ export async function scanWorkspaceCleanup( repo, repoOwnerCount: repoOwnerCountById.get(repo.id) ?? 1, scannedAt, + prCache, + findAutomationRun, + findReleasedWorker, targetWorktreeIds: targetWorktreeIdsByRepo.get(repo.id), refreshTargetActivity: args.worktreeId !== undefined || args.refreshActivity === true, includeAllWorkspaces: args.includeAllWorkspaces === true, @@ -114,10 +134,13 @@ export async function scanWorkspaceCleanup( async function scanRepoWorkspaces( args: { - store: Store + store: RuntimeStore repo: Repo repoOwnerCount: number scannedAt: number + prCache: PRCacheView + findAutomationRun: WorkspaceCleanupAutomationRunLookup + findReleasedWorker: WorkspaceCleanupReleasedWorkerLookup targetWorktreeIds?: ReadonlySet refreshTargetActivity: boolean includeAllWorkspaces: boolean @@ -130,6 +153,9 @@ async function scanRepoWorkspaces( repo, repoOwnerCount, scannedAt, + prCache, + findAutomationRun, + findReleasedWorker, targetWorktreeIds, refreshTargetActivity, includeAllWorkspaces, @@ -212,6 +238,7 @@ async function scanRepoWorkspaces( // Stat cannot cancel: after one timeout, use persisted activity rather than queueing more work on a hung mount. let activityStatsUnavailable = false const fsActivityCache: WorkspaceCleanupFsActivityCache = new Map() + const repoRefs = createWorkspaceCleanupRepoRefs(repo, signal) const candidatesWithSkipped = await mapWorkspaceCleanupWithConcurrency( candidateWorktrees, WORKTREE_SCAN_CONCURRENCY, @@ -227,7 +254,7 @@ async function scanRepoWorkspaces( activityStatsUnavailable || (targetWorktreeIds ? !refreshTargetActivity : persistedActivityIsRecent) ? persistedActivityWorktree - : await resolveCleanupActivityWithTimeout( + : await resolveWorkspaceCleanupActivityWithTimeout( route, worktree, () => { @@ -248,10 +275,14 @@ async function scanRepoWorkspaces( worktree: worktreeWithActivity, scannedAt, route, + prCache, // Defer Git for active rows during fleet scans; forced removal preflight reads fresh evidence. skipGit: skipGitWorktreeIds.has(worktreeWithActivity.id) || !isInactive, forceGitCheck: Boolean(targetWorktreeIds), - signal + findAutomationRun, + releasedWorker: findReleasedWorker(worktreeWithActivity, mergedWorktrees), + signal, + repoRefs }).catch((error) => { if (error instanceof WorkspaceCleanupScanCancelledError) { throw error @@ -269,34 +300,3 @@ async function scanRepoWorkspaces( return { scannedAt, candidates, errors } } - -async function resolveCleanupActivityWithTimeout( - route: WorkspaceCleanupGitRoute, - worktree: Worktree, - onActivityStatsUnavailable: () => void, - signal?: AbortSignal, - fsActivityCache?: WorkspaceCleanupFsActivityCache -): Promise { - try { - return await withWorkspaceCleanupTimeout( - () => - resolveWorkspaceCleanupActivityWorktree( - route, - worktree, - undefined, - undefined, - fsActivityCache - ), - WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, - 'Timed out reading worktree activity.', - signal - ) - } catch (error) { - if (error instanceof WorkspaceCleanupScanCancelledError) { - throw error - } - onActivityStatsUnavailable() - console.warn('Workspace cleanup activity scan failed', error) - return resolvePersistedWorkspaceCleanupActivityWorktree(worktree) - } -} diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-worktree-listing.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-worktree-listing.ts index a05753d9599..198f75a1611 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-worktree-listing.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-worktree-listing.ts @@ -1,4 +1,4 @@ -import type { Store } from '../../persistence/loading-store/store' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' import { listRepoWorktrees, createFolderWorktree } from '../../workspaces/catalog/repo-worktrees' import type { Repo } from '../../../shared/repo-types' import type { GitWorktreeInfo } from '../../../shared/worktree/types' @@ -21,7 +21,7 @@ import { import { getLocalProjectWorktreeGitOptions } from '../../workspaces/execution-host/project-runtime-git-options' export async function listCleanupGitWorktrees( - store: Store, + store: RuntimeStore, repo: Repo, repoIsFolder: boolean, signal?: AbortSignal diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup.ts index a0cae5ab93f..58fb43334f5 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup.ts @@ -1,5 +1,6 @@ import { ipcMain } from 'electron' import type { Store } from '../../persistence/loading-store/store' +import type { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' import { WORKSPACE_CLEANUP_CLASSIFIER_VERSION, type WorkspaceCleanupDismissArgs, @@ -32,7 +33,10 @@ function getBroadScanModeKey(senderId: number, args: WorkspaceCleanupScanArgs): return `${senderId}\0${args.includeAllWorkspaces === true}` } -export function registerWorkspaceCleanupHandlers(store: Store): void { +export function registerWorkspaceCleanupHandlers( + store: Store, + getOrchestrationDb?: () => OrchestrationDb | null +): void { const snapshotDirectory = store.getProfileStorageDirectory() ipcMain.removeHandler('workspaceCleanup:scan') ipcMain.removeHandler('workspaceCleanup:cancelScan') @@ -66,6 +70,7 @@ export function registerWorkspaceCleanupHandlers(store: Store): void { try { const result = await scanWorkspaceCleanup(store, scanArgs, { signal: controller.signal, + getOrchestrationDb, onProgress: scanArgs.scanId ? (progress) => { if (!controller.signal.aborted && !sender.isDestroyed()) { diff --git a/src/main/ipc/workspace-space/workspace-space-window.ts b/src/main/ipc/workspace-space/workspace-space-window.ts index 1c5443a91be..21f99e41cf6 100644 --- a/src/main/ipc/workspace-space/workspace-space-window.ts +++ b/src/main/ipc/workspace-space/workspace-space-window.ts @@ -5,8 +5,8 @@ import { getWorkspaceSpaceWindow, isWorkspaceSpaceWindowRenderer } from '../../window/workspace-space-window' -import { safelyRevealWindow } from '../../window/focus-existing-window' -import { isBackgroundLaunch } from '../../window/foreground-activation-policy' +import { safelyRevealWindow } from '../../window/activation/focus-existing-window' +import { isBackgroundLaunch } from '../../window/activation/foreground-activation-policy' import { normalizeExecutionHostId } from '../../../shared/execution-host' import { isWorkspaceSpaceChange } from '../../../shared/workspace-disk-space/workspace-space-change' import type { Store } from '../../persistence/loading-store/store' diff --git a/src/main/ipc/worktree-metadata-merge.ts b/src/main/ipc/worktree-metadata-merge.ts index a2c7f353f30..68e9b11de59 100644 --- a/src/main/ipc/worktree-metadata-merge.ts +++ b/src/main/ipc/worktree-metadata-merge.ts @@ -4,7 +4,7 @@ import { DEFAULT_WORKSPACE_STATUS_ID } from '../../shared/workspace-statuses' import { getLinkedWorkItemMetadata } from './worktree-linked-work-item-metadata' import { normalizeWorkspaceCreatorProvenance } from '../../shared/workspace-creator-provenance' import { createWorktreeIdentity } from '../../shared/worktree/identity' -import { automaticWorktreeDisplayName } from '../../shared/worktree/display-name-provenance' +import { automaticWorktreeDisplayName } from '../../shared/worktree/metadata/display-name-provenance' export function mergeWorktree( repoId: string, @@ -52,6 +52,8 @@ export function mergeWorktree( ...(git.isSparse === true ? { isSparse: true } : {}), isMainWorktree: git.isMainWorktree, ...(git.removalError ? { removalError: git.removalError } : {}), + ...(git.removing ? { removing: true } : {}), + ...(git.removalRecorded ? { removalRecorded: true } : {}), // Automatic labels follow the live branch; persisted values are only authoritative when pinned. displayName: meta?.displayNameIsPinned === false diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 0a90ecee34c..12f85da814d 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -8,7 +8,7 @@ import type { BrowserWindow } from 'electron' import { existsSync } from 'node:fs' import { randomUUID } from 'node:crypto' import type { Store } from '../persistence/loading-store/store' -import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../shared/rpc-contract/source-control/git-admission-tier-params' import type { Repo } from '../../shared/repo-types' import type { CreateWorktreeArgs, @@ -28,7 +28,7 @@ import type { Worktree, WorktreeHeadIdentity } from '../../shared/worktree/types' -import { getPRForBranch } from '../github/client' +import { getPRForBranch } from '../github/client/lookup/get-pr-for-branch' import { addWorktree } from '../git/worktrees/creation/worktree-add' import { addSparseWorktree } from '../git/worktrees/creation/worktree-sparse-add' import type { @@ -104,7 +104,7 @@ import { import type { BranchPrefixSettings } from '../../shared/git/branches/branch-prefix' import { parseWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope' import { sharesWorktreeLineageBoundary } from '../../shared/resolved-worktree-lineage' -import { CrossStoreParentRefSchema } from '../../shared/rpc-contract/cross-store-parent-params' +import { CrossStoreParentRefSchema } from '../../shared/rpc-contract/workspaces/cross-store-parent-params' import { assertParentInAnotherStore } from '../runtime/workspaces/lineage/cross-store-parent-store-check' import { crossStoreManualLineage, @@ -171,8 +171,9 @@ import { getRetiredNameRegistryForRepo, retireGeneratedWorktreeName } from '../workspaces/removal/retirement/worktree-name-retirement' -import { createRetiredNameLookup } from '../../shared/worktree/retired-name-registry' -import { findPendingWorktreeRemovalConflict } from '../workspaces/removal/worktree-removal-table' +import { createRetiredNameLookup } from '../../shared/worktree/naming/retired-name-registry' +import { assertNoPendingWorktreeRemovalConflict } from '../workspaces/removal/worktree-removal-table' +import { isWorktreePathReserved } from '../workspaces/creation/reserved-worktree-path' import { exactNameBranchConflict, exactNameLateCollision, @@ -1221,6 +1222,27 @@ async function performLocalWorktreeCreate( const shouldRetireGeneratedName = args.nameWasGenerated === true && isGeneratedWorktreeCreateName(sanitizedName) const exactName = args.branchIntent === 'create-exact' + if (args.nameWasGenerated !== true || args.branchNameOverride) { + assertNoPendingWorktreeRemovalConflict(repo.path, { + worktreePath: + args.nameWasGenerated === true + ? undefined + : ensurePathWithinWorkspace( + computeWorktreePath(sanitizedName, repo.path, worktreePathSettings, workspaceRoot), + workspaceRoot + ), + branch: + args.branchNameOverride || + (await resolveCreateBranchName( + repo.path, + undefined, + sanitizedName, + settings, + username, + localWorktreeGitOptions + )) + }) + } if ( args.branchIntent === 'open-existing' && args.branchNameOverride && @@ -1291,10 +1313,10 @@ async function performLocalWorktreeCreate( computeWorktreePath(effectiveSanitizedName, repo.path, worktreePathSettings, workspaceRoot), workspaceRoot ) - // Pending removals still own paths Git may already have deleted; skip them until teardown settles. + // Pending removals and archived workspaces still own paths Git may already have deleted. return ( !existsSync(worktreePath) && - !findPendingWorktreeRemovalConflict(repo.path, { worktreePath }) && + !isWorktreePathReserved(store, repo, worktreePath) && pathClaim.claim(worktreePath) ) } diff --git a/src/main/ipc/worktrees-delete-pty-teardown.test.ts b/src/main/ipc/worktrees-delete-pty-teardown.test.ts deleted file mode 100644 index 0bf3532b539..00000000000 --- a/src/main/ipc/worktrees-delete-pty-teardown.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - listWorktreesMock, - removeWorktreeMock, - killAllProcessesForWorktreeMock -} from './worktrees-test-module-mocks' -import { handlers, setupWorktreeHandlers, store } from './worktrees-test-harness' -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' - -vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - return { - ...(await importOriginal()), - listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks')) - .listWorktreesMock, - listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock - } -}) - -vi.mock('electron', async () => - (await import('./worktrees-test-module-mocks')).electronModuleMock() -) -vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({ - ...(await importOriginal>()), - parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({ - ...(await importOriginal>()), - assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks')) - .assertWorktreeCleanForRemovalMock -})) - -vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock -})) - -vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock -})) -vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({ - ...(await importOriginal>()), - listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - describeCreatedWorktree: (await import('./worktrees-test-module-mocks')) - .describeCreatedWorktreeMock -})) -const { getWorktreeRunnerMocks } = vi.hoisted(() => { - function createWorktreeRunnerMocks() { - return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())() - } - let runner: ReturnType | undefined - return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) } -}) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync -})) - -vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync -})) -vi.mock('../git/remotes/repo-remote-queries', async () => ({ - getDefaultRemote: (await import('./worktrees-test-module-mocks')).getDefaultRemoteMock -})) -vi.mock('../git/refs/resolution/repo-branch-conflict', async () => - (await import('./worktrees-test-module-mocks')).gitBranchConflictModuleMock() -) - -vi.mock('../git/refs/resolution/repo-default-base-ref', async (importOriginal) => ({ - ...(await importOriginal>()), - getDefaultBaseRefAsync: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock, - resolveDefaultBaseRefWithLocalGit: (await import('./worktrees-test-module-mocks')) - .resolveDefaultBaseRefWithLocalGitMock -})) -vi.mock('../git/repositories/git-username', async (importOriginal) => ({ - ...(await importOriginal>()), - resolveLocalGitUsername: (await import('./worktrees-test-module-mocks')) - .resolveLocalGitUsernameMock -})) -vi.mock('../github/client', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../github/client/lookup/get-pr-for-branch', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../source-control/hosted-review', async () => - (await import('./worktrees-test-module-mocks')).hostedReviewModuleMock() -) -vi.mock('./worktree-symlinks', async () => - (await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock() -) - -vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({ - ...(await importOriginal>()), - findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks')) - .findExistingWorktreeSymlinkPathsMock -})) -vi.mock('../workspace-hooks/hooks', async () => - (await import('./worktrees-test-module-mocks')).hooksModuleMock() -) -vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('./worktree-logic', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../pty/history/terminal-history-deletion', async () => - (await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock() -) -vi.mock('../ports/advertised-url-watcher', async () => - (await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock() -) -vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock() -) -vi.mock('../runtime/workspaces/removal/worktree-teardown', async () => - (await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock() -) -vi.mock('./pty/provider/registry', async () => - (await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock() -) -vi.mock('./pty/provider/state-cleanup', async () => - (await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock() -) - -describe('registerWorktreeHandlers', () => { - beforeEach(() => { - setupWorktreeHandlers() - }) - - it('refuses an SSH worktree delete this process does not serve, never deleting here', async () => { - const repo = { - id: 'repo-ssh', - path: '/remote/repo', - displayName: 'ssh', - badgeColor: '#000', - addedAt: 0, - connectionId: 'conn-1', - worktreeBaseRef: null - } - store.getRepos.mockReturnValue([repo]) - store.getRepo.mockReturnValue(repo) - - await expect( - handlers['worktrees:remove'](null, { worktreeId: 'repo-ssh::/remote/feature-wt' }) - ).rejects.toThrow(SshHostNotServedError) - - expect(listWorktreesMock).not.toHaveBeenCalled() - expect(removeWorktreeMock).not.toHaveBeenCalled() - expect(killAllProcessesForWorktreeMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/worktrees-issue-command-overrides.test.ts b/src/main/ipc/worktrees-issue-command-overrides.test.ts deleted file mode 100644 index 2526c4a954c..00000000000 --- a/src/main/ipc/worktrees-issue-command-overrides.test.ts +++ /dev/null @@ -1,217 +0,0 @@ -import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { addWorktreeMock, getBranchConflictKindStrictMock } from './worktrees-test-module-mocks' -import { handlers, setupWorktreeHandlers, store } from './worktrees-test-harness' -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' - -vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - return { - ...(await importOriginal()), - listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks')) - .listWorktreesMock, - listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock - } -}) - -vi.mock('electron', async () => - (await import('./worktrees-test-module-mocks')).electronModuleMock() -) -vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({ - ...(await importOriginal>()), - parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({ - ...(await importOriginal>()), - assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks')) - .assertWorktreeCleanForRemovalMock -})) - -vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock -})) - -vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock -})) -vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({ - ...(await importOriginal>()), - listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - describeCreatedWorktree: (await import('./worktrees-test-module-mocks')) - .describeCreatedWorktreeMock -})) -const { getWorktreeRunnerMocks } = vi.hoisted(() => { - function createWorktreeRunnerMocks() { - return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())() - } - let runner: ReturnType | undefined - return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) } -}) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync -})) - -vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync -})) -vi.mock('../git/remotes/repo-remote-queries', async () => ({ - getDefaultRemote: (await import('./worktrees-test-module-mocks')).getDefaultRemoteMock -})) -vi.mock('../git/refs/resolution/repo-branch-conflict', async () => - (await import('./worktrees-test-module-mocks')).gitBranchConflictModuleMock() -) - -vi.mock('../git/refs/resolution/repo-default-base-ref', async (importOriginal) => ({ - ...(await importOriginal>()), - getDefaultBaseRefAsync: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock, - resolveDefaultBaseRefWithLocalGit: (await import('./worktrees-test-module-mocks')) - .resolveDefaultBaseRefWithLocalGitMock -})) -vi.mock('../git/repositories/git-username', async (importOriginal) => ({ - ...(await importOriginal>()), - resolveLocalGitUsername: (await import('./worktrees-test-module-mocks')) - .resolveLocalGitUsernameMock -})) -vi.mock('../github/client', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../github/client/lookup/get-pr-for-branch', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../source-control/hosted-review', async () => - (await import('./worktrees-test-module-mocks')).hostedReviewModuleMock() -) -vi.mock('./worktree-symlinks', async () => - (await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock() -) - -vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({ - ...(await importOriginal>()), - findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks')) - .findExistingWorktreeSymlinkPathsMock -})) -vi.mock('../workspace-hooks/hooks', async () => - (await import('./worktrees-test-module-mocks')).hooksModuleMock() -) -vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('./worktree-logic', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../pty/history/terminal-history-deletion', async () => - (await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock() -) -vi.mock('../ports/advertised-url-watcher', async () => - (await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock() -) -vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock() -) -vi.mock('../runtime/workspaces/removal/worktree-teardown', async () => - (await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock() -) -vi.mock('./pty/provider/registry', async () => - (await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock() -) -vi.mock('./pty/provider/state-cleanup', async () => - (await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock() -) - -const REMOTE_REPO_PATH = '/remote/repo' - -function makeRepo(fields: Record) { - return { - id: 'repo-1', - path: REMOTE_REPO_PATH, - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - worktreeBaseRef: 'origin/main', - ...fields - } -} - -function useRepo(repo: ReturnType): void { - store.getRepos.mockReturnValue([repo]) - store.getRepo.mockReturnValue(repo) - store.setWorktreeMeta.mockImplementation((_target: unknown, meta: unknown) => meta) -} - -describe('worktrees:create execution host routing', () => { - beforeEach(() => { - setupWorktreeHandlers() - }) - - it('refuses a row that names an SSH host only as executionHostId instead of creating locally', async () => { - useRepo(makeRepo({ executionHostId: 'ssh:target-a' })) - - await expect( - handlers['worktrees:create'](null, { repoId: 'repo-1', name: 'wt' }) - ).rejects.toThrow(SshHostNotServedError) - - expect(addWorktreeMock).not.toHaveBeenCalled() - }) -}) - -describe('worktrees:create exact name', () => { - beforeEach(() => { - setupWorktreeHandlers() - }) - - // Electron flattens the error to its message, so the renderer reads the code from the trailing token. - it('refuses a taken name with the code token instead of suffixing', async () => { - getBranchConflictKindStrictMock.mockResolvedValue('local') - - await expect( - handlers['worktrees:create'](null, { - repoId: 'repo-1', - name: 'Login fix', - branchIntent: 'create-exact' - }) - ).rejects.toThrow(/\nworktree_create_exact_name_taken$/) - - expect(addWorktreeMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/worktrees-orphan-directory-cleanup.test.ts b/src/main/ipc/worktrees-orphan-directory-cleanup.test.ts index 47b3e4c734a..711938f49ff 100644 --- a/src/main/ipc/worktrees-orphan-directory-cleanup.test.ts +++ b/src/main/ipc/worktrees-orphan-directory-cleanup.test.ts @@ -99,12 +99,23 @@ vi.mock('../git/repositories/git-username', async (importOriginal) => ({ resolveLocalGitUsername: (await import('./worktrees-test-module-mocks')) .resolveLocalGitUsernameMock })) -vi.mock('../github/client', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../github/client/lookup/get-pr-for-branch', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) +vi.mock('../github/client/lookup/get-pr-for-branch', async () => ({ + getPRForBranch: (await import('./worktrees-test-module-mocks')).getPRForBranchMock +})) + +vi.mock('../github/client/fetch/get-work-item', async () => { + return { + getWorkItem: (await import('./worktrees-test-module-mocks')).getWorkItemMock + } +}) + +vi.mock('../github/client/lookup/pull-request-push-target', async () => { + return { + getPullRequestPushTarget: (await import('./worktrees-test-module-mocks')) + .getPullRequestPushTargetMock + } +}) + vi.mock('../source-control/hosted-review', async () => (await import('./worktrees-test-module-mocks')).hostedReviewModuleMock() ) @@ -228,45 +239,6 @@ describe('registerWorktreeHandlers', () => { } }) - it('prompts for force before removing an Orca-created orphaned worktree directory', async () => { - const parentDir = await mkdtemp(join(tmpdir(), 'orca-ipc-orphan-')) - const repoPath = join(parentDir, 'repo') - const orphanPath = join(parentDir, 'orphan') - const adminWorktreePath = join(repoPath, '.git', 'worktrees', 'orphan') - await mkdir(orphanPath, { recursive: true }) - await mkdir(adminWorktreePath, { recursive: true }) - await writeFile(join(orphanPath, '.git'), `gitdir: ${adminWorktreePath}\n`) - await writeFile(join(adminWorktreePath, 'gitdir'), `${join(orphanPath, '.git')}\n`) - const repo = { - id: 'repo-1', - path: repoPath, - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - worktreeBaseRef: null - } - store.getRepo.mockReturnValue(repo) - store.getRepos.mockReturnValue([repo]) - mockKnownFeatureWorktree(join(parentDir, 'real-feature'), repoPath) - store.getWorktreeMeta.mockReturnValue( - makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'runtime' }) - ) - - try { - await expect( - handlers['worktrees:remove'](null, { - worktreeId: `repo-1::${orphanPath}` - }) - ).rejects.toThrow('Worktree is no longer registered with Git but its directory remains.') - - await expect(lstat(orphanPath)).resolves.toBeTruthy() - expect(removeWorktreeMock).not.toHaveBeenCalled() - expect(store.removeWorktreeMeta).not.toHaveBeenCalled() - } finally { - await rm(parentDir, { recursive: true, force: true }) - } - }) - it('refuses an Orca-created unregistered directory with no git marker, even forced, until the user removes it', async () => { const parentDir = await mkdtemp(join(tmpdir(), 'orca-ipc-leftover-')) const repoPath = join(parentDir, 'repo') @@ -316,69 +288,4 @@ describe('registerWorktreeHandlers', () => { await rm(parentDir, { recursive: true, force: true }) } }) - - it('rejects an Orca-created unregistered local directory with a git directory', async () => { - const parentDir = await mkdtemp(join(tmpdir(), 'orca-ipc-standalone-')) - const repoPath = join(parentDir, 'repo') - const standalonePath = join(parentDir, 'standalone') - await mkdir(join(standalonePath, '.git'), { recursive: true }) - store.getRepo.mockReturnValue({ - id: 'repo-1', - path: repoPath, - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - worktreeBaseRef: null - }) - mockKnownFeatureWorktree(join(parentDir, 'real-feature'), repoPath) - store.getWorktreeMeta.mockReturnValue( - makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'runtime' }) - ) - - try { - await expect( - handlers['worktrees:remove'](null, { - worktreeId: `repo-1::${standalonePath}`, - force: true - }) - ).rejects.toThrow(`Refusing to delete unregistered worktree path: ${standalonePath}`) - - await expect(lstat(standalonePath)).resolves.toBeTruthy() - expect(removeWorktreeMock).not.toHaveBeenCalled() - expect(store.removeWorktreeMeta).not.toHaveBeenCalled() - } finally { - await rm(parentDir, { recursive: true, force: true }) - } - }) - - it('does not inspect or delete a local path for an SSH orphan this process does not serve', async () => { - const localPath = await mkdtemp(join(tmpdir(), 'orca-ipc-ssh-missing-fs-')) - const repo = { - id: 'repo-ssh-missing-fs', - path: '/remote/repo', - displayName: 'ssh', - badgeColor: '#000', - addedAt: 0, - connectionId: 'conn-missing-fs' - } - store.getRepo.mockReturnValue(repo) - store.getWorktreeMeta.mockReturnValue( - makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'ssh' }) - ) - - try { - await expect( - handlers['worktrees:remove'](null, { - worktreeId: `${repo.id}::${localPath}`, - force: true - }) - ).rejects.toThrow('isn’t served by Orca’s server') - - await expect(lstat(localPath)).resolves.toBeTruthy() - expect(removeWorktreeMock).not.toHaveBeenCalled() - expect(store.removeWorktreeMeta).not.toHaveBeenCalled() - } finally { - await rm(localPath, { recursive: true, force: true }) - } - }) }) diff --git a/src/main/ipc/worktrees-remove-preflight.test.ts b/src/main/ipc/worktrees-remove-preflight.test.ts index abfda1ba765..07258baad9a 100644 --- a/src/main/ipc/worktrees-remove-preflight.test.ts +++ b/src/main/ipc/worktrees-remove-preflight.test.ts @@ -98,12 +98,23 @@ vi.mock('../git/repositories/git-username', async (importOriginal) => ({ resolveLocalGitUsername: (await import('./worktrees-test-module-mocks')) .resolveLocalGitUsernameMock })) -vi.mock('../github/client', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../github/client/lookup/get-pr-for-branch', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) +vi.mock('../github/client/lookup/get-pr-for-branch', async () => ({ + getPRForBranch: (await import('./worktrees-test-module-mocks')).getPRForBranchMock +})) + +vi.mock('../github/client/fetch/get-work-item', async () => { + return { + getWorkItem: (await import('./worktrees-test-module-mocks')).getWorkItemMock + } +}) + +vi.mock('../github/client/lookup/pull-request-push-target', async () => { + return { + getPullRequestPushTarget: (await import('./worktrees-test-module-mocks')) + .getPullRequestPushTargetMock + } +}) + vi.mock('../source-control/hosted-review', async () => (await import('./worktrees-test-module-mocks')).hostedReviewModuleMock() ) diff --git a/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts b/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts deleted file mode 100644 index 79baa10474e..00000000000 --- a/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts +++ /dev/null @@ -1,260 +0,0 @@ -import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ProviderRequestId } from '../../shared/detected-worktree-provider-contract' -import { toSshExecutionHostId } from '../../shared/execution-host' -import { getSshProviderAuthority } from '../ssh/connection/authority/ssh-provider-authority' -import { listWorktreesMock } from './worktrees-test-module-mocks' -import { handlers, ipcEvent, setupWorktreeHandlers, store } from './worktrees-test-harness' - -vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - return { - ...(await importOriginal()), - listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks')) - .listWorktreesMock, - listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock - } -}) - -vi.mock('electron', async () => - (await import('./worktrees-test-module-mocks')).electronModuleMock() -) -vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({ - ...(await importOriginal>()), - parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({ - ...(await importOriginal>()), - assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks')) - .assertWorktreeCleanForRemovalMock -})) - -vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock -})) - -vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock -})) -vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({ - ...(await importOriginal>()), - listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - describeCreatedWorktree: (await import('./worktrees-test-module-mocks')) - .describeCreatedWorktreeMock -})) -const { getWorktreeRunnerMocks } = vi.hoisted(() => { - function createWorktreeRunnerMocks() { - return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())() - } - let runner: ReturnType | undefined - return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) } -}) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync -})) - -vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync -})) -vi.mock('../git/remotes/repo-remote-queries', async () => ({ - getDefaultRemote: (await import('./worktrees-test-module-mocks')).getDefaultRemoteMock -})) -vi.mock('../git/refs/resolution/repo-branch-conflict', async () => - (await import('./worktrees-test-module-mocks')).gitBranchConflictModuleMock() -) - -vi.mock('../git/refs/resolution/repo-default-base-ref', async (importOriginal) => ({ - ...(await importOriginal>()), - getDefaultBaseRefAsync: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock, - resolveDefaultBaseRefWithLocalGit: (await import('./worktrees-test-module-mocks')) - .resolveDefaultBaseRefWithLocalGitMock -})) -vi.mock('../git/repositories/git-username', async (importOriginal) => ({ - ...(await importOriginal>()), - resolveLocalGitUsername: (await import('./worktrees-test-module-mocks')) - .resolveLocalGitUsernameMock -})) -vi.mock('../github/client', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../github/client/lookup/get-pr-for-branch', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../source-control/hosted-review', async () => - (await import('./worktrees-test-module-mocks')).hostedReviewModuleMock() -) -vi.mock('./worktree-symlinks', async () => - (await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock() -) - -vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({ - ...(await importOriginal>()), - findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks')) - .findExistingWorktreeSymlinkPathsMock -})) -vi.mock('../workspace-hooks/hooks', async () => - (await import('./worktrees-test-module-mocks')).hooksModuleMock() -) -vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('./worktree-logic', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../pty/history/terminal-history-deletion', async () => - (await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock() -) -vi.mock('../ports/advertised-url-watcher', async () => - (await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock() -) -vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock() -) -vi.mock('../runtime/workspaces/removal/worktree-teardown', async () => - (await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock() -) -vi.mock('./pty/provider/registry', async () => - (await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock() -) -vi.mock('./pty/provider/state-cleanup', async () => - (await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock() -) - -describe('registerWorktreeHandlers', () => { - beforeEach(() => { - setupWorktreeHandlers() - }) - - // Runtime rows bypass local stale GC too, so only authoritative host scans retire them (#17776). - - // Runtime ownership plus a connectionId is contradictory; findExactRepoOwner must refuse it. - - it('fails closed for duplicate exact owners and ambiguous legacy repo IDs', async () => { - const sshRepo = { - id: 'shared-repo', - path: '/remote/repo-a', - displayName: 'remote repo', - badgeColor: '#000', - addedAt: 0, - connectionId: 'target-a' - } - const duplicateSshRepo = { ...sshRepo, path: '/remote/repo-b' } - const localRepo = { ...sshRepo, path: '/local/repo', connectionId: undefined } - store.getRepos.mockReturnValue([sshRepo, duplicateSshRepo, localRepo]) - const expectedAuthority = getSshProviderAuthority('target-a') - - const qualified = await handlers['worktrees:listDetected'](ipcEvent, { - providerRequestId: 'request-1' as ProviderRequestId, - repoId: 'shared-repo', - executionHostId: toSshExecutionHostId('target-a'), - expectedAuthority - }) - const legacy = await handlers['worktrees:listDetected'](null, { repoId: 'shared-repo' }) - - expect(qualified).toMatchObject({ - status: 'ambiguous-owner', - providerRequestId: 'request-1', - executionHostId: 'ssh:target-a' - }) - expect(legacy).toEqual({ - repoId: 'shared-repo', - authoritative: false, - source: 'metadata-fallback', - worktrees: [] - }) - expect(listWorktreesMock).not.toHaveBeenCalled() - }) - - it('rejects runtime hosts, wrong SSH targets, and missing authority', async () => { - const requestId = 'request-1' as ProviderRequestId - const expectedAuthority = getSshProviderAuthority('target-a') - - const runtimeResult = await handlers['worktrees:listDetected'](ipcEvent, { - providerRequestId: requestId, - repoId: 'repo-1', - executionHostId: 'runtime:runtime-a' - }) - const wrongTargetResult = await handlers['worktrees:listDetected'](ipcEvent, { - providerRequestId: requestId, - repoId: 'repo-1', - executionHostId: toSshExecutionHostId('target-b'), - expectedAuthority - }) - const missingAuthorityResult = await handlers['worktrees:listDetected'](ipcEvent, { - providerRequestId: requestId, - repoId: 'repo-1', - executionHostId: toSshExecutionHostId('target-a') - }) - const zeroOwnerResult = await handlers['worktrees:listDetected'](ipcEvent, { - providerRequestId: requestId, - repoId: 'repo-1', - executionHostId: toSshExecutionHostId('target-a'), - expectedAuthority - }) - store.getRepos.mockReturnValue([ - { - id: 'repo-1', - path: '/remote/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - connectionId: 'target-b', - executionHostId: toSshExecutionHostId('target-a') - } - ]) - const wrongProviderOwnerResult = await handlers['worktrees:listDetected'](ipcEvent, { - providerRequestId: requestId, - repoId: 'repo-1', - executionHostId: toSshExecutionHostId('target-a'), - expectedAuthority - }) - - expect(runtimeResult).toMatchObject({ status: 'rejected' }) - expect(wrongTargetResult).toMatchObject({ status: 'rejected' }) - expect(missingAuthorityResult).toMatchObject({ status: 'rejected' }) - expect(zeroOwnerResult).toMatchObject({ status: 'ambiguous-owner' }) - expect(wrongProviderOwnerResult).toMatchObject({ status: 'rejected' }) - expect(listWorktreesMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/worktrees/create/register-review-base-handlers.ts b/src/main/ipc/worktrees/create/register-review-base-handlers.ts index 7697581d73b..a17f07d01dc 100644 --- a/src/main/ipc/worktrees/create/register-review-base-handlers.ts +++ b/src/main/ipc/worktrees/create/register-review-base-handlers.ts @@ -15,10 +15,10 @@ import { import { fetchPrHeadTrackingRef, fetchGitHubPullRequestHeadRef -} from '../../../github/pr-head-tracking-ref' -import { resolveGitHubPrStartPoint } from '../../../github/pr-start-point' -import { resolvePrStartPointUnlessWslStopped } from '../../../github/pr-start-point-wsl-gate' -import { resolveGitHubReviewHeadRemote } from '../../../github/review-head-remote' +} from '../../../github/pull-requests/start-points/pr-head-tracking-ref' +import { resolveGitHubPrStartPoint } from '../../../github/pull-requests/start-points/pr-start-point' +import { resolvePrStartPointUnlessWslStopped } from '../../../github/pull-requests/start-points/pr-start-point-wsl-gate' +import { resolveGitHubReviewHeadRemote } from '../../../github/pull-requests/start-points/review-head-remote' import type { WorktreeIpcContext } from '../worktree-ipc-context' import { reviewStartPointFailure } from '../../../../shared/review-start-point-failure-copy' diff --git a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts index 0050e90b84d..0a71ff7829a 100644 --- a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts +++ b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts @@ -32,6 +32,7 @@ import { beginWorkspaceCreateTelemetry } from '../../../workspaces/creation/work import { assertWslMoveRepoWritable } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' import { applyWorkspaceCreatePluginHook } from '../../../plugins/hooks/workspace-create-plugin-hook' import { withProjectWorktreeCreate } from '../../../workspaces/creation/worktree-create-in-flight' +import { createdWorktreeLifecycleIdentity } from '../../../runtime/workspaces/lifecycle/worktree-lifecycle-event' export function registerWorktreeCreateHandlers(context: WorktreeIpcContext): void { const { mainWindow, store, runtime, options } = context @@ -107,7 +108,8 @@ export function registerWorktreeCreateHandlers(context: WorktreeIpcContext): voi kind: 'created', worktreeId: result.worktree.id, path: result.worktree.path, - branch: result.worktree.branch + branch: result.worktree.branch, + ...createdWorktreeLifecycleIdentity(result.worktree) }) // Stamp after the create notification bumps generation so the reply names its resulting catalog. @@ -165,7 +167,8 @@ export function registerWorktreeCreateHandlers(context: WorktreeIpcContext): voi kind: 'created', worktreeId: result.worktree.id, path: result.worktree.path, - branch: result.worktree.branch + branch: result.worktree.branch, + ...createdWorktreeLifecycleIdentity(result.worktree) }) return { ...result, catalogVersion: getLocalWorktreeCatalogVersion(repo.id) } }) diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-git-status-events.test.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-git-status-events.test.ts index 28f56baa0fe..b56f922c8cf 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-git-status-events.test.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-git-status-events.test.ts @@ -4,7 +4,7 @@ import { BrowserWindow } from 'electron' import { afterEach, expect, it, vi } from 'vitest' import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache' import { listWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' -import { getStatusLineStatsCacheKey } from '../../../git/source-control/status-branch-line-total-input' +import { getStatusLineStatsCacheKey } from '../../../git/source-control/status/status-branch-line-total-input' import { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { partialRuntimeStore } from '../../../runtime/orca-runtime-tests/runtime-store-partial-fixture' import { makeStore } from '../../../runtime/client/navigation/paired-client-navigation-test-harness' diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-poller.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-poller.ts index 9ecf57a8f77..147d4cb4cbe 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-poller.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-poller.ts @@ -1,7 +1,7 @@ import { isMainWindowVisible, onMainWindowBecameVisible -} from '../../../window/main-window-visibility' +} from '../../../window/visibility/main-window-visibility' import type { WorktreeBaseRepoWatchConfig, WorktreeBaseWatchTarget diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-watch-events.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-watch-events.ts index 73a9cdc0977..dedc17f5602 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-watch-events.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-watch-events.ts @@ -11,6 +11,7 @@ import { invalidateGitStatusRefResolutionForPaths } from '../git/worktree-git-status-ref-watch' import type { WorktreeWatcherFailureRefreshCooldown } from './worktree-watcher-failure-refresh-cooldown' +import { runWorktreeChangeInvalidators } from '../listing/worktree-change-invalidators' export type ActiveWatch = WorktreeBaseNotificationWatch & { subscription: { unsubscribe: () => Promise } @@ -30,12 +31,22 @@ export function handleLocalWatchEvents( if (error) { console.warn(`[worktree-base-watcher] watcher failed for ${watch.path}:`, error) invalidateActiveGitStatusRefResolution(watch, getActiveWatches) + // Events were lost: no reader may reuse rows observed before the gap, even while notification is paced. + for (const repoId of watch.repos.keys()) { + runWorktreeChangeInvalidators(repoId) + } + const refresh = (): void => { + if (!watch.disposed && !watch.mainWindow.isDestroyed()) { + scheduleWorktreeBaseNotification(watch, { structureRepoIds: [...watch.repos.keys()] }) + } + } if (watch.watcherFailureRefresh.consume()) { - scheduleWorktreeBaseNotification(watch, { structureRepoIds: [...watch.repos.keys()] }) + refresh() + } else { + watch.watcherFailureRefresh.defer(refresh) } return } - watch.watcherFailureRefresh.reset() invalidateGitStatusRefResolutionForPaths( watch, events.map((event) => event.path), @@ -56,5 +67,8 @@ export function handleWatchOverflow( return } invalidateActiveGitStatusRefResolution(watch, getActiveWatches) + for (const repoId of watch.repos.keys()) { + runWorktreeChangeInvalidators(repoId) + } scheduleWorktreeBaseNotification(watch, { structureRepoIds: [...watch.repos.keys()] }) } diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts index a1e6cefc552..1677e017dbc 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts @@ -147,6 +147,7 @@ async function removeWatch(key: string): Promise { watch.disposed = true clearTimeout(watch.notifyTimer ?? undefined) disposeWorktreeHeadIdentityRefreshState(watch.headIdentityRefresh) + watch.watcherFailureRefresh.dispose() clearPendingWorktreeBaseNotifications(watch) await watch.subscription.unsubscribe().catch((error) => { console.warn(`[worktree-base-watcher] failed to unwatch ${watch.path}:`, error) diff --git a/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.test.ts b/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.test.ts new file mode 100644 index 00000000000..3e4434d9fc2 --- /dev/null +++ b/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.test.ts @@ -0,0 +1,28 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { WorktreeWatcherFailureRefreshCooldown } from './worktree-watcher-failure-refresh-cooldown' + +describe('WorktreeWatcherFailureRefreshCooldown', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('delivers a cooled-down failure refresh once the cooldown ends instead of dropping it', () => { + const cooldown = new WorktreeWatcherFailureRefreshCooldown() + const refresh = vi.fn() + expect(cooldown.consume()).toBe(true) + + vi.advanceTimersByTime(10_000) + expect(cooldown.consume()).toBe(false) + cooldown.defer(refresh) + cooldown.defer(refresh) + vi.advanceTimersByTime(49_999) + expect(refresh).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(refresh).toHaveBeenCalledTimes(1) + expect(cooldown.consume()).toBe(false) + }) +}) diff --git a/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.ts b/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.ts index 76c33a621fa..69cb56470c3 100644 --- a/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.ts +++ b/src/main/ipc/worktrees/creation/worktree-watcher-failure-refresh-cooldown.ts @@ -2,6 +2,7 @@ const WATCHER_FAILURE_REFRESH_COOLDOWN_MS = 60_000 export class WorktreeWatcherFailureRefreshCooldown { private refreshedAt: number | null = null + private deferred: ReturnType | null = null consume(now = Date.now()): boolean { if (this.refreshedAt !== null && now - this.refreshedAt < WATCHER_FAILURE_REFRESH_COOLDOWN_MS) { @@ -11,7 +12,25 @@ export class WorktreeWatcherFailureRefreshCooldown { return true } - reset(): void { - this.refreshedAt = null + /** A cooled-down failure still owes its refresh; pace it to the cooldown's end instead of dropping it. */ + defer(refresh: () => void, now = Date.now()): void { + if (this.deferred) { + return + } + const dueInMs = Math.max( + 0, + (this.refreshedAt ?? now) + WATCHER_FAILURE_REFRESH_COOLDOWN_MS - now + ) + this.deferred = setTimeout(() => { + this.deferred = null + this.refreshedAt = Date.now() + refresh() + }, dueInMs) + this.deferred.unref?.() + } + + dispose(): void { + clearTimeout(this.deferred ?? undefined) + this.deferred = null } } diff --git a/src/main/ipc/worktrees/git/git-status-upstream-ref-watch-request.ts b/src/main/ipc/worktrees/git/git-status-upstream-ref-watch-request.ts index 54009d7de39..889733188fe 100644 --- a/src/main/ipc/worktrees/git/git-status-upstream-ref-watch-request.ts +++ b/src/main/ipc/worktrees/git/git-status-upstream-ref-watch-request.ts @@ -1,5 +1,5 @@ import type { Store } from '../../../persistence/loading-store/store' -import { resolveGitStatusUpstreamRef } from '../../../git/source-control/status-upstream-ref' +import { resolveGitStatusUpstreamRef } from '../../../git/source-control/upstream/status-upstream-ref' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { abortSignalWithTimeout } from '../../../lib/abort-signal-with-timeout' import { resolveRegisteredWorktreePath } from '../removal/registered-worktree-roots-cache' diff --git a/src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts b/src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts deleted file mode 100644 index ddbccd7a852..00000000000 --- a/src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -// Verify real Git staging events map admin-directory names back to the owning checkout. -import { execFile } from 'node:child_process' -import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { promisify } from 'node:util' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { areRuntimePathsEqual } from '../../../../shared/worktree/ownership' -import { collectLocalWorktreeBaseChanges } from '../creation/worktree-base-directory-change-collector' -import type { WorktreeBaseWatchTarget } from '../creation/worktree-base-directory-event-filter' -import { - startWorktreeBaseDirectoryPoller, - type WorktreeBasePollEvent, - type WorktreeBaseSubscription -} from '../creation/worktree-base-directory-poller' -import { cachedWorktreePathsForScope } from '../creation/worktree-head-identity-cached-paths' -import { - createWorktreeHeadIdentityCache, - readGitCommonHeadIdentities, - type WorktreeHeadIdentityCache -} from '../creation/worktree-head-identity-reader' - -const execFileAsync = promisify(execFile) -const POLL_MS = 25 - -async function git(args: string[], cwd: string): Promise { - const { stdout } = await execFileAsync('git', args, { cwd }) - return stdout -} - -async function listedWorktreePaths(cwd: string): Promise { - return (await git(['worktree', 'list', '--porcelain'], cwd)) - .split('\n') - .filter((line) => line.startsWith('worktree ')) - .map((line) => line.slice('worktree '.length)) -} - -let scratch = '' -let primary = '' -let linkedOne = '' -let linkedTwo = '' -let target: WorktreeBaseWatchTarget -let cache: WorktreeHeadIdentityCache -let poller: WorktreeBaseSubscription | null = null -let received: WorktreeBasePollEvent[] = [] - -beforeEach(async () => { - scratch = await mkdtemp(join(tmpdir(), 'orca-status-attribution-')) - primary = join(scratch, 'repo') - await git(['init', '-q', '-b', 'main', primary], scratch) - for (const [key, value] of [ - ['user.name', 'Orca Test'], - ['user.email', 'orca@example.test'], - ['commit.gpgSign', 'false'] - ]) { - await git(['config', key, value], primary) - } - await git(['commit', '-q', '--allow-empty', '-m', 'init'], primary) - // Same folder name twice: Git names the second admin dir `wt1`, not `wt`. - linkedOne = join(scratch, 'one', 'wt') - linkedTwo = join(scratch, 'two', 'wt') - await git(['worktree', 'add', '-q', linkedOne, '-b', 'one'], primary) - await git(['worktree', 'add', '-q', linkedTwo, '-b', 'two'], primary) - - // Production watches the canonical common dir (see watch-targets `addTarget`). - const commonDir = await realpath(join(primary, '.git')) - target = { - key: `git-common:local:${commonDir}`, - kind: 'git-common', - path: commonDir, - repos: new Map([['repo-1', { repoId: 'repo-1', repoName: 'repo', nestWorkspaces: false }]]) - } - cache = createWorktreeHeadIdentityCache() - await readGitCommonHeadIdentities(commonDir, cache) - received = [] - poller = await startWorktreeBaseDirectoryPoller( - target, - () => target.repos, - (events) => received.push(...events), - { pollIntervalMs: POLL_MS } - ) -}) - -afterEach(async () => { - await poller?.unsubscribe() - poller = null - await rm(scratch, { recursive: true, force: true }) -}) - -// The native watcher can deliver a previous stage's events late; drain them. -async function waitForQuietWatcher(): Promise { - let seen = -1 - while (seen !== received.length) { - seen = received.length - await new Promise((resolve) => setTimeout(resolve, 300)) - } -} - -async function stageAndAttribute(checkout: string): Promise { - await waitForQuietWatcher() - received = [] - await writeFile(join(checkout, 'staged.txt'), `${checkout}\n`) - await git(['add', 'staged.txt'], checkout) - const deadline = Date.now() + 10_000 - while (Date.now() < deadline) { - const changes = collectLocalWorktreeBaseChanges(target, received) - if (changes.gitStatusRepoIds.length > 0) { - return cachedWorktreePathsForScope(cache, changes.gitStatusScope) - } - await new Promise((resolve) => setTimeout(resolve, POLL_MS)) - } - throw new Error(`no status signal for ${checkout}; events: ${JSON.stringify(received)}`) -} - -function expectAttributedTo(paths: string[] | null, listed: string, others: string[]): void { - expect(paths).not.toBeNull() - expect(paths?.some((path) => areRuntimePathsEqual(path, listed))).toBe(true) - for (const other of others) { - expect(paths?.some((path) => areRuntimePathsEqual(path, other))).toBe(false) - } -} - -describe('git status signal attribution (real git)', () => { - it('attributes index writes to the checkout that staged, in `git worktree list` spelling', async () => { - const [listedPrimary, listedOne, listedTwo] = await listedWorktreePaths(primary) - expectAttributedTo(await stageAndAttribute(linkedTwo), listedTwo, [listedPrimary, listedOne]) - expectAttributedTo(await stageAndAttribute(linkedOne), listedOne, [listedPrimary, listedTwo]) - expectAttributedTo(await stageAndAttribute(primary), listedPrimary, [listedOne, listedTwo]) - }, 30_000) -}) diff --git a/src/main/ipc/worktrees/ipc-context-schemas.ts b/src/main/ipc/worktrees/ipc-context-schemas.ts index 78d953a2d7d..c23dd289340 100644 --- a/src/main/ipc/worktrees/ipc-context-schemas.ts +++ b/src/main/ipc/worktrees/ipc-context-schemas.ts @@ -4,7 +4,7 @@ import type { CliWorkspaceProvenance } from '../../../shared/worktree/types' import type { ExecutionHostId } from '../../../shared/execution-host' -import type { NestedWorktreeRemovalApproval } from '../../../shared/worktree/nested-removal' +import type { NestedWorktreeRemovalApproval } from '../../../shared/worktree/removal/nested-removal' import type { ListDetectedWorktreesArgs } from '../../../shared/detected-worktree-provider-contract' import { WorkspaceLinkedItemSchema } from '../../../shared/workspace-attachments/workspace-linked-item-schema' import { WorkspaceAttachmentsSchema } from '../../../shared/workspace-attachments/workspace-attachment-schema' diff --git a/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts b/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts index 4924c45d74a..7908cf8c9ef 100644 --- a/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts +++ b/src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts @@ -29,6 +29,8 @@ vi.mock('./authoritative-local-worktree-metadata-pruning', () => ({ const { listDetectedWorktreesForCapturedRepo } = await import('./detected-provider-listing') const { __resetDetectedWorktreeScanCacheForTests } = await import('./detected-worktree-scan-cache') +const { setWorktreeCatalogRouteResolver } = + await import('../../../workspaces/catalog/repo-worktree-catalog-route') await import('../../../workspaces/catalog/local-worktree-scan-generation') const localRepo: Repo = { @@ -90,4 +92,33 @@ describe('the catalog version a listing carries', () => { seq: 5 }) }) + + it('answers nothing for rows whose owner route was retired before publication', async () => { + let live = true + setWorktreeCatalogRouteResolver(() => + live ? { repoPath: localRepo.path, runtimeKey: 'local:default' } : null + ) + try { + listRepoWorktreesMock.mockResolvedValue([worktreeAt(localRepo, localRepo.path)]) + // The route changes after the scan settles, while the listing finishes its own awaits. + let calls = 0 + const isCurrent = (): boolean => { + calls += 1 + if (calls === 1) { + live = false + } + return true + } + + const result = await listDetectedWorktreesForCapturedRepo( + createStore(localRepo), + localRepo, + isCurrent + ) + + expect(result).toBeNull() + } finally { + setWorktreeCatalogRouteResolver(null) + } + }) }) diff --git a/src/main/ipc/worktrees/listing/detected-provider-listing.ts b/src/main/ipc/worktrees/listing/detected-provider-listing.ts index 7aa21b9e99a..2c1ea0fe78f 100644 --- a/src/main/ipc/worktrees/listing/detected-provider-listing.ts +++ b/src/main/ipc/worktrees/listing/detected-provider-listing.ts @@ -171,6 +171,10 @@ export async function listDetectedWorktreesForCapturedRepo( return null } } + // The owner may have retired these rows' route during the overlay and hygiene awaits. + if (scan.authorityCurrent && !scan.authorityCurrent()) { + return abortedResult() ?? null + } loggedWorktreeListFailures.delete(`${repo.id}:${repo.path}`) releaseWslStoppedWorktreeRescan(repo.id) // Rows describe scan-start generation, which clients order against applied create/remove replies. diff --git a/src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts b/src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts index 60eb7923619..13115203167 100644 --- a/src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts +++ b/src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts @@ -4,6 +4,7 @@ import type { Store } from '../../../persistence/loading-store/store' import type { Repo } from '../../../../shared/repo-types' import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { isFolderRepo } from '../../../../shared/repo-kind' +import { withRepositoryGitCause } from '../../../git/repository-git-cause' import { listRepoWorktreesForDetectedScan } from '../../../workspaces/catalog/repo-worktrees' import { getRegisteredWorktreeRootsRevision, @@ -19,9 +20,6 @@ import { import { pruneLineageForMissingRepoWorktrees } from '../../../workspaces/catalog/worktree-lineage-pruning' import { __resetLocalWorktreeMetadataPruneGateForTests, - isLocalWorktreeMetadataPruneDue, - markLocalWorktreeMetadataPruneStarted, - recordLocalWorktreeListingForPruneGate, requireLocalWorktreeMetadataPrune } from '../../../workspaces/catalog/local-worktree-metadata-prune-gate' import { pruneMetadataMissingFromAuthoritativeLocalScan } from './authoritative-local-worktree-metadata-pruning' @@ -29,29 +27,28 @@ import { assertWslUncPathRunning, wslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import { + _resetWorktreeCatalogOwnerForTests, + invalidateWorktreeCatalogForRepo, + isCurrentWorktreeCatalogObservation, + readWorktreeCatalog +} from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { resolveWorktreeScanRuntime } from '../../../runtime/workspaces/catalog/runtime-worktree-scan-cache' +import { + claimWorktreeCatalogHygiene, + needsWorktreeCatalogHygieneClaim, + worktreeCatalogHygienePlan +} from './worktree-catalog-observation-hygiene' -// Coalesce renderer polls while bounding external-change lag. +// The sidebar accepts an observation up to this old; fresher demand refreshes the shared owner. export const DETECTED_WORKTREE_SCAN_CACHE_TTL_MS = 5_000 -export type DetectedWorktreeScanCacheEntry = { - expiresAt: number - worktrees: GitWorktreeInfo[] - /** Scan-start generation, used to order these cached rows. */ - generation: number -} - -export type DetectedWorktreeScan = { - invalidated: boolean - promise: Promise - sideEffectToken: DetectedWorktreeSideEffectToken - hygieneDue: boolean - metadataPrune?: DetectedWorktreeMetadataPrune -} - export type DetectedWorktreeSideEffectToken = Readonly<{ generation: number authorizedRootsRevision: number wslDistro?: string + /** Owner authority for the observation, rechecked after every await before destructive work. */ + authorityCurrent?: () => boolean }> export type DetectedWorktreeMetadataPrune = Readonly<{ @@ -68,67 +65,22 @@ export type DetectedWorktreeScanResult = { /** Owns the next store-hygiene pass; absent preserves eager behavior for non-local scans. */ hygieneDue?: boolean metadataPrune?: DetectedWorktreeMetadataPrune + /** Owner authority for these rows, independent of who owns side effects; absent for non-owner listings. */ + authorityCurrent?: () => boolean } -export const detectedWorktreeScanCache = new Map() -export const detectedWorktreeScanInFlight = new Map() - export function invalidateDetectedWorktreeScanCache(repoId: string): void { bumpLocalWorktreeScanGeneration(repoId) requireLocalWorktreeMetadataPrune(repoId) - const keyPrefix = `${repoId}\0` - for (const key of new Set([ - ...detectedWorktreeScanCache.keys(), - ...detectedWorktreeScanInFlight.keys() - ])) { - if (!key.startsWith(keyPrefix)) { - continue - } - detectedWorktreeScanCache.delete(key) - const inFlight = detectedWorktreeScanInFlight.get(key) - if (inFlight) { - // Detached scans retain invalidation so later completions cannot make them fresh again. - inFlight.invalidated = true - detectedWorktreeScanInFlight.delete(key) - } - } + invalidateWorktreeCatalogForRepo(repoId) } export function __resetDetectedWorktreeScanCacheForTests(): void { - // Pending scans must remain invalidated across resets to prevent cache leaks into later tests. - for (const scan of detectedWorktreeScanInFlight.values()) { - scan.invalidated = true - } - detectedWorktreeScanCache.clear() - detectedWorktreeScanInFlight.clear() + _resetWorktreeCatalogOwnerForTests() resetLocalWorktreeScanGenerationsForTests() __resetLocalWorktreeMetadataPruneGateForTests() } -export function __getDetectedWorktreeScanCacheStatsForTests(): { - cacheSize: number - inFlightSize: number -} { - return { - cacheSize: detectedWorktreeScanCache.size, - inFlightSize: detectedWorktreeScanInFlight.size - } -} - -// A stopped distro fails the scan as unavailable (rows are retained) instead of booting it (E9). -// Not async: a host scan must start and settle on the same ticks as before. -function listUnlessWslDistroStopped( - repo: Repo, - options: ReturnType -): ReturnType { - if (!wslDistroForPath(repo.path, options.wslDistro)) { - return listRepoWorktreesForDetectedScan(repo, options) - } - return assertWslUncPathRunning(repo.path, options.wslDistro).then(() => - listRepoWorktreesForDetectedScan(repo, options) - ) -} - export async function listDetectedGitWorktrees( store: Store, repo: Repo @@ -143,90 +95,84 @@ export async function listDetectedGitWorktrees( generation } } - - const cacheKey = getDetectedWorktreeScanCacheKey(repo.id, localWorktreeGitOptions) - const cached = detectedWorktreeScanCache.get(cacheKey) - if (cached && cached.expiresAt > Date.now()) { - return { - gitWorktrees: cached.worktrees, - fresh: false, - superseded: false, - generation: cached.generation + // Git options, runtime key and hygiene all come from one admitted route snapshot. + const runtimeKey = resolveWorktreeScanRuntime(store, repo).runtimeKey + // A stopped distro fails as unavailable (rows are retained) instead of booting it (E9); host scans keep their ticks. + if (wslDistroForPath(repo.path, localWorktreeGitOptions.wslDistro)) { + await assertWslUncPathRunning(repo.path, localWorktreeGitOptions.wslDistro) + if ( + resolveWorktreeScanRuntime(store, repo).runtimeKey !== runtimeKey || + getLocalProjectWorktreeGitOptions(store, repo).wslDistro !== localWorktreeGitOptions.wslDistro + ) { + // The route changed during admission; the bounded overtaken rescan admits the new one. + return { + gitWorktrees: [], + fresh: false, + superseded: true, + generation: getLocalWorktreeScanGeneration(repo.id) + } } } - - const inFlight = detectedWorktreeScanInFlight.get(cacheKey) - if (inFlight) { - const gitWorktrees = await inFlight.promise + const { observation, superseded } = await readWorktreeCatalog( + repo, + runtimeKey, + { + kind: 'desktop', + maxAgeMs: DETECTED_WORKTREE_SCAN_CACHE_TTL_MS, + needsHygieneClaim: needsWorktreeCatalogHygieneClaim(repo) + }, + { + scan: async () => { + const worktrees = await withRepositoryGitCause( + repo.path, + localWorktreeGitOptions, + { family: 'catalog', reason: 'desktop-catalog', cache: 'refresh' }, + () => listRepoWorktreesForDetectedScan(repo, localWorktreeGitOptions) + ) + return worktrees.length > 0 ? { kind: 'rows', worktrees } : { kind: 'true-empty' } + }, + ...worktreeCatalogHygienePlan(store, repo, localWorktreeGitOptions, true) + } + ) + if (!observation) { return { - gitWorktrees, + gitWorktrees: [], fresh: false, - superseded: - inFlight.invalidated || - !isLocalWorktreeScanGenerationCurrent(repo.id, inFlight.sideEffectToken.generation), - generation: inFlight.sideEffectToken.generation + superseded: true, + generation: getLocalWorktreeScanGeneration(repo.id) } } - - // Capture before Git can yield or mutate synchronously; WSL/UNC aliases cannot establish native destructive expectations. - const generation = getLocalWorktreeScanGeneration(repo.id) - const authorizedRootsRevision = getRegisteredWorktreeRootsRevision(repo.id) - // Whole-table capture and missing-path stats run only when changed evidence makes hygiene due (#17775). - const hygieneDue = isLocalWorktreeMetadataPruneDue(repo.id) - if (hygieneDue) { - markLocalWorktreeMetadataPruneStarted(repo.id) + if (observation.outcome.kind === 'failed') { + // A failed scan must reject: an authoritative empty list would prune live worktrees. + throw observation.outcome.error } - const metadataPruneExpectation = - hygieneDue && !localWorktreeGitOptions.wslDistro - ? store.captureNativeLocalWorktreeMetadataScanExpectation(repo) - : undefined - const scan: DetectedWorktreeScan = { - invalidated: false, - promise: listUnlessWslDistroStopped(repo, localWorktreeGitOptions), - sideEffectToken: { generation, authorizedRootsRevision, ...localWorktreeGitOptions }, - hygieneDue, - ...(metadataPruneExpectation + const gitWorktrees = observation.outcome.kind === 'rows' ? observation.outcome.worktrees : [] + const generationCurrent = isLocalWorktreeScanGenerationCurrent(repo.id, observation.generation) + // Side effects belong to the first reader of a still-current observation, whoever started its scan. + const claim = + !superseded && generationCurrent && isCurrentWorktreeCatalogObservation(observation) + ? claimWorktreeCatalogHygiene(observation) + : null + const authorityCurrent = (): boolean => isCurrentWorktreeCatalogObservation(observation) + return { + gitWorktrees, + authorityCurrent, + fresh: claim !== null, + superseded: superseded || !generationCurrent, + generation: observation.generation, + ...(claim ? { - metadataPrune: { - expectation: metadataPruneExpectation - } + sideEffectToken: { + generation: claim.generation, + authorizedRootsRevision: claim.authorizedRootsRevision, + ...localWorktreeGitOptions, + authorityCurrent + }, + hygieneDue: claim.hygieneDue, + ...(claim.expectation ? { metadataPrune: { expectation: claim.expectation } } : {}) } : {}) } - detectedWorktreeScanInFlight.set(cacheKey, scan) - try { - const gitWorktrees = await scan.promise - // Changed listings invalidate hygiene conclusions even when native events were lost. - recordLocalWorktreeListingForPruneGate( - repo.id, - gitWorktrees.map((worktree) => worktree.path) - ) - const routingUnchanged = - getDetectedWorktreeScanCacheKey(repo.id, getLocalProjectWorktreeGitOptions(store, repo)) === - cacheKey - // Mid-scan mutations must prevent stale cache publication. - const generationCurrent = isLocalWorktreeScanGenerationCurrent(repo.id, generation) - if (!scan.invalidated && routingUnchanged && generationCurrent) { - detectedWorktreeScanCache.set(cacheKey, { - worktrees: gitWorktrees, - expiresAt: Date.now() + DETECTED_WORKTREE_SCAN_CACHE_TTL_MS, - generation - }) - } - const fresh = !scan.invalidated && routingUnchanged && generationCurrent - return { - gitWorktrees, - fresh, - superseded: !fresh, - generation, - ...(fresh ? { sideEffectToken: scan.sideEffectToken, hygieneDue: scan.hygieneDue } : {}), - ...(fresh && scan.metadataPrune ? { metadataPrune: scan.metadataPrune } : {}) - } - } finally { - if (detectedWorktreeScanInFlight.get(cacheKey) === scan) { - detectedWorktreeScanInFlight.delete(cacheKey) - } - } } export async function applyFreshDetectedWorktreeScanSideEffects( @@ -245,7 +191,8 @@ export async function applyFreshDetectedWorktreeScanSideEffects( const { isCurrent = () => true, sideEffectToken, signal, hygieneDue = true } = options const generationCurrent = () => sideEffectToken === undefined || - isLocalWorktreeScanGenerationCurrent(repo.id, sideEffectToken.generation) + (isLocalWorktreeScanGenerationCurrent(repo.id, sideEffectToken.generation) && + (sideEffectToken.authorityCurrent?.() ?? true)) if (!generationCurrent() || !isCurrent()) { return false } @@ -260,7 +207,8 @@ export async function applyFreshDetectedWorktreeScanSideEffects( gitWorktrees, scan: metadataPrune.expectation, scanGeneration: sideEffectToken.generation, - isCallerCurrent: isCurrent, + // The helper rechecks after its path probes, right before deleting. + isCallerCurrent: () => isCurrent() && (sideEffectToken.authorityCurrent?.() ?? true), signal }) if (!pruneResult.scanGenerationCurrent || !generationCurrent() || !isCurrent()) { @@ -278,7 +226,10 @@ export async function applyFreshDetectedWorktreeScanSideEffects( ) { return false } - rememberLocalWorktreeRoots(store, repo, gitWorktrees, sideEffectToken) + // Owner observations registered their roots when published; folder and non-local listings register here. + if (!sideEffectToken) { + rememberLocalWorktreeRoots(store, repo, gitWorktrees) + } // Lineage depends on metadata retention decisions; both pruning passes must share the hygiene cadence. if (hygieneDue) { pruneLineageForMissingRepoWorktrees( @@ -291,13 +242,6 @@ export async function applyFreshDetectedWorktreeScanSideEffects( return true } -export function getDetectedWorktreeScanCacheKey( - repoId: string, - localWorktreeGitOptions: { wslDistro?: string } = {} -): string { - return `${repoId}\0${localWorktreeGitOptions.wslDistro ?? 'host'}` -} - export function rememberLocalWorktreeRoots( store: Store, repo: Repo, diff --git a/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts b/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts index 20c17d5c5a7..519e985222d 100644 --- a/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts +++ b/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts @@ -30,9 +30,12 @@ vi.mock('./authoritative-local-worktree-metadata-pruning', () => ({ const { DETECTED_WORKTREE_SCAN_CACHE_TTL_MS, __resetDetectedWorktreeScanCacheForTests, + applyFreshDetectedWorktreeScanSideEffects, invalidateDetectedWorktreeScanCache, listDetectedGitWorktrees } = await import('./detected-worktree-scan-cache') +const { setWorktreeCatalogRouteResolver } = + await import('../../../workspaces/catalog/repo-worktree-catalog-route') const { invalidateLocalWorktreeMetadataPruneInputs } = await import('../../../workspaces/catalog/local-worktree-metadata-prune-gate') @@ -115,4 +118,35 @@ describe('detected worktree scan hygiene gate', () => { advancePastListingTtl() expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true) }) + + it('stops deleting once the owner retires the route during the prune helper', async () => { + let live = true + setWorktreeCatalogRouteResolver(() => + live ? { repoPath: repo.path, runtimeKey: 'local:default' } : null + ) + try { + const scan = await listDetectedGitWorktrees(store, repo) + let helperSawCurrent: boolean | undefined + pruneMetadataMock.mockImplementation(async (args: { isCallerCurrent: () => boolean }) => { + live = false + helperSawCurrent = args.isCallerCurrent() + return { scanGenerationCurrent: true, preservedMetadataCandidateIds: new Set() } + }) + + const applied = await applyFreshDetectedWorktreeScanSideEffects( + store, + repo, + scan.gitWorktrees, + scan.metadataPrune, + { sideEffectToken: scan.sideEffectToken, hygieneDue: scan.hygieneDue } + ) + + expect(helperSawCurrent).toBe(false) + expect(applied).toBe(false) + expect(pruneLineageMock).not.toHaveBeenCalled() + expect(scan.authorityCurrent?.()).toBe(false) + } finally { + setWorktreeCatalogRouteResolver(null) + } + }) }) diff --git a/src/main/ipc/worktrees/listing/folder-workspace-catalog.ts b/src/main/ipc/worktrees/listing/folder-workspace-catalog.ts index d127bbc106f..9f3a7f661b9 100644 --- a/src/main/ipc/worktrees/listing/folder-workspace-catalog.ts +++ b/src/main/ipc/worktrees/listing/folder-workspace-catalog.ts @@ -14,12 +14,12 @@ import { import { createWorktreeVisibilitySourceMatcher, resolveCustomWorktreeVisibilitySources -} from '../../../../shared/worktree/visibility-sources' -import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/configured-worktree-base-path' +} from '../../../../shared/worktree/visibility/visibility-sources' +import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/paths/configured-worktree-base-path' import { toDetectedWorktree, applyMetadataFallbackVisibility -} from '../../../../shared/worktree/ownership' +} from '../../../../shared/worktree/visibility/ownership' import { projectWorktreeLineageWithHostPeers } from '../../../workspaces/catalog/worktree-lineage-host-peers' import { getProjectHostSetupMetaUpdates } from './worktree-discovery-metadata' import { diff --git a/src/main/ipc/worktrees/listing/register-worktree-catalog-handlers.ts b/src/main/ipc/worktrees/listing/register-worktree-catalog-handlers.ts index 69e32255857..a1aac508bd5 100644 --- a/src/main/ipc/worktrees/listing/register-worktree-catalog-handlers.ts +++ b/src/main/ipc/worktrees/listing/register-worktree-catalog-handlers.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import { EMPTY_RETIRED_NAME_REGISTRY } from '../../../../shared/worktree/retired-name-registry' +import { EMPTY_RETIRED_NAME_REGISTRY } from '../../../../shared/worktree/naming/retired-name-registry' import { getRetiredNameRegistryForRepo } from '../../../workspaces/removal/retirement/worktree-name-retirement' import type { WorktreeIpcContext } from '../worktree-ipc-context' diff --git a/src/main/ipc/worktrees/listing/ssh-worktree-fallback.ts b/src/main/ipc/worktrees/listing/ssh-worktree-fallback.ts index 794916325ae..10ade9c0f41 100644 --- a/src/main/ipc/worktrees/listing/ssh-worktree-fallback.ts +++ b/src/main/ipc/worktrees/listing/ssh-worktree-fallback.ts @@ -15,9 +15,9 @@ import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-i import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' import { buildKnownOrcaWorkspaceLayouts, - isLegacyRepoForExternalWorktreeVisibility, toDetectedWorktree -} from '../../../../shared/worktree/ownership' +} from '../../../../shared/worktree/visibility/ownership' +import { isLegacyRepoForExternalWorktreeVisibility } from '../../../../shared/external-worktree-visibility' import { areWorktreePathsEqual, dedupeWorktreesByPath @@ -25,8 +25,8 @@ import { import { createWorktreeVisibilitySourceMatcher, resolveCustomWorktreeVisibilitySources -} from '../../../../shared/worktree/visibility-sources' -import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/configured-worktree-base-path' +} from '../../../../shared/worktree/visibility/visibility-sources' +import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/paths/configured-worktree-base-path' import { projectWorktreeLineageWithHostPeers } from '../../../workspaces/catalog/worktree-lineage-host-peers' import { loggedMalformedWorktreeMetaKeys, warnOnce } from './worktree-listing-diagnostics' import { @@ -105,9 +105,11 @@ export function listDisconnectedSshWorktrees( const expectedHostId = getRepoExecutionHostId(repo) const repoOwners = store.getRepos().filter((candidate) => candidate.id === repo.id) for (const candidate of metaIndex.get(repo.id) ?? []) { + // An archived row has no checkout to show while its host is unreachable. if ( (candidate.meta.hostId && candidate.meta.hostId !== expectedHostId) || - (!candidate.meta.hostId && repoOwners.length > 1) + (!candidate.meta.hostId && repoOwners.length > 1) || + candidate.meta.archivedCheckout ) { continue } diff --git a/src/main/ipc/worktrees/listing/worktree-catalog-observation-hygiene.test.ts b/src/main/ipc/worktrees/listing/worktree-catalog-observation-hygiene.test.ts new file mode 100644 index 00000000000..2369a2d3302 --- /dev/null +++ b/src/main/ipc/worktrees/listing/worktree-catalog-observation-hygiene.test.ts @@ -0,0 +1,59 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../../../shared/repo-types' +import { + _resetWorktreeCatalogOwnerForTests, + readWorktreeCatalog +} from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { __resetLocalWorktreeMetadataPruneGateForTests } from '../../../workspaces/catalog/local-worktree-metadata-prune-gate' +import { + needsWorktreeCatalogHygieneClaim, + worktreeCatalogHygienePlan +} from './worktree-catalog-observation-hygiene' + +vi.mock('../removal/registered-worktree-roots-cache', () => ({ + getRegisteredWorktreeRootsRevision: () => 0, + registerWorktreeRootsForRepo: vi.fn() +})) + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the owner and hygiene plan read only these repo fields. +const repo = { id: 'repo-1', path: '/repos/app', kind: 'git' } as Repo + +async function readFailing(times: number, claimsHygiene: boolean) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the expectation is only carried, never read, when every scan fails. + const capture = vi.fn(() => ({}) as never) + const store = { captureNativeLocalWorktreeMetadataScanExpectation: capture } + for (let read = 0; read < times; read += 1) { + await readWorktreeCatalog( + repo, + 'local:default', + { + kind: 'desktop', + maxAgeMs: 5_000, + ...(claimsHygiene ? { needsHygieneClaim: needsWorktreeCatalogHygieneClaim(repo) } : {}) + }, + { + scan: () => Promise.reject(new Error('fatal: not a git repository (permission denied)')), + ...worktreeCatalogHygienePlan(store as never, repo, {}, claimsHygiene) + } + ) + } + return capture.mock.calls.length +} + +describe('worktree catalog observation hygiene', () => { + afterEach(() => { + _resetWorktreeCatalogOwnerForTests() + __resetLocalWorktreeMetadataPruneGateForTests() + }) + + it('captures the whole-store expectation once per evidence, however often a failing repo is read', async () => { + expect(await readFailing(5, true)).toBe(1) + __resetLocalWorktreeMetadataPruneGateForTests() + _resetWorktreeCatalogOwnerForTests() + expect(await readFailing(50, true)).toBe(1) + }) + + it('never captures for readers that do not prune', async () => { + expect(await readFailing(5, false)).toBe(0) + }) +}) diff --git a/src/main/ipc/worktrees/listing/worktree-catalog-observation-hygiene.ts b/src/main/ipc/worktrees/listing/worktree-catalog-observation-hygiene.ts new file mode 100644 index 00000000000..0bcbadd858b --- /dev/null +++ b/src/main/ipc/worktrees/listing/worktree-catalog-observation-hygiene.ts @@ -0,0 +1,109 @@ +import type { Repo } from '../../../../shared/repo-types' +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import type { Store } from '../../../persistence/loading-store/store' +import type { NativeLocalWorktreeMetadataScanExpectation } from '../../../persistence/tracking-repos/missing-local-worktree-metadata-pruning' +import type { + WorktreeCatalogFlightPlan, + WorktreeCatalogObservation, + WorktreeCatalogWitness +} from '../../../workspaces/catalog/repo-worktree-catalog-observation' +import { + isLocalWorktreeMetadataPruneDue, + markLocalWorktreeMetadataPruneStarted, + recordLocalWorktreeListingForPruneGate, + requireLocalWorktreeMetadataPrune +} from '../../../workspaces/catalog/local-worktree-metadata-prune-gate' +import { + getRegisteredWorktreeRootsRevision, + registerWorktreeRootsForRepo +} from '../removal/registered-worktree-roots-cache' + +export type WorktreeCatalogHygieneClaim = Readonly<{ + generation: number + authorizedRootsRevision: number + hygieneDue: boolean + expectation?: NativeLocalWorktreeMetadataScanExpectation +}> + +/** Pre-scan facts for every flight; only readers that prune claim the evidence gate (#17775). */ +export function worktreeCatalogHygienePlan( + store: Store, + repo: Repo, + gitOptions: { wslDistro?: string }, + claimsHygiene: boolean +): Pick { + return { + captureWitness: () => { + const authorizedRootsRevision = getRegisteredWorktreeRootsRevision(repo.id) + // Whole-table capture and missing-path stats run only when changed evidence makes hygiene due, + // and only for a reader that will consume them; unclaimed captures would re-arm and repeat. + const hygieneDue = claimsHygiene && isLocalWorktreeMetadataPruneDue(repo.id) + if (hygieneDue) { + markLocalWorktreeMetadataPruneStarted(repo.id) + } + // WSL/UNC aliases cannot establish native destructive expectations. + const expectation = + hygieneDue && !gitOptions.wslDistro + ? store.captureNativeLocalWorktreeMetadataScanExpectation?.(repo) + : undefined + const witness: WorktreeCatalogWitness = { + authorizedRootsRevision, + hygieneDue, + ...(expectation ? { expectation } : {}), + rootsRevision: authorizedRootsRevision, + release: () => { + if (hygieneDue) { + requireLocalWorktreeMetadataPrune(repo.id) + } + } + } + return witness + }, + observed: (observation) => { + const worktrees = observation.outcome.kind === 'rows' ? observation.outcome.worktrees : [] + // Changed listings invalidate hygiene conclusions even when native events were lost. + recordLocalWorktreeListingForPruneGate( + repo.id, + worktrees.map((worktree) => worktree.path) + ) + const witness = observation.witness + if ( + !witness || + getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID || + getRegisteredWorktreeRootsRevision(repo.id) !== witness.authorizedRootsRevision + ) { + return + } + // Reuse listing roots for authorization to avoid another Git scan and macOS folder-permission prompts. + registerWorktreeRootsForRepo( + store, + repo, + [repo.path, ...worktrees.map((worktree) => worktree.path)], + gitOptions + ) + witness.rootsRevision = getRegisteredWorktreeRootsRevision(repo.id) + } + } +} + +/** The once-only destructive claim on a still-current observation; older rows never get new expectations. */ +export function claimWorktreeCatalogHygiene( + observation: WorktreeCatalogObservation +): WorktreeCatalogHygieneClaim | null { + const witness = observation.witness + if (!witness) { + return null + } + observation.witness = undefined + return { + generation: observation.generation, + authorizedRootsRevision: witness.rootsRevision, + hygieneDue: witness.hygieneDue, + ...(witness.expectation ? { expectation: witness.expectation } : {}) + } +} + +/** A pruning reader must not settle for rows observed without its pre-scan claim while hygiene is due. */ +export function needsWorktreeCatalogHygieneClaim(repo: Repo): () => boolean { + return () => isLocalWorktreeMetadataPruneDue(repo.id) +} diff --git a/src/main/ipc/worktrees/listing/worktree-catalog-prune-authority.test.ts b/src/main/ipc/worktrees/listing/worktree-catalog-prune-authority.test.ts new file mode 100644 index 00000000000..b15447b3fbc --- /dev/null +++ b/src/main/ipc/worktrees/listing/worktree-catalog-prune-authority.test.ts @@ -0,0 +1,75 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../../../shared/repo-types' +import { + _resetWorktreeCatalogOwnerForTests, + isCurrentWorktreeCatalogObservation, + readWorktreeCatalog +} from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { setWorktreeCatalogRouteResolver } from '../../../workspaces/catalog/repo-worktree-catalog-route' +import { pruneMetadataMissingFromAuthoritativeLocalScan } from './authoritative-local-worktree-metadata-pruning' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the owner and pruning read only these repo fields. +const repo = { id: 'repo-1', path: '/repos/app', kind: 'git' } as Repo +const goneWorktreeId = 'repo-1::/repos/app-gone' + +describe('metadata pruning under catalog owner authority', () => { + afterEach(() => { + setWorktreeCatalogRouteResolver(null) + _resetWorktreeCatalogOwnerForTests() + }) + + it('deletes nothing when the owner retires the route while the path probe is held', async () => { + let live = true + setWorktreeCatalogRouteResolver(() => + live ? { repoPath: repo.path, runtimeKey: 'local:default' } : null + ) + const { observation } = await readWorktreeCatalog( + repo, + 'local:default', + { kind: 'desktop', maxAgeMs: 5_000 }, + { + scan: async () => ({ + kind: 'rows', + worktrees: [ + { path: repo.path, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true } + ] + }) + } + ) + let releaseProbe: (() => void) | undefined + const pruneMissing = vi.fn(() => [goneWorktreeId]) + const pruning = pruneMetadataMissingFromAuthoritativeLocalScan({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the helper reads only these store members. + store: { + getRepos: () => [repo], + pruneSessionlessMissingLocalWorktreeMetadataForRepo: pruneMissing, + getProfileStorageDirectory: () => '/profile' + } as never, + repo, + gitWorktrees: [ + { path: repo.path, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true } + ], + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: pruning compares only the repo identity and metadata ids. + scan: { + repo: { id: repo.id, path: repo.path }, + metadata: [{ worktreeId: goneWorktreeId }] + } as never, + scanGeneration: observation!.generation, + platform: 'darwin', + pathsExistOrAreUnverifiable: async (paths: readonly string[]) => { + await new Promise((resolve) => { + releaseProbe = resolve + }) + return new Map(paths.map((path) => [path, false])) + }, + isCallerCurrent: () => isCurrentWorktreeCatalogObservation(observation!) + }) + await vi.waitFor(() => expect(releaseProbe).toBeDefined()) + + live = false + releaseProbe!() + + expect((await pruning).removedWorktreeIds).toEqual([]) + expect(pruneMissing).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts b/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts index b052e4cdef0..b496b96607b 100644 --- a/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts +++ b/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts @@ -1,6 +1,6 @@ import { ipcMain } from 'electron' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' -import { displayNameUpdatePinsLabel } from '../../../../shared/worktree/display-name-provenance' +import { displayNameUpdatePinsLabel } from '../../../../shared/worktree/metadata/display-name-provenance' import { parseExecutionHostId } from '../../../../shared/execution-host' import { stripOrcaProvenanceMetaUpdates } from '../../../workspaces/removal/worktree-removal-safety' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' diff --git a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts index 45cd106494f..d16509582cc 100644 --- a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts +++ b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts @@ -3,7 +3,7 @@ import type { ExecutionHostId } from '../../../../shared/execution-host' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' import { assertRemovalHostMatchesRepoRow } from '../repo-host-ownership' import { isFolderRepo } from '../../../../shared/repo-kind' -import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal/removal' import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path' import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { listWorktreesStrict as listGitWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' @@ -23,7 +23,7 @@ import { assertNestedWorktreeRemovalApproval } from '../../../workspaces/removal import { removeStaleLocalWorktreeRegistration } from '../../../workspaces/removal/local-worktree-removal-recovery' import { resolveWorktreeRemovalHomeForHost } from '../../../workspaces/removal/worktree-removal-execution-host-route' import { getEffectiveHooks, runHook } from '../../../workspace-hooks/hooks' -import type { ArchiveHookOverride } from '../../../../shared/worktree/archive-hook-removal-gate' +import type { ArchiveHookOverride } from '../../../../shared/worktree/removal/archive-hook-removal-gate' import { gateWorktreeRemovalOnArchiveHook } from '../../../workspaces/removal/worktree-archive-hook-gate' import { withWorktreeRemoveStageSpan } from '../../../observability/instrumentation' import { diff --git a/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts b/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts index eaa6eb3479f..1c0a878a0c9 100644 --- a/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts +++ b/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts @@ -20,7 +20,8 @@ import { resolveRepoForExecutionHost } from '../repo-host-ownership' import { withNestedPreservedBranches } from '../../../workspaces/removal/nested-worktree-removal-plan' import { finishAcceptedWorktreeRemoval, - waitForPendingWorktreeRemoval + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' import { runSerializedWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-removal-acceptance-queue' import { assertWslMoveRepoWritable } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' @@ -30,6 +31,7 @@ import { runWorkspaceLifecycleCommand, workspaceLifecycleKey } from '../../../runtime/workspaces/lifecycle/workspace-lifecycle-commands' +import { worktreeHostIdentity } from '../../../persistence/worktree-meta-host-identity' export function registerWorktreeRemovalHandlers(context: WorktreeIpcContext): void { const { store, options, worktreeRemovalsInFlight } = context @@ -82,18 +84,23 @@ export function registerWorktreeRemovalHandlers(context: WorktreeIpcContext): vo areWorktreePathsEqual(item.path, worktreePath) ) const executionArgs = expectedCheckout ? { ...args, expectedCheckout } : args - const accept = async (): Promise => + const accept = async (): Promise => { // Another client may acquire removal while this request waits for acceptance. - waitForPendingWorktreeRemoval(args.worktreeId, removalHostId) - ? { removing: true } - : executeWorktreeRemoval( - context, - executionArgs, - repo, - repoId, - worktreePath, - removalHostId - ) + if (waitForPendingWorktreeRemoval(args.worktreeId, removalHostId)) { + await waitForWorktreeRemovalAcceptance(args.worktreeId, removalHostId) + return { removing: true } + } + return executeWorktreeRemoval( + context, + executionArgs, + repo, + repoId, + worktreePath, + removalHostId + ) + } + // Read before the purge drops the row; listeners hear `removed` after it. + const removedIdentity = worktreeHostIdentity(store, args.worktreeId, removalHostId) let accepted: RemoveWorktreeResult let result: RemoveWorktreeResult try { @@ -108,7 +115,8 @@ export function registerWorktreeRemovalHandlers(context: WorktreeIpcContext): vo options?.onWorktreeLifecycle?.({ kind: 'removed', worktreeId: args.worktreeId, - path: worktreePath + path: worktreePath, + ...removedIdentity }) } // Stamp inside the shared promise so coalesced callers receive the same resulting catalog. diff --git a/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts b/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts index 19a5a367aa7..a142f28f03c 100644 --- a/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts +++ b/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts @@ -8,7 +8,7 @@ import { pruneGitWorktrees } from '../../../git/worktrees/removal/worktree-prune import type { ExecutionHostId } from '../../../../shared/execution-host' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' import type { GitPushTarget, GitWorktreeInfo } from '../../../../shared/worktree/types' -import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal/removal' import type { LocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { listWorktreesStrict as listGitWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' import { removeWorktree } from '../../../git/worktrees/removal/worktree-removal' @@ -39,8 +39,10 @@ import { import { preservedBranchCleanupScopeKey } from '../../../../shared/git/branches/preserved-branch-cleanup' import { removesInBackground, - startBackgroundWorktreeRemoval + startBackgroundWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' +import { worktreeHostIdentity } from '../../../persistence/worktree-meta-host-identity' export async function removeRegisteredLocalWorktree( context: WorktreeIpcContext, @@ -129,6 +131,8 @@ export async function removeRegisteredLocalWorktree( context.store, localWorktreeGitOptions ) + // Read before the purge drops the row; listeners hear `removed` after it. + const removedIdentity = worktreeHostIdentity(context.store, args.worktreeId, removalHostId) const finish = (checkoutDeleteSignal?: AbortSignal): Promise => finishLocalWorktreeRemoval({ context, @@ -166,13 +170,16 @@ export async function removeRegisteredLocalWorktree( context.options?.onWorktreeLifecycle?.({ kind: 'removed', worktreeId: args.worktreeId, - path: canonicalWorktreePath + path: canonicalWorktreePath, + ...removedIdentity }) return result }, publish: () => runtime.publishWorktreeRemovalChange(repoId), + admissionFailed: () => removalGate.finish(false), cleanupPushTargetRemote: cleanupPushTarget }) + await waitForWorktreeRemovalAcceptance(args.worktreeId) return { removing: true } } @@ -264,12 +271,11 @@ async function finishLocalWorktreeRemoval({ removalHostId, args.snapshotPruneBatchId ) - preservedBranchCleanupByScope.delete( - preservedBranchCleanupScopeKey({ - worktreeId: args.worktreeId, - hostId: removalHostId - }) - ) + const cleanupScopeKey = preservedBranchCleanupScopeKey({ + worktreeId: args.worktreeId, + hostId: removalHostId + }) + preservedBranchCleanupByScope.delete(cleanupScopeKey) invalidateAuthorizedRootsCacheForRepo(store, repoId) removalCompleted = true return {} diff --git a/src/main/ipc/worktrees/removal/retry-failed-local-worktree-removal.ts b/src/main/ipc/worktrees/removal/retry-failed-local-worktree-removal.ts index d5d24442140..a1857597c9d 100644 --- a/src/main/ipc/worktrees/removal/retry-failed-local-worktree-removal.ts +++ b/src/main/ipc/worktrees/removal/retry-failed-local-worktree-removal.ts @@ -14,6 +14,7 @@ import { removeWorktreeMetadataAndTransientState, stopPtysForDestructiveWorktreeRemoval } from './worktree-removal-ownership' +import { worktreeHostIdentity } from '../../../persistence/worktree-meta-host-identity' /** Retry recorded leftovers after Git deregistration, retaining IPC bookkeeping; return undefined if none exist. */ export function retryFailedLocalWorktreeRemoval( @@ -22,6 +23,7 @@ export function retryFailedLocalWorktreeRemoval( removalHostId: ExecutionHostId ): Promise | undefined { const { store, runtime, options } = context + const purgedIdentities = new Map>() const jobFor = (record: WorktreeRemovalRecord) => interruptedLocalWorktreeRemovalJob(record, { store, @@ -43,6 +45,11 @@ export function retryFailedLocalWorktreeRemoval( ) }, purge: ({ worktreeId, repoId }) => { + // `removed` is heard after this drops the row, so its identity is read first. + purgedIdentities.set( + worktreeId, + worktreeHostIdentity(store, worktreeId, LOCAL_EXECUTION_HOST_ID) + ) runtime.clearOptimisticReconcileToken(worktreeId) removeWorktreeMetadataAndTransientState( { store, runtime }, @@ -52,8 +59,16 @@ export function retryFailedLocalWorktreeRemoval( ) invalidateAuthorizedRootsCacheForRepo(store, repoId) }, - onRemoved: ({ worktreeId, worktreePath }) => - options?.onWorktreeLifecycle?.({ kind: 'removed', worktreeId, path: worktreePath }), + onRemoved: ({ worktreeId, worktreePath }) => { + const identity = purgedIdentities.get(worktreeId) + purgedIdentities.delete(worktreeId) + options?.onWorktreeLifecycle?.({ + kind: 'removed', + worktreeId, + path: worktreePath, + ...identity + }) + }, publish: (repoId) => runtime.publishWorktreeRemovalChange(repoId) }) return retryFailedWorktreeRemoval(args.worktreeId, removalHostId, jobFor, args.force ?? false) diff --git a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts index b5bfea14861..700c6081443 100644 --- a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts +++ b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts @@ -10,7 +10,7 @@ import { hasWorktreeRemovalRepoOwnerOnOtherHost } from '../../../workspaces/remo import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { removeWorktreeMetaRow } from '../../../persistence/host-qualified-worktree-meta' -import { pruneWorktreePRRefreshAliases } from '../../../github/pr-refresh-coordinator' +import { pruneWorktreePRRefreshAliases } from '../../../github/pull-requests/refresh/pr-refresh-coordinator' import { dropRemovedWorktreeProcessState, pruneRemovedWorktreeSnapshots diff --git a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts index 516024bf23f..a39319def3e 100644 --- a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts +++ b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts @@ -17,7 +17,7 @@ import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-path import type { Store } from '../../persistence/loading-store/store' import { pauseWslMoveScope } from '../../persistence/moving-wsl-projects/execution/wsl-move-driver-pause' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { quitProcess } from '../../startup/process-quit-request' +import { quitProcess } from '../../startup/quit/process-quit-request' import { startWslDriveUncConversion } from '../../wsl/filesystem/wsl-drive-unc-conversion-run' import { lastWslDriveUncConversionOutcomes, diff --git a/src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts b/src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts index e9b8418886e..3e280546adf 100644 --- a/src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts +++ b/src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts @@ -6,7 +6,7 @@ import { writeWslHostAutomationWakes } from '../../wsl/host-lifecycle/wsl-host-automation-wake-store' import type { WslHostService } from '../../wsl/host-lifecycle/wsl-host-service' -import { callRuntimeEnvironment } from '../runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from '../runtime-environments/requests/runtime-environment-transport-routing' import { onWslOrcadHostAutomationsChanged } from '../../wsl/orcad/wsl-orcad-host-environments' // A connected host's schedule can change from any client; re-read it this often. diff --git a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts index 8649ae59125..0c456bc4225 100644 --- a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts +++ b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts @@ -25,17 +25,19 @@ vi.mock('../../wsl/host-lifecycle/wsl-host-e2e-fake-connector', () => ({ createFakeWslHostConnector: vi.fn(), readFakeWslHostsConfig: () => null })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ hasOrcadTemplate: () => true })) -vi.mock('../runtime-environments/runtime-environment-removal-cleanup', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ + hasOrcadTemplate: () => true +})) +vi.mock('../runtime-environments/catalog/runtime-environment-removal-cleanup', () => ({ retireRemovedRuntimeEnvironment: vi.fn() })) -vi.mock('../runtime-environments/runtime-environment-status-probe', () => ({ +vi.mock('../runtime-environments/status/runtime-environment-status-probe', () => ({ getRuntimeEnvironmentStatus: vi.fn() })) -vi.mock('../runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: vi.fn() })) -vi.mock('../runtime-environments/runtime-environment-request-connections', () => ({ +vi.mock('../runtime-environments/connections/runtime-environment-request-connections', () => ({ isRemoteRuntimeConnectionReady: () => false })) vi.mock('../../managed-server/lifecycle/orcad-terminal-census-client', () => ({ @@ -87,22 +89,6 @@ describe('WSL host IPC: the user Add and Remove (D3a)', () => { service.add.mockClear() }) - it('refuses an Add in serve-only and says so in its capability, keeping saved hosts usable', async () => { - vi.stubEnv('ORCA_INTERNAL_WSL_HOSTS', undefined) - register() - - expect(await handlers.get('wslHosts:add')?.({}, { distro: 'Ubuntu' })).toMatchObject({ - ok: false, - kind: 'disabled' - }) - expect(service.add).not.toHaveBeenCalled() - expect(await handlers.get('wslHosts:getCapability')?.({})).toMatchObject({ - acceptsNewWork: false - }) - await handlers.get('wslHosts:remove')?.({}, { environmentId: 'wsl:Ubuntu' }) - expect(service.remove).toHaveBeenCalledWith('wsl:Ubuntu') - }) - // A block published while Orca runs must stop new hosts now, not at the next launch. it('a live policy block refuses an Add at once, tells the window, and keeps the saved host served', async () => { vi.stubEnv('ORCA_INTERNAL_WSL_HOSTS', '1') @@ -126,7 +112,6 @@ describe('WSL host IPC: the user Add and Remove (D3a)', () => { ok: false, kind: 'disabled' }) - expect(service.add).not.toHaveBeenCalled() expect(wslHostsServing()).toBe(true) service.remove.mockClear() await handlers.get('wslHosts:remove')?.({}, { environmentId: 'wsl:Ubuntu' }) diff --git a/src/main/ipc/wsl/wsl-host-handlers.ts b/src/main/ipc/wsl/wsl-host-handlers.ts index 6f0d8f30492..f5b939d9265 100644 --- a/src/main/ipc/wsl/wsl-host-handlers.ts +++ b/src/main/ipc/wsl/wsl-host-handlers.ts @@ -12,7 +12,7 @@ import { createFakeWslHostConnector, readFakeWslHostsConfig } from '../../wsl/host-lifecycle/wsl-host-e2e-fake-connector' -import { hasOrcadTemplate } from '../../orcad/orcad-artifact-materializer' +import { hasOrcadTemplate } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { WslHostService } from '../../wsl/host-lifecycle/wsl-host-service' import { WslHostVisibleWorkByWindow } from './wsl-host-visible-work-windows' import type { WslHostAutomationWake } from '../../wsl/host-lifecycle/wsl-host-automation-wake' @@ -30,10 +30,10 @@ import { } from '../../wsl/host-lifecycle/wsl-host-service-instance' import { WslHostPhoneGate } from '../../wsl/host-lifecycle/wsl-host-phone-reach' import { readWslHostRecordsQuietly } from '../../wsl/host-lifecycle/wsl-host-connection-record' -import { retireRemovedRuntimeEnvironment } from '../runtime-environments/runtime-environment-removal-cleanup' -import { getRuntimeEnvironmentStatus } from '../runtime-environments/runtime-environment-status-probe' -import { callRuntimeEnvironment } from '../runtime-environments/runtime-environment-transport-routing' -import { isRemoteRuntimeConnectionReady } from '../runtime-environments/runtime-environment-request-connections' +import { retireRemovedRuntimeEnvironment } from '../runtime-environments/catalog/runtime-environment-removal-cleanup' +import { getRuntimeEnvironmentStatus } from '../runtime-environments/status/runtime-environment-status-probe' +import { callRuntimeEnvironment } from '../runtime-environments/requests/runtime-environment-transport-routing' +import { isRemoteRuntimeConnectionReady } from '../runtime-environments/connections/runtime-environment-request-connections' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { reconcileWslHostBridgePorts } from '../../../shared/remote-runtime/host-store/runtime-environment-wsl-host-store' import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' diff --git a/src/main/ipc/wsl/wsl-move-driver-handlers.test.ts b/src/main/ipc/wsl/wsl-move-driver-handlers.test.ts deleted file mode 100644 index 395610423a5..00000000000 --- a/src/main/ipc/wsl/wsl-move-driver-handlers.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type * as WslMoveDriverPreviewModule from '../../persistence/moving-wsl-projects/execution/wsl-move-driver-preview' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../shared/wsl-host-internal-gate' - -type Handler = (event: unknown, request?: unknown) => unknown - -const handlers = vi.hoisted(() => new Map()) -vi.mock('electron', () => ({ - ipcMain: { - removeHandler: (channel: string) => handlers.delete(channel), - handle: (channel: string, handler: Handler) => handlers.set(channel, handler) - } -})) -const driver = vi.hoisted(() => ({ - previewWslMove: vi.fn(async () => ({ outcome: 'ready' })), - moveProjectsToWslHost: vi.fn(async () => ({ outcome: 'moved' })), - cancelWslMove: vi.fn(() => true) -})) -vi.mock('../../persistence/moving-wsl-projects/wsl-move-driver', () => ({ - moveProjectsToWslHost: driver.moveProjectsToWslHost -})) - -vi.mock( - '../../persistence/moving-wsl-projects/execution/wsl-move-driver-preview', - async (importOriginal) => ({ - ...(await importOriginal()), - previewWslMove: driver.previewWslMove - }) -) -const running = vi.hoisted(() => ({ any: false })) -vi.mock('../../persistence/moving-wsl-projects/orchestration/wsl-move-running-moves', () => ({ - isAnyWslMoveRunning: () => running.any, - cancelWslMove: driver.cancelWslMove -})) -const track = vi.hoisted(() => vi.fn()) -vi.mock('../../telemetry/client', () => ({ track })) - -import { registerWslMoveHandlers } from './wsl-move-handlers' - -const MAIN_WINDOW_ID = 7 -const progress = vi.fn() -const deps = vi.fn(() => ({ now: () => new Date(0), progress })) -const invoke = (channel: string, request?: unknown, senderId = MAIN_WINDOW_ID) => - handlers.get(channel)?.({ sender: { id: senderId } }, request) - -beforeEach(() => { - vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1') - deps.mockClear() - track.mockClear() - for (const fn of Object.values(driver)) { - fn.mockClear() - } - registerWslMoveHandlers( - () => '/unused', - (senderId) => senderId === MAIN_WINDOW_ID, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The driver is mocked; the handler only passes deps through. - deps as never - ) -}) -afterEach(() => vi.unstubAllEnvs()) - -describe('WSL move driver IPC', () => { - it('is unreachable with the internal WSL hosts gate closed: nothing is built or run', async () => { - vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '') - const refused = { outcome: 'refused', code: 'wsl_move_unavailable' } - expect(await invoke('wslMove:preview', { distro: 'Ubuntu' })).toEqual(refused) - expect(await invoke('wslMove:start', { distro: 'Ubuntu' })).toEqual(refused) - expect(invoke('wslMove:cancel', 'Ubuntu')).toBe(false) - expect(deps).not.toHaveBeenCalled() - expect(driver.previewWslMove).not.toHaveBeenCalled() - expect(driver.moveProjectsToWslHost).not.toHaveBeenCalled() - expect(driver.cancelWslMove).not.toHaveBeenCalled() - }) - - it('refuses another window, and a malformed request', async () => { - expect(await invoke('wslMove:start', { distro: 'Ubuntu' }, 99)).toMatchObject({ - code: 'wsl_move_unavailable', - detail: 'not-main-window' - }) - for (const bad of [ - undefined, - 'Ubuntu', - { distro: '' }, - { distro: '..\\x' }, - { distro: 'U', repoIds: [1] } - ]) { - expect(await invoke('wslMove:start', bad)).toMatchObject({ detail: 'invalid-request' }) - } - expect(driver.moveProjectsToWslHost).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/wsl/wsl-move-driver-wiring.ts b/src/main/ipc/wsl/wsl-move-driver-wiring.ts index 5ed63a7bb5c..d9db5cdd238 100644 --- a/src/main/ipc/wsl/wsl-move-driver-wiring.ts +++ b/src/main/ipc/wsl/wsl-move-driver-wiring.ts @@ -58,7 +58,7 @@ import { wslMoveProjectRefForWorkspace } from '../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' import { buildWslMoveShellHistoryBlobs } from '../../persistence/moving-wsl-projects/terminal-state/wsl-move-shell-history-blobs' -import { inspectPtyProviderProcessForRenderer } from '../../providers/pty-process-inspection' +import { inspectPtyProviderProcessForRenderer } from '../../providers/pty/process-inspection' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { getTrustedUIRendererWebContents, getTrustedUIRendererWindow } from '../ui' import { registerWslMoveHandlers } from './wsl-move-handlers' @@ -78,14 +78,14 @@ import { listRemoteOrcadRepositories } from '../../managed-server/migration/link import { stageRemoteOrcadMigrationBlobChunk } from '../../managed-server/migration/transfers/orcad-migration-chunk-client' import { listRemoteOrcadFolderCatalog } from '../../managed-server/migration/linking/orcad-server-folder-workspaces' import { makeTerminalScrollbackSnapshotRef } from '../../pty/scrollback/terminal-scrollback-snapshots' -import { pauseWorkspacesForProjectMove } from '../../window/project-move-pause' +import { pauseWorkspacesForProjectMove } from '../../window/renderer-relays/project-move-pause' import { getWslHostService } from '../../wsl/host-lifecycle/wsl-host-service-instance' import { readWslGuestProcessTable } from '../../wsl/execution/wsl-guest-process-table' import { isWslDistroRegistered } from '../../wsl/discovery/wsl-distro-registry-id' import { defaultWslOrcadEnvironmentId } from '../../wsl/orcad/wsl-orcad-deploy' import { ptyPaneKey } from '../pty/pane/key-state' import { tryGetProviderForPty } from '../pty/provider/registry' -import { getRuntimeEnvironmentStatus } from '../runtime-environments/runtime-environment-status-probe' +import { getRuntimeEnvironmentStatus } from '../runtime-environments/status/runtime-environment-status-probe' /** The move's IPC handlers; its driver reads every move dependency from this module. */ export function registerWslMoveWiring(store: Store, runtime: OrcaRuntimeService): void { setWslMoveReloadableWindow(() => { diff --git a/src/main/ipc/wsl/wsl-move-undo-host-connect.test.ts b/src/main/ipc/wsl/wsl-move-undo-host-connect.test.ts index 2607fd6c51d..08e96562d24 100644 --- a/src/main/ipc/wsl/wsl-move-undo-host-connect.test.ts +++ b/src/main/ipc/wsl/wsl-move-undo-host-connect.test.ts @@ -13,7 +13,7 @@ const host = vi.hoisted(() => ({ result: { terminals: [], truncated: false } })) })) -vi.mock('../runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: (...args: unknown[]) => host.call(...args) })) vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ @@ -52,8 +52,6 @@ describe("undo's stop of the host's terminals: connecting the host", () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) const ports = createWslMoveUndoPorts(store, '/user-data', 'automatic') expect(await ports.preflightHostCopies?.(move)).toBe('unreachable') - expect(host.connect).not.toHaveBeenCalled() - expect(host.call).not.toHaveBeenCalled() }) it('refuses a live host terminal instead of sleeping it', async () => { @@ -64,13 +62,6 @@ describe("undo's stop of the host's terminals: connecting the host", () => { })) const ports = createWslMoveUndoPorts(store, '/user-data', 'automatic') expect(await ports.stopHostCopies(move)).toBe('still-running') - expect(host.call).not.toHaveBeenCalledWith( - expect.anything(), - expect.anything(), - 'worktree.sleep', - expect.anything(), - expect.anything() - ) }) }) }) diff --git a/src/main/ipc/wsl/wsl-move-undo-wiring.ts b/src/main/ipc/wsl/wsl-move-undo-wiring.ts index 303337ac793..18394ac862e 100644 --- a/src/main/ipc/wsl/wsl-move-undo-wiring.ts +++ b/src/main/ipc/wsl/wsl-move-undo-wiring.ts @@ -18,7 +18,7 @@ import { wslMoveRewriteScope } from '../../persistence/moving-wsl-projects/deskt import { wslMoveReleasedSessionFocusPatch } from '../../persistence/moving-wsl-projects/terminal-state/wsl-move-session-rewrite' import { applyWslMoveSessionFocus } from '../../persistence/moving-wsl-projects/desktop-state/wsl-move-main-rewrite-stores' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { callRuntimeEnvironment } from '../runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from '../runtime-environments/requests/runtime-environment-transport-routing' import { wasWslHostKeptForPeers } from '../../wsl/host-lifecycle/wsl-host-kept-for-peers' import { stopWslMoveHostAutomations, diff --git a/src/main/jira/favourite-filters.ts b/src/main/jira/favourite-filters.ts index 860bd3f1951..8ff92459043 100644 --- a/src/main/jira/favourite-filters.ts +++ b/src/main/jira/favourite-filters.ts @@ -2,7 +2,7 @@ import { normalizeJiraFavouriteFilters, type JiraFavouriteFilterList } from '../../shared/jira/jira-favourite-filters' -import { JiraFavouriteFilterParams } from '../../shared/rpc-contract/jira-favourite-filter-params' +import { JiraFavouriteFilterParams } from '../../shared/rpc-contract/jira/jira-favourite-filter-params' import { apiBasePath, jiraRequest } from './authenticated-request' import { getClients } from './client' import { requireStrictJiraSite, withJiraDeadline } from './jira-read-failure' diff --git a/src/main/kimi/kimi-acp-launch-spec.ts b/src/main/kimi/kimi-acp-launch-spec.ts new file mode 100644 index 00000000000..a8e79da9734 --- /dev/null +++ b/src/main/kimi/kimi-acp-launch-spec.ts @@ -0,0 +1,46 @@ +import { join } from 'node:path' +import type { AcpLaunchSpec } from '../acp/launch/acp-launch-contract' +import { KIMI_ACP_DIALECT } from '../acp/acp-dialects/kimi-dialect' +import { directoryAccountBinding } from '../acp/launch/acp-account-binding' +import { agentSessionSetupFor } from '../../shared/agent-session/lifecycle/agent-session-setup-commands' +import { + resumeInvocationFromOptions, + type StructuredAgentSessionHistory +} from '../native-chat/conversation-adoption/structured-agent-cli-conversations' + +// Chats and terminals share Kimi's session store and `session_` ids. +const KIMI_SESSION_HISTORY: StructuredAgentSessionHistory = { + rowAgents: ['kimi'], + rowSessionId: (link) => link.handle.nativeId, + parseResumeArgs: (args) => + resumeInvocationFromOptions(args, { + targetless: ['-c', '--continue'], + markers: ['-S', '--session', '-r', '--resume'] + }) +} + +export const KIMI_LAUNCH_SPEC: AcpLaunchSpec = { + agent: 'kimi', + command: 'kimi', + args: () => ['acp'], + // A staged update would otherwise replace the binary when the chat starts. + env: { KIMI_CODE_NO_AUTO_UPDATE: '1' }, + dialect: KIMI_ACP_DIALECT, + loginCommand: agentSessionSetupFor('kimi')?.loginCommand ?? [], + account: directoryAccountBinding('KIMI_CODE_HOME', (homePath) => join(homePath, '.kimi-code')), + // The install scripts' default location. + installDirectories: ({ homePath }) => [join(homePath, '.kimi-code', 'bin')], + // 2.5.0 stopped failing initialize when the client's first request arrives during startup. + minimumVersions: ['2.5.0'], + // Kimi enforces its modes, and config.toml's default_permission_mode applies until one is set. + // Its ACP descriptions swap these: `yolo` still asks before risky commands, `auto` never asks. + permissionModeConfig: { + values: { ask: 'default', auto: 'yolo', 'full-access': 'auto' } + }, + // Session discovery deletes its listing session. + modelDiscovery: { kind: 'session', listingNamesConfiguredModel: false }, + compaction: true, + compactionInstructions: true, + transcriptImport: null, + sessionHistory: KIMI_SESSION_HISTORY +} diff --git a/src/main/lib/hidden-probe-cwd.ts b/src/main/lib/hidden-probe-cwd.ts index 9d024c4b6fc..1031569d5c8 100644 --- a/src/main/lib/hidden-probe-cwd.ts +++ b/src/main/lib/hidden-probe-cwd.ts @@ -2,7 +2,7 @@ import { mkdirSync, realpathSync, statSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { isRootLikePath } from '../providers/pty-path-safety' +import { isRootLikePath } from '../providers/working-directory/path-safety' // Folder names predate the generic probe naming; keep them so existing dirs are reused. const HIDDEN_PROBE_CWD_DIR = 'rate-limit-pty-cwd' diff --git a/src/main/linear/issues/context/issue-context-graphql.ts b/src/main/linear/issues/context/issue-context-graphql.ts index 86a89596b7e..9948760863b 100644 --- a/src/main/linear/issues/context/issue-context-graphql.ts +++ b/src/main/linear/issues/context/issue-context-graphql.ts @@ -153,7 +153,7 @@ export const ISSUE_QUERY = ` } project @include(if: $includeDrawerFields) { url } children(first: 25) @include(if: $includeDrawerFields) { - nodes { id identifier title url } + nodes { id identifier title url state { name type color } } } } } diff --git a/src/main/managed-server/activation/orcad-exited-own-lock.ts b/src/main/managed-server/activation/orcad-exited-own-lock.ts index 18a72abb623..e0ec70dd39a 100644 --- a/src/main/managed-server/activation/orcad-exited-own-lock.ts +++ b/src/main/managed-server/activation/orcad-exited-own-lock.ts @@ -20,7 +20,7 @@ import { ORCAD_EXITED_OWN_LOCK_QUIET_SECONDS, ORCAD_STATE_MUTATION_LOCK_DIRNAME } from '../host-state/orcad-state-snapshot-members' -import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../../providers/windows-shell-args' +import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../../providers/shell-launch/windows/shell-args' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import type { InstallLockExitedOwnerProof } from '../install/remote-install-lock' import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' diff --git a/src/main/managed-server/activation/orcad-initial-activation-admission.ts b/src/main/managed-server/activation/orcad-initial-activation-admission.ts index f346413dcfb..6e310aa3601 100644 --- a/src/main/managed-server/activation/orcad-initial-activation-admission.ts +++ b/src/main/managed-server/activation/orcad-initial-activation-admission.ts @@ -1,5 +1,5 @@ /** Before first activation, rule out hand-started orcad/headless owners of the data root. Live, unreadable or unexpected PID records defer to avoid concurrent owners. */ -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { PRIMARY_RUNTIME_METADATA_FILE } from '../../../shared/runtime-bootstrap' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { selectOrcadSlotRuntimeCommand } from '../install/orcad-remote-runtime' diff --git a/src/main/managed-server/activation/orcad-installed-activation.ts b/src/main/managed-server/activation/orcad-installed-activation.ts index 28d231bc668..618d2a7fb06 100644 --- a/src/main/managed-server/activation/orcad-installed-activation.ts +++ b/src/main/managed-server/activation/orcad-installed-activation.ts @@ -65,7 +65,7 @@ import { stopTransactionIncumbent } from './orcad-transaction-incumbent' import { withOrcadLogTail } from '../install/orcad-remote-log-tail' -import { orcadCandidateLaunchFailureCode } from '../../orcad/orcad-host-unavailable' +import { orcadCandidateLaunchFailureCode } from '../../orcad/diagnostics/orcad-host-unavailable' import { errorMessage } from '../../../shared/error-message' type Outcome = Extract diff --git a/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts b/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts index 805bc7e9b86..92eed78a482 100644 --- a/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts +++ b/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts @@ -1,6 +1,6 @@ // Match POSIX state verdicts using staged directory snapshots; avoid extra tar processes and reject symlinks/junctions throughout. import { PRIMARY_RUNTIME_METADATA_FILE } from '../../../shared/runtime-bootstrap' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { ORCAD_WINDOWS_PROCESS_TREE_FILENAME } from '../../../shared/orcad-artifacts' import { ORCAD_INSTALL_MODEL } from '../install/remote-install-model' import { diff --git a/src/main/managed-server/install/orcad-remote-context.ts b/src/main/managed-server/install/orcad-remote-context.ts index 931d935d5cb..b586cbab92c 100644 --- a/src/main/managed-server/install/orcad-remote-context.ts +++ b/src/main/managed-server/install/orcad-remote-context.ts @@ -34,7 +34,7 @@ import { type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { detectRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform-detection' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import { rememberSshHostPlatform } from '../../ssh/remote-host/ssh-host-platform-memo' /** Default SSH generic retains compatibility with lifecycle consumers requiring SSH-only fields. */ diff --git a/src/main/managed-server/install/orcad-remote-deploy.ts b/src/main/managed-server/install/orcad-remote-deploy.ts index b949851b3d4..9a1026eda48 100644 --- a/src/main/managed-server/install/orcad-remote-deploy.ts +++ b/src/main/managed-server/install/orcad-remote-deploy.ts @@ -14,7 +14,7 @@ import { installOrcadBundle } from './orcad-remote-install' import { getAppEnvironment } from '../../../shared/app-environment' import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { ORCAD_STARTUP_READINESS_TIMEOUT_MS } from '../../../shared/orcad-profile-preflight' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { readOrcadBundleTarget } from './orcad-deployment-target' import { resolveOrcadRuntimeTarget } from '../lifecycle/orcad-runtime-target' import { diff --git a/src/main/managed-server/install/orcad-remote-launch-windows.ts b/src/main/managed-server/install/orcad-remote-launch-windows.ts index 6659d0e6899..8e984545792 100644 --- a/src/main/managed-server/install/orcad-remote-launch-windows.ts +++ b/src/main/managed-server/install/orcad-remote-launch-windows.ts @@ -25,7 +25,7 @@ import { ORCAD_WINDOWS_PROCESS_FILENAME } from './orcad-remote-host-support' import { orcadManagedLaunchEnv, type OrcadLaunchSpec } from './orcad-remote-launch' -import { ORCAD_WINDOWS_LAUNCH_REFUSED_CODE } from '../../orcad/orcad-host-unavailable' +import { ORCAD_WINDOWS_LAUNCH_REFUSED_CODE } from '../../orcad/diagnostics/orcad-host-unavailable' export class OrcadWindowsLaunchRefusedError extends Error { readonly code = ORCAD_WINDOWS_LAUNCH_REFUSED_CODE diff --git a/src/main/managed-server/install/orcad-remote-node-runtime-report.ts b/src/main/managed-server/install/orcad-remote-node-runtime-report.ts index 4dd8663c0a7..7c1f2387a73 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime-report.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime-report.ts @@ -1,4 +1,4 @@ -import { parseMissingSharedLibrary } from '../../orcad/native-host-abi' +import { parseMissingSharedLibrary } from '../../orcad/native-runtime/native-host-abi' import { RelayHostAnsweredError } from '../../ssh/remote-exec/remote-host-answered-failure' export const REMOTE_NODE_RUNTIME_READY = 'ORCA_NODE_RUNTIME_READY' diff --git a/src/main/managed-server/install/orcad-remote-windows-node.ts b/src/main/managed-server/install/orcad-remote-windows-node.ts index b5ba4157128..d845ea32fee 100644 --- a/src/main/managed-server/install/orcad-remote-windows-node.ts +++ b/src/main/managed-server/install/orcad-remote-windows-node.ts @@ -20,7 +20,7 @@ import { type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' -import { ORCAD_WINDOWS_COMMAND_LINE_UNSAFE_CODE } from '../../orcad/orcad-host-unavailable' +import { ORCAD_WINDOWS_COMMAND_LINE_UNSAFE_CODE } from '../../orcad/diagnostics/orcad-host-unavailable' import { ORCAD_WINDOWS_HOST_SCRIPT, ORCAD_WINDOWS_HOST_SCRIPT_FILENAME, diff --git a/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts index dda2f33008f..280ea989f3d 100644 --- a/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' +import { OrcadStdioBridgeUnavailableError } from '../../orcad/diagnostics/orcad-host-unavailable' import { checkOrcadStdioBridge, type OrcadStdioBridge } from './orcad-stdio-bridge' import { orcadBashStdioBridgeCommand } from './orcad-stdio-bridge-script' import { OrcadStdioBridgeDecoder } from './orcad-stdio-bridge-stream' diff --git a/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts b/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts index ecc3569effe..ee6939c555e 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts @@ -3,11 +3,11 @@ import { type ManagedOrcadAutoUpdateSkip } from './orcad-managed-update-decision' import { OrcadCrashLoopError } from './orcad-managed-crash-loop' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { OrcadArtifactsUnavailableError, OrcadHostUnsupportedError -} from '../../orcad/orcad-host-unavailable' +} from '../../orcad/diagnostics/orcad-host-unavailable' import { findIncompleteManagedOrcadMigration } from './orcad-managed-migration-status' import { ORCAD_ACTIVATION_FENCE_BUSY_CODE } from '../activation/orcad-activation-fence-hold' import { resolveLinkedOrcadContext } from './orcad-managed-runtime-context' diff --git a/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts b/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts index bb7b888516a..d53f072f4de 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts @@ -1,7 +1,7 @@ // Stop waking a managed orcad that keeps dying; an explicit Connect re-arms automatic starts. import { OrcadUnexpectedExitSchema } from '../../../shared/orcad-unexpected-exit' import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import type { OrcadHealth } from '../../orcad/orcad-health' +import type { OrcadHealth } from '../../orcad/diagnostics/orcad-health' import { isOrcadLaunchFailure, orcadLaunchFailureRanProcess @@ -13,8 +13,8 @@ import { readOrcadActivationRecord } from '../activation/orcad-activation-record import { ORCAD_LOG_FILENAME } from '../install/orcad-remote-host-support' import { withOrcadLogTail } from '../install/orcad-remote-log-tail' import { readBoundedOrcadRemoteRecord } from '../install/orcad-remote-record-file' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' -import { MAX_ORCAD_LOCK_BYTES } from '../../orcad/orcad-instance-lock-reclaim' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' +import { MAX_ORCAD_LOCK_BYTES } from '../../orcad/instance-lock/orcad-instance-lock-reclaim' import { ManagedOrcadEventWindow } from './orcad-managed-event-window' import { wakeStoppedManagedOrcad } from './orcad-managed-wake' diff --git a/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts b/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts index 8a21c5cfc79..3a7c630434f 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts @@ -17,7 +17,8 @@ import { readOrcadWindowsEncodedAnswer } from '../install/orcad-remote-windows-node' import { ORCAD_WINDOWS_RUNTIME_MARKER } from '../host-state/orcad-windows-host-script' -import { ORCAD_LOCK_FILE_NAME, parseOrcadInstanceLockRecord } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' +import { parseOrcadInstanceLockRecord } from '../../orcad/instance-lock/orcad-instance-lock-record' import { ORCAD_CANCEL_MANAGED_STOP_FLAG, ORCAD_COMPLETE_MANAGED_STOP_FLAG, diff --git a/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts b/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts index 1df1f92a431..6b42998e1c7 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts @@ -24,7 +24,7 @@ import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recover import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { isSshCommandExitError } from '../../ssh/remote-exec/remote-exec-command' import { wakeStoppedManagedOrcad } from './orcad-managed-wake' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { errorMessage } from '../../../shared/error-message' const ReclaimStatusSchema = z.enum(['none', 'eligible', 'refused', 'reclaimed']) diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel.ts index 6fbdfb72840..2018e5f523a 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel.ts @@ -10,7 +10,7 @@ import { import { getManagedOrcadCrashLoopBrake } from './orcad-managed-crash-loop' import { OrcadManagedTunnelManager } from './orcad-managed-tunnel-manager' import { buildOnBindableLocalPort } from './orcad-managed-tunnel-local-port' -import { getRemoteRuntimeSharedControlAnsweredAt } from '../../ipc/runtime-environments/runtime-environment-shared-control-answers' +import { getRemoteRuntimeSharedControlAnsweredAt } from '../../ipc/runtime-environments/connections/runtime-environment-shared-control-answers' import { getSshConnectionManager, getSshTargetRegistryStore diff --git a/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts b/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts index 5787ab61cde..67785084ea1 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts @@ -15,7 +15,7 @@ import { } from '../../../shared/orcad-managed-runtime' import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' import { runTargetLifecycle } from '../../ipc/ssh/ssh-target-lifecycle-queue' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { closeOrcadManagedTunnel, ensureOrcadManagedTunnel, diff --git a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts index b9483aed0c6..08d7c760b4f 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts @@ -57,7 +57,7 @@ vi.mock('../activation/orcad-active-readiness', () => ({ probeActiveOrcadReadine vi.mock('../install/orcad-remote-build-hash', () => ({ readRemoteOrcadBuildHash: mocks.buildHash })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../install/orcad-local-build-hash', () => ({ @@ -213,21 +213,6 @@ describe('updateManagedOrcadEnvironment', () => { }) }) -describe('updateManagedOrcadEnvironment on a host already running this build', () => { - beforeEach(() => { - mocks.deploy.mockResolvedValue({ outcome: 'already-active', fullVersion: MANAGED_VERSION }) - }) - - it('starts a slot proven stopped and forwards to the port it bound', async () => { - mocks.wake.mockResolvedValueOnce({ outcome: 'started', readiness: managedReadiness() }) - await expect( - updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - ).resolves.toMatchObject({ outcome: 'already-current', activeVersion: MANAGED_VERSION }) - expect(mocks.wake.mock.calls[0]?.[0]).toMatchObject({ port: 6_768 }) - expect(mocks.rebuildTunnel).toHaveBeenCalledWith(harness.userDataPath, 'environment-1') - }) -}) - describe('rollbackManagedOrcadEnvironment', () => { it.each([ [{ ...idle, liveSessions: 2 }, 'orcad_rollback_terminals_running'], @@ -284,24 +269,6 @@ describe('rollbackManagedOrcadEnvironment', () => { expect(mocks.rollback).not.toHaveBeenCalled() }) - it('rolls back against the installed bytes of the previous slot', async () => { - mocks.rollback.mockResolvedValueOnce({ - outcome: 'rolled-back', - target: MANAGED_PREVIOUS_VERSION, - discarded: [MANAGED_VERSION], - verdict: { decision: 'activate', coverage: 'pty-spawn', warnings: [] } - }) - await expect( - rollbackManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - ).resolves.toMatchObject({ outcome: 'rolled-back', activeVersion: MANAGED_PREVIOUS_VERSION }) - expect(mocks.rollback.mock.calls[0]?.[0]).toMatchObject({ targetBuildHash: 'previous-hash' }) - expect(mocks.probe).toHaveBeenCalledWith(expect.anything(), { - buildHash: 'previous-hash', - fullVersion: MANAGED_PREVIOUS_VERSION - }) - expect(mocks.rebuildTunnel).toHaveBeenCalledWith(harness.userDataPath, 'environment-1') - }) - it('keeps the enrolled grant when the restored server offers a new device', async () => { mocks.rollback.mockResolvedValueOnce({ outcome: 'rolled-back', diff --git a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts index 64a7ed4a312..0975bc3181f 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts @@ -5,7 +5,7 @@ import type { OrcadManagedPastLiveTerminals } from '../../../shared/orcad-managed-runtime' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { wakeAlreadyActiveOrcad } from './orcad-already-active-wake' import { clearManagedOrcadUpdateDeferral, diff --git a/src/main/managed-server/lifecycle/orcad-runtime-target.ts b/src/main/managed-server/lifecycle/orcad-runtime-target.ts index 14f1f811f9e..48179070f8d 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-target.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-target.ts @@ -1,6 +1,6 @@ import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { resolveOrcadDeploymentTargetFacts } from '../install/orcad-deployment-target' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import type { OrcadHostTransport } from '../install/orcad-host-transport' import { pinnedRuntimeTargetForHost } from '../install/pinned-runtime-host-target' import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts index a1100294a84..50f9f4679cb 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts @@ -1,5 +1,5 @@ // Lost channels drop their sockets but keep the listener; tunnel reconnect logic owns recovery. -import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' +import { OrcadStdioBridgeUnavailableError } from '../../orcad/diagnostics/orcad-host-unavailable' import type { OrcadHostTransport } from '../install/orcad-host-transport' import { checkOrcadStdioBridge, diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts index 858192ec5de..2932f2718e9 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts @@ -5,7 +5,7 @@ import type { Server } from 'node:net' import { PassThrough } from 'node:stream' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import '../../orcad/orcad-host-unavailable' +import '../../orcad/diagnostics/orcad-host-unavailable' import './orcad-stdio-bridge' import { orcadPosixStdioBridgeCommand, diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts index 66c91199765..8def66aadc6 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts @@ -1,7 +1,7 @@ import { OrcadHostUnsupportedError, OrcadStdioBridgeUnavailableError -} from '../../orcad/orcad-host-unavailable' +} from '../../orcad/diagnostics/orcad-host-unavailable' import { resolveOrcadRemoteContext } from '../install/orcad-remote-context' import { orcadWindowsHomeOpCommand } from '../install/orcad-remote-windows-node' import { diff --git a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts deleted file mode 100644 index 4d7414b00dc..00000000000 --- a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' -import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' - -import { ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY } from '../../../../shared/orcad-runtime-capabilities' -import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' - -const sendRequest = vi.hoisted(() => vi.fn()) -const status = vi.hoisted((): { capabilities: string[] } => ({ capabilities: [] })) -vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ - sendRemoteRuntimeRequestOnSocket: async ( - pairing: unknown, - method: string, - params: unknown, - _timeoutMs: number, - _envelope: unknown, - validate: (response: unknown) => void - ) => { - validate({ - ok: true, - _meta: { runtimeId: 'runtime' }, - result: { capabilities: status.capabilities } - }) - return sendRequest(pairing, method, params) - } -})) - -const { - abortRemoteOrcadMigrationCatalog, - commitRemoteOrcadMigrationCatalog, - readRemoteOrcadMigrationCatalogState, - stageRemoteOrcadMigrationCatalog -} = await import('./orcad-migration-catalog-client') -const { ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED } = - await import('./orcad-migration-request') - -const OPERATIONS = [ - stageRemoteOrcadMigrationCatalog, - commitRemoteOrcadMigrationCatalog, - readRemoteOrcadMigrationCatalogState, - abortRemoteOrcadMigrationCatalog -] - -function sshManifest(): OrcadMigrationManifest { - const unsigned = { - version: ORCAD_MIGRATION_MANIFEST_VERSION, - migrationId: 'migration-kind', - createdAt: '2026-10-01T00:00:00.000Z', - source: { sshTargetId: 'ssh-prod', sshTargetGeneration: 7, targetLabel: 'Production' }, - payload: { repositories: [], projectGroups: [], folderWorkspaces: [] } - } - return { ...unsigned, manifestSha256: computeOrcadMigrationManifestSha256(unsigned) } -} - -/** Include unknown wire kinds from newer or malformed peers. */ -function manifestOfKind(kind: string): OrcadMigrationManifest { - const source: OrcadMigrationManifest['source'] = { - kind: 'local-wsl', - distro: 'Ubuntu', - scopeRepoIds: [], - scopeFolderWorkspaceIds: [], - generation: 1 - } - Object.assign(source, { kind }) - return { ...sshManifest(), source } -} - -const pairingCode = encodePairingOffer({ - v: PAIRING_OFFER_VERSION, - endpoint: 'ws://127.0.0.1:46768/runtime', - deviceToken: 'device-token', - publicKeyB64: 'public-key', - pairedDeviceId: 'paired-desktop' -}) - -beforeEach(() => { - vi.clearAllMocks() - sendRequest.mockResolvedValue({ ok: false, error: { code: 'x', message: 'sent' } }) - status.capabilities = [ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY] -}) - -describe('orcad migration source-kind capability gate', () => { - it.each(OPERATIONS)('never sends a WSL manifest to an older destination', async (op) => { - await expect(op(pairingCode, manifestOfKind('local-wsl'))).rejects.toThrow( - ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED - ) - expect(sendRequest).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts index 82969e80fdd..a5539c049b7 100644 --- a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' diff --git a/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts b/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts index a52afb6e458..fd8878d6c11 100644 --- a/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts +++ b/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts @@ -1,6 +1,6 @@ import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationSourceCutover } from '../../../../../shared/orcad-migration/orcad-migration-source-cutover' -import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/migration/orcad-migration-manifest-digest' export function orcadMigrationCutoverFixture( migrationId = 'migration-1', diff --git a/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts b/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts index f039e5abfbb..a28a2dbc602 100644 --- a/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts +++ b/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts @@ -4,8 +4,8 @@ import type { OrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest' import { parseOrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' -import { advertisedOrcadMigrationDestinationCapabilities } from '../../../../orcad/orcad-migration-destination-capabilities' -import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' +import { advertisedOrcadMigrationDestinationCapabilities } from '../../../../orcad/migration/orcad-migration-destination-capabilities' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/migration/orcad-migration-manifest-digest' import type { Store } from '../../../../persistence/loading-store/store' import type { OrcadMigrationDestinationCatalog } from '../orcad-migration-cutover-coordinator' diff --git a/src/main/media/image-file-signature.test.ts b/src/main/media/image-file-signature.test.ts deleted file mode 100644 index 760fc9f82a1..00000000000 --- a/src/main/media/image-file-signature.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { detectImageFileSignature, IMAGE_SIGNATURE_BYTES } from './image-file-signature' - -const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d] -const JPEG = [0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 1] - -describe('detectImageFileSignature', () => { - it.each([ - ['png', Buffer.from(PNG), 'image/png'], - ['jpg', Buffer.from(JPEG), 'image/jpeg'], - ['gif', Buffer.from('GIF89a\x01\x00\x01\x00\x00\x00', 'latin1'), 'image/gif'], - ['gif', Buffer.from('GIF87a\x01\x00\x01\x00\x00\x00', 'latin1'), 'image/gif'], - ['webp', Buffer.from('RIFF\x24\x00\x00\x00WEBP', 'latin1'), 'image/webp'] - ])('recognizes %s from its leading bytes', (extension, header, mimeType) => { - expect(header.length).toBeLessThanOrEqual(IMAGE_SIGNATURE_BYTES) - expect(detectImageFileSignature(header)).toEqual({ mimeType, extension }) - }) - - it.each([ - ['empty input', Buffer.alloc(0)], - ['text', Buffer.from('hello world!')], - ['a PDF', Buffer.from('%PDF-1.7\n%\xe2\xe3', 'latin1')], - ['a RIFF file that is not WebP', Buffer.from('RIFF\x24\x00\x00\x00WAVE', 'latin1')], - ['a truncated PNG header', Buffer.from(PNG.slice(0, 4))] - ])('rejects %s', (_label, header) => { - expect(detectImageFileSignature(header)).toBeNull() - }) -}) diff --git a/src/main/media/image-file-signature.ts b/src/main/media/image-file-signature.ts deleted file mode 100644 index 31ecd72724d..00000000000 --- a/src/main/media/image-file-signature.ts +++ /dev/null @@ -1,41 +0,0 @@ -export type ImageFileSignature = { - mimeType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' - extension: 'png' | 'jpg' | 'gif' | 'webp' -} - -export const IMAGE_SIGNATURE_BYTES = 12 - -const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] -const JPEG_SIGNATURE = [0xff, 0xd8, 0xff] - -function startsWith(buffer: Uint8Array, bytes: readonly number[], offset = 0): boolean { - return ( - buffer.length >= offset + bytes.length && - bytes.every((byte, index) => buffer[offset + index] === byte) - ) -} - -function startsWithAscii(buffer: Uint8Array, text: string, offset = 0): boolean { - return startsWith( - buffer, - Array.from(text, (char) => char.charCodeAt(0)), - offset - ) -} - -// Signature checks identify file types without proving the image decodes. -export function detectImageFileSignature(buffer: Uint8Array): ImageFileSignature | null { - if (startsWith(buffer, PNG_SIGNATURE)) { - return { mimeType: 'image/png', extension: 'png' } - } - if (startsWith(buffer, JPEG_SIGNATURE)) { - return { mimeType: 'image/jpeg', extension: 'jpg' } - } - if (startsWithAscii(buffer, 'GIF87a') || startsWithAscii(buffer, 'GIF89a')) { - return { mimeType: 'image/gif', extension: 'gif' } - } - if (startsWithAscii(buffer, 'RIFF') && startsWithAscii(buffer, 'WEBP', 8)) { - return { mimeType: 'image/webp', extension: 'webp' } - } - return null -} diff --git a/src/main/media/media-preview-protocol.test.ts b/src/main/media/media-preview-protocol.test.ts index 7f05d1e04ef..ec328579311 100644 --- a/src/main/media/media-preview-protocol.test.ts +++ b/src/main/media/media-preview-protocol.test.ts @@ -15,7 +15,7 @@ vi.mock('../ipc/filesystem/access/local-file-access-resolution', () => ({ resolveLocalFileRequestPath: authorize })) -vi.mock('../ipc/runtime-environments/runtime-environment-registry-root', () => ({ +vi.mock('../ipc/runtime-environments/catalog/runtime-environment-registry-root', () => ({ readRegisteredPairingRevision: vi.fn(() => 9) })) vi.mock('./remote-file-preview-reader', async (importOriginal) => ({ diff --git a/src/main/media/media-preview-protocol.ts b/src/main/media/media-preview-protocol.ts index b1d7e9a57b6..419e37875a7 100644 --- a/src/main/media/media-preview-protocol.ts +++ b/src/main/media/media-preview-protocol.ts @@ -33,7 +33,7 @@ import { statRemotePreviewFile, type RemotePreviewFileSnapshot } from './remote-file-preview-reader' -import { readRegisteredPairingRevision } from '../ipc/runtime-environments/runtime-environment-registry-root' +import { readRegisteredPairingRevision } from '../ipc/runtime-environments/catalog/runtime-environment-registry-root' import { grants, mintPreviewUrl, diff --git a/src/main/media/remote-file-preview-reader.test.ts b/src/main/media/remote-file-preview-reader.test.ts index 6f0bd64b10a..4682c101e29 100644 --- a/src/main/media/remote-file-preview-reader.test.ts +++ b/src/main/media/remote-file-preview-reader.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { callRuntimeEnvironment } = vi.hoisted(() => ({ callRuntimeEnvironment: vi.fn() })) -vi.mock('../ipc/runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../ipc/runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment })) -vi.mock('../ipc/runtime-environments/runtime-environment-registry-root', () => ({ +vi.mock('../ipc/runtime-environments/catalog/runtime-environment-registry-root', () => ({ getRuntimeEnvironmentRegistryRoot: () => '/user-data' })) import { @@ -50,16 +50,6 @@ describe('remote file preview reader', () => { ...granted, grantId: 'g-2' }) - expect(callRuntimeEnvironment).toHaveBeenCalledWith( - '/user-data', - 'env-1', - 'files.resolveTerminalPath', - { worktree: 'id:wt-1', pathText: '/tmp/clip.mp4' }, - 15_000, - 7, - undefined, - { signal } - ) callRuntimeEnvironment.mockResolvedValueOnce(answer('/tmp/other.mp4')) await expect(renewRemotePreviewGrant(granted, signal)).rejects.toThrow('no longer grants') }) @@ -76,7 +66,5 @@ describe('remote file preview reader', () => { .mockResolvedValueOnce(ok({ contentBase64: 'AQID', bytesRead: 3, eof: true })) const range = await readRemotePreviewRange(address, 10, 900_000, 262_157, signal) expect(range.byteLength).toBe(262_147) - expect(callRuntimeEnvironment.mock.calls[0]?.[3]).toMatchObject({ offset: 10, length: 262_144 }) - expect(callRuntimeEnvironment.mock.calls[1]?.[3]).toMatchObject({ offset: 262_154, length: 3 }) }) }) diff --git a/src/main/media/remote-file-preview-reader.ts b/src/main/media/remote-file-preview-reader.ts index 25602eff652..e0aa1222676 100644 --- a/src/main/media/remote-file-preview-reader.ts +++ b/src/main/media/remote-file-preview-reader.ts @@ -3,8 +3,8 @@ import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote- import { remoteFileRequest } from '../../shared/file-access/remote-file-locator' import { isRenewableTerminalFileGrantRefusal } from '../../shared/file-access/terminal-file-grant-refusal' import type { RuntimeFileReadChunkResult } from '../../shared/file-content/runtime-file-read' -import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' +import { callRuntimeEnvironment } from '../ipc/runtime-environments/requests/runtime-environment-transport-routing' +import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/catalog/runtime-environment-registry-root' const STAT_TIMEOUT_MS = 15_000 // Why: previews share a two-call lane; a stalled chunk must free it well before a download's minute. diff --git a/src/main/muse-usage/muse-usage-record-parser.ts b/src/main/muse-usage/muse-usage-record-parser.ts index 15d3bcb80a3..2e37b044df5 100644 --- a/src/main/muse-usage/muse-usage-record-parser.ts +++ b/src/main/muse-usage/muse-usage-record-parser.ts @@ -1,6 +1,7 @@ import { record, type JsonRecord } from '../../shared/codex-rollout-jsonl-cursor' import { unwrapMuseLogRecords } from '../../shared/muse-session-log' -import { ensureNumber, extractString } from '../usage/source-input/usage-record-coercion' +import { ensureNumber } from '../usage/source-input/usage-record-coercion' +import { extractString } from '../../shared/trimmed-string' import type { MuseUsageParsedEvent } from './types' export type MuseUsageParseContext = { diff --git a/src/main/native-chat/__fixtures__/openclaude-0.31.0-local-command-rows.jsonl b/src/main/native-chat/__fixtures__/openclaude-0.31.0-local-command-rows.jsonl deleted file mode 100644 index 78307deee6c..00000000000 --- a/src/main/native-chat/__fixtures__/openclaude-0.31.0-local-command-rows.jsonl +++ /dev/null @@ -1,13 +0,0 @@ -{"type":"mode","mode":"normal","sessionId":"00000000-0000-4000-8000-000000000000"} -{"type":"file-history-snapshot","messageId":"b57b5064-f405-496e-972e-a8f0401f5195","snapshot":{"messageId":"b57b5064-f405-496e-972e-a8f0401f5195","trackedFileBackups":{},"timestamp":"2026-09-23T00:21:16.966Z"},"isSnapshotUpdate":false} -{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to."},"isMeta":true,"uuid":"77469cbb-626a-48d7-a43c-c15c7614a95f","timestamp":"2026-09-23T00:21:16.965Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"parentUuid":"77469cbb-626a-48d7-a43c-c15c7614a95f","isSidechain":false,"type":"user","message":{"role":"user","content":"/context\n context\n "},"uuid":"b57b5064-f405-496e-972e-a8f0401f5195","timestamp":"2026-09-23T00:21:16.965Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"parentUuid":"b57b5064-f405-496e-972e-a8f0401f5195","isSidechain":false,"type":"user","message":{"role":"user","content":" \u001b[1mContext Usage\u001b[22m\n\u001b[38;5;244m⛁ ⛁ ⛁ ⛁ ⛁ ⛁ \u001b[38;5;246m⛁ ⛁ ⛁ ⛁ \u001b[39m \u001b[38;5;246mgpt-4o · 18.3k/128k tokens (14%)\u001b[39m\n\n\u001b[38;5;246m⛁ ⛁ ⛁ ⛁ \u001b[38;5;220m⛀ \u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;246m\u001b[3mEstimated usage by category\u001b[23m\u001b[39m\n \u001b[38;5;244m⛁\u001b[39m System prompt: \u001b[38;5;246m8k tokens (6.2%)\u001b[39m\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;246m⛁\u001b[39m System tools: \u001b[38;5;246m10k tokens (7.8%)\u001b[39m\n \u001b[38;5;220m⛁\u001b[39m Skills: \u001b[38;5;246m304 tokens (0.2%)\u001b[39m\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;246m⛶\u001b[39m Free space: \u001b[38;5;246m63.3k (49.5%)\u001b[39m\n \u001b[38;5;246m⛝ Autocompact buffer: 46.4k tokens (36.2%)\u001b[39m\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m\n\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m\n\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\u001b[38;5;246m⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\u001b[38;5;246m⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\u001b[38;5;246m⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\n\u001b[1mSkills\u001b[22m\u001b[38;5;246m · /skills\u001b[39m"},"uuid":"ed4aeadc-1c29-4cd6-a074-fc179a168707","timestamp":"2026-09-23T00:21:16.965Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"type":"file-history-snapshot","messageId":"46776637-ece8-482c-b346-65c2938f80aa","snapshot":{"messageId":"46776637-ece8-482c-b346-65c2938f80aa","trackedFileBackups":{},"timestamp":"2026-09-23T00:21:28.270Z"},"isSnapshotUpdate":false} -{"parentUuid":"ed4aeadc-1c29-4cd6-a074-fc179a168707","isSidechain":false,"type":"user","message":{"role":"user","content":"Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to."},"isMeta":true,"uuid":"b42e5475-0947-44ae-a15e-24f1e74d6a72","timestamp":"2026-09-23T00:21:28.270Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"parentUuid":"b42e5475-0947-44ae-a15e-24f1e74d6a72","isSidechain":false,"type":"user","message":{"role":"user","content":"/cost\n cost\n "},"uuid":"46776637-ece8-482c-b346-65c2938f80aa","timestamp":"2026-09-23T00:21:28.269Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"parentUuid":"46776637-ece8-482c-b346-65c2938f80aa","isSidechain":false,"type":"system","subtype":"local_command","content":"\u001b[2mTotal cost: $0.0000\u001b[22m\n\u001b[2mTotal duration (API): 0s\u001b[22m\n\u001b[2mTotal duration (wall): 24s\u001b[22m\n\u001b[2mTotal code changes: 0 lines added, 0 lines removed\u001b[22m\n\nUsage: 0 input, 0 output","level":"info","timestamp":"2026-09-23T00:21:28.270Z","uuid":"a1ea4717-298a-4f3e-b5d7-f8a6b2936f10","isMeta":false,"userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"type":"file-history-snapshot","messageId":"4bb33790-bbbf-4b6d-8701-a3e7135805b0","snapshot":{"messageId":"4bb33790-bbbf-4b6d-8701-a3e7135805b0","trackedFileBackups":{},"timestamp":"2026-09-23T00:21:39.716Z"},"isSnapshotUpdate":false} -{"parentUuid":"a1ea4717-298a-4f3e-b5d7-f8a6b2936f10","isSidechain":false,"type":"user","message":{"role":"user","content":"Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to."},"isMeta":true,"uuid":"a3492e9f-3fd7-4c15-a04f-dd6b170326ff","timestamp":"2026-09-23T00:21:39.715Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"parentUuid":"a3492e9f-3fd7-4c15-a04f-dd6b170326ff","isSidechain":false,"type":"user","message":{"role":"user","content":"/context\n context\n "},"uuid":"4bb33790-bbbf-4b6d-8701-a3e7135805b0","timestamp":"2026-09-23T00:21:39.715Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} -{"parentUuid":"4bb33790-bbbf-4b6d-8701-a3e7135805b0","isSidechain":false,"type":"user","message":{"role":"user","content":" \u001b[1mContext Usage\u001b[22m\n\u001b[38;5;244m⛁ ⛁ ⛁ ⛁ ⛁ ⛁ \u001b[38;5;246m⛁ ⛁ ⛁ ⛁ \u001b[39m \u001b[38;5;246mgpt-4o · 18.9k/128k tokens (15%)\u001b[39m\n\n\u001b[38;5;246m⛁ ⛁ ⛁ ⛁ \u001b[38;5;220m⛀ \u001b[38;5;135m⛀ \u001b[38;5;246m⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;246m\u001b[3mEstimated usage by category\u001b[23m\u001b[39m\n \u001b[38;5;244m⛁\u001b[39m System prompt: \u001b[38;5;246m8k tokens (6.2%)\u001b[39m\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;246m⛁\u001b[39m System tools: \u001b[38;5;246m10k tokens (7.8%)\u001b[39m\n \u001b[38;5;220m⛁\u001b[39m Skills: \u001b[38;5;246m304 tokens (0.2%)\u001b[39m\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;135m⛁\u001b[39m Messages: \u001b[38;5;246m607 tokens (0.5%)\u001b[39m\n \u001b[38;5;246m⛶\u001b[39m Free space: \u001b[38;5;246m62.7k (49.0%)\u001b[39m\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m \u001b[38;5;246m⛝ Autocompact buffer: 46.4k tokens (36.2%)\u001b[39m\n\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \u001b[39m\n\n\u001b[38;5;246m⛶ ⛶ ⛶ ⛶ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\u001b[38;5;246m⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\u001b[38;5;246m⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\u001b[38;5;246m⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ \u001b[39m\n\n\n\u001b[1mSkills\u001b[22m\u001b[38;5;246m · /skills\u001b[39m"},"uuid":"2b989a6e-c7d6-45b6-8367-f656471e4e2b","timestamp":"2026-09-23T00:21:39.715Z","userType":"external","entrypoint":"cli","cwd":"/tmp/project","sessionId":"00000000-0000-4000-8000-000000000000","version":"unknown","gitBranch":"main"} diff --git a/src/main/native-chat/agent-cli-installation-error.ts b/src/main/native-chat/agent-cli-installation-error.ts deleted file mode 100644 index 682a291ad33..00000000000 --- a/src/main/native-chat/agent-cli-installation-error.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { AgentCliInstallationProblem } from '../../shared/agent-launch/catalog/agent-cli-installation-problem' -import { - agentCliTooOldWords, - sayAgentSessionFailureEnglish -} from '../../shared/agent-session/failures/agent-session-failure-copy' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import './agent-session-wire/providers/structured-agent-session-adapter' -import { AgentSessionPreSpawnError } from './agent-session-wire/providers/structured-agent-session-adapter-errors' -import { findInErrorChain } from '../provider-process/provider-error-chain' - -export class AgentCliInstallationError extends AgentSessionPreSpawnError { - readonly installation: AgentCliInstallationProblem - - constructor(installation: AgentCliInstallationProblem) { - super(agentCliTooOldWords(installation, sayAgentSessionFailureEnglish)) - this.installation = installation - } - - static tooOld( - agent: TuiAgent, - check: { version: string; minimumVersion: string } - ): AgentCliInstallationError { - return new AgentCliInstallationError({ - agent, - installedVersion: check.version, - minimumVersion: check.minimumVersion - }) - } -} - -export function agentCliInstallationProblemOf( - error: unknown -): AgentCliInstallationProblem | undefined { - return findInErrorChain(error, (inner) => - inner instanceof AgentCliInstallationError ? inner.installation : undefined - ) -} diff --git a/src/main/native-chat/agent-launch/agent-cli-installation-error.ts b/src/main/native-chat/agent-launch/agent-cli-installation-error.ts new file mode 100644 index 00000000000..dd6fc5a975b --- /dev/null +++ b/src/main/native-chat/agent-launch/agent-cli-installation-error.ts @@ -0,0 +1,37 @@ +import type { AgentCliInstallationProblem } from '../../../shared/agent-launch/catalog/agent-cli-installation-problem' +import { + agentCliTooOldWords, + sayAgentSessionFailureEnglish +} from '../../../shared/agent-session/failures/agent-session-failure-copy' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import '../agent-session-wire/providers/structured-agent-session-adapter' +import { AgentSessionPreSpawnError } from '../agent-session-wire/providers/structured-agent-session-adapter-errors' +import { findInErrorChain } from '../../provider-process/provider-error-chain' + +export class AgentCliInstallationError extends AgentSessionPreSpawnError { + readonly installation: AgentCliInstallationProblem + + constructor(installation: AgentCliInstallationProblem) { + super(agentCliTooOldWords(installation, sayAgentSessionFailureEnglish)) + this.installation = installation + } + + static tooOld( + agent: TuiAgent, + check: { version: string; minimumVersion: string } + ): AgentCliInstallationError { + return new AgentCliInstallationError({ + agent, + installedVersion: check.version, + minimumVersion: check.minimumVersion + }) + } +} + +export function agentCliInstallationProblemOf( + error: unknown +): AgentCliInstallationProblem | undefined { + return findInErrorChain(error, (inner) => + inner instanceof AgentCliInstallationError ? inner.installation : undefined + ) +} diff --git a/src/main/native-chat/structured-agent-arguments-error.ts b/src/main/native-chat/agent-launch/structured-agent-arguments-error.ts similarity index 83% rename from src/main/native-chat/structured-agent-arguments-error.ts rename to src/main/native-chat/agent-launch/structured-agent-arguments-error.ts index eba0cf8bd13..ce954e3029e 100644 --- a/src/main/native-chat/structured-agent-arguments-error.ts +++ b/src/main/native-chat/agent-launch/structured-agent-arguments-error.ts @@ -1,5 +1,5 @@ -import type { AgentSessionArgumentProblem } from '../../shared/agent-session/agent-session-argument-problem' -import { findInErrorChain } from '../provider-process/provider-error-chain' +import type { AgentSessionArgumentProblem } from '../../../shared/agent-session/agent-session-argument-problem' +import { findInErrorChain } from '../../provider-process/provider-error-chain' /** Expose only the option name; saved values may contain secrets. */ export class StructuredAgentArgumentsError extends Error { diff --git a/src/main/native-chat/structured-agent-command-resolution.test.ts b/src/main/native-chat/agent-launch/structured-agent-command-resolution.test.ts similarity index 100% rename from src/main/native-chat/structured-agent-command-resolution.test.ts rename to src/main/native-chat/agent-launch/structured-agent-command-resolution.test.ts diff --git a/src/main/native-chat/structured-agent-command-resolution.ts b/src/main/native-chat/agent-launch/structured-agent-command-resolution.ts similarity index 90% rename from src/main/native-chat/structured-agent-command-resolution.ts rename to src/main/native-chat/agent-launch/structured-agent-command-resolution.ts index 73fb7d4b407..57f831094a8 100644 --- a/src/main/native-chat/structured-agent-command-resolution.ts +++ b/src/main/native-chat/agent-launch/structured-agent-command-resolution.ts @@ -1,22 +1,25 @@ -import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { homedir } from 'node:os' import { delimiter, isAbsolute, resolve as resolvePath } from 'node:path' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { resolveCliCommand, resolveExecutableCommand -} from '../../shared/node-cli-command-resolution' +} from '../../../shared/node-cli-command-resolution' import { hasExplicitTuiLaunchCommand, structuredAgentCommandPlan -} from '../../shared/agent-launch/startup/tui-agent-launch-command-override' -import './agent-session-wire/providers/structured-agent-session-adapter' +} from '../../../shared/agent-launch/startup/tui-agent-launch-command-override' +import '../agent-session-wire/providers/structured-agent-session-adapter' import { AgentSessionPreSpawnError, isAgentSessionPreSpawnError -} from './agent-session-wire/providers/structured-agent-session-adapter-errors' -import { guestNativePathEnv, resolveGuestNativeProgram } from '../ipc/wsl-guest-windows-drive-path' +} from '../agent-session-wire/providers/structured-agent-session-adapter-errors' +import { + guestNativePathEnv, + resolveGuestNativeProgram +} from '../../ipc/wsl-guest-windows-drive-path' export type StructuredAgentResolutionOperation = { deadline?: number diff --git a/src/main/native-chat/structured-agent-configured-args.test.ts b/src/main/native-chat/agent-launch/structured-agent-configured-args.test.ts similarity index 100% rename from src/main/native-chat/structured-agent-configured-args.test.ts rename to src/main/native-chat/agent-launch/structured-agent-configured-args.test.ts diff --git a/src/main/native-chat/agent-launch/structured-agent-configured-args.ts b/src/main/native-chat/agent-launch/structured-agent-configured-args.ts new file mode 100644 index 00000000000..9e8971943c0 --- /dev/null +++ b/src/main/native-chat/agent-launch/structured-agent-configured-args.ts @@ -0,0 +1,37 @@ +import { projectAgentLaunchProfile } from '../../../shared/agent-launch/choices/agent-launch-profile' +import { isTuiAgent } from '../../../shared/agent-launch/catalog/tui-agent-config' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { + resolveTuiAgentLaunchArgs, + type AgentLaunchProfileSettings +} from '../../../shared/agent-launch/choices/tui-agent-launch-defaults' +import { tokenizeStartupCommand } from '../../../shared/agent-launch/startup/tui-agent-startup-shell' +import { resolveLocalWindowsAgentStartupShell } from '../../../shared/windows-terminal-shell' + +/** Match terminal argument grouping before filtering provider-owned flags. */ +export function structuredAgentConfiguredArgs( + agent: string, + settings: AgentLaunchProfileSettings & Partial>, + platform: NodeJS.Platform = process.platform +): string[] { + const shell = + resolveLocalWindowsAgentStartupShell({ + platform, + isRemote: false, + terminalWindowsShell: settings.terminalWindowsShell + }) ?? 'posix' + const parsed = tokenizeStartupCommand( + isTuiAgent(agent) + ? projectAgentLaunchProfile( + agent, + { ...settings, agentLaunchChoices: undefined }, + { target: 'structured', shell } + ).args + : resolveTuiAgentLaunchArgs(agent, settings), + shell + ) + if (!parsed.ok) { + throw new Error(`${agent} Arguments are invalid: ${parsed.error}`) + } + return parsed.tokens +} diff --git a/src/main/native-chat/structured-agent-session-create-support.ts b/src/main/native-chat/agent-launch/structured-agent-session-create-support.ts similarity index 81% rename from src/main/native-chat/structured-agent-session-create-support.ts rename to src/main/native-chat/agent-launch/structured-agent-session-create-support.ts index fd11db71714..97329c466f1 100644 --- a/src/main/native-chat/structured-agent-session-create-support.ts +++ b/src/main/native-chat/agent-launch/structured-agent-session-create-support.ts @@ -1,6 +1,6 @@ -import type { AgentSessionExecutionLocation } from '../../shared/agent-session/lifecycle/agent-session-record' -import type { StructuredAgentId } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' export type StructuredAgentSessionCreateSupport = { supported: boolean diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-list-test-support.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-list-test-support.ts index 3d9d9165701..f3b9d9ac14d 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-list-test-support.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-list-test-support.ts @@ -2,7 +2,7 @@ import { resolveHiddenProbeCwd } from '../../lib/hidden-probe-cwd' import { onTestFinished, vi } from 'vitest' import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { agentSessionRecordFixture } from '../agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../testing/agent-session-record-test-fixture' import { agentModelCatalogFingerprint, agentModelCatalogScopeFingerprint diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts index a7f444f692f..e49f7e3ad20 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts @@ -1,11 +1,12 @@ -import { agentSessionRecordFixture } from '../agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../testing/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { describe, expect, it, vi } from 'vitest' import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import type { AgentSessionModelOption } from '../../../shared/agent-session/agent-session-wire' import { agentModelCatalogFingerprintForRecord } from './agent-model-catalog-fingerprint' import { createAgentModelCatalogService } from './agent-model-catalog-service' -import { AgentModelCatalogStore, type AgentModelCatalogSuccess } from './agent-model-catalog-store' +import { AgentModelCatalogStore } from './agent-model-catalog-store' +import type { AgentModelCatalogSuccess } from './agent-model-catalog-entry' const HOME: AgentSessionAccountHome = { variable: 'GROK_HOME', path: '/homes/grok' } diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts index 311f1d95f1b..358cd99b082 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts @@ -1,4 +1,4 @@ -import type { StructuredAgentResolutionOperation } from '../structured-agent-command-resolution' +import type { StructuredAgentResolutionOperation } from '../agent-launch/structured-agent-command-resolution' import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import type { AgentModelCatalogSuccess } from './agent-model-catalog-entry' diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts index 6aebf3e875e..c070ecf3eb0 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts @@ -1,4 +1,4 @@ -import type { StructuredAgentResolutionOperation } from '../structured-agent-command-resolution' +import type { StructuredAgentResolutionOperation } from '../agent-launch/structured-agent-command-resolution' import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import type { PrioritySemaphore } from '../../../shared/priority-semaphore' import { startSpan } from '../../observability/tracer' diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts index 37122867666..90a4cedaef7 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts @@ -1,4 +1,4 @@ -import type { StructuredAgentResolutionOperation } from '../structured-agent-command-resolution' +import type { StructuredAgentResolutionOperation } from '../agent-launch/structured-agent-command-resolution' import { resolveHiddenProbeCwd } from '../../lib/hidden-probe-cwd' import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import { isNativeLocalLocation } from '../../../shared/execution-host' diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts index 31c3202e239..836bb19aec6 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts @@ -3,8 +3,9 @@ import { createAgentModelCatalogService } from './agent-model-catalog-service' import { assertStructuredAgentResolutionCurrent, type StructuredAgentResolutionOperation -} from '../structured-agent-command-resolution' -import { AgentModelCatalogStore, type AgentModelCatalogSuccess } from './agent-model-catalog-store' +} from '../agent-launch/structured-agent-command-resolution' +import { AgentModelCatalogStore } from './agent-model-catalog-store' +import type { AgentModelCatalogSuccess } from './agent-model-catalog-entry' function listing(id: string): AgentModelCatalogSuccess { return { @@ -74,29 +75,6 @@ function sharedListingHarness() { return { discovery, listingFor, runs, run, store, service } } -it('finishes a shared listing for a folder that joined before the first reader gave up', async () => { - vi.useFakeTimers() - onTestFinished(() => { - vi.useRealTimers() - }) - const h = sharedListingHarness() - void h.service.demand({ agent: 'codex', workspacePath: '/a', deadline: Date.now() + 1_000 }) - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) - const b = h.service.read({ - agent: 'codex', - workspacePath: '/b', - waitForListing: true, - deadline: Date.now() + 60_000 - }) - await vi.advanceTimersByTimeAsync(2_000) - // The first reader is gone, but the listing it started is still running for the folder that joined. - expect(h.runs[0]?.signal?.aborted).toBe(false) - h.discovery.resolve({ ...listing('shared'), complete: true, configured: {} }) - await vi.advanceTimersByTimeAsync(0) - expect(await b).toMatchObject({ models: [{ id: 'shared' }] }) - expect(h.run).toHaveBeenCalledOnce() -}) - it("never answers a newly picked folder with the previous folder's late listing", async () => { const h = sharedListingHarness() const old = h.service.read({ agent: 'codex', workspacePath: '/own-old', waitForListing: true }) @@ -113,32 +91,3 @@ it("never answers a newly picked folder with the previous folder's late listing" models: [{ id: 'old' }] }) }) - -it('keeps a shared listing for an earlier-ending reader of the same folder when the first is cancelled', async () => { - vi.useFakeTimers() - onTestFinished(() => { - vi.useRealTimers() - }) - const h = sharedListingHarness() - const first = h.service.captureRead({ - agent: 'codex', - workspacePath: '/a', - deadline: Date.now() + 60_000 - }) - void h.service.demand({ agent: 'codex', workspacePath: '/a', operation: first }) - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) - const second = h.service.read({ - agent: 'codex', - workspacePath: '/a', - waitForListing: true, - deadline: Date.now() + 30_000 - }) - await vi.advanceTimersByTimeAsync(0) - first.controller.abort() - await vi.advanceTimersByTimeAsync(1_000) - expect(h.runs[0]?.signal?.aborted).toBe(false) - h.discovery.resolve({ ...listing('shared'), complete: true, configured: {} }) - await vi.advanceTimersByTimeAsync(0) - expect(await second).toMatchObject({ models: [{ id: 'shared' }] }) - expect(h.run).toHaveBeenCalledOnce() -}) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts index b7e0e509a72..19c2f6f17f2 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts @@ -1,9 +1,10 @@ import { expect, it, onTestFinished, vi } from 'vitest' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { agentSessionRecordFixture } from '../agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../testing/agent-session-record-test-fixture' import { createAgentModelCatalogService } from './agent-model-catalog-service' -import { AgentModelCatalogStore, type AgentModelCatalogSuccess } from './agent-model-catalog-store' +import { AgentModelCatalogStore } from './agent-model-catalog-store' +import type { AgentModelCatalogSuccess } from './agent-model-catalog-entry' const HOME = { variable: 'CODEX_HOME', path: '/account' } // Its picker follows a project's own settings, unlike Claude's and Codex's. @@ -23,25 +24,6 @@ function chat(sessionId: string, workspaceId = 'ws', provider = 'codex'): AgentS }) } -/** As when its tab closes: the owner is released with evidence that its process ended. */ -function released(record: AgentSessionRecord): AgentSessionRecord { - return { - ...record, - lease: { - ...record.lease, - claimStatus: 'released', - deathEvidence: { - kind: 'kill-delivered', - detail: 'closed', - observedAt: 2_000, - ownerFence: record.lease.runtimeFence, - lastProvenAliveAt: 1_000, - runtimeEnd: 'quit' - } - } - } -} - const listing = (id: string): AgentModelCatalogSuccess => ({ origin: 'probe', complete: true, @@ -123,89 +105,6 @@ function harness(agent = 'codex') { } } -it.each(['listing', 'setup'] as const)( - "keeps chat b's listing when chat a closes during its %s and an unrelated folder changes", - async (stage) => { - const h = harness() - const gate = stage === 'setup' ? Promise.withResolvers() : undefined - h.folder.gate = gate - void h.service.demand({ agent: 'codex', sessionId: 'a', deadline: Date.now() + 60_000 }) - const b = h.service.read({ - agent: 'codex', - sessionId: 'b', - waitForListing: true, - deadline: Date.now() + 30_000 - }) - if (stage === 'listing') { - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) - } - h.records.a = released(h.records.a) - h.service.retireContext('another-folder') - gate?.resolve() - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) - h.discovery.resolve(listing('shared')) - expect(await b).toMatchObject({ models: [{ id: 'shared' }] }) - expect(h.run).toHaveBeenCalledOnce() - } -) - -it.each( - (['gate', 'cli', 'settings'] as const).flatMap((stage) => - (['agent', 'workspace'] as const).map((retired) => [stage, retired] as const) - ) -)( - 'settles a waiting reader at once when its %s stage is stalled and its %s retires', - async (stage, retired) => { - vi.useFakeTimers() - onTestFinished(() => { - vi.useRealTimers() - }) - // Only agents whose picker follows a project's settings check them. - const listed = stage === 'settings' ? agent : 'codex' - const h = harness(listed) - const stalled = Promise.withResolvers() - h.folder[stage] = stalled - let settled = false - void h.service - .read({ agent: listed, sessionId: 'b', waitForListing: true, deadline: Date.now() + 30_000 }) - .then(() => { - settled = true - }) - await vi.advanceTimersByTimeAsync(0) - if (retired === 'agent') { - h.store.expireAgent(listed) - } else { - h.service.retireContext('ws') - } - await vi.advanceTimersByTimeAsync(0) - expect(settled).toBe(true) - stalled.resolve() - h.discovery.resolve(listing('retired')) - await vi.advanceTimersByTimeAsync(0) - expect(h.service.snapshot({ agent: listed, sessionId: 'b' })).not.toHaveProperty('models') - } -) - -it("still lists for chat b when chat a's record goes away while their shared setup runs", async () => { - const h = harness() - // The CLI is found only once the login shell is read again. - h.resolve.mockImplementation(async (_home, _cwd, lookup, _operation, at) => { - if (lookup !== 'recover') { - throw new Error('not on the saved PATH') - } - return { identity: `codex in ${at}`, run: h.run } - }) - const gate = Promise.withResolvers() - h.folder.gate = gate - void h.service.demand({ agent: 'codex', sessionId: 'a' }) - const b = h.service.read({ agent: 'codex', sessionId: 'b', waitForListing: true }) - delete h.records.a - gate.resolve() - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) - h.discovery.resolve(listing('shared')) - expect(await b).toMatchObject({ models: [{ id: 'shared' }] }) -}) - it('keeps one listing for a workspace on the same folder when another workspace there moves', async () => { const h = harness() h.records.a = chat('a', 'ws-a') @@ -303,35 +202,6 @@ it('holds readers of a stalled refresh only to their own deadlines, and starts n expect(await c).toMatchObject({ models: [{ id: 'fresh' }] }) }) -it.each(['cancelled', 'stopped'] as const)( - 'settles a reader at once when it is %s while its setup is stalled', - async (how) => { - vi.useFakeTimers() - onTestFinished(() => { - vi.useRealTimers() - }) - const h = harness() - h.folder.gate = Promise.withResolvers() - const reader = h.service.captureRead({ - agent: 'codex', - sessionId: 'b', - deadline: Date.now() + 30_000 - }) - let settled = false - void h.service.demand({ agent: 'codex', sessionId: 'b', operation: reader }).then(() => { - settled = true - }) - await vi.advanceTimersByTimeAsync(0) - if (how === 'cancelled') { - reader.controller.abort() - } else { - void h.service.stop() - } - await vi.advanceTimersByTimeAsync(0) - expect(settled).toBe(true) - } -) - it("keeps the folder's defaults when they arrive after a shorter last reader left", async () => { vi.useFakeTimers() onTestFinished(() => { diff --git a/src/main/native-chat/agent-session-journal/durable-rows/journal-storage-schema.ts b/src/main/native-chat/agent-session-journal/durable-rows/journal-storage-schema.ts index 4353e6e1c71..2098e6be388 100644 --- a/src/main/native-chat/agent-session-journal/durable-rows/journal-storage-schema.ts +++ b/src/main/native-chat/agent-session-journal/durable-rows/journal-storage-schema.ts @@ -157,7 +157,10 @@ export const storedMessageBody = messageBody.extend({ export const storedItemBody = z.discriminatedUnion('kind', [ storedMessageBody, - agentStartBody.extend({ worker: sender.nullable().optional() }), + agentStartBody.extend({ + worker: sender.nullable().optional(), + followUp: z.object({ of: z.string(), reopened: z.boolean() }).optional() + }), agentHandoffBody.extend({ agent: sender.nullable().optional() }), toolCallBody, diffBody, diff --git a/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts b/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts index 36fff34b4b6..ce3fe54b2d7 100644 --- a/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts +++ b/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts @@ -1,14 +1,15 @@ import { dirname, join } from 'node:path' -import { sessionIdFromFileName } from '../../../ai-vault/session-scanner-accumulator' +import { sessionIdFromFileName } from '../../../ai-vault/parsing/session-scanner-accumulator' import type { AgentType } from '../../../../shared/agent-status/contracts/agent-status-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' -import { extractString, parseJsonObject } from '../../../ai-vault/session-scanner-values' -import { asRecord } from '../../../ai-vault/session-scanner-record-value' +import { extractString } from '../../../../shared/trimmed-string' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' import { readOpenCodeTranscriptSignalViaWorker } from '../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn' import { samePiDirectory } from '../../../pi/rpc/launch/rpc-launch-resolution' -import { admitTranscriptPath } from '../../transcript-path-admission' +import { admitTranscriptPath } from '../../transcript-discovery/transcript-path-admission' import { adoptedDirectoryProbes } from './adopted-directory-probe' export type AdoptedTranscriptSource = { diff --git a/src/main/native-chat/agent-session-journal/history-import/imported-fork-tip.ts b/src/main/native-chat/agent-session-journal/history-import/imported-fork-tip.ts index 530a9214892..324e79ebacd 100644 --- a/src/main/native-chat/agent-session-journal/history-import/imported-fork-tip.ts +++ b/src/main/native-chat/agent-session-journal/history-import/imported-fork-tip.ts @@ -1,5 +1,5 @@ -import { parseJsonObject } from '../../../ai-vault/session-scanner-values' -import { asRecord } from '../../../ai-vault/session-scanner-record-value' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-codex-history.ts b/src/main/native-chat/agent-session-journal/history-import/journal-codex-history.ts index cf556f8f6d9..0bb71fd3008 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-codex-history.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-codex-history.ts @@ -1,4 +1,4 @@ -import type { CodexHistoryRecord } from '../../codex-local-history' +import type { CodexHistoryRecord } from '../../transcript-history/codex/codex-local-history' import { readRecord, readString } from '../../../codex/app-server/codex-item-field-readers' import { codexRolloutItem } from '../../../codex/history/rollouts/codex-rollout-item-projection' import { diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts index bfc020a501c..f8fd82fb1b3 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-import.ts @@ -15,8 +15,8 @@ import type { NativeChatMessage } from '../../../../shared/native-chat/native-ch import { resolveNativeChatTranscriptAgent } from '../../../../shared/native-chat/native-chat-agent-support' import { resolveSessionFilePath, type ResolveSessionFileOptions } from '../../session-file-resolver' import { readLegacyImportTranscript, TRANSCRIPT_DECODERS } from './journal-legacy-transcript-stream' -import { readOpenCodeNativeChatTranscriptFull } from '../../transcript-opencode' -import { mayBeClaudeConversationRecord } from '../../transcript-line-decoders-claude' +import { readOpenCodeNativeChatTranscriptFull } from '../../transcript-history/opencode/transcript-opencode' +import { mayBeClaudeConversationRecord } from '../../transcript-decoding/transcript-line-decoders-claude' import { createLegacyIdentityTracker } from './journal-legacy-identity' import { createPiTranscriptCollector } from './journal-pi-active-branch' import { createNewestItemWindow } from './journal-newest-item-window' diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-transcript-stream.ts b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-transcript-stream.ts index ab53fc45502..5ebd7eccd16 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-legacy-transcript-stream.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-legacy-transcript-stream.ts @@ -1,10 +1,13 @@ -import { decodeClaudeTranscriptLine } from '../../transcript-line-decoders-claude' -import { decodeCodexTranscriptLine } from '../../transcript-line-decoders-codex' -import { decodeGrokTranscriptLine } from '../../transcript-line-decoders-grok' -import { decodeOmpTranscriptLine } from '../../transcript-line-decoders-omp' +import { decodeClaudeTranscriptLine } from '../../transcript-decoding/transcript-line-decoders-claude' +import { decodeCodexTranscriptLine } from '../../transcript-decoding/transcript-line-decoders-codex' +import { decodeGrokTranscriptLine } from '../../transcript-decoding/transcript-line-decoders-grok' +import { decodeOmpTranscriptLine } from '../../transcript-decoding/transcript-line-decoders-omp' import { createReadStream } from 'node:fs' -import { decodeTranscriptStream } from '../../transcript-stream-lines' -import { readCodexLocalHistory, type CodexHistoryRecord } from '../../codex-local-history' +import { decodeTranscriptStream } from '../../transcript-streaming/transcript-stream-lines' +import { + readCodexLocalHistory, + type CodexHistoryRecord +} from '../../transcript-history/codex/codex-local-history' export async function readLegacyImportTranscript( input: { filePath: string; codex: boolean; roots?: readonly string[] }, diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-pi-active-branch.ts b/src/main/native-chat/agent-session-journal/history-import/journal-pi-active-branch.ts index bdaf032dec4..a1bffb4a39f 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-pi-active-branch.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-pi-active-branch.ts @@ -1,11 +1,12 @@ import { performance } from 'node:perf_hooks' import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { NativeChatMessage } from '../../../../shared/native-chat/native-chat-types' -import { parseJsonObject, timestampMs } from '../../../ai-vault/session-scanner-values' -import { asRecord } from '../../../ai-vault/session-scanner-record-value' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' +import { timestampMs } from '../../../ai-vault/parsing/session-record-time' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' import Database from '../../../sqlite/sync-database' -import { decodeOmpTranscriptLine } from '../../transcript-line-decoders-omp' +import { decodeOmpTranscriptLine } from '../../transcript-decoding/transcript-line-decoders-omp' function closePiImportDatabase(db: Database.Database | null): void { try { diff --git a/src/main/native-chat/agent-session-journal/history-import/journal-pi-context-import.spec.ts b/src/main/native-chat/agent-session-journal/history-import/journal-pi-context-import.spec.ts index 2afb48e405f..df7700a83b1 100644 --- a/src/main/native-chat/agent-session-journal/history-import/journal-pi-context-import.spec.ts +++ b/src/main/native-chat/agent-session-journal/history-import/journal-pi-context-import.spec.ts @@ -1,8 +1,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import Database from '../../../sqlite/sync-database' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { prepareLegacyTranscriptImport } from './journal-legacy-import' import { createTrackedJournalOpener } from '../store-lifecycle/journal-host-database-test-support' import './journal-pi-active-branch' @@ -40,36 +39,6 @@ export function registerJournalPiContextImportTests(): void { } describe('saved Pi context import', () => { - it('keeps prepared history when temporary database teardown reports an error', async () => { - const close = Database.prototype.close - const closeSpy = vi.spyOn(Database.prototype, 'close').mockImplementation(function ( - this: Database.Database - ) { - close.call(this) - throw new Error('test teardown failure') - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - try { - const items = await prepare([ - { - type: 'message', - id: 'first', - parentId: null, - message: { role: 'user', content: 'hello' } - } - ]) - expect(items).toHaveLength(1) - expect(items[0]?.identity).toMatchObject({ provider: 'legacy', recordId: 'first' }) - expect(warn).toHaveBeenCalledWith( - '[journal-pi-import] temporary database close failed:', - expect.objectContaining({ message: 'test teardown failure' }) - ) - } finally { - closeSpy.mockRestore() - warn.mockRestore() - } - }) - it.each(PI_CONTEXT_FIXTURES)('$name', async (fixture) => { const items = await prepare(fixture.entries, 'version' in fixture ? fixture.version : 3) expect( diff --git a/src/main/native-chat/agent-session-journal/input-order/journal-newest-turn.ts b/src/main/native-chat/agent-session-journal/input-order/journal-newest-turn.ts index a7b3d7d8781..5b6e6137a80 100644 --- a/src/main/native-chat/agent-session-journal/input-order/journal-newest-turn.ts +++ b/src/main/native-chat/agent-session-journal/input-order/journal-newest-turn.ts @@ -50,13 +50,6 @@ export class JournalNewestTurn { return this.root?.latest.item ?? null } - /** The newest turn or clear, when it is a turn still running. */ - running(): { item: AgentJournalRenderItem; turnId: string } | null { - const item = this.read() - const turn = item ? readAgentJournalTurn(item.body) : null - return item && turn?.state === 'running' ? { item, turnId: turn.turnId } : null - } - /** Releasing Resume marks must be written after this position. */ failure(): number { const winner = this.root?.winner diff --git a/src/main/native-chat/agent-session-journal/item-lifecycle/journal-subagent-item.ts b/src/main/native-chat/agent-session-journal/item-lifecycle/journal-subagent-item.ts index 11e65de4d02..aee9589d4b1 100644 --- a/src/main/native-chat/agent-session-journal/item-lifecycle/journal-subagent-item.ts +++ b/src/main/native-chat/agent-session-journal/item-lifecycle/journal-subagent-item.ts @@ -26,7 +26,18 @@ export function subagentJournalBody(block: NativeChatSubagentBlock): AgentJourna label: boundSubagentLabel(block.label), groupId: boundSubagentEntryId(block.groupId), ...(block.parentId !== undefined ? { parentId: boundSubagentEntryId(block.parentId) } : {}), - ...(block.run !== undefined ? { run: boundSubagentEntryId(block.run) } : {}) + ...(block.run !== undefined ? { run: boundSubagentEntryId(block.run) } : {}), + ...boundOptionalLabels(block), + ...(block.operation !== undefined + ? { + operation: { + toolName: boundSubagentLabel(block.operation.toolName), + ...(block.operation.input !== undefined + ? { input: boundSubagentLabel(block.operation.input) } + : {}) + } + } + : {}) } return { kind: 'message', @@ -35,6 +46,18 @@ export function subagentJournalBody(block: NativeChatSubagentBlock): AgentJourna } } +const OPTIONAL_LABELS = ['agentType', 'model', 'effort', 'lastMessage'] as const + +function boundOptionalLabels( + block: NativeChatSubagentBlock +): Pick { + return Object.fromEntries( + OPTIONAL_LABELS.flatMap((key) => + block[key] === undefined ? [] : [[key, boundSubagentLabel(block[key])]] + ) + ) +} + export function journaledSubagent( journal: { itemBody: (itemId: string) => AgentJournalItemBody | null }, id: string diff --git a/src/main/native-chat/agent-session-journal/journal-store.ts b/src/main/native-chat/agent-session-journal/journal-store.ts index 7ad19f089e6..cb22b39021f 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -15,6 +15,7 @@ import type { import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' import type { AgentSessionContextUsage } from '../../../shared/agent-session/agent-session-context-usage' import { latestStructuredAgentContextFacts } from '../../../shared/agent-session/structured-agent-session-context-usage' +import { runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/agent-session/view/structured-agent-session-live-turn' import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record' import { journalWroteBeforeOpen } from './replay/journal-cursor' import type { JournalHostDatabase } from './database/journal-host-database' @@ -229,8 +230,9 @@ export class AgentSessionJournal { hasRecordedItem = (itemId: string): boolean => this.state.items.has(itemId) || this.state.tombstones.has(itemId) - /** Read from the per-row turn index so hot readers never rescan history; host projection decides current work. */ - runningTurn = () => journalInputOrder(this.state).newestTurn.running() + /** Read the journal's running turn without allocating a snapshot; host projection decides current work. */ + runningTurn = (): { item: journal.AgentJournalRenderItem; turnId: string } | null => + runningStructuredAgentSessionTurnItemBySequence(this.state.items.values()) newestTurn = (): journal.AgentJournalTurnLifecycle | null => readAgentJournalTurn(journalInputOrder(this.state).newestTurn.read()?.body) diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts index 229f9d18d36..3fd364a11d2 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts @@ -102,6 +102,7 @@ export async function acquireOwner( sessionId: record.sessionId, fence, ...(acquired.link ? { link: acquired.link } : {}), + ...(acquired.accountHome ? { launchedAccountHome: acquired.accountHome } : {}), ...(acquired.accountRecipe ? { accountAcquisition: { diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts index 51df40c8a1d..5c4e98bf2e3 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts @@ -39,8 +39,8 @@ import { providerExecutableMissing, providerLaunchFolderMissing } from '../../../provider-process/provider-executable-missing' -import { argumentProblemOf } from '../../structured-agent-arguments-error' -import { agentCliInstallationProblemOf } from '../../agent-cli-installation-error' +import { argumentProblemOf } from '../../agent-launch/structured-agent-arguments-error' +import { agentCliInstallationProblemOf } from '../../agent-launch/agent-cli-installation-error' import { agentCliInstallationFacts } from '../../../../shared/agent-launch/catalog/agent-cli-installation-problem' export type FailedAcquisitionWording = { diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts index b1ae5005d03..0821a65d69d 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts @@ -1,6 +1,6 @@ import { prepareStructuredAgentSessionFork } from './structured-agent-session-fork' import { resolveCommittedStructuredAgentSessionAdoptionIntent } from '../../../runtime/agent-session/structured-agent-session-create-adoption' -import { agentConversationCopyRefusal } from '../../agent-conversation-copy-error' +import { agentConversationCopyRefusal } from '../../conversation-adoption/agent-conversation-copy-error' import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts index dba1bd926a7..4d4d74a6169 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts @@ -22,7 +22,7 @@ import { AgentConversationCopyError, AgentConversationCopyStartError, agentConversationCopyRefusal -} from '../../agent-conversation-copy-error' +} from '../../conversation-adoption/agent-conversation-copy-error' import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata' import type { StructuredAgentSessionHost } from '../host/structured-agent-session-host' diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts index 184a31f819a..e97a112a69c 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts @@ -10,7 +10,7 @@ import { AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH } from '../../../../shared/agent-session/agent-session-conversation-name' import { sliceAtCodeUnitLimit } from '../../../../shared/surrogate-safe-text-slice' -import { AgentConversationCopyError } from '../../agent-conversation-copy-error' +import { AgentConversationCopyError } from '../../conversation-adoption/agent-conversation-copy-error' import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' diff --git a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts deleted file mode 100644 index 00fdb85a2d7..00000000000 --- a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts +++ /dev/null @@ -1,482 +0,0 @@ -import { fixture } from '../../publication/history/testing/agent-session-history-contract-test-fixture' -import { PI_CWD_BUCKET_LAYOUT } from '../../../../ai-vault/session-cwd-bucket-layouts' -import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork' -import type { StructuredAgentSessionHost } from '../../host/structured-agent-session-host' -import { acpHistoryTurns } from '../../../../acp/history/acp-history-replay' -import { translateHistoryTurn } from '../../../../acp/history/acp-history-translation' -import { OPENCODE_ACP_DIALECT } from '../../../../acp/acp-dialects/opencode-dialect' -import { readAcpFixture } from '../../../../acp/timeline/testing/acp-timeline-fixture.test-support' -import { structuredRewindCut } from '../../rewind/structured-rewind-cut' -import type { JournalReplacementItem } from '../../../agent-session-journal/context-epochs/journal-epoch-replacement' -import { prepareForkSnapshot } from '../structured-agent-session-fork-snapshot' -import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { readFile, writeFile, mkdir } from 'node:fs/promises' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import { claudeConversationForkBoundary } from '../../../../claude/claude-conversation-fork-boundary' -import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' - -import { structuredAgentSessionForkBoundary } from '../structured-agent-session-fork-boundary' -import { - continuedOutsideNotice, - continuedOutsideRecordId -} from '../structured-agent-session-history-catch-up' - -it('carries a settled root opener even when the streamed block never acquired a final native row', () => { - const opener = agentJournalItemKey({ - provider: 'claude', - sessionId: 'native-source', - uuid: 'prompt-1' - }) - const selected = agentJournalItemKey({ - provider: 'claude', - sessionId: 'native-source', - uuid: 'block:msg_lost:0' - }) - const boundary = structuredAgentSessionForkBoundary( - { - sessionId: 'source', - cursor: { epoch: 'epoch', sequence: 3 }, - submissions: [], - items: [ - { - itemId: opener, - sequence: 1, - revision: 0, - observedAt: 1, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }, - { - itemId: 'root', - sequence: 2, - revision: 1, - observedAt: 2, - body: { kind: 'turn', turnId: 'root', userItemId: opener, state: 'interrupted' } - }, - { - itemId: selected, - sequence: 3, - revision: 1, - observedAt: 3, - turnScope: { kind: 'turn', turnItemId: 'root' }, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'partial' }] } - } - ] - }, - agentSessionRecordFixture({ sessionId: 'source', provider: 'claude' }), - selected - ) - expect(boundary?.checkpoint).toMatchObject({ - settled: true, - rootMessage: { sessionId: 'native-source', uuid: 'prompt-1' } - }) -}) - -it('cuts Claude forks before a local-command caveat following the response', async () => { - const rows = ( - await readFile( - new URL('../../../../claude/__fixtures__/claude-rewind-hook.jsonl', import.meta.url), - 'utf8' - ) - ) - .trim() - .split('\n') - .map((line) => JSON.parse(line)) - const row = (uuid: string, parentUuid: string, content: string, isMeta?: true) => ({ - ...rows[54], - uuid, - parentUuid, - isMeta, - message: { role: 'user', content } - }) - const caveat = row( - 'caveat', - 'ef5b13f9-6a3f-5d82-8452-cb799862efc0', - 'The command below was run directly in Claude Code.', - true - ) - const command = row('command', caveat.uuid, '/usage') - const stdout = row('stdout', command.uuid, 'ok') - const entries = [...rows.slice(0, 48), caveat, command, stdout] - const checkpoint = { - selectedItemId: 'response', - settled: true, - throughMessage: { sessionId: 'source', uuid: 'ef5b13f9-6a3f-5d82-8452-cb799862efc0' } - } - expect(claudeConversationForkBoundary(entries, checkpoint)).toBe( - 'ef5b13f9-6a3f-5d82-8452-cb799862efc0' - ) - expect( - claudeConversationForkBoundary(entries, { - ...checkpoint, - beforeMessage: { sessionId: 'source', uuid: command.uuid } - }) - ).toBe('ef5b13f9-6a3f-5d82-8452-cb799862efc0') -}) - -it('cuts before a Claude continuation notice attributed to the next imported prompt', () => { - const key = (uuid: string) => - agentJournalItemKey({ provider: 'claude', sessionId: 'source', uuid }) - const turn = (recordId: string) => - agentJournalItemKey({ provider: 'legacy', agent: 'claude', sessionId: 'chat', recordId }) - const snapshot: AgentJournalSnapshot = { - sessionId: 'chat', - cursor: { epoch: 'epoch', sequence: 6 }, - submissions: [], - items: ( - [ - { itemId: turn('T1'), body: { kind: 'turn', turnId: 'T1', state: 'completed' } }, - { - itemId: turn(continuedOutsideRecordId(key('answer'))), - body: continuedOutsideNotice(false), - turnScope: { kind: 'thread' } - }, - { - itemId: key('answer'), - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'FOXTROT' }] }, - turnScope: { kind: 'turn', turnItemId: turn('T1') } - }, - { - itemId: turn(continuedOutsideRecordId(key('late-detail'))), - body: continuedOutsideNotice(false), - turnScope: { kind: 'thread' } - }, - { - itemId: turn(continuedOutsideRecordId(key('terminal-user'))), - body: continuedOutsideNotice(false), - turnScope: { kind: 'thread' } - }, - { - itemId: turn('T2'), - body: { kind: 'turn', turnId: 'T2', state: 'completed', userItemId: key('terminal-user') } - }, - { - itemId: key('terminal-user'), - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'later terminal prompt' }] - }, - turnScope: { kind: 'turn', turnItemId: turn('T2') } - }, - { - itemId: key('late-detail'), - body: { kind: 'status', text: 'retained detail' }, - turnScope: { kind: 'turn', turnItemId: turn('T1') } - } - ] satisfies Omit< - AgentJournalSnapshot['items'][number], - 'sequence' | 'revision' | 'observedAt' - >[] - ).map((item, index) => ({ - ...item, - sequence: index + 1, - revision: 1, - observedAt: 123 - })) - } - expect( - prepareForkSnapshot({ snapshot, nextItemId: turn('T2') }).map((item) => - agentJournalItemKey(item.identity) - ) - ).toEqual([ - 'legacy:claude:chat:T1', - 'legacy:claude:chat:continued-outside%3Aclaude%3Asource%3Aanswer', - 'claude:source:answer', - 'legacy:claude:chat:continued-outside%3Aclaude%3Asource%3Alate-detail', - 'claude:source:late-detail' - ]) -}) - -it.each(['rewind', 'persisted', 'unrelated T3', 'saved fork'])( - 'forks FOXTROT without the orphan terminal notice: %s', - async (route) => { - const native = (turnId: string, ordinal: number) => - ({ provider: 'codex', threadId: 'thread-1', turnId, ordinal }) as const - const legacy = (recordId: string) => - ({ provider: 'legacy', agent: 'codex', sessionId: 'session-1', recordId }) as const - const root1 = agentJournalItemKey(legacy('root1')) - const root2 = agentJournalItemKey(legacy('root2')) - const source: JournalReplacementItem[] = ( - [ - { - identity: native('T1', 0), - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'first' }] } - }, - { - identity: legacy('root1'), - body: { - kind: 'turn', - turnId: 'T1', - userItemId: 'codex:thread-1:T1:0', - state: 'completed' - } - }, - { - identity: native('T1', 1), - turnScope: { kind: 'turn', turnItemId: root1 }, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'FOXTROT' }] } - }, - { - identity: legacy(continuedOutsideRecordId('T2')), - body: continuedOutsideNotice(false), - turnScope: { kind: 'thread' } - }, - { - identity: legacy('root2'), - body: { - kind: 'turn', - turnId: 'T2', - userItemId: 'codex:thread-1:T2:0', - state: 'completed' - } - }, - { - identity: native('T2', 0), - turnScope: { kind: 'turn', turnItemId: root2 }, - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'terminal prompt' }] - } - }, - { - identity: native('T2', 1), - turnScope: { kind: 'turn', turnItemId: root2 }, - body: { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'terminal answer' }] - } - } - ] satisfies Omit[] - ).map((row) => ({ ...row, observedAt: 123, ownerFence: 0 })) - const journal = fixture.journal - await journal.replaceEpochItems('session_created', 1, source) - if (route === 'rewind') { - const cut = structuredRewindCut(journal, { - itemId: 'codex:thread-1:T2:0', - provider: 'codex', - nativeId: 'thread-1' - }) - expect(cut).not.toBeNull() - await journal.replaceEpochItems('handle_forked', 1, cut!.kept) - } else { - await journal.replaceEpochItems('session_created', 1, [ - ...source.slice(0, 4), - // Earlier work alone cannot be introduced by a later notice. - { - identity: legacy(continuedOutsideRecordId('T1')), - body: continuedOutsideNotice(false), - observedAt: 123, - ownerFence: 0 - }, - ...(route === 'unrelated T3' - ? [ - { - identity: legacy('root3'), - body: { kind: 'turn' as const, turnId: 'T3', state: 'completed' as const }, - observedAt: 123, - ownerFence: 0 - }, - { - ...source[5]!, - identity: native('T3', 0), - turnScope: { - kind: 'turn' as const, - turnItemId: agentJournalItemKey(legacy('root3')) - } - } - ] - : []) - ]) - } - const record = agentSessionRecordFixture({ sessionId: 'session-1', provider: 'codex' }) - let snapshot = journal.snapshot() - let selected = 'codex:thread-1:T1:1' - let sourceThreadId = 'thread-1' - if (route === 'saved fork') { - const copied = prepareForkSnapshot({ - snapshot, - nextItemId: null, - sourceThreadId, - childThreadId: 'child' - }) - await journal.replaceEpochItems('session_created', 1, [ - ...copied, - source[3]!, - { - identity: legacy('fork-marker'), - body: { - kind: 'status', - text: 'Forked', - forkedFrom: { sessionId: 'parent' } - }, - observedAt: 123, - ownerFence: 0 - } - ]) - snapshot = journal.snapshot() - selected = 'codex:child:T1:1' - sourceThreadId = 'child' - } - const boundary = structuredAgentSessionForkBoundary(snapshot, record, selected) - expect(boundary).not.toBeNull() - expect( - prepareForkSnapshot({ - snapshot, - nextItemId: boundary!.nextItemId, - sourceThreadId, - childThreadId: 'result' - }).map((row) => agentJournalItemKey(row.identity)) - ).toEqual(['codex:result:T1:0', 'legacy:codex:session-1:root1', 'codex:result:T1:1']) - } -) - -it('retains the notice for an encoded ACP replay turn only while its introduced work survives', async () => { - const frames = (await readAcpFixture('opencode-v2-reopen-outside')) - .filter((frame) => frame.process === 'C' && frame.message.method === 'session/update') - .map((frame) => ({ method: 'session/update', params: frame.message.params })) - const first = acpHistoryTurns(frames, 'user-message-id')[0]! - if (first.turn === null) { - throw new Error('recorded replay has no user id') - } - const rows = translateHistoryTurn( - { - agent: 'opencode', - sessionId: 'chat', - providerSessionId: 'session-1', - dialect: OPENCODE_ACP_DIALECT, - identity: 'user-message-id' - }, - { ...first, turn: first.turn } - ) - const notice = { - itemId: 'legacy:opencode:chat:continued-outside%3Amsg_15fad6c9f001d4ix8WtRMUSWtI', - body: continuedOutsideNotice(false), - turnScope: { kind: 'thread' as const } - } - const snapshot: AgentJournalSnapshot = { - sessionId: 'chat', - cursor: { epoch: 'epoch', sequence: 3 }, - submissions: [], - items: [ - notice, - ...rows.map((row) => ({ ...row, itemId: agentJournalItemKey(row.identity) })) - ].map((row, index) => ({ ...row, sequence: index + 1, revision: 1, observedAt: 123 })) - } - expect( - prepareForkSnapshot({ snapshot, nextItemId: null }).map((row) => - agentJournalItemKey(row.identity) - ) - ).toEqual([ - 'legacy:opencode:chat:continued-outside%3Amsg_15fad6c9f001d4ix8WtRMUSWtI', - 'legacy:opencode:chat:turn-lifecycle%3Ap%3Asession-1%3Amsg_15fad6c9f001d4ix8WtRMUSWtI', - 'legacy:opencode:chat:item%3Ap%3Asession-1%3Asession-1%2Fuser%253Amsg_15fad6c9f001d4ix8WtRMUSWtI' - ]) - snapshot.items[2]!.body = { kind: 'tool-call', name: 'command', state: 'running', input: {} } - expect( - prepareForkSnapshot({ snapshot, nextItemId: null }).map((row) => - agentJournalItemKey(row.identity) - ) - ).toEqual([]) - snapshot.items.pop() - expect( - prepareForkSnapshot({ snapshot, nextItemId: null }).map((row) => - agentJournalItemKey(row.identity) - ) - ).toEqual([ - 'legacy:opencode:chat:turn-lifecycle%3Ap%3Asession-1%3Amsg_15fad6c9f001d4ix8WtRMUSWtI' - ]) -}) - -it('refuses an imported ACP tip with assistant prose but no native terminal evidence', async () => { - const nativeId = '019e6b26-18e2-7103-b7a0-7ba6bb071123' - const home = join(fixture.root, 'omp-account') - const sessions = join(home, 'sessions') - const directory = join(sessions, `${PI_CWD_BUCKET_LAYOUT.encodeScopePrefixes(fixture.root)[0]}--`) - await mkdir(directory, { recursive: true }) - await writeFile( - join(directory, `${nativeId}.jsonl`), - `${[ - { type: 'session', version: 3, id: nativeId, cwd: fixture.root }, - { - type: 'message', - id: 'prompt', - parentId: null, - message: { role: 'user', content: 'Remember 57319' } - }, - { - type: 'message', - id: 'response', - parentId: 'prompt', - message: { role: 'assistant', content: [{ type: 'text', text: 'Remembered' }] } - } - ] - .map((row) => JSON.stringify(row)) - .join('\n')}\n` - ) - for (const [recordId, role] of [ - ['prompt', 'user'], - ['response', 'assistant'] - ] as const) { - await fixture.journal.appendItem( - { provider: 'legacy', agent: 'omp', sessionId: nativeId, recordId }, - { - kind: 'message', - role, - blocks: [{ type: 'text', text: role === 'user' ? 'Remember 57319' : 'Remembered' }] - }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - } - const record = agentSessionRecordFixture({ - sessionId: 'session-1', - provider: 'omp', - accountHome: { variable: 'PI_CODING_AGENT_DIR', path: home }, - launchDirectory: fixture.root, - providerHandleChain: [ - { - linkId: 'omp-head', - origin: 'created', - mintedAtFence: 1, - observedAt: 1, - handle: { transport: 'acp', agent: 'omp', nativeId } - } - ] - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: boundary preparation reads only these saved source and adapter facets. - const host = { - deps: { - store: { - selectWritableRecord: () => ({ kind: 'writable' }), - requireWritableRecord: () => record, - admittedSendCount: () => 0 - }, - agents: { capabilities: () => ({ fork: 'tip' }) }, - adapter: { - copyConversation: async () => { - throw new Error('unexpected copy') - } - }, - resolveLaunchEnv: async () => ({ PI_CODING_AGENT_DIR: home, OMP_CODING_AGENT_DIR: sessions }) - }, - journalSnapshot: async () => fixture.journal.snapshot() - } as unknown as StructuredAgentSessionHost - await expect( - prepareStructuredAgentSessionFork({ - host, - agent: 'omp', - sessionId: 'session-1', - throughItemId: 'legacy:omp:019e6b26-18e2-7103-b7a0-7ba6bb071123:response', - location: record.location, - envelope: { - sessionId: 'omp-child', - clientOperationId: 'copy', - expectedRuntimeFence: null, - payloadFingerprint: '' - } - }) - ).rejects.toMatchObject({ refusal: { details: { reason: 'turnActive' } } }) -}) diff --git a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts index 1b2317f83df..4d42f397280 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts @@ -1,7 +1,7 @@ import { vi } from 'vitest' import { mkdir, writeFile } from 'node:fs/promises' import { join } from 'node:path' -import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../testing/agent-session-record-test-fixture' import { claudeProviderHandle, codexProviderHandle diff --git a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts index b23257f47a6..d374162499e 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts @@ -3,7 +3,7 @@ import { forkTestSource } from './structured-agent-session-fork.test-fixture' import { resolveUncommittedStructuredCreate } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal' import { handleStructuredAgentSessionCreate } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../testing/agent-session-record-test-fixture' import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork' import { diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts index 59972ae9ea4..cc6774857f9 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts @@ -22,7 +22,14 @@ import { type MutationPlan } from '../operations/structured-agent-session-mutation-plans' import type { CommandReceiptResult } from '../../agent-session-journal/writing/command-receipt-schema' -import { structuredQueueHold } from './structured-agent-session-queued-gate' +import { + canSteerStructuredQueuedMessage, + structuredQueueHold +} from './structured-agent-session-queued-gate' +import { + structuredInputExecutionWorking, + structuredInputHandoverWorking +} from './structured-agent-session-input-selection' import { refuse } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' import { queuedMessageOwed } from './structured-agent-session-queued-mail' import { resumeStructuredQueue } from './structured-agent-session-queued-pause' @@ -124,6 +131,30 @@ export function sendQueuedStructuredAgentMessage( if (row.body.command && work.working()) { return invalid("A command can't be sent while the agent is working.") } + if ( + structuredInputExecutionWorking(ctx.journal, work) && + (work.activeTurnId() === null || + structuredInputHandoverWorking(ctx.journal, work) || + !canSteerStructuredQueuedMessage( + { + record, + work, + child: context.sessions.get(ctx.sessionId)?.child, + stopping: context.readStopping(ctx.sessionId), + adapter: context.deps.adapter + }, + row + )) + ) { + return { + ok: false, + refusal: refuse( + 'agent_session_operation_invalid', + { reason: 'turnActive' }, + 'The current turn cannot accept this queued message yet.' + ) + } + } const submissionId = operationId const owed = queuedMessageOwed(context.deps, ctx.sessionId, row.body) try { diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-published-bytes.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-published-bytes.ts index deb59cdd5aa..0a8a6b38d71 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-published-bytes.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-published-bytes.ts @@ -4,8 +4,8 @@ import { refuse } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../shared/remote-runtime/remote-runtime-memory-limits' -import '../../../../shared/rpc-contract/structured-agent-session-params' -import { MAX_PROMPT_BYTES } from '../../../../shared/rpc-contract/structured-agent-session-message-params' +import '../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import { MAX_PROMPT_BYTES } from '../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-message-params' import type { AgentSessionJournal } from '../../agent-session-journal/journal-store' import { AGENT_SESSION_HISTORY_MAX_PAGE_BYTES } from '../publication/history/agent-session-history-page-bounds' import { unsettledQueuedMessages } from './structured-agent-session-queued-stop' diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts index 9b5eb8e25a1..1d4ed8ab39b 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts @@ -62,8 +62,7 @@ export class StructuredAgentSessionHost { private readonly lifetime: HostTypes.StructuredAgentSessionConversationLifetime private readonly conversationDelivery: conversation.StructuredAgentSessionConversationDelivery private readonly eventRecovery: StructuredAgentSessionEventRecovery - /** History and work-state reads, which open a chat at rest without starting its agent. */ - readonly backgroundTasks: BackgroundTasks + private readonly backgroundTasks: BackgroundTasks readonly restartResume: StructuredAgentSessionRestartResume readonly usageLimitContinue: ReturnType diff --git a/src/main/native-chat/agent-session-wire/host/structured-provider-session-ownership.ts b/src/main/native-chat/agent-session-wire/host/structured-provider-session-ownership.ts index 7f750f5ce43..2ca88498ba3 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-provider-session-ownership.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-provider-session-ownership.ts @@ -9,7 +9,7 @@ import { keysMayMatch, recordConversationKey, type ConversationKey -} from '../../structured-conversation-key' +} from '../../conversation-adoption/structured-conversation-key' export type StructuredProviderSessionOwnership = { wslDistro: string | null diff --git a/src/main/native-chat/agent-session-wire/host/testing/mobile-queued-edit-host.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/mobile-queued-edit-host.test-fixture.ts index 7d1dd5d7360..2f7e5b2b2c8 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/mobile-queued-edit-host.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/mobile-queued-edit-host.test-fixture.ts @@ -5,7 +5,7 @@ import type { import { QueuedMessageEditHoldParams, QueuedMessageUpdateParams -} from '../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +} from '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { createQueuedMessageTestRig, QUEUED_RIG_CALLER @@ -66,7 +66,7 @@ export const createMobileCommandMenuHostFixture: MobileCommandMenuHostFixtureMod const { tmpdir } = await import('node:os') const { join } = await import('node:path') const { ClaudeAtRestCommandCatalog } = - await import('../../../../claude/claude-at-rest-commands') + await import('../../../../claude/command-catalog/claude-at-rest-commands') const { commandDiscoveryRig, OMP, DISCOVERY_SESSION } = await import('../../../../acp/discovery/testing/acp-command-discovery.test-fixture') const { acpStructuredAgentDefinition } = diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-adopted-import.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-adopted-import.test.ts index 4c06752ec35..d48943d6304 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-adopted-import.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-adopted-import.test.ts @@ -23,7 +23,8 @@ import { NO_STRUCTURED_AGENTS } from '../../providers/testing/structured-agent-s vi.mock( '../../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', async (importOriginal) => { - const query = await import('../../../transcript-opencode-sqlite-query') + const query = + await import('../../../transcript-history/opencode/transcript-opencode-sqlite-query') return { ...(await importOriginal()), readOpenCodeTranscriptPageViaWorker: async ( diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-at-rest-command-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-at-rest-command-rig.test-fixture.ts index 27495d9bfc9..b5bc1bf37c4 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-at-rest-command-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-at-rest-command-rig.test-fixture.ts @@ -22,7 +22,7 @@ import type { import { ClaudeAtRestCommandCatalog, type ClaudeAtRestCommandsDeps -} from '../../../../claude/claude-at-rest-commands' +} from '../../../../claude/command-catalog/claude-at-rest-commands' import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store' import { openTestAgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store-test-harness' diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-background-wake-owner.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-background-wake-owner.test.ts deleted file mode 100644 index 1fd1b857cdf..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-background-wake-owner.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { expect, it } from 'vitest' -import { readAgentJournalTurn } from '../../../../../shared/agent-session/lifecycle/agent-session-turn-record' -import { agentJournalSubmissionKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { claudeFrame as frame } from '../../../../claude/structured/claude-structured-session-test-support' -import { - backgroundWakeCapture, - FIRST_PROMPT -} from '../../../../claude/claude-captured-fold-steer-frames.test-fixture' -import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' -import { fixture, laneDrained } from './structured-agent-session-claude-stop-contract-test-fixture' -import { - dispatch, - eventually, - openTurn, - send, - sendUnechoed -} from './structured-agent-session-claude-stop-contract-test-actions' - -async function turns() { - await laneDrained() - await fixture.host.flushStreamedEvents(SESSION) - return (await fixture.host.journalSnapshot(SESSION)).items.flatMap((item) => { - const turn = readAgentJournalTurn(item.body) - return turn ? [turn] : [] - }) -} - -// The wake frames are CLI 2.1.280's; B's place among them is constructed, not captured. -it.each([ - ['handed over before the first result, without receipts', 3_406, null], - ['handed over before the first result, reported queued', 3_406, 'queued'], - ['handed over after the first turn ended', Infinity, null] -])( - 'keeps an unrelated background wake provider-owned when a follow-up is %s', - async (_label, handoffAt, receipt) => { - const connection = fixture.claude.connections[0]! - await send(FIRST_PROMPT) - await eventually(() => expect(connection.sent).toHaveLength(1)) - const first = connection.sent[0]! - const capture = backgroundWakeCapture({ - sessionId: String(first.session_id), - first: String(first.uuid), - steer: 'unused' - }) - for (const event of capture.firstTurn.filter((event) => event.at < handoffAt)) { - frame(connection, event.frame) - } - await laneDrained() - const followUp = await send('What is seven times eight?') - await eventually(() => expect(connection.sent).toHaveLength(2)) - const written = connection.sent[1]! - if (receipt) { - frame(connection, { type: 'command_lifecycle', state: receipt, command_uuid: written.uuid }) - } - for (const event of capture.firstTurn.filter((event) => event.at >= handoffAt)) { - frame(connection, event.frame) - } - for (const event of capture.wake) { - frame(connection, event.frame) - } - - const wake = (await turns()).at(-1) - expect(wake).toMatchObject({ turnId: 'task_updated-17547', state: 'completed' }) - expect(wake?.userItemId).not.toBe(agentJournalSubmissionKey(followUp)) - expect(wake?.userItemId).not.toContain(String(written.uuid)) - expect((await dispatch(followUp)).state).not.toBe('accepted') - - // The follow-up's own echo opens its turn. - frame(connection, { ...written, parent_tool_use_id: null }) - expect((await turns()).at(-1)).toMatchObject({ turnId: written.uuid, state: 'running' }) - expect(await dispatch(followUp)).toMatchObject({ state: 'accepted' }) - } -) - -it.each([ - ['plural', (uuid: unknown) => ({ user_message_uuids: [uuid] })], - ['singular', (uuid: unknown) => ({ user_message_uuid: uuid })] -])( - 'settles a follow-up its own %s result names without letting it own the next send', - async (_label, names) => { - const connection = fixture.claude.connections[0]! - await openTurn(connection, 'Say the word A.') - const uuidA = connection.sent.at(-1)!.uuid - const followUp = await sendUnechoed(connection) - const uuidB = connection.sent.at(-1)!.uuid - frame(connection, { - type: 'result', - subtype: 'success', - is_error: false, - uuid: 'result-a', - user_message_uuids: [uuidA] - }) - // B's own result arrives with no echo, init or output of B. - frame(connection, { - type: 'result', - subtype: 'success', - is_error: false, - uuid: 'result-b', - ...names(uuidB) - }) - expect(await dispatch(followUp)).toMatchObject({ state: 'accepted' }) - - const next = await send('Say the word C.') - await eventually(() => expect(connection.sent).toHaveLength(3)) - const written = connection.sent.at(-1)! - frame(connection, { ...written, parent_tool_use_id: null }) - expect((await turns()).filter((turn) => turn.state === 'running')).toEqual([ - expect.objectContaining({ turnId: written.uuid }) - ]) - expect(await dispatch(next)).toMatchObject({ state: 'accepted' }) - } -) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-compact-background.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-compact-background.test.ts new file mode 100644 index 00000000000..cc1bb276875 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-compact-background.test.ts @@ -0,0 +1,104 @@ +import { expect, it } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' +import { + claudeFrame as frame, + claudeWasSent as wrote +} from '../../../../claude/structured/claude-structured-session-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import { + CALLER, + declareClaudeCapabilities, + fixture +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { eventually, openTurn } from './structured-agent-session-claude-stop-contract-test-actions' + +declareClaudeCapabilities() + +function conversationCommand(command: 'clear' | 'compact') { + return fixture.host.conversationCommand(CALLER, { + command, + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.store.getRecord(SESSION)!.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.conversationCommand', + sessionId: SESSION, + fields: { command } + }) + } + }) +} + +// Frames from Claude Code 2.1.323 launching a background subagent, trimmed. +it('compacts a Claude chat while its background subagent runs, as Claude does', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection, 'Start a subagent.') + frame(connection, { + type: 'assistant', + uuid: 'agent-call', + parent_tool_use_id: null, + message: { + id: 'msg-agent', + role: 'assistant', + content: [ + { + type: 'tool_use', + id: 'toolu-agent', + name: 'Agent', + input: { description: 'probe subagent', prompt: 'Look around', run_in_background: true } + } + ] + } + }) + frame(connection, { + type: 'system', + subtype: 'background_tasks_changed', + uuid: 'tasks-changed', + tasks: [ + { + task_id: 'task-agent', + task_type: 'local_agent', + subagent_type: 'general-purpose', + description: 'probe subagent' + } + ] + }) + frame(connection, { + type: 'system', + subtype: 'task_started', + uuid: 'task-started', + task_id: 'task-agent', + tool_use_id: 'toolu-agent', + description: 'probe subagent', + is_backgrounded: true, + task_type: 'local_agent' + }) + frame(connection, { + type: 'user', + uuid: 'agent-launched', + parent_tool_use_id: null, + message: { + role: 'user', + content: [ + { type: 'tool_result', tool_use_id: 'toolu-agent', content: 'Async agent launched.' } + ] + } + }) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'turn-end' }) + await fixture.host.flushStreamedEvents(SESSION) + await eventually(() => + expect(fixture.host.readStatusSummary(SESSION)?.status).not.toBe('working') + ) + + // /clear stops the agent, which would end the subagent with it. + expect(await conversationCommand('clear')).toMatchObject({ + ok: false, + refusal: { details: { reason: 'backgroundTasksRunning' } } + }) + expect(await conversationCommand('compact')).toMatchObject({ ok: true }) + await eventually(() => expect(wrote(connection, '/compact')).toBe(true)) +}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-actions.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-actions.ts index 7710211d9fb..67f6431fb9a 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-actions.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-actions.ts @@ -10,7 +10,7 @@ import { claudeWasSent as wrote, type FakeConnection } from '../../../../claude/structured/claude-structured-session-test-support' -import { invokeCanUseTool } from '../../../../claude/claude-can-use-tool-test-support' +import { invokeCanUseTool } from '../../../../claude/structured/permissions/claude-can-use-tool-test-support' import { HOST_TEST_SESSION as SESSION, hostTestMessage, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts index f2b61430a39..66ff9f9fd09 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, expect, vi } from 'vitest' import type { AgentStatusStructuredSessionSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' -import { runClaudeControl } from '../../../../claude/claude-agent-sdk-control-requests' +import { runClaudeControl } from '../../../../claude/sdk-transport/claude-agent-sdk-control-requests' import { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' import type { ClaudeStructuredSessionEvent } from '../../../../claude/structured/claude-structured-session-event' import { @@ -26,7 +26,10 @@ import { hostTestAttachParams, resetHostTestOperationIds } from './structured-agent-session-host-test-data' -import { NO_STRUCTURED_AGENTS } from '../../providers/testing/structured-agent-session-adapter-router-test-support' +import { + claudeAndCodexAgents, + NO_STRUCTURED_AGENTS +} from '../../providers/testing/structured-agent-session-adapter-router-test-support' export const CALLER = { callerKey: 'client-1' } // Claude Code 2.1.280 system/init capabilities. @@ -57,6 +60,13 @@ let server: AgentHookServer let statusSubject: AgentStatusStructuredSessionSubject | undefined +let declaresClaude = false + +/** Call at module scope: hosts then declare Claude's real capabilities. */ +export function declareClaudeCapabilities(): void { + declaresClaude = true +} + beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) resetHostTestOperationIds() @@ -103,7 +113,9 @@ beforeEach(async () => { }) store = await openTestAgentSessionRecordStore(root) host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, + agents: declaresClaude + ? claudeAndCodexAgents({ claude: adapter, codex: adapter }) + : NO_STRUCTURED_AGENTS, store, adapter: Object.assign(adapter, { supportsCreate: () => true }), journalDatabase: openTestJournalHostDatabase(root), diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts index 63d3cdce0f4..2517f8a6f91 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts @@ -1,4 +1,11 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { CodexAppServerConnection } from '../../../../codex/app-server/codex-app-server-connection-types' +import { optionSession } from '../../../../codex/structured/catalog/codex-structured-option-session.test-fixture' +import { + readCodexAppliedInputOptions, + resolvedCodexMessageOptions +} from '../../../../codex/structured/turns/codex-structured-message-options' +import { dispatchCodexTurn } from '../../../../codex/structured/turns/codex-structured-turn-start' import { createQueuedMessageTestRig, QUEUED_RIG_CALLER @@ -17,7 +24,24 @@ import { agentJournalSubmissionKey } from '../../../../../shared/agent-session/j let rig: QueuedMessageTestRig beforeEach(async () => { + const request = vi.fn(async () => ({})) + const native = optionSession(request) + native.threadId = THREAD rig = await createQueuedMessageTestRig({ restartable: true }) + rig.host.deps.adapter.readAppliedInputOptions = (input) => + input.sessionId === SESSION ? readCodexAppliedInputOptions(native, input) : null + rig.host.deps.adapter.holdsLiveProviderProcess = (sessionId, generation) => + sessionId === SESSION && + generation === native.acquisitionGeneration && + !native.ended && + !native.connection.closed + rig.dispatch.mockImplementation(async (input) => + dispatchCodexTurn( + native, + { ...input, turnOptions: await resolvedCodexMessageOptions(native, input.executionOptions) }, + undefined + ) + ) }) afterEach(() => rig.dispose()) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-budget.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-budget.test.ts index e1b8aabf7aa..e6eed3372a4 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-budget.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-budget.test.ts @@ -2,7 +2,8 @@ import { mkdir, realpath, writeFile, rm, symlink } from 'node:fs/promises' vi.mock( '../../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', async (original) => { - const query = await import('../../../transcript-opencode-sqlite-query') + const query = + await import('../../../transcript-history/opencode/transcript-opencode-sqlite-query') return { ...(await original()), readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-contract-test-fixture.ts index 9049efc288a..68e6aa7f116 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-contract-test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-contract-test-fixture.ts @@ -2,7 +2,8 @@ import { writeFile } from 'node:fs/promises' vi.mock( '../../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', async (original) => { - const query = await import('../../../transcript-opencode-sqlite-query') + const query = + await import('../../../transcript-history/opencode/transcript-opencode-sqlite-query') return { ...(await original()), readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption.test.ts deleted file mode 100644 index e6c8557a1c5..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { mkdir, realpath, rename, writeFile } from 'node:fs/promises' -vi.mock( - '../../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', - async (original) => { - const query = await import('../../../transcript-opencode-sqlite-query') - return { - ...(await original()), - readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, - readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => - query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) - } - } -) -import { join } from 'node:path' -import { expect, it, vi } from 'vitest' -// Adoption forks the AI Vault service for the chat's title; naming is covered elsewhere. -vi.mock('../../../../ai-vault/session-titles/session-title-resolver', () => ({ - resolveLocalAiVaultSessionTitles: async () => ({ titles: [] }) -})) -import { - createTestParams, - CREATE_TEST_CALLER as CALLER -} from './structured-agent-session-create-test-fixture' -import { - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD -} from './structured-agent-session-host-test-data' -import { - codexLegacyMirrorRecords, - writeCodexHistoryFixture -} from '../../../agent-session-journal/history-import/codex-history-test-fixture' -import { structuredAgentRuntimeMetadata } from '../../../../runtime/agent-session/installation/structured-agent-runtime-metadata' -import { - resolveStructuredAgentSessionAdoptionForCreate, - structuredAgentSessionAdoptAttach -} from '../../../../runtime/agent-session/structured-agent-session-create-adoption' -import { prepareCodexAiVaultSessionResume } from '../../../../codex/history/resume/codex-ai-vault-session-resume' - -import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' - -it.each([ - ['matching', THREAD], - ['legacy', THREAD], - ['mismatched', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61'] -] as const)( - 'resolves a selected-account rollout with %s metadata before at-rest publication', - async (_kind, metadataId) => { - vi.stubEnv('ORCA_USER_DATA_PATH', join(fixture.rig.root, 'host-data')) - const accountHome = { variable: 'CODEX_HOME', path: join(fixture.rig.root, 'selected-account') } - const sessions = join(accountHome.path, 'sessions') - await mkdir(sessions, { recursive: true }) - const rollout = await writeCodexHistoryFixture( - sessions, - THREAD, - ['saved CLI turn'], - undefined, - metadataId - ) - if (_kind === 'legacy') { - await writeFile( - rollout.filePath, - [ - { type: 'session_meta', payload: { id: THREAD, cwd: fixture.rig.root } }, - ...codexLegacyMirrorRecords() - ] - .map((record) => JSON.stringify(record)) - .join('\n') - ) - } - if (metadataId !== THREAD) { - // Keep filename lookup valid so the imported metadata is what refuses the mismatched source. - await rename(rollout.filePath, join(sessions, `rollout-2026-10-27T00-00-00-${THREAD}.jsonl`)) - } - const metadata = structuredAgentRuntimeMetadata('codex') - if (!metadata?.transcriptImport) { - throw new Error('Codex transcript importer is not registered') - } - const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'codex', - transcriptImport: metadata.transcriptImport, - providerSessionId: THREAD, - selectedAccountHome: accountHome, - launchEnv: {}, - workspaceCwd: fixture.rig.root, - prepareCodexResume: (args) => - prepareCodexAiVaultSessionResume(args, { - runtimeHome: null, - systemCodexHomePath: join(fixture.rig.root, 'system-account'), - preparePinnedLaunchHome: async () => { - throw new Error('At-rest adoption must not ready a fork launch') - } - }) - }) - expect(adoption.accountHome).toEqual(accountHome) - expect(adoption.transcriptPath).toBe( - await realpath(join(sessions, `rollout-2026-10-27T00-00-00-${THREAD}.jsonl`)) - ) - const result = await fixture.rig.host.create( - CALLER, - createTestParams(undefined, { - accountHome: adoption.accountHome, - adopt: structuredAgentSessionAdoptAttach({ - definition: metadata.definition, - handleNamesTranscript: metadata.transcriptImport.handleNamesTranscript, - conversationStore: - metadata.transcriptImport.conversationStore({ - accountHome: adoption.accountHome, - launchEnv: {} - }) ?? undefined, - transcriptPath: adoption.transcriptPath, - providerSessionId: THREAD, - workspaceCwd: fixture.rig.root, - conversationName: 'Fix the flaky login test' - }) - }) - ) - expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() - expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() - if (metadataId !== THREAD) { - expect(result).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_identity_required', - details: { reason: 'transcriptUnreadable' }, - createAttemptRefusedBeforeCommit: true - } - }) - expect(fixture.rig.store.listRecords()).toEqual([]) - expect(fixture.rig.store.listOperationRows()).toEqual([]) - expect(fixture.rig.store.listVisibleSessionIds()).toEqual([]) - return - } - expect(result.ok).toBe(true) - if (!result.ok) { - throw new Error('Real selected-account adoption failed') - } - const snapshot = await fixture.rig.host.journalSnapshot(SESSION) - expect(snapshot.items.map(({ body }) => body)).toEqual( - _kind === 'legacy' - ? [ - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Prompt' }] }, - { - kind: 'message', - role: 'system', - blocks: [{ type: 'text', text: 'Context compacted', presentation: 'compaction' }] - }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Response' }] } - ] - : [ - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'saved CLI turn' }] }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'saved CLI turn answer' }] - } - ] - ) - expect(result.value.page.items).toEqual(snapshot.items) - expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) - expect(fixture.rig.store.getRecord(SESSION)?.conversationName).toBe('Fix the flaky login test') - expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ - { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } - ]) - expect(fixture.rig.store.listVisibleSessionIds()).toEqual([SESSION]) - } -) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-fork-rewind.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-fork-rewind.test.ts deleted file mode 100644 index d41f02e2918..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-fork-rewind.test.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { catchUpClaudeTranscript } from '../../../../claude/claude-transcript-catch-up' -import { createDeferredStructuredAgentSessionEventSink } from '../../journal-ingress/structured-agent-session-event-sink' -import { testEventSinkLogging } from './structured-agent-session-logger-test-support' -import { AgentSessionJournal } from '../../../agent-session-journal/journal-store' -import { usableJournalHistoryOrigin } from '../../../agent-session-journal/context-epochs/journal-history-origin' -import { recoverStructuredRewind } from '../../rewind/structured-rewind-recovery' -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - agentJournalItemKey, - parseAgentJournalItemKey -} from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import { claudeProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { agentSessionProviderHandleChainHead } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle' -import type { AgentSessionRewindFork } from '../../../../../shared/agent-session/lifecycle/agent-session-rewind' -import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store-test-harness' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter' -import { claudeAndCodexAgents } from '../../providers/testing/structured-agent-session-adapter-router-test-support' -import type { StructuredAgentSessionEventSink } from '../../journal-ingress/structured-agent-session-event-sink' -import { StructuredAgentSessionHost } from '../structured-agent-session-host' -import { - HOST_TEST_NOW, - HOST_TEST_SESSION, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data' -import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' -import { createStructuredAgentSessionLogger } from '../structured-agent-session-logger' - -const caller = { callerKey: 'desktop' } -const SOURCE = '11111111-1111-4111-8111-111111111111' -const FORK: AgentSessionRewindFork = { - sessionId: '22222222-2222-4222-8222-222222222222', - sourceSessionId: SOURCE, - replacesSessionId: SOURCE, - materialized: true, - resumeCursor: 'fork-answer-1' -} -const key = (uuid: string) => agentJournalItemKey({ provider: 'claude', sessionId: SOURCE, uuid }) -let directory: string -let store: AgentSessionRecordStore -let host: StructuredAgentSessionHost -let sink: StructuredAgentSessionEventSink -let failAcquire: boolean -const forkForRewind = vi.fn>( - async () => ({ ok: true, fork: FORK }) -) -const nameProviderConversation = vi.fn() -const closeSession = vi.fn(async () => true) - -const attachParams = (fence: number | null) => - hostTestAttachParams(fence, { - provider: 'claude', - agent: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude' }, - providerHandle: { kind: 'claude', sessionId: SOURCE, leafUuid: 'answer-2' } - }) - -beforeEach(async () => { - resetHostTestOperationIds() - failAcquire = false - nameProviderConversation.mockClear() - forkForRewind.mockReset() - closeSession.mockClear() - forkForRewind.mockImplementation(async ({ record, beforeMessage }) => ({ - ok: true, - fork: { - ...FORK, - sessionId: - beforeMessage.uuid === 'prompt-2' ? FORK.sessionId : '33333333-3333-4333-8333-333333333333', - ...(beforeMessage.uuid === 'prompt-1' ? { resumeCursor: undefined } : {}), - replacesSessionId: agentSessionProviderHandleChainHead(record.providerHandleChain)!.handle - .nativeId - } - })) - directory = await mkdtemp(join(tmpdir(), 'orca-fork-rewind-')) - store = await openTestAgentSessionRecordStore(directory) - const adapter = startsWhenPublished( - { - supportsCreate: (_location, agent) => agent === 'claude', - supportsLocation: () => true, - acquire: async (input) => { - if (failAcquire) { - throw new Error('Claude cannot start') - } - sink = input.events! - return { - providerChildPhase: 'starting' as const, - process: { - hostId: 'local', - pid: 5001, - processStartTimeMs: HOST_TEST_NOW, - spawnToken: input.spawnToken - }, - acquisitionGeneration: 'generation-1', - link: { - linkId: `acquire-${input.fence}`, - mintedAtFence: input.fence, - observedAt: HOST_TEST_NOW, - origin: store.getRecord(HOST_TEST_SESSION)!.providerHandleChain.length - ? 'resumed' - : 'created', - handle: input.identity.providerHandle ?? claudeProviderHandle(SOURCE, 'answer-2') - } - } - }, - open: async ({ fence }) => ({ - reportedOptions: { model: '' }, - link: { - ...store.getRecord(HOST_TEST_SESSION)!.providerHandleChain.at(-1)!, - origin: 'resumed', - mintedAtFence: fence - } - }), - dispatch: async () => ({ state: 'unknown', reason: 'test' }), - cancelTurn: async () => ({ cancelled: false }), - answerPrompt: async () => {}, - setOption: async () => {}, - rewindSupport: () => ({ supported: true }), - forkForRewind, - releaseAcquisition: async () => true, - closeSession - }, - () => host - ) - const agents = claudeAndCodexAgents({ claude: adapter, codex: adapter }) - host = new StructuredAgentSessionHost({ - agents, - nameProviderConversation, - logger: createStructuredAgentSessionLogger(), - store, - adapter, - journalDatabase: openTestJournalHostDatabase(directory), - claimKeyId: 'key', - now: () => HOST_TEST_NOW, - probeOwner: async () => ({ outcome: 'exit-observed' }) - }) - expect(await host.attach(caller, attachParams(null))).toMatchObject({ ok: true }) - for (const [uuid, role] of [ - ['prompt-1', 'user'], - ['answer-1', 'assistant'], - ['prompt-2', 'user'], - ['answer-2', 'assistant'] - ] as const) { - sink.appendItem( - { provider: 'claude', sessionId: SOURCE, uuid }, - { ...hostTestMessage(uuid), role }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await host.flushStreamedEvents(HOST_TEST_SESSION) -}) - -afterEach(async () => { - vi.restoreAllMocks() - await host.flushAllStreamedEvents() - await closeTestJournalHostDatabases() - await rm(directory, { recursive: true, force: true }) -}) - -async function rewindSecondPrompt(uuid = 'prompt-2') { - const fields = { - itemId: key(uuid), - expectedEpoch: (await host.journalSnapshot(HOST_TEST_SESSION)).cursor.epoch - } - return host.rewind(caller, { - ...fields, - envelope: { - sessionId: HOST_TEST_SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.rewind', - sessionId: HOST_TEST_SESSION, - fields - }) - } - }) -} - -describe('rewinding a chat whose agent forks', () => { - it('keeps the original conversation when saving its fork fails', async () => { - const before = await host.journalSnapshot(HOST_TEST_SESSION) - forkForRewind.mockRejectedValueOnce(new Error('transcript write failed')) - await expect(rewindSecondPrompt()).rejects.toThrow('transcript write failed') - expect(await host.journalSnapshot(HOST_TEST_SESSION)).toEqual(before) - expect(store.getRecord(HOST_TEST_SESSION)?.rewind).toBeUndefined() - expect(closeSession).not.toHaveBeenCalled() - }) -}) - -it('publishes the saved copy receipt after a crash before Claude rewind completion', async () => { - const session = host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)! - const journal = session.journal - const items = journal.snapshot().items.map((item) => ({ - identity: parseAgentJournalItemKey(item.itemId)!, - body: item.body, - observedAt: item.observedAt, - ownerFence: 0, - turnScope: item.turnScope - })) - await journal.replaceEpochItems('session_created', 1, items, undefined, undefined, { - version: 1, - kind: 'native_copy', - agent: 'claude', - unit: 'claude-entry', - providerHandle: { kind: 'claude', sessionId: SOURCE, leafUuid: 'answer-2' }, - ids: ['old-covered'] - }) - forkForRewind.mockResolvedValueOnce({ - ok: true, - fork: { ...FORK, resumeCursor: 'copy-answer', coverage: ['copy-prompt', 'copy-answer'] } - }) - const crash = vi - .spyOn(journal, 'replaceEpochItems') - .mockRejectedValueOnce(new Error('crash before completion')) - await expect(rewindSecondPrompt()).rejects.toThrow('crash before completion') - crash.mockRestore() - expect(store.getRecord(HOST_TEST_SESSION)?.rewind).toMatchObject({ - phase: 'provider-succeeded', - providerFork: { coverage: ['copy-prompt', 'copy-answer'] } - }) - const projects = join(directory, 'claude-home', 'projects', '-work') - await mkdir(projects, { recursive: true }) - const nativeRows = [ - { - type: 'user', - uuid: 'copy-prompt', - parentUuid: null, - message: { role: 'user', content: 'copied prompt' } - }, - { - type: 'assistant', - uuid: 'copy-answer', - parentUuid: 'copy-prompt', - message: { - id: 'msg_copy', - role: 'assistant', - content: [{ type: 'text', text: 'copied answer' }] - } - }, - { - type: 'user', - uuid: 'CLI-during-crash', - parentUuid: 'copy-answer', - message: { role: 'user', content: 'new CLI prompt' } - }, - { - type: 'assistant', - uuid: 'CLI-answer', - parentUuid: 'CLI-during-crash', - message: { - id: 'msg_cli', - role: 'assistant', - content: [{ type: 'text', text: 'new CLI answer' }] - } - } - ].map((row) => ({ - ...row, - sessionId: FORK.sessionId, - isSidechain: false, - timestamp: '2026-11-06T12:00:00Z' - })) - await writeFile( - join(projects, `${FORK.sessionId}.jsonl`), - nativeRows.map((row) => `${JSON.stringify(row)}\n`).join('') - ) - await journal.close() - store = await openTestAgentSessionRecordStore(directory) - const recovered = new AgentSessionJournal({ - identity: { - sessionId: HOST_TEST_SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(SOURCE, 'answer-2') - }, - database: openTestJournalHostDatabase(directory) - }) - await recovered.open() - await recoverStructuredRewind( - { store, logger: createStructuredAgentSessionLogger() }, - HOST_TEST_SESSION, - recovered, - store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence - ) - const origin = usableJournalHistoryOrigin(recovered.historyOrigin()) - expect(origin).toEqual({ - version: 1, - kind: 'native_copy', - agent: 'claude', - unit: 'claude-entry', - providerHandle: { kind: 'claude', sessionId: FORK.sessionId, leafUuid: 'copy-answer' }, - ids: ['copy-prompt', 'copy-answer'] - }) - expect(store.getRecord(HOST_TEST_SESSION)?.rewind?.providerFork?.coverage).toBeUndefined() - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - deferred.bind({ - journal: recovered, - fence: store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence, - publish: () => {} - }) - try { - const open = () => - catchUpClaudeTranscript({ - sessionId: HOST_TEST_SESSION, - providerSessionId: FORK.sessionId, - leafUuid: 'copy-answer', - claudeConfigDir: join(directory, 'claude-home'), - cwd: '/work', - sink: deferred.sink - }) - expect(await open()).toBe(true) - expect(await open()).toBe(true) - const messages = recovered.snapshot().items.filter((item) => item.body.kind === 'message') - expect( - messages.flatMap((item) => (item.body.kind === 'message' ? item.body.blocks : [])) - ).toContainEqual({ type: 'text', text: 'new CLI prompt' }) - expect( - messages.filter( - (item) => - item.body.kind === 'message' && - item.body.blocks.some((block) => block.type === 'text' && block.text === 'new CLI answer') - ) - ).toHaveLength(1) - } finally { - deferred.close() - await recovered.close() - } -}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts index 0b9ed81b67b..e5635725f0d 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts @@ -108,3 +108,41 @@ it('holds a Plan choice until the goal turn ends', async () => { await eventually(() => expect(rig.dispatch).toHaveBeenCalledTimes(2)) expect(rig.dispatch.mock.calls[1]?.[0].executionOptions).toEqual(choices) }) + +it('keeps an incompatible Send-now card intact until a new turn can use its choices', async () => { + await startGoalTurn() + const choices = { model: 'gpt-ran', effort: 'high', serviceTier: 'priority' } + const queued = rig.send('Keep my selected speed', 'queue-if-active', { carried: choices }) + expect(await queued.result).toMatchObject({ ok: true, value: { queued: {} } }) + const operationId = hostTestOperationId() + for (let press = 0; press < 2; press += 1) { + expect(await rig.sendNow(queued.id, operationId)).toMatchObject({ + ok: false, + refusal: { details: { reason: 'turnActive' } } + }) + } + expect(await rig.handoff(queued.id)).toBeUndefined() + expect( + rig.host.collaboratorsForTests().sessions.get(SESSION)?.journal.queuedMessages.get(queued.id) + ).toMatchObject({ + state: 'waiting', + body: { blocks: [{ type: 'text', text: 'Keep my selected speed' }] }, + options: choices + }) + + native.activeTurnIds = new Set() + rig + .providerEvents() + .appendItem( + { provider: 'codex', threadId: THREAD, turnId: 'goal-turn', ordinal: 99 }, + { kind: 'turn', turnId: 'goal-turn', state: 'completed' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await rig.host.flushStreamedEvents(SESSION) + await eventually(async () => expect((await rig.handoff(queued.id))?.handedOverAt).toBeDefined()) + expect(rig.dispatch.mock.calls[1]?.[0].executionOptions).toEqual(choices) + expect(await rig.sendNow(queued.id, operationId)).toMatchObject({ + ok: true, + value: { submission: { queuedMessageId: queued.id } } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts deleted file mode 100644 index b26fbff2522..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Simulate crash without releasing ownership. Stop delivery/renewals and drain in-flight writes -// before closing test databases so pending producers cannot commit after cleanup. - -import type { StructuredAgentSessionHost } from '../structured-agent-session-host' - -export async function abandonStructuredAgentSessionHost( - host: StructuredAgentSessionHost -): Promise { - // Stop admission before draining to prevent new delivery steps. - host['conversationDelivery'].dispose() - host['lifetime'].dispose() - await host['runtimeState'].stopLeaseRenewal() - await host['tasks'].drainAttaches() - await Promise.all([...host['sessions'].values()].map((session) => session.journal.close())) - host['sessions'].clear() -} diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.ts index d9bd29d2c5c..511a21da204 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.ts @@ -1,5 +1,5 @@ import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../testing/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import type { AgentJournalSnapshot, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-options-read-report-freshness.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-options-read-report-freshness.test.ts new file mode 100644 index 00000000000..bb368fd89a4 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-options-read-report-freshness.test.ts @@ -0,0 +1,84 @@ +import { expect, it } from 'vitest' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import { + createQueuedMessageTestRig, + QUEUED_RIG_CALLER +} from './structured-agent-session-queued-message-rig.test-fixture' +import { appendUsageLimitedTurn } from './structured-agent-session-rewind-usage-limit.test-fixture' + +it('exports the saved selection without response or confirmed-init picker overrides', async () => { + const rig = await createQueuedMessageTestRig({ agent: 'claude' }) + try { + const fields = { key: 'model', value: 'opus[1m]' } + expect( + await rig.host.setOption(QUEUED_RIG_CALLER, { + envelope: rig.envelope(fields, 'agentSession.setOption', hostTestOperationId()), + ...fields + }) + ).toMatchObject({ ok: true }) + for (const current of [ + { model: 'claude-opus-5-5', confirmed: ['model'] }, + { model: 'claude-opus-5-5', reportedModel: 'claude-opus-4-8' } + ]) { + rig.host.deps.adapter.readOptions = async () => ({ models: [], current }) + const answer = await rig.host.readOptions(SESSION) + expect(answer.current.model).toBe('opus[1m]') + expect(answer.current.reportedModel).toBeUndefined() + } + } finally { + await rig.dispose() + } +}) + +it.each([ + ['new pick', QUEUED_RIG_CALLER, ['sonnet'], 'sonnet'], + ['pick back', QUEUED_RIG_CALLER, ['sonnet', 'opus[1m]'], 'opus[1m]'], + [ + 'legacy empty no-op', + { ...QUEUED_RIG_CALLER, readsOptionsWithoutModel: false }, + [''], + 'opus[1m]' + ] +] as const)( + 'projects the latest saved choice through a %s while recovery choices load', + async (_, caller, models, expectedModel) => { + const rig = await createQueuedMessageTestRig({ agent: 'claude' }) + try { + const pick = async (value: string) => { + const fields = { key: 'model', value } + return rig.host.setOption(caller, { + envelope: rig.envelope(fields, 'agentSession.setOption', hostTestOperationId()), + ...fields + }) + } + expect(await pick('opus[1m]')).toMatchObject({ ok: true }) + rig.host.deps.adapter.readOptions = async () => ({ + models: [], + current: { model: 'claude-opus-5-5', reportedModel: 'claude-opus-4-8' } + }) + const journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await appendUsageLimitedTurn(journal, NOW, 'quota') + const recovering = Promise.withResolvers() + const released = Promise.withResolvers() + rig.host.deps.resolveLaunchEnv = () => { + recovering.resolve() + return released.promise + } + const answer = rig.host.readOptions(SESSION) + await recovering.promise + for (const model of models) { + expect(await pick(model)).toMatchObject({ ok: true }) + } + released.resolve(undefined) + const { current } = await answer + expect(current.model).toBe(expectedModel) + expect(current.reportedModel).toBeUndefined() + } finally { + await rig.dispose() + } + } +) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-telemetry.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-telemetry.test.ts deleted file mode 100644 index 174e754f079..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-telemetry.test.ts +++ /dev/null @@ -1,250 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { RpcContext } from '../../../../runtime/rpc/core' -import type { RpcCallerIdentity } from '../../../../runtime/rpc/rpc-caller-identity' -import { structuredCallerFor } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate' -import { createTestParams } from './structured-agent-session-create-test-fixture' -import { isTelemetryInitialized, track } from '../../../../telemetry/client' -import { subscribeStructuredChatTelemetry } from '../../../../telemetry/structured-chat-dispatch' -import type { StructuredChatTelemetryEvent } from '../../../../../shared/structured-chat-dispatch-telemetry' -import { - createQueuedMessageTestRig, - type QueuedMessageTestRig -} from './structured-agent-session-queued-message-rig.test-fixture' -import { eventually } from './structured-agent-session-queued-message-rig-provider.test-fixture' -import { openRigTurnFor } from './structured-agent-session-queued-rig-turn.test-fixture' -import { - HOST_TEST_SESSION, - HOST_TEST_THREAD, - hostTestMessage, - hostTestOperationId, - hostTestSendParams -} from './structured-agent-session-host-test-data' - -vi.mock('../../../../telemetry/client', () => ({ - track: vi.fn(), - isTelemetryInitialized: vi.fn(() => true) -})) - -let rig: QueuedMessageTestRig -const prompts = () => - vi.mocked(track).mock.calls.filter(([name]) => name === 'native_chat_prompt_submitted') - -function transportCaller( - caller?: RpcCallerIdentity, - clientKind?: 'mobile' | 'runtime', - pairedDeviceParentId?: string -) { - const context: Partial = { caller, clientKind, pairedDeviceParentId } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: caller derivation reads only transport identity fields supplied here. - return structuredCallerFor(context as RpcContext) -} -const desktop = () => transportCaller({ kind: 'desktop' }) - -beforeEach(async () => { - vi.clearAllMocks() - vi.mocked(isTelemetryInitialized).mockReturnValue(true) - rig = await createQueuedMessageTestRig() -}) -afterEach(async () => rig.dispose()) - -it('counts a desktop prompt at provider acceptance, excluding handover, rejection and replay', async () => { - const rejected = { ...hostTestSendParams('private rejected prompt'), userSend: true as const } - await rig.host.send(desktop(), rejected) - const refused = rejected.envelope.clientOperationId - await eventually(async () => expect((await rig.submission(refused))?.handedOverAt).toBeDefined()) - expect(prompts()).toEqual([]) - await rig.settleRejected(refused, 'Provider refused this prompt') - expect(prompts()).toEqual([]) - - const params = { ...hostTestSendParams('private accepted prompt'), userSend: true as const } - await rig.host.send(desktop(), params) - await eventually(async () => - expect((await rig.submission(params.envelope.clientOperationId))?.handedOverAt).toBeDefined() - ) - expect(prompts()).toEqual([]) - await rig.settleAccepted(params.envelope.clientOperationId, 'accepted-desktop') - const expected = [ - ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'desktop' }] - ] - expect(prompts()).toEqual(expected) - - await rig.host.send(desktop(), params) - expect(prompts()).toEqual(expected) -}) - -it('keeps the phone provenance through automatic queued handoff and ignores withdrawn cards', async () => { - const working = await rig.workingSend() - const caller = transportCaller({ kind: 'paired-device', deviceId: 'phone-1' }, 'mobile') - const queue = async (text: string) => { - const id = hostTestOperationId() - const fields = { body: hostTestMessage(text), delivery: 'queue-if-active' as const } - const answer = await rig.host.send(caller, { - envelope: rig.envelope(fields, 'agentSession.send', id), - ...fields, - userSend: true - }) - expect(answer).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) - return id - } - const withdrawn = await queue('private withdrawn phone prompt') - await rig.deleteQueued(withdrawn) - const waiting = await queue('private queued phone prompt') - expect(prompts()).toEqual([]) - - await rig.settleRejected(working, 'End the earlier request without accepting it') - await eventually(async () => expect((await rig.handoff(waiting))?.handedOverAt).toBeDefined()) - expect(prompts()).toEqual([]) - const handedOver = await rig.handoffId(waiting) - await rig.settleAccepted(handedOver, 'accepted-phone') - expect(prompts()).toEqual([ - ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'mobile' }] - ]) - expect((await rig.host.history({ sessionId: HOST_TEST_SESSION, direction: 'tail' })).ok).toBe( - true - ) - expect(prompts()).toEqual([ - ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'mobile' }] - ]) -}) - -it('does not treat provider-accepted commands or internal messages as user prompts', async () => { - const fields = { command: 'compact' as const } - const commandId = hostTestOperationId() - expect( - await rig.host.conversationCommand(desktop(), { - envelope: rig.envelope(fields, 'agentSession.conversationCommand', commandId), - ...fields - }) - ).toMatchObject({ ok: true }) - await eventually(async () => - expect( - ((await rig.submission(commandId)) ?? (await rig.handoff(commandId)))?.dispatchState - ).toBe('accepted') - ) - rig.finishCompact() - expect(prompts()).toEqual([]) - - const internal = rig.send('private unattended agent message', undefined, { internal: true }) - await internal.result - await eventually(async () => - expect((await rig.submission(internal.id))?.handedOverAt).toBeDefined() - ) - await rig.settleAccepted(internal.id, 'accepted-internal') - expect(prompts()).toEqual([]) -}) - -it('excludes CLI and unproven runtime callers even when their send uses userSend', async () => { - for (const caller of [ - transportCaller({ kind: 'local-cli' }), - transportCaller({ kind: 'local-cli' }, 'runtime'), - transportCaller(undefined, 'runtime'), - transportCaller() - ]) { - const params = { ...hostTestSendParams('private automated prompt'), userSend: true as const } - await rig.host.send(caller, params) - await eventually(async () => - expect((await rig.submission(params.envelope.clientOperationId))?.handedOverAt).toBeDefined() - ) - await rig.settleAccepted(params.envelope.clientOperationId, params.envelope.clientOperationId) - } - expect(prompts()).toEqual([]) -}) - -it('counts the trusted desktop opening message only after its provider accepts it', async () => { - const sessionId = 'new-chat-with-first-prompt' - const firstMessage = { - clientMessageId: hostTestOperationId(), - body: hostTestMessage('private opening prompt') - } - const params = createTestParams(firstMessage, {}, sessionId) - expect(await rig.host.create(desktop(), params, { firstMessage })).toMatchObject({ ok: true }) - await eventually(async () => - expect( - (await rig.host.journalSnapshot(sessionId)).submissions.find( - (entry) => entry.clientMessageId === firstMessage.clientMessageId - )?.handedOverAt - ).toBeDefined() - ) - expect(prompts()).toEqual([]) - await rig.host.settleLateDispatch({ - sessionId, - clientMessageId: firstMessage.clientMessageId, - providerIdentity: { - provider: 'codex', - threadId: HOST_TEST_THREAD, - turnId: 'opening-turn', - ordinal: 0 - } - }) - expect(prompts()).toEqual([ - ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'desktop' }] - ]) -}) - -it('relays only provider acceptance with the authenticated desktop or delegated phone owner', async () => { - vi.mocked(isTelemetryInitialized).mockReturnValue(false) - const events: { event: StructuredChatTelemetryEvent; owner: string }[] = [] - const unsubscribe = subscribeStructuredChatTelemetry((event, owner) => - events.push({ event, owner }) - ) - try { - const caller = transportCaller({ kind: 'paired-device', deviceId: 'desktop-a' }, 'runtime') - const desktopSend = { ...hostTestSendParams('private desktop prompt'), userSend: true as const } - await rig.host.send(caller, desktopSend) - await eventually(async () => - expect( - (await rig.submission(desktopSend.envelope.clientOperationId))?.handedOverAt - ).toBeDefined() - ) - expect(events).toEqual([]) - - const queuedId = hostTestOperationId() - const fields = { - body: hostTestMessage('private phone prompt'), - delivery: 'queue-if-active' as const - } - const phone = transportCaller( - { kind: 'paired-device', deviceId: 'delegated-phone' }, - 'mobile', - 'desktop-a' - ) - await rig.host.send(phone, { - envelope: rig.envelope(fields, 'agentSession.send', queuedId), - ...fields, - userSend: true - }) - expect(events).toEqual([]) - await rig.settleAccepted( - desktopSend.envelope.clientOperationId, - `of-${desktopSend.envelope.clientOperationId}` - ) - await rig.host.send(caller, desktopSend) - await openRigTurnFor(rig, desktopSend.envelope.clientOperationId, 'completed', 'success') - await eventually(async () => expect((await rig.handoff(queuedId))?.handedOverAt).toBeDefined()) - await rig.settleAccepted(await rig.handoffId(queuedId), 'remote-phone-turn') - expect(events).toEqual([ - { - owner: 'desktop-a', - event: { - type: 'structuredChatPromptAccepted', - id: expect.any(String), - agent_kind: 'codex', - client: 'desktop' - } - }, - { - owner: 'desktop-a', - event: { - type: 'structuredChatPromptAccepted', - id: expect.any(String), - agent_kind: 'codex', - client: 'mobile' - } - } - ]) - expect(events[0].event.id).not.toBe(events[1].event.id) - expect(prompts()).toEqual([]) - } finally { - unsubscribe() - } -}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-published-bytes.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-published-bytes.test.ts index deeb1e2e451..f31c6183524 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-published-bytes.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-published-bytes.test.ts @@ -1,16 +1,12 @@ import { afterEach, beforeEach, expect, it } from 'vitest' -import { agentSessionRefusalNotice } from '../../../../../shared/agent-session/failures/agent-session-refusal-notice' -import '../../../../../shared/rpc-contract/structured-agent-session-params' -import { MAX_PROMPT_BYTES } from '../../../../../shared/rpc-contract/structured-agent-session-message-params' -import { - QUEUED_MESSAGES_PERSON_RESERVE_BYTES, - QUEUED_MESSAGES_PUBLISHED_MAX_BYTES -} from '../../delivery/structured-agent-session-queued-published-bytes' + +import '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' + +import { QUEUED_MESSAGES_PUBLISHED_MAX_BYTES } from '../../delivery/structured-agent-session-queued-published-bytes' import { createQueuedMessageTestRig, type QueuedMessageTestRig } from './structured-agent-session-queued-message-rig.test-fixture' -import { hostTestMessage } from './structured-agent-session-host-test-data' let rig: QueuedMessageTestRig @@ -20,12 +16,6 @@ beforeEach(async () => { afterEach(() => rig.dispose()) -function textOfBytes(bytes: number, blocksOnly = false): string { - const empty = hostTestMessage('') - const overhead = Buffer.byteLength(JSON.stringify(blocksOnly ? empty.blocks : empty), 'utf8') - return 'x'.repeat(bytes - overhead) -} - it('refuses a draft past the published-bytes bound in words that say what to do', async () => { await rig.workingSend() const text = 'x'.repeat(Math.ceil(QUEUED_MESSAGES_PUBLISHED_MAX_BYTES * 0.6)) @@ -38,29 +28,10 @@ it('refuses a draft past the published-bytes bound in words that say what to do' throw new Error('expected a refusal') } expect(refused.refusal.details).toEqual({ reason: 'queueTooLarge' }) - expect(refused.refusal.message).not.toMatch(/frame|publish/i) - expect(agentSessionRefusalNotice(refused.refusal, 'composer-send')).toBe( - 'Too much text is waiting in the queue. Your message was not sent. Delete a queued message, or wait for one to go through, then try again.' - ) + expect(await rig.deleteQueued(first.value.queued.messageId)).toMatchObject({ ok: true }) expect(await rig.send(text, 'queue-if-active').result).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) }) - -it("leaves room for the person's largest message however much other agents queue", async () => { - await rig.workingSend() - const agentRoom = QUEUED_MESSAGES_PUBLISHED_MAX_BYTES - QUEUED_MESSAGES_PERSON_RESERVE_BYTES - expect( - await rig.send(textOfBytes(agentRoom), 'queue-if-active', { internal: true }).result - ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) - const agentRefused = await rig.send('one more task', 'queue-if-active', { internal: true }).result - expect(agentRefused).toMatchObject({ - ok: false, - refusal: { details: { reason: 'queueTooLarge' } } - }) - expect( - await rig.send(textOfBytes(MAX_PROMPT_BYTES, true), 'queue-if-active').result - ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) -}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts index 2532613fed9..29181aacbf0 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts @@ -32,7 +32,9 @@ async function queuedDraft(text: string): Promise { describe('a repeated draft press under a fresh operation id', () => { it('Send-now pressed twice sends the draft once and answers both presses with its submission', async () => { - await openRigTurnFor(rig, await rig.workingSend()) + const opening = await rig.workingSend() + await rig.settleAccepted(opening, 'opening') + await openRigTurnFor(rig, opening) const draftId = await queuedDraft('send me now') const [first, second] = await Promise.all([rig.sendNow(draftId), rig.sendNow(draftId)]) expect(first).toMatchObject({ ok: true, replayed: false }) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts index 56fc8f54434..7368ae644c0 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts @@ -135,10 +135,11 @@ describe("Stop's event", () => { it('a stopped unconfirmed hand-off stays ordinary while Resume drains waiting cards', async () => { const working = await rig.workingSend() await openRigTurnFor(rig, working) + await rig.settleAccepted(working, 'stopped') const steered = await queuedDraft('sent now into the turn') const opening = await queuedDraft('opens its own turn') const last = await queuedDraft('waiting behind them') - await rig.sendNow(steered) + expect(await rig.sendNow(steered)).toMatchObject({ ok: true }) await eventually(async () => expect((await rig.handoff(steered))?.handedOverAt).toBeDefined()) const steer = await rig.handoffId(steered) // Codex ends the stopped turn without taking the steer: the agent may have it, nothing proves @@ -153,7 +154,6 @@ describe("Stop's event", () => { }, via: 'steer' }) - await rig.settleAccepted(working, 'stopped') await openRigTurnFor(rig, working, 'interrupted') await expectHeld('stopped', opening, last) expect(await rig.drafts()).toEqual([ diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-callers.test-support.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-callers.test-support.ts deleted file mode 100644 index fedfa383bfd..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-callers.test-support.ts +++ /dev/null @@ -1,302 +0,0 @@ -import { join } from 'node:path' -import { expect, vi } from 'vitest' -import { Store } from '../../../../persistence/loading-store/store' -import { ProfileStateSqliteAuthority } from '../../../../persistence/profile-state/profile-state-sqlite-authority' -import { getAppEnvironment, setAppEnvironment } from '../../../../../shared/app-environment' -import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { claudeProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import { agentJournalSubmissionKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalMessageItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { OrchestrationSessionCaller } from '../../../../runtime/orchestration/addressing/orchestration-caller-identity' -import { resolveOrcaSessionParty } from '../../../../runtime/orchestration/addressing/orchestration-party' -import { ReceivingRuntime } from './structured-agent-session-receiving-runtime.test-support' -import { eraseRpcMethods, isStreamingMethod } from '../../../../runtime/rpc/core' -import { STRUCTURED_AGENT_SESSION_METHODS } from '../../../../runtime/rpc/methods/structured-sessions/structured-agent-session' -import { ORCHESTRATION_METHODS } from '../../../../runtime/rpc/methods/orchestration/orchestration' -import { resolveWorkerStartRun } from '../../../../runtime/rpc/methods/orchestration/worker/worker-start-authority' -import { resolveDispatchCreator } from '../../../../runtime/rpc/methods/orchestration/runs/dispatch-creator' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../../../../runtime/orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { structuredWorkerOwesWork } from '../../../../runtime/orchestration/terminal-authority/structured-sessions/structured-worker-custody' -import { createRestTestRig, REST_TEST_CALLER } from './structured-agent-session-rest-test-rig' -import { - hostTestAttachParams, - hostTestMessage, - hostTestOperationId -} from './structured-agent-session-host-test-data' -import { setStructuredAgentSessionHost } from '../structured-agent-session-registry' -import { createClaudeAccountRouting } from './structured-agent-session-claude-account-routing.test-support' -import type { StructuredAgentSessionEventSink } from '../../journal-ingress/structured-agent-session-event-sink' - -export const PARENT = testOrcaSessionId('cfe50e96-3a95-4353-9cdc-7a652779c6e8') -export const WORKER = testOrcaSessionId('4c1b8d7a-975c-4984-a2e4-8149fdd4177a') - -/** The registered attach path reads launch defaults from the runtime's profile store. */ -function receivingRuntimeStore(root: string) { - return new Store({ - dataFile: join(root, 'runtime-state.json'), - profileStateAuthority: new ProfileStateSqliteAuthority( - join(root, 'runtime-profile.db'), - 'receiving' - ) - }) -} - -/** Script only external adapter IO (the Claude process and its transcripts); the account router, - * Claude launch resolution, reservation, proof, journals, RPC and native transactions are real. */ -export async function createReceivingCallerFixture() { - const previousEnvironment = getAppEnvironment() - let runtime: ReceivingRuntime | undefined - const routing = createClaudeAccountRouting() - const rig = await createRestTestRig({ - // Production wiring: an assigned worker's own open Dispatch keeps its process. - hasOpenDispatch: (record) => - structuredWorkerOwesWork(runtime?.getOrchestrationDbIfAvailable() ?? null, record), - launchAccountHome: routing.launchAccountHome - }) - const accounts = routing.install(rig.root, () => rig.store) - setAppEnvironment({ - ...previousEnvironment, - getPath: (name) => (name === 'userData' ? rig.root : previousEnvironment.getPath(name)) - }) - const runtimeStore = receivingRuntimeStore(rig.root) - const service = new ReceivingRuntime(runtimeStore) - runtime = service - // Scheduling is externally controlled; nested contracts drive the production pointer park/wake. - const nudges = vi.spyOn(service, 'notifyMessageArrived').mockImplementation(() => {}) - rig.host.deps.adapter.supportsLocation = (location) => - location.executionHostId === 'local' && !location.wslDistro - setStructuredAgentSessionHost(rig.host) - const sinks = new Map() - let generation = 0 - rig.adapter.acquire.mockImplementation(async (input) => { - // Production launch resolution picks the account, as the Claude adapter's acquisition does. - const launched = await accounts.launch(input) - if (input.events) { - sinks.set(input.identity.sessionId, input.events) - } - return { - acquisitionGeneration: `caller-generation-${++generation}`, - ...launched, - process: { - hostId: 'local', - pid: 4242, - processStartTimeMs: 1_700_000_000_000, - spawnToken: input.spawnToken - }, - link: { - linkId: `caller-link-${generation}`, - // A chat that has answered has a leaf, which a resume elsewhere is checked against. - handle: claudeProviderHandle(`provider-${input.identity.sessionId}`, 'leaf-1'), - origin: rig.store.getRecord(input.identity.sessionId)?.providerHandleChain.length - ? 'resumed' - : 'created', - mintedAtFence: input.fence, - observedAt: rig.clock.now - } - } - }) - rig.adapter.dispatch.mockImplementation(async (input) => ({ - state: 'accepted', - providerIdentity: { - provider: 'claude', - sessionId: `provider-${input.sessionId}`, - uuid: `echo-${input.clientMessageId}` - } - })) - vi.spyOn(service, 'ensureStructuredAgentSessionHost').mockResolvedValue() - const params = (id = PARENT) => - hostTestAttachParams(rig.store.getRecord(id)?.lease.runtimeFence ?? null, { - envelope: { - sessionId: id, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: rig.store.getRecord(id)?.lease.runtimeFence ?? null, - payloadFingerprint: '' - }, - provider: 'claude', - agent: 'claude', - accountHome: accounts.homeA, - providerHandle: { kind: 'claude', sessionId: `provider-${id}`, leafUuid: null } - }) - const ensure = async (id = PARENT) => { - const method = eraseRpcMethods(STRUCTURED_AGENT_SESSION_METHODS).find( - (m) => m.name === 'agentSession.ensure' - ) - if (!method?.params || isStreamingMethod(method)) { - throw new Error('registered ensure missing') - } - return method.handler(method.params.parse(params(id)), { runtime: service }) - } - const call = async ( - name: string, - values: Record, - caller?: OrchestrationSessionCaller - ) => { - const method = eraseRpcMethods(ORCHESTRATION_METHODS).find((m) => m.name === name) - if (!method?.params || isStreamingMethod(method)) { - throw new Error(`registered method missing: ${name}`) - } - return method.handler(method.params.parse(values), { - runtime: service, - ...(caller ? { orchestrationCaller: caller } : {}) - }) - } - const caller = (id = PARENT): OrchestrationSessionCaller => ({ - ...resolveOrcaSessionParty(id, service.getExistingOrchestrationDb()), - sessionId: id, - workspaceId: 'workspace-1' - }) - const accept = async (text: string, body: AgentJournalMessageItem = hostTestMessage(text)) => { - const id = hostTestOperationId() - const result = await rig.host.send(REST_TEST_CALLER, { - body, - envelope: { - sessionId: PARENT, - clientOperationId: id, - expectedRuntimeFence: rig.store.requireWritableRecord(PARENT).lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: PARENT, - fields: { body } - }) - } - }) - expect(result.ok).toBe(true) - return id - } - const send = async (text: string, body: AgentJournalMessageItem = hostTestMessage(text)) => { - const id = await accept(text, body) - await vi.waitFor(() => - expect( - rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal.submission(id)?.dispatchState - ).toBe('accepted') - ) - return id - } - const turn = async (id: string, state: 'running' | 'completed', userId = id) => { - const sink = sinks.get(PARENT) - if (!sink) { - throw new Error('parent was not actually acquired') - } - sink.appendItem( - { provider: 'claude', sessionId: `provider-${PARENT}`, uuid: `turn-${id}` }, - { - kind: 'turn', - turnId: `turn-${id}`, - state, - userItemId: agentJournalSubmissionKey(userId), - ...(state === 'completed' ? { outcome: 'success', completedAt: rig.clock.now } : {}) - }, - { turnScope: { kind: 'thread' } } - ) - await rig.host.flushStreamedEvents(PARENT) - } - const createWorker = async (id: typeof WORKER, creator = PARENT) => { - const from = caller(creator) - const taskSpec = `work for ${id}` - const { bindRun, helperCreator } = resolveWorkerStartRun(service, { - coordinator: from, - from: from.address, - callerSession: from, - runId: undefined, - objective: taskSpec, - taskReferences: [] - }) - const { run } = bindRun() - const db = service.getOrchestrationDb() - const started = db.createStartingWorkerDispatch({ - creator: resolveDispatchCreator(service, from.address, from), - maxDepth: 9, - requiredCreatorDispatchId: helperCreator?.id, - taskSpec, - taskParentId: helperCreator?.task_id, - taskRunId: run.id, - taskCreatedByRunGeneration: run.consumer_generation, - startOptions: {}, - runtimeEpoch: service.getRuntimeId() - }) - const handle = mintStructuredWorkerHandle() - const paneKey = mintStructuredWorkerPaneKey(id) - const processIncarnation = structuredWorkerProcessIncarnation(id) - structuredWorkerIdentities.register({ - handle, - paneKey, - processIncarnation, - sessionId: id, - agent: 'claude', - worktreeId: 'workspace-1', - hostScope: { kind: 'local', hostId: 'local' } - }) - await ensure(id) - await rig.store.setSessionTabVisibility(id, true) - db.prepareStartingWorkerAuthority({ - dispatchId: started.dispatch.id, - handle, - paneKey, - processIncarnation, - worktreeId: 'workspace-1', - setupState: 'not_applicable', - effects: [{ kind: 'terminal', action: 'created', id: handle }], - terminalOwnership: 'created' - }) - db.markWorkerDispatchReady(started.dispatch.id) - return { ...started, handle, paneKey, processIncarnation, sessionId: id } - } - const report = (worker: Awaited>) => - call( - 'orchestration.send', - { - from: worker.handle, - type: 'worker_done', - subject: 'completed', - payload: JSON.stringify({ - taskId: worker.task.id, - dispatchId: worker.dispatch.id, - outcome: 'succeeded' - }) - }, - caller(worker.sessionId) - ) - return { - rig, - runtime: service, - params, - ensure, - call, - caller, - send, - accept, - turn, - createWorker, - report, - sinks, - nudges, - ...accounts, - selectB: () => accounts.select('b'), - found: async () => { - await ensure() - await rig.store.setSessionTabVisibility(PARENT, true) - expect(rig.store.requireWritableRecord(PARENT).acquiredAccount).toBeDefined() - }, - dispose: async ( - stopHost = () => rig.host.flushAllStreamedEvents(), - disposeRig = () => rig.dispose() - ) => { - service.stopOrchestrationFederationRelay() - setStructuredAgentSessionHost(null) - accounts.uninstall() - structuredWorkerIdentities.clear() - await stopHost() - service.getOrchestrationDbIfAvailable()?.close() - await runtimeStore.freezeWritesAsync() - await disposeRig() - setAppEnvironment(previousEnvironment) - vi.restoreAllMocks() - } - } -} diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-cancellation.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-cancellation.test.ts deleted file mode 100644 index 19202f2adbf..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-cancellation.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { acquiredAgentSessionAccount } from '../../../../../shared/agent-session/lifecycle/agent-session-acquired-account' -import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import { AgentSessionJournal } from '../../../agent-session-journal/journal-store' -import { REST_TEST_CALLER } from './structured-agent-session-rest-test-rig' -import { hostTestMessage, hostTestOperationId } from './structured-agent-session-host-test-data' -import { - createReceivingCallerFixture, - PARENT -} from './structured-agent-session-receiving-callers.test-support' - -it('finishes an owned ordinary open but direct cancellation publishes no child', async () => { - const f = await createReceivingCallerFixture() - const opened = Promise.withResolvers() - const release = Promise.withResolvers() - try { - await f.found() - await f.rig.host.close(PARENT, 'evict') - f.selectB() - const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT)) - const open = AgentSessionJournal.prototype.open - vi.spyOn(AgentSessionJournal.prototype, 'open').mockImplementationOnce(async function ( - this: AgentSessionJournal - ) { - opened.resolve() - await release.promise - return open.call(this) - }) - f.rig.adapter.acquire.mockClear() - const result = f.ensure().then( - (value) => ({ value }), - (error: unknown) => ({ error }) - ) - await opened.promise - f.rig.host - .collaboratorsForTests() - .runtimeState.acquireAborts.abort(PARENT, 'cancelled while opening') - release.resolve() - await result - expect(f.rig.host.hasSession(PARENT)).toBe(true) - expect(f.rig.host.childAccountHome(PARENT)).toBeUndefined() - expect(f.rig.adapter.acquire).not.toHaveBeenCalled() - expect(acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe).toEqual( - original?.recipe - ) - expect(f.rig.store.requireWritableRecord(PARENT).lease.claimStatus).toBe('released') - } finally { - release.resolve() - await f.dispose() - } -}) - -it('ensure and ordinary send share the journal refusal; retry retains history without a failed spawn', async () => { - const f = await createReceivingCallerFixture() - try { - await f.found() - await f.rig.host.close(PARENT, 'evict') - const before = f.rig.store.requireWritableRecord(PARENT) - const rows = f.rig.store.listOperationRows() - const open = vi - .spyOn(AgentSessionJournal.prototype, 'open') - .mockRejectedValue(new Error('fixture journal IO unavailable')) - f.rig.adapter.acquire.mockClear() - const ensured = await f.ensure() - expect(ensured).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_journal_unreadable', - details: { reason: 'journalUnavailable' } - } - }) - const body = hostTestMessage('retryable send') - const sent = await f.rig.host.send(REST_TEST_CALLER, { - body, - envelope: { - sessionId: PARENT, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: before.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: PARENT, - fields: { body } - }) - } - }) - expect(sent).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_journal_unreadable', - details: { reason: 'journalUnavailable' } - } - }) - expect(f.rig.adapter.acquire).not.toHaveBeenCalled() - expect(f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence).toBe( - before.lease.runtimeFence - ) - expect(acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe).toEqual( - acquiredAgentSessionAccount(before)?.recipe - ) - expect(f.rig.store.listOperationRows()).toEqual(rows) - open.mockRestore() - expect(await f.ensure()).toMatchObject({ ok: true }) - } finally { - await f.dispose() - } -}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-runtime.test-support.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-runtime.test-support.ts deleted file mode 100644 index 313790ce23d..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-receiving-runtime.test-support.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { OrcaRuntimeService } from '../../../../runtime/orca-runtime' - -export class ReceivingRuntime extends OrcaRuntimeService { - override getOrchestrationDbIfAvailable() { - return super.getOrchestrationDbIfAvailable() - } - mailTarget(handle: string) { - return this.resolveStructuredMailboxTarget(handle) - } -} diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-host-test-support.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-host-test-support.ts index 3f4ebf6863e..49f2be02878 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-host-test-support.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-host-test-support.ts @@ -55,6 +55,12 @@ const openFailures = new Map void>() const endings = new Map() const openGates = new Map void>() +let hostNow = NOW + +/** Moves the host's wall clock, as a sleep does, without running any timer. */ +export function advanceHostWallClock(ms: number): void { + hostNow += ms +} export async function proveOpen(model = 'default'): Promise { const generation = `generation-${acquire.mock.calls.length}` @@ -143,7 +149,7 @@ async function startHost({ startupLimits, supportsGoals }: StartupHostOptions = mintSpawnToken: () => `spawn-${acquire.mock.calls.length}`, idleSweep: { intervalMs: 60 * 60_000, idleMs: () => 60 * 60_000 }, ...(startupLimits === undefined ? {} : { startupLimits }), - now: () => NOW + now: () => hostNow }) const handleEvent = host.handleAdapterEvent.bind(host) host.handleAdapterEvent = async (event) => { @@ -186,6 +192,7 @@ export function registerStartupAttemptHostTests(): void { }) root = await mkdtemp(join(tmpdir(), 'orca-startup-attempt-')) resetHostTestOperationIds() + hostNow = NOW providerStarted.mockReset() recordLiveListing.mockReset() openFailures.clear() diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-reports.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-reports.test.ts index 2c2842d5ef1..faf4eecc3bd 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-reports.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-reports.test.ts @@ -5,6 +5,7 @@ import { } from './structured-agent-session-host-test-data' import { acquire, + advanceHostWallClock, eventually, heldBehindStart, host, @@ -41,3 +42,14 @@ describe('what a started child reports', () => { expect(store.getRecord(SESSION)?.options).toEqual({ model: 'picked' }) }) }) + +describe('a start across a sleep', () => { + it('lets a start that a sleep held past the idle window finish and deliver its message', async () => { + await restartWith(publishFirst) + const id = await heldBehindStart('hello') + advanceHostWallClock(2 * 60 * 60_000) + await host.collaboratorsForTests().lifetime.idleSweep.tick() + await proveOpen() + await eventually(async () => expect((await submission(id))?.dispatchState).toBe('accepted')) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-deadline.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-deadline.test-fixture.ts index 83958d70db0..34767bedf9c 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-deadline.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-deadline.test-fixture.ts @@ -1,5 +1,5 @@ import { expect, vi } from 'vitest' -import { CLAUDE_STOP_GRACE_MS } from '../../../../claude/claude-request-end-wait' +import { CLAUDE_STOP_GRACE_MS } from '../../../../claude/structured/turns/claude-request-end-wait' import type { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' import type { fakeClaude, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-event-entries.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-event-entries.test.ts index eef9bbc0295..21aae6cadd2 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-event-entries.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stop-event-entries.test.ts @@ -53,6 +53,12 @@ function stopEvents(): StoredStopEvent[] { } return [...events.values()] } +/** As the startup ceiling expiring the start in flight. */ +async function failStartAtCeiling(): Promise { + const { lifetime, serialize, sessions } = rig.host.collaboratorsForTests() + lifetime.stopStartingChild(SESSION, sessions.get(SESSION)?.child ?? null) + await serialize(SESSION, async () => {}) +} async function queuedDraft(text: string) { const queued = await rig.send(text, 'queue-if-active').result if (!queued.ok || !('queued' in queued.value)) { @@ -124,7 +130,7 @@ it('a failed personal start retains Stop after its returned input is deleted', a expect(rig.host.collaboratorsForTests().sessions.get(SESSION)?.child?.phase).toBe('starting') ) - await rig.host.collaboratorsForTests().lifetime.idleSweep.tick() + await failStartAtCeiling() await personal.result expect(stopEvents().map((event) => event.reason)).toEqual(['user-stop', 'host-stop']) @@ -169,7 +175,7 @@ it('an unattended failed start preserves a manual Stop without returning the mai expect(rig.host.collaboratorsForTests().sessions.get(SESSION)?.child?.phase).toBe('starting') ) - await rig.host.collaboratorsForTests().lifetime.idleSweep.tick() + await failStartAtCeiling() await mail.result expect(journal().queuedMessages.get(mail.id)).toBeNull() diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts index 3bd4356bc7a..5e160b2cf1f 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts @@ -75,6 +75,15 @@ async function heldChat() { launchUnder: (next: UsageLimitAccountScope) => { attributed = next }, + /** The cut's runtime launched on account A; a start of this chat would now launch on `path`. */ + switchAccount: async (path: string) => { + const fence = journal.itemFence(cut.turnItemId)! + await current.store.transitionHandoff(SESSION, (record) => ({ + ...record, + launchedAccount: { fence, accountHome: { variable: 'CODEX_HOME', path: '/homes/a' } } + })) + current.host.deps.launchAccountHome = async () => ({ variable: 'CODEX_HOME', path }) + }, setEnabled: (next: boolean) => { enabled = next }, @@ -134,6 +143,33 @@ it('holds again on spending inside the grace, and leaves an unknown reset once r await settleOne(await refused.pass(room + 15_000, (now) => weekly(0, null, now))) }) +it('continues before the cut resets once the chat would start on another account with room', async () => { + const chat = await heldChat() + const start = chat.cut.resetsAt - 60_000 + await chat.switchAccount('/homes/b') + expect(await chat.pass(start + 5_000, (now) => weekly(0, null, now))).toEqual([]) + expect(chat.state()).toMatchObject({ state: 'scheduled', continueAt: start + 5_000 }) + await settleOne(await chat.pass(start + 20_000, (now) => weekly(0, null, now))) +}) + +it('keeps the new account spent from a reading before the switch until a later one shows room', async () => { + const chat = await heldChat() + const start = chat.cut.resetsAt - 60_000 + const newAccountReset = start + 2 * HOUR + await chat.switchAccount('/homes/b') + expect(await chat.pass(start + 5_000, () => weekly(100, newAccountReset, start + 1_000))).toEqual( + [] + ) + expect(chat.state()).toMatchObject({ continueAt: newAccountReset }) + expect(await chat.pass(start + 10 * 60_000, () => weekly(100, newAccountReset, start))).toEqual( + [] + ) + const room = start + 20 * 60_000 + expect(await chat.pass(room, (now) => weekly(0, null, now))).toEqual([]) + expect(chat.state()).toMatchObject({ continueAt: room }) + await settleOne(await chat.pass(room + 15_000, (now) => weekly(0, null, now))) +}) + it('retires a hold when the launch moves to billing the reading does not describe', async () => { const chat = await heldChat() const weeklyReset = chat.cut.resetsAt + 3 * HOUR diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command-child-work.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command-child-work.test.ts index 2ab543a8747..c6d1b25cb3a 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command-child-work.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-conversation-command-child-work.test.ts @@ -1,31 +1,15 @@ -import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionBackgroundTaskState } from '../../../../../shared/agent-session/agent-session-background-task-wire' -import type { AgentChildWorkView } from '../../../../../shared/agent-status/child-work/agent-status-child-work-view' +import { beforeEach, expect, it, vi, type Mock } from 'vitest' import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter' -import { structuredAgentSessionCommandTurn } from '../../../../../shared/agent-session/view/structured-agent-session-command-turn-identity' import { attach, CALLER, envelope, - hostTestState, - serveHostTestChildWork + hostTestState } from './structured-agent-session-host-test-harness' -import { - HOST_TEST_NOW, - HOST_TEST_SESSION, - hostTestMessage -} from './structured-agent-session-host-test-data' -import { reportedChildWork } from '../../observations/testing/structured-agent-session-reported-child-work.test-support' +import { HOST_TEST_SESSION, hostTestMessage } from './structured-agent-session-host-test-data' let state: ReturnType let compact: Mock> -let records: AgentChildWorkView[] = [] - -function report(next: AgentChildWorkView[]): void { - records = next - state.host.publishChildWorkEvidence(HOST_TEST_SESSION, reportedChildWork(next, HOST_TEST_NOW)) -} function compactParams() { return { @@ -34,146 +18,10 @@ function compactParams() { } } -function devServer(overrides: Partial = {}): AgentChildWorkView { - return { - id: 'child-dev', - providerId: 'task-dev', - kind: 'command', - description: 'npm run dev', - state: 'working', - membership: 'live', - firstObservedAt: HOST_TEST_NOW, - observedAt: HOST_TEST_NOW, - stoppable: true, - invocation: { invocationId: 'spawn-dev', generation: 1 }, - ...overrides - } -} - -function finish(): void { - const { command } = compact.mock.calls.at(-1)![0] - const events = state.acquire.mock.calls.at(-1)![0].events! - events.appendLifecycleBatch!( - `turn-completed:${command.clientMessageId}`, - [ - { - kind: 'item', - identity: command.identity, - body: { ...command.running, state: 'completed', outcome: 'success' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ], - { lifecycle: true } - ) -} - -async function commandTurnState(clientMessageId: string): Promise { - const { itemId } = structuredAgentSessionCommandTurn(clientMessageId) - const item = (await state.host.journalSnapshot(HOST_TEST_SESSION)).items.find( - (entry) => entry.itemId === itemId - ) - return item?.body.kind === 'turn' ? item.body.state : undefined -} - beforeEach(() => { - records = [] state = hostTestState() compact = vi.fn(async () => ({ state: 'accepted' as const, providerIdentity: null })) - const trackerRoster: AgentSessionBackgroundTaskState = { - state: 'monitoring', - tasks: [{ id: 'tracker-only', kind: 'command', description: 'not on the strip' }] - } - Object.assign(state.host.deps.adapter, { - compact, - backgroundTaskStops: () => ({ supportsTaskStop: true, supportsStopAll: true }), - // Keep a drifted provider roster claiming live work after visible records settle. - backgroundTaskState: () => trackerRoster - }) - serveHostTestChildWork(() => records) -}) - -describe('conversation command admission reads the work the provider reported', () => { - it('refuses only while reported work runs, and names the stop the strip offers', async () => { - await attach() - const strip: (AgentSessionBackgroundTaskState | null)[] = [] - await state.host.subscribe({ - id: 'strip', - sessionId: HOST_TEST_SESSION, - emit: (event) => { - if ('backgroundTasks' in event && event.backgroundTasks !== undefined) { - strip.push(event.backgroundTasks) - } - } - }) - const stripRows = () => - (strip.at(-1)?.children ?? []).map((row) => ({ - description: row.description, - membership: row.membership, - stoppable: row.stoppable, - providerId: row.providerId - })) - - expect(stripRows()).toEqual([]) - const first = compactParams() - expect(await state.host.conversationCommand(CALLER, first)).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(compact).toHaveBeenCalledTimes(1)) - finish() - await vi.waitFor(async () => - expect(await commandTurnState(first.envelope.clientOperationId)).toBe('completed') - ) - - report([devServer()]) - expect(stripRows()).toEqual([ - { description: 'npm run dev', membership: 'live', stoppable: true, providerId: 'task-dev' } - ]) - expect(await state.host.conversationCommand(CALLER, compactParams())).toMatchObject({ - ok: false, - refusal: { message: 'Stop background tasks before using this command.' } - }) - - report([devServer({ state: 'done', membership: 'settled', outcome: 'succeeded' })]) - expect(strip.at(-1)).toBeNull() - expect(stripRows()).toEqual([]) - expect(await state.host.conversationCommand(CALLER, compactParams())).toMatchObject({ - ok: true - }) - await vi.waitFor(() => expect(compact).toHaveBeenCalledTimes(2)) - }) - - it('refuses a queued command at handover once reported work runs', async () => { - const acquireChild = state.acquire.getMockImplementation()! - state.acquire.mockImplementation(async (input) => ({ - ...(await acquireChild(input)), - acquisitionGeneration: `generation-${input.fence}` - })) - await attach() - const fence = state.store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence - await state.host.handleAdapterEvent({ - type: 'ended', - sessionId: HOST_TEST_SESSION, - fence, - acquisitionGeneration: `generation-${fence}`, - reason: 'provider exited', - cause: 'unexpected-exit' - }) - await vi.waitFor(() => expect(state.host['sessions'].get(HOST_TEST_SESSION)?.child).toBeNull()) - const start = state.acquire.getMockImplementation()! - state.acquire.mockImplementationOnce(async (input) => { - report([devServer()]) - return start(input) - }) - const params = compactParams() - expect(await state.host.conversationCommand(CALLER, params)).toMatchObject({ ok: true }) - - await vi.waitFor(async () => { - const submission = (await state.host.journalSnapshot(HOST_TEST_SESSION)).submissions.find( - (entry) => entry.clientMessageId === params.envelope.clientOperationId - ) - expect(submission?.dispatchState).toBe('rejected') - }) - expect(state.acquire).toHaveBeenCalledTimes(2) - expect(compact).not.toHaveBeenCalled() - }) + Object.assign(state.host.deps.adapter, { compact }) }) it('keeps a direct failed-start command terminal until an explicit fresh rerun', async () => { diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts index 114e895ff21..002d599aea9 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts @@ -25,7 +25,7 @@ import type { AgentSessionLatestTurn } from '../../../../shared/agent-session/ag import type { StructuredAgentSessionWorkScope } from '../../../../shared/agent-session/view/structured-agent-session-main-agent-working' import { isUnansweredStructuredAgentSessionDispatch } from '../../../../shared/agent-session/requests/structured-agent-session-unanswered-dispatch' import type { AgentSessionJournal } from '../../agent-session-journal/journal-store' -import { DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED } from '../../agent-session-journal/projection/journal-dispatch-doubt-reasons' +import { admittedStructuredSubmission } from './structured-agent-session-submission-presentation' import { continuingStructuredAgentSessionInput, finalizingStructuredAgentSessionInput, @@ -155,12 +155,7 @@ export class StructuredAgentSessionCurrentWork { * answer, reads in doubt: no client counts it as work, and its echo or refusal still settles it. */ publishedSubmission = (submission: AgentJournalSubmission): AgentJournalSubmission => this.unanswered(submission) && !this.holds(submission) - ? { - ...submission, - dispatchState: 'unknown', - recovered: true, - reason: submission.reason ?? DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED - } + ? admittedStructuredSubmission(submission, this.generationEnded(submission)) : submission private unanswered(submission: AgentJournalSubmission): boolean { diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts index 2ebdcfae18f..fe4d0cd83e4 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts @@ -125,7 +125,8 @@ export class StructuredAgentSessionJournalProjections { contextId, usageLimitCut: hostUsageLimitCut( snapshot, - latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions, journal.itemBody) + latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions, journal.itemBody), + journal.itemFence ), firstInputSubmissionKey, submissionCount: journal.inputOrder.inputCount(), diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts index 548af5dd6fc..1867b3e35ab 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary-equality.ts @@ -28,7 +28,6 @@ export function structuredStatusSummariesEqual( (a.statusStartedAt !== undefined && !isIdleHeldOpenByChildWork(b))) && a.latestPrompt === b.latestPrompt && a.model === b.model && - a.reportedModel === b.reportedModel && a.permissionMode === b.permissionMode && a.runtimePermission?.fence === b.runtimePermission?.fence && a.runtimePermission?.mode === b.runtimePermission?.mode && diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts index 5534c7ec608..9b539489762 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-summary.ts @@ -1,8 +1,5 @@ import { isAgentSessionInteractionMode } from '../../../../shared/agent-session/options/agent-session-interaction-mode' -import { - structuredAgentSessionRuntimeModel, - structuredAgentSessionRuntimePermission -} from '../options/structured-agent-session-ran-options' +import { structuredAgentSessionRuntimePermission } from '../options/structured-agent-session-ran-options' import type { AgentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import { @@ -89,9 +86,6 @@ export function structuredAgentSessionStatusSummary({ ? { rewindBlockedReason: 'outcome-unknown' as const } : {}), ...(model ? { model } : {}), - ...(session.params.provider === 'claude' && session.child - ? { reportedModel: structuredAgentSessionRuntimeModel(session.child) } - : {}), ...(isAgentChatPermissionMode(permissionMode) ? { permissionMode } : {}), ...(effort ? { effort } : {}), ...(fastMode ? { fastMode } : {}), diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-subagent-rows.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-subagent-rows.ts index 387085a598b..f7b84b1cfcb 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-subagent-rows.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-subagent-rows.ts @@ -181,7 +181,7 @@ export class StructuredAgentSessionSubagentRows { } } -/** Retain saved name, tokens and parent when a later run lacks them. */ +/** Retain saved name, tokens, parent, role and model when a later run lacks them. */ function subagentRowBlock( child: AgentChildWorkRowView, id: string, @@ -201,6 +201,12 @@ function subagentRowBlock( : saved.run === run ? (saved.startedAt ?? child.firstObservedAt) : child.observedAt + const agentType = child.agentType ?? saved?.agentType + const model = child.model ?? saved?.model + const effort = child.effort ?? saved?.effort + const operation = state === 'working' ? child.operation : undefined + // A new run's silence must not repeat the previous run's result. + const lastMessage = child.lastMessage ?? (saved?.run === run ? saved.lastMessage : undefined) return { type: 'subagent', id, @@ -209,6 +215,18 @@ function subagentRowBlock( ...(tokens !== undefined ? { tokens } : {}), startedAt, ...(state !== 'working' && child.settledAt !== undefined ? { settledAt: child.settledAt } : {}), + ...(agentType !== undefined ? { agentType } : {}), + ...(model !== undefined ? { model } : {}), + ...(effort !== undefined ? { effort } : {}), + ...(operation !== undefined + ? { + operation: { + toolName: operation.toolName, + ...(operation.input !== undefined ? { input: operation.input } : {}) + } + } + : {}), + ...(lastMessage !== undefined ? { lastMessage } : {}), groupId: saved?.groupId ?? (scope.kind === 'turn' ? scope.turnItemId : THREAD_GROUP), ...(parent !== undefined ? { parentId: parent } : {}), run, diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-submission-presentation.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-submission-presentation.ts new file mode 100644 index 00000000000..2cfb43ce545 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-submission-presentation.ts @@ -0,0 +1,22 @@ +import type { AgentJournalSubmission } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { + DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED, + DISPATCH_DOUBT_WRITE_OUTCOME_UNKNOWN +} from '../../agent-session-journal/projection/journal-dispatch-doubt-reasons' + +/** Admission releases presentation only; the journal still awaits an exact receipt. */ +export function admittedStructuredSubmission( + submission: AgentJournalSubmission, + generationEnded: boolean +): AgentJournalSubmission { + return { + ...submission, + dispatchState: 'unknown', + recovered: true, + reason: + submission.reason ?? + (generationEnded + ? DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED + : DISPATCH_DOUBT_WRITE_OUTCOME_UNKNOWN) + } +} diff --git a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-reported-child-work.test-support.ts b/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-reported-child-work.test-support.ts deleted file mode 100644 index 9f21e102679..00000000000 --- a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-reported-child-work.test-support.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { AgentChildWorkEvidence } from '../../../../../shared/agent-status/child-work/agent-status-child-work-evidence' -import type { AgentChildWorkView } from '../../../../../shared/agent-status/child-work/agent-status-child-work-view' - -/** Mirror display records into provider evidence so stub sinks and host open-work state agree. */ -export function reportedChildWork( - views: readonly AgentChildWorkView[], - observedAt: number -): AgentChildWorkEvidence[] { - return views.map((view) => { - const handle = { idKind: 'task_id' as const, id: view.providerId ?? view.id } - return view.membership === 'settled' - ? { type: 'ended', observedAt, handle, outcome: view.outcome ?? 'unknown' } - : { - type: 'live', - observedAt, - child: { - handle, - kind: view.kind, - residency: 'background', - state: view.state === 'done' ? 'idle' : view.state, - stoppable: view.stoppable - } - } - }) -} diff --git a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-resumed-child-owner.test.ts b/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-resumed-child-owner.test.ts deleted file mode 100644 index e3d514026e3..00000000000 --- a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-resumed-child-owner.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { claudeProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { parseAgentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { - isBackgroundTaskBlock, - isSubagentBlock -} from '../../../../../shared/native-chat/native-chat-types' -import { - ClaudeBackgroundTaskIdentityResolver, - writeClaudeBackgroundTaskRow -} from '../../../../claude/claude-background-task-row-journal' -import { createTrackedJournalOpener } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { StructuredAgentSessionCurrentWork } from '../structured-agent-session-current-work' -import { createDeferredStructuredAgentSessionEventSink } from '../../journal-ingress/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../../host/testing/structured-agent-session-logger-test-support' -import { settleStaleStructuredAgentSessionState } from '../../termination/structured-agent-session-stale-state-settlement' -import { - StructuredAgentSessionSubagentRows, - type AgentChildWorkRowView -} from '../structured-agent-session-subagent-rows' - -// Resumed child work belongs to the new run despite older row creation; old-owner death cannot settle it. - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-resumed-child-owner-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -const subagent: AgentChildWorkRowView = { - id: 'record-1', - providerId: 'agent-1', - kind: 'agent', - description: 'Audit the build', - state: 'working', - membership: 'live', - firstObservedAt: 100, - observedAt: 100, - stoppable: true, - invocation: { invocationId: 'toolu_1', generation: 1 }, - residency: 'background' -} - -it('keeps a resumed subagent and background task working when the run that created them dies', async () => { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('claude-session', null) - }, - now: () => 9_000, - stateDirectory: root - }) - let fence = 1 - const rows = new StructuredAgentSessionSubagentRows({ - journal: () => journal, - fence: () => fence, - currentWork: (_sessionId, open) => new StructuredAgentSessionCurrentWork(open, fence), - readChildWork: () => [subagent], - onWriteFailed: (_sessionId, error) => { - throw error - } - }) - const tasks = new ClaudeBackgroundTaskIdentityResolver() - const run = async () => { - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - deferred.bind({ journal, fence, publish: () => {} }) - rows.changed('session-1', deferred.sink) - writeClaudeBackgroundTaskRow( - deferred.sink, - tasks, - 'task-1', - { - block: { - type: 'background-task', - taskId: 'task-1', - kind: 'command', - label: 'Build', - state: 'working' - }, - lastSerialized: null, - toolUseId: 'tool-1', - terminalNotificationReceived: false, - generation: 1 - }, - () => AGENT_JOURNAL_THREAD_SCOPE - ) - await expect(deferred.drained()).resolves.toEqual({ ok: true }) - await new Promise((resolve) => setTimeout(resolve, 0)) - deferred.close() - } - - const settleRunOne = () => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence: { - kind: 'exit-observed', - detail: 'run 1 exited', - observedAt: 9_000, - ownerFence: 1 - }, - below: 2 - }) - await run() - fence = 2 - await run() - await settleRunOne() - // Epoch rebuild preserves both creation and execution provenance. - await journal.replaceEpochItems( - 'handle_forked', - 2, - journal.snapshot().items.map((item) => { - const { ownerFence, executionOwner } = journal.itemProvenance(item.itemId) - return { - identity: parseAgentJournalItemKey(item.itemId)!, - body: journal.itemBody(item.itemId)!, - ownerFence: ownerFence ?? 0, - ...(executionOwner === undefined ? {} : { executionOwner }) - } - }) - ) - await settleRunOne() - - const blocks = journal - .snapshot() - .items.flatMap((item) => (item.body.kind === 'message' ? item.body.blocks : [])) - expect(blocks.filter(isSubagentBlock).map((block) => block.state)).toEqual(['working']) - expect(blocks.filter(isBackgroundTaskBlock).map((block) => block.state)).toEqual(['working']) -}) diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-turn.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-turn.ts index 687016fe61b..352a3f96128 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-turn.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-command-turn.ts @@ -39,7 +39,10 @@ import type { StructuredAgentSessionAdapter } from '../providers/structured-agent-session-adapter' import type { StructuredAgentRegistry } from '../providers/structured-agent-registry' -import { conversationCommandBlocked } from './structured-conversation-command-admission' +import { + compactionChildWork, + conversationCommandBlocked +} from './structured-conversation-command-admission' import { structuredAgentSessionCommandTurn } from '../../../../shared/agent-session/view/structured-agent-session-command-turn-identity' import { refuseQueuedCommand } from '../delivery/structured-agent-session-queued-command-refusal' import { @@ -315,10 +318,11 @@ function commandBlocked( if (!capabilities?.compact || (body.command.instructions && !capabilities.compactInstructions)) { return agentSessionFailureFact('commandRefused') } + const childWork = () => ({ views: ctx.childWork(), open: ctx.childWorkOpen() }) const refusal = conversationCommandBlocked( ctx, record, - { views: ctx.childWork(), open: ctx.childWorkOpen() }, + compactionChildWork(capabilities, childWork), 'handover' ) return refusal diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts index 664ea0022cc..e05d409093c 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts @@ -55,10 +55,7 @@ import { openWithReadyStructuredAgentSessionChild } from './structured-agent-ses import type { StructuredAgentSessionCaller } from '../host/structured-agent-session-host-types' import '../options/structured-agent-session-options-read' -import { - noteStructuredAgentSessionOptionPick, - recordStructuredAgentSessionOptionIntent -} from '../options/structured-agent-session-option-intent' +import { recordStructuredAgentSessionOptionIntent } from '../options/structured-agent-session-option-intent' import { confirmIdleStructuredAgentSessionOption } from '../options/structured-agent-session-idle-option' export function sendStructuredAgentSessionTurn( @@ -268,7 +265,6 @@ export async function setStructuredAgentSessionOption( readsWithoutModel: caller.readsOptionsWithoutModel !== false }) if (picked.ok) { - noteStructuredAgentSessionOptionPick(context, ctx, params, !noChoice) confirmIdleStructuredAgentSessionOption(context, ctx, params) } return picked diff --git a/src/main/native-chat/agent-session-wire/operations/structured-conversation-command-admission.ts b/src/main/native-chat/agent-session-wire/operations/structured-conversation-command-admission.ts index 7e438d2960d..e183c61da13 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-conversation-command-admission.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-conversation-command-admission.ts @@ -3,6 +3,7 @@ import { type AgentSessionBackgroundTaskStops } from '../../../../shared/agent-status/child-work/agent-child-work-stop-targets' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionCapabilities } from '../../../../shared/agent-session/agent-session-capabilities' import { isQueuedAgentJournalSubmission } from '../../../../shared/agent-session/requests/agent-session-queued-submission' import type { AgentChildWorkView } from '../../../../shared/agent-status/child-work/agent-status-child-work-view' import { agentSessionCurrentContextRows } from '../../../../shared/agent-session/agent-session-context-clear' @@ -24,6 +25,14 @@ export type ConversationCommandChildWork = { open: boolean } +/** Null where the agent compacts beside background tasks, so they don't hold /compact. */ +export function compactionChildWork( + capabilities: Pick | null | undefined, + childWork: () => ConversationCommandChildWork +): ConversationCommandChildWork | null { + return capabilities?.compactBesideBackgroundTasks ? null : childWork() +} + export type ConversationCommandAdmissionContext = { sessionId: string fence: number @@ -51,7 +60,7 @@ export function conversationCommandInFlight(): AgentSessionWireRefusal { export function conversationCommandBlocked( ctx: ConversationCommandAdmissionContext, record: AgentSessionRecord, - childWork: ConversationCommandChildWork, + childWork: ConversationCommandChildWork | null, admission?: 'at-rest' | 'handover' ): AgentSessionWireRefusal | null { const { items, submissions } = agentSessionCurrentContextRows( @@ -82,7 +91,7 @@ export function conversationCommandBlocked( ) } // Closed generations’ leftover child work must not block admission. - if (work.liveFence !== null && childWork.open) { + if (work.liveFence !== null && childWork?.open) { return blocked( 'backgroundTasksRunning', stripOffersStop(childWork.views ?? [], ctx.adapter.backgroundTaskStops?.(ctx.sessionId)) diff --git a/src/main/native-chat/agent-session-wire/operations/structured-conversation-compaction.ts b/src/main/native-chat/agent-session-wire/operations/structured-conversation-compaction.ts index 8222a85937f..7f2ba18cbef 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-conversation-compaction.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-conversation-compaction.ts @@ -30,7 +30,10 @@ import { conversationCommandFailure, type ConversationCommandParams } from './structured-conversation-command' -import { conversationCommandBlocked } from './structured-conversation-command-admission' +import { + compactionChildWork, + conversationCommandBlocked +} from './structured-conversation-command-admission' import { maybeQueueStructuredAgentSessionSend } from '../delivery/structured-agent-session-queued-messages' import { structuredAgentSessionCompactBody } from './structured-agent-session-command-turn' @@ -186,10 +189,10 @@ function acceptUnderSerialize( conversationCommandBlocked( ctx, record, - { + compactionChildWork(ctx.agents.capabilities(record.provider), () => ({ views: context.readChildWork(ctx.sessionId), open: context.childWorkOpen(ctx.sessionId) - }, + })), context.sessions.get(ctx.sessionId)?.child ? undefined : 'at-rest' ) const blocked = diff --git a/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts b/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts index 0100641739c..e063b122593 100644 --- a/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts +++ b/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts @@ -46,9 +46,12 @@ export function codexTurnOptionsDiffer( next: options }) if (!applied) { - return options === undefined || Object.values(options).some((value) => value !== undefined) + return false } return OPTION_ORDER.some( - (key) => applied.next[key] !== undefined && applied.next[key] !== applied.active[key] + (key) => + applied.active[key] !== undefined && + applied.next[key] !== undefined && + applied.next[key] !== applied.active[key] ) } diff --git a/src/main/native-chat/agent-session-wire/options/structured-agent-session-option-intent.ts b/src/main/native-chat/agent-session-wire/options/structured-agent-session-option-intent.ts index f835e253b20..2de64669af4 100644 --- a/src/main/native-chat/agent-session-wire/options/structured-agent-session-option-intent.ts +++ b/src/main/native-chat/agent-session-wire/options/structured-agent-session-option-intent.ts @@ -19,10 +19,6 @@ import { } from './structured-agent-session-pick-reply' import type { StructuredAgentSessionAdapter } from '../providers/structured-agent-session-adapter' import { pickAgentSessionOption } from '../../../runtime/agent-session/records/agent-session-record-options' -import type { - StructuredAgentSessionHostSession, - StructuredAgentSessionProviderChild -} from '../host/structured-agent-session-host-types' function acceptsOptionPick( agents: Pick, @@ -107,34 +103,3 @@ export async function recordStructuredAgentSessionOptionIntent( } } } - -const modelPicks = new WeakMap() - -/** Counts saved model picks per child, so a read can tell its captured report predates one. */ -export function structuredAgentSessionModelPicks( - child: StructuredAgentSessionProviderChild -): number { - return modelPicks.get(child) ?? 0 -} - -/** A saved pick retires the current child's earlier reports, including ones a read already captured. */ -export function noteStructuredAgentSessionOptionPick( - context: { - deps: { adapter: Pick } - sessions: ReadonlyMap - }, - ctx: Pick, - input: { key: string; value: string }, - saved: boolean -): void { - const { sessionId, fence } = ctx - // An old client's empty model clears nothing, so it retires no report. - if (!saved) { - return - } - const child = context.sessions.get(sessionId)?.child - if (input.key === 'model' && child?.fence === fence) { - modelPicks.set(child, structuredAgentSessionModelPicks(child) + 1) - } - context.deps.adapter.noteOptionPick?.({ sessionId, fence, ...input }) -} diff --git a/src/main/native-chat/agent-session-wire/options/structured-agent-session-options-read.ts b/src/main/native-chat/agent-session-wire/options/structured-agent-session-options-read.ts index 76918d8fe34..59e4721f627 100644 --- a/src/main/native-chat/agent-session-wire/options/structured-agent-session-options-read.ts +++ b/src/main/native-chat/agent-session-wire/options/structured-agent-session-options-read.ts @@ -30,13 +30,12 @@ import { structuredAgentSessionImmediatePermission } from './structured-agent-se import type { StructuredAgentSessionMutationContext } from '../operations/structured-agent-session-mutation-context' import { readStructuredSessionRecovery } from '../recovery/structured-agent-session-recovery-read' import { fillUnknownModelEfforts } from '../../../../shared/agent-session/options/agent-session-model-efforts' -import { structuredAgentSessionModelPicks } from './structured-agent-session-option-intent' /** A live child's own answer, or the answer at rest; the goal, usage and rewind either way. */ export async function readStructuredAgentSessionOptions( context: Pick< StructuredAgentSessionMutationContext, - 'deps' | 'serialize' | 'openConversation' | 'conversation' | 'sessions' + 'deps' | 'serialize' | 'openConversation' | 'conversation' > & Partial>, sessionId: string, @@ -72,7 +71,6 @@ export async function readStructuredAgentSessionOptions( child && child.phase !== 'starting' ? await adapter.readOptions?.({ sessionId, fence: child.fence }) : undefined - const modelPicks = child ? structuredAgentSessionModelPicks(child) : 0 const scope = () => structuredAgentSessionCatalogScopeOwned( context.deps, @@ -95,8 +93,7 @@ export async function readStructuredAgentSessionOptions( records, session, child, - options: observed ?? null, - modelPicks + options: observed ?? null } }) let started = await readCurrent(true) @@ -163,17 +160,6 @@ export async function readStructuredAgentSessionOptions( const model = saved.model ?? (options.current.model || selected.current.model || displayDefault) const projected = live?.projectCurrent?.({ ...saved, ...(model ? { model } : {}) }) const reportedEffort = projected?.confirmed?.includes('effort') ? projected.effort : undefined - // After every await: a pick or a replaced child since the live read retires its report. - const reportedModel = - live && - started.kind === 'live' && - context.sessions.get(sessionId)?.child === started.child && - started.modelPicks === structuredAgentSessionModelPicks(started.child) - ? (options.current.reportedModel ?? - (agent === 'claude' && options.current.confirmed?.includes('model') - ? options.current.model - : undefined)) - : undefined const current = { ...selected.current, ...options.current, @@ -266,7 +252,7 @@ export async function readStructuredAgentSessionOptions( current: { ...current, acceptedInputSources, - reportedModel, + reportedModel: undefined, ...(reportedEffort !== undefined ? { reportedEffort } : {}), defaulted, confirmed, diff --git a/src/main/native-chat/agent-session-wire/options/structured-agent-session-ran-options.ts b/src/main/native-chat/agent-session-wire/options/structured-agent-session-ran-options.ts index 64b77a35157..b739ae95fa2 100644 --- a/src/main/native-chat/agent-session-wire/options/structured-agent-session-ran-options.ts +++ b/src/main/native-chat/agent-session-wire/options/structured-agent-session-ran-options.ts @@ -28,7 +28,6 @@ const childRuns = new WeakMap< StructuredAgentSessionProviderChild, { reported?: RanOptions - reportedModel?: string owed?: StructuredAgentSessionHandedOptions permission?: string | null } @@ -39,12 +38,6 @@ function currentChild(context: RanOptionsContext, sessionId: string, fence: numb return child?.fence === fence ? child : null } -export function structuredAgentSessionRuntimeModel( - child: StructuredAgentSessionProviderChild -): string | undefined { - return child.phase === 'ready' ? childRuns.get(child)?.reportedModel : undefined -} - /** The current child's startup report or applied evidence; never saved intent or send authority. */ export function structuredAgentSessionRuntimePermission( child: StructuredAgentSessionProviderChild | undefined @@ -59,9 +52,6 @@ export function noteStructuredAgentSessionRuntimeOptions( initial = false ): void { const previous = childRuns.get(child) - if (!initial || previous?.reportedModel === undefined) { - childRuns.set(child, { ...previous, reportedModel: reported.reportedModel ?? reported.model }) - } if ( reported.reportedPermissionMode !== undefined && (!initial || previous?.permission === undefined) diff --git a/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts b/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts index dad95873f13..5f5cf711ccc 100644 --- a/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts +++ b/src/main/native-chat/agent-session-wire/options/testing/at-rest-command-catalog-stamp.test.ts @@ -6,14 +6,12 @@ import { AtRestCommandCatalog } from '../at-rest-command-catalog' function catalogWithSkills() { let stamp = 'a' let skills = ['old-skill'] - let scans = 0 const catalog = new AtRestCommandCatalog({ label: 'test', accepts: () => true, resolveWorkspacePath: async () => tmpdir(), stamp: async () => stamp, scan: async () => { - scans += 1 return { commands: skills.map((name) => ({ name, kind: 'skill' as const, path: `/s/${name}` })), fromAgent: true @@ -22,7 +20,6 @@ function catalogWithSkills() { }) return { catalog, - scans: () => scans, install: (name: string, nextStamp: string) => { skills = [...skills, name] stamp = nextStamp @@ -34,13 +31,12 @@ const names = (commands: { name: string }[] | undefined) => commands?.map(({ nam describe('at-rest commands before the TTL', () => { it('rescans on a menu open once the skill sources changed', async () => { - const { catalog, scans, install } = catalogWithSkills() + const { catalog, install } = catalogWithSkills() const record = hostTestRestingOptionsRecord() expect(names(await catalog.settled(record, 1_000, true))).toEqual(['old-skill']) install('perf-scan', 'b') expect(names(await catalog.settled(record, 1_000, true))).toEqual(['old-skill', 'perf-scan']) - expect(scans()).toBe(2) catalog.dispose() }) }) diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts index 978847e8632..492ff9bc30c 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts @@ -204,8 +204,6 @@ export class StructuredAgentSessionAdapterRouter implements Adapter { canSetOptionWhileIdle: Adapter['canSetOptionWhileIdle'] = (input) => this.liveOwnerOrNull(input.sessionId)?.canSetOptionWhileIdle?.(input) === true - noteOptionPick: Adapter['noteOptionPick'] = (input) => - this.liveOwnerOrNull(input.sessionId)?.noteOptionPick?.(input) readAppliedInputOptions: Adapter['readAppliedInputOptions'] = (input) => this.liveOwnerOrNull(input.sessionId)?.readAppliedInputOptions?.(input) ?? null diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts index 2a5269d08e9..31a3adcbf6b 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts @@ -304,8 +304,6 @@ export type StructuredAgentSessionAdapter = StructuredAgentSessionAdapterStop & ): Promise>> /** Opt in only when setOption can update idle metadata without a provider turn. */ canSetOptionWhileIdle?(input: StructuredAgentSessionSetOptionInput): boolean - /** A saved pick retires this child's earlier execution reports until a turn carries it. */ - noteOptionPick?(input: { sessionId: string; fence: number; key: string; value: string }): void /** Applied inputs for this exact child; observations never decide message admission. */ readAppliedInputOptions?(input: { sessionId: string diff --git a/src/main/native-chat/agent-session-wire/providers/testing/structured-agent-session-provider-naming.test.ts b/src/main/native-chat/agent-session-wire/providers/testing/structured-agent-session-provider-naming.test.ts deleted file mode 100644 index 5d48c6e24aa..00000000000 --- a/src/main/native-chat/agent-session-wire/providers/testing/structured-agent-session-provider-naming.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record' -import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' -import type { StructuredAgentSessionAdapter } from '../structured-agent-session-adapter' -import { createStructuredChatNamingHandler } from '../../../structured-chat-naming' -import { setAgentSessionRecordUserName } from '../../../../runtime/agent-session/records/agent-session-record-conversation-name' -import { - createStructuredAgentSessionProviderNaming, - withProviderNaming -} from '../structured-agent-session-provider-naming' - -type Rename = NonNullable - -function chat(fields: Partial = {}): AgentSessionRecord { - return agentSessionRecordFixture({ - sessionId: 'chat-1', - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: '/home/work/.codex' }, - providerHandleChain: [ - { - linkId: 'link-1', - handle: codexProviderHandle('thread-1'), - origin: 'created', - mintedAtFence: 1, - observedAt: 0 - } - ], - conversationName: 'Release notes', - conversationNameSource: 'user', - ...fields - }) -} - -function naming(rename: Rename) { - const warn = vi.fn() - const queue = createStructuredAgentSessionProviderNaming({ - adapter: { renameProviderSession: rename }, - logger: { warn, error: vi.fn() } - }) - return { queue, warn } -} - -it.each([10, 100])('coalesces %i saved renames into two ordered pushes', async (count) => { - const gates = [Promise.withResolvers(), Promise.withResolvers()] - const rename = vi.fn(() => gates[rename.mock.calls.length - 1]!.promise) - let record = chat({ conversationName: 'First' }) - const { queue } = naming(rename) - const handler = createStructuredChatNamingHandler({ - getStore: () => ({ - getRecord: () => record, - compareAndSetConversationName: async () => record, - setUserConversationName: async (_id, name, write) => { - const result = setAgentSessionRecordUserName(record, name, write, 1_700_000_000_000) - record = result.record - return result - } - }), - getSettings: () => ({ nativeChatAutoName: false }), - workerTaskTitle: () => null, - readFirstPrompt: async () => '', - readJournalFirstPrompt: async () => '', - generate: async () => null, - onNamed: () => {}, - logger: { warn: vi.fn(), error: vi.fn() } - }) - const wrapped = withProviderNaming(handler, (committed) => void queue.push(committed)) - await wrapped.setUserName('chat-1', 'First', 'rename') - for (let i = 1; i <= count; i += 1) { - await wrapped.setUserName('chat-1', `Name ${i}`, 'rename') - } - expect(rename).toHaveBeenCalledTimes(1) - const done = queue.push(record) - gates[0]!.resolve() - await vi.waitFor(() => expect(rename).toHaveBeenCalledTimes(2)) - gates[1]!.resolve() - await done - expect(rename.mock.calls.map(([input]) => input.name)).toEqual(['First', `Name ${count}`]) - await wrapped.setUserName('chat-1', 'Ignored alias', 'legacy-alias') - expect(rename).toHaveBeenCalledTimes(2) -}) diff --git a/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts b/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts index f5ec1229325..65d513d7ff1 100644 --- a/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts +++ b/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts @@ -6,9 +6,6 @@ import type { AgentSessionHistoryRequest, AgentSessionHistoryResult } from '../../../../../shared/agent-session/agent-session-wire' -import type { AgentSessionWorkState } from '../../../../../shared/agent-session/agent-session-work-state' -import { AgentSessionRefusalError } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals' -import { AGENT_SESSION_NOT_ATTACHED } from '../../operations/structured-agent-session-mutation-refusals' import type { AgentSessionBackgroundTaskState } from '../../../../../shared/agent-session/agent-session-background-task-wire' import type { AgentChildWorkView } from '../../../../../shared/agent-status/child-work/agent-status-child-work-view' import { structuredChildWorkLegacyTasks } from '../../../../../shared/agent-session/structured-agent-session-child-work-legacy' @@ -88,31 +85,6 @@ export class StructuredAgentSessionBackgroundTaskChannel { } } - /** What a waiter decides from, from the sources history pages state, without building a page. */ - async workState(sessionId: string): Promise { - await this.conversation(sessionId) - const work = hostStructuredAgentSessionCurrentWork( - { store: this.deps.store, sessions: this.sessions }, - sessionId - ) - if (!work) { - throw new AgentSessionRefusalError(AGENT_SESSION_NOT_ATTACHED) - } - const queue = this.subscribers.readQueuePublication(sessionId) - const fence = this.deps.store.getConversation(sessionId)?.currentFence - return { - working: work.working(), - actionablePrompt: work.hasActionablePrompt(), - ...(queue !== undefined - ? { - queuedMessageIds: (queue.queuedMessages ?? []).map((card) => card.messageId), - nextQueuedMessageId: queue.nextQueuedMessageId - } - : {}), - ...(fence !== undefined ? { fence } : {}) - } - } - async currentRequests(request: AgentSessionCurrentRequestsRead) { await this.conversation(request.sessionId) const work = hostStructuredAgentSessionCurrentWork( diff --git a/src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-wire-admission.test.ts b/src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-wire-admission.test.ts deleted file mode 100644 index 51ce24f1cf9..00000000000 --- a/src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-wire-admission.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { AgentJournalItemIdentity } from '../../../../../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentSessionSubscribeEvent } from '../../../../../../shared/agent-session/agent-session-wire' -import type { AgentSessionBackgroundTaskState } from '../../../../../../shared/agent-session/agent-session-background-task-wire' -import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../../../shared/remote-runtime/remote-runtime-memory-limits' -import { mobileE2EETextPayloadAdmissionBytes } from '../../../../../runtime/rpc/mobile-e2ee-outbound-admission' -import { - type AgentJournalItemBody, - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { JournalRow } from '../../../../agent-session-journal/durable-rows/journal-row-schema' -import type { AgentSessionJournal } from '../../../../agent-session-journal/journal-store' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { readAgentSessionHistory } from '../../history/agent-session-history-page' -import { AgentSessionSubscribers } from '../structured-agent-session-subscribers' -import { codexProviderHandle } from '../../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const SESSION = 'wire-admission-session' -const LARGE_TEXT = 'x'.repeat(250 * 1024) - -let root: string -let journal: AgentSessionJournal -const journals = createTrackedJournalOpener({ legacyInputs: true }) - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-admission-')) - journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: root - }) - for (let ordinal = 1; ordinal <= 20; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -describe('structured agent-session outbound admission', () => { - it('admits bounded initial, background-task, epoch, compaction, and history recovery frames', async () => { - expect(Buffer.byteLength(JSON.stringify(journal.snapshot()), 'utf8')).toBeGreaterThan( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - - let roster: AgentSessionBackgroundTaskState | null = null - const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) - const initial: AgentSessionSubscribeEvent[] = [] - const dispose = subscribers.open({ - id: 'initial', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => initial.push(event) - }) - expect(initial).toHaveLength(1) - expect(initial[0]).toMatchObject({ type: 'snapshot', page: { hasOlder: true } }) - expectAdmitted(initial[0]) - - roster = { state: 'monitoring' } - subscribers.republishBackgroundTasks(SESSION, 2) - subscribers.snapshot(SESSION, journal, 2) - expect(initial.slice(1)).toHaveLength(2) - initial.slice(1).forEach(expectAdmitted) - - const epochReset: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'old-epoch', - sessionId: SESSION, - journal, - fence: 2, - cursor: { epoch: 'retired-epoch', sequence: 1 }, - emit: (event) => epochReset.push(event) - }) - expect(epochReset[0]).toMatchObject({ type: 'reset', reset: 'epoch_changed' }) - expectAdmitted(epochReset[0]) - const epochHistory = readAgentSessionHistory(journal, { - sessionId: SESSION, - direction: 'before', - cursor: { epoch: 'retired-epoch', sequence: 1 } - }) - expect(epochHistory).toMatchObject({ ok: false, reset: 'epoch_changed' }) - expectAdmitted(epochHistory) - - // Epochs no longer shed rows; exercise cursor_compacted via an over-budget legacy page. - const cursorBefore = journal.cursor() - const overBudget = await reopenWithOversizedRemoval(cursorBefore.sequence) - const history = readAgentSessionHistory(overBudget, { - sessionId: SESSION, - direction: 'after', - cursor: cursorBefore - }) - expect(history).toMatchObject({ ok: false, reset: 'cursor_compacted' }) - expectAdmitted(history) - expect(initial.some((event) => event.type === 'end')).toBe(false) - dispose() - }) - - it('replaces an over-budget catch-up with one admitted newest page', () => { - const subscribers = new AgentSessionSubscribers() - const catchup: AgentSessionSubscribeEvent[] = [] - const firstItemSequence = journal.snapshot().items[0]!.sequence - - subscribers.open({ - id: 'catchup', - sessionId: SESSION, - journal, - fence: 2, - cursor: { epoch: journal.epoch, sequence: firstItemSequence }, - emit: (event) => catchup.push(event) - }) - - expect(catchup).toHaveLength(1) - catchup.forEach(expectAdmitted) - expect(catchup[0]).toMatchObject({ - type: 'snapshot', - page: { hasOlder: true, hasNewer: false, liveCursor: journal.cursor() }, - fence: 2 - }) - }) -}) - -function expectAdmitted(value: unknown): void { - const frame = JSON.stringify({ id: 'request-1', result: value }) - const bytes = mobileE2EETextPayloadAdmissionBytes(frame) - expect(Number.isFinite(bytes)).toBe(true) - expect(bytes).toBeLessThanOrEqual(REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES) -} - -function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } -} - -function body(text: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } -} - -/** Inject a legacy oversized removal ID to force a cursor_compacted reset. */ -async function reopenWithOversizedRemoval(afterSequence: number): Promise { - const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - const base = { v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, epoch: journal.epoch, fence: 1, ts: 1 } - const rows: JournalRow[] = [ - { - ...base, - kind: 'item', - itemId: hugeItemId, - revision: 1, - seq: afterSequence + 1, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] } - }, - { ...base, kind: 'tombstone', itemId: hugeItemId, revision: 2, seq: afterSequence + 2 } - ] - await journal.close() - const opened = openTestJournalHostDatabase(root) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of rows) { - insertTestJournalRow(opened.db, SESSION, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - return journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: root - }) -} diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-continuation-context.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-continuation-context.ts index 136100ca281..a7528381dda 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-continuation-context.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-continuation-context.ts @@ -1,4 +1,4 @@ -import { projectSavedChatContextItems } from '../../agent-session-saved-prompt-text' +import { projectSavedChatContextItems } from '../../conversation-context/agent-session-saved-prompt-text' import type { AgentJournalCursor } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { AgentSessionContinuationContext } from '../../../../shared/agent-session/agent-session-wire' import { agentSessionCurrentContextRows } from '../../../../shared/agent-session/agent-session-context-clear' @@ -7,7 +7,7 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { projectStructuredAgentSessionMessages } from '../../../../shared/agent-session/view/structured-agent-session-message-projection' import { formatWorkerTranscriptMessage } from '../../../../shared/worker-transcript-text' import { toLinuxPath } from '../../../../shared/wsl-paths' -import { writeAgentSessionContextSnapshot } from '../../agent-session-context-snapshots' +import { writeAgentSessionContextSnapshot } from '../../conversation-context/agent-session-context-snapshots' import type { StructuredAgentSessionHostDeps, StructuredAgentSessionHostSession diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-recovery-read.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-recovery-read.ts index 7b026f69930..c1dfad38b63 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-recovery-read.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-recovery-read.ts @@ -3,7 +3,7 @@ import { structuredSessionRecoveryOptions, type RecoveryContextCache } from '../../../runtime/agent-session/lifecycle/structured-session-recovery-options' -import { withoutInheritedClaudeConfigDir } from '../../../claude/claude-config-dir-pin' +import { withoutInheritedClaudeConfigDir } from '../../../claude/structured/launch/claude-config-dir-pin' import type { StructuredAgentSessionHostDeps, StructuredAgentSessionHostSession diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts index 503e3471d8f..7f67ac9cc57 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts @@ -10,8 +10,11 @@ import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecy import type { AgentSessionRecordStore } from '../../../runtime/agent-session/records/agent-session-record-store' import { agentSessionAccountHomePath, + agentSessionAccountHomesEqual, + isLegacyAgentSessionAccountHome, type AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { usageLimitContinueIdentity as identity } from './structured-agent-session-usage-limit-chain' /** The polled usage of the account a chat continues on, as the host attributes it. */ @@ -75,6 +78,11 @@ export class UsageLimitAccountHolds { private readonly scopes = new Map() /** The source witness each chat's attribution was computed under. */ private readonly witnesses = new Map() + /** When each chat was first seen continuing on another account than the one its cut hit. */ + private readonly movedSince = new Map< + string, + { cut: string; to: AgentSessionAccountHome; at: number } + >() /** Shared by every chat of a pass and keyed by source witness: work scales with accounts and * their changes, not chats. */ private launchHomes = new Map>() @@ -90,15 +98,22 @@ export class UsageLimitAccountHolds { this.readings = new Map() } - /** Re-attributed each pass: the account a chat continues on follows the host's selection. */ - async attribute(id: string, host: AttributionHost): Promise { + /** Re-attributed each pass: the account a chat continues on follows the host's selection. + * `hit` names the cut and the account it hit, when known. */ + async attribute( + id: string, + host: AttributionHost, + hit?: { cut: string; home: AgentSessionAccountHome | null }, + now = Date.now() + ): Promise { const record = host.store.getRecord(id) const read = host.usageLimitAutoContinue?.accountUsage const witness = record ? liveWitness(host, record.provider) : undefined let scope: UsageLimitAccountScope | undefined + let movedTo: AgentSessionAccountHome | null = null try { // WSL readings never reach this host, so a WSL launch keeps the cut's own reset. - if (record && read && record.location.wslDistro === null) { + if (record && record.location.wslDistro === null) { // Off WSL a launch home follows only the provider's selection, never the chat. const target = JSON.stringify([witness, record.provider]) let launch = this.launchHomes.get(target) @@ -107,8 +122,9 @@ export class UsageLimitAccountHolds { this.launchHomes.set(target, launch) } const home = (await launch) ?? record.accountHome + movedTo = hit?.home && !sameAccountHome(home, hit.home) ? home : null const path = agentSessionAccountHomePath(home) - if (home && path) { + if (read && home && path) { const key = JSON.stringify([witness, record.provider, path]) let reading = this.readings.get(key) if (!reading) { @@ -129,6 +145,13 @@ export class UsageLimitAccountHolds { } this.scopes.set(id, scope) this.witnesses.set(id, witness) + const since = this.movedSince.get(id) + if (!movedTo || !hit) { + this.movedSince.delete(id) + } else if (since?.cut !== hit.cut || !sameAccountHome(since.to, movedTo)) { + // Each destination counts from when it was chosen, so an older reading of it never releases. + this.movedSince.set(id, { cut: hit.cut, to: movedTo, at: now }) + } } /** The witness the chat's attribution was computed under; a send binds to this one. */ @@ -155,20 +178,30 @@ export class UsageLimitAccountHolds { } } } + for (const id of this.movedSince.keys()) { + if (!shown.has(id)) { + this.movedSince.delete(id) + } + } } clear(): void { this.holds.clear() this.scopes.clear() this.witnesses.clear() + this.movedSince.clear() this.beginPass() } verdict( id: string, - cut: { turnItemId: string; resetsAt: number }, + limited: { turnItemId: string; resetsAt: number }, now: number ): UsageLimitAccountVerdict { + // The account the chat moved to never hit this cut: from the move on, only its reading holds. + const moved = this.movedSince.get(id) + const movedCut = moved?.cut === identity(limited) + const cut = movedCut ? { ...limited, resetsAt: Math.min(limited.resetsAt, moved.at) } : limited const scope = this.scopes.get(id) let hold = this.holds.get(id) // Nothing attributed and nothing held: the cut decides, and nothing is kept for it. @@ -202,10 +235,11 @@ export class UsageLimitAccountHolds { (hold.unknownReset && hold.spentSeenAt) || cut.resetsAt, typeof covering === 'number' ? covering : cut.resetsAt ) + // Spending the new account showed before the move still holds; only a later reading releases it. if ( account && reading && - fresh(cut.resetsAt) && + fresh(movedCut ? Number.NEGATIVE_INFINITY : cut.resetsAt) && now - anchor <= NATIVE_CHAT_USAGE_LIMIT_MAX_OVERDUE_MS ) { if (typeof covering === 'number') { @@ -220,7 +254,10 @@ export class UsageLimitAccountHolds { hold.heldUntil = Math.max(hold.heldUntil ?? spentUntil, spentUntil) } hold.spentSeenAt = Math.max(hold.spentSeenAt ?? reading.updatedAt, reading.updatedAt) - } else if (reading.updatedAt > (hold.spentSeenAt ?? Number.NEGATIVE_INFINITY)) { + } else if ( + fresh(cut.resetsAt) && + reading.updatedAt > (hold.spentSeenAt ?? Number.NEGATIVE_INFINITY) + ) { // Room newer than any spending seen releases the hold at that reading, so it counts from now. if (hold.unknownReset || (hold.heldUntil ?? Number.NEGATIVE_INFINITY) > reading.updatedAt) { hold.heldUntil = reading.updatedAt @@ -293,6 +330,14 @@ export class UsageLimitAccountHolds { } } +function sameAccountHome(left: AgentSessionAccountHome, right: AgentSessionAccountHome): boolean { + return isLegacyAgentSessionAccountHome(left) && isLegacyAgentSessionAccountHome(right) + ? left.variable === right.variable && + normalizeRuntimePathForComparison(left.path) === + normalizeRuntimePathForComparison(right.path) + : agentSessionAccountHomesEqual(left, right) +} + /** Changes whenever a source the provider's attribution reads changes. */ function liveWitness( host: AttributionHost, diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts index ee1e8927915..cf16f2a024f 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts @@ -11,6 +11,7 @@ import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle import { restoreJournal } from '../../agent-session-journal/replay/journal-open' import { renderJournalStatus } from '../../agent-session-journal/projection/journal-public-read' import { journalInputOrder } from '../../agent-session-journal/input-order/journal-input-order' +import { journalItemExecutionFence } from '../../agent-session-journal/projection/journal-item-provenance' import type Database from '../../../sqlite/sync-database' import { latestNativeChatUsageLimitCut, @@ -168,18 +169,25 @@ export function usageLimitContinueChain( return chain } -/** A cut as the host's sweep reads it: with the chain that led to it. */ -export type HostUsageLimitCut = NativeChatUsageLimitCut & { chain: number } +/** A cut as the host's sweep reads it: with the chain that led to it and the runtime fence that + * ran its turn, which names the account it hit. */ +export type HostUsageLimitCut = NativeChatUsageLimitCut & { chain: number; fence?: number } export function hostUsageLimitCut( snapshot: { items: readonly AgentJournalRenderItem[] submissions: readonly ChainSubmission[] }, - cut: NativeChatUsageLimitCut | null + cut: NativeChatUsageLimitCut | null, + fenceOf: (itemId: string) => number | undefined ): HostUsageLimitCut | null { + const fence = cut ? fenceOf(cut.turnItemId) : undefined return cut - ? { ...cut, chain: usageLimitContinueChain(snapshot.items, snapshot.submissions, cut) } + ? { + ...cut, + chain: usageLimitContinueChain(snapshot.items, snapshot.submissions, cut), + ...(fence === undefined ? {} : { fence }) + } : null } @@ -189,14 +197,13 @@ export function readSavedUsageLimitCut( id: string ): HostUsageLimitCut | null { const load = restoreJournal(db, id) - const snapshot = - load && !load.newer && !load.damage - ? renderJournalStatus(load.state, journalInputOrder(load.state)) - : null - return snapshot - ? hostUsageLimitCut( - snapshot, - latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions) - ) - : null + if (!load || load.newer || load.damage) { + return null + } + const snapshot = renderJournalStatus(load.state, journalInputOrder(load.state)) + return hostUsageLimitCut( + snapshot, + latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions), + (itemId) => journalItemExecutionFence(load.state, itemId) + ) } diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts index 7160665287b..9cd0ecac485 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts @@ -132,7 +132,9 @@ export class StructuredAgentSessionUsageLimitContinue { turnItemId: cut.turnItemId, resetsAt: cut.resetsAt, // While the reset is unknown, `hold.resetsAt` is a reading time, not a reset. - ...(!hold.unknownReset && hold.resetsAt > cut.resetsAt ? { continueAt: hold.resetsAt } : {}), + ...(!hold.unknownReset && hold.resetsAt !== cut.resetsAt + ? { continueAt: hold.resetsAt } + : {}), state } } @@ -172,13 +174,7 @@ export class StructuredAgentSessionUsageLimitContinue { if (this.running || this.disposed) { return } - // Off, nothing can be scheduled; the settings listener publishes the switch itself. - if (!this.enabled()) { - if (this.holds.size + this.cold.size + this.attempts.size > 0) { - this.retainShown(this.deps.host.store.listVisibleSessionIds()) - } - return - } + // Off, nothing is sent, but an account switch still moves when Continue applies. this.running = true try { const visible = this.deps.host.store.listVisibleSessionIds() @@ -197,10 +193,10 @@ export class StructuredAgentSessionUsageLimitContinue { if (!cut || previous?.identity !== identity(cut)) { this.attempts.delete(id) } - // Before the overdue check: after a restart only the reading still knows a later reset. - // Only a reading taken after the cut's reset counts, so attribution waits for it. - if (cut?.resetsAt !== undefined && this.deps.now() >= cut.resetsAt) { - await this.holds.attribute(id, this.deps.host) + // Before the overdue check: after a restart only the reading still knows a later reset, + // and a switched account frees the chat before it. + if (cut?.resetsAt !== undefined) { + await this.attribute(id, cut) } const attempt = this.attempts.get(id) if (!cut || !this.eligible(id, cut) || attempt?.unconfirmed || (attempt?.count ?? 0) >= 5) { @@ -226,6 +222,13 @@ export class StructuredAgentSessionUsageLimitContinue { } } + /** The account a cut hit is the one its turn's runtime launched under, when the record names it. */ + private attribute(id: string, cut: HostUsageLimitCut): Promise { + const launched = this.deps.host.store.getRecord(id)?.launchedAccount + const home = launched && launched.fence === cut.fence ? launched.accountHome : null + return this.holds.attribute(id, this.deps.host, { cut: identity(cut), home }, this.deps.now()) + } + private deferUnchangedCut(id: string, cut: Cut, at: number): void { const current = this.cold.read(id) // Admission also refuses temporary backlog; yield the next passes without spending a failure. @@ -243,7 +246,7 @@ export class StructuredAgentSessionUsageLimitContinue { private async send(id: string, cut: Cut): Promise { // Earlier sends take time; moved sources resolve again, once per new witness for every chat. if (!this.holds.attributionCurrent(id, this.deps.host)) { - await this.holds.attribute(id, this.deps.host) + await this.attribute(id, cut) } const record = this.deps.host.store.getRecord(id) if (!record) { diff --git a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-agent-start.ts b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-agent-start.ts index 5a421e7d208..0bf1c96e9bc 100644 --- a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-agent-start.ts +++ b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-agent-start.ts @@ -6,7 +6,7 @@ import type { ProviderDiagnostic } from '../../../../shared/agent-session/failures/agent-session-failure' import type { AgentSessionArgumentProblem } from '../../../../shared/agent-session/agent-session-argument-problem' -import { argumentProblemOf } from '../../structured-agent-arguments-error' +import { argumentProblemOf } from '../../agent-launch/structured-agent-arguments-error' import { agentSessionRefusalFromReference, isAgentSessionRefusalError, diff --git a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-failure-text.ts b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-failure-text.ts index 39efcf77a76..810efd87fb3 100644 --- a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-failure-text.ts +++ b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-failure-text.ts @@ -28,8 +28,8 @@ import { } from '../../../provider-process/provider-executable-missing' import { providerRequestTimeoutOf } from '../../../provider-process/provider-request-timeout' import { findInErrorChain } from '../../../provider-process/provider-error-chain' -import { argumentProblemOf } from '../../structured-agent-arguments-error' -import { agentCliInstallationProblemOf } from '../../agent-cli-installation-error' +import { argumentProblemOf } from '../../agent-launch/structured-agent-arguments-error' +import { agentCliInstallationProblemOf } from '../../agent-launch/agent-cli-installation-error' import { agentCliInstallationFacts } from '../../../../shared/agent-launch/catalog/agent-cli-installation-problem' const TYPED_START_REFUSALS = [ diff --git a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-start-failure.ts b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-start-failure.ts index 3043bb10cbe..8f02eb0997b 100644 --- a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-start-failure.ts +++ b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-start-failure.ts @@ -8,8 +8,8 @@ import { providerLaunchFolderMissing } from '../../../provider-process/provider-executable-missing' import { providerRequestTimeoutOf } from '../../../provider-process/provider-request-timeout' -import { argumentProblemOf } from '../../structured-agent-arguments-error' -import { agentCliInstallationProblemOf } from '../../agent-cli-installation-error' +import { argumentProblemOf } from '../../agent-launch/structured-agent-arguments-error' +import { agentCliInstallationProblemOf } from '../../agent-launch/agent-cli-installation-error' import { AgentSessionAcquisitionRefusal, isAgentSessionPreSpawnError diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-conversation-lifetime.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-conversation-lifetime.ts index 00fb4764507..9719f73690e 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-conversation-lifetime.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-conversation-lifetime.ts @@ -197,6 +197,8 @@ export function createStructuredAgentSessionConversationLifetime( stopStructuredAgentSessionAgentUnderSerialize(host.context(), sessionId, { cause: 'host-stop' }), + startTimed: (sessionId, child) => + host.context().runtimeState.startupAttempts.onClock(sessionId, child), closeConversation: (sessionId) => closeConversation(sessionId, true), logger: deps().logger, ...deps().idleSweep diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-teardown.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-teardown.ts index b60463c44e5..b567556d1d9 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-teardown.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-teardown.ts @@ -3,7 +3,7 @@ import { closeStructuredAgentSessionHandovers } from '../delivery/structured-agent-session-handing-over' import type { AgentSessionResumeTrigger } from '../../../../shared/agent-session/lifecycle/agent-session-resume-marker' -import { SUPERVISED_GRACEFUL_EXIT_MS } from '../../../claude/claude-child-exit-proof-ladder' +import { SUPERVISED_GRACEFUL_EXIT_MS } from '../../../claude/child-process/claude-child-exit-proof-ladder' import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../../../provider-process/provider-process-supervisor' import { SNAPSHOT_DRAIN_TIMEOUT_MS } from './structured-agent-session-eviction' import type { StructuredAgentSessionRestartResume } from '../recovery/structured-agent-session-restart-resume-contract' diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts index c63785f6c78..7460e0bf2c5 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts @@ -37,6 +37,8 @@ export type StructuredAgentSessionIdleSweepDeps = { /** Already inside nonreentrant session serialization. */ stopAgent: (sessionId: string) => Promise stopStartingAgent: (sessionId: string) => Promise + /** Whether the start's own deadline, which runs on awake time, still times this child. */ + startTimed: (sessionId: string, child: RunningChild) => boolean closeConversation: (sessionId: string) => Promise logger: StructuredAgentSessionLogger intervalMs?: number @@ -151,6 +153,10 @@ export class StructuredAgentSessionIdleSweep { if (!session || this.deps.isDisposed()) { return null } + // Wall-clock idle counts sleep, so it never ends a start its own deadline still times. + if (session.child?.phase === 'starting' && this.deps.startTimed(sessionId, session.child)) { + return null + } // Renew owed work every tick to allow a full window for the lead’s post-child wake-up. if (session.child && session.child.phase !== 'starting' && this.owesWork(sessionId, session)) { this.deps.sessions.touch(sessionId) diff --git a/src/main/native-chat/agent-conversation-copy-error.ts b/src/main/native-chat/conversation-adoption/agent-conversation-copy-error.ts similarity index 76% rename from src/main/native-chat/agent-conversation-copy-error.ts rename to src/main/native-chat/conversation-adoption/agent-conversation-copy-error.ts index 64fb08a76f8..a3baa47bc57 100644 --- a/src/main/native-chat/agent-conversation-copy-error.ts +++ b/src/main/native-chat/conversation-adoption/agent-conversation-copy-error.ts @@ -2,8 +2,8 @@ import { AgentSessionRefusalError, refuse, type AgentSessionWireRefusalCode -} from '../../shared/agent-session/failures/agent-session-wire-refusals' -import type { AgentSessionRefusalDetailsByCode } from '../../shared/agent-session/failures/agent-session-refusal-details' +} from '../../../shared/agent-session/failures/agent-session-wire-refusals' +import type { AgentSessionRefusalDetailsByCode } from '../../../shared/agent-session/failures/agent-session-refusal-details' /** Only copy errors authored here may pass through the host's generic provider failure. */ export class AgentConversationCopyError extends Error {} diff --git a/src/main/native-chat/codex-adoption-preparation.ts b/src/main/native-chat/conversation-adoption/codex-adoption-preparation.ts similarity index 82% rename from src/main/native-chat/codex-adoption-preparation.ts rename to src/main/native-chat/conversation-adoption/codex-adoption-preparation.ts index 37c5736d408..34731aaa9c4 100644 --- a/src/main/native-chat/codex-adoption-preparation.ts +++ b/src/main/native-chat/conversation-adoption/codex-adoption-preparation.ts @@ -3,12 +3,12 @@ import { join } from 'node:path' import { isLegacyAgentSessionAccountHome, type AgentSessionAccountHome -} from '../../shared/agent-session/lifecycle/agent-session-account-home' -import type { NativeCodexResumePreparation } from '../codex/history/resume/codex-ai-vault-session-resume' -import { getSystemCodexHomePath } from '../codex/configuration/homes/codex-home-paths' +} from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import type { NativeCodexResumePreparation } from '../../codex/history/resume/codex-ai-vault-session-resume' +import { getSystemCodexHomePath } from '../../codex/configuration/homes/codex-home-paths' import type { StructuredAgentSessionAdoption } from './structured-agent-session-history-adoption' -import { admitTranscriptPath } from './transcript-path-admission' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { admitTranscriptPath } from '../transcript-discovery/transcript-path-admission' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' export async function prepareCodexAdoption( source: StructuredAgentSessionAdoption, diff --git a/src/main/native-chat/structured-agent-cli-conversations.ts b/src/main/native-chat/conversation-adoption/structured-agent-cli-conversations.ts similarity index 91% rename from src/main/native-chat/structured-agent-cli-conversations.ts rename to src/main/native-chat/conversation-adoption/structured-agent-cli-conversations.ts index 467de8bf9ad..427d20c5102 100644 --- a/src/main/native-chat/structured-agent-cli-conversations.ts +++ b/src/main/native-chat/conversation-adoption/structured-agent-cli-conversations.ts @@ -1,13 +1,13 @@ import { isAbsolute } from 'node:path' -import { admitTranscriptPath } from './transcript-path-admission' +import { admitTranscriptPath } from '../transcript-discovery/transcript-path-admission' import { isLegacyAgentSessionAccountHome, type AgentSessionAccountHome -} from '../../shared/agent-session/lifecycle/agent-session-account-home' -import type { AgentSessionProviderHandleLink } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' -import { TUI_AGENT_CONFIG } from '../../shared/agent-launch/catalog/tui-agent-config' -import { sessionIdFromFileName } from '../ai-vault/session-scanner-accumulator' +} from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import type { AgentSessionProviderHandleLink } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AiVaultAgent } from '../../../shared/ai-vault/contracts/ai-vault-types' +import { TUI_AGENT_CONFIG } from '../../../shared/agent-launch/catalog/tui-agent-config' +import { sessionIdFromFileName } from '../../ai-vault/parsing/session-scanner-accumulator' export type StructuredAgentTranscriptImportSettings = { codexManagedAccounts?: readonly { managedHomePath: string }[] diff --git a/src/main/native-chat/structured-agent-cli-source.ts b/src/main/native-chat/conversation-adoption/structured-agent-cli-source.ts similarity index 86% rename from src/main/native-chat/structured-agent-cli-source.ts rename to src/main/native-chat/conversation-adoption/structured-agent-cli-source.ts index 15343324bfc..a0845bb6e3b 100644 --- a/src/main/native-chat/structured-agent-cli-source.ts +++ b/src/main/native-chat/conversation-adoption/structured-agent-cli-source.ts @@ -1,15 +1,15 @@ -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { StructuredAgentSessionResumeSource } from '../../shared/agent-session/structured-agent-session-create' -import type { StructuredAgentId } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { agentSessionRefusalError } from '../../shared/agent-session/failures/agent-session-wire-refusals' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { StructuredAgentSessionResumeSource } from '../../../shared/agent-session/structured-agent-session-create' +import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { agentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' import { adoptsCliConversations, chatAgentsShareConversations, CLI_CONVERSATION_ADOPTING_AGENTS -} from '../../shared/structured-agent-cli-conversation-adoption' -import { isWslUncPath } from '../../shared/wsl-paths' -import { needsWslHostResolution } from './host-readable-transcript-path' -import { parseSshTranscriptPath } from './ssh-transcript-path' +} from '../../../shared/structured-agent-cli-conversation-adoption' +import { isWslUncPath } from '../../../shared/wsl-paths' +import { needsWslHostResolution } from '../transcript-discovery/host-readable-transcript-path' +import { parseSshTranscriptPath } from '../transcript-filesystem/ssh-transcript-path' type CliSource = NonNullable export type StructuredAgentCliSourceRoute = 'native-local' | 'unsupported' | 'unknown' diff --git a/src/main/native-chat/structured-agent-session-history-adoption.ts b/src/main/native-chat/conversation-adoption/structured-agent-session-history-adoption.ts similarity index 85% rename from src/main/native-chat/structured-agent-session-history-adoption.ts rename to src/main/native-chat/conversation-adoption/structured-agent-session-history-adoption.ts index bc092efe416..3a49005bc1b 100644 --- a/src/main/native-chat/structured-agent-session-history-adoption.ts +++ b/src/main/native-chat/conversation-adoption/structured-agent-session-history-adoption.ts @@ -1,20 +1,20 @@ // Resolve credential homes and transcripts from host-owned facts, never client-supplied paths. -import { chatAgentsShareConversations } from '../../shared/structured-agent-cli-conversation-adoption' -import { agentSessionRefusalError } from '../../shared/agent-session/failures/agent-session-wire-refusals' -import type { AgentSessionOperationRow } from '../../shared/agent-session/lifecycle/agent-session-operation-ledger' +import { chatAgentsShareConversations } from '../../../shared/structured-agent-cli-conversation-adoption' +import { agentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' +import type { AgentSessionOperationRow } from '../../../shared/agent-session/lifecycle/agent-session-operation-ledger' import type { AgentSessionProviderHandle, AgentSessionProviderHandleLink, StructuredAgentId -} from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentSessionOwnerObservation } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { agentSessionOwnerObservationIsLive } from '../../shared/agent-session/lifecycle/agent-session-lease-adjudication' +} from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionOwnerObservation } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { agentSessionOwnerObservationIsLive } from '../../../shared/agent-session/lifecycle/agent-session-lease-adjudication' import { agentSessionAccountHomesEqual, type AgentSessionAccountHome -} from '../../shared/agent-session/lifecycle/agent-session-account-home' +} from '../../../shared/agent-session/lifecycle/agent-session-account-home' export type StructuredAgentSessionAdoptionOwnership = { sessionId: string diff --git a/src/main/native-chat/structured-conversation-key.ts b/src/main/native-chat/conversation-adoption/structured-conversation-key.ts similarity index 79% rename from src/main/native-chat/structured-conversation-key.ts rename to src/main/native-chat/conversation-adoption/structured-conversation-key.ts index c6271aa1c3f..3086f1d374e 100644 --- a/src/main/native-chat/structured-conversation-key.ts +++ b/src/main/native-chat/conversation-adoption/structured-conversation-key.ts @@ -1,15 +1,15 @@ import { chatAgentsShareConversations, CLI_CONVERSATION_ADOPTING_AGENTS -} from '../../shared/structured-agent-cli-conversation-adoption' +} from '../../../shared/structured-agent-cli-conversation-adoption' import { agentSessionAccountHomesEqual, type AgentSessionAccountHome -} from '../../shared/agent-session/lifecycle/agent-session-account-home' -import type { AgentSessionProviderHandleLink } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { structuredAgentRuntimeMetadata } from '../runtime/agent-session/installation/structured-agent-runtime-metadata' -import { sessionIdFromFileName } from '../ai-vault/session-scanner-accumulator' +} from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import type { AgentSessionProviderHandleLink } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import { structuredAgentRuntimeMetadata } from '../../runtime/agent-session/installation/structured-agent-runtime-metadata' +import { sessionIdFromFileName } from '../../ai-vault/parsing/session-scanner-accumulator' /** One conversation wherever it is named: the agents sharing its ids, its id (null: a targetless * resume that may pick any of the family's), and its account home (null: the namer can't tell). */ diff --git a/src/main/native-chat/agent-session-context-snapshots.test.ts b/src/main/native-chat/conversation-context/agent-session-context-snapshots.test.ts similarity index 100% rename from src/main/native-chat/agent-session-context-snapshots.test.ts rename to src/main/native-chat/conversation-context/agent-session-context-snapshots.test.ts diff --git a/src/main/native-chat/agent-session-context-snapshots.ts b/src/main/native-chat/conversation-context/agent-session-context-snapshots.ts similarity index 88% rename from src/main/native-chat/agent-session-context-snapshots.ts rename to src/main/native-chat/conversation-context/agent-session-context-snapshots.ts index 33693cffe1f..8eb6f6796ea 100644 --- a/src/main/native-chat/agent-session-context-snapshots.ts +++ b/src/main/native-chat/conversation-context/agent-session-context-snapshots.ts @@ -2,12 +2,12 @@ import { createHash, randomUUID } from 'node:crypto' import { rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' -import { runKeyedSerializedOperation } from '../../shared/concurrency/keyed-serialized-operations' -import { renameFileWithWindowsRetryAsync } from '../../shared/windows-retry-file-operations' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' +import { renameFileWithWindowsRetryAsync } from '../../../shared/windows-retry-file-operations' import { ensureOwnedTempStagingRoot, getOwnedTempStagingRoot -} from '../window/owned-temp-staging-root' +} from '../../filesystem/owned-temp-staging-root' const claims = new Map() const publications = new Map>() diff --git a/src/main/native-chat/agent-session-saved-prompt-text.ts b/src/main/native-chat/conversation-context/agent-session-saved-prompt-text.ts similarity index 78% rename from src/main/native-chat/agent-session-saved-prompt-text.ts rename to src/main/native-chat/conversation-context/agent-session-saved-prompt-text.ts index 42d144bcd91..798db1df28a 100644 --- a/src/main/native-chat/agent-session-saved-prompt-text.ts +++ b/src/main/native-chat/conversation-context/agent-session-saved-prompt-text.ts @@ -1,16 +1,16 @@ import type { AgentJournalRenderItem, AgentJournalQuestionItem -} from '../../shared/agent-session/journal/agent-session-journal-types' -import { agentJournalItemRowOrigin } from '../../shared/agent-session/journal/agent-session-journal-position' -import { agentJournalLinkageFields } from '../../shared/agent-session/journal/agent-session-journal-producer' +} from '../../../shared/agent-session/journal/agent-session-journal-types' +import { agentJournalItemRowOrigin } from '../../../shared/agent-session/journal/agent-session-journal-position' +import { agentJournalLinkageFields } from '../../../shared/agent-session/journal/agent-session-journal-producer' import { agentSessionPromptQuestions, legacyAgentSessionQuestionAnswers -} from '../../shared/agent-session/agent-session-question-answer' -import { nativeChatReceiptAnswers } from '../../shared/native-chat/native-chat-resolution-receipt' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { projectStructuredItemToNativeChat } from '../../shared/agent-session/view/structured-agent-session-projection' +} from '../../../shared/agent-session/agent-session-question-answer' +import { nativeChatReceiptAnswers } from '../../../shared/native-chat/native-chat-resolution-receipt' +import type { NativeChatMessage } from '../../../shared/native-chat/native-chat-types' +import { projectStructuredItemToNativeChat } from '../../../shared/agent-session/view/structured-agent-session-projection' function questionInterpretation(body: AgentJournalQuestionItem): string[] { if (body.resolution.state !== 'resolved') { diff --git a/src/main/native-chat/native-chat-media-path.test.ts b/src/main/native-chat/conversation-files/native-chat-media-path.test.ts similarity index 90% rename from src/main/native-chat/native-chat-media-path.test.ts rename to src/main/native-chat/conversation-files/native-chat-media-path.test.ts index 9c737cf047b..b6fc677790a 100644 --- a/src/main/native-chat/native-chat-media-path.test.ts +++ b/src/main/native-chat/conversation-files/native-chat-media-path.test.ts @@ -2,20 +2,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { agentSessionRecordFixture } from './agent-session-record-test-fixture' +import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { agentSessionRecordFixture } from '../testing/agent-session-record-test-fixture' import { clearGrokSessionPathLookupCacheForTests, grokEncodedCwdDirName -} from '../../shared/grok-session-paths' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +} from '../../../shared/grok-session-paths' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import { resolveNativeChatMediaPath, type NativeChatMediaPathRequest } from './native-chat-media-path' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) let root: string let home: string diff --git a/src/main/native-chat/native-chat-media-path.ts b/src/main/native-chat/conversation-files/native-chat-media-path.ts similarity index 83% rename from src/main/native-chat/native-chat-media-path.ts rename to src/main/native-chat/conversation-files/native-chat-media-path.ts index 90c9a763bb9..ebdaf0796c9 100644 --- a/src/main/native-chat/native-chat-media-path.ts +++ b/src/main/native-chat/conversation-files/native-chat-media-path.ts @@ -1,25 +1,25 @@ import { lstat } from 'node:fs/promises' import { basename, dirname, isAbsolute, join } from 'node:path' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { isLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { MAX_AGENT_SESSION_PROVIDER_HANDLE_LINKS } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { structuredAgentSessionTabId } from '../../shared/agent-session/view/structured-agent-session-projection' -import type { RuntimeNativeChatFileContext } from '../../shared/native-chat/native-chat-file-context' -import type { ExecutionHostId } from '../../shared/execution-host' -import { parsePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { AgentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { isLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import { MAX_AGENT_SESSION_PROVIDER_HANDLE_LINKS } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { structuredAgentSessionTabId } from '../../../shared/agent-session/view/structured-agent-session-projection' +import type { RuntimeNativeChatFileContext } from '../../../shared/native-chat/native-chat-file-context' +import type { ExecutionHostId } from '../../../shared/execution-host' +import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { findGrokChatHistoryByCwd, findGrokChatHistoryBySessionId, GROK_CHAT_HISTORY_FILE, isSafeGrokSessionId, resolveGrokSessionsDir -} from '../../shared/grok-session-paths' -import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' -import { needsWslHostResolution } from './host-readable-transcript-path' -import { parseWslPath } from '../wsl/filesystem/unc-path-access' -import { admitTranscriptPath } from './transcript-path-admission' +} from '../../../shared/grok-session-paths' +import { readNodeFileWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' +import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' +import { needsWslHostResolution } from '../transcript-discovery/host-readable-transcript-path' +import { parseWslPath } from '../../wsl/filesystem/unc-path-access' +import { admitTranscriptPath } from '../transcript-discovery/transcript-path-admission' export type NativeChatMediaPathResolution = | { kind: 'matched'; absolutePath: string } diff --git a/src/main/native-chat/native-chat-scratch-folder-migration.test.ts b/src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.test.ts similarity index 98% rename from src/main/native-chat/native-chat-scratch-folder-migration.test.ts rename to src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.test.ts index ff7be62703e..9cd6fb6ffb6 100644 --- a/src/main/native-chat/native-chat-scratch-folder-migration.test.ts +++ b/src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.test.ts @@ -40,7 +40,7 @@ vi.mock('node:fs/promises', async (importOriginal) => { } } }) -import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionLogger } from '../agent-session-wire/host/structured-agent-session-logger' import { nativeChatScratchFolderFor, nativeChatScratchRootFor } from './native-chat-scratch-folder' import { migrateLegacyNativeChatVisualsFolders } from './native-chat-scratch-folder-migration' import { readNativeChatVisualFile } from './native-chat-visual-file-read' diff --git a/src/main/native-chat/native-chat-scratch-folder-migration.ts b/src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.ts similarity index 95% rename from src/main/native-chat/native-chat-scratch-folder-migration.ts rename to src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.ts index 107d0c3859c..baab3168329 100644 --- a/src/main/native-chat/native-chat-scratch-folder-migration.ts +++ b/src/main/native-chat/conversation-files/native-chat-scratch-folder-migration.ts @@ -4,8 +4,8 @@ import { constants } from 'node:fs' import { copyFile, lstat, mkdir, mkdtemp, readdir, rename, rmdir, unlink } from 'node:fs/promises' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import type { StructuredAgentSessionLogger } from '../agent-session-wire/host/structured-agent-session-logger' import { isNativeChatScratchFolderName, nativeChatScratchRootFor diff --git a/src/main/native-chat/native-chat-scratch-folder.ts b/src/main/native-chat/conversation-files/native-chat-scratch-folder.ts similarity index 100% rename from src/main/native-chat/native-chat-scratch-folder.ts rename to src/main/native-chat/conversation-files/native-chat-scratch-folder.ts diff --git a/src/main/native-chat/native-chat-visual-file-read.test.ts b/src/main/native-chat/conversation-files/native-chat-visual-file-read.test.ts similarity index 100% rename from src/main/native-chat/native-chat-visual-file-read.test.ts rename to src/main/native-chat/conversation-files/native-chat-visual-file-read.test.ts diff --git a/src/main/native-chat/native-chat-visual-file-read.ts b/src/main/native-chat/conversation-files/native-chat-visual-file-read.ts similarity index 95% rename from src/main/native-chat/native-chat-visual-file-read.ts rename to src/main/native-chat/conversation-files/native-chat-visual-file-read.ts index b91968a7768..5e1236d4f57 100644 --- a/src/main/native-chat/native-chat-visual-file-read.ts +++ b/src/main/native-chat/conversation-files/native-chat-visual-file-read.ts @@ -7,13 +7,13 @@ import { basename, dirname, join } from 'node:path' import { NATIVE_CHAT_VISUAL_MAX_BYTES, isNativeChatVisualFileName -} from '../../shared/native-chat/native-chat-visual-directive' +} from '../../../shared/native-chat/native-chat-visual-directive' import type { AgentSessionReadVisualResult, AgentSessionVisualReadError -} from '../../shared/rpc-contract/agent-session-visual-params' -import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' -import { readLocalFileBounded } from '../ipc/filesystem/local-regular-file-read' +} from '../../../shared/rpc-contract/structured-agent-session/agent-session-visual-params' +import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' +import { readLocalFileBounded } from '../../ipc/filesystem/local-regular-file-read' // O_NOFOLLOW prevents final-component swaps; Windows relies on lstat and post-open identity checks. const VISUAL_OPEN_FLAGS = diff --git a/src/main/native-chat/native-chat-visual-guest-location.ts b/src/main/native-chat/conversation-files/native-chat-visual-guest-location.ts similarity index 81% rename from src/main/native-chat/native-chat-visual-guest-location.ts rename to src/main/native-chat/conversation-files/native-chat-visual-guest-location.ts index 11e97d17162..0f5152e1897 100644 --- a/src/main/native-chat/native-chat-visual-guest-location.ts +++ b/src/main/native-chat/conversation-files/native-chat-visual-guest-location.ts @@ -1,8 +1,8 @@ import { basename, dirname } from 'node:path' import { fileURLToPath } from 'node:url' -import { isNativeChatVisualFileName } from '../../shared/native-chat/native-chat-visual-directive' -import { parseDocPreviewUrl } from '../../shared/document-preview/doc-preview-scheme' -import { getDocPreviewGrant } from '../browser/document-preview/doc-preview-grant-registry' +import { isNativeChatVisualFileName } from '../../../shared/native-chat/native-chat-visual-directive' +import { parseDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme' +import { getDocPreviewGrant } from '../../browser/document-preview/doc-preview-grant-registry' /** Presentation identity only; existing file/grant policies still own every read. */ export function isNativeChatVisualGuestLocation(url: string, scratchRoot: string): boolean { diff --git a/src/main/native-chat/native-chat-visuals-delivery.ts b/src/main/native-chat/conversation-files/native-chat-visuals-delivery.ts similarity index 95% rename from src/main/native-chat/native-chat-visuals-delivery.ts rename to src/main/native-chat/conversation-files/native-chat-visuals-delivery.ts index da9309efbd6..22a111552e4 100644 --- a/src/main/native-chat/native-chat-visuals-delivery.ts +++ b/src/main/native-chat/conversation-files/native-chat-visuals-delivery.ts @@ -1,7 +1,7 @@ // Best-effort visual setup must never prevent chat startup. import { mkdir } from 'node:fs/promises' -import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionLogger } from '../agent-session-wire/host/structured-agent-session-logger' import { nativeChatScratchFolderFor } from './native-chat-scratch-folder' import { resolveNativeChatVisualsSkillLocation, diff --git a/src/main/native-chat/native-chat-visuals-skill-location.ts b/src/main/native-chat/conversation-files/native-chat-visuals-skill-location.ts similarity index 96% rename from src/main/native-chat/native-chat-visuals-skill-location.ts rename to src/main/native-chat/conversation-files/native-chat-visuals-skill-location.ts index 05b3c6e2489..5afc5b201af 100644 --- a/src/main/native-chat/native-chat-visuals-skill-location.ts +++ b/src/main/native-chat/conversation-files/native-chat-visuals-skill-location.ts @@ -2,7 +2,7 @@ import { access } from 'node:fs/promises' import { join } from 'node:path' -import { getAppEnvironment, hasAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment, hasAppEnvironment } from '../../../shared/app-environment' const PLUGIN_DIR_NAME = 'native-chat-visuals' export const NATIVE_CHAT_VISUALS_SKILL_NAME = 'orca-chat-visuals' diff --git a/src/main/native-chat/native-chat-visuals-sweep.test.ts b/src/main/native-chat/conversation-files/native-chat-visuals-sweep.test.ts similarity index 97% rename from src/main/native-chat/native-chat-visuals-sweep.test.ts rename to src/main/native-chat/conversation-files/native-chat-visuals-sweep.test.ts index 0b7375771d2..4309e9d291c 100644 --- a/src/main/native-chat/native-chat-visuals-sweep.test.ts +++ b/src/main/native-chat/conversation-files/native-chat-visuals-sweep.test.ts @@ -14,7 +14,7 @@ import { import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionLogger } from '../agent-session-wire/host/structured-agent-session-logger' import { nativeChatScratchFolderFor, nativeChatScratchRootFor } from './native-chat-scratch-folder' import { sweepNativeChatVisualsFolders, diff --git a/src/main/native-chat/native-chat-visuals-sweep.ts b/src/main/native-chat/conversation-files/native-chat-visuals-sweep.ts similarity index 93% rename from src/main/native-chat/native-chat-visuals-sweep.ts rename to src/main/native-chat/conversation-files/native-chat-visuals-sweep.ts index f91b0fac9cd..f85aa9b33f5 100644 --- a/src/main/native-chat/native-chat-visuals-sweep.ts +++ b/src/main/native-chat/conversation-files/native-chat-visuals-sweep.ts @@ -4,9 +4,9 @@ import type { Dirent } from 'node:fs' import { lstat, readdir, rm } from 'node:fs/promises' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { yieldToEventLoop } from '../../shared/event-loop-yield' -import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import { yieldToEventLoop } from '../../../shared/event-loop-yield' +import type { StructuredAgentSessionLogger } from '../agent-session-wire/host/structured-agent-session-logger' import { isNativeChatScratchFolderName, nativeChatScratchFolderName, diff --git a/src/main/native-chat/structured-chat-name-publication.ts b/src/main/native-chat/conversation-naming/structured-chat-name-publication.ts similarity index 93% rename from src/main/native-chat/structured-chat-name-publication.ts rename to src/main/native-chat/conversation-naming/structured-chat-name-publication.ts index f344d0fc605..ee3d3c22ce7 100644 --- a/src/main/native-chat/structured-chat-name-publication.ts +++ b/src/main/native-chat/conversation-naming/structured-chat-name-publication.ts @@ -1,5 +1,5 @@ -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import type { StructuredChatNamingDeps } from './structured-chat-naming' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { StructuredChatNamingDeps } from './structured-chat-naming-types' export async function runStructuredChatNameGeneration(input: { automaticTitle?: Parameters[3] diff --git a/src/main/native-chat/conversation-naming/structured-chat-naming-types.ts b/src/main/native-chat/conversation-naming/structured-chat-naming-types.ts new file mode 100644 index 00000000000..f476ff55552 --- /dev/null +++ b/src/main/native-chat/conversation-naming/structured-chat-naming-types.ts @@ -0,0 +1,52 @@ +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { AgentSessionRecordStore } from '../../runtime/agent-session/records/agent-session-record-store' +import type { AgentGenerationFailureOutput } from '../../text-generation/failures/agent-failure-output' +import type { StructuredAgentSessionLogger } from '../agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionAdapter } from '../agent-session-wire/providers/structured-agent-session-adapter' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' + +export type AutomaticChatTitle = { + owner: ReturnType> + pending?: { + ready: Promise + ended: () => boolean + recheck: () => void + unavailable: (journal: AgentSessionJournal) => void + dispose: () => void + } + retainOwnership?: (isCurrent: (record: AgentSessionRecord) => boolean) => void +} + +/** null means unavailable/canceled: no failure to display or retry. */ +export type StructuredChatNameGeneration = + | { name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } + | { error: string; errorCode?: string; failureOutput?: AgentGenerationFailureOutput } + | null + +export type StructuredChatNamingDeps = { + getStore: () => Pick< + AgentSessionRecordStore, + 'getRecord' | 'compareAndSetConversationName' | 'setUserConversationName' + > | null + getSettings: () => Pick + readFirstPrompt: (sessionId: string, hostStartedAt: number) => Promise + /** The current context's first prompt, for a name the user asked for again. */ + readJournalFirstPrompt: (sessionId: string) => Promise + now?: () => number + workerTaskTitle: (record: AgentSessionRecord) => { title: string } | null + captureAutomaticTitle?: ( + record: AgentSessionRecord, + firstInputSubmissionKey?: string, + applicable?: () => boolean + ) => AutomaticChatTitle | undefined + generate: ( + record: AgentSessionRecord, + firstPrompt: string, + shouldExecute?: () => boolean, + automaticTitle?: AutomaticChatTitle + ) => Promise + onNamed: (workspaceId: string, sessionId: string) => void + logger: StructuredAgentSessionLogger + wait?: (ms: number) => Promise +} diff --git a/src/main/native-chat/structured-chat-naming-work.ts b/src/main/native-chat/conversation-naming/structured-chat-naming-work.ts similarity index 96% rename from src/main/native-chat/structured-chat-naming-work.ts rename to src/main/native-chat/conversation-naming/structured-chat-naming-work.ts index c3a9ab0f345..bcbcdf63c2e 100644 --- a/src/main/native-chat/structured-chat-naming-work.ts +++ b/src/main/native-chat/conversation-naming/structured-chat-naming-work.ts @@ -1,6 +1,6 @@ -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' import type { AutomaticChatTitle, StructuredChatNamingDeps } from './structured-chat-naming-types' -import type { AgentSessionJournal } from './agent-session-journal/journal-store' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' export type NamingRequest = { record: AgentSessionRecord diff --git a/src/main/native-chat/structured-chat-title-handover.ts b/src/main/native-chat/conversation-naming/structured-chat-title-handover.ts similarity index 92% rename from src/main/native-chat/structured-chat-title-handover.ts rename to src/main/native-chat/conversation-naming/structured-chat-title-handover.ts index ecd72d6daad..9054e7aa278 100644 --- a/src/main/native-chat/structured-chat-title-handover.ts +++ b/src/main/native-chat/conversation-naming/structured-chat-title-handover.ts @@ -1,7 +1,7 @@ -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { sessionCrewChanges } from '../runtime/orchestration/crew/crew-changes' -import type { StructuredAgentSessionHost } from './agent-session-wire/host/structured-agent-session-host' -import type { JournalPublication } from './agent-session-wire/host/structured-agent-session-conversations' +import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import { sessionCrewChanges } from '../../runtime/orchestration/crew/crew-changes' +import type { StructuredAgentSessionHost } from '../agent-session-wire/host/structured-agent-session-host' +import type { JournalPublication } from '../agent-session-wire/host/structured-agent-session-conversations' import type { AutomaticChatTitle } from './structured-chat-naming-types' export function deferredStructuredChatTitle(input: { diff --git a/src/main/native-chat/native-chat-inline-visuals-setting.test.ts b/src/main/native-chat/native-chat-inline-visuals-setting.test.ts deleted file mode 100644 index 735680d7f1a..00000000000 --- a/src/main/native-chat/native-chat-inline-visuals-setting.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { - createClaudeStructuredLaunchResolver, - createCodexStructuredLaunchResolver -} from '../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { existsSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { CLAUDE_PLUGIN_DIR_FLAG, type ClaudeCliFlag } from '../claude/claude-cli-flag-support' -import { - acquireReadyCodexForTest, - adapterFor, - fakeCodex, - identityFor -} from '../codex/structured/session-lifecycle/codex-structured-session-adapter-fixture' -import { agentSessionRecordFixture } from './agent-session-record-test-fixture' -import { - createNativeChatVisualsDelivery, - NATIVE_CHAT_SCRATCH_DIR_ENV -} from './native-chat-visuals-delivery' -import { nativeChatScratchFolderFor } from './native-chat-scratch-folder' - -const SKILL = { pluginDir: '/app/plugin', skillsRoot: '/app/plugin/skills' } -const scratch: string[] = [] -afterEach(() => { - for (const dir of scratch.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function delivery(isEnabled: () => boolean) { - const stateDirectory = mkdtempSync(join(tmpdir(), 'orca-visuals-setting-')) - scratch.push(stateDirectory) - const prepareVisuals = createNativeChatVisualsDelivery({ - stateDirectory, - logger: { warn: vi.fn(), error: vi.fn() }, - isEnabled, - resolveSkill: async () => SKILL - }) - return { stateDirectory, prepareVisuals } -} - -describe('inline visuals launch preference', () => { - it('starts Claude without visuals while preserving configured plugins, user folders and attachment access', async () => { - const sessionId = 'claude-disabled' - const { stateDirectory, prepareVisuals } = delivery(() => false) - const check = vi.fn(async (_flag: ClaudeCliFlag) => 'supported' as const) - const record = agentSessionRecordFixture({ sessionId }) - const launch = await createClaudeStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveWorkspacePath: async () => '/repo', - resolveCommand: () => ({ command: '/bin/claude', prefixArgs: [] }), - resolveAuthPolicy: () => ({ account: 'system' }), - resolveLaunchArgs: () => ['--add-dir', '/user/notes', '--plugin-dir', '/user/plugin'], - resolveEnv: () => ({ [NATIVE_CHAT_SCRATCH_DIR_ENV]: '/inherited', KEEP: 'yes' }), - resolveInheritedEnv: async () => ({ PATH: '/bin' }), - attachmentDirectory: '/state/agent-session-attachments', - hasTranscript: async () => false, - cliFlags: { check }, - prepareVisuals - })({ identity: { ...identityFor(sessionId), agent: 'claude', providerHandle: null } }) - expect(launch.options).not.toHaveProperty('plugins') - expect(launch.options.extraArgs).toHaveProperty('plugin-dir', '/user/plugin') - expect(launch.options.additionalDirectories).toEqual([ - '/user/notes', - '/state/agent-session-attachments' - ]) - expect(launch.env).not.toHaveProperty(NATIVE_CHAT_SCRATCH_DIR_ENV) - expect(launch.env?.KEEP).toBe('yes') - expect(check.mock.calls.map(([flag]) => flag)).not.toContain(CLAUDE_PLUGIN_DIR_FLAG) - expect(existsSync(nativeChatScratchFolderFor(stateDirectory, sessionId))).toBe(false) - }) - - it('gives new Codex chats the current preference without changing another live chat', async () => { - let enabled = true - const { stateDirectory, prepareVisuals } = delivery(() => enabled) - const codex = fakeCodex({ - 'config/read': () => ({ - config: { sandbox_workspace_write: { writable_roots: ['/user/notes'] } } - }) - }) - const resolveLaunch = createCodexStructuredLaunchResolver({ - store: { - getRecord: (sessionId) => - agentSessionRecordFixture({ - sessionId, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: '/home/codex' } - }), - pinLaunchDirectory: vi.fn() - }, - resolveWorkspacePath: async () => '/repo', - resolveCommand: () => ({ command: '/bin/codex', prefixArgs: [] }), - resolveLaunchArgs: () => [], - resolveEnvironment: async () => ({ - [NATIVE_CHAT_SCRATCH_DIR_ENV]: '/inherited', - KEEP: 'yes' - }), - prepareVisuals - }) - const adapter = adapterFor(codex, {}, [], { resolveLaunch }) - const start = (sessionId: string) => - acquireReadyCodexForTest(adapter, { - identity: { - ...identityFor(sessionId), - hostId: LOCAL_EXECUTION_HOST_ID, - providerHandle: null - }, - fence: 1, - spawnToken: sessionId - }) - try { - await start('first') - const first = codex.connections[0]! - const firstCalls = [...first.calls] - const firstFolder = nativeChatScratchFolderFor(stateDirectory, 'first') - expect(first.launch.env?.[NATIVE_CHAT_SCRATCH_DIR_ENV]).toBe(firstFolder) - expect(first.calls.find(({ method }) => method === 'thread/start')?.params).toMatchObject({ - config: { 'sandbox_workspace_write.writable_roots': ['/user/notes', firstFolder] } - }) - - enabled = false - await start('disabled') - const disabled = codex.connections[1]! - expect(disabled.launch.env).not.toHaveProperty(NATIVE_CHAT_SCRATCH_DIR_ENV) - expect(disabled.launch.env?.KEEP).toBe('yes') - expect(disabled.calls.map(({ method }) => method)).not.toContain('skills/extraRoots/set') - const openIndex = disabled.calls.findIndex(({ method }) => method === 'thread/start') - expect(disabled.calls.slice(0, openIndex).map(({ method }) => method)).not.toContain( - 'config/read' - ) - const disabledOpen = disabled.calls.find(({ method }) => method === 'thread/start') - const scratchDirOverride = `shell_environment_policy.set.${NATIVE_CHAT_SCRATCH_DIR_ENV}` - expect(disabledOpen?.params?.config).not.toHaveProperty([ - 'sandbox_workspace_write.writable_roots' - ]) - expect(disabledOpen?.params?.config).not.toHaveProperty([scratchDirOverride]) - expect(existsSync(nativeChatScratchFolderFor(stateDirectory, 'disabled'))).toBe(false) - expect(first.closed).toBe(false) - expect(first.calls).toEqual(firstCalls) - - enabled = true - await start('reenabled') - const reenabled = codex.connections[2]! - expect( - reenabled.calls.find(({ method }) => method === 'skills/extraRoots/set')?.params - ).toEqual({ extraRoots: [SKILL.skillsRoot] }) - expect(reenabled.launch.env?.[NATIVE_CHAT_SCRATCH_DIR_ENV]).toBe( - nativeChatScratchFolderFor(stateDirectory, 'reenabled') - ) - expect(first.closed).toBe(false) - expect(first.calls).toEqual(firstCalls) - } finally { - await adapter.closeAll() - } - }) -}) diff --git a/src/main/window/native-chat-paste-files.test.ts b/src/main/native-chat/paste-files/native-chat-paste-files.test.ts similarity index 94% rename from src/main/window/native-chat-paste-files.test.ts rename to src/main/native-chat/paste-files/native-chat-paste-files.test.ts index 77498786878..22f09399e3f 100644 --- a/src/main/window/native-chat-paste-files.test.ts +++ b/src/main/native-chat/paste-files/native-chat-paste-files.test.ts @@ -2,11 +2,11 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSyn import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import type { Store } from '../persistence/loading-store/store' -import { resolveLocalFileRequestPath } from '../ipc/filesystem/access/local-file-access-resolution' -import { readLocalFileContent } from '../ipc/filesystem/filesystem-file-content-inspection' +import type { Store } from '../../persistence/loading-store/store' +import { resolveLocalFileRequestPath } from '../../ipc/filesystem/access/local-file-access-resolution' +import { readLocalFileContent } from '../../ipc/filesystem/filesystem-file-content-inspection' import { restoreNativeChatPastes } from './native-chat-paste-files' // A store with no projects: nothing but an access kind decides what a read may reach. diff --git a/src/main/window/native-chat-paste-files.ts b/src/main/native-chat/paste-files/native-chat-paste-files.ts similarity index 95% rename from src/main/window/native-chat-paste-files.ts rename to src/main/native-chat/paste-files/native-chat-paste-files.ts index fbe384593f7..4f224ba322c 100644 --- a/src/main/window/native-chat-paste-files.ts +++ b/src/main/native-chat/paste-files/native-chat-paste-files.ts @@ -2,8 +2,8 @@ import { lstat, realpath, stat } from 'node:fs/promises' import path from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' -import { NATIVE_CHAT_PASTE_FOLDER } from '../../shared/native-chat/input/native-chat-paste-folder' +import { getAppEnvironment } from '../../../shared/app-environment' +import { NATIVE_CHAT_PASTE_FOLDER } from '../../../shared/native-chat/input/native-chat-paste-folder' const MAX_RESTORED_PASTES = 256 diff --git a/src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts b/src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts index dc8f9949c61..6b6fba4f727 100644 --- a/src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts +++ b/src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as WslRunningPathFilterModule from '../wsl/filesystem/wsl-running-path-filter' -import type * as WslTranscriptFsGateModule from './wsl-transcript-fs-gate' +import type * as WslTranscriptFsGateModule from './transcript-filesystem/wsl-transcript-fs-gate' const WSL_SESSIONS_DIR = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions' const DEBIAN_SESSIONS_DIR = '\\\\wsl.localhost\\Debian\\home\\ada\\.codex\\sessions' @@ -22,11 +22,11 @@ const mocks = vi.hoisted(() => ({ ) })) -vi.mock('./wsl-transcript-fs-gate', async (importOriginal) => ({ +vi.mock('./transcript-filesystem/wsl-transcript-fs-gate', async (importOriginal) => ({ ...(await importOriginal()), runWslTranscriptFsTask: mocks.gate })) -vi.mock('../ai-vault/session-scanner-discovery', () => ({ +vi.mock('../ai-vault/discovery/session-scanner-discovery', () => ({ walkSessionFiles: mocks.walk, forEachSessionFile: async ( dir: string, @@ -41,7 +41,9 @@ vi.mock('../ai-vault/session-scanner-discovery', () => ({ } })) // These cases cover root and path policy; the E9 gate has its own suite. -vi.mock('./wsl-transcript-running-admission', () => ({ admitWslTranscriptPath: async () => {} })) +vi.mock('./transcript-filesystem/wsl-transcript-running-admission', () => ({ + admitWslTranscriptPath: async () => {} +})) vi.mock('../wsl/discovery/wsl-home-unless-stopped', async () => { const wsl = await import('../wsl/discovery/distro-catalog') return { @@ -60,7 +62,7 @@ vi.mock('../wsl/filesystem/wsl-running-path-filter', async (importOriginal) => ( })) import { resolveSessionFilePath } from './session-file-resolver' -import { WslTranscriptFsError } from './wsl-transcript-fs-gate' +import { WslTranscriptFsError } from './transcript-filesystem/wsl-transcript-fs-error' const realPlatform = process.platform @@ -128,18 +130,6 @@ describe('Codex WSL scan gate', () => { expect(mocks.walk).not.toHaveBeenCalled() }) - it('skips running-distro roots when a host hook path is not flushed yet', async () => { - await expect( - resolveSessionFilePath('codex', 'session-id', { - transcriptPath: `${LOCAL_SESSIONS_DIR}\\2026\\rollout-1-session-id.jsonl` - }) - ).resolves.toBeNull() - - expect(mocks.walk).toHaveBeenCalled() - expect(mocks.walk.mock.calls.some(([dir]) => dir.startsWith('\\\\wsl'))).toBe(false) - expect(mocks.gate).not.toHaveBeenCalled() - }) - it('reports the abort, not a refusal, when the hook-path probe races a caller abort', async () => { const controller = new AbortController() const abortReason = new Error('caller went away') diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index 5c45188e22c..b878a53497c 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -7,13 +7,13 @@ import { type NativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' import { isWslUncPath } from '../../shared/wsl-paths' -import { forEachSessionFile } from '../ai-vault/session-scanner-discovery' +import { forEachSessionFile } from '../ai-vault/discovery/session-scanner-discovery' import { claudeProjectsHostDirs, codexHomeSessionsDir, ompSessionsRootDirs, uniqueDirs -} from '../ai-vault/session-scanner-roots' +} from '../ai-vault/discovery/session-scanner-roots' import { resolveOrcaManagedCodexHomePath } from '../codex/configuration/homes/codex-home-paths' import { findGrokChatHistoryBySessionId, @@ -24,12 +24,16 @@ import { needsWslHostResolution, toHostReadableTranscriptPath, wslAgentSessionsDirs -} from './host-readable-transcript-path' -import { SESSION_FILE_ID_LAYOUTS, type SessionIdLookupAgent } from './session-file-id-layouts' -import { findWslSessionPath } from './wsl-session-path-scan' -import { findClaudeSessionFile } from './session-file-resolver-claude-probe' -import { parseSshTranscriptPath } from './ssh-transcript-path' -import { wslTranscriptFsRefusal, type WslTranscriptFsError } from './wsl-transcript-fs-gate' +} from './transcript-discovery/host-readable-transcript-path' +import { + SESSION_FILE_ID_LAYOUTS, + type SessionIdLookupAgent +} from './transcript-discovery/session-file-id-layouts' +import { findWslSessionPath } from './transcript-discovery/wsl-session-path-scan' +import { findClaudeSessionFile } from './transcript-discovery/session-file-resolver-claude-probe' +import { parseSshTranscriptPath } from './transcript-filesystem/ssh-transcript-path' +import { wslTranscriptFsRefusal } from './transcript-filesystem/wsl-transcript-fs-error' +import type { WslTranscriptFsError } from './transcript-filesystem/wsl-transcript-fs-error' // Read shared discovery roots per call; preference order prevents cross-account matches. function claudeProjectsDirs(): string[] { diff --git a/src/main/native-chat/structured-agent-configured-args.ts b/src/main/native-chat/structured-agent-configured-args.ts deleted file mode 100644 index 376e9fb2643..00000000000 --- a/src/main/native-chat/structured-agent-configured-args.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { projectAgentLaunchProfile } from '../../shared/agent-launch/choices/agent-launch-profile' -import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { - resolveTuiAgentLaunchArgs, - type AgentLaunchProfileSettings -} from '../../shared/agent-launch/choices/tui-agent-launch-defaults' -import { tokenizeStartupCommand } from '../../shared/agent-launch/startup/tui-agent-startup-shell' -import { resolveLocalWindowsAgentStartupShell } from '../../shared/windows-terminal-shell' - -/** Match terminal argument grouping before filtering provider-owned flags. */ -export function structuredAgentConfiguredArgs( - agent: string, - settings: AgentLaunchProfileSettings & Partial>, - platform: NodeJS.Platform = process.platform -): string[] { - const shell = - resolveLocalWindowsAgentStartupShell({ - platform, - isRemote: false, - terminalWindowsShell: settings.terminalWindowsShell - }) ?? 'posix' - const parsed = tokenizeStartupCommand( - isTuiAgent(agent) - ? projectAgentLaunchProfile( - agent, - { ...settings, agentLaunchChoices: undefined }, - { target: 'structured', shell } - ).args - : resolveTuiAgentLaunchArgs(agent, settings), - shell - ) - if (!parsed.ok) { - throw new Error(`${agent} Arguments are invalid: ${parsed.error}`) - } - return parsed.tokens -} diff --git a/src/main/native-chat/structured-chat-naming-title.test.ts b/src/main/native-chat/structured-chat-naming-title.test.ts deleted file mode 100644 index fbc58ba7566..00000000000 --- a/src/main/native-chat/structured-chat-naming-title.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { - createStructuredChatNamingHandler, - type StructuredChatNamingDeps -} from './structured-chat-naming' -import { agentSessionRecordFixture } from './agent-session-record-test-fixture' -import { - compareAndSetAgentSessionRecordName, - setAgentSessionRecordUserName -} from '../runtime/agent-session/records/agent-session-record-conversation-name' - -function rig( - generate: StructuredChatNamingDeps['generate'], - captureAutomaticTitle: StructuredChatNamingDeps['captureAutomaticTitle'] = () => ({ owner: null }) -) { - let record = agentSessionRecordFixture({ sessionId: 'chat-1' }) - let beforeWrite: (() => Promise) | undefined - const handler = createStructuredChatNamingHandler({ - getStore: () => ({ - getRecord: () => record, - compareAndSetConversationName: async (_id, name, expected, context, applicable) => - compareAndSetAgentSessionRecordName( - async (apply) => { - if (expected !== null) { - await beforeWrite?.() - } - record = apply(record) - return record - }, - name, - expected, - context, - applicable - ), - setUserConversationName: async (_id, name, write) => { - const result = setAgentSessionRecordUserName(record, name, write, 1) - record = result.record - return result - } - }), - getSettings: () => ({ nativeChatAutoName: true }), - readFirstPrompt: async () => 'Repair login', - readJournalFirstPrompt: async () => 'Repair login', - workerTaskTitle: () => null, - generate, - captureAutomaticTitle, - wait: async () => {}, - onNamed: () => {}, - logger: { warn: vi.fn(), error: vi.fn() } - }) - return { - handler, - record: () => record, - beforeWrite: (run: () => Promise) => { - beforeWrite = run - }, - start: () => - handler( - { - sessionId: 'chat-1', - workspaceId: 'workspace-1', - agent: 'claude', - status: 'working', - latestPrompt: 'Repair login', - updatedAt: 1 - }, - { replay: false, firstInputSubmissionKey: 'input-1' } - ), - done: () => vi.waitFor(() => expect(handler.activeSessionIds()).toEqual([])) - } -} - -it('tries CLI reuse once while independent generation retries, and skips it on manual regeneration', async () => { - const reuse = vi.fn() - const generate = vi.fn( - async (_record, _prompt, _current, automatic) => { - if (automatic) { - reuse() - } - return generate.mock.calls.length === 1 - ? { error: 'Retry independent generation' } - : { name: 'Login repair' } - } - ) - const state = rig(generate) - state.start() - await state.done() - expect(state.record().conversationName).toBe('Login repair') - expect(reuse).toHaveBeenCalledOnce() - state.handler.regenerate('chat-1') - await state.done() - expect(reuse).toHaveBeenCalledOnce() -}) - -it.each(['owner', 'same-text rename'] as const)( - 'rejects a queued title write after %s changes', - async (change) => { - let owned = true - const state = rig( - async (_record, _prompt, _current, automatic) => - automatic ? { name: 'CLI title', shouldApply: () => owned } : { name: 'Independent title' }, - () => ({ - owner: { isCurrent: () => owned, generate: async () => null } - }) - ) - state.beforeWrite(async () => { - if (change === 'owner') { - owned = false - } else { - await state.handler.setUserName('chat-1', 'Repair login', 'rename') - } - }) - state.start() - await state.done() - expect(state.record().conversationName).toBe( - change === 'owner' ? 'Independent title' : 'Repair login' - ) - } -) diff --git a/src/main/native-chat/structured-chat-naming-types.ts b/src/main/native-chat/structured-chat-naming-types.ts deleted file mode 100644 index 9f8b4c8fb34..00000000000 --- a/src/main/native-chat/structured-chat-naming-types.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { AgentSessionRecordStore } from '../runtime/agent-session/records/agent-session-record-store' -import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output' -import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' -import type { StructuredAgentSessionAdapter } from './agent-session-wire/providers/structured-agent-session-adapter' -import type { AgentSessionJournal } from './agent-session-journal/journal-store' - -export type AutomaticChatTitle = { - owner: ReturnType> - pending?: { - ready: Promise - ended: () => boolean - recheck: () => void - unavailable: (journal: AgentSessionJournal) => void - dispose: () => void - } - retainOwnership?: (isCurrent: (record: AgentSessionRecord) => boolean) => void -} - -/** null means unavailable/canceled: no failure to display or retry. */ -export type StructuredChatNameGeneration = - | { name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } - | { error: string; errorCode?: string; failureOutput?: AgentGenerationFailureOutput } - | null - -export type StructuredChatNamingDeps = { - getStore: () => Pick< - AgentSessionRecordStore, - 'getRecord' | 'compareAndSetConversationName' | 'setUserConversationName' - > | null - getSettings: () => Pick - readFirstPrompt: (sessionId: string, hostStartedAt: number) => Promise - /** The current context's first prompt, for a name the user asked for again. */ - readJournalFirstPrompt: (sessionId: string) => Promise - now?: () => number - workerTaskTitle: (record: AgentSessionRecord) => { title: string } | null - captureAutomaticTitle?: ( - record: AgentSessionRecord, - firstInputSubmissionKey?: string, - applicable?: () => boolean - ) => AutomaticChatTitle | undefined - generate: ( - record: AgentSessionRecord, - firstPrompt: string, - shouldExecute?: () => boolean, - automaticTitle?: AutomaticChatTitle - ) => Promise - onNamed: (workspaceId: string, sessionId: string) => void - logger: StructuredAgentSessionLogger - wait?: (ms: number) => Promise -} diff --git a/src/main/native-chat/structured-chat-naming.ts b/src/main/native-chat/structured-chat-naming.ts index ec4e230b256..f4bb04594d9 100644 --- a/src/main/native-chat/structured-chat-naming.ts +++ b/src/main/native-chat/structured-chat-naming.ts @@ -1,19 +1,16 @@ import type { StructuredChatNameGeneration, StructuredChatNamingDeps -} from './structured-chat-naming-types' -export type { - StructuredChatNameGeneration, - StructuredChatNamingDeps -} from './structured-chat-naming-types' -import { runStructuredChatNameGeneration } from './structured-chat-name-publication' +} from './conversation-naming/structured-chat-naming-types' + +import { runStructuredChatNameGeneration } from './conversation-naming/structured-chat-name-publication' import { chatNamingFailure } from '../../shared/chat-naming-failure-copy' import { automaticChatNamingRequest, createStructuredChatNamingWork, namingRequestOwnsRecord, type NamingRequest -} from './structured-chat-naming-work' +} from './conversation-naming/structured-chat-naming-work' import type { StructuredAgentSessionStatusObserverOptions } from './agent-session-wire/observations/structured-agent-session-status-observation' import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' @@ -26,7 +23,7 @@ import { sliceAtCodeUnitLimit } from '../../shared/surrogate-safe-text-slice' import { formatAgentGenerationFailureOutputForDisplay, type AgentGenerationFailureOutput -} from '../text-generation/agent-failure-output' +} from '../text-generation/failures/agent-failure-output' import type { StructuredAgentSessionConversationNaming, StructuredChatNamingFailure diff --git a/src/main/native-chat/agent-session-record-test-fixture.ts b/src/main/native-chat/testing/agent-session-record-test-fixture.ts similarity index 89% rename from src/main/native-chat/agent-session-record-test-fixture.ts rename to src/main/native-chat/testing/agent-session-record-test-fixture.ts index 5a5952f46b0..8da8e22f672 100644 --- a/src/main/native-chat/agent-session-record-test-fixture.ts +++ b/src/main/native-chat/testing/agent-session-record-test-fixture.ts @@ -2,8 +2,8 @@ import { AGENT_SESSION_RECORD_SCHEMA_VERSION, type AgentSessionExecutionLocation, type AgentSessionRecord -} from '../../shared/agent-session/lifecycle/agent-session-record' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +} from '../../../shared/agent-session/lifecycle/agent-session-record' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' export function agentSessionRecordFixture( overrides: Partial> & { diff --git a/src/main/native-chat/transcript-claude-read-image.test.ts b/src/main/native-chat/transcript-claude-read-image.test.ts deleted file mode 100644 index 658c6d71bff..00000000000 --- a/src/main/native-chat/transcript-claude-read-image.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { foldToolMessages } from '../../shared/native-chat/tools/native-chat-tool-fold' -import { nativeChatToolRunViewedImages } from '../../shared/native-chat/tools/native-chat-tool-viewed-images' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' - -// Claude 2.x Read of an image: the result holds only base64, the path is on the call. -function readTurn(filePath: string, result: Record): string[] { - return [ - JSON.stringify({ - type: 'assistant', - uuid: 'call-row', - timestamp: '2026-10-29T14:09:20.000Z', - message: { - role: 'assistant', - content: [{ type: 'tool_use', id: 'toolu_1', name: 'Read', input: { file_path: filePath } }] - } - }), - JSON.stringify({ - type: 'user', - uuid: 'result-row', - timestamp: '2026-10-29T14:09:23.939Z', - message: { - role: 'user', - content: [{ tool_use_id: 'toolu_1', type: 'tool_result', ...result }] - }, - toolUseResult: { type: 'image', file: { base64: 'iVBORw0KGgo=', type: 'image/png' } } - }) - ] -} - -const IMAGE_RESULT = { - content: [ - { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'iVBORw0KGgo=' } } - ] -} - -function viewedImages(lines: string[]): ReturnType { - const decoded = lines - .map((line, index) => decodeClaudeTranscriptLine(line, `fallback-${index}`)) - .filter((message): message is NativeChatMessage => message !== null) - const folded = foldToolMessages(decoded) - expect(folded).toHaveLength(1) - return nativeChatToolRunViewedImages(folded[0]!.blocks) -} - -describe('Claude Read of an image', () => { - it('shows the screenshot the agent read', () => { - expect(viewedImages(readTurn('/tmp/orca-annot/s2.png', IMAGE_RESULT))).toEqual([ - { type: 'image-ref', path: '/tmp/orca-annot/s2.png' } - ]) - }) - - it('shows nothing for a read that failed or returned text', () => { - const failed = { content: 'File does not exist.', is_error: true } - expect(viewedImages(readTurn('/tmp/gone.png', failed))).toEqual([]) - expect(viewedImages(readTurn('/repo/src/a.ts', { content: '1\tconst a = 1' }))).toEqual([]) - expect(viewedImages(readTurn('/repo/icons/logo.svg', { content: '1\t' }))).toEqual([]) - }) -}) - -it('shows nothing for a shell read, which gave the agent bytes as text', () => { - const codexCat = { - type: 'tool-call', - name: 'read', - callId: 'c1', - input: { command: 'cat /repo/images/shot.png', cwd: '/repo', path: '/repo/images/shot.png' } - } as const - expect( - nativeChatToolRunViewedImages([codexCat, { type: 'tool-result', callId: 'c1', output: '' }]) - ).toEqual([]) -}) diff --git a/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-control-bytes.test.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-control-bytes.test.ts new file mode 100644 index 00000000000..b16a5befda3 --- /dev/null +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-control-bytes.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' + +import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' + +const COMPOSER_TEXT = 'line 000 xxxxxxxxxx\nline 001 xxxxxxxxxx\nline 002 xxxxxxxxxx' + +// Matches the string-content shape observed when a TUI records Ctrl+U with the prompt. +const MOBILE_SEND_LINE = JSON.stringify({ + type: 'user', + uuid: 'synthetic-user-turn', + message: { role: 'user', content: `\u0015${COMPOSER_TEXT}` } +}) + +describe('decodeClaudeTranscriptLine on a mobile-sent prompt', () => { + it('keeps the Ctrl+U byte the TUI pasted into the prompt', () => { + const message = decodeClaudeTranscriptLine(MOBILE_SEND_LINE, 'fallback') + expect(message?.role).toBe('user') + expect(message?.blocks[0]).toEqual({ + type: 'text', + text: `\u0015${COMPOSER_TEXT}` + }) + }) +}) diff --git a/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-image-companion.test.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-image-companion.test.ts new file mode 100644 index 00000000000..fc0a6aac2d6 --- /dev/null +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-image-companion.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' + +import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' + +// Claude 2.1.237 stores source paths in separate isMeta/turnCompanion rows; prompt base64 has no path. + +describe('Claude pasted-image companion row', () => { + it('still drops an ordinary isMeta injected turn', () => { + const injected = JSON.stringify({ + type: 'user', + uuid: 'injected', + isMeta: true, + message: { + role: 'user', + content: [{ type: 'text', text: 'Base directory for this skill: /x' }] + } + }) + expect(decodeClaudeTranscriptLine(injected, 'fallback')).toBeNull() + }) + + it('does not turn a mixed marker-and-prose meta row into an image source turn', () => { + const mixed = JSON.stringify({ + type: 'user', + uuid: 'mixed', + isMeta: true, + message: { + role: 'user', + content: [ + { type: 'text', text: '[Image: source: /tmp/a.png]' }, + { type: 'text', text: 'metadata prose' } + ] + } + }) + + expect(decodeClaudeTranscriptLine(mixed, 'fallback')).toBeNull() + }) + + it('retains tool results from a mixed meta row while dropping its marker text', () => { + const mixed = JSON.stringify({ + type: 'user', + uuid: 'mixed-tool', + isMeta: true, + message: { + role: 'user', + content: [ + { type: 'text', text: '[Image: source: /tmp/a.png]' }, + { type: 'tool_result', content: 'tool output' } + ] + } + }) + + expect(decodeClaudeTranscriptLine(mixed, 'fallback')).toMatchObject({ + id: 'mixed-tool', + role: 'tool', + blocks: [{ type: 'tool-result', output: 'tool output' }] + }) + }) +}) diff --git a/src/main/native-chat/transcript-line-decoders-claude-queued-prompt.test.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-queued-prompt.test.ts similarity index 100% rename from src/main/native-chat/transcript-line-decoders-claude-queued-prompt.test.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders-claude-queued-prompt.test.ts diff --git a/src/main/native-chat/transcript-line-decoders-claude.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts similarity index 89% rename from src/main/native-chat/transcript-line-decoders-claude.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts index 095e183e1d4..716ae6ae4fe 100644 --- a/src/main/native-chat/transcript-line-decoders-claude.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts @@ -4,25 +4,23 @@ import { type NativeChatEditPatch, type NativeChatEditPatchHunk, type NativeChatMessage -} from '../../shared/native-chat/native-chat-types' -import { - asRecord, - extractString, - parseJsonObject, - timestampMs -} from '../ai-vault/session-scanner-values' -import { imageSourcePathFromText } from '../../shared/native-chat/transcript/native-chat-image-transcript-markers' +} from '../../../shared/native-chat/native-chat-types' +import { asRecord } from '../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../shared/trimmed-string' +import { parseJsonObject } from '../../ai-vault/parsing/session-json-object' +import { timestampMs } from '../../ai-vault/parsing/session-record-time' +import { imageSourcePathFromText } from '../../../shared/native-chat/transcript/native-chat-image-transcript-markers' import { claudeContentBlocks } from './transcript-record-blocks' -import { isKnownRasterImageMimeType } from '../../shared/file-preview/raster-image-preview-limits' -import { unwrapClaudePastedContentBlock } from '../../shared/claude-pasted-content' -import { unwrapClaudeBashInputBlock } from '../../shared/claude-bash-input' +import { isKnownRasterImageMimeType } from '../../../shared/file-preview/raster-image-preview-limits' +import { unwrapClaudePastedContentBlock } from '../../../shared/claude-pasted-content' +import { unwrapClaudeBashInputBlock } from '../../../shared/claude-bash-input' import { claudeInterruptedMessageId } from './transcript-turn-markers' -import { claudeStopHookFeedbackRow } from '../claude/claude-stop-hook-feedback' -import { structuredAgentSessionStatusBlock } from '../../shared/agent-session/view/structured-agent-session-status-block' +import { claudeStopHookFeedbackRow } from '../../claude/structured/journal/claude-stop-hook-feedback' +import { structuredAgentSessionStatusBlock } from '../../../shared/agent-session/view/structured-agent-session-status-block' import { claudeMessageWithoutSyntheticText, isClaudeInjectedUserMessage -} from '../claude/claude-internal-message-content' +} from '../../claude/structured/journal/claude-internal-message-content' const MAX_EDIT_PATCH_HUNKS = 40 const MAX_EDIT_PATCH_HUNK_LINES = 400 diff --git a/src/main/native-chat/transcript-line-decoders-codex.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-codex.ts similarity index 95% rename from src/main/native-chat/transcript-line-decoders-codex.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders-codex.ts index 09c975ce385..45712b07ada 100644 --- a/src/main/native-chat/transcript-line-decoders-codex.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-codex.ts @@ -2,14 +2,12 @@ import { NATIVE_CHAT_INTERRUPTED_STATUS_TEXT, type NativeChatBlock, type NativeChatMessage -} from '../../shared/native-chat/native-chat-types' -import { NATIVE_CHAT_NOTICE_COPY } from '../../shared/native-chat/native-chat-notice' -import { - asRecord, - extractString, - parseJsonObject, - timestampMs -} from '../ai-vault/session-scanner-values' +} from '../../../shared/native-chat/native-chat-types' +import { NATIVE_CHAT_NOTICE_COPY } from '../../../shared/native-chat/native-chat-notice' +import { asRecord } from '../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../shared/trimmed-string' +import { parseJsonObject } from '../../ai-vault/parsing/session-json-object' +import { timestampMs } from '../../ai-vault/parsing/session-record-time' import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks' import { CODEX_EVENT_TURN_ABORTED } from './transcript-turn-markers' diff --git a/src/main/native-chat/transcript-line-decoders-grok.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-grok.ts similarity index 94% rename from src/main/native-chat/transcript-line-decoders-grok.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders-grok.ts index aaaa87bcb50..30bd7612e31 100644 --- a/src/main/native-chat/transcript-line-decoders-grok.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-grok.ts @@ -1,12 +1,13 @@ -import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { - asRecord, - extractString, - parseJsonObject, - timestampMs -} from '../ai-vault/session-scanner-values' +import type { + NativeChatBlock, + NativeChatMessage +} from '../../../shared/native-chat/native-chat-types' +import { asRecord } from '../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../shared/trimmed-string' +import { parseJsonObject } from '../../ai-vault/parsing/session-json-object' +import { timestampMs } from '../../ai-vault/parsing/session-record-time' import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks' -import { AGENT_SESSION_PASTED_IMAGE_SUFFIX_SOURCE } from '../../shared/agent-session/agent-session-attachments' +import { AGENT_SESSION_PASTED_IMAGE_SUFFIX_SOURCE } from '../../../shared/agent-session/agent-session-attachments' export function decodeGrokTranscriptLine( line: string, diff --git a/src/main/native-chat/transcript-line-decoders-omp.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-omp.ts similarity index 93% rename from src/main/native-chat/transcript-line-decoders-omp.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders-omp.ts index dcd3a555bb6..69112f2d197 100644 --- a/src/main/native-chat/transcript-line-decoders-omp.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-omp.ts @@ -5,15 +5,13 @@ import { NATIVE_CHAT_INTERRUPTED_STATUS_TEXT, type NativeChatBlock, type NativeChatMessage -} from '../../shared/native-chat/native-chat-types' -import type { AgentSessionTokenUsage } from '../../shared/agent-session/agent-session-context-usage' -import { buildImageDataUri } from '../../shared/file-preview/image-data-uri' -import { - asRecord, - extractString, - parseJsonObject, - timestampMs -} from '../ai-vault/session-scanner-values' +} from '../../../shared/native-chat/native-chat-types' +import type { AgentSessionTokenUsage } from '../../../shared/agent-session/agent-session-context-usage' +import { buildImageDataUri } from '../../../shared/file-preview/image-data-uri' +import { asRecord } from '../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../shared/trimmed-string' +import { parseJsonObject } from '../../ai-vault/parsing/session-json-object' +import { timestampMs } from '../../ai-vault/parsing/session-record-time' import { toolResultOutput } from './transcript-record-blocks' export function decodeOmpTranscriptLine( diff --git a/src/main/native-chat/transcript-line-decoders.grok.test.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders.grok.test.ts similarity index 99% rename from src/main/native-chat/transcript-line-decoders.grok.test.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders.grok.test.ts index 4fce5911220..ea4b30f9141 100644 --- a/src/main/native-chat/transcript-line-decoders.grok.test.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders.grok.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { decodeGrokTranscriptLine } from './transcript-line-decoders' +import { decodeGrokTranscriptLine } from './transcript-line-decoders-grok' describe('decodeGrokTranscriptLine', () => { it('decodes assistant tool calls on empty content rows', () => { diff --git a/src/main/native-chat/transcript-line-decoders.omp.test.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders.omp.test.ts similarity index 99% rename from src/main/native-chat/transcript-line-decoders.omp.test.ts rename to src/main/native-chat/transcript-decoding/transcript-line-decoders.omp.test.ts index 20d71adbf9c..6b58847389e 100644 --- a/src/main/native-chat/transcript-line-decoders.omp.test.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders.omp.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { decodeOmpTranscriptLine } from './transcript-line-decoders' +import { decodeOmpTranscriptLine } from './transcript-line-decoders-omp' const line = (record: unknown): string => JSON.stringify(record) diff --git a/src/main/native-chat/transcript-record-blocks.ts b/src/main/native-chat/transcript-decoding/transcript-record-blocks.ts similarity index 94% rename from src/main/native-chat/transcript-record-blocks.ts rename to src/main/native-chat/transcript-decoding/transcript-record-blocks.ts index c9fba58d705..3a7c7a896f3 100644 --- a/src/main/native-chat/transcript-record-blocks.ts +++ b/src/main/native-chat/transcript-decoding/transcript-record-blocks.ts @@ -2,14 +2,15 @@ import type { NativeChatBlock, NativeChatImageRefBlock, NativeChatToolResultBlock -} from '../../shared/native-chat/native-chat-types' -import { asRecord, extractString } from '../ai-vault/session-scanner-values' +} from '../../../shared/native-chat/native-chat-types' +import { asRecord } from '../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../shared/trimmed-string' import { isClaudeToolUseContent, isClaudeToolResultContent, claudeToolResultText, claudeToolResultFailed -} from '../../shared/claude-tool-content' +} from '../../../shared/claude-tool-content' export function toolResultOutput(value: unknown): string { if (typeof value === 'string') { diff --git a/src/main/native-chat/transcript-turn-lifecycle.test.ts b/src/main/native-chat/transcript-decoding/transcript-turn-lifecycle.test.ts similarity index 100% rename from src/main/native-chat/transcript-turn-lifecycle.test.ts rename to src/main/native-chat/transcript-decoding/transcript-turn-lifecycle.test.ts diff --git a/src/main/native-chat/transcript-turn-lifecycle.ts b/src/main/native-chat/transcript-decoding/transcript-turn-lifecycle.ts similarity index 87% rename from src/main/native-chat/transcript-turn-lifecycle.ts rename to src/main/native-chat/transcript-decoding/transcript-turn-lifecycle.ts index 68bff178ecb..e5a1d663459 100644 --- a/src/main/native-chat/transcript-turn-lifecycle.ts +++ b/src/main/native-chat/transcript-decoding/transcript-turn-lifecycle.ts @@ -1,14 +1,12 @@ -import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' -import type { NativeChatTurnLifecycle } from '../../shared/native-chat/native-chat-types' -import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' -import { isNoiseMessage } from '../../shared/native-chat/native-chat-noise' -import { claudeBashInputAsTypedCommand } from '../../shared/claude-bash-input' -import { - asRecord, - extractString, - parseJsonObject, - timestampMs -} from '../ai-vault/session-scanner-values' +import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' +import type { NativeChatTurnLifecycle } from '../../../shared/native-chat/native-chat-types' +import { resolveNativeChatTranscriptAgent } from '../../../shared/native-chat/native-chat-agent-support' +import { isNoiseMessage } from '../../../shared/native-chat/native-chat-noise' +import { claudeBashInputAsTypedCommand } from '../../../shared/claude-bash-input' +import { asRecord } from '../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../shared/trimmed-string' +import { parseJsonObject } from '../../ai-vault/parsing/session-json-object' +import { timestampMs } from '../../ai-vault/parsing/session-record-time' import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' import { claudeInterruptedMessageId, diff --git a/src/main/native-chat/transcript-turn-markers.ts b/src/main/native-chat/transcript-decoding/transcript-turn-markers.ts similarity index 87% rename from src/main/native-chat/transcript-turn-markers.ts rename to src/main/native-chat/transcript-decoding/transcript-turn-markers.ts index 96d43748b6b..4a5e48b343d 100644 --- a/src/main/native-chat/transcript-turn-markers.ts +++ b/src/main/native-chat/transcript-decoding/transcript-turn-markers.ts @@ -1,6 +1,6 @@ // Share provider boundary predicates so visible interruption rows and lifecycle settlement agree. -import { extractString } from '../ai-vault/session-scanner-values' +import { extractString } from '../../../shared/trimmed-string' export function claudeInterruptedMessageId(record: Record): string | undefined { if (record.type !== 'user') { diff --git a/src/main/native-chat/host-readable-transcript-path.test.ts b/src/main/native-chat/transcript-discovery/host-readable-transcript-path.test.ts similarity index 92% rename from src/main/native-chat/host-readable-transcript-path.test.ts rename to src/main/native-chat/transcript-discovery/host-readable-transcript-path.test.ts index 0aed607bed1..751aced6dd3 100644 --- a/src/main/native-chat/host-readable-transcript-path.test.ts +++ b/src/main/native-chat/transcript-discovery/host-readable-transcript-path.test.ts @@ -8,30 +8,30 @@ const wslMocks = vi.hoisted(() => ({ })) // These cases cover root and path policy; the E9 gate has its own suite. -vi.mock('./wsl-transcript-running-admission', () => ({ +vi.mock('../transcript-filesystem/wsl-transcript-running-admission', () => ({ admitWslTranscriptPath: wslMocks.admitWslTranscriptPath })) -vi.mock('../wsl/discovery/wsl-home-unless-stopped', async () => { - const wsl = await import('../wsl/discovery/distro-catalog') +vi.mock('../../wsl/discovery/wsl-home-unless-stopped', async () => { + const wsl = await import('../../wsl/discovery/distro-catalog') return { wslHomeUnlessStopped: (distro: string) => wsl.getWslHomeAsync(distro), listRunningWslHomeDirsUnlessStopped: () => wsl.listRunningWslHomeDirsAsync() } }) -vi.mock('../wsl/discovery/distro-catalog', () => ({ +vi.mock('../../wsl/discovery/distro-catalog', () => ({ listRunningWslHomeDirsAsync: wslMocks.listRunningWslHomeDirsAsync })) -vi.mock('../wsl/filesystem/unc-path-access', () => ({ +vi.mock('../../wsl/filesystem/unc-path-access', () => ({ resolveWslGuestRealDirAsync: wslMocks.resolveWslGuestRealDirAsync })) -vi.mock('../wsl/filesystem/wsl-running-path-filter', () => ({ +vi.mock('../../wsl/filesystem/wsl-running-path-filter', () => ({ filterPathsToRunningWslDistrosAsync: wslMocks.filterPathsToRunningWslDistrosAsync })) import { resetHostReadableTranscriptPathCacheForTests, toHostReadableTranscriptPath } from './host-readable-transcript-path' -import { WslTranscriptFsError } from './wsl-transcript-fs-gate' +import { WslTranscriptFsError } from '../transcript-filesystem/wsl-transcript-fs-error' const UBUNTU_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' const DEBIAN_HOME = '\\\\wsl.localhost\\Debian\\home\\other' diff --git a/src/main/native-chat/host-readable-transcript-path.ts b/src/main/native-chat/transcript-discovery/host-readable-transcript-path.ts similarity index 94% rename from src/main/native-chat/host-readable-transcript-path.ts rename to src/main/native-chat/transcript-discovery/host-readable-transcript-path.ts index 72f7835b253..a089788c4e1 100644 --- a/src/main/native-chat/host-readable-transcript-path.ts +++ b/src/main/native-chat/transcript-discovery/host-readable-transcript-path.ts @@ -1,23 +1,26 @@ import { existsSync } from 'node:fs' import { isAbsolute, posix } from 'node:path' -import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' +import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../../shared/wsl-paths' import { uniqueDirs, wslHomeSessionDirs, type SessionHomeAgent -} from '../ai-vault/session-scanner-roots' -import { resolveWslGuestRealDirAsync } from '../wsl/filesystem/unc-path-access' +} from '../../ai-vault/discovery/session-scanner-roots' +import { resolveWslGuestRealDirAsync } from '../../wsl/filesystem/unc-path-access' import { listRunningWslHomeDirsUnlessStopped, wslHomeUnlessStopped -} from '../wsl/discovery/wsl-home-unless-stopped' -import { admitWslTranscriptPath } from './wsl-transcript-running-admission' +} from '../../wsl/discovery/wsl-home-unless-stopped' +import { admitWslTranscriptPath } from '../transcript-filesystem/wsl-transcript-running-admission' import { filterPathsToRunningWslDistrosAsync, filterPathsToWslDistros -} from '../wsl/filesystem/wsl-running-path-filter' -import { wslGatedAccess } from './wsl-transcript-fs-access' -import { WslTranscriptFsError, wslTranscriptFsRefusal } from './wsl-transcript-fs-gate' +} from '../../wsl/filesystem/wsl-running-path-filter' +import { wslGatedAccess } from '../transcript-filesystem/wsl-transcript-fs-access' +import { + WslTranscriptFsError, + wslTranscriptFsRefusal +} from '../transcript-filesystem/wsl-transcript-fs-error' export function isGuestAbsoluteLinuxPath(path: string): boolean { if (!path.startsWith('/') || path.startsWith('//')) { diff --git a/src/main/native-chat/native-chat-open-wake.ts b/src/main/native-chat/transcript-discovery/native-chat-open-wake.ts similarity index 78% rename from src/main/native-chat/native-chat-open-wake.ts rename to src/main/native-chat/transcript-discovery/native-chat-open-wake.ts index ad8367aa90c..161c767560d 100644 --- a/src/main/native-chat/native-chat-open-wake.ts +++ b/src/main/native-chat/transcript-discovery/native-chat-open-wake.ts @@ -1,18 +1,18 @@ -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import { isWslHookRelayConnectionId, WSL_HOOK_RELAY_CONNECTION_PREFIX -} from '../../shared/wsl-hook-relay-contract' -import { toWindowsWslPath } from '../../shared/wsl-paths' +} from '../../../shared/wsl-hook-relay-contract' +import { toWindowsWslPath } from '../../../shared/wsl-paths' import { blockedWslDistroForPath, runAsWslUserAct, wslDistroForPath -} from '../wsl/filesystem/wsl-unc-access-gate' -import { wslGatedAccess } from './wsl-transcript-fs-access' -import { WSL_TRANSCRIPT_RUNNING_LEASE_MS } from './wsl-transcript-running-admission' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { nativeChatTranscriptPathOnExecutionHost } from './ssh-transcript-path' +} from '../../wsl/filesystem/wsl-unc-access-gate' +import { wslGatedAccess } from '../transcript-filesystem/wsl-transcript-fs-access' +import { WSL_TRANSCRIPT_RUNNING_LEASE_MS } from '../transcript-filesystem/wsl-transcript-running-admission' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { nativeChatTranscriptPathOnExecutionHost } from '../transcript-filesystem/ssh-transcript-path' type HookRow = Pick diff --git a/src/main/native-chat/session-file-id-layouts.ts b/src/main/native-chat/transcript-discovery/session-file-id-layouts.ts similarity index 82% rename from src/main/native-chat/session-file-id-layouts.ts rename to src/main/native-chat/transcript-discovery/session-file-id-layouts.ts index 205fe7861f6..2e581c54a1f 100644 --- a/src/main/native-chat/session-file-id-layouts.ts +++ b/src/main/native-chat/transcript-discovery/session-file-id-layouts.ts @@ -1,7 +1,7 @@ import { win32 } from 'node:path' -import { GROK_CHAT_HISTORY_FILE } from '../../shared/grok-session-paths' -import { isClaudeProjectBucketDirectory } from '../ai-vault/scanners/claude/claude-project-dir-encoding' -import { isOmpConversationDirectory } from '../ai-vault/scanners/omp/session-scanner-omp-subagent-transcripts' +import { GROK_CHAT_HISTORY_FILE } from '../../../shared/grok-session-paths' +import { isClaudeProjectBucketDirectory } from '../../ai-vault/scanners/claude/claude-project-dir-encoding' +import { isOmpConversationDirectory } from '../../ai-vault/scanners/omp/session-scanner-omp-subagent-transcripts' export type SessionIdLookupAgent = 'claude' | 'codex' | 'grok' | 'omp' diff --git a/src/main/native-chat/session-file-resolver-claude-probe.ts b/src/main/native-chat/transcript-discovery/session-file-resolver-claude-probe.ts similarity index 96% rename from src/main/native-chat/session-file-resolver-claude-probe.ts rename to src/main/native-chat/transcript-discovery/session-file-resolver-claude-probe.ts index 9e07e12699e..bd91d1261df 100644 --- a/src/main/native-chat/session-file-resolver-claude-probe.ts +++ b/src/main/native-chat/transcript-discovery/session-file-resolver-claude-probe.ts @@ -1,6 +1,6 @@ import { lstat, readdir } from 'node:fs/promises' import { join } from 'node:path' -import { encodeClaudeProjectPaths } from '../ai-vault/scanners/claude/claude-project-dir-encoding' +import { encodeClaudeProjectPaths } from '../../ai-vault/scanners/claude/claude-project-dir-encoding' // Ids become path segments here; a separator or dot segment would escape the bucket. function isSafeClaudeSessionId(sessionId: string): boolean { diff --git a/src/main/native-chat/transcript-path-admission.ts b/src/main/native-chat/transcript-discovery/transcript-path-admission.ts similarity index 91% rename from src/main/native-chat/transcript-path-admission.ts rename to src/main/native-chat/transcript-discovery/transcript-path-admission.ts index 1da92501b0f..a61280c70d1 100644 --- a/src/main/native-chat/transcript-path-admission.ts +++ b/src/main/native-chat/transcript-discovery/transcript-path-admission.ts @@ -1,7 +1,10 @@ import { lstat, realpath } from 'node:fs/promises' import { basename, dirname, isAbsolute, relative, resolve } from 'node:path' -import { isDescendantOrEqual, isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' -import { isWslUncPath } from '../../shared/wsl-paths' +import { + isDescendantOrEqual, + isENOENT +} from '../../ipc/filesystem/access/filesystem-path-containment' +import { isWslUncPath } from '../../../shared/wsl-paths' import { needsWslHostResolution } from './host-readable-transcript-path' /** Account containment must survive symlinks and host-native path translation. */ diff --git a/src/main/native-chat/wsl-session-path-scan.ts b/src/main/native-chat/transcript-discovery/wsl-session-path-scan.ts similarity index 96% rename from src/main/native-chat/wsl-session-path-scan.ts rename to src/main/native-chat/transcript-discovery/wsl-session-path-scan.ts index 19398d01f54..bd8709c2dc4 100644 --- a/src/main/native-chat/wsl-session-path-scan.ts +++ b/src/main/native-chat/transcript-discovery/wsl-session-path-scan.ts @@ -1,7 +1,7 @@ import type { Dirent } from 'node:fs' -import { walkSessionFiles } from '../ai-vault/session-scanner-discovery' +import { walkSessionFiles } from '../../ai-vault/discovery/session-scanner-discovery' import { SESSION_FILE_ID_LAYOUTS, type SessionIdLookupAgent } from './session-file-id-layouts' -import { wslGatedReaddir } from './wsl-transcript-fs-access' +import { wslGatedReaddir } from '../transcript-filesystem/wsl-transcript-fs-access' type ScanWaiter = { sessionId: string diff --git a/src/main/native-chat/wsl-transcript-fs-process-client.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-client.ts similarity index 98% rename from src/main/native-chat/wsl-transcript-fs-process-client.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-client.ts index 567c381f267..77def126afb 100644 --- a/src/main/native-chat/wsl-transcript-fs-process-client.ts +++ b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-client.ts @@ -7,7 +7,7 @@ import { decodeWslTranscriptFsProcessValue } from './wsl-transcript-fs-process-decode' // Classify transport faults as unavailable so discovery cannot mistake unconsulted mounts for missing paths. -import { wslTranscriptFsProcessFailureError } from './wsl-transcript-fs-error' +import { wslTranscriptFsProcessFailureError } from '../wsl-transcript-fs-error' import { attachSlotChild, WSL_TRANSCRIPT_FS_PROCESS_CLOSE_TIMEOUT_MS, @@ -24,8 +24,6 @@ import { wslTranscriptFsHandleOwners } from './wsl-transcript-fs-process-handle-owner' -export type { WslTranscriptFsProcessHandle } from './wsl-transcript-fs-process-slot' - export class WslTranscriptFsProcessClient { private readonly pool: WslTranscriptFsProcessLanePool private readonly handles = new WeakMap() diff --git a/src/main/native-chat/wsl-transcript-fs-process-decode.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-decode.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-decode.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-decode.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-dispatch.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-dispatch.ts similarity index 93% rename from src/main/native-chat/wsl-transcript-fs-process-dispatch.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-dispatch.ts index b3f5e7dd9af..63fe3d5e89e 100644 --- a/src/main/native-chat/wsl-transcript-fs-process-dispatch.ts +++ b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-dispatch.ts @@ -4,16 +4,12 @@ import { type WslTranscriptFsReusableProcessCall } from './wsl-transcript-fs-process-protocol' import { decodeWslTranscriptFsProcessValue } from './wsl-transcript-fs-process-decode' -import { - WslTranscriptFsProcessClient, - type WslTranscriptFsProcessHandle -} from './wsl-transcript-fs-process-client' +import { WslTranscriptFsProcessClient } from './wsl-transcript-fs-process-client' +import type { WslTranscriptFsProcessHandle } from './wsl-transcript-fs-process-slot' import { wslTranscriptFsHandleOwners } from './wsl-transcript-fs-process-handle-owner' import { WslTranscriptFsProcessOperations } from './wsl-transcript-fs-process-operations' import { forkWslTranscriptFsProcess } from './wsl-transcript-fs-process-spawn' -export type { WslTranscriptFsProcessHandle } from './wsl-transcript-fs-process-client' - // Require the worker global too: leaked VITEST=true must never enable in-process UNC I/O in real apps. function inVitestWorker(): boolean { return process.env.VITEST === 'true' && '__vitest_worker__' in globalThis diff --git a/src/main/native-chat/wsl-transcript-fs-process-entry.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-entry.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-entry.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-entry.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-handle-owner.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-handle-owner.ts similarity index 89% rename from src/main/native-chat/wsl-transcript-fs-process-handle-owner.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-handle-owner.ts index 5b11fc208b6..6c4bb7d0971 100644 --- a/src/main/native-chat/wsl-transcript-fs-process-handle-owner.ts +++ b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-handle-owner.ts @@ -1,4 +1,4 @@ -import { wslTranscriptFsProcessFailureError } from './wsl-transcript-fs-error' +import { wslTranscriptFsProcessFailureError } from '../wsl-transcript-fs-error' import { invalidTranscriptHandleError } from './wsl-transcript-fs-process-protocol' import type { WslTranscriptFsProcessClient } from './wsl-transcript-fs-process-client' import type { WslTranscriptFsProcessHandle } from './wsl-transcript-fs-process-slot' diff --git a/src/main/native-chat/wsl-transcript-fs-process-lane-pool.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-lane-pool.ts similarity index 98% rename from src/main/native-chat/wsl-transcript-fs-process-lane-pool.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-lane-pool.ts index 31f060c9498..4d51e2c962a 100644 --- a/src/main/native-chat/wsl-transcript-fs-process-lane-pool.ts +++ b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-lane-pool.ts @@ -2,7 +2,7 @@ import { WSL_TRANSCRIPT_FS_PROCESS_IDLE_REAP_MS, type ProcessSlot } from './wsl-transcript-fs-process-slot' -import { wslTranscriptFsProcessFailureError } from './wsl-transcript-fs-error' +import { wslTranscriptFsProcessFailureError } from '../wsl-transcript-fs-error' type SlotWaiter = { resolve: (slot: ProcessSlot) => void diff --git a/src/main/native-chat/wsl-transcript-fs-process-operations.test.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-operations.test.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-operations.test.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-operations.test.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-operations.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-operations.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-operations.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-operations.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-protocol.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-protocol.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-protocol.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-protocol.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-send.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-send.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-send.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-send.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-slot.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-slot.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-process-slot.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-slot.ts diff --git a/src/main/native-chat/wsl-transcript-fs-process-spawn.ts b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-spawn.ts similarity index 96% rename from src/main/native-chat/wsl-transcript-fs-process-spawn.ts rename to src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-spawn.ts index ba604aa0287..431cee9353f 100644 --- a/src/main/native-chat/wsl-transcript-fs-process-spawn.ts +++ b/src/main/native-chat/transcript-filesystem/process/wsl-transcript-fs-process-spawn.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { pickAllowedEnv, RUNTIME_ENV_ALLOWLIST -} from '../ai-vault/scan-service/session-scanner-service-env' +} from '../../../ai-vault/scan-service/session-scanner-service-env' const PROCESS_ENTRY_FILENAME = 'wsl-transcript-fs-process-entry.js' diff --git a/src/main/native-chat/ssh-transcript-fs-access.ts b/src/main/native-chat/transcript-filesystem/ssh-transcript-fs-access.ts similarity index 88% rename from src/main/native-chat/ssh-transcript-fs-access.ts rename to src/main/native-chat/transcript-filesystem/ssh-transcript-fs-access.ts index 71d41f88ba4..fcc333a53e0 100644 --- a/src/main/native-chat/ssh-transcript-fs-access.ts +++ b/src/main/native-chat/transcript-filesystem/ssh-transcript-fs-access.ts @@ -1,4 +1,4 @@ -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' +import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import type { SshTranscriptLocation } from './ssh-transcript-path' export type SshTranscriptHandle = { sshTranscript: SshTranscriptLocation } diff --git a/src/main/native-chat/ssh-transcript-path.ts b/src/main/native-chat/transcript-filesystem/ssh-transcript-path.ts similarity index 91% rename from src/main/native-chat/ssh-transcript-path.ts rename to src/main/native-chat/transcript-filesystem/ssh-transcript-path.ts index 75a98a0c9bd..e6b20c69036 100644 --- a/src/main/native-chat/ssh-transcript-path.ts +++ b/src/main/native-chat/transcript-filesystem/ssh-transcript-path.ts @@ -1,5 +1,5 @@ -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import { isWslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import { isWslHookRelayConnectionId } from '../../../shared/wsl-hook-relay-contract' // Encode connection and file in the engine’s single path string so local files cannot answer remote reads. const SSH_TRANSCRIPT_PATH_PREFIX = 'orca-ssh-transcript:' diff --git a/src/main/native-chat/wsl-transcript-fs-access.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-access.ts similarity index 96% rename from src/main/native-chat/wsl-transcript-fs-access.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-fs-access.ts index 31e20cb81c0..6d4df955e98 100644 --- a/src/main/native-chat/wsl-transcript-fs-access.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-access.ts @@ -2,18 +2,18 @@ import { createReadStream, type Dirent, type Stats } from 'node:fs' import { access, lstat, open, readdir, readFile, stat, type FileHandle } from 'node:fs/promises' import { Readable } from 'node:stream' import { StringDecoder } from 'node:string_decoder' -import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../shared/abort-signal-reason' -import { isWslUncPath } from '../../shared/wsl-paths' +import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' +import { isWslUncPath } from '../../../shared/wsl-paths' import { runWslTranscriptFsTask, type WslTranscriptFsTaskPriority } from './wsl-transcript-fs-gate' import { closeWslTranscriptFsProcess, isWslTranscriptFsProcessHandle, openWslTranscriptFsProcess, readWslTranscriptFsProcess, - runWslTranscriptFsProcess, - type WslTranscriptFsProcessHandle -} from './wsl-transcript-fs-process-dispatch' -import type { WslTranscriptFsReusableProcessCall } from './wsl-transcript-fs-process-protocol' + runWslTranscriptFsProcess +} from './process/wsl-transcript-fs-process-dispatch' +import type { WslTranscriptFsProcessHandle } from './process/wsl-transcript-fs-process-slot' +import type { WslTranscriptFsReusableProcessCall } from './process/wsl-transcript-fs-process-protocol' import { wslTranscriptFsLaneKey } from './wsl-transcript-fs-route' import { admitWslTranscriptPath } from './wsl-transcript-running-admission' import { diff --git a/src/main/native-chat/wsl-transcript-fs-error.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-error.ts similarity index 97% rename from src/main/native-chat/wsl-transcript-fs-error.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-fs-error.ts index 854f46f6565..fcc1808a1cd 100644 --- a/src/main/native-chat/wsl-transcript-fs-error.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-error.ts @@ -2,7 +2,7 @@ import { AI_VAULT_SCAN_ISSUE_COPY, aiVaultScanIssueText, type AiVaultScanIssueText -} from '../../shared/ai-vault/scanning/ai-vault-scan-issue-copy' +} from '../../../shared/ai-vault/scanning/ai-vault-scan-issue-copy' export const WSL_TRANSCRIPT_FS_SLOW_MESSAGE = AI_VAULT_SCAN_ISSUE_COPY.wslTranscriptFsSlow export const WSL_TRANSCRIPT_FS_CAPACITY_MESSAGE = AI_VAULT_SCAN_ISSUE_COPY.wslTranscriptFsCapacity diff --git a/src/main/native-chat/wsl-transcript-fs-gate.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-gate.ts similarity index 97% rename from src/main/native-chat/wsl-transcript-fs-gate.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-fs-gate.ts index 6854ce6ad4f..7f6707df30c 100644 --- a/src/main/native-chat/wsl-transcript-fs-gate.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-gate.ts @@ -18,14 +18,6 @@ export const WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS = 60_000 // Burst bounds keep polling fan-out from growing retained tasks or callers indefinitely. export const WSL_TRANSCRIPT_FS_MAX_PENDING_TASKS = 64 export const WSL_TRANSCRIPT_FS_MAX_WAITERS_PER_TASK = 64 -export { - WSL_TRANSCRIPT_FS_CAPACITY_MESSAGE, - WSL_TRANSCRIPT_FS_SLOW_MESSAGE, - WslTranscriptFsError, - wslTranscriptFsRefusal, - type WslTranscriptFsFailureCode -} from './wsl-transcript-fs-error' -export { WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS } from './wsl-transcript-fs-route-quarantine' export type WslTranscriptFsTaskPriority = 'exact' | 'scan' diff --git a/src/main/native-chat/wsl-transcript-fs-route-quarantine.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-route-quarantine.ts similarity index 100% rename from src/main/native-chat/wsl-transcript-fs-route-quarantine.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-fs-route-quarantine.ts diff --git a/src/main/native-chat/wsl-transcript-fs-route.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-route.ts similarity index 91% rename from src/main/native-chat/wsl-transcript-fs-route.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-fs-route.ts index e5454133d76..bb92ec11b6a 100644 --- a/src/main/native-chat/wsl-transcript-fs-route.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-fs-route.ts @@ -1,4 +1,4 @@ -import { parseWslUncPath } from '../../shared/wsl-paths' +import { parseWslUncPath } from '../../../shared/wsl-paths' /** Isolate distro/spelling consistently across gate and process ownership. * wsl$ and wsl.localhost remain distinct: provider behavior may differ, so each has its own deadlines. */ diff --git a/src/main/native-chat/wsl-transcript-running-admission.test.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.test.ts similarity index 91% rename from src/main/native-chat/wsl-transcript-running-admission.test.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.test.ts index 27e83d645b8..2479696564a 100644 --- a/src/main/native-chat/wsl-transcript-running-admission.test.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.test.ts @@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({ })) vi.mock('@orca/process-host', () => ({ runProcess: mocks.runProcess })) -vi.mock('./wsl-transcript-fs-process-dispatch', async (importOriginal) => ({ +vi.mock('./process/wsl-transcript-fs-process-dispatch', async (importOriginal) => ({ ...(await importOriginal()), runWslTranscriptFsProcess: mocks.runFsProcess, openWslTranscriptFsProcess: async () => ({ wslTranscriptFsProcessHandle: 1 }), @@ -17,11 +17,11 @@ vi.mock('./wsl-transcript-fs-process-dispatch', async (importOriginal) => ({ closeWslTranscriptFsProcess: async () => {} })) -import { _resetWslCachesForTests } from '../wsl/discovery/distro-catalog' +import { _resetWslCachesForTests } from '../../wsl/discovery/distro-catalog' import { _resetWslBackgroundDistroGateForTests, noteWslDistroMayHaveStopped -} from '../wsl/discovery/wsl-background-distro-gate' +} from '../../wsl/discovery/wsl-background-distro-gate' import { openTranscriptFile, readTranscriptFile } from './wsl-transcript-fs-access' import { resetWslTranscriptFsGateForTests } from './wsl-transcript-fs-gate' diff --git a/src/main/native-chat/wsl-transcript-running-admission.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.ts similarity index 90% rename from src/main/native-chat/wsl-transcript-running-admission.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.ts index 9a42f952e0d..486236f91c8 100644 --- a/src/main/native-chat/wsl-transcript-running-admission.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-running-admission.ts @@ -1,4 +1,4 @@ -import { blockedWslDistroForPath } from '../wsl/filesystem/wsl-unc-access-gate' +import { blockedWslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' import { wslTranscriptFsDistroNotRunningError } from './wsl-transcript-fs-error' /** diff --git a/src/main/native-chat/wsl-transcript-running-observer.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-running-observer.ts similarity index 95% rename from src/main/native-chat/wsl-transcript-running-observer.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-running-observer.ts index f90fdeae789..14363883a70 100644 --- a/src/main/native-chat/wsl-transcript-running-observer.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-running-observer.ts @@ -1,5 +1,5 @@ -import { listRunningWslDistrosAsync } from '../wsl/discovery/distro-catalog' -import { filterPathsToWslDistros } from '../wsl/filesystem/wsl-running-path-filter' +import { listRunningWslDistrosAsync } from '../../wsl/discovery/distro-catalog' +import { filterPathsToWslDistros } from '../../wsl/filesystem/wsl-running-path-filter' /** Every watched WSL transcript shares one running-list read on this cadence, and reuses any * read another caller started within it, so watching never adds a `wsl.exe` per watcher. */ diff --git a/src/main/native-chat/wsl-transcript-watcher-running-guard.ts b/src/main/native-chat/transcript-filesystem/wsl-transcript-watcher-running-guard.ts similarity index 84% rename from src/main/native-chat/wsl-transcript-watcher-running-guard.ts rename to src/main/native-chat/transcript-filesystem/wsl-transcript-watcher-running-guard.ts index 7d98f4a9c03..f64e327068d 100644 --- a/src/main/native-chat/wsl-transcript-watcher-running-guard.ts +++ b/src/main/native-chat/transcript-filesystem/wsl-transcript-watcher-running-guard.ts @@ -1,9 +1,9 @@ -import { isWslUncPath } from '../../shared/wsl-paths' -import { filterPathsToRunningWslDistrosAsync } from '../wsl/filesystem/wsl-running-path-filter' +import { isWslUncPath } from '../../../shared/wsl-paths' +import { filterPathsToRunningWslDistrosAsync } from '../../wsl/filesystem/wsl-running-path-filter' import { createTranscriptNativeWatcher, type TranscriptNativeWatcher -} from '../../shared/transcript-native-watcher' +} from '../../../shared/transcript-native-watcher' import { parseSshTranscriptPath } from './ssh-transcript-path' export function isWslTranscriptWatcherPath(filePath: string): boolean { diff --git a/src/main/native-chat/codex-local-history.ts b/src/main/native-chat/transcript-history/codex/codex-local-history.ts similarity index 90% rename from src/main/native-chat/codex-local-history.ts rename to src/main/native-chat/transcript-history/codex/codex-local-history.ts index 71ce7089e49..dfd470055b0 100644 --- a/src/main/native-chat/codex-local-history.ts +++ b/src/main/native-chat/transcript-history/codex/codex-local-history.ts @@ -1,11 +1,13 @@ import { createHash } from 'node:crypto' -import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' -import { sessionIdFromFileName } from '../ai-vault/session-scanner-accumulator' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../../shared/trimmed-string' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' +import { sessionIdFromFileName } from '../../../ai-vault/parsing/session-scanner-accumulator' import { codexHistorySources, codexPhysicalRolloutId } from './codex-rollout-history-source' import { readCodexRolloutBytes } from './codex-rollout-history-stream' -import { splitTranscriptStreamLines } from './transcript-stream-lines' -import { isCodexVisibleHistoryRecord } from './transcript-line-decoders-codex' -import { transcriptFallbackId } from './transcript-fallback-id' +import { splitTranscriptStreamLines } from '../../transcript-streaming/transcript-stream-lines' +import { isCodexVisibleHistoryRecord } from '../../transcript-decoding/transcript-line-decoders-codex' +import { transcriptFallbackId } from '../../transcript-streaming/transcript-fallback-id' type HistoryPosition = { thread_id: string diff --git a/src/main/native-chat/codex-rollout-history-source.ts b/src/main/native-chat/transcript-history/codex/codex-rollout-history-source.ts similarity index 93% rename from src/main/native-chat/codex-rollout-history-source.ts rename to src/main/native-chat/transcript-history/codex/codex-rollout-history-source.ts index 3932efc5c6b..28af5c17c24 100644 --- a/src/main/native-chat/codex-rollout-history-source.ts +++ b/src/main/native-chat/transcript-history/codex/codex-rollout-history-source.ts @@ -1,6 +1,6 @@ import { basename, dirname, join } from 'node:path' -import { forEachSessionFile } from '../ai-vault/session-scanner-discovery' -import { admitTranscriptPath } from './transcript-path-admission' +import { forEachSessionFile } from '../../../ai-vault/discovery/session-scanner-discovery' +import { admitTranscriptPath } from '../../transcript-discovery/transcript-path-admission' export function codexPhysicalRolloutId(path: string): string | null { const match = basename(path).match( diff --git a/src/main/native-chat/codex-rollout-history-stream.ts b/src/main/native-chat/transcript-history/codex/codex-rollout-history-stream.ts similarity index 100% rename from src/main/native-chat/codex-rollout-history-stream.ts rename to src/main/native-chat/transcript-history/codex/codex-rollout-history-stream.ts diff --git a/src/main/native-chat/transcript-opencode-database.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-database.ts similarity index 86% rename from src/main/native-chat/transcript-opencode-database.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-database.ts index c063ad325f2..ff40857e82c 100644 --- a/src/main/native-chat/transcript-opencode-database.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode-database.ts @@ -1,19 +1,19 @@ import { homedir } from 'node:os' -import { wslGatedAccess } from './wsl-transcript-fs-access' +import { wslGatedAccess } from '../../transcript-filesystem/wsl-transcript-fs-access' import { join } from 'node:path' -import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' -import { getAiVaultWslScanHomeDirs } from '../ai-vault/cached-session-list' -import { prepareOpenCodeWslReaders } from '../ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { getAiVaultWslScanHomeDirs } from '../../../ai-vault/discovery/ai-vault-scan-roots' +import { prepareOpenCodeWslReaders } from '../../../ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation' import { configureOpenCodeWslReaders, openCodeWslPath -} from '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-client' -import { readOpenCodeTranscriptSignalViaWorker } from '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn' +} from '../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-client' +import { readOpenCodeTranscriptSignalViaWorker } from '../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn' import { compareOpenCodeClaimPriority, listOpenCodeDatabases, listOpenCodeDatabasesInDirectory -} from '../opencode-usage/opencode-database-discovery' +} from '../../../opencode-usage/opencode-database-discovery' // ZCode sessions belong only to its own store. function zcodeTranscriptDatabasePaths(wslHomeDirs: readonly string[]): string[] { diff --git a/src/main/native-chat/transcript-opencode-fingerprint-window.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-fingerprint-window.ts similarity index 100% rename from src/main/native-chat/transcript-opencode-fingerprint-window.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-fingerprint-window.ts diff --git a/src/main/native-chat/transcript-opencode-part-blocks.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-part-blocks.ts similarity index 92% rename from src/main/native-chat/transcript-opencode-part-blocks.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-part-blocks.ts index 22118011b63..1f14d6afb63 100644 --- a/src/main/native-chat/transcript-opencode-part-blocks.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode-part-blocks.ts @@ -4,9 +4,11 @@ import type { NativeChatImageRefBlock, NativeChatMessage, NativeChatTextBlock -} from '../../shared/native-chat/native-chat-types' -import { agentSessionHostStatusBody } from '../../shared/agent-session/view/agent-session-host-status-rows' -import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' +} from '../../../../shared/native-chat/native-chat-types' +import { agentSessionHostStatusBody } from '../../../../shared/agent-session/view/agent-session-host-status-rows' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../../shared/trimmed-string' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' // Electron-free: imported by the OpenCode SQLite worker. export type OpenCodePartRow = { diff --git a/src/main/native-chat/transcript-opencode-row-budget.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-row-budget.ts similarity index 94% rename from src/main/native-chat/transcript-opencode-row-budget.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-row-budget.ts index 1060ebe1277..10cc244e82f 100644 --- a/src/main/native-chat/transcript-opencode-row-budget.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode-row-budget.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../../sqlite/sync-database' type BindValue = SyncDatabase.BindValue type SqliteStatement = SyncDatabase.Statement diff --git a/src/main/native-chat/transcript-opencode-sqlite-query.test.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.test.ts similarity index 87% rename from src/main/native-chat/transcript-opencode-sqlite-query.test.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.test.ts index 46ebeb5e799..bec22c45201 100644 --- a/src/main/native-chat/transcript-opencode-sqlite-query.test.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.test.ts @@ -1,9 +1,8 @@ -import { readOpenCodeNativeChatTranscriptFull } from './transcript-opencode' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import Database from '../sqlite/sync-database' +import Database from '../../../sqlite/sync-database' import { readOpenCodeTranscriptPage, readOpenCodeTranscriptSignal @@ -235,26 +234,3 @@ describe('readOpenCodeTranscriptSignal', () => { }) }) }) - -it.each(['stop', 'tool-calls', undefined])( - 'uses native v1 completion evidence without treating prose or tool work as terminal: %s', - async (finish) => { - const { db, path } = createTempDb() - applySchema(db) - insertMessage(db, { id: 'u1', time: 1 }) - insertPart(db, { id: 'pu', messageId: 'u1', time: 1, data: { type: 'text', text: 'Prompt' } }) - insertMessage(db, { id: 'a1', time: 2, role: 'assistant' }) - insertPart(db, { id: 'pa', messageId: 'a1', time: 2, data: { type: 'text', text: 'Response' } }) - if (finish) { - db.prepare('UPDATE message SET data = ? WHERE id = ?').run( - JSON.stringify({ role: 'assistant', time: { completed: 3 }, finish }), - 'a1' - ) - } - const imported = await readOpenCodeNativeChatTranscriptFull('ses-1', { - resolveDbPath: async () => path, - readPage: async (args) => readOpenCodeTranscriptPage(args) - }) - expect(imported).toMatchObject({ forkTipItemIds: finish === 'stop' ? ['u1', 'a1'] : [] }) - } -) diff --git a/src/main/native-chat/transcript-opencode-sqlite-query.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.ts similarity index 88% rename from src/main/native-chat/transcript-opencode-sqlite-query.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.ts index f1973c83970..cf032b8bf5b 100644 --- a/src/main/native-chat/transcript-opencode-sqlite-query.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode-sqlite-query.ts @@ -1,15 +1,17 @@ -import { openOpenCodeDatabaseReadonly } from '../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-open' -import { zcodeVisibleMessageFilter } from '../ai-vault/scanners/zcode/session-scanner-zcode-visibility' -import { zcodeTranscriptOrder } from '../ai-vault/scanners/zcode/session-scanner-zcode-order' +import { openOpenCodeDatabaseReadonly } from '../../../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-open' +import { zcodeVisibleMessageFilter } from '../../../ai-vault/scanners/zcode/session-scanner-zcode-visibility' +import { zcodeTranscriptOrder } from '../../../ai-vault/scanners/zcode/session-scanner-zcode-order' import { readOpenCode2TranscriptPage, readOpenCode2TranscriptSignal } from './transcript-opencode2-sqlite' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' -import { columnExists, tableExists } from '../opencode-usage/schema-helpers' -import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' -import type SyncDatabase from '../sqlite/sync-database' +import type { NativeChatMessage } from '../../../../shared/native-chat/native-chat-types' +import { openCodeTranscriptPageLimit } from '../../../../shared/opencode-transcript-page-limit' +import { columnExists, tableExists } from '../../../opencode-usage/schema-helpers' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../../shared/trimmed-string' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' +import type SyncDatabase from '../../../sqlite/sync-database' import { rowsOf, rowsWithinBudget } from './transcript-opencode-row-budget' import { opencodeMessages, @@ -180,18 +182,7 @@ export function readOpenCodeTranscriptPage(args: { hasMore = rows.length > limit const selected = hasMore ? rows.slice(0, limit) : rows cursor = selected.at(-1)!.message_rowid - for (const row of selected) { - const record = row.data === null ? null : parseJsonObject(row.data) - forkTip.push({ - id: row.id, - role: String(record?.role), - terminal: - record?.role === 'assistant' && - typeof asRecord(record.time)?.completed === 'number' && - record.finish !== 'tool-calls' - }) - } - const mapped = mapMessageRows(db, args.sessionId, selected, rawBudget, args.agent) + const mapped = mapMessageRows(db, args.sessionId, selected, rawBudget, forkTip, args.agent) pageBytes += Buffer.byteLength(JSON.stringify(mapped)) if (pageBytes > 16 * 1024 * 1024) { throw new Error('OpenCode transcript page exceeds its byte limit') @@ -243,6 +234,7 @@ function mapMessageRows( sessionId: string, rows: MessageRow[], rawBudget: { bytes: number }, + forkTip: OpenCodeForkTipEvent[], agent?: 'zcode' ): OpenCodeTranscriptItem[] { if (rows.length === 0) { @@ -279,6 +271,14 @@ function mapMessageRows( for (const row of rows) { const partList = partsByMessage.get(row.id) ?? [] const record = row.data === null ? null : parseJsonObject(row.data) + forkTip.push({ + id: row.id, + role: String(record?.role), + terminal: + record?.role === 'assistant' && + typeof asRecord(record.time)?.completed === 'number' && + record.finish !== 'tool-calls' + }) const role = extractString(record?.role) const messages = opencodeMessages( { diff --git a/src/main/native-chat/transcript-opencode-subscribe.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode-subscribe.ts similarity index 97% rename from src/main/native-chat/transcript-opencode-subscribe.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode-subscribe.ts index 4f694ff5834..ac6f89fb523 100644 --- a/src/main/native-chat/transcript-opencode-subscribe.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode-subscribe.ts @@ -1,18 +1,18 @@ import { pruneOpenCodeFingerprintCache } from './transcript-opencode-fingerprint-window' -export { pruneOpenCodeFingerprintCache as pruneOpenCodeFingerprintCacheForTest } from './transcript-opencode-fingerprint-window' -import { errorMessage } from '../ai-vault/session-scanner-values' + +import { errorMessage } from '../../../../shared/error-message' import { DESKTOP_READ_WINDOW, UNFLUSHED_SETTLE_MS, type NativeChatTranscriptSubscription, type SubscribeNativeChatTranscriptArgs -} from './transcript-watch-contract' +} from '../../transcript-watching/transcript-watch-contract' import type { OpenCodeTranscriptItem } from './transcript-opencode-sqlite-query' import { openCodeTranscriptDefaultDeps, type OpenCodeTranscriptDeps } from './transcript-opencode' import { openCodeTranscriptPageLimit, OPENCODE_TRANSCRIPT_MAX_WINDOW -} from '../../shared/opencode-transcript-page-limit' +} from '../../../../shared/opencode-transcript-page-limit' const OPENCODE_POLL_MS = 1_000 diff --git a/src/main/native-chat/transcript-opencode.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode.ts similarity index 88% rename from src/main/native-chat/transcript-opencode.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode.ts index 7bcb66b6e97..473f8113f4e 100644 --- a/src/main/native-chat/transcript-opencode.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode.ts @@ -1,4 +1,4 @@ -import { createImportedForkTip } from './agent-session-journal/history-import/imported-fork-tip' +import { createImportedForkTip } from '../../agent-session-journal/history-import/imported-fork-tip' import type { OpenCodeForkTipEvent, OpenCodeTranscriptItem, @@ -8,17 +8,17 @@ import type { import { OPENCODE_CAPTURE_RECORD_LIMIT, OPENCODE_CAPTURE_TEXT_LIMIT -} from '../ai-vault/scanners/opencode/sqlite/opencode-transcript-capture-limits' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { errorMessage } from '../ai-vault/session-scanner-values' -import type { ReadTranscriptResult } from './transcript-reader' +} from '../../../ai-vault/scanners/opencode/sqlite/opencode-transcript-capture-limits' +import type { NativeChatMessage } from '../../../../shared/native-chat/native-chat-types' +import { errorMessage } from '../../../../shared/error-message' +import type { ReadTranscriptResult } from '../../transcript-reader' import { readOpenCodeTranscriptPageViaWorker, readOpenCodeTranscriptSignalViaWorker -} from '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn' +} from '../../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn' import { discoverOpenCodeTranscriptDatabase } from './transcript-opencode-database' -import { DESKTOP_READ_WINDOW } from './transcript-watch-contract' -import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' +import { DESKTOP_READ_WINDOW } from '../../transcript-watching/transcript-watch-contract' +import { openCodeTranscriptPageLimit } from '../../../../shared/opencode-transcript-page-limit' export type OpenCodeTranscriptDeps = { resolveDbPath?: ( diff --git a/src/main/native-chat/transcript-opencode2-fork-coverage.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode2-fork-coverage.ts similarity index 91% rename from src/main/native-chat/transcript-opencode2-fork-coverage.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode2-fork-coverage.ts index 04e470dd0ff..a6902f95535 100644 --- a/src/main/native-chat/transcript-opencode2-fork-coverage.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode2-fork-coverage.ts @@ -1,6 +1,7 @@ -import type SyncDatabase from '../sqlite/sync-database' -import { tableExists } from '../opencode-usage/schema-helpers' -import { asRecord, parseJsonObject } from '../ai-vault/session-scanner-values' +import type SyncDatabase from '../../../sqlite/sync-database' +import { tableExists } from '../../../opencode-usage/schema-helpers' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' import { hasOpenCode2Session } from './transcript-opencode2-sqlite' export function readOpenCode2ForkCoverage( diff --git a/src/main/native-chat/transcript-opencode2-sqlite.ts b/src/main/native-chat/transcript-history/opencode/transcript-opencode2-sqlite.ts similarity index 91% rename from src/main/native-chat/transcript-opencode2-sqlite.ts rename to src/main/native-chat/transcript-history/opencode/transcript-opencode2-sqlite.ts index 53fc07115e9..fee3e84a89a 100644 --- a/src/main/native-chat/transcript-opencode2-sqlite.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-opencode2-sqlite.ts @@ -1,13 +1,15 @@ import { createHash } from 'node:crypto' -import type SyncDatabase from '../sqlite/sync-database' -import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' -import { columnExists, tableExists } from '../opencode-usage/schema-helpers' -import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' +import type SyncDatabase from '../../../sqlite/sync-database' +import { openCodeTranscriptPageLimit } from '../../../../shared/opencode-transcript-page-limit' +import { columnExists, tableExists } from '../../../opencode-usage/schema-helpers' +import { asRecord } from '../../../ai-vault/parsing/session-record-fields' +import { extractString } from '../../../../shared/trimmed-string' +import { parseJsonObject } from '../../../ai-vault/parsing/session-json-object' import { opencodeMessages, OPENCODE_TRANSCRIPT_MAX_ROW_BYTES } from './transcript-opencode-part-blocks' -import type { NativeChatBlock } from '../../shared/native-chat/native-chat-types' +import type { NativeChatBlock } from '../../../../shared/native-chat/native-chat-types' import type { OpenCodeTranscriptPage, OpenCodeTranscriptSignal, @@ -60,7 +62,10 @@ export function readOpenCode2TranscriptSignal( } } -function messageItems(value: unknown): OpenCodeTranscriptItem[] { +function messageItems( + value: unknown, + record: Record | null +): OpenCodeTranscriptItem[] { const row = asRecord(value) if ( typeof row?.id !== 'string' || @@ -94,7 +99,6 @@ function messageItems(value: unknown): OpenCodeTranscriptItem[] { throw new Error('OpenCode transcript message is invalid') } const messageId = row.id - const record = parseJsonObject(row.data) if (!record) { throw new Error('OpenCode transcript message contains invalid JSON') } @@ -226,7 +230,7 @@ export function readOpenCode2TranscriptPage( row.type === 'idle' && ['succeeded', 'interrupted', 'failed'].includes(String(record?.outcome)) }) - const mapped = messageItems(value) + const mapped = messageItems(value, record) cursor = row.cursor for (const item of mapped) { pageBytes += Buffer.byteLength(JSON.stringify(item)) diff --git a/src/main/native-chat/transcript-zcode.test.ts b/src/main/native-chat/transcript-history/opencode/transcript-zcode.test.ts similarity index 98% rename from src/main/native-chat/transcript-zcode.test.ts rename to src/main/native-chat/transcript-history/opencode/transcript-zcode.test.ts index d8ac97ba68e..855aedd24a3 100644 --- a/src/main/native-chat/transcript-zcode.test.ts +++ b/src/main/native-chat/transcript-history/opencode/transcript-zcode.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import Database from '../sqlite/sync-database' +import Database from '../../../sqlite/sync-database' import { readOpenCodeTranscriptPage, readOpenCodeTranscriptSignal diff --git a/src/main/native-chat/transcript-interruption-message.test.ts b/src/main/native-chat/transcript-interruption-message.test.ts deleted file mode 100644 index 5d2d2c3ccbe..00000000000 --- a/src/main/native-chat/transcript-interruption-message.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - NATIVE_CHAT_INTERRUPTED_STATUS_TEXT, - type NativeChatMessage -} from '../../shared/native-chat/native-chat-types' -import { stripNoiseMessages } from '../../shared/native-chat/native-chat-noise' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' -import { decodeCodexTranscriptLine } from './transcript-line-decoders-codex' - -function expectNormalizedInterruption(message: NativeChatMessage | null): void { - expect(message).toMatchObject({ - role: 'system', - blocks: [{ type: 'text', text: NATIVE_CHAT_INTERRUPTED_STATUS_TEXT }], - source: 'transcript' - }) - expect(stripNoiseMessages(message ? [message] : [])).toEqual([message]) -} - -describe('native chat transcript interruption messages', () => { - it('normalizes Claude interruption boilerplate into one visible status row', () => { - const message = decodeClaudeTranscriptLine( - JSON.stringify({ - type: 'user', - uuid: 'interrupt-row', - interruptedMessageId: 'assistant-request-1', - timestamp: '2026-07-16T23:46:01.000Z', - message: { - role: 'user', - content: [{ type: 'text', text: '[Request interrupted by user]' }] - } - }), - 'fallback' - ) - - expectNormalizedInterruption(message) - expect(message?.id).toBe('interrupt-row') - }) - - it('normalizes Codex turn_aborted into one visible status row', () => { - const message = decodeCodexTranscriptLine( - JSON.stringify({ - type: 'event_msg', - timestamp: '2026-07-16T23:46:01.000Z', - payload: { type: 'turn_aborted', reason: 'interrupted', turn_id: 'turn-2' } - }), - 'fallback' - ) - - expectNormalizedInterruption(message) - expect(message?.id).toBe('fallback') - }) -}) diff --git a/src/main/native-chat/transcript-line-decoders-claude-command-output.test.ts b/src/main/native-chat/transcript-line-decoders-claude-command-output.test.ts deleted file mode 100644 index 09a6cf28e19..00000000000 --- a/src/main/native-chat/transcript-line-decoders-claude-command-output.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { surfaceNativeChatCommandOutputs } from '../../shared/native-chat/tools/native-chat-command-output' -import { stripNoiseMessages } from '../../shared/native-chat/native-chat-noise' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' - -// OpenClaude 0.31.0: /context, /cost, /context without model calls; session ID/cwd scrubbed. -const FIXTURE_LINES = readFileSync( - join(__dirname, '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), - 'utf8' -) - .split('\n') - .filter((line) => line.trim() !== '') - -function decoded(lines: readonly string[]): NativeChatMessage[] { - return lines.flatMap((line, index) => decodeClaudeTranscriptLine(line, `f${index}`) ?? []) -} - -function commandRow(messages: NativeChatMessage[], index: number): NativeChatMessage | undefined { - return messages.filter((message) => - message.blocks.some((block) => block.type === 'text' && block.text.includes('')) - )[index] -} - -describe("OpenClaude's local command rows through the transcript decoder", () => { - const messages = decoded(FIXTURE_LINES) - - it("links each reply row to its command row's id", () => { - const replies = messages.filter((message) => - message.blocks.some( - (block) => block.type === 'text' && block.text.includes('') - ) - ) - expect(replies.map(({ parentId }) => parentId)).toEqual([ - commandRow(messages, 0)?.id, - commandRow(messages, 2)?.id - ]) - }) - - it('shows both /context reports as plain command output and nothing else', () => { - const visible = stripNoiseMessages(surfaceNativeChatCommandOutputs(messages, 'openclaude')) - expect(visible.map(({ role }) => role)).toEqual(['system', 'system']) - const totals = visible.map(({ blocks: [block] }) => { - expect(block).toMatchObject({ type: 'text', presentation: 'command-output' }) - const text = block?.type === 'text' ? block.text : '' - expect(text.split('\n')[0]).toBe('Context Usage') - expect(text).not.toContain('\u001b') - return /gpt-4o · \S+ tokens \(\d+%\)/.exec(text)?.[0] - }) - expect(totals).toEqual(['gpt-4o · 18.3k/128k tokens (14%)', 'gpt-4o · 18.9k/128k tokens (15%)']) - }) - - it('keeps the reply hidden for a host that sends no row link', () => { - const unlinked = messages.map(({ parentId: _parentId, ...message }) => message) - expect(stripNoiseMessages(surfaceNativeChatCommandOutputs(unlinked, 'openclaude'))).toEqual([]) - }) -}) diff --git a/src/main/native-chat/transcript-line-decoders-claude-control-bytes.test.ts b/src/main/native-chat/transcript-line-decoders-claude-control-bytes.test.ts deleted file mode 100644 index 404c3b403ce..00000000000 --- a/src/main/native-chat/transcript-line-decoders-claude-control-bytes.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - normalizeNativeChatUserText, - normalizedNativeChatUserMessageText -} from '../../shared/native-chat/transcript/native-chat-image-transcript-markers' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' - -const COMPOSER_TEXT = 'line 000 xxxxxxxxxx\nline 001 xxxxxxxxxx\nline 002 xxxxxxxxxx' - -// Matches the string-content shape observed when a TUI records Ctrl+U with the prompt. -const MOBILE_SEND_LINE = JSON.stringify({ - type: 'user', - uuid: 'synthetic-user-turn', - message: { role: 'user', content: `\u0015${COMPOSER_TEXT}` } -}) - -describe('decodeClaudeTranscriptLine on a mobile-sent prompt', () => { - it('keeps the Ctrl+U byte the TUI pasted into the prompt', () => { - const message = decodeClaudeTranscriptLine(MOBILE_SEND_LINE, 'fallback') - expect(message?.role).toBe('user') - expect(message?.blocks[0]).toEqual({ - type: 'text', - text: `\u0015${COMPOSER_TEXT}` - }) - }) - - it('normalizes to the composer text so the optimistic echo can retire', () => { - const message = decodeClaudeTranscriptLine(MOBILE_SEND_LINE, 'fallback')! - expect(normalizedNativeChatUserMessageText(message)).toBe( - normalizeNativeChatUserText(COMPOSER_TEXT) - ) - }) -}) diff --git a/src/main/native-chat/transcript-line-decoders-claude-image-companion.test.ts b/src/main/native-chat/transcript-line-decoders-claude-image-companion.test.ts deleted file mode 100644 index 0e6e6641309..00000000000 --- a/src/main/native-chat/transcript-line-decoders-claude-image-companion.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { normalizeImageTranscriptMessages } from '../../shared/native-chat/transcript/native-chat-image-transcript-markers' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' - -// Claude 2.1.237 stores source paths in separate isMeta/turnCompanion rows; prompt base64 has no path. -const PROMPT_ROW = JSON.stringify({ - type: 'user', - uuid: 'prompt-uuid', - timestamp: '2026-09-01T01:33:04.608Z', - message: { - role: 'user', - content: [ - { type: 'text', text: 'look at this\r[Image #1] [Image #2] does it repro?' }, - { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: 'AAAA' } }, - { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: 'BBBB' } } - ] - } -}) -const COMPANION_ROW = JSON.stringify({ - type: 'user', - uuid: 'companion-uuid', - isMeta: true, - turnCompanion: true, - timestamp: '2026-09-01T01:33:04.608Z', - message: { - role: 'user', - content: [ - { type: 'text', text: '[Image: source: /tmp/orca-paste-a.png]' }, - { type: 'text', text: '[Image: source: /tmp/orca-paste-b.png]' } - ] - } -}) - -function decode(): NativeChatMessage[] { - return [COMPANION_ROW, PROMPT_ROW] - .map((line, index) => decodeClaudeTranscriptLine(line, `fallback-${index}`)) - .filter((message): message is NativeChatMessage => message !== null) -} - -describe('Claude pasted-image companion row', () => { - it('folds a multi-image companion into the prompt as image refs', () => { - const folded = normalizeImageTranscriptMessages(decode()) - expect(folded).toHaveLength(1) - expect(folded[0]!.blocks.filter((b) => b.type === 'image-ref')).toEqual([ - { type: 'image-ref', path: '/tmp/orca-paste-a.png' }, - { type: 'image-ref', path: '/tmp/orca-paste-b.png' } - ]) - const text = folded[0]!.blocks - .filter((b) => b.type === 'text') - .map((b) => b.text) - .join('') - expect(text).toContain('look at this') - expect(text).toContain('does it repro?') - expect(text).not.toContain('[Image #') - }) - - it('still drops an ordinary isMeta injected turn', () => { - const injected = JSON.stringify({ - type: 'user', - uuid: 'injected', - isMeta: true, - message: { - role: 'user', - content: [{ type: 'text', text: 'Base directory for this skill: /x' }] - } - }) - expect(decodeClaudeTranscriptLine(injected, 'fallback')).toBeNull() - }) - - it('does not turn a mixed marker-and-prose meta row into an image source turn', () => { - const mixed = JSON.stringify({ - type: 'user', - uuid: 'mixed', - isMeta: true, - message: { - role: 'user', - content: [ - { type: 'text', text: '[Image: source: /tmp/a.png]' }, - { type: 'text', text: 'metadata prose' } - ] - } - }) - - expect(decodeClaudeTranscriptLine(mixed, 'fallback')).toBeNull() - }) - - it('retains tool results from a mixed meta row while dropping its marker text', () => { - const mixed = JSON.stringify({ - type: 'user', - uuid: 'mixed-tool', - isMeta: true, - message: { - role: 'user', - content: [ - { type: 'text', text: '[Image: source: /tmp/a.png]' }, - { type: 'tool_result', content: 'tool output' } - ] - } - }) - - expect(decodeClaudeTranscriptLine(mixed, 'fallback')).toMatchObject({ - id: 'mixed-tool', - role: 'tool', - blocks: [{ type: 'tool-result', output: 'tool output' }] - }) - }) -}) diff --git a/src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts b/src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts deleted file mode 100644 index 733baa0602b..00000000000 --- a/src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { nativeChatRowTurnKeys } from '../../shared/native-chat/transcript/native-chat-turn-grouping' -import { - nativeChatTurnFold, - nativeChatTurnFoldRow -} from '../../shared/native-chat/transcript/native-chat-turn-fold' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' - -// Text rows of a Claude Code 2.1.316 turn whose Stop hook blocked once. -function stopHookTurn(feedback: string): string[] { - return [ - { type: 'user', uuid: 'prompt', message: { role: 'user', content: 'Say: the sky is blue' } }, - { - type: 'assistant', - uuid: 'reply', - message: { role: 'assistant', content: [{ type: 'text', text: 'The sky is blue.' }] } - }, - { - type: 'user', - uuid: 'feedback', - isMeta: true, - message: { role: 'user', content: `Stop hook feedback:\n${feedback}` } - }, - { - type: 'assistant', - uuid: 'continuation', - message: { role: 'assistant', content: [{ type: 'text', text: 'Evidence: I checked.' }] } - } - ].map((record) => JSON.stringify({ timestamp: '2026-11-01T05:33:22.035Z', ...record })) -} - -describe('a Claude turn its Stop hook sent back', () => { - it.each([ - ['a JSON block decision', 'Verify your statement with evidence.'], - ['an exit-2 hook', '[/tmp/hook.sh]: Verify your statement with evidence.\n'] - ])('keeps the reply and the hook row visible once settled (%s)', (_, feedback) => { - const messages = stopHookTurn(feedback).flatMap( - (line) => decodeClaudeTranscriptLine(line, 'fallback') ?? [] - ) - const turnKeys = nativeChatRowTurnKeys(messages) - const { foldedRows } = nativeChatTurnFold({ - rows: messages.map((message, index) => - nativeChatTurnFoldRow(message, turnKeys[index], false) - ), - settledTurnKeys: new Set(['prompt']), - expandedTurnKeys: new Set() - }) - expect( - messages.flatMap((message, index) => - foldedRows.has(index) ? [] : [[message.role, message.blocks[0]]] - ) - ).toEqual([ - ['user', { type: 'text', text: 'Say: the sky is blue' }], - ['assistant', { type: 'text', text: 'The sky is blue.' }], - [ - 'system', - expect.objectContaining({ - text: 'Stop hook feedback: Verify your statement with evidence.', - tone: 'warning' - }) - ], - ['assistant', { type: 'text', text: 'Evidence: I checked.' }] - ]) - }) -}) diff --git a/src/main/native-chat/transcript-line-decoders.ts b/src/main/native-chat/transcript-line-decoders.ts deleted file mode 100644 index 9e646485db8..00000000000 --- a/src/main/native-chat/transcript-line-decoders.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Stateless line decoders serve full reads and tailing; callers supply stable per-line fallback IDs. - -export { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' -export { decodeCodexTranscriptLine } from './transcript-line-decoders-codex' -export { decodeGrokTranscriptLine } from './transcript-line-decoders-grok' -export { decodeOmpTranscriptLine } from './transcript-line-decoders-omp' diff --git a/src/main/native-chat/transcript-opencode2-fork.test-fixture.ts b/src/main/native-chat/transcript-opencode2-fork.test-fixture.ts deleted file mode 100644 index 429f749df27..00000000000 --- a/src/main/native-chat/transcript-opencode2-fork.test-fixture.ts +++ /dev/null @@ -1,85 +0,0 @@ -import Database from '../sqlite/sync-database' - -// OpenCode 2.0.21 M1: copied seqs keep a fresh prefix; the event table is empty. -export function openCode2ForkStore(path: string) { - const db = new Database(path) - db.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY, parent_id TEXT, fork_session_id TEXT, fork_boundary TEXT); - CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, - seq INTEGER, data TEXT, time_created INTEGER, time_updated INTEGER); - CREATE TABLE event (id TEXT PRIMARY KEY, aggregate_id TEXT, type TEXT, seq INTEGER); - INSERT INTO session_v2 VALUES ('ses_e4d7a0c31ffejclsdjiiDszHMB', NULL, NULL, NULL); - INSERT INTO session_v2 VALUES ('ses_e4d797526ffee7BYM6ri3gpmbg', NULL, - 'ses_e4d7a0c31ffejclsdjiiDszHMB', '{"type":"through","messageID":"msg_1b2868a8e0026IQTGMmj77bBFi"}');`) - const insert = db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)') - for (const [session, user, idle] of [ - [ - 'ses_e4d7a0c31ffejclsdjiiDszHMB', - 'msg_1b285f9e10016X0Hu1rKOHAACe', - 'msg_1b2868a8e0026IQTGMmj77bBFi' - ], - [ - 'ses_e4d797526ffee7BYM6ri3gpmbg', - 'msg_1b2868ada001HhsJYcY0OtPOjp_4', - 'msg_1b2868ada001HhsJYcY0OtPOjp_87' - ] - ]) { - insert.run( - user!, - session!, - 'user', - 4, - JSON.stringify({ files: [{ uri: 'file:///image.png' }] }), - 1, - 1 - ) - insert.run(idle!, session!, 'idle', 87, '{"outcome":"succeeded"}', 1, 1) - } - // Match copied timestamps deliberately: time is not provenance. - insert.run( - 'msg_1b2868b430019orGpEpk0E3liv', - 'ses_e4d797526ffee7BYM6ri3gpmbg', - 'user', - 90, - '{"text":"CLI after fork"}', - 1, - 1 - ) - return db -} - -// OpenCode 1.19.5 M1: regenerated message IDs and empty newer-schema tables. -export function openCode1ForkStore(path: string) { - const db = new Database(path) - db.exec(`CREATE TABLE session (id TEXT PRIMARY KEY, parent_id TEXT); - CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, - time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL); - CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, - time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL); - CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, - seq INTEGER, data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session VALUES ('ses_e4d773f6affe3HGZP6SZo2NjZp', NULL); - INSERT INTO session VALUES ('ses_e4d76d713ffe98vxcM3WaxWjVI', NULL);`) - const insert = db.prepare('INSERT INTO message VALUES (?, ?, 1, 1, ?)') - insert.run('msg_1b288c688001YdJeVFY2Yyte5V', 'ses_e4d773f6affe3HGZP6SZo2NjZp', '{"role":"user"}') - for (const [id, role] of [ - ['msg_1b28928ed001PfHNbepa2ju4PH', 'user'], - ['msg_1b28928ee001wHBhq6QZzVGJ3f', 'assistant'], - ['msg_1b28928f5001P7iHSIEED9Iq2p', 'user'], - ['msg_1b28928f6001CkhDQSpYI3ByI4', 'user'], - ['msg_1b28928f80012WtB5Unb6QBY2Y', 'assistant'], - // Deliberately before capture: the accepted 1.x interval limitation covers this CLI root too. - ['msg_1b2892ade0019IigeE4JneP9j3', 'user'] - ]) { - insert.run(id!, 'ses_e4d76d713ffe98vxcM3WaxWjVI', JSON.stringify({ role })) - } - const part = db.prepare( - "INSERT INTO part VALUES (?, ?, 'ses_e4d76d713ffe98vxcM3WaxWjVI', 1, 1, ?)" - ) - part.run( - 'file-part', - 'msg_1b28928ed001PfHNbepa2ju4PH', - '{"type":"file","url":"file:///image.png"}' - ) - part.run('compaction-part', 'msg_1b28928f6001CkhDQSpYI3ByI4', '{"type":"compaction","auto":true}') - return db -} diff --git a/src/main/native-chat/transcript-opencode2-sqlite.test.ts b/src/main/native-chat/transcript-opencode2-sqlite.test.ts deleted file mode 100644 index 4983e43bf1d..00000000000 --- a/src/main/native-chat/transcript-opencode2-sqlite.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { openCode2ForkStore } from './transcript-opencode2-fork.test-fixture' -import { handleOpenCodeSqliteRequest } from '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-dispatch' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import Database from '../sqlite/sync-database' -import { readOpenCodeNativeChatTranscriptFull } from './transcript-opencode' -import { readOpenCodeTranscriptPage } from './transcript-opencode-sqlite-query' - -const fixtures: { db: Database.Database; root: string }[] = [] -afterEach(() => { - for (const { db, root } of fixtures.splice(0)) { - db.close() - rmSync(root, { recursive: true, force: true }) - } -}) -function fixture() { - const root = mkdtempSync(join(tmpdir(), 'orca-native-opencode2-')) - const path = join(root, 'opencode.db') - const db = new Database(path) - fixtures.push({ db, root }) - db.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY); - CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, - seq INTEGER, data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session_v2 VALUES ('session'); - ALTER TABLE session_v2 ADD COLUMN directory TEXT; - UPDATE session_v2 SET directory = '/folder';`) - const insertMessage = db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)') - let sequence = 0 - const insert = (id: string, type: string, data: unknown, time = 1) => - insertMessage.run(id, 'session', type, ++sequence, JSON.stringify(data), time, time) - return { path, insert, db } -} - -it.each([true, false])( - 'uses genuine v2 idle evidence for the imported latest root, completed: %s', - async (completed) => { - const { path, insert } = fixture() - insert('u1', 'user', { text: 'First prompt' }) - insert('a1', 'assistant', { content: [{ type: 'text', text: 'First response' }] }) - insert('idle1', 'idle', { outcome: 'succeeded' }) - insert('u2', 'user', { text: 'Latest prompt' }) - insert('a2', 'assistant', { content: [{ type: 'text', text: 'Latest prose' }] }) - if (completed) { - insert('idle2', 'idle', { outcome: 'succeeded' }) - } - const imported = await readOpenCodeNativeChatTranscriptFull('session', { - resolveDbPath: async () => path, - readPage: async (args) => readOpenCodeTranscriptPage(args) - }) - expect(imported).toMatchObject({ - forkTipItemIds: completed ? ['opencode:u2', 'opencode:a2', 'opencode:idle2'] : [] - }) - } -) - -it('captures the M1 copied roots without events, excludes a racing CLI root, and honors before', async () => { - const root = mkdtempSync(join(tmpdir(), 'orca-native-opencode2-fork-')) - const path = join(root, 'opencode.db') - const db = openCode2ForkStore(path) - fixtures.push({ db, root }) - const request = { - id: 1, - kind: 'fork-coverage' as const, - dbPath: path, - sessionId: 'ses_e4d797526ffee7BYM6ri3gpmbg', - sourceSessionId: 'ses_e4d7a0c31ffejclsdjiiDszHMB' - } - expect(await handleOpenCodeSqliteRequest(request)).toEqual({ - id: 1, - ok: true, - value: ['msg_1b2868ada001HhsJYcY0OtPOjp_4'] - }) - expect( - await handleOpenCodeSqliteRequest({ ...request, sourceSessionId: 'wrong-source' }) - ).toMatchObject({ ok: false }) - db.exec(`UPDATE session_v2 SET fork_boundary = - '{"type":"before","messageID":"msg_1b285f9e10016X0Hu1rKOHAACe"}' - WHERE id = 'ses_e4d797526ffee7BYM6ri3gpmbg'; - DELETE FROM session_message WHERE session_id = 'ses_e4d797526ffee7BYM6ri3gpmbg' AND seq < 90;`) - expect(await handleOpenCodeSqliteRequest(request)).toEqual({ id: 1, ok: true, value: [] }) -}) diff --git a/src/main/native-chat/transcript-read-cache.ts b/src/main/native-chat/transcript-read-cache.ts index 01f6b425545..20d886c758e 100644 --- a/src/main/native-chat/transcript-read-cache.ts +++ b/src/main/native-chat/transcript-read-cache.ts @@ -1,15 +1,15 @@ import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' -import { readOpenCodeNativeChatTranscriptFull } from './transcript-opencode' +import { readOpenCodeNativeChatTranscriptFull } from './transcript-history/opencode/transcript-opencode' import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' import { InFlightPromiseDedupe, stableInFlightKey } from '../../shared/in-flight-promise-dedupe' import { resolveSessionFilePath } from './session-file-resolver' import { readNativeChatTranscript, type ReadTranscriptResult } from './transcript-reader' -import { wslGatedStat } from './wsl-transcript-fs-access' +import { wslGatedStat } from './transcript-filesystem/wsl-transcript-fs-access' import { isWslTranscriptFsRefusalMessage, WslTranscriptFsError, wslTranscriptFsRefusal -} from './wsl-transcript-fs-error' +} from './transcript-filesystem/wsl-transcript-fs-error' // Share one unwindowed parse per resolved path across desktop and paired clients. // Session IDs can resolve to different worktree files; connection keys would duplicate memory. diff --git a/src/main/native-chat/transcript-reader.ts b/src/main/native-chat/transcript-reader.ts index 97dad1b6080..f13420f58f9 100644 --- a/src/main/native-chat/transcript-reader.ts +++ b/src/main/native-chat/transcript-reader.ts @@ -1,4 +1,4 @@ -import { readOpenCodeNativeChatTranscriptFull } from './transcript-opencode' +import { readOpenCodeNativeChatTranscriptFull } from './transcript-history/opencode/transcript-opencode' import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' import type { @@ -6,17 +6,15 @@ import type { NativeChatTurnLifecycle } from '../../shared/native-chat/native-chat-types' import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' -import { errorMessage } from '../ai-vault/session-scanner-values' +import { errorMessage } from '../../shared/error-message' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' -import { openTranscriptReadStream } from './wsl-transcript-fs-access' -import { wslTranscriptFsRefusal } from './wsl-transcript-fs-gate' -import { - decodeClaudeTranscriptLine, - decodeCodexTranscriptLine, - decodeGrokTranscriptLine, - decodeOmpTranscriptLine -} from './transcript-line-decoders' -import { decodeTranscriptStream } from './transcript-stream-lines' +import { openTranscriptReadStream } from './transcript-filesystem/wsl-transcript-fs-access' +import { wslTranscriptFsRefusal } from './transcript-filesystem/wsl-transcript-fs-error' +import { decodeClaudeTranscriptLine } from './transcript-decoding/transcript-line-decoders-claude' +import { decodeCodexTranscriptLine } from './transcript-decoding/transcript-line-decoders-codex' +import { decodeGrokTranscriptLine } from './transcript-decoding/transcript-line-decoders-grok' +import { decodeOmpTranscriptLine } from './transcript-decoding/transcript-line-decoders-omp' +import { decodeTranscriptStream } from './transcript-streaming/transcript-stream-lines' export type ReadTranscriptResult = | { diff --git a/src/main/native-chat/transcript-fallback-id.ts b/src/main/native-chat/transcript-streaming/transcript-fallback-id.ts similarity index 100% rename from src/main/native-chat/transcript-fallback-id.ts rename to src/main/native-chat/transcript-streaming/transcript-fallback-id.ts diff --git a/src/main/native-chat/transcript-file-order.ts b/src/main/native-chat/transcript-streaming/transcript-file-order.ts similarity index 89% rename from src/main/native-chat/transcript-file-order.ts rename to src/main/native-chat/transcript-streaming/transcript-file-order.ts index 75ba5ce62ec..5d567324d91 100644 --- a/src/main/native-chat/transcript-file-order.ts +++ b/src/main/native-chat/transcript-streaming/transcript-file-order.ts @@ -1,4 +1,4 @@ -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' +import type { NativeChatMessage } from '../../../shared/native-chat/native-chat-types' /** Modern readers use record position; legacy readers retain their historical backward-clock clamp. */ export function inTranscriptFileOrder( diff --git a/src/main/native-chat/transcript-stream-lines.test.ts b/src/main/native-chat/transcript-streaming/transcript-stream-lines.test.ts similarity index 100% rename from src/main/native-chat/transcript-stream-lines.test.ts rename to src/main/native-chat/transcript-streaming/transcript-stream-lines.test.ts diff --git a/src/main/native-chat/transcript-stream-lines.ts b/src/main/native-chat/transcript-streaming/transcript-stream-lines.ts similarity index 97% rename from src/main/native-chat/transcript-stream-lines.ts rename to src/main/native-chat/transcript-streaming/transcript-stream-lines.ts index 20ce58d5fe7..8d96b627ab0 100644 --- a/src/main/native-chat/transcript-stream-lines.ts +++ b/src/main/native-chat/transcript-streaming/transcript-stream-lines.ts @@ -1,6 +1,6 @@ import type { Readable } from 'node:stream' import { StringDecoder } from 'node:string_decoder' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' +import type { NativeChatMessage } from '../../../shared/native-chat/native-chat-types' import { transcriptFallbackId } from './transcript-fallback-id' import { inTranscriptFileOrder } from './transcript-file-order' diff --git a/src/main/native-chat/transcript-zstd-decompression.test.ts b/src/main/native-chat/transcript-streaming/transcript-zstd-decompression.test.ts similarity index 100% rename from src/main/native-chat/transcript-zstd-decompression.test.ts rename to src/main/native-chat/transcript-streaming/transcript-zstd-decompression.test.ts diff --git a/src/main/native-chat/transcript-zstd-decompression.ts b/src/main/native-chat/transcript-streaming/transcript-zstd-decompression.ts similarity index 100% rename from src/main/native-chat/transcript-zstd-decompression.ts rename to src/main/native-chat/transcript-streaming/transcript-zstd-decompression.ts diff --git a/src/main/native-chat/transcript-tail-reader.ts b/src/main/native-chat/transcript-tail-reader.ts index 83c3e6f9f0a..e6f32d41d6c 100644 --- a/src/main/native-chat/transcript-tail-reader.ts +++ b/src/main/native-chat/transcript-tail-reader.ts @@ -1,4 +1,4 @@ -import { readOpenCodeNativeChatTranscriptTail } from './transcript-opencode' +import { readOpenCodeNativeChatTranscriptTail } from './transcript-history/opencode/transcript-opencode' import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' import type { @@ -7,31 +7,29 @@ import type { } from '../../shared/native-chat/native-chat-types' import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' -import { - decodeClaudeTranscriptLine, - decodeCodexTranscriptLine, - decodeGrokTranscriptLine, - decodeOmpTranscriptLine -} from './transcript-line-decoders' -import { transcriptFallbackId } from './transcript-fallback-id' -import { inTranscriptFileOrder } from './transcript-file-order' -import { extendTranscriptBoundary } from './transcript-file-version' +import { decodeClaudeTranscriptLine } from './transcript-decoding/transcript-line-decoders-claude' +import { decodeCodexTranscriptLine } from './transcript-decoding/transcript-line-decoders-codex' +import { decodeGrokTranscriptLine } from './transcript-decoding/transcript-line-decoders-grok' +import { decodeOmpTranscriptLine } from './transcript-decoding/transcript-line-decoders-omp' +import { transcriptFallbackId } from './transcript-streaming/transcript-fallback-id' +import { inTranscriptFileOrder } from './transcript-streaming/transcript-file-order' +import { extendTranscriptBoundary } from './transcript-watching/transcript-file-version' import { nativeChatTurnLifecycleDecoderForAgent, type NativeChatTurnLifecycleDecoder -} from './transcript-turn-lifecycle' +} from './transcript-decoding/transcript-turn-lifecycle' import { findLastCompleteLineEnd, readTranscriptByteAt, TAIL_CHUNK_BYTES -} from './transcript-tail-boundary' +} from './transcript-watching/transcript-tail-boundary' import { closeTranscriptHandle, openTranscriptFile, readTranscriptFile, transcriptFileStat -} from './wsl-transcript-fs-access' -import { wslTranscriptFsRefusal } from './wsl-transcript-fs-gate' +} from './transcript-filesystem/wsl-transcript-fs-access' +import { wslTranscriptFsRefusal } from './transcript-filesystem/wsl-transcript-fs-error' export const MAX_NATIVE_CHAT_TRANSCRIPT_RECORD_BYTES = 2 * 1024 * 1024 diff --git a/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts b/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts deleted file mode 100644 index 75d4117cd36..00000000000 --- a/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFsPromisesModule from 'node:fs/promises' - -const UNC_PATH = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions\\rollout.jsonl' -const EMPTY_STATS = { size: 0, mtimeMs: 1, ctimeMs: 1, ino: 1, dev: 1 } - -const mocks = vi.hoisted(() => ({ - bind: vi.fn(), - dispose: vi.fn(), - filterRunning: vi.fn(), - invalidate: vi.fn(), - observe: vi.fn(), - observation: undefined as ((running: boolean) => Promise | void) | undefined, - rebindNeeded: true, - stat: vi.fn() -})) - -vi.mock('../wsl/filesystem/wsl-running-path-filter', () => ({ - filterPathsToRunningWslDistrosAsync: mocks.filterRunning -})) -vi.mock('node:fs/promises', async (importOriginal) => ({ - ...(await importOriginal()), - stat: mocks.stat -})) -vi.mock('../../shared/transcript-native-watcher', () => ({ - createTranscriptNativeWatcher: () => ({ - bind: mocks.bind, - dispose: mocks.dispose, - invalidate: mocks.invalidate, - needsRebind: () => mocks.rebindNeeded - }) -})) -vi.mock('./wsl-transcript-running-observer', () => ({ - observeWslTranscriptRunningState: mocks.observe -})) - -import { installTranscriptWatcher } from './transcript-watch-engine' - -describe('installed WSL transcript watcher lifecycle', () => { - beforeEach(() => { - vi.useFakeTimers() - mocks.rebindNeeded = true - mocks.bind.mockReset().mockImplementation(() => { - mocks.rebindNeeded = false - return true - }) - mocks.dispose.mockReset() - mocks.filterRunning.mockReset().mockResolvedValue([UNC_PATH]) - mocks.invalidate.mockReset().mockImplementation(() => { - mocks.rebindNeeded = true - }) - mocks.observation = undefined - mocks.observe.mockReset().mockImplementation((_path, onRunning, onStopped) => { - mocks.observation = (running) => (running ? onRunning() : onStopped()) - return vi.fn() - }) - mocks.stat.mockReset().mockResolvedValue(EMPTY_STATS) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('settles the guarded initial drain when the distro stops after install', async () => { - const onInitialSnapshot = vi.fn() - const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { - agent: 'codex', - sessionId: 'wsl-session', - reconciliationIntervalMs: 100, - onAppend: () => {}, - onInitialSnapshot - }) - expect(subscription).not.toBeNull() - - mocks.filterRunning.mockResolvedValue([]) - const statsAfterInstall = mocks.stat.mock.calls.length - await vi.advanceTimersByTimeAsync(50) - - expect(mocks.stat).toHaveBeenCalledTimes(statsAfterInstall) - expect(onInitialSnapshot).toHaveBeenCalledWith([], false, 0, 'Transcript unavailable') - subscription?.unsubscribe() - }) - - it('does not settle after unsubscribe wins a delayed running probe', async () => { - const onInitialSnapshot = vi.fn() - const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { - agent: 'codex', - sessionId: 'wsl-session', - onAppend: () => {}, - onInitialSnapshot - }) - let finishProbe: (() => void) | undefined - mocks.filterRunning.mockImplementationOnce( - () => - new Promise((resolve) => { - finishProbe = () => resolve([]) - }) - ) - - const drain = vi.advanceTimersByTimeAsync(50) - await vi.waitFor(() => expect(finishProbe).toBeDefined()) - subscription?.unsubscribe() - finishProbe?.() - await drain - - expect(onInitialSnapshot).not.toHaveBeenCalled() - }) - - it('suspends observation while stopped and resumes after an explicit start', async () => { - const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { - agent: 'codex', - sessionId: 'wsl-session', - reconciliationIntervalMs: 100, - onAppend: () => {} - }) - await vi.advanceTimersByTimeAsync(50) - const statsBeforeStop = mocks.stat.mock.calls.length - - mocks.observation?.(false) - await vi.advanceTimersByTimeAsync(100) - expect(mocks.stat).toHaveBeenCalledTimes(statsBeforeStop) - - mocks.filterRunning.mockResolvedValue([UNC_PATH]) - mocks.observation?.(true) - await vi.advanceTimersByTimeAsync(0) - - expect(mocks.stat.mock.calls.length).toBeGreaterThan(statsBeforeStop) - expect(mocks.bind).not.toHaveBeenCalled() - subscription?.unsubscribe() - }) - - it('defers a failed observed UNC probe to the next shared observation', async () => { - const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { - agent: 'codex', - sessionId: 'wsl-session', - onAppend: () => {} - }) - await vi.advanceTimersByTimeAsync(50) - mocks.filterRunning.mockClear().mockResolvedValue([]) - mocks.stat.mockClear().mockRejectedValueOnce(new Error('distro stopped')) - - await mocks.observation?.(true) - - expect(mocks.stat).toHaveBeenCalledTimes(1) - expect(mocks.filterRunning).not.toHaveBeenCalled() - await mocks.observation?.(false) - expect(mocks.stat).toHaveBeenCalledTimes(1) - subscription?.unsubscribe() - }) -}) diff --git a/src/main/native-chat/transcript-watch-unflushed-settle.test.ts b/src/main/native-chat/transcript-watch-unflushed-settle.test.ts deleted file mode 100644 index abcd0c47c41..00000000000 --- a/src/main/native-chat/transcript-watch-unflushed-settle.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' - -const mocks = vi.hoisted(() => ({ - install: vi.fn(), - resolve: vi.fn() -})) - -vi.mock('./session-file-resolver', () => ({ - resolveSessionFilePath: mocks.resolve -})) -vi.mock('./transcript-watch-engine', () => ({ - getActiveNativeChatWatcherCount: vi.fn(() => 0), - installTranscriptWatcher: mocks.install -})) - -import { subscribeNativeChatTranscript } from './transcript-watch' -import { WslTranscriptFsError } from './wsl-transcript-fs-gate' - -type Snapshot = [NativeChatMessage[], boolean, number, string | undefined] - -const realPlatform = process.platform - -function subscribeCollecting( - snapshots: Snapshot[], - onTranscriptPending: () => void = () => {} -): Promise<{ unsubscribe: () => void }> { - return subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session-id', - transcriptPath: '/projects/p/session-id.jsonl', - resolvePollIntervalMs: 10, - onAppend: () => {}, - onTranscriptPending, - onInitialSnapshot: (messages, hasMore, beforeOffset, error) => { - snapshots.push([messages, hasMore, beforeOffset, error]) - } - }) -} - -describe('unflushed transcript settles the view', () => { - beforeEach(() => { - vi.useFakeTimers() - mocks.install.mockReset().mockResolvedValue(null) - mocks.resolve.mockReset().mockResolvedValue(null) - Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) - }) - - afterEach(() => { - Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true }) - vi.useRealTimers() - }) - - it('reports the pending transcript once while it stays unflushed', async () => { - const pending = vi.fn() - const snapshots: Snapshot[] = [] - const subscription = await subscribeCollecting(snapshots, pending) - - await vi.advanceTimersByTimeAsync(1_400) - expect(pending).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(200) - expect(pending).toHaveBeenCalledTimes(1) - // Pending must not masquerade as an empty snapshot and overwrite retained history. - expect(snapshots).toEqual([]) - - await vi.advanceTimersByTimeAsync(30_000) - expect(pending).toHaveBeenCalledTimes(1) - - subscription.unsubscribe() - }) - - it('leaves the settle to the real snapshot when the file lands inside the grace window', async () => { - const unsubscribe = vi.fn() - mocks.install.mockResolvedValueOnce(null).mockResolvedValue({ unsubscribe, watching: true }) - const pending = vi.fn() - const subscription = await subscribeCollecting([], pending) - - await vi.advanceTimersByTimeAsync(5_000) - // The engine supplies the real snapshot; emitting empty here would flash away history. - expect(pending).not.toHaveBeenCalled() - - subscription.unsubscribe() - }) - - it('does not report a subscription that was torn down first', async () => { - const pending = vi.fn() - const subscription = await subscribeCollecting([], pending) - - await vi.advanceTimersByTimeAsync(100) - subscription.unsubscribe() - await vi.advanceTimersByTimeAsync(5_000) - - expect(pending).not.toHaveBeenCalled() - }) - - it('keeps the WSL gate message instead of overwriting it with the empty window', async () => { - const stalled = new WslTranscriptFsError('timeout', 'WSL transcript files are unavailable.') - mocks.install.mockRejectedValue(stalled) - const pending = vi.fn() - const snapshots: Snapshot[] = [] - const subscription = await subscribeCollecting(snapshots, pending) - - await vi.advanceTimersByTimeAsync(5_000) - - expect(snapshots).toEqual([[[], false, 0, stalled.message]]) - expect(pending).not.toHaveBeenCalled() - - subscription.unsubscribe() - }) -}) diff --git a/src/main/native-chat/transcript-watch.ts b/src/main/native-chat/transcript-watch.ts index 2a20c19dd7b..1128251481b 100644 --- a/src/main/native-chat/transcript-watch.ts +++ b/src/main/native-chat/transcript-watch.ts @@ -1,5 +1,5 @@ -import { UNFLUSHED_SETTLE_MS } from './transcript-watch-contract' -import { subscribeOpenCodeNativeChatTranscript } from './transcript-opencode-subscribe' +import { UNFLUSHED_SETTLE_MS } from './transcript-watching/transcript-watch-contract' +import { subscribeOpenCodeNativeChatTranscript } from './transcript-history/opencode/transcript-opencode-subscribe' import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' import { extname } from 'node:path' import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' @@ -7,23 +7,19 @@ import { needsWslHostResolution, toHostReadableTranscriptPath, type WslTranscriptResolutionSnapshot -} from './host-readable-transcript-path' +} from './transcript-discovery/host-readable-transcript-path' import { resolveSessionFilePath } from './session-file-resolver' -import { installTranscriptWatcher } from './transcript-watch-engine' +import { installTranscriptWatcher } from './transcript-watching/transcript-watch-engine' import type { NativeChatTranscriptSubscription, SubscribeNativeChatTranscriptArgs -} from './transcript-watch-contract' +} from './transcript-watching/transcript-watch-contract' import { nativeChatLineDecoderForAgent } from './transcript-tail-reader' -import { WslTranscriptFsError, wslTranscriptFsRefusal } from './wsl-transcript-fs-gate' -import { observeRunningWslDistros } from './wsl-transcript-running-observer' - -export { readNativeChatTranscriptTail } from './transcript-tail-reader' -export { getActiveNativeChatWatcherCount } from './transcript-watcher-count' -export type { - NativeChatTranscriptSubscription, - SubscribeNativeChatTranscriptArgs -} from './transcript-watch-contract' +import { + WslTranscriptFsError, + wslTranscriptFsRefusal +} from './transcript-filesystem/wsl-transcript-fs-error' +import { observeRunningWslDistros } from './transcript-filesystem/wsl-transcript-running-observer' /** Unresolved files retry; native watch failure still permits reconciliation-only mode. */ async function attemptInstall( diff --git a/src/main/native-chat/transcript-watcher-install-probe.ts b/src/main/native-chat/transcript-watcher-install-probe.ts deleted file mode 100644 index 8fe3488829d..00000000000 --- a/src/main/native-chat/transcript-watcher-install-probe.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { transcriptFileStat } from './wsl-transcript-fs-access' -import { WslTranscriptFsError } from './wsl-transcript-fs-gate' -import { transcriptWatcherPathIsRunning } from './wsl-transcript-watcher-running-guard' - -export async function transcriptWatcherPathIsInstallable( - filePath: string, - signal?: AbortSignal -): Promise { - if (!(await transcriptWatcherPathIsRunning(filePath))) { - return false - } - try { - await transcriptFileStat(filePath, 'exact', signal) - return true - } catch (error) { - if (error instanceof WslTranscriptFsError) { - throw error - } - return false - } -} diff --git a/src/main/native-chat/transcript-file-version.test.ts b/src/main/native-chat/transcript-watching/transcript-file-version.test.ts similarity index 100% rename from src/main/native-chat/transcript-file-version.test.ts rename to src/main/native-chat/transcript-watching/transcript-file-version.test.ts diff --git a/src/main/native-chat/transcript-file-version.ts b/src/main/native-chat/transcript-watching/transcript-file-version.ts similarity index 95% rename from src/main/native-chat/transcript-file-version.ts rename to src/main/native-chat/transcript-watching/transcript-file-version.ts index 67ca14451ab..550a2e76129 100644 --- a/src/main/native-chat/transcript-file-version.ts +++ b/src/main/native-chat/transcript-watching/transcript-file-version.ts @@ -1,4 +1,7 @@ -import { readTranscriptSlice, transcriptFileStat } from './wsl-transcript-fs-access' +import { + readTranscriptSlice, + transcriptFileStat +} from '../transcript-filesystem/wsl-transcript-fs-access' const BOUNDARY_FINGERPRINT_BYTES = 64 diff --git a/src/main/native-chat/transcript-incremental-reader.ts b/src/main/native-chat/transcript-watching/transcript-incremental-reader.ts similarity index 91% rename from src/main/native-chat/transcript-incremental-reader.ts rename to src/main/native-chat/transcript-watching/transcript-incremental-reader.ts index 73946a27169..a294da0b79b 100644 --- a/src/main/native-chat/transcript-incremental-reader.ts +++ b/src/main/native-chat/transcript-watching/transcript-incremental-reader.ts @@ -1,15 +1,18 @@ import type { NativeChatMessage, NativeChatTurnLifecycle -} from '../../shared/native-chat/native-chat-types' -import { transcriptFallbackId } from './transcript-fallback-id' +} from '../../../shared/native-chat/native-chat-types' +import { transcriptFallbackId } from '../transcript-streaming/transcript-fallback-id' import { extendTranscriptBoundary } from './transcript-file-version' -import { inTranscriptFileOrder } from './transcript-file-order' +import { inTranscriptFileOrder } from '../transcript-streaming/transcript-file-order' import { MAX_NATIVE_CHAT_TRANSCRIPT_RECORD_BYTES, type NativeChatLineDecoder -} from './transcript-tail-reader' -import { openTranscriptReadStream, transcriptFileStat } from './wsl-transcript-fs-access' +} from '../transcript-tail-reader' +import { + openTranscriptReadStream, + transcriptFileStat +} from '../transcript-filesystem/wsl-transcript-fs-access' const APPEND_BATCH_MESSAGE_LIMIT = 40 diff --git a/src/main/native-chat/transcript-tail-boundary.ts b/src/main/native-chat/transcript-watching/transcript-tail-boundary.ts similarity index 89% rename from src/main/native-chat/transcript-tail-boundary.ts rename to src/main/native-chat/transcript-watching/transcript-tail-boundary.ts index a626f1ae5d8..4a538ddf6dc 100644 --- a/src/main/native-chat/transcript-tail-boundary.ts +++ b/src/main/native-chat/transcript-watching/transcript-tail-boundary.ts @@ -1,5 +1,5 @@ -import { readTranscriptFile } from './wsl-transcript-fs-access' -import type { TranscriptFileHandle } from './wsl-transcript-fs-access' +import { readTranscriptFile } from '../transcript-filesystem/wsl-transcript-fs-access' +import type { TranscriptFileHandle } from '../transcript-filesystem/wsl-transcript-fs-access' export const TAIL_CHUNK_BYTES = 64 * 1024 diff --git a/src/main/native-chat/transcript-unavailable-snapshot.ts b/src/main/native-chat/transcript-watching/transcript-unavailable-snapshot.ts similarity index 100% rename from src/main/native-chat/transcript-unavailable-snapshot.ts rename to src/main/native-chat/transcript-watching/transcript-unavailable-snapshot.ts diff --git a/src/main/native-chat/transcript-watch-contract.ts b/src/main/native-chat/transcript-watching/transcript-watch-contract.ts similarity index 83% rename from src/main/native-chat/transcript-watch-contract.ts rename to src/main/native-chat/transcript-watching/transcript-watch-contract.ts index 565bd631948..1da7c2f3983 100644 --- a/src/main/native-chat/transcript-watch-contract.ts +++ b/src/main/native-chat/transcript-watching/transcript-watch-contract.ts @@ -1,12 +1,12 @@ export const DESKTOP_READ_WINDOW = 300 export const UNFLUSHED_SETTLE_MS = 1_500 -import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' +import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' import type { NativeChatMessage, NativeChatTurnLifecycle -} from '../../shared/native-chat/native-chat-types' -import type { ResolveSessionFileOptions } from './session-file-resolver' +} from '../../../shared/native-chat/native-chat-types' +import type { ResolveSessionFileOptions } from '../session-file-resolver' export type SubscribeNativeChatTranscriptArgs = ResolveSessionFileOptions & { agent: AgentType diff --git a/src/main/native-chat/transcript-watch-engine.ts b/src/main/native-chat/transcript-watching/transcript-watch-engine.ts similarity index 94% rename from src/main/native-chat/transcript-watch-engine.ts rename to src/main/native-chat/transcript-watching/transcript-watch-engine.ts index 0ec7153a59e..4e534b1847c 100644 --- a/src/main/native-chat/transcript-watch-engine.ts +++ b/src/main/native-chat/transcript-watching/transcript-watch-engine.ts @@ -1,7 +1,7 @@ import type { NativeChatMessage, NativeChatTurnLifecycle -} from '../../shared/native-chat/native-chat-types' +} from '../../../shared/native-chat/native-chat-types' import { boundaryFingerprint, readTranscriptFileVersion, @@ -14,22 +14,22 @@ import { readIncrementalTranscriptMessages, resetIncrementalTranscriptState } from './transcript-incremental-reader' -import { readNativeChatTranscriptTailFile } from './transcript-tail-reader' +import { readNativeChatTranscriptTailFile } from '../transcript-tail-reader' import { emitTranscriptUnavailableSnapshot } from './transcript-unavailable-snapshot' import { transcriptWatcherPathIsInstallable } from './transcript-watcher-install-probe' -import { nativeChatTurnLifecycleDecoderForAgent } from './transcript-turn-lifecycle' +import { nativeChatTurnLifecycleDecoderForAgent } from '../transcript-decoding/transcript-turn-lifecycle' import type { NativeChatTranscriptSubscription, SubscribeNativeChatTranscriptArgs } from './transcript-watch-contract' import { createTranscriptWatchScheduler } from './transcript-watch-scheduler' -import { WslTranscriptFsError } from './wsl-transcript-fs-gate' +import { WslTranscriptFsError } from '../transcript-filesystem/wsl-transcript-fs-error' import { createRunningGuardedTranscriptNativeWatcher, isWslTranscriptWatcherPath, transcriptWatcherPathIsRunning -} from './wsl-transcript-watcher-running-guard' -import { observeWslTranscriptRunningState } from './wsl-transcript-running-observer' +} from '../transcript-filesystem/wsl-transcript-watcher-running-guard' +import { observeWslTranscriptRunningState } from '../transcript-filesystem/wsl-transcript-running-observer' import { trackActiveNativeChatWatcher } from './transcript-watcher-count' export async function installTranscriptWatcher( diff --git a/src/main/native-chat/transcript-watch-scheduler.ts b/src/main/native-chat/transcript-watching/transcript-watch-scheduler.ts similarity index 100% rename from src/main/native-chat/transcript-watch-scheduler.ts rename to src/main/native-chat/transcript-watching/transcript-watch-scheduler.ts diff --git a/src/main/native-chat/transcript-watcher-count.ts b/src/main/native-chat/transcript-watching/transcript-watcher-count.ts similarity index 100% rename from src/main/native-chat/transcript-watcher-count.ts rename to src/main/native-chat/transcript-watching/transcript-watcher-count.ts diff --git a/src/main/native-chat/transcript-watching/transcript-watcher-install-probe.ts b/src/main/native-chat/transcript-watching/transcript-watcher-install-probe.ts new file mode 100644 index 00000000000..1561bd30745 --- /dev/null +++ b/src/main/native-chat/transcript-watching/transcript-watcher-install-probe.ts @@ -0,0 +1,21 @@ +import { transcriptFileStat } from '../transcript-filesystem/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../transcript-filesystem/wsl-transcript-fs-error' +import { transcriptWatcherPathIsRunning } from '../transcript-filesystem/wsl-transcript-watcher-running-guard' + +export async function transcriptWatcherPathIsInstallable( + filePath: string, + signal?: AbortSignal +): Promise { + if (!(await transcriptWatcherPathIsRunning(filePath))) { + return false + } + try { + await transcriptFileStat(filePath, 'exact', signal) + return true + } catch (error) { + if (error instanceof WslTranscriptFsError) { + throw error + } + return false + } +} diff --git a/src/main/native-chat/transcript-window-tool-attribution.test.ts b/src/main/native-chat/transcript-window-tool-attribution.test.ts deleted file mode 100644 index bcef9e47702..00000000000 --- a/src/main/native-chat/transcript-window-tool-attribution.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { stripNoiseMessages } from '../../shared/native-chat/native-chat-noise' -import { mergeNativeChatMessages } from '../../shared/native-chat/native-chat-merge' -import { foldToolMessages } from '../../shared/native-chat/tools/native-chat-tool-fold' -import { pairToolBlocks } from '../../shared/native-chat/tools/native-chat-tool-pairs' -import { isToolCallBlock, isToolResultBlock } from '../../shared/native-chat/native-chat-types' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' -import { readNativeChatTranscriptTailFile } from './transcript-tail-reader' - -let tempRoots: string[] = [] - -afterEach(async () => { - await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) - tempRoots = [] -}) - -async function writeTranscript(records: unknown[]): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-attribution-')) - tempRoots.push(root) - const filePath = join(root, 'transcript.jsonl') - await writeFile(filePath, records.map((record) => JSON.stringify(record)).join('\n')) - return filePath -} - -function toolTurn(n: number): unknown[] { - return [ - { - type: 'assistant', - uuid: `call-${n}`, - timestamp: `2026-08-20T10:00:${String(n).padStart(2, '0')}.000Z`, - message: { - role: 'assistant', - content: [ - { type: 'tool_use', id: `toolu_${n}`, name: 'Bash', input: { command: `echo ${n}` } } - ] - } - }, - { - type: 'user', - uuid: `result-${n}`, - timestamp: `2026-08-20T10:00:${String(n).padStart(2, '0')}.500Z`, - message: { - role: 'user', - content: [{ type: 'tool_result', content: `output ${n}`, tool_use_id: `toolu_${n}` }] - } - } - ] -} - -function unattributedResults(messages: readonly NativeChatMessage[]): string[] { - const stray: string[] = [] - for (const message of messages) { - const tools = message.blocks.filter( - (block) => isToolCallBlock(block) || isToolResultBlock(block) - ) - if (tools.length === 0) { - continue - } - for (const pair of pairToolBlocks(tools)) { - if (pair.call === undefined && pair.result) { - stray.push(pair.result.output) - } - } - } - return stray -} - -async function renderedMessages(filePath: string, limit: number): Promise { - const page = await readNativeChatTranscriptTailFile( - filePath, - limit, - decodeClaudeTranscriptLine, - true - ) - return stripNoiseMessages(foldToolMessages(mergeNativeChatMessages([], page.messages))) -} - -describe('windowed transcript tool attribution', () => { - it('shows a tool result whose call falls outside the read window without guessing its owner', async () => { - const filePath = await writeTranscript([...toolTurn(1), ...toolTurn(2), ...toolTurn(3)]) - - const windowed = await renderedMessages(filePath, 3) - - expect(unattributedResults(windowed)).toEqual(['output 2']) - expect(windowed[0]).toMatchObject({ id: 'result-2', role: 'tool' }) - expect( - windowed.flatMap((message) => - message.blocks.filter(isToolResultBlock).map((block) => block.output) - ) - ).toEqual(['output 2', 'output 3']) - }) - - it('drops the answered result records Claude re-emits at a /compact boundary', async () => { - const [, answeredResult] = toolTurn(1) - const filePath = await writeTranscript([ - ...toolTurn(1), - { - type: 'user', - uuid: 'compact-prompt', - timestamp: '2026-08-20T10:05:00.000Z', - message: { role: 'user', content: '/compact' } - }, - answeredResult - ]) - - const whole = await renderedMessages(filePath, 100) - - expect(unattributedResults(whole)).toEqual([]) - expect( - whole.flatMap((message) => - message.blocks.filter(isToolResultBlock).map((block) => block.output) - ) - ).toEqual(['output 1']) - }) - - it('keeps a hidden interruption from authorizing a later result', async () => { - const [abandonedCall] = toolTurn(1) - const [, laterResult] = toolTurn(2) - const filePath = await writeTranscript([ - abandonedCall, - { - type: 'user', - uuid: 'interrupt', - timestamp: '2026-08-20T10:01:00.000Z', - message: { role: 'user', content: '[Request interrupted by user]' } - }, - laterResult - ]) - - const messages = await renderedMessages(filePath, 100) - - expect(unattributedResults(messages)).toEqual(['output 2']) - expect(messages.map((message) => message.id)).toEqual(['call-1', 'result-2']) - expect(pairToolBlocks(messages[0]!.blocks)[0]?.result).toBeUndefined() - expect(messages[1]?.role).toBe('tool') - }) - - it('uses provider paging cursors unchanged while an older page restores the exact call', async () => { - const filePath = await writeTranscript([...toolTurn(1), ...toolTurn(2), ...toolTurn(3)]) - const page = await readNativeChatTranscriptTailFile( - filePath, - 3, - decodeClaudeTranscriptLine, - true - ) - const cursor = page.beforeOffset - const consumed = page.consumedTo - const windowed = foldToolMessages(page.messages) - const older = await readNativeChatTranscriptTailFile( - filePath, - 100, - decodeClaudeTranscriptLine, - true, - cursor - ) - expect(page.beforeOffset).toBe(cursor) - expect(page.consumedTo).toBe(consumed) - expect(page.hasMore).toBe(true) - expect(windowed[0]).toMatchObject({ id: 'result-2', role: 'tool' }) - expect(older.messages.at(-1)?.id).toBe('call-2') - expect(older.consumedTo).toBe(cursor) - const whole = foldToolMessages(mergeNativeChatMessages(older.messages, page.messages)) - expect(unattributedResults(whole)).toEqual([]) - expect( - whole - .flatMap((message) => pairToolBlocks(message.blocks)) - .map((pair) => [pair.call?.callId, pair.result?.output]) - ).toEqual([ - ['toolu_1', 'output 1'], - ['toolu_2', 'output 2'], - ['toolu_3', 'output 3'] - ]) - }) -}) diff --git a/src/main/native-chat/wsl-transcript-running-observer.test.ts b/src/main/native-chat/wsl-transcript-running-observer.test.ts deleted file mode 100644 index a635a2d0e4f..00000000000 --- a/src/main/native-chat/wsl-transcript-running-observer.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ listRunning: vi.fn() })) - -vi.mock('../wsl/discovery/distro-catalog', () => ({ - listRunningWslDistrosAsync: mocks.listRunning -})) - -import { - observeWslTranscriptRunningState, - resetWslTranscriptRunningObserverForTests, - WSL_TRANSCRIPT_FIRST_OBSERVATION_MS as FIRST, - WSL_TRANSCRIPT_RUNNING_OBSERVATION_MS as INTERVAL -} from './wsl-transcript-running-observer' - -describe('WSL transcript running observer', () => { - beforeEach(() => { - vi.useFakeTimers() - mocks.listRunning.mockReset().mockResolvedValue(['Ubuntu']) - }) - - afterEach(() => { - resetWslTranscriptRunningObserverForTests() - vi.useRealTimers() - }) - - it('shares one running-distro probe across staggered watchers', async () => { - const ubuntu = vi.fn() - const debian = vi.fn() - const stopUbuntu = observeWslTranscriptRunningState( - '\\\\wsl.localhost\\Ubuntu\\home\\ada\\a.jsonl', - () => ubuntu(true), - () => ubuntu(false) - ) - await vi.advanceTimersByTimeAsync(FIRST / 2) - const stopDebian = observeWslTranscriptRunningState( - '\\\\wsl.localhost\\Debian\\home\\ada\\b.jsonl', - () => debian(true), - () => debian(false) - ) - await vi.advanceTimersByTimeAsync(FIRST / 2) - - expect(mocks.listRunning).toHaveBeenCalledTimes(1) - expect(ubuntu).toHaveBeenCalledWith(true) - expect(debian).toHaveBeenCalledWith(false) - - // After the first look, one shared read per cadence. - await vi.advanceTimersByTimeAsync(INTERVAL - 1) - expect(mocks.listRunning).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(mocks.listRunning).toHaveBeenCalledTimes(2) - stopUbuntu() - stopDebian() - }) - - it('coalesces slow subscription callbacks and retains the latest observation', async () => { - let finishFirst: (() => void) | undefined - const callback = vi - .fn() - .mockImplementationOnce( - () => - new Promise((resolve) => { - finishFirst = resolve - }) - ) - .mockResolvedValue(undefined) - const stop = observeWslTranscriptRunningState( - '\\\\wsl.localhost\\Ubuntu\\home\\ada\\a.jsonl', - callback, - callback - ) - - await vi.advanceTimersByTimeAsync(FIRST) - expect(callback).toHaveBeenCalledTimes(1) - - mocks.listRunning.mockResolvedValue([]) - await vi.advanceTimersByTimeAsync(INTERVAL * 3) - expect(mocks.listRunning).toHaveBeenCalledTimes(4) - expect(callback).toHaveBeenCalledTimes(1) - - finishFirst?.() - await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(2)) - stop() - }) -}) diff --git a/src/main/network/macos-python-proxy-environment.ts b/src/main/network/macos-python-proxy-environment.ts new file mode 100644 index 00000000000..f87212a31c8 --- /dev/null +++ b/src/main/network/macos-python-proxy-environment.ts @@ -0,0 +1,166 @@ +import { isIP } from 'node:net' +import { runProcess } from '@orca/process-host' + +type PythonSystemProxy = { + proxies: Readonly> + bypass: readonly string[] +} + +let pending: Promise | null = null + +/** Read on the execution host, never through the desktop's Chromium proxy session. */ +export function readMacosPythonProxyEnvironment(): Promise { + if (process.platform !== 'darwin') { + return Promise.resolve(null) + } + // Share launch bursts, but reread after settlement so changed system settings take effect. + return (pending ??= readSystemProxy().finally(() => { + pending = null + })) +} + +async function readSystemProxy(): Promise { + try { + const result = await runProcess({ + program: '/usr/sbin/scutil', + args: ['--proxy'], + timeoutMs: 3000, + maxOutputBytes: 64 * 1024 + }) + if (result.code !== 0 || result.signal || result.timedOut || result.outputTruncated) { + return null + } + return parseSystemProxy(result.stdout) + } catch { + return null + } +} + +function parseSystemProxy(output: string): PythonSystemProxy | null { + const fields = new Map() + const exceptions: string[] = [] + let depth = 0 + let inExceptions = false + let opened = false + for (const line of output.split(/\r?\n/)) { + const trimmed = line.trim() + if (!trimmed) { + continue + } + if (!opened) { + if (trimmed !== ' {') { + return null + } + opened = true + depth = 1 + continue + } + if (trimmed === '}') { + if (--depth < 0) { + return null + } + if (depth === 1) { + inExceptions = false + } + continue + } + if (depth === 0) { + return null + } + const entry = /^\s+([^ ]+) : (.*)$/.exec(line) + if (!entry) { + return null + } + const [, key, value] = entry + if (depth === 1) { + fields.set(key, value) + inExceptions = key === 'ExceptionsList' && value === ' {' + } else if (depth === 2 && inExceptions) { + exceptions.push(value) + } + if (value === ' {' || value === ' {') { + depth++ + } + } + if (!opened || depth !== 0) { + return null + } + // Python ignores PAC; an environment mapping cannot preserve arbitrary PAC policies. + if ( + Number(fields.get('ProxyAutoConfigEnable') ?? 0) !== 0 || + Number(fields.get('ProxyAutoDiscoveryEnable') ?? 0) !== 0 + ) { + return null + } + if (fields.has('ExceptionsList') && fields.get('ExceptionsList') !== ' {') { + return null + } + const bypass: string[] = [] + for (const entry of exceptions) { + if (['localhost', '127.0.0.1', '::1', '[::1]'].includes(entry.toLowerCase())) { + continue + } + if (isIP(entry)) { + bypass.push(entry) + } else if (entry === '*.local') { + bypass.push('.local') + } else if (!isPrivateIpv4Prefix(entry)) { + // NO_PROXY widens domain wildcards to their apex and exact hostnames to suffixes. + return null + } + } + const proxies: Record = {} + for (const [scheme, key] of [ + ['http', 'HTTP'], + ['https', 'HTTPS'], + ['ftp', 'FTP'], + ['gopher', 'Gopher'], + ['socks', 'SOCKS'] + ]) { + const enabled = Number(fields.get(`${key}Enable`) ?? 0) + if (!Number.isFinite(enabled)) { + return null + } + if (!enabled) { + continue + } + const host = fields.get(`${key}Proxy`) + const port = fields.get(`${key}Port`) + if (!host || (port !== undefined && !/^\d+$/.test(port))) { + return null + } + // CPython's _scproxy uses http:// even for the SOCKS dictionary entry. + proxies[scheme] = `http://${host}${port === undefined ? '' : `:${port}`}` + } + // Private/link-local ranges and exclude-simple are omitted; no exact NO_PROXY equivalent exists. + return Object.keys(proxies).length ? { proxies, bypass } : null +} + +function isPrivateIpv4Prefix(value: string): boolean { + const match = /^(\d+(?:\.\d+){0,3})(?:\/(\d+))?$/.exec(value) + if (!match) { + return false + } + const parts = match[1].split('.').map(Number) + if (parts.some((part) => part > 255)) { + return false + } + const prefix = match[2] === undefined ? parts.length * 8 : Number(match[2]) + if (prefix > 32) { + return false + } + while (parts.length < 4) { + parts.push(0) + } + const address = parts.reduce((total, part) => total * 256 + part, 0) + const size = 2 ** (32 - prefix) + const start = Math.floor(address / size) * size + const end = start + size - 1 + return [ + [0x0a000000, 0x0affffff], + [0x7f000000, 0x7fffffff], + [0xa9fe0000, 0xa9feffff], + [0xac100000, 0xac1fffff], + [0xc0a80000, 0xc0a8ffff] + ].some(([first, last]) => start >= first && end <= last) +} diff --git a/src/main/notifications/desktop-presence-reporter.ts b/src/main/notifications/desktop-presence-reporter.ts index a3be7b210e7..9591197c5a8 100644 --- a/src/main/notifications/desktop-presence-reporter.ts +++ b/src/main/notifications/desktop-presence-reporter.ts @@ -2,11 +2,11 @@ import { DESKTOP_PRESENCE_REPORT_INTERVAL_MS, NOTIFICATIONS_DESKTOP_PRESENCE_RUNTIME_CAPABILITY } from '../../shared/desktop-client-presence' -import { getRuntimeEnvironmentStatusSnapshots } from '../ipc/runtime-environments/runtime-environment-request-connections' +import { getRuntimeEnvironmentStatusSnapshots } from '../ipc/runtime-environments/connections/runtime-environment-request-connections' import { listReadySharedControlSockets, type ReadySharedControlSocket -} from '../ipc/runtime-environments/runtime-environment-shared-control-answers' +} from '../ipc/runtime-environments/connections/runtime-environment-shared-control-answers' const SAMPLE_INTERVAL_MS = 5_000 const REPORT_TIMEOUT_MS = 10_000 diff --git a/src/main/observability/git-execution-spans.ts b/src/main/observability/git-execution-spans.ts new file mode 100644 index 00000000000..08d17ca266b --- /dev/null +++ b/src/main/observability/git-execution-spans.ts @@ -0,0 +1,237 @@ +import { hasActiveTraceSink, startSpan, withSpan, type ActiveSpan } from './tracer' +import { getGitOperationCause } from './git-operation-cause' + +const GIT_FAST_SUCCESS_THRESHOLD_MS = 250 +const GIT_FAST_SUCCESS_WINDOW_MS = 60_000 +const GIT_FAST_SUCCESS_BUDGET_PER_WINDOW = 60 +const GIT_SAMPLING_MAX_BUCKETS = 512 + +const GIT_GLOBAL_OPTIONS_WITH_OPERAND = new Set([ + '-c', + '-C', + '--git-dir', + '--work-tree', + '--config-env', + '--namespace', + '--exec-path', + '--super-prefix', + '--pathspec-from-file' +]) +const GIT_GLOBAL_FLAGS = new Set([ + '--bare', + '--no-pager', + '--paginate', + '--literal-pathspecs', + '--glob-pathspecs', + '--noglob-pathspecs', + '--icase-pathspecs', + '--no-optional-locks', + '--pathspec-file-nul' +]) + +type GitSamplingBucket = { + windowStartMs: number + emitted: number +} + +const gitSamplingBuckets = new Map() + +function gitSubcommandIndex(args: readonly string[]): number { + for (let index = 0; index < args.length; index++) { + const arg = args[index] + if (!arg) { + continue + } + if (arg === '--') { + return -1 + } + if (GIT_GLOBAL_OPTIONS_WITH_OPERAND.has(arg)) { + index += 1 + continue + } + if ( + arg.startsWith('--git-dir=') || + arg.startsWith('--work-tree=') || + arg.startsWith('--config-env=') || + arg.startsWith('--namespace=') || + arg.startsWith('--exec-path=') || + arg.startsWith('--super-prefix=') || + arg.startsWith('--pathspec-from-file=') || + (arg.startsWith('-c') && arg.length > 2) || + (arg.startsWith('-C') && arg.length > 2) + ) { + continue + } + if (GIT_GLOBAL_FLAGS.has(arg)) { + continue + } + if (arg.startsWith('-')) { + continue + } + return index + } + return -1 +} + +function gitSubcommandFromArgs(args: readonly string[]): string { + return args[gitSubcommandIndex(args)] ?? '' +} + +function gitCommandVariant(args: readonly string[]): string { + const index = gitSubcommandIndex(args) + switch (args[index]) { + case 'worktree': { + const operation = args[index + 1] + if (operation === 'list') { + return args.includes('-z') ? 'worktree-list-z' : 'worktree-list-legacy' + } + return operation === 'add' || operation === 'remove' || operation === 'move' + ? `worktree-${operation}` + : 'worktree-other' + } + case 'for-each-ref': + return args.includes('--sort=-committerdate') ? 'refs-date-sort' : 'refs-other' + case 'fetch': + return args.some((arg) => arg.startsWith('+refs/heads/') && arg.includes(':refs/')) + ? 'fetch-exact-base' + : 'fetch-other' + case 'rev-parse': + return args.includes('--git-path') ? 'git-path' : 'rev-parse-other' + default: + return 'other' + } +} + +function safeGitSpan(span: ActiveSpan): ActiveSpan { + return { + ...span, + fail(cause) { + const name = cause instanceof Error ? cause.name : undefined + span.fail( + name === 'AbortError' + ? 'Git command cancelled' + : name === 'GitCommandTimeoutError' + ? 'Git command timed out' + : 'Git command failed' + ) + }, + interrupt() { + span.interrupt('Git command cancelled') + } + } +} + +function pruneGitSamplingBuckets(nowMs: number): void { + for (const [key, bucket] of gitSamplingBuckets) { + if (nowMs - bucket.windowStartMs >= GIT_FAST_SUCCESS_WINDOW_MS) { + gitSamplingBuckets.delete(key) + } + } + while (gitSamplingBuckets.size > GIT_SAMPLING_MAX_BUCKETS) { + let oldestKey: string | undefined + let oldestWindowStartMs = Number.POSITIVE_INFINITY + for (const [key, bucket] of gitSamplingBuckets) { + if (bucket.windowStartMs < oldestWindowStartMs) { + oldestKey = key + oldestWindowStartMs = bucket.windowStartMs + } + } + if (oldestKey === undefined) { + return + } + gitSamplingBuckets.delete(oldestKey) + } +} + +function gitSamplingKey(meta: GitSpanArgs): string { + return `${gitSubcommandFromArgs(meta.args)}\u0000${meta.cwd ?? ''}` +} + +function shouldRecordGitSpan( + meta: GitSpanArgs, + record: { durationMs: number; startTimeUnixNano: string; exit: { _tag: string } } +): boolean { + if (record.exit._tag !== 'Success' || record.durationMs >= GIT_FAST_SUCCESS_THRESHOLD_MS) { + return true + } + + const nowMs = Number(BigInt(record.startTimeUnixNano) / 1_000_000n) + pruneGitSamplingBuckets(nowMs) + const key = gitSamplingKey(meta) + const bucket = gitSamplingBuckets.get(key) + if (!bucket) { + gitSamplingBuckets.set(key, { windowStartMs: nowMs, emitted: 1 }) + pruneGitSamplingBuckets(nowMs) + return true + } + if (bucket.emitted < GIT_FAST_SUCCESS_BUDGET_PER_WINDOW) { + bucket.emitted += 1 + return true + } + return false +} + +function addGitAttributes(span: ActiveSpan, meta: GitSpanArgs): void { + span.setAttribute('git.subcommand', gitSubcommandFromArgs(meta.args)) + // Git arguments may contain user content; record counts instead. + span.setAttribute('git.arg_count', meta.args.length) + span.setAttribute('git.variant', gitCommandVariant(meta.args)) + const cause = getGitOperationCause() + if (cause) { + span.setAttribute('git.operation', cause.family) + span.setAttribute('git.reason', cause.reason) + span.setAttribute('git.cache', cause.cache) + span.setAttribute('git.common_dir_hash', cause.commonDirHash ?? 'unknown') + } + if (meta.cwd) { + span.setAttribute('cwd', meta.cwd) + } +} + +export function _resetGitSpanSamplingForTests(): void { + gitSamplingBuckets.clear() +} + +export function _gitSpanSamplingBucketCountForTests(): number { + return gitSamplingBuckets.size +} + +export type GitSpanArgs = { + readonly args: readonly string[] + readonly cwd?: string +} + +export async function withGitSpan( + meta: GitSpanArgs, + fn: (span: ActiveSpan) => Promise +): Promise { + if (!hasActiveTraceSink()) { + return fn(startSpan('git.exec')) + } + return withSpan( + 'git.exec', + async (span) => { + addGitAttributes(span, meta) + const safeSpan = safeGitSpan(span) + try { + return await fn(safeSpan) + } catch (error) { + safeSpan.fail(error instanceof Error ? error : 'Git command failed') + throw error + } + }, + { attributes: { kind: 'git' }, shouldRecord: (record) => shouldRecordGitSpan(meta, record) } + ) +} + +export function startGitSpan(meta: GitSpanArgs): ActiveSpan { + if (!hasActiveTraceSink()) { + return startSpan('git.exec') + } + const span = startSpan('git.exec', { + attributes: { kind: 'git' }, + shouldRecord: (record) => shouldRecordGitSpan(meta, record) + }) + addGitAttributes(span, meta) + return safeGitSpan(span) +} diff --git a/src/main/observability/git-operation-cause.ts b/src/main/observability/git-operation-cause.ts new file mode 100644 index 00000000000..5d1ea7198e0 --- /dev/null +++ b/src/main/observability/git-operation-cause.ts @@ -0,0 +1,61 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { createHash } from 'node:crypto' +import { hasActiveTraceSink } from './tracer' + +export type GitOperationCause = { + family: 'catalog' | 'refs' | 'status' | 'fetch' | 'setup' + reason: + | 'desktop-catalog' + | 'runtime-catalog' + | 'worktree-scan' + | 'creation-base-refresh' + | 'branch-search' + | 'status-read' + | 'remote-fetch' + | 'base-refresh' + | 'conflict-preview' + | 'setup-runner' + cache: 'miss' | 'expired' | 'refresh' | 'bypass-signal' | 'uncached' +} + +type CauseScope = GitOperationCause & { commonDirHash?: string; active: boolean } +const causes = new AsyncLocalStorage() + +export function runWithGitCause( + cause: GitOperationCause, + identity: { namespace: string; commonDir: string } | undefined, + run: () => Promise +): Promise { + if (!hasActiveTraceSink()) { + return run() + } + const parent = causes.getStore() + const scope: CauseScope = { + ...cause, + reason: parent?.active ? parent.reason : cause.reason, + ...(identity + ? { + commonDirHash: createHash('sha256') + .update(identity.namespace) + .update('\0') + .update(identity.commonDir) + .digest('hex') + .slice(0, 16) + } + : {}), + active: true + } + return causes.run(scope, async () => { + try { + return await run() + } finally { + // Detached work must not inherit a completed action's cause. + scope.active = false + } + }) +} + +export function getGitOperationCause(): Readonly | undefined { + const scope = causes.getStore() + return scope?.active ? scope : undefined +} diff --git a/src/main/observability/instrumentation.ts b/src/main/observability/instrumentation.ts index c850df164f1..c0895e208c3 100644 --- a/src/main/observability/instrumentation.ts +++ b/src/main/observability/instrumentation.ts @@ -1,172 +1,13 @@ import type { PreparedCheckoutOutcome } from '../../shared/worktree/create-types' -import { startSpan, withSpan, type ActiveSpan } from './tracer' +import { withSpan, type ActiveSpan } from './tracer' -const GIT_FAST_SUCCESS_THRESHOLD_MS = 250 -const GIT_FAST_SUCCESS_WINDOW_MS = 60_000 -const GIT_FAST_SUCCESS_BUDGET_PER_WINDOW = 60 -const GIT_SAMPLING_MAX_BUCKETS = 512 - -const GIT_GLOBAL_OPTIONS_WITH_OPERAND = new Set([ - '-c', - '-C', - '--git-dir', - '--work-tree', - '--config-env', - '--namespace', - '--exec-path', - '--super-prefix', - '--pathspec-from-file' -]) -const GIT_GLOBAL_FLAGS = new Set([ - '--bare', - '--no-pager', - '--paginate', - '--literal-pathspecs', - '--glob-pathspecs', - '--noglob-pathspecs', - '--icase-pathspecs', - '--no-optional-locks', - '--pathspec-file-nul' -]) - -type GitSamplingBucket = { - windowStartMs: number - emitted: number -} - -const gitSamplingBuckets = new Map() - -function gitSubcommandFromArgs(args: readonly string[]): string { - for (let index = 0; index < args.length; index++) { - const arg = args[index] - if (!arg) { - continue - } - if (arg === '--') { - return '' - } - if (GIT_GLOBAL_OPTIONS_WITH_OPERAND.has(arg)) { - index += 1 - continue - } - if ( - arg.startsWith('--git-dir=') || - arg.startsWith('--work-tree=') || - arg.startsWith('--config-env=') || - arg.startsWith('--namespace=') || - arg.startsWith('--exec-path=') || - arg.startsWith('--super-prefix=') || - arg.startsWith('--pathspec-from-file=') || - (arg.startsWith('-c') && arg.length > 2) || - (arg.startsWith('-C') && arg.length > 2) - ) { - continue - } - if (GIT_GLOBAL_FLAGS.has(arg)) { - continue - } - if (arg.startsWith('-')) { - continue - } - return arg - } - return '' -} - -function pruneGitSamplingBuckets(nowMs: number): void { - for (const [key, bucket] of gitSamplingBuckets) { - if (nowMs - bucket.windowStartMs >= GIT_FAST_SUCCESS_WINDOW_MS) { - gitSamplingBuckets.delete(key) - } - } - while (gitSamplingBuckets.size > GIT_SAMPLING_MAX_BUCKETS) { - let oldestKey: string | undefined - let oldestWindowStartMs = Number.POSITIVE_INFINITY - for (const [key, bucket] of gitSamplingBuckets) { - if (bucket.windowStartMs < oldestWindowStartMs) { - oldestKey = key - oldestWindowStartMs = bucket.windowStartMs - } - } - if (oldestKey === undefined) { - return - } - gitSamplingBuckets.delete(oldestKey) - } -} - -function gitSamplingKey(meta: GitSpanArgs): string { - return `${gitSubcommandFromArgs(meta.args)}\u0000${meta.cwd ?? ''}` -} - -function shouldRecordGitSpan( - meta: GitSpanArgs, - record: { durationMs: number; startTimeUnixNano: string; exit: { _tag: string } } -): boolean { - if (record.exit._tag !== 'Success' || record.durationMs >= GIT_FAST_SUCCESS_THRESHOLD_MS) { - return true - } - - const nowMs = Number(BigInt(record.startTimeUnixNano) / 1_000_000n) - pruneGitSamplingBuckets(nowMs) - const key = gitSamplingKey(meta) - const bucket = gitSamplingBuckets.get(key) - if (!bucket) { - gitSamplingBuckets.set(key, { windowStartMs: nowMs, emitted: 1 }) - pruneGitSamplingBuckets(nowMs) - return true - } - if (bucket.emitted < GIT_FAST_SUCCESS_BUDGET_PER_WINDOW) { - bucket.emitted += 1 - return true - } - return false -} - -function addGitAttributes(span: ActiveSpan, meta: GitSpanArgs): void { - span.setAttribute('git.subcommand', gitSubcommandFromArgs(meta.args)) - // Git arguments may contain user content; record counts instead. - span.setAttribute('git.arg_count', meta.args.length) - if (meta.cwd) { - span.setAttribute('cwd', meta.cwd) - } -} - -export function _resetGitSpanSamplingForTests(): void { - gitSamplingBuckets.clear() -} - -export function _gitSpanSamplingBucketCountForTests(): number { - return gitSamplingBuckets.size -} - -export type GitSpanArgs = { - readonly args: readonly string[] - readonly cwd?: string -} - -export async function withGitSpan( - meta: GitSpanArgs, - fn: (span: ActiveSpan) => Promise -): Promise { - return withSpan( - 'git.exec', - async (span) => { - addGitAttributes(span, meta) - return await fn(span) - }, - { attributes: { kind: 'git' }, shouldRecord: (record) => shouldRecordGitSpan(meta, record) } - ) -} - -export function startGitSpan(meta: GitSpanArgs): ActiveSpan { - const span = startSpan('git.exec', { - attributes: { kind: 'git' }, - shouldRecord: (record) => shouldRecordGitSpan(meta, record) - }) - addGitAttributes(span, meta) - return span -} +export { + withGitSpan, + startGitSpan, + _resetGitSpanSamplingForTests, + _gitSpanSamplingBucketCountForTests, + type GitSpanArgs +} from './git-execution-spans' export type WorktreeSpanArgs = { readonly stage: 'clone' | 'checkout' | 'install' | 'create' | 'remove' diff --git a/src/main/omp/omp-session-cwd-lookup.ts b/src/main/omp/omp-session-cwd-lookup.ts index 262a46d2f8e..4cc68fe73ad 100644 --- a/src/main/omp/omp-session-cwd-lookup.ts +++ b/src/main/omp/omp-session-cwd-lookup.ts @@ -1,8 +1,8 @@ import { createHash } from 'node:crypto' import { lstat, opendir, realpath } from 'node:fs/promises' import { basename, extname, isAbsolute, join, relative, resolve } from 'node:path' -import { PI_CWD_BUCKET_LAYOUT } from '../ai-vault/session-cwd-bucket-layouts' -import { SESSION_FILE_ID_LAYOUTS } from '../native-chat/session-file-id-layouts' +import { PI_CWD_BUCKET_LAYOUT } from '../ai-vault/scope/session-cwd-bucket-layouts' +import { SESSION_FILE_ID_LAYOUTS } from '../native-chat/transcript-discovery/session-file-id-layouts' async function canonicalPath(path: string): Promise { return realpath(path).catch(() => resolve(path)) diff --git a/src/main/omp/omp-session-history.ts b/src/main/omp/omp-session-history.ts index d4dbeb251e7..9d02397a731 100644 --- a/src/main/omp/omp-session-history.ts +++ b/src/main/omp/omp-session-history.ts @@ -2,7 +2,7 @@ import { resumeInvocationFromOptions, sessionFileResumeTargetMatches, type StructuredAgentSessionHistory -} from '../native-chat/structured-agent-cli-conversations' +} from '../native-chat/conversation-adoption/structured-agent-cli-conversations' export const OMP_SESSION_HISTORY: StructuredAgentSessionHistory = { rowAgents: ['omp'], diff --git a/src/main/omp/omp-transcript-import.ts b/src/main/omp/omp-transcript-import.ts index e462093ca76..8611a9a34ac 100644 --- a/src/main/omp/omp-transcript-import.ts +++ b/src/main/omp/omp-transcript-import.ts @@ -1,6 +1,6 @@ import { homedir } from 'node:os' import { resolveOmpSessionsDir } from '../ai-vault/scanners/omp/omp-session-root' -import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-conversations' +import { directoryTranscriptImport } from '../native-chat/conversation-adoption/structured-agent-cli-conversations' import { findOmpSessionByCwd } from './omp-session-cwd-lookup' function sessionsRoot(accountHomePath: string, launchEnv: NodeJS.ProcessEnv) { diff --git a/src/main/openclaude/hook-service.ts b/src/main/openclaude/hook-service.ts index 5f93d47d813..ccac406a70e 100644 --- a/src/main/openclaude/hook-service.ts +++ b/src/main/openclaude/hook-service.ts @@ -1,5 +1,5 @@ import { ClaudeHookService } from '../claude/hook-service' -import { OPENCLAUDE_HOOK_SETTINGS } from '../claude/hook-settings' +import { OPENCLAUDE_HOOK_SETTINGS } from '../claude/hooks/hook-settings' export const openClaudeHookService = new ClaudeHookService({ agent: 'openclaude', diff --git a/src/main/opencode-usage/opencode-database-discovery.ts b/src/main/opencode-usage/opencode-database-discovery.ts index 7c46cf0bc49..4c6c714453f 100644 --- a/src/main/opencode-usage/opencode-database-discovery.ts +++ b/src/main/opencode-usage/opencode-database-discovery.ts @@ -1,7 +1,10 @@ import { stat } from 'node:fs/promises' import { basename, join } from 'node:path' -import { wslGatedReaddir, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' -import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' +import { + wslGatedReaddir, + wslGatedStat +} from '../native-chat/transcript-filesystem/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/transcript-filesystem/wsl-transcript-fs-error' import { resolveOpenCodeDataDirectory, resolveOpenCodeDatabasePath diff --git a/src/main/opencode-usage/opencode-usage-row-parsing.ts b/src/main/opencode-usage/opencode-usage-row-parsing.ts index b254787f582..18414a701c2 100644 --- a/src/main/opencode-usage/opencode-usage-row-parsing.ts +++ b/src/main/opencode-usage/opencode-usage-row-parsing.ts @@ -1,4 +1,5 @@ -import { ensureNumber, extractString } from '../usage/source-input/usage-record-coercion' +import { ensureNumber } from '../usage/source-input/usage-record-coercion' +import { extractString } from '../../shared/trimmed-string' import type { OpenCodeUsageRow } from './opencode-usage-row-queries' import type { OpenCodeUsageParsedEvent } from './types' diff --git a/src/main/opencode/model-launch/opencode-root-model-overlay.test.ts b/src/main/opencode/model-launch/opencode-root-model-overlay.test.ts index abe8099fd87..c010d63ab9c 100644 --- a/src/main/opencode/model-launch/opencode-root-model-overlay.test.ts +++ b/src/main/opencode/model-launch/opencode-root-model-overlay.test.ts @@ -21,15 +21,6 @@ describe('planOpenCodeRootModelRewrite', () => { ).toBe(`& opencode --standalone${tail}`) }) - it('uses the last of repeated models and an existing --standalone', () => { - expect( - planOpenCodeRootModelRewrite( - `opencode2 --standalone ${q(['--model', 'a/b', '--model=c/d'], 'posix')}`, - 'posix' - ) - ).toMatchObject({ command: 'opencode2 --standalone', model: 'c/d' }) - }) - it.each([ ['posix', `opencode ${q(['run', '--model', 'a/b'], 'posix')}`], ['posix', `opencode ${q(['./pkg', '--model', 'a/b'], 'posix')}`], @@ -51,13 +42,4 @@ describe('planOpenCodeRootModelRewrite', () => { ] as const)('leaves %s `%s` as typed', (shell, command) => { expect(planOpenCodeRootModelRewrite(command, shell, 'C:\\')).toBeNull() }) - - it('probes the primary agent only for a new session on it', () => { - expect( - planOpenCodeRootModelRewrite( - `opencode ${q(['-s', 'ses_1', '--model', 'a/b'], 'posix')}`, - 'posix' - )?.probeExecutable - ).toBeUndefined() - }) }) diff --git a/src/main/opencode/startup-prompts/opencode-startup-prompt-owner.ts b/src/main/opencode/startup-prompts/opencode-startup-prompt-owner.ts index ea1a4a955bb..d6ac492b713 100644 --- a/src/main/opencode/startup-prompts/opencode-startup-prompt-owner.ts +++ b/src/main/opencode/startup-prompts/opencode-startup-prompt-owner.ts @@ -1,8 +1,8 @@ import type { PtySpawnOutcome } from '../../ipc/pty/spawn-outcome' import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import type { IPtyProvider } from '../../providers/pty-provider-contract' -import type { PtySpawnResult } from '../../providers/pty-spawn-result' +import type { IPtyProvider } from '../../providers/pty/provider-contract' +import type { PtySpawnResult } from '../../providers/pty/spawn-result' import { ptyIncarnationById, ptyOwnership } from '../../ipc/pty/provider/ownership-state' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { isPtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation' diff --git a/src/main/opencode/text-tasks/opencode-text-task-events.ts b/src/main/opencode/text-tasks/opencode-text-task-events.ts index b0db40e4d25..79550f67e4a 100644 --- a/src/main/opencode/text-tasks/opencode-text-task-events.ts +++ b/src/main/opencode/text-tasks/opencode-text-task-events.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import { SearchSubprocessLineAccumulator } from '../../../shared/search-subprocess-lines' -import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../text-generation/source-control-generation-limits' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../text-generation/execution/source-control-generation-limits' import type { createOpenCodeTextTaskHttp } from './opencode-text-task-http' import { openCodeTextTaskUrl } from './opencode-text-task-http' diff --git a/src/main/opencode/text-tasks/opencode-text-task-http.ts b/src/main/opencode/text-tasks/opencode-text-task-http.ts index 8ec5fd55fb6..38436bf0964 100644 --- a/src/main/opencode/text-tasks/opencode-text-task-http.ts +++ b/src/main/opencode/text-tasks/opencode-text-task-http.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../text-generation/source-control-generation-limits' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../text-generation/execution/source-control-generation-limits' const envelope = z.looseObject({ data: z.unknown().optional() }) diff --git a/src/main/opencode/text-tasks/opencode-text-task-server-ready.ts b/src/main/opencode/text-tasks/opencode-text-task-server-ready.ts index 3814a4a9d32..2a07ca2b6d2 100644 --- a/src/main/opencode/text-tasks/opencode-text-task-server-ready.ts +++ b/src/main/opencode/text-tasks/opencode-text-task-server-ready.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { SearchSubprocessLineAccumulator } from '../../../shared/search-subprocess-lines' import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' -import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../text-generation/source-control-generation-limits' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../text-generation/execution/source-control-generation-limits' import type { SpawnedSourceControlAgentProcess } from '../../text-generation/source-control-text-generation-types' const lease = z.object({ url: z.url() }) diff --git a/src/main/opencode/text-tasks/opencode-text-task.ts b/src/main/opencode/text-tasks/opencode-text-task.ts index e56f2c6ae78..2deb65e70be 100644 --- a/src/main/opencode/text-tasks/opencode-text-task.ts +++ b/src/main/opencode/text-tasks/opencode-text-task.ts @@ -1,18 +1,18 @@ import { mergeCommandEnvironment } from '../../../shared/command-environment' import { textGenerationFailure } from '../../../shared/text-generation-failure-copy' -import { cleanGeneratedCommitMessage } from '../../../shared/source-control/ai/generation/commit-message-agent-output' +import { cleanAgentAnswer } from '../../text-generation/failures/source-control-agent-failure' import { wslDistroForCommand } from '../../../shared/wsl-paths' import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' import { OpenCodeTextTaskError, runOwnedOpenCodeTextTask } from './opencode-owned-text-task' import { runOpenCodeWslTextTask } from './wsl/opencode-wsl-text-task' -import { killSourceControlAgentProcess } from '../../text-generation/source-control-agent-termination' +import { killSourceControlAgentProcess } from '../../text-generation/execution/source-control-agent-termination' import { clearLocalGenerationCancelToken, localGenerationLaneKey, setLocalGenerationCancelToken -} from '../../text-generation/source-control-generation-lanes' +} from '../../text-generation/execution/source-control-generation-lanes' import { processEnvWithoutAgentSession } from '../../../shared/agent-launch/startup/parent-agent-session-env' -import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../../text-generation/source-control-generation-limits' +import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../../text-generation/execution/source-control-generation-limits' import type { InternalTextGenerationResult, LocalGenerationTarget, @@ -40,7 +40,7 @@ export async function runOpenCodeTextTask(input: { const deadline = AbortSignal.timeout(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) const signal = AbortSignal.any([canceled.signal, deadline]) const cancel = () => canceled.abort() - const lane = localGenerationLaneKey(input.operation, input.target.cwd) + const lane = localGenerationLaneKey(input.operation, input.target.cwd, input.target.laneId) setLocalGenerationCancelToken(lane, cancel) try { if (input.shouldExecute?.() === false) { @@ -82,7 +82,7 @@ export async function runOpenCodeTextTask(input: { stop: killSourceControlAgentProcess, shouldExecute: input.shouldExecute }) - const cleaned = cleanGeneratedCommitMessage(rawOutput) + const cleaned = cleanAgentAnswer(rawOutput, input.operation) if (!cleaned) { throw new OpenCodeTextTaskError('session') } diff --git a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts index 4f0b0513031..3b8a7bf7f3f 100644 --- a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts +++ b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { SearchSubprocessLineAccumulator } from '../../../../shared/search-subprocess-lines' -import { killSourceControlAgentProcess } from '../../../text-generation/source-control-agent-termination' -import { spawnSupervisedAgent } from '../../../text-generation/source-control-supervised-agent-spawn' +import { killSourceControlAgentProcess } from '../../../text-generation/execution/source-control-agent-termination' +import { spawnSupervisedAgent } from '../../../text-generation/execution/source-control-supervised-agent-spawn' import { OPENCODE_WSL_TEXT_TASK_CLEANUP_MS, OPENCODE_WSL_TEXT_TASK_REQUEST_MAX_BYTES, @@ -25,7 +25,8 @@ const request = z.object({ 'pull-request-fields', 'branch-name', 'jira-issue-summary', - 'conversation-name' + 'conversation-name', + 'dictation-cleanup' ]) .optional(), timeoutMs: z.number().int().positive() diff --git a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts index f04f11f207b..28190433ae4 100644 --- a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts +++ b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts @@ -10,9 +10,9 @@ import { ensureWslPinnedRuntime } from '../../../wsl/execution/wsl-pinned-runtim import { runWslProcess, type WslSpec } from '../../../wsl/execution/wsl-runner' import { describeWslProcessFailure } from '../../../wsl/execution/wsl-process-failure' import { translateArgsForWsl } from '../../../git/command-runner/host-routing/wsl-path-translation' -import { spawnSourceControlAgent } from '../../../text-generation/source-control-agent-launch' -import { killSourceControlAgentProcess } from '../../../text-generation/source-control-agent-termination' -import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../../text-generation/source-control-generation-limits' +import { spawnSourceControlAgent } from '../../../text-generation/execution/source-control-agent-launch' +import { killSourceControlAgentProcess } from '../../../text-generation/execution/source-control-agent-termination' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../../text-generation/execution/source-control-generation-limits' import { waitForProcessExitUntil } from '../../../provider-process/provider-process-exit-deadline' import type { TextGenerationOperation, diff --git a/src/main/opencode/transcripts/opencode-session-history.ts b/src/main/opencode/transcripts/opencode-session-history.ts index a46a6b4b25a..4f36be36254 100644 --- a/src/main/opencode/transcripts/opencode-session-history.ts +++ b/src/main/opencode/transcripts/opencode-session-history.ts @@ -2,7 +2,7 @@ import { ownOptionsInclude, resumeInvocationFromOptions, type StructuredAgentSessionHistory -} from '../../native-chat/structured-agent-cli-conversations' +} from '../../native-chat/conversation-adoption/structured-agent-cli-conversations' export const OPENCODE_SESSION_HISTORY: StructuredAgentSessionHistory = { rowAgents: ['opencode', 'opencode2'], diff --git a/src/main/opencode/transcripts/opencode-transcript-import.ts b/src/main/opencode/transcripts/opencode-transcript-import.ts index d98d0bf6745..328e3df94ec 100644 --- a/src/main/opencode/transcripts/opencode-transcript-import.ts +++ b/src/main/opencode/transcripts/opencode-transcript-import.ts @@ -1,5 +1,5 @@ import { stat } from 'node:fs/promises' -import { admitTranscriptPath } from '../../native-chat/transcript-path-admission' +import { admitTranscriptPath } from '../../native-chat/transcript-discovery/transcript-path-admission' import { dirname } from 'node:path' import { homedir } from 'node:os' import { isLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' @@ -7,7 +7,7 @@ import { getManagedDataAccountService } from '../../managed-data-accounts/servic import { absoluteConversationStore, type StructuredAgentTranscriptImport -} from '../../native-chat/structured-agent-cli-conversations' +} from '../../native-chat/conversation-adoption/structured-agent-cli-conversations' import { resolveOpenCodeDatabasePath } from '../accounts/opencode-data-directory' import { environmentForStructuredOpenCodeAccountHome } from '../accounts/opencode-structured-account-home' diff --git a/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts index df765279535..77616a1843f 100644 --- a/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts @@ -38,7 +38,7 @@ import { setOrcaCloudSignInLink, startOrcaCloudSignInProgress } from './profile-cloud-sign-in-progress' -import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/relay-region-preference' +import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/region-selection/relay-region-preference' import './profile-cloud-capability-refresh' diff --git a/src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts b/src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts index 70bcc80756b..18161b749c4 100644 --- a/src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts @@ -2,7 +2,7 @@ import type { Repo } from '../../../shared/repo-types' import { mergeRetiredNameRegistries, type RetiredNameRegistry -} from '../../../shared/worktree/retired-name-registry' +} from '../../../shared/worktree/naming/retired-name-registry' import { getRemoteRetirementNamespaceKey } from '../../workspaces/removal/retirement/worktree-name-retirement' import { retirementNamespaceKeysToRead } from '../../workspaces/removal/retirement/worktree-retirement-namespace' import type { PersistedState } from '../../../shared/persisted-state-types' diff --git a/src/main/orca-profiles/project-transfer/profile-project-state-file.ts b/src/main/orca-profiles/project-transfer/profile-project-state-file.ts index acbeb9e3b57..70573b77246 100644 --- a/src/main/orca-profiles/project-transfer/profile-project-state-file.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-state-file.ts @@ -12,7 +12,7 @@ import type { Project, ProjectHostSetup } from '../../../shared/project-types' import type { Repo } from '../../../shared/repo-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { SparsePreset } from '../../../shared/worktree/create-types' -import type { RetiredNameRegistry } from '../../../shared/worktree/retired-name-registry' +import type { RetiredNameRegistry } from '../../../shared/worktree/naming/retired-name-registry' import '../profile-index-store' import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from '../profile-storage-paths' import { diff --git a/src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts index 8d48800ad20..1cfd6224286 100644 --- a/src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts @@ -6,7 +6,7 @@ import type { WorkspaceKey } from '../../../shared/workspace-scope' import type { PersistedState } from '../../../shared/persisted-state-types' import type { Repo } from '../../../shared/repo-types' import type { SparsePreset } from '../../../shared/worktree/create-types' -import type { RetiredNameRegistry } from '../../../shared/worktree/retired-name-registry' +import type { RetiredNameRegistry } from '../../../shared/worktree/naming/retired-name-registry' import { extractRetiredNameRegistriesByNamespace, mergeRetiredNameRegistryMaps @@ -24,7 +24,7 @@ import { rekeyWorktreeId, rekeyWorkspaceKey } from './profile-project-worktree-identity' -import { assertNoCrossStoreLinkedWorkspaceInMove } from '../../../shared/worktree/cross-store-lineage-move-refusal' +import { assertNoCrossStoreLinkedWorkspaceInMove } from '../../../shared/worktree/lineage/cross-store-lineage-move-refusal' export type TransferPayload = { repo: Repo diff --git a/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts index 823124fa78d..9c90b6a65cc 100644 --- a/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts @@ -66,6 +66,15 @@ async function loadTransferModule() { return import('./profile-project-transfer') } +function transferMove( + transfer: Awaited>['transferOrcaProfileProject'] +) { + return transfer( + { sourceProfileId: 'personal', targetProfileId: 'work', repoId: 'repo-1', mode: 'move' }, + testState.dir + ) +} + function profile(id: string, name: string): OrcaProfileIndex['profiles'][number] { return { id, @@ -135,6 +144,22 @@ function makeState(overrides: Partial = {}): PersistedState { } } +// A profile saved before artifactSharingEnabled existed carries no defaults for it. +function writeOlderProfileStateDatabase( + profileId: string, + settings: Record, + repos: Repo[] = [] +): void { + const databasePath = profileDatabasePath(profileId) + mkdirSync(join(databasePath, '..'), { recursive: true }) + const opened = openProfileStateDatabase(databasePath, profileId) + try { + importProfileStateJson(opened.db, JSON.stringify({ settings, repos })) + } finally { + opened.db.close() + } +} + describe('profile project transfer', () => { beforeEach(() => { testState.dir = mkdtempSync(join(tmpdir(), 'orca-profile-transfer-')) @@ -200,4 +225,16 @@ describe('profile project transfer', () => { expect(readProfileStateDatabase('personal').repos).toHaveLength(1) expect(existsSync(intentPath)).toBe(true) }) + + it('moves a project without granting publishing permission to either older profile', async () => { + writeOlderProfileStateDatabase('personal', {}, [makeRepo()]) + writeOlderProfileStateDatabase('work', {}) + const { transferOrcaProfileProject } = await loadTransferModule() + + expect(transferMove(transferOrcaProfileProject)).toMatchObject({ status: 'transferred' }) + expect(readProfileStateDatabase('personal').settings).not.toHaveProperty( + 'artifactSharingEnabled' + ) + expect(readProfileStateDatabase('work').settings).not.toHaveProperty('artifactSharingEnabled') + }) }) diff --git a/src/main/orcad/orcad-account-services.ts b/src/main/orcad/account-launch/orcad-account-services.ts similarity index 76% rename from src/main/orcad/orcad-account-services.ts rename to src/main/orcad/account-launch/orcad-account-services.ts index ae8767016d3..65a2d7daf8e 100644 --- a/src/main/orcad/orcad-account-services.ts +++ b/src/main/orcad/account-launch/orcad-account-services.ts @@ -1,24 +1,24 @@ -import type { Store } from '../persistence/loading-store/store' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import type { GetSelectedCodexHomePath, PrepareClaudeAuth, PrepareCodexSessionResume -} from '../ipc/pty/host-env/types' +} from '../../ipc/pty/host-env/types' import type { AiVaultPrepareSessionResumeArgs, AiVaultPrepareSessionResumeResult -} from '../../shared/ai-vault/resume/ai-vault-resume-preparation' -import type { ClaudeStatusLineRateLimits } from '../../shared/claude-statusline-rate-limits' -import { resolveTuiAgentLaunchEnv } from '../../shared/agent-launch/choices/tui-agent-launch-defaults' -import { createProviderAccountServices } from '../providers/accounts/provider-account-services' -import { createCodexRuntimeHomeLaunchPreparation } from '../codex/configuration/homes/codex-runtime-home-launch-preparation' -import { createCodexSessionResumeLaunchPreparation } from '../codex/history/resume/codex-session-resume-launch-preparation' -import { prepareCodexAiVaultSessionResume } from '../codex/history/resume/codex-ai-vault-session-resume' -import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { resolveHostAgentBaseEnvironment } from '../runtime/agent-session/environment/structured-agent-shell-environment' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' +} from '../../../shared/ai-vault/resume/ai-vault-resume-preparation' +import type { ClaudeStatusLineRateLimits } from '../../../shared/claude-statusline-rate-limits' +import { resolveTuiAgentLaunchEnv } from '../../../shared/agent-launch/choices/tui-agent-launch-defaults' +import { createProviderAccountServices } from '../../providers/accounts/provider-account-services' +import { createCodexRuntimeHomeLaunchPreparation } from '../../codex/configuration/homes/codex-runtime-home-launch-preparation' +import { createCodexSessionResumeLaunchPreparation } from '../../codex/history/resume/codex-session-resume-launch-preparation' +import { prepareCodexAiVaultSessionResume } from '../../codex/history/resume/codex-ai-vault-session-resume' +import { resolveHostCodexSessionSourceHome } from '../../codex/history/rollouts/codex-session-source-home' +import { resolveHostAgentBaseEnvironment } from '../../runtime/agent-session/environment/structured-agent-shell-environment' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import type { BackendServiceCleanup } from '../../backend/service-composition' type StructuredLaunchInput = { launchEnv: NodeJS.ProcessEnv } @@ -50,7 +50,7 @@ export function createOrcadAccountServices(args: { setClaudeStatusLineListener: ( listener: ((event: ClaudeStatusLineRateLimits) => void) | null ) => void - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void + registerCleanup: (cleanup: BackendServiceCleanup) => void /** Client-provided account homes override host selection, as for PTYs. */ clientCodexHomes: { selectLaunchHome: GetSelectedCodexHomePath diff --git a/src/main/orcad/account-launch/orcad-codex-account-homes.ts b/src/main/orcad/account-launch/orcad-codex-account-homes.ts new file mode 100644 index 00000000000..4ddecf9c34e --- /dev/null +++ b/src/main/orcad/account-launch/orcad-codex-account-homes.ts @@ -0,0 +1,39 @@ +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { isAgentStatusHooksEnabledForAgent } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { + listGuestCodexAccountHomes, + resolveGuestCodexAccountHome +} from '../../codex-accounts/managed-homes/guest-codex-account-homes' +import { reconcileCodexAccountHomeHook } from '../../codex/hooks/reconciliation/codex-account-home-hook' +import { stopCodexStateDbBackfillRecoveries } from '../../codex/history/index/codex-state-db-backfill-recovery' +import type { GetSelectedCodexHomePath } from '../../ipc/pty/host-env/types' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import type { BackendServiceCleanup } from '../../backend/service-composition' + +/** Keep host status hooks and session discovery in client-selected managed CODEX_HOME paths. */ +export function orcadCodexAccountHomes( + getSettings: () => GlobalSettings, + registerCleanup: (cleanup: BackendServiceCleanup) => void +) { + registerCleanup(() => stopCodexStateDbBackfillRecoveries()) + const selectLaunchHome: GetSelectedCodexHomePath = async (_target, launchEnv, context) => { + // Wire-supplied CODEX_HOME must be managed; user-owned homes are not ours to edit. + const home = resolveGuestCodexAccountHome(launchEnv?.CODEX_HOME) + if (!home) { + return null + } + const isEnabled = () => isAgentStatusHooksEnabledForAgent(getSettings(), 'codex') + // R42, COMPAT(wsl-bridge): the bridge's panes share these homes; off skips until D4 drops it. + if (isEnabled() || !isWslHostOrcadProcess()) { + await reconcileCodexAccountHomeHook(home, isEnabled, context?.launchesCodex === true) + } + return home + } + return { + selectLaunchHome, + /** Read selected homes without hook reconciliation for record-less catalogs. */ + readLaunchHome: (launchEnv?: NodeJS.ProcessEnv): string | null => + resolveGuestCodexAccountHome(launchEnv?.CODEX_HOME), + listSessionHomes: (): readonly string[] => listGuestCodexAccountHomes() + } +} diff --git a/src/main/orcad/orcad-host-account-launch-env-store.ts b/src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts similarity index 89% rename from src/main/orcad/orcad-host-account-launch-env-store.ts rename to src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts index dad560a016d..c533c91cfc2 100644 --- a/src/main/orcad/orcad-host-account-launch-env-store.ts +++ b/src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts @@ -5,9 +5,9 @@ import { join } from 'node:path' import { HostAccountLaunchEnvParams, type HostAccountLaunchEnv -} from '../../shared/agent-launch/startup/host-account-launch-env' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' +} from '../../../shared/agent-launch/startup/host-account-launch-env' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' import { createWslHostClaudeProfileRefresh } from './orcad-wsl-host-claude-profile-refresh' const FILE_NAME = 'host-account-launch-env.json' diff --git a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts b/src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts similarity index 84% rename from src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts rename to src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts index 008e92264da..f91a4b31a7a 100644 --- a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts +++ b/src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts @@ -6,11 +6,11 @@ import { existsSync } from 'node:fs' import { homedir } from 'node:os' import { posix } from 'node:path' -import type { HostAccountLaunchEnv } from '../../shared/agent-launch/startup/host-account-launch-env' -import { claudeProfileMarkerPath } from '../claude-accounts/profiles/claude-profile-paths' -import type { ClaudeProfileSetupReport } from '../claude-accounts/profiles/setup/claude-profile-setup' -import { wslClaudeProfile } from '../claude-accounts/profiles/wsl/claude-profile-wsl-paths' -import { provisionWslClaudeAccountProfile } from '../claude-accounts/profiles/wsl/claude-profile-wsl-provision' +import type { HostAccountLaunchEnv } from '../../../shared/agent-launch/startup/host-account-launch-env' +import { claudeProfileMarkerPath } from '../../claude-accounts/profiles/claude-profile-paths' +import type { ClaudeProfileSetupReport } from '../../claude-accounts/profiles/setup/claude-profile-setup' +import { wslClaudeProfile } from '../../claude-accounts/profiles/wsl/claude-profile-wsl-paths' +import { provisionWslClaudeAccountProfile } from '../../claude-accounts/profiles/wsl/claude-profile-wsl-provision' /** The desktop router's cap: a slow refresh delays a launch this long, then runs alongside it. */ const REFRESH_WAIT_MS = 5_000 diff --git a/src/main/orcad/orcad-artifact-cache-retention.test.ts b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts similarity index 98% rename from src/main/orcad/orcad-artifact-cache-retention.test.ts rename to src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts index faa07750cee..083c3ad1f8f 100644 --- a/src/main/orcad/orcad-artifact-cache-retention.test.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts @@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' import { pruneDesktopOrcadArtifactCache, pruneOrcadArtifactCache diff --git a/src/main/orcad/orcad-artifact-cache-retention.ts b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.ts similarity index 91% rename from src/main/orcad/orcad-artifact-cache-retention.ts rename to src/main/orcad/artifact-slots/orcad-artifact-cache-retention.ts index d50ff03fe6c..a2e75edc634 100644 --- a/src/main/orcad/orcad-artifact-cache-retention.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.ts @@ -2,12 +2,13 @@ // Unknown machine/boot ownership must preserve slots too. import { readdir, rm, stat } from 'node:fs/promises' import { join } from 'node:path' -import { nodeRuntimeAsset } from '../../shared/node-runtime-pin' -import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' -import { orcadPeerPidIsJudgeableHere } from './orcad-lock-holder-locality' +import { nodeRuntimeAsset } from '../../../shared/node-runtime-pin' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' +import { readOrcadInstanceLockRecord } from '../instance-lock/orcad-instance-lock-record' +import { orcadPeerPidIsJudgeableHere } from '../instance-lock/orcad-lock-holder-locality' import { materializedOrcadArtifactVersions } from './orcad-artifact-materializer' import { orcadArtifactSlotVersion } from './orcad-artifact-slot-name' -import { isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' +import { isProcessAlive } from '../../daemon/endpoint/identity/daemon-process-inspection' import { defaultOrcadSlotPeerJudge, liveDaemonOrcadSlots, diff --git a/src/main/orcad/orcad-artifact-identity.ts b/src/main/orcad/artifact-slots/orcad-artifact-identity.ts similarity index 88% rename from src/main/orcad/orcad-artifact-identity.ts rename to src/main/orcad/artifact-slots/orcad-artifact-identity.ts index 7c916c8b671..cb7cdf90d72 100644 --- a/src/main/orcad/orcad-artifact-identity.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-identity.ts @@ -9,9 +9,9 @@ import { ORCAD_VERSION, orcadArtifactFilenames, orcadMobileWebAssetFilenames -} from '../../shared/orcad-artifacts' -import { COMPAT_SERVER_TARGETS, SERVER_TARGETS } from '../../shared/node-runtime-pin' -import { orcadAgentBrowserNativeName } from '../../shared/orcad-agent-browser-name' +} from '../../../shared/orcad-artifacts' +import { COMPAT_SERVER_TARGETS, SERVER_TARGETS } from '../../../shared/node-runtime-pin' +import { orcadAgentBrowserNativeName } from '../../../shared/orcad-agent-browser-name' /** Hash installed bytes in the build's order; a version marker is not proof of delivery. */ export async function readOrcadArtifactIdentity(directory: string): Promise { diff --git a/src/main/orcad/orcad-artifact-materializer.test.ts b/src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts similarity index 99% rename from src/main/orcad/orcad-artifact-materializer.test.ts rename to src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts index 7c676992b3b..c121fa928f5 100644 --- a/src/main/orcad/orcad-artifact-materializer.test.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts @@ -14,7 +14,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { z } from 'zod' -import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../shared/node-runtime-pin' +import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { ORCAD_MOBILE_WEB_MANIFEST, ORCAD_NODE_RUNTIME_MARKER_FILENAME, @@ -24,13 +24,13 @@ import { orcadRipgrepArtifact, orcadTemplateCommonFilenames, orcadTemplateTargetFilenames -} from '../../shared/orcad-artifacts' +} from '../../../shared/orcad-artifacts' import { getAppEnvironment, hasAppEnvironment, setAppEnvironment, type AppEnvironment -} from '../../shared/app-environment' +} from '../../../shared/app-environment' import { assembleOrcadArtifact, getOrcadTemplateCandidates, diff --git a/src/main/orcad/orcad-artifact-materializer.ts b/src/main/orcad/artifact-slots/orcad-artifact-materializer.ts similarity index 95% rename from src/main/orcad/orcad-artifact-materializer.ts rename to src/main/orcad/artifact-slots/orcad-artifact-materializer.ts index c04585a07a5..5301e22abc6 100644 --- a/src/main/orcad/orcad-artifact-materializer.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-materializer.ts @@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto' import { existsSync } from 'node:fs' import { chmod, copyFile, mkdir, readFile, rename, rm, utimes, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' -import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import { getAppEnvironment } from '../../../shared/app-environment' +import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { ORCAD_MOBILE_WEB_DIR, ORCAD_MOBILE_WEB_MANIFEST, @@ -18,10 +18,10 @@ import { orcadTemplateCommonFilenames, orcadTemplatePackagedRipgrep, orcadTemplateTargetFilenames -} from '../../shared/orcad-artifacts' -import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../shared/node-runtime-pin' -import { findOrcadCachePath } from '../node-runtime/orcad-cache-path' -import type { PinnedRuntimeMaterializeOptions } from '../node-runtime/pinned-runtime-materializer' +} from '../../../shared/orcad-artifacts' +import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../../shared/node-runtime-pin' +import { findOrcadCachePath } from '../../node-runtime/orcad-cache-path' +import type { PinnedRuntimeMaterializeOptions } from '../../node-runtime/pinned-runtime-materializer' import { readOrcadArtifactVerificationRecord } from './orcad-artifact-verification-record' import { orcadArtifactSlotName } from './orcad-artifact-slot-name' import { @@ -35,7 +35,10 @@ import { type ExpectedSha256 } from './orcad-artifact-source-verification' import { OrcadTemplateManifestSchema, type OrcadTemplateManifest } from './orcad-template-manifest' -import { OrcadArtifactsUnavailableError, OrcadHostUnsupportedError } from './orcad-host-unavailable' +import { + OrcadArtifactsUnavailableError, + OrcadHostUnsupportedError +} from '../diagnostics/orcad-host-unavailable' type MaterializeOptions = PinnedRuntimeMaterializeOptions & { templateDir?: string diff --git a/src/main/orcad/orcad-artifact-slot-name.ts b/src/main/orcad/artifact-slots/orcad-artifact-slot-name.ts similarity index 100% rename from src/main/orcad/orcad-artifact-slot-name.ts rename to src/main/orcad/artifact-slots/orcad-artifact-slot-name.ts diff --git a/src/main/orcad/orcad-artifact-source-verification.ts b/src/main/orcad/artifact-slots/orcad-artifact-source-verification.ts similarity index 97% rename from src/main/orcad/orcad-artifact-source-verification.ts rename to src/main/orcad/artifact-slots/orcad-artifact-source-verification.ts index 3e509060559..1995a3c29f1 100644 --- a/src/main/orcad/orcad-artifact-source-verification.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-source-verification.ts @@ -2,13 +2,13 @@ import { createHash, type Hash } from 'node:crypto' import { createReadStream } from 'node:fs' import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { ORCAD_VERSION, ORCAD_VERSION_FILENAME } from '../../shared/orcad-artifacts' +import { ORCAD_VERSION, ORCAD_VERSION_FILENAME } from '../../../shared/orcad-artifacts' import { fileSignature, writeOrcadArtifactVerificationRecord, type OrcadArtifactVerificationRecord } from './orcad-artifact-verification-record' -import { fileSha256 } from '../node-runtime/pinned-runtime-materializer' +import { fileSha256 } from '../../node-runtime/pinned-runtime-materializer' export type ArtifactSource = { filename: string; path: string; executable?: boolean } export type ExpectedSha256 = { sha256: string; label: string } diff --git a/src/main/orcad/orcad-artifact-verification-record.ts b/src/main/orcad/artifact-slots/orcad-artifact-verification-record.ts similarity index 100% rename from src/main/orcad/orcad-artifact-verification-record.ts rename to src/main/orcad/artifact-slots/orcad-artifact-verification-record.ts diff --git a/src/main/orcad/orcad-daemon-slot-pins.ts b/src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts similarity index 87% rename from src/main/orcad/orcad-daemon-slot-pins.ts rename to src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts index 5ffcc927b0c..d000b610462 100644 --- a/src/main/orcad/orcad-daemon-slot-pins.ts +++ b/src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts @@ -1,14 +1,17 @@ // Daemons outlive instance locks; pin their entry/runtime slots separately. import { readdirSync, readFileSync } from 'node:fs' import { isAbsolute, join, relative, resolve, sep } from 'node:path' -import { parseDaemonPidFile } from '../daemon/endpoint/identity/daemon-pid-file-parse' -import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' +import { parseDaemonPidFile } from '../../daemon/endpoint/identity/daemon-pid-file-parse' +import { + hasErrorCode, + isProcessAlive +} from '../../daemon/endpoint/identity/daemon-process-inspection' import { currentOrcadPeerMachine, orcadPeerPidIsJudgeableHere, type OrcadPeerMachine -} from './orcad-lock-holder-locality' -import { orcadDataRootIsOnLocalDisk } from './orcad-data-root-locality' +} from '../instance-lock/orcad-lock-holder-locality' +import { orcadDataRootIsOnLocalDisk } from '../instance-lock/orcad-data-root-locality' export type OrcadSlotPeerJudge = { self: OrcadPeerMachine diff --git a/src/main/orcad/orcad-template-manifest.ts b/src/main/orcad/artifact-slots/orcad-template-manifest.ts similarity index 100% rename from src/main/orcad/orcad-template-manifest.ts rename to src/main/orcad/artifact-slots/orcad-template-manifest.ts diff --git a/src/main/orcad/external-chromium-browser-process.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-process.ts similarity index 91% rename from src/main/orcad/external-chromium-browser-process.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-browser-process.ts index e170c0e50b4..40b52dbbbc0 100644 --- a/src/main/orcad/external-chromium-browser-process.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-process.ts @@ -1,14 +1,14 @@ import { z } from 'zod' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' -import { BrowserError } from '../browser/browser-error' -import { assertUploadFilesExist } from '../browser/cdp/input/browser-upload-files' +import type { RuntimeBrowserCommandHost } from '../../../runtime/browser/commands/browser-command-contracts' +import type { RuntimeBrowserCommands } from '../../../runtime/browser/commands/browser-commands' +import { BrowserError } from '../../../browser/browser-error' +import { assertUploadFilesExist } from '../../../browser/cdp/input/browser-upload-files' import { agentBrowserEvalCommand, ExternalChromiumBrowserSession, type ExternalChromiumLaunch } from './external-chromium-browser-session' -import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' +import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import { externalChromiumCommandArguments, externalChromiumWaitCommand, @@ -20,9 +20,9 @@ import { } from './external-chromium-tab-projection' import { ExternalChromiumTabRegistry } from './external-chromium-tab-registry' import { runExternalChromiumPageInput, type PageInputSession } from './external-chromium-page-input' -import { agentBrowserSnapshotArgs } from '../browser/agent-browser/protocol/agent-browser-snapshot-arguments' -import { Snapshot } from '../../shared/rpc-contract/browser-observation-params' -import { ExpectedPageUrlGuard } from '../browser/cdp/input/browser-expected-page-url' +import { agentBrowserSnapshotArgs } from '../../../browser/agent-browser/protocol/agent-browser-snapshot-arguments' +import { Snapshot } from '../../../../shared/rpc-contract/browser/browser-observation-params' +import { ExpectedPageUrlGuard } from '../../../browser/cdp/input/browser-expected-page-url' const AgentBrowserCurrentUrl = z.object({ url: z.string() }) diff --git a/src/main/orcad/external-chromium-browser-session.test.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts similarity index 85% rename from src/main/orcad/external-chromium-browser-session.test.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts index 1dd8d8a3459..144fd9edec3 100644 --- a/src/main/orcad/external-chromium-browser-session.test.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts @@ -16,7 +16,7 @@ vi.mock('node:fs/promises', () => ({ })) import { ExternalChromiumBrowserSession } from './external-chromium-browser-session' -import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../../../browser/agent-browser/testing/agent-browser-bridge-test-harness' const BASE = { executablePath: '/opt/orca/chromium', @@ -100,13 +100,4 @@ describe('orcad external-chromium agent-browser environment', () => { message: expect.stringContaining('--no-sandbox') }) }) - - it("keeps Chromium's own explanation when another process holds the profile", async () => { - const inUse = - 'The profile appears to be in use by another Chromium process (4242) on another computer (build-box).\n' + - 'Failed to create a ProcessSingleton for your profile directory.' - await expect(startFailingOpen(inUse)).rejects.toMatchObject({ - message: expect.stringContaining('in use by another Chromium process (4242)') - }) - }) }) diff --git a/src/main/orcad/external-chromium-browser-session.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts similarity index 96% rename from src/main/orcad/external-chromium-browser-session.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts index 364a6edad00..c014d87e5a7 100644 --- a/src/main/orcad/external-chromium-browser-session.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts @@ -2,19 +2,19 @@ import { createHash, randomUUID } from 'node:crypto' import { chmod, mkdir, readFile, rm } from 'node:fs/promises' import { join } from 'node:path' import { z } from 'zod' -import { BrowserError } from '../browser/browser-error' +import { BrowserError } from '../../../browser/browser-error' import { AGENT_BROWSER_BATCH_ARGS, agentBrowserBatchInput, isAgentBrowserStaleRefError, parseAgentBrowserJsonOutput -} from '../browser/agent-browser/protocol/agent-browser-batch-command' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import { Screenshot } from '../../shared/rpc-contract/browser-observation-params' +} from '../../../browser/agent-browser/protocol/agent-browser-batch-command' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../shared/runtime-session-contracts' +import { Screenshot } from '../../../../shared/rpc-contract/browser/browser-observation-params' import { agentBrowserScreenshotArgs, readAgentBrowserScreenshot -} from '../browser/agent-browser/observation/agent-browser-screenshot-arguments' +} from '../../../browser/agent-browser/observation/agent-browser-screenshot-arguments' import { runProcess } from '@orca/process-host' import { resolveExternalChromiumProfilePath } from './external-chromium-profile-path' diff --git a/src/main/orcad/external-chromium-command-arguments.ts b/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts similarity index 96% rename from src/main/orcad/external-chromium-command-arguments.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts index e3ff45e5a45..8f7fa05b8d7 100644 --- a/src/main/orcad/external-chromium-command-arguments.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts @@ -1,6 +1,6 @@ -import { BrowserError } from '../browser/browser-error' -import { agentBrowserSetMediaArguments } from '../browser/agent-browser/protocol/agent-browser-set-media-arguments' -import { agentBrowserWaitArguments } from '../browser/agent-browser/protocol/agent-browser-wait-arguments' +import { BrowserError } from '../../../browser/browser-error' +import { agentBrowserSetMediaArguments } from '../../../browser/agent-browser/protocol/agent-browser-set-media-arguments' +import { agentBrowserWaitArguments } from '../../../browser/agent-browser/protocol/agent-browser-wait-arguments' const TARGET_OVERRIDE_FLAGS: Record = { '--args': true, '--cdp': true, diff --git a/src/main/orcad/external-chromium-page-input.ts b/src/main/orcad/browser-providers/chromium/external-chromium-page-input.ts similarity index 96% rename from src/main/orcad/external-chromium-page-input.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-page-input.ts index 2485783a6fc..849fe21a5e9 100644 --- a/src/main/orcad/external-chromium-page-input.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-page-input.ts @@ -1,13 +1,13 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' -import { assertClipboardTextWriteWithinLimitWithYield } from '../../shared/clipboard-text' -import { BrowserError } from '../browser/browser-error' +import { assertClipboardTextWriteWithinLimitWithYield } from '../../../../shared/clipboard-text' +import { BrowserError } from '../../../browser/browser-error' import { FILL_ELEMENT_FUNCTION, SELECT_ALL_ELEMENT_FUNCTION, SELECT_OPTION_TARGET_FUNCTION -} from '../browser/cdp/input/browser-element-functions' -import { typedInputSteps } from '../browser/cdp/input/cdp-keyboard-us-layout' +} from '../../../browser/cdp/input/browser-element-functions' +import { typedInputSteps } from '../../../browser/cdp/input/cdp-keyboard-us-layout' import { agentBrowserError, agentBrowserEvalCommand, diff --git a/src/main/orcad/external-chromium-profile-path.test.ts b/src/main/orcad/browser-providers/chromium/external-chromium-profile-path.test.ts similarity index 100% rename from src/main/orcad/external-chromium-profile-path.test.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-profile-path.test.ts diff --git a/src/main/orcad/external-chromium-profile-path.ts b/src/main/orcad/browser-providers/chromium/external-chromium-profile-path.ts similarity index 100% rename from src/main/orcad/external-chromium-profile-path.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-profile-path.ts diff --git a/src/main/orcad/external-chromium-tab-projection.ts b/src/main/orcad/browser-providers/chromium/external-chromium-tab-projection.ts similarity index 100% rename from src/main/orcad/external-chromium-tab-projection.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-tab-projection.ts diff --git a/src/main/orcad/external-chromium-tab-registry.ts b/src/main/orcad/browser-providers/chromium/external-chromium-tab-registry.ts similarity index 97% rename from src/main/orcad/external-chromium-tab-registry.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-tab-registry.ts index 35ae649067a..00f542b8ef2 100644 --- a/src/main/orcad/external-chromium-tab-registry.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-tab-registry.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' -import { BrowserError } from '../browser/browser-error' -import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' +import type { RuntimeBrowserCommandHost } from '../../../runtime/browser/commands/browser-command-contracts' +import { BrowserError } from '../../../browser/browser-error' +import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import type { ExternalChromiumBrowserSession } from './external-chromium-browser-session' import { externalChromiumTabInfo, diff --git a/src/main/orcad/electron-serve-browser-environment.ts b/src/main/orcad/browser-providers/electron/electron-serve-browser-environment.ts similarity index 100% rename from src/main/orcad/electron-serve-browser-environment.ts rename to src/main/orcad/browser-providers/electron/electron-serve-browser-environment.ts diff --git a/src/main/orcad/electron-serve-browser-process.ts b/src/main/orcad/browser-providers/electron/electron-serve-browser-process.ts similarity index 88% rename from src/main/orcad/electron-serve-browser-process.ts rename to src/main/orcad/browser-providers/electron/electron-serve-browser-process.ts index c54a8b0f929..f295d87085b 100644 --- a/src/main/orcad/electron-serve-browser-process.ts +++ b/src/main/orcad/browser-providers/electron/electron-serve-browser-process.ts @@ -1,28 +1,28 @@ import { BROWSER_EXPECT_URL_RUNTIME_CAPABILITY, BROWSER_GOOGLE_COOKIE_CLEAR_CAPABILITY -} from '../../shared/browser/runtime/browser-runtime-capabilities' +} from '../../../../shared/browser/runtime/browser-runtime-capabilities' import { BROWSER_EXPECT_URL_UNSUPPORTED_CODE, BrowserExpectedUrlMismatch -} from '../../shared/browser/client-hosting/browser-expected-url' -import { browserExpectedUrlMismatchError } from '../browser/cdp/input/browser-expected-page-url' +} from '../../../../shared/browser/client-hosting/browser-expected-url' +import { browserExpectedUrlMismatchError } from '../../../browser/cdp/input/browser-expected-page-url' import { setTimeout as delay } from 'node:timers/promises' import { z } from 'zod' -import { BrowserError } from '../browser/browser-error' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' -import type { RuntimeMetadata } from '../../shared/runtime-bootstrap' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import { readRuntimeMetadata } from '../runtime/rpc/server/runtime-metadata' +import { BrowserError } from '../../../browser/browser-error' +import type { RuntimeBrowserCommandHost } from '../../../runtime/browser/commands/browser-command-contracts' +import type { RuntimeBrowserCommands } from '../../../runtime/browser/commands/browser-commands' +import type { RuntimeMetadata } from '../../../../shared/runtime-bootstrap' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../shared/runtime-session-contracts' +import { readRuntimeMetadata } from '../../../runtime/rpc/server/runtime-metadata' import { spawnProcess } from '@orca/process-host' -import { isProcessAlive } from '../../shared/serve-bundle-coordination' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { BROWSER_SIDECAR_OWNER_ENV } from '../../shared/browser-sidecar-lifetime' -import { electronIsolatedProfileSwitches } from '../../shared/electron-isolated-profile-switches' -import { headlessServeOzonePlatformSwitches } from '../../shared/headless-serve-ozone-platform' -import { sendOrcadSidecarRequest } from './orcad-sidecar-runtime-client' -import { browserWaitRequestTimeoutMs } from '../../shared/browser-wait-timeout' +import { isProcessAlive } from '../../../../shared/serve-bundle-coordination' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { BROWSER_SIDECAR_OWNER_ENV } from '../../../../shared/browser-sidecar-lifetime' +import { electronIsolatedProfileSwitches } from '../../../../shared/electron-isolated-profile-switches' +import { headlessServeOzonePlatformSwitches } from '../../../../shared/headless-serve-ozone-platform' +import { sendOrcadSidecarRequest } from '../orcad-sidecar-runtime-client' +import { browserWaitRequestTimeoutMs } from '../../../../shared/browser-wait-timeout' import { electronServeEnvironment } from './electron-serve-browser-environment' import { reserveLoopbackPort } from './loopback-port-reservation' import { diff --git a/src/main/orcad/electron-sidecar-method-routing.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-method-routing.ts similarity index 100% rename from src/main/orcad/electron-sidecar-method-routing.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-method-routing.ts diff --git a/src/main/orcad/electron-sidecar-profile.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-profile.ts similarity index 87% rename from src/main/orcad/electron-sidecar-profile.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-profile.ts index bc12b6f3291..53fe86bbc35 100644 --- a/src/main/orcad/electron-sidecar-profile.ts +++ b/src/main/orcad/browser-providers/electron/electron-sidecar-profile.ts @@ -3,12 +3,12 @@ import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { z } from 'zod' -import { isSafeOwnedDirectory } from '../../shared/owned-private-directory' -import { isProcessAlive } from '../../shared/serve-bundle-coordination' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { isDirectChild } from '../window/owned-temp-staging-root' -import { readRuntimeMetadataAsync } from '../runtime/rpc/server/runtime-metadata' -import { sendOrcadSidecarRequest } from './orcad-sidecar-runtime-client' +import { isSafeOwnedDirectory } from '../../../../shared/owned-private-directory' +import { isProcessAlive } from '../../../../shared/serve-bundle-coordination' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { isDirectChild } from '../../../filesystem/owned-temp-staging-root' +import { readRuntimeMetadataAsync } from '../../../runtime/rpc/server/runtime-metadata' +import { sendOrcadSidecarRequest } from '../orcad-sidecar-runtime-client' const STOP_TIMEOUT_MS = 5_000 const ORPHAN_PROBE_TIMEOUT_MS = 2_000 diff --git a/src/main/orcad/electron-sidecar-tab-registry.test.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts similarity index 100% rename from src/main/orcad/electron-sidecar-tab-registry.test.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts diff --git a/src/main/orcad/electron-sidecar-tab-registry.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.ts similarity index 99% rename from src/main/orcad/electron-sidecar-tab-registry.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.ts index 02b8dbf048e..f10deaf9cf9 100644 --- a/src/main/orcad/electron-sidecar-tab-registry.ts +++ b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { BrowserError } from '../browser/browser-error' +import { BrowserError } from '../../../browser/browser-error' const CertificateFailure = z .object({ browserPageId: z.string() }) diff --git a/src/main/orcad/loopback-port-reservation.ts b/src/main/orcad/browser-providers/electron/loopback-port-reservation.ts similarity index 100% rename from src/main/orcad/loopback-port-reservation.ts rename to src/main/orcad/browser-providers/electron/loopback-port-reservation.ts diff --git a/src/main/orcad/orcad-agent-browser-binary.ts b/src/main/orcad/browser-providers/orcad-agent-browser-binary.ts similarity index 85% rename from src/main/orcad/orcad-agent-browser-binary.ts rename to src/main/orcad/browser-providers/orcad-agent-browser-binary.ts index c8e8e7261fe..abe55a5e455 100644 --- a/src/main/orcad/orcad-agent-browser-binary.ts +++ b/src/main/orcad/browser-providers/orcad-agent-browser-binary.ts @@ -1,8 +1,8 @@ import { accessSync, constants, existsSync } from 'node:fs' import { arch, platform } from 'node:os' import { dirname, join } from 'node:path' -import { orcadAgentBrowserNativeName } from '../../shared/orcad-agent-browser-name' -import { ensureDependencyBinaryExecutable } from '../browser/agent-browser/helper-process/agent-browser-dependency-binary' +import { orcadAgentBrowserNativeName } from '../../../shared/orcad-agent-browser-name' +import { ensureDependencyBinaryExecutable } from '../../browser/agent-browser/helper-process/agent-browser-dependency-binary' /** A slot carries only its own target's driver, so trying both libc names needs no libc probe. */ function hostDriverNames(): string[] { diff --git a/src/main/orcad/orcad-browser-install-park.ts b/src/main/orcad/browser-providers/orcad-browser-install-park.ts similarity index 98% rename from src/main/orcad/orcad-browser-install-park.ts rename to src/main/orcad/browser-providers/orcad-browser-install-park.ts index 32c66dca1d6..7b31c97b744 100644 --- a/src/main/orcad/orcad-browser-install-park.ts +++ b/src/main/orcad/browser-providers/orcad-browser-install-park.ts @@ -1,8 +1,8 @@ import { ORCAD_BROWSER_PARK_LABEL, SERVE_SUPERVISOR_HEARTBEAT_MS -} from '../../shared/serve-bundle-coordination' -import { openServeBundlePark, type ServeBundlePark } from '../../shared/serve-bundle-park' +} from '../../../shared/serve-bundle-coordination' +import { openServeBundlePark, type ServeBundlePark } from '../../../shared/serve-bundle-park' const PARK_POLL_MS = 1_000 const RESTART_RETRY_MIN_MS = 5_000 diff --git a/src/main/orcad/orcad-browser-provider.test.ts b/src/main/orcad/browser-providers/orcad-browser-provider.test.ts similarity index 96% rename from src/main/orcad/orcad-browser-provider.test.ts rename to src/main/orcad/browser-providers/orcad-browser-provider.test.ts index a24452e201c..7a503fd5ef6 100644 --- a/src/main/orcad/orcad-browser-provider.test.ts +++ b/src/main/orcad/browser-providers/orcad-browser-provider.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess, spawnProcess } from '@orca/process-host' -import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../../browser/agent-browser/testing/agent-browser-bridge-test-harness' import { resolveInstalledElectronExecutable, resolveOrcadBrowserProvider @@ -11,7 +11,7 @@ import { import { runtimeBrowserUnavailableCause, setRuntimeBrowserUnavailableCause -} from '../runtime/browser/installation/runtime-browser-commands-factory' +} from '../../runtime/browser/installation/runtime-browser-commands-factory' vi.mock('@orca/process-host', () => ({ runProcess: vi.fn(), diff --git a/src/main/orcad/orcad-browser-provider.ts b/src/main/orcad/browser-providers/orcad-browser-provider.ts similarity index 95% rename from src/main/orcad/orcad-browser-provider.ts rename to src/main/orcad/browser-providers/orcad-browser-provider.ts index cf03c41c2e5..5f0723d7b72 100644 --- a/src/main/orcad/orcad-browser-provider.ts +++ b/src/main/orcad/browser-providers/orcad-browser-provider.ts @@ -6,13 +6,13 @@ import { setRuntimeBrowserUnavailableCause, type RuntimeBrowserCommandsFactory, type RuntimeBrowserUnavailableCause -} from '../runtime/browser/installation/runtime-browser-commands-factory' -import { ExternalChromiumBrowserProcess } from './external-chromium-browser-process' -import type { ExternalChromiumLaunch } from './external-chromium-browser-session' +} from '../../runtime/browser/installation/runtime-browser-commands-factory' +import { ExternalChromiumBrowserProcess } from './chromium/external-chromium-browser-process' +import type { ExternalChromiumLaunch } from './chromium/external-chromium-browser-session' import { resolveOrcadAgentBrowserBinary } from './orcad-agent-browser-binary' -import { ElectronServeBrowserProcess } from './electron-serve-browser-process' +import { ElectronServeBrowserProcess } from './electron/electron-serve-browser-process' import { openOrcadBrowserInstallPark } from './orcad-browser-install-park' -import { errorMessage } from '../../shared/error-message' +import { errorMessage } from '../../../shared/error-message' export type OrcadBrowserProvider = { kind: 'electron' | 'chromium' diff --git a/src/main/orcad/orcad-browser-startup.ts b/src/main/orcad/browser-providers/orcad-browser-startup.ts similarity index 90% rename from src/main/orcad/orcad-browser-startup.ts rename to src/main/orcad/browser-providers/orcad-browser-startup.ts index a0aef4d2d57..0542e657420 100644 --- a/src/main/orcad/orcad-browser-startup.ts +++ b/src/main/orcad/browser-providers/orcad-browser-startup.ts @@ -1,10 +1,10 @@ -import { BrowserError } from '../browser/browser-error' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' +import { BrowserError } from '../../browser/browser-error' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../shared/runtime-session-contracts' +import type { RuntimeBrowserCommands } from '../../runtime/browser/commands/browser-commands' import { browserUnavailableError, setRuntimeBrowserCommandsFactory -} from '../runtime/browser/installation/runtime-browser-commands-factory' +} from '../../runtime/browser/installation/runtime-browser-commands-factory' import { resolveOrcadBrowserProvider, type OrcadBrowserProvider, diff --git a/src/main/orcad/orcad-client-page-commands.ts b/src/main/orcad/browser-providers/orcad-client-page-commands.ts similarity index 77% rename from src/main/orcad/orcad-client-page-commands.ts rename to src/main/orcad/browser-providers/orcad-client-page-commands.ts index 11e8e8e4a1e..edfa1a8117b 100644 --- a/src/main/orcad/orcad-client-page-commands.ts +++ b/src/main/orcad/browser-providers/orcad-client-page-commands.ts @@ -1,37 +1,37 @@ // Paired desktops can host pages without a local engine; present engine and desktop pages as one tab list. -import { BrowserError } from '../browser/browser-error' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' +import { BrowserError } from '../../browser/browser-error' +import type { RuntimeBrowserCommands } from '../../runtime/browser/commands/browser-commands' +import type { RuntimeBrowserCommandHost } from '../../runtime/browser/commands/browser-command-contracts' import type { BrowserTabListResult, BrowserTabShowResult, BrowserTabSwitchResult -} from '../../shared/browser/runtime/runtime-browser-contracts' -import { browserUnavailableError } from '../runtime/browser/installation/runtime-browser-commands-factory' -import { browserTabCreateClientPageStartsActive } from '../runtime/browser/tabs/browser-tab-create-publication' +} from '../../../shared/browser/runtime/runtime-browser-contracts' +import { browserUnavailableError } from '../../runtime/browser/installation/runtime-browser-commands-factory' +import { browserTabCreateClientPageStartsActive } from '../../runtime/browser/tabs/browser-tab-create-publication' import { closeBrowserPageWithoutEngine, resolveClientPageToClose, retireRuntimeBrowserClientPage -} from '../runtime/browser/client-pages/browser-client-page-close' +} from '../../runtime/browser/client-pages/browser-client-page-close' import { - canPlacePairedPage, createBrowserClientPage, createBrowserPageOnPairedHost, DEFAULT_BROWSER_PROFILE_ID, hasPairedPageHost, openBrowserUrlOnClient -} from '../runtime/browser/client-pages/browser-client-page-opening' +} from '../../runtime/browser/client-pages/browser-client-page-opening' +import { opensOnPairedDesktop } from '../../runtime/browser/client-pages/server-agent-tab-placement' import { BrowserClientPageQueries, yieldClientPageSelection, type BrowserEngineTabs -} from '../runtime/browser/client-pages/browser-client-page-queries' +} from '../../runtime/browser/client-pages/browser-client-page-queries' import { findListedBrowserTab, readBrowserTabAnnotations -} from '../runtime/browser/tabs/browser-tab-annotations' +} from '../../runtime/browser/tabs/browser-tab-annotations' type Forward = (args: unknown[], name?: string) => unknown @@ -117,31 +117,35 @@ function createTab( ) })() } - // Only this host’s CLI defaults to client pages; omitted paired-client placement means server. - if ( - !params?.placement && - !caller?.pairedDeviceId && - !engineAvailable() && - canPlacePairedPage(host) - ) { + const hasEngine = engineAvailable() + const createOnEngine = async (): Promise => { + const created = await forward([params, caller]) + if ( + hasEngine && + browserTabCreateClientPageStartsActive(params?.activate) && + host.getRuntimeBrowserPageRegistry().listPages().length > 0 + ) { + await yieldClientPageSelection(host, params?.worktree) + } + return created + } + // Engine tabs reach no client, so this host's own agents open on a paired desktop when one can host. + // The engine keeps profiles orcad cannot describe to a desktop. + const engineOnlyProfile = + hasEngine && params?.profileId !== undefined && params.profileId !== DEFAULT_BROWSER_PROFILE_ID + if (!engineOnlyProfile && opensOnPairedDesktop(host, params, caller, hasEngine)) { return createBrowserPageOnPairedHost( host, params ?? {}, - orcadBrowserProfileId(params?.profileId) + orcadBrowserProfileId(params?.profileId), + hasEngine ? async () => requireCreatedPage(await createOnEngine()) : undefined ) } - if ( - !engineAvailable() || - !browserTabCreateClientPageStartsActive(params?.activate) || - host.getRuntimeBrowserPageRegistry().listPages().length === 0 - ) { - return forward([params, caller]) - } - return (async () => { - const created = await forward([params, caller]) - await yieldClientPageSelection(host, params?.worktree) - return created - })() + return createOnEngine() +} + +function requireCreatedPage(value: unknown): { browserPageId: string } { + return requireTabResult(value, isTabSwitchResult) } function engineTabs(forward: Forward): BrowserEngineTabs { diff --git a/src/main/orcad/orcad-sidecar-runtime-client.ts b/src/main/orcad/browser-providers/orcad-sidecar-runtime-client.ts similarity index 92% rename from src/main/orcad/orcad-sidecar-runtime-client.ts rename to src/main/orcad/browser-providers/orcad-sidecar-runtime-client.ts index 9e8b832f590..8cb6a02084d 100644 --- a/src/main/orcad/orcad-sidecar-runtime-client.ts +++ b/src/main/orcad/browser-providers/orcad-sidecar-runtime-client.ts @@ -1,10 +1,10 @@ import { randomUUID } from 'node:crypto' import { createConnection } from 'node:net' import { z } from 'zod' -import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import { BrowserError } from '../browser/browser-error' -import { daemonSocketDirIsTrusted } from '../daemon/endpoint/publication/daemon-socket-endpoint-path' +import { findTransport, type RuntimeMetadata } from '../../../shared/runtime-bootstrap' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../shared/runtime-session-contracts' +import { BrowserError } from '../../browser/browser-error' +import { daemonSocketDirIsTrusted } from '../../daemon/endpoint/publication/daemon-socket-endpoint-path' const SIDECAR_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 const RuntimeResponse = z.discriminatedUnion('ok', [ diff --git a/src/main/orcad/orcad-legacy-keyring-key.ts b/src/main/orcad/credentials/orcad-legacy-keyring-key.ts similarity index 100% rename from src/main/orcad/orcad-legacy-keyring-key.ts rename to src/main/orcad/credentials/orcad-legacy-keyring-key.ts diff --git a/src/main/orcad/orcad-plaintext-credential-migration.test.ts b/src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts similarity index 96% rename from src/main/orcad/orcad-plaintext-credential-migration.test.ts rename to src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts index 658dec396bb..d47691a4db1 100644 --- a/src/main/orcad/orcad-plaintext-credential-migration.test.ts +++ b/src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts @@ -2,9 +2,9 @@ import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { SecretStore } from '../../shared/secret-store' -import { _resetSecretStoreForTests, setSecretStore } from '../../shared/secret-store' -import { readStoredCredentialToken } from '../credentials/integration-credential-file' +import type { SecretStore } from '../../../shared/secret-store' +import { _resetSecretStoreForTests, setSecretStore } from '../../../shared/secret-store' +import { readStoredCredentialToken } from '../../credentials/integration-credential-file' import { migratePlaintextCredentials } from './orcad-plaintext-credential-migration' import { orcadSecretStateFileName } from './orcad-secret-key-record' import { createOrcadSecretStore } from './orcad-secret-store' diff --git a/src/main/orcad/orcad-plaintext-credential-migration.ts b/src/main/orcad/credentials/orcad-plaintext-credential-migration.ts similarity index 79% rename from src/main/orcad/orcad-plaintext-credential-migration.ts rename to src/main/orcad/credentials/orcad-plaintext-credential-migration.ts index cd4e990fc52..aab696fa158 100644 --- a/src/main/orcad/orcad-plaintext-credential-migration.ts +++ b/src/main/orcad/credentials/orcad-plaintext-credential-migration.ts @@ -2,23 +2,29 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' -import type { SecretStore } from '../../shared/secret-store' -import { classifyUnenvelopedCredential } from '../../shared/secret-at-rest-protection' -import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-storage/secure-file' -import { writeCredentialFileAtomic } from '../credentials/integration-credential-file' +import type { SecretStore } from '../../../shared/secret-store' +import { classifyUnenvelopedCredential } from '../../../shared/secret-at-rest-protection' +import { + hardenExistingSecureFile, + writeSecureFile +} from '../../../shared/secure-storage/secure-file' +import { writeCredentialFileAtomic } from '../../credentials/integration-credential-file' import { getWorkspaceTokenDir, getWorkspaceTokenPath, LEGACY_WORKSPACE_ID -} from '../linear/accounts/linear-credential-paths' -import { getTokenDir as getJiraTokenDir } from '../jira/site-credential-store' -import { getSecretPath as getBitbucketSecretPath } from '../bitbucket/credential-store' -import { getOpenAiKeyPath } from '../speech/openai-api-key-store' -import { API_KEY_ENVELOPE_PREFIX, getZcodePlanApiKeyPath } from '../zcode/zcode-plan-api-key-store' -import { COOKIE_ENVELOPE_PREFIX, getMiniMaxCookiePath } from '../minimax/minimax-cookie-store' -import { miniMaxApiKeyEnvelopeFile } from '../minimax/minimax-api-key-store' -import { openCodeGoApiKeyEnvelopeFile } from '../opencode/accounts/opencode-go-api-key-store' -import { openAiCompatibleSpeechProviderEnvelopeFile } from '../speech/openai-compatible-speech-provider-store' +} from '../../linear/accounts/linear-credential-paths' +import { getTokenDir as getJiraTokenDir } from '../../jira/site-credential-store' +import { getSecretPath as getBitbucketSecretPath } from '../../bitbucket/credential-store' +import { getOpenAiKeyPath } from '../../speech/openai-api-key-store' +import { + API_KEY_ENVELOPE_PREFIX, + getZcodePlanApiKeyPath +} from '../../zcode/zcode-plan-api-key-store' +import { COOKIE_ENVELOPE_PREFIX, getMiniMaxCookiePath } from '../../minimax/minimax-cookie-store' +import { miniMaxApiKeyEnvelopeFile } from '../../minimax/minimax-api-key-store' +import { openCodeGoApiKeyEnvelopeFile } from '../../opencode/accounts/opencode-go-api-key-store' +import { openAiCompatibleSpeechProviderEnvelopeFile } from '../../speech/openai-compatible-speech-provider-store' type PlaintextCredentialTarget = { path: string diff --git a/src/main/orcad/orcad-secret-key-record.ts b/src/main/orcad/credentials/orcad-secret-key-record.ts similarity index 95% rename from src/main/orcad/orcad-secret-key-record.ts rename to src/main/orcad/credentials/orcad-secret-key-record.ts index 680d1384fe0..4b35018b2aa 100644 --- a/src/main/orcad/orcad-secret-key-record.ts +++ b/src/main/orcad/credentials/orcad-secret-key-record.ts @@ -16,11 +16,14 @@ import { bestEffortFsyncDirectorySync, hardenExistingSecureFile, writeSecureFile -} from '../../shared/secure-storage/secure-file' -import { restrictWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl' +} from '../../../shared/secure-storage/secure-file' +import { restrictWindowsFile } from '../../../shared/secure-storage/secure-path-windows-acl' import { ORCAD_MASTER_KEY_BYTES } from './orcad-secret-sealing' -import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' -import { errorMessage } from '../../shared/error-message' +import { + hasErrorCode, + isProcessAlive +} from '../../daemon/endpoint/identity/daemon-process-inspection' +import { errorMessage } from '../../../shared/error-message' // Read legacy keyring records only for migration. export type StoredKeyState = diff --git a/src/main/orcad/orcad-secret-key-resolution.ts b/src/main/orcad/credentials/orcad-secret-key-resolution.ts similarity index 97% rename from src/main/orcad/orcad-secret-key-resolution.ts rename to src/main/orcad/credentials/orcad-secret-key-resolution.ts index 16945c2e50b..314386381ad 100644 --- a/src/main/orcad/orcad-secret-key-resolution.ts +++ b/src/main/orcad/credentials/orcad-secret-key-resolution.ts @@ -1,8 +1,8 @@ import { randomBytes } from 'node:crypto' import { join } from 'node:path' import process from 'node:process' -import { withFileTransactionLock } from '../filesystem/file-transaction-lock' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' +import { withFileTransactionLock } from '../../filesystem/file-transaction-lock' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' import { resolveOrcadLegacyKeyringReader, type OrcadLegacyKeyringReader diff --git a/src/main/orcad/orcad-secret-protection-gap.ts b/src/main/orcad/credentials/orcad-secret-protection-gap.ts similarity index 100% rename from src/main/orcad/orcad-secret-protection-gap.ts rename to src/main/orcad/credentials/orcad-secret-protection-gap.ts diff --git a/src/main/orcad/orcad-secret-sealing.ts b/src/main/orcad/credentials/orcad-secret-sealing.ts similarity index 100% rename from src/main/orcad/orcad-secret-sealing.ts rename to src/main/orcad/credentials/orcad-secret-sealing.ts diff --git a/src/main/orcad/credentials/orcad-secret-store-startup.ts b/src/main/orcad/credentials/orcad-secret-store-startup.ts new file mode 100644 index 00000000000..83d0b77b8b6 --- /dev/null +++ b/src/main/orcad/credentials/orcad-secret-store-startup.ts @@ -0,0 +1,14 @@ +import { join } from 'node:path' +import { prepareOrcadSecretStore } from '../host-runtime/orcad-host-adapters' + +export async function prepareOrcadSecretStoreAndMigrate(userDataPath: string): Promise { + const { getSecretStore } = await import('../../../shared/secret-store') + const { reportSecretProtectionGap } = await import('../../host/secret-protection-report') + const { migratePlaintextCredentials, orcadCredentialRoot } = + await import('./orcad-plaintext-credential-migration') + // Keep sealing keys outside disposable ORCA_USER_DATA roots. + if (await prepareOrcadSecretStore(orcadCredentialRoot(), userDataPath)) { + migratePlaintextCredentials(getSecretStore()) + } + reportSecretProtectionGap({ dataFile: join(userDataPath, 'orca-data.json') }) +} diff --git a/src/main/orcad/orcad-secret-store.test.ts b/src/main/orcad/credentials/orcad-secret-store.test.ts similarity index 98% rename from src/main/orcad/orcad-secret-store.test.ts rename to src/main/orcad/credentials/orcad-secret-store.test.ts index c37a8f5d6ba..5f773aa4294 100644 --- a/src/main/orcad/orcad-secret-store.test.ts +++ b/src/main/orcad/credentials/orcad-secret-store.test.ts @@ -10,7 +10,7 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _resetSecretStoreForTests } from '../../shared/secret-store' +import { _resetSecretStoreForTests } from '../../../shared/secret-store' import type { OrcadLegacyKeyringReader } from './orcad-legacy-keyring-key' import { orcadSecretStateFileName } from './orcad-secret-key-record' import { createOrcadSecretStore } from './orcad-secret-store' diff --git a/src/main/orcad/orcad-secret-store.ts b/src/main/orcad/credentials/orcad-secret-store.ts similarity index 96% rename from src/main/orcad/orcad-secret-store.ts rename to src/main/orcad/credentials/orcad-secret-store.ts index 9a63a7a01c9..0e62a7b30e9 100644 --- a/src/main/orcad/orcad-secret-store.ts +++ b/src/main/orcad/credentials/orcad-secret-store.ts @@ -1,5 +1,5 @@ // Always report available to prevent plaintext fallback; throw on seal/unseal when the key is unavailable. -import type { SecretStore } from '../../shared/secret-store' +import type { SecretStore } from '../../../shared/secret-store' import { sweepStaleRecordStaging } from './orcad-secret-key-record' import { orcadSecretStatePath, diff --git a/src/main/orcad/orcad-daemon-retirement.ts b/src/main/orcad/daemon/orcad-daemon-retirement.ts similarity index 87% rename from src/main/orcad/orcad-daemon-retirement.ts rename to src/main/orcad/daemon/orcad-daemon-retirement.ts index d68b9648766..633619ec675 100644 --- a/src/main/orcad/orcad-daemon-retirement.ts +++ b/src/main/orcad/daemon/orcad-daemon-retirement.ts @@ -4,11 +4,11 @@ import { listLiveDaemonSessions, releaseDaemonRetirementFence, requestIdleDaemonRetirement -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { DaemonIdleRetirementResult } from '../daemon/providers/adapter/daemon-pty-runtime-state' -import type { OrcadDaemonRetirementVerdict } from '../../shared/orcad-stop-request' -import { withTimeout } from '../../shared/promise-timeout-fallback' -import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from './orcad-stop-deadlines' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { DaemonIdleRetirementResult } from '../../daemon/providers/adapter/daemon-pty-runtime-state' +import type { OrcadDaemonRetirementVerdict } from '../../../shared/orcad-stop-request' +import { withTimeout } from '../../../shared/promise-timeout-fallback' +import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from '../host-lifecycle/managed-stop/orcad-stop-deadlines' export type OrcadDaemonRetirement = { retirement: OrcadDaemonRetirementVerdict diff --git a/src/main/orcad/orcad-daemon-supervision.test.ts b/src/main/orcad/daemon/orcad-daemon-supervision.test.ts similarity index 79% rename from src/main/orcad/orcad-daemon-supervision.test.ts rename to src/main/orcad/daemon/orcad-daemon-supervision.test.ts index cf455e9623d..ed866214056 100644 --- a/src/main/orcad/orcad-daemon-supervision.test.ts +++ b/src/main/orcad/daemon/orcad-daemon-supervision.test.ts @@ -1,15 +1,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const initDaemonPtyProvider = vi.hoisted(() => vi.fn()) -vi.mock('../daemon/providers/lifecycle/daemon-provider-init', () => ({ initDaemonPtyProvider })) +vi.mock('../../daemon/providers/lifecycle/daemon-provider-init', () => ({ initDaemonPtyProvider })) import { startOrcadDaemon } from './orcad-daemon-supervision' -import { OrcadTerminalsNotDurableError } from './orcad-serve-supervision' -import { resolveOrcadExitCode } from './orcad-exit-code' +import { OrcadTerminalsNotDurableError } from '../serve-startup/orcad-serve-supervision' +import { resolveOrcadExitCode } from '../serve-startup/orcad-exit-code' import { ORCA_SERVE_SUPERVISED_ENV, ORCAD_EXIT_TERMINALS_NOT_DURABLE -} from '../../shared/serve-supervised-terminal-durability' +} from '../../../shared/serve-supervised-terminal-durability' afterEach(() => { vi.restoreAllMocks() diff --git a/src/main/orcad/orcad-daemon-supervision.ts b/src/main/orcad/daemon/orcad-daemon-supervision.ts similarity index 85% rename from src/main/orcad/orcad-daemon-supervision.ts rename to src/main/orcad/daemon/orcad-daemon-supervision.ts index 4c1e48f78cd..a3cd51dba92 100644 --- a/src/main/orcad/orcad-daemon-supervision.ts +++ b/src/main/orcad/daemon/orcad-daemon-supervision.ts @@ -3,11 +3,14 @@ import { disconnectDaemon, daemonOwnsFreshPersistentPtys, readDaemonPidRecord -} from '../daemon/providers/lifecycle/daemon-provider-state' -import { initDaemonPtyProvider } from '../daemon/providers/lifecycle/daemon-provider-init' -import { resolveTerminalSpawnAdmissionMode } from '../daemon/admission/terminal-spawn-admission-mode' -import { errorMessage } from '../../shared/error-message' -import { OrcadTerminalsNotDurableError, takeOrcadServeSupervision } from './orcad-serve-supervision' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import { initDaemonPtyProvider } from '../../daemon/providers/lifecycle/daemon-provider-init' +import { resolveTerminalSpawnAdmissionMode } from '../../daemon/admission/terminal-spawn-admission-mode' +import { errorMessage } from '../../../shared/error-message' +import { + OrcadTerminalsNotDurableError, + takeOrcadServeSupervision +} from '../serve-startup/orcad-serve-supervision' const WINDOWS_DAEMON_STARTUP_TIMEOUT_MS = 30_000 diff --git a/src/main/orcad/orcad-idle-stop-daemon-recovery.ts b/src/main/orcad/daemon/orcad-idle-stop-daemon-recovery.ts similarity index 91% rename from src/main/orcad/orcad-idle-stop-daemon-recovery.ts rename to src/main/orcad/daemon/orcad-idle-stop-daemon-recovery.ts index c535e4facb2..b8ac12f850e 100644 --- a/src/main/orcad/orcad-idle-stop-daemon-recovery.ts +++ b/src/main/orcad/daemon/orcad-idle-stop-daemon-recovery.ts @@ -1,8 +1,8 @@ // Cancelled idle stops may leave daemon admission closed. Replace only after atomic retirement // agreement: replacement could otherwise kill the old daemon’s live sessions. -import { withTimeout } from '../../shared/promise-timeout-fallback' +import { withTimeout } from '../../../shared/promise-timeout-fallback' import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' -import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from './orcad-stop-deadlines' +import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from '../host-lifecycle/managed-stop/orcad-stop-deadlines' type RetirementOutcome = Pick diff --git a/src/main/orcad/orcad-event-loop-watchdog.ts b/src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts similarity index 98% rename from src/main/orcad/orcad-event-loop-watchdog.ts rename to src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts index e2e87cb5690..6bc31064af3 100644 --- a/src/main/orcad/orcad-event-loop-watchdog.ts +++ b/src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts @@ -2,7 +2,7 @@ // The check runs on a worker thread, which a blocked main thread cannot starve. import inspector from 'node:inspector' import type { Worker } from 'node:worker_threads' -import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' +import { spawnWorkerThread } from '../../worker-threads/worker-thread-spawn' export const ORCAD_EVENT_LOOP_WATCHDOG_ENV = 'ORCA_ORCAD_EVENT_LOOP_WATCHDOG' const BEAT_INTERVAL_MS = 1_000 diff --git a/src/main/orcad/orcad-health.ts b/src/main/orcad/diagnostics/orcad-health.ts similarity index 86% rename from src/main/orcad/orcad-health.ts rename to src/main/orcad/diagnostics/orcad-health.ts index 9d3cc4920c2..bad23db05c8 100644 --- a/src/main/orcad/orcad-health.ts +++ b/src/main/orcad/diagnostics/orcad-health.ts @@ -1,22 +1,22 @@ // RPC readiness cannot prove terminal health; cross the daemon socket boundary for its own self-test. -import { hashOrcadLauncher } from '../../shared/orcad-build-identity' +import { hashOrcadLauncher } from '../../../shared/orcad-build-identity' import { confirmPtyProcessCeiling, type PtyProcessCeilingState -} from '../../shared/terminal/pty/native-process/pty-process-ceiling-state' +} from '../../../shared/terminal/pty/native-process/pty-process-ceiling-state' import process from 'node:process' -import { checkDaemonHealthWithCoverage, type DaemonHealth } from '../daemon/health/daemon-health' -import { ptySpawnHealthPlatformCoverage } from '../daemon/health/daemon-health-identity' +import { checkDaemonHealthWithCoverage, type DaemonHealth } from '../../daemon/health/daemon-health' +import { ptySpawnHealthPlatformCoverage } from '../../daemon/health/daemon-health-identity' import { daemonOwnsFreshPersistentPtys, getDaemonEndpointFacts, readDaemonPidRecord -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { OrcadProfileStateAuthoritySelection } from './orcad-profile-state-telemetry' -import { ORCAD_STOP_REQUESTS_CAPABILITY } from '../../shared/orcad-stop-request' -import type { OrcadIdleStopRecord } from '../../shared/orcad-idle-exit' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' -import { orcadPreviousUnexpectedExit } from './orcad-unexpected-exit' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { OrcadProfileStateAuthoritySelection } from '../profile-state/orcad-profile-state-telemetry' +import { ORCAD_STOP_REQUESTS_CAPABILITY } from '../../../shared/orcad-stop-request' +import type { OrcadIdleStopRecord } from '../../../shared/orcad-idle-exit' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' +import { orcadPreviousUnexpectedExit } from '../host-lifecycle/orcad-unexpected-exit' /** Distinguish real PTY spawn coverage from handshake-only platform probes. */ type PtySelfTestCoverage = 'pty-spawn' | 'handshake' diff --git a/src/main/orcad/orcad-host-unavailable.ts b/src/main/orcad/diagnostics/orcad-host-unavailable.ts similarity index 100% rename from src/main/orcad/orcad-host-unavailable.ts rename to src/main/orcad/diagnostics/orcad-host-unavailable.ts diff --git a/src/main/orcad/diagnostics/orcad-observability.test.ts b/src/main/orcad/diagnostics/orcad-observability.test.ts new file mode 100644 index 00000000000..bca26152fbb --- /dev/null +++ b/src/main/orcad/diagnostics/orcad-observability.test.ts @@ -0,0 +1,80 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +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 { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { installOrcadObservability } from './orcad-observability' + +const CI_ENV = [ + 'CI', + 'GITHUB_ACTIONS', + 'GITLAB_CI', + 'CIRCLECI', + 'TRAVIS', + 'BUILDKITE', + 'JENKINS_URL', + 'TEAMCITY_VERSION' +] + +describe('orcad trace file', () => { + let dataRoot: string + + beforeEach(() => { + dataRoot = mkdtempSync(join(tmpdir(), 'orca-orcad-observability-')) + setAppEnvironment({ + getPath: (name) => { + if (name !== 'userData') { + throw new Error(`unexpected getPath: ${name}`) + } + return dataRoot + }, + getAppPath: () => dataRoot, + getVersion: () => '0.0.0-test', + isPackaged: () => true, + onWillQuit: () => {}, + exit: () => {}, + getAppMetrics: () => [] + }) + // Clear diagnostics gates to exercise the default host. + for (const name of [...CI_ENV, 'ORCA_DIAGNOSTICS_DISABLED']) { + vi.stubEnv(name, '') + } + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + }) + + afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + rmSync(dataRoot, { recursive: true, force: true }) + }) + + const traceRecords = (): { name: string; attributes: Record }[] => + readFileSync(join(dataRoot, 'logs', 'orcad.trace.ndjson'), 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + + const reportLateSettlement = (): void => + createStructuredAgentSessionLogger().warn('settling a late dispatch failed', { + scope: 'late-settlement', + sessionId: 'session-1', + error: new Error('disk full') + }) + + it('writes a structured chat failure to its own file under the data root, flushed by close', async () => { + const close = installOrcadObservability() + + reportLateSettlement() + await close() + + expect(traceRecords()).toContainEqual( + expect.objectContaining({ + name: 'agentSession.late-settlement', + attributes: expect.objectContaining({ sessionId: 'session-1' }), + exit: expect.objectContaining({ _tag: 'Failure' }) + }) + ) + expect(existsSync(join(dataRoot, 'logs', 'main.trace.ndjson'))).toBe(false) + }) +}) diff --git a/src/main/orcad/orcad-observability.ts b/src/main/orcad/diagnostics/orcad-observability.ts similarity index 85% rename from src/main/orcad/orcad-observability.ts rename to src/main/orcad/diagnostics/orcad-observability.ts index 84ac75ae558..ac44e15c08d 100644 --- a/src/main/orcad/orcad-observability.ts +++ b/src/main/orcad/diagnostics/orcad-observability.ts @@ -3,8 +3,8 @@ import { closeObservabilityOnExit, initObservability, shutdownObservability -} from '../observability' -import { getOrcadTraceFilePath } from '../observability/logs-directory' +} from '../../observability/index' +import { getOrcadTraceFilePath } from '../../observability/logs-directory' /** Install before runtime startup; close after quit handlers so their spans reach disk. */ export function installOrcadObservability(): () => Promise { diff --git a/src/main/orcad/orcad-startup-timing.ts b/src/main/orcad/diagnostics/orcad-startup-timing.ts similarity index 100% rename from src/main/orcad/orcad-startup-timing.ts rename to src/main/orcad/diagnostics/orcad-startup-timing.ts diff --git a/src/main/orcad/orcad-terminal-census.ts b/src/main/orcad/diagnostics/orcad-terminal-census.ts similarity index 87% rename from src/main/orcad/orcad-terminal-census.ts rename to src/main/orcad/diagnostics/orcad-terminal-census.ts index d55ff3f7c92..8003644f210 100644 --- a/src/main/orcad/orcad-terminal-census.ts +++ b/src/main/orcad/diagnostics/orcad-terminal-census.ts @@ -1,9 +1,9 @@ import { countInProcessFallbackTerminals, listLiveDaemonSessionsWithProtocol -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { DaemonSessionInfo } from '../daemon/protocol/daemon-session-info' -import type { OrcadTerminalCensus } from '../../shared/orcad-terminal-census' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { DaemonSessionInfo } from '../../daemon/protocol/daemon-session-info' +import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' const UNVERIFIABLE: OrcadTerminalCensus = { liveSessions: null, diff --git a/src/main/orcad/electron-serve-provider-selection.test.ts b/src/main/orcad/electron-serve-provider-selection.test.ts deleted file mode 100644 index f201d43aebf..00000000000 --- a/src/main/orcad/electron-serve-provider-selection.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { ProcessSpec } from '@orca/process-host/process-spec' -import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RunProcessModule from '@orca/process-host' - -const { runProcessMock, spawnProcessMock } = vi.hoisted(() => ({ - runProcessMock: vi.fn(), - spawnProcessMock: vi.fn() -})) - -vi.mock('@orca/process-host', async (importOriginal) => ({ - ...(await importOriginal()), - runProcess: runProcessMock, - spawnProcess: spawnProcessMock -})) - -// Real macOS installs would register a park in the developer’s home. -vi.mock('./orcad-browser-install-park', () => ({ openOrcadBrowserInstallPark: () => null })) - -import { resolveOrcadBrowserProvider, type OrcadBrowserProvider } from './orcad-browser-provider' -import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' - -const FAKE_SIDECAR = join(import.meta.dirname, '__fixtures__', 'fake-orcad-electron-sidecar.cjs') -const INSTALLED_EXECUTABLE = join('/Applications', 'Orca.app', 'Contents', 'MacOS', 'Orca') - -let harnessRoot: string -let controlPath: string -let chromiumExecutable: string -let sidecarMode: string | undefined -let provider: OrcadBrowserProvider | null - -function agentBrowserSuccess(data: unknown) { - return Promise.resolve({ - code: 0, - signal: null, - stdout: JSON.stringify({ success: true, data, error: null }), - stderr: '', - timedOut: false - }) -} - -beforeEach(async () => { - harnessRoot = await mkdtemp(join(tmpdir(), 'orcad-provider-selection-')) - controlPath = join(harnessRoot, 'control.json') - chromiumExecutable = join(harnessRoot, process.platform === 'win32' ? 'chromium.exe' : 'chromium') - sidecarMode = undefined - provider = null - await writeFile(controlPath, '{}') - await writeFile(chromiumExecutable, '') - if (process.platform !== 'win32') { - await chmod(chromiumExecutable, 0o755) - } - - const actual = await vi.importActual('@orca/process-host') - spawnProcessMock.mockReset() - spawnProcessMock.mockImplementation((spec: ProcessSpec) => - actual.spawnProcess({ - ...spec, - program: process.execPath, - args: [FAKE_SIDECAR, ...(spec.args ?? [])], - env: { - ...spec.env, - ORCA_FAKE_SIDECAR_CONTROL: controlPath, - ...(sidecarMode ? { ORCA_FAKE_SIDECAR_MODE: sidecarMode } : {}) - } - }) - ) - runProcessMock.mockReset() - runProcessMock.mockImplementation(async (spec: ProcessSpec) => { - const command = agentBrowserCommandOf(spec.args ?? [], spec.input) - if (command[0] === 'open') { - return agentBrowserSuccess({ url: 'about:blank', title: '' }) - } - if (command[0] === 'tab') { - return agentBrowserSuccess({ - tabs: [{ active: true, tabId: 't1', title: '', url: 'about:blank' }] - }) - } - if (command[0] === 'close') { - return agentBrowserSuccess({ closed: true }) - } - throw new Error(`Unexpected agent-browser command: ${command.join(' ')}`) - }) -}) - -afterEach(async () => { - await provider?.stop() - vi.restoreAllMocks() - await rm(harnessRoot, { recursive: true, force: true }) -}) - -describe('resolveOrcadBrowserProvider Electron preference', () => { - it('falls back to the operator Chromium when the installed Electron app cannot start', async () => { - sidecarMode = 'exit-before-ready' - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - provider = await resolveOrcadBrowserProvider({ - userDataPath: join(harnessRoot, 'state'), - environment: { ORCA_BROWSER_EXECUTABLE: chromiumExecutable }, - resolveInstalledElectronExecutable: async () => INSTALLED_EXECUTABLE, - resolveAgentBrowserBinary: () => '/agent-browser' - }) - - expect(spawnProcessMock).toHaveBeenCalled() - expect(provider?.kind).toBe('chromium') - expect(warn).toHaveBeenCalledWith( - '[orcad] Installed Electron browser provider unavailable:', - expect.anything() - ) - }) -}) diff --git a/src/main/orcad/orcad-idle-exit-monitor.test.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts similarity index 80% rename from src/main/orcad/orcad-idle-exit-monitor.test.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts index 87ea58eefcf..0e30fcf132e 100644 --- a/src/main/orcad/orcad-idle-exit-monitor.test.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { OrcadIdleExitMonitor, - resolveOrcadIdlePollMs, type OrcadIdleProbe, type OrcadIdleVerdict } from './orcad-idle-exit-monitor' @@ -115,31 +114,4 @@ describe('OrcadIdleExitMonitor', () => { h.advance(100) expect(await h.monitor.check()).toBe(true) }) - - it('polls often enough for a short test timeout and at most once a minute', () => { - expect(resolveOrcadIdlePollMs(15 * 60_000)).toBe(60_000) - expect(resolveOrcadIdlePollMs(2_000)).toBe(400) - expect(resolveOrcadIdlePollMs(10)).toBe(250) - }) - - it('stops itself on a timer once idle', async () => { - vi.useFakeTimers() - try { - const onIdle = vi.fn() - const monitor = new OrcadIdleExitMonitor({ - timeoutMs: 1_000, - probes: [{ name: 'clients', read: () => 'idle' }], - lastClientActivityAt: () => 0, - onIdle, - log: () => {} - }) - monitor.start() - await vi.advanceTimersByTimeAsync(1_600) - expect(onIdle).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(5_000) - expect(onIdle).toHaveBeenCalledTimes(1) - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/orcad/orcad-idle-exit-monitor.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.ts similarity index 100% rename from src/main/orcad/orcad-idle-exit-monitor.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.ts diff --git a/src/main/orcad/orcad-idle-stop-record.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts similarity index 84% rename from src/main/orcad/orcad-idle-stop-record.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts index 30c8d3fd7e8..d6c98b8fc35 100644 --- a/src/main/orcad/orcad-idle-stop-record.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts @@ -1,15 +1,15 @@ // Consume clean idle-stop evidence once; discard failed stops so later crashes cannot inherit it. import { rmSync } from 'node:fs' import { join } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { ORCAD_IDLE_STOP_RECORD_FILENAME, OrcadIdleStopRecordSchema, type OrcadIdleStopRecord -} from '../../shared/orcad-idle-exit' +} from '../../../../shared/orcad-idle-exit' import type { OrcadIdleExitEvidence } from './orcad-idle-exit-monitor' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' const RECORD_MAX_BYTES = 16 * 1024 diff --git a/src/main/orcad/orcad-managed-idle-exit-host.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit-host.ts similarity index 88% rename from src/main/orcad/orcad-managed-idle-exit-host.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit-host.ts index cf8c9eb7608..c1fb1afb454 100644 --- a/src/main/orcad/orcad-managed-idle-exit-host.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit-host.ts @@ -1,5 +1,5 @@ -import { getAppEnvironment } from '../../shared/app-environment' -import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc' +import { getAppEnvironment } from '../../../../shared/app-environment' +import type { RuntimeRpcClientActivity } from '../../../runtime/rpc/server/runtime-rpc' import type { OrcadIdleExitEvidence } from './orcad-idle-exit-monitor' import { activationFenceExists, @@ -9,21 +9,21 @@ import { type OrcadManagedIdleExitConfig, type OrcadManagedIdleExitPorts } from './orcad-managed-idle-exit' -import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' -import { recoverDaemonAfterCancelledIdleStop } from './orcad-idle-stop-daemon-recovery' +import type { OrcadDaemonRetirement } from '../../daemon/orcad-daemon-retirement' +import { recoverDaemonAfterCancelledIdleStop } from '../../daemon/orcad-idle-stop-daemon-recovery' import { consumeOrcadIdleStopRecord, discardOrcadIdleStopRecord, writeOrcadIdleStopRecord } from './orcad-idle-stop-record' -import type { OrcadShutdownTrigger } from './orcad-lifecycle' +import type { OrcadShutdownTrigger } from '../orcad-lifecycle' import { idleStopMayReleaseWslHolder, requestOrcadWslHolderRelease, withdrawOrcadWslHolderRelease -} from './orcad-wsl-holder-release' -import type { OrcadIdleStopRecord } from '../../shared/orcad-idle-exit' -import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry' +} from '../../instance-lock/orcad-wsl-holder-release' +import type { OrcadIdleStopRecord } from '../../../../shared/orcad-idle-exit' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' let requestIdleShutdown: OrcadShutdownTrigger | null = null @@ -70,11 +70,11 @@ async function startOrcadManagedIdleExit( version: string } ): Promise { - const { getLocalPtyProvider } = await import('../ipc/pty/provider/registry') + const { getLocalPtyProvider } = await import('../../../ipc/pty/provider/registry') const { getCurrentDaemonPid, getDaemonEndpointFacts, isDaemonTerminalAdmissionClosed } = - await import('../daemon/providers/lifecycle/daemon-provider-state') + await import('../../../daemon/providers/lifecycle/daemon-provider-state') const { countLiveOrcadDaemonSessions, retireOrcadDaemonIfIdle } = - await import('./orcad-daemon-retirement') + await import('../../daemon/orcad-daemon-retirement') const idleRecord = createIdleStopRecordOwnership(input.userDataPath) const hasChatProviders = (): boolean => getStructuredAgentSessionHost()?.hasLoadedProviders() ?? false @@ -130,7 +130,7 @@ async function startOrcadManagedIdleExit( throw new Error('the retiring daemon never identified itself') } const { restartDaemon } = - await import('../daemon/providers/lifecycle/daemon-provider-restart') + await import('../../../daemon/providers/lifecycle/daemon-provider-restart') await restartDaemon({ expectedDaemonPid: retiringPid, endpointMayBeGone: true }) } }) diff --git a/src/main/orcad/orcad-managed-idle-exit.test.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts similarity index 100% rename from src/main/orcad/orcad-managed-idle-exit.test.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts diff --git a/src/main/orcad/orcad-managed-idle-exit.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.ts similarity index 90% rename from src/main/orcad/orcad-managed-idle-exit.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.ts index cc77791741b..2064eb6a575 100644 --- a/src/main/orcad/orcad-managed-idle-exit.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.ts @@ -1,15 +1,15 @@ // Live terminals block idle exit; ordinary shutdown disconnects without killing their daemon. import { stat } from 'node:fs/promises' import { join } from 'node:path' -import { RELAY_INSTALL_LOCK_NAME } from '../../shared/relay-install-lock-name' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' -import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' +import { RELAY_INSTALL_LOCK_NAME } from '../../../../shared/relay-install-lock-name' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' +import type { RuntimeRpcClientActivity } from '../../../runtime/rpc/server/runtime-rpc' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../../shared/orcad-managed-launch-env' import { ORCAD_IDLE_EXIT_TIMEOUT_MS, readOrcadE2EIdleTimeoutMs, readOrcadIdleTimeoutMs -} from '../../shared/orcad-idle-exit' +} from '../../../../shared/orcad-idle-exit' import { OrcadIdleExitMonitor, type OrcadIdleExitEvidence, diff --git a/src/main/orcad/orcad-completed-stop-receipt.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts similarity index 91% rename from src/main/orcad/orcad-completed-stop-receipt.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts index 8114ddddcbe..58f0defc7b5 100644 --- a/src/main/orcad/orcad-completed-stop-receipt.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts @@ -1,9 +1,9 @@ import { lstatSync } from 'node:fs' import { dirname, join } from 'node:path' import type { z } from 'zod' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' import { ORCAD_STOP_RECEIPTS_DIRNAME, OrcadCompletedStopReceiptSchema, @@ -13,7 +13,7 @@ import { type OrcadCompletedStopReceipt, type OrcadDaemonRetirementRecord, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' const RECEIPT_MAX_BYTES = 64 * 1024 diff --git a/src/main/orcad/orcad-managed-stop-admission.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-admission.ts similarity index 80% rename from src/main/orcad/orcad-managed-stop-admission.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-admission.ts index 5a3ae86da7d..c7018dc145f 100644 --- a/src/main/orcad/orcad-managed-stop-admission.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-admission.ts @@ -1,12 +1,12 @@ -import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' +import type { OrcadManagedStopRequest } from '../../../../shared/orcad-stop-request' import { persistOrcadDaemonRetirementRecord } from './orcad-completed-stop-receipt' -import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' -import { stopOrcadAutomationScheduler } from './orcad-automations' +import type { OrcadDaemonRetirement } from '../../daemon/orcad-daemon-retirement' +import { stopOrcadAutomationScheduler } from '../../host-runtime/orcad-automations' import { holdOrcadTerminalAdmissionUntilExit } from './orcad-stop-terminal-admission' // Keep daemon imports lazy so entry loading cannot initialize native code. async function retireLazily(): Promise { - const { retireOrcadDaemonIfIdle } = await import('./orcad-daemon-retirement') + const { retireOrcadDaemonIfIdle } = await import('../../daemon/orcad-daemon-retirement') return retireOrcadDaemonIfIdle() } diff --git a/src/main/orcad/orcad-managed-stop-cancel-race.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts similarity index 95% rename from src/main/orcad/orcad-managed-stop-cancel-race.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts index 4fe4c5414c5..77d718a4480 100644 --- a/src/main/orcad/orcad-managed-stop-cancel-race.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts @@ -10,7 +10,7 @@ vi.mock('./orcad-managed-stop-decision', async (importOriginal) => ({ readOrcadManagedStopDecision: decisions.read })) -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' import { completeOrcadManagedStop } from './orcad-managed-stop-completion' import { orcadManagedStopRequestPath } from './orcad-managed-stop-request' diff --git a/src/main/orcad/orcad-managed-stop-cancellation.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts similarity index 88% rename from src/main/orcad/orcad-managed-stop-cancellation.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts index 5e8a906c7a1..0a34a78a4aa 100644 --- a/src/main/orcad/orcad-managed-stop-cancellation.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts @@ -3,17 +3,17 @@ import { rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' -import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' +import type * as WindowsAcl from '../../../../shared/secure-storage/secure-path-windows-acl' +import type { OrcadManagedStopRequest } from '../../../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' import { orcadManagedStopRequestPath } from './orcad-managed-stop-request' import { cancelOrcadManagedStop } from './orcad-managed-stop-cancellation' import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' const hardening = vi.hoisted(() => ({ pending: new Set>() })) -vi.mock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { +vi.mock('../../../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { const acl = await importOriginal() return { ...acl, diff --git a/src/main/orcad/orcad-managed-stop-cancellation.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts similarity index 95% rename from src/main/orcad/orcad-managed-stop-cancellation.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts index db8556765c0..f820a69f57e 100644 --- a/src/main/orcad/orcad-managed-stop-cancellation.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts @@ -2,7 +2,7 @@ import { rmSync } from 'node:fs' import type { OrcadManagedStopCancellation, OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' import { orcadManagedStopRequestPath, diff --git a/src/main/orcad/orcad-managed-stop-command.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-command.ts similarity index 98% rename from src/main/orcad/orcad-managed-stop-command.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-command.ts index e5375e1fc7a..0a26dcea1aa 100644 --- a/src/main/orcad/orcad-managed-stop-command.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-command.ts @@ -7,7 +7,7 @@ import { type OrcadManagedStopCancellation, type OrcadManagedStopCompletion, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { cancelOrcadManagedStop } from './orcad-managed-stop-cancellation' import { readOrcadCompletedStopReceipt } from './orcad-completed-stop-receipt' import { readOrcadManagedStopRequest } from './orcad-managed-stop-request' diff --git a/src/main/orcad/orcad-managed-stop-completion.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-completion.ts similarity index 95% rename from src/main/orcad/orcad-managed-stop-completion.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-completion.ts index 839372a972c..edc8155adef 100644 --- a/src/main/orcad/orcad-managed-stop-completion.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-completion.ts @@ -1,23 +1,23 @@ // Request shutdown without signaling; only kernel identity, owner change or PID absence proves exit. import { setTimeout as delay } from 'node:timers/promises' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { OrcadManagedStopRequestSchema, orcadManagedStopRequestKey, type OrcadManagedStopInstance, type OrcadManagedStopRequest, type OrcadManagedStopVerdict -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { compareOrcadProcessIdentity, recordedOrcadProcessIncarnation, type OrcadProcessIdentityReaders, type OrcadRecordedIdentity -} from './orcad-process-start-time' +} from '../../instance-lock/orcad-process-start-time' import { hasErrorCode, inspectProcessSignal -} from '../daemon/endpoint/identity/daemon-process-inspection' +} from '../../../daemon/endpoint/identity/daemon-process-inspection' import { persistOrcadCompletedStopReceipt } from './orcad-completed-stop-receipt' import { readOrcadManagedStopDecision } from './orcad-managed-stop-decision' import { withdrawOrcadManagedStopRequest } from './orcad-managed-stop-cancellation' diff --git a/src/main/orcad/orcad-managed-stop-decision.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts similarity index 88% rename from src/main/orcad/orcad-managed-stop-decision.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts index 8684361d2ed..bdbf1db5f05 100644 --- a/src/main/orcad/orcad-managed-stop-decision.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts @@ -1,15 +1,15 @@ // Exclusive hard links arbitrate stop versus cancel; cancel cannot succeed once dispatch wins. import { linkSync, rmSync } from 'node:fs' import { randomUUID } from 'node:crypto' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { OrcadManagedStopDecisionSchema, OrcadManagedStopRequestSchema, type OrcadManagedStopDecision, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { orcadStopReceiptPath, readOrcadStopReceipt } from './orcad-completed-stop-receipt' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' type OrcadManagedStopDecisionValue = OrcadManagedStopDecision['decision'] diff --git a/src/main/orcad/orcad-managed-stop-identity.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts similarity index 96% rename from src/main/orcad/orcad-managed-stop-identity.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts index 37a285670e5..af67beb5b4f 100644 --- a/src/main/orcad/orcad-managed-stop-identity.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts @@ -6,15 +6,15 @@ import { z } from 'zod' import { OrcadManagedStopRequestSchema, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +} from '../../../../shared/orcad-stop-request' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' import { orcadManagedStopRequestPath } from './orcad-managed-stop-request' import { completeOrcadManagedStop, type OrcadManagedStopCompletionOptions } from './orcad-managed-stop-completion' import { orcadStopReceiptPath } from './orcad-completed-stop-receipt' -import type { OrcadProcessIncarnation } from './orcad-process-start-time' +import type { OrcadProcessIncarnation } from '../../instance-lock/orcad-process-start-time' const roots: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-managed-stop-request.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts similarity index 90% rename from src/main/orcad/orcad-managed-stop-request.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts index 4a75f130bf7..d782428b528 100644 --- a/src/main/orcad/orcad-managed-stop-request.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { lstatSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import { ORCAD_MANAGED_STOP_REQUEST_MAX_BYTES, ORCAD_MANAGED_STOP_REQUEST_PREFIX, @@ -9,8 +9,11 @@ import { type OrcadManagedStopContext, type OrcadManagedStopInstance, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' -import { readOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock' +} from '../../../../shared/orcad-stop-request' +import { + readOrcadInstanceLockRecord, + type OrcadLockRecord +} from '../../instance-lock/orcad-instance-lock-record' /** Nonce-scoped paths prevent requests from addressing a previous instance. */ export function orcadManagedStopRequestPath(instance: OrcadManagedStopInstance): string { diff --git a/src/main/orcad/orcad-managed-stop.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts similarity index 94% rename from src/main/orcad/orcad-managed-stop.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts index 51a2ed944f1..5924bf79a04 100644 --- a/src/main/orcad/orcad-managed-stop.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts @@ -2,9 +2,10 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'no import { tmpdir } from 'node:os' import { basename, dirname, join, sep } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' -import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock, type OrcadInstanceLock } from './orcad-instance-lock' +import type * as WindowsAcl from '../../../../shared/secure-storage/secure-path-windows-acl' +import type { OrcadManagedStopRequest } from '../../../../shared/orcad-stop-request' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' +import type { OrcadInstanceLock } from '../../instance-lock/orcad-instance-lock-hold' import { orcadManagedStopRequestPath, validateOrcadManagedStopRequest @@ -18,7 +19,7 @@ import { runOrcadManagedStopCommand } from './orcad-managed-stop-command' const hardening = vi.hoisted(() => ({ pending: new Set>() })) -vi.mock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { +vi.mock('../../../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { const acl = await importOriginal() return { ...acl, diff --git a/src/main/orcad/orcad-stop-deadlines.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-deadlines.ts similarity index 100% rename from src/main/orcad/orcad-stop-deadlines.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-deadlines.ts diff --git a/src/main/orcad/orcad-stop-request-listener.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts similarity index 96% rename from src/main/orcad/orcad-stop-request-listener.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts index 4e237e65aba..5e9c765fda9 100644 --- a/src/main/orcad/orcad-stop-request-listener.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts @@ -5,14 +5,14 @@ import { ORCAD_STOP_REQUEST_FILENAME, type OrcadManagedStopContext, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { orcadManagedStopRequestPath, validateOrcadManagedStopRequest } from './orcad-managed-stop-request' import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' import { withdrawOrcadManagedStopRequest } from './orcad-managed-stop-cancellation' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' export type OrcadStopRequestListener = { close(): void } diff --git a/src/main/orcad/orcad-stop-request-shutdown.integration.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts similarity index 86% rename from src/main/orcad/orcad-stop-request-shutdown.integration.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts index 89b14cc4a6e..70a5a5b327d 100644 --- a/src/main/orcad/orcad-stop-request-shutdown.integration.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts @@ -4,22 +4,23 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { spawnProcess } from '@orca/process-host' -import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../shared/orcad-artifacts' -import { ORCAD_STOP_REQUEST_FILENAME } from '../../shared/orcad-stop-request' +import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../../shared/orcad-artifacts' +import { ORCAD_STOP_REQUEST_FILENAME } from '../../../../shared/orcad-stop-request' import { killChildAndWait, killProfileDaemons, recordProfileDaemons, removeTestRoot -} from './orcad-daemon-teardown-fixture' -import { parseOrcadReadinessOutput } from '../managed-server/install/orcad-remote-launch' -import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' +} from '../../testing/daemon-processes/orcad-daemon-teardown-fixture' +import { parseOrcadReadinessOutput } from '../../../managed-server/install/orcad-remote-launch' +import { ORCAD_LOCK_FILE_NAME } from '../../instance-lock/orcad-instance-lock' +import { readOrcadInstanceLockRecord } from '../../instance-lock/orcad-instance-lock-record' import { ORCAD_SHUTDOWN_DEADLINE_MS } from './orcad-stop-deadlines' import { installPackagedOrcadSlotForTests, locatePinnedNodeForTests, skipForMissingInputs -} from './orcad-node-slot-fixture' +} from '../../testing/native-slots/orcad-node-slot-fixture' const pinnedNode = locatePinnedNodeForTests() const skip = skipForMissingInputs('artifact', [ diff --git a/src/main/orcad/orcad-stop-terminal-admission.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-terminal-admission.ts similarity index 100% rename from src/main/orcad/orcad-stop-terminal-admission.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-terminal-admission.ts diff --git a/src/main/orcad/orcad-fatal-stop-lock.test.ts b/src/main/orcad/host-lifecycle/orcad-fatal-stop-lock.test.ts similarity index 92% rename from src/main/orcad/orcad-fatal-stop-lock.test.ts rename to src/main/orcad/host-lifecycle/orcad-fatal-stop-lock.test.ts index 1c65da9a49a..6ffa86f14ff 100644 --- a/src/main/orcad/orcad-fatal-stop-lock.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-fatal-stop-lock.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -vi.mock('./orcad-browser-startup', () => ({ +vi.mock('../browser-providers/orcad-browser-startup', () => ({ startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) })) -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' import { installOrcadShutdownSignals, startOrcadWithHost } from './orcad-lifecycle' const roots: string[] = [] diff --git a/src/main/orcad/orcad-lifecycle-host.test.ts b/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts similarity index 89% rename from src/main/orcad/orcad-lifecycle-host.test.ts rename to src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts index dc1c1e9da1d..b28c26c5697 100644 --- a/src/main/orcad/orcad-lifecycle-host.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -vi.mock('./orcad-browser-startup', () => ({ +vi.mock('../browser-providers/orcad-browser-startup', () => ({ startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) })) -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' import { startOrcadWithHost } from './orcad-lifecycle' const roots: string[] = [] diff --git a/src/main/orcad/orcad-lifecycle.ts b/src/main/orcad/host-lifecycle/orcad-lifecycle.ts similarity index 80% rename from src/main/orcad/orcad-lifecycle.ts rename to src/main/orcad/host-lifecycle/orcad-lifecycle.ts index cc534a847bc..884cab84148 100644 --- a/src/main/orcad/orcad-lifecycle.ts +++ b/src/main/orcad/host-lifecycle/orcad-lifecycle.ts @@ -1,26 +1,29 @@ -import { setRuntimeBrowserCommandsFactory } from '../runtime/browser/installation/runtime-browser-commands-factory' -import { markHostShuttingDown } from '../startup/quit/host-shutdown-state' -import { setDesktopBrowserBridgeHostEnabled } from '../runtime/desktop-browser-bridge/desktop-browser-bridge-registry' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' -import { startOrcadBrowserProvider } from './orcad-browser-startup' -import { OrcadRuntimeLifetime, type OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import type { OrcadManagedStopInstance } from '../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { setRuntimeBrowserCommandsFactory } from '../../runtime/browser/installation/runtime-browser-commands-factory' +import { markHostShuttingDown } from '../../startup/quit/host-shutdown-state' +import { setDesktopBrowserBridgeHostEnabled } from '../../runtime/desktop-browser-bridge/desktop-browser-bridge-registry' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' +import { startOrcadBrowserProvider } from '../browser-providers/orcad-browser-startup' +import { + BackendServiceLifetime, + type BackendServiceCleanup +} from '../../backend/service-composition' +import type { OrcadManagedStopInstance } from '../../../shared/orcad-stop-request' +import { acquireOrcadInstanceLock } from '../instance-lock/orcad-instance-lock' import { markOrcadRunFailed, orcadRunFailed, recordOrcadPreviousUnexpectedExit } from './orcad-unexpected-exit' -import { ORCAD_BUNDLED_LAUNCHER_ENV } from './orcad-bundled-runtime' -import { resolveOrcadExitCode } from './orcad-exit-code' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' -import { recordAgentSessionRuntimeEnd } from '../runtime/agent-session/records/agent-session-runtime-end-record' -import { ORCAD_SHUTDOWN_DEADLINE_MS } from './orcad-stop-deadlines' -import { holdOrcadTerminalAdmissionUntilExit } from './orcad-stop-terminal-admission' +import { ORCAD_BUNDLED_LAUNCHER_ENV } from '../runtime-launch/orcad-bundled-runtime' +import { resolveOrcadExitCode } from '../serve-startup/orcad-exit-code' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../../shared/single-instance-exit-code' +import { recordAgentSessionRuntimeEnd } from '../../runtime/agent-session/records/agent-session-runtime-end-record' +import { ORCAD_SHUTDOWN_DEADLINE_MS } from './managed-stop/orcad-stop-deadlines' +import { holdOrcadTerminalAdmissionUntilExit } from './managed-stop/orcad-stop-terminal-admission' import { acquireProfileStateRuntimeAdmission, type ProfileStateRuntimeAdmission -} from '../persistence/profile-state/access/profile-state-access' +} from '../../persistence/profile-state/access/profile-state-access' const bundledLauncherChannel = process.env[ORCAD_BUNDLED_LAUNCHER_ENV] === '1' delete process.env[ORCAD_BUNDLED_LAUNCHER_ENV] @@ -108,15 +111,15 @@ export function installOrcadShutdownSignals( export async function stopOrcadStructuredAgentSessions(): Promise { const { stopStructuredAgentSessionRuntime } = - await import('../runtime/agent-session/structured-agent-session-runtime') + await import('../../runtime/agent-session/structured-agent-session-runtime') await stopStructuredAgentSessionRuntime({ trigger: 'quit' }) } export async function startOrcadWithLifecycle( - start: (registerRuntimeCleanup: (cleanup: OrcadRuntimeCleanup) => void) => Promise, + start: (registerRuntimeCleanup: (cleanup: BackendServiceCleanup) => void) => Promise, cleanupHost: (runtimeCleanupSucceeded: boolean) => Promise ): Promise }> { - const runtime = new OrcadRuntimeLifetime() + const runtime = new BackendServiceLifetime() const cleanup = createIdempotentOrcadCleanup(async () => { // Stamp quit before awaiting teardown so dying chat agents read as restart rather than crash. recordAgentSessionRuntimeEnd('quit') @@ -147,7 +150,7 @@ export async function startOrcadWithLifecycle( /** Keep profile admission/lock until all runtime writers stop. */ export async function startOrcadWithHost( userDataPath: string, - start: (registerCleanup: (cleanup: OrcadRuntimeCleanup) => void) => Promise, + start: (registerCleanup: (cleanup: BackendServiceCleanup) => void) => Promise, runQuitHandlers: () => void | Promise ): Promise; instance: OrcadManagedStopInstance }> { const instanceLock = acquireOrcadInstanceLock(userDataPath, { @@ -183,7 +186,7 @@ export async function startOrcadWithHost( }, async (runtimeCleanupSucceeded) => { // Failed cleanup retains both ownership fences until process exit. - const host = new OrcadRuntimeLifetime(() => { + const host = new BackendServiceLifetime(() => { if (runtimeCleanupSucceeded && !orcadRunFailed()) { instanceLock.release() } diff --git a/src/main/orcad/orcad-lock-yield.test.ts b/src/main/orcad/host-lifecycle/orcad-lock-yield.test.ts similarity index 84% rename from src/main/orcad/orcad-lock-yield.test.ts rename to src/main/orcad/host-lifecycle/orcad-lock-yield.test.ts index 6051f615f05..ac51d380859 100644 --- a/src/main/orcad/orcad-lock-yield.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-lock-yield.test.ts @@ -3,16 +3,19 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -vi.mock('./orcad-browser-startup', () => ({ +vi.mock('../browser-providers/orcad-browser-startup', () => ({ startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) })) -import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' -import { readOrcadInstanceLockRecord } from './orcad-instance-lock-record' +import { + acquireOrcadInstanceLock, + ORCAD_LOCK_FILE_NAME +} from '../instance-lock/orcad-instance-lock' +import { readOrcadInstanceLockRecord } from '../instance-lock/orcad-instance-lock-record' import { installOrcadShutdownSignals, startOrcadWithHost } from './orcad-lifecycle' -import { ORCAD_LOCK_HEARTBEAT_MS } from './orcad-lock-clone-machine' +import { ORCAD_LOCK_HEARTBEAT_MS } from '../instance-lock/orcad-lock-clone-machine' import { orcadRunFailed } from './orcad-unexpected-exit' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../../shared/single-instance-exit-code' const roots: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-process-error-guards.ts b/src/main/orcad/host-lifecycle/orcad-process-error-guards.ts similarity index 94% rename from src/main/orcad/orcad-process-error-guards.ts rename to src/main/orcad/host-lifecycle/orcad-process-error-guards.ts index 8032cc4178f..41c364d22b2 100644 --- a/src/main/orcad/orcad-process-error-guards.ts +++ b/src/main/orcad/host-lifecycle/orcad-process-error-guards.ts @@ -1,7 +1,7 @@ // Survive rejected tasks and known-benign exceptions; unknown exceptions require bounded shutdown. import process from 'node:process' -import { isNativePtyException } from '../daemon/pty-subprocess/daemon-native-pty-exception' -import { ORCAD_EXIT_FAILED } from './orcad-exit-code' +import { isNativePtyException } from '../../daemon/pty-subprocess/daemon-native-pty-exception' +import { ORCAD_EXIT_FAILED } from '../serve-startup/orcad-exit-code' import type { OrcadShutdownTrigger } from './orcad-lifecycle' // Cap rejection storms so logging cannot stall the server. diff --git a/src/main/orcad/orcad-unexpected-exit.test.ts b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.test.ts similarity index 98% rename from src/main/orcad/orcad-unexpected-exit.test.ts rename to src/main/orcad/host-lifecycle/orcad-unexpected-exit.test.ts index b43300a56f1..6e8bd46ffe1 100644 --- a/src/main/orcad/orcad-unexpected-exit.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.test.ts @@ -6,7 +6,7 @@ import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME, type OrcadInstanceLockHooks -} from './orcad-instance-lock' +} from '../instance-lock/orcad-instance-lock' const roots: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-unexpected-exit.ts b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.ts similarity index 89% rename from src/main/orcad/orcad-unexpected-exit.ts rename to src/main/orcad/host-lifecycle/orcad-unexpected-exit.ts index 96b55416aa8..bf721df1e2e 100644 --- a/src/main/orcad/orcad-unexpected-exit.ts +++ b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.ts @@ -1,6 +1,6 @@ import { uptime } from 'node:os' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' -import type { OrcadLockRecord } from './orcad-instance-lock' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' +import type { OrcadLockRecord } from '../instance-lock/orcad-instance-lock-record' /** A reclaimed orcad lock from this boot means that run died; without boot evidence a reboot cannot be ruled out. */ export function reclaimedUnexpectedExit( diff --git a/src/main/orcad/orcad-app-paths.test.ts b/src/main/orcad/host-runtime/orcad-app-paths.test.ts similarity index 100% rename from src/main/orcad/orcad-app-paths.test.ts rename to src/main/orcad/host-runtime/orcad-app-paths.test.ts diff --git a/src/main/orcad/orcad-app-paths.ts b/src/main/orcad/host-runtime/orcad-app-paths.ts similarity index 97% rename from src/main/orcad/orcad-app-paths.ts rename to src/main/orcad/host-runtime/orcad-app-paths.ts index 2839cbbd3ba..12ae8f27342 100644 --- a/src/main/orcad/orcad-app-paths.ts +++ b/src/main/orcad/host-runtime/orcad-app-paths.ts @@ -3,7 +3,7 @@ import { realpathSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import process from 'node:process' -import type { AppPathName } from '../../shared/app-environment' +import type { AppPathName } from '../../../shared/app-environment' // Empty exported paths remain unset. function env(name: string): string | null { diff --git a/src/main/orcad/host-runtime/orcad-automations.ts b/src/main/orcad/host-runtime/orcad-automations.ts new file mode 100644 index 00000000000..c825e9f034b --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-automations.ts @@ -0,0 +1,36 @@ +import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { createRuntimeAutomationService } from '../../automations/runtime-automation-service' +import { isFinalAutomationRunStatus } from '../../../shared/automations/history/automation-run' + +type AutomationStore = Pick + +let stopScheduler: (() => void) | null = null + +export function startOrcadAutomations( + runtime: OrcaRuntimeService, + store: Store, + registerCleanup: (cleanup: () => void) => void +): void { + const service = createRuntimeAutomationService({ + store, + runtime, + allowRemoteHostScheduling: true + }) + stopScheduler = () => service.stop() + // Stop before final profile flush so runs cannot persist afterward. + registerCleanup(() => service.stop()) + service.start() +} + +export function stopOrcadAutomationScheduler(): void { + stopScheduler?.() +} + +/** Pending schedules/runs must keep the host alive. */ +export function orcadAutomationsKeepHostBusy(store: AutomationStore): boolean { + return ( + store.listAutomations().some((automation) => automation.enabled) || + store.listAutomationRuns().some((run) => !isFinalAutomationRunStatus(run.status)) + ) +} diff --git a/src/main/orcad/host-runtime/orcad-emulator-bridge.ts b/src/main/orcad/host-runtime/orcad-emulator-bridge.ts new file mode 100644 index 00000000000..a4371a2c7d8 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-emulator-bridge.ts @@ -0,0 +1,20 @@ +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { BackendServiceCleanup } from '../../backend/service-composition' +import { EmulatorBridge } from '../../emulator/emulator-bridge' +import { withTimeout } from '../../../shared/promise-timeout-fallback' + +// A stalled adb must not hold the final profile flush past orcad's shutdown deadline. +const EMULATOR_TEARDOWN_BUDGET_MS = 3_000 + +/** Android drives adb/emulator on any host; iOS backends report their own host-support errors. */ +export function installOrcadEmulatorBridge( + runtime: OrcaRuntimeService, + registerCleanup: (cleanup: BackendServiceCleanup) => void +): void { + const bridge = new EmulatorBridge() + runtime.setEmulatorBridge(bridge) + // Like desktop quit: stop the helpers and devices Orca started. + registerCleanup(() => + withTimeout(bridge.destroyAllSessions(), EMULATOR_TEARDOWN_BUDGET_MS, undefined) + ) +} diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/host-runtime/orcad-entry.ts similarity index 76% rename from src/main/orcad/orcad-entry.ts rename to src/main/orcad/host-runtime/orcad-entry.ts index cdaf0a5631d..008d8d4ba70 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/host-runtime/orcad-entry.ts @@ -1,36 +1,36 @@ // Compose the Node-host runtime; paired desktop pages work even without a local browser engine. import process from 'node:process' -import { getAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment } from '../../../shared/app-environment' import { resolveUserDataPath } from './orcad-app-paths' -import { prepareOrcadCliLauncher } from './orcad-cli-launcher' +import { prepareOrcadCliLauncher } from '../serve-startup/orcad-cli-launcher' import { installOrcadHostAdapters, runOrcadQuitHandlers } from './orcad-host-adapters' -import { prepareOrcadSecretStoreAndMigrate } from './orcad-secret-store-startup' -import { describeOrcadBindExposure, resolveOrcadBindHost } from '../../shared/orcad-bind-address' +import { prepareOrcadSecretStoreAndMigrate } from '../credentials/orcad-secret-store-startup' +import { describeOrcadBindExposure, resolveOrcadBindHost } from '../../../shared/orcad-bind-address' import { flushOrcadProfileStoreForShutdown, startOrcadWithHost, stopOrcadStructuredAgentSessions -} from './orcad-lifecycle' -import { resolveOrcadWebClientRoot } from './orcad-command-arguments' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import { bindOrcadStopTerminalAdmission } from './orcad-stop-terminal-admission' -import type { OrcadHandle, OrcadOptions } from './orcad-start-contract' -import { beginOrcadIdleExit } from './orcad-managed-idle-exit-host' -import { orcadAutomationsKeepHostBusy, startOrcadAutomations } from './orcad-automations' +} from '../host-lifecycle/orcad-lifecycle' +import { resolveOrcadWebClientRoot } from '../serve-startup/orcad-command-arguments' +import type { BackendServiceCleanup } from '../../backend/service-composition' +import { bindOrcadStopTerminalAdmission } from '../host-lifecycle/managed-stop/orcad-stop-terminal-admission' +import type { OrcadHandle, OrcadOptions } from '../serve-startup/orcad-start-contract' +import { beginOrcadIdleExit } from '../host-lifecycle/idle-exit/orcad-managed-idle-exit-host' +import { orcadSchedulersKeepHostBusy, startOrcadSchedulers } from './orcad-schedulers' import { changedAiVaultSearchSettings, type AiVaultSearchSettings -} from '../../shared/ai-vault/search/ai-vault-search-settings' -import { stampRuntimeSourceEnv } from '../../shared/runtime-source-env' +} from '../../../shared/ai-vault/search/ai-vault-search-settings' +import { stampRuntimeSourceEnv } from '../../../shared/runtime-source-env' import { adoptWslHostLoginEnvironmentLogged } from './orcad-wsl-host-login-environment' -import { orcadWsPortOptions } from './orcad-ws-port-policy' -import { createOrcadStartupTiming } from './orcad-startup-timing' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' +import { orcadWsPortOptions } from '../serve-startup/orcad-ws-port-policy' +import { createOrcadStartupTiming } from '../diagnostics/orcad-startup-timing' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { restoreOrcadTerminalAuthority } from './orcad-restored-terminal-authority' -import { installOrcadFeatureReadiness } from '../runtime/rpc/orcad-feature-readiness' -import { ORCA_SERVE_SUPERVISED_ENV } from '../../shared/serve-supervised-terminal-durability' -import { activateBackendServices } from '../backend/service-composition' -import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { installOrcadFeatureReadiness } from '../../runtime/rpc/startup/orcad-readiness' +import { ORCA_SERVE_SUPERVISED_ENV } from '../../../shared/serve-supervised-terminal-durability' +import { activateBackendServices } from '../../backend/service-composition' +import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' let closeOrcadObservability = (): Promise => Promise.resolve() @@ -67,12 +67,12 @@ export async function startOrcad(options: OrcadOptions = {}): Promise void + registerCleanup: (cleanup: BackendServiceCleanup) => void ): Promise> { const { time: timed, report: reportStartupTiming } = createOrcadStartupTiming() // Overlap login-shell probing with imports and store startup. const loginEnvironment = adoptWslHostLoginEnvironmentLogged() - const { startOrcadDaemon, stopOrcadDaemon } = await import('./orcad-daemon-supervision') + const { startOrcadDaemon, stopOrcadDaemon } = await import('../daemon/orcad-daemon-supervision') // The daemon and its PTYs inherit the adopted login env and nothing later startup writes, so it // spawns as soon as that lands, alongside imports, stores and hooks. Rejects only when supervised. const daemonStartup = loginEnvironment.then(() => timed('daemon', () => startOrcadDaemon())) @@ -82,33 +82,34 @@ async function activateOrcadRuntime( // mid-spawn. It disconnects without killing daemon PTYs that must survive restart, after an // in-flight spawn settles; a failed one leaves only the disconnect to do. registerCleanup(() => daemonStartup.catch(() => {}).then(() => stopOrcadDaemon())) - const { OrcaRuntimeService } = await import('../runtime/orca-runtime') - const { OrcaRuntimeRpcServer } = await import('../runtime/rpc/server/runtime-rpc') - const { registerHeadlessPtyRuntime } = await import('../ipc/pty/register-headless-runtime') - const { getLocalPtyProvider } = await import('../ipc/pty/provider/registry') - const { installOrcadObservability } = await import('./orcad-observability') + const { OrcaRuntimeService } = await import('../../runtime/orca-runtime') + const { OrcaRuntimeRpcServer } = await import('../../runtime/rpc/server/runtime-rpc') + const { registerHeadlessPtyRuntime } = await import('../../ipc/pty/register-headless-runtime') + const { getLocalPtyProvider } = await import('../../ipc/pty/provider/registry') + const { installOrcadObservability } = await import('../diagnostics/orcad-observability') closeOrcadObservability = installOrcadObservability() - const { ServeReadinessPublisher } = await import('../server/serve-readiness') - const { servePublishMode } = await import('../server/serve-pairing-readiness') - const { buildOrcadServeReadiness } = await import('./orcad-serve-readiness') - const { createOrcadProfileStateStartup } = await import('./orcad-profile-state-startup') + const { ServeReadinessPublisher } = await import('../../server/serve-readiness') + const { servePublishMode } = await import('../../server/serve-pairing-readiness') + const { buildOrcadServeReadiness } = await import('../serve-startup/orcad-serve-readiness') + const { createOrcadProfileStateStartup } = + await import('../profile-state/orcad-profile-state-startup') const { daemonOwnsFreshPersistentPtys } = - await import('../daemon/providers/lifecycle/daemon-provider-state') + await import('../../daemon/providers/lifecycle/daemon-provider-state') const { resolveDaemonSessionScrollbackRows } = - await import('../daemon/sessions/daemon-session-scrollback-window') - const { collectOrcadHealth } = await import('./orcad-health') - const { agentHookServer } = await import('../agent-hooks/server/agent-hook-server') - await import('../agent-hooks/installation/managed-agent-hook-controls') - const { agentHookRuntimeDeps } = await import('../agent-hooks/runtime/agent-hook-runtime-deps') + await import('../../daemon/sessions/daemon-session-scrollback-window') + const { collectOrcadHealth } = await import('../diagnostics/orcad-health') + const { agentHookServer } = await import('../../agent-hooks/server/agent-hook-server') + await import('../../agent-hooks/installation/managed-agent-hook-controls') + const { agentHookRuntimeDeps } = await import('../../agent-hooks/runtime/agent-hook-runtime-deps') const { installHookStatusSessionTabsRepublish } = - await import('../agent-hooks/runtime/hook-status-session-tabs-republish') + await import('../../agent-hooks/runtime/hook-status-session-tabs-republish') const { startOrcadAgentHookServer, startOrcadManagedAgentHooks } = await import('./orcad-managed-agent-hooks') const { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } = - await import('../runtime/terminal/identity/agent-status-observed-pane-identity') + await import('../../runtime/terminal/identity/agent-status-observed-pane-identity') const { disposeWatcherProcessAndWait } = - await import('../ipc/filesystem/watcher-process/parcel-watcher-process') + await import('../../ipc/filesystem/watcher-process/parcel-watcher-process') let paneGridsForShutdown: { flushPaneGrids(): Promise | null } | null = null let profileStoreForShutdown: Parameters[0] | undefined @@ -127,11 +128,11 @@ async function activateOrcadRuntime( }) registerCleanup(stopOrcadStructuredAgentSessions) registerCleanup(() => disposeWatcherProcessAndWait()) - const { DesktopPushService } = await import('../runtime/push/desktop-push-service') - const { resolvePushGatewayOrigin } = await import('../runtime/push/push-gateway-origin') + const { DesktopPushService } = await import('../../runtime/push/desktop-push-service') + const { resolvePushGatewayOrigin } = await import('../../runtime/push/push-gateway-origin') const runtimeUserDataPath = getAppEnvironment().getPath('userData') - const { startEventLoopDelayProbe } = await import('../diagnostics/event-loop-delay-probe') + const { startEventLoopDelayProbe } = await import('../../diagnostics/event-loop-delay-probe') startEventLoopDelayProbe('orcad', runtimeUserDataPath) await timed('cli-launcher', () => prepareOrcadCliLauncher()).catch((error: unknown) => { console.warn('[orcad] Could not prepare the profile CLI launcher', error) @@ -173,7 +174,7 @@ async function activateOrcadRuntime( // Runtime constructor callbacks use this index only after it is installed. let sessionSearch: { apply(settings: AiVaultSearchSettings): void; dispose(): void } | null = null - const { orcadCodexAccountHomes } = await import('./orcad-codex-account-homes') + const { orcadCodexAccountHomes } = await import('../account-launch/orcad-codex-account-homes') const codexAccountHomes = orcadCodexAccountHomes( () => profileStore.getSettings(), registerCleanup @@ -181,7 +182,7 @@ async function activateOrcadRuntime( // Gates open where each phase finishes today; RPC starts after all of them (no behavior change). const featureReadiness = installOrcadFeatureReadiness() - const { createOrcadAccountServices } = await import('./orcad-account-services') + const { createOrcadAccountServices } = await import('../account-launch/orcad-account-services') const accountLaunch = createOrcadAccountServices({ store: profileStore, setClaudeStatusLineListener: (listener) => @@ -191,7 +192,7 @@ async function activateOrcadRuntime( }) const { loadAgentSessionClaimSigner } = - await import('../runtime/agent-session/ownership/agent-session-claim-identity') + await import('../../runtime/agent-session/ownership/agent-session-claim-identity') const { createOrcadPairedEnvironmentOptions } = await import('./orcad-paired-environment-options') const pairedEnvironments = createOrcadPairedEnvironmentOptions() const runtime = new OrcaRuntimeService(profileStore, stats, { @@ -226,13 +227,15 @@ async function activateOrcadRuntime( paneGridsForShutdown = runtime accountLaunch?.attachToRuntime(runtime) - const { wireGitHubIssueLinkTitleFill } = await import('../github/github-issue-link-title-wiring') + const { wireGitHubIssueLinkTitleFill } = + await import('../../github/workspace-links/github-issue-link-title-wiring') registerCleanup(wireGitHubIssueLinkTitleFill(profileStore, runtime)) const { installOrcadEmulatorBridge } = await import('./orcad-emulator-bridge') installOrcadEmulatorBridge(runtime, registerCleanup) // Restore prior desktop-pushed account selection before automations or CLI launches. - const { restoreOrcadHostAccountLaunchEnv } = await import('./orcad-host-account-launch-env-store') + const { restoreOrcadHostAccountLaunchEnv } = + await import('../account-launch/orcad-host-account-launch-env-store') restoreOrcadHostAccountLaunchEnv(runtime, runtimeUserDataPath) featureReadiness.open('accounts') @@ -245,16 +248,16 @@ async function activateOrcadRuntime( featureReadiness.open('sessionSearch') const { startAgentStateRulesLiveUpdates } = - await import('../runtime/agent-state-rules/agent-state-rules-live-update') + await import('../../runtime/agent-state-rules/agent-state-rules-live-update') startAgentStateRulesLiveUpdates(profileStore, (rules) => console.info(`[orcad] agent state rules ${rules.version} (${rules.source})`) ) // Paired phones dictate through this host; keep its model loaded the same way the desktop does. - const { startSpeechModelWarmup } = await import('../speech/speech-model-warmup') + const { startSpeechModelWarmup } = await import('../../speech/speech-model-warmup') startSpeechModelWarmup(profileStore) if (ORCA_LAYOUT_OWNER_IS_MAIN) { const { repairDuplicatePtyPanesOnStart } = - await import('../runtime/terminal/identity/moved-pane-owner-rekey') + await import('../../runtime/terminal/identity/moved-pane-owner-rekey') // Wait behind earlier writes and persist repair before reconciliation/RPC admission. await repairDuplicatePtyPanesOnStart(profileStore, runtime) } @@ -297,7 +300,7 @@ async function activateOrcadRuntime( agentHookServer.setClaudePermissionHolds(runtime.terminalWorkerApprovals) // First RPC clients must see a fully published graph. const { publishHeadlessRuntimeGraph } = - await import('../runtime/session-graph/headless-runtime-graph') + await import('../../runtime/session-graph/headless-runtime-graph') publishHeadlessRuntimeGraph(runtime) // Only the runtime can identify running shells and install deferred migrated history. void runtime.installPendingOrcadMigrationShellHistory().catch((error: unknown) => { @@ -327,7 +330,7 @@ async function activateOrcadRuntime( await timed('rpc', () => rpc.start()) // The daemon has no window to wait for; its CI-line watches start with the runtime. runtime.startPullRequestWatches() - startOrcadAutomations(runtime, profileStore, registerCleanup) + startOrcadSchedulers(runtime, profileStore, registerCleanup) const pushService = DesktopPushService.create({ runtime, runtimeRpc: rpc, @@ -357,7 +360,7 @@ async function activateOrcadRuntime( rpc, agentStates: () => agentHookServer.getStatusSnapshot(), hasStagedMigration: () => profileStore.hasStagedOrcadMigrationCatalog(), - automationsBusy: () => orcadAutomationsKeepHostBusy(profileStore), + automationsBusy: () => orcadSchedulersKeepHostBusy(runtime, profileStore), emulatorsBusy: async () => (await runtime.getEmulatorBridge()?.hasLiveManagedSessions()) ?? false, registerCleanup diff --git a/src/main/orcad/orcad-host-adapters.ts b/src/main/orcad/host-runtime/orcad-host-adapters.ts similarity index 80% rename from src/main/orcad/orcad-host-adapters.ts rename to src/main/orcad/host-runtime/orcad-host-adapters.ts index 63ce0b05d38..9049e511e82 100644 --- a/src/main/orcad/orcad-host-adapters.ts +++ b/src/main/orcad/host-runtime/orcad-host-adapters.ts @@ -1,14 +1,14 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import process from 'node:process' -import { ORCAD_CLI_PACKAGE_FILENAME } from '../../shared/orcad-artifacts' -import { setAppEnvironment, type AppEnvironment } from '../../shared/app-environment' -import { createNodeServiceEnvironment } from '../backend/node-service-environment' -import { setSecretStore } from '../../shared/secret-store' +import { ORCAD_CLI_PACKAGE_FILENAME } from '../../../shared/orcad-artifacts' +import { setAppEnvironment, type AppEnvironment } from '../../../shared/app-environment' +import { createNodeServiceEnvironment } from '../../backend/node-service-environment' +import { setSecretStore } from '../../../shared/secret-store' import { resolveOrcadInstallRoot, resolveOrcadPath } from './orcad-app-paths' -import { getOrcadCliLauncherPath } from './orcad-cli-launcher' -import { createOrcadSecretStore, type OrcadSecretStore } from './orcad-secret-store' -import { setSpeechServiceFactories } from '../speech/speech-runtime-service' +import { getOrcadCliLauncherPath } from '../serve-startup/orcad-cli-launcher' +import { createOrcadSecretStore, type OrcadSecretStore } from '../credentials/orcad-secret-store' +import { setSpeechServiceFactories } from '../../speech/speech-runtime-service' import { orcadSpeechServiceFactories } from './orcad-speech-services' let quitRegisteredHandlers = (): void => {} diff --git a/src/main/orcad/host-runtime/orcad-managed-agent-hooks.ts b/src/main/orcad/host-runtime/orcad-managed-agent-hooks.ts new file mode 100644 index 00000000000..efbe72ef3df --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-managed-agent-hooks.ts @@ -0,0 +1,72 @@ +import { getClaudeAgentViewService } from '../../claude/agent-view/agent-view-service' +import { getAppEnvironment } from '../../../shared/app-environment' +import { startCodexHooks } from '../../codex/hooks/reconciliation/codex-hook-reconcile' +import { adoptLoginShellAgentHomes } from '../../agent-hooks/installation/agent-home-login-shell' +import { hydrateAgentCliShellPath } from '../../agent-hooks/installation/local-agent-cli-presence' +import { + isAgentStatusHooksEnabled, + isAgentStatusHooksEnabledForAgent +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { reconcileStartupManagedAgentHooks } from '../../agent-hooks/installation/managed-agent-hook-startup' +import { refreshInstalledOpenCodeStatusPlugins } from '../../opencode/status-hooks/opencode-status-plugin-startup-refresh' +import type { ProfilePreferences } from '../../persistence/loading-store/profile-preferences/profile-preferences' +import type { BackendServiceCleanup } from '../../backend/service-composition' +import type { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { installLocalHookRootEvidence } from '../../agent-hooks/observations/local-hook-root-evidence' + +/** SSH and WSL-host panes run beside this host, so it proves which agent owns each pane, from the + * first record its startup replay reads. */ +export function startOrcadAgentHookServer( + server: AgentHookServer, + options: Parameters[0] +): Promise { + installLocalHookRootEvidence(server) + return server.start(options) +} + +/** + * Reconcile hooks at startup as well as setting changes so newly managed hosts report status immediately. + * Call `readinessPublished` once readiness is out; work held off the ready path starts then. + */ +export function startOrcadManagedAgentHooks( + store: Pick, + setStatusHooksEnabled: (enabled: boolean) => void, + registerCleanup: (cleanup: BackendServiceCleanup) => void +): { readinessPublished: () => void } { + const published = Promise.withResolvers() + let stopping = false + const agentView = getClaudeAgentViewService() + void agentView.reconcile(store.getSettings()) + const removeSettingsListener = store.onSettingsChanged((updates, settings) => { + void agentView.reconcile(settings) + if ('agentStatusHooksEnabled' in updates) { + setStatusHooksEnabled(isAgentStatusHooksEnabled(settings)) + } + }) + registerCleanup(() => { + stopping = true + removeSettingsListener() + }) + const getSettings = () => store.getSettings() + const shouldHydrateShellPath = getAppEnvironment().isPackaged() + startCodexHooks({ + pathReady: shouldHydrateShellPath ? hydrateAgentCliShellPath() : Promise.resolve(), + // Every orcad host defers this; it pays off on WSL, where finding codex stats Windows-drive PATH. + startAfter: published.promise, + isEnabled: () => isAgentStatusHooksEnabledForAgent(getSettings(), 'codex'), + resolveLaunchHome: () => null + }) + void adoptLoginShellAgentHomes().then(() => + reconcileStartupManagedAgentHooks({ + getSettings, + isQuitting: () => stopping, + shouldHydrateShellPath + }) + ) + try { + refreshInstalledOpenCodeStatusPlugins(getSettings()) + } catch (error) { + console.warn('[orcad] could not refresh OpenCode status plugins:', error) + } + return { readinessPublished: () => published.resolve() } +} diff --git a/src/main/orcad/host-runtime/orcad-paired-environment-options.ts b/src/main/orcad/host-runtime/orcad-paired-environment-options.ts new file mode 100644 index 00000000000..6c2c6647084 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-paired-environment-options.ts @@ -0,0 +1,27 @@ +import { createOrchestrationEnvironmentTransport } from '../../ipc/runtime-environments/requests/orchestration-environment-transport' +import type { RuntimeConstructionDependencies } from '../../runtime/construction/runtime-construction-dependencies' +import type { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' + +type PairedEnvironmentRuntimeOptions = Required< + Pick +> + +/** Runtime options for this host's pairings: the servers it dials and the devices paired to it. */ +export function createOrcadPairedEnvironmentOptions(): { + runtimeOptions: PairedEnvironmentRuntimeOptions + /** RPC owns the device registry and starts after the runtime. */ + bindRpc: (rpc: Pick) => void +} { + let rpc: Pick | null = null + return { + runtimeOptions: { + // A headless host is a Run home too; it places workers on its own paired servers (#36853). + orchestrationEnvironmentTransport: createOrchestrationEnvironmentTransport(), + getPairedDeviceName: (pairedDeviceId) => + rpc?.getDeviceRegistry()?.getDevice(pairedDeviceId)?.name ?? null + }, + bindRpc: (server) => { + rpc = server + } + } +} diff --git a/src/main/orcad/host-runtime/orcad-restored-terminal-authority.ts b/src/main/orcad/host-runtime/orcad-restored-terminal-authority.ts new file mode 100644 index 00000000000..3141ccebd51 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-restored-terminal-authority.ts @@ -0,0 +1,21 @@ +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { OrcadFeatureReadiness } from '../../runtime/rpc/startup/orcad-readiness' +import { placeUnshownLiveTerminalsBestEffort } from '../../runtime/terminal/adoption/unshown-live-terminal-placement' +import type { createOrcadStartupTiming } from '../diagnostics/orcad-startup-timing' + +/** Restored orchestration authority, the legacy terminal reconcile and unshown placement, in order. */ +export async function restoreOrcadTerminalAuthority( + runtime: OrcaRuntimeService, + timed: ReturnType['time'], + readiness: OrcadFeatureReadiness +): Promise { + await timed('orchestration', () => runtime.refreshRestoredOrchestrationAuthority()) + readiness.open('orchestration') + // Terminal inventory stays on the critical path: no latch, every client needs it at connect. + await timed('reconcile-terminals', () => runtime.reconcileLegacyWorkerTerminals()) + if (ORCA_LAYOUT_OWNER_IS_MAIN) { + await placeUnshownLiveTerminalsBestEffort(runtime) + } + readiness.open('unshownPlacement') +} diff --git a/src/main/orcad/host-runtime/orcad-schedulers.ts b/src/main/orcad/host-runtime/orcad-schedulers.ts new file mode 100644 index 00000000000..a7d174d2e85 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-schedulers.ts @@ -0,0 +1,23 @@ +import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { startWorkspaceCleanupRunner } from '../../workspaces/cleanup/workspace-cleanup-runner-startup' +import { getWorkspaceCleanupRunner } from '../../workspaces/cleanup/workspace-cleanup-runner-registry' +import { orcadAutomationsKeepHostBusy, startOrcadAutomations } from './orcad-automations' + +/** The host's own background jobs: automation schedules and workspace cleanup rules. */ +export function startOrcadSchedulers( + runtime: OrcaRuntimeService, + store: Store, + registerCleanup: (cleanup: () => void) => void +): void { + startOrcadAutomations(runtime, store, registerCleanup) + const cleanupRunner = startWorkspaceCleanupRunner(runtime, store) + registerCleanup(() => cleanupRunner?.stop()) +} + +/** A cleanup run mid-removal must finish before idle exit, like a pending automation run. */ +export function orcadSchedulersKeepHostBusy(runtime: OrcaRuntimeService, store: Store): boolean { + return ( + orcadAutomationsKeepHostBusy(store) || getWorkspaceCleanupRunner(runtime)?.isRunning() === true + ) +} diff --git a/src/main/orcad/orcad-session-scanner-idle.ts b/src/main/orcad/host-runtime/orcad-session-scanner-idle.ts similarity index 82% rename from src/main/orcad/orcad-session-scanner-idle.ts rename to src/main/orcad/host-runtime/orcad-session-scanner-idle.ts index f7e83c9a354..961913db36d 100644 --- a/src/main/orcad/orcad-session-scanner-idle.ts +++ b/src/main/orcad/host-runtime/orcad-session-scanner-idle.ts @@ -1,4 +1,4 @@ -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' /** WSL hosts hold a per-distro memory budget; a retire there costs the next scan ~1.5x on a big history. */ export const WSL_HOST_SESSION_SCANNER_IDLE_TIMEOUT_MS = 3 * 60_000 @@ -14,7 +14,7 @@ export async function applyOrcadSessionScannerIdleTimeout(): Promise { const timeoutMs = orcadSessionScannerIdleTimeoutMs() if (timeoutMs !== null) { const { setAiVaultServiceIdleTimeoutMs } = - await import('../ai-vault/scan-service/session-scanner-service-spawn') + await import('../../ai-vault/scan-service/session-scanner-service-spawn') setAiVaultServiceIdleTimeoutMs(timeoutMs) } } diff --git a/src/main/orcad/host-runtime/orcad-session-search.ts b/src/main/orcad/host-runtime/orcad-session-search.ts new file mode 100644 index 00000000000..f463806ca0b --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-session-search.ts @@ -0,0 +1,23 @@ +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' + +import { + type AiVaultSearchSettings, + resolveAiVaultSearchSettings +} from '../../../shared/ai-vault/search/ai-vault-search-settings' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { localAiVaultScanRoots } from '../../ai-vault/discovery/ai-vault-scan-roots' +import { installInProcessSessionSearchService } from '../../ai-vault-search/session-search-in-process-service' + +/** Index in-process as sole writer; the scanner child has no installed search data root. */ +export async function installOrcadSessionSearchService(args: { + userDataPath: string + getSettings: () => Pick +}): Promise<{ apply(settings: AiVaultSearchSettings): void; dispose(): void } | null> { + return installInProcessSessionSearchService({ + dataRoot: args.userDataPath, + roots: { executionHostId: LOCAL_EXECUTION_HOST_ID }, + resolveRoots: localAiVaultScanRoots, + settings: resolveAiVaultSearchSettings(args.getSettings()), + onError: (error) => console.error('[orcad] session search:', error) + }) +} diff --git a/src/main/orcad/host-runtime/orcad-speech-services.ts b/src/main/orcad/host-runtime/orcad-speech-services.ts new file mode 100644 index 00000000000..e51a29710d2 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-speech-services.ts @@ -0,0 +1,19 @@ +import { ModelManager } from '../../speech/model-manager' +import { openNodeSpeechDownloadRequest } from '../../speech/node-speech-download-request' +import { canReadCloudSpeechCredentials } from '../../speech/cloud-transcription-target' +import type { SpeechServiceFactories } from '../../speech/speech-runtime-service' +import { SttService } from '../../speech/stt-service' +import { createSttGpuPolicy } from '../../speech/stt-gpu-failure-marker' +import { spawnSttWorkerWithCpuFallback } from '../../speech/stt-worker-cpu-fallback' +import { spawnSttForkedProcess } from '../../speech/stt-worker-forked-process' + +// Local speech needs the installed app recognizer supplied by orca serve. +export const orcadSpeechServiceFactories: SpeechServiceFactories = { + createModelManager: (customModelsDir) => + // Headless key reads cannot open keychain prompts, so readiness may verify decryption. + new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadCloudSpeechCredentials), + createSttService: (models, gpuEnabled) => { + const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled) + return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttForkedProcess, gpu)) + } +} diff --git a/src/main/orcad/host-runtime/orcad-stats.ts b/src/main/orcad/host-runtime/orcad-stats.ts new file mode 100644 index 00000000000..c1938f98391 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-stats.ts @@ -0,0 +1,16 @@ +import { feedAgentSessionStats, type AgentStatusSource } from '../../stats/agent-session-stats-feed' +import { initStatsPath, StatsCollector } from '../../stats/collector' +import type { BackendServiceCleanup } from '../../backend/service-composition' + +export function startOrcadStats( + userDataPath: string, + hooks: AgentStatusSource, + registerCleanup: (cleanup: BackendServiceCleanup) => void +): StatsCollector { + initStatsPath(userDataPath) + const stats = new StatsCollector() + // Reverse cleanup order stops feeds/RPC before the final stats flush. + registerCleanup(() => stats.flushAsync()) + registerCleanup(feedAgentSessionStats(stats, hooks)) + return stats +} diff --git a/src/main/orcad/orcad-wsl-host-login-environment.ts b/src/main/orcad/host-runtime/orcad-wsl-host-login-environment.ts similarity index 90% rename from src/main/orcad/orcad-wsl-host-login-environment.ts rename to src/main/orcad/host-runtime/orcad-wsl-host-login-environment.ts index 670b2b75be8..9ca2e61c729 100644 --- a/src/main/orcad/orcad-wsl-host-login-environment.ts +++ b/src/main/orcad/host-runtime/orcad-wsl-host-login-environment.ts @@ -1,7 +1,7 @@ // WSL exec skips shell setup; hydrate login-shell credentials/proxies before git and daemon startup. -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import { PROBE_MARKER_ENV_VAR } from '../startup/hydrate-shell-path' -import { resolveLoginShellEnvironment } from '../startup/login-shell-environment' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import { PROBE_MARKER_ENV_VAR } from '../../startup/shell-environment/hydrate-shell-path' +import { resolveLoginShellEnvironment } from '../../startup/shell-environment/login-shell-environment' // Allowlist excludes GUI askpass (which could block) and PATH (which has separate drive filtering). const WSL_HOST_LOGIN_ENV_NAMES: readonly string[] = [ diff --git a/src/main/orcad/orcad-data-root-locality.ts b/src/main/orcad/instance-lock/orcad-data-root-locality.ts similarity index 100% rename from src/main/orcad/orcad-data-root-locality.ts rename to src/main/orcad/instance-lock/orcad-data-root-locality.ts diff --git a/src/main/orcad/orcad-data-root-privacy.ts b/src/main/orcad/instance-lock/orcad-data-root-privacy.ts similarity index 96% rename from src/main/orcad/orcad-data-root-privacy.ts rename to src/main/orcad/instance-lock/orcad-data-root-privacy.ts index f32688b0a59..412ad8544f1 100644 --- a/src/main/orcad/orcad-data-root-privacy.ts +++ b/src/main/orcad/instance-lock/orcad-data-root-privacy.ts @@ -1,6 +1,6 @@ import { chmodSync, statSync } from 'node:fs' import process from 'node:process' -import { restrictWindowsPathSync } from '../../shared/secure-storage/secure-path-windows-acl' +import { restrictWindowsPathSync } from '../../../shared/secure-storage/secure-path-windows-acl' type OrcadInstanceLockCode = | 'orcad_data_root_unusable' diff --git a/src/main/orcad/orcad-instance-lock-hold.ts b/src/main/orcad/instance-lock/orcad-instance-lock-hold.ts similarity index 98% rename from src/main/orcad/orcad-instance-lock-hold.ts rename to src/main/orcad/instance-lock/orcad-instance-lock-hold.ts index 31542c1703a..97574747cb5 100644 --- a/src/main/orcad/orcad-instance-lock-hold.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock-hold.ts @@ -7,7 +7,7 @@ import { parseOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock-record' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' export type OrcadInstanceLock = { readonly path: string diff --git a/src/main/orcad/orcad-instance-lock-reclaim.ts b/src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts similarity index 97% rename from src/main/orcad/orcad-instance-lock-reclaim.ts rename to src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts index e8444b6804a..0518327c2a1 100644 --- a/src/main/orcad/orcad-instance-lock-reclaim.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts @@ -13,8 +13,8 @@ import { import { basename, dirname, join } from 'node:path' import process from 'node:process' import { OrcadInstanceLockError } from './orcad-data-root-privacy' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' +import { hasErrorCode } from '../../daemon/endpoint/identity/daemon-process-inspection' export const MAX_ORCAD_LOCK_BYTES = 64 * 1024 // Serialize recovery so reclaimers cannot displace newly published live locks. diff --git a/src/main/orcad/orcad-instance-lock-record.ts b/src/main/orcad/instance-lock/orcad-instance-lock-record.ts similarity index 100% rename from src/main/orcad/orcad-instance-lock-record.ts rename to src/main/orcad/instance-lock/orcad-instance-lock-record.ts diff --git a/src/main/orcad/orcad-instance-lock.test.ts b/src/main/orcad/instance-lock/orcad-instance-lock.test.ts similarity index 99% rename from src/main/orcad/orcad-instance-lock.test.ts rename to src/main/orcad/instance-lock/orcad-instance-lock.test.ts index 4c3419d48b3..2991dde3c2f 100644 --- a/src/main/orcad/orcad-instance-lock.test.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock.test.ts @@ -16,10 +16,9 @@ import type * as NodeFs from 'node:fs' import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME, - readOrcadInstanceLockRecord, - type OrcadInstanceLockHooks, - type OrcadLockRecord + type OrcadInstanceLockHooks } from './orcad-instance-lock' +import { readOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock-record' import { OrcadInstanceLockError } from './orcad-data-root-privacy' // Inject a contender immediately after canonical-lock rename. diff --git a/src/main/orcad/orcad-instance-lock.ts b/src/main/orcad/instance-lock/orcad-instance-lock.ts similarity index 94% rename from src/main/orcad/orcad-instance-lock.ts rename to src/main/orcad/instance-lock/orcad-instance-lock.ts index 95ad6fbc0bc..fe56fc3dab6 100644 --- a/src/main/orcad/orcad-instance-lock.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock.ts @@ -18,12 +18,15 @@ import { OrcadInstanceLockError, type OrcadDataRootPrivacyHooks } from './orcad-data-root-privacy' -import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' +import { + hasErrorCode, + isProcessAlive +} from '../../daemon/endpoint/identity/daemon-process-inspection' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' import { orcadDataRootIsOnLocalDisk } from './orcad-data-root-locality' -import type { OrcadReclaimHintRuntime } from '../../shared/orcad-stale-lock-reclaim' -import { reclaimedUnexpectedExit } from './orcad-unexpected-exit' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' +import type { OrcadReclaimHintRuntime } from '../../../shared/orcad-stale-lock-reclaim' +import { reclaimedUnexpectedExit } from '../host-lifecycle/orcad-unexpected-exit' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' import { orcadLockHolderLocality, orcadLockHolderUnverifiableError @@ -47,13 +50,6 @@ import { } from './orcad-instance-lock-record' import { holdOrcadInstanceLock, type OrcadInstanceLock } from './orcad-instance-lock-hold' -export { - parseOrcadInstanceLockRecord, - readOrcadInstanceLockRecord, - type OrcadLockRecord -} from './orcad-instance-lock-record' -export type { OrcadInstanceLock } from './orcad-instance-lock-hold' - export const ORCAD_LOCK_FILE_NAME = 'orcad.lock' // Allow old torn writes time to complete before treating garbled records as abandoned. const GARBLED_LOCK_GRACE_MS = 10_000 diff --git a/src/main/orcad/orcad-lock-clone-machine.ts b/src/main/orcad/instance-lock/orcad-lock-clone-machine.ts similarity index 94% rename from src/main/orcad/orcad-lock-clone-machine.ts rename to src/main/orcad/instance-lock/orcad-lock-clone-machine.ts index 7926733665f..78951edcb93 100644 --- a/src/main/orcad/orcad-lock-clone-machine.ts +++ b/src/main/orcad/instance-lock/orcad-lock-clone-machine.ts @@ -1,9 +1,9 @@ // Images cloned with one /etc/machine-id look like one machine to every PID check (#32918). import { statSync } from 'node:fs' import process from 'node:process' -import { ORCA_MACHINE_NAME_ENV } from '../../shared/orcad-managed-launch-env' +import { ORCA_MACHINE_NAME_ENV } from '../../../shared/orcad-managed-launch-env' import type { OrcadPeerMachine } from './orcad-lock-holder-locality' -import { currentLinuxBootStartedAtMs } from '../persistence/profile-state/access/profile-state-access-identity' +import { currentLinuxBootStartedAtMs } from '../../persistence/profile-state/access/profile-state-access-identity' const CLONE_MACHINE_ID_HINT = 'Machines cloned from one image share /etc/machine-id, so Orca cannot tell them apart. If the Orca ' + diff --git a/src/main/orcad/orcad-lock-holder-locality.ts b/src/main/orcad/instance-lock/orcad-lock-holder-locality.ts similarity index 94% rename from src/main/orcad/orcad-lock-holder-locality.ts rename to src/main/orcad/instance-lock/orcad-lock-holder-locality.ts index dc5489b27be..33dcb62b2cd 100644 --- a/src/main/orcad/orcad-lock-holder-locality.ts +++ b/src/main/orcad/instance-lock/orcad-lock-holder-locality.ts @@ -1,12 +1,12 @@ import process from 'node:process' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' import { readOrcadProcessIncarnation } from './orcad-process-start-time' import { OrcadInstanceLockError } from './orcad-data-root-privacy' import { orcadCloneMachineHint, orcadPeerIsLiveCloneMachine } from './orcad-lock-clone-machine' import { orcadStaleLockReclaimCommand, type OrcadReclaimHintRuntime -} from '../../shared/orcad-stale-lock-reclaim' +} from '../../../shared/orcad-stale-lock-reclaim' /** Match machine identity, then legacy boot identity; identity-less records require local-only storage. */ export function orcadLockHolderLocality( diff --git a/src/main/orcad/orcad-process-start-time.test.ts b/src/main/orcad/instance-lock/orcad-process-start-time.test.ts similarity index 94% rename from src/main/orcad/orcad-process-start-time.test.ts rename to src/main/orcad/instance-lock/orcad-process-start-time.test.ts index 4eb2b6442e5..527b55de466 100644 --- a/src/main/orcad/orcad-process-start-time.test.ts +++ b/src/main/orcad/instance-lock/orcad-process-start-time.test.ts @@ -3,16 +3,16 @@ import { mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as DaemonProcessStartTime from '../daemon/endpoint/identity/daemon-process-start-time' +import type * as DaemonProcessStartTime from '../../daemon/endpoint/identity/daemon-process-start-time' const { readWindowsProcessCreationTime, getProcessStartedAtMs } = vi.hoisted(() => ({ readWindowsProcessCreationTime: vi.fn<(pid: number) => number | null>(), getProcessStartedAtMs: vi.fn<(pid: number) => number | null>() })) -vi.mock('../windows/windows-process-table', () => ({ +vi.mock('../../windows/windows-process-table', () => ({ readWindowsProcessCreationTime })) -vi.mock('../daemon/endpoint/identity/daemon-process-start-time', async (importOriginal) => ({ +vi.mock('../../daemon/endpoint/identity/daemon-process-start-time', async (importOriginal) => ({ ...(await importOriginal()), getProcessStartedAtMs })) diff --git a/src/main/orcad/orcad-process-start-time.ts b/src/main/orcad/instance-lock/orcad-process-start-time.ts similarity index 94% rename from src/main/orcad/orcad-process-start-time.ts rename to src/main/orcad/instance-lock/orcad-process-start-time.ts index 555ace95778..7b5159cd01f 100644 --- a/src/main/orcad/orcad-process-start-time.ts +++ b/src/main/orcad/instance-lock/orcad-process-start-time.ts @@ -1,12 +1,12 @@ // Linux ticks/boot ID avoid drifting wall time; Windows uses kernel creation time. Unknown never proves exit. import { readFileSync, statSync } from 'node:fs' -import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../../agent-hooks/installation/locking/managed-hook-owner-identity' import { getProcessStartedAtMs, START_TIME_TOLERANCE_MS, startTimesWithinTolerance -} from '../daemon/endpoint/identity/daemon-process-start-time' -import { readWindowsProcessCreationTime } from '../windows/windows-process-table' +} from '../../daemon/endpoint/identity/daemon-process-start-time' +import { readWindowsProcessCreationTime } from '../../windows/windows-process-table' export type OrcadProcessIncarnation = { linuxStartTicks: string; bootId: string } diff --git a/src/main/orcad/orcad-stale-lock-reclaim.test.ts b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts similarity index 97% rename from src/main/orcad/orcad-stale-lock-reclaim.test.ts rename to src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts index 060740df8e5..15aa04e2a9e 100644 --- a/src/main/orcad/orcad-stale-lock-reclaim.test.ts +++ b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts @@ -10,9 +10,10 @@ import { import { createServer, type Server } from 'node:net' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' -import type { OrcadLockRecord } from './orcad-instance-lock' -import { shortDaemonSocketDir } from '../daemon/endpoint/publication/daemon-socket-endpoint-path' +import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { readOrcadInstanceLockRecord } from './orcad-instance-lock-record' +import type { OrcadLockRecord } from './orcad-instance-lock-record' +import { shortDaemonSocketDir } from '../../daemon/endpoint/publication/daemon-socket-endpoint-path' import { probeOrcadEndpoint, reclaimStaleOrcadInstanceLock, diff --git a/src/main/orcad/orcad-stale-lock-reclaim.ts b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts similarity index 93% rename from src/main/orcad/orcad-stale-lock-reclaim.ts rename to src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts index 4ba94080ccb..2ed93b481f6 100644 --- a/src/main/orcad/orcad-stale-lock-reclaim.ts +++ b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts @@ -8,23 +8,22 @@ import process from 'node:process' import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME, - parseOrcadInstanceLockRecord, - type OrcadInstanceLockHooks, - type OrcadLockRecord + type OrcadInstanceLockHooks } from './orcad-instance-lock' +import { parseOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock-record' import { readBoundedLockFile } from './orcad-instance-lock-reclaim' import { orcadLockHolderLocality } from './orcad-lock-holder-locality' import { ORCAD_LOCK_FRESH_MS, orcadLockPeer, orcadLockSelf } from './orcad-lock-clone-machine' import { orcadDataRootIsOnLocalDisk } from './orcad-data-root-locality' import { readOrcadProcessIncarnation } from './orcad-process-start-time' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' -import { resolveUserDataPath } from './orcad-app-paths' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' -import { readRuntimeMetadata } from '../runtime/rpc/server/runtime-metadata' +import { hasErrorCode } from '../../daemon/endpoint/identity/daemon-process-inspection' +import { resolveUserDataPath } from '../host-runtime/orcad-app-paths' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' +import { readRuntimeMetadata } from '../../runtime/rpc/server/runtime-metadata' import { RUNTIME_SOCKET_NAME_REGEX, runtimeSocketDirs -} from '../runtime/rpc/server/runtime-rpc-socket-metadata' +} from '../../runtime/rpc/server/runtime-rpc-socket-metadata' import { ORCAD_RECLAIM_STALE_LOCK_FLAG, ORCAD_STALE_LOCK_DATA_ROOT_FLAG, @@ -33,10 +32,8 @@ import { type OrcadReclaimHintRuntime, type OrcadStaleLockEvidence, type OrcadStaleLockReclaimStatus -} from '../../shared/orcad-stale-lock-reclaim' +} from '../../../shared/orcad-stale-lock-reclaim' -// A new holder may not listen yet, and NFS attribute caching can age a live heartbeat this much. -export const ORCAD_STALE_LOCK_MIN_AGE_MS = ORCAD_LOCK_FRESH_MS const ENDPOINT_PROBE_TIMEOUT_MS = 1_500 /** Silent requires OS-confirmed absence of a listener; errors leave ownership unknown. */ @@ -177,8 +174,8 @@ async function checkStaleLock( } const now = (hooks.now ?? Date.now)() const writtenMs = Math.max(Date.parse(holder.acquiredAt), statOrNull(lockPath)?.mtimeMs ?? now) - if (!(now - writtenMs >= ORCAD_STALE_LOCK_MIN_AGE_MS)) { - return { refusal: `The lock is less than ${ORCAD_STALE_LOCK_MIN_AGE_MS / 60_000} minutes old.` } + if (!(now - writtenMs >= ORCAD_LOCK_FRESH_MS)) { + return { refusal: `The lock is less than ${ORCAD_LOCK_FRESH_MS / 60_000} minutes old.` } } const endpoints = await holderEndpoints(dataRoot, holder.pid) if (!endpoints) { diff --git a/src/main/orcad/orcad-wsl-holder-release.ts b/src/main/orcad/instance-lock/orcad-wsl-holder-release.ts similarity index 82% rename from src/main/orcad/orcad-wsl-holder-release.ts rename to src/main/orcad/instance-lock/orcad-wsl-holder-release.ts index 942c21abf82..2a348888168 100644 --- a/src/main/orcad/orcad-wsl-holder-release.ts +++ b/src/main/orcad/instance-lock/orcad-wsl-holder-release.ts @@ -4,10 +4,10 @@ */ import { rmSync } from 'node:fs' import { join } from 'node:path' -import { ORCAD_WSL_HOLDER_RELEASE_FILENAME } from '../../shared/orcad-idle-exit' -import { writeSecureFile } from '../../shared/secure-storage/secure-file' -import { ORCAD_WSL_HOST_ENV } from '../ipc/wsl-guest-windows-drive-path' -import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' +import { ORCAD_WSL_HOLDER_RELEASE_FILENAME } from '../../../shared/orcad-idle-exit' +import { writeSecureFile } from '../../../shared/secure-storage/secure-file' +import { ORCAD_WSL_HOST_ENV } from '../../../shared/orcad-server-launch-env' +import type { OrcadDaemonRetirement } from '../daemon/orcad-daemon-retirement' export function orcadWslHolderReleasePath(userDataPath: string): string { return join(userDataPath, ORCAD_WSL_HOLDER_RELEASE_FILENAME) diff --git a/src/main/orcad/launcher.ts b/src/main/orcad/launcher.ts index bb956c00737..031142e16db 100644 --- a/src/main/orcad/launcher.ts +++ b/src/main/orcad/launcher.ts @@ -3,9 +3,12 @@ import { readFileSync, realpathSync } from 'node:fs' import { createRequire } from 'node:module' import { dirname, join } from 'node:path' import { ORCAD_SERVER_ENTRY_FILENAME } from '../../shared/orcad-artifacts' -import { assertOrcadServerRuntime, handoffToBundledOrcad } from './orcad-bundled-runtime' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { enableManagedOrcadCompileCache } from './orcad-compile-cache' +import { + assertOrcadServerRuntime, + handoffToBundledOrcad +} from './runtime-launch/orcad-bundled-runtime' +import { ORCAD_EXIT_CONFIGURATION } from './serve-startup/orcad-configuration-exit' +import { enableManagedOrcadCompileCache } from './runtime-launch/orcad-compile-cache' declare const ORCAD_SERVER_SHA256: string diff --git a/src/main/orcad/main.ts b/src/main/orcad/main.ts index 4f64317bcb7..5a81c8ed71f 100644 --- a/src/main/orcad/main.ts +++ b/src/main/orcad/main.ts @@ -1,22 +1,22 @@ import '../memory/host-malloc-tunables-claim' import process from 'node:process' -import { main } from './orcad-command-startup' -import { resolveOrcadExitCode } from './orcad-exit-code' +import { main } from './serve-startup/orcad-command-startup' +import { resolveOrcadExitCode } from './serve-startup/orcad-exit-code' import { reserveServeStdoutForReadiness } from '../server/serve-stdout-boundary' -import { runOrcadNativePreflightVerdict } from './orcad-native-preflight' +import { runOrcadNativePreflightVerdict } from './native-runtime/orcad-native-preflight' import { ORCAD_PROFILE_PREFLIGHT_FLAG, ORCAD_STARTUP_PREFLIGHT_FLAG } from '../../shared/orcad-profile-preflight' -import { onNodePtyLoadFailure } from '../providers/node-pty-load-failure' +import { onNodePtyLoadFailure } from '../providers/pty/node-pty-load-failure' import { confirmBundledOrcadStartupQualified, discardBundledOrcadStartupQualification, forgetBundledOrcadStartupQualification, preflightBundledOrcadStartup, runOrcadProfilePreflight -} from './orcad-profile-preflight' -import { assertOrcadServerRuntime } from './orcad-bundled-runtime' +} from './runtime-launch/orcad-profile-preflight' +import { assertOrcadServerRuntime } from './runtime-launch/orcad-bundled-runtime' import { formatOrcadNativePreflightReport, ORCAD_NATIVE_PREFLIGHT_FLAG @@ -30,7 +30,7 @@ import { WINDOWS_BREAKAWAY_LAUNCH_FLAG } from '../../shared/windows-breakaway-launch' import { runWindowsBreakawayLaunchIfRequested } from '../../shared/windows-breakaway-launcher' -import { parseArgs } from './orcad-command-arguments' +import { parseArgs } from './serve-startup/orcad-command-arguments' import { ORCAD_RECLAIM_STALE_LOCK_FLAG } from '../../shared/orcad-stale-lock-reclaim' // A resolved plain-Node module graph proves the build guard; skip probes, ports and data-root locks. @@ -46,7 +46,7 @@ function failStartup(error: unknown): void { // One-shot launch and stop commands must skip server startup and preflights. if (process.argv[2] === '--orcad-structured-provider-load-check') { - void import('./orcad-structured-provider-smoke') + void import('./native-runtime/orcad-structured-provider-smoke') .then(({ smokeLoadOrcadStructuredProviders }) => smokeLoadOrcadStructuredProviders()) .then(() => process.exit(0)) .catch(failStartup) @@ -56,12 +56,14 @@ if (process.argv[2] === '--orcad-structured-provider-load-check') { process.argv[2] === ORCAD_COMPLETE_MANAGED_STOP_FLAG || process.argv[2] === ORCAD_CANCEL_MANAGED_STOP_FLAG ) { - void import('./orcad-managed-stop-command').then(({ runOrcadManagedStopCommandAndExit }) => - runOrcadManagedStopCommandAndExit(process.argv.slice(2)) + void import('./host-lifecycle/managed-stop/orcad-managed-stop-command').then( + ({ runOrcadManagedStopCommandAndExit }) => + runOrcadManagedStopCommandAndExit(process.argv.slice(2)) ) } else if (process.argv[2] === ORCAD_RECLAIM_STALE_LOCK_FLAG) { - void import('./orcad-stale-lock-reclaim').then(({ runOrcadStaleLockReclaimCommandAndExit }) => - runOrcadStaleLockReclaimCommandAndExit(process.argv.slice(2)) + void import('./instance-lock/orcad-stale-lock-reclaim').then( + ({ runOrcadStaleLockReclaimCommandAndExit }) => + runOrcadStaleLockReclaimCommandAndExit(process.argv.slice(2)) ) } else { startOrcadProcess() @@ -77,7 +79,7 @@ function startOrcadProcess(): void { assertOrcadServerRuntime() const flag = process.argv[2] if (flag === ORCAD_NATIVE_PREFLIGHT_FLAG && process.argv.length === 3) { - void import('./node-pty-precondition').then(({ checkNodePtyPrecondition }) => { + void import('./native-runtime/node-pty-precondition').then(({ checkNodePtyPrecondition }) => { const verdict = checkNodePtyPrecondition() const report = formatOrcadNativePreflightReport(verdict.status, verdict.reason ?? null) process.stdout.write(`${report}\n`, () => process.exit(0)) diff --git a/src/main/orcad/orcad-migration-destination-capabilities.ts b/src/main/orcad/migration/orcad-migration-destination-capabilities.ts similarity index 85% rename from src/main/orcad/orcad-migration-destination-capabilities.ts rename to src/main/orcad/migration/orcad-migration-destination-capabilities.ts index dd10fd3a2ef..0ab1583679d 100644 --- a/src/main/orcad/orcad-migration-destination-capabilities.ts +++ b/src/main/orcad/migration/orcad-migration-destination-capabilities.ts @@ -1,5 +1,5 @@ -import { advertisedOrcadMigrationBlobCapabilities } from '../../shared/orcad-migration/orcad-migration-blob-transfer' -import { SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY } from '../../shared/session-tabs-runtime-capabilities' +import { advertisedOrcadMigrationBlobCapabilities } from '../../../shared/orcad-migration/orcad-migration-blob-transfer' +import { SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY } from '../../../shared/session-tabs-runtime-capabilities' import { servesWslMovedPaneHistory } from './orcad-migration-wsl-destination' /** diff --git a/src/main/orcad/orcad-migration-manifest-digest.ts b/src/main/orcad/migration/orcad-migration-manifest-digest.ts similarity index 94% rename from src/main/orcad/orcad-migration-manifest-digest.ts rename to src/main/orcad/migration/orcad-migration-manifest-digest.ts index 810dc4aa8f3..410dcd0fc6e 100644 --- a/src/main/orcad/orcad-migration-manifest-digest.ts +++ b/src/main/orcad/migration/orcad-migration-manifest-digest.ts @@ -3,7 +3,7 @@ import { orcadMigrationManifestHashInput, serializeOrcadMigrationValue, type OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' +} from '../../../shared/orcad-migration/orcad-migration-manifest' export function computeOrcadMigrationManifestSha256( manifest: Omit diff --git a/src/main/orcad/orcad-migration-wsl-destination.ts b/src/main/orcad/migration/orcad-migration-wsl-destination.ts similarity index 81% rename from src/main/orcad/orcad-migration-wsl-destination.ts rename to src/main/orcad/migration/orcad-migration-wsl-destination.ts index 1982c6392e4..16faa2b9f91 100644 --- a/src/main/orcad/orcad-migration-wsl-destination.ts +++ b/src/main/orcad/migration/orcad-migration-wsl-destination.ts @@ -1,13 +1,11 @@ // In-place WSL moves require the desktop-launched orcad in the source distro to own the unchanged paths. -import type { OrcadMigrationManifestSource } from '../../shared/orcad-migration/orcad-migration-manifest' -import { isOrcadMigrationLocalWslSource } from '../../shared/orcad-migration/orcad-migration-source-kind' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import { ORCAD_WSL_DISTRO_GUID_ENV } from '../../shared/orcad-server-launch-env' +import type { OrcadMigrationManifestSource } from '../../../shared/orcad-migration/orcad-migration-manifest' +import { isOrcadMigrationLocalWslSource } from '../../../shared/orcad-migration/orcad-migration-source-kind' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import { ORCAD_WSL_DISTRO_GUID_ENV } from '../../../shared/orcad-server-launch-env' export const ORCAD_MIGRATION_SOURCE_NOT_THIS_HOST = 'orcad_migration_source_not_this_host' -export { ORCAD_WSL_DISTRO_GUID_ENV } - export function servesLocalWslMigrationSource( env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform diff --git a/src/main/orcad/build-toolchain-diagnosis.ts b/src/main/orcad/native-runtime/build-toolchain-diagnosis.ts similarity index 100% rename from src/main/orcad/build-toolchain-diagnosis.ts rename to src/main/orcad/native-runtime/build-toolchain-diagnosis.ts diff --git a/src/main/orcad/native-host-abi.ts b/src/main/orcad/native-runtime/native-host-abi.ts similarity index 100% rename from src/main/orcad/native-host-abi.ts rename to src/main/orcad/native-runtime/native-host-abi.ts diff --git a/src/main/orcad/node-pty-loader-diagnosis.ts b/src/main/orcad/native-runtime/node-pty-loader-diagnosis.ts similarity index 95% rename from src/main/orcad/node-pty-loader-diagnosis.ts rename to src/main/orcad/native-runtime/node-pty-loader-diagnosis.ts index 3d48db58b9e..982fbf3bad8 100644 --- a/src/main/orcad/node-pty-loader-diagnosis.ts +++ b/src/main/orcad/native-runtime/node-pty-loader-diagnosis.ts @@ -1,4 +1,4 @@ -import type { RuntimeTerminalUnavailableReason } from '../../shared/runtime-types' +import type { RuntimeTerminalUnavailableReason } from '../../../shared/runtime-capability-degradation' import { parseIncompatibleArchitecture, parseMissingSharedLibrary, diff --git a/src/main/orcad/node-pty-prebuilt-slot.test.ts b/src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts similarity index 100% rename from src/main/orcad/node-pty-prebuilt-slot.test.ts rename to src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts diff --git a/src/main/orcad/node-pty-prebuilt-slot.ts b/src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts similarity index 98% rename from src/main/orcad/node-pty-prebuilt-slot.ts rename to src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts index 44a3ee55744..d5059bbea5a 100644 --- a/src/main/orcad/node-pty-prebuilt-slot.ts +++ b/src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts @@ -5,8 +5,8 @@ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync } from 'no import { dirname, join } from 'node:path' import process from 'node:process' import { z } from 'zod' -import { usesNodePtySpawnHelper } from '../../shared/node-pty-spawn-helper' -import { COMPAT_SERVER_TARGET_BASES, COMPAT_SERVER_TARGETS } from '../../shared/node-runtime-pin' +import { usesNodePtySpawnHelper } from '../../../shared/node-pty-spawn-helper' +import { COMPAT_SERVER_TARGET_BASES, COMPAT_SERVER_TARGETS } from '../../../shared/node-runtime-pin' import { compareDottedVersions, hostNodeApiVersion, diff --git a/src/main/orcad/node-pty-precondition.test.ts b/src/main/orcad/native-runtime/node-pty-precondition.test.ts similarity index 100% rename from src/main/orcad/node-pty-precondition.test.ts rename to src/main/orcad/native-runtime/node-pty-precondition.test.ts diff --git a/src/main/orcad/node-pty-precondition.ts b/src/main/orcad/native-runtime/node-pty-precondition.ts similarity index 98% rename from src/main/orcad/node-pty-precondition.ts rename to src/main/orcad/native-runtime/node-pty-precondition.ts index 8dda5bdaba0..6c85c88e4a5 100644 --- a/src/main/orcad/node-pty-precondition.ts +++ b/src/main/orcad/native-runtime/node-pty-precondition.ts @@ -4,8 +4,8 @@ import { dirname, join } from 'node:path' import process from 'node:process' import { runProcessSync } from '@orca/process-host' import type { ProcessResult } from '@orca/process-host/process-spec' -import { usesNodePtySpawnHelper } from '../../shared/node-pty-spawn-helper' -import type { RuntimeTerminalUnavailableReason } from '../../shared/runtime-types' +import { usesNodePtySpawnHelper } from '../../../shared/node-pty-spawn-helper' +import type { RuntimeTerminalUnavailableReason } from '../../../shared/runtime-capability-degradation' import { buildToolchainProbeCommand, parseBuildToolchainProbe, diff --git a/src/main/orcad/orcad-bundle-native-load-order.test.ts b/src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts similarity index 97% rename from src/main/orcad/orcad-bundle-native-load-order.test.ts rename to src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts index 985a8e5dd0e..8705205a2d3 100644 --- a/src/main/orcad/orcad-bundle-native-load-order.test.ts +++ b/src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts @@ -5,7 +5,7 @@ import { pathToFileURL } from 'node:url' import { afterEach, expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' -const REPO_ROOT = join(__dirname, '..', '..', '..') +const REPO_ROOT = join(__dirname, '..', '..', '..', '..') const directories: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-native-preflight.ts b/src/main/orcad/native-runtime/orcad-native-preflight.ts similarity index 90% rename from src/main/orcad/orcad-native-preflight.ts rename to src/main/orcad/native-runtime/orcad-native-preflight.ts index fb991b1a5de..495fbef62c7 100644 --- a/src/main/orcad/orcad-native-preflight.ts +++ b/src/main/orcad/native-runtime/orcad-native-preflight.ts @@ -1,13 +1,13 @@ import process from 'node:process' -import { setRuntimeTerminalUnavailableCause } from '../runtime/terminal/launch/native-terminal-availability' -import { terminalUnavailableMessage } from '../../shared/runtime-types' +import { setRuntimeTerminalUnavailableCause } from '../../runtime/terminal/launch/native-terminal-availability' +import { terminalUnavailableMessage } from '../../../shared/runtime-capability-degradation' import { checkNodePtyPrecondition, formatNodePtyPreconditionReport, probeLocalBuildToolchainHints, type NodePtyPreconditionVerdict } from './node-pty-precondition' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' +import { ORCAD_EXIT_CONFIGURATION } from '../serve-startup/orcad-configuration-exit' type NativePreflightHooks = { /** The slot's last launch on this unchanged host passed this probe (startup qualification). */ diff --git a/src/main/orcad/orcad-packaged-node-pty.integration.test.ts b/src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts similarity index 82% rename from src/main/orcad/orcad-packaged-node-pty.integration.test.ts rename to src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts index c0c33c9f032..62c67deedd8 100644 --- a/src/main/orcad/orcad-packaged-node-pty.integration.test.ts +++ b/src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts @@ -5,10 +5,12 @@ import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { NODE_RUNTIME_PIN } from '../../shared/node-runtime-pin' -import { ORCAD_NODE_PTY_DIR } from '../../shared/orcad-artifacts' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { locatePinnedNodeForTests, skipForMissingInputs } from './orcad-node-slot-fixture' +import { ORCAD_NODE_PTY_DIR } from '../../../shared/orcad-artifacts' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' +import { + locatePinnedNodeForTests, + skipForMissingInputs +} from '../testing/native-slots/orcad-node-slot-fixture' const packageDir = resolve('out/orcad') const pinnedNode = locatePinnedNodeForTests() @@ -19,7 +21,7 @@ const skip = skipForMissingInputs('artifact', [ ]) describe.skipIf(skip)('packaged node-pty under the pinned Node', () => { - it('spawns, reattaches, delivers data and retires a shell from the shipped slot only', async () => { + it('spawns a shell and delivers its output and exit from the shipped slot only', async () => { const directory = await mkdtemp(join(tmpdir(), 'orca-packaged-node-pty-')) try { const entry = join(directory, 'local-pty.cjs') @@ -49,16 +51,13 @@ describe.skipIf(skip)('packaged node-pty under the pinned Node', () => { sessionId: 'packaged-node-pty', cols: 80, rows: 24, cwd: process.cwd(), shellOverride: process.platform === 'win32' ? getCmdExePath() : '/bin/sh' }) - const again = await provider.spawn({ sessionId: first.id, cols: 100, rows: 30 }) provider.write(first.id, process.platform === 'win32' ? 'echo ORCA_PACKAGED_PTY_READY & exit 17\\r' : 'printf ORCA_PACKAGED_PTY_READY; exit 17\\r') const code = await exit clearTimeout(deadline) console.log(JSON.stringify({ - version: process.versions.node, code, output: output.includes('ORCA_PACKAGED_PTY_READY'), - reattached: again.isReattach === true && again.pid === first.pid, - retired: provider.getPtyProcess(first.id) === undefined + code, output: output.includes('ORCA_PACKAGED_PTY_READY') })) })().catch(error => { clearTimeout(deadline); provider.killAll(); console.error(error); process.exitCode = 1 }) `, @@ -88,11 +87,8 @@ describe.skipIf(skip)('packaged node-pty under the pinned Node', () => { }) expect(result.code, result.stderr).toBe(0) expect(JSON.parse(result.stdout)).toEqual({ - version: NODE_RUNTIME_PIN.version, code: 17, - output: true, - reattached: true, - retired: true + output: true }) } finally { // Remove the junction before recursively deleting the test root. diff --git a/src/main/orcad/orcad-runtime-native-preflight.ts b/src/main/orcad/native-runtime/orcad-runtime-native-preflight.ts similarity index 88% rename from src/main/orcad/orcad-runtime-native-preflight.ts rename to src/main/orcad/native-runtime/orcad-runtime-native-preflight.ts index 7e2c972c4c0..5b99f08f50a 100644 --- a/src/main/orcad/orcad-runtime-native-preflight.ts +++ b/src/main/orcad/native-runtime/orcad-runtime-native-preflight.ts @@ -5,17 +5,17 @@ import { PtySpawnHealthTimeoutError, PTY_SPAWN_HEALTH_TIMEOUT_MS, runPtySpawnHealthProbe -} from '../daemon/pty-subprocess/spawn-preflight' -import { WatcherProcessSupervisor } from '../ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor' -import { resolveWatcherProcessEntryPath } from '../ipc/filesystem/watcher-process/parcel-watcher-entry-path' -import { resolveOrcadInstallRoot } from './orcad-app-paths' +} from '../../daemon/pty-subprocess/spawn-preflight' +import { WatcherProcessSupervisor } from '../../ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor' +import { resolveWatcherProcessEntryPath } from '../../ipc/filesystem/watcher-process/parcel-watcher-entry-path' +import { resolveOrcadInstallRoot } from '../host-runtime/orcad-app-paths' import { isWindowsProcessTableAvailable, isWindowsProcessStartTimeAvailable, readWindowsProcessCreationTime, readWindowsProcessIdentityTableFresh -} from '../windows/windows-process-table' -import { WindowsProcessTableTimeoutError } from '../windows/windows-process-table-timeout-error' +} from '../../windows/windows-process-table' +import { WindowsProcessTableTimeoutError } from '../../windows/windows-process-table-timeout-error' // Antivirus and cold arm64 conpty startup can exceed the steady-state budget. const WINDOWS_FIRST_PTY_PROBE_TIMEOUT_MS = 15_000 diff --git a/src/main/orcad/orcad-structured-provider-smoke.ts b/src/main/orcad/native-runtime/orcad-structured-provider-smoke.ts similarity index 84% rename from src/main/orcad/orcad-structured-provider-smoke.ts rename to src/main/orcad/native-runtime/orcad-structured-provider-smoke.ts index ac4177e2363..95166d7b835 100644 --- a/src/main/orcad/orcad-structured-provider-smoke.ts +++ b/src/main/orcad/native-runtime/orcad-structured-provider-smoke.ts @@ -1,4 +1,4 @@ -import { openClaudeStreamJsonConnection } from '../claude/claude-stream-json-connection' +import { openClaudeStreamJsonConnection } from '../../claude/claude-stream-json-connection' export async function smokeLoadOrcadStructuredProviders(): Promise { const loaded = new Error('structured provider module loaded') diff --git a/src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts b/src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts similarity index 95% rename from src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts rename to src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts index 4c0791ea20d..26fee48dff1 100644 --- a/src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts +++ b/src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts @@ -8,13 +8,13 @@ import { quoteWindowsArgument } from '@orca/process-host/windows-command-line' import { ORCAD_NODE_PTY_DIR, ORCAD_WINDOWS_PROCESS_TREE_FILENAME -} from '../../shared/orcad-artifacts' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +} from '../../../shared/orcad-artifacts' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' import { installPackagedOrcadSlotForTests, locatePinnedNodeForTests, skipForMissingInputs -} from './orcad-node-slot-fixture' +} from '../testing/native-slots/orcad-node-slot-fixture' const pinnedNode = locatePinnedNodeForTests() const windows = process.platform === 'win32' diff --git a/src/main/orcad/orcad-agent-session-claim-signer.test.ts b/src/main/orcad/orcad-agent-session-claim-signer.test.ts deleted file mode 100644 index dc88854333f..00000000000 --- a/src/main/orcad/orcad-agent-session-claim-signer.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { ClaimedAgentPtyOwnerRegistry } from '../../shared/claimed-agent-pty-owner' -import { - canonicalizeAgentSessionIdentity, - loadAgentSessionClaimSigner, - type AgentSessionClaimSigner -} from '../runtime/agent-session/ownership/agent-session-claim-identity' - -const namespace = { machine: 'm', principal: 'u', container: 'native', providerRoot: 'default' } -const identity = canonicalizeAgentSessionIdentity('claude', { key: 'session_id', id: 'conv-1' }) -const surface = { - worktreeId: 'worktree', - tabId: 'tab', - leafId: '12345678-1234-4234-8234-123456789abc', - terminalHandle: 'term_handle' -} - -async function ensureFrom( - daemonOwners: ClaimedAgentPtyOwnerRegistry, - signer: AgentSessionClaimSigner, - ptyId: string -) { - return await daemonOwners.ensure({ - claim: signer.createClaim({ namespace, identity, canonicalWorktreeId: 'worktree' }), - surface, - spawn: async () => ({ ptyId }), - isLive: () => true - }) -} - -describe('orcad agent-session claim signer', () => { - it('adopts the live PTY after an orcad restart instead of starting a second writer', async () => { - const userData = mkdtempSync(join(tmpdir(), 'orcad-claim-signer-')) - try { - const daemonOwners = new ClaimedAgentPtyOwnerRegistry() - const first = await ensureFrom( - daemonOwners, - loadAgentSessionClaimSigner(userData, userData), - 'pty-1' - ) - const restarted = await ensureFrom( - daemonOwners, - loadAgentSessionClaimSigner(userData, userData), - 'pty-2' - ) - expect(first.disposition).toBe('created') - expect(restarted).toMatchObject({ disposition: 'adopted', owner: { ptyId: 'pty-1' } }) - } finally { - rmSync(userData, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/orcad/orcad-automations.ts b/src/main/orcad/orcad-automations.ts deleted file mode 100644 index bac55aea8dc..00000000000 --- a/src/main/orcad/orcad-automations.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { createRuntimeAutomationService } from '../automations/runtime-automation-service' -import { isFinalAutomationRunStatus } from '../../shared/automations/history/automation-run' - -type AutomationStore = Pick - -let stopScheduler: (() => void) | null = null - -export function startOrcadAutomations( - runtime: OrcaRuntimeService, - store: Store, - registerCleanup: (cleanup: () => void) => void -): void { - const service = createRuntimeAutomationService({ - store, - runtime, - allowRemoteHostScheduling: true - }) - stopScheduler = () => service.stop() - // Stop before final profile flush so runs cannot persist afterward. - registerCleanup(() => service.stop()) - service.start() -} - -export function stopOrcadAutomationScheduler(): void { - stopScheduler?.() -} - -/** Pending schedules/runs must keep the host alive. */ -export function orcadAutomationsKeepHostBusy(store: AutomationStore): boolean { - return ( - store.listAutomations().some((automation) => automation.enabled) || - store.listAutomationRuns().some((run) => !isFinalAutomationRunStatus(run.status)) - ) -} diff --git a/src/main/orcad/orcad-browser-install-park.test.ts b/src/main/orcad/orcad-browser-install-park.test.ts deleted file mode 100644 index c7c7aad0c94..00000000000 --- a/src/main/orcad/orcad-browser-install-park.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { setImmediate as flush } from 'node:timers/promises' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { ORCAD_BROWSER_PARK_LABEL } from '../../shared/serve-bundle-coordination' -import { openServeBundlePark } from '../../shared/serve-bundle-park' -import { - commitServeSupervisorPark, - parkServeSupervisorsForInstall, - releaseServeSupervisorPark -} from '../updater/lifecycle/serve-supervisor-install-park' -import { watchOrcadBrowserInstallPark } from './orcad-browser-install-park' - -const HELPER = 424242 - -describe('orcad browser helper in the desktop install park', () => { - let root: string - let bundle: string - let executable: string - let tick: () => void - let running: boolean - let starts: AbortSignal[] - let failStarts: number - let hangStarts: boolean - let clock: number - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orcad-browser-park-')) - bundle = join(root, 'Orca.app') - executable = join(bundle, 'Contents', 'MacOS', 'Orca') - await mkdir(join(bundle, 'Contents', 'MacOS'), { recursive: true }) - await writeFile(executable, '') - await writeFile(join(bundle, 'Contents', 'Info.plist'), 'v1') - tick = () => undefined - running = true - starts = [] - failStarts = 0 - hangStarts = false - clock = 1_000 - }) - - afterEach(async () => { - await releaseServeSupervisorPark() - await rm(root, { recursive: true, force: true }) - }) - - function watch() { - const park = openServeBundlePark({ - executable, - label: ORCAD_BROWSER_PARK_LABEL, - platform: 'darwin', - env: {}, - userDataRoot: join(root, 'data') - }) - expect(park).not.toBeNull() - return watchOrcadBrowserInstallPark( - { - pid: () => (running ? HELPER : null), - stop: async () => { - running = false - }, - start: async (signal) => { - starts.push(signal) - if (hangStarts) { - running = true - await new Promise((_resolve, reject) => - signal.addEventListener('abort', () => reject(new Error('aborted'))) - ) - } - if (failStarts > 0) { - failStarts-- - throw new Error('helper did not become ready') - } - running = true - } - }, - { - park: park!, - now: () => clock, - log: () => undefined, - setRepeating: (callback) => { - tick = callback - return () => { - tick = () => undefined - } - } - } - ) - } - - async function step(): Promise { - tick() - await flush() - await flush() - } - - const installerDeps = () => ({ - macUserDataRoot: join(root, 'data'), - listBlockers: async () => (running ? [HELPER] : []), - sleep: step - }) - - it('stops the helper for an install and starts it again from the replaced bundle', async () => { - const parkWatch = watch() - await expect( - parkServeSupervisorsForInstall(executable, [HELPER], installerDeps()) - ).resolves.toEqual({ kind: 'parked' }) - expect(running).toBe(false) - - await commitServeSupervisorPark(async () => (running ? [HELPER] : [])) - await step() - expect(running).toBe(false) - - await rm(join(bundle, 'Contents', 'Info.plist')) - await step() - expect(starts).toHaveLength(0) - - await writeFile(join(bundle, 'Contents', 'Info.plist'), 'v2-new-bundle') - await step() - expect(running).toBe(true) - expect(starts).toHaveLength(1) - await parkWatch.close() - }) - - it('gives up a slow restart so a new install can still park the helper', async () => { - const parkWatch = watch() - await parkServeSupervisorsForInstall(executable, [HELPER], installerDeps()) - await releaseServeSupervisorPark() - hangStarts = true - await step() - await step() - expect(starts).toHaveLength(1) - await expect( - parkServeSupervisorsForInstall(executable, [HELPER], installerDeps()) - ).resolves.toEqual({ kind: 'parked' }) - expect(starts[0]?.aborted).toBe(true) - await parkWatch.close() - }) -}) diff --git a/src/main/orcad/orcad-chat-restart-offer.test.ts b/src/main/orcad/orcad-chat-restart-offer.test.ts deleted file mode 100644 index 724bdf310f6..00000000000 --- a/src/main/orcad/orcad-chat-restart-offer.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' -import { - CALLER, - hostTestState -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' -import { - HOST_TEST_THREAD as THREAD, - HOST_TEST_NOW as NOW, - hostTestAttachParams, - hostTestOperationId -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import { AgentSessionRecoveryCapsule } from '../runtime/agent-session/records/agent-session-recovery-capsule' -import { startOrcadWithLifecycle, stopOrcadStructuredAgentSessions } from './orcad-lifecycle' - -vi.mock('../runtime/agent-session/structured-agent-session-runtime', () => ({ - stopStructuredAgentSessionRuntime: async (options: { trigger: 'quit' }) => { - await hostTestState().host.flushAllStreamedEvents(options) - } -})) - -afterEach(() => vi.restoreAllMocks()) - -it.each([10, 100])( - 'batches %i working chats into durable offers before the profile closes', - async (size) => { - const { host, acquire, root } = hostTestState() - const ids = Array.from({ length: size }, (_, i) => `session-${i}`) - for (const sessionId of ids) { - const params = hostTestAttachParams(null, { - envelope: { - sessionId, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: null, - payloadFingerprint: '' - } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - const events = acquire.mock.calls.at(-1)?.[0].events - if (!events) { - throw new Error('missing provider event sink') - } - events.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'working', ordinal: 1 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await host.flushStreamedEvents(sessionId) - } - const close = vi.fn(async () => true) - host.deps.adapter.closeSession = close - const record = vi.spyOn(AgentSessionRecoveryCapsule.prototype, 'record') - const getRecord = vi.spyOn(host.deps.store, 'getRecord') - const server = await startOrcadWithLifecycle( - async (register) => { - register(async () => { - expect(close.mock.calls).toEqual(ids.map((id) => [id, undefined])) - expect(record).toHaveBeenCalledTimes(1) - expect(record.mock.calls[0]?.[0]).toHaveLength(size) - expect( - (await new AgentSessionRecoveryCapsule(root).list(NOW)).map((row) => row.sessionId) - ).toEqual(ids) - }) - register(stopOrcadStructuredAgentSessions) - return {} - }, - async () => {} - ) - await server.stop() - // Witness, lease and status passes are per session; no inventory scan for each child. - expect(getRecord.mock.calls.length).toBeLessThanOrEqual(32 * size) - const reads = getRecord.mock.calls.length - await server.stop() - expect(getRecord).toHaveBeenCalledTimes(reads) - expect(close).toHaveBeenCalledTimes(size) - expect(record).toHaveBeenCalledTimes(1) - record.mockRestore() - getRecord.mockRestore() - expect(await host.restartResume.list()).toMatchObject( - ids.map((sessionId) => ({ sessionId, trigger: 'quit' })) - ) - } -) diff --git a/src/main/orcad/orcad-codex-account-homes.ts b/src/main/orcad/orcad-codex-account-homes.ts deleted file mode 100644 index e3d6ba5da97..00000000000 --- a/src/main/orcad/orcad-codex-account-homes.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { - listGuestCodexAccountHomes, - resolveGuestCodexAccountHome -} from '../codex-accounts/guest-codex-account-homes' -import { reconcileCodexAccountHomeHook } from '../codex/hooks/reconciliation/codex-account-home-hook' -import { stopCodexStateDbBackfillRecoveries } from '../codex/history/index/codex-state-db-backfill-recovery' -import type { GetSelectedCodexHomePath } from '../ipc/pty/host-env/types' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' - -/** Keep host status hooks and session discovery in client-selected managed CODEX_HOME paths. */ -export function orcadCodexAccountHomes( - getSettings: () => GlobalSettings, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void -) { - registerCleanup(() => stopCodexStateDbBackfillRecoveries()) - const selectLaunchHome: GetSelectedCodexHomePath = async (_target, launchEnv, context) => { - // Wire-supplied CODEX_HOME must be managed; user-owned homes are not ours to edit. - const home = resolveGuestCodexAccountHome(launchEnv?.CODEX_HOME) - if (!home) { - return null - } - const isEnabled = () => isAgentStatusHooksEnabledForAgent(getSettings(), 'codex') - // R42, COMPAT(wsl-bridge): the bridge's panes share these homes; off skips until D4 drops it. - if (isEnabled() || !isWslHostOrcadProcess()) { - await reconcileCodexAccountHomeHook(home, isEnabled, context?.launchesCodex === true) - } - return home - } - return { - selectLaunchHome, - /** Read selected homes without hook reconciliation for record-less catalogs. */ - readLaunchHome: (launchEnv?: NodeJS.ProcessEnv): string | null => - resolveGuestCodexAccountHome(launchEnv?.CODEX_HOME), - listSessionHomes: (): readonly string[] => listGuestCodexAccountHomes() - } -} diff --git a/src/main/orcad/orcad-command-startup.ts b/src/main/orcad/orcad-command-startup.ts deleted file mode 100644 index a0dd47d055b..00000000000 --- a/src/main/orcad/orcad-command-startup.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { startOrcad } from './orcad-entry' -import process from 'node:process' -import { resolveOrcadInstallRoot } from './orcad-app-paths' -import { ORCAD_USAGE, parseArgs } from './orcad-command-arguments' -import { installOrcadShutdownSignals, type OrcadShutdownTrigger } from './orcad-lifecycle' -import { installOrcadProcessErrorGuards } from './orcad-process-error-guards' -import { installOrcadStopRequestListeners } from './orcad-stop-request-listener' -import { prepareOrcadManagedStop } from './orcad-managed-stop-admission' -import { bindOrcadIdleShutdown } from './orcad-managed-idle-exit-host' - -export async function main(argv: string[] = process.argv.slice(2)): Promise { - const options = parseArgs(argv) - if (options.help) { - console.log(ORCAD_USAGE) - return - } - let shutdownTrigger: OrcadShutdownTrigger | null = null - // Fire-and-forget startup work can reject before its first await completes. - installOrcadProcessErrorGuards(() => shutdownTrigger) - const startup = startOrcad(options) - const requestShutdown = installOrcadShutdownSignals(async () => (await startup).stop()) - shutdownTrigger = requestShutdown - const handle = await startup - // Stop requests must name the runtime/instance established by startup. - installOrcadStopRequestListeners(() => requestShutdown('stop request'), { - installRoot: resolveOrcadInstallRoot(), - managedStop: handle.managedStop, - beforeManagedStop: prepareOrcadManagedStop - }) - bindOrcadIdleShutdown(requestShutdown) -} diff --git a/src/main/orcad/orcad-emulator-bridge.ts b/src/main/orcad/orcad-emulator-bridge.ts deleted file mode 100644 index 96575d47b68..00000000000 --- a/src/main/orcad/orcad-emulator-bridge.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import { EmulatorBridge } from '../emulator/emulator-bridge' -import { withTimeout } from '../../shared/promise-timeout-fallback' - -// A stalled adb must not hold the final profile flush past orcad's shutdown deadline. -const EMULATOR_TEARDOWN_BUDGET_MS = 3_000 - -/** Android drives adb/emulator on any host; iOS backends report their own host-support errors. */ -export function installOrcadEmulatorBridge( - runtime: OrcaRuntimeService, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void -): void { - const bridge = new EmulatorBridge() - runtime.setEmulatorBridge(bridge) - // Like desktop quit: stop the helpers and devices Orca started. - registerCleanup(() => - withTimeout(bridge.destroyAllSessions(), EMULATOR_TEARDOWN_BUDGET_MS, undefined) - ) -} diff --git a/src/main/orcad/orcad-event-loop-watchdog.test.ts b/src/main/orcad/orcad-event-loop-watchdog.test.ts deleted file mode 100644 index 837e200033e..00000000000 --- a/src/main/orcad/orcad-event-loop-watchdog.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { spawn } from 'node:child_process' -import { afterEach, expect, it } from 'vitest' -import { - ORCAD_EVENT_LOOP_WATCHDOG_ENV, - ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE, - startOrcadEventLoopWatchdog, - type OrcadEventLoopWatchdog, - type OrcadEventLoopWatchdogMessage -} from './orcad-event-loop-watchdog' - -const watchdogs: OrcadEventLoopWatchdog[] = [] -afterEach(() => watchdogs.splice(0).forEach((watchdog) => watchdog.stop())) - -/** Models a synchronous call that never yields the event loop; the worker's clock cannot be faked. */ -function blockMainThread(ms: number): void { - // ast-grep-ignore: test-no-wall-clock -- a busy-wait must read the real clock to block the real thread - const until = Date.now() + ms - // ast-grep-ignore: test-no-wall-clock -- a busy-wait must read the real clock to block the real thread - while (Date.now() < until) { - // Busy-wait. - } -} - -it('reports a blocked event loop from a thread the block cannot starve, then its recovery (#34410)', async () => { - const watchdog = startOrcadEventLoopWatchdog({ - supervised: false, - env: {}, - timings: { beatIntervalMs: 20, checkIntervalMs: 50, warnAfterMs: 300 } - }) - expect(watchdog).not.toBeNull() - watchdogs.push(watchdog!) - const messages: OrcadEventLoopWatchdogMessage[] = [] - watchdog!.worker.on('message', (message: OrcadEventLoopWatchdogMessage) => messages.push(message)) - await expect.poll(() => messages.map((message) => message.type)).toEqual(['started']) - - blockMainThread(900) - - await expect - .poll(() => messages.map((message) => message.type), { timeout: 2000 }) - .toEqual(['started', 'stalled', 'recovered']) - const stalled = messages[1] - expect(stalled.type === 'stalled' && stalled.blockedMs >= 300).toBe(true) -}) - -it('can be turned off', () => { - expect( - startOrcadEventLoopWatchdog({ supervised: true, env: { [ORCAD_EVENT_LOOP_WATCHDOG_ENV]: '0' } }) - ).toBeNull() -}) - -// Why the longer timeout: the child must boot a runtime and a worker before its loop blocks. -it('ends a supervised process whose event loop stays blocked past the exit bound', async () => { - // A child process stands in for orcad so the test runner survives the kill. - const script = ` - const { Worker } = require('node:worker_threads') - const worker = new Worker(process.env.WATCHDOG_SOURCE, { - eval: true, - workerData: { - beat: new SharedArrayBuffer(4), - checkIntervalMs: 50, - warnAfterMs: 100, - exitAfterMs: 300 - } - }) - worker.once('message', () => { - const until = Date.now() + 10000 - while (Date.now() < until) {} - process.exit(0) - }) - ` - const child = spawn(process.execPath, ['-e', script], { - env: { ...process.env, WATCHDOG_SOURCE: ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE }, - stdio: ['ignore', 'ignore', 'pipe'] - }) - let stderr = '' - child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString())) - const exit = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>( - // close, not exit: stderr may still hold the worker's last line when exit fires. - (resolve) => child.once('close', (code, signal) => resolve({ code, signal })) - ) - expect(exit.code === 0 && exit.signal === null).toBe(false) - expect(stderr).toContain('exiting so the service manager restarts it') -}, 20_000) diff --git a/src/main/orcad/orcad-exit-code.ts b/src/main/orcad/orcad-exit-code.ts deleted file mode 100644 index 17cbec53673..00000000000 --- a/src/main/orcad/orcad-exit-code.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { OrcadBindAddressError } from '../../shared/orcad-bind-address' -import { OrcadBundledRuntimeError } from './orcad-bundled-runtime' -import { OrcadInstanceLockError } from './orcad-data-root-privacy' -import { ProfileStateAccessError } from '../persistence/profile-state/access/profile-state-access-error' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' -import { ORCAD_EXIT_TERMINALS_NOT_DURABLE } from '../../shared/serve-supervised-terminal-durability' -import { OrcadTerminalsNotDurableError } from './orcad-serve-supervision' - -export const ORCAD_EXIT_FAILED = 1 - -export function resolveOrcadExitCode(error: unknown): number { - // Supervisors wait for an existing holder instead of abandoning the host. - if ( - error instanceof OrcadInstanceLockError && - error.code === 'orcad_instance_lock_holder_unverifiable' - ) { - return SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE - } - if (error instanceof OrcadTerminalsNotDurableError) { - return ORCAD_EXIT_TERMINALS_NOT_DURABLE - } - return error instanceof OrcadInstanceLockError || - error instanceof OrcadBindAddressError || - error instanceof OrcadBundledRuntimeError || - error instanceof ProfileStateAccessError - ? ORCAD_EXIT_CONFIGURATION - : ORCAD_EXIT_FAILED -} diff --git a/src/main/orcad/orcad-forked-child-paths.test.ts b/src/main/orcad/orcad-forked-child-paths.test.ts deleted file mode 100644 index 177ed5a1671..00000000000 --- a/src/main/orcad/orcad-forked-child-paths.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { getWatcherProcessEntryPath } from '../ipc/filesystem/watcher-process/parcel-watcher-entry-path' -import { AI_VAULT_SERVICE_ENTRY_FILENAME } from '../ai-vault/scan-service/session-scanner-service-entry-path' -import { FOREIGN_SQLITE_READER_ENTRY_FILENAME } from '../foreign-sqlite-readers/foreign-sqlite-reader-entry-path' -import { installOrcadHostAdapters } from './orcad-host-adapters' - -// Compose real adapters and deployment paths: isolated resolver tests missed nonexistent fork targets. -describe('orcad forked-child paths', () => { - let deployRoot: string - let originalArgv: string[] - - beforeEach(() => { - deployRoot = mkdtempSync(join(tmpdir(), 'orcad-deploy-')) - writeFileSync(join(deployRoot, 'orcad.js'), '') - writeFileSync(join(deployRoot, 'parcel-watcher-process-entry.js'), '') - writeFileSync(join(deployRoot, FOREIGN_SQLITE_READER_ENTRY_FILENAME), '') - writeFileSync(join(deployRoot, AI_VAULT_SERVICE_ENTRY_FILENAME), '') - originalArgv = process.argv - process.argv = [process.execPath, join(deployRoot, 'orcad.js')] - installOrcadHostAdapters() - }) - - afterEach(() => { - process.argv = originalArgv - rmSync(deployRoot, { recursive: true, force: true }) - }) - - it('ignores a decoy child under the working directory', () => { - // Cwd may hold an unrelated build; only the install root establishes shipped children. - const elsewhere = mkdtempSync(join(tmpdir(), 'orcad-cwd-')) - mkdirSync(join(elsewhere, 'out', 'main'), { recursive: true }) - writeFileSync(join(elsewhere, 'out', 'main', 'parcel-watcher-process-entry.js'), '') - writeFileSync(join(elsewhere, 'parcel-watcher-process-entry.js'), '') - const originalCwd = process.cwd() - process.chdir(elsewhere) - try { - expect(getWatcherProcessEntryPath()).toBe(join(deployRoot, 'parcel-watcher-process-entry.js')) - } finally { - process.chdir(originalCwd) - rmSync(elsewhere, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/orcad/orcad-local-serve-selection-entry.ts b/src/main/orcad/orcad-local-serve-selection-entry.ts index 86dab58700e..944f01379c1 100644 --- a/src/main/orcad/orcad-local-serve-selection-entry.ts +++ b/src/main/orcad/orcad-local-serve-selection-entry.ts @@ -5,8 +5,8 @@ import { formatServeRuntimeSelection, ORCAD_LOCAL_SERVE_SELECTION_FLAGS as FLAGS } from '../../shared/orcad-local-serve-selection' -import { selectServeRuntime } from './orcad-local-serve-selection' -import { pruneDesktopOrcadArtifactCache } from './orcad-artifact-cache-retention' +import { selectServeRuntime } from './serve-startup/orcad-local-serve-selection' +import { pruneDesktopOrcadArtifactCache } from './artifact-slots/orcad-artifact-cache-retention' import { findAppImageNodeRuntime } from '../node-runtime/appimage-bundled-node-runtime' function flagValue(argv: readonly string[], flag: string): string | null { diff --git a/src/main/orcad/orcad-managed-agent-hooks.ts b/src/main/orcad/orcad-managed-agent-hooks.ts deleted file mode 100644 index 1e3bdc4ebb7..00000000000 --- a/src/main/orcad/orcad-managed-agent-hooks.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { getClaudeAgentViewService } from '../claude/agent-view/agent-view-service' -import { getAppEnvironment } from '../../shared/app-environment' -import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' -import { adoptLoginShellAgentHomes } from '../agent-hooks/installation/agent-home-login-shell' -import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' -import { - isAgentStatusHooksEnabled, - isAgentStatusHooksEnabledForAgent -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/managed-agent-hook-startup' -import { refreshInstalledOpenCodeStatusPlugins } from '../opencode/status-hooks/opencode-status-plugin-startup-refresh' -import type { ProfilePreferences } from '../persistence/loading-store/profile-preferences/profile-preferences' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' -import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' - -/** SSH and WSL-host panes run beside this host, so it proves which agent owns each pane, from the - * first record its startup replay reads. */ -export function startOrcadAgentHookServer( - server: AgentHookServer, - options: Parameters[0] -): Promise { - installLocalHookRootEvidence(server) - return server.start(options) -} - -/** - * Reconcile hooks at startup as well as setting changes so newly managed hosts report status immediately. - * Call `readinessPublished` once readiness is out; work held off the ready path starts then. - */ -export function startOrcadManagedAgentHooks( - store: Pick, - setStatusHooksEnabled: (enabled: boolean) => void, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void -): { readinessPublished: () => void } { - const published = Promise.withResolvers() - let stopping = false - const agentView = getClaudeAgentViewService() - void agentView.reconcile(store.getSettings()) - const removeSettingsListener = store.onSettingsChanged((updates, settings) => { - void agentView.reconcile(settings) - if ('agentStatusHooksEnabled' in updates) { - setStatusHooksEnabled(isAgentStatusHooksEnabled(settings)) - } - }) - registerCleanup(() => { - stopping = true - removeSettingsListener() - }) - const getSettings = () => store.getSettings() - const shouldHydrateShellPath = getAppEnvironment().isPackaged() - startCodexHooks({ - pathReady: shouldHydrateShellPath ? hydrateAgentCliShellPath() : Promise.resolve(), - // Every orcad host defers this; it pays off on WSL, where finding codex stats Windows-drive PATH. - startAfter: published.promise, - isEnabled: () => isAgentStatusHooksEnabledForAgent(getSettings(), 'codex'), - resolveLaunchHome: () => null - }) - void adoptLoginShellAgentHomes().then(() => - reconcileStartupManagedAgentHooks({ - getSettings, - isQuitting: () => stopping, - shouldHydrateShellPath - }) - ) - try { - refreshInstalledOpenCodeStatusPlugins(getSettings()) - } catch (error) { - console.warn('[orcad] could not refresh OpenCode status plugins:', error) - } - return { readinessPublished: () => published.resolve() } -} diff --git a/src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts b/src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts deleted file mode 100644 index bfd76d38c7c..00000000000 --- a/src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' -import { - createRestTestRig, - foundRestTestChat, - sweepOnce -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig' - -import { STRUCTURED_AGENT_SESSION_IDLE_MS as IDLE_MS } from '../native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep' -import { - HOST_TEST_SESSION as REST_TEST_SESSION, - HOST_TEST_THREAD as REST_TEST_THREAD -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import type { RestTestRig } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig' -import { OrcadIdleExitMonitor } from './orcad-idle-exit-monitor' -import { createOrcadIdleProbes } from './orcad-managed-idle-exit' - -let rig: RestTestRig -const SERVER_IDLE_MS = 15 * 60_000 - -beforeEach(async () => { - rig = await createRestTestRig() - rig.host.collaboratorsForTests().lifetime.idleSweep.dispose() - await foundRestTestChat(rig) -}) - -afterEach(async () => { - await rig.dispose() -}) - -function idleMonitor() { - const onIdle = vi.fn() - const monitor = new OrcadIdleExitMonitor({ - timeoutMs: SERVER_IDLE_MS, - now: () => rig.clock.now, - log: () => {}, - lastClientActivityAt: () => 0, - onIdle, - probes: createOrcadIdleProbes( - { timeoutMs: SERVER_IDLE_MS, activationRoot: 'test-fence' }, - { - readClientActivity: () => ({ openConnections: 0, requestsInFlight: 0, lastRequestAt: 0 }), - listTerminals: async () => [], - countDaemonSessions: async () => 0, - hasDaemon: () => true, - hasChatProviders: () => rig.host.hasLoadedProviders(), - agentStates: () => [{ state: 'blocked' }], - hasStagedMigration: () => false, - automationsBusy: () => false, - emulatorsBusy: async () => false, - activationFenceExists: async () => false - } - ) - }) - return { monitor, onIdle } -} - -function providerEvents() { - const events = rig.adapter.acquire.mock.calls.at(-1)?.[0].events - if (!events) { - throw new Error('no provider was started') - } - return events -} - -it('U2: keeps the provider and disconnected server alive while an approval is unanswered', async () => { - providerEvents().appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'approval-turn', ordinal: 70 }, - { - kind: 'approval', - title: 'Run the command?', - detail: null, - options: [{ id: 'allow', label: 'Allow' }], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(REST_TEST_SESSION) - const { monitor, onIdle } = idleMonitor() - expect(await monitor.check()).toBe(false) - rig.clock.now += 7 * 24 * 60 * 60_000 - await sweepOnce(rig.host) - - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(await monitor.check()).toBe(false) - expect(onIdle).not.toHaveBeenCalled() -}) - -it('releases an idle provider after the existing window, then lets the disconnected server exit', async () => { - const { monitor, onIdle } = idleMonitor() - expect(await monitor.check()).toBe(false) - rig.clock.now += IDLE_MS - 1 - await sweepOnce(rig.host) - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(await monitor.check()).toBe(false) - - rig.clock.now += 2 - await sweepOnce(rig.host) - expect(rig.adapter.closeSession).toHaveBeenCalledWith(REST_TEST_SESSION, undefined) - expect(rig.host.hasLoadedProviders()).toBe(false) - expect(await monitor.check()).toBe(false) - rig.clock.now += SERVER_IDLE_MS - expect(await monitor.check()).toBe(true) - expect(onIdle).toHaveBeenCalledOnce() -}) - -it('never releases a quiet running turn or idle-exits its server', async () => { - providerEvents().appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 71 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(REST_TEST_SESSION) - const { monitor, onIdle } = idleMonitor() - expect(await monitor.check()).toBe(false) - for (let pass = 0; pass < 3; pass += 1) { - rig.clock.now += 7 * 24 * 60 * 60_000 - await sweepOnce(rig.host) - expect(await monitor.check()).toBe(false) - } - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(onIdle).not.toHaveBeenCalled() -}) diff --git a/src/main/orcad/orcad-observability.test.ts b/src/main/orcad/orcad-observability.test.ts deleted file mode 100644 index 1e46b71d084..00000000000 --- a/src/main/orcad/orcad-observability.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -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 { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { installOrcadObservability } from './orcad-observability' - -const CI_ENV = [ - 'CI', - 'GITHUB_ACTIONS', - 'GITLAB_CI', - 'CIRCLECI', - 'TRAVIS', - 'BUILDKITE', - 'JENKINS_URL', - 'TEAMCITY_VERSION' -] - -describe('orcad trace file', () => { - let dataRoot: string - - beforeEach(() => { - dataRoot = mkdtempSync(join(tmpdir(), 'orca-orcad-observability-')) - setAppEnvironment({ - getPath: (name) => { - if (name !== 'userData') { - throw new Error(`unexpected getPath: ${name}`) - } - return dataRoot - }, - getAppPath: () => dataRoot, - getVersion: () => '0.0.0-test', - isPackaged: () => true, - onWillQuit: () => {}, - exit: () => {}, - getAppMetrics: () => [] - }) - // Clear diagnostics gates to exercise the default host. - for (const name of [...CI_ENV, 'ORCA_DIAGNOSTICS_DISABLED']) { - vi.stubEnv(name, '') - } - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - }) - - afterEach(() => { - vi.unstubAllEnvs() - vi.restoreAllMocks() - rmSync(dataRoot, { recursive: true, force: true }) - }) - - const traceRecords = (): { name: string; attributes: Record }[] => - readFileSync(join(dataRoot, 'logs', 'orcad.trace.ndjson'), 'utf8') - .trim() - .split('\n') - .map((line) => JSON.parse(line)) - - const reportLateSettlement = (): void => - createStructuredAgentSessionLogger().warn('settling a late dispatch failed', { - scope: 'late-settlement', - sessionId: 'session-1', - error: new Error('disk full') - }) - - it('writes a structured chat failure to its own file under the data root, flushed by close', async () => { - const close = installOrcadObservability() - - reportLateSettlement() - await close() - - expect(traceRecords()).toContainEqual( - expect.objectContaining({ - name: 'agentSession.late-settlement', - attributes: expect.objectContaining({ sessionId: 'session-1' }), - exit: expect.objectContaining({ _tag: 'Failure' }) - }) - ) - expect(existsSync(join(dataRoot, 'logs', 'main.trace.ndjson'))).toBe(false) - }) - - it('flushes what is buffered when the process exits with no cleanup', async () => { - const before = new Set(process.listeners('exit')) - const close = installOrcadObservability() - const onExit = process.listeners('exit').filter((listener) => !before.has(listener)) - expect(onExit).toHaveLength(1) - - reportLateSettlement() - onExit[0]?.call(process, 1) - - expect(traceRecords().map((record) => record.name)).toContain('agentSession.late-settlement') - await close() - expect(process.listeners('exit')).toHaveLength(before.size) - }) - - it('still starts when the logs folder cannot be opened, with tracing off', async () => { - writeFileSync(join(dataRoot, 'logs'), 'not a folder') - const warn = vi.mocked(console.warn) - - const close = installOrcadObservability() - reportLateSettlement() - await close() - - expect(warn).toHaveBeenCalledWith( - expect.stringContaining('[observability] tracing is off'), - expect.any(Error) - ) - expect(readFileSync(join(dataRoot, 'logs'), 'utf8')).toBe('not a folder') - }) -}) diff --git a/src/main/orcad/orcad-paired-environment-options.ts b/src/main/orcad/orcad-paired-environment-options.ts deleted file mode 100644 index 4430d41babc..00000000000 --- a/src/main/orcad/orcad-paired-environment-options.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { createOrchestrationEnvironmentTransport } from '../ipc/runtime-environments/orchestration-environment-transport' -import type { RuntimeConstructionDependencies } from '../runtime/construction/runtime-construction-dependencies' -import type { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' - -type PairedEnvironmentRuntimeOptions = Required< - Pick -> - -/** Runtime options for this host's pairings: the servers it dials and the devices paired to it. */ -export function createOrcadPairedEnvironmentOptions(): { - runtimeOptions: PairedEnvironmentRuntimeOptions - /** RPC owns the device registry and starts after the runtime. */ - bindRpc: (rpc: Pick) => void -} { - let rpc: Pick | null = null - return { - runtimeOptions: { - // A headless host is a Run home too; it places workers on its own paired servers (#36853). - orchestrationEnvironmentTransport: createOrchestrationEnvironmentTransport(), - getPairedDeviceName: (pairedDeviceId) => - rpc?.getDeviceRegistry()?.getDevice(pairedDeviceId)?.name ?? null - }, - bindRpc: (server) => { - rpc = server - } - } -} diff --git a/src/main/orcad/orcad-restored-terminal-authority.ts b/src/main/orcad/orcad-restored-terminal-authority.ts deleted file mode 100644 index 8cc5e1fa736..00000000000 --- a/src/main/orcad/orcad-restored-terminal-authority.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { OrcadFeatureReadiness } from '../runtime/rpc/orcad-feature-readiness' -import { placeUnshownLiveTerminalsBestEffort } from '../runtime/terminal/adoption/unshown-live-terminal-placement' -import type { createOrcadStartupTiming } from './orcad-startup-timing' - -/** Restored orchestration authority, the legacy terminal reconcile and unshown placement, in order. */ -export async function restoreOrcadTerminalAuthority( - runtime: OrcaRuntimeService, - timed: ReturnType['time'], - readiness: OrcadFeatureReadiness -): Promise { - await timed('orchestration', () => runtime.refreshRestoredOrchestrationAuthority()) - readiness.open('orchestration') - // Terminal inventory stays on the critical path: no latch, every client needs it at connect. - await timed('reconcile-terminals', () => runtime.reconcileLegacyWorkerTerminals()) - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - await placeUnshownLiveTerminalsBestEffort(runtime) - } - readiness.open('unshownPlacement') -} diff --git a/src/main/orcad/orcad-runtime-lifetime.ts b/src/main/orcad/orcad-runtime-lifetime.ts deleted file mode 100644 index 283adac3bb5..00000000000 --- a/src/main/orcad/orcad-runtime-lifetime.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { - BackendServiceLifetime as OrcadRuntimeLifetime, - type BackendServiceCleanup as OrcadRuntimeCleanup -} from '../backend/service-composition' diff --git a/src/main/orcad/orcad-secret-store-startup.ts b/src/main/orcad/orcad-secret-store-startup.ts deleted file mode 100644 index d8247da1754..00000000000 --- a/src/main/orcad/orcad-secret-store-startup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { join } from 'node:path' -import { prepareOrcadSecretStore } from './orcad-host-adapters' - -export async function prepareOrcadSecretStoreAndMigrate(userDataPath: string): Promise { - const { getSecretStore } = await import('../../shared/secret-store') - const { reportSecretProtectionGap } = await import('../host/secret-protection-report') - const { migratePlaintextCredentials, orcadCredentialRoot } = - await import('./orcad-plaintext-credential-migration') - // Keep sealing keys outside disposable ORCA_USER_DATA roots. - if (await prepareOrcadSecretStore(orcadCredentialRoot(), userDataPath)) { - migratePlaintextCredentials(getSecretStore()) - } - reportSecretProtectionGap({ dataFile: join(userDataPath, 'orca-data.json') }) -} diff --git a/src/main/orcad/orcad-serve-readiness.ts b/src/main/orcad/orcad-serve-readiness.ts deleted file mode 100644 index 2e94738f536..00000000000 --- a/src/main/orcad/orcad-serve-readiness.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { ServeReadiness } from '../server/serve-readiness' -import type { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' -import { buildServePairingReadiness } from '../server/serve-pairing-readiness' -import type { OrcadHealth } from './orcad-health' -import type { OrcadOptions } from './orcad-start-contract' - -export async function buildOrcadServeReadiness(input: { - options: OrcadOptions - runtimeId: string - rpc: Pick - collectHealth: () => Promise -}): Promise { - return { - runtimeId: input.runtimeId, - ...(await buildServePairingReadiness(input.options, input.rpc)), - // WSL CLI reconciliation runs only in desktop launch, so no repair is pending here. - managedWslCliReconciliation: 'settled', - // Deployers inspect readiness health to reject hosts whose terminal daemon is unavailable. - health: await input.collectHealth() - } -} diff --git a/src/main/orcad/orcad-session-search.ts b/src/main/orcad/orcad-session-search.ts deleted file mode 100644 index f154aff15b2..00000000000 --- a/src/main/orcad/orcad-session-search.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' - -import { - type AiVaultSearchSettings, - resolveAiVaultSearchSettings -} from '../../shared/ai-vault/search/ai-vault-search-settings' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { localAiVaultScanRoots } from '../ai-vault/cached-session-list' -import { installInProcessSessionSearchService } from '../ai-vault-search/session-search-in-process-service' - -/** Index in-process as sole writer; the scanner child has no installed search data root. */ -export async function installOrcadSessionSearchService(args: { - userDataPath: string - getSettings: () => Pick -}): Promise<{ apply(settings: AiVaultSearchSettings): void; dispose(): void } | null> { - return installInProcessSessionSearchService({ - dataRoot: args.userDataPath, - roots: { executionHostId: LOCAL_EXECUTION_HOST_ID }, - resolveRoots: localAiVaultScanRoots, - settings: resolveAiVaultSearchSettings(args.getSettings()), - onError: (error) => console.error('[orcad] session search:', error) - }) -} diff --git a/src/main/orcad/orcad-speech-services.ts b/src/main/orcad/orcad-speech-services.ts deleted file mode 100644 index d9c0c661c90..00000000000 --- a/src/main/orcad/orcad-speech-services.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ModelManager } from '../speech/model-manager' -import { openNodeSpeechDownloadRequest } from '../speech/node-speech-download-request' -import { canReadCloudSpeechCredentials } from '../speech/cloud-transcription-target' -import type { SpeechServiceFactories } from '../speech/speech-runtime-service' -import { SttService } from '../speech/stt-service' -import { createSttGpuPolicy } from '../speech/stt-gpu-failure-marker' -import { spawnSttWorkerWithCpuFallback } from '../speech/stt-worker-cpu-fallback' -import { spawnSttForkedProcess } from '../speech/stt-worker-forked-process' - -// Local speech needs the installed app recognizer supplied by orca serve. -export const orcadSpeechServiceFactories: SpeechServiceFactories = { - createModelManager: (customModelsDir) => - // Headless key reads cannot open keychain prompts, so readiness may verify decryption. - new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadCloudSpeechCredentials), - createSttService: (models, gpuEnabled) => { - const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled) - return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttForkedProcess, gpu)) - } -} diff --git a/src/main/orcad/orcad-startup-qualification.test.ts b/src/main/orcad/orcad-startup-qualification.test.ts deleted file mode 100644 index 4b5342cef9f..00000000000 --- a/src/main/orcad/orcad-startup-qualification.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const artifacts = vi.hoisted(() => ({ files: ['orcad-server.js', 'daemon-entry.js'] })) -vi.mock('./orcad-artifact-identity', () => ({ - listOrcadArtifactFilenames: async () => artifacts.files -})) - -import { - consumeOrcadStartupQualification, - orcadStartupQualificationKey, - recordOrcadStartupQualification -} from './orcad-startup-qualification' - -let slot: string - -beforeEach(() => { - slot = mkdtempSync(join(tmpdir(), 'orcad-qualified-')) - for (const name of artifacts.files) { - writeFileSync(join(slot, name), `${name} bytes`) - } -}) - -afterEach(() => { - rmSync(slot, { recursive: true, force: true }) -}) - -describe('orcad startup qualification', () => { - it('keys on the artifact version and on every installed file staying the same file', async () => { - const key = await orcadStartupQualificationKey(slot, '0.1.0+aaaaaaaaaaaa') - - expect(await orcadStartupQualificationKey(slot, '0.1.0+aaaaaaaaaaaa')).toBe(key) - expect(await orcadStartupQualificationKey(slot, '0.2.0+aaaaaaaaaaaa')).not.toBe(key) - rmSync(join(slot, 'daemon-entry.js')) - writeFileSync(join(slot, 'daemon-entry.js'), 'replaced') - expect(await orcadStartupQualificationKey(slot, '0.1.0+aaaaaaaaaaaa')).not.toBe(key) - }) - - it('consumes a matching marker once, so a launch that dies before readiness re-qualifies', async () => { - await recordOrcadStartupQualification(slot, 'key-1') - - expect(await consumeOrcadStartupQualification(slot, 'key-1')).toBe(true) - expect(await consumeOrcadStartupQualification(slot, 'key-1')).toBe(false) - }) -}) diff --git a/src/main/orcad/orcad-stats.ts b/src/main/orcad/orcad-stats.ts deleted file mode 100644 index 260054832da..00000000000 --- a/src/main/orcad/orcad-stats.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { feedAgentSessionStats, type AgentStatusSource } from '../stats/agent-session-stats-feed' -import { initStatsPath, StatsCollector } from '../stats/collector' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' - -export function startOrcadStats( - userDataPath: string, - hooks: AgentStatusSource, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void -): StatsCollector { - initStatsPath(userDataPath) - const stats = new StatsCollector() - // Reverse cleanup order stops feeds/RPC before the final stats flush. - registerCleanup(() => stats.flushAsync()) - registerCleanup(feedAgentSessionStats(stats, hooks)) - return stats -} diff --git a/src/main/orcad/orcad-host-identity-reset.ts b/src/main/orcad/profile-state/orcad-host-identity-reset.ts similarity index 90% rename from src/main/orcad/orcad-host-identity-reset.ts rename to src/main/orcad/profile-state/orcad-host-identity-reset.ts index c0f21f9a70d..5cb0ac954e3 100644 --- a/src/main/orcad/orcad-host-identity-reset.ts +++ b/src/main/orcad/profile-state/orcad-host-identity-reset.ts @@ -1,11 +1,11 @@ // CLI entry for `orca serve reset-identity`; plain Node, loaded from the packaged CLI. import { existsSync } from 'node:fs' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' -import { OrcadInstanceLockError } from './orcad-data-root-privacy' +import { acquireOrcadInstanceLock } from '../instance-lock/orcad-instance-lock' +import { OrcadInstanceLockError } from '../instance-lock/orcad-data-root-privacy' import { HostIdentityRotationNotStartedError, rotateHostIdentity -} from '../runtime/host-instance-identity' +} from '../../runtime/host-instance-identity' export type HostIdentityResetResult = | { status: 'reset' } diff --git a/src/main/orcad/orcad-profile-state-startup.ts b/src/main/orcad/profile-state/orcad-profile-state-startup.ts similarity index 75% rename from src/main/orcad/orcad-profile-state-startup.ts rename to src/main/orcad/profile-state/orcad-profile-state-startup.ts index 711a019e981..ef8262ab4db 100644 --- a/src/main/orcad/orcad-profile-state-startup.ts +++ b/src/main/orcad/profile-state/orcad-profile-state-startup.ts @@ -1,11 +1,11 @@ -import { createProfileStateStoreForStartup } from '../persistence/profile-state/startup/profile-state-startup-authority' -import type { ProfileStateStoreFactoryResult } from '../persistence/profile-state/startup/profile-state-store-factory' -import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' -import { initOrcaProfilePaths } from '../orca-profiles/profile-storage-paths' -import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' -import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' +import { createProfileStateStoreForStartup } from '../../persistence/profile-state/startup/profile-state-startup-authority' +import type { ProfileStateStoreFactoryResult } from '../../persistence/profile-state/startup/profile-state-store-factory' +import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store' +import { initOrcaProfilePaths } from '../../orca-profiles/profile-storage-paths' +import { initSshHostKeyStoreFile } from '../../ssh/host-keys/ssh-host-key-store' +import { initOrcadHeldFenceTokenFile } from '../../managed-server/activation/orcad-held-fence-tokens' import { emitOrcadProfileStateAuthoritySelected } from './orcad-profile-state-telemetry' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' /** WSL hosts are held to a per-distro memory budget; the idle writer thread costs ~13-15 MB. */ export const WSL_HOST_PROFILE_WRITER_IDLE_STOP_MS = 60_000 diff --git a/src/main/orcad/orcad-profile-state-telemetry.ts b/src/main/orcad/profile-state/orcad-profile-state-telemetry.ts similarity index 89% rename from src/main/orcad/orcad-profile-state-telemetry.ts rename to src/main/orcad/profile-state/orcad-profile-state-telemetry.ts index 4e04fd10412..efc796cbc6d 100644 --- a/src/main/orcad/orcad-profile-state-telemetry.ts +++ b/src/main/orcad/profile-state/orcad-profile-state-telemetry.ts @@ -1,4 +1,4 @@ -import type { ProfileStateStorageClassification } from '../persistence/profile-state/database/profile-state-storage-classification' +import type { ProfileStateStorageClassification } from '../../persistence/profile-state/database/profile-state-storage-classification' /** Exclude paths, profile IDs and serialized state from fleet telemetry. */ export type OrcadProfileStateAuthoritySelection = { diff --git a/src/main/orcad/profile-state/serve-profile-ssh-targets.ts b/src/main/orcad/profile-state/serve-profile-ssh-targets.ts new file mode 100644 index 00000000000..8db9b6ef718 --- /dev/null +++ b/src/main/orcad/profile-state/serve-profile-ssh-targets.ts @@ -0,0 +1,38 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../shared/orca-profiles' +import { PROFILE_STATE_DATABASE_FILE_NAME } from '../../../shared/profile-state-storage-paths' +import { getActiveProfileStateLocation } from '../../persistence/profile-state/offline-access/profile-state-active-location' +import { readProfileStateDomain } from '../../persistence/profile-state/documents/profile-state-domain-reader' +import { classifyProfileStateStorage } from '../../persistence/profile-state/database/profile-state-storage-classification' + +/** Inspect SSH targets without creating, locking or migrating state owned by the next serve host. */ +export function serveProfileHasSshTargets(userDataPath: string): boolean { + // Before profile indexes existed, state lived at the legacy root paths. + const location = getActiveProfileStateLocation(userDataPath) ?? { + dataFile: join(userDataPath, 'orca-data.json'), + databaseFile: join(userDataPath, PROFILE_STATE_DATABASE_FILE_NAME), + profileId: DEFAULT_LOCAL_ORCA_PROFILE_ID + } + const storage = classifyProfileStateStorage(location.dataFile, location.databaseFile) + if (storage === 'neither') { + return false + } + if (storage === 'json-only') { + const parsed: unknown = JSON.parse(readFileSync(location.dataFile, 'utf8')) + return hasEntries(isRecord(parsed) ? parsed.sshTargets : undefined) + } + const result = readProfileStateDomain(location.databaseFile, location.profileId, 'sshTargets') + if (result.kind === 'unreadable') { + throw result.error + } + return result.kind === 'value' && hasEntries(result.value) +} + +function hasEntries(value: unknown): boolean { + return Array.isArray(value) && value.length > 0 +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} diff --git a/src/main/orcad/orcad-bundled-runtime.ts b/src/main/orcad/runtime-launch/orcad-bundled-runtime.ts similarity index 94% rename from src/main/orcad/orcad-bundled-runtime.ts rename to src/main/orcad/runtime-launch/orcad-bundled-runtime.ts index 59785312057..547f686ea4e 100644 --- a/src/main/orcad/orcad-bundled-runtime.ts +++ b/src/main/orcad/runtime-launch/orcad-bundled-runtime.ts @@ -2,15 +2,15 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs' import { dirname, join } from 'node:path' import { constants } from 'node:os' import { spawnProcess } from '@orca/process-host' -import { resolveOrcadInstallRoot } from './orcad-app-paths' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' +import { resolveOrcadInstallRoot } from '../host-runtime/orcad-app-paths' +import { ORCAD_EXIT_CONFIGURATION } from '../serve-startup/orcad-configuration-exit' import { ORCAD_NODE_RUNTIME_MARKER_FILENAME, ORCAD_SERVER_TARGET_FILENAME, ORCAD_VERSION_FILENAME, orcadNodeRuntimeRelativePath -} from '../../shared/orcad-artifacts' -import { NODE_RUNTIME_PIN, nodeRuntimeAsset } from '../../shared/node-runtime-pin' +} from '../../../shared/orcad-artifacts' +import { NODE_RUNTIME_PIN, nodeRuntimeAsset } from '../../../shared/node-runtime-pin' export class OrcadBundledRuntimeError extends Error {} export const ORCAD_BUNDLED_LAUNCHER_ENV = 'ORCA_BUNDLED_LAUNCHER_CHANNEL' diff --git a/src/main/orcad/orcad-compile-cache.ts b/src/main/orcad/runtime-launch/orcad-compile-cache.ts similarity index 93% rename from src/main/orcad/orcad-compile-cache.ts rename to src/main/orcad/runtime-launch/orcad-compile-cache.ts index 7e7f3db8052..e5db79bff7f 100644 --- a/src/main/orcad/orcad-compile-cache.ts +++ b/src/main/orcad/runtime-launch/orcad-compile-cache.ts @@ -1,6 +1,6 @@ import module from 'node:module' import { join } from 'node:path' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' export const ORCAD_COMPILE_CACHE_DIRNAME = '.orcad-compile-cache' diff --git a/src/main/orcad/orcad-launcher-isolation.integration.test.ts b/src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts similarity index 88% rename from src/main/orcad/orcad-launcher-isolation.integration.test.ts rename to src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts index 4cfc10f784c..896058d75c2 100644 --- a/src/main/orcad/orcad-launcher-isolation.integration.test.ts +++ b/src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts @@ -4,14 +4,17 @@ import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { ORCAD_LAUNCHER_FILENAME, ORCAD_SERVER_ENTRY_FILENAME } from '../../shared/orcad-artifacts' -import { NODE_RUNTIME_PIN } from '../../shared/node-runtime-pin' -import { hashOrcadLauncher } from '../../shared/orcad-build-identity' +import { + ORCAD_LAUNCHER_FILENAME, + ORCAD_SERVER_ENTRY_FILENAME +} from '../../../shared/orcad-artifacts' +import { NODE_RUNTIME_PIN } from '../../../shared/node-runtime-pin' +import '../../../shared/orcad-build-identity' import { locatePinnedNodeForTests, skipForMissingInputs, writeNodeSlotFixture -} from './orcad-node-slot-fixture' +} from '../testing/native-slots/orcad-node-slot-fixture' const pinnedNode = locatePinnedNodeForTests() const launcherNode = @@ -51,19 +54,6 @@ beforeAll(async () => { await buildLauncher(launcher) }) -it('changes the launcher identity when the server is rebuilt', async () => { - const directory = join(root, 'rebuilt') - await mkdir(directory) - const entry = join(directory, ORCAD_LAUNCHER_FILENAME) - const server = join(directory, ORCAD_SERVER_ENTRY_FILENAME) - await writeFile(server, SERVER_FIXTURE) - await buildLauncher(entry) - const first = hashOrcadLauncher(entry) - await writeFile(server, 'console.log("rebuilt server")') - await buildLauncher(entry) - expect(hashOrcadLauncher(entry)).not.toBe(first) -}) - afterAll(async () => { // Windows can hold an exited node.exe image open briefly (EBUSY). await rm(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 }) diff --git a/src/main/orcad/orcad-profile-preflight.ts b/src/main/orcad/runtime-launch/orcad-profile-preflight.ts similarity index 88% rename from src/main/orcad/orcad-profile-preflight.ts rename to src/main/orcad/runtime-launch/orcad-profile-preflight.ts index 39acd0eaf3d..f8576c65e42 100644 --- a/src/main/orcad/orcad-profile-preflight.ts +++ b/src/main/orcad/runtime-launch/orcad-profile-preflight.ts @@ -2,20 +2,23 @@ import { z } from 'zod' import { randomUUID } from 'node:crypto' import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { preflightProfileStateRuntime } from '../persistence/profile-state/startup/profile-state-runtime-preflight' +import { preflightProfileStateRuntime } from '../../persistence/profile-state/startup/profile-state-runtime-preflight' import { ORCAD_STARTUP_PREFLIGHT_FLAG, ORCAD_PROFILE_PREFLIGHT_TIMEOUT_MS, parseOrcadProfilePreflight, orcadProfilePreflightResponseSchema, type OrcadProfilePreflightResponse -} from '../../shared/orcad-profile-preflight' -import { readOrcadArtifactIdentity } from './orcad-artifact-identity' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { ORCAD_SERVER_ENTRY_FILENAME, ORCAD_VERSION_FILENAME } from '../../shared/orcad-artifacts' -import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../shared/orcad-node-runtime-identity' +} from '../../../shared/orcad-profile-preflight' +import { readOrcadArtifactIdentity } from '../artifact-slots/orcad-artifact-identity' +import { ORCAD_EXIT_CONFIGURATION } from '../serve-startup/orcad-configuration-exit' +import { + ORCAD_SERVER_ENTRY_FILENAME, + ORCAD_VERSION_FILENAME +} from '../../../shared/orcad-artifacts' +import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../../shared/orcad-node-runtime-identity' import { runProcess } from '@orca/process-host' -import { preflightOrcadNativeRuntime } from './orcad-runtime-native-preflight' +import { preflightOrcadNativeRuntime } from '../native-runtime/orcad-runtime-native-preflight' import { orcadCompileCacheEnv } from './orcad-compile-cache' import { consumeOrcadStartupQualification, @@ -152,9 +155,9 @@ async function readServedDaemonProtocols(servedUserDataPath: string): Promise ({ files: ['orcad-server.js', 'daemon-entry.js'] })) +vi.mock('../artifact-slots/orcad-artifact-identity', () => ({ + listOrcadArtifactFilenames: async () => artifacts.files +})) + +import { + consumeOrcadStartupQualification, + recordOrcadStartupQualification +} from './orcad-startup-qualification' + +let slot: string + +beforeEach(() => { + slot = mkdtempSync(join(tmpdir(), 'orcad-qualified-')) + for (const name of artifacts.files) { + writeFileSync(join(slot, name), `${name} bytes`) + } +}) + +afterEach(() => { + rmSync(slot, { recursive: true, force: true }) +}) + +describe('orcad startup qualification', () => { + it('consumes a matching marker once, so a launch that dies before readiness re-qualifies', async () => { + await recordOrcadStartupQualification(slot, 'key-1') + + expect(await consumeOrcadStartupQualification(slot, 'key-1')).toBe(true) + expect(await consumeOrcadStartupQualification(slot, 'key-1')).toBe(false) + }) +}) diff --git a/src/main/orcad/orcad-startup-qualification.ts b/src/main/orcad/runtime-launch/orcad-startup-qualification.ts similarity index 90% rename from src/main/orcad/orcad-startup-qualification.ts rename to src/main/orcad/runtime-launch/orcad-startup-qualification.ts index 8236f357a99..911feaa677f 100644 --- a/src/main/orcad/orcad-startup-qualification.ts +++ b/src/main/orcad/runtime-launch/orcad-startup-qualification.ts @@ -4,11 +4,11 @@ import { readFile, rename, stat, unlink, writeFile } from 'node:fs/promises' import { release } from 'node:os' import { isAbsolute, join, relative } from 'node:path' import process from 'node:process' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' -import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../shared/orcad-node-runtime-identity' -import { mapWithConcurrency } from '../../shared/map-with-concurrency' -import { listOrcadArtifactFilenames } from './orcad-artifact-identity' -import { detectNativeHostAbi } from './native-host-abi' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' +import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../../shared/orcad-node-runtime-identity' +import { mapWithConcurrency } from '../../../shared/map-with-concurrency' +import { listOrcadArtifactFilenames } from '../artifact-slots/orcad-artifact-identity' +import { detectNativeHostAbi } from '../native-runtime/native-host-abi' export const ORCAD_STARTUP_QUALIFIED_FILENAME = '.orcad-startup-qualified' const ARTIFACT_STAT_CONCURRENCY = 16 diff --git a/src/main/orcad/serve-profile-ssh-targets.ts b/src/main/orcad/serve-profile-ssh-targets.ts deleted file mode 100644 index 6698e81e2ca..00000000000 --- a/src/main/orcad/serve-profile-ssh-targets.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../shared/orca-profiles' -import { PROFILE_STATE_DATABASE_FILE_NAME } from '../../shared/profile-state-storage-paths' -import { getActiveProfileStateLocation } from '../persistence/profile-state/offline-access/profile-state-active-location' -import { readProfileStateDomain } from '../persistence/profile-state/documents/profile-state-domain-reader' -import { classifyProfileStateStorage } from '../persistence/profile-state/database/profile-state-storage-classification' - -/** Inspect SSH targets without creating, locking or migrating state owned by the next serve host. */ -export function serveProfileHasSshTargets(userDataPath: string): boolean { - // Before profile indexes existed, state lived at the legacy root paths. - const location = getActiveProfileStateLocation(userDataPath) ?? { - dataFile: join(userDataPath, 'orca-data.json'), - databaseFile: join(userDataPath, PROFILE_STATE_DATABASE_FILE_NAME), - profileId: DEFAULT_LOCAL_ORCA_PROFILE_ID - } - const storage = classifyProfileStateStorage(location.dataFile, location.databaseFile) - if (storage === 'neither') { - return false - } - if (storage === 'json-only') { - const parsed: unknown = JSON.parse(readFileSync(location.dataFile, 'utf8')) - return hasEntries(isRecord(parsed) ? parsed.sshTargets : undefined) - } - const result = readProfileStateDomain(location.databaseFile, location.profileId, 'sshTargets') - if (result.kind === 'unreadable') { - throw result.error - } - return result.kind === 'value' && hasEntries(result.value) -} - -function hasEntries(value: unknown): boolean { - return Array.isArray(value) && value.length > 0 -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} diff --git a/src/main/orcad/orcad-cli-launcher.integration.test.ts b/src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts similarity index 88% rename from src/main/orcad/orcad-cli-launcher.integration.test.ts rename to src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts index 2513f878d06..b94833cdaad 100644 --- a/src/main/orcad/orcad-cli-launcher.integration.test.ts +++ b/src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts @@ -2,18 +2,18 @@ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { expect, it } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' import { runProcess, spawnProcess } from '@orca/process-host' -import { sealedChildEnv } from '../runtime/agent-session/environment/structured-session-child-env.test-support' -import { resolveBundledOrcadRuntime } from './orcad-bundled-runtime' -import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../shared/orcad-artifacts' -import { skipForMissingInputs } from './orcad-node-slot-fixture' +import { sealedChildEnv } from '../../runtime/agent-session/environment/structured-session-child-env.test-support' +import { resolveBundledOrcadRuntime } from '../runtime-launch/orcad-bundled-runtime' +import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../shared/orcad-artifacts' +import { skipForMissingInputs } from '../testing/native-slots/orcad-node-slot-fixture' import { killChildAndWait, killProfileDaemons, recordProfileDaemons, removeTestRoot -} from './orcad-daemon-teardown-fixture' +} from '../testing/daemon-processes/orcad-daemon-teardown-fixture' const slotDir = resolve('out/orcad') const runtime = existsSync(join(slotDir, ORCAD_NODE_RUNTIME_MARKER_FILENAME)) @@ -112,7 +112,7 @@ it.skipIf(skip)( cwd: home, timeoutMs: 15_000 }) - expect(result.code, result.stderr).toBe(0) + expect(result.code, `${result.stdout}\n${result.stderr}`).toBe(0) expect(JSON.parse(result.stdout)).toMatchObject({ ok: true, result: { diff --git a/src/main/orcad/orcad-cli-launcher.test.ts b/src/main/orcad/serve-startup/orcad-cli-launcher.test.ts similarity index 96% rename from src/main/orcad/orcad-cli-launcher.test.ts rename to src/main/orcad/serve-startup/orcad-cli-launcher.test.ts index 6d3b4560541..8defbce327b 100644 --- a/src/main/orcad/orcad-cli-launcher.test.ts +++ b/src/main/orcad/serve-startup/orcad-cli-launcher.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -import { ORCAD_CLI_ENTRY_FILENAME } from '../../shared/orcad-artifacts' +import { ORCAD_CLI_ENTRY_FILENAME } from '../../../shared/orcad-artifacts' import { getOrcadCliLauncherPath, prepareOrcadCliLauncher } from './orcad-cli-launcher' const roots = vi.hoisted(() => ({ install: '', profile: '' })) -vi.mock('./orcad-app-paths', () => ({ +vi.mock('../host-runtime/orcad-app-paths', () => ({ resolveOrcadInstallRoot: () => roots.install, resolveUserDataPath: () => roots.profile })) diff --git a/src/main/orcad/orcad-cli-launcher.ts b/src/main/orcad/serve-startup/orcad-cli-launcher.ts similarity index 90% rename from src/main/orcad/orcad-cli-launcher.ts rename to src/main/orcad/serve-startup/orcad-cli-launcher.ts index ed39f5c49bb..01ef8b0d60d 100644 --- a/src/main/orcad/orcad-cli-launcher.ts +++ b/src/main/orcad/serve-startup/orcad-cli-launcher.ts @@ -5,11 +5,11 @@ import { join } from 'node:path' import { ORCAD_CLI_ENTRY_FILENAME, ORCAD_WINDOWS_CLI_LAUNCHER_FILENAME -} from '../../shared/orcad-artifacts' -import { nodeFileContentsEqual } from '../../shared/file-content/node-file-content-equality' -import { buildUnixCliLauncher } from '../cli/launchers/cli-dev-launcher' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { resolveOrcadInstallRoot, resolveUserDataPath } from './orcad-app-paths' +} from '../../../shared/orcad-artifacts' +import { nodeFileContentsEqual } from '../../../shared/file-content/node-file-content-equality' +import { buildUnixCliLauncher } from '../../cli/launchers/cli-dev-launcher' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' +import { resolveOrcadInstallRoot, resolveUserDataPath } from '../host-runtime/orcad-app-paths' // The native Windows launcher selects server mode when this sibling config exists. export const ORCAD_WINDOWS_CLI_LAUNCHER_CONFIG_FILENAME = 'orca-launcher.cfg' diff --git a/src/main/orcad/orcad-command-arguments.ts b/src/main/orcad/serve-startup/orcad-command-arguments.ts similarity index 94% rename from src/main/orcad/orcad-command-arguments.ts rename to src/main/orcad/serve-startup/orcad-command-arguments.ts index 1a1b5da57b7..6db33d64835 100644 --- a/src/main/orcad/orcad-command-arguments.ts +++ b/src/main/orcad/serve-startup/orcad-command-arguments.ts @@ -1,10 +1,10 @@ import type { OrcadOptions } from './orcad-start-contract' -import { DEFAULT_WS_PORT } from '../runtime/rpc/server/runtime-rpc-pairing-types' -import { ORCAD_LOOPBACK_BIND_HOST } from '../../shared/orcad-bind-address' -import { getServeOptionValidationError } from '../../shared/serve-option-validation' +import { DEFAULT_WS_PORT } from '../../runtime/rpc/server/runtime-rpc-pairing-types' +import { ORCAD_LOOPBACK_BIND_HOST } from '../../../shared/orcad-bind-address' +import { getServeOptionValidationError } from '../../../shared/serve-option-validation' import { existsSync } from 'node:fs' import { join, resolve } from 'node:path' -import { WEB_CLIENT_INDEX_FILENAME } from '../../shared/bundled-web-client-root' +import { WEB_CLIENT_INDEX_FILENAME } from '../../../shared/bundled-web-client-root' export const ORCAD_USAGE = `orcad — the Orca runtime served without Electron. diff --git a/src/main/orcad/serve-startup/orcad-command-startup.ts b/src/main/orcad/serve-startup/orcad-command-startup.ts new file mode 100644 index 00000000000..2dbbe27103a --- /dev/null +++ b/src/main/orcad/serve-startup/orcad-command-startup.ts @@ -0,0 +1,34 @@ +import { startOrcad } from '../host-runtime/orcad-entry' +import process from 'node:process' +import { resolveOrcadInstallRoot } from '../host-runtime/orcad-app-paths' +import { ORCAD_USAGE, parseArgs } from './orcad-command-arguments' +import { + installOrcadShutdownSignals, + type OrcadShutdownTrigger +} from '../host-lifecycle/orcad-lifecycle' +import { installOrcadProcessErrorGuards } from '../host-lifecycle/orcad-process-error-guards' +import { installOrcadStopRequestListeners } from '../host-lifecycle/managed-stop/orcad-stop-request-listener' +import { prepareOrcadManagedStop } from '../host-lifecycle/managed-stop/orcad-managed-stop-admission' +import { bindOrcadIdleShutdown } from '../host-lifecycle/idle-exit/orcad-managed-idle-exit-host' + +export async function main(argv: string[] = process.argv.slice(2)): Promise { + const options = parseArgs(argv) + if (options.help) { + console.log(ORCAD_USAGE) + return + } + let shutdownTrigger: OrcadShutdownTrigger | null = null + // Fire-and-forget startup work can reject before its first await completes. + installOrcadProcessErrorGuards(() => shutdownTrigger) + const startup = startOrcad(options) + const requestShutdown = installOrcadShutdownSignals(async () => (await startup).stop()) + shutdownTrigger = requestShutdown + const handle = await startup + // Stop requests must name the runtime/instance established by startup. + installOrcadStopRequestListeners(() => requestShutdown('stop request'), { + installRoot: resolveOrcadInstallRoot(), + managedStop: handle.managedStop, + beforeManagedStop: prepareOrcadManagedStop + }) + bindOrcadIdleShutdown(requestShutdown) +} diff --git a/src/main/orcad/orcad-configuration-exit.ts b/src/main/orcad/serve-startup/orcad-configuration-exit.ts similarity index 100% rename from src/main/orcad/orcad-configuration-exit.ts rename to src/main/orcad/serve-startup/orcad-configuration-exit.ts diff --git a/src/main/orcad/serve-startup/orcad-exit-code.ts b/src/main/orcad/serve-startup/orcad-exit-code.ts new file mode 100644 index 00000000000..846e949f3cf --- /dev/null +++ b/src/main/orcad/serve-startup/orcad-exit-code.ts @@ -0,0 +1,29 @@ +import { OrcadBindAddressError } from '../../../shared/orcad-bind-address' +import { OrcadBundledRuntimeError } from '../runtime-launch/orcad-bundled-runtime' +import { OrcadInstanceLockError } from '../instance-lock/orcad-data-root-privacy' +import { ProfileStateAccessError } from '../../persistence/profile-state/access/profile-state-access-error' +import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../../shared/single-instance-exit-code' +import { ORCAD_EXIT_TERMINALS_NOT_DURABLE } from '../../../shared/serve-supervised-terminal-durability' +import { OrcadTerminalsNotDurableError } from './orcad-serve-supervision' + +export const ORCAD_EXIT_FAILED = 1 + +export function resolveOrcadExitCode(error: unknown): number { + // Supervisors wait for an existing holder instead of abandoning the host. + if ( + error instanceof OrcadInstanceLockError && + error.code === 'orcad_instance_lock_holder_unverifiable' + ) { + return SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE + } + if (error instanceof OrcadTerminalsNotDurableError) { + return ORCAD_EXIT_TERMINALS_NOT_DURABLE + } + return error instanceof OrcadInstanceLockError || + error instanceof OrcadBindAddressError || + error instanceof OrcadBundledRuntimeError || + error instanceof ProfileStateAccessError + ? ORCAD_EXIT_CONFIGURATION + : ORCAD_EXIT_FAILED +} diff --git a/src/main/orcad/orcad-help.integration.test.ts b/src/main/orcad/serve-startup/orcad-help.integration.test.ts similarity index 94% rename from src/main/orcad/orcad-help.integration.test.ts rename to src/main/orcad/serve-startup/orcad-help.integration.test.ts index c1157a9a1f8..50be505dd13 100644 --- a/src/main/orcad/orcad-help.integration.test.ts +++ b/src/main/orcad/serve-startup/orcad-help.integration.test.ts @@ -4,7 +4,10 @@ import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { ORCAD_LAUNCHER_FILENAME, ORCAD_SERVER_ENTRY_FILENAME } from '../../shared/orcad-artifacts' +import { + ORCAD_LAUNCHER_FILENAME, + ORCAD_SERVER_ENTRY_FILENAME +} from '../../../shared/orcad-artifacts' let directory = '' let launcher = '' diff --git a/src/main/orcad/orcad-local-serve-selection.ts b/src/main/orcad/serve-startup/orcad-local-serve-selection.ts similarity index 87% rename from src/main/orcad/orcad-local-serve-selection.ts rename to src/main/orcad/serve-startup/orcad-local-serve-selection.ts index 0bf91a2228f..bc5d364db4f 100644 --- a/src/main/orcad/orcad-local-serve-selection.ts +++ b/src/main/orcad/serve-startup/orcad-local-serve-selection.ts @@ -3,31 +3,31 @@ import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { runProcess } from '@orca/process-host' -import { NODE_RUNTIME_ASSETS, type ServerTarget } from '../../shared/node-runtime-pin' +import { NODE_RUNTIME_ASSETS, type ServerTarget } from '../../../shared/node-runtime-pin' import { ORCAD_SERVER_ENTRY_FILENAME, ORCAD_VERSION_FILENAME, orcadNodeRuntimeRelativePath -} from '../../shared/orcad-artifacts' +} from '../../../shared/orcad-artifacts' import { ORCAD_NATIVE_PREFLIGHT_FLAG, parseOrcadNativePreflightReport -} from '../../shared/orcad-native-preflight-report' +} from '../../../shared/orcad-native-preflight-report' import { SERVE_RUNTIME_ELECTRON, SERVE_RUNTIME_ENV, type ServeRuntimeSelection -} from '../../shared/orcad-local-serve-selection' -import { resolveBundledOrcadRuntime } from './orcad-bundled-runtime' -import { detectNativeHostAbi, nativeSlotName } from './native-host-abi' -import { materializeOrcadArtifact } from './orcad-artifact-materializer' -import { materializeCachedNodeRuntime } from '../node-runtime/pinned-runtime-materializer' +} from '../../../shared/orcad-local-serve-selection' +import { resolveBundledOrcadRuntime } from '../runtime-launch/orcad-bundled-runtime' +import { detectNativeHostAbi, nativeSlotName } from '../native-runtime/native-host-abi' +import { materializeOrcadArtifact } from '../artifact-slots/orcad-artifact-materializer' +import { materializeCachedNodeRuntime } from '../../node-runtime/pinned-runtime-materializer' import { copyVerifiedAppImageNodeRuntime, type AppImageNodeRuntime -} from '../node-runtime/appimage-bundled-node-runtime' -import { serveProfileHasSshTargets } from './serve-profile-ssh-targets' -import { errorMessage } from '../../shared/error-message' +} from '../../node-runtime/appimage-bundled-node-runtime' +import { serveProfileHasSshTargets } from '../profile-state/serve-profile-ssh-targets' +import { errorMessage } from '../../../shared/error-message' const NATIVE_PREFLIGHT_TIMEOUT_MS = 30_000 diff --git a/src/main/orcad/serve-startup/orcad-serve-readiness.ts b/src/main/orcad/serve-startup/orcad-serve-readiness.ts new file mode 100644 index 00000000000..4e4159e0d66 --- /dev/null +++ b/src/main/orcad/serve-startup/orcad-serve-readiness.ts @@ -0,0 +1,21 @@ +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' +import { buildServePairingReadiness } from '../../server/serve-pairing-readiness' +import type { OrcadHealth } from '../diagnostics/orcad-health' +import type { OrcadOptions } from './orcad-start-contract' + +export async function buildOrcadServeReadiness(input: { + options: OrcadOptions + runtimeId: string + rpc: Pick + collectHealth: () => Promise +}): Promise { + return { + runtimeId: input.runtimeId, + ...(await buildServePairingReadiness(input.options, input.rpc)), + // WSL CLI reconciliation runs only in desktop launch, so no repair is pending here. + managedWslCliReconciliation: 'settled', + // Deployers inspect readiness health to reject hosts whose terminal daemon is unavailable. + health: await input.collectHealth() + } +} diff --git a/src/main/orcad/orcad-serve-supervision.ts b/src/main/orcad/serve-startup/orcad-serve-supervision.ts similarity index 90% rename from src/main/orcad/orcad-serve-supervision.ts rename to src/main/orcad/serve-startup/orcad-serve-supervision.ts index e45e076d85e..061f31fa140 100644 --- a/src/main/orcad/orcad-serve-supervision.ts +++ b/src/main/orcad/serve-startup/orcad-serve-supervision.ts @@ -1,6 +1,6 @@ // `orca serve --supervise` runs orcad under a service manager, which restarts it routinely. import process from 'node:process' -import { ORCA_SERVE_SUPERVISED_ENV } from '../../shared/serve-supervised-terminal-durability' +import { ORCA_SERVE_SUPERVISED_ENV } from '../../../shared/serve-supervised-terminal-durability' /** A supervised service must not hand out terminals that its next restart would kill. */ export class OrcadTerminalsNotDurableError extends Error { diff --git a/src/main/orcad/orcad-start-contract.ts b/src/main/orcad/serve-startup/orcad-start-contract.ts similarity index 84% rename from src/main/orcad/orcad-start-contract.ts rename to src/main/orcad/serve-startup/orcad-start-contract.ts index e30420addb6..f61e4f16cc4 100644 --- a/src/main/orcad/orcad-start-contract.ts +++ b/src/main/orcad/serve-startup/orcad-start-contract.ts @@ -1,5 +1,5 @@ -import type { ServeReadiness } from '../server/serve-readiness' -import type { OrcadManagedStopContext } from '../../shared/orcad-stop-request' +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcadManagedStopContext } from '../../../shared/orcad-stop-request' export type OrcadOptions = { port?: number diff --git a/src/main/orcad/orcad-ws-port-policy.ts b/src/main/orcad/serve-startup/orcad-ws-port-policy.ts similarity index 85% rename from src/main/orcad/orcad-ws-port-policy.ts rename to src/main/orcad/serve-startup/orcad-ws-port-policy.ts index 37445ae3eb9..7103e9e32ca 100644 --- a/src/main/orcad/orcad-ws-port-policy.ts +++ b/src/main/orcad/serve-startup/orcad-ws-port-policy.ts @@ -1,4 +1,4 @@ -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' type OrcadWsPortOptions = { wsPort?: number diff --git a/src/main/orcad/orcad-daemon-session-client-fixture.ts b/src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture.ts similarity index 100% rename from src/main/orcad/orcad-daemon-session-client-fixture.ts rename to src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture.ts diff --git a/src/main/orcad/orcad-daemon-teardown-fixture.ts b/src/main/orcad/testing/daemon-processes/orcad-daemon-teardown-fixture.ts similarity index 91% rename from src/main/orcad/orcad-daemon-teardown-fixture.ts rename to src/main/orcad/testing/daemon-processes/orcad-daemon-teardown-fixture.ts index bbd400bf7dc..133372497c2 100644 --- a/src/main/orcad/orcad-daemon-teardown-fixture.ts +++ b/src/main/orcad/testing/daemon-processes/orcad-daemon-teardown-fixture.ts @@ -7,15 +7,15 @@ import { buildProcessTableIndex, collectDescendantsFromIndex, type ProcessTableIndexOf -} from '../../shared/process-table-index' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' -import { DaemonEndpointOwnershipError } from '../daemon/launch/daemon-endpoint-adoption' -import { parseLinuxProcessState } from '../daemon/endpoint/identity/daemon-incarnation-evidence' -import { readDaemonPidRecord } from '../daemon/endpoint/identity/daemon-endpoint-incarnation' -import { readLinuxStat } from '../daemon/endpoint/identity/daemon-process-inspection' -import { cleanupDaemonForProtocol } from '../daemon/launch/daemon-protocol-cleanup' -import type { WindowsProcessIdentityRow } from '../windows/windows-process-table' +} from '../../../../shared/process-table-index' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { parseLinuxStartTicks } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' +import { DaemonEndpointOwnershipError } from '../../../daemon/launch/daemon-endpoint-adoption' +import { parseLinuxProcessState } from '../../../daemon/endpoint/identity/daemon-incarnation-evidence' +import { readDaemonPidRecord } from '../../../daemon/endpoint/identity/daemon-endpoint-incarnation' +import { readLinuxStat } from '../../../daemon/endpoint/identity/daemon-process-inspection' +import { cleanupDaemonForProtocol } from '../../../daemon/launch/daemon-protocol-cleanup' +import type { WindowsProcessIdentityRow } from '../../../windows/windows-process-table' import type { spawnProcess } from '@orca/process-host' const EXIT_WAIT_MS = 10_000 @@ -126,7 +126,7 @@ async function readWindowsProcessTable(): Promise limit - ? value.slice(-limit).replace(/^[^\r\n]*(?:\r?\n|$)/u, '[truncated]\n') - : value - return tail - .replace(/\b(?:https?|wss?):\/\/\S+/giu, '[url]') - .replace(/\bBearer\s+\S+/giu, 'Bearer [redacted]') - .replace(/((?:token|pairingCode|authToken)["'=:\s]+)\S+/giu, '$1[redacted]') - .slice(-limit) -} - function errorDetails(error: unknown): Record { if (!(error instanceof Error)) { return { message: boundedText(String(error)) } @@ -139,7 +129,7 @@ export class ServeCleanupDiagnostics { snapshot.processEvidence = 'unverifiable: Windows native capture only' return } - const table = await import('../windows/windows-process-table') + const table = await import('../../../windows/windows-process-table') // Refuse fallback evidence: the public reader can use CIM without the native binding. if (!table.isWindowsProcessTableAvailable()) { snapshot.processEvidence = 'unverifiable: native process table unavailable' diff --git a/src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts b/src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts new file mode 100644 index 00000000000..343332b4fae --- /dev/null +++ b/src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts @@ -0,0 +1,11 @@ +export function boundedText(value: string, limit = 2_048): string { + const tail = + value.length > limit + ? value.slice(-limit).replace(/^[^\r\n]*(?:\r?\n|$)/u, '[truncated]\n') + : value + return tail + .replace(/\b(?:https?|wss?):\/\/\S+/giu, '[url]') + .replace(/\bBearer\s+\S+/giu, 'Bearer [redacted]') + .replace(/((?:token|pairingCode|authToken)["'=:\s]+)\S+/giu, '$1[redacted]') + .slice(-limit) +} diff --git a/src/main/orcad/orcad-serve-parity.integration.test.ts b/src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts similarity index 93% rename from src/main/orcad/orcad-serve-parity.integration.test.ts rename to src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts index 4965f8aefc5..7b936dde3eb 100644 --- a/src/main/orcad/orcad-serve-parity.integration.test.ts +++ b/src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts @@ -3,16 +3,16 @@ import { tmpdir, userInfo } from 'node:os' import { join, resolve } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { runProcess, spawnProcess } from '@orca/process-host' -import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../shared/orcad-artifacts' +import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../../shared/orcad-artifacts' import { findBundledWebClientRoot, WEB_CLIENT_INDEX_FILENAME -} from '../../shared/bundled-web-client-root' -import { orcadServeArgs } from '../../shared/orcad-serve-argv' -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' -import { resolveBundledOrcadRuntime } from './orcad-bundled-runtime' -import { skipForMissingInputs } from './orcad-node-slot-fixture' -import { buildDaemonSessionClient } from './orcad-daemon-session-client-fixture' +} from '../../../../shared/bundled-web-client-root' +import { orcadServeArgs } from '../../../../shared/orcad-serve-argv' +import { ORCAD_LOCK_FILE_NAME } from '../../instance-lock/orcad-instance-lock' +import { resolveBundledOrcadRuntime } from '../../runtime-launch/orcad-bundled-runtime' +import { skipForMissingInputs } from '../native-slots/orcad-node-slot-fixture' +import { buildDaemonSessionClient } from '../daemon-processes/orcad-daemon-session-client-fixture' import type { ServeCleanupDiagnostics } from './orcad-serve-cleanup-diagnostics.test-fixture' import { killAndAwaitExit, @@ -20,7 +20,7 @@ import { recordProfileDaemons, removeTestRoot, waitForProcessExit -} from './orcad-daemon-teardown-fixture' +} from '../daemon-processes/orcad-daemon-teardown-fixture' const slotDir = resolve('out/orcad') const runtime = existsSync(join(slotDir, ORCAD_NODE_RUNTIME_MARKER_FILENAME)) diff --git a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts b/src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts similarity index 88% rename from src/main/orcad/orcad-packaged-structured-chat.integration.test.ts rename to src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts index 09dfd71eb7c..5f22fa3cd04 100644 --- a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts +++ b/src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts @@ -12,40 +12,40 @@ import { tmpdir } from 'node:os' import { delimiter, dirname, join, resolve } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { z } from 'zod' -import { getDefaultPersistedState } from '../../shared/constants' -import { folderWorkspaceKey } from '../../shared/workspace-scope' +import { getDefaultPersistedState } from '../../../../shared/constants' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { spawnProcess } from '@orca/process-host' -import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import type { AgentSessionSubscribeEvent } from '../../shared/agent-session/agent-session-wire' -import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import { parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' +import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' +import type { AgentSessionSubscribeEvent } from '../../../../shared/agent-session/agent-session-wire' +import type { AgentJournalRenderItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' import { pairedRuntimeConnectionFromOffer, type PairedRuntimeConnection -} from '../../shared/remote-runtime/pairing/paired-runtime-connection' +} from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import { AGENT_SESSION_TURN_ITEM_CAPABILITY, CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY -} from '../../shared/agent-session/agent-session-runtime-capabilities' -import { sendRemoteRuntimeRequestOnSocket } from '../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RemoteRuntimeTransportSubscription } from '../../shared/remote-runtime/requests/remote-runtime-subscription-contract' -import { claudeSessionIdForOrcaSession } from '../claude/structured/claude-structured-session-id' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { materializeOrcadArtifact } from './orcad-artifact-materializer' +} from '../../../../shared/agent-session/agent-session-runtime-capabilities' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { materializeOrcadArtifact } from '../../artifact-slots/orcad-artifact-materializer' import { hostServerTarget, installPackagedOrcadSlotForTests, locatePinnedNodeForTests, skipForMissingInputs -} from './orcad-node-slot-fixture' +} from '../native-slots/orcad-node-slot-fixture' import { killChildAndWait, killProfileDaemons, removeTestRoot -} from './orcad-daemon-teardown-fixture' +} from '../daemon-processes/orcad-daemon-teardown-fixture' import { packagedClaudeChatScenario } from './orcad-structured-chat-scenario' const pinnedNode = locatePinnedNodeForTests() diff --git a/src/main/orcad/orcad-structured-chat-scenario.ts b/src/main/orcad/testing/structured-chat/orcad-structured-chat-scenario.ts similarity index 100% rename from src/main/orcad/orcad-structured-chat-scenario.ts rename to src/main/orcad/testing/structured-chat/orcad-structured-chat-scenario.ts diff --git a/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts b/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts index 19462e0987f..398cc20e6a2 100644 --- a/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts +++ b/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts @@ -5,7 +5,7 @@ import { type WslMoveCutover, type WslMoveCutoverPhase } from '../../../../shared/wsl-move/wsl-move-cutover' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' export function wslMoveCutoverFixture( migrationId = 'move-1', diff --git a/src/main/persistence/__fixtures__/wsl-mover/wsl-mover-folders-profile.ts b/src/main/persistence/__fixtures__/wsl-mover/wsl-mover-folders-profile.ts deleted file mode 100644 index beb806bdafc..00000000000 --- a/src/main/persistence/__fixtures__/wsl-mover/wsl-mover-folders-profile.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../../../shared/project-group-types' -import type { WorkspaceLineage } from '../../../../shared/worktree/lineage-types' -import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' -import type { WslMoveProjectionInput } from '../../moving-wsl-projects/manifest-scope/wsl-move-state-projection' -import { - project, - repo, - terminalTab, - worktreeMeta, - type WslMoverPaths -} from './wsl-mover-profile-rows' - -export function foldersAndAutomationsWslMoverProfile(paths: WslMoverPaths): WslMoveProjectionInput { - const repoAuto = repo('repo-auto', paths.at('/srv/jobs')) - const wtAuto = `repo-auto::${repoAuto.path}` - const group: ProjectGroup = { - id: 'group-1', - name: 'Ops', - parentPath: paths.at('/srv'), - parentGroupId: null, - createdFrom: 'manual', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } - const folder: FolderWorkspace = { - id: 'folder-1', - projectGroupId: 'group-1', - name: 'Notes', - folderPath: paths.at('/srv/notes'), - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } - const runContext = { - kind: 'workspace-run' as const, - projectId: 'project-auto', - hostId: 'local' as const, - // A repo's own setup is keyed by the repo id on both sides (createSetupFromRepo, the export). - projectHostSetupId: 'repo-auto', - repoId: 'repo-auto', - path: repoAuto.path - } - const automation: Automation = { - id: 'auto-1', - name: 'Nightly', - prompt: 'Run the nightly sweep', - precheck: null, - agentId: 'claude', - runContext, - projectId: 'repo-auto', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: paths.side === 'source' ? 'local_host_service' : 'remote_host_service', - workspaceMode: 'existing', - workspaceId: wtAuto, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', - dtstart: 1, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - enabled: true, - nextRunAt: 2, - createdAt: 1, - updatedAt: 1 - } - const run: AutomationRun = { - id: 'run-1', - automationId: 'auto-1', - runContext, - title: 'Nightly #1', - scheduledFor: 1, - status: 'completed', - trigger: 'scheduled', - workspaceId: wtAuto, - sessionKind: 'terminal', - chatSessionId: null, - terminalSessionId: null, - terminalPaneKey: null, - terminalPtyId: null, - outputSnapshot: null, - precheckResult: null, - usage: null, - error: null, - startedAt: 1, - dispatchedAt: 1, - createdAt: 1 - } - const lineage: WorkspaceLineage = { - childWorkspaceKey: worktreeWorkspaceKey(wtAuto), - parentWorkspaceKey: folderWorkspaceKey('folder-1'), - origin: 'manual', - capture: { source: 'explicit-cli-flag', confidence: 'explicit' }, - createdAt: 1 - } - return { - state: { - repos: [{ ...repoAuto, projectGroupId: 'group-1' }], - projects: [project('project-auto', ['repo-auto'])], - projectGroups: [group], - folderWorkspaces: [folder], - sparsePresetsByRepo: {}, - retiredWorktreeNamesByRepo: {}, - worktreeMeta: { [wtAuto]: worktreeMeta('jobs') }, - worktreeLineageById: {}, - workspaceLineageByChildKey: { [lineage.childWorkspaceKey]: lineage }, - automations: [automation], - automationRuns: [run] - }, - session: { - tabsByWorktree: { - 'folder:folder-1': [terminalTab('tab-f', 'folder:folder-1', null, null)] - }, - lastVisitedAtByWorktreeId: { 'folder:folder-1': 3 } - } - } -} diff --git a/src/main/persistence/__fixtures__/wsl-mover/wsl-mover-profiles.ts b/src/main/persistence/__fixtures__/wsl-mover/wsl-mover-profiles.ts deleted file mode 100644 index 23b047ff43a..00000000000 --- a/src/main/persistence/__fixtures__/wsl-mover/wsl-mover-profiles.ts +++ /dev/null @@ -1,91 +0,0 @@ -// Render the same logical state as desktop UNC paths or destination Linux paths; out-of-scope rows stay behind. -import type { - WslMoveProjectionInput, - WslMoveProjectionScope -} from '../../moving-wsl-projects/manifest-scope/wsl-move-state-projection' -import { foldersAndAutomationsWslMoverProfile } from './wsl-mover-folders-profile' -import { heavyWslMoverProfile } from './wsl-mover-heavy-profile' -import { - repo, - worktreeMeta, - WSL_MOVER_DISTRO, - wslMoverPaths, - type WslMoverProfileSide -} from './wsl-mover-profile-rows' - -export { WSL_MOVER_DISTRO } - -export type WslMoverProfileName = 'heavy-wsl' | 'mixed-windows-wsl' | 'folders-and-automations' -export const WSL_MOVER_PROFILE_NAMES: readonly WslMoverProfileName[] = [ - 'heavy-wsl', - 'mixed-windows-wsl', - 'folders-and-automations' -] - -export function wslMoverProfileScope( - name: WslMoverProfileName, - side: WslMoverProfileSide -): WslMoveProjectionScope { - const repoIds = name === 'folders-and-automations' ? ['repo-auto'] : ['repo-a', 'repo-b'] - return { - distro: WSL_MOVER_DISTRO, - repoIds: new Set(name === 'mixed-windows-wsl' ? ['repo-a'] : repoIds), - folderWorkspaceIds: new Set(name === 'folders-and-automations' ? ['folder-1'] : []), - ownerHostId: 'local', - hostAliases: - side === 'source' - ? ['local'] - : ['local', `runtime:wsl:${WSL_MOVER_DISTRO}`, `wsl:${WSL_MOVER_DISTRO}`] - } -} - -export function wslMoverProfile( - name: WslMoverProfileName, - side: WslMoverProfileSide -): WslMoveProjectionInput { - const paths = wslMoverPaths(side) - switch (name) { - case 'heavy-wsl': - return heavyWslMoverProfile(paths) - case 'mixed-windows-wsl': - return withOutOfScopeRows(heavyWslMoverProfile(paths), side, ['repo-b']) - case 'folders-and-automations': - return foldersAndAutomationsWslMoverProfile(paths) - } -} - -function withOutOfScopeRows( - profile: WslMoveProjectionInput, - side: WslMoverProfileSide, - alsoUnscopedRepoIds: readonly string[] -): WslMoveProjectionInput { - if (side === 'destination') { - const keep = (repoId: string): boolean => !alsoUnscopedRepoIds.includes(repoId) - return { - ...profile, - state: { - ...profile.state, - repos: profile.state.repos.filter((row) => keep(row.id)), - worktreeMeta: Object.fromEntries( - Object.entries(profile.state.worktreeMeta).filter(([key]) => - keep(key.slice(0, key.indexOf('::'))) - ) - ) - } - } - } - const windowsRepo = repo('repo-win', 'C:\\src\\win') - const debianRepo = repo('repo-deb', '\\\\wsl.localhost\\Debian\\home\\dev\\other') - return { - ...profile, - state: { - ...profile.state, - repos: [...profile.state.repos, windowsRepo, debianRepo], - worktreeMeta: { - ...profile.state.worktreeMeta, - [`repo-win::${windowsRepo.path}`]: worktreeMeta('win'), - [`repo-deb::${debianRepo.path}`]: worktreeMeta('deb') - } - } - } -} diff --git a/src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts b/src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts new file mode 100644 index 00000000000..116f79f70b8 --- /dev/null +++ b/src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts @@ -0,0 +1,54 @@ +import { closeTestStores, testState, createStore, writeDataFile } from '../persistence-test-harness' +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { rmSync, mkdtempSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' + +vi.mock('electron', () => ({ + app: { getPath: () => testState.dir }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), + decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) + } +})) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: () => ({ nth_repo_added: 2 }) +})) + +function writeSettings(settings: Record): void { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) +} + +describe('artifact sharing default', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) + }) + + afterEach(async () => { + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('allows publishing on a new profile and keeps it after a reload', async () => { + const store = createStore() + expect(store.getSettings().artifactSharingEnabled).toBe(true) + store.flush() + await closeTestStores() + expect(createStore().getSettings().artifactSharingEnabled).toBe(true) + }) + + it('keeps publishing off for a stored profile saved before the setting existed', () => { + writeSettings({ showArtifactsButton: false }) + expect(createStore().getSettings().artifactSharingEnabled).toBe(false) + }) +}) diff --git a/src/main/persistence/applying-settings/persistence-automations.test.ts b/src/main/persistence/applying-settings/persistence-automations.test.ts index 4831c74f568..c112bceef4c 100644 --- a/src/main/persistence/applying-settings/persistence-automations.test.ts +++ b/src/main/persistence/applying-settings/persistence-automations.test.ts @@ -120,6 +120,83 @@ describe('Store', () => { expect(store.updateAutomation(existing.id, { workspaceId: undefined }).workspaceId).toBe('wt1') }) + it('applies a batch of updates, reporting a missing row without blocking the rest', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + const create = (name: string) => + store.createAutomation({ + name, + prompt: 'Run checks', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'new_per_run', + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime() + }) + const [a, b, c] = [create('A'), create('B'), create('C')] + + const results = store.updateAutomations([ + { id: a.id, updates: { enabled: false } }, + { id: 'missing', updates: { enabled: false } }, + { id: b.id, updates: { enabled: false } } + ]) + + expect(results.map((result) => ('automation' in result ? 'ok' : 'error'))).toEqual([ + 'ok', + 'error', + 'ok' + ]) + expect(store.listAutomations().map(({ name, enabled }) => [name, enabled])).toEqual([ + ['A', false], + ['B', false], + ['C', true] + ]) + expect(store.automationEnablementRevision(a.id)).toBe(1) + expect(store.automationEnablementRevision(c.id)).toBe(0) + }) + + it('writes the same record from a batch as from a single update', async () => { + vi.useFakeTimers({ now: new Date('2026-06-01T00:00:00Z'), toFake: ['Date'] }) + try { + const store = await createStore() + store.addRepo(makeRepo()) + const createdBy = { kind: 'plugin', pluginKey: 'p', name: 'P' } as const + const create = () => + store.createAutomation({ + name: 'Same', + prompt: 'Run checks', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'new_per_run', + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime(), + createdBy + }) + const [single, batched] = [create(), create()] + vi.setSystemTime(new Date('2026-06-02T00:00:00Z')) + const updates = { enabled: false, createdBy: { ...createdBy, endedAt: 42 } } + + const fromSingle = store.updateAutomation(single.id, updates) + const [fromBatch] = store.updateAutomations([{ id: batched.id, updates }]) + + const { id: _singleId, ...expected } = fromSingle + expect('automation' in fromBatch && fromBatch.automation).toEqual({ + ...expected, + id: batched.id + }) + const stored = store.listAutomations() + const { id: _storedSingleId, ...storedSingle } = stored[0] + expect(stored[1]).toEqual({ ...storedSingle, id: batched.id }) + expect(store.automationEnablementRevision(batched.id)).toBe( + store.automationEnablementRevision(single.id) + ) + } finally { + vi.useRealTimers() + } + }) + it('stores its own contexts over a client-perspective create runContext', async () => { const store = await createStore() store.addRepo(makeRepo({ upstream: { owner: 'stablyai', repo: 'orca' } })) diff --git a/src/main/persistence/applying-settings/persistence-chat-ui-launch-tip-audience.test.ts b/src/main/persistence/applying-settings/persistence-chat-ui-launch-tip-audience.test.ts index 92cf377cacc..bf7a196acdc 100644 --- a/src/main/persistence/applying-settings/persistence-chat-ui-launch-tip-audience.test.ts +++ b/src/main/persistence/applying-settings/persistence-chat-ui-launch-tip-audience.test.ts @@ -11,8 +11,10 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import * as crypto from 'node:crypto' -import { ensureChatUiLaunchTipCohort } from '../../telemetry/chat-ui-launch-tip-cohort' +import { + ensureChatUiLaunchTipCohort, + isChatUiLaunchTipDeferredForConsent +} from '../../telemetry/chat-ui-launch-tip-cohort' import { restoreConsentEnv, stashAndClearConsentEnv } from '../../telemetry/client-test-harness' vi.mock('electron', () => ({ @@ -20,10 +22,6 @@ vi.mock('electron', () => ({ safeStorage: { isEncryptionAvailable: () => false } })) vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('node:crypto', async (importOriginal) => ({ - ...(await importOriginal()), - randomInt: vi.fn(() => 0) -})) beforeEach(() => { testState.dir = mkdtempSync(join(tmpdir(), 'orca-chat-ui-launch-tip-audience-')) @@ -61,48 +59,59 @@ it('keeps frozen imported originals separate for each Store and prepared export' }) }) -it('preserves separate rollout completion through stale client writes and reloads', async () => { +const EXISTING_TELEMETRY = { + optedIn: true, + installId: 'install', + existedBeforeTelemetryRelease: true +} as const + +it('keeps a re-offered card completed through stale client writes and reloads', async () => { const env = stashAndClearConsentEnv() try { - writeDataFile({ settings: { experimentalNativeChat: false } }) - const store = createStore() - store.updateSettings({ - telemetry: { - ...store.getSettings().telemetry!, - optedIn: true, - chatUiLaunchTipCohort: 'control' + writeDataFile({ + settings: { + experimentalNativeChat: false, + telemetry: { ...EXISTING_TELEMETRY, chatUiLaunchTipCohort: 'control' } } }) - store.updateUI({ featureTipsSeenIds: ['orca-cli', 'chat-ui-here'] }) - vi.mocked(crypto.randomInt).mockImplementationOnce(() => 4) - expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment') - expect(store.getUI().featureTipsSeenIds).toEqual(['orca-cli', 'chat-ui-here']) - - store.updateUI({ featureTipsSeenIds: ['orca-cli', 'chat-ui-here', 'voice-dictation'] }) + const store = createStore() + expect(ensureChatUiLaunchTipCohort(store)).toBe('control') + store.updateUI({ featureTipsSeenIds: ['orca-cli', 'chat-ui-here', 'chat-ui-here-v2'] }) + store.updateUI({ featureTipsSeenIds: ['orca-cli', 'chat-ui-here', 'cmd-j-palette'] }) store.flushOrThrow() await closeTestStores() - const pending = createStore() - expect(ensureChatUiLaunchTipCohort(pending)).toBe('treatment') - expect(pending.getUI().featureTipsSeenIds).toEqual([ - 'orca-cli', - 'chat-ui-here', - 'voice-dictation' - ]) - pending.updateUI({ featureTipsSeenIds: ['chat-ui-here-rollout-v1'] }) - pending.updateUI({ featureTipsSeenIds: ['orca-cli', 'chat-ui-here', 'cmd-j-palette'] }) - pending.flushOrThrow() - await closeTestStores() - const shown = createStore() - expect(ensureChatUiLaunchTipCohort(shown)).toBe('treatment') - expect(shown.getUI().featureTipsSeenIds).toEqual([ + const reloaded = createStore() + expect(ensureChatUiLaunchTipCohort(reloaded)).toBe('control') + expect(reloaded.getSettings().telemetry).not.toHaveProperty('chatUiLaunchTipRolloutCohort') + expect(reloaded.getUI().featureTipsSeenIds).toEqual([ 'orca-cli', 'chat-ui-here', - 'voice-dictation', - 'chat-ui-here-rollout-v1', + 'chat-ui-here-v2', 'cmd-j-palette' ]) } finally { restoreConsentEnv(env) } }) + +it('checks only applicable completion IDs while consent is pending', () => { + const env = stashAndClearConsentEnv() + try { + writeDataFile({ + ui: { featureTipsSeenIds: ['chat-ui-here'] }, + settings: { + experimentalNativeChat: false, + telemetry: { ...EXISTING_TELEMETRY, optedIn: null, chatUiLaunchTipCohort: 'control' } + } + }) + const store = createStore() + expect(ensureChatUiLaunchTipCohort(store)).toBe('control') + expect(isChatUiLaunchTipDeferredForConsent()).toBe(true) + store.updateUI({ featureTipsSeenIds: ['chat-ui-here-v2'] }) + expect(ensureChatUiLaunchTipCohort(store)).toBe('control') + expect(isChatUiLaunchTipDeferredForConsent()).toBe(false) + } finally { + restoreConsentEnv(env) + } +}) diff --git a/src/main/persistence/applying-settings/persistence-settings-update.test.ts b/src/main/persistence/applying-settings/persistence-settings-update.test.ts index 3117cabecaa..1362f08f91d 100644 --- a/src/main/persistence/applying-settings/persistence-settings-update.test.ts +++ b/src/main/persistence/applying-settings/persistence-settings-update.test.ts @@ -124,4 +124,43 @@ describe('Store', () => { expect(updated.notifications.enabled).toBe(false) expect(updated.notifications.customSoundPath).toBe('/sounds/custom.wav') }) + + it('repairs workspace cleanup rules when loading and when writing', async () => { + writeDataFile({ + settings: { + workspaceCleanupPolicy: { merged: { enabled: true }, unchanged: { afterDays: -4 } } + }, + repos: [ + { ...makeRepo({ id: 'r1' }), workspaceCleanupPolicy: { mode: 'off', extra: 1 } }, + { ...makeRepo({ id: 'r2', path: '/repo2' }), workspaceCleanupPolicy: { mode: 'sometimes' } } + ] + }) + const store = await createStore() + const offRules = { + merged: { enabled: false }, + unchanged: { enabled: false, afterDays: 1 }, + inactive: { enabled: false, afterDays: 30, action: 'archive' }, + automationRuns: { enabled: false }, + orchestrationWorkers: { enabled: false }, + keepWhen: 'any-local-files' + } + expect(store.getSettings().workspaceCleanupPolicy).toEqual({ + ...offRules, + merged: { enabled: true } + }) + expect(store.getRepo('r1')?.workspaceCleanupPolicy).toEqual({ mode: 'off' }) + expect(store.getRepo('r2')).not.toHaveProperty('workspaceCleanupPolicy') + + store.updateSettings({ + // @ts-expect-error -- Malformed writes can arrive from untyped writers. + workspaceCleanupPolicy: { inactive: { enabled: true, action: 'delete', afterDays: 'soon' } } + }) + expect(store.getSettings().workspaceCleanupPolicy).toEqual({ + ...offRules, + inactive: { enabled: true, afterDays: 30, action: 'delete' } + }) + + store.updateRepo({ id: 'r1' }, { workspaceCleanupPolicy: null }) + expect(store.getRepo('r1')).not.toHaveProperty('workspaceCleanupPolicy') + }) }) diff --git a/src/main/persistence/applying-settings/settings-update.ts b/src/main/persistence/applying-settings/settings-update.ts index 32220723e6a..82acc7ee5d9 100644 --- a/src/main/persistence/applying-settings/settings-update.ts +++ b/src/main/persistence/applying-settings/settings-update.ts @@ -28,6 +28,7 @@ import { normalizeUiLanguage } from '../../../shared/ui-language' import { normalizeWorktreeVisibilityDefaults } from '../../../shared/external-worktree-visibility' import { normalizePRBotAuthorOverrides } from '../../../shared/source-control/review-comments/pr-bot-author-overrides' import { normalizeMachineName } from '../../../shared/machine-name' +import { normalizeWorkspaceCleanupRules } from '../../../shared/workspace-cleanup/workspace-cleanup-policy' import type { PersistedState } from '../../../shared/persisted-state-types' import { addMobilePairingCustomAddress, @@ -112,6 +113,11 @@ export function updateSettings( }) } } + if ('workspaceCleanupPolicy' in updates) { + sanitizedUpdates.workspaceCleanupPolicy = normalizeWorkspaceCleanupRules( + updates.workspaceCleanupPolicy + ) + } sanitizeAgentLaunchProfileUpdates(sanitizedUpdates, updates) if ('nativeChatPermissionMode' in updates || 'agentPermissionDefault' in updates) { Object.assign( diff --git a/src/main/persistence/applying-settings/terminal-settings-migrations.ts b/src/main/persistence/applying-settings/terminal-settings-migrations.ts index 9264e9db532..de75428d2d0 100644 --- a/src/main/persistence/applying-settings/terminal-settings-migrations.ts +++ b/src/main/persistence/applying-settings/terminal-settings-migrations.ts @@ -12,7 +12,7 @@ import { normalizeTuiAgentEnvRecord } from '../../../shared/agent-launch/choices/tui-agent-launch-defaults' import { expandLeadingHomePath } from '../../filesystem/home-path-expansion' -import { normalizeWorkspaceDirInput } from '../../../shared/worktree/workspace-dir-input' +import { normalizeWorkspaceDirInput } from '../../../shared/worktree/paths/workspace-dir-input' /** A raw ~ or padded absolute path resolves inside each repo (#34944, STA-14308); normalize at the store boundary. */ export function normalizeWorkspaceDirSetting( diff --git a/src/main/persistence/applying-settings/ui-state-read.ts b/src/main/persistence/applying-settings/ui-state-read.ts index a550fb1cf37..db303f4eea9 100644 --- a/src/main/persistence/applying-settings/ui-state-read.ts +++ b/src/main/persistence/applying-settings/ui-state-read.ts @@ -1,11 +1,8 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-listing/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' -import { - getDefaultUIState, - normalizeAgentActivityDisplayMode, - normalizeWorktreeCardProperties -} from '../../../shared/constants' +import { getDefaultUIState, normalizeAgentActivityDisplayMode } from '../../../shared/constants' +import { normalizeWorktreeCardProperties } from '../../../shared/worktree/row-display/card-properties' import { normalizeWorkspaceStatuses, clampWorkspaceBoardColumnWidth, diff --git a/src/main/persistence/applying-settings/ui-state-update.ts b/src/main/persistence/applying-settings/ui-state-update.ts index eb282c1c973..a80b59268f2 100644 --- a/src/main/persistence/applying-settings/ui-state-update.ts +++ b/src/main/persistence/applying-settings/ui-state-update.ts @@ -1,11 +1,8 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-listing/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' -import { - getDefaultUIState, - normalizeAgentActivityDisplayMode, - normalizeWorktreeCardProperties -} from '../../../shared/constants' +import { getDefaultUIState, normalizeAgentActivityDisplayMode } from '../../../shared/constants' +import { normalizeWorktreeCardProperties } from '../../../shared/worktree/row-display/card-properties' import { normalizeWorkspaceStatuses, clampWorkspaceBoardColumnWidth, diff --git a/src/main/persistence/closed-terminal-tab-write-fence.test.ts b/src/main/persistence/closed-terminal-tab-write-fence.test.ts index 9f637850ea5..61c37a856b9 100644 --- a/src/main/persistence/closed-terminal-tab-write-fence.test.ts +++ b/src/main/persistence/closed-terminal-tab-write-fence.test.ts @@ -14,7 +14,7 @@ import { WORKTREE_PATH, makeSession } from '../runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' -import { advanceTerminalTopologyRevision } from './terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from './terminal-topology/pane-ownership/terminal-topology-membership' const SSH_HOST_ID = 'ssh:target-1' const SSH_WORKTREE_ID = 'ssh-repo::/srv/app' @@ -148,36 +148,4 @@ describe('a write cannot bring back a tab its partition recorded as closed (#124 OTHER_TAB_ID ]) }) - - it.each(['set', 'stage-before-unload'] as const)( - 'accepts a browser-only host slice once the partition has a close record (%s)', - async (write) => { - const { store, runtime } = createPersistedStore() - store.setWorkspaceSession( - { ...getDefaultWorkspaceSession(), tabsByWorktree: { [SSH_WORKTREE_ID]: [] } }, - SSH_HOST_ID - ) - await runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: SSH_WORKTREE_ID, - target: { kind: 'tab', tabId: TAB_ID } - }) - const { - tabsByWorktree: _omitted, - terminalLayoutsByTabId: _alsoOmitted, - ...slice - } = { ...getDefaultWorkspaceSession(), activeWorktreeId: SSH_WORKTREE_ID } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: models the renderer's host split, which omits empty terminal maps from its IPC payload. - const sparse = slice as WorkspaceSessionState - - if (write === 'set') { - store.setWorkspaceSession(sparse, SSH_HOST_ID) - } else { - store.stageWorkspaceSessionBeforeUnload(sparse, SSH_HOST_ID) - } - - const after = store.getWorkspaceSession(SSH_HOST_ID) - expect(after.activeWorktreeId).toBe(SSH_WORKTREE_ID) - expect(after.closedTerminalTabTombstonesByTabId?.[TAB_ID]).toBeDefined() - } - ) }) diff --git a/src/main/persistence/closed-terminal-tab-write-fence.ts b/src/main/persistence/closed-terminal-tab-write-fence.ts index 71e129ded6c..d085f419d84 100644 --- a/src/main/persistence/closed-terminal-tab-write-fence.ts +++ b/src/main/persistence/closed-terminal-tab-write-fence.ts @@ -1,4 +1,4 @@ -import { hasClosedTerminalTabRecord } from '../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { closeTerminalTabInWorkspaceSession, workspaceSessionListsTerminalTab diff --git a/src/main/persistence/host-qualified-worktree-meta.ts b/src/main/persistence/host-qualified-worktree-meta.ts index 0ce97c1ff14..4cab1d6d276 100644 --- a/src/main/persistence/host-qualified-worktree-meta.ts +++ b/src/main/persistence/host-qualified-worktree-meta.ts @@ -7,7 +7,7 @@ import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' -import { isLocalOnlyWorktreeMetaId } from '../../shared/worktree/local-only-worktree-meta-ids' +import { isLocalOnlyWorktreeMetaId } from '../../shared/worktree/metadata/local-only-worktree-meta-ids' import type { Repo } from '../../shared/repo-types' import type { WorktreeMeta } from '../../shared/worktree/meta-types' import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' diff --git a/src/main/persistence/terminal-topology/persistence-ssh-pending-pty-kill.test.ts b/src/main/persistence/leasing-ssh-ptys/persistence-ssh-pending-pty-kill.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-ssh-pending-pty-kill.test.ts rename to src/main/persistence/leasing-ssh-ptys/persistence-ssh-pending-pty-kill.test.ts diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts b/src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts similarity index 77% rename from src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts rename to src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts index 535a691065d..590d1853630 100644 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts +++ b/src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts @@ -1,17 +1,16 @@ import { closeTestStores, testState, - createStore, - createStoreWithSshRemotePtyLeases, - writeDataFile + type createStore, + createStoreWithSshRemotePtyLeases } from '../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { getDefaultPersistedState } from '../../../shared/constants' -import { sshRemotePtyLeaseAllowsReattach } from '../../../shared/ssh-types' +import '../../../shared/constants' +import '../../../shared/ssh-types' import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' import { PtyExitProof } from '../../pty/process-retirement/pty-exit-proof' @@ -202,50 +201,3 @@ describe('Store', () => { expect(session.terminalLayoutsByTabId.tab1.ptyIdsByLeafId).toEqual({}) }) }) - -// Round-trip retirement marks through the strict loader; older rows omit them and older builds ignore them. -describe('ssh remote pty lease route-retirement marks survive the disk round trip', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - }) - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - function persistLeases(leases: unknown[]): void { - const persisted = getDefaultPersistedState(testState.dir) - writeDataFile({ ...persisted, sshRemotePtyLeases: leases }) - } - - it('salvages both marks rather than stripping them', async () => { - persistLeases([ - { - targetId: 'ssh-1', - ptyId: 'pty-1', - state: 'expired', - createdAt: 1, - updatedAt: 2, - supersededBy: 'pty-2' - }, - { - targetId: 'ssh-1', - ptyId: 'pty-3', - state: 'expired', - createdAt: 1, - updatedAt: 2, - relayIdRecycled: true - } - ]) - - const store = await createStore() - - expect(store.getSshRemotePtyLeases('ssh-1')).toEqual([ - expect.objectContaining({ ptyId: 'pty-1', supersededBy: 'pty-2' }), - expect.objectContaining({ ptyId: 'pty-3', relayIdRecycled: true }) - ]) - expect(store.getSshRemotePtyLeases('ssh-1').filter(sshRemotePtyLeaseAllowsReattach)).toEqual([]) - }) - - // Missing retirement marks on older rows must preserve reattachability. -}) diff --git a/src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts b/src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts index 0d736878dbb..04eef116f51 100644 --- a/src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts +++ b/src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts @@ -15,7 +15,7 @@ import { import { migrateAutomationHostFilterSshTargetId, migrateAutomationsForSshReadoption -} from '../../automations/automation-ssh-readoption-migration' +} from '../../automations/ownership/automation-ssh-readoption-migration' import { automationIdsPinnedToSshTarget } from '../scheduling-automations/automation-owner-projection' import { reassignCanonicalWorktreeMetadataHost } from './canonical-worktree-host-reassignment' diff --git a/src/main/persistence/loading-store/automation-state/automation-enablement-transitions.ts b/src/main/persistence/loading-store/automation-state/automation-enablement-transitions.ts index b149bc63db7..c7d6f40fc0b 100644 --- a/src/main/persistence/loading-store/automation-state/automation-enablement-transitions.ts +++ b/src/main/persistence/loading-store/automation-state/automation-enablement-transitions.ts @@ -21,4 +21,21 @@ export class AutomationEnablementTransitions { } return updated } + + /** `track` for a batch: counts each updated row whose `enabled` flipped. */ + trackMany( + stored: readonly Automation[], + update: () => R[] + ): R[] { + const wasEnabled = new Map(stored.map((entry) => [entry.id, entry.enabled])) + const results = update() + for (const result of results) { + const before = wasEnabled.get(result.id) + if (result.automation && before !== undefined && result.automation.enabled !== before) { + this.counts.set(result.id, this.revision(result.id) + 1) + wasEnabled.set(result.id, result.automation.enabled) + } + } + return results + } } diff --git a/src/main/persistence/loading-store/automation-state/automation-persistence.ts b/src/main/persistence/loading-store/automation-state/automation-persistence.ts index f8f719ced03..7704e845f3b 100644 --- a/src/main/persistence/loading-store/automation-state/automation-persistence.ts +++ b/src/main/persistence/loading-store/automation-state/automation-persistence.ts @@ -35,6 +35,11 @@ import { type AutomationDefinitionOperations } from '../../scheduling-automations/automation-definition-operations' import { deleteAutomation as deleteAutomationOperation } from '../../scheduling-automations/automation-definition-removal' +import { + updateAutomations as updateAutomationsOperation, + type AutomationBatchUpdate, + type AutomationBatchUpdateResult +} from '../../scheduling-automations/automation-definition-update' import { createAutomationRun as createAutomationRunOperation, listAutomationRuns as listAutomationRunsOperation, @@ -170,6 +175,14 @@ export class AutomationPersistence { ) } + /** `updateAutomation` for many rows with one list write and one flush. */ + updateAutomations(batch: readonly AutomationBatchUpdate[]): AutomationBatchUpdateResult[] { + const stored = this[automationPersistenceContext].runtime.state.automations ?? [] + return this[automationEnablement].trackMany(stored, () => + updateAutomationsOperation(getAutomationDefinitionOperations(this), batch) + ) + } + /** Changes when an update pauses or re-enables the automation, never on run bookkeeping. */ automationEnablementRevision(id: string): number { return this[automationEnablement].revision(id) diff --git a/src/main/persistence/loading-store/profile-loading/loaded-cohort-migrations.ts b/src/main/persistence/loading-store/profile-loading/loaded-cohort-migrations.ts index c68fceba6ab..16a37f742f5 100644 --- a/src/main/persistence/loading-store/profile-loading/loaded-cohort-migrations.ts +++ b/src/main/persistence/loading-store/profile-loading/loaded-cohort-migrations.ts @@ -1,4 +1,4 @@ -import { randomInt, randomUUID } from 'node:crypto' +import { randomUUID } from 'node:crypto' import type { PersistedState } from '../../../../shared/persisted-state-types' import { parseChatUiLaunchTipAudience, @@ -164,16 +164,10 @@ export class LoadedCohortMigrationOperations { ) { return state } - // Resolve cohort once so partial new-user state cannot change its default mid-migration. const resolvedExistedBefore = typeof existing?.existedBeforeTelemetryRelease === 'boolean' ? existing.existedBeforeTelemetryRelease : fileExistedOnLoad - const onboardingLanguageCohort = !fileExistedOnLoad - ? randomInt(2) === 0 - ? 'control' - : 'treatment' - : undefined this.runtime.loadNeedsSave = true return { ...state, @@ -181,7 +175,6 @@ export class LoadedCohortMigrationOperations { ...state.settings, telemetry: { ...existing, - ...(onboardingLanguageCohort ? { onboardingLanguageCohort } : {}), existedBeforeTelemetryRelease: resolvedExistedBefore, // Preserve explicit true, false and null; only absence uses the cohort default. optedIn: diff --git a/src/main/persistence/loading-store/profile-loading/loaded-state-parsing.ts b/src/main/persistence/loading-store/profile-loading/loaded-state-parsing.ts index b0da8b65e4e..b934f9e7e35 100644 --- a/src/main/persistence/loading-store/profile-loading/loaded-state-parsing.ts +++ b/src/main/persistence/loading-store/profile-loading/loaded-state-parsing.ts @@ -9,7 +9,7 @@ import { pruneLocalTerminalScrollbackBuffers } from '../../../../shared/workspac import { pruneWorkspaceSessionBrowserHistory } from '../../../../shared/workspace-session/workspace-session-browser-history' import { clearMissingProjectGroupMemberships } from '../../../../shared/project-groups' import { migrateWorkspaceSessionTerminalScrollbackSnapshots } from '../../../pty/scrollback/terminal-scrollback-snapshots' -import { logStartupMilestone } from '../../../startup/startup-diagnostics' +import { logStartupMilestone } from '../../../startup/diagnostics/startup-diagnostics' import { PROTECTED_SECRET_SLOT, sshPtyOwnerLeaseSecretSlot @@ -25,7 +25,7 @@ import { normalizeWorktreeLinkedItemMetadata } from '../../tracking-repos/worktree-metadata-normalization' import { backfillLegacyAutomationContexts } from '../../scheduling-automations/automation-context-migration' -import { migrateAutomationOwners } from '../../../automations/automation-owner-migration' +import { migrateAutomationOwners } from '../../../automations/ownership/automation-owner-migration' import { ENCRYPTED_SSH_PTY_OWNER_LEASE_MAX_LENGTH, normalizeSshPtyConsumerRecovery diff --git a/src/main/persistence/loading-store/profile-loading/normalize-loaded-global-settings.ts b/src/main/persistence/loading-store/profile-loading/normalize-loaded-global-settings.ts index 86ca2b8b9cf..76e3b3ce913 100644 --- a/src/main/persistence/loading-store/profile-loading/normalize-loaded-global-settings.ts +++ b/src/main/persistence/loading-store/profile-loading/normalize-loaded-global-settings.ts @@ -23,6 +23,7 @@ import { } from '../../applying-settings/terminal-settings-migrations' import { readLegacySidekickFlag } from '../../applying-settings/onboarding-normalization' import { normalizeMachineName } from '../../../../shared/machine-name' +import { normalizeWorkspaceCleanupRules } from '../../../../shared/workspace-cleanup/workspace-cleanup-policy' import { replaceRetiredSpeechModelId } from '../../../speech/model-catalog' import type { PersistedState } from '../../../../shared/persisted-state-types' import type { VoiceSettings } from '../../../../shared/speech-types' @@ -98,6 +99,7 @@ export function normalizeLoadedGlobalSettings( parsed.settings?.nativeChatAppearance ), worktreeVisibilityDefaults: migratedExternalVisibility.defaults, + workspaceCleanupPolicy: normalizeWorkspaceCleanupRules(parsed.settings?.workspaceCleanupPolicy), prBotAuthorOverrides: normalizePRBotAuthorOverrides(parsed.settings?.prBotAuthorOverrides), // Only fresh profiles take the on default; a stored profile saved before the key existed was off. artifactSharingEnabled: parsed.settings?.artifactSharingEnabled === true, diff --git a/src/main/persistence/loading-store/profile-loading/normalize-loaded-profile-state.ts b/src/main/persistence/loading-store/profile-loading/normalize-loaded-profile-state.ts index 524453fc6d3..5183f7592cd 100644 --- a/src/main/persistence/loading-store/profile-loading/normalize-loaded-profile-state.ts +++ b/src/main/persistence/loading-store/profile-loading/normalize-loaded-profile-state.ts @@ -8,7 +8,7 @@ import { normalizeOrcadMigrationImportReceipts } from '../../../../shared/orcad- import { normalizeOrcadMigrationStagedCatalogs } from '../../../../shared/orcad-migration/orcad-migration-staged-catalog-validation' import { normalizeWorkspaceLineageByChildKey } from '../../applying-settings/ui-interaction-merge' import { dropInferredParentsOverFolderParents } from '../workspace-lineage/folder-parent-lineage-persistence' -import { normalizeCrossStoreLineageByChildKey } from '../../../../shared/worktree/cross-store-lineage-records' +import { normalizeCrossStoreLineageByChildKey } from '../../../../shared/worktree/lineage/cross-store-lineage-records' import { normalizeSshRemotePtyLease, normalizeSshTarget diff --git a/src/main/persistence/loading-store/profile-loading/normalize-loaded-ui-state.ts b/src/main/persistence/loading-store/profile-loading/normalize-loaded-ui-state.ts index ca3bfb5cea3..6f8d328d320 100644 --- a/src/main/persistence/loading-store/profile-loading/normalize-loaded-ui-state.ts +++ b/src/main/persistence/loading-store/profile-loading/normalize-loaded-ui-state.ts @@ -7,7 +7,7 @@ import { isCurrentCompactWorktreeCardProperties, isDefaultedCompactWorktreeCardProperties, normalizeWorktreeCardProperties -} from '../../../../shared/worktree/card-properties' +} from '../../../../shared/worktree/row-display/card-properties' import { isExistingPersistedProfile } from '../../../../shared/project-order-manual-default-notice' import { resolveUsagePercentageDisplayChangeNoticeDismissed } from '../../../../shared/usage-percentage-display-change-notice' import { normalizePersistedWorkspaceStatuses } from '../../../../shared/workspace-statuses' diff --git a/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts b/src/main/persistence/loading-store/profile-loading/persistence-floating-workspace-trust-load.test.ts similarity index 94% rename from src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts rename to src/main/persistence/loading-store/profile-loading/persistence-floating-workspace-trust-load.test.ts index 530e7c5a9b6..bdc9f7bd55f 100644 --- a/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts +++ b/src/main/persistence/loading-store/profile-loading/persistence-floating-workspace-trust-load.test.ts @@ -5,7 +5,7 @@ import { writeDataFile, readDataFile, symlinkDirectorySync -} from '../persistence-test-harness' +} from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync, mkdirSync, realpathSync } from 'node:fs' import { join } from 'node:path' @@ -16,7 +16,7 @@ const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -42,11 +42,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/loading-store/profile-preferences/profile-preferences.ts b/src/main/persistence/loading-store/profile-preferences/profile-preferences.ts index d7059b79b1b..0b6b17f52a7 100644 --- a/src/main/persistence/loading-store/profile-preferences/profile-preferences.ts +++ b/src/main/persistence/loading-store/profile-preferences/profile-preferences.ts @@ -1,3 +1,4 @@ +import { normalizeFeatureTipIds } from '../../../../shared/feature-tips' import type { GlobalSettings } from '../../../../shared/global-settings-types' import { retireAtRestCommandSettings } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { createAgentModelCatalogSettingsExpiry } from '../../../native-chat/agent-model-catalog/agent-model-catalog-account-expiry' @@ -145,6 +146,12 @@ export class ProfilePreferences { return this.getSettings() } + getFeatureTipsSeenIds(): string[] { + return normalizeFeatureTipIds( + this[profilePreferencesContext].runtime.state.ui?.featureTipsSeenIds + ) + } + getUI(): PersistedState['ui'] { return getPersistedUI( this[profilePreferencesContext].runtime.state, diff --git a/src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts b/src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts index 93aad9d2e4b..a75cbecedd2 100644 --- a/src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts +++ b/src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts @@ -13,7 +13,7 @@ import { } from '../../../credentials/protected-secret-persistence' import { stripRetiredGlobalSettings } from '../../applying-settings/terminal-settings-migrations' import { LEGACY_OPENCODE_GO_API_KEY_SLOT } from '../profile-loading/legacy-opencode-go-api-key-migration' -import { omitDefaultWorktreeMetaFieldsInMap } from '../../../../shared/worktree/meta-persisted-defaults' +import { omitDefaultWorktreeMetaFieldsInMap } from '../../../../shared/worktree/metadata/meta-persisted-defaults' import { projectWorktreeMetaByIdentityOntoLocators } from '../worktree-metadata/worktree-meta-alias-projection' import { withoutRedundantPartitionGlobals } from '../../../../shared/workspace-session/workspace-session-host-field-ownership' import { WORKTREE_METADATA_DOMAINS } from '../../profile-save-domains' diff --git a/src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts b/src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts index 6e4ba7b17cc..8f0b22c7b99 100644 --- a/src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts +++ b/src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts @@ -3,7 +3,6 @@ import { REMOVE_PROJECT_DOMAINS, REPO_CATALOG_DOMAINS } from '../../profile-save import type { ProjectHostSetup, ProjectHostSetupUpdateArgs } from '../../../../shared/project-types' import type { Repo } from '../../../../shared/repo-types' import type { RepoHostTarget } from '../../../../shared/repo-host-identity' -import type { GhAccountBinding } from '../../../../shared/github/account-binding' import { removeRepoFromHostWorkspaceSessions, removeRepoFromWorkspaceSession @@ -13,7 +12,7 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import { mergeProjectHostSetupCompatibilityState } from '../../tracking-repos/project-host-compatibility' +import { applyProjectHostSetupCompatibilityState } from '../../tracking-repos/project-host-compatibility' import { RepoOrderPersistenceOperations } from '../../tracking-repos/repo-order-operations' import { pruneWorktreeStateForRepo as pruneWorktreeStateForRepoOperation } from '../../tracking-repos/repo-worktree-pruning' import { collectDeregisteredRepoIds } from '../../tracking-repos/deregistered-repo-residue' @@ -171,43 +170,7 @@ export class RepoLifecycleOperations { updateRepo( target: RepoHostTarget, - updates: Partial< - Pick< - Repo, - | 'displayName' - | 'badgeColor' - | 'repoIcon' - | 'upstream' - | 'gitRemoteIdentity' - | 'defaultJiraProject' - | 'hookSettings' - | 'editorFormatter' - | 'worktreeBaseRef' - | 'worktreeBasePath' - | 'kind' - | 'folderUpgradeGitRootPath' - | 'executionHostId' - | 'symlinkPaths' - | 'dictationTerms' - | 'issueSourcePreference' - | 'forkSyncMode' - | 'agentWorkspaceTrust' - | 'externalWorktreeVisibilityPromptDismissedAt' - | 'externalWorktreeInboxBaselinePaths' - | 'importedExternalWorktreePaths' - | 'customWorktreeVisibilitySources' - | 'worktreeVisibilitySourcePreferences' - | 'projectGroupId' - | 'projectHostSetupMethod' - > - > & { - projectGroupOrder?: number | null - externalWorktreeVisibility?: Repo['externalWorktreeVisibility'] | null - agentWorktreeVisibility?: Repo['agentWorktreeVisibility'] | null - sourceControlAi?: Repo['sourceControlAi'] | null - externalWorktreeDiscoverySuppressedAt?: Repo['externalWorktreeDiscoverySuppressedAt'] | null - ghAccount?: GhAccountBinding | null - } + updates: Parameters[1] ): Repo | null { return getRepoUpdateOperations(this).updateRepo(target, updates) } @@ -282,13 +245,8 @@ export function getRepoUpdateOperations( } export function syncProjectHostSetupCompatibilityState(owner: RepoLifecycleOperations): void { - const compatibilityState = mergeProjectHostSetupCompatibilityState( - owner[repoLifecycleOperationsContext].runtime.state, - owner[repoLifecycleOperationsContext].runtime.state.repos - ) - owner[repoLifecycleOperationsContext].runtime.state.projects = compatibilityState.projects - owner[repoLifecycleOperationsContext].runtime.state.projectHostSetups = - compatibilityState.projectHostSetups + const state = owner[repoLifecycleOperationsContext].runtime.state + applyProjectHostSetupCompatibilityState(state, state.repos) } export function getProjectHostSetupOperations( diff --git a/src/main/persistence/loading-store/project-catalog/retired-name-registry-normalization.ts b/src/main/persistence/loading-store/project-catalog/retired-name-registry-normalization.ts index 53f77421d23..5bc2389468d 100644 --- a/src/main/persistence/loading-store/project-catalog/retired-name-registry-normalization.ts +++ b/src/main/persistence/loading-store/project-catalog/retired-name-registry-normalization.ts @@ -4,7 +4,7 @@ import { compactRetiredNames, isEmptyRetiredNameRegistry, type RetiredNameRegistry -} from '../../../../shared/worktree/retired-name-registry' +} from '../../../../shared/worktree/naming/retired-name-registry' function normalizeRetiredNameRegistry(row: unknown): RetiredNameRegistry { const isPlainArray = Array.isArray(row) diff --git a/src/main/persistence/loading-store/project-catalog/retired-worktree-name-persistence.ts b/src/main/persistence/loading-store/project-catalog/retired-worktree-name-persistence.ts index becfdc90cd6..941a42dc969 100644 --- a/src/main/persistence/loading-store/project-catalog/retired-worktree-name-persistence.ts +++ b/src/main/persistence/loading-store/project-catalog/retired-worktree-name-persistence.ts @@ -4,7 +4,7 @@ import { addRetiredNames, EMPTY_RETIRED_NAME_REGISTRY, type RetiredNameRegistry -} from '../../../../shared/worktree/retired-name-registry' +} from '../../../../shared/worktree/naming/retired-name-registry' import type { StoreRuntimeState } from '../store-runtime-state' import type { WriteSchedulingOperations } from '../profile-writing/write-scheduling' import { scheduleSave } from '../profile-writing/write-scheduling' diff --git a/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts b/src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts similarity index 96% rename from src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts rename to src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts index 8b3d420c0b6..86e4ce73394 100644 --- a/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts +++ b/src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts @@ -3,21 +3,21 @@ import { createStore, registerWorkspaceRepos, testState -} from '../persistence-test-harness' +} from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -43,11 +43,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts b/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts similarity index 92% rename from src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts rename to src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts index 2673cdb3ece..56c848a5617 100644 --- a/src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts +++ b/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts @@ -1,20 +1,20 @@ -import { closeTestStores, createStore, testState } from '../persistence-test-harness' +import { closeTestStores, createStore, testState } from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' -import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { ProfileStateSqliteAuthority } from '../../profile-state/profile-state-sqlite-authority' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -40,11 +40,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-fast-lane.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-fast-lane.ts index d12bab2b05d..68e2df2529e 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-fast-lane.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-fast-lane.ts @@ -1,7 +1,7 @@ import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import '../../restoring-sessions/terminal-layout-normalization' -import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { tabRowPtyIdAfterLeafBinding } from './terminal-tab-pty-ownership' /** not_durable alone means memory matches and only the debounced save remains. */ diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts index 24c6ce90af0..e11a0b98c5d 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts @@ -14,7 +14,7 @@ import { resolveHostId, type SessionHostPartitionOperations } from '../workspace import { withdrawUnstartedPane, type UnstartedPaneKept -} from '../../terminal-topology/unstarted-pane-withdraw' +} from '../../terminal-topology/pane-admission/unstarted-pane-withdraw' import { evaluatePtyBindingFastLane } from './pty-binding-fast-lane' import { durabilityOnlyBindingResult, isDurabilityOnlyMatch } from './pty-binding-durability-only' import { ptyBindingIsRefused } from './pty-binding-refusals' @@ -26,11 +26,11 @@ import { type PtyBindingOrigin, type PtyBindingSpan } from './pty-binding-span' -import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' import type { TerminalLeafMoveRequest, TerminalLeafMoveResult -} from '../../../../shared/workspace-layout/terminal-leaf-move' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import { admitPane, moveLeaf, @@ -41,7 +41,7 @@ import { import type { TerminalPaneAdmission, TerminalPaneAdmissionOutcome -} from '../../terminal-topology/terminal-pane-admission' +} from '../../terminal-topology/pane-admission/terminal-pane-admission' import type { CommandOf, LayoutRefusalCode diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts index 483bbc42954..1a8dd2f463f 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts @@ -1,12 +1,12 @@ -import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import type { TerminalSessionPartition } from '../../../../shared/workspace-layout/terminal-owner-invariants' +import type { TerminalSessionPartition } from '../../../../shared/workspace-layout/terminal-topology/terminal-owner-invariants' import '../../restoring-sessions/terminal-layout-normalization' -import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import type { PtyBindingSourceExpectation } from '../store' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { isClosedPaneFenced } from '../../terminal-topology/closed-pane-binding-fence' +import { isClosedPaneFenced } from '../../terminal-topology/pane-ownership/closed-pane-binding-fence' export type PtyBindingRefusalRequest = { tabId: string diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts index a738f44bd5c..786d0f983a8 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts @@ -2,10 +2,10 @@ import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pan import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import { cloneLayoutNode } from '../../restoring-sessions/terminal-layout-normalization' -import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { createMinimalPersistedTerminalTab } from '../../restoring-sessions/session-owner-fields' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { placedSplitRoot } from '../../terminal-topology/terminal-pane-placement-graft' +import { placedSplitRoot } from '../../terminal-topology/pane-admission/terminal-pane-placement-graft' import { tabRowPtyIdAfterLeafBinding } from './terminal-tab-pty-ownership' import type { PersistPtyBindingArgs } from './pty-binding-persistence' import { reusedTerminalIdUnbinding } from './reused-terminal-id-unbind' diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts index ae7d27904cf..89325a8ad30 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts @@ -3,13 +3,13 @@ import type { PtyBindingFastLaneMiss } from './pty-binding-fast-lane' import { terminalPanePlacementAgreement, type TerminalPanePlacementAgreement -} from '../../terminal-topology/terminal-pane-placement-agreement' +} from '../../terminal-topology/pane-admission/terminal-pane-placement-agreement' import { findTerminalBindingConflict, type TerminalOwnerConflictReason -} from '../../../../shared/workspace-layout/terminal-owner-invariants' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-owner-invariants' import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' export type PtyBindingPath = 'durable_match' | 'durability_only' | 'mutation' diff --git a/src/main/persistence/loading-store/terminal-bindings/terminal-binding-recovery.ts b/src/main/persistence/loading-store/terminal-bindings/terminal-binding-recovery.ts index 229fc654670..85f9648c137 100644 --- a/src/main/persistence/loading-store/terminal-bindings/terminal-binding-recovery.ts +++ b/src/main/persistence/loading-store/terminal-bindings/terminal-binding-recovery.ts @@ -1,6 +1,5 @@ import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' import type { SshRemotePtyLease } from '../../../../shared/ssh-types' -import '../../../providers/ssh-pty-id' import { toComparableRelaySshPtyId, toRelaySshPtyId } from '../../../../shared/ssh-pty-id' import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' diff --git a/src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts b/src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts deleted file mode 100644 index 7d920f44371..00000000000 --- a/src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import { _resetClosedPaneFencesForTests } from '../../terminal-topology/closed-pane-binding-fence' -import { fixture } from '../profile-writing/profile-state-delayed-authority-fixture' -import { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' - -vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: () => ({ nth_repo_added: 2 }) -})) -vi.mock('../../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -// Clear process-wide close fences because these tests reuse pane IDs. -beforeEach(_resetClosedPaneFencesForTests) - -const binding = { - worktreeId: 'repo-local::/fixture/local', - tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', - ptyId: 'closing-pty', - incarnationId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' -} -const siblingLeafId = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd' - -class CloseRuntime extends OrcaRuntimeService { - async closeHeadlessTab(): Promise { - const snapshot = this.mobileSessionTabsByWorktree.get(binding.worktreeId) - const tab = snapshot?.tabs[0] - if (!snapshot || tab?.type !== 'terminal') { - throw new Error('missing test tab') - } - await this.closeHeadlessMobileTerminalTab(binding.worktreeId, snapshot, tab) - } - publish(): void { - const snapshot: RuntimeMobileSessionTabsSnapshot = { - worktree: binding.worktreeId, - publicationEpoch: 'close-test', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: `${binding.tabId}::${binding.leafId}`, - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: `${binding.tabId}::${binding.leafId}`, - parentTabId: binding.tabId, - leafId: binding.leafId, - ptyId: binding.ptyId, - title: 'Terminal', - isActive: true - } - ] - } - this.storeMobileSessionSnapshot(binding.worktreeId, snapshot) - } -} - -async function closeFixture(options: { split?: boolean } = {}) { - const result = await fixture() - await result.store.persistPtyBinding(binding) - if (options.split) { - await result.store.persistPtyBinding({ - ...binding, - leafId: siblingLeafId, - ptyId: 'sibling-pty', - incarnationId: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', - expectedSourceBinding: binding - }) - } - const runtime = new CloseRuntime(result.store) - const kill = vi.fn(() => true) - runtime.setPtyController({ write: () => true, kill, getForegroundProcess: async () => null }) - return { - ...result, - runtime, - kill, - persistedLeafIds: () => - Object.keys( - result.readState().workspaceSession.terminalLayoutsByTabId[binding.tabId]?.ptyIdsByLeafId ?? - {} - ), - liveLeafIds: () => - Object.keys( - result.store.getWorkspaceSession().terminalLayoutsByTabId[binding.tabId]?.ptyIdsByLeafId ?? - {} - ) - } -} - -it.each([ - ['tab', { kind: 'tab' as const, tabId: binding.tabId }, []], - [ - 'split pane', - { kind: 'pane' as const, tabId: binding.tabId, leafId: binding.leafId }, - [siblingLeafId] - ] -])('acknowledges a renderer %s close only once it is durable', async (kind, target, remaining) => { - const { authority, runtime, persistedLeafIds } = await closeFixture({ split: kind !== 'tab' }) - const before = persistedLeafIds() - const gate = authority.pause() - let acknowledged = false - const closing = runtime - .closeTerminalSurfaceFromRenderer({ worktreeId: binding.worktreeId, target: target }) - .then(() => { - acknowledged = true - }) - try { - await Promise.race([gate.started.promise, closing]) - expect(acknowledged).toBe(false) - expect(persistedLeafIds()).toEqual(before) - } finally { - gate.finish.resolve() - } - await closing - expect(persistedLeafIds()).toEqual(remaining) -}) - -it('commits a renderer tab close whose split pane bound while the close waited for the writer', async () => { - const { authority, store, runtime, persistedLeafIds, liveLeafIds } = await closeFixture() - const gate = authority.pause() - const session = store.getWorkspaceSession() - store.setWorkspaceSession({ ...session, activeTabIdByWorktree: { [binding.worktreeId]: null } }) - const earlierWrite = store.flushPendingOrThrowAsync() - await gate.started.promise - // Queue the split before close executes to test a sibling added after capture. - const split = store.persistPtyBinding({ - ...binding, - leafId: siblingLeafId, - ptyId: 'sibling-pty', - incarnationId: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', - expectedSourceBinding: binding - }) - const closing = runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: binding.worktreeId, - target: { - kind: 'tab', - tabId: binding.tabId - } - }) - gate.finish.resolve() - await earlierWrite - await expect(split).resolves.toBe(true) - await expect(closing).resolves.toBeUndefined() - - expect(persistedLeafIds()).toEqual([]) - expect(liveLeafIds()).toEqual([]) - expect( - store - .getWorkspaceSession() - .tabsByWorktree[binding.worktreeId]?.some((tab) => tab.id === binding.tabId) - ).toBe(false) - expect(store.getWorkspaceSession().closedTerminalTabTombstonesByTabId?.[binding.tabId]).toEqual( - expect.objectContaining({ worktreeId: binding.worktreeId, reason: 'user' }) - ) -}) diff --git a/src/main/persistence/loading-store/workspace-lineage/cross-store-lineage-persistence.ts b/src/main/persistence/loading-store/workspace-lineage/cross-store-lineage-persistence.ts index 650ec9dcc26..0d34ad491c4 100644 --- a/src/main/persistence/loading-store/workspace-lineage/cross-store-lineage-persistence.ts +++ b/src/main/persistence/loading-store/workspace-lineage/cross-store-lineage-persistence.ts @@ -7,7 +7,7 @@ import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { isCrossStoreWorkspaceLineage, validCrossStoreLineage -} from '../../../../shared/worktree/cross-store-lineage-records' +} from '../../../../shared/worktree/lineage/cross-store-lineage-records' import { ownsRawIdBucket } from './metadata-lineage-operations' import type { StoreRuntimeState } from '../store-runtime-state' import { type WriteSchedulingOperations, scheduleSave } from '../profile-writing/write-scheduling' diff --git a/src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts b/src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts index 597226341b1..81c9af4a863 100644 --- a/src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts +++ b/src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts @@ -2,7 +2,7 @@ import type { WorkspaceAttachmentMutation } from '../../../../shared/workspace-a import type { DiffCommentBaseMutation } from '../../../../shared/diff-comment-mutation' import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' -import { toWorkspaceLineageRow } from '../../../../shared/worktree/worktree-lineage-workspace-row' +import { toWorkspaceLineageRow } from '../../../../shared/worktree/lineage/worktree-lineage-workspace-row' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { Repo } from '../../../../shared/repo-types' import type { ExecutionHostId } from '../../../../shared/execution-host' diff --git a/src/main/persistence/loading-store/workspace-sessions/layout-editor-views.ts b/src/main/persistence/loading-store/workspace-sessions/layout-editor-views.ts index 5c4e0a6ed31..48d27a780d9 100644 --- a/src/main/persistence/loading-store/workspace-sessions/layout-editor-views.ts +++ b/src/main/persistence/loading-store/workspace-sessions/layout-editor-views.ts @@ -6,7 +6,7 @@ import { type ExecutionHostId } from '../../../../shared/execution-host' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import type { LayoutEditorView } from '../../../../shared/workspace-layout/layout-editor-view' +import type { LayoutEditorView } from '../../../../shared/workspace-layout/editor-tabs/layout-editor-view' import type { WorkspaceLayoutModel } from '../../../../shared/workspace-layout/workspace-layout-model' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { StoreRuntimeState } from '../store-runtime-state' diff --git a/src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts b/src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts similarity index 94% rename from src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts rename to src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts index 9894605d808..e35067540d2 100644 --- a/src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts +++ b/src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts @@ -3,19 +3,19 @@ import { testState, createStore, createStoreWithSshRemotePtyLeases -} from '../persistence-test-harness' +} from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { TEST_LEAF_1 } from '../persistence-session-fixtures' +import { TEST_LEAF_1 } from '../../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -41,11 +41,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) @@ -133,7 +133,7 @@ describe('Store', () => { [TEST_LEAF_1]: expect.stringMatching(/^v1-[0-9a-f]{32}$/) }) const ref = layout.scrollbackRefsByLeafId?.[TEST_LEAF_1] - expect(ref ? store.readTerminalScrollbackSnapshot(ref) : null).toBe('Current buffer') + expect(ref ? await store.readTerminalScrollbackSnapshotAsync(ref) : null).toBe('Current buffer') expect(layout.titlesByLeafId).toEqual({ [TEST_LEAF_1]: 'Current' }) expect(session.tabsByWorktree.wt1[0].ptyId).toBe('daemon-pty') }) diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts b/src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts similarity index 87% rename from src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts rename to src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts index b1f823fc82e..eaf4b24a8a3 100644 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts +++ b/src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts @@ -1,17 +1,17 @@ -import { closeTestStores, testState, createStore } from '../persistence-test-harness' +import { closeTestStores, testState, createStore } from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { TEST_LEAF_1 } from '../persistence-session-fixtures' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { TEST_LEAF_1 } from '../../persistence-session-fixtures' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -37,11 +37,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts b/src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts index 88c3453f5f7..1c55bd604ac 100644 --- a/src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts +++ b/src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts @@ -1,4 +1,4 @@ -import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-row-order' +import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-topology/terminal-row-order' import type { PersistedState } from '../../../../shared/persisted-state-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { sanitizeWorkspaceSessionTerminalRetirements } from '../../../runtime/terminal/surface/mobile-session-terminal-persistence-retirement' @@ -13,9 +13,7 @@ import { pruneLocalTerminalScrollbackBuffers } from '../../../../shared/workspac import { pruneWorkspaceSessionBrowserHistory } from '../../../../shared/workspace-session/workspace-session-browser-history' import { withoutRedundantGlobalFields } from '../../../../shared/workspace-session/workspace-session-host-field-ownership' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' -import { readTerminalScrollbackSnapshotSync } from '../../../pty/scrollback/terminal-scrollback-snapshots' import { - hasTerminalScrollbackSnapshotSync, readTerminalScrollbackSnapshot, statTerminalScrollbackSnapshotSize } from '../../../pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads' @@ -114,20 +112,6 @@ export class SessionHostPartitionOperations { ) } - readTerminalScrollbackSnapshot(ref: string): string | null { - return readTerminalScrollbackSnapshotSync( - ref, - this[sessionHostPartitionOperationsContext].runtime.terminalScrollbackSnapshotStorage - ) - } - - hasTerminalScrollbackSnapshot(ref: string): boolean { - return hasTerminalScrollbackSnapshotSync( - ref, - this[sessionHostPartitionOperationsContext].runtime.terminalScrollbackSnapshotStorage - ) - } - readTerminalScrollbackSnapshotAsync(ref: string): Promise { return readTerminalScrollbackSnapshot( ref, diff --git a/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts b/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts index f3ddd05bd70..4b9be5cba5a 100644 --- a/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts +++ b/src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts @@ -25,7 +25,7 @@ import { import { dropClosedTerminalTabs } from '../../closed-terminal-tab-write-fence' import { keepWslMoveFrozenSessionsForStore } from '../../moving-wsl-projects/terminal-state/wsl-move-session-freeze' import { type WriteSchedulingOperations, scheduleSave } from '../profile-writing/write-scheduling' -import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-row-order' +import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-topology/terminal-row-order' export class SessionSnapshotOperations { readonly [sessionSnapshotOperationsContext]: SessionSnapshotOperationsContext diff --git a/src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts b/src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts similarity index 88% rename from src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts rename to src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts index d31ec45ea4a..c7d6c9aaf53 100644 --- a/src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts +++ b/src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import { buildAgentResumeStartupPlan } from '../../../shared/agent-launch/startup/tui-agent-resume-startup' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { Store } from '../loading-store/store' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import { buildAgentResumeStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-resume-startup' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { Store } from '../store' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID as WORKTREE, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../../terminal-topology/testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts b/src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts index 23e801471b1..e14007f1878 100644 --- a/src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts +++ b/src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts @@ -30,7 +30,7 @@ import { preserveMissingWorkspaceSessionTerminalBindings } from './workspace-ses import type { SessionSnapshotOperations } from './session-snapshot-operations' import { getSessionSnapshotOperationsContext } from './session-snapshot-operations-context' import { scheduleSave } from '../profile-writing/write-scheduling' -import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-row-order' +import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-topology/terminal-row-order' export function setLocalWorkspaceSession( owner: SessionSnapshotOperations, diff --git a/src/main/persistence/loading-store/worktree-metadata/local-only-worktree-meta-rehoming.ts b/src/main/persistence/loading-store/worktree-metadata/local-only-worktree-meta-rehoming.ts index 2a409ac1c7b..bfee31333f8 100644 --- a/src/main/persistence/loading-store/worktree-metadata/local-only-worktree-meta-rehoming.ts +++ b/src/main/persistence/loading-store/worktree-metadata/local-only-worktree-meta-rehoming.ts @@ -8,7 +8,7 @@ import { getExecutionHostIdFromWorktreeHostIdentity, getWorktreeIdFromHostIdentity } from '../../../../shared/worktree/host-qualified-identity' -import { isLocalOnlyWorktreeMetaId } from '../../../../shared/worktree/local-only-worktree-meta-ids' +import { isLocalOnlyWorktreeMetaId } from '../../../../shared/worktree/metadata/local-only-worktree-meta-ids' import { pruneUnreferencedWorktreeIdentityMeta, resolveAliasIdentityKey diff --git a/src/main/persistence/loading-store/worktree-metadata/worktree-identity-metadata.ts b/src/main/persistence/loading-store/worktree-metadata/worktree-identity-metadata.ts index c93e23c2c6c..074e39dd8e3 100644 --- a/src/main/persistence/loading-store/worktree-metadata/worktree-identity-metadata.ts +++ b/src/main/persistence/loading-store/worktree-metadata/worktree-identity-metadata.ts @@ -18,7 +18,7 @@ import { WORKTREE_METADATA_DOMAINS } from '../../profile-save-domains' import { isLocalOnlyWorktreeMetaId, worktreeMetaHostFor -} from '../../../../shared/worktree/local-only-worktree-meta-ids' +} from '../../../../shared/worktree/metadata/local-only-worktree-meta-ids' type MetadataRuntime = Pick & Partial> diff --git a/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.test.ts b/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.test.ts index 02020052a3f..893510978e7 100644 --- a/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.test.ts +++ b/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import type { DiffComment } from '../../../../shared/diff-comment-types' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import { mergeWorktreeMetaForWrite } from './worktree-meta-write-normalization' -import { CLEARED_HOSTED_REVIEW_LINK_UPDATES } from '../../../../shared/worktree/hosted-review-links' +import { CLEARED_HOSTED_REVIEW_LINK_UPDATES } from '../../../../shared/worktree/hosted-review/hosted-review-links' const existingMeta: WorktreeMeta = { displayName: 'Feature', diff --git a/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.ts b/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.ts index eb969d8e17c..e9cbe411495 100644 --- a/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.ts +++ b/src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.ts @@ -5,8 +5,8 @@ import { normalizeWorkspaceLinkedItem } from '../../../../shared/workspace-attac import { isWorkspaceLinkedItemSourceContextMatch } from '../../../../shared/workspace-attachments/workspace-linked-item-source-context' import { DEFAULT_WORKSPACE_STATUS_ID } from '../../../../shared/workspace-statuses' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' -import { WORKTREE_META_PERSISTED_DEFAULTS } from '../../../../shared/worktree/meta-persisted-defaults' -import { normalizeGitHubPRSuppressionUpdate } from '../../../../shared/worktree/github-pr-suppression' +import { WORKTREE_META_PERSISTED_DEFAULTS } from '../../../../shared/worktree/metadata/meta-persisted-defaults' +import { normalizeGitHubPRSuppressionUpdate } from '../../../../shared/worktree/hosted-review/github-pr-suppression' import type { WorkspaceAttachmentMutation } from '../../../../shared/workspace-attachments/workspace-attachment-mutation' import { normalizeWorkspaceAttachmentUpdate } from '../../../../shared/workspace-attachments/workspace-attachments' import { diff --git a/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts b/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts index 6cf08858025..3aef7f43e57 100644 --- a/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts +++ b/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts @@ -1,5 +1,5 @@ // Validate blob contents before commit; install only advertised kinds after durable commit. -import { servesWslMovedPaneHistory } from '../../../orcad/orcad-migration-wsl-destination' +import { servesWslMovedPaneHistory } from '../../../orcad/migration/orcad-migration-wsl-destination' import { readFileSync, rmSync } from 'node:fs' import { dirname } from 'node:path' import type { OrcadMigrationBlobKind } from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' diff --git a/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts b/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts index 23659cc7b2d..02220b07db8 100644 --- a/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts +++ b/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts @@ -10,7 +10,7 @@ import type { ProjectGroup } from '../../../../shared/project-group-types' import type { Repo } from '../../../../shared/repo-types' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { worktreeWorkspaceKey } from '../../../../shared/workspace-scope' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' export const PROJECT_GROUP: ProjectGroup = { id: 'group-1', diff --git a/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-workspace-session.ts b/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-workspace-session.ts index 655f06c7338..68ed59efe77 100644 --- a/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-workspace-session.ts +++ b/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-workspace-session.ts @@ -4,7 +4,7 @@ import type { PersistedState } from '../../../../shared/persisted-state-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { SESSION_FOCUS_FIELDS } from '../../../../shared/workspace-session/workspace-session-host-field-ownership' import { mergeWorkspaceSessions } from '../../../orca-profiles/project-transfer/profile-project-session-state' -import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' const MERGED_SESSION_RECORD_FIELDS = [ 'tabsByWorktree', diff --git a/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-worktree-metadata.ts b/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-worktree-metadata.ts index 39c9f87c7ea..92fd45454f2 100644 --- a/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-worktree-metadata.ts +++ b/src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-worktree-metadata.ts @@ -6,7 +6,7 @@ import { } from '../../../../shared/orcad-migration/orcad-migration-manifest' import { canonicalWorktreeIdentity } from '../../../../shared/worktree/identity' import { composeWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' -import { omitDefaultWorktreeMetaFields } from '../../../../shared/worktree/meta-persisted-defaults' +import { omitDefaultWorktreeMetaFields } from '../../../../shared/worktree/metadata/meta-persisted-defaults' export function assertOrcadDestinationCanonicalMetadata( state: PersistedState, diff --git a/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-lineage-reconciliation.ts b/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-lineage-reconciliation.ts index 38b04d57627..7181f2bbf38 100644 --- a/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-lineage-reconciliation.ts +++ b/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-lineage-reconciliation.ts @@ -2,7 +2,7 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import type { PersistedState } from '../../../../shared/persisted-state-types' import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' -import { toWorkspaceLineageRow } from '../../../../shared/worktree/worktree-lineage-workspace-row' +import { toWorkspaceLineageRow } from '../../../../shared/worktree/lineage/worktree-lineage-workspace-row' import { folderWorkspaceKey, parseWorkspaceKey, diff --git a/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-state-records.ts b/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-state-records.ts index c9044f16690..3655ff46535 100644 --- a/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-state-records.ts +++ b/src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-state-records.ts @@ -6,13 +6,13 @@ import type { PersistedState } from '../../../../shared/persisted-state-types' import type { SparsePreset } from '../../../../shared/worktree/create-types' import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' -import { omitDefaultWorktreeMetaFields } from '../../../../shared/worktree/meta-persisted-defaults' +import { omitDefaultWorktreeMetaFields } from '../../../../shared/worktree/metadata/meta-persisted-defaults' import { assertOrcadDestinationCanonicalMetadata } from './orcad-destination-worktree-metadata' import { assertSameValue } from '../catalog-commit/orcad-catalog-row-identity' import { mergeRetiredNameRegistries, type RetiredNameRegistry -} from '../../../../shared/worktree/retired-name-registry' +} from '../../../../shared/worktree/naming/retired-name-registry' import { recordRetirementNamespaceRegistry } from '../../../workspaces/removal/retirement/worktree-retirement-namespace' import { applyPreparedOrcadMigrationWorkspaceSession, diff --git a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts index 99b85207721..583b31a74c6 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts @@ -24,7 +24,7 @@ import { import type { SshTarget } from '../../../../../shared/ssh-types' import type { Store } from '../../../loading-store/store' import { collectOrcadMigrationSourceCatalog } from './orcad-source-catalog' -import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/migration/orcad-migration-manifest-digest' import { IDENTITY_ORCAD_MIGRATION_PATH_REWRITER, rewriteOrcadMigrationPayloadPaths, diff --git a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts index d0631ca7efa..305a73dfa01 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts @@ -9,7 +9,7 @@ import type { OrcadMigrationManifest, OrcadMigrationManifestSource } from '../../../../../shared/orcad-migration/orcad-migration-manifest' -import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/migration/orcad-migration-manifest-digest' import type { StoreRuntimeState } from '../../../loading-store/store-runtime-state' import { collectOrcadMigrationUntransferredDependencyCensus, diff --git a/src/main/persistence/migrating-orcad-catalog/source/dormancy/orcad-source-dormant-state.ts b/src/main/persistence/migrating-orcad-catalog/source/dormancy/orcad-source-dormant-state.ts index cad7eb5f8d3..867a1341977 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/dormancy/orcad-source-dormant-state.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/dormancy/orcad-source-dormant-state.ts @@ -7,7 +7,7 @@ import type { OrcadMigrationDependencyKind } from '../../../../../shared/orcad-m import type { PersistedState } from '../../../../../shared/persisted-state-types' import type { TerminalScrollbackSnapshotStorage } from '../../../../pty/scrollback/terminal-scrollback-snapshots' import { projectHostSetupProjectionFromRepos } from '../../../../../shared/project-host-setup-projection' -import { isEmptyRetiredNameRegistry } from '../../../../../shared/worktree/retired-name-registry' +import { isEmptyRetiredNameRegistry } from '../../../../../shared/worktree/naming/retired-name-registry' import { getRepoIdFromWorktreeId } from '../../../../../shared/worktree/id' import { toOrcadDestinationRepository } from '../../destination/orcad-destination-catalog-projection' import { collectOrcadMigrationRetiredWorktreeNamespaces } from '../worktrees/orcad-source-retired-worktree-names' @@ -22,7 +22,7 @@ import { import { collectOrcadMigrationSourceClientState } from '../clients/orcad-source-client-state' import { inspectOrcadSourceWorktreeMetadata } from '../worktrees/orcad-source-worktree-metadata' import { compareKeys } from '../catalog/orcad-source-key-order' -import { assertNoCrossStoreLinkedWorkspaceInMove } from '../../../../../shared/worktree/cross-store-lineage-move-refusal' +import { assertNoCrossStoreLinkedWorkspaceInMove } from '../../../../../shared/worktree/lineage/cross-store-lineage-move-refusal' export const ORCAD_MIGRATION_TRANSFERRED_DORMANT_KINDS = [ 'worktree-metadata', diff --git a/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-session-partitions.ts b/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-session-partitions.ts index de85886068d..adfa007a0d9 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-session-partitions.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-session-partitions.ts @@ -1,4 +1,4 @@ -import { hasClosedTerminalTabRecord } from '../../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import type { PersistedState } from '../../../../../shared/persisted-state-types' import { normalizeWorkspaceSessionKeyToWorkspaceId } from '../../../../../shared/workspace-scope' diff --git a/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session.ts b/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session.ts index 1341973eae4..7700280c0e3 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session.ts @@ -36,7 +36,7 @@ import { type SessionFragment } from './orcad-source-session-copy-resolution' import { withoutOrcadMigrationDrafts } from '../worktrees/orcad-source-draft-rename' -import { hasClosedTerminalTabRecord } from '../../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { normalizeWorkspaceSessionKeyToWorkspaceId } from '../../../../../shared/workspace-scope' import { orcadMigrationSessionPartitions } from './orcad-source-session-partitions' diff --git a/src/main/persistence/migrating-orcad-catalog/source/worktrees/orcad-source-retired-worktree-names.ts b/src/main/persistence/migrating-orcad-catalog/source/worktrees/orcad-source-retired-worktree-names.ts index 3efd2494813..c4a568c273b 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/worktrees/orcad-source-retired-worktree-names.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/worktrees/orcad-source-retired-worktree-names.ts @@ -8,7 +8,7 @@ import { isEmptyRetiredNameRegistry, mergeRetiredNameRegistries, type RetiredNameRegistry -} from '../../../../../shared/worktree/retired-name-registry' +} from '../../../../../shared/worktree/naming/retired-name-registry' import { getRemoteRetirementNamespaceKey } from '../../../../workspaces/removal/retirement/worktree-name-retirement' import { swapRetirementNamespaceHost, diff --git a/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts b/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts index f2fe0a7ecc5..209d0580a1a 100644 --- a/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts +++ b/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts @@ -6,7 +6,7 @@ import { type WslMoveCutover } from '../../../../shared/wsl-move/wsl-move-cutover' import { isRecord } from '../../../../shared/orcad-migration/orcad-migration-manifest-fields' -import { assertOrcadMigrationManifestDigest } from '../../../orcad/orcad-migration-manifest-digest' +import { assertOrcadMigrationManifestDigest } from '../../../orcad/migration/orcad-migration-manifest-digest' import { createMigrationJournalDirectory, orderMigrationJournalChain diff --git a/src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-seeded-view-state.ts b/src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-seeded-view-state.ts index ddd44442fb8..0296f166402 100644 --- a/src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-seeded-view-state.ts +++ b/src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-seeded-view-state.ts @@ -5,7 +5,7 @@ * cannot rewrite) and closed-terminal-tab tombstones. Only for workspaces seeded in this run, so * anything the user since changed on the host stays as it is. */ -import type { ClosedTerminalTabTombstone } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import type { ClosedTerminalTabTombstone } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { ownedEditorFileId } from '../../../../shared/workspace-session/workspace-session-pane-ownership' import { isHostBoundOpenFile } from '../../migrating-orcad-catalog/source/worktrees/orcad-source-draft-rename' diff --git a/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts b/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts index f8a96420334..d5aaacd7700 100644 --- a/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts +++ b/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts @@ -23,7 +23,7 @@ import type { ProjectGroup } from '../../../../shared/project-group-types' import type { Repo } from '../../../../shared/repo-types' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { getRepoIdFromWorktreeId, getRepoMainWorktreeId } from '../../../../shared/worktree/id' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' import { hasDormantState } from '../../migrating-orcad-catalog/source/dormancy/orcad-migration-dormant-state' import { rewriteOrcadMigrationPayloadPaths, diff --git a/src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback.ts b/src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback.ts index 55cbd4e35a5..f658fba9012 100644 --- a/src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback.ts +++ b/src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback.ts @@ -23,7 +23,7 @@ import { import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { WslMoveRequest } from '../../../../shared/wsl-move/wsl-move-driver-types' import { parsePtySessionId } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' -import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import type { ColdRestoreInfo } from '../../../daemon/history/restoration/terminal-history-cold-restore-info' import type { TerminalCheckpointFile } from '../../../daemon/protocol/daemon-checkpoint-file' import type { OrcadMigrationBlobSource } from '../../../managed-server/migration/transfers/orcad-migration-blob-coordinator' diff --git a/src/main/persistence/preferences/persistence-onboarding-language-cohort.test.ts b/src/main/persistence/preferences/persistence-onboarding-language-cohort.test.ts index 46f9bbf6216..e5e2f0f8c70 100644 --- a/src/main/persistence/preferences/persistence-onboarding-language-cohort.test.ts +++ b/src/main/persistence/preferences/persistence-onboarding-language-cohort.test.ts @@ -1,12 +1,5 @@ -import { - closeTestStores, - createStore, - readDataFile, - testState, - writeDataFile -} from '../persistence-test-harness' +import { closeTestStores, createStore, testState, writeDataFile } from '../persistence-test-harness' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as crypto from 'node:crypto' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -16,10 +9,6 @@ vi.mock('electron', () => ({ safeStorage: { isEncryptionAvailable: () => false } })) vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('node:crypto', async (importOriginal) => ({ - ...(await importOriginal()), - randomInt: vi.fn() -})) beforeEach(() => { testState.dir = mkdtempSync(join(tmpdir(), 'orca-onboarding-language-cohort-')) @@ -31,33 +20,40 @@ afterEach(async () => { }) describe('persisted onboarding language cohorts', () => { - it.each([ - { draw: 0, cohort: 'control' }, - { draw: 1, cohort: 'treatment' } - ])('retains $cohort through settings changes and restart', async ({ draw, cohort }) => { - vi.mocked(crypto.randomInt).mockImplementation(() => draw) + it('does not assign a historical setting to a fresh profile, including after restart', async () => { const store = createStore() const telemetry = store.getSettings().telemetry if (!telemetry) { throw new Error('Fresh profile has no telemetry settings') } - expect(telemetry.onboardingLanguageCohort).toBe(cohort) + expect(telemetry.onboardingLanguageCohort).toBeUndefined() expect(store.getSettings().uiLanguage).toBe('system') store.flush() - expect(readDataFile()).toHaveProperty('settings.telemetry.onboardingLanguageCohort', cohort) - expect(readDataFile()).toHaveProperty('settings.uiLanguage', 'system') - - store.updateSettings({ uiLanguage: 'fr' }) - store.updateSettings({ telemetry: { ...telemetry, optedIn: false } }) - store.flush() await closeTestStores() - - const reopened = createStore() - expect(reopened.getSettings().telemetry).toEqual({ ...telemetry, optedIn: false }) - expect(reopened.getSettings().uiLanguage).toBe('fr') - expect(crypto.randomInt).toHaveBeenCalledExactlyOnceWith(2) + expect(createStore().getSettings().telemetry?.onboardingLanguageCohort).toBeUndefined() }) + it.each(['control', 'treatment'] as const)( + 'retains the historical setting through migration, settings changes and restart', + async (cohort) => { + writeDataFile({ settings: { telemetry: { onboardingLanguageCohort: cohort } } }) + const store = createStore() + const telemetry = store.getSettings().telemetry + if (!telemetry) { + throw new Error('Migrated profile has no telemetry settings') + } + expect(telemetry.onboardingLanguageCohort).toBe(cohort) + store.updateSettings({ uiLanguage: 'fr' }) + store.updateSettings({ telemetry: { ...telemetry, optedIn: false } }) + store.flush() + await closeTestStores() + + const reopened = createStore() + expect(reopened.getSettings().telemetry).toEqual({ ...telemetry, optedIn: false }) + expect(reopened.getSettings().uiLanguage).toBe('fr') + } + ) + it('keeps a previously migrated profile excluded through restart', async () => { writeDataFile({ settings: { @@ -76,6 +72,5 @@ describe('persisted onboarding language cohorts', () => { expect(reopened.getSettings().telemetry?.onboardingLanguageCohort).toBeUndefined() expect(reopened.getSettings().telemetry?.optedIn).toBe(false) expect(reopened.getSettings().uiLanguage).toBe('ja') - expect(crypto.randomInt).not.toHaveBeenCalled() }) }) diff --git a/src/main/persistence/profile-state/offline-access/profile-state-offline-settings.ts b/src/main/persistence/profile-state/offline-access/profile-state-offline-settings.ts index 475d0d7e959..dc0821bd3e4 100644 --- a/src/main/persistence/profile-state/offline-access/profile-state-offline-settings.ts +++ b/src/main/persistence/profile-state/offline-access/profile-state-offline-settings.ts @@ -36,6 +36,14 @@ export type AgentHookSettingsUpdate = { settingsPath: string } +/** The file the reader below takes settings from. */ +export function resolveAgentHookSettingsPath(location: ProfileStateOfflineLocation): string { + const classification = classifyProfileStateStorage(location.dataFile, location.databaseFile) + return classification === 'json-only' || classification === 'neither' + ? location.dataFile + : location.databaseFile +} + /** JSON-only profiles must not create SQLite while reading settings. */ export function readAgentHookSettingsFromProfileState( location: ProfileStateOfflineLocation diff --git a/src/main/persistence/profile-state/recovery/profile-state-recovery-command.ts b/src/main/persistence/profile-state/recovery/profile-state-recovery-command.ts index 7cc6d9a676c..cfdd5d27374 100644 --- a/src/main/persistence/profile-state/recovery/profile-state-recovery-command.ts +++ b/src/main/persistence/profile-state/recovery/profile-state-recovery-command.ts @@ -36,7 +36,7 @@ import { profileHasPendingProjectMove } from '../../../orca-profiles/project-tra import { invalidateHttp1CompatibilityMarker, writeHttp1CompatibilityMarker -} from '../../../startup/http1-compatibility-marker' +} from '../../../startup/network-compatibility/http1-compatibility-marker' export function getProfileStateExports( userDataPath: string, diff --git a/src/main/persistence/profile-state/recovery/profile-state-recovery-crash-process.ts b/src/main/persistence/profile-state/recovery/profile-state-recovery-crash-process.ts index 0f35c9fce7a..22628f181c3 100644 --- a/src/main/persistence/profile-state/recovery/profile-state-recovery-crash-process.ts +++ b/src/main/persistence/profile-state/recovery/profile-state-recovery-crash-process.ts @@ -30,7 +30,7 @@ export function buildRecoveryCrashProcess(directory: string): { export { restoreProfileStateDatabaseBackup } from './src/main/persistence/profile-state/recovery/profile-state-database-recovery' export { openProfileStateDatabase } from './src/main/persistence/profile-state/database/profile-state-database' export { importProfileStateJson } from './src/main/persistence/profile-state/documents/profile-state-documents' - export { invalidateHttp1CompatibilityMarker, writeHttp1CompatibilityMarker } from './src/main/startup/http1-compatibility-marker' + export { invalidateHttp1CompatibilityMarker, writeHttp1CompatibilityMarker } from './src/main/startup/network-compatibility/http1-compatibility-marker' `, loader: 'ts', resolveDir: process.cwd() diff --git a/src/main/persistence/restoring-sessions/empty-terminal-layout-root-repair.ts b/src/main/persistence/restoring-sessions/empty-terminal-layout-root-repair.ts index 41aa7261d59..081ef6165fc 100644 --- a/src/main/persistence/restoring-sessions/empty-terminal-layout-root-repair.ts +++ b/src/main/persistence/restoring-sessions/empty-terminal-layout-root-repair.ts @@ -1,7 +1,7 @@ import type { PersistedState } from '../../../shared/persisted-state-types' import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { resolveRootlessTerminalLayoutLeafId } from '../../../shared/workspace-layout/terminal-pane-tree' +import { resolveRootlessTerminalLayoutLeafId } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { deriveHeadlessLegacyTerminalLeafId } from '../../runtime/terminal/surface/mobile-session-layout-projection' function nameEmptyLayoutRoot( diff --git a/src/main/persistence/restoring-sessions/invalid-workspace-layout-purge.ts b/src/main/persistence/restoring-sessions/invalid-workspace-layout-purge.ts index be9e3a5018b..65b3e1352f9 100644 --- a/src/main/persistence/restoring-sessions/invalid-workspace-layout-purge.ts +++ b/src/main/persistence/restoring-sessions/invalid-workspace-layout-purge.ts @@ -5,11 +5,11 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/exec import type { PersistedState } from '../../../shared/persisted-state-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { parseWorkspaceKey } from '../../../shared/workspace-scope' -import { isWorktreeCatalogVersionBefore } from '../../../shared/worktree/catalog-version' +import { isWorktreeCatalogVersionBefore } from '../../../shared/worktree/catalog/catalog-version' import { buildValidWorktreeIdsForSessionHydration, collectPersistedWorktreeIdsForSessionHydration -} from '../../../shared/worktree/degraded-repo-worktree-validity' +} from '../../../shared/worktree/catalog/degraded-repo-worktree-validity' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import { hostWorktreeTarget, diff --git a/src/main/persistence/restoring-sessions/pane-identity-migration.ts b/src/main/persistence/restoring-sessions/pane-identity-migration.ts index 906f193b08e..ec8fa7796a7 100644 --- a/src/main/persistence/restoring-sessions/pane-identity-migration.ts +++ b/src/main/persistence/restoring-sessions/pane-identity-migration.ts @@ -6,7 +6,10 @@ import type { } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { collectLayoutLeafIdsInOrder, firstLayoutLeafId } from './terminal-layout-normalization' +import { + collectLayoutLeafIdsInOrder, + firstLayoutLeafId +} from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' export function findWorktreeIdForTab( session: WorkspaceSessionState, diff --git a/src/main/persistence/terminal-topology/persistence-cross-host-pane-identity.test.ts b/src/main/persistence/restoring-sessions/persistence-cross-host-pane-identity.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-cross-host-pane-identity.test.ts rename to src/main/persistence/restoring-sessions/persistence-cross-host-pane-identity.test.ts diff --git a/src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts b/src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts similarity index 78% rename from src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts rename to src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts index 8ecdcb4efbd..dd8d11c3b9e 100644 --- a/src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts +++ b/src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from 'node:os' import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { isTerminalLeafId } from '../../../shared/workspace-layout/stable-pane-id' +import '../../../shared/workspace-layout/stable-pane-id' import { makeTerminalTab, TEST_LEAF_1 } from '../persistence-session-fixtures' vi.mock('electron', () => ({ @@ -80,26 +80,6 @@ describe('a saved layout with an empty root', () => { expect(session.terminalLayoutsByTabId['tab-1']?.ptyIdsByLeafId).toEqual({ [leafId]: 'pty-1' }) }) - it('names a fresh pane when the old layout names none', () => { - const layout = loadOldSession({ - root: null, - activeLeafId: null, - expandedLeafId: null - }).getWorkspaceSession().terminalLayoutsByTabId['tab-1'] - const leafId = layout?.activeLeafId ?? '' - expect(isTerminalLeafId(leafId)).toBe(true) - expect(layout?.root).toEqual({ type: 'leaf', leafId }) - }) - - it('names the same pane on every load until something saves', async () => { - const emptyRoot = { root: null, activeLeafId: null, expandedLeafId: null } - const first = loadOldSession(emptyRoot).getWorkspaceSession().terminalLayoutsByTabId['tab-1'] - await closeTestStores() - const second = loadOldSession(emptyRoot).getWorkspaceSession().terminalLayoutsByTabId['tab-1'] - - expect(second?.root).toEqual(first?.root) - }) - it('names the pane the old layout was already bound to', () => { const store = loadOldSession({ root: null, diff --git a/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts b/src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts rename to src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts diff --git a/src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts b/src/main/persistence/restoring-sessions/persistence-tab-terminal-pane-binding-load.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts rename to src/main/persistence/restoring-sessions/persistence-tab-terminal-pane-binding-load.test.ts diff --git a/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.test.ts b/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.test.ts index 1fccc5abfa6..cd8c0080ec2 100644 --- a/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.test.ts +++ b/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.test.ts @@ -14,7 +14,7 @@ import { GIT_KEY, leaf, SSH_KEY -} from '../../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { bindPersistedTabTerminalPanes, bindTabTerminalPanesInSession @@ -52,21 +52,6 @@ describe("load repair: a tab's own terminal and its unbound pane", () => { expect(bindings(repair(stored, true))).toEqual({ [leaf(1)]: 'ssh:box@@pty-9' }) }) - it("never takes a terminal another tab's pane binds", () => { - const stored = addWorkspace(emptySession(), GIT_KEY, [ - { - id: 'g1', - tabs: [ - { id: 'tab-a', leaves: [[leaf(1)]] }, - { id: 'tab-b', leaves: [[leaf(2), 'pty-a']] } - ] - } - ]) - stored.tabsByWorktree[GIT_KEY]![0]!.ptyId = 'pty-a' - stored.activeWorktreeIdsOnShutdown = [GIT_KEY] - expect(repair(stored)).toBe(stored) - }) - it('binds one of two tabs naming the same terminal, never both', () => { const stored = addWorkspace(emptySession(), GIT_KEY, [ { diff --git a/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.ts b/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.ts index e5b117c12cd..fb92f1e67b0 100644 --- a/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.ts +++ b/src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.ts @@ -3,15 +3,15 @@ import type { PersistedState } from '../../../shared/persisted-state-types' import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-pane-tree' +import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { readCanonicalPtyOwners, resolveCanonicalPtyClaim -} from '../../../shared/workspace-layout/legacy-terminal-row-claims' +} from '../../../shared/workspace-layout/terminal-topology/legacy-terminal-row-claims' import { liveAtShutdown, sweepUnattachedTerminalRows -} from '../../../shared/workspace-layout/unattached-terminal-row-sweep' +} from '../../../shared/workspace-layout/terminal-topology/unattached-terminal-row-sweep' /** Removed leaves cannot claim terminal ownership. */ function mountedPtyIds(layout: TerminalLayoutSnapshot): string[] { diff --git a/src/main/persistence/restoring-sessions/terminal-layout-normalization.test.ts b/src/main/persistence/restoring-sessions/terminal-layout-normalization.test.ts index c4bbfac5bcc..76405adc0e5 100644 --- a/src/main/persistence/restoring-sessions/terminal-layout-normalization.test.ts +++ b/src/main/persistence/restoring-sessions/terminal-layout-normalization.test.ts @@ -1,9 +1,7 @@ import { describe, expect, it } from 'vitest' import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' -import { - collectLayoutLeafIdsInOrder, - normalizeTerminalLayoutSnapshotForPersistence -} from './terminal-layout-normalization' +import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { normalizeTerminalLayoutSnapshotForPersistence } from './terminal-layout-normalization' const STABLE_A = '11111111-1111-4111-8111-111111111111' const STABLE_B = '22222222-2222-4222-8222-222222222222' diff --git a/src/main/persistence/restoring-sessions/terminal-layout-normalization.ts b/src/main/persistence/restoring-sessions/terminal-layout-normalization.ts index 971d09450ec..9ccc592d03a 100644 --- a/src/main/persistence/restoring-sessions/terminal-layout-normalization.ts +++ b/src/main/persistence/restoring-sessions/terminal-layout-normalization.ts @@ -7,13 +7,7 @@ import { isTerminalLeafId } from '../../../shared/workspace-layout/stable-pane-i import { collectLayoutLeafIdsInOrder, firstLayoutLeafId -} from '../../../shared/workspace-layout/terminal-pane-tree' - -export { - collectLayoutLeafIdsInOrder, - firstLayoutLeafId, - layoutContainsLeafId -} from '../../../shared/workspace-layout/terminal-pane-tree' +} from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' export type LayoutLeafNormalization = { snapshot: TerminalLayoutSnapshot diff --git a/src/main/persistence/restoring-sessions/unattached-terminal-row-sweep.test.ts b/src/main/persistence/restoring-sessions/unattached-terminal-row-sweep.test.ts index fe15342cc41..3989db60a86 100644 --- a/src/main/persistence/restoring-sessions/unattached-terminal-row-sweep.test.ts +++ b/src/main/persistence/restoring-sessions/unattached-terminal-row-sweep.test.ts @@ -4,17 +4,15 @@ import { describe, expect, it } from 'vitest' import { getDefaultPersistedState } from '../../../shared/constants' import { toRuntimeExecutionHostId, toSshExecutionHostId } from '../../../shared/execution-host' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { sleepingRecord } from '../../../shared/workspace-layout/workspace-layout-profile.test-fixture' +import '../../../shared/workspace-layout/persistence/workspace-layout-profile.test-fixture' import { addWorkspace, emptySession, GIT_KEY, leaf -} from '../../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { sweepPersistedUnattachedTerminalRows } from './tab-terminal-pane-binding-repair' -const CLI_KEY = 'repo-1::/Users/dev/orca-cli' - function unattachedRow(): WorkspaceSessionState { const session = addWorkspace(emptySession(), GIT_KEY, [ { @@ -30,97 +28,10 @@ function unattachedRow(): WorkspaceSessionState { return session } -function swept(session: WorkspaceSessionState): WorkspaceSessionState { - const state = getDefaultPersistedState('/home/dev') - state.workspaceSession = session - return sweepPersistedUnattachedTerminalRows(state).workspaceSession -} - const rowIds = (session: WorkspaceSessionState, key = GIT_KEY): string[] => (session.tabsByWorktree[key] ?? []).map((row) => row.id) describe('load sweep: a terminal row outside the tab bar', () => { - it('goes with its pane layout when nothing would reattach it', () => { - const session = swept(unattachedRow()) - expect(rowIds(session)).toEqual(['tab-a']) - expect(session.terminalLayoutsByTabId['tab-b']).toBeUndefined() - }) - - it('goes when only a pane binds a terminal, as the window does', () => { - const session = unattachedRow() - session.terminalLayoutsByTabId['tab-b']!.ptyIdsByLeafId = { [leaf(2)]: 'pty-b' } - expect(rowIds(swept(session))).toEqual(['tab-a']) - }) - - it('goes when its workspace was not live at shutdown', () => { - const session = unattachedRow() - session.tabsByWorktree[GIT_KEY]![1]!.ptyId = 'pty-b' - session.activeWorktreeIdsOnShutdown = [] - expect(rowIds(swept(session))).toEqual(['tab-a']) - }) - - it('leaves its sleeping agent record in place, as the window does', () => { - const session = unattachedRow() - const paneKey = `tab-b:${leaf(2)}` - session.sleepingAgentSessionsByPaneKey = { - [paneKey]: sleepingRecord(GIT_KEY, 'tab-b', leaf(2)) - } - const after = swept(session) - expect(rowIds(after)).toEqual(['tab-a']) - expect(Object.keys(after.sleepingAgentSessionsByPaneKey ?? {})).toEqual([paneKey]) - }) - - it('moves selections off it: the workspace to its first kept row, the global one to none', () => { - const session = unattachedRow() - session.activeTabId = 'tab-b' - session.activeTabIdByWorktree = { [GIT_KEY]: 'tab-b' } - const after = swept(session) - expect(after.activeTabIdByWorktree).toEqual({ [GIT_KEY]: 'tab-a' }) - expect(after.activeTabId).toBeNull() - }) - - it('stays when its own terminal would reattach', () => { - const session = unattachedRow() - session.tabsByWorktree[GIT_KEY]![1]!.ptyId = 'pty-b' - expect(swept(session)).toBe(session) - }) - - it('stays when its terminal is on an SSH relay', () => { - const session = unattachedRow() - session.remoteSessionIdsByTabId = { 'tab-b': 'relay-b' } - expect(swept(session)).toBe(session) - }) - - it('stays when a split row keeps its own pane’s terminal after the tab bar takes the shared one', () => { - const session = unattachedRow() - session.terminalLayoutsByTabId['tab-b'] = { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: leaf(2) }, - second: { type: 'leaf', leafId: leaf(3) } - }, - activeLeafId: leaf(2), - expandedLeafId: null, - ptyIdsByLeafId: { [leaf(2)]: 'pty-a', [leaf(3)]: 'pty-c' } - } - expect(swept(session)).toBe(session) - }) - - it('stays when the CLI started it in a workspace the window never opened', () => { - const session = unattachedRow() - session.tabsByWorktree[GIT_KEY]![1]!.ptyId = 'pty-b' - session.tabsByWorktree[CLI_KEY] = [ - { - ...session.tabsByWorktree[GIT_KEY]![1]!, - id: 'tab-cli', - worktreeId: CLI_KEY, - ptyId: 'pty-cli' - } - ] - expect(swept(session)).toBe(session) - }) - it('sweeps SSH partitions too and passes a paired server’s through', () => { const state = getDefaultPersistedState('/home/dev') const sshHost = toSshExecutionHostId('box') @@ -131,48 +42,4 @@ describe('load sweep: a terminal row outside the tab bar', () => { expect(rowIds(after[sshHost]!)).toEqual(['tab-a']) expect(after[serverHost]).toBe(serverSession) }) - - it('stays when it is an SSH workspace’s and only its own terminal id names one, as the window may reattach it', () => { - const state = getDefaultPersistedState('/home/dev') - state.repos = [ - { - id: 'repo-1', - path: '/Users/dev/orca', - displayName: 'orca', - badgeColor: '#000', - addedAt: 0, - connectionId: 'box' - } - ] - const session = unattachedRow() - session.tabsByWorktree[GIT_KEY]![1]!.ptyId = 'pty-b' - state.workspaceSession = session - expect(rowIds(sweepPersistedUnattachedTerminalRows(state).workspaceSession)).toEqual([ - 'tab-a', - 'tab-b' - ]) - }) - - it('stays when another partition’s stale shutdown list names its workspace, as the merged list does', () => { - const state = getDefaultPersistedState('/home/dev') - const sshHost = toSshExecutionHostId('box') - const local = unattachedRow() - local.tabsByWorktree[GIT_KEY]![1]!.ptyId = 'pty-b' - local.activeWorktreeIdsOnShutdown = [] - const remote = emptySession() - remote.activeWorktreeIdsOnShutdown = [GIT_KEY] - state.workspaceSession = local - state.workspaceSessionsByHostId = { [sshHost]: remote } - expect(sweepPersistedUnattachedTerminalRows(state).workspaceSession).toBe(local) - }) - - it('treats a session from before the tab bar as the window does: keeps a live row, sweeps the rest', () => { - const session = unattachedRow() - delete session.unifiedTabs - delete session.tabGroups - delete session.tabGroupLayouts - const after = swept(session) - expect(rowIds(after)).toEqual(['tab-a']) - expect(after.terminalLayoutsByTabId['tab-a']).toBeDefined() - }) }) diff --git a/src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts b/src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts similarity index 94% rename from src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts rename to src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts index 262a7b960cc..05004921f64 100644 --- a/src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts +++ b/src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts @@ -4,13 +4,13 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { Store } from '../loading-store/store' -import { leafIds } from './terminal-topology-window-session-fixture' +import { leafIds } from '../terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../terminal-topology/testing/terminal-topology-profile-fixture' vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) diff --git a/src/main/persistence/scheduling-automations/automation-create-identity.ts b/src/main/persistence/scheduling-automations/automation-create-identity.ts new file mode 100644 index 00000000000..1b0cce84053 --- /dev/null +++ b/src/main/persistence/scheduling-automations/automation-create-identity.ts @@ -0,0 +1,14 @@ +import type { + Automation, + AutomationCreateInput +} from '../../../shared/automations/automation-definition' + +/** The fields a new automation keeps from how it was asked for: its retry key and its creator. */ +export function automationCreateIdentity( + input: Pick +): Pick { + return { + ...(input.creationKey ? { creationKey: input.creationKey } : {}), + ...(input.createdBy ? { createdBy: input.createdBy } : {}) + } +} diff --git a/src/main/persistence/scheduling-automations/automation-definition-operations.ts b/src/main/persistence/scheduling-automations/automation-definition-operations.ts index 0ff7d5f8bb0..630c5d9a65d 100644 --- a/src/main/persistence/scheduling-automations/automation-definition-operations.ts +++ b/src/main/persistence/scheduling-automations/automation-definition-operations.ts @@ -1,4 +1,4 @@ -import { retainAutomationReselectionContexts } from './automation-host-reselection' +import { automationCreateIdentity } from './automation-create-identity' import { getRepoSshConnectionId } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' import { findAutomationRepoForWrite } from '../../../shared/automations/ownership/automation-repo-target' @@ -6,12 +6,10 @@ import { applyAutomationLaunchSetupPatch, automationWithLaunchSetup } from '../../../shared/automations/launch/automation-launch-setup' -import { automationCanonicalLaunchSetup } from '../../../shared/automations/launch/automation-canonical-launch-setup' import { randomUUID } from 'node:crypto' import type { Automation, - AutomationCreateInput, - AutomationUpdateInput + AutomationCreateInput } from '../../../shared/automations/automation-definition' import type { AutomationRun } from '../../../shared/automations/history/automation-run' import type { PersistedState } from '../../../shared/persisted-state-types' @@ -21,28 +19,20 @@ import { storedExtraAgentArgs } from '../../../shared/automations/launch/automation-extra-agent-args-record' import { nextAutomationOccurrenceAfter } from '../../../shared/automations/scheduling/automation-schedule-occurrences' -import { - applyAutomationExecutionTarget, - deriveAutomationExecutionTargetForCreate, - deriveAutomationExecutionTargetForUpdate -} from '../../../shared/automations/ownership/automation-execution-target' +import { deriveAutomationExecutionTargetForCreate } from '../../../shared/automations/ownership/automation-execution-target' import { assertAutomationDestination, - assertAutomationOwnerFence, - assertAutomationWorkspaceModePrecondition, assertExecutionTargetMatchesDestination, - type AutomationDestination, - type AutomationUpdatePreconditions + type AutomationDestination } from '../../../shared/automations/ownership/automation-owner-precondition' import { getAutomationContextsForRepo, - automationContextAfterUpdate, getAutomationSchedulerOwner, applyAutomationSetupTrust, normalizeAutomationSessionReuse, normalizeAutomationSetupDecisionForWorkspaceMode } from './automation-context-migration' -import { refuseManagedOrcadHost } from '../../automations/orcad-fenced-automation' +import { refuseManagedOrcadHost } from '../../automations/ownership/orcad-fenced-automation' import { automationProjectionContext, automationWorkspaceSshPin, @@ -110,7 +100,7 @@ export function createAutomation( const extraAgentArgs = storedExtraAgentArgs(setup.extraAgentArgs) const automation: Automation = { id: randomUUID(), - ...(input.creationKey ? { creationKey: input.creationKey } : {}), + ...automationCreateIdentity(input), name: input.name.trim() || 'Untitled automation', prompt: input.prompt, precheck: normalizeAutomationPrecheck(input.precheck), @@ -153,161 +143,5 @@ export function createAutomation( return automationWithLaunchSetup(automation) } -export function updateAutomation( - operations: AutomationDefinitionOperations, - id: string, - updates: AutomationUpdateInput, - options?: AutomationUpdatePreconditions & { resolvedRepo?: Repo } -): Automation { - const index = (operations.state.automations ?? []).findIndex((entry) => entry.id === id) - if (index === -1) { - throw new Error('Automation not found.') - } - const current = operations.state.automations[index] - const projectionContext = automationProjectionContext( - operations.state, - operations.storageAuthority, - false - ) - assertAutomationOwnerFence({ - automation: current, - expectedOwner: options?.expectedOwner, - operation: 'mutate', - context: projectionContext - }) - if (options?.destination) { - assertAutomationDestination(options.destination, projectionContext) - } - assertAutomationWorkspaceModePrecondition(current, options?.expectedWorkspaceMode) - const retainContexts = retainAutomationReselectionContexts( - operations.state, - current, - updates, - options?.destination, - projectionContext - ) - const launchSetupUpdate = applyAutomationLaunchSetupPatch(updates, current) - // Ignore undefined values preserved by structuredClone; explicit clears use null. - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: filtering removes only undefined entries from the validated patch and retains every remaining field's type. - const definedUpdates = Object.fromEntries( - Object.entries(launchSetupUpdate).filter(([, value]) => value !== undefined) - ) as Omit & Pick - const repoId = updates.projectId ?? current.projectId - const selectorMoveRequested = - updates.projectId !== undefined || options?.destination !== undefined - const repo = findAutomationRepoForWrite( - operations.state.repos, - repoId, - updates.runContext ?? (selectorMoveRequested ? undefined : current.runContext), - options?.resolvedRepo, - !!updates.runContext - ) - const schedulerOwner = - selectorMoveRequested && repo ? getAutomationSchedulerOwner(repo) : current.schedulerOwner - const contexts = getAutomationContextsForRepo(repo, operations.state.projectHostSetups ?? []) - const rrule = updates.rrule ?? current.rrule - const dtstart = updates.dtstart ?? current.dtstart - const scheduleChanged = updates.rrule !== undefined || updates.dtstart !== undefined - const workspaceMode = updates.workspaceMode ?? current.workspaceMode - const merged: Automation = { - ...current, - ...definedUpdates, - name: updates.name !== undefined ? updates.name.trim() || 'Untitled automation' : current.name, - precheck: Object.hasOwn(definedUpdates, 'precheck') - ? normalizeAutomationPrecheck(definedUpdates.precheck) - : normalizeAutomationPrecheck(current.precheck), - projectId: repoId, - // Why the wire object is ignored: contexts are the storing authority's own - // registry speaking. A move restates them from that registry, anything else - // keeps the stored value; an explicit null still clears. - runContext: retainContexts - ? current.runContext - : automationContextAfterUpdate( - current.runContext, - definedUpdates.runContext, - contexts.runContext, - selectorMoveRequested - ), - sourceContext: retainContexts - ? current.sourceContext - : automationContextAfterUpdate( - current.sourceContext, - definedUpdates.sourceContext, - contexts.sourceContext, - selectorMoveRequested - ), - schedulerOwner, - workspaceMode, - workspaceId: - workspaceMode === 'existing' - ? Object.hasOwn(definedUpdates, 'workspaceId') - ? (definedUpdates.workspaceId ?? null) - : current.workspaceId - : null, - baseBranch: - workspaceMode === 'new_per_run' - ? Object.hasOwn(definedUpdates, 'baseBranch') - ? (definedUpdates.baseBranch ?? null) - : (current.baseBranch ?? null) - : null, - setupDecision: normalizeAutomationSetupDecisionForWorkspaceMode( - workspaceMode, - Object.hasOwn(definedUpdates, 'setupDecision') - ? definedUpdates.setupDecision - : current.setupDecision - ), - reuseSession: - workspaceMode === 'existing' - ? (updates.reuseSession ?? current.reuseSession ?? false) - : false, - rrule, - dtstart, - nextRunAt: scheduleChanged - ? nextAutomationOccurrenceAfter(rrule, dtstart, Date.now()) - : current.nextRunAt, - updatedAt: Date.now() - } - if (retainContexts && !Object.hasOwn(current, 'sourceContext')) { - delete merged.sourceContext - } - applyAutomationSetupTrust(merged, definedUpdates, current) - delete merged.launchSetup - for (const key of ['surface', 'launchPreferences', 'agentArgs', 'extraAgentArgs'] as const) { - delete merged[key] - } - Object.assign(merged, automationCanonicalLaunchSetup(launchSetupUpdate)) - assertAutomationExtraAgentArgs(merged) - const previousPin = automationWorkspaceSshPin(operations.state, current.workspaceId) - const workspaceSshPin = automationWorkspaceSshPin(operations.state, merged.workspaceId) - const workspaceSshPinMoved = previousPin?.targetId !== workspaceSshPin?.targetId - const executionTarget = deriveAutomationExecutionTargetForUpdate({ - current, - repo, - selectorMoveRequested, - sshTargetGeneration: sshTargetGenerationForConnection( - operations.state, - repo ? getRepoSshConnectionId(repo) : undefined - ), - workspaceSshPin, - workspaceSshPinMoved - }) - refuseManagedOrcadHost(operations.state, executionTarget, workspaceSshPin, current, previousPin) - if (options?.destination) { - assertExecutionTargetMatchesDestination(executionTarget, options.destination, workspaceSshPin) - } - const updated = applyAutomationExecutionTarget( - merged, - executionTarget, - workspaceSshPinMoved ? undefined : workspaceSshPin - ) - // Replace the array to invalidate identity-keyed list projections. - operations.state.automations = operations.state.automations.map((entry) => - entry.id === id ? updated : entry - ) - operations.flush() - return automationWithLaunchSetup(updated) -} - -export { stampLegacyAutomationRunContext } from './automation-context-migration' - +export { updateAutomation } from './automation-definition-update' export { deleteAutomation } from './automation-definition-removal' diff --git a/src/main/persistence/scheduling-automations/automation-definition-update.ts b/src/main/persistence/scheduling-automations/automation-definition-update.ts new file mode 100644 index 00000000000..0f95d88d7dd --- /dev/null +++ b/src/main/persistence/scheduling-automations/automation-definition-update.ts @@ -0,0 +1,245 @@ +import { retainAutomationReselectionContexts } from './automation-host-reselection' +import { getRepoSshConnectionId } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import { findAutomationRepoForWrite } from '../../../shared/automations/ownership/automation-repo-target' +import { + applyAutomationLaunchSetupPatch, + automationWithLaunchSetup +} from '../../../shared/automations/launch/automation-launch-setup' +import { automationCanonicalLaunchSetup } from '../../../shared/automations/launch/automation-canonical-launch-setup' +import type { + Automation, + AutomationUpdateInput +} from '../../../shared/automations/automation-definition' +import { normalizeAutomationPrecheck } from '../../../shared/automations/launch/automation-precheck' +import { assertAutomationExtraAgentArgs } from '../../../shared/automations/launch/automation-extra-agent-args-record' +import { nextAutomationOccurrenceAfter } from '../../../shared/automations/scheduling/automation-schedule-occurrences' +import { + applyAutomationExecutionTarget, + deriveAutomationExecutionTargetForUpdate +} from '../../../shared/automations/ownership/automation-execution-target' +import { + assertAutomationDestination, + assertAutomationOwnerFence, + assertAutomationWorkspaceModePrecondition, + assertExecutionTargetMatchesDestination, + type AutomationUpdatePreconditions +} from '../../../shared/automations/ownership/automation-owner-precondition' +import { + getAutomationContextsForRepo, + automationContextAfterUpdate, + getAutomationSchedulerOwner, + applyAutomationSetupTrust, + normalizeAutomationSetupDecisionForWorkspaceMode +} from './automation-context-migration' +import { refuseManagedOrcadHost } from '../../automations/ownership/orcad-fenced-automation' +import { + automationProjectionContext, + automationWorkspaceSshPin, + sshTargetGenerationForConnection +} from './automation-owner-projection' +import type { AutomationDefinitionOperations } from './automation-definition-operations' + +export type AutomationBatchUpdate = { id: string; updates: AutomationUpdateInput } + +export type AutomationBatchUpdateResult = + | { id: string; automation: Automation } + | { id: string; error: unknown } + +/** + * Applies each update as `updateAutomation` would, but replaces the list and flushes once for the + * whole batch. Why: per-row writes re-copy every stored automation once per row. One row's refusal + * (missing, fenced) is its own result and never blocks the others. + */ +export function updateAutomations( + operations: AutomationDefinitionOperations, + batch: readonly AutomationBatchUpdate[] +): AutomationBatchUpdateResult[] { + const byId = new Map((operations.state.automations ?? []).map((entry) => [entry.id, entry])) + const written = new Map() + const results = batch.map(({ id, updates }): AutomationBatchUpdateResult => { + const current = written.get(id) ?? byId.get(id) + if (!current) { + return { id, error: new Error('Automation not found.') } + } + try { + const updated = mergeAutomationUpdate(operations, current, updates) + written.set(id, updated) + return { id, automation: automationWithLaunchSetup(updated) } + } catch (error) { + return { id, error } + } + }) + if (written.size > 0) { + // Replace the array to invalidate identity-keyed list projections. + operations.state.automations = operations.state.automations.map( + (entry) => written.get(entry.id) ?? entry + ) + operations.flush() + } + return results +} + +export function updateAutomation( + operations: AutomationDefinitionOperations, + id: string, + updates: AutomationUpdateInput, + options?: AutomationUpdatePreconditions & { resolvedRepo?: Repo } +): Automation { + const current = (operations.state.automations ?? []).find((entry) => entry.id === id) + if (!current) { + throw new Error('Automation not found.') + } + const updated = mergeAutomationUpdate(operations, current, updates, options) + // Replace the array to invalidate identity-keyed list projections. + operations.state.automations = operations.state.automations.map((entry) => + entry.id === id ? updated : entry + ) + operations.flush() + return automationWithLaunchSetup(updated) +} + +/** The stored record `updates` makes of `current`, checked but not yet written. */ +export function mergeAutomationUpdate( + operations: AutomationDefinitionOperations, + current: Automation, + updates: AutomationUpdateInput, + options?: AutomationUpdatePreconditions & { resolvedRepo?: Repo } +): Automation { + const projectionContext = automationProjectionContext( + operations.state, + operations.storageAuthority, + false + ) + assertAutomationOwnerFence({ + automation: current, + expectedOwner: options?.expectedOwner, + operation: 'mutate', + context: projectionContext + }) + if (options?.destination) { + assertAutomationDestination(options.destination, projectionContext) + } + assertAutomationWorkspaceModePrecondition(current, options?.expectedWorkspaceMode) + const retainContexts = retainAutomationReselectionContexts( + operations.state, + current, + updates, + options?.destination, + projectionContext + ) + const launchSetupUpdate = applyAutomationLaunchSetupPatch(updates, current) + // Ignore undefined values preserved by structuredClone; explicit clears use null. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: filtering removes only undefined entries from the validated patch and retains every remaining field's type. + const definedUpdates = Object.fromEntries( + Object.entries(launchSetupUpdate).filter(([, value]) => value !== undefined) + ) as Omit & Pick + const repoId = updates.projectId ?? current.projectId + const selectorMoveRequested = + updates.projectId !== undefined || options?.destination !== undefined + const repo = findAutomationRepoForWrite( + operations.state.repos, + repoId, + updates.runContext ?? (selectorMoveRequested ? undefined : current.runContext), + options?.resolvedRepo, + !!updates.runContext + ) + const schedulerOwner = + selectorMoveRequested && repo ? getAutomationSchedulerOwner(repo) : current.schedulerOwner + const contexts = getAutomationContextsForRepo(repo, operations.state.projectHostSetups ?? []) + const rrule = updates.rrule ?? current.rrule + const dtstart = updates.dtstart ?? current.dtstart + const scheduleChanged = updates.rrule !== undefined || updates.dtstart !== undefined + const workspaceMode = updates.workspaceMode ?? current.workspaceMode + const merged: Automation = { + ...current, + ...definedUpdates, + name: updates.name !== undefined ? updates.name.trim() || 'Untitled automation' : current.name, + precheck: Object.hasOwn(definedUpdates, 'precheck') + ? normalizeAutomationPrecheck(definedUpdates.precheck) + : normalizeAutomationPrecheck(current.precheck), + projectId: repoId, + // Why the wire object is ignored: contexts are the storing authority's own + // registry speaking. A move restates them from that registry, anything else + // keeps the stored value; an explicit null still clears. + runContext: retainContexts + ? current.runContext + : automationContextAfterUpdate( + current.runContext, + definedUpdates.runContext, + contexts.runContext, + selectorMoveRequested + ), + sourceContext: retainContexts + ? current.sourceContext + : automationContextAfterUpdate( + current.sourceContext, + definedUpdates.sourceContext, + contexts.sourceContext, + selectorMoveRequested + ), + schedulerOwner, + workspaceMode, + workspaceId: + workspaceMode === 'existing' + ? Object.hasOwn(definedUpdates, 'workspaceId') + ? (definedUpdates.workspaceId ?? null) + : current.workspaceId + : null, + baseBranch: + workspaceMode === 'new_per_run' + ? Object.hasOwn(definedUpdates, 'baseBranch') + ? (definedUpdates.baseBranch ?? null) + : (current.baseBranch ?? null) + : null, + setupDecision: normalizeAutomationSetupDecisionForWorkspaceMode( + workspaceMode, + Object.hasOwn(definedUpdates, 'setupDecision') + ? definedUpdates.setupDecision + : current.setupDecision + ), + reuseSession: + workspaceMode === 'existing' + ? (updates.reuseSession ?? current.reuseSession ?? false) + : false, + rrule, + dtstart, + nextRunAt: scheduleChanged + ? nextAutomationOccurrenceAfter(rrule, dtstart, Date.now()) + : current.nextRunAt, + updatedAt: Date.now() + } + if (retainContexts && !Object.hasOwn(current, 'sourceContext')) { + delete merged.sourceContext + } + applyAutomationSetupTrust(merged, definedUpdates, current) + delete merged.launchSetup + for (const key of ['surface', 'launchPreferences', 'agentArgs', 'extraAgentArgs'] as const) { + delete merged[key] + } + Object.assign(merged, automationCanonicalLaunchSetup(launchSetupUpdate)) + assertAutomationExtraAgentArgs(merged) + const previousPin = automationWorkspaceSshPin(operations.state, current.workspaceId) + const workspaceSshPin = automationWorkspaceSshPin(operations.state, merged.workspaceId) + const workspaceSshPinMoved = previousPin?.targetId !== workspaceSshPin?.targetId + const executionTarget = deriveAutomationExecutionTargetForUpdate({ + current, + repo, + selectorMoveRequested, + sshTargetGeneration: sshTargetGenerationForConnection( + operations.state, + repo ? getRepoSshConnectionId(repo) : undefined + ), + workspaceSshPin, + workspaceSshPinMoved + }) + refuseManagedOrcadHost(operations.state, executionTarget, workspaceSshPin, current, previousPin) + if (options?.destination) { + assertExecutionTargetMatchesDestination(executionTarget, options.destination, workspaceSshPin) + } + return applyAutomationExecutionTarget( + merged, + executionTarget, + workspaceSshPinMoved ? undefined : workspaceSshPin + ) +} diff --git a/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts b/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts deleted file mode 100644 index 1740f709dfc..00000000000 --- a/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { - _resetClosedPaneFencesForTests, - fencedIfLayoutOwner, - isClosedPaneFenced, - partitionsFence -} from './closed-pane-binding-fence' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const LOCAL: ExecutionHostId = 'local' -const SSH: ExecutionHostId = 'ssh:box' - -function sessionWith(tabId: string, leafIds: string[]): WorkspaceSessionState { - const [first, second] = leafIds - return { - ...getDefaultWorkspaceSession(), - terminalLayoutsByTabId: first - ? { - [tabId]: { - root: second - ? { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: first }, - second: { type: 'leaf', leafId: second } - } - : { type: 'leaf', leafId: first }, - activeLeafId: first, - expandedLeafId: null - } - } - : {} - } -} - -function partitions(initial: Partial>) { - const sessions = new Map(Object.entries(initial)) - return { - get: (hostId: ExecutionHostId) => sessions.get(hostId), - set: (hostId: ExecutionHostId, session: WorkspaceSessionState) => sessions.set(hostId, session) - } -} - -describe('the closed-pane fence', () => { - afterEach(() => _resetClosedPaneFencesForTests()) - - it('a write elsewhere that only keeps a fenced pane does not lift its fence', () => { - // An old relay reattach left the tab in both partitions; the SSH copy is taken back. - const store = partitions({ - [SSH]: sessionWith('t', ['a', 'b']), - [LOCAL]: sessionWith('t', ['a', 'b']) - }) - fencedIfLayoutOwner( - () => partitionsFence([SSH], store.get, true), - () => (store.set(SSH, sessionWith('t', ['a'])), { value: null }) - )() - expect(isClosedPaneFenced('t:b')).toBe(true) - - fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, false), - () => (store.set(LOCAL, sessionWith('t', ['a', 'b'])), { value: null }) - )() - expect(isClosedPaneFenced('t:b')).toBe(true) - }) - - it('a rolled-back close lifts the fence it wrote, and a rolled-back create restores the one it lifted', () => { - const store = partitions({ [LOCAL]: sessionWith('t', ['a', 'b']) }) - const close = fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, true), - () => (store.set(LOCAL, sessionWith('t', ['a'])), { value: null, rollback: () => {} }) - )() - expect(isClosedPaneFenced('t:b')).toBe(true) - close.rollback?.() - store.set(LOCAL, sessionWith('t', ['a', 'b'])) - expect(isClosedPaneFenced('t:b')).toBe(false) - - fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, true), - () => (store.set(LOCAL, sessionWith('t', ['a'])), { value: null }) - )() - const create = fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, false), - () => (store.set(LOCAL, sessionWith('t', ['a', 'b'])), { value: null, rollback: () => {} }) - )() - expect(isClosedPaneFenced('t:b')).toBe(false) - create.rollback?.() - expect(isClosedPaneFenced('t:b')).toBe(true) - }) -}) diff --git a/src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts b/src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts similarity index 82% rename from src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts rename to src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts index c96e4f498ea..3d11f3ffd55 100644 --- a/src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts +++ b/src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts @@ -1,18 +1,18 @@ import { describe, expect, it, vi } from 'vitest' -import { getDefaultUIState } from '../../../shared/constants' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' +import { getDefaultUIState } from '../../../../shared/constants' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { addWorkspace, emptySession, GIT_KEY, SSH_KEY -} from '../../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { commitLayoutCommandsAcrossPartitions } from './layout-command-commit' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) const SSH: ExecutionHostId = 'ssh:target-1' diff --git a/src/main/persistence/terminal-topology/layout-command-commit.ts b/src/main/persistence/terminal-topology/command-application/layout-command-commit.ts similarity index 85% rename from src/main/persistence/terminal-topology/layout-command-commit.ts rename to src/main/persistence/terminal-topology/command-application/layout-command-commit.ts index f295da221c7..b58cde5d3b1 100644 --- a/src/main/persistence/terminal-topology/layout-command-commit.ts +++ b/src/main/persistence/terminal-topology/command-application/layout-command-commit.ts @@ -1,28 +1,31 @@ // Apply routed-partition commands first while carrying in-memory editor views through saved-session loads. -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { LayoutApplyOutcome, LayoutCommand, LayoutEffects -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' import { keepPartitionEditorViews, partitionEditorViewsOf -} from '../loading-store/workspace-sessions/layout-editor-views' -import { keepWslMoveFrozenSessionsForStore } from '../moving-wsl-projects/terminal-state/wsl-move-session-freeze' +} from '../../loading-store/workspace-sessions/layout-editor-views' +import { keepWslMoveFrozenSessionsForStore } from '../../moving-wsl-projects/terminal-state/wsl-move-session-freeze' import { applyCommandToSession, type LayoutLiveContext, type PaneLayoutChange -} from './terminal-pane-admission' -import { writeMovedLeafProfileRecords } from './terminal-leaf-move' +} from '../pane-admission/terminal-pane-admission' +import { writeMovedLeafProfileRecords } from '../pane-moves/terminal-leaf-move' import { writeRestorable } from './restorable-write' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' -import { resolveWindowPaneDetach, type WindowPaneDetachCommand } from './window-pane-detach' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' +import { assignWorkspaceSessionPartition } from '../pane-ownership/terminal-topology-membership' +import { + resolveWindowPaneDetach, + type WindowPaneDetachCommand +} from '../pane-moves/window-pane-detach' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' export type LayoutCommandRun = { live?: LayoutLiveContext diff --git a/src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts b/src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts similarity index 90% rename from src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts rename to src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts index 89213bb966d..c455968f62c 100644 --- a/src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/pane-last-grid.test.ts b/src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts similarity index 89% rename from src/main/persistence/terminal-topology/pane-last-grid.test.ts rename to src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts index ade8d50f6ea..39cdec85300 100644 --- a/src/main/persistence/terminal-topology/pane-last-grid.test.ts +++ b/src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { OrcaRuntimeService } from '../../runtime/orca-runtime' -import type { Store } from '../loading-store/store' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import type { Store } from '../../loading-store/store' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/restorable-write.ts b/src/main/persistence/terminal-topology/command-application/restorable-write.ts similarity index 100% rename from src/main/persistence/terminal-topology/restorable-write.ts rename to src/main/persistence/terminal-topology/command-application/restorable-write.ts diff --git a/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts new file mode 100644 index 00000000000..53c06f6ab50 --- /dev/null +++ b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts @@ -0,0 +1,46 @@ +import { expect, it, vi } from 'vitest' +import { + admitRuntimeSpawnPane, + fixture +} from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' + +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ + loadUserSshConfig: () => ({ hosts: [] }), + sshConfigHostsToTargets: () => [] +})) + +const pane = { + worktreeId: 'repo-local::/fixture/local', + tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +} + +async function openWithTab() { + const opened = await fixture() + await admitRuntimeSpawnPane(opened.store, pane) + + return { + ...opened + } +} + +it('still refuses and rolls back a rename whose profile write fails', async () => { + const { store, authority } = await openWithTab() + authority.failNextWrite() + + await expect( + store.applyLayoutCommand({ + type: 'renameTab', + workspace: pane.worktreeId, + tabId: pane.tabId, + kind: 'custom', + title: 'Renamed' + }) + ).rejects.toThrow('profile_state_write_failed') + const tab = store + .getWorkspaceSession() + .tabsByWorktree[pane.worktreeId]?.find((row) => row.id === pane.tabId) + expect(tab?.customTitle ?? null).toBeNull() +}) diff --git a/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts new file mode 100644 index 00000000000..6b4fa340665 --- /dev/null +++ b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts @@ -0,0 +1,48 @@ +import { expect, it, vi } from 'vitest' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { + admitRuntimeSpawnPane, + fixture +} from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' + +// Preserve switch-off behavior regardless of the active build switch. +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ + loadUserSshConfig: () => ({ hosts: [] }), + sshConfigHostsToTargets: () => [] +})) + +const pane = { + worktreeId: 'repo-local::/fixture/local', + tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +} + +const closes: [string, LayoutCommand][] = [ + ['tab', { type: 'closeTabs', workspace: pane.worktreeId, tabIds: [pane.tabId] }], + [ + 'pane', + { + type: 'closePane', + workspace: pane.worktreeId, + tabId: pane.tabId, + leafId: pane.leafId + } + ] +] + +it.each(closes)( + 'switch off: a %s close through layout.apply still refuses and rolls back on a failed write', + async (_kind, command) => { + const { store, authority } = await fixture() + await admitRuntimeSpawnPane(store, pane) + authority.failNextWrite() + + await expect(store.applyLayoutCommand(command)).rejects.toThrow('profile_state_write_failed') + const ids = (store.getWorkspaceSession().tabsByWorktree[pane.worktreeId] ?? []).map( + (tab) => tab.id + ) + expect(ids).toContain(pane.tabId) + } +) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure.ts b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure.ts similarity index 84% rename from src/main/persistence/terminal-topology/terminal-close-write-failure.ts rename to src/main/persistence/terminal-topology/command-application/terminal-close-write-failure.ts index 7a99713e98a..8bd12cccc05 100644 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure.ts @@ -1,7 +1,7 @@ // Keep applied closes after failed saves and retry persistence; frozen writes still refuse before mutation. -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' export function isTerminalClose(command: LayoutCommand): boolean { return command.type === 'closeTabs' || command.type === 'closePane' diff --git a/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts similarity index 91% rename from src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts index 522f710b9ac..e3dbdc703e4 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts @@ -1,19 +1,19 @@ -import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' +import { withoutGitGraph } from '../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { applyCommandToSession } from './terminal-pane-admission' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import { applyCommandToSession } from '../pane-admission/terminal-pane-admission' +import { leafIds, WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts similarity index 88% rename from src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts index 7bf8631a50a..7d49d98b77b 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts @@ -2,21 +2,21 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/command-application/terminal-layout-renames-commit.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-renames-commit.ts new file mode 100644 index 00000000000..58b895ad2fc --- /dev/null +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-renames-commit.ts @@ -0,0 +1,47 @@ +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { + CommandOf, + LayoutRefusalCode +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' +import { writeRestorable } from './restorable-write' +import { applyRenamesToSession } from '../pane-admission/terminal-pane-admission' +import { traced, type TerminalTopologyCommitContext } from '../terminal-topology-commit' +import { keepFrozen } from './layout-command-commit' +import { assignWorkspaceSessionPartition } from '../pane-ownership/terminal-topology-membership' + +/** Publish routed tab renames in one frame and return per-tab refusals. */ +export function applyLayoutRenames( + batches: readonly { hostId: ExecutionHostId; renames: readonly CommandOf<'renameTab'>[] }[], + context: TerminalTopologyCommitContext +): () => DurableProfileStateMutation< + { rename: CommandOf<'renameTab'>; code: LayoutRefusalCode }[] +> { + return traced( + 'apply_layout', + () => { + const changes = batches.map(({ hostId, renames }) => ({ + hostId, + change: applyRenamesToSession(hostId, context.getSession(hostId), renames) + })) + const refused = changes.flatMap(({ change }) => change.value) + const restores = changes.flatMap(({ hostId, change }) => + change.session + ? [ + writeRestorable( + () => context.getSession(hostId), + (value) => + context.markDirty(assignWorkspaceSessionPartition(context.state, hostId, value)), + keepFrozen(hostId, change.session, context) + ) + ] + : [] + ) + return restores.length === 0 + ? { value: refused, persist: false } + : { value: refused, rollback: () => restores.forEach((restore) => restore()) } + }, + // Per-tab refusals do not reject the remaining write. + () => undefined + ) +} diff --git a/src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts similarity index 83% rename from src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts index 62951725f84..d4b999986f5 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) @@ -116,28 +116,6 @@ describe('Store.applyLayoutCommand sleep and wake (layout.apply)', () => { }) }) - it('a wake starts the pane and keeps its record, which the start resumes from', async () => { - const { store } = await storeWithSplitTab() - const left = record(LEFT, 'left-session') - await store.applyLayoutCommand({ - type: 'sleep', - workspace: WORKTREE, - paneKeys: [left.paneKey], - records: [left] - }) - const onEffects = vi.fn() - - const reply = await store.applyLayoutCommand( - { type: 'wake', workspace: WORKTREE, paneKeys: [left.paneKey] }, - [], - { onEffects } - ) - - expect(reply).toEqual({ ok: true, result: { woken: [left.paneKey] } }) - expect(onEffects).toHaveBeenCalledWith({ stopPtyIds: [], startPaneKeys: [left.paneKey] }) - expect(store.getWorkspaceSession().sleepingAgentSessionsByPaneKey?.[left.paneKey]).toEqual(left) - }) - it('wakes nothing for a pane that holds no record', async () => { const { store } = await storeWithSplitTab() const before = store.getWorkspaceSession() diff --git a/src/main/persistence/terminal-topology/cross-partition-tab-move.ts b/src/main/persistence/terminal-topology/cross-partition-tab-move.ts deleted file mode 100644 index c2eaf41cefe..00000000000 --- a/src/main/persistence/terminal-topology/cross-partition-tab-move.ts +++ /dev/null @@ -1,129 +0,0 @@ -// Main moves editor tabs across partitions and writes only changed records, retaining in-memory views. - -import type { LayoutClientVisibility } from '../../../shared/workspace-layout/workspace-layout-client-visibility' -import { randomUUID } from 'node:crypto' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { - CommandOf, - LayoutApplyOutcome -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import { updateLegacyPersistence } from '../../../shared/workspace-layout/workspace-layout-legacy-persistence' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load' -import type { LoadedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load-types' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/workspace-layout-minted-ids' -import type { - WorkspaceLayout, - WorkspaceLayoutModel -} from '../../../shared/workspace-layout/workspace-layout-model' -import { patchStoredSession } from '../../../shared/workspace-layout/workspace-layout-record-patch' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save' -import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' -import { - editorViewsOfModel, - type PartitionEditorViews -} from '../loading-store/workspace-sessions/layout-editor-views' - -type PartitionSession = { - hostId: ExecutionHostId - session: WorkspaceSessionState - /** In-memory views may be absent for this partition. */ - views?: PartitionEditorViews -} - -export type CrossPartitionTabMove = { - value: LayoutApplyOutcome - /** Null means no session changes. */ - sessions: { from: WorkspaceSessionState; to: WorkspaceSessionState } | null - views?: { from: PartitionEditorViews; to: PartitionEditorViews } -} - -function loadContext(partition: PartitionSession) { - const { views } = partition - return views - ? { ...nameBasedLoadContext(), editorViewsOf: (key: string) => views[key] } - : nameBasedLoadContext() -} - -function withLoadedWorkspace( - model: WorkspaceLayoutModel, - key: string, - workspace: WorkspaceLayout | undefined -): WorkspaceLayoutModel { - const workspaces = { ...model.workspaces } - if (workspace) { - workspaces[key] = workspace - } else { - delete workspaces[key] - } - return { ...model, workspaces } -} - -/** Patch changed loaded records back into stored form. */ -function written( - stored: WorkspaceSessionState, - loaded: LoadedWorkspaceLayout, - after: WorkspaceLayoutModel -): WorkspaceSessionState { - const layout = updateLegacyPersistence(loaded.layout, after) - return patchStoredSession( - stored, - saveWorkspaceLayout(loaded), - saveWorkspaceLayout({ ...loaded, layout }) - ) -} - -export function moveTabAcrossPartitions( - from: PartitionSession, - to: PartitionSession, - command: CommandOf<'moveTabToWorkspace'>, - visibility?: LayoutClientVisibility -): CrossPartitionTabMove { - const loadedFrom = loadWorkspaceLayout(from.hostId, from.session, loadContext(from)) - const loadedTo = loadWorkspaceLayout(to.hostId, to.session, loadContext(to)) - if (!loadedFrom.layout.workspaces[command.workspace]) { - return { value: { ok: false, code: 'workspace_not_found' }, sessions: null } - } - // Include both partitions so generated tab IDs cannot collide in either. - const joined = withLoadedWorkspace( - { - ...loadedFrom.layout, - workspaces: { ...loadedTo.layout.workspaces, ...loadedFrom.layout.workspaces } - }, - command.toWorkspace, - loadedTo.layout.workspaces[command.toWorkspace] - ) - const moved = applyLayoutCommand(joined, command, { - visibility, - mintId: randomUUID, - mintLeafId: randomUUID, - now: Date.now - }) - if (!moved.ok) { - return { value: { ok: false, code: moved.code }, sessions: null } - } - const value: LayoutApplyOutcome = { ok: true, result: moved.result } - if (moved.model === joined) { - return { value, sessions: null } - } - const fromAfter = withLoadedWorkspace( - loadedFrom.layout, - command.workspace, - moved.model.workspaces[command.workspace] - ) - const toAfter = withLoadedWorkspace( - loadedTo.layout, - command.toWorkspace, - moved.model.workspaces[command.toWorkspace] - ) - return { - value, - sessions: { - from: written(from.session, loadedFrom, fromAfter), - to: written(to.session, loadedTo, toAfter) - }, - ...(from.views && to.views - ? { views: { from: editorViewsOfModel(fromAfter), to: editorViewsOfModel(toAfter) } } - : {}) - } -} diff --git a/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts b/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts deleted file mode 100644 index 43197bb7b45..00000000000 --- a/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' -import type { ExecutionHostId } from '../../../shared/execution-host' -import { applyWindowLayoutCommand } from '../../runtime/terminal/layout/runtime-layout-apply' -import { WindowSession } from './terminal-topology-window-session-fixture' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from './terminal-topology-profile-fixture' - -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const TAB = 'tab-1' -const LEAF = '11111111-1111-4111-8111-111111111111' -const directories: string[] = [] - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -async function storeWithTerminal(worktreeId: string): Promise<{ store: Store; directory: string }> { - const directory = mkdtempSync(join(tmpdir(), 'orca-editor-apply-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - const window = new WindowSession(getDefaultWorkspaceSession()) - window.addTab(worktreeId, TAB, LEAF) - store.setWorkspaceSession(window.snapshot()) - await store.flushPendingOrThrowAsync() - return { store, directory } -} - -function editorOpen(worktreeId: string, tabId: string, path: string) { - return { - type: 'openEditorTab', - workspace: worktreeId, - tabId, - fileId: path, - contentType: 'editor', - groupId: `group-${worktreeId}`, - preview: true, - file: { filePath: path, relativePath: path.slice(1), language: 'typescript' } - } as const -} - -describe('a window moveTabToWorkspace between a local and an SSH workspace', () => { - const SSH_HOST = 'ssh:target-1' - const SSH_WORKTREE = 'repo-ssh::/home/dev/api' - const routes: Record = { - [FIXTURE_GIT_WORKTREE_ID]: 'local', - [SSH_WORKTREE]: SSH_HOST - } - const hostIdsFor = (worktreeId: string) => (routes[worktreeId] ? [routes[worktreeId]] : []) - - it.each([ - ['local to SSH', FIXTURE_GIT_WORKTREE_ID, SSH_WORKTREE], - ['SSH to local', SSH_WORKTREE, FIXTURE_GIT_WORKTREE_ID] - ])('moves a restored editor tab %s in one durable write', async (_name, from, to) => { - const { store, directory } = await storeWithTerminal(FIXTURE_GIT_WORKTREE_ID) - const path = '/fixture/other/readme.md' - const open = { ...editorOpen(from, 'e1', path), preview: undefined } - await store.applyLayoutCommand({ ...open, file: { ...open.file, relativePath: path } }, [ - routes[from]! - ]) - const newId = `editor:${to}:${path}` - const held = store.getWorkspaceSession(routes[to]).tabGroups?.[to]?.[0]?.id - await store.applyLayoutCommand( - { - type: 'openEditorTab', - workspace: to, - tabId: 'graph', - fileId: 'graph', - contentType: 'git-graph', - view: { - view: { mode: 'git-graph' }, - file: { filePath: 'graph', relativePath: 'graph', language: 'plaintext' } - }, - groupId: 'hidden', - ...(held ? { split: { besideGroupId: held, direction: 'right' as const } } : {}) - }, - [routes[to]!] - ) - const destination = held ?? 'hidden' - - await expect( - applyWindowLayoutCommand( - store, - hostIdsFor, - { - type: 'moveTabToWorkspace', - workspace: from, - toWorkspace: to, - tabs: [{ tabId: 'e1', newTabId: 'e1', newEntityId: newId }], - groupId: `group-${to}`, - file: { filePath: path, relativePath: 'readme.md', language: 'markdown' } - }, - undefined, - { visibility: withoutGitGraph } - ) - ).resolves.toEqual({ ok: true, result: { tabId: 'e1', groupId: destination } }) - - // Inspect before reload: this fixture lacks the SSH repo needed to retain its workspace. - const source = store.getWorkspaceSession(routes[from]) - const target = store.getWorkspaceSession(routes[to]) - expect(target.tabGroups?.[to]?.find((group) => group.id === destination)?.tabOrder).toEqual( - held ? [TAB, 'e1'] : ['graph', 'e1'] - ) - expect(target.unifiedTabs?.[to]?.find((tab) => tab.id === 'graph')?.contentType).toBe( - 'git-graph' - ) - expect(source.unifiedTabs?.[from]?.some((tab) => tab.id === 'e1') ?? false).toBe(false) - expect(source.openFilesByWorktree?.[from] ?? []).toEqual([]) - expect(target.unifiedTabs?.[to]?.find((tab) => tab.id === 'e1')).toMatchObject({ - entityId: newId - }) - expect(target.openFilesByWorktree?.[to]).toEqual([ - expect.objectContaining({ filePath: path, relativePath: 'readme.md', worktreeId: to }) - ]) - const reopened = await reopenTopologyStore(store, directory) - expect(reopened.getWorkspaceSession('local').tabsByWorktree[FIXTURE_GIT_WORKTREE_ID]).toEqual([ - expect.objectContaining({ id: TAB }) - ]) - expect( - reopened - .getWorkspaceSession('local') - .unifiedTabs?.[FIXTURE_GIT_WORKTREE_ID]?.some((tab) => tab.id === 'e1') - ).toBe(to === FIXTURE_GIT_WORKTREE_ID) - }) -}) diff --git a/src/main/persistence/terminal-topology/layout-command-persistence.ts b/src/main/persistence/terminal-topology/layout-command-persistence.ts index 779f03344d4..982c8a676d6 100644 --- a/src/main/persistence/terminal-topology/layout-command-persistence.ts +++ b/src/main/persistence/terminal-topology/layout-command-persistence.ts @@ -1,4 +1,4 @@ -import type { LayoutClientVisibility } from '../../../shared/workspace-layout/workspace-layout-client-visibility' +import type { LayoutClientVisibility } from '../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { CommandOf, @@ -7,7 +7,7 @@ import type { LayoutEffects, LayoutRefusalCode } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { LayoutLiveContext } from './terminal-pane-admission' +import type { LayoutLiveContext } from './pane-admission/terminal-pane-admission' import { resolveHostId, type SessionHostPartitionOperations @@ -22,22 +22,25 @@ import { applyEditorFileRenamesInPartitions, topologyCommitContext } from './terminal-topology-commit' -import { keepFrozen } from './layout-command-commit' -import { applyLayoutRenames } from './terminal-layout-renames-commit' -import { isTerminalClose, keptOnWriteFailure } from './terminal-close-write-failure' +import { keepFrozen } from './command-application/layout-command-commit' +import { applyLayoutRenames } from './command-application/terminal-layout-renames-commit' +import { + isTerminalClose, + keptOnWriteFailure +} from './command-application/terminal-close-write-failure' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { moveTabAcrossPartitions } from './cross-partition-tab-move' -import { writeRestorable } from './restorable-write' -import { raisingBindingGenerations } from './layout-command-binding-generations' +import { moveTabAcrossPartitions } from './pane-moves/cross-partition-tab-move' +import { writeRestorable } from './command-application/restorable-write' +import { raisingBindingGenerations } from './pane-ownership/layout-command-binding-generations' import { keepPartitionEditorViews, partitionEditorViewsOf } from '../loading-store/workspace-sessions/layout-editor-views' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' +import { assignWorkspaceSessionPartition } from './pane-ownership/terminal-topology-membership' import { repairDuplicatePtyPanesMutation, type DuplicatePtyPaneTransfer -} from './duplicate-pty-pane-repair' +} from './pane-ownership/duplicate-pty-pane-repair' /** Scope publication so readers reload only changed partitions. */ function writingOnly( diff --git a/src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts b/src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts similarity index 93% rename from src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts rename to src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts index 4256cba8ad4..ffc1da6f38c 100644 --- a/src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts @@ -1,11 +1,11 @@ -import { closeTestStores, createStore, testState } from '../persistence-test-harness' +import { closeTestStores, createStore, testState } from '../../persistence-test-harness' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, diff --git a/src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts similarity index 79% rename from src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts index 62fa62d5fde..a79bbc87f30 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts @@ -2,21 +2,21 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' -import type { Store } from '../loading-store/store' -import { _resetClosedPaneFencesForTests } from './closed-pane-binding-fence' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' +import type { Store } from '../../loading-store/store' +import { _resetClosedPaneFencesForTests } from '../pane-ownership/closed-pane-binding-fence' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts new file mode 100644 index 00000000000..05a81c14bcc --- /dev/null +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts @@ -0,0 +1,128 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' +import { + emptyTerminalSessionProfile, + FIXTURE_FOLDER_WORKTREE_ID, + FIXTURE_GIT_WORKTREE_ID, + openTopologyStore, + reopenTopologyStore +} from '../testing/terminal-topology-profile-fixture' + +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ + loadUserSshConfig: () => ({ hosts: [] }), + sshConfigHostsToTargets: () => [] +})) + +const WORKTREE = FIXTURE_GIT_WORKTREE_ID +const GROUP = `group-${WORKTREE}` +const TAB = 'tab-1' +const LEAF = '11111111-1111-4111-8111-111111111111' +const NEW_TAB = 'tab-new' +const NEW_LEAF = '22222222-2222-4222-8222-222222222222' +const directories: string[] = [] + +afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +async function openStore( + seed: (window: WindowSession) => void, + hostId?: string +): Promise<{ store: Store; directory: string }> { + const directory = mkdtempSync(join(tmpdir(), 'orca-layout-create-')) + directories.push(directory) + const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) + const window = new WindowSession(getDefaultWorkspaceSession()) + seed(window) + store.setWorkspaceSession(window.snapshot(), hostId) + await store.flushPendingOrThrowAsync() + return { store, directory } +} + +const withOneTab = (window: WindowSession): void => { + window.addTab(WORKTREE, TAB, LEAF) + window.bind(TAB, LEAF, 'pty-1') +} + +const create: CommandOf<'createTerminalTab'> = { + type: 'createTerminalTab', + workspace: WORKTREE, + tabId: NEW_TAB, + leafId: NEW_LEAF, + groupId: GROUP, + creation: { defaultTitle: 'Terminal 2', startupCwd: '/fixture/local/src' } +} + +describe('Store.applyLayoutCommand: a window’s terminal tab create', () => { + it('writes the tab durably under the window’s ids, in the group it names', async () => { + const { store, directory } = await openStore(withOneTab) + + const reply = await store.applyLayoutCommand(create) + + expect(reply).toEqual({ + ok: true, + result: { tabId: NEW_TAB, leafId: NEW_LEAF, paneKey: `${NEW_TAB}:${NEW_LEAF}` } + }) + const session = (await reopenTopologyStore(store, directory)).getWorkspaceSession() + expect(session.terminalLayoutsByTabId[NEW_TAB]?.root).toEqual({ + type: 'leaf', + leafId: NEW_LEAF + }) + const row = session.tabsByWorktree[WORKTREE]?.find((tab) => tab.id === NEW_TAB) + expect(row).toMatchObject({ defaultTitle: 'Terminal 2', startupCwd: '/fixture/local/src' }) + expect(session.tabGroups?.[WORKTREE]?.[0]).toMatchObject({ + id: GROUP, + tabOrder: [TAB, NEW_TAB] + }) + }) + + it('writes an SSH workspace’s tab into that host’s partition only', async () => { + const { store } = await openStore(withOneTab, 'ssh:target-1') + const local = store.getWorkspaceSession() + + const reply = await store.applyLayoutCommand(create, ['ssh:target-1']) + + expect(reply.ok).toBe(true) + expect(store.getWorkspaceSession('ssh:target-1').terminalLayoutsByTabId[NEW_TAB]?.root).toEqual( + { type: 'leaf', leafId: NEW_LEAF } + ) + expect(store.getWorkspaceSession()).toEqual(local) + }) +}) + +describe('Store.applyLayoutCommand: a workspace’s default tabs', () => { + const defaults: CommandOf<'applyDefaultTabs'> = { + type: 'applyDefaultTabs', + workspace: FIXTURE_FOLDER_WORKTREE_ID, + tabs: [ + { tabId: NEW_TAB, leafId: NEW_LEAF, title: 'Server' }, + { tabId: 'tab-new-2', leafId: '33333333-3333-4333-8333-333333333333', color: 'blue' } + ] + } + + it('writes every tab under the window’s ids with the mark, durably, in one command', async () => { + const { store, directory } = await openStore(withOneTab) + + const reply = await store.applyLayoutCommand(defaults) + + expect(reply.ok && reply.result.createdTabs?.map((tab) => tab.tabId)).toEqual([ + NEW_TAB, + 'tab-new-2' + ]) + const session = (await reopenTopologyStore(store, directory)).getWorkspaceSession() + expect(session.tabsByWorktree[FIXTURE_FOLDER_WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ + NEW_TAB, + 'tab-new-2' + ]) + expect(session.defaultTerminalTabsAppliedByWorktreeId?.[FIXTURE_FOLDER_WORKTREE_ID]).toBe(true) + }) +}) diff --git a/src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts similarity index 86% rename from src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts index b7a6d1baf6a..cecab47edb1 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts @@ -2,18 +2,18 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { Store } from '../../loading-store/store' +import { leafIds, WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-pane-admission.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission.ts similarity index 87% rename from src/main/persistence/terminal-topology/terminal-pane-admission.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission.ts index 88822bc30e8..eb3730fe03d 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-admission.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission.ts @@ -1,12 +1,12 @@ // Persist runtime pane membership before spawning through the same layout model used by client commands. import { randomUUID } from 'node:crypto' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { leafIdsOf, locatePane -} from '../../../shared/workspace-layout/workspace-layout-command-steps' +} from '../../../../shared/workspace-layout/commands/workspace-layout-command-steps' import type { CommandOf, LayoutApplyOutcome, @@ -14,27 +14,27 @@ import type { LayoutContext, LayoutEffects, LayoutRefusalCode -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load' -import type { LoadedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load-types' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/workspace-layout-minted-ids' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import { paneKeyOf, type WorkspaceLayoutModel -} from '../../../shared/workspace-layout/workspace-layout-model' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save' -import { patchStoredSession } from '../../../shared/workspace-layout/workspace-layout-record-patch' +} from '../../../../shared/workspace-layout/workspace-layout-model' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' +import { patchStoredSession } from '../../../../shared/workspace-layout/persistence/workspace-layout-record-patch' import { followRemoteSessionAfterPaneClose, followRemoteSessionAfterPaneDetach -} from './pane-remote-session-follow' -import { pruneClosedTerminalTabTombstones } from '../../../shared/workspace-layout/closed-terminal-tab-tombstones' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +} from '../pane-moves/pane-remote-session-follow' +import { pruneClosedTerminalTabTombstones } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { editorViewsOfModel, type PartitionEditorViews -} from '../loading-store/workspace-sessions/layout-editor-views' +} from '../../loading-store/workspace-sessions/layout-editor-views' export type TerminalPaneAdmission = | (CommandOf<'createTerminalTab'> & { tabId: string; leafId: string }) diff --git a/src/main/persistence/terminal-topology/terminal-pane-placement-agreement.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-agreement.ts similarity index 78% rename from src/main/persistence/terminal-topology/terminal-pane-placement-agreement.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-agreement.ts index 7229bf93e6e..2472991785a 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-placement-agreement.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-agreement.ts @@ -1,6 +1,6 @@ -import type { TerminalPanePlacement } from '../../../shared/workspace-layout/terminal-pane-placement' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { layoutContainsLeafId } from '../restoring-sessions/terminal-layout-normalization' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' /** Low-cardinality span attribute; absent tracks new leaves relying on legacy mint/graft placement. */ export type TerminalPanePlacementAgreement = diff --git a/src/main/persistence/terminal-topology/terminal-pane-placement-graft.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-graft.ts similarity index 84% rename from src/main/persistence/terminal-topology/terminal-pane-placement-graft.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-graft.ts index 063e99f02fa..8a3976e2eab 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-placement-graft.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-graft.ts @@ -1,13 +1,13 @@ -import type { TerminalPanePlacement } from '../../../shared/workspace-layout/terminal-pane-placement' -import type { TerminalPaneLayoutNode } from '../../../shared/workspace-layout/terminal-tab-types' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' +import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' import { collectLayoutLeafIdsInOrder, insertLeafBeside, layoutContainsLeafId, removeLayoutLeaf, samePanesIgnoringRatios -} from '../../../shared/workspace-layout/terminal-pane-tree' -import { cloneLayoutNode } from '../restoring-sessions/terminal-layout-normalization' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { cloneLayoutNode } from '../../restoring-sessions/terminal-layout-normalization' /** Accept a proposed tree only if it adds this leaf alone; otherwise split beside the parent or return null. */ export function placedSplitRoot( diff --git a/src/main/persistence/terminal-topology/unstarted-pane-withdraw.ts b/src/main/persistence/terminal-topology/pane-admission/unstarted-pane-withdraw.ts similarity index 76% rename from src/main/persistence/terminal-topology/unstarted-pane-withdraw.ts rename to src/main/persistence/terminal-topology/pane-admission/unstarted-pane-withdraw.ts index 784f4b0d4a9..c67ea42c4b0 100644 --- a/src/main/persistence/terminal-topology/unstarted-pane-withdraw.ts +++ b/src/main/persistence/terminal-topology/pane-admission/unstarted-pane-withdraw.ts @@ -1,10 +1,10 @@ -import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' import type { CommandOf, LayoutRefusalCode -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' -import { withdrawPane, type TerminalTopologyCommitContext } from './terminal-topology-commit' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' +import { withdrawPane, type TerminalTopologyCommitContext } from '../terminal-topology-commit' export type UnstartedPaneKept = 'bound' | 'starting' diff --git a/src/main/persistence/terminal-topology/pane-moves/cross-partition-tab-move.ts b/src/main/persistence/terminal-topology/pane-moves/cross-partition-tab-move.ts new file mode 100644 index 00000000000..669b8506020 --- /dev/null +++ b/src/main/persistence/terminal-topology/pane-moves/cross-partition-tab-move.ts @@ -0,0 +1,129 @@ +// Main moves editor tabs across partitions and writes only changed records, retaining in-memory views. + +import type { LayoutClientVisibility } from '../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' +import { randomUUID } from 'node:crypto' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { + CommandOf, + LayoutApplyOutcome +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { updateLegacyPersistence } from '../../../../shared/workspace-layout/persistence/workspace-layout-legacy-persistence' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +import type { + WorkspaceLayout, + WorkspaceLayoutModel +} from '../../../../shared/workspace-layout/workspace-layout-model' +import { patchStoredSession } from '../../../../shared/workspace-layout/persistence/workspace-layout-record-patch' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' +import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' +import { + editorViewsOfModel, + type PartitionEditorViews +} from '../../loading-store/workspace-sessions/layout-editor-views' + +type PartitionSession = { + hostId: ExecutionHostId + session: WorkspaceSessionState + /** In-memory views may be absent for this partition. */ + views?: PartitionEditorViews +} + +export type CrossPartitionTabMove = { + value: LayoutApplyOutcome + /** Null means no session changes. */ + sessions: { from: WorkspaceSessionState; to: WorkspaceSessionState } | null + views?: { from: PartitionEditorViews; to: PartitionEditorViews } +} + +function loadContext(partition: PartitionSession) { + const { views } = partition + return views + ? { ...nameBasedLoadContext(), editorViewsOf: (key: string) => views[key] } + : nameBasedLoadContext() +} + +function withLoadedWorkspace( + model: WorkspaceLayoutModel, + key: string, + workspace: WorkspaceLayout | undefined +): WorkspaceLayoutModel { + const workspaces = { ...model.workspaces } + if (workspace) { + workspaces[key] = workspace + } else { + delete workspaces[key] + } + return { ...model, workspaces } +} + +/** Patch changed loaded records back into stored form. */ +function written( + stored: WorkspaceSessionState, + loaded: LoadedWorkspaceLayout, + after: WorkspaceLayoutModel +): WorkspaceSessionState { + const layout = updateLegacyPersistence(loaded.layout, after) + return patchStoredSession( + stored, + saveWorkspaceLayout(loaded), + saveWorkspaceLayout({ ...loaded, layout }) + ) +} + +export function moveTabAcrossPartitions( + from: PartitionSession, + to: PartitionSession, + command: CommandOf<'moveTabToWorkspace'>, + visibility?: LayoutClientVisibility +): CrossPartitionTabMove { + const loadedFrom = loadWorkspaceLayout(from.hostId, from.session, loadContext(from)) + const loadedTo = loadWorkspaceLayout(to.hostId, to.session, loadContext(to)) + if (!loadedFrom.layout.workspaces[command.workspace]) { + return { value: { ok: false, code: 'workspace_not_found' }, sessions: null } + } + // Include both partitions so generated tab IDs cannot collide in either. + const joined = withLoadedWorkspace( + { + ...loadedFrom.layout, + workspaces: { ...loadedTo.layout.workspaces, ...loadedFrom.layout.workspaces } + }, + command.toWorkspace, + loadedTo.layout.workspaces[command.toWorkspace] + ) + const moved = applyLayoutCommand(joined, command, { + visibility, + mintId: randomUUID, + mintLeafId: randomUUID, + now: Date.now + }) + if (!moved.ok) { + return { value: { ok: false, code: moved.code }, sessions: null } + } + const value: LayoutApplyOutcome = { ok: true, result: moved.result } + if (moved.model === joined) { + return { value, sessions: null } + } + const fromAfter = withLoadedWorkspace( + loadedFrom.layout, + command.workspace, + moved.model.workspaces[command.workspace] + ) + const toAfter = withLoadedWorkspace( + loadedTo.layout, + command.toWorkspace, + moved.model.workspaces[command.toWorkspace] + ) + return { + value, + sessions: { + from: written(from.session, loadedFrom, fromAfter), + to: written(to.session, loadedTo, toAfter) + }, + ...(from.views && to.views + ? { views: { from: editorViewsOfModel(fromAfter), to: editorViewsOfModel(toAfter) } } + : {}) + } +} diff --git a/src/main/persistence/terminal-topology/pane-remote-session-follow.ts b/src/main/persistence/terminal-topology/pane-moves/pane-remote-session-follow.ts similarity index 90% rename from src/main/persistence/terminal-topology/pane-remote-session-follow.ts rename to src/main/persistence/terminal-topology/pane-moves/pane-remote-session-follow.ts index 7c1c876cf2c..dadbecc7118 100644 --- a/src/main/persistence/terminal-topology/pane-remote-session-follow.ts +++ b/src/main/persistence/terminal-topology/pane-moves/pane-remote-session-follow.ts @@ -1,5 +1,5 @@ -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' /** Remote session IDs live outside the layout model and must follow the remaining pane after close. */ export function followRemoteSessionAfterPaneClose( diff --git a/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts new file mode 100644 index 00000000000..5388c811229 --- /dev/null +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts @@ -0,0 +1,56 @@ +import { tmpdir } from 'node:os' +import { afterEach, expect, it, vi } from 'vitest' + +import '../../persistence-test-harness' +import { + closeMoveTestStores, + MOVED, + moveRequest, + newDataFile, + openStore, + seedSplitSource, + SOURCE, + TARGET, + tabsHoldingLeaf, + WT +} from '../testing/terminal-leaf-move-fixture' +import '../terminal-topology-commit' + +vi.mock('electron', () => ({ + app: { + getPath: () => tmpdir(), + getName: () => 'orca-test', + getVersion: () => '0.0.0-test', + isPackaged: false, + on: () => {}, + whenReady: () => Promise.resolve() + }, + safeStorage: { + isEncryptionAvailable: () => false, + encryptString: (value: string) => Buffer.from(value), + decryptString: (value: Buffer) => value.toString() + }, + ipcMain: { on: () => {}, handle: () => {} }, + BrowserWindow: { getAllWindows: () => [] } +})) + +afterEach(closeMoveTestStores) + +const request = { ...moveRequest, ptyId: 'pty-agent' } + +// The renderer completes a post-move close against main's new tab. + +// In-flight drags must refuse: a spawn without captured PTY identity can recreate SOURCE:leaf after move. +it('grafts a late spawn result for the moved leaf back into its source tab', async () => { + const store = openStore(newDataFile()) + await seedSplitSource(store) + await store.moveTerminalLeafToNewTab({ ...request, ptyId: null }) + await store.persistPtyBinding({ + worktreeId: WT, + tabId: SOURCE, + leafId: MOVED, + ptyId: 'pty-late', + incarnationId: 'inc-late' + }) + expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED).sort()).toEqual([SOURCE, TARGET]) +}) diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts similarity index 97% rename from src/main/persistence/terminal-topology/terminal-leaf-move.test.ts rename to src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts index 3e7c628392b..0ba41a168b5 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { toSshExecutionHostId } from '../../../shared/execution-host' -import { _resetTracerForTests } from '../../observability/tracer' -import { makeRepo } from '../persistence-test-harness' +import { toSshExecutionHostId } from '../../../../shared/execution-host' +import { _resetTracerForTests } from '../../../observability/tracer' +import { makeRepo } from '../../persistence-test-harness' import { closeMoveTestStores, @@ -21,7 +21,7 @@ import { tabsHoldingLeaf, TO, WT -} from './terminal-leaf-move-fixture' +} from '../testing/terminal-leaf-move-fixture' vi.mock('electron', () => ({ app: { diff --git a/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.ts new file mode 100644 index 00000000000..332c842e43f --- /dev/null +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.ts @@ -0,0 +1,298 @@ +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' +import { + terminalLeafMovePaneKeys, + type TerminalLeafMoveRequest, + type TerminalLeafMoveResult +} from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' +import type { + TerminalLayoutSnapshot, + TerminalTab +} from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-leaf-retirement' +import { createMinimalPersistedTerminalTab } from '../../restoring-sessions/session-owner-fields' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { writeRestorable } from '../command-application/restorable-write' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' +import { + advanceTerminalTopologyRevision, + isTerminalOwnerPartition, + type TerminalSessionPartition +} from '../pane-ownership/terminal-topology-membership' + +type PlannedTerminalLeafMove = { + result: TerminalLeafMoveResult + sessions: TerminalSessionPartition[] +} + +export function moveRecordKey( + record: Record | undefined, + fromKey: string, + toKey: string | null, + remap: (value: T) => T = (value) => value, + /** Preserve existing destination values on collision. */ + keepTarget = false +): Record | undefined { + if (!record || !Object.hasOwn(record, fromKey)) { + return record + } + const next = { ...record } + const value = next[fromKey] + delete next[fromKey] + if (toKey !== null && value !== undefined && !(keepTarget && Object.hasOwn(next, toKey))) { + next[toKey] = remap(value) + } + return next +} + +function liveTabIds(session: WorkspaceSessionState): Set { + return new Set( + Object.values(session.tabsByWorktree ?? {}).flatMap((tabs) => tabs.map((tab) => tab.id)) + ) +} + +function hasTabId(session: WorkspaceSessionState, tabId: string): boolean { + return ( + liveTabIds(session).has(tabId) || Object.hasOwn(session.terminalLayoutsByTabId ?? {}, tabId) + ) +} + +/** Removed-tab layouts cannot claim leaf ownership. */ +export function leafHeldByOtherTab( + session: WorkspaceSessionState, + sourceTabId: string, + leafId: string +): boolean { + const tabIds = liveTabIds(session) + return Object.entries(session.terminalLayoutsByTabId ?? {}).some( + ([tabId, layout]) => + tabId !== sourceTabId && + tabIds.has(tabId) && + layoutContainsLeafId(layout?.root ?? null, leafId) + ) +} + +type SourceHolder = TerminalSessionPartition & { + sourceTab: TerminalTab + sourceLayout: TerminalLayoutSnapshot +} + +function moveLeafInPartition( + { session, sourceTab, sourceLayout }: SourceHolder, + request: TerminalLeafMoveRequest, + ptyId: string | null +): WorkspaceSessionState { + const { worktreeId, sourceTabId, targetTabId, leafId } = request + const tabs = session.tabsByWorktree?.[worktreeId] ?? [] + const { from: fromPaneKey, to: toPaneKey } = terminalLeafMovePaneKeys(request) + const boundHere = sourceLayout.ptyIdsByLeafId?.[leafId] + const remainingLayout = retireLeavesFromTerminalLayout(sourceLayout, new Set([leafId])) + const remainingPtyIds = Object.values(remainingLayout?.ptyIdsByLeafId ?? {}) + const row = createMinimalPersistedTerminalTab({ + worktreeId, + tabId: targetTabId, + ptyId: ptyId ?? '', + existingTabCount: tabs.length, + ...(sourceTab.startupCwd ? { startupCwd: sourceTab.startupCwd } : {}) + }) + const targetTab = { + ...row, + ptyId, + ...(sourceTab.shellOverride ? { shellOverride: sourceTab.shellOverride } : {}) + } + const nextTabs = tabs.map((tab) => + tab.id === sourceTabId && tab.ptyId === ptyId + ? { ...tab, ptyId: remainingPtyIds[0] ?? null } + : tab + ) + const movedTitle = sourceLayout.titlesByLeafId?.[leafId] + const terminalLayoutsByTabId = { + ...session.terminalLayoutsByTabId, + [targetTabId]: { + root: { type: 'leaf' as const, leafId }, + activeLeafId: leafId, + expandedLeafId: null, + ...(ptyId ? { ptyIdsByLeafId: { [leafId]: ptyId } } : {}), + ...(movedTitle ? { titlesByLeafId: { [leafId]: movedTitle } } : {}), + ...(sourceLayout.chatLeafId === leafId ? { chatLeafId: leafId } : {}) + } + } + if (remainingLayout) { + terminalLayoutsByTabId[sourceTabId] = remainingLayout + } else { + // A sibling never bound here can recreate its layout when its own binding arrives. + delete terminalLayoutsByTabId[sourceTabId] + } + const remoteSessionIdsByTabId = { ...session.remoteSessionIdsByTabId } + if (ptyId && remoteSessionIdsByTabId[sourceTabId] === ptyId) { + remoteSessionIdsByTabId[targetTabId] = ptyId + if (remainingPtyIds[0]) { + remoteSessionIdsByTabId[sourceTabId] = remainingPtyIds[0] + } else { + delete remoteSessionIdsByTabId[sourceTabId] + } + } + return advanceTerminalTopologyRevision( + { + ...session, + tabsByWorktree: { ...session.tabsByWorktree, [worktreeId]: [...nextTabs, targetTab] }, + terminalLayoutsByTabId, + ...(session.remoteSessionIdsByTabId ? { remoteSessionIdsByTabId } : {}), + // Stale copies cannot carry another PTY's incarnation to the destination. + terminalPtyIncarnationsByPaneKey: moveRecordKey( + session.terminalPtyIncarnationsByPaneKey, + fromPaneKey, + boundHere && boundHere !== ptyId ? null : toPaneKey + ), + sleepingAgentSessionsByPaneKey: moveRecordKey( + session.sleepingAgentSessionsByPaneKey, + fromPaneKey, + toPaneKey, + (record) => ({ ...record, paneKey: toPaneKey, tabId: targetTabId }) + ) + }, + worktreeId + ) +} + +/** Move every partition holder and pane-keyed record atomically; preserve leaf/PTY identity (STA-9259). */ +export function planTerminalLeafMove( + partitions: readonly TerminalSessionPartition[], + request: TerminalLeafMoveRequest +): PlannedTerminalLeafMove { + const { worktreeId, sourceTabId, leafId } = request + const refuse = ( + reason: Extract['reason'] + ): PlannedTerminalLeafMove => ({ result: { status: 'refused', reason }, sessions: [] }) + const owners = partitions.filter(({ hostId }) => isTerminalOwnerPartition(hostId)) + if (partitions.some(({ session }) => hasTabId(session, request.targetTabId))) { + return refuse('target_tab_exists') + } + if (owners.some(({ session }) => leafHeldByOtherTab(session, sourceTabId, leafId))) { + return refuse('leaf_in_other_tab') + } + const holders = owners.flatMap(({ hostId, session }) => { + const sourceTab = session.tabsByWorktree?.[worktreeId]?.find((tab) => tab.id === sourceTabId) + const sourceLayout = session.terminalLayoutsByTabId?.[sourceTabId] + return sourceTab && sourceLayout && layoutContainsLeafId(sourceLayout.root, leafId) + ? [{ hostId, session, sourceTab, sourceLayout }] + : [] + }) + if (holders.length === 0) { + return { result: { status: 'not_held' }, sessions: [] } + } + if ( + request.keepsSourcePane && + holders.some(({ sourceLayout }) => collectLeafIds(sourceLayout.root).length < 2) + ) { + return refuse('last_pane') + } + const boundPtyIds = new Set( + holders.flatMap(({ sourceLayout }) => sourceLayout.ptyIdsByLeafId?.[leafId] ?? []) + ) + // Prefer the renderer's live PTY; an SSH respawn can leave an old ID in one copy. + const ptyId = request.ptyId ?? (boundPtyIds.size === 1 ? [...boundPtyIds][0] : null) + if (boundPtyIds.size > 0 && !(ptyId && boundPtyIds.has(ptyId))) { + return refuse('pty_mismatch') + } + return { + result: { status: 'moved', ptyId }, + sessions: holders.map((holder) => ({ + hostId: holder.hostId, + session: moveLeafInPartition(holder, request, ptyId) + })) + } +} + +const PANE_KEYED_UI_RECORDS = [ + 'acknowledgedAgentsByPaneKey', + 'activityClearedAtByPaneKey', + 'manuallyUnreadTurnsByPaneKey' +] as const + +type PaneAddress = { tabId: string; leafId: string } + +export function rekeyPaneProfileRecords( + state: Pick, + from: PaneAddress, + to: PaneAddress +): { ui?: PersistedState['ui']; sshRemotePtyLeases?: SshRemotePtyLease[] } { + const fromPaneKey = makePaneKey(from.tabId, from.leafId) + const toPaneKey = makePaneKey(to.tabId, to.leafId) + const ui = state.ui + let nextUi: PersistedState['ui'] | undefined + for (const key of PANE_KEYED_UI_RECORDS) { + const moved = moveRecordKey(ui?.[key], fromPaneKey, toPaneKey) + if (ui && moved !== ui[key]) { + nextUi = { ...(nextUi ?? ui), [key]: moved } + } + } + const leases = state.sshRemotePtyLeases ?? [] + const leasesChanged = leases.some( + (lease) => lease.tabId === from.tabId && lease.leafId === from.leafId + ) + return { + ...(nextUi ? { ui: nextUi } : {}), + ...(leasesChanged + ? { + sshRemotePtyLeases: leases.map((lease) => + lease.tabId === from.tabId && lease.leafId === from.leafId + ? { ...lease, tabId: to.tabId, leafId: to.leafId } + : lease + ) + } + : {}) + } +} + +export function rekeyMovedLeafProfileRecords( + state: Pick, + move: TerminalLeafMoveRequest +): { ui?: PersistedState['ui']; sshRemotePtyLeases?: SshRemotePtyLease[] } { + return rekeyPaneProfileRecords( + state, + { tabId: move.sourceTabId, leafId: move.leafId }, + { tabId: move.targetTabId, leafId: move.leafId } + ) +} + +/** Return restores for rekeyed UI marks and SSH leases. */ +export function writeMovedLeafProfileRecords( + request: TerminalLeafMoveRequest, + context: TerminalTopologyCommitContext +): (() => void)[] { + return writeRekeyedProfileRecords(rekeyMovedLeafProfileRecords(context.state, request), context) +} + +/** Return restores for rekeyed profile records. */ +export function writeRekeyedProfileRecords( + rekeyed: ReturnType, + context: TerminalTopologyCommitContext +): (() => void)[] { + const { state } = context + const restores: (() => void)[] = [] + if (rekeyed.ui) { + restores.push( + writeRestorable( + () => state.ui, + (ui) => (state.ui = ui), + rekeyed.ui + ) + ) + context.markDirty('ui') + } + if (rekeyed.sshRemotePtyLeases) { + restores.push( + writeRestorable( + () => state.sshRemotePtyLeases, + (leases) => (state.sshRemotePtyLeases = leases), + rekeyed.sshRemotePtyLeases + ) + ) + context.markDirty('sshRemotePtyLeases') + } + return restores +} diff --git a/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts similarity index 97% rename from src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts rename to src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts index 1155756d26f..158412257fc 100644 --- a/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { toSshExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { makeRepo } from '../persistence-test-harness' -import type { Store } from '../loading-store/store' +import { toSshExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { makeRepo } from '../../persistence-test-harness' +import type { Store } from '../../loading-store/store' import { closeMoveTestStores, FROM, @@ -20,7 +20,7 @@ import { tabsHoldingLeaf, TO, WT -} from './terminal-leaf-move-fixture' +} from '../testing/terminal-leaf-move-fixture' vi.mock('electron', () => ({ app: { diff --git a/src/main/persistence/terminal-topology/window-pane-detach.ts b/src/main/persistence/terminal-topology/pane-moves/window-pane-detach.ts similarity index 80% rename from src/main/persistence/terminal-topology/window-pane-detach.ts rename to src/main/persistence/terminal-topology/pane-moves/window-pane-detach.ts index d8c21f83ffc..335eb023f84 100644 --- a/src/main/persistence/terminal-topology/window-pane-detach.ts +++ b/src/main/persistence/terminal-topology/pane-moves/window-pane-detach.ts @@ -1,25 +1,25 @@ // Validate every holder before any partition writes a renderer-requested detach. import { randomUUID } from 'node:crypto' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import type { ExecutionHostId } from '../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import type { ExecutionHostId } from '../../../../shared/execution-host' import { collectLayoutLeafIdsInOrder, layoutContainsLeafId -} from '../../../shared/workspace-layout/terminal-pane-tree' -import { findTerminal } from '../../../shared/workspace-layout/workspace-layout-command-steps' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { findTerminal } from '../../../../shared/workspace-layout/commands/workspace-layout-command-steps' import type { CommandOf, LayoutRefusalCode, WindowPaneDetach -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/workspace-layout-minted-ids' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import { leafHeldByOtherTab } from './terminal-leaf-move' import { isTerminalOwnerPartition, type TerminalSessionPartition -} from './terminal-topology-membership' +} from '../pane-ownership/terminal-topology-membership' export type WindowPaneDetachCommand = CommandOf<'movePaneToNewTab'> & { windowDetach: WindowPaneDetach diff --git a/src/main/persistence/terminal-topology/closed-pane-binding-fence.ts b/src/main/persistence/terminal-topology/pane-ownership/closed-pane-binding-fence.ts similarity index 88% rename from src/main/persistence/terminal-topology/closed-pane-binding-fence.ts rename to src/main/persistence/terminal-topology/pane-ownership/closed-pane-binding-fence.ts index 9134c3c0681..9caa1a91329 100644 --- a/src/main/persistence/terminal-topology/closed-pane-binding-fence.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/closed-pane-binding-fence.ts @@ -1,11 +1,11 @@ // Layout-owner builds fence removed panes against late spawns that would recreate missing membership. -import type { ExecutionHostId } from '../../../shared/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-pane-tree' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' // Five minutes covers credential/connect/relay waits; unique pane IDs make longer fences harmless apart from memory. export const CLOSED_PANE_BINDING_FENCE_MS = 5 * 60_000 diff --git a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts similarity index 75% rename from src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts rename to src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts index ad1b9e316fb..78fc059cb6a 100644 --- a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts @@ -2,24 +2,24 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { repairDuplicatePtyPanesOnStart } from '../../runtime/terminal/identity/moved-pane-owner-rekey' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { DelayedAuthority } from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' -import { Store } from '../loading-store/store' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { repairDuplicatePtyPanesOnStart } from '../../../runtime/terminal/identity/moved-pane-owner-rekey' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { DelayedAuthority } from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' +import { Store } from '../../loading-store/store' +import { ProfileStateSqliteAuthority } from '../../profile-state/profile-state-sqlite-authority' import { planDuplicatePtyPaneRepair } from './duplicate-pty-pane-repair' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { leafIds, WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) @@ -147,26 +147,6 @@ describe('duplicate-terminal pane repair at load (layout-owner builds)', () => { expect(storedLeafIds(directory)).toEqual([KEPT]) expect(JSON.parse(storedLayouts(directory))[TAB].ptyIdsByLeafId).toEqual({ [KEPT]: 'pty-1' }) }) - - it('writes nothing when a pane owner move fails, so the next start retries', async () => { - const directory = seededDirectory() - const seeded = storedLayouts(directory) - const { store } = await load(directory) - vi.spyOn(agentHookServer, 'transferPaneAuthority').mockImplementation(() => {}) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the repair reads only the orchestration DB accessor. - const runtime = { - getExistingOrchestrationDb: () => ({ - rekeyWorkerTerminalResourcePaneKey: () => { - throw new Error('database is locked') - } - }) - } as unknown as OrcaRuntimeService - - await repairDuplicatePtyPanesOnStart(store, runtime) - await quit(store) - - expect(storedLayouts(directory)).toBe(seeded) - }) }) describe('planDuplicatePtyPaneRepair', () => { diff --git a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.ts b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.ts similarity index 83% rename from src/main/persistence/terminal-topology/duplicate-pty-pane-repair.ts rename to src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.ts index 005b55b574a..1c78a2a132d 100644 --- a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.ts @@ -1,22 +1,22 @@ -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { normalizeTerminalLayoutPtyOwnership, resolveTerminalLayoutPtyOwnershipTransfers -} from '../../../shared/workspace-layout/terminal-layout-pty-ownership' -import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' -import { isWslMoveWorkspaceSessionFrozen } from '../moving-wsl-projects/quiescence/wsl-move-scope-guard' -import { findWorktreeIdForTab } from '../restoring-sessions/pane-identity-migration' -import { writeRestorable } from './restorable-write' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership' +import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' +import { isWslMoveWorkspaceSessionFrozen } from '../../moving-wsl-projects/quiescence/wsl-move-scope-guard' +import { findWorktreeIdForTab } from '../../restoring-sessions/pane-identity-migration' +import { writeRestorable } from '../command-application/restorable-write' import { moveRecordKey, rekeyPaneProfileRecords, writeRekeyedProfileRecords -} from './terminal-leaf-move' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' -import { keepFrozen } from './layout-command-commit' +} from '../pane-moves/terminal-leaf-move' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' +import { keepFrozen } from '../command-application/layout-command-commit' import { assignWorkspaceSessionPartition } from './terminal-topology-membership' export type DuplicatePtyPaneTransfer = { diff --git a/src/main/persistence/terminal-topology/layout-command-binding-generations.ts b/src/main/persistence/terminal-topology/pane-ownership/layout-command-binding-generations.ts similarity index 77% rename from src/main/persistence/terminal-topology/layout-command-binding-generations.ts rename to src/main/persistence/terminal-topology/pane-ownership/layout-command-binding-generations.ts index bad7d4c2539..36a530b2b03 100644 --- a/src/main/persistence/terminal-topology/layout-command-binding-generations.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/layout-command-binding-generations.ts @@ -1,14 +1,14 @@ // Layout-owner commands and rollback advance generations only for changed bindings, excluding moves/removals. -import type { ExecutionHostId } from '../../../shared/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-pane-tree' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { bumpPtyBindingGeneration } from '../loading-store/terminal-bindings/pty-binding-generations' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { bumpPtyBindingGeneration } from '../../loading-store/terminal-bindings/pty-binding-generations' import type { DurableProfileStateMutation, StoreRuntimeState -} from '../loading-store/store-runtime-state' +} from '../../loading-store/store-runtime-state' function bindingsOf(session: WorkspaceSessionState): Map { return new Map( diff --git a/src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts b/src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts new file mode 100644 index 00000000000..1f785a3115b --- /dev/null +++ b/src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts @@ -0,0 +1,193 @@ +import { closeTestStores, createStore, testState } from '../../persistence-test-harness' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' +import { _resetClosedPaneFencesForTests } from './closed-pane-binding-fence' +import '../terminal-topology-commit' +import '../../../runtime/terminal/surface/terminal-surface-close' + +import '../../../../shared/execution-host' + +vi.mock('electron', () => ({ + app: { getPath: () => testState.dir }, + safeStorage: { isEncryptionAvailable: () => false } +})) +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) + +const WORKTREE = 'repo1::/worktree' +const TAB = 'host-tab' + +type TestStore = ReturnType + +// Main knows the tab’s running terminal and a split whose terminal is still starting. +async function tabWithStartingSplit(store: TestStore): Promise { + expect( + await store.admitTerminalPane({ + type: 'createTerminalTab', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_1 + }) + ).toBe('admitted') + expect( + await store.persistPtyBinding({ + worktreeId: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_1, + ptyId: 'source-pty', + mayCreate: false + }) + ).toBe(true) + expect( + await store.admitTerminalPane({ + type: 'splitPane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_1, + direction: 'vertical', + newLeafId: TEST_LEAF_2 + }) + ).toBe('admitted') +} + +// Simulate a late window binding that carries no expected state. +function lateWindowBinding(store: TestStore): Promise { + return store.persistPtyBinding({ + worktreeId: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_2, + ptyId: 'late-pty', + origin: 'spawn' + }) +} + +function leafIds(store: TestStore): string[] { + const root = store.getWorkspaceSession().terminalLayoutsByTabId[TAB]?.root + return root ? collectLayoutLeafIdsInOrder(root) : [] +} + +describe('a pane main closed or took back is not brought back by its late terminal binding', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-closed-pane-fence-')) + }) + + afterEach(async () => { + vi.useRealTimers() + _resetClosedPaneFencesForTests() + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('refuses the binding of a split main took back when its terminal did not start in time', async () => { + const store = createStore() + await tabWithStartingSplit(store) + + await store.withdrawTerminalPane({ + type: 'closePane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_2 + }) + + expect(await lateWindowBinding(store)).toBe(false) + expect(leafIds(store)).toEqual([TEST_LEAF_1]) + }) + + it('refuses the binding of a pane the user closed while its terminal was starting', async () => { + const store = createStore() + await tabWithStartingSplit(store) + + const reply = await store.applyLayoutCommand({ + type: 'closePane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_2, + userPaneClose: true + }) + expect(reply.ok).toBe(true) + + expect(await lateWindowBinding(store)).toBe(false) + expect(leafIds(store)).toEqual([TEST_LEAF_1]) + }) + + it('refuses the binding of a pane whose tab the window closed while it was starting', async () => { + const store = createStore() + await tabWithStartingSplit(store) + + const reply = await store.applyLayoutCommand({ + type: 'closeTabs', + workspace: WORKTREE, + tabIds: [TAB], + force: true + }) + expect(reply.ok).toBe(true) + + expect(await lateWindowBinding(store)).toBe(false) + expect(store.getWorkspaceSession().terminalLayoutsByTabId[TAB]).toBeUndefined() + }) + + it('binds a pane the window creates again under the same id', async () => { + const store = createStore() + await tabWithStartingSplit(store) + await store.withdrawTerminalPane({ + type: 'closePane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_2 + }) + + const reply = await store.applyLayoutCommand({ + type: 'splitPane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_1, + direction: 'vertical', + newLeafId: TEST_LEAF_2 + }) + expect(reply.ok).toBe(true) + expect(await lateWindowBinding(store)).toBe(true) + }) + + it('binds a pane a real create wrote again under the same id', async () => { + const store = createStore() + await tabWithStartingSplit(store) + await store.withdrawTerminalPane({ + type: 'closePane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_2 + }) + + expect( + await store.admitTerminalPane({ + type: 'splitPane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_1, + direction: 'vertical', + newLeafId: TEST_LEAF_2 + }) + ).toBe('admitted') + expect(await lateWindowBinding(store)).toBe(true) + expect(leafIds(store)).toEqual([TEST_LEAF_1, TEST_LEAF_2]) + }) + + it('lets a binding create the pane again once the binding window has passed', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const store = createStore() + await tabWithStartingSplit(store) + await store.withdrawTerminalPane({ + type: 'closePane', + workspace: WORKTREE, + tabId: TAB, + leafId: TEST_LEAF_2 + }) + + vi.setSystemTime(Date.now() + 5 * 60_000 + 1_000) + expect(await lateWindowBinding(store)).toBe(true) + expect(leafIds(store)).toEqual([TEST_LEAF_1, TEST_LEAF_2]) + }) +}) diff --git a/src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts b/src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts similarity index 86% rename from src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts rename to src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts index 28b6c2e0cc6..37c32fdcfcd 100644 --- a/src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts @@ -1,20 +1,20 @@ -import { closeTestStores, testState, createStore } from '../persistence-test-harness' +import { closeTestStores, testState, createStore } from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { findTerminalTabIdForLeaf } from './terminal-topology-membership' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, safeStorage: { isEncryptionAvailable: () => false } })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) describe('findTerminalTabIdForLeaf after persistPtyBinding grafts a leaf', () => { beforeEach(() => { diff --git a/src/main/persistence/terminal-topology/terminal-topology-membership.ts b/src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts similarity index 84% rename from src/main/persistence/terminal-topology/terminal-topology-membership.ts rename to src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts index fcf14a4f777..cbe54299f7d 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-membership.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts @@ -2,11 +2,11 @@ import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { layoutContainsLeafId } from '../restoring-sessions/terminal-layout-normalization' +} from '../../../../shared/execution-host' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' export function advanceTerminalTopologyRevision( session: WorkspaceSessionState, diff --git a/src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts b/src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts deleted file mode 100644 index fe7e7114726..00000000000 --- a/src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { closeTestStores, createStore, testState } from '../persistence-test-harness' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-pane-tree' -import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' -import { _resetClosedPaneFencesForTests } from './closed-pane-binding-fence' -import { closeLeafOrTab } from './terminal-topology-commit' -import { captureTerminalCloseRequest } from '../../runtime/terminal/surface/terminal-surface-close' -import type { TerminalSurfaceCloseTarget } from '../../../shared/workspace-layout/terminal-surface-close-target' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' - -vi.mock('electron', () => ({ - app: { getPath: () => testState.dir }, - safeStorage: { isEncryptionAvailable: () => false } -})) -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const WORKTREE = 'repo1::/worktree' -const TAB = 'host-tab' - -type TestStore = ReturnType - -// Main knows the tab’s running terminal and a split whose terminal is still starting. -async function tabWithStartingSplit(store: TestStore): Promise { - expect( - await store.admitTerminalPane({ - type: 'createTerminalTab', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_1 - }) - ).toBe('admitted') - expect( - await store.persistPtyBinding({ - worktreeId: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_1, - ptyId: 'source-pty', - mayCreate: false - }) - ).toBe(true) - expect( - await store.admitTerminalPane({ - type: 'splitPane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_1, - direction: 'vertical', - newLeafId: TEST_LEAF_2 - }) - ).toBe('admitted') -} - -// Simulate a late window binding that carries no expected state. -function lateWindowBinding(store: TestStore): Promise { - return store.persistPtyBinding({ - worktreeId: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_2, - ptyId: 'late-pty', - origin: 'spawn' - }) -} - -async function closeThroughMain( - store: TestStore, - target: TerminalSurfaceCloseTarget -): Promise { - const hostIds: readonly ExecutionHostId[] = [LOCAL_EXECUTION_HOST_ID] - const refusal = await store.runDurableMutation( - closeLeafOrTab({ - worktreeId: WORKTREE, - target, - options: { allowMissing: true }, - ...captureTerminalCloseRequest(WORKTREE, target, hostIds, store, false), - ownerMatches: () => true, - hostIds: () => hostIds, - getSession: (hostId) => store.getWorkspaceSession(hostId), - setSession: (session, hostId) => store.setWorkspaceSession(session, hostId), - onClosed: () => {} - }) - ) - expect(refusal).toBeUndefined() -} - -function leafIds(store: TestStore): string[] { - const root = store.getWorkspaceSession().terminalLayoutsByTabId[TAB]?.root - return root ? collectLayoutLeafIdsInOrder(root) : [] -} - -describe('a pane main closed or took back is not brought back by its late terminal binding', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-closed-pane-fence-')) - }) - - afterEach(async () => { - vi.useRealTimers() - _resetClosedPaneFencesForTests() - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('refuses the binding of a split main took back when its terminal did not start in time', async () => { - const store = createStore() - await tabWithStartingSplit(store) - - await store.withdrawTerminalPane({ - type: 'closePane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_2 - }) - - expect(await lateWindowBinding(store)).toBe(false) - expect(leafIds(store)).toEqual([TEST_LEAF_1]) - }) - - it('refuses the binding of a pane the user closed while its terminal was starting', async () => { - const store = createStore() - await tabWithStartingSplit(store) - - const reply = await store.applyLayoutCommand({ - type: 'closePane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_2, - userPaneClose: true - }) - expect(reply.ok).toBe(true) - - expect(await lateWindowBinding(store)).toBe(false) - expect(leafIds(store)).toEqual([TEST_LEAF_1]) - }) - - it('refuses the binding of a pane main closed while its terminal was starting', async () => { - const store = createStore() - await tabWithStartingSplit(store) - - await closeThroughMain(store, { kind: 'pane', tabId: TAB, leafId: TEST_LEAF_2 }) - - expect(await lateWindowBinding(store)).toBe(false) - expect(leafIds(store)).toEqual([TEST_LEAF_1]) - }) - - it('refuses the binding of a pane whose tab the window closed while it was starting', async () => { - const store = createStore() - await tabWithStartingSplit(store) - - const reply = await store.applyLayoutCommand({ - type: 'closeTabs', - workspace: WORKTREE, - tabIds: [TAB], - force: true - }) - expect(reply.ok).toBe(true) - - expect(await lateWindowBinding(store)).toBe(false) - expect(store.getWorkspaceSession().terminalLayoutsByTabId[TAB]).toBeUndefined() - }) - - it('binds a pane the window creates again under the same id', async () => { - const store = createStore() - await tabWithStartingSplit(store) - await store.withdrawTerminalPane({ - type: 'closePane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_2 - }) - - const reply = await store.applyLayoutCommand({ - type: 'splitPane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_1, - direction: 'vertical', - newLeafId: TEST_LEAF_2 - }) - expect(reply.ok).toBe(true) - expect(await lateWindowBinding(store)).toBe(true) - }) - - it('binds a pane a real create wrote again under the same id', async () => { - const store = createStore() - await tabWithStartingSplit(store) - await store.withdrawTerminalPane({ - type: 'closePane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_2 - }) - - expect( - await store.admitTerminalPane({ - type: 'splitPane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_1, - direction: 'vertical', - newLeafId: TEST_LEAF_2 - }) - ).toBe('admitted') - expect(await lateWindowBinding(store)).toBe(true) - expect(leafIds(store)).toEqual([TEST_LEAF_1, TEST_LEAF_2]) - }) - - it('lets a binding create the pane again once the binding window has passed', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - const store = createStore() - await tabWithStartingSplit(store) - await store.withdrawTerminalPane({ - type: 'closePane', - workspace: WORKTREE, - tabId: TAB, - leafId: TEST_LEAF_2 - }) - - vi.setSystemTime(Date.now() + 5 * 60_000 + 1_000) - expect(await lateWindowBinding(store)).toBe(true) - expect(leafIds(store)).toEqual([TEST_LEAF_1, TEST_LEAF_2]) - }) -}) diff --git a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts b/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts deleted file mode 100644 index 40929cbf9dd..00000000000 --- a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { closeTestStores, createStore, dataFile, testState } from '../persistence-test-harness' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { - clearMigrationUnsupportedPty, - setMigrationUnsupportedPtyPersistenceListener -} from '../../agent-hooks/observations/migration-unsupported-pty-state' -import { StateSerializationSecretHandlingOperations } from '../loading-store/profile-writing/state-serialization-secret-handling' -import { openProfileStateDatabaseReadOnly } from '../profile-state/database/profile-state-database' -import { profileStateDatabaseFile } from '../../../shared/profile-state-storage-paths' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' - -vi.mock('electron', () => ({ - app: { getPath: () => testState.dir }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) - } -})) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) - -const SOURCE = makePaneKey('tab-source', '11111111-1111-4111-8111-111111111111') -const TARGET = makePaneKey('tab-target', '22222222-2222-4222-8222-222222222222') -const migrationEntry = { - ptyId: 'ssh:ssh-1@@legacy-pty', - worktreeId: 'repo-1::/worktree', - tabId: 'tab-1', - reason: 'legacy-numeric-pane-key' as const, - source: 'ssh' as const, - updatedAt: 1_700_000_000_123 -} - -type DocumentRow = { domain: string; payload: string; revision: number } - -function isDocumentRow(row: unknown): row is DocumentRow { - return ( - typeof row === 'object' && - row !== null && - 'domain' in row && - typeof row.domain === 'string' && - 'payload' in row && - typeof row.payload === 'string' && - 'revision' in row && - typeof row.revision === 'number' - ) -} - -// Read independently of Store, using one SQL statement for a consistent snapshot. -function readDocuments(): Map { - const opened = openProfileStateDatabaseReadOnly( - profileStateDatabaseFile(dirname(dataFile())), - 'persistence-test' - ) - try { - const rows = opened.db - .prepare('SELECT domain, payload, revision FROM profile_state_documents') - .all() - return new Map(rows.filter(isDocumentRow).map((row) => [row.domain, row])) - } finally { - opened.db.close() - } -} - -async function runBackgroundSave(store: Awaited>): Promise { - vi.advanceTimersByTime(1_000) - await store.waitForPendingWrite() -} - -describe('pane alias and migration listeners save only their sections', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-alias-saves-')) - }) - - afterEach(async () => { - vi.useRealTimers() - vi.restoreAllMocks() - await closeTestStores() - agentHookServer.setPaneKeyAliasPersistenceListener(null) - setMigrationUnsupportedPtyPersistenceListener(null) - agentHookServer.retirePaneAuthority(TARGET) - for (const ptyId of ['pty-1', 'ssh:ssh-1@@pty-1', 'local-pty']) { - agentHookServer.clearPaneKeyAliasesForPty(ptyId) - } - clearMigrationUnsupportedPty(migrationEntry.ptyId) - rmSync(testState.dir, { recursive: true, force: true }) - }) - - async function durableBaseline() { - const store = await createStore() - store.flushOrThrow() - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const fullPreparation = vi.spyOn( - StateSerializationSecretHandlingOperations.prototype, - 'buildStateToSave' - ) - const domainWrites = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'writeSerializedDomains') - return { store, fullPreparation, domainWrites, before: readDocuments() } - } - - function expectOnlyChanged( - before: Map, - after: Map, - changed: readonly string[] - ): void { - for (const [domain, row] of before) { - if (!changed.includes(domain)) { - expect(after.get(domain), domain).toEqual(row) - } - } - } - - it('commits a co-batched SSH host session with the alias in one transaction', async () => { - const { store, fullPreparation, domainWrites, before } = await durableBaseline() - const remoteSession = { ...getDefaultWorkspaceSession(), activeRepoId: 'remote-repo' } - store.setWorkspaceSession(remoteSession, 'ssh:ssh-1') - agentHookServer.transferPaneAuthority(SOURCE, TARGET, 'ssh:ssh-1@@pty-1', 30) - await runBackgroundSave(store) - - expect(fullPreparation).not.toHaveBeenCalled() - expect(domainWrites).toHaveBeenCalledOnce() - expect(domainWrites.mock.calls[0]?.[0].map(({ domain }) => domain).toSorted()).toEqual([ - 'legacyPaneKeyAliasEntries', - 'workspaceSessionsByHostId' - ]) - const after = readDocuments() - const sessions = JSON.parse(after.get('workspaceSessionsByHostId')?.payload ?? '{}') - expect(sessions['ssh:ssh-1']).toMatchObject({ activeRepoId: 'remote-repo' }) - expect(after.get('workspaceSessionsByHostId')?.revision).toBe( - after.get('legacyPaneKeyAliasEntries')?.revision - ) - expectOnlyChanged(before, after, ['legacyPaneKeyAliasEntries', 'workspaceSessionsByHostId']) - }) -}) diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts b/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts deleted file mode 100644 index 3a7d2672515..00000000000 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { - closeTestStores, - testState, - createStore, - writeDataFile, - readDataFile -} from '../persistence-test-harness' -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { rmSync, mkdtempSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import type { SshTarget } from '../../../shared/ssh-types' -import { isRemoteCliControlAllowed } from '../../../shared/ssh-remote-cli-control' -import { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' - -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: vi.fn(), - sshConfigHostsToTargets: vi.fn() -})) -vi.mock('electron', () => ({ - app: { getPath: () => testState.dir }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) - } -})) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: () => ({ nth_repo_added: 2 }) -})) - -const host = (id: string, extra: Partial = {}): SshTarget => ({ - id, - label: id, - host: `${id}.example.com`, - port: 22, - username: 'dev', - ...extra -}) - -function writeProfile(sshTargets: SshTarget[], settings: Record = {}): void { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {}, - sshTargets - }) -} - -async function reopenStore(): Promise> { - await closeTestStores() - return createStore() -} - -// The orcad serve host uses the same SSH-target loading path. -describe("pinning existing hosts' orca CLI control switch on upgrade", () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - }) - - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('turns an existing absent switch off and keeps explicit values', async () => { - writeProfile([ - host('absent'), - host('on', { allowRemoteCliControl: true }), - host('off', { allowRemoteCliControl: false }) - ]) - - const store = await createStore() - - expect(store.getSshTarget('absent')?.allowRemoteCliControl).toBe(false) - expect(isRemoteCliControlAllowed(store.getSshTarget('absent'))).toBe(false) - expect(store.getSshTarget('on')?.allowRemoteCliControl).toBe(true) - expect(store.getSshTarget('off')?.allowRemoteCliControl).toBe(false) - expect(store.getSettings().sshRemoteCliControlExistingHostsMigrated).toBe(true) - - store.flush() - expect(readDataFile()).toMatchObject({ - sshTargets: expect.arrayContaining([ - expect.objectContaining({ id: 'absent', allowRemoteCliControl: false }) - ]), - settings: expect.objectContaining({ sshRemoteCliControlExistingHostsMigrated: true }) - }) - }) - - it('runs once, so hosts added afterwards keep the on-by-default switch', async () => { - writeProfile([host('existing')]) - const store = await createStore() - const added = new SshConnectionStore(store).addTarget({ - label: 'new', - host: 'new.example.com', - port: 22, - username: 'dev', - allowRemoteCliControl: true - }) - store.flush() - - const reopened = await reopenStore() - - expect(reopened.getSshTarget('existing')?.allowRemoteCliControl).toBe(false) - expect(reopened.getSshTarget(added.id)?.allowRemoteCliControl).toBe(true) - expect(isRemoteCliControlAllowed(reopened.getSshTarget(added.id))).toBe(true) - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts b/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts deleted file mode 100644 index 00d489fb044..00000000000 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { - admitRuntimeSpawnPane, - fixture -} from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const pane = { - worktreeId: 'repo-local::/fixture/local', - tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -} - -async function openWithTab() { - const opened = await fixture() - await admitRuntimeSpawnPane(opened.store, pane) - const tabIds = (session: { tabsByWorktree?: Record }) => - (session.tabsByWorktree?.[pane.worktreeId] ?? []).map((tab) => tab.id) - return { - ...opened, - liveTabIds: () => tabIds(opened.store.getWorkspaceSession()), - savedTabIds: () => tabIds(opened.readState().workspaceSession ?? {}) - } -} - -it('keeps a tab closed when its profile write fails, and saves it on a later write', async () => { - const { store, authority, liveTabIds, savedTabIds } = await openWithTab() - expect(savedTabIds()).toContain(pane.tabId) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - authority.failNextWrite() - - const reply = await store.applyLayoutCommand({ - type: 'closeTabs', - workspace: pane.worktreeId, - tabIds: [pane.tabId] - }) - - expect(reply.ok).toBe(true) - expect(liveTabIds()).not.toContain(pane.tabId) - expect(savedTabIds()).toContain(pane.tabId) - await vi.waitFor(() => expect(savedTabIds()).not.toContain(pane.tabId), { timeout: 5000 }) -}) - -it('still refuses and rolls back a rename whose profile write fails', async () => { - const { store, authority } = await openWithTab() - authority.failNextWrite() - - await expect( - store.applyLayoutCommand({ - type: 'renameTab', - workspace: pane.worktreeId, - tabId: pane.tabId, - kind: 'custom', - title: 'Renamed' - }) - ).rejects.toThrow('profile_state_write_failed') - const tab = store - .getWorkspaceSession() - .tabsByWorktree[pane.worktreeId]?.find((row) => row.id === pane.tabId) - expect(tab?.customTitle ?? null).toBeNull() -}) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts b/src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts deleted file mode 100644 index 058a7110b83..00000000000 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { expect, it, vi } from 'vitest' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { - admitRuntimeSpawnPane, - fixture -} from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' - -// Preserve switch-off behavior regardless of the active build switch. -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const pane = { - worktreeId: 'repo-local::/fixture/local', - tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -} - -const closes: [string, LayoutCommand][] = [ - ['tab', { type: 'closeTabs', workspace: pane.worktreeId, tabIds: [pane.tabId] }], - [ - 'pane', - { - type: 'closePane', - workspace: pane.worktreeId, - tabId: pane.tabId, - leafId: pane.leafId - } - ] -] - -it.each(closes)( - 'switch off: a %s close through layout.apply still refuses and rolls back on a failed write', - async (_kind, command) => { - const { store, authority } = await fixture() - await admitRuntimeSpawnPane(store, pane) - authority.failNextWrite() - - await expect(store.applyLayoutCommand(command)).rejects.toThrow('profile_state_write_failed') - const ids = (store.getWorkspaceSession().tabsByWorktree[pane.worktreeId] ?? []).map( - (tab) => tab.id - ) - expect(ids).toContain(pane.tabId) - } -) diff --git a/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts b/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts deleted file mode 100644 index 133cb702ab2..00000000000 --- a/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' -import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' -import type { Store } from '../loading-store/store' -import { closeLeafOrTab } from './terminal-topology-commit' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore -} from './terminal-topology-profile-fixture' -import { WindowSession } from './terminal-topology-window-session-fixture' -import { checkWorkspaceLayoutRules } from '../../../shared/workspace-layout/workspace-layout-rules' - -// Retire this rollback coverage with switch-off code. -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) - -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const WT = FIXTURE_GIT_WORKTREE_ID -const directories: string[] = [] - -async function openWithSplit(): Promise<{ store: Store; window: WindowSession }> { - const directory = mkdtempSync(join(tmpdir(), 'orca-late-bind-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - const window = new WindowSession(structuredClone(store.getWorkspaceSession())) - window.addTab(WT, 'tab-a', TEST_LEAF_1) - window.setLayout( - 'tab-a', - { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: TEST_LEAF_1 }, - second: { type: 'leaf', leafId: TEST_LEAF_2 } - }, - {} - ) - store.setWorkspaceSession(window.snapshot()) - for (const [leafId, ptyId] of [ - [TEST_LEAF_1, 'pty-1'], - [TEST_LEAF_2, 'pty-2'] - ] as const) { - await expect( - store.persistPtyBinding({ worktreeId: WT, tabId: 'tab-a', leafId, ptyId }) - ).resolves.toBe(true) - window.bind('tab-a', leafId, ptyId) - } - store.setWorkspaceSession(window.snapshot()) - return { store, window } -} - -function violations(store: Store): string[] { - return checkWorkspaceLayoutRules([ - { hostId: LOCAL_EXECUTION_HOST_ID, session: store.getWorkspaceSession() } - ]).map((violation) => `${violation.rule}: ${violation.detail}`) -} - -describe('a terminal spawn that lands after its pane changed', () => { - afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } - }) - - it('does not bring back a tab the user closed', async () => { - const { store, window } = await openWithSplit() - window.removeTab('tab-a') - await store.runDurableMutation( - closeLeafOrTab({ - worktreeId: WT, - target: { kind: 'tab', tabId: 'tab-a' }, - options: { allowMissing: true, force: true, closedByLayoutOwner: true, reason: 'user' }, - requestedSession: store.getWorkspaceSession(), - ownerMatches: () => true, - hostIds: () => [LOCAL_EXECUTION_HOST_ID], - getSession: (hostId) => store.getWorkspaceSession(hostId), - setSession: (session, hostId) => store.setWorkspaceSession(session, hostId), - onClosed: () => {} - }) - ) - store.setWorkspaceSession(window.snapshot()) - await store.persistPtyBinding({ - worktreeId: WT, - tabId: 'tab-a', - leafId: TEST_LEAF_1, - ptyId: 'pty-late' - }) - expect(violations(store)).toEqual([]) - expect(store.getWorkspaceSession().tabsByWorktree[WT] ?? []).toEqual([]) - await store.freezeWritesAsync() - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts index b64d12311b9..f95ff084f38 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts @@ -1,4 +1,4 @@ -import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' +import { withoutGitGraph } from '../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' import type { LayoutEffects } from '../../../shared/workspace-layout/workspace-layout-command-types' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -6,13 +6,13 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../shared/constants' import type { Store } from '../loading-store/store' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { WindowSession } from './testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from './testing/terminal-topology-profile-fixture' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../ssh/config/ssh-config-parser', () => ({ @@ -100,41 +100,6 @@ describe('Store.applyLayoutCommand (layout.apply)', () => { }) expect(revision(store)).toBeGreaterThan(revisionBefore) }) - - it('keeps records the split did not touch exactly as stored', async () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-layout-apply-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - const window = new WindowSession(getDefaultWorkspaceSession()) - window.addTab(WORKTREE, TAB, LEAF) - window.bind(TAB, LEAF, 'pty-1') - // Verify record patches preserve residue that full load/save normalization would drop. - window.session.terminalPtyIncarnationsByPaneKey = { [`${TAB}:${LEAF}`]: 'incarnation-1' } - window.session.tabsByWorktree[WORKTREE]![0]!.sortOrder = 7 - store.setWorkspaceSession(window.snapshot()) - const stored = store.getWorkspaceSession() - - await store.applyLayoutCommand(split) - - const written = store.getWorkspaceSession() - expect(written.terminalPtyIncarnationsByPaneKey).toEqual( - stored.terminalPtyIncarnationsByPaneKey - ) - expect(written.tabsByWorktree).toEqual(stored.tabsByWorktree) - expect(written.unifiedTabs).toEqual(stored.unifiedTabs) - }) - - it('writes an SSH workspace’s split into that host’s partition only', async () => { - const { store } = await storeWithOneTab('ssh:target-1') - const local = store.getWorkspaceSession() - - const reply = await store.applyLayoutCommand(split, ['ssh:target-1']) - - expect(reply.ok).toBe(true) - const root = store.getWorkspaceSession('ssh:target-1').terminalLayoutsByTabId[TAB]?.root - expect(leafIds(root)).toHaveLength(2) - expect(store.getWorkspaceSession()).toEqual(local) - }) }) it('admits competing initial requests against visible tabs inside the durable mutation', async () => { diff --git a/src/main/persistence/terminal-topology/terminal-layout-create.test.ts b/src/main/persistence/terminal-topology/terminal-layout-create.test.ts deleted file mode 100644 index 3f5835f0fb1..00000000000 --- a/src/main/persistence/terminal-topology/terminal-layout-create.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { Store } from '../loading-store/store' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' -import { - emptyTerminalSessionProfile, - FIXTURE_FOLDER_WORKTREE_ID, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from './terminal-topology-profile-fixture' - -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const WORKTREE = FIXTURE_GIT_WORKTREE_ID -const GROUP = `group-${WORKTREE}` -const TAB = 'tab-1' -const LEAF = '11111111-1111-4111-8111-111111111111' -const NEW_TAB = 'tab-new' -const NEW_LEAF = '22222222-2222-4222-8222-222222222222' -const directories: string[] = [] - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -async function openStore( - seed: (window: WindowSession) => void, - hostId?: string -): Promise<{ store: Store; directory: string }> { - const directory = mkdtempSync(join(tmpdir(), 'orca-layout-create-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - const window = new WindowSession(getDefaultWorkspaceSession()) - seed(window) - store.setWorkspaceSession(window.snapshot(), hostId) - await store.flushPendingOrThrowAsync() - return { store, directory } -} - -const withOneTab = (window: WindowSession): void => { - window.addTab(WORKTREE, TAB, LEAF) - window.bind(TAB, LEAF, 'pty-1') -} - -const create: CommandOf<'createTerminalTab'> = { - type: 'createTerminalTab', - workspace: WORKTREE, - tabId: NEW_TAB, - leafId: NEW_LEAF, - groupId: GROUP, - creation: { defaultTitle: 'Terminal 2', startupCwd: '/fixture/local/src' } -} - -describe('Store.applyLayoutCommand: a window’s terminal tab create', () => { - it('writes the tab durably under the window’s ids, in the group it names', async () => { - const { store, directory } = await openStore(withOneTab) - - const reply = await store.applyLayoutCommand(create) - - expect(reply).toEqual({ - ok: true, - result: { tabId: NEW_TAB, leafId: NEW_LEAF, paneKey: `${NEW_TAB}:${NEW_LEAF}` } - }) - const session = (await reopenTopologyStore(store, directory)).getWorkspaceSession() - expect(session.terminalLayoutsByTabId[NEW_TAB]?.root).toEqual({ - type: 'leaf', - leafId: NEW_LEAF - }) - const row = session.tabsByWorktree[WORKTREE]?.find((tab) => tab.id === NEW_TAB) - expect(row).toMatchObject({ defaultTitle: 'Terminal 2', startupCwd: '/fixture/local/src' }) - expect(session.tabGroups?.[WORKTREE]?.[0]).toMatchObject({ - id: GROUP, - tabOrder: [TAB, NEW_TAB] - }) - }) - - it('then accepts a split of the new pane before any window save', async () => { - const { store } = await openStore(withOneTab) - await store.applyLayoutCommand(create) - - const reply = await store.applyLayoutCommand({ - type: 'splitPane', - workspace: WORKTREE, - tabId: NEW_TAB, - leafId: NEW_LEAF, - direction: 'vertical' - }) - - expect(reply.ok).toBe(true) - const root = store.getWorkspaceSession().terminalLayoutsByTabId[NEW_TAB]?.root - expect(leafIds(root)).toEqual([NEW_LEAF, reply.ok ? reply.result.leafId : undefined]) - }) - - it('keeps records the create did not touch exactly as stored', async () => { - const { store } = await openStore((window) => { - withOneTab(window) - // Verify record patches preserve residue that full load/save normalization would drop. - window.session.terminalPtyIncarnationsByPaneKey = { [`${TAB}:${LEAF}`]: 'incarnation-1' } - window.session.tabsByWorktree[WORKTREE]![0]!.sortOrder = 7 - }) - const stored = store.getWorkspaceSession() - - await store.applyLayoutCommand(create) - - const written = store.getWorkspaceSession() - expect(written.terminalPtyIncarnationsByPaneKey).toEqual( - stored.terminalPtyIncarnationsByPaneKey - ) - expect(written.tabsByWorktree[WORKTREE]?.[0]).toEqual(stored.tabsByWorktree[WORKTREE]?.[0]) - expect(written.unifiedTabs?.[WORKTREE]?.[0]).toEqual(stored.unifiedTabs?.[WORKTREE]?.[0]) - }) - - it('writes an SSH workspace’s tab into that host’s partition only', async () => { - const { store } = await openStore(withOneTab, 'ssh:target-1') - const local = store.getWorkspaceSession() - - const reply = await store.applyLayoutCommand(create, ['ssh:target-1']) - - expect(reply.ok).toBe(true) - expect(store.getWorkspaceSession('ssh:target-1').terminalLayoutsByTabId[NEW_TAB]?.root).toEqual( - { type: 'leaf', leafId: NEW_LEAF } - ) - expect(store.getWorkspaceSession()).toEqual(local) - }) -}) - -describe('Store.applyLayoutCommand: a workspace’s default tabs', () => { - const defaults: CommandOf<'applyDefaultTabs'> = { - type: 'applyDefaultTabs', - workspace: FIXTURE_FOLDER_WORKTREE_ID, - tabs: [ - { tabId: NEW_TAB, leafId: NEW_LEAF, title: 'Server' }, - { tabId: 'tab-new-2', leafId: '33333333-3333-4333-8333-333333333333', color: 'blue' } - ] - } - - it('writes every tab under the window’s ids with the mark, durably, in one command', async () => { - const { store, directory } = await openStore(withOneTab) - - const reply = await store.applyLayoutCommand(defaults) - - expect(reply.ok && reply.result.createdTabs?.map((tab) => tab.tabId)).toEqual([ - NEW_TAB, - 'tab-new-2' - ]) - const session = (await reopenTopologyStore(store, directory)).getWorkspaceSession() - expect(session.tabsByWorktree[FIXTURE_FOLDER_WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - NEW_TAB, - 'tab-new-2' - ]) - expect(session.defaultTerminalTabsAppliedByWorktreeId?.[FIXTURE_FOLDER_WORKTREE_ID]).toBe(true) - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-layout-renames-commit.ts b/src/main/persistence/terminal-topology/terminal-layout-renames-commit.ts deleted file mode 100644 index 51ad7f2b371..00000000000 --- a/src/main/persistence/terminal-topology/terminal-layout-renames-commit.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { - CommandOf, - LayoutRefusalCode -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' -import { writeRestorable } from './restorable-write' -import { applyRenamesToSession } from './terminal-pane-admission' -import { traced, type TerminalTopologyCommitContext } from './terminal-topology-commit' -import { keepFrozen } from './layout-command-commit' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' - -/** Publish routed tab renames in one frame and return per-tab refusals. */ -export function applyLayoutRenames( - batches: readonly { hostId: ExecutionHostId; renames: readonly CommandOf<'renameTab'>[] }[], - context: TerminalTopologyCommitContext -): () => DurableProfileStateMutation< - { rename: CommandOf<'renameTab'>; code: LayoutRefusalCode }[] -> { - return traced( - 'apply_layout', - () => { - const changes = batches.map(({ hostId, renames }) => ({ - hostId, - change: applyRenamesToSession(hostId, context.getSession(hostId), renames) - })) - const refused = changes.flatMap(({ change }) => change.value) - const restores = changes.flatMap(({ hostId, change }) => - change.session - ? [ - writeRestorable( - () => context.getSession(hostId), - (value) => - context.markDirty(assignWorkspaceSessionPartition(context.state, hostId, value)), - keepFrozen(hostId, change.session, context) - ) - ] - : [] - ) - return restores.length === 0 - ? { value: refused, persist: false } - : { value: refused, rollback: () => restores.forEach((restore) => restore()) } - }, - // Per-tab refusals do not reject the remaining write. - () => undefined - ) -} diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts b/src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts deleted file mode 100644 index ef58c777496..00000000000 --- a/src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { tmpdir } from 'node:os' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { TerminalSurfaceCloseTarget } from '../../../shared/workspace-layout/terminal-surface-close-target' -import { makeRepo } from '../persistence-test-harness' -import { - closeMoveTestStores, - MOVED, - moveRequest, - newDataFile, - openStore, - seedSplitSource, - SOURCE, - TARGET, - tabsHoldingLeaf, - WT -} from './terminal-leaf-move-fixture' -import { closeLeafOrTab } from './terminal-topology-commit' - -vi.mock('electron', () => ({ - app: { - getPath: () => tmpdir(), - getName: () => 'orca-test', - getVersion: () => '0.0.0-test', - isPackaged: false, - on: () => {}, - whenReady: () => Promise.resolve() - }, - safeStorage: { - isEncryptionAvailable: () => false, - encryptString: (value: string) => Buffer.from(value), - decryptString: (value: Buffer) => value.toString() - }, - ipcMain: { on: () => {}, handle: () => {} }, - BrowserWindow: { getAllWindows: () => [] } -})) - -afterEach(closeMoveTestStores) - -const request = { ...moveRequest, ptyId: 'pty-agent' } - -async function rendererClose( - store: ReturnType, - target: TerminalSurfaceCloseTarget, - reason: 'user' | 'cleanup' -): Promise { - await store.runDurableMutation( - closeLeafOrTab({ - worktreeId: WT, - target, - options: { allowMissing: true, force: true, closedByLayoutOwner: true, reason }, - requestedSession: store.getWorkspaceSession(), - ownerMatches: () => true, - hostIds: () => ['local'], - getSession: (hostId) => store.getWorkspaceSession(hostId), - setSession: (session, hostId) => store.setWorkspaceSession(session, hostId), - onClosed: () => {} - }) - ) -} - -async function openMovedStore() { - const dataFile = newDataFile() - const store = openStore(dataFile) - store.addRepo(makeRepo({ id: 'repo-1', path: '/tmp/move-worktree' })) - await seedSplitSource(store) - await expect(store.moveTerminalLeafToNewTab(request)).resolves.toMatchObject({ - status: 'moved' - }) - return { dataFile, store } -} - -function restartedTabs(store: ReturnType, dataFile: string) { - store.flush() - const session = openStore(dataFile).getWorkspaceSession() - return { tabIds: (session.tabsByWorktree[WT] ?? []).map((tab) => tab.id), session } -} - -// The renderer completes a post-move close against main's new tab. -describe('a close that lands while main commits the move', () => { - it('leaves no dead pane after restart when the user closed the moved pane', async () => { - const { dataFile, store } = await openMovedStore() - await rendererClose(store, { kind: 'pane', tabId: SOURCE, leafId: MOVED }, 'user') - expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED)).toEqual([TARGET]) - - await rendererClose(store, { kind: 'tab', tabId: TARGET }, 'cleanup') - - const { tabIds, session } = restartedTabs(store, dataFile) - expect(tabsHoldingLeaf(session, MOVED)).toEqual([]) - expect(tabIds).toEqual([SOURCE]) - }) - - it('leaves no ghost tab after restart when the user closed the source tab', async () => { - const { dataFile, store } = await openMovedStore() - await rendererClose(store, { kind: 'tab', tabId: SOURCE }, 'user') - - await rendererClose(store, { kind: 'tab', tabId: TARGET }, 'cleanup') - - const { tabIds, session } = restartedTabs(store, dataFile) - expect(tabIds).toEqual([]) - expect(tabsHoldingLeaf(session, MOVED)).toEqual([]) - }) -}) - -// In-flight drags must refuse: a spawn without captured PTY identity can recreate SOURCE:leaf after move. -it('grafts a late spawn result for the moved leaf back into its source tab', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - await store.moveTerminalLeafToNewTab({ ...request, ptyId: null }) - await store.persistPtyBinding({ - worktreeId: WT, - tabId: SOURCE, - leafId: MOVED, - ptyId: 'pty-late', - incarnationId: 'inc-late' - }) - expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED).sort()).toEqual([SOURCE, TARGET]) -}) diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move.ts b/src/main/persistence/terminal-topology/terminal-leaf-move.ts deleted file mode 100644 index 6907df901bd..00000000000 --- a/src/main/persistence/terminal-topology/terminal-leaf-move.ts +++ /dev/null @@ -1,298 +0,0 @@ -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' -import { - terminalLeafMovePaneKeys, - type TerminalLeafMoveRequest, - type TerminalLeafMoveResult -} from '../../../shared/workspace-layout/terminal-leaf-move' -import type { - TerminalLayoutSnapshot, - TerminalTab -} from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { retireLeavesFromTerminalLayout } from '../../../shared/workspace-layout/terminal-layout-leaf-retirement' -import { createMinimalPersistedTerminalTab } from '../restoring-sessions/session-owner-fields' -import { layoutContainsLeafId } from '../restoring-sessions/terminal-layout-normalization' -import { writeRestorable } from './restorable-write' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' -import { - advanceTerminalTopologyRevision, - isTerminalOwnerPartition, - type TerminalSessionPartition -} from './terminal-topology-membership' - -type PlannedTerminalLeafMove = { - result: TerminalLeafMoveResult - sessions: TerminalSessionPartition[] -} - -export function moveRecordKey( - record: Record | undefined, - fromKey: string, - toKey: string | null, - remap: (value: T) => T = (value) => value, - /** Preserve existing destination values on collision. */ - keepTarget = false -): Record | undefined { - if (!record || !Object.hasOwn(record, fromKey)) { - return record - } - const next = { ...record } - const value = next[fromKey] - delete next[fromKey] - if (toKey !== null && value !== undefined && !(keepTarget && Object.hasOwn(next, toKey))) { - next[toKey] = remap(value) - } - return next -} - -function liveTabIds(session: WorkspaceSessionState): Set { - return new Set( - Object.values(session.tabsByWorktree ?? {}).flatMap((tabs) => tabs.map((tab) => tab.id)) - ) -} - -function hasTabId(session: WorkspaceSessionState, tabId: string): boolean { - return ( - liveTabIds(session).has(tabId) || Object.hasOwn(session.terminalLayoutsByTabId ?? {}, tabId) - ) -} - -/** Removed-tab layouts cannot claim leaf ownership. */ -export function leafHeldByOtherTab( - session: WorkspaceSessionState, - sourceTabId: string, - leafId: string -): boolean { - const tabIds = liveTabIds(session) - return Object.entries(session.terminalLayoutsByTabId ?? {}).some( - ([tabId, layout]) => - tabId !== sourceTabId && - tabIds.has(tabId) && - layoutContainsLeafId(layout?.root ?? null, leafId) - ) -} - -type SourceHolder = TerminalSessionPartition & { - sourceTab: TerminalTab - sourceLayout: TerminalLayoutSnapshot -} - -function moveLeafInPartition( - { session, sourceTab, sourceLayout }: SourceHolder, - request: TerminalLeafMoveRequest, - ptyId: string | null -): WorkspaceSessionState { - const { worktreeId, sourceTabId, targetTabId, leafId } = request - const tabs = session.tabsByWorktree?.[worktreeId] ?? [] - const { from: fromPaneKey, to: toPaneKey } = terminalLeafMovePaneKeys(request) - const boundHere = sourceLayout.ptyIdsByLeafId?.[leafId] - const remainingLayout = retireLeavesFromTerminalLayout(sourceLayout, new Set([leafId])) - const remainingPtyIds = Object.values(remainingLayout?.ptyIdsByLeafId ?? {}) - const row = createMinimalPersistedTerminalTab({ - worktreeId, - tabId: targetTabId, - ptyId: ptyId ?? '', - existingTabCount: tabs.length, - ...(sourceTab.startupCwd ? { startupCwd: sourceTab.startupCwd } : {}) - }) - const targetTab = { - ...row, - ptyId, - ...(sourceTab.shellOverride ? { shellOverride: sourceTab.shellOverride } : {}) - } - const nextTabs = tabs.map((tab) => - tab.id === sourceTabId && tab.ptyId === ptyId - ? { ...tab, ptyId: remainingPtyIds[0] ?? null } - : tab - ) - const movedTitle = sourceLayout.titlesByLeafId?.[leafId] - const terminalLayoutsByTabId = { - ...session.terminalLayoutsByTabId, - [targetTabId]: { - root: { type: 'leaf' as const, leafId }, - activeLeafId: leafId, - expandedLeafId: null, - ...(ptyId ? { ptyIdsByLeafId: { [leafId]: ptyId } } : {}), - ...(movedTitle ? { titlesByLeafId: { [leafId]: movedTitle } } : {}), - ...(sourceLayout.chatLeafId === leafId ? { chatLeafId: leafId } : {}) - } - } - if (remainingLayout) { - terminalLayoutsByTabId[sourceTabId] = remainingLayout - } else { - // A sibling never bound here can recreate its layout when its own binding arrives. - delete terminalLayoutsByTabId[sourceTabId] - } - const remoteSessionIdsByTabId = { ...session.remoteSessionIdsByTabId } - if (ptyId && remoteSessionIdsByTabId[sourceTabId] === ptyId) { - remoteSessionIdsByTabId[targetTabId] = ptyId - if (remainingPtyIds[0]) { - remoteSessionIdsByTabId[sourceTabId] = remainingPtyIds[0] - } else { - delete remoteSessionIdsByTabId[sourceTabId] - } - } - return advanceTerminalTopologyRevision( - { - ...session, - tabsByWorktree: { ...session.tabsByWorktree, [worktreeId]: [...nextTabs, targetTab] }, - terminalLayoutsByTabId, - ...(session.remoteSessionIdsByTabId ? { remoteSessionIdsByTabId } : {}), - // Stale copies cannot carry another PTY's incarnation to the destination. - terminalPtyIncarnationsByPaneKey: moveRecordKey( - session.terminalPtyIncarnationsByPaneKey, - fromPaneKey, - boundHere && boundHere !== ptyId ? null : toPaneKey - ), - sleepingAgentSessionsByPaneKey: moveRecordKey( - session.sleepingAgentSessionsByPaneKey, - fromPaneKey, - toPaneKey, - (record) => ({ ...record, paneKey: toPaneKey, tabId: targetTabId }) - ) - }, - worktreeId - ) -} - -/** Move every partition holder and pane-keyed record atomically; preserve leaf/PTY identity (STA-9259). */ -export function planTerminalLeafMove( - partitions: readonly TerminalSessionPartition[], - request: TerminalLeafMoveRequest -): PlannedTerminalLeafMove { - const { worktreeId, sourceTabId, leafId } = request - const refuse = ( - reason: Extract['reason'] - ): PlannedTerminalLeafMove => ({ result: { status: 'refused', reason }, sessions: [] }) - const owners = partitions.filter(({ hostId }) => isTerminalOwnerPartition(hostId)) - if (partitions.some(({ session }) => hasTabId(session, request.targetTabId))) { - return refuse('target_tab_exists') - } - if (owners.some(({ session }) => leafHeldByOtherTab(session, sourceTabId, leafId))) { - return refuse('leaf_in_other_tab') - } - const holders = owners.flatMap(({ hostId, session }) => { - const sourceTab = session.tabsByWorktree?.[worktreeId]?.find((tab) => tab.id === sourceTabId) - const sourceLayout = session.terminalLayoutsByTabId?.[sourceTabId] - return sourceTab && sourceLayout && layoutContainsLeafId(sourceLayout.root, leafId) - ? [{ hostId, session, sourceTab, sourceLayout }] - : [] - }) - if (holders.length === 0) { - return { result: { status: 'not_held' }, sessions: [] } - } - if ( - request.keepsSourcePane && - holders.some(({ sourceLayout }) => collectLeafIds(sourceLayout.root).length < 2) - ) { - return refuse('last_pane') - } - const boundPtyIds = new Set( - holders.flatMap(({ sourceLayout }) => sourceLayout.ptyIdsByLeafId?.[leafId] ?? []) - ) - // Prefer the renderer's live PTY; an SSH respawn can leave an old ID in one copy. - const ptyId = request.ptyId ?? (boundPtyIds.size === 1 ? [...boundPtyIds][0] : null) - if (boundPtyIds.size > 0 && !(ptyId && boundPtyIds.has(ptyId))) { - return refuse('pty_mismatch') - } - return { - result: { status: 'moved', ptyId }, - sessions: holders.map((holder) => ({ - hostId: holder.hostId, - session: moveLeafInPartition(holder, request, ptyId) - })) - } -} - -const PANE_KEYED_UI_RECORDS = [ - 'acknowledgedAgentsByPaneKey', - 'activityClearedAtByPaneKey', - 'manuallyUnreadTurnsByPaneKey' -] as const - -type PaneAddress = { tabId: string; leafId: string } - -export function rekeyPaneProfileRecords( - state: Pick, - from: PaneAddress, - to: PaneAddress -): { ui?: PersistedState['ui']; sshRemotePtyLeases?: SshRemotePtyLease[] } { - const fromPaneKey = makePaneKey(from.tabId, from.leafId) - const toPaneKey = makePaneKey(to.tabId, to.leafId) - const ui = state.ui - let nextUi: PersistedState['ui'] | undefined - for (const key of PANE_KEYED_UI_RECORDS) { - const moved = moveRecordKey(ui?.[key], fromPaneKey, toPaneKey) - if (ui && moved !== ui[key]) { - nextUi = { ...(nextUi ?? ui), [key]: moved } - } - } - const leases = state.sshRemotePtyLeases ?? [] - const leasesChanged = leases.some( - (lease) => lease.tabId === from.tabId && lease.leafId === from.leafId - ) - return { - ...(nextUi ? { ui: nextUi } : {}), - ...(leasesChanged - ? { - sshRemotePtyLeases: leases.map((lease) => - lease.tabId === from.tabId && lease.leafId === from.leafId - ? { ...lease, tabId: to.tabId, leafId: to.leafId } - : lease - ) - } - : {}) - } -} - -export function rekeyMovedLeafProfileRecords( - state: Pick, - move: TerminalLeafMoveRequest -): { ui?: PersistedState['ui']; sshRemotePtyLeases?: SshRemotePtyLease[] } { - return rekeyPaneProfileRecords( - state, - { tabId: move.sourceTabId, leafId: move.leafId }, - { tabId: move.targetTabId, leafId: move.leafId } - ) -} - -/** Return restores for rekeyed UI marks and SSH leases. */ -export function writeMovedLeafProfileRecords( - request: TerminalLeafMoveRequest, - context: TerminalTopologyCommitContext -): (() => void)[] { - return writeRekeyedProfileRecords(rekeyMovedLeafProfileRecords(context.state, request), context) -} - -/** Return restores for rekeyed profile records. */ -export function writeRekeyedProfileRecords( - rekeyed: ReturnType, - context: TerminalTopologyCommitContext -): (() => void)[] { - const { state } = context - const restores: (() => void)[] = [] - if (rekeyed.ui) { - restores.push( - writeRestorable( - () => state.ui, - (ui) => (state.ui = ui), - rekeyed.ui - ) - ) - context.markDirty('ui') - } - if (rekeyed.sshRemotePtyLeases) { - restores.push( - writeRestorable( - () => state.sshRemotePtyLeases, - (leases) => (state.sshRemotePtyLeases = leases), - rekeyed.sshRemotePtyLeases - ) - ) - context.markDirty('sshRemotePtyLeases') - } - return restores -} diff --git a/src/main/persistence/terminal-topology/terminal-topology-commit.ts b/src/main/persistence/terminal-topology/terminal-topology-commit.ts index d3c8168af1c..edc27b39f36 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-commit.ts +++ b/src/main/persistence/terminal-topology/terminal-topology-commit.ts @@ -1,10 +1,10 @@ import type { ExecutionHostId } from '../../../shared/execution-host' -import { hasClosedTerminalTabRecord } from '../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import type { PersistedState } from '../../../shared/persisted-state-types' import type { TerminalLeafMoveRequest, TerminalLeafMoveResult -} from '../../../shared/workspace-layout/terminal-leaf-move' +} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { CommandOf, @@ -18,7 +18,7 @@ import { type PaneLayoutChange, type TerminalPaneAdmission, type TerminalPaneAdmissionOutcome -} from './terminal-pane-admission' +} from './pane-admission/terminal-pane-admission' import { startSpan } from '../../observability/tracer' import { terminalSurfaceCloseMutation, @@ -29,21 +29,21 @@ import type { StoreRuntimeState } from '../loading-store/store-runtime-state' import type { SessionHostPartitionOperations } from '../loading-store/workspace-sessions/session-host-partitions' -import { planTerminalLeafMove, writeMovedLeafProfileRecords } from './terminal-leaf-move' -import { writeRestorable } from './restorable-write' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' +import { planTerminalLeafMove, writeMovedLeafProfileRecords } from './pane-moves/terminal-leaf-move' +import { writeRestorable } from './command-application/restorable-write' +import { assignWorkspaceSessionPartition } from './pane-ownership/terminal-topology-membership' import { commitLayoutCommand, commitLayoutCommandsAcrossPartitions, commitWindowPaneDetach, keepFrozen, type LayoutCommandRun -} from './layout-command-commit' +} from './command-application/layout-command-commit' import { fencedIfLayoutOwner, layoutCommandFence, partitionsFence -} from './closed-pane-binding-fence' +} from './pane-ownership/closed-pane-binding-fence' /** Binding writes already have their own persistence.pty-binding span. */ type TerminalTopologyCommitKind = diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move-fixture.ts b/src/main/persistence/terminal-topology/testing/terminal-leaf-move-fixture.ts similarity index 83% rename from src/main/persistence/terminal-topology/terminal-leaf-move-fixture.ts rename to src/main/persistence/terminal-topology/testing/terminal-leaf-move-fixture.ts index 26918caf720..9668bf9f61c 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move-fixture.ts +++ b/src/main/persistence/terminal-topology/testing/terminal-leaf-move-fixture.ts @@ -2,11 +2,11 @@ import { mkdtempSync, realpathSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' -import { Store } from '../loading-store/store' -import { collectLayoutLeafIdsInOrder } from '../restoring-sessions/terminal-layout-normalization' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { closeTestStores, createSqliteTestStore } from '../../persistence-test-harness' +import { Store } from '../../loading-store/store' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' // Import only after the test mocks electron. diff --git a/src/main/persistence/terminal-topology/terminal-topology-profile-fixture.ts b/src/main/persistence/terminal-topology/testing/terminal-topology-profile-fixture.ts similarity index 80% rename from src/main/persistence/terminal-topology/terminal-topology-profile-fixture.ts rename to src/main/persistence/terminal-topology/testing/terminal-topology-profile-fixture.ts index 5742a0a89a3..53ab655f8ec 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-profile-fixture.ts +++ b/src/main/persistence/terminal-topology/testing/terminal-topology-profile-fixture.ts @@ -1,9 +1,9 @@ import { join } from 'node:path' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { DelayedAuthority } from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' -import { Store } from '../loading-store/store' -import { buildProfileStateCutoverFixture } from '../profile-state-cutover-fixture' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import { DelayedAuthority } from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' +import { Store } from '../../loading-store/store' +import { buildProfileStateCutoverFixture } from '../../profile-state-cutover-fixture' +import { ProfileStateSqliteAuthority } from '../../profile-state/profile-state-sqlite-authority' // Register this fixture repo so load pruning preserves its workspace. export const FIXTURE_GIT_WORKTREE_ID = 'repo-local::/fixture/local' diff --git a/src/main/persistence/terminal-topology/terminal-topology-window-session-fixture.ts b/src/main/persistence/terminal-topology/testing/terminal-topology-window-session-fixture.ts similarity index 92% rename from src/main/persistence/terminal-topology/terminal-topology-window-session-fixture.ts rename to src/main/persistence/terminal-topology/testing/terminal-topology-window-session-fixture.ts index 0caf345bf7a..4b64a9acb28 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-window-session-fixture.ts +++ b/src/main/persistence/terminal-topology/testing/terminal-topology-window-session-fixture.ts @@ -1,10 +1,10 @@ -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { Tab } from '../../../shared/tab-types' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { Tab } from '../../../../shared/tab-types' import type { TerminalPaneLayoutNode, TerminalTab -} from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +} from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' export function leafIds(node: TerminalPaneLayoutNode | null | undefined): string[] { if (!node) { diff --git a/src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts b/src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts deleted file mode 100644 index 312ba9c8826..00000000000 --- a/src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { Store } from '../loading-store/store' -import { leafIds } from './terminal-topology-window-session-fixture' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from './terminal-topology-profile-fixture' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const WORKTREE = FIXTURE_GIT_WORKTREE_ID -const leaf = (n: number): string => `${n}${n}${n}${n}${n}${n}${n}${n}-1111-4111-8111-111111111111` -const directories: string[] = [] - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -const on = { workspace: WORKTREE } - -async function apply(store: Store, command: LayoutCommand): Promise { - const result = await store.applyLayoutCommand(command) - expect(result.ok, command.type).toBe(true) -} - -async function bind(store: Store, tabId: string, leafId: string, ptyId: string): Promise { - await store.persistPtyBinding({ - worktreeId: WORKTREE, - tabId, - leafId, - ptyId, - incarnationId: `inc-${ptyId}` - }) -} - -function terminalsOf(session: WorkspaceSessionState) { - return { - rows: (session.tabsByWorktree[WORKTREE] ?? []).map((row) => [row.id, row.ptyId]), - tabBar: (session.unifiedTabs?.[WORKTREE] ?? []).map((tab) => tab.id), - panes: Object.fromEntries( - Object.entries(session.terminalLayoutsByTabId).map(([tabId, layout]) => [ - tabId, - { leaves: leafIds(layout.root), bindings: layout.ptyIdsByLeafId } - ]) - ), - sleeping: Object.keys(session.sleepingAgentSessionsByPaneKey ?? {}) - } -} - -describe('a windowless host reloaded in the layout-owner build', () => { - it('drops no terminal tab, pane or sleeping agent that main wrote itself', async () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-windowless-reload-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-split', leafId: leaf(1) }) - await bind(store, 'tab-split', leaf(1), 'pty-1') - await apply(store, { - ...on, - type: 'splitPane', - tabId: 'tab-split', - leafId: leaf(1), - direction: 'vertical', - newLeafId: leaf(2) - }) - await bind(store, 'tab-split', leaf(2), 'pty-2') - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-closed', leafId: leaf(3) }) - await bind(store, 'tab-closed', leaf(3), 'pty-3') - await apply(store, { ...on, type: 'closeTabs', tabIds: ['tab-closed'] }) - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-asleep', leafId: leaf(4) }) - await bind(store, 'tab-asleep', leaf(4), 'pty-4') - const paneKey = makePaneKey('tab-asleep', leaf(4)) - await apply(store, { - ...on, - type: 'sleep', - paneKeys: [paneKey], - records: [ - { - paneKey, - tabId: 'tab-asleep', - worktreeId: WORKTREE, - agent: 'codex', - providerSession: { key: 'session_id', id: 'session-4' }, - prompt: 'p', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'live' - } - ] - }) - await apply(store, { - ...on, - type: 'createTerminalTab', - tabId: 'tab-unstarted', - leafId: leaf(5) - }) - await store.flushPendingOrThrowAsync() - const written = terminalsOf(store.getWorkspaceSession()) - expect(written.rows.map(([id]) => id)).toEqual(['tab-split', 'tab-asleep', 'tab-unstarted']) - expect(written.sleeping).toEqual([paneKey]) - - const relaunched = await reopenTopologyStore(store, directory) - - expect(terminalsOf(relaunched.getWorkspaceSession())).toEqual(written) - }) -}) diff --git a/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts b/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts index 6ae872368c6..e56d8347ef4 100644 --- a/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts +++ b/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts @@ -219,6 +219,10 @@ export function isLocallyRemovableWorktreeMetadataRow( return false } const canonical = identityKeys?.[0] ? state.worktreeMetaByIdentity?.[identityKeys[0]] : undefined + // An archived workspace's checkout is missing on purpose; its row is the workspace. + if (legacy?.archivedCheckout || canonical?.archivedCheckout) { + return false + } return !( (legacy?.hostId && legacy.hostId !== LOCAL_EXECUTION_HOST_ID) || (canonical?.hostId && canonical.hostId !== LOCAL_EXECUTION_HOST_ID) || diff --git a/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts b/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts index afbfb7b8d3a..1be5bb9bcc1 100644 --- a/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts +++ b/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts @@ -129,6 +129,27 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => { expect(state.worktreeMeta[worktreeId]).toBeDefined() }) + it('keeps an archived workspace whose checkout was deleted on purpose', () => { + const state = makeState() + const archivedId = `${REPO_ID}::/workspace/archived` + const deletedId = `${REPO_ID}::/workspace/deleted` + state.worktreeMeta[archivedId] = { + ...makeMeta(archivedId), + comment: 'pick up after review', + linkedPR: 42, + isArchived: true, + archivedCheckout: { branch: 'feature/archived', archivedAt: 1 } + } + state.worktreeMeta[deletedId] = makeMeta(deletedId) + const scan = capture(state) + + expect(pruneCaptured(state, scan, [archivedId, deletedId])).toEqual([deletedId]) + expect(state.worktreeMeta[archivedId]).toMatchObject({ + comment: 'pick up after review', + linkedPR: 42 + }) + }) + // Route-retired tombstones must not pin metadata forever (#17775). it('does not let route-retired SSH leases pin a metadata row', () => { const state = makeState() diff --git a/src/main/persistence/tracking-repos/persistence-update-repo.test.ts b/src/main/persistence/tracking-repos/persistence-update-repo.test.ts index ab0c023f7e2..e042dfdea2e 100644 --- a/src/main/persistence/tracking-repos/persistence-update-repo.test.ts +++ b/src/main/persistence/tracking-repos/persistence-update-repo.test.ts @@ -19,6 +19,12 @@ import { } from '../../workspaces/catalog/folder-repo-git-conversion' import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' import { removeWorktreeMetaRow } from '../host-qualified-worktree-meta' +import { registerWorktreeCatalogRoutes } from '../../runtime/workspaces/catalog/worktree-catalog-live-route' +import { resolveWorktreeScanRuntime } from '../../runtime/workspaces/catalog/runtime-worktree-scan-cache' +import { + isLiveWorktreeCatalogRoute, + setWorktreeCatalogRouteResolver +} from '../../workspaces/catalog/repo-worktree-catalog-route' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), @@ -96,6 +102,46 @@ describe('Store', () => { ]) }) + it("revokes a repo's local Git catalog route as soon as its registration is removed", async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1', path: '/local/repo' })) + registerWorktreeCatalogRoutes(store as never) + try { + const repo = store.getRepos()[0] + const route = { + repoPath: '/local/repo', + runtimeKey: resolveWorktreeScanRuntime(store as never, repo).runtimeKey + } + expect(isLiveWorktreeCatalogRoute('r1', 'local', route)).toBe(true) + + store.removeProjectForHost({ id: 'r1' }) + + expect(isLiveWorktreeCatalogRoute('r1', 'local', route)).toBe(false) + } finally { + setWorktreeCatalogRouteResolver(null) + } + }) + + it('admits a folder converted to Git as a local Git route as soon as the write lands', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1', path: '/local/folder', kind: 'folder' })) + registerWorktreeCatalogRoutes(store as never) + try { + const routeFor = () => ({ + repoPath: '/local/folder', + runtimeKey: resolveWorktreeScanRuntime(store as never, store.getRepos()[0]).runtimeKey + }) + expect(isLiveWorktreeCatalogRoute('r1', 'local', routeFor())).toBe(false) + + store.updateRepo({ id: 'r1' }, { kind: 'git', folderUpgradeGitRootPath: '/local/folder' }) + + expect(store.getRepos()[0]?.kind).toBe('git') + expect(isLiveWorktreeCatalogRoute('r1', 'local', routeFor())).toBe(true) + } finally { + setWorktreeCatalogRouteResolver(null) + } + }) + it('repo mutations preserve independent project host setup records', async () => { const independentProject = makeProject({ id: 'cloud-project', diff --git a/src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts b/src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts index 3e57c5c02af..5b532c927d4 100644 --- a/src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts +++ b/src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts @@ -106,6 +106,6 @@ describe('Store', () => { initDataPath() const store = createSqliteTestStore(Store, { dataFile: profileDataFile }) - expect(store.readTerminalScrollbackSnapshot(ref)).toBe('legacy-scrollback') + expect(await store.readTerminalScrollbackSnapshotAsync(ref)).toBe('legacy-scrollback') }) }) diff --git a/src/main/persistence/tracking-repos/project-host-compatibility.ts b/src/main/persistence/tracking-repos/project-host-compatibility.ts index f461bf44c6b..d22ad118fc2 100644 --- a/src/main/persistence/tracking-repos/project-host-compatibility.ts +++ b/src/main/persistence/tracking-repos/project-host-compatibility.ts @@ -4,6 +4,7 @@ import type { Repo } from '../../../shared/repo-types' import type { ExecutionHostId } from '../../../shared/execution-host' import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' import { carryProjectStateThroughIdentityChange } from '../../../shared/project-identity-succession' +import { markWorktreeRouteInputsChanged } from '../../workspaces/catalog/local-worktree-scan-generation' export function projectHostSetupCompatibilityStateEqual( state: Pick, @@ -107,3 +108,14 @@ export function makeProjectHostSetupId( } return candidate } + +/** Project membership decides each repo's Git runtime, so applying it changes catalog routes. */ +export function applyProjectHostSetupCompatibilityState( + state: Pick, + repos: readonly Repo[] +): void { + const merged = mergeProjectHostSetupCompatibilityState(state, repos) + state.projects = merged.projects + state.projectHostSetups = merged.projectHostSetups + markWorktreeRouteInputsChanged() +} diff --git a/src/main/persistence/tracking-repos/repo-hydration.ts b/src/main/persistence/tracking-repos/repo-hydration.ts index a34af6f40d6..96fef7617d6 100644 --- a/src/main/persistence/tracking-repos/repo-hydration.ts +++ b/src/main/persistence/tracking-repos/repo-hydration.ts @@ -3,10 +3,11 @@ import { getRepoExecutionHostId } from '../../../shared/execution-host' import { getDefaultRepoHookSettings } from '../../../shared/constants' import { isFolderRepo } from '../../../shared/repo-kind' import { sanitizeRepoIcon } from '../../../shared/repo-icon' -import { normalizeGhAccountBinding } from '../../../shared/github/account-binding' +import { normalizeGhAccountBinding } from '../../../shared/github/accounts/account-binding' import { normalizeJiraProjectReference } from '../../../shared/jira/jira-project-reference' import { normalizeRepoSourceControlAiOverrides } from '../../../shared/source-control/ai/settings/source-control-ai-repo-settings' import { normalizeOrcadRetainedMarker } from '../../../shared/orcad-retained-marker' +import { normalizeRepoWorkspaceCleanupPolicy } from '../../../shared/workspace-cleanup/workspace-cleanup-policy' import { sanitizeAgentWorkspaceTrustDecision } from '../../../shared/agent-launch/permissions/agent-workspace-trust-decision' import { sanitizeForkSyncMode, @@ -17,7 +18,7 @@ import { import { normalizeCustomWorktreeVisibilitySources, normalizeWorktreeVisibilitySourcePreferences -} from '../../../shared/worktree/visibility-sources' +} from '../../../shared/worktree/visibility/visibility-sources' /** Same paths on different hosts can have different git usernames and branch prefixes. */ export function repoGitUsernameCacheKey( @@ -33,6 +34,7 @@ export function hydrateRepo(repo: Repo, gitUsernameCache: ReadonlyMap { }) expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) - expect(state.worktreeMetaByIdentity).toEqual({ valid: makeMeta() }) expect(state.worktreeIdentityAliases).toEqual({ 'local|r1::/tmp/wt': ['valid'] }) }) @@ -52,10 +50,6 @@ describe('normalizeWorktreeLinkedItemMetadata', () => { expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) expect(state.worktreeMeta).toEqual({}) - expect(state.worktreeMetaByIdentity).toEqual({ - [localKey]: makeMeta(), - [remoteKey]: makeMeta() - }) expect(state.worktreeIdentityAliases).toEqual({ [`local|${worktreeId}`]: [localKey], [`ssh:builder|${worktreeId}`]: [remoteKey] @@ -73,7 +67,6 @@ describe('normalizeWorktreeLinkedItemMetadata', () => { expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) expect(state.worktreeMeta).toEqual({}) - expect(state.worktreeMetaByIdentity).toEqual({ [identityKey]: makeMeta() }) expect(state.worktreeIdentityAliases).toEqual({ [alias]: [identityKey] }) }) @@ -89,39 +82,30 @@ describe('normalizeWorktreeLinkedItemMetadata', () => { }) expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) - expect(state.worktreeMetaByIdentity).toEqual({ [liveKey]: makeMeta() }) expect(state.worktreeIdentityAliases).toEqual({ 'local|r1::/tmp/live': [liveKey] }) }) }) describe('gcStaleWorktreeMeta', () => { - it('reclaims the identity rows of a collected worktree', () => { - const worktreeId = 'r1::/definitely/missing/orca/path' - const identityKey = 'wt2:local:dead' - const remoteIdentityKey = 'wt2:ssh:live' + it('keeps an archived workspace whose checkout was deleted on purpose', () => { + const worktreeId = 'r1::/definitely/missing/orca/archived' const state = makeState({ repos: [], projects: [], worktreeMeta: { [worktreeId]: { + ...makeMeta(), hostId: 'local', - instanceId: 'dead', - displayName: 'dead', - lastActivityAt: Date.now() - WORKTREE_META_GC_GRACE_MS - 1 - } as unknown as WorktreeMeta - }, - worktreeMetaByIdentity: { [identityKey]: makeMeta(), [remoteIdentityKey]: makeMeta() }, - worktreeIdentityAliases: { - [`local|${worktreeId}`]: [identityKey], - [`ssh:conn-1|${worktreeId}`]: [remoteIdentityKey] + comment: 'resume after review', + isArchived: true, + archivedCheckout: { branch: 'feature/archived', archivedAt: 1 }, + // Epoch-start activity is past any grace period, so only the archive mark keeps it. + lastActivityAt: 1 + } } }) - expect(gcStaleWorktreeMeta(state)).toBe(1) - // Dead aliases could attach stale metadata to future worktrees reusing this path. - expect(state.worktreeMetaByIdentity).toEqual({ [remoteIdentityKey]: expect.anything() }) - expect(state.worktreeIdentityAliases).toEqual({ - [`ssh:conn-1|${worktreeId}`]: [remoteIdentityKey] - }) + expect(gcStaleWorktreeMeta(state)).toBe(0) + expect(state.worktreeMeta[worktreeId]?.comment).toBe('resume after review') }) }) diff --git a/src/main/persistence/tracking-repos/worktree-metadata-normalization.ts b/src/main/persistence/tracking-repos/worktree-metadata-normalization.ts index a5fe8bd25d0..4467046ce7b 100644 --- a/src/main/persistence/tracking-repos/worktree-metadata-normalization.ts +++ b/src/main/persistence/tracking-repos/worktree-metadata-normalization.ts @@ -20,7 +20,7 @@ import { removeWorktreeMetadataForHost } from '../loading-store/worktree-metadata/worktree-identity-metadata' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { fillDefaultWorktreeMetaFields } from '../../../shared/worktree/meta-persisted-defaults' +import { fillDefaultWorktreeMetaFields } from '../../../shared/worktree/metadata/meta-persisted-defaults' import { getWorkspaceAttachments } from '../../../shared/workspace-attachments/workspace-attachments' import { rehomeLocalOnlyWorktreeMetadata } from '../loading-store/worktree-metadata/local-only-worktree-meta-rehoming' @@ -57,7 +57,8 @@ export function gcStaleWorktreeMeta(state: PersistedState): number { } else if (projectIds.has(ownerId)) { continue } - if (meta?.hostId && meta.hostId !== LOCAL_EXECUTION_HOST_ID) { + // An archived workspace's checkout is missing on purpose; its row is the workspace. + if ((meta?.hostId && meta.hostId !== LOCAL_EXECUTION_HOST_ID) || meta?.archivedCheckout) { continue } if (!isAbsolute(worktreePath) || isWslUncPath(worktreePath)) { diff --git a/src/main/persistence/window-save-divergence.ts b/src/main/persistence/window-save-divergence.ts index bbdf8d2a566..5f8145e3357 100644 --- a/src/main/persistence/window-save-divergence.ts +++ b/src/main/persistence/window-save-divergence.ts @@ -7,9 +7,9 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' -import { loadWorkspaceLayoutWithoutReport } from '../../shared/workspace-layout/workspace-layout-load' -import { stableJson } from '../../shared/workspace-layout/workspace-layout-load-report' -import { nameBasedLoadContext } from '../../shared/workspace-layout/workspace-layout-minted-ids' +import { loadWorkspaceLayoutWithoutReport } from '../../shared/workspace-layout/persistence/workspace-layout-load' +import { stableJson } from '../../shared/workspace-layout/persistence/workspace-layout-load-report' +import { nameBasedLoadContext } from '../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import type { WorkspaceLayout, WorkspaceLayoutModel diff --git a/src/main/persistence/window-save-reconnect-facts.test.ts b/src/main/persistence/window-save-reconnect-facts.test.ts deleted file mode 100644 index 7e388dba0b7..00000000000 --- a/src/main/persistence/window-save-reconnect-facts.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { toSshExecutionHostId } from '../../shared/execution-host' -import type { SshConnectionStatus } from '../../shared/ssh-types' -import { - addWorkspace, - emptySession, - GIT_KEY, - leaf, - SSH_KEY -} from '../../shared/workspace-layout/workspace-layout-session.test-fixture' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import { deriveShutdownReconnectFacts } from '../runtime/terminal/recovery/shutdown-reconnect-facts' -import { windowViewPatchForMain, windowViewSaveForMain } from './window-save-view' - -const TARGET = 'target' -const SSH_HOST = toSshExecutionHostId(TARGET) -const RELAY = `ssh:${TARGET}@@pty-42` - -function sshPartition(): WorkspaceSessionState { - return addWorkspace( - emptySession(), - SSH_KEY, - [{ id: 'group-s', tabs: [{ id: 'tab-s', leaves: [[leaf(3), RELAY]] }] }], - SSH_HOST - ) -} - -function localPartition(): WorkspaceSessionState { - return addWorkspace(emptySession(), GIT_KEY, [ - { - id: 'group-g', - tabs: [ - { id: 'tab-live', leaves: [[leaf(1), 'pty-live']] }, - { id: 'tab-gone', leaves: [[leaf(2), 'pty-gone']] } - ] - } - ]) -} - -const factsFor = - ( - live: string[], - ssh: [string, SshConnectionStatus][], - more: { exited?: string[]; others?: WorkspaceSessionState[] } = {} - ) => - (session: WorkspaceSessionState) => - deriveShutdownReconnectFacts(session, { - isLiveLocalPty: (ptyId) => live.includes(ptyId), - isKnownExited: (ptyId) => more.exited?.includes(ptyId) ?? false, - sshStatusByTargetId: new Map(ssh), - otherPartitions: () => more.others ?? [] - }) - -function forgetfulSave(stored: WorkspaceSessionState): WorkspaceSessionState { - return { - ...stored, - activeWorktreeIdsOnShutdown: [], - remoteSessionIdsByTabId: undefined, - activeConnectionIdsAtShutdown: undefined - } -} - -describe('what the next startup reconnects comes from main, not the window’s save', () => { - it('keeps an unvisited SSH tab’s relay session and its target the window dropped', () => { - const stored = sshPartition() - - const saved = windowViewSaveForMain( - stored, - forgetfulSave(stored), - SSH_HOST, - factsFor([], [[TARGET, 'reconnecting']]) - ) - - expect(saved.remoteSessionIdsByTabId).toEqual({ 'tab-s': RELAY }) - expect(saved.activeWorktreeIdsOnShutdown).toEqual([SSH_KEY]) - expect(saved.activeConnectionIdsAtShutdown).toEqual([TARGET]) - }) - - it('names only workspaces with a running local terminal, whatever the window sent', () => { - const stored = localPartition() - const save = { ...stored, activeWorktreeIdsOnShutdown: ['repo-1::/elsewhere'] } - - const saved = windowViewSaveForMain(stored, save, null, factsFor(['pty-live'], [])) - - expect(saved.activeWorktreeIdsOnShutdown).toEqual([GIT_KEY]) - expect(saved).not.toHaveProperty('remoteSessionIdsByTabId') - expect(saved).not.toHaveProperty('activeConnectionIdsAtShutdown') - expect( - windowViewSaveForMain(stored, save, null, factsFor([], [])).activeWorktreeIdsOnShutdown - ).toEqual([]) - }) - - it('a slept pane keeps its relay id as a wake hint only: the next startup does not reconnect it', () => { - const stored = sshPartition() - stored.sleepingAgentSessionsByPaneKey = { - [`tab-s:${leaf(3)}`]: { - paneKey: `tab-s:${leaf(3)}`, - worktreeId: SSH_KEY, - agent: 'codex', - providerSession: { key: 'session_id', id: 'sess-1' }, - prompt: '', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep' - } - } - - const saved = windowViewSaveForMain(stored, stored, SSH_HOST, factsFor([], [])) - - expect(saved).not.toHaveProperty('remoteSessionIdsByTabId') - expect(saved.activeWorktreeIdsOnShutdown).toEqual([]) - }) - - it.each(['live', 'quit'] as const)( - 'a running agent’s %s resume record is not a sleep: its relay session reconnects', - (origin) => { - const stored = sshPartition() - stored.sleepingAgentSessionsByPaneKey = { - [`tab-s:${leaf(3)}`]: { - paneKey: `tab-s:${leaf(3)}`, - worktreeId: SSH_KEY, - agent: 'codex', - providerSession: { key: 'session_id', id: 'sess-1' }, - prompt: '', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin - } - } - - const saved = windowViewSaveForMain(stored, stored, SSH_HOST, factsFor([], [])) - - expect(saved.remoteSessionIdsByTabId).toEqual({ 'tab-s': RELAY }) - expect(saved.activeWorktreeIdsOnShutdown).toEqual([SSH_KEY]) - } - ) - - it('a target the user left offline is not redialed; a connected one is', () => { - const stored = sshPartition() - - expect( - windowViewSaveForMain(stored, stored, SSH_HOST, factsFor([], [[TARGET, 'disconnected']])) - ).not.toHaveProperty('activeConnectionIdsAtShutdown') - expect( - windowViewSaveForMain(stored, stored, SSH_HOST, factsFor([], [['other', 'connected']])) - .activeConnectionIdsAtShutdown - ).toEqual(['other']) - }) - - it('the local save names a target in a passing state from a relay session in its SSH partition', () => { - const local = localPartition() - // Reconnecting relay routes remain recoverable at quit. - const facts = factsFor([], [[TARGET, 'reconnecting']], { others: [sshPartition()] }) - - expect(windowViewSaveForMain(local, local, null, facts).activeConnectionIdsAtShutdown).toEqual([ - TARGET - ]) - }) - - it('a relay session proven exited (a slept plain shell) is not reconnected', () => { - const stored = sshPartition() - - const saved = windowViewSaveForMain( - stored, - stored, - SSH_HOST, - factsFor([], [[TARGET, 'reconnecting']], { exited: [RELAY] }) - ) - - expect(saved).not.toHaveProperty('remoteSessionIdsByTabId') - expect(saved.activeWorktreeIdsOnShutdown).toEqual([]) - expect(saved).not.toHaveProperty('activeConnectionIdsAtShutdown') - }) - - it('a patch has main’s facts only for the fields it carries', () => { - const stored = sshPartition() - const facts = factsFor([], [[TARGET, 'connected']]) - - expect( - windowViewPatchForMain(stored, { activeConnectionIdsAtShutdown: [] }, SSH_HOST, facts) - ).toEqual({ activeConnectionIdsAtShutdown: [TARGET] }) - expect(windowViewPatchForMain(stored, { activeRepoId: 'r' }, SSH_HOST, facts)).toEqual({ - activeRepoId: 'r' - }) - }) -}) diff --git a/src/main/persistence/window-save-view.ts b/src/main/persistence/window-save-view.ts index f59d90e3db6..241b8d421f3 100644 --- a/src/main/persistence/window-save-view.ts +++ b/src/main/persistence/window-save-view.ts @@ -10,13 +10,13 @@ import type { WorkspaceSessionPatch, WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import { SESSION_FIELD_OWNERS } from '../../shared/workspace-layout/workspace-layout-beside' -import { loadWorkspaceLayoutWithoutReport } from '../../shared/workspace-layout/workspace-layout-load' -import type { LoadedWorkspaceLayout } from '../../shared/workspace-layout/workspace-layout-load-types' -import { nameBasedLoadContext } from '../../shared/workspace-layout/workspace-layout-minted-ids' +import { SESSION_FIELD_OWNERS } from '../../shared/workspace-layout/persistence/workspace-layout-beside' +import { loadWorkspaceLayoutWithoutReport } from '../../shared/workspace-layout/persistence/workspace-layout-load' +import type { LoadedWorkspaceLayout } from '../../shared/workspace-layout/persistence/workspace-layout-load-types' +import { nameBasedLoadContext } from '../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import type { WorkspaceLayoutModel } from '../../shared/workspace-layout/workspace-layout-model' -import { patchStoredSession } from '../../shared/workspace-layout/workspace-layout-record-patch' -import { saveWorkspaceLayout } from '../../shared/workspace-layout/workspace-layout-save' +import { patchStoredSession } from '../../shared/workspace-layout/persistence/workspace-layout-record-patch' +import { saveWorkspaceLayout } from '../../shared/workspace-layout/persistence/workspace-layout-save' import type { ShutdownReconnectFacts } from '../runtime/terminal/recovery/shutdown-reconnect-facts' const FIELD_OWNERS: Readonly> = SESSION_FIELD_OWNERS diff --git a/src/main/persistence/worktree-meta-host-identity.ts b/src/main/persistence/worktree-meta-host-identity.ts new file mode 100644 index 00000000000..2f615b98974 --- /dev/null +++ b/src/main/persistence/worktree-meta-host-identity.ts @@ -0,0 +1,32 @@ +import type { ExecutionHostId } from '../../shared/execution-host' +import type { WorktreeMeta } from '../../shared/worktree/meta-types' +import { worktreeMetaIdentityKey } from '../../shared/worktree/identity' + +type IdentityMeta = Pick + +/** The metadata reads a host-qualified identity lookup needs; real Stores provide both. */ +export type WorktreeMetaIdentitySource = { + getWorktreeMeta: (worktreeId: string) => IdentityMeta | undefined + getWorktreeMetaForHost?: (worktreeId: string, hostId: ExecutionHostId) => IdentityMeta | undefined +} + +/** + * The identity key of `worktreeId` on `hostId`, from that host's metadata row only: a same-id + * row of another host never lends its identity. Without a host, the row's own stamped host + * decides, as removal does. + */ +export function worktreeHostIdentity( + store: WorktreeMetaIdentitySource | null | undefined, + worktreeId: string, + hostId?: ExecutionHostId | null +): { identityKey?: string; hostId?: ExecutionHostId } { + const owner = hostId ?? store?.getWorktreeMeta(worktreeId)?.hostId + if (!store || !owner) { + return {} + } + const meta = store.getWorktreeMetaForHost + ? store.getWorktreeMetaForHost(worktreeId, owner) + : store.getWorktreeMeta(worktreeId) + const identityKey = meta?.hostId === owner ? worktreeMetaIdentityKey(worktreeId, meta) : undefined + return identityKey ? { identityKey, hostId: owner } : { hostId: owner } +} diff --git a/src/main/persistence/worktree-sort-order-write.ts b/src/main/persistence/worktree-sort-order-write.ts index 25040fcf86b..76d2dbd0eaf 100644 --- a/src/main/persistence/worktree-sort-order-write.ts +++ b/src/main/persistence/worktree-sort-order-write.ts @@ -9,7 +9,7 @@ import { import { planWorktreeSortOrderUpdates, type WorktreeSortOrderUpdate -} from '../../shared/worktree/sort-order-update' +} from '../../shared/worktree/metadata/sort-order-update' import { resolveWorktreeMetaOwner } from './host-qualified-worktree-meta' import { createRepoRowExecutionHostLookup } from '../../shared/execution-host/worktree-execution-host-resolution' diff --git a/src/main/pi/rpc/launch/rpc-launch-resolution.ts b/src/main/pi/rpc/launch/rpc-launch-resolution.ts index 3f44e81d773..a6b2b1ce698 100644 --- a/src/main/pi/rpc/launch/rpc-launch-resolution.ts +++ b/src/main/pi/rpc/launch/rpc-launch-resolution.ts @@ -10,12 +10,13 @@ import { import { agentSessionProviderHandleKey } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import type { resolveCliCommand } from '../../../../shared/node-cli-command-resolution' +import { hasReachedAppVersion } from '../../../../shared/app-version' import { checkAgentCliVersion, type AgentCliVersionCheck, type AgentCliVersionReader } from '../../../agent-launch/preflight/agent-cli-version-probe' -import { AgentCliInstallationError } from '../../../native-chat/agent-cli-installation-error' +import { AgentCliInstallationError } from '../../../native-chat/agent-launch/agent-cli-installation-error' import { resolveAgainAfterRefreshOnMissingProgram, assertStructuredAgentResolutionCurrent, @@ -23,10 +24,10 @@ import { resolveStructuredAgentCommand, type StructuredAgentCommand, type StructuredAgentCommandSettings -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' import type { StructuredAgentLaunchPartResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition' import { isWindowsProcessStartTimeAvailable } from '../../../windows/windows-process-table' -import { sessionIdFromFileName } from '../../../ai-vault/session-scanner-accumulator' +import { sessionIdFromFileName } from '../../../ai-vault/parsing/session-scanner-accumulator' import { PI_RPC_SESSION_ENV_TO_DELETE, withoutPiCallerEnv, @@ -43,6 +44,8 @@ export type PiRpcResolvedLaunch = PiRpcLaunchOptions & { replacement?: 'unsaved' | 'restore-failed' /** Conversation files, newest first; empty for a new conversation. */ lineage?: readonly string[] + /** Pi shrinks every image it is sent, including ones queued mid-turn. */ + shrinksImages?: true } export type PiRpcLaunchPartDeps = { resolveCommand?: typeof resolveCliCommand @@ -54,6 +57,8 @@ export type PiRpcLaunchPartDeps = { // RPC turns require agent_settled (Pi 0.84+); older versions remain terminal-only. export const PI_RPC_MINIMUM_VERSIONS = ['0.84.0'] as const +// Before 1.5.1 Pi shrinks prompt images but sends steered and follow-up ones as given. +const PI_SHRINKS_EVERY_IMAGE_VERSION = '1.5.1' export function resolvePiRpcCommand( env: Readonly>, @@ -233,7 +238,11 @@ export function piRpcLaunchPart( ...(sessionFile ? { sessionFile } : {}), ...(forkFile ? { forkFile } : {}), ...(replacement ? { replacement } : {}), - ...(backgroundWork ? { backgroundWork } : {}) + ...(backgroundWork ? { backgroundWork } : {}), + ...(launchVersion.status === 'ready' && + hasReachedAppVersion(launchVersion.version, PI_SHRINKS_EVERY_IMAGE_VERSION) + ? { shrinksImages: true as const } + : {}) }, env: withoutPiCallerEnv(env), inheritedEnvToDelete: PI_RPC_SESSION_ENV_TO_DELETE diff --git a/src/main/pi/rpc/launch/rpc-launch.ts b/src/main/pi/rpc/launch/rpc-launch.ts index ea8addf2c72..2646ad37416 100644 --- a/src/main/pi/rpc/launch/rpc-launch.ts +++ b/src/main/pi/rpc/launch/rpc-launch.ts @@ -4,7 +4,7 @@ import { STRUCTURED_CHILD_ENV_TO_DELETE } from '../../../runtime/agent-session/e import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, NATIVE_CHAT_SCRATCH_DIR_ENV -} from '../../../native-chat/native-chat-visuals-delivery' +} from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import type { ProviderProcessLaunch } from '../../../provider-process/provider-process-launch' import type { PiBackgroundWorkLaunch } from '../background-work/rpc-background-work-bridge' diff --git a/src/main/pi/rpc/options/rpc-model-catalog-probe.ts b/src/main/pi/rpc/options/rpc-model-catalog-probe.ts index 4377321c924..4c693c62485 100644 --- a/src/main/pi/rpc/options/rpc-model-catalog-probe.ts +++ b/src/main/pi/rpc/options/rpc-model-catalog-probe.ts @@ -1,7 +1,7 @@ import { assertStructuredAgentResolutionCurrent, type StructuredAgentCommandSettings -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { homedir } from 'node:os' import { z } from 'zod' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' diff --git a/src/main/pi/rpc/prompts/rpc-prompt-delivery.test.ts b/src/main/pi/rpc/prompts/rpc-prompt-delivery.test.ts index e5460ec1d64..9695f284710 100644 --- a/src/main/pi/rpc/prompts/rpc-prompt-delivery.test.ts +++ b/src/main/pi/rpc/prompts/rpc-prompt-delivery.test.ts @@ -53,8 +53,8 @@ describe('Pi pending prompt delivery bounds and ownership', () => { it('bounds retained retry payload bytes before journal dispatch admission', async () => { const h = rig() - const frame = { type: 'prompt', message: 'x'.repeat(8 * 1024 * 1024 - 128) } - for (let i = 0; i < 4; i++) { + const frame = { type: 'prompt', message: 'x'.repeat(32 * 1024 * 1024 - 128) } + for (let i = 0; i < 3; i++) { await h.delivery.submit(`large:${i}`, i, frame) } const before = vi.fn(async () => {}) diff --git a/src/main/pi/rpc/prompts/rpc-prompt-delivery.ts b/src/main/pi/rpc/prompts/rpc-prompt-delivery.ts index f1d4f43804e..6159e7769d4 100644 --- a/src/main/pi/rpc/prompts/rpc-prompt-delivery.ts +++ b/src/main/pi/rpc/prompts/rpc-prompt-delivery.ts @@ -7,6 +7,7 @@ import { agentSessionFailureWords } from '../../../../shared/agent-session/failu import type { AgentSessionDispatchOutcome } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import type { JsonlRpcRecord } from '../../../jsonl-rpc/peer' import { piRpcPromptReplySchema } from '../rpc-protocol' +import { PI_RPC_PEER_OPTIONS } from './rpc-prompt' type Submission = { id: string @@ -101,7 +102,10 @@ export class PiRpcPromptDelivery { throw new Error('Pi prompt queue unavailable') } const bytes = Buffer.byteLength(JSON.stringify(frame)) - if (this.pending.size >= 128 || this.heldBytes + bytes > 32 * 1024 * 1024) { + if ( + this.pending.size >= 128 || + this.heldBytes + bytes > PI_RPC_PEER_OPTIONS.maxQueuedWriteBytes + ) { return { state: 'rejected', ...agentSessionFailureWords(agentSessionFailureFact('queueFull'), { diff --git a/src/main/pi/rpc/prompts/rpc-prompt.test.ts b/src/main/pi/rpc/prompts/rpc-prompt.test.ts new file mode 100644 index 00000000000..b231d06674c --- /dev/null +++ b/src/main/pi/rpc/prompts/rpc-prompt.test.ts @@ -0,0 +1,67 @@ +import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { preparePiRpcPrompt } from './rpc-prompt' + +const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex') +const directories: string[] = [] +afterEach(async () => { + await Promise.all(directories.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))) +}) + +async function pngOfSize(bytes: number): Promise { + const directory = await mkdtemp(join(tmpdir(), 'orca-pi-prompt-')) + directories.push(directory) + const path = join(directory, `${bytes}.png`) + await writeFile(path, PNG_SIGNATURE) + await truncate(path, bytes) + return path +} + +function message(paths: string[]): AgentJournalMessageItem { + return { + kind: 'message', + role: 'user', + blocks: [ + { type: 'text', text: 'look' }, + ...paths.map((path) => ({ type: 'image-ref' as const, path })) + ] + } +} + +describe('preparePiRpcPrompt', () => { + it('sends a 6 MiB PNG for a Pi that shrinks images', async () => { + const path = await pngOfSize(6 * 1024 * 1024) + + const prompt = await preparePiRpcPrompt(message([path]), true) + + expect(prompt.images).toHaveLength(1) + expect(prompt.images[0]?.mimeType).toBe('image/png') + expect(prompt.images[0]?.data).toHaveLength(8 * 1024 * 1024) + expect(prompt.images[0]?.data.startsWith('iVBORw0KGgo')).toBe(true) + }) + + it('reports an image total over 64 MiB as too large a total, not as history', async () => { + const path = await pngOfSize(22 * 1024 * 1024) + + await expect(preparePiRpcPrompt(message([path, path, path]), true)).rejects.toMatchObject({ + failure: { + kind: 'attachmentInvalid', + attachment: { reason: 'totalTooLarge', limit: 64 * 1024 * 1024 } + } + }) + }) + + it("refuses an image over Anthropic's base64 limit for a Pi that sends it unshrunk", async () => { + const path = await pngOfSize(4 * 1024 * 1024) + + await expect(preparePiRpcPrompt(message([path]), false)).rejects.toMatchObject({ + failure: { + kind: 'attachmentInvalid', + attachment: { reason: 'tooLarge', limit: 3_932_160 } + } + }) + }) +}) diff --git a/src/main/pi/rpc/prompts/rpc-prompt.ts b/src/main/pi/rpc/prompts/rpc-prompt.ts index dc43d62aae6..6903b49b8b5 100644 --- a/src/main/pi/rpc/prompts/rpc-prompt.ts +++ b/src/main/pi/rpc/prompts/rpc-prompt.ts @@ -1,7 +1,16 @@ -import { extname } from 'node:path' -import { resolveJsonlRpcPeerOptions } from '../../../jsonl-rpc/peer-limits' +import { + resolveJsonlRpcPeerOptions, + type JsonlRpcPeerOptions +} from '../../../jsonl-rpc/peer-limits' +import { + AGENT_SESSION_ATTACHMENT_MAX_BYTES, + AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT, + AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES +} from '../../../../shared/agent-session/agent-session-attachments' import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type { NativeChatImageRefBlock } from '../../../../shared/native-chat/native-chat-types' +import { agentInlineImageMimeType } from '../../../../shared/agent-inline-image-types' +import { detectImageFileSignature } from '../../../../shared/image-file-signature' import { agentSessionFailureFact, type SubmissionRejectionFact @@ -12,17 +21,29 @@ import { readClaudeImage } from '../../../claude/structured/claude-structured-dispatch-content' -const MAX_IMAGE_BYTES = 5 * 1024 * 1024 -const MAX_IMAGE_COUNT = 20 -const MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024 -const MAX_PROMPT_WIRE_BYTES = resolveJsonlRpcPeerOptions().maxLineBytes - 1 -const MIME_BY_EXTENSION: Readonly> = { - '.gif': 'image/gif', - '.jpeg': 'image/jpeg', - '.jpg': 'image/jpeg', - '.png': 'image/png', - '.webp': 'image/webp' +type ImageLimits = { image: number; total: number } +const SHRUNK_IMAGE_LIMITS: ImageLimits = { + image: AGENT_SESSION_ATTACHMENT_MAX_BYTES, + total: AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES } +const PEER_DEFAULTS = resolveJsonlRpcPeerOptions() +const MAX_TEXT_WIRE_BYTES = PEER_DEFAULTS.maxLineBytes - 1 +// Pi before 1.5.1 sends mid-turn images unshrunk: keep each under Anthropic's 5 MB of base64 and +// the message to what one ordinary line held before. +const UNSHRUNK_IMAGE_LIMITS: ImageLimits = { + image: (5 * 1024 * 1024 * 3) / 4, + total: (PEER_DEFAULTS.maxLineBytes * 3) / 4 +} +// Pi echoes a prompt back in its events and history replies, so reads need the same room as writes. +const MAX_LINE_BYTES = + PEER_DEFAULTS.maxLineBytes + + Math.ceil(AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES / 3) * 4 + + AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT * 64 + + 1024 +export const PI_RPC_PEER_OPTIONS = { + maxLineBytes: MAX_LINE_BYTES, + maxQueuedWriteBytes: PEER_DEFAULTS.maxQueuedWriteBytes + MAX_LINE_BYTES +} satisfies JsonlRpcPeerOptions export type PiRpcPrompt = Record & { type: 'prompt' @@ -31,10 +52,6 @@ export type PiRpcPrompt = Record & { streamingBehavior?: 'steer' | 'followUp' } -type ImageReads = { - readLocal(path: string): Promise -} - export class PiRpcPromptError extends Error { constructor( message: string, @@ -52,37 +69,9 @@ function attachmentError( return new PiRpcPromptError(message, agentSessionFailureFact('attachmentInvalid', { attachment })) } -function imageMime(bytes: Uint8Array): string | null { - if ( - bytes.length >= 8 && - Buffer.from(bytes.subarray(0, 8)).equals(Buffer.from('89504e470d0a1a0a', 'hex')) - ) { - return 'image/png' - } - if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) { - return 'image/jpeg' - } - if ( - bytes.length >= 6 && - Buffer.from(bytes.subarray(0, 6)) - .toString('ascii') - .match(/^GIF8[79]a$/) - ) { - return 'image/gif' - } - if ( - bytes.length >= 12 && - Buffer.from(bytes.subarray(0, 4)).toString('ascii') === 'RIFF' && - Buffer.from(bytes.subarray(8, 12)).toString('ascii') === 'WEBP' - ) { - return 'image/webp' - } - return null -} - async function readImage( block: NativeChatImageRefBlock, - reads: ImageReads + maxBytes: number ): Promise<{ bytes: Buffer; mimeType: string }> { if (block.url) { throw attachmentError('Pi does not accept image URLs', { reason: 'unsupportedType' }) @@ -90,13 +79,13 @@ async function readImage( if (!block.path) { throw attachmentError('Pi image needs a local path', { reason: 'noSource' }) } - const mimeType = MIME_BY_EXTENSION[extname(block.path).toLowerCase()] + const mimeType = agentInlineImageMimeType(block.path) if (!mimeType) { throw attachmentError('Pi image file type is unsupported', { reason: 'unsupportedType' }) } let bytes: Buffer try { - bytes = await reads.readLocal(block.path) + bytes = await readClaudeImage(block.path, maxBytes) } catch (error) { if (error instanceof ClaudeDispatchContentError) { throw new PiRpcPromptError('Pi image could not be read', error.failure) @@ -109,13 +98,7 @@ async function readImage( if (bytes.byteLength === 0) { throw attachmentError('Pi image is empty', { reason: 'empty' }) } - if (bytes.byteLength > MAX_IMAGE_BYTES) { - throw attachmentError('Pi image exceeds the size limit', { - reason: 'tooLarge', - limit: MAX_IMAGE_BYTES - }) - } - if (imageMime(bytes) !== mimeType) { + if (detectImageFileSignature(bytes)?.mimeType !== mimeType) { throw attachmentError('Pi image file did not contain a supported image', { reason: 'unsupportedType' }) @@ -125,9 +108,9 @@ async function readImage( export async function preparePiRpcPrompt( body: AgentJournalMessageItem, - streamingBehavior?: PiRpcPrompt['streamingBehavior'], - reads: ImageReads = { readLocal: readClaudeImage } + piShrinksImages: boolean ): Promise { + const limits = piShrinksImages ? SHRUNK_IMAGE_LIMITS : UNSHRUNK_IMAGE_LIMITS if (body.role !== 'user') { throw new Error('Pi prompt must be a user message') } @@ -138,18 +121,18 @@ export async function preparePiRpcPrompt( if (block.type === 'text' && block.text.length > 0) { texts.push(block.text) } else if (block.type === 'image-ref') { - if (images.length >= MAX_IMAGE_COUNT) { + if (images.length >= AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT) { throw attachmentError('Pi prompt has too many images', { reason: 'tooMany', - limit: MAX_IMAGE_COUNT + limit: AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT }) } - const { bytes, mimeType } = await readImage(block, reads) + const { bytes, mimeType } = await readImage(block, limits.image) totalImageBytes += bytes.byteLength - if (totalImageBytes > MAX_TOTAL_IMAGE_BYTES) { + if (totalImageBytes > limits.total) { throw attachmentError('Pi images exceed the total size limit', { reason: 'totalTooLarge', - limit: MAX_TOTAL_IMAGE_BYTES + limit: limits.total }) } images.push({ type: 'image', data: bytes.toString('base64'), mimeType }) @@ -161,10 +144,10 @@ export async function preparePiRpcPrompt( const prompt: PiRpcPrompt = { type: 'prompt', message: texts.join('\n'), - images, - ...(streamingBehavior ? { streamingBehavior } : {}) + images } - if (Buffer.byteLength(JSON.stringify(prompt), 'utf8') > MAX_PROMPT_WIRE_BYTES) { + // Images are bounded by their total above; the rest of the line keeps the ordinary limit. + if (Buffer.byteLength(JSON.stringify({ ...prompt, images: [] }), 'utf8') > MAX_TEXT_WIRE_BYTES) { throw new PiRpcPromptError( 'Pi prompt exceeds the RPC write limit', agentSessionFailureFact('historyTooLarge') diff --git a/src/main/pi/rpc/rpc-message-dispatch.ts b/src/main/pi/rpc/rpc-message-dispatch.ts index c965914f39a..e340b1d775c 100644 --- a/src/main/pi/rpc/rpc-message-dispatch.ts +++ b/src/main/pi/rpc/rpc-message-dispatch.ts @@ -35,7 +35,7 @@ export async function dispatchPiRpcMessage( ): Promise { let prompt try { - prompt = await preparePiRpcPrompt(input.body) + prompt = await preparePiRpcPrompt(input.body, session.shrinksImages) } catch (error) { logger.warn('Pi prompt could not be prepared', { scope: 'pi-prompt', diff --git a/src/main/pi/rpc/rpc-session-rename.test.ts b/src/main/pi/rpc/rpc-session-rename.test.ts index f7eceff56ee..e722901dded 100644 --- a/src/main/pi/rpc/rpc-session-rename.test.ts +++ b/src/main/pi/rpc/rpc-session-rename.test.ts @@ -1,7 +1,7 @@ import { PassThrough } from 'node:stream' import { afterEach, expect, it, vi } from 'vitest' import { JsonlRpcPeer } from '../../jsonl-rpc/peer' -import { agentSessionRecordFixture } from '../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../native-chat/testing/agent-session-record-test-fixture' import { closePiRpcAdapterFixtures, file, diff --git a/src/main/pi/rpc/rpc-session.ts b/src/main/pi/rpc/rpc-session.ts index bb828645d00..7889bd913b7 100644 --- a/src/main/pi/rpc/rpc-session.ts +++ b/src/main/pi/rpc/rpc-session.ts @@ -14,6 +14,7 @@ import { import type { ProviderProcessLaunch } from '../../provider-process/provider-process-launch' import { piExitFailure } from './rpc-exit-classification' import { PiRpcTurns } from './rpc-turns' +import { PI_RPC_PEER_OPTIONS } from './prompts/rpc-prompt' import { PiRpcDialogCallbacks } from './rpc-dialog-callbacks' import { PiRpcOptionObservations, type PiRpcOptionWrite } from './options/rpc-options' import type { PiRpcResolvedLaunch } from './launch/rpc-launch-resolution' @@ -82,6 +83,10 @@ export class PiRpcSession { private readonly reading = new ReaderPauseHolds<'lane' | 'journal'>(() => this.connection) private unbindReadingControl?: () => void + get shrinksImages(): boolean { + return this.resolvedLaunch.shrinksImages === true + } + constructor( readonly input: StructuredAgentSessionAcquireInput, readonly generation: string, @@ -139,6 +144,7 @@ export class PiRpcSession { this.connection = ( deps.openConnection ?? ((spec, handlers) => new JsonlRpcAgentConnection(spec, handlers)) )(launch, { + peer: PI_RPC_PEER_OPTIONS, onRecord: (frame) => frame.type === 'extension_ui_request' ? this.dialogs.receive(frame) diff --git a/src/main/pi/transcripts/pi-session-history.ts b/src/main/pi/transcripts/pi-session-history.ts index 9e86873a799..c333d9c18e7 100644 --- a/src/main/pi/transcripts/pi-session-history.ts +++ b/src/main/pi/transcripts/pi-session-history.ts @@ -1,9 +1,9 @@ -import { sessionIdFromFileName } from '../../ai-vault/session-scanner-accumulator' +import { sessionIdFromFileName } from '../../ai-vault/parsing/session-scanner-accumulator' import { resumeInvocationFromOptions, sessionFileResumeTargetMatches, type StructuredAgentSessionHistory -} from '../../native-chat/structured-agent-cli-conversations' +} from '../../native-chat/conversation-adoption/structured-agent-cli-conversations' export const PI_SESSION_HISTORY: StructuredAgentSessionHistory = { rowAgents: ['pi'], diff --git a/src/main/pi/transcripts/pi-transcript-import.ts b/src/main/pi/transcripts/pi-transcript-import.ts index ace25d9dc76..259b4e69f7b 100644 --- a/src/main/pi/transcripts/pi-transcript-import.ts +++ b/src/main/pi/transcripts/pi-transcript-import.ts @@ -1,9 +1,9 @@ import { homedir } from 'node:os' import { join } from 'node:path' -import { sessionIdFromFileName } from '../../ai-vault/session-scanner-accumulator' -import { walkSessionFiles } from '../../ai-vault/session-scanner-discovery' -import { piSessionHistorySessionsDir } from '../../ai-vault/session-scanner-agent-sources' -import { directoryTranscriptImport } from '../../native-chat/structured-agent-cli-conversations' +import { sessionIdFromFileName } from '../../ai-vault/parsing/session-scanner-accumulator' +import { walkSessionFiles } from '../../ai-vault/discovery/session-scanner-discovery' +import { piSessionHistorySessionsDir } from '../../ai-vault/discovery/session-scanner-agent-sources' +import { directoryTranscriptImport } from '../../native-chat/conversation-adoption/structured-agent-cli-conversations' import { readPiSessionHeader } from '../rpc/launch/rpc-launch-resolution' export const PI_TRANSCRIPT_IMPORT = directoryTranscriptImport({ diff --git a/src/main/plugins/catalog/plugin-install-stats-service.ts b/src/main/plugins/catalog/plugin-install-stats-service.ts index 0d30ced5c1d..38ac8605bce 100644 --- a/src/main/plugins/catalog/plugin-install-stats-service.ts +++ b/src/main/plugins/catalog/plugin-install-stats-service.ts @@ -7,7 +7,7 @@ import { import { writePluginFileAtomically } from '../installation/plugin-atomic-file-write' import { fetchBoundedJson } from './plugin-bounded-json-fetch' -export const PLUGIN_INSTALL_STATS_URL = 'https://onorca.dev/plugins/stats.json' +export const PLUGIN_INSTALL_STATS_URL = 'https://orca.dev/plugins/stats.json' const PLUGIN_INSTALL_STATS_MAX_BYTES = 2 * 1024 * 1024 const PLUGIN_INSTALL_STATS_FETCH_TIMEOUT_MS = 30_000 // Why 6h: the file is rebuilt daily; counts are display-only, so staleness costs nothing. diff --git a/src/main/plugins/catalog/plugin-kill-list-service.ts b/src/main/plugins/catalog/plugin-kill-list-service.ts index 3693dd17ad8..18f2835974e 100644 --- a/src/main/plugins/catalog/plugin-kill-list-service.ts +++ b/src/main/plugins/catalog/plugin-kill-list-service.ts @@ -8,7 +8,7 @@ import { import { PluginKillListStore } from './plugin-kill-list-store' import { fetchBoundedJson } from './plugin-bounded-json-fetch' -export const PLUGIN_KILL_LIST_URL = 'https://onorca.dev/plugins/kill-list.json' +export const PLUGIN_KILL_LIST_URL = 'https://orca.dev/plugins/kill-list.json' const PLUGIN_KILL_LIST_DOWNLOAD_LIMIT = 4 * 1024 * 1024 // Why: revocations must reach sessions that stay open for days, not only fresh launches. export const PLUGIN_KILL_LIST_REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000 diff --git a/src/main/plugins/catalog/plugin-marketplace-projection.ts b/src/main/plugins/catalog/plugin-marketplace-projection.ts index a93bfaf3ec6..ddfbc2be436 100644 --- a/src/main/plugins/catalog/plugin-marketplace-projection.ts +++ b/src/main/plugins/catalog/plugin-marketplace-projection.ts @@ -16,6 +16,7 @@ import { type PluginHostImages } from '../../../shared/plugins/images/plugin-image-url' import type { PluginCatalogRelease } from '../../../shared/plugins/catalog/plugin-catalog-release' +import { estimatePluginAddedAt } from '../../../shared/plugins/catalog/plugin-added-at' export type PluginMarketplaceSourceState = { id: string @@ -44,6 +45,9 @@ export type PluginMarketplaceListing = { official: boolean bundled: boolean blockedByKillList?: { reason: string; advisoryUrl?: string } + /** Estimated listing date (ISO 8601): a community plugin's oldest dated release. Absent for + * official plugins and undated releases; catalogs carry no listing date of their own. */ + addedAt?: string /** The release offered to this host: the newest it can install, else the one needing the least * newer Orca. Absent for v1 catalogs. */ release?: PluginCatalogRelease @@ -137,6 +141,7 @@ export function pluginMarketplaceListing(input: { isOfficialMarketplaceGitSource(source.source.url) && snapshot.marketplace.owner.toLowerCase() === OFFICIAL_MARKETPLACE_OWNER && isOfficialOrganizationGitSource(entry.source.url) + const addedAt = estimatePluginAddedAt(entry.releases, official) return { marketplaceSourceId: source.id, marketplaceName: snapshot.marketplace.name, @@ -145,6 +150,7 @@ export function pluginMarketplaceListing(input: { pluginKey: entry.id, source: entry.source, ...(entry.description ? { description: entry.description } : {}), + ...(addedAt ? { addedAt } : {}), categories: entry.categories, official, bundled: false, diff --git a/src/main/plugins/consent/plugin-action-confirmation.ts b/src/main/plugins/consent/plugin-action-confirmation.ts new file mode 100644 index 00000000000..e15c7c2e9a0 --- /dev/null +++ b/src/main/plugins/consent/plugin-action-confirmation.ts @@ -0,0 +1,57 @@ +import { dialog, type BrowserWindow } from 'electron' +import { translateMain } from '../../i18n/main-i18n' +import type { PluginActionConfirmation } from './plugin-confirmation-subject' + +export type { PluginActionConfirmation } + +export type PluginActionConfirmationRequest = { + /** One line that names the plugin and what it wants to do. */ + message: string + detail?: string + /** The button that allows it; Cancel is the default. */ + confirmLabel: string + cancelLabel?: string + /** An "always allow" choice; its state comes back as `remember`. */ + checkboxLabel?: string +} + +/** A sheet on a hidden or minimized window would wait, unseen, forever. */ +export function canConfirmInWindow(window: BrowserWindow | null): window is BrowserWindow { + return !!window && !window.isDestroyed() && window.isVisible() && !window.isMinimized() +} + +/** + * Orca asks the person before a plugin acts on their behalf; where nobody can see the question, + * nobody is asked and the answer is `unavailable`. + */ +export async function confirmPluginAction( + window: BrowserWindow | null, + request: PluginActionConfirmationRequest, + /** Closes the question, unanswered, once whoever asked it is gone. */ + signal?: AbortSignal +): Promise<{ answer: PluginActionConfirmation; remember: boolean }> { + if (!canConfirmInWindow(window) || signal?.aborted) { + return { answer: 'unavailable', remember: false } + } + const { response, checkboxChecked } = await dialog.showMessageBox(window, { + type: 'question', + buttons: [ + request.confirmLabel, + request.cancelLabel ?? translateMain('plugins.actionConfirmation.cancel', 'Cancel') + ], + defaultId: 1, + cancelId: 1, + noLink: true, + message: request.message, + ...(request.detail ? { detail: request.detail } : {}), + ...(request.checkboxLabel ? { checkboxLabel: request.checkboxLabel } : {}), + ...(signal ? { signal } : {}) + }) + if (signal?.aborted) { + // Closed because the caller went away: nobody answered, so this is no refusal. + return { answer: 'unavailable', remember: false } + } + return response === 0 + ? { answer: 'allowed', remember: checkboxChecked } + : { answer: 'cancelled', remember: false } +} diff --git a/src/main/plugins/consent/plugin-confirmation-copy.ts b/src/main/plugins/consent/plugin-confirmation-copy.ts new file mode 100644 index 00000000000..4e484395d7a --- /dev/null +++ b/src/main/plugins/consent/plugin-confirmation-copy.ts @@ -0,0 +1,93 @@ +// @protected-copy: a plugin language pack must not reword what the person is asked to allow. +import { translateMain } from '../../i18n/main-i18n' +import type { PluginActionConfirmationRequest } from './plugin-action-confirmation' +import type { + PluginConfirmationAutomation, + PluginConfirmationSubject +} from './plugin-confirmation-subject' + +const NAME_MAX = 120 +const PROMPT_EXCERPT_MAX = 400 + +/** Long text is cut, on one line, so the question stays readable. */ +function excerpt(text: string, max: number): string { + const line = text.replace(/\s+/g, ' ').trim() + return line.length > max ? `${line.slice(0, max - 1)}…` : line +} + +/** The line that says which automation this is: its short id, where and when it runs. */ +function automationIdentity(automation: PluginConfirmationAutomation): string { + const values = { + id: automation.id.slice(0, 8), + project: + automation.project ?? + translateMain('plugins.actionConfirmation.unknownProject', 'an unknown project'), + schedule: excerpt(automation.schedule, NAME_MAX) + } + return automation.workspace === null + ? translateMain( + 'plugins.actionConfirmation.automationNewWorkspaces', + 'Automation {{id}}: a new workspace of {{project}} each run, on {{schedule}}.', + values + ) + : translateMain( + 'plugins.actionConfirmation.automationInWorkspace', + 'Automation {{id}}: in {{project}} / {{workspace}}, on {{schedule}}.', + { ...values, workspace: excerpt(automation.workspace, NAME_MAX) } + ) +} + +/** The question Orca shows for a plugin's request. */ +export function pluginConfirmationCopy( + pluginName: string, + subject: PluginConfirmationSubject +): PluginActionConfirmationRequest { + const values = { plugin: pluginName, automation: excerpt(subject.automation.name, NAME_MAX) } + const identity = automationIdentity(subject.automation) + if (subject.kind === 'automation.delete') { + return { + message: translateMain( + 'plugins.actionConfirmation.deleteAutomation', + '{{plugin}} wants to delete the automation “{{automation}}”', + values + ), + detail: [ + identity, + translateMain( + 'plugins.actionConfirmation.deleteAutomationDetail', + 'The plugin did not create it. Its schedule stops and it is removed from Automations.' + ) + ].join('\n\n'), + confirmLabel: translateMain('plugins.actionConfirmation.delete', 'Delete') + } + } + return { + message: translateMain( + 'plugins.actionConfirmation.changeAutomation', + '{{plugin}} wants to change the automation “{{automation}}”', + values + ), + detail: [ + identity, + subject.elevated + ? translateMain( + 'plugins.actionConfirmation.changeElevatedAutomationDetail', + 'It runs its agent with extra settings you chose (arguments, a permission mode or a precheck command). It would change: {{fields}}.', + { fields: subject.fields.join(', ') } + ) + : translateMain( + 'plugins.actionConfirmation.changeAutomationDetail', + 'The plugin did not create it. It would change: {{fields}}.', + { fields: subject.fields.join(', ') } + ), + subject.prompt === undefined + ? null + : translateMain('plugins.actionConfirmation.newPrompt', 'New prompt: “{{prompt}}”', { + prompt: excerpt(subject.prompt, PROMPT_EXCERPT_MAX) + }) + ] + .filter((line) => line !== null) + .join('\n\n'), + confirmLabel: translateMain('plugins.actionConfirmation.change', 'Change') + } +} diff --git a/src/main/plugins/consent/plugin-confirmation-gate.ts b/src/main/plugins/consent/plugin-confirmation-gate.ts new file mode 100644 index 00000000000..809c3a718ec --- /dev/null +++ b/src/main/plugins/consent/plugin-confirmation-gate.ts @@ -0,0 +1,40 @@ +import { PluginHostCallError } from '../workers/host-api/plugin-host-call-scope' +import type { PluginActionConfirmation } from './plugin-confirmation-subject' + +/** How long a plugin waits to ask again after the person said no. */ +export const PLUGIN_CONFIRMATION_COOLDOWN_MS = 30_000 + +/** + * One question per plugin at a time, and a pause after a refusal, so a plugin cannot stack + * dialogs or re-ask until the person gives in. Refused calls get `rate_limited`. + */ +export function createPluginConfirmationGate(now: () => number = Date.now) { + const asking = new Set() + const quietUntil = new Map() + return async function ask( + pluginId: string, + question: () => Promise + ): Promise { + if (asking.has(pluginId)) { + throw new PluginHostCallError('rate_limited', 'Orca is already asking about this plugin') + } + const wait = (quietUntil.get(pluginId) ?? 0) - now() + if (wait > 0) { + throw new PluginHostCallError( + 'rate_limited', + 'the person just declined; try again later', + wait + ) + } + asking.add(pluginId) + try { + const answer = await question() + if (answer === 'cancelled') { + quietUntil.set(pluginId, now() + PLUGIN_CONFIRMATION_COOLDOWN_MS) + } + return answer + } finally { + asking.delete(pluginId) + } + } +} diff --git a/src/main/plugins/consent/plugin-confirmation-subject.ts b/src/main/plugins/consent/plugin-confirmation-subject.ts new file mode 100644 index 00000000000..81d167be604 --- /dev/null +++ b/src/main/plugins/consent/plugin-confirmation-subject.ts @@ -0,0 +1,29 @@ +/** `unavailable`: nobody can answer (no window, or it is hidden or minimized, or headless). */ +export type PluginActionConfirmation = 'allowed' | 'cancelled' | 'unavailable' + +/** What tells one automation from another in a question: names repeat, so where and when it runs. */ +export type PluginConfirmationAutomation = { + id: string + /** As the person sees it in Automations. */ + name: string + /** Its project's name; null when Orca no longer has the project. */ + project: string | null + /** The workspace folder each run uses; null when each run creates a workspace. */ + workspace: string | null + /** Its RRULE or cron line. */ + schedule: string +} + +/** What a plugin asks the person to allow; Orca writes the question, so a plugin cannot word it. */ +export type PluginConfirmationSubject = + | { + kind: 'automation.update' + automation: PluginConfirmationAutomation + /** The fields the change touches. */ + fields: readonly ('name' | 'prompt' | 'schedule' | 'timezone' | 'enabled')[] + /** Its runs use extra agent settings the person chose (arguments, permission mode, precheck). */ + elevated?: true + /** The new prompt, when the change sets one. */ + prompt?: string + } + | { kind: 'automation.delete'; automation: PluginConfirmationAutomation } diff --git a/src/main/plugins/contributions/plugin-language-pack-registry.test.ts b/src/main/plugins/contributions/plugin-language-pack-registry.test.ts deleted file mode 100644 index 0449989ed40..00000000000 --- a/src/main/plugins/contributions/plugin-language-pack-registry.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { fingerprintPluginConsent } from '../../../shared/plugins/approval/plugin-consent-fingerprint' -import { pluginManifestSchema } from '../../../shared/plugins/manifest/plugin-manifest' -import { PluginContentVerifier } from '../plugin-content-integrity' -import type { ValidDiscoveredPlugin } from '../plugin-discovery' -import { PluginLanguagePackRegistry } from './plugin-language-pack-registry' - -const roots: string[] = [] - -async function pluginWithCatalog(catalog: unknown): Promise { - const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-language-registry-')) - roots.push(rootDir) - await mkdir(join(rootDir, 'locales')) - await writeFile(join(rootDir, 'locales', 'pt-BR.json'), JSON.stringify(catalog)) - const manifest = pluginManifestSchema.parse({ - manifestVersion: 1, - id: 'portuguese', - publisher: 'samples', - name: 'Portuguese', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - contributes: { - languagePacks: [{ locale: 'pt-BR', path: 'locales/pt-BR.json' }] - }, - capabilities: [] - }) - return { - pluginKey: 'samples.portuguese', - rootDir, - manifest, - consentFingerprint: fingerprintPluginConsent(manifest), - contentHash: null, - isDev: true - } -} - -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('PluginLanguagePackRegistry', () => { - it('loads a pack that covers protected security copy, leaving that copy in English', async () => { - const plugin = await pluginWithCatalog({ - common: { save: 'Sávé' }, - auto: { components: { settings: { PluginConsentDialog: { disclaimer: 'Safe' } } } } - }) - const registry = new PluginLanguagePackRegistry(new PluginContentVerifier()) - - await registry.reconcile([plugin], () => true) - expect(registry.error(plugin.pluginKey)).toBeNull() - expect(registry.list()[0]?.catalog).toEqual({ - common: { save: 'Sávé' }, - auto: { components: { settings: {} } } - }) - }) -}) diff --git a/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts b/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts index c22eb8f301a..33aa5a09bc7 100644 --- a/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts +++ b/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts @@ -12,7 +12,7 @@ import { setPluginHookRunner } from './plugin-hook-dispatch' const { resumeCheck } = vi.hoisted(() => ({ resumeCheck: vi.fn<(command: string, ensureHost: () => Promise) => Promise>() })) -vi.mock('../../ai-vault/structured-session-ownership', () => ({ +vi.mock('../../ai-vault/structured-sessions/structured-session-ownership', () => ({ assertLegacyAiVaultResumeCommandAllowed: resumeCheck })) diff --git a/src/main/plugins/installation/plugin-installation-state.ts b/src/main/plugins/installation/plugin-installation-state.ts index 23eda7d2bac..88629c23e28 100644 --- a/src/main/plugins/installation/plugin-installation-state.ts +++ b/src/main/plugins/installation/plugin-installation-state.ts @@ -5,6 +5,7 @@ import { } from '../plugin-discovery' import { readPluginLockfile } from './plugin-install' import { PluginLogBuffer, type PluginLogLine } from '../plugin-log-buffer' +import { notifyPluginRemoved } from './plugin-removal-events' export class PluginInstallationState { discovered: DiscoveredPlugin[] = [] @@ -49,6 +50,7 @@ export class PluginInstallationState { await remove() this.logs.clear(pluginKey) this.discovered = this.discovered.filter((entry) => entry !== plugin) + notifyPluginRemoved(pluginKey) this.options.notifyChanged() } finally { this.removing = null diff --git a/src/main/plugins/installation/plugin-removal-events.ts b/src/main/plugins/installation/plugin-removal-events.ts new file mode 100644 index 00000000000..aee4575a7b1 --- /dev/null +++ b/src/main/plugins/installation/plugin-removal-events.ts @@ -0,0 +1,14 @@ +const listeners = new Set<(pluginKey: string) => void>() + +/** Hears each plugin the person uninstalls, as it is removed; returns an unsubscribe. */ +export function onPluginRemoved(listener: (pluginKey: string) => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +/** Told only by the uninstall path: a plugin missing from a discovery is not removed. */ +export function notifyPluginRemoved(pluginKey: string): void { + for (const listener of listeners) { + listener(pluginKey) + } +} diff --git a/src/main/plugins/panels/desktop-actions/plugin-external-open-consent.ts b/src/main/plugins/panels/desktop-actions/plugin-external-open-consent.ts index 174d650df9a..f12966eaef9 100644 --- a/src/main/plugins/panels/desktop-actions/plugin-external-open-consent.ts +++ b/src/main/plugins/panels/desktop-actions/plugin-external-open-consent.ts @@ -1,6 +1,12 @@ -import { dialog, type BrowserWindow } from 'electron' +// @protected-copy: a plugin language pack must not reword what the person is asked to allow. +import type { BrowserWindow } from 'electron' import type { Store } from '../../../persistence/loading-store/store' import { translateMain } from '../../../i18n/main-i18n' +import { + canConfirmInWindow, + confirmPluginAction, + type PluginActionConfirmation +} from '../../consent/plugin-action-confirmation' type GrantStore = Pick @@ -17,7 +23,7 @@ function rememberHost(store: GrantStore, pluginId: string, host: string): void { store.updateSettings({ pluginExternalHostGrants: grants }) } -export type PluginExternalOpenConsent = 'allowed' | 'cancelled' | 'unavailable' +export type PluginExternalOpenConsent = PluginActionConfirmation export function truncatedUrl(url: string): string { return url.length > URL_DETAIL_MAX_LENGTH ? `${url.slice(0, URL_DETAIL_MAX_LENGTH - 1)}…` : url @@ -45,8 +51,7 @@ export async function confirmPluginExternalOpen(input: { input.admit?.() return 'allowed' } - // A sheet on a hidden or minimized window would wait, unseen, forever. - if (input.window.isDestroyed() || !input.window.isVisible() || input.window.isMinimized()) { + if (!canConfirmInWindow(input.window)) { input.log?.( `shell.openExternal(${host}): not opened; Orca's window is hidden, so nobody can confirm it` ) @@ -54,15 +59,9 @@ export async function confirmPluginExternalOpen(input: { } input.admit?.() input.log?.(`shell.openExternal(${host}): waiting for the person to confirm`) - const { response, checkboxChecked } = await dialog.showMessageBox(input.window, { - type: 'question', - buttons: [ - translateMain('plugins.frameOpenExternal.open', 'Open'), - translateMain('plugins.frameOpenExternal.cancel', 'Cancel') - ], - defaultId: 1, - cancelId: 1, - noLink: true, + const { answer, remember } = await confirmPluginAction(input.window, { + confirmLabel: translateMain('plugins.frameOpenExternal.open', 'Open'), + cancelLabel: translateMain('plugins.frameOpenExternal.cancel', 'Cancel'), message: translateMain( 'plugins.frameOpenExternal.message', '{{plugin}} wants to open {{host}}', @@ -78,10 +77,10 @@ export async function confirmPluginExternalOpen(input: { { host } ) }) - if (response !== 0) { - return 'cancelled' + if (answer !== 'allowed') { + return answer } - if (checkboxChecked) { + if (remember) { rememberHost(input.store, input.pluginId, host) } return 'allowed' diff --git a/src/main/plugins/panels/desktop-actions/plugin-frame-desktop-services.ts b/src/main/plugins/panels/desktop-actions/plugin-frame-desktop-services.ts index 3d46e798412..9f89180a18f 100644 --- a/src/main/plugins/panels/desktop-actions/plugin-frame-desktop-services.ts +++ b/src/main/plugins/panels/desktop-actions/plugin-frame-desktop-services.ts @@ -12,6 +12,9 @@ import { } from '../../workers/host-api/plugin-host-call-scope' import { markPluginSavedFileAsDownloaded } from './plugin-save-as-download-mark' import { confirmPluginExternalOpen } from './plugin-external-open-consent' +import { canConfirmInWindow, confirmPluginAction } from '../../consent/plugin-action-confirmation' +import { createPluginConfirmationGate } from '../../consent/plugin-confirmation-gate' +import { pluginConfirmationCopy } from '../../consent/plugin-confirmation-copy' import type { Store } from '../../../persistence/loading-store/store' import { translateMain } from '../../../i18n/main-i18n' import { blockedPluginSaveAsExtension } from '../../../../shared/plugins/frames/plugin-save-as-extensions' @@ -27,6 +30,7 @@ const DESKTOP_FRAME_RATE_LIMIT = { const hostWindows = new Set() const budgets = new Map() let services: PluginDesktopFrameServices | null = null +const askOnce = createPluginConfirmationGate() /** Null in headless serve and before a main window exists: the methods then fail. */ export function getPluginDesktopFrameServices(): PluginDesktopFrameServices | null { @@ -46,6 +50,16 @@ function callingWindow(scope: PluginHostCallScope): BrowserWindow { return window } +/** Where a host confirmation shows: the calling frame's window; for workers, Orca's focused + * main window, else the first one the person can see. */ +function confirmationWindow(scope: PluginHostCallScope): BrowserWindow | null { + if (scope.callerWebContentsId !== undefined) { + return callingWindow(scope) + } + const windows = [...hostWindows].filter((window) => !window.isDestroyed()) + return windows.find((window) => window.isFocused()) ?? windows.find(canConfirmInWindow) ?? null +} + function admit(window: BrowserWindow, pluginId: string): void { const key = `${window.id}\0${pluginId}` let budget = budgets.get(key) @@ -80,6 +94,24 @@ export function installPluginDesktopFrameServices( return } services = { + async confirm(pluginId, subject, scope) { + const window = confirmationWindow(scope) + if (!canConfirmInWindow(window)) { + return 'unavailable' + } + return askOnce(pluginId, async () => { + admit(window, pluginId) + // A worker that exits or cancels the call closes its question, freeing the plugin's turn. + const { answer } = await confirmPluginAction( + window, + pluginConfirmationCopy(scope.pluginName ?? pluginId, subject), + scope.signal + ) + // The question may have stayed open while the plugin was disabled or removed. + scope.assertActive() + return answer + }) + }, async openExternal(pluginId, url, scope) { // Re-checked here: the shared schema already refused other schemes, but this is the sink. if (!isPluginExternalUrl(url)) { diff --git a/src/main/plugins/panels/desktop-actions/plugin-host-confirmation.test.ts b/src/main/plugins/panels/desktop-actions/plugin-host-confirmation.test.ts new file mode 100644 index 00000000000..56404f6816d --- /dev/null +++ b/src/main/plugins/panels/desktop-actions/plugin-host-confirmation.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest' + +const showMessageBox = vi.hoisted(() => vi.fn()) +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp' }, + shell: {}, + dialog: { showMessageBox }, + webContents: { fromId: () => undefined }, + BrowserWindow: { fromWebContents: () => null } +})) +vi.mock('../../../i18n/main-i18n', () => ({ + translateMain: (_key: string, fallback: string) => fallback +})) + +const { installPluginDesktopFrameServices, getPluginDesktopFrameServices } = + await import('./plugin-frame-desktop-services') + +function fakeWindow(id: number, shown: { visible: boolean; focused: boolean }) { + return { + id, + once: vi.fn(), + isDestroyed: () => false, + isVisible: () => shown.visible, + isMinimized: () => false, + isFocused: () => shown.focused + } +} + +const scope = { assertActive: vi.fn(), pluginName: 'Demo' } +const subject = { + kind: 'automation.delete' as const, + automation: { + id: 'a1', + name: 'Nightly', + project: 'App', + workspace: null, + schedule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0' + } +} + +describe('host confirmations for workers', () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only these window members. + const hidden = fakeWindow(1, { visible: false, focused: false }) as never + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. + const shown = fakeWindow(2, { visible: true, focused: false }) as never + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: confirmations never read settings. + const store = { getSettings: () => ({}), updateSettings: vi.fn() } as never + installPluginDesktopFrameServices(hidden, store) + installPluginDesktopFrameServices(shown, store) + const services = getPluginDesktopFrameServices()! + + it("close a question whose worker went away, so the plugin's next one is not refused", async () => { + const worker = new AbortController() + showMessageBox.mockImplementationOnce( + (_window: unknown, options: { signal: AbortSignal }) => + new Promise((resolve) => + options.signal.addEventListener('abort', () => resolve({ response: 1 })) + ) + ) + const pending = services.confirm('acme.four', subject, { ...scope, signal: worker.signal }) + worker.abort() + // Nobody answered: no refusal, and no wait before the next question. + await expect(pending).resolves.toBe('unavailable') + showMessageBox.mockResolvedValueOnce({ response: 0 }) + await expect(services.confirm('acme.four', subject, scope)).resolves.toBe('allowed') + }) +}) diff --git a/src/main/plugins/panels/guest-isolation/plugin-frame-guest-policies.ts b/src/main/plugins/panels/guest-isolation/plugin-frame-guest-policies.ts index dc179bd4e16..777ef91c478 100644 --- a/src/main/plugins/panels/guest-isolation/plugin-frame-guest-policies.ts +++ b/src/main/plugins/panels/guest-isolation/plugin-frame-guest-policies.ts @@ -2,7 +2,7 @@ import { BrowserWindow, Menu, webContents as electronWebContents } from 'electro import type { Session, WebContents } from 'electron' import type { KeybindingOverrides } from '../../../../shared/keybindings' import { setupGuestShortcutForwarding } from '../../../browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding' -import { buildEditableContextMenuTemplate } from '../../../window/editable-context-menu' +import { buildEditableContextMenuTemplate } from '../../../window/editing/editable-context-menu' import { isAllowedPluginFrameNavigation } from './plugin-frame-request-policy' /** `did-attach-webview`: per-guest fences the session cannot express, plus Orca's own input. */ diff --git a/src/main/plugins/panels/plugin-panel-bridge-replay.test.ts b/src/main/plugins/panels/plugin-panel-bridge-replay.test.ts index e0b99308b84..1ceb3539012 100644 --- a/src/main/plugins/panels/plugin-panel-bridge-replay.test.ts +++ b/src/main/plugins/panels/plugin-panel-bridge-replay.test.ts @@ -30,7 +30,12 @@ function setup(capabilities: PluginCapabilityKind[] = ['workspace:read']) { return { bridge, unfocus: () => (active = null) } } -const context = { branch: 'main', displayName: 'w', terminals: [{ id: 'term_a', title: 'zsh' }] } +// The raw id (`repo::/w`) embeds a path, so panels never get it. +const context = { + branch: 'main', + displayName: 'w', + terminals: [{ id: 'term_a', title: 'zsh' }] +} describe('workspace.changed replay on subscribe', () => { it('gives a panel the current context as soon as it subscribes', async () => { diff --git a/src/main/plugins/panels/plugin-panel-bridge.ts b/src/main/plugins/panels/plugin-panel-bridge.ts index 91763d15e10..165d4395790 100644 --- a/src/main/plugins/panels/plugin-panel-bridge.ts +++ b/src/main/plugins/panels/plugin-panel-bridge.ts @@ -30,6 +30,10 @@ import type { PluginWorkerHandle } from '../workers/parent-process/plugin-host-p import { PluginHostCallError } from '../workers/host-api/plugin-host-call-scope' import type { PluginRuntimeDelegate } from '../workers/host-api/plugin-host-service-bindings' import { readPluginWorkspaceChange } from '../plugin-runtime-binding' +import { + pluginFrameEventPayload, + pluginFrameWorkspaceContext +} from '../workers/host-api/plugin-workspace-projection' type PushChannel = { pluginKey: string @@ -125,7 +129,8 @@ export class PluginPanelBridge { } this.replays.delete(panelId) for (const event of owed) { - const payload = (await readPluginWorkspaceChange(delegate)).change + const { context } = (await readPluginWorkspaceChange(delegate)).change + const payload = { context: pluginFrameWorkspaceContext(context) } if ( this.channels.get(panelId) === channel && this.subscriptions.get(panelId)?.has(event) && @@ -213,7 +218,7 @@ export class PluginPanelBridge { if (!projected.success) { return 0 } - const payload = projected.data + const payload = pluginFrameEventPayload(event, projected.data) let delivered = 0 for (const [panelId, channel] of this.channels) { if ( diff --git a/src/main/plugins/plugin-agent-status-event.ts b/src/main/plugins/plugin-agent-status-event.ts index 26280c8b958..b063422e182 100644 --- a/src/main/plugins/plugin-agent-status-event.ts +++ b/src/main/plugins/plugin-agent-status-event.ts @@ -1,19 +1,35 @@ import type { EnrichedAgentHookEventPayload } from '../agent-hooks/server/server-types' import type { PluginAgentStatusChangedPayload } from '../../shared/plugins/events/plugin-events' +import type { WorktreeMetaIdentitySource } from '../persistence/worktree-meta-host-identity' +import { pluginAgentWorkspaceListId } from './plugin-event-workspace-id' +import { pluginAgentSessionId } from './workers/host-api/plugin-workspace-projection' -/** Exclude restored rows from live automation triggers; optional mainAgent preserves old-host compatibility. */ +/** Exclude restored rows from live automation triggers; optional mainAgent preserves old-host compatibility. + * `store` names each worktree by the id `workspace.list` gives it. */ export function projectPluginAgentStatusChangedPayload( enriched: Pick< EnrichedAgentHookEventPayload, - 'worktreeId' | 'paneKey' | 'receivedAt' | 'restoredUnconfirmed' | 'payload' - > + | 'worktreeId' + | 'connectionId' + | 'paneKey' + | 'receivedAt' + | 'restoredUnconfirmed' + | 'payload' + | 'providerSession' + >, + store: WorktreeMetaIdentitySource | null | undefined ): PluginAgentStatusChangedPayload | null { if (enriched.restoredUnconfirmed) { return null } const mainAgent = enriched.payload.mainAgent + const sessionId = pluginAgentSessionId(enriched.providerSession) + const listId = enriched.worktreeId + ? pluginAgentWorkspaceListId(store, enriched.worktreeId, enriched.connectionId) + : undefined return { workspaceId: enriched.worktreeId ?? null, + ...(listId ? { workspaceListId: listId } : {}), paneKey: enriched.paneKey, state: enriched.payload.state, receivedAt: enriched.receivedAt, @@ -25,6 +41,7 @@ export function projectPluginAgentStatusChangedPayload( stateStartedAt: mainAgent.stateStartedAt } } - : {}) + : {}), + ...(sessionId ? { sessionId } : {}) } } diff --git a/src/main/plugins/plugin-authoring-checks.ts b/src/main/plugins/plugin-authoring-checks.ts deleted file mode 100644 index fbdcaeb6d28..00000000000 --- a/src/main/plugins/plugin-authoring-checks.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** The main-process plugin checks `orca plugin validate|inspect|release-entry` runs. One CLI entry so the - * packaged CLI loads them after electron-vite replaces out/main; keep it free of Electron. */ -export { - validateDeclaredPluginArtifacts, - validatePluginInstallContent -} from './plugin-artifact-validation' -export { hashPluginTree } from './plugin-content-hash' -export { - pluginCatalogReleaseForHead, - type PluginCatalogReleaseReport -} from './plugin-catalog-release-entry' diff --git a/src/main/plugins/plugin-automation-ownership.test.ts b/src/main/plugins/plugin-automation-ownership.test.ts new file mode 100644 index 00000000000..8e2fd82f418 --- /dev/null +++ b/src/main/plugins/plugin-automation-ownership.test.ts @@ -0,0 +1,102 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import type { Automation } from '../../shared/automations/automation-definition' +import { installPluginAutomationOwnershipEnd } from './plugin-automation-ownership' +import { PluginService } from './plugin-service' + +vi.mock('electron', () => ({ ipcMain: { handle() {}, on() {} } })) + +function automation(id: string, pluginKey: string, createdAt = 1): Automation { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sweep reads only id, createdAt and createdBy. + return { + id, + enabled: true, + createdAt, + createdBy: { kind: 'plugin', pluginKey, name: pluginKey } + } as Automation +} + +function automationStore(initial: Automation[]) { + let stored = initial + const updateAutomations = vi.fn( + async (entries: readonly { id: string; updates: Partial }[]) => { + const patches = new Map(entries.map(({ id, updates }) => [id, updates])) + stored = stored.map((entry) => ({ ...entry, ...patches.get(entry.id) })) + return entries.map(({ id }) => ({ id, automation: stored.find((entry) => entry.id === id)! })) + } + ) + return { + source: { listAutomationsForScope: () => ({ automations: stored }), updateAutomations }, + updateAutomations, + get: (id: string) => stored.find((entry) => entry.id === id) + } +} + +// The sweep settles within a few microtasks; nothing in it waits on time. +const settle = () => new Promise((resolve) => setImmediate(resolve)) + +describe('automations of a plugin the person took away', () => { + it('never ends ownership because discovery could not read the plugins folder', async () => { + const userData = await mkdtemp(join(tmpdir(), 'orca-plugin-ownership-')) + // A file where the plugins folder belongs: every discovery fails to list it. + await writeFile(join(userData, 'plugins'), '') + const service = new PluginService({ + userDataPath: userData, + hostVersion: '1.4.0', + isPluginSystemEnabled: () => true, + getDisabledPlugins: () => [], + getPluginConsents: () => ({}), + getDevPluginPaths: () => [], + hostEntryPath: 'inert-worker-entry' + }) + const store = automationStore([automation('a-installed', 'acme.installed')]) + try { + installPluginAutomationOwnershipEnd(service, store.source) + await service.initialize() + await service.refresh() + await settle() + expect(service.getDiscovered()).toEqual([]) + expect(store.updateAutomations).not.toHaveBeenCalled() + expect(store.get('a-installed')).toMatchObject({ enabled: true }) + } finally { + await service.dispose() + await rm(userData, { recursive: true, force: true }) + } + }) + + it('pauses every automation of a disabled plugin in one write', async () => { + const store = automationStore([ + automation('a-1', 'acme.gone'), + automation('a-2', 'acme.gone'), + automation('a-3', 'acme.gone'), + automation('b-1', 'acme.kept') + ]) + installPluginAutomationOwnershipEnd( + { + options: { + isPluginSystemEnabled: () => true, + getDisabledPlugins: () => ['acme.gone'] + }, + whenReady: () => Promise.resolve(), + onChanged: () => () => {} + }, + store.source + ) + await settle() + expect(store.updateAutomations).toHaveBeenCalledTimes(1) + expect(store.updateAutomations.mock.calls[0][0].map(({ id }) => id)).toEqual([ + 'a-1', + 'a-2', + 'a-3' + ]) + for (const id of ['a-1', 'a-2', 'a-3']) { + expect(store.get(id)).toMatchObject({ + enabled: false, + createdBy: { endedAt: expect.any(Number) } + }) + } + expect(store.get('b-1')).toMatchObject({ enabled: true }) + }) +}) diff --git a/src/main/plugins/plugin-automation-ownership.ts b/src/main/plugins/plugin-automation-ownership.ts new file mode 100644 index 00000000000..82744e78174 --- /dev/null +++ b/src/main/plugins/plugin-automation-ownership.ts @@ -0,0 +1,119 @@ +import type { + Automation, + AutomationUpdateInput +} from '../../shared/automations/automation-definition' +import type { PluginServiceOptions } from './plugin-service-options' +import { onPluginRemoved } from './installation/plugin-removal-events' + +type PluginStateSource = { + options: Pick< + PluginServiceOptions, + 'isPluginSystemEnabled' | 'getDisabledPlugins' | 'getPluginKillListEntry' + > + whenReady(): Promise + onChanged(listener: () => void): () => void +} + +type AutomationSource = { + listAutomationsForScope(params: Record): { automations: readonly Automation[] } + updateAutomations( + entries: readonly { + id: string + updates: Pick + }[] + ): Promise +} + +/** + * Whether the person took the plugin away from this automation: uninstalled it after creating it + * (`removedAt`), disabled it or all plugins, or Orca blocked it. Only these settings and the + * uninstall itself count; a plugin missing from a discovery (an unreadable folder, a failed scan) + * keeps its automations. + */ +export function pluginOwnershipEnded( + options: PluginStateSource['options'], + removedAt: ReadonlyMap, + automation: Pick & { createdBy: { pluginKey: string } } +): boolean { + const pluginKey = automation.createdBy.pluginKey + return ( + automation.createdAt <= (removedAt.get(pluginKey) ?? -Infinity) || + !options.isPluginSystemEnabled() || + options.getDisabledPlugins().includes(pluginKey) || + options.getPluginKillListEntry?.(pluginKey) != null + ) +} + +/** + * Pauses the automations of a plugin the person uninstalled or disabled, or Orca blocked, and ends + * its ownership, so neither re-enabling it nor a later install under the same key resumes or edits + * them without the person. Sweeps only once the plugin service has loaded. + */ +export function installPluginAutomationOwnershipEnd( + service: PluginStateSource, + automations: AutomationSource, + log: (message: string) => void = console.warn +): () => void { + // Why times: an install under the same key after the removal owns what it creates. + const removedAt = new Map() + let ready = false + let running = false + let again = false + const sweep = async (): Promise => { + if (!ready || running) { + again = running + return + } + running = true + try { + do { + again = false + const ended = automations.listAutomationsForScope({}).automations.filter( + (automation) => + automation.createdBy?.kind === 'plugin' && + automation.createdBy.endedAt === undefined && + pluginOwnershipEnded(service.options, removedAt, { + createdAt: automation.createdAt, + createdBy: automation.createdBy + }) + ) + if (ended.length === 0) { + continue + } + const endedAt = Date.now() + // Why one batch: per-row updates rewrite and persist the whole list once per automation. + const results = await automations + .updateAutomations( + ended.map((automation) => ({ + id: automation.id, + updates: { + enabled: false, + ...(automation.createdBy ? { createdBy: { ...automation.createdBy, endedAt } } : {}) + } + })) + ) + .catch((error: unknown) => ended.map(({ id }) => ({ id, error }))) + for (const result of results) { + if ('error' in result) { + log(`[plugins] could not pause automation ${result.id}: ${String(result.error)}`) + } + } + } while (again) + } finally { + running = false + } + } + const stopChanges = service.onChanged(() => void sweep()) + const stopRemovals = onPluginRemoved((pluginKey) => { + removedAt.set(pluginKey, Date.now()) + void sweep() + }) + void service.whenReady().then(() => { + ready = true + void sweep() + }) + return () => { + stopChanges() + stopRemovals() + } +} diff --git a/src/main/plugins/plugin-cli-approval.ts b/src/main/plugins/plugin-cli-approval.ts index 75432c8a273..312439ab6b5 100644 --- a/src/main/plugins/plugin-cli-approval.ts +++ b/src/main/plugins/plugin-cli-approval.ts @@ -7,7 +7,7 @@ import { type PluginApprovalAction } from '../../shared/plugins/approval/plugin-cli-approval' import type { PluginConsentRequest } from '../../shared/plugins/approval/plugin-consent-request' -import type { RpcCallerIdentity } from '../runtime/rpc/rpc-caller-identity' +import type { RpcCallerIdentity } from '../runtime/rpc/callers/rpc-caller-identity' import type { PluginAuditEntry } from './plugin-audit-log' import type { ValidDiscoveredPlugin } from './plugin-discovery' diff --git a/src/main/plugins/plugin-cli-install.integration.test.ts b/src/main/plugins/plugin-cli-install.integration.test.ts index dd6244a493d..b09bb1301e1 100644 --- a/src/main/plugins/plugin-cli-install.integration.test.ts +++ b/src/main/plugins/plugin-cli-install.integration.test.ts @@ -292,7 +292,7 @@ describe('orca plugin install and update over Git', () => { const catalog = join(root, 'catalog') const moved = join(root, 'moved-locale') await mkdir(catalog, { recursive: true }) - await git(catalog, ['init', '--quiet']) + await git(catalog, ['init', '--quiet', '--initial-branch=master']) const listCatalog = (url: string, tag: string) => commitTag( catalog, diff --git a/src/main/plugins/plugin-cli-install.ts b/src/main/plugins/plugin-cli-install.ts index 2ca58ef58b6..2de0e396f18 100644 --- a/src/main/plugins/plugin-cli-install.ts +++ b/src/main/plugins/plugin-cli-install.ts @@ -14,7 +14,7 @@ import { import { parsePluginGitInstallInput } from '../../shared/plugins/installation/plugin-git-install-input' import type { PluginInstallSourceInfo } from '../../shared/plugins/installation/plugin-install-source-info' import type { PluginInstallSource } from '../../shared/plugins/installation/plugin-install-lockfile' -import type { RpcCallerIdentity } from '../runtime/rpc/rpc-caller-identity' +import type { RpcCallerIdentity } from '../runtime/rpc/callers/rpc-caller-identity' import type { PluginPolicySource } from './plugin-activation-policy' import { installCatalogReleaseWithApproval, diff --git a/src/main/plugins/plugin-dev-folders.ts b/src/main/plugins/plugin-dev-folders.ts index f6885448e9b..e453ac906aa 100644 --- a/src/main/plugins/plugin-dev-folders.ts +++ b/src/main/plugins/plugin-dev-folders.ts @@ -8,7 +8,7 @@ import { PluginCliError } from '../../shared/plugins/approval/plugin-cli-approval' import type { PluginConsentRequest } from '../../shared/plugins/approval/plugin-consent-request' -import type { RpcCallerIdentity } from '../runtime/rpc/rpc-caller-identity' +import type { RpcCallerIdentity } from '../runtime/rpc/callers/rpc-caller-identity' import { approvePluginFromCli, type PluginCliApprovalOutcome, diff --git a/src/main/plugins/plugin-event-workspace-id.ts b/src/main/plugins/plugin-event-workspace-id.ts new file mode 100644 index 00000000000..6097e371149 --- /dev/null +++ b/src/main/plugins/plugin-event-workspace-id.ts @@ -0,0 +1,24 @@ +import { getConnectionExecutionHostId } from '../../shared/execution-host' +import { parseWorkspaceKey } from '../../shared/workspace-scope' +import { + worktreeHostIdentity, + type WorktreeMetaIdentitySource +} from '../persistence/worktree-meta-host-identity' +import { pluginListedWorkspaceId } from './workers/host-api/plugin-workspace-projection' + +/** + * The `workspaceListId` of an agent's workspace: the id `workspace.list` gives it. The identity + * comes from the metadata row of the host the agent reported from (`connectionId`: an SSH host, + * else this machine), never another host's same-id row; without one the raw id stands. + */ +export function pluginAgentWorkspaceListId( + store: WorktreeMetaIdentitySource | null | undefined, + worktreeId: string, + connectionId: string | null | undefined +): string | undefined { + const { identityKey } = + parseWorkspaceKey(worktreeId)?.type === 'folder' + ? {} + : worktreeHostIdentity(store, worktreeId, getConnectionExecutionHostId(connectionId)) + return pluginListedWorkspaceId({ id: worktreeId, identityKey }) +} diff --git a/src/main/plugins/plugin-host-call-revocation.test.ts b/src/main/plugins/plugin-host-call-revocation.test.ts index 1f534fedaec..644fae2d29c 100644 --- a/src/main/plugins/plugin-host-call-revocation.test.ts +++ b/src/main/plugins/plugin-host-call-revocation.test.ts @@ -36,6 +36,7 @@ async function createSavingPlugin() { const dialog = gate() const writes: string[] = [] const desktop: PluginDesktopFrameServices = { + confirm: async () => 'allowed', openExternal: async () => ({ opened: true }), async saveFile(pluginId, _input, scope) { await dialog.opened diff --git a/src/main/plugins/plugin-runtime-binding.test.ts b/src/main/plugins/plugin-runtime-binding.test.ts index 101c0b4696d..f86dcd06357 100644 --- a/src/main/plugins/plugin-runtime-binding.test.ts +++ b/src/main/plugins/plugin-runtime-binding.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { createPluginAgentStatusForwarder, pluginRuntimeDelegate } from './plugin-runtime-binding' import { PluginPanelBridge } from './panels/plugin-panel-bridge' +import type { AgentStatusOrchestrationContext } from '../../shared/agent-status/contracts/agent-status-types' import type { ValidDiscoveredPlugin } from './plugin-discovery' const LEAF = '11111111-1111-4111-8111-111111111111' @@ -22,7 +23,23 @@ function runtime(terminals: { handle: string; title: string | null; paneTitle?: })) })), sendTerminal: vi.fn(), - dispatchPluginNotification: vi.fn() + dispatchPluginNotification: vi.fn(), + listAgentTasksByPaneKey: vi.fn((): Record => ({ + 'tab0:worker': { + taskId: 't-1', + dispatchId: 'd-1', + dispatchStatus: 'dispatched', + taskTitle: 'Write the tests', + coordinatorHandle: 'h' + }, + 'tab0:untitled': { taskId: 't-2', dispatchId: 'd-2' }, + 'tab0:finished': { + taskId: 't-3', + dispatchId: 'd-3', + dispatchStatus: 'completed', + taskTitle: 'Done' + } + })) } } diff --git a/src/main/plugins/plugin-runtime-binding.ts b/src/main/plugins/plugin-runtime-binding.ts index 8ca87949ae7..166fc869d5d 100644 --- a/src/main/plugins/plugin-runtime-binding.ts +++ b/src/main/plugins/plugin-runtime-binding.ts @@ -1,15 +1,18 @@ import type { PluginEventName } from '../../shared/plugins/manifest/plugin-manifest' +import type { AgentStatusOrchestrationContext } from '../../shared/agent-status/contracts/agent-status-types' import { savedWorkspaceCatalog } from '../persistence/profile-save-domains' import type { PluginAgentStatusChangedPayload } from '../../shared/plugins/events/plugin-events' import { PLUGIN_WORKSPACE_TERMINAL_LIMIT } from '../../shared/plugins/workers/plugin-host-api' import type { PluginRuntimeDelegate } from './workers/host-api/plugin-host-service-bindings' import type { PluginService } from './plugin-service' import { installPluginHookRunner } from './hooks/plugin-hook-participants' +import { installPluginOpenedTerminalPruning } from './workers/host-api/plugin-opened-terminals' +import { installPluginAutomationOwnershipEnd } from './plugin-automation-ownership' import { installPluginResidentWorkerWarmer } from './workers/worker-admission/plugin-resident-worker' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { pluginRuntimeRpc } from './plugin-runtime-rpc' import type { DispatcherOptions } from '../runtime/rpc/dispatcher' -import type { PluginRuntimeRpc } from './workers/host-api/plugin-host-workspace-method-bindings' +import type { PluginRuntimeRpc } from './workers/host-api/plugin-host-runtime-call' import { pluginTerminalTitle, projectPluginWorkspaceContext, @@ -25,7 +28,46 @@ type PluginEvents = { wantsEvent(event: PluginEventName): boolean } -type RuntimeDelegateSource = Omit +type RuntimeDelegateSource = Omit< + PluginRuntimeDelegate, + 'listAgentStatuses' | 'listAgentTaskTitles' | 'callRuntime' +> & { + listAgentTasksByPaneKey(): Readonly> +} + +type PluginAgentTask = Pick + +const TASK_TITLES_TTL_MS = 1000 +// A dispatch that ended leaves its pane, which then runs no task. +const ENDED_DISPATCH: ReadonlySet = new Set([ + 'completed', + 'failed', + 'circuit_broken' +]) + +/** + * Each pane's active dispatched task title, by pane key: only that it runs one and its title, + * never the dispatch's records. Kept for a second, since building it reads the orchestration + * database and plugins may poll `agents.list`. + */ +function pluginAgentTaskTitles( + read: () => Readonly> +): () => ReadonlyMap { + let last: { at: number; titles: ReadonlyMap } | null = null + return () => { + const now = Date.now() + if (last && now - last.at < TASK_TITLES_TTL_MS) { + return last.titles + } + const titles = new Map( + Object.entries(read()).flatMap(([paneKey, task]) => + ENDED_DISPATCH.has(task.dispatchStatus) ? [] : [[paneKey, task.taskTitle ?? ''] as const] + ) + ) + last = { at: now, titles } + return titles + } +} const WORKSPACE_CHANGE_DEBOUNCE_MS = 150 @@ -41,7 +83,8 @@ export function pluginRuntimeDelegate( listTerminals: (...args) => runtime.listTerminals(...args), sendTerminal: (...args) => runtime.sendTerminal(...args), dispatchPluginNotification: (input) => runtime.dispatchPluginNotification(input), - listAgentStatuses: agentStatuses + listAgentStatuses: agentStatuses, + listAgentTaskTitles: pluginAgentTaskTitles(() => runtime.listAgentTasksByPaneKey()) } } @@ -56,6 +99,8 @@ export function bindPluginRuntime( const delegate = pluginRuntimeDelegate(runtime, statuses, pluginRuntimeRpc(runtime, methods)) service.setRuntimeDelegate(delegate) installPluginHookRunner(service, runtime) + installPluginOpenedTerminalPruning(service) + installPluginAutomationOwnershipEnd(service, runtime) installPluginResidentWorkerWarmer(service) return delegate } diff --git a/src/main/plugins/plugin-runtime-rpc.ts b/src/main/plugins/plugin-runtime-rpc.ts index bd2c1fa0b05..2d11096120b 100644 --- a/src/main/plugins/plugin-runtime-rpc.ts +++ b/src/main/plugins/plugin-runtime-rpc.ts @@ -1,15 +1,17 @@ import { randomUUID } from 'node:crypto' import { RpcDispatcher, type DispatcherOptions } from '../runtime/rpc/dispatcher' import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { PluginRuntimeRpc } from './workers/host-api/plugin-host-workspace-method-bindings' +import type { PluginRuntimeRpc } from './workers/host-api/plugin-host-runtime-call' -/** An error the runtime answered, with its code (`selector_not_found`, ...). */ +/** An error the runtime answered, with its code (`selector_not_found`, ...); `cause` is what the + * handler threw, for callers that tell refusals apart by class. */ export class PluginRuntimeRpcError extends Error { constructor( readonly code: string, - message: string + message: string, + options?: ErrorOptions ) { - super(message) + super(message, options) } } @@ -26,11 +28,15 @@ export function pluginRuntimeRpc( dispatcher ??= new RpcDispatcher({ runtime, methods }) // The dispatcher maps a throw to an error answer; keep the original so its code reaches the plugin. let refusal: unknown = null + let thrown: unknown const response = await dispatcher.dispatch( { id: randomUUID(), authToken: 'plugin-host', method, params }, { // Why the CLI's identity: a mod's action is automation, as an agent's `orca` call is. caller: { kind: 'local-cli' }, + ...(options.plugin + ? { plugin: { ...options.plugin, assertActive: () => options.beforeEffect?.() } } + : {}), ...(options.signal ? { signal: options.signal } : {}), beforeInvoke: () => { try { @@ -40,6 +46,9 @@ export function pluginRuntimeRpc( refusal = error throw error } + }, + onHandlerError: (error) => { + thrown = error } } ) @@ -47,7 +56,11 @@ export function pluginRuntimeRpc( throw refusal } if (!response.ok) { - throw new PluginRuntimeRpcError(response.error.code, response.error.message) + throw new PluginRuntimeRpcError( + response.error.code, + response.error.message, + thrown === undefined ? undefined : { cause: thrown } + ) } return response.result } diff --git a/src/main/plugins/plugin-service-host-call.ts b/src/main/plugins/plugin-service-host-call.ts index eb51cdea860..7844dab8557 100644 --- a/src/main/plugins/plugin-service-host-call.ts +++ b/src/main/plugins/plugin-service-host-call.ts @@ -81,6 +81,7 @@ export function resolvePluginServiceHostCallPolicy(input: { const plugin = input.findApprovedPlugin(input.pluginKey) return { grantedCapabilities: plugin ? capabilityKinds(plugin.manifest.capabilities) : null, + allowProposed: plugin?.isDev === true, services: input.runtimeDelegate ? bindPluginHostServices({ delegate: input.runtimeDelegate, diff --git a/src/main/plugins/view/plugin-view-desktop.ts b/src/main/plugins/view/plugin-view-desktop.ts index 43013399cd7..4aab56bf37b 100644 --- a/src/main/plugins/view/plugin-view-desktop.ts +++ b/src/main/plugins/view/plugin-view-desktop.ts @@ -5,7 +5,7 @@ import type { PluginShotChromeParams, PluginShotEditorParams, PluginShotReplayParams -} from '../../../shared/rpc-contract/plugins-params' +} from '../../../shared/rpc-contract/plugins/plugins-params' import { PLUGIN_VIEW_NO_WORKSPACE_CODE, PLUGIN_VIEW_NOT_SHOWN_CODE, diff --git a/src/main/plugins/view/plugin-view-replay-shot.ts b/src/main/plugins/view/plugin-view-replay-shot.ts index 67085a04eee..622dca29aa6 100644 --- a/src/main/plugins/view/plugin-view-replay-shot.ts +++ b/src/main/plugins/view/plugin-view-replay-shot.ts @@ -2,7 +2,7 @@ import type { WebContents } from 'electron' import type { z } from 'zod' import { PluginCliError } from '../../../shared/plugins/approval/plugin-cli-approval' import { parsePluginDeclarativeTree } from '../../../shared/plugins/declarative/plugin-declarative-tree' -import type { PluginShotReplayParams } from '../../../shared/rpc-contract/plugins-params' +import type { PluginShotReplayParams } from '../../../shared/rpc-contract/plugins/plugins-params' import { capturePluginPanelPng, withPaintingWhileHidden } from './plugin-view-capture' import { requestPluginViewFromRenderer } from './plugin-view-renderer-relay' import { pluginShotReplayRefusal } from './plugin-shot-policy' diff --git a/src/main/plugins/workers/child-runtime/plugin-host-runtime.ts b/src/main/plugins/workers/child-runtime/plugin-host-runtime.ts index 38ab6b318c8..986dff235e2 100644 --- a/src/main/plugins/workers/child-runtime/plugin-host-runtime.ts +++ b/src/main/plugins/workers/child-runtime/plugin-host-runtime.ts @@ -148,7 +148,8 @@ export function createPluginWorkerRuntime( hostCall: (method, params, callOptions) => hostCall(method, params, callOptions?.signal), postToPanels: (post) => send(pluginEvent(WORKER_EVENTS.panelPost, post)), log: (message) => send(pluginWorkerLog('info', message)), - grantedCapabilities: input.grantedCapabilities + grantedCapabilities: input.grantedCapabilities, + allowProposed: input.allowProposed === true }) await activate(orca) send(pluginEvent(WORKER_EVENTS.ready, { commands: [...commandHandlers.keys()] })) diff --git a/src/main/plugins/workers/host-api/__mocks__/plugin-host-services-fixture.ts b/src/main/plugins/workers/host-api/__mocks__/plugin-host-services-fixture.ts new file mode 100644 index 00000000000..ef958f72182 --- /dev/null +++ b/src/main/plugins/workers/host-api/__mocks__/plugin-host-services-fixture.ts @@ -0,0 +1,48 @@ +import { vi } from 'vitest' +import type { PluginCapabilityKind } from '../../../../../shared/plugins/capabilities/plugin-capabilities' +import { executePluginHostCall } from '../plugin-host-methods' +import type { PluginHostServices } from '../plugin-host-method-bindings' +import type { PluginAuditLog } from '../../../plugin-audit-log' + +/** Host services with inert stores and the given runtime RPC; `overrides` replaces any of them. */ +export function pluginHostTestServices( + runtimeRpc: PluginHostServices['runtimeRpc'], + overrides: Partial = {} +): PluginHostServices { + return { + resolveActiveWorktreeContext: vi.fn().mockResolvedValue(null), + listWorktreeTerminals: vi.fn().mockResolvedValue([]), + sendTerminalText: vi.fn().mockResolvedValue({ accepted: true }), + listAgentStatuses: () => [], + dispatchPluginNotification: vi.fn().mockResolvedValue({ delivered: true }), + storage: { get: vi.fn(), set: vi.fn(), delete: vi.fn(), keys: vi.fn().mockReturnValue([]) }, + secrets: { + get: vi.fn().mockReturnValue({ ok: true, value: null }), + set: vi.fn().mockReturnValue({ ok: true }), + delete: vi.fn(), + protection: vi.fn().mockReturnValue('unavailable') + }, + settings: { getAll: vi.fn().mockReturnValue({}), set: vi.fn().mockReturnValue({ ok: true }) }, + runtimeRpc, + ...overrides + } +} + +/** A worker's call through the one chokepoint every transport uses, with an audit sink. */ +export function callPluginHost(input: { + method: string + params: unknown + granted: PluginCapabilityKind[] + services: PluginHostServices + audit?: Pick +}) { + return executePluginHostCall({ + pluginId: 'samples.demo', + method: input.method, + params: input.params, + surface: 'worker', + grantedCapabilities: input.granted, + services: input.services, + audit: input.audit ?? { record: vi.fn().mockResolvedValue(undefined) } + }) +} diff --git a/src/main/plugins/workers/host-api/plugin-agent-history.ts b/src/main/plugins/workers/host-api/plugin-agent-history.ts new file mode 100644 index 00000000000..4941f449cd2 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-agent-history.ts @@ -0,0 +1,278 @@ +import { z } from 'zod' +import { + aiVaultSessionInScope, + createAiVaultScopeCwdMatcher +} from '../../../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import { PLUGIN_AGENT_SESSION_LIST_LIMIT } from '../../../../shared/plugins/workers/plugin-host-api-agent-history' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { aiVaultSessionListCacheGeneration } from '../../../ai-vault/listing/cached-session-list' +import { resolveAiVaultScopeRealPaths } from '../../../ai-vault/scope/session-scope-real-paths' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' + +/** + * The parts of an Agent Session History row the plugin host reads. Previews, prompts and the + * account home stay behind; `filePath` and `codexHome` stay in main, for resume preparation only. + */ +const historyRow = z.object({ + agent: z.string(), + sessionId: z.string(), + title: z.string(), + cwd: z.string().nullable(), + cwdAliases: z.array(z.string()).optional(), + branch: z.string().nullable(), + filePath: z.string(), + codexHome: z.string().nullable(), + executionHostId: z.string(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), + modifiedAt: z.string(), + messageCount: z.number(), + totalTokens: z.number(), + subagent: z.unknown().nullable().optional() +}) +const historyAnswer = z.object({ + sessions: z.array(z.unknown()), + fingerprint: z.string().optional(), + unchanged: z.literal(true).optional() +}) + +export type PluginHistorySession = { + agent: string + sessionId: string + title: string + cwd: string | null + cwdAliases?: string[] + branch: string | null + filePath: string + codexHome: string | null + hostId: string + createdAt: number | null + updatedAt: number + messageCount: number + totalTokens: number +} + +export type PluginHistoryRead = { + /** Newest first. */ + sessions: readonly PluginHistorySession[] + /** The read may have stopped at a vault budget, so older sessions may exist that it lacks. */ + depthReached: boolean +} + +function epochMs(value: string | null): number | null { + const ms = value === null ? Number.NaN : Date.parse(value) + return Number.isFinite(ms) ? ms : null +} + +function count(value: number): number { + return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0 +} + +function toHistorySession(raw: unknown): PluginHistorySession | null { + const parsed = historyRow.safeParse(raw) + // Subagent transcripts belong to their parent session, which is the one a plugin resumes. + if (!parsed.success || parsed.data.subagent) { + return null + } + const row = parsed.data + return { + agent: row.agent, + sessionId: row.sessionId, + title: row.title, + cwd: row.cwd, + ...(row.cwdAliases ? { cwdAliases: row.cwdAliases } : {}), + branch: row.branch, + filePath: row.filePath, + codexHome: row.codexHome, + hostId: row.executionHostId, + createdAt: epochMs(row.createdAt), + updatedAt: epochMs(row.updatedAt) ?? epochMs(row.modifiedAt) ?? 0, + messageCount: count(row.messageCount), + totalTokens: count(row.totalTokens) + } +} + +/** How long a read answers every plugin before the next call revalidates it. */ +export const PLUGIN_HISTORY_TTL_MS = 30_000 +const MAX_CACHED_SCOPES = 16 + +type ReadState = { settledAt: number | null; fingerprint?: string; generation: number } +type CachedRead = { read: Promise; state: ReadState } +// Why shared and keyed by scope: every plugin sees the same history, and each read scans transcript +// folders. Plugins polling together share one read in flight and its answer for the TTL; after it, +// the vault's fingerprint tells whether the rows changed, so an unchanged history is not re-parsed. +// Keyed by the runtime RPC the reads went through. +const reads = new WeakMap>() + +async function readHistory( + call: PluginRuntimeRpc, + scopePath: string | null, + previous: { fingerprint: string; value: PluginHistoryRead } | null +): Promise<{ value: PluginHistoryRead; fingerprint?: string }> { + const answer = historyAnswer.parse( + await call('aiVault.listSessions', { + // One depth for every caller, so all plugins share the vault's cached scan. + limit: PLUGIN_AGENT_SESSION_LIST_LIMIT, + ...(scopePath ? { scopePaths: [scopePath], scopeOnly: true } : {}), + // Null asks for this answer's fingerprint, which the next read revalidates with. + afterFingerprint: previous?.fingerprint ?? null + }) + ) + if (answer.unchanged && previous && answer.fingerprint === previous.fingerprint) { + return { value: previous.value, fingerprint: previous.fingerprint } + } + if (answer.unchanged) { + // A reply about some other body cannot stand in for rows this host no longer holds. + return readHistory(call, scopePath, null) + } + const sessions = answer.sessions + .map(toHistorySession) + .filter((row): row is PluginHistorySession => row !== null) + .toSorted((a, b) => b.updatedAt - a.updatedAt) + return { + value: { + sessions, + // The vault reports no truncation. An unscoped read keeps the newest 200; a scoped one has + // per-source budgets (200 sessions per walked agent, 400 files per cwd-bucketed one), so + // 200 or more rows means some source may have stopped at its budget. + depthReached: answer.sessions.length >= PLUGIN_AGENT_SESSION_LIST_LIMIT + }, + ...(answer.fingerprint ? { fingerprint: answer.fingerprint } : {}) + } +} + +function startRead( + call: PluginRuntimeRpc, + scopePath: string | null, + stale: CachedRead | undefined +): CachedRead { + // A delete (or anything else that invalidates the vault's list) voids reads from before it. + const generation = aiVaultSessionListCacheGeneration() + const state: ReadState = { settledAt: null, generation } + const read = (async () => { + const reusable = stale?.state.generation === generation ? stale : undefined + const fingerprint = reusable?.state.fingerprint + // The stale read has settled: it is past its TTL. + const value = reusable && fingerprint ? await reusable.read.catch(() => null) : null + const result = await readHistory( + call, + scopePath, + fingerprint && value ? { fingerprint, value } : null + ) + state.fingerprint = result.fingerprint + state.settledAt = Date.now() + return result.value + })() + return { read, state } +} + +/** + * This computer's Agent Session History, all of it (`scopePath` null) or one folder's. `owner` is + * the runtime RPC `call` wraps, which keys the shared reads. + */ +export function pluginAgentHistory( + call: PluginRuntimeRpc, + owner: PluginRuntimeRpc, + scopePath: string | null +): Promise { + let scopes = reads.get(owner) + if (!scopes) { + scopes = new Map() + reads.set(owner, scopes) + } + const key = scopePath ?? '' + const cached = scopes.get(key) + if ( + cached && + cached.state.generation === aiVaultSessionListCacheGeneration() && + (cached.state.settledAt === null || Date.now() - cached.state.settledAt < PLUGIN_HISTORY_TTL_MS) + ) { + return cached.read + } + const entry = startRead(call, scopePath, cached) + scopes.delete(key) + scopes.set(key, entry) + // Bounded: the scope read longest ago goes first. + for (const oldest of scopes.keys()) { + if (scopes.size <= MAX_CACHED_SCOPES) { + break + } + scopes.delete(oldest) + } + const owned = scopes + entry.read.catch(() => { + // A failed read is not kept: the next call asks again. + if (owned.get(key) === entry) { + owned.delete(key) + } + }) + return entry.read +} + +/** A workspace a session may have run in: its public id, host and folder. */ +export type PluginHistoryWorkspace = { id: string; hostId: string | null; path: string } + +/** Whether a workspace row lives on this computer, where its history is read. */ +export function isLocalHistoryWorkspace(row: Pick): boolean { + return row.hostId === null || row.hostId === LOCAL_EXECUTION_HOST_ID +} + +const REAL_PATH_TTL_MS = PLUGIN_HISTORY_TTL_MS +const REAL_PATH_MAX_ENTRIES = 2048 +const realPaths = new Map() + +/** + * A folder's spellings a session's cwd may carry: the registered path and, behind a symlink, the + * resolved one, which agents record. A scoped vault read adds the same alias, so a session maps + * to the same workspace whether it was read by scope or not. + */ +async function workspaceScopePaths(path: string): Promise { + const cached = realPaths.get(path) + if (cached && Date.now() - cached.at < REAL_PATH_TTL_MS) { + return cached.paths + } + const { scanScopePaths } = await resolveAiVaultScopeRealPaths([path]) + if (realPaths.size >= REAL_PATH_MAX_ENTRIES) { + realPaths.clear() + } + realPaths.set(path, { paths: scanScopePaths, at: Date.now() }) + return scanScopePaths +} + +/** + * The workspace each session ran in: the deepest of this computer's workspaces holding its + * folder (by its resolved path behind a symlink), so a worktree nested in its project's folder claims its own sessions; between two of + * equal depth, a project's workspace before a project-group folder of the same path. SSH and + * runtime hosts' workspaces never match: a same-named folder there is another machine's. + */ +export async function pluginHistoryWorkspaceMatcher( + workspaces: readonly PluginHistoryWorkspace[] +): Promise< + ( + session: Pick + ) => string | null +> { + const local = workspaces.filter(isLocalHistoryWorkspace) + const candidates = ( + await Promise.all( + local.map(async (row) => { + const paths = await workspaceScopePaths(row.path) + return { + id: row.id, + // Behind a symlink, its resolved folder counts: that is the spelling sessions record. + depth: Math.max(...paths.map((path) => normalizeRuntimePathForComparison(path).length)), + folder: parseWorkspaceKey(row.id)?.type === 'folder', + inScope: createAiVaultScopeCwdMatcher(paths) + } + }) + ) + ).toSorted((a, b) => b.depth - a.depth || Number(a.folder) - Number(b.folder)) + return (session) => { + if (session.hostId !== LOCAL_EXECUTION_HOST_ID) { + return null + } + return candidates.find((row) => aiVaultSessionInScope(row.inScope, session))?.id ?? null + } +} diff --git a/src/main/plugins/workers/host-api/plugin-automation-confirmation.ts b/src/main/plugins/workers/host-api/plugin-automation-confirmation.ts new file mode 100644 index 00000000000..2b34057a919 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-automation-confirmation.ts @@ -0,0 +1,82 @@ +import { z } from 'zod' +import { suggestionPathBasename } from '../../../../shared/worktree-name-suggestion' +import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' +import type { PluginHostMethodContext } from './plugin-host-method-bind' +import { pluginHostRpc as rpc } from './plugin-host-runtime-call' +import { + automationAnswer, + pluginOwnsAutomation, + type PluginAutomationRecord +} from './plugin-automation-projection' +import type { + PluginConfirmationAutomation, + PluginConfirmationSubject +} from '../../consent/plugin-confirmation-subject' + +const automationShowAnswer = z.object({ automation: automationAnswer }) +const repoListAnswer = z.object({ + repos: z.array(z.object({ id: z.string(), displayName: z.string().optional() })) +}) + +export type PluginAutomationRefusal = { reason: 'cancelled' | 'consent-unavailable' | 'changed' } + +/** What a question asks; Orca adds which automation it is about. */ +export type PluginAutomationQuestion = DistributiveOmit +type DistributiveOmit = T extends unknown ? Omit : never + +async function showAutomation( + ctx: PluginHostMethodContext, + automationId: string +): Promise { + return automationShowAnswer.parse( + await rpc(ctx.services)('automation.show', { id: automationId }) + ).automation +} + +/** Which automation this is, as the person can tell it apart from one with the same name. */ +async function confirmationIdentity( + ctx: PluginHostMethodContext, + automation: PluginAutomationRecord +): Promise { + const projectId = automation.runContext?.repoId ?? automation.projectId + const { repos } = repoListAnswer.parse(await rpc(ctx.services)('repo.list', {})) + const workspacePath = + automation.workspaceMode === 'existing' && automation.workspaceId + ? (splitWorktreeIdForFilesystem(automation.workspaceId)?.worktreePath ?? + automation.workspaceId) + : null + return { + id: automation.id, + name: automation.name, + project: repos.find((repo) => repo.id === projectId)?.displayName || null, + workspace: workspacePath === null ? null : suggestionPathBasename(workspacePath), + schedule: automation.rrule + } +} + +/** + * Null when the plugin may go ahead: `question` asks nothing, or the person allowed it and the + * automation is still what they were shown. Headless serve cannot ask. + */ +export async function pluginAutomationRefusal( + ctx: PluginHostMethodContext, + automationId: string, + question: (current: PluginAutomationRecord, own: boolean) => PluginAutomationQuestion | null +): Promise { + const shown = await showAutomation(ctx, automationId) + const asked = question(shown, pluginOwnsAutomation(shown, ctx.pluginId)) + if (!asked) { + return null + } + if (!ctx.services.confirm) { + return { reason: 'consent-unavailable' } + } + const automation = await confirmationIdentity(ctx, shown) + const answer = await ctx.services.confirm(ctx.pluginId, { ...asked, automation }, ctx.scope) + if (answer !== 'allowed') { + return { reason: answer === 'cancelled' ? 'cancelled' : 'consent-unavailable' } + } + // The person answered about the record they saw; one edited meanwhile is another question. + const now = await showAutomation(ctx, automationId).catch(() => null) + return now?.updatedAt === shown.updatedAt ? null : { reason: 'changed' } +} diff --git a/src/main/plugins/workers/host-api/plugin-automation-projection.ts b/src/main/plugins/workers/host-api/plugin-automation-projection.ts new file mode 100644 index 00000000000..2ae6df805e2 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-automation-projection.ts @@ -0,0 +1,111 @@ +import { z } from 'zod' +import type { PluginHostResult } from '../../../../shared/plugins/workers/plugin-host-api' +import { + PLUGIN_HOST_ID_MAX_LENGTH, + PLUGIN_HOST_TEXT_MAX_LENGTH +} from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { + PLUGIN_AUTOMATION_LIST_LIMIT, + PLUGIN_AUTOMATION_SCHEDULE_MAX +} from '../../../../shared/plugins/workers/plugin-host-api-automation-methods' + +/** The parts of a stored automation plugins may read; the rest (precheck, agent arguments, + * launch setup, setup trust, owner) never reaches them. */ +export const automationAnswer = z.object({ + id: z.string(), + name: z.string(), + prompt: z.string(), + agentId: z.string(), + projectId: z.string(), + runContext: z + .object({ repoId: z.string().optional(), hostId: z.string().optional() }) + .nullable() + .optional(), + workspaceMode: z.enum(['existing', 'new_per_run']), + workspaceId: z.string().nullable(), + rrule: z.string(), + timezone: z.string(), + enabled: z.boolean(), + nextRunAt: z.number(), + /** Moves with every write: a question is about the record at this revision. */ + updatedAt: z.number().optional(), + lastRunAt: z.number().optional(), + createdBy: z + .object({ + kind: z.string(), + pluginKey: z.string().optional(), + endedAt: z.number().optional() + }) + .optional(), + // Read only to tell whether runs use extra agent settings; never projected. + precheck: z.object({ command: z.string() }).nullable().optional(), + agentArgs: z.string().nullable().optional(), + extraAgentArgs: z.string().optional(), + launchPreferences: z.record(z.string(), z.unknown()).optional() +}) +export type PluginAutomationRecord = z.output + +/** The plugin created it and still owns it: its removal or disabling ends that. */ +export function pluginOwnsAutomation( + automation: PluginAutomationRecord, + pluginId: string +): boolean { + const creator = automation.createdBy + return ( + creator?.kind === 'plugin' && creator.pluginKey === pluginId && creator.endedAt === undefined + ) +} + +/** Runs start the agent with more than the person's defaults: arguments, launch choices such as a + * permission mode, or a precheck command. Only the person can set these. */ +export function automationRunsElevated(automation: PluginAutomationRecord): boolean { + return Boolean( + automation.precheck || + automation.agentArgs || + automation.extraAgentArgs?.trim() || + Object.keys(automation.launchPreferences ?? {}).length > 0 + ) +} + +/** An id as it is, or null when it is empty or too long for the field: never cut, never failing. */ +function fittingId(id: string | null | undefined): string | null { + return id && id.length <= PLUGIN_HOST_ID_MAX_LENGTH ? id : null +} + +/** `automation.list`: rows as plugins see them; `workspaceIds` maps raw worktree ids to listed ones. */ +export function projectPluginAutomations( + automations: readonly PluginAutomationRecord[], + pluginId: string, + workspaceIds: ReadonlyMap +): PluginHostResult<'automation.list'> { + return { + automations: automations.slice(0, PLUGIN_AUTOMATION_LIST_LIMIT).map((automation) => { + const raw = automation.workspaceMode === 'existing' ? automation.workspaceId : null + // A workspace `workspace.list` no longer lists keeps its raw id, when that fits the field. + const workspaceId = raw ? (workspaceIds.get(raw) ?? fittingId(raw)) : null + return { + id: automation.id, + name: automation.name.slice(0, 512), + agent: automation.agentId.slice(0, 64), + prompt: automation.prompt.slice(0, PLUGIN_HOST_TEXT_MAX_LENGTH), + promptTruncated: automation.prompt.length > PLUGIN_HOST_TEXT_MAX_LENGTH, + projectId: fittingId(automation.runContext?.repoId ?? automation.projectId), + hostId: fittingId(automation.runContext?.hostId), + workspaceId, + workspaceMode: + automation.workspaceMode === 'new_per_run' + ? ('new-per-run' as const) + : ('existing' as const), + // Never cut: a partial RRULE or cron line would read as another schedule. + schedule: + automation.rrule.length <= PLUGIN_AUTOMATION_SCHEDULE_MAX ? automation.rrule : null, + timezone: automation.timezone.slice(0, 64), + enabled: automation.enabled, + nextRunAt: automation.enabled ? automation.nextRunAt : null, + lastRunAt: automation.lastRunAt ?? null, + createdByThisPlugin: pluginOwnsAutomation(automation, pluginId) + } + }), + truncated: automations.length > PLUGIN_AUTOMATION_LIST_LIMIT + } +} diff --git a/src/main/plugins/workers/host-api/plugin-host-agent-history-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-agent-history-bindings.ts new file mode 100644 index 00000000000..8a5a6eb13b7 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-agent-history-bindings.ts @@ -0,0 +1,159 @@ +import { z } from 'zod' +import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' +import { + PLUGIN_AGENT_SESSION_LIST_DEFAULT, + PLUGIN_AGENT_SESSION_TITLE_MAX +} from '../../../../shared/plugins/workers/plugin-host-api-agent-history' +import { pluginAgentSessionIdSchema } from '../../../../shared/plugins/workers/plugin-host-api-panel-methods' +import { pluginWorkspaceId } from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import { + aiVaultHistoryAgents, + isAiVaultAgent +} from '../../../../shared/ai-vault/contracts/ai-vault-types' +import { + bind, + type BoundPluginHostMethod, + type PluginHostMethodContext +} from './plugin-host-method-bind' +import { PluginHostCallError } from './plugin-host-call-scope' +import { + pluginHostRpc as rpc, + pluginWorkspaceSelector as workspaceSelector +} from './plugin-host-runtime-call' +import { listPluginWorkspaces } from './plugin-host-workspace-list' +import { + isLocalHistoryWorkspace, + pluginAgentHistory, + pluginHistoryWorkspaceMatcher, + type PluginHistorySession, + type PluginHistoryWorkspace +} from './plugin-agent-history' +import type { PluginAgentStatusRow } from './plugin-workspace-projection' + +const worktreeShowAnswer = z.object({ + worktree: z.object({ id: z.string(), identity: z.object({ key: z.string() }).optional() }) +}) + +/** One line, at most the public bound: a title can be the start of a multi-line first message. */ +function sessionTitle(title: string): string { + return title.replace(/\s+/g, ' ').trim().slice(0, PLUGIN_AGENT_SESSION_TITLE_MAX) +} + +/** The workspace `workspaceId` names, as `workspace.list` lists it, in either id form. */ +async function namedWorkspace( + ctx: PluginHostMethodContext, + workspaces: readonly PluginHistoryWorkspace[], + workspaceId: string +): Promise { + const listed = workspaces.find((row) => row.id === workspaceId) + if (listed) { + return listed + } + // A raw id of a workspace `workspace.list` names by its identity. + const { worktree } = worktreeShowAnswer.parse( + await rpc(ctx.services)('worktree.show', { + worktree: workspaceSelector(workspaceId), + matchFolderWorkspaces: true + }) + ) + const id = pluginWorkspaceId({ id: worktree.id, identityKey: worktree.identity?.key }) + const shown = workspaces.find((row) => row.id === id) + if (!shown) { + throw new PluginHostCallError('action_failed', 'no workspace has this id') + } + return shown +} + +/** The sessions Orca panes on this computer run now, by agent and session id. */ +function runningSessions(rows: readonly PluginAgentStatusRow[]): Set { + return new Set( + rows + .filter((row) => row.providerSessionOnly !== true && !row.connectionId && row.providerSession) + .map((row) => `${row.agentType ?? ''}\0${row.providerSession?.id ?? ''}`) + ) +} + +/** One OpenCode store holds both versions' sessions, which panes and history may label apart. */ +function isRunning(session: PluginHistorySession, running: ReadonlySet): boolean { + const agents = isAiVaultAgent(session.agent) + ? aiVaultHistoryAgents(session.agent) + : [session.agent] + return agents.some((agent) => running.has(`${agent}\0${session.sessionId}`)) +} + +function publicSession( + session: PluginHistorySession, + workspaceId: string | null, + running: ReadonlySet +) { + return { + sessionId: session.sessionId, + agent: session.agent.slice(0, 128), + title: sessionTitle(session.title), + workspaceId, + hostId: session.hostId, + branch: session.branch?.replace(/^refs\/heads\//, '').slice(0, 512) || null, + createdAt: session.createdAt, + updatedAt: session.updatedAt, + messageCount: session.messageCount, + totalTokens: session.totalTokens, + running: isRunning(session, running) + } +} + +export const PLUGIN_AGENT_HISTORY_HANDLERS = { + 'agent.listSessions': bind(PLUGIN_HOST_API['agent.listSessions'], async (params, ctx) => { + const call = rpc(ctx.services) + const limit = params?.limit ?? PLUGIN_AGENT_SESSION_LIST_DEFAULT + const { workspaces } = await listPluginWorkspaces(call, false) + const scope = params?.workspaceId + ? await namedWorkspace(ctx, workspaces, params.workspaceId) + : null + // Orca reads only this computer's history; another host's workspace has none here. + if (scope && !isLocalHistoryWorkspace(scope)) { + return { sessions: [], truncated: false } + } + const owner = ctx.services.runtimeRpc ?? call + const history = await pluginAgentHistory(call, owner, scope?.path ?? null) + const workspaceOf = await pluginHistoryWorkspaceMatcher(workspaces) + const running = runningSessions(ctx.services.listAgentStatuses()) + const matching = history.sessions + .filter((session) => pluginAgentSessionIdSchema.safeParse(session.sessionId).success) + .map((session) => ({ session, workspaceId: workspaceOf(session) })) + // A folder holds the worktrees nested in it; their sessions are theirs. + .filter((row) => !scope || row.workspaceId === scope.id) + return { + sessions: matching + .slice(0, limit) + .map(({ session, workspaceId }) => publicSession(session, workspaceId, running)), + truncated: matching.length > limit || history.depthReached + } + }) +} satisfies Record + +/** + * The history row `agent.resume` prepares for a session no Orca pane runs: the workspace's own + * sessions first, then this computer's newest. Null when the history lists none, or the workspace + * is on another host. + */ +export async function findPluginPastSession( + ctx: PluginHostMethodContext, + match: { agents: readonly string[]; sessionId: string; workspacePath: string | null } +): Promise { + const call = rpc(ctx.services) + const owner = ctx.services.runtimeRpc ?? call + for (const scopePath of match.workspacePath ? [match.workspacePath, null] : [null]) { + const { sessions } = await pluginAgentHistory(call, owner, scopePath) + const found = sessions.find( + (session) => + session.hostId === LOCAL_EXECUTION_HOST_ID && + session.sessionId === match.sessionId && + match.agents.includes(session.agent) + ) + if (found) { + return found + } + } + return null +} diff --git a/src/main/plugins/workers/host-api/plugin-host-agent-history.test.ts b/src/main/plugins/workers/host-api/plugin-host-agent-history.test.ts new file mode 100644 index 00000000000..de9d4994056 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-agent-history.test.ts @@ -0,0 +1,131 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import type { PluginCapabilityKind } from '../../../../shared/plugins/capabilities/plugin-capabilities' +import { callPluginHost, pluginHostTestServices } from './__mocks__/plugin-host-services-fixture' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' +import type { PluginHostServices } from './plugin-host-method-bindings' + +const WORKTREES = { + worktrees: [ + // A project's own folder, with a worktree nested inside it. + { id: 'r1::/src/r1', repoId: 'r1', displayName: 'r1', path: '/src/r1', hostId: 'local' }, + { + id: 'r1::/src/r1/.worktrees/seal', + repoId: 'r1', + displayName: 'seal', + path: '/src/r1/.worktrees/seal', + hostId: 'local', + identity: { key: 'wt2:local:seal' } + }, + // The same path on an SSH machine is another computer's folder. + { id: 'r2::/src/r1', repoId: 'r2', displayName: 'remote', path: '/src/r1', hostId: 'ssh:box' } + ] +} +const FOLDERS = { + folderWorkspaces: [{ id: 'notes', name: 'Notes', folderPath: '/notes', executionHostId: null }] +} + +function vaultRow(overrides: Record = {}) { + return { + id: 'row', + executionHostId: 'local', + agent: 'claude', + sessionId: 's-1', + title: 'Fix the login\n page', + cwd: '/src/r1/.worktrees/seal/app', + branch: 'refs/heads/seal', + model: 'opus', + filePath: '/home/me/.claude/projects/x/s-1.jsonl', + codexHome: null, + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-02T00:00:00.000Z', + modifiedAt: '2026-01-02T00:00:00.000Z', + messageCount: 12, + totalTokens: 3400, + previewMessages: [{ role: 'user', text: 'secret prompt', timestamp: null }], + firstUserPrompt: 'secret prompt', + lastUserPrompt: 'another secret', + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: 'claude --resume s-1', + subagent: null, + ...overrides + } +} + +function runtime(answers: Record = {}) { + const all: Record = { + 'worktree.list': WORKTREES, + 'repo.list': { + repos: [ + { id: 'r1', kind: 'git' }, + { id: 'r2', connectionId: 'box' } + ] + }, + 'folderWorkspace.list': FOLDERS, + 'aiVault.listSessions': { + sessions: [vaultRow()], + issues: [], + scannedAt: 'x', + fingerprint: 'f1' + }, + ...answers + } + return vi.fn(async (method, params) => { + const answer = all[method] + if (answer instanceof Error) { + throw answer + } + return typeof answer === 'function' ? answer(params) : answer + }) +} + +const listSessions = ( + rpc: PluginRuntimeRpc, + params: unknown = {}, + overrides: Partial = {}, + granted: PluginCapabilityKind[] = ['history:read'] +) => + callPluginHost({ + method: 'agent.listSessions', + params, + granted, + services: pluginHostTestServices(rpc, overrides) + }) + +describe('agent.listSessions', () => { + it('ranks a symlinked workspace by its resolved folder', async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-history-'))) + try { + const deep = join(root, 'project', 'deep', 'worktree') + mkdirSync(deep, { recursive: true }) + const link = join(root, 'l') + symlinkSync(deep, link, process.platform === 'win32' ? 'junction' : 'dir') + const project = join(root, 'project') + const rpc = runtime({ + 'worktree.list': { + worktrees: [ + { + id: `r1::${project}`, + repoId: 'r1', + displayName: 'p', + path: project, + hostId: 'local' + }, + { id: `r1::${link}`, repoId: 'r1', displayName: 'l', path: link, hostId: 'local' } + ] + }, + 'folderWorkspace.list': { folderWorkspaces: [] }, + 'aiVault.listSessions': { sessions: [vaultRow({ cwd: deep })], issues: [], scannedAt: 'x' } + }) + const outcome = await listSessions(rpc) + expect(outcome.ok && outcome.value).toMatchObject({ + sessions: [{ workspaceId: `r1::${link}` }] + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/plugins/workers/host-api/plugin-host-agent-resume-binding.ts b/src/main/plugins/workers/host-api/plugin-host-agent-resume-binding.ts new file mode 100644 index 00000000000..e171a79210a --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-agent-resume-binding.ts @@ -0,0 +1,93 @@ +import { z } from 'zod' +import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' +import { pluginResumeKey } from '../../../../shared/plugins/workers/plugin-agent-resume-key' +import { + getConnectionExecutionHostId, + LOCAL_EXECUTION_HOST_ID +} from '../../../../shared/execution-host' +import { bind, type BoundPluginHostMethod } from './plugin-host-method-bind' +import { preparePluginPastSession, resumableTranscript } from './plugin-past-session-resume' +import { + pluginHostEffect as effect, + pluginHostRpc as rpc, + pluginWorkspaceSelector as workspaceSelector +} from './plugin-host-runtime-call' +import { recordPluginOpenedTerminal } from './plugin-opened-terminals' +import type { PluginAgentStatusRow } from './plugin-workspace-projection' + +const worktreeShowAnswer = z.object({ + worktree: z.object({ id: z.string(), hostId: z.string().optional(), path: z.string().optional() }) +}) +const ensureSessionAnswer = z.object({ + terminal: z.object({ handle: z.string() }), + disposition: z.enum(['created', 'adopted']) +}) + +/** The live row of this session in this workspace, whose transcript some agents resume from; + * a same-id session elsewhere is another agent's. */ +function liveRow( + rows: readonly PluginAgentStatusRow[], + match: { agent: string; sessionId: string; worktreeId: string; hostId: string } +): PluginAgentStatusRow | undefined { + return rows.find( + (candidate) => + // A session-only row is no live pane: the session is past, and is prepared as one. + candidate.providerSessionOnly !== true && + candidate.agentType === match.agent && + candidate.providerSession?.id === match.sessionId && + candidate.worktreeId === match.worktreeId && + getConnectionExecutionHostId(candidate.connectionId) === match.hostId + ) +} + +export const PLUGIN_AGENT_RESUME_HANDLERS = { + 'agent.resume': bind( + PLUGIN_HOST_API['agent.resume'], + async ({ workspaceId, agent, sessionId }, ctx) => { + const worktree = workspaceSelector(workspaceId) + const shown = worktreeShowAnswer.parse( + await rpc(ctx.services)('worktree.show', { worktree }) + ).worktree + const hostId = shown.hostId ?? LOCAL_EXECUTION_HOST_ID + const live = liveRow(ctx.services.listAgentStatuses(), { + agent, + sessionId, + worktreeId: shown.id, + hostId + }) + const transcriptPath = live + ? resumableTranscript(live.providerSession?.transcriptPath) + : // History lists this computer's sessions only; another host's agent resumes by id. + hostId === LOCAL_EXECUTION_HOST_ID + ? await preparePluginPastSession(ctx, { + agent, + sessionId, + workspacePath: shown.path ?? null + }) + : undefined + const answer = ensureSessionAnswer.parse( + await effect(ctx, 'terminal.ensureAgentSession', { + kind: 'explicit', + worktree, + agent, + providerSession: { + // The params schema admits only agents that resume by session id. + key: pluginResumeKey(agent) ?? 'session_id', + id: sessionId, + ...(transcriptPath ? { transcriptPath } : {}) + }, + // A mod works beside the person: never take their focus. + presentation: 'background' + }) + ) + const started = answer.disposition === 'created' + // A terminal that already ran the session is not the plugin's to close; one it started is, + // unless the plugin lost approval while it started. + if (started) { + ctx.scope.assertActive() + recordPluginOpenedTerminal(ctx.pluginId, answer.terminal.handle) + } + return { terminalId: answer.terminal.handle, started } + } + ) +} satisfies Record diff --git a/src/main/plugins/workers/host-api/plugin-host-automation-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-automation-bindings.ts new file mode 100644 index 00000000000..d21d22c2764 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-automation-bindings.ts @@ -0,0 +1,181 @@ +import { z } from 'zod' +import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' +import { + PLUGIN_WORKSPACE_LIST_LIMIT, + pluginWorkspaceId +} from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { + bind, + type BoundPluginHostMethod, + type PluginHostMethodContext +} from './plugin-host-method-bind' +import { + pluginHostEffect as effect, + pluginHostRpc as rpc, + pluginWorkspaceSelector as workspaceSelector +} from './plugin-host-runtime-call' +import { resolvePluginProject } from './plugin-host-project-target' +import { PluginHostCallError } from './plugin-host-call-scope' +import { buildWorkspaceRunContext } from '../../../../shared/work-items/task-source-context' +import { + automationAnswer, + automationRunsElevated, + projectPluginAutomations, + type PluginAutomationRecord +} from './plugin-automation-projection' +import { pluginAutomationRefusal } from './plugin-automation-confirmation' + +const api = PLUGIN_HOST_API + +const automationListAnswer = z.object({ automations: z.array(automationAnswer) }) +const automationCreateAnswer = z.object({ automation: z.object({ id: z.string() }) }) +const projectHostSetupAnswer = z.object({ + setups: z.array( + z.object({ + id: z.string(), + projectId: z.string(), + hostId: z.string(), + repoId: z.string(), + path: z.string(), + setupState: z.string() + }) + ) +}) +const worktreeListAnswer = z.object({ + worktrees: z.array( + z.object({ id: z.string(), identity: z.object({ key: z.string() }).optional() }) + ) +}) + +/** The ids `workspace.list` gives the workspaces automations run in. */ +async function listedWorkspaceIds( + ctx: PluginHostMethodContext, + automations: readonly PluginAutomationRecord[] +): Promise> { + if (!automations.some((automation) => automation.workspaceId)) { + return new Map() + } + const { worktrees } = worktreeListAnswer.parse( + await rpc(ctx.services)('worktree.list', { limit: PLUGIN_WORKSPACE_LIST_LIMIT }) + ) + return new Map( + worktrees.map((row) => [ + row.id, + pluginWorkspaceId({ id: row.id, identityKey: row.identity?.key }) + ]) + ) +} + +/** Each run in one workspace, whose id also names its host; or in a new one of a project, on + * the host `hostId` names: the runtime takes a host only with the project's setup there. */ +async function automationTarget( + ctx: PluginHostMethodContext, + params: { projectId?: string; hostId?: string; workspaceId?: string } +): Promise> { + if (params.workspaceId) { + return { workspace: workspaceSelector(params.workspaceId), workspaceMode: 'existing' } + } + const call = rpc(ctx.services) + const project = await resolvePluginProject( + call, + params.projectId ?? '', + params.hostId, + 'pass the hostId project.list gives' + ) + const target = { repo: `id:${project.id}`, workspaceMode: 'new_per_run' } + if (!project.hostId) { + return target + } + const { setups } = projectHostSetupAnswer.parse(await call('projectHostSetup.list', undefined)) + const setup = setups.find( + (candidate) => + candidate.repoId === project.id && + candidate.hostId === project.hostId && + candidate.setupState === 'ready' + ) + const runContext = setup && buildWorkspaceRunContext({ ...setup, projectHostSetupId: setup.id }) + if (!runContext) { + throw new PluginHostCallError('action_failed', 'this project is not set up on that host') + } + return { ...target, runContext } +} + +export const PLUGIN_AUTOMATION_HANDLERS = { + 'automation.list': bind(api['automation.list'], async (_params, ctx) => { + // No selector: every automation this Orca stores, the list `orca automations list` prints. + const { automations } = automationListAnswer.parse( + await rpc(ctx.services)('automation.list', {}) + ) + return projectPluginAutomations( + automations, + ctx.pluginId, + await listedWorkspaceIds(ctx, automations) + ) + }), + 'automation.create': bind(api['automation.create'], async (params, ctx) => { + const target = await automationTarget(ctx, params) + // Never forwarded: a precheck (a shell command), agent arguments, launch setup (permission + // modes), setup decisions or trust, or a destination. Runs use the person's settings for the + // agent, here. Orca records this plugin as the creator from the caller, not from params. + const answer = await effect(ctx, 'automation.create', { + name: params.name.trim(), + prompt: params.prompt, + agentId: params.agent, + ...target, + rrule: params.schedule, + dtstart: Date.now(), + ...(params.timezone ? { timezone: params.timezone } : {}), + enabled: params.enabled ?? true, + // Scoped to this plugin, so its keys never answer with another creator's automation. + ...(params.creationKey ? { creationKey: `plugin:${ctx.pluginId}:${params.creationKey}` } : {}) + }) + return { automationId: automationCreateAnswer.parse(answer).automation.id } + }), + 'automation.update': bind(api['automation.update'], async (params, ctx) => { + const { automationId, name, prompt, schedule, timezone, enabled } = params + const fields = (['name', 'prompt', 'schedule', 'timezone', 'enabled'] as const).filter( + (field) => params[field] !== undefined + ) + // Another's automation is the person's. One that runs its agent with extra settings (its + // arguments, permission mode or a precheck) is asked about even for its own creator when a + // change would make it run something new: a new prompt, schedule or time zone, or resuming. + const startsNewRun = + prompt !== undefined || schedule !== undefined || timezone !== undefined || enabled === true + const refused = await pluginAutomationRefusal(ctx, automationId, (current, own) => { + const elevated = automationRunsElevated(current) && startsNewRun + return own && !elevated + ? null + : { + kind: 'automation.update', + fields, + ...(elevated ? { elevated: true } : {}), + // Whatever the reason to ask, a new prompt is what the person approves. + ...(prompt !== undefined ? { prompt } : {}) + } + }) + if (refused) { + return { updated: false, ...refused } + } + await effect(ctx, 'automation.update', { + id: automationId, + updates: { + ...(name !== undefined ? { name: name.trim() } : {}), + ...(prompt !== undefined ? { prompt } : {}), + ...(schedule !== undefined ? { rrule: schedule, dtstart: Date.now() } : {}), + ...(timezone !== undefined ? { timezone } : {}), + ...(enabled !== undefined ? { enabled } : {}) + } + }) + return { updated: true } + }), + 'automation.delete': bind(api['automation.delete'], async ({ automationId }, ctx) => { + const refused = await pluginAutomationRefusal(ctx, automationId, (_current, own) => + own ? null : { kind: 'automation.delete' } + ) + if (refused) { + return { deleted: false, ...refused } + } + await effect(ctx, 'automation.delete', { id: automationId }) + return { deleted: true } + }) +} satisfies Record diff --git a/src/main/plugins/workers/host-api/plugin-host-call-adapter.ts b/src/main/plugins/workers/host-api/plugin-host-call-adapter.ts index 2c373c0fa99..c84cb6bfdae 100644 --- a/src/main/plugins/workers/host-api/plugin-host-call-adapter.ts +++ b/src/main/plugins/workers/host-api/plugin-host-call-adapter.ts @@ -15,7 +15,7 @@ const pluginHostCallRequestSchema = z export type PluginHostCallPolicy = Pick< ExecutePluginHostCallInput, - 'grantedCapabilities' | 'services' | 'audit' | 'scope' + 'grantedCapabilities' | 'allowProposed' | 'services' | 'audit' | 'scope' > export type ResolvePluginHostCallPolicy = ( diff --git a/src/main/plugins/workers/host-api/plugin-host-call-scope.ts b/src/main/plugins/workers/host-api/plugin-host-call-scope.ts index b921a14fc30..ab582340c3a 100644 --- a/src/main/plugins/workers/host-api/plugin-host-call-scope.ts +++ b/src/main/plugins/workers/host-api/plugin-host-call-scope.ts @@ -27,12 +27,24 @@ export class PluginHostCallError extends Error { constructor( readonly code: PluginErrorCode, message: string, - readonly retryAfterMs?: number + readonly retryAfterMs?: number, + /** What actually failed, for the plugin's log only; the plugin gets `message`. */ + readonly detail?: string, + options?: ErrorOptions ) { - super(message) + super(message, options) } } +/** + * A runtime refusal as the plugin sees it. Its code applies from host API 1.7; a method that + * shipped earlier reports every runtime refusal as `action_failed`, as it always has. + */ +export class PluginRuntimeCallError extends PluginHostCallError {} + +/** The host API minor whose methods report runtime refusals with their own codes. */ +export const PLUGIN_RUNTIME_FAILURE_CODES_SINCE = 7 + export function pluginHostCallRevoked(): PluginHostCallError { return new PluginHostCallError('consent_required', 'plugin is no longer enabled') } diff --git a/src/main/plugins/workers/host-api/plugin-host-method-bind.ts b/src/main/plugins/workers/host-api/plugin-host-method-bind.ts index 1ee172cf535..3b582b437ef 100644 --- a/src/main/plugins/workers/host-api/plugin-host-method-bind.ts +++ b/src/main/plugins/workers/host-api/plugin-host-method-bind.ts @@ -1,10 +1,13 @@ import type { z } from 'zod' import type { PluginHostMethodSpec } from '../../../../shared/plugins/workers/plugin-host-api' import type { PluginHostCallScope } from './plugin-host-call-scope' +import type { PluginSurface } from '../../../../shared/plugins/frames/plugin-protocol' import type { PluginHostServices } from './plugin-host-method-bindings' export type PluginHostMethodContext = { pluginId: string + /** Who called: frames (panel, editor) see less than a full-access worker. */ + surface: PluginSurface services: PluginHostServices scope: PluginHostCallScope } diff --git a/src/main/plugins/workers/host-api/plugin-host-method-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-method-bindings.ts index d0d3f402e03..c2682a6c8a4 100644 --- a/src/main/plugins/workers/host-api/plugin-host-method-bindings.ts +++ b/src/main/plugins/workers/host-api/plugin-host-method-bindings.ts @@ -7,6 +7,7 @@ import { } from '../../../../shared/plugins/workers/plugin-host-api' import { projectPluginWorkspaceAgents, + pluginFrameWorkspaceContext, projectPluginWorkspaceContext, type PluginAgentStatusRow, type PluginWorkspaceTerminal @@ -23,22 +24,37 @@ import { PLUGIN_STATUS_BAR_HANDLERS, type PluginStatusBarServices } from './plugin-host-status-bar-method-bindings' -import { - PLUGIN_WORKSPACE_ACTION_HANDLERS, - type PluginRuntimeRpc -} from './plugin-host-workspace-method-bindings' +import { PLUGIN_WORKSPACE_ACTION_HANDLERS } from './plugin-host-workspace-method-bindings' +import { PLUGIN_TERMINAL_ACTION_HANDLERS } from './plugin-host-terminal-method-bindings' +import { PLUGIN_WORKSPACE_CREATE_HANDLERS } from './plugin-host-workspace-create-bindings' +import { PLUGIN_AUTOMATION_HANDLERS } from './plugin-host-automation-bindings' +import { PLUGIN_AGENT_HISTORY_HANDLERS } from './plugin-host-agent-history-bindings' +import { PLUGIN_PROJECT_VISIBILITY_HANDLERS } from './plugin-host-project-visibility-binding' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' import type { PluginAppearanceService } from '../../appearance/plugin-appearance-service' import type { PluginEditorTypographySource } from '../../appearance/plugin-editor-typography' import { PluginHostCallError } from './plugin-host-call-scope' +import type { + PluginActionConfirmation, + PluginConfirmationSubject +} from '../../consent/plugin-confirmation-subject' export type PluginWorktreeContext = { worktreeId: string + /** Host-qualified identity key, which `workspace.list` ids carry; absent without one. */ + identityKey?: string branch: string displayName: string } -/** Desktop-only sinks for frame methods; absent in headless serve. */ +/** Desktop-only sinks for frame methods and host confirmations; absent in headless serve. */ export type PluginDesktopFrameServices = { + /** Asks the person in the calling frame's window, else Orca's focused or first window. */ + confirm( + pluginId: string, + subject: PluginConfirmationSubject, + scope: PluginHostCallScope + ): Promise openExternal( pluginId: string, url: string, @@ -59,6 +75,9 @@ export type PluginHostServices = { resolveActiveWorktreeContext(): Promise listWorktreeTerminals(worktreeId: string): Promise listAgentStatuses(): readonly PluginAgentStatusRow[] + /** The title of the orchestration task each pane runs, by pane key (`tabId:leafId`); absent + * where no runtime dispatches tasks. */ + listAgentTaskTitles?(): ReadonlyMap sendTerminalText( terminalId: string, action: { text: string; enter: boolean } @@ -96,6 +115,9 @@ export type PluginHostServices = { runtimeRpc?: PluginRuntimeRpc | null /** Orca's window, for actions only it can take; absent in headless serve. */ renderer?: PluginHostRendererActions | null + /** Asks the person before the plugin acts; absent where nobody can be asked (headless serve). + * Re-checks the plugin's approval once the person answers. */ + confirm?: PluginDesktopFrameServices['confirm'] | null settings: { getAll(pluginId: string): Record set( @@ -131,14 +153,18 @@ const HANDLERS: Record = { } return services.editorTypography.read() }), - 'workspace.readContext': bind(api['workspace.readContext'], async (_params, { services }) => { - const context = await services.resolveActiveWorktreeContext() - // A remote host may be unreachable; its workspace context still exists, so omit only its terminals. - const terminals = context - ? await services.listWorktreeTerminals(context.worktreeId).catch(() => []) - : [] - return projectPluginWorkspaceContext(context, terminals) - }), + 'workspace.readContext': bind( + api['workspace.readContext'], + async (_params, { services, surface }) => { + const context = await services.resolveActiveWorktreeContext() + // A remote host may be unreachable; its workspace context still exists, so omit only its terminals. + const terminals = context + ? await services.listWorktreeTerminals(context.worktreeId).catch(() => []) + : [] + const projected = projectPluginWorkspaceContext(context, terminals) + return surface === 'worker' ? projected : pluginFrameWorkspaceContext(projected) + } + ), 'agents.list': bind(api['agents.list'], async (_params, { services }) => { const context = await services.resolveActiveWorktreeContext() if (!context) { @@ -149,7 +175,9 @@ const HANDLERS: Record = { agents: projectPluginWorkspaceAgents( context.worktreeId, terminals, - services.listAgentStatuses() + services.listAgentStatuses(), + // Only read when the workspace has agents: it reads the orchestration database. + () => services.listAgentTaskTitles?.() ?? new Map() ) } }), @@ -230,7 +258,12 @@ const HANDLERS: Record = { }), ...PLUGIN_PANEL_BRIDGE_HANDLERS, ...PLUGIN_STATUS_BAR_HANDLERS, - ...PLUGIN_WORKSPACE_ACTION_HANDLERS + ...PLUGIN_WORKSPACE_ACTION_HANDLERS, + ...PLUGIN_PROJECT_VISIBILITY_HANDLERS, + ...PLUGIN_TERMINAL_ACTION_HANDLERS, + ...PLUGIN_WORKSPACE_CREATE_HANDLERS, + ...PLUGIN_AUTOMATION_HANDLERS, + ...PLUGIN_AGENT_HISTORY_HANDLERS } function requireDesktop(services: PluginHostServices): PluginDesktopFrameServices { diff --git a/src/main/plugins/workers/host-api/plugin-host-methods.test.ts b/src/main/plugins/workers/host-api/plugin-host-methods.test.ts index 27264b0cf64..dafaf64c6f6 100644 --- a/src/main/plugins/workers/host-api/plugin-host-methods.test.ts +++ b/src/main/plugins/workers/host-api/plugin-host-methods.test.ts @@ -71,3 +71,61 @@ describe('workspace.readContext host reachability', () => { }) }) }) + +describe('workspace.readContext workspace id', () => { + it('is the id workspace.list gives: identity form, folder key, else the raw id', async () => { + const contexts = [ + { worktreeId: 'repo::/w', identityKey: 'wt2:local:i1' }, + { worktreeId: 'folder:f1' }, + // A remote workspace known only from stored rows has no identity. + { worktreeId: 'remote-repo::/home/user/repo' } + ] + const outcomes = await Promise.all( + contexts.map((context) => { + const services = createServices(vi.fn()) + vi.mocked(services.resolveActiveWorktreeContext).mockResolvedValue({ + ...context, + branch: '', + displayName: 'w' + }) + return executePluginHostCall({ + pluginId: 'samples.demo', + method: 'workspace.readContext', + params: {}, + surface: 'worker', + grantedCapabilities: ['workspace:read'], + services + }) + }) + ) + expect(outcomes).toMatchObject([ + { ok: true, value: { workspaceId: 'identity:wt2:local:i1' } }, + { ok: true, value: { workspaceId: 'folder:f1' } }, + { ok: true, value: { workspaceId: 'remote-repo::/home/user/repo' } } + ]) + }) +}) + +describe('workspace.readContext in frames', () => { + it('gives panels only path-free ids', async () => { + const read = (worktreeId: string) => { + const services = createServices(vi.fn()) + vi.mocked(services.resolveActiveWorktreeContext).mockResolvedValue({ + worktreeId, + branch: '', + displayName: 'w' + }) + return executePluginHostCall({ + pluginId: 'samples.demo', + method: 'workspace.readContext', + params: {}, + surface: 'panel', + grantedCapabilities: ['workspace:read'], + services + }) + } + const [raw, folder] = await Promise.all([read('repo::/home/me/w'), read('folder:f1')]) + expect(raw.ok && raw.value).not.toHaveProperty('workspaceId') + expect(folder).toMatchObject({ ok: true, value: { workspaceId: 'folder:f1' } }) + }) +}) diff --git a/src/main/plugins/workers/host-api/plugin-host-methods.ts b/src/main/plugins/workers/host-api/plugin-host-methods.ts index f6ab9b886a5..8e15c488e4e 100644 --- a/src/main/plugins/workers/host-api/plugin-host-methods.ts +++ b/src/main/plugins/workers/host-api/plugin-host-methods.ts @@ -1,6 +1,10 @@ +import { ZodError } from 'zod' import { getBoundPluginHostMethod, type PluginHostServices } from './plugin-host-method-bindings' import { isQualifiedPluginKey } from '../../../../shared/plugins/manifest/plugin-manifest' -import { gatePluginHostCall as decidePluginHostCall } from '../../../../shared/plugins/capabilities/plugin-capability-gate' +import { + gatePluginHostCall as decidePluginHostCall, + missingPluginParamCapability +} from '../../../../shared/plugins/capabilities/plugin-capability-gate' import type { PluginCapabilityKind } from '../../../../shared/plugins/capabilities/plugin-capabilities' import { isPluginJsonObject } from '../../../../shared/plugins/manifest/plugin-json-object' import type { @@ -9,7 +13,9 @@ import type { } from '../../../../shared/plugins/frames/plugin-protocol' import type { PluginAuditLog } from '../../plugin-audit-log' import { + PLUGIN_RUNTIME_FAILURE_CODES_SINCE, PluginHostCallError, + PluginRuntimeCallError, UNSCOPED_PLUGIN_HOST_CALL, type PluginHostCallScope } from './plugin-host-call-scope' @@ -30,6 +36,8 @@ export type ExecutePluginHostCallInput = { surface: PluginSurface /** Consented capability kinds; null = unknown/disabled/consent-stale. */ grantedCapabilities: readonly PluginCapabilityKind[] | null + /** A development plugin, which may call proposed methods. */ + allowProposed?: boolean services: PluginHostServices | null audit?: Pick /** Re-checked right before the side effect; absent only in tests and the relay suite. */ @@ -43,7 +51,11 @@ export async function executePluginHostCall( return { ok: false, code: 'invalid_request', error: 'invalid qualified plugin key' } } const gate = decidePluginHostCall( - { grantedCapabilities: input.grantedCapabilities, surface: input.surface }, + { + grantedCapabilities: input.grantedCapabilities, + surface: input.surface, + allowProposed: input.allowProposed + }, input.method ) if (!gate.granted) { @@ -57,6 +69,18 @@ export async function executePluginHostCall( if (!prepared.ok) { return { ok: false, code: 'invalid_params', error: prepared.issue } } + const missing = missingPluginParamCapability( + bound.spec, + prepared.params, + input.grantedCapabilities ?? [] + ) + if (missing) { + return { + ok: false, + code: 'capability_denied', + error: `${missing.param} needs the "${missing.capability}" capability` + } + } const services = input.services if (!services) { return { ok: false, code: 'unavailable', error: 'runtime is not available' } @@ -95,7 +119,12 @@ export async function executePluginHostCall( try { // The audit write awaited: approval may have been revoked meanwhile. scope.assertActive() - const validated = await prepared.execute({ pluginId: input.pluginId, services, scope }) + const validated = await prepared.execute({ + pluginId: input.pluginId, + surface: input.surface, + services, + scope + }) if (!validated) { await auditMutation('error').catch(() => undefined) // Malformed host results must not leak unvalidated shapes through any plugin transport. @@ -109,8 +138,25 @@ export async function executePluginHostCall( return { ok: true, value: validated.value } } catch (error) { await auditMutation('error').catch(() => undefined) + if (error instanceof ZodError) { + // A runtime answer Orca's own binding did not expect; its shape is internal. + scope.log?.(`${input.method}: unexpected runtime answer: ${error.message}`) + return { + ok: false, + code: 'action_failed', + error: `internal: malformed ${input.method} answer` + } + } if (error instanceof PluginHostCallError) { - const { code, message, retryAfterMs } = error + if (error.detail) { + scope.log?.(`${input.method}: ${error.detail}`) + } + const { message, retryAfterMs } = error + const code = + error instanceof PluginRuntimeCallError && + bound.spec.since < PLUGIN_RUNTIME_FAILURE_CODES_SINCE + ? 'action_failed' + : error.code return { ok: false, code, @@ -133,6 +179,23 @@ function summarizeParams(method: string, params: unknown): string { const text = typeof record.text === 'string' ? record.text : '' return `terminal=${String(record.terminalId)} bytes=${Buffer.byteLength(text, 'utf8')} enter=${record.enter === true}` } + case 'terminal.focus': + case 'terminal.close': + return `terminal=${String(record.terminalId)}` + case 'workspace.create': + return `project=${String(record.projectId)} agent=${String(record.agent ?? 'none')} promptChars=${textLength(record.prompt)} setup=${String(record.setup ?? 'default')} open=${record.open === true}` + case 'project.setHidden': + return `project=${String(record.projectId)} host=${String(record.hostId ?? 'any')} hidden=${record.hidden === true}` + case 'agent.resume': + return `workspace=${String(record.workspaceId)} agent=${String(record.agent)} session=${String(record.sessionId)}` + case 'automation.create': + return `${record.workspaceId ? `workspace=${String(record.workspaceId)}` : `project=${String(record.projectId)}`} agent=${String(record.agent)} promptChars=${textLength(record.prompt)}` + case 'automation.update': + return `automation=${String(record.automationId)} fields=${Object.keys(record) + .filter((key) => key !== 'automationId') + .join(',')}` + case 'automation.delete': + return `automation=${String(record.automationId)}` case 'notifications.show': { const title = typeof record.title === 'string' ? record.title : '' return `titleChars=${title.length}` @@ -147,3 +210,7 @@ function summarizeParams(method: string, params: unknown): string { return '' } } + +function textLength(value: unknown): number { + return typeof value === 'string' ? value.length : 0 +} diff --git a/src/main/plugins/workers/host-api/plugin-host-panel-methods.test.ts b/src/main/plugins/workers/host-api/plugin-host-panel-methods.test.ts index 3e0e2607502..254d22b2623 100644 --- a/src/main/plugins/workers/host-api/plugin-host-panel-methods.test.ts +++ b/src/main/plugins/workers/host-api/plugin-host-panel-methods.test.ts @@ -71,11 +71,3 @@ describe('plugin.request', () => { }) }) }) - -describe('panel storage and settings', () => { - it('keeps the capability gate for panels', async () => { - await expect(call('storage.get', { key: 'todos' }, { grants: [] })).resolves.toMatchObject({ - code: 'capability_denied' - }) - }) -}) diff --git a/src/main/plugins/workers/host-api/plugin-host-project-target.ts b/src/main/plugins/workers/host-api/plugin-host-project-target.ts new file mode 100644 index 00000000000..c00b8244c2a --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-project-target.ts @@ -0,0 +1,57 @@ +import { z } from 'zod' +import { getRepoExecutionHostId, normalizeExecutionHostId } from '../../../../shared/execution-host' +import { PluginHostCallError } from './plugin-host-call-scope' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' + +const repoListAnswer = z.object({ + repos: z.array( + z.object({ + id: z.string(), + kind: z.string().optional(), + executionHostId: z.string().nullable().optional(), + connectionId: z.string().nullable().optional() + }) + ) +}) + +export type PluginProjectTarget = { + id: string + kind: 'git' | 'folder' + /** The host the plugin named; null when it named none. */ + hostId: string | null + /** The host of the one copy found, named or not: `local`, `ssh:…` or `runtime:…`. */ + ownerHostId: string +} + +/** + * The project a plugin names by its `project.list` id, refused with a fixed message when no + * project has it, or when two hosts do and `hostId` does not pick one. + */ +export async function resolvePluginProject( + call: PluginRuntimeRpc, + projectId: string, + hostId: string | undefined, + ambiguousHint: string +): Promise { + const wantedHost = hostId === undefined ? undefined : normalizeExecutionHostId(hostId) + const matches = repoListAnswer + .parse(await call('repo.list', {})) + .repos.filter( + (repo) => + repo.id === projectId && + (wantedHost === undefined || getRepoExecutionHostId(repo) === wantedHost) + ) + if (matches.length > 1) { + throw new PluginHostCallError('action_failed', `two hosts have this project; ${ambiguousHint}`) + } + const [repo] = matches + if (!repo) { + throw new PluginHostCallError('action_failed', 'no project has this id') + } + return { + id: repo.id, + kind: repo.kind === 'folder' ? 'folder' : 'git', + hostId: wantedHost ?? null, + ownerHostId: getRepoExecutionHostId(repo) + } +} diff --git a/src/main/plugins/workers/host-api/plugin-host-project-visibility-binding.ts b/src/main/plugins/workers/host-api/plugin-host-project-visibility-binding.ts new file mode 100644 index 00000000000..65c60704325 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-project-visibility-binding.ts @@ -0,0 +1,37 @@ +import { z } from 'zod' +import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' +import { bind, type BoundPluginHostMethod } from './plugin-host-method-bind' +import { PluginHostCallError } from './plugin-host-call-scope' +import { pluginHostEffect as effect, pluginHostRpc as rpc } from './plugin-host-runtime-call' +import { resolvePluginProject } from './plugin-host-project-target' + +// Optional: a host that predates hidden projects answers without `hidden`, which must read as a +// refusal, never as done. +const repoSetHiddenAnswer = z.object({ hidden: z.boolean().optional() }) + +export const PLUGIN_PROJECT_VISIBILITY_HANDLERS = { + 'project.setHidden': bind(PLUGIN_HOST_API['project.setHidden'], async (params, ctx) => { + const project = await resolvePluginProject( + rpc(ctx.services), + params.projectId, + params.hostId, + 'pass the hostId project.list gives' + ) + // By id on the one host found: a name or path could pick another project, and a bare id + // another host's copy. + const { hidden } = repoSetHiddenAnswer.parse( + await effect(ctx, 'repo.setHidden', { + repo: `id:${project.id}`, + repoHostId: project.ownerHostId, + hidden: params.hidden + }) + ) + if (hidden !== params.hidden) { + throw new PluginHostCallError( + 'action_failed', + "this project's host could not change it; it may need an Orca update" + ) + } + return { hostId: project.ownerHostId, hidden } + }) +} satisfies Record diff --git a/src/main/plugins/workers/host-api/plugin-host-runtime-call.ts b/src/main/plugins/workers/host-api/plugin-host-runtime-call.ts new file mode 100644 index 00000000000..2cd11f0927d --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-runtime-call.ts @@ -0,0 +1,123 @@ +import type { PluginErrorCode } from '../../../../shared/plugins/frames/plugin-protocol' +import type { PluginHostMethodContext } from './plugin-host-method-bind' +import type { PluginHostServices } from './plugin-host-method-bindings' +import { PluginHostCallError, PluginRuntimeCallError } from './plugin-host-call-scope' +import type { PluginHostRendererActions } from '../../view/plugin-host-renderer-actions' + +/** The runtime RPC the `orca` CLI calls, run in process; rejects with the runtime's error. + * `beforeEffect` runs right before the runtime acts, after its own waits; a throw refuses it. + * `plugin` names who the call acts for, which the runtime records where it keeps provenance. */ +export type PluginRuntimeRpc = ( + method: string, + params: unknown, + options?: { + signal?: AbortSignal + beforeEffect?: () => void + plugin?: { key: string; name: string } + } +) => Promise + +type Failure = [PluginErrorCode, string] +const NO_LIVE_TERMINAL: Failure = ['action_failed', 'no live terminal has this id'] +const NO_WINDOW: Failure = ['unavailable', "Orca's window is not available"] + +// Runtime refusals whose wording names Orca internals; a plugin gets a fixed message instead. +const RUNTIME_FAILURES: ReadonlyMap = new Map([ + ['selector_not_found', ['action_failed', 'no workspace has this id']], + [ + 'selector_ambiguous', + ['action_failed', 'two hosts have a workspace with this id; use the id workspace.list gives'] + ], + ['repo_not_found', ['action_failed', 'no project has this id']], + ['terminal_not_found', NO_LIVE_TERMINAL], + ['terminal_handle_stale', NO_LIVE_TERMINAL], + ['terminal_exited', NO_LIVE_TERMINAL], + ['terminal_gone', NO_LIVE_TERMINAL], + ['tab_not_found', NO_LIVE_TERMINAL], + ['terminal_tab_pinned', ['conflict', "the terminal's tab is pinned; unpin it in Orca first"]], + ['renderer_unavailable', NO_WINDOW], + ['client_disconnected', ['unavailable', 'the host that owns this is not connected']], + ['runtime_unavailable', ['unavailable', 'this Orca host cannot run workspace actions now']], + ['Automation not found.', ['action_failed', 'no automation has this id']] +]) +const UNKNOWN_FAILURE: Failure = ['action_failed', 'Orca could not complete this action'] + +/** + * A runtime refusal as the plugin sees it: a fixed message, never the runtime's wording, which + * goes to the plugin's log as `detail`. Approval and cancellation refusals pass through. + */ +export function pluginRuntimeFailure(error: unknown): unknown { + if ( + error instanceof PluginHostCallError || + (error instanceof Error && error.name === 'AbortError') + ) { + return error + } + const detail = error instanceof Error ? error.message : String(error) + // The runtime answers a code (`selector_not_found`); some refusals arrive as a bare message. + const code = + error instanceof Error && 'code' in error && typeof error.code === 'string' + ? error.code + : undefined + const [failureCode, message] = + (code && RUNTIME_FAILURES.get(code)) || RUNTIME_FAILURES.get(detail) || UNKNOWN_FAILURE + return new PluginRuntimeCallError(failureCode, message, undefined, detail, { cause: error }) +} + +export function pluginHostRenderer(services: PluginHostServices): PluginHostRendererActions { + if (!services.renderer) { + throw new PluginHostCallError('unavailable', 'only the Orca desktop app can do this') + } + return services.renderer +} + +/** The runtime RPC, with its refusals mapped by `pluginRuntimeFailure`. */ +export function pluginHostRpc(services: PluginHostServices): PluginRuntimeRpc { + const call = services.runtimeRpc + if (!call) { + throw new PluginHostCallError('unavailable', 'this Orca host cannot run workspace actions') + } + return (method, params, options) => + call(method, params, options).catch((error: unknown) => { + throw pluginRuntimeFailure(error) + }) +} + +/** A runtime call that changes something: refused if the plugin lost approval, or its worker + * cancelled the call, at any point before the runtime acts. */ +export function pluginHostEffect( + ctx: PluginHostMethodContext, + method: string, + params: unknown +): Promise { + ctx.scope.assertActive() + return pluginHostRpc(ctx.services)(method, params, { + ...(ctx.scope.signal ? { signal: ctx.scope.signal } : {}), + beforeEffect: () => ctx.scope.assertActive(), + plugin: { key: ctx.pluginId, name: ctx.scope.pluginName ?? ctx.pluginId } + }) +} + +/** + * The selector a listed workspace id names. Ids carry their host (`identity:`, unique across + * twins on two hosts) or are folder keys; a bare id from elsewhere is taken as an exact id. + */ +export function pluginWorkspaceSelector(workspaceId: string): string { + return workspaceId.startsWith('identity:') ? workspaceId : `id:${workspaceId}` +} + +/** Whether `error`, or an error it was caused by, is an instance of `type`. */ +export function pluginRuntimeErrorIs( + error: unknown, + type: abstract new (...args: never[]) => Error +): boolean { + let current: unknown = error + for (let depth = 0; depth < 8 && current instanceof Error; depth += 1) { + const cause: unknown = current.cause + if (current instanceof type) { + return true + } + current = cause + } + return false +} diff --git a/src/main/plugins/workers/host-api/plugin-host-service-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-service-bindings.ts index 4097a079ce9..5278044fae8 100644 --- a/src/main/plugins/workers/host-api/plugin-host-service-bindings.ts +++ b/src/main/plugins/workers/host-api/plugin-host-service-bindings.ts @@ -2,7 +2,7 @@ import { PLUGIN_WORKSPACE_TERMINAL_LIMIT } from '../../../../shared/plugins/work import type { PluginHostServices, PluginDesktopFrameServices } from './plugin-host-method-bindings' import type { PluginPanelBridgeServices } from './plugin-host-panel-method-bindings' import type { PluginStatusBarState } from '../../status-bar/plugin-status-bar-state' -import type { PluginRuntimeRpc } from './plugin-host-workspace-method-bindings' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' import type { PluginHostRendererActions } from '../../view/plugin-host-renderer-actions' import { pluginSettingValueIssue, @@ -19,6 +19,7 @@ import type { PluginEditorTypographySource } from '../../appearance/plugin-edito export type PluginRuntimeDelegate = { resolveActiveWorktreeContext(): Promise<{ worktreeId: string + identityKey?: string path: string branch: string displayName: string @@ -48,6 +49,8 @@ export type PluginRuntimeDelegate = { }): Promise<{ delivered: boolean }> /** The hook server's agent rows; absent where no hook server runs. */ listAgentStatuses?(): readonly PluginAgentStatusRow[] + /** Dispatched orchestration task titles by pane key; absent where no runtime dispatches tasks. */ + listAgentTaskTitles?(): ReadonlyMap /** The runtime RPC the `orca` CLI calls, in process; absent where none is bound. */ callRuntime?: PluginRuntimeRpc } @@ -73,6 +76,7 @@ export function bindPluginHostServices(input: { appearance: input.appearance ?? null, editorTypography: input.editorTypography ?? null, desktop: input.desktop ?? null, + confirm: input.desktop?.confirm ?? null, panels: input.panels ?? null, statusBar: input.statusBar ? statusBarServices(input.statusBar, input.declaredStatusBarItemIds, input.statusBarRevision) @@ -84,9 +88,11 @@ export function bindPluginHostServices(input: { if (!context) { return null } - // Retain path-bearing worktree IDs for host membership checks; public projections exclude them. + // Retain path-bearing worktree IDs for host membership checks; public projections expose + // the identity form instead when there is one. return { worktreeId: context.worktreeId, + ...(context.identityKey ? { identityKey: context.identityKey } : {}), branch: context.branch, displayName: context.displayName } @@ -106,6 +112,14 @@ export function bindPluginHostServices(input: { })) }, listAgentStatuses: () => delegate.listAgentStatuses?.() ?? [], + listAgentTaskTitles: () => { + try { + return delegate.listAgentTaskTitles?.() ?? new Map() + } catch { + // Task titles are optional; an orchestration read failure must not lose the agent rows. + return new Map() + } + }, sendTerminalText: async (terminalId, action) => { const result = await delegate.sendTerminal(terminalId, action, { inputKind: 'driving' }) return { accepted: result.accepted } diff --git a/src/main/plugins/workers/host-api/plugin-host-terminal-actions.test.ts b/src/main/plugins/workers/host-api/plugin-host-terminal-actions.test.ts new file mode 100644 index 00000000000..b06cac69cee --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-terminal-actions.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from 'vitest' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' +import { callPluginHost, pluginHostTestServices } from './__mocks__/plugin-host-services-fixture' +import { executePluginHostCall } from './plugin-host-methods' +import { PluginHostCallError } from './plugin-host-call-scope' + +const focusedOn = (terminalIds: string[]) => ({ + resolveActiveWorktreeContext: vi + .fn() + .mockResolvedValue({ worktreeId: 'repo::/w', branch: 'main', displayName: 'w' }), + listWorktreeTerminals: vi.fn().mockResolvedValue(terminalIds.map((id) => ({ id }))) +}) + +describe('terminal.close', () => { + const close = (rpc: PluginRuntimeRpc, terminalId = 'term_a') => + callPluginHost({ + method: 'terminal.close', + params: { terminalId }, + granted: ['terminal:send'], + services: pluginHostTestServices(rpc, focusedOn(['term_a'])) + }) + + it('gains no close rights from a create that finished after the plugin lost approval', async () => { + let approved = true + const rpc = vi.fn(async () => { + // Approval is revoked while the runtime creates the terminal. + approved = false + return { terminal: { handle: 'term_late' } } + }) + const created = await executePluginHostCall({ + pluginId: 'samples.demo', + method: 'terminal.create', + params: { workspaceId: 'identity:other' }, + surface: 'worker', + grantedCapabilities: ['terminal:send'], + services: pluginHostTestServices(rpc), + audit: { record: vi.fn().mockResolvedValue(undefined) }, + scope: { + assertActive: () => { + if (!approved) { + throw new PluginHostCallError('consent_required', 'plugin is no longer enabled') + } + } + } + }) + expect(created).toMatchObject({ ok: false, code: 'consent_required' }) + expect(await close(vi.fn(), 'term_late')).toMatchObject({ ok: false, code: 'action_failed' }) + }) +}) diff --git a/src/main/plugins/workers/host-api/plugin-host-terminal-method-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-terminal-method-bindings.ts new file mode 100644 index 00000000000..009e7ff1771 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-terminal-method-bindings.ts @@ -0,0 +1,99 @@ +import { z } from 'zod' +import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' +import { PLUGIN_WORKSPACE_TERMINAL_LIMIT } from '../../../../shared/plugins/workers/plugin-host-api-workspace-context' +import { PLUGIN_HOST_ID_MAX_LENGTH } from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { PluginHostCallError } from './plugin-host-call-scope' +import type { PluginHostServices } from './plugin-host-method-bindings' +import { forgetPluginOpenedTerminal, isPluginOpenedTerminal } from './plugin-opened-terminals' +import { bind, type BoundPluginHostMethod } from './plugin-host-method-bind' +import { pluginTerminalTitle } from './plugin-workspace-projection' +import { + pluginHostEffect as effect, + pluginHostRenderer as renderer, + pluginHostRpc as rpc, + pluginWorkspaceSelector as workspaceSelector +} from './plugin-host-runtime-call' + +const api = PLUGIN_HOST_API + +// The parts of each runtime answer a host method reads; anything else is dropped. +const terminalListAnswer = z.object({ + terminals: z.array( + z.object({ + handle: z.string(), + title: z.string().nullable(), + paneTitle: z.string().optional() + }) + ), + totalCount: z.number().optional(), + truncated: z.boolean().optional() +}) +const terminalFocusAnswer = z.object({ focus: z.object({ navigated: z.boolean().optional() }) }) + +export const TERMINAL_CLOSE_REFUSAL = + 'terminal.close closes only terminals of the focused workspace or ones this plugin opened' + +/** Whether the terminal belongs to the focused workspace now, as `terminal.sendText` checks. */ +async function inFocusedWorkspace( + services: PluginHostServices, + terminalId: string +): Promise { + const context = await services.resolveActiveWorktreeContext() + if (!context) { + return false + } + const terminals = await services.listWorktreeTerminals(context.worktreeId).catch(() => []) + return terminals.some((terminal) => terminal.id === terminalId) +} + +export const PLUGIN_TERMINAL_ACTION_HANDLERS = { + 'terminal.list': bind(api['terminal.list'], async ({ workspaceId }, { services, scope }) => { + const answer = await rpc(services)( + 'terminal.list', + { + worktree: workspaceSelector(workspaceId), + limit: PLUGIN_WORKSPACE_TERMINAL_LIMIT, + includeVisualLayouts: false, + includePreview: false + }, + scope.signal ? { signal: scope.signal } : {} + ) + const { terminals, totalCount, truncated } = terminalListAnswer.parse(answer) + // Why filter: one over-long handle must not fail the whole list; it counts as left out. + const listed = terminals + .slice(0, PLUGIN_WORKSPACE_TERMINAL_LIMIT) + .filter(({ handle }) => handle.length > 0 && handle.length <= PLUGIN_HOST_ID_MAX_LENGTH) + return { + terminals: listed.map((terminal) => { + const title = pluginTerminalTitle(terminal) + return title ? { id: terminal.handle, title } : { id: terminal.handle } + }), + truncated: truncated === true || (totalCount ?? terminals.length) > listed.length + } + }), + 'terminal.focus': bind(api['terminal.focus'], async ({ terminalId }, ctx) => { + // Focus means Orca's window; headless serve has none to show. + renderer(ctx.services) + const answer = await effect(ctx, 'terminal.focus', { + terminal: terminalId, + // This window only: paired phones and other clients are not steered by a plugin. + navigation: 'host' + }) + // `navigated: false`: a newer focus request won, or Orca's window did not move to it. + return { focused: terminalFocusAnswer.parse(answer).focus.navigated !== false } + }), + 'terminal.close': bind(api['terminal.close'], async ({ terminalId }, ctx) => { + // Destructive, so narrower than focus: the focused workspace's terminals (where + // `terminal.sendText` may type), or ones this plugin opened wherever they are. + if ( + !isPluginOpenedTerminal(ctx.pluginId, terminalId) && + !(await inFocusedWorkspace(ctx.services, terminalId)) + ) { + throw new PluginHostCallError('action_failed', TERMINAL_CLOSE_REFUSAL) + } + await effect(ctx, 'terminal.close', { terminal: terminalId }) + forgetPluginOpenedTerminal(ctx.pluginId, terminalId) + // Why no exit report: a local close answers before Orca knows whether the process stopped. + return { closed: true as const } + }) +} satisfies Record diff --git a/src/main/plugins/workers/host-api/plugin-host-workspace-create-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-workspace-create-bindings.ts new file mode 100644 index 00000000000..73444a635c0 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-workspace-create-bindings.ts @@ -0,0 +1,175 @@ +import { z } from 'zod' +import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' +import { pluginWorkspaceId } from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { + suggestCreatureNameForPaths, + suggestionPathBasename +} from '../../../../shared/worktree-name-suggestion' +import { WorktreeCreateSetupChoiceRefusedError } from '../../../runtime/workspaces/creation/worktree-create-setup-choice-refusal' +import { bind, type BoundPluginHostMethod } from './plugin-host-method-bind' +import { PluginHostCallError } from './plugin-host-call-scope' +import { + pluginHostEffect as effect, + pluginHostRpc as rpc, + pluginRuntimeErrorIs, + type PluginRuntimeRpc +} from './plugin-host-runtime-call' +import { resolvePluginProject, type PluginProjectTarget } from './plugin-host-project-target' +import { recordPluginOpenedTerminal } from './plugin-opened-terminals' +import { PLUGIN_AGENT_RESUME_HANDLERS } from './plugin-host-agent-resume-binding' + +const api = PLUGIN_HOST_API + +// The parts of each runtime answer these methods read; anything else is dropped. +const worktreeRecord = z.object({ + id: z.string(), + identity: z.object({ key: z.string() }).optional() +}) +const worktreeCreateAnswer = z.object({ worktree: worktreeRecord }) +const worktreeShowAnswer = z.object({ worktree: worktreeRecord }) +const agentLaunchAnswer = z.object({ + worktreeId: z.string(), + outcome: z.object({ handle: z.string() }) +}) +const worktreeListAnswer = z.object({ + worktrees: z.array( + worktreeRecord.extend({ + repoId: z.string(), + path: z.string(), + displayName: z.string().optional(), + hostId: z.string().optional() + }) + ) +}) + +const listedId = (worktree: z.output): string => + pluginWorkspaceId({ id: worktree.id, identityKey: worktree.identity?.key }) + +/** Every worktree of the project on its host; the list is not paged, so none is missed. */ +async function projectWorktrees(call: PluginRuntimeRpc, project: PluginProjectTarget) { + const { worktrees } = worktreeListAnswer.parse( + await call('worktree.list', { limit: Number.MAX_SAFE_INTEGER }) + ) + return worktrees.filter( + (worktree) => + worktree.repoId === project.id && (!project.hostId || worktree.hostId === project.hostId) + ) +} + +const setupDecisionRequired = (): PluginHostCallError => + new PluginHostCallError( + 'action_failed', + "this project's setup script needs a decision; pass setup: 'skip' or create it in Orca" + ) + +export const PLUGIN_WORKSPACE_CREATE_HANDLERS = { + 'workspace.create': bind(api['workspace.create'], async (params, ctx) => { + const call = rpc(ctx.services) + const project = await resolvePluginProject( + call, + params.projectId, + params.hostId, + 'pass the hostId project.list gives' + ) + if (project.kind === 'folder') { + throw new PluginHostCallError('action_failed', 'folder projects have no worktrees') + } + const existing = await projectWorktrees(call, project) + const open = params.open === true + // A creature no workspace of the project uses; a later clash gets a suffix from the host. + const name = params.name?.trim() || suggestCreatureNameForPaths(existing.map((w) => w.path)) + // Never `run`, an approved setup hash or a startup command: those approve or run repository + // code the person has not. Absent, setup follows the project's settings and approvals. + const create = { + repo: `id:${project.id}`, + ...(project.hostId ? { repoHostId: project.hostId } : {}), + name, + ...(params.name + ? { displayName: name, displayNameKind: 'user' } + : { nameWasGenerated: true, displayNameKind: 'generated' }), + ...(params.baseBranch ? { baseBranch: params.baseBranch } : {}), + setupDecision: params.setup === 'skip' ? 'skip' : 'inherit', + activate: open, + // A plugin moves this window only: paired clients are not steered. + ...(open ? { navigation: 'host' } : {}) + } + // Told apart by the class the runtime threw, never by its wording. + const setupRefusal = (error: unknown): unknown => + pluginRuntimeErrorIs(error, WorktreeCreateSetupChoiceRefusedError) + ? setupDecisionRequired() + : error + if (!params.agent) { + const { worktree } = worktreeCreateAnswer.parse( + await effect(ctx, 'worktree.create', create).catch((error: unknown) => { + throw setupRefusal(error) + }) + ) + return { workspaceId: listedId(worktree) } + } + // The agent starts after setup, in the terminal setup ran in, as `orca worktree create + // --agent` does; the prompt rides its launch. + const launched = agentLaunchAnswer.parse( + await effect(ctx, 'agent.launch', { + target: { kind: 'create-worktree', create }, + agent: params.agent, + surface: 'terminal', + presentation: open ? 'focused' : 'background', + launchSource: 'plugin', + ...(params.prompt ? { prompt: { text: params.prompt, delivery: 'submit' } } : {}) + }).catch(async (error: unknown) => { + const refusal = setupRefusal(error) + throw refusal === error + ? await withCreatedWorkspace(call, project, existing, name, error) + : refusal + }) + ) + // The plugin may have lost approval while the agent started. + ctx.scope.assertActive() + recordPluginOpenedTerminal(ctx.pluginId, launched.outcome.handle) + const { worktree } = worktreeShowAnswer.parse( + await call('worktree.show', { worktree: `id:${launched.worktreeId}` }) + ) + return { workspaceId: listedId(worktree), terminalId: launched.outcome.handle } + }), + ...PLUGIN_AGENT_RESUME_HANDLERS +} satisfies Record + +/** Whether a worktree is the one a create named `name` makes: it shows that name, or its folder + * is that name, or that name with the `-N` Orca adds when the name is taken. */ +function madeFromName(worktree: { path: string; displayName?: string }, name: string): boolean { + const folder = suggestionPathBasename(worktree.path) + const suffix = folder.startsWith(`${name}-`) ? folder.slice(name.length + 1) : '' + return ( + worktree.displayName === name || + folder === name || + (suffix.length > 0 && [...suffix].every((char) => char >= '0' && char <= '9')) + ) +} + +/** + * A launch can fail after its worktree exists; the refusal then names that workspace, so the + * plugin can use or remove it. Found as the one new worktree of the project with this name. + */ +async function withCreatedWorkspace( + call: PluginRuntimeRpc, + project: PluginProjectTarget, + before: readonly { id: string }[], + name: string, + error: unknown +): Promise { + const known = new Set(before.map((worktree) => worktree.id)) + const created = await projectWorktrees(call, project).then( + (after) => after.filter((worktree) => !known.has(worktree.id) && madeFromName(worktree, name)), + () => [] + ) + if (created.length !== 1 || !(error instanceof PluginHostCallError)) { + return error + } + return new PluginHostCallError( + error.code, + `${error.message}; the workspace was created: ${listedId(created[0])}`, + error.retryAfterMs, + error.detail, + { cause: error } + ) +} diff --git a/src/main/plugins/workers/host-api/plugin-host-workspace-list.ts b/src/main/plugins/workers/host-api/plugin-host-workspace-list.ts new file mode 100644 index 00000000000..8626712e045 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-host-workspace-list.ts @@ -0,0 +1,251 @@ +import { z } from 'zod' +import type { PluginHostResult } from '../../../../shared/plugins/workers/plugin-host-api' +import { + PLUGIN_HOST_ID_MAX_LENGTH, + PLUGIN_PROJECT_LIST_LIMIT, + PLUGIN_WORKSPACE_LIST_LIMIT, + pluginWorkspaceId +} from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { isRepoHidden } from '../../../../shared/hidden-projects' +import type { PluginRuntimeRpc } from './plugin-host-runtime-call' +import type { PluginHostServices } from './plugin-host-method-bindings' + +type WorkspaceList = PluginHostResult<'workspace.list'> +type WorkspaceStatus = NonNullable + +// The parts of each runtime answer `workspace.list` and `project.list` read; the rest is dropped. +const worktreeListAnswer = z.object({ + worktrees: z.array( + z.object({ + id: z.string(), + repoId: z.string(), + displayName: z.string(), + path: z.string(), + branch: z.string().optional(), + hostId: z.string().optional(), + identity: z.object({ key: z.string() }).optional() + }) + ), + totalCount: z.number().optional(), + truncated: z.boolean().optional() +}) +const repoRow = z.object({ + id: z.string(), + kind: z.string().optional(), + displayName: z.string().optional(), + executionHostId: z.string().nullable().optional(), + connectionId: z.string().nullable().optional() +}) +const repoListAnswer = z.object({ repos: z.array(repoRow) }) +const projectListAnswer = z.object({ + repos: z.array( + // A malformed `hiddenAt` reads as shown, as Orca's sidebar reads it, not as a failed list. + repoRow.extend({ path: z.string(), hiddenAt: z.number().optional().catch(undefined) }) + ) +}) +const folderListAnswer = z.object({ + folderWorkspaces: z.array( + z.object({ + id: z.string(), + name: z.string(), + folderPath: z.string(), + executionHostId: z.string().nullable().optional(), + connectionId: z.string().nullable().optional() + }) + ) +}) +const worktreePsAnswer = z.object({ + worktrees: z.array( + z.object({ + worktreeId: z.string(), + identity: z.object({ key: z.string() }).optional(), + status: z.enum(['working', 'permission', 'done', 'active', 'inactive']), + unread: z.boolean(), + liveTerminalCount: z.number().int().nonnegative(), + lastOutputAt: z.number().finite().nullable().optional(), + lastActivityAt: z.number().finite().optional() + }) + ), + totalCount: z.number().optional(), + truncated: z.boolean().optional() +}) + +/** `refs/heads/main` reads as `main`; a detached or folder workspace has none. */ +function branchName(branch: string | undefined): string | null { + const name = branch?.replace(/^refs\/heads\//, '') ?? '' + return name || null +} + +type WorkspaceStatuses = { byId: Map; truncated: boolean } + +/** Each workspace's status by the id `workspace.list` gives it. */ +async function readWorkspaceStatuses(call: PluginRuntimeRpc): Promise { + const { worktrees, totalCount, truncated } = worktreePsAnswer.parse( + await call('worktree.ps', { limit: PLUGIN_WORKSPACE_LIST_LIMIT }) + ) + return { + byId: new Map( + worktrees.map((row) => [ + // Folder workspace rows carry their `folder:` key as worktreeId, as list rows do. + pluginWorkspaceId({ id: row.worktreeId, identityKey: row.identity?.key }), + { + state: row.status, + unread: row.unread, + terminalCount: row.liveTerminalCount, + lastActivityAt: row.lastOutputAt ?? row.lastActivityAt ?? null + } + ]) + ), + truncated: truncated === true || (totalCount ?? worktrees.length) > worktrees.length + } +} + +export const PLUGIN_WORKSPACE_STATUS_TTL_MS = 1000 +// Why shared: `worktree.ps` refreshes every terminal host, so plugins polling together share one +// listing in flight, however long it takes, and its answer for a second after it lands. Keyed by +// the runtime RPC it came from. +type StatusRead = { read: Promise; settledAt: number | null } +/** What the shared status listing is keyed by: the runtime RPC, or the services without one. */ +export type PluginStatusListingOwner = + | NonNullable + | PluginHostServices + | PluginRuntimeRpc +const statusReads = new WeakMap() + +function workspaceStatuses( + call: PluginRuntimeRpc, + source: PluginStatusListingOwner +): Promise { + const cached = statusReads.get(source) + if ( + cached && + (cached.settledAt === null || Date.now() - cached.settledAt < PLUGIN_WORKSPACE_STATUS_TTL_MS) + ) { + return cached.read + } + const entry: StatusRead = { read: readWorkspaceStatuses(call), settledAt: null } + statusReads.set(source, entry) + entry.read.then( + () => { + entry.settledAt = Date.now() + }, + // A failed listing is not kept: the next call asks again. + () => { + if (statusReads.get(source) === entry) { + statusReads.delete(source) + } + } + ) + return entry.read +} + +/** `project.list`'s host: `local` for this machine, else its `ssh:` or `runtime:` host. */ +function projectHostId(repo: { + executionHostId?: string | null + connectionId?: string | null +}): string { + return getRepoExecutionHostId(repo) +} + +const LABEL_MAX = 512 + +/** Whether a row's ids and path fit the public bounds; one that does not is left out. */ +function fitsBounds(row: { + id: string + path: string + hostId: string | null + projectId?: string | null +}): boolean { + return [row.id, row.path, row.hostId ?? '', row.projectId ?? ''].every( + (value) => value.length <= PLUGIN_HOST_ID_MAX_LENGTH + ) +} + +/** + * `workspace.list`: Git worktrees (and folder projects), then project-group folders. With + * `includeStatus`, each row Orca has a status for carries it. `statusSource` keys the shared + * status listing (the runtime RPC the call came through). + */ +export async function listPluginWorkspaces( + call: PluginRuntimeRpc, + includeStatus: boolean, + statusSource: PluginStatusListingOwner = call +): Promise { + const [listed, repos, folderList, statuses] = await Promise.all([ + call('worktree.list', { limit: PLUGIN_WORKSPACE_LIST_LIMIT }), + call('repo.list', {}), + call('folderWorkspace.list', undefined), + includeStatus ? workspaceStatuses(call, statusSource) : null + ]) + const { worktrees, totalCount, truncated } = worktreeListAnswer.parse(listed) + const repoRows = repoListAnswer.parse(repos).repos + const reposById = new Map(repoRows.map((repo) => [repo.id, repo])) + // Host ids keep the values host API 1.3 shipped: the row's recorded host, else null. + const withStatus = (row: Row) => { + const status = statuses?.byId.get(row.id) + return status ? { ...row, status } : row + } + const worktreeRows = worktrees.slice(0, PLUGIN_WORKSPACE_LIST_LIMIT).map((worktree) => { + const repo = reposById.get(worktree.repoId) + const folder = repo?.kind === 'folder' + return withStatus({ + id: pluginWorkspaceId({ id: worktree.id, identityKey: worktree.identity?.key }), + kind: folder ? ('folder' as const) : ('worktree' as const), + name: worktree.displayName.slice(0, LABEL_MAX), + project: repo?.displayName?.slice(0, LABEL_MAX) || null, + projectId: worktree.repoId, + path: worktree.path, + branch: folder ? null : (branchName(worktree.branch)?.slice(0, LABEL_MAX) ?? null), + hostId: worktree.hostId ?? null + }) + }) + // Project-group folders have no repo row; their key is what selectors take. + const projectFolders = folderListAnswer.parse(folderList).folderWorkspaces.map((folder) => + withStatus({ + id: folderWorkspaceKey(folder.id), + kind: 'folder' as const, + name: folder.name.slice(0, LABEL_MAX), + project: null, + projectId: null, + path: folder.folderPath, + branch: null, + hostId: folder.executionHostId ?? null + }) + ) + const room = PLUGIN_WORKSPACE_LIST_LIMIT - worktreeRows.length + const candidates = [...worktreeRows, ...projectFolders.slice(0, room)] + const workspaces = candidates.filter(fitsBounds) + return { + workspaces, + truncated: + truncated === true || + (totalCount ?? worktrees.length) > worktreeRows.length || + projectFolders.length > room || + workspaces.length < candidates.length, + ...(statuses + ? { statusTruncated: statuses.truncated && workspaces.some((row) => !('status' in row)) } + : {}) + } +} + +/** `project.list`: the repositories and folders `repo.list` shows, which hides retired rows. */ +export async function listPluginProjects( + call: PluginRuntimeRpc +): Promise> { + const { repos } = projectListAnswer.parse(await call('repo.list', {})) + const candidates = repos.slice(0, PLUGIN_PROJECT_LIST_LIMIT).map((repo) => ({ + id: repo.id, + name: (repo.displayName ?? '').slice(0, LABEL_MAX), + kind: repo.kind === 'folder' ? ('folder' as const) : ('git' as const), + hostId: projectHostId(repo), + path: repo.path, + hidden: isRepoHidden(repo) + })) + const projects = candidates.filter((project) => project.id.length > 0 && fitsBounds(project)) + return { + projects, + truncated: repos.length > PLUGIN_PROJECT_LIST_LIMIT || projects.length < candidates.length + } +} diff --git a/src/main/plugins/workers/host-api/plugin-host-workspace-method-bindings.ts b/src/main/plugins/workers/host-api/plugin-host-workspace-method-bindings.ts index 94bd8579a74..2a34d5a165b 100644 --- a/src/main/plugins/workers/host-api/plugin-host-workspace-method-bindings.ts +++ b/src/main/plugins/workers/host-api/plugin-host-workspace-method-bindings.ts @@ -1,62 +1,23 @@ import { z } from 'zod' import { PLUGIN_HOST_API } from '../../../../shared/plugins/workers/plugin-host-api' -import { - PLUGIN_TERMINAL_READ_MAX_LINES, - PLUGIN_WORKSPACE_LIST_LIMIT -} from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' -import { - bind, - type BoundPluginHostMethod, - type PluginHostMethodContext -} from './plugin-host-method-bind' -import type { PluginHostServices } from './plugin-host-method-bindings' +import { PLUGIN_TERMINAL_READ_MAX_LINES } from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { bind, type BoundPluginHostMethod } from './plugin-host-method-bind' import { PluginHostCallError } from './plugin-host-call-scope' import { claimPluginReplacedActionRun } from '../../plugin-command-replacement-deadline' -import type { PluginHostRendererActions } from '../../view/plugin-host-renderer-actions' -import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' - -/** The runtime RPC the `orca` CLI calls, run in process; rejects with the runtime's error. - * `beforeEffect` runs right before the runtime acts, after its own waits; a throw refuses it. */ -export type PluginRuntimeRpc = ( - method: string, - params: unknown, - options?: { signal?: AbortSignal; beforeEffect?: () => void } -) => Promise +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { + pluginHostEffect as effect, + pluginHostRenderer as renderer, + pluginHostRpc as rpc, + pluginWorkspaceSelector as workspaceSelector +} from './plugin-host-runtime-call' +import { listPluginProjects, listPluginWorkspaces } from './plugin-host-workspace-list' +import { recordPluginOpenedTerminal } from './plugin-opened-terminals' const api = PLUGIN_HOST_API const DEFAULT_READ_LINES = 200 // The parts of each runtime answer a host method reads; anything else is dropped. -const worktreeListAnswer = z.object({ - worktrees: z.array( - z.object({ - id: z.string(), - repoId: z.string(), - displayName: z.string(), - path: z.string(), - branch: z.string().optional(), - hostId: z.string().optional(), - identity: z.object({ key: z.string() }).optional() - }) - ), - totalCount: z.number().optional(), - truncated: z.boolean().optional() -}) -const repoListAnswer = z.object({ - repos: z.array( - z.object({ id: z.string(), kind: z.string().optional(), displayName: z.string().optional() }) - ) -}) -const folderListAnswer = z.object({ - folderWorkspaces: z.array( - z.object({ - id: z.string(), - name: z.string(), - folderPath: z.string(), - executionHostId: z.string().nullable().optional() - }) - ) -}) const folderUpdateAnswer = z.object({ folderWorkspace: z.object({ name: z.string() }).nullable() }) @@ -73,89 +34,24 @@ const agentLaunchAnswer = z.object({ outcome: z.object({ kind: z.enum(['structured', 'terminal']), handle: z.string() }) }) -function renderer(services: PluginHostServices): PluginHostRendererActions { - if (!services.renderer) { - throw new PluginHostCallError('unavailable', 'only the Orca desktop app can do this') +function failureDetail(error: unknown): string { + if (error instanceof PluginHostCallError) { + return error.detail ?? error.message } - return services.renderer -} - -function rpc(services: PluginHostServices): PluginRuntimeRpc { - if (!services.runtimeRpc) { - throw new PluginHostCallError('unavailable', 'this Orca host cannot run workspace actions') - } - return services.runtimeRpc -} - -/** A runtime call that changes something: refused if the plugin lost approval, or its worker - * cancelled the call, at any point before the runtime acts. */ -function effect(ctx: PluginHostMethodContext, method: string, params: unknown): Promise { - ctx.scope.assertActive() - return rpc(ctx.services)(method, params, { - ...(ctx.scope.signal ? { signal: ctx.scope.signal } : {}), - beforeEffect: () => ctx.scope.assertActive() - }) -} - -/** - * The selector a listed workspace id names. Ids carry their host (`identity:`, unique across - * twins on two hosts) or are folder keys; a bare id from elsewhere is taken as an exact id. - */ -function workspaceSelector(workspaceId: string): string { - return workspaceId.startsWith('identity:') ? workspaceId : `id:${workspaceId}` -} - -/** `refs/heads/main` reads as `main`; a detached or folder workspace has none. */ -function branchName(branch: string | undefined): string | null { - const name = branch?.replace(/^refs\/heads\//, '') ?? '' - return name || null + return error instanceof Error ? error.message : String(error) } export const PLUGIN_WORKSPACE_ACTION_HANDLERS = { - 'workspace.list': bind(api['workspace.list'], async (_params, { services }) => { - const call = rpc(services) - const [listed, repos, folderList] = await Promise.all([ - call('worktree.list', { limit: PLUGIN_WORKSPACE_LIST_LIMIT }), - call('repo.list', {}), - call('folderWorkspace.list', undefined) - ]) - const { worktrees, totalCount, truncated } = worktreeListAnswer.parse(listed) - const repoRows = repoListAnswer.parse(repos).repos - const folderRepos = new Set( - repoRows.filter((repo) => repo.kind === 'folder').map((repo) => repo.id) + 'workspace.list': bind(api['workspace.list'], async (params, { services }) => + listPluginWorkspaces( + rpc(services), + params?.includeStatus === true, + services.runtimeRpc ?? services ) - const projectNames = new Map(repoRows.map((repo) => [repo.id, repo.displayName || null])) - const worktreeRows = worktrees.slice(0, PLUGIN_WORKSPACE_LIST_LIMIT).map((worktree) => { - const folder = folderRepos.has(worktree.repoId) - return { - id: worktree.identity ? `identity:${worktree.identity.key}` : worktree.id, - kind: folder ? ('folder' as const) : ('worktree' as const), - name: worktree.displayName, - project: projectNames.get(worktree.repoId)?.slice(0, 512) ?? null, - path: worktree.path, - branch: folder ? null : branchName(worktree.branch), - hostId: worktree.hostId ?? null - } - }) - // Project-group folders have no repo row; their key is what selectors take. - const projectFolders = folderListAnswer.parse(folderList).folderWorkspaces.map((folder) => ({ - id: folderWorkspaceKey(folder.id), - kind: 'folder' as const, - name: folder.name, - project: null, - path: folder.folderPath, - branch: null, - hostId: folder.executionHostId ?? null - })) - const room = PLUGIN_WORKSPACE_LIST_LIMIT - worktreeRows.length - return { - workspaces: [...worktreeRows, ...projectFolders.slice(0, room)], - truncated: - truncated === true || - (totalCount ?? worktrees.length) > worktreeRows.length || - projectFolders.length > room - } - }), + ), + 'project.list': bind(api['project.list'], async (_params, { services }) => + listPluginProjects(rpc(services)) + ), 'workspace.open': bind(api['workspace.open'], async ({ workspaceId }, ctx) => { const scope = parseWorkspaceKey(workspaceId) if (scope?.type === 'folder') { @@ -209,7 +105,14 @@ export const PLUGIN_WORKSPACE_ACTION_HANDLERS = { // A mod works beside the person: never reveal or focus the new terminal. presentation: 'background' }) - return { terminalId: terminalCreateAnswer.parse(answer).terminal.handle } + const terminalId = terminalCreateAnswer.parse(answer).terminal.handle + // A plugin that lost approval, or a worker that cancelled, while the call ran gains no close + // rights from it. + ctx.scope.assertActive() + if (!ctx.scope.signal?.aborted) { + recordPluginOpenedTerminal(ctx.pluginId, terminalId) + } + return { terminalId } }), 'terminal.read': bind(api['terminal.read'], async (params, { services, scope }) => { const limit = Math.min(params.maxLines ?? DEFAULT_READ_LINES, PLUGIN_TERMINAL_READ_MAX_LINES) @@ -237,6 +140,12 @@ export const PLUGIN_WORKSPACE_ACTION_HANDLERS = { launchSource: 'plugin' }) const terminalId = agentLaunchAnswer.parse(answer).outcome.handle + // A plugin that lost approval, or a worker that cancelled, while the call ran gains no close + // rights from it. + ctx.scope.assertActive() + if (!ctx.scope.signal?.aborted) { + recordPluginOpenedTerminal(ctx.pluginId, terminalId) + } if (params.prompt) { // Delivery waits for the agent's composer (up to a minute), longer than a host call may take. void effect(ctx, 'agent.launch', { @@ -248,7 +157,7 @@ export const PLUGIN_WORKSPACE_ACTION_HANDLERS = { launchSource: 'plugin' }).catch((error: unknown) => { ctx.scope.log?.( - `agent.launch: the prompt did not reach ${terminalId}: ${error instanceof Error ? error.message : String(error)}` + `agent.launch: the prompt did not reach ${terminalId}: ${failureDetail(error)}` ) }) } diff --git a/src/main/plugins/workers/host-api/plugin-host-workspace-rename.test.ts b/src/main/plugins/workers/host-api/plugin-host-workspace-rename.test.ts index 0bac502a354..4cc836089c9 100644 --- a/src/main/plugins/workers/host-api/plugin-host-workspace-rename.test.ts +++ b/src/main/plugins/workers/host-api/plugin-host-workspace-rename.test.ts @@ -54,13 +54,6 @@ describe('workspace.rename', () => { ) }) - it('fails when no folder workspace has the id', async () => { - const rpc = vi.fn().mockResolvedValue({ folderWorkspace: null }) - expect( - await call('workspace.rename', { workspaceId: 'folder:gone', name: 'Notes' }, rpc) - ).toMatchObject({ ok: false, code: 'action_failed' }) - }) - it('refuses blank, multi-line, bidi or invisible names and plugins without workspace:write', async () => { const rpc = vi.fn() const outcomes = await Promise.all( @@ -84,39 +77,3 @@ describe('workspace.rename', () => { expect(rpc).not.toHaveBeenCalled() }) }) - -describe('workspace.list project names', () => { - it("names each worktree's project and leaves project folders without one", async () => { - const rpc = vi.fn(async (method: string) => { - if (method === 'worktree.list') { - return { - worktrees: [ - { - id: 'w1', - repoId: 'r1', - displayName: 'main', - path: '/src/app', - branch: 'refs/heads/main' - } - ] - } - } - if (method === 'repo.list') { - return { repos: [{ id: 'r1', displayName: 'App' }] } - } - return { - folderWorkspaces: [{ id: 'f1', name: 'Notes', folderPath: '/notes' }] - } - }) - const outcome = await call('workspace.list', {}, rpc, ['workspace:read']) - expect(outcome).toMatchObject({ - ok: true, - value: { - workspaces: [ - { id: 'w1', name: 'main', project: 'App', branch: 'main' }, - { id: 'folder:f1', name: 'Notes', project: null } - ] - } - }) - }) -}) diff --git a/src/main/plugins/workers/host-api/plugin-opened-terminals.ts b/src/main/plugins/workers/host-api/plugin-opened-terminals.ts new file mode 100644 index 00000000000..1d0ef7ad191 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-opened-terminals.ts @@ -0,0 +1,57 @@ +/** + * Terminals each plugin opened itself (`terminal.create`, `agent.launch`), which it may close + * wherever they are. Bounded per plugin, oldest forgotten first; cleared when the plugin is + * disabled or removed, so a re-enabled or reinstalled plugin starts with none. + */ + +export const PLUGIN_OPENED_TERMINAL_LIMIT = 128 + +const openedByPlugin = new Map>() + +export function recordPluginOpenedTerminal(pluginId: string, terminalId: string): void { + const opened = openedByPlugin.get(pluginId) ?? new Set() + opened.delete(terminalId) + opened.add(terminalId) + if (opened.size > PLUGIN_OPENED_TERMINAL_LIMIT) { + const oldest = opened.values().next() + if (!oldest.done) { + opened.delete(oldest.value) + } + } + openedByPlugin.set(pluginId, opened) +} + +export function isPluginOpenedTerminal(pluginId: string, terminalId: string): boolean { + return openedByPlugin.get(pluginId)?.has(terminalId) === true +} + +export function forgetPluginOpenedTerminal(pluginId: string, terminalId: string): void { + openedByPlugin.get(pluginId)?.delete(terminalId) +} + +export function clearPluginOpenedTerminals(pluginId: string): void { + openedByPlugin.delete(pluginId) +} + +/** Drops every plugin `keep` rejects. */ +export function prunePluginOpenedTerminals(keep: (pluginId: string) => boolean): void { + for (const pluginId of openedByPlugin.keys()) { + if (!keep(pluginId)) { + openedByPlugin.delete(pluginId) + } + } +} + +type PluginApprovalSource = { + onChanged(listener: () => void): () => void + findApprovedPlugin(pluginKey: string, allowRefreshPause?: boolean): unknown +} + +/** Forgets a plugin's terminals once it is disabled, loses consent or is removed: each notifies a + * change. Why not on worker stop: an event-driven worker is reaped and restarted between events, + * and must still close what it opened. */ +export function installPluginOpenedTerminalPruning(service: PluginApprovalSource): () => void { + return service.onChanged(() => + prunePluginOpenedTerminals((pluginKey) => service.findApprovedPlugin(pluginKey, true) !== null) + ) +} diff --git a/src/main/plugins/workers/host-api/plugin-past-session-resume.ts b/src/main/plugins/workers/host-api/plugin-past-session-resume.ts new file mode 100644 index 00000000000..7b3213e20f3 --- /dev/null +++ b/src/main/plugins/workers/host-api/plugin-past-session-resume.ts @@ -0,0 +1,128 @@ +import { join, resolve } from 'node:path' +import { z } from 'zod' +import { + aiVaultHistoryAgents, + isAiVaultAgent +} from '../../../../shared/ai-vault/contracts/ai-vault-types' +import { + aiVaultSessionAfterResumePreparation, + aiVaultTerminalResumeRequest, + aiVaultTerminalResumeResult, + type AiVaultPrepareSessionResumeArgs, + type AiVaultPrepareSessionResumeResult +} from '../../../../shared/ai-vault/resume/ai-vault-resume-preparation' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import { ProviderSession } from '../../../../shared/rpc-contract/terminal/agent-session-params' +import { codexDatedRolloutRelativePath } from '../../../codex/history/resume/codex-session-resume-home' +import type { PluginHostMethodContext } from './plugin-host-method-bind' +import { PluginHostCallError } from './plugin-host-call-scope' +import { pluginHostEffect as effect } from './plugin-host-runtime-call' +import { findPluginPastSession } from './plugin-host-agent-history-bindings' +import type { PluginHistorySession } from './plugin-agent-history' + +// The parts of the host's answer a terminal resume applies; anything else refuses it. +const preparedAnswer = z.object({ + useRealCodexHome: z.boolean(), + substituteCodexHome: z.string().optional() +}) + +/** A transcript the resume launch accepts, else none. */ +export function resumableTranscript(path: string | undefined): string | undefined { + const transcript = ProviderSession.shape.transcriptPath.safeParse(path) + return transcript.success ? transcript.data : undefined +} + +/** + * The transcript to resume from once the host prepared the session. Repinned to the selected + * account (`substituteCodexHome`): that account's hard-linked copy, since the launch picks the + * account whose home holds the transcript it is given, as the desktop pins that home. Otherwise + * the recorded transcript: for `useRealCodexHome` the launch moves a legacy session into the + * system home itself, wherever that home is configured. + */ +export function preparedResumeTranscript( + session: Pick, + result: AiVaultPrepareSessionResumeResult +): string { + const prepared = aiVaultSessionAfterResumePreparation(session, result) + if (!session.codexHome || !prepared.codexHome || prepared.codexHome === session.codexHome) { + return session.filePath + } + const rollout = codexDatedRolloutRelativePath( + join(session.codexHome, 'sessions'), + resolve(session.filePath) + ) + return rollout ? join(prepared.codexHome, 'sessions', rollout) : session.filePath +} + +async function findPastSession( + ctx: PluginHostMethodContext, + match: { agent: string; sessionId: string; workspacePath: string | null } +): Promise { + if (!isAiVaultAgent(match.agent)) { + return null + } + try { + return await findPluginPastSession(ctx, { + agents: aiVaultHistoryAgents(match.agent), + sessionId: match.sessionId, + workspacePath: match.workspacePath + }) + } catch (error) { + if (error instanceof PluginHostCallError && error.code === 'consent_required') { + throw error + } + // History that cannot be read now leaves the resume as before: by id. + const detail = error instanceof PluginHostCallError ? (error.detail ?? error.message) : error + ctx.scope.log?.(`agent.resume: Agent Session History is unavailable: ${String(detail)}`) + return null + } +} + +/** + * A session no pane runs, readied as Orca's own terminal Resume from Agent Session History + * readies it (the same request and answer handling): an older Codex home's transcript moved + * where `codex resume` finds it, a session repinned to the selected account, a session an Orca + * chat owns refused. Answers the transcript to resume from, or undefined when this computer's + * history does not list the session: the agent then resumes it by id. + */ +export async function preparePluginPastSession( + ctx: PluginHostMethodContext, + match: { agent: string; sessionId: string; workspacePath: string | null } +): Promise { + const session = await findPastSession(ctx, match) + if (!session || !isAiVaultAgent(session.agent)) { + return undefined + } + const args: AiVaultPrepareSessionResumeArgs = { + agent: session.agent, + sessionId: session.sessionId, + filePath: session.filePath, + codexHome: session.codexHome, + executionHostId: LOCAL_EXECUTION_HOST_ID + } + let result: AiVaultPrepareSessionResumeResult + try { + const answer = await effect( + ctx, + 'aiVault.prepareSessionResume', + aiVaultTerminalResumeRequest(args) + ) + const parsed = preparedAnswer.safeParse(answer) + result = aiVaultTerminalResumeResult(args, parsed.success ? parsed.data : null) + } catch (error) { + if (error instanceof PluginHostCallError && error.code === 'consent_required') { + throw error + } + if (error instanceof Error && error.name === 'AbortError') { + throw error + } + throw new PluginHostCallError( + 'action_failed', + 'Orca could not prepare this session to resume', + undefined, + error instanceof PluginHostCallError ? (error.detail ?? error.message) : String(error), + { cause: error } + ) + } + return resumableTranscript(preparedResumeTranscript(session, result)) +} diff --git a/src/main/plugins/workers/host-api/plugin-workspace-projection.ts b/src/main/plugins/workers/host-api/plugin-workspace-projection.ts index 2626411e2c8..7ffce98336f 100644 --- a/src/main/plugins/workers/host-api/plugin-workspace-projection.ts +++ b/src/main/plugins/workers/host-api/plugin-workspace-projection.ts @@ -1,12 +1,25 @@ import type { z } from 'zod' -import { shortPluginBranchName } from '../../../../shared/plugins/events/plugin-events' +import { + shortPluginBranchName, + workspaceChangedPayloadSchema +} from '../../../../shared/plugins/events/plugin-events' +import type { PluginEventName } from '../../../../shared/plugins/manifest/plugin-manifest' import { PLUGIN_TERMINAL_ID_MAX_LENGTH, PLUGIN_WORKSPACE_LABEL_MAX_LENGTH, PLUGIN_WORKSPACE_TERMINAL_LIMIT, type pluginWorkspaceContextSchema } from '../../../../shared/plugins/workers/plugin-host-api' -import { PLUGIN_AGENT_LIST_LIMIT } from '../../../../shared/plugins/workers/plugin-host-api-panel-methods' +import { + PLUGIN_AGENT_LIST_LIMIT, + PLUGIN_AGENT_TASK_TITLE_MAX, + pluginAgentSessionIdSchema +} from '../../../../shared/plugins/workers/plugin-host-api-panel-methods' +import { + PLUGIN_HOST_ID_MAX_LENGTH, + pluginWorkspaceId +} from '../../../../shared/plugins/workers/plugin-host-api-workspace-methods' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import type { AgentStatusState } from '../../../../shared/agent-status/contracts/agent-status-types' /** One terminal of a workspace, as main's runtime lists it. */ @@ -27,11 +40,23 @@ export type PluginAgentStatusRow = { agentType?: string stateStartedAt: number providerSessionOnly?: boolean + /** The SSH connection the pane runs on; null or absent on this machine. */ + connectionId?: string | null + /** The agent's own session, which a resume names. */ + providerSession?: { id: string; transcriptPath?: string } } export type PluginWorkspaceContext = z.output -type Context = { worktreeId: string; branch: string; displayName: string } +type Context = { worktreeId: string; identityKey?: string; branch: string; displayName: string } + +/** The session id a plugin may see: what `agent.resume` accepts, else none. */ +export function pluginAgentSessionId( + session: { id: string } | null | undefined +): string | undefined { + const id = session?.id + return id && pluginAgentSessionIdSchema.safeParse(id).success ? id : undefined +} /** A pane's own name wins over the title its program sets. */ export function pluginTerminalTitle(terminal: { @@ -42,7 +67,39 @@ export function pluginTerminalTitle(terminal: { return title ? title.slice(0, PLUGIN_WORKSPACE_LABEL_MAX_LENGTH) : undefined } -/** Worktree ids embed provider paths: only these public fields reach plugins. */ +/** The id `workspace.list` gives, or undefined when it exceeds the public bound. */ +export function pluginListedWorkspaceId(row: { + id: string + identityKey?: string | null +}): string | undefined { + const id = pluginWorkspaceId(row) + return id.length <= PLUGIN_HOST_ID_MAX_LENGTH ? id : undefined +} + +/** + * What a frame (panel, editor) may see of a context: no raw workspace id, which embeds the + * workspace's path. Only the path-free forms (`identity:`, `folder:`) reach frames. + */ +export function pluginFrameWorkspaceContext( + context: PluginWorkspaceContext +): PluginWorkspaceContext { + const id = context?.workspaceId + if (!context || !id || id.startsWith('identity:') || parseWorkspaceKey(id)?.type === 'folder') { + return context + } + const { workspaceId: _rawId, ...pathFree } = context + return pathFree +} + +/** An event payload as frames get it: `workspace.changed` without a raw workspace id. */ +export function pluginFrameEventPayload(event: PluginEventName, payload: unknown): unknown { + const changed = event === 'workspace.changed' && workspaceChangedPayloadSchema.safeParse(payload) + return changed && changed.success + ? { context: pluginFrameWorkspaceContext(changed.data.context) } + : payload +} + +/** Only these public fields reach plugins; the id is the one `workspace.list` gives. */ export function projectPluginWorkspaceContext( context: Context | null, terminals: readonly PluginWorkspaceTerminal[] @@ -50,7 +107,12 @@ export function projectPluginWorkspaceContext( if (!context) { return null } + const workspaceId = pluginListedWorkspaceId({ + id: context.worktreeId, + identityKey: context.identityKey + }) return { + ...(workspaceId ? { workspaceId } : {}), branch: shortPluginBranchName(context.branch).slice(0, PLUGIN_WORKSPACE_LABEL_MAX_LENGTH), displayName: context.displayName.slice(0, PLUGIN_WORKSPACE_LABEL_MAX_LENGTH), terminals: terminals @@ -75,20 +137,27 @@ export function terminalForPane( export function projectPluginWorkspaceAgents( worktreeId: string, terminals: readonly PluginWorkspaceTerminal[], - rows: readonly PluginAgentStatusRow[] + rows: readonly PluginAgentStatusRow[], + readTaskTitles: () => ReadonlyMap = () => new Map() ) { - return rows + const listed = rows .filter((row) => row.worktreeId === worktreeId && row.providerSessionOnly !== true) .toSorted((a, b) => b.stateStartedAt - a.stateStartedAt) .slice(0, PLUGIN_AGENT_LIST_LIMIT) - .map((row) => { - const terminal = terminalForPane(terminals, row) - return { - terminalId: terminal?.id ?? null, - title: terminal?.title ?? null, - agent: row.agentType?.slice(0, 128) ?? null, - state: row.state, - stateStartedAt: row.stateStartedAt - } - }) + const taskTitles = listed.length > 0 ? readTaskTitles() : new Map() + return listed.map((row) => { + const terminal = terminalForPane(terminals, row) + const taskTitle = taskTitles.get(row.paneKey) + return { + terminalId: terminal?.id ?? null, + title: terminal?.title ?? null, + agent: row.agentType?.slice(0, 128) ?? null, + state: row.state, + stateStartedAt: row.stateStartedAt, + sessionId: pluginAgentSessionId(row.providerSession) ?? null, + // Only that it is a dispatched task, and its title: never the dispatch's own records. + task: + taskTitle === undefined ? null : { title: taskTitle.slice(0, PLUGIN_AGENT_TASK_TITLE_MAX) } + } + }) } diff --git a/src/main/plugins/workers/parent-process/plugin-host-process-types.ts b/src/main/plugins/workers/parent-process/plugin-host-process-types.ts index 8a1f6fb6252..c606e6367ab 100644 --- a/src/main/plugins/workers/parent-process/plugin-host-process-types.ts +++ b/src/main/plugins/workers/parent-process/plugin-host-process-types.ts @@ -57,6 +57,8 @@ export type StartPluginWorkerOptions = { /** Caller-resolved compiled entry path. */ entryPath: string grantedCapabilities: readonly PluginCapabilityKind[] + /** A development plugin, whose `host.has` also answers for proposed methods. */ + allowProposed?: boolean executeHostCall: PluginWorkerHostCallExecutor /** `orca.panels.post` from this worker, already shape-checked. */ onPanelPost?: (post: PluginWorkerPanelPost) => void diff --git a/src/main/plugins/workers/parent-process/plugin-host-process.ts b/src/main/plugins/workers/parent-process/plugin-host-process.ts index 8195d8dc7ef..1e38aa03f98 100644 --- a/src/main/plugins/workers/parent-process/plugin-host-process.ts +++ b/src/main/plugins/workers/parent-process/plugin-host-process.ts @@ -199,7 +199,8 @@ export async function startPluginWorker( pluginId, pluginRoot: rootDir, mainEntry, - grantedCapabilities: [...options.grantedCapabilities] + grantedCapabilities: [...options.grantedCapabilities], + ...(options.allowProposed ? { allowProposed: true } : {}) }) ) if (options.signal?.aborted) { diff --git a/src/main/plugins/workers/worker-admission/plugin-worker-spawn-spec.ts b/src/main/plugins/workers/worker-admission/plugin-worker-spawn-spec.ts index 0faee624efc..3b068500567 100644 --- a/src/main/plugins/workers/worker-admission/plugin-worker-spawn-spec.ts +++ b/src/main/plugins/workers/worker-admission/plugin-worker-spawn-spec.ts @@ -17,7 +17,7 @@ export function buildPluginWorkerSpawnSpec( // Dev roots survive manifest changes; include revision to prevent stale worker reuse. manifestRevision: JSON.stringify(plugin.manifest), reviewedContentHash: plugin.contentHash ?? plugin.consentContentHash ?? null, - ...(plugin.isDev ? { devRevision: plugin.devRevision ?? null } : {}), + ...(plugin.isDev ? { devRevision: plugin.devRevision ?? null, allowProposed: true } : {}), ...(pluginNeedsResidentWorker(plugin.manifest) ? { keepWarm: true as const } : {}), grantedCapabilities } diff --git a/src/main/plugins/workers/worker-supervision/plugin-worker-startup.ts b/src/main/plugins/workers/worker-supervision/plugin-worker-startup.ts index 06f65628e64..d35aab9ed2d 100644 --- a/src/main/plugins/workers/worker-supervision/plugin-worker-startup.ts +++ b/src/main/plugins/workers/worker-supervision/plugin-worker-startup.ts @@ -18,6 +18,8 @@ export type PluginWorkerSpawnSpec = { /** Dev tree hash; reviewed content is null for dev trees, so code edits need their own revision. */ devRevision?: string | null grantedCapabilities: readonly PluginCapabilityKind[] + /** A development plugin: `host.has` also answers for proposed methods. */ + allowProposed?: true /** Not reaped when idle: Orca waits on it (hooks), so a cold start must not be on that path. */ keepWarm?: true } @@ -35,6 +37,7 @@ export type PluginWorkerFactory = (options: { mainEntry: string entryPath: string grantedCapabilities: readonly PluginCapabilityKind[] + allowProposed?: boolean executeHostCall: PluginWorkerHostCallExecutor onPanelPost?: (post: PluginWorkerPanelPost) => void log: PluginWorkerLogSink @@ -79,6 +82,7 @@ export async function startPluginWorkerAttempt(options: { mainEntry: options.spec.mainEntry, entryPath: options.entryPath, grantedCapabilities: options.spec.grantedCapabilities, + allowProposed: options.spec.allowProposed === true, executeHostCall: options.executeHostCall, onPanelPost: options.onPanelPost, log: options.log, diff --git a/src/main/preflight/agent-detection.ts b/src/main/preflight/agent-detection.ts index 094045de7b2..c73172badfc 100644 --- a/src/main/preflight/agent-detection.ts +++ b/src/main/preflight/agent-detection.ts @@ -3,7 +3,10 @@ import type { PathSource, ShellHydrationFailureReason } from '../../shared/shell/launch/shell-path-hydration-types' -import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' +import { + hydrateShellPath, + mergePathSegments +} from '../startup/shell-environment/hydrate-shell-path' import { getAzureDevOpsAuthStatus } from '../azure-devops/client' import { getBitbucketAuthStatus } from '../bitbucket/client' import { getGiteaAuthStatus } from '../gitea/client' diff --git a/src/main/preflight/codex-workspace-relative-path.test.ts b/src/main/preflight/codex-workspace-relative-path.test.ts index 7999dde364d..0e8839a0767 100644 --- a/src/main/preflight/codex-workspace-relative-path.test.ts +++ b/src/main/preflight/codex-workspace-relative-path.test.ts @@ -2,25 +2,12 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentSessionRecordFixture } from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { codexProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { runProcess } from '@orca/process-host' -import { - createCodexStructuredLaunchResolver, - TEST_SPAWN_TOKEN -} from '../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { - readCodexCliVersion, - withSupportedCodexCli -} from '../codex/structured/launch/codex-cli-installation-error' -import { resolveStructuredAgentCommand } from '../native-chat/structured-agent-command-resolution' -import { resolveTuiAgentLaunchEnv } from '../../shared/agent-launch/choices/tui-agent-launch-defaults' -import { createStructuredAgentEnvironmentResolvers } from '../runtime/agent-session/environment/structured-agent-shell-environment' -import { identityFor } from '../codex/structured/session-lifecycle/codex-structured-session-adapter-fixture' + +import { readCodexCliVersion } from '../codex/structured/launch/codex-cli-installation-error' + import type * as CommandResolution from '../../shared/node-cli-command-resolution' -vi.mock('../startup/login-shell-environment', () => ({ +vi.mock('../startup/shell-environment/login-shell-environment', () => ({ resolveLoginShellEnvironment: async () => ({}) })) vi.mock('../../shared/node-cli-command-resolution', async (original) => { @@ -40,77 +27,6 @@ afterEach(async () => { }) describe.skipIf(process.platform === 'win32')('workspace-relative Codex selection', () => { - it.each(['bin', 'node_modules/.bin', '.'])( - 'admits the child selected through PATH=%s and recovers once it is updated', - async (entry) => { - root = await mkdtemp(join(tmpdir(), 'codex-relative-path-')) - const cwd = root - const directory = join(cwd, entry) - await mkdir(directory, { recursive: true }) - const program = join(directory, 'codex') - const versionFile = `${program}.version` - await writeFile(versionFile, '0.136.0') - await writeFile( - program, - `#!${process.execPath}\nconst fs = require('node:fs')\n` + - `const file = __filename + '.version'\n` + - `console.log('codex-cli ' + fs.readFileSync(file, 'utf8'))\n`, - { mode: 0o755 } - ) - const settings = { agentDefaultEnv: { codex: { PATH: entry } } } - const sources = { - resolveCommand: (options?: { pathEnv?: string | null; homePath?: string }) => - resolveStructuredAgentCommand('codex', settings, options), - resolveAgentLaunchEnv: () => resolveTuiAgentLaunchEnv('codex', settings) - } - const environment = createStructuredAgentEnvironmentResolvers(sources) - const record: AgentSessionRecord = { - ...agentSessionRecordFixture(), - provider: 'codex' as const, - providerHandleChain: [], - accountHome: { variable: 'CODEX_HOME' as const, path: join(cwd, 'account') }, - location: { ...agentSessionRecordFixture().location, workspaceKind: 'folder' as const } - } - const resolve = withSupportedCodexCli( - createCodexStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveCommand: sources.resolveCommand, - resolveEnvironment: () => environment.resolveAgentEnvironment('codex'), - resolveLaunchArgs: () => [], - resolveWorkspacePath: async () => cwd - }) - ) - for (const resume of [false, true]) { - const value = agentSessionRecordFixture() - record.providerHandleChain = resume - ? [{ ...value.providerHandleChain[0], handle: codexProviderHandle('thread') }] - : [] - const launch = await resolve({ - identity: identityFor(record.sessionId), - spawnToken: TEST_SPAWN_TOKEN - }) - const actual = await runProcess({ - program: launch.command, - cwd: launch.cwd, - env: launch.env, - args: ['--version'] - }) - expect(actual.code).toBe(0) - expect(actual.stdout.trim()).toBe('codex-cli 0.136.0') - await writeFile(versionFile, '0.135.0') - await expect( - resolve({ identity: identityFor(record.sessionId), spawnToken: TEST_SPAWN_TOKEN }) - ).rejects.toThrow('0.135.0') - await writeFile(versionFile, '0.136.0') - await expect( - resolve({ identity: identityFor(record.sessionId), spawnToken: TEST_SPAWN_TOKEN }) - ).resolves.toMatchObject({ - cwd - }) - } - } - ) - it('resolves a relative command path before probing it', async () => { root = await mkdtemp(join(tmpdir(), 'codex-relative-command-')) await mkdir(join(root, 'bin')) diff --git a/src/main/preflight/workspace-agent-detection.ts b/src/main/preflight/workspace-agent-detection.ts index ff5db58b8d5..6b73d7486d9 100644 --- a/src/main/preflight/workspace-agent-detection.ts +++ b/src/main/preflight/workspace-agent-detection.ts @@ -1,5 +1,5 @@ import { isFolderRepo } from '../../shared/repo-kind' -import type { ProjectLaunchContext } from '../../shared/rpc-contract/preflight-params' +import type { ProjectLaunchContext } from '../../shared/rpc-contract/preflight/preflight-params' import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' import { WORKSPACE_ON_OTHER_RUNTIME } from '../../shared/protocol-version' import { refreshAtRestCommandContext } from '../native-chat/agent-session-wire/options/at-rest-command-context' diff --git a/src/main/provider-process/managed-provider-writer-close.test.ts b/src/main/provider-process/managed-provider-writer-close.test.ts deleted file mode 100644 index c3e0bf4730f..00000000000 --- a/src/main/provider-process/managed-provider-writer-close.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child' -import { createClaudeChildTreeReaper } from '../claude/claude-agent-sdk-exit-proof' -import { claudeChildCloseProven } from '../claude/claude-child-exit-proof-ladder' -import { spawnManagedProviderProcess } from './managed-provider-process' - -const taskkill = vi.hoisted(() => vi.fn(async () => false)) -vi.mock('../pty/process-retirement/windows-process-tree-kill', () => ({ - terminateWindowsProcessTree: taskkill -})) - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - taskkill.mockReset() -}) - -function fixture(strict = false) { - const child = createFakePipedChild(424242) - vi.spyOn(child, 'kill').mockReturnValue(true) - const managed = spawnManagedProviderProcess( - { command: 'fixture', args: [] }, - { - spawnImpl: () => child, - platform: 'win32', - site: 'fixture', - policy: () => ({ gracefulExitMs: 10, forcedExitMs: 5 }), - ...(strict ? { acceptClose: claudeChildCloseProven } : {}) - } - ) - return { child, managed } -} - -it('retains irreversible delivery through explicit strict cleanup retries without delaying writer joins', async () => { - vi.useFakeTimers() - const { managed, child } = fixture(true) - const kill = vi.fn().mockResolvedValueOnce(true).mockResolvedValue(false) - const tree = createClaudeChildTreeReaper(child, { - site: 'claude-structured-child-close', - platform: 'win32', - terminateWindowsTree: kill - }) - const first = managed.close(tree) - await vi.advanceTimersByTimeAsync(15) - expect(await first).toMatchObject({ root: 'live', killDelivered: true }) - const retry = managed.close(tree) - const writer = managed.closeWriter(tree) - await expect(writer).resolves.toMatchObject({ root: 'live', killDelivered: true }) - await vi.advanceTimersByTimeAsync(15) - expect(await retry).toMatchObject({ root: 'live', killDelivered: true }) - expect(kill).toHaveBeenCalledTimes(2) - child.emit('exit', 0, null) - await expect(managed.close(tree)).resolves.toMatchObject({ root: 'exited', killDelivered: true }) - await expect(managed.closeWriter(tree)).resolves.toMatchObject({ - root: 'exited', - killDelivered: true - }) - expect(kill).toHaveBeenCalledTimes(2) - const replacement = fixture().managed.close() - await vi.advanceTimersByTimeAsync(15) - expect(await replacement).not.toHaveProperty('killDelivered') -}) diff --git a/src/main/provider-process/provider-tree-kill-attribution.test.ts b/src/main/provider-process/provider-tree-kill-attribution.test.ts deleted file mode 100644 index 45a4fe286a6..00000000000 --- a/src/main/provider-process/provider-tree-kill-attribution.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child' -import { spawnCodexAppServerConnection } from '../codex/app-server/codex-app-server-connection' -import { proveClaudeChildExit } from '../claude/claude-agent-sdk-exit-proof' -import { - findSelfInitiatedTreeKills, - resetSelfInitiatedTreeKillLogForTest -} from '../crash-reporting/process-exits/self-initiated-tree-kill-log' -import { spawnManagedProviderProcess } from './managed-provider-process' - -vi.mock('node:child_process', async (importOriginal) => ({ - ...(await importOriginal>()), - execFile: vi.fn( - (_file: string, _args: string[], _options: unknown, callback: (error: Error | null) => void) => - callback(null) - ) -})) - -const platform = Object.getOwnPropertyDescriptor(process, 'platform')! - -afterEach(() => { - Object.defineProperty(process, 'platform', platform) - vi.useRealTimers() - resetSelfInitiatedTreeKillLogForTest() -}) - -it('attributes forced Windows child closes to their owning agent and path', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - vi.useFakeTimers() - resetSelfInitiatedTreeKillLogForTest() - const codexChild = createFakePipedChild(424242) - const codex = await spawnCodexAppServerConnection( - { command: 'codex', args: ['app-server'] }, - {}, - () => codexChild - ) - const claudeChild = createFakePipedChild(424243) - const claude = spawnManagedProviderProcess( - { command: 'claude', args: [] }, - { spawnImpl: () => claudeChild, site: 'claude-stream-json-teardown' } - ) - const closes = Promise.all([codex.close(), proveClaudeChildExit({ managed: claude })]) - await vi.runAllTimersAsync() - await closes - - expect(findSelfInitiatedTreeKills(Date.now())).toEqual([ - { - pid: 424242, - site: 'codex-app-server-child-close', - scope: 'win-taskkill-tree', - at: expect.any(Number) - }, - { - pid: 424243, - site: 'claude-structured-child-close', - scope: 'win-taskkill-tree', - at: expect.any(Number) - } - ]) -}) diff --git a/src/main/providers/accounts/provider-account-services.ts b/src/main/providers/accounts/provider-account-services.ts index 99b32924dfa..65bcb2c0ca9 100644 --- a/src/main/providers/accounts/provider-account-services.ts +++ b/src/main/providers/accounts/provider-account-services.ts @@ -21,7 +21,7 @@ import { setAntigravityNativeCredentialChangeListener } from '../../antigravity/native-account-host' import { createAccountRuntimeTargetSettingsSync } from '../../rate-limits/service/account-runtime-target-sync' -import { normalizeCodexRuntimeSelection } from '../../codex-accounts/runtime-selection' +import { normalizeCodexRuntimeSelection } from '../../codex-accounts/account-management/runtime-selection' import { normalizeClaudeRuntimeSelection } from '../../claude-accounts/selection/runtime-selection' import type { ClaudeStatusLineRateLimits } from '../../../shared/claude-statusline-rate-limits' @@ -69,6 +69,18 @@ export function createProviderAccountServices( ) store.onSettingsChanged((updates, settings) => { void agentView.reconcile(settings) + if (updates.claudeOAuthUsageEnabled === false) { + rateLimits.discardClaudeOAuthUsage() + } else if (updates.claudeOAuthUsageEnabled === true) { + void rateLimits + .refreshClaudeForTarget(rateLimits.getState().claudeTarget) + .catch((error: unknown) => { + console.warn( + '[rate-limits] Failed to refresh Claude usage after enabling polling:', + error + ) + }) + } // Auto runtime selection remains live as provider settings change. void syncAccountRuntimeTargets(updates, settings).catch((error) => console.warn('[rate-limits] Failed to apply account runtime target:', error) @@ -137,6 +149,7 @@ export function createProviderAccountServices( apiKey: readZcodePlanApiKey() ?? '' })) rateLimits.setGeminiCliOAuthEnabledResolver(() => store.getSettings().geminiCliOAuthEnabled) + rateLimits.setClaudeOAuthUsageEnabledResolver(() => store.getSettings().claudeOAuthUsageEnabled) // Reuse the meter switch so hidden Antigravity usage does not spawn agy. rateLimits.setAntigravityUsageEnabledResolver(() => store.getUI().statusBarItems.includes('antigravity') diff --git a/src/main/providers/agent-foreground-context-paths.ts b/src/main/providers/agent-foreground-context-paths.ts deleted file mode 100644 index 760b2933960..00000000000 --- a/src/main/providers/agent-foreground-context-paths.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { splitWorktreeIdForFilesystem } from '../../shared/worktree/id' - -export function getAgentForegroundContextPaths(options: { - cwd?: string - worktreeId?: string | null -}): string[] { - const worktreePath = options.worktreeId - ? splitWorktreeIdForFilesystem(options.worktreeId)?.worktreePath - : undefined - return [...new Set([options.cwd, worktreePath].filter((path): path is string => Boolean(path)))] -} diff --git a/src/main/providers/agent-foreground-process-batch.ts b/src/main/providers/agent-foreground-process-batch.ts deleted file mode 100644 index 4a0c97da2c9..00000000000 --- a/src/main/providers/agent-foreground-process-batch.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { - isAgentForegroundWrapperProcess, - isExpectedAgentProcess -} from '../../shared/agent-status/process/agent-process-recognition' -import { getFirstCommandToken } from '../../shared/command-token-scanner' -import { resolveOuterWrapperForegroundProcess } from '../../shared/foreground-wrapper-agent' -import { selectForegroundProcessCandidate } from '../../shared/foreground-process-selection' -import type { - ForegroundProcessEvidence, - RemoteForegroundEvidence -} from '../../shared/foreground-process-evidence' -import { - buildProcessTableIndex, - lookupProcessTableIndex, - type ProcessTableIndex, - type ProcessTableIndexStats -} from '../../shared/process-table-index' -import { unreadableArgvName, type ProcessTableRow } from '../../shared/process-table-snapshot' -import { getStrictProcessTableSnapshot } from '../../shared/process-table-snapshot-reader' -import { resolveRemoteForegroundEvidenceFromRows } from './agent-foreground-process-remote-evidence' - -export type BatchedForegroundProcessRequest = { - rootPid: number - fallbackProcess?: string | null -} - -export type BatchedForegroundProcessResult = { - available: boolean - processName: string | null - reason?: string - /** True only for a readable table with no other tty groups/stopped processes and the shell alone in its group. - * Keep the wire name for old clients; stricter proof can only reduce skipped sweeps. */ - shellOwnsEveryTtyProcessGroup?: boolean -} - -export type RemoteForegroundEvidenceOptions = { - ptyId: string - ptyIncarnationId: string - authorityGeneration: string - observationEpoch: number - capturedAgeMs: number - platform?: NodeJS.Platform -} - -/** Resolve a host-stamped, fenced observation from one complete process-table capture. */ -export function resolveRemoteForegroundEvidence( - request: BatchedForegroundProcessRequest, - options: RemoteForegroundEvidenceOptions, - rows: readonly ProcessTableRow[] -): RemoteForegroundEvidence { - return resolveRemoteForegroundEvidenceFromRows( - request, - options, - rows, - resolveAgentForegroundProcessesFromIndex - ) -} - -export type BatchedForegroundProcessOptions = { - rows?: readonly ProcessTableRow[] - readRows?: () => Promise - stats?: ProcessTableIndexStats -} - -type PaneOccupancy = { - processGroupsByTty: ReadonlyMap> - stoppedTtys: ReadonlySet - /** Count all group members: killpg also reaches members without a controlling terminal. */ - rowsByProcessGroup: ReadonlyMap - /** Missing pgid rows make group counts insufficient to prove idle. */ - processGroupsIncomplete: boolean -} - -const paneOccupancyByCapture = new WeakMap() - -/** A live tpgid identifies one controlling terminal; memoize its groups and host-wide group sizes per shared capture. */ -function getPaneOccupancy(rows: readonly ProcessTableRow[]): PaneOccupancy { - const cached = paneOccupancyByCapture.get(rows) - if (cached) { - return cached - } - const processGroupsByTty = new Map>() - const stoppedTtys = new Set() - const rowsByProcessGroup = new Map() - let processGroupsIncomplete = false - for (const row of rows) { - if (row.pgid === undefined) { - processGroupsIncomplete = true - continue - } - rowsByProcessGroup.set(row.pgid, (rowsByProcessGroup.get(row.pgid) ?? 0) + 1) - if (row.tpgid === undefined || row.tpgid <= 0) { - continue - } - let groups = processGroupsByTty.get(row.tpgid) - if (!groups) { - groups = new Set() - processGroupsByTty.set(row.tpgid, groups) - } - groups.add(row.pgid) - // `T` is a job-control stop (Ctrl-Z), `t` a tracing stop. Both are work the pane still holds. - if (row.stat.startsWith('T') || row.stat.startsWith('t')) { - stoppedTtys.add(row.tpgid) - } - } - const occupancy: PaneOccupancy = { - processGroupsByTty, - stoppedTtys, - rowsByProcessGroup, - processGroupsIncomplete - } - paneOccupancyByCapture.set(rows, occupancy) - return occupancy -} - -export async function resolveAgentForegroundProcessesBatch( - requests: readonly BatchedForegroundProcessRequest[], - options: BatchedForegroundProcessOptions = {} -): Promise { - let rows = options.rows - if (!rows) { - if (options.stats) { - options.stats.captures = (options.stats.captures ?? 0) + 1 - } - rows = await (options.readRows?.() ?? getStrictProcessTableSnapshot()) - } - const index = buildProcessTableIndex(rows, options.stats) - return resolveAgentForegroundProcessesFromIndex(index, requests) -} - -export function resolveAgentForegroundProcessesFromIndex( - index: ProcessTableIndex, - requests: readonly BatchedForegroundProcessRequest[] -): BatchedForegroundProcessResult[] { - const uniqueRoots = new Set() - for (const request of requests) { - uniqueRoots.add(request.rootPid) - } - const rootsByPid = new Set(uniqueRoots) - const depthByPid = new Map() - const rowsByOwner = new Map() - const queue: { row: ProcessTableRow; owner: number; depth: number }[] = [] - for (const rootPid of uniqueRoots) { - const root = lookupProcessTableIndex(index, (value) => value.byPid.get(rootPid)) - if (root) { - depthByPid.set(root.pid, 0) - queue.push({ row: root, owner: root.pid, depth: 0 }) - } - } - for (let cursor = 0; cursor < queue.length; cursor += 1) { - const current = queue[cursor] - const owned = rowsByOwner.get(current.owner) ?? [] - if (current.depth > 0) { - owned.push({ ...current.row, depth: current.depth }) - } - rowsByOwner.set(current.owner, owned) - const children = lookupProcessTableIndex( - index, - (value) => value.childrenByPpid.get(current.row.pid) ?? [] - ) - for (const child of children) { - const childOwner = rootsByPid.has(child.pid) ? child.pid : current.owner - const childDepth = rootsByPid.has(child.pid) ? 0 : current.depth + 1 - const priorDepth = depthByPid.get(child.pid) - if (priorDepth !== undefined && priorDepth <= childDepth) { - continue - } - depthByPid.set(child.pid, childDepth) - queue.push({ row: child, owner: childOwner, depth: childDepth }) - } - } - - const occupancy = getPaneOccupancy(index.rows) - return requests.map((request) => { - const root = lookupProcessTableIndex(index, (value) => value.byPid.get(request.rootPid)) - if (!root) { - return { - available: false, - processName: request.fallbackProcess ?? null, - reason: 'root_missing' - } - } - if (root.pgid === undefined || root.tpgid === undefined) { - return { - available: false, - processName: request.fallbackProcess ?? null, - reason: 'correlation_unavailable' - } - } - if (root.tpgid === 0 || root.tpgid === -1) { - return { - available: false, - processName: request.fallbackProcess ?? null, - reason: 'no_controlling_tty' - } - } - // Sweep authorization needs both: no other tty group (background/stopped jobs), and no other shell-group member - // anywhere (job control off, detached/reparented children). Missing evidence never proves idle. - // Capture age bounds races with new work; ps permission/namespace omissions remain unobservable despite killpg reach. - const ttyProcessGroups = occupancy.processGroupsByTty.get(root.tpgid) - const shellOwnsEveryTtyProcessGroup = - root.tpgid === root.pgid && - ttyProcessGroups !== undefined && - ttyProcessGroups.size === 1 && - ttyProcessGroups.has(root.pgid) && - !occupancy.stoppedTtys.has(root.tpgid) && - !occupancy.processGroupsIncomplete && - // The root counts itself; exactly one group member excludes all other killpg targets. - occupancy.rowsByProcessGroup.get(root.pgid) === 1 - const allCandidates = rowsByOwner.get(root.pid) ?? [] - const foregroundCandidates = allCandidates.filter((row) => row.pgid === root.tpgid) - // A foreground process whose argv ps withheld could be the agent: absence of a name proves nothing. - if (foregroundCandidates.some((row) => unreadableArgvName(row.command) !== null)) { - return { - available: false, - processName: request.fallbackProcess ?? null, - reason: 'argv_unreadable' - } - } - const fallbackProcess = request.fallbackProcess - const wrapperFallback = - typeof fallbackProcess === 'string' && isAgentForegroundWrapperProcess(fallbackProcess) - const candidates = wrapperFallback - ? foregroundCandidates.filter((candidate) => - isExpectedAgentProcess(getFirstCommandToken(candidate.command), fallbackProcess) - ) - : foregroundCandidates - if (wrapperFallback && candidates.length !== 1) { - return { available: true, processName: null, shellOwnsEveryTtyProcessGroup } - } - const selected = selectForegroundProcessCandidate(candidates, allCandidates) - if (selected) { - return { - available: true, - processName: resolveOuterWrapperForegroundProcess( - selected.recognized, - selected.candidate, - allCandidates - ), - shellOwnsEveryTtyProcessGroup - } - } - return { available: true, processName: null, shellOwnsEveryTtyProcessGroup } - }) -} - -export function toForegroundProcessEvidence( - result: BatchedForegroundProcessResult, - metadata: { authorityGeneration: string; observationEpoch: number; capturedAgeMs: number } -): ForegroundProcessEvidence { - return result.available - ? { - ...metadata, - verdict: 'live', - processName: result.processName, - ...(result.shellOwnsEveryTtyProcessGroup !== undefined - ? { shellOwnsEveryTtyProcessGroup: result.shellOwnsEveryTtyProcessGroup } - : {}) - } - : { - ...metadata, - verdict: 'unverifiable', - reason: result.reason ?? 'correlation_unavailable' - } -} diff --git a/src/main/providers/agent-foreground-process-git-bash.win32.test.ts b/src/main/providers/agent-foreground-process-git-bash.win32.test.ts deleted file mode 100644 index a24969fd38f..00000000000 --- a/src/main/providers/agent-foreground-process-git-bash.win32.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { mkdtempSync, rmdirSync, symlinkSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' -import { confirmPtyShellForeground } from '../daemon/pty-subprocess/pty-shell-foreground-confirmation' -import { - createPtyShellLaunchPlan, - type PtyShellLaunchPlan -} from '../daemon/pty-subprocess/shell-launch-plan' -import { spawnNativeDaemonPty } from '../daemon/pty-subprocess/native-pty-spawn' -import { createDaemonPtyEnvironment } from '../daemon/pty-subprocess/spawn-environment' -import { inspectSpawnFileWindowsChildProcesses } from '../daemon/pty-subprocess/spawn-file-child-processes' - -import type { PtySubprocessOptions } from '../daemon/pty-subprocess/pty-subprocess' -import { isGitForWindowsBashLauncherPath, resolveGitBashPath } from '../pty/shell-startup/git-bash' -import { readWindowsPtyJobProcessIds } from './windows-pty-job-membership' - -const describeOnWindows = process.platform === 'win32' ? describe : describe.skip - -async function spawnPlannedPane( - plan: PtyShellLaunchPlan, - env: Record, - opts: PtySubprocessOptions -): ReturnType { - return spawnNativeDaemonPty({ ...plan, env, cols: opts.cols, rows: opts.rows }) -} - -/** Drives a live pane through prompt -> foreground command -> interrupt -> background job. */ -async function proveIdlePromptCycle( - spawned: Awaited>, - expectedJobSize: number -): Promise { - const proc = spawned.process - let output = spawned.claimStartupEvents?.().data.join('') ?? '' - let dead = false - proc.onData((chunk) => { - output += chunk - }) - proc.onExit(() => { - dead = true - }) - const confirm = (): Promise => - confirmPtyShellForeground({ - process: proc, - shellPath: spawned.shellPath, - isDead: () => dead - }) - try { - await vi.waitFor(() => expect(output).toContain('$'), { timeout: 20_000 }) - await vi.waitFor(() => expect(readWindowsPtyJobProcessIds(proc)?.size).toBe(expectedJobSize), { - timeout: 5_000 - }) - await vi.waitFor(async () => expect(await confirm(), 'initial prompt').toBe(true), { - timeout: 5_000 - }) - - // Interrupt only after the child is ready, not during a transient shell fork. - proc.write( - "node -e \"console.log(['ORCA','FOREGROUND_READY'].join('_')); setInterval(() => {}, 1000)\"\r" - ) - await vi.waitFor(() => expect(output).toContain('ORCA_FOREGROUND_READY'), { - timeout: 10_000 - }) - await vi.waitFor(async () => expect(await confirm()).toBe(false), { timeout: 10_000 }) - - proc.write('\x03') - await vi.waitFor( - async () => { - expect(dead, 'terminal survived foreground interrupt').toBe(false) - expect(await confirm(), 'prompt after interrupt').toBe(true) - }, - { timeout: 10_000 } - ) - - proc.write('sleep 60 &\r') - await vi.waitFor(async () => expect(await confirm()).toBe(false), { timeout: 10_000 }) - } finally { - proc.kill() - } -} - -describeOnWindows("Git Bash launcher shell proof with Orca's real launch", () => { - let userData: string - const previousUserData = process.env.ORCA_USER_DATA_PATH - - beforeAll(() => { - // The launch plan writes shell-ready wrappers under the user-data root. - userData = mkdtempSync(join(tmpdir(), 'orca-git-bash-proof-')) - process.env.ORCA_USER_DATA_PATH = userData - }) - - afterAll(() => { - if (previousUserData === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previousUserData - } - removeTreeSync(userData) - }) - - it.each([ - ['login shell', {}], - // Why: with the Codex preflight set, the exec'd shell runs Orca's --rcfile wrapper. - ['rcfile wrapper', { ORCA_CODEX_LAUNCH_PREFLIGHT: 'C:\\orca-missing-preflight.exe' }] - ])( - 'confirms an idle %s prompt, refutes a running command, and confirms again', - async (_label, extraEnv) => { - const opts: PtySubprocessOptions = { - sessionId: 'git-bash-shell-proof', - cols: 120, - rows: 30, - cwd: tmpdir(), - shellOverride: WINDOWS_GIT_BASH_SHELL, - env: extraEnv - } - const env = createDaemonPtyEnvironment(opts) - const plan = createPtyShellLaunchPlan(opts, env) - expect(isGitForWindowsBashLauncherPath(plan.shellPath)).toBe(true) - expect(plan.shellArgs.join(' ')).toContain('exec "$BASH"') - // Launcher, exec stub, interactive bash: the shape that a size-1 or size-2 rule never matches. - await proveIdlePromptCycle(await spawnPlannedPane(plan, env, opts), 3) - }, - 60_000 - ) - - it('confirms an idle prompt for an install folder named neither Git nor PortableGit', async () => { - const discovered = resolveGitBashPath() - if (!discovered) { - throw new Error('this host has no Git for Windows install to stage') - } - expect(isGitForWindowsBashLauncherPath(discovered)).toBe(true) - // A junction, not a copy: the operator's install is neither modified nor duplicated. - const stagingRoot = mkdtempSync(join(tmpdir(), 'orca-git-renamed-')) - const stagedInstall = join(stagingRoot, 'Git-2.55') - symlinkSync(dirname(dirname(discovered)), stagedInstall, 'junction') - const opts: PtySubprocessOptions = { - sessionId: 'git-bash-renamed-shell-proof', - cols: 120, - rows: 30, - cwd: tmpdir(), - shellOverride: join(stagedInstall, 'bin', 'bash.exe') - } - try { - const env = createDaemonPtyEnvironment(opts) - const plan = createPtyShellLaunchPlan(opts, env) - expect(plan.shellPath).toBe(opts.shellOverride) - expect(isGitForWindowsBashLauncherPath(plan.shellPath)).toBe(true) - // No Git Bash startup args for an unrecognized folder, so no exec stub: launcher -> bash. - await proveIdlePromptCycle(await spawnPlannedPane(plan, env, opts), 2) - } finally { - // rmdir, never a recursive remove: it detaches the junction and cannot reach the target. - rmdirSync(stagedInstall) - removeTreeSync(stagingRoot) - } - }, 60_000) - - it('sets aside a detached ssh-agent for adoption, but not a background job', async () => { - const opts: PtySubprocessOptions = { - sessionId: 'git-bash-detached-daemon-proof', - cols: 120, - rows: 30, - cwd: tmpdir(), - shellOverride: WINDOWS_GIT_BASH_SHELL - } - const env = createDaemonPtyEnvironment(opts) - const spawned = await spawnPlannedPane(createPtyShellLaunchPlan(opts, env), env, opts) - const proc = spawned.process - let output = spawned.claimStartupEvents?.().data.join('') ?? '' - proc.onData((chunk) => { - output += chunk - }) - let agentPid = 0 - const inspect = (ignoreDetached: boolean) => - inspectSpawnFileWindowsChildProcesses(proc, spawned.shellPath, true, ignoreDetached) - try { - await vi.waitFor(() => expect(output).toContain('$'), { timeout: 20_000 }) - // ssh-agent forks, setsids off the console, and its Win32 parent exits. - proc.write('eval "$(ssh-agent -s)"; echo ORCA_AGENT_$SSH_AGENT_PID\r') - // Usually ~1s, but it exceeded 10s on a loaded runner; the bound only catches a hang. - await vi.waitFor(() => expect(output).toMatch(/ORCA_AGENT_\d+/), { timeout: 30_000 }) - agentPid = Number(/ORCA_AGENT_(\d+)/.exec(output)?.[1]) - await vi.waitFor(async () => expect(await inspect(true)).toBe('no-children'), { - timeout: 10_000 - }) - // Close checks keep the job census: the daemon still counts there. - expect(await inspect(false)).not.toBe('no-children') - - // MSYS leaves the background sleep under an exited Win32 parent too, but on the console. - proc.write('sleep 60 &\r') - await vi.waitFor(async () => expect(await inspect(true)).toBe('children'), { - timeout: 10_000 - }) - } finally { - // From inside the pane: SSH_AGENT_PID is an MSYS pid, and it outlives the pane otherwise. - if (agentPid) { - proc.write(`kill %1; kill ${agentPid}\r`) - await new Promise((resolve) => setTimeout(resolve, 500)) - } - proc.kill() - } - }, 90_000) -}) diff --git a/src/main/providers/agent-foreground-process-remote-evidence.ts b/src/main/providers/agent-foreground-process-remote-evidence.ts deleted file mode 100644 index 4f1c5ff7bfa..00000000000 --- a/src/main/providers/agent-foreground-process-remote-evidence.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { hasControllingTty } from '../../shared/posix-controlling-terminal' -import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-status/process/agent-process-recognition' -import type { - PosixFence, - RemoteForegroundEvidence, - WindowsFence -} from '../../shared/foreground-process-evidence' -import { buildProcessTableIndex, type ProcessTableIndex } from '../../shared/process-table-index' -import type { ProcessTableRow } from '../../shared/process-table-snapshot' -import type { - BatchedForegroundProcessRequest, - BatchedForegroundProcessResult, - RemoteForegroundEvidenceOptions -} from './agent-foreground-process-batch' - -type ResolveForegroundProcesses = ( - index: ProcessTableIndex, - requests: readonly BatchedForegroundProcessRequest[] -) => BatchedForegroundProcessResult[] - -/** Resolve a host-stamped, fenced observation from one complete process-table capture. */ -export function resolveRemoteForegroundEvidenceFromRows( - request: BatchedForegroundProcessRequest, - options: RemoteForegroundEvidenceOptions, - rows: readonly ProcessTableRow[], - resolveForegroundProcesses: ResolveForegroundProcesses -): RemoteForegroundEvidence { - const metadata = { - authorityGeneration: options.authorityGeneration, - observationEpoch: options.observationEpoch, - capturedAgeMs: options.capturedAgeMs, - ptyId: options.ptyId, - ptyIncarnationId: options.ptyIncarnationId - } - if (!options.ptyIncarnationId || !options.ptyId || rows.length === 0) { - return { ...metadata, verdict: 'unverifiable', reason: 'process_table_unreadable' } - } - if (options.platform === 'win32') { - // Windows SSH lacks native process-table, creation-time and ConPTY session proof; descendant names cannot authorize foreground identity. - const fence: WindowsFence = { - platform: 'windows', - rootProcessId: request.rootPid, - rootCreationTime: 'unavailable', - sessionId: 'unavailable' - } - void fence - return { ...metadata, verdict: 'unverifiable', reason: 'windows_ssh_foreground_unavailable' } - } - const root = rows.find((row) => row.pid === request.rootPid) - if (!root || root.pgid === undefined || root.tpgid === undefined) { - return { ...metadata, verdict: 'unverifiable', reason: 'anchor_missing' } - } - if (!hasControllingTty(root.tty) || root.tpgid <= 0 || !root.startTime) { - return { ...metadata, verdict: 'unverifiable', reason: 'fence_incomplete' } - } - const index = buildProcessTableIndex(rows) - const resolved = resolveForegroundProcesses(index, [request])[0] - if (!resolved?.available) { - return { - ...metadata, - verdict: 'unverifiable', - reason: resolved?.reason ?? 'capture_incomplete' - } - } - const descendants = collectDescendantRows(index, root.pid) - // Another controlling terminal falls outside this pane; its work cannot prove this shell idle. - if (descendants.some((row) => hasControllingTty(row.tty) && row.tty !== root.tty)) { - return { ...metadata, verdict: 'unverifiable', reason: 'tty_boundary' } - } - // Without a multiplexer/session fence, apparent foreground ancestry cannot establish user focus. - if ([root, ...descendants].some((row) => /(?:^|\s)(?:tmux|screen)(?:\s|$)/i.test(row.command))) { - return { ...metadata, verdict: 'unverifiable', reason: 'multiplexer_boundary' } - } - if (descendants.some((row) => row.pgid === root.tpgid && !hasControllingTty(row.tty))) { - return { ...metadata, verdict: 'unverifiable', reason: 'fence_incomplete' } - } - const foreground = descendants.filter((row) => row.pgid === root.tpgid && row.tty === root.tty) - const recognized = foreground - .map((row) => ({ row, name: recognizeAgentProcessFromCommandLine(row.command) })) - .filter( - ( - entry - ): entry is { - row: ProcessTableRow - name: NonNullable> - } => Boolean(entry.name) - ) - // One agent can hold two rows (npm Codex: node codex.js spawning native codex; Gemini relaunching itself in node): - // that names it, and the outermost row is its fence. Two different agents prove neither. - if (new Set(recognized.map((entry) => entry.name.agent)).size > 1) { - return { ...metadata, verdict: 'unverifiable', reason: 'ambiguous_foreground_group' } - } - const candidate = recognized[0] - const fence: PosixFence = { - platform: 'posix', - shellPid: root.pid, - shellStartTime: root.startTime, - tty: root.tty, - foregroundPgid: root.tpgid, - ...(candidate?.row.startTime - ? { process: { pid: candidate.row.pid, startTime: candidate.row.startTime } } - : {}) - } - if (candidate && !candidate.row.startTime) { - return { ...metadata, verdict: 'unverifiable', reason: 'candidate_start_time_missing' } - } - return { - ...metadata, - verdict: 'live', - processName: candidate?.name.processName ?? null, - fence - } -} - -function collectDescendantRows(index: ProcessTableIndex, rootPid: number): ProcessTableRow[] { - const result: ProcessTableRow[] = [] - const seen = new Set([rootPid]) - const queue = [rootPid] - for (let cursor = 0; cursor < queue.length; cursor += 1) { - const pid = queue[cursor] - for (const child of index.childrenByPpid.get(pid) ?? []) { - if (seen.has(child.pid)) { - continue - } - seen.add(child.pid) - result.push(child) - queue.push(child.pid) - } - } - return result -} diff --git a/src/main/providers/agent-foreground-process.test.ts b/src/main/providers/agent-foreground-process.test.ts deleted file mode 100644 index 35e2292f656..00000000000 --- a/src/main/providers/agent-foreground-process.test.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { execFileMock } = vi.hoisted(() => ({ - execFileMock: vi.fn() -})) - -vi.mock('child_process', () => ({ - execFile: execFileMock -})) - -const getAllProcessesMock = vi.fn() - -import { resetProcessTableSnapshotForTests } from '../../shared/process-table-snapshot-reader' -import { __setWindowsProcessTreeLoaderForTests } from '../windows/windows-process-table' -import { - confirmShellForegroundProcess, - resolveAgentForegroundProcessWithAvailability -} from './agent-foreground-process' -// Toolhelp denial may return an empty table; require the querying process to distinguish a readable snapshot. -const SELF_PROCESS_ROW = { pid: process.pid, ppid: 0, name: 'vitest.exe', commandLine: 'vitest' } -const withSelf = (rows: readonly T[]): (T | typeof SELF_PROCESS_ROW)[] => [ - SELF_PROCESS_ROW, - ...rows -] - -// Why: the POSIX reader wraps execFile with promisify, so the mock must honor -// the Node callback contract — invoke the last arg with (err, { stdout, stderr }). -function mockPs(stdout: string): void { - execFileMock.mockImplementation((_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { - const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void - callback(null, { stdout, stderr: '' }) - }) -} - -type NativeProcessRow = { - pid: number - ppid: number - name: string - commandLine?: string -} - -const DEFAULT_WINDOWS_ROWS: NativeProcessRow[] = [ - { - pid: 100, - ppid: 99, - name: 'powershell.exe', - commandLine: 'powershell.exe' - }, - { - pid: 101, - ppid: 100, - name: 'node.exe', - commandLine: 'node C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd' - } -] - -function mockWindowsRows(rows: NativeProcessRow[] = DEFAULT_WINDOWS_ROWS): void { - getAllProcessesMock.mockImplementation((cb: (snapshot: NativeProcessRow[]) => void) => { - cb(withSelf(rows)) - }) -} - -describe('resolveAgentForegroundProcess', () => { - let platform: PropertyDescriptor | undefined - - beforeEach(() => { - execFileMock.mockReset() - getAllProcessesMock.mockReset() - resetProcessTableSnapshotForTests() - // Reset the 500ms Windows snapshot cache so each case reads its own rows. - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses: getAllProcessesMock - })) - platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - }) - - afterEach(() => { - __setWindowsProcessTreeLoaderForTests() - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - }) - - // Why: OMP embeds Pi, but the outer process is the user-visible identity (#6364). - - it('rejects a foreground nested shell while the spawned shell remains suspended', async () => { - mockPs( - [ - '100 99 100 102 Ss /usr/bin/login -pfl developer /bin/zsh', - '101 100 101 102 S -zsh', - '102 101 102 102 S+ agent-tui', - '103 102 102 102 S+ /bin/zsh -i' - ].join('\n') - ) - - await expect(confirmShellForegroundProcess(100, '/bin/zsh')).resolves.toBe(false) - }) - - it('rejects shell ownership while a stopped TUI remains resumable', async () => { - mockPs(['100 99 100 100 Ss+ /bin/zsh -l', '101 100 101 100 T agent-tui'].join('\n')) - - await expect(confirmShellForegroundProcess(100, 'zsh')).resolves.toBe(false) - }) - - it('detects a foreign anchor even when the squatter is orphaned out of the descendant walk', async () => { - // PID reuse can leave the squatter outside the shell ancestry while retaining job membership. - Object.defineProperty(process, 'platform', { value: 'win32' }) - mockWindowsRows([ - { pid: 100, ppid: 99, name: 'powershell.exe', commandLine: 'powershell.exe' }, - { pid: 999, ppid: 500, name: 'node.exe', commandLine: 'node server.js' } - ]) - - await expect( - resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { - anchorProcessId: 999 - }) - ).resolves.toEqual({ - available: true, - processName: 'powershell.exe', - anchorPidForeign: true - }) - }) - - it('flags an anchor recycled by a DIFFERENT agent as foreign', async () => { - Object.defineProperty(process, 'platform', { value: 'win32' }) - mockWindowsRows([ - { pid: 100, ppid: 99, name: 'powershell.exe', commandLine: 'powershell.exe' }, - { pid: 999, ppid: 500, name: 'node.exe', commandLine: 'node /usr/bin/codex' } - ]) - - await expect( - resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { - anchorProcessId: 999, - anchorProcessName: 'claude' - }) - ).resolves.toEqual({ - available: true, - processName: 'powershell.exe', - anchorPidForeign: true - }) - }) - - it('treats a query-denied anchor row as inconclusive, never foreign', async () => { - // A denied query yields command === name; the agent may just be unreadable. - Object.defineProperty(process, 'platform', { value: 'win32' }) - mockWindowsRows([ - { pid: 100, ppid: 99, name: 'powershell.exe', commandLine: 'powershell.exe' }, - { pid: 999, ppid: 100, name: 'node.exe', commandLine: '' } - ]) - - await expect( - resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { - anchorProcessId: 999 - }) - ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) - }) - - it('filters detached agents before resolving an otherwise ambiguous ConPTY tree', async () => { - Object.defineProperty(process, 'platform', { value: 'win32' }) - mockWindowsRows([ - { - pid: 100, - ppid: 99, - name: 'powershell.exe', - commandLine: 'powershell.exe' - }, - { - pid: 101, - ppid: 100, - name: 'droid.exe', - commandLine: 'droid' - }, - { - pid: 102, - ppid: 100, - name: 'agy.exe', - commandLine: 'agy' - } - ]) - - await expect( - resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { - fresh: true, - readWindowsConsoleAttachedProcessIds: async () => new Set([100, 101]) - }) - ).resolves.toEqual({ - available: true, - processName: 'droid', - processId: 101 - }) - }) - - it('fails closed when console attachment cannot be read', async () => { - // Unreadable console attachment cannot authorize a detached descendant as the pane agent (#16419). - Object.defineProperty(process, 'platform', { value: 'win32' }) - mockWindowsRows([ - { pid: 200, ppid: 199, name: 'powershell.exe', commandLine: 'powershell.exe' }, - { pid: 201, ppid: 200, name: 'droid.exe', commandLine: 'droid' }, - { pid: 202, ppid: 200, name: 'agy.exe', commandLine: 'agy' } - ]) - - const reader = vi.fn(async () => null) - - const resolution = await resolveAgentForegroundProcessWithAvailability(200, 'powershell.exe', { - fresh: true, - readWindowsConsoleAttachedProcessIds: reader - }) - - expect(reader).toHaveBeenCalledTimes(1) - // Unavailable evidence must yield the shell fallback, never an unverified agent identity. - expect(resolution.available).toBe(false) - expect(resolution.processName).toBe('powershell.exe') - }) - - it('excludes a detached Windows Droid descendant from byte authority', async () => { - Object.defineProperty(process, 'platform', { value: 'win32' }) - mockWindowsRows([ - { - pid: 100, - ppid: 99, - name: 'powershell.exe', - commandLine: 'powershell.exe' - }, - { - pid: 101, - ppid: 100, - name: 'droid.exe', - commandLine: 'droid' - } - ]) - - await expect( - resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { - fresh: true, - readWindowsConsoleAttachedProcessIds: async () => new Set([100, 999]) - }) - ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) - }) -}) diff --git a/src/main/providers/agent-foreground-process.ts b/src/main/providers/agent-foreground-process.ts deleted file mode 100644 index 6c297662ae7..00000000000 --- a/src/main/providers/agent-foreground-process.ts +++ /dev/null @@ -1,231 +0,0 @@ -import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-status/process/agent-process-recognition' -import { resolveOuterWrapperForegroundProcess } from '../../shared/foreground-wrapper-agent' -import { unreadableArgvName, type ProcessTableRow } from '../../shared/process-table-snapshot' -import { - getFreshProcessTableSnapshot, - getFreshShellForegroundSnapshot, - getProcessTableSnapshot -} from '../../shared/process-table-snapshot-reader' -import { collectDescendantsFromIndex, getProcessTableIndex } from '../../shared/process-table-index' -import { - resolveWindowsAgentForegroundProcessWithAvailability, - shouldInspectWindowsAgentForeground, - type AgentForegroundResolutionOptions -} from './windows-agent-foreground-process' -import { isShellProcess } from '../../shared/agent-status/process/shell-process-detection' -import { - selectForegroundProcessCandidate, - type SelectedForegroundProcess -} from '../../shared/foreground-process-selection' -import { isWindowsShellAloneInJob } from './windows-shell-alone-in-job' -import { - readWindowsProcessIdentityTableFresh, - type WindowsProcessIdentityRow -} from '../windows/windows-process-table' - -export type { AgentForegroundResolutionOptions } from './windows-agent-foreground-process' -export { - resolveAgentForegroundProcessesBatch, - resolveAgentForegroundProcessesFromIndex, - resolveRemoteForegroundEvidence, - toForegroundProcessEvidence, - type BatchedForegroundProcessOptions, - type BatchedForegroundProcessRequest, - type BatchedForegroundProcessResult -} from './agent-foreground-process-batch' - -export type AgentForegroundProcessResolution = { - available: boolean - processName: string | null - /** Windows liveness anchor for an unambiguous recognized name; omitted for fallbacks and POSIX. */ - processId?: number - /** Windows: the scan proved the caller's `anchorProcessId` is now a non-agent. */ - anchorPidForeign?: boolean -} - -type ShellForegroundConfirmationOptions = { - readWindowsPtyJobProcessIds?: () => - | ReadonlySet - | null - | Promise | null> - readWindowsProcessIdentityTable?: () => Promise -} - -function commandExecutable(command: string): string { - const trimmed = command.trim().replace(/^[-]/, '') - if (trimmed.startsWith('"') || trimmed.startsWith("'")) { - const closingQuote = trimmed.indexOf(trimmed[0], 1) - return closingQuote === -1 ? trimmed.slice(1) : trimmed.slice(1, closingQuote) - } - return trimmed.split(/\s+/, 1)[0] ?? '' -} - -function executableBasename(command: string): string { - return commandExecutable(command).split(/[\\/]/).pop()?.toLowerCase() ?? '' -} - -export async function confirmShellForegroundProcess( - shellPid: number | null | undefined, - spawnedShellProcess: string | null | undefined, - options: ShellForegroundConfirmationOptions = {} -): Promise { - if (!shellPid || !spawnedShellProcess || !isShellProcess(spawnedShellProcess)) { - return false - } - if (process.platform === 'win32') { - try { - return await isWindowsShellAloneInJob( - shellPid, - spawnedShellProcess, - await options.readWindowsPtyJobProcessIds?.(), - options.readWindowsProcessIdentityTable ?? readWindowsProcessIdentityTableFresh - ) - } catch { - // Unavailable job or process-table inspection is missing proof, never a thrown confirmation. - return false - } - } - try { - const index = getProcessTableIndex(await getFreshShellForegroundSnapshot()) - const root = index.byPid.get(shellPid) - if (!root) { - return false - } - const tree = [{ ...root, depth: 0 }, ...collectDescendantsFromIndex(index, shellPid)] - // Shell paths may contain spaces; command-line tokenization would truncate their basename. - const spawnedShellBasename = spawnedShellProcess.split(/[\\/]/).pop()?.toLowerCase() ?? '' - const foregroundShell = tree - .filter( - (row) => - executableBasename(row.command) === spawnedShellBasename && - isShellProcess(commandExecutable(row.command)) - ) - .sort((left, right) => left.depth - right.depth)[0] - if (tree.some((row) => row.depth > 0 && row.stat.includes('T'))) { - return false - } - const confirmed = foregroundShell?.stat.includes('+') === true - return confirmed - } catch { - return false - } -} - -export async function resolveAgentForegroundProcess( - shellPid: number | null | undefined, - fallbackProcess: string | null, - options: AgentForegroundResolutionOptions = {} -): Promise { - return (await resolveAgentForegroundProcessWithAvailability(shellPid, fallbackProcess, options)) - .processName -} - -export async function resolveAgentForegroundProcessWithAvailability( - shellPid: number | null | undefined, - fallbackProcess: string | null, - options: AgentForegroundResolutionOptions = {} -): Promise { - if (!shellPid) { - return { available: false, processName: fallbackProcess } - } - - if (process.platform === 'win32') { - if ( - !fallbackProcess || - (!shouldInspectWindowsAgentForeground(fallbackProcess) && !options.forceProcessScan) - ) { - return { available: true, processName: fallbackProcess } - } - const resolution = await resolveWindowsAgentForegroundProcessWithAvailability( - shellPid, - fallbackProcess, - options - ) - return { - available: resolution.available, - // A forced scan that loses the recognized fallback proves exit during confirmation. - processName: - resolution.processName ?? - (options.forceProcessScan && recognizeAgentProcessFromCommandLine(fallbackProcess) - ? null - : fallbackProcess), - // The anchor only travels with the name it proved, never with a fallback. - ...(resolution.processName !== null && resolution.processId !== undefined - ? { processId: resolution.processId } - : {}), - ...(resolution.anchorPidForeign ? { anchorPidForeign: true } : {}) - } - } - - try { - const rows = options.fresh - ? await getFreshProcessTableSnapshot() - : await getProcessTableSnapshot() - if (options.fresh && !getProcessTableIndex(rows).byPid.has(shellPid)) { - return { available: false, processName: fallbackProcess } - } - // A foreground descendant whose argv ps withheld could be the agent, so its absence is not proof. - if ( - collectDescendantsFromIndex(getProcessTableIndex(rows), shellPid).some( - (row) => row.stat.includes('+') && unreadableArgvName(row.command) !== null - ) - ) { - return { available: false, processName: fallbackProcess } - } - return { - available: true, - processName: resolveAgentForegroundProcessFromPs(rows, shellPid) ?? fallbackProcess - } - } catch { - // Why: a failed scan cannot prove fallback ownership; callers retain the last recognized agent. - return { available: false, processName: fallbackProcess } - } -} - -export function resolveAgentForegroundProcessFromPs( - rows: readonly ProcessTableRow[], - shellPid: number -): string | null { - const found = selectAgentForegroundFromPs(rows, shellPid) - // Preserve the outer OMP identity across its embedded Pi child. - return found - ? resolveOuterWrapperForegroundProcess( - found.selected.recognized, - found.selected.candidate, - found.candidates - ) - : null -} - -/** The full command line of the pane's foreground agent process, for argv-level policy. */ -export async function resolveAgentForegroundCommandLine(shellPid: number): Promise { - try { - const rows = await getFreshShellForegroundSnapshot() - return selectAgentForegroundFromPs(rows, shellPid)?.selected.candidate.command ?? null - } catch { - return null - } -} - -function selectAgentForegroundFromPs( - rows: readonly ProcessTableRow[], - shellPid: number -): { - selected: SelectedForegroundProcess - candidates: (ProcessTableRow & { depth: number })[] -} | null { - const index = getProcessTableIndex(rows) - const shellRow = index.byPid.get(shellPid) - const candidates = collectDescendantsFromIndex(index, shellPid) - // Include the shell in the foreground gate: after Ctrl-Z it owns + while the stopped agent remains a child. - const foregroundIsKnown = - shellRow?.stat.includes('+') === true || - candidates.some((candidate) => candidate.stat.includes('+')) - const foregroundCandidates = foregroundIsKnown - ? candidates.filter((candidate) => candidate.stat.includes('+')) - : candidates - // Keep non-foreground helpers in ancestry so wrapper recognition can traverse them. - const ancestryCandidates = shellRow ? [{ ...shellRow, depth: 0 }, ...candidates] : candidates - const selected = selectForegroundProcessCandidate(foregroundCandidates, ancestryCandidates) - return selected ? { selected, candidates } : null -} diff --git a/src/main/providers/execution-host-provider-dispatch.ts b/src/main/providers/execution-host-provider-dispatch.ts index 92f16817908..0dbf384371b 100644 --- a/src/main/providers/execution-host-provider-dispatch.ts +++ b/src/main/providers/execution-host-provider-dispatch.ts @@ -6,8 +6,8 @@ import { type LOCAL_EXECUTION_HOST_ID, type ParsedExecutionHost } from '../../shared/execution-host' -import { createLocalFilesystemProvider } from './local-filesystem-provider' -import { createLocalGitProvider } from './local-git-provider' +import { createLocalFilesystemProvider } from './filesystem/local-provider' +import { createLocalGitProvider } from './git/local-provider' import { SshHostNotServedError } from './ssh-host-not-served-error' export class UnresolvableExecutionHostError extends Error { diff --git a/src/main/providers/filesystem-markdown-listing.ts b/src/main/providers/filesystem-markdown-listing.ts deleted file mode 100644 index 7985c29f839..00000000000 --- a/src/main/providers/filesystem-markdown-listing.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { IFilesystemProvider } from './filesystem-provider-contract' -import { markdownDocumentsFromRelativePaths } from '../../shared/file-listing/markdown-document-paths' -import { FileInventoryBudget } from '../../shared/file-listing/file-inventory-budget' - -type MarkdownListingProvider = - | Required> - | Pick - -function hasMarkdownListing( - provider: MarkdownListingProvider -): provider is Required> { - return Boolean(provider.listMarkdownDocuments) -} - -export async function listFilesystemMarkdownDocuments( - provider: MarkdownListingProvider, - rootPath: string -) { - if (hasMarkdownListing(provider)) { - return provider.listMarkdownDocuments(rootPath) - } - const paths = await provider.listFiles(rootPath) - const budget = new FileInventoryBudget() - for (const path of paths) { - budget.record(path) - } - return markdownDocumentsFromRelativePaths(rootPath, paths) -} diff --git a/src/main/providers/filesystem-provider-contract.ts b/src/main/providers/filesystem-provider-contract.ts deleted file mode 100644 index 4f2c392f68e..00000000000 --- a/src/main/providers/filesystem-provider-contract.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { PathExistenceResult } from '../../shared/file-access/path-existence-batch' -import type { SearchOptions, SearchResult } from '../../shared/file-search/code-search-types' -import type { - DocPreviewFileAccessRequest, - DocPreviewFileAccessResult, - DocPreviewFileChunk, - DocPreviewFileTarget -} from '../../shared/document-preview/doc-preview-file-access' -import type { DirEntry } from '../../shared/file-listing/directory-entry' -import type { FsChangeEvent } from '../../shared/file-watch/filesystem-change-event' -import type { MarkdownDocument } from '../../shared/file-listing/file-document' -import type { WorkspaceSpaceDirectoryScanResult } from '../../shared/workspace-disk-space/workspace-space-types' - -export type FileStat = { - size: number - type: 'file' | 'directory' | 'symlink' - mtime: number - mtimeMs?: number - /** Local only: SSH hosts do not report it. */ - ctimeMs?: number - dev?: number - ino?: number - nlink?: number -} - -export type FileReadResult = { - content: string - isBinary: boolean - isImage?: boolean - mimeType?: string -} - -export type FileReadLimits = { - maxBinaryBytes?: number - maxTextBytes?: number -} - -export type FileRangeReadResult = { - /** Hosts fill the requested range or reach EOF; over-cap requests throw, so short reads always mean EOF. */ - bytes: Buffer - bytesRead: number -} - -export type IFilesystemProvider = { - readDir(dirPath: string, options?: { followSymlinks?: boolean }): Promise - readFile(filePath: string, limits?: FileReadLimits): Promise - readDocPreviewFile?(request: DocPreviewFileAccessRequest): Promise - readDocPreviewFileChunk?( - request: DocPreviewFileTarget, - offset: number, - length: number - ): Promise - /** Optional on older hosts; unsupported reads throw instead of transferring whole files per tail chunk. - * Position/end must be safe nonnegative offsets; length must be positive and within MAX_FILE_RANGE_READ_BYTES. */ - readFileRange?( - filePath: string, - position: number, - length: number, - options?: { signal?: AbortSignal } - ): Promise - supportsFileRangeRead?(options?: { signal?: AbortSignal }): Promise - readTerminalArtifact?( - filePath: string, - options: TerminalArtifactAccessOptions - ): Promise - downloadFile?(sourcePath: string, destinationPath: string): Promise - downloadFolder?: (src: string, dest: string, options?: { signal?: AbortSignal }) => Promise - openFileUploadSession?(): Promise - getTempDir?(): Promise - writeFile(filePath: string, content: string): Promise - writeTerminalArtifact?( - filePath: string, - content: string, - options: TerminalArtifactAccessOptions - ): Promise - writeFileBase64(filePath: string, contentBase64: string): Promise - writeFileBase64Chunk(filePath: string, contentBase64: string, append: boolean): Promise - pathsExist?(filePaths: string[]): Promise - stat(filePath: string): Promise - lstat?(filePath: string): Promise - deletePath(targetPath: string, recursive?: boolean): Promise - createFile(filePath: string): Promise - createDir(dirPath: string): Promise - createDirNoClobber(dirPath: string): Promise - rename(oldPath: string, newPath: string): Promise - renameNoClobber(oldPath: string, newPath: string): Promise - copy(source: string, destination: string): Promise - realpath(filePath: string): Promise - search(opts: SearchOptions, options?: { signal?: AbortSignal }): Promise - listFiles( - rootPath: string, - options?: { - excludePaths?: string[] - signal?: AbortSignal - maxResults?: number - searchQuery?: string - candidatePaths?: string[] - includeIgnored?: boolean - followSymlinks?: boolean - } - ): Promise - listMarkdownDocuments?( - rootPath: string, - options?: { signal?: AbortSignal } - ): Promise - supportsQuickOpenSearch?(options?: { - signal?: AbortSignal - minimumVersion?: number - }): Promise - scanWorkspaceSpace?( - rootPath: string, - options?: { signal?: AbortSignal } - ): Promise - watch( - rootPath: string, - callback: (events: FsChangeEvent[]) => void, - options?: { signal?: AbortSignal; onTerminalError?: (error: Error) => void } - ): Promise<() => void> - closeWatch?(rootPath: string): Promise -} - -export type FileUploadSession = { - uploadFile( - sourcePath: string, - destinationPath: string, - options?: { exclusive?: boolean } - ): Promise - close(): void -} - -export type TerminalArtifactAccessOptions = { - expectedRealPath: string - expectedStatIdentity: string | null - maxBytes: number -} diff --git a/src/main/providers/filesystem/local-provider.ts b/src/main/providers/filesystem/local-provider.ts new file mode 100644 index 00000000000..83b94d7611a --- /dev/null +++ b/src/main/providers/filesystem/local-provider.ts @@ -0,0 +1,188 @@ +import { constants, copyFile, lstat, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises' +import { dirname } from 'node:path' +import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' +import { + readAuthorizedDocPreviewFile, + readAuthorizedDocPreviewFileChunk +} from '../../../shared/document-preview/doc-preview-file-access' +import { renameLocalPathSerializedByDestination } from '../../filesystem/destination-serialized-local-rename' +import type { resolveAuthorizedPath as ResolveAuthorizedPath } from '../../ipc/filesystem/access/filesystem-auth' +import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' +import { + assertNotExists, + rethrowWithUserMessage +} from '../../ipc/filesystem/filesystem-create-path-guards' +import { classifyFilesystemDirectoryEntries } from '../../ipc/filesystem/filesystem-symlink-directory-entries' +import { getLocalGitOptionsForRegisteredWorktree } from '../../ipc/local-worktree-runtime-options' +import { listMarkdownDocuments } from '../../ipc/markdown-documents' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { runBundledRipgrepTextSearch } from '../../ripgrep/bundled-ripgrep-text-search' +import { resolveBundledRipgrepWslRouting } from '../../ripgrep/bundled-ripgrep-wsl-routing' +import type { IFilesystemProvider } from './provider-contract' +import type { + FileWriteDiskPrecondition, + FileWriteResult +} from '../../../shared/file-write/file-write-disk-precondition' +import { writeLocalTextFileWithDiskPrecondition } from '../../ipc/filesystem/local-disk-write-precondition' +import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' + +export type LocalFilesystemProviderOptions = { + /** Read lazily so a call that fails earlier never touches the store. */ + requireStore(): RuntimeStore + /** Injected: the auth layer reaches the host router, so importing it here would be a cycle. */ + resolveAuthorizedPath: typeof ResolveAuthorizedPath +} + +/** Local twins for runtime commands; reads/listing/watching retain call sites with different limits/shapes. */ +export type LocalFilesystemProvider = Required< + Pick +> & + Pick< + IFilesystemProvider, + | 'readDir' + | 'readDocPreviewFile' + | 'writeFile' + | 'writeFileBase64' + | 'writeFileBase64Chunk' + | 'pathsExist' + | 'stat' + | 'deletePath' + | 'createFile' + | 'createDir' + | 'createDirNoClobber' + | 'renameNoClobber' + | 'copy' + | 'search' + > & { + writeFileWithDiskPrecondition( + filePath: string, + content: string, + precondition: FileWriteDiskPrecondition | undefined + ): Promise + } + +/** Build per call so path authorization uses the current store. */ +export function createLocalFilesystemProvider( + options: LocalFilesystemProviderOptions +): LocalFilesystemProvider { + const { resolveAuthorizedPath } = options + // Authorized in the caller's spelling; a UNC drive-mount path is opened by its drive path. + const authorize = async (path: string) => + windowsFsPath(await resolveAuthorizedPath(path, options.requireStore())) + // Rename/copy/delete must authorize the symlink itself, preserving its target. + const authorizeLink = async (path: string) => + windowsFsPath( + await resolveAuthorizedPath(path, options.requireStore(), { preserveSymlink: true }) + ) + const writeBase64 = async (filePath: string, contentBase64: string, append: boolean) => { + const content = Buffer.from(contentBase64, 'base64') + const authorizedPath = await authorize(filePath) + await mkdir(dirname(authorizedPath), { recursive: true }) + await writeFile(authorizedPath, content, { flag: append ? 'a' : 'wx' }) + } + const writeTextFile = async ( + filePath: string, + content: string, + precondition: FileWriteDiskPrecondition | undefined + ): Promise => { + const authorizedPath = await authorize(filePath) + try { + if ((await lstat(authorizedPath)).isDirectory()) { + throw new Error('Cannot write to a directory') + } + } catch (error) { + if (!isENOENT(error)) { + throw error + } + } + return writeLocalTextFileWithDiskPrecondition(authorizedPath, content, precondition) + } + return { + readDir: async (dirPath, readOptions = {}) => { + const entries = await readdir(await authorize(dirPath), { withFileTypes: true }) + const store = options.requireStore() + return classifyFilesystemDirectoryEntries( + dirPath, + entries, + readOptions.followSymlinks ?? store.getSettings().followSymlinkedDirectories ?? false, + (path) => resolveAuthorizedPath(path, store) + ) + }, + readDocPreviewFile: readAuthorizedDocPreviewFile, + readDocPreviewFileChunk: readAuthorizedDocPreviewFileChunk, + writeFile: async (filePath, content) => { + await writeTextFile(filePath, content, undefined) + }, + writeFileWithDiskPrecondition: writeTextFile, + writeFileBase64: (filePath, contentBase64) => writeBase64(filePath, contentBase64, false), + writeFileBase64Chunk: writeBase64, + stat: async (filePath) => { + const stats = await stat(await authorize(filePath)) + return { + size: stats.size, + type: stats.isDirectory() ? 'directory' : 'file', + mtime: stats.mtimeMs, + ctimeMs: stats.ctimeMs + } + }, + deletePath: async (targetPath, recursive) => { + await rm(await authorizeLink(targetPath), { recursive: recursive === true, force: true }) + }, + createFile: async (filePath) => { + const authorizedPath = await authorize(filePath) + await mkdir(dirname(authorizedPath), { recursive: true }) + try { + await writeFile(authorizedPath, '', { encoding: 'utf-8', flag: 'wx' }) + } catch (error) { + rethrowWithUserMessage(error, authorizedPath) + } + }, + createDir: async (dirPath) => { + const authorizedPath = await authorize(dirPath) + await assertNotExists(authorizedPath) + await mkdir(authorizedPath, { recursive: false }) + }, + createDirNoClobber: async (dirPath) => { + await mkdir(await authorize(dirPath), { recursive: false }) + }, + renameNoClobber: async (oldPath, newPath) => { + const authorizedOldPath = await authorizeLink(oldPath) + await renameLocalPathSerializedByDestination(authorizedOldPath, await authorizeLink(newPath)) + }, + copy: async (source, destination) => { + const authorizedSource = await authorizeLink(source) + const authorizedDestination = await authorizeLink(destination) + await mkdir(dirname(authorizedDestination), { recursive: true }) + // Callers deconflict names; COPYFILE_EXCL preserves no-clobber if a destination appears meanwhile. + await copyFile(authorizedSource, authorizedDestination, constants.COPYFILE_EXCL) + }, + search: async (searchOptions, { signal } = {}) => { + throwIfSignalAborted(signal) + const store = options.requireStore() + const rootPath = await waitForPromiseWithSignal( + resolveAuthorizedPath(searchOptions.rootPath, store), + signal + ) + throwIfSignalAborted(signal) + const { wslDistro, wslDistroForOutput } = resolveBundledRipgrepWslRouting( + rootPath, + getLocalGitOptionsForRegisteredWorktree(store, searchOptions.rootPath, rootPath).wslDistro + ) + return runBundledRipgrepTextSearch({ + options: searchOptions, + rootPath, + resultRootPath: rootPath, + wslDistro, + wslDistroForOutput, + signal, + // Request abort owns cancellation; only renderer IPC needs a by-id registry. + onSpawn: () => () => undefined + }) + }, + listMarkdownDocuments: (rootPath) => + listMarkdownDocuments( + rootPath, + getLocalGitOptionsForRegisteredWorktree(options.requireStore(), rootPath, rootPath) + ) + } +} diff --git a/src/main/providers/filesystem/markdown-listing.ts b/src/main/providers/filesystem/markdown-listing.ts new file mode 100644 index 00000000000..5f70e587f73 --- /dev/null +++ b/src/main/providers/filesystem/markdown-listing.ts @@ -0,0 +1,28 @@ +import type { IFilesystemProvider } from './provider-contract' +import { markdownDocumentsFromRelativePaths } from '../../../shared/file-listing/markdown-document-paths' +import { FileInventoryBudget } from '../../../shared/file-listing/file-inventory-budget' + +type MarkdownListingProvider = + | Required> + | Pick + +function hasMarkdownListing( + provider: MarkdownListingProvider +): provider is Required> { + return Boolean(provider.listMarkdownDocuments) +} + +export async function listFilesystemMarkdownDocuments( + provider: MarkdownListingProvider, + rootPath: string +) { + if (hasMarkdownListing(provider)) { + return provider.listMarkdownDocuments(rootPath) + } + const paths = await provider.listFiles(rootPath) + const budget = new FileInventoryBudget() + for (const path of paths) { + budget.record(path) + } + return markdownDocumentsFromRelativePaths(rootPath, paths) +} diff --git a/src/main/providers/filesystem/provider-contract.ts b/src/main/providers/filesystem/provider-contract.ts new file mode 100644 index 00000000000..4690dc3044a --- /dev/null +++ b/src/main/providers/filesystem/provider-contract.ts @@ -0,0 +1,135 @@ +import type { PathExistenceResult } from '../../../shared/file-access/path-existence-batch' +import type { SearchOptions, SearchResult } from '../../../shared/file-search/code-search-types' +import type { + DocPreviewFileAccessRequest, + DocPreviewFileAccessResult, + DocPreviewFileChunk, + DocPreviewFileTarget +} from '../../../shared/document-preview/doc-preview-file-access' +import type { DirEntry } from '../../../shared/file-listing/directory-entry' +import type { FsChangeEvent } from '../../../shared/file-watch/filesystem-change-event' +import type { MarkdownDocument } from '../../../shared/file-listing/file-document' +import type { WorkspaceSpaceDirectoryScanResult } from '../../../shared/workspace-disk-space/workspace-space-types' + +export type FileStat = { + size: number + type: 'file' | 'directory' | 'symlink' + mtime: number + mtimeMs?: number + /** Local only: SSH hosts do not report it. */ + ctimeMs?: number + dev?: number + ino?: number + nlink?: number +} + +export type FileReadResult = { + content: string + isBinary: boolean + isImage?: boolean + mimeType?: string +} + +export type FileReadLimits = { + maxBinaryBytes?: number + maxTextBytes?: number +} + +export type FileRangeReadResult = { + /** Hosts fill the requested range or reach EOF; over-cap requests throw, so short reads always mean EOF. */ + bytes: Buffer + bytesRead: number +} + +export type IFilesystemProvider = { + readDir(dirPath: string, options?: { followSymlinks?: boolean }): Promise + readFile(filePath: string, limits?: FileReadLimits): Promise + readDocPreviewFile?(request: DocPreviewFileAccessRequest): Promise + readDocPreviewFileChunk?( + request: DocPreviewFileTarget, + offset: number, + length: number + ): Promise + /** Optional on older hosts; unsupported reads throw instead of transferring whole files per tail chunk. + * Position/end must be safe nonnegative offsets; length must be positive and within MAX_FILE_RANGE_READ_BYTES. */ + readFileRange?( + filePath: string, + position: number, + length: number, + options?: { signal?: AbortSignal } + ): Promise + supportsFileRangeRead?(options?: { signal?: AbortSignal }): Promise + readTerminalArtifact?( + filePath: string, + options: TerminalArtifactAccessOptions + ): Promise + downloadFile?(sourcePath: string, destinationPath: string): Promise + downloadFolder?: (src: string, dest: string, options?: { signal?: AbortSignal }) => Promise + openFileUploadSession?(): Promise + getTempDir?(): Promise + writeFile(filePath: string, content: string): Promise + writeTerminalArtifact?( + filePath: string, + content: string, + options: TerminalArtifactAccessOptions + ): Promise + writeFileBase64(filePath: string, contentBase64: string): Promise + writeFileBase64Chunk(filePath: string, contentBase64: string, append: boolean): Promise + pathsExist?(filePaths: string[]): Promise + stat(filePath: string): Promise + lstat?(filePath: string): Promise + deletePath(targetPath: string, recursive?: boolean): Promise + createFile(filePath: string): Promise + createDir(dirPath: string): Promise + createDirNoClobber(dirPath: string): Promise + rename(oldPath: string, newPath: string): Promise + renameNoClobber(oldPath: string, newPath: string): Promise + copy(source: string, destination: string): Promise + realpath(filePath: string): Promise + search(opts: SearchOptions, options?: { signal?: AbortSignal }): Promise + listFiles( + rootPath: string, + options?: { + excludePaths?: string[] + signal?: AbortSignal + maxResults?: number + searchQuery?: string + candidatePaths?: string[] + includeIgnored?: boolean + followSymlinks?: boolean + } + ): Promise + listMarkdownDocuments?( + rootPath: string, + options?: { signal?: AbortSignal } + ): Promise + supportsQuickOpenSearch?(options?: { + signal?: AbortSignal + minimumVersion?: number + }): Promise + scanWorkspaceSpace?( + rootPath: string, + options?: { signal?: AbortSignal } + ): Promise + watch( + rootPath: string, + callback: (events: FsChangeEvent[]) => void, + options?: { signal?: AbortSignal; onTerminalError?: (error: Error) => void } + ): Promise<() => void> + closeWatch?(rootPath: string): Promise +} + +export type FileUploadSession = { + uploadFile( + sourcePath: string, + destinationPath: string, + options?: { exclusive?: boolean } + ): Promise + close(): void +} + +export type TerminalArtifactAccessOptions = { + expectedRealPath: string + expectedStatIdentity: string | null + maxBytes: number +} diff --git a/src/main/providers/foreground/agent-process-batch.ts b/src/main/providers/foreground/agent-process-batch.ts new file mode 100644 index 00000000000..31df0f9aa9c --- /dev/null +++ b/src/main/providers/foreground/agent-process-batch.ts @@ -0,0 +1,265 @@ +import { + isAgentForegroundWrapperProcess, + isExpectedAgentProcess +} from '../../../shared/agent-status/process/agent-process-recognition' +import { getFirstCommandToken } from '../../../shared/command-token-scanner' +import { resolveOuterWrapperForegroundProcess } from '../../../shared/foreground-wrapper-agent' +import { selectForegroundProcessCandidate } from '../../../shared/foreground-process-selection' +import type { + ForegroundProcessEvidence, + RemoteForegroundEvidence +} from '../../../shared/foreground-process-evidence' +import { + buildProcessTableIndex, + lookupProcessTableIndex, + type ProcessTableIndex, + type ProcessTableIndexStats +} from '../../../shared/process-table-index' +import { unreadableArgvName, type ProcessTableRow } from '../../../shared/process-table-snapshot' +import { getStrictProcessTableSnapshot } from '../../../shared/process-table-snapshot-reader' +import { resolveRemoteForegroundEvidenceFromRows } from './remote-evidence' + +export type BatchedForegroundProcessRequest = { + rootPid: number + fallbackProcess?: string | null +} + +export type BatchedForegroundProcessResult = { + available: boolean + processName: string | null + reason?: string + /** True only for a readable table with no other tty groups/stopped processes and the shell alone in its group. + * Keep the wire name for old clients; stricter proof can only reduce skipped sweeps. */ + shellOwnsEveryTtyProcessGroup?: boolean +} + +export type RemoteForegroundEvidenceOptions = { + ptyId: string + ptyIncarnationId: string + authorityGeneration: string + observationEpoch: number + capturedAgeMs: number + platform?: NodeJS.Platform +} + +/** Resolve a host-stamped, fenced observation from one complete process-table capture. */ +export function resolveRemoteForegroundEvidence( + request: BatchedForegroundProcessRequest, + options: RemoteForegroundEvidenceOptions, + rows: readonly ProcessTableRow[] +): RemoteForegroundEvidence { + return resolveRemoteForegroundEvidenceFromRows( + request, + options, + rows, + resolveAgentForegroundProcessesFromIndex + ) +} + +export type BatchedForegroundProcessOptions = { + rows?: readonly ProcessTableRow[] + readRows?: () => Promise + stats?: ProcessTableIndexStats +} + +type PaneOccupancy = { + processGroupsByTty: ReadonlyMap> + stoppedTtys: ReadonlySet + /** Count all group members: killpg also reaches members without a controlling terminal. */ + rowsByProcessGroup: ReadonlyMap + /** Missing pgid rows make group counts insufficient to prove idle. */ + processGroupsIncomplete: boolean +} + +const paneOccupancyByCapture = new WeakMap() + +/** A live tpgid identifies one controlling terminal; memoize its groups and host-wide group sizes per shared capture. */ +function getPaneOccupancy(rows: readonly ProcessTableRow[]): PaneOccupancy { + const cached = paneOccupancyByCapture.get(rows) + if (cached) { + return cached + } + const processGroupsByTty = new Map>() + const stoppedTtys = new Set() + const rowsByProcessGroup = new Map() + let processGroupsIncomplete = false + for (const row of rows) { + if (row.pgid === undefined) { + processGroupsIncomplete = true + continue + } + rowsByProcessGroup.set(row.pgid, (rowsByProcessGroup.get(row.pgid) ?? 0) + 1) + if (row.tpgid === undefined || row.tpgid <= 0) { + continue + } + let groups = processGroupsByTty.get(row.tpgid) + if (!groups) { + groups = new Set() + processGroupsByTty.set(row.tpgid, groups) + } + groups.add(row.pgid) + // `T` is a job-control stop (Ctrl-Z), `t` a tracing stop. Both are work the pane still holds. + if (row.stat.startsWith('T') || row.stat.startsWith('t')) { + stoppedTtys.add(row.tpgid) + } + } + const occupancy: PaneOccupancy = { + processGroupsByTty, + stoppedTtys, + rowsByProcessGroup, + processGroupsIncomplete + } + paneOccupancyByCapture.set(rows, occupancy) + return occupancy +} + +export async function resolveAgentForegroundProcessesBatch( + requests: readonly BatchedForegroundProcessRequest[], + options: BatchedForegroundProcessOptions = {} +): Promise { + let rows = options.rows + if (!rows) { + if (options.stats) { + options.stats.captures = (options.stats.captures ?? 0) + 1 + } + rows = await (options.readRows?.() ?? getStrictProcessTableSnapshot()) + } + const index = buildProcessTableIndex(rows, options.stats) + return resolveAgentForegroundProcessesFromIndex(index, requests) +} + +export function resolveAgentForegroundProcessesFromIndex( + index: ProcessTableIndex, + requests: readonly BatchedForegroundProcessRequest[] +): BatchedForegroundProcessResult[] { + const uniqueRoots = new Set() + for (const request of requests) { + uniqueRoots.add(request.rootPid) + } + const rootsByPid = new Set(uniqueRoots) + const depthByPid = new Map() + const rowsByOwner = new Map() + const queue: { row: ProcessTableRow; owner: number; depth: number }[] = [] + for (const rootPid of uniqueRoots) { + const root = lookupProcessTableIndex(index, (value) => value.byPid.get(rootPid)) + if (root) { + depthByPid.set(root.pid, 0) + queue.push({ row: root, owner: root.pid, depth: 0 }) + } + } + for (let cursor = 0; cursor < queue.length; cursor += 1) { + const current = queue[cursor] + const owned = rowsByOwner.get(current.owner) ?? [] + if (current.depth > 0) { + owned.push({ ...current.row, depth: current.depth }) + } + rowsByOwner.set(current.owner, owned) + const children = lookupProcessTableIndex( + index, + (value) => value.childrenByPpid.get(current.row.pid) ?? [] + ) + for (const child of children) { + const childOwner = rootsByPid.has(child.pid) ? child.pid : current.owner + const childDepth = rootsByPid.has(child.pid) ? 0 : current.depth + 1 + const priorDepth = depthByPid.get(child.pid) + if (priorDepth !== undefined && priorDepth <= childDepth) { + continue + } + depthByPid.set(child.pid, childDepth) + queue.push({ row: child, owner: childOwner, depth: childDepth }) + } + } + + const occupancy = getPaneOccupancy(index.rows) + return requests.map((request) => { + const root = lookupProcessTableIndex(index, (value) => value.byPid.get(request.rootPid)) + if (!root) { + return { + available: false, + processName: request.fallbackProcess ?? null, + reason: 'root_missing' + } + } + if (root.pgid === undefined || root.tpgid === undefined) { + return { + available: false, + processName: request.fallbackProcess ?? null, + reason: 'correlation_unavailable' + } + } + if (root.tpgid === 0 || root.tpgid === -1) { + return { + available: false, + processName: request.fallbackProcess ?? null, + reason: 'no_controlling_tty' + } + } + // Sweep authorization needs both: no other tty group (background/stopped jobs), and no other shell-group member + // anywhere (job control off, detached/reparented children). Missing evidence never proves idle. + // Capture age bounds races with new work; ps permission/namespace omissions remain unobservable despite killpg reach. + const ttyProcessGroups = occupancy.processGroupsByTty.get(root.tpgid) + const shellOwnsEveryTtyProcessGroup = + root.tpgid === root.pgid && + ttyProcessGroups !== undefined && + ttyProcessGroups.size === 1 && + ttyProcessGroups.has(root.pgid) && + !occupancy.stoppedTtys.has(root.tpgid) && + !occupancy.processGroupsIncomplete && + // The root counts itself; exactly one group member excludes all other killpg targets. + occupancy.rowsByProcessGroup.get(root.pgid) === 1 + const allCandidates = rowsByOwner.get(root.pid) ?? [] + const foregroundCandidates = allCandidates.filter((row) => row.pgid === root.tpgid) + // A foreground process whose argv ps withheld could be the agent: absence of a name proves nothing. + if (foregroundCandidates.some((row) => unreadableArgvName(row.command) !== null)) { + return { + available: false, + processName: request.fallbackProcess ?? null, + reason: 'argv_unreadable' + } + } + const fallbackProcess = request.fallbackProcess + const wrapperFallback = + typeof fallbackProcess === 'string' && isAgentForegroundWrapperProcess(fallbackProcess) + const candidates = wrapperFallback + ? foregroundCandidates.filter((candidate) => + isExpectedAgentProcess(getFirstCommandToken(candidate.command), fallbackProcess) + ) + : foregroundCandidates + if (wrapperFallback && candidates.length !== 1) { + return { available: true, processName: null, shellOwnsEveryTtyProcessGroup } + } + const selected = selectForegroundProcessCandidate(candidates, allCandidates) + if (selected) { + return { + available: true, + processName: resolveOuterWrapperForegroundProcess( + selected.recognized, + selected.candidate, + allCandidates + ), + shellOwnsEveryTtyProcessGroup + } + } + return { available: true, processName: null, shellOwnsEveryTtyProcessGroup } + }) +} + +export function toForegroundProcessEvidence( + result: BatchedForegroundProcessResult, + metadata: { authorityGeneration: string; observationEpoch: number; capturedAgeMs: number } +): ForegroundProcessEvidence { + return result.available + ? { + ...metadata, + verdict: 'live', + processName: result.processName, + ...(result.shellOwnsEveryTtyProcessGroup !== undefined + ? { shellOwnsEveryTtyProcessGroup: result.shellOwnsEveryTtyProcessGroup } + : {}) + } + : { + ...metadata, + verdict: 'unverifiable', + reason: result.reason ?? 'correlation_unavailable' + } +} diff --git a/src/main/providers/foreground/agent-process.ts b/src/main/providers/foreground/agent-process.ts new file mode 100644 index 00000000000..ff34a3349a6 --- /dev/null +++ b/src/main/providers/foreground/agent-process.ts @@ -0,0 +1,225 @@ +import { recognizeAgentProcessFromCommandLine } from '../../../shared/agent-status/process/agent-process-recognition' +import { resolveOuterWrapperForegroundProcess } from '../../../shared/foreground-wrapper-agent' +import { unreadableArgvName, type ProcessTableRow } from '../../../shared/process-table-snapshot' +import { + getFreshProcessTableSnapshot, + getFreshShellForegroundSnapshot, + getProcessTableSnapshot +} from '../../../shared/process-table-snapshot-reader' +import { + collectDescendantsFromIndex, + getProcessTableIndex +} from '../../../shared/process-table-index' +import { + resolveWindowsAgentForegroundProcessWithAvailability, + shouldInspectWindowsAgentForeground, + type AgentForegroundResolutionOptions +} from './windows/agent-process' +import { isShellProcess } from '../../../shared/agent-status/process/shell-process-detection' +import { + selectForegroundProcessCandidate, + type SelectedForegroundProcess +} from '../../../shared/foreground-process-selection' +import { isWindowsShellAloneInJob } from './windows/shell-alone-in-job' +import { + readWindowsProcessIdentityTableFresh, + type WindowsProcessIdentityRow +} from '../../windows/windows-process-table' + +import './agent-process-batch' + +export type AgentForegroundProcessResolution = { + available: boolean + processName: string | null + /** Windows liveness anchor for an unambiguous recognized name; omitted for fallbacks and POSIX. */ + processId?: number + /** Windows: the scan proved the caller's `anchorProcessId` is now a non-agent. */ + anchorPidForeign?: boolean +} + +type ShellForegroundConfirmationOptions = { + readWindowsPtyJobProcessIds?: () => + | ReadonlySet + | null + | Promise | null> + readWindowsProcessIdentityTable?: () => Promise +} + +function commandExecutable(command: string): string { + const trimmed = command.trim().replace(/^[-]/, '') + if (trimmed.startsWith('"') || trimmed.startsWith("'")) { + const closingQuote = trimmed.indexOf(trimmed[0], 1) + return closingQuote === -1 ? trimmed.slice(1) : trimmed.slice(1, closingQuote) + } + return trimmed.split(/\s+/, 1)[0] ?? '' +} + +function executableBasename(command: string): string { + return commandExecutable(command).split(/[\\/]/).pop()?.toLowerCase() ?? '' +} + +export async function confirmShellForegroundProcess( + shellPid: number | null | undefined, + spawnedShellProcess: string | null | undefined, + options: ShellForegroundConfirmationOptions = {} +): Promise { + if (!shellPid || !spawnedShellProcess || !isShellProcess(spawnedShellProcess)) { + return false + } + if (process.platform === 'win32') { + try { + return await isWindowsShellAloneInJob( + shellPid, + spawnedShellProcess, + await options.readWindowsPtyJobProcessIds?.(), + options.readWindowsProcessIdentityTable ?? readWindowsProcessIdentityTableFresh + ) + } catch { + // Unavailable job or process-table inspection is missing proof, never a thrown confirmation. + return false + } + } + try { + const index = getProcessTableIndex(await getFreshShellForegroundSnapshot()) + const root = index.byPid.get(shellPid) + if (!root) { + return false + } + const tree = [{ ...root, depth: 0 }, ...collectDescendantsFromIndex(index, shellPid)] + // Shell paths may contain spaces; command-line tokenization would truncate their basename. + const spawnedShellBasename = spawnedShellProcess.split(/[\\/]/).pop()?.toLowerCase() ?? '' + const foregroundShell = tree + .filter( + (row) => + executableBasename(row.command) === spawnedShellBasename && + isShellProcess(commandExecutable(row.command)) + ) + .sort((left, right) => left.depth - right.depth)[0] + if (tree.some((row) => row.depth > 0 && row.stat.includes('T'))) { + return false + } + const confirmed = foregroundShell?.stat.includes('+') === true + return confirmed + } catch { + return false + } +} + +export async function resolveAgentForegroundProcess( + shellPid: number | null | undefined, + fallbackProcess: string | null, + options: AgentForegroundResolutionOptions = {} +): Promise { + return (await resolveAgentForegroundProcessWithAvailability(shellPid, fallbackProcess, options)) + .processName +} + +export async function resolveAgentForegroundProcessWithAvailability( + shellPid: number | null | undefined, + fallbackProcess: string | null, + options: AgentForegroundResolutionOptions = {} +): Promise { + if (!shellPid) { + return { available: false, processName: fallbackProcess } + } + + if (process.platform === 'win32') { + if ( + !fallbackProcess || + (!shouldInspectWindowsAgentForeground(fallbackProcess) && !options.forceProcessScan) + ) { + return { available: true, processName: fallbackProcess } + } + const resolution = await resolveWindowsAgentForegroundProcessWithAvailability( + shellPid, + fallbackProcess, + options + ) + return { + available: resolution.available, + // A forced scan that loses the recognized fallback proves exit during confirmation. + processName: + resolution.processName ?? + (options.forceProcessScan && recognizeAgentProcessFromCommandLine(fallbackProcess) + ? null + : fallbackProcess), + // The anchor only travels with the name it proved, never with a fallback. + ...(resolution.processName !== null && resolution.processId !== undefined + ? { processId: resolution.processId } + : {}), + ...(resolution.anchorPidForeign ? { anchorPidForeign: true } : {}) + } + } + + try { + const rows = options.fresh + ? await getFreshProcessTableSnapshot() + : await getProcessTableSnapshot() + if (options.fresh && !getProcessTableIndex(rows).byPid.has(shellPid)) { + return { available: false, processName: fallbackProcess } + } + // A foreground descendant whose argv ps withheld could be the agent, so its absence is not proof. + if ( + collectDescendantsFromIndex(getProcessTableIndex(rows), shellPid).some( + (row) => row.stat.includes('+') && unreadableArgvName(row.command) !== null + ) + ) { + return { available: false, processName: fallbackProcess } + } + return { + available: true, + processName: resolveAgentForegroundProcessFromPs(rows, shellPid) ?? fallbackProcess + } + } catch { + // Why: a failed scan cannot prove fallback ownership; callers retain the last recognized agent. + return { available: false, processName: fallbackProcess } + } +} + +export function resolveAgentForegroundProcessFromPs( + rows: readonly ProcessTableRow[], + shellPid: number +): string | null { + const found = selectAgentForegroundFromPs(rows, shellPid) + // Preserve the outer OMP identity across its embedded Pi child. + return found + ? resolveOuterWrapperForegroundProcess( + found.selected.recognized, + found.selected.candidate, + found.candidates + ) + : null +} + +/** The full command line of the pane's foreground agent process, for argv-level policy. */ +export async function resolveAgentForegroundCommandLine(shellPid: number): Promise { + try { + const rows = await getFreshShellForegroundSnapshot() + return selectAgentForegroundFromPs(rows, shellPid)?.selected.candidate.command ?? null + } catch { + return null + } +} + +function selectAgentForegroundFromPs( + rows: readonly ProcessTableRow[], + shellPid: number +): { + selected: SelectedForegroundProcess + candidates: (ProcessTableRow & { depth: number })[] +} | null { + const index = getProcessTableIndex(rows) + const shellRow = index.byPid.get(shellPid) + const candidates = collectDescendantsFromIndex(index, shellPid) + // Include the shell in the foreground gate: after Ctrl-Z it owns + while the stopped agent remains a child. + const foregroundIsKnown = + shellRow?.stat.includes('+') === true || + candidates.some((candidate) => candidate.stat.includes('+')) + const foregroundCandidates = foregroundIsKnown + ? candidates.filter((candidate) => candidate.stat.includes('+')) + : candidates + // Keep non-foreground helpers in ancestry so wrapper recognition can traverse them. + const ancestryCandidates = shellRow ? [{ ...shellRow, depth: 0 }, ...candidates] : candidates + const selected = selectForegroundProcessCandidate(foregroundCandidates, ancestryCandidates) + return selected ? { selected, candidates } : null +} diff --git a/src/main/providers/foreground/context-paths.ts b/src/main/providers/foreground/context-paths.ts new file mode 100644 index 00000000000..41bf635cd71 --- /dev/null +++ b/src/main/providers/foreground/context-paths.ts @@ -0,0 +1,11 @@ +import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' + +export function getAgentForegroundContextPaths(options: { + cwd?: string + worktreeId?: string | null +}): string[] { + const worktreePath = options.worktreeId + ? splitWorktreeIdForFilesystem(options.worktreeId)?.worktreePath + : undefined + return [...new Set([options.cwd, worktreePath].filter((path): path is string => Boolean(path)))] +} diff --git a/src/main/providers/foreground/posix-pane-fingerprint.ts b/src/main/providers/foreground/posix-pane-fingerprint.ts new file mode 100644 index 00000000000..aab003e3a30 --- /dev/null +++ b/src/main/providers/foreground/posix-pane-fingerprint.ts @@ -0,0 +1,82 @@ +import { readFile } from 'node:fs/promises' +import { + collectDescendantsFromIndex, + getProcessTableIndex +} from '../../../shared/process-table-index' +import { parseLinuxProcStatStartTime } from '../../../shared/process-table-snapshot-reader' + +/** Cheap-tier job-control columns omit command/tty by design. */ +export type PaneFingerprintRow = { + pid: number + ppid: number + pgid?: number + tpgid?: number + stat: string + startTime?: string +} + +export type PaneFingerprintDeps = { + platform?: NodeJS.Platform + /** Linux: `/proc//stat` field 22, read for the pane subtree only. */ + readLinuxStartTime?: (pid: number) => Promise +} + +/** Ignore scheduler churn; stopped, zombie and foreground states can change pane ownership. */ +function jobControlState(stat: string): string { + const head = stat[0] ?? '' + const lifecycle = head === 'T' || head === 't' ? 'T' : head === 'Z' ? 'Z' : '' + return lifecycle + (stat.includes('+') ? '+' : '') +} + +async function readLinuxProcStartTime(pid: number): Promise { + try { + return parseLinuxProcStatStartTime(await readFile(`/proc/${pid}/stat`, 'utf8')) + } catch { + return null + } +} + +/** Reuse recognition only across equal fenced shell/descendant identities, groups and job-control state. + * Missing root, start markers or group columns requires a full capture instead. */ +export async function buildPaneProcessFingerprint( + rows: readonly PaneFingerprintRow[], + rootPid: number, + deps: PaneFingerprintDeps = {} +): Promise { + const platform = deps.platform ?? process.platform + const index = getProcessTableIndex(rows) + const root = index.byPid.get(rootPid) + if (!root || root.pgid === undefined || root.tpgid === undefined) { + return null + } + const descendants = collectDescendantsFromIndex(index, rootPid) + const subtree = [root, ...descendants] + let startTimes: ReadonlyMap + if (platform === 'linux') { + const read = deps.readLinuxStartTime ?? readLinuxProcStartTime + const entries = await Promise.all( + subtree.map(async (row) => [row.pid, await read(row.pid)] as const) + ) + startTimes = new Map(entries) + } else { + // Collapse `lstart` padding (`Sep 3`) so both column sets stamp identically. + startTimes = new Map( + subtree.map((row) => [row.pid, row.startTime?.replace(/\s+/g, ' ') ?? null] as const) + ) + } + const rootStart = startTimes.get(rootPid) + if (!rootStart) { + return null + } + // Every descendant needs a start marker; placeholders could compare equal across PID reuse and mask agent exit. + const members: string[] = [] + for (const row of descendants) { + const startTime = startTimes.get(row.pid) + if (!startTime) { + return null + } + members.push(`${row.pid}@${startTime}:${row.pgid ?? '?'}:${jobControlState(row.stat)}`) + } + members.sort() + return `${rootPid}@${rootStart}#${root.tpgid}:${jobControlState(root.stat)}|${members.join(',')}` +} diff --git a/src/main/providers/foreground/pty-confirmation.ts b/src/main/providers/foreground/pty-confirmation.ts new file mode 100644 index 00000000000..1253ea322ef --- /dev/null +++ b/src/main/providers/foreground/pty-confirmation.ts @@ -0,0 +1,87 @@ +import type { IPty } from 'node-pty' +import { recognizeAgentProcess } from '../../../shared/agent-status/process/agent-process-recognition' +import { shouldInspectOuterWrapperForegroundProcess } from '../../../shared/foreground-wrapper-agent' +import { ptyShellProcessId } from '../../windows/windows-pty-job' +import { createPtyForegroundResolver } from '../../daemon/pty-subprocess/spawn-file-foreground-process' +import { + resolveAgentForegroundProcessWithAvailability, + type AgentForegroundProcessResolution +} from './agent-process' +import type { AgentForegroundResolutionOptions } from './windows/agent-process' +import { + judgeCachedAgentJobEvidence, + reconcileWindowsAgentDecision, + type WindowsCachedAgentJobVerdict +} from './windows/cached-agent-revalidation' +import { readWindowsConsoleAttachedProcessIds } from './windows/console-attached-processes' +import { isWindowsPtyJobReadable, readWindowsPtyJobProcessIds } from './windows/pty-job-membership' + +/** Execute fresh confirmation; owners retain cache publication and lifetime fences. */ +export async function confirmFreshPtyForeground(args: { + process: IPty + fallbackProcess: string | null + contextPaths: AgentForegroundResolutionOptions['contextPaths'] + decision: boolean + anchor: { processName: string; pid: number | null } | null + anchorAt?: number +}): Promise<{ resolution: AgentForegroundProcessResolution; processName: string | null }> { + const proc = args.process + const shellPid = ptyShellProcessId(proc) ?? proc.pid + let verdict: WindowsCachedAgentJobVerdict = 'unavailable' + if (args.decision) { + try { + verdict = judgeCachedAgentJobEvidence({ + jobProcessIds: readWindowsPtyJobProcessIds(proc), + jobSupported: isWindowsPtyJobReadable(), + shellPid, + anchorProcessId: args.anchor?.pid ?? null, + identityAgeMs: Date.now() - (args.anchorAt ?? 0) + }) + } catch { + /* A failed job read cannot release a known anchor. */ + } + } + let resolution: AgentForegroundProcessResolution + try { + const resolve = args.decision + ? resolveAgentForegroundProcessWithAvailability + : createPtyForegroundResolver(proc) + resolution = await resolve(proc.pid, args.fallbackProcess, { + contextPaths: args.contextPaths, + fresh: true, + ...(args.decision && args.anchor?.pid != null + ? { anchorProcessId: args.anchor.pid, anchorProcessName: args.anchor.processName } + : {}), + ...(process.platform === 'win32' + ? { + forceProcessScan: true, + readWindowsConsoleAttachedProcessIds: () => + readWindowsConsoleAttachedProcessIds(proc.pid) + } + : {}) + }) + } catch { + resolution = { available: false, processName: null } + } + return { + resolution, + processName: args.decision + ? reconcileWindowsAgentDecision(resolution, verdict, args.anchor, shellPid) + : resolution.available + ? resolution.processName + : null + } +} + +/** Known direct agent names need no POSIX scan; Windows decisions still require fresh evidence. */ +export function shouldConfirmPtyForeground(fallback: string | null, decision: boolean): boolean { + if (!fallback) { + return decision + } + const recognized = recognizeAgentProcess(fallback) + return ( + process.platform === 'win32' || + recognized === null || + shouldInspectOuterWrapperForegroundProcess(recognized) + ) +} diff --git a/src/main/providers/foreground/remote-evidence.ts b/src/main/providers/foreground/remote-evidence.ts new file mode 100644 index 00000000000..a94e2d0286d --- /dev/null +++ b/src/main/providers/foreground/remote-evidence.ts @@ -0,0 +1,131 @@ +import { hasControllingTty } from '../../../shared/posix-controlling-terminal' +import { recognizeAgentProcessFromCommandLine } from '../../../shared/agent-status/process/agent-process-recognition' +import type { + PosixFence, + RemoteForegroundEvidence, + WindowsFence +} from '../../../shared/foreground-process-evidence' +import { buildProcessTableIndex, type ProcessTableIndex } from '../../../shared/process-table-index' +import type { ProcessTableRow } from '../../../shared/process-table-snapshot' +import type { + BatchedForegroundProcessRequest, + BatchedForegroundProcessResult, + RemoteForegroundEvidenceOptions +} from './agent-process-batch' + +type ResolveForegroundProcesses = ( + index: ProcessTableIndex, + requests: readonly BatchedForegroundProcessRequest[] +) => BatchedForegroundProcessResult[] + +/** Resolve a host-stamped, fenced observation from one complete process-table capture. */ +export function resolveRemoteForegroundEvidenceFromRows( + request: BatchedForegroundProcessRequest, + options: RemoteForegroundEvidenceOptions, + rows: readonly ProcessTableRow[], + resolveForegroundProcesses: ResolveForegroundProcesses +): RemoteForegroundEvidence { + const metadata = { + authorityGeneration: options.authorityGeneration, + observationEpoch: options.observationEpoch, + capturedAgeMs: options.capturedAgeMs, + ptyId: options.ptyId, + ptyIncarnationId: options.ptyIncarnationId + } + if (!options.ptyIncarnationId || !options.ptyId || rows.length === 0) { + return { ...metadata, verdict: 'unverifiable', reason: 'process_table_unreadable' } + } + if (options.platform === 'win32') { + // Windows SSH lacks native process-table, creation-time and ConPTY session proof; descendant names cannot authorize foreground identity. + const fence: WindowsFence = { + platform: 'windows', + rootProcessId: request.rootPid, + rootCreationTime: 'unavailable', + sessionId: 'unavailable' + } + void fence + return { ...metadata, verdict: 'unverifiable', reason: 'windows_ssh_foreground_unavailable' } + } + const root = rows.find((row) => row.pid === request.rootPid) + if (!root || root.pgid === undefined || root.tpgid === undefined) { + return { ...metadata, verdict: 'unverifiable', reason: 'anchor_missing' } + } + if (!hasControllingTty(root.tty) || root.tpgid <= 0 || !root.startTime) { + return { ...metadata, verdict: 'unverifiable', reason: 'fence_incomplete' } + } + const index = buildProcessTableIndex(rows) + const resolved = resolveForegroundProcesses(index, [request])[0] + if (!resolved?.available) { + return { + ...metadata, + verdict: 'unverifiable', + reason: resolved?.reason ?? 'capture_incomplete' + } + } + const descendants = collectDescendantRows(index, root.pid) + // Another controlling terminal falls outside this pane; its work cannot prove this shell idle. + if (descendants.some((row) => hasControllingTty(row.tty) && row.tty !== root.tty)) { + return { ...metadata, verdict: 'unverifiable', reason: 'tty_boundary' } + } + // Without a multiplexer/session fence, apparent foreground ancestry cannot establish user focus. + if ([root, ...descendants].some((row) => /(?:^|\s)(?:tmux|screen)(?:\s|$)/i.test(row.command))) { + return { ...metadata, verdict: 'unverifiable', reason: 'multiplexer_boundary' } + } + if (descendants.some((row) => row.pgid === root.tpgid && !hasControllingTty(row.tty))) { + return { ...metadata, verdict: 'unverifiable', reason: 'fence_incomplete' } + } + const foreground = descendants.filter((row) => row.pgid === root.tpgid && row.tty === root.tty) + const recognized = foreground + .map((row) => ({ row, name: recognizeAgentProcessFromCommandLine(row.command) })) + .filter( + ( + entry + ): entry is { + row: ProcessTableRow + name: NonNullable> + } => Boolean(entry.name) + ) + // One agent can hold two rows (npm Codex: node codex.js spawning native codex; Gemini relaunching itself in node): + // that names it, and the outermost row is its fence. Two different agents prove neither. + if (new Set(recognized.map((entry) => entry.name.agent)).size > 1) { + return { ...metadata, verdict: 'unverifiable', reason: 'ambiguous_foreground_group' } + } + const candidate = recognized[0] + const fence: PosixFence = { + platform: 'posix', + shellPid: root.pid, + shellStartTime: root.startTime, + tty: root.tty, + foregroundPgid: root.tpgid, + ...(candidate?.row.startTime + ? { process: { pid: candidate.row.pid, startTime: candidate.row.startTime } } + : {}) + } + if (candidate && !candidate.row.startTime) { + return { ...metadata, verdict: 'unverifiable', reason: 'candidate_start_time_missing' } + } + return { + ...metadata, + verdict: 'live', + processName: candidate?.name.processName ?? null, + fence + } +} + +function collectDescendantRows(index: ProcessTableIndex, rootPid: number): ProcessTableRow[] { + const result: ProcessTableRow[] = [] + const seen = new Set([rootPid]) + const queue = [rootPid] + for (let cursor = 0; cursor < queue.length; cursor += 1) { + const pid = queue[cursor] + for (const child of index.childrenByPpid.get(pid) ?? []) { + if (seen.has(child.pid)) { + continue + } + seen.add(child.pid) + result.push(child) + queue.push(child.pid) + } + } + return result +} diff --git a/src/main/providers/foreground/stable-process.ts b/src/main/providers/foreground/stable-process.ts new file mode 100644 index 00000000000..2627b9f612f --- /dev/null +++ b/src/main/providers/foreground/stable-process.ts @@ -0,0 +1,27 @@ +import { recognizeAgentProcess } from '../../../shared/agent-status/process/agent-process-recognition' +import type { AgentForegroundProcessResolution } from './agent-process' + +export type StableForegroundProcess = { + processName: string | null + /** Agent name to remember for the next degraded read; null clears the memory. */ + lastRecognizedAgent: string | null +} + +/** Degraded scans cannot prove agent exit; preserve recognized identity until an available scan refreshes or clears it. */ +export function resolveStableForegroundProcess( + resolution: AgentForegroundProcessResolution, + lastRecognizedAgent: string | null +): StableForegroundProcess { + if (resolution.available) { + const isAgent = + resolution.processName !== null && recognizeAgentProcess(resolution.processName) !== null + return { + processName: resolution.processName, + lastRecognizedAgent: isAgent ? resolution.processName : null + } + } + return { + processName: lastRecognizedAgent ?? resolution.processName, + lastRecognizedAgent + } +} diff --git a/src/main/providers/foreground/windows/agent-command-line.ts b/src/main/providers/foreground/windows/agent-command-line.ts new file mode 100644 index 00000000000..0bd6f691bca --- /dev/null +++ b/src/main/providers/foreground/windows/agent-command-line.ts @@ -0,0 +1,21 @@ +import { resolveWindowsForegroundIdentity } from './agent-process' +import { queryWindowsPaneProcessInventory } from './process-rows' + +/** Command line of the pane's foreground agent process, from one fresh native table read. */ +export async function resolveWindowsAgentForegroundCommandLine( + shellPid: number, + foregroundProcess: string +): Promise { + const inventory = await queryWindowsPaneProcessInventory(shellPid, { fresh: true }) + if (!inventory) { + return null + } + const { processId } = resolveWindowsForegroundIdentity( + inventory.candidates, + foregroundProcess, + undefined + ) + return processId === undefined + ? null + : (inventory.candidates.find((candidate) => candidate.pid === processId)?.command ?? null) +} diff --git a/src/main/providers/foreground/windows/agent-process.ts b/src/main/providers/foreground/windows/agent-process.ts new file mode 100644 index 00000000000..4daa952d7be --- /dev/null +++ b/src/main/providers/foreground/windows/agent-process.ts @@ -0,0 +1,319 @@ +import { + isAgentForegroundWrapperProcess, + isExpectedAgentProcess, + recognizeAgentProcess, + recognizeAgentProcessFromCommandLine, + type RecognizedAgentProcess +} from '../../../../shared/agent-status/process/agent-process-recognition' +import { + resolveOuterWrapperForegroundIdentity, + shouldInspectOuterWrapperForegroundProcess +} from '../../../../shared/foreground-wrapper-agent' +import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' +import { + queryWindowsPaneProcessInventory, + type WindowsProcessCandidate, + type WindowsProcessRow +} from './process-rows' + +export type AgentForegroundResolutionOptions = { + contextPaths?: readonly string[] + /** Require a Windows process-table scan started after this request. */ + fresh?: boolean + /** Force confirmation scans even when node-pty reports a recognized name. */ + forceProcessScan?: boolean + /** Lazily proves which global descendants still belong to this ConPTY. */ + readWindowsConsoleAttachedProcessIds?: () => Promise | null> + /** A contradictory full-table command line proves cached anchor PID reuse. */ + anchorProcessId?: number + /** The cached agent name the anchor pid is supposed to prove. */ + anchorProcessName?: string +} + +export type WindowsAgentForegroundResolution = { + available: boolean + processName: string | null + /** Unambiguous recognized-name anchor; use the outer wrapper PID so embedded-child restarts do not imply exit. */ + processId?: number + /** True when the scan proves `anchorProcessId` now belongs to a non-agent. */ + anchorPidForeign?: boolean +} + +type WindowsForegroundIdentity = { + processName: string | null + processId?: number +} + +export function shouldInspectWindowsAgentForeground(fallbackProcess: string): boolean { + const recognized = recognizeAgentProcess(fallbackProcess) + return ( + isAgentForegroundWrapperProcess(fallbackProcess) || + isShellProcess(fallbackProcess) || + (recognized !== null && shouldInspectOuterWrapperForegroundProcess(recognized)) + ) +} + +export async function resolveWindowsAgentForegroundProcessWithAvailability( + shellPid: number, + fallbackProcess: string, + options: AgentForegroundResolutionOptions +): Promise { + const inventory = await queryWindowsPaneProcessInventory(shellPid, { + ...(options.fresh === true ? { fresh: true } : {}), + ...(options.anchorProcessId !== undefined ? { anchorPid: options.anchorProcessId } : {}) + }) + if (!inventory) { + return { available: false, processName: null } + } + const candidates = inventory.candidates + // Filter console membership before ambiguity checks so detached agents cannot suppress the attached input owner. + const hasRecognizedCandidate = windowsCandidatesContainRecognizedAgent( + candidates, + fallbackProcess, + options.contextPaths + ) + let filteredCandidates = candidates + if (hasRecognizedCandidate && options.readWindowsConsoleAttachedProcessIds) { + // Job membership retains detached descendants; only console attachment can exclude their byte authority. + const consoleProcessIds = await options.readWindowsConsoleAttachedProcessIds() + if (!consoleProcessIds) { + return { available: false, processName: null } + } + filteredCandidates = candidates.filter((candidate) => consoleProcessIds.has(candidate.pid)) + } + // Orphaned job members can hold recycled PIDs outside the descendant walk; inspect the full-table anchor. + const anchorRow = inventory.anchorRow + const anchorRecognized = anchorRow === null ? null : recognizeWindowsProcessCandidate(anchorRow) + const anchorPidForeign = + anchorRow !== null && + (anchorRecognized !== null + ? // A recognized row is foreign when it names a DIFFERENT agent. + options.anchorProcessName !== undefined && + anchorRecognized.processName !== options.anchorProcessName + : // Query-denied command === name is inconclusive, never foreign proof. + anchorRow.command !== anchorRow.name) + return { + available: true, + ...resolveWindowsForegroundIdentity(filteredCandidates, fallbackProcess, options.contextPaths), + ...(anchorPidForeign ? { anchorPidForeign: true } : {}) + } +} + +function windowsCandidatesContainRecognizedAgent( + candidates: readonly WindowsProcessCandidate[], + fallbackProcess: string, + contextPaths: readonly string[] | undefined +): boolean { + if (isShellProcess(fallbackProcess)) { + return createRecognizedWindowsProcessCandidates(candidates, contextPaths).length > 0 + } + return candidates + .filter((candidate) => windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess)) + .some( + (candidate) => + recognizeAgentProcessFromCommandLine(candidate.command) !== null || + recognizeAgentProcessFromCommandLine(candidate.name) !== null + ) +} + +export function resolveWindowsForegroundIdentity( + candidates: readonly WindowsProcessCandidate[], + fallbackProcess: string, + contextPaths: readonly string[] | undefined +): WindowsForegroundIdentity { + if (isShellProcess(fallbackProcess)) { + return resolveShellForegroundProcessFromWindowsCandidates(candidates, contextPaths) + } + const wrapperCandidates = candidates.filter((candidate) => + windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess) + ) + if (wrapperCandidates.length !== 1) { + return resolveWrapperForegroundProcessFromWindowsCandidates( + wrapperCandidates, + candidates, + contextPaths + ) + } + const [candidate] = wrapperCandidates + const recognized = + recognizeAgentProcessFromCommandLine(candidate.command) ?? + recognizeAgentProcessFromCommandLine(candidate.name) + if (recognized) { + return resolveOuterWrapperForegroundIdentity(recognized, candidate, candidates) + } + return { processName: null } +} + +function resolveShellForegroundProcessFromWindowsCandidates( + candidates: readonly WindowsProcessCandidate[], + contextPaths: readonly string[] | undefined +): WindowsForegroundIdentity { + const recognizedCandidates = createRecognizedWindowsProcessCandidates(candidates, contextPaths) + const contextCandidates = recognizedCandidates.filter((candidate) => candidate.contextMatch) + if (contextCandidates.length > 0) { + return resolveRecognizedWindowsProcessCandidates(contextCandidates, candidates) + } + return resolveRecognizedWindowsProcessCandidates(recognizedCandidates, candidates) +} + +function resolveWrapperForegroundProcessFromWindowsCandidates( + candidates: readonly WindowsProcessCandidate[], + allCandidates: readonly WindowsProcessCandidate[], + contextPaths: readonly string[] | undefined +): WindowsForegroundIdentity { + const contextCandidates = createRecognizedWindowsProcessCandidates( + candidates, + contextPaths + ).filter((candidate) => candidate.contextMatch) + return contextCandidates.length > 0 + ? resolveRecognizedWindowsProcessCandidates(contextCandidates, allCandidates) + : { processName: null } +} + +type RecognizedWindowsProcessCandidate = WindowsProcessRow & { + contextMatch: boolean + depth: number + processName: string + recognized: RecognizedAgentProcess +} + +function createRecognizedWindowsProcessCandidates( + candidates: readonly WindowsProcessCandidate[], + contextPaths: readonly string[] | undefined +): RecognizedWindowsProcessCandidate[] { + const normalizedContextPaths = normalizeContextPaths(contextPaths) + return candidates.flatMap((candidate) => { + const recognized = recognizeWindowsProcessCandidate(candidate) + if (!recognized) { + return [] + } + return [ + { + ...candidate, + contextMatch: candidateMatchesContextPath(candidate, normalizedContextPaths), + processName: recognized.processName, + recognized + } + ] + }) +} + +function resolveRecognizedWindowsProcessCandidates( + recognizedCandidates: readonly RecognizedWindowsProcessCandidate[], + allCandidates: readonly WindowsProcessCandidate[] +): WindowsForegroundIdentity { + if (recognizedCandidates.length === 0) { + return { processName: null } + } + const candidatesByPid = new Map(allCandidates.map((candidate) => [candidate.pid, candidate])) + const leafCandidates = recognizedCandidates.filter( + (candidate) => + !recognizedCandidates.some( + (other) => + other.pid !== candidate.pid && + windowsCandidateIsAncestor(candidate, other, candidatesByPid) + ) + ) + const leafIdentities = leafCandidates.map((candidate) => + resolveOuterWrapperForegroundIdentity(candidate.recognized, candidate, allCandidates) + ) + const leafProcessNames = new Set(leafIdentities.map((identity) => identity.processName)) + // Windows lacks POSIX foreground markers; disagreeing recognized lineage leaves cannot prove one agent. + if (leafProcessNames.size !== 1) { + return { processName: null } + } + // Anchor the named outer wrapper; its embedded child may exit/restart while the wrapper stays live. + const anchorProcessIds = new Set(leafIdentities.map((identity) => identity.processId)) + return { + processName: [...leafProcessNames][0], + // Distinct anchors agreeing on one name still leave no single liveness anchor. + ...(anchorProcessIds.size === 1 ? { processId: [...anchorProcessIds][0] } : {}) + } +} + +function windowsCandidateIsAncestor( + candidate: WindowsProcessRow, + other: WindowsProcessRow, + candidatesByPid: ReadonlyMap +): boolean { + let current = candidatesByPid.get(other.ppid) + while (current) { + if (current.pid === candidate.pid) { + return true + } + current = candidatesByPid.get(current.ppid) + } + return false +} + +function normalizeContextPaths(contextPaths: readonly string[] | undefined): string[] { + const normalized = new Set() + for (const contextPath of contextPaths ?? []) { + const candidate = normalizePathForCommandMatch(contextPath) + if (isSafeContextPath(candidate)) { + normalized.add(candidate) + } + } + return [...normalized].sort((a, b) => b.length - a.length) +} + +function isSafeContextPath(contextPath: string): boolean { + return contextPath.length >= 4 && (/^[a-z]:\//.test(contextPath) || contextPath.startsWith('//')) +} + +function candidateMatchesContextPath( + candidate: WindowsProcessRow, + normalizedContextPaths: readonly string[] +): boolean { + if (normalizedContextPaths.length === 0) { + return false + } + const haystack = normalizePathForCommandMatch(candidate.command) + return normalizedContextPaths.some((contextPath) => + commandLineContainsPath(haystack, contextPath) + ) +} + +function normalizePathForCommandMatch(value: string): string { + return value + .trim() + .replace(/^["']|["']$/g, '') + .replace(/\\/g, '/') + .replace(/\/+$/g, '') + .toLowerCase() +} + +function commandLineContainsPath(haystack: string, contextPath: string): boolean { + let index = haystack.indexOf(contextPath) + while (index !== -1) { + const before = index > 0 ? haystack[index - 1] : '' + const after = haystack[index + contextPath.length] ?? '' + const beforeOk = !before || /[\s"'(=]/.test(before) + const afterOk = !after || after === '/' || /[\s"'),;]/.test(after) + if (beforeOk && afterOk) { + return true + } + index = haystack.indexOf(contextPath, index + 1) + } + return false +} + +function recognizeWindowsProcessCandidate( + candidate: WindowsProcessRow +): RecognizedAgentProcess | null { + return ( + recognizeAgentProcessFromCommandLine(candidate.command) ?? + recognizeAgentProcessFromCommandLine(candidate.name) + ) +} + +function windowsCandidateMatchesFallbackWrapper( + candidate: WindowsProcessRow, + fallbackProcess: string +): boolean { + const commandToken = candidate.command.trim().split(/\s+/, 1)[0] ?? '' + return ( + isExpectedAgentProcess(candidate.name, fallbackProcess) || + isExpectedAgentProcess(commandToken, fallbackProcess) + ) +} diff --git a/src/main/providers/foreground/windows/cached-agent-revalidation.ts b/src/main/providers/foreground/windows/cached-agent-revalidation.ts new file mode 100644 index 00000000000..15c73ac0830 --- /dev/null +++ b/src/main/providers/foreground/windows/cached-agent-revalidation.ts @@ -0,0 +1,87 @@ +import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' +import { recognizeAgentProcessFromCommandLine } from '../../../../shared/agent-status/process/agent-process-recognition' +import type { AgentForegroundProcessResolution } from '../agent-process' + +/** Unanchored job evidence may outlive console agents; cap it at five renderer confirm ladders (30s). + * Refresh on every positive recognition so the limit never times out a confirmed live agent. */ +export const WINDOWS_DETACHED_DESCENDANT_IDENTITY_MAX_AGE_MS = 30_000 + +export function canRevalidateCachedAgentWithoutScan( + cachedAgentName: string | null, + fallbackProcess: string | null +): boolean { + return ( + cachedAgentName !== null && + fallbackProcess !== null && + // Generic wrappers can outlive agents; only unreliable shell fallbacks may bridge through this cache. + isShellProcess(fallbackProcess) + ) +} + +export type WindowsCachedAgentJobVerdict = + /** Missing native capability: scans decide; distinct from an attempted but unavailable read. */ + | 'unsupported' + /** Anchor pid alive in the job, recently confirmed: identity stands, no scan. */ + | 'confirmed' + /** Anchor pid alive but past the age bound: scan for drift; a silent scan keeps it. */ + | 'recheck' + /** The shell alone in a complete job read: no successor is possible, retire. */ + | 'exited' + /** Other job members may be a restarted successor; keep only age-bounded identity until a scan settles it. */ + | 'anchor-exited' + /** No anchor; a non-shell member exists and the bound has not elapsed: identity stands. */ + | 'unproven' + /** No anchor and the bound elapsed: the superset answer stops standing in for a scan. */ + | 'expired' + /** No job answer: unverifiable per ssh-execution-boundary.md, never exit proof. */ + | 'unavailable' + +/** Complete inescapable-job membership proves anchor liveness/exit; unanchored members only supply age-bounded evidence. */ +export function judgeCachedAgentJobEvidence(args: { + jobProcessIds: ReadonlySet | null + jobSupported?: boolean + shellPid: number + anchorProcessId: number | null + identityAgeMs: number +}): WindowsCachedAgentJobVerdict { + if (args.jobProcessIds === null) { + return args.jobSupported === false ? 'unsupported' : 'unavailable' + } + const withinAgeBound = args.identityAgeMs <= WINDOWS_DETACHED_DESCENDANT_IDENTITY_MAX_AGE_MS + // A shell-pid "anchor" proves nothing about a child; treat it as unanchored. + if (args.anchorProcessId !== null && args.anchorProcessId !== args.shellPid) { + if (!args.jobProcessIds.has(args.anchorProcessId)) { + return args.jobProcessIds.size <= 1 ? 'exited' : 'anchor-exited' + } + return withinAgeBound ? 'confirmed' : 'recheck' + } + if (args.jobProcessIds.size <= 1) { + return 'exited' + } + return withinAgeBound ? 'unproven' : 'expired' +} + +/** Decision authority comes from fresh recognition or a known anchor not yet proved gone. */ +export function reconcileWindowsAgentDecision( + resolution: AgentForegroundProcessResolution, + verdict: WindowsCachedAgentJobVerdict, + anchor: { processName: string; pid: number | null } | null, + shellPid: number +): string | null { + if (resolution.available && recognizeAgentProcessFromCommandLine(resolution.processName ?? '')) { + return resolution.processName + } + if ( + anchor?.pid != null && + anchor.pid !== shellPid && + recognizeAgentProcessFromCommandLine(anchor.processName) && + !resolution.anchorPidForeign && + (verdict === 'confirmed' || + verdict === 'recheck' || + verdict === 'unavailable' || + verdict === 'unsupported') + ) { + return anchor.processName + } + return resolution.available ? resolution.processName : null +} diff --git a/src/main/providers/windows-console-attached-processes.ts b/src/main/providers/foreground/windows/console-attached-processes.ts similarity index 100% rename from src/main/providers/windows-console-attached-processes.ts rename to src/main/providers/foreground/windows/console-attached-processes.ts diff --git a/src/main/providers/foreground/windows/process-rows.ts b/src/main/providers/foreground/windows/process-rows.ts new file mode 100644 index 00000000000..85ed43dc2b7 --- /dev/null +++ b/src/main/providers/foreground/windows/process-rows.ts @@ -0,0 +1,92 @@ +import { + collectDescendantsFromIndex, + getProcessTableIndex +} from '../../../../shared/process-table-index' +import { + readWindowsProcessIdentityTableFresh, + readWindowsProcessTable, + readWindowsProcessTableFresh, + resetWindowsProcessTableForTests, + type WindowsProcessIdentityRow, + type WindowsProcessRow as NativeWindowsProcessRow +} from '../../../windows/windows-process-table' + +export type WindowsProcessRow = { + pid: number + ppid: number + name: string + command: string +} + +export type WindowsProcessCandidate = WindowsProcessRow & { depth: number } + +function toProcessRow(row: NativeWindowsProcessRow): WindowsProcessRow { + return { + pid: row.pid, + ppid: row.ppid, + name: row.name, + // Query denial can hide command lines; preserve image-name recognition as fallback. + command: row.command || row.name + } +} + +/** Share projection identity so per-pane reads also reuse the process-table index; rows remain immutable. */ +const projectedRows = new WeakMap() + +function projectProcessRows(native: readonly NativeWindowsProcessRow[]): WindowsProcessRow[] { + const cached = projectedRows.get(native) + if (cached) { + return cached + } + const rows = native.map(toProcessRow) + projectedRows.set(native, rows) + return rows +} + +/** Ancestry only needs identity rows; requesting unused command lines costs one OpenProcess per row. */ +export async function queryWindowsProcessLinksFresh(): Promise { + return readWindowsProcessIdentityTableFresh() +} + +export async function queryWindowsProcessDescendants( + rootPid: number, + options: { fresh?: boolean } = {} +): Promise { + return (await queryWindowsPaneProcessInventory(rootPid, options))?.candidates ?? null +} + +export type WindowsPaneProcessInventory = { + candidates: WindowsProcessCandidate[] + /** Full-table anchor catches recycled job-member PIDs orphaned outside the descendant walk. */ + anchorRow: WindowsProcessRow | null +} + +export async function queryWindowsPaneProcessInventory( + rootPid: number, + options: { fresh?: boolean; anchorPid?: number } = {} +): Promise { + let rows: WindowsProcessRow[] + try { + const native = + options.fresh === true + ? await readWindowsProcessTableFresh() + : await readWindowsProcessTable() + rows = projectProcessRows(native) + } catch { + return null + } + // Snapshot-shared index avoids per-pane whole-table map builds and linear PID lookups. + const index = getProcessTableIndex(rows) + // Missing roots may indicate stale/filtered snapshots, never observed absence of children. + if (!index.byPid.has(rootPid)) { + return null + } + return { + candidates: collectDescendantsFromIndex(index, rootPid).sort((a, b) => b.depth - a.depth), + anchorRow: options.anchorPid !== undefined ? (index.byPid.get(options.anchorPid) ?? null) : null + } +} + +export function resetWindowsProcessRowsSnapshotForTests(): void { + resetWindowsProcessTableForTests() +} diff --git a/src/main/providers/foreground/windows/pty-job-membership.ts b/src/main/providers/foreground/windows/pty-job-membership.ts new file mode 100644 index 00000000000..88d5bd7e6e2 --- /dev/null +++ b/src/main/providers/foreground/windows/pty-job-membership.ts @@ -0,0 +1,34 @@ +import type { IPty } from 'node-pty' +import { + isPtyJobOwnershipAvailable, + listPtyJobProcessIds, + ptyShellProcessId +} from '../../../windows/windows-pty-job' + +/** Read job membership without console-helper forks (#10857); null is unverifiable, never exit proof. + * Complete membership proves known-anchor liveness/exit and shell-alone state. Unanchored extra members + * may be detached leftovers, so callers must age-bound that evidence rather than claim agent liveness. */ +export function readWindowsPtyJobProcessIds( + proc: IPty, + listJobProcessIds: (proc: IPty) => readonly number[] | null = listPtyJobProcessIds +): ReadonlySet | null { + const pids = listJobProcessIds(proc) + if (!pids) { + return null + } + const membership = new Set(pids.filter((pid) => Number.isSafeInteger(pid) && pid > 0)) + // A size-one set lacking the shell proves a surviving child, never shell-alone state. + const shellPid = ptyShellProcessId(proc) + if (shellPid === undefined || !membership.has(proc.pid) || !membership.has(shellPid)) { + return null + } + if (shellPid !== proc.pid) { + membership.delete(proc.pid) + } + return membership +} + +/** Missing native exports are unsupported, distinct from an attempted but unavailable read. */ +export function isWindowsPtyJobReadable(): boolean { + return isPtyJobOwnershipAvailable() +} diff --git a/src/main/providers/foreground/windows/shell-alone-in-job.ts b/src/main/providers/foreground/windows/shell-alone-in-job.ts new file mode 100644 index 00000000000..4cce888f196 --- /dev/null +++ b/src/main/providers/foreground/windows/shell-alone-in-job.ts @@ -0,0 +1,87 @@ +import { isGitForWindowsBashLauncherPath } from '../../../pty/shell-startup/git-bash' +import type { WindowsProcessIdentityRow } from '../../../windows/windows-process-table' +import { + buildProcessTableIndex, + collectDescendantsFromIndex +} from '../../../../shared/process-table-index' + +const MSYS_BASH_IMAGE = 'bash.exe' + +/** Git Bash launcher/MSYS exec stubs form a live unbranched bash chain; commands add a non-bash leaf or branch. + * Builtin-only/nested bash remains indistinguishable from idle. Optional console proof excludes detached orphans; + * ancestry alone cannot distinguish them from live MSYS children with exited Win32 parents. */ +export async function isWindowsShellAloneInJob( + shellPid: number, + spawnedShellPath: string, + jobProcessIds: ReadonlySet | null | undefined, + readIdentityTable: () => Promise, + readConsoleAttachedProcessIds?: () => Promise | null> +): Promise { + if (!jobProcessIds?.has(shellPid)) { + return false + } + if (jobProcessIds.size === 1) { + return true + } + const isLauncher = isGitForWindowsBashLauncherPath(spawnedShellPath) + if (!isLauncher && !readConsoleAttachedProcessIds) { + return false + } + const rows = (await readIdentityTable()).filter((row) => jobProcessIds.has(row.pid)) + // A member missing from the table exited or was never readable: no proof either way. + if (rows.length !== jobProcessIds.size) { + return false + } + const members = await withoutDetachedOrphans(shellPid, rows, readConsoleAttachedProcessIds) + if (members.length === 1) { + return true + } + if (!isLauncher) { + return false + } + const startMsByPid = new Map(members.map((row) => [row.pid, row.creationTimeMs])) + const visited = new Set([shellPid]) + let parentPid = shellPid + while (visited.size < members.length) { + const children = members.filter((row) => row.ppid === parentPid && !visited.has(row.pid)) + const child = children[0] + if ( + children.length !== 1 || + child.name.toLowerCase() !== MSYS_BASH_IMAGE || + startedBefore(child.creationTimeMs, startMsByPid.get(parentPid)) + ) { + return false + } + visited.add(child.pid) + parentPid = child.pid + } + return true +} + +/** Drops members that are neither linked to the shell through live parents nor on its console. */ +async function withoutDetachedOrphans( + shellPid: number, + members: WindowsProcessIdentityRow[], + readConsoleAttachedProcessIds: (() => Promise | null>) | undefined +): Promise { + if (!readConsoleAttachedProcessIds) { + return members + } + const linked = new Set([ + shellPid, + ...collectDescendantsFromIndex(buildProcessTableIndex(members), shellPid).map((row) => row.pid) + ]) + if (members.every((row) => linked.has(row.pid))) { + return members + } + const attached = await readConsoleAttachedProcessIds().catch(() => null) + return attached ? members.filter((row) => linked.has(row.pid) || attached.has(row.pid)) : members +} + +/** A child older than its parent carries a reused ppid; only checkable when the snapshot has start times. */ +function startedBefore( + childStartMs: number | undefined, + parentStartMs: number | undefined +): boolean { + return childStartMs !== undefined && parentStartMs !== undefined && childStartMs < parentStartMs +} diff --git a/src/main/providers/git-provider-contract.ts b/src/main/providers/git-provider-contract.ts deleted file mode 100644 index c762253d1bb..00000000000 --- a/src/main/providers/git-provider-contract.ts +++ /dev/null @@ -1,164 +0,0 @@ -import type { - GitCommitAction, - GitCommitActionResult -} from '../../shared/git/commands/git-commit-action' -import type { - GitBranchCompareResult, - GitCommitCompareResult, - GitDiffResult -} from '../../shared/git/diff/git-diff-compare-types' -import type { - GitForkSyncExpectedUpstream, - GitForkSyncResult -} from '../../shared/git/remotes/git-fork-sync' -import type { - GitConflictOperation, - GitStagingArea, - GitStatusResult, - GitUpstreamStatus -} from '../../shared/git/status/git-status-types' -import type { GitStageWorktreeScope } from '../../shared/git/paths/git-stage-worktree-scope' -import type { RemoveWorktreeResult } from '../../shared/worktree/create-types' -import type { GitPushTarget, GitWorktreeInfo } from '../../shared/worktree/types' -import type { - GitHistoryItemRef, - GitHistoryOptions, - GitHistoryResult -} from '../../shared/git/history/git-history-types' -import type { CommitMessageDraftContext } from '../../shared/source-control/ai/generation/commit-message-generation' -import type { ConflictResolution } from '../../shared/source-control/listing/source-control-entry-actions' -import type { GitProviderStatusOptions } from './git-provider-status-options' -import type { BranchSwitchCreation } from '../../shared/git/branch-switch-target' -import type { RuntimeGitLocalBranches } from '../../shared/runtime-worktree-contracts' -import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' - -export type { GitProviderStatusOptions } from './git-provider-status-options' - -export type IGitProvider = { - getStatus(worktreePath: string, options?: GitProviderStatusOptions): Promise - getSubmoduleStatus( - worktreePath: string, - submodulePath: string, - area?: GitStagingArea - ): Promise - checkIgnoredPaths(worktreePath: string, relativePaths: string[]): Promise - getHistoryRefs(worktreePath: string, query?: string): Promise - getHistory(worktreePath: string, options?: GitHistoryOptions): Promise - commit(worktreePath: string, message: string): Promise<{ success: boolean; error?: string }> - createBranch( - worktreePath: string, - name: string, - startPoint: string - ): Promise - applyCommit( - worktreePath: string, - operation: GitCommitAction, - commitId: string - ): Promise - recoverSequencer( - worktreePath: string, - operation: GitCommitAction, - action: 'abort' | 'continue' - ): Promise - completeMerge(worktreePath: string): Promise<{ success: boolean; error?: string }> - getStagedCommitContext(worktreePath: string): Promise - getDiff( - worktreePath: string, - filePath: string, - staged: boolean, - compareAgainstHead?: boolean, - oldPath?: string - ): Promise - stageFile(worktreePath: string, filePath: string): Promise - resolveConflict( - worktreePath: string, - filePath: string, - resolution: ConflictResolution - ): Promise - unstageFile(worktreePath: string, filePath: string): Promise - bulkStageFiles( - worktreePath: string, - filePaths: string[], - scope?: GitStageWorktreeScope - ): Promise - bulkUnstageFiles(worktreePath: string, filePaths: string[]): Promise - discardChanges(worktreePath: string, filePath: string): Promise - bulkDiscardChanges(worktreePath: string, filePaths: string[]): Promise - detectConflictOperation(worktreePath: string): Promise - abortMerge(worktreePath: string): Promise - abortRebase(worktreePath: string): Promise - /** `skippedPaths`: files git could not replace (held open on Windows) though the switch landed. */ - checkoutBranch( - worktreePath: string, - branch: string, - creation?: BranchSwitchCreation, - detached?: boolean - ): Promise<{ skippedPaths: string[] }> - listLocalBranches(worktreePath: string): Promise - getBranchCompare( - worktreePath: string, - baseRef: string, - options?: { admissionTier?: GitAdmissionTier } - ): Promise - getCommitCompare(worktreePath: string, commitId: string): Promise - getUpstreamStatus(worktreePath: string, pushTarget?: GitPushTarget): Promise - pushBranch( - worktreePath: string, - publish?: boolean, - pushTarget?: GitPushTarget, - options?: { forceWithLease?: boolean } - ): Promise - pullBranch(worktreePath: string, pushTarget?: GitPushTarget): Promise - fastForwardBranch(worktreePath: string, pushTarget?: GitPushTarget): Promise - rebaseFromBase(worktreePath: string, baseRef: string): Promise - fetchRemote(worktreePath: string, pushTarget?: GitPushTarget): Promise - syncForkDefaultBranch( - worktreePath: string, - expectedUpstream: GitForkSyncExpectedUpstream - ): Promise - getBranchDiff( - worktreePath: string, - baseRef: string, - options?: { includePatch?: boolean; filePath?: string; oldPath?: string; headOid?: string } - ): Promise - getCommitDiff( - worktreePath: string, - args: { commitOid: string; parentOid?: string | null; filePath: string; oldPath?: string } - ): Promise - listWorktrees(repoPath: string, options?: { signal?: AbortSignal }): Promise - addWorktree( - repoPath: string, - branchName: string, - targetDir: string, - options?: { base?: string; checkoutExistingBranch?: boolean; noCheckout?: boolean } - ): Promise - removeWorktree( - worktreePath: string, - force?: boolean, - options?: { deleteBranch?: boolean; forceBranchDelete?: boolean } - ): Promise - renameCurrentBranch?(worktreePath: string, newBranch: string): Promise - forceDeletePreservedBranch?( - repoPath: string, - branchName: string, - expectedHead: string - ): Promise - isGitRepo(path: string): boolean - isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }> - exec( - args: string[], - cwd: string, - options?: { signal?: AbortSignal; timeoutMs?: number } - ): Promise<{ stdout: string; stderr: string }> - getRemoteFileUrl( - worktreePath: string, - relativePath: string, - line: number, - endLine?: number - ): Promise - getRemoteCommitUrl(worktreePath: string, sha: string): Promise - worktreeIsClean( - worktreePath: string, - options?: { includeUntracked?: boolean } - ): Promise<{ clean: boolean; stdout?: string }> -} diff --git a/src/main/providers/git/local-provider.ts b/src/main/providers/git/local-provider.ts new file mode 100644 index 00000000000..f8d5715b714 --- /dev/null +++ b/src/main/providers/git/local-provider.ts @@ -0,0 +1,171 @@ +import { createBranch } from '../../git/worktrees/checkout/create-branch' +import { applyCommit, recoverSequencer } from '../../git/worktrees/checkout/commit-actions' +import { gitSyncForkDefaultBranch } from '../../git/remotes/fork-sync' +import type { GitRuntimeOptions } from '../../git/command-runner/git-runtime-options' +import { checkIgnoredPaths } from '../../git/source-control/ignores/check-ignored-paths' +import { checkoutBranch, listLocalBranches } from '../../git/worktrees/checkout/checkout' +import { getHistory, getHistoryRefs } from '../../git/source-control/history' +import { gitFastForward, gitFetch, gitPull, gitPush } from '../../git/remotes/remote' +import { gitPullRebaseFromBase } from '../../git/remotes/remote-rebase' +import { getRemoteCommitUrl, getRemoteFileUrl } from '../../git/remotes/repo-remote-queries' +import { isGitRepo } from '../../git/repositories/discovery/repo-detection' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' +import { + abortMerge, + abortRebase, + detectConflictOperation +} from '../../git/source-control/mutations/git-conflict-operation' +import { + bulkDiscardChanges, + discardChanges +} from '../../git/source-control/mutations/discard-changes' +import { + bulkStageFiles, + bulkUnstageFiles, + resolveConflict, + stageFile, + stageWorktreeChanges, + unstageFile +} from '../../git/source-control/mutations/staging' +import { commitChanges, completeMerge } from '../../git/source-control/mutations/commit-changes' +import { getBranchCompare } from '../../git/source-control/comparisons/branch-compare' +import { getCommitCompare } from '../../git/source-control/comparisons/commit-compare' +import { getCommitDiff } from '../../git/source-control/comparisons/commit-diff' +import { getDiff } from '../../git/source-control/diffs/file-diff' +import { getStagedCommitContext } from '../../git/source-control/mutations/staged-commit-context' +import { getStatus } from '../../git/source-control/status/status-read' +import { getSubmoduleStatus } from '../../git/source-control/submodules/submodule-status' +import { getUpstreamStatus } from '../../git/source-control/upstream/upstream' +import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache' +import type { IGitProvider } from './provider-contract' + +/** Per-worktree execution options; build one provider per call and never cache it (WSL routing). */ +export type LocalGitProviderOptions = GitRuntimeOptions & { + /** Shared symlinks Git cannot ignore. Lazy: only status and stage-all read the repo config. */ + getSharedLinkPaths?: () => readonly string[] +} + +/** Methods needing extra local inputs, such as repo paths or pinned diffs, retain their existing call sites. */ +export type LocalGitProvider = Omit< + IGitProvider, + | 'getBranchDiff' + | 'addWorktree' + | 'removeWorktree' + | 'isGitRepoAsync' + | 'worktreeIsClean' + | 'renameCurrentBranch' + | 'forceDeletePreservedBranch' +> + +export function createLocalGitProvider(options: LocalGitProviderOptions = {}): LocalGitProvider { + const { getSharedLinkPaths = () => [], ...base } = options + const interactive = { ...base, admissionTier: 'interactive' as const } + return { + getStatus: (worktreePath, statusOptions) => { + // Shared directory symlinks do not match Git directory-only ignore rules. + const sharedLinkPaths = getSharedLinkPaths() + return getStatus(worktreePath, { + ...statusOptions, + ...base, + admissionTier: statusOptions?.admissionTier ?? 'status', + ...(sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {}) + }) + }, + getSubmoduleStatus: (worktreePath, submodulePath, area = 'unstaged') => + getSubmoduleStatus(worktreePath, submodulePath, { + ...interactive, + ...(area === 'staged' ? { staged: true } : {}) + }), + checkIgnoredPaths: (worktreePath, relativePaths) => + checkIgnoredPaths(worktreePath, relativePaths, interactive), + getHistoryRefs: (worktreePath, query) => getHistoryRefs(worktreePath, query, interactive), + getHistory: (worktreePath, historyOptions = {}) => + getHistory(worktreePath, { ...historyOptions, ...interactive }), + commit: (worktreePath, message) => commitChanges(worktreePath, message, interactive), + createBranch: (worktreePath, name, startPoint) => + createBranch(worktreePath, name, startPoint, interactive), + applyCommit: (worktreePath, operation, commitId) => + applyCommit(worktreePath, operation, commitId, interactive), + recoverSequencer: (worktreePath, operation, action) => + recoverSequencer(worktreePath, operation, action, interactive), + completeMerge: (worktreePath) => completeMerge(worktreePath, interactive), + getStagedCommitContext: (worktreePath) => getStagedCommitContext(worktreePath, interactive), + getDiff: (worktreePath, filePath, staged, compareAgainstHead, oldPath) => + getDiff(worktreePath, filePath, staged, compareAgainstHead, { + ...interactive, + ...(oldPath ? { oldPath } : {}) + }), + stageFile: (worktreePath, filePath) => stageFile(worktreePath, filePath, interactive), + resolveConflict: (worktreePath, filePath, resolution) => + resolveConflict(worktreePath, filePath, resolution, interactive), + unstageFile: (worktreePath, filePath) => unstageFile(worktreePath, filePath, interactive), + bulkStageFiles: async (worktreePath, filePaths, scope) => { + if (scope) { + await stageWorktreeChanges(worktreePath, scope, { + ...interactive, + sharedLinkPaths: getSharedLinkPaths() + }) + return + } + await bulkStageFiles(worktreePath, filePaths, interactive) + }, + bulkUnstageFiles: (worktreePath, filePaths) => + bulkUnstageFiles(worktreePath, filePaths, interactive), + discardChanges: (worktreePath, filePath) => discardChanges(worktreePath, filePath, interactive), + bulkDiscardChanges: (worktreePath, filePaths) => + bulkDiscardChanges(worktreePath, filePaths, interactive), + detectConflictOperation: (worktreePath) => detectConflictOperation(worktreePath, base), + abortMerge: (worktreePath) => abortMerge(worktreePath, interactive), + abortRebase: (worktreePath) => abortRebase(worktreePath, interactive), + checkoutBranch: (worktreePath, branch, creation, detached) => + checkoutBranch( + worktreePath, + branch, + { ...interactive, ...(detached ? { detached } : {}) }, + creation + ), + listLocalBranches: (worktreePath) => listLocalBranches(worktreePath, base), + getBranchCompare: (worktreePath, baseRef, compareOptions) => + getBranchCompare(worktreePath, baseRef, { + ...base, + admissionTier: compareOptions?.admissionTier ?? 'interactive' + }), + getCommitCompare: (worktreePath, commitId) => + getCommitCompare(worktreePath, commitId, interactive), + getUpstreamStatus: (worktreePath, pushTarget) => + getUpstreamStatus(worktreePath, pushTarget, base), + pushBranch: (worktreePath, publish, pushTarget, pushOptions) => + gitPush(worktreePath, publish === true, pushTarget, { + forceWithLease: pushOptions?.forceWithLease === true, + ...interactive + }), + pullBranch: (worktreePath, pushTarget) => gitPull(worktreePath, pushTarget, interactive), + fastForwardBranch: (worktreePath, pushTarget) => + gitFastForward(worktreePath, pushTarget, interactive), + rebaseFromBase: (worktreePath, baseRef) => + gitPullRebaseFromBase(worktreePath, baseRef, interactive), + fetchRemote: (worktreePath, pushTarget) => gitFetch(worktreePath, pushTarget, interactive), + syncForkDefaultBranch: (worktreePath, expectedUpstream) => + gitSyncForkDefaultBranch(worktreePath, expectedUpstream, interactive), + getCommitDiff: (worktreePath, args) => getCommitDiff(worktreePath, args, interactive), + listWorktrees: (repoPath, listOptions) => + listWorktrees(repoPath, listOptions?.signal ? { ...base, signal: listOptions.signal } : base), + isGitRepo: (path) => isGitRepo(path), + exec: (args, cwd, execOptions) => + gitExecFileAsync(args, { + ...base, + cwd, + ...(execOptions?.signal ? { signal: execOptions.signal } : {}), + ...(execOptions?.timeoutMs === undefined ? {} : { timeout: execOptions.timeoutMs }) + }), + getRemoteFileUrl: async (worktreePath, relativePath, line, endLine) => { + await awaitWindowsHostGitEnvironmentReady({ ...base, cwd: worktreePath }) + return getRemoteFileUrl(worktreePath, relativePath, line, endLine, base) + }, + getRemoteCommitUrl: async (worktreePath, sha) => { + await awaitWindowsHostGitEnvironmentReady({ cwd: worktreePath }) + return getRemoteCommitUrl(worktreePath, sha) + } + } +} diff --git a/src/main/providers/git/provider-contract.ts b/src/main/providers/git/provider-contract.ts new file mode 100644 index 00000000000..e755c67e01e --- /dev/null +++ b/src/main/providers/git/provider-contract.ts @@ -0,0 +1,162 @@ +import type { + GitCommitAction, + GitCommitActionResult +} from '../../../shared/git/commands/git-commit-action' +import type { + GitBranchCompareResult, + GitCommitCompareResult, + GitDiffResult +} from '../../../shared/git/diff/git-diff-compare-types' +import type { + GitForkSyncExpectedUpstream, + GitForkSyncResult +} from '../../../shared/git/remotes/git-fork-sync' +import type { + GitConflictOperation, + GitStagingArea, + GitStatusResult, + GitUpstreamStatus +} from '../../../shared/git/status/git-status-types' +import type { GitStageWorktreeScope } from '../../../shared/git/paths/git-stage-worktree-scope' +import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' +import type { GitPushTarget, GitWorktreeInfo } from '../../../shared/worktree/types' +import type { + GitHistoryItemRef, + GitHistoryOptions, + GitHistoryResult +} from '../../../shared/git/history/git-history-types' +import type { CommitMessageDraftContext } from '../../../shared/source-control/ai/generation/commit-message-generation' +import type { ConflictResolution } from '../../../shared/source-control/listing/source-control-entry-actions' +import type { GitProviderStatusOptions } from './status-options' +import type { BranchSwitchCreation } from '../../../shared/git/branch-switch-target' +import type { RuntimeGitLocalBranches } from '../../../shared/runtime-worktree-contracts' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' + +export type IGitProvider = { + getStatus(worktreePath: string, options?: GitProviderStatusOptions): Promise + getSubmoduleStatus( + worktreePath: string, + submodulePath: string, + area?: GitStagingArea + ): Promise + checkIgnoredPaths(worktreePath: string, relativePaths: string[]): Promise + getHistoryRefs(worktreePath: string, query?: string): Promise + getHistory(worktreePath: string, options?: GitHistoryOptions): Promise + commit(worktreePath: string, message: string): Promise<{ success: boolean; error?: string }> + createBranch( + worktreePath: string, + name: string, + startPoint: string + ): Promise + applyCommit( + worktreePath: string, + operation: GitCommitAction, + commitId: string + ): Promise + recoverSequencer( + worktreePath: string, + operation: GitCommitAction, + action: 'abort' | 'continue' + ): Promise + completeMerge(worktreePath: string): Promise<{ success: boolean; error?: string }> + getStagedCommitContext(worktreePath: string): Promise + getDiff( + worktreePath: string, + filePath: string, + staged: boolean, + compareAgainstHead?: boolean, + oldPath?: string + ): Promise + stageFile(worktreePath: string, filePath: string): Promise + resolveConflict( + worktreePath: string, + filePath: string, + resolution: ConflictResolution + ): Promise + unstageFile(worktreePath: string, filePath: string): Promise + bulkStageFiles( + worktreePath: string, + filePaths: string[], + scope?: GitStageWorktreeScope + ): Promise + bulkUnstageFiles(worktreePath: string, filePaths: string[]): Promise + discardChanges(worktreePath: string, filePath: string): Promise + bulkDiscardChanges(worktreePath: string, filePaths: string[]): Promise + detectConflictOperation(worktreePath: string): Promise + abortMerge(worktreePath: string): Promise + abortRebase(worktreePath: string): Promise + /** `skippedPaths`: files git could not replace (held open on Windows) though the switch landed. */ + checkoutBranch( + worktreePath: string, + branch: string, + creation?: BranchSwitchCreation, + detached?: boolean + ): Promise<{ skippedPaths: string[] }> + listLocalBranches(worktreePath: string): Promise + getBranchCompare( + worktreePath: string, + baseRef: string, + options?: { admissionTier?: GitAdmissionTier } + ): Promise + getCommitCompare(worktreePath: string, commitId: string): Promise + getUpstreamStatus(worktreePath: string, pushTarget?: GitPushTarget): Promise + pushBranch( + worktreePath: string, + publish?: boolean, + pushTarget?: GitPushTarget, + options?: { forceWithLease?: boolean } + ): Promise + pullBranch(worktreePath: string, pushTarget?: GitPushTarget): Promise + fastForwardBranch(worktreePath: string, pushTarget?: GitPushTarget): Promise + rebaseFromBase(worktreePath: string, baseRef: string): Promise + fetchRemote(worktreePath: string, pushTarget?: GitPushTarget): Promise + syncForkDefaultBranch( + worktreePath: string, + expectedUpstream: GitForkSyncExpectedUpstream + ): Promise + getBranchDiff( + worktreePath: string, + baseRef: string, + options?: { includePatch?: boolean; filePath?: string; oldPath?: string; headOid?: string } + ): Promise + getCommitDiff( + worktreePath: string, + args: { commitOid: string; parentOid?: string | null; filePath: string; oldPath?: string } + ): Promise + listWorktrees(repoPath: string, options?: { signal?: AbortSignal }): Promise + addWorktree( + repoPath: string, + branchName: string, + targetDir: string, + options?: { base?: string; checkoutExistingBranch?: boolean; noCheckout?: boolean } + ): Promise + removeWorktree( + worktreePath: string, + force?: boolean, + options?: { deleteBranch?: boolean; forceBranchDelete?: boolean } + ): Promise + renameCurrentBranch?(worktreePath: string, newBranch: string): Promise + forceDeletePreservedBranch?( + repoPath: string, + branchName: string, + expectedHead: string + ): Promise + isGitRepo(path: string): boolean + isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }> + exec( + args: string[], + cwd: string, + options?: { signal?: AbortSignal; timeoutMs?: number } + ): Promise<{ stdout: string; stderr: string }> + getRemoteFileUrl( + worktreePath: string, + relativePath: string, + line: number, + endLine?: number + ): Promise + getRemoteCommitUrl(worktreePath: string, sha: string): Promise + worktreeIsClean( + worktreePath: string, + options?: { includeUntracked?: boolean } + ): Promise<{ clean: boolean; stdout?: string }> +} diff --git a/src/main/providers/git-provider-status-options.ts b/src/main/providers/git/status-options.ts similarity index 100% rename from src/main/providers/git-provider-status-options.ts rename to src/main/providers/git/status-options.ts diff --git a/src/main/providers/local-filesystem-provider.test.ts b/src/main/providers/local-filesystem-provider.test.ts deleted file mode 100644 index 8f52f8e2132..00000000000 --- a/src/main/providers/local-filesystem-provider.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' -import { createLocalFilesystemProvider } from './local-filesystem-provider' - -let root: string -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the provider reads only settings from the store; authorization is the injected stub. -const store = { - getSettings: () => ({ followSymlinkedDirectories: true }) -} as unknown as RuntimeStore -const authorize = vi.fn(async (path: string, _store: RuntimeStore, _options?: unknown) => path) -const provider = () => - createLocalFilesystemProvider({ requireStore: () => store, resolveAuthorizedPath: authorize }) - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-local-fs-provider-')) - authorize.mockClear() -}) -afterEach(() => rm(root, { recursive: true, force: true })) - -describe('createLocalFilesystemProvider', () => { - it('authorizes every path against the injected store before touching it', async () => { - const file = join(root, 'a', 'b.txt') - await provider().writeFileBase64(file, Buffer.from('hi').toString('base64')) - await provider().writeFileBase64Chunk(file, Buffer.from('!').toString('base64'), true) - expect(await readFile(file, 'utf8')).toBe('hi!') - expect(authorize).toHaveBeenCalledWith(file, store) - await expect(provider().writeFileBase64(file, '')).rejects.toMatchObject({ code: 'EEXIST' }) - }) - - // Why: creating symlinks needs elevated rights on Windows runners. - it.skipIf(process.platform === 'win32')( - 'renames, copies and deletes a symlink itself rather than its target', - async () => { - const target = join(root, 'target.txt') - const link = join(root, 'link.txt') - await writeFile(target, 'body') - await symlink(target, link) - await provider().renameNoClobber(link, join(root, 'moved.txt')) - expect(await readlink(join(root, 'moved.txt'))).toBe(target) - await provider().copy(target, join(root, 'nested', 'copy.txt')) - await expect(provider().copy(target, join(root, 'nested', 'copy.txt'))).rejects.toMatchObject( - { code: 'EEXIST' } - ) - await provider().deletePath(join(root, 'moved.txt')) - expect(await readFile(target, 'utf8')).toBe('body') - for (const call of authorize.mock.calls.filter(([path]) => path !== target)) { - expect(call[2]).toEqual({ preserveSymlink: true }) - } - } - ) - - it.skipIf(process.platform === 'win32')( - 'follows symlinked directories by the store setting unless the caller overrides it', - async () => { - await mkdir(join(root, 'real')) - await symlink(join(root, 'real'), join(root, 'alias')) - const isAliasDir = async (followSymlinks?: boolean) => - (await provider().readDir(root, { followSymlinks })).find((entry) => entry.name === 'alias') - ?.isDirectory - expect(await isAliasDir()).toBe(true) - expect(await isAliasDir(false)).toBe(false) - } - ) -}) diff --git a/src/main/providers/local-filesystem-provider.ts b/src/main/providers/local-filesystem-provider.ts deleted file mode 100644 index 6847fcf5085..00000000000 --- a/src/main/providers/local-filesystem-provider.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { constants, copyFile, lstat, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises' -import { dirname } from 'node:path' -import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../shared/abort-signal-reason' -import { - readAuthorizedDocPreviewFile, - readAuthorizedDocPreviewFileChunk -} from '../../shared/document-preview/doc-preview-file-access' -import { renameLocalPathSerializedByDestination } from '../filesystem/destination-serialized-local-rename' -import type { resolveAuthorizedPath as ResolveAuthorizedPath } from '../ipc/filesystem/access/filesystem-auth' -import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' -import { - assertNotExists, - rethrowWithUserMessage -} from '../ipc/filesystem/filesystem-create-path-guards' -import { classifyFilesystemDirectoryEntries } from '../ipc/filesystem/filesystem-symlink-directory-entries' -import { getLocalGitOptionsForRegisteredWorktree } from '../ipc/local-worktree-runtime-options' -import { listMarkdownDocuments } from '../ipc/markdown-documents' -import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' -import { runBundledRipgrepTextSearch } from '../ripgrep/bundled-ripgrep-text-search' -import { resolveBundledRipgrepWslRouting } from '../ripgrep/bundled-ripgrep-wsl-routing' -import type { IFilesystemProvider } from './filesystem-provider-contract' -import type { - FileWriteDiskPrecondition, - FileWriteResult -} from '../../shared/file-write/file-write-disk-precondition' -import { writeLocalTextFileWithDiskPrecondition } from '../ipc/filesystem/local-disk-write-precondition' -import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' - -export type LocalFilesystemProviderOptions = { - /** Read lazily so a call that fails earlier never touches the store. */ - requireStore(): RuntimeStore - /** Injected: the auth layer reaches the host router, so importing it here would be a cycle. */ - resolveAuthorizedPath: typeof ResolveAuthorizedPath -} - -/** Local twins for runtime commands; reads/listing/watching retain call sites with different limits/shapes. */ -export type LocalFilesystemProvider = Required< - Pick -> & - Pick< - IFilesystemProvider, - | 'readDir' - | 'readDocPreviewFile' - | 'writeFile' - | 'writeFileBase64' - | 'writeFileBase64Chunk' - | 'pathsExist' - | 'stat' - | 'deletePath' - | 'createFile' - | 'createDir' - | 'createDirNoClobber' - | 'renameNoClobber' - | 'copy' - | 'search' - > & { - writeFileWithDiskPrecondition( - filePath: string, - content: string, - precondition: FileWriteDiskPrecondition | undefined - ): Promise - } - -/** Build per call so path authorization uses the current store. */ -export function createLocalFilesystemProvider( - options: LocalFilesystemProviderOptions -): LocalFilesystemProvider { - const { resolveAuthorizedPath } = options - // Authorized in the caller's spelling; a UNC drive-mount path is opened by its drive path. - const authorize = async (path: string) => - windowsFsPath(await resolveAuthorizedPath(path, options.requireStore())) - // Rename/copy/delete must authorize the symlink itself, preserving its target. - const authorizeLink = async (path: string) => - windowsFsPath( - await resolveAuthorizedPath(path, options.requireStore(), { preserveSymlink: true }) - ) - const writeBase64 = async (filePath: string, contentBase64: string, append: boolean) => { - const content = Buffer.from(contentBase64, 'base64') - const authorizedPath = await authorize(filePath) - await mkdir(dirname(authorizedPath), { recursive: true }) - await writeFile(authorizedPath, content, { flag: append ? 'a' : 'wx' }) - } - const writeTextFile = async ( - filePath: string, - content: string, - precondition: FileWriteDiskPrecondition | undefined - ): Promise => { - const authorizedPath = await authorize(filePath) - try { - if ((await lstat(authorizedPath)).isDirectory()) { - throw new Error('Cannot write to a directory') - } - } catch (error) { - if (!isENOENT(error)) { - throw error - } - } - return writeLocalTextFileWithDiskPrecondition(authorizedPath, content, precondition) - } - return { - readDir: async (dirPath, readOptions = {}) => { - const entries = await readdir(await authorize(dirPath), { withFileTypes: true }) - const store = options.requireStore() - return classifyFilesystemDirectoryEntries( - dirPath, - entries, - readOptions.followSymlinks ?? store.getSettings().followSymlinkedDirectories ?? false, - (path) => resolveAuthorizedPath(path, store) - ) - }, - readDocPreviewFile: readAuthorizedDocPreviewFile, - readDocPreviewFileChunk: readAuthorizedDocPreviewFileChunk, - writeFile: async (filePath, content) => { - await writeTextFile(filePath, content, undefined) - }, - writeFileWithDiskPrecondition: writeTextFile, - writeFileBase64: (filePath, contentBase64) => writeBase64(filePath, contentBase64, false), - writeFileBase64Chunk: writeBase64, - stat: async (filePath) => { - const stats = await stat(await authorize(filePath)) - return { - size: stats.size, - type: stats.isDirectory() ? 'directory' : 'file', - mtime: stats.mtimeMs, - ctimeMs: stats.ctimeMs - } - }, - deletePath: async (targetPath, recursive) => { - await rm(await authorizeLink(targetPath), { recursive: recursive === true, force: true }) - }, - createFile: async (filePath) => { - const authorizedPath = await authorize(filePath) - await mkdir(dirname(authorizedPath), { recursive: true }) - try { - await writeFile(authorizedPath, '', { encoding: 'utf-8', flag: 'wx' }) - } catch (error) { - rethrowWithUserMessage(error, authorizedPath) - } - }, - createDir: async (dirPath) => { - const authorizedPath = await authorize(dirPath) - await assertNotExists(authorizedPath) - await mkdir(authorizedPath, { recursive: false }) - }, - createDirNoClobber: async (dirPath) => { - await mkdir(await authorize(dirPath), { recursive: false }) - }, - renameNoClobber: async (oldPath, newPath) => { - const authorizedOldPath = await authorizeLink(oldPath) - await renameLocalPathSerializedByDestination(authorizedOldPath, await authorizeLink(newPath)) - }, - copy: async (source, destination) => { - const authorizedSource = await authorizeLink(source) - const authorizedDestination = await authorizeLink(destination) - await mkdir(dirname(authorizedDestination), { recursive: true }) - // Callers deconflict names; COPYFILE_EXCL preserves no-clobber if a destination appears meanwhile. - await copyFile(authorizedSource, authorizedDestination, constants.COPYFILE_EXCL) - }, - search: async (searchOptions, { signal } = {}) => { - throwIfSignalAborted(signal) - const store = options.requireStore() - const rootPath = await waitForPromiseWithSignal( - resolveAuthorizedPath(searchOptions.rootPath, store), - signal - ) - throwIfSignalAborted(signal) - const { wslDistro, wslDistroForOutput } = resolveBundledRipgrepWslRouting( - rootPath, - getLocalGitOptionsForRegisteredWorktree(store, searchOptions.rootPath, rootPath).wslDistro - ) - return runBundledRipgrepTextSearch({ - options: searchOptions, - rootPath, - resultRootPath: rootPath, - wslDistro, - wslDistroForOutput, - signal, - // Request abort owns cancellation; only renderer IPC needs a by-id registry. - onSpawn: () => () => undefined - }) - }, - listMarkdownDocuments: (rootPath) => - listMarkdownDocuments( - rootPath, - getLocalGitOptionsForRegisteredWorktree(options.requireStore(), rootPath, rootPath) - ) - } -} diff --git a/src/main/providers/local-git-provider.ts b/src/main/providers/local-git-provider.ts deleted file mode 100644 index cac84249253..00000000000 --- a/src/main/providers/local-git-provider.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { createBranch } from '../git/worktrees/checkout/create-branch' -import { applyCommit, recoverSequencer } from '../git/worktrees/checkout/commit-actions' -import { gitSyncForkDefaultBranch } from '../git/remotes/fork-sync' -import type { GitRuntimeOptions } from '../git/command-runner/git-runtime-options' -import { checkIgnoredPaths } from '../git/source-control/check-ignored-paths' -import { checkoutBranch, listLocalBranches } from '../git/worktrees/checkout/checkout' -import { getHistory, getHistoryRefs } from '../git/source-control/history' -import { gitFastForward, gitFetch, gitPull, gitPush } from '../git/remotes/remote' -import { gitPullRebaseFromBase } from '../git/remotes/remote-rebase' -import { getRemoteCommitUrl, getRemoteFileUrl } from '../git/remotes/repo-remote-queries' -import { isGitRepo } from '../git/repositories/discovery/repo-detection' -import { awaitWindowsHostGitEnvironmentReady } from '../git/command-runner/host-routing/windows-host-git-environment' -import { gitExecFileAsync } from '../git/command-runner/git-exec-file' -import { - abortMerge, - abortRebase, - detectConflictOperation -} from '../git/source-control/git-conflict-operation' -import { bulkDiscardChanges, discardChanges } from '../git/source-control/discard-changes' -import { - bulkStageFiles, - bulkUnstageFiles, - resolveConflict, - stageFile, - stageWorktreeChanges, - unstageFile -} from '../git/source-control/staging' -import { commitChanges, completeMerge } from '../git/source-control/commit-changes' -import { getBranchCompare } from '../git/source-control/branch-compare' -import { getCommitCompare } from '../git/source-control/commit-compare' -import { getCommitDiff } from '../git/source-control/commit-diff' -import { getDiff } from '../git/source-control/file-diff' -import { getStagedCommitContext } from '../git/source-control/staged-commit-context' -import { getStatus } from '../git/source-control/status-read' -import { getSubmoduleStatus } from '../git/source-control/submodule-status' -import { getUpstreamStatus } from '../git/source-control/upstream' -import { listWorktrees } from '../git/worktrees/catalog/worktree-scan-cache' -import type { IGitProvider } from './git-provider-contract' - -/** Per-worktree execution options; build one provider per call and never cache it (WSL routing). */ -export type LocalGitProviderOptions = GitRuntimeOptions & { - /** Shared symlinks Git cannot ignore. Lazy: only status and stage-all read the repo config. */ - getSharedLinkPaths?: () => readonly string[] -} - -/** Methods needing extra local inputs, such as repo paths or pinned diffs, retain their existing call sites. */ -export type LocalGitProvider = Omit< - IGitProvider, - | 'getBranchDiff' - | 'addWorktree' - | 'removeWorktree' - | 'isGitRepoAsync' - | 'worktreeIsClean' - | 'renameCurrentBranch' - | 'forceDeletePreservedBranch' -> - -export function createLocalGitProvider(options: LocalGitProviderOptions = {}): LocalGitProvider { - const { getSharedLinkPaths = () => [], ...base } = options - const interactive = { ...base, admissionTier: 'interactive' as const } - return { - getStatus: (worktreePath, statusOptions) => { - // Shared directory symlinks do not match Git directory-only ignore rules. - const sharedLinkPaths = getSharedLinkPaths() - return getStatus(worktreePath, { - ...statusOptions, - ...base, - admissionTier: statusOptions?.admissionTier ?? 'status', - ...(sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {}) - }) - }, - getSubmoduleStatus: (worktreePath, submodulePath, area = 'unstaged') => - getSubmoduleStatus(worktreePath, submodulePath, { - ...interactive, - ...(area === 'staged' ? { staged: true } : {}) - }), - checkIgnoredPaths: (worktreePath, relativePaths) => - checkIgnoredPaths(worktreePath, relativePaths, interactive), - getHistoryRefs: (worktreePath, query) => getHistoryRefs(worktreePath, query, interactive), - getHistory: (worktreePath, historyOptions = {}) => - getHistory(worktreePath, { ...historyOptions, ...interactive }), - commit: (worktreePath, message) => commitChanges(worktreePath, message, interactive), - createBranch: (worktreePath, name, startPoint) => - createBranch(worktreePath, name, startPoint, interactive), - applyCommit: (worktreePath, operation, commitId) => - applyCommit(worktreePath, operation, commitId, interactive), - recoverSequencer: (worktreePath, operation, action) => - recoverSequencer(worktreePath, operation, action, interactive), - completeMerge: (worktreePath) => completeMerge(worktreePath, interactive), - getStagedCommitContext: (worktreePath) => getStagedCommitContext(worktreePath, interactive), - getDiff: (worktreePath, filePath, staged, compareAgainstHead, oldPath) => - getDiff(worktreePath, filePath, staged, compareAgainstHead, { - ...interactive, - ...(oldPath ? { oldPath } : {}) - }), - stageFile: (worktreePath, filePath) => stageFile(worktreePath, filePath, interactive), - resolveConflict: (worktreePath, filePath, resolution) => - resolveConflict(worktreePath, filePath, resolution, interactive), - unstageFile: (worktreePath, filePath) => unstageFile(worktreePath, filePath, interactive), - bulkStageFiles: async (worktreePath, filePaths, scope) => { - if (scope) { - await stageWorktreeChanges(worktreePath, scope, { - ...interactive, - sharedLinkPaths: getSharedLinkPaths() - }) - return - } - await bulkStageFiles(worktreePath, filePaths, interactive) - }, - bulkUnstageFiles: (worktreePath, filePaths) => - bulkUnstageFiles(worktreePath, filePaths, interactive), - discardChanges: (worktreePath, filePath) => discardChanges(worktreePath, filePath, interactive), - bulkDiscardChanges: (worktreePath, filePaths) => - bulkDiscardChanges(worktreePath, filePaths, interactive), - detectConflictOperation: (worktreePath) => detectConflictOperation(worktreePath, base), - abortMerge: (worktreePath) => abortMerge(worktreePath, interactive), - abortRebase: (worktreePath) => abortRebase(worktreePath, interactive), - checkoutBranch: (worktreePath, branch, creation, detached) => - checkoutBranch( - worktreePath, - branch, - { ...interactive, ...(detached ? { detached } : {}) }, - creation - ), - listLocalBranches: (worktreePath) => listLocalBranches(worktreePath, base), - getBranchCompare: (worktreePath, baseRef, compareOptions) => - getBranchCompare(worktreePath, baseRef, { - ...base, - admissionTier: compareOptions?.admissionTier ?? 'interactive' - }), - getCommitCompare: (worktreePath, commitId) => - getCommitCompare(worktreePath, commitId, interactive), - getUpstreamStatus: (worktreePath, pushTarget) => - getUpstreamStatus(worktreePath, pushTarget, base), - pushBranch: (worktreePath, publish, pushTarget, pushOptions) => - gitPush(worktreePath, publish === true, pushTarget, { - forceWithLease: pushOptions?.forceWithLease === true, - ...interactive - }), - pullBranch: (worktreePath, pushTarget) => gitPull(worktreePath, pushTarget, interactive), - fastForwardBranch: (worktreePath, pushTarget) => - gitFastForward(worktreePath, pushTarget, interactive), - rebaseFromBase: (worktreePath, baseRef) => - gitPullRebaseFromBase(worktreePath, baseRef, interactive), - fetchRemote: (worktreePath, pushTarget) => gitFetch(worktreePath, pushTarget, interactive), - syncForkDefaultBranch: (worktreePath, expectedUpstream) => - gitSyncForkDefaultBranch(worktreePath, expectedUpstream, interactive), - getCommitDiff: (worktreePath, args) => getCommitDiff(worktreePath, args, interactive), - listWorktrees: (repoPath, listOptions) => - listWorktrees(repoPath, listOptions?.signal ? { ...base, signal: listOptions.signal } : base), - isGitRepo: (path) => isGitRepo(path), - exec: (args, cwd, execOptions) => - gitExecFileAsync(args, { - ...base, - cwd, - ...(execOptions?.signal ? { signal: execOptions.signal } : {}), - ...(execOptions?.timeoutMs === undefined ? {} : { timeout: execOptions.timeoutMs }) - }), - getRemoteFileUrl: async (worktreePath, relativePath, line, endLine) => { - await awaitWindowsHostGitEnvironmentReady({ ...base, cwd: worktreePath }) - return getRemoteFileUrl(worktreePath, relativePath, line, endLine, base) - }, - getRemoteCommitUrl: async (worktreePath, sha) => { - await awaitWindowsHostGitEnvironmentReady({ cwd: worktreePath }) - return getRemoteCommitUrl(worktreePath, sha) - } - } -} diff --git a/src/main/providers/local-pty/local-pty-child-process-verdict.test.ts b/src/main/providers/local-pty/local-pty-child-process-verdict.test.ts deleted file mode 100644 index 95d8ed7394d..00000000000 --- a/src/main/providers/local-pty/local-pty-child-process-verdict.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import * as pty from 'node-pty' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as PtyMasterForegroundObservation from '../../pty/process-retirement/pty-master-foreground-observation' - -const { resolveForegroundMock } = vi.hoisted(() => ({ resolveForegroundMock: vi.fn() })) -const jobMembers = vi.hoisted(() => vi.fn()) -vi.mock('../windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: jobMembers, - isWindowsPtyJobReadable: () => true -})) - -const { confirmShellForegroundMock } = vi.hoisted(() => ({ - confirmShellForegroundMock: vi.fn() -})) - -vi.mock('../agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: resolveForegroundMock, - confirmShellForegroundProcess: confirmShellForegroundMock -})) - -const observeForegroundMock = vi.hoisted(() => vi.fn()) -vi.mock( - '../../pty/process-retirement/pty-master-foreground-observation', - async (importOriginal) => ({ - ...(await importOriginal()), - observePtyForeground: observeForegroundMock - }) -) -import { isRetiredPtyMaster } from '../../pty/process-retirement/node-pty-master-fd-retirement' - -import { LocalPtyProvider } from './local-pty-provider' -import { ptyIncarnations, ptyProcesses, ptyShellPath } from './local-pty-provider-state' -import { inspectPtyProviderProcess } from '../pty-process-inspection' - -// Match the recorded basename so only the retired descriptor distinguishes the pane from idle. -const POSIX_SHELL = 'sh' - -function registerPane(id: string, foreground: string | (() => string), shell?: string): void { - const pane: pty.IPty = { - pid: 4242, - cols: 80, - rows: 24, - get process(): string { - return typeof foreground === 'function' ? foreground() : foreground - }, - handleFlowControl: false, - onData: () => ({ dispose() {} }), - onExit: () => ({ dispose() {} }), - resize() {}, - clear() {}, - write() {}, - kill() {}, - pause() {}, - resume() {} - } - ptyProcesses.set(id, pane) - ptyIncarnations.set(id, `incarnation:${id}`) - if (shell) { - ptyShellPath.set(id, shell) - } -} - -/** Retired node-pty getters still report the spawn name; only descriptor state distinguishes this from idle. */ -async function registerRetiredPane(id: string): Promise { - const term = pty.spawn(POSIX_SHELL, ['-c', 'exit 0'], { - name: 'xterm-256color', - cols: 80, - rows: 24, - cwd: process.cwd(), - env: { ...process.env } - }) - await new Promise((resolve) => { - term.onExit(() => resolve()) - }) - // `onExit` runs before node-pty's `_close()`, which is where the patch retires `_fd`. - await vi.waitFor(() => expect(isRetiredPtyMaster(term)).toBe(true), { - timeout: 10000, - interval: 10 - }) - ptyProcesses.set(id, term) - ptyIncarnations.set(id, `incarnation:${id}`) - ptyShellPath.set(id, POSIX_SHELL) - return term -} - -beforeEach(() => { - // These fake foreground names model POSIX; Windows uses the owned-job fixture below. - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') - jobMembers.mockReset() - resolveForegroundMock.mockReset() - resolveForegroundMock.mockResolvedValue({ available: true, processName: '/bin/zsh' }) -}) - -afterEach(() => { - vi.restoreAllMocks() - ptyProcesses.clear() - ptyIncarnations.clear() - ptyShellPath.clear() -}) - -// Windows has no master fd to retire, and `WindowsTerminal.process` answers from the spawn name. -const describeOnPosix = process.platform === 'win32' ? describe.skip : describe - -describe('inspectPtyProviderProcess child-process evidence', () => { - const provider = new LocalPtyProvider() - - it('refuses to pair one panes foreground with its replacements children', async () => { - registerPane('pty-swapped', '/bin/zsh', '/bin/zsh') - resolveForegroundMock.mockImplementation(async () => { - // Cleanup plus reactivation lands a different IPty under the same id mid-read. - registerPane('pty-swapped', 'vim', '/bin/zsh') - return { available: true, processName: '/bin/zsh' } - }) - - await expect(inspectPtyProviderProcess(provider, 'pty-swapped')).resolves.toEqual({ - foregroundProcess: null, - hasChildProcesses: true, - childProcessEvidence: 'unverifiable' - }) - }) -}) - -describeOnPosix('inspectPtyProviderProcess on a retired master', () => { - const provider = new LocalPtyProvider() - - it('carries unverifiable child evidence beside the foreground it could still read', async () => { - await registerRetiredPane('pty-retired') - - const inspection = await inspectPtyProviderProcess(provider, 'pty-retired') - expect(inspection.hasChildProcesses).toBe(true) - expect(inspection.childProcessEvidence).toBe('unverifiable') - }, 15000) -}) diff --git a/src/main/providers/local-pty/local-pty-default-shell.test.ts b/src/main/providers/local-pty/local-pty-default-shell.test.ts deleted file mode 100644 index 8a5905bb48c..00000000000 --- a/src/main/providers/local-pty/local-pty-default-shell.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { spawnSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { REMOTE_VIEWER_CLIPBOARD_ENV } from '../../../shared/remote-viewer-clipboard-env' -import { finalizeLocalPtySpawnEnvironment } from './local-pty-finalize-environment' -import { createLocalPtyLaunchPlan } from './local-pty-launch-plan' - -vi.mock('./local-pty-executable-spawn', () => ({ - ensureNodePtySpawnHelperExecutable: vi.fn() -})) - -vi.mock('../working-directory-validation', () => ({ - validateWorkingDirectory: vi.fn() -})) - -afterEach(() => vi.unstubAllEnvs()) - -describe.skipIf(process.platform === 'win32')('default terminal shell', () => { - it.for([ - { shell: '/bin/bash', shellArgs: ['--rcfile', 'custom rc'], expected: 'custom:off' }, - { shell: '/bin/zsh', shellArgs: ['-f'], expected: 'unset:off' }, - { shell: '/bin/zsh', shellArgs: [], expected: 'zshrc:off' } - ])( - 'honors remote profile startup behavior for $shell $shellArgs', - ({ shell, shellArgs, expected }, { skip }) => { - if (spawnSync(shell, ['--version']).status !== 0) { - skip('Shell is not installed') - } - const home = mkdtempSync(join(tmpdir(), 'orca-profile-argv-')) - vi.stubEnv('ORCA_USER_DATA_PATH', home) - vi.stubEnv('ZDOTDIR', home) - try { - writeFileSync(join(home, '.bash_profile'), 'export ORCA_TEST_STARTUP=profile\n') - writeFileSync(join(home, 'custom rc'), 'export ORCA_TEST_STARTUP=custom\n') - writeFileSync(join(home, '.zshrc'), 'export ORCA_TEST_STARTUP=zshrc\n') - const terminalShellArgs = shellArgs.map((arg) => - arg === 'custom rc' ? join(home, arg) : arg - ) - const spawn = { cwd: home, cols: 80, rows: 24, terminalShellArgs } - const getOptions = () => ({ getDefaultShell: () => shell }) - const plan = createLocalPtyLaunchPlan(spawn, getOptions) - if (!('shellArgs' in plan)) { - throw new Error('Expected a POSIX shell launch plan') - } - const env = { HOME: home, PATH: '/usr/bin:/bin', [REMOTE_VIEWER_CLIPBOARD_ENV]: '1' } - finalizeLocalPtySpawnEnvironment({ spawn, getOptions, plan, env }) - - const result = spawnSync( - plan.shellPath, - [ - ...plan.shellArgs, - '-i', - '-c', - 'login=off; if [ -n "${ZSH_VERSION:-}" ]; then [[ -o login ]] && login=on; else shopt -q login_shell && login=on; fi; printf "\\nORCA_STARTUP_RESULT=%s:%s\\n" "${ORCA_TEST_STARTUP:-unset}" "$login"' - ], - { env, encoding: 'utf8', timeout: 10_000 } - ) - expect(result.status, result.stderr).toBe(0) - expect(result.stdout.match(/^ORCA_STARTUP_RESULT=(.*)$/m)?.[1]).toBe(expected) - } finally { - rmSync(home, { recursive: true, force: true }) - } - } - ) -}) diff --git a/src/main/providers/local-pty/local-pty-executable-spawn.test.ts b/src/main/providers/local-pty/local-pty-executable-spawn.test.ts deleted file mode 100644 index 92114c2cfb6..00000000000 --- a/src/main/providers/local-pty/local-pty-executable-spawn.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as fs from 'node:fs' -import type * as FsPromises from 'node:fs/promises' -import type { Stats } from 'node:fs' - -const { - existsSyncMock, - statSyncMock, - statMock, - accessSyncMock, - wslUncDirectoryExistsAsyncMock, - wrapSpawnMock -} = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), - statSyncMock: vi.fn(), - statMock: vi.fn(), - accessSyncMock: vi.fn(), - wslUncDirectoryExistsAsyncMock: vi.fn(), - wrapSpawnMock: vi.fn() -})) - -vi.mock('fs', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - existsSync: existsSyncMock, - statSync: statSyncMock, - accessSync: accessSyncMock - } -}) - -vi.mock('node:fs/promises', async (importOriginal) => ({ - ...(await importOriginal()), - stat: statMock -})) - -function dirStats(isDirectory: boolean): Stats { - return { isDirectory: () => isDirectory } as Stats -} - -vi.mock('../../wsl/filesystem/unc-path-access', () => ({ - wslUncDirectoryExistsAsync: wslUncDirectoryExistsAsyncMock -})) - -vi.mock('../macos-tcc-login-shell', () => ({ - wrapShellSpawnForMacosTccAttribution: wrapSpawnMock, - hostReportsChildExitStatus: (file: string) => file !== '/usr/bin/login' -})) -import { spawnShellWithFallback } from './local-pty-executable-spawn' -import { _resetWorkingDirectoryValidationStateForTest } from '../working-directory-validation' - -describe('spawnShellWithFallback macOS TCC login wrapping', () => { - let origPlatform: PropertyDescriptor | undefined - - beforeEach(() => { - origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - existsSyncMock.mockReturnValue(true) - statSyncMock.mockReturnValue(dirStats(true)) - accessSyncMock.mockReturnValue(undefined) - wrapSpawnMock.mockImplementation((file: string, args: string[]) => ({ - file: '/wrapped/login', - args: ['wrapped', file, ...args] - })) - }) - - afterEach(() => { - if (origPlatform) { - Object.defineProperty(process, 'platform', origPlatform) - } - vi.restoreAllMocks() - }) - - it('drops the first fallback’s launch env when a second fallback takes over', () => { - // Scrub the last attempt keys; a once-only primary scrub would leak the first fallback env. - const bashLaunchEnv = { ORCA_SHELL_FEATURES: 'markers', BASH_ENV: '/userdata/bash/rcfile' } - const env: Record = { HOME: '/home/jin', ZDOTDIR: '/userdata/shell-ready/zsh' } - const ptySpawn = vi - .fn() - .mockImplementationOnce(() => { - throw new Error('primary boom') - }) - .mockImplementationOnce(() => { - throw new Error('first fallback boom') - }) - .mockReturnValue({ pid: 4 }) - - spawnShellWithFallback({ - shellPath: '/bin/zsh', - shellArgs: ['-l'], - cols: 80, - rows: 24, - cwd: '/work', - env, - ptySpawn: ptySpawn as never, - preLaunchEnv: { ZDOTDIR: undefined }, - getShellReadyConfig: (shell) => - shell === '/bin/bash' ? { args: ['--rcfile', '/rc'], env: bashLaunchEnv } : null - }) - - expect(env.ORCA_SHELL_FEATURES).toBeUndefined() - expect(env.BASH_ENV).toBeUndefined() - expect(env.ZDOTDIR).toBeUndefined() - expect(env.HOME).toBe('/home/jin') - }) -}) diff --git a/src/main/providers/local-pty/local-pty-executable-spawn.ts b/src/main/providers/local-pty/local-pty-executable-spawn.ts index 4645f40668c..93bece9cb1b 100644 --- a/src/main/providers/local-pty/local-pty-executable-spawn.ts +++ b/src/main/providers/local-pty/local-pty-executable-spawn.ts @@ -9,8 +9,8 @@ import { TERMINAL_SPAWN_ISSUE_REQUEST } from '../../../shared/terminal/pty/lifec import { hostReportsChildExitStatus, wrapShellSpawnForMacosTccAttribution -} from '../macos-tcc-login-shell' -import { formatLocalPtyEnvironmentDiag } from '../working-directory-validation' +} from '../shell-launch/macos/tcc-login-shell' +import { formatLocalPtyEnvironmentDiag } from '../working-directory/validation' let didEnsureSpawnHelperExecutable = false diff --git a/src/main/providers/local-pty/local-pty-finalize-environment.ts b/src/main/providers/local-pty/local-pty-finalize-environment.ts index 8cfb51333d2..9fb3f971b10 100644 --- a/src/main/providers/local-pty/local-pty-finalize-environment.ts +++ b/src/main/providers/local-pty/local-pty-finalize-environment.ts @@ -27,7 +27,7 @@ import type { LocalPtyLaunchPlan } from './local-pty-launch-plan' import type { LocalPtyProviderOptions } from './local-pty-provider-types' import { getShellLaunchConfig } from './local-pty-shell-ready' import { finalizeWindowsLocalPtySpawnEnvironment } from './local-pty-windows-spawn-environment' -import type { PtySpawnOptions } from '../pty-provider-contract' +import type { PtySpawnOptions } from '../pty/provider-contract' export function finalizeLocalPtySpawnEnvironment(args: { spawn: PtySpawnOptions diff --git a/src/main/providers/local-pty/local-pty-foreground-inspection-cheap-tier.test.ts b/src/main/providers/local-pty/local-pty-foreground-inspection-cheap-tier.test.ts deleted file mode 100644 index e18576f7a6c..00000000000 --- a/src/main/providers/local-pty/local-pty-foreground-inspection-cheap-tier.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ProcessTableSnapshotReader from '../../../shared/process-table-snapshot-reader' - -const { cheapSnapshotMock, fullSnapshotMock, resolveMock } = vi.hoisted(() => ({ - cheapSnapshotMock: vi.fn(), - fullSnapshotMock: vi.fn(), - resolveMock: vi.fn() -})) - -vi.mock('../../../shared/cheap-process-table-snapshot-reader', () => ({ - getCheapProcessTableSnapshot: cheapSnapshotMock -})) -vi.mock('../../../shared/process-table-snapshot-reader', async (importOriginal) => ({ - ...(await importOriginal()), - getProcessTableSnapshot: fullSnapshotMock -})) -vi.mock('../agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: resolveMock, - confirmShellForegroundProcess: vi.fn() -})) - -import { getLocalPtyForegroundProcess } from './local-pty-foreground-inspection' -import { ptyLastRecognizedForeground, ptyProcesses, ptyShellPath } from './local-pty-provider-state' - -const SHELL_PID = 4242 -const AGENT_PID = 4300 -const ID = 'pty-1' - -type Table = 'agent' | 'shell-only' -let table: Table = 'agent' - -function rows(): Record[] { - const tpgid = table === 'agent' ? AGENT_PID : SHELL_PID - const out: Record[] = [ - { - pid: SHELL_PID, - ppid: 1, - pgid: SHELL_PID, - tpgid, - stat: table === 'agent' ? 'Ss' : 'Ss+', - tty: 'ttys004', - startTime: 'Thu Sep 3 16:02:01 2026', - command: '-zsh' - } - ] - if (table === 'agent') { - out.push({ - pid: AGENT_PID, - ppid: SHELL_PID, - pgid: AGENT_PID, - tpgid, - stat: 'S+', - tty: 'ttys004', - startTime: 'Thu Sep 3 16:02:05 2026', - command: 'node /usr/local/bin/claude' - }) - } - return out -} - -describe('local POSIX provider cheap-tier revalidation', () => { - let platform: PropertyDescriptor | undefined - const proc = { pid: SHELL_PID, process: 'node' } - - beforeEach(() => { - platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - table = 'agent' - proc.process = 'node' - cheapSnapshotMock.mockReset() - cheapSnapshotMock.mockImplementation(async () => rows()) - fullSnapshotMock.mockReset() - fullSnapshotMock.mockImplementation(async () => rows()) - resolveMock.mockReset() - resolveMock.mockImplementation(async () => ({ - available: true, - processName: table === 'agent' ? 'claude' : 'zsh' - })) - ptyProcesses.set(ID, proc as never) - ptyShellPath.set(ID, '/bin/zsh') - ptyLastRecognizedForeground.delete(ID) - }) - - afterEach(() => { - ptyProcesses.delete(ID) - ptyShellPath.delete(ID) - ptyLastRecognizedForeground.delete(ID) - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - }) - - it('once recognized, an unchanged pane re-proves the agent from the cheap tier without a full scan', async () => { - expect(await getLocalPtyForegroundProcess(ID)).toBe('claude') - expect(resolveMock).toHaveBeenCalledTimes(1) - expect(ptyLastRecognizedForeground.get(ID)?.steady?.fingerprint).toEqual(expect.any(String)) - for (let i = 0; i < 3; i += 1) { - expect(await getLocalPtyForegroundProcess(ID)).toBe('claude') - } - expect(cheapSnapshotMock).toHaveBeenCalledTimes(3) - expect(resolveMock).toHaveBeenCalledTimes(1) - }) - - it('an agent exit changes the fingerprint, escalates to the full scan, and clears the anchor', async () => { - expect(await getLocalPtyForegroundProcess(ID)).toBe('claude') - table = 'shell-only' - expect(await getLocalPtyForegroundProcess(ID)).toBe('zsh') - expect(resolveMock).toHaveBeenCalledTimes(2) - expect(ptyLastRecognizedForeground.get(ID)).toBeUndefined() - }) - - it('a cheap capture failure falls through to the full scan', async () => { - expect(await getLocalPtyForegroundProcess(ID)).toBe('claude') - cheapSnapshotMock.mockRejectedValueOnce(new Error('ps died')) - expect(await getLocalPtyForegroundProcess(ID)).toBe('claude') - expect(resolveMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/providers/local-pty/local-pty-foreground-inspection.ts b/src/main/providers/local-pty/local-pty-foreground-inspection.ts index becbfe5b4d1..0632925e8d6 100644 --- a/src/main/providers/local-pty/local-pty-foreground-inspection.ts +++ b/src/main/providers/local-pty/local-pty-foreground-inspection.ts @@ -5,8 +5,8 @@ import { getProcessTableSnapshot, getStrictProcessTableSnapshotWithAge } from '../../../shared/process-table-snapshot-reader' -import { confirmShellForegroundProcess } from '../agent-foreground-process' -import { confirmFreshPtyForeground } from '../pty-foreground-confirmation' +import { confirmShellForegroundProcess } from '../foreground/agent-process' +import { confirmFreshPtyForeground } from '../foreground/pty-confirmation' import { createPtyForegroundResolver, ptyProcessNameIsSpawnFile @@ -15,7 +15,7 @@ import { inspectSpawnFileChildProcessesFromRows, inspectSpawnFileWindowsChildProcesses } from '../../daemon/pty-subprocess/spawn-file-child-processes' -import { buildPaneProcessFingerprint } from '../posix-pane-foreground-fingerprint' +import { buildPaneProcessFingerprint } from '../foreground/posix-pane-fingerprint' import { isRetiredPtyMaster } from '../../pty/process-retirement/node-pty-master-fd-retirement' import { ptyShellProcessId } from '../../windows/windows-pty-job' import { resolveForegroundFallbackProcess } from './local-pty-launch-context' @@ -26,12 +26,15 @@ import { getPtyShellName, ptyShellPath } from './local-pty-provider-state' -import { resolveStableForegroundProcess } from '../stable-foreground-process' +import { resolveStableForegroundProcess } from '../foreground/stable-process' import { canRevalidateCachedAgentWithoutScan, judgeCachedAgentJobEvidence -} from '../windows-cached-agent-revalidation' -import { isWindowsPtyJobReadable, readWindowsPtyJobProcessIds } from '../windows-pty-job-membership' +} from '../foreground/windows/cached-agent-revalidation' +import { + isWindowsPtyJobReadable, + readWindowsPtyJobProcessIds +} from '../foreground/windows/pty-job-membership' /** Retired masters still report the spawn name; inspect the descriptor first so unreadability cannot prove idle. */ export async function inspectLocalPtyChildProcesses( diff --git a/src/main/providers/local-pty/local-pty-launch-context.ts b/src/main/providers/local-pty/local-pty-launch-context.ts index cb169d2fade..171be229296 100644 --- a/src/main/providers/local-pty/local-pty-launch-context.ts +++ b/src/main/providers/local-pty/local-pty-launch-context.ts @@ -3,7 +3,7 @@ import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' import { parseWslPath } from '../../wsl/filesystem/unc-path-access' import { resolvePathEnvKey } from '../../pty/environment/windows-path-segment-merge' import { expandWindowsEnvironmentVariables } from '../../../shared/windows-environment-expansion' -import { resolveSafePtyDefaultCwd } from '../pty-default-cwd' +import { resolveSafePtyDefaultCwd } from '../working-directory/default-cwd' import { REMOTE_VIEWER_CLIPBOARD_ENV } from '../../../shared/remote-viewer-clipboard-env' import { ORCAD_SERVER_LAUNCH_ENV_KEYS } from '../../../shared/orcad-server-launch-env' import { isLocalCounterPtyId } from '../../../shared/terminal/pty/lifecycle/pty-session-id-format' diff --git a/src/main/providers/local-pty/local-pty-launch-plan.ts b/src/main/providers/local-pty/local-pty-launch-plan.ts index 2c8a710793f..fa1bd9471cf 100644 --- a/src/main/providers/local-pty/local-pty-launch-plan.ts +++ b/src/main/providers/local-pty/local-pty-launch-plan.ts @@ -17,11 +17,11 @@ import { resolveEffectiveWindowsPowerShell, shouldProbeWindowsPowerShellAvailability, type WindowsPowerShellShellFamily -} from '../windows-powershell' -import { buildWindowsPowerShellSpawnAttempts } from '../windows-shell-fallback-chain' -import { resolveWindowsShellLaunchArgs } from '../windows-shell-args' -import { assertSafeAgentStartupCwd } from '../pty-default-cwd' -import type { PtySpawnOptions } from '../pty-provider-contract' +} from '../shell-launch/windows/powershell' +import { buildWindowsPowerShellSpawnAttempts } from '../shell-launch/windows/shell-fallback-chain' +import { resolveWindowsShellLaunchArgs } from '../shell-launch/windows/shell-args' +import { assertSafeAgentStartupCwd } from '../working-directory/default-cwd' +import type { PtySpawnOptions } from '../pty/provider-contract' type WslLaunchContext = { distro: string; treatPosixCwdAsWsl: true } type LocalPtyLaunchSeed = { diff --git a/src/main/providers/local-pty/local-pty-provider-foreground-process.test.ts b/src/main/providers/local-pty/local-pty-provider-foreground-process.test.ts deleted file mode 100644 index 97cf0da6f7d..00000000000 --- a/src/main/providers/local-pty/local-pty-provider-foreground-process.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import type * as WslPathOwner from '../../../shared/wsl-paths' -import type * as WslAvailabilityTypes from '../../wsl/discovery/wsl-availability' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as MacosTccLoginShell from '../macos-tcc-login-shell' -import type * as ForegroundProcess from '../agent-foreground-process' - -const { - fullTable, - identityTable, - consoleMembers, - existsSyncMock, - statSyncMock, - accessSyncMock, - mkdirSyncMock, - writeFileSyncMock, - spawnMock, - prepareMacosTccLoginShellMock, - resolveAgentForegroundProcessMock, - readWindowsPtyJobProcessIdsMock, - killWithDescendantSweepMock, - isWslAvailableAsyncMock, - wslUncDirectoryExistsAsyncMock, - createShellPromptReadinessProbeMock -} = vi.hoisted(() => ({ - fullTable: vi.fn(), - identityTable: vi.fn(), - consoleMembers: vi.fn(), - existsSyncMock: vi.fn(), - statSyncMock: vi.fn(), - accessSyncMock: vi.fn(), - mkdirSyncMock: vi.fn(), - writeFileSyncMock: vi.fn(), - spawnMock: vi.fn(), - prepareMacosTccLoginShellMock: vi.fn(), - resolveAgentForegroundProcessMock: vi.fn(), - readWindowsPtyJobProcessIdsMock: vi.fn(), - killWithDescendantSweepMock: vi.fn(), - isWslAvailableAsyncMock: vi.fn(), - wslUncDirectoryExistsAsyncMock: vi.fn(), - createShellPromptReadinessProbeMock: vi.fn() -})) - -vi.mock('../../../shared/wsl-paths', async (importOriginal) => ({ - ...(await importOriginal()), - toLinuxPath: (path: string) => path.replace(/^C:\\/i, '/mnt/c/').replace(/\\/g, '/'), - toWindowsWslPath: (path: string, distro: string) => - `\\\\wsl.localhost\\${distro}${path.replace(/\//g, '\\')}` -})) - -vi.mock('fs', () => ({ - existsSync: existsSyncMock, - statSync: statSyncMock, - accessSync: accessSyncMock, - mkdirSync: mkdirSyncMock, - writeFileSync: writeFileSyncMock, - chmodSync: vi.fn(), - renameSync: vi.fn(), - rmSync: vi.fn(), - constants: { X_OK: 1 } -})) - -vi.mock('electron', () => ({ - app: { - getPath: vi.fn(() => '/tmp/orca-user-data') - } -})) - -vi.mock('node-pty', () => ({ - spawn: spawnMock -})) - -vi.mock('../macos-tcc-login-shell', async (importOriginal) => ({ - ...(await importOriginal()), - prepareMacosTccLoginShell: prepareMacosTccLoginShellMock -})) - -vi.mock('../../pty/process-retirement/pty-descendant-termination', () => ({ - killWithDescendantSweep: killWithDescendantSweepMock -})) - -// The fs mock misses executable probes; pin paths here and leave Store-alias coverage to the resolver tests. -const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' -const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../windows-powershell-executable', () => ({ - resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, - resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' - ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] - : [WINDOWS_POWERSHELL_ABS, CMD_ABS], - getWindowsCmdPath: () => CMD_ABS -})) - -vi.mock('../agent-foreground-process', async (importOriginal) => ({ - ...(await importOriginal()), - resolveAgentForegroundProcessWithAvailability: (...args: unknown[]) => - resolveAgentForegroundProcessMock(...args) -})) - -vi.mock('../windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: (...args: unknown[]) => readWindowsPtyJobProcessIdsMock(...args), - isWindowsPtyJobReadable: () => true -})) - -vi.mock('../../windows/windows-process-table', () => ({ - readWindowsProcessTable: fullTable, - readWindowsProcessTableFresh: fullTable, - readWindowsProcessIdentityTable: identityTable, - readWindowsProcessIdentityTableFresh: identityTable -})) -vi.mock('../windows-console-attached-processes', () => ({ - readWindowsConsoleAttachedProcessIds: consoleMembers -})) - -vi.mock('../../wsl/filesystem/unc-path-access', () => ({ - parseWslPath: (path: string) => { - const match = path.match(/^\\\\wsl\.localhost\\([^\\]+)(.*)$/) - if (!match) { - return null - } - return { - distro: match[1], - linuxPath: (match[2] || '').replace(/\\/g, '/') || '/' - } - }, - wslUncDirectoryExistsAsync: (...args: unknown[]) => wslUncDirectoryExistsAsyncMock(...args) -})) -vi.mock('../../wsl/discovery/distro-catalog', () => ({ - getDefaultWslDistro: () => 'Ubuntu' -})) - -vi.mock('../../wsl/discovery/wsl-availability', async (importOriginal) => ({ - ...(await importOriginal()), - isWslAvailableAsync: () => isWslAvailableAsyncMock() -})) - -vi.mock('../../pty/shell-startup/shell-prompt-readiness-probe', () => ({ - createShellPromptReadinessProbe: createShellPromptReadinessProbeMock -})) - -import { LocalPtyProvider } from './local-pty-provider' -import { - applyLocalPtyProviderMockDefaults, - createLocalPtyMockProcess, - installLocalPtyProviderEnvSandbox, - type LocalPtyMockProcess -} from './local-pty-provider-test-harness' - -describe('LocalPtyProvider', () => { - let provider: LocalPtyProvider - let mockProc: LocalPtyMockProcess - let exitCb: ((info: { exitCode: number }) => void) | undefined - - installLocalPtyProviderEnvSandbox() - - beforeEach(() => { - applyLocalPtyProviderMockDefaults({ - existsSyncMock, - statSyncMock, - accessSyncMock, - mkdirSyncMock, - writeFileSyncMock, - prepareMacosTccLoginShellMock, - resolveAgentForegroundProcessMock, - readWindowsPtyJobProcessIdsMock, - killWithDescendantSweepMock, - isWslAvailableAsyncMock, - wslUncDirectoryExistsAsyncMock, - createShellPromptReadinessProbeMock - }) - - exitCb = undefined - mockProc = createLocalPtyMockProcess({ - get: () => exitCb, - set: (cb) => { - exitCb = cb - } - }) - spawnMock.mockReturnValue(mockProc) - - provider = new LocalPtyProvider() - }) - - describe('hasChildProcesses', () => { - it('fences full inspection with the original PTY incarnation across awaits', async () => { - const { id, incarnationId } = await provider.spawn({ cols: 80, rows: 24 }) - await expect( - provider.inspectProcess(id, { expectedIncarnationId: 'replacement' }) - ).resolves.toMatchObject({ childProcessEvidence: 'unverifiable' }) - let resolveScan!: (resolution: { available: boolean; processName: string }) => void - resolveAgentForegroundProcessMock.mockReturnValue( - new Promise((resolve) => { - resolveScan = resolve - }) - ) - const inspection = provider.inspectProcess(id, { expectedIncarnationId: incarnationId }) - exitCb?.({ exitCode: 0 }) - resolveScan({ available: true, processName: 'zsh' }) - await expect(inspection).resolves.toMatchObject({ childProcessEvidence: 'unverifiable' }) - }) - }) - - describe('getForegroundProcess', () => { - it('retires an anchored agent immediately when its pid leaves the job, despite a leftover', async () => { - // A missing anchor proves exit immediately; detached leftovers cannot preserve that identity. - Object.defineProperty(process, 'platform', { - configurable: true, - value: 'win32' - }) - mockProc.process = 'powershell.exe' - resolveAgentForegroundProcessMock - .mockResolvedValueOnce({ - available: true, - processName: 'claude', - processId: 999 - }) - .mockResolvedValue({ available: true, processName: null }) - readWindowsPtyJobProcessIdsMock.mockReturnValue(new Set([12345, 999])) - const { id } = await provider.spawn({ cols: 80, rows: 24 }) - - await expect(provider.getForegroundProcess(id)).resolves.toBe('claude') - readWindowsPtyJobProcessIdsMock.mockReturnValue(new Set([12345, 777])) - await expect(provider.getForegroundProcess(id)).resolves.toBeNull() - expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(2) - }) - - it('drops an anchored agent when the drift recheck proves the pid was recycled', async () => { - // A recycled PID still in the job cannot preserve an identity contradicted by the scan. - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - mockProc.process = 'powershell.exe' - resolveAgentForegroundProcessMock - .mockResolvedValueOnce({ available: true, processName: 'claude', processId: 999 }) - .mockResolvedValue({ available: true, processName: null, anchorPidForeign: true }) - readWindowsPtyJobProcessIdsMock.mockReturnValue(new Set([12345, 999])) - vi.useFakeTimers({ toFake: ['Date'] }) - try { - vi.setSystemTime(1_000_000) - const { id } = await provider.spawn({ cols: 80, rows: 24 }) - - await expect(provider.getForegroundProcess(id)).resolves.toBe('claude') - - vi.setSystemTime(1_000_000 + 40_000) - await expect(provider.getForegroundProcess(id)).resolves.toBeNull() - expect(resolveAgentForegroundProcessMock).toHaveBeenLastCalledWith( - mockProc.pid, - 'powershell.exe', - expect.objectContaining({ anchorProcessId: 999 }) - ) - } finally { - vi.useRealTimers() - } - }) - }) -}) diff --git a/src/main/providers/local-pty/local-pty-provider-shutdown.test.ts b/src/main/providers/local-pty/local-pty-provider-shutdown.test.ts index 4fcb79bb6db..1b38279902a 100644 --- a/src/main/providers/local-pty/local-pty-provider-shutdown.test.ts +++ b/src/main/providers/local-pty/local-pty-provider-shutdown.test.ts @@ -1,7 +1,7 @@ import type * as WslPathOwner from '../../../shared/wsl-paths' import type * as WslAvailabilityTypes from '../../wsl/discovery/wsl-availability' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as MacosTccLoginShell from '../macos-tcc-login-shell' +import type * as MacosTccLoginShell from '../shell-launch/macos/tcc-login-shell' import type * as PosixPtyProcessTable from '../../pty/process-retirement/posix-pty-process-table' const { @@ -72,7 +72,7 @@ vi.mock('../../pty/process-retirement/posix-pty-process-table', async (importOri readPosixPtyProcessTableSync: () => '' })) -vi.mock('../macos-tcc-login-shell', async (importOriginal) => ({ +vi.mock('../shell-launch/macos/tcc-login-shell', async (importOriginal) => ({ ...(await importOriginal()), prepareMacosTccLoginShell: prepareMacosTccLoginShellMock })) @@ -85,7 +85,7 @@ vi.mock('../../pty/process-retirement/pty-descendant-termination', () => ({ const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../windows-powershell-executable', () => ({ +vi.mock('../shell-launch/windows/powershell-executable', () => ({ resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => @@ -95,12 +95,12 @@ vi.mock('../windows-powershell-executable', () => ({ getWindowsCmdPath: () => CMD_ABS })) -vi.mock('../agent-foreground-process', () => ({ +vi.mock('../foreground/agent-process', () => ({ resolveAgentForegroundProcessWithAvailability: (...args: unknown[]) => resolveAgentForegroundProcessMock(...args) })) -vi.mock('../windows-pty-job-membership', () => ({ +vi.mock('../foreground/windows/pty-job-membership', () => ({ readWindowsPtyJobProcessIds: (...args: unknown[]) => readWindowsPtyJobProcessIdsMock(...args), isWindowsPtyJobReadable: () => true })) @@ -130,10 +130,6 @@ vi.mock('../../wsl/discovery/wsl-availability', async (importOriginal) => ({ vi.mock('../../pty/shell-startup/shell-prompt-readiness-probe', () => ({ createShellPromptReadinessProbe: createShellPromptReadinessProbeMock })) -import { - LOCAL_PTY_GRACEFUL_FORCE_TIMEOUT_MS, - LOCAL_PTY_PHYSICAL_EXIT_TIMEOUT_MS -} from './local-pty-termination' import { LocalPtyProvider } from './local-pty-provider' import { applyLocalPtyProviderMockDefaults, @@ -198,75 +194,5 @@ describe('LocalPtyProvider', () => { await shutdown expect(provider.hasPty(id)).toBe(false) }) - - it('escalates through orphan cleanup when the graceful-deadline sweep it joined is refused', async () => { - vi.useFakeTimers() - try { - let forceAttempts = 0 - const destroySpy = vi.fn() - const killSpy = vi.fn((signal: string) => { - if (signal === 'SIGKILL' && forceAttempts++ === 0) { - throw new Error('transient force-kill failure') - } - if (destroySpy.mock.calls.length > 0) { - throw new Error('killed through a released handle') - } - }) - spawnMock.mockReturnValue({ ...mockProc, kill: killSpy, destroy: destroySpy }) - const { id } = await provider.spawn({ cols: 80, rows: 24 }) - const table = Promise.withResolvers() - readProcessTableMock.mockReturnValueOnce(table.promise) - - const graceful = provider.shutdown(id, { immediate: false }) - await vi.advanceTimersByTimeAsync(LOCAL_PTY_GRACEFUL_FORCE_TIMEOUT_MS) - provider.killOrphanedPtys(1) - table.resolve('') - - await vi.waitFor(() => expect(destroySpy).toHaveBeenCalledOnce()) - expect(killSpy.mock.calls).toEqual([['SIGTERM'], ['SIGKILL'], ['SIGKILL']]) - exitCb?.({ exitCode: 137 }) - await graceful - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('rejects a physical-exit timeout but retains the owner for a successful retry', async () => { - vi.useFakeTimers() - try { - const killSpy = vi.fn() - mockProc.kill = killSpy - const { id } = await provider.spawn({ cols: 80, rows: 24 }) - - const shutdown = provider.shutdown(id, { immediate: true }) - const rejected = expect(shutdown).rejects.toThrow('Timed out waiting for PTY process exit') - await vi.advanceTimersByTimeAsync(LOCAL_PTY_PHYSICAL_EXIT_TIMEOUT_MS) - await rejected - expect(provider.hasPty(id)).toBe(true) - - const retry = provider.shutdown(id, { immediate: true }) - expect(killSpy).toHaveBeenCalledTimes(1) - exitCb?.({ exitCode: 137 }) - await expect(retry).resolves.toBeUndefined() - expect(provider.hasPty(id)).toBe(false) - } finally { - vi.useRealTimers() - } - }) - - it('propagates kill failure without dropping the physical owner', async () => { - mockProc.kill = vi.fn(() => { - throw new Error('kill denied') - }) - const { id } = await provider.spawn({ cols: 80, rows: 24 }) - - await expect(provider.shutdown(id, { immediate: true })).rejects.toThrow('kill denied') - expect(provider.hasPty(id)).toBe(true) - - mockProc.kill = vi.fn(() => exitCb?.({ exitCode: 137 })) - await expect(provider.shutdown(id, { immediate: true })).resolves.toBeUndefined() - expect(provider.hasPty(id)).toBe(false) - }) }) }) diff --git a/src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts b/src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts index ec481fe88d1..58595d543bf 100644 --- a/src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts +++ b/src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts @@ -1,7 +1,7 @@ import type * as WslPathOwner from '../../../shared/wsl-paths' import type * as WslAvailabilityTypes from '../../wsl/discovery/wsl-availability' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as MacosTccLoginShell from '../macos-tcc-login-shell' +import type * as MacosTccLoginShell from '../shell-launch/macos/tcc-login-shell' import type { ShellSpawnParams } from './local-pty-executable-spawn' const { @@ -72,7 +72,7 @@ vi.mock('./local-pty-runtime-spawn', async () => { } }) -vi.mock('../macos-tcc-login-shell', async (importOriginal) => ({ +vi.mock('../shell-launch/macos/tcc-login-shell', async (importOriginal) => ({ ...(await importOriginal()), prepareMacosTccLoginShell: prepareMacosTccLoginShellMock })) @@ -85,7 +85,7 @@ vi.mock('../../pty/process-retirement/pty-descendant-termination', () => ({ const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../windows-powershell-executable', () => ({ +vi.mock('../shell-launch/windows/powershell-executable', () => ({ resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => @@ -95,12 +95,12 @@ vi.mock('../windows-powershell-executable', () => ({ getWindowsCmdPath: () => CMD_ABS })) -vi.mock('../agent-foreground-process', () => ({ +vi.mock('../foreground/agent-process', () => ({ resolveAgentForegroundProcessWithAvailability: (...args: unknown[]) => resolveAgentForegroundProcessMock(...args) })) -vi.mock('../windows-pty-job-membership', () => ({ +vi.mock('../foreground/windows/pty-job-membership', () => ({ readWindowsPtyJobProcessIds: (...args: unknown[]) => readWindowsPtyJobProcessIdsMock(...args), isWindowsPtyJobReadable: () => true })) @@ -132,12 +132,6 @@ vi.mock('../../pty/shell-startup/shell-prompt-readiness-probe', () => ({ })) import { LocalPtyProvider } from './local-pty-provider' -import { - ptyDisposables, - ptyExitDisposables, - ptyPhysicalExits, - startupIngressByPty -} from './local-pty-provider-state' import { applyLocalPtyProviderMockDefaults, createLocalPtyMockProcess, @@ -181,101 +175,6 @@ describe('LocalPtyProvider', () => { }) describe('spawn', () => { - it('retires buffered output and synchronous Bun exit before replying to spawn', async () => { - const disposeData = vi.fn() - const disposeExit = vi.fn() - const onExit = vi.fn() - provider.configure({ onExit }) - mockProc.onData.mockImplementation((listener: (data: string) => void) => { - listener('last output') - return { dispose: disposeData } - }) - mockProc.onExit.mockImplementation((listener: (event: { exitCode: number }) => void) => { - listener({ exitCode: 17 }) - return { dispose: disposeExit } - }) - const result = await provider.spawn({ - cols: 80, - rows: 24, - sessionId: 'already-exited-bun-shell', - command: 'must-not-run' - }) - expect(result.exitedBeforeSpawnReply).toBe(true) - expect(provider.getPtyProcess(result.id)).toBeUndefined() - for (const map of [ - ptyDisposables, - ptyExitDisposables, - ptyPhysicalExits, - startupIngressByPty - ]) { - expect(map.has(result.id)).toBe(false) - } - expect(disposeData).toHaveBeenCalledOnce() - expect(disposeExit).toHaveBeenCalledOnce() - expect(onExit).toHaveBeenCalledOnce() - await Promise.resolve() - expect(mockProc.write).not.toHaveBeenCalled() - }) - - // Hook/trust setup makes env build a long pre-spawn await; shutdown must cancel during it (#16441). - it('does not spawn after shutdown cancels a pending spawn during the env build', async () => { - spawnMock.mockClear() - let finishEnvBuild!: (env: Record) => void - const buildSpawnEnv = vi.fn( - (_id: string, baseEnv: Record) => - new Promise>((resolve) => { - finishEnvBuild = () => resolve(baseEnv) - }) - ) - const envProvider = new LocalPtyProvider({ buildSpawnEnv }) - - const spawn = envProvider.spawn({ cols: 80, rows: 24, sessionId: 'env-build-session' }) - const canceledSpawn = expect(spawn).rejects.toThrow('PTY spawn canceled: env-build-session') - await vi.waitFor(() => expect(buildSpawnEnv).toHaveBeenCalledOnce()) - - await envProvider.shutdown('env-build-session', { immediate: true }) - finishEnvBuild({}) - await canceledSpawn - expect(spawnMock).not.toHaveBeenCalled() - }) - - it.each([1, 2])( - 'keeps cancellation registered across %i environment-resume microtasks', - async (microtasks) => { - spawnMock.mockClear() - let finishEnvBuild!: () => void - const envProvider = new LocalPtyProvider({ - buildSpawnEnv: (_id, baseEnv) => - new Promise>((resolve) => { - finishEnvBuild = () => resolve(baseEnv) - }) - }) - const spawn = envProvider.spawn({ - cols: 80, - rows: 24, - sessionId: 'resolved-env-build-session' - }) - const canceledSpawn = expect(spawn).rejects.toThrow( - 'PTY spawn canceled: resolved-env-build-session' - ) - await vi.waitFor(() => expect(finishEnvBuild).toBeTypeOf('function')) - - finishEnvBuild() - const shutdown = new Promise((resolve, reject) => { - const shutdown = () => { - envProvider - .shutdown('resolved-env-build-session', { immediate: true }) - .then(resolve, reject) - } - queueMicrotask(() => (microtasks === 1 ? shutdown() : queueMicrotask(shutdown))) - }) - - await shutdown - await canceledSpawn - expect(spawnMock).not.toHaveBeenCalled() - } - ) - it('coalesces a concurrent same-session-id spawn before launching a redundant shell (F3)', async () => { spawnMock.mockClear() const procA = { ...mockProc, pid: 1001 } diff --git a/src/main/providers/local-pty/local-pty-provider-state.ts b/src/main/providers/local-pty/local-pty-provider-state.ts index 30d004f06eb..caccf587016 100644 --- a/src/main/providers/local-pty/local-pty-provider-state.ts +++ b/src/main/providers/local-pty/local-pty-provider-state.ts @@ -2,8 +2,8 @@ import type { WslGuestRoot } from '../../../shared/wsl-guest-root-marker' import type * as pty from 'node-pty' import type { PhysicalExitTracker } from '../../../shared/physical-exit-tracker' import type { PtyStartupIngress } from '../../../shared/terminal/pty/ingress/pty-startup-ingress' -import type { IPtyProvider } from '../pty-provider-contract' -import type { PtyDataEvent } from '../pty-provider-events' +import type { IPtyProvider } from '../pty/provider-contract' +import type { PtyDataEvent } from '../pty/events' import { getSpawnedShellName, normalizeLocalCallerSessionId } from './local-pty-launch-context' export type PtyShutdownOperation = { diff --git a/src/main/providers/local-pty/local-pty-provider-types.ts b/src/main/providers/local-pty/local-pty-provider-types.ts index 2144c64a106..b09c4d608b0 100644 --- a/src/main/providers/local-pty/local-pty-provider-types.ts +++ b/src/main/providers/local-pty/local-pty-provider-types.ts @@ -1,5 +1,5 @@ import type { TerminalExitCause } from '../../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import type { PtySpawnOptions } from '../pty-provider-contract' +import type { PtySpawnOptions } from '../pty/provider-contract' export type LocalPtyProviderOptions = { /** Agent command selects overlay directories; disk-presence fallback can shadow another agent. */ diff --git a/src/main/providers/local-pty/local-pty-provider-windows-shell-launch.test.ts b/src/main/providers/local-pty/local-pty-provider-windows-shell-launch.test.ts deleted file mode 100644 index cd975da1dda..00000000000 --- a/src/main/providers/local-pty/local-pty-provider-windows-shell-launch.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import type * as WslPathOwner from '../../../shared/wsl-paths' -import type * as WslAvailabilityTypes from '../../wsl/discovery/wsl-availability' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as MacosTccLoginShell from '../macos-tcc-login-shell' - -const { toLinuxPathMock } = vi.hoisted(() => ({ - toLinuxPathMock: (path: string) => path.replace(/^C:\\/i, '/mnt/c/').replace(/\\/g, '/') -})) - -const { - existsSyncMock, - statSyncMock, - accessSyncMock, - mkdirSyncMock, - writeFileSyncMock, - spawnMock, - prepareMacosTccLoginShellMock, - resolveAgentForegroundProcessMock, - readWindowsPtyJobProcessIdsMock, - killWithDescendantSweepMock, - isWslAvailableAsyncMock, - wslUncDirectoryExistsAsyncMock, - createShellPromptReadinessProbeMock, - readWslDistroRunningStateMock -} = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), - statSyncMock: vi.fn(), - accessSyncMock: vi.fn(), - mkdirSyncMock: vi.fn(), - writeFileSyncMock: vi.fn(), - spawnMock: vi.fn(), - prepareMacosTccLoginShellMock: vi.fn(), - resolveAgentForegroundProcessMock: vi.fn(), - readWindowsPtyJobProcessIdsMock: vi.fn(), - killWithDescendantSweepMock: vi.fn(), - isWslAvailableAsyncMock: vi.fn(), - wslUncDirectoryExistsAsyncMock: vi.fn(), - createShellPromptReadinessProbeMock: vi.fn(), - readWslDistroRunningStateMock: vi.fn() -})) - -vi.mock('../../../shared/wsl-paths', async (importOriginal) => ({ - ...(await importOriginal()), - toLinuxPath: toLinuxPathMock, - toWindowsWslPath: (path: string, distro: string) => - `\\\\wsl.localhost\\${distro}${path.replace(/\//g, '\\')}` -})) - -vi.mock('fs', () => ({ - existsSync: existsSyncMock, - statSync: statSyncMock, - accessSync: accessSyncMock, - mkdirSync: mkdirSyncMock, - writeFileSync: writeFileSyncMock, - chmodSync: vi.fn(), - renameSync: vi.fn(), - rmSync: vi.fn(), - constants: { X_OK: 1 } -})) - -vi.mock('electron', () => ({ - app: { - getPath: vi.fn(() => '/tmp/orca-user-data') - } -})) - -vi.mock('node-pty', () => ({ - spawn: spawnMock -})) - -vi.mock('../macos-tcc-login-shell', async (importOriginal) => ({ - ...(await importOriginal()), - prepareMacosTccLoginShell: prepareMacosTccLoginShellMock -})) - -vi.mock('../../pty/process-retirement/pty-descendant-termination', () => ({ - killWithDescendantSweep: killWithDescendantSweepMock -})) - -// The fs mock misses executable probes; pin paths and leave Store-alias coverage to resolver tests. -const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' -const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' -vi.mock('../windows-powershell-executable', () => ({ - resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, - resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => - family === 'pwsh.exe' - ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] - : [WINDOWS_POWERSHELL_ABS, CMD_ABS], - getWindowsCmdPath: () => CMD_ABS -})) - -vi.mock('../agent-foreground-process', () => ({ - resolveAgentForegroundProcessWithAvailability: (...args: unknown[]) => - resolveAgentForegroundProcessMock(...args) -})) - -vi.mock('../windows-pty-job-membership', () => ({ - readWindowsPtyJobProcessIds: (...args: unknown[]) => readWindowsPtyJobProcessIdsMock(...args), - isWindowsPtyJobReadable: () => true -})) - -vi.mock('../../wsl/filesystem/unc-path-access', async () => ({ - parseWslPath: (await import('../../../shared/wsl-paths')).parseWslUncPath, - wslUncDirectoryExistsAsync: (...args: unknown[]) => wslUncDirectoryExistsAsyncMock(...args) -})) -vi.mock('../../wsl/discovery/distro-catalog', async () => ({ - getDefaultWslDistro: () => 'Ubuntu' -})) - -vi.mock('../../wsl/discovery/wsl-availability', async (importOriginal) => ({ - ...(await importOriginal()), - isWslAvailableAsync: () => isWslAvailableAsyncMock() -})) - -vi.mock('../../wsl/discovery/wsl-background-distro-gate', () => ({ - readWslDistroRunningState: (...args: unknown[]) => readWslDistroRunningStateMock(...args) -})) - -vi.mock('../../pty/shell-startup/shell-prompt-readiness-probe', () => ({ - createShellPromptReadinessProbe: createShellPromptReadinessProbeMock -})) - -import { LocalPtyProvider } from './local-pty-provider' -import { - applyLocalPtyProviderMockDefaults, - createLocalPtyMockProcess, - installLocalPtyProviderEnvSandbox, - type LocalPtyMockProcess -} from './local-pty-provider-test-harness' - -describe('LocalPtyProvider', () => { - let provider: LocalPtyProvider - let mockProc: LocalPtyMockProcess - let exitCb: ((info: { exitCode: number }) => void) | undefined - - installLocalPtyProviderEnvSandbox() - - beforeEach(() => { - applyLocalPtyProviderMockDefaults({ - existsSyncMock, - statSyncMock, - accessSyncMock, - mkdirSyncMock, - writeFileSyncMock, - prepareMacosTccLoginShellMock, - resolveAgentForegroundProcessMock, - readWindowsPtyJobProcessIdsMock, - killWithDescendantSweepMock, - isWslAvailableAsyncMock, - wslUncDirectoryExistsAsyncMock, - createShellPromptReadinessProbeMock - }) - - exitCb = undefined - mockProc = createLocalPtyMockProcess({ - get: () => exitCb, - set: (cb) => { - exitCb = cb - } - }) - spawnMock.mockReturnValue(mockProc) - - provider = new LocalPtyProvider() - }) - - describe('spawn', () => { - it('rejects a canceled spawn while its WSL cwd probe is still pending', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const probeStarted = Promise.withResolvers() - wslUncDirectoryExistsAsyncMock.mockImplementation(() => { - probeStarted.resolve() - return new Promise(() => {}) - }) - const spawnCallsBefore = spawnMock.mock.calls.length - - const spawn = provider.spawn({ - cols: 80, - rows: 24, - cwd: '\\\\wsl.localhost\\Stalled\\home\\jin\\repo', - sessionId: 'stalled-wsl-cwd-session' - }) - const canceledSpawn = expect(spawn).rejects.toThrow( - 'PTY spawn canceled: stalled-wsl-cwd-session' - ) - await probeStarted.promise - await provider.shutdown('stalled-wsl-cwd-session', { immediate: true }) - - await canceledSpawn - expect(spawnMock.mock.calls).toHaveLength(spawnCallsBefore) - }) - }) -}) diff --git a/src/main/providers/local-pty/local-pty-provider.ts b/src/main/providers/local-pty/local-pty-provider.ts index 55196a9bdd0..ba301fbcfad 100644 --- a/src/main/providers/local-pty/local-pty-provider.ts +++ b/src/main/providers/local-pty/local-pty-provider.ts @@ -1,9 +1,9 @@ import { randomUUID } from 'node:crypto' import { observePtyForeground } from '../../pty/process-retirement/pty-master-foreground-observation' import type * as pty from 'node-pty' -import type { IPtyProvider, PtySpawnOptions } from '../pty-provider-contract' -import type { PtyProcessInfo } from '../pty-process-info' -import type { PtySpawnResult } from '../pty-spawn-result' +import type { IPtyProvider, PtySpawnOptions } from '../pty/provider-contract' +import type { PtyProcessInfo } from '../pty/process-info' +import type { PtySpawnResult } from '../pty/spawn-result' import { WRITE_ACCEPTED, writeRefused, @@ -17,7 +17,7 @@ import { inspectLocalPtyChildProcesses } from './local-pty-foreground-inspection' import type { LocalPtyProviderOptions } from './local-pty-provider-types' -import type { PtyProcessInspectionOptions } from '../pty-process-inspection' +import type { PtyProcessInspectionOptions } from '../pty/process-inspection' import type { TerminalProcessInspection as PtyProcessInspection } from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' import type { TerminalOscColorQueryReplyColors } from '../../../shared/terminal/protocol/queries/terminal-osc-color-reply' import { diff --git a/src/main/providers/local-pty/local-pty-runtime-spawn.ts b/src/main/providers/local-pty/local-pty-runtime-spawn.ts index baa546bc13f..9ac4bc508d4 100644 --- a/src/main/providers/local-pty/local-pty-runtime-spawn.ts +++ b/src/main/providers/local-pty/local-pty-runtime-spawn.ts @@ -4,7 +4,7 @@ import { type ShellSpawnParams, type ShellSpawnResult } from './local-pty-executable-spawn' -import { reportNodePtyLoadFailure } from '../node-pty-load-failure' +import { reportNodePtyLoadFailure } from '../pty/node-pty-load-failure' type LocalPtySpawn = ( params: Omit & { signal?: AbortSignal } diff --git a/src/main/providers/local-pty/local-pty-session-activation.ts b/src/main/providers/local-pty/local-pty-session-activation.ts index e39f650b767..488dafb7940 100644 --- a/src/main/providers/local-pty/local-pty-session-activation.ts +++ b/src/main/providers/local-pty/local-pty-session-activation.ts @@ -18,7 +18,7 @@ import { resolveProcessExitCause } from '../../../shared/terminal/pty/lifecycle/terminal-exit-cause' import { POSIX_SHELL_STARTUP_COMMAND_ENV } from '../../pty/shell-startup/posix-shell-startup-command' -import { getAgentForegroundContextPaths } from '../agent-foreground-context-paths' +import { getAgentForegroundContextPaths } from '../foreground/context-paths' import { getSpawnedShellName } from './local-pty-launch-context' import type { LocalPtyLaunchPlan } from './local-pty-launch-plan' import type { LocalPtyProviderOptions } from './local-pty-provider-types' @@ -49,8 +49,8 @@ import { createWslGuestRootObserver } from '../../../shared/wsl-guest-root-marke import { createLocalPtyShellReadinessSession } from './local-pty-shell-readiness-session' import { destroyPtyProcess, createPtyPhysicalExit } from './local-pty-termination' import { writeStartupCommandWhenShellReady } from './local-pty-shell-ready-startup-command' -import type { PtySpawnOptions } from '../pty-provider-contract' -import type { PtySpawnResult } from '../pty-spawn-result' +import type { PtySpawnOptions } from '../pty/provider-contract' +import type { PtySpawnResult } from '../pty/spawn-result' export function activateLocalPtySession(args: { id: string diff --git a/src/main/providers/local-pty/local-pty-session-operations.ts b/src/main/providers/local-pty/local-pty-session-operations.ts index 02707eb8572..f586521d2a3 100644 --- a/src/main/providers/local-pty/local-pty-session-operations.ts +++ b/src/main/providers/local-pty/local-pty-session-operations.ts @@ -7,7 +7,7 @@ import { signalPosixPtyForegroundGroup } from '../../pty/process-retirement/posi import { ptyShellProcessId } from '../../windows/windows-pty-job' import { isWslAvailableAsync } from '../../wsl/discovery/wsl-availability' import { resolveGitBashPath } from '../../pty/shell-startup/git-bash' -import { resolveProcessCwd } from '../process-cwd' +import { resolveProcessCwd } from '../working-directory/process-cwd' import { dataListeners, exitListeners, @@ -24,7 +24,7 @@ import { type ExitCallback } from './local-pty-provider-state' import type { LocalPtyProviderOptions } from './local-pty-provider-types' -import type { PtyProcessInfo } from '../pty-process-info' +import type { PtyProcessInfo } from '../pty/process-info' export function writeLocalPty(id: string, data: string): boolean { // Hold private DSR/OSC replies through cooked-mode echo; CPR/DA cannot overtake held replies (#13137, #7329, #15559). diff --git a/src/main/providers/local-pty/local-pty-shell-readiness-session.ts b/src/main/providers/local-pty/local-pty-shell-readiness-session.ts index 59906961830..75dabfc6feb 100644 --- a/src/main/providers/local-pty/local-pty-shell-readiness-session.ts +++ b/src/main/providers/local-pty/local-pty-shell-readiness-session.ts @@ -16,7 +16,7 @@ import { STARTUP_COMMAND_READY_MAX_WAIT_MS, type ShellReadySignal } from './local-pty-shell-ready-startup-command' -import type { PtySpawnOptions } from '../pty-provider-contract' +import type { PtySpawnOptions } from '../pty/provider-contract' export type LocalPtyShellReadinessSession = { shellReadyPromise: Promise diff --git a/src/main/providers/local-pty/local-pty-spawn-environment.ts b/src/main/providers/local-pty/local-pty-spawn-environment.ts index 65b1c4f2f2d..ae86f9f9cb0 100644 --- a/src/main/providers/local-pty/local-pty-spawn-environment.ts +++ b/src/main/providers/local-pty/local-pty-spawn-environment.ts @@ -14,7 +14,7 @@ import { applyScrubSafeAgentEnvAliases } from '../../../shared/agent-hook-listen import { removeUnspecifiedPaneIdentityEnv } from './local-pty-launch-context' import type { LocalPtyLaunchPlan } from './local-pty-launch-plan' import type { LocalPtyProviderOptions } from './local-pty-provider-types' -import type { PtySpawnOptions } from '../pty-provider-contract' +import type { PtySpawnOptions } from '../pty/provider-contract' import { stripInheritedAgentSessionEnv } from '../../../shared/agent-launch/startup/parent-agent-session-env' /** Pane ownership must be fresh even when Orca itself was launched inside an agent. */ diff --git a/src/main/providers/local-pty/local-pty-spawn-state.ts b/src/main/providers/local-pty/local-pty-spawn-state.ts index c006c8cbecb..7a1f15d49fc 100644 --- a/src/main/providers/local-pty/local-pty-spawn-state.ts +++ b/src/main/providers/local-pty/local-pty-spawn-state.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../pty-spawn-result' +import type { PtySpawnResult } from '../pty/spawn-result' import { pendingLocalPtySpawns, ptyIncarnations, diff --git a/src/main/providers/local-pty/local-pty-spawn.ts b/src/main/providers/local-pty/local-pty-spawn.ts index 4950914a432..5d9e928077a 100644 --- a/src/main/providers/local-pty/local-pty-spawn.ts +++ b/src/main/providers/local-pty/local-pty-spawn.ts @@ -3,7 +3,7 @@ import { win32 as pathWin32 } from 'node:path' import { mkdir } from 'node:fs/promises' import { JCODE_RUNTIME_DIR_ENV_KEY } from '../../../shared/jcode-runtime-dir' import { SessionNotFoundError } from '../../daemon/protocol/daemon-errors' -import { prepareMacosTccLoginShell } from '../macos-tcc-login-shell' +import { prepareMacosTccLoginShell } from '../shell-launch/macos/tcc-login-shell' import { finalizeLocalPtySpawnEnvironment } from './local-pty-finalize-environment' import { normalizeLocalCallerSessionId } from './local-pty-launch-context' import { createLocalPtyLaunchPlan, DeferredLocalPtyLaunchPlan } from './local-pty-launch-plan' @@ -12,7 +12,7 @@ import type { LocalPtyProviderOptions } from './local-pty-provider-types' import { validateWorkingDirectory, WorkingDirectoryValidationAbortedError -} from '../working-directory-validation' +} from '../working-directory/validation' import { allocatePtyId, ptyShutdownOperations } from './local-pty-provider-state' import { activateLocalPtySession } from './local-pty-session-activation' import { @@ -27,8 +27,8 @@ import { import { loadLocalPtyRuntimeSpawn } from './local-pty-runtime-spawn' import { destroyPtyProcess } from './local-pty-termination' import { updateHistoryEnvForFallback } from '../../pty/history/terminal-history' -import type { PtySpawnOptions } from '../pty-provider-contract' -import type { PtySpawnResult } from '../pty-spawn-result' +import type { PtySpawnOptions } from '../pty/provider-contract' +import type { PtySpawnResult } from '../pty/spawn-result' export async function spawnLocalPty( args: PtySpawnOptions, diff --git a/src/main/providers/local-pty/local-pty-windows-spawn-environment.ts b/src/main/providers/local-pty/local-pty-windows-spawn-environment.ts index cef4871e415..950932256ae 100644 --- a/src/main/providers/local-pty/local-pty-windows-spawn-environment.ts +++ b/src/main/providers/local-pty/local-pty-windows-spawn-environment.ts @@ -15,8 +15,8 @@ import type { LocalPtyLaunchPlan } from './local-pty-launch-plan' import { ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV, resolveWindowsShellLaunchArgs -} from '../windows-shell-args' -import type { PtySpawnOptions } from '../pty-provider-contract' +} from '../shell-launch/windows/shell-args' +import type { PtySpawnOptions } from '../pty/provider-contract' export function finalizeWindowsLocalPtySpawnEnvironment(args: { spawn: PtySpawnOptions diff --git a/src/main/providers/macos-login-session-pty-probe.ts b/src/main/providers/macos-login-session-pty-probe.ts deleted file mode 100644 index e3c8da79da2..00000000000 --- a/src/main/providers/macos-login-session-pty-probe.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { execFile } from 'node:child_process' -import { existsSync } from 'node:fs' - -const MACOS_EXPECT_PATH = '/usr/bin/expect' -const LOGIN_PREFLIGHT_MARKER = 'ORCA_LOGIN_PREFLIGHT_OK' -const LOGIN_PROBE_USERNAME_ENV = 'ORCA_LOGIN_PROBE_USERNAME' -// expect owns the probe PTY without leaving a long-lived native handle in the daemon. -const EXPECT_LOGIN_PROBE_SCRIPT = - 'log_user 1; ' + - 'spawn -noecho /usr/bin/login -flpq $env(ORCA_LOGIN_PROBE_USERNAME) /usr/bin/printf ORCA_LOGIN_PREFLIGHT_OK; ' + - 'send "\\004"; expect eof; wait; exit 0' - -export type LoginPreflightOutcome = { - ok: boolean - conclusive: boolean - reason: 'accepted' | 'rejected' | 'timeout' | 'error' -} - -/** Runs the login-session oracle under a real PTY when the pipe probe cannot decide. */ -export function runMacosLoginSessionPtyProbe( - username: string, - accountHome: string, - timeoutMs: number, - maxOutputBytes: number, - signal?: AbortSignal -): Promise { - if (!existsSync(MACOS_EXPECT_PATH)) { - return Promise.resolve({ ok: false, conclusive: false, reason: 'error' }) - } - return new Promise((resolve) => { - try { - const child = execFile( - MACOS_EXPECT_PATH, - ['-c', EXPECT_LOGIN_PROBE_SCRIPT], - { - cwd: accountHome, - encoding: 'utf8', - env: { ...process.env, [LOGIN_PROBE_USERNAME_ENV]: username }, - killSignal: 'SIGKILL', - maxBuffer: maxOutputBytes, - signal, - timeout: timeoutMs - }, - (error, stdout) => { - if (error !== null) { - // Tcl/PTY failures are inconclusive, never PAM rejection proof. - resolve( - error.killed || error.code === 'ETIMEDOUT' - ? { ok: false, conclusive: false, reason: 'timeout' } - : { ok: false, conclusive: false, reason: 'error' } - ) - return - } - resolve( - stdout.includes(LOGIN_PREFLIGHT_MARKER) - ? { ok: true, conclusive: true, reason: 'accepted' } - : { ok: false, conclusive: true, reason: 'rejected' } - ) - } - ) - child.stdin?.end() - } catch { - resolve({ ok: false, conclusive: false, reason: 'error' }) - } - }) -} diff --git a/src/main/providers/macos-tcc-login-shell.test.ts b/src/main/providers/macos-tcc-login-shell.test.ts deleted file mode 100644 index e23f9de19e9..00000000000 --- a/src/main/providers/macos-tcc-login-shell.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as LoginSessionPtyProbe from './macos-login-session-pty-probe' - -const { existsSyncMock, userInfoMock, runProcessMock, ptyProbeMock } = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), - userInfoMock: vi.fn(), - runProcessMock: vi.fn(), - ptyProbeMock: vi.fn() -})) - -vi.mock('node:fs', () => ({ existsSync: existsSyncMock })) -vi.mock('node:os', () => ({ userInfo: userInfoMock })) -// Process-host owns encoding/signals/caps; this suite checks PAM argv and verdicts. -vi.mock('@orca/process-host', () => ({ - runProcess: (...args: unknown[]) => Promise.resolve(runProcessMock(...args)) -})) -vi.mock('./macos-login-session-pty-probe', async (importOriginal) => ({ - ...(await importOriginal()), - runMacosLoginSessionPtyProbe: ptyProbeMock -})) - -import { - prepareMacosTccLoginShell, - probeMacosLoginSessionAlive, - resetMacosLoginShellPreflightForTests, - wrapShellSpawnForMacosTccAttribution -} from './macos-tcc-login-shell' - -const ACCEPTED_RESULT = { - code: 0, - signal: null, - stdout: 'ORCA_LOGIN_PREFLIGHT_OK', - stderr: '', - timedOut: false -} -const REJECTED_RESULT = { code: 1, signal: null, stdout: '', stderr: '', timedOut: false } -const ACCEPTED_OUTCOME = { ok: true, conclusive: true, reason: 'accepted' } as const -const REJECTED_OUTCOME = { ok: false, conclusive: true, reason: 'rejected' } as const -void (process.platform === 'win32' ? it.skip : it) - -describe('probeMacosLoginSessionAlive', () => { - let origPlatform: PropertyDescriptor | undefined - let origDisable: string | undefined - - function setPlatform(value: string): void { - Object.defineProperty(process, 'platform', { configurable: true, value }) - } - - beforeEach(() => { - origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - origDisable = process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL - delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL - existsSyncMock.mockReturnValue(true) - userInfoMock.mockReturnValue({ username: 'ada', homedir: '/Users/ada' }) - runProcessMock.mockResolvedValue({ - code: 0, - signal: null, - stdout: 'ORCA_LOGIN_PREFLIGHT_OK', - stderr: '', - timedOut: false - }) - ptyProbeMock.mockResolvedValue({ ok: true, conclusive: true, reason: 'accepted' }) - resetMacosLoginShellPreflightForTests() - }) - - afterEach(() => { - if (origPlatform) { - Object.defineProperty(process, 'platform', origPlatform) - } - if (origDisable === undefined) { - delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL - } else { - process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL = origDisable - } - vi.restoreAllMocks() - vi.clearAllMocks() - }) - - it('does not let a spawn-path probe overwrite a newer death verdict', async () => { - setPlatform('darwin') - ptyProbeMock.mockResolvedValue(REJECTED_OUTCOME) - const finishers: ((result: typeof ACCEPTED_RESULT) => void)[] = [] - runProcessMock.mockImplementation(() => new Promise((resolve) => finishers.push(resolve))) - - const freshProbe = probeMacosLoginSessionAlive() - const spawnProbe = prepareMacosTccLoginShell() - expect(runProcessMock).toHaveBeenCalledTimes(2) - - finishers[0](REJECTED_RESULT) - await expect(freshProbe).resolves.toEqual(REJECTED_OUTCOME) - finishers[1](ACCEPTED_RESULT) - await expect(spawnProbe).resolves.toEqual(ACCEPTED_OUTCOME) - - expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l']).file).toBe('/bin/zsh') - }) -}) diff --git a/src/main/providers/macos-tcc-login-shell.ts b/src/main/providers/macos-tcc-login-shell.ts deleted file mode 100644 index db37b75358a..00000000000 --- a/src/main/providers/macos-tcc-login-shell.ts +++ /dev/null @@ -1,321 +0,0 @@ -import { runProcess } from '@orca/process-host' -import { existsSync } from 'node:fs' -import { userInfo } from 'node:os' -import { basename } from 'node:path' -import { - runMacosLoginSessionPtyProbe, - type LoginPreflightOutcome -} from './macos-login-session-pty-probe' - -export type { LoginPreflightOutcome } from './macos-login-session-pty-probe' - -export const MACOS_LOGIN_PATH = '/usr/bin/login' -const MACOS_BASH_PATH = '/bin/bash' -const MACOS_PRINTF_PATH = '/usr/bin/printf' -const LOGIN_SHELL_TRAMPOLINE = 'export SHELL="$1"; shift; exec -l -- "$@"' -const DIRECT_SHELL_TRAMPOLINE = 'export SHELL="$1"; shift; exec -- "$@"' -const LOGIN_PREFLIGHT_TIMEOUT_MS = 500 -// Off the spawn path, the death watch can outwait a slow PAM stack without delaying terminal creation. -const LOGIN_SESSION_WATCH_PROBE_TIMEOUT_MS = 4_000 -const LOGIN_PREFLIGHT_MARKER = 'ORCA_LOGIN_PREFLIGHT_OK' -const LOGIN_PREFLIGHT_MAX_BUFFER_BYTES = 1024 -const LOGIN_PREFLIGHT_RETRY_BASE_MS = 5_000 -const LOGIN_PREFLIGHT_RETRY_MAX_MS = 5 * 60_000 -// Long-lived daemons must recheck rejected PAM capability rather than disable attribution forever (#9756). -const LOGIN_PREFLIGHT_REJECTED_REVALIDATE_MS = 30 * 60_000 - -const DISABLE_ENV_VAR = 'ORCA_DISABLE_MACOS_LOGIN_SHELL' - -// Cache only actual PAM verdicts; timeout, output-cap and spawn failures remain retryable. -let cachedLoginPreflightResult: boolean | null = null -let cachedRejectionAtMs: number | null = null -let loginPreflightInFlight: Promise | null = null -let transientLoginPreflightFailure: { failureCount: number; retryAtMs: number } | null = null -let loginPreflightCacheEpoch = 0 -let loginSessionProbeInFlight = false -let loginSessionAcceptedInProcess = false - -function isDisabledByEnv(): boolean { - const value = process.env[DISABLE_ENV_VAR] - return value === '1' || value === 'true' -} - -function loginPreflightRetryDelayMs(failureCount: number): number { - return Math.min( - LOGIN_PREFLIGHT_RETRY_MAX_MS, - LOGIN_PREFLIGHT_RETRY_BASE_MS * 2 ** Math.max(0, failureCount - 1) - ) -} - -// Pipes can differ from production PTYs; later wrapper spawn failures still degrade to a direct shell. -async function runLoginPreflight( - username: string, - accountHome: string, - timeoutMs = LOGIN_PREFLIGHT_TIMEOUT_MS, - signal?: AbortSignal -): Promise { - try { - const result = await runProcess({ - program: MACOS_LOGIN_PATH, - args: ['-flpq', username, MACOS_PRINTF_PATH, LOGIN_PREFLIGHT_MARKER], - // Detached daemons may outlive their worktree; probe from the account home. - cwd: accountHome, - maxOutputBytes: LOGIN_PREFLIGHT_MAX_BUFFER_BYTES, - signal, - timeoutMs - }) - if (result.timedOut) { - return { ok: false, conclusive: false, reason: 'timeout' } - } - if (result.code === null) { - return { ok: false, conclusive: false, reason: 'error' } - } - if (result.code !== 0) { - return { ok: false, conclusive: true, reason: 'rejected' } - } - // login(1) can return zero after failed EOF prompting; require clean exit plus child marker. - return result.stdout === LOGIN_PREFLIGHT_MARKER - ? { ok: true, conclusive: true, reason: 'accepted' } - : { ok: false, conclusive: true, reason: 'rejected' } - } catch { - return { ok: false, conclusive: false, reason: 'error' } - } -} - -async function verifyRejectedLoginPreflightUnderPty( - username: string, - accountHome: string, - outcome: LoginPreflightOutcome -): Promise { - if (outcome.ok || !outcome.conclusive) { - return outcome - } - const ptyOutcome = await runMacosLoginSessionPtyProbe( - username, - accountHome, - LOGIN_PREFLIGHT_TIMEOUT_MS, - LOGIN_PREFLIGHT_MAX_BUFFER_BYTES - ) - // Why: a pipe-sensitive PAM stack must not override the production-shaped PTY oracle. - return ptyOutcome.conclusive ? ptyOutcome : outcome -} - -function expireStaleRejectedVerdict(): void { - if ( - cachedLoginPreflightResult === false && - cachedRejectionAtMs !== null && - Date.now() - cachedRejectionAtMs >= LOGIN_PREFLIGHT_REJECTED_REVALIDATE_MS - ) { - cachedLoginPreflightResult = null - cachedRejectionAtMs = null - } -} - -function cachedOutcome(): LoginPreflightOutcome | null { - if (cachedLoginPreflightResult === null) { - return null - } - return cachedLoginPreflightResult - ? { ok: true, conclusive: true, reason: 'accepted' } - : { ok: false, conclusive: true, reason: 'rejected' } -} - -function cacheConclusiveLoginPreflightOutcome(outcome: LoginPreflightOutcome): void { - if (outcome.ok) { - cachedRejectionAtMs = null - loginSessionAcceptedInProcess = true - } else if (cachedLoginPreflightResult !== false || cachedRejectionAtMs === null) { - // Why: periodic health probes must not extend one rejected verdict forever. - cachedRejectionAtMs = Date.now() - } - cachedLoginPreflightResult = outcome.ok - transientLoginPreflightFailure = null -} - -function loginPreflightSucceeds( - username: string, - accountHome: string -): Promise { - const cached = cachedOutcome() - if (cached) { - return Promise.resolve(cached) - } - if (!loginPreflightInFlight) { - const cacheEpoch = loginPreflightCacheEpoch - // Coalesce pane restores so startup bursts share one PAM subprocess. - loginPreflightInFlight = runLoginPreflight(username, accountHome).then(async (pipeOutcome) => { - const outcome = await verifyRejectedLoginPreflightUnderPty(username, accountHome, pipeOutcome) - // Environmental failures cannot become cached PAM verdicts; retry through bounded backoff. - const mayUpdateCache = !loginSessionProbeInFlight && cacheEpoch === loginPreflightCacheEpoch - if (outcome.conclusive && mayUpdateCache) { - cacheConclusiveLoginPreflightOutcome(outcome) - } else if (!outcome.conclusive && mayUpdateCache) { - const failureCount = (transientLoginPreflightFailure?.failureCount ?? 0) + 1 - transientLoginPreflightFailure = { - failureCount, - retryAtMs: Date.now() + loginPreflightRetryDelayMs(failureCount) - } - } - if (!outcome.ok) { - console.warn('[pty] macOS login(1) preflight failed; spawning shells directly') - } - // Release the in-flight slot so future spawns can retry inconclusive outcomes. - loginPreflightInFlight = null - return outcome - }) - } - return loginPreflightInFlight -} - -/** Await asynchronously to keep main responsive; null means no probe ran. - * Rejections expire; accepted state changes through the health watch. Return outcomes for detached-daemon telemetry. */ -export async function prepareMacosTccLoginShell(): Promise { - if (process.platform !== 'darwin' || isDisabledByEnv()) { - return null - } - expireStaleRejectedVerdict() - if (cachedLoginPreflightResult !== null) { - return null - } - // Why: a persistently hung probe must not add 500 ms and a subprocess to every terminal spawn. - if (transientLoginPreflightFailure && Date.now() < transientLoginPreflightFailure.retryAtMs) { - return null - } - if (!existsSync(MACOS_LOGIN_PATH)) { - return null - } - - let username: string - let accountHome: string - try { - const account = userInfo() - username = account.username - accountHome = account.homedir - } catch { - return null - } - if (!username || !accountHome) { - return null - } - return loginPreflightSucceeds(username, accountHome) -} - -export function resetMacosLoginShellPreflightForTests(): void { - cachedLoginPreflightResult = null - cachedRejectionAtMs = null - loginPreflightInFlight = null - transientLoginPreflightFailure = null - loginPreflightCacheEpoch = 0 - loginSessionProbeInFlight = false - loginSessionAcceptedInProcess = false -} - -/** Fresh death-watch check bypasses spawn cache/backoff and updates conclusive verdicts (#7936). - * Ambiguous results or rejection after prior acceptance require PTY confirmation; null means wrapping does not apply. */ -export async function probeMacosLoginSessionAlive( - signal?: AbortSignal -): Promise { - if (process.platform !== 'darwin' || isDisabledByEnv() || !existsSync(MACOS_LOGIN_PATH)) { - return null - } - let username: string - let accountHome: string - try { - const account = userInfo() - username = account.username - accountHome = account.homedir - } catch { - return null - } - if (!username || !accountHome) { - return null - } - // Why: reuse the startup warmup when present, and fence older spawn-path results from restoring a stale verdict. - const existingPreflight = loginPreflightInFlight - loginSessionProbeInFlight = true - loginPreflightCacheEpoch++ - let outcome: LoginPreflightOutcome - try { - outcome = await (existingPreflight ?? - runLoginPreflight(username, accountHome, LOGIN_SESSION_WATCH_PROBE_TIMEOUT_MS, signal)) - if (!outcome.ok && !signal?.aborted && (!outcome.conclusive || loginSessionAcceptedInProcess)) { - outcome = await runMacosLoginSessionPtyProbe( - username, - accountHome, - LOGIN_SESSION_WATCH_PROBE_TIMEOUT_MS, - LOGIN_PREFLIGHT_MAX_BUFFER_BYTES, - signal - ) - } - } finally { - // Why: invalidate spawn probes started during this fresh check before they can overwrite its newer verdict. - loginPreflightCacheEpoch++ - loginSessionProbeInFlight = false - } - if (outcome.conclusive) { - cacheConclusiveLoginPreflightOutcome(outcome) - } - return outcome -} - -/** login(1) reports its own status, losing shell exit codes/signals; wrapped outcomes must be unknown (STA-4536). */ -export function hostReportsChildExitStatus(file: string): boolean { - return file !== MACOS_LOGIN_PATH -} - -/** login(1) gives signed terminal CLIs independent TCC grants; positional trampoline args cannot become shell source. */ -export function wrapShellSpawnForMacosTccAttribution( - file: string, - args: string[], - env?: Record -): { file: string; args: string[] } { - if (process.platform !== 'darwin') { - return { file, args } - } - if (file === MACOS_LOGIN_PATH || isDisabledByEnv()) { - return { file, args } - } - if (!existsSync(MACOS_LOGIN_PATH)) { - return { file, args } - } - - let username: string - try { - username = userInfo().username - } catch { - return { file, args } - } - if (!username) { - return { file, args } - } - // Unprepared/rejected hosts still need usable shells; fresh-spawn callers prepare asynchronously first. - if (cachedLoginPreflightResult !== true) { - return { file, args } - } - - const shellEnvValue = env?.SHELL || file - // Login argv[0] disables Bash --rcfile; the Orca rcfile already implements login startup. - const trampoline = - basename(file).toLowerCase() === 'bash' && args.includes('--rcfile') - ? DIRECT_SHELL_TRAMPOLINE - : LOGIN_SHELL_TRAMPOLINE - - // -p blocks inherited BASH_ENV and imported functions before the fixed positional trampoline. - return { - file: MACOS_LOGIN_PATH, - args: [ - '-flpq', - username, - MACOS_BASH_PATH, - '--noprofile', - '--norc', - '-p', - '-c', - trampoline, - 'orca-tcc-login', - shellEnvValue, - file, - ...args - ] - } -} diff --git a/src/main/providers/posix-pane-foreground-fingerprint.ts b/src/main/providers/posix-pane-foreground-fingerprint.ts deleted file mode 100644 index c2a00221d80..00000000000 --- a/src/main/providers/posix-pane-foreground-fingerprint.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { readFile } from 'node:fs/promises' -import { collectDescendantsFromIndex, getProcessTableIndex } from '../../shared/process-table-index' -import { parseLinuxProcStatStartTime } from '../../shared/process-table-snapshot-reader' - -/** Cheap-tier job-control columns omit command/tty by design. */ -export type PaneFingerprintRow = { - pid: number - ppid: number - pgid?: number - tpgid?: number - stat: string - startTime?: string -} - -export type PaneFingerprintDeps = { - platform?: NodeJS.Platform - /** Linux: `/proc//stat` field 22, read for the pane subtree only. */ - readLinuxStartTime?: (pid: number) => Promise -} - -/** Ignore scheduler churn; stopped, zombie and foreground states can change pane ownership. */ -function jobControlState(stat: string): string { - const head = stat[0] ?? '' - const lifecycle = head === 'T' || head === 't' ? 'T' : head === 'Z' ? 'Z' : '' - return lifecycle + (stat.includes('+') ? '+' : '') -} - -async function readLinuxProcStartTime(pid: number): Promise { - try { - return parseLinuxProcStatStartTime(await readFile(`/proc/${pid}/stat`, 'utf8')) - } catch { - return null - } -} - -/** Reuse recognition only across equal fenced shell/descendant identities, groups and job-control state. - * Missing root, start markers or group columns requires a full capture instead. */ -export async function buildPaneProcessFingerprint( - rows: readonly PaneFingerprintRow[], - rootPid: number, - deps: PaneFingerprintDeps = {} -): Promise { - const platform = deps.platform ?? process.platform - const index = getProcessTableIndex(rows) - const root = index.byPid.get(rootPid) - if (!root || root.pgid === undefined || root.tpgid === undefined) { - return null - } - const descendants = collectDescendantsFromIndex(index, rootPid) - const subtree = [root, ...descendants] - let startTimes: ReadonlyMap - if (platform === 'linux') { - const read = deps.readLinuxStartTime ?? readLinuxProcStartTime - const entries = await Promise.all( - subtree.map(async (row) => [row.pid, await read(row.pid)] as const) - ) - startTimes = new Map(entries) - } else { - // Collapse `lstart` padding (`Sep 3`) so both column sets stamp identically. - startTimes = new Map( - subtree.map((row) => [row.pid, row.startTime?.replace(/\s+/g, ' ') ?? null] as const) - ) - } - const rootStart = startTimes.get(rootPid) - if (!rootStart) { - return null - } - // Every descendant needs a start marker; placeholders could compare equal across PID reuse and mask agent exit. - const members: string[] = [] - for (const row of descendants) { - const startTime = startTimes.get(row.pid) - if (!startTime) { - return null - } - members.push(`${row.pid}@${startTime}:${row.pgid ?? '?'}:${jobControlState(row.stat)}`) - } - members.sort() - return `${rootPid}@${rootStart}#${root.tpgid}:${jobControlState(root.stat)}|${members.join(',')}` -} diff --git a/src/main/providers/pty-default-cwd.ts b/src/main/providers/pty-default-cwd.ts deleted file mode 100644 index 4f13523a3c3..00000000000 --- a/src/main/providers/pty-default-cwd.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { homedir } from 'node:os' - -import { isRootLikePath } from './pty-path-safety' - -function homeDrivePath(env: NodeJS.ProcessEnv): string | null { - if (!env.HOMEDRIVE || !env.HOMEPATH) { - return null - } - return `${env.HOMEDRIVE}${env.HOMEPATH}` -} - -export function isSafeImplicitPtyCwd(path: string | null | undefined): path is string { - return !isRootLikePath(path) -} - -export function resolveSafePtyDefaultCwd(env: NodeJS.ProcessEnv = process.env): string { - const candidates = - process.platform === 'win32' - ? [env.USERPROFILE, homeDrivePath(env), homedir()] - : [env.HOME, homedir()] - const selected = candidates.find(isSafeImplicitPtyCwd) - // Root fallback can trigger runaway discovery; refuse when no safe home exists. - if (!selected) { - // Record candidate values so malformed home environments remain diagnosable. - console.error( - '[pty-default-cwd] No safe default working directory for terminal launch; every home candidate resolved to a root-like path.', - { platform: process.platform, candidates } - ) - throw new Error('No safe default working directory is available for terminal launch.') - } - return selected -} - -export function assertSafeAgentStartupCwd(cwd: string | undefined, command: string): void { - if (isSafeImplicitPtyCwd(cwd)) { - return - } - throw new Error( - `Automatic agent startup command "${command}" requires a non-root workspace working directory.` - ) -} diff --git a/src/main/providers/pty-foreground-confirmation.ts b/src/main/providers/pty-foreground-confirmation.ts deleted file mode 100644 index a741600dd7f..00000000000 --- a/src/main/providers/pty-foreground-confirmation.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { IPty } from 'node-pty' -import { recognizeAgentProcess } from '../../shared/agent-status/process/agent-process-recognition' -import { shouldInspectOuterWrapperForegroundProcess } from '../../shared/foreground-wrapper-agent' -import { ptyShellProcessId } from '../windows/windows-pty-job' -import { createPtyForegroundResolver } from '../daemon/pty-subprocess/spawn-file-foreground-process' -import { - resolveAgentForegroundProcessWithAvailability, - type AgentForegroundResolutionOptions, - type AgentForegroundProcessResolution -} from './agent-foreground-process' -import { - judgeCachedAgentJobEvidence, - reconcileWindowsAgentDecision, - type WindowsCachedAgentJobVerdict -} from './windows-cached-agent-revalidation' -import { readWindowsConsoleAttachedProcessIds } from './windows-console-attached-processes' -import { isWindowsPtyJobReadable, readWindowsPtyJobProcessIds } from './windows-pty-job-membership' - -/** Execute fresh confirmation; owners retain cache publication and lifetime fences. */ -export async function confirmFreshPtyForeground(args: { - process: IPty - fallbackProcess: string | null - contextPaths: AgentForegroundResolutionOptions['contextPaths'] - decision: boolean - anchor: { processName: string; pid: number | null } | null - anchorAt?: number -}): Promise<{ resolution: AgentForegroundProcessResolution; processName: string | null }> { - const proc = args.process - const shellPid = ptyShellProcessId(proc) ?? proc.pid - let verdict: WindowsCachedAgentJobVerdict = 'unavailable' - if (args.decision) { - try { - verdict = judgeCachedAgentJobEvidence({ - jobProcessIds: readWindowsPtyJobProcessIds(proc), - jobSupported: isWindowsPtyJobReadable(), - shellPid, - anchorProcessId: args.anchor?.pid ?? null, - identityAgeMs: Date.now() - (args.anchorAt ?? 0) - }) - } catch { - /* A failed job read cannot release a known anchor. */ - } - } - let resolution: AgentForegroundProcessResolution - try { - const resolve = args.decision - ? resolveAgentForegroundProcessWithAvailability - : createPtyForegroundResolver(proc) - resolution = await resolve(proc.pid, args.fallbackProcess, { - contextPaths: args.contextPaths, - fresh: true, - ...(args.decision && args.anchor?.pid != null - ? { anchorProcessId: args.anchor.pid, anchorProcessName: args.anchor.processName } - : {}), - ...(process.platform === 'win32' - ? { - forceProcessScan: true, - readWindowsConsoleAttachedProcessIds: () => - readWindowsConsoleAttachedProcessIds(proc.pid) - } - : {}) - }) - } catch { - resolution = { available: false, processName: null } - } - return { - resolution, - processName: args.decision - ? reconcileWindowsAgentDecision(resolution, verdict, args.anchor, shellPid) - : resolution.available - ? resolution.processName - : null - } -} - -/** Known direct agent names need no POSIX scan; Windows decisions still require fresh evidence. */ -export function shouldConfirmPtyForeground(fallback: string | null, decision: boolean): boolean { - if (!fallback) { - return decision - } - const recognized = recognizeAgentProcess(fallback) - return ( - process.platform === 'win32' || - recognized === null || - shouldInspectOuterWrapperForegroundProcess(recognized) - ) -} diff --git a/src/main/providers/pty-process-info.ts b/src/main/providers/pty-process-info.ts deleted file mode 100644 index 2c72c0ff8ca..00000000000 --- a/src/main/providers/pty-process-info.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { AgentSessionOwnerBinding } from '../../shared/agent-session/agent-session-host-authority' -import type { PtyIncarnationId } from '../../shared/terminal/pty/lifecycle/pty-incarnation' -import type { ForegroundProcessEvidence } from '../../shared/foreground-process-evidence' -import type { WslGuestRoot } from '../../shared/wsl-guest-root-marker' - -export type PtyProcessInfo = { - id: string - incarnationId?: PtyIncarnationId - /** Local diagnostic provenance supplied by a multi-daemon router. */ - inventorySourceId?: string - /** Whether this diagnostic candidate is the established route for its id. */ - routed?: boolean - /** Root process owned by this exact PTY incarnation, when the provider can prove it. */ - rootProcessId?: number - /** Recently observed process name; inventory reads never initiate process inspection. */ - foregroundProcess?: string - cwd: string - title: string - /** Owning worktree when the provider can report it authoritatively. */ - worktreeId?: string - /** Trusted ORCA_TERMINAL_HANDLE exported into this PTY, when known. */ - terminalHandle?: string - /** ORCA_PANE_KEY this PTY was spawned with, when the provider recorded it. */ - paneKey?: string - /** Exact WSL owner reported by the PTY provider; null means native Windows. */ - wslDistro?: string | null - /** A live WSL PTY's guest root shell, seen once at its launch; absent from older owners. */ - wslGuestRoot?: WslGuestRoot - /** Optional host-side process evidence attached to an inventory seed. */ - foregroundProcessEvidence?: ForegroundProcessEvidence - agentSessionOwners?: AgentSessionOwnerBinding[] - /** Owning-host clock age; absent is unmeasured, so age-dependent decisions must defer. */ - hostAgeMs?: number - /** Host attests Orca pane (true) or bare shell (false); absent is unknown on older hosts. */ - paneBound?: boolean - /** Creator identity attested by the owning host; absent never means unowned. */ - ownerClientInstanceId?: string - /** Still live during accepted termination, but cannot be adopted/restored; absent on older hosts. */ - exiting?: true -} diff --git a/src/main/providers/pty-process-inspection.ts b/src/main/providers/pty-process-inspection.ts deleted file mode 100644 index 30fd15186dd..00000000000 --- a/src/main/providers/pty-process-inspection.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { IPtyProvider } from './pty-provider-contract' -import type { PtyIncarnationId } from '../../shared/terminal/pty/lifecycle/pty-incarnation' -import { - classifyTerminalProcessInspectionFailure, - clientOnlyUnverifiableInspection, - type TerminalProcessInspection as PtyProcessInspection -} from '../../shared/terminal/pty/lifecycle/terminal-process-inspection' - -type CompletionSensitivePtyProvider = IPtyProvider & { - inspectProcess?: ( - id: string, - options?: PtyProcessInspectionOptions - ) => Promise -} - -/** scanChildProcesses requests decision-time evidence; steady polls may rely on the next tick to correct stale reads. */ -export type PtyProcessInspectionOptions = { - foregroundOnly?: boolean - expectedIncarnationId?: PtyIncarnationId - scanChildProcesses?: boolean - /** Adoption only: ignore members outside both shell ancestry and console; close still reaches the whole job. */ - ignoreDetached?: boolean - /** Name-only cadence polls may use cheap captures and omit evidence; evidence consumers must never set this. */ - steadyState?: boolean - /** Also reach a session the daemon still runs that no window has reattached since a relaunch. - * WSL move gate only: other callers keep reading such a session as gone. */ - includeUnattached?: boolean -} - -export async function inspectPtyProviderProcess( - provider: IPtyProvider, - ptyId: string, - options?: PtyProcessInspectionOptions -): Promise { - // The daemon's own inspect still refuses a session it no longer runs. - if (options?.includeUnattached !== true && provider.hasPty?.(ptyId) === false) { - throw new Error('terminal_gone') - } - const inspectProcess = (provider as CompletionSensitivePtyProvider).inspectProcess - if (inspectProcess) { - return options - ? inspectProcess.call(provider, ptyId, options) - : inspectProcess.call(provider, ptyId) - } - const foregroundProcess = await provider.getForegroundProcess(ptyId) - const hasChildProcesses = await provider.hasChildProcesses(ptyId) - return { foregroundProcess, hasChildProcesses } -} - -export async function inspectPtyProviderProcessForRenderer( - provider: IPtyProvider, - ptyId: string, - options?: PtyProcessInspectionOptions -): Promise { - try { - return await inspectPtyProviderProcess(provider, ptyId, options) - } catch (error) { - const reason = classifyTerminalProcessInspectionFailure(error) - if (reason) { - return clientOnlyUnverifiableInspection(reason) - } - throw error - } -} diff --git a/src/main/providers/pty-process-list-admission.test.ts b/src/main/providers/pty-process-list-admission.test.ts deleted file mode 100644 index 33c27ceab66..00000000000 --- a/src/main/providers/pty-process-list-admission.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - MAX_AGGREGATED_PTY_PROCESS_LIST_BYTES, - MAX_AGGREGATED_PTY_PROCESS_LIST_ENTRIES, - MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS, - PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE, - PtyProcessListAdmission, - visitPtyProcessListingsInBatches -} from './pty-process-list-admission' - -describe('PtyProcessListAdmission', () => { - const evidence = { - verdict: 'live' as const, - processName: 'codex', - authorityGeneration: 'relay-generation', - observationEpoch: 4, - capturedAgeMs: 12 - } - - it('rejects malformed foreground evidence instead of stripping it', () => { - expect(() => - new PtyProcessListAdmission().admit({ - id: 'pty-1', - cwd: '/repo', - title: 'shell', - foregroundProcessEvidence: { ...evidence, verdict: 'wat' } - } as never) - ).toThrow('invalid_pty_process_list') - }) - - it('carries a WSL guest root and rejects a malformed one instead of stripping it', () => { - const session = { - id: 'pty', - cwd: '/', - title: 'shell', - wslDistro: 'Ubuntu', - wslGuestRoot: { pid: 4242, startTime: '0b1d2c3e-4f50-4617-8293-a4b5c6d7e8f9:98765' } - } - expect(new PtyProcessListAdmission().admit(session)).toEqual(session) - expect(() => - new PtyProcessListAdmission().admit({ ...session, wslGuestRoot: { pid: 1, startTime: 'x' } }) - ).toThrow('invalid_pty_process_list') - }) - - it('admits diagnostic provenance and rejects malformed routing evidence', () => { - const session = { - id: 'pty', - cwd: '/', - title: 'shell', - inventorySourceId: 'source', - routed: false - } - expect(new PtyProcessListAdmission().admit(session)).toEqual(session) - Reflect.set(session, 'routed', 'yes') - expect(() => new PtyProcessListAdmission().admit(session)).toThrow('invalid_pty_process_list') - Reflect.set(session, 'routed', false) - Reflect.set(session, 'inventorySourceId', 1) - expect(() => new PtyProcessListAdmission().admit(session)).toThrow('invalid_pty_process_list') - }) - - it('strips unknown provider payloads from admitted process metadata', () => { - const admission = new PtyProcessListAdmission() - - expect( - admission.admit({ - id: 'pty-1', - cwd: '/repo', - title: 'shell', - unknownPayload: 'x'.repeat(1024 * 1024) - } as never) - ).toEqual({ id: 'pty-1', cwd: '/repo', title: 'shell' }) - }) - - it('rejects aggregate entry and byte amplification', () => { - const entryAdmission = new PtyProcessListAdmission() - for (let index = 0; index < MAX_AGGREGATED_PTY_PROCESS_LIST_ENTRIES; index += 1) { - entryAdmission.admit({ id: `pty-${index}`, cwd: '', title: 'shell' }) - } - expect(() => entryAdmission.admit({ id: 'one-more', cwd: '', title: 'shell' })).toThrow( - 'pty_process_list_capacity' - ) - - const byteAdmission = new PtyProcessListAdmission() - expect(() => - byteAdmission.admit({ - id: 'pty-large', - cwd: 'x'.repeat(MAX_AGGREGATED_PTY_PROCESS_LIST_BYTES), - title: 'shell' - }) - ).toThrow('pty_process_list_capacity') - - expect(() => - new PtyProcessListAdmission().admit({ - id: 'pty-owner-flood', - cwd: '', - title: 'shell', - agentSessionOwners: Array.from( - { length: MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS + 1 }, - () => ({}) - ) - } as never) - ).toThrow('pty_process_list_capacity') - }) -}) - -describe('visitPtyProcessListingsInBatches', () => { - it('never starts more than the bounded provider batch concurrently', async () => { - let active = 0 - let peak = 0 - const finishes: (() => void)[] = [] - const load = vi.fn( - async (source: number) => - await new Promise<{ id: string; cwd: string; title: string }[]>((resolve) => { - active += 1 - peak = Math.max(peak, active) - finishes.push(() => { - active -= 1 - resolve([{ id: `pty-${source}`, cwd: '', title: 'shell' }]) - }) - }) - ) - const visiting = visitPtyProcessListingsInBatches( - Array.from({ length: PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE + 1 }, (_, index) => index), - load, - () => {} - ) - - await vi.waitFor(() => expect(finishes).toHaveLength(PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE)) - finishes.splice(0).forEach((finish) => finish()) - await vi.waitFor(() => expect(finishes).toHaveLength(1)) - finishes.splice(0).forEach((finish) => finish()) - await visiting - - expect(peak).toBe(PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE) - }) -}) diff --git a/src/main/providers/pty-process-list-admission.ts b/src/main/providers/pty-process-list-admission.ts deleted file mode 100644 index 0c277ff9dee..00000000000 --- a/src/main/providers/pty-process-list-admission.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { isAgentSessionOwnerBinding } from '../../shared/agent-session/agent-session-host-authority' -import { MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES } from '../../shared/claimed-agent-pty-owner' -import { cloneAgentSessionOwnerBinding } from '../../shared/claimed-agent-pty-owner-snapshot' -import { isPtyIncarnationId } from '../../shared/terminal/pty/lifecycle/pty-incarnation' -import { - cloneForegroundProcessEvidence, - isForegroundProcessEvidence -} from '../../shared/foreground-process-evidence' -import type { PtyProcessInfo } from './pty-provider-contract' -import { readWslGuestRoot } from '../../shared/wsl-guest-root-marker' - -export const MAX_AGGREGATED_PTY_PROCESS_LIST_ENTRIES = 4096 -export const MAX_AGGREGATED_PTY_PROCESS_LIST_BYTES = 32 * 1024 * 1024 -export const MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS = MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES -export const PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE = 4 - -function retainedStringBytes(value: unknown): number | null { - return typeof value === 'string' ? Buffer.byteLength(value, 'utf8') : null -} - -function retainedOptionalStringBytes(value: unknown): number | null { - return value === undefined ? 0 : retainedStringBytes(value) -} - -function retainedOwnerBytes(owner: unknown, ptyId: string): number | null { - if (!isAgentSessionOwnerBinding(owner) || owner.phase !== 'live' || owner.ptyId !== ptyId) { - return null - } - return [ - owner.claim.keyId, - owner.claim.identityDigest, - owner.claim.worktreeScopeDigest, - owner.claim.agent, - owner.generation, - owner.ptyId, - owner.surface.worktreeId, - owner.surface.tabId, - owner.surface.leafId, - owner.surface.terminalHandle - ].reduce((total, value) => total + Buffer.byteLength(value, 'utf8'), 0) -} - -export class PtyProcessListAdmission { - private entries = 0 - private retainedBytes = 0 - private owners = 0 - - constructor(private readonly capacityError = 'pty_process_list_capacity') {} - - admit(value: PtyProcessInfo): PtyProcessInfo { - if (typeof value !== 'object' || value === null) { - throw new Error('invalid_pty_process_list') - } - const idBytes = retainedStringBytes(value.id) - const cwdBytes = retainedStringBytes(value.cwd) - const titleBytes = retainedStringBytes(value.title) - const foregroundProcessBytes = retainedOptionalStringBytes(value.foregroundProcess) - const inventorySourceBytes = retainedOptionalStringBytes(value.inventorySourceId) - const worktreeIdBytes = retainedOptionalStringBytes(value.worktreeId) - const terminalHandleBytes = retainedOptionalStringBytes(value.terminalHandle) - const paneKeyBytes = retainedOptionalStringBytes(value.paneKey) - const wslDistroBytes = - value.wslDistro === null ? 0 : retainedOptionalStringBytes(value.wslDistro) - const wslGuestRoot = readWslGuestRoot(value.wslGuestRoot) - const evidenceBytes = - value.foregroundProcessEvidence === undefined - ? 0 - : isForegroundProcessEvidence(value.foregroundProcessEvidence) - ? Buffer.byteLength(JSON.stringify(value.foregroundProcessEvidence), 'utf8') - : null - if ( - idBytes === null || - cwdBytes === null || - titleBytes === null || - foregroundProcessBytes === null || - inventorySourceBytes === null || - (value.routed !== undefined && typeof value.routed !== 'boolean') || - worktreeIdBytes === null || - terminalHandleBytes === null || - paneKeyBytes === null || - wslDistroBytes === null || - evidenceBytes === null || - (value.wslGuestRoot !== undefined && !wslGuestRoot) || - (value.rootProcessId !== undefined && - (!Number.isSafeInteger(value.rootProcessId) || value.rootProcessId <= 0)) || - (value.incarnationId !== undefined && !isPtyIncarnationId(value.incarnationId)) || - (value.agentSessionOwners !== undefined && !Array.isArray(value.agentSessionOwners)) - ) { - throw new Error('invalid_pty_process_list') - } - if ( - (value.agentSessionOwners?.length ?? 0) > - MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS - this.owners - ) { - throw new Error(this.capacityError) - } - - let ownerBytes = 0 - const normalizedOwners = value.agentSessionOwners?.map((owner) => { - const bytes = retainedOwnerBytes(owner, value.id) - if (bytes === null) { - throw new Error('agent_session_ownership_unknown') - } - ownerBytes += bytes - return cloneAgentSessionOwnerBinding(owner) - }) - const nextEntries = this.entries + 1 - const nextOwners = this.owners + (normalizedOwners?.length ?? 0) - const nextBytes = - this.retainedBytes + - idBytes + - cwdBytes + - titleBytes + - foregroundProcessBytes + - inventorySourceBytes + - worktreeIdBytes + - terminalHandleBytes + - paneKeyBytes + - wslDistroBytes + - evidenceBytes + - (wslGuestRoot?.startTime.length ?? 0) + - ownerBytes - if ( - nextEntries > MAX_AGGREGATED_PTY_PROCESS_LIST_ENTRIES || - nextOwners > MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS || - nextBytes > MAX_AGGREGATED_PTY_PROCESS_LIST_BYTES - ) { - throw new Error(this.capacityError) - } - this.entries = nextEntries - this.owners = nextOwners - this.retainedBytes = nextBytes - - return { - id: value.id, - cwd: value.cwd, - title: value.title, - ...(value.inventorySourceId !== undefined - ? { inventorySourceId: value.inventorySourceId } - : {}), - ...(value.routed !== undefined ? { routed: value.routed } : {}), - ...(value.foregroundProcess !== undefined - ? { foregroundProcess: value.foregroundProcess } - : {}), - ...(value.incarnationId !== undefined ? { incarnationId: value.incarnationId } : {}), - ...(value.rootProcessId !== undefined ? { rootProcessId: value.rootProcessId } : {}), - ...(value.worktreeId !== undefined ? { worktreeId: value.worktreeId } : {}), - ...(value.terminalHandle !== undefined ? { terminalHandle: value.terminalHandle } : {}), - ...(value.paneKey !== undefined ? { paneKey: value.paneKey } : {}), - ...(value.wslDistro !== undefined ? { wslDistro: value.wslDistro } : {}), - ...(wslGuestRoot ? { wslGuestRoot } : {}), - ...(value.exiting === true ? { exiting: true as const } : {}), - ...(value.foregroundProcessEvidence !== undefined - ? { - foregroundProcessEvidence: cloneForegroundProcessEvidence( - value.foregroundProcessEvidence - ) - } - : {}), - ...(normalizedOwners !== undefined ? { agentSessionOwners: normalizedOwners } : {}) - } - } -} - -export async function visitPtyProcessListingsInBatches( - sources: Iterable, - load: (source: T) => Promise, - visit: (source: T, processes: readonly PtyProcessInfo[]) => void -): Promise { - let batch: T[] = [] - for (const source of sources) { - batch.push(source) - if (batch.length < PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE) { - continue - } - const listings = await Promise.all( - batch.map(async (entry) => ({ entry, processes: await load(entry) })) - ) - for (const listing of listings) { - visit(listing.entry, listing.processes) - } - batch = [] - } - if (batch.length === 0) { - return - } - const listings = await Promise.all( - batch.map(async (entry) => ({ entry, processes: await load(entry) })) - ) - for (const listing of listings) { - visit(listing.entry, listing.processes) - } -} diff --git a/src/main/providers/pty-provider-contract.ts b/src/main/providers/pty-provider-contract.ts deleted file mode 100644 index 3119863ad4e..00000000000 --- a/src/main/providers/pty-provider-contract.ts +++ /dev/null @@ -1,246 +0,0 @@ -import type { DaemonLaunchNoteChange } from '../daemon/protocol/daemon-launch-note-protocol' -import type { - PtyFencedTerminationRequest, - PtyFencedTerminationOutcome -} from '../../shared/terminal/pty/lifecycle/pty-fenced-termination' -import type { SpawnIntent } from '../../shared/terminal/pty/admission/spawn-admission-contract' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import type { AgentWorkspaceTrustSpawnRequest } from '../../shared/agent-launch/permissions/agent-workspace-trust-spawn-request' -import type { PtyStartupIngressIntent } from '../../shared/terminal/pty/ingress/pty-startup-ingress-intent' -import type { TerminalOscColorQueryReplyColors } from '../../shared/terminal/protocol/queries/terminal-osc-color-reply' -import type { StartupCommandDelivery } from '../../shared/agent-launch/startup/codex-startup-delivery' -import type { TerminalOscLinkRange } from '../../shared/terminal/links/terminal-osc-link-ranges' -import type { PtyBackgroundStreamEvent, PtyDataEvent } from './pty-provider-events' -import type { PtySpawnResult } from './pty-spawn-result' -import type { PtyIncarnationId } from '../../shared/terminal/pty/lifecycle/pty-incarnation' -import type { - AgentSessionExecutionClaim, - AgentSessionSurfaceBinding -} from '../../shared/agent-session/agent-session-host-authority' -import type { PtyProcessInfo } from './pty-process-info' -import type { TerminalExitCause } from '../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import type { TerminalOwner } from '../../shared/terminal/pty/lifecycle/terminal-owner' -import type { WriteSettlement } from '../../shared/terminal/pty/lifecycle/pty-write-settlement' - -export type { - PtyBackgroundStreamEvent, - PtyDataEvent, - PtyTransientFact -} from './pty-provider-events' - -export type PtyProviderBufferSnapshot = { - data: string - /** Live state that can be restored without an alternate-screen frame. */ - frameRestoreAnsi?: string - /** Authoritative normal buffer captured beside an alternate-screen frame. */ - scrollbackAnsi?: string - cols: number - rows: number - cwd?: string | null - lastTitle?: string - seq: number - source: 'headless' - oscLinks?: TerminalOscLinkRange[] - alternateScreen?: boolean - pendingEscapeTailAnsi?: string - /** Flags proven at this snapshot seq; absent is unknown, never zero. */ - kittyKeyboardFlags?: number - /** Ordered ownership evidence proven at this snapshot's `seq`. */ - terminalOwner?: TerminalOwner -} - -export type PtySpawnOptions = { - cols: number - rows: number - cwd?: string - /** Exact per-spawn cwd already proven by main; providers validate any other resolved path. */ - prevalidatedCwd?: string - env?: Record - envToDelete?: string[] - /** Main-validated home provenance for an automatic Codex session resume. */ - codexHomePathOverride?: { value: string | null } - command?: string - commandDelivery?: 'renderer' | 'provider' - startupCommandDelivery?: StartupCommandDelivery - /** Minimal allowlisted launch ownership preserved by daemon reattach. */ - launchAgent?: TuiAgent - /** Workspace identity also scopes local shell history. */ - worktreeId?: string - /** Stable pane metadata for remote routing even when it cannot be exported into the shell env. */ - paneKey?: string - /** Coarser attach guard when pane identity is unavailable. */ - tabId?: string - /** Caller IDs request attachment; hosts also mint fresh IDs for state needed before spawn returns. */ - sessionId?: string - /** Freshly minted session only; attaching a live PTY must not authorize daemon replacement. */ - isNewSession?: boolean - /** Host setting forwarded additively to the process owner; old owners ignore it. */ - historyIsolationEnabled?: boolean - /** SSH only: workspace the relay pre-trusts for `launchAgent` before spawning; old relays ignore it. */ - agentWorkspaceTrust?: AgentWorkspaceTrustSpawnRequest - /** Attach the named session atomically or fail without creating a process. */ - attachOnly?: boolean - /** Exact persisted owner expected by an attach-only routing decision. */ - expectedIncarnationId?: PtyIncarnationId - /** True when runtime state makes the expected incarnation a hard attach fence. */ - expectedIncarnationIsAuthoritative?: boolean - /** Windows-only per-tab shell selection without changing the persistent default. */ - shellOverride?: string - /** Optional Unix interactive profile args; ignored for command and agent launches. */ - terminalShellArgs?: string[] - /** Default WSL distro for generic wsl.exe; workspace/session cwd identity takes precedence. */ - terminalWindowsWslDistro?: string | null - /** Persisted inbox/pwsh choice keeps local and daemon PowerShell-family launches aligned. */ - terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' - /** Fresh-spawn-only source authority installed before any PTY output is released. */ - startupIngress?: PtyStartupIngressIntent - /** Why the caller is starting this terminal; presence lets the host defer an automatic restore. */ - spawnIntent?: SpawnIntent - /** A restore no user act asked for: a WSL bridge pane whose distro is stopped is held, not started. */ - wslPassiveRestore?: true - /** A main-side start no user act asked for (orchestration, automations, recovery): held like a passive restore. */ - wslBackgroundStart?: true - /** performance.now() before this spawn's startup-target hold read: the provider hold reuses only that read. */ - wslHoldReadAnchor?: number - agentSessionEnsure?: { - claim: AgentSessionExecutionClaim - surface: AgentSessionSurfaceBinding - } - /** Host-scoped structured-create identity used only for lower-owner replay. */ - agentSessionCreateOperationId?: string - /** Signals that the native process exists even if later publication fails. */ - onPtySpawnCommitted?: () => void - /** Cancels only before physical dispatch; operation identity fences later ambiguity. */ - signal?: AbortSignal -} - -export type { PtyProcessInfo, PtySpawnResult } - -type PtyProbeOptions = { signal?: AbortSignal } - -export type IPtyProvider = { - /** SSH providers only: the relay session generation that registered them. */ - readonly providerGeneration?: number - requestHostRpc?: ( - method: string, - params: unknown, - options?: { signal?: AbortSignal; timeoutMs?: number } - ) => Promise - /** Fresh local spawns currently route to an in-process, non-persistent fallback. */ - readonly routesFreshSpawnsToLocalProvider?: true - /** Re-probes a degraded durable host before main commits to fallback spawn semantics. */ - recoverFreshSpawnRouting?: () => Promise - spawn(opts: PtySpawnOptions): Promise - /** Process-owner cleanup for history stored outside the workspace tree. */ - deleteWorktreeHistory?: (worktreeId: string) => Promise - /** Whether this spawn target can append the Git guard after its final env merge. */ - supportsGitCredentialGuardHost?: (sessionId?: string) => boolean - /** Explicit false selects pre-claim legacy spawn for a preserved old daemon. */ - supportsAgentSessionClaims?: (options?: PtyProbeOptions) => boolean | Promise - /** Whether missing claim metadata in this PTY's process listing proves absence. */ - providesAgentSessionOwnerListings?: (ptyId: string) => boolean - supportsFencedTermination?: (id: string) => boolean - killFenced?: (request: PtyFencedTerminationRequest) => Promise - /** Whether fresh structured creates can replay one spawn across a lost relay response. */ - supportsAgentSessionCreateOperations?: (options?: PtyProbeOptions) => boolean | Promise - attach(id: string): Promise - hasPty?: (id: string) => boolean - /** Read-only input availability, including retained unattached PTYs; null means unobserved. */ - getPtyAvailability?: (id: string) => boolean | null - /** Exact provider readback: false only when the provider answered that the PTY is absent. */ - probePtyLiveness?: (id: string) => Promise - write(id: string, data: string): boolean | void - /** Durable claims require real write settlement; fire-and-forget providers must report inability to settle. */ - writeWithSettlement: (id: string, data: string) => WriteSettlement | Promise - resize(id: string, cols: number, rows: number): void - /** Best-effort kernel backpressure; unsupported/legacy providers omit or no-op, leaving output caps to bound memory. */ - pauseProducer?: (id: string) => void - resumeProducer?: (id: string) => void - /** Optional hidden-view hint allows keep-tail thinning so unwatched output cannot bury visible-pane echo. */ - setPtyBackgrounded?: (id: string, background: boolean) => void - /** Thinning transports preserve byte order for scan-authority markers, gaps and notification facts from dropped bytes. */ - onBackgroundStreamEvent?: (callback: (payload: PtyBackgroundStreamEvent) => void) => () => void - /** Endpoint-wide failure requires every affected PTY to remount/reattach; only respawnable providers emit it (STA-2373). */ - onWriteUnavailable?: (callback: (payload: { id: string }) => void) => () => void - /** Authoritative provider model snapshot after monitoring-stream gaps; optional for other providers. */ - getBufferSnapshot?: ( - id: string, - opts?: { scrollbackRows?: number } - ) => Promise - /** Whether this exact PTY can return a sequence-safe provider snapshot. */ - canProvideAuthoritativeBufferSnapshot?: (id: string) => boolean - /** Applied size readback detects dropped/clamped remote resize requests. - * Null means unconfirmed: callers re-forward once; providers without an authoritative source may omit this. */ - getAppliedSize?: (id: string) => Promise<{ cols: number; rows: number } | null> - /** Optional host capability used to suppress expensive legacy remote inventory polls. */ - supportsForegroundProcessEvidence?(options?: { signal?: AbortSignal }): Promise - - // Absolute deadlines bound leaf RPCs within the destructive sweep budget; each leaf converts to a relative timeout. - shutdown( - id: string, - opts: { - immediate?: boolean - keepHistory?: boolean - deadlineMs?: number - expectedIncarnationId?: PtyIncarnationId - /** Require the host-attested creator and current authenticated client to match before destructive ownership-based stops. - * Optional/ignored on older hosts; ordinary teardown and unattested revived PTYs may omit it. */ - expectedOwnerClientInstanceId?: string - } - ): Promise - sendSignal(id: string, signal: string): Promise - getCwd(id: string): Promise - getInitialCwd(id: string): Promise - clearBuffer(id: string): Promise - /** Grounds the host's own terminal models (Reset Terminal); renderers ground themselves. */ - resetInputModes(id: string): Promise - /** Sends ESC [ O to a ?1004 program once no viewer is left to blur; hosts that own no viewers omit it. */ - reportFocusLost?(id: string): Promise - /** Ends the startup Kitty-query window; OSC 10/11 authority stays with the owner for life. */ - closeStartupQueryAuthority?: (id: string) => Promise | number - /** Host-wide viewer colours the PTY owner answers OSC 10/11 from. */ - setColorQueryReplyColors?: (colors: TerminalOscColorQueryReplyColors) => void - acknowledgeDataEvent(id: string, charCount: number): void - hasChildProcesses(id: string): Promise - supportsForegroundObservation?(id: string): boolean - getForegroundProcess(id: string): Promise - /** Strong process evidence captured after the caller's command boundary. */ - confirmForegroundProcess?: (id: string) => Promise - /** Fresh execution-host proof that the spawned shell owns the PTY foreground. */ - confirmShellForeground?: (id: string) => Promise - /** Persist main's live launch where the PTY outlives main; only the daemon keeps one. */ - setLaunchNote?: (id: string, change: DaemonLaunchNoteChange) => void - serialize(ids: string[]): Promise - revive(state: string): Promise - listProcesses(opts?: { - deadlineMs?: number - includeForegroundProcessEvidence?: boolean - /** Scope route validation to this workspace; providers may return a broader inventory. */ - worktreeId?: string - /** Scope route validation to these PTYs; absence still requires a complete inventory. */ - ptyIds?: readonly string[] - /** Foreground proof only: read `ptyIds` from their established owner. Never exit proof or a census. */ - targetOwnerOnly?: boolean - /** Diagnostic display only: include generations whose routing owner is unverifiable. */ - includeUnrouted?: boolean - }): Promise - getDefaultShell(): Promise - getProfiles(): Promise<{ name: string; path: string }[]> - onData(callback: (payload: PtyDataEvent) => void): () => void - onReplay(callback: (payload: { id: string; data: string }) => void): () => void - onExit( - callback: (payload: { - id: string - code: number - incarnationId?: PtyIncarnationId - /** Absent when the provider predates exit causes; readers must not infer one from `code`. */ - cause?: TerminalExitCause - /** Main ended the session to restart the daemon; the pane stays for its next process. */ - replacedByRestart?: true - /** The session's host went away; its pane and history stay to cold-restore. */ - hostLost?: true - /** The emitting provider already reported this exit to the runtime through configure().onExit. */ - runtimeFed?: true - }) => void - ): () => void -} diff --git a/src/main/providers/pty-provider-events.ts b/src/main/providers/pty-provider-events.ts deleted file mode 100644 index c73a0262ee8..00000000000 --- a/src/main/providers/pty-provider-events.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { TerminalGitHubPRLink } from '../../shared/terminal/links/terminal-github-pr-link-detector' - -export type PtyDataEvent = { - id: string - data: string - sequenceChars?: number - transformed?: boolean - seq?: number - /** The emitting provider already fed this chunk to the runtime through configure().onData. */ - runtimeFed?: true -} - -/** Notification fact observed while the thinning transport owned scan authority for this PTY. */ -export type PtyTransientFact = - | { kind: 'bell' } - | { kind: 'command-finished'; exitCode: number | null } - | { kind: 'pr-link'; link: TerminalGitHubPRLink } - | { kind: '2031-subscribe' } - | { kind: '2031-unsubscribe' } - -export type PtyBackgroundStreamEvent = - | { - id: string - kind: 'backgroundMarker' - background: boolean - scanSeedAnsi?: string - mode2031PendingSubscribe?: true - } - | { id: string; kind: 'dataGap'; droppedChars: number; sequenceChars?: number } - | { id: string; kind: 'transientFact'; fact: PtyTransientFact } diff --git a/src/main/providers/pty-spawn-result.ts b/src/main/providers/pty-spawn-result.ts deleted file mode 100644 index ced9ec130a2..00000000000 --- a/src/main/providers/pty-spawn-result.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { DaemonLaunchNote } from '../daemon/protocol/daemon-launch-note-protocol' -import type { TerminalExitCause } from '../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import type { TerminalLaunchResult } from '../../shared/agent-session/lifecycle/agent-session-resume' -import type { TerminalOscLinkRange } from '../../shared/terminal/links/terminal-osc-link-ranges' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import type { AgentSessionClaimedSpawnResult } from '../../shared/agent-session/agent-session-host-authority' -import type { PtyIncarnationId } from '../../shared/terminal/pty/lifecycle/pty-incarnation' -import type { TerminalOwner } from '../../shared/terminal/pty/lifecycle/terminal-owner' -import type { OpenCodeCliCapabilities } from '../../shared/opencode-cli-version' - -export type PtySpawnResult = TerminalLaunchResult & { - /** Execution-host probe; absent on older hosts and reattachments. */ - openCodeCapabilities?: OpenCodeCliCapabilities - agentSessionEnsure?: AgentSessionClaimedSpawnResult - /** App-routable id; remote relay-local handles cannot route renderer/runtime IPC. */ - id: string - /** Opaque provider-owned identity for this process behind a reusable PTY id. */ - incarnationId?: PtyIncarnationId - /** The provider observed this exact spawn exit before returning its spawn result. */ - exitedBeforeSpawnReply?: true - /** Observed cause for this exact early-dead process. */ - exitCause?: TerminalExitCause - /** Host marker proof: false means inspected/unarmed; absent means legacy and retains the client guess. */ - shellReadyArmed?: boolean - /** OS shell PID for subtree memory collection; null when the host cannot publish one during spawn. */ - pid?: number | null - /** Minimal allowlisted launch ownership returned by daemon reattach. */ - launchAgent?: TuiAgent - /** The unretired launch main armed before a restart, returned by daemon reattach. */ - launchNote?: DaemonLaunchNote | null - /** Local WSL context: null is native; undefined is unavailable/legacy. */ - wslDistro?: string | null - /** Daemon reattach ANSI screen restore for xterm. */ - snapshot?: string - /** Restore xterm size before snapshot replay so cursor coordinates match. */ - snapshotCols?: number - snapshotRows?: number - /** Normal-buffer history and mode preamble before an alternate-screen frame. */ - snapshotPrefixAnsi?: string - /** Visual alternate-screen frame, separate so newer clients can omit it safely. */ - snapshotFrameAnsi?: string - /** Live state to append when omitting `snapshotFrameAnsi`. */ - snapshotFrameRestoreAnsi?: string - /** Attach sequence domain: reset begins a new provider generation; continued retains the absolute domain. */ - providerSequence?: { - value: number - generation: 'continued' | 'reset' - } - /** Snapshot kitty flags seed hidden runtime query replies; renderers reassert after replay screen switches. */ - snapshotKittyKeyboardFlags?: number - /** Main-reconciled renderer sequence for the flags attach boundary; providers cannot set this. */ - snapshotSeq?: number - /** Ordered ownership evidence proven by the provider snapshot. */ - snapshotTerminalOwner?: TerminalOwner - /** Fresh-spawn cwd provenance only; in-process and never sent over the wire. */ - startupCwdSource?: 'request' | 'recovered-history' - isReattach?: boolean - /** Measured post-attach grid only; daemon/relay leave size unchanged and must not echo requested dimensions. */ - attachedGrid?: { cols: number; rows: number } - /** Daemon OSC title seeds main records after relaunch; never replay as terminal bytes. */ - lastTitle?: string - isAlternateScreen?: boolean - /** Incremental relay replay; unlike snapshot, must not clear the terminal before writing. */ - replay?: string - /** Requested session expired before reattach; renderer reports that a new shell started. */ - sessionExpired?: boolean - /** Crash-history restore: spawn in saved cwd and replay scrollback as read-only history. */ - coldRestore?: { - scrollback: string - cwd: string - /** Optional for compatibility with restore payloads from older app code. */ - cols?: number - rows?: number - oscLinks?: TerminalOscLinkRange[] - } -} diff --git a/src/main/providers/pty/events.ts b/src/main/providers/pty/events.ts new file mode 100644 index 00000000000..b918e3fae29 --- /dev/null +++ b/src/main/providers/pty/events.ts @@ -0,0 +1,30 @@ +import type { TerminalGitHubPRLink } from '../../../shared/terminal/links/terminal-github-pr-link-detector' + +export type PtyDataEvent = { + id: string + data: string + sequenceChars?: number + transformed?: boolean + seq?: number + /** The emitting provider already fed this chunk to the runtime through configure().onData. */ + runtimeFed?: true +} + +/** Notification fact observed while the thinning transport owned scan authority for this PTY. */ +export type PtyTransientFact = + | { kind: 'bell' } + | { kind: 'command-finished'; exitCode: number | null } + | { kind: 'pr-link'; link: TerminalGitHubPRLink } + | { kind: '2031-subscribe' } + | { kind: '2031-unsubscribe' } + +export type PtyBackgroundStreamEvent = + | { + id: string + kind: 'backgroundMarker' + background: boolean + scanSeedAnsi?: string + mode2031PendingSubscribe?: true + } + | { id: string; kind: 'dataGap'; droppedChars: number; sequenceChars?: number } + | { id: string; kind: 'transientFact'; fact: PtyTransientFact } diff --git a/src/main/providers/node-pty-load-failure.ts b/src/main/providers/pty/node-pty-load-failure.ts similarity index 100% rename from src/main/providers/node-pty-load-failure.ts rename to src/main/providers/pty/node-pty-load-failure.ts diff --git a/src/main/providers/pty/process-info.ts b/src/main/providers/pty/process-info.ts new file mode 100644 index 00000000000..77cf223a9f7 --- /dev/null +++ b/src/main/providers/pty/process-info.ts @@ -0,0 +1,40 @@ +import type { AgentSessionOwnerBinding } from '../../../shared/agent-session/agent-session-host-authority' +import type { PtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation' +import type { ForegroundProcessEvidence } from '../../../shared/foreground-process-evidence' +import type { WslGuestRoot } from '../../../shared/wsl-guest-root-marker' + +export type PtyProcessInfo = { + id: string + incarnationId?: PtyIncarnationId + /** Local diagnostic provenance supplied by a multi-daemon router. */ + inventorySourceId?: string + /** Whether this diagnostic candidate is the established route for its id. */ + routed?: boolean + /** Root process owned by this exact PTY incarnation, when the provider can prove it. */ + rootProcessId?: number + /** Recently observed process name; inventory reads never initiate process inspection. */ + foregroundProcess?: string + cwd: string + title: string + /** Owning worktree when the provider can report it authoritatively. */ + worktreeId?: string + /** Trusted ORCA_TERMINAL_HANDLE exported into this PTY, when known. */ + terminalHandle?: string + /** ORCA_PANE_KEY this PTY was spawned with, when the provider recorded it. */ + paneKey?: string + /** Exact WSL owner reported by the PTY provider; null means native Windows. */ + wslDistro?: string | null + /** A live WSL PTY's guest root shell, seen once at its launch; absent from older owners. */ + wslGuestRoot?: WslGuestRoot + /** Optional host-side process evidence attached to an inventory seed. */ + foregroundProcessEvidence?: ForegroundProcessEvidence + agentSessionOwners?: AgentSessionOwnerBinding[] + /** Owning-host clock age; absent is unmeasured, so age-dependent decisions must defer. */ + hostAgeMs?: number + /** Host attests Orca pane (true) or bare shell (false); absent is unknown on older hosts. */ + paneBound?: boolean + /** Creator identity attested by the owning host; absent never means unowned. */ + ownerClientInstanceId?: string + /** Still live during accepted termination, but cannot be adopted/restored; absent on older hosts. */ + exiting?: true +} diff --git a/src/main/providers/pty/process-inspection.ts b/src/main/providers/pty/process-inspection.ts new file mode 100644 index 00000000000..3bdd4649c2f --- /dev/null +++ b/src/main/providers/pty/process-inspection.ts @@ -0,0 +1,64 @@ +import type { IPtyProvider } from './provider-contract' +import type { PtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation' +import { + classifyTerminalProcessInspectionFailure, + clientOnlyUnverifiableInspection, + type TerminalProcessInspection as PtyProcessInspection +} from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' + +type CompletionSensitivePtyProvider = IPtyProvider & { + inspectProcess?: ( + id: string, + options?: PtyProcessInspectionOptions + ) => Promise +} + +/** scanChildProcesses requests decision-time evidence; steady polls may rely on the next tick to correct stale reads. */ +export type PtyProcessInspectionOptions = { + foregroundOnly?: boolean + expectedIncarnationId?: PtyIncarnationId + scanChildProcesses?: boolean + /** Adoption only: ignore members outside both shell ancestry and console; close still reaches the whole job. */ + ignoreDetached?: boolean + /** Name-only cadence polls may use cheap captures and omit evidence; evidence consumers must never set this. */ + steadyState?: boolean + /** Also reach a session the daemon still runs that no window has reattached since a relaunch. + * The WSL move gate and the cleanup runner, which must see what teardown would stop; others read it as gone. */ + includeUnattached?: boolean +} + +export async function inspectPtyProviderProcess( + provider: IPtyProvider, + ptyId: string, + options?: PtyProcessInspectionOptions +): Promise { + // The daemon's own inspect still refuses a session it no longer runs. + if (options?.includeUnattached !== true && provider.hasPty?.(ptyId) === false) { + throw new Error('terminal_gone') + } + const inspectProcess = (provider as CompletionSensitivePtyProvider).inspectProcess + if (inspectProcess) { + return options + ? inspectProcess.call(provider, ptyId, options) + : inspectProcess.call(provider, ptyId) + } + const foregroundProcess = await provider.getForegroundProcess(ptyId) + const hasChildProcesses = await provider.hasChildProcesses(ptyId) + return { foregroundProcess, hasChildProcesses } +} + +export async function inspectPtyProviderProcessForRenderer( + provider: IPtyProvider, + ptyId: string, + options?: PtyProcessInspectionOptions +): Promise { + try { + return await inspectPtyProviderProcess(provider, ptyId, options) + } catch (error) { + const reason = classifyTerminalProcessInspectionFailure(error) + if (reason) { + return clientOnlyUnverifiableInspection(reason) + } + throw error + } +} diff --git a/src/main/providers/pty/process-list-admission.ts b/src/main/providers/pty/process-list-admission.ts new file mode 100644 index 00000000000..a8f2f5deeb8 --- /dev/null +++ b/src/main/providers/pty/process-list-admission.ts @@ -0,0 +1,193 @@ +import { isAgentSessionOwnerBinding } from '../../../shared/agent-session/agent-session-host-authority' +import { MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES } from '../../../shared/claimed-agent-pty-owner' +import { cloneAgentSessionOwnerBinding } from '../../../shared/claimed-agent-pty-owner-snapshot' +import { isPtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation' +import { + cloneForegroundProcessEvidence, + isForegroundProcessEvidence +} from '../../../shared/foreground-process-evidence' +import type { PtyProcessInfo } from './process-info' +import { readWslGuestRoot } from '../../../shared/wsl-guest-root-marker' + +export const MAX_AGGREGATED_PTY_PROCESS_LIST_ENTRIES = 4096 +export const MAX_AGGREGATED_PTY_PROCESS_LIST_BYTES = 32 * 1024 * 1024 +const MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS = MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES +export const PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE = 4 + +function retainedStringBytes(value: unknown): number | null { + return typeof value === 'string' ? Buffer.byteLength(value, 'utf8') : null +} + +function retainedOptionalStringBytes(value: unknown): number | null { + return value === undefined ? 0 : retainedStringBytes(value) +} + +function retainedOwnerBytes(owner: unknown, ptyId: string): number | null { + if (!isAgentSessionOwnerBinding(owner) || owner.phase !== 'live' || owner.ptyId !== ptyId) { + return null + } + return [ + owner.claim.keyId, + owner.claim.identityDigest, + owner.claim.worktreeScopeDigest, + owner.claim.agent, + owner.generation, + owner.ptyId, + owner.surface.worktreeId, + owner.surface.tabId, + owner.surface.leafId, + owner.surface.terminalHandle + ].reduce((total, value) => total + Buffer.byteLength(value, 'utf8'), 0) +} + +export class PtyProcessListAdmission { + private entries = 0 + private retainedBytes = 0 + private owners = 0 + + constructor(private readonly capacityError = 'pty_process_list_capacity') {} + + admit(value: PtyProcessInfo): PtyProcessInfo { + if (typeof value !== 'object' || value === null) { + throw new Error('invalid_pty_process_list') + } + const idBytes = retainedStringBytes(value.id) + const cwdBytes = retainedStringBytes(value.cwd) + const titleBytes = retainedStringBytes(value.title) + const foregroundProcessBytes = retainedOptionalStringBytes(value.foregroundProcess) + const inventorySourceBytes = retainedOptionalStringBytes(value.inventorySourceId) + const worktreeIdBytes = retainedOptionalStringBytes(value.worktreeId) + const terminalHandleBytes = retainedOptionalStringBytes(value.terminalHandle) + const paneKeyBytes = retainedOptionalStringBytes(value.paneKey) + const wslDistroBytes = + value.wslDistro === null ? 0 : retainedOptionalStringBytes(value.wslDistro) + const wslGuestRoot = readWslGuestRoot(value.wslGuestRoot) + const evidenceBytes = + value.foregroundProcessEvidence === undefined + ? 0 + : isForegroundProcessEvidence(value.foregroundProcessEvidence) + ? Buffer.byteLength(JSON.stringify(value.foregroundProcessEvidence), 'utf8') + : null + if ( + idBytes === null || + cwdBytes === null || + titleBytes === null || + foregroundProcessBytes === null || + inventorySourceBytes === null || + (value.routed !== undefined && typeof value.routed !== 'boolean') || + worktreeIdBytes === null || + terminalHandleBytes === null || + paneKeyBytes === null || + wslDistroBytes === null || + evidenceBytes === null || + (value.wslGuestRoot !== undefined && !wslGuestRoot) || + (value.rootProcessId !== undefined && + (!Number.isSafeInteger(value.rootProcessId) || value.rootProcessId <= 0)) || + (value.incarnationId !== undefined && !isPtyIncarnationId(value.incarnationId)) || + (value.agentSessionOwners !== undefined && !Array.isArray(value.agentSessionOwners)) + ) { + throw new Error('invalid_pty_process_list') + } + if ( + (value.agentSessionOwners?.length ?? 0) > + MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS - this.owners + ) { + throw new Error(this.capacityError) + } + + let ownerBytes = 0 + const normalizedOwners = value.agentSessionOwners?.map((owner) => { + const bytes = retainedOwnerBytes(owner, value.id) + if (bytes === null) { + throw new Error('agent_session_ownership_unknown') + } + ownerBytes += bytes + return cloneAgentSessionOwnerBinding(owner) + }) + const nextEntries = this.entries + 1 + const nextOwners = this.owners + (normalizedOwners?.length ?? 0) + const nextBytes = + this.retainedBytes + + idBytes + + cwdBytes + + titleBytes + + foregroundProcessBytes + + inventorySourceBytes + + worktreeIdBytes + + terminalHandleBytes + + paneKeyBytes + + wslDistroBytes + + evidenceBytes + + (wslGuestRoot?.startTime.length ?? 0) + + ownerBytes + if ( + nextEntries > MAX_AGGREGATED_PTY_PROCESS_LIST_ENTRIES || + nextOwners > MAX_AGGREGATED_PTY_PROCESS_LIST_OWNERS || + nextBytes > MAX_AGGREGATED_PTY_PROCESS_LIST_BYTES + ) { + throw new Error(this.capacityError) + } + this.entries = nextEntries + this.owners = nextOwners + this.retainedBytes = nextBytes + + return { + id: value.id, + cwd: value.cwd, + title: value.title, + ...(value.inventorySourceId !== undefined + ? { inventorySourceId: value.inventorySourceId } + : {}), + ...(value.routed !== undefined ? { routed: value.routed } : {}), + ...(value.foregroundProcess !== undefined + ? { foregroundProcess: value.foregroundProcess } + : {}), + ...(value.incarnationId !== undefined ? { incarnationId: value.incarnationId } : {}), + ...(value.rootProcessId !== undefined ? { rootProcessId: value.rootProcessId } : {}), + ...(value.worktreeId !== undefined ? { worktreeId: value.worktreeId } : {}), + ...(value.terminalHandle !== undefined ? { terminalHandle: value.terminalHandle } : {}), + ...(value.paneKey !== undefined ? { paneKey: value.paneKey } : {}), + ...(value.wslDistro !== undefined ? { wslDistro: value.wslDistro } : {}), + ...(wslGuestRoot ? { wslGuestRoot } : {}), + ...(value.exiting === true ? { exiting: true as const } : {}), + ...(value.foregroundProcessEvidence !== undefined + ? { + foregroundProcessEvidence: cloneForegroundProcessEvidence( + value.foregroundProcessEvidence + ) + } + : {}), + ...(normalizedOwners !== undefined ? { agentSessionOwners: normalizedOwners } : {}) + } + } +} + +export async function visitPtyProcessListingsInBatches( + sources: Iterable, + load: (source: T) => Promise, + visit: (source: T, processes: readonly PtyProcessInfo[]) => void +): Promise { + let batch: T[] = [] + for (const source of sources) { + batch.push(source) + if (batch.length < PTY_PROCESS_LIST_PROVIDER_BATCH_SIZE) { + continue + } + const listings = await Promise.all( + batch.map(async (entry) => ({ entry, processes: await load(entry) })) + ) + for (const listing of listings) { + visit(listing.entry, listing.processes) + } + batch = [] + } + if (batch.length === 0) { + return + } + const listings = await Promise.all( + batch.map(async (entry) => ({ entry, processes: await load(entry) })) + ) + for (const listing of listings) { + visit(listing.entry, listing.processes) + } +} diff --git a/src/main/providers/pty/provider-contract.ts b/src/main/providers/pty/provider-contract.ts new file mode 100644 index 00000000000..19510b49323 --- /dev/null +++ b/src/main/providers/pty/provider-contract.ts @@ -0,0 +1,238 @@ +import type { DaemonLaunchNoteChange } from '../../daemon/protocol/daemon-launch-note-protocol' +import type { + PtyFencedTerminationRequest, + PtyFencedTerminationOutcome +} from '../../../shared/terminal/pty/lifecycle/pty-fenced-termination' +import type { SpawnIntent } from '../../../shared/terminal/pty/admission/spawn-admission-contract' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import type { AgentWorkspaceTrustSpawnRequest } from '../../../shared/agent-launch/permissions/agent-workspace-trust-spawn-request' +import type { PtyStartupIngressIntent } from '../../../shared/terminal/pty/ingress/pty-startup-ingress-intent' +import type { TerminalOscColorQueryReplyColors } from '../../../shared/terminal/protocol/queries/terminal-osc-color-reply' +import type { StartupCommandDelivery } from '../../../shared/agent-launch/startup/codex-startup-delivery' +import type { TerminalOscLinkRange } from '../../../shared/terminal/links/terminal-osc-link-ranges' +import type { PtyBackgroundStreamEvent, PtyDataEvent } from './events' +import type { PtySpawnResult } from './spawn-result' +import type { PtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation' +import type { + AgentSessionExecutionClaim, + AgentSessionSurfaceBinding +} from '../../../shared/agent-session/agent-session-host-authority' +import type { PtyProcessInfo } from './process-info' +import type { TerminalExitCause } from '../../../shared/terminal/pty/lifecycle/terminal-exit-cause' +import type { TerminalOwner } from '../../../shared/terminal/pty/lifecycle/terminal-owner' +import type { WriteSettlement } from '../../../shared/terminal/pty/lifecycle/pty-write-settlement' + +export type PtyProviderBufferSnapshot = { + data: string + /** Live state that can be restored without an alternate-screen frame. */ + frameRestoreAnsi?: string + /** Authoritative normal buffer captured beside an alternate-screen frame. */ + scrollbackAnsi?: string + cols: number + rows: number + cwd?: string | null + lastTitle?: string + seq: number + source: 'headless' + oscLinks?: TerminalOscLinkRange[] + alternateScreen?: boolean + pendingEscapeTailAnsi?: string + /** Flags proven at this snapshot seq; absent is unknown, never zero. */ + kittyKeyboardFlags?: number + /** Ordered ownership evidence proven at this snapshot's `seq`. */ + terminalOwner?: TerminalOwner +} + +export type PtySpawnOptions = { + cols: number + rows: number + cwd?: string + /** Exact per-spawn cwd already proven by main; providers validate any other resolved path. */ + prevalidatedCwd?: string + env?: Record + envToDelete?: string[] + /** Main-validated home provenance for an automatic Codex session resume. */ + codexHomePathOverride?: { value: string | null } + command?: string + commandDelivery?: 'renderer' | 'provider' + startupCommandDelivery?: StartupCommandDelivery + /** Minimal allowlisted launch ownership preserved by daemon reattach. */ + launchAgent?: TuiAgent + /** Workspace identity also scopes local shell history. */ + worktreeId?: string + /** Stable pane metadata for remote routing even when it cannot be exported into the shell env. */ + paneKey?: string + /** Coarser attach guard when pane identity is unavailable. */ + tabId?: string + /** Caller IDs request attachment; hosts also mint fresh IDs for state needed before spawn returns. */ + sessionId?: string + /** Freshly minted session only; attaching a live PTY must not authorize daemon replacement. */ + isNewSession?: boolean + /** Host setting forwarded additively to the process owner; old owners ignore it. */ + historyIsolationEnabled?: boolean + /** SSH only: workspace the relay pre-trusts for `launchAgent` before spawning; old relays ignore it. */ + agentWorkspaceTrust?: AgentWorkspaceTrustSpawnRequest + /** Attach the named session atomically or fail without creating a process. */ + attachOnly?: boolean + /** Exact persisted owner expected by an attach-only routing decision. */ + expectedIncarnationId?: PtyIncarnationId + /** True when runtime state makes the expected incarnation a hard attach fence. */ + expectedIncarnationIsAuthoritative?: boolean + /** Windows-only per-tab shell selection without changing the persistent default. */ + shellOverride?: string + /** Optional Unix interactive profile args; ignored for command and agent launches. */ + terminalShellArgs?: string[] + /** Default WSL distro for generic wsl.exe; workspace/session cwd identity takes precedence. */ + terminalWindowsWslDistro?: string | null + /** Persisted inbox/pwsh choice keeps local and daemon PowerShell-family launches aligned. */ + terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' + /** Fresh-spawn-only source authority installed before any PTY output is released. */ + startupIngress?: PtyStartupIngressIntent + /** Why the caller is starting this terminal; presence lets the host defer an automatic restore. */ + spawnIntent?: SpawnIntent + /** A restore no user act asked for: a WSL bridge pane whose distro is stopped is held, not started. */ + wslPassiveRestore?: true + /** A main-side start no user act asked for (orchestration, automations, recovery): held like a passive restore. */ + wslBackgroundStart?: true + /** performance.now() before this spawn's startup-target hold read: the provider hold reuses only that read. */ + wslHoldReadAnchor?: number + agentSessionEnsure?: { + claim: AgentSessionExecutionClaim + surface: AgentSessionSurfaceBinding + } + /** Host-scoped structured-create identity used only for lower-owner replay. */ + agentSessionCreateOperationId?: string + /** Signals that the native process exists even if later publication fails. */ + onPtySpawnCommitted?: () => void + /** Cancels only before physical dispatch; operation identity fences later ambiguity. */ + signal?: AbortSignal +} + +type PtyProbeOptions = { signal?: AbortSignal } + +export type IPtyProvider = { + /** SSH providers only: the relay session generation that registered them. */ + readonly providerGeneration?: number + requestHostRpc?: ( + method: string, + params: unknown, + options?: { signal?: AbortSignal; timeoutMs?: number } + ) => Promise + /** Fresh local spawns currently route to an in-process, non-persistent fallback. */ + readonly routesFreshSpawnsToLocalProvider?: true + /** Re-probes a degraded durable host before main commits to fallback spawn semantics. */ + recoverFreshSpawnRouting?: () => Promise + spawn(opts: PtySpawnOptions): Promise + /** Process-owner cleanup for history stored outside the workspace tree. */ + deleteWorktreeHistory?: (worktreeId: string) => Promise + /** Whether this spawn target can append the Git guard after its final env merge. */ + supportsGitCredentialGuardHost?: (sessionId?: string) => boolean + /** Explicit false selects pre-claim legacy spawn for a preserved old daemon. */ + supportsAgentSessionClaims?: (options?: PtyProbeOptions) => boolean | Promise + /** Whether missing claim metadata in this PTY's process listing proves absence. */ + providesAgentSessionOwnerListings?: (ptyId: string) => boolean + supportsFencedTermination?: (id: string) => boolean + killFenced?: (request: PtyFencedTerminationRequest) => Promise + /** Whether fresh structured creates can replay one spawn across a lost relay response. */ + supportsAgentSessionCreateOperations?: (options?: PtyProbeOptions) => boolean | Promise + attach(id: string): Promise + hasPty?: (id: string) => boolean + /** Read-only input availability, including retained unattached PTYs; null means unobserved. */ + getPtyAvailability?: (id: string) => boolean | null + /** Exact provider readback: false only when the provider answered that the PTY is absent. */ + probePtyLiveness?: (id: string) => Promise + write(id: string, data: string): boolean | void + /** Durable claims require real write settlement; fire-and-forget providers must report inability to settle. */ + writeWithSettlement: (id: string, data: string) => WriteSettlement | Promise + resize(id: string, cols: number, rows: number): void + /** Best-effort kernel backpressure; unsupported/legacy providers omit or no-op, leaving output caps to bound memory. */ + pauseProducer?: (id: string) => void + resumeProducer?: (id: string) => void + /** Optional hidden-view hint allows keep-tail thinning so unwatched output cannot bury visible-pane echo. */ + setPtyBackgrounded?: (id: string, background: boolean) => void + /** Thinning transports preserve byte order for scan-authority markers, gaps and notification facts from dropped bytes. */ + onBackgroundStreamEvent?: (callback: (payload: PtyBackgroundStreamEvent) => void) => () => void + /** Endpoint-wide failure requires every affected PTY to remount/reattach; only respawnable providers emit it (STA-2373). */ + onWriteUnavailable?: (callback: (payload: { id: string }) => void) => () => void + /** Authoritative provider model snapshot after monitoring-stream gaps; optional for other providers. */ + getBufferSnapshot?: ( + id: string, + opts?: { scrollbackRows?: number } + ) => Promise + /** Whether this exact PTY can return a sequence-safe provider snapshot. */ + canProvideAuthoritativeBufferSnapshot?: (id: string) => boolean + /** Applied size readback detects dropped/clamped remote resize requests. + * Null means unconfirmed: callers re-forward once; providers without an authoritative source may omit this. */ + getAppliedSize?: (id: string) => Promise<{ cols: number; rows: number } | null> + /** Optional host capability used to suppress expensive legacy remote inventory polls. */ + supportsForegroundProcessEvidence?(options?: { signal?: AbortSignal }): Promise + + // Absolute deadlines bound leaf RPCs within the destructive sweep budget; each leaf converts to a relative timeout. + shutdown( + id: string, + opts: { + immediate?: boolean + keepHistory?: boolean + deadlineMs?: number + expectedIncarnationId?: PtyIncarnationId + /** Require the host-attested creator and current authenticated client to match before destructive ownership-based stops. + * Optional/ignored on older hosts; ordinary teardown and unattested revived PTYs may omit it. */ + expectedOwnerClientInstanceId?: string + } + ): Promise + sendSignal(id: string, signal: string): Promise + getCwd(id: string): Promise + getInitialCwd(id: string): Promise + clearBuffer(id: string): Promise + /** Grounds the host's own terminal models (Reset Terminal); renderers ground themselves. */ + resetInputModes(id: string): Promise + /** Sends ESC [ O to a ?1004 program once no viewer is left to blur; hosts that own no viewers omit it. */ + reportFocusLost?(id: string): Promise + /** Ends the startup Kitty-query window; OSC 10/11 authority stays with the owner for life. */ + closeStartupQueryAuthority?: (id: string) => Promise | number + /** Host-wide viewer colours the PTY owner answers OSC 10/11 from. */ + setColorQueryReplyColors?: (colors: TerminalOscColorQueryReplyColors) => void + acknowledgeDataEvent(id: string, charCount: number): void + hasChildProcesses(id: string): Promise + supportsForegroundObservation?(id: string): boolean + getForegroundProcess(id: string): Promise + /** Strong process evidence captured after the caller's command boundary. */ + confirmForegroundProcess?: (id: string) => Promise + /** Fresh execution-host proof that the spawned shell owns the PTY foreground. */ + confirmShellForeground?: (id: string) => Promise + /** Persist main's live launch where the PTY outlives main; only the daemon keeps one. */ + setLaunchNote?: (id: string, change: DaemonLaunchNoteChange) => void + serialize(ids: string[]): Promise + revive(state: string): Promise + listProcesses(opts?: { + deadlineMs?: number + includeForegroundProcessEvidence?: boolean + /** Scope route validation to this workspace; providers may return a broader inventory. */ + worktreeId?: string + /** Scope route validation to these PTYs; absence still requires a complete inventory. */ + ptyIds?: readonly string[] + /** Foreground proof only: read `ptyIds` from their established owner. Never exit proof or a census. */ + targetOwnerOnly?: boolean + /** Diagnostic display only: include generations whose routing owner is unverifiable. */ + includeUnrouted?: boolean + }): Promise + getDefaultShell(): Promise + getProfiles(): Promise<{ name: string; path: string }[]> + onData(callback: (payload: PtyDataEvent) => void): () => void + onReplay(callback: (payload: { id: string; data: string }) => void): () => void + onExit( + callback: (payload: { + id: string + code: number + incarnationId?: PtyIncarnationId + /** Absent when the provider predates exit causes; readers must not infer one from `code`. */ + cause?: TerminalExitCause + /** Main ended the session to restart the daemon; the pane stays for its next process. */ + replacedByRestart?: true + /** The session's host went away; its pane and history stay to cold-restore. */ + hostLost?: true + /** The emitting provider already reported this exit to the runtime through configure().onExit. */ + runtimeFed?: true + }) => void + ): () => void +} diff --git a/src/main/providers/pty/spawn-result.ts b/src/main/providers/pty/spawn-result.ts new file mode 100644 index 00000000000..7326b8a10dd --- /dev/null +++ b/src/main/providers/pty/spawn-result.ts @@ -0,0 +1,76 @@ +import type { DaemonLaunchNote } from '../../daemon/protocol/daemon-launch-note-protocol' +import type { TerminalExitCause } from '../../../shared/terminal/pty/lifecycle/terminal-exit-cause' +import type { TerminalLaunchResult } from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { TerminalOscLinkRange } from '../../../shared/terminal/links/terminal-osc-link-ranges' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import type { AgentSessionClaimedSpawnResult } from '../../../shared/agent-session/agent-session-host-authority' +import type { PtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation' +import type { TerminalOwner } from '../../../shared/terminal/pty/lifecycle/terminal-owner' +import type { OpenCodeCliCapabilities } from '../../../shared/opencode-cli-version' + +export type PtySpawnResult = TerminalLaunchResult & { + /** Execution-host probe; absent on older hosts and reattachments. */ + openCodeCapabilities?: OpenCodeCliCapabilities + agentSessionEnsure?: AgentSessionClaimedSpawnResult + /** App-routable id; remote relay-local handles cannot route renderer/runtime IPC. */ + id: string + /** Opaque provider-owned identity for this process behind a reusable PTY id. */ + incarnationId?: PtyIncarnationId + /** The provider observed this exact spawn exit before returning its spawn result. */ + exitedBeforeSpawnReply?: true + /** Observed cause for this exact early-dead process. */ + exitCause?: TerminalExitCause + /** Host marker proof: false means inspected/unarmed; absent means legacy and retains the client guess. */ + shellReadyArmed?: boolean + /** OS shell PID for subtree memory collection; null when the host cannot publish one during spawn. */ + pid?: number | null + /** Minimal allowlisted launch ownership returned by daemon reattach. */ + launchAgent?: TuiAgent + /** The unretired launch main armed before a restart, returned by daemon reattach. */ + launchNote?: DaemonLaunchNote | null + /** Local WSL context: null is native; undefined is unavailable/legacy. */ + wslDistro?: string | null + /** Daemon reattach ANSI screen restore for xterm. */ + snapshot?: string + /** Restore xterm size before snapshot replay so cursor coordinates match. */ + snapshotCols?: number + snapshotRows?: number + /** Normal-buffer history and mode preamble before an alternate-screen frame. */ + snapshotPrefixAnsi?: string + /** Visual alternate-screen frame, separate so newer clients can omit it safely. */ + snapshotFrameAnsi?: string + /** Live state to append when omitting `snapshotFrameAnsi`. */ + snapshotFrameRestoreAnsi?: string + /** Attach sequence domain: reset begins a new provider generation; continued retains the absolute domain. */ + providerSequence?: { + value: number + generation: 'continued' | 'reset' + } + /** Snapshot kitty flags seed hidden runtime query replies; renderers reassert after replay screen switches. */ + snapshotKittyKeyboardFlags?: number + /** Main-reconciled renderer sequence for the flags attach boundary; providers cannot set this. */ + snapshotSeq?: number + /** Ordered ownership evidence proven by the provider snapshot. */ + snapshotTerminalOwner?: TerminalOwner + /** Fresh-spawn cwd provenance only; in-process and never sent over the wire. */ + startupCwdSource?: 'request' | 'recovered-history' + isReattach?: boolean + /** Measured post-attach grid only; daemon/relay leave size unchanged and must not echo requested dimensions. */ + attachedGrid?: { cols: number; rows: number } + /** Daemon OSC title seeds main records after relaunch; never replay as terminal bytes. */ + lastTitle?: string + isAlternateScreen?: boolean + /** Incremental relay replay; unlike snapshot, must not clear the terminal before writing. */ + replay?: string + /** Requested session expired before reattach; renderer reports that a new shell started. */ + sessionExpired?: boolean + /** Crash-history restore: spawn in saved cwd and replay scrollback as read-only history. */ + coldRestore?: { + scrollback: string + cwd: string + /** Optional for compatibility with restore payloads from older app code. */ + cols?: number + rows?: number + oscLinks?: TerminalOscLinkRange[] + } +} diff --git a/src/main/providers/pty/worktree-ownership.ts b/src/main/providers/pty/worktree-ownership.ts new file mode 100644 index 00000000000..ce2b4e1a972 --- /dev/null +++ b/src/main/providers/pty/worktree-ownership.ts @@ -0,0 +1,21 @@ +import { isPathInsideOrEqual } from '../../../shared/cross-platform-path' +import { splitWorktreeId, splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' +import type { PtyProcessInfo } from './process-info' + +export function worktreePtyOwnership(worktreeId: string): (session: PtyProcessInfo) => boolean { + const prefix = `${worktreeId}@@` + const fullWorktreePath = splitWorktreeId(worktreeId)?.worktreePath + // Folder instances share a checkout; cwd alone cannot identify the owning instance. + const cwdFallbackPath = + splitWorktreeIdForFilesystem(worktreeId)?.worktreePath === fullWorktreePath + ? fullWorktreePath + : undefined + return (session) => + session.id.startsWith(prefix) || + session.worktreeId === worktreeId || + (cwdFallbackPath !== undefined && + session.worktreeId === undefined && + typeof session.cwd === 'string' && + session.cwd.length > 0 && + isPathInsideOrEqual(cwdFallbackPath, session.cwd)) +} diff --git a/src/main/providers/pty-write-unavailable-error.ts b/src/main/providers/pty/write-unavailable-error.ts similarity index 100% rename from src/main/providers/pty-write-unavailable-error.ts rename to src/main/providers/pty/write-unavailable-error.ts diff --git a/src/main/providers/shell-launch/macos/login-session-pty-probe.ts b/src/main/providers/shell-launch/macos/login-session-pty-probe.ts new file mode 100644 index 00000000000..dc34d58de91 --- /dev/null +++ b/src/main/providers/shell-launch/macos/login-session-pty-probe.ts @@ -0,0 +1,57 @@ +import { runProcess } from '@orca/process-host' +import { existsSync } from 'node:fs' + +const MACOS_EXPECT_PATH = '/usr/bin/expect' +const LOGIN_PREFLIGHT_MARKER = 'ORCA_LOGIN_PREFLIGHT_OK' +const LOGIN_PROBE_USERNAME_ENV = 'ORCA_LOGIN_PROBE_USERNAME' +// expect owns the probe PTY without leaving a long-lived native handle in the daemon. +// login(1) ignores a closed PTY's SIGHUP, so expect kills it on runProcess's SIGTERM (#30806). +// Trap only after spawn: before it, exp_pid is 0 and would signal our whole process group. +const EXPECT_LOGIN_PROBE_SCRIPT = + 'log_user 1; ' + + 'spawn -noecho /usr/bin/login -flpq $env(ORCA_LOGIN_PROBE_USERNAME) /usr/bin/printf ORCA_LOGIN_PREFLIGHT_OK; ' + + 'trap {catch {exec /bin/kill -KILL [exp_pid]}; exit 1} SIGTERM; ' + + 'send "\\004"; expect eof; wait; exit 0' + +export type LoginPreflightOutcome = { + ok: boolean + conclusive: boolean + reason: 'accepted' | 'rejected' | 'timeout' | 'error' +} + +/** Runs the login-session oracle under a real PTY when the pipe probe cannot decide. */ +export async function runMacosLoginSessionPtyProbe( + username: string, + accountHome: string, + timeoutMs: number, + maxOutputBytes: number, + signal?: AbortSignal +): Promise { + if (!existsSync(MACOS_EXPECT_PATH)) { + return { ok: false, conclusive: false, reason: 'error' } + } + try { + const result = await runProcess({ + program: MACOS_EXPECT_PATH, + args: ['-c', EXPECT_LOGIN_PROBE_SCRIPT], + cwd: accountHome, + env: { ...process.env, [LOGIN_PROBE_USERNAME_ENV]: username }, + killOnOutputLimit: true, + maxOutputBytes, + signal, + timeoutMs + }) + if (result.timedOut) { + return { ok: false, conclusive: false, reason: 'timeout' } + } + // Tcl/PTY failures are inconclusive, never PAM rejection proof. + if (result.code !== 0 || result.outputTruncated) { + return { ok: false, conclusive: false, reason: 'error' } + } + return result.stdout.includes(LOGIN_PREFLIGHT_MARKER) + ? { ok: true, conclusive: true, reason: 'accepted' } + : { ok: false, conclusive: true, reason: 'rejected' } + } catch { + return { ok: false, conclusive: false, reason: 'error' } + } +} diff --git a/src/main/providers/shell-launch/macos/tcc-login-shell.ts b/src/main/providers/shell-launch/macos/tcc-login-shell.ts new file mode 100644 index 00000000000..2b943eb3428 --- /dev/null +++ b/src/main/providers/shell-launch/macos/tcc-login-shell.ts @@ -0,0 +1,316 @@ +import { runProcess } from '@orca/process-host' +import { existsSync } from 'node:fs' +import { userInfo } from 'node:os' +import { basename } from 'node:path' +import { runMacosLoginSessionPtyProbe, type LoginPreflightOutcome } from './login-session-pty-probe' + +export const MACOS_LOGIN_PATH = '/usr/bin/login' +const MACOS_BASH_PATH = '/bin/bash' +const MACOS_PRINTF_PATH = '/usr/bin/printf' +const LOGIN_SHELL_TRAMPOLINE = 'export SHELL="$1"; shift; exec -l -- "$@"' +const DIRECT_SHELL_TRAMPOLINE = 'export SHELL="$1"; shift; exec -- "$@"' +const LOGIN_PREFLIGHT_TIMEOUT_MS = 500 +// Off the spawn path, the death watch can outwait a slow PAM stack without delaying terminal creation. +const LOGIN_SESSION_WATCH_PROBE_TIMEOUT_MS = 4_000 +const LOGIN_PREFLIGHT_MARKER = 'ORCA_LOGIN_PREFLIGHT_OK' +const LOGIN_PREFLIGHT_MAX_BUFFER_BYTES = 1024 +const LOGIN_PREFLIGHT_RETRY_BASE_MS = 5_000 +const LOGIN_PREFLIGHT_RETRY_MAX_MS = 5 * 60_000 +// Long-lived daemons must recheck rejected PAM capability rather than disable attribution forever (#9756). +const LOGIN_PREFLIGHT_REJECTED_REVALIDATE_MS = 30 * 60_000 + +const DISABLE_ENV_VAR = 'ORCA_DISABLE_MACOS_LOGIN_SHELL' + +// Cache only actual PAM verdicts; timeout, output-cap and spawn failures remain retryable. +let cachedLoginPreflightResult: boolean | null = null +let cachedRejectionAtMs: number | null = null +let loginPreflightInFlight: Promise | null = null +let transientLoginPreflightFailure: { failureCount: number; retryAtMs: number } | null = null +let loginPreflightCacheEpoch = 0 +let loginSessionProbeInFlight = false +let loginSessionAcceptedInProcess = false + +function isDisabledByEnv(): boolean { + const value = process.env[DISABLE_ENV_VAR] + return value === '1' || value === 'true' +} + +function loginPreflightRetryDelayMs(failureCount: number): number { + return Math.min( + LOGIN_PREFLIGHT_RETRY_MAX_MS, + LOGIN_PREFLIGHT_RETRY_BASE_MS * 2 ** Math.max(0, failureCount - 1) + ) +} + +// Pipes can differ from production PTYs; later wrapper spawn failures still degrade to a direct shell. +async function runLoginPreflight( + username: string, + accountHome: string, + timeoutMs = LOGIN_PREFLIGHT_TIMEOUT_MS, + signal?: AbortSignal +): Promise { + try { + const result = await runProcess({ + program: MACOS_LOGIN_PATH, + args: ['-flpq', username, MACOS_PRINTF_PATH, LOGIN_PREFLIGHT_MARKER], + // Detached daemons may outlive their worktree; probe from the account home. + cwd: accountHome, + maxOutputBytes: LOGIN_PREFLIGHT_MAX_BUFFER_BYTES, + signal, + timeoutMs + }) + if (result.timedOut) { + return { ok: false, conclusive: false, reason: 'timeout' } + } + if (result.code === null) { + return { ok: false, conclusive: false, reason: 'error' } + } + if (result.code !== 0) { + return { ok: false, conclusive: true, reason: 'rejected' } + } + // login(1) can return zero after failed EOF prompting; require clean exit plus child marker. + return result.stdout === LOGIN_PREFLIGHT_MARKER + ? { ok: true, conclusive: true, reason: 'accepted' } + : { ok: false, conclusive: true, reason: 'rejected' } + } catch { + return { ok: false, conclusive: false, reason: 'error' } + } +} + +async function verifyRejectedLoginPreflightUnderPty( + username: string, + accountHome: string, + outcome: LoginPreflightOutcome +): Promise { + if (outcome.ok || !outcome.conclusive) { + return outcome + } + const ptyOutcome = await runMacosLoginSessionPtyProbe( + username, + accountHome, + LOGIN_PREFLIGHT_TIMEOUT_MS, + LOGIN_PREFLIGHT_MAX_BUFFER_BYTES + ) + // Why: a pipe-sensitive PAM stack must not override the production-shaped PTY oracle. + return ptyOutcome.conclusive ? ptyOutcome : outcome +} + +function expireStaleRejectedVerdict(): void { + if ( + cachedLoginPreflightResult === false && + cachedRejectionAtMs !== null && + Date.now() - cachedRejectionAtMs >= LOGIN_PREFLIGHT_REJECTED_REVALIDATE_MS + ) { + cachedLoginPreflightResult = null + cachedRejectionAtMs = null + } +} + +function cachedOutcome(): LoginPreflightOutcome | null { + if (cachedLoginPreflightResult === null) { + return null + } + return cachedLoginPreflightResult + ? { ok: true, conclusive: true, reason: 'accepted' } + : { ok: false, conclusive: true, reason: 'rejected' } +} + +function cacheConclusiveLoginPreflightOutcome(outcome: LoginPreflightOutcome): void { + if (outcome.ok) { + cachedRejectionAtMs = null + loginSessionAcceptedInProcess = true + } else if (cachedLoginPreflightResult !== false || cachedRejectionAtMs === null) { + // Why: periodic health probes must not extend one rejected verdict forever. + cachedRejectionAtMs = Date.now() + } + cachedLoginPreflightResult = outcome.ok + transientLoginPreflightFailure = null +} + +function loginPreflightSucceeds( + username: string, + accountHome: string +): Promise { + const cached = cachedOutcome() + if (cached) { + return Promise.resolve(cached) + } + if (!loginPreflightInFlight) { + const cacheEpoch = loginPreflightCacheEpoch + // Coalesce pane restores so startup bursts share one PAM subprocess. + loginPreflightInFlight = runLoginPreflight(username, accountHome).then(async (pipeOutcome) => { + const outcome = await verifyRejectedLoginPreflightUnderPty(username, accountHome, pipeOutcome) + // Environmental failures cannot become cached PAM verdicts; retry through bounded backoff. + const mayUpdateCache = !loginSessionProbeInFlight && cacheEpoch === loginPreflightCacheEpoch + if (outcome.conclusive && mayUpdateCache) { + cacheConclusiveLoginPreflightOutcome(outcome) + } else if (!outcome.conclusive && mayUpdateCache) { + const failureCount = (transientLoginPreflightFailure?.failureCount ?? 0) + 1 + transientLoginPreflightFailure = { + failureCount, + retryAtMs: Date.now() + loginPreflightRetryDelayMs(failureCount) + } + } + if (!outcome.ok) { + console.warn('[pty] macOS login(1) preflight failed; spawning shells directly') + } + // Release the in-flight slot so future spawns can retry inconclusive outcomes. + loginPreflightInFlight = null + return outcome + }) + } + return loginPreflightInFlight +} + +/** Await asynchronously to keep main responsive; null means no probe ran. + * Rejections expire; accepted state changes through the health watch. Return outcomes for detached-daemon telemetry. */ +export async function prepareMacosTccLoginShell(): Promise { + if (process.platform !== 'darwin' || isDisabledByEnv()) { + return null + } + expireStaleRejectedVerdict() + if (cachedLoginPreflightResult !== null) { + return null + } + // Why: a persistently hung probe must not add 500 ms and a subprocess to every terminal spawn. + if (transientLoginPreflightFailure && Date.now() < transientLoginPreflightFailure.retryAtMs) { + return null + } + if (!existsSync(MACOS_LOGIN_PATH)) { + return null + } + + let username: string + let accountHome: string + try { + const account = userInfo() + username = account.username + accountHome = account.homedir + } catch { + return null + } + if (!username || !accountHome) { + return null + } + return loginPreflightSucceeds(username, accountHome) +} + +export function resetMacosLoginShellPreflightForTests(): void { + cachedLoginPreflightResult = null + cachedRejectionAtMs = null + loginPreflightInFlight = null + transientLoginPreflightFailure = null + loginPreflightCacheEpoch = 0 + loginSessionProbeInFlight = false + loginSessionAcceptedInProcess = false +} + +/** Fresh death-watch check bypasses spawn cache/backoff and updates conclusive verdicts (#7936). + * Ambiguous results or rejection after prior acceptance require PTY confirmation; null means wrapping does not apply. */ +export async function probeMacosLoginSessionAlive( + signal?: AbortSignal +): Promise { + if (process.platform !== 'darwin' || isDisabledByEnv() || !existsSync(MACOS_LOGIN_PATH)) { + return null + } + let username: string + let accountHome: string + try { + const account = userInfo() + username = account.username + accountHome = account.homedir + } catch { + return null + } + if (!username || !accountHome) { + return null + } + // Why: reuse the startup warmup when present, and fence older spawn-path results from restoring a stale verdict. + const existingPreflight = loginPreflightInFlight + loginSessionProbeInFlight = true + loginPreflightCacheEpoch++ + let outcome: LoginPreflightOutcome + try { + outcome = await (existingPreflight ?? + runLoginPreflight(username, accountHome, LOGIN_SESSION_WATCH_PROBE_TIMEOUT_MS, signal)) + if (!outcome.ok && !signal?.aborted && (!outcome.conclusive || loginSessionAcceptedInProcess)) { + outcome = await runMacosLoginSessionPtyProbe( + username, + accountHome, + LOGIN_SESSION_WATCH_PROBE_TIMEOUT_MS, + LOGIN_PREFLIGHT_MAX_BUFFER_BYTES, + signal + ) + } + } finally { + // Why: invalidate spawn probes started during this fresh check before they can overwrite its newer verdict. + loginPreflightCacheEpoch++ + loginSessionProbeInFlight = false + } + if (outcome.conclusive) { + cacheConclusiveLoginPreflightOutcome(outcome) + } + return outcome +} + +/** login(1) reports its own status, losing shell exit codes/signals; wrapped outcomes must be unknown (STA-4536). */ +export function hostReportsChildExitStatus(file: string): boolean { + return file !== MACOS_LOGIN_PATH +} + +/** login(1) gives signed terminal CLIs independent TCC grants; positional trampoline args cannot become shell source. */ +export function wrapShellSpawnForMacosTccAttribution( + file: string, + args: string[], + env?: Record +): { file: string; args: string[] } { + if (process.platform !== 'darwin') { + return { file, args } + } + if (file === MACOS_LOGIN_PATH || isDisabledByEnv()) { + return { file, args } + } + if (!existsSync(MACOS_LOGIN_PATH)) { + return { file, args } + } + + let username: string + try { + username = userInfo().username + } catch { + return { file, args } + } + if (!username) { + return { file, args } + } + // Unprepared/rejected hosts still need usable shells; fresh-spawn callers prepare asynchronously first. + if (cachedLoginPreflightResult !== true) { + return { file, args } + } + + const shellEnvValue = env?.SHELL || file + // Login argv[0] disables Bash --rcfile; the Orca rcfile already implements login startup. + const trampoline = + basename(file).toLowerCase() === 'bash' && args.includes('--rcfile') + ? DIRECT_SHELL_TRAMPOLINE + : LOGIN_SHELL_TRAMPOLINE + + // -p blocks inherited BASH_ENV and imported functions before the fixed positional trampoline. + return { + file: MACOS_LOGIN_PATH, + args: [ + '-flpq', + username, + MACOS_BASH_PATH, + '--noprofile', + '--norc', + '-p', + '-c', + trampoline, + 'orca-tcc-login', + shellEnvValue, + file, + ...args + ] + } +} diff --git a/src/main/providers/windows-powershell-executable.ts b/src/main/providers/shell-launch/windows/powershell-executable.ts similarity index 100% rename from src/main/providers/windows-powershell-executable.ts rename to src/main/providers/shell-launch/windows/powershell-executable.ts diff --git a/src/main/providers/windows-powershell.ts b/src/main/providers/shell-launch/windows/powershell.ts similarity index 100% rename from src/main/providers/windows-powershell.ts rename to src/main/providers/shell-launch/windows/powershell.ts diff --git a/src/main/providers/shell-launch/windows/shell-args.ts b/src/main/providers/shell-launch/windows/shell-args.ts new file mode 100644 index 00000000000..be9e0d81161 --- /dev/null +++ b/src/main/providers/shell-launch/windows/shell-args.ts @@ -0,0 +1,200 @@ +import { win32 as pathWin32 } from 'node:path' +import { isWindowsGitBashShellPath } from '../../../pty/shell-startup/git-bash' +import { parseWslPath } from '../../../wsl/filesystem/unc-path-access' +import { toLinuxPath, toWindowsWslPath } from '../../../../shared/wsl-paths' +import { msysDrivePathToWindows } from '../../../../shared/cross-platform-path' +import { + buildWslExecArgs, + buildWslInteractiveLoginShellCommand +} from '../../../../shared/wsl-login-shell-command' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { getBashWrapperLaunchArgs } from '../../local-pty/local-pty-shell-ready' +import { ensureShellReadyWrappersAt } from '../../local-pty/local-pty-shell-ready-wrapper-generation' +import { encodePowerShellCommand } from '../../../../shared/powershell-command-encoding' +import { + getPowerShellOsc133Bootstrap, + getPowerShellOsc133StartupCommandMark +} from '../../../pty/shell-startup/powershell-osc133-bootstrap' +import { quoteStartupArg } from '../../../../shared/agent-launch/startup/tui-agent-startup-shell' +import { WSL_GUEST_ROOT_MARKER_COMMAND } from '../../../../shared/wsl-guest-root-marker' + +/** cmd.exe's own documented ceiling; callers that go through sshd budget below it. */ +export const CMD_EXE_COMMAND_LINE_MAX_CHARS = 8191 +const STARTUP_COMMAND_TEXT_MAX_CHARS = 6000 +// Includes ~400 encoded chars for the startup command mark so real commands keep the prior budget. +const POWERSHELL_ENCODED_COMMAND_ARG_MAX_CHARS = 28_400 +const CMD_UTF8_SETUP_COMMAND = 'chcp 65001 > nul' +export const ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV = 'ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE' +const CMD_CODEX_LAUNCH_PREFLIGHT = `if defined ORCA_CODEX_LAUNCH_PREFLIGHT call %${ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV}%%ORCA_CODEX_LAUNCH_PREFLIGHT%%${ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV}% agent hooks prepare-codex > nul 2>&1` +// Git Bash inherits OEM codepage; select UTF-8 before TUIs write bytes, but keep startup working if chcp.com is missing. +const GIT_BASH_UTF8_LOGIN_COMMAND = 'chcp.com 65001 >/dev/null 2>&1; exec "$BASH" --login -i' + +// Every Bash pane needs account-following wrappers; the rcfile also owns login startup. +function getGitBashLaunchCommand(): string { + ensureShellReadyWrappersAt() + const wrapperArgs = getBashWrapperLaunchArgs() + if (!wrapperArgs) { + return GIT_BASH_UTF8_LOGIN_COMMAND + } + const bashArgs = [...wrapperArgs, '-i'] + .map((arg) => (arg.startsWith('-') ? arg : quotePosixShell(arg.replace(/\\/g, '/')))) + .join(' ') + return `chcp.com 65001 >/dev/null 2>&1; exec "$BASH" ${bashArgs}` +} + +/** Shared local/daemon resolution prevents shell-preference drift between execution paths. */ +export type WindowsShellLaunchArgs = { + shellArgs: string[] + /** Startup is already in argv; suppress a second stdin write. */ + startupCommandDeliveredInShellArgs?: boolean + /** Native node-pty cwd; WSL launches from Windows home and performs guest cd through argv. */ + effectiveCwd: string + /** Requested path to validate even when WSL launches from a different native cwd. */ + validationCwd: string +} + +export type WindowsShellWslContext = { + distro: string + treatPosixCwdAsWsl?: boolean +} + +function getCmdShellArgStartupCommand(command?: string): string | null { + if (!command || command.length > STARTUP_COMMAND_TEXT_MAX_CHARS) { + return null + } + // node-pty C-runtime escaping changes cmd /K quotes; interactive stdin preserves them. + if (command.includes('"')) { + return null + } + const commandArg = `${CMD_UTF8_SETUP_COMMAND} & ${command}` + if (commandArg.length > CMD_EXE_COMMAND_LINE_MAX_CHARS) { + return null + } + return command +} + +function getPowerShellRestoreCwdCommand(cwd: string): string { + // Profiles may change directory; restore requested PTY cwd afterward. + return [ + '', + `try { Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction Stop } catch { Write-Warning "Failed to restore working directory: $_" }` + ].join('\n') +} + +function getPowerShellEncodedCommand( + cwd: string, + startupCommand?: string +): { + encodedCommand: string + startupCommandDeliveredInShellArgs?: boolean +} { + const bootstrap = `${getPowerShellOsc133Bootstrap()}${getPowerShellRestoreCwdCommand(cwd)}` + if (!startupCommand || startupCommand.length > STARTUP_COMMAND_TEXT_MAX_CHARS) { + return { encodedCommand: encodePowerShellCommand(bootstrap) } + } + + const command = `${bootstrap}\n${getPowerShellOsc133StartupCommandMark()}\n${startupCommand}` + const encodedCommand = encodePowerShellCommand(command) + // UTF-16/base64 expands payloads; leave margin under CreateProcess 32,767-character limit. + if (encodedCommand.length > POWERSHELL_ENCODED_COMMAND_ARG_MAX_CHARS) { + return { encodedCommand: encodePowerShellCommand(bootstrap) } + } + + return { + encodedCommand, + startupCommandDeliveredInShellArgs: true + } +} + +function buildWslShellArgs(linuxCwd: string, distro?: string): string[] { + ensureShellReadyWrappersAt() + const setupCommand = [ + `cd ${quotePosixShell(linuxCwd)}`, + 'export PATH="$HOME/.local/bin:$PATH"', + // Before any user startup file: the PTY owner binds this guest root to its live terminal. + WSL_GUEST_ROOT_MARKER_COMMAND, + buildWslInteractiveLoginShellCommand() + ].join(' && ') + // Match the distro login shell used by environment detection, including customized zsh. + return buildWslExecArgs(distro, ['sh', '-c', setupCommand]) +} + +/** Apply UTF-8/bootstrap profiles, preserve guest cwd, and share argv semantics across local and daemon spawns. */ +export function resolveWindowsShellLaunchArgs( + shellPath: string, + cwd: string, + defaultCwd: string, + wslContext?: WindowsShellWslContext, + startupCommand?: string, + codexLaunchPreflightCommand?: string +): WindowsShellLaunchArgs { + const shellBasename = pathWin32.basename(shellPath).toLowerCase() + const nativeCwd = msysDrivePathToWindows(cwd) + + if (shellBasename === 'cmd.exe') { + const shellArgStartupCommand = getCmdShellArgStartupCommand(startupCommand) + const startupCommands = [ + CMD_UTF8_SETUP_COMMAND, + ...(codexLaunchPreflightCommand ? [CMD_CODEX_LAUNCH_PREFLIGHT] : []), + ...(shellArgStartupCommand ? [shellArgStartupCommand] : []) + ] + return { + shellArgs: ['/K', startupCommands.join(' & ')], + ...(shellArgStartupCommand ? { startupCommandDeliveredInShellArgs: true } : {}), + effectiveCwd: nativeCwd, + validationCwd: nativeCwd + } + } + + if (shellBasename === 'powershell.exe' || shellBasename === 'pwsh.exe') { + const powerShellCommand = getPowerShellEncodedCommand(nativeCwd, startupCommand) + // Windows status requires OSC 133 prompt/readline hooks after profiles; encoded delivery follows powershell-osc133-bootstrap.ts MDE review. + return { + shellArgs: ['-NoLogo', '-NoExit', '-EncodedCommand', powerShellCommand.encodedCommand], + ...(powerShellCommand.startupCommandDeliveredInShellArgs + ? { startupCommandDeliveredInShellArgs: true } + : {}), + effectiveCwd: nativeCwd, + validationCwd: nativeCwd + } + } + + if (isWindowsGitBashShellPath(shellPath)) { + return { + shellArgs: ['-c', getGitBashLaunchCommand()], + effectiveCwd: nativeCwd, + validationCwd: nativeCwd + } + } + + if (shellBasename === 'wsl.exe') { + const wslInfo = parseWslPath(cwd) + if (wslInfo) { + return { + shellArgs: buildWslShellArgs(wslInfo.linuxPath, wslInfo.distro), + effectiveCwd: defaultCwd, + validationCwd: cwd + } + } + if (wslContext?.treatPosixCwdAsWsl && cwd.startsWith('/')) { + return { + shellArgs: buildWslShellArgs(cwd, wslContext.distro), + effectiveCwd: defaultCwd, + validationCwd: toWindowsWslPath(cwd, wslContext.distro) + } + } + const driveMatch = nativeCwd.replace(/\\/g, '/').match(/^([A-Za-z]):\/?(.*)$/) + const linuxCwd = driveMatch ? toLinuxPath(nativeCwd) : '/mnt/c' + return { + shellArgs: buildWslShellArgs(linuxCwd, wslContext?.distro), + effectiveCwd: defaultCwd, + validationCwd: nativeCwd + } + } + + return { + shellArgs: [], + effectiveCwd: nativeCwd, + validationCwd: nativeCwd + } +} diff --git a/src/main/providers/shell-launch/windows/shell-fallback-chain.ts b/src/main/providers/shell-launch/windows/shell-fallback-chain.ts new file mode 100644 index 00000000000..967bd0d451f --- /dev/null +++ b/src/main/providers/shell-launch/windows/shell-fallback-chain.ts @@ -0,0 +1,58 @@ +import { win32 as pathWin32 } from 'node:path' +import { resolveWindowsShellLaunchArgs } from './shell-args' +import type { WindowsShellWslContext } from './shell-args' +import { + resolveWindowsPowerShellSpawnChain, + type WindowsPowerShellResolveOptions +} from './powershell-executable' + +export type WindowsShellSpawnAttempt = { + shellPath: string + shellArgs: string[] + effectiveCwd: string + validationCwd: string + startupCommandDeliveredInShellArgs: boolean +} + +function toAttempt( + shellPath: string, + cwd: string, + defaultCwd: string, + wslContext: WindowsShellWslContext | undefined, + startupCommand: string | undefined +): WindowsShellSpawnAttempt { + const resolved = resolveWindowsShellLaunchArgs( + shellPath, + cwd, + defaultCwd, + wslContext, + startupCommand + ) + return { + shellPath, + shellArgs: resolved.shellArgs, + effectiveCwd: resolved.effectiveCwd, + validationCwd: resolved.validationCwd, + startupCommandDeliveredInShellArgs: resolved.startupCommandDeliveredInShellArgs === true + } +} + +/** Requested PowerShell → inbox PowerShell → cmd.exe, with absolute ConPTY-safe paths and per-shell argv. + * Store alias stubs fail CreateProcessW (5); non-PowerShell requests retain their single-shell path. */ +export function buildWindowsPowerShellSpawnAttempts(args: { + shellPath: string + cwd: string + defaultCwd: string + wslContext?: WindowsShellWslContext + startupCommand?: string + resolveOptions?: WindowsPowerShellResolveOptions +}): WindowsShellSpawnAttempt[] { + const basename = pathWin32.basename(args.shellPath).toLowerCase() + if (basename !== 'pwsh.exe' && basename !== 'powershell.exe') { + return [] + } + const chain = resolveWindowsPowerShellSpawnChain(basename, args.resolveOptions) + return chain.map((candidate) => + toAttempt(candidate, args.cwd, args.defaultCwd, args.wslContext, args.startupCommand) + ) +} diff --git a/src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts b/src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts new file mode 100644 index 00000000000..e1b9da070a8 --- /dev/null +++ b/src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts @@ -0,0 +1,188 @@ +import { + copyFileSync, + existsSync, + linkSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import * as pty from 'node-pty' +import { afterEach, describe, expect, it } from 'vitest' +import { CODEX_COMMAND_IDENTITY_ENV_KEYS } from '../../../../shared/codex-shell-function' +import { resolveGitBashPath } from '../../../pty/shell-startup/git-bash' +import { resolveWindowsShellLaunchArgs } from './shell-args' + +const describeWindows = process.platform === 'win32' ? describe : describe.skip +const tempDirs: string[] = [] + +function makeTempDir(): string { + const root = mkdtempSync(join(tmpdir(), 'orca shell preflight ')) + tempDirs.push(root) + return root +} + +function linkNodeExecutable(destination: string): void { + try { + linkSync(process.execPath, destination) + } catch { + copyFileSync(process.execPath, destination) + } +} + +function writeFailingPreflight(root: string): string { + const executable = join(root, 'orca preflight.exe') + linkNodeExecutable(executable) + writeFileSync( + join(root, 'agent'), + [ + "const { writeFileSync } = require('node:fs')", + "if (process.argv.slice(2).join(' ') !== 'hooks prepare-codex') process.exit(2)", + "writeFileSync(process.env.ORCA_PREFLIGHT_MARKER, 'ran')", + 'process.exit(7)' + ].join('\n') + ) + return executable +} + +function withPathEntry(env: NodeJS.ProcessEnv, entry: string): NodeJS.ProcessEnv { + const result = { ...env } + const pathKey = Object.keys(result).find((key) => key.toLowerCase() === 'path') + const inheritedPath = pathKey ? result[pathKey] : '' + if (pathKey) { + delete result[pathKey] + } + result.PATH = `${entry};${inheritedPath ?? ''}` + return result +} + +async function runPty(options: { + shellPath: string + shellArgs: string[] + cwd: string + env: NodeJS.ProcessEnv + input?: string + timeoutMs?: number +}): Promise { + const proc = pty.spawn(options.shellPath, options.shellArgs, { + name: 'xterm-256color', + cols: 100, + rows: 30, + cwd: options.cwd, + env: options.env + }) + let output = '' + proc.onData((data) => { + output += data + }) + let exited = false + const exitPromise = new Promise((resolve) => { + proc.onExit(({ exitCode }) => { + exited = true + resolve(exitCode) + }) + }) + let timeout: ReturnType | undefined + const timeoutPromise = new Promise((_resolve, reject) => { + timeout = setTimeout( + () => reject(new Error(`timed out waiting for Windows shell PTY:\n${output}`)), + options.timeoutMs ?? 10_000 + ) + }) + + try { + if (options.input) { + proc.write(options.input.replaceAll('\n', '\r')) + } + const exitCode = await Promise.race([exitPromise, timeoutPromise]) + expect(exitCode, output).toBe(0) + return output + } finally { + if (timeout) { + clearTimeout(timeout) + } + if (!exited) { + try { + proc.kill() + } catch { + // The PTY may have exited while cleanup was starting. + } + } + } +} + +afterEach(() => { + for (const root of tempDirs.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +describeWindows('Windows Codex shell preflight runtime', () => { + it('runs the typed-Codex wrapper through Git Bash without MSYS switch rewriting', async () => { + const gitBash = resolveGitBashPath() + expect(gitBash).not.toBeNull() + if (!gitBash) { + return + } + + const root = makeTempDir() + const preflight = writeFailingPreflight(root) + // Pin the fixture ahead of host Codex; MSYS rewrites temporary paths containing a .local segment. + const codexExecutable = join(root, 'bin', 'codex.exe') + mkdirSync(join(root, 'bin'), { recursive: true }) + linkNodeExecutable(codexExecutable) + const preflightMarker = join(root, 'git-bash-preflight-ran') + const codexMarker = join(root, 'git-bash-codex-ran') + const codexPathMarker = join(root, 'git-bash-codex-path') + const previousUserDataPath = process.env.ORCA_USER_DATA_PATH + process.env.ORCA_USER_DATA_PATH = join(root, 'user data') + + try { + const resolved = resolveWindowsShellLaunchArgs( + gitBash, + root, + root, + undefined, + undefined, + preflight + ) + await runPty({ + shellPath: gitBash, + shellArgs: resolved.shellArgs, + cwd: root, + env: { + ...withPathEntry(process.env, join(root, 'bin')), + // The fixture is Node: forwarded identity -c would become --check. + ...Object.fromEntries(CODEX_COMMAND_IDENTITY_ENV_KEYS.map((key) => [key, ''])), + CHERE_INVOKING: '1', + HOME: root, + ORCA_CODEX_LAUNCH_PREFLIGHT: preflight, + ORCA_PREFLIGHT_MARKER: preflightMarker, + ORCA_CODEX_MARKER: codexMarker, + TERM: 'xterm-256color' + }, + input: + "type -P codex > git-bash-codex-path\ncodex -e \"require('node:fs').writeFileSync(process.env.ORCA_CODEX_MARKER,'ran')\"\nexit\n", + // Low-spec QA measured 12.7–15.8s for Git Bash cold-start AV scans; cmd.exe retains its shorter budget. + timeoutMs: 25_000 + }) + } finally { + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + } + + expect(existsSync(preflightMarker)).toBe(true) + const resolvedCodexPath = readFileSync(codexPathMarker, 'utf8') + .trim() + .replaceAll('\\', '/') + .toLowerCase() + expect(resolvedCodexPath).toMatch(/\/bin\/codex(?:\.exe)?$/) + expect(readFileSync(codexMarker, 'utf8')).toBe('ran') + }) +}) diff --git a/src/main/providers/ssh-pty-id.ts b/src/main/providers/ssh-pty-id.ts deleted file mode 100644 index a7a23d77189..00000000000 --- a/src/main/providers/ssh-pty-id.ts +++ /dev/null @@ -1,7 +0,0 @@ -export { - parseAppSshPtyId, - toAppSshPtyId, - toComparableRelaySshPtyId, - toRelaySshPtyId -} from '../../shared/ssh-pty-id' -export type { ParsedSshPtyId } from '../../shared/ssh-pty-id' diff --git a/src/main/providers/stable-foreground-process.ts b/src/main/providers/stable-foreground-process.ts deleted file mode 100644 index 192c93ed791..00000000000 --- a/src/main/providers/stable-foreground-process.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { recognizeAgentProcess } from '../../shared/agent-status/process/agent-process-recognition' -import type { AgentForegroundProcessResolution } from './agent-foreground-process' - -export type StableForegroundProcess = { - processName: string | null - /** Agent name to remember for the next degraded read; null clears the memory. */ - lastRecognizedAgent: string | null -} - -/** Degraded scans cannot prove agent exit; preserve recognized identity until an available scan refreshes or clears it. */ -export function resolveStableForegroundProcess( - resolution: AgentForegroundProcessResolution, - lastRecognizedAgent: string | null -): StableForegroundProcess { - if (resolution.available) { - const isAgent = - resolution.processName !== null && recognizeAgentProcess(resolution.processName) !== null - return { - processName: resolution.processName, - lastRecognizedAgent: isAgent ? resolution.processName : null - } - } - return { - processName: lastRecognizedAgent ?? resolution.processName, - lastRecognizedAgent - } -} diff --git a/src/main/providers/startup-line-typed-length.live-shell.test.ts b/src/main/providers/startup-line-typed-length.live-shell.test.ts deleted file mode 100644 index 0b8bf25c0bc..00000000000 --- a/src/main/providers/startup-line-typed-length.live-shell.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -/** Prove multiline typed launch budgets survive zsh wrapper/readiness/startup delivery. - * Slow rc files exercise the 1.5s fallback write in cooked mode, where macOS MAX_CANON limits each line. */ -import { spawnSync } from 'node:child_process' -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import * as pty from 'node-pty' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - createShellStartupOutputScanState, - scanShellStartupOutput -} from '../pty/shell-startup/shell-startup-output-scanner' -import { selectShellStartupFeatures } from '../pty/shell-startup/shell-startup-features' -import { isBracketedPasteSafeShell } from '../../shared/startup-command-submission' -import { - TYPED_STARTUP_LINE_PROMPT_BUDGET_BYTES, - ZSH_MULTI_LINE_STARTUP_LINE_BUDGET_BYTES -} from '../../shared/startup-line-prompt-carry' -import { - restoreUserDataPathAfterEach, - setTestUserDataPath -} from './local-pty/local-pty-shell-ready-test-harness' - -function findZsh(): string { - if (process.platform === 'win32') { - return '' - } - return (spawnSync('sh', ['-c', 'command -v zsh'], { encoding: 'utf8' }).stdout ?? '').trim() -} - -const ZSH_PATH = findZsh() - -function promptLines(lineCount: number, perLine: number): string { - const words = 'Fix the failing checks on this branch, then explain what changed and why.' - return Array.from({ length: lineCount }, (_unused, index) => { - let line = `L${index}:` - while (line.length < perLine) { - line += ` ${words}` - } - return line.slice(0, perLine) - }).join('\n') -} - -let home = '' - -beforeEach(() => { - home = mkdtempSync(join(tmpdir(), 'orca-typed-line-home-')) - setTestUserDataPath(mkdtempSync(join(tmpdir(), 'orca-typed-line-ud-'))) -}) - -afterEach(() => { - rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) -}) - -restoreUserDataPathAfterEach() - -async function typeIntoZsh(text: string, userConfigSeconds: number): Promise { - if (userConfigSeconds > 0) { - writeFileSync(join(home, '.zshrc'), `sleep ${userConfigSeconds}\n`) - } - const out = join(home, 'out.txt') - const done = join(home, 'done.txt') - const { ensureShellReadyWrappers } = - await import('./local-pty/local-pty-shell-ready-wrapper-generation') - const { getShellLaunchConfig } = await import('./local-pty/local-pty-shell-ready') - const { writeStartupCommandWhenShellReady, STARTUP_COMMAND_READY_MAX_WAIT_MS } = - await import('./local-pty/local-pty-shell-ready-startup-command') - ensureShellReadyWrappers() - const env: Record = { PATH: '/usr/bin:/bin', HOME: home } - const launch = getShellLaunchConfig( - ZSH_PATH, - selectShellStartupFeatures({ - shellPath: ZSH_PATH, - env, - hasStartupCommand: true, - waitsForShellReady: true, - emitsStartupIdentity: false - }) - ) - expect(launch.supportsReadyMarker).toBe(true) - const proc = pty.spawn(ZSH_PATH, launch.args ?? [], { - name: 'xterm-256color', - cols: 200, - rows: 40, - cwd: home, - // Keep user config inside the fixture home. - env: { ...env, ...launch.env, ORCA_ORIG_ZDOTDIR: home, TERM: 'xterm-256color' } - }) - const scan = createShellStartupOutputScanState() - let resolveReady: ((signal: { postMarkerBytesObserved: boolean }) => void) | null = null - const ready = new Promise<{ postMarkerBytesObserved: boolean }>((resolve) => { - resolveReady = resolve - }) - // Match the provider readiness cap; later markers still release the write. - const cap = setTimeout(() => { - resolveReady?.({ postMarkerBytesObserved: false }) - resolveReady = null - }, STARTUP_COMMAND_READY_MAX_WAIT_MS) - proc.onData((data) => { - if (resolveReady && scanShellStartupOutput(scan, data).ready) { - resolveReady({ postMarkerBytesObserved: true }) - resolveReady = null - } - }) - writeStartupCommandWhenShellReady( - ready, - proc, - `printf '%s' '${text}' > '${out}'; printf ok > '${done}'`, - () => {}, - { - bracketedPasteSafe: isBracketedPasteSafeShell({ - shellName: 'zsh', - waitsForShellReady: launch.supportsReadyMarker === true - }) - } - ) - const deadline = Date.now() + 20_000 + userConfigSeconds * 1000 - while (!existsSync(done) && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 50)) - } - clearTimeout(cap) - const ran = existsSync(out) ? readFileSync(out, 'utf8') : null - const exited = new Promise((resolve) => proc.onExit(() => resolve())) - proc.kill() - await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2000))]) - return ran -} - -describe.skipIf(!ZSH_PATH)('a multi-line launch line typed into zsh', () => { - const perLine = TYPED_STARTUP_LINE_PROMPT_BUDGET_BYTES - 1 - const text = promptLines( - Math.floor((ZSH_MULTI_LINE_STARTUP_LINE_BUDGET_BYTES - 200) / (perLine + 1)), - perLine - ) - - it('arrives whole through the ready barrier', async () => { - expect(await typeIntoZsh(text, 0)).toBe(text) - }, 60_000) - - it('arrives whole when the user config outlasts the barrier and the write lands early', async () => { - expect(await typeIntoZsh(text, 3)).toBe(text) - }, 60_000) -}) diff --git a/src/main/providers/terminal-path-existence-batch.integration.test.ts b/src/main/providers/terminal-path-existence-batch.integration.test.ts deleted file mode 100644 index 21b09788ebe..00000000000 --- a/src/main/providers/terminal-path-existence-batch.integration.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { mkdtemp, writeFile, rm } from 'node:fs/promises' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -const handlers = vi.hoisted(() => new Map Promise>()) -vi.mock('electron', () => ({ - ipcMain: { - handle: (name: string, fn: (...args: unknown[]) => Promise) => handlers.set(name, fn) - }, - shell: {}, - dialog: {} -})) -import { registerShellHandlers } from '../ipc/shell' -let root: string | undefined -afterEach(async () => { - if (root) { - await rm(root, { recursive: true, force: true }) - } - root = undefined - handlers.clear() -}) -async function fixture() { - root = await mkdtemp(join(tmpdir(), 'orca-link-batch-')) - const paths = Array.from({ length: 8 }, (_, i) => join(root!, `file-${i}.ts`)) - await Promise.all(paths.map((path) => writeFile(path, 'fixture'))) - return paths -} -it('one actual shell IPC handler probes eight distinct temporary files and retains scalar answers', async () => { - const paths = await fixture() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This registration fixture never invokes unrelated store operations. - registerShellHandlers({} as never) - const all = [...paths, join(root!, 'missing'), root!] - expect(await handlers.get('shell:pathsExist')!(null, all)).toEqual( - await Promise.all(all.map((path) => handlers.get('shell:pathExists')!(null, path))) - ) - expect(await handlers.get('shell:pathsExist')!(null, all)).toEqual([ - ...paths.map(() => true), - false, - true - ]) - await expect(handlers.get('shell:pathsExist')!(null, Array(129).fill('x'))).rejects.toThrow( - 'Invalid' - ) -}) diff --git a/src/main/providers/settled-pty-write-stub.ts b/src/main/providers/testing/settled-pty-write-stub.ts similarity index 89% rename from src/main/providers/settled-pty-write-stub.ts rename to src/main/providers/testing/settled-pty-write-stub.ts index 3c8fd03bb19..bd5f629f8a5 100644 --- a/src/main/providers/settled-pty-write-stub.ts +++ b/src/main/providers/testing/settled-pty-write-stub.ts @@ -2,7 +2,7 @@ import { WRITE_ACCEPTED, writeRefused, type WriteSettlement -} from '../../shared/terminal/pty/lifecycle/pty-write-settlement' +} from '../../../shared/terminal/pty/lifecycle/pty-write-settlement' /** Adapt test doubles without weakening the production requirement for explicit settled writes. */ export function stubWriteSettlement(accepted: boolean): WriteSettlement { diff --git a/src/main/providers/windows-agent-foreground-command-line.ts b/src/main/providers/windows-agent-foreground-command-line.ts deleted file mode 100644 index a0858642d77..00000000000 --- a/src/main/providers/windows-agent-foreground-command-line.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { resolveWindowsForegroundIdentity } from './windows-agent-foreground-process' -import { queryWindowsPaneProcessInventory } from './windows-foreground-process-rows' - -/** Command line of the pane's foreground agent process, from one fresh native table read. */ -export async function resolveWindowsAgentForegroundCommandLine( - shellPid: number, - foregroundProcess: string -): Promise { - const inventory = await queryWindowsPaneProcessInventory(shellPid, { fresh: true }) - if (!inventory) { - return null - } - const { processId } = resolveWindowsForegroundIdentity( - inventory.candidates, - foregroundProcess, - undefined - ) - return processId === undefined - ? null - : (inventory.candidates.find((candidate) => candidate.pid === processId)?.command ?? null) -} diff --git a/src/main/providers/windows-agent-foreground-process.ts b/src/main/providers/windows-agent-foreground-process.ts deleted file mode 100644 index 8ba0fb1aa33..00000000000 --- a/src/main/providers/windows-agent-foreground-process.ts +++ /dev/null @@ -1,319 +0,0 @@ -import { - isAgentForegroundWrapperProcess, - isExpectedAgentProcess, - recognizeAgentProcess, - recognizeAgentProcessFromCommandLine, - type RecognizedAgentProcess -} from '../../shared/agent-status/process/agent-process-recognition' -import { - resolveOuterWrapperForegroundIdentity, - shouldInspectOuterWrapperForegroundProcess -} from '../../shared/foreground-wrapper-agent' -import { isShellProcess } from '../../shared/agent-status/process/shell-process-detection' -import { - queryWindowsPaneProcessInventory, - type WindowsProcessCandidate, - type WindowsProcessRow -} from './windows-foreground-process-rows' - -export type AgentForegroundResolutionOptions = { - contextPaths?: readonly string[] - /** Require a Windows process-table scan started after this request. */ - fresh?: boolean - /** Force confirmation scans even when node-pty reports a recognized name. */ - forceProcessScan?: boolean - /** Lazily proves which global descendants still belong to this ConPTY. */ - readWindowsConsoleAttachedProcessIds?: () => Promise | null> - /** A contradictory full-table command line proves cached anchor PID reuse. */ - anchorProcessId?: number - /** The cached agent name the anchor pid is supposed to prove. */ - anchorProcessName?: string -} - -export type WindowsAgentForegroundResolution = { - available: boolean - processName: string | null - /** Unambiguous recognized-name anchor; use the outer wrapper PID so embedded-child restarts do not imply exit. */ - processId?: number - /** True when the scan proves `anchorProcessId` now belongs to a non-agent. */ - anchorPidForeign?: boolean -} - -type WindowsForegroundIdentity = { - processName: string | null - processId?: number -} - -export function shouldInspectWindowsAgentForeground(fallbackProcess: string): boolean { - const recognized = recognizeAgentProcess(fallbackProcess) - return ( - isAgentForegroundWrapperProcess(fallbackProcess) || - isShellProcess(fallbackProcess) || - (recognized !== null && shouldInspectOuterWrapperForegroundProcess(recognized)) - ) -} - -export async function resolveWindowsAgentForegroundProcessWithAvailability( - shellPid: number, - fallbackProcess: string, - options: AgentForegroundResolutionOptions -): Promise { - const inventory = await queryWindowsPaneProcessInventory(shellPid, { - ...(options.fresh === true ? { fresh: true } : {}), - ...(options.anchorProcessId !== undefined ? { anchorPid: options.anchorProcessId } : {}) - }) - if (!inventory) { - return { available: false, processName: null } - } - const candidates = inventory.candidates - // Filter console membership before ambiguity checks so detached agents cannot suppress the attached input owner. - const hasRecognizedCandidate = windowsCandidatesContainRecognizedAgent( - candidates, - fallbackProcess, - options.contextPaths - ) - let filteredCandidates = candidates - if (hasRecognizedCandidate && options.readWindowsConsoleAttachedProcessIds) { - // Job membership retains detached descendants; only console attachment can exclude their byte authority. - const consoleProcessIds = await options.readWindowsConsoleAttachedProcessIds() - if (!consoleProcessIds) { - return { available: false, processName: null } - } - filteredCandidates = candidates.filter((candidate) => consoleProcessIds.has(candidate.pid)) - } - // Orphaned job members can hold recycled PIDs outside the descendant walk; inspect the full-table anchor. - const anchorRow = inventory.anchorRow - const anchorRecognized = anchorRow === null ? null : recognizeWindowsProcessCandidate(anchorRow) - const anchorPidForeign = - anchorRow !== null && - (anchorRecognized !== null - ? // A recognized row is foreign when it names a DIFFERENT agent. - options.anchorProcessName !== undefined && - anchorRecognized.processName !== options.anchorProcessName - : // Query-denied command === name is inconclusive, never foreign proof. - anchorRow.command !== anchorRow.name) - return { - available: true, - ...resolveWindowsForegroundIdentity(filteredCandidates, fallbackProcess, options.contextPaths), - ...(anchorPidForeign ? { anchorPidForeign: true } : {}) - } -} - -function windowsCandidatesContainRecognizedAgent( - candidates: readonly WindowsProcessCandidate[], - fallbackProcess: string, - contextPaths: readonly string[] | undefined -): boolean { - if (isShellProcess(fallbackProcess)) { - return createRecognizedWindowsProcessCandidates(candidates, contextPaths).length > 0 - } - return candidates - .filter((candidate) => windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess)) - .some( - (candidate) => - recognizeAgentProcessFromCommandLine(candidate.command) !== null || - recognizeAgentProcessFromCommandLine(candidate.name) !== null - ) -} - -export function resolveWindowsForegroundIdentity( - candidates: readonly WindowsProcessCandidate[], - fallbackProcess: string, - contextPaths: readonly string[] | undefined -): WindowsForegroundIdentity { - if (isShellProcess(fallbackProcess)) { - return resolveShellForegroundProcessFromWindowsCandidates(candidates, contextPaths) - } - const wrapperCandidates = candidates.filter((candidate) => - windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess) - ) - if (wrapperCandidates.length !== 1) { - return resolveWrapperForegroundProcessFromWindowsCandidates( - wrapperCandidates, - candidates, - contextPaths - ) - } - const [candidate] = wrapperCandidates - const recognized = - recognizeAgentProcessFromCommandLine(candidate.command) ?? - recognizeAgentProcessFromCommandLine(candidate.name) - if (recognized) { - return resolveOuterWrapperForegroundIdentity(recognized, candidate, candidates) - } - return { processName: null } -} - -function resolveShellForegroundProcessFromWindowsCandidates( - candidates: readonly WindowsProcessCandidate[], - contextPaths: readonly string[] | undefined -): WindowsForegroundIdentity { - const recognizedCandidates = createRecognizedWindowsProcessCandidates(candidates, contextPaths) - const contextCandidates = recognizedCandidates.filter((candidate) => candidate.contextMatch) - if (contextCandidates.length > 0) { - return resolveRecognizedWindowsProcessCandidates(contextCandidates, candidates) - } - return resolveRecognizedWindowsProcessCandidates(recognizedCandidates, candidates) -} - -function resolveWrapperForegroundProcessFromWindowsCandidates( - candidates: readonly WindowsProcessCandidate[], - allCandidates: readonly WindowsProcessCandidate[], - contextPaths: readonly string[] | undefined -): WindowsForegroundIdentity { - const contextCandidates = createRecognizedWindowsProcessCandidates( - candidates, - contextPaths - ).filter((candidate) => candidate.contextMatch) - return contextCandidates.length > 0 - ? resolveRecognizedWindowsProcessCandidates(contextCandidates, allCandidates) - : { processName: null } -} - -type RecognizedWindowsProcessCandidate = WindowsProcessRow & { - contextMatch: boolean - depth: number - processName: string - recognized: RecognizedAgentProcess -} - -function createRecognizedWindowsProcessCandidates( - candidates: readonly WindowsProcessCandidate[], - contextPaths: readonly string[] | undefined -): RecognizedWindowsProcessCandidate[] { - const normalizedContextPaths = normalizeContextPaths(contextPaths) - return candidates.flatMap((candidate) => { - const recognized = recognizeWindowsProcessCandidate(candidate) - if (!recognized) { - return [] - } - return [ - { - ...candidate, - contextMatch: candidateMatchesContextPath(candidate, normalizedContextPaths), - processName: recognized.processName, - recognized - } - ] - }) -} - -function resolveRecognizedWindowsProcessCandidates( - recognizedCandidates: readonly RecognizedWindowsProcessCandidate[], - allCandidates: readonly WindowsProcessCandidate[] -): WindowsForegroundIdentity { - if (recognizedCandidates.length === 0) { - return { processName: null } - } - const candidatesByPid = new Map(allCandidates.map((candidate) => [candidate.pid, candidate])) - const leafCandidates = recognizedCandidates.filter( - (candidate) => - !recognizedCandidates.some( - (other) => - other.pid !== candidate.pid && - windowsCandidateIsAncestor(candidate, other, candidatesByPid) - ) - ) - const leafIdentities = leafCandidates.map((candidate) => - resolveOuterWrapperForegroundIdentity(candidate.recognized, candidate, allCandidates) - ) - const leafProcessNames = new Set(leafIdentities.map((identity) => identity.processName)) - // Windows lacks POSIX foreground markers; disagreeing recognized lineage leaves cannot prove one agent. - if (leafProcessNames.size !== 1) { - return { processName: null } - } - // Anchor the named outer wrapper; its embedded child may exit/restart while the wrapper stays live. - const anchorProcessIds = new Set(leafIdentities.map((identity) => identity.processId)) - return { - processName: [...leafProcessNames][0], - // Distinct anchors agreeing on one name still leave no single liveness anchor. - ...(anchorProcessIds.size === 1 ? { processId: [...anchorProcessIds][0] } : {}) - } -} - -function windowsCandidateIsAncestor( - candidate: WindowsProcessRow, - other: WindowsProcessRow, - candidatesByPid: ReadonlyMap -): boolean { - let current = candidatesByPid.get(other.ppid) - while (current) { - if (current.pid === candidate.pid) { - return true - } - current = candidatesByPid.get(current.ppid) - } - return false -} - -function normalizeContextPaths(contextPaths: readonly string[] | undefined): string[] { - const normalized = new Set() - for (const contextPath of contextPaths ?? []) { - const candidate = normalizePathForCommandMatch(contextPath) - if (isSafeContextPath(candidate)) { - normalized.add(candidate) - } - } - return [...normalized].sort((a, b) => b.length - a.length) -} - -function isSafeContextPath(contextPath: string): boolean { - return contextPath.length >= 4 && (/^[a-z]:\//.test(contextPath) || contextPath.startsWith('//')) -} - -function candidateMatchesContextPath( - candidate: WindowsProcessRow, - normalizedContextPaths: readonly string[] -): boolean { - if (normalizedContextPaths.length === 0) { - return false - } - const haystack = normalizePathForCommandMatch(candidate.command) - return normalizedContextPaths.some((contextPath) => - commandLineContainsPath(haystack, contextPath) - ) -} - -function normalizePathForCommandMatch(value: string): string { - return value - .trim() - .replace(/^["']|["']$/g, '') - .replace(/\\/g, '/') - .replace(/\/+$/g, '') - .toLowerCase() -} - -function commandLineContainsPath(haystack: string, contextPath: string): boolean { - let index = haystack.indexOf(contextPath) - while (index !== -1) { - const before = index > 0 ? haystack[index - 1] : '' - const after = haystack[index + contextPath.length] ?? '' - const beforeOk = !before || /[\s"'(=]/.test(before) - const afterOk = !after || after === '/' || /[\s"'),;]/.test(after) - if (beforeOk && afterOk) { - return true - } - index = haystack.indexOf(contextPath, index + 1) - } - return false -} - -function recognizeWindowsProcessCandidate( - candidate: WindowsProcessRow -): RecognizedAgentProcess | null { - return ( - recognizeAgentProcessFromCommandLine(candidate.command) ?? - recognizeAgentProcessFromCommandLine(candidate.name) - ) -} - -function windowsCandidateMatchesFallbackWrapper( - candidate: WindowsProcessRow, - fallbackProcess: string -): boolean { - const commandToken = candidate.command.trim().split(/\s+/, 1)[0] ?? '' - return ( - isExpectedAgentProcess(candidate.name, fallbackProcess) || - isExpectedAgentProcess(commandToken, fallbackProcess) - ) -} diff --git a/src/main/providers/windows-cached-agent-revalidation.ts b/src/main/providers/windows-cached-agent-revalidation.ts deleted file mode 100644 index 21210de5b7f..00000000000 --- a/src/main/providers/windows-cached-agent-revalidation.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { isShellProcess } from '../../shared/agent-status/process/shell-process-detection' -import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-status/process/agent-process-recognition' -import type { AgentForegroundProcessResolution } from './agent-foreground-process' - -/** Unanchored job evidence may outlive console agents; cap it at five renderer confirm ladders (30s). - * Refresh on every positive recognition so the limit never times out a confirmed live agent. */ -export const WINDOWS_DETACHED_DESCENDANT_IDENTITY_MAX_AGE_MS = 30_000 - -export function canRevalidateCachedAgentWithoutScan( - cachedAgentName: string | null, - fallbackProcess: string | null -): boolean { - return ( - cachedAgentName !== null && - fallbackProcess !== null && - // Generic wrappers can outlive agents; only unreliable shell fallbacks may bridge through this cache. - isShellProcess(fallbackProcess) - ) -} - -export type WindowsCachedAgentJobVerdict = - /** Missing native capability: scans decide; distinct from an attempted but unavailable read. */ - | 'unsupported' - /** Anchor pid alive in the job, recently confirmed: identity stands, no scan. */ - | 'confirmed' - /** Anchor pid alive but past the age bound: scan for drift; a silent scan keeps it. */ - | 'recheck' - /** The shell alone in a complete job read: no successor is possible, retire. */ - | 'exited' - /** Other job members may be a restarted successor; keep only age-bounded identity until a scan settles it. */ - | 'anchor-exited' - /** No anchor; a non-shell member exists and the bound has not elapsed: identity stands. */ - | 'unproven' - /** No anchor and the bound elapsed: the superset answer stops standing in for a scan. */ - | 'expired' - /** No job answer: unverifiable per ssh-execution-boundary.md, never exit proof. */ - | 'unavailable' - -/** Complete inescapable-job membership proves anchor liveness/exit; unanchored members only supply age-bounded evidence. */ -export function judgeCachedAgentJobEvidence(args: { - jobProcessIds: ReadonlySet | null - jobSupported?: boolean - shellPid: number - anchorProcessId: number | null - identityAgeMs: number -}): WindowsCachedAgentJobVerdict { - if (args.jobProcessIds === null) { - return args.jobSupported === false ? 'unsupported' : 'unavailable' - } - const withinAgeBound = args.identityAgeMs <= WINDOWS_DETACHED_DESCENDANT_IDENTITY_MAX_AGE_MS - // A shell-pid "anchor" proves nothing about a child; treat it as unanchored. - if (args.anchorProcessId !== null && args.anchorProcessId !== args.shellPid) { - if (!args.jobProcessIds.has(args.anchorProcessId)) { - return args.jobProcessIds.size <= 1 ? 'exited' : 'anchor-exited' - } - return withinAgeBound ? 'confirmed' : 'recheck' - } - if (args.jobProcessIds.size <= 1) { - return 'exited' - } - return withinAgeBound ? 'unproven' : 'expired' -} - -/** Decision authority comes from fresh recognition or a known anchor not yet proved gone. */ -export function reconcileWindowsAgentDecision( - resolution: AgentForegroundProcessResolution, - verdict: WindowsCachedAgentJobVerdict, - anchor: { processName: string; pid: number | null } | null, - shellPid: number -): string | null { - if (resolution.available && recognizeAgentProcessFromCommandLine(resolution.processName ?? '')) { - return resolution.processName - } - if ( - anchor?.pid != null && - anchor.pid !== shellPid && - recognizeAgentProcessFromCommandLine(anchor.processName) && - !resolution.anchorPidForeign && - (verdict === 'confirmed' || - verdict === 'recheck' || - verdict === 'unavailable' || - verdict === 'unsupported') - ) { - return anchor.processName - } - return resolution.available ? resolution.processName : null -} diff --git a/src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts b/src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts deleted file mode 100644 index 9f183113bd9..00000000000 --- a/src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -/** #15192: test bundled ConPTY bytes for duplicate wide glyphs before xterm replay. - * Wide cells carry two copies of a wchar; script-blind renderer duplication would also affect Latin controls. */ -import { describe, expect, it } from 'vitest' -import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' -import { isWideGlyph } from '../daemon/__fixtures__/terminal-wide-cell-grid' - -const itOnWindows = process.platform === 'win32' ? it : it.skip - -const KOREAN_LINE = '안녕하세요 오르카 테스트입니다. 결론부터 말씀드리면 시각적 피로도' -const LATIN_LINE = 'roadmap/complete-overhaul-backlog-history.md (1.75) R-08)' -const LINE_REPEATS = 12 - -/** Adjacent identical wide characters. The fixtures contain none, so any hit is duplication. */ -function doubledWideRuns(text: string): string[] { - const hits: string[] = [] - for (let i = 1; i < text.length; i++) { - const ch = text[i]! - if (ch === text[i - 1] && isWideGlyph(ch)) { - hits.push(`${text.slice(Math.max(0, i - 12), i + 12)}`) - } - } - return hits -} - -async function runThroughConpty(opts: { useConptyDll: boolean }): Promise { - const nodePty = await import('node-pty') - // Node writes deterministic UTF-8; cmd.exe codepage would make fixture bytes machine-dependent. - const script = [ - `const ko=${JSON.stringify(KOREAN_LINE)};`, - `const la=${JSON.stringify(LATIN_LINE)};`, - `let i=0;`, - `const t=setInterval(()=>{process.stdout.write(ko+"\\r\\n"+la+"\\r\\n");`, - `if(++i>=${LINE_REPEATS}){clearInterval(t);process.exit(0);}},20);` - ].join('') - - const proc = nodePty.spawn(process.execPath, ['-e', script], { - name: 'xterm-256color', - // Narrow rows force wide glyphs across wrap boundaries where leading/trailing cells matter. - cols: 40, - rows: 10, - cwd: process.cwd(), - env: process.env as Record, - ...(opts.useConptyDll ? { useConptyDll: true } : {}) - }) - - let out = '' - proc.onData((chunk) => { - out += chunk - }) - // Resize triggers the repaint implicated by the intermittent report and its workaround. - const resizes = [38, 44, 36, 46] - const timers = resizes.map((cols, index) => - setTimeout( - () => { - try { - proc.resize(cols, 10) - } catch { - /* the child may already have exited */ - } - }, - 60 + index * 50 - ) - ) - - try { - await new Promise((resolve) => { - proc.onExit(() => resolve()) - }) - } finally { - // Always stop the fixture child so a hang cannot leak into later jobs. - for (const timer of timers) { - clearTimeout(timer) - } - try { - proc.kill() - } catch { - /* already gone */ - } - } - return out -} - -describe('Windows ConPTY wide-character fidelity (#15192)', () => { - itOnWindows( - 'does not double wide characters with the bundled ConPTY (useConptyDll)', - async () => { - const text = stripAnsiEscapeSequences(await runThroughConpty({ useConptyDll: true })) - expect(text).toContain(KOREAN_LINE.slice(0, 5)) - expect(doubledWideRuns(text)).toEqual([]) - // Latin is the control for script-specific corruption. - expect(text).toContain(LATIN_LINE) - }, - 60_000 - ) -}) diff --git a/src/main/providers/windows-foreground-process-rows.ts b/src/main/providers/windows-foreground-process-rows.ts deleted file mode 100644 index 62fab84d0fd..00000000000 --- a/src/main/providers/windows-foreground-process-rows.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { collectDescendantsFromIndex, getProcessTableIndex } from '../../shared/process-table-index' -import { - readWindowsProcessIdentityTableFresh, - readWindowsProcessTable, - readWindowsProcessTableFresh, - resetWindowsProcessTableForTests, - type WindowsProcessIdentityRow, - type WindowsProcessRow as NativeWindowsProcessRow -} from '../windows/windows-process-table' - -export type WindowsProcessRow = { - pid: number - ppid: number - name: string - command: string -} - -export type WindowsProcessCandidate = WindowsProcessRow & { depth: number } - -function toProcessRow(row: NativeWindowsProcessRow): WindowsProcessRow { - return { - pid: row.pid, - ppid: row.ppid, - name: row.name, - // Query denial can hide command lines; preserve image-name recognition as fallback. - command: row.command || row.name - } -} - -/** Share projection identity so per-pane reads also reuse the process-table index; rows remain immutable. */ -const projectedRows = new WeakMap() - -function projectProcessRows(native: readonly NativeWindowsProcessRow[]): WindowsProcessRow[] { - const cached = projectedRows.get(native) - if (cached) { - return cached - } - const rows = native.map(toProcessRow) - projectedRows.set(native, rows) - return rows -} - -/** Ancestry only needs identity rows; requesting unused command lines costs one OpenProcess per row. */ -export async function queryWindowsProcessLinksFresh(): Promise { - return readWindowsProcessIdentityTableFresh() -} - -export async function queryWindowsProcessDescendants( - rootPid: number, - options: { fresh?: boolean } = {} -): Promise { - return (await queryWindowsPaneProcessInventory(rootPid, options))?.candidates ?? null -} - -export type WindowsPaneProcessInventory = { - candidates: WindowsProcessCandidate[] - /** Full-table anchor catches recycled job-member PIDs orphaned outside the descendant walk. */ - anchorRow: WindowsProcessRow | null -} - -export async function queryWindowsPaneProcessInventory( - rootPid: number, - options: { fresh?: boolean; anchorPid?: number } = {} -): Promise { - let rows: WindowsProcessRow[] - try { - const native = - options.fresh === true - ? await readWindowsProcessTableFresh() - : await readWindowsProcessTable() - rows = projectProcessRows(native) - } catch { - return null - } - // Snapshot-shared index avoids per-pane whole-table map builds and linear PID lookups. - const index = getProcessTableIndex(rows) - // Missing roots may indicate stale/filtered snapshots, never observed absence of children. - if (!index.byPid.has(rootPid)) { - return null - } - return { - candidates: collectDescendantsFromIndex(index, rootPid).sort((a, b) => b.depth - a.depth), - anchorRow: options.anchorPid !== undefined ? (index.byPid.get(options.anchorPid) ?? null) : null - } -} - -export function resetWindowsProcessRowsSnapshotForTests(): void { - resetWindowsProcessTableForTests() -} diff --git a/src/main/providers/windows-powershell-executable.test.ts b/src/main/providers/windows-powershell-executable.test.ts deleted file mode 100644 index 47d9c678b89..00000000000 --- a/src/main/providers/windows-powershell-executable.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveWindowsPowerShellExecutablePath, - resolveWindowsPowerShellSpawnChain -} from './windows-powershell-executable' - -const WIN_ENV: NodeJS.ProcessEnv = { - ProgramW6432: 'C:\\Program Files', - 'ProgramFiles(x86)': 'C:\\Program Files (x86)', - LOCALAPPDATA: 'C:\\Users\\dev\\AppData\\Local', - SystemRoot: 'C:\\Windows', - ComSpec: 'C:\\Windows\\System32\\cmd.exe' -} - -const PATH_PWSH7 = 'D:\\Tools\\PowerShell\\7\\pwsh.exe' -const WINDOWS_POWERSHELL = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -// Store alias reparse points fail ConPTY CreateProcessW with access-denied (5). -const PWSH_STORE_ALIAS = 'C:\\Users\\dev\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe' -const PWSH_STORE_EXE = - 'C:\\Program Files\\WindowsApps\\Microsoft.PowerShell_7.6.3.0_x64__8wekyb3d8bbwe\\pwsh.exe' - -describe('resolveWindowsPowerShellExecutablePath', () => { - it('repro: resolves pwsh.exe from a real PATH entry when standard roots miss', () => { - expect( - resolveWindowsPowerShellExecutablePath('pwsh.exe', { - platform: 'win32', - env: { - ...WIN_ENV, - Path: [ - 'relative-tools', - 'C:\\Users\\dev\\AppData\\Local\\Microsoft\\WindowsApps', - 'D:\\Tools\\PowerShell\\7' - ].join(';') - }, - isRealExecutable: (p) => p === PATH_PWSH7 - }) - ).toBe(PATH_PWSH7) - }) - - it('repro: never resolves pwsh.exe to the Store App Execution Alias stub', () => { - // Alias existence cannot prove a ConPTY-launchable executable. - const resolved = resolveWindowsPowerShellExecutablePath('pwsh.exe', { - platform: 'win32', - env: WIN_ENV, - isRealExecutable: (p) => p === PWSH_STORE_ALIAS - }) - expect(resolved).toBeNull() - expect(resolved).not.toBe(PWSH_STORE_ALIAS) - }) - - it('repro: resolves a Store App Execution Alias to its real package executable', () => { - const resolved = resolveWindowsPowerShellExecutablePath('pwsh.exe', { - platform: 'win32', - env: { - ...WIN_ENV, - Path: 'C:\\Users\\dev\\AppData\\Local\\Microsoft\\WindowsApps' - }, - isRealExecutable: (p) => p === PWSH_STORE_EXE, - resolveAppExecutionAlias: (p) => (p === PWSH_STORE_ALIAS ? PWSH_STORE_EXE : null) - }) - expect(resolved).toBe(PWSH_STORE_EXE) - }) - - it.each(['pwsh.exe', PWSH_STORE_ALIAS, 'C:\\Tools\\powershell.exe'])( - 'rejects unsafe Store alias target %s', - (target) => { - const resolved = resolveWindowsPowerShellExecutablePath('pwsh.exe', { - platform: 'win32', - env: { - ...WIN_ENV, - Path: 'C:\\Users\\dev\\AppData\\Local\\Microsoft\\WindowsApps' - }, - isRealExecutable: (p) => p === target, - resolveAppExecutionAlias: (p) => (p === PWSH_STORE_ALIAS ? target : null) - }) - expect(resolved).toBeNull() - } - ) -}) - -describe('resolveWindowsPowerShellSpawnChain', () => { - it('falls back to Windows PowerShell + cmd.exe when pwsh is only a Store alias', () => { - const chain = resolveWindowsPowerShellSpawnChain('pwsh.exe', { - platform: 'win32', - env: WIN_ENV, - isRealExecutable: (p) => p === PWSH_STORE_ALIAS || p === WINDOWS_POWERSHELL - }) - expect(chain).toEqual([WINDOWS_POWERSHELL, WIN_ENV.ComSpec]) - expect(chain).not.toContain(PWSH_STORE_ALIAS) - }) -}) diff --git a/src/main/providers/windows-pty-job-membership.ts b/src/main/providers/windows-pty-job-membership.ts deleted file mode 100644 index 73fc6970d52..00000000000 --- a/src/main/providers/windows-pty-job-membership.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { IPty } from 'node-pty' -import { - isPtyJobOwnershipAvailable, - listPtyJobProcessIds, - ptyShellProcessId -} from '../windows/windows-pty-job' - -/** Read job membership without console-helper forks (#10857); null is unverifiable, never exit proof. - * Complete membership proves known-anchor liveness/exit and shell-alone state. Unanchored extra members - * may be detached leftovers, so callers must age-bound that evidence rather than claim agent liveness. */ -export function readWindowsPtyJobProcessIds( - proc: IPty, - listJobProcessIds: (proc: IPty) => readonly number[] | null = listPtyJobProcessIds -): ReadonlySet | null { - const pids = listJobProcessIds(proc) - if (!pids) { - return null - } - const membership = new Set(pids.filter((pid) => Number.isSafeInteger(pid) && pid > 0)) - // A size-one set lacking the shell proves a surviving child, never shell-alone state. - const shellPid = ptyShellProcessId(proc) - if (shellPid === undefined || !membership.has(proc.pid) || !membership.has(shellPid)) { - return null - } - if (shellPid !== proc.pid) { - membership.delete(proc.pid) - } - return membership -} - -/** Missing native exports are unsupported, distinct from an attempted but unavailable read. */ -export function isWindowsPtyJobReadable(): boolean { - return isPtyJobOwnershipAvailable() -} diff --git a/src/main/providers/windows-shell-alone-in-job.ts b/src/main/providers/windows-shell-alone-in-job.ts deleted file mode 100644 index b42ff9ae32f..00000000000 --- a/src/main/providers/windows-shell-alone-in-job.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { isGitForWindowsBashLauncherPath } from '../pty/shell-startup/git-bash' -import type { WindowsProcessIdentityRow } from '../windows/windows-process-table' -import { - buildProcessTableIndex, - collectDescendantsFromIndex -} from '../../shared/process-table-index' - -const MSYS_BASH_IMAGE = 'bash.exe' - -/** Git Bash launcher/MSYS exec stubs form a live unbranched bash chain; commands add a non-bash leaf or branch. - * Builtin-only/nested bash remains indistinguishable from idle. Optional console proof excludes detached orphans; - * ancestry alone cannot distinguish them from live MSYS children with exited Win32 parents. */ -export async function isWindowsShellAloneInJob( - shellPid: number, - spawnedShellPath: string, - jobProcessIds: ReadonlySet | null | undefined, - readIdentityTable: () => Promise, - readConsoleAttachedProcessIds?: () => Promise | null> -): Promise { - if (!jobProcessIds?.has(shellPid)) { - return false - } - if (jobProcessIds.size === 1) { - return true - } - const isLauncher = isGitForWindowsBashLauncherPath(spawnedShellPath) - if (!isLauncher && !readConsoleAttachedProcessIds) { - return false - } - const rows = (await readIdentityTable()).filter((row) => jobProcessIds.has(row.pid)) - // A member missing from the table exited or was never readable: no proof either way. - if (rows.length !== jobProcessIds.size) { - return false - } - const members = await withoutDetachedOrphans(shellPid, rows, readConsoleAttachedProcessIds) - if (members.length === 1) { - return true - } - if (!isLauncher) { - return false - } - const startMsByPid = new Map(members.map((row) => [row.pid, row.creationTimeMs])) - const visited = new Set([shellPid]) - let parentPid = shellPid - while (visited.size < members.length) { - const children = members.filter((row) => row.ppid === parentPid && !visited.has(row.pid)) - const child = children[0] - if ( - children.length !== 1 || - child.name.toLowerCase() !== MSYS_BASH_IMAGE || - startedBefore(child.creationTimeMs, startMsByPid.get(parentPid)) - ) { - return false - } - visited.add(child.pid) - parentPid = child.pid - } - return true -} - -/** Drops members that are neither linked to the shell through live parents nor on its console. */ -async function withoutDetachedOrphans( - shellPid: number, - members: WindowsProcessIdentityRow[], - readConsoleAttachedProcessIds: (() => Promise | null>) | undefined -): Promise { - if (!readConsoleAttachedProcessIds) { - return members - } - const linked = new Set([ - shellPid, - ...collectDescendantsFromIndex(buildProcessTableIndex(members), shellPid).map((row) => row.pid) - ]) - if (members.every((row) => linked.has(row.pid))) { - return members - } - const attached = await readConsoleAttachedProcessIds().catch(() => null) - return attached ? members.filter((row) => linked.has(row.pid) || attached.has(row.pid)) : members -} - -/** A child older than its parent carries a reused ppid; only checkable when the snapshot has start times. */ -function startedBefore( - childStartMs: number | undefined, - parentStartMs: number | undefined -): boolean { - return childStartMs !== undefined && parentStartMs !== undefined && childStartMs < parentStartMs -} diff --git a/src/main/providers/windows-shell-args.ts b/src/main/providers/windows-shell-args.ts deleted file mode 100644 index 1ac7777a5e6..00000000000 --- a/src/main/providers/windows-shell-args.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { win32 as pathWin32 } from 'node:path' -import { isWindowsGitBashShellPath } from '../pty/shell-startup/git-bash' -import { parseWslPath } from '../wsl/filesystem/unc-path-access' -import { toLinuxPath, toWindowsWslPath } from '../../shared/wsl-paths' -import { - buildWslExecArgs, - buildWslInteractiveLoginShellCommand -} from '../../shared/wsl-login-shell-command' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { getBashWrapperLaunchArgs } from './local-pty/local-pty-shell-ready' -import { ensureShellReadyWrappersAt } from './local-pty/local-pty-shell-ready-wrapper-generation' -import { encodePowerShellCommand } from '../../shared/powershell-command-encoding' -import { - getPowerShellOsc133Bootstrap, - getPowerShellOsc133StartupCommandMark -} from '../pty/shell-startup/powershell-osc133-bootstrap' -import { quoteStartupArg } from '../../shared/agent-launch/startup/tui-agent-startup-shell' -import { WSL_GUEST_ROOT_MARKER_COMMAND } from '../../shared/wsl-guest-root-marker' - -/** cmd.exe's own documented ceiling; callers that go through sshd budget below it. */ -export const CMD_EXE_COMMAND_LINE_MAX_CHARS = 8191 -const STARTUP_COMMAND_TEXT_MAX_CHARS = 6000 -// Includes ~400 encoded chars for the startup command mark so real commands keep the prior budget. -const POWERSHELL_ENCODED_COMMAND_ARG_MAX_CHARS = 28_400 -const CMD_UTF8_SETUP_COMMAND = 'chcp 65001 > nul' -export const ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV = 'ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE' -const CMD_CODEX_LAUNCH_PREFLIGHT = `if defined ORCA_CODEX_LAUNCH_PREFLIGHT call %${ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV}%%ORCA_CODEX_LAUNCH_PREFLIGHT%%${ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV}% agent hooks prepare-codex > nul 2>&1` -// Git Bash inherits OEM codepage; select UTF-8 before TUIs write bytes, but keep startup working if chcp.com is missing. -const GIT_BASH_UTF8_LOGIN_COMMAND = 'chcp.com 65001 >/dev/null 2>&1; exec "$BASH" --login -i' - -// Every Bash pane needs account-following wrappers; the rcfile also owns login startup. -function getGitBashLaunchCommand(): string { - ensureShellReadyWrappersAt() - const wrapperArgs = getBashWrapperLaunchArgs() - if (!wrapperArgs) { - return GIT_BASH_UTF8_LOGIN_COMMAND - } - const bashArgs = [...wrapperArgs, '-i'] - .map((arg) => (arg.startsWith('-') ? arg : quotePosixShell(arg.replace(/\\/g, '/')))) - .join(' ') - return `chcp.com 65001 >/dev/null 2>&1; exec "$BASH" ${bashArgs}` -} - -/** Shared local/daemon resolution prevents shell-preference drift between execution paths. */ -export type WindowsShellLaunchArgs = { - shellArgs: string[] - /** Startup is already in argv; suppress a second stdin write. */ - startupCommandDeliveredInShellArgs?: boolean - /** Native node-pty cwd; WSL launches from Windows home and performs guest cd through argv. */ - effectiveCwd: string - /** Requested path to validate even when WSL launches from a different native cwd. */ - validationCwd: string -} - -export type WindowsShellWslContext = { - distro: string - treatPosixCwdAsWsl?: boolean -} - -function getCmdShellArgStartupCommand(command?: string): string | null { - if (!command || command.length > STARTUP_COMMAND_TEXT_MAX_CHARS) { - return null - } - // node-pty C-runtime escaping changes cmd /K quotes; interactive stdin preserves them. - if (command.includes('"')) { - return null - } - const commandArg = `${CMD_UTF8_SETUP_COMMAND} & ${command}` - if (commandArg.length > CMD_EXE_COMMAND_LINE_MAX_CHARS) { - return null - } - return command -} - -function getPowerShellRestoreCwdCommand(cwd: string): string { - // Profiles may change directory; restore requested PTY cwd afterward. - return [ - '', - `try { Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction Stop } catch { Write-Warning "Failed to restore working directory: $_" }` - ].join('\n') -} - -function getPowerShellEncodedCommand( - cwd: string, - startupCommand?: string -): { - encodedCommand: string - startupCommandDeliveredInShellArgs?: boolean -} { - const bootstrap = `${getPowerShellOsc133Bootstrap()}${getPowerShellRestoreCwdCommand(cwd)}` - if (!startupCommand || startupCommand.length > STARTUP_COMMAND_TEXT_MAX_CHARS) { - return { encodedCommand: encodePowerShellCommand(bootstrap) } - } - - const command = `${bootstrap}\n${getPowerShellOsc133StartupCommandMark()}\n${startupCommand}` - const encodedCommand = encodePowerShellCommand(command) - // UTF-16/base64 expands payloads; leave margin under CreateProcess 32,767-character limit. - if (encodedCommand.length > POWERSHELL_ENCODED_COMMAND_ARG_MAX_CHARS) { - return { encodedCommand: encodePowerShellCommand(bootstrap) } - } - - return { - encodedCommand, - startupCommandDeliveredInShellArgs: true - } -} - -function buildWslShellArgs(linuxCwd: string, distro?: string): string[] { - ensureShellReadyWrappersAt() - const setupCommand = [ - `cd ${quotePosixShell(linuxCwd)}`, - 'export PATH="$HOME/.local/bin:$PATH"', - // Before any user startup file: the PTY owner binds this guest root to its live terminal. - WSL_GUEST_ROOT_MARKER_COMMAND, - buildWslInteractiveLoginShellCommand() - ].join(' && ') - // Match the distro login shell used by environment detection, including customized zsh. - return buildWslExecArgs(distro, ['sh', '-c', setupCommand]) -} - -/** Converts an MSYS drive spelling to the native cwd used by Windows terminal processes. */ -export function normalizeWindowsTerminalCwd(cwd: string): string { - const match = cwd.match(/^\/([A-Za-z])(?:\/(.*))?$/) - if (!match) { - return cwd - } - - const driveLetter = match[1].toUpperCase() - const rest = match[2]?.replace(/\//g, '\\') ?? '' - return rest ? `${driveLetter}:\\${rest}` : `${driveLetter}:\\` -} - -/** Apply UTF-8/bootstrap profiles, preserve guest cwd, and share argv semantics across local and daemon spawns. */ -export function resolveWindowsShellLaunchArgs( - shellPath: string, - cwd: string, - defaultCwd: string, - wslContext?: WindowsShellWslContext, - startupCommand?: string, - codexLaunchPreflightCommand?: string -): WindowsShellLaunchArgs { - const shellBasename = pathWin32.basename(shellPath).toLowerCase() - const nativeCwd = normalizeWindowsTerminalCwd(cwd) - - if (shellBasename === 'cmd.exe') { - const shellArgStartupCommand = getCmdShellArgStartupCommand(startupCommand) - const startupCommands = [ - CMD_UTF8_SETUP_COMMAND, - ...(codexLaunchPreflightCommand ? [CMD_CODEX_LAUNCH_PREFLIGHT] : []), - ...(shellArgStartupCommand ? [shellArgStartupCommand] : []) - ] - return { - shellArgs: ['/K', startupCommands.join(' & ')], - ...(shellArgStartupCommand ? { startupCommandDeliveredInShellArgs: true } : {}), - effectiveCwd: nativeCwd, - validationCwd: nativeCwd - } - } - - if (shellBasename === 'powershell.exe' || shellBasename === 'pwsh.exe') { - const powerShellCommand = getPowerShellEncodedCommand(nativeCwd, startupCommand) - // Windows status requires OSC 133 prompt/readline hooks after profiles; encoded delivery follows powershell-osc133-bootstrap.ts MDE review. - return { - shellArgs: ['-NoLogo', '-NoExit', '-EncodedCommand', powerShellCommand.encodedCommand], - ...(powerShellCommand.startupCommandDeliveredInShellArgs - ? { startupCommandDeliveredInShellArgs: true } - : {}), - effectiveCwd: nativeCwd, - validationCwd: nativeCwd - } - } - - if (isWindowsGitBashShellPath(shellPath)) { - return { - shellArgs: ['-c', getGitBashLaunchCommand()], - effectiveCwd: nativeCwd, - validationCwd: nativeCwd - } - } - - if (shellBasename === 'wsl.exe') { - const wslInfo = parseWslPath(cwd) - if (wslInfo) { - return { - shellArgs: buildWslShellArgs(wslInfo.linuxPath, wslInfo.distro), - effectiveCwd: defaultCwd, - validationCwd: cwd - } - } - if (wslContext?.treatPosixCwdAsWsl && cwd.startsWith('/')) { - return { - shellArgs: buildWslShellArgs(cwd, wslContext.distro), - effectiveCwd: defaultCwd, - validationCwd: toWindowsWslPath(cwd, wslContext.distro) - } - } - const driveMatch = nativeCwd.replace(/\\/g, '/').match(/^([A-Za-z]):\/?(.*)$/) - const linuxCwd = driveMatch ? toLinuxPath(nativeCwd) : '/mnt/c' - return { - shellArgs: buildWslShellArgs(linuxCwd, wslContext?.distro), - effectiveCwd: defaultCwd, - validationCwd: nativeCwd - } - } - - return { - shellArgs: [], - effectiveCwd: nativeCwd, - validationCwd: nativeCwd - } -} diff --git a/src/main/providers/windows-shell-fallback-chain.ts b/src/main/providers/windows-shell-fallback-chain.ts deleted file mode 100644 index adfcca2820e..00000000000 --- a/src/main/providers/windows-shell-fallback-chain.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { win32 as pathWin32 } from 'node:path' -import { resolveWindowsShellLaunchArgs } from './windows-shell-args' -import type { WindowsShellWslContext } from './windows-shell-args' -import { - resolveWindowsPowerShellSpawnChain, - type WindowsPowerShellResolveOptions -} from './windows-powershell-executable' - -export type WindowsShellSpawnAttempt = { - shellPath: string - shellArgs: string[] - effectiveCwd: string - validationCwd: string - startupCommandDeliveredInShellArgs: boolean -} - -function toAttempt( - shellPath: string, - cwd: string, - defaultCwd: string, - wslContext: WindowsShellWslContext | undefined, - startupCommand: string | undefined -): WindowsShellSpawnAttempt { - const resolved = resolveWindowsShellLaunchArgs( - shellPath, - cwd, - defaultCwd, - wslContext, - startupCommand - ) - return { - shellPath, - shellArgs: resolved.shellArgs, - effectiveCwd: resolved.effectiveCwd, - validationCwd: resolved.validationCwd, - startupCommandDeliveredInShellArgs: resolved.startupCommandDeliveredInShellArgs === true - } -} - -/** Requested PowerShell → inbox PowerShell → cmd.exe, with absolute ConPTY-safe paths and per-shell argv. - * Store alias stubs fail CreateProcessW (5); non-PowerShell requests retain their single-shell path. */ -export function buildWindowsPowerShellSpawnAttempts(args: { - shellPath: string - cwd: string - defaultCwd: string - wslContext?: WindowsShellWslContext - startupCommand?: string - resolveOptions?: WindowsPowerShellResolveOptions -}): WindowsShellSpawnAttempt[] { - const basename = pathWin32.basename(args.shellPath).toLowerCase() - if (basename !== 'pwsh.exe' && basename !== 'powershell.exe') { - return [] - } - const chain = resolveWindowsPowerShellSpawnChain(basename, args.resolveOptions) - return chain.map((candidate) => - toAttempt(candidate, args.cwd, args.defaultCwd, args.wslContext, args.startupCommand) - ) -} diff --git a/src/main/providers/windows-shell-preflight-runtime.windows.test.ts b/src/main/providers/windows-shell-preflight-runtime.windows.test.ts deleted file mode 100644 index 5c25ec5bd4a..00000000000 --- a/src/main/providers/windows-shell-preflight-runtime.windows.test.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { - copyFileSync, - existsSync, - linkSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import * as pty from 'node-pty' -import { afterEach, describe, expect, it } from 'vitest' -import { CODEX_COMMAND_IDENTITY_ENV_KEYS } from '../../shared/codex-shell-function' -import { resolveGitBashPath } from '../pty/shell-startup/git-bash' -import { - ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV, - resolveWindowsShellLaunchArgs -} from './windows-shell-args' - -const describeWindows = process.platform === 'win32' ? describe : describe.skip -const tempDirs: string[] = [] - -function makeTempDir(): string { - const root = mkdtempSync(join(tmpdir(), 'orca shell preflight ')) - tempDirs.push(root) - return root -} - -function linkNodeExecutable(destination: string): void { - try { - linkSync(process.execPath, destination) - } catch { - copyFileSync(process.execPath, destination) - } -} - -function writeFailingPreflight(root: string): string { - const executable = join(root, 'orca preflight.exe') - linkNodeExecutable(executable) - writeFileSync( - join(root, 'agent'), - [ - "const { writeFileSync } = require('node:fs')", - "if (process.argv.slice(2).join(' ') !== 'hooks prepare-codex') process.exit(2)", - "writeFileSync(process.env.ORCA_PREFLIGHT_MARKER, 'ran')", - 'process.exit(7)' - ].join('\n') - ) - return executable -} - -function withPathEntry(env: NodeJS.ProcessEnv, entry: string): NodeJS.ProcessEnv { - const result = { ...env } - const pathKey = Object.keys(result).find((key) => key.toLowerCase() === 'path') - const inheritedPath = pathKey ? result[pathKey] : '' - if (pathKey) { - delete result[pathKey] - } - result.PATH = `${entry};${inheritedPath ?? ''}` - return result -} - -async function runPty(options: { - shellPath: string - shellArgs: string[] - cwd: string - env: NodeJS.ProcessEnv - input?: string - timeoutMs?: number -}): Promise { - const proc = pty.spawn(options.shellPath, options.shellArgs, { - name: 'xterm-256color', - cols: 100, - rows: 30, - cwd: options.cwd, - env: options.env - }) - let output = '' - proc.onData((data) => { - output += data - }) - let exited = false - const exitPromise = new Promise((resolve) => { - proc.onExit(({ exitCode }) => { - exited = true - resolve(exitCode) - }) - }) - let timeout: ReturnType | undefined - const timeoutPromise = new Promise((_resolve, reject) => { - timeout = setTimeout( - () => reject(new Error(`timed out waiting for Windows shell PTY:\n${output}`)), - options.timeoutMs ?? 10_000 - ) - }) - - try { - if (options.input) { - proc.write(options.input.replaceAll('\n', '\r')) - } - const exitCode = await Promise.race([exitPromise, timeoutPromise]) - expect(exitCode, output).toBe(0) - return output - } finally { - if (timeout) { - clearTimeout(timeout) - } - if (!exited) { - try { - proc.kill() - } catch { - // The PTY may have exited while cleanup was starting. - } - } - } -} - -afterEach(() => { - for (const root of tempDirs.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -describeWindows('Windows Codex shell preflight runtime', () => { - it('runs a spaced executable through cmd.exe and continues after failure', async () => { - const root = makeTempDir() - const preflight = writeFailingPreflight(root) - const preflightMarker = join(root, 'cmd-preflight-ran') - const startupMarker = join(root, 'cmd-started') - const resolved = resolveWindowsShellLaunchArgs( - 'cmd.exe', - root, - root, - undefined, - 'echo launched>cmd-started & exit /b 0', - preflight - ) - - await runPty({ - shellPath: 'cmd.exe', - shellArgs: resolved.shellArgs, - cwd: root, - env: { - ...process.env, - ORCA_CODEX_LAUNCH_PREFLIGHT: preflight, - [ORCA_CODEX_LAUNCH_PREFLIGHT_CMD_QUOTE_ENV]: '"', - ORCA_PREFLIGHT_MARKER: preflightMarker - } - }) - - expect(readFileSync(preflightMarker, 'utf8')).toBe('ran') - expect(readFileSync(startupMarker, 'utf8').trim()).toBe('launched') - }) - - it('runs the typed-Codex wrapper through Git Bash without MSYS switch rewriting', async () => { - const gitBash = resolveGitBashPath() - expect(gitBash).not.toBeNull() - if (!gitBash) { - return - } - - const root = makeTempDir() - const preflight = writeFailingPreflight(root) - // Pin the fixture ahead of host Codex; MSYS rewrites temporary paths containing a .local segment. - const codexExecutable = join(root, 'bin', 'codex.exe') - mkdirSync(join(root, 'bin'), { recursive: true }) - linkNodeExecutable(codexExecutable) - const preflightMarker = join(root, 'git-bash-preflight-ran') - const codexMarker = join(root, 'git-bash-codex-ran') - const codexPathMarker = join(root, 'git-bash-codex-path') - const previousUserDataPath = process.env.ORCA_USER_DATA_PATH - process.env.ORCA_USER_DATA_PATH = join(root, 'user data') - - try { - const resolved = resolveWindowsShellLaunchArgs( - gitBash, - root, - root, - undefined, - undefined, - preflight - ) - await runPty({ - shellPath: gitBash, - shellArgs: resolved.shellArgs, - cwd: root, - env: { - ...withPathEntry(process.env, join(root, 'bin')), - // The fixture is Node: forwarded identity -c would become --check. - ...Object.fromEntries(CODEX_COMMAND_IDENTITY_ENV_KEYS.map((key) => [key, ''])), - CHERE_INVOKING: '1', - HOME: root, - ORCA_CODEX_LAUNCH_PREFLIGHT: preflight, - ORCA_PREFLIGHT_MARKER: preflightMarker, - ORCA_CODEX_MARKER: codexMarker, - TERM: 'xterm-256color' - }, - input: - "type -P codex > git-bash-codex-path\ncodex -e \"require('node:fs').writeFileSync(process.env.ORCA_CODEX_MARKER,'ran')\"\nexit\n", - // Low-spec QA measured 12.7–15.8s for Git Bash cold-start AV scans; cmd.exe retains its shorter budget. - timeoutMs: 25_000 - }) - } finally { - if (previousUserDataPath === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previousUserDataPath - } - } - - expect(existsSync(preflightMarker)).toBe(true) - const resolvedCodexPath = readFileSync(codexPathMarker, 'utf8') - .trim() - .replaceAll('\\', '/') - .toLowerCase() - expect(resolvedCodexPath).toMatch(/\/bin\/codex(?:\.exe)?$/) - expect(readFileSync(codexMarker, 'utf8')).toBe('ran') - }) -}) diff --git a/src/main/providers/working-directory-validation-retention.test.ts b/src/main/providers/working-directory-validation-retention.test.ts deleted file mode 100644 index 18bbfa92cd7..00000000000 --- a/src/main/providers/working-directory-validation-retention.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { getEventListeners } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { stat } = vi.hoisted(() => ({ - stat: vi.fn<() => Promise<{ isDirectory: () => boolean }>>() -})) -vi.mock('node:fs/promises', () => ({ stat })) -vi.mock('../wsl/filesystem/unc-path-access', () => ({ - wslUncDirectoryExistsAsync: () => { - throw new Error('Unexpected WSL probe') - } -})) - -import { - _resetWorkingDirectoryValidationStateForTest, - validateWorkingDirectoryAsync as validate, - WorkingDirectoryValidationAbortedError -} from './working-directory-validation' - -const directory = { isDirectory: () => true } -const cwd = 'synthetic-cwd-wait-retention' - -function pendingStat() { - const gate = Promise.withResolvers() - stat.mockReturnValue(gate.promise) - return gate -} - -async function canceledWait(path = cwd) { - const controller = new AbortController() - const signal = new WeakRef(controller.signal) - const waiting = validate(path, { signal: controller.signal }) - controller.abort() - try { - await waiting - throw new Error('Expected cancellation') - } catch (error) { - if (!(error instanceof WorkingDirectoryValidationAbortedError)) { - throw error - } - expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) - return { signal, error: new WeakRef(error) } - } -} - -async function collect(): Promise { - if (!('gc' in globalThis) || typeof globalThis.gc !== 'function') { - throw new Error('The test runner must enable --expose-gc') - } - for (let round = 0; round < 6; round += 1) { - await new Promise((resolve) => setImmediate(resolve)) - globalThis.gc() - } -} - -beforeEach(() => { - stat.mockReset() - _resetWorkingDirectoryValidationStateForTest() -}) -afterEach(() => vi.restoreAllMocks()) - -describe('working directory validation waiter lifetime', () => { - it('releases the first caller and subsequent canceled callers while their native stat stays owned', async () => { - const gate = pendingStat() - try { - const first = await canceledWait() - const later: Awaited>[] = [] - for (let index = 0; index < 31; index += 1) { - later.push(await canceledWait()) - } - await collect() - expect(first.signal.deref()).toBeUndefined() - expect(first.error.deref()).toBeUndefined() - expect(later.filter((ref) => ref.signal.deref() || ref.error.deref())).toHaveLength(0) - expect(stat).toHaveBeenCalledOnce() - - const staying = validate(cwd) - expect(stat).toHaveBeenCalledOnce() - gate.resolve(directory) - await staying - } finally { - gate.resolve(directory) - } - }) - - it.each([false, true])( - 'cleans a successful or rejected live waiter: reject=%s', - async (reject) => { - const gate = pendingStat() - const controller = new AbortController() - const raw = validate(cwd) - expect(validate(cwd)).toBe(raw) - const rawResult = raw.catch((error: unknown) => error) - const waiting = validate(cwd, { signal: controller.signal }).catch((error: unknown) => error) - expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1) - if (reject) { - gate.reject(new Error('Native stat failed')) - } else { - gate.resolve(directory) - } - const [rawValue, callerValue] = await Promise.all([rawResult, waiting]) - expect(callerValue).toBe(rawValue) - expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) - if (reject) { - expect(callerValue).toBeInstanceOf(Error) - } else { - expect(callerValue).toBeUndefined() - } - stat.mockResolvedValue(directory) - await validate(cwd) - expect(stat).toHaveBeenCalledTimes(2) - } - ) - - it('preserves the raw operation when the first caller is already aborted', async () => { - const gate = pendingStat() - try { - const signal = AbortSignal.abort() - await expect(validate(cwd, { signal })).rejects.toBeInstanceOf( - WorkingDirectoryValidationAbortedError - ) - const first = validate(cwd) - expect(validate(cwd)).toBe(first) - expect(stat).toHaveBeenCalledOnce() - expect(getEventListeners(signal, 'abort')).toHaveLength(0) - gate.resolve(directory) - await first - } finally { - gate.resolve(directory) - } - }) - - it('handles native rejection after every caller has already canceled', async () => { - const unhandled: unknown[] = [] - const recordUnhandled = (error: unknown): void => { - unhandled.push(error) - } - process.on('unhandledRejection', recordUnhandled) - const gate = pendingStat() - try { - await canceledWait() - gate.reject(new Error('Late native failure')) - await new Promise((resolve) => setImmediate(resolve)) - expect(unhandled).toEqual([]) - stat.mockResolvedValue(directory) - await validate(cwd) - expect(stat).toHaveBeenCalledTimes(2) - } finally { - gate.resolve(directory) - process.off('unhandledRejection', recordUnhandled) - } - }) - - it.each( - (['before', 'between', 'after'] as const).flatMap((position) => - [false, true].map((reject) => ({ position, reject })) - ) - )( - 'preserves an external raw observer at $position with reject=$reject', - async ({ position, reject }) => { - const gate = pendingStat() - const raw = validate(cwd) - const controller = new AbortController() - const start = () => - validate(cwd, { signal: controller.signal }).then( - () => 'fulfilled', - (error: unknown) => (error instanceof Error ? error.name : 'unknown') - ) - const waiters: Promise[] = [] - if (position !== 'before') { - waiters.push(start()) - } - const abortObserver = raw.then( - () => controller.abort(), - () => controller.abort() - ) - if (position !== 'after') { - waiters.push(start()) - } - if (reject) { - gate.reject(new Error('Native stat failed')) - } else { - gate.resolve(directory) - } - const rawOutcome = reject ? 'Error' : 'fulfilled' - expect(await Promise.all(waiters)).toEqual( - position === 'before' - ? ['WorkingDirectoryValidationAbortedError'] - : position === 'between' - ? [rawOutcome, 'WorkingDirectoryValidationAbortedError'] - : [rawOutcome] - ) - await abortObserver - } - ) -}) diff --git a/src/main/providers/working-directory-validation.test.ts b/src/main/providers/working-directory-validation.test.ts deleted file mode 100644 index 0fd0474dc26..00000000000 --- a/src/main/providers/working-directory-validation.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const wslUncDirectoryExistsAsyncMock = vi.hoisted(() => vi.fn()) - -vi.mock('../wsl/filesystem/unc-path-access', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { ...actual, wslUncDirectoryExistsAsync: wslUncDirectoryExistsAsyncMock } -}) - -import { - validateWorkingDirectoryAsync, - _resetWorkingDirectoryValidationStateForTest -} from './working-directory-validation' - -let tempDir: string - -beforeEach(async () => { - wslUncDirectoryExistsAsyncMock.mockReset() - wslUncDirectoryExistsAsyncMock.mockResolvedValue(null) - _resetWorkingDirectoryValidationStateForTest() - tempDir = await mkdtemp(path.join(os.tmpdir(), 'orca-cwd-validate-')) -}) - -afterEach(async () => { - await rm(tempDir, { recursive: true, force: true }) -}) - -describe('validateWorkingDirectoryAsync', () => { - describe('cancellation', () => { - // Unsettled probes persist in the module-level dedupe map; use a distinct path per test. - const deadShare = (name: string): string => `\\\\wsl.localhost\\Ubuntu\\dead-${name}` - - beforeEach(() => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('leaves the shared probe intact for callers that are still waiting', async () => { - let releaseProbe: () => void = () => {} - wslUncDirectoryExistsAsyncMock.mockReturnValue( - new Promise((resolve) => { - releaseProbe = () => resolve(true) - }) - ) - const abort = new AbortController() - - const shared = deadShare('shared') - const staying = validateWorkingDirectoryAsync(shared) - const leaving = validateWorkingDirectoryAsync(shared, { signal: abort.signal }) - abort.abort() - await expect(leaving).rejects.toThrow('was canceled') - - releaseProbe() - await expect(staying).resolves.toBeUndefined() - expect(wslUncDirectoryExistsAsyncMock).toHaveBeenCalledOnce() - }) - }) - - describe('UNC route concurrency', () => { - beforeEach(() => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('keeps a healthy local path out of a stalled share queue', async () => { - wslUncDirectoryExistsAsyncMock.mockReturnValue(new Promise(() => {})) - for (let index = 0; index < 4; index += 1) { - void validateWorkingDirectoryAsync(`\\\\wsl.localhost\\Ubuntu\\blocking-${index}`).catch( - () => {} - ) - } - - await expect(validateWorkingDirectoryAsync(tempDir)).resolves.toBeUndefined() - }) - }) -}) diff --git a/src/main/providers/working-directory-validation.ts b/src/main/providers/working-directory-validation.ts deleted file mode 100644 index 272f58ba8da..00000000000 --- a/src/main/providers/working-directory-validation.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { existsSync, statSync } from 'node:fs' -import { stat } from 'node:fs/promises' -import { release } from 'node:os' -import { isWslUncPath, uncRouteKey } from '../../shared/wsl-paths' -import { wslUncDirectoryExistsAsync } from '../wsl/filesystem/unc-path-access' -import { PrioritySemaphore } from '../../shared/priority-semaphore' - -const pendingWorkingDirectoryValidations = new Map>() -// Per-route limits keep dead UNC shares from consuming the default four-thread libuv fs pool. -const MAX_CONCURRENT_UNC_VALIDATIONS = 2 - -type UncRouteLane = { - readonly semaphore: PrioritySemaphore - waiters: number -} - -const uncRouteLanes = new Map() - -export { uncRouteKey } from '../../shared/wsl-paths' - -async function withUncRouteLane(cwd: string, run: () => Promise): Promise { - const key = uncRouteKey(cwd) - if (key === null) { - return run() - } - let lane = uncRouteLanes.get(key) - if (!lane) { - lane = { semaphore: new PrioritySemaphore(MAX_CONCURRENT_UNC_VALIDATIONS), waiters: 0 } - uncRouteLanes.set(key, lane) - } - // Counted before acquiring so a queued caller keeps the lane alive. - lane.waiters += 1 - const release = await lane.semaphore.acquire(0) - try { - return await run() - } finally { - release() - lane.waiters -= 1 - if (lane.waiters === 0) { - uncRouteLanes.delete(key) - } - } -} - -/** Thrown when the caller gave up on a probe that is still running. */ -export class WorkingDirectoryValidationAbortedError extends Error { - constructor(cwd: string) { - super(`Working directory validation for "${cwd}" was canceled.`) - this.name = 'WorkingDirectoryValidationAbortedError' - } -} - -export function _resetWorkingDirectoryValidationStateForTest(): void { - pendingWorkingDirectoryValidations.clear() - uncRouteLanes.clear() -} - -export function formatLocalPtyEnvironmentDiag(extra: Record = {}): string { - const systemVersion = - (process as NodeJS.Process & { getSystemVersion?: () => string }).getSystemVersion?.() || - release() - const parts = { - ...extra, - arch: process.arch, - platform: `${process.platform} ${systemVersion}`, - orca: process.env.ORCA_APP_VERSION?.trim() || '0.0.0-dev' - } - return Object.entries(parts) - .map(([key, value]) => `${key}: ${value}`) - .join(', ') -} - -/** A spawn refused because its folder is gone, as the daemon reports it back across its wire. */ -export function isMissingWorkingDirectoryError(error: unknown): boolean { - const message = error instanceof Error ? error.message : '' - return ( - message.startsWith('Working directory "') && - (message.includes('" does not exist.') || message.endsWith('" is not a directory.')) - ) -} - -function throwMissingWorkingDirectory(cwd: string): never { - throw new Error( - `Working directory "${cwd}" does not exist. ` + - `It may have been deleted or is on an unmounted volume ` + - `(${formatLocalPtyEnvironmentDiag({ cwd })}).` - ) -} - -export async function validateWorkingDirectory(cwd: string, signal?: AbortSignal): Promise { - // Distro probes spawn wsl.exe; never run them synchronously on main. - if (isWslUncPath(cwd)) { - return validateWorkingDirectoryAsync(cwd, { signal }) - } - - if (!existsSync(cwd)) { - throwMissingWorkingDirectory(cwd) - } - if (!statSync(cwd).isDirectory()) { - throw new Error(`Working directory "${cwd}" is not a directory.`) - } -} - -/** Cancellation abandons the caller, not the shared uninterruptible filesystem probe. */ -export function validateWorkingDirectoryAsync( - cwd: string, - options: { signal?: AbortSignal } = {} -): Promise { - const key = cwd - let validation = pendingWorkingDirectoryValidations.get(key) - if (!validation) { - validation = validateWorkingDirectoryUncached(cwd) - pendingWorkingDirectoryValidations.set(key, validation) - const started = validation - // Retain until settlement: expiring a hung stat frees no thread and lets retries pin more. - const forget = (): void => { - if (pendingWorkingDirectoryValidations.get(key) === started) { - pendingWorkingDirectoryValidations.delete(key) - } - } - void validation.then(forget, forget) - } - const signal = options.signal - if (!signal) { - return validation - } - return waitForWorkingDirectoryValidation(validation, cwd, signal) -} - -function validateWorkingDirectoryUncached(cwd: string): Promise { - return withUncRouteLane(cwd, () => probeWorkingDirectory(cwd)) -} - -async function probeWorkingDirectory(cwd: string): Promise { - // WSL 9P stat can falsely report ENOENT; ask the distro first, then fall back only if inconclusive. - if (isWslUncPath(cwd)) { - const existsInDistro = await wslUncDirectoryExistsAsync(cwd) - if (existsInDistro === false) { - throwMissingWorkingDirectory(cwd) - } - if (existsInDistro === true) { - return - } - } - - let stats: Awaited> - try { - stats = await stat(cwd) - } catch { - // One stat avoids paying an unreachable filesystem timeout twice. - throwMissingWorkingDirectory(cwd) - } - if (!stats.isDirectory()) { - throw new Error(`Working directory "${cwd}" is not a directory.`) - } -} - -type WorkingDirectoryWaiterHolder = { - waiter: { - signal: AbortSignal - onAbort: () => void - resolve: () => void - reject: (error: unknown) => void - } | null -} - -function takeWorkingDirectoryWaiter( - holder: WorkingDirectoryWaiterHolder -): WorkingDirectoryWaiterHolder['waiter'] { - const waiter = holder.waiter - holder.waiter = null - waiter?.signal.removeEventListener('abort', waiter.onAbort) - return waiter -} - -// Keep reaction order while an abandoned caller's signal and resolver become collectible. -function observeWorkingDirectoryValidation( - promise: Promise, - holder: WorkingDirectoryWaiterHolder -): void { - void promise.then( - () => takeWorkingDirectoryWaiter(holder)?.resolve(), - (error: unknown) => takeWorkingDirectoryWaiter(holder)?.reject(error) - ) -} - -function waitForWorkingDirectoryValidation( - shared: Promise, - cwd: string, - signal: AbortSignal -): Promise { - return new Promise((resolve, reject) => { - const holder: WorkingDirectoryWaiterHolder = { waiter: null } - const onAbort = (): void => { - takeWorkingDirectoryWaiter(holder)?.reject(new WorkingDirectoryValidationAbortedError(cwd)) - } - holder.waiter = { signal, onAbort, resolve, reject } - if (signal.aborted) { - onAbort() - return - } - signal.addEventListener('abort', onAbort, { once: true }) - observeWorkingDirectoryValidation(shared, holder) - }) -} diff --git a/src/main/providers/working-directory/default-cwd.ts b/src/main/providers/working-directory/default-cwd.ts new file mode 100644 index 00000000000..5bc039b1402 --- /dev/null +++ b/src/main/providers/working-directory/default-cwd.ts @@ -0,0 +1,41 @@ +import { homedir } from 'node:os' + +import { isRootLikePath } from './path-safety' + +function homeDrivePath(env: NodeJS.ProcessEnv): string | null { + if (!env.HOMEDRIVE || !env.HOMEPATH) { + return null + } + return `${env.HOMEDRIVE}${env.HOMEPATH}` +} + +export function isSafeImplicitPtyCwd(path: string | null | undefined): path is string { + return !isRootLikePath(path) +} + +export function resolveSafePtyDefaultCwd(env: NodeJS.ProcessEnv = process.env): string { + const candidates = + process.platform === 'win32' + ? [env.USERPROFILE, homeDrivePath(env), homedir()] + : [env.HOME, homedir()] + const selected = candidates.find(isSafeImplicitPtyCwd) + // Root fallback can trigger runaway discovery; refuse when no safe home exists. + if (!selected) { + // Record candidate values so malformed home environments remain diagnosable. + console.error( + '[pty-default-cwd] No safe default working directory for terminal launch; every home candidate resolved to a root-like path.', + { platform: process.platform, candidates } + ) + throw new Error('No safe default working directory is available for terminal launch.') + } + return selected +} + +export function assertSafeAgentStartupCwd(cwd: string | undefined, command: string): void { + if (isSafeImplicitPtyCwd(cwd)) { + return + } + throw new Error( + `Automatic agent startup command "${command}" requires a non-root workspace working directory.` + ) +} diff --git a/src/main/providers/pty-path-safety.ts b/src/main/providers/working-directory/path-safety.ts similarity index 100% rename from src/main/providers/pty-path-safety.ts rename to src/main/providers/working-directory/path-safety.ts diff --git a/src/main/providers/process-cwd.ts b/src/main/providers/working-directory/process-cwd.ts similarity index 96% rename from src/main/providers/process-cwd.ts rename to src/main/providers/working-directory/process-cwd.ts index e9f7a3289e8..59cdf772518 100644 --- a/src/main/providers/process-cwd.ts +++ b/src/main/providers/working-directory/process-cwd.ts @@ -1,7 +1,7 @@ import { execFile as execFileCb } from 'node:child_process' import { readlink } from 'node:fs/promises' -import { LSOF_NONBLOCKING_ARGS } from '../../shared/lsof-nonblocking-args' -import { readLibprocProcessFilePath } from '../../shared/libproc-addon' +import { LSOF_NONBLOCKING_ARGS } from '../../../shared/lsof-nonblocking-args' +import { readLibprocProcessFilePath } from '../../../shared/libproc-addon' // Coalesce/cache per-PID cwd reads briefly so rapid pane actions cannot accumulate lsof subprocesses. const CACHE_TTL_MS = 1500 diff --git a/src/main/providers/working-directory/validation.test.ts b/src/main/providers/working-directory/validation.test.ts new file mode 100644 index 00000000000..898c4f067fe --- /dev/null +++ b/src/main/providers/working-directory/validation.test.ts @@ -0,0 +1,54 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const wslUncDirectoryExistsAsyncMock = vi.hoisted(() => vi.fn()) + +vi.mock('../../wsl/filesystem/unc-path-access', async (importOriginal) => { + const actual = (await importOriginal()) as Record + return { ...actual, wslUncDirectoryExistsAsync: wslUncDirectoryExistsAsyncMock } +}) + +import { + validateWorkingDirectoryAsync, + _resetWorkingDirectoryValidationStateForTest +} from './validation' + +beforeEach(() => { + wslUncDirectoryExistsAsyncMock.mockReset() + wslUncDirectoryExistsAsyncMock.mockResolvedValue(null) + _resetWorkingDirectoryValidationStateForTest() +}) + +describe('validateWorkingDirectoryAsync', () => { + describe('cancellation', () => { + // Unsettled probes persist in the module-level dedupe map; use a distinct path per test. + const deadShare = (name: string): string => `\\\\wsl.localhost\\Ubuntu\\dead-${name}` + + beforeEach(() => { + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('leaves the shared probe intact for callers that are still waiting', async () => { + let releaseProbe: () => void = () => {} + wslUncDirectoryExistsAsyncMock.mockReturnValue( + new Promise((resolve) => { + releaseProbe = () => resolve(true) + }) + ) + const abort = new AbortController() + + const shared = deadShare('shared') + const staying = validateWorkingDirectoryAsync(shared) + const leaving = validateWorkingDirectoryAsync(shared, { signal: abort.signal }) + abort.abort() + await expect(leaving).rejects.toThrow('was canceled') + + releaseProbe() + await expect(staying).resolves.toBeUndefined() + expect(wslUncDirectoryExistsAsyncMock).toHaveBeenCalledOnce() + }) + }) +}) diff --git a/src/main/providers/working-directory/validation.ts b/src/main/providers/working-directory/validation.ts new file mode 100644 index 00000000000..af7bb666c41 --- /dev/null +++ b/src/main/providers/working-directory/validation.ts @@ -0,0 +1,203 @@ +import { existsSync, statSync } from 'node:fs' +import { stat } from 'node:fs/promises' +import { release } from 'node:os' +import { isWslUncPath, uncRouteKey } from '../../../shared/wsl-paths' +import { wslUncDirectoryExistsAsync } from '../../wsl/filesystem/unc-path-access' +import { PrioritySemaphore } from '../../../shared/priority-semaphore' + +const pendingWorkingDirectoryValidations = new Map>() +// Per-route limits keep dead UNC shares from consuming the default four-thread libuv fs pool. +const MAX_CONCURRENT_UNC_VALIDATIONS = 2 + +type UncRouteLane = { + readonly semaphore: PrioritySemaphore + waiters: number +} + +const uncRouteLanes = new Map() + +async function withUncRouteLane(cwd: string, run: () => Promise): Promise { + const key = uncRouteKey(cwd) + if (key === null) { + return run() + } + let lane = uncRouteLanes.get(key) + if (!lane) { + lane = { semaphore: new PrioritySemaphore(MAX_CONCURRENT_UNC_VALIDATIONS), waiters: 0 } + uncRouteLanes.set(key, lane) + } + // Counted before acquiring so a queued caller keeps the lane alive. + lane.waiters += 1 + const release = await lane.semaphore.acquire(0) + try { + return await run() + } finally { + release() + lane.waiters -= 1 + if (lane.waiters === 0) { + uncRouteLanes.delete(key) + } + } +} + +/** Thrown when the caller gave up on a probe that is still running. */ +export class WorkingDirectoryValidationAbortedError extends Error { + constructor(cwd: string) { + super(`Working directory validation for "${cwd}" was canceled.`) + this.name = 'WorkingDirectoryValidationAbortedError' + } +} + +export function _resetWorkingDirectoryValidationStateForTest(): void { + pendingWorkingDirectoryValidations.clear() + uncRouteLanes.clear() +} + +export function formatLocalPtyEnvironmentDiag(extra: Record = {}): string { + const systemVersion = + (process as NodeJS.Process & { getSystemVersion?: () => string }).getSystemVersion?.() || + release() + const parts = { + ...extra, + arch: process.arch, + platform: `${process.platform} ${systemVersion}`, + orca: process.env.ORCA_APP_VERSION?.trim() || '0.0.0-dev' + } + return Object.entries(parts) + .map(([key, value]) => `${key}: ${value}`) + .join(', ') +} + +/** A spawn refused because its folder is gone, as the daemon reports it back across its wire. */ +export function isMissingWorkingDirectoryError(error: unknown): boolean { + const message = error instanceof Error ? error.message : '' + return ( + message.startsWith('Working directory "') && + (message.includes('" does not exist.') || message.endsWith('" is not a directory.')) + ) +} + +function throwMissingWorkingDirectory(cwd: string): never { + throw new Error( + `Working directory "${cwd}" does not exist. ` + + `It may have been deleted or is on an unmounted volume ` + + `(${formatLocalPtyEnvironmentDiag({ cwd })}).` + ) +} + +export async function validateWorkingDirectory(cwd: string, signal?: AbortSignal): Promise { + // Distro probes spawn wsl.exe; never run them synchronously on main. + if (isWslUncPath(cwd)) { + return validateWorkingDirectoryAsync(cwd, { signal }) + } + + if (!existsSync(cwd)) { + throwMissingWorkingDirectory(cwd) + } + if (!statSync(cwd).isDirectory()) { + throw new Error(`Working directory "${cwd}" is not a directory.`) + } +} + +/** Cancellation abandons the caller, not the shared uninterruptible filesystem probe. */ +export function validateWorkingDirectoryAsync( + cwd: string, + options: { signal?: AbortSignal } = {} +): Promise { + const key = cwd + let validation = pendingWorkingDirectoryValidations.get(key) + if (!validation) { + validation = validateWorkingDirectoryUncached(cwd) + pendingWorkingDirectoryValidations.set(key, validation) + const started = validation + // Retain until settlement: expiring a hung stat frees no thread and lets retries pin more. + const forget = (): void => { + if (pendingWorkingDirectoryValidations.get(key) === started) { + pendingWorkingDirectoryValidations.delete(key) + } + } + void validation.then(forget, forget) + } + const signal = options.signal + if (!signal) { + return validation + } + return waitForWorkingDirectoryValidation(validation, cwd, signal) +} + +function validateWorkingDirectoryUncached(cwd: string): Promise { + return withUncRouteLane(cwd, () => probeWorkingDirectory(cwd)) +} + +async function probeWorkingDirectory(cwd: string): Promise { + // WSL 9P stat can falsely report ENOENT; ask the distro first, then fall back only if inconclusive. + if (isWslUncPath(cwd)) { + const existsInDistro = await wslUncDirectoryExistsAsync(cwd) + if (existsInDistro === false) { + throwMissingWorkingDirectory(cwd) + } + if (existsInDistro === true) { + return + } + } + + let stats: Awaited> + try { + stats = await stat(cwd) + } catch { + // One stat avoids paying an unreachable filesystem timeout twice. + throwMissingWorkingDirectory(cwd) + } + if (!stats.isDirectory()) { + throw new Error(`Working directory "${cwd}" is not a directory.`) + } +} + +type WorkingDirectoryWaiterHolder = { + waiter: { + signal: AbortSignal + onAbort: () => void + resolve: () => void + reject: (error: unknown) => void + } | null +} + +function takeWorkingDirectoryWaiter( + holder: WorkingDirectoryWaiterHolder +): WorkingDirectoryWaiterHolder['waiter'] { + const waiter = holder.waiter + holder.waiter = null + waiter?.signal.removeEventListener('abort', waiter.onAbort) + return waiter +} + +// Keep reaction order while an abandoned caller's signal and resolver become collectible. +function observeWorkingDirectoryValidation( + promise: Promise, + holder: WorkingDirectoryWaiterHolder +): void { + void promise.then( + () => takeWorkingDirectoryWaiter(holder)?.resolve(), + (error: unknown) => takeWorkingDirectoryWaiter(holder)?.reject(error) + ) +} + +function waitForWorkingDirectoryValidation( + shared: Promise, + cwd: string, + signal: AbortSignal +): Promise { + return new Promise((resolve, reject) => { + const holder: WorkingDirectoryWaiterHolder = { waiter: null } + const onAbort = (): void => { + takeWorkingDirectoryWaiter(holder)?.reject(new WorkingDirectoryValidationAbortedError(cwd)) + } + holder.waiter = { signal, onAbort, resolve, reject } + if (signal.aborted) { + onAbort() + return + } + signal.addEventListener('abort', onAbort, { once: true }) + observeWorkingDirectoryValidation(shared, holder) + }) +} diff --git a/src/main/providers/worktree-pty-ownership.ts b/src/main/providers/worktree-pty-ownership.ts deleted file mode 100644 index 21e4e464913..00000000000 --- a/src/main/providers/worktree-pty-ownership.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { isPathInsideOrEqual } from '../../shared/cross-platform-path' -import { splitWorktreeId, splitWorktreeIdForFilesystem } from '../../shared/worktree/id' -import type { PtyProcessInfo } from './pty-process-info' - -export function worktreePtyOwnership(worktreeId: string): (session: PtyProcessInfo) => boolean { - const prefix = `${worktreeId}@@` - const fullWorktreePath = splitWorktreeId(worktreeId)?.worktreePath - // Folder instances share a checkout; cwd alone cannot identify the owning instance. - const cwdFallbackPath = - splitWorktreeIdForFilesystem(worktreeId)?.worktreePath === fullWorktreePath - ? fullWorktreePath - : undefined - return (session) => - session.id.startsWith(prefix) || - session.worktreeId === worktreeId || - (cwdFallbackPath !== undefined && - session.worktreeId === undefined && - typeof session.cwd === 'string' && - session.cwd.length > 0 && - isPathInsideOrEqual(cwdFallbackPath, session.cwd)) -} diff --git a/src/main/pty/history/history-gc-worktree-ids.test.ts b/src/main/pty/history/history-gc-worktree-ids.test.ts new file mode 100644 index 00000000000..0604b456f0a --- /dev/null +++ b/src/main/pty/history/history-gc-worktree-ids.test.ts @@ -0,0 +1,33 @@ +/** An incomplete GC live set deletes owned history; regressions here caused the #14863 revert (#14975). */ +import { describe, expect, it } from 'vitest' +import { getKnownWorktreeIdsForHistoryGc } from './history-gc-worktree-ids' + +const noOtherProfiles = () => ({ ids: new Set(), unreadableProfiles: 0 }) + +const store = (worktreeIds: string[], folderIds: string[]) => + ({ + getAllWorktreeMeta: () => Object.fromEntries(worktreeIds.map((id) => [id, {}])), + getFolderWorkspaces: () => folderIds.map((id) => ({ id })) + }) as never + +describe('getKnownWorktreeIdsForHistoryGc', () => { + it('includes git worktrees', () => { + expect( + getKnownWorktreeIdsForHistoryGc(store(['repo-1::/path/wt'], []), noOtherProfiles) + ).toEqual(new Set(['repo-1::/path/wt'])) + }) + + // Folder PTYs mint history under folder:; omitting their separate store collection falsely marks live history orphaned. + + // History is not profile-scoped, so other profiles must remain in the live set. + + // Unreadable profiles make ownership unknown; empty means prune nothing, while partial IDs would delete live history. + it('reports nothing live when a profile could not be read', () => { + const live = getKnownWorktreeIdsForHistoryGc(store(['repo-1::/b'], ['fw-b']), () => ({ + ids: new Set(['repo-1::/a']), + unreadableProfiles: 1 + })) + + expect(live.size).toBe(0) + }) +}) diff --git a/src/main/window/history-gc-worktree-ids.ts b/src/main/pty/history/history-gc-worktree-ids.ts similarity index 78% rename from src/main/window/history-gc-worktree-ids.ts rename to src/main/pty/history/history-gc-worktree-ids.ts index 577c4287d4a..89b99f5a624 100644 --- a/src/main/window/history-gc-worktree-ids.ts +++ b/src/main/pty/history/history-gc-worktree-ids.ts @@ -1,6 +1,6 @@ -import type { Store } from '../persistence/loading-store/store' -import { folderWorkspaceKey } from '../../shared/workspace-scope' -import { getOtherProfileWorktreeIdsForHistoryGc } from '../orca-profiles/catalog/other-profile-workspace-catalog' +import type { Store } from '../../persistence/loading-store/store' +import { folderWorkspaceKey } from '../../../shared/workspace-scope' +import { getOtherProfileWorktreeIdsForHistoryGc } from '../../orca-profiles/catalog/other-profile-workspace-catalog' /** Include git and folder: PTY workspace keys; omitting folder workspaces makes their live shell history appear orphaned. */ export function getKnownWorktreeIdsForHistoryGc( diff --git a/src/main/pty/process-retirement/windows-pty-root-identity.ts b/src/main/pty/process-retirement/windows-pty-root-identity.ts index 384a6632130..778d7a18297 100644 --- a/src/main/pty/process-retirement/windows-pty-root-identity.ts +++ b/src/main/pty/process-retirement/windows-pty-root-identity.ts @@ -1,4 +1,4 @@ -import { queryWindowsProcessLinksFresh } from '../../providers/windows-foreground-process-rows' +import { queryWindowsProcessLinksFresh } from '../../providers/foreground/windows/process-rows' import { readOrcaChromiumProcessPids } from './orca-chromium-process-pids' /** `own` proves ancestry, not PTY identity: a recycled PID under another Orca child still qualifies. */ diff --git a/src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts b/src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts index a3a5e039d04..2deabf016d4 100644 --- a/src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts +++ b/src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts @@ -1,5 +1,5 @@ -import { statSync } from 'node:fs' import { open, stat } from 'node:fs/promises' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' import { TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT } from '../../../shared/terminal/replay/terminal-scrollback-limits' import { decodeFromFirstUtf8Boundary, @@ -7,23 +7,6 @@ import { type TerminalScrollbackSnapshotStorage } from './terminal-scrollback-snapshots' -/** Whether a non-empty snapshot exists for `ref`; a stat only, so it never reads bytes. */ -export function hasTerminalScrollbackSnapshotSync( - ref: string, - storage?: TerminalScrollbackSnapshotStorage -): boolean { - for (const path of snapshotReadPaths(ref, storage)) { - try { - if (statSync(path).size > 0) { - return true - } - } catch { - // Try the legacy/global fallback when a profile-local snapshot is absent. - } - } - return false -} - /** Byte size of the snapshot `readTerminalScrollbackSnapshot` would read; `null` when absent. */ export async function statTerminalScrollbackSnapshotSize( ref: string, @@ -55,17 +38,22 @@ async function readTrailingUtf8Async(path: string, maxBytes: number): Promise>() + +/** Read the bounded replay tail without blocking the request owner on disk I/O. */ export async function readTerminalScrollbackSnapshot( ref: string, storage?: TerminalScrollbackSnapshotStorage ): Promise { - for (const path of snapshotReadPaths(ref, storage)) { - try { - return await readTrailingUtf8Async(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT) - } catch { - // Try the legacy/global fallback when a profile-local snapshot is absent. + // Async requests share the old single-reader resource bound without blocking the event loop. + return runKeyedSerializedOperation(snapshotReads, 'snapshot-read', async () => { + for (const path of snapshotReadPaths(ref, storage)) { + try { + return await readTrailingUtf8Async(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT) + } catch { + // Try the legacy/global fallback when a profile-local snapshot is absent. + } } - } - return null + return null + }) } diff --git a/src/main/pty/scrollback/terminal-scrollback-snapshots.ts b/src/main/pty/scrollback/terminal-scrollback-snapshots.ts index 8ed8dd1349d..7cabbca9791 100644 --- a/src/main/pty/scrollback/terminal-scrollback-snapshots.ts +++ b/src/main/pty/scrollback/terminal-scrollback-snapshots.ts @@ -1,23 +1,10 @@ import { createHash } from 'node:crypto' -import { - closeSync, - mkdirSync, - openSync, - readFileSync, - readSync, - renameSync, - rmSync, - statSync, - writeFileSync -} from 'node:fs' +import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs' import { mkdir, rename, rm, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { getAppEnvironment } from '../../../shared/app-environment' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { - TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT, - TERMINAL_SCROLLBACK_STORE_BYTE_LIMIT -} from '../../../shared/terminal/replay/terminal-scrollback-limits' +import { TERMINAL_SCROLLBACK_STORE_BYTE_LIMIT } from '../../../shared/terminal/replay/terminal-scrollback-limits' import { errorMessage } from '../../../shared/error-message' const SNAPSHOT_DIR_NAME = 'terminal-scrollback' @@ -122,22 +109,6 @@ function trailingUtf8Bytes(value: string, maxBytes: number): Buffer { return bytes.subarray(start) } -function readTrailingUtf8(path: string, maxBytes: number): string { - const size = statSync(path).size - const length = Math.min(size, maxBytes) - if (length <= 0) { - return '' - } - const bytes = Buffer.allocUnsafe(length) - const fd = openSync(path, 'r') - try { - readSync(fd, bytes, 0, length, size - length) - } finally { - closeSync(fd) - } - return decodeFromFirstUtf8Boundary(bytes) -} - /** Decodes a tail slice, skipping continuation bytes of a character the slice cut in half. */ export function decodeFromFirstUtf8Boundary(bytes: Buffer): string { let start = 0 @@ -217,20 +188,6 @@ export async function writeTerminalScrollbackSnapshot(args: { } } -export function readTerminalScrollbackSnapshotSync( - ref: string, - storage?: TerminalScrollbackSnapshotStorage -): string | null { - for (const path of snapshotReadPaths(ref, storage)) { - try { - return readTrailingUtf8(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT) - } catch { - // Try the next snapshot root when this read fails. - } - } - return null -} - export function deleteTerminalScrollbackSnapshotSync( ref: string, storage?: TerminalScrollbackSnapshotStorage diff --git a/src/main/pty/shell-startup/powershell-osc133-bootstrap-windows-clm.test.ts b/src/main/pty/shell-startup/powershell-osc133-bootstrap-windows-clm.test.ts index 19922f93cfb..4ec8293e0a5 100644 --- a/src/main/pty/shell-startup/powershell-osc133-bootstrap-windows-clm.test.ts +++ b/src/main/pty/shell-startup/powershell-osc133-bootstrap-windows-clm.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { encodePowerShellCommand } from '../../../shared/powershell-command-encoding' -import { resolveWindowsShellLaunchArgs } from '../../providers/windows-shell-args' +import { resolveWindowsShellLaunchArgs } from '../../providers/shell-launch/windows/shell-args' const WINDOWS_POWERSHELLS = ['powershell.exe', 'pwsh.exe'] as const const PROFILE_CODEX_HOME = 'C:\\Profile Custom\\codex' diff --git a/src/main/qoder/hook-service.ts b/src/main/qoder/hook-service.ts index 4e5db2c33ee..1ed5a33ef5c 100644 --- a/src/main/qoder/hook-service.ts +++ b/src/main/qoder/hook-service.ts @@ -1,4 +1,4 @@ -import type { ClaudeManagedHookPlan } from '../claude/claude-managed-hook-events' +import type { ClaudeManagedHookPlan } from '../claude/hooks/claude-managed-hook-events' import { ClaudeHookService } from '../claude/hook-service' // Qoder documents Claude-shaped hooks at https://docs.qoder.com/cli/hooks. diff --git a/src/main/qoder/real-cli.test.ts b/src/main/qoder/real-cli.test.ts index 15f0af89e5a..bc486e10fa4 100644 --- a/src/main/qoder/real-cli.test.ts +++ b/src/main/qoder/real-cli.test.ts @@ -1,3 +1,4 @@ +import '../agent-hooks/server/testing/memory-agent-identity-store.test-fixture' import { cp, mkdtemp, diff --git a/src/main/qwen-code/hook-service.ts b/src/main/qwen-code/hook-service.ts index 7488271380e..bceea6c9950 100644 --- a/src/main/qwen-code/hook-service.ts +++ b/src/main/qwen-code/hook-service.ts @@ -1,5 +1,5 @@ import { ClaudeHookService } from '../claude/hook-service' -import type { ClaudeManagedHookPlan } from '../claude/claude-managed-hook-events' +import type { ClaudeManagedHookPlan } from '../claude/hooks/claude-managed-hook-events' // Qwen's hook enum is authoritative; Claude's version table and statusline do not apply. export const QWEN_CODE_HOOK_EVENTS = [ diff --git a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts index 5c6b11b11b3..727cee43b38 100644 --- a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts +++ b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts @@ -109,7 +109,7 @@ export async function readClaudeOAuthCredentials( return keychain } try { - return parseClaudeOAuthCredentialsJson( + const file = parseClaudeOAuthCredentialsJson( await readFile( path.join( options?.credentialsFileConfigDir ?? path.join(homedir(), '.claude'), @@ -119,6 +119,10 @@ export async function readClaudeOAuthCredentials( ), 'credentials-file' ) + // A file with no token must not hide a refreshable or unreadable Keychain login. + return file.token || !(keychain.hasRefreshableCredentials || keychain.unavailable) + ? file + : keychain } catch (error) { return isDefinitiveAbsence(error) ? keychain : { ...keychain, unavailable: true } } diff --git a/src/main/rate-limits/providers/claude/claude-usage-result.ts b/src/main/rate-limits/providers/claude/claude-usage-result.ts index c729e503f78..06b33d52aa0 100644 --- a/src/main/rate-limits/providers/claude/claude-usage-result.ts +++ b/src/main/rate-limits/providers/claude/claude-usage-result.ts @@ -30,6 +30,14 @@ export function makeClaudeUsageResult( } } +// Not idle: the meter draws idle as pending, and nothing here will settle it. +export function claudeOAuthUsageDisabledResult(): ProviderRateLimits { + return makeClaudeUsageResult('unavailable', 'Usage appears when a Claude session runs.', { + failureKind: 'usage-unavailable', + attemptedSources: [] + }) +} + // Account rows explain host/profile failures; usage keeps its generic message. export function claudeUsageUnavailable(): ProviderRateLimits { return makeClaudeUsageResult('error', 'Claude usage is unavailable right now.', { diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-target.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-target.ts index 253fcacabc1..097625c922d 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-target.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-target.ts @@ -3,7 +3,7 @@ import { getWslSelectionKey, type CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' -import { normalizeCodexRuntimeSelection } from '../../../codex-accounts/runtime-selection' +import { normalizeCodexRuntimeSelection } from '../../../codex-accounts/account-management/runtime-selection' import { getInitialAccountRateLimitTarget } from '../../initial-account-rate-limit-target' export function getInitialCodexRateLimitTarget( diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts index c4667e40ead..087e8e035c0 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' -import type { CodexRateLimitHomeResolution } from '../../../codex-accounts/runtime-home-service-types' +import type { CodexRateLimitHomeResolution } from '../../../codex-accounts/runtime-home/runtime-home-service-types' vi.mock('../../../wsl/discovery/wsl-default-distro', () => ({ resolveWslDefaultDistro: vi.fn(async () => null) @@ -40,34 +40,6 @@ describe('Codex quota poll home for a WSL account (E9)', () => { } }) - it('skips without preparing a home when the targeted distro is stopped, even if the default runs', async () => { - const h = harness(['Ubuntu'], () => homeIn('orca-w')) - - const resolution = await resolveCodexRateLimitHomeUnlessStopped( - h.source, - { runtime: 'wsl', wslDistro: 'orca-w' }, - h.deps - ) - - expect(resolution).toEqual({ kind: 'skip' }) - expect(h.deps.isRunning).toHaveBeenCalledExactlyOnceWith('orca-w') - expect(h.prepareForRateLimitFetch).not.toHaveBeenCalled() - }) - - it('gates the default distro and pins it for the home lookup when none is configured', async () => { - const h = harness(['Ubuntu'], (target) => homeIn(target?.wslDistro ?? '?')) - - const resolution = await resolveCodexRateLimitHomeUnlessStopped( - h.source, - { runtime: 'wsl' }, - h.deps - ) - - // The account lane stays the default lane; only paths and probes are pinned. - expect(h.prepareForRateLimitFetch).toHaveBeenCalledExactlyOnceWith({ runtime: 'wsl' }, 'Ubuntu') - expect(resolution).toEqual({ kind: 'ready', codexHomePath: homeIn('Ubuntu') }) - }) - it('skips a home that lives in a distro other than the one it read as running', async () => { // The gated default runs, but the account's home is in a stopped distro. const h = harness(['Ubuntu'], () => homeIn('orca-w')) diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.ts index e32d0e2cda5..21896d3d3d9 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.ts @@ -1,6 +1,6 @@ import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import { parseWslUncPath } from '../../../../shared/wsl-paths' -import type { CodexRateLimitHomeResolution } from '../../../codex-accounts/runtime-home-service-types' +import type { CodexRateLimitHomeResolution } from '../../../codex-accounts/runtime-home/runtime-home-service-types' import { isWslDistroRunning } from '../../../wsl/discovery/wsl-background-distro-gate' import { resolveWslDefaultDistro } from '../../../wsl/discovery/wsl-default-distro' diff --git a/src/main/rate-limits/service/account-runtime-target-sync.ts b/src/main/rate-limits/service/account-runtime-target-sync.ts index 06529204995..fedae9b76cd 100644 --- a/src/main/rate-limits/service/account-runtime-target-sync.ts +++ b/src/main/rate-limits/service/account-runtime-target-sync.ts @@ -58,7 +58,7 @@ export function createAccountRuntimeTargetSettingsSync( } await Promise.all(refreshes) - // Antigravity has no targeted refresh; queueing a full one beside targeted ones can drop their reruns. + // Antigravity has no targeted refresh, so a usage target change needs a full one. if (usageTargetChanged) { await rateLimits.refresh() } diff --git a/src/main/rate-limits/service/rate-limit-service.ts b/src/main/rate-limits/service/rate-limit-service.ts index 9dcc556cc53..fd199a2bb73 100644 --- a/src/main/rate-limits/service/rate-limit-service.ts +++ b/src/main/rate-limits/service/rate-limit-service.ts @@ -19,6 +19,7 @@ import type { OpenCodeGoRateLimitConfig, MiniMaxRateLimitConfig, AntigravityUsageEnabledResolver, + ClaudeOAuthUsageEnabledResolver, MuseUsageEnabledResolver, ZcodePlanRateLimitConfig, GeminiCliOAuthEnabledResolver, @@ -73,6 +74,27 @@ export class RateLimitService extends RateLimitServiceAccountRefresh { this.geminiCliOAuthEnabledResolver = resolver } + setClaudeOAuthUsageEnabledResolver(resolver: ClaudeOAuthUsageEnabledResolver): void { + this.claudeOAuthUsageEnabledResolver = resolver + } + + // Retain only readings actually received from the terminal feed. + discardClaudeOAuthUsage(): void { + this.claudeUsageAbortController.abort() + this.claudeUsageAbortController = new AbortController() + this.claudeFetchGeneration += 1 + this.inactiveClaudeAccountsGeneration += 1 + this.inactiveClaudeCache.clear() + this.inactiveClaudeFetching.clear() + this.lastInactiveClaudeFetchAt = 0 + this.lastClaudeCheckCompletedAt = null + this.activeFailureStreakByProvider.claude = 0 + this.updateState({ ...this.state, claude: this.claudeUsageWithoutOAuth() }) + if (!this.lastClaudeAuthSnapshot) { + void this.fetchClaudeOnly({ force: true }) + } + } + setAntigravityUsageEnabledResolver(resolver: AntigravityUsageEnabledResolver): void { this.antigravityUsageEnabledResolver = resolver } @@ -162,6 +184,10 @@ export class RateLimitService extends RateLimitServiceAccountRefresh { void this.fetchAll() } else { this.scheduleDeferredStartupRefresh() + // Passive terminal usage needs account attribution even without a usage viewer. + if (!this.isClaudeOAuthUsageEnabled()) { + void this.fetchClaudeOnly({ force: true }) + } } this.startTimer() } diff --git a/src/main/rate-limits/service/service-account-refresh.ts b/src/main/rate-limits/service/service-account-refresh.ts index fdea05aff72..0cb65b2070f 100644 --- a/src/main/rate-limits/service/service-account-refresh.ts +++ b/src/main/rate-limits/service/service-account-refresh.ts @@ -57,6 +57,9 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna provider: 'claude' | 'codex', options: { notWithinMs?: number } = {} ): boolean { + if (provider === 'claude' && !this.isClaudeOAuthUsageEnabled()) { + return false + } const limits = this.state[provider] const now = Date.now() if (this.isFetching || this.isRetryAfterActive(limits)) { @@ -230,6 +233,8 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna this.activeFailureStreakByProvider.claude = 0 // Outgoing statusline posts must not land on the incoming account during the switch. this.lastClaudeAuthSnapshot = null + this.liveClaudeUsage = null + this.usageReadingAccounts.claude = undefined this.lastInactiveClaudeFetchAt = 0 this.updateState({ ...this.state, @@ -249,6 +254,8 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna if (targetChanged) { // Outgoing target posts must not land on the incoming target during the switch. this.lastClaudeAuthSnapshot = null + this.liveClaudeUsage = null + this.usageReadingAccounts.claude = undefined } this.updateState({ ...this.state, diff --git a/src/main/rate-limits/service/service-fetch-policy.ts b/src/main/rate-limits/service/service-fetch-policy.ts index 8af5c4b22b0..32512ce90c0 100644 --- a/src/main/rate-limits/service/service-fetch-policy.ts +++ b/src/main/rate-limits/service/service-fetch-policy.ts @@ -15,10 +15,24 @@ import { isStaleClaudeUsageWindow, mapClaudeUsageWindow } from '../providers/claude/claude-usage-window' +import { claudeOAuthUsageDisabledResult } from '../providers/claude/claude-usage-result' import { readUserClaudeConfigDir } from '../../claude-accounts/profiles/claude-profile-paths' import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchTargets { + protected isClaudeOAuthUsageEnabled(): boolean { + return this.claudeOAuthUsageEnabledResolver?.() ?? true + } + + protected claudeUsageFetchSignal(signal: AbortSignal): AbortSignal { + return AbortSignal.any([signal, this.claudeUsageAbortController.signal]) + } + + protected claudeUsageWithoutOAuth(): ProviderRateLimits { + const live = this.liveClaudeUsage ? withoutResetWindows(this.liveClaudeUsage, Date.now()) : null + return live?.session || live?.weekly ? live : claudeOAuthUsageDisabledResult() + } + protected getMiniMaxCredentialError(message: string): ProviderRateLimits { return { provider: 'minimax', @@ -44,6 +58,12 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT } } + protected claudeStateAtCycleStart(limits: ProviderRateLimits | null): ProviderRateLimits { + return this.isClaudeOAuthUsageEnabled() + ? this.withFetchingStatus(limits, 'claude') + : this.claudeUsageWithoutOAuth() + } + // Retry-After remains binding even when live posts restore ok display; early polls waste budget and prolong 429s. protected isRetryAfterActive(limits: ProviderRateLimits | null): boolean { return Boolean(limits?.usageMetadata?.retryAtMs && limits.usageMetadata.retryAtMs > Date.now()) @@ -70,6 +90,9 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT fresh: ProviderRateLimits, previous: ProviderRateLimits | null ): ProviderRateLimits { + if (!this.isClaudeOAuthUsageEnabled()) { + return this.claudeUsageWithoutOAuth() + } this.lastClaudeCheckCompletedAt = fresh.updatedAt // Failed OAuth must preserve newer live display while forwarding Retry-After to the poll gate. const current = this.state.claude @@ -94,15 +117,23 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT ) { return } - this.lastClaudeAuthSnapshot = { + const snapshot = { // System Default uses the user config folder without injecting a managed one. configDir: normalizeClaudeConfigDir( authPreparation?.envPatch.CLAUDE_CONFIG_DIR ?? getClaudeProfileRouter()?.userConfigDir() ?? readUserClaudeConfigDir(process.env) ), + home: authPreparation?.configDir, provenance: authPreparation?.provenance ?? 'system' } + if ( + snapshot.configDir !== this.lastClaudeAuthSnapshot?.configDir || + snapshot.provenance !== this.lastClaudeAuthSnapshot?.provenance + ) { + this.liveClaudeUsage = null + } + this.lastClaudeAuthSnapshot = snapshot } ingestLiveClaudeRateLimits(event: ClaudeStatusLineRateLimits): void { @@ -155,6 +186,26 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT ) { return } + const priorLive = this.liveClaudeUsage ? withoutResetWindows(this.liveClaudeUsage, now) : null + this.liveClaudeUsage = { + provider: 'claude', + session: freshSession ?? priorLive?.session ?? null, + weekly: freshWeekly ?? priorLive?.weekly ?? null, + updatedAt: now, + error: null, + status: 'ok', + usageMetadata: { + source: 'live-session', + lastSuccessfulSource: 'live-session', + authProvenance: snapshot.provenance + } + } + this.rememberUsageReadingAccount( + 'claude', + this.claudeFetchTarget, + snapshot.home, + snapshot.provenance + ) if ( previous?.status === 'ok' && previous.usageMetadata?.source === 'live-session' && diff --git a/src/main/rate-limits/service/service-fetch-queue.ts b/src/main/rate-limits/service/service-fetch-queue.ts index 6b04b1877b8..4958ca1f9aa 100644 --- a/src/main/rate-limits/service/service-fetch-queue.ts +++ b/src/main/rate-limits/service/service-fetch-queue.ts @@ -1,5 +1,7 @@ import { RateLimitServiceProviderCycles } from './service-provider-cycles' +type FetchCycle = (signal: AbortSignal) => Promise + export abstract class RateLimitServiceFetchQueue extends RateLimitServiceProviderCycles { protected async fetchAll(options?: { force?: boolean }): Promise { if (this.isFetching) { @@ -9,58 +11,10 @@ export abstract class RateLimitServiceFetchQueue extends RateLimitServiceProvide } return } - this.isFetching = true - - try { - let shouldContinue = true - // Only user-forced refreshes bypass Retry-After; queued reruns inherit that force. - let cycleForce = options?.force ?? false - while (shouldContinue) { - const signal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchAllCycle(fetchSignal, { force: cycleForce }) - ) - shouldContinue = false - cycleForce = true - if (signal.aborted) { - break - } - if (this.fullFetchQueued) { - this.fullFetchQueued = false - shouldContinue = true - continue - } - if (this.codexOnlyFetchQueued) { - this.codexOnlyFetchQueued = false - const codexSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchCodexOnlyCycle(fetchSignal) - ) - if (codexSignal.aborted) { - break - } - } - if (this.claudeOnlyFetchQueued) { - this.claudeOnlyFetchQueued = false - const claudeSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchClaudeOnlyCycle(fetchSignal, { force: true }) - ) - if (claudeSignal.aborted) { - break - } - } - if (this.grokOnlyFetchQueued) { - this.grokOnlyFetchQueued = false - const grokSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchGrokOnlyCycle(fetchSignal) - ) - if (grokSignal.aborted) { - break - } - } - } - } finally { - this.isFetching = false - this.resolveFetchIdleWaiters() - } + // Only user-forced refreshes bypass Retry-After; queued reruns are forced. + return this.runFetchQueue((signal) => + this.runFetchAllCycle(signal, { force: options?.force ?? false }) + ) } protected async fetchCodexOnly(options?: { force?: boolean }): Promise { @@ -71,55 +25,7 @@ export abstract class RateLimitServiceFetchQueue extends RateLimitServiceProvide } return } - this.isFetching = true - - try { - let shouldContinue = true - while (shouldContinue) { - const signal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchCodexOnlyCycle(fetchSignal) - ) - shouldContinue = false - if (signal.aborted) { - break - } - if (this.fullFetchQueued) { - this.fullFetchQueued = false - const fullSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchAllCycle(fetchSignal, { force: true }) - ) - if (fullSignal.aborted) { - break - } - continue - } - if (this.codexOnlyFetchQueued) { - this.codexOnlyFetchQueued = false - shouldContinue = true - } - if (this.claudeOnlyFetchQueued) { - this.claudeOnlyFetchQueued = false - const claudeSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchClaudeOnlyCycle(fetchSignal, { force: true }) - ) - if (claudeSignal.aborted) { - break - } - } - if (this.grokOnlyFetchQueued) { - this.grokOnlyFetchQueued = false - const grokSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchGrokOnlyCycle(fetchSignal) - ) - if (grokSignal.aborted) { - break - } - } - } - } finally { - this.isFetching = false - this.resolveFetchIdleWaiters() - } + return this.runFetchQueue((signal) => this.runFetchCodexOnlyCycle(signal)) } protected async fetchClaudeOnly(options?: { force?: boolean }): Promise { @@ -130,58 +36,9 @@ export abstract class RateLimitServiceFetchQueue extends RateLimitServiceProvide } return } - this.isFetching = true - - try { - let shouldContinue = true - // Only user-forced refreshes bypass Retry-After; queued reruns inherit that force. - let cycleForce = options?.force ?? false - while (shouldContinue) { - const signal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchClaudeOnlyCycle(fetchSignal, { force: cycleForce }) - ) - shouldContinue = false - cycleForce = true - if (signal.aborted) { - break - } - if (this.fullFetchQueued) { - this.fullFetchQueued = false - const fullSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchAllCycle(fetchSignal, { force: true }) - ) - if (fullSignal.aborted) { - break - } - continue - } - if (this.claudeOnlyFetchQueued) { - this.claudeOnlyFetchQueued = false - shouldContinue = true - } - if (this.codexOnlyFetchQueued) { - this.codexOnlyFetchQueued = false - const codexSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchCodexOnlyCycle(fetchSignal) - ) - if (codexSignal.aborted) { - break - } - } - if (this.grokOnlyFetchQueued) { - this.grokOnlyFetchQueued = false - const grokSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchGrokOnlyCycle(fetchSignal) - ) - if (grokSignal.aborted) { - break - } - } - } - } finally { - this.isFetching = false - this.resolveFetchIdleWaiters() - } + return this.runFetchQueue((signal) => + this.runFetchClaudeOnlyCycle(signal, { force: options?.force ?? false }) + ) } protected async fetchGrokOnly(options?: { force?: boolean }): Promise { @@ -192,54 +49,44 @@ export abstract class RateLimitServiceFetchQueue extends RateLimitServiceProvide } return } - this.isFetching = true + return this.runFetchQueue((signal) => this.runFetchGrokOnlyCycle(signal)) + } + private async runFetchQueue(first: FetchCycle): Promise { + this.isFetching = true try { - let shouldContinue = true - while (shouldContinue) { - const signal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchGrokOnlyCycle(fetchSignal) - ) - shouldContinue = false + let cycle: FetchCycle | null = first + while (cycle) { + const signal = await this.runWithFetchAbortSignal(cycle) if (signal.aborted) { break } - if (this.fullFetchQueued) { - this.fullFetchQueued = false - const fullSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchAllCycle(fetchSignal, { force: true }) - ) - if (fullSignal.aborted) { - break - } - continue - } - if (this.grokOnlyFetchQueued) { - this.grokOnlyFetchQueued = false - shouldContinue = true - } - if (this.codexOnlyFetchQueued) { - this.codexOnlyFetchQueued = false - const codexSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchCodexOnlyCycle(fetchSignal) - ) - if (codexSignal.aborted) { - break - } - } - if (this.claudeOnlyFetchQueued) { - this.claudeOnlyFetchQueued = false - const claudeSignal = await this.runWithFetchAbortSignal((fetchSignal) => - this.runFetchClaudeOnlyCycle(fetchSignal, { force: true }) - ) - if (claudeSignal.aborted) { - break - } - } + // Re-read every flag after each cycle: a request can queue while any cycle runs. + cycle = this.takeQueuedFetchCycle() } } finally { this.isFetching = false this.resolveFetchIdleWaiters() } } + + private takeQueuedFetchCycle(): FetchCycle | null { + if (this.fullFetchQueued) { + this.fullFetchQueued = false + return (signal) => this.runFetchAllCycle(signal, { force: true }) + } + if (this.codexOnlyFetchQueued) { + this.codexOnlyFetchQueued = false + return (signal) => this.runFetchCodexOnlyCycle(signal) + } + if (this.claudeOnlyFetchQueued) { + this.claudeOnlyFetchQueued = false + return (signal) => this.runFetchClaudeOnlyCycle(signal, { force: true }) + } + if (this.grokOnlyFetchQueued) { + this.grokOnlyFetchQueued = false + return (signal) => this.runFetchGrokOnlyCycle(signal) + } + return null + } } diff --git a/src/main/rate-limits/service/service-full-cycle-preparation.ts b/src/main/rate-limits/service/service-full-cycle-preparation.ts index fc9c8186b05..b9ed5efd4e8 100644 --- a/src/main/rate-limits/service/service-full-cycle-preparation.ts +++ b/src/main/rate-limits/service/service-full-cycle-preparation.ts @@ -153,7 +153,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ this.updateState({ ...previousState, - claude: this.withFetchingStatus(previousState.claude, 'claude'), + claude: this.claudeStateAtCycleStart(previousState.claude), // A gated slot makes no attempt and cannot settle a fetching chip. codex: codexFetchGated ? codexStateBeforeFetch @@ -220,7 +220,9 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ // Live display does not waive automated Retry-After gates. const claudeFetchGated = - !options?.force && this.shouldSkipAutomatedFetch('claude', previousState.claude) + !this.isClaudeOAuthUsageEnabled() || + claudeGeneration !== this.claudeFetchGeneration || + (!options?.force && this.shouldSkipAutomatedFetch('claude', previousState.claude)) const [claudeResult, codexResult, geminiResult, opencodeGoResult, kimiResult, miniMaxResult] = await Promise.allSettled([ @@ -231,7 +233,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation), allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement(), networkProxySettings: this.networkProxySettingsResolver?.(), - signal + signal: this.claudeUsageFetchSignal(signal) }), codexFetchGated ? Promise.resolve(previousState.codex as ProviderRateLimits) diff --git a/src/main/rate-limits/service/service-inactive-accounts.ts b/src/main/rate-limits/service/service-inactive-accounts.ts index ffcaba04f59..45c171dc0e6 100644 --- a/src/main/rate-limits/service/service-inactive-accounts.ts +++ b/src/main/rate-limits/service/service-inactive-accounts.ts @@ -6,6 +6,9 @@ import { delayUnlessAborted } from '../../../shared/abort-aware-delay' export abstract class RateLimitServiceInactiveAccounts extends RateLimitServicePolling { async fetchInactiveClaudeAccountsOnOpen(): Promise { + if (!this.isClaudeOAuthUsageEnabled()) { + return + } if (Date.now() - this.lastInactiveClaudeFetchAt < INACTIVE_FETCH_DEBOUNCE_MS) { return } @@ -21,7 +24,7 @@ export abstract class RateLimitServiceInactiveAccounts extends RateLimitServiceP } const fetchGeneration = this.inactiveClaudeAccountsGeneration const controller = this.beginFetchCycle() - const signal = controller.signal + const signal = this.claudeUsageFetchSignal(controller.signal) for (const account of accounts) { this.inactiveClaudeFetching.add(account.id) diff --git a/src/main/rate-limits/service/service-polling.ts b/src/main/rate-limits/service/service-polling.ts index 0a6e7421d3c..33da0aa57a8 100644 --- a/src/main/rate-limits/service/service-polling.ts +++ b/src/main/rate-limits/service/service-polling.ts @@ -87,6 +87,7 @@ export abstract class RateLimitServicePolling extends RateLimitServiceFetchQueue const museEnabled = this.museUsageEnabledResolver?.() ?? true return Object.entries(byProvider) .filter(([provider]) => provider !== 'muse' || museEnabled) + .filter(([provider]) => provider !== 'claude' || this.isClaudeOAuthUsageEnabled()) .map(([provider, limits]) => ({ provider: provider as ActiveRateLimitProvider, limits diff --git a/src/main/rate-limits/service/service-provider-cycles.ts b/src/main/rate-limits/service/service-provider-cycles.ts index 3218091ead4..42a8be46035 100644 --- a/src/main/rate-limits/service/service-provider-cycles.ts +++ b/src/main/rate-limits/service/service-provider-cycles.ts @@ -94,10 +94,15 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul // Why: capture before the resolver await so an account switch during it invalidates both the snapshot and the state apply. const claudeGeneration = this.claudeFetchGeneration const claudeAuthPreparation = await this.claudeAuthPreparationResolver?.(claudeTarget) - if (signal.aborted) { + if (signal.aborted || claudeGeneration !== this.claudeFetchGeneration) { return } this.rememberClaudeAuthSnapshot(claudeAuthPreparation, claudeGeneration, claudeTarget) + // After the snapshot: statusLine posts are dropped until one names the selected account. + if (!this.isClaudeOAuthUsageEnabled()) { + this.updateState({ ...this.state, claude: this.claudeUsageWithoutOAuth() }) + return + } const claudeProvenance = claudeAuthPreparation?.provenance ?? 'system' const previousState = this.state @@ -111,7 +116,7 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation), allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement(), networkProxySettings: this.networkProxySettingsResolver?.(), - signal + signal: this.claudeUsageFetchSignal(signal) }).catch((err): ProviderRateLimits => ({ provider: 'claude', session: null, diff --git a/src/main/rate-limits/service/service-refresh-orchestration.test.ts b/src/main/rate-limits/service/service-refresh-orchestration.test.ts index 9a347132d93..28afdea75ff 100644 --- a/src/main/rate-limits/service/service-refresh-orchestration.test.ts +++ b/src/main/rate-limits/service/service-refresh-orchestration.test.ts @@ -1,12 +1,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ProviderRateLimits } from '../../../shared/rate-limit-types' import { RateLimitService } from './rate-limit-service' import { fetchActiveClaudeRateLimits } from '../providers/claude/claude-active-usage-fetch' +import { fetchInactiveClaudeAccountUsage } from '../providers/claude/claude-managed-account-usage' import { fetchCodexRateLimits } from '../providers/codex/codex-fetcher' -import { fetchZcodeRateLimits } from '../providers/zcode/zcode-usage-fetcher' -import { fetchOpenCodeGoUsage } from '../providers/opencode-go/opencode-go-usage-source-selection' import { - errorProvider, + deferred, flushMicrotasks, + mockFreshBackgroundProviderFetches, okProvider, resetRateLimitProviderMocks } from './rate-limit-service-test-harness' @@ -78,103 +79,231 @@ describe('RateLimitService', () => { vi.mocked(fetchCodexRateLimits).mockResolvedValue(okProvider('codex', 0, 1_000)) }) - it('does not keep a previous ZCode account quota after a failed account switch', async () => { - vi.mocked(fetchZcodeRateLimits) - .mockResolvedValueOnce({ - ...okProvider('zcode', 42), - usageMetadata: { source: 'web', authProvenance: 'account-a' } - }) - .mockResolvedValueOnce({ - ...errorProvider('zcode', 'request failed'), - usageMetadata: { source: 'web', authProvenance: 'account-b', failureKind: 'network' } - }) + it('reads the account picked by a second switch made during a refresh', async () => { const service = new RateLimitService() - - await service.refresh() - await service.refresh() - - expect(service.getState().zcode?.status).toBe('error') - expect(service.getState().zcode?.session).toBeNull() + const reads = [deferred(), deferred()] + vi.mocked(fetchActiveClaudeRateLimits) + .mockReturnValueOnce(reads[0].promise) + .mockReturnValueOnce(reads[1].promise) + .mockResolvedValueOnce(okProvider('claude', 55)) + void service.refresh() + await flushMicrotasks(20) + void service.refreshForClaudeAccountChange('acct-a') + reads[0].resolve(okProvider('claude', 0)) + await flushMicrotasks(40) + // The first switch's rerun is reading when the user switches again. + void service.refreshForClaudeAccountChange('acct-b') + reads[1].resolve(okProvider('claude', 11)) + await flushMicrotasks(60) + expect(service.getState().claude?.session?.usedPercent).toBe(55) }) - it('discards stale data when Workspace ID override is changed', async () => { + it('keeps live Claude usage through refreshes without reading OAuth usage when disabled', async () => { + mockFreshBackgroundProviderFetches() const service = new RateLimitService() - let workspaceId = 'wrk_A' - service.setOpenCodeGoConfigResolver(() => ({ - sessionCookie: 'session=valid', - workspaceIdOverride: workspaceId + service.setClaudeOAuthUsageEnabledResolver(() => false) + service.setInactiveClaudeAccountsResolver(() => [{ id: 'other' }]) + let home = '/claude/account-a' + service.setClaudeAuthPreparationResolver(async () => ({ + configDir: home, + envPatch: { CLAUDE_CONFIG_DIR: home }, + provenance: home })) - - vi.mocked(fetchOpenCodeGoUsage).mockResolvedValue(okProvider('opencode-go', 40, Date.now())) - await service.refresh() - expect(service.getState().opencodeGo?.session?.usedPercent).toBe(40) - - workspaceId = 'wrk_B' - vi.mocked(fetchOpenCodeGoUsage).mockResolvedValue(okProvider('opencode-go', 10, Date.now())) - await service.refresh() - expect(service.getState().opencodeGo?.session?.usedPercent).toBe(10) - - // Switching to automatic mode must discard workspace B's data even if the first refresh fails. - workspaceId = '' - vi.mocked(fetchOpenCodeGoUsage).mockResolvedValue({ - provider: 'opencode-go', + service.start({ fetchImmediately: false }) + await flushMicrotasks(20) + service.stop() + expect(service.getState().claude).toMatchObject({ session: null, weekly: null, - monthly: null, - updatedAt: Date.now(), - error: 'No workspace ID found', - status: 'error' + status: 'unavailable' + }) + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/account-a', + fiveHour: { used_percentage: 33 }, + sevenDay: { used_percentage: 62 } + }) + await service.refreshClaudeForTarget() + await service.refresh() + await service.fetchInactiveClaudeAccountsOnOpen() + + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 33 }, + weekly: { usedPercent: 62 }, + status: 'ok', + usageMetadata: { source: 'live-session' } + }) + expect(service.getState().inactiveClaudeAccounts).toEqual([]) + expect(service.usageReadingAccount('claude')).toEqual({ + home: '/claude/account-a', + provenance: '/claude/account-a' + }) + expect(service.requestUsageReading('claude')).toBe(false) + expect(fetchActiveClaudeRateLimits).not.toHaveBeenCalled() + expect(fetchInactiveClaudeAccountUsage).not.toHaveBeenCalled() + + home = '/claude/account-b' + await service.refreshForClaudeAccountChange('outgoing') + expect(service.getState().claude?.session).toBeNull() + expect(service.getState().claude?.status).toBe('unavailable') + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/account-b', + fiveHour: { used_percentage: 12 }, + sevenDay: null + }) + expect(service.getState().claude?.session?.usedPercent).toBe(12) + expect(service.usageReadingAccount('claude')).toEqual({ + home: '/claude/account-b', + provenance: '/claude/account-b' + }) + }) + + it('cancels pending Claude usage and rejects its reply even after polling is enabled again', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + const started = deferred() + const reply = deferred() + vi.mocked(fetchActiveClaudeRateLimits).mockImplementationOnce((options) => { + started.resolve(options?.signal) + return reply.promise + }) + const refresh = service.refresh() + const signal = await started.promise + + enabled = false + service.discardClaudeOAuthUsage() + expect(signal?.aborted).toBe(true) + service.ingestLiveClaudeRateLimits({ + configDir: null, + fiveHour: { used_percentage: 41 }, + sevenDay: null + }) + enabled = true + reply.resolve(okProvider('claude', 90)) + await refresh + + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 41 }, + status: 'ok', + usageMetadata: { source: 'live-session' } + }) + }) + + it('retains only terminal-observed windows when disabling OAuth-enriched usage', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce({ + ...okProvider('claude', 20), + weekly: { usedPercent: 50, windowMinutes: 10080, resetsAt: null, resetDescription: null }, + fableWeekly: { + usedPercent: 70, + windowMinutes: 10080, + resetsAt: null, + resetDescription: null + }, + extraUsage: { + unit: 'credits', + enabled: true, + balance: 100, + unlimited: false, + disabledReason: null, + resetsAt: null + } }) await service.refresh() - const state = service.getState() - expect(state.opencodeGo?.status).toBe('error') - expect(state.opencodeGo?.session).toBeNull() - expect(state.opencodeGo?.error).toBe('No workspace ID found') + service.ingestLiveClaudeRateLimits({ + configDir: null, + fiveHour: { used_percentage: 35 }, + sevenDay: null + }) + expect(service.getState().claude?.weekly?.usedPercent).toBe(50) + + enabled = false + service.discardClaudeOAuthUsage() + await service.refresh() + + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 35 }, + weekly: null, + usageMetadata: { source: 'live-session' } + }) + expect(service.getState().claude?.fableWeekly).toBeFalsy() + expect(service.getState().claude?.extraUsage).toBeFalsy() + await service.refreshForClaudeAccountChange('outgoing') + expect(service.getState().claude?.session).toBeNull() }) - it('keeps automatic usage readings inside a failing provider backoff', async () => { - vi.mocked(fetchCodexRateLimits).mockResolvedValue(errorProvider('codex', 'probe failed')) + it('discards pending inactive-account usage when polling is disabled', async () => { const service = new RateLimitService() - service.requestUsageReading('codex') - await flushMicrotasks(20) - expect(vi.mocked(fetchCodexRateLimits)).toHaveBeenCalledTimes(1) - // That failure starts the backoff the poller keeps; an automatic read waits it out. - service.requestUsageReading('codex') - await flushMicrotasks(20) - expect(vi.mocked(fetchCodexRateLimits)).toHaveBeenCalledTimes(1) + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + service.setInactiveClaudeAccountsResolver(() => [{ id: 'other' }, { id: 'another' }]) + const started = deferred() + const reply = deferred() + vi.mocked(fetchInactiveClaudeAccountUsage).mockImplementationOnce((_account, options) => { + started.resolve(options?.signal) + return reply.promise + }) + const refresh = service.fetchInactiveClaudeAccountsOnOpen() + const signal = await started.promise + + enabled = false + service.discardClaudeOAuthUsage() + expect(signal?.aborted).toBe(true) + enabled = true + reply.resolve(okProvider('claude', 90)) + await refresh + + expect(service.getState().inactiveClaudeAccounts).toEqual([]) + expect(service.getState().claude).toMatchObject({ + session: null, + weekly: null, + status: 'unavailable' + }) }) - it('admits an automatic read for the account selected after a switch, both ways', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - try { - const start = 1_000_000 - let home = '/accounts/default/.codex' + it.each(['all', 'claude'] as const)( + 'does not revive a canceled %s request still preparing account attribution', + async (cycle) => { + mockFreshBackgroundProviderFetches() const service = new RateLimitService() - service.setCodexHomePathResolver(() => ({ kind: 'ready', codexHomePath: home })) - vi.mocked(fetchCodexRateLimits).mockClear() - const automaticRead = async (at: number) => { - vi.setSystemTime(at) - vi.mocked(fetchCodexRateLimits).mockResolvedValue(okProvider('codex', 10, at)) - service.requestUsageReading('codex', { notWithinMs: 600_000 }) - await flushMicrotasks(20) - } - // The other account is selected and its switch-time read fails. - const switchTo = async (next: string, at: number) => { - vi.setSystemTime(at) - home = next - vi.mocked(fetchCodexRateLimits).mockResolvedValue(errorProvider('codex', 'probe failed')) - await service.refreshForCodexAccountChange(null) - } - await automaticRead(start) - await switchTo('/accounts/managed-b', start + 60_000) - // Past the failure backoff and well inside the default account's ten minutes. - await automaticRead(start + 90_000) - expect(vi.mocked(fetchCodexRateLimits)).toHaveBeenCalledTimes(3) - await switchTo('/accounts/default/.codex', start + 150_000) - await automaticRead(start + 180_000) - expect(vi.mocked(fetchCodexRateLimits)).toHaveBeenCalledTimes(5) - } finally { - vi.useRealTimers() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + const oldAuth = { configDir: '/claude/old', envPatch: {}, provenance: 'old' } + const preparation = deferred() + service.setClaudeAuthPreparationResolver( + vi + .fn() + .mockReturnValueOnce(preparation.promise) + .mockResolvedValue({ + configDir: '/claude/current', + envPatch: { CLAUDE_CONFIG_DIR: '/claude/current' }, + provenance: 'current' + }) + ) + const refresh = cycle === 'all' ? service.refresh() : service.refreshClaudeForTarget() + enabled = false + service.discardClaudeOAuthUsage() + enabled = true + preparation.resolve(oldAuth) + await refresh + + expect(fetchActiveClaudeRateLimits).not.toHaveBeenCalledWith( + expect.objectContaining({ authPreparation: oldAuth }) + ) + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/current', + fiveHour: { used_percentage: 15 }, + sevenDay: null + }) + expect(service.getState().claude?.session?.usedPercent).toBe(15) + expect(service.usageReadingAccount('claude')).toEqual({ + home: '/claude/current', + provenance: 'current' + }) } - }) + ) }) diff --git a/src/main/rate-limits/service/service-state.ts b/src/main/rate-limits/service/service-state.ts index 3b0b3c0d35a..f847392189c 100644 --- a/src/main/rate-limits/service/service-state.ts +++ b/src/main/rate-limits/service/service-state.ts @@ -17,6 +17,7 @@ import { type OpenCodeGoRateLimitConfig, type MiniMaxRateLimitConfig, type AntigravityUsageEnabledResolver, + type ClaudeOAuthUsageEnabledResolver, type MuseUsageEnabledResolver, type ZcodePlanRateLimitConfig, type GeminiCliOAuthEnabledResolver, @@ -90,10 +91,16 @@ export abstract class RateLimitServiceState { protected fetchIdleResolvers: (() => void)[] = [] protected codexFetchGeneration = 0 protected claudeFetchGeneration = 0 + protected claudeUsageAbortController = new AbortController() + protected liveClaudeUsage: ProviderRateLimits | null = null // Why: cached display receipts cannot establish when the selected account was last checked. protected lastClaudeCheckCompletedAt: number | null = null // Capture account attribution once per cycle instead of rerunning auth preparation on every post. - protected lastClaudeAuthSnapshot: { configDir: string | null; provenance: string } | null = null + protected lastClaudeAuthSnapshot: { + configDir: string | null + home: string | undefined + provenance: string + } | null = null /** Where the applied host-runtime Claude/Codex readings were taken. */ protected usageReadingAccounts: Partial< Record<'claude' | 'codex', { home: string; provenance: string }> @@ -122,6 +129,7 @@ export abstract class RateLimitServiceState { protected miniMaxConfigResolver: (() => MiniMaxRateLimitConfig) | null = null protected zcodePlanConfigResolver: (() => ZcodePlanRateLimitConfig) | null = null protected geminiCliOAuthEnabledResolver: GeminiCliOAuthEnabledResolver | null = null + protected claudeOAuthUsageEnabledResolver: ClaudeOAuthUsageEnabledResolver | null = null protected antigravityUsageEnabledResolver: AntigravityUsageEnabledResolver | null = null protected antigravityFetchTarget: LocalAccountRuntimeTarget = { runtime: 'host', wslDistro: null } protected antigravityAccountUsageRecorder: AntigravityAccountUsageRecorder | null = null diff --git a/src/main/rate-limits/service/service-types.ts b/src/main/rate-limits/service/service-types.ts index 7b02dda32e9..bb67e283a65 100644 --- a/src/main/rate-limits/service/service-types.ts +++ b/src/main/rate-limits/service/service-types.ts @@ -4,7 +4,7 @@ import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime import type { ClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' import type { KimiHomeResolution } from '../../kimi/kimi-runtime-home' import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' -import type { CodexRateLimitHomeResolution } from '../../codex-accounts/runtime-home-service-types' +import type { CodexRateLimitHomeResolution } from '../../codex-accounts/runtime-home/runtime-home-service-types' export type InactiveCodexHome = { kind: 'ready'; managedHomePath: string } | { kind: 'skip' } @@ -62,6 +62,7 @@ export type ZcodePlanResolvedConfig = { export type GeminiCliOAuthEnabledResolver = () => boolean export type AntigravityUsageEnabledResolver = () => boolean +export type ClaudeOAuthUsageEnabledResolver = () => boolean export type MuseUsageEnabledResolver = () => boolean export type ActiveRateLimitProvider = ProviderRateLimits['provider'] export type ActiveProviderState = { diff --git a/src/main/repository-icons/repo-icon-autodetect.ts b/src/main/repository-icons/repo-icon-autodetect.ts index 393672a9ef9..4d585178aeb 100644 --- a/src/main/repository-icons/repo-icon-autodetect.ts +++ b/src/main/repository-icons/repo-icon-autodetect.ts @@ -1,6 +1,6 @@ import { readFile, stat } from 'node:fs/promises' import type { ExecutionHostId } from '../../shared/execution-host' -import type { GitHubRepositoryIdentity } from '../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity } from '../../shared/github/repositories/repository-identity' import type { RepoKind } from '../../shared/repo-types' import { faviconUrlFromWebsite, diff --git a/src/main/repository-icons/repo-icon-file-detection.ts b/src/main/repository-icons/repo-icon-file-detection.ts index 1a60db840f2..9429280c3a4 100644 --- a/src/main/repository-icons/repo-icon-file-detection.ts +++ b/src/main/repository-icons/repo-icon-file-detection.ts @@ -2,7 +2,7 @@ import { readFile, stat } from 'node:fs/promises' import { buildImageDataUri } from '../../shared/file-preview/image-data-uri' import { MAX_REPO_ICON_UPLOAD_BYTES, type RepoIcon } from '../../shared/repo-icon' import type { ExecutionHostFilesystemRoute } from '../providers/execution-host-provider-dispatch' -import { detectImageFileSignature } from '../media/image-file-signature' +import { detectImageFileSignature } from '../../shared/image-file-signature' import { extractIconHref } from './repo-icon-source-href' import { iconHrefCandidates } from './repo-icon-href-candidates' import { joinWorktreeRelativePath } from '../runtime/files/paths/runtime-relative-paths' diff --git a/src/main/runtime/__fixtures__/main-layout-close-fixture.ts b/src/main/runtime/__fixtures__/main-layout-close-fixture.ts index 724c396f612..adc2c3979ae 100644 --- a/src/main/runtime/__fixtures__/main-layout-close-fixture.ts +++ b/src/main/runtime/__fixtures__/main-layout-close-fixture.ts @@ -1,6 +1,6 @@ import { expect, type Mock } from 'vitest' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' +import { collectLeafIds } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import type { LayoutApplyOutcome, LayoutCommand @@ -8,11 +8,11 @@ import type { import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { DurableProfileStateMutation } from '../../persistence/loading-store/store-runtime-state' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { isTerminalClose, keptOnWriteFailure -} from '../../persistence/terminal-topology/terminal-close-write-failure' +} from '../../persistence/terminal-topology/command-application/terminal-close-write-failure' type SessionCell = { get: () => WorkspaceSessionState diff --git a/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts b/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts index 96941027333..8aeb7a387fb 100644 --- a/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts +++ b/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts @@ -1,165 +1,6 @@ import { expect, it, vi } from 'vitest' import { createChatTabLayoutQueue } from './agent-session-tab-layout-queue' -const open = (sessionId: string) => ({ - worktreeId: 'wt', - change: { open: { sessionId, agent: 'codex' as const, tabId: `tab-${sessionId}` } } -}) - -it('settles continuous placement changes and drains the next worktree open', async () => { - const { getDefaultWorkspaceSession } = await import('../../../shared/constants') - const { withChatTabChanges } = await import('./agent-session-tab-layout') - const { applyCommandToSession } = - await import('../../persistence/terminal-topology/terminal-pane-admission') - let session = withChatTabChanges('local', getDefaultWorkspaceSession(), 'wt', [ - open('source').change, - open('B').change, - open('other').change - ])! - const group1 = session.tabGroups!['wt']![0]!.id - const applyNow = (command: Parameters[2]) => { - const result = applyCommandToSession('local', session, command) - session = result.session ?? session - return result.value - } - expect( - applyNow({ - type: 'splitGroup', - workspace: 'wt', - tabId: 'tab-other', - besideGroupId: group1, - direction: 'right' - }).ok - ).toBe(true) - const group2 = session.tabGroups!['wt']!.find((group) => group.id !== group1)!.id - let attempts = 0 - const written: string[] = [] - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const queue = createChatTabLayoutQueue({ - sessionOf: () => session, - hostIdOf: () => 'local', - apply: async (command, run) => { - if (command.type === 'openAgentSessionTab' && command.sessionId === 'child') { - attempts++ - expect( - applyNow({ - type: 'moveTab', - workspace: 'wt', - tabId: 'tab-source', - toGroupId: command.groupId === group1 ? group2 : group1, - index: 0 - }).ok - ).toBe(true) - } - const admitted = run?.admit([session]) !== false - // Let the uncapped regression fail without leaving its asynchronous loop running. - if (command.type === 'openAgentSessionTab' && command.sessionId === 'child' && attempts > 4) { - throw new Error('placement attempts did not settle') - } - if (!admitted) { - return { ok: false, code: 'tab_not_found' } - } - const result = applyNow(command) - if (result.ok && command.type === 'openAgentSessionTab') { - written.push(command.sessionId) - } - return result - } - }) - try { - queue([ - { - worktreeId: 'wt', - change: { - open: { - sessionId: 'child', - agent: 'codex', - tabId: 'tab-child', - placement: { afterTabId: 'agent-session:source' } - } - }, - eligible: () => true - } - ]) - await queue([{ ...open('next'), worktreeId: 'next-worktree' }]) - expect(attempts).toBe(4) - expect(written).toEqual(['next']) - expect(session.unifiedTabs?.['next-worktree']?.map((tab) => tab.entityId)).toEqual(['next']) - expect(queue.pendingOpens()).toEqual([]) - } finally { - warn.mockRestore() - } -}) - -it('checks admission inside the actual profile queue before replacement close effects, and does not freeze later writes', async () => { - const { fixture } = - await import('../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture') - const { applyWindowLayoutCommand } = await import('../terminal/layout/runtime-layout-apply') - const { store, authority } = await fixture() - const workspace = 'chat-inner-queue' - const opened = await store.applyLayoutCommand({ - type: 'openAgentSessionTab', - workspace, - sessionId: 'session-a', - agent: 'codex', - tabId: 'agent-chat-tab-v1-old' - }) - expect(opened.ok).toBe(true) - const gate = authority.pause() - const holding = store.runDurableMutation(() => { - store.updateSettings({ theme: 'dark' }) - return { value: undefined } - }) - await gate.started.promise - let current = true - const effects = vi.fn() - const entered = Promise.withResolvers(), - settled = Promise.withResolvers() - const queue = createChatTabLayoutQueue({ - sessionOf: () => store.getWorkspaceSession(), - hostIdOf: () => 'local', - apply: async (command, run) => { - entered.resolve() - try { - return await applyWindowLayoutCommand(store, () => ['local'], command, undefined, { - ...run, - onEffects: effects - }) - } finally { - settled.resolve() - } - } - }) - queue(() => [ - { - worktreeId: workspace, - change: { close: 'session-a', tabId: 'agent-chat-tab-v1-old' }, - eligible: () => current - } - ]) - await entered.promise - current = false - const before = authority.captures.length - gate.finish.resolve() - await holding - await settled.promise - expect(effects).not.toHaveBeenCalled() - expect(authority.captures.length).toBe(before) - expect(store.getWorkspaceSession().unifiedTabs?.[workspace]?.map((tab) => tab.id)).toEqual([ - 'agent-chat-tab-v1-old' - ]) - expect( - await applyWindowLayoutCommand( - store, - () => ['local'], - { type: 'closeTabs', workspace, tabIds: ['agent-chat-tab-v1-old'], force: true }, - undefined, - { admit: () => true } - ) - ).toMatchObject({ ok: true }) - expect(store.getWorkspaceSession().unifiedTabs?.[workspace] ?? []).toEqual([]) -}) - it('refuses a captured close when another actual holder now uses that id for a different session', async () => { const { fixture } = await import('../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture') diff --git a/src/main/runtime/agent-session/agent-session-tab-layout.ts b/src/main/runtime/agent-session/agent-session-tab-layout.ts index 713acd1e9bf..3e69855b1e4 100644 --- a/src/main/runtime/agent-session/agent-session-tab-layout.ts +++ b/src/main/runtime/agent-session/agent-session-tab-layout.ts @@ -3,11 +3,11 @@ import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' import type { ExecutionHostId } from '../../../shared/execution-host' import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/workspace-layout-minted-ids' +import { loadWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' import type { WorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-model' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save' +import { saveWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-save' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { randomUUID } from 'node:crypto' import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' diff --git a/src/main/runtime/agent-session/environment/host-account-launch-env-state.ts b/src/main/runtime/agent-session/environment/host-account-launch-env-state.ts index fb4ce68d467..370212121c2 100644 --- a/src/main/runtime/agent-session/environment/host-account-launch-env-state.ts +++ b/src/main/runtime/agent-session/environment/host-account-launch-env-state.ts @@ -1,6 +1,6 @@ import { retireAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' -import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/execution/commit-message-agent-environment' import { hostAccountLaunchEnvFor, type HostAccountLaunchEnv diff --git a/src/main/runtime/agent-session/environment/runtime-account-controller.ts b/src/main/runtime/agent-session/environment/runtime-account-controller.ts index a7a8ed17960..ecdae1f811a 100644 --- a/src/main/runtime/agent-session/environment/runtime-account-controller.ts +++ b/src/main/runtime/agent-session/environment/runtime-account-controller.ts @@ -10,7 +10,7 @@ import type { ManagedDataAccountsState } from '../../../../shared/managed-account-types' import type { CodexAccountService } from '../../../codex-accounts/service' -import type { CodexResetCreditRejectedBeforeProviderReason } from '../../../codex-accounts/codex-account-service-types' +import type { CodexResetCreditRejectedBeforeProviderReason } from '../../../codex-accounts/account-management/codex-account-service-types' import type { CodexAccountSelectionTarget } from '../../../../shared/codex-selection-lane' import type { RateLimitService } from '../../../rate-limits/service/rate-limit-service' import type { @@ -23,7 +23,7 @@ import type { RateLimitState } from '../../../../shared/rate-limit-types' import type { CodexResetCreditExpectedScope } from '../../../../shared/codex-reset-credit-scope' -import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/execution/commit-message-agent-environment' import { getClaudeSelectionTargetForAccount, getSelectedClaudeAccountIdForTarget, diff --git a/src/main/runtime/agent-session/environment/structured-agent-account-home.ts b/src/main/runtime/agent-session/environment/structured-agent-account-home.ts index bd6058eb775..10dd8071c33 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-account-home.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-account-home.ts @@ -3,7 +3,7 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { claudeRoutedHomeAsync } from '../../../claude-accounts/profiles/routing/claude-profile-routed-home' -import { normalizeCodexRuntimeSelection } from '../../../codex-accounts/runtime-selection' +import { normalizeCodexRuntimeSelection } from '../../../codex-accounts/account-management/runtime-selection' import { resolveOrcaManagedCodexHomePath, getSystemCodexHomePath diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts index bc51568ddc0..0935e71ddb3 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts @@ -22,7 +22,7 @@ const shell = vi.hoisted( nextSaved: [] }) ) -vi.mock('../../../startup/login-shell-environment', () => ({ +vi.mock('../../../startup/shell-environment/login-shell-environment', () => ({ resolveLoginShellEnvironment: async (options?: { startedAfter?: number }) => { if (options?.startedAfter !== undefined) { shell.current = { ...shell.next } diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index 0858371173e..256ce90d5ce 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -2,7 +2,7 @@ import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog import { loginShellEnvironmentRevision, resolveLoginShellEnvironment -} from '../../../startup/login-shell-environment' +} from '../../../startup/shell-environment/login-shell-environment' import { refreshAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { cachedPersistedWindowsPathSegments, diff --git a/src/main/runtime/agent-session/installation/runtime-structured-agent-host-env.test.ts b/src/main/runtime/agent-session/installation/runtime-structured-agent-host-env.test.ts deleted file mode 100644 index 744e51d8736..00000000000 --- a/src/main/runtime/agent-session/installation/runtime-structured-agent-host-env.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { RuntimeStructuredAgentHost } from './runtime-structured-agent-host' -import { resolveStructuredClaudeAccountHomePath } from '../environment/structured-agent-account-home' - -vi.mock('../../terminal/wait/terminal-wait-visible-probe', () => ({ - OrcaRuntimeWithStartTuiIdleVisibleReadProbe: class {} -})) -afterEach(() => vi.unstubAllGlobals()) - -abstract class LaunchRuntime extends RuntimeStructuredAgentHost { - configuredEnvironment() { - return this.structuredAgentLaunchEnv('claude', { - agentDefaultEnv: { claude: { claude_config_dir: '/configured/home' } } - }) - } -} - -it('uses the same configured Windows home for account identity, then honors the host account', async () => { - vi.stubGlobal('process', { ...process, platform: 'win32' }) - let host: Record = {} - const runtime: LaunchRuntime = Object.assign(Object.create(LaunchRuntime.prototype), { - accounts: { hostLaunchEnvFor: () => host } - }) - const accountHome = () => - resolveStructuredClaudeAccountHomePath({ - launchEnv: runtime.configuredEnvironment(), - wslDistro: null, - getClaudeConfigDirectory: () => '/fallback/home' - }) - expect(await accountHome()).toBe('/configured/home') - host = { CLAUDE_CONFIG_DIR: '/host/home' } - expect(runtime.configuredEnvironment()).toEqual({ CLAUDE_CONFIG_DIR: '/host/home' }) - expect(await accountHome()).toBe('/host/home') -}) diff --git a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts index c59f1d36e0c..281f1b67ec1 100644 --- a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts +++ b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts @@ -3,8 +3,8 @@ import type { StructuredAgentModelCatalogDeps } from './structured-agent-runtime import { resolveStructuredCodexAccountKind } from '../environment/structured-agent-account-home' import { nativeChatShellEnvironmentPolicy } from '../../../../shared/native-chat/native-chat-shell-environment' import { claudeStructuredAuthPolicyForSettings } from '../../../claude-accounts/runtime-auth/claude-structured-auth-policy' -import { resolveStructuredAgentCommand } from '../../../native-chat/structured-agent-command-resolution' -import { structuredAgentConfiguredArgs } from '../../../native-chat/structured-agent-configured-args' +import { resolveStructuredAgentCommand } from '../../../native-chat/agent-launch/structured-agent-command-resolution' +import { structuredAgentConfiguredArgs } from '../../../native-chat/agent-launch/structured-agent-configured-args' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import { resolveTuiAgentLaunchEnv } from '../../../../shared/agent-launch/choices/tui-agent-launch-defaults' diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts index a9c1b2a4d2d..a33e65abb18 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts @@ -25,7 +25,7 @@ import { claudeModelCatalogDiscovery, codexModelCatalogDiscovery } from '../model-catalog/structured-agent-model-catalog-discovery' -import { resolveStructuredAgentCommand } from '../../../native-chat/structured-agent-command-resolution' +import { resolveStructuredAgentCommand } from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' import type { StructuredAgentAccountHomeRequest, diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts index 13e82fd79dd..fd05fb5ef12 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts @@ -1,12 +1,12 @@ import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import type { applyStructuredCodexWorkspaceTrust } from '../../../agent-launch/trust/agent-workspace-trust-spawn' -import type { StructuredAgentCliConversations } from '../../../native-chat/structured-agent-cli-conversations' +import type { StructuredAgentCliConversations } from '../../../native-chat/conversation-adoption/structured-agent-cli-conversations' import type { StructuredAgentSessionAdapter, StructuredAgentSessionLifecycleEvent } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import type { StructuredAgentCommandSettings } from '../../../native-chat/structured-agent-command-resolution' +import type { StructuredAgentCommandSettings } from '../../../native-chat/agent-launch/structured-agent-command-resolution' import type { AcpHostBackendSettings } from '../../../acp/launch/acp-launch-contract' import type { StructuredAgentDefinition } from '../../../native-chat/agent-session-wire/providers/structured-agent-definition' import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-registrations.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-registrations.ts index fa247c73bac..c7273f87f2d 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-registrations.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-registrations.ts @@ -1,10 +1,10 @@ import { AcpAtRestCommandCatalog } from '../../../acp/discovery/acp-at-rest-commands' -import { resolveNativeChatVisualsSkillLocation } from '../../../native-chat/native-chat-visuals-skill-location' +import { resolveNativeChatVisualsSkillLocation } from '../../../native-chat/conversation-files/native-chat-visuals-skill-location' import { withSupportedCodexCli } from '../../../codex/structured/launch/codex-cli-installation-error' import { codexStructuredLaunchPart } from '../../../codex/structured/launch/codex-structured-launch-resolution' import { claudeStructuredLaunchPart } from '../../../claude/structured/launch/claude-structured-launch-resolution' -import { claudeNamingInvocation } from '../../../claude/claude-naming-invocation' -import { createClaudeCommandCatalogProbe } from '../../../claude/claude-command-catalog-probe' +import { claudeNamingInvocation } from '../../../claude/conversation-naming/claude-naming-invocation' +import { createClaudeCommandCatalogProbe } from '../../../claude/command-catalog/claude-command-catalog-probe' import { CodexStructuredSessionAdapter } from '../../../codex/structured/session-lifecycle/codex-structured-session-adapter' import { createCodexAtRestSkillCatalog } from '../../../codex/structured/catalog/codex-at-rest-skills-probe' import { CODEX_STRUCTURED_AGENT } from '../../../codex/structured/launch/codex-structured-agent-definition' diff --git a/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts b/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts index c583ebb4b55..5ca49b58601 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts @@ -9,7 +9,7 @@ import { withProviderNaming } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-provider-naming' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { scheduleNativeChatVisualsSweep } from '../../../native-chat/native-chat-visuals-sweep' +import { scheduleNativeChatVisualsSweep } from '../../../native-chat/conversation-files/native-chat-visuals-sweep' import type { InstalledRuntime } from '../structured-agent-session-runtime-teardown' import { AgentSessionRecoveryCapsule } from '../records/agent-session-recovery-capsule' import type { OpenedAgentSessionRecordStore } from '../records/agent-session-record-store-slot' @@ -114,41 +114,49 @@ export async function installOnJournal( onState: delivery.reconcile }) } - if (deps.onTurnAttention) { - const installed = host - const onTurnAttention = deps.onTurnAttention - installed.subscribeTurnCompletions({ - id: 'host-turn-attention', - includePrompts: true, - emit: (event) => onTurnAttention(event, installed.readStatusSummary) - }) - } - // Prewarm catalogs at runtime start for local and remote hosts. - const modelCatalog = host.deps.modelCatalog - installAgentSessionAttachments({ - stateDirectory: deps.stateDirectory, - store, - journalDatabase, - logger: deps.logger - }) - const stopVisualsSweep = deps.nativeChatVisuals - ? scheduleNativeChatVisualsSweep({ - stateDirectory: deps.stateDirectory, - listHeldSessionIds: () => (store.readOnly ? null : store.listHeldSessionIds()), - logger: deps.logger - }) - : undefined - const stopCommands = bindAtRestCommandContexts( - registrations.map(({ adapter }) => adapter.atRestCommands) - ) + let turnAttention: + | ReturnType> + | undefined + let stopTurnAttention: (() => void) | undefined + let stopVisualsSweep: (() => void) | undefined + let stopCommands: (() => void) | undefined let detachCatalog: (() => void) | undefined try { + turnAttention = deps.createTurnAttention?.() + if (turnAttention) { + const installed = host + const onTurnAttention = turnAttention.onTurnAttention + stopTurnAttention = installed.subscribeTurnCompletions({ + id: 'host-turn-attention', + includePrompts: true, + emit: (event) => onTurnAttention(event, installed.readStatusSummary) + }) + } + installAgentSessionAttachments({ + stateDirectory: deps.stateDirectory, + store, + journalDatabase, + logger: deps.logger + }) + stopVisualsSweep = deps.nativeChatVisuals + ? scheduleNativeChatVisualsSweep({ + stateDirectory: deps.stateDirectory, + listHeldSessionIds: () => (store.readOnly ? null : store.listHeldSessionIds()), + logger: deps.logger + }) + : undefined + stopCommands = bindAtRestCommandContexts( + registrations.map(({ adapter }) => adapter.atRestCommands) + ) detachCatalog = catalogOwner.attach({ store, host }) - void modelCatalog?.prewarm() + void host.deps.modelCatalog?.prewarm() setStructuredAgentSessionHost(host) + turnAttention?.start() } catch (error) { + turnAttention?.stop() + stopTurnAttention?.() detachCatalog?.() - stopCommands() + stopCommands?.() stopVisualsSweep?.() await providerNaming.stop() throw error @@ -159,9 +167,11 @@ export async function installOnJournal( journalDatabase, waitForRecovery: lifecycle.drain, stopBackgroundWork: () => { + turnAttention?.stop() + stopTurnAttention?.() const namingStopped = providerNaming.stop() detachCatalog?.() - stopCommands() + stopCommands?.() stopVisualsSweep?.() return namingStopped } diff --git a/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts index 34c77a1cf36..cfbc7432ef0 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts @@ -7,11 +7,11 @@ import type { StructuredAttentionMobileDelivery } from '../structured-agent-sess import type { StructuredAgentCommand, StructuredAgentCommandSettings -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' import type { NativeChatShellEnvironmentPolicy } from '../../../../shared/native-chat/native-chat-shell-environment' import type { ClaudeStructuredAuthPolicy } from '../../../claude-accounts/runtime-auth/claude-structured-auth-policy' import type { RuntimeAgentAccountHomeResolver } from '../model-catalog/structured-agent-model-catalog-wiring' -import type { ClaudeCliFlagSupport } from '../../../claude/claude-cli-flag-support' +import type { ClaudeCliFlagSupport } from '../../../claude/cli-capabilities/claude-cli-flag-support' import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import type { AgentSessionTurnCompletionEvent } from '../../../../shared/agent-session/view/agent-session-turn-completion-wire' @@ -78,10 +78,14 @@ export type StructuredAgentSessionRuntimeDeps = StructuredAgentSessionTransportO /** Host-owned phone delivery and reconciliation from the current journal projection. */ attentionDelivery?: StructuredAttentionMobileDelivery /** Every live turn completion and pending prompt, with the host's status at that edge. */ - onTurnAttention?: ( - event: AgentSessionTurnCompletionEvent, - readStatus: (sessionId: string) => AgentSessionStatusSummary | undefined - ) => void + createTurnAttention?: () => { + onTurnAttention: ( + event: AgentSessionTurnCompletionEvent, + readStatus: (sessionId: string) => AgentSessionStatusSummary | undefined + ) => void + start: () => void + stop: () => void + } /** The account home a structured launch would pin right now, for catalog * reads with no session record. Absent disables the catalog surface. */ resolveAgentAccountHome?: RuntimeAgentAccountHomeResolver diff --git a/src/main/runtime/agent-session/installation/structured-claude-runtime-adapter.ts b/src/main/runtime/agent-session/installation/structured-claude-runtime-adapter.ts index 3fd9aa4c1af..b393cf58ffb 100644 --- a/src/main/runtime/agent-session/installation/structured-claude-runtime-adapter.ts +++ b/src/main/runtime/agent-session/installation/structured-claude-runtime-adapter.ts @@ -15,11 +15,11 @@ import type { AgentSessionRecordStore } from '../records/agent-session-record-st import { ClaudeAtRestCommandCatalog, type ClaudeAtRestCommandsDeps -} from '../../../claude/claude-at-rest-commands' -import type { ClaudeCommandCatalogProbe } from '../../../claude/claude-command-catalog-probe' +} from '../../../claude/command-catalog/claude-at-rest-commands' +import type { ClaudeCommandCatalogProbe } from '../../../claude/command-catalog/claude-command-catalog-probe' import { openClaudeStreamJsonConnection } from '../../../claude/claude-stream-json-connection' -import type { ClaudeCliFlagSupport } from '../../../claude/claude-cli-flag-support' -import { prewarmClaudeCliFlags } from '../../../claude/claude-cli-flag-prewarm' +import type { ClaudeCliFlagSupport } from '../../../claude/cli-capabilities/claude-cli-flag-support' +import { prewarmClaudeCliFlags } from '../../../claude/cli-capabilities/claude-cli-flag-prewarm' export type StructuredClaudeRuntimeAdapterDeps = { store: AgentSessionRecordStore diff --git a/src/main/runtime/agent-session/installation/structured-claude-scripted-runtime-test-support.ts b/src/main/runtime/agent-session/installation/structured-claude-scripted-runtime-test-support.ts index 19036dcec59..553c214c5c2 100644 --- a/src/main/runtime/agent-session/installation/structured-claude-scripted-runtime-test-support.ts +++ b/src/main/runtime/agent-session/installation/structured-claude-scripted-runtime-test-support.ts @@ -3,7 +3,7 @@ import { CLAUDE_CLI_FLAG_PROBE_BUDGET_MS, createClaudeCliFlagSupport -} from '../../../claude/claude-cli-flag-support' +} from '../../../claude/cli-capabilities/claude-cli-flag-support' import { providerDiagnostic, withProviderDiagnostic @@ -17,7 +17,7 @@ import type { ClaudeStreamJsonLaunch, openClaudeStreamJsonConnection } from '../../../claude/claude-stream-json-connection' -import { runClaudeControl } from '../../../claude/claude-agent-sdk-control-requests' +import { runClaudeControl } from '../../../claude/sdk-transport/claude-agent-sdk-control-requests' import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' import type { AgentSessionAttachParams } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' import { hostTestAttachParams } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test-support.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test-support.ts index cf0b29098f4..4ff9b081463 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test-support.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test-support.ts @@ -21,8 +21,8 @@ import { codexStructuredLaunchPart, type CodexStructuredLaunchPartDeps } from '../../../codex/structured/launch/codex-structured-launch-resolution' -import type { PrepareNativeChatVisuals } from '../../../native-chat/native-chat-visuals-delivery' -import type { StructuredAgentCommandSettings } from '../../../native-chat/structured-agent-command-resolution' +import type { PrepareNativeChatVisuals } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' +import type { StructuredAgentCommandSettings } from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { PI_RPC_AGENT } from '../../../pi/rpc-agent-definition' import { piRpcLaunchPart, diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test.ts deleted file mode 100644 index 22d16a2a74a..00000000000 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCA_SCRUB_SAFE_PANE_ENV } from '../../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' -import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' -import { resolveProviderChildEnv } from '../../../provider-process/provider-process-launch' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities -} from '../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - createCodexStructuredLaunchResolver, - TEST_SPAWN_TOKEN -} from './structured-agent-launch-composition.test-support' - -afterEach(() => { - structuredWorkerIdentities.clear() -}) - -const INHERITED_PANE_ENV: Record = { - PATH: '/usr/bin:/bin', - HOME: '/home/work', - ORCA_PANE_KEY: 'tab_parent:parent-pane', - ORCA_TAB_ID: 'tab_parent', - ORCA_WORKTREE_ID: 'parent-worktree', - ORCA_WORKSPACE_ID: 'parent-workspace', - ORCA_TERMINAL_HANDLE: 'term_parent', - ORCA_AGENT_LAUNCH_TOKEN: 'parent-launch-token', - [ORCA_SCRUB_SAFE_PANE_ENV]: 'parent-scrub-safe-pane', - ORCA_AGENT_HOOK_PORT: '43123' -} - -function makeIdentity( - sessionId: string, - agent: 'claude' | 'codex' | 'grok' | 'pi' -): AgentSessionJournalIdentity { - return { - sessionId, - workspaceId: 'workspace-1', - hostId: LOCAL_EXECUTION_HOST_ID, - agent, - providerHandle: null - } -} - -function makeStore( - sessionId: string, - provider: 'claude' | 'codex' | 'grok' | 'pi', - accountHome: AgentSessionAccountHome -) { - const record = agentSessionRecordFixture({ - sessionId, - provider, - accountHome - }) - return { getRecord: () => record, pinLaunchDirectory: vi.fn() } -} - -function expectNoHostPaneIdentity(childEnv: NodeJS.ProcessEnv): void { - expect(childEnv).not.toHaveProperty('ORCA_PANE_KEY') - expect(childEnv).not.toHaveProperty('ORCA_TAB_ID') - expect(childEnv).not.toHaveProperty('ORCA_WORKTREE_ID') - expect(childEnv).not.toHaveProperty('ORCA_WORKSPACE_ID') - expect(childEnv).not.toHaveProperty('ORCA_AGENT_LAUNCH_TOKEN') - expect(childEnv).not.toHaveProperty(ORCA_SCRUB_SAFE_PANE_ENV) - expect(childEnv).not.toHaveProperty('ORCA_AGENT_HOOK_PORT') -} - -describe('structured agent launch composition pane-identity stripping', () => { - it("preserves a structured worker's own ORCA_TERMINAL_HANDLE while stripping host pane identity", async () => { - const sessionId = '00000000-0000-4000-8000-000000000005' - const workerHandle = mintStructuredWorkerHandle() - structuredWorkerIdentities.register({ - handle: workerHandle, - sessionId, - agent: 'codex', - paneKey: mintStructuredWorkerPaneKey(sessionId), - processIncarnation: `structured:${sessionId}`, - worktreeId: 'workspace-1', - hostScope: { kind: 'local', hostId: 'local' } - }) - - const workerLaunch = await createCodexStructuredLaunchResolver({ - store: makeStore(sessionId, 'codex', { - variable: 'CODEX_HOME', - path: '/home/work/.codex' - }), - resolveEnvironment: async () => ({ ...INHERITED_PANE_ENV }), - resolveCommand: () => ({ command: '/usr/local/bin/codex', prefixArgs: [] }), - resolveLaunchArgs: () => [] - })({ - identity: makeIdentity(sessionId, 'codex'), - spawnToken: TEST_SPAWN_TOKEN - }) - - const childEnv = resolveProviderChildEnv(workerLaunch, INHERITED_PANE_ENV) - expectNoHostPaneIdentity(childEnv) - expect(childEnv.ORCA_TERMINAL_HANDLE).toBe(workerHandle) - }) -}) diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts index 42463903dd5..892a19e48a9 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts @@ -6,12 +6,12 @@ import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecy import { isNativeLocalLocation } from '../../../../shared/execution-host' import type { StructuredAgentDefinition } from '../../../native-chat/agent-session-wire/providers/structured-agent-definition' import { agentDrivesSession } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-provider-support' -import type { StructuredAgentCommandSettings } from '../../../native-chat/structured-agent-command-resolution' +import type { StructuredAgentCommandSettings } from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { createNativeChatVisualsDelivery, type NativeChatVisualsLaunch, type PrepareNativeChatVisuals -} from '../../../native-chat/native-chat-visuals-delivery' +} from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { resolveAgentSessionLaunchDirectory } from '../agent-session-launch-directory' import type { AgentSessionRecordStore } from '../records/agent-session-record-store' import type { StructuredAgentAdapterContext } from '../installation/structured-agent-runtime-registration-types' diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts index d6c402cb949..743fe9c0667 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts @@ -16,13 +16,13 @@ import { resolveStructuredAgentSessionCreateSupport, warnStructuredAgentSessionCreateUnsupported, type StructuredAgentSessionCreateSupport -} from '../../../native-chat/structured-agent-session-create-support' +} from '../../../native-chat/agent-launch/structured-agent-session-create-support' import '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { isAgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' import { resolveAgainAfterRefreshOnMissingProgram, type StructuredAgentCommandSettings -} from '../../../native-chat/structured-agent-command-resolution' +} from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { structuredAgentRuntimeMetadata } from '../installation/structured-agent-runtime-metadata' import { refreshHostAgentBaseEnvironmentAfterMiss, diff --git a/src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts deleted file mode 100644 index 3900b2e8efa..00000000000 --- a/src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../../rpc/dispatcher' -import { STRUCTURED_AGENT_SESSION_REVEAL_METHODS } from '../../rpc/methods/structured-sessions/conversation/structured-agent-session-reveal' -import { STRUCTURED_AGENT_SESSION_CLOSE_METHOD } from '../../rpc/methods/structured-sessions/conversation/structured-agent-session-close-method' -import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/agent-session/agent-session-runtime-capabilities' -import { - B, - authorityProfile, - openAuthorityRuntime, - savedIds -} from './structured-agent-session-tab-authority.test-support' -import * as publication from '../../session-tabs/structured-session-tab-publication' -import { chatTabCommandsSettled } from '../../orca-runtime-tests/session-layout-apply.test-fixture' - -vi.mock('../../../claude/claude-cli-flag-prewarm', () => ({ - prewarmClaudeCliFlags: async () => undefined -})) - -it('does not resurrect a History tab when normal close commits before its publisher resumes', async () => { - const rig = await openAuthorityRuntime(await authorityProfile([], { records: [B], visible: [] })) - await rig.runtime.restoreStructuredAgentSessionTabs() - const rpc = new RpcDispatcher({ - runtime: rig.runtime, - methods: STRUCTURED_AGENT_SESSION_REVEAL_METHODS - }) - const events: string[] = [] - const admit = publication.admitStructuredSessionTabPublication - vi.spyOn(publication, 'admitStructuredSessionTabPublication').mockImplementationOnce( - async (...args) => { - const admitted = await admit(...args) - expect(rig.host.getSessionTabId(B)).toBe(admitted.tabId) - expect(rig.host.hasSession(B)).toBe(true) - events.push('show-committed') - // Forward real SHOW and close effects; hold only the opener's continuation after its currency read. - expect( - await STRUCTURED_AGENT_SESSION_CLOSE_METHOD.handler( - { sessionId: B }, - { - runtime: rig.runtime, - clientKind: 'mobile', - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY] - } - ) - ).toEqual({ ok: true }) - expect(rig.host.getSessionTabId(B)).toBeNull() - events.push('close-committed') - return admitted - } - ) - const reveal = await rpc.dispatch( - { - id: 'history-reveal', - authToken: 'token', - method: 'agentSession.reveal', - params: { sessionId: B, navigation: 'caller' } - }, - { - pairedDeviceId: 'phone', - clientKind: 'mobile', - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY] - } - ) - events.push('opener-settled') - await chatTabCommandsSettled() - expect(events).toEqual(['show-committed', 'close-committed', 'opener-settled']) - expect(rig.host.getSessionTabId(B)).toBeNull() - expect(rig.runtime.currentLocalStructuredSessionPresentation(B)).toBeNull() - expect(savedIds(rig)).toEqual([]) - expect(rig.host.listSessionTabs()).toEqual([]) - expect(rig.host.hasSession(B)).toBe(false) - expect(rig.store.getRecord(B)?.lease).toMatchObject({ - claimStatus: 'released', - ownerProcess: null, - reservedSpawnToken: null - }) - expect(rig.acquire).not.toHaveBeenCalled() - expect(reveal).toMatchObject({ ok: false }) -}) diff --git a/src/main/runtime/agent-session/lifecycle/structured-claude-thinking-display-refusal.test.ts b/src/main/runtime/agent-session/lifecycle/structured-claude-thinking-display-refusal.test.ts deleted file mode 100644 index 1a7e846a50d..00000000000 --- a/src/main/runtime/agent-session/lifecycle/structured-claude-thinking-display-refusal.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -// A real child, through the real SDK connection, refusing the thinking-display flag the way an -// older Claude CLI does: commander's message and exit code 1. -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { CLAUDE_STRUCTURED_BASE_OPTIONS } from '../../../claude/structured/launch/claude-structured-launch-resolution' -import { - CLAUDE_THINKING_DISPLAY_FLAG, - createClaudeCliFlagSupport -} from '../../../claude/claude-cli-flag-support' -import { openClaudeConnectionOf } from '../installation/structured-claude-runtime-adapter' - -const FAKE_CLI = join( - __dirname, - '../../..', - 'claude', - '__fixtures__', - 'claude-agent-sdk-scripted-cli.mjs' -) -const scratchDirs: string[] = [] - -afterEach(() => { - for (const dir of scratchDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -async function startRefusing(stderr: string) { - const dir = mkdtempSync(join(tmpdir(), 'claude-thinking-display-')) - scratchDirs.push(dir) - const scenarioPath = join(dir, 'scenario.json') - writeFileSync(scenarioPath, JSON.stringify({ steps: [{ stderr }, { exit: 1 }] })) - const env = { PATH: process.env.PATH ?? '', ORCA_SDK_CONTRACT_SCENARIO_PATH: scenarioPath } - const probe = vi.fn(async () => '2.1.280') - const support = createClaudeCliFlagSupport({ - probe, - keyOf: async (command, cwd) => `${command}\n${cwd}`, - budgetMs: 1_000, - now: () => performance.now() - }) - const flag = - (await support.check(CLAUDE_THINKING_DISPLAY_FLAG, { - command: FAKE_CLI, - cwd: dir, - env - })) === 'supported' - ? { 'thinking-display': 'summarized' } - : null - const { openConnection } = openClaudeConnectionOf({ claudeCliFlags: support }) - let exited: Error | null = null - const connection = await openConnection!( - { - pathToClaudeCodeExecutable: FAKE_CLI, - options: { - ...CLAUDE_STRUCTURED_BASE_OPTIONS, - extraArgs: { ...CLAUDE_STRUCTURED_BASE_OPTIONS.extraArgs, ...flag } - }, - cwd: dir, - env - }, - { onExit: (error) => (exited = error) } - ) - await vi.waitFor(() => expect(exited).not.toBeNull(), { timeout: 10_000 }) - await connection.close() - return { support, probe, flag, launch: { command: FAKE_CLI, cwd: dir, env } } -} - -describe('a Claude CLI that refuses the thinking-display flag', () => { - it('fails that one start as today, and the next launch skips the flag', async () => { - const { support, probe, flag, launch } = await startRefusing( - "error: unknown option '--thinking-display'\n" - ) - expect(flag).toEqual({ 'thinking-display': 'summarized' }) - await vi.waitFor(async () => - expect(await support.check(CLAUDE_THINKING_DISPLAY_FLAG, launch)).toBe('unsupported') - ) - expect(probe).toHaveBeenCalledTimes(1) - }) - - it('records nothing when the start failed for another reason', async () => { - const { support, launch } = await startRefusing('claude: not signed in\n') - await expect(support.check(CLAUDE_THINKING_DISPLAY_FLAG, launch)).resolves.toBe('supported') - }) -}) diff --git a/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts b/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts index a43701d9a9b..d0e7b232e90 100644 --- a/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts @@ -5,7 +5,7 @@ import { agentSessionProviderHandleChainHead } from '../../../../shared/agent-se import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { agentSessionPinnedLaunchDirectory } from '../records/agent-session-record-launch-directory' import { structuredAgentRuntimeMetadata } from '../installation/structured-agent-runtime-metadata' -import type { StructuredAgentTranscriptImport } from '../../../native-chat/structured-agent-cli-conversations' +import type { StructuredAgentTranscriptImport } from '../../../native-chat/conversation-adoption/structured-agent-cli-conversations' export type RecoveryContextCache = { key?: string diff --git a/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts b/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts index cbd1910d443..eb1f124e40f 100644 --- a/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts +++ b/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts @@ -6,7 +6,7 @@ import type { AcpLaunchSpec } from '../../../acp/launch/acp-launch-contract' import { createClaudeModelCatalogProbe, type ClaudeModelCatalogProbeDeps -} from '../../../claude/claude-model-catalog-probe' +} from '../../../claude/model-catalog/claude-model-catalog-probe' import { createCodexModelCatalogProbe } from '../../../codex/structured/catalog/codex-model-catalog-probe' import type { AgentModelCatalogDiscovery } from '../../../native-chat/agent-model-catalog/agent-model-catalog-discovery' import type { StructuredAgentModelCatalogContext } from '../installation/structured-agent-runtime-registration-types' diff --git a/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts b/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts index 99d388152ae..0340376ae9a 100644 --- a/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts +++ b/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts @@ -8,7 +8,7 @@ import { expect, it, vi } from 'vitest' import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import * as processSpawn from '../../../codex/app-server/codex-app-server-process-tree-kill' import { closeTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import { StructuredAgentSessionAdapterRouter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-router' import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { seedTestAgentSessionRecordStore } from '../records/agent-session-record-store-test-harness' diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts index c59b8c1b969..8aa358a8e67 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts @@ -7,7 +7,7 @@ import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routin import { claudeConfigDirEnvPatch, withoutInheritedClaudeConfigDir -} from '../../../claude/claude-config-dir-pin' +} from '../../../claude/structured/launch/claude-config-dir-pin' import { resolveClaudeStructuredLaunchHome } from '../../../claude/structured/launch/claude-structured-launch-home' import type { CommitMessageGenerationTarget } from '../../../text-generation/source-control-text-generation-types' diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts deleted file mode 100644 index 42e5379c62b..00000000000 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import { agentSessionRecordFixture } from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' - -import type { ExecutionHostId } from '../../../../shared/execution-host' -import { savedChatNamingCatalog } from '../../../../shared/chat-naming-catalog-work.test-fixture' -import type { SpawnSourceControlAgent } from '../../../text-generation/source-control-text-generation-types' - -import { structuredChatNamingDeps } from './structured-chat-naming-runtime' -import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' - -import type * as OwnedOpenCodeTask from '../../../opencode/text-tasks/opencode-owned-text-task' - -const boundary = vi.hoisted(() => ({ - spawn: vi.fn(), - native: vi.fn>(), - openCode: vi.fn( - async (_input: { cwd: string; env?: NodeJS.ProcessEnv; prompt: string }) => 'Owned title' - ), - account: vi.fn((_provider: string, id: string) => ({ - XDG_DATA_HOME: `/profiles/${id}/data`, - XDG_STATE_HOME: `/profiles/${id}/state` - })) -})) -vi.mock('../../../opencode/text-tasks/opencode-owned-text-task', async (importOriginal) => ({ - ...(await importOriginal()), - runOwnedOpenCodeTextTask: boundary.openCode -})) -vi.mock('../../../text-generation/source-control-agent-launch', () => ({ - spawnSourceControlAgent: boundary.spawn -})) -vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => ({ deps: { adapter: { generateText: boundary.native } } }) -})) -vi.mock('../../../managed-data-accounts/service', () => ({ - getManagedDataAccountService: () => ({ - restoreOriginalEnvironment: () => {}, - environmentForAccount: boundary.account - }) -})) -beforeEach(() => { - vi.clearAllMocks() - boundary.spawn.mockReset() - boundary.native.mockReset() - boundary.openCode.mockClear() - vi.stubEnv('ORCA_PI_SOURCE_AGENT_DIR', undefined) -}) -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -function rig() { - const settings = getDefaultSettings('/isolated') - settings.defaultTuiAgent = 'codex' - settings.sourceControlAi = savedChatNamingCatalog(0) - const env = { - PATH: '/usr/bin', - PI_CODING_AGENT_DIR: '/configured/pi', - OPENCODE_CONFIG_DIR: '/configured/oc', - OPENCODE_AUTH_CONTENT: 'current-account-sentinel' - } - const runtime = { - resolveWorkspace: vi.fn( - async (): Promise<{ path: string; executionHostId: ExecutionHostId }> => ({ - path: '/workspace/folder', - executionHostId: 'local' - }) - ), - resolveNamingEnvironment: vi.fn(async () => env), - getAgentEnvResolvers: () => ({ resolveBaseEnvironment: async () => env }), - workerTaskTitle: () => null, - retitleOpenTab: () => {} - } - return { - settings, - runtime, - deps: structuredChatNamingDeps(() => ({ getSettings: () => settings }), runtime, { - warn: vi.fn(), - error: vi.fn() - }) - } -} - -it.each(['opencode', 'opencode2'] as const)( - 'routes %s naming into the owned task with its selected account', - async (provider) => { - const state = rig() - const record = agentSessionRecordFixture() - record.provider = provider - record.accountHome = { - kind: 'opencode', - locator: { kind: 'managed', managedProfileId: 'recorded' } - } - expect(await state.deps.generate(record, 'Repair login')).toEqual({ name: 'Owned title' }) - expect(boundary.openCode).toHaveBeenCalledWith( - expect.objectContaining({ - cwd: '/workspace/folder', - prompt: expect.stringContaining('Repair login'), - env: expect.objectContaining({ - XDG_DATA_HOME: '/profiles/recorded/data', - XDG_STATE_HOME: '/profiles/recorded/state', - OPENCODE_AUTH_CONTENT: undefined - }) - }) - ) - expect(boundary.spawn).not.toHaveBeenCalled() - expect(boundary.account).toHaveBeenCalledWith('opencode', 'recorded') - } -) diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts index 88fb2bbc2ae..514828410a5 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts @@ -1,4 +1,4 @@ -import { ClaudeControlRequestTimeoutError } from '../../../claude/claude-agent-sdk-control-requests' +import { ClaudeControlRequestTimeoutError } from '../../../claude/sdk-transport/claude-agent-sdk-control-requests' import { normalizeSourceControlAiSettings } from '../../../../shared/source-control/ai/settings/source-control-ai-settings' import { resolveSourceControlActionRecipe, @@ -15,8 +15,8 @@ import type { AgentLaunchProfileSettings } from '../../../../shared/agent-launch import { chatNamingFailure } from '../../../../shared/chat-naming-failure-copy' import { agentSessionCurrentContextRows } from '../../../../shared/agent-session/agent-session-context-clear' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' -import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/commit-message-agent-environment' -import type { StructuredChatNamingDeps } from '../../../native-chat/structured-chat-naming' +import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/execution/commit-message-agent-environment' +import type { StructuredChatNamingDeps } from '../../../native-chat/conversation-naming/structured-chat-naming-types' import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { firstStructuredChatNamingPrompt } from '../../../../shared/structured-chat-naming-eligibility' @@ -24,10 +24,10 @@ import { firstStructuredAgentSessionPrompt } from '../../../../shared/agent-sess import { LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../../../shared/source-control/ai/generation/commit-message-host-key' import { generateConversationNameFromContext, - resolveTextGenerationParams + resolveCommitMessageSettings as resolveTextGenerationParams } from '../../../text-generation/commit-message-text-generation' import { resolveGenerationTarget } from '../../../agent-hooks/first-work/first-work-generation-target' -import { deferredStructuredChatTitle } from '../../../native-chat/structured-chat-title-handover' +import { deferredStructuredChatTitle } from '../../../native-chat/conversation-naming/structured-chat-title-handover' type StructuredChatNamingRuntime = { resolveWorkspace: ( @@ -181,8 +181,8 @@ export function structuredChatNamingDeps( }) const useChatAgent = !recipe.agentId && !recipe.agentArgs?.trim() const log = { scope: 'conversation-name', sessionId: record.sessionId } - // Copilot saves every run, so a naming run would sit in the user's Copilot history. - if (useChatAgent && record.provider === 'copilot') { + // These save every CLI run, so a naming run would sit in the user's own history. + if (useChatAgent && (record.provider === 'copilot' || record.provider === 'kimi')) { return null } if (useChatAgent && (record.provider === 'grok' || record.provider === 'antigravity')) { diff --git a/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts b/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts index 0a79b0e5f4c..6ee45edcae2 100644 --- a/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts +++ b/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts @@ -3,7 +3,7 @@ import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/pro import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { appendTranscriptEntries } from '../../../claude/claude-provider-session-rename' +import { appendTranscriptEntries } from '../../../claude/transcripts/claude-provider-session-rename' import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' import { fakeClaude } from '../../../claude/structured/claude-structured-session-test-support' import type { FakeConnection } from '../../../claude/structured/claude-structured-session-test-support' diff --git a/src/main/runtime/agent-session/ownership/agent-session-older-build-lease.test-fixture.ts b/src/main/runtime/agent-session/ownership/agent-session-older-build-lease.test-fixture.ts deleted file mode 100644 index d1cda09b043..00000000000 --- a/src/main/runtime/agent-session/ownership/agent-session-older-build-lease.test-fixture.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { PersistedAgentSessionLease } from '../../../../shared/agent-session/lifecycle/agent-session-legacy-handoff-lease' -import { - editPersistedTestAgentSessionStore, - readPersistedTestAgentSessionStore -} from '../records/agent-session-record-store-test-harness' - -/** Rewrites one lease on disk as an older build left it; this build's types cannot express it. */ -export async function writeOlderBuildLease( - stateDirectory: string, - sessionId: string, - fields: Partial -): Promise { - await editPersistedTestAgentSessionStore(stateDirectory, (persisted) => { - persisted.records[sessionId].lease = { ...persisted.records[sessionId].lease, ...fields } - }) -} - -export async function readPersistedLease( - stateDirectory: string, - sessionId: string -): Promise> { - return (await readPersistedTestAgentSessionStore(stateDirectory)).records[sessionId].lease -} diff --git a/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts b/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts index c0278d40d9d..cd54e93b6c3 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts @@ -1,5 +1,6 @@ import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionProviderHandleLink } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import { withAcquiredAgentSessionAccount, type ClaudeAccountRecipe @@ -21,9 +22,11 @@ export function createAgentSessionOwnerProof( now: number leaseTtlMs?: number accountAcquisition?: { generation: string; recipe: ClaudeAccountRecipe } + /** The account this runtime launched under, when the provider reports one. */ + launchedAccountHome?: AgentSessionAccountHome }): Promise => - mutate(args.sessionId, (record) => - withAcquiredAgentSessionAccount( + mutate(args.sessionId, (record) => { + const { launchedAccount: _previous, ...proved } = withAcquiredAgentSessionAccount( proveAgentSessionOwner({ record, fence: args.fence, @@ -33,5 +36,12 @@ export function createAgentSessionOwnerProof( }), args.accountAcquisition ) - ) + // A runtime that reports no account leaves no stale claim about where this fence ran. + return args.launchedAccountHome + ? { + ...proved, + launchedAccount: { fence: args.fence, accountHome: args.launchedAccountHome } + } + : proved + }) } diff --git a/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts b/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts index c3c92b863d7..d59c508115d 100644 --- a/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts +++ b/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts @@ -1,22 +1,20 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import '../../../../shared/worktree/host-qualified-identity' import '../../../../shared/ai-vault/search/ai-vault-search-test-fixture' -import '../../../ai-vault/structured-session-ownership.test-support' -import '../../../ai-vault/structured-session-ownership' +import '../../../ai-vault/structured-sessions/structured-session-ownership.test-support' +import '../../../ai-vault/structured-sessions/structured-session-ownership' import { hostTestState } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' import { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import '../../../native-chat/agent-session-journal/journal-store-factory' import { openTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { countStoreWork, scaleDirectory, scaleRecord } from './agent-session-scale.test-fixture' +import { scaleDirectory, scaleRecord } from './agent-session-scale.test-fixture' import '../../workspaces/references/runtime-reference-find' import '../../../../shared/workspace-attachments/workspace-reference-identity' import { createReferenceAgentIndex } from '../../workspaces/references/runtime-reference-agents' import { seedTestAgentSessionRecordStore, - openTestAgentSessionRecordStore, - editPersistedTestAgentSessionStore, - readPersistedTestAgentSessionStore + openTestAgentSessionRecordStore } from './agent-session-record-store-test-harness' import { OrchestrationDb } from '../../orchestration/db/orchestration-db' import '../../orchestration/db/contract-constants' @@ -61,101 +59,6 @@ function clearedRecord(sessionId: string, successor: string): AgentSessionRecord } describe('real conversation inventory work', () => { - it.each([10, 100])('visits %i unreadable rows once per audience inventory', async (u) => { - const root = await scaleDirectory() - const healthy = Array.from({ length: 10 }, (_, i) => scaleRecord(`healthy-u-${i}`)) - const unreadable = Array.from({ length: u }, (_, i) => scaleRecord(`unreadable-u-${i}`)) - const retained = unreadable.filter((_, i) => i % 2 === 0) - await seedTestAgentSessionRecordStore(root, { - records: [...healthy, ...unreadable], - sessionTabs: [...healthy, ...unreadable].map(({ sessionId }) => ({ - sessionId, - tabId: `tab-${sessionId}` - })) - }) - await editPersistedTestAgentSessionStore(root, (state) => { - unreadable.forEach(({ sessionId }, i) => { - if (i % 2 === 0) { - Object.assign(state.records[sessionId].lease, { minimumNextFence: 'bad' }) - } else { - Object.assign(state.records[sessionId], { providerHandleChain: 'bad' }) - } - }) - }) - const raw = await readPersistedTestAgentSessionStore(root) - const store = await openTestAgentSessionRecordStore(root) - const host = new StructuredAgentSessionHost({ - ...hostTestState().host.deps, - store, - journalDatabase: openTestJournalHostDatabase(root) - }) - const ids = new Set(unreadable.map(({ sessionId }) => sessionId)) - const work = countStoreWork(store) - const inventories = vi.mocked(store.listConversations) - // Default spy executes native flatMap and its production callback on every dense input row. - const flatten = vi.spyOn(Array.prototype, 'flatMap') - try { - for (let repeat = 1; repeat <= 3; repeat++) { - expect(host.knownAgentIds()).toContain('claude') - expect(work.counts).toMatchObject({ - inventories: repeat, - views: 10 * repeat, - clones: 0, - decodes: 0 - }) - } - const scans = flatten.mock.contexts - .map((rows, i) => - Array.isArray(rows) && - rows.length === u && - rows.every( - (row: unknown) => - typeof row === 'object' && - row !== null && - 'raw' in row && - typeof row.raw === 'object' && - row.raw !== null && - 'sessionId' in row.raw && - typeof row.raw.sessionId === 'string' && - ids.has(row.raw.sessionId) - ) - ? i - : -1 - ) - .filter((i) => i >= 0) - expect(scans).toHaveLength(3) - for (const i of scans) { - expect(flatten.mock.contexts[i]).toMatchObject( - unreadable.map(({ sessionId }) => ({ raw: { sessionId } })) - ) - expect(flatten.mock.results[i]).toEqual({ - type: 'return', - value: retained.map(({ sessionId }) => store.getConversation(sessionId)) - }) - } - expect(inventories.mock.results.map((result) => result.value)).toEqual( - Array.from({ length: 3 }, () => - [...healthy, ...retained].map(({ sessionId }) => store.getConversation(sessionId)) - ) - ) - } finally { - flatten.mockRestore() - } - expect(store.getVisibleSessionTabIndex().sessionIds).toEqual( - [...healthy, ...retained].map(({ sessionId }) => sessionId) - ) - for (const [i, { sessionId }] of unreadable.entries()) { - expect(store.getConversation(sessionId)?.sessionId ?? null).toBe(i % 2 ? null : sessionId) - expect(store.getRecord(sessionId)).toBeNull() - expect(() => store.requireWritableRecord(sessionId)).toThrow() - } - await store.setConversationName(healthy[0]!.sessionId, 'unrelated update') - const after = await readPersistedTestAgentSessionStore(root) - for (const { sessionId } of unreadable) { - expect(after.records[sessionId]).toEqual(raw.records[sessionId]) - } - }) - it('keeps global worker identity separate from candidate inventory and retains closure/loop outcomes', async () => { const rootId = testOrcaSessionId('global-root') const successor = testOrcaSessionId('visible-successor') diff --git a/src/main/runtime/agent-session/records/agent-session-provider-alias-index.ts b/src/main/runtime/agent-session/records/agent-session-provider-alias-index.ts new file mode 100644 index 00000000000..b3f34986807 --- /dev/null +++ b/src/main/runtime/agent-session/records/agent-session-provider-alias-index.ts @@ -0,0 +1,101 @@ +import type { AgentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { + getAgentSessionConversation, + listAgentSessionConversations, + type AgentSessionStoreState +} from './agent-session-store-state' +import { AgentSessionDraftRecords } from './agent-session-store-draft' + +/** Provider-native session ids of the loaded chats, mapped to the chats whose handle chains name + * them: built once per store authority, then kept by committed record writes, so a recipient's + * provider-id question never walks the history. Derived only; nothing is saved. */ +export class AgentSessionProviderAliasIndex { + private readonly owners = new Map>() + private readonly aliasesBySession = new Map() + /** Each chat's place in listing order (readable records, then unreadable ones), mirrored from + * the store's maps so a shared alias picks its owner among its owners alone. */ + private readonly readableOrder = new Map() + private readonly unreadableOrder = new Map() + private nextReadable = 0 + + constructor(state: AgentSessionStoreState) { + for (const sessionId of state.records.keys()) { + this.readableOrder.set(sessionId, this.nextReadable++) + } + for (const sessionId of state.unreadableRecords.keys()) { + this.unreadableOrder.set(sessionId, this.unreadableOrder.size) + } + for (const view of listAgentSessionConversations(state)) { + this.add(view) + } + } + + /** Follows one committed transaction: only the written records' places and aliases move. */ + applyCommitted( + draft: AgentSessionStoreState, + records: { upsert: readonly (readonly [string, string])[]; remove: readonly string[] } + ): void { + // Keys the draft appended take the end, in its order; every other key keeps its place. + const appended = + draft.records instanceof AgentSessionDraftRecords + ? draft.records.appended + : records.upsert.map(([id]) => id).filter((id) => !this.readableOrder.has(id)) + for (const sessionId of appended) { + this.readableOrder.delete(sessionId) + if (draft.records.has(sessionId)) { + this.readableOrder.set(sessionId, this.nextReadable++) + } + } + for (const sessionId of records.remove) { + this.readableOrder.delete(sessionId) + } + for (const sessionId of [...records.upsert.map(([id]) => id), ...records.remove]) { + this.remove(sessionId) + const view = getAgentSessionConversation(draft, sessionId) + if (view) { + this.add(view) + } + } + } + + /** The chat naming `nativeId`; with several, the first in listing order, as a full scan picks. */ + owner(nativeId: string): string | null { + let first: string | null = null + for (const sessionId of this.owners.get(nativeId) ?? []) { + if (first === null || this.precedes(sessionId, first)) { + first = sessionId + } + } + return first + } + + private precedes(a: string, b: string): boolean { + const readableA = this.readableOrder.get(a) + const readableB = this.readableOrder.get(b) + if (readableA !== undefined || readableB !== undefined) { + return readableB === undefined || (readableA !== undefined && readableA < readableB) + } + return (this.unreadableOrder.get(a) ?? Infinity) < (this.unreadableOrder.get(b) ?? Infinity) + } + + private add(view: AgentSessionConversationView): void { + const aliases = view.providerHandleChain.map(({ handle }) => handle.nativeId) + this.aliasesBySession.set(view.sessionId, aliases) + for (const alias of aliases) { + const owners = this.owners.get(alias) ?? new Set() + owners.add(view.sessionId) + this.owners.set(alias, owners) + } + } + + private remove(sessionId: string): void { + for (const alias of this.aliasesBySession.get(sessionId) ?? []) { + const owners = this.owners.get(alias) + owners?.delete(sessionId) + if (owners?.size === 0) { + this.owners.delete(alias) + } + } + this.aliasesBySession.delete(sessionId) + } +} diff --git a/src/main/runtime/agent-session/records/agent-session-provider-alias-lookup.test.ts b/src/main/runtime/agent-session/records/agent-session-provider-alias-lookup.test.ts new file mode 100644 index 00000000000..419eb432f77 --- /dev/null +++ b/src/main/runtime/agent-session/records/agent-session-provider-alias-lookup.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest' +import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import type { AgentSessionStoreState } from './agent-session-store-state' +import type { AgentSessionRecordStore } from './agent-session-record-store' +import type { AgentSessionStoreTransactions } from './agent-session-store-transactions' +import { scaleDirectory, scaleRecord } from './agent-session-scale.test-fixture' +import { + openTestAgentSessionRecordStore, + seedTestAgentSessionRecordStore +} from './agent-session-record-store-test-harness' +import { conversationRecordReader } from '../../orchestration/addressing/session-lineage/structured-session-lineage' +import { lookupOrcaAgentSession } from '../../orchestration/mailbox/routing/structured-session-mail-address' + +/** The native id the scale fixture gives each chat's provider handle. */ +function aliasOf(sessionId: string): string { + return `provider-${sessionId}-0` +} + +async function storeWith(records: ReturnType[]) { + const root = await scaleDirectory() + await seedTestAgentSessionRecordStore(root, { records }) + const store = await openTestAgentSessionRecordStore(root) + return store +} + +/** Commits through the store's own transaction, as every production write does. */ +function commit(store: AgentSessionRecordStore, apply: (draft: AgentSessionStoreState) => void) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the store's private transaction owner; tests write through it to reach the real commit boundary. + const { transactions } = store as unknown as { transactions: AgentSessionStoreTransactions } + return transactions.transact(apply) +} + +function withAlias(store: AgentSessionRecordStore, sessionId: string, nativeId: string) { + const record = store.getRecord(sessionId)! + return { + ...record, + providerHandleChain: record.providerHandleChain.map((link) => ({ + ...link, + handle: claudeProviderHandle(nativeId, null) + })) + } +} + +describe('provider alias index at the commit boundary', () => { + it('follows committed handle changes and removals, and nothing else', async () => { + const store = await storeWith([ + scaleRecord('session-a'), + { + ...scaleRecord('session-b'), + providerHandleChain: scaleRecord('session-b').providerHandleChain.map((link) => ({ + ...link, + handle: claudeProviderHandle(aliasOf('session-a'), null) + })) + }, + scaleRecord('session-c') + ]) + const reader = conversationRecordReader(store) + const owner = (nativeId: string) => { + const found = lookupOrcaAgentSession(reader, nativeId) + return found.kind === 'provider-id' ? found.orcaSessionId : found.kind + } + // Two chats name one alias: the first in listing order owns it. + expect(owner(aliasOf('session-a'))).toBe('session-a') + + await commit(store, (draft) => + draft.records.set('session-b', { ...draft.records.get('session-b')!, updatedAt: 99 }) + ) + expect(owner(aliasOf('session-a'))).toBe('session-a') + + // Deleted and set again in one draft, the first owner moves to the end, as its map does. + await commit(store, (draft) => { + const record = draft.records.get('session-a')! + draft.records.delete('session-a') + draft.records.set('session-a', { ...record, updatedAt: 98 }) + }) + expect(store.listRecords().map((record) => record.sessionId)).toEqual([ + 'session-b', + 'session-c', + 'session-a' + ]) + expect(owner(aliasOf('session-a'))).toBe('session-b') + // Removing the winning duplicate passes the alias to the other owner. + await commit(store, (draft) => draft.records.delete('session-b')) + expect(owner(aliasOf('session-a'))).toBe('session-a') + // A handle change moves the record's aliases. + await commit(store, (draft) => + draft.records.set('session-a', withAlias(store, 'session-a', 'renamed-a')) + ) + expect(owner(aliasOf('session-a'))).toBe('unknown') + expect(owner('renamed-a')).toBe('session-a') + // A failed transaction changes nothing. + await expect( + commit(store, (draft) => { + draft.records.set('session-c', withAlias(store, 'session-c', 'rolled-back')) + throw new Error('rejected') + }) + ).rejects.toThrow('rejected') + expect(owner('rolled-back')).toBe('unknown') + expect(owner(aliasOf('session-c'))).toBe('session-c') + + // A replacement store answers from its own records. + const replacement = conversationRecordReader(await storeWith([scaleRecord('session-d')])) + expect(lookupOrcaAgentSession(replacement, aliasOf('session-c')).kind).toBe('unknown') + expect(lookupOrcaAgentSession(replacement, aliasOf('session-d'))).toEqual({ + kind: 'provider-id', + orcaSessionId: 'session-d' + }) + }) +}) diff --git a/src/main/runtime/agent-session/records/agent-session-record-store-damaged.test.ts b/src/main/runtime/agent-session/records/agent-session-record-store-damaged.test.ts index 5a29271fa5e..316aaf01188 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-store-damaged.test.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-store-damaged.test.ts @@ -1,5 +1,5 @@ import { listStructuredProviderSessionOwnership } from '../../../native-chat/agent-session-wire/host/structured-provider-session-ownership' -import { findConflictingStructuredAdoption } from '../../../native-chat/structured-agent-session-history-adoption' +import { findConflictingStructuredAdoption } from '../../../native-chat/conversation-adoption/structured-agent-session-history-adoption' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/agent-session/records/agent-session-record-store.ts b/src/main/runtime/agent-session/records/agent-session-record-store.ts index 5dc57674663..c476a5b5372 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-store.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-store.ts @@ -144,6 +144,7 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs { (id) => clearSuccessor(this.getConversation(id)) === sessionId ) lineageRevision = (): object => this.transactions.lineageRevision() + providerAliasOwner = (nativeId: string) => this.transactions.providerAliasOwner(nativeId) selectWritableRecord = (sessionId: string) => selectWritableAgentSessionRecord(this.state, sessionId) requireWritableRecord = (sessionId: string) => diff --git a/src/main/runtime/agent-session/records/agent-session-store-draft.ts b/src/main/runtime/agent-session/records/agent-session-store-draft.ts index 50a80f974ac..47d00048617 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-draft.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-draft.ts @@ -1,6 +1,7 @@ // Publish drafts only after row commit so readers never see changes that can roll back. import { encodeAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record-stored-form' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionStoreState, RetiredAgentSessionClaimKey @@ -13,11 +14,33 @@ import { } from './agent-session-store-row-rules' import type { PersistedAgentSessionTab } from '../agent-session-tab-table' +/** A draft's records, remembering which keys went to the end: a Map appends a key set while + * absent (new, or deleted first) and keeps a re-set key's place. */ +export class AgentSessionDraftRecords extends Map { + /** In the order they now sit at the end; a key deleted again may be listed but absent. */ + readonly appended = new Set() + + constructor(published: ReadonlyMap) { + super() + for (const [key, value] of published) { + super.set(key, value) + } + } + + override set(key: string, value: AgentSessionRecord): this { + if (!this.has(key)) { + this.appended.delete(key) + this.appended.add(key) + } + return super.set(key, value) + } +} + /** Unreadable rows are derived at load and never written, so the draft shares them. */ export function draftAgentSessionStoreState(state: AgentSessionStoreState): AgentSessionStoreState { return { ...state, - records: new Map(state.records), + records: new AgentSessionDraftRecords(state.records), operations: new Map(state.operations), retiredClaimKeys: [...state.retiredClaimKeys], sessionTabs: state.sessionTabs?.clone() ?? null diff --git a/src/main/runtime/agent-session/records/agent-session-store-transactions.ts b/src/main/runtime/agent-session/records/agent-session-store-transactions.ts index c01cd38dc0f..e21dd9ef0c5 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-transactions.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-transactions.ts @@ -31,6 +31,7 @@ import { type AgentSessionStoreRowWrites } from './agent-session-store-draft' import { changesAgentSenderIdentity } from './agent-session-sender-identity-revision' +import { AgentSessionProviderAliasIndex } from './agent-session-provider-alias-index' // Commit validated draft rows atomically before publication; failures discard the draft. // The promise queue preserves FIFO and defers BEGIN beyond the caller's open journal transaction. @@ -96,6 +97,8 @@ export class AgentSessionStoreTransactions { /** Replaced only when a record joins or leaves, or a /clear links one conversation to the next: * lookups derived from every record's lineage stay valid across admission and lease writes. */ private lineage: object = {} + /** Built on first use; kept by each committed record write, dropped if the unreadable set moves. */ + private providerAliases: AgentSessionProviderAliasIndex | null = null /** Receipts co-written in one transaction build on each other's drafts, so adoption keeps both. */ private staged: { transaction: number; draft: AgentSessionStoreState } | null = null /** Loaded takeover evidence; immutable for this runtime. */ @@ -132,6 +135,12 @@ export class AgentSessionStoreTransactions { return this.lineage } + /** The chat whose provider handle chain names `nativeId`, from the commit-kept alias index. */ + providerAliasOwner(nativeId: string): string | null { + this.providerAliases ??= new AgentSessionProviderAliasIndex(this.published) + return this.providerAliases.owner(nativeId) + } + get readOnly(): boolean { return this.journalDatabase.readOnly } @@ -254,6 +263,11 @@ export class AgentSessionStoreTransactions { this.senderIdentityRevision++ } this.published = draft + if (published.unreadableRecords !== draft.unreadableRecords) { + this.providerAliases = null + } else { + this.providerAliases?.applyCommitted(draft, writes.records) + } const lineageChanged = writes.records.remove.length > 0 || writes.records.upsert.some(([id]) => { diff --git a/src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts b/src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts deleted file mode 100644 index 31d488df6e2..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RpcResponse } from '../rpc/core' -import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../../shared/agent-session/agent-session-runtime-capabilities' -import { RuntimeClient, RuntimeClientError } from '../../../cli/runtime-client' -import { CHAT_HANDLERS } from '../../../cli/handlers/chat' -import { - openStructuredCodexRpcHarness, - SESSION, - THREAD, - TURN, - type StructuredCodexRpcHarness -} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' - -const NEWEST_MARKER = 'newest-row-marker' - -let harness: StructuredCodexRpcHarness | undefined - -afterEach(async () => { - vi.useRealTimers() - vi.restoreAllMocks() - await harness?.dispose() - harness = undefined -}) - -/** The CLI's own client, answered by the host's dispatcher in the local CLI's caller context. */ -function cliClient(open: StructuredCodexRpcHarness) { - const client = new RuntimeClient('/tmp/orca-chat-wait-test', 60_000, null, null) - vi.spyOn(client, 'getCliStatus').mockResolvedValue({ - id: 'status', - ok: true, - result: { - app: { running: true, pid: 1 }, - runtime: { - state: 'ready', - reachable: true, - runtimeId: 'runtime-1', - capabilities: [AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY] - }, - graph: { state: 'ready' } - }, - _meta: { runtimeId: 'runtime-1' } - }) - vi.spyOn(client, 'call').mockImplementation(async (method: string, params?: unknown) => { - const response: RpcResponse = await open.call(method, params) - if (!response.ok) { - throw new RuntimeClientError(response.error.code, response.error.message) - } - return response - }) - return client -} - -function agentMessage(id: string, text: string): void { - harness!.codex.notify('item/completed', { - threadId: THREAD, - turnId: TURN, - item: { type: 'agentMessage', id, text } - }) -} - -/** A running turn holding `rows` earlier replies and one newest reply of `newestBytes`. */ -async function seedRunningTurn(rows: number, newestBytes: number): Promise { - harness!.codex.notify('turn/started', { threadId: THREAD, turn: { id: TURN } }) - for (let index = 0; index < rows; index += 1) { - agentMessage(`older-${index}`, `Older reply ${index}.`) - } - agentMessage('newest', `${NEWEST_MARKER} ${'x'.repeat(newestBytes)}`) - await vi.waitFor(async () => { - const page = await harness!.call('agentSession.history', { - sessionId: SESSION, - direction: 'tail', - limit: 1 - }) - expect(JSON.stringify(page)).toContain(NEWEST_MARKER) - }) -} - -/** Lets the command's next checks run until it prints, then surfaces its result or failure. */ -async function settle(command: Promise, logs: string[]): Promise { - for (let second = 0; second < 10 && logs.length === 0; second += 1) { - await vi.advanceTimersByTimeAsync(1_000) - } - await command -} - -describe('chat send --wait over the real host', () => { - it('returns the completed turn when the host lacks agentSession.workState', async () => { - harness = await openStructuredCodexRpcHarness( - [], - {}, - { localCli: true, omitMethods: ['agentSession.workState'] } - ) - await harness.ok('agentSession.create', harness.createIntentParams()) - const client = cliClient(harness) - const logs: string[] = [] - vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line)) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const sending = CHAT_HANDLERS['chat send']!({ - flags: new Map([ - ['session', SESSION], - ['text', 'Run the tests'], - ['wait', true] - ]), - client, - cwd: '/tmp', - json: true - }) - await vi.waitFor(() => - expect(harness!.codex.live().calls.map((c) => c.method)).toContain('turn/start') - ) - await seedRunningTurn(1, 16) - await vi.advanceTimersByTimeAsync(1_000) - harness.codex.notify('turn/completed', { - threadId: THREAD, - turn: { id: TURN, status: 'completed' } - }) - await settle(sending, logs) - expect(JSON.parse(logs.join('\n')).result).toMatchObject({ - delivery: 'submitted', - settled: 'done', - entries: [{ text: 'Older reply 0.' }, { text: `${NEWEST_MARKER} ${'x'.repeat(16)}` }] - }) - }) -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-create-adoption.ts b/src/main/runtime/agent-session/structured-agent-session-create-adoption.ts index 6629e907f6c..198b3010133 100644 --- a/src/main/runtime/agent-session/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/agent-session/structured-agent-session-create-adoption.ts @@ -3,16 +3,16 @@ import { agentSessionRefusalError, isAgentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' -import { prepareCodexAdoption } from '../../native-chat/codex-adoption-preparation' +import { prepareCodexAdoption } from '../../native-chat/conversation-adoption/codex-adoption-preparation' import { isAiVaultTitleAgent } from '../../../shared/ai-vault/contracts/ai-vault-session-title' -import { generatedSessionTitle } from '../../ai-vault/session-scanner-accumulator' +import { generatedSessionTitle } from '../../ai-vault/parsing/session-scanner-accumulator' import { resolveLocalAiVaultSessionTitles } from '../../ai-vault/session-titles/session-title-resolver' import type { NativeCodexResumePreparation } from '../../codex/history/resume/codex-ai-vault-session-resume' import type { StructuredAgentSessionResumeSource } from '../../../shared/agent-session/structured-agent-session-create' import type { StructuredAgentCliSourceEvidence, StructuredAgentCliSourceLocator -} from '../../native-chat/structured-agent-cli-source' +} from '../../native-chat/conversation-adoption/structured-agent-cli-source' import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import type { AgentSessionProviderHandle, @@ -30,12 +30,12 @@ import { findConflictingStructuredAdoption, resolveStructuredAgentSessionAdoption, structuredAdoptionConflictError -} from '../../native-chat/structured-agent-session-history-adoption' +} from '../../native-chat/conversation-adoption/structured-agent-session-history-adoption' import { structuredAgentRuntimeMetadata } from './installation/structured-agent-runtime-metadata' import type { StructuredAgentTranscriptImport, StructuredAgentTranscriptImportSettings -} from '../../native-chat/structured-agent-cli-conversations' +} from '../../native-chat/conversation-adoption/structured-agent-cli-conversations' export type StructuredAgentSessionCreateIntentInput = { envelope: { sessionId: string; clientOperationId: string } diff --git a/src/main/runtime/agent-session/structured-agent-session-install-failure.test.ts b/src/main/runtime/agent-session/structured-agent-session-install-failure.test.ts index 4818bbebf85..86f763f2a29 100644 --- a/src/main/runtime/agent-session/structured-agent-session-install-failure.test.ts +++ b/src/main/runtime/agent-session/structured-agent-session-install-failure.test.ts @@ -10,6 +10,7 @@ import { ensureStructuredAgentSessionHost, stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' +import type { StructuredAgentSessionRuntimeDeps } from './installation/structured-agent-session-runtime-contract' import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' const mocks = vi.hoisted(() => ({ failWiring: vi.fn(() => false) })) @@ -38,9 +39,12 @@ vi.mock('./model-catalog/structured-agent-model-catalog-wiring', async (importOr let root: string -function install(): ReturnType { +function install( + createTurnAttention?: StructuredAgentSessionRuntimeDeps['createTurnAttention'] +): ReturnType { return ensureStructuredAgentSessionHost({ logger: createStructuredAgentSessionLogger(), + createTurnAttention, stateDirectory: root, hostId: 'local', claimKeyId: 'key-1', @@ -78,4 +82,12 @@ describe('an install that fails after opening the chat journal', () => { await stopStructuredAgentSessionRuntime() expect(opened.isClosed).toBe(true) }) + it('retries when acquiring the turn-attention owner throws', async () => { + await expect( + install(() => { + throw new Error('attention acquisition failed') + }) + ).rejects.toThrow('attention acquisition failed') + await expect(install()).resolves.toBeDefined() + }) }) diff --git a/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts b/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts index 26ca9dfed60..76f4e38eddd 100644 --- a/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts +++ b/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts @@ -4,18 +4,15 @@ import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { __setWindowsProcessTreeLoaderForTests } from '../../windows/windows-process-table' + import { ensureStructuredAgentSessionHost, stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' import { seedTestAgentSessionRecordStore } from './records/agent-session-record-store-test-harness' -import { nativeChatScratchFolderFor } from '../../native-chat/native-chat-scratch-folder' +import { nativeChatScratchFolderFor } from '../../native-chat/conversation-files/native-chat-scratch-folder' import { foundAgentSessionRecord } from './records/agent-session-record-founding' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' import { onStructuredAgentSessionsHeldChanged } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' @@ -71,32 +68,6 @@ describe('structured agent-session runtime install', () => { }) } - it.each([false, true])( - 'backfills before the host is readable and keeps startup nonfatal on a failed write (%s)', - async (failWrite) => { - stateDirectory = await mkdtemp(join(tmpdir(), 'orca-structured-runtime-backfill-')) - await seedTestAgentSessionRecordStore(stateDirectory, { records: [oldChat('codex')] }) - if (failWrite) { - openTestJournalHostDatabase(stateDirectory).db.exec( - "CREATE TRIGGER fail_permission_backfill BEFORE UPDATE ON agent_session_records BEGIN SELECT RAISE(ABORT, 'disk full'); END" - ) - } - const logged = recordingStructuredAgentSessionLogger() - const host = await installOver(['codex'], logged.logger) - expect(host.deps.store.getRecord('old-codex')?.permissionMode).toBe( - failWrite ? undefined : 'full-access' - ) - expect((await host.readOptions('old-codex')).current.permissionMode).toBe( - failWrite ? 'ask' : 'full-access' - ) - if (failWrite) { - expect(logged.scopes()).toContain('permission-mode-backfill') - } else { - expect(logged.scopes()).not.toContain('permission-mode-backfill') - } - } - ) - it('moves pre-rename chat visuals under the current root before the host is readable', async () => { stateDirectory = await mkdtemp(join(tmpdir(), 'orca-structured-runtime-visuals-')) await seedTestAgentSessionRecordStore(stateDirectory, { records: [oldChat('codex')] }) diff --git a/src/main/runtime/agent-session/structured-agent-session-runtime.ts b/src/main/runtime/agent-session/structured-agent-session-runtime.ts index a8f3249fc4e..d9d008fc06b 100644 --- a/src/main/runtime/agent-session/structured-agent-session-runtime.ts +++ b/src/main/runtime/agent-session/structured-agent-session-runtime.ts @@ -20,7 +20,7 @@ import { neverThrowingStructuredAgentSessionLogger, type StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { migrateLegacyNativeChatVisualsFolders } from '../../native-chat/native-chat-scratch-folder-migration' +import { migrateLegacyNativeChatVisualsFolders } from '../../native-chat/conversation-files/native-chat-scratch-folder-migration' import type { StructuredAgentSessionRuntimeDeps } from './installation/structured-agent-session-runtime-contract' diff --git a/src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts b/src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts index 15a5e0933b9..1a7553cce37 100644 --- a/src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts +++ b/src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts @@ -31,6 +31,45 @@ describe('BrowserHostCommandLedger', () => { 'browser_host_command_result_page_stale' ) }) + + it('settles a chunked automation result as the value its chunks carried', async () => { + const ledger = new BrowserHostCommandLedger({ authority }) + ledger.attach(vi.fn()) + const created = ledger.issue({ + browserPageId: 'page-a', + pageHostGeneration: 1, + command: { type: 'createPage', browserProfileId: 'default', executionHostKey: 'host-key-a' } + }) + ledger.settle(resultParams(created.event, { status: 'completed' })) + const screenshot = ledger.issue({ + browserPageId: 'page-a', + pageHostGeneration: 1, + command: { + type: 'automation', + method: 'browser.screenshot', + params: {}, + stagedResults: true + } + }) + const { result: _result, ...identity } = resultParams(screenshot.event, { status: 'completed' }) + const json = Buffer.from('{"data":"iVBORw0KGgo=","format":"png"}') + ledger.stageResultChunk({ + ...identity, + offset: 0, + contentBase64: json.subarray(0, 20).toString('base64') + }) + ledger.stageResultChunk({ + ...identity, + offset: 20, + contentBase64: json.subarray(20).toString('base64') + }) + ledger.settle({ ...identity, result: { status: 'completed', stagedValueBytes: 38 } }) + + await expect(screenshot.result).resolves.toEqual({ + status: 'completed', + value: { data: 'iVBORw0KGgo=', format: 'png' } + }) + }) }) function resultParams( diff --git a/src/main/runtime/browser-host/commands/browser-host-command-ledger.ts b/src/main/runtime/browser-host/commands/browser-host-command-ledger.ts index 264abe87859..1c24827be15 100644 --- a/src/main/runtime/browser-host/commands/browser-host-command-ledger.ts +++ b/src/main/runtime/browser-host/commands/browser-host-command-ledger.ts @@ -15,6 +15,7 @@ import { type BrowserHostCommandInput, type BrowserHostCommandLedgerOptions, type BrowserHostCommandPageState, + type BrowserHostCommandResultChunkParams, type BrowserHostCommandResultParams, positiveBrowserHostCommandLimit, recordBrowserHostCommandOrder, @@ -29,6 +30,7 @@ import { replaySettledBrowserHostCommand } from './browser-host-command-result-replay' import { BrowserHostCommandResultCache } from './browser-host-command-result-cache' +import { BrowserHostCommandResultStaging } from './browser-host-command-result-staging' export class BrowserHostCommandLedger { private readonly authority: BrowserClientHostLeaseAuthority @@ -38,6 +40,7 @@ export class BrowserHostCommandLedger { private readonly maxPages: number private readonly pages = new Map() private readonly resultCache: BrowserHostCommandResultCache + private readonly staging = new BrowserHostCommandResultStaging() private delivery: ((event: BrowserClientHostCommandEvent) => void) | undefined private outstandingCommands = 0 private activePages = 0 @@ -157,6 +160,14 @@ export class BrowserHostCommandLedger { return hasOutstandingBrowserHostReconciliation(this.pages) } + stageResultChunk(params: BrowserHostCommandResultChunkParams): void { + if (this.closed) { + throw new Error('browser_host_command_ledger_closed') + } + assertBrowserHostCommandResultAuthority(this.authority, params) + this.staging.append(this.pages.get(params.browserPageId), params) + } + settle(params: BrowserHostCommandResultParams): boolean { if (this.closed) { throw new Error('browser_host_command_ledger_closed') @@ -186,7 +197,7 @@ export class BrowserHostCommandLedger { if (!record || record.event.commandId !== params.commandId || record.settled) { throw new Error('browser_host_command_result_conflict') } - const result = Object.freeze({ ...params.result }) + const result = Object.freeze({ ...this.staging.take(record, params.result) }) record.settled = result record.resolve(result) page.nextSettlementSequence += 1 @@ -230,6 +241,7 @@ export class BrowserHostCommandLedger { } this.pages.clear() this.resultCache.clear() + this.staging.clear() this.outstandingCommands = 0 this.activePages = 0 } @@ -243,6 +255,7 @@ export class BrowserHostCommandLedger { throw new Error('browser_host_command_page_stale') } for (const record of page.records.values()) { + this.staging.release(record) if (!record.settled) { record.reject(new Error('browser_host_command_outcome_unknown')) } diff --git a/src/main/runtime/browser-host/commands/browser-host-command-result-staging.ts b/src/main/runtime/browser-host/commands/browser-host-command-result-staging.ts new file mode 100644 index 00000000000..810fb5e2f9b --- /dev/null +++ b/src/main/runtime/browser-host/commands/browser-host-command-result-staging.ts @@ -0,0 +1,101 @@ +import { + BROWSER_CLIENT_AUTOMATION_STAGED_RESULT_MAX_BYTES, + type BrowserClientAutomationResult as BrowserClientHostCommandResult +} from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' +import { BrowserError } from '../../../browser/browser-error' +import type { + BrowserHostCommandPageState, + BrowserHostCommandRecord, + BrowserHostCommandResultChunkParams as ChunkParams +} from './browser-host-command-state' + +// Several pages can stage at once; bound the lease's total, not just each result. +const MAX_STAGED_BYTES_PER_LEASE = 2 * BROWSER_CLIENT_AUTOMATION_STAGED_RESULT_MAX_BYTES + +type StagedResult = { chunks: Buffer[]; bytes: number } + +/** Holds chunked automation results until the desktop settles their command. */ +export class BrowserHostCommandResultStaging { + private readonly staged = new Map() + private bytes = 0 + + append( + page: BrowserHostCommandPageState | undefined, + { pageHostGeneration, commandSequence, commandId, offset, contentBase64 }: ChunkParams + ): void { + const record = + page?.generation === pageHostGeneration ? page.records.get(commandSequence) : undefined + if ( + !record || + record.event.commandId !== commandId || + record.settled || + record.event.command.type !== 'automation' || + record.event.command.stagedResults !== true + ) { + throw new Error('browser_host_command_result_chunk_conflict') + } + if (offset === 0) { + this.release(record) + } + const staged = this.staged.get(record) ?? { chunks: [], bytes: 0 } + if (offset !== staged.bytes) { + this.release(record) + throw new Error('browser_host_command_result_chunk_out_of_order') + } + const chunk = Buffer.from(contentBase64, 'base64') + if (chunk.byteLength === 0) { + this.release(record) + throw new Error('browser_host_command_result_chunk_invalid') + } + if ( + staged.bytes + chunk.byteLength > BROWSER_CLIENT_AUTOMATION_STAGED_RESULT_MAX_BYTES || + this.bytes + chunk.byteLength > MAX_STAGED_BYTES_PER_LEASE + ) { + this.release(record) + throw new BrowserError( + 'browser_host_command_result_too_large', + 'The server is already holding too many large browser results; retry, or use --format jpeg, a selector, or a smaller viewport.' + ) + } + staged.chunks.push(chunk) + staged.bytes += chunk.byteLength + this.bytes += chunk.byteLength + this.staged.set(record, staged) + } + + /** Swaps a staged marker for the value its chunks carried, and frees them either way. */ + take( + record: BrowserHostCommandRecord, + result: BrowserClientHostCommandResult + ): BrowserClientHostCommandResult { + const staged = this.staged.get(record) + this.release(record) + if (result.status !== 'completed' || result.stagedValueBytes === undefined) { + return result + } + if (staged?.bytes !== result.stagedValueBytes) { + return { status: 'failed', errorCode: 'browser_host_command_result_incomplete' } + } + try { + return { + status: 'completed', + value: JSON.parse(Buffer.concat(staged.chunks).toString('utf8')) + } + } catch { + return { status: 'failed', errorCode: 'browser_host_command_result_invalid' } + } + } + + release(record: BrowserHostCommandRecord): void { + const staged = this.staged.get(record) + if (staged) { + this.bytes -= staged.bytes + this.staged.delete(record) + } + } + + clear(): void { + this.staged.clear() + this.bytes = 0 + } +} diff --git a/src/main/runtime/browser-host/commands/browser-host-command-state.ts b/src/main/runtime/browser-host/commands/browser-host-command-state.ts index c29f9179166..d190f05e3f2 100644 --- a/src/main/runtime/browser-host/commands/browser-host-command-state.ts +++ b/src/main/runtime/browser-host/commands/browser-host-command-state.ts @@ -30,6 +30,14 @@ export type BrowserHostCommandResultParams = Omit< result: BrowserClientHostCommandResult } +export type BrowserHostCommandResultChunkParams = Omit< + BrowserClientHostCommandEvent, + 'type' | 'command' +> & { + offset: number + contentBase64: string +} + export type BrowserHostCommandRecord = { event: BrowserClientHostCommandEvent resultAdmission: BrowserHostCommandResultAdmission @@ -163,7 +171,7 @@ export function sameBrowserHostCommandResult( export function assertBrowserHostCommandResultAuthority( authority: BrowserClientHostLeaseAuthority, - params: BrowserHostCommandResultParams + params: Omit ): void { if ( params.pageCommandProtocolVersion !== authority.pageCommandProtocolVersion || diff --git a/src/main/runtime/browser-host/leases/browser-host-lease-registry.ts b/src/main/runtime/browser-host/leases/browser-host-lease-registry.ts index a8d5ebd1723..e1373a6ce3f 100644 --- a/src/main/runtime/browser-host/leases/browser-host-lease-registry.ts +++ b/src/main/runtime/browser-host/leases/browser-host-lease-registry.ts @@ -263,14 +263,17 @@ export class BrowserHostLeaseRegistry { identity: BrowserHostCommandResultIdentity, params: BrowserHostCommandResultParams ): boolean { - const state = this.requireLeaseState(identity) - const ledger = requireBrowserHostCommandResultLedger(state, identity) + const ledger = this.requireCommandResultLedger(identity) if (!ledger.isUnplacedPageResult(params)) { this.requireClientPage(params) } return ledger.settle(params) } + requireCommandResultLedger(identity: BrowserHostCommandResultIdentity) { + return requireBrowserHostCommandResultLedger(this.requireLeaseState(identity), identity) + } + getPlacement(browserPageId: string): RuntimeBrowserPlacement | undefined { return this.pagePlacements.getPlacement(browserPageId) } diff --git a/src/main/runtime/browser-host/leases/browser-host-request-registry.test.ts b/src/main/runtime/browser-host/leases/browser-host-request-registry.test.ts index 5f0dbad515f..51eefb4ce6e 100644 --- a/src/main/runtime/browser-host/leases/browser-host-request-registry.test.ts +++ b/src/main/runtime/browser-host/leases/browser-host-request-registry.test.ts @@ -78,3 +78,44 @@ describe('BrowserHostRequestRegistry with two paired desktops', () => { expect(older.asked).toHaveLength(0) }) }) + +describe('BrowserHostRequestRegistry with a sleeping desktop', () => { + it('fails at once on a desktop that missed its last ask, until it answers again', async () => { + vi.useFakeTimers() + const requests = new BrowserHostRequestRegistry({ desktopTimeoutMs: 1_000 }) + const sleeping = desktop(requests, 'device-a') + + const timedOut = expect(requests.request()).rejects.toThrow('browser_host_unavailable') + await vi.advanceTimersByTimeAsync(1_000) + await timedOut + + const again = requests.request() + expect(sleeping.asked).toHaveLength(1) + await expect(again).rejects.toThrow('browser_host_unavailable') + + // Its late answer to the missed ask shows it is awake. + expect(sleeping.answer()).toBe(false) + const hosted = requests.request() + expect(sleeping.asked).toHaveLength(2) + sleeping.answer('host-a') + await expect(hosted).resolves.toEqual({ + browserHostClientId: 'host-a', + pairedDeviceId: 'device-a' + }) + }) + + it('hands a pending ask to the subscription a waking desktop opens', async () => { + const requests = new BrowserHostRequestRegistry() + const halfOpen = desktop(requests, 'device-a') + const hosted = requests.request() + expect(halfOpen.asked).toHaveLength(1) + + const reconnected = desktop(requests, 'device-a') + expect(reconnected.answer('host-a')).toBe(true) + + await expect(hosted).resolves.toEqual({ + browserHostClientId: 'host-a', + pairedDeviceId: 'device-a' + }) + }) +}) diff --git a/src/main/runtime/browser-host/leases/browser-host-request-registry.ts b/src/main/runtime/browser-host/leases/browser-host-request-registry.ts index 33b6c795462..432e3b4b5b5 100644 --- a/src/main/runtime/browser-host/leases/browser-host-request-registry.ts +++ b/src/main/runtime/browser-host/leases/browser-host-request-registry.ts @@ -32,6 +32,8 @@ export class BrowserHostUnresponsiveError extends Error { export class BrowserHostRequestRegistry { private readonly volunteers: Volunteer[] = [] private readonly pending = new Map() + /** Desktops that let an ask time out; asking again before they answer anything would only wait again. */ + private readonly unanswered = new Set() private inFlight: Promise | null = null constructor( @@ -42,6 +44,17 @@ export class BrowserHostRequestRegistry { register(input: Volunteer): () => void { const volunteer = { ...input } this.volunteers.push(volunteer) + // A new subscription means the desktop is running again; hand it any ask its old socket may have swallowed. + this.unanswered.delete(volunteer.pairedDeviceId) + for (const [requestId, answer] of this.pending) { + if (answer.pairedDeviceId === volunteer.pairedDeviceId) { + try { + volunteer.emit({ type: 'browserHostRequested', requestId }) + } catch { + // That socket is gone too; its cleanup unregisters it. + } + } + } return () => { const index = this.volunteers.indexOf(volunteer) if (index === -1) { @@ -51,6 +64,7 @@ export class BrowserHostRequestRegistry { if (this.volunteers.some((entry) => entry.pairedDeviceId === volunteer.pairedDeviceId)) { return } + this.unanswered.delete(volunteer.pairedDeviceId) for (const answer of this.pending.values()) { if (answer.pairedDeviceId === volunteer.pairedDeviceId) { // It may still finish hosting over another socket, so do not ask a second desktop. @@ -76,6 +90,8 @@ export class BrowserHostRequestRegistry { caller: { pairedDeviceId: string }, result: BrowserClientHostRequestResultParams ): boolean { + // Even an answer that arrives after the deadline shows the desktop answers again. + this.unanswered.delete(caller.pairedDeviceId) const answer = this.pending.get(result.requestId) if (!answer || answer.pairedDeviceId !== caller.pairedDeviceId) { return false @@ -99,12 +115,18 @@ export class BrowserHostRequestRegistry { if (!pairedDeviceId || remainingMs <= 0) { throw new Error('browser_host_unavailable') } + if (this.unanswered.has(pairedDeviceId)) { + throw new BrowserHostUnresponsiveError(pairedDeviceId) + } asked.add(pairedDeviceId) const answer = await this.ask( pairedDeviceId, Math.min(remainingMs, this.options.desktopTimeoutMs ?? DESKTOP_TIMEOUT_MS) ) if (answer === 'silent') { + if (this.volunteers.some((entry) => entry.pairedDeviceId === pairedDeviceId)) { + this.unanswered.add(pairedDeviceId) + } throw new BrowserHostUnresponsiveError(pairedDeviceId) } if (answer !== 'declined') { diff --git a/src/main/runtime/browser/client-pages/browser-client-page-opening.ts b/src/main/runtime/browser/client-pages/browser-client-page-opening.ts index 45152468354..ae4a8ee155c 100644 --- a/src/main/runtime/browser/client-pages/browser-client-page-opening.ts +++ b/src/main/runtime/browser/client-pages/browser-client-page-opening.ts @@ -150,11 +150,22 @@ export function assertClientOpenableUrl(url: string): void { export async function createBrowserPageOnPairedHost( host: BrowserClientPageOpeningHost, params: Omit & { worktree?: string }, - browserProfileId: string + browserProfileId: string, + /** The server's own browser, used when no paired desktop takes the page. */ + fallback?: () => Promise<{ browserPageId: string }> ): Promise<{ browserPageId: string }> { const { worktree: selector, ...rest } = params const worktree = selector ? await host.resolveBrowserWorkspace(selector) : undefined - const lease = await acquirePairedPageHost(host, worktree?.id) + let lease: BrowserHostLease + try { + // With a fallback, ask a desktop even while it hosts: its own setting decides, and a sleeping one times out. + lease = await acquirePairedPageHost(host, worktree?.id, fallback !== undefined) + } catch (error) { + if (fallback && error instanceof BrowserError && error.code === 'browser_host_unavailable') { + return fallback() + } + throw error + } return createBrowserClientPage( host, { ...rest, placement: { kind: 'client', browserHostClientId: lease.browserHostClientId } }, @@ -199,18 +210,22 @@ type PairedPageHostSource = Pick< /** No caller names a host for these pages, so the server picks one desktop and never leaves it ambiguous. */ async function acquirePairedPageHost( host: PairedPageHostSource, - workspaceId: string | undefined + workspaceId: string | undefined, + askDesktop: boolean ): Promise { const leases = host.getBrowserHostLeaseRegistry() - try { - return selectPairedPageHost(leases) - } catch (error) { - // Several desktops already host: choose one of them rather than asking for another lease. - if (error instanceof BrowserHostAmbiguousError) { - return chooseAmongHosts(host, error.browserHostClientIds, workspaceId) - } - if (!isHostError(error, 'browser_host_unavailable')) { - throw error + // Only desktops that answer asks are asked; older ones keep the server's own browser. + if (!askDesktop) { + try { + return selectPairedPageHost(leases) + } catch (error) { + // Several desktops already host: choose one of them rather than asking for another lease. + if (error instanceof BrowserHostAmbiguousError) { + return chooseAmongHosts(host, error.browserHostClientIds, workspaceId) + } + if (!isHostError(error, 'browser_host_unavailable')) { + throw error + } } } try { diff --git a/src/main/runtime/browser/client-pages/browser-client-page-queries.ts b/src/main/runtime/browser/client-pages/browser-client-page-queries.ts index 07b6c157b09..98509e9c4ca 100644 --- a/src/main/runtime/browser/client-pages/browser-client-page-queries.ts +++ b/src/main/runtime/browser/client-pages/browser-client-page-queries.ts @@ -158,11 +158,12 @@ export async function yieldClientPageSelection( worktree: string | undefined ): Promise { const pages = host.getRuntimeBrowserPageRegistry() + if (worktree) { + pages.yieldSelection((await host.resolveBrowserWorkspace(worktree)).id) + return + } pages.deactivateGlobal() - const workspaceIds = worktree - ? [(await host.resolveBrowserWorkspace(worktree)).id] - : [...new Set(pages.listPages().map((page) => page.workspaceId))] - for (const workspaceId of workspaceIds) { + for (const workspaceId of new Set(pages.listPages().map((page) => page.workspaceId))) { pages.deactivateWorkspace(workspaceId) } } diff --git a/src/main/runtime/browser/client-pages/client-hosted-browser-persistence-test-harness.ts b/src/main/runtime/browser/client-pages/client-hosted-browser-persistence-test-harness.ts new file mode 100644 index 00000000000..7aeefc0ac94 --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-hosted-browser-persistence-test-harness.ts @@ -0,0 +1,94 @@ +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-topology/terminal-row-order' +const WT = 'repo-1::/tmp/worktree-a' + +const storeBase = { + getRepo: () => ({ + id: 'repo-1', + path: '/tmp/repo', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1 + }), + getRepos: () => [storeBase.getRepo()], + addRepo: () => {}, + updateRepo: () => { + throw new Error('unused fixture write') + }, + getAllWorktreeMeta: () => ({}), + getWorktreeMeta: () => undefined, + getGitHubCache: () => ({ pr: {}, issue: {} }), + setWorktreeMeta: () => { + throw new Error('unused fixture write') + }, + removeWorktreeMeta: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, + getSettings: () => ({ + workspaceDir: '/tmp/workspaces', + nestWorkspaces: false, + refreshLocalBaseRefOnWorktreeCreate: false, + branchPrefix: 'none', + branchPrefixCustom: '' + }) +} + +export function createProfile(worktreeCount = 0) { + const work = { writes: 0, normalizedWorktrees: 0 } + let measuringWrite = false + const tabsByWorktree: WorkspaceSessionState['tabsByWorktree'] = {} + for (let index = 0; index < worktreeCount; index += 1) { + const id = index === 0 ? WT : `repo-1::/tmp/worktree-${index}` + const rows = [ + { + id: `terminal-${index}`, + ptyId: null, + worktreeId: id, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + Object.defineProperty(tabsByWorktree, id, { + enumerable: true, + configurable: true, + get: () => { + if (measuringWrite) { + work.normalizedWorktrees += 1 + } + return rows + } + }) + } + const state: { session: WorkspaceSessionState } = { + session: { + activeRepoId: 'repo-1', + activeWorktreeId: WT, + activeTabId: null, + tabsByWorktree, + terminalLayoutsByTabId: {} + } satisfies WorkspaceSessionState + } + return { + work, + get session() { + return state.session + }, + store: { + ...storeBase, + getWorkspaceSession: () => state.session, + setWorkspaceSession: (next: WorkspaceSessionState) => { + work.writes += 1 + measuringWrite = true + try { + state.session = orderTerminalRowsByTabGroups(next) + } finally { + measuringWrite = false + } + } + } + } +} diff --git a/src/main/runtime/browser/client-pages/client-hosted-page-reconciliation-window.ts b/src/main/runtime/browser/client-pages/client-hosted-page-reconciliation-window.ts index 35656f4273d..ba2c3fac021 100644 --- a/src/main/runtime/browser/client-pages/client-hosted-page-reconciliation-window.ts +++ b/src/main/runtime/browser/client-pages/client-hosted-page-reconciliation-window.ts @@ -1,20 +1,90 @@ +import type { ClientHostedPageObservation } from '../../construction/runtime-identity-state' export const DEFAULT_CLIENT_HOSTED_RECONCILIATION_WINDOW_MS = 45_000 /** A client with no paired-device identity, which no host attach can ever speak for. */ const ANONYMOUS_CLIENT = '\0anonymous' +const READ_REPLY = Symbol('read-reply') /** Restart snapshots precede host inventories; hold browser-row culling until each client's host reconciles. * One client's attach proves nothing about another; bound never-attached clients by the deadline. */ export class ClientHostedPageReconciliationWindow { private readonly reconciledClients = new Set() + private readonly observations = new Map>>() constructor( private readonly openedAt: number, private readonly windowMs: number = DEFAULT_CLIENT_HOSTED_RECONCILIATION_WINDOW_MS ) {} - markReconciled(pairedDeviceId: string): void { - this.reconciledClients.add(clientKey(pairedDeviceId)) + markReconciled(pairedDeviceId: string): ReadonlySet | undefined { + const key = clientKey(pairedDeviceId) + this.reconciledClients.add(key) + const observations = this.observations.get(key) + this.observations.delete(key) + return observations && new Set([...observations.values()].flatMap((held) => [...held])) + } + + forgetClient(pairedDeviceId: string): void { + this.observations.delete(clientKey(pairedDeviceId)) + } + + observe( + frames: readonly { worktree: string; clientHostedPagesUnreconciled?: true; removed?: true }[], + pairedDeviceId?: string, + observer: ClientHostedPageObservation = READ_REPLY + ): void { + const key = clientKey(pairedDeviceId) + const observations = + this.observations.get(key) ?? new Map>() + const held = observations.get(observer) ?? new Set() + for (const frame of frames) { + if (frame.clientHostedPagesUnreconciled && !frame.removed) { + held.add(frame.worktree) + } else { + held.delete(frame.worktree) + } + } + if (held.size) { + observations.set(observer, held) + } else { + observations.delete(observer) + } + if (observations.size) { + this.observations.set(key, observations) + } else { + this.observations.delete(key) + } + } + + forgetObservation( + pairedDeviceId: string | undefined, + observer: ClientHostedPageObservation + ): void { + const key = clientKey(pairedDeviceId) + const observations = this.observations.get(key) + observations?.delete(observer) + if (observations?.size === 0) { + this.observations.delete(key) + } + } + + forgetWorktree(worktree: string): void { + for (const [key, observations] of this.observations) { + for (const [observer, held] of observations) { + held.delete(worktree) + if (!held.size) { + observations.delete(observer) + } + } + if (!observations.size) { + this.observations.delete(key) + } + } + } + + dispose(): void { + this.observations.clear() + this.reconciledClients.clear() } isUnreconciled(pairedDeviceId: string | undefined, now: number): boolean { @@ -24,7 +94,7 @@ export class ClientHostedPageReconciliationWindow { } /** Set and clear per recipient: shared fan-out frames must not inherit another client's hold. */ - holdFor( + holdFor( result: T, pairedDeviceId: string | undefined, now: number diff --git a/src/main/runtime/browser/client-pages/client-page-reconciliation-delivery-test-harness.ts b/src/main/runtime/browser/client-pages/client-page-reconciliation-delivery-test-harness.ts new file mode 100644 index 00000000000..46b071a176f --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-page-reconciliation-delivery-test-harness.ts @@ -0,0 +1,80 @@ +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' +import { createProfile } from './client-hosted-browser-persistence-test-harness' +import { RpcDispatcher } from '../../rpc/dispatcher' +import { BROWSER_CLIENT_HOST_METHODS } from '../../rpc/methods/browser/browser-client-host' +import { BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY } from '../../../../shared/browser/runtime/browser-runtime-capabilities' + +class ReconciliationDeliveryRuntime extends OrcaRuntimeService { + projectedFrames = 0 + sessionTabsSequence() { + return this.mobileSessionTabsChangeSequence + } + protected override projectMobileSessionTabsForClient( + result: RuntimeMobileSessionTabsResult, + clientId?: string + ) { + this.projectedFrames += 1 + return super.projectMobileSessionTabsForClient(result, clientId) + } + peekSnapshotForClient(worktree: string, clientId: string) { + return this.getMobileSessionTabsForWorktree(worktree, clientId, { + includeAgentSenders: false + }) + } + snapshotForClient(worktree: string, clientId: string) { + const result = this.peekSnapshotForClient(worktree, clientId) + this.observeClientHostedPageSnapshots([result], clientId) + return result + } + override getRuntimeId(): string { + return 'runtime-a' + } +} + +export function createReconciliationDeliveryRuntime() { + const profile = createProfile() + const hostRuntime = new ReconciliationDeliveryRuntime(profile.store, undefined, {}) + const rpc = new RpcDispatcher({ runtime: hostRuntime, methods: BROWSER_CLIENT_HOST_METHODS }) + const streams: { stopped: AbortController; completion: Promise }[] = [] + function attach() { + const stopped = new AbortController() + const completion = rpc.dispatchStreaming( + { + id: 'empty-adoption', + authToken: 'test', + method: 'browser.clientHost.attach', + params: { + authorityRuntimeId: 'runtime-a', + browserHostClientId: 'client-a', + hostCapabilities: ['webview'], + pageCommandProtocolVersion: 1, + pageReconciliationProtocolVersion: 1, + pageInventoryProtocolVersion: 1, + pageInventory: [], + leaseReconnectProtocolVersion: 1 + } + }, + () => {}, + { + connectionId: 'empty-adoption', + pairedDeviceId: 'device-a', + clientKind: 'runtime', + clientCapabilities: [BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY], + signal: stopped.signal + } + ) + streams.push({ stopped, completion }) + return { abort: () => stopped.abort(), completion } + } + return { + hostRuntime, + attach, + async close() { + for (const stream of streams) { + stream.stopped.abort() + } + await Promise.all(streams.map((stream) => stream.completion)) + } + } +} diff --git a/src/main/runtime/browser/client-pages/client-page-reconciliation-delivery.test.ts b/src/main/runtime/browser/client-pages/client-page-reconciliation-delivery.test.ts new file mode 100644 index 00000000000..3c5bafe39df --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-page-reconciliation-delivery.test.ts @@ -0,0 +1,129 @@ +import { expect, it, vi } from 'vitest' +import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness' +import { RpcDispatcher } from '../../rpc/dispatcher' +import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs' + +import { openRecoveryTabsStream } from './client-page-recovery-stream-test-harness' + +const WORKSPACE = 'repo-1::/tmp/worktree-a' + +it.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'])( + 'forgets %s initial hold after the same stream receives an unheld frame', + async (method) => { + vi.useFakeTimers({ toFake: ['Date'] }) + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const stopped = new AbortController() + const replies: string[] = [] + try { + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: WORKSPACE, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const stream = rpc.dispatchStreaming( + { + id: 'held-stream', + authToken: 'test', + method, + params: method === 'session.tabs.subscribe' ? { worktree: `id:${WORKSPACE}` } : {} + }, + (reply) => replies.push(reply), + { + connectionId: 'held-connection', + pairedDeviceId: 'device-a', + clientKind: 'mobile', + signal: stopped.signal + } + ) + await vi.waitFor(() => + expect( + replies.some((reply) => + ['snapshots', 'snapshot'].includes(JSON.parse(reply).result?.type) + ) + ).toBe(true) + ) + expect( + replies.some((reply) => + (JSON.parse(reply).result?.snapshots ?? [JSON.parse(reply).result]).some( + (frame: { worktree: string; clientHostedPagesUnreconciled?: true }) => + frame.worktree === WORKSPACE && frame.clientHostedPagesUnreconciled + ) + ) + ).toBe(true) + vi.setSystemTime(Date.now() + 46_000) + runtime.notifyMobileSessionTabsChanged(WORKSPACE) + expect( + replies.some( + (reply) => + JSON.parse(reply).result?.type === 'updated' && + JSON.parse(reply).result?.clientHostedPagesUnreconciled === undefined + ) + ).toBe(true) + runtime.projectedFrames = 0 + const delivered = replies.length + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(0) + expect(replies).toHaveLength(delivered) + stopped.abort() + await stream + } finally { + stopped.abort() + await h.close() + vi.useRealTimers() + } + } +) + +it('delivers a cleared snapshot when authenticated empty adoption completes without another workspace change', async () => { + const h = createReconciliationDeliveryRuntime() + h.hostRuntime.attachWindow(1) + h.hostRuntime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: WORKSPACE, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + const stream = openRecoveryTabsStream(h.hostRuntime, 'empty-adoption-consumer') + try { + await stream.initial + expect( + stream.frames.findLast((frame) => frame.worktree === WORKSPACE)?.clientHostedPagesUnreconciled + ).toBe(true) + const attached = h.attach() + await vi.waitFor(() => + expect( + stream.frames.findLast((frame) => frame.worktree === WORKSPACE) + ?.clientHostedPagesUnreconciled + ).toBeUndefined() + ) + expect(stream.errors).toEqual([]) + attached.abort() + await attached.completion + } finally { + stream.stop() + await stream.completion + await h.close() + } +}) diff --git a/src/main/runtime/browser/client-pages/client-page-reconciliation-scope.test.ts b/src/main/runtime/browser/client-pages/client-page-reconciliation-scope.test.ts new file mode 100644 index 00000000000..f48d8c48b88 --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-page-reconciliation-scope.test.ts @@ -0,0 +1,252 @@ +import { expect, it, vi } from 'vitest' +import { RuntimeAgentSenderAssociations } from '../../agent-senders/runtime-agent-sender-associations' +import { RpcDispatcher } from '../../rpc/dispatcher' +import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs' +import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness' +import { openRecoveryTabsStream } from './client-page-recovery-stream-test-harness' + +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) + +function snapshots(count: number) { + return Array.from({ length: count }, (_, index) => ({ + worktree: `repo-1::/tmp/covered-${index}`, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + })) +} + +it.each([750, 7500])( + 'clears only the live workspace channel among %i held read replies', + async (count) => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const corpus = snapshots(count) + const workspace = corpus[0]!.worktree + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: corpus }) + const global = openRecoveryTabsStream(runtime, 'departing-global') + const active = openRecoveryTabsStream( + runtime, + 'surviving-active', + `id:${workspace}`, + 'device-a', + 'runtime' + ) + const refresh = vi.spyOn(runtime.sidebarFacts!.workspaceActivityFacts, 'refreshWorkspace') + const senderWorkspaces: string[] = [] + const build = RuntimeAgentSenderAssociations.prototype.buildForFramePass + const senderPass = vi + .spyOn(RuntimeAgentSenderAssociations.prototype, 'buildForFramePass') + .mockImplementation(function (this: RuntimeAgentSenderAssociations) { + const scope = build.call(this) + return (worktree) => { + senderWorkspaces.push(worktree) + return scope(worktree) + } + }) + try { + await Promise.all([global.initial, active.initial]) + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const reads: string[] = [] + await rpc.dispatchStreaming( + { id: 'held-census', authToken: 'test', method: 'session.tabs.listAll', params: {} }, + (reply) => reads.push(reply), + { connectionId: 'held-census', pairedDeviceId: 'device-a', clientKind: 'runtime' } + ) + const supplied = JSON.parse(reads[0]!).result.snapshots + expect(supplied).toHaveLength(count) + expect( + supplied.every( + (frame: { clientHostedPagesUnreconciled?: true }) => + frame.clientHostedPagesUnreconciled === true + ) + ).toBe(true) + expect(active.frames.at(-1)?.clientHostedPagesUnreconciled).toBe(true) + global.stop() + await global.completion + runtime.projectedFrames = 0 + senderWorkspaces.length = 0 + refresh.mockClear() + const sequence = runtime.sessionTabsSequence() + const delivered = active.frames.length + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(1) + expect(runtime.sessionTabsSequence()).toBe(sequence + 1) + expect(active.frames).toHaveLength(delivered + 1) + expect(active.frames.at(-1)).toMatchObject({ worktree: workspace }) + expect(active.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined() + expect(senderWorkspaces).toEqual([workspace]) + expect(refresh).not.toHaveBeenCalled() + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(1) + expect(runtime.sessionTabsSequence()).toBe(sequence + 1) + runtime.projectedFrames = 0 + senderWorkspaces.length = 0 + runtime.notifyMobileSessionTabsChanged(corpus[1]!.worktree) + runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')() + expect(runtime.projectedFrames).toBe(0) + expect(senderWorkspaces).toEqual([]) + expect(active.frames).toHaveLength(delivered + 1) + const later = openRecoveryTabsStream(runtime, 'later-uncovered', `id:${corpus[1]!.worktree}`) + await later.initial + expect(later.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined() + later.stop() + await later.completion + } finally { + global.stop() + active.stop() + await Promise.all([global.completion, active.completion]) + await h.close() + refresh.mockRestore() + senderPass.mockRestore() + } + } +) + +it('stops projecting remaining owed workspaces when clearing output releases the stream', async () => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots(2) }) + const stopped = new AbortController() + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const cleared: string[] = [] + try { + await rpc.dispatchStreaming( + { + id: 'release-on-clear', + authToken: 'test', + method: 'session.tabs.subscribeAll', + params: {} + }, + (reply) => { + const frame = JSON.parse(reply).result + if (frame?.type === 'updated') { + cleared.push(frame.worktree) + stopped.abort() + } + }, + { + connectionId: 'release-on-clear', + pairedDeviceId: 'device-a', + clientKind: 'mobile', + signal: stopped.signal + } + ) + runtime.projectedFrames = 0 + const sequence = runtime.sessionTabsSequence() + runtime.markClientHostedPagesReconciled('device-a') + expect(cleared).toEqual(['repo-1::/tmp/covered-0']) + expect(runtime.projectedFrames).toBe(1) + expect(runtime.sessionTabsSequence()).toBe(sequence + 1) + } finally { + stopped.abort() + await h.close() + } +}) + +it('refreshes sender scopes only through accepting desktop channels and settles after broad delivery', async () => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const corpus = snapshots(2) + const activeWorkspace = corpus[0]!.worktree + const otherWorkspace = corpus[1]!.worktree + let peerKey = 'sender-peer-before' + runtime.setAgentSenderPeerKey(() => peerKey) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: corpus }) + const initial = openRecoveryTabsStream( + runtime, + 'initial-sender-census', + undefined, + 'device-a', + 'runtime' + ) + const active = openRecoveryTabsStream( + runtime, + 'active-sender-scope', + `id:${activeWorkspace}`, + 'device-a', + 'runtime' + ) + const phone = openRecoveryTabsStream( + runtime, + 'phone-sender-witness', + `id:${otherWorkspace}`, + 'phone' + ) + let broad: ReturnType | undefined + try { + await Promise.all([initial.initial, active.initial, phone.initial]) + initial.stop() + await initial.completion + const before = phone.frames.at(-1)!.snapshotVersion + const beforeCount = phone.frames.length + peerKey = 'sender-peer-after' + runtime.refreshAgentSenderAssociations() + runtime.onMobileSessionTabsChanged(() => {}, 'flush', 'mobile')() + runtime.refreshAgentSenderAssociations() + runtime.onMobileSessionTabsChanged(() => {}, 'flush', 'mobile')() + expect(phone.frames.at(-1)!.snapshotVersion).toBe(before) + expect(phone.frames).toHaveLength(beforeCount) + broad = openRecoveryTabsStream( + runtime, + 'returning-sender-census', + undefined, + 'device-a', + 'runtime' + ) + await broad.initial + const refreshed = broad.frames.findLast((frame) => frame.worktree === otherWorkspace) + expect(refreshed?.agentSenderAssociations?.peerFingerprint).toBe( + 'pXI0wdMoVIozNMf8PhOCNlB9sTAAEaBF6DfNP9doYqk' + ) + runtime.refreshAgentSenderAssociations() + runtime.onMobileSessionTabsChanged(() => {}, 'flush', 'mobile')() + const settled = phone.frames.length + const version = phone.frames.at(-1)!.snapshotVersion + runtime.refreshAgentSenderAssociations() + runtime.onMobileSessionTabsChanged(() => {}, 'flush', 'mobile')() + expect(phone.frames).toHaveLength(settled) + expect(phone.frames.at(-1)!.snapshotVersion).toBe(version) + } finally { + initial.stop() + active.stop() + phone.stop() + broad?.stop() + await Promise.all([initial.completion, active.completion, phone.completion, broad?.completion]) + await h.close() + } +}) + +it('routes removal only to the matching workspace and broad RPC streams', async () => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const corpus = snapshots(2) + const keptWorkspace = corpus[0]!.worktree + const removedWorkspace = corpus[1]!.worktree + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: corpus }) + const kept = openRecoveryTabsStream(runtime, 'kept-workspace', `id:${keptWorkspace}`) + const removed = openRecoveryTabsStream(runtime, 'removed-workspace', `id:${removedWorkspace}`) + const all = openRecoveryTabsStream(runtime, 'all-workspaces') + try { + await Promise.all([kept.initial, removed.initial, all.initial]) + const delivered = kept.frames.length + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [corpus[0]!] }) + runtime.onMobileSessionTabsChanged(() => {}, 'flush', 'mobile')() + expect(kept.frames).toHaveLength(delivered) + expect(removed.frames.at(-1)).toMatchObject({ worktree: removedWorkspace, removed: true }) + expect(all.frames.at(-1)).toMatchObject({ worktree: removedWorkspace, removed: true }) + } finally { + kept.stop() + removed.stop() + all.stop() + await Promise.all([kept.completion, removed.completion, all.completion]) + await h.close() + } +}) diff --git a/src/main/runtime/browser/client-pages/client-page-recovery-hold-publication.test.ts b/src/main/runtime/browser/client-pages/client-page-recovery-hold-publication.test.ts new file mode 100644 index 00000000000..7587dbaf817 --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-page-recovery-hold-publication.test.ts @@ -0,0 +1,177 @@ +import { expect, it, vi } from 'vitest' +import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' + +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) + +it.each([750, 7500])( + 'only clears previously held frames in a %i-workspace runtime', + async (count) => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const snapshots = Array.from({ length: count }, (_, index) => ({ + worktree: `repo-1::/tmp/worktree-${index}`, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + })) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots }) + runtime.markClientHostedPagesReconciled('device-a') + const frames: RuntimeMobileSessionTabsResult[] = [] + const otherFrames: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged( + (frame) => frames.push(frame), + 'device-a', + 'mobile' + ) + const unsubscribeHeld = runtime.onMobileSessionTabsChanged( + (frame) => otherFrames.push(frame), + 'device-b', + 'mobile' + ) + const facts = runtime.sidebarFacts + if (!facts) { + throw new Error('sidebar facts fixture is required') + } + const refresh = vi.spyOn(facts.workspaceActivityFacts, 'refreshWorkspace') + try { + runtime.projectedFrames = 0 + const attached = h.attach() + expect(runtime.projectedFrames).toBe(0) + expect(frames).toEqual([]) + expect(otherFrames).toEqual([]) + expect(refresh).not.toHaveBeenCalled() + attached.abort() + await attached.completion + const heldWorktrees = [snapshots[0]!.worktree, snapshots[count - 1]!.worktree] + for (const worktree of heldWorktrees) { + expect(runtime.snapshotForClient(worktree, 'device-b').clientHostedPagesUnreconciled).toBe( + true + ) + } + runtime.projectedFrames = 0 + runtime.markClientHostedPagesReconciled('device-b') + expect(runtime.projectedFrames).toBe(2) + expect(otherFrames.map((frame) => frame.worktree)).toEqual(heldWorktrees) + expect(otherFrames.every((frame) => frame.clientHostedPagesUnreconciled === undefined)).toBe( + true + ) + expect(frames).toEqual([]) + expect(refresh).not.toHaveBeenCalled() + otherFrames.length = 0 + runtime.projectedFrames = 0 + runtime.markClientHostedPagesReconciled('device-b') + expect(runtime.projectedFrames).toBe(0) + expect(otherFrames).toEqual([]) + expect(refresh).not.toHaveBeenCalled() + } finally { + refresh.mockRestore() + unsubscribe() + unsubscribeHeld() + await h.close() + } + } +) + +it('does not owe delivery for speculative projections and forgets removed workspaces', async () => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const worktree = 'repo-1::/tmp/worktree-observed' + const frames: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged( + (frame) => frames.push(frame), + 'device-a', + 'mobile' + ) + const unsubscribeOther = runtime.onMobileSessionTabsChanged( + (frame) => frames.push(frame), + 'device-b', + 'mobile' + ) + try { + expect(runtime.peekSnapshotForClient(worktree, 'device-a').clientHostedPagesUnreconciled).toBe( + true + ) + runtime.markClientHostedPagesReconciled('device-a') + expect(frames).toEqual([]) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + expect(runtime.snapshotForClient(worktree, 'device-b').clientHostedPagesUnreconciled).toBe(true) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) + frames.length = 0 + runtime.markClientHostedPagesReconciled('device-b') + expect(frames).toEqual([]) + } finally { + unsubscribe() + unsubscribeOther() + await h.close() + } +}) + +it('keeps each subscription last held frame independently of later read replies', async () => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const worktree = 'repo-1::/tmp/worktree-observed' + const frames: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged( + (frame) => frames.push(frame), + 'device-a', + 'mobile' + ) + try { + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + // A subscription flush is a production delivery boundary. + runtime.onMobileSessionTabsChanged(() => {}, 'other-device', 'mobile')() + expect(frames.some((frame) => frame.clientHostedPagesUnreconciled === true)).toBe(true) + frames.length = 0 + const now = Date.now() + vi.spyOn(Date, 'now').mockReturnValue(now + 45_001) + expect( + runtime.snapshotForClient(worktree, 'device-a').clientHostedPagesUnreconciled + ).toBeUndefined() + runtime.markClientHostedPagesReconciled('device-a') + expect(frames.map((frame) => [frame.worktree, frame.clientHostedPagesUnreconciled])).toEqual([ + [worktree, undefined] + ]) + frames.length = 0 + runtime.markClientHostedPagesReconciled('device-a') + expect(frames).toEqual([]) + } finally { + vi.restoreAllMocks() + unsubscribe() + await h.close() + } +}) diff --git a/src/main/runtime/browser/client-pages/client-page-recovery-stream-observation.test.ts b/src/main/runtime/browser/client-pages/client-page-recovery-stream-observation.test.ts new file mode 100644 index 00000000000..97208ff8302 --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-page-recovery-stream-observation.test.ts @@ -0,0 +1,275 @@ +import { RpcDispatcher } from '../../rpc/dispatcher' +import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs' +import { expect, it, vi } from 'vitest' +import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness' +import { openRecoveryTabsStream } from './client-page-recovery-stream-test-harness' + +const WORKSPACE = 'repo-1::/tmp/worktree-a' + +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) + +it.each([750, 7500])( + 'owes no completion for %i workspace updates filtered by a real RPC stream', + async (count) => { + vi.useFakeTimers({ toFake: ['Date'] }) + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const snapshots = [ + WORKSPACE, + ...Array.from({ length: count }, (_, index) => `repo-1::/tmp/filtered-${index}`) + ].map((worktree) => ({ + worktree, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + })) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots }) + const stream = openRecoveryTabsStream(runtime, 'filtered-stream', `id:${WORKSPACE}`) + const facts = runtime.sidebarFacts! + const refresh = vi.spyOn(facts.workspaceActivityFacts, 'refreshWorkspace') + try { + await stream.initial + for (const snapshot of snapshots.slice(1)) { + runtime.notifyMobileSessionTabsChanged(snapshot.worktree) + } + runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')() + expect(stream.frames.every((frame) => frame.worktree === WORKSPACE)).toBe(true) + vi.setSystemTime(Date.now() + 46_000) + runtime.notifyMobileSessionTabsChanged(WORKSPACE) + runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')() + expect(stream.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined() + runtime.projectedFrames = 0 + refresh.mockClear() + const sequence = runtime.sessionTabsSequence() + const delivered = stream.frames.length + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(0) + expect(runtime.sessionTabsSequence()).toBe(sequence) + expect(stream.frames).toHaveLength(delivered) + expect(refresh).not.toHaveBeenCalled() + } finally { + stream.stop() + await h.close() + refresh.mockRestore() + vi.useRealTimers() + } + } +) + +it.each(['workspace', 'all'])( + 'keeps an independent held read after %s stream progression, then forgets disposed streams and removed workspaces', + async (kind) => { + vi.useFakeTimers({ toFake: ['Date'] }) + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: WORKSPACE, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + const stream = openRecoveryTabsStream( + runtime, + 'progressing-stream', + kind === 'workspace' ? `id:${WORKSPACE}` : undefined + ) + const independent = openRecoveryTabsStream(runtime, 'independent-stream') + try { + await Promise.all([stream.initial, independent.initial]) + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const reads: string[] = [] + await rpc.dispatchStreaming( + { id: 'independent-read', authToken: 'test', method: 'session.tabs.listAll', params: {} }, + (reply) => reads.push(reply), + { connectionId: 'independent-read', pairedDeviceId: 'device-a', clientKind: 'mobile' } + ) + expect(JSON.parse(reads[0]!).result.snapshots[0].clientHostedPagesUnreconciled).toBe(true) + independent.stop() + await independent.completion + vi.setSystemTime(Date.now() + 46_000) + runtime.notifyMobileSessionTabsChanged(WORKSPACE) + runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')() + expect(stream.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined() + runtime.projectedFrames = 0 + const delivered = stream.frames.length + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(1) + expect(stream.frames).toHaveLength(delivered + 1) + expect(stream.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined() + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(1) + expect(stream.frames).toHaveLength(delivered + 1) + stream.stop() + await stream.completion + vi.setSystemTime(Date.now() - 46_000) + const removed = openRecoveryTabsStream(runtime, 'removed-stream', undefined, 'device-b') + await removed.initial + expect( + removed.frames.findLast((frame) => frame.worktree === WORKSPACE) + ?.clientHostedPagesUnreconciled + ).toBe(true) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) + runtime.projectedFrames = 0 + runtime.markClientHostedPagesReconciled('device-b') + expect(runtime.projectedFrames).toBe(0) + removed.stop() + await removed.completion + } finally { + stream.stop() + independent.stop() + await h.close() + vi.useRealTimers() + } + } +) + +it('cannot recreate a raw observation when its listener unsubscribes during delivery', async () => { + const h = createReconciliationDeliveryRuntime() + let unsubscribe = () => {} + try { + unsubscribe = h.hostRuntime.onMobileSessionTabsChanged( + () => unsubscribe(), + 'device-a', + 'mobile' + ) + h.hostRuntime.notifyMobileSessionTabsChanged(WORKSPACE) + h.hostRuntime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')() + h.hostRuntime.projectedFrames = 0 + h.hostRuntime.markClientHostedPagesReconciled('device-a') + expect(h.hostRuntime.projectedFrames).toBe(0) + } finally { + unsubscribe() + await h.close() + } +}) + +it.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'])( + 'cannot recreate %s observations when initial output releases the stream', + async (method) => { + const h = createReconciliationDeliveryRuntime() + h.hostRuntime.attachWindow(1) + h.hostRuntime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: WORKSPACE, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + const stopped = new AbortController() + const rpc = new RpcDispatcher({ runtime: h.hostRuntime, methods: SESSION_TAB_METHODS }) + try { + let supplied = false + await rpc.dispatchStreaming( + { + id: 'release-during-output', + authToken: 'test', + method, + params: method === 'session.tabs.subscribe' ? { worktree: `id:${WORKSPACE}` } : {} + }, + (reply) => { + if (['snapshot', 'snapshots'].includes(JSON.parse(reply).result?.type)) { + supplied = true + stopped.abort() + } + }, + { + connectionId: 'release-during-output', + pairedDeviceId: 'device-a', + clientKind: 'mobile', + signal: stopped.signal + } + ) + expect(supplied).toBe(true) + h.hostRuntime.projectedFrames = 0 + h.hostRuntime.markClientHostedPagesReconciled('device-a') + expect(h.hostRuntime.projectedFrames).toBe(0) + } finally { + stopped.abort() + await h.close() + } + } +) + +it.each([750, 7500])( + 'does no completion projection for %i held read replies after that device unsubscribes', + async (count) => { + const h = createReconciliationDeliveryRuntime() + const runtime = h.hostRuntime + const snapshots = Array.from({ length: count }, (_, index) => ({ + worktree: `repo-1::/tmp/unsubscribed-${index}`, + publicationEpoch: 'renderer', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + })) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots }) + const departed = openRecoveryTabsStream(runtime, 'departing-device-stream') + const other = openRecoveryTabsStream( + runtime, + 'remaining-device-stream', + `id:${snapshots[0]!.worktree}`, + 'device-b' + ) + const refresh = vi.spyOn(runtime.sidebarFacts!.workspaceActivityFacts, 'refreshWorkspace') + try { + await Promise.all([departed.initial, other.initial]) + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const reads: string[] = [] + await rpc.dispatchStreaming( + { id: 'held-read', authToken: 'test', method: 'session.tabs.listAll', params: {} }, + (reply) => reads.push(reply), + { connectionId: 'held-read', pairedDeviceId: 'device-a', clientKind: 'runtime' } + ) + const supplied = JSON.parse(reads[0]!).result.snapshots + expect(supplied).toHaveLength(count) + expect( + supplied.every( + (frame: { clientHostedPagesUnreconciled?: true }) => + frame.clientHostedPagesUnreconciled === true + ) + ).toBe(true) + departed.stop() + await departed.completion + runtime.projectedFrames = 0 + refresh.mockClear() + const sequence = runtime.sessionTabsSequence() + const delivered = other.frames.length + runtime.markClientHostedPagesReconciled('device-a') + expect(runtime.projectedFrames).toBe(0) + expect(runtime.sessionTabsSequence()).toBe(sequence) + expect(other.frames).toHaveLength(delivered) + expect(refresh).not.toHaveBeenCalled() + } finally { + departed.stop() + other.stop() + await Promise.all([departed.completion, other.completion]) + await h.close() + refresh.mockRestore() + } + } +) diff --git a/src/main/runtime/browser/client-pages/client-page-recovery-stream-test-harness.ts b/src/main/runtime/browser/client-pages/client-page-recovery-stream-test-harness.ts new file mode 100644 index 00000000000..1ad26127583 --- /dev/null +++ b/src/main/runtime/browser/client-pages/client-page-recovery-stream-test-harness.ts @@ -0,0 +1,49 @@ +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { RpcDispatcher } from '../../rpc/dispatcher' +import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs' + +export function openRecoveryTabsStream( + runtime: OrcaRuntimeService, + id: string, + worktree?: string, + deviceId = 'device-a', + clientKind: 'mobile' | 'runtime' = 'mobile' +) { + const stopped = new AbortController() + const frames: RuntimeMobileSessionTabsResult[] = [] + const errors: unknown[] = [] + const initial = Promise.withResolvers() + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const completion = rpc.dispatchStreaming( + { + id, + authToken: 'test', + method: worktree ? 'session.tabs.subscribe' : 'session.tabs.subscribeAll', + params: worktree ? { worktree } : {} + }, + (reply) => { + const message: { + ok?: boolean + error?: unknown + result?: + | { type: 'snapshots'; snapshots: RuntimeMobileSessionTabsResult[] } + | ({ type: 'snapshot' | 'updated' } & RuntimeMobileSessionTabsResult) + } = JSON.parse(reply) + if (message.ok === false) { + errors.push(message.error) + initial.reject(new Error('session-stream-failed')) + } + const result = message.result + if (result?.type === 'snapshots') { + frames.push(...result.snapshots) + initial.resolve() + } else if (result?.type === 'snapshot' || result?.type === 'updated') { + frames.push(result) + initial.resolve() + } + }, + { connectionId: id, pairedDeviceId: deviceId, clientKind, signal: stopped.signal } + ) + return { frames, errors, initial: initial.promise, completion, stop: () => stopped.abort() } +} diff --git a/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts b/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts index 35465319fc9..9cb2ab11e2d 100644 --- a/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts +++ b/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts @@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentBrowserBridge } from '../../../browser/agent-browser/agent-browser-bridge' import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' import { RuntimeBrowserPageRegistry } from './runtime-browser-page-registry' +import { BrowserHostLeaseRegistry } from '../../browser-host/leases/browser-host-lease-registry' +import { BrowserHostRequestRegistry } from '../../browser-host/leases/browser-host-request-registry' const { ipcMainOnMock, @@ -96,6 +98,9 @@ function createHost(overrides: Partial = {}): Runtime resolveWorkspaceSelector: async (selector) => ({ id: selector.replace(/^id:/, '') }), resolveBrowserWorkspace: async (selector) => ({ id: selector.replace(/^id:/, '') }), getRuntimeBrowserPageRegistry: () => runtimeBrowserPages, + // No paired desktop: headless creates stay on this host. + getBrowserHostLeaseRegistry: () => new BrowserHostLeaseRegistry({ authorityRuntimeId: 'host' }), + getBrowserHostRequestRegistry: () => new BrowserHostRequestRegistry(), getAuthoritativeWindow: vi.fn(), getAvailableAuthoritativeWindow: vi.fn(() => null), getOffscreenBrowserBackend: vi.fn(() => null), @@ -191,4 +196,42 @@ describe('RuntimeBrowserCommands browser screencast', () => { expect(waitForTabRegistrationMock).toHaveBeenCalledWith('page-new') expect(bridge.setActiveTab).toHaveBeenCalledWith(101, 'wt-1') }) + // Pageless agent commands prefer an active client page; an agent's new server tab must take that over. + it('moves the workspace selection off a client page when a server tab is created', async () => { + const { RuntimeBrowserCommands } = await import('../commands/browser-commands') + const pages = new RuntimeBrowserPageRegistry() + pages.publishClientPage({ + browserPageId: 'user-page', + workspaceId: 'wt-1', + browserProfileId: 'default', + executionHostKey: 'local', + placement: { + kind: 'client', + browserHostClientId: 'desktop-1', + browserHostGeneration: 1, + pageHostGeneration: 1 + }, + url: 'https://user.example/', + loading: false, + active: true + }) + const bridge = { + getRegisteredTabs: vi.fn(() => new Map([['agent-page', 102]])), + setActiveTab: vi.fn() + } + const offscreen = { createTab: vi.fn(async () => ({ browserPageId: 'agent-page' })) } + const host = createHost({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: create reaches only these two bridge methods. + getAgentBrowserBridge: () => bridge as unknown as AgentBrowserBridge, + getRuntimeBrowserPageRegistry: () => pages, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: create reaches only createTab. + getOffscreenBrowserBackend: () => offscreen as never + }) + const commands = new RuntimeBrowserCommands(host) + + await commands.browserTabCreate({ worktree: 'id:wt-1', url: 'https://agent.example/' }) + + expect(bridge.setActiveTab).toHaveBeenCalledWith(102, 'wt-1') + expect(pages.listPages('wt-1').find((page) => page.active)).toBeUndefined() + }) }) diff --git a/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts b/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts index cfaa857e841..12660d845b2 100644 --- a/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts +++ b/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts @@ -53,7 +53,8 @@ function browserRuntime(closeTab = vi.fn(async (_pageId: string) => {}), runtime // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the bridge inventory is used by this lifecycle test. runtime.setAgentBrowserBridge({ tabList: () => ({ tabs: [...livePages.values()] }), - getRemoteTabFaviconUrl: () => null + getRemoteTabFaviconUrl: () => null, + getPageNavigationState: () => null } as never) electronMocks.BrowserWindow.fromId.mockImplementation((id: number) => id === 1 ? { isDestroyed: () => false } : null diff --git a/src/main/runtime/browser/client-pages/runtime-browser-client-automation.ts b/src/main/runtime/browser/client-pages/runtime-browser-client-automation.ts index 72a8f61bc48..89f9f4c0e9f 100644 --- a/src/main/runtime/browser/client-pages/runtime-browser-client-automation.ts +++ b/src/main/runtime/browser/client-pages/runtime-browser-client-automation.ts @@ -1,8 +1,9 @@ import { BrowserClientAutomationMethod } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' +import { BrowserError } from '../../../browser/browser-error' import { browserExpectedUrlMismatchError } from '../../../browser/cdp/input/browser-expected-page-url' import type { BrowserHostLeaseRegistry } from '../../browser-host/leases/browser-host-lease-registry' import type { RuntimeBrowserPageRegistry } from './runtime-browser-page-registry' -import { isAgentRpcCaller, type RpcCallerIdentity } from '../../rpc/rpc-caller-identity' +import { isAgentRpcCaller, type RpcCallerIdentity } from '../../rpc/callers/rpc-caller-identity' export type ClientHostedBrowserRpcRoute = { handled: false } | { handled: true; result: unknown } @@ -36,14 +37,15 @@ export async function routeRuntimeBrowserClientAutomation(options: { method: method.data, params: options.params, // A person's link or relayed input must not light the desktop page as agent-driven. - agent: isAgentRpcCaller(options.caller) + agent: isAgentRpcCaller(options.caller), + stagedResults: true } ) const result = await issued.result if (result.status === 'failed') { throw result.expectedUrlMismatch ? browserExpectedUrlMismatchError(result.expectedUrlMismatch) - : new Error(result.errorCode) + : new BrowserError(result.errorCode, result.errorMessage ?? result.errorCode) } return { handled: true, result: result.value } } diff --git a/src/main/runtime/browser/client-pages/runtime-browser-page-registry.ts b/src/main/runtime/browser/client-pages/runtime-browser-page-registry.ts index 519ed9d37d9..a7fb5cb373d 100644 --- a/src/main/runtime/browser/client-pages/runtime-browser-page-registry.ts +++ b/src/main/runtime/browser/client-pages/runtime-browser-page-registry.ts @@ -199,6 +199,14 @@ export class RuntimeBrowserPageRegistry { this.globalActivePageId = null } + /** An engine tab took the selection; unscoped creates and switches move only the global pick. */ + yieldSelection(workspaceId: string | undefined): void { + this.deactivateGlobal() + if (workspaceId !== undefined) { + this.deactivateWorkspace(workspaceId) + } + } + deactivateWorkspace(workspaceId: string): void { for (const [browserPageId, page] of this.pages) { if (page.workspaceId === workspaceId && page.active) { diff --git a/src/main/runtime/browser/client-pages/server-agent-tab-placement.ts b/src/main/runtime/browser/client-pages/server-agent-tab-placement.ts new file mode 100644 index 00000000000..df1fc69bb18 --- /dev/null +++ b/src/main/runtime/browser/client-pages/server-agent-tab-placement.ts @@ -0,0 +1,51 @@ +import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' +import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' +import { + assertClientOpenableUrl, + canPlacePairedPage, + type BrowserClientPageOpeningHost +} from './browser-client-page-opening' + +/** A tab this server's own agents open goes on a paired desktop when one can host it (#41682). */ +export function opensOnPairedDesktop( + host: Pick< + BrowserClientPageOpeningHost, + 'getBrowserHostLeaseRegistry' | 'getBrowserHostRequestRegistry' + >, + params: + | { placement?: unknown; worktree?: string; url?: string; page?: string; split?: unknown } + | undefined, + caller: { pairedDeviceId?: string; opensPageLink?: boolean } | undefined, + hasOwnBrowser: boolean +): boolean { + // Paired callers choose their own placement, and a page link opens beside its opener. + if (params?.placement || caller?.pairedDeviceId || caller?.opensPageLink) { + return false + } + // Keep what this host's own browser can do better: unscoped tabs, local URLs, named pages it + // may already hold, and splits a desktop page cannot open as. + if ( + hasOwnBrowser && + (!params?.worktree || !isDesktopOpenableUrl(params.url) || params.page || params.split) + ) { + return false + } + // With a browser to fall back on, only a desktop that can be asked is worth a request. + return hasOwnBrowser + ? host.getBrowserHostRequestRegistry().hasVolunteer() + : canPlacePairedPage(host) +} + +// Match what the desktop opens, so `localhost:3000` counts as the web URL it becomes there. +function isDesktopOpenableUrl(url: string | undefined): boolean { + const normalized = url === undefined ? null : normalizeBrowserNavigationUrl(url) + if (url === undefined || normalized === ORCA_BROWSER_BLANK_URL) { + return true + } + try { + assertClientOpenableUrl(normalized ?? url) + return true + } catch { + return false + } +} diff --git a/src/main/runtime/browser/client-pages/single-page-browser-commands-host-test-double.ts b/src/main/runtime/browser/client-pages/single-page-browser-commands-host-test-double.ts index 8e7dc7dba3c..30c55779828 100644 --- a/src/main/runtime/browser/client-pages/single-page-browser-commands-host-test-double.ts +++ b/src/main/runtime/browser/client-pages/single-page-browser-commands-host-test-double.ts @@ -2,7 +2,7 @@ import { vi } from 'vitest' import type { AgentBrowserBridge } from '../../../browser/agent-browser/agent-browser-bridge' import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' import { RuntimeBrowserPageRegistry } from './runtime-browser-page-registry' -import type { RendererPublicationThrottleTarget } from '../../../window/renderer-publication-throttle' +import type { RendererPublicationThrottleTarget } from '../../../window/visibility/renderer-publication-throttle' // The part of the authoritative window a browser stream touches: its renderer's throttle lease target. export type AuthoritativeWindowDouble = { diff --git a/src/main/runtime/browser/commands/browser-capture.ts b/src/main/runtime/browser/commands/browser-capture.ts index 96d21a15197..583e996c96b 100644 --- a/src/main/runtime/browser/commands/browser-capture.ts +++ b/src/main/runtime/browser/commands/browser-capture.ts @@ -1,4 +1,4 @@ -import type { BrowserScreenshotOptions } from '../../../../shared/rpc-contract/browser-observation-params' +import type { BrowserScreenshotOptions } from '../../../../shared/rpc-contract/browser/browser-observation-params' import type { BrowserScreenshotResult, BrowserCaptureStartResult, diff --git a/src/main/runtime/browser/commands/browser-command-targets.ts b/src/main/runtime/browser/commands/browser-command-targets.ts index 64d7b3d4f49..def633f880c 100644 --- a/src/main/runtime/browser/commands/browser-command-targets.ts +++ b/src/main/runtime/browser/commands/browser-command-targets.ts @@ -1,4 +1,4 @@ -import type { BrowserSnapshotOptions } from '../../../../shared/rpc-contract/browser-observation-params' +import type { BrowserSnapshotOptions } from '../../../../shared/rpc-contract/browser/browser-observation-params' import type { AgentBrowserBridge } from '../../../browser/agent-browser/agent-browser-bridge' import { BrowserError } from '../../../browser/browser-error' import { browserPopupPageWebContentsId } from '../../../browser/guest-lifecycle/popups/browser-popup-page-id' diff --git a/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts b/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts index 2c2399366d0..3aea2bfc463 100644 --- a/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts +++ b/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts @@ -43,6 +43,7 @@ function restartedServe(session: WorkspaceSessionState = savedServeTabs()) { })) })), getRemoteTabFaviconUrl: () => null, + getPageNavigationState: () => null, getRegisteredTabs: vi.fn(() => registered()), snapshot: vi.fn(async () => ({ snapshot: '' })), getActivePageId: vi.fn(() => livePages[0] ?? null), diff --git a/src/main/runtime/browser/headless/serve-browser-tab-layout.ts b/src/main/runtime/browser/headless/serve-browser-tab-layout.ts index 8bbfabfa69c..18c59b48987 100644 --- a/src/main/runtime/browser/headless/serve-browser-tab-layout.ts +++ b/src/main/runtime/browser/headless/serve-browser-tab-layout.ts @@ -3,10 +3,10 @@ import type { BrowserPage } from '../../../../shared/browser-workspace-types' import type { ExecutionHostId } from '../../../../shared/execution-host' import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' -import { BLANK_BROWSER_TAB_STATE } from '../../../../shared/workspace-layout/workspace-layout-beside' -import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../../shared/workspace-layout/workspace-layout-minted-ids' -import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-save' +import { BLANK_BROWSER_TAB_STATE } from '../../../../shared/workspace-layout/persistence/workspace-layout-beside' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { randomUUID } from 'node:crypto' diff --git a/src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts b/src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts deleted file mode 100644 index 64a273fe303..00000000000 --- a/src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { - LayoutApplyOutcome, - LayoutCommand -} from '../../../../shared/workspace-layout/workspace-layout-command-types' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' -import { ServeBrowserTabs } from './serve-browser-tabs' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const WT = 'repo-1::/repo' -const PAGE = { worktreeId: WT, pageId: 'page-1', url: 'https://example.com/', title: 'Example' } - -/** A host with no window whose layout writes go through `layout.apply`'s record patch. */ -function servedHost(initial: WorkspaceSessionState = getDefaultWorkspaceSession()) { - let session = initial - const save = vi.fn((_worktreeId: string, next: WorkspaceSessionState) => { - session = next - }) - const applyLayout = vi.fn( - async (command: LayoutCommand, hostId: ExecutionHostId): Promise => { - const change = applyCommandToSession(hostId, session, command) - session = change.session ?? session - return change.value - } - ) - const tabs = new ServeBrowserTabs({ - backend: () => ({ createTab: vi.fn(), closeTab: vi.fn(), ownsTab: () => true }), - livePageIds: () => new Set(), - savedWorktreeIds: () => [WT], - session: () => session, - hostId: () => 'local', - save, - applyLayout - }) - return { tabs, applyLayout, save, session: () => session } -} - -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - -describe('served browser tabs in a layout-owner build', () => { - it('closes a window-saved tab by its own tab-bar entry', async () => { - const host = servedHost() - host.tabs.opened(PAGE) - await settle() - // As a window saves it: the tab-bar entry has its own id. - const saved = host.session() - host.save(WT, { - ...saved, - unifiedTabs: { - [WT]: saved.unifiedTabs![WT]!.map((entry) => ({ ...entry, id: 'unified-1' })) - }, - tabGroups: { - [WT]: saved.tabGroups![WT]!.map((group) => ({ - ...group, - activeTabId: null, - tabOrder: ['unified-1'] - })) - } - }) - - host.tabs.closed(WT, 'page-1') - await settle() - - expect(host.applyLayout).toHaveBeenLastCalledWith( - { type: 'closeTabs', workspace: WT, tabIds: ['unified-1'], force: true }, - 'local' - ) - expect(host.session().browserTabsByWorktree?.[WT] ?? []).toEqual([]) - expect(host.session().unifiedTabs?.[WT] ?? []).toEqual([]) - }) - - it('saves the address a page reached while main was writing its tab', async () => { - const host = servedHost() - - host.tabs.opened(PAGE) - host.tabs.navigated({ ...PAGE, url: 'https://example.com/next', title: 'Next' }) - await settle() - - expect(host.session().browserPagesByWorkspace?.['page-1']).toEqual([ - expect.objectContaining({ url: 'https://example.com/next', title: 'Next' }) - ]) - expect(host.session().browserTabsByWorktree?.[WT]?.[0]).toMatchObject({ title: 'Next' }) - }) - - it('closes a tab closed while main was writing it, and saves no page for it', async () => { - const host = servedHost() - - host.tabs.opened(PAGE) - expect(host.tabs.closed(WT, 'page-1')).toBe(true) - await settle() - - expect(host.session().browserTabsByWorktree?.[WT] ?? []).toEqual([]) - expect(host.session().browserPagesByWorkspace?.['page-1']).toBeUndefined() - expect(host.tabs.listUnstarted(WT)).toEqual([]) - }) -}) diff --git a/src/main/runtime/browser/screencast/browser-screencast-contracts.ts b/src/main/runtime/browser/screencast/browser-screencast-contracts.ts index 8362b5f0cf2..c6973f3adb8 100644 --- a/src/main/runtime/browser/screencast/browser-screencast-contracts.ts +++ b/src/main/runtime/browser/screencast/browser-screencast-contracts.ts @@ -6,7 +6,7 @@ import type { } from '../../../browser/cdp/screencast/browser-screencast-stream-types' import type { ScreencastSubscriberDeliveryState } from './browser-screencast-ghost-subscriber-eviction' import type { BrowserScreencastFrameCredit } from './browser-screencast-frame-credit' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' +import type { RpcBinarySender } from '../../rpc/transports/rpc-binary-sender' import type { BrowserCommandTargetParams } from '../commands/browser-command-contracts' export type BrowserScreencastParams = { diff --git a/src/main/runtime/browser/screencast/browser-screencasts.ts b/src/main/runtime/browser/screencast/browser-screencasts.ts index d8a97faa304..14410b8d4a6 100644 --- a/src/main/runtime/browser/screencast/browser-screencasts.ts +++ b/src/main/runtime/browser/screencast/browser-screencasts.ts @@ -3,7 +3,7 @@ import { BrowserError } from '../../../browser/browser-error' import { randomUUID } from 'node:crypto' import { startBrowserScreencast } from '../../../browser/cdp/screencast/browser-screencast-stream' import { browserManager } from '../../../browser/guest-lifecycle/manager/browser-manager' -import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' +import { rendererPublicationThrottle } from '../../../window/visibility/renderer-publication-throttle' import { mintBrowserScreencastSubscriptionId } from './browser-screencast-subscription-id' import { cancelScreencastSubscriberFrameRetry, @@ -19,7 +19,7 @@ import { screencastSubscriberIsGhost } from './browser-screencast-ghost-subscriber-eviction' import type { BrowserScreencastSession } from '../../../browser/cdp/screencast/browser-screencast-stream-types' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' +import type { RpcBinarySender } from '../../rpc/transports/rpc-binary-sender' import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' import type { RuntimeBrowserCommandTargets } from '../commands/browser-command-targets' import type { RuntimeBrowserTabCatalog } from '../tabs/browser-tab-catalog' diff --git a/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-e2ee-backlog.test.ts b/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-e2ee-backlog.test.ts index 398116f4bbb..d8cde17a953 100644 --- a/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-e2ee-backlog.test.ts +++ b/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-e2ee-backlog.test.ts @@ -6,7 +6,7 @@ import { createSinglePageBrowserCommandsHost, createStreamedGuest } from '../client-pages/single-page-browser-commands-host-test-double' -import { E2EEChannel } from '../../rpc/e2ee-channel' +import { E2EEChannel } from '../../rpc/mobile/e2ee/e2ee-channel' import { decrypt, decryptBytes, @@ -14,7 +14,7 @@ import { encrypt, generateKeyPair } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' +import type { RpcBinarySender } from '../../rpc/transports/rpc-binary-sender' const { webContentsFromId, startBrowserScreencast } = vi.hoisted(() => ({ webContentsFromId: vi.fn(), diff --git a/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-pending-frame-retry.test.ts b/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-pending-frame-retry.test.ts deleted file mode 100644 index 2156f683b7a..00000000000 --- a/src/main/runtime/browser/screencast/orca-runtime-browser-screencast-pending-frame-retry.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { SCREENCAST_PENDING_FRAME_RETRY_MS } from './browser-screencast-subscriber-frame-delivery' -import { - createSinglePageBrowserCommandsHost, - createStreamedGuest -} from '../client-pages/single-page-browser-commands-host-test-double' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' - -const { webContentsFromId, startBrowserScreencast } = vi.hoisted(() => ({ - webContentsFromId: vi.fn(), - startBrowserScreencast: vi.fn() -})) - -vi.mock('electron', () => ({ - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - webContents: { fromId: webContentsFromId } -})) -vi.mock('../../../browser/cdp/screencast/browser-screencast-stream', () => ({ - startBrowserScreencast -})) - -async function subscribe(sendBinary: RpcBinarySender) { - const { RuntimeBrowserCommands } = await import('../commands/browser-commands') - let resolveDone!: () => void - const done = new Promise((resolve) => { - resolveDone = resolve - }) - const stop = vi.fn(() => resolveDone()) - startBrowserScreencast.mockResolvedValue({ - stop, - done, - updateViewport: vi.fn(async () => {}) - }) - const commands = new RuntimeBrowserCommands(createSinglePageBrowserCommandsHost()) - const subscription = await commands.browserScreencast( - { worktree: 'id:wt-1', page: 'page-1', format: 'jpeg' }, - { sendBinary } - ) - const onFrame: (bytes: Uint8Array) => unknown = - startBrowserScreencast.mock.calls[0][1].onFrame - return { subscription, onFrame, stop } -} - -describe('screencast frames a viewer refused', () => { - beforeEach(() => { - vi.useFakeTimers() - webContentsFromId.mockReset() - webContentsFromId.mockReturnValue(createStreamedGuest()) - startBrowserScreencast.mockReset() - }) - afterEach(() => { - vi.useRealTimers() - }) - - // Idle pages produce no next frame; retry the latest refused frame after socket drain. - it('delivers the last refused frame once the socket drains, with no new frame produced', async () => { - let socketFull = true - const received: Uint8Array[] = [] - const { subscription, onFrame } = await subscribe((bytes) => { - if (socketFull) { - return false - } - received.push(bytes) - return true - }) - const first = new Uint8Array([1]) - const last = new Uint8Array([2]) - onFrame(first) - onFrame(last) - await vi.advanceTimersByTimeAsync(SCREENCAST_PENDING_FRAME_RETRY_MS * 4) - expect(received).toEqual([]) - - socketFull = false - await vi.advanceTimersByTimeAsync(SCREENCAST_PENDING_FRAME_RETRY_MS) - expect(received).toEqual([last]) - await vi.advanceTimersByTimeAsync(SCREENCAST_PENDING_FRAME_RETRY_MS * 4) - expect(received).toEqual([last]) - subscription.session.stop() - }) -}) diff --git a/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts b/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts deleted file mode 100644 index c87652a7309..00000000000 --- a/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { Buffer } from 'node:buffer' -import { EventEmitter } from 'node:events' -import { describe, expect, it, vi } from 'vitest' - -import { - deriveSharedKey, - encrypt, - generateKeyPair -} from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { REMOTE_RUNTIME_MAX_OUTBOUND_BINARY_FRAME_BYTES } from '../../../../shared/remote-runtime/remote-runtime-memory-limits' -import { startBrowserScreencast } from '../../../browser/cdp/screencast/browser-screencast-stream' -import { E2EEChannel } from '../../rpc/e2ee-channel' -import { sendRemoteBrowserScreencastFrame } from './remote-browser-screencast-frame-admission' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' - -function createMockWebContents() { - let attached = false - const dbg = new EventEmitter() as EventEmitter & { - isAttached: ReturnType - attach: ReturnType - detach: ReturnType - sendCommand: ReturnType - } - dbg.isAttached = vi.fn(() => attached) - dbg.attach = vi.fn(() => { - attached = true - }) - dbg.detach = vi.fn(() => { - attached = false - }) - dbg.sendCommand = vi.fn(async () => ({})) - return { isDestroyed: vi.fn(() => false), debugger: dbg } -} - -// Use real E2EE admission to catch oversized frames before they close the transport with 1013. -function createRuntimeBinarySender() { - const serverKeys = generateKeyPair() - const clientKeys = generateKeyPair() - const ws = { - OPEN: 1 as const, - readyState: 1, - send: vi.fn(), - close: vi.fn() - } - const onTransportError = vi.fn((code: number, reason: string) => ws.close(code, reason)) - const channel = new E2EEChannel(ws as never, { - serverSecretKey: serverKeys.secretKey, - resolveAuthenticatedDevice: (token) => - token === 'valid-token' - ? { - deviceId: 'device-1', - deviceToken: token, - scope: 'runtime', - clientId: token, - callerFingerprint: 'test-fingerprint', - credentialRevision: 0 - } - : null, - onReady: vi.fn(), - onError: onTransportError - }) - const sharedKey = deriveSharedKey(clientKeys.secretKey, serverKeys.publicKey) - channel.handleRawMessage( - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: Buffer.from(clientKeys.publicKey).toString('base64') - }) - ) - channel.handleRawMessage( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), sharedKey) - ) - let sendBinary: RpcBinarySender | undefined - channel.onMessage((_plaintext, _sendText, sendBinaryReply) => { - sendBinary = sendBinaryReply - }) - channel.handleRawMessage(encrypt('start-screencast', sharedKey)) - if (!sendBinary) { - throw new Error('Runtime binary sender was not established') - } - return { channel, ws, onTransportError, sendBinary } -} - -describe('sendRemoteBrowserScreencastFrame', () => { - it('drops an oversized encoded frame without closing or stalling the paired stream', async () => { - vi.useFakeTimers() - const webContents = createMockWebContents() - const transport = createRuntimeBinarySender() - const session = await startBrowserScreencast(webContents as never, { - format: 'jpeg', - quality: 70, - maxWidth: 3840, - maxHeight: 2160, - everyNthFrame: 1, - minFrameIntervalMs: 0, - holdPaint: () => () => {}, - onFrame: (bytes) => - sendRemoteBrowserScreencastFrame(transport.sendBinary, bytes) !== 'refused' - }) - - try { - webContents.debugger.emit('message', {}, 'Page.screencastFrame', { - data: Buffer.alloc(REMOTE_RUNTIME_MAX_OUTBOUND_BINARY_FRAME_BYTES + 1).toString('base64'), - sessionId: 42, - metadata: {} - }) - await Promise.resolve() - - expect(transport.onTransportError).not.toHaveBeenCalled() - expect(transport.ws.close).not.toHaveBeenCalled() - expect(webContents.debugger.sendCommand).toHaveBeenCalledWith('Page.screencastFrameAck', { - sessionId: 42 - }) - const sendsAfterDrop = transport.ws.send.mock.calls.length - await vi.advanceTimersByTimeAsync(500) - expect(transport.ws.send).toHaveBeenCalledTimes(sendsAfterDrop) - - webContents.debugger.emit('message', {}, 'Page.screencastFrame', { - data: Buffer.from('next-frame').toString('base64'), - sessionId: 43, - metadata: {} - }) - await Promise.resolve() - - expect(transport.onTransportError).not.toHaveBeenCalled() - expect(webContents.debugger.sendCommand).toHaveBeenCalledWith('Page.screencastFrameAck', { - sessionId: 43 - }) - expect(transport.ws.send.mock.calls.length).toBeGreaterThan(sendsAfterDrop) - } finally { - session.stop() - await session.done - transport.channel.destroy() - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.ts b/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.ts index 3175fcb60e1..3b003249e52 100644 --- a/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.ts +++ b/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.ts @@ -1,5 +1,5 @@ import { isRemoteRuntimeBinaryFrameWithinLimit } from '../../../../shared/remote-runtime/remote-runtime-memory-limits' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' +import type { RpcBinarySender } from '../../rpc/transports/rpc-binary-sender' /** 'dropped': oversize, never sent or retried; 'backlogged': a live socket skipped the frame; * 'refused': the transport would not take it. */ diff --git a/src/main/runtime/browser/screencast/runtime-browser-screencast-controller.ts b/src/main/runtime/browser/screencast/runtime-browser-screencast-controller.ts index 473aefcc58d..b492e1a1141 100644 --- a/src/main/runtime/browser/screencast/runtime-browser-screencast-controller.ts +++ b/src/main/runtime/browser/screencast/runtime-browser-screencast-controller.ts @@ -7,7 +7,7 @@ import { type BrowserScreencastSubscriber } from './browser-screencast-driver-scope' import type { RuntimeBrowserCommands } from '../commands/browser-commands' -import type { RpcBinarySender } from '../../rpc/rpc-binary-sender' +import type { RpcBinarySender } from '../../rpc/transports/rpc-binary-sender' type RuntimeBrowserScreencastControllerDeps = { getCommands: () => Pick diff --git a/src/main/runtime/browser/tabs/browser-tab-create-publication.ts b/src/main/runtime/browser/tabs/browser-tab-create-publication.ts index 08ba33d6c28..9d6401abb34 100644 --- a/src/main/runtime/browser/tabs/browser-tab-create-publication.ts +++ b/src/main/runtime/browser/tabs/browser-tab-create-publication.ts @@ -1,4 +1,5 @@ import type { AgentBrowserBridge } from '../../../browser/agent-browser/agent-browser-bridge' +import type { RuntimeBrowserPageRegistry } from '../client-pages/runtime-browser-page-registry' import { navigationTargetsHost, resolveRuntimeNavigationTarget, @@ -20,6 +21,7 @@ type BrowserTabCreatePublicationBridge = Pick< export type BrowserTabCreatePublicationHost = { getAgentBrowserBridge(): BrowserTabCreatePublicationBridge | null + getRuntimeBrowserPageRegistry(): Pick markHeadlessBrowserSessionTabActive?( worktreeId: string | undefined, browserPageId: string, @@ -194,6 +196,11 @@ export function publishCreatedBrowserSessionTab( ?.getRegisteredTabs(publication.worktreeId) .get(publication.browserPageId) if (bridge && webContentsId != null) { + // Pageless commands prefer an active client page, so the new engine tab must take over from it. + // Yield first so the bridge's own tabs-changed publication carries the cleared client row. + if (publication.focus.startsActive) { + host.getRuntimeBrowserPageRegistry().yieldSelection(publication.worktreeId) + } bridge.setActiveTab(webContentsId, publication.worktreeId) } } diff --git a/src/main/runtime/browser/tabs/browser-tab-creation.ts b/src/main/runtime/browser/tabs/browser-tab-creation.ts index cc003bf5f62..59bef7af39e 100644 --- a/src/main/runtime/browser/tabs/browser-tab-creation.ts +++ b/src/main/runtime/browser/tabs/browser-tab-creation.ts @@ -4,7 +4,8 @@ import type { BrowserPageCreationPlacement } from '../../../../shared/browser/cl import type { BrowserTabSplitDirection } from '../../../../shared/browser-tab-split-direction' import { publishCreatedBrowserSessionTab, - resolveBrowserTabCreateFocus + resolveBrowserTabCreateFocus, + type BrowserTabCreateFocusResolution } from './browser-tab-create-publication' import { browserSessionRegistry } from '../../../browser/sessions/profiles/browser-session-registry' import { BrowserError } from '../../../browser/browser-error' @@ -13,8 +14,30 @@ import type { RuntimeBrowserCommandHost } from '../commands/browser-command-cont import type { RuntimeBrowserCommandTargets } from '../commands/browser-command-targets' import { createBrowserClientPage, + createBrowserPageOnPairedHost, openBrowserUrlOnClient } from '../client-pages/browser-client-page-opening' +import { opensOnPairedDesktop } from '../client-pages/server-agent-tab-placement' + +type BrowserTabCreateRequest = { + url?: string + worktree?: string + page?: string + profileId?: string + waitForRegistration?: boolean + activate?: boolean + navigation?: RuntimeNavigationTarget + targetGroupId?: string + placement?: BrowserPageCreationPlacement + split?: BrowserTabSplitDirection + splitFromTabId?: string +} + +type BrowserTabCreateCaller = { + pairedDeviceId?: string + clientKind?: 'mobile' | 'runtime' + opensPageLink?: boolean +} export class RuntimeBrowserTabCreation { constructor( @@ -41,24 +64,8 @@ export class RuntimeBrowserTabCreation { ) {} async browserTabCreate( - params: { - url?: string - worktree?: string - page?: string - profileId?: string - waitForRegistration?: boolean - activate?: boolean - navigation?: RuntimeNavigationTarget - targetGroupId?: string - placement?: BrowserPageCreationPlacement - split?: BrowserTabSplitDirection - splitFromTabId?: string - }, - caller?: { - pairedDeviceId?: string - clientKind?: 'mobile' | 'runtime' - opensPageLink?: boolean - } + params: BrowserTabCreateRequest, + caller?: BrowserTabCreateCaller ): Promise<{ browserPageId: string }> { const url = params.url ?? 'about:blank' const focus = resolveBrowserTabCreateFocus({ @@ -102,35 +109,22 @@ export class RuntimeBrowserTabCreation { // Headless hosts use offscreen WebContents because no renderer webview exists. if (!this.host.getAvailableAuthoritativeWindow()) { const offscreen = this.host.getOffscreenBrowserBackend() - if (!offscreen) { - throw new BrowserError('browser_error', 'This host does not support browser panes.') + const createOffscreen = async (): Promise<{ browserPageId: string }> => { + if (!offscreen) { + throw new BrowserError('browser_error', 'This host does not support browser panes.') + } + return this.createOffscreenTab(offscreen, params, caller, url, worktreeId, focus) } - const created = await offscreen.createTab({ - url, - worktreeId, - profileId: params.profileId, - ...(params.page ? { browserPageId: params.page } : {}) - }) - if (worktreeId) { - this.host.serveBrowserTabs?.opened({ - worktreeId, - pageId: created.browserPageId, - url, - title: '', - ...(params.profileId ? { profileId: params.profileId } : {}), - ...(params.targetGroupId ? { groupId: params.targetGroupId } : {}) - }) + // A desktop on "Server (streamed)" declines when asked, so agent tabs keep streaming from here. + if (opensOnPairedDesktop(this.host, params, caller, offscreen !== null)) { + return createBrowserPageOnPairedHost( + this.host, + params, + params.profileId ?? browserSessionRegistry.getDefaultProfile().id, + offscreen ? createOffscreen : undefined + ) } - publishCreatedBrowserSessionTab(this.host, { - placementKind: 'offscreen', - browserPageId: created.browserPageId, - worktreeId, - focus, - ...(caller?.pairedDeviceId ? { clientNavigationId: caller.pairedDeviceId } : {}), - ...(caller?.opensPageLink ? { opensPageLink: true } : {}), - targetGroupId: params.targetGroupId - }) - return { browserPageId: created.browserPageId } + return createOffscreen() } const { browserPageId } = await createBrowserTabInRenderer( this.host, @@ -187,6 +181,42 @@ export class RuntimeBrowserTabCreation { return { browserPageId } } + private async createOffscreenTab( + offscreen: NonNullable>, + params: BrowserTabCreateRequest, + caller: BrowserTabCreateCaller | undefined, + url: string, + worktreeId: string | undefined, + focus: BrowserTabCreateFocusResolution + ): Promise<{ browserPageId: string }> { + const created = await offscreen.createTab({ + url, + worktreeId, + profileId: params.profileId, + ...(params.page ? { browserPageId: params.page } : {}) + }) + if (worktreeId) { + this.host.serveBrowserTabs?.opened({ + worktreeId, + pageId: created.browserPageId, + url, + title: '', + ...(params.profileId ? { profileId: params.profileId } : {}), + ...(params.targetGroupId ? { groupId: params.targetGroupId } : {}) + }) + } + publishCreatedBrowserSessionTab(this.host, { + placementKind: 'offscreen', + browserPageId: created.browserPageId, + worktreeId, + focus, + ...(caller?.pairedDeviceId ? { clientNavigationId: caller.pairedDeviceId } : {}), + ...(caller?.opensPageLink ? { opensPageLink: true } : {}), + targetGroupId: params.targetGroupId + }) + return { browserPageId: created.browserPageId } + } + async browserOpenUrlOnClient(params: { url: string worktree: string diff --git a/src/main/runtime/browser/tabs/browser-tab-queries.ts b/src/main/runtime/browser/tabs/browser-tab-queries.ts index 51f31bdbe76..5f6deea8b96 100644 --- a/src/main/runtime/browser/tabs/browser-tab-queries.ts +++ b/src/main/runtime/browser/tabs/browser-tab-queries.ts @@ -166,10 +166,7 @@ export class RuntimeBrowserTabQueries { ? (await this.host.resolveBrowserWorkspace(params.worktree)).id : undefined const result = await bridge.tabSwitch(undefined, worktreeId, selected.browserPageId) - this.host.getRuntimeBrowserPageRegistry().deactivateGlobal() - if (worktreeId) { - this.host.getRuntimeBrowserPageRegistry().deactivateWorkspace(worktreeId) - } + this.host.getRuntimeBrowserPageRegistry().yieldSelection(worktreeId) // Scope focus to the owning worktree; never switch the user's workspace. const focusWorktreeId = worktreeId ?? browserManager.getWorktreeIdForTab(result.browserPageId) ?? undefined diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index 0715c88c511..a91a15a9255 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -1,4 +1,4 @@ -import type { WorkspaceMetadataSet } from '../../../../shared/worktree/workspace-metadata-set' +import type { WorkspaceMetadataSet } from '../../../../shared/worktree/metadata/workspace-metadata-set' import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition @@ -13,12 +13,12 @@ import type { AgentLaunchTabPublishRequest } from '../../../../shared/agent-launch/contracts/agent-launch-tab-publication' import type { TerminalPaneSplitSource } from '../../../../shared/feature-education-telemetry' -import type { TerminalRevealIdentity } from '../../../../shared/workspace-layout/terminal-reveal-identity' -import type { TerminalPaneRevealTarget } from '../../../../shared/workspace-layout/terminal-pane-reveal' +import type { TerminalRevealIdentity } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-reveal-identity' +import type { TerminalPaneRevealTarget } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal' import type { TerminalLeafMoveResult, TerminalPaneMoveToNewTabRequest -} from '../../../../shared/workspace-layout/terminal-leaf-move' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { WorkspaceSleepNotice } from '../../../../shared/workspace-sleep' import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' @@ -26,9 +26,9 @@ import type { ClientHostedBrowserRowsEvent } from '../../../../shared/client-hos import type { WorktreeBaseStatusEvent, WorktreeRemoteBranchConflictEvent -} from '../../../../shared/worktree/base-ref-drift-types' +} from '../../../../shared/worktree/base-refs/base-ref-drift-types' import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { RuntimeMobileSessionTabMove, RuntimeTerminalDriverState diff --git a/src/main/runtime/client/navigation/client-session-tab-selection-projection.ts b/src/main/runtime/client/navigation/client-session-tab-selection-projection.ts index 60253dcba2f..d6cbe43a93e 100644 --- a/src/main/runtime/client/navigation/client-session-tab-selection-projection.ts +++ b/src/main/runtime/client/navigation/client-session-tab-selection-projection.ts @@ -1,7 +1,7 @@ import type { RuntimeMobileSessionClientTab } from '../../../../shared/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' import { pickNextActiveTabAfterClose } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close' -import { findSiblingGroupId } from '../../../../shared/workspace-layout/tab-group-layout-tree' +import { findSiblingGroupId } from '../../../../shared/workspace-layout/tab-groups/tab-group-layout-tree' export type ClientSessionTabSelection = { activeTabId: string | null diff --git a/src/main/runtime/client/runtime-client-state.ts b/src/main/runtime/client/runtime-client-state.ts index d2e6570e368..d8e3036681a 100644 --- a/src/main/runtime/client/runtime-client-state.ts +++ b/src/main/runtime/client/runtime-client-state.ts @@ -12,7 +12,7 @@ import { LOCAL_EXECUTION_HOST_ID, getRepoExecutionHostId } from '../../../shared/execution-host' -import type { IPtyProvider } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' import { killAllProcessesForWorktree } from '../workspaces/removal/worktree-teardown' import type { MemorySnapshot, StatsSummary } from '../../../shared/process-stats-types' import { collectMemorySnapshot } from '../../memory/collector' diff --git a/src/main/runtime/client/settings/runtime-client-settings-shape.ts b/src/main/runtime/client/settings/runtime-client-settings-shape.ts index c32d4836729..c59ee8d22e6 100644 --- a/src/main/runtime/client/settings/runtime-client-settings-shape.ts +++ b/src/main/runtime/client/settings/runtime-client-settings-shape.ts @@ -3,6 +3,7 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { VoiceSettings } from '../../../../shared/speech-types' import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceCleanupRules } from '../../../../shared/workspace-cleanup/workspace-cleanup-policy' import type { SourceControlAiActionDefaults } from '../../../../shared/source-control/ai/recipes/source-control-ai-actions' export type RuntimeClientSettings = Pick< @@ -42,6 +43,8 @@ export type RuntimeClientSettings = Pick< | 'sourceControlCompareAgainstUpstream' | 'diffShowWhitespace' > & { + /** Always set; older hosts omit it, so clients must not write it to them (settings.update is strict). */ + workspaceCleanupPolicy: WorkspaceCleanupRules hostSettingOverrides: RuntimeHostDisplayLabelOverrides sourceControlAi: RuntimeClientSourceControlAi /** Models directory and microphone stay host-private. */ @@ -82,4 +85,5 @@ export type RuntimeClientSettingsUpdate = Pick< | 'machineName' | 'nativeChatPermissionMode' | 'nativeChatAutoContinueAfterUsageLimit' + | 'workspaceCleanupPolicy' > diff --git a/src/main/runtime/client/settings/runtime-client-settings.ts b/src/main/runtime/client/settings/runtime-client-settings.ts index 16b1030d13a..4008aa9c0ad 100644 --- a/src/main/runtime/client/settings/runtime-client-settings.ts +++ b/src/main/runtime/client/settings/runtime-client-settings.ts @@ -17,6 +17,7 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import { applyNativeChatSessionOptionSettingsMutation } from '../../../../shared/native-chat/input/native-chat-session-option-defaults' import type { NativeChatSessionOptionSettingsMutation } from '../../../../shared/native-chat/input/native-chat-session-options' import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-overrides' +import { getDefaultWorkspaceCleanupRules } from '../../../../shared/workspace-cleanup/workspace-cleanup-policy' import { nativeChatQueueFollowUps } from '../../../../shared/native-chat/input/native-chat-follow-up-behavior' import { nativeChatShowsCiResultLines } from '../../../../shared/native-chat/native-chat-appearance-settings' import type { TerminalQuickCommand } from '../../../../shared/terminal/quick-commands/terminal-quick-command-types' @@ -105,6 +106,7 @@ export class RuntimeClientSettingsController { ? {} : { artifactSharingEnabled: isArtifactSharingEnabled(settings) }), worktreeVisibilityDefaults: settings.worktreeVisibilityDefaults ?? { external: 'hide' }, + workspaceCleanupPolicy: settings.workspaceCleanupPolicy ?? getDefaultWorkspaceCleanupRules(), ...(this.sharingServices?.skills() === false ? {} : { agentSkillSharingEnabled: isAgentSkillSharingEnabled(settings) }), diff --git a/src/main/runtime/client/settings/runtime-workspace-view-change-events.ts b/src/main/runtime/client/settings/runtime-workspace-view-change-events.ts new file mode 100644 index 00000000000..275a24b3159 --- /dev/null +++ b/src/main/runtime/client/settings/runtime-workspace-view-change-events.ts @@ -0,0 +1,40 @@ +import { isDeepStrictEqual } from 'node:util' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' +import { ALL_WORKSPACE_VIEW_UI_FIELDS } from '../../../../shared/workspace-view/workspace-view-ui-fields' +import type { RuntimeStore } from '../../construction/runtime-store-contract' + +/** The settings a phone's workspace list mirrors: Card layout, card style and pinned placement. */ +const WORKSPACE_VIEW_SETTINGS: readonly (keyof GlobalSettings)[] = [ + 'compactWorktreeCards', + 'experimentalNewWorktreeCardStyle', + 'showPinnedWorktreesInGroups' +] + +function workspaceViewUiValues(ui: PersistedUIState): unknown[] { + return ALL_WORKSPACE_VIEW_UI_FIELDS.map((key) => ui[key]) +} + +/** Publish workspace-option changes promptly without re-reading on every UI drag frame. */ +export function publishWorkspaceViewChanges( + store: Pick | null, + emit: (event: RuntimeClientEvent) => void +): void { + if (!store?.getUI || !store.onUIChanged) { + return + } + let previous = workspaceViewUiValues(store.getUI()) + store.onUIChanged((ui) => { + const next = workspaceViewUiValues(ui) + if (!isDeepStrictEqual(previous, next)) { + previous = next + emit({ type: 'workspaceViewChanged' }) + } + }) + store.onSettingsChanged?.((updates) => { + if (WORKSPACE_VIEW_SETTINGS.some((key) => key in updates)) { + emit({ type: 'workspaceViewChanged' }) + } + }) +} diff --git a/src/main/runtime/sidebar-inputs/workspace-view-collapse-writes.ts b/src/main/runtime/client/settings/workspace-view-collapse-writes.ts similarity index 92% rename from src/main/runtime/sidebar-inputs/workspace-view-collapse-writes.ts rename to src/main/runtime/client/settings/workspace-view-collapse-writes.ts index 4b2f55b5bc4..cbfe6ffe6b4 100644 --- a/src/main/runtime/sidebar-inputs/workspace-view-collapse-writes.ts +++ b/src/main/runtime/client/settings/workspace-view-collapse-writes.ts @@ -1,8 +1,8 @@ -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' import type { SetCollapsedRequest, SetCollapsedResult -} from '../../../shared/rpc-contract/workspace-view-collapse-params' +} from '../../../../shared/rpc-contract/workspaces/workspace-view-collapse-params' // Far above writers x sections in use; an evicted entry only lets a very old retry apply again. const MAX_TRACKED_WRITES = 4096 diff --git a/src/main/runtime/construction/dark-switch-runtime-capabilities.ts b/src/main/runtime/construction/dark-switch-runtime-capabilities.ts index 3195f45d33d..f4cf787b867 100644 --- a/src/main/runtime/construction/dark-switch-runtime-capabilities.ts +++ b/src/main/runtime/construction/dark-switch-runtime-capabilities.ts @@ -4,7 +4,7 @@ import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../shared/sidebar-inputs-swit import { LAYOUT_INTENTS_RUNTIME_CAPABILITY, LAYOUT_REOPEN_HELD_PANES_CAPABILITY -} from '../../../shared/workspace-layout/layout-intents-capability' +} from '../../../shared/workspace-layout/published-layout/layout-intents-capability' import { WORKSPACE_UNREAD_HOST_RAISES_CAPABILITY } from '../../../shared/workspace-unread-raise-capability' export function darkSwitchRuntimeCapabilities(): RuntimeCapability[] { diff --git a/src/main/runtime/construction/orca-runtime-agent-transitions.ts b/src/main/runtime/construction/orca-runtime-agent-transitions.ts index 4700e65ad43..6cc3657600d 100644 --- a/src/main/runtime/construction/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/construction/orca-runtime-agent-transitions.ts @@ -1,4 +1,4 @@ -import { watchMovedWorkerResumeSessions } from '../rpc/methods/orchestration/worker/worker-resume-session-capture' +import { watchMovedWorkerResumeSessions } from '../rpc/methods/orchestration/worker/follow-up/worker-resume-session-capture' import { AgentTransitionDetector } from '../../agent-hooks/observations/agent-transition-detector' import type { ConnectorCloud } from '../../connector-cloud/connector-cloud' import type { ExternalConversationSeam } from '../../external-conversations/external-conversation-seam' @@ -7,9 +7,9 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-cont import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { OrcaRuntimeWithWindowlessTerminalActivity } from '../sidebar-inputs/orca-runtime-windowless-terminal-activity' +import { OrcaRuntimeWithWindowlessTerminalActivity } from '../sidebar-inputs/temporal/orca-runtime-windowless-terminal-activity' import { getRuntimeDesktopSurface } from './runtime-desktop-surface' -import type { AgentStatusStoreView } from '../sidebar-inputs/workspace-activity-facts-producer' +import type { AgentStatusStoreView } from '../sidebar-inputs/workspace-facts/workspace-activity-facts-producer' import { subscribeHookStatusTitles } from '../terminal/layout/hook-status-title-subscription' import { resolveTerminalWorkerDispatch, @@ -99,8 +99,9 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithWin readHookRow: (paneKey) => this.agentTransitions.latestRow(paneKey), setTimer: unrefTimer, readScreen: (handle) => this.readTerminal(handle, { screen: true, limit: 15 }), - takeOpenApproval: (paneKey, dispatchId, reporting) => - this.terminalWorkerApprovals.takeOpenApproval(paneKey, dispatchId, reporting) + takeOpenApproval: (paneKey, dispatchId) => + this.terminalWorkerApprovals.takeOpenApproval(paneKey, dispatchId), + markApprovalReported: (approvalId) => this.terminalWorkerApprovals.markReported(approvalId) }) private readonly externalConversations = installExternalConversations(this.store, this) diff --git a/src/main/runtime/construction/orca-runtime.test.ts b/src/main/runtime/construction/orca-runtime.test.ts index f0ca09dcef6..22d0d8cbee4 100644 --- a/src/main/runtime/construction/orca-runtime.test.ts +++ b/src/main/runtime/construction/orca-runtime.test.ts @@ -22,24 +22,18 @@ await import('../orca-runtime-tests/terminal-listing.spec') await import('../orca-runtime-tests/worktree-selector-resolution.spec') await import('../orca-runtime-tests/local-worktree-creation.spec') await import('../orca-runtime-tests/local-worktree-creation-part-02.spec') -await import('../orca-runtime-tests/ssh-worktree-lifecycle.spec') await import('../orca-runtime-tests/hooks-and-hosted-review-part-02.spec') -await import('../orca-runtime-tests/repository-project-operations.spec') await import('../orca-runtime-tests/repository-project-operations-part-02.spec') await import('../orca-runtime-tests/project-setup-folder-remote-identity.spec') await import('../orca-runtime-tests/pty-title-status.spec') await import('../orca-runtime-tests/terminal-side-effect-facts.spec') await import('../orca-runtime-tests/terminal-side-effect-facts-part-02.spec') -await import('../orca-runtime-tests/terminal-side-effect-facts-part-03.spec') await import('../orca-runtime-tests/headless-snapshots.spec') -await import('../orca-runtime-tests/headless-snapshots-part-02.spec') -await import('../orca-runtime-tests/agent-status-and-waits.spec') await import('../orca-runtime-tests/agent-status-and-waits-part-02.spec') -await import('../orca-runtime-tests/agent-status-and-waits-part-03.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-02.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-04.spec') -await import('../orca-runtime-tests/terminal-creation-and-readiness-part-05.spec') + await import('../orca-runtime-tests/terminal-creation-and-readiness-part-06.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-07.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-08.spec') @@ -49,19 +43,15 @@ await import('../orca-runtime-tests/terminal-creation-and-readiness-part-10.spec await import('../orca-runtime-tests/terminal-creation-and-readiness-part-11.spec') await import('../orca-runtime-tests/conpty-stream-read.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-12.spec') -await import('../orca-runtime-tests/terminal-output-and-worker-recovery.spec') await import('../orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec') await import('../orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec') await import('../orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec') -await import('../orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec') await import('../orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec') await import('../orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec') await import('../orca-runtime-tests/terminal-handles-and-agent-status.spec') await import('../orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec') -await import('../orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec') await import('../orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec') await import('../orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec') -await import('../orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec') await import('../orca-runtime-tests/mobile-session-tabs.spec') await import('../orca-runtime-tests/mobile-session-tabs-part-02.spec') await import('../orca-runtime-tests/mobile-session-tabs-part-03.spec') @@ -80,7 +70,6 @@ await import('../orca-runtime-tests/mobile-session-tabs-targeted-agent-resume.sp await import('../orca-runtime-tests/mobile-session-tabs-headless-wake-report.spec') await import('../orca-runtime-tests/exit-retirement-activation.spec') await import('../orca-runtime-tests/mobile-creation-and-orchestration.spec') -await import('../orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec') await import('../orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec') await import('../orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec') await import('../orca-runtime-tests/mobile-summaries.spec') @@ -99,12 +88,11 @@ await import('../orca-runtime-tests/wsl-stopped-distro-worktree-scan.spec') await import('../orca-runtime-tests/worktree-setup-and-startup-part-03.spec') await import('../orca-runtime-tests/worktree-setup-and-startup-part-04.spec') -await import('../orca-runtime-tests/worktree-setup-single-creator.spec') + await import('../orca-runtime-tests/gitlab-and-pr-bases-part-02.spec') await import('../orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec') await import('../orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec') await import('../orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec') -await import('../orca-runtime-tests/worktree-removal-archive-hook-gate.spec') await import('../orca-runtime-tests/worktree-removal-failed-retry.spec') await import('../orca-runtime-tests/targeting-and-resilience.spec') await import('../orca-runtime-tests/worktree-scan-cache-ttl.spec') diff --git a/src/main/runtime/sidebar-inputs/require-switched-on.ts b/src/main/runtime/construction/require-sidebar-inputs-enabled.ts similarity index 100% rename from src/main/runtime/sidebar-inputs/require-switched-on.ts rename to src/main/runtime/construction/require-sidebar-inputs-enabled.ts diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index e7d30136582..1497669db64 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -1,6 +1,6 @@ import type { CliWriterObservation } from '../../agent-hooks/server/cli-writer-observation' import type { ExecutionHostScope } from '../../../shared/execution-host' -import type { IPtyProvider } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' import type { PrepareClaudeAuth } from '../../ipc/pty/host-env/types' import type { RuntimeTerminalAgentStatusEvent, diff --git a/src/main/runtime/construction/runtime-construction-services.ts b/src/main/runtime/construction/runtime-construction-services.ts index 6c1c4baadcd..68ee5e5cea7 100644 --- a/src/main/runtime/construction/runtime-construction-services.ts +++ b/src/main/runtime/construction/runtime-construction-services.ts @@ -1,7 +1,7 @@ import type { TerminalIdentityReadContext as IdentityRead } from '../terminal/query/terminal-identity-read-context' import type * as Calls from './runtime-host-service-calls' import type { selectFreshExplicitAgentStatus } from '../workspaces/process-listing/runtime-hook-agent-row-selection' -import type { IPtyProvider } from '../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../providers/pty/provider-contract' import type { RuntimePtyWorktreeRecord, RuntimeHeadlessTerminal, @@ -210,7 +210,8 @@ export abstract class RuntimeConstructionServices { protected abstract selectReposBySelector(selector: string): Repo[] protected abstract listRepoWorktreesForListing( repo: Repo, - projectRuntimeByRepoId?: ReadonlyMap + projectRuntimeByRepoId?: ReadonlyMap, + options?: { claimsHygiene?: boolean } ): Promise protected abstract listKnownExecutionHostIds( additionalHostIds?: Iterable, diff --git a/src/main/runtime/construction/runtime-construction.ts b/src/main/runtime/construction/runtime-construction.ts index 797bbb1e977..0d4e0c709fb 100644 --- a/src/main/runtime/construction/runtime-construction.ts +++ b/src/main/runtime/construction/runtime-construction.ts @@ -14,7 +14,7 @@ import type { ProjectExecutionRuntimeResolution } from '../../../shared/executio import { OrcaRuntimeWithLinearCommands } from '../integrations/linear/linear-commands' import type { RuntimeStore } from './runtime-store-contract' -import { installGitHubProjectAccounts } from '../../github/github-project-account' +import { installGitHubProjectAccounts } from '../../github/accounts/github-project-account' import type { WorkspaceSleepPlatform } from '../workspaces/sleep/workspace-sleep-platform' import type { StatsCollector } from '../../stats/collector' @@ -50,13 +50,13 @@ import { RuntimeClientSettingsController } from '../client/settings/runtime-clie import { RuntimeSessionSearchSettingsController } from '../integrations/ai-vault/runtime-session-search-settings' import { RuntimeAutomationController } from '../integrations/automations/runtime-automation-controller' import { RuntimeOrchestrationFederation } from '../orchestration/federation/runtime-orchestration-federation' -import { configureAiVaultSessionSources } from '../../ai-vault/cached-session-list' -import { configureHostReadableTranscriptPathSources } from '../../native-chat/host-readable-transcript-path' +import { configureAiVaultSessionSources } from '../../ai-vault/discovery/ai-vault-scan-roots' +import { configureHostReadableTranscriptPathSources } from '../../native-chat/transcript-discovery/host-readable-transcript-path' import { createEphemeralAgentSessionClaimSigner } from '../agent-session/ownership/agent-session-claim-identity' import { registerConptyDa1OverrideInstaller } from '../terminal/output/terminal-model-query-authority' import { registerTerminalViewAttributesApplier } from '../terminal/view/terminal-view-attribute-store' import { RuntimeMachineName } from '../hosts/platform-probe/runtime-machine-name' -import { setPRConflictSummaryRemoteFetches } from '../../github/conflict-summary' +import { setPRConflictSummaryRemoteFetches } from '../../github/pull-requests/conflicts/conflict-summary' import { DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT } from '../../../shared/terminal/replay/terminal-scrollback-policy' // oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- SAFETY: The constructor installs every checked canonical surface. diff --git a/src/main/runtime/construction/runtime-edge-command-controller.ts b/src/main/runtime/construction/runtime-edge-command-controller.ts index 6d6b7fac4ec..f76118f1fdd 100644 --- a/src/main/runtime/construction/runtime-edge-command-controller.ts +++ b/src/main/runtime/construction/runtime-edge-command-controller.ts @@ -6,7 +6,7 @@ import { RuntimeEmulatorCommands } from '../emulator/runtime-emulator-commands' import { RuntimeBrowserScreencastController } from '../browser/screencast/runtime-browser-screencast-controller' import { createRuntimeBrowserCommands } from '../browser/installation/runtime-browser-commands-factory' import { RuntimeJiraCommands } from '../integrations/jira/runtime-jira-commands' -import type { RpcBinarySender } from '../rpc/rpc-binary-sender' +import type { RpcBinarySender } from '../rpc/transports/rpc-binary-sender' type PublicMethods = Pick type BrowserSurface = Omit, 'browserScreencast'> & { diff --git a/src/main/runtime/construction/runtime-file-command-state.ts b/src/main/runtime/construction/runtime-file-command-state.ts index da392c5e975..fadf9abe715 100644 --- a/src/main/runtime/construction/runtime-file-command-state.ts +++ b/src/main/runtime/construction/runtime-file-command-state.ts @@ -1,5 +1,5 @@ import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import type { LocalProjectGhExecOptions } from '../../workspaces/execution-host/project-runtime-git-options' import { OrcaRuntimeWithPreservedBranchCleanup } from './runtime-host-services' import { createRuntimeFileWatcherRemoval } from '../workspaces/removal/runtime-file-watcher-removal' @@ -14,7 +14,7 @@ import type { RuntimeRepoSelector } from '../workspaces/catalog/runtime-repo-sel import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types' import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' import { createRuntimeEditorFileOpener } from '../files/editor-open-through-layout-owner' -import { resolveNativeChatMediaPath } from '../../native-chat/native-chat-media-path' +import { resolveNativeChatMediaPath } from '../../native-chat/conversation-files/native-chat-media-path' import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { RuntimeFileSearch } from '../files/search/file-search' import { RuntimeTerminalArtifacts } from '../terminal/artifacts/terminal-artifacts' diff --git a/src/main/runtime/construction/runtime-identity-state.ts b/src/main/runtime/construction/runtime-identity-state.ts index cd404f04b8d..ea4a9ce5aa7 100644 --- a/src/main/runtime/construction/runtime-identity-state.ts +++ b/src/main/runtime/construction/runtime-identity-state.ts @@ -71,6 +71,20 @@ import type { TerminalHandleAccess } from '../agent-senders/runtime-agent-sender import { RuntimeConstructionServices } from './runtime-construction-services' +export type ClientHostedPageObservation = MobileSessionTabSubscription | symbol + +export type MobileSessionTabSubscription = { + listener: ( + snapshot: RuntimeMobileSessionTabsResult, + changeSequence: number, + delivery?: 'reconciliation' + ) => void + clientNavigationId?: string + clientKind?: 'mobile' | 'runtime' + observation?: 'caller' + acceptsWorktree?: (worktree: string) => boolean +} + export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServices { protected getLeafKey(tabId: string, leafId: string): string { return `${tabId}::${leafId}` @@ -217,11 +231,7 @@ export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServic } >() - protected mobileSessionTabListeners = new Set<{ - listener: (snapshot: RuntimeMobileSessionTabsResult, changeSequence: number) => void - clientNavigationId?: string - clientKind?: 'mobile' | 'runtime' - }>() + protected mobileSessionTabListeners = new Set() protected pendingMobileSessionTabsChangeSequenceByWorktree = new Map() diff --git a/src/main/runtime/construction/runtime-service-command-surface.ts b/src/main/runtime/construction/runtime-service-command-surface.ts index 5c35c36b2da..8cd562414d0 100644 --- a/src/main/runtime/construction/runtime-service-command-surface.ts +++ b/src/main/runtime/construction/runtime-service-command-surface.ts @@ -201,7 +201,8 @@ export function installRuntimeServiceCommandSurface( clearOpenAiSpeechKey: speech.clearOpenAiKey.bind(speech), startMobileDictation: dictation.start.bind(dictation), feedMobileDictation: dictation.feed.bind(dictation), - finishMobileDictation: dictation.finish.bind(dictation), + finishMobileDictation: (params) => + dictation.finish(params, accounts.getCommitMessageAgentEnvironment()), cancelMobileDictation: dictation.cancel.bind(dictation), getAllBrowserDrivers: browsers.getAll.bind(browsers), reclaimBrowserForDesktop: browsers.reclaimForDesktop.bind(browsers), diff --git a/src/main/runtime/construction/runtime-service-state.ts b/src/main/runtime/construction/runtime-service-state.ts index f25190d73ee..6962b1c843d 100644 --- a/src/main/runtime/construction/runtime-service-state.ts +++ b/src/main/runtime/construction/runtime-service-state.ts @@ -14,7 +14,6 @@ import { RuntimeClientEventBus } from '../client/events/runtime-client-event-bus import { RuntimeNativeChatDraftResolutions } from '../agent-session/launch/runtime-native-chat-draft-resolutions' import { RuntimeWorktreeLifecycleEvents } from '../workspaces/lifecycle/runtime-worktree-lifecycle-events' import type { RuntimeWorktreeLifecycleEvent } from '../workspaces/lifecycle/worktree-lifecycle-event' -import type * as WorktreeScan from '../workspaces/catalog/runtime-worktree-scan-state' import type { AgentBrowserBridge } from '../../browser/agent-browser/agent-browser-bridge' import type { BrowserBackend } from '../../browser/browser-backend' import type { EmulatorBridge } from '../../emulator/emulator-bridge' @@ -100,12 +99,6 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith protected readonly resolvedWorktrees = new RuntimeResolvedWorktreeCache() - protected worktreeScanGenerations = new Map() - - protected worktreeScanCache = new Map() - - protected worktreeScanInFlight = new Map() - /** Bound abandoned Git-admin filesystem probes to one per repo. */ protected worktreeAdminFingerprintProbes = new Set() @@ -154,7 +147,8 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith listResolved: () => this.listResolvedWorktrees(), resolveRepo: (selector) => this.resolveRepoSelector(selector), selectRepos: (selector) => this.selectReposBySelector(selector), - scanRepo: (repo) => this.listRepoWorktreesForListing(repo), + // listDetected prunes metadata, so its scans carry the pre-scan hygiene claim. + scanRepo: (repo) => this.listRepoWorktreesForListing(repo, undefined, { claimsHygiene: true }), listKnownHostIds: () => this.listKnownExecutionHostIds() }) @@ -314,7 +308,13 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith isWaitingForMail: (mailbox) => (this.messageWaiters.get(mailbox)?.size ?? 0) > 0, notify: (handle, messageType) => this.notifyMessageArrived(handle, messageType), isChatMailbox: (mailbox) => - typeof structuredMailboxCustody(mailbox, this._orchestrationDb) === 'object' + typeof structuredMailboxCustody(mailbox, this._orchestrationDb) === 'object', + coordinatorApprovals: () => this.coordinatorApprovalsEnabled() + } + + /** This machine's own setting: it runs the worker, so it decides whether an agent may allow its prompts. */ + coordinatorApprovalsEnabled(): boolean { + return this.store?.getSettings?.()?.orchestrationCoordinatorApprovalsEnabled === true } protected readonly lostWorkerReport: LostWorkerReport = { diff --git a/src/main/runtime/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index 4847daa5909..3d976eede42 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -104,6 +104,7 @@ export type RuntimeStore = { listAutomationRunsPage?: Store['listAutomationRunsPage'] createAutomation?: Store['createAutomation'] updateAutomation?: Store['updateAutomation'] + updateAutomations?: Store['updateAutomations'] deleteAutomation?: Store['deleteAutomation'] getSparsePresets?: Store['getSparsePresets'] saveSparsePreset?: Store['saveSparsePreset'] @@ -124,6 +125,7 @@ export type RuntimeStore = { codexShareHistoryAcrossAccounts?: GlobalSettings['codexShareHistoryAcrossAccounts'] nestedWorkerMaxDepth?: GlobalSettings['nestedWorkerMaxDepth'] orchestrationWorkerAutoReleaseEnabled?: GlobalSettings['orchestrationWorkerAutoReleaseEnabled'] + orchestrationCoordinatorApprovalsEnabled?: GlobalSettings['orchestrationCoordinatorApprovalsEnabled'] workspaceDir: string nestWorkspaces: boolean workspaceDirHistory?: GlobalSettings['workspaceDirHistory'] @@ -189,6 +191,7 @@ export type RuntimeStore = { terminalHiddenDeliveryGate?: GlobalSettings['terminalHiddenDeliveryGate'] terminalModelQueryAuthority?: GlobalSettings['terminalModelQueryAuthority'] worktreeVisibilityDefaults?: GlobalSettings['worktreeVisibilityDefaults'] + workspaceCleanupPolicy?: GlobalSettings['workspaceCleanupPolicy'] hostSettingOverrides?: GlobalSettings['hostSettingOverrides'] activeRuntimeEnvironmentId?: GlobalSettings['activeRuntimeEnvironmentId'] showPinnedWorktreesInGroups?: GlobalSettings['showPinnedWorktreesInGroups'] diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-dispatch.test.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-dispatch.test.ts index 8810994f1ea..5929827f0cb 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-dispatch.test.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-dispatch.test.ts @@ -9,8 +9,8 @@ import { defineMethod } from '../rpc/core' import { RpcDispatcher } from '../rpc/dispatcher' import { DESKTOP_BROWSER_BRIDGE_RPC_METHODS } from '../rpc/methods/browser/desktop-browser-bridge' import { BrowserTarget } from '../../../shared/rpc-contract/rpc-param-primitives' -import { Goto } from '../../../shared/rpc-contract/browser-params' -import { BrowserOpenUrlParams } from '../../../shared/rpc-contract/browser-tab-create-params' +import { Goto } from '../../../shared/rpc-contract/browser/browser-params' +import { BrowserOpenUrlParams } from '../../../shared/rpc-contract/browser/browser-tab-create-params' import { getDesktopBrowserBridgeRegistry, setDesktopBrowserBridgeHostEnabled diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts index 2f472b5f36e..49954b49970 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-route.ts @@ -8,7 +8,7 @@ import { } from '../../../shared/desktop-browser-bridge-protocol' import { BROWSER_EXPECT_URL_UNSUPPORTED_CODE } from '../../../shared/browser/client-hosting/browser-expected-url' import { browserWaitRequestTimeoutMs } from '../../../shared/browser-wait-timeout' -import type { RpcCallerIdentity } from '../rpc/rpc-caller-identity' +import type { RpcCallerIdentity } from '../rpc/callers/rpc-caller-identity' import { assertClientOpenableUrl } from '../browser/client-pages/browser-client-page-opening' import type { DesktopBrowserBridgeRegistry } from './desktop-browser-bridge-registry' diff --git a/src/main/runtime/files/chat-scratch-file-root.ts b/src/main/runtime/files/chat-scratch-file-root.ts index cb75684420b..bb33a00ad4a 100644 --- a/src/main/runtime/files/chat-scratch-file-root.ts +++ b/src/main/runtime/files/chat-scratch-file-root.ts @@ -6,7 +6,7 @@ import { type ResolveAuthorizedPathOptions } from '../../ipc/filesystem/access/filesystem-auth' import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' -import { nativeChatScratchRootFor } from '../../native-chat/native-chat-scratch-folder' +import { nativeChatScratchRootFor } from '../../native-chat/conversation-files/native-chat-scratch-folder' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { getFloatingWorkspaceFileRoots } from '../../ipc/floating-workspace-directory' diff --git a/src/main/runtime/files/file-access.ts b/src/main/runtime/files/file-access.ts index 1ec963b2319..48692f39c1a 100644 --- a/src/main/runtime/files/file-access.ts +++ b/src/main/runtime/files/file-access.ts @@ -2,7 +2,7 @@ import type { RuntimeFileOpenPosition, RuntimeFileOpenResult } from '../../../shared/file-access/runtime-editor-file-open' -import { listFilesystemMarkdownDocuments } from '../../providers/filesystem-markdown-listing' +import { listFilesystemMarkdownDocuments } from '../../providers/filesystem/markdown-listing' import type { MarkdownDocument } from '../../../shared/file-listing/file-document' import { validatePathExistenceBatch, @@ -25,7 +25,7 @@ import { resolveFileExplorerPaths } from './file-target' import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import type { FileStat } from '../../providers/filesystem-provider-contract' +import type { FileStat } from '../../providers/filesystem/provider-contract' import { assertRuntimeReadWslDistroRunning } from '../integrations/git/runtime-wsl-background-read-gate' type RuntimeFileAccessHost = Pick< diff --git a/src/main/runtime/files/file-command-host.ts b/src/main/runtime/files/file-command-host.ts index 9fe85b417a3..95f14ddecdb 100644 --- a/src/main/runtime/files/file-command-host.ts +++ b/src/main/runtime/files/file-command-host.ts @@ -6,7 +6,7 @@ import type { RuntimeFileOpenPosition } from '../../../shared/file-access/runtim import type { NativeChatMediaPathRequest, NativeChatMediaPathResolution -} from '../../native-chat/native-chat-media-path' +} from '../../native-chat/conversation-files/native-chat-media-path' export type RuntimeFileCommandHost = { getRuntimeId(): string diff --git a/src/main/runtime/files/file-reads.ts b/src/main/runtime/files/file-reads.ts index f84056c724b..587faf2088c 100644 --- a/src/main/runtime/files/file-reads.ts +++ b/src/main/runtime/files/file-reads.ts @@ -40,7 +40,7 @@ import type { DocPreviewFileChunk, DocPreviewFileTarget } from '../../../shared/document-preview/doc-preview-file-access' -import type { LocalFilesystemProvider } from '../../providers/local-filesystem-provider' +import type { LocalFilesystemProvider } from '../../providers/filesystem/local-provider' const CHAT_IMAGE_ACCESS: LocalFileAccess = { kind: 'chat-image' } diff --git a/src/main/runtime/files/file-target.ts b/src/main/runtime/files/file-target.ts index 3e031f3ade3..cc58917aa7d 100644 --- a/src/main/runtime/files/file-target.ts +++ b/src/main/runtime/files/file-target.ts @@ -13,7 +13,7 @@ import type { createLocalFilesystemProvider, LocalFilesystemProvider, LocalFilesystemProviderOptions -} from '../../providers/local-filesystem-provider' +} from '../../providers/filesystem/local-provider' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' export type ResolvedRuntimeFileWorktree = Worktree & { git: GitWorktreeInfo } diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index 73dc3dea758..7452fa18c76 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -13,9 +13,9 @@ import { runtimeBrowserUnavailableCause } from '../browser/installation/runtime-browser-commands-factory' import { isBrowserIdentityModeStoreInitialized } from '../../browser/identity/mode/browser-identity-mode-store' -import { servesLocalWslMigrationSource } from '../../orcad/orcad-migration-wsl-destination' +import { servesLocalWslMigrationSource } from '../../orcad/migration/orcad-migration-wsl-destination' import { ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY } from '../../../shared/orcad-runtime-capabilities' -import { advertisedOrcadMigrationDestinationCapabilities } from '../../orcad/orcad-migration-destination-capabilities' +import { advertisedOrcadMigrationDestinationCapabilities } from '../../orcad/migration/orcad-migration-destination-capabilities' import { USAGE_CREDENTIALS_RUNTIME_CAPABILITY } from '../../../shared/account-runtime-capabilities' import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, diff --git a/src/main/runtime/integrations/ai-vault/runtime-ai-vault-commands.ts b/src/main/runtime/integrations/ai-vault/runtime-ai-vault-commands.ts index 2ac12d2e69d..513158d547a 100644 --- a/src/main/runtime/integrations/ai-vault/runtime-ai-vault-commands.ts +++ b/src/main/runtime/integrations/ai-vault/runtime-ai-vault-commands.ts @@ -10,8 +10,8 @@ import type { AiVaultListArgs, AiVaultListResult } from '../../../../shared/ai-vault/contracts/ai-vault-types' -import { listAiVaultSessions } from '../../../ai-vault/cached-session-list' -import { deleteAiVaultSessionForRemoteClient } from '../../../ai-vault/host-session-delete' +import { listAiVaultSessions } from '../../../ai-vault/listing/cached-session-list' +import { deleteAiVaultSessionForRemoteClient } from '../../../ai-vault/deletion/host-session-delete' import type { AiVaultDeleteSessionArgs, AiVaultDeleteSessionResult diff --git a/src/main/runtime/integrations/automations/runtime-automation-batch-update.ts b/src/main/runtime/integrations/automations/runtime-automation-batch-update.ts new file mode 100644 index 00000000000..cdd10f0ecd2 --- /dev/null +++ b/src/main/runtime/integrations/automations/runtime-automation-batch-update.ts @@ -0,0 +1,39 @@ +import type { AutomationUpdateInput } from '../../../../shared/automations/automation-definition' +import type { AutomationBatchUpdateResult } from '../../../persistence/scheduling-automations/automation-definition-update' +import type { RuntimeStore } from '../../construction/runtime-store-contract' + +/** Why only these fields: target, run-context and session changes need the checks only a single + * `update` performs, so the batch path cannot carry them. */ +export type RuntimeAutomationBatchUpdate = { + id: string + updates: Pick +} + +/** + * The controller's `update` for many automations at once: one store write and one flush instead + * of one per row. + */ +export async function updateRuntimeAutomations( + store: RuntimeStore | null, + entries: readonly RuntimeAutomationBatchUpdate[] +): Promise { + if (!store?.updateAutomations) { + throw new Error('runtime_unavailable') + } + if (entries.length === 0) { + return [] + } + const results = store.updateAutomations( + entries.map(({ id, updates }) => ({ + id, + updates: { + ...(updates.enabled !== undefined ? { enabled: updates.enabled } : {}), + ...(updates.createdBy !== undefined ? { createdBy: updates.createdBy } : {}) + } + })) + ) + if (results.some((result) => 'automation' in result)) { + await store.flushPendingOrThrowAsync?.({ drainToStableGeneration: false }) + } + return results +} diff --git a/src/main/runtime/integrations/automations/runtime-automation-controller.ts b/src/main/runtime/integrations/automations/runtime-automation-controller.ts index e5ea2e49f6f..64c5fdd0d07 100644 --- a/src/main/runtime/integrations/automations/runtime-automation-controller.ts +++ b/src/main/runtime/integrations/automations/runtime-automation-controller.ts @@ -1,7 +1,7 @@ import { hostQualifiedRepoSelector } from '../../workspaces/catalog/runtime-repo-selector' import { RUNTIME_AUTOMATION_PATCH_KEYS } from './runtime-automation-patch-keys' import { parseExecutionHostId } from '../../../../shared/execution-host' -import type { AutomationService } from '../../../automations/service' +import type { AutomationService } from '../../../automations/automation-service' import type { Automation, AutomationUpdateInput @@ -18,9 +18,13 @@ import type { AutomationOwnerPrecondition, AutomationDestination } from '../../../../shared/automations/ownership/automation-owner-precondition' -import { runAutomationNowFenced } from '../../../automations/refused-manual-run' +import { runAutomationNowFenced } from '../../../automations/dispatch/refused-manual-run' import { paginateAutomationRuns } from '../../../../shared/automations/history/automation-run-cursor' import { hasRuntimeAutomationUpdateValue } from './runtime-automation-update-value' +import { + updateRuntimeAutomations, + type RuntimeAutomationBatchUpdate +} from './runtime-automation-batch-update' import { assertAutomationRunContextMatchesTarget, type RuntimeAutomationTargetResolvers, @@ -94,12 +98,16 @@ export class RuntimeAutomationController { async create( input: RuntimeAutomationCreateInput, - destination?: AutomationDestination + destination?: AutomationDestination, + /** Runs after the target resolves, right before the write; a throw refuses it (a plugin + * creator that lost its approval meanwhile). */ + beforeWrite?: () => void ): Promise { if (!this.store?.createAutomation) { throw new Error('runtime_unavailable') } const target = await this.resolveTarget(input) + beforeWrite?.() assertAutomationRunContextMatchesTarget(input.runContext, target.repo) if (input.reuseSession && target.workspaceMode !== 'existing') { throw new Error('Session reuse requires an existing workspace target.') @@ -126,7 +134,8 @@ export class RuntimeAutomationController { rrule: input.rrule, dtstart: input.dtstart, enabled: input.enabled, - missedRunGraceMinutes: input.missedRunGraceMinutes + missedRunGraceMinutes: input.missedRunGraceMinutes, + createdBy: input.createdBy }, { destination: destination ?? input.destination, resolvedRepo: target.repo ?? undefined } ) @@ -187,6 +196,11 @@ export class RuntimeAutomationController { return automation } + /** `update` for many automations with one store write and one flush; moves need `update`. */ + updateMany(entries: readonly RuntimeAutomationBatchUpdate[]) { + return updateRuntimeAutomations(this.store, entries) + } + async delete( id: string, expectedOwner?: AutomationOwnerPrecondition diff --git a/src/main/runtime/integrations/automations/runtime-automation-create-revocation.test.ts b/src/main/runtime/integrations/automations/runtime-automation-create-revocation.test.ts new file mode 100644 index 00000000000..0641d701284 --- /dev/null +++ b/src/main/runtime/integrations/automations/runtime-automation-create-revocation.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../../../shared/repo-types' +import { RuntimeAutomationController } from './runtime-automation-controller' + +describe('creating an automation for a plugin', () => { + it('writes nothing when the plugin loses approval while the target resolves', async () => { + let approved = true + const createAutomation = vi.fn() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: create reads only these store members. + const store = { createAutomation } as never + const controller = new RuntimeAutomationController(store, { + showRepo: async () => { + // The person disables the plugin while Orca resolves the project. + approved = false + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: create reads id and path only. + return { id: 'r1', path: '/src/r1' } as Repo + }, + showManagedWorktree: vi.fn() + }) + await expect( + controller.create( + { + name: 'Nightly', + prompt: 'Check', + agentId: 'claude', + repo: 'id:r1', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: 1 + }, + undefined, + () => { + if (!approved) { + throw new Error('plugin is no longer enabled') + } + } + ) + ).rejects.toThrow('plugin is no longer enabled') + expect(createAutomation).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/integrations/automations/runtime-automation-patch-keys.ts b/src/main/runtime/integrations/automations/runtime-automation-patch-keys.ts index 47c808bbdda..d3f1cc8e221 100644 --- a/src/main/runtime/integrations/automations/runtime-automation-patch-keys.ts +++ b/src/main/runtime/integrations/automations/runtime-automation-patch-keys.ts @@ -16,5 +16,7 @@ export const RUNTIME_AUTOMATION_PATCH_KEYS = [ 'rrule', 'dtstart', 'enabled', - 'missedRunGraceMinutes' + 'missedRunGraceMinutes', + // Set only in process (a plugin's ownership ending); RPC params never carry it. + 'createdBy' ] as const diff --git a/src/main/runtime/integrations/git/orca-runtime-git.ts b/src/main/runtime/integrations/git/orca-runtime-git.ts index 51576ad17d0..ca6cdcdc8eb 100644 --- a/src/main/runtime/integrations/git/orca-runtime-git.ts +++ b/src/main/runtime/integrations/git/orca-runtime-git.ts @@ -13,6 +13,7 @@ export class RuntimeGitCommands { readonly getRuntimeGitHistory: RuntimeGitStatusCommands['getRuntimeGitHistory'] readonly getRuntimeGitConflictOperation: RuntimeGitStatusCommands['getRuntimeGitConflictOperation'] readonly getRuntimeGitMutationInFlight: RuntimeGitStatusCommands['getRuntimeGitMutationInFlight'] + readonly readRuntimeWorktreeAtRiskLocalFiles: RuntimeGitStatusCommands['readRuntimeWorktreeAtRiskLocalFiles'] readonly switchRuntimeGitBranch: RuntimeGitStatusCommands['switchRuntimeGitBranch'] readonly checkoutRuntimeGitBranch: RuntimeGitStatusCommands['checkoutRuntimeGitBranch'] readonly listRuntimeGitLocalBranches: RuntimeGitStatusCommands['listRuntimeGitLocalBranches'] @@ -66,6 +67,8 @@ export class RuntimeGitCommands { this.getRuntimeGitHistory = status.getRuntimeGitHistory.bind(status) this.getRuntimeGitConflictOperation = status.getRuntimeGitConflictOperation.bind(status) this.getRuntimeGitMutationInFlight = status.getRuntimeGitMutationInFlight.bind(status) + this.readRuntimeWorktreeAtRiskLocalFiles = + status.readRuntimeWorktreeAtRiskLocalFiles.bind(status) this.switchRuntimeGitBranch = status.switchRuntimeGitBranch.bind(status) this.checkoutRuntimeGitBranch = status.checkoutRuntimeGitBranch.bind(status) this.listRuntimeGitLocalBranches = status.listRuntimeGitLocalBranches.bind(status) diff --git a/src/main/runtime/integrations/git/runtime-branch-switch-host.ts b/src/main/runtime/integrations/git/runtime-branch-switch-host.ts index 43c3c669597..f716ed82862 100644 --- a/src/main/runtime/integrations/git/runtime-branch-switch-host.ts +++ b/src/main/runtime/integrations/git/runtime-branch-switch-host.ts @@ -3,7 +3,7 @@ import type { Worktree } from '../../../../shared/worktree/types' import { CLEARED_HOSTED_REVIEW_LINK_UPDATES, HOSTED_REVIEW_LINK_KEYS -} from '../../../../shared/worktree/hosted-review-links' +} from '../../../../shared/worktree/hosted-review/hosted-review-links' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' import { isWslMoveWorktreeBlocked } from '../../../persistence/moving-wsl-projects/orchestration/wsl-move-background-backoff' diff --git a/src/main/runtime/integrations/git/runtime-git-command-surface.ts b/src/main/runtime/integrations/git/runtime-git-command-surface.ts index f0d8a68568b..0d88773cbd8 100644 --- a/src/main/runtime/integrations/git/runtime-git-command-surface.ts +++ b/src/main/runtime/integrations/git/runtime-git-command-surface.ts @@ -8,6 +8,7 @@ type RuntimeGitCommandName = | 'getRuntimeGitHistory' | 'getRuntimeGitConflictOperation' | 'getRuntimeGitMutationInFlight' + | 'readRuntimeWorktreeAtRiskLocalFiles' | 'abortRuntimeGitMerge' | 'abortRuntimeGitRebase' | 'switchRuntimeGitBranch' @@ -61,6 +62,8 @@ export function installRuntimeGitCommandSurface( getRuntimeGitHistory: commands.getRuntimeGitHistory.bind(commands), getRuntimeGitConflictOperation: commands.getRuntimeGitConflictOperation.bind(commands), getRuntimeGitMutationInFlight: commands.getRuntimeGitMutationInFlight.bind(commands), + readRuntimeWorktreeAtRiskLocalFiles: + commands.readRuntimeWorktreeAtRiskLocalFiles.bind(commands), abortRuntimeGitMerge: commands.abortRuntimeGitMerge.bind(commands), abortRuntimeGitRebase: commands.abortRuntimeGitRebase.bind(commands), switchRuntimeGitBranch: commands.switchRuntimeGitBranch.bind(commands), diff --git a/src/main/runtime/integrations/git/runtime-git-command-target.ts b/src/main/runtime/integrations/git/runtime-git-command-target.ts index 9a24d7052f8..fb0f30e8116 100644 --- a/src/main/runtime/integrations/git/runtime-git-command-target.ts +++ b/src/main/runtime/integrations/git/runtime-git-command-target.ts @@ -11,9 +11,9 @@ import { import type { createLocalGitProvider, LocalGitProvider -} from '../../../providers/local-git-provider' +} from '../../../providers/git/local-provider' import { SshHostNotServedError } from '../../../providers/ssh-host-not-served-error' -import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentEnvironmentResolvers } from '../../../text-generation/execution/commit-message-agent-environment' import type { PullRequestLinkedIssueMeta } from '../../../source-control/pull-request-linked-issue' import { normalizeRuntimeRelativePath } from '../../files/paths/runtime-relative-paths' diff --git a/src/main/runtime/integrations/git/runtime-git-diff-commands.ts b/src/main/runtime/integrations/git/runtime-git-diff-commands.ts index 4da4a859976..99fa251c69e 100644 --- a/src/main/runtime/integrations/git/runtime-git-diff-commands.ts +++ b/src/main/runtime/integrations/git/runtime-git-diff-commands.ts @@ -4,8 +4,8 @@ import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' import { assertGitDiffWithinTransportBudget } from '../../../../shared/git/diff/git-diff-transport-budget' -import { getBranchDiff } from '../../../git/source-control/branch-diff' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import { getBranchDiff } from '../../../git/source-control/comparisons/branch-diff' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { normalizeRuntimeRelativePath } from '../../files/paths/runtime-relative-paths' import { localGitOptionsForTarget, diff --git a/src/main/runtime/integrations/git/runtime-git-generation-admission.test.ts b/src/main/runtime/integrations/git/runtime-git-generation-admission.test.ts index 2b4b0e22138..1a459683ebb 100644 --- a/src/main/runtime/integrations/git/runtime-git-generation-admission.test.ts +++ b/src/main/runtime/integrations/git/runtime-git-generation-admission.test.ts @@ -16,14 +16,14 @@ const mocks = vi.hoisted(() => ({ const linkedLookup = vi.hoisted(() => ({ run: (): Promise => Promise.resolve(null) })) -vi.mock('../../../git/source-control/staged-commit-context', () => ({ +vi.mock('../../../git/source-control/mutations/staged-commit-context', () => ({ getStagedCommitContext: mocks.getStagedCommitContext })) vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: mocks.gitExecFileAsync })) -vi.mock('../../../text-generation/pull-request-context', () => ({ +vi.mock('../../../text-generation/pull-request-context/pull-request-context', () => ({ getPullRequestDraftContext: mocks.getPullRequestDraftContext })) vi.mock('../../../source-control/pull-request-linked-issue', () => ({ @@ -33,7 +33,7 @@ vi.mock('../../../source-control/pull-request-linked-issue', () => ({ return linkedLookup.run() } })) -vi.mock('../../../text-generation/commit-message-agent-environment', () => ({ +vi.mock('../../../text-generation/execution/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: mocks.prepareLocalCommitMessageAgentEnv })) vi.mock('../../../text-generation/commit-message-text-generation', () => ({ diff --git a/src/main/runtime/integrations/git/runtime-git-generation-commands.ts b/src/main/runtime/integrations/git/runtime-git-generation-commands.ts index bfc0007a147..f81be24f0c3 100644 --- a/src/main/runtime/integrations/git/runtime-git-generation-commands.ts +++ b/src/main/runtime/integrations/git/runtime-git-generation-commands.ts @@ -7,11 +7,11 @@ import { getCommitMessageModelDiscoveryHostKey } from '../../../../shared/source import type { HostedReviewProvider } from '../../../../shared/source-control/hosted-review/hosted-review-contracts' import { withLinkedIssueDraftContext } from '../../../../shared/source-control/ai/recipes/source-control-ai-action-variables' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { getStagedCommitContext } from '../../../git/source-control/staged-commit-context' +import { getStagedCommitContext } from '../../../git/source-control/mutations/staged-commit-context' import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../../providers/ssh-host-not-served-error' import { loadPullRequestLinkedIssue } from '../../../source-control/pull-request-linked-issue' import { resolveHostedReviewBodyForGeneration } from '../../../source-control/pull-request-template' -import { prepareLocalCommitMessageAgentEnv } from '../../../text-generation/commit-message-agent-environment' +import { prepareLocalCommitMessageAgentEnv } from '../../../text-generation/execution/commit-message-agent-environment' import { cancelGenerateCommitMessageLocal, cancelGeneratePullRequestFieldsLocal, @@ -25,7 +25,7 @@ import type { GenerateCommitMessageResult } from '../../../text-generation/source-control-text-generation-types' import type { GeneratePullRequestFieldsResult } from '../../../text-generation/commit-message-text-generation' -import { getPullRequestDraftContext } from '../../../text-generation/pull-request-context' +import { getPullRequestDraftContext } from '../../../text-generation/pull-request-context/pull-request-context' import { localGitOptionsForTarget, runtimeGitRouteForTarget, diff --git a/src/main/runtime/integrations/git/runtime-git-generation-context.ts b/src/main/runtime/integrations/git/runtime-git-generation-context.ts index defe825d5b8..f636028dea0 100644 --- a/src/main/runtime/integrations/git/runtime-git-generation-context.ts +++ b/src/main/runtime/integrations/git/runtime-git-generation-context.ts @@ -1,13 +1,13 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' -import type { getPullRequestDraftContext } from '../../../text-generation/pull-request-context' +import type { getPullRequestDraftContext } from '../../../text-generation/pull-request-context/pull-request-context' import { mergeLegacyCommitMessageAiIntoSourceControlAi } from '../../../../shared/source-control/ai/settings/source-control-ai-legacy-reconciliation' import type { SourceControlAiSettingsInput, ResolvedSourceControlAiGenerationParams } from '../../../../shared/source-control/ai/source-control-ai-operation-resolution' import type { SourceControlAiOperation } from '../../../../shared/source-control/ai/settings/source-control-ai-settings-types' -import type { CommitMessageAgentRuntimeTarget } from '../../../text-generation/commit-message-agent-environment' +import type { CommitMessageAgentRuntimeTarget } from '../../../text-generation/execution/commit-message-agent-environment' import type { CommitMessageGenerationTarget } from '../../../text-generation/source-control-text-generation-types' import type { PullRequestLinkedIssueMeta } from '../../../source-control/pull-request-linked-issue' import { diff --git a/src/main/runtime/integrations/git/runtime-git-status-commands.ts b/src/main/runtime/integrations/git/runtime-git-status-commands.ts index cac22baf689..788d4861f97 100644 --- a/src/main/runtime/integrations/git/runtime-git-status-commands.ts +++ b/src/main/runtime/integrations/git/runtime-git-status-commands.ts @@ -19,7 +19,7 @@ import type { RuntimeGitCheckoutResult, RuntimeGitLocalBranches } from '../../../../shared/runtime-worktree-contracts' -import type { GitProviderStatusOptions } from '../../../providers/git-provider-status-options' +import type { GitProviderStatusOptions } from '../../../providers/git/status-options' import { localGitOptionsForTarget, requireLocalRuntimeGitRoute, @@ -28,6 +28,8 @@ import { type RuntimeGitTarget } from './runtime-git-command-target' import { assertRuntimeReadWslDistroRunning } from './runtime-wsl-background-read-gate' +import type { WorktreeAtRiskLocalFiles } from '../../../../shared/worktree/removal/at-risk-local-files' +import { readWorktreeAtRiskLocalFiles } from '../../../git/worktrees/removal/worktree-at-risk-local-files' // Followers nobody is looking at: a stopped distro must stay stopped for them (E9). async function resolveGatedGitTarget( @@ -104,6 +106,19 @@ export class RuntimeGitStatusCommands { } } + async readRuntimeWorktreeAtRiskLocalFiles( + worktreeSelector: string, + signal?: AbortSignal + ): Promise { + const target = await resolveGatedGitTarget(this.host, worktreeSelector) + requireLocalRuntimeGitRoute(target) + return readWorktreeAtRiskLocalFiles({ + worktreePath: target.worktree.path, + mainCheckoutPath: target.repo?.path ?? null, + gitOptions: { ...localGitOptionsForTarget(target), ...(signal ? { signal } : {}) } + }) + } + async checkoutRuntimeGitBranch( worktreeSelector: string, branch: string, diff --git a/src/main/runtime/integrations/git/runtime-git-sync-commands.ts b/src/main/runtime/integrations/git/runtime-git-sync-commands.ts index da0a56e0798..a2c4b7aae9b 100644 --- a/src/main/runtime/integrations/git/runtime-git-sync-commands.ts +++ b/src/main/runtime/integrations/git/runtime-git-sync-commands.ts @@ -7,7 +7,7 @@ import type { GitUpstreamStatus } from '../../../../shared/git/status/git-status import type { GitPushTarget } from '../../../../shared/worktree/types' import { materializeWorktreePushTargetRemote } from '../../../ipc/worktree-remote' import { assertRuntimeReadWslDistroRunning } from './runtime-wsl-background-read-gate' -import type { LocalGitProvider } from '../../../providers/local-git-provider' +import type { LocalGitProvider } from '../../../providers/git/local-provider' import { localGitOptionsForTarget, requireRuntimeGitProvider, diff --git a/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts b/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts index 75fd1e209a5..2a5908f3259 100644 --- a/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts +++ b/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts @@ -1,27 +1,27 @@ -import '../../../github/rate-limit' +import '../../../github/api/rate-limit' import type { GitHubCreateIssueFields, GitHubIssueUpdate } from '../../../../shared/issue-mutation-types' -import type { GitHubOwnerRepo } from '../../../../shared/github/pull-request-types' -import type { GitHubPRReviewCommentInput } from '../../../../shared/github/comment-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubPRReviewCommentInput } from '../../../../shared/github/comments/comment-types' import type { Repo } from '../../../../shared/repo-types' import type { LocalProjectGhExecOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -import { addIssueComment } from '../../../github/issue-comment' +import { addIssueComment } from '../../../github/issues/issue-comment' import { addPRReviewComment, addPRReviewCommentReply } from '../../../github/client/create/add-pr-review-comment' -import { createIssue } from '../../../github/issue-create' -import { updateIssue } from '../../../github/issue-update' +import { createIssue } from '../../../github/issues/issue-create' +import { updateIssue } from '../../../github/issues/issue-update' import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' -import type { GitHubAttachmentTarget } from '../../../../shared/rpc-contract/github-attachment-params' -import { uploadGitHubImage } from '../../../github/image-attachment-upload' +import type { GitHubAttachmentTarget } from '../../../../shared/rpc-contract/github/github-attachment-params' +import { uploadGitHubImage } from '../../../github/attachments/image-attachment-upload' import { resolveGitHubRepoExecution, resolveIssueGitHubApiRepositorySource -} from '../../../github/github-api-repository' -import { projectGhExecOptions } from '../../../github/project-view/internals' +} from '../../../github/repositories/github-api-repository' +import { projectGhExecOptions } from '../../../github/project-view/project-host-execution' import { runAsDefaultWslCliUserAct } from '../../../git/command-runner/hosted-cli/default-wsl-cli-fallback' type LocalGitArgs = [] | [LocalProjectGhExecOptions] diff --git a/src/main/runtime/integrations/github/runtime-github-project-commands.ts b/src/main/runtime/integrations/github/runtime-github-project-commands.ts index 6ca90af4da3..60b9d7872e9 100644 --- a/src/main/runtime/integrations/github/runtime-github-project-commands.ts +++ b/src/main/runtime/integrations/github/runtime-github-project-commands.ts @@ -37,7 +37,7 @@ import type { UpdateIssueTypeBySlugArgs, UpdateProjectItemFieldArgs, UpdatePullRequestBySlugArgs -} from '../../../../shared/github/project-request-types' +} from '../../../../shared/github/projects/project-request-types' export class RuntimeGitHubProjectCommands { listGitHubProjects(args?: ListAccessibleProjectsArgs) { diff --git a/src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts b/src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts index 9f940082a59..8381eff8594 100644 --- a/src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts +++ b/src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts @@ -1,21 +1,21 @@ -import type { GhAccountBinding } from '../../../../shared/github/account-binding' -import type { GitHubOwnerRepo } from '../../../../shared/github/pull-request-types' -import type { ListWorkItemsResult } from '../../../../shared/github/work-item-types' +import type { GhAccountBinding } from '../../../../shared/github/accounts/account-binding' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { ListWorkItemsResult } from '../../../../shared/github/work-items/work-item-types' import type { Repo } from '../../../../shared/repo-types' import type { LocalProjectGhExecOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { countWorkItems } from '../../../github/client/list/count-work-items' import { getWorkItem, getWorkItemByOwnerRepo } from '../../../github/client/fetch/get-work-item' -import { listAssignableUsers, listLabels } from '../../../github/issue-field-options' -import { listIssues } from '../../../github/issues' +import { listAssignableUsers, listLabels } from '../../../github/issues/issue-field-options' +import { listIssues } from '../../../github/issues/issues' import { listWorkItems } from '../../../github/client/list/list-work-items' import type { MainWorkItem } from '../../../github/client/map/work-item-field-coercion' import { listGhAccountBindingInventory, validateGhAccountBinding -} from '../../../github/gh-account-binding-inventory' -import { getRateLimit } from '../../../github/rate-limit' -import { resolveGhAccountRequiredHost } from '../../../github/account-binding-required-host' -import { getWorkItemDetails } from '../../../github/work-item-details' +} from '../../../github/accounts/gh-account-binding-inventory' +import { getRateLimit } from '../../../github/api/rate-limit' +import { resolveGhAccountRequiredHost } from '../../../github/accounts/account-binding-required-host' +import { getWorkItemDetails } from '../../../github/work-items/work-item-details' import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' type LocalGitArgs = [] | [LocalProjectGhExecOptions] diff --git a/src/main/runtime/integrations/github/runtime-github-review-mutation-commands.ts b/src/main/runtime/integrations/github/runtime-github-review-mutation-commands.ts index 74678a15ac0..6949c22e576 100644 --- a/src/main/runtime/integrations/github/runtime-github-review-mutation-commands.ts +++ b/src/main/runtime/integrations/github/runtime-github-review-mutation-commands.ts @@ -1,7 +1,7 @@ -import type { GhAccountBinding } from '../../../../shared/github/account-binding' -import type { GitHubOwnerRepo } from '../../../../shared/github/pull-request-types' +import type { GhAccountBinding } from '../../../../shared/github/accounts/account-binding' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' import type { GitHubPullRequestStateUpdate } from '../../../../shared/issue-mutation-types' -import type { GitHubReactionContent } from '../../../../shared/github/comment-types' +import type { GitHubReactionContent } from '../../../../shared/github/comments/comment-types' import type { Repo } from '../../../../shared/repo-types' import type { LocalProjectGhExecOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { mergePR } from '../../../github/client/merge/merge-pr' diff --git a/src/main/runtime/integrations/github/runtime-github-review-query-commands.ts b/src/main/runtime/integrations/github/runtime-github-review-query-commands.ts index 36504aa8e11..48e4118088f 100644 --- a/src/main/runtime/integrations/github/runtime-github-review-query-commands.ts +++ b/src/main/runtime/integrations/github/runtime-github-review-query-commands.ts @@ -1,11 +1,12 @@ -import type { GitHubOwnerRepo, GitHubPRFile } from '../../../../shared/github/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubPRFile } from '../../../../shared/github/pull-requests/pull-request-types' import type { Repo } from '../../../../shared/repo-types' import type { LocalProjectGhExecOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -import { getIssue } from '../../../github/issues' +import { getIssue } from '../../../github/issues/issues' import { getPRCheckDetails } from '../../../github/client/check/get-pr-check-details' import { getPRChecks } from '../../../github/client/check/get-pr-checks' import { getPRComments } from '../../../github/client/fetch/get-pr-comments' -import { getPRFileContents } from '../../../github/work-item-details' +import { getPRFileContents } from '../../../github/pull-requests/files/pull-request-file-contents' import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' type LocalGitArgs = [] | [LocalProjectGhExecOptions] diff --git a/src/main/runtime/integrations/github/runtime-github-worktree-base.ts b/src/main/runtime/integrations/github/runtime-github-worktree-base.ts index 4e41d8f86b2..2ed65b7763c 100644 --- a/src/main/runtime/integrations/github/runtime-github-worktree-base.ts +++ b/src/main/runtime/integrations/github/runtime-github-worktree-base.ts @@ -3,10 +3,10 @@ import type { Repo } from '../../../../shared/repo-types' import { fetchPrHeadTrackingRef, fetchGitHubPullRequestHeadRef -} from '../../../github/pr-head-tracking-ref' -import { resolveGitHubPrStartPoint } from '../../../github/pr-start-point' -import { resolvePrStartPointUnlessWslStopped } from '../../../github/pr-start-point-wsl-gate' -import { resolveGitHubReviewHeadRemote } from '../../../github/review-head-remote' +} from '../../../github/pull-requests/start-points/pr-head-tracking-ref' +import { resolveGitHubPrStartPoint } from '../../../github/pull-requests/start-points/pr-start-point' +import { resolvePrStartPointUnlessWslStopped } from '../../../github/pull-requests/start-points/pr-start-point-wsl-gate' +import { resolveGitHubReviewHeadRemote } from '../../../github/pull-requests/start-points/review-head-remote' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { getLocalProjectGitExecOptions, diff --git a/src/main/runtime/integrations/gitlab/runtime-gitlab-worktree-base.ts b/src/main/runtime/integrations/gitlab/runtime-gitlab-worktree-base.ts index b996fd2513e..2ac4f5b6d59 100644 --- a/src/main/runtime/integrations/gitlab/runtime-gitlab-worktree-base.ts +++ b/src/main/runtime/integrations/gitlab/runtime-gitlab-worktree-base.ts @@ -16,7 +16,7 @@ import type { ProjectRuntimeResolutionStore } from '../../../workspaces/executio import { resolveRuntimeGitLabForkMrBase } from './runtime-gitlab-fork-mr-base' import { resolveRuntimeGitLabIssueSourceRemote } from './runtime-gitlab-issue-source-remote' import { reviewStartPointFailure } from '../../../../shared/review-start-point-failure-copy' -import { resolvePrStartPointUnlessWslStopped } from '../../../github/pr-start-point-wsl-gate' +import { resolvePrStartPointUnlessWslStopped } from '../../../github/pull-requests/start-points/pr-start-point-wsl-gate' export type RuntimeGitLabWorktreeBaseArgs = { repoSelector: string diff --git a/src/main/runtime/integrations/jira/runtime-jira-commands.ts b/src/main/runtime/integrations/jira/runtime-jira-commands.ts index e1faae96bab..ee4e7d126c4 100644 --- a/src/main/runtime/integrations/jira/runtime-jira-commands.ts +++ b/src/main/runtime/integrations/jira/runtime-jira-commands.ts @@ -6,7 +6,7 @@ import { generateJiraIssueSummaryRequest, cancelJiraIssueSummaryRequest, type JiraIssueSummaryGenerationHost -} from '../../../text-generation/jira-issue-summary-requests' +} from '../../../text-generation/requests/jira-issue-summary-requests' import type { JiraConnectArgs, JiraCreateIssueArgs, diff --git a/src/main/runtime/integrations/linear/runtime-linear-write-lifetime.test.ts b/src/main/runtime/integrations/linear/runtime-linear-write-lifetime.test.ts index 70ca0106911..9236528bff7 100644 --- a/src/main/runtime/integrations/linear/runtime-linear-write-lifetime.test.ts +++ b/src/main/runtime/integrations/linear/runtime-linear-write-lifetime.test.ts @@ -1,3 +1,4 @@ +import type { RuntimeLinearCommandPorts } from './runtime-linear-command-base' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import * as mutations from '../../../linear/issues/linear-issue-mutations' import * as comments from '../../../linear/issues/linear-issue-comments' @@ -26,7 +27,10 @@ const issue = { const target = { issue, workspaceId: 'w1' } const team = { ...issue.team, workspaceId: 'w1' } -function commands(listResolvedWorktrees: () => Promise<[]> = async () => []) { +function commands( + listResolvedWorktrees: RuntimeLinearCommandPorts['listResolvedWorktrees'] = async () => [], + emitClientEvent: RuntimeLinearCommandPorts['emitClientEvent'] = () => {} +) { const unusedSelector = async () => { throw new Error('unused') } @@ -39,7 +43,7 @@ function commands(listResolvedWorktrees: () => Promise<[]> = async () => []) { resolveWorkspaceSelector: unusedSelector, listResolvedWorktrees, setWorktreeMeta: () => {}, - emitClientEvent: () => {} + emitClientEvent } const result = new RuntimeLinearReadCommands(ports) vi.spyOn(result, 'resolveLinearAgentWriteTarget').mockResolvedValue(target) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts index 47bfa21315c..6a14b007a13 100644 --- a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts @@ -1,29 +1,30 @@ -import type { - CreateHostedReviewInput, - CreateHostedReviewResult, - CreateStackedHostedReviewInput, - CreateStackedHostedReviewResult, - HostedReviewCreationEligibility, - HostedReviewCreationEligibilityArgs, - HostedReviewForBranchReply -} from '../../../../shared/source-control/hosted-review/hosted-review-contracts' -import type { GitHubOwnerRepo } from '../../../../shared/github/pull-request-types' -import type { - GitHubPRRefreshReason, - PRRefreshOutcome -} from '../../../../shared/github/pull-request-refresh-types' -import type { Repo } from '../../../../shared/repo-types' -import type { DeviceScope } from '../../../../shared/runtime-session-contracts' import { getPRForBranchOutcome, readRecentPhonePROutcome } from '../../../github/client/lookup/pr-for-branch-outcome' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { + GitHubPRRefreshReason, + PRRefreshOutcome +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { Repo } from '../../../../shared/repo-types' +import type { DeviceScope } from '../../../../shared/runtime-session-contracts' import { getRepoSlug, getRepoUpstream } from '../../../github/client/fetch/repo-slug-upstream' +import { admissionTierForRefreshReason } from '../../../github/pull-requests/refresh/pr-refresh-candidate-policy' import type { GitHubPRBranchLookupOptions } from '../../../github/client/lookup/pull-request-lookup-data' -import { admissionTierForRefreshReason } from '../../../github/pr-refresh-candidate-policy' -import { runHostedPRRead } from '../../../github/pr-refresh-coordinator' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' -import { hostedReviewForBranchReply } from '../../../../shared/source-control/hosted-review/hosted-review-contracts' +import { runHostedPRRead } from '../../../github/pull-requests/refresh/pr-refresh-coordinator' +import { + type CreateHostedReviewInput, + type CreateHostedReviewResult, + type CreateStackedHostedReviewInput, + type CreateStackedHostedReviewResult, + type HostedReviewCreationEligibility, + type HostedReviewCreationEligibilityArgs, + type HostedReviewForBranchReply, + hostedReviewForBranchReply +} from '../../../../shared/source-control/hosted-review/hosted-review-contracts' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' + import { readHostedReviewForBranch } from '../../../source-control/hosted-review' import { getStoredRepoExecutionHostId } from '../../../workspaces/execution-host/repo-execution-host' import { hostedReviewSshConnectionId } from '../../../source-control/hosted-review-execution-host' diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts index 00ec6e32707..caa4161c0a1 100644 --- a/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts @@ -1,20 +1,25 @@ +import type * as GithubRepositoryIdentityModule from '../../../github/repositories/github-repository-identity' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { GitHubPRRefreshReason, PRRefreshOutcome -} from '../../../../shared/github/pull-request-refresh-types' +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { GitHubRepoContext, LocalGitExecOptions -} from '../../../github/github-repository-identity' +} from '../../../github/repositories/github-repository-identity' import type { Repo } from '../../../../shared/repo-types' import type { DeviceScope } from '../../../../shared/runtime-session-contracts' -import { makePR } from '../../../github/pr-refresh-coordinator-test-harness' +import { makePR } from '../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness' const mocks = vi.hoisted(() => ({ resolve: vi.fn() })) -vi.mock('../../../github/gh-utils', () => ({ +vi.mock('../../../github/execution/github-operation-slots', () => ({ acquire: vi.fn(async () => {}), - release: vi.fn(), + release: vi.fn() +})) + +vi.mock('../../../github/repositories/github-repository-identity', async (importOriginal) => ({ + ...(await importOriginal()), githubRepoContext: ( repoPath: string, connectionId: string | null, @@ -25,7 +30,7 @@ vi.mock('../../../github/gh-utils', () => ({ vi.mock('../../../github/client/lookup/branch-lookup-resolution', () => ({ resolvePRForBranchOutcome: mocks.resolve })) -vi.mock('../../../github/pr-refresh-coordinator', () => ({ +vi.mock('../../../github/pull-requests/refresh/pr-refresh-coordinator', () => ({ runHostedPRRead: (_candidate: unknown, read: () => Promise) => read() })) import { RuntimeHostedReviewCommands } from './runtime-hosted-review-commands' diff --git a/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts b/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts index af262a95740..03f5974bbd6 100644 --- a/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts +++ b/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts @@ -67,10 +67,14 @@ export async function executeLocalBundledSkills( export async function autoUpdateLocalBundledSkills( host: RuntimeSkillCommandHost, - { names }: BundledSkillAutoUpdateRequest + { names, recordOnly }: BundledSkillAutoUpdateRequest ): Promise { const input = await appInput(host, {}) - const result = await autoUpdateInstalledBundledSkills({ ...input, names }) + const result = await autoUpdateInstalledBundledSkills({ + ...input, + names, + ...(recordOnly ? { recordOnly } : {}) + }) clearSkillDiscoveryCaches() return result } diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-context.ts similarity index 76% rename from src/main/runtime/mobile-cloud-relay/relay-auth-context.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-context.ts index 6f4b751dec0..ca0a2c01bdf 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-context.ts @@ -1,6 +1,6 @@ -import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' -import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store' -import { readFreshOrcaCloudSession } from '../../orca-profiles/cloud-session/profile-cloud-session-refresh' +import type { OrcaCloudAuthConfig } from '../../../orca-profiles/cloud-auth/profile-cloud-auth-config' +import { ensureActiveOrcaProfile } from '../../../orca-profiles/profile-index-store' +import { readFreshOrcaCloudSession } from '../../../orca-profiles/cloud-session/profile-cloud-session-refresh' import type { RelayAuthContext } from './relay-auth-identity' export async function readRelayAuthContext( diff --git a/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts new file mode 100644 index 00000000000..d0e235f41bc --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import '../desktop-relay-service' +import { RelayAuthCoordinator } from './relay-auth-coordinator' +import type { RelayAuthContext } from './relay-auth-identity' +import { RelayHttpError } from '../director/relay-http-client' + +import '../session-lifecycle/relay-session-broker' + +const context: RelayAuthContext = { + identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, + accessToken: 'access-1', + relayEntitled: true +} + +describe('relay readiness', () => { + afterEach(() => vi.useRealTimers()) + + it('stops waiting when a fence cancels the scheduled retry', async () => { + vi.useFakeTimers() + const coordinator = new RelayAuthCoordinator({ + readContext: async () => context, + openBroker: async () => { + throw new RelayHttpError('token-exchange', 502) + }, + onStatus: () => {}, + random: () => 1 + }) + coordinator.reconcile() + const waiting = coordinator.waitForReadiness(20_000) + await vi.advanceTimersByTimeAsync(0) + coordinator.fenceAndCloseNow() + await expect(waiting).resolves.toEqual({ + ready: false, + reason: 'control_not_active', + retryAt: null + }) + }) + + function coldStartWithHungRetry(): RelayAuthCoordinator { + const openBroker = vi + .fn() + .mockRejectedValueOnce(new RelayHttpError('assignment', 503)) + .mockImplementationOnce(() => new Promise(() => {})) + return new RelayAuthCoordinator({ + readContext: async () => context, + openBroker, + onStatus: () => {}, + random: () => 0.5 + }) + } + + it('returns at its deadline while the retry it followed is still opening', async () => { + vi.useFakeTimers() + const coordinator = coldStartWithHungRetry() + coordinator.reconcile() + let settled: unknown = null + void coordinator.waitForReadiness(10_000).then((readiness) => (settled = readiness)) + await vi.advanceTimersByTimeAsync(9_999) + expect(settled).toBeNull() + await vi.advanceTimersByTimeAsync(1) + expect(settled).toMatchObject({ ready: false, reason: 'director_assignment_503' }) + coordinator.stop() + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts similarity index 94% rename from src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts index ef73086b5af..cbc73d071d9 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { RelayAuthCoordinator } from './relay-auth-coordinator' import type { RelayAuthContext } from './relay-auth-identity' -import type { RelayAccessTokenRefresh } from './relay-session-broker-contract' +import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract' function deferred() { let resolve!: (value: T) => void diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.ts similarity index 96% rename from src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.ts index ad2554d1185..4a2b5b101a2 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.ts @@ -1,12 +1,12 @@ import { RELAY_HOST_CLOSE_REASON, type RelayHostCloseReason -} from '../../../shared/relay-host-close-reason' -import { relayStatusCellUrl } from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type * as RelayStatus from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { RelayAccessTokenRefresh } from './relay-session-broker-contract' +} from '../../../../shared/relay-host-close-reason' +import { relayStatusCellUrl } from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type * as RelayStatus from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract' -import { shouldRetryRelayConnectionError } from './relay-http-client' +import { shouldRetryRelayConnectionError } from '../director/relay-http-client' import { RelayReadinessWaiters, relayRetryFloorMs, diff --git a/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-identity.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-identity.ts new file mode 100644 index 00000000000..fee2cb49707 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-identity.ts @@ -0,0 +1,11 @@ +import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract' + +export type RelayAuthContext = { + identity: RelayIdentity + accessToken: string + relayEntitled: boolean +} + +export function relayIdentityKey(identity: RelayIdentity): string { + return `${identity.userId}\0${identity.profileId}\0${identity.organizationId}` +} diff --git a/src/main/runtime/mobile-cloud-relay/relay-linger-timer.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-linger-timer.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-linger-timer.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-linger-timer.ts diff --git a/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts new file mode 100644 index 00000000000..7a311015e68 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts @@ -0,0 +1,24 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' +import { RelayReadinessWaiters } from './relay-readiness' + +afterEach(() => vi.useRealTimers()) + +describe('relay readiness wait lifetime', () => { + it('releases callers without cancelling shared work and permits a later wait', async () => { + vi.useFakeTimers() + let finish = (): void => {} + const work = new Promise((resolve) => { + finish = resolve + }) + const waiters = new RelayReadinessWaiters() + const first = waiters.until(work, Date.now() + 10_000) + waiters.releaseAll() + await expect(first).resolves.toBe(false) + expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0) + const next = waiters.until(work, Date.now() + 10_000) + finish() + await expect(next).resolves.toBe(true) + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-readiness.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-readiness.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-readiness.ts index f8949fc7eb7..2b943e73014 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-readiness.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness.ts @@ -1,6 +1,6 @@ -import { RelayHttpError } from './relay-http-client' -import { RelayHostProofClockSkewError } from './relay-host-proof' -import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' +import { RelayHttpError } from '../director/relay-http-client' +import { RelayHostProofClockSkewError } from '../control-channel/relay-host-proof' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' // Lowercase reason tokens must form valid relay_ mint-failure codes. export type RelayUnavailableReason = diff --git a/src/main/runtime/mobile-cloud-relay/relay-retry-schedule.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-retry-schedule.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-retry-schedule.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-retry-schedule.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client-options.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client-options.ts similarity index 91% rename from src/main/runtime/mobile-cloud-relay/relay-control-client-options.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client-options.ts index 5a67bdeb8c9..7902b07c633 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client-options.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client-options.ts @@ -1,5 +1,5 @@ import type WebSocket from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' import type { RelayConnectionOpenMessage, RelayDrainMessage } from './relay-control-protocol' export type RelayControlClientOptions = { diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts similarity index 99% rename from src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts index a43d8abd3d7..b9acf8e13c6 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts @@ -4,7 +4,7 @@ import type { Server, Socket } from 'node:net' import { afterEach, describe, expect, it, vi } from 'vitest' import nacl from 'tweetnacl' import { WebSocketServer, type WebSocket } from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' import { RelayControlClient } from './relay-control-client' diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-control-client.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.ts index e5227a79034..7dc56857d58 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.ts @@ -1,8 +1,8 @@ import type { RelayControlClientOptions } from './relay-control-client-options' import { randomUUID } from 'node:crypto' import WebSocket, { type RawData } from 'ws' -import { MOBILE_RELAY_CLOSE_CODE } from '../../../shared/remote-runtime/relay/mobile-relay-close-codes' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' +import { MOBILE_RELAY_CLOSE_CODE } from '../../../../shared/remote-runtime/relay/mobile-relay-close-codes' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' import { RelayConnectionOpenMessageSchema, RelayControlErrorMessageSchema, diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts index 1d85b1431a0..fab2ddd9cf7 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts @@ -1,5 +1,5 @@ import type { RelayControlRequestTimeout } from './relay-control-requests' -import { RELAY_RENEWAL_JITTER_RATIO } from './relay-renewal-jitter' +import { RELAY_RENEWAL_JITTER_RATIO } from '../session-lifecycle/relay-renewal-jitter' import { RELAY_CLIENT_KEEPALIVE_FRAME, RelayKeepaliveAckMessageSchema, diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol.ts index a0fca00db85..619ceaebecf 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol.ts @@ -3,7 +3,7 @@ import type { RawData } from 'ws' import { DeviceCredentialInstalledSchema, DeviceResumeConfirmedSchema -} from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract' +} from '../../../../shared/remote-runtime/relay/mobile-relay-credential-contract' const OpaqueIdSchema = z.string().min(1).max(128) const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-requests.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-requests.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-control-requests.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-requests.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-socket-close.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-socket-close.ts similarity index 88% rename from src/main/runtime/mobile-cloud-relay/relay-control-socket-close.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-socket-close.ts index f215c9c40cc..9a46710e060 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-socket-close.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-socket-close.ts @@ -1,5 +1,5 @@ import type WebSocket from 'ws' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' const NORMAL_CLOSE_CODE = 1000 const REASONED_CLOSE_FLUSH_MS = 1_000 diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-url.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-url.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-control-url.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-url.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts similarity index 88% rename from src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts index 9e491599db5..0b2f06a5564 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts @@ -1,4 +1,4 @@ -import { createHmac, randomBytes } from 'node:crypto' +import { randomBytes } from 'node:crypto' import { describe, expect, it } from 'vitest' import nacl from 'tweetnacl' import { @@ -84,7 +84,6 @@ function buildChallengeFixture(options: { }): { challenge: RelayHostChallenge context: RelayHostProofContext - expectedProof: string } { const hostKeys = nacl.box.keyPair() const relayKeys = nacl.box.keyPair() @@ -130,27 +129,11 @@ function buildChallengeFixture(options: { resumeRequested: false, now: () => options.localNow } - const expectedProof = createHmac('sha256', secret) - .update(text(`${HOST_PROOF_DOMAIN}\0ack\0`)) - .update(transcript) - .digest('base64') - return { challenge, context, expectedProof } + + return { challenge, context } } describe('answerRelayHostChallenge clock skew (#10401)', () => { - it('accepts challenges at the clock-skew boundaries', () => { - const issuedAt = 1_700_000_000_000 - const expiresAt = issuedAt + 10_000 - for (const localNow of [issuedAt - CLOCK_SKEW_MS, expiresAt + CLOCK_SKEW_MS]) { - const { challenge, context, expectedProof } = buildChallengeFixture({ - issuedAt, - expiresAt, - localNow - }) - expect(answerRelayHostChallenge(challenge, context)).toBe(expectedProof) - } - }) - it('still rejects challenges outside the allowed skew window', () => { const serverNow = 1_700_000_000_000 const issuedAt = serverNow diff --git a/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-host-proof.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.ts index 69e536eed38..c2700838753 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.ts @@ -6,7 +6,7 @@ import { openHostChallengeEnvelope, parseHostChallengeTranscript, readTranscriptUint64 -} from '../hosts/identity/host-challenge-envelope' +} from '../../hosts/identity/host-challenge-envelope' const HOST_PROOF_TRANSCRIPT_DOMAIN = 'orca-relay-host-proof/v1' const HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-relay-host-challenge/v1' diff --git a/src/main/runtime/mobile-cloud-relay/relay-demand-ledger.ts b/src/main/runtime/mobile-cloud-relay/demand/relay-demand-ledger.ts similarity index 93% rename from src/main/runtime/mobile-cloud-relay/relay-demand-ledger.ts rename to src/main/runtime/mobile-cloud-relay/demand/relay-demand-ledger.ts index 965d81fc203..1d12fe2e45f 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-demand-ledger.ts +++ b/src/main/runtime/mobile-cloud-relay/demand/relay-demand-ledger.ts @@ -1,5 +1,5 @@ -import type { DeviceRegistry } from '../rpc/server/pairing/device-registry' -import type { RelayRevokeOutbox } from './relay-revoke-outbox' +import type { DeviceRegistry } from '../../rpc/server/pairing/device-registry' +import type { RelayRevokeOutbox } from '../pairing/relay-revoke-outbox' type RelayDemandLedgerOptions = { deviceRegistry: DeviceRegistry diff --git a/src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts b/src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts deleted file mode 100644 index e25df17f42e..00000000000 --- a/src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { DesktopRelayService } from './desktop-relay-service' -import { createDesktopRelayServiceInstaller } from './desktop-relay-service-installer' - -function fakeService(): DesktopRelayService { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installer only calls start() and wraps the provider methods. - return { start: vi.fn() } as unknown as DesktopRelayService -} - -function installerWith(overrides: { - create: () => DesktopRelayService | null - isFenced?: () => boolean - whenNetworkReady?: Promise -}) { - const runtimeRpc = { setMobileRelayPairingProvider: vi.fn() } - const onInstalled = vi.fn() - const installer = createDesktopRelayServiceInstaller({ - runtimeRpc, - whenNetworkReady: overrides.whenNetworkReady ?? Promise.resolve(), - isFenced: overrides.isFenced ?? (() => false), - create: overrides.create, - onInstalled - }) - return { installer, runtimeRpc, onInstalled } -} - -describe('createDesktopRelayServiceInstaller', () => { - it('holds the first install until the network is ready and shares one in-flight install', async () => { - let ready!: () => void - const whenNetworkReady = new Promise((resolve) => (ready = resolve)) - const create = vi.fn(() => fakeService()) - const { installer } = installerWith({ create, whenNetworkReady }) - - const first = installer.ensure() - const second = installer.ensure() - await Promise.resolve() - expect(create).not.toHaveBeenCalled() - ready() - await expect(Promise.all([first, second])).resolves.toEqual([true, true]) - expect(create).toHaveBeenCalledOnce() - }) - - it('refuses installs after sign-out, including one already waiting, until the next auth change', async () => { - let ready!: () => void - const whenNetworkReady = new Promise((resolve) => (ready = resolve)) - const create = vi.fn(() => fakeService()) - const { installer } = installerWith({ create, whenNetworkReady }) - - const waiting = installer.ensure() - installer.suspend() - ready() - await expect(waiting).resolves.toBe(false) - await expect(installer.ensure()).resolves.toBe(false) - expect(create).not.toHaveBeenCalled() - await expect(installer.authChanged()).resolves.toBe(true) - expect(create).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts index 20f26c42aa0..482676a9e06 100644 --- a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts +++ b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts @@ -8,22 +8,22 @@ import type { PairingProvisionRelayParams } from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract' import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import { readRelayAuthContext } from './relay-auth-context' -import { relayIdentityKey } from './relay-auth-identity' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import { RelayUnavailableError } from './relay-readiness' -import { RelaySessionBroker } from './relay-session-broker' +import { readRelayAuthContext } from './authentication/relay-auth-context' +import { relayIdentityKey } from './authentication/relay-auth-identity' +import { RelayAuthCoordinator } from './authentication/relay-auth-coordinator' +import { RelayUnavailableError } from './authentication/relay-readiness' +import { RelaySessionBroker } from './session-lifecycle/relay-session-broker' import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status' import type { PairingRelay } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' import type { RelayRevokeOutbox, RelayDeviceBinding, RelayRevokeOutboxItem -} from './relay-revoke-outbox' -import { pairingAuthorizationForContext } from './relay-pairing-authorization' -import { deriveRelayHostId } from './relay-http-client' -import { RelayDemandLedger } from './relay-demand-ledger' -import { createRelayRegionPreferenceReader } from './relay-region-preference-reader' +} from './pairing/relay-revoke-outbox' +import { pairingAuthorizationForContext } from './pairing/relay-pairing-authorization' +import { deriveRelayHostId } from './director/relay-http-client' +import { RelayDemandLedger } from './demand/relay-demand-ledger' +import { createRelayRegionPreferenceReader } from './region-selection/relay-region-preference-reader' type DesktopRelayServiceOptions = { authConfig: OrcaCloudAuthConfig diff --git a/src/main/runtime/mobile-cloud-relay/relay-assign-rate-gate.ts b/src/main/runtime/mobile-cloud-relay/director/relay-assign-rate-gate.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-assign-rate-gate.ts rename to src/main/runtime/mobile-cloud-relay/director/relay-assign-rate-gate.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts b/src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts rename to src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-http-client.ts b/src/main/runtime/mobile-cloud-relay/director/relay-http-client.ts similarity index 94% rename from src/main/runtime/mobile-cloud-relay/relay-http-client.ts rename to src/main/runtime/mobile-cloud-relay/director/relay-http-client.ts index c3cd5b23094..d601bb8e23d 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-http-client.ts +++ b/src/main/runtime/mobile-cloud-relay/director/relay-http-client.ts @@ -1,8 +1,8 @@ import { createHash } from 'node:crypto' import { z } from 'zod' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' -import { parseRetryAfterHeaderMs } from '../../../shared/retry-after-header' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' +import { parseRetryAfterHeaderMs } from '../../../../shared/retry-after-header' import { RelayAssignAbortedError, RelayAssignRateLimitedError, @@ -10,11 +10,11 @@ import { sharedRelayAssignRateGate, type RelayAssignRateGate } from './relay-assign-rate-gate' -import type { RelayRegion } from './relay-region-probe' +import type { RelayRegion } from '../region-selection/relay-region-probe' import { RelayRegionCorrectionResponseSchema, type RelayRegionCorrectionRequest -} from './relay-region-correction-protocol' +} from '../region-selection/relay-region-correction-protocol' const RELAY_HTTP_REQUEST_DEADLINE_MS = 15_000 const RELAY_RETRY_AFTER_MAX_MS = 5 * 60_000 diff --git a/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin-options.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin-options.ts new file mode 100644 index 00000000000..2f74e8a1c7f --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin-options.ts @@ -0,0 +1,24 @@ +import type WebSocket from 'ws' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract' +import type { RelayAssignment } from '../director/relay-http-client' +import type { RelayControlOrigin } from './relay-control-origin' +import type { RelayDrainMessage } from '../control-channel/relay-control-protocol' + +export type RelayControlOriginOptions = { + assignment: RelayAssignment + relayJwt: string + relayHostId: string + identity: RelayIdentity + keypair: E2EEKeypair + appVersion: string + mobileSocketWiring: MobileSocketWiring + createControlSocket?: (url: string, relayJwt: string) => WebSocket + createDataSocket?: (url: string) => WebSocket + onConnectionOwned: (connectionId: string, origin: RelayControlOrigin) => void + onConnectionReleased: (connectionId: string, origin: RelayControlOrigin) => void + onDrain: (origin: RelayControlOrigin, message: RelayDrainMessage) => void + onClose: (origin: RelayControlOrigin, code: number) => void + onPendingChanged?: (origin: RelayControlOrigin) => void +} diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-origin.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-control-origin.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin.ts index cbe78b50a7e..002df4b73de 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-origin.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin.ts @@ -1,14 +1,14 @@ import type { RelayControlOriginOptions } from './relay-control-origin-options' -import { CloudRelayTransport } from '../rpc/relay-transport' -import { RelayControlClient } from './relay-control-client' -import { RELAY_HOST_ATTACH_DEADLINE_MS } from './relay-control-protocol' +import { CloudRelayTransport } from '../../rpc/transports/relay-transport' +import { RelayControlClient } from '../control-channel/relay-control-client' +import { RELAY_HOST_ATTACH_DEADLINE_MS } from '../control-channel/relay-control-protocol' import type { RelayConnectionOpenMessage, RelayHostHelloAckMessage, RelayPendingConnection -} from './relay-control-protocol' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { RelayAssignment } from './relay-http-client' +} from '../control-channel/relay-control-protocol' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import type { RelayAssignment } from '../director/relay-http-client' const OBSERVED_OPEN_LIMIT = 16 diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-rotation.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-rotation.ts similarity index 92% rename from src/main/runtime/mobile-cloud-relay/relay-control-rotation.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-rotation.ts index 2f1de94e6c0..b3e620a7277 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-rotation.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-rotation.ts @@ -1,6 +1,6 @@ import type { RelayControlOrigin } from './relay-control-origin' -import type { RelayAssignment } from './relay-http-client' -import { relayRenewalDelayMs } from './relay-renewal-jitter' +import type { RelayAssignment } from '../director/relay-http-client' +import { relayRenewalDelayMs } from '../session-lifecycle/relay-renewal-jitter' type RotationOptions = { current: () => RelayControlOrigin | null diff --git a/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-options.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-options.ts new file mode 100644 index 00000000000..c31f90108e3 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-options.ts @@ -0,0 +1,23 @@ +import type WebSocket from 'ws' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract' +import type { MobileRelayStatus as RelayBrokerStatus } from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { RelayRegion } from '../region-selection/relay-region-probe' + +export type RelayOriginPoolOptions = { + directorUrl: string + relayHostId: string + identity: RelayIdentity + keypair: E2EEKeypair + appVersion: string + mobileSocketWiring: MobileSocketWiring + isCurrent: () => boolean + onStatus: (status: RelayBrokerStatus) => void + resolvePreferredRegion?: () => Promise + fetch?: typeof globalThis.fetch + createControlSocket?: (url: string, relayJwt: string) => WebSocket + createDataSocket?: (url: string) => WebSocket + random?: () => number + now?: () => number +} diff --git a/src/main/runtime/mobile-cloud-relay/relay-origin-pool.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool.ts similarity index 94% rename from src/main/runtime/mobile-cloud-relay/relay-origin-pool.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool.ts index c189ef8b908..e135de4eeae 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-origin-pool.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool.ts @@ -1,11 +1,15 @@ import { RelayOriginRetirement } from './relay-origin-retirement' import type { RelayOriginPoolOptions } from './relay-origin-pool-options' import { RelayControlOrigin } from './relay-control-origin' -import type { RelayControlClient } from './relay-control-client' -import type { RelayDrainMessage } from './relay-control-protocol' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import { RelayRetrySchedule } from './relay-retry-schedule' -import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client' +import type { RelayControlClient } from '../control-channel/relay-control-client' +import type { RelayDrainMessage } from '../control-channel/relay-control-protocol' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import { RelayRetrySchedule } from '../authentication/relay-retry-schedule' +import { + RelayHttpError, + requestRelayAssignment, + type RelayAssignment +} from '../director/relay-http-client' import { RelayControlRotation } from './relay-control-rotation' export class RelayOriginPool { diff --git a/src/main/runtime/mobile-cloud-relay/relay-origin-retirement.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-retirement.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-origin-retirement.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-retirement.ts index bcc2a439ef2..8ae08bd49c0 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-origin-retirement.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-retirement.ts @@ -1,4 +1,4 @@ -import type { RelayDrainMessage } from './relay-control-protocol' +import type { RelayDrainMessage } from '../control-channel/relay-control-protocol' import type { RelayControlOrigin } from './relay-control-origin' export class RelayOriginRetirement { diff --git a/src/main/runtime/mobile-cloud-relay/relay-pairing-authorization.ts b/src/main/runtime/mobile-cloud-relay/pairing/relay-pairing-authorization.ts similarity index 76% rename from src/main/runtime/mobile-cloud-relay/relay-pairing-authorization.ts rename to src/main/runtime/mobile-cloud-relay/pairing/relay-pairing-authorization.ts index 9f2d5e48132..97e87ea5b94 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-pairing-authorization.ts +++ b/src/main/runtime/mobile-cloud-relay/pairing/relay-pairing-authorization.ts @@ -1,5 +1,5 @@ -import type { MobilePairingConnectionContext } from '../rpc/server/runtime-rpc-pairing-types' -import type { DeviceCredentialInstallAuthorization } from './relay-control-requests' +import type { MobilePairingConnectionContext } from '../../rpc/server/runtime-rpc-pairing-types' +import type { DeviceCredentialInstallAuthorization } from '../control-channel/relay-control-requests' // Derives install authorization only from immutable connection metadata, never from request params. export function pairingAuthorizationForContext( diff --git a/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts new file mode 100644 index 00000000000..2fd60c56a06 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts @@ -0,0 +1,33 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +import { RelayRevokeOutbox } from './relay-revoke-outbox' + +describe('RelayRevokeOutbox', () => { + const paths: string[] = [] + afterEach(() => { + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + }) + + it('durably retains an idempotent account-scoped revoke after local deletion', () => { + const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) + paths.push(path) + const binding = { + relayHostId: 'AbCdEf0123_-xyZ9', + relayDeviceId: 'device-1', + ownerIdentityKey: 'user-1\0profile-1\0org-1' + } + const first = new RelayRevokeOutbox(path).enqueue(binding) + const reloaded = new RelayRevokeOutbox(path) + expect(reloaded.enqueue(binding).reqId).toBe(first.reqId) + expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first]) + reloaded.remove(first.reqId) + expect( + new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId) + ).toEqual([]) + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts rename to src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts index fba0a05ef81..f800980229e 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts +++ b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts @@ -5,7 +5,7 @@ import { hardenExistingSecureFile, isUnreadableError, writeSecureJsonFile -} from '../../../shared/secure-storage/secure-file' +} from '../../../../shared/secure-storage/secure-file' export type RelayDeviceBinding = { relayHostId: string diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-catalog-fetch.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-catalog-fetch.ts similarity index 91% rename from src/main/runtime/mobile-cloud-relay/relay-region-catalog-fetch.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-catalog-fetch.ts index 64566b89b94..385eab9e41e 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-catalog-fetch.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-catalog-fetch.ts @@ -1,5 +1,5 @@ -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' -import { readFetchResponseJsonWithinLimit } from '../../../shared/fetch-response-body' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' +import { readFetchResponseJsonWithinLimit } from '../../../../shared/fetch-response-body' import { RelayRegionCatalogSchema, type RelayRegionCatalog } from './relay-region-probe' const CATALOG_MAX_BYTES = 16 * 1024 diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-correction-protocol.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-correction-protocol.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-correction-protocol.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-correction-protocol.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-decision.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-decision.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-decision.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-decision.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference-reader.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference-reader.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-preference-reader.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference-reader.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts similarity index 99% rename from src/main/runtime/mobile-cloud-relay/relay-region-preference.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts index db5e0205449..7276e4dab77 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts @@ -6,7 +6,7 @@ import { z } from 'zod' import { hardenExistingSecureFile, writeSecureJsonFile -} from '../../../shared/secure-storage/secure-file' +} from '../../../../shared/secure-storage/secure-file' import { fetchRelayRegionCatalog, relayDirectorHost } from './relay-region-catalog-fetch' import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' import { diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-probe-log.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe-log.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-probe-log.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe-log.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-probe.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-region-probe.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe.ts index f296c3f6a18..fee8f97d5c3 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-probe.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe.ts @@ -1,6 +1,6 @@ import { performance } from 'node:perf_hooks' import { z } from 'zod' -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const export type RelayRegion = (typeof RELAY_REGIONS)[number] diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-refresh.ts similarity index 97% rename from src/main/runtime/mobile-cloud-relay/relay-region-refresh.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-refresh.ts index c93a9d9618e..88fba8fe921 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-refresh.ts @@ -1,4 +1,8 @@ -import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client' +import { + RelayHttpError, + requestRelayAssignment, + type RelayAssignment +} from '../director/relay-http-client' import type { RelayRegionCorrectionRequest, RelayRegionDecision, diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts deleted file mode 100644 index c6e724ee319..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { DesktopRelayService } from './desktop-relay-service' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import type { RelayAuthContext } from './relay-auth-identity' -import { RelayHttpError } from './relay-http-client' - -import { RelaySessionBroker } from './relay-session-broker' - -const context: RelayAuthContext = { - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - accessToken: 'access-1', - relayEntitled: true -} - -function fakeSessionBroker(): RelaySessionBroker { - const broker = Object.create(RelaySessionBroker.prototype) - Object.defineProperties(broker, { - closeNow: { value: vi.fn() }, - isLive: { value: () => true }, - createPairingRelay: { value: vi.fn(async () => ({ inviteExpiresAt: 1 })) }, - endpoint: { value: null }, - hostId: { value: 'host-1' }, - ownerIdentityKey: { value: 'owner-1' } - }) - return broker -} - -function serviceWith(coordinator: RelayAuthCoordinator): DesktopRelayService { - const service = Object.create(DesktopRelayService.prototype) - return Object.assign(service, { - coordinator, - stopped: false, - livenessTimer: null, - demandExpiryTimer: null, - demandLedger: { acquireTransient: () => () => {}, nextPendingExpiry: () => null } - }) -} - -describe('relay readiness', () => { - afterEach(() => vi.useRealTimers()) - - it('waits through the retry a cold-start failure scheduled instead of failing the mint', async () => { - vi.useFakeTimers() - const broker = fakeSessionBroker() - const openBroker = vi - .fn() - .mockRejectedValueOnce(new RelayHttpError('assignment', 503)) - .mockResolvedValueOnce(broker) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: () => {}, - random: () => 1 - }) - const service = serviceWith(coordinator) - const mint = service.createPairingRelay('device-1') - await vi.advanceTimersByTimeAsync(2_000) - await expect(mint).resolves.toMatchObject({ binding: { relayHostId: 'host-1' } }) - expect(openBroker).toHaveBeenCalledTimes(2) - service.stop() - }) - - it('stops waiting when a fence cancels the scheduled retry', async () => { - vi.useFakeTimers() - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker: async () => { - throw new RelayHttpError('token-exchange', 502) - }, - onStatus: () => {}, - random: () => 1 - }) - coordinator.reconcile() - const waiting = coordinator.waitForReadiness(20_000) - await vi.advanceTimersByTimeAsync(0) - coordinator.fenceAndCloseNow() - await expect(waiting).resolves.toEqual({ - ready: false, - reason: 'control_not_active', - retryAt: null - }) - }) - - function coldStartWithHungRetry(): RelayAuthCoordinator { - const openBroker = vi - .fn() - .mockRejectedValueOnce(new RelayHttpError('assignment', 503)) - .mockImplementationOnce(() => new Promise(() => {})) - return new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: () => {}, - random: () => 0.5 - }) - } - - it('returns at its deadline while the retry it followed is still opening', async () => { - vi.useFakeTimers() - const coordinator = coldStartWithHungRetry() - coordinator.reconcile() - let settled: unknown = null - void coordinator.waitForReadiness(10_000).then((readiness) => (settled = readiness)) - await vi.advanceTimersByTimeAsync(9_999) - expect(settled).toBeNull() - await vi.advanceTimersByTimeAsync(1) - expect(settled).toMatchObject({ ready: false, reason: 'director_assignment_503' }) - coordinator.stop() - }) - - it.each(['fence', 'stop'] as const)( - 'a %s releases a waiter whose followed retry is still opening', - async (action) => { - vi.useFakeTimers() - const coordinator = coldStartWithHungRetry() - coordinator.reconcile() - let settled: unknown = null - void coordinator.waitForReadiness(20_000).then((readiness) => (settled = readiness)) - await vi.advanceTimersByTimeAsync(1_000) - expect(settled).toBeNull() - if (action === 'fence') { - coordinator.fenceAndCloseNow() - } else { - coordinator.stop() - } - await vi.advanceTimersByTimeAsync(0) - expect(settled).toMatchObject({ ready: false, retryAt: null }) - coordinator.stop() - } - ) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts deleted file mode 100644 index 955701e1ae3..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import type { RelayAuthContext } from './relay-auth-identity' -import { RelayHttpError } from './relay-http-client' - -const context: RelayAuthContext = { - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - accessToken: 'access-1', - relayEntitled: true -} - -afterEach(() => { - vi.useRealTimers() -}) - -describe('RelayAuthCoordinator transient recovery', () => { - it('does not carry a pending retry across an identity switch', async () => { - vi.useFakeTimers() - let current = context - const broker = { closeNow: vi.fn() } - const openBroker = vi - .fn() - .mockRejectedValueOnce(new Error('temporary control open failure')) - .mockResolvedValueOnce(broker) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => current, - openBroker, - onStatus: vi.fn(), - random: () => 0.75 - }) - - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledOnce() - - current = { - ...context, - identity: { ...context.identity, profileId: 'profile-2' } - } - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - expect(coordinator.getActiveBroker()).toBe(broker) - await vi.advanceTimersByTimeAsync(120_000) - - expect(openBroker).toHaveBeenCalledTimes(2) - }) -}) - -describe('RelayAuthCoordinator liveness safety net', () => { - it('reopens a broker that died leaving no retry timer behind', async () => { - // Expired-token refresh failure leaves no retry; ensureLive must revive it. - vi.useFakeTimers() - const dead = { closeNow: vi.fn(), isLive: () => false } - const live = { closeNow: vi.fn(), isLive: () => true } - const openBroker = vi.fn().mockResolvedValueOnce(dead).mockResolvedValueOnce(live) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: vi.fn(), - random: () => 0.5 - }) - - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(coordinator.getActiveBroker()).toBe(dead) - await vi.advanceTimersByTimeAsync(600_000) - expect(openBroker).toHaveBeenCalledOnce() - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - expect(dead.closeNow).toHaveBeenCalled() - expect(coordinator.getActiveBroker()).toBe(live) - }) - - it('does not disturb a live broker, a scheduled retry, or an open in flight', async () => { - vi.useFakeTimers() - const broker = { closeNow: vi.fn(), isLive: () => true } - let releaseOpen: ((value: typeof broker) => void) | undefined - const openBroker = vi - .fn() - .mockRejectedValueOnce(new RelayHttpError('assignment', 503, 30_000)) - .mockImplementationOnce( - () => - new Promise((resolve) => { - releaseOpen = resolve - }) - ) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: vi.fn(), - random: () => 0.5 - }) - - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledOnce() - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledOnce() - - await vi.advanceTimersByTimeAsync(30_000) - expect(openBroker).toHaveBeenCalledTimes(2) - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - releaseOpen?.(broker) - await vi.advanceTimersByTimeAsync(0) - expect(coordinator.getActiveBroker()).toBe(broker) - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-identity.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-identity.ts deleted file mode 100644 index 7251ba8d998..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-identity.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { RelayIdentity } from './relay-session-broker-contract' - -export type RelayAuthContext = { - identity: RelayIdentity - accessToken: string - relayEntitled: boolean -} - -export function relayIdentityKey(identity: RelayIdentity): string { - return `${identity.userId}\0${identity.profileId}\0${identity.organizationId}` -} diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts deleted file mode 100644 index aa103136bdb..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { RelayControlLiveness } from './relay-control-liveness' - -describe('RelayControlLiveness keepalive', () => { - afterEach(() => { - vi.useRealTimers() - }) - - function liveness(live = { value: true }) { - const terminate = vi.fn() - // The relay's ack is an inbound frame. - const sendKeepalive = vi.fn((frame: string) => { - expect(frame).toBe('{"type":"keepalive"}') - instance.noteInbound() - }) - const instance: RelayControlLiveness = new RelayControlLiveness({ - cellUrl: 'https://relay.test', - ping: vi.fn(), - isLive: () => live.value, - terminate, - send: sendKeepalive - }) - return { instance, sendKeepalive, terminate, live } - } - - it('sends a keepalive instead of tearing down when its own timers were held back', () => { - vi.useFakeTimers() - const terminate = vi.fn() - const send = vi.fn() - const instance = new RelayControlLiveness({ - cellUrl: 'https://relay.test', - ping: vi.fn(), - isLive: () => true, - terminate, - send - }) - instance.start() - instance.startKeepalive(25_000) - // A throttled app: no timer ran for 100 s, then the silence check runs before the keepalive. - vi.setSystemTime(Date.now() + 100_000) - vi.advanceTimersToNextTimer() - expect(terminate).not.toHaveBeenCalled() - expect(send).toHaveBeenCalledWith('{"type":"keepalive"}') - // Still unanswered at a later check: the link is judged dead as before. - vi.advanceTimersByTime(80_000) - expect(terminate).toHaveBeenCalledOnce() - }) - - it('ignores an offer before the control is active and stops with the control', () => { - vi.useFakeTimers() - const { instance, sendKeepalive } = liveness() - instance.startKeepalive(25_000) - vi.advanceTimersByTime(50_000) - expect(sendKeepalive).not.toHaveBeenCalled() - instance.start() - instance.startKeepalive(25_000) - instance.stop() - vi.advanceTimersByTime(100_000) - expect(sendKeepalive).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-origin-options.ts b/src/main/runtime/mobile-cloud-relay/relay-control-origin-options.ts deleted file mode 100644 index 2302de96422..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-control-origin-options.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type WebSocket from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' -import type { RelayIdentity } from './relay-session-broker-contract' -import type { RelayAssignment } from './relay-http-client' -import type { RelayControlOrigin } from './relay-control-origin' -import type { RelayDrainMessage } from './relay-control-protocol' - -export type RelayControlOriginOptions = { - assignment: RelayAssignment - relayJwt: string - relayHostId: string - identity: RelayIdentity - keypair: E2EEKeypair - appVersion: string - mobileSocketWiring: MobileSocketWiring - createControlSocket?: (url: string, relayJwt: string) => WebSocket - createDataSocket?: (url: string) => WebSocket - onConnectionOwned: (connectionId: string, origin: RelayControlOrigin) => void - onConnectionReleased: (connectionId: string, origin: RelayControlOrigin) => void - onDrain: (origin: RelayControlOrigin, message: RelayDrainMessage) => void - onClose: (origin: RelayControlOrigin, code: number) => void - onPendingChanged?: (origin: RelayControlOrigin) => void -} diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts deleted file mode 100644 index 809676ae2a1..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import type { RelayConnectionOpenMessage, RelayHostHelloAckMessage } from './relay-control-protocol' -import type { RelayAssignment } from './relay-http-client' - -const fakes = vi.hoisted(() => ({ - controls: [] as { - options: { - previousGeneration?: number - controlResumeSecret?: string - onConnectionOpen(message: RelayConnectionOpenMessage): void - onDrain(message: { type: 'drain'; graceMs: number; recovery: 'resolve-director' }): void - onClose(code: number): void - } - }[], - transports: [] as { - openConnections: Set - openConnection: ReturnType - hasConnection: ReturnType - }[], - controlConnect: vi.fn() -})) - -vi.mock('./relay-control-client', () => ({ - RelayControlClient: class { - connect = fakes.controlConnect - closeNow = vi.fn() - isLive = vi.fn(() => true) - pendingRequestCount = 0 - - constructor(readonly options: (typeof fakes.controls)[number]['options']) { - fakes.controls.push(this) - } - } -})) - -vi.mock('../rpc/relay-transport', () => ({ - CloudRelayTransport: class { - readonly openConnections = new Set() - start = vi.fn().mockResolvedValue(undefined) - stop = vi.fn().mockResolvedValue(undefined) - setGeneration = vi.fn() - metadataFor = vi.fn() - hasConnection = vi.fn((connectionId: string) => this.openConnections.has(connectionId)) - openConnection = vi.fn(async (connection: RelayConnectionOpenMessage) => { - this.openConnections.add(connection.connId) - }) - - constructor() { - fakes.transports.push(this) - } - } -})) - -import { RelayControlOrigin } from './relay-control-origin' - -const ASSIGNMENT: RelayAssignment = { - v: 1, - cellUrl: 'https://relay.example.test', - assignmentEpoch: 1, - lease: 'lease-token' -} -const TICKET = 'T'.repeat(43) - -function ack(overrides: Partial = {}): RelayHostHelloAckMessage { - return { - type: 'host-hello-ack', - v: 1, - generation: 7, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [], - ...overrides - } -} - -function connOpen(overrides: Partial = {}): RelayConnectionOpenMessage { - return { - type: 'conn-open', - connId: 'conn-1', - connTicket: TICKET, - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 10_000, - ...overrides - } -} - -function createOrigin(): { - origin: RelayControlOrigin - owned: string[] - released: string[] -} { - const keypair = nacl.box.keyPair() - const owned: string[] = [] - const released: string[] = [] - const origin = new RelayControlOrigin({ - assignment: ASSIGNMENT, - relayJwt: 'relay-jwt', - relayHostId: 'host-1', - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - keypair: { ...keypair, publicKeyB64: Buffer.from(keypair.publicKey).toString('base64') }, - appVersion: '1.0.0', - mobileSocketWiring: { attachTransport: vi.fn(() => () => {}) } as never, - onConnectionOwned: (connectionId) => owned.push(connectionId), - onConnectionReleased: (connectionId) => released.push(connectionId), - onDrain: vi.fn(), - onClose: vi.fn() - }) - return { origin, owned, released } -} - -describe('RelayControlOrigin pending-connection replay', () => { - beforeEach(() => { - fakes.controls.length = 0 - fakes.transports.length = 0 - fakes.controlConnect.mockReset() - }) - - it('replays a pending connection the relay only identified, reusing the observed conn-open', async () => { - fakes.controlConnect - .mockResolvedValueOnce(ack()) - .mockResolvedValueOnce(ack({ pendingConns: [{ connId: 'conn-1', connTicket: TICKET }] })) - const { origin } = createOrigin() - await origin.open() - fakes.controls[0]!.options.onConnectionOpen(connOpen()) - fakes.transports[0]!.openConnections.delete('conn-1') - - await origin.rebind('relay-jwt', ASSIGNMENT) - - expect(fakes.transports[0]!.openConnection).toHaveBeenCalledTimes(2) - expect(fakes.transports[0]!.openConnection).toHaveBeenLastCalledWith({ - type: 'conn-open', - connId: 'conn-1', - connTicket: TICKET, - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 10_000 - }) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-origin-pool-options.ts b/src/main/runtime/mobile-cloud-relay/relay-origin-pool-options.ts deleted file mode 100644 index 4141c226b8e..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-origin-pool-options.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type WebSocket from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' -import type { RelayIdentity } from './relay-session-broker-contract' -import type { MobileRelayStatus as RelayBrokerStatus } from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { RelayRegion } from './relay-region-probe' - -export type RelayOriginPoolOptions = { - directorUrl: string - relayHostId: string - identity: RelayIdentity - keypair: E2EEKeypair - appVersion: string - mobileSocketWiring: MobileSocketWiring - isCurrent: () => boolean - onStatus: (status: RelayBrokerStatus) => void - resolvePreferredRegion?: () => Promise - fetch?: typeof globalThis.fetch - createControlSocket?: (url: string, relayJwt: string) => WebSocket - createDataSocket?: (url: string) => WebSocket - random?: () => number - now?: () => number -} diff --git a/src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts b/src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts deleted file mode 100644 index cc2e7796f52..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { sharedPromiseSettlementWaiters } from '../../../shared/promise-settlement-waiters' -import { RelayReadinessWaiters } from './relay-readiness' - -afterEach(() => vi.useRealTimers()) - -describe('relay readiness wait lifetime', () => { - it('detaches expired mint callers while shared reconnect work remains pending', async () => { - vi.useFakeTimers() - let finish = (): void => {} - const work = new Promise((resolve) => { - finish = resolve - }) - const observed = vi.spyOn(work, 'then') - const waiters = new RelayReadinessWaiters() - const anchor = waiters.until(work, Date.now() + 10_000) - for (let index = 0; index < 100; index += 1) { - const waiting = waiters.until(work, Date.now() + 1) - await vi.advanceTimersByTimeAsync(1) - await expect(waiting).resolves.toBe(false) - } - expect(observed).toHaveBeenCalledOnce() - expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(1) - finish() - await expect(anchor).resolves.toBe(true) - expect(vi.getTimerCount()).toBe(0) - }) - - it('releases callers without cancelling shared work and permits a later wait', async () => { - vi.useFakeTimers() - let finish = (): void => {} - const work = new Promise((resolve) => { - finish = resolve - }) - const waiters = new RelayReadinessWaiters() - const first = waiters.until(work, Date.now() + 10_000) - waiters.releaseAll() - await expect(first).resolves.toBe(false) - expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0) - const next = waiters.until(work, Date.now() + 10_000) - finish() - await expect(next).resolves.toBe(true) - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts b/src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts deleted file mode 100644 index 2d9387c773a..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RelayAssignment } from './relay-http-client' -import type * as RelayHttpClientModule from './relay-http-client' -import type { RelayRegionWindow } from './relay-region-correction-protocol' -const fake = vi.hoisted(() => ({ assign: vi.fn() })) -vi.mock('./relay-http-client', async (original) => ({ - ...(await original()), - requestRelayAssignment: fake.assign -})) -import { RelayRegionRefresh } from './relay-region-refresh' -const HOUR = 60 * 60_000 -const window: RelayRegionWindow = { - generation: 1, - assignmentEpoch: 1, - incumbentRegion: 'asia-east2', - expiresAt: 24 * HOUR, - policyVersion: 1 -} -const assignment: RelayAssignment = { - v: 1, - cellUrl: 'https://source.example.test', - assignmentEpoch: 1, - lease: 'test', - regionCorrection: { v: 1, window } -} -let scheduler: RelayRegionRefresh -function setup(random = 0.5) { - const measure = vi.fn().mockResolvedValue({ - outcome: 'conclusive', - measurements: { 'us-central1': 30, 'asia-east2': 200 } - }) - const applyAssignment = vi.fn(() => true) - const isOnline = vi.fn(() => true) - scheduler = new RelayRegionRefresh({ - directorUrl: 'https://director.example.test', - relayHostId: 'test-host', - token: () => 'test-token', - assignment: () => assignment, - isCurrent: () => true, - isOnline, - applyAssignment, - measure, - random: () => random, - now: () => Date.now() - }) - return { measure, applyAssignment, isOnline } -} -describe('broker-owned region decision refresh', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(0) - fake.assign.mockReset() - }) - afterEach(() => { - scheduler?.close() - vi.useRealTimers() - }) - - it('retries exactly the same report without probing or extending its window', async () => { - const { measure } = setup() - fake.assign - .mockRejectedValueOnce(new Error('offline')) - .mockResolvedValue({ ...assignment, regionCorrection: { v: 1, reportStatus: 'accepted' } }) - scheduler.start(assignment) - await vi.advanceTimersByTimeAsync(60_000) - expect(measure).toHaveBeenCalledOnce() - expect(fake.assign).toHaveBeenCalledTimes(2) - expect(fake.assign.mock.calls[0]![0].regionCorrection).toEqual( - fake.assign.mock.calls[1]![0].regionCorrection - ) - }) - - it('does not report a measurement that completed after broker close', async () => { - const { measure } = setup() - let resolve!: (value: unknown) => void - measure.mockReturnValue( - new Promise((done) => { - resolve = done - }) - ) - scheduler.start(assignment) - scheduler.close() - resolve({ outcome: 'inconclusive', reason: 'incomplete-measurement' }) - await vi.advanceTimersByTimeAsync(0) - expect(fake.assign).not.toHaveBeenCalled() - }) - it('uses a successor window after an expired report retry', async () => { - setup() - fake.assign.mockRejectedValueOnce(new Error('offline')).mockResolvedValue({ - ...assignment, - regionCorrection: { v: 1, window: { ...window, generation: 2, expiresAt: 48 * HOUR } } - }) - scheduler.start(assignment) - await vi.advanceTimersByTimeAsync(0) - vi.setSystemTime(25 * HOUR) - await vi.advanceTimersByTimeAsync(60_000) - expect(fake.assign.mock.calls[1]![0].regionCorrection).toEqual({ v: 1, action: 'issue-window' }) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts b/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts deleted file mode 100644 index 5784b632239..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as SecureFileModule from '../../../shared/secure-storage/secure-file' -import { RelayRevokeOutbox } from './relay-revoke-outbox' - -const secureFileMocks = vi.hoisted(() => ({ failWrites: false })) - -vi.mock('../../../shared/secure-storage/secure-file', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeSecureJsonFile: (targetPath: string, value: unknown) => { - if (secureFileMocks.failWrites) { - throw new Error('disk full') - } - actual.writeSecureJsonFile(targetPath, value) - } - } -}) - -describe('RelayRevokeOutbox', () => { - const paths: string[] = [] - afterEach(() => { - secureFileMocks.failWrites = false - for (const path of paths.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } - }) - - it('durably retains an idempotent account-scoped revoke after local deletion', () => { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) - paths.push(path) - const binding = { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - ownerIdentityKey: 'user-1\0profile-1\0org-1' - } - const first = new RelayRevokeOutbox(path).enqueue(binding) - const reloaded = new RelayRevokeOutbox(path) - expect(reloaded.enqueue(binding).reqId).toBe(first.reqId) - expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first]) - reloaded.remove(first.reqId) - expect( - new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId) - ).toEqual([]) - }) - - it('does not retain an enqueue that failed to reach disk', () => { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) - paths.push(path) - const binding = { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - ownerIdentityKey: 'user-1\0profile-1\0org-1' - } - const outbox = new RelayRevokeOutbox(path) - secureFileMocks.failWrites = true - expect(() => outbox.enqueue(binding)).toThrow('disk full') - - secureFileMocks.failWrites = false - const persisted = outbox.enqueue(binding) - expect( - new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId) - ).toEqual([persisted]) - }) - - it('does not remove an item in memory when the durable removal fails', () => { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) - paths.push(path) - const binding = { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - ownerIdentityKey: 'user-1\0profile-1\0org-1' - } - const outbox = new RelayRevokeOutbox(path) - const item = outbox.enqueue(binding) - secureFileMocks.failWrites = true - expect(() => outbox.remove(item.reqId)).toThrow('disk full') - - secureFileMocks.failWrites = false - expect(outbox.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([item]) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts b/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts deleted file mode 100644 index 033bfefc318..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type WebSocket from 'ws' -import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' -import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { RelayRegion } from './relay-region-probe' -import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' - -export type RelayIdentity = { - userId: string - profileId: string - organizationId: string -} - -// Carry auth refusal through broker-first closure so phones retain the cause. -export type RelayAccessTokenRefresh = - | { accessToken: string } - | { accessToken: null; hostCloseReason?: RelayHostCloseReason } - -export type RelaySessionBrokerOptions = { - authConfig: OrcaCloudAuthConfig - accessToken: string - identity: RelayIdentity - keypair: E2EEKeypair - appVersion: string - mobileSocketWiring: MobileSocketWiring - isCurrent: () => boolean - refreshAccessToken: () => Promise - resolvePreferredRegion?: () => Promise - measureRegionDecision?: (window: RelayRegionWindow) => Promise - onAssignedCellActive?: (cellUrl: string) => void - /** `cellUrl` is absent whenever the host holds no active assignment. */ - onStatus: MobileRelayStatusPublisher - fetch?: typeof globalThis.fetch - createControlSocket?: (url: string, relayJwt: string) => WebSocket - createDataSocket?: (url: string) => WebSocket - random?: () => number - now?: () => number -} - -export class StaleRelayBrokerError extends Error { - constructor() { - super('stale_relay_broker') - } -} diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts b/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts deleted file mode 100644 index f531ba66a81..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' -import type { RelayHostHelloAckMessage } from './relay-control-protocol' -import type * as RelayHttpClientModule from './relay-http-client' - -const fakes = vi.hoisted(() => ({ - controls: [] as { - options: { - onConnectionOpen(message: { - connId: string - connTicket: string - kind: 'invite' | 'resume' - relayDeviceId: string - attachDeadlineMs: number - }): void - onDrain(message: { type: 'drain'; graceMs: number; recovery: 'resolve-director' }): void - onClose(code: number): void - previousGeneration?: number - controlResumeSecret?: string - } - connect: ReturnType - closeNow: ReturnType - confirmResume: ReturnType - installCredential: ReturnType - pendingRequestCount: number - }[], - transports: [] as { - start: ReturnType - stop: ReturnType - setGeneration: ReturnType - metadataFor: ReturnType - openConnection: ReturnType - }[], - controlConnect: vi.fn(), - exchange: vi.fn(), - assign: vi.fn() -})) - -vi.mock('./relay-http-client', async (importOriginal) => ({ - ...(await importOriginal()), - exchangeRelayAuthorization: fakes.exchange, - requestRelayAssignment: fakes.assign -})) - -vi.mock('./relay-control-client', () => ({ - RelayControlClient: class { - connect = fakes.controlConnect - closeNow = vi.fn() - isLive = vi.fn(() => true) - confirmResume = vi.fn().mockResolvedValue({ - type: 'device-resume-confirmed', - v: 1, - reqId: 'confirm-1', - currentVersion: 1, - acceptedAs: 'current', - renewed: true, - resumeExpiresAt: 100_000 - }) - installCredential = vi.fn().mockResolvedValue({ - type: 'device-credential-installed', - v: 1, - reqId: 'install-1', - authorizationMode: 'relay-basis', - currentVersion: 1, - resumeExpiresAt: 100_000 - }) - pendingRequestCount = 0 - - constructor(readonly options: (typeof fakes.controls)[number]['options']) { - fakes.controls.push(this) - } - } -})) - -vi.mock('../rpc/relay-transport', () => ({ - CloudRelayTransport: class { - start = vi.fn().mockResolvedValue(undefined) - stop = vi.fn().mockResolvedValue(undefined) - setGeneration = vi.fn() - metadataFor = vi.fn() - hasConnection = vi.fn(() => false) - openConnection = vi.fn().mockResolvedValue(undefined) - - constructor() { - fakes.transports.push(this) - } - } -})) - -import { RelaySessionBroker } from './relay-session-broker' -import './relay-session-broker-contract' -import './relay-http-client' -import './relay-auth-coordinator' - -import '../../../shared/relay-host-close-reason' - -describe('RelaySessionBroker lifecycle ownership', () => { - beforeEach(() => { - fakes.controls.length = 0 - fakes.transports.length = 0 - fakes.controlConnect.mockReset() - fakes.exchange.mockReset().mockResolvedValue({ relayToken: 'relay-jwt', expiresAt: 1_000_000 }) - fakes.assign.mockReset().mockResolvedValue(relayAssignment('https://relay.example.test', 1)) - }) - - it('recovers through a new origin after the director failure clears', async () => { - vi.useFakeTimers() - try { - const ack: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } - fakes.controlConnect.mockResolvedValue(ack) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://relay-c1.example.test', 1)) - .mockRejectedValueOnce(new Error('director_unavailable')) - .mockResolvedValueOnce(relayAssignment('https://relay-c2.example.test', 2)) - const broker = await RelaySessionBroker.connect(brokerOptions({ random: () => 0.5 })) - - fakes.controls[0]!.options.onDrain({ - type: 'drain', - graceMs: 5_000, - recovery: 'resolve-director' - }) - await vi.advanceTimersByTimeAsync(499) - expect(broker.endpoint?.cellUrl).toBe('https://relay-c1.example.test') - await vi.advanceTimersByTimeAsync(1) - expect(broker.endpoint?.cellUrl).toBe('https://relay-c2.example.test') - expect(fakes.assign).toHaveBeenCalledTimes(3) - broker.closeNow() - } finally { - vi.useRealTimers() - } - }) -}) - -// Renewal can discover auth loss before the coordinator; its close must carry the reason. - -function relayAssignment( - cellUrl: string, - assignmentEpoch: number -): RelayHttpClientModule.RelayAssignment { - return { v: 1, cellUrl, assignmentEpoch, lease: 'assignment-lease' } -} - -function brokerOptions( - overrides: Partial[0]> = {} -): Parameters[0] { - const keypair = nacl.box.keyPair() - return { - authConfig: { - relayTokenEndpoint: 'https://auth.example.test/v1/relay-token', - relayDirectorUrl: 'https://relay.example.test' - } as OrcaCloudAuthConfig, - accessToken: 'access-token', - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - keypair: { - ...keypair, - publicKeyB64: Buffer.from(keypair.publicKey).toString('base64') - }, - appVersion: '1.0.0', - mobileSocketWiring: { attachTransport: vi.fn(() => () => {}) } as never, - isCurrent: () => true, - refreshAccessToken: async () => ({ accessToken: null }), - onStatus: vi.fn(), - now: () => 0, - random: () => 0, - ...overrides - } -} diff --git a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts b/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts deleted file mode 100644 index a5461458549..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { RelayWallClockTimer } from './relay-wall-clock-timer' - -function resumeSource(): { - subscribe: (onResume: () => void) => () => void - resume: () => void - count: () => number -} { - const listeners = new Set<() => void>() - return { - subscribe: (onResume) => { - listeners.add(onResume) - onResume() - return () => listeners.delete(onResume) - }, - resume: () => { - for (const listener of Array.from(listeners)) { - listener() - } - }, - count: () => listeners.size - } -} - -describe('RelayWallClockTimer', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('runs a task that fell due during a sleep as soon as the machine resumes', () => { - vi.useFakeTimers() - let wall = 1_000_000 - const source = resumeSource() - const timer = new RelayWallClockTimer(() => wall, source.subscribe) - const task = vi.fn() - timer.schedule(180_000, task) - // Asleep: the wall clock moves, the timer clock does not. - wall += 200_000 - source.resume() - expect(task).toHaveBeenCalledTimes(1) - vi.advanceTimersByTime(180_000) - expect(task).toHaveBeenCalledTimes(1) - expect(source.count()).toBe(0) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-renewal-jitter.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-renewal-jitter.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-renewal-jitter.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-renewal-jitter.ts diff --git a/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-contract.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-contract.ts new file mode 100644 index 00000000000..c64035b95e5 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-contract.ts @@ -0,0 +1,49 @@ +import type WebSocket from 'ws' +import type { OrcaCloudAuthConfig } from '../../../orca-profiles/cloud-auth/profile-cloud-auth-config' +import type { MobileRelayStatusPublisher } from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import type { RelayRegion } from '../region-selection/relay-region-probe' +import type { + RelayRegionDecision, + RelayRegionWindow +} from '../region-selection/relay-region-correction-protocol' + +export type RelayIdentity = { + userId: string + profileId: string + organizationId: string +} + +// Carry auth refusal through broker-first closure so phones retain the cause. +export type RelayAccessTokenRefresh = + | { accessToken: string } + | { accessToken: null; hostCloseReason?: RelayHostCloseReason } + +export type RelaySessionBrokerOptions = { + authConfig: OrcaCloudAuthConfig + accessToken: string + identity: RelayIdentity + keypair: E2EEKeypair + appVersion: string + mobileSocketWiring: MobileSocketWiring + isCurrent: () => boolean + refreshAccessToken: () => Promise + resolvePreferredRegion?: () => Promise + measureRegionDecision?: (window: RelayRegionWindow) => Promise + onAssignedCellActive?: (cellUrl: string) => void + /** `cellUrl` is absent whenever the host holds no active assignment. */ + onStatus: MobileRelayStatusPublisher + fetch?: typeof globalThis.fetch + createControlSocket?: (url: string, relayJwt: string) => WebSocket + createDataSocket?: (url: string) => WebSocket + random?: () => number + now?: () => number +} + +export class StaleRelayBrokerError extends Error { + constructor() { + super('stale_relay_broker') + } +} diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker.ts similarity index 93% rename from src/main/runtime/mobile-cloud-relay/relay-session-broker.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker.ts index d7be7f45381..c4ae1d3a7e9 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts +++ b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker.ts @@ -3,21 +3,21 @@ import type { RelaySessionBrokerOptions } from './relay-session-broker-contract' import { relayStatusCellUrl, type MobileRelayStatus as RelayBrokerStatus -} from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { PairingRelay } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import type * as RelayCredentials from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { DeviceCredentialInstallAuthorization } from './relay-control-requests' +} from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { PairingRelay } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type * as RelayCredentials from '../../../../shared/remote-runtime/relay/mobile-relay-credential-contract' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import type { DeviceCredentialInstallAuthorization } from '../control-channel/relay-control-requests' import { deriveRelayHostId, exchangeRelayAuthorization, requestRelayAssignment, type RelayAuthorization, type RelayAssignment -} from './relay-http-client' -import { relayIdentityKey } from './relay-auth-identity' -import { RelayOriginPool } from './relay-origin-pool' -import { RelayRegionRefresh } from './relay-region-refresh' +} from '../director/relay-http-client' +import { relayIdentityKey } from '../authentication/relay-auth-identity' +import { RelayOriginPool } from '../origin-lifecycle/relay-origin-pool' +import { RelayRegionRefresh } from '../region-selection/relay-region-refresh' import { relayRenewalDelayMs } from './relay-renewal-jitter' import { RelayWallClockTimer } from './relay-wall-clock-timer' diff --git a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-wall-clock-timer.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-wall-clock-timer.ts index da84d170f86..c04c38765e6 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts +++ b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-wall-clock-timer.ts @@ -1,4 +1,4 @@ -import { subscribeSystemPowerLifecycle } from '../../power/system-power-lifecycle' +import { subscribeSystemPowerLifecycle } from '../../../power/system-power-lifecycle' type SubscribeResume = (onResume: () => void) => () => void diff --git a/src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts b/src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts new file mode 100644 index 00000000000..11af3b19dff --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest' +import type { DesktopRelayService } from '../desktop-relay-service' +import { createDesktopRelayServiceInstaller } from '../desktop-relay-service-installer' + +function fakeService(): DesktopRelayService { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installer only calls start() and wraps the provider methods. + return { start: vi.fn() } as unknown as DesktopRelayService +} + +function installerWith(overrides: { + create: () => DesktopRelayService | null + isFenced?: () => boolean + whenNetworkReady?: Promise +}) { + const runtimeRpc = { setMobileRelayPairingProvider: vi.fn() } + const onInstalled = vi.fn() + const installer = createDesktopRelayServiceInstaller({ + runtimeRpc, + whenNetworkReady: overrides.whenNetworkReady ?? Promise.resolve(), + isFenced: overrides.isFenced ?? (() => false), + create: overrides.create, + onInstalled + }) + return { installer, runtimeRpc, onInstalled } +} + +describe('createDesktopRelayServiceInstaller', () => { + it('refuses installs after sign-out, including one already waiting, until the next auth change', async () => { + let ready!: () => void + const whenNetworkReady = new Promise((resolve) => (ready = resolve)) + const create = vi.fn(() => fakeService()) + const { installer } = installerWith({ create, whenNetworkReady }) + + const waiting = installer.ensure() + installer.suspend() + ready() + await expect(waiting).resolves.toBe(false) + await expect(installer.ensure()).resolves.toBe(false) + expect(create).not.toHaveBeenCalled() + await expect(installer.authChanged()).resolves.toBe(true) + expect(create).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts b/src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts similarity index 96% rename from src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts rename to src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts index fa9bf85f755..b0215561891 100644 --- a/src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts +++ b/src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts @@ -4,10 +4,10 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import nacl from 'tweetnacl' import WebSocketClient, { WebSocketServer, type RawData, type WebSocket } from 'ws' -import { DeviceRegistry } from '../rpc/server/pairing/device-registry' -import { MobileSocketWiring } from '../rpc/mobile-socket-wiring' -import { CloudRelayTransport } from '../rpc/relay-transport' -import { deriveRelayHostId } from './relay-http-client' +import { DeviceRegistry } from '../../rpc/server/pairing/device-registry' +import { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import { CloudRelayTransport } from '../../rpc/transports/relay-transport' +import { deriveRelayHostId } from '../director/relay-http-client' import { SimulatedMobileE2EEV2Peer } from './simulated-mobile-e2ee-v2-peer' function deferred() { diff --git a/src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer.ts b/src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer.ts similarity index 90% rename from src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer.ts rename to src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer.ts index e4fd1d59291..acc3d389f44 100644 --- a/src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer.ts +++ b/src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer.ts @@ -4,13 +4,13 @@ import { validateMobileE2EEV2Handshake, type MobileE2EEPayloadKind, type MobileE2EEV2Hello -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' +} from '../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' import { openMobileE2EEV2Frame, sealMobileE2EEV2Frame -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' -import { deriveSharedKey } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' +} from '../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' +import { deriveSharedKey } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { deriveMobileE2EEV2KeySchedule } from '../../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' // Independent mobile wire peer for desktop tests, avoiding Expo imports. export class SimulatedMobileE2EEV2Peer { diff --git a/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.ts b/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.ts index fa30a6d765a..98f605f6a72 100644 --- a/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.ts +++ b/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.ts @@ -1,7 +1,7 @@ import { PHONE_RELAY_CONNECT_BUDGET_MS } from '../../../shared/remote-runtime/recipe-vm-wake' import { verifyRelayedGitHubAuthority } from './relay-github-authority' import { createRelayedBrowserTab } from './relayed-browser-tab-create' -import { GITHUB_EXACT_OPERATION_UNSUPPORTED } from '../../../shared/github/work-item-target' +import { GITHUB_EXACT_OPERATION_UNSUPPORTED } from '../../../shared/github/work-items/work-item-target' import { pairedRuntimeConnectionFromOffer } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' import { randomUUID } from 'node:crypto' import type { RpcRequest } from '../rpc/core' diff --git a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts index 0c0a0ebeee0..aa953d2563c 100644 --- a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts +++ b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts @@ -11,7 +11,7 @@ import type { SshConnectionState } from '../../../shared/ssh-types' import type { MobileDesktopRelayHosts } from './mobile-desktop-relay-hosts' import { MobileRelayHostCatalog } from './mobile-relay-host-catalog' -import { PairedServerRowsProducer } from '../sidebar-inputs/paired-server-rows-producer' +import { PairedServerRowsProducer } from '../sidebar-inputs/workspace-rows/paired-server-rows-producer' function answer(capable: boolean): RuntimeStatus { return { diff --git a/src/main/runtime/mobile-desktop-relay/relay-github-authority.ts b/src/main/runtime/mobile-desktop-relay/relay-github-authority.ts index 552b91f0a99..cd28d4cb32a 100644 --- a/src/main/runtime/mobile-desktop-relay/relay-github-authority.ts +++ b/src/main/runtime/mobile-desktop-relay/relay-github-authority.ts @@ -1,7 +1,7 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' -import { classifyExactGitHubOperation } from '../../../shared/github/exact-work-item-operation' -import { GITHUB_EXACT_OPERATION_UNSUPPORTED } from '../../../shared/github/work-item-target' +import { classifyExactGitHubOperation } from '../../../shared/github/work-items/exact-work-item-operation' +import { GITHUB_EXACT_OPERATION_UNSUPPORTED } from '../../../shared/github/work-items/work-item-target' import { GITHUB_EXACT_DETAILS_READ_INTENT_RUNTIME_CAPABILITY } from '../../../shared/work-items/task-source-runtime-capabilities' import { GITHUB_EXACT_WORK_ITEM_TARGET_RUNTIME_CAPABILITY } from '../../../shared/source-control/runtime/source-control-runtime-capabilities' import type { RemoteRuntimePassthroughSocket } from '../../../shared/remote-runtime/remote-runtime-passthrough-socket' diff --git a/src/main/runtime/mobile-desktop-relay/relayed-browser-tab-create.ts b/src/main/runtime/mobile-desktop-relay/relayed-browser-tab-create.ts index 6349a4ff417..157683952b4 100644 --- a/src/main/runtime/mobile-desktop-relay/relayed-browser-tab-create.ts +++ b/src/main/runtime/mobile-desktop-relay/relayed-browser-tab-create.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' -import { BrowserTabCreateParams } from '../../../shared/rpc-contract/browser-tab-create-params' +import { BrowserTabCreateParams } from '../../../shared/rpc-contract/browser/browser-tab-create-params' import { RuntimeRpcEnvelopeSchema, type RuntimeRpcResponse diff --git a/src/main/runtime/mobile-subscribe-exit-first-screen.test.ts b/src/main/runtime/mobile-subscribe-exit-first-screen.test.ts deleted file mode 100644 index 3f5b3917868..00000000000 --- a/src/main/runtime/mobile-subscribe-exit-first-screen.test.ts +++ /dev/null @@ -1,223 +0,0 @@ -import './rpc/unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from './orca-runtime' -import { RpcDispatcher } from './rpc/dispatcher' -import { TERMINAL_METHODS } from './rpc/methods/terminal/terminal' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText -} from '../../shared/terminal/stream/terminal-stream-protocol' -import { HeadlessEmulator } from '../daemon/emulation/headless-emulator' - -const WORKTREE_ID = 'repo-1::/tmp/wt' -const PTY_ID = `${WORKTREE_ID}@@5e1f0a2b` -const GRID = { cols: 40, rows: 6 } - -type RuntimeInternals = { - recordPtyWorktree: (ptyId: string, worktreeId: string, state?: { connected?: boolean }) => unknown - issuePtyHandle: (pty: unknown) => string -} - -function internals(runtime: OrcaRuntimeService): RuntimeInternals { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test reaches protected members the runtime defines. - return runtime as unknown as RuntimeInternals -} - -async function paintedRows(cols: number, rows: number, data: string): Promise { - const emulator = new HeadlessEmulator({ cols, rows, scrollback: 0 }) - try { - await emulator.write(data) - return emulator.getVisibleLines().map((line) => line.trimEnd()) - } finally { - emulator.dispose() - } -} - -function setup(controller: Partial[0]> = {}) { - const runtime = new OrcaRuntimeService() - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - getSize: () => GRID, - ...controller - }) - const handle = internals(runtime).issuePtyHandle( - internals(runtime).recordPtyWorktree(PTY_ID, WORKTREE_ID, { connected: true }) - ) - return { runtime, handle } -} - -/** Subscribes a phone whose fit is still running when the PTY writes `lastOutput` and exits. */ -async function subscribeThroughExit( - runtime: OrcaRuntimeService, - handle: string, - capabilities: { outputAck?: number }, - lastOutput: string -) { - let finishFit = (): void => {} - const fit = vi - .spyOn(runtime, 'handleMobileSubscribe') - .mockImplementation(() => new Promise((resolve) => (finishFit = () => resolve(true)))) - const messages: string[] = [] - const frames: Uint8Array[] = [] - const done = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }).dispatchStreaming( - { - id: 'req-phone', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: handle, - client: { id: 'phone-1', type: 'mobile' }, - viewport: GRID, - capabilities: { terminalBinaryStream: 1, ...capabilities } - } - }, - (message) => messages.push(message), - { - connectionId: 'conn-phone', - sendBinary: (bytes) => { - frames.push(bytes) - }, - registerBinaryStreamHandler: () => () => {} - } - ) - await vi.waitFor(() => expect(fit).toHaveBeenCalled()) - if (lastOutput) { - runtime.onPtyData(PTY_ID, lastOutput, 2_000) - } - await runtime.onPtyExit(PTY_ID, 2) - finishFit() - await done - const decoded = frames.flatMap((bytes) => decodeTerminalStreamFrame(bytes) ?? []) - return { - results: messages.map((message) => JSON.parse(message).result?.type), - snapshotMeta: () => { - const start = decoded.find((frame) => frame.opcode === TerminalStreamOpcode.SnapshotStart) - return start && decodeTerminalStreamJson<{ cols: number; rows: number }>(start.payload) - }, - painted: () => - decoded - .filter( - (frame) => - frame.opcode === TerminalStreamOpcode.SnapshotChunk || - frame.opcode === TerminalStreamOpcode.Output - ) - .map((frame) => decodeTerminalStreamText(frame.payload)) - .join('') - } -} - -describe('phone subscribe when the PTY exits while its first screen is publishing', () => { - it.each([{ outputAck: 1 }, {}])( - 'sends the final screen before end (capabilities %o)', - async (credit) => { - const { runtime, handle } = setup() - runtime.onPtyData(PTY_ID, '$ make\r\n', 1_000) - - const stream = await subscribeThroughExit(runtime, handle, credit, 'build failed\r\n') - - expect(stream.results).toEqual(['subscribed', 'end']) - expect(stream.snapshotMeta()).toMatchObject(GRID) - expect(await paintedRows(GRID.cols, GRID.rows, stream.painted())).toEqual([ - '$ make', - 'build failed', - '', - '', - '', - '' - ]) - expect(runtime.hasHeadlessTerminalState(PTY_ID)).toBe(false) - } - ) - - it('builds no model for the dead PTY when it had none and its pane is mounted', async () => { - const { runtime, handle } = setup({ - hasRendererSerializer: () => true, - getRendererSerializerGeneration: () => 1, - waitForRendererSerializer: async () => true, - serializeBuffer: async () => ({ data: '$ make\r\n', ...GRID }) - }) - vi.spyOn(runtime, 'requestRendererTerminalTabMount').mockReturnValue(false) - expect(runtime.hasHeadlessTerminalState(PTY_ID)).toBe(false) - - const stream = await subscribeThroughExit(runtime, handle, {}, '') - - expect(stream.results).toEqual(['subscribed', 'end']) - expect(runtime.hasHeadlessTerminalState(PTY_ID)).toBe(false) - }) - - it('still sends the renderer screen but builds no model when the PTY exits while it is read', async () => { - let rendererReads = 0 - let finishRead = (): void => {} - let readStarted = (): void => {} - const stableReadStarted = new Promise((resolve) => (readStarted = resolve)) - const { runtime, handle } = setup({ - hasRendererSerializer: () => true, - getRendererSerializerGeneration: () => 1, - waitForRendererSerializer: async () => true, - serializeBuffer: async () => { - rendererReads += 1 - // Hydration, the budgeted snapshot and the readiness probe come first; then the stable read. - if (rendererReads === 1) { - return { data: '', ...GRID } - } - if (rendererReads === 2) { - return null - } - if (rendererReads === 3) { - return { data: 'x', ...GRID } - } - readStarted() - await new Promise((resolve) => (finishRead = resolve)) - return { data: '$ make\r\nbuild failed\r\n', ...GRID, seq: 0 } - } - }) - vi.spyOn(runtime, 'requestRendererTerminalTabMount').mockReturnValue(false) - vi.spyOn(runtime, 'handleMobileSubscribe').mockResolvedValue(true) - const messages: string[] = [] - const frames: Uint8Array[] = [] - const done = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }).dispatchStreaming( - { - id: 'req-phone', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: handle, - client: { id: 'phone-1', type: 'mobile' }, - viewport: GRID, - capabilities: { terminalBinaryStream: 1 } - } - }, - (message) => messages.push(message), - { - connectionId: 'conn-phone', - sendBinary: (bytes) => { - frames.push(bytes) - }, - registerBinaryStreamHandler: () => () => {} - } - ) - await stableReadStarted - await runtime.onPtyExit(PTY_ID, 0) - finishRead() - await done - - expect(messages.map((message) => JSON.parse(message).result?.type)).toEqual([ - 'subscribed', - 'end' - ]) - const snapshot = frames - .flatMap((bytes) => decodeTerminalStreamFrame(bytes) ?? []) - .filter((frame) => frame.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => decodeTerminalStreamText(frame.payload)) - .join('') - expect((await paintedRows(GRID.cols, GRID.rows, snapshot)).slice(0, 2)).toEqual([ - '$ make', - 'build failed' - ]) - expect(runtime.hasHeadlessTerminalState(PTY_ID)).toBe(false) - }) -}) diff --git a/src/main/runtime/multi-client-terminal.integration.test.ts b/src/main/runtime/multi-client-terminal.integration.test.ts index 213282227c6..0e59b41df5c 100644 --- a/src/main/runtime/multi-client-terminal.integration.test.ts +++ b/src/main/runtime/multi-client-terminal.integration.test.ts @@ -24,7 +24,7 @@ import { readRuntimeMetadata } from './rpc/server/runtime-metadata' import { sendRequest } from './rpc/server/runtime-rpc-test-harness' import { makeStore } from './rpc/server/runtime-rpc-worktree-store-fixtures' import { partialRuntimeStore } from './orca-runtime-tests/runtime-store-partial-fixture' -import { settledWriteStub } from '../providers/settled-pty-write-stub' +import { settledWriteStub } from '../providers/testing/settled-pty-write-stub' import { publishHeadlessRuntimeGraph } from './session-graph/headless-runtime-graph' import { committingSpawn } from './orca-runtime-tests/bind-first-pane.test-fixture' diff --git a/src/main/runtime/orca-runtime-saved-restore-launch.test.ts b/src/main/runtime/orca-runtime-saved-restore-launch.test.ts deleted file mode 100644 index fd03c943bd2..00000000000 --- a/src/main/runtime/orca-runtime-saved-restore-launch.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { EnsureAgentSessionParams } from '../../shared/rpc-contract/agent-session-params' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import { OrcaRuntimeService } from './orca-runtime' -import { partialRuntimeStore } from './orca-runtime-tests/runtime-store-partial-fixture' - -const TAB = '11111111-1111-4111-8111-111111111111' -const SOURCE_PANE = `${TAB}:22222222-2222-4222-8222-222222222222` -const NEW_TAB = '33333333-3333-4333-8333-333333333333' -const NEW_LEAF = '44444444-4444-4444-8444-444444444444' -const SESSION = { key: 'session_id', id: 'conversation-1' } as const - -function restoreOnHost(args: { - recorded?: { agentArgs: string; agentEnv: Record } - hookMode?: string -}) { - const runtime = new OrcaRuntimeService( - partialRuntimeStore({ - getSettings: () => ({ - disabledTuiAgents: [], - agentCmdOverrides: {}, - agentDefaultArgs: { claude: '--model current' }, - agentDefaultEnv: { claude: { CURRENT: '1' } } - }) - }) - ) - const record = { - paneKey: SOURCE_PANE, - worktreeId: 'worktree-1', - agent: 'claude' as const, - providerSession: SESSION, - prompt: '', - state: 'done' as const, - capturedAt: 1, - updatedAt: 1, - ...(args.recorded ? { launchConfig: args.recorded } : {}) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the host's restore reads only the row's pane, agent and provider session. - const hookRow = { - paneKey: SOURCE_PANE, - agentType: 'claude', - providerSession: { ...SESSION, permissionMode: args.hookMode } - } as AgentStatusIpcPayload - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: 'worktree-1', - path: '/tmp/worktree-1', - connectionId: null - })), - getWorkspaceSessionForWorktree: () => ({ - sleepingAgentSessionsByPaneKey: { [SOURCE_PANE]: record } - }), - getAgentProviderSessionSnapshotFn: () => [hookRow] - }) - const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ - handle: 'term_restore', - tabId: NEW_TAB, - paneKey: `${NEW_TAB}:${NEW_LEAF}`, - ptyId: 'pty-restore', - worktreeId: 'worktree-1', - title: null, - surface: 'background' - }) - return { - restore: () => - runtime.ensureAgentSession( - EnsureAgentSessionParams.parse({ - kind: 'explicit', - resumeOrigin: 'saved', - restoreSourcePaneKey: SOURCE_PANE, - worktree: 'id:worktree-1', - agent: 'claude', - providerSession: SESSION, - agentArgs: '--model client', - placement: { tabId: NEW_TAB, leafId: NEW_LEAF } - }) - ), - launched: () => createTerminal.mock.calls[0]?.[1] - } -} - -// A Wake opens a new tab: the host must replay the pane that ran, not the new pane or its own settings. -describe('a saved restore into a new pane on its host', () => { - it("replays the source pane's note", async () => { - const host = restoreOnHost({ - recorded: { agentArgs: '--verbose', agentEnv: { RECORDED: '1' } } - }) - await host.restore() - expect(host.launched()?.command).toContain('--verbose') - expect(host.launched()?.command).not.toContain('--model') - expect(host.launched()?.env).toMatchObject({ RECORDED: '1' }) - expect(host.launched()?.env).not.toHaveProperty('CURRENT') - }) - - it("without a note, keeps only the bypass the host's hooks saw, never current settings", async () => { - const host = restoreOnHost({ hookMode: 'bypassPermissions' }) - await host.restore() - expect(host.launched()?.command).toContain('--dangerously-skip-permissions') - expect(host.launched()?.command).not.toContain('--model') - expect(host.launched()?.env).not.toHaveProperty('CURRENT') - }) -}) diff --git a/src/main/runtime/orca-runtime-test-mocks/github-hosted-review-test-harness.ts b/src/main/runtime/orca-runtime-test-mocks/github-hosted-review-test-harness.ts index 916703fc1d8..464f41685a3 100644 --- a/src/main/runtime/orca-runtime-test-mocks/github-hosted-review-test-harness.ts +++ b/src/main/runtime/orca-runtime-test-mocks/github-hosted-review-test-harness.ts @@ -1,3 +1,29 @@ +import type * as RepoSlugUpstreamModule from '../../github/client/fetch/repo-slug-upstream' +import type * as GetPrForBranchModule from '../../github/client/lookup/get-pr-for-branch' +import type * as PrForBranchOutcomeModule from '../../github/client/lookup/pr-for-branch-outcome' +import type * as GetWorkItemModule from '../../github/client/fetch/get-work-item' +import type * as PullRequestPushTargetModule from '../../github/client/lookup/pull-request-push-target' +import type * as GetPrChecksModule from '../../github/client/check/get-pr-checks' +import type * as RerunPrChecksModule from '../../github/client/check/rerun-pr-checks' +import type * as GetPrCheckDetailsModule from '../../github/client/check/get-pr-check-details' +import type * as GetPrCommentsModule from '../../github/client/fetch/get-pr-comments' +import type * as ResolveReviewThreadModule from '../../github/client/update/resolve-review-thread' +import type * as PrFileViewedModule from '../../github/client/update/pr-file-viewed' +import type * as PrDetailsModule from '../../github/client/update/pr-details' +import type * as MergePrModule from '../../github/client/merge/merge-pr' +import type * as PrAutoMergeModule from '../../github/client/merge/pr-auto-merge' +import type * as PrStateModule from '../../github/client/update/pr-state' +import type * as PrReviewersModule from '../../github/client/update/pr-reviewers' +import type * as AddPrReviewCommentModule from '../../github/client/create/add-pr-review-comment' +import type * as IssuesModule from '../../github/issues/issues' +import type * as ListWorkItemsModule from '../../github/client/list/list-work-items' +import type * as CountWorkItemsModule from '../../github/client/list/count-work-items' +import type * as IssueCreateModule from '../../github/issues/issue-create' +import type * as IssueUpdateModule from '../../github/issues/issue-update' +import type * as IssueCommentModule from '../../github/issues/issue-comment' +import type * as IssueFieldOptionsModule from '../../github/issues/issue-field-options' +import type * as WorkItemDetailsModule from '../../github/work-items/work-item-details' +import type * as PullRequestFileContentsModule from '../../github/pull-requests/files/pull-request-file-contents' import { vi, type Mock } from 'vitest' // GitHub and hosted-review mocks shared by runtime specs through setup.spec. @@ -105,176 +131,147 @@ vi.mock('../../source-control/hosted-review', () => ({ })) vi.mock('../../github/client/fetch/repo-slug-upstream', async (importOriginal) => ({ - ...(await importOriginal>()), + ...(await importOriginal()), getRepoSlug: getRepoSlugMock, getRepoUpstream: getRepoUpstreamMock })) -vi.mock('../../github/client', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { - ...actual, - getPRForBranch: getPRForBranchMock, - getPRForBranchOutcome: getPRForBranchOutcomeMock, - getRepoSlug: getRepoSlugMock, - getRepoUpstream: getRepoUpstreamMock, - getWorkItem: getGitHubWorkItemMock, - getPullRequestPushTarget: getPullRequestPushTargetMock, - getWorkItemByOwnerRepo: getGitHubWorkItemByOwnerRepoMock, - getPRChecks: getGitHubPRChecksMock, - rerunPRChecks: rerunGitHubPRChecksMock, - getPRCheckDetails: getGitHubPRCheckDetailsMock, - getPRComments: getGitHubPRCommentsMock, - resolveReviewThread: resolveGitHubReviewThreadMock, - setPRFileViewed: setGitHubPRFileViewedMock, - updatePRTitle: updateGitHubPRTitleMock, - updatePRDetails: updateGitHubPRDetailsMock, - mergePR: mergeGitHubPRMock, - setPRAutoMerge: setGitHubPRAutoMergeMock, - updatePRState: updateGitHubPRStateMock, - requestPRReviewers: requestGitHubPRReviewersMock, - removePRReviewers: removeGitHubPRReviewersMock, - addPRReviewComment: addGitHubPRReviewCommentMock, - addPRReviewCommentReply: addGitHubPRReviewCommentReplyMock, - listIssues: listGitHubIssuesMock, - listWorkItems: listGitHubWorkItemsMock, - countWorkItems: countGitHubWorkItemsMock, - getIssue: getIssueMock, - createIssue: createGitHubIssueMock, - updateIssue: updateGitHubIssueMock, - addIssueComment: addGitHubIssueCommentMock, - listLabels: listGitHubLabelsMock, - listAssignableUsers: listGitHubAssignableUsersMock - } -}) +vi.mock('../../github/client/lookup/get-pr-for-branch', async (importOriginal) => ({ + ...(await importOriginal()), + getPRForBranch: getPRForBranchMock +})) -vi.mock('../../github/work-item-details', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { - ...actual, - getWorkItemDetails: getGitHubWorkItemDetailsMock, - getPRFileContents: getGitHubPRFileContentsMock - } -}) - -vi.mock('../../github/issues', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { - ...actual, - getIssue: getIssueMock, - listIssues: listGitHubIssuesMock - } -}) - -vi.mock(import('../../github/client/lookup/pr-for-branch-outcome'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/lookup/pr-for-branch-outcome', async (importOriginal) => ({ + ...(await importOriginal()), getPRForBranchOutcome: getPRForBranchOutcomeMock })) -vi.mock(import('../../github/client/fetch/get-work-item'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/fetch/get-work-item', async (importOriginal) => ({ + ...(await importOriginal()), getWorkItem: getGitHubWorkItemMock, getWorkItemByOwnerRepo: getGitHubWorkItemByOwnerRepoMock })) -vi.mock(import('../../github/client/check/get-pr-checks'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/lookup/pull-request-push-target', async (importOriginal) => { + return { + ...(await importOriginal()), + getPullRequestPushTarget: getPullRequestPushTargetMock + } +}) + +vi.mock('../../github/client/check/get-pr-checks', async (importOriginal) => ({ + ...(await importOriginal()), getPRChecks: getGitHubPRChecksMock })) -vi.mock(import('../../github/client/check/rerun-pr-checks'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/check/rerun-pr-checks', async (importOriginal) => ({ + ...(await importOriginal()), rerunPRChecks: rerunGitHubPRChecksMock })) -vi.mock(import('../../github/client/check/get-pr-check-details'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/check/get-pr-check-details', async (importOriginal) => ({ + ...(await importOriginal()), getPRCheckDetails: getGitHubPRCheckDetailsMock })) -vi.mock(import('../../github/client/fetch/get-pr-comments'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/fetch/get-pr-comments', async (importOriginal) => ({ + ...(await importOriginal()), getPRComments: getGitHubPRCommentsMock })) -vi.mock(import('../../github/client/update/resolve-review-thread'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/update/resolve-review-thread', async (importOriginal) => ({ + ...(await importOriginal()), resolveReviewThread: resolveGitHubReviewThreadMock })) -vi.mock(import('../../github/client/update/pr-file-viewed'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/update/pr-file-viewed', async (importOriginal) => ({ + ...(await importOriginal()), setPRFileViewed: setGitHubPRFileViewedMock })) -vi.mock(import('../../github/client/update/pr-details'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/update/pr-details', async (importOriginal) => ({ + ...(await importOriginal()), updatePRTitle: updateGitHubPRTitleMock, updatePRDetails: updateGitHubPRDetailsMock })) -vi.mock(import('../../github/client/merge/merge-pr'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/merge/merge-pr', async (importOriginal) => ({ + ...(await importOriginal()), mergePR: mergeGitHubPRMock })) -vi.mock(import('../../github/client/merge/pr-auto-merge'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/merge/pr-auto-merge', async (importOriginal) => ({ + ...(await importOriginal()), setPRAutoMerge: setGitHubPRAutoMergeMock })) -vi.mock(import('../../github/client/update/pr-state'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/update/pr-state', async (importOriginal) => ({ + ...(await importOriginal()), updatePRState: updateGitHubPRStateMock })) -vi.mock(import('../../github/client/update/pr-reviewers'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/update/pr-reviewers', async (importOriginal) => ({ + ...(await importOriginal()), requestPRReviewers: requestGitHubPRReviewersMock, removePRReviewers: removeGitHubPRReviewersMock })) -vi.mock(import('../../github/client/create/add-pr-review-comment'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/create/add-pr-review-comment', async (importOriginal) => ({ + ...(await importOriginal()), addPRReviewComment: addGitHubPRReviewCommentMock, addPRReviewCommentReply: addGitHubPRReviewCommentReplyMock })) -vi.mock(import('../../github/client/list/list-work-items'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/issues/issues', async (importOriginal) => ({ + ...(await importOriginal()), + listIssues: listGitHubIssuesMock, + getIssue: getIssueMock +})) + +vi.mock('../../github/client/list/list-work-items', async (importOriginal) => ({ + ...(await importOriginal()), listWorkItems: listGitHubWorkItemsMock })) -vi.mock(import('../../github/client/list/count-work-items'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/client/list/count-work-items', async (importOriginal) => ({ + ...(await importOriginal()), countWorkItems: countGitHubWorkItemsMock })) -vi.mock(import('../../github/issue-create'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/issues/issue-create', async (importOriginal) => ({ + ...(await importOriginal()), createIssue: createGitHubIssueMock })) -vi.mock(import('../../github/issue-update'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/issues/issue-update', async (importOriginal) => ({ + ...(await importOriginal()), updateIssue: updateGitHubIssueMock })) -vi.mock(import('../../github/issue-comment'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/issues/issue-comment', async (importOriginal) => ({ + ...(await importOriginal()), addIssueComment: addGitHubIssueCommentMock })) -vi.mock(import('../../github/issue-field-options'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('../../github/issues/issue-field-options', async (importOriginal) => ({ + ...(await importOriginal()), listLabels: listGitHubLabelsMock, listAssignableUsers: listGitHubAssignableUsersMock })) -vi.mock(import('../../github/client/lookup/get-pr-for-branch'), async (importOriginal) => ({ - ...(await importOriginal()), - getPRForBranch: getPRForBranchMock -})) +vi.mock('../../github/work-items/work-item-details', async (importOriginal) => { + return { + ...(await importOriginal()), + getWorkItemDetails: getGitHubWorkItemDetailsMock + } +}) + +vi.mock('../../github/pull-requests/files/pull-request-file-contents', async (importOriginal) => { + return { + ...(await importOriginal()), + getPRFileContents: getGitHubPRFileContentsMock + } +}) export { createHostedReviewMock, diff --git a/src/main/runtime/orca-runtime-test-mocks/mobile-presence-store.ts b/src/main/runtime/orca-runtime-test-mocks/mobile-presence-store.ts deleted file mode 100644 index 161b58df2a0..00000000000 --- a/src/main/runtime/orca-runtime-test-mocks/mobile-presence-store.ts +++ /dev/null @@ -1,29 +0,0 @@ -export const mobilePresenceStore = { - getRepo: () => ({ - id: 'repo-1', - path: '/tmp/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 - }), - getRepos: () => [mobilePresenceStore.getRepo()], - addRepo: () => {}, - updateRepo: () => undefined as never, - getAllWorktreeMeta: () => ({}), - getWorktreeMeta: () => undefined, - getGitHubCache: () => ({ pr: {}, issue: {} }), - setWorktreeMeta: () => undefined as never, - removeWorktreeMeta: () => {}, - getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), - addRetiredWorktreeName: () => {}, - mergeRetiredWorktreeNames: () => false, - getSettings: () => ({ - workspaceDir: '/tmp/workspaces', - nestWorkspaces: false, - refreshLocalBaseRefOnWorktreeCreate: false, - branchPrefix: 'none', - branchPrefixCustom: '', - // Legacy restore tests need a finite 5s; production defaults to indefinite hold. - mobileAutoRestoreFitMs: 5_000 - }) -} diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index 6a5eb25c25d..44106d170c9 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -1,7 +1,7 @@ export * from './github-hosted-review-test-harness' export * from './gitlab-test-harness' import type * as WorktreeScanCacheModule from '../../git/worktrees/catalog/worktree-scan-cache' -import { vi, type Mock } from 'vitest' +import { beforeEach, vi, type Mock } from 'vitest' import type * as GitUsernameModule from '../../git/repositories/git-username' import './repo-creation.spec' @@ -13,6 +13,12 @@ export const ORIGIN_REMOTE_URL = 'git@example.com:group/repo.git' export const ORIGIN_HEAD_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_REMOTE_URL) import type { OrcaRuntimeService as OrcaRuntimeServiceConstructor } from '../orca-runtime' import { setWorktreeWatcherRemoval } from '../../workspaces/removal/worktree-watcher-removal' +import { _resetWorktreeCatalogOwnerForTests } from '../../workspaces/catalog/repo-worktree-catalog-owner' + +// Each runtime case once had private scan caches; the process-wide catalog owner starts unobserved instead. +beforeEach(() => { + _resetWorktreeCatalogOwnerForTests() +}) type TestMock = Mock @@ -337,7 +343,9 @@ vi.mock('../../ipc/filesystem/access/filesystem-auth', () => ({ })) vi.mock('../../ipc/worktrees/removal/registered-worktree-roots-cache', () => ({ - invalidateAuthorizedRootsCache: invalidateAuthorizedRootsCacheMock + invalidateAuthorizedRootsCache: invalidateAuthorizedRootsCacheMock, + getRegisteredWorktreeRootsRevision: () => 0, + registerWorktreeRootsForRepo: vi.fn() })) vi.mock('../../ipc/worktrees/removal/registered-worktree-roots-scoped-invalidation', () => ({ diff --git a/src/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts b/src/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts index 288bf1fa176..0dc11827149 100644 --- a/src/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts +++ b/src/main/runtime/orca-runtime-tests/agent-launch-prompt-submit.spec.ts @@ -4,7 +4,6 @@ import { AGENT_PROMPT_BRACKETED_PASTE_END } from '../../../shared/agent-launch/s import { OrcaRuntimeService } from '../orca-runtime' import { acknowledgeAgentPromptSubmit } from '../orca-runtime-test-mocks/setup.spec' import { TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' -import { wrapTerminalBracketedPasteText } from '../../../shared/terminal/input/terminal-bracketed-paste-text' // Match desktop paste: submit Enter one turn after paste, without waiting for render quiescence. async function launchedAgentPane(agent: 'claude' | 'codex' | 'qwen-code', startsTurn = true) { @@ -37,32 +36,6 @@ async function launchedAgentPane(agent: 'claude' | 'codex' | 'qwen-code', starts } describe('a launch prompt into a composer the caller saw ready', () => { - it('pastes the same bytes the desktop draft paste sent for the prompt', async () => { - vi.useFakeTimers() - try { - const { runtime, handle, writes } = await launchedAgentPane('claude') - const prompt = 'Explain this commit:\n- first line\r\n- second line with \x1b[31m colour' - - const send = runtime.sendTerminalAgentPrompt(handle, prompt, { - inputKind: 'launch', - composerReady: true - }) - await vi.advanceTimersByTimeAsync(100) - await send - - const pasted = writes - .map((write) => write.data) - .filter((data) => data !== '\r') - .join('') - expect(pasted).toBe(wrapTerminalBracketedPasteText(prompt)) - expect(pasted).toBe( - '\x1b[200~Explain this commit:\r- first line\r- second line with \u241b[31m colour\x1b[201~' - ) - } finally { - vi.useRealTimers() - } - }) - it('submits one turn after the paste instead of waiting out the render cap', async () => { vi.useFakeTimers() try { @@ -110,22 +83,4 @@ describe('a launch prompt into a composer the caller saw ready', () => { } } ) - - it('keeps a prompt into a running agent behind the render settle, as before', async () => { - vi.useFakeTimers() - try { - const { runtime, handle, writes } = await launchedAgentPane('claude') - - const send = runtime.sendTerminalAgentPrompt(handle, 'fix the checks', { - inputKind: 'driving' - }) - await vi.advanceTimersByTimeAsync(7_000) - expect(writes.map((write) => write.data)).not.toContain('\r') - await vi.advanceTimersByTimeAsync(2_000) - await send - expect(writes.filter((write) => write.data === '\r')).toHaveLength(1) - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts index a1097c6ed27..f7af11cda68 100644 --- a/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-02.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import '../orca-runtime' -import '../../providers/pty-process-inspection' +import '../../providers/pty/process-inspection' import '../../../shared/workspace-layout/stable-pane-id' import { createExplicitAgentStatusHarness, deferred } from './orca-runtime-test-fixtures.spec' @@ -25,18 +25,6 @@ describe('OrcaRuntimeService', () => { expect(confirmForegroundProcess).not.toHaveBeenCalled() }) - it('rejects a handle rebind while a controller-less status check yields', async () => { - const { runtime, handle, syncPty } = await createExplicitAgentStatusHarness({ - getForegroundProcess: async () => 'zsh' - }) - runtime.setPtyController(null) - - const status = runtime.getTerminalAgentStatus(handle) - syncPty('pty-2') - - await expect(status).rejects.toThrow('terminal_handle_stale') - }) - it('rejects confirmation evidence when the handle rebinds during the fresh read', async () => { const confirmation = deferred() const confirmForegroundProcess = vi.fn(() => confirmation.promise) @@ -52,20 +40,4 @@ describe('OrcaRuntimeService', () => { await expect(status).rejects.toThrow('terminal_handle_stale') }) - - it('rejects confirmation evidence when the owning PTY exits', async () => { - const confirmation = deferred() - const confirmForegroundProcess = vi.fn(() => confirmation.promise) - const { runtime, handle } = await createExplicitAgentStatusHarness({ - getForegroundProcess: async () => 'powershell.exe', - confirmForegroundProcess - }) - - const status = runtime.getTerminalAgentStatus(handle) - await vi.waitFor(() => expect(confirmForegroundProcess).toHaveBeenCalledWith('pty-1')) - runtime.onPtyExit('pty-1', 0) - confirmation.resolve('codex') - - await expect(status).rejects.toThrow('terminal_exited') - }) }) diff --git a/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts deleted file mode 100644 index b43133f009b..00000000000 --- a/src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' - -describe('OrcaRuntimeService', () => { - it('keeps ordinary terminal send suffix failures on the existing not-writable contract', async () => { - const writes: string[] = [] - const beforeWrite = vi.fn() - const afterWrite = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }), - write: (_ptyId: string, data: string) => { - writes.push(data) - return data !== '\r' - }, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Codex ready', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'pty-1' - } - ] - }) - - const [terminal] = (await runtime.listTerminals()).terminals - - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'], shouldClearNativeTimers: true }) - try { - await Promise.all([ - expect( - runtime.sendTerminal( - terminal.handle, - { text: 'notes', enter: true }, - { inputKind: 'driving', beforeWrite, afterWrite } - ) - ).rejects.toThrow('terminal_not_writable'), - vi.runAllTimersAsync() - ]) - expect(writes).toEqual(['notes', '\r']) - expect(beforeWrite).toHaveBeenCalledTimes(2) - expect(afterWrite).toHaveBeenCalledOnce() - } finally { - vi.clearAllTimers() - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts b/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts deleted file mode 100644 index f9b3a89e316..00000000000 --- a/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { committingSpawn } from './bind-first-pane.test-fixture' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import '../../../shared/workspace-layout/stable-pane-id' -import type { RuntimeTerminalAgentStatusEvent } from '../terminal/output/terminal-agent-status-events' -import { - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - expectStablePaneKeyEnv, - store -} from './orca-runtime-test-fixtures.spec' -import { spawnedPtyEnv } from '../terminal/launch/spawned-pty-env-fixtures' - -describe('OrcaRuntimeService', () => { - it('preserves OSC 9999 parser state for rendererless background PTYs', async () => { - const statuses: RuntimeTerminalAgentStatusEvent[] = [] - const spawn = vi.fn().mockResolvedValue({ id: 'pty-bg' }) - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalAgentStatus: (event) => statuses.push(event) - }) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - title: 'worker' - }) - const spawnedEnv = spawnedPtyEnv(spawn.mock.calls[0]?.[0]) - const paneKey = expectStablePaneKeyEnv(spawnedEnv) - - runtime.onPtyData('pty-bg', 'before\x1b]999', 123) - runtime.onPtyData('pty-bg', '9;{"state":"done","prompt":"ok"}\x1b\\after', 124) - - expect(statuses).toEqual([ - { - ptyId: 'pty-bg', - source: 'pty-record', - paneKey, - tabId: spawnedEnv.ORCA_TAB_ID, - worktreeId: TEST_WORKTREE_ID, - connectionId: null, - terminalHandle: expect.stringMatching(/^term_/), - payload: { - state: 'done', - prompt: 'ok' - } - } - ]) - }) - - it('continues terminal agent status fanout when a callback throws', () => { - const statuses: RuntimeTerminalAgentStatusEvent[] = [] - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalAgentStatus: (event) => { - statuses.push(event) - if (statuses.length === 1) { - throw new Error('status listener failed') - } - } - }) - const leafId = '11111111-1111-4111-8111-111111111111' - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Terminal', - activeLeafId: leafId, - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId, - paneRuntimeId: 1, - ptyId: 'pty-1' - } - ] - }) - - runtime.onPtyData( - 'pty-1', - '\x1b]9999;{"state":"working","prompt":"one","agentType":"codex"}\x07' + - '\x1b]9999;{"state":"done","prompt":"two","agentType":"codex"}\x07', - 123 - ) - - expect(statuses.map((event) => event.payload.prompt)).toEqual(['one', 'two']) - expect(errorSpy).toHaveBeenCalledWith( - '[runtime] terminal agent status listener threw', - expect.objectContaining({ - ptyId: 'pty-1', - paneKey: `tab-1:${leafId}`, - state: 'working', - agentType: 'codex', - err: expect.any(Error) - }) - ) - }) - - it('keeps blocked prompt text authoritative over an OpenCode marker', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'opencode' - }) - const leafId = '11111111-1111-4111-8111-111111111111' - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'OC | Native session', - activeLeafId: leafId, - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId, - paneRuntimeId: 1, - ptyId: 'pty-1', - paneTitle: 'OC | Native session' - } - ] - }) - runtime.onPtyData( - 'pty-1', - 'Permission required\nThis command requires permission\nAllow once\nAllow always\nReject\n', - 123 - ) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({ - handle: terminal.handle, - isRunningAgent: true, - status: 'permission' - }) - await expect( - runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - satisfied: false, - blockedReason: 'agent-interactive-prompt' - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/bind-first-pane.test-fixture.ts b/src/main/runtime/orca-runtime-tests/bind-first-pane.test-fixture.ts index dc7be8afda1..0e4a6baf7d7 100644 --- a/src/main/runtime/orca-runtime-tests/bind-first-pane.test-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/bind-first-pane.test-fixture.ts @@ -9,7 +9,7 @@ import { storeOf } from '../terminal/layout/profile-session-store.test-fixture' import { reusedTerminalIdUnbinding } from '../../persistence/loading-store/terminal-bindings/reused-terminal-id-unbind' -import { layoutContainsLeafId } from '../../../shared/workspace-layout/terminal-pane-tree' +import { layoutContainsLeafId } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import type { OrcaRuntimeService } from '../orca-runtime' export type BoundPane = { diff --git a/src/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts b/src/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts index 31dc7d65eb7..16de2d82ff5 100644 --- a/src/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts +++ b/src/main/runtime/orca-runtime-tests/browser-capabilities.spec.ts @@ -1,6 +1,6 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' +import '../orca-runtime' import '../orca-runtime-test-mocks/setup.spec' import { getBrowserHostLeaseRegistry } from '../browser-host/leases/browser-host-lease-registry-instance' import { getRuntimeBrowserPageRegistry } from '../browser/client-pages/runtime-browser-page-registry' @@ -119,49 +119,4 @@ describe('OrcaRuntimeService', () => { survivor ) }) - - it('drops a client page record even when its close command cannot be issued', async () => { - const runtime = createRuntime() - const host = attachClientBrowserHost(runtime) - await publishClientHostedPage(runtime, host, 'page-removed', TEST_WORKTREE_ID) - host.detachDelivery() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - runtime['removeWorktreeMetadataAndHistory'](store as never, TEST_WORKTREE_ID) - - expect(getRuntimeBrowserPageRegistry(runtime).getPage('page-removed')).toBeUndefined() - expect(runtime['buildHeadlessMobileSessionBrowserTabs'](TEST_WORKTREE_ID)).toEqual([]) - await vi.waitFor(() => - expect(warn).toHaveBeenCalledWith( - expect.stringContaining('could not close its client page'), - expect.objectContaining({ - browserPageId: 'page-removed', - error: expect.objectContaining({ message: 'browser_host_command_delivery_required' }) - }) - ) - ) - warn.mockRestore() - }) - - it('leaves client-hosted pages alone when another host still owns the same worktree id', async () => { - const runtimeStore = { - ...store, - getWorktreeMeta: () => ({ ...store.getWorktreeMeta(TEST_WORKTREE_ID), hostId: 'local' }), - removeWorktreeMeta: vi.fn() - } - const runtime = new OrcaRuntimeService(runtimeStore as never) - const host = attachClientBrowserHost(runtime) - const placement = await publishClientHostedPage(runtime, host, 'page-kept', TEST_WORKTREE_ID) - - runtime['removeWorktreeMetadataAndHistory']( - runtimeStore as never, - TEST_WORKTREE_ID, - 'runtime:env-b' - ) - - expect(host.takeCommands()).toEqual([]) - expect(getRuntimeBrowserPageRegistry(runtime).getPage('page-kept')?.placement).toEqual( - placement - ) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts b/src/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts index f4a3f6bec81..b2908be3d5f 100644 --- a/src/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts +++ b/src/main/runtime/orca-runtime-tests/conpty-stream-read.spec.ts @@ -46,21 +46,4 @@ describe('OrcaRuntimeService ConPTY stream reads', () => { clearNativeWindowsConptyPty(ptyId) } }) - - it('fills the requested line count even when blank rows sit below the prompt', async () => { - const ptyId = 'pty-conpty-limit' - markNativeWindowsConptyPty(ptyId) - try { - const runtime = startConptyRuntime(ptyId) - const [terminal] = (await runtime.listTerminals()).terminals - const output = Array.from({ length: 40 }, (_, index) => `line-${index}\r\n`).join('') - runtime.onPtyData(ptyId, output, 100) - - const read = await runtime.readTerminal(terminal.handle, { limit: 3 }) - - expect(read.tail).toEqual(['line-37', 'line-38', 'line-39']) - } finally { - clearNativeWindowsConptyPty(ptyId) - } - }) }) diff --git a/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts deleted file mode 100644 index d01a7500876..00000000000 --- a/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import '../orca-runtime-test-mocks/setup.spec' - -import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' - -describe('OrcaRuntimeService', () => { - it('projects frame-independent live state through main buffer snapshots', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.registerPty('pty-frame-state', TEST_WORKTREE_ID) - runtime.onPtyData('pty-frame-state', '\x1b[?1049h\x1b[?1004h\x1b[?25lSTATIC-FRAME', 123) - - const snapshot = await runtime.serializeMainTerminalBuffer('pty-frame-state') - - expect(snapshot?.frameRestoreAnsi).toContain('\x1b[?1004h') - expect(snapshot?.frameRestoreAnsi).toContain('\x1b[?25l') - expect(snapshot?.frameRestoreAnsi).not.toContain('STATIC-FRAME') - expect(snapshot?.data).toContain('STATIC-FRAME') - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts b/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts index daff33f8b55..ef5209e1ace 100644 --- a/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts +++ b/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { setPlatform } from '../orca-runtime-test-mocks/setup.spec' -import type { RuntimeTerminalAgentStatusEvent } from '../terminal/output/terminal-agent-status-events' import type { HeadlessEmulator } from '../../daemon/emulation/headless-emulator' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { @@ -15,41 +14,12 @@ import { TEST_WORKTREE_ID, createRuntime, makeDeferred, - makeStatusFrame, parseHeadlessSnapshotLines, - referenceStatusFrameLines, store, syncSinglePty } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('resizes the headless mirror after an accepted desktop PTY resize', async () => { - const spawn = { cols: 80, rows: 24 } - const resized = { cols: 120, rows: 30 } - let currentSize = spawn - const runtime = createRuntime() - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - getSize: () => currentSize - }) - syncSinglePty(runtime, 'pty-1') - - runtime.onPtyData('pty-1', 'user@host % claude\r\n', 100) - currentSize = resized - runtime.onExternalPtyResize('pty-1', resized.cols, resized.rows) - for (let index = 0; index < 5; index += 1) { - runtime.onPtyData('pty-1', makeStatusFrame(index, index === 0), 200 + index) - } - - const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 5000 }) - expect(snapshot).toMatchObject({ cols: resized.cols, rows: resized.rows, source: 'headless' }) - await expect(parseHeadlessSnapshotLines(snapshot!, resized)).resolves.toEqual( - await referenceStatusFrameLines(spawn, resized) - ) - }) - it('orders headless mirror resizes behind queued PTY writes', async () => { const spawn = { cols: 80, rows: 10 } const resized = { cols: 120, rows: 10 } @@ -138,35 +108,6 @@ describe('OrcaRuntimeService', () => { expect(restored).toContain('AGENTS.md') }) - it('replaces suffix-only headless state with the recovered renderer snapshot', async () => { - const runtime = createRuntime() - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - getSize: () => ({ cols: 47, rows: 40 }) - }) - syncSinglePty(runtime, 'pty-1') - runtime.seedHeadlessTerminal('pty-1', 'suffix-only redraw', { cols: 47, rows: 40 }) - - runtime.replaceHeadlessTerminalFromRendererSnapshotForRecovery('pty-1', { - data: 'restored history\r\nprompt $ ', - cols: 200, - rows: 50, - cwd: '/projects/restored' - }) - runtime.onPtyData('pty-1', 'after recovery\r\n', 100) - - const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { - scrollbackRows: 100 - }) - expect(snapshot?.data).toContain('restored history') - expect(snapshot?.data).toContain('after recovery') - expect(snapshot?.data).not.toContain('suffix-only redraw') - expect(snapshot?.cwd).toBe('/projects/restored') - expect({ cols: snapshot?.cols, rows: snapshot?.rows }).toEqual({ cols: 47, rows: 40 }) - }) - it('retains cold-restored history in hidden-output recovery while renderer serialization is pending', async () => { const runtime = createRuntime() syncSinglePty(runtime, 'cold-pty') @@ -234,50 +175,6 @@ describe('OrcaRuntimeService', () => { expect(liveSnapshot?.terminalOwner).toBeUndefined() }) - it('stamps SSH connection identity on runtime terminal status', () => { - const statuses: RuntimeTerminalAgentStatusEvent[] = [] - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalAgentStatus: (event) => statuses.push(event) - }) - const leafId = '11111111-1111-4111-8111-111111111111' - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Terminal', - activeLeafId: leafId, - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId, - paneRuntimeId: 1, - ptyId: 'pty-ssh' - } - ] - }) - runtime.registerPty('pty-ssh', TEST_WORKTREE_ID, 'ssh-conn-1') - - runtime.onPtyData('pty-ssh', '\x1b]9999;{"state":"working","agentType":"codex"}\x07', 123) - - expect(statuses).toEqual([ - expect.objectContaining({ - ptyId: 'pty-ssh', - source: 'mounted-leaf', - connectionId: 'ssh-conn-1', - payload: expect.objectContaining({ - state: 'working', - agentType: 'codex' - }) - }) - ]) - }) - it('keeps SSH OSC7 cwd POSIX when the desktop runtime is on Windows', async () => { setPlatform('win32') const runtime = new OrcaRuntimeService(store) @@ -312,38 +209,4 @@ describe('OrcaRuntimeService', () => { expect(cwds.get('pty-ubuntu')).toBe('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo') expect(cwds.get('pty-debian')).toBe('\\\\wsl.localhost\\Debian\\home\\me\\repo') }) - - it('does not retain WSL context when a PTY id is reused', () => { - setPlatform('win32') - const runtime = new OrcaRuntimeService(store) - runtime.preparePtyExecutionContext('pty-reused', 'Ubuntu', { resetIncarnation: true }) - runtime.registerPty('pty-reused', TEST_WORKTREE_ID) - runtime.onPtyExit('pty-reused', 0) - - runtime.preparePtyExecutionContext('pty-reused', null, { resetIncarnation: true }) - runtime.registerPty('pty-reused', TEST_WORKTREE_ID) - runtime.onPtyData('pty-reused', '\x1b]7;file://server/share/repo\x07', 1) - - const cwds = (runtime as unknown as { terminalCwdByPtyId: Map }) - .terminalCwdByPtyId - expect(cwds.get('pty-reused')).toBe('\\\\server\\share\\repo') - }) - - it('preserves immutable context while a live daemon attach is unresolved', () => { - setPlatform('win32') - const runtime = new OrcaRuntimeService(store) - runtime.preparePtyExecutionContext('pty-attached', 'Ubuntu', { resetIncarnation: true }) - runtime.registerPty('pty-attached', TEST_WORKTREE_ID) - - const changed = runtime.preparePtyExecutionContext('pty-attached', 'Debian', { - preserveExisting: true - }) - runtime.onPtyData('pty-attached', '\x1b]7;file://DESKTOP/home/me/repo\x07', 1) - - const cwd = ( - runtime as unknown as { terminalCwdByPtyId: Map } - ).terminalCwdByPtyId.get('pty-attached') - expect(changed).toBe(false) - expect(cwd).toBe('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo') - }) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts deleted file mode 100644 index 856d8fdda90..00000000000 --- a/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts +++ /dev/null @@ -1,423 +0,0 @@ -import { settledWriteStub } from '../../providers/settled-pty-write-stub' -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import { - bindSinglePtyRun, - setInMemoryOrchestrationMessages, - store, - syncSinglePty -} from './orca-runtime-test-fixtures.spec' -import { InMemoryOrchestrationMessages } from '../orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec' -import { MessageWake } from '../orchestration/mailbox/runtime-message-waiters' - -describe('OrcaRuntimeService', () => { - it('points a Run mailbox at its live-idle coordinator without replaying pending rows', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - db.setRun({ - id: 'run_mailbox', - coordinator_handle: terminal.handle, - coordinator_pane_key: `${terminal.tabId}:${terminal.leafId}` - }) - const message = db.insertMessage({ - from: 'term_worker', - to: 'run:run_mailbox', - subject: 'one P3 finding', - body: 'private worker report', - type: 'worker_done' - }) - - runtime.notifyMessageArrived('run:run_mailbox', 'worker_done') - await Promise.resolve() - expect(write).not.toHaveBeenCalled() - - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - expect(write).toHaveBeenCalledWith( - 'pty-1', - '\nYou have 1 orchestration message. Run `orca-dev orchestration check --run run_mailbox`.\n' - ) - expect(write).not.toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('private worker report') - ) - await vi.advanceTimersByTimeAsync(500) - expect(write).toHaveBeenCalledWith('pty-1', '\r') - expect(message.delivered_at).toEqual(expect.any(String)) - - runtime.notifyMessageArrived('run:run_mailbox', 'worker_done') - await Promise.resolve() - await vi.advanceTimersByTimeAsync(500) - expect( - write.mock.calls.filter( - ([, payload]) => typeof payload === 'string' && payload.includes('orchestration check') - ) - ).toHaveLength(1) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('repoints worker_done when a stale waiter wakes without consuming it', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - db.setRun({ - id: 'run_stale_waiter', - coordinator_handle: terminal.handle, - coordinator_pane_key: `${terminal.tabId}:${terminal.leafId}` - }) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - write.mockClear() - - const staleWait = runtime.waitForMessage('run:run_stale_waiter', { - typeFilter: ['worker_done'], - timeoutMs: 60_000 - }) - db.insertMessage({ - from: 'term_final_worker', - to: 'run:run_stale_waiter', - subject: 'final worker settled', - type: 'worker_done' - }) - runtime.notifyMessageArrived('run:run_stale_waiter', 'worker_done') - - await expect(staleWait).resolves.toBeInstanceOf(MessageWake) - expect(write).not.toHaveBeenCalled() - - db.insertMessage({ - from: 'term_other_worker', - to: 'run:run_stale_waiter', - subject: 'newer status', - type: 'status' - }) - runtime.deliverPendingMessagesForHandle('run:run_stale_waiter', new Set(['worker_done'])) - await vi.advanceTimersByTimeAsync(500) - - const pointers = () => - write.mock.calls.filter( - ([, payload]) => typeof payload === 'string' && payload.includes('orchestration check') - ) - expect(pointers()).toHaveLength(1) - expect(pointers()[0]?.[1]).toContain('You have 1 orchestration message') - - await vi.advanceTimersByTimeAsync(1_500) - expect(pointers()).toHaveLength(2) - expect(pointers()[1]?.[1]).toContain('You have 1 orchestration message') - db.close() - } finally { - vi.useRealTimers() - } - }) - - // Mail follows the terminal: a window reload does not hold a live-idle terminal's restored mail. - it('points restored mail at the repair edge while the window reloads', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.registerPreAllocatedHandleForPty('pty-1', terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - runtime.markRendererReloading(1) - db.insertMessage({ - from: 'term_worker', - to: terminal.handle, - subject: 'restored' - }) - setInMemoryOrchestrationMessages(runtime, db) - - await vi.advanceTimersByTimeAsync(2_000) - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('stops a pending repoint after its database closes', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new OrchestrationDb(':memory:') - const write = vi.fn().mockReturnValue(true) - runtime.setOrchestrationDb(db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - db.insertMessage({ - runId: 'run_legacy_local', - from: 'term_worker', - to: terminal.handle, - subject: 'pending' - }) - runtime.notifyMessageArrived(terminal.handle, 'status') - db.close() - - await vi.advanceTimersByTimeAsync(2_000) - expect(write).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - - it('points already-idle Run mail after Codex replaces its completion title', async () => { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => 'codex' - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - db.setRun({ - id: 'run_codex_native_title', - coordinator_handle: terminal.handle, - coordinator_pane_key: `${terminal.tabId}:${terminal.leafId}` - }) - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;Codex ready\x07') - runtime.onPtyData('pty-1', '\x1b]0;fix-12953-orchestration-mail-pointer\x07', 101) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() - db.insertMessage({ - from: 'term_worker', - to: 'run:run_codex_native_title', - subject: 'real-agent smoke complete', - body: 'The package name is orca.', - type: 'worker_done' - }) - - runtime.notifyMessageArrived('run:run_codex_native_title', 'worker_done') - await Promise.resolve() - - await vi.waitFor(() => { - expect(write).toHaveBeenCalledWith( - 'pty-1', - '\nYou have 1 orchestration message. Run `orca-dev orchestration check --run run_codex_native_title`.\n' - ) - }) - db.close() - }) - - it('does not inject pending mail on notify when the recipient awaits permission', async () => { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex waiting for permission\x07', 100) - const message = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'while asking' - }) - write.mockClear() - - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - - expect(write).not.toHaveBeenCalled() - // Held rows must remain undelivered for a later edge; stamping without writing would lose delivery (#12584). - expect(message.delivered_at).toBeNull() - db.close() - }) - - it('delivers on a first live idle frame that follows a seeded idle with no transition', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.seedTerminalRestoreTail('pty-1', { lastTitle: 'Codex done' }) - const message = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'restored idle' - }) - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - write.mockClear() - - // Resumed agents can report idle first; seeded idle has no transition, so liveness alone must release mail (#12536). - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 100) - - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toEqual(expect.any(String)) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('does not push on a cold-restore seeded idle status with no live observation', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - // Persisted idle is historical; never authorize writes to a possibly busy replacement. - runtime.seedTerminalRestoreTail('pty-1', { lastTitle: 'Codex done' }) - const message = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'seeded idle' - }) - write.mockClear() - - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - - expect(write).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toBeNull() - - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toEqual(expect.any(String)) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('lets a resolved check consume its rows before a later same-tick notify pushes', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - const mailbox = bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - write.mockClear() - - // Waiter removal precedes read-marking by a microtask; deferred push must not duplicate the resolving check's rows. - const consumed = runtime - .waitForMessage(mailbox, { timeoutMs: 5_000 }) - .then(() => db.getUnreadMessages(mailbox).map((row) => (row.read = 1))) - const first = db.insertMessage({ from: 'sender', to: terminal.handle, subject: 'pulled' }) - runtime.notifyMessageArrived(terminal.handle, 'status') - const second = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'also pulled' - }) - runtime.notifyMessageArrived(terminal.handle, 'status') - - await consumed - await Promise.resolve() - expect(write).not.toHaveBeenCalled() - expect(first.delivered_at).toBeNull() - expect(second.delivered_at).toBeNull() - db.close() - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts index e9f6d2b5863..de8ebeff271 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts @@ -1,415 +1,10 @@ -import { settledWriteStub } from '../../providers/settled-pty-write-stub' import { describe, expect, it, vi } from 'vitest' -import { registerLivePty } from './bind-first-pane.test-fixture' + import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { - TEST_WORKTREE_ID, - bindSinglePtyRun, - setInMemoryOrchestrationMessages, - store, - syncSinglePty -} from './orca-runtime-test-fixtures.spec' -import { InMemoryOrchestrationMessages } from '../orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec' -import { MessageWake } from '../orchestration/mailbox/runtime-message-waiters' +import { store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('leaves rows a live filtered waiter reserved out of the pushed batch', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - const mailbox = bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - write.mockClear() - - // Push scans all pending rows; exclude worker_done owned by the blocked check or it delivers twice. - const waitPromise = runtime.waitForMessage(mailbox, { - typeFilter: ['worker_done'], - timeoutMs: 5_000 - }) - const status = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'unclaimed status', - type: 'status' - }) - runtime.notifyMessageArrived(terminal.handle, 'status') - const done = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'reserved completion', - type: 'worker_done' - }) - runtime.notifyMessageArrived(terminal.handle, 'worker_done') - - await expect(waitPromise).resolves.toBeInstanceOf(MessageWake) - await vi.advanceTimersByTimeAsync(600) - const payloads = write.mock.calls - .map(([, data]) => data) - .filter((data): data is string => typeof data === 'string') - expect(payloads).toContain( - '\nYou have 1 orchestration message. Run `orca-dev orchestration check --run run_test`.\n' - ) - expect(payloads.some((data) => data.includes('reserved completion'))).toBe(false) - expect(status.delivered_at).toEqual(expect.any(String)) - expect(done.delivered_at).toBeNull() - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('skips rows claimed by a waiter that registered after the notify', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - const mailbox = bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - write.mockClear() - - const message = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'claimed late', - type: 'status' - }) - // A waiter arriving after notify still owns rows before deferred push; consult live waiters at push time. - runtime.notifyMessageArrived(terminal.handle, 'status') - const waitPromise = runtime.waitForMessage(mailbox, { - typeFilter: ['status'], - timeoutMs: 5_000 - }) - await Promise.resolve() - - expect(write).not.toHaveBeenCalled() - expect(message.delivered_at).toBeNull() - - await vi.advanceTimersByTimeAsync(5_000) - await expect(waitPromise).resolves.toBe('timed_out') - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('does not carry pty-record live authority into a rebuilt leaf after a same-id respawn', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - // Non-UUID leaves fall back to tab:paneRuntimeId and are always exit-fenced; use UUID to exercise exact retirement. - const leafId = '11111111-1111-1111-8111-111111111111' - registerLivePty(runtime, 'pty-1', TEST_WORKTREE_ID, null, { tabId: 'tab-1', leafId }) - const syncUuidLeaf = (): void => { - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Codex', - activeLeafId: leafId, - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId, - paneRuntimeId: 1, - ptyId: 'pty-1', - paneTitle: null - } - ] - }) - } - syncUuidLeaf() - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - write.mockClear() - - runtime.onPtyExit('pty-1', 0) - runtime.onPtySpawned('pty-1', undefined, { awaitsRegistration: false }) - registerLivePty(runtime, 'pty-1', TEST_WORKTREE_ID, null, { tabId: 'tab-1', leafId }) - // Rebuild without the previous leaf so PTY-level tail clearing is tested. - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - syncUuidLeaf() - - const leaves = ( - runtime as unknown as { - leaves: Map< - string, - { lastAgentStatus: string | null; lastAgentStatusObservedLive: boolean } - > - } - ).leaves - expect(leaves.size).toBeGreaterThan(0) - const rebuilt = [...leaves.values()][0] - expect(rebuilt.lastAgentStatus).toBe('idle') - expect(rebuilt.lastAgentStatusObservedLive).toBe(false) - - setInMemoryOrchestrationMessages(runtime, db) - const [republished] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, republished.handle) - const message = db.insertMessage({ - from: 'sender', - to: republished.handle, - subject: 'rebuilt leaf' - }) - runtime.notifyMessageArrived(republished.handle, 'status') - await Promise.resolve() - - expect(write).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toBeNull() - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('keeps live idle authority across a renderer graph republish', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - write.mockClear() - - // Graph rebuilds must retain live idle or mail waits forever for another OSC frame (#12536). - syncSinglePty(runtime) - - const [republished] = (await runtime.listTerminals()).terminals - const message = db.insertMessage({ - from: 'sender', - to: republished.handle, - subject: 'after republish' - }) - - runtime.notifyMessageArrived(republished.handle, 'status') - await Promise.resolve() - - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toEqual(expect.any(String)) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('does not reuse the dead process live idle authority after a same-id respawn', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - write.mockClear() - - // Same-id respawn is writable before new status; dead-process idle must never authorize replacement writes. - runtime.onPtyExit('pty-1', 0) - runtime.onPtySpawned('pty-1', undefined, { awaitsRegistration: false }) - setInMemoryOrchestrationMessages(runtime, db) - bindSinglePtyRun(db, terminal.handle) - const message = db.insertMessage({ - from: 'sender', - to: terminal.handle, - subject: 'after same id respawn' - }) - - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - - expect(write).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toBeNull() - - // Replacement can start idle with no transition; its first live idle evidence must reauthorize delivery. - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 200) - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - await vi.advanceTimersByTimeAsync(600) - expect(message.delivered_at).toEqual(expect.any(String)) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('does not re-inject the same message when notify fires again during Enter delay', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - db.insertMessage({ from: 'sender', to: terminal.handle, subject: 'once only' }) - - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - - const pointerWrites = write.mock.calls.filter( - ([, payload]) => typeof payload === 'string' && payload.includes('orchestration check') - ) - expect(pointerWrites).toHaveLength(1) - - await vi.advanceTimersByTimeAsync(500) - const enterWrites = write.mock.calls.filter(([, payload]) => payload === '\r') - expect(enterWrites).toHaveLength(1) - - await vi.advanceTimersByTimeAsync(2_000) - expect( - write.mock.calls.filter( - ([, payload]) => typeof payload === 'string' && payload.includes('orchestration check') - ) - ).toHaveLength(1) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('delivers a second message parked during Enter delay once the flight settles', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - await runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle' }) - const first = db.insertMessage({ from: 'sender', to: terminal.handle, subject: 'first' }) - runtime.notifyMessageArrived(terminal.handle, 'status') - // Arm the first flight before the next message, or this tests ordinary batching. - await Promise.resolve() - - // Mid-flight notify must retry after settlement without losing or duplicating the second row. - const second = db.insertMessage({ from: 'sender', to: terminal.handle, subject: 'second' }) - runtime.notifyMessageArrived(terminal.handle, 'status') - await Promise.resolve() - expect( - write.mock.calls.filter( - ([, payload]) => typeof payload === 'string' && payload.includes('orchestration check') - ) - ).toHaveLength(1) - expect(second.delivered_at).toBeNull() - - // Delayed-Enter settlement alone must retry mail; no further agent OSC is required (#12584). - await vi.advanceTimersByTimeAsync(3_000) - expect(write).toHaveBeenCalledWith('pty-1', '\r') - expect(first.delivered_at).toEqual(expect.any(String)) - expect( - write.mock.calls.filter( - ([, payload]) => typeof payload === 'string' && payload.includes('orchestration check') - ) - ).toHaveLength(2) - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - expect(second.delivered_at).toEqual(expect.any(String)) - db.close() - } finally { - vi.useRealTimers() - } - }) - it('rejects leaf PTY waits when the request signal aborts', async () => { vi.useFakeTimers() try { diff --git a/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts index e0540cde89c..ecaea515c3f 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts @@ -118,9 +118,7 @@ describe('OrcaRuntimeService', () => { } const staleScan = deferred() const scansBefore = vi.mocked(listWorktrees).mock.calls.length - vi.mocked(listWorktrees) - .mockImplementationOnce(() => staleScan.promise) - .mockResolvedValueOnce(MOCK_GIT_WORKTREES) + vi.mocked(listWorktrees).mockImplementationOnce(() => staleScan.promise) const runtime = new OrcaRuntimeService(runtimeStore as never) const stalePoll = runtime.getWorktreePs() @@ -129,8 +127,8 @@ describe('OrcaRuntimeService', () => { const freshPolling = runtime.getWorktreePs() staleScan.resolve(MOCK_GIT_WORKTREES) const [staleResult, freshPoll] = await Promise.all([stalePoll, freshPolling]) - // Both generations scanned; neither poll fell back to stored rows at the scan timeout. - expect(vi.mocked(listWorktrees).mock.calls.length - scansBefore).toBe(2) + // Only the live route lists; the poll admitted for the replaced WSL route runs no Git. + expect(vi.mocked(listWorktrees).mock.calls.length - scansBefore).toBe(1) // Concurrent scans retain the platform map from their own generation even when they finish out of order. expect(staleResult.worktrees[0]).toMatchObject({ terminalPlatform: 'linux' }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts index 12f3e19989f..a842a39b330 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts @@ -1,244 +1,19 @@ import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import '../orca-runtime-test-mocks/setup.spec' +import '../../../shared/constants' + import { HEADLESS_LEAF_ID, - HEADLESS_SECOND_LEAF_ID, - TEST_WINDOW_ID, TEST_WORKTREE_ID, makeHeadlessTerminalLayout, makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal, - makeWorktreeMeta, - store + makeWorkspaceSessionWithHeadlessTerminal } from './orca-runtime-test-fixtures.spec' import '../../../shared/worktree/host-qualified-identity' describe('OrcaRuntimeService', () => { - it('reports the wake as unsupported when a phone activates a worktree on headless serve', async () => { - // #7906: legacy headless hosts cannot wake renderer-owned sleep records; report degradation honestly. - const metaById: Record = { - [TEST_WORKTREE_ID]: makeWorktreeMeta({ isUnread: false }) - } - const resumeSleepingAgents = vi.fn() - const getWorkspaceSession = vi.fn(() => ({ - ...getDefaultWorkspaceSession(), - sleepingAgentSessionsByPaneKey: { - 'tab-1:leaf-1': { - paneKey: 'tab-1:leaf-1', - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - agent: 'codex', - providerSession: { key: 'session_id', id: 'session-1' }, - prompt: 'test', - state: 'done', - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep' - } - } - })) - const runtime = new OrcaRuntimeService({ - ...store, - getAllWorktreeMeta: () => metaById, - getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], - getWorkspaceSession - } as never) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - resumeSleepingAgents, - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - // Ready graph has no real BrowserWindow, keeping available authoritative window null. - electronMocks.BrowserWindow.fromId.mockReturnValue(null as never) - runtime.attachWindow(TEST_WINDOW_ID) - runtime.markGraphReady(TEST_WINDOW_ID) - - const result = await runtime.activateManagedWorktree(`id:${TEST_WORKTREE_ID}`, { - notifyClients: false, - clientKind: 'mobile' - }) - - expect(result.activated).toBe(true) - expect(result.sleepingAgentWake).toBe('unsupported-headless') - // Sleep records belong to the repo's execution-host partition. - expect(getWorkspaceSession).toHaveBeenCalledWith('local') - expect(resumeSleepingAgents).not.toHaveBeenCalled() - }) - - it('materializes phone-local pending terminal tabs without stored PTY bindings', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'fresh-mobile-pty' }) - const focusTerminal = vi.fn() - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'host-tab', - ptyId: null, - worktreeId: TEST_WORKTREE_ID, - title: 'Persisted Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }) - } - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal, - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - const activated = await runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - 'host-tab', - HEADLESS_LEAF_ID, - { notifyClients: false } - ) - - expect(focusTerminal).not.toHaveBeenCalled() - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - worktreeId: TEST_WORKTREE_ID, - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - sessionId: expect.stringMatching(/@@serve-/), - isNewSession: true, - persistHostSessionBinding: true - }) - ) - expect(activated.tabs).toEqual([ - expect.objectContaining({ - id: `host-tab::${HEADLESS_LEAF_ID}`, - status: 'ready', - terminal: expect.any(String) - }) - ]) - }) - - it('keeps the target group active when phone-local activation materializes a tab', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'group-target-pty' }) - const focusTerminal = vi.fn() - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'host-tab' }, - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'host-tab', - ptyId: null, - worktreeId: TEST_WORKTREE_ID, - title: 'Left', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'host-tab-2', - ptyId: null, - worktreeId: TEST_WORKTREE_ID, - title: 'Right', - customTitle: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - terminalLayoutsByTabId: { - 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }), - 'host-tab-2': makeHeadlessTerminalLayout({ [HEADLESS_SECOND_LEAF_ID]: undefined }) - }, - tabGroups: { - [TEST_WORKTREE_ID]: [ - { - id: 'group-left', - worktreeId: TEST_WORKTREE_ID, - activeTabId: 'host-tab', - tabOrder: ['host-tab'] - }, - { - id: 'group-right', - worktreeId: TEST_WORKTREE_ID, - activeTabId: 'host-tab-2', - tabOrder: ['host-tab-2'] - } - ] - } - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal, - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - const activated = await runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - 'host-tab-2', - HEADLESS_SECOND_LEAF_ID, - { notifyClients: false } - ) - - expect(focusTerminal).not.toHaveBeenCalled() - expect(activated.activeGroupId).toBe('group-right') - expect(activated.tabGroups).toEqual([ - expect.objectContaining({ id: 'group-left', activeTabId: 'host-tab' }), - expect.objectContaining({ id: 'group-right', activeTabId: 'host-tab-2' }) - ]) - expect(activated.activeTabId).toBe(`host-tab-2::${HEADLESS_SECOND_LEAF_ID}`) - }) - it('refreshes stale daemon liveness before phone-local terminal materialization', async () => { const stalePtyId = `${TEST_WORKTREE_ID}@@stale-mobile-pty` const spawn = vi.fn().mockResolvedValue({ id: stalePtyId }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-03.spec.ts index 85825f323a6..20180c3fdae 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-03.spec.ts @@ -160,34 +160,6 @@ describe('OrcaRuntimeService', () => { expect(setBackgroundThrottling).not.toHaveBeenCalled() }) - it('selects a created terminal only for the paired caller', async () => { - let spawnIndex = 0 - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn(committingSpawn(runtime, async () => ({ id: `pty-headless-${++spawnIndex}` }))), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - const hostTerminal = await runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`) - - const callerTerminal = await runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { - clientNavigationId: 'device-a', - navigation: 'caller' - }) - - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).activeTabId).toBe( - hostTerminal.tab.id - ) - expect( - (await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`, 'device-a')).activeTabId - ).toBe(callerTerminal.tab.id) - expect( - (await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`, 'device-b')).activeTabId - ).toBe(hostTerminal.tab.id) - }) - it('scopes terminal-create idempotency to the paired caller', async () => { let spawnIndex = 0 const runtime = new OrcaRuntimeService(store) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts index bbd89e5f1b4..b75ef13be64 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts @@ -1,17 +1,16 @@ +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { withDurableRuntimeStore } from './runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' -import { committingSpawn } from './bind-first-pane.test-fixture' +import './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' -import { waitForMobileSessionTabsEvents } from './mobile-session-tab-event-wait' +import './mobile-session-tab-event-wait' import { getDefaultWorkspaceSession } from '../../../shared/constants' import 'node:path' import 'node:fs/promises' import 'node:os' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { HEADLESS_LEAF_ID, TEST_REPO_ID, @@ -25,78 +24,6 @@ import { import '../terminal/launch/spawned-pty-env-fixtures' describe('OrcaRuntimeService', () => { - it('hydrates an SSH worktree only from its SSH workspace-session partition', async () => { - const localSession = makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'local-decoy-tab', - ptyId: 'local-decoy-pty', - worktreeId: TEST_WORKTREE_ID, - title: 'Local decoy', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'local-decoy-tab': makeHeadlessTerminalLayout({ - [HEADLESS_LEAF_ID]: 'local-decoy-pty' - }) - } - }) - const sshPtyId = 'ssh:ssh-1@@remote-pty' - const sshSession = makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'ssh-host-tab', - ptyId: sshPtyId, - worktreeId: TEST_WORKTREE_ID, - title: 'SSH host terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'ssh-host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: sshPtyId }) - } - }) - const remoteRepo = { ...store.getRepo(TEST_REPO_ID)!, connectionId: 'ssh-1' } - const getWorkspaceSession = vi.fn((hostId?: string | null) => - hostId === 'ssh:ssh-1' ? sshSession : localSession - ) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ - ...store, - flushOrThrow: vi.fn(), - getRepos: () => [remoteRepo], - getRepo: (id: string) => (id === TEST_REPO_ID ? remoteRepo : undefined), - getWorkspaceSession - }) - ) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(listed.tabs).toEqual([ - expect.objectContaining({ parentTabId: 'ssh-host-tab', ptyId: sshPtyId }) - ]) - expect(listed.tabs).not.toEqual([expect.objectContaining({ parentTabId: 'local-decoy-tab' })]) - expect(getWorkspaceSession).toHaveBeenCalledWith('ssh:ssh-1') - }) - it('closes a headless SSH tab only in its SSH workspace-session partition', async () => { const sshPtyId = 'ssh:ssh-1@@remote-pty' const localSession = makeWorkspaceSessionWithHeadlessTerminal() @@ -261,213 +188,4 @@ describe('OrcaRuntimeService', () => { expect(kill).toHaveBeenCalledWith(splitPtyId) expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([]) }) - - it('publishes laptop-created remote runtime terminals to phone session tabs', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-empty', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - - const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - command: "claude 'work on the issue'", - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID - }) - runtime.onPtyData('laptop-created-pty', '\x1b]0;Codex working\x07', Date.now()) - runtime.onPtyData('laptop-created-pty', 'Claude is working...\r\n', Date.now()) - - const phoneTabs = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(laptopTerminal.surface).toBe('background') - expect(phoneTabs.tabs).toEqual([ - expect.objectContaining({ - type: 'terminal', - parentTabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID, - status: 'ready', - terminal: laptopTerminal.handle, - agentStatus: expect.objectContaining({ - state: 'working', - paneKey: `laptop-tab:${HEADLESS_LEAF_ID}`, - terminalHandle: laptopTerminal.handle - }) - }) - ]) - await expect(runtime.readTerminal(laptopTerminal.handle)).resolves.toMatchObject({ - tail: ['Claude is working...'] - }) - }) - - it('keeps background-presentation PTY-backed mobile session tabs inactive', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - activate: true, - presentation: 'background', - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID - }) - - const phoneTabs = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(phoneTabs.activeTabId).toBeNull() - expect(phoneTabs.tabs[0]).toMatchObject({ - type: 'terminal', - id: `laptop-tab::${HEADLESS_LEAF_ID}`, - isActive: false - }) - }) - - it('replaces pending phone session tabs when a laptop-created remote PTY becomes live', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-pending', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: `laptop-tab::${HEADLESS_LEAF_ID}`, - activeTabType: 'terminal', - tabGroups: [{ id: 'group-1', activeTabId: 'laptop-tab', tabOrder: ['laptop-tab'] }], - tabs: [ - { - type: 'terminal', - id: `laptop-tab::${HEADLESS_LEAF_ID}`, - parentTabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Starting Claude', - isActive: true - } - ] - } - ] - }) - - const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID - }) - - const phoneTabs = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(phoneTabs.tabs).toHaveLength(1) - expect(phoneTabs.tabs[0]).toMatchObject({ - type: 'terminal', - id: `laptop-tab::${HEADLESS_LEAF_ID}`, - status: 'ready', - terminal: laptopTerminal.handle - }) - }) - - it('pushes PTY-backed mobile session tab title and agent status changes to subscribers', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID - }) - events.length = 0 - - runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07', 123) - runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude waiting for permission\x07', 124) - - await waitForMobileSessionTabsEvents(events, 1) - expect(events).toEqual([ - expect.objectContaining({ - tabs: [ - expect.objectContaining({ - type: 'terminal', - agentStatus: expect.objectContaining({ - state: 'blocked', - terminalHandle: laptopTerminal.handle - }) - }) - ] - }) - ]) - - unsubscribe() - }) - - it('does not publish stale PTY-backed mobile agent status for Claude agents screens', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID - }) - events.length = 0 - - runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07', 123) - runtime.onPtyData('laptop-created-pty', '\x1b]0;claude agents\x07', 124) - - await waitForMobileSessionTabsEvents(events, 1) - expect(events[0]?.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - title: 'claude agents' - }) - ) - expect(events[0]?.tabs[0]).not.toHaveProperty('agentStatus') - - unsubscribe() - }) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts index 5a8fd703845..112a2fe60e2 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts @@ -435,4 +435,89 @@ describe('OrcaRuntimeService', () => { expect(getSession().terminalLayoutsByTabId['durable-tab']).toBeUndefined() expect(flushOrThrow).toHaveBeenCalledTimes(1) }) + + // Main-owned layouts restore a ready headless graph when the window closes. + it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)( + 'closes a paired session tab after the desktop window is gone', + async () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const closeTerminalTab = vi.fn(async () => undefined) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService( + withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }) + ) + runtime.setNotifier({ closeTerminal: vi.fn(), closeTerminalTab } as never) + runtime.setPtyController({ + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Durable', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'persisted-pty' + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer:paired-close', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: `host-tab::${HEADLESS_LEAF_ID}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `host-tab::${HEADLESS_LEAF_ID}`, + parentTabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + ptyId: 'persisted-pty', + title: 'Durable', + isActive: true + } + ] + } + ] + }) + runtime.registerPty('persisted-pty', TEST_WORKTREE_ID, null, { + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID + }) + + const closePaired = () => + runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab', { + reason: 'user', + clientNavigationId: 'device-a' + }) + runtime.markGraphUnavailable(1) + runtime.setNotifier(null) + runtime.attachWindow(2) + + await expect(closePaired()).rejects.toThrow('runtime_unavailable') + + runtime.markGraphUnavailable(2) + + await expect(closePaired()).resolves.toEqual({ closed: true, retirementConfirmed: true }) + expect(closeTerminalTab).not.toHaveBeenCalled() + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID] ?? []).toEqual([]) + expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() + } + ) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts index 2fa84eedaf6..2e7c650e71e 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts @@ -1,9 +1,9 @@ +import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' import { HEADLESS_LEAF_ID, @@ -15,214 +15,12 @@ import { makeWorkspaceSessionWithHeadlessTerminal, store } from './orca-runtime-test-fixtures.spec' -import { makePendingAgentTabActivationRuntime } from './orca-runtime-test-scenario-builders.spec' -import { trackRunningAgentLaunchPane } from '../../agent-launch/agent-launch-pane-attachment' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import './orca-runtime-test-scenario-builders.spec' +import '../../agent-launch/agent-launch-pane-attachment' +import '../../../shared/workspace-layout/stable-pane-id' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' describe('OrcaRuntimeService', () => { - it('briefly preserves abnormal SSH exits for paired pane recovery', async () => { - vi.useFakeTimers() - try { - vi.setSystemTime(new Date('2026-01-01T00:00:00Z')) - const runtime = new OrcaRuntimeService(store) - const ptyId = 'ssh:ssh-1@@pty-recover' - const tabId = 'host-tab' - runtime.registerPty(ptyId, TEST_WORKTREE_ID, 'ssh-1', { - tabId, - leafId: HEADLESS_LEAF_ID - }) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-with-ssh-pane', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: `${tabId}::${HEADLESS_LEAF_ID}`, - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: `${tabId}::${HEADLESS_LEAF_ID}`, - parentTabId: tabId, - leafId: HEADLESS_LEAF_ID, - ptyId, - title: 'Terminal', - isActive: true - } - ] - } - ] - }) - runtime.onPtyExit(ptyId, -1) - - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-with-ssh-pane', - snapshotVersion: 2, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([ - expect.objectContaining({ parentTabId: tabId, status: 'pending-handle' }) - ]) - - vi.advanceTimersByTime(30_001) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-with-ssh-pane', - snapshotVersion: 3, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([]) - } finally { - vi.useRealTimers() - } - }) - - it('briefly preserves an unregistered SSH pane while a restarted HUB rebuilds PTY state', async () => { - vi.useFakeTimers() - try { - vi.setSystemTime(new Date('2026-01-01T00:00:00Z')) - const runtime = new OrcaRuntimeService(store) - const ptyId = 'ssh:ssh-1@@pty-restart' - const tabId = 'host-tab' - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-restarted-hub', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: `${tabId}::${HEADLESS_LEAF_ID}`, - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: `${tabId}::${HEADLESS_LEAF_ID}`, - parentTabId: tabId, - leafId: HEADLESS_LEAF_ID, - ptyId, - title: 'Terminal', - isActive: true - } - ] - } - ] - }) - - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-restarted-hub', - snapshotVersion: 2, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([ - expect.objectContaining({ parentTabId: tabId, status: 'pending-handle' }) - ]) - - vi.advanceTimersByTime(30_001) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-restarted-hub', - snapshotVersion: 3, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([]) - } finally { - vi.useRealTimers() - } - }) - - it('hydrates a persisted SSH-owned pane when the restarted renderer has not published sessions', async () => { - const ptyId = 'ssh:ssh-1@@pty-persisted' - const sshSession = makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'host-tab', - ptyId, - worktreeId: TEST_WORKTREE_ID, - title: 'Persisted SSH Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: ptyId }) - } - }) - const localSession = getDefaultWorkspaceSession() - const remoteRepo = { ...store.getRepo(TEST_REPO_ID)!, connectionId: 'ssh-1' } - const getWorkspaceSession = vi.fn((hostId?: string | null) => - hostId === 'ssh:ssh-1' ? sshSession : localSession - ) - const runtime = new OrcaRuntimeService({ - ...store, - getRepos: () => [remoteRepo], - getRepo: (id: string) => (id === TEST_REPO_ID ? remoteRepo : undefined), - getWorkspaceSession - } as never) - expect(getWorkspaceSession).toHaveBeenCalledExactlyOnceWith('local') - getWorkspaceSession.mockClear() - - runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) - expect(getWorkspaceSession).toHaveBeenCalledTimes(2) - - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([ - expect.objectContaining({ - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - ptyId, - status: 'pending-handle' - }) - ]) - expect(getWorkspaceSession).toHaveBeenCalledWith('ssh:ssh-1') - }) - it('publishes a recovered SSH pane when its relay becomes ready after an empty restart replay', async () => { const ptyId = 'ssh:ssh-1@@pty-recovered' const sshSession = makeWorkspaceSessionWithHeadlessTerminal({ @@ -397,212 +195,4 @@ describe('OrcaRuntimeService', () => { vi.useRealTimers() } }) - - it('does not preserve a normally exited SSH shell for pane recovery', async () => { - const runtime = new OrcaRuntimeService(store) - const ptyId = 'ssh:ssh-1@@pty-normal-exit' - runtime.registerPty(ptyId, TEST_WORKTREE_ID, 'ssh-1', { - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID - }) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-normal-exit', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: `host-tab::${HEADLESS_LEAF_ID}`, - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: `host-tab::${HEADLESS_LEAF_ID}`, - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - ptyId, - title: 'Terminal', - isActive: true - } - ] - } - ] - }) - runtime.onPtyExit(ptyId, 0) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-normal-exit', - snapshotVersion: 2, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([]) - }) - - it('hydrates persisted serve-owned mobile session terminals while a renderer is attached', async () => { - const focusTerminal = vi.fn() - const spawn = vi.fn().mockResolvedValue({ id: 'serve-persisted-pty', isReattach: true }) - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'host-tab', - ptyId: 'serve-persisted-pty', - worktreeId: TEST_WORKTREE_ID, - title: 'Persisted Mobile Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'serve-persisted-pty' }) - } - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal, - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - electronMocks.BrowserWindow.fromId.mockReturnValue({ - isDestroyed: () => false, - webContents: { send: vi.fn() } - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-empty', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(listed.tabs).toEqual([ - expect.objectContaining({ - type: 'terminal', - id: `host-tab::${HEADLESS_LEAF_ID}`, - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - ptyId: 'serve-persisted-pty', - status: 'pending-handle' - }) - ]) - expect(listed.tabGroups?.[0]).toMatchObject({ - activeTabId: 'host-tab', - tabOrder: ['host-tab'] - }) - - const activated = await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') - - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - sessionId: 'serve-persisted-pty', - persistHostSessionBinding: true, - worktreeId: TEST_WORKTREE_ID - }) - ) - expect(focusTerminal).not.toHaveBeenCalled() - expect(activated.tabs[0]).toMatchObject({ - type: 'terminal', - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - status: 'ready' - }) - }) - - it('launches the pending agent when mobile activation materializes an agent tab', async () => { - const { runtime, spawn } = makePendingAgentTabActivationRuntime() - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - expect(listed.tabs[0]).toMatchObject({ - type: 'terminal', - launchAgent: 'claude', - status: 'pending-handle' - }) - - // #7587: notifyClients false models phone activation materializing a pending tab headlessly. - const activated = await runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - `host-tab::${HEADLESS_LEAF_ID}`, - undefined, - { notifyClients: false } - ) - - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - command: expect.stringContaining('claude'), - sessionId: 'serve-dead-pty', - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - worktreeId: TEST_WORKTREE_ID - }) - ) - expect(activated.tabs[0]).toMatchObject({ - type: 'terminal', - launchAgent: 'claude', - status: 'ready' - }) - }) - // Early launch tabs precede agent spawn; phone activation must not race the owning launch. - it('leaves a pending agent tab to the launch still starting in it', async () => { - const { runtime, spawn } = makePendingAgentTabActivationRuntime() - const running = trackRunningAgentLaunchPane({ - worktreeId: TEST_WORKTREE_ID, - paneKey: makePaneKey('host-tab', HEADLESS_LEAF_ID) - }) - try { - await runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - `host-tab::${HEADLESS_LEAF_ID}`, - undefined, - { notifyClients: false } - ) - expect(spawn).not.toHaveBeenCalled() - } finally { - running.finish({ kind: 'proceed' }) - } - }) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-targeted-agent-resume.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-targeted-agent-resume.spec.ts index e8026059f74..3f8ef42d770 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-targeted-agent-resume.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-targeted-agent-resume.spec.ts @@ -15,20 +15,11 @@ import { makeWorkspaceSessionWithHeadlessTerminal } from './orca-runtime-test-fixtures.spec' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { PtyProcessInfo } from '../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../providers/pty/process-info' import { deterministicAgentSessionUuid } from '../terminal/launch/runtime-agent-launch-resolution' import { deriveRemoteRuntimeTerminalCreateHandle } from '../terminal/identity/remote-runtime-terminal-create-identity' import type { RuntimePtyController } from '../terminal/lifecycle/runtime-pty-controller-contract' -import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { AgentSessionRecordStore } from '../agent-session/records/agent-session-record-store' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { - chooseSavedResumeFreshLaunch, - savedResumeResult -} from '../../ipc/pty/host-env/saved-resume-admission' +import { savedResumeResult } from '../../ipc/pty/host-env/saved-resume-admission' import { spawnedCommands, resumeSpawns } from './agent-resume-spawn-commands.test-fixture' const PANE_KEY = `host-tab:${HEADLESS_LEAF_ID}` @@ -58,19 +49,6 @@ function makeSleptWorkspace() { type Fixture = ReturnType -type WorkspaceScopeResolver = { - resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise -} - -function hasWorkspaceScopeResolver( - runtime: OrcaRuntimeService -): runtime is OrcaRuntimeService & WorkspaceScopeResolver { - return ( - 'resolveTerminalWorkspaceLaunchScope' in runtime && - typeof runtime.resolveTerminalWorkspaceLaunchScope === 'function' - ) -} - function sessionRow(paneKey: string, receivedAt = 0): AgentStatusIpcPayload { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resume guards read only paneKey, providerSession and the observation clocks. return { paneKey, providerSession: SESSION, receivedAt } as never @@ -144,67 +122,6 @@ function storedRecord(fixture: Fixture) { } describe('resumeAgentSessionInWorkspace', () => { - it.each(['live', 'worktree-sleep'] as const)( - 'releases a %s saved resume claim when actual admission creates a plain shell', - async (origin) => { - const fixture = makeSleptWorkspace() - const saved = storedRecord(fixture) - if (!saved) { - throw new Error('missing saved conversation') - } - saved.origin = origin - const chat = agentSessionRecordFixture( - agentSessionLeaseFixture({ - claimStatus: 'released', - ownerProcess: null, - reservedSpawnToken: null, - deathEvidence: { kind: 'exit-observed', detail: 'closed', observedAt: 1 } - }) - ) - chat.providerHandleChain[0]!.handle.nativeId = SESSION.id - let nativeOpen = true - const store: AgentSessionRecordStore = Object.create(AgentSessionRecordStore.prototype) - store.listConversations = () => [agentSessionConversationView(chat)] - store.getVisibleSessionTabIndex = () => ({ - present: true, - sessionIds: nativeOpen ? [chat.sessionId] : [] - }) - const effectiveCommands: (string | undefined)[] = [] - const { runtime, spawn, openOldPane, resume } = makeRuntime(fixture, { - spawn: async (args) => { - const admission = await chooseSavedResumeFreshLaunch( - { openAgentSessionRecordStore: async () => store }, - args, - null, - args - ) - effectiveCommands.push(args.command) - return { - id: effectiveCommands.length === 1 ? 'refused-shell' : 'resumed-C', - launchAgent: args.launchAgent, - launchConfig: args.launchConfig, - ...savedResumeResult(admission) - } - } - }) - await openOldPane() - expect(runtime.getTerminalLaunchResult('refused-shell')).toMatchObject({ - agentResumeRefused: 'chat-home', - savedResumeDecision: { agent: 'claude', providerSession: SESSION, verdict: 'chat-home' } - }) - expect(runtime.getTerminalLaunchResult('refused-shell')?.launchAgent).toBeUndefined() - expect(effectiveCommands).toEqual([undefined]) - nativeOpen = false - await expect(resume({ mutationId: 'after-native-close' })).resolves.toMatchObject({ - ok: true, - ptyId: 'resumed-C' - }) - expect(effectiveCommands[1]).toContain(SESSION.id) - expect(spawn).toHaveBeenCalledTimes(2) - expect(runtime.getTerminalLaunchResult('refused-shell')).toBeDefined() - } - ) - it('settles only fresh matching saved results and binds unproven or observed results until exit', async () => { for (const kind of [ 'matching', @@ -319,34 +236,6 @@ describe('resumeAgentSessionInWorkspace', () => { expect(send).not.toHaveBeenCalledWith('terminal:requestTabCreate', expect.anything()) }) - it('rechecks hook ownership when another resume settles during pane preflight', async () => { - const fixture = makeSleptWorkspace() - let rows: AgentStatusIpcPayload[] = [] - const { runtime, spawn, resume, openOldPane } = makeRuntime(fixture, { - rows: () => rows, - checkHookAgentPresence: async () => 'live' - }) - if (!hasWorkspaceScopeResolver(runtime)) { - throw new Error('missing resolver') - } - const resolveWorkspace = runtime.resolveTerminalWorkspaceLaunchScope.bind(runtime) - let first = true - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: async (selector: string) => { - if (first) { - first = false - const result = await resume() - if (result.ok) { - rows = [sessionRow(result.paneKey, Date.now() + 1)] - } - } - return resolveWorkspace(selector) - } - }) - await openOldPane() - expect(resumeSpawns(spawn)).toBe(1) - }) - it.each(['resume', 'old pane'] as const)( 'refuses the other resumer while the %s spawn is in flight', async (first) => { @@ -386,29 +275,6 @@ describe('resumeAgentSessionInWorkspace', () => { } ) - it.each([ - ['live', 1], - ['exited', 2] - ] as const)( - 'hands the session to the hook-store guard once the resumed pane reports it (%s)', - async (presence, expectedResumes) => { - const fixture = makeSleptWorkspace() - let rows: AgentStatusIpcPayload[] = [] - const { spawn, resume, openOldPane } = makeRuntime(fixture, { - rows: () => rows, - checkHookAgentPresence: async () => presence - }) - const result = await resume() - if (!result.ok) { - throw new Error(result.reason) - } - rows = [sessionRow(result.paneKey, Date.now())] - - await openOldPane() - expect(resumeSpawns(spawn)).toBe(expectedResumes) - } - ) - it('frees the session once the resumed agent reported, though it then exited to its shell', async () => { const fixture = makeSleptWorkspace() let rows: AgentStatusIpcPayload[] = [] @@ -481,38 +347,6 @@ describe('resumeAgentSessionInWorkspace', () => { }) describe('resumeAgentSessionInWorkspace retries, cancellation and a failed publication', () => { - it('reconciles the same request after its own hook arrives', async () => { - let rows: AgentStatusIpcPayload[] = [] - const terminalHandle = deriveRemoteRuntimeTerminalCreateHandle( - 'agent-session-resume', - TEST_WORKTREE_ID, - MUTATION_ID - ) - const { resume, spawn } = makeRuntime(makeSleptWorkspace(), { - rows: () => rows, - checkHookAgentPresence: async () => 'live', - listProcesses: async () => - spawn.mock.calls.length > 0 - ? [ - { - id: 'resumed-pty', - cwd: '', - title: 'claude', - terminalHandle, - worktreeId: TEST_WORKTREE_ID - } - ] - : [] - }) - const first = await resume() - if (!first.ok) { - throw new Error(first.reason) - } - rows = [sessionRow(first.paneKey, Date.now() + 1)] - await expect(resume()).resolves.toEqual(first) - expect(spawn).toHaveBeenCalledOnce() - }) - it('honors cancellation during create inventory lookup before dispatch', async () => { const controller = new AbortController() const { resume, spawn } = makeRuntime(makeSleptWorkspace(), { diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts index 0f6ccc37723..99842dfc587 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import './bind-first-pane.test-fixture' import '../terminal/layout/profile-session-store.test-fixture' import '../__fixtures__/main-layout-close-fixture' @@ -11,48 +11,6 @@ import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' import '../../../shared/worktree/host-qualified-identity' describe('OrcaRuntimeService', () => { - it('retires exited saved PTY bindings instead of publishing a pending ghost', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'tab-1::pane:1', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: 'tab-1::pane:1', - parentTabId: 'tab-1', - leafId: 'pane:1', - title: 'Terminal 1', - ptyId: 'daemon-pty-1', - isActive: true - } - ] - } - ] - }) - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - runtime.onPtyExit('daemon-pty-1', 0) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result).toMatchObject({ - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - }) - }) - it('keeps published mobile terminal handles usable across renderer graph epochs', async () => { const runtime = new OrcaRuntimeService(store) runtime.attachWindow(1) @@ -153,78 +111,4 @@ describe('OrcaRuntimeService', () => { tail: ['after graph sync'] }) }) - - it('activates mobile session tabs without focusing desktop clients when requested', async () => { - const focusTerminal = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal, - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'tab-1::pane:2', - activeTabType: 'terminal', - tabGroups: [{ id: 'group-1', activeTabId: 'tab-1', tabOrder: ['tab-1'] }], - tabs: [ - { - type: 'terminal', - id: 'tab-1::pane:1', - parentTabId: 'tab-1', - leafId: 'pane:1', - ptyId: 'pty-pane-1', - title: 'left', - isActive: false - }, - { - type: 'terminal', - id: 'tab-1::pane:2', - parentTabId: 'tab-1', - leafId: 'pane:2', - ptyId: 'pty-pane-2', - title: 'right', - isActive: true - } - ] - } - ] - }) - runtime.registerPty('pty-pane-1', TEST_WORKTREE_ID) - runtime.registerPty('pty-pane-2', TEST_WORKTREE_ID) - - const activated = await runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - 'tab-1::pane:1', - undefined, - { notifyClients: false } - ) - - expect(focusTerminal).not.toHaveBeenCalled() - expect(activated).toMatchObject({ - activeTabId: 'tab-1::pane:1', - activeTabType: 'terminal', - tabGroups: [expect.objectContaining({ id: 'group-1', activeTabId: 'tab-1' })] - }) - expect(activated.tabs).toEqual([ - expect.objectContaining({ id: 'tab-1::pane:1', isActive: true }), - expect.objectContaining({ id: 'tab-1::pane:2', isActive: false }) - ]) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts index b24d77ec8bb..6769e9ab3d2 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts @@ -3,13 +3,13 @@ import { vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../shared/constants' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' import { withDurableRuntimeStore, withRuntimePaneAdmission } from './runtime-durable-store-fixture' import { OrcaRuntimeService } from '../orca-runtime' import { committingSpawn } from './bind-first-pane.test-fixture' import type { RuntimeNotifier } from '../client/events/runtime-notifier-contract' -import type { PaneResumeOutcome } from '../../../shared/workspace-layout/workspace-layout-published' +import type { PaneResumeOutcome } from '../../../shared/workspace-layout/published-layout/workspace-layout-published' export const REPO = { id: 'repo-1', diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts index 106db82c488..94cacf7a6ab 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts @@ -16,7 +16,7 @@ import { import { getDefaultWorkspaceSession } from '../../../shared/constants' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' import { toComparableRelaySshPtyId } from '../../../shared/ssh-pty-id' import '../terminal/launch/spawned-pty-env-fixtures' @@ -79,16 +79,6 @@ function makeDeferred(): { promise: Promise; resolve: () => void } { return { promise, resolve } } -function makeStatusFrame(index: number, first: boolean): string { - const pad = '·'.repeat(60) - const rows = [ - `✻ 执行任务中… (esc to interrupt) [${index}] ${pad}`, - ` ⎿ 正在分析代码库结构与依赖关系,请稍候… ${pad}`, - ` ⎿ tokens: ${1000 + index * 137} · elapsed: ${index}s ${pad}` - ] - return `${first ? '' : '\x1b[2A'}\r${rows.map((row) => `\x1b[K${row}`).join('\r\n')}\r` -} - async function writeHeadless(emulator: HeadlessTerminal, data: string): Promise { await emulator.write(data) } @@ -112,23 +102,6 @@ async function parseHeadlessSnapshotLines( } } -async function referenceStatusFrameLines( - spawn: { cols: number; rows: number }, - resized: { cols: number; rows: number } -): Promise { - const truth = new HeadlessEmulator({ cols: spawn.cols, rows: spawn.rows }) - try { - await writeHeadless(truth, 'user@host % claude\r\n') - truth.resize(resized.cols, resized.rows) - for (let index = 0; index < 5; index += 1) { - await writeHeadless(truth, makeStatusFrame(index, index === 0)) - } - return visibleNonEmptyLines(truth) - } finally { - truth.dispose() - } -} - const TEST_WINDOW_ID = 1 // STA-517: inventory forwards its deadline; scope assertions accept any budget to avoid timing coupling. const LIST_PROVIDER_DEADLINE = expect.objectContaining({ deadlineMs: expect.any(Number) }) @@ -178,59 +151,6 @@ function isOriginMainBaseRefProbe(args: string[]): boolean { ) } -function antigravityReadyScreen(model = 'Gemini 3.5 Flash (High)'): string { - return [ - 'Antigravity CLI 1.0.3', - 'user@example.com (Antigravity Business)', - model, - '~/orca/workspaces/orca/agy-dispatch-issue', - '>' - ].join('\n') -} - -function antigravityPromptBeforeModelReadyScreen(model = 'Gemini 3.5 Flash (High)'): string { - return [ - 'Antigravity CLI 1.0.3', - 'user@example.com', - '~/orca/workspaces/orca/agy-dispatch-issue', - '', - '', - '', - '', - '>', - '', - '? for shortcuts', - `\t\t ${model}`, - '~/orca/workspaces/orca/agy-dispatch-issue', - '', - model, - ' (Antigravity Business)' - ].join('\n') -} - -// Captured Cursor 2026.07 idle screen: readiness keys on →, never its changing placeholder. -function cursorReadyScreen(): string { - return [ - 'Cursor Agent', - 'v2026.07.09-a3815c0', - 'Tip: Use /plan to plan execution and reach the right outcome faster.', - '→ Plan, search, build anything', - 'Composer 2.5 Fast Run Everything', - '~/Documents/projects/AutoGenie · main' - ].join('\n') -} - -function cursorBusyScreen(): string { - return [ - 'Cursor Agent', - 'v2026.07.09-a3815c0', - '⠰⠳ Thinking 28.61k tokens', - '→ Plan, search, build anything', - 'Composer 2.5 Fast Run Everything', - '~/Documents/projects/AutoGenie · main' - ].join('\n') -} - function setInMemoryOrchestrationMessages( runtime: RuntimeService, db: InMemoryOrchestrationMessages @@ -724,14 +644,14 @@ export { LIST_PROVIDER_DEADLINE, RESTORED_AUTHORITY_TOKEN } export { RESTORED_AUTHORITY_TOKEN_HASH, TEST_FOLDER_PROJECT_GROUP_ID, TEST_FOLDER_WORKSPACE_ID } export { TEST_FOLDER_WORKSPACE_KEY, TEST_FOLDER_WORKSPACE_PATH, TEST_REPO_ID, TEST_REPO_PATH } export { TEST_WINDOW_ID, TEST_WORKTREE_ID, TEST_WORKTREE_PATH, UUID_RE } -export { antigravityPromptBeforeModelReadyScreen, antigravityReadyScreen, bindSinglePtyRun } +export { bindSinglePtyRun } export { createExplicitAgentStatusHarness, createFolderWorkspaceRuntimeStore, createRuntime } -export { createRuntimeWithSshLease, createStaleRuntimeWorktreeStore, cursorBusyScreen } -export { cursorReadyScreen, deferred, expectStablePaneKeyEnv, isOriginMainBaseRefProbe } +export { createRuntimeWithSshLease, createStaleRuntimeWorktreeStore } +export { deferred, expectStablePaneKeyEnv, isOriginMainBaseRefProbe } export { isLocalBranchCatalogQuery } export { makeDeferred, makeFolderProjectGroup, makeFolderWorkspace, makeHeadlessTerminalLayout } -export { makeRpcRequest, makeRuntimeStoreWithWorkspaceSession, makeStatusFrame } +export { makeRpcRequest, makeRuntimeStoreWithWorkspaceSession } export { makeWorkspaceSessionWithHeadlessTerminal, makeWorktreeInfo, makeWorktreeMeta } -export { parseHeadlessSnapshotLines, pendingMailPointerRepoints, referenceStatusFrameLines } +export { parseHeadlessSnapshotLines, pendingMailPointerRepoints } export { renderGateCapMs, setInMemoryOrchestrationMessages, store, syncSinglePty } export { visibleNonEmptyLines, withPlatform, writeHeadless } diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts index 9b03263f197..f39fee39101 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts @@ -1,4 +1,7 @@ import './runtime-test-module-registration.spec' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { MOCK_GIT_WORKTREES, addGitHubIssueCommentMock, @@ -85,7 +88,7 @@ import { _resetTerminalViewAttributesForTest } from '../terminal/view/terminal-v import { addSparseWorktree } from '../../git/worktrees/creation/worktree-sparse-add' import { addWorktree } from '../../git/worktrees/creation/worktree-add' import { advertisedUrlWatcher } from '../../ports/advertised-url-watcher' -import { afterAll, afterEach, beforeEach, vi, type MockInstance } from 'vitest' +import { afterAll, afterEach, beforeAll, beforeEach, vi, type MockInstance } from 'vitest' import { initOrcaProfilePaths } from '../../orca-profiles/profile-storage-paths' import { stopStructuredAgentSessionRuntime } from '../agent-session/structured-agent-session-runtime' import { assertWorktreeCleanForRemoval } from '../../git/worktrees/removal/worktree-removal-preflight' @@ -128,6 +131,7 @@ import { _settlePendingWorktreeRemovalsForTests } from '../../workspaces/removal/worktree-background-removal' import { _resetCanonicalRepoKeyCacheForTests } from '../../git/repositories/canonical-repo-key' +import { setWorktreeRemovalRecordsDirectory } from '../../workspaces/removal/worktree-removal-table' awaitBackgroundRemovalsInRuntimeTests(runtimeMockOrcaRuntimeService.prototype) commitFakeSpawnsInRuntimeTests(runtimeMockOrcaRuntimeService.prototype) @@ -135,6 +139,7 @@ commitFakeSpawnsInRuntimeTests(runtimeMockOrcaRuntimeService.prototype) function resetRuntimeTestMocks(): void { _resetCanonicalRepoKeyCacheForTests() _resetPendingWorktreeRemovalsForTests() + setWorktreeRemovalRecordsDirectory(removalRecordsDirectory) // Chromium commands install only at Electron entry; Node hosts must refuse browser RPCs without them. setRuntimeBrowserCommandsFactory((host) => new RuntimeBrowserCommands(host), { clientHosting: true @@ -378,6 +383,11 @@ function resetRuntimeTestMocks(): void { let registrationSpy: | MockInstance | undefined +let removalRecordsDirectory = '' + +beforeAll(async () => { + removalRecordsDirectory = await mkdtemp(join(tmpdir(), 'orca-runtime-removal-records-')) +}) beforeEach(() => { resetRuntimeTestMocks() @@ -405,4 +415,5 @@ export { resetRuntimeTestMocks } afterAll(async () => { await stopStructuredAgentSessionRuntime() + await rm(removalRecordsDirectory, { recursive: true, force: true }) }) diff --git a/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts b/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts index df3da7ac847..6fa17985ebd 100644 --- a/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts +++ b/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts @@ -1,38 +1,11 @@ import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { - applyAgentStatusHooksEnabledMock, - reconcileClaudeAgentViewMock -} from '../orca-runtime-test-mocks/setup.spec' +import { applyAgentStatusHooksEnabledMock } from '../orca-runtime-test-mocks/setup.spec' import { deferred, store } from './orca-runtime-test-fixtures.spec' -import { RuntimeClientSettingsController } from '../client/settings/runtime-client-settings' +import '../client/settings/runtime-client-settings' describe('OrcaRuntimeService', () => { - it.each([true, false])( - 'awaits navigation-only updates from paired clients (%s)', - async (enabled) => { - let settings = { ...store.getSettings(), claudeSubagentNavigationEnabled: !enabled } - const controller = new RuntimeClientSettingsController({ - getSettings: () => settings, - updateSettings: (updates) => { - settings = { ...settings, ...updates } - } - }) - const gate = deferred() - reconcileClaudeAgentViewMock.mockImplementationOnce(() => gate.promise) - const complete = vi.fn() - const pending = controller.update({ claudeSubagentNavigationEnabled: enabled }).then(complete) - await vi.waitFor(() => - expect(reconcileClaudeAgentViewMock).toHaveBeenLastCalledWith(settings) - ) - expect(complete).not.toHaveBeenCalled() - gate.resolve() - await pending - expect(complete).toHaveBeenCalledOnce() - } - ) - it('serializes paired-client hook reconciliation and reads current settings', async () => { let settings = { ...store.getSettings(), diff --git a/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts b/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts index 24c275f35a4..eaac74df097 100644 --- a/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts +++ b/src/main/runtime/orca-runtime-tests/project-setup-folder-remote-identity.spec.ts @@ -123,38 +123,6 @@ describe('OrcaRuntimeService project setup of an existing folder (#30663)', () = }) }) -describe('explicit fork project setup with deferred ordinary metadata', () => { - it.each([ - ['github:acme/repo-a', { owner: 'acme', repo: 'repo-a' }], - ['github:me/repo-a', { owner: 'me', repo: 'repo-a' }] - ] as const)( - 'preserves selected project %s when a hosted parent is known', - async (projectId, upstream) => { - const repos: Repo[] = [] - parentProbe.mockResolvedValue({ - upstream: { owner: 'acme', repo: 'repo-a' }, - origin: { owner: 'me', repo: 'repo-a' } - }) - const runtime = createRuntime(repos) - await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { - const result = await runtime.setupProjectExistingFolder({ - projectId, - projectProviderIdentity: { provider: 'github', ...upstream }, - hostId: 'runtime:env-1', - path, - kind: 'git' - }) - expect(result.project.id).toBe(projectId) - expect(result.repo.upstream).toEqual(upstream) - expect( - projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId - ).toBe(projectId) - expect(parentProbe).toHaveBeenCalledTimes(1) - }) - } - ) -}) - it('completes parent-selected setup while unrelated background metadata remains pending', async () => { await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { const repos: Repo[] = [ @@ -243,70 +211,6 @@ it.each([false, true])( } ) -it.each([ - [ - 'older automatic avatar', - { - type: 'image', - source: 'github', - src: 'https://ghe.corp.example/old.png?size=64', - label: 'old/repo-a' - }, - { host: 'ghe.corp.example', owner: 'new', repo: 'repo-a' } - ], - [ - 'protected image', - { - type: 'image', - source: 'file', - src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=' - }, - null - ] -] as const)( - 'links a current enterprise remote despite unavailable metadata and a retained %s', - async (_label, repoIcon, upstream) => { - await withGitFolder({ origin: 'https://ghe.corp.example/new/repo-a.git' }, async (path) => { - const repos: Repo[] = [ - { - id: 'selected', - path: realpathSync(path), - displayName: 'repo-a', - badgeColor: 'blue', - addedAt: 1, - kind: 'git', - executionHostId: 'runtime:env-1', - gitRemoteIdentity: { - canonicalKey: 'ghe.corp.example/old/repo-a', - remoteName: 'origin', - remoteUrl: 'https://ghe.corp.example/old/repo-a.git' - }, - repoIcon - } - ] - const runtime = createRuntime(repos) - const result = await runtime.setupProjectExistingFolder({ - projectId: 'github:ghe.corp.example/new/repo-a', - projectProviderIdentity: { - provider: 'github', - host: 'ghe.corp.example', - owner: 'new', - repo: 'repo-a' - }, - hostId: 'runtime:env-1', - path, - kind: 'git' - }) - expect(result.project.id).toBe('github:ghe.corp.example/new/repo-a') - expect(repos[0].upstream).toEqual(upstream) - expect(repos[0].repoIcon).toEqual(repoIcon) - expect( - projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId - ).toBe('github:ghe.corp.example/new/repo-a') - }) - } -) - it('retains matching null authority when a nonfork result settles during setup', async () => { await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { const repos: Repo[] = [] diff --git a/src/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts index 94c570fdeb6..bd2ad8b3888 100644 --- a/src/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/repository-project-operations-part-02.spec.ts @@ -8,7 +8,7 @@ import { OrcaRuntimeService } from '../orca-runtime' import { clearSubmodulePathsCacheForTests, listSubmodulePaths -} from '../../git/source-control/submodule-paths' +} from '../../git/source-control/submodules/submodule-paths' import { execFileSync } from 'node:child_process' import '../orca-runtime-test-mocks/setup.spec' import { join } from 'node:path' @@ -24,33 +24,6 @@ async function mkdtempReal(prefix: string): Promise { } describe('OrcaRuntimeService', () => { - it('creates a missing runtime parent before creating the project directory', async () => { - const added: Record[] = [] - const createStore = { - ...store, - getRepos: () => [...added] as never, - addRepo: (repo: Record) => { - added.push(repo) - }, - getRepo: (id: string) => added.find((repo) => repo.id === id) as never - } - const runtime = new OrcaRuntimeService(createStore as never) - const tempRoot = await mkdtempReal(join(tmpdir(), 'orca-runtime-create-parent-')) - const parentDir = join(tempRoot, 'orca', 'projects') - try { - const result = await runtime.createRepo(parentDir, 'first-project', 'folder') - if ('error' in result) { - throw new Error(result.error) - } - - expect((await lstat(parentDir)).isDirectory()).toBe(true) - expect((await lstat(join(parentDir, 'first-project'))).isDirectory()).toBe(true) - expect(result).toHaveProperty('repo.path', join(parentDir, 'first-project')) - } finally { - await rm(tempRoot, { recursive: true, force: true }) - } - }) - it('drops a same-path negative submodule cache before runtime cloneRepo', async () => { const spawnSpy = vi.spyOn(gitSpawn, 'gitSpawnAfterWindowsEnvironmentReady') const destination = await mkdtempReal(join(tmpdir(), 'orca-runtime-reclone-')) diff --git a/src/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts b/src/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts deleted file mode 100644 index c89a500654f..00000000000 --- a/src/main/runtime/orca-runtime-tests/repository-project-operations.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import '../../git/command-runner/git-spawn' -import { describe, expect, it } from 'vitest' -import { realpath, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import '../../project-groups/folder-workspace-path-status' -import './runtime-test-module-registration.spec' -import '../../../shared/repo-badge-color' -import 'node:events' -import { OrcaRuntimeService } from '../orca-runtime' -import 'node:child_process' -import '../orca-runtime-test-mocks/setup.spec' -import { join, win32 } from 'node:path' -import 'node:fs' -import '../../../shared/project-host-setup-projection' -import { tmpdir } from 'node:os' -import { store } from './orca-runtime-test-fixtures.spec' - -// Clone and create register resolved paths (macOS tmpdir is a /var symlink). -async function mkdtempReal(prefix: string): Promise { - return realpath(await mkdtemp(prefix)) -} - -describe('OrcaRuntimeService', () => { - it('browses runtime server directories before projects are added', async () => { - const tempRoot = await mkdtempReal(join(tmpdir(), 'orca-runtime-browse-')) - try { - await mkdir(join(tempRoot, 'zeta')) - await mkdir(join(tempRoot, 'alpha')) - await writeFile(join(tempRoot, 'readme.md'), '# Readme\n') - const runtime = new OrcaRuntimeService(store) - - const result = await runtime.browseServerDir(tempRoot) - - expect(result.resolvedPath).toBe(tempRoot) - expect(result.pathFlavor).toBe(process.platform === 'win32' ? 'win32' : 'posix') - expect(result.entries).toEqual([ - { name: 'alpha', isDirectory: true, isSymlink: false }, - { name: 'zeta', isDirectory: true, isSymlink: false }, - { name: 'readme.md', isDirectory: false, isSymlink: false } - ]) - } finally { - await rm(tempRoot, { recursive: true, force: true }) - } - }) - - it.runIf(process.platform === 'win32')('lists drive roots for a server-root browse', async () => { - const runtime = new OrcaRuntimeService(store) - - const result = await runtime.browseServerDir('/') - - expect(result.resolvedPath).toBe('/') - expect(result.pathFlavor).toBe('win32') - expect(result.entries).toContainEqual({ - name: win32.parse(tmpdir()).root.toUpperCase(), - isDirectory: true, - isSymlink: false - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts b/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts index 3b1fe262b57..82f00edb76e 100644 --- a/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts @@ -6,7 +6,7 @@ import { withdrawPaneFromSession, type PaneLayoutChange, type TerminalPaneAdmission -} from '../../persistence/terminal-topology/terminal-pane-admission' +} from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { CommandOf, LayoutRefusalCode diff --git a/src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec.ts b/src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec.ts index fa7c16744df..bfd9fcd3fd7 100644 --- a/src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec.ts +++ b/src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec.ts @@ -27,7 +27,7 @@ import '../../git/worktrees/catalog/worktree-scan-cache' import '../../git/worktrees/removal/worktree-removal' import '../workspaces/removal/worktree-teardown' import '../workspaces/removal/worktree-teardown-deadline' -import '../../git/source-control/submodule-paths' +import '../../git/source-control/submodules/submodule-paths' import '../../workspace-hooks/hooks' import '../../../shared/orca-yaml' import '../../workspace-hooks/worktree-runner-script' @@ -56,7 +56,7 @@ import '../../../shared/agent-launch/startup/agent-prompt-injection' import '../../../shared/clipboard-text' import '../../../shared/project-host-setup-projection' import '../../memory/pty-registry' -import '../../providers/pty-process-inspection' +import '../../providers/pty/process-inspection' import '../../workspaces/catalog/worktree-path-comparison-key' import '../../workspaces/removal/local-worktree-filesystem' import '../../../shared/constants' diff --git a/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts b/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts index 3aec8eb3e3c..35af315e20c 100644 --- a/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts @@ -1,7 +1,7 @@ // Apply layout record patches to plain session maps as Store does, including main-owned chat tabs. import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' export function layoutApplyOn( diff --git a/src/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts b/src/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts deleted file mode 100644 index 79f145c4b86..00000000000 --- a/src/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle.spec.ts +++ /dev/null @@ -1,97 +0,0 @@ -import '../../git/command-runner/git-exec-file' -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { addWorktree } from '../../git/worktrees/creation/worktree-add' -import { - computeWorktreePathMock, - ensurePathWithinWorkspaceMock -} from '../orca-runtime-test-mocks/setup.spec' -import '../../git/refs/resolution/repo-branch-conflict' -import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache' -import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' -import type { WorkspaceLineage } from '../../../shared/worktree/lineage-types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { - TEST_FOLDER_WORKSPACE_KEY, - TEST_REPO_ID, - createFolderWorkspaceRuntimeStore, - makeWorktreeMeta, - store -} from './orca-runtime-test-fixtures.spec' -import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' - -describe('OrcaRuntimeService', () => { - it('refuses an SSH-backed create for mobile/runtime callers instead of creating locally', async () => { - vi.mocked(listWorktrees).mockClear() - vi.mocked(addWorktree).mockClear() - const remoteStore = { - ...store, - getRepos: () => [ - { - id: TEST_REPO_ID, - path: '/remote/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1, - connectionId: 'ssh-1' - } - ] - } - const runtime = new OrcaRuntimeService(remoteStore as never) - - await expect( - runtime.createManagedWorktree({ repoSelector: TEST_REPO_ID, name: 'mobile-feature' }) - ).rejects.toThrow(SshHostNotServedError) - - expect(addWorktree).not.toHaveBeenCalled() - expect(listWorktrees).not.toHaveBeenCalled() - }) - - // The same parent selection must keep manual cleanup semantics across hosts. - it('records an app-selected parent workspace as a manual action', async () => { - vi.mocked(addWorktree).mockClear() - const created = { - path: '/tmp/workspaces/manual-child', - head: 'def', - branch: 'refs/heads/manual-child', - isBare: false, - isMainWorktree: false - } - const childId = `${TEST_REPO_ID}::${created.path}` - const metaById: Record = {} - const runtimeStore = { - ...createFolderWorkspaceRuntimeStore(), - getAllWorktreeMeta: () => metaById, - getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], - setWorktreeMeta: ({ id: worktreeId }: HostWorktreeTarget, meta: Partial) => { - metaById[worktreeId] = { ...(metaById[worktreeId] ?? makeWorktreeMeta()), ...meta } - return metaById[worktreeId] - }, - setFolderParentLineage: vi.fn( - (_target: HostWorktreeTarget, lineage: WorkspaceLineage) => lineage - ) - } - computeWorktreePathMock.mockReturnValue(created.path) - ensurePathWithinWorkspaceMock.mockImplementation((pathValue: string) => pathValue) - vi.mocked(listWorktrees).mockResolvedValueOnce([created]) - const runtime = new OrcaRuntimeService(runtimeStore as never) - - const result = await runtime.createManagedWorktree({ - repoSelector: TEST_REPO_ID, - name: 'manual-child', - baseBranch: 'origin/main', - lineage: { - parentWorkspace: TEST_FOLDER_WORKSPACE_KEY, - parentWorkspaceOrigin: 'manual' - } - }) - - expect(result.workspaceLineage).toMatchObject({ - childWorkspaceKey: `worktree:${childId}`, - parentWorkspaceKey: TEST_FOLDER_WORKSPACE_KEY, - origin: 'manual', - capture: { source: 'active-workspace', confidence: 'explicit' } - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-05.spec.ts deleted file mode 100644 index 5e6db3e3f8e..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-05.spec.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { registerLivePty } from './bind-first-pane.test-fixture' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import 'node:path' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import 'node:fs/promises' -import 'node:os' -import { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - makeHeadlessTerminalLayout, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal, - store -} from './orca-runtime-test-fixtures.spec' -import { spawnedPtyEnv } from '../terminal/launch/spawned-pty-env-fixtures' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' - -describe('OrcaRuntimeService', () => { - it.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)( - 'returns the exact pre-minted leaf for concurrent renderer-backed splits, each started by main', - async () => { - const tabId = 'tab-concurrent-splits' - const sourceLeafId = HEADLESS_LEAF_ID - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: tabId, - ptyId: 'pty-source', - worktreeId: TEST_WORKTREE_ID, - title: 'shell', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - [tabId]: makeHeadlessTerminalLayout({ [sourceLeafId]: 'pty-source' }) - } - }) - ) - const splitTerminal = vi.fn() - const spawn = vi.fn(async (args: { leafId?: string }) => ({ id: `pty-${args.leafId}` })) - const runtime = new OrcaRuntimeService(runtimeStore) - runtime.setNotifier({ splitTerminal } as never) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'shell', - activeLeafId: sourceLeafId, - layout: null - } - ], - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: sourceLeafId, - paneRuntimeId: 1, - ptyId: 'pty-source', - paneTitle: null - } - ] - }) - registerLivePty(runtime, 'pty-source', TEST_WORKTREE_ID, null, { - tabId, - leafId: sourceLeafId - }) - const sourceHandle = runtime.getTerminalHandleForPaneKey(makePaneKey(tabId, sourceLeafId)) - expect(sourceHandle).not.toBeNull() - - const [horizontal, vertical] = await Promise.all([ - runtime.splitTerminal(sourceHandle!, { direction: 'horizontal' }), - runtime.splitTerminal(sourceHandle!, { direction: 'vertical' }) - ]) - - expect(splitTerminal).not.toHaveBeenCalled() - expect(horizontal.leafId).not.toBe(vertical.leafId) - const leafIds = collectLeafIds(getSession().terminalLayoutsByTabId[tabId]?.root) - expect(leafIds).toEqual( - expect.arrayContaining([sourceLeafId, horizontal.leafId, vertical.leafId]) - ) - for (const split of [horizontal, vertical]) { - expect(split.tabId).toBe(tabId) - const leafId = split.leafId ?? '' - const call = spawn.mock.calls.find(([args]) => args.leafId === leafId) - expect(spawnedPtyEnv(call?.[0]).ORCA_PANE_KEY).toBe(makePaneKey(tabId, leafId)) - } - expect(spawn).toHaveBeenCalledTimes(2) - } - ) - - it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)( - 'returns the exact pre-minted leaf for concurrent renderer-backed splits', - async () => { - const tabId = 'tab-concurrent-splits' - const sourceLeafId = '11111111-1111-4111-8111-111111111111' - const splitTerminal = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setNotifier({ splitTerminal } as never) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'shell', - activeLeafId: sourceLeafId, - layout: null - } - ], - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: sourceLeafId, - paneRuntimeId: 1, - ptyId: 'pty-source', - paneTitle: null - } - ] - }) - const sourceHandle = runtime.getTerminalHandleForPaneKey(makePaneKey(tabId, sourceLeafId)) - expect(sourceHandle).not.toBeNull() - - const horizontal = runtime.splitTerminal(sourceHandle!, { direction: 'horizontal' }) - const vertical = runtime.splitTerminal(sourceHandle!, { direction: 'vertical' }) - await vi.waitFor(() => expect(splitTerminal).toHaveBeenCalledTimes(2)) - const horizontalLeafId = splitTerminal.mock.calls.find( - (call) => call[2]?.direction === 'horizontal' - )?.[2]?.newLeafId - const verticalLeafId = splitTerminal.mock.calls.find( - (call) => call[2]?.direction === 'vertical' - )?.[2]?.newLeafId - expect(horizontalLeafId).toEqual(expect.any(String)) - expect(verticalLeafId).toEqual(expect.any(String)) - expect(horizontalLeafId).not.toBe(verticalLeafId) - - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'shell', - activeLeafId: verticalLeafId, - layout: null - } - ], - // Reverse publication order so a first-new-leaf heuristic would swap the receipts. - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: verticalLeafId!, - paneRuntimeId: 3, - ptyId: 'pty-vertical', - paneTitle: null - }, - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: horizontalLeafId!, - paneRuntimeId: 2, - ptyId: 'pty-horizontal', - paneTitle: null - }, - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: sourceLeafId, - paneRuntimeId: 1, - ptyId: 'pty-source', - paneTitle: null - } - ] - }) - - await expect(horizontal).resolves.toMatchObject({ leafId: horizontalLeafId }) - await expect(vertical).resolves.toMatchObject({ leafId: verticalLeafId }) - } - ) - - it('keeps a persisted split when mounted renderer adoption rejects', async () => { - const tabId = 'persisted-mounted-tab' - const ptyId = 'persisted-mounted-pty' - const splitPtyId = 'persisted-mounted-split-pty' - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: tabId, - ptyId, - worktreeId: TEST_WORKTREE_ID, - title: 'Persisted terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - [tabId]: makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: ptyId }) - } - }) - ) - const revealTerminalSession = vi.fn().mockRejectedValue(new Error('renderer rejected')) - const kill = vi.fn(() => true) - let resolveSpawn!: (result: { id: string }) => void - const spawn = vi.fn( - (_args: unknown) => - new Promise<{ id: string }>((resolve) => { - resolveSpawn = resolve - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setPtyController({ - spawn, - write: () => true, - kill, - getForegroundProcess: async () => null - }) - runtime.setNotifier({ revealTerminalSession } as never) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - runtime.registerPty(ptyId, TEST_WORKTREE_ID, null, { - tabId, - leafId: HEADLESS_LEAF_ID, - incarnationId: 'live-source-incarnation' - }) - const internals = runtime as unknown as { - issuePtyHandle: (pty: unknown) => string - ptysById: Map - } - const handle = internals.issuePtyHandle(internals.ptysById.get(ptyId)) - const split = runtime.splitTerminal(handle, { direction: 'horizontal' }) - await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce()) - const splitSpawn = spawn.mock.calls[0]?.[0] as - | { expectedSourceBinding?: { incarnationId?: string } } - | undefined - // An unsaved incarnation cannot satisfy the store's persisted-binding fence. - expect(splitSpawn?.expectedSourceBinding).not.toHaveProperty('incarnationId') - - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'Persisted terminal', - activeLeafId: HEADLESS_LEAF_ID, - layout: { type: 'leaf', leafId: HEADLESS_LEAF_ID } - } - ], - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: HEADLESS_LEAF_ID, - paneRuntimeId: 1, - ptyId - } - ] - }) - resolveSpawn({ id: splitPtyId }) - - await expect(split).resolves.toMatchObject({ - tabId, - handle: expect.stringMatching(/^term_/) - }) - - expect(revealTerminalSession).toHaveBeenCalledOnce() - expect(kill).not.toHaveBeenCalled() - expect(getSession().terminalLayoutsByTabId[tabId]?.root).toMatchObject({ - type: 'split', - direction: 'horizontal' - }) - }) - - it('rejects a projected split retired during spawn before publishing the new pane', async () => { - let resolveSplitSpawn!: (result: { id: string }) => void - const spawn = vi - .fn() - .mockResolvedValueOnce({ id: 'projected-source-pty' }) - .mockImplementationOnce( - () => - new Promise<{ id: string }>((resolve) => { - resolveSplitSpawn = resolve - }) - ) - const kill = vi.fn(() => true) - const { runtimeStore, setSession } = makeRuntimeStoreWithWorkspaceSession( - getDefaultWorkspaceSession() - ) - const runtime = new OrcaRuntimeService(runtimeStore) - runtime.setPtyController({ - spawn, - write: () => true, - kill, - getForegroundProcess: async () => null - }) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - const split = runtime.splitTerminal(handle, { direction: 'vertical' }) - await vi.waitFor(() => expect(spawn).toHaveBeenCalledTimes(2)) - - runtime['mobileSessionTabsByWorktree'].delete(TEST_WORKTREE_ID) - setSession(getDefaultWorkspaceSession()) - resolveSplitSpawn({ id: 'retired-projected-split-pty' }) - - await expect(split).rejects.toThrow('terminal_split_source_not_found') - expect(kill).toHaveBeenCalledWith('retired-projected-split-pty') - expect(runtime['mobileSessionTabsByWorktree'].has(TEST_WORKTREE_ID)).toBe(false) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts index e6d67baf6f9..881039e085a 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts @@ -1,41 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - antigravityPromptBeforeModelReadyScreen, - store, - syncSinglePty -} from './orca-runtime-test-fixtures.spec' +import { TEST_WORKTREE_ID, TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('observes setup command completion without waiting for its interactive shell to exit', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-setup' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - ;( - runtime as unknown as { setupCompletionTokenByPtyId: Map } - ).setupCompletionTokenByPtyId.set('pty-setup', 'token-live') - - const waiting = runtime.waitForSetupTerminalCompletion(handle) - runtime.onPtyData( - 'pty-setup', - 'setup failed\r\n__ORCA_SETUP_COMPLETE__:token-live:17\r\nPS>', - 100 - ) - - await expect(waiting).resolves.toEqual({ exitCode: 17 }) - await expect(runtime.readTerminal(handle)).resolves.toMatchObject({ status: 'running' }) - }) - it('replays fast setup completion emitted before its observer is registered', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ @@ -59,84 +27,6 @@ describe('OrcaRuntimeService', () => { await expect(runtime.waitForSetupTerminalCompletion(handle)).resolves.toEqual({ exitCode: 0 }) }) - it('falls back to setup terminal exit when no completion signal is available', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-legacy-setup' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - - const waiting = runtime.waitForSetupTerminalCompletion(handle) - runtime.onPtyExit('pty-legacy-setup', 9) - - await expect(waiting).resolves.toEqual({ exitCode: 9 }) - }) - - it('cancels setup completion observation when the caller aborts', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-cancelled-setup' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - ;( - runtime as unknown as { setupCompletionTokenByPtyId: Map } - ).setupCompletionTokenByPtyId.set('pty-cancelled-setup', 'token-cancelled') - const unsubscribe = vi.fn() - vi.spyOn(runtime, 'subscribeToTerminalData').mockReturnValue(unsubscribe) - const controller = new AbortController() - - const waiting = runtime.waitForSetupTerminalCompletion(handle, controller.signal) - expect(runtime.subscribeToTerminalData).toHaveBeenCalledWith( - 'pty-cancelled-setup', - expect.any(Function) - ) - - const reason = new Error('cancelled') - controller.abort(reason) - - await expect(waiting).rejects.toBe(reason) - expect(unsubscribe).toHaveBeenCalledOnce() - }) - - it('keeps observing after an uncertain setup terminal status', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-uncertain-setup' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - ;( - runtime as unknown as { setupCompletionTokenByPtyId: Map } - ).setupCompletionTokenByPtyId.set('pty-uncertain-setup', 'token-uncertain') - vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ - handle, - condition: 'exit', - satisfied: false, - status: 'unknown', - exitCode: null - }) - - const waiting = runtime.waitForSetupTerminalCompletion(handle) - await Promise.resolve() - runtime.onPtyData('pty-uncertain-setup', '__ORCA_SETUP_COMPLETE__:token-uncertain:0\r\n', 100) - - await expect(waiting).resolves.toEqual({ exitCode: 0 }) - }) - it('drops retained PTY transcript memory when a background terminal exits', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ @@ -223,149 +113,6 @@ describe('OrcaRuntimeService', () => { }) }) - it('keeps retained PTY transcript memory when controller refresh omits a record', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - runtime.registerPty('daemon-pty-1', TEST_WORKTREE_ID) - runtime.onPtyData('daemon-pty-1', 'still live\npartial', 100) - - await runtime.listTerminals() - - const pty = ( - runtime as unknown as { - ptysById: Map< - string, - { - connected: boolean - tailBuffer: string[] - tailPartialLine: string - tailLinesTotal: number - } - > - } - ).ptysById.get('daemon-pty-1') - expect(pty).toMatchObject({ - connected: false, - tailBuffer: ['still live'], - tailPartialLine: 'partial', - tailLinesTotal: 1 - }) - }) - - it('keeps retained PTY transcript memory when controller refresh times out', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: () => new Promise(() => {}) - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - runtime.registerPty('daemon-pty-1', TEST_WORKTREE_ID) - runtime.onPtyData('daemon-pty-1', 'still live\npartial', 100) - - const terminals = runtime.listTerminals() - await vi.advanceTimersByTimeAsync(3_000) - await terminals - - const pty = ( - runtime as unknown as { - ptysById: Map< - string, - { - connected: boolean - tailBuffer: string[] - tailPartialLine: string - tailLinesTotal: number - } - > - } - ).ptysById.get('daemon-pty-1') - expect(pty).toMatchObject({ - connected: true, - tailBuffer: ['still live'], - tailPartialLine: 'partial', - tailLinesTotal: 1 - }) - } finally { - vi.useRealTimers() - } - }) - - it('resolves tui-idle for adopted background PTY handles from the renderer title', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-bg', - worktreeId: TEST_WORKTREE_ID, - title: 'Codex ready', - activeLeafId: 'pane-bg', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-bg', - worktreeId: TEST_WORKTREE_ID, - leafId: 'pane-bg', - paneRuntimeId: 1, - ptyId: 'pty-bg', - paneTitle: null - } - ] - }) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - status: 'running' - }) - }) - - it('resolves live-leaf tui-idle from an OpenCode native title', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - syncSinglePty(runtime, 'remote:pty-1', { - tabTitle: 'repo terminal', - paneTitle: 'ssh build-host | OC | Native session' - }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect( - runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle: terminal.handle, - condition: 'tui-idle', - status: 'running' - }) - }) - it('does not treat a Codex launch title as tui-idle readiness', async () => { vi.useFakeTimers() try { @@ -422,61 +169,4 @@ describe('OrcaRuntimeService', () => { vi.useRealTimers() } }) - - it('resolves tui-idle from a Codex ready prompt preview', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData( - 'pty-bg', - [ - ' >_ OpenAI Codex (v0.131.0)\n', - ' model: gpt-5.5 high /model to change\n', - ' directory: ~/orca/workspaces/orca/cli-debug\n' - ].join(''), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - status: 'running' - }) - }) - - it('resolves tui-idle from an Antigravity prompt before the model line', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData( - 'pty-bg', - [ - 'Do you trust this workspace directory?\n', - 'Press t to trust\n', - antigravityPromptBeforeModelReadyScreen('Gemini 3.5 Flash (High)') - ].join(''), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - satisfied: true, - status: 'running' - }) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts index b305ea4fb7c..3e9b364b1d6 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts @@ -1,88 +1,12 @@ import { describe, expect, it, vi } from 'vitest' -import { - AGENT_PROMPT_BRACKETED_PASTE_END, - AGENT_PROMPT_BRACKETED_PASTE_START -} from '../../../shared/agent-launch/startup/agent-prompt-injection' +import { AGENT_PROMPT_BRACKETED_PASTE_END } from '../../../shared/agent-launch/startup/agent-prompt-injection' import '../../../shared/orca-dispatch-status-prompt' import { OrcaRuntimeService } from '../orca-runtime' import './runtime-test-module-registration.spec' import { acknowledgeAgentPromptSubmit } from '../orca-runtime-test-mocks/setup.spec' -import { - TEST_WORKTREE_PATH, - cursorBusyScreen, - cursorReadyScreen, - store -} from './orca-runtime-test-fixtures.spec' +import { TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('resolves tui-idle from a Codex ready prompt even when stale startup lines remain', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData( - 'pty-bg', - [ - 'Booting MCP server: computer-use(0s esc to interrupt)\n', - ' >_ OpenAI Codex (v0.132.0)\n', - ' model: gpt-5.5 high /model to change\n', - ' directory: ~/orca/workspaces/orca/cli-debug\n', - [ - 'Starting MCP servers (0/2): codex_apps, computer-use (2s esc to interrupt)', - 'Run /review on my current changes gpt-5.5 high ~/orca/workspaces/orca/cli-debug', - 'Run /review on my current changes gpt-5.5 high ~/orca/workspaces/orca/cli-debug', - 'Run /review on my current changes gpt-5.5 high ~/orca/workspaces/orca/cli-debug', - 'Run /review on my current changes gpt-5.5 high ~/orca/workspaces/orca/cli-debug\n' - ].join('') - ].join(''), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - satisfied: true, - status: 'running' - }) - }) - - it('resolves tui-idle when a stale Codex prompt is followed by the ready header', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData( - 'pty-bg', - [ - 'Choose working directory to resume this session\n', - 'Press enter to continue\n', - ' >_ OpenAI Codex (v0.132.0)\n', - ' model: gpt-5.5 high /model to change\n', - ' directory: ~/orca/workspaces/orca/cli-debug\n' - ].join(''), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - satisfied: true, - status: 'running' - }) - }) - it('blocks tui-idle when a newer prompt follows a stale prompt and ready header', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ @@ -117,164 +41,6 @@ describe('OrcaRuntimeService', () => { }) }) - it('resolves tui-idle for an idle Cursor lane past its dismissed trust dialog (#8210)', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'cursor-agent' - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - // A later idle prompt must override a dismissed trust dialog retained in scrollback. - runtime.onPtyData( - 'pty-bg', - [ - // Pick the later ready banner, not Cursor Agent in the earlier trust dialog. - 'Cursor Agent\n', - '⚠ Workspace Trust Required\n', - 'Do you trust the contents of this directory?\n', - ' ▶ [a] Trust this workspace\n', - ' [q] Quit\n', - cursorReadyScreen() - ].join(''), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 }) - ).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - satisfied: true, - status: 'running' - }) - }) - - it('does not block a mid-run Cursor lane on its dismissed trust dialog (#8210)', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'cursor-agent' - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData( - 'pty-bg', - [ - // The later banner must win over the earlier trust-dialog title. - 'Cursor Agent\n', - '⚠ Workspace Trust Required\n', - 'Do you trust the contents of this directory?\n', - ' ▶ [a] Trust this workspace\n', - ' [q] Quit\n', - cursorBusyScreen() - ].join(''), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 200 }) - ).rejects.toThrow('timeout') - }) - - it('does not classify unrelated press-enter prompts as Codex blocked prompts', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData('pty-bg', 'Press enter to continue\n', Date.now()) - - const waitPromise = runtime.waitForTerminal(handle, { - condition: 'tui-idle', - timeoutMs: 1_000 - }) - const timeoutAssertion = expect(waitPromise).rejects.toThrow('timeout') - - await vi.advanceTimersByTimeAsync(2_000) - - await timeoutAssertion - } finally { - vi.useRealTimers() - } - }) - - it('resolves tui-idle for quiet background PTY agents without OSC titles', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'codex' - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - runtime.onPtyData('pty-bg', 'OpenAI Codex\n', Date.now()) - - const waitPromise = runtime.waitForTerminal(handle, { - condition: 'tui-idle', - timeoutMs: 10_000 - }) - const waitAssertion = expect(waitPromise).resolves.toMatchObject({ - handle, - condition: 'tui-idle', - status: 'running' - }) - - await vi.advanceTimersByTimeAsync(6_000) - - await waitAssertion - } finally { - vi.useRealTimers() - } - }) - - it('sends agent prompts as bracketed paste before submit', async () => { - vi.useFakeTimers() - try { - const writes: string[] = [] - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: (_ptyId, data) => { - writes.push(data) - acknowledgeAgentPromptSubmit(runtime, 'pty-bg', data) - return true - }, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - const prompt = 'line one\nline two\x1b[201~' - - const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt, { inputKind: 'driving' }) - await vi.runAllTimersAsync() - const result = await sendPromise - - const pasted = [ - AGENT_PROMPT_BRACKETED_PASTE_START, - 'line one\nline two[201~', - AGENT_PROMPT_BRACKETED_PASTE_END - ].join('') - expect(result).toMatchObject({ - handle, - accepted: true, - bytesWritten: Buffer.byteLength(`${pasted}\r`, 'utf8') - }) - expect(writes).toEqual([pasted, '\r']) - } finally { - vi.useRealTimers() - } - }) - it.each(['claude', 'codex'] as const)( 'waits for %s composer output frames to settle before one submit', async (agent) => { diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts index d3d00fd7fc4..0ff8ff182d9 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts @@ -4,105 +4,15 @@ import '../../../shared/constants' import './runtime-test-module-registration.spec' import { AGENT_PROMPT_BRACKETED_PASTE_END, - AGENT_PROMPT_BRACKETED_PASTE_START, - buildAgentPromptPasteBytes + AGENT_PROMPT_BRACKETED_PASTE_START } from '../../../shared/agent-launch/startup/agent-prompt-injection' import '../../../shared/clipboard-text' import { OrcaRuntimeService } from '../orca-runtime' import { acknowledgeAgentPromptSubmit } from '../orca-runtime-test-mocks/setup.spec' -import { - TERMINAL_INPUT_CHUNK_MAX_BYTES, - TERMINAL_INPUT_MAX_BYTES, - TERMINAL_INPUT_TOO_LARGE_ERROR -} from '../../../shared/terminal/input/terminal-input' +import { TERMINAL_INPUT_CHUNK_MAX_BYTES } from '../../../shared/terminal/input/terminal-input' import { TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('settles a foreground Codex prompt when launch metadata has not arrived', async () => { - vi.useFakeTimers() - try { - const writes: string[] = [] - let composerReady = false - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: (_ptyId, data) => { - writes.push(data) - if (data.includes(AGENT_PROMPT_BRACKETED_PASTE_END)) { - setTimeout(() => { - composerReady = true - runtime.onPtyData('pty-bg', '\x1b[?25hcomposer rendered', Date.now()) - }, 1_200) - } - acknowledgeAgentPromptSubmit(runtime, 'pty-bg', data) - return true - }, - kill: () => true, - getForegroundProcess: async () => 'codex' - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - - await expect(runtime.isTerminalRunningSettledPromptAgent(handle)).resolves.toBe(true) - const sendPromise = runtime.sendTerminalAgentPrompt(handle, 'review this change', { - inputKind: 'driving' - }) - await vi.advanceTimersByTimeAsync(1_199) - expect(writes).not.toContain('\r') - await vi.advanceTimersByTimeAsync(1_500) - expect(writes).not.toContain('\r') - await vi.advanceTimersByTimeAsync(1) - await sendPromise - - expect(composerReady).toBe(true) - expect(writes.filter((data) => data === '\r')).toHaveLength(1) - } finally { - vi.useRealTimers() - } - }) - - it('gives a late Codex render marker a fresh quiescence window', async () => { - vi.useFakeTimers() - try { - const writes: string[] = [] - let composerReady = false - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: (_ptyId, data) => { - writes.push(data) - if (data.includes(AGENT_PROMPT_BRACKETED_PASTE_END)) { - setTimeout(() => runtime.onPtyData('pty-bg', '\x1b[?25h', Date.now()), 7_900) - setTimeout(() => { - composerReady = true - runtime.onPtyData('pty-bg', 'final slow composer frame', Date.now()) - }, 8_100) - } - acknowledgeAgentPromptSubmit(runtime, 'pty-bg', data) - return true - }, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - launchAgent: 'codex' - }) - - const sendPromise = runtime.sendTerminalAgentPrompt(handle, 'review this change', { - inputKind: 'driving' - }) - await vi.advanceTimersByTimeAsync(8_000) - expect(writes).not.toContain('\r') - await vi.advanceTimersByTimeAsync(1_599) - expect(writes).not.toContain('\r') - await vi.advanceTimersByTimeAsync(1) - await sendPromise - expect(composerReady).toBe(true) - expect(writes.filter((data) => data === '\r')).toHaveLength(1) - } finally { - vi.useRealTimers() - } - }) - it('bounds a Claude render that never settles to one fallback submit', async () => { vi.useFakeTimers() try { @@ -146,44 +56,6 @@ describe('OrcaRuntimeService', () => { } }) - it('writes large agent prompt paste frames atomically before delayed submit', async () => { - vi.useFakeTimers() - try { - const writes: string[] = [] - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: (_ptyId, data) => { - writes.push(data) - acknowledgeAgentPromptSubmit(runtime, 'pty-bg', data) - return true - }, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - launchAgent: 'claude' - }) - const prompt = `${'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES)}\ntail` - - const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt, { inputKind: 'driving' }) - await vi.runAllTimersAsync() - const result = await sendPromise - - const pasteWrites = writes.slice(0, -1) - expect(result.bytesWritten).toBe( - Buffer.byteLength(`${buildAgentPromptPasteBytes(prompt)}\r`, 'utf8') - ) - expect(writes.at(-1)).toBe('\r') - expect(pasteWrites).toHaveLength(1) - expect(pasteWrites.join('')).toBe(buildAgentPromptPasteBytes(prompt)) - expect(pasteWrites[0]).toContain(AGENT_PROMPT_BRACKETED_PASTE_START) - expect(pasteWrites.at(-1)).toContain(AGENT_PROMPT_BRACKETED_PASTE_END) - } finally { - vi.useRealTimers() - } - }) - it('rejects an agent prompt when the atomic paste write fails', async () => { vi.useFakeTimers() try { @@ -216,62 +88,6 @@ describe('OrcaRuntimeService', () => { } }) - it('rejects oversized terminal.send text before provider writes', async () => { - const writes: string[] = [] - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: (_ptyId, data) => { - writes.push(data) - return true - }, - kill: () => true, - getForegroundProcess: async () => null - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - - await expect( - runtime.sendTerminal( - handle, - { text: 'x'.repeat(TERMINAL_INPUT_MAX_BYTES + 1) }, - { inputKind: 'driving' } - ) - ).rejects.toThrow(TERMINAL_INPUT_TOO_LARGE_ERROR) - expect(writes).toEqual([]) - }) - - it('rejects focusing an exited background terminal session', async () => { - const revealTerminalSession = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession, - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) - revealTerminalSession.mockClear() - runtime.onPtyExit('pty-bg', 0) - - await expect(runtime.focusTerminal(handle)).rejects.toThrow('terminal_exited') - expect(revealTerminalSession).not.toHaveBeenCalled() - }) - it('coalesces concurrent focusTerminal navigations so only the latest full reveal runs', async () => { // Resolve initial create immediately, then gate reveals for the focus storm. const revealTerminalSession = vi.fn().mockResolvedValue({ tabId: 'tab-create' }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts index cb1b3a22bc5..d3fe2b778b9 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts @@ -3,110 +3,9 @@ import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import '../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' -import { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - store, - syncSinglePty -} from './orca-runtime-test-fixtures.spec' +import { store, syncSinglePty } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('reports a queued PTY focus as not navigated when its notifier disappears', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.registerPty('pty-a', TEST_WORKTREE_ID) - runtime.registerPty('pty-b', TEST_WORKTREE_ID) - const terminals = (await runtime.listTerminals()).terminals - const terminalA = terminals.find((terminal) => terminal.ptyId === 'pty-a') - const terminalB = terminals.find((terminal) => terminal.ptyId === 'pty-b') - expect(terminalA).toBeDefined() - expect(terminalB).toBeDefined() - - let releaseReveal!: (value: { tabId: string }) => void - const revealGate = new Promise<{ tabId: string }>((resolve) => { - releaseReveal = resolve - }) - const revealTerminalSession = vi - .fn() - .mockImplementationOnce(() => revealGate) - .mockResolvedValue({ tabId: 'tab-b' }) - runtime.setNotifier({ revealTerminalSession } as never) - - const first = runtime.focusTerminal(terminalA!.handle) - await vi.waitFor(() => expect(revealTerminalSession).toHaveBeenCalledOnce()) - const queued = runtime.focusTerminal(terminalB!.handle) - runtime.setNotifier(null) - releaseReveal({ tabId: 'tab-a' }) - - await expect(first).resolves.toMatchObject({ handle: terminalA!.handle, navigated: false }) - await expect(queued).resolves.toMatchObject({ handle: terminalB!.handle, navigated: false }) - expect(revealTerminalSession).toHaveBeenCalledOnce() - }) - - it('does not invoke a stale graph-leaf focus notifier after queued PTY work', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-leaf', - worktreeId: TEST_WORKTREE_ID, - title: 'Starting terminal', - activeLeafId: HEADLESS_LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: 'tab-leaf', - worktreeId: TEST_WORKTREE_ID, - leafId: HEADLESS_LEAF_ID, - paneRuntimeId: 1, - ptyId: null - } - ] - }) - const leafTerminal = (await runtime.listTerminals()).terminals.find( - (terminal) => terminal.tabId === 'tab-leaf' - ) - runtime.registerPty('pty-a', TEST_WORKTREE_ID) - const ptyTerminal = (await runtime.listTerminals()).terminals.find( - (terminal) => terminal.ptyId === 'pty-a' - ) - expect(ptyTerminal).toBeDefined() - expect(leafTerminal).toBeDefined() - - let releaseReveal!: (value: { tabId: string }) => void - const revealGate = new Promise<{ tabId: string }>((resolve) => { - releaseReveal = resolve - }) - const focusTerminal = vi.fn() - const revealTerminalSession = vi.fn(() => revealGate) - runtime.setNotifier({ - revealTerminalSession, - focusTerminal - } as never) - - const first = runtime.focusTerminal(ptyTerminal!.handle) - await vi.waitFor(() => expect(revealTerminalSession).toHaveBeenCalledOnce()) - const queued = runtime.focusTerminal(leafTerminal!.handle) - runtime.setNotifier(null) - releaseReveal({ tabId: 'tab-a' }) - - await expect(first).resolves.toMatchObject({ handle: ptyTerminal!.handle, navigated: false }) - await expect(queued).resolves.toMatchObject({ handle: leafTerminal!.handle, navigated: false }) - expect(focusTerminal).not.toHaveBeenCalled() - }) - it('clears terminal scrollback through the PTY controller and headless buffer', async () => { const clearBuffer = vi.fn().mockResolvedValue(undefined) const runtime = new OrcaRuntimeService(store) @@ -218,213 +117,6 @@ describe('OrcaRuntimeService', () => { expect(thirdRead.nextCursor).toBe('2') }) - it('paginates retained terminal output with explicit limits and truncation metadata', async () => { - const runtime = new OrcaRuntimeService(store) - - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - title: 'Claude', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'pty-1' - } - ] - }) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData( - 'pty-1', - `${Array.from({ length: 150 }, (_, index) => `line-${index}`).join('\n')}\n`, - 100 - ) - - const preview = await runtime.readTerminal(terminal.handle) - expect(preview.tail).toHaveLength(120) - expect(preview.tail[0]).toBe('line-30') - expect(preview.limited).toBe(true) - expect(preview.oldestCursor).toBe('0') - expect(preview.latestCursor).toBe('150') - - const defaultCursorRead = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - expect(defaultCursorRead.tail).toHaveLength(150) - expect(defaultCursorRead.nextCursor).toBe('150') - expect(defaultCursorRead.limited).toBe(false) - - const firstPage = await runtime.readTerminal(terminal.handle, { cursor: 0, limit: 50 }) - expect(firstPage.tail).toHaveLength(50) - expect(firstPage.tail[0]).toBe('line-0') - expect(firstPage.nextCursor).toBe('50') - expect(firstPage.limited).toBe(true) - expect(firstPage.truncated).toBe(false) - - const fractionalPage = await runtime.readTerminal(terminal.handle, { cursor: 0, limit: 0.5 }) - expect(fractionalPage.tail).toEqual(['line-0']) - expect(fractionalPage.nextCursor).toBe('1') - expect(fractionalPage.limited).toBe(true) - - const secondPage = await runtime.readTerminal(terminal.handle, { - cursor: Number(firstPage.nextCursor), - limit: 200 - }) - expect(secondPage.tail).toHaveLength(100) - expect(secondPage.tail[0]).toBe('line-50') - expect(secondPage.nextCursor).toBe('150') - expect(secondPage.limited).toBe(false) - - runtime.onPtyData( - 'pty-1', - `${Array.from({ length: 2100 }, (_, index) => `later-${index}`).join('\n')}\n`, - 101 - ) - - const staleCursorRead = await runtime.readTerminal(terminal.handle, { cursor: 0, limit: 5 }) - expect(staleCursorRead.truncated).toBe(true) - expect(staleCursorRead.oldestCursor).toBe('250') - expect(staleCursorRead.tail).toEqual([ - 'later-100', - 'later-101', - 'later-102', - 'later-103', - 'later-104' - ]) - expect(staleCursorRead.nextCursor).toBe('255') - - const futureCursorRead = await runtime.readTerminal(terminal.handle, { cursor: 9999 }) - expect(futureCursorRead.tail).toEqual([]) - expect(futureCursorRead.nextCursor).toBe('2250') - expect(futureCursorRead.limited).toBe(false) - }) - - it('falls back to renderer visible screen when uncursored TUI tail is blank', async () => { - const serializeBuffer = vi.fn().mockResolvedValue({ - data: '\x1b[?1049hClaude Code\r\nWorking on fix\r\nTool: Read\r\n', - cols: 80, - rows: 24 - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - hasRendererSerializer: () => true, - serializeBuffer - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', `${Array.from({ length: 3000 }, () => ' ').join('\n')}\n`, 100) - - const read = await runtime.readTerminal(terminal.handle) - - expect(read.tail).toEqual(['Claude Code', 'Working on fix', 'Tool: Read']) - expect(serializeBuffer).toHaveBeenCalledWith('pty-1', { - scrollbackRows: 0 - }) - }) - - it('reads and shows the runtime-owned alternate-screen grid without serialization', async () => { - const serializeBuffer = vi.fn() - const serializeProviderBuffer = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeBuffer, - serializeProviderBuffer - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData( - 'pty-1', - 'shell history\r\n\x1b[?1049h\x1b[2J\x1b[HClaude Code\r\nWorking on fix\r\nTool: Read\r\n', - 100 - ) - - const read = await runtime.readTerminal(terminal.handle) - const shown = await runtime.showTerminal(terminal.handle) - - expect(read.tail).toEqual(['Claude Code', 'Working on fix', 'Tool: Read']) - expect(shown.preview).toBe('Claude Code\nWorking on fix\nTool: Read') - expect(serializeBuffer).not.toHaveBeenCalled() - expect(serializeProviderBuffer).not.toHaveBeenCalled() - }) - - it('classifies older provider alternate-screen snapshots from ANSI', async () => { - const serializeProviderBuffer = vi.fn().mockResolvedValue({ - data: '\x1b[?1049h\x1b[2J\x1b[HRemote Vim\r\nediting README.md\r\n', - cols: 80, - rows: 24, - seq: 900, - source: 'headless' - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - - const [terminal] = (await runtime.listTerminals()).terminals - const read = await runtime.readTerminal(terminal.handle) - - expect(read.tail).toEqual(['Remote Vim', 'editing README.md']) - expect(runtime.isTerminalAlternateScreen('pty-1')).toBe(true) - expect(serializeProviderBuffer).toHaveBeenCalledOnce() - }) - - it('honors the last ANSI screen transition when older provider metadata is absent', async () => { - const serializeProviderBuffer = vi.fn().mockResolvedValue({ - data: '\x1b[?1049hOld TUI\r\n\x1b[?1049l', - cols: 80, - rows: 24, - seq: 900, - source: 'headless' - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.onPtyData('pty-1', 'shell history\r\n', 100) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - - const [terminal] = (await runtime.listTerminals()).terminals - const read = await runtime.readTerminal(terminal.handle) - - expect(read.tail).toEqual(['shell history']) - expect(runtime.isTerminalAlternateScreen('pty-1')).toBe(false) - }) - it.each([ { name: 'live exit wins over an alternate provider snapshot', diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts index e1065eeed56..844134c5fb2 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts @@ -57,210 +57,6 @@ describe('OrcaRuntimeService', () => { expect(read.tail.join('\n')).not.toContain('Stale Ready screen') }) - it('rejects a full provider screen frame after live output advances', async () => { - type Snapshot = { - data: string - scrollbackAnsi: string - cols: number - rows: number - seq: number - source: 'headless' - alternateScreen: boolean - } - let resolveSnapshot!: (snapshot: Snapshot) => void - const serializeProviderBuffer = vi - .fn() - .mockResolvedValueOnce(null) - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveSnapshot = resolve - }) - ) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.onPtyData('pty-1', 'shell history\r\n', 100) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - const [terminal] = (await runtime.listTerminals()).terminals - - const readPromise = runtime.readTerminal(terminal.handle, { screen: true }) - await vi.waitFor(() => expect(serializeProviderBuffer).toHaveBeenCalledTimes(2)) - runtime.onPtyData('pty-1', 'live progress\r\n', 101) - resolveSnapshot({ - data: '\x1b[?1049h\x1b[2J\x1b[HStale full screen\r\n', - scrollbackAnsi: '', - cols: 80, - rows: 24, - seq: 900, - source: 'headless', - alternateScreen: true - }) - - const read = await readPromise - expect(read.source).toBe('screen-unavailable') - expect(read.tail.join('\n')).not.toContain('Stale full screen') - }) - - it('shares one provider snapshot between concurrent read and show calls', async () => { - type Snapshot = { - data: string - cols: number - rows: number - seq: number - source: 'headless' - alternateScreen: boolean - } - let resolveSnapshot!: (snapshot: Snapshot) => void - const serializeProviderBuffer = vi.fn( - () => - new Promise((resolve) => { - resolveSnapshot = resolve - }) - ) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - const [terminal] = (await runtime.listTerminals()).terminals - - const readPromise = runtime.readTerminal(terminal.handle) - const showPromise = runtime.showTerminal(terminal.handle) - await vi.waitFor(() => expect(serializeProviderBuffer).toHaveBeenCalledOnce()) - resolveSnapshot({ - data: '\x1b[?1049h\x1b[2J\x1b[HShared TUI frame\r\n', - cols: 80, - rows: 24, - seq: 900, - source: 'headless', - alternateScreen: true - }) - - const [read, shown] = await Promise.all([readPromise, showPromise]) - expect(read.tail).toEqual(['Shared TUI frame']) - expect(shown.preview).toBe('Shared TUI frame') - expect(serializeProviderBuffer).toHaveBeenCalledOnce() - }) - - it('keeps cursor reads provider-free on restored alternate-screen PTYs', async () => { - const serializeProviderBuffer = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.onPtyData('pty-1', 'shell history\r\n', 100) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - const [terminal] = (await runtime.listTerminals()).terminals - - const read = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - - expect(read.tail).toEqual(['shell history']) - expect(serializeProviderBuffer).not.toHaveBeenCalled() - }) - - it('backs off after a provider snapshot failure instead of retrying for show', async () => { - const serializeProviderBuffer = vi.fn().mockRejectedValue(new Error('provider unavailable')) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.onPtyData('pty-1', 'shell history\r\n', 100) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - const [terminal] = (await runtime.listTerminals()).terminals - - const read = await runtime.readTerminal(terminal.handle) - const shown = await runtime.showTerminal(terminal.handle) - - expect(read.tail).toEqual(['shell history']) - expect(shown.preview).toBe('shell history') - expect(serializeProviderBuffer).toHaveBeenCalledOnce() - }) - - it('falls back once to a mounted renderer when a known alternate provider fails', async () => { - const serializeProviderBuffer = vi - .fn() - .mockResolvedValueOnce({ - data: '\x1b[?1049h\x1b[2J\x1b[HProvider TUI\r\n', - cols: 80, - rows: 24, - seq: 900, - source: 'headless', - alternateScreen: true - }) - .mockRejectedValue(new Error('provider unavailable')) - const serializeBuffer = vi.fn().mockResolvedValue({ - data: '\x1b[?1049h\x1b[2J\x1b[HRenderer TUI\r\n', - cols: 80, - rows: 24 - }) - let rendererMounted = false - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeBuffer, - serializeProviderBuffer, - hasRendererSerializer: () => rendererMounted - }) - syncSinglePty(runtime) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - const [terminal] = (await runtime.listTerminals()).terminals - await expect(runtime.readTerminal(terminal.handle)).resolves.toMatchObject({ - tail: ['Provider TUI'] - }) - runtime.onPtyData('pty-1', 'new output', 100) - rendererMounted = true - - const read = await runtime.readTerminal(terminal.handle) - - expect(read.tail).toEqual(['Renderer TUI']) - expect(serializeProviderBuffer).toHaveBeenCalledTimes(2) - expect(serializeBuffer).toHaveBeenCalledOnce() - }) - it('bounds a stuck provider snapshot and shares the timed-out request', async () => { vi.useFakeTimers() try { @@ -398,52 +194,6 @@ describe('OrcaRuntimeService', () => { await expect(readPromise).rejects.toThrow('terminal_handle_stale') }) - it('bounds provider visible frames for read and show responses', async () => { - const visibleLines = [ - 'skip-1', - 'skip-2', - 'A'.repeat(49), - 'B'.repeat(49), - 'C'.repeat(49), - 'D'.repeat(49), - 'E'.repeat(49), - 'F'.repeat(50) - ] - const expectedTail = visibleLines.slice(-6) - const serializeProviderBuffer = vi.fn().mockResolvedValue({ - data: `\x1b[?1049h\x1b[2J\x1b[H${visibleLines.join('\r\n')}\r\n`, - cols: 80, - rows: 24, - seq: 900, - source: 'headless', - alternateScreen: true - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - const [terminal] = (await runtime.listTerminals()).terminals - - const read = await runtime.readTerminal(terminal.handle, { limit: 6 }) - const shown = await runtime.showTerminal(terminal.handle) - - expect(read.tail).toEqual(expectedTail) - expect(read.returnedLineCount).toBe(6) - expect(shown.preview).toBe(expectedTail.join('\n')) - expect(shown.preview.length).toBe(300) - expect(serializeProviderBuffer).toHaveBeenCalledOnce() - }) - it('separates composer draft text from rendered terminal output', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ @@ -469,36 +219,6 @@ describe('OrcaRuntimeService', () => { }) }) - it('keeps renderer-fallback composer drafts separate from terminal output', async () => { - const serializeBuffer = vi.fn().mockResolvedValue({ - data: '\x1b[?1049hBuild passed\r\n────────\r\n❯ \x1b[2mproceed with the release\x1b[22m\x1b[3G', - cols: 80, - rows: 24 - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - hasRendererSerializer: () => true, - serializeBuffer - }) - syncSinglePty(runtime) - runtime.onPtyData('pty-1', `${Array.from({ length: 3000 }, () => '').join('\n')}\n`, 100) - const [terminal] = (await runtime.listTerminals()).terminals - - const read = await runtime.readTerminal(terminal.handle) - - expect(read).toMatchObject({ - source: 'screen', - tail: ['Build passed', '────────', '❯'], - draft: 'proceed with the release' - }) - expect(serializeBuffer).toHaveBeenCalledWith('pty-1', { - scrollbackRows: 0 - }) - }) - it('does not use renderer visible-screen fallback for cursor transcript reads', async () => { const serializeBuffer = vi.fn().mockResolvedValue({ data: 'Visible TUI\n', @@ -525,31 +245,4 @@ describe('OrcaRuntimeService', () => { scrollbackRows: 0 }) }) - - it('does not use renderer visible-screen fallback for a short blank shell tail', async () => { - const serializeBuffer = vi.fn().mockResolvedValue({ - data: 'shell prompt\n', - cols: 80, - rows: 24 - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - hasRendererSerializer: () => true, - serializeBuffer - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '\n\n', 100) - - const read = await runtime.readTerminal(terminal.handle) - - expect(read.tail).toEqual(['', '']) - expect(serializeBuffer).not.toHaveBeenCalledWith('pty-1', { - scrollbackRows: 0 - }) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts index ff9fdbf4cd4..f99931a14c9 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts @@ -1,122 +1,14 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import './runtime-test-module-registration.spec' import { HeadlessEmulator } from '../../daemon/emulation/headless-emulator' -import { MAX_OSC_TITLE_CHARS } from '../../../shared/agent-status/title/osc-title-extraction' +import '../../../shared/agent-status/title/osc-title-extraction' import { OrcaRuntimeService } from '../orca-runtime' import '../terminal/output/recent-pty-output-buffer' -import { appendNormalizedToTailBuffer } from '../terminal/output/tail/terminal-tail-buffer' +import '../terminal/output/tail/terminal-tail-buffer' import '../terminal/output/tail/terminal-tail-state' import { store, syncSinglePty } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('trims terminal tail character budget without per-line array shifts', () => { - const shiftSpy = vi.spyOn(Array.prototype, 'shift') - const lines = Array.from({ length: 1000 }, (_, index) => `line-${index}-${'x'.repeat(300)}`) - const result = appendNormalizedToTailBuffer([], '', `${lines.join('\n')}\n`) - const shiftCallCount = shiftSpy.mock.calls.length - shiftSpy.mockRestore() - - let retainedChars = lines.reduce((sum, line) => sum + line.length, 0) - let expectedStartIndex = 0 - while (expectedStartIndex < lines.length && retainedChars > 256 * 1024) { - retainedChars -= lines[expectedStartIndex].length - expectedStartIndex += 1 - } - - expect(result.truncated).toBe(true) - expect(result.lines).toEqual(lines.slice(expectedStartIndex)) - expect(result.lines.reduce((sum, line) => sum + line.length, 0)).toBeLessThanOrEqual(256 * 1024) - expect(shiftCallCount).toBe(0) - }) - - it('retains ANSI-only status redraws instead of appending every frame', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '• Working', 100) - const initialPreview = await runtime.readTerminal(terminal.handle) - expect(initialPreview.tail).toEqual(['• Working']) - - runtime.onPtyData('pty-1', '\x1b[2K\x1b[1G• Working.', 101) - const redrawPreview = await runtime.readTerminal(terminal.handle) - expect(redrawPreview.tail).toEqual(['• Working.']) - expect(redrawPreview.tail.join('\n')).not.toContain('• Working• Working') - - runtime.onPtyData('pty-1', '\x1b[2K\x1b[1G• Working..', 102) - const latestPreview = await runtime.readTerminal(terminal.handle) - expect(latestPreview.tail).toEqual(['• Working..']) - expect(latestPreview.latestCursor).toBe('0') - - const cursorReadBeforeNewline = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - expect(cursorReadBeforeNewline.tail).toEqual([]) - expect(cursorReadBeforeNewline.nextCursor).toBe('0') - - runtime.onPtyData('pty-1', '\n', 103) - - const read = await runtime.readTerminal(terminal.handle) - expect(read.tail).toEqual(['• Working..']) - expect(read.latestCursor).toBe('1') - expect(read.tail.join('\n')).not.toContain('• Working• Working') - - const cursorReadAfterNewline = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - expect(cursorReadAfterNewline.tail).toEqual(['• Working..']) - expect(cursorReadAfterNewline.nextCursor).toBe('1') - }) - - it('retains split multi-line ANSI footer redraw state across chunks', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '• Working\nTool call\n', 100) - const beforeRedraw = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - expect(beforeRedraw.tail).toEqual(['• Working', 'Tool call']) - expect(beforeRedraw.nextCursor).toBe('2') - - runtime.onPtyData('pty-1', '\x1b[2A', 101) - const betweenChunks = await runtime.readTerminal(terminal.handle) - expect(betweenChunks.tail).toEqual(['• Working']) - expect(betweenChunks.latestCursor).toBe('2') - - runtime.onPtyData('pty-1', '\x1b[2K\x1b[1G• Working.\n\x1b[2K\x1b[1GTool call finished\n', 102) - - const read = await runtime.readTerminal(terminal.handle) - expect(read.tail).toEqual(['• Working.', 'Tool call finished']) - expect(read.latestCursor).toBe('4') - - const cursorRead = await runtime.readTerminal(terminal.handle, { - cursor: Number(beforeRedraw.nextCursor) - }) - expect(cursorRead.tail).toEqual(['• Working.', 'Tool call finished']) - expect(cursorRead.oldestCursor).toBe('0') - expect(cursorRead.nextCursor).toBe('4') - }) - - it('does not let stale lower rows hide earlier corrected footer rows from cursor reads', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', 'A\nB\nC\n', 100) - const beforeRedraw = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - expect(beforeRedraw.tail).toEqual(['A', 'B', 'C']) - expect(beforeRedraw.nextCursor).toBe('3') - - runtime.onPtyData('pty-1', '\x1b[2A\x1b[2K\x1b[1GB2\n', 101) - - const read = await runtime.readTerminal(terminal.handle) - expect(read.tail).toEqual(['A', 'B2']) - expect(read.latestCursor).toBe('4') - - const cursorRead = await runtime.readTerminal(terminal.handle, { - cursor: Number(beforeRedraw.nextCursor) - }) - expect(cursorRead.tail).toEqual(['B2']) - expect(cursorRead.oldestCursor).toBe('0') - expect(cursorRead.nextCursor).toBe('4') - }) - it('keeps cursor pagination stable across a CUU redraw of the live screen', async () => { const runtime = new OrcaRuntimeService(store) const liveScreen = new HeadlessEmulator({ cols: 80, rows: 24 }) @@ -173,114 +65,6 @@ describe('OrcaRuntimeService', () => { }) }) - it('bounds completed transcript entries from a single multi-line redraw chunk', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - const lines = Array.from({ length: 2100 }, (_, index) => `redraw-${index}`) - runtime.onPtyData('pty-1', `\x1b[1A${lines.join('\n')}\n`, 100) - - await expect( - runtime.readTerminal(terminal.handle, { cursor: 0, limit: 3 }) - ).resolves.toMatchObject({ - tail: ['redraw-100', 'redraw-101', 'redraw-102'], - truncated: true, - oldestCursor: '100', - nextCursor: '103', - latestCursor: '2100' - }) - }) - - it('retains multi-line ANSI redraws when the last footer row stays partial', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '• Working\nTool call\n', 100) - const beforeRedraw = await runtime.readTerminal(terminal.handle, { cursor: 0 }) - expect(beforeRedraw.nextCursor).toBe('2') - - runtime.onPtyData( - 'pty-1', - '\x1b[2A\x1b[2K\x1b[1G• Working.\n\x1b[2K\x1b[1GTool call still running', - 101 - ) - - const read = await runtime.readTerminal(terminal.handle) - expect(read.tail).toEqual(['• Working.', 'Tool call still running']) - expect(read.latestCursor).toBe('3') - - const cursorRead = await runtime.readTerminal(terminal.handle, { - cursor: Number(beforeRedraw.nextCursor) - }) - expect(cursorRead.tail).toEqual(['• Working.']) - expect(cursorRead.oldestCursor).toBe('0') - expect(cursorRead.nextCursor).toBe('3') - - runtime.onPtyData('pty-1', '\n', 102) - const completedPartialRead = await runtime.readTerminal(terminal.handle, { cursor: 3 }) - expect(completedPartialRead.tail).toEqual(['Tool call still running']) - expect(completedPartialRead.nextCursor).toBe('4') - }) - - it('does not retain split ANSI controls as visible terminal preview text', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', 'Working\r\x1b[', 100) - runtime.onPtyData('pty-1', '38;2;190;210;223;49mWo', 101) - - const colorRead = await runtime.readTerminal(terminal.handle) - const colorRetained = colorRead.tail.join('\n') - expect(colorRetained).toContain('Wo') - expect(colorRetained).not.toContain('38;2') - expect(colorRetained).not.toContain('49m') - - runtime.onPtyData('pty-1', 'rking\x1b[?2026', 102) - runtime.onPtyData('pty-1', 'l', 103) - - const modeRead = await runtime.readTerminal(terminal.handle) - const retained = modeRead.tail.join('\n') - expect(retained).toContain('Working') - expect(retained).not.toContain('38;2') - expect(retained).not.toContain('?2026') - expect(retained).not.toContain('49m') - - runtime.onPtyData('pty-1', ` done\x1b]0;${'x'.repeat(5000)}`, 104) - runtime.onPtyData('pty-1', '\u0007\n', 105) - - const longRead = await runtime.readTerminal(terminal.handle) - const longRetained = longRead.tail.join('\n') - expect(longRetained).toContain('Working done') - expect(longRetained).not.toContain('x'.repeat(100)) - const pty = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-1') - expect(pty?.lastOscTitle).toBe('x'.repeat(MAX_OSC_TITLE_CHARS)) - }) - - it('retains same-line redraw cursor position across split full-line erase chunks', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', 'ABC', 100) - runtime.onPtyData('pty-1', '\x1b[2K', 101) - const erasedRead = await runtime.readTerminal(terminal.handle) - expect(erasedRead.tail).toEqual([]) - - runtime.onPtyData('pty-1', 'XY\n', 102) - - const read = await runtime.readTerminal(terminal.handle) - expect(read.tail).toEqual([' XY']) - expect(read.tail.join('\n')).not.toContain('ABCXY') - expect(read.tail.join('\n')).not.toContain('2K') - }) - it('keeps huge ANSI cursor movement params bounded in retained previews', async () => { const runtime = new OrcaRuntimeService(store) syncSinglePty(runtime) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts index 20623d99c34..008a1e47ae5 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts @@ -1,64 +1,8 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' -import { - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - store, - syncSinglePty -} from './orca-runtime-test-fixtures.spec' -import { agentLaunchSurfaceFactory } from '../rpc/methods/agent-launch/agent-launch-surfaces' -import { publishAgentLaunchTabEarly } from '../rpc/methods/agent-launch/agent-launch-tab-publication' -import { AgentLaunch } from '../../../shared/rpc-contract/agent-launch-params' -import { DESKTOP_RPC_CALLER } from '../rpc/rpc-caller-identity' -import type { RpcContext } from '../rpc/core' -import type { AgentLaunchTabPublished } from '../../../shared/agent-launch/contracts/agent-launch-tab-publication' - -const RESERVED_TAB_ID = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' -const RESERVED_LEAF_ID = '3f2504e0-4f89-41d3-9a0c-0305e82c3301' - -// A spawn that found the reserved pane already live answers with its owner instead of a new PTY. -const LIVE_PANE_SPAWN = { - id: 'pty-live', - stablePaneOwner: { handle: 'term_live', tabId: RESERVED_TAB_ID, leafId: RESERVED_LEAF_ID } -} - -function runtimeWithDesktopWindow(spawnResult: Record = { id: 'pty-launch' }) { - const requestTabCreate = vi.fn() - electronMocks.BrowserWindow.fromId.mockReturnValue({ - isDestroyed: () => false, - webContents: { isDestroyed: () => false, send: requestTabCreate } - }) - const revealTerminalSession = vi.fn().mockResolvedValue({ tabId: RESERVED_TAB_ID }) - const releaseStablePaneCreate = vi.fn() - const kill = vi.fn(() => true) - const spawn = vi.fn().mockResolvedValue(spawnResult) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - claimStablePaneCreate: () => releaseStablePaneCreate, - spawn, - write: () => true, - kill, - getForegroundProcess: async () => null - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession, - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - return { runtime, spawn, requestTabCreate, revealTerminalSession, releaseStablePaneCreate, kill } -} +import '../orca-runtime-test-mocks/setup.spec' +import { store, syncSinglePty } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { it('bounds retained work for many newline-separated huge ANSI cursor movements', async () => { @@ -78,119 +22,4 @@ describe('OrcaRuntimeService', () => { expect(line).not.toContain('4000G') } }) - - it('does not retain split ST-terminated string controls as preview text', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', 'Before \x1b_Gi=31337,s=1,', 100) - runtime.onPtyData('pty-1', 'v=1,a=q,t=d,f=24;AAAA\x1b\\After\n', 101) - - const read = await runtime.readTerminal(terminal.handle) - const retained = read.tail.join('\n') - expect(retained).toContain('BeforeAfter') - expect(retained).not.toContain('Gi=31337') - expect(retained).not.toContain('AAAA') - }) - - it.each([ - { desktop: false, viewer: 'focus-window' }, - { desktop: true, viewer: 'focus-in-workspace' } - ])('rechecks failed publication during the $viewer host spawn', async ({ desktop, viewer }) => { - const { runtime, spawn, requestTabCreate, revealTerminalSession } = runtimeWithDesktopWindow() - const publishing = Promise.withResolvers() - const spawning = Promise.withResolvers<{ id: string }>() - const started = Promise.withResolvers() - spawn.mockImplementation(() => { - started.resolve() - return spawning.promise - }) - vi.spyOn(runtime, 'canPublishAgentLaunchTab').mockReturnValue(true) - vi.spyOn(runtime, 'publishAgentLaunchTab').mockReturnValue(publishing.promise) - const context: RpcContext = { - runtime, - ...(desktop ? { caller: DESKTOP_RPC_CALLER, clientKind: 'runtime' as const } : {}) - } - const paneKey = `${RESERVED_TAB_ID}:${RESERVED_LEAF_ID}` - const early = await publishAgentLaunchTabEarly( - AgentLaunch.parse({ - agent: 'claude', - target: { kind: 'existing', worktree: `id:${TEST_WORKTREE_ID}` }, - paneKey, - presentation: 'focused' - }), - context - ) - expect(early?.windowOwnsPresentation()).toBe(true) - const creating = agentLaunchSurfaceFactory(context, undefined, undefined, false, undefined, { - early, - presentation: 'focused' - }).createTerminalAgent({ - worktreeId: TEST_WORKTREE_ID, - agent: 'claude', - paneKey, - startupPrompt: 'fix the build' - }) - await started.promise - publishing.reject(new Error('agent_launch_tab_publish_timeout')) - await Promise.resolve() - expect(early?.windowOwnsPresentation()).toBe(false) - spawning.resolve({ id: 'pty-launch' }) - const terminal = await creating - expect(terminal.paneKey).toBe(paneKey) - expect(spawn).toHaveBeenCalledOnce() - expect(spawn.mock.calls[0]?.[0]?.command).toContain('fix the build') - expect(requestTabCreate).not.toHaveBeenCalled() - expect(revealTerminalSession).toHaveBeenCalledExactlyOnceWith( - TEST_WORKTREE_ID, - expect.objectContaining({ - tabId: RESERVED_TAB_ID, - leafId: RESERVED_LEAF_ID, - agentLaunchViewer: viewer, - activate: false, - surfaceOwner: false - }) - ) - }) - - it('refuses a live reserved pane before issuing a handle or revealing it', async () => { - const { runtime, revealTerminalSession, releaseStablePaneCreate, kill } = - runtimeWithDesktopWindow(LIVE_PANE_SPAWN) - - await expect( - runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - startupAgent: 'claude', - tabId: RESERVED_TAB_ID, - leafId: RESERVED_LEAF_ID, - requireFreshPane: true, - presentation: 'focused' - }) - ).rejects.toThrow('agent_launch_pane_already_live') - - expect((await runtime.listTerminals()).terminals).toEqual([]) - // Refusing reveal also prevents overwriting the running agent's launch config. - expect(revealTerminalSession).not.toHaveBeenCalled() - expect(kill).not.toHaveBeenCalled() - expect(releaseStablePaneCreate).toHaveBeenCalled() - }) - - it('still attaches to a live pane when the caller did not require a fresh one', async () => { - // `terminal.create` keeps its reattach; only agent.launch opts into the refusal. - const { runtime, revealTerminalSession } = runtimeWithDesktopWindow(LIVE_PANE_SPAWN) - runtime.registerPty('pty-live', TEST_WORKTREE_ID, null, { - ...LIVE_PANE_SPAWN.stablePaneOwner, - terminalHandle: 'term_live' - }) - - const created = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - startupAgent: 'claude', - tabId: RESERVED_TAB_ID, - leafId: RESERVED_LEAF_ID - }) - - expect(created.isReattach).toBe(true) - expect((await runtime.listTerminals()).terminals.map((t) => t.handle)).toEqual([created.handle]) - expect(revealTerminalSession).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts index 4e144c42ba5..c3073da3c62 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts @@ -2,13 +2,12 @@ import { describe, expect, it, vi } from 'vitest' import { committingSpawn, registerLivePty } from './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' +import '../orca-runtime-test-mocks/setup.spec' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { HEADLESS_LEAF_ID, RESTORED_AUTHORITY_TOKEN, RESTORED_AUTHORITY_TOKEN_HASH, - TEST_REPO_ID, TEST_WINDOW_ID, TEST_WORKTREE_ID, TEST_WORKTREE_PATH, @@ -22,97 +21,6 @@ import { spawnedPtyEnv } from '../terminal/launch/spawned-pty-env-fixtures' import '../../../shared/jcode-runtime-dir' describe('OrcaRuntimeService', () => { - it('refuses a requested shell the execution host cannot apply instead of spawning its default', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'pty-unreachable-shell' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - - // Host platform here is POSIX, which has no Windows shell to pick. - await expect( - runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { shellOverride: 'cmd.exe' }) - ).rejects.toThrow(/--shell cmd\.exe names a Windows shell/) - expect(spawn).not.toHaveBeenCalled() - }) - - it('quotes the agent startup command for the requested shell, not the host default', async () => { - const hostPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - try { - const spawn = vi.fn().mockResolvedValue({ id: 'pty-shell-quoting' }) - const runtime = new OrcaRuntimeService({ - ...store, - getSettings: () => ({ - ...store.getSettings(), - disabledTuiAgents: [], - terminalWindowsShell: 'powershell.exe', - agentCmdOverrides: {}, - agentDefaultArgs: { claude: '--dangerously-skip-permissions' }, - agentDefaultEnv: {} - }) - }) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'claude' }) - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude', - shellOverride: 'cmd.exe' - }) - - // Quote for the selected shell, even when Settings names a different Windows default. - expect(spawn).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ command: "claude '--dangerously-skip-permissions'" }) - ) - expect(spawn).toHaveBeenNthCalledWith( - 2, - expect.objectContaining({ - shellOverride: 'cmd.exe', - command: 'claude "--dangerously-skip-permissions"' - }) - ) - } finally { - Object.defineProperty(process, 'platform', hostPlatform) - } - }) - - it('refuses a requested shell with no workspace instead of creating a default-shell tab', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'pty-no-workspace-shell' }) - const send = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - electronMocks.BrowserWindow.fromId.mockReturnValue({ - isDestroyed: () => false, - webContents: { send } - }) - - await expect(runtime.createTerminal(undefined, { shellOverride: 'cmd.exe' })).rejects.toThrow( - /--shell cmd\.exe needs a workspace/ - ) - expect(send).not.toHaveBeenCalled() - expect(spawn).not.toHaveBeenCalled() - }) - it('retires inherited launch authority when the agent command exits', async () => { const spawn = vi.fn().mockResolvedValue({ id: 'pty-authority', incarnationId: 'process-1' }) const retireAuthority = vi.fn() @@ -375,60 +283,4 @@ describe('OrcaRuntimeService', () => { }) ).toBeNull() }) - - it('keeps restored receipts outside a targeted worktree scan', async () => { - const secondWorktreeId = `${TEST_REPO_ID}::/tmp/worktree-b` - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { - id: 'pty-moved', - incarnationId: 'inc-moved', - terminalHandle: 'term_moved', - title: 'Moved', - cwd: '/tmp/worktree-b', - worktreeId: secondWorktreeId, - wslDistro: null - }, - { - id: 'pty-second', - incarnationId: 'inc-second', - terminalHandle: 'term_second', - title: 'Second', - cwd: '/tmp/worktree-b', - worktreeId: secondWorktreeId, - wslDistro: null - } - ] - }) - const receipts = ( - runtime as unknown as { - restoredOrchestrationAuthorityByPtyId: Map> - } - ).restoredOrchestrationAuthorityByPtyId - receipts.set('pty-moved', { - ptyId: 'pty-moved', - worktreeId: TEST_WORKTREE_ID, - terminalHandle: 'term_moved', - paneKey: makePaneKey('moved-tab', HEADLESS_LEAF_ID), - processIncarnation: 'pty-moved:inc-moved', - hostScope: { kind: 'local', hostId: 'local' } - }) - receipts.set('pty-second', { - ptyId: 'pty-second', - worktreeId: secondWorktreeId, - terminalHandle: 'term_second', - paneKey: makePaneKey('second-tab', HEADLESS_LEAF_ID), - processIncarnation: 'pty-second:inc-second', - hostScope: { kind: 'local', hostId: 'local' } - }) - - await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - - expect(receipts.has('pty-moved')).toBe(false) - expect(receipts.has('pty-second')).toBe(true) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts index 5f14b236f98..75a94bd28ef 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts @@ -4,196 +4,6 @@ import { OrcaRuntimeService } from '../orca-runtime' import { TEST_WORKTREE_PATH, store, syncSinglePty } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('lets Claude agents pane titles override stale live-leaf title status', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude working' }) - runtime.onPtyData('pty-1', '\x1b]0;claude working\x07', 100) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude agents' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - it('lets Claude agents OSC titles override stale live-leaf pane titles', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude working' }) - runtime.onPtyData('pty-1', '\x1b]0;claude agents\x07', 100) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - it('does not let stale tab-level Claude agents titles suppress current pane activity', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - syncSinglePty(runtime, 'pty-1', { - tabTitle: 'claude agents', - paneTitle: 'claude working' - }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(true) - }) - - it('does not let stale live-leaf status override current neutral pane titles', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude working' }) - runtime.onPtyData('pty-1', '\x1b]0;claude working\x07', 100) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'bash' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - it('does not expose stale live-leaf agent status after Claude agents title supersedes it', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude working' }) - runtime.onPtyData('pty-1', '\x1b]0;claude working\x07', 100) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude agents' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.getAgentStatusForHandle(terminal.handle)).resolves.toBeNull() - }) - - it('does not let stale Claude agents OSC titles suppress current pane activity', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude agents' }) - runtime.onPtyData('pty-1', '\x1b]0;claude agents\x07', 100) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'claude working' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(true) - }) - - it('lets adopted pane Claude agents titles override stale PTY-handle activity', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude', - title: 'claude working' - }) - runtime.onPtyData('pty-bg', '\x1b]0;claude working\x07', 100) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'claude agents' }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) - - it('lets adopted neutral pane titles override stale PTY-handle activity', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude', - title: 'claude working' - }) - runtime.onPtyData('pty-bg', '\x1b]0;claude working\x07', 100) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'bash' }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) - - it('does not poll a wrapper foreground for a speculative CLI prompt send', async () => { - const getForegroundProcess = vi - .fn() - .mockResolvedValueOnce('node') - .mockResolvedValueOnce('codex') - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'bash', - title: 'bash' - }) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'bash' }) - - await expect( - runtime.isTerminalRunningAgent(handle, { retryForegroundWrappers: false }) - ).resolves.toBe(false) - expect(getForegroundProcess).toHaveBeenCalledTimes(1) - }) - - it.each(['orca', 'acli', 'cn', 'vibe'])( - 'keeps direct input for a bare %s foreground that may be an ordinary tool', - async (processName) => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => processName - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'bash' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningSettledPromptAgent(terminal.handle)).resolves.toBe( - false - ) - } - ) - - it('keeps stale Codex launch identity on legacy delivery after the shell returns', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'zsh' - }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - title: 'Codex working', - launchAgent: 'codex' - }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - await expect(runtime.isTerminalRunningSettledPromptAgent(handle)).resolves.toBe(false) - }) - it('waits for delayed wrapper foreground cache enrichment', async () => { const getForegroundProcess = vi.fn(async () => (Date.now() >= 4_000 ? 'codex' : 'node')) const runtime = new OrcaRuntimeService(store) @@ -223,165 +33,4 @@ describe('OrcaRuntimeService', () => { vi.useRealTimers() } }) - - it('does not recognize unresolved wrapper foregrounds as running agents', async () => { - const getForegroundProcess = vi.fn().mockResolvedValue('node') - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'bash', - title: 'bash' - }) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'bash' }) - - vi.useFakeTimers() - try { - const result = runtime.isTerminalRunningAgent(handle) - await vi.advanceTimersByTimeAsync(7_000) - - await expect(result).resolves.toBe(false) - expect(getForegroundProcess.mock.calls.length).toBeGreaterThan(2) - } finally { - vi.useRealTimers() - } - }) - - it('keeps Claude management titles suppressed after wrapper foreground refreshes', async () => { - const getForegroundProcess = vi - .fn() - .mockResolvedValueOnce('node') - .mockResolvedValueOnce('claude') - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'claude agents' }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - expect(getForegroundProcess).toHaveBeenCalledTimes(2) - }) - - it('lets adopted Claude agents pane titles use non-Claude foreground fallback', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'codex' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'claude agents' }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('keeps ready prompt evidence when an adopted pane title is neutral', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - title: 'Codex working' - }) - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'bash' }) - runtime.onPtyData( - 'pty-bg', - ['OpenAI Codex', 'Model: gpt-5.4', 'Directory: /tmp/worktree-a'].join('\n'), - 100 - ) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('lets adopted pane agent titles override stale PTY Claude agents titles', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - runtime.onPtyData('pty-bg', '\x1b]0;claude agents\x07', 100) - - syncSinglePty(runtime, 'pty-bg', { paneTitle: 'claude working' }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('recognizes fresh runtime-created agent OSC titles over stale Claude agents launch titles', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - runtime.onPtyData('pty-bg', '\x1b]0;claude working\x07', 100) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('keeps Claude agents management evidence when controller refresh reports a Claude process title', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude', - listProcesses: async () => [{ id: 'pty-bg', cwd: TEST_WORKTREE_PATH, title: 'claude' }] - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - - await runtime.getWorktreePs() - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts deleted file mode 100644 index d3400e95011..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts +++ /dev/null @@ -1,482 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' -import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' -import { - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - antigravityPromptBeforeModelReadyScreen, - antigravityReadyScreen, - store -} from './orca-runtime-test-fixtures.spec' - -describe('OrcaRuntimeService', () => { - it('allows non-Claude foreground agents after preserved Claude agents management evidence', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'codex', - listProcesses: async () => [{ id: 'pty-bg', cwd: TEST_WORKTREE_PATH, title: 'zsh' }] - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - - await runtime.getWorktreePs() - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('does not let stale PTY status override a fresh neutral PTY title', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude', - title: 'Claude working' - }) - runtime.onPtyData('pty-bg', '\x1b]0;Claude working\x07', 100) - runtime.onPtyData('pty-bg', '\x1b]0;zsh\x07', 101) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) - - it('recognizes ready prompt evidence even with a stale Claude agents title', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - - runtime.onPtyData( - 'pty-bg', - ['OpenAI Codex', 'Model: gpt-5.4', 'Directory: /tmp/worktree-a'].join('\n'), - 100 - ) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('recognizes Antigravity ready tails with the prompt before the model line', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'agy', - title: 'worker' - }) - - runtime.onPtyData('pty-bg', antigravityPromptBeforeModelReadyScreen(), 100) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('does not recognize partial Antigravity startup output as an agent', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'agy', - title: 'worker' - }) - - runtime.onPtyData( - 'pty-bg', - [ - 'Antigravity CLI 1.0.3', - 'user@example.com (Antigravity Business)', - 'Gemini 3.5 Flash (High)' - ].join('\n'), - 100 - ) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) - - it('uses the latest Antigravity header when checking readiness', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'agy', - title: 'worker' - }) - - runtime.onPtyData( - 'pty-bg', - [ - antigravityReadyScreen(), - '\nAntigravity CLI 1.0.4\n', - 'user@example.com (Antigravity Business)\n', - 'Gemini 4 Experimental (High)\n', - 'Do you trust this workspace directory?\n' - ].join(''), - 100 - ) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) - - it('recognizes Antigravity prompts written as the current partial line', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'agy', - title: 'worker' - }) - - runtime.onPtyData( - 'pty-bg', - [ - 'Antigravity CLI 1.0.3\n', - 'user@example.com (Antigravity Business)\n', - 'Gemini 3.5 Flash (High)\n', - '~/orca/workspaces/orca/agy-dispatch-issue\n' - ].join(''), - 100 - ) - runtime.onPtyData('pty-bg', ' > ', 101) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(true) - }) - - it('does not classify agy workspace paths or titles without the ready prompt', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: '/tmp/agy-workspace', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'pty-1', - paneTitle: '/tmp/agy-workspace' - } - ] - }) - runtime.onPtyData('pty-1', 'cd /tmp/agy-workspace\n', 100) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - it('keeps mobile terminal surfaces pending while a live leaf has no PTY', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Terminal 1', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: null, - paneTitle: 'Terminal 1' - } - ], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'tab-1::pane:1', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: 'tab-1::pane:1', - parentTabId: 'tab-1', - leafId: 'pane:1', - title: 'Terminal 1', - isActive: true - } - ] - } - ] - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result.tabs).toEqual([ - expect.objectContaining({ - type: 'terminal', - id: 'tab-1::pane:1', - status: 'pending-handle', - terminal: null - }) - ]) - }) - - it('selects a visible active pane when terminal visual layout prunes a stale leaf', async () => { - const runtime = new OrcaRuntimeService(store) - const parentLayout: TerminalLayoutSnapshot = { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: 'pane:1' }, - second: { type: 'leaf', leafId: 'pane:2' } - }, - activeLeafId: 'pane:1', - expandedLeafId: null, - ptyIdsByLeafId: { 'pane:2': 'pty-2' } - } - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Split terminal', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId: 'pane:2', - paneRuntimeId: 2, - ptyId: 'pty-2', - paneTitle: 'Live pane' - } - ], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'tab-1::pane:1', - activeTabType: 'terminal', - tabGroups: [ - { - id: 'group-1', - activeTabId: 'missing-tab', - tabOrder: ['missing-tab', 'tab-1'] - } - ], - tabs: [ - { - type: 'terminal', - id: 'tab-1::pane:1', - parentTabId: 'tab-1', - leafId: 'pane:1', - title: 'Stale pane', - parentLayout, - isActive: true - }, - { - type: 'terminal', - id: 'tab-1::pane:2', - parentTabId: 'tab-1', - leafId: 'pane:2', - title: 'Live pane', - parentLayout, - isActive: false - } - ] - } - ] - }) - - const result = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - - expect(result.visualLayouts).toMatchObject([ - { - worktreeId: TEST_WORKTREE_ID, - root: { - type: 'group', - activeTabId: 'tab-1', - tabs: [ - { - tabId: 'tab-1', - activeLeafId: 'pane:2', - panes: { - type: 'terminal', - leafId: 'pane:2', - active: true - } - } - ] - } - } - ]) - }) - - it('keeps renderer browser tabs without live webContents but filters stale headless tabs', async () => { - const runtime = new OrcaRuntimeService(store) - const tabList = vi.fn(() => ({ - tabs: [ - { - browserPageId: 'browser-page-live', - index: 0, - url: 'https://live.example/', - title: 'Live Browser', - active: true - } - ] - })) - runtime.setAgentBrowserBridge({ tabList } as never) - electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'browser-unified-stale', - activeTabType: 'browser', - tabs: [ - { - type: 'browser', - id: 'browser-unified-stale', - title: 'Dead Browser', - browserWorkspaceId: 'browser-workspace-stale', - browserPageId: 'browser-page-stale', - url: 'about:blank', - loading: false, - canGoBack: false, - canGoForward: false, - isActive: true - }, - { - type: 'browser', - id: 'browser-unified-live', - title: 'Stale Title', - browserWorkspaceId: 'browser-workspace-live', - browserPageId: 'browser-page-live', - url: 'https://stale.example/', - loading: false, - canGoBack: false, - canGoForward: false, - isActive: false - } - ] - } - ] - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(tabList).toHaveBeenCalledWith(TEST_WORKTREE_ID) - expect(result.tabs).toEqual([ - expect.objectContaining({ - type: 'browser', - id: 'browser-unified-stale', - browserPageId: 'browser-page-stale', - url: 'about:blank', - title: 'Dead Browser', - isActive: true - }), - expect.objectContaining({ - type: 'browser', - id: 'browser-unified-live', - browserPageId: 'browser-page-live', - url: 'https://live.example/', - title: 'Live Browser', - isActive: false - }) - ]) - expect(result.activeTabId).toBe('browser-unified-stale') - expect(result.activeTabType).toBe('browser') - - const rendererSnapshot = runtime['mobileSessionTabsByWorktree'].get(TEST_WORKTREE_ID)! - expect([...runtime['collectPublicMobileSessionTabIds'](rendererSnapshot)]).toEqual([ - 'browser-unified-stale', - 'browser-workspace-stale', - 'browser-unified-live', - 'browser-workspace-live' - ]) - - const headlessSnapshot = { ...rendererSnapshot, publicationEpoch: 'headless:epoch-1' } - runtime['mobileSessionTabsByWorktree'].set(TEST_WORKTREE_ID, headlessSnapshot) - const headlessResult = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(headlessResult.tabs).toEqual([ - expect.objectContaining({ - type: 'browser', - id: 'browser-unified-live', - browserPageId: 'browser-page-live', - url: 'https://live.example/', - title: 'Live Browser', - isActive: false - }) - ]) - expect(headlessResult.activeTabId).toBeNull() - expect(headlessResult.activeTabType).toBeNull() - expect([...runtime['collectPublicMobileSessionTabIds'](headlessSnapshot)]).toEqual([ - 'browser-unified-live', - 'browser-workspace-live' - ]) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts index 9fcfa73447a..72909542797 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts @@ -1,82 +1,11 @@ import type { AdoptStablePaneArgs, AdoptStablePaneResult } from '../../ipc/pty/ipc/spawn-types' import { describe, expect, it, vi } from 'vitest' -import { committingSpawn } from './bind-first-pane.test-fixture' +import './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { HEADLESS_LEAF_ID, TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('does not let the active browser webContents steal session focus from terminals', async () => { - const runtime = new OrcaRuntimeService(store) - const tabList = vi.fn(() => ({ - tabs: [ - { - browserPageId: 'browser-page-1', - index: 0, - url: 'https://example.com/', - title: 'Live Browser', - active: true - } - ] - })) - runtime.setAgentBrowserBridge({ tabList } as never) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'terminal-tab::pane:1', - activeTabType: 'terminal', - tabs: [ - { - type: 'browser', - id: 'browser-unified-1', - title: 'Stale Browser', - browserWorkspaceId: 'browser-workspace-1', - browserPageId: 'browser-page-1', - url: 'https://stale.example/', - loading: false, - canGoBack: false, - canGoForward: false, - isActive: false - }, - { - type: 'terminal', - id: 'terminal-tab::pane:1', - parentTabId: 'terminal-tab', - leafId: 'pane:1', - title: 'Terminal 2', - isActive: true - } - ] - } - ] - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result.activeTabId).toBe('terminal-tab::pane:1') - expect(result.activeTabType).toBe('terminal') - expect(result.tabs).toEqual([ - expect.objectContaining({ - type: 'browser', - id: 'browser-unified-1', - isActive: false, - title: 'Live Browser' - }), - expect.objectContaining({ - type: 'terminal', - id: 'terminal-tab::pane:1', - isActive: true - }) - ]) - }) - it.each([ { behavior: 'fills a missing renderer session', @@ -199,43 +128,6 @@ describe('OrcaRuntimeService', () => { } ) - it('normalizes Pi-compatible mobile session status to OMP for an unknown-launch foreground omp PTY', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'pty-typed-omp' }) - const getForegroundProcess = vi.fn(async () => 'omp') - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess - }) - const terminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'typed-omp-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - - runtime.onPtyData('pty-typed-omp', '\x1b]0;Pi ready\x07', 123) - await new Promise((resolve) => setImmediate(resolve)) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(getForegroundProcess).toHaveBeenCalledWith('pty-typed-omp') - expect(result.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - title: 'OMP ready', - agentStatus: expect.objectContaining({ - state: 'done', - agentType: 'omp', - terminalHandle: terminal.handle, - terminalTitle: 'OMP ready' - }) - }) - ) - expect(result.tabs[0]).not.toHaveProperty('launchAgent') - }) - it('preserves host metadata when terminal.create adopts a stable pane owner', async () => { const adoptStablePane = vi.fn( async (args: AdoptStablePaneArgs): Promise => { @@ -313,35 +205,6 @@ describe('OrcaRuntimeService', () => { expect(spawn).toHaveBeenCalledOnce() }) - it('releases a stable-pane claim when creation aborts before provider spawn', async () => { - const releaseClaim = vi.fn() - const spawn = vi.fn() - const adoptStablePane = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - claimStablePaneCreate: vi.fn(() => releaseClaim), - adoptStablePane, - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - const abort = new AbortController() - abort.abort() - - await expect( - runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'aborted-stable-pane', - leafId: HEADLESS_LEAF_ID, - signal: abort.signal - }) - ).rejects.toThrow('client_disconnected') - - expect(spawn).not.toHaveBeenCalled() - expect(adoptStablePane).not.toHaveBeenCalled() - expect(releaseClaim).toHaveBeenCalledOnce() - }) - it('refuses before spawning when the client disconnects during pane adoption', async () => { const abort = new AbortController() const spawn = vi.fn() diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts index 154804a6e84..1121373b8c0 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts @@ -1,12 +1,13 @@ +import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' import { describe, expect, it, vi } from 'vitest' import { committingSpawn } from './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../shared/agent-status/contracts/agent-status-freshness' +import '../../../shared/agent-status/contracts/agent-status-freshness' import { OrcaRuntimeService } from '../orca-runtime' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import '../../../shared/workspace-layout/stable-pane-id' import '../orca-runtime-test-mocks/setup.spec' import { waitForMobileSessionTabsEvents } from './mobile-session-tab-event-wait' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' + import { HEADLESS_LEAF_ID, TEST_WORKTREE_ID, @@ -15,247 +16,6 @@ import { } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('publishes hook-only identity for a pane that never emitted an agent title', async () => { - // Hook-only agents can have no launchAgent or OSC status; do not gate their hook read on either. - const paneKey = makePaneKey('quiet-tab', HEADLESS_LEAF_ID) - const providerSession = { - key: 'session_id' as const, - id: 'b91c7e40-5a2d-4f19-9c33-2a7b6e5d4c88', - transcriptPath: '/transcripts/b91c7e40.jsonl' - } - const runtime = new OrcaRuntimeService(store, undefined, { - getAgentStatusSnapshot: () => [ - { - paneKey, - state: 'done', - prompt: 'Hi', - agentType: 'claude', - connectionId: null, - receivedAt: Date.now(), - stateStartedAt: Date.now(), - tabId: 'quiet-tab', - worktreeId: TEST_WORKTREE_ID, - providerSession - } - ] - }) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-quiet' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'quiet-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - agentStatus: expect.objectContaining({ agentType: 'claude', providerSession }) - }) - ) - }) - - it('reads a resume-identity-only row the live-agent snapshot filters out', async () => { - // Pi session-only rows are excluded from running status but still carry the transcript native chat needs. - const paneKey = makePaneKey('pi-tab', HEADLESS_LEAF_ID) - const providerSession = { - key: 'session_id' as const, - id: '/sessions/pi-1.json', - transcriptPath: '/sessions/pi-1.json' - } - const now = Date.now() - const runtime = new OrcaRuntimeService(store, undefined, { - getAgentProviderSessionSnapshot: () => [ - { - paneKey, - state: 'done', - prompt: '', - agentType: 'pi', - connectionId: null, - receivedAt: now + 1, - stateStartedAt: now + 1, - tabId: 'pi-tab', - worktreeId: TEST_WORKTREE_ID, - providerSession, - providerSessionOnly: true - } - ] - }) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-pi' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'pi-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - agentStatus: expect.objectContaining({ agentType: 'pi', providerSession }) - }) - ) - }) - - it('does not let stale Pi resume metadata claim a plain terminal', async () => { - const paneKey = makePaneKey('stale-pi-tab', HEADLESS_LEAF_ID) - const runtime = new OrcaRuntimeService(store, undefined, { - getAgentProviderSessionSnapshot: () => [ - { - paneKey, - state: 'done', - prompt: '', - agentType: 'pi', - connectionId: null, - receivedAt: Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1, - stateStartedAt: Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1, - tabId: 'stale-pi-tab', - worktreeId: TEST_WORKTREE_ID, - providerSession: { - key: 'session_id', - id: '/sessions/stale-pi.json', - transcriptPath: '/sessions/stale-pi.json' - }, - providerSessionOnly: true - } - ] - }) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-stale-pi' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'stale-pi-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - agentStatus: expect.not.objectContaining({ agentType: 'pi' }) - }) - ) - }) - - it('does not claim a stale hook agent owns a pane whose agent has since exited', async () => { - // Retained status must not offer native chat for an agent that exited to its shell. - const paneKey = makePaneKey('exited-tab', HEADLESS_LEAF_ID) - const staleReceivedAt = Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1_000 - const runtime = new OrcaRuntimeService(store, undefined, { - getAgentStatusSnapshot: () => [ - { - paneKey, - state: 'done', - prompt: 'Hi', - agentType: 'claude', - connectionId: null, - receivedAt: staleReceivedAt, - stateStartedAt: staleReceivedAt, - tabId: 'exited-tab', - worktreeId: TEST_WORKTREE_ID, - providerSession: { - key: 'session_id' as const, - id: 'd4c3b2a1-0000-4000-8000-000000000001', - transcriptPath: '/transcripts/d4c3b2a1.jsonl' - } - } - ] - }) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-exited' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'exited-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - - runtime.onPtyData('pty-exited', '\x1b]0;✳ Claude Code\x07', 123) - await new Promise((resolve) => setImmediate(resolve)) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - const tab = result.tabs[0] - expect(tab?.type).toBe('terminal') - const agentStatus = tab && 'agentStatus' in tab ? tab.agentStatus : null - expect(agentStatus?.agentType ?? null).toBeNull() - }) - - it('keeps decorative Pi frames queued behind the foreground owner probe', async () => { - const foregroundProcess = deferred() - const spawn = vi.fn().mockResolvedValue({ id: 'pty-typed-omp' }) - const getForegroundProcess = vi.fn(() => foregroundProcess.promise) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess - }) - const terminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'typed-omp-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - runtime.onPtyData('pty-typed-omp', '\x1b]0;⠋ Pi\x07', 123) - await new Promise((resolve) => setImmediate(resolve)) - runtime.onPtyData('pty-typed-omp', '\x1b]0;⠙ Pi\x07', 124) - await new Promise((resolve) => setImmediate(resolve)) - - expect(getForegroundProcess).toHaveBeenCalledTimes(1) - expect(events).toHaveLength(0) - - foregroundProcess.resolve('omp') - await new Promise((resolve) => setImmediate(resolve)) - await waitForMobileSessionTabsEvents(events, 1) - - expect(events).toEqual([ - expect.objectContaining({ - tabs: [ - expect.objectContaining({ - type: 'terminal', - title: '⠋ OMP', - agentStatus: expect.objectContaining({ - state: 'working', - agentType: 'omp', - terminalHandle: terminal.handle, - terminalTitle: '⠋ OMP' - }) - }) - ] - }) - ]) - - runtime.onPtyData('pty-typed-omp', '\x1b]0;⠹ Pi\x07', 125) - await new Promise((resolve) => setImmediate(resolve)) - expect(events).toHaveLength(1) - - unsubscribe() - }) - it('coalesces same-status title frames behind one post-title foreground probe', async () => { const staleForegroundProcess = deferred() const freshForegroundProcess = deferred() @@ -318,68 +78,4 @@ describe('OrcaRuntimeService', () => { unsubscribe() }) - - it('starts a post-title foreground probe when an older pending probe finds no owner', async () => { - const staleForegroundProcess = deferred() - const freshForegroundProcess = deferred() - const spawn = vi.fn().mockResolvedValue({ id: 'pty-typed-omp' }) - const getForegroundProcess = vi - .fn() - .mockReturnValueOnce(staleForegroundProcess.promise) - .mockReturnValueOnce(freshForegroundProcess.promise) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess - }) - const terminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'typed-omp-tab', - leafId: HEADLESS_LEAF_ID, - title: 'Terminal' - }) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - ;( - runtime as unknown as { - refreshPtyForegroundAgentFromController: (ptyId: string) => Promise - } - ).refreshPtyForegroundAgentFromController('pty-typed-omp') - runtime.onPtyData('pty-typed-omp', '\x1b]0;Pi ready\x07', 123) - await new Promise((resolve) => setImmediate(resolve)) - - expect(getForegroundProcess).toHaveBeenCalledTimes(1) - expect(events).toHaveLength(0) - - staleForegroundProcess.resolve(null) - await new Promise((resolve) => setImmediate(resolve)) - - expect(getForegroundProcess).toHaveBeenCalledTimes(2) - expect(events).toHaveLength(0) - - freshForegroundProcess.resolve('omp') - await new Promise((resolve) => setImmediate(resolve)) - await waitForMobileSessionTabsEvents(events, 1) - - expect(events).toEqual([ - expect.objectContaining({ - tabs: [ - expect.objectContaining({ - type: 'terminal', - title: 'OMP ready', - agentStatus: expect.objectContaining({ - state: 'done', - agentType: 'omp', - terminalHandle: terminal.handle, - terminalTitle: 'OMP ready' - }) - }) - ] - }) - ]) - - unsubscribe() - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec.ts deleted file mode 100644 index 7e700f6774e..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' - -describe('OrcaRuntimeService', () => { - it('reattaches mobile terminal surfaces from saved PTY bindings when the PTY is connected', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Terminal 1', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'daemon-pty-1' - } - ] - }) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'tab-1::pane:1', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: 'tab-1::pane:1', - parentTabId: 'tab-1', - leafId: 'pane:1', - title: 'Terminal 1', - ptyId: 'daemon-pty-1', - isActive: true - } - ] - } - ] - }) - - const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(result.tabs).toEqual([ - expect.objectContaining({ - type: 'terminal', - id: 'tab-1::pane:1', - status: 'ready', - terminal: expect.stringMatching(/^term_/) - }) - ]) - expect(runtime.resolveLeafForHandle((result.tabs[0] as { terminal: string }).terminal)).toEqual( - { ptyId: 'daemon-pty-1' } - ) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts index 21835c3448c..e298ede2079 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts @@ -1,9 +1,9 @@ import { withDurableRuntimeStore } from './runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' -import { registerLivePty } from './bind-first-pane.test-fixture' +import './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { advertisedUrlWatcher } from '../../ports/advertised-url-watcher' +import '../../ports/advertised-url-watcher' import { getDefaultWorkspaceSession } from '../../../shared/constants' import { HEADLESS_LEAF_ID, @@ -11,8 +11,7 @@ import { TEST_WORKTREE_ID, TEST_WORKTREE_PATH, makeRuntimeStoreWithWorkspaceSession, - store, - syncSinglePty + store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { @@ -64,72 +63,6 @@ describe('OrcaRuntimeService', () => { }) }) - it('rejects a proposed visual surface occupied by a different PTY', async () => { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession({ - ...getDefaultWorkspaceSession(), - tabsByWorktree: { [TEST_WORKTREE_ID]: [] } - }) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }) - ) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'occupied-tab', - worktreeId: TEST_WORKTREE_ID, - title: 'occupied', - activeLeafId: HEADLESS_LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: 'occupied-tab', - worktreeId: TEST_WORKTREE_ID, - leafId: HEADLESS_LEAF_ID, - paneRuntimeId: 1, - ptyId: 'visual-pty' - } - ] - }) - registerLivePty(runtime, 'visual-pty', TEST_WORKTREE_ID, null, { - tabId: 'occupied-tab', - leafId: HEADLESS_LEAF_ID - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { - id: 'orphan-pty', - incarnationId: 'inc-orphan', - terminalHandle: 'term_orphan', - title: 'orphan', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } - ] - }) - - await expect( - runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 0, - claims: [ - { - terminal: 'term_orphan', - ptyId: 'orphan-pty', - incarnationId: 'inc-orphan', - tabId: 'occupied-tab', - leafId: HEADLESS_LEAF_ID - } - ] - }) - ).rejects.toThrow('terminal_orphan_surface_occupied') - }) - it('rejects ambiguous duplicate persisted bindings before idempotence', async () => { const duplicateTab = (id: string) => ({ id, @@ -240,80 +173,6 @@ describe('OrcaRuntimeService', () => { expect(writesByPty.has('pty-imposter')).toBe(false) }) - it('keeps an already-bound terminal handle when discovery reports a different exported one', async () => { - const runtime = new OrcaRuntimeService(store) - const writes: string[] = [] - runtime.setPtyController({ - write: (_ptyId, data) => { - writes.push(data) - return true - }, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { - id: 'pty-1', - cwd: TEST_WORKTREE_PATH, - title: 'claude', - terminalHandle: 'term_from_env' - } - ] - }) - runtime.registerPreAllocatedHandleForPty('pty-1', 'term_already_bound') - - const listed = await runtime.listTerminals() - expect(listed.terminals[0]?.handle).toBe('term_already_bound') - await expect( - runtime.sendTerminal('term_already_bound', { text: 'still routed' }, { inputKind: 'driving' }) - ).resolves.toMatchObject({ accepted: true }) - expect(writes).toEqual(['still routed']) - await expect(runtime.readTerminal('term_from_env')).rejects.toThrow() - }) - - it('binds advertised URLs for renderer-restored PTYs that skip registerPty', () => { - const runtime = new OrcaRuntimeService(store) - - syncSinglePty(runtime, 'pty-restored') - runtime.onPtyData('pty-restored', 'Network: https://restored.example.com:3001/\n', 100) - - expect(advertisedUrlWatcher.lookup(TEST_WORKTREE_ID, 3001)?.origin).toBe( - 'https://restored.example.com:3001' - ) - }) - - it('keeps preallocated terminal handles valid when a reload graph omits the live leaf', async () => { - const runtime = new OrcaRuntimeService(store) - const handle = runtime.preAllocateHandleForPty('pty-1') - - syncSinglePty(runtime) - runtime.markRendererReloading(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [] - }) - runtime.onPtyData('pty-1', 'after omitted leaf\n', 100) - - const read = await runtime.readTerminal(handle) - expect(read.tail).toEqual(['after omitted leaf']) - }) - - it('keeps preallocated terminal handles valid after graph unavailable during reload', async () => { - const runtime = new OrcaRuntimeService(store) - const handle = runtime.preAllocateHandleForPty('pty-1') - - syncSinglePty(runtime) - runtime.markGraphUnavailable(1) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [], - leaves: [] - }) - runtime.onPtyData('pty-1', 'after unavailable\n', 100) - - const read = await runtime.readTerminal(handle) - expect(read.tail).toEqual(['after unavailable']) - }) - it('keeps runtime-created PTY handles valid after graph unavailable', async () => { const writes: string[] = [] const runtime = new OrcaRuntimeService(store) @@ -404,150 +263,4 @@ describe('OrcaRuntimeService', () => { }) expect(runtime.getTerminalProcessIncarnation(created.handle)).not.toBe(before) }) - - it('does not authorize an OpenCode marker left on a shell pane', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'zsh' - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'OC | zsh' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({ - handle: terminal.handle, - isRunningAgent: false, - status: null - }) - }) - - it('authorizes a hookless OpenCode marker with an OpenCode foreground process', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'opencode' - }) - syncSinglePty(runtime, 'pty-1', { paneTitle: 'OC | Native session' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(true) - await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({ - handle: terminal.handle, - isRunningAgent: true, - status: 'idle' - }) - }) - - it('does not authorize an OpenCode marker left on a runtime PTY shell', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'zsh' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'bash', - title: 'OC | zsh' - }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - await expect(runtime.getTerminalAgentStatus(handle)).resolves.toEqual({ - handle, - isRunningAgent: false, - status: null - }) - }) - - // Without a PTY, foreground corroboration is unreachable and the bare title is insufficient. - it('does not treat a bare Cursor title as an agent on a leaf with no pty', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'cursor-agent' - }) - syncSinglePty(runtime, null, { tabTitle: 'bash', paneTitle: 'Cursor Agent' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - // A renderer can push a bare Cursor title over stale working status; neither proves a live agent. - it('does not let a renderer-pushed bare Cursor title revive stale agent status', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'zsh' - }) - syncSinglePty(runtime, 'pty-1', { tabTitle: '' }) - runtime.onPtyData('pty-1', '\x1b]0;⠋ Cursor Agent\x07', 100) - syncSinglePty(runtime, 'pty-1', { tabTitle: '', paneTitle: 'Cursor Agent' }) - const [terminal] = (await runtime.listTerminals()).terminals - - expect(terminal.title).toBe('Cursor Agent') - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - // Exercise the outer catch; production providers normalize foreground failures to null. - it('does not treat a bare Cursor title as an agent when the foreground read throws', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => { - throw new Error('ssh channel closed') - } - }) - syncSinglePty(runtime, 'pty-1', { tabTitle: '', paneTitle: 'Cursor Agent' }) - const [terminal] = (await runtime.listTerminals()).terminals - - await expect(runtime.isTerminalRunningAgent(terminal.handle)).resolves.toBe(false) - }) - - // node plus a Cursor title is insufficient unless the wrapper retry resolves cursor-agent. - it('does not treat a bare Cursor title as an agent behind a wrapper foreground', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'node' - }) - syncSinglePty(runtime, 'pty-1', { tabTitle: '', paneTitle: 'Cursor Agent' }) - const [terminal] = (await runtime.listTerminals()).terminals - - const running = runtime.isTerminalRunningAgent(terminal.handle) - await vi.advanceTimersByTimeAsync(7_000) - await expect(running).resolves.toBe(false) - } finally { - vi.useRealTimers() - } - }) - - it('does not recognize runtime-created Claude agents management screens as agents', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - - const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'claude agents', - title: 'claude agents' - }) - - await expect(runtime.isTerminalRunningAgent(handle)).resolves.toBe(false) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts index cda936e93ce..bd369a56753 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts @@ -12,64 +12,6 @@ import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import '../orca-runtime' describe('OrcaRuntimeService', () => { - it('keeps a no-incarnation handle across an in-graph pane remint', async () => { - const runtime = createRuntime() - const tabId = 'tab-1' - // No preallocated handle or incarnation id: the live PTY itself is the continuity proof within this graph. - runtime.attachWindow(TEST_WINDOW_ID) - runtime.syncWindowGraph(TEST_WINDOW_ID, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'Shell', - activeLeafId: 'leaf-old', - layout: null - } - ], - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: 'leaf-old', - paneRuntimeId: 1, - ptyId: 'pty-plain' - } - ] - }) - const before = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - expect(before.terminals).toHaveLength(1) - const stableHandle = before.terminals[0].handle - const waiting = runtime.waitForTerminal(stableHandle, { condition: 'exit', timeoutMs: 30_000 }) - - runtime.syncWindowGraph(TEST_WINDOW_ID, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'Shell', - activeLeafId: 'leaf-new', - layout: null - } - ], - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: 'leaf-new', - paneRuntimeId: 2, - ptyId: 'pty-plain' - } - ] - }) - - const after = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - expect(after.terminals).toHaveLength(1) - expect(after.terminals[0].handle).toBe(stableHandle) - runtime.onPtyExit('pty-plain', 0) - await expect(waiting).resolves.toMatchObject({ handle: stableHandle, status: 'exited' }) - }) - it('keeps a live CLI waiter pending when a re-keyed shared handle transfers to the live leaf', async () => { const runtime = createRuntime() const tabId = 'tab-1' diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts index bab9686a29e..6b4348a9570 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts @@ -14,7 +14,6 @@ import { TEST_WINDOW_ID, TEST_WORKTREE_ID, createRuntime, - createRuntimeWithSshLease, store } from './orca-runtime-test-fixtures.spec' @@ -263,38 +262,6 @@ describe('OrcaRuntimeService', () => { expect(createTerminal).not.toHaveBeenCalled() }) - it('clears a failed pane recovery so a later reconnect can retry', async () => { - const tabId = 'tab-retry' - const runtime = createRuntimeWithSshLease('pty-expired', tabId) - const paneKey = makePaneKey(tabId, HEADLESS_LEAF_ID) - registerBoundPty(runtime, 'pty-expired', TEST_WORKTREE_ID, null, { - tabId, - leafId: HEADLESS_LEAF_ID - }) - const expiredHandle = runtime.resolveTerminalPane(paneKey, TEST_WORKTREE_ID).handle - await dropFromHostInventory(runtime, 'pty-expired') - const createTerminal = vi - .spyOn(runtime, 'createTerminal') - .mockRejectedValueOnce(new Error('relay_reconnecting')) - .mockResolvedValueOnce({ - handle: 'term-retry', - tabId, - paneKey, - ptyId: 'pty-retry', - worktreeId: TEST_WORKTREE_ID, - title: null, - surface: 'background' - }) - - await expect( - runtime.recoverTerminalPane(paneKey, TEST_WORKTREE_ID, expiredHandle) - ).rejects.toThrow('relay_reconnecting') - await expect( - runtime.recoverTerminalPane(paneKey, TEST_WORKTREE_ID, expiredHandle) - ).resolves.toMatchObject({ handle: 'term-retry' }) - expect(createTerminal).toHaveBeenCalledTimes(2) - }) - it('drops a stale leaf when a woken agent PTY is re-keyed to a new leaf on renderer reload', async () => { const runtime = createRuntime() const tabId = 'tab-1' @@ -355,40 +322,4 @@ describe('OrcaRuntimeService', () => { ptyId: 'pty-agent' }) }) - - it('still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY', async () => { - const runtime = createRuntime() - const tabId = 'tab-1' - runtime.preAllocateHandleForPty('pty-agent') - runtime.attachWindow(TEST_WINDOW_ID) - runtime.syncWindowGraph(TEST_WINDOW_ID, { - tabs: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - title: 'Claude', - activeLeafId: 'leaf-old', - layout: null - } - ], - leaves: [ - { - tabId, - worktreeId: TEST_WORKTREE_ID, - leafId: 'leaf-old', - paneRuntimeId: 1, - ptyId: 'pty-agent' - } - ] - }) - expect((await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`)).terminals).toHaveLength(1) - - // An empty reload graph must preserve the live CLI PTY and its exported handle. - runtime.markRendererReloading(TEST_WINDOW_ID) - runtime.syncWindowGraph(TEST_WINDOW_ID, { tabs: [], leaves: [] }) - - const after = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - expect(after.terminals).toHaveLength(1) - expect(after.terminals[0].ptyId).toBe('pty-agent') - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts index b595c323bea..df6f6c7286d 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts @@ -66,41 +66,6 @@ describe('OrcaRuntimeService', () => { expect(internals.ptysById.has('nested-controller-pty')).toBe(false) }) - it('matches explicit-id cwd PTYs when the resolved worktree cache is incomplete', async () => { - vi.mocked(listWorktrees).mockResolvedValueOnce([ - { - path: '/tmp/worktree-a/nested', - head: 'ghi', - branch: 'feature/nested', - isBare: false, - isMainWorktree: false - } - ]) - const runtime = createRuntime() - await runtime.listTerminals() - vi.mocked(listWorktrees).mockClear() - vi.mocked(listWorktrees).mockRejectedValue( - new Error('explicit-id fallback should not rescan worktrees') - ) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { id: 'cwd-only-pty', cwd: `${TEST_WORKTREE_PATH}/src`, title: 'cwd shell' }, - { id: 'nested-controller-pty', cwd: `${TEST_WORKTREE_PATH}/nested/src`, title: 'nested' } - ] - }) - - const terminals = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - - expect(listWorktrees).not.toHaveBeenCalled() - expect(terminals.terminals.map((terminal) => terminal.worktreeId)).toEqual([TEST_WORKTREE_ID]) - const internals = runtime as unknown as { ptysById: Map } - expect(internals.ptysById.has('cwd-only-pty')).toBe(true) - expect(internals.ptysById.has('nested-controller-pty')).toBe(false) - }) - it('keeps explicit-id cold-cache terminal lists from adopting nested worktree PTYs', async () => { const nestedWorktreeId = `${TEST_REPO_ID}::${TEST_WORKTREE_PATH}/nested` vi.mocked(listWorktrees).mockClear() @@ -138,29 +103,6 @@ describe('OrcaRuntimeService', () => { expect(internals.ptysById.has('nested-controller-pty')).toBe(false) }) - it('ignores cwd-only controller PTYs for malformed explicit worktree IDs', async () => { - vi.mocked(listWorktrees).mockClear() - vi.mocked(listWorktrees).mockRejectedValue( - new Error('malformed explicit-id fallback should not rescan worktrees') - ) - const runtime = createRuntime() - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { id: 'cwd-only-pty', cwd: `${TEST_WORKTREE_PATH}/src`, title: 'cwd shell' } - ] - }) - - const terminals = await runtime.listTerminals(`id:${TEST_REPO_ID}::`) - - expect(listWorktrees).not.toHaveBeenCalled() - expect(terminals.terminals).toEqual([]) - const internals = runtime as unknown as { ptysById: Map } - expect(internals.ptysById.has('cwd-only-pty')).toBe(false) - }) - it('keeps same-path folder workspace instance PTYs scoped to their exact ids', async () => { const firstWorktreeId = `${TEST_REPO_ID}::${TEST_FOLDER_WORKSPACE_PATH}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}11111111-1111-4111-8111-111111111111` const secondWorktreeId = `${TEST_REPO_ID}::${TEST_FOLDER_WORKSPACE_PATH}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}22222222-2222-4222-8222-222222222222` diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts index 8bb5db83c5c..67c8107a4b4 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts @@ -1,17 +1,15 @@ import { makeRuntimeOrchestrationDb } from './runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from './runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +import '../../../shared/layout-owner-switch' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import '../../../shared/workspace-layout/stable-pane-id' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID, - HEADLESS_THIRD_LEAF_ID, - LIST_PROVIDER_DEADLINE, RESTORED_AUTHORITY_TOKEN, RESTORED_AUTHORITY_TOKEN_HASH, TEST_REPO_ID, @@ -24,187 +22,6 @@ import { import { publishLegacyWorkerReveal } from './orca-runtime-test-scenario-builders.spec' describe('OrcaRuntimeService', () => { - it('adopts a v1.4.150-shaped agent, setup, and shell orphan as one topology transaction', async () => { - const session = { - ...getDefaultWorkspaceSession(), - activeRepoId: TEST_REPO_ID, - activeWorktreeId: TEST_WORKTREE_ID, - tabsByWorktree: { [TEST_WORKTREE_ID]: [] } - } - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const writes: [string, string][] = [] - const resize = vi.fn(() => true) - const processes = [ - ['pty-agent', 'inc-agent', 'term_agent', 'Agent'], - ['pty-setup', 'inc-setup', 'term_setup', 'Setup'], - ['pty-shell', 'inc-shell', 'term_shell', 'Shell'] - ] as const - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }) - ) - const listProcesses = vi.fn(async () => - processes.map(([id, incarnationId, terminalHandle, title]) => ({ - id, - incarnationId, - terminalHandle, - title, - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - })) - ) - runtime.setPtyController({ - write: (ptyId, data) => { - writes.push([ptyId, data]) - return true - }, - resize, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses - }) - const before = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - expect(before.terminals.map((terminal) => terminal.tabId)).toEqual( - processes.map(([id]) => `pty:${id}`) - ) - const targeted = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`, 100, { - handles: ['term_setup'], - requireFreshPtyLiveness: true - }) - expect(targeted).toMatchObject({ - terminals: [expect.objectContaining({ handle: 'term_setup', ptyId: 'pty-setup' })], - totalCount: 1, - truncated: false - }) - runtime.onPtyData('pty-agent', 'legacy output\n', 1) - - await expect( - runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 0, - claims: [ - { - terminal: 'term_agent', - ptyId: 'pty-agent', - incarnationId: 'stale-incarnation', - tabId: 'tab-agent', - leafId: HEADLESS_LEAF_ID - } - ] - }) - ).rejects.toThrow('terminal_orphan_stale') - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) - - const adopted = await runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: before.topologyRevisions?.[TEST_WORKTREE_ID] ?? 0, - activeTabId: 'tab-agent', - activeGroupId: 'legacy-group', - claims: processes.map(([ptyId, incarnationId, terminal], index) => ({ - terminal, - ptyId, - incarnationId, - tabId: ['tab-agent', 'tab-setup', 'tab-shell'][index]!, - leafId: [HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID, HEADLESS_THIRD_LEAF_ID][index]! - })) - }) - - expect(adopted.adopted).toBe(true) - expect(adopted.topologyRevision).toBe(1) - expect(adopted.snapshot.tabs).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - parentTabId: 'tab-agent', - leafId: HEADLESS_LEAF_ID, - title: 'Agent', - terminal: 'term_agent' - }), - expect.objectContaining({ - parentTabId: 'tab-setup', - leafId: HEADLESS_SECOND_LEAF_ID, - title: 'Setup', - terminal: 'term_setup' - }), - expect.objectContaining({ - parentTabId: 'tab-shell', - leafId: HEADLESS_THIRD_LEAF_ID, - title: 'Shell', - terminal: 'term_shell' - }) - ]) - ) - expect(adopted.snapshot.tabGroups).toEqual([ - expect.objectContaining({ - activeTabId: 'tab-agent', - tabOrder: ['tab-agent', 'tab-setup', 'tab-shell'] - }) - ]) - expect(getSession().terminalTopologyRevisionByRepoId?.[TEST_REPO_ID]).toBe(1) - - await runtime.sendTerminal('term_agent', { text: 'input' }, { inputKind: 'driving' }) - await runtime.updateRemoteDesktopViewer('pty-agent', 'viewer', 'client', 132, 41) - expect(writes).toEqual([['pty-agent', 'input']]) - expect(resize).toHaveBeenCalledWith('pty-agent', 132, 41) - await expect(runtime.readTerminal('term_agent')).resolves.toMatchObject({ - tail: ['legacy output'] - }) - - const inventoryCount = listProcesses.mock.calls.length - const agentPty = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-agent')! - agentPty.tabId = null - agentPty.paneKey = null - const secondClient = await runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 0, - claims: processes.map(([ptyId, incarnationId, terminal], index) => ({ - terminal, - ptyId, - incarnationId, - tabId: ['tab-agent', 'tab-setup', 'tab-shell'][index]!, - leafId: [HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID, HEADLESS_THIRD_LEAF_ID][index]! - })) - }) - expect(secondClient).toMatchObject({ adopted: false, topologyRevision: 1 }) - // Main-owned bindings live in the layout, not the record's legacy copies. - if (!ORCA_LAYOUT_OWNER_IS_MAIN) { - expect(agentPty).toMatchObject({ - tabId: 'tab-agent', - paneKey: makePaneKey('tab-agent', HEADLESS_LEAF_ID) - }) - } - expect(listProcesses).toHaveBeenCalledTimes(inventoryCount + 1) - expect(listProcesses).toHaveBeenLastCalledWith('local', LIST_PROVIDER_DEADLINE) - expect( - (await runtime.listTerminals()).terminals.find((terminal) => terminal.ptyId === 'pty-agent') - ).toMatchObject({ - handle: 'term_agent', - orphaned: false, - tabId: 'tab-agent', - leafId: HEADLESS_LEAF_ID - }) - expect(listProcesses).toHaveBeenCalledTimes(inventoryCount + 2) - expect(listProcesses).toHaveBeenLastCalledWith(undefined, LIST_PROVIDER_DEADLINE) - await expect( - runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 0, - claims: [ - { - terminal: 'term_agent', - ptyId: 'pty-agent', - incarnationId: 'inc-agent', - tabId: 'competing-tab', - leafId: HEADLESS_LEAF_ID - } - ] - }) - ).rejects.toThrow('terminal_orphan_competing_owner') - }) - it('preserves concurrent workspace-session changes when async orphan persistence fails', async () => { const session = { ...getDefaultWorkspaceSession(), diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts index 8cb1bc8a5ff..2bf669c03aa 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts @@ -99,171 +99,6 @@ describe('OrcaRuntimeService', () => { } }) - it('retires the exact worker when it exits after renderer reveal', async () => { - const liveProcess = { - id: 'pty-post-reveal', - incarnationId: '45454545-4545-4545-8545-454545454545', - terminalHandle: 'term_post_reveal', - title: 'Post-reveal worker', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } as const - const listProcesses = vi - .fn() - .mockResolvedValueOnce([liveProcess]) - .mockResolvedValueOnce([liveProcess]) - .mockResolvedValueOnce([]) - const harness = makePostRevealWorkerRecoveryHarness(() => false, listProcesses) - harness.revealTerminalSession.mockImplementation(() => - publishLegacyWorkerReveal(harness.runtime, { - worktreeId: TEST_WORKTREE_ID, - tabId: 'legacy-post-reveal', - leafId: HEADLESS_LEAF_ID, - ptyId: harness.ptyId - }) - ) - - await expect( - harness.runtime.reconcileLegacyWorkerTerminals({ materializeRenderer: true }) - ).resolves.toMatchObject({ - adoptedDispatchIds: [], - exitedDispatchIds: ['dispatch-post-reveal'], - deferredDispatchIds: [] - }) - - expect(listProcesses).toHaveBeenCalledTimes(3) - expect(harness.revealTerminalSession).toHaveBeenCalledOnce() - expect(harness.getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) - expect( - harness.getSession().sleepingAgentSessionsByPaneKey?.[harness.workerPaneKey] - ).toBeUndefined() - expect( - ( - harness.runtime as unknown as { - ptysById: Map - } - ).ptysById.get(harness.ptyId) - ).toMatchObject({ connected: false, incarnationId: '45454545-4545-4545-8545-454545454545' }) - expect(harness.resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith( - harness.workerPaneKey, - 'exited' - ) - }) - - it('re-reveals a recovered worker after the renderer graph epoch changes', async () => { - vi.useFakeTimers() - try { - const harness = makePostRevealWorkerRecoveryHarness(() => false) - harness.runtime.attachWindow(TEST_WINDOW_ID) - harness.revealTerminalSession - .mockResolvedValueOnce({ - tabId: 'legacy-post-reveal', - identity: { - worktreeId: TEST_WORKTREE_ID, - tabId: 'legacy-post-reveal', - leafId: HEADLESS_LEAF_ID, - ptyId: harness.ptyId - } - }) - .mockImplementationOnce(() => - publishLegacyWorkerReveal(harness.runtime, { - worktreeId: TEST_WORKTREE_ID, - tabId: 'legacy-post-reveal', - leafId: HEADLESS_LEAF_ID, - ptyId: harness.ptyId - }) - ) - - await expect( - harness.runtime.reconcileLegacyWorkerTerminals({ materializeRenderer: true }) - ).resolves.toMatchObject({ - adoptedDispatchIds: [], - deferredDispatchIds: ['dispatch-post-reveal'] - }) - harness.runtime.syncWindowGraph(TEST_WINDOW_ID, { tabs: [], leaves: [] }) - harness.runtime.markRendererReloading(TEST_WINDOW_ID) - await expect( - harness.runtime.reconcileLegacyWorkerTerminals({ materializeRenderer: true }) - ).resolves.toMatchObject({ - adoptedDispatchIds: ['dispatch-post-reveal'], - deferredDispatchIds: [] - }) - - expect(harness.revealTerminalSession).toHaveBeenCalledTimes(2) - expect( - harness.getSession().sleepingAgentSessionsByPaneKey?.[harness.workerPaneKey] - ).toBeUndefined() - expect(harness.resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith( - harness.workerPaneKey, - 'adopted' - ) - } finally { - vi.useRealTimers() - } - }) - - it('defers recovery when the renderer omits the exact reveal identity', async () => { - const harness = makePostRevealWorkerRecoveryHarness(() => false) - harness.revealTerminalSession.mockResolvedValue({ tabId: 'legacy-post-reveal' }) - - await expect( - harness.runtime.reconcileLegacyWorkerTerminals({ materializeRenderer: true }) - ).resolves.toMatchObject({ - adoptedDispatchIds: [], - exitedDispatchIds: [], - deferredDispatchIds: ['dispatch-post-reveal'] - }) - - expect(harness.revealTerminalSession).toHaveBeenCalledTimes(2) - expect( - harness.getSession().sleepingAgentSessionsByPaneKey?.[harness.workerPaneKey] - ).toBeDefined() - expect(harness.resolveLegacyWorkerTerminalRecovery).not.toHaveBeenCalled() - }) - - it('reconciles a same-id process replacement before headless adoption', async () => { - const exactProcess = { - id: 'pty-post-reveal', - incarnationId: '45454545-4545-4545-8545-454545454545', - terminalHandle: 'term_post_reveal', - title: 'Post-reveal worker', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } as const - const replacement = { - ...exactProcess, - incarnationId: '56565656-5656-4656-8656-565656565656', - terminalHandle: 'term_replacement' - } - const listProcesses = vi - .fn() - .mockResolvedValueOnce([exactProcess]) - .mockResolvedValueOnce([replacement]) - const harness = makePostRevealWorkerRecoveryHarness(() => false, listProcesses) - - await expect(harness.runtime.reconcileLegacyWorkerTerminals()).resolves.toMatchObject({ - adoptedDispatchIds: [], - exitedDispatchIds: ['dispatch-post-reveal'], - deferredDispatchIds: [] - }) - - expect(harness.getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) - expect( - harness.getSession().sleepingAgentSessionsByPaneKey?.[harness.workerPaneKey] - ).toBeUndefined() - expect(harness.resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith( - harness.workerPaneKey, - 'rolled_back', - harness.ptyId - ) - expect(harness.resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith( - harness.workerPaneKey, - 'exited' - ) - }) - it('reconciles a same-id process replacement after renderer materialization', async () => { const exactProcess = { id: 'pty-post-reveal', diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts index 71aa1c50fb6..14a1ce8a8b0 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts @@ -1,5 +1,5 @@ -import { CrewChanges } from '../orchestration/crew/crew-changes' -import { makeRuntimeOrchestrationDb } from './runtime-orchestration-db.test-fixture' +import '../orchestration/crew/crew-changes' +import './runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from './runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' @@ -9,14 +9,11 @@ import { getDefaultWorkspaceSession } from '../../../shared/constants' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { HEADLESS_LEAF_ID, - HEADLESS_SECOND_LEAF_ID, - LIST_PROVIDER_DEADLINE, TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, deferred, makeRuntimeStoreWithWorkspaceSession } from './orca-runtime-test-fixtures.spec' -import { publishLegacyWorkerReveal } from './orca-runtime-test-scenario-builders.spec' +import './orca-runtime-test-scenario-builders.spec' describe('OrcaRuntimeService', () => { it('requeues an active Task before clearing recovery for an authoritatively missing worker', async () => { @@ -236,252 +233,4 @@ describe('OrcaRuntimeService', () => { db.close() } }) - - it('retires provider resume only after authoritative inventory proves the legacy PTY exited', async () => { - const workerPaneKey = `legacy-worker:${HEADLESS_LEAF_ID}` - const secondWorkerPaneKey = `legacy-worker-two:${HEADLESS_SECOND_LEAF_ID}` - const incarnationId = '33333333-3333-4333-8333-333333333333' - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { [TEST_WORKTREE_ID]: [] }, - sleepingAgentSessionsByPaneKey: { - [workerPaneKey]: { - paneKey: workerPaneKey, - tabId: 'legacy-worker', - worktreeId: TEST_WORKTREE_ID, - agent: 'codex', - providerSession: { key: 'session_id', id: 'legacy-codex-session' }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'live' - }, - [secondWorkerPaneKey]: { - paneKey: secondWorkerPaneKey, - tabId: 'legacy-worker-two', - worktreeId: TEST_WORKTREE_ID, - agent: 'codex', - providerSession: { key: 'session_id', id: 'legacy-codex-session-two' }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'live' - } - } - } - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }), - undefined, - { canRecoverPersistentLocalPtys: () => true } - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This isolated recovery path reaches only the supplied planner and missing-terminal settlement methods. - runtime.setOrchestrationDb({ - crewChanges: new CrewChanges(), - listSessionDispatchesForPresentation: () => [], - reconcileMissingWorkerTerminal: vi.fn(), - getDispatchContextById: () => undefined, - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-exited', - task_id: 'task-exited', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_exited', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-exited:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_exited' - }, - { - dispatch_id: 'dispatch-exited-two', - task_id: 'task-exited-two', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_exited_two', - assignee_pane_key: secondWorkerPaneKey, - process_incarnation: `pty-exited-two:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_exited_two' - } - ] - } as unknown as OrchestrationDb) - const listProcesses = vi.fn(async (hostId?: string) => { - if (hostId !== 'local') { - throw new Error('unrelated SSH inventory must not run') - } - return [ - { - id: 'pty-exited-two', - incarnationId, - terminalHandle: 'term_exited_two', - title: 'Exited worker', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } - ] - }) - runtime.setPtyController({ - write: vi.fn(() => true), - kill: vi.fn(() => true), - getForegroundProcess: async () => null, - hasPty: () => false, - listProcesses - }) - const revealTerminalSession = vi.fn() - const resolveLegacyWorkerTerminalRecovery = vi.fn() - runtime.setNotifier({ - revealTerminalSession, - resolveLegacyWorkerTerminalRecovery - } as never) - - expect(getSession().sleepingAgentSessionsByPaneKey?.[workerPaneKey]).toBeDefined() - - await expect(runtime.reconcileLegacyWorkerTerminals()).resolves.toMatchObject({ - adoptedDispatchIds: ['dispatch-exited-two'], - exitedDispatchIds: ['dispatch-exited'], - deferredDispatchIds: [] - }) - expect(getSession().sleepingAgentSessionsByPaneKey?.[workerPaneKey]).toBeUndefined() - expect(getSession().sleepingAgentSessionsByPaneKey?.[secondWorkerPaneKey]).toBeUndefined() - expect(listProcesses).toHaveBeenCalledTimes(3) - expect(listProcesses).toHaveBeenCalledWith('local', LIST_PROVIDER_DEADLINE) - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([ - expect.objectContaining({ id: 'legacy-worker-two', ptyId: 'pty-exited-two' }) - ]) - expect(revealTerminalSession).not.toHaveBeenCalled() - expect( - ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-exited-two') - ).toMatchObject({ connected: true }) - expect(resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith(workerPaneKey, 'exited') - expect(resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith(secondWorkerPaneKey, 'adopted') - }) - - it('retries inventory and unknown liveness without revealing a ghost worker', async () => { - const workerPaneKey = `legacy-worker:${HEADLESS_LEAF_ID}` - const incarnationId = '55555555-5555-4555-8555-555555555555' - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { [TEST_WORKTREE_ID]: [] }, - sleepingAgentSessionsByPaneKey: { - [workerPaneKey]: { - paneKey: workerPaneKey, - tabId: 'legacy-worker', - worktreeId: TEST_WORKTREE_ID, - agent: 'codex', - providerSession: { key: 'session_id', id: 'legacy-codex-session' }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'live' - } - } - } - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }), - undefined, - { canRecoverPersistentLocalPtys: () => true } - ) - const orchestrationDb = makeRuntimeOrchestrationDb() - vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) - vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ - { - dispatch_id: 'dispatch-inventory-unavailable', - task_id: 'task-inventory-unavailable', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_inventory_unavailable', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-inventory-unavailable:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_inventory_unavailable' - } - ]) - runtime.setOrchestrationDb(orchestrationDb) - const listProcesses = vi - .fn() - .mockRejectedValueOnce(new Error('local provider unavailable')) - .mockResolvedValue([ - { - id: 'pty-inventory-unavailable', - incarnationId, - terminalHandle: 'term_inventory_unavailable', - title: 'Recovered legacy worker', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } - ]) - const hasPty = vi.fn().mockReturnValueOnce(null).mockReturnValue(true) - runtime.setPtyController({ - write: vi.fn(() => true), - kill: vi.fn(() => true), - getForegroundProcess: async () => null, - hasPty, - listProcesses - }) - const revealTerminalSession = vi.fn().mockImplementation(() => - publishLegacyWorkerReveal(runtime, { - worktreeId: TEST_WORKTREE_ID, - tabId: 'legacy-worker', - leafId: HEADLESS_LEAF_ID, - ptyId: 'pty-inventory-unavailable' - }) - ) - const resolveLegacyWorkerTerminalRecovery = vi.fn() - runtime.setNotifier({ - revealTerminalSession, - resolveLegacyWorkerTerminalRecovery - } as never) - - vi.useFakeTimers() - try { - await expect( - runtime.reconcileLegacyWorkerTerminals({ materializeRenderer: true }) - ).resolves.toMatchObject({ - adoptedDispatchIds: [], - exitedDispatchIds: [], - deferredDispatchIds: ['dispatch-inventory-unavailable'] - }) - expect(getSession().sleepingAgentSessionsByPaneKey?.[workerPaneKey]).toBeDefined() - expect(resolveLegacyWorkerTerminalRecovery).not.toHaveBeenCalled() - expect(listProcesses).toHaveBeenCalledOnce() - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) - expect(revealTerminalSession).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(1_000) - - expect(listProcesses).toHaveBeenCalledTimes(4) - expect(listProcesses.mock.calls.map((call) => call[0])).toEqual([ - 'local', - 'local', - 'local', - 'local' - ]) - expect(hasPty).not.toHaveBeenCalled() - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([ - expect.objectContaining({ id: 'legacy-worker', ptyId: 'pty-inventory-unavailable' }) - ]) - expect(revealTerminalSession).toHaveBeenCalledOnce() - expect(getSession().sleepingAgentSessionsByPaneKey?.[workerPaneKey]).toBeUndefined() - expect(resolveLegacyWorkerTerminalRecovery).toHaveBeenCalledWith(workerPaneKey, 'adopted') - await vi.advanceTimersByTimeAsync(30_000) - expect(listProcesses).toHaveBeenCalledTimes(4) - expect(revealTerminalSession).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts deleted file mode 100644 index 64f441ce9ee..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts +++ /dev/null @@ -1,138 +0,0 @@ -import '../orchestration/crew/crew-changes' -import { makeRuntimeOrchestrationDb } from './runtime-orchestration-db.test-fixture' -import { withDurableRuntimeStore } from './runtime-durable-store-fixture' -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { join } from 'node:path' -import { mkdtemp } from 'node:fs/promises' -import { tmpdir } from 'node:os' - -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { - HEADLESS_LEAF_ID, - LIST_PROVIDER_DEADLINE, - TEST_FOLDER_WORKSPACE_KEY, - makeFolderProjectGroup, - makeFolderWorkspace, - makeRuntimeStoreWithWorkspaceSession -} from './orca-runtime-test-fixtures.spec' -import { publishLegacyWorkerReveal } from './orca-runtime-test-scenario-builders.spec' - -describe('OrcaRuntimeService', () => { - it('adopts an exact live legacy worker in a folder workspace', async () => { - const workerPaneKey = `legacy-folder-worker:${HEADLESS_LEAF_ID}` - const incarnationId = '66666666-6666-4666-8666-666666666666' - const folderPath = await mkdtemp(join(tmpdir(), 'orca-legacy-worker-folder-')) - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - activeWorktreeId: TEST_FOLDER_WORKSPACE_KEY, - tabsByWorktree: { [TEST_FOLDER_WORKSPACE_KEY]: [] }, - sleepingAgentSessionsByPaneKey: { - [workerPaneKey]: { - paneKey: workerPaneKey, - tabId: 'legacy-folder-worker', - worktreeId: TEST_FOLDER_WORKSPACE_KEY, - agent: 'codex', - providerSession: { key: 'session_id', id: 'legacy-folder-codex-session' }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'live' - } - } - } - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const folderWorkspace = makeFolderWorkspace({ folderPath }) - const projectGroup = makeFolderProjectGroup({ parentPath: folderPath }) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ - ...runtimeStore, - getFolderWorkspaces: () => [folderWorkspace], - getFolderWorkspace: (id: string) => - id === folderWorkspace.id ? folderWorkspace : undefined, - getProjectGroups: () => [projectGroup], - flushOrThrow: vi.fn() - }), - undefined, - { canRecoverPersistentLocalPtys: () => true } - ) - const orchestrationDb = makeRuntimeOrchestrationDb() - vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) - vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ - { - dispatch_id: 'dispatch-folder', - task_id: 'task-folder', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_folder', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-folder-legacy:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_FOLDER_WORKSPACE_KEY, - agent_terminal_handle: 'term_folder' - } - ]) - runtime.setOrchestrationDb(orchestrationDb) - const listProcesses = vi.fn(async () => [ - { - id: 'pty-folder-legacy', - incarnationId, - terminalHandle: 'term_folder', - title: 'Folder worker', - cwd: folderPath, - worktreeId: TEST_FOLDER_WORKSPACE_KEY, - wslDistro: null - } - ]) - runtime.setPtyController({ - write: vi.fn(() => true), - kill: vi.fn(() => true), - getForegroundProcess: async () => null, - hasPty: (candidate) => candidate === 'pty-folder-legacy', - listProcesses - }) - const revealTerminalSession = vi.fn().mockImplementation(() => - publishLegacyWorkerReveal(runtime, { - worktreeId: TEST_FOLDER_WORKSPACE_KEY, - tabId: 'legacy-folder-worker', - leafId: HEADLESS_LEAF_ID, - ptyId: 'pty-folder-legacy' - }) - ) - runtime.setNotifier({ revealTerminalSession } as never) - - await expect( - runtime.reconcileLegacyWorkerTerminals({ materializeRenderer: true }) - ).resolves.toMatchObject({ - adoptedDispatchIds: ['dispatch-folder'], - exitedDispatchIds: [], - deferredDispatchIds: [] - }) - expect(getSession().tabsByWorktree[TEST_FOLDER_WORKSPACE_KEY]).toContainEqual( - expect.objectContaining({ - id: 'legacy-folder-worker', - ptyId: 'pty-folder-legacy', - worktreeId: TEST_FOLDER_WORKSPACE_KEY - }) - ) - expect(getSession().sleepingAgentSessionsByPaneKey?.[workerPaneKey]).toBeUndefined() - expect(listProcesses).toHaveBeenCalledTimes(3) - expect(listProcesses).toHaveBeenCalledWith('local', LIST_PROVIDER_DEADLINE) - expect(revealTerminalSession).toHaveBeenCalledWith(TEST_FOLDER_WORKSPACE_KEY, { - ptyId: 'pty-folder-legacy', - title: 'Folder worker', - activate: false, - presentation: 'background', - tabId: 'legacy-folder-worker', - leafId: HEADLESS_LEAF_ID, - focus: false, - expectedProcessIdentity: { - terminalHandle: 'term_folder', - incarnationId - } - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts index a93b4817f8d..b49f163b54f 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts @@ -1,3 +1,4 @@ +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { makeRuntimeOrchestrationDb } from './runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from './runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' @@ -5,7 +6,7 @@ import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { getDefaultWorkspaceSession } from '../../../shared/constants' import { setPlatform } from '../orca-runtime-test-mocks/setup.spec' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' + import { HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID, @@ -507,64 +508,4 @@ describe('OrcaRuntimeService', () => { ['tab-shell', 'group-old-right'] ]) }) - - it('canonicalizes an equivalent persisted worktree key without duplicating terminal topology', async () => { - const aliasWorktreeId = `${TEST_REPO_ID}::/tmp//worktree-a/` - const base = makeWorkspaceSessionWithHeadlessTerminal({ - terminalPtyIncarnationsByPaneKey: { - [`host-tab:${HEADLESS_LEAF_ID}`]: 'inc-alias' - } - }) - const session: WorkspaceSessionState = { - ...base, - activeTabIdByWorktree: { [aliasWorktreeId]: 'host-tab' }, - tabsByWorktree: { - [aliasWorktreeId]: base.tabsByWorktree[TEST_WORKTREE_ID]!.map((tab) => ({ - ...tab, - worktreeId: aliasWorktreeId - })) - } - } - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }) - ) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { - id: 'persisted-pty', - incarnationId: 'inc-alias', - terminalHandle: 'term_alias', - title: 'Alias shell', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } - ] - }) - - const adopted = await runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 0, - claims: [ - { - terminal: 'term_alias', - ptyId: 'persisted-pty', - incarnationId: 'inc-alias', - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID - } - ] - }) - - expect(adopted).toMatchObject({ adopted: true, topologyRevision: 1 }) - expect(adopted.snapshot.worktree).toBe(TEST_WORKTREE_ID) - expect(Object.keys(getSession().tabsByWorktree)).toContain(TEST_WORKTREE_ID) - expect(Object.keys(getSession().tabsByWorktree)).not.toContain(aliasWorktreeId) - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]?.[0]?.worktreeId).toBe(TEST_WORKTREE_ID) - expect(getSession().activeTabIdByWorktree).toEqual({ [TEST_WORKTREE_ID]: 'host-tab' }) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts index b1a619a9c47..73e07d39c3b 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts @@ -5,8 +5,6 @@ import { OrcaRuntimeService } from '../orca-runtime' import { getDefaultWorkspaceSession } from '../../../shared/constants' import { HEADLESS_LEAF_ID, - HEADLESS_SECOND_LEAF_ID, - HEADLESS_THIRD_LEAF_ID, TEST_REPO_ID, TEST_WORKTREE_ID, TEST_WORKTREE_PATH, @@ -104,50 +102,6 @@ describe('OrcaRuntimeService', () => { expect(resize).toHaveBeenCalledWith('persisted-pty', 132, 41) }) - it('uses topology CAS before a client can claim a still-orphaned PTY', async () => { - const session = { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { [TEST_WORKTREE_ID]: [] }, - terminalTopologyRevisionByRepoId: { [TEST_REPO_ID]: 7 } - } - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }) - ) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { - id: 'pty-cas', - incarnationId: 'inc-cas', - terminalHandle: 'term_cas', - title: 'shell', - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - } - ] - }) - - await expect( - runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 6, - claims: [ - { - terminal: 'term_cas', - ptyId: 'pty-cas', - incarnationId: 'inc-cas', - tabId: 'tab-cas', - leafId: HEADLESS_LEAF_ID - } - ] - }) - ).rejects.toThrow('terminal_topology_conflict') - }) - // The client's retirement proofs die with a host restart; the close record does not. it('refuses to adopt an orphan under a tab the user closed', async () => { const session = { @@ -367,120 +321,4 @@ describe('OrcaRuntimeService', () => { ) }) }) - - it('preserves legacy pane and group topology without changing host focus', async () => { - const session = { - ...getDefaultWorkspaceSession(), - activeWorktreeId: 'other-worktree', - activeTabId: 'other-tab', - tabsByWorktree: { [TEST_WORKTREE_ID]: [] } - } - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService( - withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() }) - ) - const processes = [ - ['pty-left', 'inc-left', 'term_left'], - ['pty-right', 'inc-right', 'term_right'], - ['pty-shell', 'inc-shell', 'term_shell'] - ] as const - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => - processes.map(([id, incarnationId, terminalHandle]) => ({ - id, - incarnationId, - terminalHandle, - title: id, - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - wslDistro: null - })) - }) - - await runtime.adoptTerminalOrphans({ - worktree: `id:${TEST_WORKTREE_ID}`, - expectedTopologyRevision: 0, - activeTabId: 'tab-agent', - activeGroupId: 'group-left', - claims: processes.map(([ptyId, incarnationId, terminal], index) => ({ - terminal, - ptyId, - incarnationId, - tabId: index < 2 ? 'tab-agent' : 'tab-shell', - leafId: [HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID, HEADLESS_THIRD_LEAF_ID][index]! - })), - topology: { - tabs: [ - { - tabId: 'tab-agent', - root: { - type: 'split', - direction: 'horizontal', - ratio: 0.35, - first: { type: 'leaf', leafId: HEADLESS_LEAF_ID }, - second: { type: 'leaf', leafId: HEADLESS_SECOND_LEAF_ID } - }, - activeLeafId: HEADLESS_SECOND_LEAF_ID, - expandedLeafId: HEADLESS_SECOND_LEAF_ID - }, - { - tabId: 'tab-shell', - root: { type: 'leaf', leafId: HEADLESS_THIRD_LEAF_ID }, - activeLeafId: HEADLESS_THIRD_LEAF_ID, - expandedLeafId: null - } - ], - groups: [ - { - id: 'group-left', - activeTabId: 'tab-agent', - tabOrder: ['tab-agent'], - recentTabIds: ['tab-agent'] - }, - { id: 'group-right', activeTabId: 'tab-shell', tabOrder: ['tab-shell'] } - ], - groupLayout: { - type: 'split', - direction: 'vertical', - ratio: 0.6, - first: { type: 'leaf', groupId: 'group-left' }, - second: { type: 'leaf', groupId: 'group-right' } - } - } - }) - - expect(getSession()).toMatchObject({ - activeWorktreeId: 'other-worktree', - activeTabId: 'other-tab', - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'tab-agent' }, - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: 'group-left' }, - tabGroups: { - [TEST_WORKTREE_ID]: [ - { id: 'group-left', activeTabId: 'tab-agent', tabOrder: ['tab-agent'] }, - { id: 'group-right', activeTabId: 'tab-shell', tabOrder: ['tab-shell'] } - ] - }, - tabGroupLayouts: { - [TEST_WORKTREE_ID]: expect.objectContaining({ - type: 'split', - direction: 'vertical', - ratio: 0.6 - }) - }, - terminalLayoutsByTabId: { - 'tab-agent': expect.objectContaining({ - root: expect.objectContaining({ - type: 'split', - direction: 'horizontal', - ratio: 0.35 - }), - activeLeafId: HEADLESS_SECOND_LEAF_ID, - expandedLeafId: HEADLESS_SECOND_LEAF_ID - }) - } - }) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts deleted file mode 100644 index 57dfe58296b..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts +++ /dev/null @@ -1,298 +0,0 @@ -import { settledWriteStub } from '../../providers/settled-pty-write-stub' -import { makeAgentStatusStoreWiring } from '../terminal/identity/agent-status-store-wiring.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { committingSpawn } from './bind-first-pane.test-fixture' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import '../../../shared/agent-status/title/agent-title-status' -import '../orca-runtime-test-mocks/setup.spec' -import { waitForMobileSessionTabsEvents } from './mobile-session-tab-event-wait' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' -import { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - bindSinglePtyRun, - setInMemoryOrchestrationMessages, - store, - syncSinglePty -} from './orca-runtime-test-fixtures.spec' -import { InMemoryOrchestrationMessages } from '../orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec' - -describe('OrcaRuntimeService', () => { - it('detects split OSC titles before retaining terminal previews', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '\x1b]0;Codex work', 100) - runtime.onPtyData('pty-1', 'ing\x07Visible\n', 101) - - const pty = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-1') - expect(pty?.lastOscTitle).toBe('Codex working') - expect(pty?.lastAgentStatus).toBe('working') - - const [terminal] = (await runtime.listTerminals()).terminals - const read = await runtime.readTerminal(terminal.handle) - expect(read.tail.join('\n')).toContain('Visible') - expect(read.tail.join('\n')).not.toContain('Codex working') - }) - - it('detects ST-terminated OSC titles split before the final backslash', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x1b', 100) - runtime.onPtyData('pty-1', '\\Visible\n', 101) - - const pty = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-1') - expect(pty?.lastOscTitle).toBe('Codex working') - expect(pty?.lastAgentStatus).toBe('working') - }) - - it('preserves a trailing escape after a completed OSC title', async () => { - const runtime = new OrcaRuntimeService(store) - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07\x1b', 100) - runtime.onPtyData('pty-1', ']0;Codex done\x07Visible\n', 101) - - const pty = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-1') - expect(pty?.lastOscTitle).toBe('Codex done') - expect(pty?.lastAgentStatus).toBe('idle') - }) - - // Hook-only OSC 9999 transitions must republish mobile status without a renderer (#7970). - it('republishes mobile session tabs with hook payloads for title-less OSC 9999 transitions', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'hook-only-pty' }) - const statusWiring = makeAgentStatusStoreWiring() - const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) - const uninstallRepublish = statusWiring.attach(runtime) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - writeWithSettlement: settledWriteStub(() => true), - kill: () => true, - getForegroundProcess: async () => null - }) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'hook-tab', - leafId: HEADLESS_LEAF_ID - }) - events.length = 0 - - runtime.onPtyData( - 'hook-only-pty', - '\x1b]9999;{"state":"working","prompt":"fix the tests","agentType":"opencode"}\x07', - 100 - ) - - await waitForMobileSessionTabsEvents(events, 1) - expect(events).toHaveLength(1) - expect(events[0]?.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - agentStatus: expect.objectContaining({ - state: 'working', - prompt: 'fix the tests', - agentType: 'opencode' - }) - }) - ) - - runtime.onPtyData( - 'hook-only-pty', - '\x1b]9999;{"state":"waiting","prompt":"fix the tests","agentType":"opencode"}\x07', - 101 - ) - - await waitForMobileSessionTabsEvents(events, 2) - expect(events).toHaveLength(2) - expect(events[1]?.tabs[0]?.type === 'terminal' && events[1].tabs[0].agentStatus).toEqual( - expect.objectContaining({ state: 'waiting' }) - ) - - unsubscribe() - uninstallRepublish() - }) - - it('seeds newly synced leaves from PTY pending ANSI state', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.registerPty('pty-1', TEST_WORKTREE_ID) - runtime.onPtyData('pty-1', 'Working\r\x1b[', 100) - - syncSinglePty(runtime) - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData('pty-1', '38;2;190;210;223;49mDone\n', 101) - - const read = await runtime.readTerminal(terminal.handle) - const retained = read.tail.join('\n') - expect(retained).toContain('Done') - expect(retained).not.toContain('38;2') - expect(retained).not.toContain('49m') - }) - - it('bounds retained partial terminal output before preview reads', async () => { - const runtime = new OrcaRuntimeService(store) - - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - title: 'Claude', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'pty-1' - } - ] - }) - - const [terminal] = (await runtime.listTerminals()).terminals - runtime.onPtyData( - 'pty-1', - `${Array.from({ length: 2000 }, (_, index) => `line-${index}`).join('\n')}\n`, - 99 - ) - runtime.onPtyData('pty-1', `${'x'.repeat(40_000)}tail-marker-0`, 100) - type RetainedTailState = { - tailBuffer: string[] - tailPartialLine: string - tailTruncated: boolean - } - const cappedPartialState = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-1') - const retainedLineBuffer = cappedPartialState?.tailBuffer - for (let index = 1; index < 5; index += 1) { - runtime.onPtyData('pty-1', `${'x'.repeat(40_000)}tail-marker-${index}`, 100 + index) - } - - const retained = ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get('pty-1') - expect(retained?.tailBuffer).toBe(retainedLineBuffer) - expect(retained?.tailPartialLine).toHaveLength(4000) - expect(retained?.tailPartialLine.endsWith('tail-marker-4')).toBe(true) - expect(retained?.tailTruncated).toBe(true) - - const preview = await runtime.readTerminal(terminal.handle) - expect(preview.tail).toHaveLength(120) - expect(preview.tail.at(-1)).toHaveLength(4000) - expect(preview.tail.at(-1)?.endsWith('tail-marker-4')).toBe(true) - expect(preview.truncated).toBe(true) - expect(preview.nextCursor).toBe('2000') - }) - - it('submits the mail pointer to Cursor Agent only after the paste-burst delay', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - const mailbox = bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;\u280b Cursor Agent\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Cursor ready\x07', 101) - db.insertMessage({ from: 'term_sender', to: terminal.handle, subject: 'hello cursor' }) - - runtime.deliverPendingMessagesForHandle(terminal.handle) - - expect(write).toHaveBeenCalledWith( - 'pty-1', - expect.stringContaining('You have 1 orchestration message') - ) - const isSubmit = ([ptyId, text]: unknown[]): boolean => ptyId === 'pty-1' && text === '\r' - // Why: Cursor reads Enter within a 35ms keystroke burst as a newline, so it must trail the pointer. - await vi.advanceTimersByTimeAsync(100) - expect(write.mock.calls.filter(isSubmit)).toHaveLength(0) - await vi.advanceTimersByTimeAsync(400) - expect(write.mock.calls.filter(isSubmit)).toHaveLength(1) - - const unread = db.getUnreadMessages(mailbox) - expect(unread).toHaveLength(1) - expect(unread[0].read).toBe(0) - expect(unread[0].delivered_at).toEqual(expect.any(String)) - db.close() - } finally { - vi.useRealTimers() - } - }) - - it('does not replay an already-delivered message on a later idle transition', async () => { - vi.useFakeTimers() - try { - const runtime = new OrcaRuntimeService(store) - const db = new InMemoryOrchestrationMessages() - const write = vi.fn().mockReturnValue(true) - setInMemoryOrchestrationMessages(runtime, db) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null - }) - syncSinglePty(runtime) - - const [terminal] = (await runtime.listTerminals()).terminals - bindSinglePtyRun(db, terminal.handle) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - db.insertMessage({ from: 'term_sender', to: terminal.handle, subject: 'hello' }) - - runtime.deliverPendingMessagesForHandle(terminal.handle) - await vi.advanceTimersByTimeAsync(500) - - const firstInjections = write.mock.calls.filter( - (c) => typeof c[1] === 'string' && c[1].includes('orchestration check') - ).length - expect(firstInjections).toBe(1) - - runtime.deliverPendingMessagesForHandle(terminal.handle) - await vi.advanceTimersByTimeAsync(500) - - const totalInjections = write.mock.calls.filter( - (c) => typeof c[1] === 'string' && c[1].includes('orchestration check') - ).length - expect(totalInjections).toBe(1) - db.close() - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts index 942dbc32798..d04c792592f 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts @@ -1,92 +1,11 @@ import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { AUTHORITATIVE_TERMINAL_SNAPSHOT_TIMEOUT_MS } from '../terminal/output/provider-snapshot-budget' -import { OrcaRuntimeService } from '../orca-runtime' -import { store, syncSinglePty } from './orca-runtime-test-fixtures.spec' +import '../orca-runtime' +import { syncSinglePty } from './orca-runtime-test-fixtures.spec' import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec' describe('terminal side-effect fact channel', () => { - it('emits 2031-subscribe facts across chunk splits', () => { - // Hidden views need this fact to answer DECSET 2031 because they never receive its bytes. - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '\x1b[?20', 100) - expect(batches).toEqual([]) - runtime.onPtyData('pty-1', '31h', 101) - - expect(batches.flatMap((batch) => batch.facts)).toEqual([{ kind: '2031-subscribe' }]) - }) - - it('restores a provisional 2031 subscribe when daemon scan authority returns', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.setPtyTransientFactDelegation('pty-1', true) - runtime.setPtyTransientFactDelegation('pty-1', false, '\x1b[?', true) - runtime.onPtyData('pty-1', '25h', 100) - - expect(batches.flatMap((batch) => batch.facts)).toEqual([{ kind: '2031-subscribe' }]) - }) - - it('prefers the tracked title over the renderer snapshot lastTitle', async () => { - const { runtime } = createSideEffectRuntime() - const serializeBuffer = vi.fn().mockResolvedValue({ - data: 'visible content', - cols: 80, - rows: 24, - // Renderer serialization still has the stale title because synthetic frames bypass pty:data. - lastTitle: 'stale shell title' - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeBuffer, - hasRendererSerializer: () => true, - getSize: () => ({ cols: 80, rows: 24 }) - }) - syncSinglePty(runtime) - - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Cursor Agent\x07') - - const snapshot = await runtime.serializeTerminalBuffer('pty-1', { scrollbackRows: 10 }) - expect(snapshot?.source).toBe('renderer') - expect(snapshot?.lastTitle).toBe('⠋ Cursor Agent') - }) - - it('prefers provider history over a partial headless mirror for requested snapshots', async () => { - const { runtime } = createSideEffectRuntime() - const serializeProviderBuffer = vi.fn().mockResolvedValue({ - data: 'authoritative screen\r\n', - scrollbackAnsi: 'deep provider history\r\n', - cols: 120, - rows: 40, - seq: 900, - source: 'headless' - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - syncSinglePty(runtime) - runtime.onPtyData('pty-1', 'partial current screen\r\n', 100) - - await expect( - runtime.serializeAuthoritativeTerminalBuffer('pty-1', { scrollbackRows: 5000 }) - ).resolves.toMatchObject({ - data: 'authoritative screen\r\n', - scrollbackAnsi: 'deep provider history\r\n', - seq: 900 - }) - expect(serializeProviderBuffer).toHaveBeenCalledWith('pty-1', { - scrollbackRows: 5000 - }) - }) - it('bounds a hung authoritative provider acquisition and reuses its fallback', async () => { vi.useFakeTimers() try { @@ -224,37 +143,6 @@ describe('terminal side-effect fact channel', () => { expect(serializeProviderBuffer).toHaveBeenCalledOnce() }) - it('tracks live alternate-screen transitions after a provider snapshot', async () => { - const { runtime } = createSideEffectRuntime() - const serializeProviderBuffer = vi.fn().mockResolvedValue({ - data: 'restored tui', - cols: 80, - rows: 24, - seq: 900, - source: 'headless', - alternateScreen: true - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer, - hasRendererSerializer: () => false - }) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-tui', - { value: 900, generation: 'continued' }, - 0 - ) - await runtime.serializeTerminalBuffer('pty-tui') - expect(runtime.isTerminalAlternateScreen('pty-tui')).toBe(true) - - runtime.onPtyData('pty-tui', '\x1b[?1049l', 100) - expect(runtime.isTerminalAlternateScreen('pty-tui')).toBe(false) - runtime.onPtyData('pty-tui', '\x1b[?1049h', 101) - expect(runtime.isTerminalAlternateScreen('pty-tui')).toBe(true) - }) - it('keeps mode transitions that race a provider snapshot response', async () => { const { runtime } = createSideEffectRuntime() let resolveProviderSnapshot: @@ -309,98 +197,6 @@ describe('terminal side-effect fact channel', () => { expect(runtime.isTerminalAlternateScreen('pty-tui-race')).toBe(false) }) - it('translates reset provider snapshots without retaining the old title', async () => { - const { runtime } = createSideEffectRuntime() - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-replaced', - { value: 0, generation: 'reset' }, - 0 - ) - runtime.onPtyData('pty-replaced', '\x1b]0;Old process\x07old', 100) - const sequenceBeforeRespawn = runtime.getPtyOutputSequence('pty-replaced') - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeProviderBuffer: vi.fn().mockResolvedValue({ - data: 'new process', - cols: 80, - rows: 24, - seq: 'new process'.length, - source: 'headless', - lastTitle: 'New process' - }), - hasRendererSerializer: () => false - }) - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-replaced', - { value: 0, generation: 'reset' }, - sequenceBeforeRespawn - ) - - await expect(runtime.serializeTerminalBuffer('pty-replaced')).resolves.toMatchObject({ - lastTitle: 'New process', - seq: sequenceBeforeRespawn + 'new process'.length - }) - }) - - it('returns a title-only replay snapshot and never historical attention', () => { - const { runtime } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07\x07', 100) - - expect(runtime.getTerminalSideEffectSnapshot('pty-1')).toMatchObject({ - ptyId: 'pty-1', - replay: true, - facts: [{ kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' }] - }) - expect(runtime.getTerminalSideEffectSnapshot('pty-unknown')).toBeNull() - }) - - it('emits the chunk agentStatus events before its side-effect batch', () => { - const order: string[] = [] - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalAgentStatus: () => order.push('agentStatus:set'), - onTerminalSideEffects: () => order.push('pty:sideEffect') - }) - syncSinglePty(runtime) - - runtime.onPtyData( - 'pty-1', - '\x1b]9999;{"state":"working","agentType":"codex"}\x07\x1b]0;Codex working\x07\x07', - 100 - ) - - expect(order).toEqual(['agentStatus:set', 'pty:sideEffect']) - }) - - it('still emits a throwing chunk’s facts under its own seq, not the next chunk’s', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - vi.spyOn( - runtime as unknown as { applyTrackedPtyTitle: (ptyId: string, title: string) => boolean }, - 'applyTrackedPtyTitle' - ).mockImplementationOnce(() => { - throw new Error('tracker boom') - }) - - const first = '\x1b]0;Codex working\x07' - expect(() => runtime.onPtyData('pty-1', first, 100)).toThrow('tracker boom') - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - - expect(batches).toHaveLength(2) - expect(batches[0].seq).toBe(first.length) - expect(batches[0].facts).toEqual([ - { kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' } - ]) - // A throw aborted the prior tracker pass; its facts must not leak into the next chunk. - expect(batches[1].seq).toBeGreaterThan(batches[0].seq) - expect(batches[1].facts).toEqual([ - { kind: 'title', normalizedTitle: 'Codex done', rawTitle: 'Codex done' } - ]) - }) - it('parses synthetic frames statelessly so ticks cannot corrupt the bell detector', () => { const { runtime, batches } = createSideEffectRuntime() syncSinglePty(runtime) @@ -420,37 +216,4 @@ describe('terminal side-effect fact channel', () => { { kind: 'bell' } ]) }) - - it('seeds the lazily created tracker from the daemon-snapshot title', async () => { - const { runtime, batches } = createSideEffectRuntime() - const serializeBuffer = vi.fn().mockResolvedValue({ - data: 'restored scrollback\n', - cols: 80, - rows: 24, - lastTitle: 'Codex working' - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeBuffer, - hasRendererSerializer: () => true, - getSize: () => ({ cols: 80, rows: 24 }) - }) - syncSinglePty(runtime) - - // Cold tracker hydration must seed status before processing later transitions. - runtime.onPtyData('pty-1', 'plain output without a title\n', 100) - await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 10 }) - batches.length = 0 - - runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) - - // Without a working seed, the idle title cannot produce a completion fact. - expect(batches.flatMap((batch) => batch.facts)).toContainEqual({ - kind: 'agent-idle', - title: 'Codex done', - status: 'idle' - }) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts deleted file mode 100644 index 25a048d7a28..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from 'vitest' -import './runtime-test-module-registration.spec' -import '../orca-runtime' -import { TEST_WORKTREE_ID, syncSinglePty } from './orca-runtime-test-fixtures.spec' -import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec' - -describe('terminal side-effect fact channel', () => { - it('emits command-code-working facts only after the banner arms the scrape', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '❯ Fix the spinner\r\nThinking...', 100) - expect(batches.flatMap((batch) => batch.facts)).toEqual([]) - - runtime.onPtyData('pty-1', '# Command Code v0.27.3\r\n', 101) - runtime.onPtyData('pty-1', '❯ Fix the spinner\r\n\x1b[35m✻ Thinking...\x1b[0m', 102) - - expect(batches.at(-1)).toMatchObject({ - ptyId: 'pty-1', - worktreeId: TEST_WORKTREE_ID, - tabId: 'tab-1' - }) - expect(batches.at(-1)?.facts).toEqual([ - { kind: 'command-code-working', prompt: 'Fix the spinner' } - ]) - }) - - it('emits a command-code-done fact when the idle composer returns', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', '# Command Code v0.27.3\r\n', 100) - runtime.onPtyData('pty-1', '❯ say hi\r\n✻ Thinking...', 101) - runtime.onPtyData( - 'pty-1', - '\r\n✻ Thought for 1 second\r\n:: Hi!\r\n❯ Ask your question...', - 102 - ) - - expect(batches.at(-1)?.facts).toEqual([{ kind: 'command-code-done', prompt: 'say hi' }]) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts index 4c7b468ef79..e3b352a4bec 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts.spec.ts @@ -1,10 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' -import { OrcaRuntimeService } from '../orca-runtime' +import '../orca-runtime' import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' -import { TEST_WORKTREE_ID, store, syncSinglePty } from './orca-runtime-test-fixtures.spec' +import { syncSinglePty } from './orca-runtime-test-fixtures.spec' import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec' import { DECORATIVE_TITLE_FACT_HEARTBEAT_MS } from '../terminal/output/decorative-title-fact-emission' @@ -69,21 +68,6 @@ describe('terminal side-effect fact channel', () => { } }) - it('skips a listener unsubscribed mid-fan-out even with mobile exclusions active', () => { - const runtime = new OrcaRuntimeService(store) - const lateEvents: RuntimeClientEvent[] = [] - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - runtime.onClientEvent(() => {}, { consumesTerminalSideEffects: false }) - runtime.onClientEvent(() => { - unsubscribeLate() - }) - const unsubscribeLate = runtime.onClientEvent((event) => lateEvents.push(event)) - - runtime.onPtyData('pty-remote', '\x1b]0;Codex working\x07', 100) - - expect(lateEvents).toEqual([]) - }) - it('does not confirm an agent exit from a foreground read predating its title', async () => { const { runtime, batches } = createSideEffectRuntime() syncSinglePty(runtime) @@ -132,26 +116,6 @@ describe('terminal side-effect fact channel', () => { }) }) - it('retains bytes emitted before a fresh daemon spawn resolves', async () => { - const { runtime } = createSideEffectRuntime() - const earlyOutput = '\x1b]0;Fresh shell\x07early prompt' - runtime.onPtyData('pty-fresh', earlyOutput, 100) - - expect( - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-fresh', - { value: 0, generation: 'reset' }, - 0 - ) - ).toBe(earlyOutput.length) - - await expect(runtime.serializeMainTerminalBuffer('pty-fresh')).resolves.toMatchObject({ - data: expect.stringContaining('early prompt'), - lastTitle: 'Fresh shell', - seq: earlyOutput.length - }) - }) - it('drops stale headless state without rewinding the runtime sequence', async () => { const { runtime } = createSideEffectRuntime() runtime.synchronizePtyOutputSequenceFromProvider( @@ -206,53 +170,4 @@ describe('terminal side-effect fact channel', () => { sequenceBeforeRespawn + 'early'.length + 'later'.length ]) }) - - it('emits command-finished facts with best-effort exit codes across chunk splits', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', 'output\x1b]133;D;13', 100) - expect(batches).toEqual([]) - runtime.onPtyData('pty-1', '0\x07prompt $ ', 101) - runtime.onPtyData('pty-1', '\x1b]133;D\x07', 102) - - expect(batches.flatMap((batch) => batch.facts)).toEqual([ - { kind: 'command-finished', exitCode: 130 }, - { kind: 'command-finished', exitCode: null } - ]) - }) - - it('emits pr-link facts once per URL with batch attribution', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', 'PR https://github.com/acme/orca/pull/4', 100) - runtime.onPtyData('pty-1', '2\r\nand https://github.com/acme/orca/pull/43 done\r\n', 101) - runtime.onPtyData('pty-1', 'again https://github.com/acme/orca/pull/42\r\n', 102) - - expect(batches).toHaveLength(1) - expect(batches[0]).toMatchObject({ - ptyId: 'pty-1', - worktreeId: TEST_WORKTREE_ID, - tabId: 'tab-1' - }) - expect(batches[0].facts).toEqual([ - { - kind: 'pr-link', - link: { - url: 'https://github.com/acme/orca/pull/42', - slug: { owner: 'acme', repo: 'orca', host: 'github.com' }, - number: 42 - } - }, - { - kind: 'pr-link', - link: { - url: 'https://github.com/acme/orca/pull/43', - slug: { owner: 'acme', repo: 'orca', host: 'github.com' }, - number: 43 - } - } - ]) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/window-authority.spec.ts b/src/main/runtime/orca-runtime-tests/window-authority.spec.ts index 38c7d9725e9..f91748b06f8 100644 --- a/src/main/runtime/orca-runtime-tests/window-authority.spec.ts +++ b/src/main/runtime/orca-runtime-tests/window-authority.spec.ts @@ -2,102 +2,17 @@ import '../../../shared/layout-owner-switch' import { describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' -import { OrcaRuntimeService } from '../orca-runtime' +import '../orca-runtime' import { RUNTIME_GRAPH_RELOAD_TIMEOUT_MS } from '../session-graph/runtime-graph-reload-lifecycle' import '../orca-runtime-test-mocks/setup.spec' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { HEADLESS_LEAF_ID, TEST_WINDOW_ID, TEST_WORKTREE_ID, - createRuntime, - makeHeadlessTerminalLayout, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal + createRuntime } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('marks live bindings again when reopening after a promoted window closes', () => { - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - activeWorktreeIdsOnShutdown: [] - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - runtime.registerPty('persisted-pty', TEST_WORKTREE_ID, null, { - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID - }) - runtime.attachWindow(TEST_WINDOW_ID) - ;(runtimeStore.setWorkspaceSession as unknown as (next: WorkspaceSessionState) => void)({ - ...getSession(), - activeWorktreeIdsOnShutdown: [] - }) - runtime.markGraphUnavailable(TEST_WINDOW_ID) - - runtime.attachWindow(2) - - expect(getSession().activeWorktreeIdsOnShutdown).toEqual([TEST_WORKTREE_ID]) - }) - - it('preserves live SSH session identities when promoting a headless runtime', () => { - const remotePtyId = 'ssh:ssh-1@@persisted-pty' - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - activeWorktreeIdsOnShutdown: [], - activeConnectionIdsAtShutdown: [], - remoteSessionIdsByTabId: {}, - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'host-tab', - ptyId: remotePtyId, - worktreeId: TEST_WORKTREE_ID, - title: 'Remote Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: remotePtyId }) - } - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - runtime.registerPty(remotePtyId, TEST_WORKTREE_ID, 'ssh-1', { - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID - }) - - runtime.attachWindow(TEST_WINDOW_ID) - - expect(getSession()).toMatchObject({ - activeWorktreeIdsOnShutdown: [TEST_WORKTREE_ID], - activeConnectionIdsAtShutdown: ['ssh-1'], - remoteSessionIdsByTabId: { 'host-tab': remotePtyId } - }) - }) - - it('restores a surviving renderer when its reload is cancelled', () => { - const runtime = createRuntime() - runtime.attachWindow(TEST_WINDOW_ID) - runtime.markGraphReady(TEST_WINDOW_ID) - const fence = runtime.markRendererReloading(TEST_WINDOW_ID) - if (fence === null) { - throw new Error('expected active renderer reload fence') - } - - expect(fence.recovery).toBe('renderer') - expect(runtime.getStatus().graphStatus).toBe('reloading') - expect(runtime.markRendererReloadCancelled(TEST_WINDOW_ID, fence)).toBe(true) - expect(runtime.getStatus().graphStatus).toBe('ready') - }) - it('keeps an earlier committed reload fenced when a later reload is cancelled', async () => { vi.useFakeTimers() try { @@ -122,23 +37,6 @@ describe('OrcaRuntimeService', () => { } }) - it('restores headless authority when desktop promotion navigation is cancelled', () => { - const runtime = createRuntime() - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - runtime.attachWindow(TEST_WINDOW_ID) - const fence = runtime.markRendererReloading(TEST_WINDOW_ID) - if (fence === null) { - throw new Error('expected active promotion reload fence') - } - - expect(fence.recovery).toBe('headless') - expect(runtime.markRendererReloadCancelled(TEST_WINDOW_ID, fence)).toBe(false) - expect(runtime.getStatus()).toMatchObject({ - authoritativeWindowId: HEADLESS_RUNTIME_WINDOW_ID, - graphStatus: 'ready' - }) - }) - it('restores headless graph authority after a promoted renderer reload times out', async () => { vi.useFakeTimers() try { @@ -166,46 +64,6 @@ describe('OrcaRuntimeService', () => { } }) - it('moves a desktop graph to unavailable when its reload times out', async () => { - vi.useFakeTimers() - try { - const runtime = createRuntime() - runtime.attachWindow(TEST_WINDOW_ID) - runtime.markGraphReady(TEST_WINDOW_ID) - runtime.markRendererReloading(TEST_WINDOW_ID) - - await vi.advanceTimersByTimeAsync(RUNTIME_GRAPH_RELOAD_TIMEOUT_MS) - - expect(runtime.getStatus()).toMatchObject({ - authoritativeWindowId: TEST_WINDOW_ID, - graphStatus: 'unavailable', - rendererGraphEpoch: 1 - }) - } finally { - vi.useRealTimers() - } - }) - - it('recovers a failed headless promotion and accepts a later renderer generation', () => { - const runtime = createRuntime() - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - runtime.attachWindow(TEST_WINDOW_ID) - - runtime.markGraphReloadFailed(TEST_WINDOW_ID, 'renderer-process-gone') - - expect(runtime.getStatus()).toMatchObject({ - authoritativeWindowId: HEADLESS_RUNTIME_WINDOW_ID, - graphStatus: 'ready' - }) - - runtime.syncWindowGraph(TEST_WINDOW_ID, { tabs: [], leaves: [] }) - - expect(runtime.getStatus()).toMatchObject({ - authoritativeWindowId: TEST_WINDOW_ID, - graphStatus: 'ready' - }) - }) - it('retires the headless fallback after renderer promotion succeeds', () => { const runtime = createRuntime() runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) diff --git a/src/main/runtime/orca-runtime-tests/workspace-layout-stream-events.test-fixture.ts b/src/main/runtime/orca-runtime-tests/workspace-layout-stream-events.test-fixture.ts index 7978945e743..7456b90e81f 100644 --- a/src/main/runtime/orca-runtime-tests/workspace-layout-stream-events.test-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/workspace-layout-stream-events.test-fixture.ts @@ -1,11 +1,11 @@ // Normalize records frames into per-workspace whole-layout events so both layout ownership modes share assertions. -import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' -import { applyWorkspaceLayoutRecordChange } from '../../../shared/workspace-layout/workspace-layout-records' +import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/published-layout/workspace-layout-published' +import { applyWorkspaceLayoutRecordChange } from '../../../shared/workspace-layout/published-layout/workspace-layout-records' import type { WorkspaceLayoutEvent, WorkspaceLayoutStreamEvent -} from '../../../shared/workspace-layout/workspace-layout-stream-frames' +} from '../../../shared/workspace-layout/published-layout/workspace-layout-stream-frames' export type LayoutEventCollector = { /** One per workspace changed, in frame order. */ diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts index f15dc34b58b..ae6898acc6e 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts @@ -96,8 +96,9 @@ describe('OrcaRuntimeService', () => { hostId: 'ssh:host-b' }) + const remoteRefusal = expect(remote).rejects.toThrow('selector_not_found') await localStarted.promise - await expect(remote).rejects.toThrow('selector_not_found') + await remoteRefusal finishRemovals.resolve() await expect(local).resolves.toEqual({}) diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts deleted file mode 100644 index c31815c0f7b..00000000000 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts +++ /dev/null @@ -1,155 +0,0 @@ -// Archive hook failure must preserve the checkout, Git registration, agents and ownership evidence (#19334). -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { assertWorktreeCleanForRemoval } from '../../git/worktrees/removal/worktree-removal-preflight' -import { - deleteWorktreeHistoryDirMock, - invalidateAuthorizedRootsCacheMock, - removeWorktreeLinkedPathsMock -} from '../orca-runtime-test-mocks/setup.spec' -import { getEffectiveHooks, runHook } from '../../workspace-hooks/hooks' -import { listWorktreesStrict } from '../../git/worktrees/catalog/worktree-listing' -import { removeWorktree } from '../../git/worktrees/removal/worktree-removal' -import { - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - createStaleRuntimeWorktreeStore, - deferred -} from './orca-runtime-test-fixtures.spec' -import { createWorktreeRemovalRuntime } from './orca-runtime-test-scenario-builders.spec' -import { - ARCHIVE_HOOK_FAILED_REMOVAL_CODE, - asArchiveHookRefusal -} from '../../../shared/worktree/archive-hook-removal-gate' -import '../../workspaces/removal/worktree-removal-acceptance-queue' -import '../../workspaces/removal/worktree-background-removal' - -function withArchiveHook(): void { - vi.mocked(getEffectiveHooks).mockReturnValue({ - scripts: { archive: 'pnpm worktree:archive' } - }) -} - -function expectNothingMutated(removeWorktreeMeta: ReturnType): void { - expect(removeWorktree).not.toHaveBeenCalled() - expect(removeWorktreeMeta).not.toHaveBeenCalled() - expect(removeWorktreeLinkedPathsMock).not.toHaveBeenCalled() - expect(deleteWorktreeHistoryDirMock).not.toHaveBeenCalled() - expect(invalidateAuthorizedRootsCacheMock).not.toHaveBeenCalled() - // Only the pre-hook lookup runs; hook failure prevents post-hook refresh and preflights. - expect(listWorktreesStrict).toHaveBeenCalledTimes(1) - expect(assertWorktreeCleanForRemoval).not.toHaveBeenCalled() -} - -describe('archive hook removal gate', () => { - // Aggregate imports share mocks; clear call counts here and restore defaults afterwards. - beforeEach(() => { - vi.clearAllMocks() - }) - - afterEach(() => { - vi.mocked(getEffectiveHooks).mockReturnValue(null) - vi.mocked(runHook).mockResolvedValue({ success: true, output: '' }) - }) - - it('refuses removal and mutates nothing when the archive hook exits 23', async () => { - const { runtimeStore, removeWorktreeMeta } = createStaleRuntimeWorktreeStore(TEST_WORKTREE_ID) - const runtime = createWorktreeRemovalRuntime(runtimeStore) - withArchiveHook() - vi.mocked(runHook).mockResolvedValue({ - success: false, - output: 'backup target unreachable', - exitCode: 23 - }) - - const failure = await runtime - .removeManagedWorktree(TEST_WORKTREE_ID, { force: false, runHooks: true }) - .catch((error: unknown) => error) - - const refusal = asArchiveHookRefusal(failure) - expect(refusal.code).toBe(ARCHIVE_HOOK_FAILED_REMOVAL_CODE) - expect(refusal.data).toEqual({ - worktreePath: TEST_WORKTREE_PATH, - outcome: 'exited', - exitCode: 23, - output: 'backup target unreachable' - }) - expectNothingMutated(removeWorktreeMeta) - }) - - it('refuses removal when the hook never reported an exit, without claiming it passed', async () => { - const { runtimeStore, removeWorktreeMeta } = createStaleRuntimeWorktreeStore(TEST_WORKTREE_ID) - const runtime = createWorktreeRemovalRuntime(runtimeStore) - withArchiveHook() - // Timeout or host loss is unverifiable, never a successful hook. - vi.mocked(runHook).mockResolvedValue({ - success: false, - output: 'Hook timed out after 120000ms.' - }) - - const failure = await runtime - .removeManagedWorktree(TEST_WORKTREE_ID, { force: false, runHooks: true }) - .catch((error: unknown) => error) - - const refusal = asArchiveHookRefusal(failure) - expect(refusal.data).toEqual({ - worktreePath: TEST_WORKTREE_PATH, - outcome: 'unverifiable', - output: 'Hook timed out after 120000ms.' - }) - expectNothingMutated(removeWorktreeMeta) - }) - - it('does not let --force waive a failed archive hook', async () => { - const { runtimeStore, removeWorktreeMeta } = createStaleRuntimeWorktreeStore(TEST_WORKTREE_ID) - const runtime = createWorktreeRemovalRuntime(runtimeStore) - withArchiveHook() - vi.mocked(runHook).mockResolvedValue({ - success: false, - output: 'boom', - exitCode: 23 - }) - - await expect( - runtime.removeManagedWorktree(TEST_WORKTREE_ID, { - force: true, - runHooks: true, - allowUnverifiedPtyStop: true - }) - ).rejects.toMatchObject({ code: ARCHIVE_HOOK_FAILED_REMOVAL_CODE }) - expectNothingMutated(removeWorktreeMeta) - }) - - it('does not coalesce an override retry onto the refusal already in flight', async () => { - const runtime = createWorktreeRemovalRuntime() - withArchiveHook() - const hookRun = deferred<{ - success: boolean - output: string - exitCode?: number - }>() - vi.mocked(runHook).mockReturnValue(hookRun.promise) - vi.mocked(removeWorktree).mockResolvedValue({}) - - const refused = runtime.removeManagedWorktree(TEST_WORKTREE_ID, { - force: false, - runHooks: true - }) - await vi.waitFor(() => expect(runHook).toHaveBeenCalled()) - - // A concurrent waiver changes the options key and must not join an attempt about to reject the hook. - await expect( - runtime.removeManagedWorktree(TEST_WORKTREE_ID, { - force: false, - runHooks: true, - allowUnverifiedPtyStop: false, - allowFailedArchiveHook: true - }) - ).rejects.toThrow('Worktree deletion already in progress') - - hookRun.resolve({ success: false, output: 'boom', exitCode: 23 }) - await expect(refused).rejects.toMatchObject({ - code: ARCHIVE_HOOK_FAILED_REMOVAL_CODE - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts index 3cc3289ed47..cae57710711 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts @@ -71,9 +71,7 @@ describe('runtime Delete on a failed delete’s leftover', () => { force, waitForBackgroundRemoval: false }) - ).rejects.toThrow( - `${leftover} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` - ) + ).rejects.toThrow(/folder was left on disk/) } await _settlePendingWorktreeRemovalsForTests() @@ -88,14 +86,22 @@ describe('runtime Delete on a failed delete’s leftover', () => { ]) }) - it('ends the row once the user removed the folder', async () => { + it('keeps the failure after manual folder removal until explicit retry finishes cleanup', async () => { const runtime = createWorktreeRemovalRuntime() await rm(leftover, { recursive: true, force: true }) const detected = await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`) - - expect(detected.worktrees.find((row) => row.id === leftoverId)).toBeUndefined() - await vi.waitFor(async () => expect(await readWorktreeRemovalRecords(directory)).toEqual([])) + expect(detected.worktrees.find((row) => row.id === leftoverId)).toMatchObject({ + removalError: FAILURE + }) + await runtime.removeManagedWorktree(`id:${leftoverId}`, { waitForBackgroundRemoval: true }) + await _settlePendingWorktreeRemovalsForTests() + expect( + (await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`)).worktrees.find( + (row) => row.id === leftoverId + ) + ).toBeUndefined() + expect(await readWorktreeRemovalRecords(directory)).toEqual([]) expect(removeWorktree).not.toHaveBeenCalled() }) }) diff --git a/src/main/runtime/orca-runtime-tests/worktree-selector-resolution.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-selector-resolution.spec.ts index 3db5b63dec5..4f6f9006b8f 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-selector-resolution.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-selector-resolution.spec.ts @@ -77,6 +77,8 @@ describe('OrcaRuntimeService', () => { vi.mocked(listWorktrees) .mockImplementationOnce(() => staleScan.promise) .mockResolvedValueOnce([createdWorktree]) + // listDetected prunes after the create, so it observes again with its own pre-scan claim. + .mockResolvedValueOnce([...MOCK_GIT_WORKTREES, createdWorktree]) .mockResolvedValueOnce([...MOCK_GIT_WORKTREES, createdWorktree]) const staleLookup = runtime.showManagedWorktree(TEST_WORKTREE_ID) diff --git a/src/main/runtime/orca-runtime-tests/worktree-setup-single-creator.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-setup-single-creator.spec.ts deleted file mode 100644 index b61723fed29..00000000000 --- a/src/main/runtime/orca-runtime-tests/worktree-setup-single-creator.spec.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' -import type { WorktreeStartupLaunch } from '../../../shared/worktree/launch-types' -import './runtime-test-module-registration.spec' -import { - computeWorktreePathMock, - ensurePathWithinWorkspaceMock -} from '../orca-runtime-test-mocks/setup.spec' -import { createSetupRunnerScript } from '../../workspace-hooks/worktree-runner-script' -import { getEffectiveHooks } from '../../workspace-hooks/hooks' -import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache' -import { setRuntimeDesktopSurface } from '../construction/runtime-desktop-surface' -import { shouldRunSetupForCreate } from '../../workspace-hooks/effective-hook-config' -import { makeRuntimeStoreWithWorkspaceSession, store } from './orca-runtime-test-fixtures.spec' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' -import { ProvisioningRuntime } from './orca-runtime-layout-owner-start-fixture' - -const WORKTREE_PATH = '/tmp/workspaces/runtime-setup-all' -const RUNNER = '/tmp/repo/.git/orca/setup-runner.sh' - -async function createActivated(options: { - startup?: WorktreeStartupLaunch - failAgentSpawn?: boolean -}): Promise<{ - activateWorktree: ReturnType - events: RuntimeClientEvent[] - spawnedCommands: (string | undefined)[] - runtime: ProvisioningRuntime - session: () => WorkspaceSessionState -}> { - const mainLayout = makeRuntimeStoreWithWorkspaceSession(getDefaultWorkspaceSession()) - const runtime = new ProvisioningRuntime( - ORCA_LAYOUT_OWNER_IS_MAIN ? mainLayout.runtimeStore : store - ) - const activateWorktree = vi.fn() - let spawned = 0 - const spawn = vi.fn(async (args: { command?: string }) => { - if (options.failAgentSpawn && args.command === options.startup?.command) { - throw new Error('agent_session_exited_during_start') - } - return { id: `pty-${++spawned}` } - }) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree, - createTerminal: vi.fn(), - revealTerminalSession: vi.fn().mockResolvedValue({ tabId: 'tab-revealed' }), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - // Keep a live window to exercise foreground provisioning. - const liveWindow = { isDestroyed: () => false, webContents: { isDestroyed: () => false } } - setRuntimeDesktopSurface({ - showNotification: () => false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create path reads only the window's liveness. - findWindowById: () => liveWindow as never, - onIpc: () => {}, - removeIpcListener: () => {} - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const events: RuntimeClientEvent[] = [] - const unsubscribe = runtime.onClientEvent((event) => events.push(event)) - - computeWorktreePathMock.mockReturnValue(WORKTREE_PATH) - ensurePathWithinWorkspaceMock.mockReturnValue(WORKTREE_PATH) - vi.mocked(getEffectiveHooks).mockReturnValue({ scripts: { setup: 'pnpm worktree:setup' } }) - vi.mocked(shouldRunSetupForCreate).mockReturnValue(true) - vi.mocked(createSetupRunnerScript).mockResolvedValue({ - runnerScriptPath: RUNNER, - envVars: { ORCA_ROOT_PATH: '/tmp/repo', ORCA_WORKTREE_PATH: WORKTREE_PATH } - }) - vi.mocked(listWorktrees).mockResolvedValue([ - { - path: WORKTREE_PATH, - head: 'def', - branch: 'runtime-setup-all', - isBare: false, - isMainWorktree: false - } - ]) - - try { - await runtime.createManagedWorktree({ - repoSelector: 'id:repo-1', - name: 'runtime-setup-all', - setupDecision: 'run', - activate: true, - navigation: 'all', - ...(options.startup ? { startup: options.startup } : {}) - }) - } finally { - unsubscribe() - setRuntimeDesktopSurface(null) - } - return { - activateWorktree, - events, - spawnedCommands: spawn.mock.calls.map(([args]) => args.command), - runtime, - session: mainLayout.getSession - } -} - -describe('OrcaRuntimeService setup creator', () => { - it('creates the setup terminal once when an activated create navigates the window and clients', async () => { - const { activateWorktree, events, spawnedCommands } = await createActivated({}) - - const hostHandoffs = activateWorktree.mock.calls.filter((call) => call[2] !== undefined) - const clientHandoffs = events.filter( - (event) => event.type === 'activateWorktree' && event.setup !== undefined - ) - expect({ - hostHandoffs: hostHandoffs.length, - clientHandoffs: clientHandoffs.length, - setupSpawns: spawnedCommands.filter((command) => command?.includes(RUNNER)).length - }).toEqual({ hostHandoffs: 0, clientHandoffs: 0, setupSpawns: 1 }) - }) - - it('hands the host window the whole create when the agent fails to start', async () => { - const startup = { command: 'claude' } - const { activateWorktree, events, spawnedCommands, runtime, session } = await createActivated({ - startup, - failAgentSpawn: true - }) - - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - expect(spawnedCommands).toEqual(['claude', expect.stringContaining(RUNNER)]) - expect(activateWorktree.mock.calls).toEqual([ - ['repo-1', expect.any(String), undefined, undefined, undefined] - ]) - const [agentRow] = Object.values(session().tabsByWorktree).flat() - const [agentLeafId] = collectLeafIds(session().terminalLayoutsByTabId[agentRow!.id]?.root) - expect(runtime.startStatusOf(`${agentRow!.id}:${agentLeafId}`)).toEqual({ - status: 'failed', - reason: 'agent_session_exited_during_start' - }) - expect( - events.filter((event) => event.type === 'activateWorktree' && event.setup !== undefined) - ).toEqual([]) - return - } - expect(spawnedCommands).toEqual(['claude']) - expect(activateWorktree).toHaveBeenCalledOnce() - expect(activateWorktree).toHaveBeenCalledWith( - 'repo-1', - expect.any(String), - expect.objectContaining({ runnerScriptPath: RUNNER }), - expect.objectContaining({ command: 'claude' }), - undefined - ) - expect( - events.filter((event) => event.type === 'activateWorktree' && event.setup !== undefined) - ).toEqual([]) - }) -}) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9156fdd5865..9c545bc77d2 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -4,7 +4,7 @@ import type { RuntimeLinearCommandSurface } from './integrations/linear/runtime- import { installRuntimeLinearCommandSurface } from './integrations/linear/runtime-linear-command-surface' import { publishNativeChatPreferenceChanges } from './agent-session/launch/runtime-native-chat-preference-events' import { publishSettingsChanges } from './client/settings/runtime-settings-change-events' -import { publishWorkspaceViewChanges } from './sidebar-inputs/runtime-workspace-view-change-events' +import { publishWorkspaceViewChanges } from './client/settings/runtime-workspace-view-change-events' import { OrcaRuntimeWithSidebarTemporal, sidebarFactsRuntime @@ -28,6 +28,7 @@ import { createAgentLaunchRecordWarmupGate } from './construction/agent-launch-r import * as WorkspaceLayouts from './terminal/surface/workspace-layout-stream' import type { RemoteLayoutSnapshot } from '../../shared/remote-layout-snapshot' import { registerDetectedWorktreeScanInvalidation } from '../ipc/worktrees/listing/register-detected-worktree-scan-invalidation' +import { registerWorktreeCatalogRoutes } from './workspaces/catalog/worktree-catalog-live-route' import { listReferenceWorkspaces, selectWarmedReferenceWorkspace, @@ -48,15 +49,15 @@ import { installStructuredAgentAvailability as installAvailability, type StructuredAgentAvailabilityReader as AvailabilityReader } from './agent-session/launch/structured-agent-availability' -import { PairedServerRowsProducer } from './sidebar-inputs/paired-server-rows-producer' -import { RepoIconDataUrls } from './sidebar-inputs/repo-icon-data-urls' -import { WorkspaceRowsProducer } from './sidebar-inputs/workspace-rows-producer' +import { PairedServerRowsProducer } from './sidebar-inputs/workspace-rows/paired-server-rows-producer' +import { RepoIconDataUrls } from './sidebar-inputs/repo-icons/repo-icon-data-urls' +import { WorkspaceRowsProducer } from './sidebar-inputs/workspace-rows/workspace-rows-producer' import { getMainHttpClient } from '../network/http-client' import { getRuntimeDesktopSurface } from './construction/runtime-desktop-surface' -import { CollapseWriteOrder } from './sidebar-inputs/workspace-view-collapse-writes' -import { SidebarInputsFeed } from './sidebar-inputs/sidebar-inputs-feed' +import { CollapseWriteOrder } from './client/settings/workspace-view-collapse-writes' +import { SidebarInputsFeed } from './sidebar-inputs/feed/sidebar-inputs-feed' import { sidebarInputsFeedDomains } from './sidebar-inputs/sidebar-inputs-feed-domains' -import { requireSwitchedOn } from './sidebar-inputs/require-switched-on' +import { requireSwitchedOn } from './construction/require-sidebar-inputs-enabled' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contracts' import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' import type { OrchestrationDb } from './orchestration/db/orchestration-db' @@ -201,6 +202,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { // Headless hosts must register both invalidators themselves; they never load desktop IPC. registerDetectedWorktreeScanInvalidation() registerWorktreeChangeInvalidator((repoId) => this.invalidateWorktreeCatalog(repoId)) + registerWorktreeCatalogRoutes(this.store) publishWorkspaceViewChanges(this.store, (event) => this.emitClientEvent(event)) publishNativeChatPreferenceChanges(this.store, (event) => this.emitClientEvent(event)) publishSettingsChanges(this.store, (event) => this.emitClientEvent(event)) diff --git a/src/main/runtime/orchestration/addressing/session-lineage/structured-session-lineage.ts b/src/main/runtime/orchestration/addressing/session-lineage/structured-session-lineage.ts index 0e463d3fbfe..5aec0a4558d 100644 --- a/src/main/runtime/orchestration/addressing/session-lineage/structured-session-lineage.ts +++ b/src/main/runtime/orchestration/addressing/session-lineage/structured-session-lineage.ts @@ -25,6 +25,9 @@ export type AgentSessionRecordReader = { /** Changes identity only when records join or leave or a /clear links them, so lookups derived from * every record's lineage can be reused across other writes. */ lineageRevision?: () => object + /** The chat whose provider handle chain names a native session id, from an index the store's + * commits keep; readers without it scan the records. */ + providerAliasOwner?: (nativeId: string) => string | null } /** Null until the agent-session host is installed; callers that must see records ensure it first. */ @@ -43,6 +46,7 @@ export function conversationRecordReader(store: { listClearedFrom?: (sessionId: string) => readonly string[] isSessionTabRetired?: AgentSessionRecordReader['isSessionTabRetired'] lineageRevision?: AgentSessionRecordReader['lineageRevision'] + providerAliasOwner?: AgentSessionRecordReader['providerAliasOwner'] }): AgentSessionRecordReader { return { getRecord: store.getConversation, @@ -55,7 +59,8 @@ export function conversationRecordReader(store: { : {}), ...(store.listClearedFrom ? { listClearedFrom: store.listClearedFrom } : {}), isSessionTabRetired: store.isSessionTabRetired, - lineageRevision: store.lineageRevision + lineageRevision: store.lineageRevision, + ...(store.providerAliasOwner ? { providerAliasOwner: store.providerAliasOwner } : {}) } } diff --git a/src/main/runtime/orchestration/crew/crew-mounted-render.test-fixture.ts b/src/main/runtime/orchestration/crew/crew-mounted-render.test-fixture.ts index 121deafa180..e8af83de983 100644 --- a/src/main/runtime/orchestration/crew/crew-mounted-render.test-fixture.ts +++ b/src/main/runtime/orchestration/crew/crew-mounted-render.test-fixture.ts @@ -1,7 +1,7 @@ import { CrewReadModel } from './crew-read-model' import { fixture } from './crew-read-model.test-fixture' import { subscribeCrew } from './crew-stream' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { testOrcaSessionId } from '../../../../shared/orca-session-address-test-fixture' import { formatOrcaSessionAddress } from '../../../../shared/orca-session-address' diff --git a/src/main/runtime/orchestration/crew/crew-read-model.test.ts b/src/main/runtime/orchestration/crew/crew-read-model.test.ts index 0e7cf250ec9..9a2bcb0df2a 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.test.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest' import { buildCrewSnapshot } from './crew-party-snapshot' import { CrewReadModel } from './crew-read-model' import { subscribeCrew } from './crew-stream' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { fixture } from './crew-read-model.test-fixture' diff --git a/src/main/runtime/orchestration/crew/crew-recipient-authority.test.ts b/src/main/runtime/orchestration/crew/crew-recipient-authority.test.ts index 060a9505d6e..7ccc014529d 100644 --- a/src/main/runtime/orchestration/crew/crew-recipient-authority.test.ts +++ b/src/main/runtime/orchestration/crew/crew-recipient-authority.test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { isOrcaSessionId, formatOrcaSessionAddress } from '../../../../shared/orca-session-address' import { testOrcaSessionId } from '../../../../shared/orca-session-address-test-fixture' diff --git a/src/main/runtime/orchestration/crew/crew-recipient-delta-cost.test-fixture.ts b/src/main/runtime/orchestration/crew/crew-recipient-delta-cost.test-fixture.ts index 5e2c12e4b19..c732965302b 100644 --- a/src/main/runtime/orchestration/crew/crew-recipient-delta-cost.test-fixture.ts +++ b/src/main/runtime/orchestration/crew/crew-recipient-delta-cost.test-fixture.ts @@ -1,4 +1,4 @@ -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { testOrcaSessionId } from '../../../../shared/orca-session-address-test-fixture' import { formatOrcaSessionAddress as address } from '../../../../shared/orca-session-address' diff --git a/src/main/runtime/orchestration/crew/crew-recipient-follow-up-cost.test.ts b/src/main/runtime/orchestration/crew/crew-recipient-follow-up-cost.test.ts deleted file mode 100644 index fe959d025a2..00000000000 --- a/src/main/runtime/orchestration/crew/crew-recipient-follow-up-cost.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -import * as helperScope from '../../rpc/methods/orchestration/worker/helper-start-scope' -import * as custodyHistory from '../db/pane-key-match' -import { crewQueryPlans, meterCrewSql, sqlTotals } from './crew-recipient-sql.test-fixture' -import * as followUpPlan from '../db/dispatch-context/worker-follow-up-plan' -import { z } from 'zod' -import { expect, it, vi } from 'vitest' -import { CrewReadModel } from './crew-read-model' -import { deltaFixture } from './crew-recipient-delta-cost.test-fixture' - -it('charges selected genuine worker follow-up lineage, origin and caller facts at N and 10N without per-row SQL', () => { - const samples = [3, 30].map((population) => { - const f = deltaFixture() - f.records.clear() - f.visible.clear() - const roots: string[] = [] - for (let i = 0; i < population; i++) { - const index = String(i).padStart(2, '0') - const handle = `term_follow_${index}` - const pane = `tab_follow_${index}:aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` - f.handles.set(handle, pane) - const root = f.db.createStartingWorkerDispatch({ - creator: { kind: 'terminal', handle: 'term_coord', paneKey: f.handles.get('term_coord') }, - maxDepth: 10, - taskSpec: `original ${i}`, - taskRunId: f.run.id, - startOptions: { agent: 'codex' } - }) - f.db.prepareStartingWorkerAuthority({ - dispatchId: root.dispatch.id, - handle, - paneKey: pane, - processIncarnation: `process:${handle}`, - worktreeId: 'folder-worker-host', - effects: [], - setupState: 'not_applicable', - terminalOwnership: 'created' - }) - f.db.markWorkerDispatchReady(root.dispatch.id) - f.db.settleWorkerReport({ - taskId: root.task.id, - dispatchId: root.dispatch.id, - outcome: 'succeeded', - result: 'done' - }) - roots.push(root.dispatch.id) - const failed = f.db.createStartingWorkerDispatch({ - creator: { kind: 'terminal', handle: 'term_coord', paneKey: f.handles.get('term_coord') }, - maxDepth: 10, - taskSpec: `unplaced ${i}`, - taskRunId: f.run.id, - startOptions: { agent: 'codex' }, - followUpOf: root.dispatch.id - }) - f.db.failWorkerStart(failed.dispatch.id, 'terminal_create', 'No terminal opened') - } - let visits = 0 - const actual = followUpPlan.resolveWorkerLineageFacts - const traversal = vi - .spyOn(followUpPlan, 'resolveWorkerLineageFacts') - .mockImplementation((facts, id) => - actual( - { - dispatch: (key) => { - visits++ - return facts.dispatch(key) - }, - ownedResource: (key) => { - visits++ - return facts.ownedResource(key) - }, - formerResource: (key) => { - visits++ - return facts.formerResource(key) - }, - followUp: (key) => { - visits++ - return facts.followUp(key) - } - }, - id - ) - ) - const live = vi.fn(f.deps.livePaneForHandle!) - const processRead = vi.fn(f.deps.processForHandle!) - f.deps.livePaneForHandle = live - f.deps.processForHandle = processRead - const meter = meterCrewSql(f.db.db) - const model = new CrewReadModel(() => f.deps, f.db.crewChanges.subscribe) - const stop = model.subscribe(() => {}) - try { - const output = model.read('term_coord') - const rows = Object.values(output.sections).flat() - for (const root of roots) { - expect(rows.some((row) => row.sendAddress === `dispatch:${root}`)).toBe(true) - } - const raw = meter.executions.slice() - const acquired = raw.filter((entry) => entry.sql.includes('crew_follow_up_seeds')) - expect(acquired).toHaveLength(1) - expect(acquired[0].rows).toBe(2 * population) - const keys = z.array(z.string()).parse(JSON.parse(String(acquired[0].parameters[0]))) - expect(new Set(keys).size).toBe(keys.length) - expect(keys).toEqual(expect.arrayContaining(roots)) - const work = { - visits, - traversals: traversal.mock.calls.length, - live: live.mock.calls.length, - process: processRead.mock.calls.length - } - const before = meter.executions.length - expect(model.read('term_coord')).toEqual(output) - expect( - meter.executions.slice(before).filter((entry) => entry.sql.includes('crew_follow_up_seeds')) - ).toHaveLength(0) - f.db.rekeyWorkerTerminalResourcePaneKey({ - fromPaneKey: f.handles.get('term_follow_00')!, - toPaneKey: f.handles.get('term_follow_00')! - }) - expect(model.read('term_coord')).toEqual(output) - expect( - meter.executions.filter((entry) => entry.sql.includes('crew_follow_up_seeds')) - ).toHaveLength(2) - stop() - return { - selected: sqlTotals(acquired), - boundKeys: keys.length, - boundChars: String(acquired[0].parameters[0]).length, - work - } - } finally { - stop() - meter.restore() - traversal.mockRestore() - } - }) - for (const field of ['all', 'rows', 'bytes', 'stringChars'] as const) { - expect(samples[1].selected[field]).toBeLessThanOrEqual(10 * samples[0].selected[field]) - } - expect(samples[1].boundKeys).toBeLessThanOrEqual(10 * samples[0].boundKeys) - expect(samples[1].boundChars).toBeLessThanOrEqual(10 * samples[0].boundChars) - for (const field of ['visits', 'traversals', 'live', 'process'] as const) { - expect(samples[1].work[field]).toBeLessThanOrEqual(10 * samples[0].work[field]) - } -}) - -it('shares one caller continuation union across selected starts and charges raw misses, histories and warm recomputation', () => { - const samples = [ - [3, 3], - [30, 30] - ].map(([eligible, closure]) => { - const f = deltaFixture() - f.records.clear() - f.visible.clear() - const make = (handle: string, creator: string, previous?: string) => { - f.handles.set( - handle, - f.handles.get(handle) ?? - `tab_${handle}:aaaaaaaa-aaaa-4aaa-8aaa-${handle.slice(-2).padStart(12, '0')}` - ) - const start = f.db.createStartingWorkerDispatch({ - creator: { kind: 'terminal', handle: creator, paneKey: f.handles.get(creator) }, - maxDepth: 100, - taskRunId: f.run.id, - taskSpec: `work ${handle}`, - startOptions: { agent: 'codex' }, - followUpOf: previous - }) - f.db.prepareStartingWorkerAuthority({ - dispatchId: start.dispatch.id, - handle, - paneKey: f.handles.get(handle)!, - processIncarnation: `process:${handle}`, - worktreeId: 'folder-worker-host', - effects: [], - setupState: 'not_applicable', - terminalOwnership: previous ? 'external' : 'created' - }) - f.db.markWorkerDispatchReady(start.dispatch.id) - return start - } - const settle = (start: ReturnType) => - f.db.settleWorkerReport({ - dispatchId: start.dispatch.id, - taskId: start.task.id, - outcome: 'succeeded', - result: 'done' - }) - let caller = make('term_worker', 'term_coord') - const targets = Array.from({ length: eligible }, (_, i) => { - const target = make(`term_cost_${String(i).padStart(2, '0')}`, 'term_worker') - settle(target) - return target.dispatch.id - }) - for (let depth = 1; depth < closure; depth++) { - settle(caller) - caller = make('term_worker', 'term_coord', caller.dispatch.id) - } - let visits = 0 - const algorithm = helperScope.createHelperStartScope - const scope = vi - .spyOn(helperScope, 'createHelperStartScope') - .mockImplementation((read, creator) => - algorithm( - { - ...read, - dispatch: (id) => { - visits++ - return read.dispatch(id) - } - }, - creator - ) - ) - const decoder = vi.spyOn(custodyHistory, 'parseWorkerTerminalPriorOwnerIds') - const meter = meterCrewSql(f.db.db) - const model = new CrewReadModel(() => f.deps, f.db.crewChanges.subscribe) - const stop = model.subscribe(() => {}) - const authority = (sql: string) => - sql.startsWith('SELECT id, run_id, creator_dispatch_id') || - sql.includes('prior_owner_dispatch_ids FROM worker_terminal_resources') || - sql.startsWith('SELECT id, legacy FROM runs') || - sql.startsWith('SELECT dispatch_id, depth') - try { - const output = model.read('term_worker') - for (const id of targets) { - expect(output.sections.managing.some((row) => row.sendAddress === `dispatch:${id}`)).toBe( - true - ) - } - const cold = meter.executions.filter((entry) => authority(entry.sql)) - const coldVisits = visits - const histories = decoder.mock.calls.map(([text]) => text.length) - expect(scope).toHaveBeenCalledTimes(1) - expect(coldVisits).toBeLessThanOrEqual(eligible + closure + 2) - expect(histories).toHaveLength(1) - const queries = cold.map((row) => JSON.stringify([row.sql, row.parameters])) - expect(new Set(queries).size).toBe(queries.length) - const mark = meter.executions.length - expect(model.read('term_worker')).toEqual(output) - expect(meter.executions.slice(mark).filter((entry) => authority(entry.sql))).toHaveLength(0) - expect(visits - coldVisits).toBe(coldVisits) - const plans = crewQueryPlans(f.db.db, cold) - expect(JSON.stringify(plans)).not.toMatch( - /SCAN (?:worker_terminal_resources|remote_dispatch_attachments)/ - ) - settle(caller) - const retired = model.read('term_worker') - expect( - retired.sections.managing.every((row) => !row.sendAddress?.startsWith('dispatch:')) - ).toBe(true) - const afterWrite = meter.executions.filter((entry) => authority(entry.sql)).length - expect(afterWrite).toBeGreaterThan(cold.length) - stop() - const reacquired = model.read('term_worker') - expect(reacquired).toEqual(retired) - expect(meter.executions.filter((entry) => authority(entry.sql)).length).toBeGreaterThan( - afterWrite - ) - return sqlTotals(cold) - } finally { - stop() - meter.restore() - scope.mockRestore() - decoder.mockRestore() - } - }) - for (const field of ['all', 'rows', 'bytes', 'stringChars'] as const) { - expect(samples[1][field]).toBeLessThanOrEqual(10 * samples[0][field]) - } -}) diff --git a/src/main/runtime/orchestration/crew/crew-recipient-mailbox-selection.ts b/src/main/runtime/orchestration/crew/crew-recipient-mailbox-selection.ts index 2cfbd981463..7d9bd63c085 100644 --- a/src/main/runtime/orchestration/crew/crew-recipient-mailbox-selection.ts +++ b/src/main/runtime/orchestration/crew/crew-recipient-mailbox-selection.ts @@ -3,7 +3,7 @@ import { createWorkerFollowUpQualification, planSemanticWorkerFollowUp, workerFollowUpArguments -} from '../../rpc/methods/orchestration/worker/worker-follow-up-admission' +} from '../../rpc/methods/orchestration/worker/follow-up/worker-follow-up-admission' import type { createCrewFollowUpAuthorityInputs } from './crew-follow-up-authority-inputs' import type { DispatchCreator } from '../db/dispatch-depth' import { diff --git a/src/main/runtime/orchestration/crew/crew-recipient-nested-authority.test.ts b/src/main/runtime/orchestration/crew/crew-recipient-nested-authority.test.ts deleted file mode 100644 index bfc044d5106..00000000000 --- a/src/main/runtime/orchestration/crew/crew-recipient-nested-authority.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { testOrcaSessionId } from '../../../../shared/orca-session-address-test-fixture' -import { fixture } from './crew-read-model.test-fixture' -import { meterCrewSql, sqlTotals } from './crew-recipient-sql.test-fixture' -import { CrewReadModel } from './crew-read-model' -import { OrcaRuntimeService } from '../../orca-runtime' -import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' -import { formatOrcaSessionAddress } from '../../../../shared/orca-session-address' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerIdentityFromRow, - structuredWorkerProcessIncarnation -} from '../terminal-authority/structured-sessions/structured-worker-identity' -import { backfillStructuredWorkerOrcaSessionIds } from '../db/schema/structured-worker-orca-session-backfill' -import * as recipientRouting from '../../rpc/methods/orchestration/messaging/recipient-routing' -import { afterEach, expect, it, vi } from 'vitest' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) -afterEach(() => { - vi.restoreAllMocks() -}) - -it('keeps retained NULL-session nested structured process reads inside selected batches at N/10N', () => { - const samples = [3, 30].map((population) => { - const f = fixture() - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(f.db) - const records = new Map>() - const identities = Array.from({ length: population }, (_, i) => { - const session = testOrcaSessionId(`chat-nested-${i}`) - const handle = mintStructuredWorkerHandle() - const pane = mintStructuredWorkerPaneKey(session) - const task = () => f.db.createTask({ runId: f.run.id, spec: 'retained nested owner' }).id - const older = f.db.createDispatchContext({ - taskId: task(), - assigneeHandle: `term_older_${i}`, - creator: { kind: 'system' }, - maxDepth: 10 - }) - const oldResource = f.db.createWorkerTerminalResourceStatement({ - dispatchId: older.id, - worktreeId: 'wt_nested', - terminalHandle: handle, - paneKey: null, - processIncarnation: structuredWorkerProcessIncarnation(`chat-older-${i}`), - ownership: 'owned' - }) - f.db.db - .prepare("UPDATE worker_terminal_resources SET updated_at = '2000-01-01' WHERE id = ?") - .run(oldResource.id) - const dispatch = f.db.createDispatchContext({ - taskId: task(), - assigneeHandle: handle, - assigneePaneKey: pane, - processIncarnation: structuredWorkerProcessIncarnation(session), - creator: { kind: 'system' }, - maxDepth: 10 - }) - const resource = f.db.createWorkerTerminalResourceStatement({ - dispatchId: dispatch.id, - worktreeId: 'wt_nested', - terminalHandle: handle, - paneKey: pane, - processIncarnation: structuredWorkerProcessIncarnation(session), - hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), - ownership: 'owned' - }) - // Retained older writers omitted this column; conflicting evidence must remain NULL after open. - f.db.db - .prepare('UPDATE dispatch_contexts SET assignee_orca_session_id = NULL WHERE id = ?') - .run(dispatch.id) - const identity = structuredWorkerIdentityFromRow(resource) - if (!identity) { - throw new Error('Expected actual validated structured resource identity') - } - structuredWorkerIdentities.register(identity) - records.set( - session, - agentSessionConversationView(agentSessionRecordFixture({ sessionId: session })) - ) - f.handles.set(handle, pane) - f.db.insertMessage({ - from: formatOrcaSessionAddress(session), - to: 'term_worker', - subject: 'Nested peer', - body: session - }) - return { ...identity, dispatch } - }) - backfillStructuredWorkerOrcaSessionIds(f.db.db) - for (const identity of identities) { - expect(f.db.getDispatchContextById(identity.dispatch.id)?.assignee_orca_session_id).toBeNull() - expect( - f.db.getCurrentRunForCoordinator({ - terminalHandle: identity.handle, - paneKey: identity.paneKey, - orcaSessionId: testOrcaSessionId(identity.sessionId) - }) - ).toBeUndefined() - } - f.deps.records = { - listRecords: () => [...records.values()], - getRecord: (id) => records.get(id) ?? null, - getVisibleSessionTabIndex: () => ({ present: true, sessionIds: [...records.keys()] }) - } - hostRef.current = { - deps: { - store: { - getConversation: (id: string) => records.get(id) ?? null, - listConversations: () => [...records.values()] - } - }, - getPersistedVisibleSessionTabIndex: () => ({ present: true, sessionIds: [...records.keys()] }) - } - const context = runtime.createTerminalIdentityReadContext() - f.deps.openIdentityRead = () => ({ - liveHandle: f.deps.liveHandle, - handleForPane: f.deps.handleForPane, - paneForHandle: f.deps.paneForHandle, - name: f.deps.name, - processForHandle: (handle) => runtime.getTerminalProcessIncarnation(handle, context) - }) - f.deps.livePaneForHandle = (handle) => runtime.getLiveTerminalPaneKey(handle, context) - const productionProcess = runtime.getTerminalProcessIncarnation.bind(runtime) - const meter = meterCrewSql(f.db.db) - let nestedProcess = 0 - let selecting = false - const select = recipientRouting.dispatchAssigneeCoordinatorKey - const selection = vi - .spyOn(recipientRouting, 'dispatchAssigneeCoordinatorKey') - .mockImplementation((...args) => { - selecting = true - meter.control.phase = 'selecting' - try { - return select(...args) - } finally { - selecting = false - meter.control.phase = 'trigger' - } - }) - const process = vi - .spyOn(runtime, 'getTerminalProcessIncarnation') - .mockImplementation((...args) => { - if (selecting) { - nestedProcess++ - } - return productionProcess(...args) - }) - const operations = () => ({ - ...sqlTotals(meter.executions), - nestedGet: meter.executions.filter( - (entry) => entry.phase === 'selecting' && entry.method === 'get' - ).length, - nestedProcess - }) - const registration = vi.spyOn(structuredWorkerIdentities, 'register') - const model = new CrewReadModel(() => f.deps, f.db.crewChanges.subscribe) - const stop = model.subscribe(() => {}) - try { - const output = model.read('term_worker') - expect(output.sections.talkingWith).toHaveLength(population) - expect( - output.sections.talkingWith.every((row) => row.sendAddress && row.latest && row.openTarget) - ).toBe(true) - expect(registration).not.toHaveBeenCalled() - const measured = operations() - expect(measured.selected).toBeLessThanOrEqual(5) - // Actual baseline presentation resolves/registers cold identities before the selected callback. - structuredWorkerIdentities.clear() - f.db.crewChanges.notify(new Set(['topology'])) - const beforeCold = operations() - expect(model.read('term_worker')).toEqual(output) - expect(registration).toHaveBeenCalledTimes(population) - expect(operations().nestedGet - beforeCold.nestedGet).toBe(0) - expect(operations().nestedProcess - beforeCold.nestedProcess).toBe(0) - return measured - } finally { - stop() - meter.restore() - process.mockRestore() - selection.mockRestore() - registration.mockRestore() - hostRef.current = null - structuredWorkerIdentities.clear() - } - }) - expect(samples.map((sample) => sample.nestedProcess)).toEqual([0, 0]) - expect(samples.map((sample) => sample.nestedGet)).toEqual([0, 0]) - expect(samples[1].all).toBe(samples[0].all) - expect(samples[1].get).toBeLessThanOrEqual(10 * samples[0].get) -}) diff --git a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts index 28948462d3b..4fc7015d837 100644 --- a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts +++ b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts @@ -75,6 +75,17 @@ export function listHomePeerMailEnvironments(this: OrchestrationDb): string[] { return rows.map((row) => row.environment_id) } +/** One server's check, for its pull loop: a seek on that server's home rows, not every server's. */ +export function hasHomePeerMailEnvironment(this: OrchestrationDb, environmentId: string): boolean { + return ( + this.db + .prepare( + `SELECT 1 FROM peer_mail_conversations WHERE role = 'home' AND environment_id = ? LIMIT 1` + ) + .get(environmentId) !== undefined + ) +} + /** Conversations a paired Orca opened here that hold replies it has not acknowledged yet. */ export function listPeerConversationIdsWithPendingReplies( this: OrchestrationDb, @@ -178,6 +189,7 @@ export type PeerMailStoreMethods = { openHomePeerMailConversation: typeof openHomePeerMailConversation getPeerMailConversation: typeof getPeerMailConversation listHomePeerMailEnvironments: typeof listHomePeerMailEnvironments + hasHomePeerMailEnvironment: typeof hasHomePeerMailEnvironment listPeerConversationIdsWithPendingReplies: typeof listPeerConversationIdsWithPendingReplies getPeerMailMessage: typeof getPeerMailMessage isPeerMailSenderLabel: typeof isPeerMailSenderLabel @@ -189,6 +201,7 @@ export function attachPeerMailStore(ctor: { prototype: object }): void { openHomePeerMailConversation, getPeerMailConversation, listHomePeerMailEnvironments, + hasHomePeerMailEnvironment, listPeerConversationIdsWithPendingReplies, getPeerMailMessage, isPeerMailSenderLabel, diff --git a/src/main/runtime/orchestration/db/messages/message-inbox.ts b/src/main/runtime/orchestration/db/messages/message-inbox.ts index 5036288daa9..711c851f17f 100644 --- a/src/main/runtime/orchestration/db/messages/message-inbox.ts +++ b/src/main/runtime/orchestration/db/messages/message-inbox.ts @@ -3,6 +3,7 @@ import { exposeMessageTimestamps, exposeMessageListTimestamps } from '../utc-tim import { addLifecycleRejectionMarker } from '../lifecycle-rejection-marker' import type { OrchestrationDb } from '../orchestration-db' import { MESSAGE_COLUMN_LIST } from '../row-column-lists' +import { runOwnsDirectMessageSql } from '../runs/run-coordinator-mail-routing' const MESSAGE_ID_UPDATE_BATCH_SIZE = 500 const MESSAGE_MUTATION_SAVEPOINT = 'message_id_mutation' @@ -34,28 +35,22 @@ function runBatchedMessageMutation( export function getUnreadMessages( this: OrchestrationDb, toHandle: string, - types?: MessageType[] + types?: MessageType[], + options?: { excludeRunOwnedDirect?: boolean } ): MessageRow[] { - if (types && types.length > 0) { - const placeholders = types.map(() => '?').join(',') - return exposeMessageListTimestamps( - this.db - .prepare( - `SELECT * FROM messages - WHERE to_handle = ? AND read = 0 AND delivery_contract = 'current_delivery' - AND type IN (${placeholders}) ORDER BY sequence` - ) - .all(toHandle, ...types) as MessageRow[] - ) - } + const typeSql = types?.length ? ` AND type IN (${types.map(() => '?').join(',')})` : '' + const runOwnedSql = options?.excludeRunOwnedDirect + ? ` AND NOT ${runOwnsDirectMessageSql('messages')}` + : '' return exposeMessageListTimestamps( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over messages returns the row shape its schema and MessageRow define, like every row cast in db/. this.db .prepare( `SELECT * FROM messages - WHERE to_handle = ? AND read = 0 AND delivery_contract = 'current_delivery' + WHERE to_handle = ? AND read = 0 AND delivery_contract = 'current_delivery'${typeSql}${runOwnedSql} ORDER BY sequence` ) - .all(toHandle) as MessageRow[] + .all(toHandle, ...(types ?? [])) as MessageRow[] ) } @@ -93,14 +88,20 @@ export function getUndeliveredUnreadMessages( this: OrchestrationDb, toHandle: string, types?: MessageType[], - options?: { excludeTypes?: readonly string[]; excludeIds?: readonly string[]; limit?: number } + options?: { + excludeTypes?: readonly string[] + excludeIds?: readonly string[] + excludeRunOwnedDirect?: boolean + limit?: number + } ): MessageRow[] { const conditions = [ 'to_handle = ?', 'read = 0', 'delivered_at IS NULL', 'pointer_enter_pending = 0', - "delivery_contract = 'current_delivery'" + "delivery_contract = 'current_delivery'", + ...(options?.excludeRunOwnedDirect ? [`NOT ${runOwnsDirectMessageSql('messages')}`] : []) ] const params: (string | number)[] = [toHandle] if (types?.length) { diff --git a/src/main/runtime/orchestration/db/orchestration-db.test.ts b/src/main/runtime/orchestration/db/orchestration-db.test.ts index 62db8bd591c..9fad89a5977 100644 --- a/src/main/runtime/orchestration/db/orchestration-db.test.ts +++ b/src/main/runtime/orchestration/db/orchestration-db.test.ts @@ -49,53 +49,9 @@ describe('OrchestrationDb', () => { /already has an active dispatch/ ) }) - - it('getLatestDispatchForTerminal returns the most recent completed dispatch', () => { - const d = createDb() - const firstTask = d.createTask({ - runId, - spec: 'first' - }) - const first = createRootDispatch(d, firstTask.id, 'term_a') - d.completeDispatch(first.id) - const secondTask = d.createTask({ - runId, - spec: 'second' - }) - const second = createRootDispatch(d, secondTask.id, 'term_a') - d.completeDispatch(second.id) - - const latest = d.getLatestDispatchForTerminal('term_a') - expect(latest?.id).toBe(second.id) - expect(latest?.status).toBe('completed') - expect(d.getActiveDispatchForTerminal('term_a')).toBeUndefined() - }) }) describe('decision gates', () => { - it('creates a gate and blocks the task', () => { - const d = createDb() - const task = d.createTask({ - runId, - spec: 'needs approval' - }) - createRootDispatch(d, task.id, 'term_a') - const gate = d.createGate({ - taskId: task.id, - question: 'Proceed?', - options: ['yes', 'no'] - }) - - expect(gate.id).toMatch(/^gate_/) - expect(gate.task_id).toBe(task.id) - expect(gate.status).toBe('pending') - expect(JSON.parse(gate.options)).toEqual(['yes', 'no']) - - const updated = d.getTask(task.id) - expect(updated?.status).toBe('blocked') - expect(d.getActiveDispatchForTerminal('term_a')).toBeUndefined() - }) - it('rolls back the gate row when the Task transition cannot commit', () => { const d = createDb() const task = d.createTask({ runId: 'run_legacy_local', spec: 'atomic gate creation' }) diff --git a/src/main/runtime/orchestration/db/orchestration-db.ts b/src/main/runtime/orchestration/db/orchestration-db.ts index e45a66e03ce..405cc6327f0 100644 --- a/src/main/runtime/orchestration/db/orchestration-db.ts +++ b/src/main/runtime/orchestration/db/orchestration-db.ts @@ -42,6 +42,8 @@ class OrchestrationDbCore { this.db.pragma('journal_mode = WAL') this.db.pragma('synchronous = NORMAL') this.db.pragma('busy_timeout = 5000') + // Truncate the WAL back to 8 MiB after a checkpoint, as the other app databases do; otherwise it stays at its high-water size. + this.db.pragma('journal_size_limit = 8388608') // Savepoint journals otherwise need a temp file; a full or unwritable temp dir then aborts the whole transaction (#38123). this.db.pragma('temp_store = MEMORY') createTables.call(this as unknown as OrchestrationDb) diff --git a/src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts b/src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts index 48876ff1790..a29d0302d7c 100644 --- a/src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts +++ b/src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts @@ -47,6 +47,15 @@ function coordinatorAliasSql(runIdSql: string, addressSql: string): string { )` } +/** Whether routing would move direct row `messageSql`: alias OR active Dispatch, unlike the insert trigger's alias AND NOT Dispatch. */ +export function runOwnsDirectMessageSql(messageSql: string): string { + const runIdSql = `${messageSql}.run_id` + const addressSql = `${messageSql}.to_handle` + return `(EXISTS (SELECT 1 FROM runs WHERE runs.id = ${runIdSql} AND runs.legacy = 0) + AND (${coordinatorAliasSql(runIdSql, addressSql)} + OR ${activeDispatchOwnsAddressSql(runIdSql, addressSql)}))` +} + export function rememberRunCoordinatorHandle( this: OrchestrationDb, runId: string, diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-created-worktrees.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-created-worktrees.ts new file mode 100644 index 00000000000..6743a2f1cf6 --- /dev/null +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-created-worktrees.ts @@ -0,0 +1,144 @@ +import { + WORKER_SETTLED_STATES, + type WorkerTerminalReleaseState +} from '../../terminal-authority/release/worker-terminal-ownership' +import type { WorkerDispatchState } from '../orchestration-records' +import { dispatchCompletionEpoch } from '../dispatch-context/dispatch-completion-epoch' +import type { OrchestrationDb } from '../orchestration-db' +import { parseWorkerTerminalPriorOwnerIds } from '../pane-key-match' +import { readWorkerTerminalHostScope } from '../../../../../shared/orchestration/workers/worker-terminal-host-scope' + +export type WorkerCreatedWorktree = { + /** When the newest creating worker's terminal started; a workspace made later at that path is not the worker's. */ + workerStartedAt: number + /** Every dispatch that used the workspace has released its terminal or settled without one. */ + released: boolean +} + +type WorkerWorktreeUseRow = { + dispatch_id: string + worktree_id: string + state: WorkerDispatchState + effects: string + terminal_handle: string | null +} + +type WorkerTerminalRow = { + origin_dispatch_id: string + owner_dispatch_id: string + prior_owner_dispatch_ids: string + created_at: string + host_scope: string | null + worktree_id: string | null + release_state: WorkerTerminalReleaseState +} + +/** Workspaces a worker start created, keyed by worktree id. Reused workspaces are never listed. */ +export function listWorkerCreatedWorktrees( + db: OrchestrationDb +): Map { + // Local workers live in worker_dispatches; on a federated worker's host they live in remote_dispatch_attachments. + // A worker still starting in an existing workspace has only its resolved target, not worktree_id yet. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query selects exactly these columns. + const rows = db.db + .prepare( + `SELECT * FROM ( + SELECT dispatch_id, state, effects, agent_terminal_handle AS terminal_handle, + COALESCE(worktree_id, CASE WHEN json_valid(start_options) + THEN json_extract(start_options, '$.resolvedWorktreeId') END) AS worktree_id + FROM worker_dispatches + ) WHERE worktree_id IS NOT NULL + UNION ALL + SELECT dispatch_id, state, effects, terminal_handle, worktree_id + FROM remote_dispatch_attachments WHERE worktree_id IS NOT NULL` + ) + .all() as WorkerWorktreeUseRow[] + const terminals = readWorkerTerminals(db) + const uses = new Map() + for (const row of rows) { + const use = uses.get(row.worktree_id) ?? { startedAt: null, held: false } + const startedAt = terminals.startedAtByOrigin.get(row.dispatch_id) + if (startedAt !== undefined && createdWorktree(row.effects, row.worktree_id)) { + use.startedAt = Math.max(use.startedAt ?? 0, startedAt) + } + // A terminal row speaks for its owner; a dispatch whose terminal moved on, or never existed, holds nothing once settled. + use.held ||= + !terminals.owners.has(row.dispatch_id) && + ((row.terminal_handle !== null && !terminals.handedOff.has(row.dispatch_id)) || + !WORKER_SETTLED_STATES.includes(row.state)) + uses.set(row.worktree_id, use) + } + const created = new Map() + for (const [worktreeId, use] of uses) { + if (use.startedAt !== null) { + created.set(worktreeId, { + workerStartedAt: use.startedAt, + released: + !use.held && + terminals.releasedWorktreeIds.has(worktreeId) && + !terminals.heldWorktreeIds.has(worktreeId) + }) + } + } + return created +} + +function readWorkerTerminals(db: OrchestrationDb): { + startedAtByOrigin: Map + owners: Set + handedOff: Set + releasedWorktreeIds: Set + heldWorktreeIds: Set +} { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query selects exactly these columns. + const rows = db.db + .prepare( + `SELECT origin_dispatch_id, owner_dispatch_id, prior_owner_dispatch_ids, created_at, + host_scope, worktree_id, release_state + FROM worker_terminal_resources` + ) + .all() as WorkerTerminalRow[] + const terminals = { + startedAtByOrigin: new Map(), + owners: new Set(), + handedOff: new Set(), + releasedWorktreeIds: new Set(), + heldWorktreeIds: new Set() + } + for (const row of rows) { + const startedAt = dispatchCompletionEpoch(row.created_at) + // An SSH worker's workspace can share its id with one on this machine; only this machine's workers count. + const hostScope = readWorkerTerminalHostScope(row.host_scope).kind + if (startedAt !== null && (hostScope === 'absent' || hostScope === 'local')) { + terminals.startedAtByOrigin.set(row.origin_dispatch_id, startedAt) + } + terminals.owners.add(row.owner_dispatch_id) + for (const dispatchId of parseWorkerTerminalPriorOwnerIds(row.prior_owner_dispatch_ids) ?? []) { + terminals.handedOff.add(dispatchId) + } + // Includes a terminal placed in the workspace before its dispatch recorded the workspace. + if (row.worktree_id !== null && row.release_state === 'released') { + terminals.releasedWorktreeIds.add(row.worktree_id) + } else if (row.worktree_id !== null) { + terminals.heldWorktreeIds.add(row.worktree_id) + } + } + return terminals +} + +function createdWorktree(effectsJson: string, worktreeId: string): boolean { + try { + const effects: unknown = JSON.parse(effectsJson) + return ( + Array.isArray(effects) && + effects.some( + (effect) => + effect?.kind === 'worktree' && + effect.id === worktreeId && + (effect.action === 'created_child' || effect.action === 'created_top_level') + ) + ) + } catch { + return false + } +} diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-report-wait-candidates.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-report-wait-candidates.ts index 3ee96e9326e..afa6371cfe9 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-report-wait-candidates.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-report-wait-candidates.ts @@ -56,10 +56,12 @@ const SEED_SQL = `WITH seed(id) AS ( FROM seed CROSS JOIN dispatch_contexts d ON d.id = seed.id AND d.run_id = ?1 ${CANDIDATE_JOINS}` -/** Newest-first position in the Run, which is how worker-list pages it. */ -const RUN_POSITION_SQL = `SELECT requested.value AS database_id, - (SELECT COUNT(*) FROM dispatch_contexts WHERE run_id = ?2 AND rowid > requested.value) AS position - FROM json_each(?1) AS requested` +/** Newest-first position in the Run, which is how worker-list pages it; one pass down to the oldest candidate (?3). */ +const RUN_POSITION_SQL = `WITH ranked AS ( + SELECT rowid AS database_id, ROW_NUMBER() OVER (ORDER BY rowid DESC) - 1 AS position + FROM dispatch_contexts WHERE run_id = ?2 AND rowid >= ?3) + SELECT database_id, position FROM ranked + WHERE database_id IN (SELECT value FROM json_each(?1))` /** The row `offset` rows from `rowid` in the Run, newer or older. */ const NEWER_ROW_SQL = `SELECT rowid AS database_id FROM dispatch_contexts @@ -116,9 +118,11 @@ export function listWorkerReportWaitCandidates(this: OrchestrationDb, runId: str } const candidates = seeded.filter(isCandidate) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query selects exactly these columns. - const positions = this.db - .prepare(RUN_POSITION_SQL) - .all(JSON.stringify(candidates.map((row) => row.database_id)), runId) as { + const positions = this.db.prepare(RUN_POSITION_SQL).all( + JSON.stringify(candidates.map((row) => row.database_id)), + runId, + candidates.reduce((min, row) => Math.min(min, row.database_id), Infinity) + ) as { database_id: number position: number }[] diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts index 6f932cdefdd..12977d889a6 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts @@ -28,7 +28,7 @@ export function storeWorkerTerminalArchive( .run(params.dispatchId, params.resourceId, params.kind, params.content) } -/** Stop closes the terminal; keep its output so a later release has an archive to settle with. */ +/** Stop closes the terminal; record where its output lives so a later release has a reference to settle with. */ export function storeWorkerTerminalArchiveBeforeStop( this: OrchestrationDb, params: { @@ -37,7 +37,7 @@ export function storeWorkerTerminalArchiveBeforeStop( kind: WorkerTerminalArchiveKind content: string archiveSource: 'transcript' | 'terminal' - archiveStatus: Extract + archiveStatus: WorkerTerminalArchiveStatus } ): void { this.db.exec('BEGIN IMMEDIATE') @@ -68,7 +68,7 @@ export function commitWorkerTerminalArchiveForRelease( kind?: WorkerTerminalArchiveKind content?: string archiveSource: 'transcript' | 'terminal' - archiveStatus: Extract + archiveStatus: WorkerTerminalArchiveStatus } ): WorkerTerminalResourceRow { this.db.exec('BEGIN IMMEDIATE') @@ -128,7 +128,7 @@ export function getWorkerTerminalArchive( .get(dispatchId) as WorkerTerminalArchiveRow | undefined } -/** Existence only; archive rows hold up to 256 KB of output. */ +/** Existence only; rows written before references can still hold a saved copy until it is removed. */ export function hasWorkerTerminalArchive(this: OrchestrationDb, dispatchId: string): boolean { return Boolean( this.db.prepare('SELECT 1 FROM worker_terminal_archives WHERE dispatch_id = ?').get(dispatchId) @@ -181,7 +181,7 @@ export function revertWorkerTerminalReleaseToRetained( return this.getWorkerTerminalResource(resourceId) as WorkerTerminalResourceRow } -/** Caller owns the transaction; retain must preserve committed release state and its output archive. */ +/** Caller owns the transaction; retain must preserve committed release state and its output reference. */ export function retainTerminalResourceInTransaction( database: OrchestrationDb, resourceId: string, @@ -198,7 +198,7 @@ export function retainTerminalResourceInTransaction( ) .run(reason, resourceId) if (changes > 0) { - // A stopped worker's terminal is closed; the archive taken before stop is its only output. + // A stopped worker's terminal is closed; the reference taken before stop is its only pointer to output. const dropped = database.db .prepare( `DELETE FROM worker_terminal_archives WHERE dispatch_id = ? AND NOT EXISTS ( diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts index fc6dcdb86c3..fd5ca81a376 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts @@ -122,7 +122,7 @@ export function claimDueWorkerTerminalAutoReleases( return claimed } -/** A claimed close found its agent working again: back to suspended, output archive dropped. */ +/** A claimed close found its agent working again: back to suspended, output reference dropped. */ export function deferWorkerTerminalAutoRelease(this: OrchestrationDb, resourceId: string): void { this.db.exec('BEGIN IMMEDIATE') try { diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts index 014ba4f5a3c..0e142f62837 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-release.ts @@ -122,7 +122,7 @@ export function settleDeadWorkerTerminalRelease( const owner = this.getWorkerDispatch(resource.owner_dispatch_id) const requesterSettled = Boolean(requester && WORKER_SETTLED_STATES.includes(requester.state)) const ownerSettled = Boolean(owner && WORKER_SETTLED_STATES.includes(owner.state)) - // Exit proves process death, not preserved output; require an archive whenever capture is reachable. + // Exit proves process death, not a recorded output location; require one whenever recording is reachable. // Capture runs only while requested; an unrequested or retained owner settles unavailable instead. const archive = this.getWorkerTerminalArchive(resource.owner_dispatch_id) const archiveUnreachable = diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay-environments.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay-environments.ts new file mode 100644 index 00000000000..d3cc5c2ea91 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay-environments.ts @@ -0,0 +1,29 @@ +import type { OrchestrationDb } from '../../db/orchestration-db' +import { listLiveRemoteRunLinkEnvironments } from '../../db/remote-owned/remote-run-links' + +/** Servers this Orca opened conversations with, or has a link to that still needs reading or a cancel. */ +export function peerMailRelayEnvironments(db: OrchestrationDb): Set { + return new Set([...db.listHomePeerMailEnvironments(), ...listLiveRemoteRunLinkEnvironments(db)]) +} + +/** Whether a server's pull loop still has a reason to run; a store read error keeps it running. Runs + * every pull, so it asks about this one server only: closed links' history never enters it. */ +export function peerMailRelayWants(db: OrchestrationDb, environmentId: string): boolean { + try { + return db.hasHomePeerMailEnvironment(environmentId) || hasLiveRemoteRunLink(db, environmentId) + } catch { + return true + } +} + +/** A seek on this server's own (environment_id, state) index rows, however many closed links it keeps. */ +function hasLiveRemoteRunLink(db: OrchestrationDb, environmentId: string): boolean { + return ( + db.db + .prepare( + `SELECT 1 FROM remote_run_links + WHERE environment_id = ? AND state IN ('open', 'cancel_owed') LIMIT 1` + ) + .get(environmentId) !== undefined + ) +} diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.test.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.test.ts new file mode 100644 index 00000000000..e294e963da3 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.test.ts @@ -0,0 +1,53 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { OrchestrationDb } from '../../db/orchestration-db' +import { closeRemoteRunLink, openRemoteRunLink } from '../../db/remote-owned/remote-run-links' +import type { OrchestrationWorkerServer } from '../environment-transport' +import { PeerMailRelay } from './peer-mail-relay' + +const SERVER: OrchestrationWorkerServer = { + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'host_b', + homePeerFingerprint: 'cred_a', + pairingRevision: 1 +} + +let relay: PeerMailRelay | null = null +afterEach(() => relay?.stop()) + +it("stops pulling from a server once this Orca's last link to it closes", async () => { + const db = new OrchestrationDb(':memory:') + const run = db.createRun({ + objective: 'remote work', + coordinatorHandle: 'term_coordinator', + coordinatorPaneKey: 'tab_coord:11111111-1111-4111-8111-111111111111' + }) + const link = openRemoteRunLink(db, run.id, SERVER) + let pulls = 0 + const runtime = { + getOrchestrationDb: () => db, + resolveOrchestrationWorkerServer: () => SERVER, + notifyMessageArrived: vi.fn(), + callOrchestrationWorkerServer: async (_environmentId: string, method: string) => { + if (method === 'orchestration.peerMailPull') { + pulls += 1 + if (pulls === 2) { + closeRemoteRunLink(db, link.conversation_id, 'The Run ended.') + } + // An idle pull answers empty after its wait. + await new Promise((resolve) => setImmediate(resolve)) + } + return { items: [] } + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the relay reads only these runtime members. + relay = new PeerMailRelay(runtime as never, () => ({}) as never) + + relay.ensure() + await vi.waitFor(() => expect(pulls).toBeGreaterThanOrEqual(2)) + for (let i = 0; i < 20; i++) { + await new Promise((resolve) => setImmediate(resolve)) + } + + expect(pulls).toBe(2) +}) diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts index dbd37b0e756..f465ad1b83a 100644 --- a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import type { OrcaRuntimeService } from '../../../orca-runtime' -import { PeerMailRelayPayload } from '../../../../../shared/rpc-contract/orchestration-peer-mail-params' +import { PeerMailRelayPayload } from '../../../../../shared/rpc-contract/orchestration/orchestration-peer-mail-params' import { resolveBareOrchestrationRecipient } from '../../../rpc/methods/orchestration/messaging/recipient-routing' import type { OrchestrationDb } from '../../db/orchestration-db' import type { MessageRow } from '../../db/orchestration-records' @@ -8,6 +8,7 @@ import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler import { HeldPeerConversations } from './held-peer-conversations' import type { OrchestrationEnvironmentTransport } from '../environment-transport' import { peerMailLocalRecipient } from './peer-mail-delivery' +import { peerMailRelayEnvironments, peerMailRelayWants } from './peer-mail-relay-environments' import { presentImportedPeerItem } from '../../mailbox/formatting/imported-peer-item-presentation' import { importRemoteOwnedItem } from '../../db/remote-owned/remote-owned-import' import { @@ -15,7 +16,6 @@ import { closeRemoteRunLinksOfRemovedServer, dueRemoteResendsNow, getRemoteRunLink, - listLiveRemoteRunLinkEnvironments, noteRemoteRunLinkError, remoteServerPin } from '../../db/remote-owned/remote-run-links' @@ -71,11 +71,7 @@ export class PeerMailRelay { return } const db = this.runtime.getOrchestrationDb() - const environments = new Set([ - ...db.listHomePeerMailEnvironments(), - ...listLiveRemoteRunLinkEnvironments(db) - ]) - for (const environmentId of environments) { + for (const environmentId of peerMailRelayEnvironments(db)) { const current = this.loops.get(environmentId) if (current && !current.stopped && current.db === db) { continue @@ -109,7 +105,8 @@ export class PeerMailRelay { let failures = 0 // Named while it is still paired, so a removal can say which server went. const serverName = remoteServerName(this.runtime, environmentId) - while (this.isCurrent(environmentId, loop)) { + // Ends with its last reason to pull; a later conversation or link starts a new loop through ensure(). + while (this.isCurrent(environmentId, loop) && peerMailRelayWants(loop.db, environmentId)) { try { await this.pullOnce(environmentId, loop) if (failures > 0) { @@ -305,6 +302,7 @@ export class PeerMailRelay { return undefined } const handle = peerMailLocalRecipient(this.runtime, conversation) + // Peer-mail replies come home to this Orca's own sender handle, never a terminal agent's id. const recipient = resolveBareOrchestrationRecipient({ runtime: this.runtime, db, handle }) const presented = presentImportedPeerItem({ kind: 'peer_mail', diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts index c41daaf0f39..09206a0d134 100644 --- a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts @@ -8,7 +8,7 @@ import { import { emptyWorkerListPage } from '../../../rpc/methods/orchestration/worker/worker-list-method' import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../../shared/orchestration/fleet/orchestration-fleet-projection' import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' -import { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration-worker-start-params' +import { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration/orchestration-worker-start-params' import { isOrchestrationMutation } from '../../../../../shared/orchestration/orchestration-rpc-contract' import type { OrchestrationDb } from '../../db/orchestration-db' import { runLifecycleWriteTransaction } from '../../db/lifecycle-write-transaction-runner' diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts index 195beb02ca8..7c79072e748 100644 --- a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts @@ -1,13 +1,13 @@ import { createHash, randomUUID } from 'node:crypto' import { z } from 'zod' -import type { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration-worker-start-params' +import type { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration/orchestration-worker-start-params' import { ORCHESTRATION_REMOTE_OWNED_WORKERS_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' import { ORCHESTRATION_CONTRACT_PREFLIGHT_TIMEOUT_MS } from '../../../../../shared/orchestration/orchestration-timing-budgets' import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' import type { OrcaRuntimeService } from '../../../orca-runtime' import type { RpcContext } from '../../../rpc/core' -import { prepareWorkerStart } from '../../../rpc/methods/orchestration/worker/workers' -import { resolveFederatedWorkerStartBudgets } from '../../../rpc/methods/orchestration/worker/worker-start-budgets' +import { prepareWorkerStart } from '../../../rpc/methods/orchestration/worker/worker-start-method' +import { resolveFederatedWorkerStartBudgets } from '../../../rpc/methods/orchestration/worker/start/launch/worker-start-budgets' import { OrchestrationError } from '../../orchestration-error' import { prepareWorkerStartCard } from '../../workers/launch/worker-start-card' import { getOrchestrationPeerCapabilityCache } from '../orchestration-peer-capability-cache' @@ -60,7 +60,8 @@ function adoptedTaskId(key: string): string { const StartedOnServer = z.object({ dispatchId: z.string().min(1), run: z.object({ id: z.string().min(1) }).optional(), - agent: z.string().nullable().optional() + agent: z.string().nullable().optional(), + state: z.string().optional() }) /** @@ -169,15 +170,18 @@ export async function startRemoteOwnedWorker( { server: server.name } ) } - prepareWorkerStartCard( - runtime, - ctx.orchestrationCaller - )({ - dispatchId: started.data.dispatchId, - workerAddress: `dispatch:${started.data.dispatchId}`, - task: task.spec, - agent: null - }) + // As local and attached starts do: a start the server could not ready leaves no card. + if (started.data.state === 'ready') { + prepareWorkerStartCard( + runtime, + ctx.orchestrationCaller + )({ + dispatchId: started.data.dispatchId, + workerAddress: `dispatch:${started.data.dispatchId}`, + task: task.spec, + agent: started.data.agent ?? null + }) + } } const answer = inServerTerms(receipt, { server: server.name, forward }) return withRun( diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts index 69767a4c3b9..6e3cd82b3a4 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts @@ -1,4 +1,4 @@ -import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences' +import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/start/launch/worker-launch-preferences' export type RemoteFederatedWorkerStartReceipt = { dispatchId: string diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts index c8e71b5e7ad..d2897b11bd4 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts @@ -12,7 +12,7 @@ import { liveFederatedHomeAutoReleaseAt } from '../terminal-authority/release/wo import type { OrchestrationDb } from '../db/orchestration-db' import { OrchestrationError } from '../orchestration-error' import type { OrcaRuntimeService } from '../../orca-runtime' -import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' +import { resolvePinnedFederatedServer } from './pinned-federated-server' import { applyConfirmedFederatedReleaseHomeProjection } from './federated-worker-release' const FLEET_HOST_CONCURRENCY = 4 diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts index db9125181dc..a74b5b3277c 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts @@ -1,5 +1,5 @@ import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' -import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' +import { resolvePinnedFederatedServer } from './pinned-federated-server' import { releaseFederatedWorker } from './federated-worker-release' /** The home's deadline for a host that did not arm its own; the host's takeover and ownership checks still refuse it. */ diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts index 1cf73b35ea8..3c32afa87e7 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts @@ -9,7 +9,7 @@ import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration import type { FederatedDispatchRow } from '../db/orchestration-records' import type { OrcaRuntimeService } from '../../orca-runtime' import { readLegacyFederatedTerminal } from './worker-legacy-federated-read' -import type { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' +import type { resolvePinnedFederatedServer } from './pinned-federated-server' export async function readFederatedWorkerOutput(args: { runtime: OrcaRuntimeService diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts index a9965dfafba..a912b0754a3 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts @@ -9,9 +9,9 @@ import { OrchestrationError } from '../orchestration-error' import type { OrchestrationDb } from '../db/orchestration-db' import type { FederatedDispatchRow } from '../db/orchestration-records' import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' -import type { WorkerReleaseReceipt } from '../../rpc/methods/orchestration/worker/worker-release-completion' -import { releaseUnknownRecovery } from '../../rpc/methods/orchestration/worker/worker-release-unknown-recovery' -import type { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' +import type { WorkerReleaseReceipt } from '../../rpc/methods/orchestration/worker/release/worker-release-completion' +import { releaseUnknownRecovery } from '../../rpc/methods/orchestration/worker/release/worker-release-unknown-recovery' +import type { resolvePinnedFederatedServer } from './pinned-federated-server' type RemoteReleaseReceipt = Omit & { archive?: WorkerReleaseReceipt['archive'] diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts index b8e9b89d78d..e2b1d116202 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts @@ -1,6 +1,6 @@ import type { OrchestrationFleetWorker } from '../../../../shared/orchestration/fleet/orchestration-fleet-projection' import type { OrchestrationDb } from '../db/orchestration-db' -import { exposeDispatchContext } from '../../rpc/methods/orchestration/worker/dispatch-context-exposure' +import { exposeDispatchContext } from '../../rpc/methods/orchestration/worker/observation/dispatch-context-exposure' import { OrchestrationError } from '../orchestration-error' import { liveFederatedHomeAutoReleaseAt } from '../terminal-authority/release/worker-terminal-ownership' import type { DispatchContextRow, FederatedDispatchRow } from '../db/orchestration-records' @@ -10,8 +10,8 @@ import { exposeFederatedWorkerObservation, exposeWorker, projectFleetWorkerPage -} from '../../rpc/methods/orchestration/worker/worker-observation' -import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' +} from '../../rpc/methods/orchestration/worker/observation/worker-observation' +import { resolvePinnedFederatedServer } from './pinned-federated-server' import { applyFederatedFleetObservations } from './federated-fleet-snapshot' import { applyConfirmedFederatedReleaseHomeProjection } from './federated-worker-release' diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts index da38e2ab909..8ff8bd00ac0 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts @@ -1,4 +1,4 @@ -import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences' +import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/start/launch/worker-launch-preferences' export function isKnownRemoteStartFailure(code: string): boolean { return [ diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts index d4a6950dfc6..32689f4ab9a 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts @@ -1,8 +1,8 @@ import type { OrchestrationEntryCaller } from '../addressing/orchestration-caller-identity' import type { OrcaRuntimeService } from '../../orca-runtime' import type { OrchestrationDb } from '../db/orchestration-db' -import type { WorkerStartInput } from '../../rpc/methods/orchestration/worker/worker-start-schema' -import type { WorkerStartMutation } from '../../rpc/methods/orchestration/worker/worker-start-mutation' +import type { WorkerStartInput } from '../../rpc/methods/orchestration/worker/start/worker-start-input' +import type { WorkerStartMutation } from '../../rpc/methods/orchestration/worker/start/worker-start-mutation' export type FederatedWorkerStartRequest = { params: WorkerStartInput diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts index c3057804017..a72925f4331 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts @@ -17,9 +17,9 @@ import { assertWorkerLaunchPreferencesCreateTerminal, createPendingWorkerLaunchReceipt, resolveFederatedWorkerLaunchReceipt -} from '../../rpc/methods/orchestration/worker/worker-launch-preferences' -import { validateFederatedWorkerStartPlacement } from '../../rpc/methods/orchestration/worker/worker-start-validation' -import { resolveFederatedWorkerStartBudgets } from '../../rpc/methods/orchestration/worker/worker-start-budgets' +} from '../../rpc/methods/orchestration/worker/start/launch/worker-launch-preferences' +import { validateFederatedWorkerStartPlacement } from '../../rpc/methods/orchestration/worker/start/launch/worker-start-validation' +import { resolveFederatedWorkerStartBudgets } from '../../rpc/methods/orchestration/worker/start/launch/worker-start-budgets' import { resolveDispatchCreator } from '../../rpc/methods/orchestration/runs/dispatch-creator' import { isReadyRemoteFederatedWorkerStartReceipt, @@ -31,7 +31,7 @@ import { federatedUnknownReceipt, isKnownRemoteStartFailure } from './federated-worker-start-receipts' -import { releaseRetriedWorkerTerminal } from '../../rpc/methods/orchestration/worker/retried-worker-terminal-release' +import { releaseRetriedWorkerTerminal } from '../../rpc/methods/orchestration/worker/release/retried-worker-terminal-release' import { withWorkerStartNext } from '../../rpc/methods/orchestration/receipt-next' import { recordReadyFederatedDispatch } from './federated-worker-ready-record' import { resolveFederatedChildParent } from './federated-worker-child-parent' diff --git a/src/main/runtime/orchestration/legacy-remote-home/pinned-federated-server.ts b/src/main/runtime/orchestration/legacy-remote-home/pinned-federated-server.ts new file mode 100644 index 00000000000..d5091b12550 --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote-home/pinned-federated-server.ts @@ -0,0 +1,30 @@ +import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' +import { OrchestrationError } from '../orchestration-error' +import type { FederatedDispatchRow } from '../db/orchestration-records' +import { RuntimeEnvironmentStoreError } from '../../../../shared/remote-runtime/host-store/runtime-environment-store-records' + +export function resolvePinnedFederatedServer( + runtime: WorkerTerminalReleaseRuntime, + federated: FederatedDispatchRow +) { + let server + try { + server = runtime.resolveOrchestrationWorkerServer(federated.environment_id) + } catch (error) { + // Not found: removed, or re-paired, which adds the server as a new environment. + if (error instanceof RuntimeEnvironmentStoreError && error.code === 'invalid_argument') { + throw new OrchestrationError( + 'peer_changed', + `Saved environment ${federated.environment_name} is no longer a paired server here, so this Orca cannot reach this worker. Re-pairing adds the server as a new environment.` + ) + } + throw error + } + if (server.peerFingerprint !== federated.peer_fingerprint) { + throw new OrchestrationError( + 'peer_changed', + `Saved environment ${federated.environment_name} now identifies a different Orca server.` + ) + } + return server +} diff --git a/src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts b/src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts index 05c44fc1633..898bedede85 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts @@ -6,7 +6,7 @@ import { decodeWorkerOutputCursor, encodeWorkerOutputCursor } from '../workers/transcripts/worker-output-cursor' -import type { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' +import type { resolvePinnedFederatedServer } from './pinned-federated-server' // Old peers expose only terminal reads; retain fences and cursor scope instead of silently degrading transcript cursors. export async function readLegacyFederatedTerminal(args: { diff --git a/src/main/runtime/orchestration/legacy-remote/ask-remote.ts b/src/main/runtime/orchestration/legacy-remote/ask-remote.ts index b18edd2e418..3ec5444c533 100644 --- a/src/main/runtime/orchestration/legacy-remote/ask-remote.ts +++ b/src/main/runtime/orchestration/legacy-remote/ask-remote.ts @@ -3,7 +3,7 @@ import type { OrcaRuntimeService } from '../../orca-runtime' import type { WorkerDispatchState } from '../db/orchestration-records' import { OrchestrationError } from '../orchestration-error' import { clampOrchestrationAskTimeoutMs } from '../../../../shared/orchestration/mailbox/orchestration-ask-timeout' -import type { AskParams } from '../../../../shared/rpc-contract/orchestration-params' +import type { AskParams } from '../../../../shared/rpc-contract/orchestration/orchestration-params' import { assertWorkerCanReport } from '../workers/reports/worker-report-admission' import { askedQuestionReceipt, diff --git a/src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts index 3699d1ade1d..2e9757f32f3 100644 --- a/src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts @@ -8,14 +8,14 @@ import type { OrcaRuntimeService } from '../../orca-runtime' import type { OrchestrationDb } from '../db/orchestration-db' import { resolveUnattendedSetupDecision } from '../../../workspace-hooks/effective-hook-config' import { WORKER_START_VOCABULARY } from '../../rpc/methods/orchestration/structured-workers/orchestration-worker-start-mode' -import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' -import { resolveWorkerWorktreeName } from '../../rpc/methods/orchestration/worker/worker-worktree-creation' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/start/placement/worker-placement-topology' +import { resolveWorkerWorktreeName } from '../../rpc/methods/orchestration/worker/start/placement/worker-worktree-creation' import { appendFederationSetupEffect, appendFederationTerminalEffects, type FederationEffect } from './federation-effects' -import type { FederationAttachStartInput } from '../../../../shared/rpc-contract/orchestration-federation-start-params' +import type { FederationAttachStartInput } from '../../../../shared/rpc-contract/orchestration/orchestration-federation-start-params' import type { Worktree } from '../../../../shared/worktree/types' const TERMINAL_ONLY_MESSAGE = 'A federated worker starts a terminal agent only.' diff --git a/src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts index 1739ab48fcd..991fb1ebe14 100644 --- a/src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts @@ -6,24 +6,24 @@ import type { WorkerTerminalRetainedReason } from '../terminal-authority/release/worker-terminal-ownership' import { - captureWorkerOutputArchive, + captureWorkerOutputReference, releaseCommitFieldsForCapturedArchive, releaseCommitFieldsForStoredArchive, summarizeWorkerOutputArchive } from '../workers/archives/worker-output-archive' import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' -import { readRemoteAttachmentArchive } from './remote-attachment-archive-read' -import { WorkerTerminalReleaseSingleFlight } from '../../rpc/methods/orchestration/worker/worker-terminal-release-single-flight' +import { readRemoteAttachmentOutputIfAvailable } from './remote-attachment-archive-read' +import { WorkerTerminalReleaseSingleFlight } from '../../rpc/methods/orchestration/worker/release/worker-terminal-release-single-flight' import { yieldAutoReleaseToWorkingAgent } from '../terminal-authority/release/worker-terminal-auto-release-working-yield' -import { archiveSummary } from '../../rpc/methods/orchestration/worker/worker-terminal-resource-presentation' -import type { WorkerReleaseReceipt } from '../../rpc/methods/orchestration/worker/worker-release-completion' -import { releaseUnknownRecovery } from '../../rpc/methods/orchestration/worker/worker-release-unknown-recovery' -import { orchestrationTimestampToMs } from '../../rpc/methods/orchestration/worker/worker-output' +import { archiveSummary } from '../../rpc/methods/orchestration/worker/release/worker-terminal-resource-presentation' +import type { WorkerReleaseReceipt } from '../../rpc/methods/orchestration/worker/release/worker-release-completion' +import { releaseUnknownRecovery } from '../../rpc/methods/orchestration/worker/release/worker-release-unknown-recovery' +import { orchestrationTimestampToMs } from '../../rpc/methods/orchestration/worker/output/worker-output' import type { inspectRemoteAttachment } from './federation-attachment-observation' import { classifyWorkerTerminalCloseError, TRANSIENT_WORKER_RELEASE_RECOVERY -} from '../../rpc/methods/orchestration/worker/worker-release-close-error' +} from '../../rpc/methods/orchestration/worker/release/worker-release-close-error' type RemoteAttachmentReleaseArgs = { runtime: WorkerTerminalReleaseRuntime @@ -70,7 +70,7 @@ async function requestRemoteAttachmentRelease( } } if (attachment.stage === 'released') { - const archived = await readRemoteAttachmentArchive({ + const archived = await readRemoteAttachmentOutputIfAvailable({ runtime, attachment, liveness: 'exited' @@ -127,7 +127,7 @@ async function completeRemoteAttachmentRelease( } const retained = db.revertWorkerTerminalReleaseToRetained(resource.id, 'identity_unproven') const output = storedArchive - ? await readRemoteAttachmentArchive({ + ? await readRemoteAttachmentOutputIfAvailable({ runtime, attachment, liveness: observation.status === 'exited' ? 'exited' : 'unverifiable' @@ -155,9 +155,8 @@ async function completeRemoteAttachmentRelease( const archive = storedArchive ? releaseCommitFieldsForStoredArchive(storedArchive) : releaseCommitFieldsForCapturedArchive( - await captureWorkerOutputArchive({ + captureWorkerOutputReference({ runtime, - dispatchId: attachment.dispatch_id, terminalHandle: observation.terminal.handle, attachedAtMs: orchestrationTimestampToMs(attachment.created_at) }) @@ -169,10 +168,8 @@ async function completeRemoteAttachmentRelease( ...archive }) if (isStillReleasing(committed)) { - output = await readRemoteAttachmentArchive({ runtime, attachment, liveness }) - if (!output) { - throw new Error('The execution host could not reopen the committed worker output archive.') - } + // A worker with no readable original still releases; its receipt carries no output. + output = await readRemoteAttachmentOutputIfAvailable({ runtime, attachment, liveness }) } } catch (error) { const retained = db.revertWorkerTerminalReleaseToRetained(resource.id, 'identity_unproven') @@ -192,7 +189,7 @@ async function completeRemoteAttachmentRelease( : !remoteAttachmentLeaseIsCurrent(runtime, attachment, observation, current) ? db.revertWorkerTerminalReleaseToRetained(resource.id, 'identity_unproven') : yieldAutoReleaseToWorkingAgent(runtime, current) - if (!isStillReleasing(releasing) || !output) { + if (!isStillReleasing(releasing)) { return { dispatchId: attachment.dispatch_id, state: 'retained', @@ -214,10 +211,14 @@ async function completeRemoteAttachmentRelease( lastError: reason, recovery: releaseUnknownRecovery(attachment.dispatch_id), archive: archiveSummary(db.markWorkerTerminalReleaseUnknown(resource.id, reason)), - output: projectArchivedOutputLiveness( - output, - close.ptyStopVerdict === 'live' ? 'live' : 'unverifiable' - ) + ...(output + ? { + output: projectArchivedOutputLiveness( + output, + close.ptyStopVerdict === 'live' ? 'live' : 'unverifiable' + ) + } + : {}) } } } catch (error) { @@ -237,7 +238,7 @@ async function completeRemoteAttachmentRelease( ? releasing : db.markWorkerTerminalReleaseUnknown(resource.id, closeError.reason) ), - output: projectArchivedOutputLiveness(output, 'unverifiable') + ...(output ? { output: projectArchivedOutputLiveness(output, 'unverifiable') } : {}) } } } @@ -252,7 +253,7 @@ async function completeRemoteAttachmentRelease( processAction: observation.status === 'exited' ? 'closed_exited_terminal' : 'closed_agent_terminal', archive: archiveSummary(released), - output: projectArchivedOutputLiveness(output, 'exited') + ...(output ? { output: projectArchivedOutputLiveness(output, 'exited') } : {}) } } diff --git a/src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts index 5ec5bfe4af0..4e38b58f8a3 100644 --- a/src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts @@ -1,6 +1,6 @@ import type { OrcaRuntimeService } from '../../orca-runtime' import type { WorkerStopReceipt } from '../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' -import { archiveWorkerOutputBeforeStop } from '../../rpc/methods/orchestration/worker/worker-stop-archive' +import { archiveWorkerOutputBeforeStop } from '../../rpc/methods/orchestration/worker/stop/worker-stop-archive' import { describeUnconfirmedAgentStop } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import { inspectRemoteAttachment } from './federation-attachment-observation' @@ -33,7 +33,7 @@ export async function stopRemoteAttachment( lastError: attachment.last_error } } - await archiveWorkerOutputBeforeStop({ + archiveWorkerOutputBeforeStop({ runtime, db, dispatchId: params.dispatchId, diff --git a/src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts b/src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts index a91511e3e03..c7b573d326a 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts @@ -1,7 +1,7 @@ import type { OrcaRuntimeService } from '../../orca-runtime' import type { OrchestrationDb } from '../db/orchestration-db' import type { FederationEffect } from './federation-effects' -import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/start/placement/worker-placement-topology' export function prepareFederatedAttachmentAuthority(args: { runtime: OrcaRuntimeService diff --git a/src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts b/src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts index 470c9b55df6..8a2ec0da7e4 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts @@ -3,7 +3,7 @@ import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release import { OrchestrationError } from '../orchestration-error' import { parseWorkerTerminalHostScope } from '../../../../shared/orchestration/workers/worker-terminal-host-scope' import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' -import { orchestrationTimestampToMs } from '../../rpc/methods/orchestration/worker/worker-output' +import { orchestrationTimestampToMs } from '../../rpc/methods/orchestration/worker/output/worker-output' export function requireHomeAttachment( runtime: WorkerTerminalReleaseRuntime, diff --git a/src/main/runtime/orchestration/legacy-remote/federation-control.ts b/src/main/runtime/orchestration/legacy-remote/federation-control.ts index d0bb1171c76..8cd916478cb 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation-control.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-control.ts @@ -3,8 +3,8 @@ import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' import { defineOrchestrationMethod } from '../../rpc/methods/orchestration/access/orchestration-method-access' import { isUserKeptWorkerTerminalOwner } from '../db/worker-terminal/worker-terminal-user-keep' import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' -import { readExactWorkerOutput } from '../../rpc/methods/orchestration/worker/worker-output' -import { exposeWorkerRetainReceipt } from '../../rpc/methods/orchestration/worker/worker-terminal-resource-presentation' +import { readExactWorkerOutput } from '../../rpc/methods/orchestration/worker/output/worker-output' +import { exposeWorkerRetainReceipt } from '../../rpc/methods/orchestration/worker/release/worker-terminal-resource-presentation' import { withStoppedHelpers } from '../../rpc/methods/orchestration/worker/worker-stop' import { stopRemoteAttachment } from './federated-worker-stop-host' import { @@ -19,7 +19,7 @@ import { FederationFleetSnapshotParams, FederationOutputReadParams, FederationReadParams -} from '../../../../shared/rpc-contract/orchestration-federation-control-params' +} from '../../../../shared/rpc-contract/orchestration/orchestration-federation-control-params' export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ defineOrchestrationMethod({ diff --git a/src/main/runtime/orchestration/legacy-remote/federation-relay.ts b/src/main/runtime/orchestration/legacy-remote/federation-relay.ts index 5982444fd7c..d1b2a1715f6 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation-relay.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-relay.ts @@ -14,7 +14,7 @@ import { FederationAckParams, FederationImportParams, FederationPullParams -} from '../../../../shared/rpc-contract/orchestration-federation-relay-params' +} from '../../../../shared/rpc-contract/orchestration/orchestration-federation-relay-params' export const ORCHESTRATION_FEDERATION_RELAY_METHODS = [ defineOrchestrationMethod({ diff --git a/src/main/runtime/orchestration/legacy-remote/federation-setup.ts b/src/main/runtime/orchestration/legacy-remote/federation-setup.ts index ddf87653e11..b5a49ffc7ec 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation-setup.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-setup.ts @@ -3,7 +3,7 @@ import type { OrchestrationDb } from '../db/orchestration-db' import { applyWaitForSetupOutcome, type WorkerSetupReceipt -} from '../../rpc/methods/orchestration/worker/worker-topology' +} from '../../rpc/methods/orchestration/worker/start/placement/worker-placement-topology' import { isFederationResidualEffect, type FederationEffect } from './federation-effects' type FederationSetupStageArgs = { diff --git a/src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts b/src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts index c0c00eef44e..c9ccbf53a7b 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts @@ -1,8 +1,8 @@ import { formatTerminalStartFailure } from '../../../../shared/terminal/pty/lifecycle/terminal-start-failure' import type { OrchestrationDb } from '../db/orchestration-db' import { isFederationEffectUnknown } from './federation-effects' -import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' -import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/start/placement/worker-placement-topology' +import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/start/launch/worker-launch-preferences' export function failFederatedAttachmentWithReceipt(args: { db: OrchestrationDb diff --git a/src/main/runtime/orchestration/legacy-remote/federation.ts b/src/main/runtime/orchestration/legacy-remote/federation.ts index 6a803cc1ac5..522efc19515 100644 --- a/src/main/runtime/orchestration/legacy-remote/federation.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation.ts @@ -6,26 +6,26 @@ import { sendAgentTurn } from '../turn-delivery/send-agent-turn' import { createWorkerBriefWriteGuard } from '../../terminal/wait/launched-agent-write-guard' import { OrchestrationError } from '../orchestration-error' import { defineOrchestrationMethod } from '../../rpc/methods/orchestration/access/orchestration-method-access' -import { assertOrchestrationWorktreeCreationSupported } from '../../rpc/methods/orchestration/worker/folder-worktree-placement' +import { assertOrchestrationWorktreeCreationSupported } from '../../rpc/methods/orchestration/worker/start/placement/folder-worktree-placement' import type { FederationEffect } from './federation-effects' import { launchFederatedWorkerAgent } from './federated-worker-agent-launch' -import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/start/placement/worker-placement-topology' import { monitorFederatedSetup, persistFederatedReadinessStage, persistFederatedSetupSpawnFailure, persistFederatedSetupWaitOutcome } from './federation-setup' -import { FederationAttachStartParams } from '../../../../shared/rpc-contract/orchestration-federation-start-params' +import { FederationAttachStartParams } from '../../../../shared/rpc-contract/orchestration/orchestration-federation-start-params' import { failFederatedAttachmentWithReceipt } from './federation-start-receipt' -import { prepareFederationWorkerLaunchOnHost } from '../../rpc/methods/orchestration/worker/worker-opencode-model-preflight' +import { prepareFederationWorkerLaunchOnHost } from '../../rpc/methods/orchestration/worker/start/launch/worker-opencode-model-preflight' import { isWorkerStartTimeoutWithinTimerLimit, resolveWorkerStartReadinessTimeoutMs } from '../../../../shared/orchestration/orchestration-timing-budgets' -import { assertWorkerStartTaskSpecWithinPromptBudget } from '../../rpc/methods/orchestration/worker/worker-start-prompt-budget' +import { assertWorkerStartTaskSpecWithinPromptBudget } from '../../rpc/methods/orchestration/worker/start/admission/worker-start-prompt-budget' import { prepareFederatedAttachmentAuthority } from './federation-attachment-authority' -import { resolveRpcWorkspaceCreatorProvenance } from '../../rpc/workspace-creator-context' +import { resolveRpcWorkspaceCreatorProvenance } from '../../rpc/callers/workspace-creator-context' import { claimTerminalForRemoteAttach } from '../db/worker-dispatch/worker-terminal-claim' export const ORCHESTRATION_FEDERATION_ATTACH_METHODS = [ diff --git a/src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts b/src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts index f49421c3a87..0cf0271288b 100644 --- a/src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts @@ -1,6 +1,7 @@ import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' -import { readArchivedWorkerOutput } from '../../rpc/methods/orchestration/worker/worker-archive-read' +import { readArchivedWorkerOutput } from '../../rpc/methods/orchestration/worker/output/worker-archive-read' +import { OrchestrationError } from '../orchestration-error' export async function readRemoteAttachmentArchive(args: { runtime: WorkerTerminalReleaseRuntime @@ -10,14 +11,13 @@ export async function readRemoteAttachmentArchive(args: { limit?: number liveness?: 'live' | 'unverifiable' | 'exited' }) { - const archive = args.runtime - .getOrchestrationDb() - .getWorkerTerminalArchive(args.attachment.dispatch_id) + const db = args.runtime.getOrchestrationDb() + const archive = db.getWorkerTerminalArchive(args.attachment.dispatch_id) if (!archive || !args.attachment.terminal_handle) { return null } return readArchivedWorkerOutput({ - db: args.runtime.getOrchestrationDb(), + db, dispatchId: args.attachment.dispatch_id, workerState: args.attachment.state, resource: { @@ -31,3 +31,19 @@ export async function readRemoteAttachmentArchive(args: { liveness: args.liveness }) } + +/** Release receipts carry the output only while its original is still readable and steady. */ +export function readRemoteAttachmentOutputIfAvailable( + args: Parameters[0] +): ReturnType { + return readRemoteAttachmentArchive(args).catch((error: unknown) => { + // A transcript written during the read only drops the optional page; it never blocks release. + if ( + error instanceof OrchestrationError && + (error.code === 'archive_unavailable' || error.code === 'source_changed') + ) { + return null + } + throw error + }) +} diff --git a/src/main/runtime/orchestration/mailbox/notifications/mailbox-notification-coordinator.ts b/src/main/runtime/orchestration/mailbox/notifications/mailbox-notification-coordinator.ts index bd0ab6e4d73..dc5d2559207 100644 --- a/src/main/runtime/orchestration/mailbox/notifications/mailbox-notification-coordinator.ts +++ b/src/main/runtime/orchestration/mailbox/notifications/mailbox-notification-coordinator.ts @@ -62,7 +62,8 @@ export class OrchestrationMailboxNotificationCoordinator< db, mailboxHandle, waiters, - reservedTypes: undefined + reservedTypes: undefined, + excludeRunOwnedDirect: mailboxHandle === terminal.handle }).messages.length > 0) ) }) diff --git a/src/main/runtime/orchestration/mailbox/notifications/orchestration-message-delivery-identity.test.ts b/src/main/runtime/orchestration/mailbox/notifications/orchestration-message-delivery-identity.test.ts index a442ebc885b..d3daf76637d 100644 --- a/src/main/runtime/orchestration/mailbox/notifications/orchestration-message-delivery-identity.test.ts +++ b/src/main/runtime/orchestration/mailbox/notifications/orchestration-message-delivery-identity.test.ts @@ -1,5 +1,5 @@ -import '../../../rpc/unused-default-rpc-methods.test-fixture' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' +import '../../../rpc/dispatch/testing/unused-default-rpc-methods.test-fixture' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' diff --git a/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-direct-terminal-pointer.spec.ts b/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-direct-terminal-pointer.spec.ts new file mode 100644 index 00000000000..4798285e3b4 --- /dev/null +++ b/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-direct-terminal-pointer.spec.ts @@ -0,0 +1,82 @@ +import { rmSync } from 'node:fs' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { checkDirectMailbox } from '../../../rpc/methods/orchestration/messaging/check-direct' +import { + createBoundRun, + createDatabase, + createRuntime, + driveToLiveIdle, + insertDirectRunMessage, + pointerCount, + SECOND_PANE_KEY, + SECOND_TERMINAL_HANDLE, + sqliteFor, + temporaryDirectories, + TERMINAL_HANDLE +} from '../terminal-pointer/orchestration-mailbox-notification-test-harness' + +describe('orchestration direct terminal mailbox pointer', () => { + afterEach(() => { + vi.useRealTimers() + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } + }) + + it('points and checks an unbound pane at its own direct mail but leaves Run-owned rows for routing', async () => { + vi.useFakeTimers() + const db = createDatabase('orca-mailbox-direct-terminal-pointer-') + const harness = createRuntime(db) + const formerRun = createBoundRun(db, 'Former coordinator Run') + const runOwned = insertDirectRunMessage(db, formerRun.id, 'Former Run completion') + db.bindRun({ + runId: formerRun.id, + coordinatorHandle: SECOND_TERMINAL_HANDLE, + coordinatorPaneKey: SECOND_PANE_KEY + }) + sqliteFor(db) + .prepare('UPDATE messages SET to_handle = ? WHERE id = ?') + .run(TERMINAL_HANDLE, runOwned.id) + const peerRun = db.createRun({ + objective: 'Peer Run', + coordinatorHandle: SECOND_TERMINAL_HANDLE, + coordinatorPaneKey: SECOND_PANE_KEY + }) + const plain = db.insertMessage({ + from: 'term_peer', + to: TERMINAL_HANDLE, + subject: 'Direct status', + type: 'status' + }) + const fromPeerRun = db.insertMessage({ + from: SECOND_TERMINAL_HANDLE, + to: TERMINAL_HANDLE, + subject: 'Peer Run status', + type: 'status', + runId: peerRun.id + }) + + await driveToLiveIdle(harness.runtime) + await vi.advanceTimersByTimeAsync(1_000) + + expect(pointerCount(harness.write)).toBe(1) + expect(db.getMessageById(plain.id)?.delivered_at).not.toBeNull() + expect(db.getMessageById(fromPeerRun.id)?.delivered_at).not.toBeNull() + expect(db.getMessageById(runOwned.id)).toMatchObject({ + to_handle: TERMINAL_HANDLE, + delivered_at: null + }) + await expect( + checkDirectMailbox({ + params: {}, + runtime: harness.runtime, + db, + handle: TERMINAL_HANDLE, + typeFilter: undefined, + signal: undefined + }) + ).resolves.toMatchObject({ count: 2 }) + expect(db.getMessageById(runOwned.id)?.read).toBe(0) + db.close() + }) +}) diff --git a/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts b/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts index ba1222cbc3a..ed1ee0f7e41 100644 --- a/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts +++ b/src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts @@ -10,6 +10,7 @@ vi.mock('electron', () => ({ import '../terminal-pointer/orchestration-mailbox-crash-recovery.spec' import './orchestration-mailbox-detached-routing.spec' +import './orchestration-mailbox-direct-terminal-pointer.spec' import './orchestration-mailbox-filtered-waiters.spec' import './orchestration-mailbox-routing-races.spec' import '../terminal-pointer/orchestration-multi-run-coordinator-wake.spec' diff --git a/src/main/runtime/orchestration/mailbox/routing/structured-session-mail-address.ts b/src/main/runtime/orchestration/mailbox/routing/structured-session-mail-address.ts index 1c6dffa05c4..4300591171c 100644 --- a/src/main/runtime/orchestration/mailbox/routing/structured-session-mail-address.ts +++ b/src/main/runtime/orchestration/mailbox/routing/structured-session-mail-address.ts @@ -39,10 +39,15 @@ export function lookupOrcaAgentSession( if (record) { return { kind: 'found', record } } - const owner = store - .listRecords() - .find((candidate) => candidate.providerHandleChain.some(({ handle }) => handle.nativeId === id)) - return owner ? { kind: 'provider-id', orcaSessionId: owner.sessionId } : { kind: 'unknown' } + // The store's commit-kept alias index answers without walking the history. + const owner = store.providerAliasOwner + ? store.providerAliasOwner(id) + : (store + .listRecords() + .find((candidate) => + candidate.providerHandleChain.some(({ handle }) => handle.nativeId === id) + )?.sessionId ?? null) + return owner ? { kind: 'provider-id', orcaSessionId: owner } : { kind: 'unknown' } } export type StructuredSessionMailReach = diff --git a/src/main/runtime/orchestration/mailbox/senders/runtime-orchestration-sender-names.test.ts b/src/main/runtime/orchestration/mailbox/senders/runtime-orchestration-sender-names.test.ts index 2b2f2543dfa..00ca889756c 100644 --- a/src/main/runtime/orchestration/mailbox/senders/runtime-orchestration-sender-names.test.ts +++ b/src/main/runtime/orchestration/mailbox/senders/runtime-orchestration-sender-names.test.ts @@ -32,7 +32,7 @@ import { RuntimeOrchestrationSenderNames } from './runtime-orchestration-sender- import { structuredMailSource } from '../structured-mail/structured-mail-source' import '../../../../../shared/agent-session/view/structured-agent-session-projection' -import '../../../rpc/methods/orchestration/worker/worker-earlier-work' +import '../../../rpc/methods/orchestration/worker/follow-up/worker-earlier-work' const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) vi.mock( @@ -60,13 +60,11 @@ let generatedTitles: boolean let hookRows: HookRow[] let pty: NonNullable> let trackedTitle: string | null -let terminalReads: number function names() { return new RuntimeOrchestrationSenderNames({ getDb: () => db, getHandleRecord: (handle) => { - terminalReads++ return handle === 'term_worker' || handle === 'term_plain' ? { worktreeId: WORKTREE, tabId: `tab_${handle}`, ptyId: `pty_${handle}` } : undefined @@ -80,33 +78,6 @@ function names() { }) } -/** A worker dispatched `spec` on its own terminal, as `worker-start` leaves it. */ -function finishedWorker(spec: string, handle = 'term_worker') { - const run = db.createRun({ - objective: 'o', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: null - }) - const task = db.createTask({ runId: run.id, spec }) - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {} - }) - db.prepareStartingWorkerAuthority({ - dispatchId: started.dispatch.id, - handle, - paneKey: `tab_${handle}:leaf`, - processIncarnation: 'p:1', - worktreeId: WORKTREE, - effects: [], - setupState: 'not_applicable' - }) - db.markWorkerDispatchReady(started.dispatch.id) - return { runId: run.id, taskId: task.id, dispatchId: started.dispatch.id } -} - beforeEach(() => { db = new OrchestrationDb(':memory:') session = { unifiedTabs: {}, tabsByWorktree: {} } @@ -114,7 +85,6 @@ beforeEach(() => { hookRows = [] pty = { launchAgent: 'codex', connectionId: null, launchToken: 'launch-current' } trackedTitle = null - terminalReads = 0 const base = agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: CHAT })) records = new Map([[CHAT, { ...base, location: { ...base.location, workspaceId: WORKTREE } }]]) hostRef.current = { @@ -134,38 +104,6 @@ afterEach(() => { db.close() }) -it('preserves old, malformed and absent launch observations without inventing an agent', () => { - const { dispatchId } = finishedWorker('Inspect parser', 'term_older') - const party = { address: `dispatch:${dispatchId}`, terminalHandle: null, orcaSessionId: null } - for (const launch of [ - undefined, - null, - {}, - [], - { requested: null, effective: {} }, - { requested: { agent: 42 }, effective: { agent: 'x'.repeat(41) } } - ]) { - for (const agent of ['codex', 'cx-personal']) { - const json = JSON.stringify({ agent, launch, unrelated: { keep: true } }) - db.db - .prepare('UPDATE worker_dispatches SET start_options = ? WHERE dispatch_id = ?') - .run(json, dispatchId) - db.retainWorkerLaunchObservation(dispatchId, undefined) - expect(db.getWorkerDispatch(dispatchId)!.start_options).toBe(json) - expect(names().snapshotOf(party)).toEqual({ - name: 'Inspect parser', - agent: agent === 'codex' ? 'codex' : null - }) - } - } - db.db - .prepare('UPDATE worker_dispatches SET start_options = ? WHERE dispatch_id = ?') - .run('invalid-json', dispatchId) - db.retainWorkerLaunchObservation(dispatchId, { requested: { agent: 'codex' } }) - expect(db.getWorkerDispatch(dispatchId)!.start_options).toBe('invalid-json') - expect(names().snapshotOf(party)).toEqual({ name: 'Inspect parser', agent: null }) -}) - it('keeps the accepted answer actor after A parks and B adopts the same Run', () => { const runtime = new OrcaRuntimeService() runtime.setOrchestrationDb(db) diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts index 5f432be1a32..2e0b75b2533 100644 --- a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts +++ b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts @@ -19,7 +19,7 @@ import { formatMessageBannerWithContent, formatMessagePointer } from '../formatting/message-formatting' -import { structuredAgentSessionBlocksTooLarge } from '../../../../../shared/rpc-contract/structured-agent-session-message-params' +import { structuredAgentSessionBlocksTooLarge } from '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-message-params' export type MailSourceMessage = Pick< MessageRow, diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-delivery.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-delivery.ts index 7060b432b3e..b6d224a0c39 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-delivery.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-delivery.ts @@ -59,7 +59,13 @@ export class OrchestrationMailboxPointerDelivery | undefined reservedTypes: ReadonlySet | undefined + /** A terminal's own mailbox leaves rows a Run owns undelivered for routing to move. */ + excludeRunOwnedDirect?: boolean }): OrchestrationPointerBatch { if (hasUnfilteredOrchestrationWaiter(input.waiters)) { return { messages: [], heldDeliveryId: undefined } @@ -60,6 +62,7 @@ export function selectOrchestrationPointerBatch(input: { messages: input.db.getUndeliveredUnreadMessages(input.mailboxHandle, undefined, { excludeTypes: [...excludedTypes], excludeIds: held?.messageIds, + excludeRunOwnedDirect: input.excludeRunOwnedDirect, limit: ORCHESTRATION_DELIVERY_BATCH_LIMIT }), heldDeliveryId: held?.id diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-submit.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-submit.test.ts index 984c7a62423..208cdc83971 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-submit.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-submit.test.ts @@ -10,7 +10,10 @@ import '../../db/dispatch-row-writer' import '../../db/attempt-outcome-projection' import { OrchestrationMailboxPointerState } from './mailbox-pointer-state' import { submitOrchestrationMailboxPointer } from './mailbox-pointer-submit' -import { settledWriteStub, stubWriteSettlement } from '../../../../providers/settled-pty-write-stub' +import { + settledWriteStub, + stubWriteSettlement +} from '../../../../providers/testing/settled-pty-write-stub' import type { WriteSettlement } from '../../../../../shared/terminal/pty/lifecycle/pty-write-settlement' describe('orchestration mailbox pointer submit', () => { @@ -119,72 +122,6 @@ describe('orchestration mailbox pointer submit', () => { db.close() }) - it('holds the Enter while a dialog is open and submits once the agent is idle again', async () => { - const ptyId = 'pty-question' - const mailboxHandle = 'run:run-1' - const terminal = { - ptyId, - handle: 'term-question', - paneKeys: ['tab-1:leaf-1'], - lastAgentStatus: 'idle' as const, - lastAgentStatusObservedLive: true - } - const target = { terminal, processIncarnation: 'inc-question' } - const state = new OrchestrationMailboxPointerState() - const flight = state.beginFlight(ptyId) - state.setWatermark(mailboxHandle, 1, ptyId) - let dialogOpen = true - const writePty = vi.fn(settledWriteStub()) - const markMailboxPointerEnterAttempted = vi.fn(() => true) - const settle = vi.fn(() => state.settleFlight(ptyId, flight)) - const isPtyAwaitingUserInput = vi.fn(() => dialogOpen) - - submitOrchestrationMailboxPointer( - { - mailboxOwner: { resolve: () => mailboxHandle } as never, - state, - getDb: () => - ({ - areUnreadMessages: () => true, - markMailboxPointerEnterAttempted, - settleMailboxPointerEnter: vi.fn() - }) as never, - resolveSubmitTarget: () => target, - isLeafPtyProvenAbsent: async () => false, - isPtyAwaitingUserInput, - writePty, - settle, - redrive: vi.fn() - }, - { - mailboxHandle, - messages: [{ id: 'msg-1', type: 'status' }], - newestSequence: 1, - ptyId, - flight, - expectedTarget: target - } - ) - - await vi.waitFor(() => expect(isPtyAwaitingUserInput).toHaveBeenCalledWith(ptyId)) - await Promise.resolve() - expect(writePty).not.toHaveBeenCalled() - expect(markMailboxPointerEnterAttempted).not.toHaveBeenCalled() - expect(settle).not.toHaveBeenCalled() - expect(flight.deferredUntilIdle).toBe(true) - - state.takeDeferredEnter(ptyId)?.() - await vi.waitFor(() => expect(isPtyAwaitingUserInput).toHaveBeenCalledTimes(2)) - await Promise.resolve() - expect(writePty).not.toHaveBeenCalled() - - dialogOpen = false - state.takeDeferredEnter(ptyId)?.() - await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) - expect(writePty).toHaveBeenCalledOnce() - expect(writePty).toHaveBeenCalledWith(ptyId, '\r') - }) - describe('a pointer whose mail a check read before Enter', () => { function submitAfterRead( options: { @@ -256,70 +193,5 @@ describe('orchestration mailbox pointer submit', () => { }) db.close() }) - - it.each([ - ['the PTY is gone', { absent: true }], - ['the process was replaced', { replaced: true }], - ['a shell is in front', { shellInFront: true }] - ])('sends no Enter when %s', async (_name, options) => { - const { db, writePty, settle } = submitAfterRead(options) - - await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) - expect(writePty).not.toHaveBeenCalled() - db.close() - }) - }) - - it('sends no second Enter for unread mail whose Enter was already attempted', async () => { - const db = new OrchestrationDb(':memory:') - const message = db.insertMessage({ - runId: 'run_legacy_local', - from: 'a', - to: 'run:run-1', - subject: 'already entered' - }) - const ptyId = 'pty-entered' - const reservation = { ptyId, processIncarnation: 'inc-entered' } - const terminal = { - ptyId, - handle: 'term-entered', - paneKeys: ['tab-1:leaf-1'], - lastAgentStatus: 'idle' as const, - lastAgentStatusObservedLive: true - } - const expectedTarget = { terminal, processIncarnation: reservation.processIncarnation } - const state = new OrchestrationMailboxPointerState() - const flight = state.beginFlight(ptyId) - expect(db.stageMailboxPointerEnter([message.id], reservation)).toBe(true) - expect(db.markMailboxPointerWriteAttempted([message.id], reservation)).toBe(true) - expect(db.markMailboxPointerEnterAttempted([message.id], reservation)).toBe(true) - const writePty = vi.fn(settledWriteStub()) - const settle = vi.fn(() => state.settleFlight(ptyId, flight)) - - submitOrchestrationMailboxPointer( - { - mailboxOwner: { resolve: () => 'run:run-1' } as never, - state, - getDb: () => db, - resolveSubmitTarget: () => expectedTarget, - isLeafPtyProvenAbsent: async () => false, - isPtyAwaitingUserInput: () => false, - writePty, - settle, - redrive: vi.fn() - }, - { - mailboxHandle: 'run:run-1', - messages: [{ id: message.id, type: 'status' }], - newestSequence: 1, - ptyId, - flight, - expectedTarget - } - ) - - await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) - expect(writePty).not.toHaveBeenCalled() - db.close() }) }) diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts index c0e79e71901..f11aa72ddab 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts @@ -9,7 +9,7 @@ import { getManagedScript } from '../../../../codex/hooks/definitions/codex-hook import { getSyntheticAgentTerminalTitle } from '../../../../../shared/agent-status/title/synthetic-agent-title' import { extractAllOscTitles } from '../../../../../shared/agent-status/title/osc-title-extraction' import { extractOscTitleScanTail } from '../../../../../shared/osc-title-scan-tail' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' vi.mock('electron', () => ({ app: { getPath: vi.fn(() => tmpdir()), isPackaged: false }, diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mail-follows-terminal-owner.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mail-follows-terminal-owner.test.ts index bd165c3bcea..eebc634d202 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mail-follows-terminal-owner.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mail-follows-terminal-owner.test.ts @@ -5,13 +5,11 @@ import '../../db/contract-constants' import '../../db/messages/mailbox-routing-page' import '../../db/dispatch-row-writer' import '../../db/attempt-outcome-projection' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' import { - createRuntime, LEAF_ID, PANE_KEY, pointerCount, - PTY_ID, SECOND_LEAF_ID, SECOND_TAB_ID, TAB_ID, @@ -43,68 +41,6 @@ describe('Run mail follows the terminal that owns its mailbox', () => { vi.useRealTimers() }) - it('does not type a stale pointer after the terminal moves to another pane mid-probe', async () => { - const db = new OrchestrationDb(':memory:') - const { runtime } = createRuntime(db) - const write = vi.fn(() => true) - let finishProbe: ((live: boolean) => void) | undefined - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: () => true, - getForegroundProcess: async () => null, - probePtyLiveness: () => new Promise((resolve) => (finishProbe = resolve)) - }) - const [terminal] = (await runtime.listTerminals()).terminals - const run = db.createRun({ - objective: 'Moved coordinator', - coordinatorHandle: terminal.handle, - coordinatorPaneKey: PANE_KEY - }) - runtime.onPtyData(PTY_ID, '\x1b]0;Codex done\x07', 1) - await runtime.serializeMainTerminalBuffer(PTY_ID) - db.insertMessage({ - from: 'term_sender', - to: `run:${run.id}`, - subject: 'old pane', - type: 'status', - runId: run.id - }) - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(0) - expect(finishProbe).toBeTypeOf('function') - - runtime.registerPty(PTY_ID, WORKTREE_ID, null, { - tabId: SECOND_TAB_ID, - leafId: SECOND_LEAF_ID, - incarnationId: 'mailbox-incarnation' - }) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: SECOND_TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Moved', - activeLeafId: SECOND_LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: SECOND_TAB_ID, - leafId: SECOND_LEAF_ID, - worktreeId: WORKTREE_ID, - ptyId: PTY_ID, - paneRuntimeId: 2 - } - ] - }) - finishProbe?.(true) - await vi.advanceTimersByTimeAsync(1) - expect(pointerCount(write)).toBe(0) - db.close() - }) - it('wakes a Run bound to one of two panes showing its terminal, whichever is listed first', async () => { const runtime = new OrcaRuntimeService(null) const write = vi.fn((_ptyId: string, _data: string) => true) diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-crash-recovery.spec.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-crash-recovery.spec.ts index 0c316d97871..00713e32fbd 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-crash-recovery.spec.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-crash-recovery.spec.ts @@ -1,4 +1,4 @@ -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness.ts index 614dbef9396..9323a43dd25 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness.ts @@ -1,4 +1,4 @@ -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts deleted file mode 100644 index ccad720259d..00000000000 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { - createBoundRun, - createDatabase, - createRuntime, - insertDirectRunMessage, - PANE_KEY, - PTY_ID, - TERMINAL_HANDLE, - temporaryDirectories -} from './orchestration-mailbox-notification-test-harness' -import { USER_INPUT_HOLD_CAP_MS } from '../../../terminal/wait/claude-open-dialog-hold' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' - -vi.mock('electron', () => ({ - app: { getPath: vi.fn(() => tmpdir()), isPackaged: false }, - BrowserWindow: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - webContents: { fromId: vi.fn(() => null) } -})) - -function claudeHookRow(state: AgentStatusIpcPayload['state']): AgentStatusIpcPayload { - return { - paneKey: PANE_KEY, - terminalHandle: TERMINAL_HANDLE, - agentType: 'claude', - state, - prompt: '', - connectionId: null, - receivedAt: Date.now(), - stateStartedAt: Date.now() - } -} - -const QUESTION_SCREEN = - '\x1b]0;✳ Claude Code\x07Which color?\r\n❯ 1. Red\r\n 2. Blue\r\n' + - 'Enter to select · ↑/↓ to navigate · Esc to cancel\r\n' - -describe('mailbox delivery into a pane awaiting the user', () => { - afterEach(() => { - vi.useRealTimers() - for (const directory of temporaryDirectories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } - }) - - it.each([ - ['answered', 'done', '\x1b[2J\x1b[H❯ \r\n', 2], - ['dismissed with Esc, which posts no hook', 'waiting', '\x1b[2J\x1b[H❯ \r\n', 2], - ['only navigated', 'waiting', '\x1b[2J\x1b[H 1. Red\r\n❯ 2. Blue\r\n', 0] - ] as const)( - 'holds the pointer under a rest title while a question shows; %s', - async (_label, rowAfter, screenAfter, expectedWrites) => { - vi.useFakeTimers() - const db = createDatabase('orca-open-dialog-delivery-hold-') - let hook = claudeHookRow('waiting') - const { runtime, write } = createRuntime(db, { - getAgentStatusSnapshot: () => [hook], - checkHookAgentPresence: async () => 'live', - launchAgent: 'claude' - }) - const run = createBoundRun(db, 'Claude Run') - await runtime.listTerminals() - - runtime.onPtyData(PTY_ID, QUESTION_SCREEN, 1) - await vi.advanceTimersByTimeAsync(200) - insertDirectRunMessage(db, run.id, 'Worker heartbeat') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(10_000) - expect(write).not.toHaveBeenCalled() - - if (rowAfter === 'done') { - hook = claudeHookRow('done') - } - runtime.onPtyData(PTY_ID, screenAfter, 2) - await vi.advanceTimersByTimeAsync(5000) - - expect(write.mock.calls.map(([, data]) => data)).toEqual( - expectedWrites === 0 - ? [] - : [expect.stringContaining('You have 1 orchestration message'), '\r'] - ) - db.close() - } - ) - - it.each([ - ['sent', 'driving', '\x1b[2J\x1b[H', 5000], - ['abandoned past the cap', 'driving', '', USER_INPUT_HOLD_CAP_MS], - ["not for Orca's own launch draft", 'launch', '', 0] - ] as const)( - 'holds the pointer while the composer has an unsent draft; %s', - async (_label, inputKind, screenAfter, waitAfterMs) => { - vi.useFakeTimers() - const db = createDatabase('orca-composer-draft-delivery-hold-') - const { runtime, write } = createRuntime(db, { - getAgentStatusSnapshot: () => [claudeHookRow('done')], - checkHookAgentPresence: async () => 'live', - launchAgent: 'claude' - }) - const run = createBoundRun(db, 'Claude Run') - await runtime.listTerminals() - runtime.terminalRunFacts.recordSpawnCommit({ id: PTY_ID }) - - runtime.onPtyData(PTY_ID, `\x1b]0;✳ Claude Code\x07${'─'.repeat(40)}\r\n❯ `, 1) - runtime.terminalRunFacts.recordInput(PTY_ID, inputKind, 'please refactor the auth') - runtime.onPtyData(PTY_ID, 'please refactor the auth', 2) - await vi.advanceTimersByTimeAsync(200) - insertDirectRunMessage(db, run.id, 'Worker heartbeat') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(10_000) - expect(write).toHaveBeenCalledTimes(inputKind === 'launch' ? 2 : 0) - - runtime.onPtyData(PTY_ID, screenAfter, 3) - await vi.advanceTimersByTimeAsync(waitAfterMs) - - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - db.close() - } - ) - - it("delivers past the agent's dim prompt suggestion right after the user typed (#38015)", async () => { - vi.useFakeTimers() - const db = createDatabase('orca-prompt-suggestion-delivery-') - const { runtime, write } = createRuntime(db, { - getAgentStatusSnapshot: () => [claudeHookRow('done')], - checkHookAgentPresence: async () => 'live', - launchAgent: 'claude' - }) - const run = createBoundRun(db, 'Claude Run') - await runtime.listTerminals() - - runtime.terminalRunFacts.recordInput(PTY_ID, 'driving', 'add a second line\r') - runtime.onPtyData( - PTY_ID, - `\x1b]0;✳ Claude Code\x07${'─'.repeat(40)}\r\n❯ \x1b7\x1b[2madd a timestamp line\x1b[22m\x1b8\r\n${'─'.repeat(40)}\x1b[1A\x1b[3G`, - 1 - ) - await vi.advanceTimersByTimeAsync(200) - insertDirectRunMessage(db, run.id, 'Worker heartbeat') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(10_000) - - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - db.close() - }) - - it.each([ - ['a draft typed before the restart', 'please refactor the auth'], - // Orca died between typing a pointer and its Enter: the new pointer follows it and both submit. - [ - "Orca's own unsent pointer", - 'You have 1 orchestration message. Run `orca orchestration check`.' - ] - ] as const)( - 'after an Orca restart reattaches the agent, holds mail behind %s until the cap', - async (_label, composerText) => { - vi.useFakeTimers() - const db = createDatabase('orca-restored-draft-delivery-hold-') - const { runtime, write } = createRuntime(db, { - getAgentStatusSnapshot: () => [claudeHookRow('done')], - checkHookAgentPresence: async () => 'live', - launchAgent: 'claude' - }) - const run = createBoundRun(db, 'Claude Run') - await runtime.listTerminals() - - runtime.onPtyData(PTY_ID, `\x1b]0;✳ Claude Code\x07${'─'.repeat(40)}\r\n❯ ${composerText}`, 1) - await vi.advanceTimersByTimeAsync(200) - insertDirectRunMessage(db, run.id, 'Worker heartbeat') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(10_000) - expect(write).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(USER_INPUT_HOLD_CAP_MS) - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - db.close() - } - ) - - it('after an Orca restart, holds mail while the restored screen is still loading', async () => { - vi.useFakeTimers() - const db = createDatabase('orca-restoring-screen-delivery-hold-') - const { runtime } = createRuntime(db, { - getAgentStatusSnapshot: () => [claudeHookRow('done')], - checkHookAgentPresence: async () => 'live', - launchAgent: 'claude' - }) - let finishRestore = (_screen: string): void => {} - const write = vi.fn((_ptyId: string, _data: string) => true) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess: async () => null, - hasRendererSerializer: () => true, - serializeBuffer: () => - new Promise((resolve) => { - finishRestore = (data) => resolve({ data, cols: 80, rows: 24 }) - }) - }) - const run = createBoundRun(db, 'Claude Run') - await runtime.listTerminals() - - runtime.onPtyData(PTY_ID, '\x1b]0;✳ Claude Code\x07', 1) - await vi.advanceTimersByTimeAsync(200) - insertDirectRunMessage(db, run.id, 'Worker heartbeat') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(10_000) - expect(write).not.toHaveBeenCalled() - - finishRestore(`${'─'.repeat(40)}\r\n❯ `) - await vi.advanceTimersByTimeAsync(5000) - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - db.close() - }) -}) diff --git a/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts b/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts index e84bf3599bf..bb96e484b36 100644 --- a/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts @@ -1,3 +1,4 @@ +import '../../../agent-hooks/server/testing/memory-agent-identity-store.test-fixture' import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' import { createHash } from 'node:crypto' diff --git a/src/main/runtime/orchestration/terminal-authority/release/terminal-close-slow-agent-exit.test.ts b/src/main/runtime/orchestration/terminal-authority/release/terminal-close-slow-agent-exit.test.ts index 3e7968a16d5..1c222867ad2 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/terminal-close-slow-agent-exit.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/terminal-close-slow-agent-exit.test.ts @@ -10,7 +10,7 @@ import type { OrchestrationDb } from '../../db/orchestration-db' import type { WorkerTerminalResourceRow } from './worker-terminal-ownership' import type { OrcaRuntimeService } from '../../../orca-runtime' -import { completeWorkerTerminalRelease } from '../../../rpc/methods/orchestration/worker/worker-release-completion' +import { completeWorkerTerminalRelease } from '../../../rpc/methods/orchestration/worker/release/worker-release-completion' type Harness = Awaited> @@ -72,7 +72,7 @@ async function closeThroughDaemon( })), isDispatchProcessCurrent: vi.fn(() => true), workerTerminalResourceHasIdentityConflict: vi.fn(() => false), - getWorkerTerminalArchive: vi.fn(() => ({ kind: 'transcript_pin' })), + getWorkerTerminalArchive: vi.fn(() => ({ kind: 'transcript_pin', content: '{}' })), commitWorkerTerminalArchiveForRelease: vi.fn(() => ({ ...resource, release_state: 'releasing' diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield.ts index 4074c6c9b46..418a4f67887 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield.ts @@ -2,7 +2,7 @@ import type { WorkerTerminalReleaseRuntime } from './worker-terminal-release-run import type { WorkerTerminalResourceRow } from './worker-terminal-ownership' /** An automatic close yields to an agent working again, as after a follow-up; its countdown restarts when it rests. - * Checked just before the close, after the output archive committed. */ + * Checked just before the close, after the output reference committed. */ export function yieldAutoReleaseToWorkingAgent( runtime: WorkerTerminalReleaseRuntime, resource: WorkerTerminalResourceRow diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-process-liveness.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-process-liveness.ts index 932adbe7a7f..ae4ca3acc0f 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-process-liveness.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-process-liveness.ts @@ -1,4 +1,4 @@ -import type { PtyProcessInfo } from '../../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../../providers/pty/process-info' /** Match the whole ptyId:incarnationId exactly, including embedded colons; absent or whitespace-dirty incarnation cannot attest identity. */ export function matchesProcessIncarnation( diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts index 9fa5749cf9c..0f9a46fb7c7 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts @@ -1,7 +1,7 @@ import type { WorkerTerminalReleaseRuntime } from './worker-terminal-release-runtime' import { inspectRemoteAttachment } from '../../legacy-remote/federation-attachment-observation' import { releaseRemoteAttachment } from '../../legacy-remote/federated-worker-release-host' -import { completeWorkerTerminalRelease } from '../../../rpc/methods/orchestration/worker/worker-release-completion' +import { completeWorkerTerminalRelease } from '../../../rpc/methods/orchestration/worker/release/worker-release-completion' export type WorkerTerminalReleaseReconciliationResult = { attempted: number diff --git a/src/main/runtime/orchestration/terminal-authority/startup-worker-authority-restore.ts b/src/main/runtime/orchestration/terminal-authority/startup-worker-authority-restore.ts index 76fdb15df98..6a03290146e 100644 --- a/src/main/runtime/orchestration/terminal-authority/startup-worker-authority-restore.ts +++ b/src/main/runtime/orchestration/terminal-authority/startup-worker-authority-restore.ts @@ -1,4 +1,4 @@ -import { waitForStartupPhases } from '../../rpc/startup-phase-wait' +import { waitForStartupPhases } from '../../rpc/startup/startup-phase-wait' // Long enough for a desktop renderer to reattach its terminals; well inside the CLI's 60 s request timeout. export const STARTUP_IDENTITY_WAIT_MS = 30_000 diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts index c60f52afbba..1ee38bcf0de 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts @@ -6,7 +6,7 @@ import type { import type { openCodexAppServerConnection } from '../../../../codex/app-server/codex-app-server-connection' import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' import { attachFingerprintFields } from '../../../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' -import { isRecord } from '../../../rpc/orchestration-session-caller-test-fixture' +import { isRecord } from '../../../rpc/orchestration/callers/session.test-fixture' const WORKSPACE = 'workspace-1' diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts index dc51981640f..789164dd1a9 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts @@ -21,7 +21,7 @@ import { OrchestrationDb } from '../../db/orchestration-db' import { RpcDispatcher } from '../../../rpc/dispatcher' import { ORCHESTRATION_METHODS } from '../../../rpc/methods/orchestration/orchestration' -import { idOf, isRecord, resultOf } from '../../../rpc/orchestration-session-caller-test-fixture' +import { idOf, isRecord, resultOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { ensureStructuredAgentSessionHost, stopStructuredAgentSessionRuntime diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts index ac776f19b44..d3a1ff7e616 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts @@ -1,99 +1,23 @@ -import '../../../rpc/unused-default-rpc-methods.test-fixture' +import '../../../rpc/dispatch/testing/unused-default-rpc-methods.test-fixture' -import { execFile } from 'node:child_process' -import { createRequire } from 'node:module' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { promisify } from 'node:util' import { describe, expect, it, vi } from 'vitest' import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { idOf } from '../../../rpc/orchestration-session-caller-test-fixture' +import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { closeStructuredAgentSessionChild } from '../../../agent-session/structured-agent-session-close' -import { restoreJournal } from '../../../../native-chat/agent-session-journal/replay/journal-open' -import { OrcaRuntimeRpcServer } from '../../../rpc/server/runtime-rpc' -import { ORCHESTRATION_METHODS } from '../../../rpc/methods/orchestration/orchestration' import type { FakeConnection } from './structured-chat-coordinator-fake-codex-fixture' import { COORDINATOR, PEER_CHAT, WAIT, call, - clearChat, coordinatorRunAndTask, - codex, db, - dispatcher, host, - openChat, - request, - root, - runtime, - sendUserMessage, - settleTurn, - startClearedContext + openChat } from './structured-chat-coordinator-mail-rig.test-fixture' const WORKER = formatOrcaSessionAddress(testOrcaSessionId(PEER_CHAT)) -const cliPath = join(process.cwd(), 'src/cli/index.ts') -const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href - -async function readWorkerThroughCli(dispatchId: string): Promise { - const env = { ...process.env } - for (const name of [ - 'HOME', - 'USERPROFILE', - 'APPDATA', - 'LOCALAPPDATA', - 'XDG_CONFIG_HOME', - 'XDG_CACHE_HOME', - 'XDG_DATA_HOME', - 'XDG_STATE_HOME', - 'XDG_RUNTIME_DIR', - 'CLAUDE_CONFIG_DIR', - 'CODEX_HOME', - 'ORCA_E2E_HOME_DIR', - 'ORCA_E2E_USER_DATA_DIR', - 'ORCA_USER_DATA_PATH' - ]) { - env[name] = root - } - for (const name of [ - 'ORCA_ENVIRONMENT', - 'ORCA_PAIRING_CODE', - 'ORCA_REMOTE_PAIRING', - 'ORCA_RUNTIME_SOURCE_ID', - 'ORCA_RUNTIME_SOURCE_INCARNATION', - 'ORCA_RUNTIME_SOURCE_PROFILE_PATH', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_PANE_KEY', - 'ORCA_AGENT_LAUNCH_TOKEN', - 'ORCA_STRUCTURED_SESSION' - ]) { - env[name] = '' - } - env.ORCA_AGENT_SESSION_ID = COORDINATOR - env.ORCA_BACKGROUND_LAUNCH = '1' - env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1' - // execFile owns its child handle, bounds its lifetime, and awaits exit before server cleanup. - const { stdout } = await promisify(execFile)( - process.execPath, - [ - '--import', - tsxLoader, - '--conditions=orca-source', - cliPath, - 'orchestration', - 'worker-read', - '--dispatch', - dispatchId, - '--source', - 'transcript' - ], - { cwd: root, env, timeout: 15_000, windowsHide: true, encoding: 'utf8' } - ) - return stdout -} /** A Dispatch of the coordinator's task to the peer chat, both chats open. */ async function dispatchToChat(): Promise<{ @@ -127,32 +51,6 @@ function expectChatOpen(sessionId: string): void { } describe("a chat assignee's report", () => { - it('is admitted from the same cleared chat, which keeps its Dispatch', async () => { - const { taskId, dispatchId } = await dispatchToChat() - const cleared = await clearChat(PEER_CHAT) - expect(cleared).toBe(PEER_CHAT) - expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') - await startClearedContext(cleared) - - await call('orchestration.send', workerDone(taskId, dispatchId), { sessionId: cleared }) - - expect(db.getDispatchContextById(dispatchId)?.status).toBe('completed') - }) - - it('is refused from a terminal that names the chat as its caller', async () => { - const { taskId, dispatchId } = await dispatchToChat() - - const response = await dispatcher.dispatch( - request('orchestration.send', { ...workerDone(taskId, dispatchId), from: WORKER }) - ) - - expect(response).toMatchObject({ - ok: false, - error: { code: 'session_caller_chat_not_declarable' } - }) - expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') - }) - it("is refused from a terminal that carries the chat's Dispatch under its own handle", async () => { const { taskId, dispatchId } = await dispatchToChat() @@ -168,19 +66,6 @@ describe("a chat assignee's report", () => { }) describe("a chat assignee's liveness, stop and close", () => { - it('reads live at rest, since the next send starts its agent', async () => { - const { dispatchId } = await dispatchToChat() - await host.close(PEER_CHAT, 'evict') - expect(host.deps.store.getRecord(PEER_CHAT)?.lease.claimStatus).toBe('released') - - const shown = await call('orchestration.workerShow', { dispatch: dispatchId }) - - expect(shown).toMatchObject({ - observation: { status: 'live', exactWorker: true }, - projection: { liveness: { verdict: 'live', source: 'execution_host' } } - }) - }) - it('fails its Dispatch when the chat is closed, as a closed terminal does, and reads exited', async () => { const { taskId, dispatchId } = await dispatchToChat() @@ -233,43 +118,4 @@ describe("a chat assignee's liveness, stop and close", () => { expectChatOpen(PEER_CHAT) expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') }) - - it("reads the chat's transcript for worker-read", async () => { - const { dispatchId, worker } = await dispatchToChat() - expect(await sendUserMessage(PEER_CHAT, 'working on it')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - await settleTurn(PEER_CHAT, 0) - - const journal = host.collaboratorsForTests().sessions.get(PEER_CHAT)?.journal - if (!journal) { - throw new Error('Worker conversation was not opened') - } - const prefix = journal.cursor() - await host.close(PEER_CHAT, 'evict') - expect(host.hasSession(PEER_CHAT)).toBe(false) - const saved = restoreJournal(host.deps.journalDatabase.db, PEER_CHAT)?.state - expect(saved?.lastSequence).toBeGreaterThanOrEqual(prefix.sequence) - const acquisitions = codex.connections.length - const server = new OrcaRuntimeRpcServer({ - runtime, - userDataPath: root, - enableWebSocket: false, - methods: ORCHESTRATION_METHODS - }) - try { - await server.start() - const output = await readWorkerThroughCli(dispatchId) - expect(output).toContain('Source: transcript (provider=codex)') - expect(output).toContain('working on it') - expect(host.hasSession(PEER_CHAT)).toBe(true) - expect(codex.connections).toHaveLength(acquisitions) - - const read = await call('orchestration.workerRead', { dispatch: dispatchId }) - - expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) - expect(JSON.stringify(read.transcript)).toContain('working on it') - } finally { - await server.stop() - } - }) }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts index 0513dcf3457..ff73c9fe459 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from 'vitest' import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { idOf } from '../../../rpc/orchestration-session-caller-test-fixture' +import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { COORDINATOR, PEER_CHAT, diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts index 2ab8ca1750a..1528c81caac 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { idOf } from '../../../rpc/orchestration-session-caller-test-fixture' +import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { sendChatTask } from '../../../rpc/methods/orchestration/chat-task-delivery' import { providerFaults, @@ -19,7 +19,6 @@ import { openChat, queuedCardTexts, request, - runtime, sendUserMessage, settleTurn, turnText @@ -52,10 +51,6 @@ async function runningUserTurn( } } -function queuedRows(sessionId: string) { - return host.collaboratorsForTests().sessions.get(sessionId)?.journal.queuedMessages.list() ?? [] -} - async function refusal(method: string, params: Record, sessionId?: string) { const response = await dispatcher.dispatch( request(method, params, sessionId ? { sessionId } : {}) @@ -66,56 +61,11 @@ async function refusal(method: string, params: Record, sessionI return response.error } -/** Who each agent message in the chat's journal says it is from. */ -async function taskSenders(sessionId: string): Promise { - return (await host.journalSnapshot(sessionId)).items.flatMap((item) => - item.body.kind === 'message' && item.body.from ? [item.body.from] : [] - ) -} - function dispatchCount(): unknown { return db.db.prepare('SELECT COUNT(*) AS n FROM dispatch_contexts').get() } describe('a chat as the assignee of orchestration dispatch', () => { - it("holds the task as a card in a busy chat's queue, naming the Dispatch, and sends it when the turn ends", async () => { - await openChat(COORDINATOR) - const worker = await openChat(PEER_CHAT) - const { runId, taskId } = await coordinatorRunAndTask() - const endTurn = await runningUserTurn(PEER_CHAT, worker) - - const result = await call( - 'orchestration.dispatch', - { task: taskId, to: WORKER, inject: true }, - { sessionId: COORDINATOR } - ) - - expect(result).toMatchObject({ injected: true }) - const dispatchId = idOf(result.dispatch) - expect(worker.turns).toHaveLength(1) - const from = { - kind: 'agent', - senders: [ - { - party: { - address: formatOrcaSessionAddress(testOrcaSessionId(COORDINATOR)), - terminalHandle: null, - orcaSessionId: COORDINATOR - } - } - ], - orchestration: { message: 'task', runId, taskId, dispatchId } - } - // On the card's body: the turn the queue sends carries it, and the provider never sees it. - expect(queuedRows(PEER_CHAT).map((card) => card.body.from)).toMatchObject([from]) - - await endTurn() - await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) - expect(turnText(worker.turns[1]!)).toContain(dispatchId) - expect(await queuedCardTexts(PEER_CHAT)).toEqual([]) - expect(await taskSenders(PEER_CHAT)).toMatchObject([from]) - }) - it('queues one card for one Dispatch however often its task is sent', async () => { await openChat(COORDINATOR) const worker = await openChat(PEER_CHAT) @@ -203,30 +153,4 @@ describe('a chat as the assignee of orchestration dispatch', () => { messages: [] }) }) - - it("counts a chat worker's own Dispatch as depth 2, under the nesting cap", async () => { - await openChat(COORDINATOR) - await openChat(PEER_CHAT) - const { taskId } = await coordinatorRunAndTask() - const parent = await call( - 'orchestration.dispatch', - { task: taskId, to: WORKER }, - { sessionId: COORDINATOR } - ) - expect(parent.dispatch).toMatchObject({ depth: 1 }) - await call('orchestration.runCreate', { objective: 'sub' }, { sessionId: PEER_CHAT }) - const subTask = idOf( - (await call('orchestration.taskCreate', { spec: 'part' }, { sessionId: PEER_CHAT })).task - ) - - const subDispatch = { task: subTask, to: 'term_worker' } - - const maxDepth = vi.spyOn(runtime, 'getNestedWorkerMaxDepth').mockReturnValue(1) - expect(await refusal('orchestration.dispatch', subDispatch, PEER_CHAT)).toMatchObject({ - code: 'nested_worker_depth_exceeded' - }) - maxDepth.mockReturnValue(2) - const child = await call('orchestration.dispatch', subDispatch, { sessionId: PEER_CHAT }) - expect(child.dispatch).toMatchObject({ depth: 2, creator_dispatch_id: idOf(parent.dispatch) }) - }) }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts index 1e02c1f3b95..5faea46c987 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts @@ -3,15 +3,12 @@ import { describe, expect, it, vi } from 'vitest' import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' +import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store' import { structuredAgentSessionMessageSendMutation } from '../../../../../shared/agent-session/requests/structured-agent-session-send-mutation' import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store' import type { AgentMessageSource } from '../../../../../shared/agent-session/agent-session-message-source' -import { agentSessionRefusalNotice } from '../../../../../shared/agent-session/failures/agent-session-refusal-notice' -import { agentSessionWriteKindForMethod } from '../../../../../shared/agent-session/failures/agent-session-write-failure' -import { nextStructuredQueuedMessage } from '../../../../native-chat/agent-session-wire/delivery/structured-agent-session-queued-gate' -import { idOf } from '../../../rpc/orchestration-session-caller-test-fixture' +import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { operationId } from './structured-chat-coordinator-fake-codex-fixture' import { COORDINATOR, @@ -31,9 +28,19 @@ import { turnText } from './structured-chat-coordinator-mail-rig.test-fixture' -/** A chat with a turn running, so mail waits as cards behind it. */ -async function busyChat(sessionId: string) { +/** A running turn, optionally with its first handover still unanswered. */ +async function busyChat(sessionId: string, startReply?: Promise) { const chat = await openChat(sessionId) + if (startReply) { + const request = chat.request + chat.request = async (...args) => { + const response = await request(...args) + if (args[0] === 'turn/start') { + await startReply + } + return response + } + } expect(await sendUserMessage(sessionId, 'go')).toMatchObject({ ok: true }) await vi.waitFor(() => expect(chat.turns).toHaveLength(1), WAIT) chat.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) @@ -137,71 +144,38 @@ describe('a queued mail card runs only while its chat still owes it', () => { await vi.waitFor(() => expect(db.getUnreadMessages(`run:${runId}`)).toEqual([]), WAIT) }) - it('refuses an explicit Send of a card no longer owed, removing it without a turn', async () => { - const chat = await busyChat(COORDINATOR) - const { runId, taskId } = await coordinatorRunAndTask() - await finishWorker(taskId) - await vi.waitFor(async () => expect(await queuedCardTexts()).toHaveLength(1), WAIT) - vi.spyOn(runtime, 'withdrawStaleChatMail').mockImplementation(() => {}) - // A check takes the report while its card still waits. - expect(await call('orchestration.check', {}, { sessionId: COORDINATOR })).toMatchObject({ - runId, - count: 1 - }) - const [card] = journalOf(COORDINATOR).queuedMessages.list() - const fields = { messageId: card!.messageId } - const sent = await host.queuedMessageSend( - { callerKey: 'test-surface' }, - { - envelope: { - sessionId: COORDINATOR, - clientOperationId: operationId(), - expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.queuedMessageSend', - sessionId: COORDINATOR, - fields - }) - }, - ...fields - } - ) - if (sent.ok) { - throw new Error('a stale Send went through') - } - // The person is told why the card went, on desktop and phone alike. - expect(agentSessionRefusalNotice(sent.refusal, 'send', { agentName: 'Codex' })).toContain( - 'This chat has moved on.' - ) - expect(await queuedCardTexts()).toEqual([]) - expect(chat.turns).toHaveLength(1) - }) - it("lets the person's cards pass mail it cannot decide on now, then hands the mail over first once it can", async () => { - const chat = await busyChat(COORDINATOR) - const { taskId } = await coordinatorRunAndTask() - await finishWorker(taskId) - await vi.waitFor(async () => expect(await queuedCardTexts()).toHaveLength(1), WAIT) - await queueCard('first question of mine') - await queueCard('second question of mine') - const unreadable = vi.spyOn(db, 'areUnreadMessages').mockImplementation(() => { - throw new Error('database unavailable') - }) - await settleTurn(COORDINATOR, 0) - await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) - // The person's first card went, in their order; the report and their second card still wait. - expect(turnText(chat.turns[1]!)).toContain('first question of mine') - const waiting = await queuedCardTexts() - expect(waiting).toHaveLength(2) - expect(waiting[0]).toContain('(worker_done)') - unreadable.mockRestore() - await settleTurn(COORDINATOR, 1) - // Readable again: the older report goes before the person's later card. - await vi.waitFor(() => expect(chat.turns).toHaveLength(3), WAIT) - expect(isWholeMail(turnText(chat.turns[2]!))).toBe(true) - await settleTurn(COORDINATOR, 2) - await vi.waitFor(() => expect(chat.turns).toHaveLength(4), WAIT) - expect(turnText(chat.turns[3]!)).toContain('second question of mine') + const reply = Promise.withResolvers() + try { + const chat = await busyChat(COORDINATOR, reply.promise) + const { taskId } = await coordinatorRunAndTask() + await finishWorker(taskId) + await vi.waitFor(async () => expect(await queuedCardTexts()).toHaveLength(1), WAIT) + await queueCard('first question of mine') + await queueCard('second question of mine') + const unreadable = vi.spyOn(db, 'areUnreadMessages').mockImplementation(() => { + throw new Error('database unavailable') + }) + expect(chat.steers).toEqual([]) + reply.resolve() + await settleTurn(COORDINATOR, 0) + await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) + // The person's first card went, in their order; the report and their second card still wait. + expect(turnText(chat.turns[1]!)).toContain('first question of mine') + const waiting = await queuedCardTexts() + expect(waiting).toHaveLength(2) + expect(waiting[0]).toContain('(worker_done)') + unreadable.mockRestore() + await settleTurn(COORDINATOR, 1) + // Readable again: the older report goes before the person's later card. + await vi.waitFor(() => expect(chat.turns).toHaveLength(3), WAIT) + expect(isWholeMail(turnText(chat.turns[2]!))).toBe(true) + await settleTurn(COORDINATOR, 2) + await vi.waitFor(() => expect(chat.turns).toHaveLength(4), WAIT) + expect(turnText(chat.turns[3]!)).toContain('second question of mine') + } finally { + reply.resolve() + } }) it('hands a Task over without opening the mail database', async () => { @@ -247,121 +221,70 @@ describe('a queued mail card runs only while its chat still owes it', () => { await vi.waitFor(() => expect(selectable).toContain(1), WAIT) }) - it('publishes nothing as next while only undecidable mail waits, and hands it over once readable', async () => { - const chat = await busyChat(COORDINATOR) - const { taskId } = await coordinatorRunAndTask() - await finishWorker(taskId) - await vi.waitFor(async () => expect(await queuedCardTexts()).toHaveLength(1), WAIT) - const unreadable = vi.spyOn(db, 'areUnreadMessages').mockImplementation(() => { - throw new Error('database unavailable') - }) - await settleTurn(COORDINATOR, 0) - const journal = journalOf(COORDINATOR) - const work = host.currentWork(COORDINATOR)! - // Idle with nothing to hand over: not working, so /clear and the person's sends go through. - await vi.waitFor(() => expect(work.working()).toBe(false), WAIT) - const record = host.deps.store.getRecord(COORDINATOR) - expect(nextStructuredQueuedMessage({ journal, record, work })).toBeNull() - // The person's Send of that card says what happened, never that Orca restarted. - const card = journal.queuedMessages.list().find((row) => row.state === 'waiting') - const fields = { messageId: card!.messageId } - const sent = await host.queuedMessageSend( - { callerKey: 'test-surface' }, - { - envelope: { + it('sends a report refused for queue room once the queue frees room', async () => { + const reply = Promise.withResolvers() + try { + const chat = await busyChat(COORDINATOR, reply.promise) + const { runId, taskId } = await coordinatorRunAndTask() + // The person's queue holds almost all the room an agent's message may use. + for (let card = 0; card < 4; card += 1) { + const mutation = structuredAgentSessionMessageSendMutation({ sessionId: COORDINATOR, clientOperationId: operationId(), expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.queuedMessageSend', - sessionId: COORDINATOR, - fields - }) - }, - ...fields + body: { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'x'.repeat(240_000) }] + }, + delivery: 'queue-if-active' + }) + expect( + await host.send({ callerKey: 'test-surface' }, { ...mutation, userSend: true }) + ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) } - ) - if (sent.ok) { - throw new Error('an undecidable Send went through') - } - // Worded as the card's Send is, desktop and phone alike, with its step even beside a Retry. - const write = agentSessionWriteKindForMethod('agentSession.queuedMessageSend', fields) - for (const retryControl of [false, true]) { - expect(agentSessionRefusalNotice(sent.refusal, write, { retryControl })).toBe( - "Orca couldn't confirm this message is still meant for this chat. Your message was not sent. Try again." + const send = vi.spyOn(host, 'send') + await finishWorker(taskId) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1), WAIT) + // The refusal releases the reservation made before the send. + await vi.waitFor( + () => expect(db.getUnreadMessages(`run:${runId}`)).toMatchObject([{ delivered_at: null }]), + WAIT ) - } - expect(chat.turns).toHaveLength(1) - // Readable again: the lane's next look wakes the queue, with no action from the person. - unreadable.mockRestore() - runtime.withdrawStaleChatMail() - await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) - expect(isWholeMail(turnText(chat.turns[1]!))).toBe(true) - }) - - it('sends a report refused for queue room once the queue frees room, and never spins meanwhile', async () => { - const chat = await busyChat(COORDINATOR) - const { runId, taskId } = await coordinatorRunAndTask() - // The person's queue holds almost all the room an agent's message may use. - for (let card = 0; card < 4; card += 1) { - const mutation = structuredAgentSessionMessageSendMutation({ - sessionId: COORDINATOR, - clientOperationId: operationId(), - expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'x'.repeat(240_000) }] - }, - delivery: 'queue-if-active' - }) - expect( - await host.send({ callerKey: 'test-surface' }, { ...mutation, userSend: true }) - ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) - } - const send = vi.spyOn(host, 'send') - await finishWorker(taskId) - await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1), WAIT) - // The refusal releases the reservation made before the send. - await vi.waitFor( - () => expect(db.getUnreadMessages(`run:${runId}`)).toMatchObject([{ delivered_at: null }]), - WAIT - ) - // Unrelated journal writes do not retry a refusal into a loop. - await journalOf(COORDINATOR).appendQueueResume( - host.deps.store.getConversation(COORDINATOR)!.currentFence - ) - await vi.waitFor(() => expect(send.mock.calls.length).toBeLessThanOrEqual(2), WAIT) - - // Deleting the person's cards frees room: that journal edge alone sends the report. - for (const card of journalOf(COORDINATOR).queuedMessages.list()) { - const fields = { messageId: card.messageId } - expect( - await host.queuedMessageDelete( - { callerKey: 'test-surface' }, - { - envelope: { - sessionId: COORDINATOR, - clientOperationId: operationId(), - expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.queuedMessageDelete', + // Deleting the person's cards frees room: that journal edge alone sends the report. + for (const card of journalOf(COORDINATOR).queuedMessages.list()) { + const fields = { messageId: card.messageId } + expect( + await host.queuedMessageDelete( + { callerKey: 'test-surface' }, + { + envelope: { sessionId: COORDINATOR, - fields - }) - }, - ...fields - } - ) - ).toMatchObject({ ok: true }) + clientOperationId: operationId(), + expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.queuedMessageDelete', + sessionId: COORDINATOR, + fields + }) + }, + ...fields + } + ) + ).toMatchObject({ ok: true }) + } + await vi.waitFor(async () => { + const cards = await queuedCardTexts() + expect(cards).toHaveLength(1) + expect(cards[0]).toContain('(worker_done)') + }, WAIT) + expect(chat.steers).toEqual([]) + reply.resolve() + await settleTurn(COORDINATOR, 0) + await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) + expect(isWholeMail(turnText(chat.turns[1]!))).toBe(true) + } finally { + reply.resolve() } - await vi.waitFor(async () => { - const cards = await queuedCardTexts() - expect(cards).toHaveLength(1) - expect(cards[0]).toContain('(worker_done)') - }, WAIT) - await settleTurn(COORDINATOR, 0) - await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) - expect(isWholeMail(turnText(chat.turns[1]!))).toBe(true) }) }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-helpers.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-helpers.test.ts deleted file mode 100644 index b2f386285ae..00000000000 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-helpers.test.ts +++ /dev/null @@ -1,329 +0,0 @@ -// Dispatched chats retain their mailbox while starting nested helpers; unhandled mail returns to the Run coordinator on settlement. - -import { describe, expect, it, vi } from 'vitest' -import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' -import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { idOf, resultOf } from '../../../rpc/orchestration-session-caller-test-fixture' -import type { DispatchCreator } from '../../db/dispatch-depth' -import { - COORDINATOR, - PEER_CHAT, - WAIT, - WORKER_2_PANE, - WORKER_PANE, - call, - coordinatorRunAndTask, - db, - dispatcher, - openChat, - request, - restartRuntime, - runtime, - turnText -} from './structured-chat-coordinator-mail-rig.test-fixture' - -const WORKER = formatOrcaSessionAddress(testOrcaSessionId(PEER_CHAT)) -const HELPER = 'term_worker' -/** A helper's own helper, two levels below the Run's coordinator. */ -const LEAF = 'term_worker_2' - -async function refusal(method: string, params: Record, sessionId: string) { - const response = await dispatcher.dispatch(request(method, params, { sessionId })) - if (response.ok) { - throw new Error(`expected a refusal, got ${JSON.stringify(response)}`) - } - return response.error -} - -/** The helper row worker-start reserves once the worker's authority resolved, in a live terminal. */ -function reserveHelper( - creatorDispatchId: string, - creator: DispatchCreator = { kind: 'session', orcaSessionId: testOrcaSessionId(PEER_CHAT) }, - handle = HELPER, - paneKey = WORKER_PANE -): { dispatchId: string; taskId: string } { - const started = db.createStartingWorkerDispatch({ - creator, - maxDepth: runtime.getNestedWorkerMaxDepth(), - requiredCreatorDispatchId: creatorDispatchId, - taskSpec: 'review the parser', - taskRunId: db.getDispatchContextById(creatorDispatchId)!.run_id, - taskParentId: db.getDispatchContextById(creatorDispatchId)!.task_id, - startOptions: {} - }) - db.prepareStartingWorkerAuthority({ - dispatchId: started.dispatch.id, - handle, - paneKey, - processIncarnation: `runtime_test:${handle}:1`, - worktreeId: 'repo::worker', - effects: [], - setupState: 'not_applicable' - }) - db.markWorkerDispatchReady(started.dispatch.id) - return { dispatchId: started.dispatch.id, taskId: started.task.id } -} - -function helperSend(type: string, subject: string, helper: { dispatchId: string; taskId: string }) { - return call('orchestration.send', { - from: HELPER, - type, - subject, - payload: JSON.stringify({ ...helper, outcome: 'succeeded' }) - }) -} - -function inboxOf(inbox: Record) { - const messages = Array.isArray(inbox.messages) - ? inbox.messages.map((message: Record) => ({ - id: String(message.id), - subject: String(message.subject), - type: String(message.type) - })) - : [] - return { deliveryId: inbox.deliveryId, messages } -} - -/** A chat checks by its session; a terminal helper by its handle. */ -async function check(caller: string, ack?: unknown) { - const byTerminal = caller.startsWith('term_') - return inboxOf( - await call( - 'orchestration.check', - { ...(byTerminal ? { terminal: caller } : {}), ...(ack ? { ack } : {}) }, - byTerminal ? {} : { sessionId: caller } - ) - ) -} - -async function subjects(caller: string, ack?: unknown): Promise { - return (await check(caller, ack)).messages.map((message) => message.subject) -} - -describe('a worker starting helpers on the Run it works for', () => { - it('gets their reports and questions in its own check, and hands the unhandled rest to the Run when it settles', async () => { - await openChat(COORDINATOR) - await openChat(PEER_CHAT) - const { runId, taskId } = await coordinatorRunAndTask() - const parent = idOf( - ( - await call( - 'orchestration.dispatch', - { task: taskId, to: WORKER }, - { sessionId: COORDINATOR } - ) - ).dispatch - ) - vi.spyOn(runtime, 'getNestedWorkerMaxDepth').mockReturnValue(2) - - // The coordinator seat no longer gates it: the worker reaches the helper-scope rules instead. - expect( - await refusal( - 'orchestration.workerStart', - { run: runId, spec: 'review', terminal: HELPER }, - PEER_CHAT - ) - ).toMatchObject({ code: 'invalid_argument', message: expect.stringContaining('--terminal') }) - - const helper = reserveHelper(parent) - expect(db.getDispatchContextById(helper.dispatchId)).toMatchObject({ - run_id: runId, - creator_dispatch_id: parent, - depth: 2 - }) - - await helperSend('escalation', 'Blocked on fixtures', helper) - const asked = call('orchestration.ask', { from: HELPER, question: 'Which parser?' }) - await vi.waitFor( - () => - expect(db.db.prepare('SELECT COUNT(*) AS n FROM question_threads').get()).toEqual({ n: 1 }), - WAIT - ) - const inbox = await check(PEER_CHAT) - const messages = inbox.messages - expect(messages.map((message) => message.subject)).toEqual(['Blocked on fixtures', 'Question']) - await call( - 'orchestration.reply', - { id: messages.find((message) => message.type === 'question')!.id, body: 'the TOML one' }, - { sessionId: PEER_CHAT } - ) - expect(await asked).toMatchObject({ answer: 'the TOML one' }) - - expect(await subjects(COORDINATOR)).toEqual([]) - expect(await call('orchestration.runCurrent', {}, { sessionId: PEER_CHAT })).toEqual({ - run: null - }) - - // The worker's last check acknowledges what it read; what arrives after goes to the Run. - expect(await subjects(PEER_CHAT, inbox.deliveryId)).toEqual([]) - await helperSend('escalation', 'Blocked again', helper) - await call( - 'orchestration.send', - { - type: 'worker_done', - subject: 'Parent done', - payload: JSON.stringify({ taskId, dispatchId: parent, outcome: 'succeeded' }) - }, - { sessionId: PEER_CHAT } - ) - await helperSend('worker_done', 'Helper done', helper) - expect(await subjects(COORDINATOR)).toEqual(['Blocked again', 'Parent done', 'Helper done']) - }) -}) - -/** The Run's coordinator, a dispatched chat, its terminal helper, and that helper's own helper. */ -async function threeLevels() { - const chat = await openChat(COORDINATOR) - await openChat(PEER_CHAT) - const { runId, taskId } = await coordinatorRunAndTask() - const parent = idOf( - (await call('orchestration.dispatch', { task: taskId, to: WORKER }, { sessionId: COORDINATOR })) - .dispatch - ) - vi.spyOn(runtime, 'getNestedWorkerMaxDepth').mockReturnValue(3) - const middle = reserveHelper(parent) - const leaf = reserveHelper( - middle.dispatchId, - { kind: 'terminal', handle: HELPER, paneKey: WORKER_PANE }, - LEAF, - WORKER_2_PANE - ) - return { chat, runId, middle, leaf } -} - -/** The coordinator waiting on questions only, as its loop does between steps. */ -async function parkRunQuestionCheck(runId: string) { - expect(await subjects(COORDINATOR)).toEqual([]) - const parked = call( - 'orchestration.check', - { wait: true, types: 'question', timeoutMs: 10_000 }, - { sessionId: COORDINATOR } - ) - await vi.waitFor( - () => expect(runtime.messageWaitersByHandle.has(`run:${runId}`)).toBe(true), - WAIT - ) - return { parked } -} - -async function answerFromRun(parked: Promise>, expected: string[]) { - const woke = inboxOf(await parked) - expect(woke.messages.map((message) => message.subject)).toEqual(expected) - const question = woke.messages.find((message) => message.type === 'question')! - await call( - 'orchestration.reply', - { id: question.id, body: 'the TOML one' }, - { sessionId: COORDINATOR } - ) - return woke -} - -describe('a helper whose creator settles between it and the Run', () => { - it('wakes the Run for its question, which the Run answers, and reports arrive once', async () => { - const { runId, middle } = await threeLevels() - await call('orchestration.send', { from: LEAF, type: 'status', subject: 'Read status' }) - const asked = call('orchestration.ask', { from: LEAF, question: 'Which parser?' }) - await vi.waitFor( - () => expect(db.getAllMessages(`dispatch:${middle.dispatchId}`)).toHaveLength(2), - WAIT - ) - // The middle worker reads both, but never answers. - const read = await check(HELPER) - expect(read.messages.map((message) => message.subject)).toEqual(['Read status', 'Question']) - expect(await subjects(HELPER, read.deliveryId)).toEqual([]) - await call('orchestration.send', { from: LEAF, type: 'status', subject: 'Unread status' }) - const { parked } = await parkRunQuestionCheck(runId) - - await helperSend('worker_done', 'Middle done', middle) - const woke = await answerFromRun(parked, ['Question', 'Unread status']) - expect(await asked).toMatchObject({ answer: 'the TOML one' }) - expect(await subjects(COORDINATOR, woke.deliveryId)).toEqual([]) - expect(await subjects(PEER_CHAT)).toEqual(['Middle done']) - }) - - it('also hands over a question asked while its creator was being stopped', async () => { - const { runId, middle } = await threeLevels() - const { parked } = await parkRunQuestionCheck(runId) - db.beginWorkerStop(middle.dispatchId, 'test-stop') - const asked = call('orchestration.ask', { from: LEAF, question: 'Which parser?' }) - await vi.waitFor( - () => expect(db.getAllMessages(`dispatch:${middle.dispatchId}`)).toHaveLength(1), - WAIT - ) - - db.settleWorkerStop(middle.dispatchId) - await answerFromRun(parked, ['Question']) - expect(await asked).toMatchObject({ answer: 'the TOML one' }) - }) - - it('re-offers the handed-back question to the Run on every replay of its settling report', async () => { - const { runId, middle, leaf } = await threeLevels() - db.createQuestion({ - runId, - dispatchId: leaf.dispatchId, - askerHandle: LEAF, - question: 'Which parser?', - to: `dispatch:${middle.dispatchId}` - }) - const done = request('orchestration.send', { - from: HELPER, - type: 'worker_done', - subject: 'Middle done', - payload: JSON.stringify({ ...middle, outcome: 'succeeded' }) - }) - resultOf(await dispatcher.dispatch(done)) - await new Promise((resolve) => setTimeout(resolve, 0)) - const countMessages = () => db.db.prepare('SELECT COUNT(*) AS n FROM messages').get() - const before = countMessages() - const notify = vi.spyOn(runtime, 'notifyMessageArrived') - - // The second replay reads the receipt the first replay rewrote. - for (const replays of [1, 2]) { - expect(resultOf(await dispatcher.dispatch(done))).toMatchObject({ - mutation: { replayed: true } - }) - expect( - notify.mock.calls.filter(([to, type]) => to === `run:${runId}` && type === 'question') - ).toHaveLength(replays) - } - expect(countMessages()).toEqual(before) - }) - - it('moves nothing on rollback; a restart offers a committed hand-back nothing woke', async () => { - const { chat, runId, middle, leaf } = await threeLevels() - const mailbox = `dispatch:${middle.dispatchId}` - db.createQuestion({ - runId, - dispatchId: leaf.dispatchId, - askerHandle: LEAF, - question: 'Which parser?', - to: mailbox - }) - await call('orchestration.send', { from: LEAF, type: 'status', subject: 'Unread status' }) - const ids = db.getAllMessages(mailbox).map((message) => message.id) - // The middle worker's pointer for both already landed. - db.markAsDelivered(ids, mailbox) - const notify = vi.spyOn(runtime, 'notifyMessageArrived') - - db.db.exec('BEGIN IMMEDIATE') - db.completeDispatch(middle.dispatchId) - db.db.exec('ROLLBACK') - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(db.getAllMessages(mailbox)).toHaveLength(2) - expect(db.getUndeliveredUnreadMessages(mailbox)).toEqual([]) - expect(notify).not.toHaveBeenCalledWith(`run:${runId}`, expect.anything()) - - // Committed, but the process ends before anything wakes the Run; the old pointer lands late. - db.mailHandBackListener = undefined - db.completeDispatch(middle.dispatchId) - db.markAsDelivered(ids, mailbox) - expect(db.getUndeliveredUnreadMessages(`run:${runId}`).map((message) => message.id)).toEqual( - expect.arrayContaining(ids) - ) - - restartRuntime() - await vi.waitFor(() => expect(chat.turns).toHaveLength(1), WAIT) - // Oldest first, whole: the handed-back question is the Run coordinator's first turn. - expect(turnText(chat.turns[0]!)).toMatch(/Subject: Question\nWhich parser\?/) - }) -}) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts index 3b2524898c6..b3710287a0e 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts @@ -1,11 +1,9 @@ // A finished structured worker takes follow-up work in its own chat through worker-start --terminal , or a send to its Dispatch. -import { structuredMailboxCustody } from '../../mailbox/routing/structured-session-mail-target' import { beforeEach, describe, expect, it, vi } from 'vitest' import '../../../../../shared/orca-session-address' -import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { idOf } from '../../../rpc/orchestration-session-caller-test-fixture' +import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { COORDINATOR, WAIT, @@ -27,7 +25,7 @@ import { import { getFollowUpDispatch } from '../../db/dispatch-context/worker-follow-up-lineage' import { structuredWorkerIdentities } from './structured-worker-identity' import { createStructuredWorkerSession } from '../../../rpc/methods/orchestration/structured-workers/orchestration-structured-worker-session' -import type { placeWorkerAgent } from '../../../rpc/methods/orchestration/worker/worker-start-agent-placement' +import type { placeWorkerAgent } from '../../../rpc/methods/orchestration/worker/start/placement/worker-start-agent-placement' // The worker's chat is created in the rig's real session host, as the production create would. vi.mock( @@ -147,75 +145,6 @@ async function followUpTask(): Promise { } describe('a finished structured worker', () => { - it('takes a follow-up Dispatch in its chat, and releasing it frees the worker', async () => { - await openChat(COORDINATOR) - const { taskId } = await coordinatorRunAndTask() - const { identity, released, firstDispatchId } = await finishedStructuredWorker(taskId) - const worker = connectionFor(identity.sessionId) - const resource = db.getWorkerTerminalResourceByOwner(firstDispatchId) - expect(resource?.auto_release_at).not.toBeNull() - - const followUp = await followUpTask() - const started = call( - 'orchestration.workerStart', - { task: followUp, terminal: identity.handle }, - { sessionId: COORDINATOR } - ) - await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - await settleTurn(identity.sessionId, 0) - const receipt = await started - - expect(receipt).toMatchObject({ state: 'ready', turnStart: 'observed' }) - const dispatchId = String(receipt.dispatchId) - const task = turnText(worker.turns[0]!) - expect(task).toContain(dispatchId) - expect(task).toContain( - `Your Orca session ID is: ${ORCA_SESSION_ADDRESS_PREFIX}${identity.sessionId}` - ) - expect(db.getDispatchContextById(dispatchId)).toMatchObject({ - assignee_handle: identity.handle, - assignee_orca_session_id: identity.sessionId - }) - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - id: resource!.id, - ownership_state: 'owned', - auto_release_at: null - }) - - expect(await reportDone(identity.sessionId, followUp, dispatchId)).toMatchObject({ ok: true }) - expect(released()).toBe(0) - expect(structuredMailboxCustody(identity.handle, db)).toMatchObject({ - sessionId: identity.sessionId - }) - await call('orchestration.workerRelease', { dispatch: dispatchId }, { sessionId: COORDINATOR }) - await vi.waitFor(() => expect(released()).toBe(1), WAIT) - // Released: mail to its handle is no longer this chat's, so a card for it never holds the person's queue. - expect(structuredMailboxCustody(identity.handle, db)).toBe('elsewhere') - }) - - it('given new work after abandon, is bound again so its release frees it again', async () => { - await openChat(COORDINATOR) - const { taskId } = await coordinatorRunAndTask() - const { identity, released } = await finishedStructuredWorker(taskId, 'abandon') - expect(released()).toBe(1) - const worker = connectionFor(identity.sessionId) - - const followUp = await followUpTask() - const started = call( - 'orchestration.workerStart', - { task: followUp, terminal: identity.handle }, - { sessionId: COORDINATOR } - ) - await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - await settleTurn(identity.sessionId, 0) - const dispatchId = String((await started).dispatchId) - expect(structuredWorkerIdentities.get(identity.handle)).not.toBeNull() - - expect(await reportDone(identity.sessionId, followUp, dispatchId)).toMatchObject({ ok: true }) - await call('orchestration.workerRelease', { dispatch: dispatchId }, { sessionId: COORDINATOR }) - await vi.waitFor(() => expect(released()).toBe(2), WAIT) - }) - it('kept open by the user takes follow-up work and stays kept', async () => { await openChat(COORDINATOR) const { taskId } = await coordinatorRunAndTask() @@ -355,6 +284,15 @@ describe('a send to a finished structured worker', () => { expect(await followUp).toMatchObject({ delivery: 'reopened', state: 'ready' }) expect(host.isSessionTabVisible(identity.sessionId)).toBe(true) + // The coordinator's chat shows the reopen, never a newly started worker. + await vi.waitFor(async () => { + const cards = (await host.journalSnapshot(COORDINATOR)).items.flatMap(({ body }) => + body?.kind === 'agent-start' ? [body] : [] + ) + expect(cards).toEqual([ + expect.objectContaining({ followUp: { of: firstDispatchId, reopened: true } }) + ]) + }, WAIT) expect(db.getWorkerTerminalResourceByOwner(String((await followUp).dispatchId))).toMatchObject({ terminal_handle: identity.handle, ownership_state: 'owned' @@ -368,44 +306,59 @@ describe('a send to a finished structured worker', () => { const { taskId } = await coordinatorRunAndTask() const { identity, firstDispatchId } = await finishedStructuredWorker(taskId, 'none') const worker = connectionFor(identity.sessionId) - expect(await sendUserMessage(identity.sessionId, 'go')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - worker.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) - await host.flushStreamedEvents(identity.sessionId) - await sendTo(firstDispatchId, 'and the docs') - // The mail waits as a card behind the running turn; the worker reports before it is handed over. - await vi.waitFor( - async () => expect(await queuedCardTexts(identity.sessionId)).toHaveLength(1), - WAIT - ) + const reply = Promise.withResolvers() + const request = worker.request + worker.request = async (...args) => { + const response = await request(...args) + if (args[0] === 'turn/start') { + await reply.promise + } + return response + } + try { + expect(await sendUserMessage(identity.sessionId, 'go')).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + worker.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + await sendTo(firstDispatchId, 'and the docs') + // The mail waits as a card behind the running turn; the worker reports before it is handed over. + await vi.waitFor( + async () => expect(await queuedCardTexts(identity.sessionId)).toHaveLength(1), + WAIT + ) + expect(worker.steers).toEqual([]) - expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ - ok: true - }) - // The follow-up took the mail: the old card is gone, its Task waits first, then the mail itself. - await vi.waitFor(async () => { - const cards = await queuedCardTexts(identity.sessionId) - expect(cards).toHaveLength(2) - expect(cards[0]).toContain('arrive next, one at a time') - expect(isWholeMail(cards[1]!)).toBe(true) - expect(cards[1]).toContain('and the docs') - }, WAIT) - expect((await queuedCardTexts(identity.sessionId)).join('\n')).not.toContain('`check`') - worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) - await host.flushStreamedEvents(identity.sessionId) - await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) - expect(turnText(worker.turns[1]!)).toContain('arrive next, one at a time') - await settleTurn(identity.sessionId, 1) - await vi.waitFor(() => expect(worker.turns).toHaveLength(3), WAIT) - expect(isWholeMail(turnText(worker.turns[2]!))).toBe(true) - expect(turnText(worker.turns[2]!)).toContain('and the docs') - await settleTurn(identity.sessionId, 2) + expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ + ok: true + }) + // The follow-up took the mail: the old card is gone, its Task waits first, then the mail itself. + await vi.waitFor(async () => { + const cards = await queuedCardTexts(identity.sessionId) + expect(cards).toHaveLength(2) + expect(cards[0]).toContain('arrive next, one at a time') + expect(isWholeMail(cards[1]!)).toBe(true) + expect(cards[1]).toContain('and the docs') + }, WAIT) + expect((await queuedCardTexts(identity.sessionId)).join('\n')).not.toContain('`check`') + reply.resolve() + worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) + expect(turnText(worker.turns[1]!)).toContain('arrive next, one at a time') + await settleTurn(identity.sessionId, 1) + await vi.waitFor(() => expect(worker.turns).toHaveLength(3), WAIT) + expect(isWholeMail(turnText(worker.turns[2]!))).toBe(true) + expect(turnText(worker.turns[2]!)).toContain('and the docs') + await settleTurn(identity.sessionId, 2) - const followUp = getFollowUpDispatch(db, firstDispatchId)! - await vi.waitFor( - () => expect(db.getUnreadMessages(`dispatch:${followUp.id}`)).toEqual([]), - WAIT - ) - expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toEqual([]) + const followUp = getFollowUpDispatch(db, firstDispatchId)! + await vi.waitFor( + () => expect(db.getUnreadMessages(`dispatch:${followUp.id}`)).toEqual([]), + WAIT + ) + expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toEqual([]) + } finally { + reply.resolve() + } }) }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start.test.ts index 2056a53ba65..09f7caaa4ee 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start.test.ts @@ -21,7 +21,7 @@ import { turnText } from './structured-chat-coordinator-mail-rig.test-fixture' -import type { placeWorkerAgent } from '../../../rpc/methods/orchestration/worker/worker-start-agent-placement' +import type { placeWorkerAgent } from '../../../rpc/methods/orchestration/worker/start/placement/worker-start-agent-placement' type WorkspaceLookup = { showManagedTerminalWorkspace: ( diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-cleared-session.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-cleared-session.test.ts index dfdee2f10cd..26278fc62d4 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-cleared-session.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-cleared-session.test.ts @@ -31,10 +31,13 @@ const { structuredSessionMailTarget } = await import('../../mailbox/routing/structured-session-mail-target') const { structuredSessionMailReach } = await import('../../mailbox/routing/structured-session-mail-address') -const { stopStructuredWorker, readStructuredWorkerJournal, captureStructuredWorkerArchive } = +const { captureWorkerOutputReference } = + await import('../../workers/archives/worker-output-archive') +const { encodeWorkerOutputCursor } = await import('../../workers/transcripts/worker-output-cursor') +const { stopStructuredWorker, readStructuredWorkerJournal } = await import('../../../rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle') await import('../../../rpc/methods/orchestration/structured-workers/orchestration-structured-worker-session') -await import('../../../rpc/methods/orchestration/worker/worker-observation') +await import('../../../rpc/methods/orchestration/worker/observation/worker-observation') await import('../../addressing/groups/structured-worker-group-addressing') const { readStructuredLineageJournalPage, STRUCTURED_JOURNAL_PAGE_LIMIT } = await import('../../workers/archives/structured-worker-journal-page') @@ -367,19 +370,20 @@ describe.each(['live', 'at-rest'] as const)( expect(lines.indexOf('POST-CLEAR')).toBeGreaterThan(lines.indexOf('PRE-CLEAR')) }) - it('freezes the whole conversation into the release archive', async () => { - const archive = await captureStructuredWorkerArchive(registerWorker(), 'claude') - const frozen = texts(archive.messages) - expect(frozen.indexOf('PRE-CLEAR')).toBeGreaterThan(-1) - expect(frozen.indexOf('POST-CLEAR')).toBeGreaterThan(frozen.indexOf('PRE-CLEAR')) - }) - - it("retains the worker when the successor's journal cannot be read", async () => { - unreadable.add(SUCCESSOR) + it('reads the whole conversation from its chat once released, keeping no copy', async () => { + const dispatchId = startWorkerDispatch(db, registerWorker()) + await expect(releaseSucceeded(dispatchId)).resolves.toMatchObject({ state: 'released' }) + const read = await rpcRuntime(db).call('orchestration.workerRead', { dispatch: dispatchId }) + expect(read).toMatchObject({ source: 'transcript', archived: true }) + const history = JSON.stringify(read) + expect(history.indexOf('PRE-CLEAR')).toBeGreaterThan(-1) + expect(history.indexOf('POST-CLEAR')).toBeGreaterThan(history.indexOf('PRE-CLEAR')) + expect(db.getWorkerTerminalArchive(dispatchId)?.content).not.toContain('CLEAR') + // A cursor refusal keeps its own code; it never reads as lost output. + const foreign = encodeWorkerOutputCursor('ctx_other', 'transcript', 'identity', 1) await expect( - captureStructuredWorkerArchive(registerWorker(), 'claude') - ).rejects.toMatchObject({ code: 'archive_failed' }) - expect(historyAsked).toEqual([SUCCESSOR]) + rpcRuntime(db).call('orchestration.workerRead', { dispatch: dispatchId, cursor: foreign }) + ).rejects.toMatchObject({ code: 'cursor_dispatch_mismatch' }) }) it('stops the worker by closing the successor, and can then release it', async () => { @@ -551,31 +555,27 @@ describe('worker-stop on a structured worker that reads exited without any /clea }) }) -describe.each([ - { clears: 1, warning: /latest session .* could not be preserved; earlier sessions were/ }, - { clears: 2, warning: /latest 2 sessions .* could not be preserved; earlier sessions were/ } -])('a retired lineage of $clears clear(s) whose later sessions cannot be read', (lineage) => { - beforeEach(() => { - // The user closed the cleared chat, and every journal after the first is gone. - const later = lineage.clears === 1 ? [SUCCESSOR] : [SUCCESSOR, SECOND] - const newest = later.at(-1) ?? SUCCESSOR - const chain = lineage.clears === 1 ? [] : [clearedRecord(SUCCESSOR, SECOND)] - installSessions([clearedRecord(MINTED, SUCCESSOR), ...chain, foundedRecord(newest)], []) - later.forEach((sessionId) => unreadable.add(sessionId)) - }) +describe.each([{ clears: 1 }, { clears: 2 }])( + 'a retired lineage of $clears clear(s) whose later sessions cannot be read', + (lineage) => { + beforeEach(() => { + // The user closed the cleared chat, and every journal after the first is gone. + const later = lineage.clears === 1 ? [SUCCESSOR] : [SUCCESSOR, SECOND] + const newest = later.at(-1) ?? SUCCESSOR + const chain = lineage.clears === 1 ? [] : [clearedRecord(SUCCESSOR, SECOND)] + installSessions([clearedRecord(MINTED, SUCCESSOR), ...chain, foundedRecord(newest)], []) + later.forEach((sessionId) => unreadable.add(sessionId)) + }) - it('archives the readable earliest session and says how many later ones were lost', async () => { - const archive = await captureStructuredWorkerArchive(registerWorker(), 'claude') - expect(texts(archive.messages)).toContain('PRE-CLEAR') - expect(archive.warnings.join(' ')).toMatch(lineage.warning) - }) - - it('commits that archive when the worker is released', async () => { - const dispatchId = startWorkerDispatch(db, registerWorker()) - await expect(releaseSucceeded(dispatchId)).resolves.toMatchObject({ state: 'released' }) - expect(db.getWorkerTerminalArchive(dispatchId)?.content).toContain('PRE-CLEAR') - }) -}) + it('releases, then says the output is no longer available instead of reading nothing', async () => { + const dispatchId = startWorkerDispatch(db, registerWorker()) + await expect(releaseSucceeded(dispatchId)).resolves.toMatchObject({ state: 'released' }) + await expect( + rpcRuntime(db).call('orchestration.workerRead', { dispatch: dispatchId }) + ).rejects.toMatchObject({ code: 'archive_unavailable' }) + }) + } +) describe('the worker-read cursor across a /clear', () => { it('stays valid: what the caller already read did not change, the successor follows it', async () => { @@ -635,9 +635,14 @@ describe('a worker cleared twice', () => { describe('a running session that cannot be verified is refused, never declared exited', () => { async function expectRefused(identity: ReturnType, code: string) { await expect(readJournal(identity)).rejects.toMatchObject({ code }) - await expect(captureStructuredWorkerArchive(identity, 'claude')).rejects.toMatchObject({ - code - }) + expect(() => + captureWorkerOutputReference({ + runtime: { getExactWorkerProviderSession: () => null }, + terminalHandle: identity.handle, + attachedAtMs: 0, + structuredWorker: identity + }) + ).toThrow(expect.objectContaining({ code })) await expect( readStructuredWorkerTerminal({ handle: identity.handle, db: null }) ).rejects.toMatchObject({ code }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.test.ts deleted file mode 100644 index 669972dc427..00000000000 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from 'vitest' -import '../../../orca-runtime-tests/runtime-test-module-registration.spec' -import { createRuntime } from '../../../orca-runtime-tests/orca-runtime-test-fixtures.spec' - -const CHAT = 'orca_session_id:0f9c2f6e-6c1b-4f5e-9d8a-2b7f3c4d5e6f' - -describe('terminal commands addressed to a chat', () => { - it('refuses read and send as a chat session instead of a stale terminal handle', async () => { - const runtime = createRuntime() - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - const refusal = { - code: 'terminal_unsupported_for_agent_session', - message: expect.stringContaining(`orca orchestration send --to ${CHAT}`) - } - - await expect(runtime.readTerminal(CHAT)).rejects.toMatchObject(refusal) - await expect( - runtime.sendTerminal(CHAT, { text: 'hi', enter: true }, { inputKind: 'driving' }) - ).rejects.toMatchObject(refusal) - }) -}) diff --git a/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-prompt.ts b/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-prompt.ts index 1d44a3a0656..6463936c999 100644 --- a/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-prompt.ts +++ b/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-prompt.ts @@ -55,16 +55,27 @@ export type ChatWorkerApprovalAnswer = | { ok: true; prompt: ChatWorkerPrompt; optionLabel: string } | { ok: false - code: 'approval_not_open' | 'approval_option_missing' | 'approval_refused' + code: + | 'approval_not_open' + | 'approval_option_missing' + | 'approval_refused' + | 'approval_requires_person' message: string } +/** Why an agent's allow was refused: the worker's own agent says only a person may approve it. */ +export function personOnlyMessage(approvalId: string): string { + return `The worker's agent lets only a person approve ${approvalId}, so it stays with the user. You can deny it with a reason, or leave it.` +} + /** Answer as Orca with the one option the decision may pick; the chat checks the revision it read. */ export async function answerChatWorkerApproval(input: { sessionId: string approvalId: string dispatchId: string decision: WorkerApprovalDecision + /** An agent answers for the coordinator: the agent's person-only prompts stay with the person. */ + byAgent?: boolean readPrompt?: ChatWorkerPromptReader }): Promise { const { sessionId, approvalId, decision } = input @@ -85,6 +96,11 @@ export async function answerChatWorkerApproval(input: { if (!prompt) { return notOpen } + // A prompt answered meanwhile is not open, whoever may answer it. + const open = prompt.body.resolution.state === 'pending' + if (open && decision === 'allow' && input.byAgent && prompt.body.personOnly) { + return { ok: false, code: 'approval_requires_person', message: personOnlyMessage(approvalId) } + } const option = workerApprovalOption(prompt.body.options, decision) if (!option) { return { diff --git a/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-watch.ts b/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-watch.ts index ed5e64168c3..58f60740756 100644 --- a/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-watch.ts +++ b/src/main/runtime/orchestration/workers/approvals/chat-worker-approval-watch.ts @@ -37,10 +37,25 @@ export class ChatWorkerApprovalWatch { private readonly deps: Pick & { readPrompt?: ChatWorkerPromptReader watchJournal?: ChatJournalWatch + signal: AbortSignal } - ) {} + ) { + deps.signal.addEventListener( + 'abort', + () => { + for (const session of this.sessions.values()) { + session.stop() + } + this.sessions.clear() + }, + { once: true } + ) + } track(sessionId: string, approvalId: string, dispatchId: string): void { + if (this.deps.signal.aborted) { + return + } let session = this.sessions.get(sessionId) if (!session) { const approvals = new Map>() @@ -57,6 +72,10 @@ export class ChatWorkerApprovalWatch { }) ) } + if (this.deps.signal.aborted) { + session.stop() + return + } this.sessions.set(sessionId, session) } const dispatchIds = session.approvals.get(approvalId) ?? new Set() @@ -66,7 +85,7 @@ export class ChatWorkerApprovalWatch { async check(sessionId: string): Promise { const session = this.sessions.get(sessionId) - if (!session) { + if (!session || this.deps.signal.aborted) { return } for (const [approvalId, dispatchIds] of session.approvals) { @@ -75,6 +94,9 @@ export class ChatWorkerApprovalWatch { sessionId, approvalId ).catch(() => undefined) + if (this.deps.signal.aborted) { + return + } if (prompt === undefined || prompt?.body.resolution.state === 'pending') { continue } @@ -86,6 +108,9 @@ export class ChatWorkerApprovalWatch { } if (outcome && db) { for (const dispatchId of dispatchIds) { + if (this.deps.signal.aborted) { + return + } const dispatch = db.getDispatchContextById(dispatchId) if (!dispatch || closeReportedApproval(db, dispatch, approvalId, outcome, this.deps)) { dispatchIds.delete(dispatchId) @@ -104,9 +129,15 @@ export class ChatWorkerApprovalWatch { /** After a restart, picks up approvals reported open whose closing line never came. */ async adopt(): Promise { + if (this.deps.signal.aborted) { + return + } const db = this.deps.getDb() const sessions = new Set() for (const { approval, dispatch } of db ? recentOpenApprovalReports(db) : []) { + if (this.deps.signal.aborted) { + return + } const { approvalId } = approval if ( !db || diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts index c1d9750a09e..6c857918d40 100644 --- a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts +++ b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-hold.ts @@ -4,9 +4,10 @@ import type { OrchestrationDb } from '../../db/orchestration-db' import type { DispatchContextRow } from '../../db/orchestration-records' import type { WorkerTurnStopReportDeps } from '../turn-stops/worker-turn-stop-report' import type { ClaudeToolRecord } from './claude-tool-result-close' -import type { - WorkerApprovalOutcome, - WorkerApprovalPayload +import { + closedApproval, + type WorkerApprovalOutcome, + type WorkerApprovalPayload } from '../../../../../shared/orchestration/approvals/worker-approval-payload' export type TerminalWorkerApprovalHoldsDeps = Pick & { @@ -50,11 +51,59 @@ export type TerminalWorkerApprovalHold = { expiresAt?: string /** The coordinator was told about it, so it is owed one closing line. */ reported: boolean + /** How Orca closed it, once closed other than by its own answer. */ + closedAs?: TerminalWorkerApprovalCloseHow | null timer: { cancel: () => void } | null } export type TerminalWorkerApprovalCloseHow = Pick +// Claude's words for a check no hook may approve (2.1.322 strings: "allow rules, hooks and plugins +// cannot approve it", "hooks cannot approve …"); its dialog shows them as the warning. +const HOOKS_CANNOT_APPROVE = /\bhooks\b[^.]*\bcannot (?:approve|grant)\b/i + +/** Claude lets only a person at its terminal allow this prompt. */ +export function holdIsPersonOnly(hold: Pick): boolean { + return HOOKS_CANNOT_APPROVE.test(hold.summary.reason ?? '') +} + +/** An allow Claude will not take: its check is one only a person at the terminal may approve, or it + * dropped Orca's allow and still asks. */ +export function droppedAllowRefusal( + hold: TerminalWorkerApprovalHold, + input: { approvalId: string; decision: 'allow' | 'deny' } +): TerminalWorkerApprovalAnswer | null { + if ( + input.decision !== 'allow' || + (hold.closedAs?.by !== 'terminal-only' && !holdIsPersonOnly(hold)) + ) { + return null + } + return { + ok: false, + code: 'approval_requires_person', + message: `Claude lets only a person approve ${input.approvalId}, in the worker's terminal, so it stays with the user.` + } +} + export type TerminalWorkerApprovalAnswer = | { ok: true; approval: WorkerApprovalPayload } - | { ok: false; code: 'approval_not_open'; message: string } + | { ok: false; code: 'approval_not_open' | 'approval_requires_person'; message: string } + +/** The approval as its escalation and closing message carry it. */ +export function holdPayload( + hold: TerminalWorkerApprovalHold, + outcome?: WorkerApprovalOutcome +): WorkerApprovalPayload { + const open: WorkerApprovalPayload = { + v: 1, + approvalId: hold.approvalId, + state: 'open', + worker: { handle: hold.handle, dispatchId: hold.dispatch.id, taskId: hold.dispatch.task_id }, + summary: hold.summary, + allowedActions: ['allow', 'deny'], + ...(holdIsPersonOnly(hold) ? { personOnly: true } : {}), + ...(hold.expiresAt ? { expiresAt: hold.expiresAt } : {}) + } + return outcome ? closedApproval(open, outcome) : open +} diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts index 16fc46dbd99..d2fff4793a5 100644 --- a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts +++ b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.test.ts @@ -147,10 +147,17 @@ function postToolUse(toolUseId: string): AgentHookEventPayload { } } +/** Takes the open approval and marks its escalation sent, as the turn-stop report does. */ +async function escalated(ctx: ReturnType) { + const approval = (await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id))! + ctx.holds.markReported(approval.approvalId) + return approval +} + async function opened(ctx: ReturnType, asked: ReturnType) { ctx.holds.admit(asked.request) await ctx.tick() - return (await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id))!.approvalId + return (await escalated(ctx)).approvalId } const answer = ( @@ -219,6 +226,64 @@ describe('terminal worker approval holds', () => { expect(ctx.closedWith()[0]).toMatchObject({ state: 'answered', by: 'unknown' }) }) + it('marks a check Claude lets no hook approve as person-only, and refuses an allow without spending the hook', async () => { + const ctx = setup() + ctx.screen.lines = [ + ' Bash command', + ' │ rm -rf build', + ' ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌', + " │ Bash may act on this session's desktop, so each call is reviewed; allow rules, hooks and plugins cannot approve it.", + ...DIALOG.slice(3) + ] + const asked = hook('tool-1', () => { + ctx.screen.lines = AFTER + ctx.screen.record = record(OURS, 'deny') + }) + ctx.holds.admit(asked.request) + await ctx.tick() + const approval = await escalated(ctx) + const approvalId = approval.approvalId + + expect(approval).toMatchObject({ personOnly: true }) + expect(await answer(ctx, approvalId, 'allow')).toMatchObject({ + ok: false, + code: 'approval_requires_person' + }) + expect(asked.replies).toEqual([]) + expect(await deny(ctx, approvalId)).toMatchObject({ ok: true }) + }) + + it('refuses an allow on a person-only check whose warning painted only after the escalation', async () => { + const ctx = setup() + const asked = hook('tool-1') + const approvalId = await opened(ctx, asked) + ctx.screen.lines = [ + ' Bash command', + ' │ rm -rf build', + ' ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌', + " │ Bash may act on this session's desktop, so each call is reviewed; allow rules, hooks and plugins cannot approve it.", + ...DIALOG.slice(3) + ] + + expect(await answer(ctx, approvalId, 'allow')).toMatchObject({ + code: 'approval_requires_person' + }) + expect(asked.replies).toEqual([]) + }) + + it('refuses an allow Claude drops while its dialog stays, and leaves the prompt with the person', async () => { + const ctx = setup() + // A check only a person may approve: Claude ignores a hook's allow and keeps asking. + const approvalId = await opened(ctx, hook('tool-1')) + const answering = answer(ctx, approvalId, 'allow') + await ctx.tick(40) + + expect(await answering).toMatchObject({ ok: false, code: 'approval_requires_person' }) + expect(ctx.closedWith()).toEqual([ + expect.objectContaining({ by: 'terminal-only', decision: null }) + ]) + }) + it("doesn't take Orca's allow when the person's No won the race", async () => { const ctx = setup() const approvalId = await opened( @@ -241,68 +306,12 @@ describe('terminal worker approval holds', () => { ]) }) - it("tells the coordinator to send the user to the terminal when the hook is gone but the dialog isn't", async () => { - const ctx = setup() - const asked = hook('tool-1') - await opened(ctx, asked) - asked.end('hook-gone') - await ctx.tick(40) - - expect(ctx.closings()).toEqual([ - expect.objectContaining({ - type: 'escalation', - body: expect.stringContaining("Tell the user to answer it in the worker's terminal") - }) - ]) - }) - - it('closes as worker ended, not "answer it in the terminal", when the worker is stopped at the prompt', async () => { - const ctx = setup() - const asked = hook('tool-1') - await opened(ctx, asked) - // A stop kills the process; its last screen still shows the dialog. - ctx.screen.incarnation = 'run-2' - asked.end('hook-gone') - await ctx.tick(40) - - expect(ctx.closedWith()).toEqual([ - { - state: 'answered', - by: 'worker-ended', - decision: null, - reason: null, - reasonDelivered: false - } - ]) - }) - - it("escalates with Claude's reason once the dialog paints, though a long command hides its box's top", async () => { - const ctx = setup() - // The live case (2026-11-11): the escalation came before the paint, and the command was so long - // that only the rule closing its box was on screen. - ctx.screen.lines = null - ctx.holds.admit(hook('tool-1').request) - const escalating = ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id) - ctx.screen.lines = [ - ...Array.from({ length: 30 }, (_, line) => ` │ s=s.replace("import ${line}")`), - ' │ fs.writeFileSync(p,s)\'; rg -n "ComputerBots" BotSettingsGroups.tsx', - ' ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌', - ' │ Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed', - ...DIALOG.slice(2) - ] - await ctx.tick(2) - - expect((await escalating)?.summary.reason).toBe( - 'Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed' - ) - }) - it('owes no closing line to a prompt whose escalation never went out', async () => { const ctx = setup() const asked = hook('tool-1') ctx.holds.admit(asked.request) - // The worker resumed while the escalation waited for the dialog, so no report was sent. - expect(await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id, () => false)).toBeNull() + // Taken, but the turn-stop report never sent it, so it is never marked reported. + expect(await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id)).not.toBeNull() asked.end('hook-gone') await ctx.tick(40) @@ -312,7 +321,7 @@ describe('terminal worker approval holds', () => { it('closes a prompt left open by an earlier run, once, when the database opens', async () => { const ctx = setup() ctx.holds.admit(hook('tool-1').request) - const approval = (await ctx.holds.takeOpenApproval(PANE, ctx.dispatch.id))! + const approval = await escalated(ctx) const escalate = (id: string | undefined, carried: typeof approval) => ctx.db.insertMessage({ ...(id ? { id } : {}), diff --git a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts index 6ae36876c4f..d4cd680aeb7 100644 --- a/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts +++ b/src/main/runtime/orchestration/workers/approvals/terminal-worker-approval-holds.ts @@ -19,18 +19,18 @@ import { type ClaudeToolRecord } from './claude-tool-result-close' import { firstWithin } from './first-within' -import type { - TerminalWorkerApprovalAnswer, - TerminalWorkerApprovalCloseHow, - TerminalWorkerApprovalHold, - TerminalWorkerApprovalHoldsDeps +import { + droppedAllowRefusal, + holdPayload, + type TerminalWorkerApprovalAnswer, + type TerminalWorkerApprovalCloseHow, + type TerminalWorkerApprovalHold, + type TerminalWorkerApprovalHoldsDeps } from './terminal-worker-approval-hold' import { reportWorkerApprovalClosed } from '../turn-stops/worker-turn-stop-report' -import { - closedApproval, - type WorkerApprovalDecision, - type WorkerApprovalOutcome, - type WorkerApprovalPayload +import type { + WorkerApprovalDecision, + WorkerApprovalPayload } from '../../../../../shared/orchestration/approvals/worker-approval-payload' import { TERMINAL_APPROVAL_ID_PREFIX } from './worker-approval-report' @@ -137,17 +137,22 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { } /** The open approval this pane's worker waits on, for its one escalation. */ + /** Its escalation went out, so its close owes the coordinator one closing line. */ + markReported(approvalId: string): void { + const hold = this.byApprovalId.get(approvalId) + if (hold) { + hold.reported = true + } + } + /** Whether Orca still holds this prompt's hook, answering or not. */ isHeld(approvalId: string): boolean { return this.byApprovalId.has(approvalId) } - /** `reporting`: whether the caller still sends its report, read last, so a close owes a closing - * line only to an approval whose escalation went out. */ async takeOpenApproval( paneKey: string, - dispatchId: string, - reporting: () => boolean = () => true + dispatchId: string ): Promise { const hold = this.openByPane.get(paneKey) if (hold?.state !== 'open' || hold.dispatch.id !== dispatchId) { @@ -158,12 +163,11 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { const screen = this.deps.readScreen(paneKey) return screen && showsClaudeDialog(screen) ? screen : null }) - if (hold.state !== 'open' || this.openByPane.get(paneKey) !== hold || !reporting()) { + if (hold.state !== 'open' || this.openByPane.get(paneKey) !== hold) { return null } - hold.reported = true this.readDialog(hold, lines) - return this.payload(hold) + return holdPayload(hold) } /** Writes a decision only to a dialog still on a caught-up screen, and claims it only once this @@ -188,6 +192,12 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { if (hold.state !== 'open' || !before || !showsClaudeDialog(before)) { return notOpen } + // The escalation can go out before Claude paints its warning: read it from this screen too. + this.readDialog(hold, before) + const personOnly = droppedAllowRefusal(hold, input) + if (personOnly) { + return personOnly + } hold.state = 'answering' hold.timer?.cancel() const written = await hold.channel.answer( @@ -203,11 +213,11 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { hold.state = 'open' await this.settle(hold, record) } - return notOpen + return droppedAllowRefusal(hold, input) ?? notOpen } hold.state = 'answered' this.release(hold) - return { ok: true, approval: this.payload(hold) } + return { ok: true, approval: holdPayload(hold) } } private watchDialog(hold: Hold): void { @@ -285,6 +295,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { return } hold.state = 'closed' + hold.closedAs = how this.release(hold) this.closingByToolUseId.delete(hold.toolUseId) void hold.channel.answer(null) @@ -299,7 +310,7 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { hold.dispatch, { from: hold.handle, - approval: this.payload(hold, { + approval: holdPayload(hold, { by: how?.by ?? 'unknown', decision: how?.decision ?? null, reason: null, @@ -333,17 +344,4 @@ export class TerminalWorkerApprovalHolds implements ClaudePermissionHolds { private toolRecord(hold: Hold): Promise { return firstWithin(this.deps.setTimer, () => this.deps.readToolRecord(hold)) } - - private payload(hold: Hold, outcome?: WorkerApprovalOutcome): WorkerApprovalPayload { - const open: WorkerApprovalPayload = { - v: 1, - approvalId: hold.approvalId, - state: 'open', - worker: { handle: hold.handle, dispatchId: hold.dispatch.id, taskId: hold.dispatch.task_id }, - summary: hold.summary, - allowedActions: ['allow', 'deny'], - ...(hold.expiresAt ? { expiresAt: hold.expiresAt } : {}) - } - return outcome ? closedApproval(open, outcome) : open - } } diff --git a/src/main/runtime/orchestration/workers/approvals/worker-approval.ts b/src/main/runtime/orchestration/workers/approvals/worker-approval.ts index 39ae9eb75dd..be21e730ab3 100644 --- a/src/main/runtime/orchestration/workers/approvals/worker-approval.ts +++ b/src/main/runtime/orchestration/workers/approvals/worker-approval.ts @@ -13,17 +13,19 @@ import { type WorkerApprovalPayload } from '../../../../../shared/orchestration/approvals/worker-approval-payload' -/** The outcome of a chat prompt Orca answered: its reason is told only when it went to the worker as mail. */ +/** The outcome of a chat prompt Orca answered: a deny's reason is told only when it went to the + * worker as mail; a coordinator's allow keeps its reason for the receipt. */ export function chatAnswerOutcome(input: { by: WorkerApprovalAnswerer decision: WorkerApprovalDecision reason: string | null reasonMailed: boolean }): WorkerApprovalOutcome { + const kept = input.decision === 'allow' ? input.by === 'coordinator' : input.reasonMailed return { by: input.by, decision: input.decision, - reason: input.reasonMailed ? input.reason : null, + reason: kept ? input.reason : null, reasonDelivered: false } } @@ -87,7 +89,8 @@ export function workerApprovalPayload(input: { detail, reason: item.decisionReason ?? null }, - allowedActions: workerApprovalActions(item.options) + allowedActions: workerApprovalActions(item.options), + ...(item.personOnly ? { personOnly: true } : {}) } return outcome ? closedApproval(open, outcome) : open } diff --git a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.test.ts b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.test.ts index d27c840f799..41de11d1670 100644 --- a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.test.ts +++ b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import { buildStructuredJournalArchive } from './structured-worker-journal-archive' +import { boundStructuredJournalTail } from './structured-worker-journal-archive' import { foldToolMessages } from '../../../../../shared/native-chat/tools/native-chat-tool-fold' import { pairToolBlocks } from '../../../../../shared/native-chat/tools/native-chat-tool-pairs' @@ -28,16 +28,9 @@ function longJournal(count: number): AgentJournalRenderItem[] { ) } -function archive(items: AgentJournalRenderItem[], hasOlder = false) { - return buildStructuredJournalArchive({ - agent: 'claude', - processIncarnation: 'structured:session-1', - items, - hasOlder - }) -} +const archive = boundStructuredJournalTail -describe('buildStructuredJournalArchive', () => { +describe('boundStructuredJournalTail', () => { it('keeps the worker final answer when the journal exceeds the bound', () => { // Forward bounding keeps early exploration; archive tail bounding must retain the final answer. const items = longJournal(200) diff --git a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.ts b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.ts index 95bb26100e1..d78396dabab 100644 --- a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.ts +++ b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-archive.ts @@ -1,19 +1,12 @@ -/** Archive structured journals as transcript-shaped evidence with session identity, rather than pretending a PTY or file exists. */ +/** Bound a structured journal as transcript-shaped output for the terminal view of a structured worker. */ import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' import { projectStructuredItemsToNativeChat } from '../../../../../shared/agent-session/view/structured-agent-session-projection' import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' import { boundWorkerTranscriptTail } from '../transcripts/worker-transcript-payload' -import { - readRetiredLineageJournalPage, - readStructuredLineageJournalPage, - type StructuredLineageJournalPage -} from './structured-worker-journal-page' - -// Same durable bound the terminal archive uses; a session journal can grow without limit. -const STRUCTURED_ARCHIVE_MAX_BYTES = 262_144 +/** A chat worker's output copy, saved by releases before references. */ export type WorkerStructuredJournalArchive = { version: 1 agent: AgentType @@ -23,6 +16,9 @@ export type WorkerStructuredJournalArchive = { warnings: string[] } +// A session journal can grow without limit. +const STRUCTURED_ARCHIVE_MAX_BYTES = 262_144 + /** Redact and bound newest-first so final answers survive; forward wire bounding first would discard them. */ export function boundStructuredJournalTail(items: readonly AgentJournalRenderItem[]): { messages: NativeChatMessage[] @@ -34,71 +30,3 @@ export function boundStructuredJournalTail(items: readonly AgentJournalRenderIte STRUCTURED_ARCHIVE_MAX_BYTES ) } - -/** Page a lineage back until the archive's byte bound fills, not just the newest history page. */ -export function readStructuredLineageArchiveJournal( - lineage: readonly string[] -): Promise { - return readStructuredLineageJournalPage(lineage, archiveBoundFilled) -} - -function archiveBoundFilled(items: readonly AgentJournalRenderItem[]): boolean { - return boundStructuredJournalTail(items).limited -} - -export function buildStructuredJournalArchive(input: { - agent: AgentType - processIncarnation: string - items: readonly AgentJournalRenderItem[] - hasOlder: boolean -}): WorkerStructuredJournalArchive { - const bounded = boundStructuredJournalTail(input.items) - const warnings = [...bounded.warnings] - if (input.hasOlder) { - warnings.push('Older journal items were omitted from the bounded archive.') - } - if (bounded.limited) { - warnings.push('The oldest archived journal messages were dropped to fit the size bound.') - } - return { - version: 1, - agent: input.agent, - processIncarnation: input.processIncarnation, - messages: bounded.messages, - limited: bounded.limited || input.hasOlder, - warnings - } -} - -/** - * The archive of a retired lineage whose running session cannot be read: what the latest readable - * sessions still hold, saying how many later sessions were lost. - */ -export async function captureRetiredLineageArchive(input: { - agent: AgentType - processIncarnation: string - lineage: readonly string[] -}): Promise { - const { page, unreadable } = await readRetiredLineageJournalPage( - input.lineage, - archiveBoundFilled - ) - const archive = buildStructuredJournalArchive({ - agent: input.agent, - processIncarnation: input.processIncarnation, - items: page?.items ?? [], - hasOlder: page?.hasOlder ?? false - }) - return { ...archive, warnings: [...archive.warnings, closedSessionsWarning(unreadable, !!page)] } -} - -function closedSessionsWarning(unreadable: number, earlierPreserved: boolean): string { - if (!earlierPreserved) { - return unreadable > 1 - ? `None of this conversation's ${unreadable} sessions could be read, so its journal could not be preserved.` - : 'The structured session was already closed, so its journal could not be preserved.' - } - return unreadable > 1 - ? `The latest ${unreadable} sessions of this conversation were already closed, so their journals could not be preserved; earlier sessions were.` - : 'The latest session of this conversation was already closed, so its journal could not be preserved; earlier sessions were.' -} diff --git a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.test.ts b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.test.ts index ed2ed7c5c83..c3e8e31d8a5 100644 --- a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.test.ts +++ b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.test.ts @@ -17,7 +17,6 @@ import { readStructuredJournalPage, STRUCTURED_JOURNAL_PAGE_LIMIT } from './structured-worker-journal-page' -import { readStructuredLineageArchiveJournal } from './structured-worker-journal-archive' import { claudeProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' const host = vi.hoisted(() => { @@ -134,17 +133,4 @@ describe("a worker's journal page", () => { expect(page?.items.at(-1)?.body).toEqual(said(`worker-${STRUCTURED_JOURNAL_PAGE_LIMIT + 4}`)) expect(page?.hasOlder).toBe(true) }) - - it('archives every row that fits the byte bound, not just the newest page', async () => { - for (let index = 0; index < 250; index += 1) { - await append(`worker-${index}`) - } - - const page = await readStructuredLineageArchiveJournal(['session-1']) - - expect(page?.items).toHaveLength(250) - expect(page?.items[0]?.body).toEqual(said('worker-0')) - expect(page?.items.at(-1)?.body).toEqual(said('worker-249')) - expect(page?.hasOlder).toBe(false) - }) }) diff --git a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.ts b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.ts index 7e8de66c652..6fd4889f884 100644 --- a/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.ts +++ b/src/main/runtime/orchestration/workers/archives/structured-worker-journal-page.ts @@ -88,17 +88,3 @@ export async function readStructuredLineageJournalPage( } return { items, sessionIds, hasOlder: false } } - -/** For retired unreadable tails, return the latest readable history and count every skipped session. */ -export async function readRetiredLineageJournalPage( - lineage: readonly string[], - filled?: (items: readonly AgentJournalRenderItem[]) => boolean -): Promise<{ page: StructuredLineageJournalPage | null; unreadable: number }> { - for (let unreadable = 1; unreadable < lineage.length; unreadable += 1) { - const page = await readStructuredLineageJournalPage(lineage.slice(0, -unreadable), filled) - if (page) { - return { page, unreadable } - } - } - return { page: null, unreadable: lineage.length } -} diff --git a/src/main/runtime/orchestration/workers/archives/worker-output-archive-bounding.test.ts b/src/main/runtime/orchestration/workers/archives/worker-output-archive-bounding.test.ts deleted file mode 100644 index f859795eac1..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-output-archive-bounding.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { boundArchiveLines } from './worker-output-archive' - -const TERMINAL_ARCHIVE_MAX_CHARS = 262_144 - -function totalCost(lines: string[]): number { - return lines.reduce((sum, line) => sum + line.length + 1, 0) -} - -describe('boundArchiveLines', () => { - it('keeps the newest lines in order and reports truncation', () => { - const lines = Array.from({ length: 40_000 }, (_, index) => `line ${index}`) - const bounded = boundArchiveLines(lines) - expect(bounded.truncated).toBe(true) - expect(totalCost(bounded.lines)).toBeLessThanOrEqual(TERMINAL_ARCHIVE_MAX_CHARS) - expect(bounded.lines.at(-1)).toBe(lines.at(-1)) - expect(bounded.lines).toEqual(lines.slice(lines.length - bounded.lines.length)) - }) - - it('truncates a single oversized line from its tail', () => { - const bounded = boundArchiveLines(['x'.repeat(TERMINAL_ARCHIVE_MAX_CHARS * 2)]) - expect(bounded.truncated).toBe(true) - expect(bounded.lines).toHaveLength(1) - expect(bounded.lines[0]).toHaveLength(TERMINAL_ARCHIVE_MAX_CHARS - 1) - }) -}) diff --git a/src/main/runtime/orchestration/workers/archives/worker-output-archive.test.ts b/src/main/runtime/orchestration/workers/archives/worker-output-archive.test.ts deleted file mode 100644 index 5cd29e02080..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-output-archive.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import * as workerTranscriptRead from '../transcripts/worker-transcript-read' -import { captureWorkerOutputArchive } from './worker-output-archive' - -function codexMessage(id: string, text: string): string { - return JSON.stringify({ - type: 'event_msg', - payload: { id, type: 'agent_message', message: text } - }) -} - -describe('worker output archive WSL routing', () => { - let directory: string - let transcriptPath: string - let transcriptReadSpy: { mockRestore: () => void } | undefined - - beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'orca-worker-archive-')) - transcriptPath = join(directory, 'session.jsonl') - await writeFile(transcriptPath, `${codexMessage('wsl', 'WSL archive output')}\n`) - }) - - afterEach(async () => { - transcriptReadSpy?.mockRestore() - await rm(directory, { recursive: true, force: true }) - }) - - it('does not resolve an SSH transcript locally', async () => { - transcriptReadSpy = vi.spyOn(workerTranscriptRead, 'readWorkerTranscript') - const runtime = { - getExactWorkerProviderSession: vi.fn(() => ({ - paneKey: 'tab:ssh-worker', - processIncarnation: 'pty:ssh-incarnation', - connectionId: 'ssh:remote-host', - agent: 'codex' as const, - providerSession: { - key: 'session_id', - id: 'ssh-session', - transcriptPath: '/home/ada/.codex/sessions/rollout-ssh.jsonl' - }, - observedAt: Date.now() - })), - readTerminal: vi.fn().mockResolvedValue({ - tail: ['remote worker terminal fallback'], - truncated: false, - status: 'live' - }) - } as unknown as OrcaRuntimeService - - const result = await captureWorkerOutputArchive({ - runtime, - dispatchId: 'dispatch-ssh', - terminalHandle: 'term-ssh', - attachedAtMs: Date.now() - 1 - }) - - expect(workerTranscriptRead.readWorkerTranscript).not.toHaveBeenCalled() - expect(result).toMatchObject({ - kind: 'terminal_tail', - status: 'captured', - content: { - lines: ['remote worker terminal fallback'], - fallbackReason: 'remote_capability_unavailable', - warnings: expect.arrayContaining([ - 'The terminal read did not identify an authoritative screen; available terminal output was preserved.', - 'Terminal wrap information was unavailable; capability masking used complete lines.' - ]) - } - }) - }) -}) diff --git a/src/main/runtime/orchestration/workers/archives/worker-output-archive.ts b/src/main/runtime/orchestration/workers/archives/worker-output-archive.ts index 19b4c7c7a38..d6278cf9ab3 100644 --- a/src/main/runtime/orchestration/workers/archives/worker-output-archive.ts +++ b/src/main/runtime/orchestration/workers/archives/worker-output-archive.ts @@ -1,26 +1,39 @@ import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import type { OrchestrationWorkerReadFallbackReason } from '../../../../../shared/orchestration/workers/orchestration-worker-output' +import type { WorkerStructuredJournalArchive } from './structured-worker-journal-archive' +import { canReadWorkerTranscript } from '../transcripts/worker-transcript-read' +import { + ORCHESTRATION_WORKER_READ_FALLBACK_REASONS, + type ExactWorkerProviderSession, + type OrchestrationWorkerReadFallbackReason +} from '../../../../../shared/orchestration/workers/orchestration-worker-output' +import { isWslHookRelayConnectionId } from '../../../../../shared/wsl-hook-relay-contract' import type { WorkerTerminalReleaseRuntime } from '../../terminal-authority/release/worker-terminal-release-runtime' -import { OrchestrationError } from '../../orchestration-error' import type { WorkerTerminalArchiveKind, WorkerTerminalArchiveRow, WorkerTerminalArchiveStatus } from '../../terminal-authority/release/worker-terminal-ownership' -import { MAX_WORKER_TRANSCRIPT_MESSAGE_LIMIT } from '../transcripts/worker-transcript-payload' -import { redactWorkerTerminalLines } from '../../terminal-authority/views/worker-terminal-redaction' -import { readWorkerTranscript } from '../transcripts/worker-transcript-read' -import { isWslHookRelayConnectionId } from '../../../../../shared/wsl-hook-relay-contract' -import { captureStructuredWorkerArchive } from '../../../rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle' -import type { WorkerStructuredJournalArchive } from './structured-worker-journal-archive' -import { structuredWorkerAgent } from '../../terminal-authority/structured-sessions/structured-worker-authority' +import { + requireRunningStructuredWorker, + structuredWorkerAgent +} from '../../terminal-authority/structured-sessions/structured-worker-authority' import type { StructuredWorkerIdentity } from '../../terminal-authority/structured-sessions/structured-worker-identity' -import { readWorkerTerminalArchive } from './worker-terminal-archive-read' -// Bound the durable copy of raw terminal output; the tail end is the evidence that matters. -const TERMINAL_ARCHIVE_MAX_CHARS = 262_144 +/** Where a released worker's output still lives; readers open the original, never a saved copy. */ +export type WorkerOutputReference = { + version: 3 + agent?: AgentType + processIncarnation?: string + /** The provider transcript a terminal worker's reader opens. */ + sessionId?: string + transcriptPath?: string + wslDistro?: string + /** Why a terminal worker left no transcript to read. */ + fallbackReason?: OrchestrationWorkerReadFallbackReason +} +/** Output copies saved by releases before references; their rows stay readable as they were. */ export type WorkerTranscriptSnapshotArchive = { version: 2 agent: AgentType @@ -42,169 +55,157 @@ export type WorkerTerminalTailArchive = { clipping?: string[] } -export type WorkerOutputArchiveCapture = - | { - kind: 'transcript_pin' - content: WorkerTranscriptSnapshotArchive - status: 'captured' - } - | { - kind: 'structured_journal' - content: WorkerStructuredJournalArchive - status: 'captured' | 'empty' - } - | { kind: 'terminal_tail'; content: WorkerTerminalTailArchive; status: 'captured' | 'empty' } +/** References serialize `version` first, so this never parses a saved copy. */ +export function isWorkerOutputReference( + archive: Pick +): boolean { + return archive.content.startsWith('{"version":3,') || archive.content === '{"version":3}' +} -export function summarizeWorkerOutputArchive(archive: WorkerTerminalArchiveRow): { +export type WorkerOutputArchiveStatus = Extract< + WorkerTerminalArchiveStatus, + 'captured' | 'unavailable' +> + +export type WorkerOutputArchiveCapture = { + kind: WorkerTerminalArchiveKind + content: WorkerOutputReference + status: WorkerOutputArchiveStatus +} + +/** Record where a worker's output lives before its terminal or session closes. */ +export function captureWorkerOutputReference(args: { + runtime: Pick + terminalHandle: string + attachedAtMs: number + /** Present when the worker IS a structured session; its chat history is its output. */ + structuredWorker?: StructuredWorkerIdentity | null +}): WorkerOutputArchiveCapture { + if (args.structuredWorker) { + // An unverifiable session refuses here, so its release ends release_unknown instead of closing it. + requireRunningStructuredWorker(args.structuredWorker) + return { + kind: 'structured_journal', + status: 'captured', + content: { + version: 3, + agent: structuredWorkerAgent(args.structuredWorker), + processIncarnation: args.structuredWorker.processIncarnation + } + } + } + const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, args.attachedAtMs) + const unreachable = transcriptUnreachableReason(session) + if (!session || unreachable) { + return { + kind: 'terminal_tail', + status: 'unavailable', + content: { version: 3, fallbackReason: unreachable ?? 'session_not_reported' } + } + } + const { transcriptPath } = session.providerSession + return { + kind: 'transcript_pin', + status: 'captured', + content: { + version: 3, + agent: session.agent, + processIncarnation: session.processIncarnation, + sessionId: session.providerSession.id, + ...(transcriptPath ? { transcriptPath } : {}), + ...(session.wslDistro ? { wslDistro: session.wslDistro } : {}) + } + } +} + +function transcriptUnreachableReason( + session: ExactWorkerProviderSession | null +): OrchestrationWorkerReadFallbackReason | null { + if (!session) { + return 'session_not_reported' + } + const isWslSession = isWslHookRelayConnectionId(session.connectionId) + // No SSH filesystem provider is installed, so remote transcripts are unreachable. + if ((isWslSession && !session.wslDistro) || (session.connectionId && !isWslSession)) { + return 'remote_capability_unavailable' + } + // The released read uses the same reader, so record only what it can open. + return canReadWorkerTranscript(session.agent) ? null : 'provider_unsupported' +} + +/** The reference a row holds; check isWorkerOutputReference first. */ +export function readWorkerOutputReference( + archive: WorkerTerminalArchiveRow +): WorkerOutputReference { + let parsed: unknown + try { + parsed = JSON.parse(archive.content) + } catch { + return { version: 3 } + } + const fields = new Map( + typeof parsed === 'object' && parsed !== null ? Object.entries(parsed) : [] + ) + const text = (name: string): string | undefined => { + const value = fields.get(name) + return typeof value === 'string' && value !== '' ? value : undefined + } + const fallbackReason = ORCHESTRATION_WORKER_READ_FALLBACK_REASONS.find( + (reason) => reason === fields.get('fallbackReason') + ) + const reference: WorkerOutputReference = { version: 3 } + for (const name of [ + 'agent', + 'processIncarnation', + 'sessionId', + 'transcriptPath', + 'wslDistro' + ] as const) { + const value = text(name) + if (value) { + reference[name] = value + } + } + return fallbackReason ? { ...reference, fallbackReason } : reference +} + +export function summarizeWorkerOutputArchive( + archive: Pick +): { source: 'transcript' | 'terminal' - status: Extract + status: WorkerTerminalArchiveStatus +} { + if (!isWorkerOutputReference(archive)) { + return summarizeSavedOutputCopy(archive) + } + return summarizeReferenceKind(archive.kind) +} + +function summarizeReferenceKind(kind: WorkerTerminalArchiveKind): { + source: 'transcript' | 'terminal' + status: WorkerOutputArchiveStatus +} { + // Report chat history as transcript output to preserve the existing paired-client source union. + return kind === 'terminal_tail' + ? { source: 'terminal', status: 'unavailable' } + : { source: 'transcript', status: 'captured' } +} + +function summarizeSavedOutputCopy(archive: Pick): { + source: 'transcript' | 'terminal' + status: 'captured' | 'empty' } { if (archive.kind === 'transcript_pin') { return { source: 'transcript', status: 'captured' } } if (archive.kind === 'structured_journal') { - // Report journals as transcript output to preserve the existing paired-client source union. const journal = JSON.parse(archive.content) as WorkerStructuredJournalArchive return { source: 'transcript', status: journal.messages.length > 0 ? 'captured' : 'empty' } } const content = JSON.parse(archive.content) as WorkerTerminalTailArchive const empty = content.lines.every((line) => line.trim() === '') && (content.draft?.trim() ?? '') === '' - return { - source: 'terminal', - status: empty ? 'empty' : 'captured' - } -} - -// Archive exact provider transcript or redacted terminal tail before close; typed archive_failed retains live output. -export async function captureWorkerOutputArchive(args: { - runtime: WorkerTerminalReleaseRuntime - dispatchId: string - terminalHandle: string - attachedAtMs: number - /** Present when the worker IS a structured session; its journal is the only output it has. */ - structuredWorker?: StructuredWorkerIdentity | null -}): Promise { - if (args.structuredWorker) { - const content = await captureStructuredWorkerArchive( - args.structuredWorker, - structuredWorkerAgent(args.structuredWorker) - ) - return { - kind: 'structured_journal', - status: content.messages.length > 0 ? 'captured' : 'empty', - content - } - } - const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, args.attachedAtMs) - let transcriptFallbackReason: OrchestrationWorkerReadFallbackReason = 'session_not_reported' - if (session) { - transcriptFallbackReason = 'transcript_unreadable' - const isWslSession = isWslHookRelayConnectionId(session.connectionId) - // No SSH filesystem provider is installed, so remote transcripts are unreachable. - const isSshSession = Boolean(session.connectionId) && !isWslSession - if ((isWslSession && !session.wslDistro) || isSshSession) { - transcriptFallbackReason = 'remote_capability_unavailable' - } else { - const snapshot = await readWorkerTranscript({ - agent: session.agent, - sessionId: session.providerSession.id, - transcriptPath: session.providerSession.transcriptPath, - wslDistro: session.wslDistro, - limit: MAX_WORKER_TRANSCRIPT_MESSAGE_LIMIT - }).catch(() => null) - if (snapshot?.ok && snapshot.messages.length > 0) { - return { - kind: 'transcript_pin', - status: 'captured', - content: { - version: 2, - agent: session.agent, - processIncarnation: session.processIncarnation, - messages: snapshot.messages, - limited: snapshot.limited, - clipping: snapshot.clipping, - warnings: snapshot.warnings - } - } - } - if (snapshot?.ok) { - transcriptFallbackReason = snapshot.limited ? 'transcript_unreadable' : 'transcript_empty' - } else if (snapshot) { - transcriptFallbackReason = - snapshot.reason === 'source_changed' ? 'transcript_unreadable' : snapshot.reason - } - } - } - let terminal - try { - terminal = await readWorkerTerminalArchive(args.runtime, args.terminalHandle) - } catch (error) { - throw new OrchestrationError( - 'archive_failed', - `Output could not be preserved for Dispatch ${args.dispatchId}; the terminal was retained. ${error instanceof Error ? error.message : String(error)}` - ) - } - const redacted = redactWorkerTerminalLines([ - ...terminal.tail, - ...(terminal.draft ? [terminal.draft] : []) - ]) - const bounded = boundArchiveLines(redacted.lines) - const draft = terminal.draft ? bounded.lines.at(-1) : undefined - const lines = terminal.draft ? bounded.lines.slice(0, -1) : bounded.lines - // An exited PTY clears its tail; report empty evidence explicitly to worker-read. - const empty = bounded.lines.every((line) => line.trim() === '') - return { - kind: 'terminal_tail', - status: empty ? 'empty' : 'captured', - content: { - lines, - ...(draft ? { draft } : {}), - truncated: terminal.truncated || bounded.truncated, - terminalStatus: terminal.status, - warnings: empty - ? [ - ...redacted.warnings, - ...terminal.warnings, - 'The live terminal buffer was empty at release; structured transcript output was unavailable.' - ] - : [...redacted.warnings, ...terminal.warnings], - fallbackReason: transcriptFallbackReason, - clipping: [ - 'terminal_fallback', - ...(bounded.truncated || terminal.truncated ? ['terminal_buffer'] : []) - ] - } - } -} - -export function boundArchiveLines(lines: string[]): { lines: string[]; truncated: boolean } { - let total = 0 - for (const line of lines) { - total += line.length + 1 - if (total > TERMINAL_ARCHIVE_MAX_CHARS) { - break - } - } - if (total <= TERMINAL_ARCHIVE_MAX_CHARS) { - return { lines, truncated: false } - } - // Collect newest-first and reverse once; per-line unshift is quadratic for ~260k blank lines. - const keptReversed: string[] = [] - let budget = TERMINAL_ARCHIVE_MAX_CHARS - for (let index = lines.length - 1; index >= 0; index -= 1) { - const cost = lines[index].length + 1 - if (cost > budget) { - if (keptReversed.length === 0 && budget > 1) { - keptReversed.push(lines[index].slice(-(budget - 1))) - } - break - } - keptReversed.push(lines[index]) - budget -= cost - } - keptReversed.reverse() - return { lines: keptReversed, truncated: true } + return { source: 'terminal', status: empty ? 'empty' : 'captured' } } /** Errors at compile time if a capture kind is ever added that the durable row cannot store. */ @@ -215,18 +216,29 @@ export type WorkerOutputArchiveCaptureKind = AssertAssignable< > /** Archive fields a release commit records for an archive an earlier attempt already stored. */ -export function releaseCommitFieldsForStoredArchive(archive: WorkerTerminalArchiveRow) { +export function releaseCommitFieldsForStoredArchive( + archive: Pick +) { const stored = summarizeWorkerOutputArchive(archive) return { archiveSource: stored.source, archiveStatus: stored.status } } -/** Archive fields a release commit publishes for freshly captured output. */ +/** Archive fields a release commit publishes for a freshly recorded reference. */ export function releaseCommitFieldsForCapturedArchive(captured: WorkerOutputArchiveCapture) { return { kind: captured.kind, - content: JSON.stringify(captured.content), - archiveSource: - captured.kind === 'terminal_tail' ? ('terminal' as const) : ('transcript' as const), + content: JSON.stringify({ ...captured.content, ...olderReaderFields(captured.kind) }), + archiveSource: summarizeReferenceKind(captured.kind).source, archiveStatus: captured.status } } + +const OLDER_READER_NOTE = + 'This version of Orca reads released output from the saved copy only. Read it with a newer Orca, or see its report (worker_done) or task result.' + +/** Empty copy fields, so a downgraded Orca shows a note instead of failing on a reference row. */ +function olderReaderFields(kind: WorkerTerminalArchiveKind) { + return kind === 'terminal_tail' + ? { lines: [], truncated: false, terminalStatus: 'exited', warnings: [OLDER_READER_NOTE] } + : { messages: [], limited: true, warnings: [OLDER_READER_NOTE] } +} diff --git a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-read.ts b/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-read.ts deleted file mode 100644 index 845419d30b4..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-read.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { MAX_TERMINAL_READ_LIMIT } from '../../../terminal/output/tail/terminal-tail-limits' -import { redactWorkerTerminalView } from '../../terminal-authority/views/worker-terminal-redaction' - -export async function readWorkerTerminalArchive( - runtime: Pick, - handle: string -) { - // Cursor reads retain completed history; the screen read also preserves partial output/drafts. - const history = await runtime.readTerminal(handle, { cursor: 0, limit: MAX_TERMINAL_READ_LIMIT }) - const screen = await runtime.readTerminal(handle, { - screen: true, - limit: MAX_TERMINAL_READ_LIMIT - }) - const hasScreen = screen.source === 'screen' - const redactedHistory = redactWorkerTerminalView(history) - const redactedScreen = redactWorkerTerminalView(screen) - const alreadyRetained = - redactedScreen.tail.length <= redactedHistory.tail.length && - redactedScreen.tail.every( - (line, index) => - line === - redactedHistory.tail[redactedHistory.tail.length - redactedScreen.tail.length + index] - ) - const appended = screen.tail.length > 0 && !alreadyRetained - const warnings: string[] = [] - if (!hasScreen) { - warnings.push( - screen.source === 'screen-unavailable' - ? 'The current terminal screen was unavailable; only retained stream output could be preserved.' - : 'The terminal read did not identify an authoritative screen; available terminal output was preserved.' - ) - } else if (appended) { - warnings.push( - history.tail.some((line) => line.trim() !== '') - ? 'Terminal output includes retained stream history followed by the current screen; overlapping lines may appear more than once.' - : 'Terminal output was preserved from the current terminal screen.' - ) - } - return { - ...history, - ...redactedHistory, - tail: appended ? [...redactedHistory.tail, ...redactedScreen.tail] : redactedHistory.tail, - ...(redactedScreen.draft ? { draft: redactedScreen.draft } : {}), - truncated: - history.truncated || history.limited === true || screen.truncated || screen.limited === true, - warnings: [...new Set([...redactedHistory.warnings, ...redactedScreen.warnings, ...warnings])] - } -} diff --git a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-release.test.ts b/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-release.test.ts deleted file mode 100644 index 5e17bf2af23..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-release.test.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - ARCHIVE_SCREEN_LINES, - createTerminalArchiveFixture -} from './worker-terminal-archive.test-support' -import { createOrchestrationWorkerReleaseHarness } from '../../../rpc/methods/orchestration/worker/worker-release.test-support' - -function dispatchIdOf(receipt: unknown): string { - if ( - typeof receipt !== 'object' || - receipt === null || - !('dispatchId' in receipt) || - typeof receipt.dispatchId !== 'string' - ) { - throw new Error('No dispatch in worker-start receipt') - } - return receipt.dispatchId -} - -describe('released worker archives preserve the host screen', () => { - const h = createOrchestrationWorkerReleaseHarness() - afterEach(() => h.cleanup()) - - function prepareFailedStart() { - h.setup() - const retryPane = 'tab_retry:cccccccc-cccc-4ccc-8ccc-cccccccccccc' - vi.mocked(h.runtime.createTerminal) - .mockResolvedValueOnce({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - title: 'worker' - }) - .mockResolvedValue({ handle: 'term_retry', worktreeId: 'repo::worktree', title: 'retry' }) - vi.mocked(h.runtime.getTerminalPaneKey).mockImplementation((handle) => - handle === 'term_retry' - ? retryPane - : handle === 'term_coord' - ? h.coordinatorPaneKey - : h.workerPaneKey - ) - vi.mocked(h.runtime.getTerminalProcessIncarnation).mockImplementation( - (handle) => `runtime_test:${handle}:1` - ) - vi.mocked(h.runtime.getOrchestrationDispatchAuthority).mockImplementation((handle) => ({ - runtimeId: 'runtime_test', - terminalHandle: handle, - ptyId: `pty_${handle}`, - worktreeId: 'repo::worktree', - paneKey: handle === 'term_retry' ? retryPane : h.workerPaneKey, - processIncarnation: `runtime_test:${handle}:1`, - launchTokenHash: null, - hostScope: { kind: 'local', hostId: 'local' } - })) - vi.mocked(h.runtime.waitForTerminal).mockResolvedValue({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: false, - status: 'running', - exitCode: null, - blockedReason: 'agent-interactive-prompt' - }) - return h.db.createTask({ spec: 'startup diagnostic', runId: h.activeRunId }) - } - - it.each([ - { route: 'automatic retry', provider: false, stream: '\r\n'.repeat(7) }, - { route: 'automatic retry', provider: false, stream: `host % codex\r\n${'\r\n'.repeat(6)}` }, - { route: 'manual release', provider: false, stream: '\r\n'.repeat(7) }, - { route: 'manual release', provider: false, stream: `host % codex\r\n${'\r\n'.repeat(6)}` }, - { route: 'automatic retry', provider: true, stream: '\r\n'.repeat(7) }, - { route: 'automatic retry', provider: true, stream: `host % codex\r\n${'\r\n'.repeat(6)}` }, - { route: 'manual release', provider: true, stream: '\r\n'.repeat(7) }, - { route: 'manual release', provider: true, stream: `host % codex\r\n${'\r\n'.repeat(6)}` } - ])('freezes the full diagnostic before $route (%j)', async ({ route, provider, stream }) => { - const task = prepareFailedStart() - const fixture = await createTerminalArchiveFixture({ provider }) - fixture.runtime.onPtyData('pty-1', stream, Date.now()) - const failed = await h.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - }) - const dispatchId = dispatchIdOf(failed) - vi.mocked(h.runtime.readTerminal).mockImplementation((_handle, opts) => - fixture.runtime.readTerminal(fixture.handle, opts) - ) - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - const archive = h.db.getWorkerTerminalArchive(dispatchId) - expect(archive?.content).toContain(ARCHIVE_SCREEN_LINES[1]) - fixture.runtime.onPtyExit('pty-1', 0) - return { handle, tabId: 'tab-worker', ptyKilled: true } - }) - - if (route === 'automatic retry') { - await expect( - h.call('orchestration.workerStart', { - task: task.id, - retryOf: dispatchId, - from: 'term_coord', - agent: 'codex' - }) - ).resolves.toMatchObject({ state: 'failed' }) - await vi.waitFor(() => - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') - ) - } else { - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'released' }) - } - - expect(h.runtime.closeTerminal).toHaveBeenCalledExactlyOnceWith('term_worker') - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.archive_status).toBe('captured') - vi.mocked(h.runtime.readTerminal).mockRejectedValue(new Error('Live output is gone')) - const read = await h.call('orchestration.workerRead', { dispatch: dispatchId, limit: 2000 }) - expect(read).toMatchObject({ - archived: true, - source: 'terminal', - sourceExact: false, - contentComplete: false, - terminal: { tail: expect.arrayContaining(ARCHIVE_SCREEN_LINES), nextCursor: null } - }) - if (stream.includes('host % codex')) { - expect(read).toMatchObject({ terminal: { tail: expect.arrayContaining(['host % codex']) } }) - } - }) - - it.each(['soft wrap', 'multiple lines'] as const)( - 'masks a real composer draft after release (%s)', - async (layout) => { - h.setup() - const { dispatchId } = await h.startSettledWorker('failed') - const fixture = await createTerminalArchiveFixture({ hydrate: false }) - const secret = `dcap_${'s'.repeat(24)}` - const composer = - layout === 'soft wrap' - ? `❯ ${'x'.repeat(89)} ${secret}\x1b[1A\x1b[3G` - : `❯ dc\r\n ap_sssss\r\n ${'s'.repeat(19)}\x1b[2A\x1b[3G` - fixture.runtime.onPtyData('pty-1', `Safe diagnostic\r\n────────\r\n${composer}`, Date.now()) - const screen = await fixture.runtime.readTerminal(fixture.handle, { screen: true }) - expect(screen.draft?.replaceAll('\n', '')).toContain(secret) - vi.mocked(h.runtime.readTerminal).mockImplementation((_handle, opts) => - fixture.runtime.readTerminal(fixture.handle, opts) - ) - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - fixture.runtime.onPtyExit('pty-1', 0) - return { handle, tabId: 'tab-worker', ptyKilled: true } - }) - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - expect(h.db.getWorkerTerminalArchive(dispatchId)?.content).not.toContain(secret) - vi.mocked(h.runtime.readTerminal).mockRejectedValue(new Error('Live output gone')) - const read = await h.call('orchestration.workerRead', { dispatch: dispatchId, limit: 2000 }) - expect(read).toMatchObject({ - archived: true, - terminal: { - nextCursor: null, - draft: - layout === 'soft wrap' - ? expect.stringContaining('[dispatch capability redacted]') - : screen.draft - } - }) - if ( - typeof read !== 'object' || - read === null || - !('terminal' in read) || - typeof read.terminal !== 'object' || - read.terminal === null || - !('draft' in read.terminal) || - typeof read.terminal.draft !== 'string' - ) { - throw new Error('No archived draft') - } - if (layout === 'soft wrap') { - expect(read.terminal.draft.replaceAll('\n', '')).not.toContain(secret) - } else { - expect(read.terminal.draft).toBe(screen.draft) - } - } - ) - - it('keeps the pane when an identity change wins during the screen capture', async () => { - const task = prepareFailedStart() - const fixture = await createTerminalArchiveFixture() - fixture.runtime.onPtyData('pty-1', '\r\n'.repeat(7), Date.now()) - const failed = await h.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - }) - const dispatchId = dispatchIdOf(failed) - const pending = h.deferred() - let screenStarted = false - vi.mocked(h.runtime.readTerminal).mockImplementation(async (_handle, opts) => { - if (opts?.screen) { - screenStarted = true - await pending.promise - } - return fixture.runtime.readTerminal(fixture.handle, opts) - }) - const release = h.call('orchestration.workerRelease', { dispatch: dispatchId }) - await vi.waitFor(() => expect(screenStarted).toBe(true)) - vi.mocked(h.runtime.getTerminalProcessIncarnation).mockReturnValue('runtime_test:term_worker:2') - vi.mocked(h.runtime.getOrchestrationDispatchAuthority).mockReturnValue({ - runtimeId: 'runtime_test', - terminalHandle: 'term_worker', - ptyId: 'pty_term_worker', - worktreeId: 'repo::worktree', - paneKey: h.workerPaneKey, - processIncarnation: 'runtime_test:term_worker:2', - launchTokenHash: null, - hostScope: { kind: 'local', hostId: 'local' } - }) - pending.resolve() - await expect(release).resolves.toMatchObject({ state: 'retained' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.retained_reason).toBe( - 'identity_unproven' - ) - }) -}) diff --git a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-screen.test.ts b/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-screen.test.ts deleted file mode 100644 index c78ae54638a..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive-screen.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createTerminalArchiveFixture } from './worker-terminal-archive.test-support' -import { syncSinglePty } from '../../../orca-runtime-tests/orca-runtime-test-fixtures.spec' - -afterEach(() => vi.restoreAllMocks()) - -describe('worker archive through real terminal read routing', () => { - it('keeps history and current-screen boundaries independent for masking', async () => { - const history = `dcap_${'s'.repeat(5)}` - const screen = 's'.repeat(19) - const fixture = await createTerminalArchiveFixture({ - provider: true, - screenLines: [screen, 'Safe diagnostic'] - }) - fixture.runtime.onPtyData('pty-1', `${history}\r\n`, Date.now()) - const archive = await fixture.capture() - if (archive.kind !== 'terminal_tail') { - throw new Error('Expected terminal archive') - } - expect(archive.content.lines).toEqual([history, screen, 'Safe diagnostic']) - expect(archive.content.warnings).not.toContain( - 'Dispatch capability tokens were redacted from terminal output.' - ) - }) - - it.each(['unavailable', 'stale'] as const)( - 'preserves useful stream output when the provider screen is %s', - async (authority) => { - const fixture = await createTerminalArchiveFixture({ provider: true }) - fixture.runtime.onPtyData('pty-1', 'retained diagnostic\r\npartial output', Date.now()) - if (authority === 'unavailable') { - fixture.serializeProviderBuffer.mockRejectedValue(new Error('Host snapshot unavailable')) - } else { - fixture.serializeProviderBuffer.mockResolvedValue({ - data: 'untrusted old screen\r\n', - cols: 100, - rows: 30, - seq: 0, - source: 'headless', - alternateScreen: false - }) - } - - const archive = await fixture.capture() - - expect(archive.status).toBe('captured') - if (archive.kind !== 'terminal_tail') { - throw new Error('Expected terminal archive') - } - expect(archive.content.lines).toContain('retained diagnostic') - expect(archive.content.lines).toContain('partial output') - expect(archive.content.lines.join('\n')).not.toContain('untrusted old screen') - expect(archive.content.warnings.join(' ')).toContain('screen was unavailable') - } - ) - - it('refuses capture when the terminal handle changes during a host screen read', async () => { - const fixture = await createTerminalArchiveFixture({ provider: true }) - fixture.runtime.onPtyData('pty-1', 'retained diagnostic\r\n', Date.now()) - const snapshot = { - data: 'Wrong terminal frame\r\n', - cols: 100, - rows: 30, - seq: 900, - source: 'headless' as const, - alternateScreen: false - } - let resolveSnapshot!: (value: typeof snapshot) => void - fixture.serializeProviderBuffer.mockResolvedValue(snapshot).mockImplementationOnce( - () => - new Promise((resolve) => { - resolveSnapshot = resolve - }) - ) - const capture = fixture.capture() - await vi.waitFor(() => expect(fixture.serializeProviderBuffer).toHaveBeenCalledOnce()) - syncSinglePty(fixture.runtime, 'pty-2') - resolveSnapshot(snapshot) - - await expect(capture).rejects.toThrow('terminal_handle_stale') - }) - - it('redacts stream and screen evidence before applying the durable budget', async () => { - const secret = `dcap_${'s'.repeat(24)}` - const fixture = await createTerminalArchiveFixture({ - screenLines: [`screen ${secret}`], - provider: true - }) - fixture.runtime.onPtyData( - 'pty-1', - `${Array.from( - { length: 1800 }, - (_, index) => `history ${index} ${'x'.repeat(150)} ${secret}` - ).join('\r\n')}\r\n`, - Date.now() - ) - - const archive = await fixture.capture() - - if (archive.kind !== 'terminal_tail') { - throw new Error('Expected terminal archive') - } - expect(JSON.stringify(archive.content)).not.toContain(secret) - expect(archive.content.lines).toContain('screen [dispatch capability redacted]') - expect(archive.content.lines.some((line) => line.includes('history 1799'))).toBe(true) - expect( - archive.content.lines.reduce((total, line) => total + line.length + 1, 0) - ).toBeLessThanOrEqual(262_144) - expect(archive.content.truncated).toBe(true) - expect(archive.content.clipping).toContain('terminal_buffer') - }) -}) diff --git a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive.test-support.ts b/src/main/runtime/orchestration/workers/archives/worker-terminal-archive.test-support.ts deleted file mode 100644 index ba6c3bb6800..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-terminal-archive.test-support.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { vi } from 'vitest' -import { - createRuntime, - syncSinglePty -} from '../../../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { captureWorkerOutputArchive } from './worker-output-archive' - -// Synthetic normal-screen output; this exercises capture, not agent prompt detection. -export const ARCHIVE_SCREEN_LINES = [ - 'Worker startup diagnostic', - 'Would you like to grant these permissions?', - '1. Yes, grant these permissions for this turn', - '2. No, continue without permissions', - 'Press enter to confirm or esc to cancel' -] - -export async function createTerminalArchiveFixture( - options: { - screenLines?: string[] - alternate?: boolean - hydrate?: boolean - provider?: boolean - cols?: number - rows?: number - } = {} -) { - const runtime = createRuntime() - const snapshot = { - data: `${options.alternate ? '\x1b[?1049h' : ''}${(options.screenLines ?? ARCHIVE_SCREEN_LINES).join('\r\n')}\r\n`, - cols: options.cols ?? 100, - rows: options.rows ?? 30 - } - const serializeProviderBuffer = vi.fn(async () => ({ - ...snapshot, - seq: runtime.getPtyOutputSequence('pty-1'), - source: 'headless' as const, - alternateScreen: options.alternate ?? false - })) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'codex', - hasRendererSerializer: () => !options.provider && options.hydrate !== false, - serializeBuffer: async () => snapshot, - ...(options.provider ? { serializeProviderBuffer } : {}), - getSize: () => ({ cols: options.cols ?? 100, rows: options.rows ?? 30 }) - }) - syncSinglePty(runtime) - const [terminal] = (await runtime.listTerminals()).terminals - if (!terminal) { - throw new Error('No fixture terminal') - } - if (options.provider) { - runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-1', - { value: 900, generation: 'continued' }, - 0 - ) - } - vi.spyOn(runtime, 'getExactWorkerProviderSession').mockReturnValue(null) - return { - runtime, - handle: terminal.handle, - serializeProviderBuffer, - capture: () => - captureWorkerOutputArchive({ - runtime, - terminalHandle: terminal.handle, - dispatchId: 'ctx_archive', - attachedAtMs: 0 - }) - } -} diff --git a/src/main/runtime/orchestration/workers/archives/worker-terminal-wrap-provenance.test.ts b/src/main/runtime/orchestration/workers/archives/worker-terminal-wrap-provenance.test.ts deleted file mode 100644 index d361bf92c71..00000000000 --- a/src/main/runtime/orchestration/workers/archives/worker-terminal-wrap-provenance.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createTerminalArchiveFixture } from './worker-terminal-archive.test-support' -import { createOrchestrationWorkerReleaseHarness } from '../../../rpc/methods/orchestration/worker/worker-release.test-support' - -function readTail(read: unknown): string[] { - if ( - typeof read !== 'object' || - read === null || - !('terminal' in read) || - typeof read.terminal !== 'object' || - read.terminal === null || - !('tail' in read.terminal) || - !Array.isArray(read.terminal.tail) - ) { - throw new Error('No worker terminal output') - } - return read.terminal.tail -} - -describe('host wrap provenance in worker output', () => { - const h = createOrchestrationWorkerReleaseHarness() - afterEach(() => h.cleanup()) - - it('retains both views when identical raw history and screen rows have different continuity', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('failed') - const fixture = await createTerminalArchiveFixture({ hydrate: false, cols: 10 }) - const historyLines = ['dcap_abcde', 'fghijklmno', 'pqrstuvwx', 'Safe'] - fixture.runtime.onPtyData('pty-1', `${historyLines.join('\r\n')}\r\n`, Date.now()) - fixture.runtime.onPtyData( - 'pty-1', - '\x1b[2J\x1b[Hdcap_abcdefghijklmnopqrstuvwx\x1b[4;1HSafe', - Date.now() - ) - const history = await fixture.runtime.readTerminal(fixture.handle, { cursor: 0, limit: 2000 }) - const screen = await fixture.runtime.readTerminal(fixture.handle, { screen: true, limit: 2000 }) - expect(history.tail).toEqual(screen.tail) - expect(screen.tailRows?.some((row) => row.wrapped)).toBe(true) - vi.mocked(h.runtime.readTerminal).mockImplementation((_handle, opts) => - fixture.runtime.readTerminal(fixture.handle, opts) - ) - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - fixture.runtime.onPtyExit('pty-1', 0) - return { handle, tabId: 'tab-worker', ptyKilled: true } - }) - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - expect(h.db.getWorkerTerminalArchive(dispatchId)?.content).toContain( - '[dispatch capability redacted]' - ) - vi.mocked(h.runtime.readTerminal).mockRejectedValue(new Error('Live gone')) - const read = await h.call('orchestration.workerRead', { dispatch: dispatchId, limit: 2000 }) - expect(read).toMatchObject({ archived: true }) - expect(readTail(read)).toEqual([ - ...historyLines, - '[dispatch capability redacted]', - '', - '', - 'Safe' - ]) - }) - - it.each([1, 2, 3, 5, 10, 29, 30, 80, 100])( - 'masks complete soft-wrapped values from provider-only screens at width %i', - async (cols) => { - h.setup() - const { dispatchId } = await h.startSettledWorker('failed') - const secret = 'dcap_abcdefghijklmnopqrstuvwx' - const fixture = await createTerminalArchiveFixture({ - provider: true, - alternate: true, - cols, - rows: 100, - screenLines: [ - `界e\u0301 ${'x'.repeat(Math.max(0, cols - 3))} ${secret}`, - 'PermissionDenied' - ] - }) - fixture.runtime.onPtyData('pty-1', 'useful history\r\n', Date.now()) - const raw = await fixture.runtime.readTerminal(fixture.handle, { screen: true, limit: 2000 }) - expect(raw.tail.join('')).toContain(secret) - expect(raw.tailRows).toHaveLength(raw.tail.length) - vi.mocked(h.runtime.readTerminal).mockImplementation((_handle, opts) => - fixture.runtime.readTerminal(fixture.handle, opts) - ) - const live = await h.call('orchestration.workerRead', { - dispatch: dispatchId, - source: 'terminal', - limit: 2000 - }) - expect(readTail(live)).toHaveLength(raw.tail.length) - expect(readTail(live).join('')).not.toContain(secret) - expect(readTail(live).join('')).not.toContain('abcdefghijklmnopqrstuvwx') - expect(readTail(live).join('')).toContain('PermissionDenied') - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - fixture.runtime.onPtyExit('pty-1', 0) - return { handle, tabId: 'tab-worker', ptyKilled: true } - }) - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - const stored = h.db.getWorkerTerminalArchive(dispatchId) - expect(stored?.content).not.toContain('abcdefghijklmnopqrstuvwx') - vi.mocked(h.runtime.readTerminal).mockRejectedValue(new Error('Live output gone')) - const read = await h.call('orchestration.workerRead', { dispatch: dispatchId, limit: 2000 }) - expect(read).toMatchObject({ archived: true, terminal: { nextCursor: null } }) - expect(readTail(read).join('')).not.toContain(secret) - expect(readTail(read).join('')).not.toContain('abcdefghijklmnopqrstuvwx') - expect(readTail(read).join('')).toContain('PermissionDenied') - expect(readTail(read)).toContain('useful history') - } - ) - - it.each(['screen' as const, undefined])( - 'retains complete-line semantics and coverage limits without wrap metadata (source=%s)', - async (source) => { - h.setup() - const { dispatchId } = await h.startSettledWorker('failed') - const secret = 'dcap_abcdefghijklmnopqrstuvwx' - const fixture = await createTerminalArchiveFixture({ - provider: true, - alternate: true, - screenLines: [`${'x'.repeat(89)} ${secret}`, 'PermissionDenied'] - }) - fixture.runtime.onPtyData('pty-1', 'useful history\r\n', Date.now()) - vi.mocked(h.runtime.readTerminal).mockImplementation(async (_handle, opts) => { - const { - source: _source, - tailRows: _rows, - ...read - } = await fixture.runtime.readTerminal(fixture.handle, opts) - return { ...read, ...(source ? { source } : {}) } - }) - const live = await h.call('orchestration.workerRead', { - dispatch: dispatchId, - source: 'terminal', - limit: 2000 - }) - expect(readTail(live).join('')).toContain(secret) - expect(readTail(live)).toContain('PermissionDenied') - expect(live).toMatchObject({ - warnings: expect.arrayContaining([ - 'Terminal wrap information was unavailable; capability masking used complete lines.' - ]) - }) - } - ) - - it('keeps hard composer breaks in stored and full archived draft output', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('failed') - const fixture = await createTerminalArchiveFixture({ hydrate: false, alternate: true }) - fixture.runtime.onPtyData( - 'pty-1', - '\x1b[?1049hSafe diagnostic\r\n────────\r\n❯ dcap_sssss\r\n PermissionDenied\x1b[1A\x1b[3G', - Date.now() - ) - vi.mocked(h.runtime.readTerminal).mockImplementation((_handle, opts) => - fixture.runtime.readTerminal(fixture.handle, opts) - ) - const live = await h.call('orchestration.workerRead', { - dispatch: dispatchId, - source: 'terminal', - limit: 2000 - }) - expect(live).toMatchObject({ terminal: { draft: 'dcap_sssss\nPermissionDenied' } }) - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - fixture.runtime.onPtyExit('pty-1', 0) - return { handle, tabId: 'tab-worker', ptyKilled: true } - }) - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - expect(h.db.getWorkerTerminalArchive(dispatchId)?.content).toContain('PermissionDenied') - vi.mocked(h.runtime.readTerminal).mockRejectedValue(new Error('Live output gone')) - await expect( - h.call('orchestration.workerRead', { dispatch: dispatchId, limit: 2000 }) - ).resolves.toMatchObject({ - archived: true, - terminal: { draft: 'dcap_sssss\nPermissionDenied', nextCursor: null } - }) - }) -}) diff --git a/src/main/runtime/orchestration/workers/launch/worker-start-card.ts b/src/main/runtime/orchestration/workers/launch/worker-start-card.ts index c68dca11f1a..0b73f16c643 100644 --- a/src/main/runtime/orchestration/workers/launch/worker-start-card.ts +++ b/src/main/runtime/orchestration/workers/launch/worker-start-card.ts @@ -55,6 +55,7 @@ export function prepareWorkerStartCard( task: string /** What this start launched; the only kind known for a worker on another host. */ agent: AgentType | null + followUp?: AgentJournalAgentStartItem['followUp'] }) => void { // A paired Orca has no chat here to show the card in. const publish = prepareAgentCreationCard( @@ -68,7 +69,8 @@ export function prepareWorkerStartCard( kind: 'agent-start', dispatchId: args.dispatchId, worker: startedAgentSender(runtime, args.workerAddress, args.agent, args.dispatchId), - task: args.task + task: args.task, + ...(args.followUp ? { followUp: args.followUp } : {}) })) } diff --git a/src/main/runtime/orchestration/workers/transcripts/worker-transcript-local-read.ts b/src/main/runtime/orchestration/workers/transcripts/worker-transcript-local-read.ts index 27abc46b5be..9e7ec215ba1 100644 --- a/src/main/runtime/orchestration/workers/transcripts/worker-transcript-local-read.ts +++ b/src/main/runtime/orchestration/workers/transcripts/worker-transcript-local-read.ts @@ -5,8 +5,8 @@ import { readNativeChatTranscriptTailFile, type NativeChatLineDecoder } from '../../../../native-chat/transcript-tail-reader' -import { TAIL_CHUNK_BYTES } from '../../../../native-chat/transcript-tail-boundary' -import { transcriptFallbackId } from '../../../../native-chat/transcript-fallback-id' +import { TAIL_CHUNK_BYTES } from '../../../../native-chat/transcript-watching/transcript-tail-boundary' +import { transcriptFallbackId } from '../../../../native-chat/transcript-streaming/transcript-fallback-id' import { localTranscriptOffsetStartsInsideRecord, readLocalTranscriptHandleBoundaryCheckpoint, diff --git a/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts b/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts index 7346edc844f..962d0e4d760 100644 --- a/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts +++ b/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts @@ -19,7 +19,7 @@ type WorkerTranscriptReadFailure = { warnings: string[] } -type WorkerTranscriptReadSuccess = { +export type WorkerTranscriptReadSuccess = { ok: true filePath: string sourceFingerprint: string @@ -33,6 +33,11 @@ type WorkerTranscriptReadSuccess = { export type WorkerTranscriptReadResult = WorkerTranscriptReadFailure | WorkerTranscriptReadSuccess +/** Whether readWorkerTranscript can read this agent's transcript at all. */ +export function canReadWorkerTranscript(agent: AgentType): boolean { + return Boolean(resolveNativeChatTranscriptAgent(agent) && nativeChatLineDecoderForAgent(agent)) +} + export async function readWorkerTranscript(args: { agent: AgentType sessionId: string diff --git a/src/main/runtime/orchestration/workers/turn-stops/chat-worker-turn-stops.ts b/src/main/runtime/orchestration/workers/turn-stops/chat-worker-turn-stops.ts index f770aff26e5..941a493e53e 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/chat-worker-turn-stops.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/chat-worker-turn-stops.ts @@ -18,7 +18,7 @@ import { import { workerApprovalPayload } from '../approvals/worker-approval' import type { AgentJournalApprovalItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -// Why a delay: the reporter is built with the chat host, which registers just after. +// Defer saved-report observation until the installed host is available. const ADOPT_AFTER_MS = 5_000 type ChatStop = { @@ -52,9 +52,11 @@ function chatStop(event: AgentSessionTurnCompletionEvent): ChatStop | null { * A finished turn waits out the quiet period, as a terminal's does, and while its Dispatch is still * starting: the turn that reported ends just before the follow-up it claimed hands over its task. */ export function chatWorkerTurnStopReporter( - deps: WorkerTurnStopReportDeps, - setTimer: (run: () => void, delayMs: number) => void = (run, delayMs) => { - setTimeout(run, delayMs).unref?.() + deps: WorkerTurnStopReportDeps & { openExistingDb?: () => unknown }, + setTimer: (run: () => void, delayMs: number) => void | (() => void) = (run, delayMs) => { + const timer = setTimeout(run, delayMs) + timer.unref?.() + return () => clearTimeout(timer) }, readPrompt: ChatWorkerPromptReader = readChatWorkerPrompt, watchJournal?: ChatJournalWatch, @@ -63,20 +65,41 @@ export function chatWorkerTurnStopReporter( const generations = new Map() // A turn begins after its session's previous turn completed; a prompt arrives mid-turn and bounds nothing. const previousCompletionAt = new Map() - const approvals = new ChatWorkerApprovalWatch({ ...deps, readPrompt, watchJournal }) - setTimer(() => { - approvals.adopt().catch((error: unknown) => { - console.warn('[orchestration] chat worker approval adoption failed', error) - }) - }, ADOPT_AFTER_MS) - - return ( + const lifetime = new AbortController() + const timers = new Set<() => void>() + const schedule = (run: () => void, delayMs: number): void => { + if (lifetime.signal.aborted) { + return + } + let cancel: void | (() => void) + const stop = () => { + cancel?.() + timers.delete(stop) + } + timers.add(stop) + cancel = setTimer(() => { + timers.delete(stop) + if (!lifetime.signal.aborted) { + run() + } + }, delayMs) + } + const approvals = new ChatWorkerApprovalWatch({ + ...deps, + readPrompt, + watchJournal, + signal: lifetime.signal + }) + const onTurnAttention = ( event: AgentSessionTurnCompletionEvent, readStatus: ( sessionId: string ) => Pick | undefined ): void => { try { + if (lifetime.signal.aborted) { + return + } const sessionId = event.type === 'completion' ? event.completion.sessionId @@ -105,6 +128,9 @@ export function chatWorkerTurnStopReporter( let approval: AgentJournalApprovalItem | null = null const deliver = (): void => { try { + if (lifetime.signal.aborted) { + return + } const current = deps.getDb() const status = readStatus(stop.sessionId) // A newer edge supersedes this one, and a queued follow-up already started the next turn. @@ -124,10 +150,13 @@ export function chatWorkerTurnStopReporter( ({ dispatch }) => current.getWorkerDispatch(dispatch.id)?.state === 'starting' ) ) { - setTimer(deliver, AGENT_DONE_QUIET_MS) + schedule(deliver, AGENT_DONE_QUIET_MS) return } for (const { dispatch, from } of open) { + if (lifetime.signal.aborted) { + return + } const candidate = approval && stop.promptId ? workerApprovalPayload({ @@ -165,13 +194,15 @@ export function chatWorkerTurnStopReporter( } } if (stop.reason === 'finished') { - setTimer(deliver, AGENT_DONE_QUIET_MS) + schedule(deliver, AGENT_DONE_QUIET_MS) } else if (stop.promptId) { // A permission prompt is reported with what it asks; anything else as a plain prompt. const promptId = stop.promptId void readPrompt(stop.sessionId, promptId) .then((prompt) => { - approval = prompt?.body.resolution.state === 'pending' ? prompt.body : null + if (!lifetime.signal.aborted) { + approval = prompt?.body.resolution.state === 'pending' ? prompt.body : null + } }) .catch(() => undefined) .finally(deliver) @@ -182,4 +213,29 @@ export function chatWorkerTurnStopReporter( console.warn('[orchestration] chat worker stop report failed', error) } } + return { + onTurnAttention, + start: () => + schedule(() => { + void Promise.resolve() + .then(() => { + if (lifetime.signal.aborted) { + return + } + deps.openExistingDb?.() + return approvals.adopt() + }) + .catch((error: unknown) => { + console.warn('[orchestration] chat worker approval adoption failed', error) + }) + }, ADOPT_AFTER_MS), + stop: () => { + lifetime.abort() + for (const cancel of timers) { + cancel() + } + generations.clear() + previousCompletionAt.clear() + } + } } diff --git a/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts b/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts index 7e3286365f7..7727c26610c 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts @@ -24,13 +24,10 @@ export type TerminalWorkerTurnStopsDeps = WorkerTurnStopReportDeps & { getHandle: (paneKey: string) => string | null getProcessIncarnation: (handle: string) => string | null readScreen: (handle: string) => Promise - /** The pane's open approval Orca can answer; taking it marks it reported. */ - /** `reporting` is read after the wait; the approval is marked reported only when it holds. */ - takeOpenApproval: ( - paneKey: string, - dispatchId: string, - reporting: () => boolean - ) => Promise + /** The pane's open approval Orca can answer. */ + takeOpenApproval: (paneKey: string, dispatchId: string) => Promise + /** Called only once the approval's escalation went out. */ + markApprovalReported: (approvalId: string) => void } /** Report a terminal worker whose turn ended (or stopped at a prompt) while its Dispatch is open. */ @@ -80,19 +77,14 @@ export class TerminalWorkerTurnStops { // One report per approval; the screen shows Claude's own reason for asking. const approval = reason === 'needs-input' && before?.target.kind === 'local' - ? await this.deps.takeOpenApproval( - stop.paneKey, - before.target.dispatch.id, - // Read at the end of the dialog wait; a resume after it is caught by the re-read below. - () => this.stillStopped(stop) !== null - ) + ? await this.deps.takeOpenApproval(stop.paneKey, before.target.dispatch.id) : null // Both reads awaited: the worker may have resumed, reported, or been handed a new Dispatch since. const resolved = this.stillStopped(stop) if (!resolved) { return } - reportWorkerTurnStop( + const sent = reportWorkerTurnStop( resolved.db, resolved.target, { @@ -105,6 +97,9 @@ export class TerminalWorkerTurnStops { }, this.deps ) + if (approval && sent) { + this.deps.markApprovalReported(approval.approvalId) + } } private stillStopped(stop: PreparedStop) { diff --git a/src/main/runtime/orchestration/workers/turn-stops/worker-approval-text.ts b/src/main/runtime/orchestration/workers/turn-stops/worker-approval-text.ts new file mode 100644 index 00000000000..e31d60e2b6d --- /dev/null +++ b/src/main/runtime/orchestration/workers/turn-stops/worker-approval-text.ts @@ -0,0 +1,71 @@ +/** What a coordinator is told about a worker's permission prompt: who may answer, and how it closed. */ +import type { WorkerApprovalPayload } from '../../../../../shared/orchestration/approvals/worker-approval-payload' +import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' + +/** With the user's setting on: the coordinator may answer too, and the first answer wins. */ +export function describeCoordinatorAnswer( + { approvalId, allowedActions, personOnly, worker }: WorkerApprovalPayload, + { dispatchId, chatCoordinator }: { dispatchId: string; chatCoordinator?: boolean } +): string[] { + const shown = allowedActions.map((action) => (action === 'allow' ? 'Allow' : 'Deny')).join('/') + const where = worker.handle.startsWith(ORCA_SESSION_ADDRESS_PREFIX) + ? ` in the worker's chat` + : ` in the worker's terminal` + const approve = allowedActions.includes('allow') && !personOnly + const deny = allowedActions.includes('deny') + const commands = [ + ...(approve + ? [ + `\`orchestration approve --dispatch ${dispatchId} --prompt ${approvalId} --reason ""\`` + ] + : []), + ...(deny + ? [ + `\`orchestration deny --dispatch ${dispatchId} --prompt ${approvalId} --reason ""\`` + ] + : []) + ] + const how = approve + ? deny + ? 'You can approve or deny it, with a reason:' + : 'You can approve it, with a reason:' + : `${personOnly ? "The worker's agent lets only a person approve this one." : 'Orca cannot approve this one.'}${deny ? ' You can deny it, with a reason:' : ''}` + return [ + `The user has been shown ${shown}${chatCoordinator ? '' : where} too; whoever answers first wins. ${how}`, + ...commands, + 'Or leave it for the user and carry on with other work.' + ] +} + +const CLOSED_BY: Record['by'], string> = { + person: 'by a person in Orca', + coordinator: 'by the coordinator', + 'worker-chat': "in the worker's own chat", + 'worker-terminal': "in the worker's terminal", + auto: "by the worker's agent on its own (its 2:00 timeout)", + 'terminal-only': "for Orca; a person must answer it in the worker's terminal", + 'worker-ended': 'because its worker ended', + unknown: 'without an answer Orca can name' +} + +export function describeApprovalClosed(approval: WorkerApprovalPayload): string { + const { outcome, approvalId, worker } = approval + const decision = + outcome?.decision === 'allow' ? 'Allowed' : outcome?.decision === 'deny' ? 'Denied' : 'Closed' + return [ + `${decision} ${CLOSED_BY[outcome?.by ?? 'unknown']}: approval ${approvalId} of worker ${worker.handle} (${approval.summary.title}).`, + ...(outcome?.reason + ? [ + `Reason: ${outcome.reason}`, + ...(outcome.reasonDelivered || outcome.decision !== 'deny' + ? [] + : [ + "This agent's prompt takes no message, so the reason was sent to the worker as mail." + ]) + ] + : []), + outcome?.by === 'terminal-only' + ? "Tell the user to answer it in the worker's terminal." + : 'Nothing to do unless the worker stays stuck.' + ].join('\n') +} diff --git a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts index 234e8dc4289..277213225e3 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stop-report.ts @@ -12,6 +12,7 @@ import { escalateWorkerFailure } from '../reports/worker-failure-escalation' import { replaceDispatchCapabilities } from '../../terminal-authority/views/worker-terminal-redaction' import type { WorkerApprovalPayload } from '../../../../../shared/orchestration/approvals/worker-approval-payload' import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' +import { describeApprovalClosed, describeCoordinatorAnswer } from './worker-approval-text' // One screenful: enough to show the agent's last words or error banner without flooding the inbox. const LAST_OUTPUT_MAX_CHARS = 2_000 @@ -52,6 +53,8 @@ export type WorkerTurnStopReportDeps = { notify: (handle: string, messageType: string) => void /** Whether a mailbox reaches a chat coordinator, whose user sees the approval card; unknown reads as no. */ isChatMailbox?: (mailbox: string) => boolean + /** Whether the user lets coordinator agents allow this machine's workers' prompts; unknown reads as no. */ + coordinatorApprovals?: () => boolean } export function workerTurnStopDispatchId(target: WorkerTurnStopDispatch): string { @@ -78,6 +81,8 @@ type StopContext = { dispatchId: string chatCoordinator?: boolean taskReady?: boolean + /** The user lets the coordinator allow this machine's workers' prompts. */ + coordinatorApprovals?: boolean } function describeStop(stop: WorkerTurnStop, context: StopContext): string { @@ -126,7 +131,7 @@ function describeStop(stop: WorkerTurnStop, context: StopContext): string { // The reader runs its own CLI build, so name the subcommand, never an executable. function describeNextStep( stop: WorkerTurnStop, - { taskId, dispatchId, chatCoordinator, taskReady }: StopContext + { taskId, dispatchId, chatCoordinator, taskReady, coordinatorApprovals }: StopContext ): string[] { if (stop.settled === 'circuit_broken') { return [ @@ -147,9 +152,18 @@ function describeNextStep( const { summary, approvalId, allowedActions } = stop.approval const where = stop.from.startsWith(ORCA_SESSION_ADDRESS_PREFIX) ? 'chat' : 'terminal' const shown = allowedActions.map((action) => (action === 'allow' ? 'Allow' : 'Deny')).join('/') - return [ + const given = [ ...(summary.detail ? [summary.detail] : []), - ...(summary.reason ? [`Reason given: ${summary.reason}`] : []), + ...(summary.reason ? [`Reason given: ${summary.reason}`] : []) + ] + if (coordinatorApprovals) { + return [ + ...given, + ...describeCoordinatorAnswer(stop.approval, { dispatchId, chatCoordinator }) + ] + } + return [ + ...given, `${ chatCoordinator ? `The user has been shown ${shown} in your chat in Orca.` @@ -172,13 +186,14 @@ function describeNextStep( ] } -/** Tell the coordinator once that a worker is at rest or gone without reporting; never settles its Dispatch. */ +/** Tell the coordinator once that a worker is at rest or gone without reporting; never settles its Dispatch. + * True when the report is in the coordinator's mail. */ export function reportWorkerTurnStop( db: OrchestrationDb, target: WorkerTurnStopDispatch, stop: WorkerTurnStop, deps: WorkerTurnStopReportDeps -): void { +): boolean { const dispatchId = workerTurnStopDispatchId(target) // Waiting on mail, or a clean finish resting on its own question or helpers, is deliberate; going away never is. if ( @@ -189,7 +204,7 @@ export function reportWorkerTurnStop( rejectedReportInTurn(db, dispatchId, stop.turnStartedAt) || (target.kind === 'local' && db.hasOpenHelperDispatch(dispatchId))))) ) { - return + return false } // An idle finish answers the coordinator's mail the worker took, so it is news once per mail taken: a later // idle turn (a worker on its own schedule, or one the user is talking to) repeats what the coordinator was told. @@ -225,20 +240,22 @@ export function reportWorkerTurnStop( taskId: dispatch.task_id, dispatchId: dispatch.id, chatCoordinator: deps.isChatMailbox?.(dispatchReportMailbox(db, dispatch)) === true, - taskReady: db.getTask(dispatch.task_id)?.status === 'ready' + taskReady: db.getTask(dispatch.task_id)?.status === 'ready', + coordinatorApprovals: deps.coordinatorApprovals?.() === true }) }), payload: { taskId: dispatch.task_id, ...payload } }, deps.notify ) - return + // Stored is sent: a failed wake or an earlier send of this stop still reached the mailbox. + return db.getMessageById(id) !== undefined } // The Run home imports relayed worker mail into the coordinator's Run and wakes it. const { attachment } = target // A worker_done the home has not acknowledged yet is still a report. if (db.hasPendingFederatedWorkerReport(dispatchId)) { - return + return false } // The stable message id makes a repeated report of the same stop a no-op on both sides. try { @@ -253,7 +270,8 @@ export function reportWorkerTurnStop( body: describeStop(stop, { task: attachment.task_id, taskId: attachment.task_id, - dispatchId + dispatchId, + coordinatorApprovals: deps.coordinatorApprovals?.() === true }), type: 'escalation', priority: 'high', @@ -262,8 +280,10 @@ export function reportWorkerTurnStop( payload: JSON.stringify({ taskId: attachment.task_id, ...payload }) }) }) + return true } catch (error) { console.warn('[orchestration] failed to relay a worker stop report', dispatchId, error) + return false } } @@ -275,39 +295,6 @@ export function stopReportId(dispatchId: string, stopKey: string): string { .slice(0, 24)}` } -const CLOSED_BY: Record['by'], string> = { - person: 'by a person in Orca', - coordinator: 'by the coordinator', - 'worker-chat': "in the worker's own chat", - 'worker-terminal': "in the worker's terminal", - auto: "by the worker's agent on its own (its 2:00 timeout)", - 'terminal-only': "for Orca; a person must answer it in the worker's terminal", - 'worker-ended': 'because its worker ended', - unknown: 'without an answer Orca can name' -} - -function describeApprovalClosed(approval: WorkerApprovalPayload): string { - const { outcome, approvalId, worker } = approval - const decision = - outcome?.decision === 'allow' ? 'Allowed' : outcome?.decision === 'deny' ? 'Denied' : 'Closed' - return [ - `${decision} ${CLOSED_BY[outcome?.by ?? 'unknown']}: approval ${approvalId} of worker ${worker.handle} (${approval.summary.title}).`, - ...(outcome?.reason - ? [ - `Reason: ${outcome.reason}`, - ...(outcome.reasonDelivered - ? [] - : [ - "This agent's prompt takes no message, so the reason was sent to the worker as mail." - ]) - ] - : []), - outcome?.by === 'terminal-only' - ? "Tell the user to answer it in the worker's terminal." - : 'Nothing to do unless the worker stays stuck.' - ].join('\n') -} - /** The one closing line for a reported approval; the same stable id makes a second closer a no-op. */ export function reportWorkerApprovalClosed( db: OrchestrationDb, diff --git a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts index 013cca49ea0..4216c3d2094 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts @@ -66,7 +66,16 @@ function moved(from: 'working' | 'done', to: 'done' | 'needs-you'): AgentPaneCha } } -function terminal(ctx: ReturnType, current: { row: AgentStatusIpcPayload }) { +function terminal( + ctx: ReturnType, + current: { row: AgentStatusIpcPayload }, + approvals: Partial< + Pick< + ConstructorParameters[0], + 'takeOpenApproval' | 'markApprovalReported' + > + > = {} +) { return new TerminalWorkerTurnStops({ ...ctx.deps, readHookRow: () => current.row, @@ -77,6 +86,8 @@ function terminal(ctx: ReturnType, current: { row: AgentStatusIpcP getHandle: () => HANDLE, getProcessIncarnation: () => null, takeOpenApproval: async () => null, + markApprovalReported: () => {}, + ...approvals, readScreen: async () => ({ handle: HANDLE, status: 'running', @@ -111,6 +122,38 @@ describe('terminal worker turn stops', () => { expect(ctx.mail()).toHaveLength(0) }) + it.each([ + { waitingForMail: false, marked: ['apr_1'] }, + { waitingForMail: true, marked: [] } + ])( + 'marks an approval reported only when its escalation went out (%o)', + async ({ waitingForMail, marked }) => { + const ctx = setup() + if (waitingForMail) { + ctx.waiting.add(`dispatch:${ctx.dispatch.id}`) + } + const markApprovalReported = vi.fn() + const current = { row: hookRow({ state: 'working', agentType: 'claude' }) } + const stops = terminal(ctx, current, { + takeOpenApproval: async () => ({ + 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: ['allow', 'deny'] + }), + markApprovalReported + }) + current.row = hookRow({ state: 'blocked', agentType: 'claude' }) + stops.observe(moved('working', 'needs-you')) + await settle() + + expect(ctx.mail()).toHaveLength(marked.length) + expect(markApprovalReported.mock.calls.flat()).toEqual(marked) + } + ) + it('never mails a capability or credential carried in why a worker went away', () => { const ctx = setup() const capability = 'dcap_0123456789abcdefghijKLMN' @@ -225,10 +268,15 @@ describe('chat worker turn stops', () => { function chatWithTimers(ctx: ReturnType) { const timers: (() => void)[] = [] const status = 'idle' as const - const report = chatWorkerTurnStopReporter(ctx.deps, (run) => timers.push(run)) + const report = chatWorkerTurnStopReporter(ctx.deps, (run) => { + timers.push(run) + }) return { finish: (turnId: string) => - report(completion('success', turnId), () => ({ status, lastAssistantMessage: 'Done.' })), + report.onTurnAttention(completion('success', turnId), () => ({ + status, + lastAssistantMessage: 'Done.' + })), runTimers: () => { for (const run of timers.splice(0)) { run() @@ -252,4 +300,55 @@ describe('chat worker turn stops', () => { { subject: 'Worker stopped without reporting', payload: expect.stringContaining(followUp) } ]) }) + it('retiring the owner suppresses pending reports and permits a fresh owner to report', async () => { + const ctx = setup(formatOrcaSessionAddress(CHAT_SESSION)) + let finishRead!: (value: null) => void + const queued: (() => void)[] = [] + const owner = chatWorkerTurnStopReporter( + ctx.deps, + (run) => { + queued.push(run) + }, + () => + new Promise((resolve) => { + finishRead = resolve + }) + ) + const edge = completion('success') + if (edge.type !== 'completion') { + throw new Error('Expected completion') + } + owner.onTurnAttention(edge, () => ({ status: 'idle' })) + owner.onTurnAttention( + { + type: 'prompt', + prompt: { + scope: edge.completion.scope, + sessionId: CHAT_SESSION, + promptId: 'approval-retired', + raisedAt: 1 + } + }, + () => ({ status: 'attention' }) + ) + owner.stop() + finishRead(null) + for (const run of queued) { + run() + } + await Promise.resolve() + await Promise.resolve() + expect(ctx.mail()).toEqual([]) + expect(ctx.notify).not.toHaveBeenCalled() + + const live = chatWorkerTurnStopReporter(ctx.deps, (run) => { + queued.push(run) + }) + live.onTurnAttention(completion('success', 'fresh-turn'), () => ({ status: 'idle' })) + for (const run of queued.splice(0)) { + run() + } + expect(ctx.mail()).toMatchObject([{ subject: 'Worker stopped without reporting' }]) + live.stop() + }) }) diff --git a/src/main/runtime/push/desktop-push-service.test.ts b/src/main/runtime/push/desktop-push-service.test.ts index 9a0e2297b54..1d6b1bbf96e 100644 --- a/src/main/runtime/push/desktop-push-service.test.ts +++ b/src/main/runtime/push/desktop-push-service.test.ts @@ -1,11 +1,10 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import type { MobileNotificationEvent } from './notifications/runtime-mobile-notification-controller' import { DeviceRegistry } from '../rpc/server/pairing/device-registry' import { DesktopPushService } from './desktop-push-service' -import { PushRegisterThrottle } from './push-register-throttle' import { PushUnregisterOutbox } from './push-unregister-outbox' import { createPushHostKeypair } from './push-host-challenge-fixtures' @@ -21,7 +20,6 @@ function createService( deleteFails?: boolean /** Runs before each delete resolves, so a suite can queue work mid-flush. */ onDelete?: (registrationId: string) => void - now?: () => number } = {} ): { service: DesktopPushService @@ -30,6 +28,7 @@ function createService( deviceId: string deletes: string[] send: ReturnType + registerDevice: ReturnType dispatch: (event: MobileNotificationEvent) => void retries: { run: () => void; delayMs: number }[] } { @@ -76,8 +75,7 @@ function createService( client: client as never, scheduleRetry: (run, delayMs) => { retries.push({ run, delayMs }) - }, - ...(options.now ? { registerThrottle: new PushRegisterThrottle({ now: options.now }) } : {}) + } })! service.start() @@ -88,6 +86,7 @@ function createService( deviceId: device.deviceId, deletes, send: client.send, + registerDevice: client.registerDevice, dispatch: (event) => listener?.(event), retries } @@ -156,20 +155,6 @@ describe('DesktopPushService', () => { expect(harness.outbox.pending()).toEqual([]) }) - it('retries a failed drain on a capped backoff instead of waiting for a relaunch', async () => { - const harness = createService({ deleteFails: true }) - harness.outbox.enqueue({ registrationId: 'reg-stuck', deviceId: 'device-1' }) - - await harness.service.flushUnregisterOutbox() - expect(harness.retries.map((entry) => entry.delayMs)).toEqual([30_000]) - - harness.retries[0]?.run() - await new Promise((resolve) => setImmediate(resolve)) - expect(harness.deletes).toEqual(['reg-stuck', 'reg-stuck']) - expect(harness.retries.map((entry) => entry.delayMs)).toEqual([30_000, 60_000]) - expect(harness.outbox.pending()).toHaveLength(1) - }) - it('stops re-arming the retry once the service is stopped', async () => { const harness = createService({ deleteFails: true }) harness.outbox.enqueue({ registrationId: 'reg-stuck', deviceId: 'device-1' }) @@ -181,56 +166,6 @@ describe('DesktopPushService', () => { expect(harness.retries).toHaveLength(1) }) - - it('throttles a device that registers in a loop and lets it back in a minute later', async () => { - let clock = 1_700_000_000_000 - const harness = createService({ now: () => clock }) - const input = { deviceId: harness.deviceId, ...REGISTER_INPUT } - - for (let index = 0; index < 10; index++) { - expect(await harness.service.register(input)).toEqual({ - registered: true, - registrationId: 'reg-1' - }) - } - expect(await harness.service.register(input)).toEqual({ - registered: false, - reason: 'throttled' - }) - expect(harness.registry.getDevice(harness.deviceId)?.pushRegistration?.registrationId).toBe( - 'reg-1' - ) - - clock += 60_000 - expect(await harness.service.register(input)).toEqual({ - registered: true, - registrationId: 'reg-1' - }) - }) -}) - -it('renews a seven-day mobile lease only on explicit registration', async () => { - const now = 1_800_000_000_000 - const clock = vi.spyOn(Date, 'now').mockReturnValue(now) - const h = createService() - try { - await h.service.register({ - deviceId: h.deviceId, - ...REGISTER_INPUT - }) - expect(h.registry.getDevice(h.deviceId)?.pushRegistration?.expiresAt).toBe(now + 7 * 86400_000) - clock.mockReturnValue(now + 86400_000) - h.dispatch({ type: 'notification', source: 'terminal-bell', title: 'QA', body: 'QA' }) - expect(h.registry.getDevice(h.deviceId)?.pushRegistration?.expiresAt).toBe(now + 7 * 86400_000) - await h.service.register({ - deviceId: h.deviceId, - ...REGISTER_INPUT - }) - expect(h.registry.getDevice(h.deviceId)?.pushRegistration?.expiresAt).toBe(now + 8 * 86400_000) - } finally { - h.service.stop() - clock.mockRestore() - } }) it('does not claim success for missing registrations or failed gateway sends', async () => { @@ -249,3 +184,44 @@ it('does not claim success for missing registrations or failed gateway sends', a }) await expect(service.test(deviceId)).resolves.toEqual({ accepted: false, reason: 'rate_limited' }) }) + +describe('host mobile push privacy', () => { + afterEach(() => vi.unstubAllEnvs()) + + it.each(['disabled', 'invalid-mode'])( + 'blocks registration and delivery in %s mode while retaining cleanup', + async (mode) => { + vi.stubEnv('ORCA_MOBILE_PUSH_MODE', mode) + const h = createService() + try { + await expect( + h.service.register({ ...REGISTER_INPUT, deviceId: h.deviceId }) + ).resolves.toEqual({ registered: false, reason: 'gateway_rejected' }) + expect(h.registerDevice).not.toHaveBeenCalled() + h.registry.setPushRegistration(h.deviceId, { + registrationId: 'existing-reg', + filter: {}, + expiresAt: Number.MAX_SAFE_INTEGER + }) + h.dispatch({ + type: 'notification', + source: 'terminal-bell', + title: 'Private', + body: 'Context', + notificationSeq: 1, + notificationEpoch: 'epoch' + }) + await expect(h.service.test(h.deviceId)).resolves.toEqual({ + accepted: false, + reason: 'unavailable' + }) + expect(h.send).not.toHaveBeenCalled() + await h.service.unregister(h.deviceId) + await h.service.flushUnregisterOutbox() + expect(h.deletes).toEqual(['existing-reg']) + } finally { + h.service.stop() + } + } + ) +}) diff --git a/src/main/runtime/push/desktop-push-service.ts b/src/main/runtime/push/desktop-push-service.ts index 7b0c7b18a8b..5e89d05e688 100644 --- a/src/main/runtime/push/desktop-push-service.ts +++ b/src/main/runtime/push/desktop-push-service.ts @@ -12,6 +12,10 @@ import type { OrcaRuntimeRpcServer } from '../rpc/server/runtime-rpc' import { PushDispatcher } from './push-dispatcher' import { PushGatewayClient } from './push-gateway-client' import { PushRegisterThrottle } from './push-register-throttle' +import { + readMobilePushDeliveryMode, + type MobilePushDeliveryMode +} from './mobile-push-delivery-policy' import type { PushUnregisterOutbox } from './push-unregister-outbox' const OUTBOX_RETRY_BASE_MS = 30_000 @@ -38,6 +42,7 @@ export class DesktopPushService { private readonly outbox: PushUnregisterOutbox private readonly client: PushGatewayClient private readonly dispatcher: PushDispatcher + private readonly deliveryMode: MobilePushDeliveryMode private readonly registerThrottle: PushRegisterThrottle private readonly scheduleRetry: (run: () => void, delayMs: number) => void private unsubscribe: (() => void) | null = null @@ -58,7 +63,8 @@ export class DesktopPushService { this.registry = registry this.client = client this.outbox = options.runtimeRpc.getPushUnregisterOutbox() - this.dispatcher = new PushDispatcher({ client, registry }) + this.deliveryMode = readMobilePushDeliveryMode() + this.dispatcher = new PushDispatcher({ client, registry, deliveryMode: this.deliveryMode }) this.registerThrottle = options.registerThrottle ?? new PushRegisterThrottle() this.scheduleRetry = options.scheduleRetry ?? @@ -110,7 +116,7 @@ export class DesktopPushService { if (device?.scope !== 'mobile' || !registration || registration.expiresAt <= Date.now()) { return { accepted: false, reason: 'not_registered' } } - if (this.stopped) { + if (this.stopped || this.deliveryMode === 'disabled') { return { accepted: false, reason: 'unavailable' } } // Explicit tests target only the caller and bypass automatic activity filters. @@ -152,6 +158,9 @@ export class DesktopPushService { } async register(input: MobilePushRegisterInput): Promise { + if (this.deliveryMode === 'disabled') { + return { registered: false, reason: 'gateway_rejected' } + } if (this.registry.getDevice(input.deviceId)?.scope !== 'mobile') { return { registered: false, reason: 'not_mobile' } } diff --git a/src/main/runtime/push/mobile-push-delivery-policy.ts b/src/main/runtime/push/mobile-push-delivery-policy.ts new file mode 100644 index 00000000000..319ab5f54b9 --- /dev/null +++ b/src/main/runtime/push/mobile-push-delivery-policy.ts @@ -0,0 +1,13 @@ +export type MobilePushDeliveryMode = 'full' | 'disabled' + +export function readMobilePushDeliveryMode(): MobilePushDeliveryMode { + const value = process.env.ORCA_MOBILE_PUSH_MODE?.trim().toLowerCase() + if (!value || value === 'full') { + return 'full' + } + if (value === 'disabled') { + return 'disabled' + } + console.warn('[push] Invalid ORCA_MOBILE_PUSH_MODE; push delivery disabled') + return 'disabled' +} diff --git a/src/main/runtime/push/notifications/workspace-notification-mute.ts b/src/main/runtime/push/notifications/workspace-notification-mute.ts index affd0c3b84a..ed625e8ed09 100644 --- a/src/main/runtime/push/notifications/workspace-notification-mute.ts +++ b/src/main/runtime/push/notifications/workspace-notification-mute.ts @@ -7,7 +7,7 @@ import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { isHiddenByWorkspaceKindSwitch, type WorkspaceKindSwitches -} from '../../../../shared/worktree/workspace-kinds' +} from '../../../../shared/worktree/visibility/workspace-kinds' import { EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, isWorkspaceOwnedBySomeoneElse diff --git a/src/main/runtime/push/push-dispatcher.ts b/src/main/runtime/push/push-dispatcher.ts index b8ef5c16cd6..2af9ad98fe8 100644 --- a/src/main/runtime/push/push-dispatcher.ts +++ b/src/main/runtime/push/push-dispatcher.ts @@ -5,6 +5,7 @@ import { allowsMobilePushDelivery, mobilePushAlertContent } from '../../../share import type { MobileNotificationEvent } from './notifications/runtime-mobile-notification-controller' import type { PushGatewayClient, PushSendNotification } from './push-gateway-client' import { PushOutcomeCounters } from './push-outcome-counters' +import type { MobilePushDeliveryMode } from './mobile-push-delivery-policy' const PUSH_RETRY_DELAY_MS = 2_000 // Split requests at the gateway's per-send limit so extra paired phones still receive notifications. @@ -18,6 +19,7 @@ export type PushDispatcherRegistry = { type PushDispatcherOptions = { client: PushGatewayClient registry: PushDispatcherRegistry + deliveryMode?: MobilePushDeliveryMode /** Test seam: lets a suite drive the single retry without real time. */ scheduleRetry?: (run: () => void, delayMs: number) => void } @@ -30,11 +32,13 @@ export class PushDispatcher { private stopped = false private readonly client: PushGatewayClient private readonly registry: PushDispatcherRegistry + private readonly deliveryMode: MobilePushDeliveryMode private readonly scheduleRetry: (run: () => void, delayMs: number) => void constructor(options: PushDispatcherOptions) { this.client = options.client this.registry = options.registry + this.deliveryMode = options.deliveryMode ?? 'full' this.scheduleRetry = options.scheduleRetry ?? ((run, delayMs) => { @@ -53,7 +57,7 @@ export class PushDispatcher { } enqueue(event: MobileNotificationEvent): void { - if (this.stopped) { + if (this.stopped || this.deliveryMode === 'disabled') { return } try { diff --git a/src/main/runtime/push/push-gateway-session.ts b/src/main/runtime/push/push-gateway-session.ts index b062002032b..26ba19c1bd8 100644 --- a/src/main/runtime/push/push-gateway-session.ts +++ b/src/main/runtime/push/push-gateway-session.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { cancelUnreadResponseBody } from '../../lib/unread-response-body' import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import { deriveRelayHostId } from '../mobile-cloud-relay/relay-http-client' +import { deriveRelayHostId } from '../mobile-cloud-relay/director/relay-http-client' import { answerPushHostChallenge } from './push-host-proof' import { postPushGatewayJson, diff --git a/src/main/runtime/repositories/folder-workspace-deletion.ts b/src/main/runtime/repositories/folder-workspace-deletion.ts index e81bb5cb500..90611e41f27 100644 --- a/src/main/runtime/repositories/folder-workspace-deletion.ts +++ b/src/main/runtime/repositories/folder-workspace-deletion.ts @@ -65,7 +65,8 @@ export async function deleteFolderWorkspaceRow( deps.emitWorktreeLifecycle({ kind: 'removed', worktreeId: folderWorkspaceKey(folderWorkspaceId), - path: workspace.folderPath + path: workspace.folderPath, + ...(workspace.executionHostId ? { hostId: workspace.executionHostId } : {}) }) } } diff --git a/src/main/runtime/repositories/runtime-remote-fetch-controller.ts b/src/main/runtime/repositories/runtime-remote-fetch-controller.ts index 0f25d866094..36723d9d1dc 100644 --- a/src/main/runtime/repositories/runtime-remote-fetch-controller.ts +++ b/src/main/runtime/repositories/runtime-remote-fetch-controller.ts @@ -1,7 +1,7 @@ import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import type { GitExecOptions } from '../../git/command-runner/git-exec-options' import type { LocalGitExecOptions } from '../../git/refs/resolution/repo-default-base-ref' -import { GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS } from '../../../shared/git/fetch/git-fetch-auto-maintenance' +import { runRemoteTrackingBaseFetch } from './runtime-remote-tracking-base-fetch' import { getCanonicalRepoKey } from '../../git/repositories/canonical-repo-key' import type { CanonicalRepoKeyOptions } from '../../git/repositories/canonical-repo-key' import { @@ -10,6 +10,7 @@ import { } from '../../git/refs/maintenance/local-repo-ref-maintenance' import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' import { setBoundedMapEntry } from './remote-fetch-cache' +import { withRepositoryGitCause } from '../../git/repository-git-cause' export type RemoteFetchResult = { ok: true } | { ok: false; errorKind: 'git_error' } @@ -54,7 +55,7 @@ export class RuntimeRemoteFetchController { return resolved } - /** Exact-base fetch skips auto-maintenance and leaves loose refs; arm repo maintenance after quiet time, extended by each fetch. */ + /** Exact-base fetch skips auto-maintenance and leaves loose refs; retain one idle repo-maintenance opportunity. */ private armRefMaintenance(repoPath: string, gitOptions: LocalGitExecOptions): void { void this.getCanonicalRepoKey(repoPath, gitOptions) .then((key) => { @@ -120,11 +121,17 @@ export class RuntimeRemoteFetchController { return existing } const promise = this.enqueueRemoteFetch(key, () => - gitExecFileAsync(['fetch', remote], { - cwd: repoPath, - ...gitOptions, - timeout: REMOTE_FETCH_TIMEOUT_MS - }) + withRepositoryGitCause( + repoPath, + gitOptions, + { family: 'fetch', reason: 'remote-fetch', cache: 'miss' }, + () => + gitExecFileAsync(['fetch', remote], { + cwd: repoPath, + ...gitOptions, + timeout: REMOTE_FETCH_TIMEOUT_MS + }) + ) .then((): RemoteFetchResult => { this.rememberFreshFetchCompletedAt(key) return { ok: true } @@ -208,7 +215,12 @@ export class RuntimeRemoteFetchController { if (this.getFreshFetchCompletedAt(key) !== null) { return Promise.resolve({ ok: true }) } - return this.runExactBaseRefresh(repoPath, base, key, previewOptions, remainingMs) + return withRepositoryGitCause( + repoPath, + gitOptions, + { family: 'fetch', reason: 'conflict-preview', cache: 'refresh' }, + () => this.runExactBaseRefresh(repoPath, base, key, previewOptions, remainingMs) + ) }).finally(() => this.armRefMaintenance(repoPath, gitOptions)) })() try { @@ -227,21 +239,7 @@ export class RuntimeRemoteFetchController { gitOptions: LocalGitExecOptions & Pick, timeout = REMOTE_FETCH_TIMEOUT_MS ): Promise { - return gitExecFileAsync( - [ - ...GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS, - 'fetch', - '--no-tags', - base.remote, - `+refs/heads/${base.branch}:${base.ref}` - ], - { - cwd: repoPath, - ...gitOptions, - useConfiguredSshCommandForNetwork: true, - timeout - } - ) + return runRemoteTrackingBaseFetch(repoPath, base, gitOptions, timeout) .then((): RemoteFetchResult => { this.rememberFreshFetchCompletedAt(key) return { ok: true } diff --git a/src/main/runtime/repositories/runtime-remote-tracking-base-fetch.ts b/src/main/runtime/repositories/runtime-remote-tracking-base-fetch.ts new file mode 100644 index 00000000000..c58f0ad03a6 --- /dev/null +++ b/src/main/runtime/repositories/runtime-remote-tracking-base-fetch.ts @@ -0,0 +1,29 @@ +import { GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS } from '../../../shared/git/fetch/git-fetch-auto-maintenance' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' +import type { GitExecOptions } from '../../git/command-runner/git-exec-options' +import { withRepositoryGitCause } from '../../git/repository-git-cause' +import type { RemoteTrackingBase } from './runtime-remote-fetch-controller' + +export function runRemoteTrackingBaseFetch( + repoPath: string, + base: RemoteTrackingBase, + gitOptions: Omit, + timeout: number +): Promise<{ stdout: string; stderr: string }> { + return withRepositoryGitCause( + repoPath, + gitOptions, + { family: 'fetch', reason: 'base-refresh', cache: 'miss' }, + () => + gitExecFileAsync( + [ + ...GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS, + 'fetch', + '--no-tags', + base.remote, + `+refs/heads/${base.branch}:${base.ref}` + ], + { cwd: repoPath, ...gitOptions, useConfiguredSshCommandForNetwork: true, timeout } + ) + ) +} diff --git a/src/main/runtime/repositories/runtime-repository-command-surface.ts b/src/main/runtime/repositories/runtime-repository-command-surface.ts index 4bf48c0edf9..b57328ef114 100644 --- a/src/main/runtime/repositories/runtime-repository-command-surface.ts +++ b/src/main/runtime/repositories/runtime-repository-command-surface.ts @@ -70,6 +70,7 @@ export type RuntimeRepositoryCommandSurface = { showRepo: RuntimeRepositorySettingsController['show'] setRepoBaseRef: RuntimeRepositorySettingsController['setBaseRef'] updateRepo: RuntimeRepositorySettingsController['update'] + setRepoHidden: RuntimeRepositorySettingsController['setHidden'] removeProject: RuntimeRepositorySettingsController['remove'] reorderRepos: RuntimeRepositorySettingsController['reorder'] getRepoBaseRefDefault: RuntimeRepositoryRefQueries['getDefault'] @@ -166,6 +167,7 @@ export function installRuntimeRepositoryCommandSurface( showRepo: settings.show.bind(settings), setRepoBaseRef: settings.setBaseRef.bind(settings), updateRepo: settings.update.bind(settings), + setRepoHidden: settings.setHidden.bind(settings), removeProject: settings.remove.bind(settings), reorderRepos: settings.reorder.bind(settings), getRepoBaseRefDefault: refs.getDefault.bind(refs), diff --git a/src/main/runtime/repositories/runtime-repository-issue-command.test.ts b/src/main/runtime/repositories/runtime-repository-issue-command.test.ts index 7c963a2ce80..44562d512d4 100644 --- a/src/main/runtime/repositories/runtime-repository-issue-command.test.ts +++ b/src/main/runtime/repositories/runtime-repository-issue-command.test.ts @@ -6,7 +6,7 @@ import { RuntimeRepositoryIssueCommand } from './runtime-repository-issue-comman const mocks = vi.hoisted(() => ({ localCheck: vi.fn() })) -vi.mock('../../git/source-control/check-ignored-paths', () => ({ +vi.mock('../../git/source-control/ignores/check-ignored-paths', () => ({ checkIgnoredPaths: mocks.localCheck })) diff --git a/src/main/runtime/repositories/runtime-repository-ref-queries.ts b/src/main/runtime/repositories/runtime-repository-ref-queries.ts index c47baeb4fc8..c5151d72932 100644 --- a/src/main/runtime/repositories/runtime-repository-ref-queries.ts +++ b/src/main/runtime/repositories/runtime-repository-ref-queries.ts @@ -40,7 +40,7 @@ export class RuntimeRepositoryRefQueries { if (getRepoRoutingConnectionId(repo)) { throw new Error('This project is not served by this host.') } - const page = await searchRemoteRefPage(repo.path, query, effectiveLimit) + const page = await searchRemoteRefPage(repo.path, query, effectiveLimit, includeQualifiedRefs) return { ...page, refs: page.refDetails.map((row) => row.refName), namespace } } // Unserved SSH hosts report no refs; never search local files for them. diff --git a/src/main/runtime/repositories/runtime-repository-settings-controller.ts b/src/main/runtime/repositories/runtime-repository-settings-controller.ts index 157632613ef..b312766d2f2 100644 --- a/src/main/runtime/repositories/runtime-repository-settings-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-settings-controller.ts @@ -1,8 +1,9 @@ import { isFolderRepo } from '../../../shared/repo-kind' +import { isRepoHidden } from '../../../shared/hidden-projects' import { commitProvenRepoKindChange } from '../../workspaces/catalog/folder-repo-git-conversion' import type { Repo } from '../../../shared/repo-types' import type { RuntimeRepoSelector } from '../workspaces/catalog/runtime-repo-selector' -import type { GhAccountBinding } from '../../../shared/github/account-binding' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import type { RuntimeStore } from '../construction/runtime-store-contract' @@ -56,7 +57,9 @@ type RepositoryUpdates = Partial< > & { projectGroupOrder?: number | null sourceControlAi?: Repo['sourceControlAi'] | null + workspaceCleanupPolicy?: Repo['workspaceCleanupPolicy'] | null externalWorktreeDiscoverySuppressedAt?: Repo['externalWorktreeDiscoverySuppressedAt'] | null + hiddenAt?: Repo['hiddenAt'] | null /** Only `null` clears; `omitUndefined` drops a stripped (undefined) field so it never unbinds. */ ghAccount?: GhAccountBinding | null } @@ -100,6 +103,22 @@ export class RuntimeRepositorySettingsController { return updated } + /** View-only: hiding stops nothing, so terminals, agents and automations keep running. */ + async setHidden(repoSelector: RuntimeRepoSelector, hidden: boolean): Promise { + const store = this.requireStore() + const repo = await this.deps.resolveRepo(repoSelector) + if (isRepoHidden(repo) === hidden) { + return repo + } + assertWslMoveRepoWritable(store, repo) + const updated = store.updateRepo(repo, { hiddenAt: hidden ? Date.now() : null }) + if (!updated) { + throw new Error('repo_not_found') + } + this.deps.notifyReposChanged() + return updated + } + async update(repoSelector: string, updates: RepositoryUpdates): Promise { const store = this.requireStore() const repo = await this.deps.resolveRepo(repoSelector) @@ -114,6 +133,9 @@ export class RuntimeRepositorySettingsController { ) { sanitizedUpdates.externalWorktreeDiscoverySuppressedAt = undefined } + if ('hiddenAt' in updates && updates.hiddenAt === null) { + sanitizedUpdates.hiddenAt = undefined + } if ('sourceControlAi' in updates && updates.sourceControlAi === null) { sanitizedUpdates.sourceControlAi = null } diff --git a/src/main/runtime/rpc/browser-error-response.ts b/src/main/runtime/rpc/browser-error-response.ts deleted file mode 100644 index 115aa44d12a..00000000000 --- a/src/main/runtime/rpc/browser-error-response.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { BrowserError } from '../../browser/browser-error' -import type { RpcEnvelopeMeta, RpcFailure } from './core' -import { errorResponse, mapRuntimeError } from './errors' - -// BrowserError.code uses the browser namespace, separate from the runtime message-code allowlist. -export function mapBrowserError(id: string, meta: RpcEnvelopeMeta, error: unknown): RpcFailure { - if (error instanceof Error && 'code' in error && typeof error.code === 'string') { - const data = error instanceof BrowserError ? error.data : undefined - return errorResponse(id, meta, error.code, error.message, data) - } - return mapRuntimeError(id, meta, error) -} diff --git a/src/main/runtime/rpc/callers/active-call.ts b/src/main/runtime/rpc/callers/active-call.ts new file mode 100644 index 00000000000..5f2f49adf70 --- /dev/null +++ b/src/main/runtime/rpc/callers/active-call.ts @@ -0,0 +1,40 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { isOrcaSessionId } from '../../../../shared/orca-session-address' +import { isAgentRpcCaller, type RpcCallerIdentity } from './rpc-caller-identity' + +type ActiveRpcCall = { + caller: RpcCallerIdentity | undefined + agentSessionId: string | undefined +} + +// Lets code far below a handler tell an agent's CLI call from a person's relayed input. +const activeCall = new AsyncLocalStorage() + +export function runWithActiveRpcCaller( + caller: RpcCallerIdentity | undefined, + run: () => T, + claimedAgentSessionId?: string +): T { + // Only this host's CLI can name a chat here; as in the handoff card, other callers act for a person. + const agentSessionId = + isAgentRpcCaller(caller) && claimedAgentSessionId && isOrcaSessionId(claimedAgentSessionId) + ? claimedAgentSessionId + : undefined + return activeCall.run({ caller, agentSessionId }, run) +} + +/** The caller of the RPC handler this code runs under; undefined outside any handler. */ +export function getActiveRpcCaller(): RpcCallerIdentity | undefined { + return activeCall.getStore()?.caller +} + +/** The chat whose agent sent this call, as its CLI claims it: display attribution, never authority. */ +export function getActiveRpcAgentSessionId(): string | undefined { + return activeCall.getStore()?.agentSessionId +} + +/** Re-enters this call later, for work a queue runs from inside another caller's call. */ +export function captureActiveRpcCall(): (run: () => T) => T { + const call = activeCall.getStore() + return (run) => (call ? activeCall.run(call, run) : activeCall.exit(run)) +} diff --git a/src/main/runtime/rpc/host-own-phone.ts b/src/main/runtime/rpc/callers/host-own-phone.ts similarity index 89% rename from src/main/runtime/rpc/host-own-phone.ts rename to src/main/runtime/rpc/callers/host-own-phone.ts index c5052ba72f7..909b376b20a 100644 --- a/src/main/runtime/rpc/host-own-phone.ts +++ b/src/main/runtime/rpc/callers/host-own-phone.ts @@ -1,4 +1,4 @@ -import type { RpcContext } from './core' +import type { RpcContext } from '../core' /** This host's own phone shares its Workspace options; delegated phones, paired desktops and web clients retain their own view (PAIRING_LOCAL_UI_FIELDS). */ export function isHostOwnPhone( diff --git a/src/main/runtime/rpc/rpc-caller-identity.ts b/src/main/runtime/rpc/callers/rpc-caller-identity.ts similarity index 95% rename from src/main/runtime/rpc/rpc-caller-identity.ts rename to src/main/runtime/rpc/callers/rpc-caller-identity.ts index 11ac7794b9c..0f726a4238e 100644 --- a/src/main/runtime/rpc/rpc-caller-identity.ts +++ b/src/main/runtime/rpc/callers/rpc-caller-identity.ts @@ -1,6 +1,6 @@ /** Transport-proven identity, never request params, controls durable ledger namespaces and whose view a launch moves. */ -import type { RpcDispatchStreamingOptions } from './dispatcher-stream-options' +import type { RpcDispatchStreamingOptions } from '../dispatch/dispatcher-stream-options' export type RpcCallerIdentity = /** The `orca` CLI over the runtime socket, and the in-process bridges that relay it. */ diff --git a/src/main/runtime/rpc/rpc-caller-scope.ts b/src/main/runtime/rpc/callers/rpc-caller-scope.ts similarity index 95% rename from src/main/runtime/rpc/rpc-caller-scope.ts rename to src/main/runtime/rpc/callers/rpc-caller-scope.ts index 649ddc5844b..9295458139f 100644 --- a/src/main/runtime/rpc/rpc-caller-scope.ts +++ b/src/main/runtime/rpc/callers/rpc-caller-scope.ts @@ -1,5 +1,5 @@ /** Transport stamps proven scope; unstamped calls are local desktop/owner CLI. Non-owner methods require an explicitly granted permission. */ -import { MOBILE_RPC_METHOD_ALLOWLIST } from './server/runtime-rpc-mobile-method-allowlist' +import { MOBILE_RPC_METHOD_ALLOWLIST } from '../server/runtime-rpc-mobile-method-allowlist' import type { RpcMethodPermission, RuntimeDeviceGrant } from './rpc-method-permission' export type RpcCallerScope = diff --git a/src/main/runtime/rpc/rpc-method-permission.ts b/src/main/runtime/rpc/callers/rpc-method-permission.ts similarity index 100% rename from src/main/runtime/rpc/rpc-method-permission.ts rename to src/main/runtime/rpc/callers/rpc-method-permission.ts diff --git a/src/main/runtime/rpc/runtime-client-capabilities.ts b/src/main/runtime/rpc/callers/runtime-client-capabilities.ts similarity index 95% rename from src/main/runtime/rpc/runtime-client-capabilities.ts rename to src/main/runtime/rpc/callers/runtime-client-capabilities.ts index 92195a4c83e..ba9b747fde1 100644 --- a/src/main/runtime/rpc/runtime-client-capabilities.ts +++ b/src/main/runtime/rpc/callers/runtime-client-capabilities.ts @@ -1,4 +1,4 @@ -import type { RuntimeCapability } from '../../../shared/protocol-version' +import type { RuntimeCapability } from '../../../../shared/protocol-version' export function parseRuntimeClientCapabilities(value: unknown): readonly RuntimeCapability[] { if (!Array.isArray(value) || value.length > 64) { diff --git a/src/main/runtime/rpc/workspace-creator-context.ts b/src/main/runtime/rpc/callers/workspace-creator-context.ts similarity index 86% rename from src/main/runtime/rpc/workspace-creator-context.ts rename to src/main/runtime/rpc/callers/workspace-creator-context.ts index fcbdad4d1eb..242b86442c6 100644 --- a/src/main/runtime/rpc/workspace-creator-context.ts +++ b/src/main/runtime/rpc/callers/workspace-creator-context.ts @@ -1,5 +1,5 @@ -import type { WorkspaceCreatorProvenance } from '../../../shared/worktree/types' -import type { RpcContext } from './core' +import type { WorkspaceCreatorProvenance } from '../../../../shared/worktree/types' +import type { RpcContext } from '../core' export function resolveRpcWorkspaceCreatorProvenance( context: Pick< diff --git a/src/main/runtime/rpc/mobile-clipboard-image-provenance.ts b/src/main/runtime/rpc/clipboard/mobile-clipboard-image-provenance.ts similarity index 100% rename from src/main/runtime/rpc/mobile-clipboard-image-provenance.ts rename to src/main/runtime/rpc/clipboard/mobile-clipboard-image-provenance.ts diff --git a/src/main/runtime/rpc/rpc-clipboard-text-validation.ts b/src/main/runtime/rpc/clipboard/rpc-clipboard-text-validation.ts similarity index 86% rename from src/main/runtime/rpc/rpc-clipboard-text-validation.ts rename to src/main/runtime/rpc/clipboard/rpc-clipboard-text-validation.ts index 3e3715993b8..7379e7d75cb 100644 --- a/src/main/runtime/rpc/rpc-clipboard-text-validation.ts +++ b/src/main/runtime/rpc/clipboard/rpc-clipboard-text-validation.ts @@ -2,8 +2,8 @@ import { CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR, assertClipboardTextWriteWithinLimitWithYield, isClipboardTextWriteTooLargeError -} from '../../../shared/clipboard-text' -import { InvalidArgumentError } from './core' +} from '../../../../shared/clipboard-text' +import { InvalidArgumentError } from '../core' export async function assertRpcClipboardTextWriteWithinLimit(text: string): Promise { try { diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index f135d2ae3f8..dd2b33a6c97 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -1,9 +1,9 @@ -import type { RuntimeClientCapabilities } from './runtime-client-capabilities' +import type { RuntimeClientCapabilities } from './callers/runtime-client-capabilities' import type { ZodError, ZodType } from 'zod' import type { TerminalStreamFrame } from '../../../shared/terminal/stream/terminal-stream-protocol' import type { OrcaRuntimeService } from '../orca-runtime' import type { OrchestrationCompatibilityCallerAuthority } from '../orchestration/terminal-authority/orchestration-compatibility-authority' -import type { StructuredAgentCliSourceEvidence } from '../../native-chat/structured-agent-cli-source' +import type { StructuredAgentCliSourceEvidence } from '../../native-chat/conversation-adoption/structured-agent-cli-source' import type { DeviceCredentialInstalled, PairingGetEndpointsParams, @@ -21,11 +21,11 @@ import type { } from '../../../shared/delegated-mobile-device-contract' import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' -import type { RpcCallerIdentity } from './rpc-caller-identity' +import type { RpcCallerIdentity } from './callers/rpc-caller-identity' import type { OrcadPeerDesktopsResult } from '../../../shared/orcad-peer-desktops-contract' -import type { RpcBinarySender } from './rpc-binary-sender' -import type { RpcMethodPermission } from './rpc-method-permission' -import type { OrcadFeatureRequirement } from './orcad-feature-readiness' +import type { RpcBinarySender } from './transports/rpc-binary-sender' +import type { RpcMethodPermission } from './callers/rpc-method-permission' +import type { OrcadFeatureRequirement } from './startup/orcad-readiness' import { runsOrchestrationAccessCheck, type OrchestrationMethodAccessDeclaration @@ -128,6 +128,8 @@ export type RpcContext = { pairedDeviceParentId?: string // Host-assigned transport identity; absent means the caller could not be established. caller?: RpcCallerIdentity + // Set only by the in-process plugin host: the plugin a call acts for, kept as provenance. + plugin?: { key: string; name: string; assertActive?: () => void } // Only phones receive truncated payloads; undefined in-process callers remain unclipped. clientKind?: 'mobile' | 'runtime' // Session-tab streams re-project with .current; other readers use the request-time clientCapabilities. diff --git a/src/main/runtime/rpc/dispatcher-request-parsing.ts b/src/main/runtime/rpc/dispatch/dispatcher-request-parsing.ts similarity index 77% rename from src/main/runtime/rpc/dispatcher-request-parsing.ts rename to src/main/runtime/rpc/dispatch/dispatcher-request-parsing.ts index fb4b6b7e5a4..2f4918e7bb6 100644 --- a/src/main/runtime/rpc/dispatcher-request-parsing.ts +++ b/src/main/runtime/rpc/dispatch/dispatcher-request-parsing.ts @@ -1,12 +1,12 @@ -import { getCompiledSchema } from '../../schema-validation/zod-schema-compilation' +import { getCompiledSchema } from '../../../schema-validation/zod-schema-compilation' import { formatZodError, type RpcAnyMethodDeclaration, type RpcEnvelopeMeta, type RpcRequest, type RpcResponse -} from './core' -import { invalidArgumentResponse } from './dispatcher-error-response' +} from '../core' +import { invalidArgumentResponse } from '../responses/dispatcher-error-response' export function parseRpcRequestParams( request: RpcRequest, diff --git a/src/main/runtime/rpc/dispatcher-stream-options.ts b/src/main/runtime/rpc/dispatch/dispatcher-stream-options.ts similarity index 85% rename from src/main/runtime/rpc/dispatcher-stream-options.ts rename to src/main/runtime/rpc/dispatch/dispatcher-stream-options.ts index 21b77e43870..647aac18b7a 100644 --- a/src/main/runtime/rpc/dispatcher-stream-options.ts +++ b/src/main/runtime/rpc/dispatch/dispatcher-stream-options.ts @@ -1,9 +1,9 @@ -import type { OrcaRuntimeService } from '../orca-runtime' -import { captureStructuredAgentCliSource } from '../../native-chat/structured-agent-cli-source' -import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' -import { isRegistrationFencedUnsubscribe, type RpcContext, type RpcRequest } from './core' -import { resolveRpcCallerIdentity } from './rpc-caller-identity' -import type { RpcCallerScope } from './rpc-caller-scope' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { captureStructuredAgentCliSource } from '../../../native-chat/conversation-adoption/structured-agent-cli-source' +import type { OrchestrationEntryCaller } from '../../orchestration/addressing/orchestration-caller-identity' +import { isRegistrationFencedUnsubscribe, type RpcContext, type RpcRequest } from '../core' +import { resolveRpcCallerIdentity } from '../callers/rpc-caller-identity' +import type { RpcCallerScope } from '../callers/rpc-caller-scope' export type RpcDispatchStreamingOptions = Pick< RpcContext, @@ -14,6 +14,7 @@ export type RpcDispatchStreamingOptions = Pick< | 'pairedDeviceId' | 'pairedDeviceParentId' | 'caller' + | 'plugin' | 'clientKind' | 'clientCapabilities' | 'capabilitySource' @@ -35,6 +36,8 @@ export type RpcDispatchStreamingOptions = Pick< /** In-process callers: runs after admission and feature waits, just before the handler; a throw * refuses the call (a plugin revoked while its call waited). */ beforeInvoke?: () => void + /** In-process callers: sees a unary handler's own throw before it becomes an error answer. */ + onHandlerError?: (error: unknown) => void } export function rpcContextFromTransport( @@ -66,6 +69,7 @@ export function rpcContextFromTransport( pairedDeviceId: options?.pairedDeviceId, pairedDeviceParentId: options?.pairedDeviceParentId, caller: resolveRpcCallerIdentity(options), + plugin: options?.plugin, clientKind: options?.clientKind, clientCapabilities: options?.clientCapabilities, capabilitySource: options?.capabilitySource, diff --git a/src/main/runtime/rpc/dispatcher-streaming-feature-emitter.ts b/src/main/runtime/rpc/dispatch/dispatcher-streaming-feature-emitter.ts similarity index 77% rename from src/main/runtime/rpc/dispatcher-streaming-feature-emitter.ts rename to src/main/runtime/rpc/dispatch/dispatcher-streaming-feature-emitter.ts index c46c8f3bd6f..6da446e476d 100644 --- a/src/main/runtime/rpc/dispatcher-streaming-feature-emitter.ts +++ b/src/main/runtime/rpc/dispatch/dispatcher-streaming-feature-emitter.ts @@ -1,7 +1,7 @@ -import type { FeatureInteractionId } from '../../../shared/feature-interaction-catalog' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from './core' -import { successResponse } from './errors' +import type { FeatureInteractionId } from '../../../../shared/feature-interaction-catalog' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from '../core' +import { successResponse } from '../responses/rpc-response' import { recordRuntimeFeatureInteraction } from './runtime-feature-interaction' export function createDispatcherStreamingFeatureEmitter( diff --git a/src/main/runtime/rpc/rpc-params-type-parity.ts b/src/main/runtime/rpc/dispatch/rpc-params-type-parity.ts similarity index 87% rename from src/main/runtime/rpc/rpc-params-type-parity.ts rename to src/main/runtime/rpc/dispatch/rpc-params-type-parity.ts index 11d9829a994..dbc21a21ed1 100644 --- a/src/main/runtime/rpc/rpc-params-type-parity.ts +++ b/src/main/runtime/rpc/dispatch/rpc-params-type-parity.ts @@ -1,9 +1,9 @@ import type { RpcMethodName, RpcParams -} from '../../../shared/rpc-contract/rpc-params-catalog.generated' -import type { RpcAnyMethodDeclaration } from './core' -import type { ALL_RPC_METHODS } from './methods/rpc-method-registry' +} from '../../../../shared/rpc-contract/rpc-params-catalog.generated' +import type { RpcAnyMethodDeclaration } from '../core' +import type { ALL_RPC_METHODS } from '../methods/rpc-method-registry' type RegisteredMethod = (typeof ALL_RPC_METHODS)[number] diff --git a/src/main/runtime/rpc/rpc-request-admission-prologue.ts b/src/main/runtime/rpc/dispatch/rpc-request-admission-prologue.ts similarity index 84% rename from src/main/runtime/rpc/rpc-request-admission-prologue.ts rename to src/main/runtime/rpc/dispatch/rpc-request-admission-prologue.ts index d6942601062..8e99cb252e4 100644 --- a/src/main/runtime/rpc/rpc-request-admission-prologue.ts +++ b/src/main/runtime/rpc/dispatch/rpc-request-admission-prologue.ts @@ -5,26 +5,26 @@ import type { RpcRequest, RpcResponse, RpcStreamingMethod -} from './core' -import { errorResponse } from './errors' -import type { OrcaRuntimeService } from '../orca-runtime' -import { orchestrationMigrationFence } from './orchestration-contract-fence' +} from '../core' +import { errorResponse } from '../responses/rpc-response' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { orchestrationMigrationFence } from '../orchestration/compatibility/orchestration-contract-fence' import { runtimeSourceFence } from './runtime-source-admission' import type { RpcDispatchStreamingOptions } from './dispatcher-stream-options' -import { mapDispatcherError } from './dispatcher-error-response' +import { mapDispatcherError } from '../responses/dispatcher-error-response' import { parseRpcRequestParams } from './dispatcher-request-parsing' import { denyRpcMethodForCaller, OWNER_RPC_CALLER_SCOPE, type RpcCallerScope -} from './rpc-caller-scope' +} from '../callers/rpc-caller-scope' import { needsOrchestrationCallerResolution, resolveOrchestrationSessionCaller, type ResolvedOrchestrationRequest -} from './orchestration-session-caller' -import { admitOrchestrationPeerCall } from './orchestration-peer-caller' -import { waitForRestoredWorkerCallerIdentity } from './worker-caller-identity-restore-wait' +} from '../orchestration/callers/orchestration-session-caller' +import { admitOrchestrationPeerCall } from '../orchestration/callers/orchestration-peer-caller' +import { waitForRestoredWorkerCallerIdentity } from '../orchestration/callers/worker-caller-identity-restore-wait' type RpcRequestAdmissionDeps = { runtime: OrcaRuntimeService diff --git a/src/main/runtime/rpc/runtime-feature-interaction.ts b/src/main/runtime/rpc/dispatch/runtime-feature-interaction.ts similarity index 87% rename from src/main/runtime/rpc/runtime-feature-interaction.ts rename to src/main/runtime/rpc/dispatch/runtime-feature-interaction.ts index 9153309b34a..9bf21be2a27 100644 --- a/src/main/runtime/rpc/runtime-feature-interaction.ts +++ b/src/main/runtime/rpc/dispatch/runtime-feature-interaction.ts @@ -1,6 +1,6 @@ -import type { FeatureInteractionId } from '../../../shared/feature-interaction-catalog' -import { isBrowserPaneUiRuntimeRpcParams } from '../../../shared/runtime-rpc-feature-interaction-source' -import type { OrcaRuntimeService } from '../orca-runtime' +import type { FeatureInteractionId } from '../../../../shared/feature-interaction-catalog' +import { isBrowserPaneUiRuntimeRpcParams } from '../../../../shared/runtime-rpc-feature-interaction-source' +import type { OrcaRuntimeService } from '../../orca-runtime' export function getRuntimeFeatureInteractionId( method: string, diff --git a/src/main/runtime/rpc/dispatch/runtime-source-admission.test.ts b/src/main/runtime/rpc/dispatch/runtime-source-admission.test.ts new file mode 100644 index 00000000000..534ad56d4e5 --- /dev/null +++ b/src/main/runtime/rpc/dispatch/runtime-source-admission.test.ts @@ -0,0 +1,86 @@ +import { randomUUID } from 'node:crypto' +import { z } from 'zod' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { publishHostDescriptor } from '../../hosts/platform-probe/host-descriptor' +import { defineMethod, type RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' + +const SOURCE_A = '11111111-1111-4111-8111-111111111111' +const SOURCE_B = '22222222-2222-4222-8222-222222222222' + +describe('runtime source admission', () => { + const published: string[] = [] + + afterEach(() => { + for (const runtimeId of published.splice(0)) { + publishHostDescriptor(runtimeId, null) + } + }) + + function createHarness(installationId: string | null = SOURCE_A) { + const id = randomUUID() + const runtime = { getRuntimeId: () => id } + const runtimeId = runtime.getRuntimeId() + if (installationId) { + publishHostDescriptor(runtimeId, { installationId }) + published.push(runtimeId) + } + const effect = vi.fn(() => ({ sent: true })) + const dispatcher = new RpcDispatcher({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture handler is effect; admission and response metadata read only getRuntimeId. + runtime: runtime as OrcaRuntimeService, + methods: [ + defineMethod({ + name: 'terminal.send', + permission: 'workspace', + params: z.object({ text: z.string() }), + handler: effect + }) + ] + }) + const request = (expectedRuntimeSource?: unknown): RpcRequest => ({ + id: 'rpc_1', + authToken: 'token', + method: 'terminal.send', + params: { text: 'hi' }, + ...(expectedRuntimeSource === undefined ? {} : { expectedRuntimeSource }) + }) + return { runtimeId, dispatcher, effect, request } + } + + it('refuses a request meant for another profile before the handler runs', async () => { + const { runtimeId, dispatcher, effect, request } = createHarness() + + const response = await dispatcher.dispatch(request({ sourceId: SOURCE_B, runtimeId })) + + expect(response).toMatchObject({ ok: false, error: { code: 'runtime_source_mismatch' } }) + expect(effect).not.toHaveBeenCalled() + }) + + it('refuses a request verified against another runtime of the same profile', async () => { + const { dispatcher, effect, request } = createHarness() + + const response = await dispatcher.dispatch( + request({ sourceId: SOURCE_A, runtimeId: 'runtime-other' }) + ) + + expect(response).toMatchObject({ ok: false, error: { code: 'runtime_source_mismatch' } }) + expect(effect).not.toHaveBeenCalled() + }) + + it('fences the streaming transport too', async () => { + const { runtimeId, dispatcher, effect, request } = createHarness() + const replies: string[] = [] + + await dispatcher.dispatchStreaming(request({ sourceId: SOURCE_B, runtimeId }), (reply) => + replies.push(reply) + ) + + expect(JSON.parse(replies[0])).toMatchObject({ + ok: false, + error: { code: 'runtime_source_mismatch' } + }) + expect(effect).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/rpc/runtime-source-admission.ts b/src/main/runtime/rpc/dispatch/runtime-source-admission.ts similarity index 84% rename from src/main/runtime/rpc/runtime-source-admission.ts rename to src/main/runtime/rpc/dispatch/runtime-source-admission.ts index 77b9117adbc..38dc1b7aecd 100644 --- a/src/main/runtime/rpc/runtime-source-admission.ts +++ b/src/main/runtime/rpc/dispatch/runtime-source-admission.ts @@ -1,7 +1,7 @@ -import { ExpectedRuntimeSourceSchema } from '../../../shared/runtime-rpc-envelope' -import { getPublishedHostDescriptor } from '../hosts/platform-probe/host-descriptor' -import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from './core' -import { errorResponse } from './errors' +import { ExpectedRuntimeSourceSchema } from '../../../../shared/runtime-rpc-envelope' +import { getPublishedHostDescriptor } from '../../hosts/platform-probe/host-descriptor' +import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from '../core' +import { errorResponse } from '../responses/rpc-response' /** Refuses, before any handler runs, a request whose client expects another runtime. */ export function runtimeSourceFence(request: RpcRequest, meta: RpcEnvelopeMeta): RpcResponse | null { diff --git a/src/main/runtime/rpc/unused-default-rpc-methods.test-fixture.ts b/src/main/runtime/rpc/dispatch/testing/unused-default-rpc-methods.test-fixture.ts similarity index 84% rename from src/main/runtime/rpc/unused-default-rpc-methods.test-fixture.ts rename to src/main/runtime/rpc/dispatch/testing/unused-default-rpc-methods.test-fixture.ts index c40253666b0..6250cbc56a5 100644 --- a/src/main/runtime/rpc/unused-default-rpc-methods.test-fixture.ts +++ b/src/main/runtime/rpc/dispatch/testing/unused-default-rpc-methods.test-fixture.ts @@ -1,5 +1,5 @@ import { afterEach, expect, vi } from 'vitest' -import type { RpcAnyMethodDeclaration } from './core' +import type { RpcAnyMethodDeclaration } from '../../core' const unusedDefaultRpcMethods = vi.hoisted(() => { const methods: RpcAnyMethodDeclaration[] = [] @@ -11,7 +11,7 @@ const unusedDefaultRpcMethods = vi.hoisted(() => { return { methods, consumption } }) -vi.mock('./methods/rpc-method-registry', () => ({ +vi.mock('../../methods/rpc-method-registry', () => ({ ALL_RPC_METHODS: unusedDefaultRpcMethods.methods })) diff --git a/src/main/runtime/rpc/dispatcher-request-parsing.test.ts b/src/main/runtime/rpc/dispatcher-request-parsing.test.ts deleted file mode 100644 index 6db462dc9fd..00000000000 --- a/src/main/runtime/rpc/dispatcher-request-parsing.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { z } from 'zod' -import { defineMethod, type RpcEnvelopeMeta, type RpcRequest } from './core' -import { parseRpcRequestParams } from './dispatcher-request-parsing' - -const META: RpcEnvelopeMeta = { runtimeId: 'runtime-1' } - -function request(params: unknown): RpcRequest { - return { id: 'req-1', authToken: 'token', method: 'test.parse', params } -} - -describe('parseRpcRequestParams', () => { - it('parses repeated valid requests through the compiled schema', () => { - const method = defineMethod({ - name: 'test.parse', - permission: 'workspace', - params: z.object({ requestId: z.string().min(1), count: z.number().int().nonnegative() }), - handler: () => null - }) - - expect(parseRpcRequestParams(request({ requestId: 'a', count: 1 }), method, META)).toEqual({ - value: { requestId: 'a', count: 1 } - }) - expect(parseRpcRequestParams(request({ requestId: 'b', count: 2 }), method, META)).toEqual({ - value: { requestId: 'b', count: 2 } - }) - }) - - it('preserves validation errors from the runtime fallback', () => { - const method = defineMethod({ - name: 'test.parse', - permission: 'workspace', - params: z.object({ count: z.number().int('Count must be an integer') }), - handler: () => null - }) - - expect(parseRpcRequestParams(request({ count: 1.5 }), method, META)).toMatchObject({ - error: { - id: 'req-1', - _meta: { runtimeId: 'runtime-1' }, - ok: false, - error: { code: 'invalid_argument', message: 'Count must be an integer' } - } - }) - }) - - it('keeps transform output when compilation falls back', () => { - const method = defineMethod({ - name: 'test.parse', - permission: 'workspace', - params: z.object({ value: z.string().transform((value) => value.toUpperCase()) }), - handler: () => null - }) - - expect(parseRpcRequestParams(request({ value: 'ok' }), method, META)).toEqual({ - value: { value: 'OK' } - }) - }) -}) diff --git a/src/main/runtime/rpc/dispatcher.ts b/src/main/runtime/rpc/dispatcher.ts index d91d728cd5b..e6f9c840bff 100644 --- a/src/main/runtime/rpc/dispatcher.ts +++ b/src/main/runtime/rpc/dispatcher.ts @@ -10,7 +10,7 @@ import { type RpcStreamingMethod } from './core' -import { successResponse } from './errors' +import { successResponse } from './responses/rpc-response' import { withoutMethodsThisHostDoesNotServe } from './methods/terminal/session-terminal-scrollback' import { emulatorProbe, emulatorProbeError } from '../../emulator/emulator-probe' import type { OrcaRuntimeService } from '../orca-runtime' @@ -20,19 +20,19 @@ import { getOrchestrationMutationExecutor, type DurableMutationInvocation, type OrchestrationMutationExecutor -} from './orchestration-mutation-executor' -import { OrchestrationLegacyCompatibility } from './orchestration-legacy-compatibility' +} from './orchestration/mutations/orchestration-mutation-executor' +import { OrchestrationLegacyCompatibility } from './orchestration/compatibility/orchestration-legacy-compatibility' import { rpcContextFromTransport, type RpcDispatchStreamingOptions -} from './dispatcher-stream-options' -import { mapDispatcherError } from './dispatcher-error-response' -import { createDispatcherStreamingFeatureEmitter } from './dispatcher-streaming-feature-emitter' -import { recordRuntimeFeatureInteraction } from './runtime-feature-interaction' -import type { RpcCallerScope } from './rpc-caller-scope' -import { runWithActiveRpcCaller } from './rpc-active-caller' -import { admitRpcRequest } from './rpc-request-admission-prologue' -import { resolveOrcadFeatureRequirement, rpcMethodFeatureWait } from './orcad-feature-readiness' +} from './dispatch/dispatcher-stream-options' +import { mapDispatcherError } from './responses/dispatcher-error-response' +import { createDispatcherStreamingFeatureEmitter } from './dispatch/dispatcher-streaming-feature-emitter' +import { recordRuntimeFeatureInteraction } from './dispatch/runtime-feature-interaction' +import type { RpcCallerScope } from './callers/rpc-caller-scope' +import { runWithActiveRpcCaller } from './callers/active-call' +import { admitRpcRequest } from './dispatch/rpc-request-admission-prologue' +import { resolveOrcadFeatureRequirement, rpcMethodFeatureWait } from './startup/orcad-readiness' import { routeRemoteOwnedCall } from '../orchestration/federation/remote-owned/remote-owned-route' export type DispatcherOptions = { @@ -94,6 +94,7 @@ export class RpcDispatcher { options?.beforeInvoke?.() return successResponse(request.id, meta, await this.invokeUnary(admission, options)) } catch (error) { + options?.onHandlerError?.(error) if (probeEmulator) { emulatorProbeError(`rpc ${request.method}`, error, { params: request.params diff --git a/src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts b/src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts deleted file mode 100644 index 49573b521f6..00000000000 --- a/src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { WebSocket } from 'ws' -import type { RpcBinarySendResult } from './rpc-binary-sender' -import { E2EEChannel, type E2EEChannelOptions } from './e2ee-channel' -import { - deriveSharedKey, - decrypt, - decryptBytes, - encrypt, - generateKeyPair -} from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { createMobileE2EEOutboundMemoryBudget } from './mobile-e2ee-outbound-memory-budget' -import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits' - -const trackMock = vi.hoisted(() => vi.fn()) - -vi.mock('../../telemetry/client', () => ({ track: trackMock })) - -// Legacy terminal.subscribe has no seq/resync: congestion must queue text and binary replies in order, never drop them. - -function publicKeyToBase64(key: Uint8Array): string { - return Buffer.from(key).toString('base64') -} - -function createMockWs() { - const sent: (string | Buffer)[] = [] - return { - OPEN: 1 as const, - readyState: 1, - bufferedAmount: 0, - send: vi.fn((data: string | Buffer) => { - sent.push(data) - }), - close: vi.fn(), - sent - } -} - -function setup(overrides?: Partial) { - const serverKeys = generateKeyPair() - const clientKeys = generateKeyPair() - const ws = createMockWs() - const onError = vi.fn() - const channel = new E2EEChannel(ws as unknown as WebSocket, { - serverSecretKey: serverKeys.secretKey, - resolveAuthenticatedDevice: (token) => - token === 'valid-token' - ? { - deviceId: 'device-1', - deviceToken: token, - scope: 'mobile', - clientId: token, - callerFingerprint: 'test-fingerprint', - credentialRevision: 0 - } - : null, - onReady: vi.fn(), - onError, - ...overrides - }) - const sharedKey = deriveSharedKey(clientKeys.secretKey, serverKeys.publicKey) - channel.handleRawMessage( - JSON.stringify({ type: 'e2ee_hello', publicKeyB64: publicKeyToBase64(clientKeys.publicKey) }) - ) - channel.handleRawMessage( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), sharedKey) - ) - return { channel, ws, sharedKey, onError } -} - -function emitReply(ctx: ReturnType, payload: string): void { - ctx.channel.onMessage((_plaintext, encryptedReply) => { - encryptedReply(payload) - }) - ctx.channel.handleRawMessage(encrypt('{"id":"x","method":"status.get"}', ctx.sharedKey)) -} - -describe('E2EE text reply backpressure', () => { - beforeEach(() => { - vi.useFakeTimers() - trackMock.mockReset() - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('still closes an oversized reply when telemetry throws', () => { - const ctx = setup() - trackMock.mockImplementationOnce(() => { - throw new Error('telemetry unavailable') - }) - - expect(() => - emitReply(ctx, 'x'.repeat(REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + 1)) - ).not.toThrow() - expect(trackMock).toHaveBeenCalledWith('remote_outbound_budget_close', { emitter: 'size' }) - expect(ctx.onError).toHaveBeenCalledWith(1013, 'Outbound reply buffer overflow') - }) - - it('rejects aggregate queue growth across independently backpressured sockets', () => { - const outboundMemoryBudget = createMobileE2EEOutboundMemoryBudget({ - maxBufferedBytes: 1_000, - maxQueuedBytes: 150, - maxQueuedFrames: 10 - }) - const first = setup({ outboundMemoryBudget }) - const second = setup({ outboundMemoryBudget }) - first.ws.bufferedAmount = 1_001 - second.ws.bufferedAmount = 1_001 - - emitReply(first, 'x'.repeat(40)) - emitReply(second, 'x'.repeat(40)) - - expect(first.onError).not.toHaveBeenCalled() - expect(second.onError).toHaveBeenCalledWith(1013, 'Outbound reply buffer overflow') - expect(trackMock).toHaveBeenCalledWith('remote_outbound_budget_close', { - emitter: 'queue' - }) - first.channel.destroy() - expect(outboundMemoryBudget.evidence().queuedBytes).toBe(0) - }) -}) - -describe('E2EE legacy binary reply backpressure', () => { - beforeEach(() => { - vi.useFakeTimers() - trackMock.mockReset() - }) - afterEach(() => { - vi.useRealTimers() - }) - - function decodeSent(ctx: ReturnType, frame: string | Buffer): string { - return typeof frame === 'string' - ? decrypt(frame, ctx.sharedKey)! - : `binary:${Buffer.from(decryptBytes(new Uint8Array(frame), ctx.sharedKey)!).toString()}` - } - - // Legacy binary terminal frames lack gap detection; loss or reordering corrupts the phone screen. - it('holds binary replies in one order with text while the outbound budget is full', () => { - const outboundMemoryBudget = createMobileE2EEOutboundMemoryBudget({ maxBufferedBytes: 1_000 }) - const ctx = setup({ outboundMemoryBudget }) - const baseline = ctx.ws.sent.length - ctx.ws.bufferedAmount = 1_001 - const accepted: RpcBinarySendResult[] = [] - - ctx.channel.onMessage((_plaintext, encryptedReply, encryptedBinaryReply) => { - encryptedReply('{"seq":1}') - accepted.push(encryptedBinaryReply(Buffer.from('2'))) - encryptedReply('{"seq":3}') - accepted.push(encryptedBinaryReply(Buffer.from('4'))) - }) - ctx.channel.handleRawMessage(encrypt('{"id":"x","method":"terminal.subscribe"}', ctx.sharedKey)) - expect(ctx.ws.sent.length).toBe(baseline) - - ctx.ws.bufferedAmount = 0 - vi.runOnlyPendingTimers() - - expect(accepted).toEqual([true, true]) - expect(ctx.ws.sent.slice(baseline).map((frame) => decodeSent(ctx, frame))).toEqual([ - '{"seq":1}', - 'binary:2', - '{"seq":3}', - 'binary:4' - ]) - expect(ctx.onError).not.toHaveBeenCalled() - }) - - it('closes for budget instead of dropping when queued binary overflows', () => { - const outboundMemoryBudget = createMobileE2EEOutboundMemoryBudget({ - maxBufferedBytes: 1_000, - maxQueuedBytes: 150 - }) - const ctx = setup({ outboundMemoryBudget }) - ctx.ws.bufferedAmount = 1_001 - - ctx.channel.onMessage((_plaintext, _encryptedReply, encryptedBinaryReply) => { - encryptedBinaryReply(new Uint8Array(100)) - encryptedBinaryReply(new Uint8Array(100)) - }) - ctx.channel.handleRawMessage(encrypt('{"id":"x","method":"terminal.subscribe"}', ctx.sharedKey)) - - expect(ctx.onError).toHaveBeenCalledWith(1013, 'Outbound reply buffer overflow') - expect(trackMock).toHaveBeenCalledWith('remote_outbound_budget_close', { emitter: 'queue' }) - }) - - it('drops a backlogged lossy binary reply instead of queueing it, then sends once drained', () => { - const ctx = setup() - const baseline = ctx.ws.sent.length - ctx.ws.bufferedAmount = 9 * 1024 * 1024 - const accepted: RpcBinarySendResult[] = [] - ctx.channel.onMessage((_plaintext, _encryptedReply, encryptedBinaryReply) => { - accepted.push(encryptedBinaryReply(Buffer.from('frame'), { dropWhenBacklogged: true })) - }) - const request = encrypt('{"id":"x","method":"browser.screencast"}', ctx.sharedKey) - ctx.channel.handleRawMessage(request) - ctx.ws.bufferedAmount = 0 - vi.runOnlyPendingTimers() - expect(ctx.ws.sent.length).toBe(baseline) - - ctx.channel.handleRawMessage(request) - expect(accepted).toEqual(['backlogged', true]) - expect(ctx.ws.sent.slice(baseline).map((frame) => decodeSent(ctx, frame))).toEqual([ - 'binary:frame' - ]) - expect(ctx.onError).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/rpc/e2ee-channel.test.ts b/src/main/runtime/rpc/e2ee-channel.test.ts deleted file mode 100644 index 0ba494fffd8..00000000000 --- a/src/main/runtime/rpc/e2ee-channel.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' -import type { WebSocket } from 'ws' -import { E2EEChannel, type E2EEChannelOptions } from './e2ee-channel' -import { - generateKeyPair, - deriveSharedKey, - encrypt, - decrypt, - encryptBytes -} from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' - -function publicKeyToBase64(key: Uint8Array): string { - return Buffer.from(key).toString('base64') -} - -function createMockWs() { - const sent: string[] = [] - return { - OPEN: 1 as const, - readyState: 1, - send: vi.fn((data: string) => sent.push(data)), - close: vi.fn(), - sent - } -} - -function setup(overrides?: Partial) { - const serverKeys = generateKeyPair() - const clientKeys = generateKeyPair() - const ws = createMockWs() - const onReady = vi.fn() - const onError = vi.fn() - - const channel = new E2EEChannel(ws as unknown as WebSocket, { - serverSecretKey: serverKeys.secretKey, - resolveAuthenticatedDevice: (token) => - token === 'valid-token' - ? { - deviceId: 'device-1', - deviceToken: token, - scope: 'mobile', - clientId: token, - callerFingerprint: 'test-fingerprint', - credentialRevision: 0 - } - : null, - onReady, - onError, - ...overrides - }) - - return { channel, ws, serverKeys, clientKeys, onReady, onError } -} - -function doHandshake(ctx: ReturnType) { - const hello = JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: publicKeyToBase64(ctx.clientKeys.publicKey) - }) - ctx.channel.handleRawMessage(hello) - const sharedKey = deriveSharedKey(ctx.clientKeys.secretKey, ctx.serverKeys.publicKey) - ctx.channel.handleRawMessage( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), sharedKey) - ) - return sharedKey -} - -describe('E2EEChannel', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - describe('handshake', () => { - it('completes handshake with valid encrypted auth', () => { - const ctx = setup() - doHandshake(ctx) - - expect(ctx.onReady).toHaveBeenCalledWith(ctx.channel, { - deviceId: 'device-1', - deviceToken: 'valid-token', - scope: 'mobile', - clientId: 'valid-token', - callerFingerprint: 'test-fingerprint', - credentialRevision: 0 - }) - expect(ctx.onError).not.toHaveBeenCalled() - expect(ctx.channel.deviceToken).toBe('valid-token') - - const readyMsg = JSON.parse(ctx.ws.sent[0]!) - expect(readyMsg).toEqual({ type: 'e2ee_ready' }) - const authMsg = decrypt( - ctx.ws.sent[1]!, - deriveSharedKey(ctx.clientKeys.secretKey, ctx.serverKeys.publicKey) - ) - expect(JSON.parse(authMsg!)).toEqual({ type: 'e2ee_authenticated' }) - }) - - it('does not authenticate from plaintext hello alone', () => { - const ctx = setup() - ctx.channel.handleRawMessage( - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: publicKeyToBase64(ctx.clientKeys.publicKey) - }) - ) - - expect(ctx.onReady).not.toHaveBeenCalled() - expect(JSON.parse(ctx.ws.sent[0]!)).toEqual({ type: 'e2ee_ready' }) - }) - - it('rejects an auth frame encrypted to a stale desktop key', () => { - const ctx = setup() - ctx.channel.handleRawMessage( - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: publicKeyToBase64(ctx.clientKeys.publicKey) - }) - ) - const staleServer = generateKeyPair() - const staleSharedKey = deriveSharedKey(ctx.clientKeys.secretKey, staleServer.publicKey) - - ctx.channel.handleRawMessage( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), staleSharedKey) - ) - - expect(ctx.onError).toHaveBeenCalledOnce() - expect(ctx.onError).toHaveBeenCalledWith(4001, 'Unauthorized') - expect(ctx.onReady).not.toHaveBeenCalled() - }) - }) - - describe('post-handshake messaging', () => { - it('decrypts and forwards messages', () => { - const ctx = setup() - const sharedKey = doHandshake(ctx) - const received: string[] = [] - - ctx.channel.onMessage((plaintext) => { - received.push(plaintext) - }) - - const request = '{"id":"rpc-1","method":"status.get"}' - ctx.channel.handleRawMessage(encrypt(request, sharedKey)) - - expect(received).toEqual([request]) - }) - - it('provides encrypted reply function', () => { - const ctx = setup() - const sharedKey = doHandshake(ctx) - - ctx.channel.onMessage((_plaintext, encryptedReply) => { - encryptedReply('{"id":"rpc-1","ok":true}') - }) - - ctx.channel.handleRawMessage(encrypt('{"id":"rpc-1","method":"status.get"}', sharedKey)) - - const replyEncrypted = ctx.ws.sent[2]! - const replyPlain = decrypt(replyEncrypted, sharedKey) - expect(replyPlain).toBe('{"id":"rpc-1","ok":true}') - }) - - it('decrypts and forwards binary messages after authentication', () => { - const ctx = setup() - const sharedKey = doHandshake(ctx) - const received: Uint8Array[] = [] - - ctx.channel.onBinaryMessage((bytes) => { - received.push(bytes) - }) - - ctx.channel.handleRawMessage(encryptBytes(new Uint8Array([1, 2, 3]), sharedKey)) - - expect([...received[0]!]).toEqual([1, 2, 3]) - }) - - it('silently drops messages with wrong key', () => { - const ctx = setup() - doHandshake(ctx) - const received: string[] = [] - - ctx.channel.onMessage((plaintext) => { - received.push(plaintext) - }) - - const attackerKey = deriveSharedKey(generateKeyPair().secretKey, generateKeyPair().publicKey) - ctx.channel.handleRawMessage(encrypt('attack', attackerKey)) - - expect(received).toEqual([]) - }) - }) - - describe('destroy', () => { - it('clears state and stops forwarding', () => { - const ctx = setup() - const sharedKey = doHandshake(ctx) - const received: string[] = [] - - ctx.channel.onMessage((plaintext) => { - received.push(plaintext) - }) - - ctx.channel.destroy() - ctx.channel.handleRawMessage(encrypt('after destroy', sharedKey)) - - expect(received).toEqual([]) - }) - - // Streaming handlers retain this reply closure after disconnect; destroy clears its key, so late emits must not encrypt with null. - it('does not throw when streaming emit fires after destroy', () => { - const ctx = setup() - const sharedKey = doHandshake(ctx) - const sentBefore = ctx.ws.sent.length - - let capturedReply: ((response: string) => void) | null = null - ctx.channel.onMessage((_plaintext, encryptedReply) => { - capturedReply = encryptedReply - }) - - ctx.channel.handleRawMessage(encrypt('subscribe-trigger', sharedKey)) - expect(capturedReply).not.toBeNull() - - ctx.channel.destroy() - - const callLateEmit = () => capturedReply?.('late streaming frame') - expect(callLateEmit).not.toThrow() - expect(ctx.ws.sent.length).toBe(sentBefore) - }) - }) -}) diff --git a/src/main/runtime/rpc/e2ee-crypto.test.ts b/src/main/runtime/rpc/e2ee-crypto.test.ts deleted file mode 100644 index 824a2e09868..00000000000 --- a/src/main/runtime/rpc/e2ee-crypto.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' -import nacl from 'tweetnacl' -import { - generateKeyPair, - deriveSharedKey, - decrypt, - decryptBytes -} from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { MOBILE_E2EE_LEGACY_FIXTURE } from '../../../shared/remote-runtime/e2ee/mobile-e2ee-legacy-fixtures' - -describe('e2ee-crypto', () => { - it('preserves the captured legacy key and text/binary frame bytes', () => { - const fixture = MOBILE_E2EE_LEGACY_FIXTURE - const server = nacl.box.keyPair.fromSecretKey(fixture.serverSecretKey) - const client = nacl.box.keyPair.fromSecretKey(fixture.clientSecretKey) - const shared = deriveSharedKey(client.secretKey, server.publicKey) - - expect(Buffer.from(server.publicKey).toString('base64')).toBe(fixture.serverPublicKeyB64) - expect(Buffer.from(client.publicKey).toString('base64')).toBe(fixture.clientPublicKeyB64) - expect(Buffer.from(shared).toString('hex')).toBe(fixture.sharedKeyHex) - expect(decrypt(fixture.authFrameB64, shared)).toBe(fixture.authPlaintext) - expect(decryptBytes(Buffer.from(fixture.binaryFrameHex, 'hex'), shared)).toEqual( - fixture.binaryPlaintext - ) - }) - - it('decrypt returns null for truncated data', () => { - const shared = deriveSharedKey(generateKeyPair().secretKey, generateKeyPair().publicKey) - expect(decrypt('dG9vc2hvcnQ=', shared)).toBeNull() - }) -}) diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts deleted file mode 100644 index 36dc87c63aa..00000000000 --- a/src/main/runtime/rpc/errors.ts +++ /dev/null @@ -1,317 +0,0 @@ -import { BranchSwitchCollisionError } from '../../git/worktrees/checkout/branch-switch-target' -import { SparsePresetValidationError } from '../../../shared/worktree/sparse-preset-failure' -import { - RECIPE_VM_REFUSAL_CODES, - RecipeVmWakeUnavailableError -} from '../../../shared/remote-runtime/recipe-vm-wake' -import { RecipeWorkspaceRemovalError } from '../../../shared/recipe-host-removal' -import { formatTerminalStartFailure } from '../../../shared/terminal/pty/lifecycle/terminal-start-failure' -// Centralize the runtimeId envelope and error-code contracts that clients use for decisions and display. -import { AGENT_LAUNCH_SURFACE_UNAVAILABLE_CODE } from '../../../shared/agent-launch/contracts/agent-launch-surface' -import { - agentSessionRefusalReference, - isAgentSessionRefusalError, - type AgentSessionRefusalError -} from '../../../shared/agent-session/failures/agent-session-wire-refusals' -import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from './core' -import { CONNECTOR_REPLY_ERROR_CODES } from '../../../shared/rpc-contract/connector-params' -import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES } from '../../../shared/orchestration/orchestration-session-caller-codes' -import { ORCHESTRATION_FEDERATION_ERROR_CODES } from '../../../shared/orchestration/orchestration-federation-error-codes' -import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery' -import { COMPUTER_ERROR_CODES } from '../../../shared/computer-use-runtime-types' -import { TerminalSplitOutcomeError } from '../../../shared/workspace-layout/terminal-split-outcome' -import { WslHostWindowsDriveRefusalError } from '../../../shared/wsl-host-windows-drive-refusal' -import { wslDistroHoldRpcFailure } from '../../../shared/wsl-distro-stopped-hold' -import { LINEAR_ERROR_CODES } from '../../../shared/linear/agent-access' -import { AGENT_SESSION_RPC_ERROR_CODES } from '../../../shared/agent-session/agent-session-host-authority' -import { ARTIFACT_SHARING_DISABLED_CODE } from '../../../shared/artifacts/artifact-sharing-gate' -import { AGENT_SKILL_SHARING_DISABLED_CODE } from '../../../shared/agent-skill-sharing-gate' -import { SHARING_UNAVAILABLE_ON_HOST_CODE } from '../../../shared/sharing-unavailable-on-host' -import { - AGENT_SKILL_NOT_SHAREABLE_CODE, - AGENT_SKILL_SELECTOR_AMBIGUOUS_CODE, - AGENT_SKILL_SELECTOR_NOT_FOUND_CODE, - AGENT_SKILL_SHARING_BUSY_CODE, - AGENT_SKILL_BUNDLE_NAME_TAKEN_CODE, - AGENT_SKILL_SHARING_UNSUPPORTED_ENVIRONMENT_CODE -} from '../../../shared/agent-skill-sharing-contract' -import { - SKILL_INSTALL_RPC_ERROR_CODE, - classifySkillInstallFailureCode -} from '../../../shared/skill-install-failure' -import { PLUGIN_CLI_ERROR_CODES } from '../../../shared/plugins/approval/plugin-cli-approval' -import { GIT_DIFF_TOO_LARGE_CODE } from '../../../shared/git/diff/git-diff-transport-budget' -import { AUTOMATION_OWNER_CONFLICT_CODES } from '../../../shared/automations/ownership/automation-owner-conflict' -import { ARCHIVE_HOOK_FAILED_REMOVAL_CODE } from '../../../shared/worktree/archive-hook-removal-gate' -import { NESTED_WORKER_DEPTH_EXCEEDED_CODE } from '../../../shared/orchestration/workers/nested-worker-depth' -import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../shared/project-runtime-repair-message' -import { - WORKTREE_CREATE_COLLISION_CODE, - WORKTREE_CREATE_EXACT_NAME_TAKEN_CODE -} from '../../../shared/new-workspace/worktree-create-collision' -import { AGENT_LAUNCH_PANE_ALREADY_LIVE_CODE } from '../../../shared/agent-launch/contracts/agent-launch-pane-already-live' -import { AGENT_LAUNCH_SESSION_ALREADY_EXISTS_CODE } from '../../../shared/agent-launch/contracts/agent-launch-session-already-exists' -import { AGENT_LAUNCH_TAB_CLOSED_CODE } from '../../../shared/agent-launch/contracts/agent-launch-tab-closed' -import { AGENT_LAUNCH_TARGET_FORBIDDEN_CODE } from '../../../shared/agent-launch/contracts/agent-launch-target-forbidden' -import { - parseTerminalSpawnDeferral, - TERMINAL_SPAWN_DEFERRED_CODE -} from '../../../shared/terminal/pty/admission/spawn-admission-contract' - -export function successResponse(id: string, meta: RpcEnvelopeMeta, result: unknown): RpcSuccess { - return { id, ok: true, result, _meta: meta } -} - -export function errorResponse( - id: string, - meta: RpcEnvelopeMeta, - code: string, - message: string, - data?: unknown -): RpcFailure { - return { - id, - ok: false, - error: data === undefined ? { code, message } : { code, message, data }, - _meta: meta - } -} - -// Runtime plain Error messages are stable codes; changing this allowlist also requires updating the CLI. -const RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ - WORKTREE_CREATE_COLLISION_CODE, - AGENT_LAUNCH_PANE_ALREADY_LIVE_CODE, - AGENT_LAUNCH_SESSION_ALREADY_EXISTS_CODE, - AGENT_LAUNCH_TAB_CLOSED_CODE, - AGENT_LAUNCH_TARGET_FORBIDDEN_CODE, - 'agent_launch_replay_unsupported', - 'runtime_unavailable', - 'chat_fork_source_unavailable', - 'chat_fork_runtime_incompatible', - 'chat_fork_anchor_changed', - 'selector_not_found', - 'selector_ambiguous', - 'terminal_handle_stale', - 'terminal_not_writable', - 'terminal_exited', - 'terminal_gone', - 'terminal_tab_close_timeout', - 'terminal_tab_not_found', - 'terminal_tab_pinned', - 'agent_prompt_blocked', - 'agent_prompt_stalled', - 'no_active_terminal', - 'repo_not_found', - 'timeout', - 'invalid_limit', - 'request_aborted', - 'remote_update_manual_required', - 'remote_update_not_available', - 'remote_update_not_downloaded', - 'connectors_disabled', - 'external_conversation_not_found', - ...CONNECTOR_REPLY_ERROR_CODES, - ...AGENT_SESSION_RPC_ERROR_CODES -]) - -const COMPUTER_PASSTHROUGH_CODES: ReadonlySet = new Set(Object.values(COMPUTER_ERROR_CODES)) -const LINEAR_PASSTHROUGH_CODES: ReadonlySet = new Set(LINEAR_ERROR_CODES) -const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ - ...RECIPE_VM_REFUSAL_CODES, - WORKTREE_CREATE_COLLISION_CODE, - WORKTREE_CREATE_EXACT_NAME_TAKEN_CODE, - AGENT_LAUNCH_SURFACE_UNAVAILABLE_CODE, - 'worktree_id_requires_full_path', - // A workspace selector's choices ride in data; a plain Error('selector_ambiguous') keeps the bare code. - 'selector_ambiguous', - 'run_not_found', - 'run_home_unreachable', - 'run_required', - 'stable_pane_required', - 'consumer_fenced', - 'task_not_found', - 'task_not_startable', - 'inject_rejected', - 'dispatch_not_found', - 'dispatch_run_mismatch', - 'task_run_mismatch', - 'terminal_not_found', - // This live agent session never had a terminal; terminal_handle_stale would falsely imply one died. - 'terminal_unsupported_for_agent_session', - 'recipient_ambiguous', - 'recipient_run_mismatch', - 'dispatch_inactive', - // Its start failed before an agent ran, so there is no output to read. - 'worker_never_started', - 'worker_identity_changed', - 'cursor_invalid', - 'cursor_dispatch_mismatch', - 'source_changed', - 'transcript_required', - ...ORCHESTRATION_FEDERATION_ERROR_CODES, - 'dispatch_capability_invalid', - 'agent_unconfigured', - 'worker_prompt_too_large', - 'terminal_worktree_mismatch', - 'terminal_is_coordinator', - // Another open Dispatch holds the terminal; data names it and says no effects were applied. - 'terminal_busy', - // The user chose Keep open; only they can undo it, so a coordinator must not retry blindly. - 'terminal_kept_open', - 'worker_cannot_coordinate_own_run', - 'worker_cannot_take_over_run', - 'request_mismatch', - 'mutation_ledger_full', - 'legacy_read_only', - 'orchestration_migration_required', - 'operation_unknown', - // A re-made pairing: work through the earlier one is not recovered, so the caller is told plainly. - 'server_pairing_changed', - 'dispatch_preamble_undelivered', - 'question_not_found', - 'answer_conflict', - // A worker's permission prompt: only a person allows; Orca answers chat prompts only, while open. - 'approval_requires_person', - 'approval_not_open', - 'approval_option_missing', - 'approval_refused', - 'stale_delivery', - 'invalid_argument', - // Preserve archive-hook failure so callers can retry, waive or skip it (#19334). - ARCHIVE_HOOK_FAILED_REMOVAL_CODE, - // Paired-only method refusal must match the mobile transport allowlist's forbidden code. - 'forbidden', - NESTED_WORKER_DEPTH_EXCEEDED_CODE, - PROJECT_RUNTIME_REPAIR_REQUIRED_CODE, - GIT_DIFF_TOO_LARGE_CODE, - ARTIFACT_SHARING_DISABLED_CODE, - AGENT_SKILL_SHARING_DISABLED_CODE, - SHARING_UNAVAILABLE_ON_HOST_CODE, - AGENT_SKILL_NOT_SHAREABLE_CODE, - AGENT_SKILL_SELECTOR_AMBIGUOUS_CODE, - AGENT_SKILL_SELECTOR_NOT_FOUND_CODE, - AGENT_SKILL_SHARING_BUSY_CODE, - AGENT_SKILL_BUNDLE_NAME_TAKEN_CODE, - AGENT_SKILL_SHARING_UNSUPPORTED_ENVIRONMENT_CODE, - SKILL_INSTALL_RPC_ERROR_CODE, - ...PLUGIN_CLI_ERROR_CODES, - // Keep owner conflicts distinct so clients can choose reload, re-adopt or stop offering the action. - ...Object.values(AUTOMATION_OWNER_CONFLICT_CODES), - ...Object.values(ORCHESTRATION_SESSION_CALLER_ERROR_CODES) -]) - -export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknown): RpcFailure { - const message = error instanceof Error ? error.message : String(error) - if (isAgentSessionRefusalError(error)) { - return agentSessionRefusalErrorResponse(id, meta, error) - } - // A recipe workspace removal keeps its environment's own code (archive hook, PTY stop, selector). - if ( - error instanceof RecipeVmWakeUnavailableError || - error instanceof RecipeWorkspaceRemovalError - ) { - return errorResponse(id, meta, error.code, message, 'data' in error ? error.data : undefined) - } - if ( - error instanceof BranchSwitchCollisionError || - error instanceof TerminalSplitOutcomeError || - error instanceof SparsePresetValidationError || - error instanceof WslHostWindowsDriveRefusalError - ) { - // Keep the existing RPC code while preserving structured details. - return errorResponse(id, meta, 'runtime_error', message, error.data) - } - if ( - error instanceof Error && - 'code' in error && - typeof (error as { code: unknown }).code === 'string' && - COMPUTER_PASSTHROUGH_CODES.has((error as { code: string }).code) - ) { - const code = (error as { code: string }).code - return errorResponse(id, meta, code, message, computerUseErrorRecoveryData(code, message)) - } - if ( - error instanceof Error && - 'code' in error && - typeof (error as { code: unknown }).code === 'string' && - (error as { code: string }).code.startsWith('LINEAGE_') - ) { - return errorResponse( - id, - meta, - (error as { code: string }).code, - message, - (error as { data?: unknown }).data - ) - } - if ( - error instanceof Error && - 'code' in error && - typeof (error as { code: unknown }).code === 'string' && - (LINEAR_PASSTHROUGH_CODES.has((error as { code: string }).code) || - STRUCTURED_RUNTIME_PASSTHROUGH_CODES.has((error as { code: string }).code)) - ) { - return errorResponse( - id, - meta, - (error as { code: string }).code, - message, - (error as { data?: unknown }).data - ) - } - if (RUNTIME_PASSTHROUGH_CODES.has(message)) { - return errorResponse(id, meta, message, formatTerminalStartFailure(error) ?? message) - } - const deferral = parseTerminalSpawnDeferral(message) - if (deferral) { - // Why: only a caller that sent spawnIntent can be deferred, so the code is new to no client. - return errorResponse(id, meta, TERMINAL_SPAWN_DEFERRED_CODE, message, { reason: deferral }) - } - const skillInstallFailure = classifySkillInstallFailureCode(message) - if (skillInstallFailure) { - return errorResponse( - id, - meta, - SKILL_INSTALL_RPC_ERROR_CODE, - skillInstallFailure.code, - skillInstallFailure - ) - } - // Same code older clients match; people read the sentence, programs the hold in `data`. - const held = wslDistroHoldRpcFailure(message) - if (held) { - return errorResponse(id, meta, 'runtime_error', held.message, held.data) - } - if (message === 'invalid_terminal_send') { - return errorResponse(id, meta, 'invalid_argument', 'Missing terminal send payload') - } - return errorResponse(id, meta, 'runtime_error', formatTerminalStartFailure(error) ?? message) -} - -/** Map agent-session refusals before generic code passthrough; preserve released clients' exact code/message and add ignored details only in data. */ -function agentSessionRefusalErrorResponse( - id: string, - meta: RpcEnvelopeMeta, - error: AgentSessionRefusalError -): RpcFailure { - const { code } = error.refusal - return errorResponse( - id, - meta, - RUNTIME_PASSTHROUGH_CODES.has(code) ? code : 'runtime_error', - code, - { refusal: agentSessionRefusalReference(error.refusal) } - ) -} - -// EmulatorError.code likewise uses its own namespace rather than generic runtime_error. -export function mapEmulatorError(id: string, meta: RpcEnvelopeMeta, error: unknown): RpcFailure { - if ( - error instanceof Error && - 'code' in error && - typeof (error as { code: unknown }).code === 'string' - ) { - return errorResponse(id, meta, (error as { code: string }).code, error.message) - } - return mapRuntimeError(id, meta, error) -} diff --git a/src/main/runtime/rpc/git-graph-layout-projection.test.ts b/src/main/runtime/rpc/git-graph-layout-projection.test.ts deleted file mode 100644 index 804e5487c50..00000000000 --- a/src/main/runtime/rpc/git-graph-layout-projection.test.ts +++ /dev/null @@ -1,478 +0,0 @@ -import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { WorkspaceLayoutModel } from '../../../shared/workspace-layout/workspace-layout-model' -import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' -import { expect, it } from 'vitest' -import { createGitGraphFrameProjection, projectGitGraphLayout } from './git-graph-layout-projection' -import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' -import { - diffPublishedLayouts, - indexPublishedLayout -} from '../../../shared/workspace-layout/workspace-layout-records' - -function layout(): PublishedWorkspaceLayout { - return { - worktreeId: 'w', - editorFiles: [], - browserTabs: [], - tabs: ['a', 'graph', 'b', 'c'].map((id) => ({ - id, - entityId: id, - kind: id === 'graph' ? 'git-graph' : 'editor', - executionHostId: 'local', - createdAt: 0, - customTitle: null, - color: null - })), - groups: [ - { id: 'g1', tabIds: ['a', 'graph', 'b'] }, - { id: 'g2', tabIds: ['c'] } - ], - groupLayout: { - type: 'split', - direction: 'horizontal', - ratio: 0.3, - first: { type: 'leaf', groupId: 'g1' }, - second: { type: 'leaf', groupId: 'g2' } - } - } -} - -it('hides graph tabs in snapshots and later record frames while preserving sequence', () => { - const original = layout() - const project = createGitGraphFrameProjection() - expect( - project({ type: 'snapshot', seq: 1, workspaces: [{ key: 'w', layout: original }] }) - ).toMatchObject({ - workspaces: [ - { - layout: { - groups: [ - { id: 'g1', tabIds: ['a', 'b'] }, - { id: 'g2', tabIds: ['c'] } - ] - } - } - ] - }) - const after = { - ...original, - groups: [ - { id: 'g1', tabIds: ['graph'] }, - { id: 'g2', tabIds: ['a', 'b', 'c'] } - ] - } - const change = diffPublishedLayouts( - 'w', - indexPublishedLayout(original), - indexPublishedLayout(after), - after - )! - const frame = project({ type: 'records', epoch: 'e', seq: 2, workspaces: [change] }) - expect(frame).toMatchObject({ - type: 'records', - epoch: 'e', - seq: 2, - workspaces: [ - { - workspace: { - groups: [{ id: 'g2', tabIds: ['a', 'b', 'c'] }], - groupLayout: { type: 'leaf', groupId: 'g2' } - } - } - ] - }) - expect(projectGitGraphLayout(after).tabs.map((tab) => tab.id)).toEqual(['a', 'b', 'c']) -}) - -function canonical(original = layout()): WorkspaceLayoutModel { - return { - hostId: 'local', - records: {}, - legacy: { terminalRowOwners: {} }, - workspaces: { - w: { - worktreeId: 'w', - tabs: original.tabs.map(({ kind, ...tab }) => { - if (kind === 'terminal') { - throw new Error('Expected a content fixture') - } - return { ...tab, kind } - }), - groups: original.groups.map(({ id, tabIds }) => ({ id, tabOrder: tabIds })), - groupLayout: original.groupLayout - } - } - } -} - -function applyClient(command: LayoutCommand, model = canonical()) { - return applyLayoutCommand(model, command, { - visibility: withoutGitGraph, - mintId: () => 'minted', - mintLeafId: () => 'leaf', - now: () => 0 - }) -} - -it('reopens at the visible index and accounts for preview replacement before placing', () => { - const model = canonical() - model.workspaces.w!.tabs.find((tab) => tab.id === 'a')!.isPreview = true - const opened = applyClient( - { - type: 'openEditorTab', - workspace: 'w', - contentType: 'editor', - fileId: '/new', - tabId: 'new', - preview: true, - groupId: 'g1', - index: 1 - }, - model - ) - expect(opened.ok && opened.model.workspaces.w!.groups[0]!.tabOrder).toEqual(['graph', 'b', 'new']) - model.workspaces.w!.tabs.find((tab) => tab.id === 'a')!.isPreview = false - model.workspaces.w!.tabs.find((tab) => tab.id === 'graph')!.isPreview = true - const hiddenPreview = applyClient( - { - type: 'openEditorTab', - workspace: 'w', - contentType: 'editor', - fileId: '/new', - tabId: 'new', - preview: true, - groupId: 'g1', - index: 1 - }, - model - ) - expect(hiddenPreview.ok && hiddenPreview.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ - 'a', - 'graph', - 'new', - 'b' - ]) - const root = canonical() - root.workspaces.w!.groups = [{ id: 'g1', tabOrder: ['graph', 'a', 'b', 'c'] }] - root.workspaces.w!.groupLayout = { type: 'leaf', groupId: 'g1' } - const closed = applyClient({ type: 'closeTabs', workspace: 'w', tabIds: ['b'] }, root) - if (!closed.ok) { - throw new Error(closed.code) - } - const reopened = applyClient( - { - type: 'openEditorTab', - workspace: 'w', - contentType: 'editor', - fileId: 'b', - tabId: 'b', - groupId: 'g1', - index: 1 - }, - closed.model - ) - expect(reopened.ok && reopened.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ - 'graph', - 'a', - 'b', - 'c' - ]) -}) - -it.each([ - { index: 0, afterTabId: 'a', expected: ['a', 'graph', 'b'] }, - { index: 1, afterTabId: null, expected: ['b', 'a', 'graph'] }, - { index: 1, afterTabId: 'gone', expected: ['a', 'graph', 'b'] } -])('moves using anchor precedence: $afterTabId', ({ index, afterTabId, expected }) => { - const moved = applyClient({ - type: 'moveTab', - workspace: 'w', - tabId: 'b', - toGroupId: 'g1', - index, - afterTabId - }) - expect(moved.ok && moved.model.workspaces.w!.groups[0]!.tabOrder).toEqual(expected) -}) - -it('gives creation indexes precedence over anchors and retains pin-aware omitted placement', () => { - const model = canonical() - model.workspaces.w!.tabs.find((tab) => tab.id === 'a')!.isPinned = true - const command = { - type: 'openSimulatorTab', - workspace: 'w', - tabId: 'new', - groupId: 'g1', - afterTabId: 'b' - } as const - const indexed = applyClient({ ...command, index: 0 }, model) - expect(indexed.ok && indexed.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ - 'new', - 'a', - 'graph', - 'b' - ]) - const omitted = applyClient({ ...command, afterTabId: 'a' }, model) - expect(omitted.ok && omitted.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ - 'a', - 'graph', - 'new', - 'b' - ]) -}) - -it('uses visible groups for implicit opens and refuses stale split anchors', () => { - const model = canonical() - model.workspaces.w!.groups = [ - { id: 'hidden', tabOrder: ['graph'] }, - { id: 'g1', tabOrder: ['a', 'b', 'c'] } - ] - const implicit = applyClient( - { type: 'openEditorTab', workspace: 'w', contentType: 'editor', fileId: '/new', tabId: 'new' }, - model - ) - expect(implicit.ok && implicit.model.workspaces.w!.groups).toEqual([ - { id: 'hidden', tabOrder: ['graph'] }, - { id: 'g1', tabOrder: ['a', 'b', 'c', 'new'] } - ]) - const defaults = applyClient( - { type: 'applyDefaultTabs', workspace: 'w', tabs: [{ tabId: 'default', leafId: 'leaf' }] }, - model - ) - expect(defaults.ok && defaults.model.workspaces.w!.groups).toEqual([ - { id: 'hidden', tabOrder: ['graph'] }, - { id: 'g1', tabOrder: ['a', 'b', 'c', 'default'] } - ]) - expect(defaults.ok && defaults.effects).toEqual({ - stopPtyIds: [], - startPaneKeys: ['default:leaf'] - }) - expect( - applyClient( - { - type: 'openEditorTab', - workspace: 'w', - contentType: 'editor', - fileId: '/new', - tabId: 'new', - groupId: 'proposed', - split: { besideGroupId: 'stale', direction: 'right' } - }, - model - ) - ).toEqual({ ok: false, code: 'group_not_found' }) -}) - -it('translates split paths and identities together while retaining hidden branches', () => { - const model = canonical() - const workspace = model.workspaces.w! - workspace.groups = [ - { id: 'hidden', tabOrder: ['graph'] }, - { id: 'g1', tabOrder: ['a', 'b'] }, - { id: 'g2', tabOrder: ['c'] } - ] - workspace.groupLayout = { - type: 'split', - direction: 'vertical', - ratio: 0.2, - first: { type: 'leaf', groupId: 'hidden' }, - second: workspace.groupLayout! - } - const resized = applyClient( - { - type: 'setGroupRatios', - workspace: 'w', - ratios: [ - { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } - ] - }, - model - ) - expect(resized.ok && resized.model.workspaces.w!.groupLayout).toEqual({ - ...workspace.groupLayout, - second: { ...layout().groupLayout, ratio: 0.7 } - }) - workspace.groupLayout = { - type: 'split', - direction: 'horizontal', - ratio: 0.3, - first: { - type: 'split', - direction: 'vertical', - ratio: 0.2, - first: { type: 'leaf', groupId: 'hidden' }, - second: { type: 'leaf', groupId: 'g1' } - }, - second: { type: 'leaf', groupId: 'g2' } - } - const identities = applyClient( - { - type: 'setGroupRatios', - workspace: 'w', - ratios: [ - { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } - ] - }, - model - ) - expect(identities.ok && identities.model.workspaces.w!.groupLayout).toEqual({ - ...workspace.groupLayout, - ratio: 0.7 - }) - expect( - applyClient( - { - type: 'setGroupRatios', - workspace: 'w', - ratios: [ - { path: '', ratio: 0.7, split: { direction: 'vertical', first: 'stale', second: 'g2' } } - ] - }, - model - ) - ).toEqual({ ok: false, code: 'group_set_changed' }) -}) - -it('splits a lone visible tab without moving its hidden sibling and refuses splitting it off itself', () => { - const model = canonical() - model.workspaces.w!.groups = [ - { id: 'g1', tabOrder: ['a', 'graph'] }, - { id: 'g2', tabOrder: ['b', 'c'] } - ] - expect( - applyClient( - { type: 'splitGroup', workspace: 'w', tabId: 'a', besideGroupId: 'g1', direction: 'right' }, - model - ) - ).toEqual({ ok: false, code: 'invalid_params' }) - const split = applyClient( - { type: 'splitGroup', workspace: 'w', tabId: 'a', besideGroupId: 'g2', direction: 'right' }, - model - ) - expect(split.ok && split.model.workspaces.w!.groups).toEqual([ - { id: 'g1', tabOrder: ['graph'] }, - { id: 'g2', tabOrder: ['b', 'c'] }, - { id: 'minted', tabOrder: ['a'] } - ]) -}) - -it('places a detached pane at a visible gap and leaves the hidden graph untouched', () => { - const model = canonical() - const workspace = model.workspaces.w! - workspace.tabs = workspace.tabs.filter((tab) => tab.id !== 'c') - workspace.tabs.push({ - id: 'c', - entityId: 'c', - kind: 'terminal', - createdAt: 0, - customTitle: null, - color: null, - terminal: { defaultTitle: 'Terminal 1' }, - panes: { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: 'one' }, - second: { type: 'leaf', leafId: 'two' } - } - } - }) - const detached = applyClient( - { - type: 'movePaneToNewTab', - workspace: 'w', - tabId: 'c', - leafId: 'one', - groupId: 'g1', - index: 1 - }, - model - ) - expect(detached.ok && detached.model.workspaces.w!.groups).toEqual([ - { id: 'g1', tabOrder: ['a', 'graph', 'minted', 'b'] }, - { id: 'g2', tabOrder: ['c'] } - ]) - expect(detached.ok && detached.effects).toEqual({ stopPtyIds: [], startPaneKeys: [] }) - const implicit = applyClient( - { type: 'movePaneToNewTab', workspace: 'w', tabId: 'c', leafId: 'one' }, - model - ) - expect(implicit.ok && implicit.model.workspaces.w!.groups).toEqual([ - { id: 'g1', tabOrder: ['a', 'graph', 'b'] }, - { id: 'g2', tabOrder: ['c', 'minted'] } - ]) -}) - -it('projects graph add/remove around binding-only deltas without losing visible updates', () => { - const original = layout() - original.tabs = original.tabs.map((tab) => - tab.id === 'c' - ? { - ...tab, - kind: 'terminal', - terminal: { - defaultTitle: 'Terminal 1', - root: { type: 'leaf', leafId: 'one' }, - panes: [{ leafId: 'one', ptyId: 'initial' }] - } - } - : tab - ) - const graphFree = { - ...original, - tabs: original.tabs.filter((tab) => tab.id !== 'graph'), - groups: [ - { id: 'g1', tabIds: ['a', 'b'] }, - { id: 'g2', tabIds: ['c'] } - ] - } - const project = createGitGraphFrameProjection() - project({ type: 'workspace', key: 'w', seq: 1, layout: graphFree }) - const binding = { - key: 'w', - change: 'records' as const, - bindings: { set: [{ leafId: 'one', ptyId: 'pty' }] } - } - const before = project({ type: 'records', epoch: 'e', seq: 2, workspaces: [binding] }) - expect(before.type === 'records' && before.workspaces[0]).toBe(binding) - const added = project({ - type: 'records', - epoch: 'e', - seq: 3, - workspaces: [ - diffPublishedLayouts( - 'w', - indexPublishedLayout(graphFree), - indexPublishedLayout(original), - original - )! - ] - }) - expect(added).toMatchObject({ workspaces: [] }) - const whileHidden = project({ - type: 'records', - epoch: 'e', - seq: 4, - workspaces: [{ ...binding, bindings: { set: [{ leafId: 'one', ptyId: 'next' }] } }] - }) - expect(whileHidden).toMatchObject({ - workspaces: [{ key: 'w', bindings: { set: [{ leafId: 'one', ptyId: 'next' }] } }] - }) - const removed = project({ - type: 'records', - epoch: 'e', - seq: 5, - workspaces: [ - diffPublishedLayouts( - 'w', - indexPublishedLayout(original), - indexPublishedLayout(graphFree), - graphFree - )! - ] - }) - expect(removed).toMatchObject({ workspaces: [] }) - const after = project({ type: 'records', epoch: 'e', seq: 6, workspaces: [binding] }) - expect(after.type === 'records' && after.workspaces[0]).toBe(binding) -}) diff --git a/src/main/runtime/rpc/methods/accounts/accounts.ts b/src/main/runtime/rpc/methods/accounts/accounts.ts index 33c9fdc4879..9d07acbcee8 100644 --- a/src/main/runtime/rpc/methods/accounts/accounts.ts +++ b/src/main/runtime/rpc/methods/accounts/accounts.ts @@ -1,6 +1,6 @@ import { defineMethod, defineStreamingMethod, type RpcContext } from '../../core' -import type { OrcadFeature } from '../../orcad-feature-readiness' -import { rpcCallerOperationKey } from '../../rpc-caller-identity' +import type { OrcadFeature } from '../../startup/orcad-readiness' +import { rpcCallerOperationKey } from '../../callers/rpc-caller-identity' import { HostAccountSignInFlows } from '../../../agent-session/environment/host-account-sign-in-flows' import type { OrcaRuntimeService } from '../../../orca-runtime' import { @@ -22,7 +22,7 @@ import { HostAccountSignInWaitParams, HostAccountSignInFlowParams, HostAccountSignInCodeParams -} from '../../../../../shared/rpc-contract/accounts-params' +} from '../../../../../shared/rpc-contract/accounts/accounts-params' import { HostAccountLaunchEnvParams } from '../../../../../shared/agent-launch/startup/host-account-launch-env' import { withTimeout } from '../../../../../shared/promise-timeout-fallback' diff --git a/src/main/runtime/rpc/methods/accounts/antigravity-accounts.ts b/src/main/runtime/rpc/methods/accounts/antigravity-accounts.ts index 8b5cb21c145..3f76d01da61 100644 --- a/src/main/runtime/rpc/methods/accounts/antigravity-accounts.ts +++ b/src/main/runtime/rpc/methods/accounts/antigravity-accounts.ts @@ -1,12 +1,12 @@ import { defineMethod, defineStreamingMethod, type RpcContext } from '../../core' -import { rpcCallerOperationKey } from '../../rpc-caller-identity' +import { rpcCallerOperationKey } from '../../callers/rpc-caller-identity' import type { OrcaRuntimeService } from '../../../orca-runtime' import { AntigravityAccountMutationParams, AntigravityAccountTargetParams, AntigravityChatSignInCompleteParams, AntigravityChatSignInFlowParams -} from '../../../../../shared/rpc-contract/antigravity-accounts-params' +} from '../../../../../shared/rpc-contract/accounts/antigravity-accounts-params' import { AntigravityChatAuthConfigSchema } from '../../../../../shared/antigravity-chat-auth-config' import { getAntigravityAccountService } from '../../../../antigravity/native-account-host' import { diff --git a/src/main/runtime/rpc/methods/accounts/usage-credentials.ts b/src/main/runtime/rpc/methods/accounts/usage-credentials.ts index 0ab9149f7e7..7b604dbcf86 100644 --- a/src/main/runtime/rpc/methods/accounts/usage-credentials.ts +++ b/src/main/runtime/rpc/methods/accounts/usage-credentials.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../core' import { UsageCredentialApiKeyParams, UsageCredentialSessionCookieParams -} from '../../../../../shared/rpc-contract/usage-credentials-params' +} from '../../../../../shared/rpc-contract/accounts/usage-credentials-params' import { assertMiniMaxCredentialOpensHere, clearMiniMaxApiKeyCredential, diff --git a/src/main/runtime/rpc/methods/agent-hooks/agent-hooks.ts b/src/main/runtime/rpc/methods/agent-hooks/agent-hooks.ts index c3a2522f2a5..2541c86db22 100644 --- a/src/main/runtime/rpc/methods/agent-hooks/agent-hooks.ts +++ b/src/main/runtime/rpc/methods/agent-hooks/agent-hooks.ts @@ -1,7 +1,7 @@ import { isAgentStatusHooksEnabledForAgent } from '../../../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import { prepareManagedWslCodexHomeBeforeShellLaunch } from '../../../../codex/hooks/installation/managed-wsl-home-shell-preflight' import { defineMethod } from '../../core' -import { PrepareCodexForWslPaneParams } from '../../../../../shared/rpc-contract/agent-hooks-params' +import { PrepareCodexForWslPaneParams } from '../../../../../shared/rpc-contract/accounts/agent-hooks-params' export const AGENT_HOOK_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts index 4876683f976..5ee742065ed 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts @@ -11,7 +11,7 @@ import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane import type { OrcaRuntimeService } from '../../../orca-runtime' import type { RpcContext } from '../../core' import { clientRendersStructuredAgent } from '../structured-sessions/structured-agent-session-policy' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { agentLaunchTabViewerRule } from './agent-launch-tab-publication' /** The paired client whose view this launch should move, or null when it moves the host's. */ diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts index cc642b119ee..391c0662043 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts @@ -66,7 +66,7 @@ const cliPath = '../../../../../cli/index' await import(cliPath) const harnessPath = '../../../../../cli/index-test-harness' await import(harnessPath) -const fixturesPath = '../../../../../cli/test-fixtures' +const fixturesPath = '../../../../../cli/runtime/fixtures/runtime-rpc-fixtures' await import(fixturesPath) const agentFixturesPath = '../../../../../cli/agent-launch-test-fixtures' await import(agentFixturesPath) diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-resources.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-resources.test.ts deleted file mode 100644 index f21812a8492..00000000000 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-resources.test.ts +++ /dev/null @@ -1,483 +0,0 @@ -import type * as RuntimeEnvironmentStore from '../../../../../shared/remote-runtime/host-store/runtime-environment-store' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('../../../../../cli/runtime-client', async () => { - const harnessPath = '../../../../../cli/index-test-harness.js' - const { - createRuntimeClientModuleMock - }: { createRuntimeClientModuleMock: RuntimeClientModuleMockFactory } = await import(harnessPath) - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('../../../../../cli/runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock( - '../../../../../shared/remote-runtime/host-store/runtime-environment-store', - async (importOriginal) => ({ - ...(await importOriginal()), - listEnvironments: listEnvironmentsMock - }) -) - -import { createConnection } from 'node:net' -import { mkdir, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { randomUUID } from 'node:crypto' -import type { - RuntimeClientModuleMockFactory, - AgentLaunchCwdCliEntry, - AgentLaunchCwdEnvironmentBindings, - AgentLaunchCwdWorktreeFixtures, - AgentLaunchCwdAgentFixtures -} from './agent-launch-cwd-cli.test-fixture' -import './agent-launch-cwd-cli.test-fixture' -const cliPath = '../../../../../cli/index' -const { main }: AgentLaunchCwdCliEntry = await import(cliPath) -const harnessPath = '../../../../../cli/index-test-harness' -const { - useWorktreeAwarenessEnvironment: configureWorktreeAwarenessEnvironment -}: AgentLaunchCwdEnvironmentBindings = await import(harnessPath) -const fixturesPath = '../../../../../cli/test-fixtures' -const { buildWorktree, worktreeListFixture }: AgentLaunchCwdWorktreeFixtures = await import( - fixturesPath -) -const agentFixturesPath = '../../../../../cli/agent-launch-test-fixtures' -const { agentLaunchHostFixture }: AgentLaunchCwdAgentFixtures = await import(agentFixturesPath) - -import { RuntimeRpcFailureError } from '../../../../../cli/runtime/types' -import { RpcDispatcher } from '../../dispatcher' -import { UnixSocketTransport } from '../../unix-socket-transport' -import { AGENT_LAUNCH_METHODS } from './agent-launch' -import { WORKTREE_METHODS } from '../workspaces/worktree' -import '../../../orca-runtime-tests/runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../../../orca-runtime' -import '../../../orca-runtime-tests/orca-runtime-test-lifecycle.spec' -import { - store as runtimeStore, - TEST_WORKTREE_ID -} from '../../../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { openTestAgentSessionRecordStore } from '../../../agent-session/records/agent-session-record-store-test-harness' -import { - openTestJournalHostDatabase, - closeTestJournalHostDatabase -} from '../../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { setAgentLaunchRecordStore } from './agent-launch.test-fixture' -import { RuntimeWorktreeLineageController } from '../../../workspaces/lineage/runtime-worktree-lineage-controller' -import { formatAmbiguousCwdParentMessage } from '../../../workspaces/lineage/runtime-worktree-lineage-resolution' -import { managedCwdLaunchFixture } from './managed-cwd-launch.test-fixture' - -configureWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -}) - -// Actual local framing, including named pipes on Windows, precedes dispatch and schema validation. -async function socketCall(endpoint: string, frame: string) { - return new Promise((resolve, reject) => { - const socket = createConnection(endpoint) - let response = '' - socket.setEncoding('utf8') - socket.setTimeout(10_000, () => socket.destroy(new Error('fixture RPC timed out'))) - socket.on('error', reject) - socket.on('connect', () => socket.write(frame)) - socket.on('data', (chunk) => { - response += chunk.toString() - if (response.includes('\n')) { - socket.end() - resolve(response.trim()) - } - }) - }) -} - -describe('CLI cwd resource frames, managed receipts and raw-path controls', () => { - let directory: string - let transport: UnixSocketTransport - let prior: typeof process.exitCode - const childStateDirectories = new Set() - beforeEach(async () => { - vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined) - vi.stubEnv('ORCA_STRUCTURED_SESSION', undefined) - directory = await mkdtemp(join(tmpdir(), 'orca-cwd-receipt-')) - prior = process.exitCode - const saved = runtimeStore.getAllWorktreeMeta() - const metadata = { - ...saved, - [TEST_WORKTREE_ID]: { ...saved[TEST_WORKTREE_ID]!, instanceId: 'parent-instance' } - } - vi.spyOn(runtimeStore, 'getAllWorktreeMeta').mockReturnValue(metadata) - vi.spyOn(runtimeStore, 'getWorktreeMeta').mockImplementation((id) => metadata[id]) - }) - afterEach(async () => { - const failures: unknown[] = [] - try { - await transport?.stop() - } catch (error) { - failures.push(error) - } - setAgentLaunchRecordStore(null) - for (const stateDirectory of [...childStateDirectories, directory]) { - try { - await closeTestJournalHostDatabase(stateDirectory) - } catch (error) { - failures.push(error) - } - } - childStateDirectories.clear() - try { - await rm(directory, { recursive: true, force: true }) - } catch (error) { - failures.push(error) - } - process.exitCode = prior - vi.unstubAllEnvs() - vi.restoreAllMocks() - if (failures.length > 0) { - throw new AggregateError(failures, 'cwd resource fixture cleanup failed') - } - }) - - it.each(['uuid', 'root+instances'] as const)( - 'measures real managed Codex T/X framing, receipts and restart at N/10N (%s)', - async (shape) => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - const samples: { - count: number - valid: boolean - operations: number - elapsedMs: number - jsonBytes: number - frameBytes: number - replyBytes: number - rowBytes: number - reopenedReplyBytes: number - textBytes: number - prettyJsonBytes: number - normalizedReplyBytes: number - normalizedRowBytes: number - }[] = [] - for (const count of [1000, 10000]) { - const stateDirectory = join(directory, `${shape}-${count}`) - await mkdir(stateDirectory) - childStateDirectories.add(stateDirectory) - let records = await openTestAgentSessionRecordStore(stateDirectory) - const parentBase = buildWorktree('/tmp/scale-parent', 'main', 'abc', 'parent-repo') - const parent = { - ...parentBase, - id: - shape === 'uuid' - ? `${parentBase.id}::workspace:00000000-1111-4111-8111-111111111111` - : parentBase.id - } - const host = managedCwdLaunchFixture(records, parent, stateDirectory) - const writes = vi.spyOn(records, 'recordOperationOutcome') - const lineage = vi.spyOn(RuntimeWorktreeLineageController.prototype, 'resolveCreate') - const rows = Array.from({ length: count }, (_, index) => { - const id = - index === 0 - ? parent.id - : `${parentBase.id}::workspace:${index.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111` - return { - ...parentBase, - get id() { - operations++ - return id - }, - get path() { - operations++ - return parent.path - }, - get hostId() { - operations++ - return 'local' as const - } - } - }) - let operations = 0 - let dispatcher = new RpcDispatcher({ - runtime: host.runtime, - methods: [...AGENT_LAUNCH_METHODS, ...WORKTREE_METHODS] - }) - const endpoint = - process.platform === 'win32' - ? `\\\\.\\pipe\\orca-managed-scale-${randomUUID()}` - : join(stateDirectory, 's.sock') - transport = new UnixSocketTransport({ - endpoint, - kind: process.platform === 'win32' ? 'named-pipe' : 'unix' - }) - const frames: string[] = [] - const replies: string[] = [] - let execution = () => [ - lineage.mock.calls.length, - host.showTerminal.mock.calls.length, - host.catalog.mock.calls.length, - host.showRepo.mock.calls.length, - host.create.mock.calls.length, - host.start.mock.calls.length, - host.publish.mock.calls.length, - host.save.mock.calls.length - ] - const settledExecution: number[][] = [] - transport.onMessage((raw, reply) => { - const request = JSON.parse(raw) - const before = execution() - void dispatcher.dispatch(request).then((response) => { - const serialized = JSON.stringify(response) - if (request.method === 'agent.launchReplay') { - replies.push(serialized) - settledExecution.push(execution().map((n, i) => n - before[i]!)) - } - reply(serialized) - }) - }) - await transport.start() - callMock.mockImplementation(async (method, params) => { - if (method === 'worktree.list') { - return worktreeListFixture(rows) - } - if (method === 'status.get') { - return agentLaunchHostFixture() - } - const frame = `${JSON.stringify({ id: 'scale', authToken: 'fixture', method, params })}\n` - frames.push(frame) - const response = JSON.parse(await socketCall(endpoint, frame)) - if (!response.ok) { - throw new RuntimeRpcFailureError(response) - } - return response - }) - const argv = [ - 'worktree', - 'create', - '--repo', - 'id:repo-1', - '--name', - 'child', - '--agent', - 'codex' - ] - const operationIds: string[] = [] - const originals = new Map; row: string }>() - const normalize = (value: unknown, id: string) => - JSON.stringify(value, (key, entry) => - key === 'runtimeId' - ? 'runtime' - : key === 'operationId' || entry === id - ? 'operation' - : ['recordedAt', 'expiresAt', 'operationTimestamp'].includes(key) - ? 0 - : key === 'worktreeId' && entry === host.childId - ? 'created-workspace' - : entry - ) - - for (const valid of [true, false]) { - process.env.ORCA_TERMINAL_HANDLE = valid ? host.caller : 'term_X' - process.exitCode = prior - operations = 0 - log.mockClear() - error.mockClear() - const effectBefore = [ - host.start.mock.calls.length, - host.save.mock.calls.length, - host.publish.mock.calls.length - ] - const lineageBefore = lineage.mock.calls.length - const writeBefore = writes.mock.calls.length - const started = performance.now() - await main([...argv, '--json'], parent.path) - const elapsedMs = performance.now() - started - const launchFrame = frames.findLast( - (frame) => JSON.parse(frame).method === 'agent.launchReplay' - )! - const envelope = JSON.parse(launchFrame) - const operationId = String(envelope.params.operationId) - operationIds.push(operationId) - const { cwdParentAmbiguous, ...oldCreate } = envelope.params.target.create - const oldProjection = { - ...envelope, - params: { ...envelope.params, target: { ...envelope.params.target, create: oldCreate } } - } - expect(cwdParentAmbiguous).toBe(true) - expect(envelope.params.target.create.cwdParentWorktree).toBe(`id:${parent.id}`) - const frameBytes = Buffer.byteLength(launchFrame) - const jsonBytes = Buffer.byteLength(launchFrame.slice(0, -1)) - expect(jsonBytes).toBe(Buffer.byteLength(JSON.stringify(oldProjection)) + 26) - expect(frameBytes).toBe(jsonBytes + 1) - expect(frameBytes).toBeLessThan(1024 * 1024) - expect(operations).toBeLessThanOrEqual(50 * count) - expect(lineage.mock.calls.length - lineageBefore).toBe(1) - expect(writes.mock.calls.length - writeBefore).toBeGreaterThanOrEqual(1) - expect(writes.mock.calls.length - writeBefore).toBeLessThanOrEqual(3) - const measuredOperations = operations - const output = JSON.parse(log.mock.calls.flat().join('\n')) - expect(output.ok, error.mock.calls.flat().join('\n')).toBe(valid) - expect(process.exitCode).toBe(valid ? prior : 1) - expect(host.start.mock.calls.length - effectBefore[0]!).toBe(valid ? 1 : 0) - if (!valid) { - expect( - host.save.mock.calls.length, - JSON.stringify({ - diagnostic: 'managed-cwd-save', - shape, - count, - valid, - savesBefore: effectBefore[1], - writes: host.metadataWrites - }) - ).toBe(effectBefore[1]) - expect(output.error).toEqual({ - code: 'LINEAGE_PARENT_AMBIGUOUS', - message: formatAmbiguousCwdParentMessage('codex') - }) - expect(output.error.message).toHaveLength(637) - expect(host.publish.mock.calls.length).toBe(effectBefore[2]) - } - const row = openTestJournalHostDatabase(stateDirectory) - .db.prepare('SELECT row_json FROM agent_session_operations ORDER BY rowid DESC LIMIT 1') - .get() - expect(typeof row?.row_json).toBe('string') - const rowJson = String(row!.row_json) - expect(JSON.parse(rowJson).outcome.status).toBe(valid ? 'succeeded' : 'failed') - expect(rowJson).not.toContain('cwdParentAmbiguous') - expect(rowJson).not.toContain('workspaces') - const prettyJsonBytes = Buffer.byteLength(log.mock.calls.flat().join('\n')) - const originalReply = replies.at(-1)! - const { _meta: _originalMeta, ...replyBody } = JSON.parse(originalReply) - originals.set(operationId, { reply: replyBody, row: rowJson }) - const normalizedReplyBytes = Buffer.byteLength(normalize(replyBody, operationId)) - const normalizedRowBytes = Buffer.byteLength(normalize(JSON.parse(rowJson), operationId)) - log.mockClear() - error.mockClear() - process.exitCode = prior - await main([...argv, '--retry-launch', operationId], parent.path) - const text = (valid ? log : error).mock.calls.flat().join('\n') - expect( - valid - ? text.includes('term_started') - : text === formatAmbiguousCwdParentMessage('codex') - ).toBe(true) - expect(settledExecution.at(-1)).toEqual(Array(8).fill(0)) - samples.push({ - count, - valid, - operations: measuredOperations, - elapsedMs, - jsonBytes, - frameBytes, - replyBytes: Buffer.byteLength(originalReply), - rowBytes: Buffer.byteLength(rowJson), - reopenedReplyBytes: 0, - textBytes: Buffer.byteLength(text), - prettyJsonBytes, - normalizedReplyBytes, - normalizedRowBytes - }) - } - await closeTestJournalHostDatabase(stateDirectory) - records = await openTestAgentSessionRecordStore(stateDirectory) - const restarted = new OrcaRuntimeService(host.runtimeStore) - vi.spyOn(restarted, 'openAgentSessionRecordStore').mockResolvedValue(records) - const executionSpies = [ - vi.spyOn(restarted, 'createManagedWorktree'), - vi.spyOn(restarted, 'showTerminal'), - vi.spyOn(restarted, 'listManagedWorktrees'), - vi.spyOn(restarted, 'showRepo'), - vi.spyOn(restarted, 'createTerminal'), - vi.spyOn(restarted, 'publishAgentLaunchTab') - ] - execution = () => [ - lineage.mock.calls.length, - ...executionSpies.map((spy) => spy.mock.calls.length), - host.save.mock.calls.length - ] - dispatcher = new RpcDispatcher({ - runtime: restarted, - methods: [...AGENT_LAUNCH_METHODS, ...WORKTREE_METHODS] - }) - for (const [index, operationId] of operationIds.entries()) { - process.env.ORCA_TERMINAL_HANDLE = index === 0 ? host.caller : 'term_X' - log.mockClear() - error.mockClear() - process.exitCode = prior - await main([...argv, '--retry-launch', operationId, '--json'], parent.path) - const result = JSON.parse(log.mock.calls.flat().join('\n')) - const { _meta: _reopenedMeta, ...replyBody } = JSON.parse(replies.at(-1)!) - expect(replyBody).toEqual(originals.get(operationId)!.reply) - expect(settledExecution.at(-1)).toEqual(Array(8).fill(0)) - const persisted = openTestJournalHostDatabase(stateDirectory) - .db.prepare('SELECT row_json FROM agent_session_operations') - .all() - .map((row) => String(row.row_json)) - expect(persisted).toContain(originals.get(operationId)!.row) - expect(result.ok).toBe(index === 0) - if (index === 1) { - expect(result.error.message).toBe(formatAmbiguousCwdParentMessage('codex')) - } - samples.findLast( - (sample) => sample.count === count && sample.valid === (index === 0) - )!.reopenedReplyBytes = Buffer.byteLength(replies.at(-1)!) - } - expect(host.start).toHaveBeenCalledTimes(1) - expect(host.create).toHaveBeenCalledTimes(2) - await transport.stop() - await closeTestJournalHostDatabase(stateDirectory) - lineage.mockRestore() - } - for (const valid of [true, false]) { - const pair = samples.filter((sample) => sample.valid === valid) - expect(pair[1]!.operations).toBeLessThanOrEqual(11 * pair[0]!.operations) - // Raw sizes above retain generated IDs/meta; only fixed request shape is compared across N. - expect(pair[1]!.frameBytes).toBe(pair[0]!.frameBytes) - expect(pair[1]!.normalizedReplyBytes).toBe(pair[0]!.normalizedReplyBytes) - expect(pair[1]!.normalizedRowBytes).toBe(pair[0]!.normalizedRowBytes) - } - console.info( - 'managed-cwd-benchmark', - JSON.stringify({ - platform: process.platform, - node: process.version, - base: '3bfcda1bf043af8d83371b2f131a65f2056f7970', - shape, - boundary: - 'CLI catalog already supplied; real managed creation; external Git/terminal effects substituted; each N uses new runtime/store/socket after corpus setup; T is first trigger, X and receipt replays reuse warmed runtime; modules already loaded', - samples - }) - ) - } - ) -}) diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-folder-workspace-creation.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-folder-workspace-creation.ts index 6dc831c7c7a..9d7b2bd8afc 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-folder-workspace-creation.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-folder-workspace-creation.ts @@ -4,8 +4,8 @@ import { folderWorkspaceKey } from '../../../../../shared/workspace-scope' import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import type { AgentLaunchWorkspaceFactory } from '../../../../agent-launch/agent-launch-surface-factories' import type { RpcContext } from '../../core' -import { resolveRpcWorkspaceCreatorProvenance } from '../../workspace-creator-context' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import { resolveRpcWorkspaceCreatorProvenance } from '../../callers/workspace-creator-context' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' type FolderWorkspaceCreateParams = Extract< AgentLaunchParams['target'], diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.test.ts index 4c821e38a54..25b70e5dcea 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.test.ts @@ -8,7 +8,7 @@ import { import { HOST_TEST_NOW } from '../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import type { RpcContext } from '../../core' -import { LOCAL_CLI_RPC_CALLER } from '../../rpc-caller-identity' +import { LOCAL_CLI_RPC_CALLER } from '../../callers/rpc-caller-identity' import { methodNamed, rpcContext, diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts index 6e5c26927ee..87056f65c61 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts @@ -2,13 +2,13 @@ import type { AgentLaunchResult } from '../../../../../shared/agent-launch/contr import { isOrcaSessionId } from '../../../../../shared/orca-session-address' import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { prepareAgentCreationCard, startedAgentSender } from '../../../orchestration/workers/launch/worker-start-card' import type { RpcContext } from '../../core' -import { isAgentRpcCaller } from '../../rpc-caller-identity' +import { isAgentRpcCaller } from '../../callers/rpc-caller-identity' /** An agent that hands work to another from its chat leaves a card there linking to it. * Display bookkeeping: nothing here refuses, holds or fails the launch, whose result passes through. */ diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-instant-tab.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-instant-tab.test.ts index 0d43d0b30e9..9cfe7729c9c 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-instant-tab.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-instant-tab.test.ts @@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AGENT_LAUNCH_TAB_CLOSED_CODE } from '../../../../../shared/agent-launch/contracts/agent-launch-tab-closed' import '../../../../../shared/agent-launch/contracts/agent-launch-replay-refusal' -import '../../errors' +import '../../responses/rpc-response' import type { AgentLaunchResult } from '../../../../../shared/agent-launch/contracts/agent-launch-intent' import type { @@ -33,7 +33,7 @@ import { openTestAgentSessionRecordStore } from '../../../agent-session/records/ import type { RpcContext } from '../../core' -import '../../rpc-caller-identity' +import '../../callers/rpc-caller-identity' import { methodNamed, rpcContext, @@ -187,24 +187,5 @@ describe.each(['window', 'main'] as const)('the %s owning the layout', (owner) = ) expect(retried.published).toEqual([]) }) - - it('stops an agent whose tab was closed while its terminal was created, before its prompt is pasted', async () => { - const runtime = hostWithWindow({ terminalPaneKey: PANE_KEY, lineCarriesPrompt: false }) - const spawn = runtime.createTerminal.getMockImplementation()! - runtime.createTerminal.mockImplementationOnce(async (selector, createOptions) => { - markAgentLaunchesClosedByUser('wt-7', { kind: 'tab', tabId: TAB_ID }) - return spawn(selector, createOptions) - }) - - await expect( - replayLaunch( - runtime, - { paneKey: PANE_KEY, prompt: { text: 'fix the build', delivery: 'submit' } }, - CLI - ) - ).rejects.toMatchObject({ code: AGENT_LAUNCH_TAB_CLOSED_CODE }) - expect(runtime.closeTerminal).toHaveBeenCalledWith('term_1') - expect(deliverTerminalAgentLaunchPrompt).not.toHaveBeenCalled() - }) }) }) diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-intent-resolution.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-intent-resolution.ts index 6068804456f..6c0c963d0ca 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-intent-resolution.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-intent-resolution.ts @@ -8,7 +8,7 @@ import type { } from '../../../../../shared/agent-launch/contracts/agent-launch-intent' import type { OrcaRuntimeService } from '../../../orca-runtime' import { assertTerminalLaunchAdmissible } from '../../../../agent-launch/agent-launch-surface-factories' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { resolveAgentLaunchModeOnHost } from '../../../../agent-launch/agent-launch-mode' import type { EarlyAgentLaunchTab } from './agent-launch-tab-publication' diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-prestart-failure.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-prestart-failure.test.ts index 0a66d21bfc8..579c8f8ffe2 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-prestart-failure.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-prestart-failure.test.ts @@ -15,7 +15,7 @@ import '../../../workspaces/lineage/runtime-worktree-lineage-resolution' import '../../../../agent-launch/agent-launch-not-started' import './agent-launch-failure-code' import { RpcDispatcher } from '../../dispatcher' -import type { RpcDispatchStreamingOptions } from '../../dispatcher-stream-options' +import type { RpcDispatchStreamingOptions } from '../../dispatch/dispatcher-stream-options' import { methodNamed, runtimeStub, diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-replay.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-replay.ts index 69d0fc38c00..d994d0463a5 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-replay.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-replay.ts @@ -18,9 +18,9 @@ import type { import { resolveAgentSessionReplayOutcome } from '../../../../native-chat/agent-session-wire/operations/structured-agent-session-replay-outcome' import type { TerminalSpawnDispatch } from '../../../../agent-launch/agent-launch-not-started' import type { RpcContext } from '../../core' -import { rpcCallerOperationKey } from '../../rpc-caller-identity' +import { rpcCallerOperationKey } from '../../callers/rpc-caller-identity' import { agentLaunchFailureMessage } from './agent-launch-failure-code' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' /** Partition the ledger by transport-proven caller; an unnamed caller gets no replay safety or shared namespace. */ export function agentLaunchOperationCallerKey(context: Pick): string { diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts index 79a10627983..2add85cae79 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-restart-replay.test.ts @@ -10,17 +10,14 @@ import { AGENT_LAUNCH_PROMPT_UNCONFIRMED_RUNTIME_CAPABILITY, AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../../shared/agent-launch/contracts/agent-launch-runtime-capability' -import { - isAgentLaunchResult, - type AgentLaunchResult -} from '../../../../../shared/agent-launch/contracts/agent-launch-intent' +import type { AgentLaunchResult } from '../../../../../shared/agent-launch/contracts/agent-launch-intent' import type { AgentSessionOperationRow } from '../../../../../shared/agent-session/lifecycle/agent-session-operation-ledger' import type { AgentSessionRecordStore } from '../../../agent-session/records/agent-session-record-store' import { openTestAgentSessionRecordStore } from '../../../agent-session/records/agent-session-record-store-test-harness' import type { OrcaRuntimeService } from '../../../orca-runtime' import type { RpcContext } from '../../core' import { RpcDispatcher } from '../../dispatcher' -import { DESKTOP_RPC_CALLER } from '../../rpc-caller-identity' +import { DESKTOP_RPC_CALLER } from '../../callers/rpc-caller-identity' import { DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES } from '../../../../ipc/desktop-renderer-runtime-capabilities' import { methodNamed, @@ -123,17 +120,6 @@ function row(callerKey = 'device-1'): AgentSessionOperationRow | null { return store.getOperationRow(callerKey, OPERATION_ID) } -/** The first write is fired, not awaited, so it lands a moment after the tab is published. */ -async function untilRecorded(status: AgentSessionOperationRow['outcome']['status']): Promise { - const deadline = Date.now() + 2_000 - while (row()?.outcome.status !== status) { - if (Date.now() > deadline) { - throw new Error(`the launch row never reached ${status}`) - } - await new Promise((resolve) => setTimeout(resolve, 5)) - } -} - /** The store commits in order, so a write queued now lands after every write already fired. */ async function ledgerWritesQueuedBefore(ledger: AgentSessionRecordStore): Promise { await ledger.recordOperationOutcome({ @@ -158,31 +144,6 @@ async function launchUntilPasteStarts(runtime: AgentLaunchRuntimeStub): Promise< await ledgerWritesQueuedBefore(store) } -/** The ledger as the launch reaches it, with the launch's `nth` write (1-based) replaced. */ -function replaceLaunchWrite( - ledger: AgentSessionRecordStore, - nth: number, - write: () => Promise -): void { - const recordOperationOutcome = ledger.recordOperationOutcome.bind(ledger) - let launchWrites = 0 - vi.spyOn(ledger, 'recordOperationOutcome').mockImplementation((input) => { - if (input.operationId === OPERATION_ID && input.callerKey === 'device-1') { - launchWrites += 1 - if (launchWrites === nth) { - return write() - } - } - return recordOperationOutcome(input) - }) -} - -function promptOutcome(outcome: AgentSessionOperationRow['outcome'] | undefined): unknown { - return outcome?.status === 'succeeded' && isAgentLaunchResult(outcome.launch) - ? outcome.launch.prompt?.outcome - : undefined -} - function dispatcherFor(runtime: AgentLaunchRuntimeStub): RpcDispatcher { return new RpcDispatcher({ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture implements every runtime method agent.launch reaches, plus the id the dispatcher stamps on replies. @@ -237,31 +198,6 @@ describe('a host restart mid-launch', () => { expect(deliverTerminalPrompt).toHaveBeenCalledOnce() }) - it('stays unconfirmed when the host died after the paste returned, before the final write', async () => { - let pasted: () => void = () => {} - const pasteReturned = new Promise((resolve) => { - pasted = resolve - }) - deliverTerminalPrompt.mockImplementationOnce(async () => { - pasted() - return true - }) - replaceLaunchWrite(store, 2, () => new Promise(() => {})) - void launch(hostRuntime()) - await pasteReturned - await untilRecorded('succeeded') - await ledgerWritesQueuedBefore(store) - - await restartHost() - const restarted = restartedHostRuntime() - - await expect(launch(restarted, PROMPTED_LAUNCH, UPGRADED_PHONE)).resolves.toEqual( - UNCONFIRMED_AGENT - ) - await expect(launch(restarted)).rejects.toThrow('agent_session_operation_unknown') - expect(deliverTerminalPrompt).toHaveBeenCalledOnce() - }) - it('keeps the recorded handle when the restarted host no longer has the pane', async () => { await launchUntilPasteStarts(hostRuntime()) @@ -308,56 +244,6 @@ describe('a host restart mid-launch', () => { expect(restarted.createTerminal).not.toHaveBeenCalled() expect(deliverTerminalPrompt).toHaveBeenCalledOnce() }) - - it('lets the final write replace the first, never the other way round', async () => { - let releasePaste: (pasted: boolean) => void = () => {} - deliverTerminalPrompt.mockImplementationOnce( - () => - new Promise((resolve) => { - releasePaste = resolve - }) - ) - const running = launch(hostRuntime()) - await untilRecorded('succeeded') - releasePaste(true) - await running - - await restartHost() - const outcome = row()?.outcome - expect(outcome?.status === 'succeeded' && outcome.launch).toMatchObject({ - prompt: { outcome: 'handed-to-terminal' } - }) - }) -}) - -describe('a final write that fails', () => { - it('leaves the prompt unconfirmed, or unknown to a caller that cannot read it, never "not sent"', async () => { - replaceLaunchWrite(store, 2, () => Promise.reject(new Error('SQLITE_BUSY'))) - const host = hostRuntime() - - const first = await launch(host) - - // The live answer is the truth the host saw; only the record missed it. - expect(first.prompt).toEqual({ delivery: 'submit', outcome: 'handed-to-terminal' }) - await expect(launch(host)).rejects.toThrow('agent_session_operation_unknown') - await expect(launch(host, PROMPTED_LAUNCH, UPGRADED_PHONE)).resolves.toMatchObject({ - outcome: { kind: 'terminal', handle: 'term_1', paneKey: PANE_KEY }, - prompt: { delivery: 'submit', outcome: 'unconfirmed' } - }) - expect(host.createTerminal).toHaveBeenCalledOnce() - expect(deliverTerminalPrompt).toHaveBeenCalledOnce() - }) -}) - -describe('the two writes', () => { - it('never lets a failed first write block the launch', async () => { - replaceLaunchWrite(store, 1, () => Promise.reject(new Error('SQLITE_BUSY'))) - - const first = await launch(hostRuntime()) - - expect(first.prompt).toEqual({ delivery: 'submit', outcome: 'handed-to-terminal' }) - expect(promptOutcome(row()?.outcome)).toBe('handed-to-terminal') - }) }) describe('the desktop launches replay-safely', () => { diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-tab-publication.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-tab-publication.ts index 8b5e78553ec..74ab49decad 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-tab-publication.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-tab-publication.ts @@ -25,7 +25,7 @@ import { readAgentLaunchModeSettings } from '../../../../agent-launch/agent-launch-mode' import type { RpcContext } from '../../core' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { agentLaunchOperationCallerKey } from './agent-launch-replay' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-worktree-creation.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-worktree-creation.ts index cf5faf98cbd..034884d740d 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-worktree-creation.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-worktree-creation.ts @@ -11,17 +11,17 @@ import { releaseAutomationWorkspaceProvenanceRequest, resolveAutomationWorkspaceProvenance, resolveClientAutomationWorkspaceProvenance -} from '../../../../automations/workspace-provenance' +} from '../../../../automations/ownership/workspace-provenance' import type { AgentLaunchWorkspaceFactory } from '../../../../agent-launch/agent-launch-surface-factories' import { combineLaunchWarnings } from '../../../../agent-launch/agent-launch-warnings' import type { RpcContext } from '../../core' -import { resolveRpcWorkspaceCreatorProvenance } from '../../workspace-creator-context' +import { resolveRpcWorkspaceCreatorProvenance } from '../../callers/workspace-creator-context' import { buildManagedWorktreeCreateArgs, worktreeCreateRepoSelector } from '../workspaces/worktree-create-args' import { toAgentLaunchPreferences } from '../../../../../shared/agent-launch/choices/agent-launch-preferences' -import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { agentLaunchFolderWorkspaceCreator } from './agent-launch-folder-workspace-creation' import { agentLaunchMovesHostWindow } from './agent-launch-tab-publication' diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch.test-fixture.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch.test-fixture.ts index f98c27dad3a..b683c316c48 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch.test-fixture.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch.test-fixture.ts @@ -6,7 +6,7 @@ import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../../shared/agent-lau import type { WorktreeLineageWarning } from '../../../../../shared/worktree/lineage-types' import { AgentLaunchPaneAlreadyLiveError } from '../../../../../shared/agent-launch/contracts/agent-launch-pane-already-live' import type { RpcContext } from '../../core' -import { resolveRpcCallerIdentity } from '../../rpc-caller-identity' +import { resolveRpcCallerIdentity } from '../../callers/rpc-caller-identity' import type { AgentSessionRecordStore } from '../../../agent-session/records/agent-session-record-store' import type { TerminalWorkspaceLaunchScope } from '../../../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' import type { diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts index ce81b25b229..920e23ce71d 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts @@ -2,7 +2,7 @@ * Keep worktree.create's PTY/handle contract for older clients. * operationId adds durable at-most-once execution and recorded replay; unknown outcomes refuse, while stranded-surface recovery remains separate. */ -import { agentLaunchFeatureRequirement } from '../../agent-launch-feature-requirement' +import { agentLaunchFeatureRequirement } from '../../startup/agent-launch-feature-requirement' import { AgentLaunchTabClosedError } from '../../../../../shared/agent-launch/contracts/agent-launch-tab-closed' import { computeAgentLaunchFingerprint } from '../../../../../shared/agent-launch/contracts/agent-launch-operation' import type { AgentLaunchResult } from '../../../../../shared/agent-launch/contracts/agent-launch-intent' @@ -32,7 +32,7 @@ import { AgentLaunch, AgentLaunchReplay, type AgentLaunchParams -} from '../../../../../shared/rpc-contract/agent-launch-params' +} from '../../../../../shared/rpc-contract/agent-launch/agent-launch-params' import { agentLaunchSurfaceFactory } from './agent-launch-surfaces' import { prepareAgentHandoffCard } from './agent-launch-handoff-card' import { diff --git a/src/main/runtime/rpc/methods/artifacts/artifacts.ts b/src/main/runtime/rpc/methods/artifacts/artifacts.ts index 79eb16003d9..240399399bd 100644 --- a/src/main/runtime/rpc/methods/artifacts/artifacts.ts +++ b/src/main/runtime/rpc/methods/artifacts/artifacts.ts @@ -4,7 +4,7 @@ import { ListOptions, SourceRequest, WriteRequest -} from '../../../../../shared/rpc-contract/artifacts-params' +} from '../../../../../shared/rpc-contract/artifacts/artifacts-params' export const ARTIFACT_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/automations/automations.ts b/src/main/runtime/rpc/methods/automations/automations.ts index 3e061896286..a62ca969fa6 100644 --- a/src/main/runtime/rpc/methods/automations/automations.ts +++ b/src/main/runtime/rpc/methods/automations/automations.ts @@ -10,7 +10,7 @@ import { AutomationList, AutomationRuns, AutomationUpdate -} from '../../../../../shared/rpc-contract/automation-params' +} from '../../../../../shared/rpc-contract/automations/automation-params' function mutationOwner( id: string, @@ -51,8 +51,16 @@ export const AUTOMATION_METHODS = [ name: 'automation.create', permission: 'workspace', params: AutomationCreate, - handler: async (params, { runtime }) => ({ - automation: await runtime.createAutomation(params) + handler: async (params, { runtime, plugin }) => ({ + automation: await runtime.createAutomation( + // Provenance comes from the in-process caller only; params cannot claim it. + plugin + ? { ...params, createdBy: { kind: 'plugin', pluginKey: plugin.key, name: plugin.name } } + : params, + undefined, + // A plugin disabled while the target resolved must not leave an automation it owns. + plugin?.assertActive + ) }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/browser/browser-client-host.ts b/src/main/runtime/rpc/methods/browser/browser-client-host.ts index 87b96c1a590..7d5d3d9d409 100644 --- a/src/main/runtime/rpc/methods/browser/browser-client-host.ts +++ b/src/main/runtime/rpc/methods/browser/browser-client-host.ts @@ -11,8 +11,10 @@ import { import { BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE, BrowserClientHostAttachParams, + BrowserClientHostCommandResultChunkParams, BrowserClientHostCommandResultParams } from '../../../../../shared/browser/client-hosting/browser-client-host-protocol' +import { BROWSER_CLIENT_HOST_COMMAND_RESULT_CHUNK_METHOD } from '../../../../../shared/browser/client-hosting/browser-client-automation-protocol' import { BrowserError } from '../../../../browser/browser-error' import { getBrowserHostLeaseRegistry } from '../../../browser-host/leases/browser-host-lease-registry-instance' import { getRuntimeBrowserPageRegistry } from '../../../browser/client-pages/runtime-browser-page-registry' @@ -20,7 +22,7 @@ import { adoptRuntimeBrowserClientPagesFromInventory } from '../../../browser/cl import { recoverUnavailableRuntimeBrowserClientPages } from '../../../browser/client-pages/runtime-browser-client-page-recovery' import { releaseRuntimeBrowserClientPageRecord } from '../../../browser/client-pages/runtime-browser-client-page-release' import { getBrowserHostRequestRegistry } from '../../../browser-host/leases/browser-host-request-registry' -import { defineMethod, defineStreamingMethod } from '../../core' +import { defineMethod, defineStreamingMethod, type RpcContext } from '../../core' export const BROWSER_CLIENT_HOST_METHODS = [ defineStreamingMethod({ @@ -169,35 +171,25 @@ export const BROWSER_CLIENT_HOST_METHODS = [ name: 'browser.clientHost.commandResult', permission: 'workspace', params: BrowserClientHostCommandResultParams, - handler: ( - params, - { runtime, pairedDeviceId, connectionId, clientKind, clientCapabilities } - ) => { - if (clientKind !== 'runtime' || !pairedDeviceId || !connectionId) { - throw new Error('authenticated_browser_client_host_required') - } - if (!clientCapabilities?.includes(BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY)) { - throw new Error('browser_client_host_capability_required') - } - if (params.authorityRuntimeId !== runtime.getRuntimeId()) { - throw new BrowserError( - BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE, - BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE - ) - } - const accepted = getBrowserHostLeaseRegistry(runtime).settleClientPageCommand( - { - authorityEpoch: params.authorityEpoch, - browserHostClientId: params.browserHostClientId, - browserHostGeneration: params.browserHostGeneration, - pairedDeviceId, - connectionId - }, + handler: (params, context) => { + const accepted = getBrowserHostLeaseRegistry(context.runtime).settleClientPageCommand( + requireCommandResultIdentity(params, context), params ) return { accepted } } }), + defineMethod({ + name: BROWSER_CLIENT_HOST_COMMAND_RESULT_CHUNK_METHOD, + permission: 'workspace', + params: BrowserClientHostCommandResultChunkParams, + handler: (params, context) => { + getBrowserHostLeaseRegistry(context.runtime) + .requireCommandResultLedger(requireCommandResultIdentity(params, context)) + .stageResultChunk(params) + return { accepted: true } + } + }), defineMethod({ name: 'browser.clientHost.requestResult', permission: 'workspace', @@ -256,3 +248,37 @@ export const BROWSER_CLIENT_HOST_METHODS = [ } }) ] + +function requireCommandResultIdentity( + params: { + authorityRuntimeId: string + authorityEpoch: string + browserHostClientId: string + browserHostGeneration: number + }, + context: Pick< + RpcContext, + 'runtime' | 'pairedDeviceId' | 'connectionId' | 'clientKind' | 'clientCapabilities' + > +) { + const { runtime, pairedDeviceId, connectionId, clientKind, clientCapabilities } = context + if (clientKind !== 'runtime' || !pairedDeviceId || !connectionId) { + throw new Error('authenticated_browser_client_host_required') + } + if (!clientCapabilities?.includes(BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY)) { + throw new Error('browser_client_host_capability_required') + } + if (params.authorityRuntimeId !== runtime.getRuntimeId()) { + throw new BrowserError( + BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE, + BROWSER_CLIENT_HOST_AUTHORITY_MISMATCH_CODE + ) + } + return { + authorityEpoch: params.authorityEpoch, + browserHostClientId: params.browserHostClientId, + browserHostGeneration: params.browserHostGeneration, + pairedDeviceId, + connectionId + } +} diff --git a/src/main/runtime/rpc/methods/browser/browser-core.ts b/src/main/runtime/rpc/methods/browser/browser-core.ts index 6edf1f772ba..e76b9e2efeb 100644 --- a/src/main/runtime/rpc/methods/browser/browser-core.ts +++ b/src/main/runtime/rpc/methods/browser/browser-core.ts @@ -28,21 +28,21 @@ import { TabSwitch, Upload, Wait -} from '../../../../../shared/rpc-contract/browser-params' -import { Screenshot, Snapshot } from '../../../../../shared/rpc-contract/browser-observation-params' +} from '../../../../../shared/rpc-contract/browser/browser-params' +import * as browserObservationParams from '../../../../../shared/rpc-contract/browser/browser-observation-params' import { BrowserOpenUrlParams, BrowserTabCreateParams -} from '../../../../../shared/rpc-contract/browser-tab-create-params' +} from '../../../../../shared/rpc-contract/browser/browser-tab-create-params' import { BROWSER_TEXT_METHODS } from './browser-text-rpc-methods' import { BROWSER_PROFILE_METHODS } from './browser-profile-rpc-methods' -import { CertificateProceed } from '../../../../../shared/rpc-contract/browser-core-params' +import { CertificateProceed } from '../../../../../shared/rpc-contract/browser/browser-core-params' export const BROWSER_CORE_METHODS = [ defineMethod({ name: 'browser.snapshot', permission: 'workspace', - params: Snapshot, + params: browserObservationParams.Snapshot, handler: async (params, { runtime }) => runtime.browserSnapshot(params) }), defineMethod({ @@ -91,7 +91,7 @@ export const BROWSER_CORE_METHODS = [ defineMethod({ name: 'browser.screenshot', permission: 'workspace', - params: Screenshot, + params: browserObservationParams.Screenshot, handler: async (params, { runtime }) => runtime.browserScreenshot(params) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts b/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts index 0ccb61c2dca..36ad3814945 100644 --- a/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/browser/browser-extension-rpc-methods.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../core' import { ExtensionList, ExtensionReload -} from '../../../../../shared/rpc-contract/browser-extension-params' +} from '../../../../../shared/rpc-contract/browser/browser-extension-params' import { getRuntimeBrowserExtensions } from '../../../browser/installation/runtime-browser-commands-factory' export const BROWSER_EXTENSION_METHODS = [ diff --git a/src/main/runtime/rpc/methods/browser/browser-extras.ts b/src/main/runtime/rpc/methods/browser/browser-extras.ts index c8381e3511a..a9d738365b0 100644 --- a/src/main/runtime/rpc/methods/browser/browser-extras.ts +++ b/src/main/runtime/rpc/methods/browser/browser-extras.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { assertRpcClipboardTextWriteWithinLimit } from '../../rpc-clipboard-text-validation' +import { assertRpcClipboardTextWriteWithinLimit } from '../../clipboard/rpc-clipboard-text-validation' import { BrowserTarget, ExpectUrlBrowserTarget @@ -23,8 +23,8 @@ import { StorageKey, StorageKeyValue, Viewport -} from '../../../../../shared/rpc-contract/browser-params' -import { MouseClick } from '../../../../../shared/rpc-contract/browser-extras-params' +} from '../../../../../shared/rpc-contract/browser/browser-params' +import { MouseClick } from '../../../../../shared/rpc-contract/browser/browser-extras-params' export const BROWSER_EXTRA_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts b/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts index 3bdc3a48b05..9174142b949 100644 --- a/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts +++ b/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { BrowserIdentitySet } from '../../../../../shared/rpc-contract/browser-identity-params' +import { BrowserIdentitySet } from '../../../../../shared/rpc-contract/browser/browser-identity-params' import { getBrowserIdentityModeStatus, setBrowserIdentityMode diff --git a/src/main/runtime/rpc/methods/browser/browser-profile-rpc-methods.ts b/src/main/runtime/rpc/methods/browser/browser-profile-rpc-methods.ts index d79dbba4c6c..66d48029520 100644 --- a/src/main/runtime/rpc/methods/browser/browser-profile-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/browser/browser-profile-rpc-methods.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { ProfileCreate } from '../../../../../shared/rpc-contract/browser-identity-params' +import { ProfileCreate } from '../../../../../shared/rpc-contract/browser/browser-identity-params' import { ProfileDelete, ProfileClearGoogleCookies, @@ -7,7 +7,7 @@ import { TabProfileClone, TabSetProfile, TabShow -} from '../../../../../shared/rpc-contract/browser-params' +} from '../../../../../shared/rpc-contract/browser/browser-params' export const BROWSER_PROFILE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/browser/browser-screencast.ts b/src/main/runtime/rpc/methods/browser/browser-screencast.ts index d55f3f9aebe..fa7c159e0fa 100644 --- a/src/main/runtime/rpc/methods/browser/browser-screencast.ts +++ b/src/main/runtime/rpc/methods/browser/browser-screencast.ts @@ -1,5 +1,5 @@ import { defineMethod, defineStreamingMethod } from '../../core' -import { Screencast } from '../../../../../shared/rpc-contract/browser-params' +import { Screencast } from '../../../../../shared/rpc-contract/browser/browser-params' import { BrowserError } from '../../../../browser/browser-error' import '../../../../../shared/runtime-types' import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../../shared/runtime-session-contracts' @@ -7,7 +7,7 @@ import { runtimeBrowserCommandsFactoryIsAvailable } from '../../../browser/insta import { ScreencastAck, ScreencastUnsubscribe -} from '../../../../../shared/rpc-contract/browser-screencast-params' +} from '../../../../../shared/rpc-contract/browser/browser-screencast-params' import { acknowledgeBrowserScreencastFrame } from '../../../browser/screencast/browser-screencast-frame-credit' export const BROWSER_SCREENCAST_METHODS = [ diff --git a/src/main/runtime/rpc/methods/browser/browser-text-rpc-methods.ts b/src/main/runtime/rpc/methods/browser/browser-text-rpc-methods.ts index 82c9a972012..8cc3fc59061 100644 --- a/src/main/runtime/rpc/methods/browser/browser-text-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/browser/browser-text-rpc-methods.ts @@ -1,6 +1,10 @@ import { defineMethod } from '../../core' -import { assertRpcClipboardTextWriteWithinLimit } from '../../rpc-clipboard-text-validation' -import { Fill, KeyboardInsert, Type } from '../../../../../shared/rpc-contract/browser-params' +import { assertRpcClipboardTextWriteWithinLimit } from '../../clipboard/rpc-clipboard-text-validation' +import { + Fill, + KeyboardInsert, + Type +} from '../../../../../shared/rpc-contract/browser/browser-params' export const BROWSER_TEXT_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/client-events/client-events.ts b/src/main/runtime/rpc/methods/client-events/client-events.ts index f78a7844631..7e96dd47873 100644 --- a/src/main/runtime/rpc/methods/client-events/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events/client-events.ts @@ -7,7 +7,7 @@ import { defineMethod, defineStreamingMethod } from '../../core' import { ClientEventsSubscribeParams, ClientEventsUnsubscribeParams -} from '../../../../../shared/rpc-contract/client-events-params' +} from '../../../../../shared/rpc-contract/client-ui/client-events-params' import { BROWSER_CLIENT_HOST_REQUEST_CAPABILITY } from '../../../../../shared/browser/client-hosting/browser-client-host-request-protocol' import { getBrowserHostRequestRegistry } from '../../../browser-host/leases/browser-host-request-registry' import { diff --git a/src/main/runtime/rpc/methods/client-events/runtime-client-capabilities.ts b/src/main/runtime/rpc/methods/client-events/runtime-client-capabilities.ts index a3a54b9e698..1e509eea001 100644 --- a/src/main/runtime/rpc/methods/client-events/runtime-client-capabilities.ts +++ b/src/main/runtime/rpc/methods/client-events/runtime-client-capabilities.ts @@ -1,6 +1,6 @@ import type { RuntimeCapability } from '../../../../../shared/protocol-version' import { defineMethod } from '../../core' -import { ClientCapabilitiesUpdate } from '../../../../../shared/rpc-contract/runtime-client-capabilities-params' +import { ClientCapabilitiesUpdate } from '../../../../../shared/rpc-contract/host-management/runtime-client-capabilities-params' export const RUNTIME_CLIENT_CAPABILITY_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/client-state/client-ui-schemas.ts b/src/main/runtime/rpc/methods/client-state/client-ui-schemas.ts index a32149374df..b791076cf4c 100644 --- a/src/main/runtime/rpc/methods/client-state/client-ui-schemas.ts +++ b/src/main/runtime/rpc/methods/client-state/client-ui-schemas.ts @@ -1,4 +1,4 @@ -import type { UiUpdateFields } from '../../../../../shared/rpc-contract/client-ui-params' +import type { UiUpdateFields } from '../../../../../shared/rpc-contract/client-ui/client-ui-params' // The key/value parity assertions over this live in ui-state-schema-parity-checks.ts. export type UiUpdateFieldsSchema = typeof UiUpdateFields diff --git a/src/main/runtime/rpc/methods/client-state/client-ui-set-collapsed.test.ts b/src/main/runtime/rpc/methods/client-state/client-ui-set-collapsed.test.ts index 340473e880f..2d9df273538 100644 --- a/src/main/runtime/rpc/methods/client-state/client-ui-set-collapsed.test.ts +++ b/src/main/runtime/rpc/methods/client-state/client-ui-set-collapsed.test.ts @@ -2,10 +2,10 @@ import { describe, expect, it } from 'vitest' import { getDefaultUIState } from '../../../../../shared/constants' import type { PersistedUIState } from '../../../../../shared/persisted-ui-state-types' import type { OrcaRuntimeService } from '../../../orca-runtime' -import { CollapseWriteOrder } from '../../../sidebar-inputs/workspace-view-collapse-writes' +import { CollapseWriteOrder } from '../../../client/settings/workspace-view-collapse-writes' import type { RpcRequest } from '../../core' import { RpcDispatcher } from '../../dispatcher' -import type { RpcDispatchStreamingOptions } from '../../dispatcher-stream-options' +import type { RpcDispatchStreamingOptions } from '../../dispatch/dispatcher-stream-options' import { CLIENT_UI_METHODS } from './client-ui' import { SIDEBAR_INPUT_METHODS } from '../sidebar-inputs/sidebar-inputs' diff --git a/src/main/runtime/rpc/methods/client-state/client-ui.ts b/src/main/runtime/rpc/methods/client-state/client-ui.ts index 85fff95b7aa..77205cc4be1 100644 --- a/src/main/runtime/rpc/methods/client-state/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-state/client-ui.ts @@ -1,10 +1,10 @@ import { normalizeJiraQuickFilterState } from '../../../../../shared/jira/jira-quick-filters' -import { JiraQuickFilterStateParam } from '../../../../../shared/rpc-contract/jira-quick-filter-params' +import { JiraQuickFilterStateParam } from '../../../../../shared/rpc-contract/jira/jira-quick-filter-params' import { normalizeJiraSavedFilterState, mutateJiraSavedFilterState } from '../../../../../shared/jira/jira-saved-filters' -import { JiraSavedFilterMutationParam } from '../../../../../shared/rpc-contract/jira-saved-filter-params' +import { JiraSavedFilterMutationParam } from '../../../../../shared/rpc-contract/jira/jira-saved-filter-params' import { omitPairingLocalUiFields, type PairedUiState @@ -12,20 +12,20 @@ import { import type { PersistedUIState } from '../../../../../shared/persisted-ui-state-types' import { isWorkspaceHostScope } from '../../../../../shared/orcad-migration/orcad-migration-client-state-value-validation' import { defineMethod, type RpcContext } from '../../core' -import { isHostOwnPhone } from '../../host-own-phone' +import { isHostOwnPhone } from '../../callers/host-own-phone' import { NativeChatSessionOptionsMutation, PRBotAuthorOverrideUpdate, SettingsUpdate -} from '../../../../../shared/rpc-contract/client-settings-params' +} from '../../../../../shared/rpc-contract/client-ui/client-settings-params' import { FeatureInteractionIdParam, UiUpdate -} from '../../../../../shared/rpc-contract/client-ui-params' +} from '../../../../../shared/rpc-contract/client-ui/client-ui-params' // Keep schema/PersistedUIState parity assertions in the typecheck graph so drift fails before reaching paired clients. -import { TerminalQuickCommandsUpdate } from '../../../../../shared/rpc-contract/terminal-quick-command-params' -import { AgentLaunchSettingsMutation } from '../../../../../shared/rpc-contract/agent-launch-settings-params' +import { TerminalQuickCommandsUpdate } from '../../../../../shared/rpc-contract/terminal/terminal-quick-command-params' +import { AgentLaunchSettingsMutation } from '../../../../../shared/rpc-contract/agent-launch/agent-launch-settings-params' import { assertTerminalQuickCommandMutationReadableForClient, projectTerminalQuickCommandsForClient diff --git a/src/main/runtime/rpc/methods/client-state/task-resume-state-parity.ts b/src/main/runtime/rpc/methods/client-state/task-resume-state-parity.ts index a38f2982f8c..1320a49b336 100644 --- a/src/main/runtime/rpc/methods/client-state/task-resume-state-parity.ts +++ b/src/main/runtime/rpc/methods/client-state/task-resume-state-parity.ts @@ -1,8 +1,8 @@ import type { z } from 'zod' import type { TaskResumeState as TaskResumeStateType } from '../../../../../shared/ui-chrome-types' import type { AssertNoMissingKeys } from './ui-state-schema-parity' -import type { TaskResumeState } from '../../../../../shared/rpc-contract/task-resume-state-params' -import '../../../../../shared/rpc-contract/task-resume-state-params' +import type { TaskResumeState } from '../../../../../shared/rpc-contract/client-ui/task-resume-state-params' +import '../../../../../shared/rpc-contract/client-ui/task-resume-state-params' const _taskResumeStateParity: AssertNoMissingKeys< TaskResumeStateType, diff --git a/src/main/runtime/rpc/methods/clipboard/clipboard.test.ts b/src/main/runtime/rpc/methods/clipboard/clipboard.test.ts index 25dfce28e94..f43cc0e60f3 100644 --- a/src/main/runtime/rpc/methods/clipboard/clipboard.test.ts +++ b/src/main/runtime/rpc/methods/clipboard/clipboard.test.ts @@ -8,15 +8,15 @@ const { saveClipboardImageBufferAsTempFile } = vi.hoisted(() => ({ saveClipboardImageBufferAsTempFile: vi.fn() })) -vi.mock('../../../../window/clipboard-image-temp-file', () => ({ +vi.mock('../../../../window/clipboard/clipboard-image-temp-file', () => ({ saveClipboardImageBufferAsTempFile })) -import '../../../../../shared/rpc-contract/clipboard-params' +import '../../../../../shared/rpc-contract/clipboard/clipboard-params' import { CLIPBOARD_METHODS, resetClipboardImageUploadsForTest } from './clipboard' import { hasMobileClipboardImagePath, resetMobileClipboardImageProvenanceForTest -} from '../../mobile-clipboard-image-provenance' +} from '../../clipboard/mobile-clipboard-image-provenance' function makeRequest(method: string, params?: unknown): RpcRequest { return { id: 'req-1', authToken: 'tok', method, params } diff --git a/src/main/runtime/rpc/methods/clipboard/clipboard.ts b/src/main/runtime/rpc/methods/clipboard/clipboard.ts index 0b13863a3ab..b0b0f1bfc8b 100644 --- a/src/main/runtime/rpc/methods/clipboard/clipboard.ts +++ b/src/main/runtime/rpc/methods/clipboard/clipboard.ts @@ -1,14 +1,14 @@ import { defineMethod, type RpcContext } from '../../core' -import { saveClipboardImageBufferAsTempFile } from '../../../../window/clipboard-image-temp-file' +import { saveClipboardImageBufferAsTempFile } from '../../../../window/clipboard/clipboard-image-temp-file' import { randomUUID } from 'node:crypto' -import { recordMobileClipboardImagePath } from '../../mobile-clipboard-image-provenance' +import { recordMobileClipboardImagePath } from '../../clipboard/mobile-clipboard-image-provenance' import { AbortImageUpload, AppendImageUploadChunk, CommitImageUpload, SaveImageAsTempFile, StartImageUpload -} from '../../../../../shared/rpc-contract/clipboard-params' +} from '../../../../../shared/rpc-contract/clipboard/clipboard-params' import { decodeClipboardImageUpload } from './clipboard-image-upload-decoding' export const CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT = 8 const CLIPBOARD_IMAGE_UPLOAD_TTL_MS = 5 * 60 * 1000 diff --git a/src/main/runtime/rpc/methods/computer/computer.ts b/src/main/runtime/rpc/methods/computer/computer.ts index d0eeb451444..0279258b115 100644 --- a/src/main/runtime/rpc/methods/computer/computer.ts +++ b/src/main/runtime/rpc/methods/computer/computer.ts @@ -21,11 +21,11 @@ import { Scroll, SetValue, TypeText -} from '../../../../../shared/rpc-contract/computer-schemas-params' +} from '../../../../../shared/rpc-contract/computer/computer-schemas-params' import { ComputerCapabilitiesParams, ComputerPermissionsStatusParams -} from '../../../../../shared/rpc-contract/computer-params' +} from '../../../../../shared/rpc-contract/computer/computer-params' export function resetComputerSessionsForTest(): void { resetComputerSidecarForTest() diff --git a/src/main/runtime/rpc/methods/connectors/connector.ts b/src/main/runtime/rpc/methods/connectors/connector.ts index 10d088b8203..a8ebd8584d8 100644 --- a/src/main/runtime/rpc/methods/connectors/connector.ts +++ b/src/main/runtime/rpc/methods/connectors/connector.ts @@ -10,7 +10,7 @@ import { ConnectorSend, ConnectorStart, ConnectorWatch -} from '../../../../../shared/rpc-contract/connector-params' +} from '../../../../../shared/rpc-contract/connectors/connector-params' import type { ConversationEvent, ConversationSnapshot diff --git a/src/main/runtime/rpc/methods/emulator/emulator.ts b/src/main/runtime/rpc/methods/emulator/emulator.ts index c3d547fe814..df41bf509b5 100644 --- a/src/main/runtime/rpc/methods/emulator/emulator.ts +++ b/src/main/runtime/rpc/methods/emulator/emulator.ts @@ -21,7 +21,7 @@ import { TapParams, TypeParams, WorktreeParam -} from '../../../../../shared/rpc-contract/emulator-params' +} from '../../../../../shared/rpc-contract/emulator/emulator-params' const InstallParams = z.object({ path: z.string().refine((value) => path.isAbsolute(value), { diff --git a/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts b/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts index 6742047593f..5b8e2726b51 100644 --- a/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts +++ b/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts @@ -1,7 +1,7 @@ import { watchBatchFlushDelayMs } from '../../../../../shared/file-watch/filesystem-watch-batch-window' import type { FsChangeEvent } from '../../../../../shared/file-watch/filesystem-change-event' import { FileWatchEventBuffer } from '../../../../../shared/file-watch/filesystem-watch-event-buffer' -import type { FileWatchBatchCadence } from '../../../../../shared/rpc-contract/files-target-params' +import type { FileWatchBatchCadence } from '../../../../../shared/rpc-contract/filesystem/files-target-params' // Older clients discard superseded reads; 100ms batches starve slow links, so preserve their trailing window unless opted in. const LEGACY_WATCH_BATCH_TRAILING_MS = 150 diff --git a/src/main/runtime/rpc/methods/files/file-watch-stream-lifecycle.ts b/src/main/runtime/rpc/methods/files/file-watch-stream-lifecycle.ts index 27f88de11cc..ffa958b2552 100644 --- a/src/main/runtime/rpc/methods/files/file-watch-stream-lifecycle.ts +++ b/src/main/runtime/rpc/methods/files/file-watch-stream-lifecycle.ts @@ -2,7 +2,7 @@ import { isWatcherProcessFailure } from '../../../../ipc/filesystem/watcher-proc import type { OrcaRuntimeService } from '../../../orca-runtime' import { createFileWatchEventBatcher } from './file-watch-event-batcher' import { dirListingPageCache } from './files-read-dir-page' -import type { FileWatchBatchCadence } from '../../../../../shared/rpc-contract/files-target-params' +import type { FileWatchBatchCadence } from '../../../../../shared/rpc-contract/filesystem/files-target-params' export async function runFileWatchStream(args: { runtime: OrcaRuntimeService diff --git a/src/main/runtime/rpc/methods/files/files-mutation-methods.ts b/src/main/runtime/rpc/methods/files/files-mutation-methods.ts index 05f23e5b703..c7e14294d2d 100644 --- a/src/main/runtime/rpc/methods/files/files-mutation-methods.ts +++ b/src/main/runtime/rpc/methods/files/files-mutation-methods.ts @@ -12,7 +12,7 @@ import { FileWriteIfUnchanged, FileWriteBase64, FileWriteBase64Chunk -} from '../../../../../shared/rpc-contract/files-mutation-params' +} from '../../../../../shared/rpc-contract/filesystem/files-mutation-params' type SshMutationParams = { expectedExecutionHostId?: string diff --git a/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts b/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts index 88dddbf742a..98a01ef5279 100644 --- a/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts +++ b/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts @@ -4,7 +4,7 @@ import { FileSaveBegin, FileSaveChunk, FileSaveCommit -} from '../../../../../shared/rpc-contract/files-staged-save-params' +} from '../../../../../shared/rpc-contract/filesystem/files-staged-save-params' import { STAGED_FILE_SAVE_METHODS } from '../../../../../shared/file-write/staged-file-save' // Saves belong to the socket that began them; in-process callers share one owner. diff --git a/src/main/runtime/rpc/methods/files/files-terminal-artifact-methods.ts b/src/main/runtime/rpc/methods/files/files-terminal-artifact-methods.ts index 512dd1d7a68..9a26ecfc04e 100644 --- a/src/main/runtime/rpc/methods/files/files-terminal-artifact-methods.ts +++ b/src/main/runtime/rpc/methods/files/files-terminal-artifact-methods.ts @@ -4,7 +4,7 @@ import { TerminalArtifactFile, TerminalArtifactFileChunk, TerminalArtifactFileWrite -} from '../../../../../shared/rpc-contract/files-terminal-artifact-params' +} from '../../../../../shared/rpc-contract/filesystem/files-terminal-artifact-params' export const FILE_TERMINAL_ARTIFACT_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/files/files.ts b/src/main/runtime/rpc/methods/files/files.ts index 56c8c93d755..c5992a77d08 100644 --- a/src/main/runtime/rpc/methods/files/files.ts +++ b/src/main/runtime/rpc/methods/files/files.ts @@ -12,7 +12,7 @@ import { FileOpen, FileWatch, WorktreeSelector -} from '../../../../../shared/rpc-contract/files-target-params' +} from '../../../../../shared/rpc-contract/filesystem/files-target-params' import { FILE_TERMINAL_ARTIFACT_METHODS } from './files-terminal-artifact-methods' import { ChatImageRead, @@ -30,7 +30,7 @@ import { FileUnwatch, ResolveTerminalPath, ServerDirectoryBrowse -} from '../../../../../shared/rpc-contract/files-params' +} from '../../../../../shared/rpc-contract/filesystem/files-params' import { limitSearchResultToContentBudget } from '../../../../../shared/file-search/search-result-transport-budget' let filesWatchSubscriptionSeq = 0 diff --git a/src/main/runtime/rpc/methods/history/ai-vault.test.ts b/src/main/runtime/rpc/methods/history/ai-vault.test.ts index 245be54fe3b..7c1a825ce8d 100644 --- a/src/main/runtime/rpc/methods/history/ai-vault.test.ts +++ b/src/main/runtime/rpc/methods/history/ai-vault.test.ts @@ -38,17 +38,17 @@ vi.mock( import { AI_VAULT_METHODS } from './ai-vault' -import '../../../../../shared/rpc-contract/ai-vault-params' +import '../../../../../shared/rpc-contract/ai-vault/ai-vault-params' import { agentSessionRefusalError } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals' import { recordStructuredAgentSessionHostInstallRefusal } from '../../../agent-session/structured-agent-session-host-refusal' import '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import '../../../../ai-vault/structured-session-ownership.test-support' +import '../../../../ai-vault/structured-sessions/structured-session-ownership.test-support' import { listAiVaultSessions, resetAiVaultSessionListCacheForTests -} from '../../../../ai-vault/cached-session-list' +} from '../../../../ai-vault/listing/cached-session-list' function makeRequest(method: string, params?: unknown): RpcRequest { return { id: 'req-1', authToken: 'tok', method, params } @@ -164,27 +164,6 @@ describe('aiVault.listSessions handler + shared cache', () => { resetAiVaultSessionListCacheForTests() }) - it('aborts the host scan when its last RPC caller disconnects', async () => { - scanAiVaultSessionsInService.mockImplementation( - (_options, signal) => - new Promise((_resolve, reject) => { - signal?.addEventListener('abort', () => reject(new Error('scan aborted')), { once: true }) - }) - ) - const dispatcher = makeDispatcher() - const caller = new AbortController() - const response = dispatcher.dispatch(makeRequest('aiVault.listSessions', {}), { - signal: caller.signal - }) - await vi.waitFor(() => expect(scanAiVaultSessionsInService).toHaveBeenCalledOnce()) - const scanSignal = scanAiVaultSessionsInService.mock.calls[0]?.[1] - - caller.abort() - - expect(scanSignal?.aborted).toBe(true) - await expect(response).resolves.toMatchObject({ ok: false }) - }) - it('omits unchanged session bodies only for clients with the matching fingerprint', async () => { const dispatcher = makeDispatcher() const first = await dispatcher.dispatch( @@ -247,7 +226,7 @@ describe('aiVault.listSessions handler + shared cache', () => { expect(changed.result).not.toHaveProperty('unchanged') expect(changed.result).not.toMatchObject({ fingerprint: first.result.fingerprint }) } - expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(1) + const forced = await dispatcher.dispatch( makeRequest('aiVault.listSessions', { afterFingerprint: first.result.fingerprint, @@ -258,7 +237,6 @@ describe('aiVault.listSessions handler + shared cache', () => { if (forced.ok) { expect(forced.result).not.toHaveProperty('unchanged') } - expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(2) }) it('restamps the shared cached result as the addressed runtime host', async () => { @@ -279,10 +257,6 @@ describe('aiVault.listSessions handler + shared cache', () => { )) as { ok: boolean; result: AiVaultListResult } // Host identity changes response stamps, never host-local scan/cache identity. - expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(1) - expect(scanAiVaultSessionsInService.mock.calls[0]?.[0]).toMatchObject({ - executionHostId: 'local' - }) expect(localResponse.result.sessions[0]?.executionHostId).toBe('local') expect(runtimeResponse.result.sessions[0]?.executionHostId).toBe('runtime:remote-server') diff --git a/src/main/runtime/rpc/methods/history/ai-vault.ts b/src/main/runtime/rpc/methods/history/ai-vault.ts index 0354adef06d..b5295e78e25 100644 --- a/src/main/runtime/rpc/methods/history/ai-vault.ts +++ b/src/main/runtime/rpc/methods/history/ai-vault.ts @@ -1,4 +1,4 @@ -import { prepareStructuredChatCliFork } from '../../../../ai-vault/structured-chat-cli-fork' +import { prepareStructuredChatCliFork } from '../../../../ai-vault/structured-sessions/structured-chat-cli-fork' import { writeAiVaultSessionHandoffSnapshot } from '../../../../ai-vault/session-handoff-snapshot' import { AiVaultSearchRequestSchema, @@ -11,9 +11,9 @@ import { sessionSearchServiceStatus } from '../../../../ai-vault-search/session-search-service-registry' import { defineMethod } from '../../core' -import { conditionalAiVaultListResult } from '../../../../ai-vault/session-list-fingerprint' -import { restampAiVaultListResult } from '../../../../ai-vault/session-list-results' -import { copyStructuredChatConversation } from '../../../../ai-vault/structured-chat-conversation-copy' +import { conditionalAiVaultListResult } from '../../../../ai-vault/listing/session-list-fingerprint' +import { restampAiVaultListResult } from '../../../../ai-vault/listing/session-list-results' +import { copyStructuredChatConversation } from '../../../../ai-vault/structured-sessions/structured-chat-conversation-copy' import type { AiVaultPrepareSessionResumeArgs } from '../../../../../shared/ai-vault/resume/ai-vault-resume-preparation' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { isWslUncPath } from '../../../../../shared/wsl-paths' @@ -22,7 +22,7 @@ import { assertLegacyAiVaultResumeAllowed, projectStructuredAiVaultSessions, searchWithStructuredOwners -} from '../../../../ai-vault/structured-session-ownership' +} from '../../../../ai-vault/structured-sessions/structured-session-ownership' import { ensureStructuredAgentSessionHostUnlessRefused, tryEnsureStructuredAgentSessionHostForResume @@ -37,7 +37,7 @@ import { AiVaultPrepareSessionHandoffParams, AiVaultPrepareSessionResumeParams, AiVaultSessionTitlesParams -} from '../../../../../shared/rpc-contract/ai-vault-params' +} from '../../../../../shared/rpc-contract/ai-vault/ai-vault-params' export const AI_VAULT_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/host-management/environment-doctor.ts b/src/main/runtime/rpc/methods/host-management/environment-doctor.ts index 80f1a883132..c8219f08b61 100644 --- a/src/main/runtime/rpc/methods/host-management/environment-doctor.ts +++ b/src/main/runtime/rpc/methods/host-management/environment-doctor.ts @@ -1,5 +1,5 @@ import { ENVIRONMENT_DOCTOR_METHOD } from '../../../../../shared/environment-doctor-runtime' -import { EnvironmentDoctorParams } from '../../../../../shared/rpc-contract/environment-doctor-params' +import { EnvironmentDoctorParams } from '../../../../../shared/rpc-contract/host-management/environment-doctor-params' import { runEnvironmentDoctor } from '../../../../environment-doctor/environment-doctor' import { createHostEnvironmentDoctorDeps } from '../../../../environment-doctor/environment-doctor-host' import { defineMethod } from '../../core' diff --git a/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts b/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts index 7185324d40d..6a69ddd72a4 100644 --- a/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts +++ b/src/main/runtime/rpc/methods/host-management/managed-runtime-install.ts @@ -4,7 +4,7 @@ import type { OrcaRuntimeService } from '../../../orca-runtime' import { ManagedRuntimeAgentParams, ManagedRuntimeCancelParams -} from '../../../../../shared/rpc-contract/managed-runtime-install-params' +} from '../../../../../shared/rpc-contract/host-management/managed-runtime-install-params' import { acpLaunchSpecFor } from '../../../../acp/launch/acp-launch-registry' import { resolveAcpLaunchCommand } from '../../../../acp/launch/acp-launch-command' import { ManagedRuntimeInstallation } from '../../../../node-runtime/managed-runtime-installation' diff --git a/src/main/runtime/rpc/methods/host-management/managed-server.ts b/src/main/runtime/rpc/methods/host-management/managed-server.ts index b541938ad51..4ee68047f5c 100644 --- a/src/main/runtime/rpc/methods/host-management/managed-server.ts +++ b/src/main/runtime/rpc/methods/host-management/managed-server.ts @@ -2,7 +2,7 @@ import { ManagedServerRecover, ManagedServerSelector, ManagedServerUpdate -} from '../../../../../shared/rpc-contract/managed-server-params' +} from '../../../../../shared/rpc-contract/host-management/managed-server-params' import { getManagedServerActions, type ManagedServerActions diff --git a/src/main/runtime/rpc/methods/host-management/recipe-vm-wake.ts b/src/main/runtime/rpc/methods/host-management/recipe-vm-wake.ts index 91dd56c06f6..c665113685c 100644 --- a/src/main/runtime/rpc/methods/host-management/recipe-vm-wake.ts +++ b/src/main/runtime/rpc/methods/host-management/recipe-vm-wake.ts @@ -2,7 +2,7 @@ import { RECIPE_VM_WAKE_METHOD, RecipeVmWakeUnavailableError } from '../../../../../shared/remote-runtime/recipe-vm-wake' -import { RecipeVmWakeParams } from '../../../../../shared/rpc-contract/recipe-vm-wake-params' +import { RecipeVmWakeParams } from '../../../../../shared/rpc-contract/host-management/recipe-vm-wake-params' import { getRecipeVmWaker } from '../../../workspaces/sleep/recipe-vm-waker-registry' import { defineMethod } from '../../core' diff --git a/src/main/runtime/rpc/methods/host-management/status.ts b/src/main/runtime/rpc/methods/host-management/status.ts index 8905927e996..1e696544766 100644 --- a/src/main/runtime/rpc/methods/host-management/status.ts +++ b/src/main/runtime/rpc/methods/host-management/status.ts @@ -1,7 +1,7 @@ import { defineMethod } from '../../core' import { getRemoteServerUpdaterSnapshot } from '../../../hosts/management/remote-server-updater' import { getPublishedHostDescriptor } from '../../../hosts/platform-probe/host-descriptor' -import { StatusGetParams } from '../../../../../shared/rpc-contract/status-params' +import { StatusGetParams } from '../../../../../shared/rpc-contract/host-management/status-params' import { readHostMachineWithin } from '../../../hosts/platform-probe/runtime-host-machine' import { MACHINE_NAME_PUBLISH_WAIT_MS } from '../../../hosts/platform-probe/runtime-machine-name' diff --git a/src/main/runtime/rpc/methods/integrations/jira/jira-attachment-image.ts b/src/main/runtime/rpc/methods/integrations/jira/jira-attachment-image.ts index cf08b0e33b4..a0ae168ac96 100644 --- a/src/main/runtime/rpc/methods/integrations/jira/jira-attachment-image.ts +++ b/src/main/runtime/rpc/methods/integrations/jira/jira-attachment-image.ts @@ -7,7 +7,7 @@ import { isAttachmentImageGrantCurrent } from '../../../../../jira/attachments/image-grants' import { readGrantedAttachmentImage } from '../../../../../jira/attachments/image-read' -import { AttachmentImage } from '../../../../../../shared/rpc-contract/jira-params' +import { AttachmentImage } from '../../../../../../shared/rpc-contract/jira/jira-params' import { defineStreamingMethod } from '../../../core' export const JIRA_ATTACHMENT_IMAGE_METHODS = [ diff --git a/src/main/runtime/rpc/methods/integrations/jira/jira.ts b/src/main/runtime/rpc/methods/integrations/jira/jira.ts index 5d4a8fa4e15..e3ec88adfa7 100644 --- a/src/main/runtime/rpc/methods/integrations/jira/jira.ts +++ b/src/main/runtime/rpc/methods/integrations/jira/jira.ts @@ -4,7 +4,7 @@ import { } from '../../../../../../shared/jira/jira-payload-stream' import { defineMethod, defineStreamingMethod, type RpcContext } from '../../../core' import { JIRA_ATTACHMENT_IMAGE_METHODS } from './jira-attachment-image' -import { JiraFavouriteFilterParams } from '../../../../../../shared/rpc-contract/jira-favourite-filter-params' +import { JiraFavouriteFilterParams } from '../../../../../../shared/rpc-contract/jira/jira-favourite-filter-params' import { AssignableUsers, GenerateIssueSummary, @@ -22,7 +22,7 @@ import { SelectSite, SiteSelection, UserSearch -} from '../../../../../../shared/rpc-contract/jira-params' +} from '../../../../../../shared/rpc-contract/jira/jira-params' /** Emits a Jira result over RPC, normalizing it to the shape clients decode. */ function emitJiraPayload(value: unknown, emit: (result: unknown) => void): void { diff --git a/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.ts b/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.ts index a4dafc27b8b..7dc584fd26e 100644 --- a/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.ts +++ b/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.ts @@ -18,7 +18,7 @@ import { LinearSaveIssue, LinearTeamLookup, LinearWorkspaceRead -} from '../../../../../../shared/rpc-contract/linear-agent-access-params' +} from '../../../../../../shared/rpc-contract/linear/linear-agent-access-params' function parseLinearWriteId(writeId: string | undefined): string | undefined { if (writeId === undefined) { diff --git a/src/main/runtime/rpc/methods/integrations/linear/linear-issue-list-method.ts b/src/main/runtime/rpc/methods/integrations/linear/linear-issue-list-method.ts index 99fb33a29d7..290ce0e64b1 100644 --- a/src/main/runtime/rpc/methods/integrations/linear/linear-issue-list-method.ts +++ b/src/main/runtime/rpc/methods/integrations/linear/linear-issue-list-method.ts @@ -3,7 +3,7 @@ import { defineMethod } from '../../../core' import { ListIssues, McpListIssues -} from '../../../../../../shared/rpc-contract/linear-issue-list-params' +} from '../../../../../../shared/rpc-contract/linear/linear-issue-list-params' export const LINEAR_ISSUE_LIST_METHOD = defineMethod({ name: 'linear.listIssues', diff --git a/src/main/runtime/rpc/methods/integrations/linear/linear-project-create.ts b/src/main/runtime/rpc/methods/integrations/linear/linear-project-create.ts index c44155d4cb9..acf5e0b25ac 100644 --- a/src/main/runtime/rpc/methods/integrations/linear/linear-project-create.ts +++ b/src/main/runtime/rpc/methods/integrations/linear/linear-project-create.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../../core' -import { CreateProject } from '../../../../../../shared/rpc-contract/linear-project-create-params' +import { CreateProject } from '../../../../../../shared/rpc-contract/linear/linear-project-create-params' export const LINEAR_PROJECT_CREATE_METHOD = defineMethod({ name: 'linear.createProject', diff --git a/src/main/runtime/rpc/methods/integrations/linear/linear.ts b/src/main/runtime/rpc/methods/integrations/linear/linear.ts index c1361240167..169148cebf8 100644 --- a/src/main/runtime/rpc/methods/integrations/linear/linear.ts +++ b/src/main/runtime/rpc/methods/integrations/linear/linear.ts @@ -18,7 +18,7 @@ import { SelectWorkspace, TeamId, WorkspaceSelection -} from '../../../../../../shared/rpc-contract/linear-params' +} from '../../../../../../shared/rpc-contract/linear/linear-params' export const LINEAR_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/link-preview/link-preview.ts b/src/main/runtime/rpc/methods/link-preview/link-preview.ts index 4c553b9423a..9e0e73c4fd1 100644 --- a/src/main/runtime/rpc/methods/link-preview/link-preview.ts +++ b/src/main/runtime/rpc/methods/link-preview/link-preview.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { LinkPreviewGetParams } from '../../../../../shared/rpc-contract/link-preview-params' +import { LinkPreviewGetParams } from '../../../../../shared/rpc-contract/link-preview/link-preview-params' import { getLinkPreview } from '../../../../link-preview/link-preview' export const LINK_PREVIEW_METHODS = [ diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-project-sections.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-project-sections.ts index 8e8993e9ca9..1626ebaa04f 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-project-sections.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-project-sections.ts @@ -1,9 +1,9 @@ import { defineMethod } from '../../core' import { MOBILE_PROJECT_SECTIONS_METHOD } from '../../../../../shared/mobile-project-sections-contract' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../../../shared/sidebar-inputs-switch' -import { readMobileProjectSections } from '../../../sidebar-inputs/mobile-project-sections-snapshot' -import { requireSwitchedOn } from '../../../sidebar-inputs/require-switched-on' -import { readSidebarProjectCatalog } from '../../../sidebar-inputs/sidebar-project-catalog' +import { readMobileProjectSections } from '../../../sidebar-inputs/catalog/mobile-project-sections-snapshot' +import { requireSwitchedOn } from '../../../construction/require-sidebar-inputs-enabled' +import { readSidebarProjectCatalog } from '../../../sidebar-inputs/catalog/sidebar-project-catalog' export const MOBILE_PROJECT_SECTIONS_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/native-chat/native-chat-opencode-semantic-pages.test.ts b/src/main/runtime/rpc/methods/native-chat/native-chat-opencode-semantic-pages.test.ts deleted file mode 100644 index b382b4922e7..00000000000 --- a/src/main/runtime/rpc/methods/native-chat/native-chat-opencode-semantic-pages.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import Database from '../../../../sqlite/sync-database' -import '../../../../ai-vault/session-scanner-values' -import { asRecord } from '../../../../ai-vault/session-scanner-record-value' -import { readOpenCodeTranscriptPage } from '../../../../native-chat/transcript-opencode-sqlite-query' -import { readOpenCodeNativeChatTranscriptTail } from '../../../../native-chat/transcript-opencode' -import type { SubscribeNativeChatTranscriptArgs } from '../../../../native-chat/transcript-watch-contract' -import { buildRegistry, isStreamingMethod, type RpcContext } from '../../core' - -const state: { path: string; watcher: SubscribeNativeChatTranscriptArgs | null } = vi.hoisted( - () => ({ - path: '', - watcher: null - }) -) -vi.mock('../../../../managed-data-accounts/service', () => ({ - getManagedDataAccountService: vi.fn() -})) -vi.mock('../../../../native-chat/transcript-watch', () => ({ - subscribeNativeChatTranscript: async (args: SubscribeNativeChatTranscriptArgs) => { - state.watcher = args - return { watching: true, unsubscribe: vi.fn() } - } -})) -vi.mock('../../../../native-chat/transcript-tail-reader', () => ({ - readNativeChatTranscriptTail: (args: { - sessionId: string - limit: number - beforeOffset?: number - }) => - readOpenCodeNativeChatTranscriptTail(args, { - resolveDbPath: async () => state.path, - readPage: async (page) => readOpenCodeTranscriptPage(page) - }) -})) -import { NATIVE_CHAT_METHODS } from './native-chat' - -const roots: string[] = [] -afterEach(() => { - state.watcher = null - for (const root of roots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -function fixture() { - const root = mkdtempSync(join(tmpdir(), 'orca-opencode-paired-pages-')) - roots.push(root) - state.path = join(root, 'opencode.db') - const db = new Database(state.path) - db.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY); - CREATE TABLE session_message (id TEXT, session_id TEXT, type TEXT, seq INTEGER, - data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session_v2 VALUES ('session');`) - for (let index = 1; index <= 3; index++) { - db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)').run( - String(index), - 'session', - 'assistant', - index * 7, - JSON.stringify({ - content: [ - { type: 'reasoning', text: `thinking ${index}` }, - { type: 'text', text: `answer ${index}` } - ] - }), - 1, - 1 - ) - } - db.close() -} - -function context(): RpcContext { - const runtime = { - getAgentProviderSessionRows: () => [], - registerSubscriptionCleanup: vi.fn(), - cleanupSubscription: vi.fn() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These handlers only read hook rows and register or invoke subscription cleanup on the runtime. - return { runtime: runtime as unknown as RpcContext['runtime'], clientKind: 'mobile' } -} - -describe.each(['opencode', 'opencode2'])('%s paired semantic pages', (agent) => { - it('reconstructs reasoning and answers across raw-row cursors at limit 1', async () => { - fixture() - const method = buildRegistry(NATIVE_CHAT_METHODS).get('nativeChat.readSession')! - if (isStreamingMethod(method)) { - throw new Error('Expected a page read') - } - const pages: string[][] = [] - let beforeOffset: number | undefined - for (let index = 0; index < 4; index++) { - const params = method.params?.parse({ agent, sessionId: 'session', limit: 1, beforeOffset }) - const result = asRecord(await method.handler(params, context())) - expect(result?.hasMore).toBe(index < 2) - const messages = Array.isArray(result?.messages) ? result.messages : [] - expect(messages.map((message) => asRecord(message)?.role)).toEqual(['reasoning', 'assistant']) - pages.push(messages.map((message) => String(asRecord(message)?.id))) - if (result?.hasMore !== true) { - break - } - expect(typeof result.beforeOffset).toBe('number') - beforeOffset = typeof result.beforeOffset === 'number' ? result.beforeOffset : undefined - } - expect(pages.toReversed().flat()).toEqual([ - 'opencode:1:reasoning', - 'opencode:1', - 'opencode:2:reasoning', - 'opencode:2', - 'opencode:3:reasoning', - 'opencode:3' - ]) - }) -}) diff --git a/src/main/runtime/rpc/methods/native-chat/native-chat-resume.test.ts b/src/main/runtime/rpc/methods/native-chat/native-chat-resume.test.ts index 9fe0a34a4a1..82a2b03e3a4 100644 --- a/src/main/runtime/rpc/methods/native-chat/native-chat-resume.test.ts +++ b/src/main/runtime/rpc/methods/native-chat/native-chat-resume.test.ts @@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import '../../../../../shared/rpc-contract/native-chat-params' +import '../../../../../shared/rpc-contract/native-chat/native-chat-params' import { RuntimeSubscriptionRegistry } from '../../../client/runtime-subscription-registry' import type { RpcContext } from '../../core' diff --git a/src/main/runtime/rpc/methods/native-chat/native-chat-subscription-token.test.ts b/src/main/runtime/rpc/methods/native-chat/native-chat-subscription-token.test.ts deleted file mode 100644 index 40388cb1654..00000000000 --- a/src/main/runtime/rpc/methods/native-chat/native-chat-subscription-token.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RuntimeSubscriptionRegistry } from '../../../client/runtime-subscription-registry' -import type { RpcContext } from '../../core' - -vi.mock('../../../../native-chat/transcript-watch', () => ({ - subscribeNativeChatTranscript: () => Promise.resolve({ unsubscribe: () => {}, watching: true }) -})) -vi.mock('../../../../native-chat/transcript-tail-reader', () => ({ - readNativeChatTranscriptTail: vi.fn() -})) - -import { NATIVE_CHAT_METHODS } from './native-chat' - -type Handler = ( - params: unknown, - ctx: RpcContext, - emit: (value: unknown) => void -) => Promise - -function handler(name: string): Handler { - const method = NATIVE_CHAT_METHODS.find((candidate) => candidate.name === name) - if (!method) { - throw new Error(`${name} not registered`) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: both methods take (params, ctx[, emit]); the test only calls them with that shape. - return method.handler as Handler -} - -/** One phone connection on a runtime whose subscriptions live in the real registry. */ -function phoneConnection(): { - subscribe: (subscriptionId: string) => Promise - unsubscribe: (subscriptionId: string) => Promise -} { - const registry = new RuntimeSubscriptionRegistry() - const context: RpcContext = { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers under test only touch these registry-backed members and the hook rows. - runtime: { - getAgentProviderSessionRows: () => [], - registerSubscriptionCleanup: registry.register.bind(registry), - cleanupSubscription: registry.cleanup.bind(registry), - cleanupSubscriptionsByPrefix: registry.cleanupByPrefix.bind(registry) - } as unknown as RpcContext['runtime'], - connectionId: 'phone-connection', - clientKind: 'mobile' - } - return { - subscribe: async (subscriptionId) => { - const emitted: unknown[] = [] - await handler('nativeChat.subscribe')( - { agent: 'claude', sessionId: 'session', subscriptionId }, - context, - (value) => emitted.push(value) - ) - return emitted - }, - unsubscribe: async (subscriptionId) => { - await handler('nativeChat.unsubscribe')({ subscriptionId }, context, () => {}) - } - } -} - -describe('nativeChat subscription tokens on one connection', () => { - it('keeps two feeds of the same chat apart when each has its own token', async () => { - const phone = phoneConnection() - const under = await phone.subscribe('claude:session:under') - const top = await phone.subscribe('claude:session:top') - expect(under).toEqual([]) - expect(top).toEqual([]) - - await phone.unsubscribe('claude:session:top') - expect(top).toEqual([{ type: 'end' }]) - expect(under).toEqual([]) - }) - - it('ends the older feed when a second one reuses its token', async () => { - const phone = phoneConnection() - const older = await phone.subscribe('claude:session') - const newer = await phone.subscribe('claude:session') - expect(older).toEqual([{ type: 'end' }]) - expect(newer).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/methods/native-chat/native-chat.test.ts b/src/main/runtime/rpc/methods/native-chat/native-chat.test.ts index 045aa5b7742..8d77b225d5a 100644 --- a/src/main/runtime/rpc/methods/native-chat/native-chat.test.ts +++ b/src/main/runtime/rpc/methods/native-chat/native-chat.test.ts @@ -371,20 +371,6 @@ describe('nativeChat.subscribe initial snapshot', () => { expect((emitted[1] as { pending?: boolean }).pending).toBeUndefined() }) - it('does not publish pending semantics to a legacy client', async () => { - watcher.watching = true - watcher.args = null - const emitted: unknown[] = [] - await subscribeHandler()( - { agent: 'claude', sessionId: 's' }, - streamingContext('mobile'), - (value) => emitted.push(value) - ) - - expect(activeWatcherArgs().onTranscriptPending).toBeUndefined() - expect(emitted).toEqual([]) - }) - it('emits one windowed snapshot with pagination state before live appends', async () => { watcher.watching = true watcher.args = null @@ -419,26 +405,6 @@ describe('nativeChat.subscribe initial snapshot', () => { expect((emitted[1] as { messages: NativeChatMessage[] }).messages).toHaveLength(60) }) - it('emits an explicit error snapshot when no transcript can be watched', async () => { - watcher.watching = false - watcher.args = null - const emitted: unknown[] = [] - await subscribeHandler()( - { agent: 'claude', sessionId: 'missing' }, - streamingContext('mobile'), - (value) => emitted.push(value) - ) - - expect(emitted).toEqual([ - { - type: 'snapshot', - messages: [], - hasMore: false, - error: 'Transcript unavailable' - } - ]) - }) - it('cancels pending setup when the stream is cleaned up', async () => { const cleanups = new Map void>() const context = streamingContext('mobile') @@ -511,20 +477,4 @@ describe('nativeChat.subscribe initial snapshot', () => { watcher.setupFactory = null } }) - - it('skips setup for an already-cancelled request', async () => { - const controller = new AbortController() - controller.abort() - const context = { ...streamingContext('mobile'), signal: controller.signal } - watcher.args = null - const emitted: unknown[] = [] - - await subscribeHandler()({ agent: 'claude', sessionId: 'already-closed' }, context, (value) => - emitted.push(value) - ) - - expect(context.runtime.registerSubscriptionCleanup).not.toHaveBeenCalled() - expect(watcher.args).toBeNull() - expect(emitted).toEqual([]) - }) }) diff --git a/src/main/runtime/rpc/methods/native-chat/native-chat.ts b/src/main/runtime/rpc/methods/native-chat/native-chat.ts index 0c0871ef268..9ae0e4acf5d 100644 --- a/src/main/runtime/rpc/methods/native-chat/native-chat.ts +++ b/src/main/runtime/rpc/methods/native-chat/native-chat.ts @@ -10,8 +10,8 @@ import { readNativeChatTranscriptTail } from '../../../../native-chat/transcript import type { NativeChatTranscriptSubscription, SubscribeNativeChatTranscriptArgs -} from '../../../../native-chat/transcript-watch-contract' -import { nativeChatTranscriptPathOnExecutionHost } from '../../../../native-chat/ssh-transcript-path' +} from '../../../../native-chat/transcript-watching/transcript-watch-contract' +import { nativeChatTranscriptPathOnExecutionHost } from '../../../../native-chat/transcript-filesystem/ssh-transcript-path' import { defineMethod, defineStreamingMethod, type RpcContext } from '../../core' import { sanitizeNativeChatRpcBlock } from './native-chat-rpc-block-sanitize' import { @@ -23,7 +23,7 @@ import { NativeChatSession, NativeChatUnsubscribe, type NativeChatResumePoint -} from '../../../../../shared/rpc-contract/native-chat-params' +} from '../../../../../shared/rpc-contract/native-chat/native-chat-params' // Default to a small transcript tail for fast paired-client paint; clients page older history, while local IPC stays virtualized. const MOBILE_NATIVE_CHAT_DEFAULT_WINDOW = 40 diff --git a/src/main/runtime/rpc/methods/notifications/notifications.ts b/src/main/runtime/rpc/methods/notifications/notifications.ts index 18472f00d22..4fb53af3d2f 100644 --- a/src/main/runtime/rpc/methods/notifications/notifications.ts +++ b/src/main/runtime/rpc/methods/notifications/notifications.ts @@ -7,7 +7,7 @@ import { NotificationReportDesktopPresenceParams, NotificationUnsubscribeParams, NotificationsSubscribeParams -} from '../../../../../shared/rpc-contract/notifications-params' +} from '../../../../../shared/rpc-contract/notifications/notifications-params' // Use a per-process counter so same-millisecond subscriptions cannot collide. let notificationsSubscriptionSeq = 0 diff --git a/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts b/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts index 1f570dab21a..ba0d755f1c8 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest' -import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/migration/orcad-migration-manifest-digest' import type { OrcaRuntimeService } from '../../../orca-runtime' import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' import '../rpc-method-registry' @@ -62,39 +62,6 @@ function context( } describe('orcad migration RPC', () => { - it.each([ - ['mobile client', { clientKind: 'mobile', pairedDeviceId: 'paired-phone' }], - ['unpaired runtime client', { clientKind: 'runtime', pairedDeviceId: undefined }], - ['local caller', { clientKind: undefined, pairedDeviceId: undefined }] - ] as const)('rejects a %s before any migration mutation', async (_label, caller) => { - for (const name of MIGRATION_METHOD_NAMES) { - const invoke = vi.fn() - const method = migrationMethod(name) - const runtimeMethod = - name === 'orcad.migration.stageCatalog' - ? 'stageOrcadMigrationCatalog' - : name === 'orcad.migration.commitCatalog' - ? 'commitStagedOrcadMigrationCatalog' - : name === 'orcad.migration.stageSnapshotChunk' - ? 'stageOrcadMigrationSnapshotChunk' - : name === 'orcad.migration.stageBlobChunk' - ? 'stageOrcadMigrationBlobChunk' - : name === 'orcad.migration.abortCatalog' - ? 'abortStagedOrcadMigrationCatalog' - : name === 'orcad.migration.abortCatalogByReference' - ? 'abortStagedOrcadMigrationCatalogByReference' - : 'getOrcadMigrationCatalogState' - - await expect( - method.handler( - method.params?.parse(migrationMethodInput(name)), - context(invoke, caller, { [runtimeMethod]: invoke }) - ) - ).rejects.toThrow('orcad_migration_runtime_client_required') - expect(invoke).not.toHaveBeenCalled() - } - }) - it('rejects malformed and tampered manifests before staging', async () => { const stageCatalog = vi.fn() const method = migrationMethod() @@ -150,36 +117,3 @@ describe('orcad migration RPC', () => { expect(stageCatalog).toHaveBeenCalledTimes(1) }) }) - -function migrationSnapshotRequest(input: OrcadMigrationManifest) { - return { - migrationId: input.migrationId, - manifestSha256: input.manifestSha256, - ref: `v1-${'1'.repeat(32)}`, - offset: 0, - bytesBase64: 'YQ==' - } -} - -function migrationMethodInput(name: (typeof MIGRATION_METHOD_NAMES)[number]) { - const input = manifest() - if (name === 'orcad.migration.stageBlobChunk') { - return migrationBlobRequest(input) - } - if (name === 'orcad.migration.abortCatalogByReference') { - return { migrationId: input.migrationId, manifestSha256: input.manifestSha256 } - } - return name === 'orcad.migration.stageSnapshotChunk' - ? migrationSnapshotRequest(input) - : { manifest: input } -} - -function migrationBlobRequest(input: OrcadMigrationManifest, key = `${'a'.repeat(16)}-zsh`) { - return { - migrationId: input.migrationId, - manifestSha256: input.manifestSha256, - blob: { blobKind: 'shell-history', key, sha256: 'b'.repeat(64), byteLength: 1 }, - offset: 0, - bytesBase64: 'YQ==' - } -} diff --git a/src/main/runtime/rpc/methods/orcad/orcad-migration.ts b/src/main/runtime/rpc/methods/orcad/orcad-migration.ts index 0ff85c6b71c..41bf7194416 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-migration.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-migration.ts @@ -3,12 +3,12 @@ import { OrcadMigrationCatalogParams, OrcadMigrationCatalogReferenceParams, OrcadMigrationCommitCatalogParams -} from '../../../../../shared/rpc-contract/orcad-migration-params' +} from '../../../../../shared/rpc-contract/host-management/orcad-migration-params' import { parseOrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' import { OrcadMigrationSnapshotChunkRequestSchema } from '../../../../../shared/orcad-migration/orcad-migration-scrollback' import { OrcadMigrationBlobChunkRequestSchema } from '../../../../../shared/orcad-migration/orcad-migration-blob-transfer' -import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' -import { assertOrcadMigrationSourceServedHere } from '../../../../orcad/orcad-migration-wsl-destination' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/migration/orcad-migration-manifest-digest' +import { assertOrcadMigrationSourceServedHere } from '../../../../orcad/migration/orcad-migration-wsl-destination' import { defineMethod, type RpcContext } from '../../core' export const ORCAD_MIGRATION_METHODS = [ diff --git a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts index 953c6b65120..bcfb8bb819c 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts @@ -1,7 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const collect = vi.hoisted(() => vi.fn()) -vi.mock('../../../../orcad/orcad-terminal-census', () => ({ collectOrcadTerminalCensus: collect })) +vi.mock('../../../../orcad/diagnostics/orcad-terminal-census', () => ({ + collectOrcadTerminalCensus: collect +})) import { ORCAD_TERMINAL_CENSUS_METHODS } from './orcad-terminal-census' import { TerminalUpdateAdmission } from '../../../terminal/stop/terminal-update-admission' diff --git a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts index 701ea5b00fd..5358e113543 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts @@ -40,7 +40,8 @@ async function countTerminals( runtime: Pick ): Promise { // Import lazily: daemon modules install xterm's global window and must not contaminate every dispatcher process. - const { collectOrcadTerminalCensus } = await import('../../../../orcad/orcad-terminal-census') + const { collectOrcadTerminalCensus } = + await import('../../../../orcad/diagnostics/orcad-terminal-census') if (!params.releaseFinishedAutomationTerminals) { return collectOrcadTerminalCensus(params.activatedAt) } diff --git a/src/main/runtime/rpc/methods/orchestration/access/worker-approval-access.ts b/src/main/runtime/rpc/methods/orchestration/access/worker-approval-access.ts new file mode 100644 index 00000000000..a2599908f8d --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/worker-approval-access.ts @@ -0,0 +1,39 @@ +import type { z } from 'zod' +import type { ApprovalAnswerParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-approval-answer-params' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { OrchestrationAccessRuleInput } from './orchestration-method-access' + +export type WorkerApprovalAccess = { answeredBy: 'person' | 'coordinator'; reason: string | null } + +/** Approve requires a person, or an agent caller when the user's setting is on; deny allows an agent + * or a person. A person is proven by the transport: only the desktop app's own IPC. A paired device + * can carry a remote CLI, so it counts as an agent. The setting read is this machine's, which runs + * the worker. */ +export function workerApprovalAccess({ + params, + ctx +}: OrchestrationAccessRuleInput>): WorkerApprovalAccess { + const person = ctx.caller?.kind === 'desktop' + const reason = params.reason?.trim() || null + // Without a reason it is not a coordinator's approve: a person on a remote-connected desktop + // sends none, and keeps the refusal they always got. + if ( + params.decision === 'allow' && + !person && + !(reason && ctx.runtime.coordinatorApprovalsEnabled()) + ) { + throw new OrchestrationError( + 'approval_requires_person', + `Only a person can allow ${params.prompt}, from Orca or the worker itself. You can deny it with a reason, or leave it for the person.`, + { effectsApplied: false } + ) + } + if (!person && !reason) { + throw new OrchestrationError( + 'invalid_argument', + 'Missing --reason: tell the worker what to do instead.', + { effectsApplied: false } + ) + } + return { answeredBy: person ? 'person' : 'coordinator', reason } +} diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index 5d0acbef31b..8ec4d8dd75a 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -11,7 +11,7 @@ import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../../. import { PartyLocationParams, SessionAddressParams -} from '../../../../../shared/rpc-contract/orchestration-params' +} from '../../../../../shared/rpc-contract/orchestration/orchestration-params' import { OrchestrationError } from '../../../orchestration/orchestration-error' import { resolveOrcaSessionParty } from '../../../orchestration/addressing/orchestration-party' import { locateOrchestrationParty } from '../../../orchestration/addressing/orchestration-party-location' @@ -20,7 +20,7 @@ import type { z } from 'zod' import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db' import type { RpcContext } from '../../core' import { defineOrchestrationMethod } from './access/orchestration-method-access' -import { openClosedWorkerTerminal } from './worker/closed-worker-terminal' +import { openClosedWorkerTerminal } from './worker/follow-up/closed-worker-terminal' import { ensureStructuredHostInstalled } from '../structured-sessions/creation/structured-agent-session-gate' async function locateParty( diff --git a/src/main/runtime/rpc/methods/orchestration/chat-assignee-admission.ts b/src/main/runtime/rpc/methods/orchestration/chat-assignee-admission.ts index f56534a2f6b..5a7cbc141be 100644 --- a/src/main/runtime/rpc/methods/orchestration/chat-assignee-admission.ts +++ b/src/main/runtime/rpc/methods/orchestration/chat-assignee-admission.ts @@ -11,7 +11,10 @@ import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db import { OrchestrationError } from '../../../orchestration/orchestration-error' import type { OrchestrationPartyIdentity as OrchestrationParty } from '../../../../../shared/orchestration/mailbox/orchestration-party-identity' import { readAgentSessionRecordStore } from '../../../orchestration/addressing/session-lineage/structured-session-lineage' -import { refuseUndeliverableSessionRecipient } from './messaging/session-recipient' +import { + refuseUndeliverableSessionRecipient, + resolveTerminalAgentRecipient +} from './messaging/session-recipient' const NO_EFFECTS = 'No effects were applied.' @@ -31,11 +34,14 @@ export async function admitChatAssignee( ): Promise { // A failed install leaves no store, which the refusal below names. await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + const terminalRecipient = await resolveTerminalAgentRecipient(sessionId) + // Read after every wait: the store this admission checks is the one it then observes. const store = readAgentSessionRecordStore() const refusal = refuseUndeliverableSessionRecipient( { sessionId, address: formatOrcaSessionAddress(sessionId) }, store, db, + terminalRecipient, NO_EFFECTS ) if (refusal) { diff --git a/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts b/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts index 1b37b5c220f..e0a58382ac5 100644 --- a/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts @@ -26,8 +26,7 @@ describe('orchestration CLI/runtime boundary', () => { afterEach(() => { h.cleanup() restoreTerminalHandle() - vi.doUnmock('../../../../../cli/format') - vi.doUnmock('../../../../../cli/runtime-client') + vi.doUnmock('../../../../../cli/output/command-result-output') vi.unstubAllEnvs() vi.restoreAllMocks() vi.resetModules() @@ -104,8 +103,8 @@ describe('orchestration CLI/runtime boundary', () => { /** Imports orchestration handlers after mocking output so the test observes state, not stdout. */ async function loadOrchestrationHandlers(): Promise> { - vi.doMock('../../../../../cli/format', () => ({ printResult: vi.fn() })) - const cliModulePath = '../../../../../cli/handlers/orchestration' + vi.doMock('../../../../../cli/output/command-result-output', () => ({ printResult: vi.fn() })) + const cliModulePath = '../../../../../cli/orchestration/orchestration-handlers' const module = (await import(cliModulePath)) as { ORCHESTRATION_HANDLERS: Record } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-terminal-claim.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-terminal-claim.test.ts index db2443cfaed..5be900debbb 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-terminal-claim.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-terminal-claim.test.ts @@ -7,7 +7,7 @@ import '../../../../orchestration/db/dispatch-row-writer' import '../../../../orchestration/db/attempt-outcome-projection' import { refuseClaimedWorkerTerminal } from '../../../../orchestration/db/worker-dispatch/worker-terminal-claim' import { ORCHESTRATION_METHODS } from '../orchestration' -import { configureFederationWorkerRuntime } from './federation-runtime.test-support' +import { configureFederationWorkerRuntime } from './testing/federation-runtime.test-support' const TERMINAL = 'term_windows_worker' diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts index 571b6eb881d..4b63973e9c3 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts @@ -1,15 +1,12 @@ import { describe, expect, it, vi } from 'vitest' -import { - ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, - ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY -} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { OrcaRuntimeService } from '../../../../orca-runtime' +import { ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' import '../../../../orchestration/legacy-remote-home/federated-worker-read' import { releaseFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-release' -import '../worker/worker-observation' +import '../worker/observation/worker-observation' import '../../../../orchestration/legacy-remote-home/federation-sync' import { ORCHESTRATION_WORKER_STOP_METHODS } from '../worker/worker-stop' @@ -21,46 +18,6 @@ const server = { } describe('federated transport safety', () => { - it('uses the same pairing-revision fence for mutation preflight and effect calls', async () => { - const call = vi.fn(async (_selector, method: string) => ({ - id: method, - ok: true as const, - result: - method === 'status.get' - ? runtimeStatus([ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY]) - : { - dispatchId: 'dispatch-worker', - state: 'released', - processAction: 'closed_agent_terminal', - archive: null - }, - _meta: { runtimeId: 'epoch-worker' } - })) - const runtime = new OrcaRuntimeService(null, undefined, { - orchestrationEnvironmentTransport: { - resolve: () => server, - call - } - }) - - await runtime.callOrchestrationWorkerServer( - server.environmentId, - 'orchestration.federationRelease', - { dispatchId: 'dispatch-worker' }, - 30_000, - { orchestrationRequestId: 'release-request' }, - { expectedEnvironmentPairingRevision: server.pairingRevision } - ) - - expect(call.mock.calls.map((entry) => entry[1])).toEqual([ - 'status.get', - 'orchestration.federationRelease' - ]) - for (const entry of call.mock.calls) { - expect((entry as unknown[])[5]).toBe(73) - } - }) - it('rejects a mismatched release receipt before applying home effects', async () => { const transitionLifecycle = vi.fn() const db = { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-auto-release-scenarios.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-auto-release-scenarios.test-support.ts deleted file mode 100644 index 715b3d1d4cb..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-auto-release-scenarios.test-support.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import type { RuntimeRpcResponse } from '../../../../../../shared/runtime-rpc-envelope' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { RpcRequest } from '../../../core' -import { registerHomeAutoReleaseScenarios } from './federation-home-auto-release-scenarios.test-support' -import { GRACE_MS } from './federation-auto-release-grace.test-support' - -export type AutoReleaseScenarioHarness = { - startRemoteWorker: () => Promise - dispatchHome: (request: RpcRequest) => Promise> - dispatchWorker: (request: RpcRequest) => Promise> - syncHome: (dispatchId: string) => Promise - workerRuntime: () => OrcaRuntimeService - homeRuntime: () => OrcaRuntimeService - homeDb: () => OrchestrationDb - workerDb: () => OrchestrationDb - remoteCalls: () => string[] - // Mixed versions: a host without the capability, or a home that never opts in on ack. - setWorkerAdvertisesAutoRelease: (advertised: boolean) => void - setHomeOmitsAutoRelease: (omitted: boolean) => void -} - -export function registerFederatedAutoReleaseScenarios(harness: AutoReleaseScenarioHarness): void { - afterEach(() => { - getWorkerTerminalAutoReleaseScheduler(harness.workerRuntime()).clear() - getWorkerTerminalAutoReleaseScheduler(harness.homeRuntime()).clear() - vi.useRealTimers() - }) - - async function settleRemotely(): Promise { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(new Date('2026-10-27T12:00:00Z')) - const dispatchId = await harness.startRemoteWorker() - const taskId = harness.homeDb().getDispatchContextById(dispatchId)!.task_id - const sent = harness.dispatchWorker({ - id: 'rpc_remote_worker_done', - authToken: 'worker-local-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'remote_worker_done', - method: 'orchestration.send', - params: { - from: 'term_windows_worker', - subject: 'Done', - type: 'worker_done', - payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded' }) - } - }) - await vi.waitFor(() => - expect(harness.workerDb().listPendingFederationRelay(dispatchId, 'to_home')).toHaveLength(1) - ) - // Queued, not yet accepted by the home: no deadline. - expect(harness.workerDb().getWorkerTerminalResourceByOwner(dispatchId)?.auto_release_at).toBe( - null - ) - await harness.syncHome(dispatchId) - await expect(sent).resolves.toMatchObject({ ok: true }) - return dispatchId - } - - function retainFromHome(dispatchId: string) { - return harness.dispatchHome({ - id: 'rpc_remote_retain', - authToken: 'coordinator-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'remote_retain', - method: 'orchestration.workerRetain', - params: { dispatch: dispatchId } - }) - } - - function holdHostCapture() { - const read = { - handle: 'term_windows_worker', - status: 'running' as const, - tail: ['remote output'], - truncated: false, - nextCursor: '1' - } - const held: (() => void)[] = [] - vi.mocked(harness.workerRuntime().readTerminal).mockImplementation( - () => new Promise((resolve) => held.push(() => resolve(read))) - ) - return () => { - vi.mocked(harness.workerRuntime().readTerminal).mockResolvedValue(read) - held.splice(0).forEach((release) => release()) - } - } - - it('publishes no archive when worker-retain wins during host capture', async () => { - const dispatchId = await settleRemotely() - const finishCapture = holdHostCapture() - vi.setSystemTime(Date.now() + GRACE_MS) - const timer = getWorkerTerminalAutoReleaseScheduler(harness.workerRuntime()).releaseDue() - await vi.waitFor(() => expect(harness.workerRuntime().readTerminal).toHaveBeenCalled()) - - await expect(retainFromHome(dispatchId)).resolves.toMatchObject({ ok: true }) - finishCapture() - await timer - - expect(harness.workerRuntime().closeTerminal).not.toHaveBeenCalled() - expect(harness.workerDb().getWorkerTerminalArchive(dispatchId)).toBeUndefined() - }) - - registerHomeAutoReleaseScenarios({ harness, settleRemotely }) -} diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-child-lineage-origin.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-child-lineage-origin.test.ts deleted file mode 100644 index 90e78bd74fd..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-child-lineage-origin.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { crossStoreCreateLineage } from '../../../../workspaces/lineage/runtime-worktree-lineage-recording' -import { ORCHESTRATION_METHODS } from '../orchestration' - -const PARENT = { - installationId: 'home-install', - workspaceKey: 'worktree:repo::/home/parent', - instanceId: 'parent-instance' -} - -describe('a server nesting an orchestration worker under a workspace on another machine', () => { - let db: OrchestrationDb | undefined - - afterEach(() => db?.close()) - - async function createdLineage(attach: Record) { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: worktree-creation support reads only id and kind. - vi.spyOn(runtime, 'showRepo').mockResolvedValue({ id: 'repo', kind: 'git' } as never) - const create = vi - .spyOn(runtime, 'createManagedWorktree') - .mockRejectedValue(new Error('stop after create args')) - const method = ORCHESTRATION_METHODS.find( - (candidate) => candidate.name === 'orchestration.federationAttachStart' - )! - await method - .handler( - method.params!.parse({ - runId: 'run-home', - dispatchId: 'ctx_child', - taskId: 'task_child', - taskSpec: 'work on the server', - protocolVersion: 3, - worktree: 'new-top-level', - repo: 'repo', - name: 'child', - agent: 'codex', - crossStoreParent: PARENT, - ...attach - }), - { - runtime, - orchestrationMutation: { - callerFingerprint: 'home_peer', - requestId: 'request_child', - method: 'orchestration.federationAttachStart', - payloadHash: 'child_payload' - } - } - ) - .catch(() => undefined) - const lineage = create.mock.calls[0]?.[0].lineage - if (!lineage?.crossStoreParent) { - throw new Error('the server created no nested worktree') - } - return crossStoreCreateLineage({ ...lineage, crossStoreParent: lineage.crossStoreParent }) - } - - it('records orchestration as the origin when orchestration picked the parent', async () => { - await expect( - createdLineage({ crossStoreParentInferredFrom: 'orchestration-context' }) - ).resolves.toEqual({ - kind: 'crossStore', - parent: PARENT, - origin: 'orchestration', - capture: { source: 'orchestration-context', confidence: 'inferred' } - }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts index 79f9710cc50..bfce33ad975 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts @@ -12,7 +12,7 @@ import type { RpcRequest } from '../../../core' import { RpcDispatcher } from '../../../dispatcher' import { fingerprintAuthenticatedPairingCredential } from '../../../server/pairing/device-principal' import { ORCHESTRATION_METHODS } from '../orchestration' -import { syncFederationBarrier } from './federation-sync-barrier.test-support' +import { syncFederationBarrier } from './testing/federation-sync-barrier.test-support' describe('orchestration federation control mail', () => { const homeToken = 'run-home-device-token' @@ -186,26 +186,6 @@ describe('orchestration federation control mail', () => { expect(homeDb.listPendingFederationRelay(dispatchId, 'to_worker')).toHaveLength(0) }) - it('wakes a remote worker waiter when control mail imports', async () => { - const waiting = workerDispatcher.dispatch(checkRequest('wait-for-control', true)) - await Promise.resolve() - - const imported = await dispatchImport(importRequest('import-control', 1, 'relay-control')) - - expect(imported).toMatchObject({ - ok: true, - result: { acknowledgedThrough: 1, imported: 1 } - }) - await expect(waiting).resolves.toMatchObject({ - ok: true, - result: { - dispatchId, - count: 1, - messages: [{ id: 'relay-control', subject: 'Continue' }] - } - }) - }) - it('accepts a repeated import after a lost acknowledgment without duplicating mail', async () => { const first = await dispatchImport(importRequest('first-import', 1, 'relay-control')) const repeated = await dispatchImport( diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-output.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-output.test.ts index e262626474d..2fb7be231a7 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-output.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-output.test.ts @@ -15,8 +15,8 @@ import type { RpcRequest } from '../../../core' import { RpcDispatcher } from '../../../dispatcher' import { ORCHESTRATION_METHODS } from '../orchestration' -import { registerFederatedAutoReleaseScenarios } from './federation-auto-release-scenarios.test-support' -import { olderPeerStatusResponse } from './federation-peer-capabilities.test-support' +import { registerFederatedAutoReleaseScenarios } from './testing/federation-auto-release-scenarios.test-support' +import { olderPeerStatusResponse } from './testing/federation-peer-capabilities.test-support' describe('orchestration federated worker output', () => { const databases: OrchestrationDb[] = [] @@ -297,36 +297,6 @@ describe('orchestration federated worker output', () => { return dispatchId } - it('routes show and read by Dispatch without repeating the worker server', async () => { - const dispatchId = await startRemoteWorker() - - const shown = await homeCall('rpc_remote_show', 'orchestration.workerShow', { - dispatch: dispatchId - }) - const read = await homeCall('rpc_remote_read', 'orchestration.workerRead', { - dispatch: dispatchId, - limit: 20 - }) - - expect(shown).toMatchObject({ - ok: true, - result: { - server: { environmentId: 'environment_windows', name: 'windows' }, - observation: { status: 'live', exactWorker: true }, - terminal: { handle: 'term_windows_worker' } - } - }) - expect(read).toMatchObject({ - ok: true, - result: { - source: 'terminal', - fallbackReason: 'session_not_reported', - server: { environmentId: 'environment_windows', name: 'windows' }, - terminal: { tail: ['remote output'] } - } - }) - }) - it('reads the exact transcript on the worker server without leaking its path home', async () => { const dispatchId = await startRemoteWorker() const directory = await mkdtemp(join(tmpdir(), 'orca-federated-worker-output-')) @@ -377,20 +347,10 @@ describe('orchestration federated worker output', () => { } }) - it('serves a durable redacted archive after remote terminal removal and host restart', async () => { + it('releases a remote worker with no transcript and says its output is unavailable, across a host restart', async () => { const dispatchId = await startSettledRemoteWorker() - const capability = `dcap_${'A'.repeat(43)}` - vi.mocked(workerRuntime.readTerminal).mockResolvedValue({ - handle: 'term_windows_worker', - status: 'running', - tail: ['x'.repeat(300_000), `secret ${capability}`, 'remote output'], - truncated: false, - nextCursor: '3' - }) vi.mocked(workerRuntime.closeTerminal).mockImplementation(async () => { - const archive = workerDb.getWorkerTerminalArchive(dispatchId) - expect(archive).toBeDefined() - expect(archive!.content.length).toBeLessThan(270_000) + expect(workerDb.getWorkerTerminalArchive(dispatchId)?.kind).toBe('terminal_tail') workerTerminalAvailable = false return { ptyKilled: true } as never }) @@ -405,42 +365,25 @@ describe('orchestration federated worker output', () => { }) expect(released).toMatchObject({ ok: true, - result: { state: 'released', archive: { source: 'terminal', status: 'captured' } } + result: { state: 'released', archive: { source: 'terminal', status: 'unavailable' } } }) - const afterRemoval = await homeCall( - 'rpc_remote_read_archive_after_removal', - 'orchestration.workerRead', - { dispatch: dispatchId } - ) - expect(afterRemoval).toMatchObject({ - ok: true, - result: { - archived: true, - terminal: { - tail: ['secret [dispatch capability redacted]', 'remote output'], - truncated: true - } - } - }) - expect(JSON.stringify(afterRemoval)).not.toContain(capability) + const unavailable = { + ok: false, + error: { code: 'archive_unavailable', message: expect.stringContaining('worker_done') } + } + await expect( + homeCall('rpc_remote_read_archive_after_removal', 'orchestration.workerRead', { + dispatch: dispatchId + }) + ).resolves.toMatchObject(unavailable) restartWorkerRuntime(true) - const afterRestart = await homeCall( - 'rpc_remote_read_archive_after_restart', - 'orchestration.workerRead', - { dispatch: dispatchId } - ) - expect(afterRestart).toMatchObject({ - ok: true, - result: { - archived: true, - terminal: { - tail: ['secret [dispatch capability redacted]', 'remote output'], - truncated: true - } - } - }) + await expect( + homeCall('rpc_remote_read_archive_after_restart', 'orchestration.workerRead', { + dispatch: dispatchId + }) + ).resolves.toMatchObject(unavailable) const replayed = await homeDispatcher.dispatch({ id: 'rpc_remote_release_archive_replay', @@ -455,7 +398,7 @@ describe('orchestration federated worker output', () => { result: { state: 'already_released', processAction: 'none', - archive: { source: 'terminal', status: 'captured' } + archive: { source: 'terminal', status: 'unavailable' } } }) expect(workerRuntime.closeTerminal).not.toHaveBeenCalled() @@ -482,84 +425,4 @@ describe('orchestration federated worker output', () => { homeOmitsAutoRelease = omitted } }) - - it('does not report a captured remote archive or close when persistence fails', async () => { - const dispatchId = await startRemoteWorker() - workerDb.db.exec('DROP TABLE worker_terminal_archives') - - const released = await homeDispatcher.dispatch({ - id: 'rpc_remote_release_archive_failure', - authToken: 'coordinator-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'remote_release_archive_failure', - method: 'orchestration.workerRelease', - params: { dispatch: dispatchId } - }) - - expect(released).toMatchObject({ - ok: true, - result: { state: 'retained', processAction: 'none', archive: null } - }) - expect(workerRuntime.closeTerminal).not.toHaveBeenCalled() - }) - - it('keeps reads, fleet snapshots, and release on legacy fallbacks for an old peer', async () => { - workerAdvertisesNewCapabilities = false - // Ask shipped hosts directly for structured output; only method_not_found permits terminal fallback. - workerSupportsStructuredRead = false - const dispatchId = await startRemoteWorker() - remoteCalls = [] - const read = await homeCall('rpc_old_peer_read', 'orchestration.workerRead', { - dispatch: dispatchId - }) - const fleet = await homeCall('rpc_old_peer_fleet', 'orchestration.workerList', { - includeRemote: true - }) - const release = await homeDispatcher.dispatch({ - id: 'rpc_old_peer_release', - authToken: 'coordinator-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'old_peer_release', - method: 'orchestration.workerRelease', - params: { dispatch: dispatchId } - }) - - expect(read).toMatchObject({ - ok: true, - result: { fallbackReason: 'remote_capability_unavailable' } - }) - expect(fleet).toMatchObject({ - ok: true, - result: { partialHostErrors: [{ code: 'capability_unsupported' }] } - }) - expect(release).toMatchObject({ - ok: true, - result: { state: 'retained', reason: 'federation_unsupported' } - }) - expect(remoteCalls).toContain('orchestration.federationReadOutput') - expect(remoteCalls).toContain('orchestration.federationFleetSnapshot') - expect(remoteCalls).not.toContain('orchestration.federationRelease') - }) - - it('retains a mixed-version worker when its host cannot guarantee a durable archive', async () => { - workerAdvertisesDurableRelease = false - const dispatchId = await startRemoteWorker() - remoteCalls = [] - - const release = await homeDispatcher.dispatch({ - id: 'rpc_nondurable_peer_release', - authToken: 'coordinator-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'nondurable_peer_release', - method: 'orchestration.workerRelease', - params: { dispatch: dispatchId } - }) - - expect(release).toMatchObject({ - ok: true, - result: { state: 'retained', reason: 'federation_unsupported', archive: null } - }) - expect(remoteCalls).not.toContain('orchestration.federationRelease') - expect(workerRuntime.closeTerminal).not.toHaveBeenCalled() - }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts deleted file mode 100644 index 1a92079167b..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' - -// Await the next relay round: the current coalesced tick may have read peers before the latest mutation. -export async function syncFederationBarrier( - runtime: OrcaRuntimeService, - db: OrchestrationDb -): Promise { - const dispatches = db.listActiveFederatedDispatches() - await Promise.allSettled( - dispatches.map((dispatch) => - runtime.syncOrchestrationFederatedDispatchAfterCurrent(dispatch.dispatch_id) - ) - ) -} diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-worker-brief-agent-in-front.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-worker-brief-agent-in-front.test.ts index 3a611bb8856..3c548ff71fb 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-worker-brief-agent-in-front.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-worker-brief-agent-in-front.test.ts @@ -7,7 +7,7 @@ import '../../../../orchestration/db/dispatch-row-writer' import '../../../../orchestration/db/attempt-outcome-projection' import type { LaunchedAgentForeground } from '../../../../terminal/wait/launched-agent-foreground' import { ORCHESTRATION_METHODS } from '../orchestration' -import { configureFederationWorkerRuntime } from './federation-runtime.test-support' +import { configureFederationWorkerRuntime } from './testing/federation-runtime.test-support' const PTY_ID = 'pty_worker' @@ -22,7 +22,7 @@ describe('a paired-server worker start writes its brief only into the agent it l vi.restoreAllMocks() }) - function workerHost(foreground: LaunchedAgentForeground, provesAgent = true) { + function workerHost(foreground: LaunchedAgentForeground) { const db = new OrchestrationDb(':memory:') databases.push(db) const runtime = new OrcaRuntimeService() @@ -30,7 +30,6 @@ describe('a paired-server worker start writes its brief only into the agent it l configureFederationWorkerRuntime(runtime) const writes: string[] = [] vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue(foreground) - vi.spyOn(runtime, 'launchedAgentHostProvesAgent').mockReturnValue(provesAgent) vi.spyOn(runtime, 'subscribeToTerminalData').mockReturnValue(() => {}) vi.mocked(runtime.sendTerminalAgentPrompt).mockImplementation(async (handle, text, options) => { await options?.beforeWrite?.(PTY_ID) @@ -81,28 +80,4 @@ describe('a paired-server worker start writes its brief only into the agent it l }) expect(host.writes).toEqual([]) }) - - it('types nothing where the host cannot tell what is in front', async () => { - const host = workerHost('unknown') - - await expect(attach(host.runtime)).resolves.toMatchObject({ state: 'failed' }) - expect(host.writes).toEqual([]) - }) - - it('writes the brief once into the agent found in front', async () => { - const host = workerHost('agent') - - await expect(attach(host.runtime)).resolves.toMatchObject({ state: 'ready' }) - expect(host.writes).toHaveLength(1) - }) - - it('on a host that cannot prove the agent (Windows), writes unless a shell is proven', async () => { - const unknown = workerHost('unknown', false) - await expect(attach(unknown.runtime)).resolves.toMatchObject({ state: 'ready' }) - expect(unknown.writes).toHaveLength(1) - - const shell = workerHost('shell', false) - await expect(attach(shell.runtime)).resolves.toMatchObject({ state: 'failed' }) - expect(shell.writes).toEqual([]) - }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts index 71b368e2967..6572b196acb 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts @@ -1,4 +1,4 @@ -import { registerFederationAnswerAtomicityTest } from './federation-answer-atomicity.test-support' +import { registerFederationAnswerAtomicityTest } from './testing/federation-answer-atomicity.test-support' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' @@ -9,12 +9,12 @@ import '../../../../orchestration/db/messages/mailbox-routing-page' import '../../../../orchestration/db/dispatch-row-writer' import '../../../../orchestration/db/attempt-outcome-projection' import type { OrchestrationEnvironmentTransport } from '../../../../orchestration/federation/environment-transport' -import { attachmentHostCapabilities } from './federation-peer-capabilities.test-support' +import { attachmentHostCapabilities } from './testing/federation-peer-capabilities.test-support' import { RpcDispatcher } from '../../../dispatcher' import { ORCHESTRATION_METHODS } from '../orchestration' -import { createFederationWorkerStartRequest as startRequest } from './federation-request.test-support' -import { configureFederationWorkerRuntime } from './federation-runtime.test-support' -import { syncFederationBarrier } from './federation-sync-barrier.test-support' +import { createFederationWorkerStartRequest as startRequest } from './testing/federation-request.test-support' +import { configureFederationWorkerRuntime } from './testing/federation-runtime.test-support' +import { syncFederationBarrier } from './testing/federation-sync-barrier.test-support' describe('orchestration federation', () => { const databases: OrchestrationDb[] = [] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts index 2771bf07bc0..8513f4936d0 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -5,13 +5,13 @@ import { isGeneratedId } from '../../../../orchestration/db/generated-id' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import type { FederationRelayItemRow } from '../../../../orchestration/db/orchestration-records' import { resolveBareOrchestrationRecipient } from '../messaging/recipient-routing' -import { mayNameSession } from '../messaging/session-recipient' +import { prepareSessionRecipient } from '../messaging/session-recipient' import { waitForPeerMail } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters' import { PeerMailAckParams, PeerMailDeliverParams, PeerMailPullParams -} from '../../../../../../shared/rpc-contract/orchestration-peer-mail-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-peer-mail-params' const NOTHING_DELIVERED = { effectsApplied: false } as const const MAX_PULL_WAIT_MS = 25_000 @@ -97,11 +97,14 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ ) } // A retry after a lost answer is acknowledged even if the recipient has since gone. - const delivered = db.getPeerMailMessage(params.messageId) - if (delivered) { - const conversation = db.getPeerMailConversation(delivered.conversation_id) + const delivered = (): { message: { id: string; to: string } } | null => { + const message = db.getPeerMailMessage(params.messageId) + if (!message) { + return null + } + const conversation = db.getPeerMailConversation(message.conversation_id) if ( - delivered.conversation_id !== params.conversationId || + message.conversation_id !== params.conversationId || conversation?.peer_fingerprint !== peerFingerprint ) { throw new OrchestrationError( @@ -112,11 +115,23 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ } return { message: { id: params.messageId, to } } } - if (mayNameSession(to)) { - // Recipient routing reads the session record store, which the host opens lazily. - await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + // A replay needs no routing, so it never waits on the recipient's preparation. + const replayed = delivered() + if (replayed) { + return replayed } - const recipient = resolveBareOrchestrationRecipient({ runtime, db, handle: to }) + const terminalRecipient = await prepareSessionRecipient(runtime, to) + // Read again after the wait: a copy of this delivery may have landed meanwhile. + const landed = delivered() + if (landed) { + return landed + } + const recipient = resolveBareOrchestrationRecipient({ + runtime, + db, + handle: to, + terminalRecipient + }) if (!recipient.ok) { throw new OrchestrationError( recipient.code, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-answer-atomicity.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-answer-atomicity.test-support.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-answer-atomicity.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/federation/testing/federation-answer-atomicity.test-support.ts index 47ee98906cc..f4e367cf96b 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-answer-atomicity.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-answer-atomicity.test-support.ts @@ -1,7 +1,7 @@ import { expect, it } from 'vitest' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { RpcDispatcher } from '../../../dispatcher' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { RpcDispatcher } from '../../../../dispatcher' import { createFederationWorkerStartRequest as startRequest } from './federation-request.test-support' export function registerFederationAnswerAtomicityTest( @@ -80,7 +80,6 @@ export function registerFederationAnswerAtomicityTest( workerDb.db.exec('DROP TRIGGER ignore_answer') const { answerSenderReport: _report, ...withoutReport } = item await send('accepted-without', withoutReport) - expect(workerDb.getMessageById('answer-atomic')?.answer_sender_snapshot).toBeNull() await send('replay-with-report', item) expect(workerDb.getMessageById('answer-atomic')?.answer_sender_snapshot).toBeNull() expect(workerDb.getRemoteDispatchAttachment(dispatch.id)?.to_worker_imported_sequence).toBe(1) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-auto-release-grace.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-auto-release-grace.test-support.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-auto-release-grace.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/federation/testing/federation-auto-release-grace.test-support.ts diff --git a/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-auto-release-scenarios.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-auto-release-scenarios.test-support.ts new file mode 100644 index 00000000000..63a2aa533a6 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-auto-release-scenarios.test-support.ts @@ -0,0 +1,63 @@ +import { afterEach, expect, vi } from 'vitest' +import type { RuntimeRpcResponse } from '../../../../../../../shared/runtime-rpc-envelope' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { RpcRequest } from '../../../../core' +import { registerHomeAutoReleaseScenarios } from './federation-home-auto-release-scenarios.test-support' + +export type AutoReleaseScenarioHarness = { + startRemoteWorker: () => Promise + dispatchHome: (request: RpcRequest) => Promise> + dispatchWorker: (request: RpcRequest) => Promise> + syncHome: (dispatchId: string) => Promise + workerRuntime: () => OrcaRuntimeService + homeRuntime: () => OrcaRuntimeService + homeDb: () => OrchestrationDb + workerDb: () => OrchestrationDb + remoteCalls: () => string[] + // Mixed versions: a host without the capability, or a home that never opts in on ack. + setWorkerAdvertisesAutoRelease: (advertised: boolean) => void + setHomeOmitsAutoRelease: (omitted: boolean) => void +} + +export function registerFederatedAutoReleaseScenarios(harness: AutoReleaseScenarioHarness): void { + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(harness.workerRuntime()).clear() + getWorkerTerminalAutoReleaseScheduler(harness.homeRuntime()).clear() + vi.useRealTimers() + }) + + async function settleRemotely(): Promise { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-10-27T12:00:00Z')) + const dispatchId = await harness.startRemoteWorker() + const taskId = harness.homeDb().getDispatchContextById(dispatchId)!.task_id + const sent = harness.dispatchWorker({ + id: 'rpc_remote_worker_done', + authToken: 'worker-local-token', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: 'remote_worker_done', + method: 'orchestration.send', + params: { + from: 'term_windows_worker', + subject: 'Done', + type: 'worker_done', + payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded' }) + } + }) + await vi.waitFor(() => + expect(harness.workerDb().listPendingFederationRelay(dispatchId, 'to_home')).toHaveLength(1) + ) + // Queued, not yet accepted by the home: no deadline. + expect(harness.workerDb().getWorkerTerminalResourceByOwner(dispatchId)?.auto_release_at).toBe( + null + ) + await harness.syncHome(dispatchId) + await expect(sent).resolves.toMatchObject({ ok: true }) + return dispatchId + } + + registerHomeAutoReleaseScenarios({ harness, settleRemotely }) +} diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-home-auto-release-scenarios.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-home-auto-release-scenarios.test-support.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-home-auto-release-scenarios.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/federation/testing/federation-home-auto-release-scenarios.test-support.ts index a856fe2788f..7a027195d92 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-home-auto-release-scenarios.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-home-auto-release-scenarios.test-support.ts @@ -1,7 +1,7 @@ import { expect, it, vi } from 'vitest' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../../shared/orchestration/orchestration-runtime-capabilities' import type { AutoReleaseScenarioHarness } from './federation-auto-release-scenarios.test-support' import { GRACE_MS } from './federation-auto-release-grace.test-support' @@ -25,7 +25,7 @@ export function registerHomeAutoReleaseScenarios(args: { it('leaves a worker the user kept open on the host when the home deadline fires', async () => { const dispatchId = await settleOnOlderHost() const paneKey = harness.workerDb().getWorkerTerminalResourceByOwner(dispatchId)!.pane_key! - expect(harness.workerDb().keepWorkerTerminalOpen(paneKey)).toBe(1) + harness.workerDb().keepWorkerTerminalOpen(paneKey) await releaseDueAtHome() @@ -51,14 +51,13 @@ export function registerHomeAutoReleaseScenarios(args: { it('refuses a home worker-stop of a worker kept open on its host before either side stops it', async () => { const dispatchId = await harness.startRemoteWorker() const paneKey = harness.workerDb().getWorkerTerminalResourceByOwner(dispatchId)?.pane_key - expect(harness.workerDb().keepWorkerTerminalOpen(paneKey ?? '')).toBe(1) + harness.workerDb().keepWorkerTerminalOpen(paneKey ?? '') await expect(stopFromHome(dispatchId)).resolves.toMatchObject({ ok: false, error: { code: 'terminal_kept_open' } }) expect(harness.homeDb().getWorkerDispatch(dispatchId)?.state).toBe('ready') - expect(harness.remoteCalls()).not.toContain('orchestration.federationStop') // An older home skips that check; the host still refuses before it stops anything. expect(() => harness.workerDb().beginRemoteAttachmentStop(dispatchId)).toThrow('Keep open') expect(harness.workerDb().getRemoteDispatchAttachment(dispatchId)?.state).toBe('ready') diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-peer-capabilities.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-peer-capabilities.test-support.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-peer-capabilities.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/federation/testing/federation-peer-capabilities.test-support.ts index 2180ec199f8..7f81f68e337 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-peer-capabilities.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-peer-capabilities.test-support.ts @@ -4,8 +4,8 @@ import { ORCHESTRATION_FEDERATION_STRUCTURED_READ_RUNTIME_CAPABILITY, ORCHESTRATION_REMOTE_OWNED_WORKERS_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_AUTO_RELEASE_RUNTIME_CAPABILITY -} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +} from '../../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' /** Capabilities a simulated older execution host leaves out of its status.get. */ function withheldPeerCapabilities(host: { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-request.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-request.test-support.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-request.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/federation/testing/federation-request.test-support.ts index ecbb36c9e08..2b34ce6f51a 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-request.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-request.test-support.ts @@ -1,5 +1,5 @@ -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { RpcRequest } from '../../../core' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RpcRequest } from '../../../../core' export function createFederationWorkerStartRequest( taskId: string, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-runtime.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-runtime.test-support.ts similarity index 94% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-runtime.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/federation/testing/federation-runtime.test-support.ts index 7be5ade9247..f3d5afd12d6 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-runtime.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-runtime.test-support.ts @@ -1,6 +1,6 @@ import { vi } from 'vitest' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { RuntimeTerminalShow } from '../../../../../../shared/runtime-terminal-contracts' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { RuntimeTerminalShow } from '../../../../../../../shared/runtime-terminal-contracts' export function configureFederationWorkerRuntime( runtime: OrcaRuntimeService, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-sync-barrier.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-sync-barrier.test-support.ts new file mode 100644 index 00000000000..3bbddbf3eeb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/testing/federation-sync-barrier.test-support.ts @@ -0,0 +1,15 @@ +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' + +// Await the next relay round: the current coalesced tick may have read peers before the latest mutation. +export async function syncFederationBarrier( + runtime: OrcaRuntimeService, + db: OrchestrationDb +): Promise { + const dispatches = db.listActiveFederatedDispatches() + await Promise.allSettled( + dispatches.map((dispatch) => + runtime.syncOrchestrationFederatedDispatchAfterCurrent(dispatch.dispatch_id) + ) + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/gates/gate-run-authorization.test.ts b/src/main/runtime/rpc/methods/orchestration/gates/gate-run-authorization.test.ts index bd9f71868fc..40aac838244 100644 --- a/src/main/runtime/rpc/methods/orchestration/gates/gate-run-authorization.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/gates/gate-run-authorization.test.ts @@ -10,10 +10,7 @@ import { invoke, request, type LegacyCompatibilityDispatcherHarness -} from '../../../orchestration-legacy-compatibility-dispatcher-test-fixture' - -const STRANGER_HANDLE = 'term_stranger_coord' -const STRANGER_PANE = 'tab_stranger:77777777-7777-4777-8777-777777777777' +} from '../../../orchestration/compatibility/testing/orchestration-legacy-compatibility-dispatcher-test-fixture' afterEach(() => { cleanupLegacyCompatibilityDispatcherHarnesses() @@ -61,30 +58,6 @@ describe('orchestration gate Run authorization', () => { } ) - it('G2 refuses an unattested caller creating a gate on another Run task', async () => { - const harness = createHarness() - const runA = bindCurrentCoordinatorRun(harness) - const before = adoptedTaskState(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.gateCreate', - { task: harness.taskId, question: 'Proceed?', from: CURRENT_COORDINATOR_HANDLE }, - UNATTESTED_CURRENT_COORDINATOR, - 'g2-cross-run-gate-create' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'task_not_found', - message: `Task ${harness.taskId} was not found in Run ${runA}.` - } - }) - expect(adoptedTaskState(harness)).toEqual(before) - }) - it('G2 refuses the same caller when it names no sender terminal at all', async () => { const harness = createHarness() bindCurrentCoordinatorRun(harness) @@ -130,95 +103,6 @@ describe('orchestration gate Run authorization', () => { expect(adoptedTaskState(harness)).toEqual(before) }) - it('G4 refuses an attested bound caller creating a gate in a stranger Run', async () => { - const harness = createHarness() - const runA = bindCurrentCoordinatorRun(harness) - const strangerRun = harness.db.createRun({ - objective: 'stranger work', - coordinatorHandle: STRANGER_HANDLE, - coordinatorPaneKey: STRANGER_PANE - }) - const strangerTask = harness.db.createTask({ - spec: 'stranger assignment', - runId: strangerRun.id - }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.gateCreate', - { task: strangerTask.id, question: 'Proceed?', from: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('coordinator'), - 'g4-stranger-gate-create' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'task_not_found', - message: `Task ${strangerTask.id} was not found in Run ${runA}.` - } - }) - expect(harness.db.getTask(strangerTask.id)?.status).toBe('ready') - expect(harness.db.listGates({ taskId: strangerTask.id })).toHaveLength(0) - }) - - it('G4 refuses the stranger Run even when it is named explicitly', async () => { - const harness = createHarness() - const runA = bindCurrentCoordinatorRun(harness) - const strangerRun = harness.db.createRun({ - objective: 'stranger work', - coordinatorHandle: STRANGER_HANDLE, - coordinatorPaneKey: STRANGER_PANE - }) - const strangerTask = harness.db.createTask({ - spec: 'stranger assignment', - runId: strangerRun.id - }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.gateCreate', - { - task: strangerTask.id, - question: 'Proceed?', - from: CURRENT_COORDINATOR_HANDLE, - run: strangerRun.id - }, - currentEvidence('coordinator'), - 'g4-explicit-stranger-gate-create' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'consumer_fenced', - message: `This caller is bound to Run ${runA}, not Run ${strangerRun.id}. Nothing changed.` - } - }) - expect(harness.db.getTask(strangerTask.id)?.status).toBe('ready') - }) - - it('G5 refuses an unattested caller resolving another Run gate', async () => { - const harness = createHarness() - bindCurrentCoordinatorRun(harness) - const gate = harness.db.createGate({ taskId: harness.taskId, question: 'Proceed?' }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.gateResolve', - { id: gate.id, resolution: 'yes', from: CURRENT_COORDINATOR_HANDLE }, - UNATTESTED_CURRENT_COORDINATOR, - 'g5-cross-run-gate-resolve' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { message: `Gate not found: ${gate.id}` } }) - expect(harness.db.getGate(gate.id)?.status).toBe('pending') - expect(harness.db.getTask(harness.taskId)?.status).toBe('blocked') - }) - it('keeps gate-list from leaking gates outside the caller Run', async () => { const harness = createHarness() const runA = bindCurrentCoordinatorRun(harness) diff --git a/src/main/runtime/rpc/methods/orchestration/gates/gates.ts b/src/main/runtime/rpc/methods/orchestration/gates/gates.ts index 7f1556a2edc..5ecf5392d66 100644 --- a/src/main/runtime/rpc/methods/orchestration/gates/gates.ts +++ b/src/main/runtime/rpc/methods/orchestration/gates/gates.ts @@ -8,7 +8,7 @@ import { GateResolveParams, RunParams, RunStopParams -} from '../../../../../../shared/rpc-contract/orchestration-gates-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-gates-params' // Keep one coordinator reference for runStop; the DB allows only one active run. let activeCoordinator: Coordinator | null = null diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts index ee868bd05cb..41acf5b5660 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts @@ -3,7 +3,7 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-erro import { clampOrchestrationAskTimeoutMs } from '../../../../../../shared/orchestration/mailbox/orchestration-ask-timeout' import { isGroupAddress } from '../../../../orchestration/addressing/groups/group-addressing' import { dispatchReportMailbox } from '../../../../orchestration/workers/reports/dispatch-report-mailbox' -import { AskParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import { AskParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { rejectFederatedExplicitTarget } from '../routing' import { askRemoteRunHome } from '../../../../orchestration/legacy-remote/ask-remote' import { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-direct.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-direct.ts index 6b0f2e3d244..be0a2f9d8f0 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-direct.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-direct.ts @@ -7,7 +7,7 @@ import { exposeMessages } from './mailbox-message-receipt' import { staleDelivery } from '../../../../orchestration/db/messages/role-mailbox-delivery' import { reconcileLifecycleMessage } from '../../../../orchestration/workers/lifecycle/lifecycle-reconciliation' import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../../shared/orchestration/orchestration-rpc-contract' -import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import type { z } from 'zod' type CheckParamsInput = z.infer @@ -31,7 +31,7 @@ export async function checkDirectMailbox(args: { const readAndReturn = () => { const messages = showAll ? db.getAllMessagesForHandle(handle, undefined, typeFilter) - : db.getUnreadMessages(handle, typeFilter) + : db.getUnreadMessages(handle, typeFilter, { excludeRunOwnedDirect: true }) if ( consumeUnread && messages.some((message) => message.run_id === ORCHESTRATION_LEGACY_RUN_ID) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts index 11af8dd3c25..6218cd16e8a 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts @@ -1,6 +1,6 @@ import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import { CheckParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { parseMessageTypes } from '../routing' import { checkRunMailbox } from './check-run' import { checkWorkerMailbox } from './check-worker' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts index 31ec54fb285..e73d619cb45 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts @@ -8,7 +8,7 @@ import { currentDispatchAssigneeRun } from './recipient-routing' import { callerHoldsDispatchPane, dispatchFenced } from './dispatch-mailbox-fence' import { orchestrationCallerIdentity } from '../runs/run-scope' import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import type { z } from 'zod' export async function checkRunPendingMail(args: { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts index 5a34463d588..53f1980fc92 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts @@ -9,7 +9,7 @@ import { deliveryReceipt, exposeMessages, handsOverBatch } from './mailbox-messa import { interruptedAcknowledgedCheck } from '../routing' import { routeAllMailboxPages } from './mailbox-page-routing' import { resolveRunScope } from '../runs/run-scope' -import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import type { z } from 'zod' import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import { checkRunPendingMail } from './check-run-pending-mail' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-worker.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-worker.ts index 8ae22f5fa61..5f355435f46 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-worker.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-worker.ts @@ -9,7 +9,7 @@ import { routeAllMailboxPages } from './mailbox-page-routing' import { asDispatchFence, callerHoldsDispatchPane, dispatchFenced } from './dispatch-mailbox-fence' import { interruptedAcknowledgedCheck } from '../routing' import { currentDispatchAssigneeRun } from './recipient-routing' -import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import type { z } from 'zod' type CheckParamsInput = z.infer diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/finished-worker-mail.ts b/src/main/runtime/rpc/methods/orchestration/messaging/finished-worker-mail.ts index 791c8a2905d..c0657d80fa7 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/finished-worker-mail.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/finished-worker-mail.ts @@ -5,7 +5,7 @@ import { dispatchReportMailbox } from '../../../../orchestration/workers/reports import { reportCorrectsUnobservedPrompt } from '../../../../orchestration/workers/reports/worker-report-admission' import { isDispatchAssignee } from '../../../../orchestration/db/dispatch-context/dispatch-lookup' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration-params' +import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import type { MessageRouting } from '../routing' /** A terminal also proves its process, so a new process in the same pane is not taken for the old worker; diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts index fff196ea676..1a5e4ecd953 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts @@ -9,7 +9,7 @@ import { InboxParams, TaskCreateParams, TaskListParams -} from '../../../../../../shared/rpc-contract/orchestration-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { TaskUpdateParams } from './task-update-params' export const ORCHESTRATION_MESSAGE_METHODS = [ diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/mutation-replay-nudge.ts b/src/main/runtime/rpc/methods/orchestration/messaging/mutation-replay-nudge.ts index 2ccf77ff8a1..f3a63e89b0e 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/mutation-replay-nudge.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/mutation-replay-nudge.ts @@ -2,7 +2,7 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' import { attachMutationReplayNudge, type MutationReplayNudge -} from '../../../orchestration-mutation-receipt' +} from '../../../orchestration/mutations/orchestration-mutation-receipt' /** Persists the receipt (with its replay nudge) before waking recipients, for mutations whose effect is already durable. */ export function recordReceiptBeforeNudge( diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts b/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts index 40a1666dd04..225b23d6c92 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts @@ -15,6 +15,7 @@ import { readAgentSessionRecordStore } from '../../../../orchestration/addressin import { readSessionRecipient, refuseUndeliverableSessionRecipient, + type TerminalAgentRecipient, type SessionRecipientRefusal } from './session-recipient' import { reportFollowUpAction } from '../../../../orchestration/workers/reports/report-follow-up-action' @@ -164,6 +165,7 @@ export function resolveReplyRecipient(params: { db: OrchestrationDb originalFrom: string originalRunId: string | undefined + terminalRecipient: TerminalAgentRecipient }): { to: string; runId: string | undefined; warning?: SendRecipientWarning } { const { runtime, db, originalFrom, originalRunId } = params const unchanged = { to: originalFrom, runId: originalRunId } @@ -184,7 +186,8 @@ export function resolveReplyRecipient(params: { runtime, db, handle: originalFrom, - senderRunId: originalRunId + senderRunId: originalRunId, + terminalRecipient: params.terminalRecipient }) if (!recipient.ok) { throw new OrchestrationError(recipient.code, `${recipient.message} No reply was sent.`, { @@ -236,10 +239,14 @@ export function resolveBareOrchestrationRecipient(params: { senderRunId?: string explicitRunId?: string legacyAdoptedMailboxOwner?: LegacyAdoptedMailboxOwner | null + /** `resolveTerminalAgentRecipient(handle)`, awaited first; omit only where the handle cannot + * name a terminal agent. */ + terminalRecipient?: TerminalAgentRecipient }): BareRecipientResolution { const { runtime, db } = params const sessionStore = readAgentSessionRecordStore() - const session = readSessionRecipient(params.handle, sessionStore) + const terminal = params.terminalRecipient ?? null + const session = readSessionRecipient(params.handle, sessionStore, terminal) if (session && 'code' in session) { return refused(params.handle, session) } @@ -263,7 +270,7 @@ export function resolveBareOrchestrationRecipient(params: { ownerRunIds: () => db.getRunMailboxOwnerIdsForHandle(handle, params.legacyAdoptedMailboxOwner), fallback: () => { if (session) { - const refusal = refuseUndeliverableSessionRecipient(session, sessionStore, db) + const refusal = refuseUndeliverableSessionRecipient(session, sessionStore, db, terminal) return refusal ? refused(params.handle, refusal) : { ok: true, to: handle, runId: params.senderRunId } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts index 13b96bc1d5f..ad1a2156df2 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts @@ -6,7 +6,7 @@ import type { } from '../../../../orchestration/db/orchestration-records' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../../shared/orchestration/orchestration-rpc-contract' -import type { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import type { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { resolveRunScope } from '../runs/run-scope' import type { OrchestrationAccessRuleInput } from '../access/orchestration-method-access' import { helperQuestionAnswerer } from './helper-question-answerer' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts index d9d2e239d91..f8db1c506fb 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -1,4 +1,5 @@ import { acceptedAnswerSender } from '../../../../orchestration/mailbox/senders/accepted-answer-sender' +import { resolveTerminalAgentRecipient } from './session-recipient' import { answerSenderRelayReport } from '../../../../orchestration/mailbox/senders/answer-sender-relay-report' import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { deliverQuestionAnswer } from '../../../../orchestration/mailbox/questions/question-answer-delivery' @@ -7,7 +8,7 @@ import { orchestrationCallerIdentity } from '../runs/run-scope' import { readMutationReplayNudge, stripMutationReplayNudge -} from '../../../orchestration-mutation-receipt' +} from '../../../orchestration/mutations/orchestration-mutation-receipt' import { exposeMessage } from './mailbox-message-receipt' import { recordReceiptBeforeNudge, replayMutationNudge } from './mutation-replay-nudge' import { resolveReplyRecipient } from './recipient-routing' @@ -15,7 +16,7 @@ import { replyAccess } from './reply-access' import { replyToRemoteRunHome } from '../../../../orchestration/legacy-remote/reply-remote' import { replyOverPeerMail } from './peer-mail-reply' import { withAnswerNext } from '../receipt-next' -import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { completionReportDispatchId, reportFollowUpAction @@ -140,6 +141,8 @@ export const ORCHESTRATION_REPLY_METHOD = defineOrchestrationMethod({ if (db.getRun(original.run_id)?.home_database === 'remote') { return await replyToRemoteRunHome({ runtime, db, original, params, signal }) } + // Await first, so the refusals and routing below read state as it is after the wait. + const terminalRecipient = await resolveTerminalAgentRecipient(original.from_handle) // A finished task's worker never reads a reply to its report; refuse before marking or storing anything. const reportDispatchId = completionReportDispatchId(db, original) const followUp = reportDispatchId ? reportFollowUpAction(db, reportDispatchId) : undefined @@ -154,7 +157,8 @@ export const ORCHESTRATION_REPLY_METHOD = defineOrchestrationMethod({ runtime, db, originalFrom: original.from_handle, - originalRunId: original.run_id + originalRunId: original.run_id, + terminalRecipient }) db.markAsRead([original.id]) const reply = db.insertMessage({ diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-group.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-group.ts index c49308b13b0..a3f1f7fb9e8 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-group.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-group.ts @@ -31,6 +31,9 @@ type GroupAgentSnapshot = OrchestrationAddressableAgent & { tabId?: string; leaf type GroupCandidate = OrchestrationAddressableAgent & { mailbox?: { to: string; runId: string } } +// Status reads for a candidate set that keeps changing during them, at most this many. +const MAX_STATUS_READS = 3 + function listRunGroupCandidates(args: { db: OrchestrationDb runtime: OrcaRuntimeService @@ -159,35 +162,53 @@ export async function sendGroupMessage(args: { }) agents = [...terminals, ...listAddressableStructuredWorkers(db)] } - // Revalidate after discovery before selecting recipients or writing mail. - revalidateLegacyCoordinator?.() - if (!worktreeGroup) { - audienceRunId = resolveAudienceRunId() + // Authority, audience and candidates are read after the last wait, before any effect. + function selectCandidates(): { + candidates: GroupCandidate[] + groupWarnings: SendRecipientWarning[] + } { + revalidateLegacyCoordinator?.() + if (!worktreeGroup) { + audienceRunId = resolveAudienceRunId() + } + const groupWarnings: SendRecipientWarning[] = [] + const candidates: GroupCandidate[] = + worktreeGroup || !audienceRunId + ? agents + : listRunGroupCandidates({ + db, + runtime, + senderRunId: audienceRunId, + groupAddress, + agents, + warnings: groupWarnings + }) + return { candidates, groupWarnings } } - const groupWarnings: SendRecipientWarning[] = [] - const candidates: GroupCandidate[] = - worktreeGroup || !audienceRunId - ? agents - : listRunGroupCandidates({ - db, - runtime, - senderRunId: audienceRunId, - groupAddress, - agents, - warnings: groupWarnings - }) - // Read up front: a structured worker's status comes from its journal, which may need opening. - const statuses = - groupAddress.toLowerCase() === '@idle' - ? new Map( - await Promise.all( - candidates.map( - async (candidate) => - [candidate.handle, await runtime.getAgentStatusForHandle(candidate.handle)] as const - ) - ) + let { candidates, groupWarnings } = selectCandidates() + // A structured worker's status comes from its journal, which may need opening; candidates found + // during that wait need their own, so every status is read again with them. + let statuses = new Map() + for (let attempt = 0; groupAddress.toLowerCase() === '@idle'; attempt++) { + if (attempt === MAX_STATUS_READS) { + throw new OrchestrationError( + 'terminal_not_found', + `The recipients of ${groupAddress} kept changing while their status was read. No message was sent.` + ) + } + statuses = new Map( + await Promise.all( + candidates.map( + async (candidate) => + [candidate.handle, await runtime.getAgentStatusForHandle(candidate.handle)] as const ) - : new Map() + ) + ) + ;({ candidates, groupWarnings } = selectCandidates()) + if (candidates.every((candidate) => statuses.has(candidate.handle))) { + break + } + } const handles = resolveGroupAddress( groupAddress, from, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index 19637336cd5..b24f5cfe064 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -7,7 +7,7 @@ import { } from '../../../../orchestration/workers/reports/dispatch-report-mailbox' import { orchestrationSkillRecoveryData } from '../../../../../../shared/orchestration/orchestration-rpc-contract' import { SendParams } from './send-params' -import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration-params' +import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { isWorkerReportOutcome, parseRemoteWorkerPayload } from './message-payload' import { resolveMessageRun } from '../routing' import { @@ -19,7 +19,7 @@ import { import { replayAcceptedSend } from './send-replay' import { sendRemoteMessage } from '../../../../orchestration/legacy-remote/send-remote' import { withPeerMailSend } from './peer-mail-send' -import { mayNameSession } from './session-recipient' +import { prepareSessionRecipient } from './session-recipient' import { sendPointToPointMessage } from './send-point-to-point' import { sendGroupMessage } from './send-group' import { sendFederatedControlMail } from '../../../../orchestration/legacy-remote-home/send-control-mail' @@ -161,16 +161,14 @@ export const ORCHESTRATION_SEND_METHODS = [ const sendWarnings: SendRecipientWarning[] = [] let messageRunId = routing.run?.id if (!isGroupAddress(to) && !to.startsWith('run:') && !to.startsWith('dispatch:')) { - if (mayNameSession(to)) { - // Recipient routing reads the session record store, which the host opens lazily. - await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) - } + const terminal = await prepareSessionRecipient(runtime, to, revalidateLegacyCoordinator) const recipient = resolveBareOrchestrationRecipient({ runtime, db, handle: to, senderRunId: routing.run?.id, - explicitRunId: params.run + explicitRunId: params.run, + terminalRecipient: terminal }) if (!recipient.ok) { throw new OrchestrationError(recipient.code, recipient.message) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts index cce983c33e3..4b1a2c6e071 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts @@ -9,7 +9,7 @@ import { MESSAGE_TYPES } from '../../../../orchestration/db/orchestration-record import { getLifecycleGroupRecipientError, isDispatchMutationMessageType -} from '../../../../../../shared/rpc-contract/orchestration-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' const SEND_MESSAGE_TYPE_ERROR = [ `Invalid --type. Expected one of: ${MESSAGE_TYPES.join(', ')}.`, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts index 85752b5aa3d..74577e8f286 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts @@ -6,7 +6,7 @@ import type { OrchestrationDb } from '../../../../orchestration/db/orchestration import type { OrcaRuntimeService } from '../../../../orca-runtime' import { reconcileLifecycleMessage } from '../../../../orchestration/workers/lifecycle/lifecycle-reconciliation' import { bindCoordinatorMutationPayload } from '../../../../orchestration/workers/reports/dispatch-message-binding' -import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration-params' +import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { parseMessageTaskId } from './message-payload' import { isDispatchAssignee } from '../../../../orchestration/db/dispatch-context/dispatch-lookup' import type { SendParams } from './send-params' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts index 8d471f1ef85..1569c0c9861 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts @@ -5,7 +5,7 @@ import { readMutationReplayNudge, readWorkerDoneReplayNudge, stripMutationReplayNudge -} from '../../../orchestration-mutation-receipt' +} from '../../../orchestration/mutations/orchestration-mutation-receipt' import { replayMutationNudge } from './mutation-replay-nudge' import type { SendParams } from './send-params' import { followThroughWorkerReport, settledDispatchId } from './settled-worker-follow-through' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/session-recipient.ts b/src/main/runtime/rpc/methods/orchestration/messaging/session-recipient.ts index 31e78fad741..9324d1be824 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/session-recipient.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/session-recipient.ts @@ -15,9 +15,13 @@ import { lookupOrcaAgentSession, structuredSessionMailReach } from '../../../../orchestration/mailbox/routing/structured-session-mail-address' -import type { AgentSessionRecordReader } from '../../../../orchestration/addressing/session-lineage/structured-session-lineage' +import { + readAgentSessionRecordStore, + type AgentSessionRecordReader +} from '../../../../orchestration/addressing/session-lineage/structured-session-lineage' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import { canonicalOrcaSessionId } from '../../../../orchestration/addressing/session-lineage/canonical-orca-session-id' +import { agentHookServer } from '../../../../../agent-hooks/server/agent-hook-server' /** `address` is the named session's own spelling; the mailbox mail lands in is its identity address. */ export type SessionRecipient = { sessionId: OrcaSessionId; address: OrcaSessionAddress } @@ -32,10 +36,54 @@ export function mayNameSession(recipient: string): boolean { return recipient.startsWith(ORCA_SESSION_ADDRESS_PREFIX) || isOrcaSessionId(recipient) } +/** A recipient that names one of this host's terminal agents, and where it runs now. */ +export type TerminalAgentRecipient = { + sessionId: string + places: { paneKey: string; worktreeId?: string }[] +} | null + +/** Resolved before routing: a dormant terminal id is known only to the identity store, which + * answers asynchronously. A known chat (or its provider id) is decided by the chat store alone, + * so chat mail never waits on the identity worker. Callers reread the facts they act on after + * awaiting this. */ +export async function resolveTerminalAgentRecipient( + recipient: string +): Promise { + const sessionId = recipient.startsWith(ORCA_SESSION_ADDRESS_PREFIX) + ? parseOrcaSessionAddress(recipient) + : isOrcaSessionId(recipient) + ? recipient + : null + const store = sessionId ? readAgentSessionRecordStore() : null + if (!sessionId || (store && lookupOrcaAgentSession(store, sessionId).kind !== 'unknown')) { + return null + } + const places = await agentHookServer.terminalAgentPlaces(sessionId) + return places ? { sessionId, places } : null +} + +/** Before routing a session-shaped recipient: opens the chat store, resolves a terminal agent, + * then checks the caller's authority again, since the waits may have outlived it. */ +export async function prepareSessionRecipient( + runtime: { ensureStructuredAgentSessionHost(): Promise }, + recipient: string, + revalidateCaller?: () => unknown +): Promise { + if (!mayNameSession(recipient)) { + return null + } + // Recipient routing reads the session record store, which the host opens lazily. + await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + const terminal = await resolveTerminalAgentRecipient(recipient) + revalidateCaller?.() + return terminal +} + /** Recognize bare ids as sessions only when a local record exists; preserve terminal-handle interpretation otherwise. */ export function readSessionRecipient( recipient: string, - store: AgentSessionRecordReader | null + store: AgentSessionRecordReader | null, + terminalRecipient: TerminalAgentRecipient ): SessionRecipient | SessionRecipientRefusal | null { if (recipient.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { const sessionId = parseOrcaSessionAddress(recipient) @@ -51,6 +99,12 @@ export function readSessionRecipient( if (found?.kind === 'provider-id') { return providerIdRefusal(recipient, found.orcaSessionId, store) } + if (sessionId && found?.kind !== 'found') { + const terminal = terminalAgentRefusal(sessionId, terminalRecipient) + if (terminal) { + return terminal + } + } return sessionId && found?.kind === 'found' ? { sessionId, address: formatOrcaSessionAddress(sessionId) } : null @@ -61,9 +115,15 @@ export function refuseUndeliverableSessionRecipient( recipient: SessionRecipient, store: AgentSessionRecordReader | null, db: OrchestrationDb, + terminalRecipient: TerminalAgentRecipient, noEffect = 'No message was sent.' ): SessionRecipientRefusal | null { const { sessionId } = recipient + // Before the host check: terminal-only users have no agent-session host to blame. + const terminal = terminalAgentRefusal(sessionId, terminalRecipient, noEffect) + if (terminal) { + return terminal + } if (!store) { return { code: CODES.unknown, @@ -121,3 +181,24 @@ function providerIdRefusal( message: `${id} is the provider's own session id, which changes on /clear. This session's Orca session ID is ${address}; address it by that instead. ${noEffect}` } } + +/** Terminal agents have Orca ids, but mail reaches them only through their terminal for now. */ +function terminalAgentRefusal( + sessionId: OrcaSessionId, + terminalRecipient: TerminalAgentRecipient, + noEffect = 'No message was sent.' +): SessionRecipientRefusal | null { + if (terminalRecipient?.sessionId !== sessionId) { + return null + } + const places = terminalRecipient.places.map((place) => + place.worktreeId + ? `pane ${place.paneKey} in workspace ${place.worktreeId}` + : `pane ${place.paneKey}` + ) + const where = places.length > 0 ? `, running in ${places.join('; ')}` : '' + return { + code: CODES.terminalAgent, + message: `Agent ${sessionId} is a terminal agent${where}. Messaging terminal agents by ID isn't supported yet; address its terminal instead. ${noEffect}` + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts index 3aec8ace463..696c6e9b5e2 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts @@ -25,8 +25,8 @@ import { startWorkerFollowUp, type WorkerFollowUpOutcome } from './worker-follow-up' -import { captureReportedWorkerResumeSession } from '../worker/worker-resume-session-capture' -import { reportedWorkerOutcome } from '../worker/worker-start-receipt' +import { captureReportedWorkerResumeSession } from '../worker/follow-up/worker-resume-session-capture' +import { reportedWorkerOutcome } from '../worker/start/worker-start-receipt' /** After a report settles (or replays): save the worker's conversation, then continue mail it never read. */ export function followThroughWorkerReport( diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/terminal-agent-recipient-authority.test.ts b/src/main/runtime/rpc/methods/orchestration/messaging/terminal-agent-recipient-authority.test.ts new file mode 100644 index 00000000000..292feb556a9 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/terminal-agent-recipient-authority.test.ts @@ -0,0 +1,197 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { + formatOrcaSessionAddress, + isOrcaSessionId +} from '../../../../../../shared/orca-session-address' + +const identity = vi.hoisted(() => ({ + terminalAgentPlaces: vi.fn<(id: string) => Promise<{ paneKey: string }[] | null>>(), + chats: new Set() +})) +vi.mock('../../../../../agent-hooks/server/agent-hook-server', () => ({ + agentHookServer: { terminalAgentPlaces: identity.terminalAgentPlaces } +})) +vi.mock('../../../../orchestration/addressing/session-lineage/structured-session-lineage', () => ({ + readAgentSessionRecordStore: () => ({}) +})) +vi.mock('../../../../orchestration/mailbox/routing/structured-session-mail-address', () => ({ + lookupOrcaAgentSession: (_store: unknown, id: string) => + identity.chats.has(id) ? { kind: 'found', record: {} } : { kind: 'unknown' }, + structuredSessionMailReach: () => ({ kind: 'local' }) +})) +// Group selection is what this file checks; the sender's own mailbox routing is out of scope. +vi.mock('./recipient-routing', () => ({ + resolveBareOrchestrationRecipient: ({ handle }: { handle: string }) => ({ + ok: true, + to: handle, + runId: 'run_1' + }) +})) +vi.mock('../routing', () => ({ legacyWorkerDeliveryContract: () => undefined })) +vi.mock('../../../../orchestration/addressing/groups/structured-worker-group-addressing', () => ({ + listAddressableStructuredWorkers: () => [] +})) + +import { + readSessionRecipient, + refuseUndeliverableSessionRecipient, + resolveTerminalAgentRecipient +} from './session-recipient' +import { sendGroupMessage } from './send-group' + +const CHAT = 'codex_0123456789abcdef' +const TERMINAL = 'claude_0123456789abcdef' + +beforeEach(() => { + identity.chats.clear() + identity.terminalAgentPlaces.mockReset() +}) + +it('decides a known chat from the chat store alone and refuses a cold terminal id', async () => { + identity.chats.add(CHAT) + // A broken identity worker never answers; a chat recipient must not wait on it. + identity.terminalAgentPlaces.mockReturnValue(new Promise(() => {})) + expect(await resolveTerminalAgentRecipient(`orca_session_id:${CHAT}`)).toBeNull() + expect(identity.terminalAgentPlaces).not.toHaveBeenCalled() + + // A conversation no row carries now is still a terminal agent once the store confirms it. + identity.terminalAgentPlaces.mockResolvedValue([]) + const terminal = await resolveTerminalAgentRecipient(TERMINAL) + expect(terminal).toEqual({ sessionId: TERMINAL, places: [] }) + expect(readSessionRecipient(TERMINAL, null, terminal)).toMatchObject({ + code: 'session_caller_terminal_agent' + }) + if (!isOrcaSessionId(TERMINAL)) { + throw new Error('expected an Orca session id') + } + const recipient = { sessionId: TERMINAL, address: formatOrcaSessionAddress(TERMINAL) } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a terminal refusal returns before any database read. + const db = {} as OrchestrationDb + expect(refuseUndeliverableSessionRecipient(recipient, null, db, terminal)?.message).toBe( + `Agent ${TERMINAL} is a terminal agent. Messaging terminal agents by ID isn't supported yet; address its terminal instead. No message was sent.` + ) +}) + +type GroupWorld = { + /** Live Dispatches of the sender's Run, by worker terminal handle. */ + dispatches: Map + terminals: { handle: string; worktreeId: string; agentIdentity?: string }[] + statuses: Map + /** Runs inside each status read, as other work may while a journal opens. */ + duringStatusRead?: () => void + revalidate?: () => string +} + +function groupSend(groupAddress: string, world: GroupWorld) { + const written: string[][] = [] + const db = { + getCoordinatedRun: () => undefined, + getCurrentRunForCoordinator: () => undefined, + getActiveDispatchForIdentity: () => undefined, + listWorkerTerminalResources: () => + [...world.dispatches].map(([handle, dispatchId]) => ({ + dispatchStatus: 'dispatched', + dispatchId, + runId: 'run_1', + paneKey: `tab:${handle}`, + agentTerminalHandle: handle, + worktreeId: 'w' + })), + listFederatedDispatchesByIds: () => [], + getCurrentRunForPane: () => undefined, + getLegacyAdoptedRunMailboxOwner: () => null, + insertMessages: (rows: { to: string }[]) => { + written.push(rows.map((row) => row.to)) + return rows + } + } + const runtime = { + listTerminals: async () => ({ terminals: world.terminals }), + getAgentStatusForHandle: async (handle: string) => { + world.duringStatusRead?.() + return world.statuses.get(handle) ?? null + }, + getTerminalHandleForPaneKey: (paneKey: string) => paneKey.slice('tab:'.length), + getLiveTerminalPaneKey: (handle: string) => `tab:${handle}`, + getLegacyAdoptedRunMailboxOwner: () => null, + notifyMessageArrived: () => {} + } + const args = { + params: { subject: 'test', body: 'body' }, + runtime, + db, + from: 'term_coord', + groupAddress, + sender: { terminalHandle: 'term_coord', paneKey: 'tab:coord', orcaSessionId: null }, + senderPaneKey: 'tab:coord', + senderRunId: 'run_1', + explicitRunId: undefined, + legacyCoordinatorRunId: 'run_1', + revalidateLegacyCoordinator: world.revalidate ?? (() => 'run_1'), + recordMutationReceipt: undefined, + withSendWarnings: (receipt: T) => receipt + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a group send reads only these runtime and database members. + const sent = sendGroupMessage(args as unknown as Parameters[0]) + return { sent, written } +} + +function stableWorld(): GroupWorld { + return { + dispatches: new Map([['term_a', 'dispatch_a']]), + terminals: [{ handle: 'term_a', worktreeId: 'w1', agentIdentity: 'claude' }], + statuses: new Map([['term_a', 'idle']]) + } +} + +it.each([ + ['@all', ['dispatch:dispatch_a']], + ['@idle', ['dispatch:dispatch_a']], + ['@worktree:w1', ['term_a']], + ['@claude', ['dispatch:dispatch_a']] +])('routes %s to its host-issued candidates with no identity lookup', async (group, to) => { + // A hung identity worker: group candidates are handles, worker ids and mailboxes, never ids + // to classify, so the send cannot wait on it. + identity.terminalAgentPlaces.mockReturnValue(new Promise(() => {})) + const { sent, written } = groupSend(group, stableWorld()) + await sent + expect(written).toEqual([to]) + expect(identity.terminalAgentPlaces).not.toHaveBeenCalled() +}) + +it('selects @idle recipients from the facts current after the status read', async () => { + // While statuses were read, A went busy and B was dispatched: B's own status is read too. + const world = stableWorld() + world.duringStatusRead = () => { + world.statuses.set('term_a', 'busy') + world.dispatches.set('term_b', 'dispatch_b') + world.statuses.set('term_b', 'idle') + } + const changed = groupSend('@idle', world) + await changed.sent + expect(changed.written).toEqual([['dispatch:dispatch_b']]) + + // The worker moved to another Dispatch during the read: mail follows its current mailbox. + const moving = stableWorld() + moving.duringStatusRead = () => moving.dispatches.set('term_a', 'dispatch_a2') + const moved = groupSend('@idle', moving) + await moved.sent + expect(moved.written).toEqual([['dispatch:dispatch_a2']]) + + // Authority revoked during the read: nothing is written. + let valid = true + const revoking = stableWorld() + revoking.duringStatusRead = () => { + valid = false + } + revoking.revalidate = () => { + if (!valid) { + throw new Error('revoked') + } + return 'run_1' + } + const revoked = groupSend('@idle', revoking) + await expect(revoked.sent).rejects.toThrow('revoked') + expect(revoked.written).toEqual([]) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts b/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts index becb596de26..3179eea73b3 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts @@ -1,7 +1,7 @@ import { planSemanticWorkerFollowUp, workerFollowUpArguments -} from '../worker/worker-follow-up-admission' +} from '../worker/follow-up/worker-follow-up-admission' /** A message to a worker that finished becomes its next Task: worker-start run for the sender, on that same worker. * Open workers take it in place, closed ones reopen in their saved conversation, and agents that keep none start fresh. */ @@ -17,11 +17,11 @@ import type { } from '../../../../orchestration/db/orchestration-records' import type { WorkerTerminalResourceRow } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' import type { RpcContext } from '../../../core' -import { startWorker } from '../worker/workers' +import { startWorker } from '../worker/worker-start-method' import { chooseWorkerFollowUpPlacement, type WorkerFollowUpDelivery -} from '../worker/worker-follow-up-choice' +} from '../worker/follow-up/worker-follow-up-choice' export type WorkerFollowUpPlan = | { kind: 'steer'; dispatchId: string } diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration.ts b/src/main/runtime/rpc/methods/orchestration/orchestration.ts index 377058c7526..ebd3ab25c0d 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration.ts @@ -1,4 +1,4 @@ -import { requiringOrcadFeature } from '../../orcad-feature-readiness' +import { requiringOrcadFeature } from '../../startup/orcad-readiness' import { ORCHESTRATION_CREW_METHODS } from './crew-methods' import { ORCHESTRATION_RUN_METHODS } from './runs/runs' import { ORCHESTRATION_WORKER_METHODS } from './worker/worker-methods' diff --git a/src/main/runtime/rpc/methods/orchestration/receipt-next.ts b/src/main/runtime/rpc/methods/orchestration/receipt-next.ts index 8d699ee357a..1f0b7d68372 100644 --- a/src/main/runtime/rpc/methods/orchestration/receipt-next.ts +++ b/src/main/runtime/rpc/methods/orchestration/receipt-next.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import type { OrcaRuntimeService } from '../../../orca-runtime' -import { projectWorkerListFleet } from './worker/worker-list-projection' +import { projectWorkerListFleet } from './worker/fleet/worker-list-projection' // Only an empty check sees the whole mailbox, so only it says to stop. const AWAIT_WAKE = "Orca wakes you when workers report; end your turn when you're done." diff --git a/src/main/runtime/rpc/methods/orchestration/routing.ts b/src/main/runtime/rpc/methods/orchestration/routing.ts index 2a49c012f14..7a27aa5269c 100644 --- a/src/main/runtime/rpc/methods/orchestration/routing.ts +++ b/src/main/runtime/rpc/methods/orchestration/routing.ts @@ -12,7 +12,7 @@ import { LEGACY_CONTRACT_VERSION } from '../../../orchestration/db/contract-cons import '../../../orchestration/db/messages/mailbox-routing-page' import '../../../orchestration/db/dispatch-row-writer' import '../../../orchestration/db/attempt-outcome-projection' -import { isDispatchMutationMessageType } from '../../../../../shared/rpc-contract/orchestration-params' +import { isDispatchMutationMessageType } from '../../../../../shared/rpc-contract/orchestration/orchestration-params' import { parseMessageTaskId } from './messaging/message-payload' import { federatedMessageNamesOnlyHome } from '../../../orchestration/workers/reports/dispatch-report-mailbox' diff --git a/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts b/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts index 485fa8cb048..222fb086f68 100644 --- a/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts +++ b/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts @@ -7,19 +7,12 @@ import '../../../orchestration/db/messages/mailbox-routing-page' import '../../../orchestration/db/dispatch-row-writer' import '../../../orchestration/db/attempt-outcome-projection' import { OrcaRuntimeService } from '../../../orca-runtime' -import type { TerminalHandleRecord } from '../../../terminal/identity/terminal-handle-records' - -class OrchestrationRpcRuntime extends OrcaRuntimeService { - seedTerminalHandle(handle: string, record: TerminalHandleRecord): void { - this.terminalIdentity.setHandle(handle, record) - } -} export const COORDINATOR_PANE_KEY = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' export type OrchestrationRpcState = { db: OrchestrationDb - runtime: OrchestrationRpcRuntime + runtime: OrcaRuntimeService ctx: RpcContext activeRunId: string | undefined } @@ -28,7 +21,7 @@ export type OrchestrationRpcState = { export function createOrchestrationRpcHarness() { let db: OrchestrationDb let dbOpen = false - let runtime: OrchestrationRpcRuntime + let runtime: OrcaRuntimeService let activeRunId: string | undefined let databasePath = ':memory:' @@ -42,7 +35,7 @@ export function createOrchestrationRpcHarness() { databasePath = path db = new OrchestrationDb(path) dbOpen = true - runtime = new OrchestrationRpcRuntime(store) + runtime = new OrcaRuntimeService(store) runtime.setOrchestrationDb(db) vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => handle === 'term_coord' ? coordinatorPaneKey : null diff --git a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts index 0910402a660..b5829859b49 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts @@ -11,7 +11,7 @@ import { import { DispatchParams, DispatchShowParams -} from '../../../../../../shared/rpc-contract/orchestration-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import { orcaSessionIdOrHandle, resolveDispatchAssigneeParty diff --git a/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts b/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts index 764d3f89580..7236224f535 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts @@ -3,7 +3,7 @@ import { type OrchestrationMutationRequestShowResult } from '../../../../../../shared/orchestration/orchestration-mutation-request' import { defineOrchestrationMethod } from '../access/orchestration-method-access' -import { RequestShowParams } from '../../../../../../shared/rpc-contract/orchestration-runs-mutation-request-show-params' +import { RequestShowParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-runs-mutation-request-show-params' export const ORCHESTRATION_MUTATION_REQUEST_METHODS = [ defineOrchestrationMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts b/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts index f3a4e7c73ca..026d8374d16 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts @@ -1,5 +1,5 @@ import { defineOrchestrationMethod } from '../access/orchestration-method-access' -import { ResetParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import { ResetParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-params' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { listLiveRemoteRunLinkEnvironments } from '../../../../orchestration/db/remote-owned/remote-run-links' diff --git a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts index 12289a6b700..4d81a0390bd 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts @@ -14,7 +14,7 @@ import { RunListParams, RunShowParams, RunUseParams -} from '../../../../../../shared/rpc-contract/orchestration-runs-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-runs-params' function cancelBoundDispatchWaiters( runtime: OrcaRuntimeService, diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.test.ts deleted file mode 100644 index 09b8d40c559..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { agentSessionConversationView } from '../../../../../../shared/agent-session/lifecycle/agent-session-conversation-view' -import type { AgentSessionLease } from '../../../../../../shared/agent-session/lifecycle/agent-session-record' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { StructuredWorkerIdentity } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' - -const hostRef: { current: unknown } = { current: null } - -vi.mock( - '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', - () => ({ - getStructuredAgentSessionHost: () => hostRef.current - }) -) -vi.mock('./orchestration-structured-worker-session', () => ({ - releaseStructuredWorkerSession: vi.fn() -})) - -const { - captureStructuredWorkerArchive, - readArchivedStructuredJournal, - readStructuredWorkerJournal, - stopStructuredWorker -} = await import('./orchestration-structured-worker-lifecycle') -await import('../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority') -await import('../worker/worker-archive-read') - -const IDENTITY: StructuredWorkerIdentity = { - handle: 'structworker_1', - sessionId: 'session-1', - agent: 'claude', - paneKey: 'structured-agent-session-session-1:11111111-1111-4111-a111-111111111111', - processIncarnation: 'structured:session-1', - worktreeId: 'wt_1', - hostScope: { kind: 'local', hostId: 'local' } -} - -const ITEMS: AgentJournalRenderItem[] = [ - { - itemId: 'i1', - observedAt: 1, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'hello' }] } - } as unknown as AgentJournalRenderItem -] - -function installHost(options: { - items?: AgentJournalRenderItem[] - hasSession?: boolean - claimStatus?: AgentSessionLease['claimStatus'] - deathEvidence?: AgentSessionLease['deathEvidence'] - record?: null - close?: () => Promise - setSessionTabVisibility?: () => Promise - historyThrows?: boolean - tabListed?: boolean -}) { - const record = - options.record === null - ? null - : agentSessionRecordFixture( - agentSessionLeaseFixture({ - sessionId: IDENTITY.sessionId, - claimStatus: options.claimStatus ?? 'live', - deathEvidence: options.deathEvidence ?? null, - runtimeFence: 3 - }) - ) - let closed = false - hostRef.current = { - deps: { - logger: { warn: vi.fn() }, - store: { getConversation: () => (record ? agentSessionConversationView(record) : null) } - }, - getPersistedVisibleSessionTabIndex: () => ({ - present: true, - sessionIds: options.tabListed ? [IDENTITY.sessionId] : [] - }), - getSessionTabId: () => (options.tabListed ? 'tab-1' : null), - hasSession: () => (closed ? false : (options.hasSession ?? true)), - setSessionTabVisibility: options.setSessionTabVisibility ?? (async () => {}), - close: - options.close ?? - (async () => { - closed = true - }), - history: () => { - if (options.historyThrows) { - throw new Error('agent_session_not_attached') - } - return { ok: true, page: { items: options.items ?? ITEMS, hasOlder: false } } - } - } -} - -describe('structured worker stop', () => { - beforeEach(() => { - hostRef.current = null - }) - - it('retains without closing a worker whose session has no durable record', async () => { - // Not being able to find the running session is not a reason to act on a guess. - const close = vi.fn(async () => {}) - installHost({ record: null, close }) - const result = await stopStructuredWorker(IDENTITY) - expect(result).toMatchObject({ stopped: false, closeAttempted: false }) - expect(close).not.toHaveBeenCalled() - }) - - it.each([{ hasSession: false }, { claimStatus: 'conflicted' as const }])( - 'retains without positive exit evidence: %j', - async (options) => { - installHost({ ...options, close: async () => {} }) - const retireStructuredAgentSessionTabFromSnapshot = vi.fn() - const result = await stopStructuredWorker(IDENTITY, { - forgetStructuredSessionMail: vi.fn(), - captureStructuredAgentSessionPresentation: () => ({ raw: null, saved: [] }), - currentLocalStructuredSessionPresentation: () => null, - removeCapturedStructuredSessionSavedTabs: vi.fn(), - retireStructuredAgentSessionTabFromSnapshot - }) - expect(result).toMatchObject({ stopped: false, closeAttempted: true }) - expect(retireStructuredAgentSessionTabFromSnapshot).not.toHaveBeenCalled() - } - ) - - it('retains when the close throws, and admits the close was issued', async () => { - installHost({ - close: async () => { - throw new Error('close is queued for retry') - } - }) - const result = await stopStructuredWorker(IDENTITY) - expect(result.stopped).toBe(false) - expect(result.closeAttempted).toBe(true) - expect(result.reason).toContain('retry') - }) - - it('retains when the session is still attached after the close', async () => { - installHost({ hasSession: true, close: async () => {} }) - const result = await stopStructuredWorker(IDENTITY) - expect(result.stopped).toBe(false) - }) - - it('attempts provider close despite a failed tab visibility write', async () => { - // Claiming closed_agent_terminal without an actual close would hide a still-running child. - const close = vi.fn(async () => {}) - installHost({ - close, - setSessionTabVisibility: async () => { - throw new Error('the durable tab index is wedged') - } - }) - const result = await stopStructuredWorker(IDENTITY) - expect(result.stopped).toBe(false) - expect(result.closeAttempted).toBe(true) - expect(close).toHaveBeenCalledOnce() - }) -}) - -describe('structured worker output', () => { - beforeEach(() => { - hostRef.current = null - }) - - it('round-trips the journal through the archive and back out of a released read', async () => { - installHost({}) - const live = await readStructuredWorkerJournal({ - identity: IDENTITY, - dispatchId: 'd1', - workerState: 'ready', - liveness: 'live', - agent: 'claude' - }) - expect(live.source).toBe('transcript') - const archive = await captureStructuredWorkerArchive(IDENTITY, 'claude') - hostRef.current = null - const archived = readArchivedStructuredJournal({ - dispatchId: 'd1', - workerState: 'succeeded', - resourceId: 'res_1', - createdAt: '2026-09-05 00:00:00', - releaseState: 'released', - archive - }) - expect(archived.source).toBe('transcript') - expect(archived.archived).toBe(true) - expect(archived.transcript?.messages).toHaveLength(1) - expect(archived.transcript?.messages[0]?.blocks[0]).toMatchObject({ text: 'hello' }) - // The frozen source has its own identity, so a live cursor cannot be replayed against it. - expect(archived.sourceIdentity).not.toBe(live.sourceIdentity) - }) - - it('redacts dispatch capabilities from the archived journal', async () => { - installHost({ - items: [ - { - itemId: 'i1', - observedAt: 1, - body: { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: `token dcap_${'a'.repeat(30)} here` }] - } - } as unknown as AgentJournalRenderItem - ] - }) - const archive = await captureStructuredWorkerArchive(IDENTITY, 'claude') - expect(JSON.stringify(archive)).not.toContain('dcap_aaa') - expect(JSON.stringify(archive)).toContain('[dispatch capability redacted]') - }) - - it('refuses a cursor once the tail window has slid past it', async () => { - // A stable identity over a sliding bounded tail skipped middle pages; cursor identity must cover index shifts. - installHost({ items: ITEMS }) - const first = await readStructuredWorkerJournal({ - identity: IDENTITY, - dispatchId: 'd1', - workerState: 'ready', - liveness: 'live', - agent: 'claude' - }) - installHost({ - items: [ - { - itemId: 'i2', - observedAt: 2, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'later' }] } - } as unknown as AgentJournalRenderItem - ] - }) - await expect( - readStructuredWorkerJournal({ - identity: IDENTITY, - dispatchId: 'd1', - workerState: 'ready', - liveness: 'live', - agent: 'claude', - cursor: first.cursor - }) - ).rejects.toThrow(/source changed/i) - }) -}) - -describe('archiving a structured worker whose journal cannot be read', () => { - beforeEach(() => { - hostRef.current = null - }) - - it('settles with an empty, warned archive once the session is PROVEN gone', async () => { - // A user-closed chat cannot produce future journal evidence; archive_failed must not wedge release forever. - installHost({ - historyThrows: true, - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed', detail: 'surface released', observedAt: 1 } - }) - const archive = await captureStructuredWorkerArchive(IDENTITY, 'claude') - expect(archive.messages).toEqual([]) - expect(archive.processIncarnation).toBe(IDENTITY.processIncarnation) - expect(archive.warnings).toContain( - 'The structured session was already closed, so its journal could not be preserved.' - ) - }) - - it('retains a worker at rest: released, but its chat tab still lists it', async () => { - // Idle-sweep release is not retirement; owned unreadable journals retain evidence for later archive. - installHost({ - historyThrows: true, - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed', detail: 'idle stop', observedAt: 1 }, - tabListed: true - }) - await expect(captureStructuredWorkerArchive(IDENTITY, 'claude')).rejects.toThrow(/retained/) - }) - - it('still retains when the journal is unreadable but nothing proves the child is gone', async () => { - installHost({ historyThrows: true }) - await expect(captureStructuredWorkerArchive(IDENTITY, 'claude')).rejects.toThrow(/retained/) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts index 699587cb6d0..538e804dc01 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts @@ -6,12 +6,8 @@ import type { OrchestrationWorkerReadTranscriptResult } from '../../../../../../ import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { - buildStructuredJournalArchive, - captureRetiredLineageArchive, - readStructuredLineageArchiveJournal, - type WorkerStructuredJournalArchive -} from '../../../../orchestration/workers/archives/structured-worker-journal-archive' +import type { WorkerStructuredJournalArchive } from '../../../../orchestration/workers/archives/structured-worker-journal-archive' +import type { WorkerTerminalReleaseState } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' import { readStructuredLineageJournalPage, type StructuredLineageJournalPage @@ -37,9 +33,7 @@ import { } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import type { StructuredWorkerObservation } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' -import { structuredWorkerOwned } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-custody' import type { StructuredWorkerIdentity } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import type { WorkerTerminalReleaseState } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' import { releaseStructuredWorkerSession } from './orchestration-structured-worker-session' import { closeStructuredAgentSessionChild, @@ -148,6 +142,8 @@ export async function readStructuredWorkerJournal(args: { workerState: string liveness: StructuredWorkerObservation['status'] agent: AgentType + /** A released worker's history, read from its closed session. */ + archived?: boolean cursor?: string | number limit?: number }): Promise { @@ -186,7 +182,7 @@ export async function readStructuredWorkerJournal(args: { identityAt, start: cursor?.position ?? 0, limit: args.limit, - archived: false, + archived: args.archived ?? false, liveness: args.liveness }) } @@ -222,38 +218,6 @@ function structuredJournalPrefixIdentity(args: { ]) } -/** Freezes the journal before the session is closed, so a released worker is still readable. */ -export async function captureStructuredWorkerArchive( - identity: StructuredWorkerIdentity, - agent: AgentType -): Promise { - const running = requireRunningStructuredWorker(identity) - // Open resting journals too and preserve the whole /clear lineage. - const page = await readStructuredLineageArchiveJournal(running.lineage) - if (page) { - return buildStructuredJournalArchive({ - agent, - processIncarnation: identity.processIncarnation, - items: page.items, - hasOlder: page.hasOlder - }) - } - // Unreadable owned/unverifiable journals must retain evidence for later archive. - // Only proven-retired lineages may skip missing journals: a user-closed chat can never supply more evidence. - if (structuredWorkerOwned(running) !== false) { - throw new OrchestrationError( - 'archive_failed', - 'Output could not be preserved for this structured worker; the session was retained.' - ) - } - // A retired lineage's unreadable sessions are gone for good; earlier ones may not be. - return captureRetiredLineageArchive({ - agent, - processIncarnation: identity.processIncarnation, - lineage: running.lineage - }) -} - export function readArchivedStructuredJournal(args: { dispatchId: string workerState: string diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-redrive.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-redrive.test.ts deleted file mode 100644 index d1a30bc71e0..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-redrive.test.ts +++ /dev/null @@ -1,611 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../../../shared/constants' -import { partialRuntimeStore } from '../../../../orca-runtime-tests/runtime-store-partial-fixture' -import { withChatTabChanges } from '../../../../agent-session/agent-session-tab-layout' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import '../../../../../native-chat/agent-session-wire/publication/history/agent-session-history-page' -import '../../../../../native-chat/agent-session-wire/publication/subscribers/agent-session-subscriber-frame-fields' -import { hostTestState } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' -import { createTestParams } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-create-test-fixture' -import { - hostTestAttachParams, - hostTestOperationId -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import { setStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { - structuredWorkerIdentities, - type StructuredWorkerIdentity -} from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { createOrchestrationRpcHarness } from '../rpc-test-harness' -import { - createStructuredWorkerSession, - releaseStructuredWorkerSession -} from './orchestration-structured-worker-session' -import { stopStructuredWorker } from './orchestration-structured-worker-lifecycle' -import { OrcaRuntimeRpcServer } from '../../../server/runtime-rpc' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { STATUS_METHODS } from '../../host-management/status' -import { createKeyedTrailingEdgeCoalescer } from '../../../../client/events/keyed-trailing-edge-coalescer' -import { subscribeForRedrive } from '../../../../orchestration/mailbox/structured-pointer/structured-session-journal-redrive' -import { idOf, resultOf } from '../../../orchestration-session-caller-test-fixture' -import { createStructuredWorkerSessionForWorktree } from '../worker/worker-topology' -import { completeWorkerTerminalRelease } from '../worker/worker-release-completion' - -vi.mock('../../structured-sessions/creation/structured-agent-session-create', () => ({ - createStructuredAgentSessionForWorktree: async (args: { envelope: { sessionId: string } }) => { - const { host } = hostTestState() - return host.create( - { callerKey: 'redrive-test' }, - createTestParams(undefined, { - envelope: { - ...args.envelope, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: null, - payloadFingerprint: '0'.repeat(64) - } - }) - ) - } -})) - -const harness = createOrchestrationRpcHarness() -let state: ReturnType -let dispatchId: string -let workerSessionIds: string[] -let watches: (() => void)[] - -function createDispatch() { - const task = state.db.createTask({ spec: 'redrive test' }) - const id = state.db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: 10, - taskId: task.id, - startOptions: {} - }).dispatch.id - return id -} - -beforeEach(() => { - vi.useFakeTimers() - structuredWorkerIdentities.clear() - state = harness.setup() - vi.spyOn(state.runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue(undefined) - const { host, store, acquire } = hostTestState() - const acquireImpl = acquire.getMockImplementation() - if (!acquireImpl) { - throw new Error('Fixture acquisition is missing') - } - acquire.mockImplementation(async (input) => { - const acquired = await acquireImpl(input) - if (!acquired.link) { - throw new Error('Fixture acquisition has no provider link') - } - return { - ...acquired, - link: { - ...acquired.link, - origin: store.getRecord(input.identity.sessionId)?.providerHandleChain.length - ? 'resumed' - : 'created' - } - } - }) - setStructuredAgentSessionHost(host) - workerSessionIds = [] - watches = [] - dispatchId = createDispatch() -}) - -afterEach(() => { - watches.forEach((dispose) => dispose()) - for (const id of workerSessionIds) { - releaseStructuredWorkerSession(id, state.runtime) - } - vi.useRealTimers() - harness.cleanup() - setStructuredAgentSessionHost(null) - structuredWorkerIdentities.clear() - vi.restoreAllMocks() -}) - -async function startWorker(workerDispatchId = dispatchId) { - const { identity } = await createStructuredWorkerSession({ - runtime: state.runtime, - worktreeId: 'workspace-1', - agent: 'codex', - dispatchId: workerDispatchId - }) - workerSessionIds.push(identity.sessionId) - return workerJournal(identity) -} - -/** A worker heard as parked mail hears it: every publication of its journal, coalesced. */ -async function startWatchedWorker() { - const worker = await startWorker() - const onJournalActivity = vi.fn<(sessionId: string) => void>() - watches.push( - subscribeForRedrive(worker.host, worker.identity.sessionId, onJournalActivity, () => true) - ) - return { ...worker, onJournalActivity } -} - -function workerJournal(identity: StructuredWorkerIdentity) { - const { host, store } = hostTestState() - const session = host.collaboratorsForTests().sessions.get(identity.sessionId) - if (!session) { - throw new Error('Worker did not open its journal') - } - const append = async (id: string) => { - await host - .collaboratorsForTests() - .sessions.get(identity.sessionId)! - .journal.appendItem( - { provider: 'orca', clientMessageId: id }, - { kind: 'status', text: id }, - { - fence: store.requireWritableRecord(identity.sessionId).lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - return { - host, - identity, - journal: session.journal, - fence: store.requireWritableRecord(identity.sessionId).lease.runtimeFence, - append - } -} - -async function startOwnedWorker() { - const { identity } = await createStructuredWorkerSessionForWorktree({ - runtime: state.runtime, - worktreeId: 'workspace-1', - agent: 'codex', - dispatchId, - effects: [] - }) - workerSessionIds.push(identity.sessionId) - await reattach(identity.sessionId) - state.db.prepareStartingWorkerAuthority({ - dispatchId, - ...identity, - hostScope: JSON.stringify(identity.hostScope), - setupState: 'not_applicable', - terminalOwnership: 'created', - effects: [] - }) - state.db.markWorkerDispatchReady(dispatchId) - return workerJournal(identity) -} - -function claimAutomaticRelease(identity: StructuredWorkerIdentity) { - const worker = state.db.getDispatchContextById(dispatchId) - if (!worker?.task_id) { - throw new Error('Worker Dispatch is missing') - } - expect( - state.db.settleWorkerReport({ - taskId: worker.task_id, - dispatchId, - outcome: 'succeeded', - result: 'Worker finished' - }).action - ).toBe('settled') - expect(state.db.claimDueWorkerTerminalAutoReleases(Date.now() + 120_000)).toBe(1) - const resource = state.db.getWorkerTerminalResourceByOwner(dispatchId) - if (!resource) { - throw new Error('Worker resource is missing') - } - expect(resource.terminal_handle).toBe(identity.handle) - return resource -} - -function holdClose(sessionId: string) { - const { host } = hostTestState() - const lane = Promise.withResolvers() - const entered = Promise.withResolvers() - const held = host.collaboratorsForTests().serialize(sessionId, () => lane.promise) - const close = host.close - vi.spyOn(host, 'close').mockImplementation((...args) => { - entered.resolve() - return close(...args) - }) - return { - entered: entered.promise, - release: async () => { - lane.resolve() - await held - } - } -} - -async function reattach(sessionId: string) { - const { host, store } = hostTestState() - const result = await host.attach( - { callerKey: 'redrive-test' }, - hostTestAttachParams(store.requireWritableRecord(sessionId).lease.runtimeFence, { - envelope: { - sessionId, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.requireWritableRecord(sessionId).lease.runtimeFence, - payloadFingerprint: '0'.repeat(64) - } - }) - ) - expect(result.ok).toBe(true) -} - -describe('the structured redrive publication edge', () => { - it.each(['stream', 'journal'] as const)( - '%s steers real CLI mail into the running turn, retains failed sends and cancels teardown', - async (carrier) => { - vi.useRealTimers() - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - const { host, root, store, dispatch } = hostTestState() - const notify = vi.spyOn(state.runtime, 'notifyStructuredSessionJournalActivity') - let disposeStream = () => {} - if (carrier === 'stream') { - vi.spyOn(host, 'observeJournalPublications').mockImplementation(() => () => {}) - } - const { identity } = await createStructuredWorkerSessionForWorktree({ - runtime: state.runtime, - worktreeId: 'workspace-1', - agent: 'codex', - dispatchId, - effects: [] - }) - const worker = workerJournal(identity) - await reattach(worker.identity.sessionId) - if (carrier === 'stream') { - // Preserve the previous batch/reset carrier as an outcome oracle for the moved wake. - const coalescer = createKeyedTrailingEdgeCoalescer( - (id) => state.runtime.notifyStructuredSessionJournalActivity(id), - { flushMs: 300, maxWaitMs: 2_000 } - ) - const unsubscribe = await host.subscribe({ - id: `orchestration:redrive:${worker.identity.sessionId}`, - sessionId: worker.identity.sessionId, - emit: (event) => { - if (event.type === 'batch' || event.type === 'reset') { - coalescer.schedule(worker.identity.sessionId) - } - } - }) - disposeStream = () => { - coalescer.dispose() - unsubscribe() - } - } - state.db.prepareStartingWorkerAuthority({ - dispatchId, - handle: worker.identity.handle, - paneKey: worker.identity.paneKey, - processIncarnation: worker.identity.processIncarnation, - worktreeId: 'workspace-1', - effects: [], - setupState: 'not_applicable' - }) - state.db.markWorkerDispatchReady(dispatchId) - const mailbox = `dispatch:${dispatchId}` - const held = state.db.insertMessage({ - from: 'term_coord', - to: mailbox, - subject: 'Already being handled', - deliveryContract: 'current_delivery' - }) - expect( - state.db - .getOrCreateMailboxDelivery({ - runId: state.activeRunId!, - mailboxHandle: mailbox, - consumerGeneration: state.db.getDispatchContextById(dispatchId)!.consumer_generation - }) - ?.messages.map((message) => message.id) - ).toEqual([held.id]) - const fence = store.requireWritableRecord(worker.identity.sessionId).lease.runtimeFence - const turn = { provider: 'orca', clientMessageId: 'busy-turn' } as const - await worker.journal.appendItem( - turn, - { kind: 'turn', turnId: 'busy-turn', state: 'running' }, - { fence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - expect(host.currentWork(worker.identity.sessionId)?.working()).toBe(true) - await vi.advanceTimersByTimeAsync(300) - dispatch.mockClear() - notify.mockClear() - for (const name of ['ORCA_AGENT_SESSION_ID', 'ORCA_ENVIRONMENT', 'ORCA_PAIRING_CODE']) { - vi.stubEnv(name, '') - } - vi.stubEnv('ORCA_USER_DATA_PATH', root) - vi.stubEnv('ORCA_TERMINAL_HANDLE', 'term_coord') - const output = vi.spyOn(console, 'log').mockImplementation(() => {}) - const server = new OrcaRuntimeRpcServer({ - runtime: state.runtime, - userDataPath: root, - enableWebSocket: false, - methods: [...STATUS_METHODS, ...ORCHESTRATION_METHODS] - }) - const exitCode = process.exitCode - // The CLI has its own typecheck project; load its real entry point at the runtime boundary. - const cliPath = '../../../../../../cli/index' - const { main }: { main(argv: string[], cwd: string): Promise } = await import(cliPath) - const sendMail = async (subject: string) => { - output.mockClear() - process.exitCode = undefined - await main( - ['orchestration', 'send', '--to', mailbox, '--subject', subject, '--json', '--full'], - root - ) - expect(process.exitCode, JSON.stringify(output.mock.calls)).toBeUndefined() - const response: unknown = JSON.parse(String(output.mock.calls.at(-1)?.[0])) - return idOf(resultOf(response).message) - } - try { - await server.start() - // A send that throws keeps its reservation; the session's next journal edge finds it never - // admitted and sends it again under the same id. - const send = vi.spyOn(host, 'send').mockRejectedValueOnce(new Error('provider unavailable')) - const messageId = await sendMail('Continue during the current turn') - expect(send).toHaveBeenCalledTimes(1) - expect(state.db.getMessageById(messageId)).toMatchObject({ read: 0 }) - expect(state.db.getStructuredMailSends(mailbox)).toHaveLength(1) - await worker.append('provider-available') - await vi.advanceTimersByTimeAsync(300) - expect(send).toHaveBeenCalledTimes(2) - // Retried mail joins the current turn through the host's automatic drain. - expect(state.db.getMessageById(messageId)).toMatchObject({ - read: 0, - delivered_at: expect.any(String) - }) - expect(dispatch).toHaveBeenCalledTimes(1) - expect(dispatch.mock.calls[0]![0].body).toMatchObject({ - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: expect.stringContaining('Subject: Continue during the current turn') - } - ], - from: { - orchestration: { - message: 'mail-notice', - mailbox, - messages: [{ messageId }] - } - } - }) - releaseStructuredWorkerSession(worker.identity.sessionId, state.runtime) - disposeStream() - notify.mockClear() - const cancelledId = await sendMail('Do not deliver after teardown') - await worker.append('after-teardown') - await vi.advanceTimersByTimeAsync(5_000) - expect(notify).not.toHaveBeenCalled() - expect(dispatch).toHaveBeenCalledTimes(1) - expect(state.db.getMessageById(cancelledId)).toMatchObject({ read: 0 }) - } finally { - disposeStream() - await server.stop() - process.exitCode = exitCode - vi.unstubAllEnvs() - } - } - ) - - it.each(['new-turn', 'kept-released-owner'] as const)( - 'retains ownership, presentation and parked mail on refused automatic close: %s', - async (mode) => { - vi.useRealTimers() - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - harness.cleanup() - let savedSession = getDefaultWorkspaceSession() - state = harness.setup( - true, - partialRuntimeStore({ - getWorkspaceSession: () => savedSession, - getWorkspaceSessionHostIds: () => ['local'], - setWorkspaceSession: (next) => { - savedSession = next - } - }) - ) - vi.spyOn(state.runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue(undefined) - dispatchId = createDispatch() - const { host, store, dispatch } = hostTestState() - const { identity, journal } = await startOwnedWorker() - const tabId = host.getSessionTabId(identity.sessionId) - if (!tabId) { - throw new Error('Worker has no listed tab') - } - savedSession = - withChatTabChanges('local', savedSession, identity.worktreeId, [ - { - open: { sessionId: identity.sessionId, agent: 'codex', tabId } - } - ]) ?? savedSession - await state.runtime.publishStructuredAgentSessionTab({ - workspaceId: identity.worktreeId, - sessionId: identity.sessionId, - agent: 'codex', - activate: true - }) - await vi.advanceTimersByTimeAsync(300) - const mailbox = `dispatch:${dispatchId}` - const { id: messageId } = state.db.insertMessage({ - from: 'term_coord', - to: mailbox, - subject: 'Continue when available' - }) - const send = vi.spyOn(host, 'send').mockRejectedValueOnce(new Error('provider unavailable')) - dispatch.mockClear() - state.runtime.notifyMessageArrived(mailbox, 'message') - await vi.advanceTimersByTimeAsync(300) - expect(send).toHaveBeenCalledTimes(1) - expect(dispatch).not.toHaveBeenCalled() - expect(state.db.getMessageById(messageId)).toMatchObject({ read: 0 }) - expect(state.db.getStructuredMailSends(mailbox)).toHaveLength(1) - const attached = host.collaboratorsForTests().sessions.get(identity.sessionId) - if (mode === 'kept-released-owner') { - const child = attached?.child - if (!child?.generation) { - throw new Error('Worker has no acquired child') - } - await host.handleAdapterEvent({ - type: 'ended', - sessionId: identity.sessionId, - fence: child.fence, - acquisitionGeneration: child.generation, - reason: 'Provider naturally exited', - cause: 'unexpected-exit' - }) - expect(store.requireWritableRecord(identity.sessionId).lease).toMatchObject({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed' } - }) - expect(host.collaboratorsForTests().sessions.get(identity.sessionId)?.journal).toBe(journal) - } - const lease = store.requireWritableRecord(identity.sessionId).lease - const resource = claimAutomaticRelease(identity) - const presentation = state.runtime.captureStructuredAgentSessionPresentation( - identity.sessionId - ) - expect(presentation.raw).toEqual({ - worktreeId: identity.worktreeId, - tabId: `agent-session:${identity.sessionId}` - }) - expect(presentation.saved).toContainEqual({ worktreeId: identity.worktreeId, tabId }) - const savedBefore = structuredClone(savedSession) - const providerStop = vi.fn>( - async () => true - ) - host.deps.adapter.closeSession = providerStop - const forget = vi.spyOn(state.runtime, 'forgetStructuredSessionMail') - const retire = vi.spyOn(state.runtime, 'retireStructuredAgentSessionTabFromSnapshot') - const saved = vi.spyOn(state.runtime, 'removeCapturedStructuredSessionSavedTabs') - const hide = vi.spyOn(host, 'setSessionTabVisibility') - const admission = vi.spyOn(state.db, 'admitWorkerChatReleaseClose') - const observe = vi.spyOn(host, 'observeJournalPublications') - const create = vi.spyOn(host, 'create') - const heldClose = holdClose(identity.sessionId) - const closing = completeWorkerTerminalRelease({ - runtime: state.runtime, - db: state.db, - dispatchId, - resource - }) - const newTurn = { provider: 'orca', clientMessageId: 'new-turn-before-close' } as const - try { - await heldClose.entered - expect(state.db.getWorkerTerminalResource(resource.id)?.release_state).toBe('releasing') - expect(state.db.getWorkerTerminalArchive(dispatchId)).toBeDefined() - if (mode === 'new-turn') { - await journal.appendItem( - newTurn, - { kind: 'turn', turnId: 'new-turn-before-close', state: 'running' }, - { fence: lease.runtimeFence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - expect(state.runtime.isWorkerAgentInTurn(resource)).toBe(true) - } else { - expect(state.db.keepWorkerTerminalOpen(identity.paneKey)).toBe(1) - } - } finally { - await heldClose.release() - } - expect(await closing).toMatchObject({ state: 'retained', processAction: 'none' }) - expect(admission).toHaveBeenCalledExactlyOnceWith(resource.id, expect.any(Function)) - expect(admission.mock.results[0]?.value).toBe(false) - for (const effect of [providerStop, retire, saved, hide]) { - expect(effect).not.toHaveBeenCalled() - } - expect(host.getSessionTabId(identity.sessionId)).toBe(tabId) - expect(host.collaboratorsForTests().sessions.get(identity.sessionId)).toBe(attached) - expect(store.requireWritableRecord(identity.sessionId).lease).toEqual(lease) - expect(state.db.getWorkerTerminalResource(resource.id)).toMatchObject({ - ownership_state: 'owned', - release_state: mode === 'new-turn' ? 'not_requested' : 'retained', - ...(mode === 'kept-released-owner' ? { retained_reason: 'user_kept' } : {}) - }) - expect(state.db.getWorkerTerminalArchive(dispatchId)).toBeUndefined() - expect.soft(forget).not.toHaveBeenCalled() - expect.soft(structuredWorkerIdentities.get(identity.handle)).toEqual(identity) - expect(state.runtime.captureStructuredAgentSessionPresentation(identity.sessionId)).toEqual( - presentation - ) - expect(savedSession).toEqual(savedBefore) - // The send that threw keeps its reservation for the retry. - expect(state.db.getMessageById(messageId)).toMatchObject({ read: 0 }) - expect(state.db.getStructuredMailSends(mailbox)).toHaveLength(1) - if (mode === 'new-turn') { - await journal.appendTombstone(newTurn, { fence: lease.runtimeFence }) - await vi.advanceTimersByTimeAsync(300) - expect(observe).not.toHaveBeenCalled() - expect(create).not.toHaveBeenCalled() - // Its Dispatch settled: the mail goes to a follow-up, never into the chat that finished it. - expect(send).toHaveBeenCalledTimes(1) - expect(dispatch).not.toHaveBeenCalled() - expect(state.db.getMessageById(messageId)).toMatchObject({ read: 0, delivered_at: null }) - } - } - ) - - it('releases bookkeeping after an admitted genuinely failed provider Stop without retiring its surface', async () => { - const { host, store } = hostTestState() - const { identity } = await startWorker() - await reattach(identity.sessionId) - const tabId = host.getSessionTabId(identity.sessionId) - const child = host.collaboratorsForTests().sessions.get(identity.sessionId)?.child - if (!child?.generation) { - throw new Error('Worker has no acquired child') - } - const providerStop = vi.fn(async () => false) - host.deps.adapter.closeSession = providerStop - const admit = vi.fn(() => true) - const forget = vi.spyOn(state.runtime, 'forgetStructuredSessionMail') - const hide = vi.spyOn(host, 'setSessionTabVisibility') - const retire = vi.spyOn(state.runtime, 'retireStructuredAgentSessionTabFromSnapshot') - try { - expect(await stopStructuredWorker(identity, state.runtime, admit)).toMatchObject({ - stopped: false, - closeAttempted: true - }) - expect(admit).toHaveBeenCalledOnce() - expect(providerStop).toHaveBeenCalledOnce() - expect(admit.mock.invocationCallOrder[0]).toBeLessThan( - providerStop.mock.invocationCallOrder[0]! - ) - expect(forget).toHaveBeenCalledExactlyOnceWith(identity.sessionId) - expect(structuredWorkerIdentities.get(identity.handle)).toBeNull() - expect(store.requireWritableRecord(identity.sessionId).lease.claimStatus).toBe('live') - expect(host.getSessionTabId(identity.sessionId)).toBe(tabId) - expect(hide).not.toHaveBeenCalled() - expect(retire).not.toHaveBeenCalled() - } finally { - await host.handleAdapterEvent({ - type: 'ended', - sessionId: identity.sessionId, - fence: child.fence, - acquisitionGeneration: child.generation, - reason: 'Provider exited after failed Stop', - cause: 'unexpected-exit' - }) - } - }) - - it('keeps the observer across close and reattach with a new fence', async () => { - const { host, identity, onJournalActivity } = await startWatchedWorker() - await reattach(identity.sessionId) - const snapshot = vi.spyOn(host.collaboratorsForTests().subscribers, 'snapshot') - await host.close(identity.sessionId, 'evict') - await host.journalSnapshot(identity.sessionId) - vi.advanceTimersByTime(300) - onJournalActivity.mockClear() - - await reattach(identity.sessionId) - vi.advanceTimersByTime(300) - - expect(snapshot).toHaveBeenCalled() - expect(onJournalActivity).toHaveBeenCalledExactlyOnceWith(identity.sessionId) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-retry.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-retry.test.ts index 2ff29416200..371a48bc2be 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-retry.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-retry.test.ts @@ -17,8 +17,8 @@ import { createStructuredWorkerSession, releaseStructuredWorkerSession } from './orchestration-structured-worker-session' -import { deliverWorkerDispatchPreamble } from '../worker/deliver-worker-dispatch-preamble' -import { tearDownFailedWorkerStart } from '../worker/failed-worker-start-teardown' +import { deliverWorkerDispatchPreamble } from '../worker/start/readiness/deliver-worker-dispatch-preamble' +import { tearDownFailedWorkerStart } from '../worker/start/readiness/failed-worker-start-teardown' import { structuredWorkerIdentities } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' import { rpcContext, runtimeStub } from '../../agent-launch/agent-launch.test-fixture' diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-mode-opacity.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-mode-opacity.test.ts index 8d157240133..4f27a921989 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-mode-opacity.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-mode-opacity.test.ts @@ -22,7 +22,7 @@ import { import '../../../../orchestration/workers/launch/worker-dispatch-preamble' import { ORCHESTRATION_METHODS } from '../orchestration' import './orchestration-structured-worker-lifecycle' -import '../worker/worker-observation' +import '../worker/observation/worker-observation' const WORKTREE = 'repo::wt' const STRUCTURED_HANDLE = 'structworker_worker' @@ -39,7 +39,7 @@ vi.mock( }) ) -vi.mock('../worker/worker-topology', async (importOriginal) => ({ +vi.mock('../worker/start/placement/worker-placement-topology', async (importOriginal) => ({ ...(await importOriginal>()), createStructuredWorkerSessionForWorktree: async (args: { effects: unknown[] }) => { args.effects.push({ kind: 'terminal', role: 'agent', action: 'created' }) diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-release-incarnation-fallback.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-release-incarnation-fallback.test.ts deleted file mode 100644 index a51ac90d1e5..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-worker-release-incarnation-fallback.test.ts +++ /dev/null @@ -1,396 +0,0 @@ -import { afterEach, describe, expect, it, vi, type MockInstance } from 'vitest' -import { z } from 'zod' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { isStreamingMethod, eraseRpcMethods, type RpcContext, type RpcMethod } from '../../../core' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' - -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { completeWorkerTerminalRelease } from '../worker/worker-release-completion' -import type { RuntimeTerminalShow } from '../../../../../../shared/runtime-terminal-contracts' -import type { OrchestrationCompatibilityTerminalAuthority } from '../../../../orchestration/terminal-authority/orchestration-compatibility-authority' - -const workerStartResult = z.object({ dispatchId: z.string(), state: z.string() }) - -describe('orchestration worker release incarnation fallback', () => { - let db: OrchestrationDb - let dbOpen = false - let runtime: OrcaRuntimeService - let ctx: RpcContext - let activeRunId: string - let inspectProcessLiveness: MockInstance< - OrcaRuntimeService['inspectTerminalProcessIncarnationLiveness'] - > - - const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - - function workerTerminal(handle: string): RuntimeTerminalShow { - return { - handle, - ptyId: 'pty_worker', - paneRuntimeId: 1, - rendererGraphEpoch: 1, - worktreeId: 'repo::worktree', - worktreePath: '/repo/worktree', - branch: 'worktree', - tabId: 'tab-worker', - leafId: 'leaf-worker', - title: 'worker', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - } - } - - function workerAuthority(handle: string): OrchestrationCompatibilityTerminalAuthority { - return { - runtimeId: 'runtime_test', - terminalHandle: handle, - ptyId: 'pty_worker', - worktreeId: 'repo::worktree', - paneKey: workerPaneKey, - processIncarnation: 'runtime_test:term_worker:1', - launchTokenHash: null, - hostScope: { kind: 'local', hostId: 'local' } - } - } - - function setup(): void { - db = new OrchestrationDb(':memory:') - dbOpen = true - runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - inspectProcessLiveness = vi - .spyOn(runtime, 'inspectTerminalProcessIncarnationLiveness') - .mockResolvedValue('live') - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' - ? coordinatorPaneKey - : handle === 'term_worker' || handle === 'term_reminted' - ? workerPaneKey - : null - ) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => - handle === 'term_worker' || handle === 'term_reminted' ? 'runtime_test:term_worker:1' : null - ) - vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockImplementation((handle) => - handle === 'term_worker' || handle === 'term_reminted' ? workerAuthority(handle) : null - ) - vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) - vi.spyOn(runtime, 'showTerminal').mockImplementation(async (handle) => workerTerminal(handle)) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: worker start reads only the managed worktree's id. - vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockResolvedValue({ - id: 'repo::worktree' - } as never) - vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - title: 'worker' - }) - vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: true, - status: 'running', - exitCode: null - }) - vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ - handle: 'term_worker', - accepted: true, - bytesWritten: 1 - }) - vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - vi.spyOn(runtime, 'getExactWorkerProviderSession').mockReturnValue(null) - vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: ['worker output line 1', 'worker output line 2'], - truncated: false, - nextCursor: '2' - }) - vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({ - handle: 'term_worker', - tabId: 'tab-worker', - ptyKilled: true - }) - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) - activeRunId = db.createRun({ - objective: 'Release test Run', - coordinatorHandle: 'term_coord', - coordinatorPaneKey - }).id - ctx = { runtime } - } - - afterEach(() => { - if (dbOpen) { - dbOpen = false - db.close() - } - vi.restoreAllMocks() - }) - - function findMethod(name: string): RpcMethod { - const method = eraseRpcMethods(ORCHESTRATION_METHODS).find((m) => m.name === name) - if (!method || isStreamingMethod(method)) { - throw new Error(`Method not found: ${name}`) - } - return method - } - - async function call(name: string, params: Record) { - const method = findMethod(name) - const parsed = method.params ? method.params.parse(params) : undefined - return method.handler(parsed, ctx) - } - - async function startWorker(options: { terminal?: string } = {}): Promise<{ - taskId: string - dispatchId: string - }> { - const task = db.createTask({ spec: 'release fixture task', runId: activeRunId }) - const result = workerStartResult.parse( - await call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - ...(options.terminal ? { terminal: options.terminal } : { agent: 'codex' }) - }) - ) - expect(result.state).toBe('ready') - return { taskId: task.id, dispatchId: result.dispatchId } - } - - /** Record the worker's report as settled — the precondition for release. */ - function settle(taskId: string, dispatchId: string, outcome: 'succeeded' | 'failed'): void { - const settlement = db.settleWorkerReport({ - taskId, - dispatchId, - outcome, - result: `worker ${outcome}` - }) - expect(settlement.action).toBe('settled') - } - - async function startSettledWorker( - outcome: 'succeeded' | 'failed' = 'succeeded', - options: { terminal?: string } = {} - ): Promise<{ taskId: string; dispatchId: string }> { - const worker = await startWorker(options) - settle(worker.taskId, worker.dispatchId, outcome) - return worker - } - - it('closes a live worker terminal whose durable handle no longer resolves but whose process incarnation still matches', async () => { - setup() - const { dispatchId } = await startSettledWorker() - // The durable handle stops resolving (renderer graph epoch bump / handle invalidation)... - vi.mocked(runtime.showTerminal).mockImplementation(async (handle) => - handle === 'term_worker' - ? Promise.reject(new Error('terminal_handle_stale')) - : workerTerminal(handle) - ) - // ...but the recorded process incarnation still names a live PTY, re-minted to a fresh handle. - const resolveByIncarnation = vi.fn().mockReturnValue('term_reminted') - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - - const receipt = await call('orchestration.workerRelease', { dispatch: dispatchId }) - - expect(receipt).toMatchObject({ state: 'released', processAction: 'closed_agent_terminal' }) - expect(resolveByIncarnation).toHaveBeenCalledWith( - 'runtime_test:term_worker:1', - JSON.stringify({ kind: 'local', hostId: 'local' }) - ) - // The close targeted exactly the re-minted live handle for that PTY, never the stale one. - expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) - expect(runtime.closeTerminal).toHaveBeenCalledWith('term_reminted') - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'released', - release_state: 'released' - }) - }) - - it('stays release_unknown and closes nothing when the recorded incarnation no longer matches a live pty', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - // A reused ptyId now belongs to a different process: the incarnation mismatch refuses a close. - const resolveByIncarnation = vi.fn().mockReturnValue(null) - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - - const receipt = await call('orchestration.workerRelease', { dispatch: dispatchId }) - - expect(receipt).toMatchObject({ state: 'release_unknown' }) - expect(resolveByIncarnation).toHaveBeenCalledWith( - 'runtime_test:term_worker:1', - JSON.stringify({ kind: 'local', hostId: 'local' }) - ) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('unknown') - }) - - it('does not plain-settle an exited missing worker when the archive was never committed', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - const resolveByIncarnation = vi.fn().mockReturnValue(null) - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - inspectProcessLiveness.mockResolvedValue('exited') - - const receipt = await call('orchestration.workerRelease', { dispatch: dispatchId }) - - expect(receipt).toMatchObject({ state: 'release_unknown', processAction: 'none' }) - expect(inspectProcessLiveness).toHaveBeenCalled() - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'owned', - release_state: 'unknown' - }) - }) - - it('settles released without a close when exited missing and an archive is already committed', async () => { - setup() - const { dispatchId } = await startSettledWorker() - const requested = db.requestWorkerTerminalRelease(dispatchId) - if (requested.disposition !== 'requested') { - throw new Error(`expected requested, got ${requested.disposition}`) - } - db.commitWorkerTerminalArchiveForRelease({ - dispatchId, - resourceId: requested.resource.id, - kind: 'terminal_tail', - content: JSON.stringify({ lines: [] }), - archiveSource: 'terminal', - archiveStatus: 'empty' - }) - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - const resolveByIncarnation = vi.fn().mockReturnValue(null) - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - inspectProcessLiveness.mockResolvedValue('exited') - - const receipt = await completeWorkerTerminalRelease({ - runtime, - db, - dispatchId, - resource: db.getWorkerTerminalResource(requested.resource.id)!, - mode: 'interactive' - }) - - expect(receipt).toMatchObject({ state: 'released', processAction: 'none' }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'released', - release_state: 'released' - }) - }) - - it('recovery-mode: defers when exited missing has no archive rather than plain-settling', async () => { - // After proven death with no archive, recovery retains release_pending rather than plain-settling. - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - const resolveByIncarnation = vi.fn().mockReturnValue(null) - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - inspectProcessLiveness.mockResolvedValue('exited') - const requested = db.requestWorkerTerminalRelease(dispatchId) - if (requested.disposition !== 'requested') { - throw new Error(`expected a requested release, got ${requested.disposition}`) - } - - const receipt = await completeWorkerTerminalRelease({ - runtime, - db, - dispatchId, - resource: requested.resource, - mode: 'recovery' - }) - - expect(receipt).toMatchObject({ state: 'release_pending', processAction: 'none' }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'owned', - release_state: 'requested' - }) - }) - - it('recovery-mode: settles released before the defer when exited missing already has an archive', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - const resolveByIncarnation = vi.fn().mockReturnValue(null) - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - inspectProcessLiveness.mockResolvedValue('exited') - const requested = db.requestWorkerTerminalRelease(dispatchId) - if (requested.disposition !== 'requested') { - throw new Error(`expected a requested release, got ${requested.disposition}`) - } - db.commitWorkerTerminalArchiveForRelease({ - dispatchId, - resourceId: requested.resource.id, - kind: 'terminal_tail', - content: JSON.stringify({ lines: [] }), - archiveSource: 'terminal', - archiveStatus: 'empty' - }) - - const receipt = await completeWorkerTerminalRelease({ - runtime, - db, - dispatchId, - resource: db.getWorkerTerminalResource(requested.resource.id)!, - mode: 'recovery' - }) - - expect(receipt).toMatchObject({ state: 'released', processAction: 'none' }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'released', - release_state: 'released' - }) - }) - - it('recovery-mode: defers release_pending when liveness is unverifiable rather than provably exited', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - const resolveByIncarnation = vi.fn().mockReturnValue(null) - vi.spyOn(runtime, 'resolveTerminalHandleByProcessIncarnation').mockImplementation( - resolveByIncarnation - ) - // Not a death certificate: inventory may still be incomplete, so recovery must defer. - inspectProcessLiveness.mockResolvedValue('unverifiable') - const requested = db.requestWorkerTerminalRelease(dispatchId) - if (requested.disposition !== 'requested') { - throw new Error(`expected a requested release, got ${requested.disposition}`) - } - - const receipt = await completeWorkerTerminalRelease({ - runtime, - db, - dispatchId, - resource: requested.resource, - mode: 'recovery' - }) - - expect(receipt).toMatchObject({ state: 'release_pending' }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).not.toBe('released') - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-read-cursor.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-read-cursor.test.ts index 9d7ee69b721..b93d5ab7f2d 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-read-cursor.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-read-cursor.test.ts @@ -6,8 +6,8 @@ import { agentSessionConversationView } from '../../../../../../shared/agent-ses /** Mutate journals between reads to catch in-place revisions and mid-array insertions missed by oldest-item-only cursor identity; both can silently omit or duplicate output. */ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { buildStructuredJournalArchive } from '../../../../orchestration/workers/archives/structured-worker-journal-archive' -import { projectSavedChatContextItems } from '../../../../../native-chat/agent-session-saved-prompt-text' +import { boundStructuredJournalTail } from '../../../../orchestration/workers/archives/structured-worker-journal-archive' +import { projectSavedChatContextItems } from '../../../../../native-chat/conversation-context/agent-session-saved-prompt-text' import { formatWorkerTranscriptMessage } from '../../../../../../shared/worker-transcript-text' import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { StructuredWorkerIdentity } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' @@ -97,7 +97,7 @@ describe('the structured worker-read cursor over a mutating journal', () => { hostRef.current = null }) - it('omits creation facts from worker output, consumed prefixes, saved context and archives', async () => { + it('omits creation facts from worker output, consumed prefixes, saved context and terminal views', async () => { const start: AgentJournalRenderItem = { itemId: 'i2', revision: 1, @@ -132,13 +132,7 @@ describe('the structured worker-read cursor over a mutating journal', () => { expect(textsOf(await read(first.cursor))).toEqual(['answer']) const saved = projectSavedChatContextItems(items).map(formatWorkerTranscriptMessage).join('\n') expect(saved).toBe('[assistant] first\n[assistant] answer') - const archive = buildStructuredJournalArchive({ - agent: 'claude', - processIncarnation: 'fixture', - items, - hasOlder: false - }) - expect(archive.messages.map(formatWorkerTranscriptMessage)).toEqual([ + expect(boundStructuredJournalTail(items).messages.map(formatWorkerTranscriptMessage)).toEqual([ '[assistant] first', '[assistant] answer' ]) diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-tab-retirement.test.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-tab-retirement.test.ts index 739f0f86167..a858d0f97cd 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-tab-retirement.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/structured-worker-tab-retirement.test.ts @@ -26,7 +26,7 @@ vi.mock('../../structured-sessions/creation/structured-agent-session-create', () const { stopStructuredWorker } = await import('./orchestration-structured-worker-lifecycle') const { createStructuredWorkerSession } = await import('./orchestration-structured-worker-session') -await import('../worker/worker-release-completion') +await import('../worker/release/worker-release-completion') const WORKTREE = 'workspace-1' const SESSION = 'session-1' @@ -148,17 +148,6 @@ describe('structured worker stop retires the chat tab', () => { expect(published.activeTabType).toBeNull() expect(emit).toHaveBeenCalled() }) - - it('leaves the tab alone when the close was NOT proven', async () => { - installHost({ closeThrows: true }) - const identity = registerIdentity() - const { runtime } = await runtimeShowingStructuredTab() - - const stop = await stopStructuredWorker(identity, runtime) - - expect(stop.stopped).toBe(false) - expect(await structuredTabIds(runtime)).toEqual([`agent-session:${SESSION}`]) - }) }) describe('structured worker discard retires the chat tab', () => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/closed-worker-terminal.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/closed-worker-terminal.test.ts deleted file mode 100644 index 4b2412d5fa7..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/closed-worker-terminal.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AgentStatusIpcPayload } from '../../../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { useHelperFollowUpCli } from './helper-follow-up-cli.test-support' -import { chooseWorkerFollowUpPlacement } from './worker-follow-up-choice' - -const CONVERSATION = { key: 'session_id', id: 'fixture-conversation' } as const -const REOPENED_PANE = 'tab_reopened:leaf' - -describe('opening a terminal worker Orca closed', () => { - const { h, panes, pair, success } = useHelperFollowUpCli() - - /** A finished helper whose pane recorded `conversation`, then closed by Orca. */ - async function closedHelper(recorded = true) { - const { helper } = await pair() - if (recorded) { - vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ - paneKey: panes.get('term_helper')!, - agent: 'claude', - processIncarnation: 'process:term_helper', - providerSession: CONVERSATION, - observedAt: 1 - }) - } - await success('worker-release', '--dispatch', helper.dispatchId) - const live = new Set() - let hookRows: AgentStatusIpcPayload[] = [] - Object.defineProperty(h.runtime, 'getAgentStatusSnapshotFn', { - configurable: true, - value: () => hookRows - }) - vi.spyOn(h.runtime, 'getTerminalHandleForPaneKey').mockImplementation((paneKey) => - paneKey === REOPENED_PANE && live.has('term_reopened') ? 'term_reopened' : null - ) - vi.spyOn(h.runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => - live.has(handle) ? REOPENED_PANE : null - ) - vi.spyOn(h.runtime, 'isTerminalRunningAgent').mockImplementation(async (handle) => - live.has(handle) - ) - const resume = vi - .spyOn(h.runtime, 'resumeAgentSessionInWorkspace') - .mockImplementation(async () => { - live.add('term_reopened') - return { ok: true, handle: 'term_reopened', paneKey: REOPENED_PANE, ptyId: 'pty' } - }) - /** The reopened pane's agent reports its conversation. */ - const report = (row: Pick) => { - hookRows = [ - { - state: 'working', - prompt: '', - paneKey: REOPENED_PANE, - connectionId: null, - receivedAt: 1, - stateStartedAt: 1, - ...row - } - ] - } - const resource = h.db.getWorkerTerminalResourceByOwner(helper.dispatchId)! - return { helper, resource, resume, report } - } - - const open = (address: string) => h.call('orchestration.partyOpen', { address }) - - it('resumes its conversation in a new terminal, and a click after it reports reuses it', async () => { - const { resource, resume, report } = await closedHelper() - for (let click = 0; click < 2; click++) { - expect(await open(resource.terminal_handle)).toEqual({ - location: { kind: 'terminal', handle: 'term_reopened' } - }) - report({ agentType: 'claude', providerSession: CONVERSATION }) - } - expect(resume).toHaveBeenCalledOnce() - expect(resume).toHaveBeenCalledWith( - resource.worktree_id, - expect.objectContaining({ - agent: 'claude', - providerSession: CONVERSATION, - captureHostId: 'local' - }) - ) - }) - - it('sends a later follow-up into the reopened terminal, not a second one', async () => { - const { helper, resource, resume, report } = await closedHelper() - await open(resource.terminal_handle) - report({ agentType: 'claude', providerSession: CONVERSATION }) - const placement = await chooseWorkerFollowUpPlacement( - h.runtime, - h.db, - h.db.getDispatchContextById(helper.dispatchId)!, - resource, - { admit: () => {}, requested: () => {} } - ) - expect(placement).toMatchObject({ delivery: 'follow_up', terminal: 'term_reopened' }) - expect(resume).toHaveBeenCalledOnce() - }) - - it('resumes again once the reopened terminal holds another conversation', async () => { - const { resource, resume, report } = await closedHelper() - await open(resource.terminal_handle) - report({ agentType: 'codex', providerSession: { key: 'session_id', id: 'unrelated' } }) - await open(resource.terminal_handle) - expect(resume).toHaveBeenCalledTimes(2) - }) - - it('retries an uncertain resume as the same request, and a later resume as a new one', async () => { - const { resource, resume } = await closedHelper() - const succeed = resume.getMockImplementation()! - resume.mockResolvedValueOnce({ ok: false, reason: 'create_failed' }) - await expect(open(resource.terminal_handle)).rejects.toThrow() - resume.mockImplementation(succeed) - await open(resource.terminal_handle) - vi.mocked(h.runtime.isTerminalRunningAgent).mockResolvedValue(false) - await open(resource.terminal_handle) - const [first, retry, later] = resume.mock.calls.map(([, request]) => request.mutationId) - expect(retry).toBe(first) - expect(later).not.toBe(first) - }) - - it('forgets an uncertain request once its conversation reports, so a later resume is a new one', async () => { - const { resource, resume, report } = await closedHelper() - const succeed = resume.getMockImplementation()! - resume.mockImplementationOnce(async (...args) => { - await succeed(...args) - return { ok: false, reason: 'create_failed' } - }) - await expect(open(resource.terminal_handle)).rejects.toThrow() - report({ agentType: 'claude', providerSession: CONVERSATION }) - expect(await open(resource.terminal_handle)).toEqual({ - location: { kind: 'terminal', handle: 'term_reopened' } - }) - vi.mocked(h.runtime.isTerminalRunningAgent).mockResolvedValue(false) - await open(resource.terminal_handle) - const [uncertainId, later] = resume.mock.calls.map(([, request]) => request.mutationId) - expect(resume).toHaveBeenCalledTimes(2) - expect(later).not.toBe(uncertainId) - }) - - it('resumes again once the agent left the reopened terminal', async () => { - const { resource, resume, report } = await closedHelper() - await open(resource.terminal_handle) - report({ agentType: 'claude', providerSession: CONVERSATION }) - vi.mocked(h.runtime.isTerminalRunningAgent).mockResolvedValue(false) - await open(resource.terminal_handle) - expect(resume).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts deleted file mode 100644 index 8c5264ced2e..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RpcContext } from '../../../core' -import { createOrchestrationRpcHarness } from '../rpc-test-harness' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import '../../../../../../shared/constants' -import '../../../../orchestration/workers/launch/worker-dispatch-preamble' - -describe('orchestration RPC methods', () => { - const h = createOrchestrationRpcHarness() - const { coordinatorPaneKey } = h - let db: OrchestrationDb - let runtime: OrcaRuntimeService - let ctx: RpcContext - - function setup(withBoundRun = true): void { - ;({ db, runtime, ctx } = h.setup(withBoundRun)) - } - - afterEach(() => { - h.cleanup() - }) - - async function call(name: string, params: Record) { - return h.call(name, params, ctx) - } - - describe('composed workers', () => { - function mockCurrentWorkerStart(options?: { ready?: boolean }): void { - vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => - handle === 'term_coord' - ? coordinatorPaneKey - : handle === 'term_worker' - ? 'tab_worker:leaf_worker' - : null - ) - vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) - vi.spyOn(runtime, 'showTerminal').mockImplementation( - async (handle) => ({ handle, worktreeId: 'repo::worktree', status: 'running' }) as never - ) - vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({ - id: 'repo::worktree' - } as never) - vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockResolvedValue({ - id: 'repo::worktree' - } as never) - vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - title: 'worker' - }) - vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: options?.ready !== false, - status: 'running', - exitCode: null - }) - vi.mocked(runtime.getTerminalProcessIncarnation).mockImplementation((handle) => - handle === 'term_worker' ? 'runtime_test:term_worker:1' : null - ) - vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ - handle: 'term_worker', - accepted: true, - bytesWritten: 1 - }) - } - - it('rejects a declared caller that disagrees with complete attested evidence', async () => { - setup() - mockCurrentWorkerStart() - vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => - handle === 'term_coord' || handle === 'term_other' - ? coordinatorPaneKey - : handle === 'term_worker' - ? 'tab_worker:leaf_worker' - : null - ) - const attestedEvidence = { - terminalHandle: 'term_attested', - paneKey: 'tab_attested:leaf_attested', - launchToken: 'attested-launch-token' - } as const - vi.spyOn(runtime, 'verifyOrchestrationCompatibilityCaller').mockReturnValue({ - terminalHandle: attestedEvidence.terminalHandle, - paneKey: attestedEvidence.paneKey, - processIncarnation: 'runtime_test:attested:1', - launchTokenHash: 'attested-launch-token-hash', - hostScope: { kind: 'local', hostId: 'local' } - }) - ctx = { ...ctx, orchestrationCompatibilityEvidence: attestedEvidence } - const task = db.createTask({ spec: 'mismatched caller' }) - - await expect( - call('orchestration.workerStart', { - task: task.id, - from: 'term_other', - agent: 'codex' - }) - ).rejects.toMatchObject({ code: 'consumer_fenced' }) - expect(db.getDispatchContext(task.id)).toBeUndefined() - }) - - it('deliberately permits present but unverifiable restored-terminal evidence', async () => { - setup() - mockCurrentWorkerStart() - // Restored/adopted terminals have no launch token; preserve intentional fail-open compatibility. - const task = db.createTask({ spec: 'restored caller limitation' }) - ctx = { - ...ctx, - orchestrationCompatibilityEvidence: { - terminalHandle: 'term_worker', - paneKey: 'tab_worker:leaf_worker' - } - } - - const result = (await call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - })) as { state: string } - - expect(result.state).toBe('ready') - expect(db.getDispatchContext(task.id)).toBeDefined() - }) - - it('creates and binds a Run for an unbound coordinator, then names it on reuse', async () => { - setup(false) - mockCurrentWorkerStart() - const start = () => - call('orchestration.workerStart', { - spec: 'Audit the parser\nCheck every branch.', - from: 'term_coord', - agent: 'codex' - }) - - const first = await start() - const bound = db.getCurrentRunForCoordinator({ - terminalHandle: 'term_coord', - paneKey: coordinatorPaneKey, - orcaSessionId: null - }) - const run = { id: bound?.id, objective: 'Audit the parser' } - expect(first).toMatchObject({ state: 'ready', run: { ...run, created: true } }) - expect(await start()).toMatchObject({ run: { ...run, created: false } }) - }) - - it('puts overlapping first starts from an unbound coordinator in one Run', async () => { - setup(false) - mockCurrentWorkerStart() - // Hold both starts in preflight, then let the second finish first. - const preflights: (() => void)[] = [] - vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockImplementation( - () => - new Promise((resolve) => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preflight reads only the workspace id. - preflights.push(() => resolve({ id: 'repo::worktree' } as never)) - ) - ) - const start = (spec: string) => - call('orchestration.workerStart', { spec, from: 'term_coord', agent: 'codex' }) - - const first = start('Audit the parser') - const second = start('Audit the lexer') - await vi.waitFor(() => expect(preflights).toHaveLength(2)) - preflights[1]() - const secondReceipt = await second - preflights[0]() - const firstReceipt = await first - - const runs = db.listRuns().runs.filter((run) => run.legacy === 0) - expect(runs).toHaveLength(1) - expect(secondReceipt).toMatchObject({ run: { id: runs[0].id, created: true } }) - expect(firstReceipt).toMatchObject({ run: { id: runs[0].id, created: false } }) - }) - - it('creates no Run when an unbound coordinator start fails preflight', async () => { - setup(false) - mockCurrentWorkerStart() - - await expect( - call('orchestration.workerStart', { - spec: 'Audit the parser', - from: 'term_coord', - agent: 'codex', - worktree: 'new-child' - }) - ).rejects.toThrow('repo_not_found') - expect(db.listRuns().runs.filter((run) => run.legacy === 0)).toEqual([]) - }) - - it('commits the launched worker token with its durable authority', async () => { - setup() - mockCurrentWorkerStart() - vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({ - runtimeId: runtime.getRuntimeId(), - terminalHandle: 'term_worker', - ptyId: 'pty_worker', - worktreeId: 'repo::worktree', - paneKey: 'tab_worker:leaf_worker', - processIncarnation: 'runtime_test:term_worker:1', - launchTokenHash: 'worker-launch-token-hash', - hostScope: { kind: 'local', hostId: 'local' } - }) - const task = db.createTask({ spec: 'persist worker identity' }) - - const result = (await call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - })) as { dispatchId: string } - - expect(db.getDispatchContextById(result.dispatchId)?.launch_token_hash).toBe( - 'worker-launch-token-hash' - ) - }) - - it('returns a failed receipt and preserves a created terminal as residual', async () => { - setup() - mockCurrentWorkerStart({ ready: false }) - const task = db.createTask({ spec: 'worker timeout' }) - - const result = (await call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - })) as { state: string; failedStage: string; residualResources: { id: string }[] } - - expect(result).toMatchObject({ state: 'failed', failedStage: 'agent_readiness' }) - expect(result.residualResources).toEqual([expect.objectContaining({ id: 'term_worker' })]) - expect(db.getTask(task.id)?.status).toBe('failed') - expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/finished-report-reply.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/finished-report-reply.test.ts deleted file mode 100644 index 19f206c77c0..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/finished-report-reply.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import { getFollowUpDispatch } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import './worker-resume-session-capture' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -// A coordinator replying to a finished worker's report, through the same calls the CLI makes. -describe('a reply to a finished worker report', () => { - const h = createOrchestrationWorkerReleaseHarness() - - afterEach(() => { - getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() - h.cleanup() - }) - - async function reportDone() { - const { taskId, dispatchId } = await h.startWorker() - await h.call('orchestration.send', { - from: 'term_worker', - type: 'worker_done', - subject: 'Done', - payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded' }) - }) - const report = h.db - .getUnreadMessages(`run:${h.activeRunId}`) - .find((message) => message.type === 'worker_done')! - return { dispatchId, reportId: report.id } - } - - const reply = (id: string) => - h.call('orchestration.reply', { id, from: 'term_coord', body: 'Also fix the docs' }) - - it('is refused without writing anything, and check offers the send that continues the worker', async () => { - h.setup() - const { dispatchId, reportId } = await reportDone() - - await expect(reply(reportId)).rejects.toMatchObject({ - code: 'dispatch_inactive', - data: { effectsApplied: false, followUp: { kind: 'send', dispatchId, active: false } } - }) - expect(h.db.getMessageById(reportId)?.read).toBe(0) - expect(h.db.getAllMessagesForHandle('term_worker')).toHaveLength(0) - expect(h.db.getAllMessagesForHandle(`dispatch:${dispatchId}`)).toHaveLength(0) - - expect(await h.call('orchestration.check', { terminal: 'term_coord' })).toMatchObject({ - messages: [{ id: reportId, follow_up: { kind: 'send', dispatchId, active: false } }] - }) - }) - - it('never lands in a later task on the same terminal, and names that running follow-up', async () => { - h.setup() - const { dispatchId, reportId } = await reportDone() - await h.call('orchestration.send', { - from: 'term_coord', - to: `dispatch:${dispatchId}`, - subject: 'Next task', - body: 'unrelated work' - }) - const followUp = getFollowUpDispatch(h.db, dispatchId)! - expect(followUp.status).toBe('dispatched') - const before = h.db.getAllMessagesForHandle(`dispatch:${followUp.id}`).length - - await expect(reply(reportId)).rejects.toMatchObject({ - code: 'dispatch_inactive', - data: { followUp: { kind: 'send', dispatchId: followUp.id, active: true } } - }) - expect(h.db.getAllMessagesForHandle(`dispatch:${followUp.id}`)).toHaveLength(before) - expect(h.db.getAllMessagesForHandle('term_worker')).toHaveLength(0) - }) - - it('refuses another message type to a finished worker by naming the continuing send, not a Run', async () => { - h.setup() - const { dispatchId } = await reportDone() - - const refused: unknown = await h - .call('orchestration.send', { - from: 'term_coord', - to: `dispatch:${dispatchId}`, - type: 'escalation', - subject: 'Look again' - }) - .catch((error: unknown) => error) - - expect(refused).toMatchObject({ - code: 'dispatch_inactive', - message: expect.not.stringContaining(`run:${h.activeRunId}`), - data: { followUp: { kind: 'send', dispatchId, active: false } } - }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-cursor.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-cursor.ts similarity index 96% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-list-cursor.ts rename to src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-cursor.ts index 74d0d23180c..acb9b876b91 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-cursor.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-cursor.ts @@ -1,4 +1,4 @@ -import type { WorkerTerminalListState } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import type { WorkerTerminalListState } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' /** Order by databaseId; keep createdAt/dispatchId so older peers can decode new cursors. */ type WorkerListCursorAfter = { createdAt: string; dispatchId: string; databaseId?: number } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-pagination.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-pagination.test.ts new file mode 100644 index 00000000000..9c19dc28e28 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-pagination.test.ts @@ -0,0 +1,294 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type Database from '../../../../../../sqlite/sync-database' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' +import type { FederatedDispatchRow } from '../../../../../orchestration/db/orchestration-records' +import { OrcaRuntimeService } from '../../../../../orca-runtime' +import { encodeWorkerListCursor } from './worker-list-cursor' +import { ORCHESTRATION_WORKER_LIST_METHOD } from '../worker-list-method' + +type WorkerListResult = { + workers: { + dispatchId: string + projection: { attention: { categories: string[] } } + }[] + counts: Record + page: { total: number; hasMore: boolean; nextCursor: string | null } + warnings?: string[] +} + +describe('orchestration worker-list pagination', () => { + let db: OrchestrationDb | undefined + + afterEach(() => db?.close()) + + it('opens on the newest Dispatches, warns that the page truncated, and pages down', async () => { + db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + const run = db.createRun({ + objective: 'Newest-first worker inventory', + coordinatorHandle: 'term-coordinator', + coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + const id = (index: number): string => `dispatch-${String(index).padStart(3, '0')}` + for (let index = 1; index <= 105; index += 1) { + insertDispatch(db, run.id, id(index)) + } + + const first = await callWorkerList(runtime, { run: run.id, paginate: true }) + + expect(first.workers.map((worker) => worker.dispatchId)).toEqual( + Array.from({ length: 100 }, (_, offset) => id(105 - offset)) + ) + expect(first.page).toMatchObject({ total: 105, hasMore: true }) + expect(first.warnings).toEqual([ + 'Showing 100 of 105 Dispatches, newest first; more are on later pages. Follow page.nextCursor with --cursor.' + ]) + expect(first.counts).toEqual({ retained: 105 }) + + insertDispatch(db, run.id, 'dispatch-after-first-call') + const second = await callWorkerList(runtime, { + run: run.id, + paginate: true, + cursor: first.page.nextCursor + }) + + expect(second.workers.map((worker) => worker.dispatchId)).toEqual([5, 4, 3, 2, 1].map(id)) + expect(second.page).toEqual({ total: 105, limit: 100, hasMore: false, nextCursor: null }) + expect(second.warnings).toBeUndefined() + expect(second.counts).toEqual({ retained: 105 }) + }) + + it('keeps filtered snapshot membership when a later worker changes state', async () => { + db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + const run = db.createRun({ + objective: 'Stable filtered inventory', + coordinatorHandle: 'term-coordinator', + coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + insertDispatch(db, run.id, 'dispatch-a') + insertDispatch(db, run.id, 'dispatch-z') + + const first = await callWorkerList(runtime, { + run: run.id, + terminalState: 'retained', + limit: 1 + }) + expect(first.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-z']) + expect(first.page).toMatchObject({ total: 2, hasMore: true }) + + sqliteFor(db) + .prepare('UPDATE dispatch_contexts SET assignee_handle = NULL WHERE id = ?') + .run('dispatch-a') + const second = await callWorkerList(runtime, { + run: run.id, + terminalState: 'retained', + limit: 1, + cursor: first.page.nextCursor + }) + + expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) + expect(second.page).toEqual({ total: 2, limit: 1, hasMore: false, nextCursor: null }) + // The pinned total and the counts have to describe the same rows. + expect(second.counts).toEqual({ retained: second.page.total }) + }) + + it('keeps an include-remote filtered page pinned across 32 concurrent snapshot allocations', async () => { + db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + const run = db.createRun({ + objective: 'Pinned filtered inventory', + coordinatorHandle: 'term-coordinator', + coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + insertDispatch(db, run.id, 'dispatch-a') + insertDispatch(db, run.id, 'dispatch-z') + vi.spyOn(db, 'listFederatedDispatchesByIds').mockImplementation((dispatchIds) => + dispatchIds.includes('dispatch-z') ? [federatedDispatch('dispatch-z')] : [] + ) + vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({ + environmentId: 'environment-remote', + name: 'remote', + peerFingerprint: 'peer-remote', + pairingRevision: 1 + }) + let resolveSnapshot!: () => void + const snapshotGate = new Promise((resolve) => { + resolveSnapshot = resolve + }) + const remoteCall = vi + .spyOn(runtime, 'callOrchestrationWorkerServer') + .mockImplementation(async () => { + await snapshotGate + return { + runtimeEpoch: 'epoch-remote', + items: [ + { + dispatchId: 'dispatch-z', + observation: { status: 'live', exactWorker: true } + } + ] + } + }) + + const pending = callWorkerList(runtime, { + run: run.id, + terminalState: 'retained', + includeRemote: true, + limit: 1 + }) + await vi.waitFor(() => + expect(remoteCall).toHaveBeenCalledWith( + 'environment-remote', + 'orchestration.federationFleetSnapshot', + { dispatchIds: ['dispatch-z'] }, + expect.any(Number), + undefined, + { expectedEnvironmentPairingRevision: 1 } + ) + ) + for (let call = 0; call < 32; call += 1) { + await callWorkerList(runtime, { run: run.id, terminalState: 'retained', limit: 1 }) + } + resolveSnapshot() + + const first = await pending + expect(first).toMatchObject({ + workers: [{ dispatchId: 'dispatch-z' }], + page: { total: 2, hasMore: true, nextCursor: expect.any(String) } + }) + const second = await callWorkerList(runtime, { + run: run.id, + terminalState: 'retained', + limit: 1, + cursor: first.page.nextCursor + }) + expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) + }) + + it('never re-emits a row whose worker registers between pages', async () => { + db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + const run = db.createRun({ + objective: 'Stable order key', + coordinatorHandle: 'term-coordinator', + coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + insertDispatch(db, run.id, 'dispatch-a') + insertDispatch(db, run.id, 'dispatch-z') + + const seen: string[] = [] + let cursor: string | null = null + for (let page = 0; page < 5; page += 1) { + const result: WorkerListResult = await callWorkerList(runtime, { + run: run.id, + limit: 1, + ...(cursor ? { cursor } : {}) + }) + seen.push(...result.workers.map((worker) => worker.dispatchId)) + if (page === 0) { + // A worker row lands for the page-1 row; its COALESCE(created_at) sort key moves forward. + sqliteFor(db) + .prepare( + `INSERT INTO worker_dispatches (dispatch_id, state, stage, agent_terminal_handle, created_at) + VALUES (?, 'ready', 'ready', ?, '2026-08-27 01:00:00')` + ) + .run('dispatch-a', 'term-dispatch-a') + } + cursor = result.page.nextCursor + if (!cursor) { + break + } + } + + expect(seen).toEqual(['dispatch-z', 'dispatch-a']) + }) + + describe('a legacy cursor anchored outside the requested Run', () => { + function twoRuns(): { runA: string; runB: string } { + db = new OrchestrationDb(':memory:') + const runA = db.createRun({ + objective: 'A', + coordinatorHandle: 'term-a', + coordinatorPaneKey: 'tab-a:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + const runB = db.createRun({ + objective: 'B', + coordinatorHandle: 'term-b', + coordinatorPaneKey: 'tab-b:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + }) + insertDispatch(db, runA.id, 'a-1') + insertDispatch(db, runA.id, 'a-2') + insertDispatch(db, runB.id, 'b-1') + insertDispatch(db, runB.id, 'b-2') + return { runA: runA.id, runB: runB.id } + } + + // Both shapes used to resolve to a rowid past Run A's rows and report a finished, empty page. + + it('expires a v2 cursor that carries a foreign rowid', async () => { + const { runA } = twoRuns() + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db!) + const foreign = encodeWorkerListCursor({ + version: 2, + snapshot: { databaseId: 4 }, + after: { createdAt: '2026-08-27 00:00:00', dispatchId: 'b-1', databaseId: 3 } + }) + + await expect( + callWorkerList(runtime, { run: runA, limit: 10, cursor: foreign }) + ).rejects.toThrow(/changed destructively/u) + }) + }) +}) + +async function callWorkerList( + runtime: OrcaRuntimeService, + params: Record +): Promise { + const parsed = ORCHESTRATION_WORKER_LIST_METHOD.params?.parse(params) + return (await ORCHESTRATION_WORKER_LIST_METHOD.handler(parsed, { runtime })) as WorkerListResult +} + +function insertDispatch(db: OrchestrationDb, runId: string, dispatchId: string): void { + const task = db.createTask({ spec: dispatchId, runId }) + sqliteFor(db) + .prepare( + `INSERT INTO dispatch_contexts ( + id, run_id, task_id, assignee_handle, status, created_at + ) VALUES (?, ?, ?, ?, 'dispatched', '2026-08-27 00:00:00')` + ) + .run(dispatchId, runId, task.id, `term-${dispatchId}`) +} + +function sqliteFor(db: OrchestrationDb): Database.Database { + return (db as unknown as { db: Database.Database }).db +} + +function federatedDispatch(dispatchId: string): FederatedDispatchRow { + return { + dispatch_id: dispatchId, + environment_id: 'environment-remote', + environment_name: 'remote', + peer_fingerprint: 'peer-remote', + remote_runtime_epoch: 'epoch-remote', + protocol_version: 3, + remote_worktree_id: null, + remote_terminal_handle: null, + to_home_imported_sequence: 0, + to_home_acknowledged_sequence: 0, + home_auto_release_at: null, + home_auto_release_state: null, + created_at: '2026-08-27 00:00:00', + updated_at: '2026-08-27 00:00:00' + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-projection.ts similarity index 84% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts rename to src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-projection.ts index df87127d9ca..e0dd2bc8698 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-projection.ts @@ -2,20 +2,20 @@ import { ORCHESTRATION_FLEET_PAGE_MAX, projectOrchestrationFleet, type FleetDurableWorker -} from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' -import { resolveFleetWorkerOutcome } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-outcome-resolution' +} from '../../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import { resolveFleetWorkerOutcome } from '../../../../../../../shared/orchestration/fleet/orchestration-fleet-outcome-resolution' import { liveWorkerTerminalAutoReleaseAt, type WorkerTerminalListState -} from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { createSessionWorkerLivenessReader } from '../../../../orchestration/workers/lifecycle/session-worker-liveness' +} from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { createSessionWorkerLivenessReader } from '../../../../../orchestration/workers/lifecycle/session-worker-liveness' import { applyFederatedFleetObservations, readFederatedFleetSnapshots -} from '../../../../orchestration/legacy-remote-home/federated-fleet-snapshot' -import { ensureSessionWorkerRecords } from './session-worker-observation' +} from '../../../../../orchestration/legacy-remote-home/federated-fleet-snapshot' +import { ensureSessionWorkerRecords } from '../observation/session-worker-observation' export type WorkerListPageParams = { run?: string diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-run-scope-rpc.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-run-scope-rpc.spec.ts similarity index 97% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-list-run-scope-rpc.spec.ts rename to src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-run-scope-rpc.spec.ts index 1959fcc6827..eec9aba7f51 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-run-scope-rpc.spec.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-run-scope-rpc.spec.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +import { createRootDispatch } from '../../../../../orchestration/db/root-dispatch-test-fixture' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' export function registerWorkerListRunScopeRpcTests(): void { type WorkerListReceipt = { workers: { dispatchId: string; runId: string }[] } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-snapshot-store.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-snapshot-store.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-list-snapshot-store.ts rename to src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-snapshot-store.ts index 14be184c4d2..85e3997791d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-snapshot-store.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-snapshot-store.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' -import { BoundedMap } from '../../../../../../shared/bounded-map' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { WorkerTerminalListState } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { BoundedMap } from '../../../../../../../shared/bounded-map' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import type { WorkerTerminalListState } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' export const ORCHESTRATION_WORKER_LIST_SNAPSHOT_MAX_ROWS = 5_000 const ORCHESTRATION_WORKER_LIST_SNAPSHOT_MAX_ENTRIES = 32 diff --git a/src/main/runtime/rpc/methods/orchestration/worker/folder-worktree-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/folder-worktree-placement.ts deleted file mode 100644 index b898b6cfd59..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/folder-worktree-placement.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { isFolderRepo } from '../../../../../../shared/repo-kind' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' - -export async function assertOrchestrationWorktreeCreationSupported(args: { - runtime: OrcaRuntimeService - repoSelector: string - existingPlacement: string -}): Promise { - if (!isFolderRepo(await args.runtime.showRepo(args.repoSelector))) { - return - } - throw new OrchestrationError( - 'invalid_argument', - `Folder projects cannot create orchestration worktrees; use ${args.existingPlacement}.` - ) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts new file mode 100644 index 00000000000..06845a04bb9 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../../../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import { useHelperFollowUpCli } from '../testing/helper-follow-up-cli.test-support' + +const CONVERSATION = { key: 'session_id', id: 'fixture-conversation' } as const +const REOPENED_PANE = 'tab_reopened:leaf' + +describe('opening a terminal worker Orca closed', () => { + const { h, panes, pair, success } = useHelperFollowUpCli() + + /** A finished helper whose pane recorded `conversation`, then closed by Orca. */ + async function closedHelper(recorded = true) { + const { helper } = await pair() + if (recorded) { + vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ + paneKey: panes.get('term_helper')!, + agent: 'claude', + processIncarnation: 'process:term_helper', + providerSession: CONVERSATION, + observedAt: 1 + }) + } + await success('worker-release', '--dispatch', helper.dispatchId) + const live = new Set() + let hookRows: AgentStatusIpcPayload[] = [] + Object.defineProperty(h.runtime, 'getAgentStatusSnapshotFn', { + configurable: true, + value: () => hookRows + }) + vi.spyOn(h.runtime, 'getTerminalHandleForPaneKey').mockImplementation((paneKey) => + paneKey === REOPENED_PANE && live.has('term_reopened') ? 'term_reopened' : null + ) + vi.spyOn(h.runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => + live.has(handle) ? REOPENED_PANE : null + ) + vi.spyOn(h.runtime, 'isTerminalRunningAgent').mockImplementation(async (handle) => + live.has(handle) + ) + const resume = vi + .spyOn(h.runtime, 'resumeAgentSessionInWorkspace') + .mockImplementation(async () => { + live.add('term_reopened') + return { ok: true, handle: 'term_reopened', paneKey: REOPENED_PANE, ptyId: 'pty' } + }) + /** The reopened pane's agent reports its conversation. */ + const report = (row: Pick) => { + hookRows = [ + { + state: 'working', + prompt: '', + paneKey: REOPENED_PANE, + connectionId: null, + receivedAt: 1, + stateStartedAt: 1, + ...row + } + ] + } + const resource = h.db.getWorkerTerminalResourceByOwner(helper.dispatchId)! + return { helper, resource, resume, report } + } + + const open = (address: string) => h.call('orchestration.partyOpen', { address }) + + it('forgets an uncertain request once its conversation reports, so a later resume is a new one', async () => { + const { resource, resume, report } = await closedHelper() + const succeed = resume.getMockImplementation()! + resume.mockImplementationOnce(async (...args) => { + await succeed(...args) + return { ok: false, reason: 'create_failed' } + }) + await expect(open(resource.terminal_handle)).rejects.toThrow() + report({ agentType: 'claude', providerSession: CONVERSATION }) + expect(await open(resource.terminal_handle)).toEqual({ + location: { kind: 'terminal', handle: 'term_reopened' } + }) + vi.mocked(h.runtime.isTerminalRunningAgent).mockResolvedValue(false) + await open(resource.terminal_handle) + const [uncertainId, later] = resume.mock.calls.map(([, request]) => request.mutationId) + expect(resume).toHaveBeenCalledTimes(2) + expect(later).not.toBe(uncertainId) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/closed-worker-terminal.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.ts similarity index 81% rename from src/main/runtime/rpc/methods/orchestration/worker/closed-worker-terminal.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.ts index 308a28e2f8b..3857fef56e8 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/closed-worker-terminal.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.ts @@ -1,11 +1,11 @@ /** A terminal worker Orca closed keeps its conversation; resume it in a terminal of the user's so any client can open it. */ import { randomUUID } from 'node:crypto' -import { isResumableTuiAgent } from '../../../../../../shared/agent-session/lifecycle/agent-session-resume' -import type { OrchestrationPartyLocation } from '../../../../../../shared/orchestration/orchestration-caller-status' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { readWorkerResumeSession } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { isResumableTuiAgent } from '../../../../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { OrchestrationPartyLocation } from '../../../../../../../shared/orchestration/orchestration-caller-status' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { readWorkerResumeSession } from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' import { userTabHoldingSession } from './worker-follow-up-choice' import { reopenWorkerTerminal } from './worker-follow-up-placement' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/finished-report-reply.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/finished-report-reply.test.ts new file mode 100644 index 00000000000..f5ac3f86f43 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/finished-report-reply.test.ts @@ -0,0 +1,53 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { getFollowUpDispatch } from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import './worker-resume-session-capture' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' + +// A coordinator replying to a finished worker's report, through the same calls the CLI makes. +describe('a reply to a finished worker report', () => { + const h = createOrchestrationWorkerReleaseHarness() + + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() + h.cleanup() + }) + + async function reportDone() { + const { taskId, dispatchId } = await h.startWorker() + await h.call('orchestration.send', { + from: 'term_worker', + type: 'worker_done', + subject: 'Done', + payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded' }) + }) + const report = h.db + .getUnreadMessages(`run:${h.activeRunId}`) + .find((message) => message.type === 'worker_done')! + return { dispatchId, reportId: report.id } + } + + const reply = (id: string) => + h.call('orchestration.reply', { id, from: 'term_coord', body: 'Also fix the docs' }) + + it('never lands in a later task on the same terminal, and names that running follow-up', async () => { + h.setup() + const { dispatchId, reportId } = await reportDone() + await h.call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + subject: 'Next task', + body: 'unrelated work' + }) + const followUp = getFollowUpDispatch(h.db, dispatchId)! + expect(followUp.status).toBe('dispatched') + const before = h.db.getAllMessagesForHandle(`dispatch:${followUp.id}`).length + + await expect(reply(reportId)).rejects.toMatchObject({ + code: 'dispatch_inactive', + data: { followUp: { kind: 'send', dispatchId: followUp.id, active: true } } + }) + expect(h.db.getAllMessagesForHandle(`dispatch:${followUp.id}`)).toHaveLength(before) + expect(h.db.getAllMessagesForHandle('term_worker')).toHaveLength(0) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-ownership-cli.integration.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/helper-follow-up-ownership-cli.integration.test.ts similarity index 96% rename from src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-ownership-cli.integration.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/helper-follow-up-ownership-cli.integration.test.ts index 46a305dcc90..4f8854b37de 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-ownership-cli.integration.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/helper-follow-up-ownership-cli.integration.test.ts @@ -1,10 +1,14 @@ import { describe, expect, it, vi } from 'vitest' -import { getFollowUpDispatch } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import { continueAllUnreadWorkerMail } from '../messaging/settled-worker-follow-through' +import { getFollowUpDispatch } from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { continueAllUnreadWorkerMail } from '../../messaging/settled-worker-follow-through' import { z } from 'zod' -import * as setupGate from './worker-start-structured-setup-gate' -import { receipt, type Started, useHelperFollowUpCli } from './helper-follow-up-cli.test-support' -import { traceDispatchProbes } from './helper-follow-up-sql-trace.test-support' +import * as setupGate from '../start/readiness/worker-start-structured-setup-gate' +import { + receipt, + type Started, + useHelperFollowUpCli +} from '../testing/helper-follow-up-cli.test-support' +import { traceDispatchProbes } from './testing/helper-follow-up-sql-trace.test-support' const failedReceipt = z.object({ taskId: z.string(), diff --git a/src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-sql-trace.test-support.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/testing/helper-follow-up-sql-trace.test-support.ts similarity index 95% rename from src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-sql-trace.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/testing/helper-follow-up-sql-trace.test-support.ts index 829da7178b9..1c7788ee0c8 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-sql-trace.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/testing/helper-follow-up-sql-trace.test-support.ts @@ -1,7 +1,7 @@ import { expect, vi } from 'vitest' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { SqliteBindings, SqliteRow } from '../../../../../sqlite/sqlite-statement' -import { installSqlVisitCounters } from '../../../../orchestration/db/dispatch-predicate-visits.test-fixture' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import type { SqliteBindings, SqliteRow } from '../../../../../../../sqlite/sqlite-statement' +import { installSqlVisitCounters } from '../../../../../../orchestration/db/dispatch-predicate-visits.test-fixture' const CALLER_READ_NAMES = ['identity', 'formerOwner'] as const type CallerRead = (typeof CALLER_READ_NAMES)[number] diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-earlier-work.ts similarity index 87% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-earlier-work.ts index 8838adeecbd..048d2d07716 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-earlier-work.ts @@ -1,7 +1,7 @@ import { z } from 'zod' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' -import type { DispatchContextRow } from '../../../../orchestration/db/orchestration-records' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { isTuiAgent } from '../../../../../../../shared/agent-launch/catalog/tui-agent-config' +import type { DispatchContextRow } from '../../../../../orchestration/db/orchestration-records' const EARLIER_WORK_CLIP = 2_000 diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-admission.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-admission.ts similarity index 86% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-admission.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-admission.ts index cdbb88473bd..870d87302ab 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-admission.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-admission.ts @@ -1,13 +1,13 @@ -import type { OrchestrationAdmission } from '../../../../orchestration/addressing/orchestration-admission' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { createDispatchCreatorEvaluation } from '../../../../orchestration/db/dispatch-creator-evaluation' -import { selectWorkerFollowUpPlan } from '../../../../orchestration/db/dispatch-context/worker-follow-up-plan' -import { existingWorkerStartRunAdmission } from './worker-start-run-authority' +import type { OrchestrationAdmission } from '../../../../../orchestration/addressing/orchestration-admission' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import type { createDispatchCreatorEvaluation } from '../../../../../orchestration/db/dispatch-creator-evaluation' +import { selectWorkerFollowUpPlan } from '../../../../../orchestration/db/dispatch-context/worker-follow-up-plan' +import { existingWorkerStartRunAdmission } from '../start/admission/worker-start-run-authority' import { createHelperStartScope, type HelperDispatch, type HelperReaders -} from './helper-start-scope' +} from '../start/admission/helper-start-scope' export function planSemanticWorkerFollowUp< D extends { id: string; status: string; follow_up_of_dispatch_id: string | null }, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-choice.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-choice.ts index 81b8c8d3e42..7f9666bee64 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-choice.ts @@ -2,30 +2,28 @@ * conversation once closed, or a fresh agent of the same kind. Effect-free except closing a pane Orca owns * whose agent is proven gone, so the replacement never sits beside it. */ -import { - agentProviderSessionsEqual, - isResumableTuiAgent -} from '../../../../../../shared/agent-session/lifecycle/agent-session-resume' -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { isResumableTuiAgent } from '../../../../../../../shared/agent-session/lifecycle/agent-session-resume' +import { agentProviderSessionsEqual } from '../../../../../../../shared/agent-session/lifecycle/agent-provider-session-equality' +import { isStructuredWorkerHandle } from '../../../../../../../shared/orchestration/workers/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import { readWorkerResumeSession, type WorkerResumeSession -} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { DispatchContextRow } from '../../../../orchestration/db/orchestration-records' -import type { WorkerTerminalResourceRow } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { resolveStructuredWorkerIdentity } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' +} from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import type { DispatchContextRow } from '../../../../../orchestration/db/orchestration-records' +import type { WorkerTerminalResourceRow } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { getStructuredAgentSessionHost } from '../../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { resolveStructuredWorkerIdentity } from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import { earlierWork, parseStartOptions } from './worker-earlier-work' import { reopenWorkerChat, reopenWorkerTerminal, type WorkerFollowUp } from './worker-follow-up-placement' -import { inspectWorkerTerminal } from './worker-observation' -import { completeWorkerTerminalRelease } from './worker-release-completion' +import { inspectWorkerTerminal } from '../observation/worker-observation' +import { completeWorkerTerminalRelease } from '../release/worker-release-completion' const RELEASE_SETTLE_WAIT_MS = 15_000 diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts index 606dabfc297..d2b869979d6 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts @@ -1,17 +1,17 @@ -import { resolveResumeLaunchRecipe } from '../../../../../../shared/agent-launch/choices/resume-launch-recipe' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrchestrationPartyIdentity as OrchestrationParty } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' -import { CHAT_WORKER_AUTHORITY } from '../chat-assignee-admission' -import type { WorkerResumeSession } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { resolveResumeLaunchRecipe } from '../../../../../../../shared/agent-launch/choices/resume-launch-recipe' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import type { OrchestrationPartyIdentity as OrchestrationParty } from '../../../../../../../shared/orchestration/mailbox/orchestration-party-identity' +import { CHAT_WORKER_AUTHORITY } from '../../chat-assignee-admission' +import type { WorkerResumeSession } from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { getStructuredAgentSessionHost } from '../../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { resolveStructuredWorkerIdentity, structuredWorkerSession -} from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' +} from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import type { WorkerFollowUpPlacement } from './worker-follow-up-choice' -import { publishChatTabInBackground } from '../../../../session-tabs/background-chat-tab-publication' +import { publishChatTabInBackground } from '../../../../../session-tabs/background-chat-tab-publication' /** What a follow-up continues, and for a closed worker how it comes back once the follow-up holds its Dispatch. */ export type WorkerFollowUp = { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up.test.ts new file mode 100644 index 00000000000..595b4bcb0fe --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up.test.ts @@ -0,0 +1,87 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { getFollowUpDispatch } from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import './worker-resume-session-capture' +import { continueAllUnreadWorkerMail } from '../../messaging/settled-worker-follow-through' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' + +// A send to a finished terminal worker, through the same worker-start the coordinator would run. +describe('a follow-up to a finished terminal worker', () => { + const h = createOrchestrationWorkerReleaseHarness() + let userDataDir: string | undefined + + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() + h.cleanup() + if (userDataDir) { + rmSync(userDataDir, { recursive: true, force: true }) + userDataDir = undefined + } + }) + + const send = (dispatchId: string, body: string) => + h.call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + subject: 'More', + body + }) + + it('retries a follow-up a restart interrupted before it placed an agent, with the mail it took', async () => { + userDataDir = mkdtempSync(join(tmpdir(), 'orca-follow-up-midstart-')) + h.setup({ userDataDir }) + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + // The claim commits; the app quits before the start places an agent. + const claimed = h.db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: 9, + taskSpec: 'New messages', + taskRunId: h.activeRunId, + startOptions: { agent: 'codex' }, + runtimeEpoch: 'runtime_before_restart', + followUpOf: dispatchId, + takesMailOf: dispatchId + }).dispatch.id + + h.restart() + + await vi.waitFor(() => expect(getFollowUpDispatch(h.db, claimed)).toBeDefined()) + const retry = getFollowUpDispatch(h.db, claimed)! + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${retry.id}`)).toMatchObject([ + { body: 'DO NOT PUSH' } + ]) + ) + }) + + it('keeps the mail a stopped follow-up never read for the next send, without restarting it', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + continueAllUnreadWorkerMail(h.runtime, h.db) + await vi.waitFor(() => + expect(h.db.getWorkerDispatch(getFollowUpDispatch(h.db, dispatchId)?.id ?? '')?.state).toBe( + 'ready' + ) + ) + const stopped = getFollowUpDispatch(h.db, dispatchId)!.id + h.db.beginWorkerStop(stopped, h.runtime.getRuntimeId()) + h.db.settleWorkerStop(stopped) + + continueAllUnreadWorkerMail(h.runtime, h.db) + expect(getFollowUpDispatch(h.db, stopped)).toBeUndefined() + + await send(dispatchId, 'and the docs') + const next = getFollowUpDispatch(h.db, stopped)! + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${next.id}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + ) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-resume-session-capture.ts similarity index 79% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts rename to src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-resume-session-capture.ts index 4ebd0e2b723..4c36edbce81 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-resume-session-capture.ts @@ -1,12 +1,12 @@ -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { isStructuredWorkerHandle } from '../../../../../../../shared/orchestration/workers/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import { findHeldWorkerResourceForPane, recordWorkerResumeSession -} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import type { WorkerTerminalResourceRow } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import { orchestrationTimestampToMs } from './worker-output' +} from '../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import type { WorkerTerminalResourceRow } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { orchestrationTimestampToMs } from '../output/worker-output' /** Save the terminal agent's conversation while its hook rows still name it: at its report, and before stop or release closes it. */ export function captureWorkerResumeSession( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts deleted file mode 100644 index 8c43a03382b..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' -import { isStreamingMethod, eraseRpcMethods } from '../../../core' - -describe('manual Dispatch observation', () => { - let db: OrchestrationDb | undefined - - afterEach(() => db?.close()) - - it('covers the real dispatch --inject entry path before observing the lane', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const coordinatorPaneKey = 'tab_coord:leaf_coord' - const workerPaneKey = 'tab_worker:leaf_worker' - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' ? coordinatorPaneKey : workerPaneKey - ) - // Authority is per handle in the real runtime; a flat mock would give the coordinator the worker's pane. - vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - ({ - terminalHandle: handle, - paneKey: handle === 'term_coord' ? coordinatorPaneKey : workerPaneKey, - processIncarnation: - handle === 'term_coord' ? 'runtime_test:term_coord:1' : 'runtime_test:term_worker:1' - }) as never - ) - vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ - handle: 'term_worker', - accepted: true, - bytesWritten: 1 - }) - vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ - handle: 'term_worker', - connected: true, - status: 'running' - } as never) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('runtime_test:term_worker:1') - vi.spyOn(runtime, 'getTerminalLivenessVerdict').mockReturnValue({ - status: 'live', - ptyIds: ['runtime_test:term_worker:1'] - }) - vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - const run = db.createRun({ - objective: 'STA-3848 repro', - coordinatorHandle: 'term_coord', - coordinatorPaneKey - }) - const task = db.createTask({ spec: 'injected lane', runId: run.id }) - const dispatchMethod = eraseRpcMethods(ORCHESTRATION_METHODS).find( - (candidate) => candidate.name === 'orchestration.dispatch' - ) - if (!dispatchMethod || isStreamingMethod(dispatchMethod)) { - throw new Error('Missing method orchestration.dispatch') - } - - const result = (await dispatchMethod.handler( - dispatchMethod.params?.parse({ - task: task.id, - to: 'term_worker', - from: 'term_coord', - run: run.id, - inject: true - }), - { runtime, legacyCoordinatorRunId: run.id } - )) as { dispatch: { id: string } } - - expect(db.getWorkerDispatch(result.dispatch.id)).toBeUndefined() - expect(db.getDispatchContextById(result.dispatch.id)).toMatchObject({ - assignee_handle: 'term_worker', - assignee_pane_key: workerPaneKey, - process_incarnation: 'runtime_test:term_worker:1' - }) - - const workerShowMethod = eraseRpcMethods(ORCHESTRATION_METHODS).find( - (candidate) => candidate.name === 'orchestration.workerShow' - ) - if (!workerShowMethod || isStreamingMethod(workerShowMethod)) { - throw new Error('Missing method orchestration.workerShow') - } - await expect( - workerShowMethod.handler(workerShowMethod.params?.parse({ dispatch: result.dispatch.id }), { - runtime - }) - ).resolves.toMatchObject({ - worker: { state: 'unsupervised', stage: 'context_only' }, - observation: { status: 'live', exactWorker: true } - }) - }) - - it.each([ - ['orchestration.workerStop', 'stopped'], - ['orchestration.workerAbandon', 'abandoned'] - ] as const)('%s fences the assignment without closing the operator pane', async (name, state) => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const closeTerminal = vi.spyOn(runtime, 'closeTerminal') - const task = db.createTask({ - runId: 'run_legacy_local', - spec: 'operator-owned lane' - }) - const dispatch = createRootDispatch( - db, - task.id, - 'term_worker', - 'tab_worker:leaf_worker', - 'launch-hash', - 'runtime_test:term_worker:1' - ) - const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( - (candidate) => candidate.name === name - ) - - if (!method || isStreamingMethod(method)) { - throw new Error(`Missing method ${name}`) - } - const result = await method.handler(method.params?.parse({ dispatch: dispatch.id }), { - runtime - }) - - expect(result).toMatchObject({ state, processAction: 'none' }) - expect(closeTerminal).not.toHaveBeenCalled() - expect(db.getWorkerDispatch(dispatch.id)).toBeUndefined() - expect(db.getDispatchContextById(dispatch.id)).toMatchObject({ - status: 'failed', - last_failure: state - }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts b/src/main/runtime/rpc/methods/orchestration/worker/observation/dispatch-context-exposure.ts similarity index 89% rename from src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts rename to src/main/runtime/rpc/methods/orchestration/worker/observation/dispatch-context-exposure.ts index c89bedef546..989d3892c53 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/observation/dispatch-context-exposure.ts @@ -1,5 +1,5 @@ -import { parseWorkerTerminalHostScope } from '../../../../../../shared/orchestration/workers/worker-terminal-host-scope' -import type { DispatchContextRow } from '../../../../orchestration/db/orchestration-records' +import { parseWorkerTerminalHostScope } from '../../../../../../../shared/orchestration/workers/worker-terminal-host-scope' +import type { DispatchContextRow } from '../../../../../orchestration/db/orchestration-records' // Hide authority hashes and decode host_scope; emit one camelCase shape matching exposeWorker. export function exposeDispatchContext(dispatch: DispatchContextRow) { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/observation/fleet-status-observed-identity.test.ts similarity index 78% rename from src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/observation/fleet-status-observed-identity.test.ts index ae80a2162bc..a2e81f96e67 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/observation/fleet-status-observed-identity.test.ts @@ -1,19 +1,19 @@ import { describe, expect, it } from 'vitest' -import type { AgentStatusOrchestrationContext } from '../../../../../../shared/agent-status/contracts/agent-status-types' +import type { AgentStatusOrchestrationContext } from '../../../../../../../shared/agent-status/contracts/agent-status-types' -import { AgentHookServer } from '../../../../../agent-hooks/server/agent-hook-server' +import { AgentHookServer } from '../../../../../../agent-hooks/server/agent-hook-server' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' -import { OrcaRuntimeWithGetOrchestrationDispatchAuthority } from '../../../../terminal/output/terminal-orchestration-authority' +import { OrcaRuntimeWithGetOrchestrationDispatchAuthority } from '../../../../../terminal/output/terminal-orchestration-authority' import { AgentStatusObservedPaneIdentities, recordObservedAgentStatusPaneIdentity -} from '../../../../terminal/identity/agent-status-observed-pane-identity' +} from '../../../../../terminal/identity/agent-status-observed-pane-identity' import { projectFleetWorkerPage } from './worker-observation' @@ -156,51 +156,6 @@ describe('fleet evidence keeps the identity it was observed under', () => { ).toMatchObject({ verdict: 'unverifiable', reason: 'missing_status' }) }) - it('refuses the same row for a dispatch that took the pane over afterwards', () => { - const world = createWorld() - world.bindPane(PANE_KEY, TERMINAL_HANDLE) - world.runProcess(TERMINAL_HANDLE, INCARNATION_ONE) - world.dispatchPane(PANE_KEY, DISPATCH_OLD) - world.ingest(PANE_KEY, 'working') - world.dispatchPane(PANE_KEY, DISPATCH_NEW) - - expect( - livenessOf( - world, - createDb({ - dispatchId: DISPATCH_NEW, - paneKey: PANE_KEY, - handle: TERMINAL_HANDLE, - incarnation: INCARNATION_ONE - }), - DISPATCH_NEW - ) - ).toMatchObject({ verdict: 'unverifiable', reason: 'missing_status' }) - }) - - it('refuses the same row after a remint when no resource names an incarnation', () => { - const world = createWorld() - world.bindPane(PANE_KEY, TERMINAL_HANDLE) - world.runProcess(TERMINAL_HANDLE, INCARNATION_ONE) - world.dispatchPane(PANE_KEY, DISPATCH_OLD) - world.ingest(PANE_KEY, 'working') - world.runProcess(TERMINAL_HANDLE, INCARNATION_TWO) - - // Unsupervised workers lack durable resources to contradict a wrongly minted incarnation. - expect( - livenessOf( - world, - createDb({ - dispatchId: DISPATCH_OLD, - paneKey: PANE_KEY, - handle: TERMINAL_HANDLE, - incarnation: null - }), - DISPATCH_OLD - ) - ).toMatchObject({ verdict: 'unverifiable', reason: 'missing_status' }) - }) - it('reads live for the rebound worker and not for the one it replaced', () => { const world = createWorld() world.bindPane(PANE_KEY, TERMINAL_HANDLE) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/observation/session-worker-observation.ts similarity index 83% rename from src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/observation/session-worker-observation.ts index 262e84b2298..261cd1e65e1 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/observation/session-worker-observation.ts @@ -1,15 +1,15 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { isStructuredWorkerHandle } from '../../../../../../../shared/orchestration/workers/structured-worker-handle' import { chatAssigneeSessionId, observeChatAssignee -} from '../../../../orchestration/workers/lifecycle/chat-assignee' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +} from '../../../../../orchestration/workers/lifecycle/chat-assignee' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import { holdStructuredWorker, observeStructuredSession -} from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' -import { resolveStructuredWorkerForDispatch } from '../structured-workers/orchestration-structured-worker-lifecycle' +} from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' +import { resolveStructuredWorkerForDispatch } from '../../structured-workers/orchestration-structured-worker-lifecycle' export type SessionWorkerObservation = { terminal: null diff --git a/src/main/runtime/rpc/methods/orchestration/worker/observation/structured-worker-fleet-liveness.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/observation/structured-worker-fleet-liveness.test.ts new file mode 100644 index 00000000000..3f3af8feaae --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/observation/structured-worker-fleet-liveness.test.ts @@ -0,0 +1,141 @@ +// Chat-mode workers have no terminal hook stream; worker-list must read the structured host's own verdict. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { agentSessionConversationView } from '../../../../../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' +import type { AgentSessionRecord } from '../../../../../../../shared/agent-session/lifecycle/agent-session-record' +import type { FleetAgentStatusEvidence } from '../../../../../../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../../../../../shared/agent-session/view/structured-agent-session-projection' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' + +const hostRef: { current: unknown } = { current: null } + +vi.mock( + '../../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', + () => ({ getStructuredAgentSessionHost: () => hostRef.current }) +) + +const { projectWorkerFleet } = await import('../fleet/worker-list-projection') +const { createSessionWorkerLivenessReader } = + await import('../../../../../orchestration/workers/lifecycle/session-worker-liveness') +const { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerIdentities, + structuredWorkerProcessIncarnation +} = + await import('../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity') + +const SESSION = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' +const NOW = 10 * 60 * 60 * 1000 +const HOUR = 60 * 60 * 1000 + +function record( + provider: 'codex' | 'claude', + lease: Partial = {} +): AgentSessionRecord { + return { + ...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: SESSION, ...lease })), + provider + } +} + +function installHost(current: AgentSessionRecord, attached: boolean) { + hostRef.current = { + deps: { + store: { + getConversation: () => agentSessionConversationView(current), + listConversations: () => [agentSessionConversationView(current)], + getVisibleSessionTabIndex: () => ({ present: true, sessionIds: [SESSION] }) + } + }, + getSessionTabId: () => `agent-session:${SESSION}`, + hasSession: () => attached + } +} + +/** The session's own status row, as the structured status feed publishes it. */ +function sessionStatus( + state: FleetAgentStatusEvidence['activity']['state'], + at: number +): FleetAgentStatusEvidence { + return { + binding: { kind: 'unresolved', reason: 'pane_not_bound' }, + clock: { kind: 'observed', at }, + deliveredAt: at, + activity: { + paneKey: structuredAgentSessionPaneKey(structuredAgentSessionTabId(SESSION), SESSION), + connectionId: null, + state, + agentType: 'codex', + model: null, + worktreeId: 'wt_1', + restoredUnconfirmed: false, + providerSessionOnly: false + } + } +} + +describe('worker-list liveness for chat-mode workers', () => { + let db: OrchestrationDb + beforeEach(() => { + db = new OrchestrationDb(':memory:') + structuredWorkerIdentities.clear() + hostRef.current = null + }) + afterEach(() => db.close()) + + function seed() { + const task = db.createTask({ runId: 'run_legacy_local', spec: 'structured work' }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 9 + }) + db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle: mintStructuredWorkerHandle(), + paneKey: mintStructuredWorkerPaneKey(SESSION), + processIncarnation: structuredWorkerProcessIncarnation(SESSION), + worktreeId: 'wt_1', + effects: [], + setupState: 'not_configured', + hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), + terminalOwnership: 'created' + }) + db.markWorkerDispatchReady(dispatch.id) + return dispatch.id + } + + function project(statuses: FleetAgentStatusEvidence[]) { + const dispatchId = seed() + const rows = db.listWorkerTerminalResources({ dispatchIds: [dispatchId], limit: 1 }) + return projectWorkerFleet({ + rows, + attentionFacts: db.getWorkerAttentionFactsForDispatches([dispatchId], NOW), + statuses, + limit: 1, + now: NOW, + observeSession: createSessionWorkerLivenessReader(db, statuses) + }).workers[0]! + } + + it('keeps an idle Claude chat worker live after its last turn is hours old', () => { + installHost(record('claude'), true) + const worker = project([sessionStatus('done', NOW - 2 * HOUR)]) + + expect(worker.liveness.verdict).toBe('live') + expect(worker.stage.activity).toBe('done') + expect(worker.attention.requiresAction).toBe(false) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts new file mode 100644 index 00000000000..11fc599ba58 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts @@ -0,0 +1,322 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../../../../../orca-runtime' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' +import { ORCHESTRATION_METHODS } from '../../orchestration' +import { isStreamingMethod, eraseRpcMethods } from '../../../../core' + +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((promiseResolve) => { + resolve = promiseResolve + }) + return { promise, resolve } +} + +describe('orchestration worker recovery', () => { + let db: OrchestrationDb + let runtime: OrcaRuntimeService + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue( + 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + ) + vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1') + vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ + handle: 'term_worker', + worktreeId: 'repo::worktree', + connected: true, + status: 'running' + } as never) + vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ + handle: 'term_worker', + status: 'running', + tail: ['working'], + truncated: false, + nextCursor: null + }) + vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({ + handle: 'term_worker', + tabId: 'tab-worker', + ptyKilled: true + } as never) + }) + + afterEach(() => db.close()) + + async function call(name: string, params: Record) { + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) + if (!method || isStreamingMethod(method)) { + throw new Error(`Method not found: ${name}`) + } + return method.handler(method.params!.parse(params), { runtime }) + } + + function createWorker(runtimeEpoch = runtime.getRuntimeId(), ready = true) { + const run = db.createRun({ + objective: 'Recovery', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + const task = db.createTask({ spec: 'recover worker', runId: run.id }) + const started = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId: task.id, + startOptions: {}, + runtimeEpoch + }) + db.prepareStartingWorkerAuthority({ + dispatchId: started.dispatch.id, + handle: 'term_worker', + paneKey: 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + processIncarnation: 'runtime:pty:1', + worktreeId: 'repo::worktree', + setupState: 'not_applicable', + effects: [{ kind: 'terminal', action: 'created', id: 'term_worker' }], + terminalOwnership: 'created' + }) + if (ready) { + db.markWorkerDispatchReady(started.dispatch.id) + } else { + db.markWorkerStartUnknown(started.dispatch.id, 'dispatch_input', 'connection lost') + } + return { run, task, dispatch: started.dispatch } + } + + it('stops an exact worker whose start receipt is unknown', async () => { + const { task, dispatch } = createWorker(runtime.getRuntimeId(), false) + + await expect( + call('orchestration.workerStop', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ + state: 'stopped', + processAction: 'closed_agent_terminal' + }) + expect(runtime.closeTerminal).toHaveBeenCalledWith('term_worker') + expect(db.getTask(task.id)?.status).toBe('blocked') + }) + + it('keeps an in-flight stop fenced during runtime-epoch reconciliation', async () => { + const { dispatch } = createWorker('previous_runtime') + const pendingObservation = deferred>>() + vi.mocked(runtime.showTerminal) + .mockReturnValueOnce(pendingObservation.promise) + .mockResolvedValue({ + handle: 'term_worker', + worktreeId: 'repo::worktree', + connected: true, + status: 'running' + } as never) + + const stop = call('orchestration.workerStop', { dispatch: dispatch.id }) + await vi.waitFor(() => expect(runtime.showTerminal).toHaveBeenCalledTimes(1)) + await expect( + call('orchestration.workerShow', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ worker: { state: 'stopping' } }) + await expect(call('orchestration.workerAbandon', { dispatch: dispatch.id })).rejects.toThrow( + 'is stopping; wait for worker-stop to settle before abandoning' + ) + + pendingObservation.resolve({ + handle: 'term_worker', + worktreeId: 'repo::worktree', + connected: true, + status: 'running' + } as never) + await expect(stop).resolves.toMatchObject({ + state: 'stopped', + processAction: 'closed_agent_terminal' + }) + }) + + it('does not adopt or stop a same-looking pane with a new process incarnation', async () => { + const { task, dispatch } = createWorker() + vi.mocked(runtime.getTerminalProcessIncarnation).mockReturnValue('runtime:pty:2') + + await expect( + call('orchestration.workerShow', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ + worker: { state: 'ready' }, + observation: { status: 'identity_changed', exactWorker: false }, + terminal: null + }) + await expect(call('orchestration.workerRead', { dispatch: dispatch.id })).rejects.toMatchObject( + { + code: 'worker_identity_changed' + } + ) + await expect( + call('orchestration.workerStop', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ + state: 'stop_unknown', + processAction: 'none' + }) + expect(runtime.closeTerminal).not.toHaveBeenCalled() + expect(db.getTask(task.id)?.status).toBe('blocked') + }) + + it('labels an exact but disconnected worker as exited and does not close it again', async () => { + const { task, dispatch } = createWorker() + vi.mocked(runtime.showTerminal).mockResolvedValue({ + handle: 'term_worker', + worktreeId: 'repo::worktree', + connected: false, + writable: false + } as never) + // `connected: false` is transport state; an exited result requires the + // runtime's authoritative host-side verdict. + vi.spyOn(runtime, 'getTerminalLivenessVerdict').mockReturnValue({ status: 'exited' }) + + await expect( + call('orchestration.workerShow', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ + observation: { status: 'exited', exactWorker: true }, + terminal: { handle: 'term_worker', connected: false } + }) + await expect( + call('orchestration.workerStop', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ + state: 'stop_unknown', + processAction: 'none' + }) + expect(runtime.closeTerminal).not.toHaveBeenCalled() + expect(db.getTask(task.id)?.status).toBe('blocked') + }) + + it('turns an interrupted start into inspectable unknown after runtime restart', async () => { + const run = db.createRun({ + objective: 'Interrupted start', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + const task = db.createTask({ spec: 'interrupted', runId: run.id }) + const started = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId: task.id, + startOptions: {}, + runtimeEpoch: 'previous_runtime' + }) + db.recordWorkerStage({ + dispatchId: started.dispatch.id, + stage: 'worktree_creating' + }) + + await expect( + call('orchestration.workerShow', { dispatch: started.dispatch.id }) + ).resolves.toMatchObject({ + worker: { state: 'start_unknown', stage: 'worktree_creating' }, + observation: { status: 'unattached', exactWorker: false } + }) + expect(db.getTask(task.id)?.status).toBe('blocked') + }) + + it('turns an interrupted stop into unknown after runtime restart', async () => { + const { task, dispatch } = createWorker('previous_runtime') + db.beginWorkerStop(dispatch.id, 'previous_runtime') + + await expect( + call('orchestration.workerShow', { dispatch: dispatch.id }) + ).resolves.toMatchObject({ + worker: { state: 'stop_unknown' } + }) + expect(db.getTask(task.id)?.status).toBe('blocked') + }) + + it('does not let a delayed remote show revive a released worker projection', async () => { + const run = db.createRun({ + objective: 'Fence delayed remote show', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + const task = db.createTask({ spec: 'release remote worker', runId: run.id }) + const started = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId: task.id, + startOptions: {}, + federation: { + environmentId: 'environment_windows', + environmentName: 'windows', + peerFingerprint: 'windows_peer', + protocolVersion: 1 + } + }) + db.reconcileFederatedWorkerStart({ + dispatchId: started.dispatch.id, + state: 'ready', + stage: 'remote_input_accepted', + worktreeId: 'repo::windows-worktree', + terminalHandle: 'term_windows_worker' + }) + db.updateFederatedDispatchResources({ + dispatchId: started.dispatch.id, + remoteRuntimeEpoch: 'windows_epoch_old', + worktreeId: 'repo::windows-worktree', + terminalHandle: 'term_windows_worker' + }) + const pendingShow = deferred() + vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({ + environmentId: 'environment_windows', + name: 'windows', + peerFingerprint: 'windows_peer' + }) + vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockReturnValue(pendingShow.promise) + + const show = call('orchestration.workerShow', { dispatch: started.dispatch.id }) + await vi.waitFor(() => expect(runtime.callOrchestrationWorkerServer).toHaveBeenCalledOnce()) + db.transitionLifecycle({ + entity: 'worker', + id: started.dispatch.id, + from: 'ready', + to: 'ready', + projection: { stage: 'released', agent_terminal_handle: null } + }) + db.db + .prepare( + `UPDATE federated_dispatches + SET remote_runtime_epoch = 'windows_epoch_new', remote_terminal_handle = NULL + WHERE dispatch_id = ?` + ) + .run(started.dispatch.id) + pendingShow.resolve({ + runtimeEpoch: 'windows_epoch_old', + attachment: { + state: 'ready', + stage: 'remote_input_accepted', + last_error: null, + worktree_id: 'repo::windows-worktree', + terminal_handle: 'term_windows_worker', + setup_state: 'not_applicable', + effects: [], + residualResources: [] + }, + terminal: { handle: 'term_windows_worker', connected: true }, + observation: { status: 'live', exactWorker: true } + }) + + await expect(show).resolves.toMatchObject({ + worker: { stage: 'released', agentTerminalHandle: null }, + remoteRuntimeEpoch: 'windows_epoch_new', + terminal: null, + observation: { + status: 'unverifiable', + exactWorker: false, + reason: 'observation_superseded' + } + }) + expect(db.getFederatedDispatch(started.dispatch.id)).toMatchObject({ + remote_runtime_epoch: 'windows_epoch_new', + remote_terminal_handle: null + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/observation/worker-observation.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/observation/worker-observation.ts index 14e6423c969..c74773791ae 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/observation/worker-observation.ts @@ -1,19 +1,19 @@ -import { parseWorkerTerminalHostScope } from '../../../../../../shared/orchestration/workers/worker-terminal-host-scope' -import type { RuntimeTerminalInteractiveWait } from '../../../../../../shared/runtime-terminal-contracts' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' -import { projectWorkerFleet } from './worker-list-projection' -import { createSessionWorkerLivenessReader } from '../../../../orchestration/workers/lifecycle/session-worker-liveness' +import { parseWorkerTerminalHostScope } from '../../../../../../../shared/orchestration/workers/worker-terminal-host-scope' +import type { RuntimeTerminalInteractiveWait } from '../../../../../../../shared/runtime-terminal-contracts' +import type { WorkerTerminalReleaseRuntime } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { OrchestrationFleetWorker } from '../../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import { projectWorkerFleet } from '../fleet/worker-list-projection' +import { createSessionWorkerLivenessReader } from '../../../../../orchestration/workers/lifecycle/session-worker-liveness' import { inspectSessionWorker } from './session-worker-observation' import type { DispatchContextRow, FederatedDispatchRow, WorkerDispatchRow -} from '../../../../orchestration/db/orchestration-records' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' +} from '../../../../../orchestration/db/orchestration-records' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../../shared/layout-owner-switch' import { exposeDispatchContext } from './dispatch-context-exposure' -import { resolvePinnedFederatedServer } from './pinned-federated-server' +import { resolvePinnedFederatedServer } from '../../../../../orchestration/legacy-remote-home/pinned-federated-server' /** Recover live handles by recorded process incarnation so stale durable handles cannot hide and leak running workers. */ export async function inspectWorkerTerminal( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-archive-read.ts b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-archive-read.ts similarity index 84% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-archive-read.ts rename to src/main/runtime/rpc/methods/orchestration/worker/output/worker-archive-read.ts index cb189481119..f6f6acbe652 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-archive-read.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-archive-read.ts @@ -1,26 +1,28 @@ import type { OrchestrationWorkerReadResult, OrchestrationWorkerReadSource -} from '../../../../../../shared/orchestration/workers/orchestration-worker-output' -import type { PtyLivenessVerdict } from '../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +} from '../../../../../../../shared/orchestration/workers/orchestration-worker-output' +import type { PtyLivenessVerdict } from '../../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' import type { WorkerTerminalArchiveRow, WorkerTerminalResourceRow -} from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import type { - WorkerTerminalTailArchive, - WorkerTranscriptSnapshotArchive -} from '../../../../orchestration/workers/archives/worker-output-archive' -import { clampWorkerTranscriptLimit } from '../../../../orchestration/workers/transcripts/worker-transcript-payload' +} from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { + isWorkerOutputReference, + type WorkerTerminalTailArchive, + type WorkerTranscriptSnapshotArchive +} from '../../../../../orchestration/workers/archives/worker-output-archive' +import { readReleasedWorkerOriginal } from './worker-original-read' +import { clampWorkerTranscriptLimit } from '../../../../../orchestration/workers/transcripts/worker-transcript-payload' import { createWorkerOutputSourceIdentity, decodeWorkerOutputCursor, encodeWorkerOutputCursor -} from '../../../../orchestration/workers/transcripts/worker-output-cursor' -import type { WorkerStructuredJournalArchive } from '../../../../orchestration/workers/archives/structured-worker-journal-archive' -import { readArchivedStructuredJournal } from '../structured-workers/orchestration-structured-worker-lifecycle' +} from '../../../../../orchestration/workers/transcripts/worker-output-cursor' +import type { WorkerStructuredJournalArchive } from '../../../../../orchestration/workers/archives/structured-worker-journal-archive' +import { readArchivedStructuredJournal } from '../../structured-workers/orchestration-structured-worker-lifecycle' const ARCHIVED_TERMINAL_PAGE_LINES = 2_000 @@ -43,6 +45,10 @@ export async function readArchivedWorkerOutput(args: { `Dispatch ${args.dispatchId} was released without a preserved output archive.` ) } + // Releases now record where the original lives; rows from before keep the copy read below. + if (isWorkerOutputReference(archive)) { + return readReleasedWorkerOriginal(args, archive) + } if (archive.kind === 'structured_journal') { if (args.source === 'terminal') { throw new OrchestrationError( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/output/worker-original-read.ts b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-original-read.ts new file mode 100644 index 00000000000..0648faa5466 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-original-read.ts @@ -0,0 +1,167 @@ +import type { + OrchestrationWorkerReadResult, + OrchestrationWorkerReadSource +} from '../../../../../../../shared/orchestration/workers/orchestration-worker-output' +import type { PtyLivenessVerdict } from '../../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../../../../../shared/orchestration/orchestration-session-caller-codes' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import type { + WorkerTerminalArchiveRow, + WorkerTerminalResourceRow +} from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { structuredWorkerAgent } from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' +import { + readWorkerOutputReference, + type WorkerOutputReference +} from '../../../../../orchestration/workers/archives/worker-output-archive' +import { + createWorkerOutputSourceIdentity, + decodeWorkerOutputCursor +} from '../../../../../orchestration/workers/transcripts/worker-output-cursor' +import { readWorkerTranscript } from '../../../../../orchestration/workers/transcripts/worker-transcript-read' +import { + readStructuredWorkerJournal, + resolveStructuredWorkerForDispatch +} from '../../structured-workers/orchestration-structured-worker-lifecycle' +import { sourceChanged, workerTranscriptReadResult } from './worker-output' + +export type ReleasedWorkerReadArgs = { + db: OrchestrationDb + dispatchId: string + workerState: string + resource: Pick + source?: OrchestrationWorkerReadSource + cursor?: string | number + limit?: number + /** Process evidence is separate from the fact that the worker was released. */ + liveness?: PtyLivenessVerdict['status'] +} + +/** A released worker's output, read from its original transcript or chat history as it is now. */ +export async function readReleasedWorkerOriginal( + args: ReleasedWorkerReadArgs, + archive: WorkerTerminalArchiveRow +): Promise { + const reference = readWorkerOutputReference(archive) + if (archive.kind === 'terminal_tail') { + throw outputUnavailable( + args.dispatchId, + `it had no transcript to read (${reference.fallbackReason ?? 'session_not_reported'})` + ) + } + if (args.source === 'terminal') { + throw new OrchestrationError( + 'archive_unavailable', + `Dispatch ${args.dispatchId} keeps its transcript only; terminal output was released.` + ) + } + return archive.kind === 'structured_journal' + ? readReleasedChatHistory(args, reference) + : readReleasedTranscript(args, reference) +} + +async function readReleasedTranscript( + args: ReleasedWorkerReadArgs, + reference: WorkerOutputReference +): Promise { + const { agent, sessionId, transcriptPath, wslDistro } = reference + if (!agent || !sessionId) { + throw outputUnavailable(args.dispatchId, 'its transcript was never located') + } + const cursor = decodeWorkerOutputCursor(args.cursor, args.dispatchId) + if (cursor && (cursor.source !== 'transcript' || !cursor.boundaryCheckpoint)) { + throw sourceChanged() + } + const transcript = await readWorkerTranscript({ + agent, + sessionId, + transcriptPath, + wslDistro, + offset: cursor?.position, + expectedBoundaryCheckpoint: cursor?.boundaryCheckpoint ?? undefined, + limit: args.limit + }) + if (!transcript.ok) { + if (transcript.reason === 'source_changed') { + throw sourceChanged() + } + throw outputUnavailable(args.dispatchId, `its transcript is gone (${transcript.reason})`) + } + const sourceIdentity = createWorkerOutputSourceIdentity([ + 'released-transcript', + args.resource.id, + reference.processIncarnation ?? '', + agent, + sessionId, + transcript.filePath, + transcript.sourceFingerprint + ]) + if (cursor && cursor.sourceIdentity !== sourceIdentity) { + throw sourceChanged() + } + return { + ...workerTranscriptReadResult({ + dispatchId: args.dispatchId, + sourceIdentity, + agent, + transcript, + status: releasedStatus(args) + }), + archived: true + } +} + +async function readReleasedChatHistory( + args: ReleasedWorkerReadArgs, + reference: WorkerOutputReference +): Promise { + const identity = resolveStructuredWorkerForDispatch(args.db, args.dispatchId) + if (!identity) { + throw outputUnavailable(args.dispatchId, 'its chat is no longer recorded') + } + const status = releasedStatus(args) + try { + return await readStructuredWorkerJournal({ + identity, + dispatchId: args.dispatchId, + workerState: args.workerState, + liveness: status.liveness, + agent: reference.agent ?? structuredWorkerAgent(identity), + archived: true, + ...(args.cursor === undefined ? {} : { cursor: args.cursor }), + ...(args.limit === undefined ? {} : { limit: args.limit }) + }) + } catch (error) { + // Cursor, host-boundary and other refusals keep their own codes, as on a live read. + if ( + error instanceof OrchestrationError && + (error.code === 'transcript_required' || error.code === CODES.notLive) + ) { + throw outputUnavailable(args.dispatchId, 'its chat history could not be read') + } + throw error + } +} + +function releasedStatus(args: ReleasedWorkerReadArgs): { + worker: string + terminal: 'running' | 'exited' | 'unknown' + liveness: PtyLivenessVerdict['status'] +} { + // Only a settled host-confirmed release proves exit. + const liveness = + args.liveness ?? (args.resource.release_state === 'released' ? 'exited' : 'unverifiable') + return { + worker: args.workerState, + terminal: liveness === 'live' ? 'running' : liveness === 'exited' ? 'exited' : 'unknown', + liveness + } +} + +function outputUnavailable(dispatchId: string, why: string): OrchestrationError { + return new OrchestrationError( + 'archive_unavailable', + `The output of Dispatch ${dispatchId} is no longer available: ${why}. See its report (worker_done) or task result.` + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts new file mode 100644 index 00000000000..de1c77db93f --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts @@ -0,0 +1,91 @@ +import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { readExactWorkerOutput } from './worker-output' + +function codexMessage(id: string, text: string): string { + return JSON.stringify({ + type: 'event_msg', + payload: { id, type: 'agent_message', message: text } + }) +} + +describe('exact orchestration worker output', () => { + let directory: string + let transcriptA: string + let providerSession: ReturnType + let runtime: OrcaRuntimeService + const readTerminal = vi.fn() + + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-worker-output-')) + transcriptA = join(directory, 'session-a.jsonl') + await writeFile(transcriptA, `${codexMessage('a', 'worker A only')}\n`) + providerSession = { + paneKey: 'tab:worker', + processIncarnation: 'pty:incarnation-1', + agent: 'codex', + providerSession: { + key: 'session_id', + id: 'session-a', + transcriptPath: transcriptA + }, + observedAt: Date.now() + } + readTerminal.mockReset() + readTerminal.mockResolvedValue({ + handle: 'term_worker', + status: 'running', + tail: ['terminal output'], + truncated: false, + nextCursor: '9' + }) + runtime = { + getExactWorkerProviderSession: vi.fn(() => providerSession), + getTerminalProcessIncarnation: vi.fn(() => 'pty:incarnation-1'), + getTerminalPaneKey: vi.fn(() => 'tab:worker'), + readTerminal + } as unknown as OrcaRuntimeService + }) + + afterEach(async () => { + await rm(directory, { recursive: true, force: true }) + }) + + const read = (overrides: Partial[0]> = {}) => + readExactWorkerOutput({ + runtime, + dispatchId: 'dispatch_1', + terminalHandle: 'term_worker', + workerState: 'ready', + terminalStatus: 'running', + attachedAt: '2026-07-24 00:00:00', + ...overrides + }) + + it('rejects an old cursor after a same-inode truncate/regrow', async () => { + const initial = await read() + if (initial.source !== 'transcript') { + throw new Error('Expected transcript output') + } + const before = await stat(transcriptA, { bigint: true }) + await writeFile( + transcriptA, + `${codexMessage('replacement', 'unrelated transcript')}\n${' '.repeat(512)}` + ) + const after = await stat(transcriptA, { bigint: true }) + expect(after.ino).toBe(before.ino) + expect(after.dev).toBe(before.dev) + const fresh = await read() + if (fresh.source !== 'transcript') { + throw new Error('Expected replacement transcript output') + } + expect(fresh.sourceIdentity).toBe(initial.sourceIdentity) + + await expect(read({ cursor: initial.cursor })).rejects.toMatchObject({ + code: 'source_changed' + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.ts b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.ts new file mode 100644 index 00000000000..f08291ad345 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.ts @@ -0,0 +1,272 @@ +import type { + OrchestrationWorkerReadFallbackReason, + OrchestrationWorkerReadResult, + OrchestrationWorkerReadSource +} from '../../../../../../../shared/orchestration/workers/orchestration-worker-output' +import type { RuntimeTerminalState } from '../../../../../../../shared/runtime-terminal-contracts' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import { + createWorkerOutputSourceIdentity, + decodeWorkerOutputCursor, + encodeWorkerOutputCursor +} from '../../../../../orchestration/workers/transcripts/worker-output-cursor' +import { redactWorkerTerminalView } from '../../../../../orchestration/terminal-authority/views/worker-terminal-redaction' +import { + readWorkerTranscript, + type WorkerTranscriptReadSuccess +} from '../../../../../orchestration/workers/transcripts/worker-transcript-read' +import type { AgentType } from '../../../../../../../shared/agent-status/contracts/agent-status-types' +import { isWslHookRelayConnectionId } from '../../../../../../../shared/wsl-hook-relay-contract' + +export async function readExactWorkerOutput(args: { + runtime: OrcaRuntimeService + dispatchId: string + terminalHandle: string + workerState: string + terminalStatus: RuntimeTerminalState + terminalLiveness?: 'live' | 'unverifiable' | 'exited' + attachedAt: string + source?: OrchestrationWorkerReadSource + cursor?: string | number + limit?: number +}): Promise { + const source = args.source ?? 'auto' + const cursor = decodeWorkerOutputCursor(args.cursor, args.dispatchId) + assertCursorSourceMatchesRequest(cursor?.source, source) + + if (cursor?.source === 'terminal' || source === 'terminal') { + return readTerminalOutput(args, cursor) + } + + const observedAfter = orchestrationTimestampToMs(args.attachedAt) + const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, observedAfter) + if (!session) { + if (cursor?.source === 'transcript') { + throw sourceChanged() + } + return fallbackOrThrow(args, 'session_not_reported') + } + const isWslSession = isWslHookRelayConnectionId(session.connectionId) + if (isWslSession && !session.wslDistro) { + return fallbackOrThrow(args, 'remote_capability_unavailable') + } + // Why: this process serves no SSH filesystem, so an SSH worker's transcript is unreachable. + if (session.connectionId && !isWslSession) { + return fallbackOrThrow(args, 'remote_capability_unavailable') + } + if (cursor?.source === 'transcript' && !cursor.boundaryCheckpoint) { + throw sourceChanged() + } + const transcript = await readWorkerTranscript({ + agent: session.agent, + sessionId: session.providerSession.id, + transcriptPath: session.providerSession.transcriptPath, + wslDistro: session.wslDistro, + offset: cursor?.source === 'transcript' ? cursor.position : undefined, + expectedBoundaryCheckpoint: + cursor?.source === 'transcript' ? (cursor.boundaryCheckpoint ?? undefined) : undefined, + limit: args.limit + }) + if (!transcript.ok) { + if (transcript.reason === 'source_changed') { + throw sourceChanged() + } + if (cursor?.source === 'transcript') { + throw transcriptRequired(args.dispatchId, transcript.reason) + } + return fallbackOrThrow(args, transcript.reason, transcript.warnings) + } + const sourceIdentity = createWorkerOutputSourceIdentity([ + 'transcript', + session.processIncarnation, + session.agent, + session.providerSession.key, + session.providerSession.id, + session.connectionId ?? 'local', + transcript.filePath, + transcript.sourceFingerprint + ]) + if (cursor?.source === 'transcript' && cursor.sourceIdentity !== sourceIdentity) { + throw sourceChanged() + } + const sessionAfterRead = args.runtime.getExactWorkerProviderSession( + args.terminalHandle, + observedAfter + ) + if ( + !sessionAfterRead || + sessionAfterRead.processIncarnation !== session.processIncarnation || + sessionAfterRead.agent !== session.agent || + sessionAfterRead.providerSession.key !== session.providerSession.key || + sessionAfterRead.providerSession.id !== session.providerSession.id || + sessionAfterRead.providerSession.transcriptPath !== session.providerSession.transcriptPath || + sessionAfterRead.connectionId !== session.connectionId || + sessionAfterRead.wslDistro !== session.wslDistro + ) { + throw sourceChanged() + } + return workerTranscriptReadResult({ + dispatchId: args.dispatchId, + sourceIdentity, + agent: session.agent, + transcript, + status: { + worker: args.workerState, + terminal: args.terminalStatus, + ...(args.terminalLiveness ? { liveness: args.terminalLiveness } : {}) + } + }) +} + +/** A transcript page in the shape worker-read serves, with a cursor pinned to its source. */ +export function workerTranscriptReadResult(args: { + dispatchId: string + sourceIdentity: string + agent: AgentType + transcript: WorkerTranscriptReadSuccess + status: OrchestrationWorkerReadResult['status'] +}): OrchestrationWorkerReadResult { + const { transcript } = args + const nextCursor = encodeWorkerOutputCursor( + args.dispatchId, + 'transcript', + args.sourceIdentity, + transcript.nextOffset, + transcript.boundaryCheckpoint + ) + return { + dispatchId: args.dispatchId, + source: 'transcript', + sourceIdentity: args.sourceIdentity, + provider: args.agent, + transcript: { + messages: transcript.messages, + nextCursor, + limited: transcript.limited, + returnedMessageCount: transcript.messages.length + }, + cursor: nextCursor, + status: args.status, + fallbackReason: null, + warnings: transcript.warnings, + sourceExact: true, + contentComplete: !transcript.limited, + ...(transcript.clipping.length > 0 ? { clipping: transcript.clipping } : {}) + } +} + +async function readTerminalOutput( + args: Parameters[0], + cursor: ReturnType +): Promise { + const processIncarnation = args.runtime.getTerminalProcessIncarnation(args.terminalHandle) + const paneKey = args.runtime.getTerminalPaneKey(args.terminalHandle) + if (!processIncarnation || !paneKey) { + throw new OrchestrationError( + 'worker_identity_changed', + `Worker Dispatch ${args.dispatchId} no longer resolves to its exact process.` + ) + } + const sourceIdentity = createWorkerOutputSourceIdentity(['terminal', processIncarnation, paneKey]) + if ( + cursor?.source === 'terminal' && + cursor.sourceIdentity !== null && + cursor.sourceIdentity !== sourceIdentity + ) { + throw sourceChanged() + } + const terminal = await args.runtime.readTerminal(args.terminalHandle, { + cursor: cursor?.source === 'terminal' ? cursor.position : undefined, + limit: args.limit + }) + const redactedTerminal = redactWorkerTerminalView(terminal) + const position = + terminal.nextCursor !== null && /^\d+$/.test(terminal.nextCursor) + ? Number.parseInt(terminal.nextCursor, 10) + : null + const nextCursor = + position === null + ? null + : encodeWorkerOutputCursor(args.dispatchId, 'terminal', sourceIdentity, position) + return { + dispatchId: args.dispatchId, + source: 'terminal', + sourceIdentity, + terminal: { + ...terminal, + tail: redactedTerminal.tail, + ...(redactedTerminal.draft ? { draft: redactedTerminal.draft } : {}) + }, + cursor: nextCursor, + status: { + worker: args.workerState, + terminal: args.terminalLiveness === 'unverifiable' ? args.terminalStatus : terminal.status, + ...(args.terminalLiveness ? { liveness: args.terminalLiveness } : {}) + }, + fallbackReason: null, + warnings: redactedTerminal.warnings, + sourceExact: true, + contentComplete: !terminal.truncated, + ...(terminal.truncated ? { clipping: ['terminal_buffer'] } : {}) + } +} + +async function fallbackOrThrow( + args: Parameters[0], + reason: OrchestrationWorkerReadFallbackReason, + warnings: string[] = [] +): Promise { + if (args.source === 'transcript') { + throw transcriptRequired(args.dispatchId, reason) + } + const fallback = await readTerminalOutput(args, null) + return fallback.source === 'terminal' + ? { + ...fallback, + fallbackReason: reason, + sourceExact: false, + contentComplete: false, + clipping: [...(fallback.clipping ?? []), 'terminal_fallback'], + warnings: [...new Set([...fallback.warnings, ...warnings])] + } + : fallback +} + +function assertCursorSourceMatchesRequest( + cursorSource: 'terminal' | 'transcript' | undefined, + requestedSource: OrchestrationWorkerReadSource +): void { + if (cursorSource && requestedSource !== 'auto' && cursorSource !== requestedSource) { + throw new OrchestrationError( + 'cursor_invalid', + `The worker-read cursor is pinned to ${cursorSource} output.` + ) + } +} + +export function orchestrationTimestampToMs(value: string): number { + const normalized = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(value) + ? `${value.replace(' ', 'T')}Z` + : value + const parsed = Date.parse(normalized) + return Number.isFinite(parsed) ? parsed : 0 +} + +export function sourceChanged(): OrchestrationError { + return new OrchestrationError( + 'source_changed', + 'The worker output source changed. Start a fresh worker-read without the old cursor.' + ) +} + +function transcriptRequired( + dispatchId: string, + reason: OrchestrationWorkerReadFallbackReason +): OrchestrationError { + return new OrchestrationError( + 'transcript_required', + `Structured output is unavailable for Dispatch ${dispatchId}: ${reason}.`, + { reason } + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/pinned-federated-server.ts b/src/main/runtime/rpc/methods/orchestration/worker/pinned-federated-server.ts deleted file mode 100644 index b61bc4235f7..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/pinned-federated-server.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' -import { RuntimeEnvironmentStoreError } from '../../../../../../shared/remote-runtime/host-store/runtime-environment-store-records' - -export function resolvePinnedFederatedServer( - runtime: WorkerTerminalReleaseRuntime, - federated: FederatedDispatchRow -) { - let server - try { - server = runtime.resolveOrchestrationWorkerServer(federated.environment_id) - } catch (error) { - // Not found: removed, or re-paired, which adds the server as a new environment. - if (error instanceof RuntimeEnvironmentStoreError && error.code === 'invalid_argument') { - throw new OrchestrationError( - 'peer_changed', - `Saved environment ${federated.environment_name} is no longer a paired server here, so this Orca cannot reach this worker. Re-pairing adds the server as a new environment.` - ) - } - throw error - } - if (server.peerFingerprint !== federated.peer_fingerprint) { - throw new OrchestrationError( - 'peer_changed', - `Saved environment ${federated.environment_name} now identifies a different Orca server.` - ) - } - return server -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/retried-worker-terminal-release.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/retried-worker-terminal-release.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/retried-worker-terminal-release.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/retried-worker-terminal-release.ts index 1f00d8dc0e9..5d751759e9e 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/retried-worker-terminal-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/retried-worker-terminal-release.ts @@ -1,5 +1,5 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import { completeWorkerTerminalRelease } from './worker-release-completion' /** Release the failed attempt's terminal on retry-of: archive output, preserve user takeover and retain interrupted cleanup for recovery. diff --git a/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-release-stop.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/structured-worker-release-stop.ts similarity index 78% rename from src/main/runtime/rpc/methods/orchestration/worker/structured-worker-release-stop.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/structured-worker-release-stop.ts index 4130e81061f..f4264d3574e 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-release-stop.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/structured-worker-release-stop.ts @@ -1,8 +1,8 @@ -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { WorkerTerminalResourceRow } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import { stopStructuredWorker } from '../structured-workers/orchestration-structured-worker-lifecycle' -import type { StructuredWorkerIdentity } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' +import type { WorkerTerminalReleaseRuntime } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { WorkerTerminalResourceRow } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { stopStructuredWorker } from '../../structured-workers/orchestration-structured-worker-lifecycle' +import type { StructuredWorkerIdentity } from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' import { archiveSummary } from './worker-terminal-resource-presentation' import type { WorkerReleaseReceipt } from './worker-release-completion' import { releaseUnknownRecovery } from './worker-release-unknown-recovery' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release-turns.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts similarity index 79% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release-turns.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts index ac9eaba3a86..fab9882718f 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release-turns.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts @@ -1,8 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import { WorkerAutoReleaseActivity } from '../../../../orchestration/terminal-authority/release/worker-auto-release-activity' -import type { AgentPhase } from '../../../../../../shared/agent-status/lifecycle/agent-transitions' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { WorkerAutoReleaseActivity } from '../../../../../orchestration/terminal-authority/release/worker-auto-release-activity' +import type { AgentPhase } from '../../../../../../../shared/agent-status/lifecycle/agent-transitions' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' const GRACE_MS = 2 * 60_000 @@ -78,20 +78,6 @@ describe('orchestration worker automatic release across turns and settings', () await expectClosedAfterFreshGrace() }) - it('holds the countdown while a follow-up waits on the user', async () => { - setupWithFakeClock() - const activity = new WorkerAutoReleaseActivity(() => h.db) - await h.startSettledWorker() - - activity.observePane(moved('done', 'working')) - activity.observePane(moved('working', 'needs-you')) - await vi.advanceTimersByTimeAsync(2 * GRACE_MS) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - - activity.observePane(moved('needs-you', 'done')) - await expectClosedAfterFreshGrace() - }) - it('refuses to stop a kept worker without touching it, and stops it once auto-close is allowed', async () => { setupWithFakeClock() const { dispatchId } = await h.startWorker() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release.test.ts similarity index 79% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release.test.ts index 774f94c8576..665fa655b11 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release.test.ts @@ -2,17 +2,25 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { reconcileRequestedWorkerTerminalReleases } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-reconciliation' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' -import { WorkerAutoReleaseActivity } from '../../../../orchestration/terminal-authority/release/worker-auto-release-activity' -import type { AgentPhase } from '../../../../../../shared/agent-status/lifecycle/agent-transitions' +import { reconcileRequestedWorkerTerminalReleases } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-reconciliation' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' +import { WorkerAutoReleaseActivity } from '../../../../../orchestration/terminal-authority/release/worker-auto-release-activity' +import type { AgentPhase } from '../../../../../../../shared/agent-status/lifecycle/agent-transitions' const GRACE_MS = 2 * 60_000 describe('orchestration worker automatic release', () => { const h = createOrchestrationWorkerReleaseHarness() + // This fixture's worker reports no transcript: release records that, and worker-read says so. + async function expectOutputReference(dispatchId: string): Promise { + expect(h.db.getWorkerTerminalArchive(dispatchId)?.kind).toBe('terminal_tail') + await expect( + h.call('orchestration.workerRead', { dispatch: dispatchId }) + ).rejects.toMatchObject({ code: 'archive_unavailable' }) + } + afterEach(() => { getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() h.cleanup() @@ -26,7 +34,7 @@ describe('orchestration worker automatic release', () => { } it.each(['succeeded', 'failed'] as const)( - 'releases a %s worker once its grace period ends and keeps its output readable', + 'releases a %s worker once its grace period ends and keeps where its output lives', async (outcome) => { setupWithFakeClock() const { dispatchId } = await h.startSettledWorker(outcome) @@ -47,11 +55,7 @@ describe('orchestration worker automatic release', () => { ) expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) expect(h.runtime.closeTerminal).toHaveBeenCalledWith('term_worker') - await expect( - h.call('orchestration.workerRead', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - terminal: { tail: ['worker output line 1', 'worker output line 2'] } - }) + await expectOutputReference(dispatchId) } ) @@ -92,20 +96,6 @@ describe('orchestration worker automatic release', () => { await vi.waitFor(() => expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1)) }) - it("closes a worker the user typed into on time; an older client's typing report keeps nothing", async () => { - setupWithFakeClock() - const { dispatchId } = await h.startSettledWorker() - - await expect( - h.call('orchestration.workerTerminalUserInput', { paneKey: h.workerPaneKey }) - ).resolves.toEqual({ changed: 0 }) - await vi.advanceTimersByTimeAsync(GRACE_MS) - - await vi.waitFor(() => - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') - ) - }) - const keepOpen = (keep: boolean): Promise => h.call('orchestration.workerKeepOpen', { paneKey: h.workerPaneKey, keep }) @@ -202,51 +192,6 @@ describe('orchestration worker automatic release', () => { await vi.waitFor(() => expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1)) }) - it('does not arm a worker retained before it reported', async () => { - setupWithFakeClock() - const { taskId, dispatchId } = await h.startWorker() - await h.call('orchestration.workerRetain', { dispatch: dispatchId }) - - h.settle(taskId, dispatchId, 'succeeded') - await vi.advanceTimersByTimeAsync(2 * GRACE_MS) - - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.auto_release_at).toBeNull() - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - }) - - it.each([ - ['silent', async () => (await h.startWorker()).dispatchId], - [ - 'abandoned', - async () => { - const { dispatchId } = await h.startWorker() - await h.call('orchestration.workerAbandon', { dispatch: dispatchId }) - return dispatchId - } - ], - [ - 'pre-upgrade settled', - async () => { - const { dispatchId } = await h.startSettledWorker() - h.db.db - .prepare( - 'UPDATE worker_terminal_resources SET auto_release_at = NULL, auto_release_dispatch_id = NULL WHERE owner_dispatch_id = ?' - ) - .run(dispatchId) - return dispatchId - } - ] - ] as const)('leaves a %s worker to manual release', async (_state, start) => { - setupWithFakeClock() - const dispatchId = await start() - - getWorkerTerminalAutoReleaseScheduler(h.runtime).rearm() - await vi.advanceTimersByTimeAsync(2 * GRACE_MS) - - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.auto_release_at).toBeNull() - }) - describe('across a restart', () => { let userDataDir: string @@ -261,14 +206,6 @@ describe('orchestration worker automatic release', () => { h.setup({ userDataDir }) } - async function expectReadableArchive(dispatchId: string): Promise { - await expect( - h.call('orchestration.workerRead', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - terminal: { tail: ['worker output line 1', 'worker output line 2'] } - }) - } - it('releases a deadline missed while the app was closed once, when the database reopens', async () => { setupFileBacked() const { dispatchId } = await h.startSettledWorker() @@ -283,7 +220,7 @@ describe('orchestration worker automatic release', () => { expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') ) expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) - await expectReadableArchive(dispatchId) + await expectOutputReference(dispatchId) h.restart() await vi.advanceTimersByTimeAsync(2 * GRACE_MS) @@ -298,7 +235,7 @@ describe('orchestration worker automatic release', () => { // Hold the step after which a crash leaves the row in this state. const held = interruptedAt === 'requested' - ? vi.mocked(h.runtime.readTerminal).mockReturnValue(new Promise(() => {})) + ? vi.mocked(h.runtime.showTerminal).mockReturnValue(new Promise(() => {})) : vi.mocked(h.runtime.closeTerminal).mockReturnValue(new Promise(() => {})) await vi.advanceTimersByTimeAsync(GRACE_MS) await vi.waitFor(() => expect(held).toHaveBeenCalled()) @@ -310,7 +247,7 @@ describe('orchestration worker automatic release', () => { expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) - await expectReadableArchive(dispatchId) + await expectOutputReference(dispatchId) } ) }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-archive-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-archive-capture.ts new file mode 100644 index 00000000000..241cf20ad92 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-archive-capture.ts @@ -0,0 +1,49 @@ +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../../../../../shared/orchestration/orchestration-session-caller-codes' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import { + captureWorkerOutputReference, + type WorkerOutputArchiveCapture +} from '../../../../../orchestration/workers/archives/worker-output-archive' +import type { WorkerTerminalResourceRow } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import type { WorkerReleaseReceipt } from './worker-release-completion' +import { releaseUnknownRecovery } from './worker-release-unknown-recovery' +import { archiveSummary } from './worker-terminal-resource-presentation' +import { captureWorkerResumeSession } from '../follow-up/worker-resume-session-capture' + +/** Record where release output lives; unverifiable structured sessions finish release_unknown instead of retrying forever as requested. A fresh request may retry. */ +export function captureWorkerReleaseArchive( + args: Parameters[0] & { + db: OrchestrationDb + resource: WorkerTerminalResourceRow + dispatchId: string + } +): { captured: WorkerOutputArchiveCapture } | { receipt: WorkerReleaseReceipt } { + const { db, resource, dispatchId, ...capture } = args + captureWorkerResumeSession(capture.runtime, db, resource, capture.attachedAtMs) + try { + return { captured: captureWorkerOutputReference(capture) } + } catch (error) { + if (!capture.structuredWorker || !isUnverifiableSessionRefusal(error)) { + throw error + } + const unknown = db.markWorkerTerminalReleaseUnknown(resource.id, error.message) + return { + receipt: { + dispatchId, + state: 'release_unknown', + processAction: 'none', + archive: archiveSummary(unknown), + lastError: unknown.release_error ?? error.message, + recovery: releaseUnknownRecovery(dispatchId) + } + } + } +} + +function isUnverifiableSessionRefusal(error: unknown): error is OrchestrationError { + return ( + error instanceof OrchestrationError && + (error.code === CODES.notLive || error.code === CODES.hostBoundary) + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-archive.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-archive.spec.ts new file mode 100644 index 00000000000..ac67fe66629 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-archive.spec.ts @@ -0,0 +1,79 @@ +import { appendFile, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' + +export function registerWorkerReleaseArchiveTests(): void { + function codexMessage(id: string, text: string): string { + return JSON.stringify({ + timestamp: '2026-08-03T12:00:00.000Z', + type: 'event_msg', + payload: { id, type: 'agent_message', message: text } + }) + } + + describe('orchestration worker release archive', () => { + const h = createOrchestrationWorkerReleaseHarness() + + afterEach(() => h.cleanup()) + + it('reads the original transcript after release, until the provider file disappears', async () => { + h.setup() + const directory = await mkdtemp(join(tmpdir(), 'orca-worker-release-snapshot-')) + const transcriptPath = join(directory, 'rollout.jsonl') + try { + await writeFile( + transcriptPath, + `${codexMessage('snapshot-one', 'frozen first')}\n${codexMessage('snapshot-two', 'frozen second')}\n` + ) + vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ + agent: 'codex', + processIncarnation: 'runtime_test:term_worker:1', + providerSession: { + key: 'codex:snapshot-session', + id: 'snapshot-session', + transcriptPath + } + } as never) + const { dispatchId } = await h.startSettledWorker() + await h.call('orchestration.workerRelease', { dispatch: dispatchId }) + expect(h.db.getWorkerTerminalArchive(dispatchId)?.content).not.toContain('frozen') + + // Like a live read, the first page is the newest messages; a cursor then follows the file. + const page = await h.call('orchestration.workerRead', { dispatch: dispatchId }) + const cursor = + typeof page === 'object' && page !== null && 'cursor' in page ? page.cursor : null + expect(page).toMatchObject({ + archived: true, + source: 'transcript', + transcript: { + messages: [ + { id: 'snapshot-one', blocks: [{ type: 'text', text: 'frozen first' }] }, + { id: 'snapshot-two', blocks: [{ type: 'text', text: 'frozen second' }] } + ] + } + }) + await appendFile(transcriptPath, `${codexMessage('resumed', 'after a resume')}\n`) + await expect( + h.call('orchestration.workerRead', { dispatch: dispatchId, cursor }) + ).resolves.toMatchObject({ + transcript: { + messages: [{ id: 'resumed', blocks: [{ type: 'text', text: 'after a resume' }] }] + } + }) + // A cursor from the live terminal belongs to output that was released. + await expect( + h.call('orchestration.workerRead', { dispatch: dispatchId, cursor: 1 }) + ).rejects.toThrow(/source changed/i) + + await rm(transcriptPath) + await expect( + h.call('orchestration.workerRead', { dispatch: dispatchId }) + ).rejects.toMatchObject({ code: 'archive_unavailable' }) + } finally { + await rm(directory, { recursive: true, force: true }) + } + }) + }) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-authority-contracts.test.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-authority-contracts.test.ts diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-close-error.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-close-error.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release-close-error.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-close-error.ts diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-completion.ts similarity index 84% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-completion.ts index 9ce58a6a211..6b6d943ee51 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-completion.ts @@ -1,25 +1,27 @@ -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import type { WorkerTerminalArchiveKind, - WorkerTerminalArchiveStatus, WorkerTerminalResourceRow, WorkerTerminalRetainedReason -} from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import { summarizeWorkerOutputArchive } from '../../../../orchestration/workers/archives/worker-output-archive' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import { describeUnconfirmedAgentStop } from '../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' -import { inspectWorkerTerminal } from './worker-observation' -import { orchestrationTimestampToMs } from './worker-output' +} from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { + releaseCommitFieldsForCapturedArchive, + releaseCommitFieldsForStoredArchive +} from '../../../../../orchestration/workers/archives/worker-output-archive' +import type { WorkerTerminalReleaseRuntime } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +import { describeUnconfirmedAgentStop } from '../../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import { inspectWorkerTerminal } from '../observation/worker-observation' +import { orchestrationTimestampToMs } from '../output/worker-output' import { archiveSummary } from './worker-terminal-resource-presentation' import { classifyWorkerTerminalCloseError } from './worker-release-close-error' import { workerTerminalLeaseIsCurrent } from './worker-terminal-release-lease' -import { resolveStructuredWorkerForDispatch } from '../structured-workers/orchestration-structured-worker-lifecycle' +import { resolveStructuredWorkerForDispatch } from '../../structured-workers/orchestration-structured-worker-lifecycle' import { stopStructuredWorkerForRelease } from './structured-worker-release-stop' -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' +import { isStructuredWorkerHandle } from '../../../../../../../shared/orchestration/workers/structured-worker-handle' import { captureWorkerReleaseArchive } from './worker-release-archive-capture' import { WorkerTerminalReleaseSingleFlight } from './worker-terminal-release-single-flight' import { releaseUnknownRecovery } from './worker-release-unknown-recovery' -import { yieldAutoReleaseToWorkingAgent } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield' +import { yieldAutoReleaseToWorkingAgent } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield' export type WorkerReleaseReceipt = { dispatchId: string @@ -157,12 +159,11 @@ async function completeWorkerTerminalReleaseOnce( } } const archive = db.getWorkerTerminalArchive(dispatchId) - let archiveSource = resource.archive_source as 'transcript' | 'terminal' | null - let archiveStatus: WorkerTerminalArchiveStatus | null = resource.archive_status - let capturedArchive: { kind: WorkerTerminalArchiveKind; content: string } | undefined const structured = resolveStructuredWorkerForDispatch(db, dispatchId) - if (!archive) { - const capture = await captureWorkerReleaseArchive({ + let recorded: { kind: WorkerTerminalArchiveKind; content: string } | undefined + let stored = archive ? releaseCommitFieldsForStoredArchive(archive) : undefined + if (!stored) { + const capture = captureWorkerReleaseArchive({ db, resource, runtime, @@ -174,21 +175,18 @@ async function completeWorkerTerminalReleaseOnce( if ('receipt' in capture) { return capture.receipt } - const { captured } = capture - capturedArchive = { kind: captured.kind, content: JSON.stringify(captured.content) } - archiveSource = captured.kind === 'terminal_tail' ? 'terminal' : 'transcript' - archiveStatus = captured.status - } else { - const stored = summarizeWorkerOutputArchive(archive) - archiveSource ??= stored.source - archiveStatus ??= stored.status + const { kind, content, ...fields } = releaseCommitFieldsForCapturedArchive(capture.captured) + recorded = { kind, content } + stored = fields } + const archiveSource = stored.archiveSource + const archiveStatus = stored.archiveStatus const committed = db.commitWorkerTerminalArchiveForRelease({ dispatchId, resourceId: resource.id, - ...capturedArchive, + ...recorded, archiveSource, - archiveStatus: archiveStatus === 'empty' ? 'empty' : 'captured' + archiveStatus }) const releasing = !isStillReleasing(committed) ? committed diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-evidence-contracts.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-evidence-contracts.test.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release-evidence-contracts.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-evidence-contracts.test.ts diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-inventory.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-inventory.spec.ts new file mode 100644 index 00000000000..1cf936f4d1a --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-inventory.spec.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' + +export function registerWorkerReleaseInventoryTests(): void { + describe('orchestration worker release inventory', () => { + const h = createOrchestrationWorkerReleaseHarness() + + afterEach(() => h.cleanup()) + + it('rejects exact reuse after release intent instead of closing the new worker', async () => { + h.setup() + const first = await h.startSettledWorker('succeeded') + expect(h.db.requestWorkerTerminalRelease(first.dispatchId).disposition).toBe('requested') + const nextTask = h.db.createTask({ spec: 'racing reuse', runId: h.activeRunId }) + + const attempted = (await h.call('orchestration.workerStart', { + task: nextTask.id, + from: 'term_coord', + terminal: 'term_worker' + })) as { state: string; lastError?: string } + + expect(attempted).toMatchObject({ state: 'failed' }) + expect(attempted.lastError).toMatch(/release.*progress/i) + expect(h.runtime.closeTerminal).not.toHaveBeenCalled() + await expect( + h.call('orchestration.workerRelease', { dispatch: first.dispatchId }) + ).resolves.toMatchObject({ state: 'released' }) + expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) + }) + }) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts new file mode 100644 index 00000000000..15258350c4d --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' + +import { registerBoundPty } from '../../../../../orca-runtime-tests/bind-first-pane.test-fixture' + +const h = createOrchestrationWorkerReleaseHarness() +beforeEach(() => h.setup()) +afterEach(() => h.cleanup()) + +// Boot-wait Keep open must find custody written at terminal creation, or a later release closes a kept pane (#19337, #19608). +it('a phone Keep open during the boot wait keeps the pane and fences the later release', async () => { + const gate = h.deferred() + vi.spyOn(h.runtime, 'waitForTerminal').mockReturnValue(gate.promise as never) + const task = h.db.createTask({ spec: 'mid-boot phone takeover', runId: h.activeRunId }) + const start = h.call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + agent: 'codex' + }) + await vi.waitFor(() => expect(h.runtime.waitForTerminal).toHaveBeenCalled()) + const dispatchId = ( + h.db.db.prepare("SELECT dispatch_id FROM worker_dispatches WHERE state = 'starting'").get() as { + dispatch_id: string + } + ).dispatch_id + + h.runtime.registerPreAllocatedHandleForPty('pty-worker', 'term_worker') + registerBoundPty(h.runtime, 'pty-worker', 'repo::worktree', null, { + tabId: 'tab_worker', + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + }) + vi.mocked(h.runtime.getTerminalPaneKey).mockRestore() + await expect( + h.call('orchestration.workerKeepOpen', { terminal: 'term_worker', keep: true }) + ).resolves.toEqual({ autoClose: { kept: true } }) + + gate.resolve({ + handle: 'term_worker', + condition: 'tui-idle', + satisfied: true, + status: 'running', + exitCode: null + }) + await expect(start).resolves.toMatchObject({ state: 'ready' }) + + h.settle(task.id, dispatchId, 'succeeded') + await expect( + h.call('orchestration.workerRelease', { dispatch: dispatchId }) + ).resolves.toMatchObject({ state: 'retained', reason: 'user_kept', processAction: 'none' }) + expect(h.runtime.closeTerminal).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts new file mode 100644 index 00000000000..3bc4e18bf9d --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts @@ -0,0 +1,216 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' +import { reconcileRequestedWorkerTerminalReleases } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-reconciliation' +import { OrcaRuntimeService } from '../../../../../orca-runtime' +import { isStreamingMethod, eraseRpcMethods, type RpcContext } from '../../../../core' +import { ORCHESTRATION_METHODS } from '../../orchestration' + +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((promiseResolve) => { + resolve = promiseResolve + }) + return { promise, resolve } +} + +describe('orchestration worker release recovery', () => { + let db: OrchestrationDb + let dbOpen = false + let runtime: OrcaRuntimeService + let ctx: RpcContext + let activeRunId: string + + const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + + function setup(): void { + db = new OrchestrationDb(':memory:') + dbOpen = true + runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_coord' ? coordinatorPaneKey : handle === 'term_worker' ? workerPaneKey : null + ) + vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => + handle === 'term_worker' ? 'runtime_test:term_worker:1' : null + ) + vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockImplementation((handle) => + handle === 'term_worker' + ? ({ + terminalHandle: handle, + paneKey: workerPaneKey, + processIncarnation: 'runtime_test:term_worker:1', + hostScope: { kind: 'local', hostId: 'local' } + } as never) + : null + ) + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + vi.spyOn(runtime, 'showTerminal').mockImplementation( + async (handle) => ({ handle, worktreeId: 'repo::worktree', status: 'running' }) as never + ) + vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockResolvedValue({ + id: 'repo::worktree' + } as never) + vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ + handle: 'term_worker', + worktreeId: 'repo::worktree', + title: 'worker' + }) + vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ + handle: 'term_worker', + condition: 'tui-idle', + satisfied: true, + status: 'running', + exitCode: null + }) + vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') + vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ + handle: 'term_worker', + accepted: true, + bytesWritten: 1 + }) + vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) + vi.spyOn(runtime, 'getExactWorkerProviderSession').mockReturnValue(null) + vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ + handle: 'term_worker', + status: 'running', + tail: ['worker output line 1', 'worker output line 2'], + truncated: false, + nextCursor: '2' + }) + vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({ + handle: 'term_worker', + tabId: 'tab-worker', + ptyKilled: true + }) + vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) + activeRunId = db.createRun({ + objective: 'Release recovery test Run', + coordinatorHandle: 'term_coord', + coordinatorPaneKey + }).id + ctx = { runtime } + } + + afterEach(() => { + if (dbOpen) { + dbOpen = false + db.close() + } + vi.restoreAllMocks() + }) + + async function call(name: string, params: Record) { + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) + if (!method || isStreamingMethod(method)) { + throw new Error(`Method not found: ${name}`) + } + const parsed = method.params ? method.params.parse(params) : undefined + return method.handler(parsed, ctx) + } + + async function startWorker(): Promise<{ taskId: string; dispatchId: string }> { + const task = db.createTask({ spec: 'release recovery fixture task', runId: activeRunId }) + const result = (await call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + agent: 'codex' + })) as { dispatchId: string; state: string } + expect(result.state).toBe('ready') + return { taskId: task.id, dispatchId: result.dispatchId } + } + + async function startSettledWorker( + outcome: 'succeeded' | 'failed' = 'succeeded' + ): Promise<{ taskId: string; dispatchId: string }> { + const worker = await startWorker() + expect( + db.settleWorkerReport({ + taskId: worker.taskId, + dispatchId: worker.dispatchId, + outcome, + result: `worker ${outcome}` + }).action + ).toBe('settled') + return worker + } + + it('settles a closed terminal after restart when exact process liveness is exited', async () => { + setup() + const { dispatchId } = await startSettledWorker() + const resource = db.getWorkerTerminalResourceByOwner(dispatchId) + expect(resource).toBeDefined() + + // Simulate a crash seam after closeTerminal succeeded but before its durable settlement. + vi.spyOn(db, 'settleWorkerTerminalRelease').mockImplementationOnce(() => { + throw new Error('SQLite interrupted after terminal close') + }) + await expect(call('orchestration.workerRelease', { dispatch: dispatchId })).rejects.toThrow( + 'SQLite interrupted after terminal close' + ) + expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('releasing') + expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) + + vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) + vi.mocked(runtime.getOrchestrationDispatchAuthority).mockReturnValue(null) + vi.mocked(runtime.getTerminalPaneKey).mockReturnValue(null) + vi.mocked(runtime.getTerminalProcessIncarnation).mockReturnValue(null) + vi.spyOn(runtime, 'inspectTerminalProcessIncarnationLiveness').mockResolvedValue('exited') + + await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ + attempted: 1, + released: 1, + pending: 0 + }) + expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') + expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) + expect(runtime.inspectTerminalProcessIncarnationLiveness).toHaveBeenCalledWith( + resource?.process_incarnation, + resource?.host_scope + ) + + // A replay sees no backlog and cannot issue another close. + await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ + attempted: 0 + }) + expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) + }) + + it('records one recovery attempt when reconciliation joins an interactive release', async () => { + setup() + const { dispatchId } = await startSettledWorker() + const resourceId = db.getWorkerTerminalResourceByOwner(dispatchId)?.id + expect(resourceId).toBeDefined() + const pendingClose = deferred>>() + vi.mocked(runtime.closeTerminal).mockReturnValue(pendingClose.promise) + + const interactive = call('orchestration.workerRelease', { dispatch: dispatchId }) + await vi.waitFor(() => expect(runtime.closeTerminal).toHaveBeenCalledTimes(1)) + const first = reconcileRequestedWorkerTerminalReleases(runtime) + const second = reconcileRequestedWorkerTerminalReleases(runtime) + expect(second).toBe(first) + pendingClose.resolve({ handle: 'term_worker', tabId: 'tab-worker', ptyKilled: true }) + + await expect(interactive).resolves.toMatchObject({ state: 'released' }) + await expect(Promise.all([first, second])).resolves.toEqual([ + expect.objectContaining({ attempted: 1, released: 1 }), + expect.objectContaining({ attempted: 1, released: 1 }) + ]) + expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) + expect(db.getWorkerTerminalResource(resourceId!)).toMatchObject({ + recovery_attempt_count: 1, + last_recovery_at: expect.any(String) + }) + + await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ + attempted: 0 + }) + expect(db.getWorkerTerminalResource(resourceId!)?.recovery_attempt_count).toBe(1) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-runtime-incarnation.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-runtime-incarnation.spec.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release-runtime-incarnation.spec.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-runtime-incarnation.spec.ts index fced8246c21..b8049001376 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-runtime-incarnation.spec.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-runtime-incarnation.spec.ts @@ -1,8 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { inspectWorkerTerminal } from './worker-observation' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' -import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' -import { registerBoundPty } from '../../../../orca-runtime-tests/bind-first-pane.test-fixture' +import { inspectWorkerTerminal } from '../observation/worker-observation' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' +import { makePaneKey } from '../../../../../../../shared/workspace-layout/stable-pane-id' +import { registerBoundPty } from '../../../../../orca-runtime-tests/bind-first-pane.test-fixture' export function registerWorkerReleaseRuntimeIncarnationTests(): void { const PTY_ID = 'runtime_test:term_worker' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-unknown-recovery.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-unknown-recovery.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release-unknown-recovery.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-unknown-recovery.ts diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts new file mode 100644 index 00000000000..6c12828fd09 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts @@ -0,0 +1,27 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' + +describe('orchestration worker release', () => { + const h = createOrchestrationWorkerReleaseHarness() + + afterEach(() => h.cleanup()) + + it('does not claim retention succeeded after terminal close was committed', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + const pendingClose = h.deferred>>() + vi.mocked(h.runtime.closeTerminal).mockReturnValue(pendingClose.promise) + + const release = h.call('orchestration.workerRelease', { dispatch: dispatchId }) + await vi.waitFor(() => expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1)) + await expect( + h.call('orchestration.workerRetain', { dispatch: dispatchId }) + ).resolves.toMatchObject({ state: 'release_pending' }) + expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('releasing') + pendingClose.resolve({ handle: 'term_worker', tabId: 'tab-worker', ptyKilled: true }) + + await expect(release).resolves.toMatchObject({ state: 'released' }) + expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-release-lease.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-release-lease.ts new file mode 100644 index 00000000000..3fa59220893 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-release-lease.ts @@ -0,0 +1,56 @@ +import type { WorkerTerminalReleaseRuntime } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { WorkerTerminalResourceRow } from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import type { WorkerDispatchRow } from '../../../../../orchestration/db/orchestration-records' +import { resolveStructuredWorkerIdentity } from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' +import { isStructuredWorkerHandle } from '../../../../../../../shared/orchestration/workers/structured-worker-handle' + +export function workerTerminalLeaseIsCurrent( + runtime: WorkerTerminalReleaseRuntime, + db: OrchestrationDb, + dispatchId: string, + resource: WorkerTerminalResourceRow, + // Probe the live reminted handle; compare durable worker/resource handles only for stored identity. + liveTerminalHandle: string +): boolean { + const worker = db.getWorkerDispatch(dispatchId) + if (isStructuredWorkerHandle(resource.terminal_handle)) { + return structuredWorkerTerminalLeaseIsCurrent(db, dispatchId, worker, resource) + } + const authority = runtime.getOrchestrationDispatchAuthority(liveTerminalHandle) + // Exited PTYs keep identity/host evidence but cannot mint launch authority. + return Boolean( + worker?.agent_terminal_handle === resource.terminal_handle && + (authority + ? resource.host_scope === JSON.stringify(authority.hostScope) + : runtime.getTerminalLivenessVerdict(liveTerminalHandle)?.status === 'exited') && + db.isDispatchProcessCurrent({ + dispatchId, + paneKey: runtime.getTerminalPaneKey(liveTerminalHandle), + processIncarnation: runtime.getTerminalProcessIncarnation(liveTerminalHandle) + }) && + !db.workerTerminalResourceHasIdentityConflict(resource.id) + ) +} + +/** Check durable pane/lineage identity independently of child liveness. + * Requiring installed session records after restart would falsely retain requested releases as identity_unproven. */ +function structuredWorkerTerminalLeaseIsCurrent( + db: OrchestrationDb, + dispatchId: string, + worker: WorkerDispatchRow | undefined, + resource: WorkerTerminalResourceRow +): boolean { + const identity = resolveStructuredWorkerIdentity(resource.terminal_handle, db) + return Boolean( + worker?.agent_terminal_handle === resource.terminal_handle && + identity && + resource.host_scope === JSON.stringify(identity.hostScope) && + db.isDispatchProcessCurrent({ + dispatchId, + paneKey: identity.paneKey, + processIncarnation: identity.processIncarnation + }) && + !db.workerTerminalResourceHasIdentityConflict(resource.id) + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-single-flight.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-release-single-flight.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-single-flight.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-release-single-flight.ts index e5758be99a6..a83822db587 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-single-flight.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-release-single-flight.ts @@ -1,4 +1,4 @@ -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +import type { WorkerTerminalReleaseRuntime } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' type ActiveRelease = { promise: Promise; recoveryRequested: boolean } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-resource-presentation.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-resource-presentation.ts similarity index 94% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-resource-presentation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-resource-presentation.ts index 218f79f1d49..0b2451a6c96 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-resource-presentation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-terminal-resource-presentation.ts @@ -1,8 +1,8 @@ -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import { liveWorkerTerminalAutoReleaseAt, type WorkerTerminalResourceRow -} from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +} from '../../../../../orchestration/terminal-authority/release/worker-terminal-ownership' import type { WorkerReleaseReceipt } from './worker-release-completion' export function exposeWorkerTerminalResource(resource: WorkerTerminalResourceRow): { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/helper-start-scope.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/helper-start-scope.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/helper-start-scope.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/admission/helper-start-scope.ts index f83ccf4d57f..28c24ea35a6 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/helper-start-scope.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/helper-start-scope.ts @@ -1,14 +1,14 @@ import type { DispatchContextRow, TaskRow -} from '../../../../orchestration/db/orchestration-records' -import type { OrchestrationAdmission } from '../../../../orchestration/addressing/orchestration-admission' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +} from '../../../../../../orchestration/db/orchestration-records' +import type { OrchestrationAdmission } from '../../../../../../orchestration/addressing/orchestration-admission' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' import { createPreviousCustodianLookup, type CustodyReaders -} from '../../../../orchestration/db/worker-terminal/worker-custody-read' -import type { WorkerFollowUp } from './worker-follow-up-placement' +} from '../../../../../../orchestration/db/worker-terminal/worker-custody-read' +import type { WorkerFollowUp } from '../../follow-up/worker-follow-up-placement' export type HelperDispatch = Pick< DispatchContextRow, | 'id' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/task-deps-argument.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/task-deps-argument.ts similarity index 86% rename from src/main/runtime/rpc/methods/orchestration/worker/task-deps-argument.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/admission/task-deps-argument.ts index 1028a80097d..29dcc9460a7 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/task-deps-argument.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/task-deps-argument.ts @@ -1,4 +1,4 @@ -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' /** Parses the `--deps` JSON argument shared by the local and federated start paths. */ export function parseTaskDeps(value: string | undefined): string[] | undefined { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-authority.ts similarity index 81% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-authority.ts index d54f92f4c16..917181c83e2 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-authority.ts @@ -1,23 +1,23 @@ -import type { WorkerFollowUp } from './worker-follow-up-placement' -import { createWorkerFollowUpQualification } from './worker-follow-up-admission' -import { liveDispatchCreatorEvaluation } from '../../../../orchestration/db/dispatch-depth' +import type { WorkerFollowUp } from '../../follow-up/worker-follow-up-placement' +import { createWorkerFollowUpQualification } from '../../follow-up/worker-follow-up-admission' +import { liveDispatchCreatorEvaluation } from '../../../../../../orchestration/db/dispatch-depth' import { selectExistingWorkerStartRun } from './worker-start-run-authority' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' +import type { OrchestrationEntryCaller } from '../../../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../../../shared/orchestration/mailbox/orchestration-party-identity' import type { DispatchContextRow, RunRow, TaskRow -} from '../../../../orchestration/db/orchestration-records' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { resolveDispatchCreator } from '../runs/dispatch-creator' -import { createBoundRun } from '../runs/runs' -import { ROOT_DISPATCH_DEPTH } from '../../../../../../shared/orchestration/workers/nested-worker-depth' -import { readCustodyCohort } from '../../../../orchestration/db/worker-terminal/worker-terminal-transfer' +} from '../../../../../../orchestration/db/orchestration-records' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import { resolveDispatchCreator } from '../../../runs/dispatch-creator' +import { createBoundRun } from '../../../runs/runs' +import { ROOT_DISPATCH_DEPTH } from '../../../../../../../../shared/orchestration/workers/nested-worker-depth' +import { readCustodyCohort } from '../../../../../../orchestration/db/worker-terminal/worker-terminal-transfer' import { createHelperStartScope } from './helper-start-scope' -import { requireOrchestrationAdmission } from '../../../../orchestration/addressing/orchestration-admission' +import { requireOrchestrationAdmission } from '../../../../../../orchestration/addressing/orchestration-admission' export type WorkerStartRunBinding = { run: RunRow; created: boolean } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-busy-terminal.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-busy-terminal.test.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-busy-terminal.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-busy-terminal.test.ts index ec82660373d..2a259dab15a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-busy-terminal.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-busy-terminal.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { getFollowUpDispatch } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +import { getFollowUpDispatch } from '../../../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { createOrchestrationWorkerReleaseHarness } from '../../testing/worker-release.test-support' describe('worker-start onto a terminal another Dispatch holds', () => { const h = createOrchestrationWorkerReleaseHarness() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-budget.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-prompt-budget.ts similarity index 80% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-budget.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-prompt-budget.ts index 8b4bbe9c816..17de7d2625a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-budget.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-prompt-budget.ts @@ -1,8 +1,8 @@ import { isWorkerStartTaskSpecTooLarge, ORCHESTRATION_WORKER_START_TASK_SPEC_MAX_BYTES -} from '../../../../../../shared/orchestration/workers/orchestration-worker-start-prompt-budget' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +} from '../../../../../../../../shared/orchestration/workers/orchestration-worker-start-prompt-budget' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' export async function assertWorkerStartTaskSpecWithinPromptBudget(spec: string): Promise { if (!(await isWorkerStartTaskSpecTooLarge(spec))) { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-run-authority.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-run-authority.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-run-authority.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-run-authority.ts index 69179f3b61a..b5c7da1064a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-run-authority.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/admission/worker-start-run-authority.ts @@ -1,8 +1,8 @@ import { requireOrchestrationAdmission, type OrchestrationAdmission -} from '../../../../orchestration/addressing/orchestration-admission' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +} from '../../../../../../orchestration/addressing/orchestration-admission' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' /** Existing-Run authority is shared; binding/creation and placement remain command effects. */ export function existingWorkerStartRunAdmission< diff --git a/src/main/runtime/rpc/methods/orchestration/worker/failed-start-retry-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/failed-start-retry-release.test.ts similarity index 78% rename from src/main/runtime/rpc/methods/orchestration/worker/failed-start-retry-release.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/failed-start-retry-release.test.ts index 15218297351..edebd6335a0 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/failed-start-retry-release.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/failed-start-retry-release.test.ts @@ -1,8 +1,8 @@ /** Failed starts retain user-owned panes; retry-of must release the prior agent while launching in a new terminal, preventing one leaked agent per retry. */ import { afterEach, describe, expect, it, vi } from 'vitest' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' -import type { RuntimeTerminalWait } from '../../../../../../shared/runtime-terminal-contracts' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' +import type { RuntimeTerminalWait } from '../../../../../../../shared/runtime-terminal-contracts' const RETRY_PANE_KEY = 'tab_retry:cccccccc-cccc-4ccc-8ccc-cccccccccccc' const BLOCKED_WAIT: RuntimeTerminalWait = { @@ -96,7 +96,7 @@ describe('retrying a failed worker-start', () => { await vi.waitFor(() => expect(h.db.getWorkerTerminalResourceByOwner(failed.dispatchId)).toMatchObject({ release_state: 'released', - archive_status: 'captured' + archive_status: 'unavailable' }) ) expect(h.runtime.closeTerminal).toHaveBeenCalledWith('term_worker') @@ -104,20 +104,6 @@ describe('retrying a failed worker-start', () => { expect(h.db.getWorkerTerminalArchive(failed.dispatchId)).toBeTruthy() }) - it('also releases a worker that ran and reported its own failure', async () => { - h.setup() - giveRetryItsOwnTerminal() - const ran = await h.startSettledWorker('failed') - vi.spyOn(h.runtime, 'waitForTerminal').mockResolvedValue(BLOCKED_WAIT) - - await retry(ran) - - await vi.waitFor(() => - expect(h.db.getWorkerTerminalResourceByOwner(ran.dispatchId)?.release_state).toBe('released') - ) - expect(h.runtime.closeTerminal).toHaveBeenCalledWith('term_worker') - }) - it('keeps a pane the user kept open', async () => { h.setup() const failed = await failFirstStart() @@ -132,28 +118,6 @@ describe('retrying a failed worker-start', () => { expect(h.runtime.closeTerminal).not.toHaveBeenCalled() }) - it('leaves the pane alone when the retry reuses a terminal explicitly', async () => { - h.setup() - const failed = await failFirstStart() - vi.spyOn(h.runtime, 'waitForTerminal').mockResolvedValue({ - ...BLOCKED_WAIT, - satisfied: true, - blockedReason: undefined - }) - - await h.call('orchestration.workerStart', { - task: failed.taskId, - retryOf: failed.dispatchId, - from: 'term_coord', - terminal: 'term_retry' - }) - - expect(h.db.getWorkerTerminalResourceByOwner(failed.dispatchId)?.release_state).toBe( - 'not_requested' - ) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - }) - it('stops a retry loop at the third failed start', async () => { h.setup() const first = await failFirstStart() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/failed-worker-start-report.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/failed-worker-start-report.test.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/worker/failed-worker-start-report.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/failed-worker-start-report.test.ts index 6219ace0af1..3edacf8f406 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/failed-worker-start-report.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/failed-worker-start-report.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' describe('a worker-start that fails', () => { const h = createOrchestrationWorkerReleaseHarness() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-configured-agent-preflight.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-configured-agent-preflight.ts similarity index 81% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-configured-agent-preflight.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-configured-agent-preflight.ts index 764ebb328ff..a7839eaf673 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-configured-agent-preflight.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-configured-agent-preflight.ts @@ -1,6 +1,6 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import { isTuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent-config' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' import { prepareFederationAttachmentWorkerStart } from './worker-start-validation' type WorkerAgentTarget = { repo?: string; worktree?: string } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-launch-preferences.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-launch-preferences.ts index 7eb235cd011..71b4a7a77c2 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-launch-preferences.ts @@ -1,8 +1,8 @@ -import type { AgentLaunchPreferences } from '../../../../../../shared/agent-session/agent-session-host-authority' -import { checkAgentLaunchModelPreferences } from '../../../../../../shared/agent-launch/choices/agent-launch-model-preferences' -import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { AgentLaunchPreferences } from '../../../../../../../../shared/agent-session/agent-session-host-authority' +import { checkAgentLaunchModelPreferences } from '../../../../../../../../shared/agent-launch/choices/agent-launch-model-preferences' +import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { TuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' export type OrchestrationWorkerLaunchSelection = { agent: TuiAgent | null diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-opencode-model-preflight.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-opencode-model-preflight.ts similarity index 94% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-opencode-model-preflight.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-opencode-model-preflight.ts index af0c4aa8db7..607ab317703 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-opencode-model-preflight.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-opencode-model-preflight.ts @@ -3,7 +3,7 @@ import { resolveWorkerConfiguredAgentParams } from './worker-configured-agent-preflight' import type { prepareFederationAttachmentWorkerStart } from './worker-start-validation' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' export async function probeWorkerOpenCodeModelLaunchSupport( runtime: OrcaRuntimeService, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-start-budgets.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-start-budgets.ts index 9bfa775f6b9..cb6cac8a613 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-start-budgets.ts @@ -4,7 +4,7 @@ import { resolveFederationAttachDeadlineMs, resolveWorkerStartReadinessTimeoutMs, resolveWorkerStartClientTimeoutMs -} from '../../../../../../shared/orchestration/orchestration-timing-budgets' +} from '../../../../../../../../shared/orchestration/orchestration-timing-budgets' export function resolveFederatedWorkerStartBudgets( timeoutMs: number | undefined, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-start-validation.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-start-validation.ts index 5e0a0977644..a4f65a53529 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/launch/worker-start-validation.ts @@ -1,14 +1,14 @@ -import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { FederationAttachStartInput } from '../../../../../../shared/rpc-contract/orchestration-federation-start-params' +import { isTuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent-config' +import type { TuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' +import type { FederationAttachStartInput } from '../../../../../../../../shared/rpc-contract/orchestration/orchestration-federation-start-params' import { assertWorkerLaunchPreferencesCreateTerminal, createWorkerLaunchReceipt, resolveWorkerLaunchPreferences } from './worker-launch-preferences' -import type { WorkerStartInput } from './worker-start-schema' +import type { WorkerStartInput } from '../worker-start-input' type WorkerStartLaunch = ReturnType diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/local-worker-start-dispatch.ts similarity index 84% rename from src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/local-worker-start-dispatch.ts index 50ee585d311..dc8832e6b4c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/local-worker-start-dispatch.ts @@ -1,10 +1,10 @@ -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../shared/agent-launch/contracts/agent-launch-intent' -import type { OrchestrationWorkerLaunchReceipt } from './worker-launch-preferences' -import type { WorkerStartInput } from './worker-start-schema' -import type { RunRow } from '../../../../orchestration/db/orchestration-records' +import type { TuiAgent } from '../../../../../../../shared/agent-launch/catalog/tui-agent' +import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../../shared/agent-launch/contracts/agent-launch-intent' +import type { OrchestrationWorkerLaunchReceipt } from './launch/worker-launch-preferences' +import type { WorkerStartInput } from './worker-start-input' +import type { RunRow } from '../../../../../orchestration/db/orchestration-records' import type { startLocalWorker } from './local-worker-start' -import { resolveDispatchCreator } from '../runs/dispatch-creator' +import { resolveDispatchCreator } from '../../runs/dispatch-creator' export function createLocalWorkerStartDispatch( { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/local-worker-start.ts similarity index 78% rename from src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/local-worker-start.ts index 6d7446b10f6..60589e0be52 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/local-worker-start.ts @@ -1,44 +1,44 @@ import { createLocalWorkerStartDispatch } from './local-worker-start-dispatch' -import { refuseClaimedWorkerTerminal } from '../../../../orchestration/db/worker-dispatch/worker-terminal-claim' -import { probeWorkerOpenCodeModelLaunchSupport } from './worker-opencode-model-preflight' -import { resolveWorkerConfiguredAgentParams } from './worker-configured-agent-preflight' -import { waitForWorkerAgentReady } from '../../../../terminal/wait/launched-agent-composer-readiness' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { describeTerminalWaitBlockedReason } from '../../../../../../shared/terminal/runtime-policy/terminal-wait-blocked-reason-legacy-alias' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { refuseClaimedWorkerTerminal } from '../../../../../orchestration/db/worker-dispatch/worker-terminal-claim' +import { probeWorkerOpenCodeModelLaunchSupport } from './launch/worker-opencode-model-preflight' +import { resolveWorkerConfiguredAgentParams } from './launch/worker-configured-agent-preflight' +import { waitForWorkerAgentReady } from '../../../../../terminal/wait/launched-agent-composer-readiness' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { describeTerminalWaitBlockedReason } from '../../../../../../../shared/terminal/runtime-policy/terminal-wait-blocked-reason-legacy-alias' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' import type { DispatchContextRow, RunRow, TaskRow -} from '../../../../orchestration/db/orchestration-records' -import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' -import { resolveDispatchCallerWorktreeId } from '../orchestration-caller-workspace' -import { resolveWorkerStartModeOnHost } from '../structured-workers/orchestration-worker-start-mode' -import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../shared/agent-launch/contracts/agent-launch-intent' -import { EXISTING_WORKTREE_SETUP, placeWorkerAgent } from './worker-start-agent-placement' -import { awaitStructuredWorkerSetupGate } from './worker-start-structured-setup-gate' -import { assertOrchestrationWorktreeCreationSupported } from './folder-worktree-placement' -import { resolveWorkerWorktreeCreationTarget } from './worker-worktree-creation' -import type { WorkerStartInput } from './worker-start-schema' +} from '../../../../../orchestration/db/orchestration-records' +import type { OrchestrationEntryCaller } from '../../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../../shared/orchestration/mailbox/orchestration-party-identity' +import { resolveDispatchCallerWorktreeId } from '../../orchestration-caller-workspace' +import { resolveWorkerStartModeOnHost } from '../../structured-workers/orchestration-worker-start-mode' +import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../../shared/agent-launch/contracts/agent-launch-intent' +import { EXISTING_WORKTREE_SETUP, placeWorkerAgent } from './placement/worker-start-agent-placement' +import { awaitStructuredWorkerSetupGate } from './readiness/worker-start-structured-setup-gate' +import { assertOrchestrationWorktreeCreationSupported } from './placement/folder-worktree-placement' +import { resolveWorkerWorktreeCreationTarget } from './placement/worker-worktree-creation' +import type { WorkerStartInput } from './worker-start-input' import { persistGatedSetupSpawnFailure, persistWorkerReadinessStage, persistWorkerSetupWaitOutcome -} from './worker-setup-gate' +} from './readiness/worker-setup-gate' import { failWorkerStartWithReceipt } from './worker-start-receipt' -import { assertExplicitWorkerUsable } from './explicit-worker-terminal-validation' -import { resolveDispatchAssigneeParty } from '../../../../orchestration/addressing/orchestration-party' -import { chatAssigneeOf, chatWorkerMode } from '../chat-assignee-admission' -import { recordCreatedWorkerTerminalCustody } from './created-worker-terminal-custody' -import { releaseRetriedWorkerTerminal } from './retried-worker-terminal-release' -import { requireWorkerAuthority, type WorkerEffect } from './worker-topology' -import { prepareLocalWorkerStart } from './worker-start-validation' -import { deliverAndSettleWorkerStartReadiness } from './worker-start-readiness-settlement' +import { assertExplicitWorkerUsable } from './placement/explicit-worker-terminal-validation' +import { resolveDispatchAssigneeParty } from '../../../../../orchestration/addressing/orchestration-party' +import { chatAssigneeOf, chatWorkerMode } from '../../chat-assignee-admission' +import { recordCreatedWorkerTerminalCustody } from './placement/created-worker-terminal-custody' +import { releaseRetriedWorkerTerminal } from '../release/retried-worker-terminal-release' +import { requireWorkerAuthority, type WorkerEffect } from './placement/worker-placement-topology' +import { prepareLocalWorkerStart } from './launch/worker-start-validation' +import { deliverAndSettleWorkerStartReadiness } from './readiness/worker-start-readiness-settlement' import type { WorkerStartMutation } from './worker-start-mutation' -import { prepareWorkerStartCard } from '../../../../orchestration/workers/launch/worker-start-card' -import { rebindReusedStructuredWorker } from '../structured-workers/orchestration-structured-worker-session' -import { placedWorkerParty, type WorkerFollowUp } from './worker-follow-up-placement' +import { prepareWorkerStartCard } from '../../../../../orchestration/workers/launch/worker-start-card' +import { rebindReusedStructuredWorker } from '../../structured-workers/orchestration-structured-worker-session' +import { placedWorkerParty, type WorkerFollowUp } from '../follow-up/worker-follow-up-placement' export async function startLocalWorker(args: { params: WorkerStartInput @@ -306,7 +306,8 @@ export async function startLocalWorker(args: { dispatchId: started.dispatch.id, workerAddress: terminalHandle, task: task.spec, - agent: agent ?? null + agent: agent ?? null, + followUp: args.followUp && { of: args.followUp.of, reopened: Boolean(placed?.reopened) } }) } return result diff --git a/src/main/runtime/rpc/methods/orchestration/worker/created-worker-terminal-custody.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/created-worker-terminal-custody.ts similarity index 78% rename from src/main/runtime/rpc/methods/orchestration/worker/created-worker-terminal-custody.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/placement/created-worker-terminal-custody.ts index 4f5e2dabb4b..5d8c5b45113 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/created-worker-terminal-custody.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/created-worker-terminal-custody.ts @@ -1,6 +1,6 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { requireWorkerAuthority } from './worker-topology' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import { requireWorkerAuthority } from './worker-placement-topology' /** Record created PTY custody before boot so user input can revoke ownership before worker-release cleanup. * Dispatch authority still waits for readiness; reused caller panes and structured sessions have no custody gap. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/explicit-worker-terminal-validation.ts similarity index 82% rename from src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/placement/explicit-worker-terminal-validation.ts index 6adb724d6f9..a9e8a05884f 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/explicit-worker-terminal-validation.ts @@ -1,19 +1,19 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { isPeerCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' +import { isPeerCaller } from '../../../../../../orchestration/addressing/orchestration-caller-identity' +import { isStructuredWorkerHandle } from '../../../../../../../../shared/orchestration/workers/structured-worker-handle' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity, OrchestrationPartyIdentity as OrchestrationParty -} from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { OrcaSessionId } from '../../../../../../shared/orca-session-address' -import { formatOrcaSessionAddress } from '../../../../../../shared/orca-session-address' +} from '../../../../../../../../shared/orchestration/mailbox/orchestration-party-identity' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import type { OrcaSessionId } from '../../../../../../../../shared/orca-session-address' +import { formatOrcaSessionAddress } from '../../../../../../../../shared/orca-session-address' import { admitChatAssignee, chatAssigneeOf, refuseChatSelfAssignment -} from '../chat-assignee-admission' +} from '../../../chat-assignee-admission' /** Before any effects, refuse coordinator self-assignment, foreign-workspace panes and terminals without agents. */ export async function assertExplicitWorkerTerminalUsable(args: { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/placement/folder-worktree-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/folder-worktree-placement.ts new file mode 100644 index 00000000000..8d66ce6e372 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/folder-worktree-placement.ts @@ -0,0 +1,17 @@ +import { isFolderRepo } from '../../../../../../../../shared/repo-kind' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' + +export async function assertOrchestrationWorktreeCreationSupported(args: { + runtime: OrcaRuntimeService + repoSelector: string + existingPlacement: string +}): Promise { + if (!isFolderRepo(await args.runtime.showRepo(args.repoSelector))) { + return + } + throw new OrchestrationError( + 'invalid_argument', + `Folder projects cannot create orchestration worktrees; use ${args.existingPlacement}.` + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-new-worktree-start.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-new-worktree-start.test.ts new file mode 100644 index 00000000000..d76ad9c107f --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-new-worktree-start.test.ts @@ -0,0 +1,274 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { OrcaRuntimeService } from '../../../../../../orca-runtime' +import { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import '../../../../../../orchestration/db/contract-constants' +import '../../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../../orchestration/db/attempt-outcome-projection' +import { RpcDispatcher } from '../../../../../dispatcher' +import type { RpcRequest } from '../../../../../core' +import { ORCHESTRATION_METHODS } from '../../../orchestration' +import '../launch/worker-opencode-model-preflight' +import '../../../../../../../../shared/rpc-contract/orchestration/orchestration-federation-start-params' + +describe('orchestration new-worktree workers', () => { + const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let runId: string + const paths: string[] = [] + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + runId = db.createRun({ + objective: 'Test new-worktree workers', + coordinatorHandle: 'term_coord', + coordinatorPaneKey + }).id + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_coord' + ? coordinatorPaneKey + : handle === 'term_worker' + ? 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + : null + ) + vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => + handle === 'term_worker' ? 'runtime_test:term_worker:1' : null + ) + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ + handle: 'term_coord', + worktreeId: 'repo::parent', + status: 'running' + } as never) + vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({ + id: 'repo::parent', + repoId: 'repo' + } as never) + vi.spyOn(runtime, 'showRepo').mockResolvedValue({ + id: 'repo', + kind: 'git' + } as never) + vi.spyOn(runtime, 'createTerminal') + vi.spyOn(runtime, 'listTerminals').mockResolvedValue({ + terminals: [{ handle: 'term_worker', title: 'Codex' }], + totalCount: 1, + truncated: false + } as never) + vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ + handle: 'term_worker', + condition: 'tui-idle', + satisfied: true, + status: 'running', + exitCode: null + }) + vi.spyOn(runtime, 'waitForSetupTerminalCompletion').mockReturnValue( + new Promise(() => undefined) + ) + vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') + vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ + handle: 'term_worker', + accepted: true, + bytesWritten: 1 + }) + }) + + afterEach(() => { + db.close() + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + }) + + async function startWorker(overrides: Record = {}) { + const task = db.createTask({ spec: 'new-worktree task', runId }) + const method = ORCHESTRATION_METHODS.find( + (candidate) => candidate.name === 'orchestration.workerStart' + ) + if (!method) { + throw new Error('workerStart method is not registered') + } + const params = method.params!.parse({ + task: task.id, + from: 'term_coord', + worktree: 'new-child', + name: 'new-worker', + agent: 'codex', + ...overrides + }) + const result = await method.handler(params, { runtime }) + return { result, task } + } + + function mockCreatedWorktree(options?: { + hookFound?: boolean + startupPolicy?: 'start-immediately' | 'wait-for-setup' + state?: 'running' | 'skipped' | 'not_configured' | 'spawn_failed' + terminals?: { handle: string; title: string }[] + setupTerminalHandle?: string + }) { + const hookFound = options?.hookFound ?? true + const state = options?.state ?? (hookFound ? 'running' : 'not_configured') + vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({ + worktree: { id: 'repo::created', repoId: 'repo' }, + startupTerminal: { spawned: true, handle: 'term_worker' }, + setupReceipt: { + requested: state === 'skipped' ? 'skip' : 'run', + hookFound, + startupPolicy: options?.startupPolicy ?? 'start-immediately', + state, + terminalHandle: + options?.setupTerminalHandle ?? + options?.terminals?.find((terminal) => terminal.title === 'Setup')?.handle + } + } as never) + if (options?.terminals) { + vi.mocked(runtime.listTerminals).mockResolvedValue({ + terminals: options.terminals, + totalCount: options.terminals.length, + truncated: false + } as never) + } + } + + // Composer and idle readiness paths must both record setup evidence; the composer path previously dropped it. + + it('does not inject task input when the gated setup terminal fails to start', async () => { + mockCreatedWorktree({ startupPolicy: 'wait-for-setup', state: 'spawn_failed' }) + vi.mocked(runtime.waitForTerminal).mockResolvedValue({ + handle: 'term_worker', + condition: 'tui-idle', + satisfied: false, + status: 'exited', + exitCode: 1 + }) + + const { result, task } = await startWorker() + + expect(result).toMatchObject({ + state: 'failed', + failedStage: 'setup_start', + setup: { startupPolicy: 'wait-for-setup', state: 'spawn_failed' }, + effects: expect.arrayContaining([ + expect.objectContaining({ kind: 'setup', state: 'spawn_failed' }) + ]) + }) + expect(db.getTask(task.id)?.status).toBe('failed') + expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() + }) + + it('returns outcome unknown when worktree creation may have been accepted remotely', async () => { + vi.spyOn(runtime, 'createManagedWorktree').mockRejectedValue( + Object.assign(new Error('connection closed after request acceptance'), { + code: 'operation_unknown' + }) + ) + + const { result, task } = await startWorker() + + expect(result).toMatchObject({ + state: 'outcome_unknown', + failedStage: 'worktree_create' + }) + expect(db.getTask(task.id)?.status).toBe('blocked') + }) + + it('replays a dispatch-input failure after restart without creating another worker', async () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-worker-start-replay-')) + paths.push(dir) + db.close() + db = new OrchestrationDb(join(dir, 'orchestration.db')) + runtime.setOrchestrationDb(db) + runId = db.createRun({ + objective: 'Recover dispatch input', + coordinatorHandle: 'term_coord', + coordinatorPaneKey + }).id + mockCreatedWorktree({ hookFound: false }) + vi.mocked(runtime.sendTerminalAgentPrompt).mockRejectedValueOnce( + new Error('connection closed before dispatch input was accepted') + ) + const task = db.createTask({ spec: 'recover dispatch input', runId }) + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + const request: RpcRequest = { + id: 'rpc_worker_start', + authToken: 'caller-token', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: 'worker_start_request', + method: 'orchestration.workerStart', + params: { + task: task.id, + from: 'term_coord', + worktree: 'new-child', + name: 'recover-input-worker', + agent: 'codex' + } + } + + const first = await dispatcher.dispatch(request) + if (!first.ok) { + throw new Error(`Initial worker start failed: ${first.error.code}`) + } + const firstReceipt = first.result as { + dispatchId: string + residualResources: unknown[] + } + db.close() + + db = new OrchestrationDb(join(dir, 'orchestration.db')) + const restartedRuntime = new OrcaRuntimeService() + restartedRuntime.setOrchestrationDb(db) + vi.spyOn(restartedRuntime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_coord_reminted' + ? `tab_coord_reminted:${coordinatorPaneKey.split(':')[1]}` + : null + ) + const recreateWorktree = vi + .spyOn(restartedRuntime, 'createManagedWorktree') + .mockRejectedValue(new Error('replay recreated the worktree')) + const reinjectPrompt = vi + .spyOn(restartedRuntime, 'sendTerminalAgentPrompt') + .mockRejectedValue(new Error('replay reinjected the prompt')) + const restartedDispatcher = new RpcDispatcher({ + runtime: restartedRuntime, + methods: ORCHESTRATION_METHODS + }) + const replay = await restartedDispatcher.dispatch({ + ...request, + id: 'rpc_worker_start_retry', + authToken: 'caller-token-after-restart', + params: { ...(request.params as Record), from: 'term_coord_reminted' } + }) + + expect(first).toMatchObject({ + ok: true, + result: { + state: 'failed', + failedStage: 'dispatch_input', + residualResources: expect.arrayContaining([ + expect.objectContaining({ kind: 'worktree', id: 'repo::created' }), + expect.objectContaining({ kind: 'terminal', id: 'term_worker' }) + ]), + mutation: { requestId: 'worker_start_request', replayed: false } + } + }) + expect(replay).toMatchObject({ + ok: true, + result: { + dispatchId: firstReceipt.dispatchId, + state: 'failed', + failedStage: 'dispatch_input', + residualResources: firstReceipt.residualResources, + mutation: { requestId: 'worker_start_request', replayed: true } + } + }) + expect(recreateWorktree).not.toHaveBeenCalled() + expect(reinjectPrompt).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-placement-topology.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-placement-topology.ts new file mode 100644 index 00000000000..d7ba4cb6641 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-placement-topology.ts @@ -0,0 +1,205 @@ +import type { RuntimeTerminalCreate } from '../../../../../../../../shared/runtime-terminal-create-contract' +import type { AgentLaunchPreferences } from '../../../../../../../../shared/agent-session/agent-session-host-authority' +import { narrowStructuredLaunchSeedOptions } from '../../../../../../../../shared/native-chat/input/native-chat-session-option-defaults' +import type { TuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import { createStructuredWorkerSession } from '../../../structured-workers/orchestration-structured-worker-session' +import { dispatchReportMailbox } from '../../../../../../orchestration/workers/reports/dispatch-report-mailbox' + +export type WorkerEffect = { + kind: 'worktree' | 'terminal' | 'setup' | 'dispatch_input' + action?: string + role?: string + id?: string + /** A created worktree's name, so the coordinator can tell the user where the worker runs. */ + name?: string + state?: string + tabId?: string + leafId?: string + requested?: string + effective?: string + source?: string + hookFound?: boolean + startupPolicy?: string + terminalId?: string + surface?: 'visible' | 'background' + warning?: string +} + +export type WorkerSetupReceipt = { + requested: 'run' | 'skip' | 'inherit' | 'not_applicable' + effective: 'run' | 'skip' | 'inherit' | 'not_applicable' + source: string + hookFound: boolean + startupPolicy: 'start-immediately' | 'wait-for-setup' + state: + | 'running' + | 'succeeded' + | 'failed' + | 'skipped' + | 'not_configured' + | 'spawn_failed' + | 'not_applicable' +} + +export function requireWorkerAuthority(runtime: OrcaRuntimeService, terminalHandle: string) { + const authority = runtime.getOrchestrationDispatchAuthority(terminalHandle) + const paneKey = authority?.paneKey ?? runtime.getTerminalPaneKey(terminalHandle) + const processIncarnation = + authority?.processIncarnation ?? runtime.getTerminalProcessIncarnation(terminalHandle) + if (!paneKey || !processIncarnation) { + throw new Error('stable_pane_required') + } + return { + paneKey, + processIncarnation, + ...(authority?.launchTokenHash ? { launchTokenHash: authority.launchTokenHash } : {}), + ...(authority?.hostScope ? { hostScope: JSON.stringify(authority.hostScope) } : {}) + } +} + +export async function createExistingWorktreeWorkerTerminal(args: { + runtime: OrcaRuntimeService + worktreeId: string + agent: TuiAgent + launchPreferences?: AgentLaunchPreferences + taskId: string + effects: WorkerEffect[] +}): Promise { + const terminal = await args.runtime.createTerminal(`id:${args.worktreeId}`, { + // Resolve ids through agent config; cursor alone opens the desktop app, its CLI is cursor-agent. + startupAgent: args.agent, + launchSource: 'orchestration', + suppressStartupUpdatePrompt: true, + ...(args.launchPreferences ? { launchPreferences: args.launchPreferences } : {}), + title: `worker-${args.taskId}`, + // Worker creation is background work and must not pull the sidebar away. + surfaceOwner: false + }) + args.effects.push({ + kind: 'terminal', + role: 'agent', + action: 'created', + id: terminal.handle, + surface: terminal.surface, + warning: terminal.warning + }) + return terminal +} + +/** Return structured workers in the terminal authority shape; registry-backed pane/incarnation getters keep requireWorkerAuthority mode-independent. */ +export async function createStructuredWorkerSessionForWorktree(args: { + runtime: OrcaRuntimeService + worktreeId: string + agent: TuiAgent + dispatchId: string + /** `--model`/`--effort`; the session seeds them exactly as a saved selection is seeded. */ + launchPreferences?: AgentLaunchPreferences + effects: WorkerEffect[] +}): Promise>> { + const options = narrowStructuredLaunchSeedOptions(args.launchPreferences) + const created = await createStructuredWorkerSession({ + runtime: args.runtime, + worktreeId: args.worktreeId, + agent: args.agent, + dispatchId: args.dispatchId, + ...(options ? { options } : {}) + }) + args.effects.push({ + kind: 'terminal', + role: 'agent', + action: 'created', + id: created.identity.handle, + surface: 'background' + }) + return created +} + +export function applyWaitForSetupOutcome( + receipt: WorkerSetupReceipt, + effects: WorkerEffect[], + wait: { satisfied: boolean; status: string } +): void { + if (receipt.startupPolicy !== 'wait-for-setup' || receipt.state !== 'running') { + return + } + if (wait.satisfied) { + receipt.state = 'succeeded' + } else if (wait.status === 'exited') { + receipt.state = 'failed' + } else { + return + } + const setupEffect = effects.find((effect) => effect.kind === 'setup') + if (setupEffect) { + setupEffect.state = receipt.state + } +} + +export function monitorWorkerSetup(args: { + runtime: OrcaRuntimeService + db: OrchestrationDb + runId: string + dispatchId: string + setupReceipt: WorkerSetupReceipt + effects: WorkerEffect[] +}): void { + const setupTerminal = args.effects.find( + (effect) => effect.kind === 'terminal' && effect.role === 'setup' && effect.id + ) + if ( + !setupTerminal?.id || + args.setupReceipt.startupPolicy !== 'start-immediately' || + args.setupReceipt.state !== 'running' + ) { + return + } + // Why: setup is intentionally non-gating, but command completion remains durable evidence. + void args.runtime + .waitForSetupTerminalCompletion(setupTerminal.id) + .then((completion) => { + const setupState = completion.exitCode === 0 ? 'succeeded' : 'failed' + const evidence = args.db.updateWorkerSetupEvidence({ + dispatchId: args.dispatchId, + setupState, + effects: args.effects.map((effect) => + effect.kind === 'setup' ? { ...effect, state: setupState } : effect + ) + }) + if (!evidence.changed) { + return + } + const dispatch = args.db.getDispatchContextById(args.dispatchId) + const message = args.db.insertMessage({ + runId: args.runId, + from: `dispatch:${args.dispatchId}`, + to: dispatch ? dispatchReportMailbox(args.db, dispatch) : `run:${args.runId}`, + subject: `Setup ${setupState} for worker ${args.dispatchId}`, + type: 'status', + priority: setupState === 'failed' ? 'high' : 'normal', + payload: JSON.stringify({ + dispatchId: args.dispatchId, + setupState, + terminalHandle: setupTerminal.id + }) + }) + args.runtime.notifyMessageArrived(message.to_handle, message.type) + }) + .catch(() => undefined) +} + +export function isUnknownWorkerStartOutcome(error: unknown, stage: string): boolean { + const code = + error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string' + ? (error as { code: string }).code + : '' + if (code === 'operation_unknown') { + return true + } + if (stage !== 'worktree_create') { + return false + } + const message = error instanceof Error ? error.message : String(error) + return /connection|disconnect|timed?\s*out|runtime changed|outcome unknown/i.test(message) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-agent-placement.ts similarity index 89% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-agent-placement.ts index b58aaa6d82a..0ebeae79721 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-agent-placement.ts @@ -1,26 +1,26 @@ -import type { RuntimeTerminalCreate } from '../../../../../../shared/runtime-terminal-create-contract' +import type { RuntimeTerminalCreate } from '../../../../../../../../shared/runtime-terminal-create-contract' /** Use the shared executor for new workers; structured worktrees omit startup agent, then resolve host support before chat creation. * Keep worker lineage/effects and background presentation in factories; caller passes the pre-decided mode. * Structured create refusals fail start through the worker error contract instead of silently downgrading. */ -import type { AgentLaunchPreferences } from '../../../../../../shared/agent-session/agent-session-host-authority' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import { executeAgentLaunch } from '../../../../../agent-launch/agent-launch-executor' -import type { AgentLaunchSurfaceFactory } from '../../../../../agent-launch/agent-launch-surface-factories' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { WORKER_START_VOCABULARY } from '../structured-workers/orchestration-worker-start-mode' -import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../shared/agent-launch/contracts/agent-launch-intent' -import { tearDownFailedWorkerStart } from './failed-worker-start-teardown' -import type { WorkerStartInput } from './worker-start-schema' +import type { AgentLaunchPreferences } from '../../../../../../../../shared/agent-session/agent-session-host-authority' +import type { TuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent' +import { executeAgentLaunch } from '../../../../../../../agent-launch/agent-launch-executor' +import type { AgentLaunchSurfaceFactory } from '../../../../../../../agent-launch/agent-launch-surface-factories' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import { WORKER_START_VOCABULARY } from '../../../structured-workers/orchestration-worker-start-mode' +import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../../../shared/agent-launch/contracts/agent-launch-intent' +import { tearDownFailedWorkerStart } from '../readiness/failed-worker-start-teardown' +import type { WorkerStartInput } from '../worker-start-input' import { createExistingWorktreeWorkerTerminal, createStructuredWorkerSessionForWorktree, type WorkerEffect, type WorkerSetupReceipt -} from './worker-topology' +} from './worker-placement-topology' import { createWorkerWorktree, type WorkerWorktreeCreationTarget } from './worker-worktree-creation' -import type { ReopenedWorker, WorkerFollowUp } from './worker-follow-up-placement' +import type { ReopenedWorker, WorkerFollowUp } from '../../follow-up/worker-follow-up-placement' /** Name only the two required fields so untyped worktree accessors cannot introduce any into unions. */ type PlacedWorktree = { id: string; repoId: string } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts new file mode 100644 index 00000000000..cdee0a1657b --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { createOrchestrationWorkerReleaseHarness } from '../../testing/worker-release.test-support' + +export function registerWorkerStartTerminalTargetTests(): void { + describe('worker-start --terminal target', () => { + const harness = createOrchestrationWorkerReleaseHarness() + beforeEach(() => harness.setup()) + afterEach(() => harness.cleanup()) + + it('refuses the coordinator terminal by handle', async () => { + const task = harness.db.createTask({ spec: 'self adoption', runId: harness.activeRunId }) + + await expect( + harness.call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + terminal: 'term_coord' + }) + ).rejects.toMatchObject({ + code: 'terminal_is_coordinator', + message: expect.stringContaining("coordinator's own terminal") + }) + expect(harness.db.getDispatchContext(task.id)).toBeUndefined() + }) + + it('refuses a different handle that resolves to the coordinator pane', async () => { + const task = harness.db.createTask({ + spec: 'self adoption alias', + runId: harness.activeRunId + }) + vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_coord' || handle === 'term_coord_alias' ? harness.coordinatorPaneKey : null + ) + + await expect( + harness.call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + terminal: 'term_coord_alias' + }) + ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) + }) + }) + + // Manual inject is another self-adoption path; compare target with caller too. + describe('orchestration.dispatch --to the caller', () => { + const harness = createOrchestrationWorkerReleaseHarness() + beforeEach(() => harness.setup()) + afterEach(() => harness.cleanup()) + + it('refuses an injected dispatch aimed at the coordinator handle', async () => { + vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( + (handle) => + ({ + terminalHandle: handle, + paneKey: harness.coordinatorPaneKey, + processIncarnation: 'runtime_test:term_coord:1' + }) as never + ) + const task = harness.db.createTask({ spec: 'self dispatch', runId: harness.activeRunId }) + + await expect( + harness.call('orchestration.dispatch', { + task: task.id, + from: 'term_coord', + to: 'term_coord', + inject: true + }) + ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) + expect(harness.db.getDispatchContext(task.id)).toBeUndefined() + expect(harness.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() + }) + + it('refuses an injected dispatch to a different handle that resolves to the coordinator pane', async () => { + vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_coord' || handle === 'term_coord_alias' ? harness.coordinatorPaneKey : null + ) + vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( + (handle) => + ({ + terminalHandle: handle, + paneKey: harness.coordinatorPaneKey, + processIncarnation: 'runtime_test:term_coord:1' + }) as never + ) + const task = harness.db.createTask({ + spec: 'self dispatch alias', + runId: harness.activeRunId + }) + + await expect( + harness.call('orchestration.dispatch', { + task: task.id, + from: 'term_coord', + to: 'term_coord_alias', + inject: true + }) + ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) + }) + + // Context-only self-dispatch writes no preamble and remains valid for low-level topologies. + it('still records a context-only dispatch aimed at the coordinator handle', async () => { + const task = harness.db.createTask({ spec: 'self context', runId: harness.activeRunId }) + + const result = (await harness.call('orchestration.dispatch', { + task: task.id, + from: 'term_coord', + to: 'term_coord' + })) as { dispatch: { id: string; status: string } } + + expect(result.dispatch.status).toBe('dispatched') + expect(harness.db.getDispatchContextById(result.dispatch.id)?.assignee_handle).toBe( + 'term_coord' + ) + expect(harness.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() + }) + + // Self-injection must refuse regardless of agent detection; without-inject advice cannot authorize it. + it.each([ + ['the coordinator handle', 'term_coord'], + ['an alias of the coordinator pane', 'term_coord_alias'] + ])('refuses %s even when no agent is detected', async (_label, target) => { + vi.spyOn(harness.runtime, 'isTerminalRunningAgent').mockResolvedValue(false) + vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( + (handle) => + (handle === 'term_coord_alias' + ? { + terminalHandle: handle, + paneKey: harness.coordinatorPaneKey, + processIncarnation: 'runtime_test:term_coord:1' + } + : null) as never + ) + const task = harness.db.createTask({ + spec: `self inject ${target}`, + runId: harness.activeRunId + }) + + await expect( + harness.call('orchestration.dispatch', { + task: task.id, + from: 'term_coord', + to: target, + inject: true + }) + ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) + expect(harness.db.getDispatchContext(task.id)).toBeUndefined() + }) + }) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-terminal-custody-at-creation.test.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-terminal-custody-at-creation.test.ts index 70565f5b191..79cfa2e6bcb 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-terminal-custody-at-creation.test.ts @@ -1,12 +1,12 @@ /** Write custody at terminal creation so boot-time user input can revoke ownership; waiting for TUI idle lost takeover and later release closed claimed panes. */ import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +import { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import '../../../../../../orchestration/db/contract-constants' +import '../../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../../orchestration/db/attempt-outcome-projection' +import { createOrchestrationWorkerReleaseHarness } from '../../testing/worker-release.test-support' const READY_WAIT = { handle: 'term_worker', diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-worktree-creation.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-worktree-creation.ts index 8f74380878e..7e15466ab35 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-worktree-creation.ts @@ -1,15 +1,15 @@ -import type { RuntimeTerminalCreate } from '../../../../../../shared/runtime-terminal-create-contract' +import type { RuntimeTerminalCreate } from '../../../../../../../../shared/runtime-terminal-create-contract' /** Create PTY worktrees agent-first; structured workers create sessions afterwards without startup agents. Setup/default tabs/lineage stay identical. */ -import type { AgentLaunchPreferences } from '../../../../../../shared/agent-session/agent-session-host-authority' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import { suggestCreatureNameForPaths } from '../../../../../../shared/worktree-name-suggestion' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { resolveUnattendedSetupDecision } from '../../../../../workspace-hooks/effective-hook-config' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope' -import type { WorkerEffect, WorkerSetupReceipt } from './worker-topology' +import type { AgentLaunchPreferences } from '../../../../../../../../shared/agent-session/agent-session-host-authority' +import type { TuiAgent } from '../../../../../../../../shared/agent-launch/catalog/tui-agent' +import { suggestCreatureNameForPaths } from '../../../../../../../../shared/worktree-name-suggestion' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import { resolveUnattendedSetupDecision } from '../../../../../../../workspace-hooks/effective-hook-config' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' +import { parseWorkspaceKey } from '../../../../../../../../shared/workspace-scope' +import type { WorkerEffect, WorkerSetupReceipt } from './worker-placement-topology' /** The repo a new worker worktree is created in, and its parent for `new-child`. */ export type WorkerWorktreeCreationTarget = { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/deliver-worker-dispatch-preamble.ts similarity index 80% rename from src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/readiness/deliver-worker-dispatch-preamble.ts index dc79fd4eef1..6461db5bdca 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/deliver-worker-dispatch-preamble.ts @@ -1,26 +1,26 @@ -import type { RuntimeTerminalSend } from '../../../../../../shared/runtime-terminal-send-contract' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { RuntimeTerminalSend } from '../../../../../../../../shared/runtime-terminal-send-contract' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' import { formatOrcaSessionAddress, isOrcaSessionId -} from '../../../../../../shared/orca-session-address' -import { canonicalOrcaSessionId } from '../../../../orchestration/addressing/session-lineage/canonical-orca-session-id' +} from '../../../../../../../../shared/orca-session-address' +import { canonicalOrcaSessionId } from '../../../../../../orchestration/addressing/session-lineage/canonical-orca-session-id' import { orcaSessionIdOrHandle, resolveDispatchAssigneeParty -} from '../../../../orchestration/addressing/orchestration-party' -import { buildDispatchPreamble } from '../../../../orchestration/workers/launch/worker-dispatch-preamble' -import { sendAgentTurn } from '../../../../orchestration/turn-delivery/send-agent-turn' -import { createWorkerBriefWriteGuard } from '../../../../terminal/wait/launched-agent-write-guard' -import { sendStructuredWorkerPreamble } from '../structured-workers/orchestration-structured-worker-session' -import { chatAssigneeOf } from '../chat-assignee-admission' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { sendChatTask, type ChatTaskDelivery } from '../chat-task-delivery' -import { dispatchTaskSource } from '../../../../orchestration/coordinator/dispatch/dispatch-task-source' -import type { AgentMessageSource } from '../../../../../../shared/agent-session/agent-session-message-source' +} from '../../../../../../orchestration/addressing/orchestration-party' +import { buildDispatchPreamble } from '../../../../../../orchestration/workers/launch/worker-dispatch-preamble' +import { sendAgentTurn } from '../../../../../../orchestration/turn-delivery/send-agent-turn' +import { createWorkerBriefWriteGuard } from '../../../../../../terminal/wait/launched-agent-write-guard' +import { sendStructuredWorkerPreamble } from '../../../structured-workers/orchestration-structured-worker-session' +import { chatAssigneeOf } from '../../../chat-assignee-admission' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' +import { sendChatTask, type ChatTaskDelivery } from '../../../chat-task-delivery' +import { dispatchTaskSource } from '../../../../../../orchestration/coordinator/dispatch/dispatch-task-source' +import type { AgentMessageSource } from '../../../../../../../../shared/agent-session/agent-session-message-source' import type { WorkerTurnStartObservation } from './worker-start-turn-observation' -import type { createStructuredWorkerSessionForWorktree } from './worker-topology' +import type { createStructuredWorkerSessionForWorktree } from '../placement/worker-placement-topology' type StructuredSession = Awaited> | null diff --git a/src/main/runtime/rpc/methods/orchestration/worker/failed-worker-start-teardown.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts similarity index 75% rename from src/main/runtime/rpc/methods/orchestration/worker/failed-worker-start-teardown.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts index 9b4f7e46538..85212bff6bd 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/failed-worker-start-teardown.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts @@ -1,11 +1,11 @@ -import { closeStructuredAgentSessionChild } from '../../../../agent-session/structured-agent-session-close' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +import { closeStructuredAgentSessionChild } from '../../../../../../agent-session/structured-agent-session-close' +import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' import { discardStructuredWorkerSession, releaseStructuredWorkerSession -} from '../structured-workers/orchestration-structured-worker-session' -import type { createStructuredWorkerSessionForWorktree } from './worker-topology' +} from '../../../structured-workers/orchestration-structured-worker-session' +import type { createStructuredWorkerSessionForWorktree } from '../placement/worker-placement-topology' /** Keep refused tasks reachable with their worker custody until retry or release; other partial starts retire their surface. */ export async function tearDownFailedWorkerStart(args: { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-setup-gate.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-setup-gate.ts similarity index 93% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-setup-gate.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-setup-gate.ts index d31b9cf6cb1..35929adaa1c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-setup-gate.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-setup-gate.ts @@ -1,9 +1,9 @@ -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' import { applyWaitForSetupOutcome, type WorkerEffect, type WorkerSetupReceipt -} from './worker-topology' +} from '../placement/worker-placement-topology' function residualWorkerEffects(effects: WorkerEffect[]): WorkerEffect[] { // 'reused_agent_terminal' is the retired verb agent-first creation used for its own agent diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts new file mode 100644 index 00000000000..9bea620390e --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts @@ -0,0 +1,86 @@ +import type * as WorktreeScanCacheModule from '../../../../../../../git/worktrees/catalog/worktree-scan-cache' +import type * as WorktreeListingModule from '../../../../../../../git/worktrees/catalog/worktree-listing' + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createAgentPromptSubmissionRuntime } from '../../../../../../terminal/input/agent-prompt-submission-runtime-test-fixture' + +vi.mock( + '../../../../../../../git/worktrees/catalog/worktree-scan-cache', + async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktrees: facade.listWorktrees + } + } +) + +vi.mock('../../../../../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktreesStrict: facade.listWorktreesStrict + } +}) + +const { getWorktreeListingMocks } = vi.hoisted(() => { + const createWorktreeListingMocks = () => ({ + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/prompt-contract', + isBare: false, + isMainWorktree: false + } + ]), + listWorktreesStrict: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/prompt-contract', + isBare: false, + isMainWorktree: false + } + ]) + }) + let listings: ReturnType | undefined + return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } +}) + +describe('orchestration worker-start prompt contract', () => { + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('does not attribute output from the old busy turn to a queued prompt', async () => { + vi.useFakeTimers() + const { runtime, handle } = await createAgentPromptSubmissionRuntime(() => undefined, 'codex') + runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + const pending = runtime.sendTerminalAgentPrompt(handle, 'queued prompt', { + inputKind: 'driving', + acceptQueued: true, + requestId: 'busy-swallowed', + observationTimeoutMs: 0 + }) + + await vi.runAllTimersAsync() + const send = await pending + expect(send).toMatchObject({ + prompt: { + requestId: 'busy-swallowed', + stages: ['input_accepted'] + } + }) + const observed = runtime.observeTerminalAgentPrompt(handle, send.prompt!, 1_000) + setTimeout(() => { + runtime.onPtyData('pty-prompt', 'old turn output', Date.now()) + }, 50) + await vi.runAllTimersAsync() + + await expect(observed).resolves.toMatchObject({ + stages: ['input_accepted'] + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-readiness-settlement.ts similarity index 89% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-readiness-settlement.ts index 69da4b33192..b489edcc650 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-readiness-settlement.ts @@ -1,15 +1,15 @@ import { AGENT_PROMPT_EFFECT_TIMEOUT_MS, ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS -} from '../../../../../../shared/orchestration/orchestration-timing-budgets' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { RunRow, TaskRow } from '../../../../orchestration/db/orchestration-records' -import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../shared/agent-launch/contracts/agent-launch-intent' +} from '../../../../../../../../shared/orchestration/orchestration-timing-budgets' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../../../orchestration/db/orchestration-db' +import type { RunRow, TaskRow } from '../../../../../../orchestration/db/orchestration-records' +import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../../../shared/agent-launch/contracts/agent-launch-intent' import { deliverWorkerDispatchPreamble } from './deliver-worker-dispatch-preamble' -import { reportedWorkerOutcome } from './worker-start-receipt' -import { chatAssigneeSessionId } from '../../../../orchestration/workers/lifecycle/chat-assignee' -import type { OrchestrationWorkerLaunchReceipt } from './worker-launch-preferences' +import { reportedWorkerOutcome } from '../worker-start-receipt' +import { chatAssigneeSessionId } from '../../../../../../orchestration/workers/lifecycle/chat-assignee' +import type { OrchestrationWorkerLaunchReceipt } from '../launch/worker-launch-preferences' import { describeUnobservedWorkerTurnStart, observeWorkerTurnStart, @@ -20,7 +20,7 @@ import { type createStructuredWorkerSessionForWorktree, type WorkerEffect, type WorkerSetupReceipt -} from './worker-topology' +} from '../placement/worker-placement-topology' /** Claim ready only for proven turn start or unsupported observation; supported-but-unobserved starts remain start_unknown. */ export async function deliverAndSettleWorkerStartReadiness(args: { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-structured-setup-gate.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-structured-setup-gate.ts index 5d01b0332e2..f0a061ff9b9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-structured-setup-gate.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-structured-setup-gate.ts @@ -1,8 +1,8 @@ /** Structured chats have no startup command to sequence after setup, so wait explicitly within the start deadline. * Missing evidence never fails start: unavailable waits need no receipt; attempted waits that throw record wait_unevaluated. */ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { WorkerEffect, WorkerSetupReceipt } from './worker-topology' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' +import type { WorkerEffect, WorkerSetupReceipt } from '../placement/worker-placement-topology' export type StructuredWorkerSetupGate = { satisfied: boolean diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-turn-observation.ts similarity index 94% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-turn-observation.ts index dd8d776eec6..3b32cfa295b 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-turn-observation.ts @@ -1,6 +1,6 @@ -import { AGENT_PROMPT_EFFECT_TIMEOUT_MS } from '../../../../../../shared/orchestration/orchestration-timing-budgets' -import type { RuntimeTerminalPromptDelivery } from '../../../../../../shared/runtime-terminal-send-contract' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +import { AGENT_PROMPT_EFFECT_TIMEOUT_MS } from '../../../../../../../../shared/orchestration/orchestration-timing-budgets' +import type { RuntimeTerminalPromptDelivery } from '../../../../../../../../shared/runtime-terminal-send-contract' +import type { OrcaRuntimeService } from '../../../../../../orca-runtime' /** Observed/permission prove live input handling; unsupported keeps accepted-write evidence. * Unobserved means supported observation timed out after write: unverifiable, never dead, and no safe blind resend. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts new file mode 100644 index 00000000000..ec4784f16b1 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts @@ -0,0 +1,236 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { RpcContext } from '../../../../core' +import { createOrchestrationRpcHarness } from '../../rpc-test-harness' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import '../../../../../../../shared/constants' +import '../../../../../orchestration/workers/launch/worker-dispatch-preamble' + +describe('orchestration RPC methods', () => { + const h = createOrchestrationRpcHarness() + const { coordinatorPaneKey } = h + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let ctx: RpcContext + + function setup(withBoundRun = true): void { + ;({ db, runtime, ctx } = h.setup(withBoundRun)) + } + + afterEach(() => { + h.cleanup() + }) + + async function call(name: string, params: Record) { + return h.call(name, params, ctx) + } + + describe('composed workers', () => { + function mockCurrentWorkerStart(options?: { ready?: boolean }): void { + vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => + handle === 'term_coord' + ? coordinatorPaneKey + : handle === 'term_worker' + ? 'tab_worker:leaf_worker' + : null + ) + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + vi.spyOn(runtime, 'showTerminal').mockImplementation( + async (handle) => ({ handle, worktreeId: 'repo::worktree', status: 'running' }) as never + ) + vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({ + id: 'repo::worktree' + } as never) + vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockResolvedValue({ + id: 'repo::worktree' + } as never) + vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ + handle: 'term_worker', + worktreeId: 'repo::worktree', + title: 'worker' + }) + vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ + handle: 'term_worker', + condition: 'tui-idle', + satisfied: options?.ready !== false, + status: 'running', + exitCode: null + }) + vi.mocked(runtime.getTerminalProcessIncarnation).mockImplementation((handle) => + handle === 'term_worker' ? 'runtime_test:term_worker:1' : null + ) + vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') + vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ + handle: 'term_worker', + accepted: true, + bytesWritten: 1 + }) + } + + it('rejects a declared caller that disagrees with complete attested evidence', async () => { + setup() + mockCurrentWorkerStart() + vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => + handle === 'term_coord' || handle === 'term_other' + ? coordinatorPaneKey + : handle === 'term_worker' + ? 'tab_worker:leaf_worker' + : null + ) + const attestedEvidence = { + terminalHandle: 'term_attested', + paneKey: 'tab_attested:leaf_attested', + launchToken: 'attested-launch-token' + } as const + vi.spyOn(runtime, 'verifyOrchestrationCompatibilityCaller').mockReturnValue({ + terminalHandle: attestedEvidence.terminalHandle, + paneKey: attestedEvidence.paneKey, + processIncarnation: 'runtime_test:attested:1', + launchTokenHash: 'attested-launch-token-hash', + hostScope: { kind: 'local', hostId: 'local' } + }) + ctx = { ...ctx, orchestrationCompatibilityEvidence: attestedEvidence } + const task = db.createTask({ spec: 'mismatched caller' }) + + await expect( + call('orchestration.workerStart', { + task: task.id, + from: 'term_other', + agent: 'codex' + }) + ).rejects.toMatchObject({ code: 'consumer_fenced' }) + expect(db.getDispatchContext(task.id)).toBeUndefined() + }) + + it('deliberately permits present but unverifiable restored-terminal evidence', async () => { + setup() + mockCurrentWorkerStart() + // Restored/adopted terminals have no launch token; preserve intentional fail-open compatibility. + const task = db.createTask({ spec: 'restored caller limitation' }) + ctx = { + ...ctx, + orchestrationCompatibilityEvidence: { + terminalHandle: 'term_worker', + paneKey: 'tab_worker:leaf_worker' + } + } + + const result = (await call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + agent: 'codex' + })) as { state: string } + + expect(result.state).toBe('ready') + expect(db.getDispatchContext(task.id)).toBeDefined() + }) + + it('creates and binds a Run for an unbound coordinator, then names it on reuse', async () => { + setup(false) + mockCurrentWorkerStart() + const start = () => + call('orchestration.workerStart', { + spec: 'Audit the parser\nCheck every branch.', + from: 'term_coord', + agent: 'codex' + }) + + const first = await start() + const bound = db.getCurrentRunForCoordinator({ + terminalHandle: 'term_coord', + paneKey: coordinatorPaneKey, + orcaSessionId: null + }) + const run = { id: bound?.id, objective: 'Audit the parser' } + expect(first).toMatchObject({ state: 'ready', run: { ...run, created: true } }) + expect(await start()).toMatchObject({ run: { ...run, created: false } }) + }) + + it('puts overlapping first starts from an unbound coordinator in one Run', async () => { + setup(false) + mockCurrentWorkerStart() + // Hold both starts in preflight, then let the second finish first. + const preflights: (() => void)[] = [] + vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockImplementation( + () => + new Promise((resolve) => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preflight reads only the workspace id. + preflights.push(() => resolve({ id: 'repo::worktree' } as never)) + ) + ) + const start = (spec: string) => + call('orchestration.workerStart', { spec, from: 'term_coord', agent: 'codex' }) + + const first = start('Audit the parser') + const second = start('Audit the lexer') + await vi.waitFor(() => expect(preflights).toHaveLength(2)) + preflights[1]() + const secondReceipt = await second + preflights[0]() + const firstReceipt = await first + + const runs = db.listRuns().runs.filter((run) => run.legacy === 0) + expect(runs).toHaveLength(1) + expect(secondReceipt).toMatchObject({ run: { id: runs[0].id, created: true } }) + expect(firstReceipt).toMatchObject({ run: { id: runs[0].id, created: false } }) + }) + + it('creates no Run when an unbound coordinator start fails preflight', async () => { + setup(false) + mockCurrentWorkerStart() + + await expect( + call('orchestration.workerStart', { + spec: 'Audit the parser', + from: 'term_coord', + agent: 'codex', + worktree: 'new-child' + }) + ).rejects.toThrow('repo_not_found') + expect(db.listRuns().runs.filter((run) => run.legacy === 0)).toEqual([]) + }) + + it('commits the launched worker token with its durable authority', async () => { + setup() + mockCurrentWorkerStart() + vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({ + runtimeId: runtime.getRuntimeId(), + terminalHandle: 'term_worker', + ptyId: 'pty_worker', + worktreeId: 'repo::worktree', + paneKey: 'tab_worker:leaf_worker', + processIncarnation: 'runtime_test:term_worker:1', + launchTokenHash: 'worker-launch-token-hash', + hostScope: { kind: 'local', hostId: 'local' } + }) + const task = db.createTask({ spec: 'persist worker identity' }) + + const result = (await call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + agent: 'codex' + })) as { dispatchId: string } + + expect(db.getDispatchContextById(result.dispatchId)?.launch_token_hash).toBe( + 'worker-launch-token-hash' + ) + }) + + it('returns a failed receipt and preserves a created terminal as residual', async () => { + setup() + mockCurrentWorkerStart({ ready: false }) + const task = db.createTask({ spec: 'worker timeout' }) + + const result = (await call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + agent: 'codex' + })) as { state: string; failedStage: string; residualResources: { id: string }[] } + + expect(result).toMatchObject({ state: 'failed', failedStage: 'agent_readiness' }) + expect(result.residualResources).toEqual([expect.objectContaining({ id: 'term_worker' })]) + expect(db.getTask(task.id)?.status).toBe('failed') + expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-input.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-input.ts new file mode 100644 index 00000000000..c07bec88b59 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-input.ts @@ -0,0 +1,4 @@ +import type { z } from 'zod' +import type { WorkerStartParams } from '../../../../../../../shared/rpc-contract/orchestration/orchestration-worker-start-params' + +export type WorkerStartInput = z.infer diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-mutation.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-mutation.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-mutation.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-mutation.ts diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-receipt.ts similarity index 80% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts rename to src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-receipt.ts index 520c542b5d9..cbb50af87af 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-receipt.ts @@ -1,18 +1,18 @@ -import { formatTerminalStartFailure } from '../../../../../../shared/terminal/pty/lifecycle/terminal-start-failure' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { WorkerDispatchRow } from '../../../../orchestration/db/orchestration-records' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { tearDownFailedWorkerStart } from './failed-worker-start-teardown' -import { reportFailedWorkerStart } from '../../../../orchestration/workers/turn-stops/failed-worker-start-report' +import { formatTerminalStartFailure } from '../../../../../../../shared/terminal/pty/lifecycle/terminal-start-failure' +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import type { WorkerDispatchRow } from '../../../../../orchestration/db/orchestration-records' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { tearDownFailedWorkerStart } from './readiness/failed-worker-start-teardown' +import { reportFailedWorkerStart } from '../../../../../orchestration/workers/turn-stops/failed-worker-start-report' import { isUnknownWorkerStartOutcome, type createStructuredWorkerSessionForWorktree, type WorkerSetupReceipt -} from './worker-topology' -import type { OrchestrationWorkerLaunchReceipt } from './worker-launch-preferences' -import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../shared/agent-launch/contracts/agent-launch-intent' -import { replaceDispatchCapabilities } from '../../../../orchestration/terminal-authority/views/worker-terminal-redaction' -import { redactString } from '../../../../../observability/redactor' +} from './placement/worker-placement-topology' +import type { OrchestrationWorkerLaunchReceipt } from './launch/worker-launch-preferences' +import type { AgentLaunchModeReceipt as WorkerStartModeReceipt } from '../../../../../../../shared/agent-launch/contracts/agent-launch-intent' +import { replaceDispatchCapabilities } from '../../../../../orchestration/terminal-authority/views/worker-terminal-redaction' +import { redactString } from '../../../../../../observability/redactor' type WorkerStartFailureArgs = { runtime: OrcaRuntimeService diff --git a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts similarity index 93% rename from src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts index d698f30aab4..f482e42810d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts @@ -1,15 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type Database from '../../../../../sqlite/sync-database' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { isStreamingMethod, eraseRpcMethods, type RpcContext } from '../../../core' -import { parseOrcaSessionAddress } from '../../../../../../shared/orca-session-address' +import type Database from '../../../../../../sqlite/sync-database' +import { OrcaRuntimeService } from '../../../../../orca-runtime' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' +import type { OrchestrationSessionCaller } from '../../../../../orchestration/addressing/orchestration-caller-identity' +import { ORCHESTRATION_METHODS } from '../../orchestration' +import { isStreamingMethod, eraseRpcMethods, type RpcContext } from '../../../../core' +import { parseOrcaSessionAddress } from '../../../../../../../shared/orca-session-address' const COORDINATOR = 'term_coordinator' const TARGET = 'term_target' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/single-worker-stop.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/single-worker-stop.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/single-worker-stop.ts rename to src/main/runtime/rpc/methods/orchestration/worker/stop/single-worker-stop.ts index d1063263db5..c83e3c6a329 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/single-worker-stop.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/single-worker-stop.ts @@ -1,22 +1,22 @@ -import type { WorkerStopReceipt } from '../../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' +import type { WorkerStopReceipt } from '../../../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' import { RemoteCapabilities, RemoteStopReceipt, remoteHelpers } from './worker-stop-remote-receipt' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { RpcContext } from '../../../core' -import { describeUnconfirmedAgentStop } from '../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import { OrchestrationError } from '../../../../../orchestration/orchestration-error' +import type { RpcContext } from '../../../../core' +import { describeUnconfirmedAgentStop } from '../../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import { ORCHESTRATION_WORKER_STOP_HELPERS_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_STOP_VERDICT_RUNTIME_CAPABILITY -} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { inspectWorkerTerminal } from './worker-observation' -import { resolvePinnedFederatedServer } from './pinned-federated-server' -import { refuseFederatedStopWhileKeptOpen } from './worker-keep-open' +} from '../../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { OrcaRuntimeService } from '../../../../../orca-runtime' +import { inspectWorkerTerminal } from '../observation/worker-observation' +import { resolvePinnedFederatedServer } from '../../../../../orchestration/legacy-remote-home/pinned-federated-server' +import { refuseFederatedStopWhileKeptOpen } from '../worker-keep-open' import { archiveWorkerOutputBeforeStop } from './worker-stop-archive' import { resolveStructuredWorkerForDispatch, stopStructuredWorker -} from '../structured-workers/orchestration-structured-worker-lifecycle' -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' +} from '../../structured-workers/orchestration-structured-worker-lifecycle' +import { isStructuredWorkerHandle } from '../../../../../../../shared/orchestration/workers/structured-worker-handle' export type StopMutation = RpcContext['orchestrationMutation'] @@ -198,7 +198,7 @@ export async function stopSingleWorker( 'none' ) } - await archiveWorkerOutputBeforeStop({ + archiveWorkerOutputBeforeStop({ runtime, db, dispatchId, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-archive.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-archive.ts new file mode 100644 index 00000000000..8e07ec62edb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-archive.ts @@ -0,0 +1,48 @@ +import type { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import { + captureWorkerOutputReference, + releaseCommitFieldsForCapturedArchive +} from '../../../../../orchestration/workers/archives/worker-output-archive' +import type { WorkerTerminalReleaseRuntime } from '../../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +import { resolveStructuredWorkerForDispatch } from '../../structured-workers/orchestration-structured-worker-lifecycle' +import { orchestrationTimestampToMs } from '../output/worker-output' +import { captureWorkerResumeSession } from '../follow-up/worker-resume-session-capture' + +/** Record where a worker's output lives before stop closes its terminal; release would otherwise find nothing to point at. */ +export function archiveWorkerOutputBeforeStop(args: { + runtime: WorkerTerminalReleaseRuntime + db: OrchestrationDb + dispatchId: string + terminalHandle: string + attachedAt: string +}): void { + const { db, dispatchId } = args + // Stopping matters more than the reference; on failure, release reports the output unavailable. + try { + const resource = db.getWorkerTerminalResourceByOwner(dispatchId) + const attachedAtMs = orchestrationTimestampToMs(args.attachedAt) + if (resource) { + captureWorkerResumeSession(args.runtime, db, resource, attachedAtMs) + } + if ( + !resource || + resource.ownership_state !== 'owned' || + db.hasWorkerTerminalArchive(dispatchId) + ) { + return + } + const captured = captureWorkerOutputReference({ + runtime: args.runtime, + terminalHandle: args.terminalHandle, + attachedAtMs, + structuredWorker: resolveStructuredWorkerForDispatch(db, dispatchId) + }) + db.storeWorkerTerminalArchiveBeforeStop({ + dispatchId, + resourceId: resource.id, + ...releaseCommitFieldsForCapturedArchive(captured) + }) + } catch (error) { + console.warn('[orchestration] worker output was not located before stop', dispatchId, error) + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts similarity index 95% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts index b8840f6c8ba..c29dd067b06 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { OPERATOR_CLOSE_EXIT_CAUSE, type TerminalExitCause -} from '../../../../../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +} from '../../../../../../../shared/terminal/pty/lifecycle/terminal-exit-cause' +import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' const h = createOrchestrationWorkerReleaseHarness() beforeEach(() => h.setup()) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-helpers.integration.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-helpers.integration.test.ts similarity index 97% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-stop-helpers.integration.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-helpers.integration.test.ts index 81c0b266af7..2ef11c3dcb9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-helpers.integration.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-helpers.integration.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { receipt, useHelperFollowUpCli } from './helper-follow-up-cli.test-support' -import './worker-stop' +import { receipt, useHelperFollowUpCli } from '../testing/helper-follow-up-cli.test-support' +import '../worker-stop' describe('worker-stop through CLI argv, RPC and SQLite', () => { const f = useHelperFollowUpCli() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-liveness-verdict.test.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts rename to src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-liveness-verdict.test.ts index 6637854b9ba..dadfaec5138 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-liveness-verdict.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { isStreamingMethod, eraseRpcMethods } from '../../../core' +import { OrcaRuntimeService } from '../../../../../orca-runtime' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' +import { ORCHESTRATION_METHODS } from '../../orchestration' +import { isStreamingMethod, eraseRpcMethods } from '../../../../core' // Dropped relays clear connected across remote PTYs; use host verdicts to distinguish lost contact from death. describe('worker-stop against a terminal we lost contact with', () => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-remote-receipt.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-remote-receipt.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-stop-remote-receipt.ts rename to src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-remote-receipt.ts index f739152a050..7af89642a6c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-remote-receipt.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-remote-receipt.ts @@ -1,9 +1,9 @@ import { z } from 'zod' -import { ORCHESTRATION_WORKER_STOP_HELPERS_RUNTIME_CAPABILITY } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { ORCHESTRATION_WORKER_STOP_HELPERS_RUNTIME_CAPABILITY } from '../../../../../../../shared/orchestration/orchestration-runtime-capabilities' import { HelperStopOutcome, type WorkerStopReceipt -} from '../../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' +} from '../../../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' export const RemoteCapabilities = z.object({ capabilities: z.array(z.string()).optional() }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts deleted file mode 100644 index efaf9137e9d..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -// Chat-mode workers have no terminal hook stream; worker-list must read the structured host's own verdict. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { agentSessionConversationView } from '../../../../../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import type { AgentSessionRecord } from '../../../../../../shared/agent-session/lifecycle/agent-session-record' -import type { FleetAgentStatusEvidence } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' -import { - structuredAgentSessionPaneKey, - structuredAgentSessionTabId -} from '../../../../../../shared/agent-session/view/structured-agent-session-projection' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' - -const hostRef: { current: unknown } = { current: null } - -vi.mock( - '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', - () => ({ getStructuredAgentSessionHost: () => hostRef.current }) -) - -const { projectWorkerFleet } = await import('./worker-list-projection') -const { ensureSessionWorkerRecords, inspectSessionWorker } = - await import('./session-worker-observation') -const { createSessionWorkerLivenessReader } = - await import('../../../../orchestration/workers/lifecycle/session-worker-liveness') -const { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} = - await import('../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity') - -const SESSION = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' -const NOW = 10 * 60 * 60 * 1000 -const HOUR = 60 * 60 * 1000 - -function record( - provider: 'codex' | 'claude', - lease: Partial = {} -): AgentSessionRecord { - return { - ...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: SESSION, ...lease })), - provider - } -} - -function installHost(current: AgentSessionRecord, attached: boolean) { - hostRef.current = { - deps: { - store: { - getConversation: () => agentSessionConversationView(current), - listConversations: () => [agentSessionConversationView(current)], - getVisibleSessionTabIndex: () => ({ present: true, sessionIds: [SESSION] }) - } - }, - getSessionTabId: () => `agent-session:${SESSION}`, - hasSession: () => attached - } -} - -/** The session's own status row, as the structured status feed publishes it. */ -function sessionStatus( - state: FleetAgentStatusEvidence['activity']['state'], - at: number -): FleetAgentStatusEvidence { - return { - binding: { kind: 'unresolved', reason: 'pane_not_bound' }, - clock: { kind: 'observed', at }, - deliveredAt: at, - activity: { - paneKey: structuredAgentSessionPaneKey(structuredAgentSessionTabId(SESSION), SESSION), - connectionId: null, - state, - agentType: 'codex', - model: null, - worktreeId: 'wt_1', - restoredUnconfirmed: false, - providerSessionOnly: false - } - } -} - -describe('worker-list liveness for chat-mode workers', () => { - let db: OrchestrationDb - beforeEach(() => { - db = new OrchestrationDb(':memory:') - structuredWorkerIdentities.clear() - hostRef.current = null - }) - afterEach(() => db.close()) - - function seed() { - const task = db.createTask({ runId: 'run_legacy_local', spec: 'structured work' }) - const { dispatch } = db.createStartingWorkerDispatch({ - taskId: task.id, - startOptions: {}, - creator: { kind: 'system' }, - maxDepth: 9 - }) - db.prepareStartingWorkerAuthority({ - dispatchId: dispatch.id, - handle: mintStructuredWorkerHandle(), - paneKey: mintStructuredWorkerPaneKey(SESSION), - processIncarnation: structuredWorkerProcessIncarnation(SESSION), - worktreeId: 'wt_1', - effects: [], - setupState: 'not_configured', - hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), - terminalOwnership: 'created' - }) - db.markWorkerDispatchReady(dispatch.id) - return dispatch.id - } - - function project(statuses: FleetAgentStatusEvidence[]) { - const dispatchId = seed() - const rows = db.listWorkerTerminalResources({ dispatchIds: [dispatchId], limit: 1 }) - return projectWorkerFleet({ - rows, - attentionFacts: db.getWorkerAttentionFactsForDispatches([dispatchId], NOW), - statuses, - limit: 1, - now: NOW, - observeSession: createSessionWorkerLivenessReader(db, statuses) - }).workers[0]! - } - - it('keeps an idle Claude chat worker live after its last turn is hours old', () => { - installHost(record('claude'), true) - const worker = project([sessionStatus('done', NOW - 2 * HOUR)]) - - expect(worker.liveness.verdict).toBe('live') - expect(worker.stage.activity).toBe('done') - expect(worker.attention.requiresAction).toBe(false) - }) - - it('reports a session the host saw exit as exited', () => { - installHost( - record('codex', { - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed', detail: 'provider exited', observedAt: 1 } - }), - false - ) - const worker = project([sessionStatus('done', NOW - HOUR)]) - - expect(worker.liveness).toEqual({ verdict: 'exited', source: 'execution_host' }) - expect(worker.nextAction.kind).toBe('recover') - }) - - it('names the lost host when the session cannot be observed', () => { - const worker = project([]) - - expect(worker.liveness).toEqual({ - verdict: 'unverifiable', - reason: 'host_unavailable', - detail: 'The structured agent-session host is not installed in this runtime generation.' - }) - expect(worker.attention.requiresAction).toBe(true) - }) - - it('installs the session host after a restart before judging a structured worker', async () => { - const dispatchId = seed() - const ended = record('codex', { - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed', detail: 'provider exited', observedAt: 1 } - }) - // After a restart the host is not installed until a caller asks for it. - const runtime = { ensureStructuredAgentSessionHost: async () => installHost(ended, false) } - const rows = db.listWorkerTerminalResources({ dispatchIds: [dispatchId], limit: 1 }) - - await ensureSessionWorkerRecords(runtime, rows) - const listed = projectWorkerFleet({ - rows, - attentionFacts: db.getWorkerAttentionFactsForDispatches([dispatchId], NOW), - statuses: [], - limit: 1, - now: NOW, - observeSession: createSessionWorkerLivenessReader(db, []) - }) - expect(listed.workers[0]!.liveness).toEqual({ verdict: 'exited', source: 'execution_host' }) - - hostRef.current = null - const shown = await inspectSessionWorker(runtime, db, dispatchId, rows[0]!.agentTerminalHandle!) - expect(shown?.status).toBe('exited') - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-cli.test-support.ts b/src/main/runtime/rpc/methods/orchestration/worker/testing/helper-follow-up-cli.test-support.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-cli.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/worker/testing/helper-follow-up-cli.test-support.ts index b8291fc51f0..0b756a13adb 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/helper-follow-up-cli.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/testing/helper-follow-up-cli.test-support.ts @@ -4,25 +4,25 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, vi, type MockInstance } from 'vitest' import { z } from 'zod' -import { OrcaRuntimeRpcServer } from '../../../server/runtime-rpc' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { STATUS_METHODS } from '../../host-management/status' -import { TERMINAL_QUERY_METHODS } from '../../terminal/terminal-query-methods' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { OrcaRuntimeRpcServer } from '../../../../server/runtime-rpc' +import { ORCHESTRATION_METHODS } from '../../orchestration' +import { STATUS_METHODS } from '../../../host-management/status' +import { TERMINAL_QUERY_METHODS } from '../../../terminal/terminal-query-methods' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' import { createQueuedMessageTestRig, type QueuedMessageTestRig -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' -import { setStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +} from '../../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' +import { setStructuredAgentSessionHost } from '../../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { mintStructuredWorkerHandle, mintStructuredWorkerPaneKey, structuredWorkerIdentities, structuredWorkerProcessIncarnation -} from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { testOrcaSessionId } from '../../../../../../shared/orca-session-address-test-fixture' -import * as placement from './worker-start-agent-placement' +} from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' +import { testOrcaSessionId } from '../../../../../../../shared/orca-session-address-test-fixture' +import * as placement from '../start/placement/worker-start-agent-placement' export const receipt = z.object({ taskId: z.string(), @@ -117,7 +117,7 @@ export function useHelperFollowUpCli() { methods: [...STATUS_METHODS, ...TERMINAL_QUERY_METHODS, ...ORCHESTRATION_METHODS] }) await server.start() - const cliPath = '../../../../../../cli/index' + const cliPath = '../../../../../../../cli/index' main = (await import(cliPath)).main }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts b/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-release.test-support.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts rename to src/main/runtime/rpc/methods/orchestration/worker/testing/worker-release.test-support.ts index b795c0b4489..89d2dc17c3f 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-release.test-support.ts @@ -1,22 +1,27 @@ import { expect, vi } from 'vitest' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { isStreamingMethod, eraseRpcMethods, type RpcContext, type RpcMethod } from '../../../core' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import type { RuntimeStore } from '../../../../construction/runtime-store-contract' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' +import { ORCHESTRATION_METHODS } from '../../orchestration' +import { + isStreamingMethod, + eraseRpcMethods, + type RpcContext, + type RpcMethod +} from '../../../../core' +import { OrchestrationDb } from '../../../../../orchestration/db/orchestration-db' +import '../../../../../orchestration/db/contract-constants' +import '../../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../../orchestration/db/dispatch-row-writer' +import '../../../../../orchestration/db/attempt-outcome-projection' +import { OrcaRuntimeService } from '../../../../../orca-runtime' +import type { TuiAgent } from '../../../../../../../shared/agent-launch/catalog/tui-agent' +import type { RuntimeStore } from '../../../../../construction/runtime-store-contract' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../../shared/layout-owner-switch' import { getAppEnvironment, hasAppEnvironment, setAppEnvironment, type AppEnvironment -} from '../../../../../../shared/app-environment' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +} from '../../../../../../../shared/app-environment' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' type WorkerStartOptions = { terminal?: string; agent?: TuiAgent } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts new file mode 100644 index 00000000000..15743810727 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts @@ -0,0 +1,5 @@ +import { registerWorkerListRunScopeRpcTests } from '../fleet/worker-list-run-scope-rpc.spec' +import { registerWorkerStartTerminalTargetTests } from '../start/placement/worker-start-terminal-target.spec' + +registerWorkerListRunScopeRpcTests() +registerWorkerStartTerminalTargetTests() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-access.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-access.ts deleted file mode 100644 index 00d1f21e78f..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-access.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { z } from 'zod' -import type { ApprovalAnswerParams } from '../../../../../../shared/rpc-contract/orchestration-approval-answer-params' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrchestrationAccessRuleInput } from '../access/orchestration-method-access' - -export type WorkerApprovalAccess = { answeredBy: 'person' | 'coordinator'; reason: string | null } - -/** Approve requires a person; deny allows an agent or a person. A person is proven by the transport: - * only the desktop app's own IPC. A paired device can carry a remote CLI, so it counts as an agent. */ -export function workerApprovalAccess({ - params, - ctx -}: OrchestrationAccessRuleInput>): WorkerApprovalAccess { - const person = ctx.caller?.kind === 'desktop' - const reason = params.reason?.trim() || null - if (params.decision === 'allow' && !person) { - throw new OrchestrationError( - 'approval_requires_person', - `Only a person can allow ${params.prompt}, from Orca or the worker itself. You can deny it with a reason, or leave it for the person.`, - { effectsApplied: false } - ) - } - if (!person && !reason) { - throw new OrchestrationError( - 'invalid_argument', - 'Missing --reason: tell the worker what to do instead.', - { effectsApplied: false } - ) - } - return { answeredBy: person ? 'person' : 'coordinator', reason } -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-answer.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-answer.ts index 84cafe7b835..7a55862bc94 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-answer.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-approval-answer.ts @@ -1,5 +1,5 @@ import { defineOrchestrationMethod } from '../access/orchestration-method-access' -import { ApprovalAnswerParams } from '../../../../../../shared/rpc-contract/orchestration-approval-answer-params' +import { ApprovalAnswerParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-approval-answer-params' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { structuredMailboxCustody } from '../../../../orchestration/mailbox/routing/structured-session-mail-target' import { @@ -19,7 +19,7 @@ import { } from '../../../../orchestration/workers/turn-stops/worker-turn-stop-report' import type { z } from 'zod' import type { RpcContext } from '../../../core' -import { workerApprovalAccess, type WorkerApprovalAccess } from './worker-approval-access' +import { workerApprovalAccess, type WorkerApprovalAccess } from '../access/worker-approval-access' import { formatOrcaSessionAddress } from '../../../../../../shared/orca-session-address' export type WorkerApprovalAnswerReceipt = { @@ -108,7 +108,7 @@ export async function answerWorkerApproval( by: access.answeredBy, decision: params.decision, reason: access.reason, - reasonDelivered: true + reasonDelivered: params.decision === 'deny' }) }, { notify } @@ -125,7 +125,8 @@ export async function answerWorkerApproval( sessionId: custody.sessionId, approvalId: params.prompt, dispatchId: dispatch.id, - decision: params.decision + decision: params.decision, + byAgent: access.answeredBy === 'coordinator' }) if (!answered.ok) { // Answered in the worker's own chat, or gone: say so now, not at the worker's next turn edge. diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts index 028d779e55f..9ea94c34645 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts @@ -1,4 +1,4 @@ -import { exposeDispatchContext } from './dispatch-context-exposure' +import { exposeDispatchContext } from './observation/dispatch-context-exposure' import { contextOnlyAbandonWarning } from '../../../../orchestration/workers/lifecycle/context-only-dispatch-release' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { defineOrchestrationMethod } from '../access/orchestration-method-access' @@ -8,21 +8,22 @@ import { inspectWorkerTerminal, projectFleetWorker, showContextOnlyWorker -} from './worker-observation' -import { resolvePinnedFederatedServer } from './pinned-federated-server' -import { readArchivedWorkerOutput } from './worker-archive-read' +} from './observation/worker-observation' +import { resolvePinnedFederatedServer } from '../../../../orchestration/legacy-remote-home/pinned-federated-server' +import { readArchivedWorkerOutput } from './output/worker-archive-read' +import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' import { readStructuredWorkerOutput } from '../structured-workers/orchestration-structured-worker-lifecycle' import { releaseStructuredWorkerSession } from '../structured-workers/orchestration-structured-worker-session' import { sessionIdFromStructuredWorkerIncarnation } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { readExactWorkerOutput } from './worker-output' -import { exposeWorkerTerminalResource } from './worker-terminal-resource-presentation' +import { readExactWorkerOutput } from './output/worker-output' +import { exposeWorkerTerminalResource } from './release/worker-terminal-resource-presentation' import { liveWorkerTerminalAutoReleaseAt } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' import { readFederatedWorkerOutput } from '../../../../orchestration/legacy-remote-home/federated-worker-read' import { showFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-show' import { WorkerDispatchParams, WorkerReadParams -} from '../../../../../../shared/rpc-contract/orchestration-worker-control-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-worker-control-params' export const ORCHESTRATION_WORKER_CONTROL_METHODS = [ defineOrchestrationMethod({ @@ -139,6 +140,10 @@ export const ORCHESTRATION_WORKER_CONTROL_METHODS = [ ? 'exited' : 'unverifiable' } + if (isStructuredWorkerHandle(resource.terminal_handle)) { + // A released chat's history is read from its closed session, which needs the host after a restart. + await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + } const archived = await readArchivedWorkerOutput({ db, dispatchId: params.dispatch, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts deleted file mode 100644 index a7468862a07..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import { getFollowUpDispatch } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' -import './worker-resume-session-capture' -import { - continueAllUnreadWorkerMail, - continueUnreadWorkerMail -} from '../messaging/settled-worker-follow-through' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -// A send to a finished terminal worker, through the same worker-start the coordinator would run. -describe('a follow-up to a finished terminal worker', () => { - const h = createOrchestrationWorkerReleaseHarness() - let userDataDir: string | undefined - - afterEach(() => { - getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() - h.cleanup() - if (userDataDir) { - rmSync(userDataDir, { recursive: true, force: true }) - userDataDir = undefined - } - }) - - const send = (dispatchId: string, body: string) => - h.call('orchestration.send', { - from: 'term_coord', - to: `dispatch:${dispatchId}`, - subject: 'More', - body - }) - - it('retries a follow-up a restart interrupted before it placed an agent, with the mail it took', async () => { - userDataDir = mkdtempSync(join(tmpdir(), 'orca-follow-up-midstart-')) - h.setup({ userDataDir }) - const { taskId, dispatchId } = await h.startWorker() - await send(dispatchId, 'DO NOT PUSH') - h.settle(taskId, dispatchId, 'succeeded') - // The claim commits; the app quits before the start places an agent. - const claimed = h.db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: 9, - taskSpec: 'New messages', - taskRunId: h.activeRunId, - startOptions: { agent: 'codex' }, - runtimeEpoch: 'runtime_before_restart', - followUpOf: dispatchId, - takesMailOf: dispatchId - }).dispatch.id - - h.restart() - - await vi.waitFor(() => expect(getFollowUpDispatch(h.db, claimed)).toBeDefined()) - const retry = getFollowUpDispatch(h.db, claimed)! - await vi.waitFor(() => - expect(h.db.getUnreadMessages(`dispatch:${retry.id}`)).toMatchObject([ - { body: 'DO NOT PUSH' } - ]) - ) - }) - - it('keeps the mail a stopped follow-up never read for the next send, without restarting it', async () => { - h.setup() - const { taskId, dispatchId } = await h.startWorker() - await send(dispatchId, 'DO NOT PUSH') - h.settle(taskId, dispatchId, 'succeeded') - continueAllUnreadWorkerMail(h.runtime, h.db) - await vi.waitFor(() => - expect(h.db.getWorkerDispatch(getFollowUpDispatch(h.db, dispatchId)?.id ?? '')?.state).toBe( - 'ready' - ) - ) - const stopped = getFollowUpDispatch(h.db, dispatchId)!.id - h.db.beginWorkerStop(stopped, h.runtime.getRuntimeId()) - h.db.settleWorkerStop(stopped) - - continueAllUnreadWorkerMail(h.runtime, h.db) - expect(getFollowUpDispatch(h.db, stopped)).toBeUndefined() - - await send(dispatchId, 'and the docs') - const next = getFollowUpDispatch(h.db, stopped)! - await vi.waitFor(() => - expect(h.db.getUnreadMessages(`dispatch:${next.id}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) - ) - }) - - it('keeps the mail a failed follow-up took when a replayed report ran during its start', async () => { - h.setup() - const { taskId, dispatchId } = await h.startWorker() - await send(dispatchId, 'DO NOT PUSH') - h.settle(taskId, dispatchId, 'succeeded') - vi.mocked(h.runtime.sendTerminalAgentPrompt).mockImplementationOnce(async () => { - // The replay finds no unread mail, since the start took it, and clears the marker. - continueUnreadWorkerMail(h.runtime, h.db, dispatchId) - throw new Error('prompt lost') - }) - - continueAllUnreadWorkerMail(h.runtime, h.db) - - await vi.waitFor(() => expect(getFollowUpDispatch(h.db, dispatchId)).toBeDefined()) - const failed = getFollowUpDispatch(h.db, dispatchId)!.id - await vi.waitFor(() => - expect(h.db.getUnreadMessages(`dispatch:${failed}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) - ) - }) - - it('lists the finished worker without the terminal its follow-up took over', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - await send(dispatchId, 'and the docs') - const followUpId = getFollowUpDispatch(h.db, dispatchId)!.id - expect(h.db.getWorkerTerminalResourceByOwner(followUpId)?.terminal_handle).toBe('term_worker') - - await expect(h.call('orchestration.workerList', { run: h.activeRunId })).resolves.toMatchObject( - { - workers: expect.arrayContaining([ - expect.objectContaining({ - dispatchId, - agentTerminalHandle: null, - terminalState: null, - projection: expect.objectContaining({ - // Nothing proves the original's process ended, so liveness stays unverifiable. - liveness: { verdict: 'unverifiable', reason: 'missing_status' }, - nextAction: expect.objectContaining({ kind: 'none' }) - }) - }), - expect.objectContaining({ - dispatchId: followUpId, - agentTerminalHandle: 'term_worker', - terminalState: 'active' - }) - ]), - counts: { active: 1 } - } - ) - - // A -> B -> C, then C's release: neither earlier row claims the terminal. - const b = getFollowUpDispatch(h.db, dispatchId)! - h.settle(b.task_id, b.id, 'succeeded') - await send(b.id, 'and the tests') - const c = getFollowUpDispatch(h.db, b.id)! - h.settle(c.task_id, c.id, 'succeeded') - await expect(h.call('orchestration.workerRelease', { dispatch: c.id })).resolves.toMatchObject({ - state: 'released' - }) - const handedOn = (id: string) => - expect.objectContaining({ dispatchId: id, agentTerminalHandle: null, terminalState: null }) - await expect(h.call('orchestration.workerList', { run: h.activeRunId })).resolves.toMatchObject( - { - workers: [ - expect.objectContaining({ - dispatchId: c.id, - agentTerminalHandle: 'term_worker', - terminalState: 'released' - }), - handedOn(b.id), - handedOn(dispatchId) - ], - counts: { released: 1 } - } - ) - await expect( - h.call('orchestration.workerList', { run: h.activeRunId, terminalState: 'retained' }) - ).resolves.toMatchObject({ workers: [] }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts deleted file mode 100644 index 92a159d9abc..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -// Drive real detector/plumbing through RPC to distinguish workers waiting on human prompts (STA-3714, STA-4513). -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' - -vi.mock('electron', () => ({ - BrowserWindow: { fromId: vi.fn(() => null) }, - webContents: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - app: { getPath: vi.fn(() => '/tmp') } -})) - -const LEAF_ID = '22222222-2222-4222-8222-222222222222' -const TAB_ID = 'tab-worker' -const WORKTREE_ID = 'wt-worker' -const PTY_ID = 'pty-worker' - -// Captured verbatim from cursor-agent 2026.08.11-e8db854 driven through Orca. -function fixture(name: string): string { - return readFileSync(join(__dirname, '../../../../__fixtures__', `${name}.txt`), 'utf8') -} - -function workerShowMethod() { - const method = ORCHESTRATION_METHODS.find( - (candidate) => candidate.name === 'orchestration.workerShow' - ) - if (!method) { - throw new Error('Missing method orchestration.workerShow') - } - return method -} - -describe('worker-show interactive wait (STA-3714, STA-4513)', () => { - let db: OrchestrationDb | undefined - - afterEach(() => db?.close()) - - async function showWorkerPaneServing(paneOutput: string, opts?: { breakIdentity?: boolean }) { - const runtime = new OrcaRuntimeService(null) - const internals = runtime as unknown as { - resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise - } - vi.spyOn(internals, 'resolveTerminalWorkspaceLaunchScope').mockResolvedValue({ - id: WORKTREE_ID, - path: '/repo/app', - connectionId: null, - repo: null, - folderWorkspace: null - }) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: PTY_ID, incarnationId: 'inc-1' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'cursor-agent' - }) - const terminal = await runtime.createTerminal(`id:${WORKTREE_ID}`, { - tabId: TAB_ID, - leafId: LEAF_ID, - title: 'worker' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'worker', - activeLeafId: LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - leafId: LEAF_ID, - paneRuntimeId: 1, - ptyId: PTY_ID, - // cursor-agent's spinner title, identical whether it runs or waits. - paneTitle: '⠇ Cursor Agent' - } - ] - }) - runtime.onPtyData(PTY_ID, paneOutput, Date.now()) - - db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'supervise lanes', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_coord:leaf_coord' - }) - const task = db.createTask({ spec: 'run the suite', runId: run.id }) - const paneKey = runtime.getTerminalPaneKey(terminal.handle) - const incarnation = runtime.getTerminalProcessIncarnation(terminal.handle) - if (!paneKey || !incarnation) { - throw new Error('Runtime did not expose the worker pane identity.') - } - const dispatch = createRootDispatch( - db, - task.id, - terminal.handle, - paneKey, - 'launch-hash', // A dispatch recorded against a process that has since been replaced. - opts?.breakIdentity === true ? `${incarnation}:replaced` : incarnation - ) - - const method = workerShowMethod() - return method.handler(method.params?.parse({ dispatch: dispatch.id }), { runtime }) - } - - it('names the pending prompt on the observation a coordinator polls', async () => { - const result = await showWorkerPaneServing(fixture('cursor-agent-approval-prompt')) - - expect(result).toMatchObject({ - observation: { - exactWorker: true, - agentWait: { - source: 'prompt-text', - reason: 'agent-approval-prompt', - since: expect.any(Number) - } - } - }) - }) - - it('reports an explicit null for the same lane inside a long tool call', async () => { - // Explicit null means checked-and-not-waiting; absence preserves compatibility with hosts too old to know. - const result = await showWorkerPaneServing(fixture('cursor-agent-long-tool-call')) - - expect(result).toMatchObject({ observation: { exactWorker: true, agentWait: null } }) - }) - - it('omits the field entirely for a worker it could not verify', async () => { - // Replaced processes were never checked; null would falsely claim no wait. - const result = (await showWorkerPaneServing(fixture('cursor-agent-approval-prompt'), { - breakIdentity: true - })) as { observation: Record } - - expect(result.observation.exactWorker).toBe(false) - expect('agentWait' in result.observation).toBe(false) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts index 8d5f269f1eb..6cc31c5090a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts @@ -4,12 +4,12 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-erro import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' import { keptOpenStopRefusal } from '../../../../orchestration/db/worker-terminal/worker-terminal-user-keep' -import { callFederatedWorkerShow } from './worker-observation' +import { callFederatedWorkerShow } from './observation/worker-observation' import { resolveStructuredWorkerIdentityForSession } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import { OrchestrationWorkerKeepOpenParams, OrchestrationWorkerSubjectParams -} from '../../../../../../shared/rpc-contract/orchestration-worker-release-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-worker-release-params' export const ORCHESTRATION_WORKER_KEEP_OPEN_METHODS = [ defineOrchestrationMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts index 7ee074feebc..cfaf81b9af8 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts @@ -11,20 +11,20 @@ import { encodeWorkerListCursor, type WorkerListCursor, type WorkerListInventory -} from './worker-list-cursor' +} from './fleet/worker-list-cursor' import { createWorkerListSnapshot, ORCHESTRATION_WORKER_LIST_SNAPSHOT_MAX_ROWS, pinWorkerListSnapshot, readWorkerListSnapshot -} from './worker-list-snapshot-store' -import { projectWorkerListFleet, type WorkerListPageParams } from './worker-list-projection' -import { exposeWorkerTerminalResource } from './worker-terminal-resource-presentation' +} from './fleet/worker-list-snapshot-store' +import { projectWorkerListFleet, type WorkerListPageParams } from './fleet/worker-list-projection' +import { exposeWorkerTerminalResource } from './release/worker-terminal-resource-presentation' import { withRemoteWorkerRows } from '../../../../orchestration/federation/remote-owned/remote-owned-reads' import { WORKER_TERMINAL_LIST_STATES, WorkerListParams -} from '../../../../../../shared/rpc-contract/orchestration-worker-release-schemas-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-worker-release-schemas-params' export const emptyWorkerListPage = (limit: number) => ({ workers: [], diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-pagination.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-pagination.test.ts deleted file mode 100644 index 5a2f24acffb..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-pagination.test.ts +++ /dev/null @@ -1,476 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type Database from '../../../../../sqlite/sync-database' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { encodeWorkerListCursor } from './worker-list-cursor' -import { ORCHESTRATION_WORKER_LIST_METHOD } from './worker-list-method' - -type WorkerListResult = { - workers: { - dispatchId: string - projection: { attention: { categories: string[] } } - }[] - counts: Record - page: { total: number; hasMore: boolean; nextCursor: string | null } - warnings?: string[] -} - -describe('orchestration worker-list pagination', () => { - let db: OrchestrationDb | undefined - - afterEach(() => db?.close()) - - it('returns a complete filtered legacy result while current clients page above 100 rows', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Mixed-version worker inventory', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - for (let index = 0; index < 125; index += 1) { - insertDispatch(db, run.id, `dispatch-${String(index).padStart(3, '0')}`) - } - - const legacy = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained' - }) - expect(legacy.workers).toHaveLength(125) - expect(legacy.page).toEqual({ total: 125, limit: 5_000, hasMore: false, nextCursor: null }) - - const first = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - paginate: true - }) - expect(first.workers).toHaveLength(100) - expect(first.page).toMatchObject({ total: 125, hasMore: true }) - expect(first.page.nextCursor).toEqual(expect.any(String)) - expect(first.page.nextCursor).not.toBe('dispatch-099') - - const second = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - paginate: true, - cursor: first.page.nextCursor - }) - expect(second.workers).toHaveLength(25) - expect(second.page).toEqual({ total: 125, limit: 100, hasMore: false, nextCursor: null }) - }) - - it('opens on the newest Dispatches, warns that the page truncated, and pages down', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Newest-first worker inventory', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - const id = (index: number): string => `dispatch-${String(index).padStart(3, '0')}` - for (let index = 1; index <= 105; index += 1) { - insertDispatch(db, run.id, id(index)) - } - - const first = await callWorkerList(runtime, { run: run.id, paginate: true }) - - expect(first.workers.map((worker) => worker.dispatchId)).toEqual( - Array.from({ length: 100 }, (_, offset) => id(105 - offset)) - ) - expect(first.page).toMatchObject({ total: 105, hasMore: true }) - expect(first.warnings).toEqual([ - 'Showing 100 of 105 Dispatches, newest first; more are on later pages. Follow page.nextCursor with --cursor.' - ]) - expect(first.counts).toEqual({ retained: 105 }) - - insertDispatch(db, run.id, 'dispatch-after-first-call') - const second = await callWorkerList(runtime, { - run: run.id, - paginate: true, - cursor: first.page.nextCursor - }) - - expect(second.workers.map((worker) => worker.dispatchId)).toEqual([5, 4, 3, 2, 1].map(id)) - expect(second.page).toEqual({ total: 105, limit: 100, hasMore: false, nextCursor: null }) - expect(second.warnings).toBeUndefined() - expect(second.counts).toEqual({ retained: 105 }) - }) - - it('repeats the first page counts on later pages of the same snapshot', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Counted once per snapshot', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-z') - - const first = await callWorkerList(runtime, { run: run.id, limit: 1 }) - expect(first.counts).toEqual({ retained: 2 }) - - sqliteFor(db) - .prepare('UPDATE dispatch_contexts SET assignee_handle = NULL WHERE id = ?') - .run('dispatch-a') - const second = await callWorkerList(runtime, { - run: run.id, - limit: 1, - cursor: first.page.nextCursor - }) - - expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) - expect(second.page).toEqual({ total: 2, limit: 1, hasMore: false, nextCursor: null }) - expect(second.counts).toEqual({ retained: 2 }) - }) - - it('expires a pre-rowid cursor whose anchor row a reset deleted', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Old cursor', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-m') - insertDispatch(db, run.id, 'dispatch-z') - // Old binaries never wrote `databaseId`; this is the exact shape they mint. - const cursor = encodeWorkerListCursor({ - version: 2, - snapshot: { databaseId: 3 }, - after: { createdAt: '2026-08-27 00:00:00', dispatchId: 'dispatch-z' } - }) - const ok = await callWorkerList(runtime, { run: run.id, limit: 10, cursor }) - expect(ok.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-m', 'dispatch-a']) - - sqliteFor(db).prepare('DELETE FROM dispatch_contexts WHERE id = ?').run('dispatch-z') - - // `rowid < NULL` used to exclude every row: zero workers against a non-zero total. - await expect(callWorkerList(runtime, { run: run.id, limit: 10, cursor })).rejects.toMatchObject( - { - code: 'worker_list_cursor_expired' - } - ) - }) - - it('keeps filtered snapshot membership when a later worker changes state', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Stable filtered inventory', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-z') - - const first = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1 - }) - expect(first.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-z']) - expect(first.page).toMatchObject({ total: 2, hasMore: true }) - - sqliteFor(db) - .prepare('UPDATE dispatch_contexts SET assignee_handle = NULL WHERE id = ?') - .run('dispatch-a') - const second = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1, - cursor: first.page.nextCursor - }) - - expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) - expect(second.page).toEqual({ total: 2, limit: 1, hasMore: false, nextCursor: null }) - // The pinned total and the counts have to describe the same rows. - expect(second.counts).toEqual({ retained: second.page.total }) - }) - - it('keeps an include-remote filtered page pinned across 32 concurrent snapshot allocations', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Pinned filtered inventory', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-z') - vi.spyOn(db, 'listFederatedDispatchesByIds').mockImplementation((dispatchIds) => - dispatchIds.includes('dispatch-z') ? [federatedDispatch('dispatch-z')] : [] - ) - vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({ - environmentId: 'environment-remote', - name: 'remote', - peerFingerprint: 'peer-remote', - pairingRevision: 1 - }) - let resolveSnapshot!: () => void - const snapshotGate = new Promise((resolve) => { - resolveSnapshot = resolve - }) - const remoteCall = vi - .spyOn(runtime, 'callOrchestrationWorkerServer') - .mockImplementation(async () => { - await snapshotGate - return { - runtimeEpoch: 'epoch-remote', - items: [ - { - dispatchId: 'dispatch-z', - observation: { status: 'live', exactWorker: true } - } - ] - } - }) - - const pending = callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - includeRemote: true, - limit: 1 - }) - await vi.waitFor(() => - expect(remoteCall).toHaveBeenCalledWith( - 'environment-remote', - 'orchestration.federationFleetSnapshot', - { dispatchIds: ['dispatch-z'] }, - expect.any(Number), - undefined, - { expectedEnvironmentPairingRevision: 1 } - ) - ) - for (let call = 0; call < 32; call += 1) { - await callWorkerList(runtime, { run: run.id, terminalState: 'retained', limit: 1 }) - } - resolveSnapshot() - - const first = await pending - expect(first).toMatchObject({ - workers: [{ dispatchId: 'dispatch-z' }], - page: { total: 2, hasMore: true, nextCursor: expect.any(String) } - }) - const second = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1, - cursor: first.page.nextCursor - }) - expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) - }) - - it('does not allocate filtered snapshots when the first page has no more rows', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Snapshot-free terminal page', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-z') - const first = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1 - }) - - for (let call = 0; call < 32; call += 1) { - const terminalPage = await callWorkerList(runtime, { - run: run.id, - terminalState: 'released', - limit: 1 - }) - expect(terminalPage.page).toMatchObject({ total: 0, hasMore: false, nextCursor: null }) - } - const second = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1, - cursor: first.page.nextCursor - }) - - expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) - }) - - it('never re-emits a row whose worker registers between pages', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Stable order key', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-z') - - const seen: string[] = [] - let cursor: string | null = null - for (let page = 0; page < 5; page += 1) { - const result: WorkerListResult = await callWorkerList(runtime, { - run: run.id, - limit: 1, - ...(cursor ? { cursor } : {}) - }) - seen.push(...result.workers.map((worker) => worker.dispatchId)) - if (page === 0) { - // A worker row lands for the page-1 row; its COALESCE(created_at) sort key moves forward. - sqliteFor(db) - .prepare( - `INSERT INTO worker_dispatches (dispatch_id, state, stage, agent_terminal_handle, created_at) - VALUES (?, 'ready', 'ready', ?, '2026-08-27 01:00:00')` - ) - .run('dispatch-a', 'term-dispatch-a') - } - cursor = result.page.nextCursor - if (!cursor) { - break - } - } - - expect(seen).toEqual(['dispatch-z', 'dispatch-a']) - }) - - it('counts only the rows a pinned filtered cursor can still reach', async () => { - db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Pinned filtered counts', - coordinatorHandle: 'term-coordinator', - coordinatorPaneKey: 'tab-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - insertDispatch(db, run.id, 'dispatch-a') - insertDispatch(db, run.id, 'dispatch-z') - - const first = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1 - }) - expect(first.page).toMatchObject({ total: 2, hasMore: true }) - expect(first.counts).toEqual({ retained: 2 }) - - insertDispatch(db, run.id, 'dispatch-m') - const second = await callWorkerList(runtime, { - run: run.id, - terminalState: 'retained', - limit: 1, - cursor: first.page.nextCursor - }) - - expect(second.workers.map((worker) => worker.dispatchId)).toEqual(['dispatch-a']) - expect(second.page.total).toBe(2) - expect(second.counts).toEqual({ retained: 2 }) - }) - - describe('a legacy cursor anchored outside the requested Run', () => { - function twoRuns(): { runA: string; runB: string } { - db = new OrchestrationDb(':memory:') - const runA = db.createRun({ - objective: 'A', - coordinatorHandle: 'term-a', - coordinatorPaneKey: 'tab-a:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - const runB = db.createRun({ - objective: 'B', - coordinatorHandle: 'term-b', - coordinatorPaneKey: 'tab-b:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - }) - insertDispatch(db, runA.id, 'a-1') - insertDispatch(db, runA.id, 'a-2') - insertDispatch(db, runB.id, 'b-1') - insertDispatch(db, runB.id, 'b-2') - return { runA: runA.id, runB: runB.id } - } - - // Both shapes used to resolve to a rowid past Run A's rows and report a finished, empty page. - it('expires a v2 cursor that must be resolved from a foreign anchor', async () => { - const { runA } = twoRuns() - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db!) - const foreign = encodeWorkerListCursor({ - version: 2, - snapshot: { databaseId: 4 }, - after: { createdAt: '2026-08-27 00:00:00', dispatchId: 'b-1' } - }) - - await expect( - callWorkerList(runtime, { run: runA, limit: 10, cursor: foreign }) - ).rejects.toThrow(/changed destructively/u) - }) - - it('expires a v2 cursor that carries a foreign rowid', async () => { - const { runA } = twoRuns() - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db!) - const foreign = encodeWorkerListCursor({ - version: 2, - snapshot: { databaseId: 4 }, - after: { createdAt: '2026-08-27 00:00:00', dispatchId: 'b-1', databaseId: 3 } - }) - - await expect( - callWorkerList(runtime, { run: runA, limit: 10, cursor: foreign }) - ).rejects.toThrow(/changed destructively/u) - }) - }) -}) - -async function callWorkerList( - runtime: OrcaRuntimeService, - params: Record -): Promise { - const parsed = ORCHESTRATION_WORKER_LIST_METHOD.params?.parse(params) - return (await ORCHESTRATION_WORKER_LIST_METHOD.handler(parsed, { runtime })) as WorkerListResult -} - -function insertDispatch(db: OrchestrationDb, runId: string, dispatchId: string): void { - const task = db.createTask({ spec: dispatchId, runId }) - sqliteFor(db) - .prepare( - `INSERT INTO dispatch_contexts ( - id, run_id, task_id, assignee_handle, status, created_at - ) VALUES (?, ?, ?, ?, 'dispatched', '2026-08-27 00:00:00')` - ) - .run(dispatchId, runId, task.id, `term-${dispatchId}`) -} - -function sqliteFor(db: OrchestrationDb): Database.Database { - return (db as unknown as { db: Database.Database }).db -} - -function federatedDispatch(dispatchId: string): FederatedDispatchRow { - return { - dispatch_id: dispatchId, - environment_id: 'environment-remote', - environment_name: 'remote', - peer_fingerprint: 'peer-remote', - remote_runtime_epoch: 'epoch-remote', - protocol_version: 3, - remote_worktree_id: null, - remote_terminal_handle: null, - to_home_imported_sequence: 0, - to_home_acknowledged_sequence: 0, - home_auto_release_at: null, - home_auto_release_state: null, - created_at: '2026-08-27 00:00:00', - updated_at: '2026-08-27 00:00:00' - } -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts index f7e9135e93f..7ea4b64fe74 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts @@ -1,7 +1,7 @@ import { ORCHESTRATION_WORKER_CONTROL_METHODS } from './worker-control' import { ORCHESTRATION_WORKER_RELEASE_METHODS } from './worker-release' import { ORCHESTRATION_WORKER_STOP_METHODS } from './worker-stop' -import { ORCHESTRATION_WORKER_START_METHODS } from './workers' +import { ORCHESTRATION_WORKER_START_METHODS } from './worker-start-method' import { ORCHESTRATION_WORKER_APPROVAL_METHODS } from './worker-approval-answer' export const ORCHESTRATION_WORKER_METHODS = [ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-output.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-output.test.ts deleted file mode 100644 index 6d02ca046c9..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-output.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { readExactWorkerOutput } from './worker-output' - -function codexMessage(id: string, text: string): string { - return JSON.stringify({ - type: 'event_msg', - payload: { id, type: 'agent_message', message: text } - }) -} - -describe('exact orchestration worker output', () => { - let directory: string - let transcriptA: string - let transcriptB: string - let providerSession: ReturnType - let runtime: OrcaRuntimeService - const readTerminal = vi.fn() - - beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'orca-worker-output-')) - transcriptA = join(directory, 'session-a.jsonl') - transcriptB = join(directory, 'session-b.jsonl') - await writeFile(transcriptA, `${codexMessage('a', 'worker A only')}\n`) - await writeFile(transcriptB, `${codexMessage('b', 'worker B only')}\n`) - providerSession = { - paneKey: 'tab:worker', - processIncarnation: 'pty:incarnation-1', - agent: 'codex', - providerSession: { - key: 'session_id', - id: 'session-a', - transcriptPath: transcriptA - }, - observedAt: Date.now() - } - readTerminal.mockReset() - readTerminal.mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: ['terminal output'], - truncated: false, - nextCursor: '9' - }) - runtime = { - getExactWorkerProviderSession: vi.fn(() => providerSession), - getTerminalProcessIncarnation: vi.fn(() => 'pty:incarnation-1'), - getTerminalPaneKey: vi.fn(() => 'tab:worker'), - readTerminal - } as unknown as OrcaRuntimeService - }) - - afterEach(async () => { - await rm(directory, { recursive: true, force: true }) - }) - - const read = (overrides: Partial[0]> = {}) => - readExactWorkerOutput({ - runtime, - dispatchId: 'dispatch_1', - terminalHandle: 'term_worker', - workerState: 'ready', - terminalStatus: 'running', - attachedAt: '2026-07-24 00:00:00', - ...overrides - }) - - it('reads only the exact pane session and keeps its local path private', async () => { - const result = await read() - - expect(result).toMatchObject({ - source: 'transcript', - provider: 'codex', - transcript: { - messages: [{ id: 'a', blocks: [{ type: 'text', text: 'worker A only' }] }] - } - }) - expect(JSON.stringify(result)).not.toContain(transcriptA) - expect(JSON.stringify(result)).not.toContain('worker B only') - expect(readTerminal).not.toHaveBeenCalled() - }) - - it('labels OpenCode as a terminal fallback when no transcript decoder exists', async () => { - const capability = `dcap_${'A'.repeat(43)}` - readTerminal.mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: [`opencode --dispatch-capability ${capability}`], - truncated: false, - nextCursor: '9' - }) - providerSession = { - ...providerSession!, - agent: 'opencode', - providerSession: { - key: 'session_id', - id: 'session-opencode', - transcriptPath: transcriptA - } - } - - const result = await read() - - expect(result).toMatchObject({ - source: 'terminal', - fallbackReason: 'provider_unsupported', - terminal: { tail: ['opencode --dispatch-capability [dispatch capability redacted]'] }, - warnings: [ - 'Dispatch capability tokens were redacted from terminal output.', - 'Terminal wrap information was unavailable; capability masking used complete lines.' - ] - }) - expect(JSON.stringify(result)).not.toContain(capability) - }) - - it('redacts dispatch capabilities from terminal composer drafts', async () => { - const capability = `dcap_${'A'.repeat(43)}` - readTerminal.mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: ['safe output'], - draft: `send --dispatch-capability ${capability}`, - truncated: false, - nextCursor: '9' - }) - providerSession = null - - const result = await read() - - expect(result).toMatchObject({ - source: 'terminal', - terminal: { - tail: ['safe output'], - draft: 'send --dispatch-capability [dispatch capability redacted]' - }, - warnings: [ - 'Dispatch capability tokens were redacted from terminal output.', - 'Terminal wrap information was unavailable; capability masking used complete lines.' - ] - }) - expect(JSON.stringify(result)).not.toContain(capability) - }) - - it('rejects an old cursor after the exact provider session changes', async () => { - const initial = await read() - if (initial.source !== 'transcript') { - throw new Error('Expected transcript output') - } - providerSession = { - ...providerSession!, - providerSession: { - key: 'session_id', - id: 'session-b', - transcriptPath: transcriptB - } - } - - await expect(read({ cursor: initial.cursor })).rejects.toMatchObject({ - code: 'source_changed' - }) - }) - - it('rejects an old cursor after a same-inode truncate/regrow', async () => { - const initial = await read() - if (initial.source !== 'transcript') { - throw new Error('Expected transcript output') - } - const before = await stat(transcriptA, { bigint: true }) - await writeFile( - transcriptA, - `${codexMessage('replacement', 'unrelated transcript')}\n${' '.repeat(512)}` - ) - const after = await stat(transcriptA, { bigint: true }) - expect(after.ino).toBe(before.ino) - expect(after.dev).toBe(before.dev) - const fresh = await read() - if (fresh.source !== 'transcript') { - throw new Error('Expected replacement transcript output') - } - expect(fresh.sourceIdentity).toBe(initial.sourceIdentity) - - await expect(read({ cursor: initial.cursor })).rejects.toMatchObject({ - code: 'source_changed' - }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-output.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-output.ts deleted file mode 100644 index 693dba21add..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-output.ts +++ /dev/null @@ -1,250 +0,0 @@ -import type { - OrchestrationWorkerReadFallbackReason, - OrchestrationWorkerReadResult, - OrchestrationWorkerReadSource -} from '../../../../../../shared/orchestration/workers/orchestration-worker-output' -import type { RuntimeTerminalState } from '../../../../../../shared/runtime-terminal-contracts' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { - createWorkerOutputSourceIdentity, - decodeWorkerOutputCursor, - encodeWorkerOutputCursor -} from '../../../../orchestration/workers/transcripts/worker-output-cursor' -import { redactWorkerTerminalView } from '../../../../orchestration/terminal-authority/views/worker-terminal-redaction' -import { readWorkerTranscript } from '../../../../orchestration/workers/transcripts/worker-transcript-read' -import { isWslHookRelayConnectionId } from '../../../../../../shared/wsl-hook-relay-contract' - -export async function readExactWorkerOutput(args: { - runtime: OrcaRuntimeService - dispatchId: string - terminalHandle: string - workerState: string - terminalStatus: RuntimeTerminalState - terminalLiveness?: 'live' | 'unverifiable' | 'exited' - attachedAt: string - source?: OrchestrationWorkerReadSource - cursor?: string | number - limit?: number -}): Promise { - const source = args.source ?? 'auto' - const cursor = decodeWorkerOutputCursor(args.cursor, args.dispatchId) - assertCursorSourceMatchesRequest(cursor?.source, source) - - if (cursor?.source === 'terminal' || source === 'terminal') { - return readTerminalOutput(args, cursor) - } - - const observedAfter = orchestrationTimestampToMs(args.attachedAt) - const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, observedAfter) - if (!session) { - if (cursor?.source === 'transcript') { - throw sourceChanged() - } - return fallbackOrThrow(args, 'session_not_reported') - } - const isWslSession = isWslHookRelayConnectionId(session.connectionId) - if (isWslSession && !session.wslDistro) { - return fallbackOrThrow(args, 'remote_capability_unavailable') - } - // Why: this process serves no SSH filesystem, so an SSH worker's transcript is unreachable. - if (session.connectionId && !isWslSession) { - return fallbackOrThrow(args, 'remote_capability_unavailable') - } - if (cursor?.source === 'transcript' && !cursor.boundaryCheckpoint) { - throw sourceChanged() - } - const transcript = await readWorkerTranscript({ - agent: session.agent, - sessionId: session.providerSession.id, - transcriptPath: session.providerSession.transcriptPath, - wslDistro: session.wslDistro, - offset: cursor?.source === 'transcript' ? cursor.position : undefined, - expectedBoundaryCheckpoint: - cursor?.source === 'transcript' ? (cursor.boundaryCheckpoint ?? undefined) : undefined, - limit: args.limit - }) - if (!transcript.ok) { - if (transcript.reason === 'source_changed') { - throw sourceChanged() - } - if (cursor?.source === 'transcript') { - throw transcriptRequired(args.dispatchId, transcript.reason) - } - return fallbackOrThrow(args, transcript.reason, transcript.warnings) - } - const sourceIdentity = createWorkerOutputSourceIdentity([ - 'transcript', - session.processIncarnation, - session.agent, - session.providerSession.key, - session.providerSession.id, - session.connectionId ?? 'local', - transcript.filePath, - transcript.sourceFingerprint - ]) - if (cursor?.source === 'transcript' && cursor.sourceIdentity !== sourceIdentity) { - throw sourceChanged() - } - const sessionAfterRead = args.runtime.getExactWorkerProviderSession( - args.terminalHandle, - observedAfter - ) - if ( - !sessionAfterRead || - sessionAfterRead.processIncarnation !== session.processIncarnation || - sessionAfterRead.agent !== session.agent || - sessionAfterRead.providerSession.key !== session.providerSession.key || - sessionAfterRead.providerSession.id !== session.providerSession.id || - sessionAfterRead.providerSession.transcriptPath !== session.providerSession.transcriptPath || - sessionAfterRead.connectionId !== session.connectionId || - sessionAfterRead.wslDistro !== session.wslDistro - ) { - throw sourceChanged() - } - const nextCursor = encodeWorkerOutputCursor( - args.dispatchId, - 'transcript', - sourceIdentity, - transcript.nextOffset, - transcript.boundaryCheckpoint - ) - return { - dispatchId: args.dispatchId, - source: 'transcript', - sourceIdentity, - provider: session.agent, - transcript: { - messages: transcript.messages, - nextCursor, - limited: transcript.limited, - returnedMessageCount: transcript.messages.length - }, - cursor: nextCursor, - status: { - worker: args.workerState, - terminal: args.terminalStatus, - ...(args.terminalLiveness ? { liveness: args.terminalLiveness } : {}) - }, - fallbackReason: null, - warnings: transcript.warnings, - sourceExact: true, - contentComplete: !transcript.limited, - ...(transcript.clipping.length > 0 ? { clipping: transcript.clipping } : {}) - } -} - -async function readTerminalOutput( - args: Parameters[0], - cursor: ReturnType -): Promise { - const processIncarnation = args.runtime.getTerminalProcessIncarnation(args.terminalHandle) - const paneKey = args.runtime.getTerminalPaneKey(args.terminalHandle) - if (!processIncarnation || !paneKey) { - throw new OrchestrationError( - 'worker_identity_changed', - `Worker Dispatch ${args.dispatchId} no longer resolves to its exact process.` - ) - } - const sourceIdentity = createWorkerOutputSourceIdentity(['terminal', processIncarnation, paneKey]) - if ( - cursor?.source === 'terminal' && - cursor.sourceIdentity !== null && - cursor.sourceIdentity !== sourceIdentity - ) { - throw sourceChanged() - } - const terminal = await args.runtime.readTerminal(args.terminalHandle, { - cursor: cursor?.source === 'terminal' ? cursor.position : undefined, - limit: args.limit - }) - const redactedTerminal = redactWorkerTerminalView(terminal) - const position = - terminal.nextCursor !== null && /^\d+$/.test(terminal.nextCursor) - ? Number.parseInt(terminal.nextCursor, 10) - : null - const nextCursor = - position === null - ? null - : encodeWorkerOutputCursor(args.dispatchId, 'terminal', sourceIdentity, position) - return { - dispatchId: args.dispatchId, - source: 'terminal', - sourceIdentity, - terminal: { - ...terminal, - tail: redactedTerminal.tail, - ...(redactedTerminal.draft ? { draft: redactedTerminal.draft } : {}) - }, - cursor: nextCursor, - status: { - worker: args.workerState, - terminal: args.terminalLiveness === 'unverifiable' ? args.terminalStatus : terminal.status, - ...(args.terminalLiveness ? { liveness: args.terminalLiveness } : {}) - }, - fallbackReason: null, - warnings: redactedTerminal.warnings, - sourceExact: true, - contentComplete: !terminal.truncated, - ...(terminal.truncated ? { clipping: ['terminal_buffer'] } : {}) - } -} - -async function fallbackOrThrow( - args: Parameters[0], - reason: OrchestrationWorkerReadFallbackReason, - warnings: string[] = [] -): Promise { - if (args.source === 'transcript') { - throw transcriptRequired(args.dispatchId, reason) - } - const fallback = await readTerminalOutput(args, null) - return fallback.source === 'terminal' - ? { - ...fallback, - fallbackReason: reason, - sourceExact: false, - contentComplete: false, - clipping: [...(fallback.clipping ?? []), 'terminal_fallback'], - warnings: [...new Set([...fallback.warnings, ...warnings])] - } - : fallback -} - -function assertCursorSourceMatchesRequest( - cursorSource: 'terminal' | 'transcript' | undefined, - requestedSource: OrchestrationWorkerReadSource -): void { - if (cursorSource && requestedSource !== 'auto' && cursorSource !== requestedSource) { - throw new OrchestrationError( - 'cursor_invalid', - `The worker-read cursor is pinned to ${cursorSource} output.` - ) - } -} - -export function orchestrationTimestampToMs(value: string): number { - const normalized = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(value) - ? `${value.replace(' ', 'T')}Z` - : value - const parsed = Date.parse(normalized) - return Number.isFinite(parsed) ? parsed : 0 -} - -function sourceChanged(): OrchestrationError { - return new OrchestrationError( - 'source_changed', - 'The worker output source changed. Start a fresh worker-read without the old cursor.' - ) -} - -function transcriptRequired( - dispatchId: string, - reason: OrchestrationWorkerReadFallbackReason -): OrchestrationError { - return new OrchestrationError( - 'transcript_required', - `Structured output is unavailable for Dispatch ${dispatchId}: ${reason}.`, - { reason } - ) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts deleted file mode 100644 index 62827e93b6d..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../../../../shared/orchestration/orchestration-session-caller-codes' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { - captureWorkerOutputArchive, - type WorkerOutputArchiveCapture -} from '../../../../orchestration/workers/archives/worker-output-archive' -import type { WorkerTerminalResourceRow } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import type { WorkerReleaseReceipt } from './worker-release-completion' -import { releaseUnknownRecovery } from './worker-release-unknown-recovery' -import { archiveSummary } from './worker-terminal-resource-presentation' -import { captureWorkerResumeSession } from './worker-resume-session-capture' - -/** Freeze release output; unverifiable structured sessions finish release_unknown instead of retrying forever as requested. A fresh request may retry. */ -export async function captureWorkerReleaseArchive( - args: Parameters[0] & { - db: OrchestrationDb - resource: WorkerTerminalResourceRow - } -): Promise<{ captured: WorkerOutputArchiveCapture } | { receipt: WorkerReleaseReceipt }> { - const { db, resource, ...capture } = args - captureWorkerResumeSession(capture.runtime, db, resource, capture.attachedAtMs) - try { - return { captured: await captureWorkerOutputArchive(capture) } - } catch (error) { - if (!capture.structuredWorker || !isUnverifiableSessionRefusal(error)) { - throw error - } - const unknown = db.markWorkerTerminalReleaseUnknown(resource.id, error.message) - return { - receipt: { - dispatchId: capture.dispatchId, - state: 'release_unknown', - processAction: 'none', - archive: archiveSummary(unknown), - lastError: unknown.release_error ?? error.message, - recovery: releaseUnknownRecovery(capture.dispatchId) - } - } - } -} - -function isUnverifiableSessionRefusal(error: unknown): error is OrchestrationError { - return ( - error instanceof OrchestrationError && - (error.code === CODES.notLive || error.code === CODES.hostBoundary) - ) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts deleted file mode 100644 index fcccbf13f24..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts +++ /dev/null @@ -1,267 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -export function registerWorkerReleaseArchiveTests(): void { - function codexMessage(id: string, text: string): string { - return JSON.stringify({ - timestamp: '2026-08-03T12:00:00.000Z', - type: 'event_msg', - payload: { id, type: 'agent_message', message: text } - }) - } - - describe('orchestration worker release archive', () => { - const h = createOrchestrationWorkerReleaseHarness() - - afterEach(() => h.cleanup()) - - it('records an explicitly empty archive for an already-exited worker process', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - vi.mocked(h.runtime.showTerminal).mockImplementation( - async (handle) => ({ handle, worktreeId: 'repo::worktree', connected: false }) as never - ) - vi.mocked(h.runtime.readTerminal).mockResolvedValue({ - handle: 'term_worker', - status: 'exited', - tail: [], - truncated: false, - nextCursor: null - }) - const receipt = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - processAction: string - archive: { status: string | null } | null - } - expect(receipt).toMatchObject({ - state: 'released', - processAction: 'closed_exited_terminal', - archive: { status: 'empty' } - }) - }) - - it('keeps a bounded tail when one terminal line exceeds the archive budget', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - const suffix = 'meaningful-tail' - vi.mocked(h.runtime.readTerminal).mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: [`${'x'.repeat(300_000)}${suffix}`], - truncated: false, - nextCursor: '1' - }) - - const release = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - archive: { status: string | null } | null - } - const read = (await h.call('orchestration.workerRead', { dispatch: dispatchId })) as { - terminal: { tail: string[]; truncated: boolean } - warnings: string[] - } - - expect(release.archive?.status).toBe('captured') - expect(read.terminal.tail).toHaveLength(1) - expect(read.terminal.tail[0]).toMatch(new RegExp(`${suffix}$`)) - expect(read.terminal.truncated).toBe(true) - expect(read.warnings).not.toContain( - 'The live terminal buffer was empty at release; structured transcript output was unavailable.' - ) - }) - - it('serves the frozen redacted archive through worker-read after release, with cursors', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - vi.mocked(h.runtime.readTerminal).mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: ['first line', `capability dcap_${'a'.repeat(24)} leaked`, 'last line'], - draft: `send --dispatch-capability dcap_${'b'.repeat(24)}`, - truncated: false, - nextCursor: '3' - }) - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - vi.mocked(h.runtime.readTerminal).mockClear() - - const page1 = (await h.call('orchestration.workerRead', { - dispatch: dispatchId, - limit: 2 - })) as { - archived?: boolean - terminal: { tail: string[]; draft?: string } - cursor: string | null - } - expect(page1.terminal.tail).toEqual([ - 'first line', - 'capability [dispatch capability redacted] leaked' - ]) - expect(page1.terminal.draft).toBe('send --dispatch-capability [dispatch capability redacted]') - expect(page1.cursor).not.toBeNull() - - const page2 = (await h.call('orchestration.workerRead', { - dispatch: dispatchId, - cursor: page1.cursor as string - })) as { terminal: { tail: string[]; draft?: string }; cursor: string | null } - expect(page2.terminal.tail).toEqual(['last line']) - expect(page2.terminal.draft).toBeUndefined() - expect(page2.cursor).toBeNull() - // The live terminal is never consulted after release. - expect(h.runtime.readTerminal).not.toHaveBeenCalled() - }) - - it('keeps the conversation the agent reports last, so a follow-up can reopen it after release', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - // A /clear after the report moved the agent to a new conversation. - vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ - paneKey: 'tab_worker:leaf', - agent: 'claude', - processIncarnation: 'runtime_test:term_worker:1', - providerSession: { key: 'session_id', id: 'after-clear' }, - observedAt: 1 - }) - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - - expect( - JSON.parse(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.resume_session ?? 'null') - ).toMatchObject({ agent: 'claude', providerSession: { id: 'after-clear' } }) - }) - - it('reads an immutable transcript snapshot after the provider file disappears', async () => { - h.setup() - const directory = await mkdtemp(join(tmpdir(), 'orca-worker-release-snapshot-')) - const transcriptPath = join(directory, 'rollout.jsonl') - try { - await writeFile( - transcriptPath, - `${codexMessage('snapshot-one', 'frozen first')}\n${codexMessage('snapshot-two', 'frozen second')}\n` - ) - vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ - agent: 'codex', - processIncarnation: 'runtime_test:term_worker:1', - providerSession: { - key: 'codex:snapshot-session', - id: 'snapshot-session', - transcriptPath - } - } as never) - const { dispatchId } = await h.startSettledWorker() - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - await rm(transcriptPath) - - const page = (await h.call('orchestration.workerRead', { - dispatch: dispatchId, - limit: 1 - })) as { cursor: string } - expect(page).toMatchObject({ - archived: true, - source: 'transcript', - transcript: { - messages: [{ id: 'snapshot-one', blocks: [{ type: 'text', text: 'frozen first' }] }] - } - }) - await expect( - h.call('orchestration.workerRead', { dispatch: dispatchId, cursor: page.cursor }) - ).resolves.toMatchObject({ - transcript: { - messages: [{ id: 'snapshot-two', blocks: [{ type: 'text', text: 'frozen second' }] }] - } - }) - } finally { - await rm(directory, { recursive: true, force: true }) - } - }) - - it('preserves payload clipping metadata in the released transcript snapshot', async () => { - h.setup() - const directory = await mkdtemp(join(tmpdir(), 'orca-worker-release-clipped-snapshot-')) - const transcriptPath = join(directory, 'rollout.jsonl') - try { - await writeFile( - transcriptPath, - `${JSON.stringify({ - timestamp: '2026-08-03T12:00:00.000Z', - type: 'event_msg', - payload: { id: 'clipped-message', type: 'agent_message', message: 'x'.repeat(5_000) } - })}\n` - ) - vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ - agent: 'codex', - processIncarnation: 'runtime_test:term_worker:1', - providerSession: { - key: 'codex:clipped-session', - id: 'clipped-session', - transcriptPath - } - } as never) - const { dispatchId } = await h.startSettledWorker() - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - - const read = (await h.call('orchestration.workerRead', { dispatch: dispatchId })) as { - transcript: { limited: boolean } - cursor: string - contentComplete: boolean - clipping: string[] - warnings: string[] - } - - expect(read).toMatchObject({ - transcript: { limited: true }, - contentComplete: false, - clipping: ['transcript_payload'], - warnings: ['Oversized transcript text was clipped.'] - }) - expect(read.cursor).toMatch(/^owr1_/) - expect(read.warnings).not.toContain( - 'Older transcript messages were omitted from the bounded archive.' - ) - } finally { - await rm(directory, { recursive: true, force: true }) - } - }) - - it('rejects a legacy live-terminal cursor after output moves to the archive', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - - await expect( - h.call('orchestration.workerRead', { dispatch: dispatchId, cursor: 1 }) - ).rejects.toThrow(/source changed/i) - }) - - it('recovers archive metadata when a prior attempt committed only the archive row', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - const requested = h.db.requestWorkerTerminalRelease(dispatchId) - expect(requested.disposition).toBe('requested') - if (requested.disposition !== 'requested') { - throw new Error('release request was not recorded') - } - h.db.storeWorkerTerminalArchive({ - dispatchId, - resourceId: requested.resource.id, - kind: 'terminal_tail', - content: JSON.stringify({ - lines: ['archive survived the interrupted attempt'], - truncated: false, - terminalStatus: 'running', - warnings: [] - }) - }) - - const release = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - archive: { source: string | null; status: string | null } | null - } - - expect(release.archive).toEqual({ source: 'terminal', status: 'captured' }) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - archive_source: 'terminal', - archive_status: 'captured' - }) - }) - }) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-inventory.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-inventory.spec.ts deleted file mode 100644 index 97b7e7cef44..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-inventory.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -export function registerWorkerReleaseInventoryTests(): void { - describe('orchestration worker release inventory', () => { - const h = createOrchestrationWorkerReleaseHarness() - - afterEach(() => h.cleanup()) - - it('rejects exact reuse after release intent instead of closing the new worker', async () => { - h.setup() - const first = await h.startSettledWorker('succeeded') - expect(h.db.requestWorkerTerminalRelease(first.dispatchId).disposition).toBe('requested') - const nextTask = h.db.createTask({ spec: 'racing reuse', runId: h.activeRunId }) - - const attempted = (await h.call('orchestration.workerStart', { - task: nextTask.id, - from: 'term_coord', - terminal: 'term_worker' - })) as { state: string; lastError?: string } - - expect(attempted).toMatchObject({ state: 'failed' }) - expect(attempted.lastError).toMatch(/release.*progress/i) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - await expect( - h.call('orchestration.workerRelease', { dispatch: first.dispatchId }) - ).resolves.toMatchObject({ state: 'released' }) - expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) - }) - - it('reports abandoned workers as retained instead of reclaimable', async () => { - h.setup() - const { dispatchId } = await h.startWorker() - await h.call('orchestration.workerAbandon', { dispatch: dispatchId }) - - const listed = (await h.call('orchestration.workerList', { run: h.activeRunId })) as { - workers: { dispatchId: string; terminalState: string | null }[] - } - - expect(listed.workers).toContainEqual( - expect.objectContaining({ dispatchId, terminalState: 'retained' }) - ) - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - state: 'retained', - reason: 'identity_unproven', - processAction: 'none' - }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - }) - }) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts deleted file mode 100644 index 63fd92f07f2..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -import { registerBoundPty } from '../../../../orca-runtime-tests/bind-first-pane.test-fixture' - -const h = createOrchestrationWorkerReleaseHarness() -beforeEach(() => h.setup()) -afterEach(() => h.cleanup()) - -it.each(['local', 'ssh'])( - 'a handle-addressed phone Keep open fences %s worker release', - async (host) => { - if (host === 'ssh') { - vi.mocked(h.runtime.getOrchestrationDispatchAuthority).mockImplementation((handle) => - handle === 'term_worker' - ? ({ - terminalHandle: handle, - paneKey: h.workerPaneKey, - processIncarnation: 'runtime_test:term_worker:1', - hostScope: { kind: 'ssh', targetId: 'ssh-1' } - } as never) - : null - ) - } - const worker = await h.startSettledWorker() - expect(h.db.getWorkerTerminalResourceByOwner(worker.dispatchId)?.host_scope).toContain(host) - h.runtime.registerPreAllocatedHandleForPty('pty-worker', 'term_worker') - registerBoundPty(h.runtime, 'pty-worker', 'repo::worktree', null, { - tabId: 'tab_worker', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - }) - vi.mocked(h.runtime.getTerminalPaneKey).mockRestore() - await expect( - h.call('orchestration.workerKeepOpen', { terminal: 'term_worker', keep: true }) - ).resolves.toEqual({ autoClose: { kept: true } }) - await expect( - h.call('orchestration.workerRelease', { dispatch: worker.dispatchId }) - ).resolves.toMatchObject({ state: 'retained', reason: 'user_kept' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - } -) - -it('an unknown handle does not fence another worker or access the database', async () => { - const worker = await h.startSettledWorker() - h.runtime.registerPreAllocatedHandleForPty('pty-worker', 'term_worker') - registerBoundPty(h.runtime, 'pty-worker', 'repo::worktree', null, { - tabId: 'tab_worker', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - }) - vi.mocked(h.runtime.getTerminalPaneKey).mockRestore() - const db = vi.spyOn(h.runtime, 'getOrchestrationDb') - await expect( - h.call('orchestration.workerKeepOpen', { terminal: 'term_missing', keep: true }) - ).resolves.toEqual({ autoClose: null }) - expect(db).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(worker.dispatchId)?.ownership_state).toBe('owned') - await expect( - h.call('orchestration.workerRelease', { dispatch: worker.dispatchId }) - ).resolves.toMatchObject({ state: 'released' }) -}) - -// Boot-wait Keep open must find custody written at terminal creation, or a later release closes a kept pane (#19337, #19608). -it('a phone Keep open during the boot wait keeps the pane and fences the later release', async () => { - const gate = h.deferred() - vi.spyOn(h.runtime, 'waitForTerminal').mockReturnValue(gate.promise as never) - const task = h.db.createTask({ spec: 'mid-boot phone takeover', runId: h.activeRunId }) - const start = h.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - }) - await vi.waitFor(() => expect(h.runtime.waitForTerminal).toHaveBeenCalled()) - const dispatchId = ( - h.db.db.prepare("SELECT dispatch_id FROM worker_dispatches WHERE state = 'starting'").get() as { - dispatch_id: string - } - ).dispatch_id - - h.runtime.registerPreAllocatedHandleForPty('pty-worker', 'term_worker') - registerBoundPty(h.runtime, 'pty-worker', 'repo::worktree', null, { - tabId: 'tab_worker', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - }) - vi.mocked(h.runtime.getTerminalPaneKey).mockRestore() - await expect( - h.call('orchestration.workerKeepOpen', { terminal: 'term_worker', keep: true }) - ).resolves.toEqual({ autoClose: { kept: true } }) - - gate.resolve({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: true, - status: 'running', - exitCode: null - }) - await expect(start).resolves.toMatchObject({ state: 'ready' }) - - h.settle(task.id, dispatchId, 'succeeded') - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'retained', reason: 'user_kept', processAction: 'none' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts deleted file mode 100644 index bf365f7b86e..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts +++ /dev/null @@ -1,314 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { reconcileRequestedWorkerTerminalReleases } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-reconciliation' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { isStreamingMethod, eraseRpcMethods, type RpcContext } from '../../../core' -import { ORCHESTRATION_METHODS } from '../orchestration' - -function deferred(): { promise: Promise; resolve: (value: T) => void } { - let resolve!: (value: T) => void - const promise = new Promise((promiseResolve) => { - resolve = promiseResolve - }) - return { promise, resolve } -} - -describe('orchestration worker release recovery', () => { - let db: OrchestrationDb - let dbOpen = false - let runtime: OrcaRuntimeService - let ctx: RpcContext - let activeRunId: string - - const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - - function setup(): void { - db = new OrchestrationDb(':memory:') - dbOpen = true - runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' ? coordinatorPaneKey : handle === 'term_worker' ? workerPaneKey : null - ) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => - handle === 'term_worker' ? 'runtime_test:term_worker:1' : null - ) - vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockImplementation((handle) => - handle === 'term_worker' - ? ({ - terminalHandle: handle, - paneKey: workerPaneKey, - processIncarnation: 'runtime_test:term_worker:1', - hostScope: { kind: 'local', hostId: 'local' } - } as never) - : null - ) - vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) - vi.spyOn(runtime, 'showTerminal').mockImplementation( - async (handle) => ({ handle, worktreeId: 'repo::worktree', status: 'running' }) as never - ) - vi.spyOn(runtime, 'showManagedTerminalWorkspace').mockResolvedValue({ - id: 'repo::worktree' - } as never) - vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - title: 'worker' - }) - vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: true, - status: 'running', - exitCode: null - }) - vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ - handle: 'term_worker', - accepted: true, - bytesWritten: 1 - }) - vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - vi.spyOn(runtime, 'getExactWorkerProviderSession').mockReturnValue(null) - vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: ['worker output line 1', 'worker output line 2'], - truncated: false, - nextCursor: '2' - }) - vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({ - handle: 'term_worker', - tabId: 'tab-worker', - ptyKilled: true - }) - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) - activeRunId = db.createRun({ - objective: 'Release recovery test Run', - coordinatorHandle: 'term_coord', - coordinatorPaneKey - }).id - ctx = { runtime } - } - - afterEach(() => { - if (dbOpen) { - dbOpen = false - db.close() - } - vi.restoreAllMocks() - }) - - async function call(name: string, params: Record) { - const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( - (candidate) => candidate.name === name - ) - if (!method || isStreamingMethod(method)) { - throw new Error(`Method not found: ${name}`) - } - const parsed = method.params ? method.params.parse(params) : undefined - return method.handler(parsed, ctx) - } - - async function startWorker(): Promise<{ taskId: string; dispatchId: string }> { - const task = db.createTask({ spec: 'release recovery fixture task', runId: activeRunId }) - const result = (await call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - agent: 'codex' - })) as { dispatchId: string; state: string } - expect(result.state).toBe('ready') - return { taskId: task.id, dispatchId: result.dispatchId } - } - - async function startSettledWorker( - outcome: 'succeeded' | 'failed' = 'succeeded' - ): Promise<{ taskId: string; dispatchId: string }> { - const worker = await startWorker() - expect( - db.settleWorkerReport({ - taskId: worker.taskId, - dispatchId: worker.dispatchId, - outcome, - result: `worker ${outcome}` - }).action - ).toBe('settled') - return worker - } - - it('finishes a requested release after restart-style interruption', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.closeTerminal).mockRejectedValueOnce(new Error('Multiplexer disposed')) - const interrupted = (await call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - } - expect(interrupted.state).toBe('release_pending') - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('releasing') - - const result = await reconcileRequestedWorkerTerminalReleases(runtime) - expect(result).toMatchObject({ attempted: 1, released: 1 }) - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') - expect(runtime.closeTerminal).toHaveBeenCalledTimes(2) - }) - - it('settles a closed terminal after restart when exact process liveness is exited', async () => { - setup() - const { dispatchId } = await startSettledWorker() - const resource = db.getWorkerTerminalResourceByOwner(dispatchId) - expect(resource).toBeDefined() - - // Simulate a crash seam after closeTerminal succeeded but before its durable settlement. - vi.spyOn(db, 'settleWorkerTerminalRelease').mockImplementationOnce(() => { - throw new Error('SQLite interrupted after terminal close') - }) - await expect(call('orchestration.workerRelease', { dispatch: dispatchId })).rejects.toThrow( - 'SQLite interrupted after terminal close' - ) - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('releasing') - expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) - - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - vi.mocked(runtime.getOrchestrationDispatchAuthority).mockReturnValue(null) - vi.mocked(runtime.getTerminalPaneKey).mockReturnValue(null) - vi.mocked(runtime.getTerminalProcessIncarnation).mockReturnValue(null) - vi.spyOn(runtime, 'inspectTerminalProcessIncarnationLiveness').mockResolvedValue('exited') - - await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ - attempted: 1, - released: 1, - pending: 0 - }) - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') - expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) - expect(runtime.inspectTerminalProcessIncarnationLiveness).toHaveBeenCalledWith( - resource?.process_incarnation, - resource?.host_scope - ) - - // A replay sees no backlog and cannot issue another close. - await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ - attempted: 0 - }) - expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) - }) - - it('keeps a requested release pending after positive exit when no archive was committed', async () => { - setup() - const { dispatchId } = await startSettledWorker() - const requested = db.requestWorkerTerminalRelease(dispatchId) - expect(requested.disposition).toBe('requested') - expect(db.getWorkerTerminalArchive(dispatchId)).toBeUndefined() - - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - vi.mocked(runtime.getOrchestrationDispatchAuthority).mockReturnValue(null) - vi.mocked(runtime.getTerminalPaneKey).mockReturnValue(null) - vi.mocked(runtime.getTerminalProcessIncarnation).mockReturnValue(null) - vi.spyOn(runtime, 'inspectTerminalProcessIncarnationLiveness').mockResolvedValue('exited') - - await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ - attempted: 1, - released: 0, - pending: 1, - unknown: 0 - }) - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - release_state: 'requested', - ownership_state: 'owned' - }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - }) - - it('defers instead of settling unknown while inventory is incomplete', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.closeTerminal).mockRejectedValueOnce(new Error('Multiplexer disposed')) - await call('orchestration.workerRelease', { dispatch: dispatchId }) - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - - const result = await reconcileRequestedWorkerTerminalReleases(runtime) - expect(result).toMatchObject({ attempted: 1, pending: 1, unknown: 0 }) - expect(db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('releasing') - }) - - it('preserves archived output when an unconfirmed release retry cannot find the terminal', async () => { - setup() - const { dispatchId } = await startSettledWorker() - vi.mocked(runtime.closeTerminal).mockResolvedValueOnce({ - handle: 'term_worker', - tabId: 'tab-worker', - ptyKilled: false, - ptyStopVerdict: 'unverifiable', - ptyStopReason: 'its SSH provider is no longer registered' - }) - - await expect( - call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'release_unknown' }) - expect(db.getWorkerTerminalArchive(dispatchId)).toBeDefined() - - vi.mocked(runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - await expect( - call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'release_unknown' }) - const read = (await call('orchestration.workerRead', { dispatch: dispatchId })) as { - archived?: boolean - status: { terminal: string } - terminal: { tail: string[] } - } - expect(read).toMatchObject({ - archived: true, - status: { terminal: 'unknown', liveness: 'unverifiable' }, - terminal: { tail: ['worker output line 1', 'worker output line 2'] } - }) - }) - - it('records one recovery attempt when reconciliation joins an interactive release', async () => { - setup() - const { dispatchId } = await startSettledWorker() - const resourceId = db.getWorkerTerminalResourceByOwner(dispatchId)?.id - expect(resourceId).toBeDefined() - const pendingClose = deferred>>() - vi.mocked(runtime.closeTerminal).mockReturnValue(pendingClose.promise) - - const interactive = call('orchestration.workerRelease', { dispatch: dispatchId }) - await vi.waitFor(() => expect(runtime.closeTerminal).toHaveBeenCalledTimes(1)) - const first = reconcileRequestedWorkerTerminalReleases(runtime) - const second = reconcileRequestedWorkerTerminalReleases(runtime) - expect(second).toBe(first) - pendingClose.resolve({ handle: 'term_worker', tabId: 'tab-worker', ptyKilled: true }) - - await expect(interactive).resolves.toMatchObject({ state: 'released' }) - await expect(Promise.all([first, second])).resolves.toEqual([ - expect.objectContaining({ attempted: 1, released: 1 }), - expect.objectContaining({ attempted: 1, released: 1 }) - ]) - expect(runtime.closeTerminal).toHaveBeenCalledTimes(1) - expect(db.getWorkerTerminalResource(resourceId!)).toMatchObject({ - recovery_attempt_count: 1, - last_recovery_at: expect.any(String) - }) - - await expect(reconcileRequestedWorkerTerminalReleases(runtime)).resolves.toMatchObject({ - attempted: 0 - }) - expect(db.getWorkerTerminalResource(resourceId!)?.recovery_attempt_count).toBe(1) - }) - - it('removes terminal authority and archived output on orchestration reset', async () => { - setup() - const { dispatchId } = await startSettledWorker() - await call('orchestration.workerRelease', { dispatch: dispatchId }) - expect(db.getWorkerTerminalArchive(dispatchId)).toBeDefined() - - db.resetTasks() - - expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toBeUndefined() - expect(db.getWorkerTerminalArchive(dispatchId)).toBeUndefined() - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts deleted file mode 100644 index f2111c49250..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -describe('orchestration worker release', () => { - const h = createOrchestrationWorkerReleaseHarness() - - afterEach(() => h.cleanup()) - - it('releases a succeeded worker: archives then closes exactly the agent terminal', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('succeeded') - - const receipt = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - processAction: string - archive: { source: string | null; status: string | null } | null - } - - expect(receipt).toMatchObject({ - state: 'released', - processAction: 'closed_agent_terminal', - archive: { source: 'terminal', status: 'captured' } - }) - expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) - expect(h.runtime.closeTerminal).toHaveBeenCalledWith('term_worker') - const resource = h.db.getWorkerTerminalResourceByOwner(dispatchId) - expect(resource?.release_state).toBe('released') - expect(resource?.ownership_state).toBe('released') - expect(h.db.getWorkerDispatch(dispatchId)?.state).toBe('succeeded') - }) - - it('is idempotent: a duplicate release returns already_released without another close', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - await h.call('orchestration.workerRelease', { dispatch: dispatchId }) - const second = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - processAction: string - } - expect(second).toMatchObject({ state: 'already_released', processAction: 'none' }) - expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) - }) - - it('rejects an active worker without recording release intent', async () => { - h.setup() - const { dispatchId } = await h.startWorker() - await expect(h.call('orchestration.workerRelease', { dispatch: dispatchId })).rejects.toThrow( - /only a settled worker can release/ - ) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('not_requested') - }) - - it('retains a dead external terminal the orchestration never owned', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('succeeded', { terminal: 'term_worker' }) - h.inspectProcessLiveness.mockResolvedValue('exited') - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - state: 'retained', - reason: 'external_terminal', - processAction: 'none' - }) - expect(h.inspectProcessLiveness).toHaveBeenCalledWith( - 'runtime_test:term_worker:1', - JSON.stringify({ kind: 'local', hostId: 'local' }) - ) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'external', - release_state: 'not_requested' - }) - }) - - it('retains dead inventory evidence when persisted ownership history is invalid', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('succeeded', { terminal: 'term_worker' }) - const resource = h.db.getWorkerTerminalResourceByOwner(dispatchId) - const raw = ( - h.db as unknown as { db: { prepare: (sql: string) => { run: (...args: unknown[]) => void } } } - ).db - raw - .prepare('UPDATE worker_terminal_resources SET prior_owner_dispatch_ids = ? WHERE id = ?') - .run('{invalid', resource?.id) - h.inspectProcessLiveness.mockResolvedValue('exited') - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'retained', processAction: 'none' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).not.toBe('released') - }) - - it.each(['stopped', 'abandoned'] as const)( - 'releases a dead %s worker whose output could never be archived', - async (state) => { - h.setup() - const { dispatchId } = await h.startWorker() - if (state === 'stopped') { - h.db.beginWorkerStop(dispatchId, h.runtime.getRuntimeId()) - h.db.settleWorkerStop(dispatchId) - } else { - h.db.abandonWorkerDispatch(dispatchId, 'epoch_test') - } - h.inspectProcessLiveness.mockResolvedValue('exited') - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - state: 'released', - processAction: 'none', - archive: { status: 'unavailable' } - }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'released', - release_state: 'released', - archive_status: 'unavailable' - }) - } - ) - - it.each([false, true])( - 'keeps the output of a stopped worker (retained first: %s)', - async (retain) => { - h.setup() - const { dispatchId } = await h.startWorker() - await expect( - h.call('orchestration.workerStop', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'stopped' }) - if (retain) { - await h.call('orchestration.workerRetain', { dispatch: dispatchId }) - } - h.inspectProcessLiveness.mockResolvedValue('exited') - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'released', archive: { status: 'captured' } }) - expect(h.db.getWorkerTerminalArchive(dispatchId)?.kind).toBe('terminal_tail') - } - ) - - it.each(['stopped', 'abandoned'] as const)( - 'keeps a dead %s worker retained while its process is still unproven', - async (state) => { - h.setup() - const { dispatchId } = await h.startWorker() - if (state === 'stopped') { - h.db.beginWorkerStop(dispatchId, h.runtime.getRuntimeId()) - h.db.settleWorkerStop(dispatchId) - } else { - h.db.abandonWorkerDispatch(dispatchId, 'epoch_test') - } - h.inspectProcessLiveness.mockResolvedValue('unverifiable') - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - state: 'retained', - reason: 'identity_unproven', - processAction: 'none' - }) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).not.toBe('released') - } - ) - - it('lets an explicit retain cancel a release while output capture is pending', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - const pendingRead = h.deferred>>() - vi.mocked(h.runtime.readTerminal).mockReturnValue(pendingRead.promise) - - const release = h.call('orchestration.workerRelease', { dispatch: dispatchId }) - await vi.waitFor(() => expect(h.runtime.readTerminal).toHaveBeenCalledTimes(1)) - await expect( - h.call('orchestration.workerRetain', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'retained', reason: 'user_requested' }) - pendingRead.resolve({ - handle: 'term_worker', - status: 'running', - tail: ['captured before retention'], - truncated: false, - nextCursor: '1' - }) - - await expect(release).resolves.toMatchObject({ state: 'retained', reason: 'user_requested' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalArchive(dispatchId)).toBeUndefined() - }) - - it('does not claim retention succeeded after terminal close was committed', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - const pendingClose = h.deferred>>() - vi.mocked(h.runtime.closeTerminal).mockReturnValue(pendingClose.promise) - - const release = h.call('orchestration.workerRelease', { dispatch: dispatchId }) - await vi.waitFor(() => expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1)) - await expect( - h.call('orchestration.workerRetain', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'release_pending' }) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('releasing') - pendingClose.resolve({ handle: 'term_worker', tabId: 'tab-worker', ptyKilled: true }) - - await expect(release).resolves.toMatchObject({ state: 'released' }) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('released') - }) - - it('keeps a resumed settled worker retained in worker-list without re-dispatch or release', async () => { - h.setup() - const { dispatchId, taskId } = await h.startSettledWorker() - const dispatch = h.db.getDispatchContextById(dispatchId) - const task = h.db.getTask(taskId) - vi.mocked(h.runtime.createTerminal).mockClear() - vi.mocked(h.runtime.sendTerminalAgentPrompt).mockClear() - vi.mocked(h.runtime.getTerminalProcessIncarnation).mockImplementation((handle) => - handle === 'term_worker' ? 'runtime_test:term_worker:2' : null - ) - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ - state: 'retained', - reason: 'identity_unproven', - processAction: 'none' - }) - const listed = (await h.call('orchestration.workerList', { run: h.activeRunId })) as { - workers: { dispatchId: string; terminalState: string; workerState: string }[] - } - expect(listed.workers).toEqual([ - expect.objectContaining({ dispatchId, terminalState: 'retained', workerState: 'succeeded' }) - ]) - expect(h.db.getTask(taskId)).toEqual(task) - expect(h.db.getDispatchContextById(dispatchId)).toEqual(dispatch) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('retained') - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.runtime.createTerminal).not.toHaveBeenCalled() - expect(h.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - - it('re-proves process identity after archive capture before closing', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - const pendingRead = h.deferred>>() - vi.mocked(h.runtime.readTerminal).mockReturnValue(pendingRead.promise) - - const release = h.call('orchestration.workerRelease', { dispatch: dispatchId }) - await vi.waitFor(() => expect(h.runtime.readTerminal).toHaveBeenCalledTimes(1)) - vi.mocked(h.runtime.getTerminalProcessIncarnation).mockImplementation((handle) => - handle === 'term_worker' ? 'runtime_test:term_worker:2' : null - ) - pendingRead.resolve({ - handle: 'term_worker', - status: 'running', - tail: ['output from the old process'], - truncated: false, - nextCursor: '1' - }) - - await expect(release).resolves.toMatchObject({ - state: 'retained', - reason: 'identity_unproven' - }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - }) - - it('returns release_unknown when the terminal no longer resolves, then completes a retry', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - vi.mocked(h.runtime.showTerminal).mockRejectedValue(new Error('terminal_handle_stale')) - const receipt = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - recovery?: string - } - expect(receipt.state).toBe('release_unknown') - expect(receipt.recovery).toContain('worker-show') - expect(receipt.recovery).toContain('fresh request ID') - expect(receipt.recovery).not.toContain('same --retry-request') - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - - vi.mocked(h.runtime.showTerminal).mockImplementation( - async (handle) => ({ handle, worktreeId: 'repo::worktree', status: 'running' }) as never - ) - const retry = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - } - expect(retry.state).toBe('released') - expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(1) - }) - - it('retains the live terminal when output capture fails', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - vi.mocked(h.runtime.readTerminal).mockRejectedValue(new Error('read exploded')) - await expect(h.call('orchestration.workerRelease', { dispatch: dispatchId })).rejects.toThrow( - /Output could not be preserved/ - ) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('requested') - }) - - it('marks release_unknown when the close itself fails', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker() - vi.mocked(h.runtime.closeTerminal).mockRejectedValue(new Error('close exploded')) - const receipt = (await h.call('orchestration.workerRelease', { dispatch: dispatchId })) as { - state: string - lastError?: string - recovery?: string - } - expect(receipt.state).toBe('release_unknown') - expect(receipt.recovery).toContain('fresh request ID') - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe('unknown') - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts index 985a7ca1476..6843a2f3a8c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts @@ -5,16 +5,19 @@ import { retainFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-release' import { ORCHESTRATION_WORKER_LIST_METHOD } from './worker-list-method' -import { resolvePinnedFederatedServer } from './pinned-federated-server' -import { archiveSummary, exposeWorkerRetainReceipt } from './worker-terminal-resource-presentation' +import { resolvePinnedFederatedServer } from '../../../../orchestration/legacy-remote-home/pinned-federated-server' +import { + archiveSummary, + exposeWorkerRetainReceipt +} from './release/worker-terminal-resource-presentation' import { completeWorkerTerminalRelease, type WorkerReleaseReceipt -} from './worker-release-completion' +} from './release/worker-release-completion' import { WorkerDispatchParams, WorkerRetainParams -} from '../../../../../../shared/rpc-contract/orchestration-worker-release-schemas-params' +} from '../../../../../../shared/rpc-contract/orchestration/orchestration-worker-release-schemas-params' import { ORCHESTRATION_WORKER_KEEP_OPEN_METHODS } from './worker-keep-open' export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-run-dispatch-contracts.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-run-dispatch-contracts.test.ts deleted file mode 100644 index c2e03e681db..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-run-dispatch-contracts.test.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { registerWorkerListRunScopeRpcTests } from './worker-list-run-scope-rpc.spec' -import { registerWorkerStartTerminalTargetTests } from './worker-start-terminal-target.spec' - -registerWorkerListRunScopeRpcTests() -registerWorkerStartTerminalTargetTests() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-method.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-method.ts new file mode 100644 index 00000000000..258b89044f2 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-method.ts @@ -0,0 +1,259 @@ +import { stopHelperAfterStart } from './worker-stop' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { z } from 'zod' +import type { RpcContext } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { startFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-start' +import { startLocalWorker } from './start/local-worker-start' +import type { WorkerFollowUp } from './follow-up/worker-follow-up-placement' +import { withWorkerStartNext } from '../receipt-next' +import { + decideWorkerStartMode, + readWorkerStartModeSettings +} from '../structured-workers/orchestration-worker-start-mode' +import { resolveOrchestrationCaller } from '../runs/run-scope' +import { + assertHelperStartScope, + resolveWorkerStartRun, + qualifyLiveWorkerFollowUp +} from './start/admission/worker-start-authority' +import { parseTaskDeps } from './start/admission/task-deps-argument' +import { WorkerStartParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-worker-start-params' +import { + isWorkerStartTimeoutWithinTimerLimit, + resolveWorkerStartReadinessTimeoutMs +} from '../../../../../../shared/orchestration/orchestration-timing-budgets' +import { buildOrchestrationTaskDisplayMetadata } from '../../../../../../shared/orchestration/orchestration-task-display' +import { assertWorkerStartTaskSpecWithinPromptBudget } from './start/admission/worker-start-prompt-budget' +import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../../shared/orca-session-address-prefix' +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as SESSION_CODES } from '../../../../../../shared/orchestration/orchestration-session-caller-codes' +import { resolveDispatchCreator } from '../runs/dispatch-creator' + +type WorkerStartContext = Pick< + RpcContext, + 'runtime' | 'orchestrationMutation' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' +> + +export const ORCHESTRATION_WORKER_START_METHODS = [ + defineOrchestrationMethod({ + name: 'orchestration.workerStart', + access: { + kind: 'writes', + caller: 'from', + server: 'on', + targets: { + task: 'task', + parent: 'task', + deps: 'task', + run: 'run', + retryOf: 'dispatch', + terminal: 'worker', + adoptTaskId: 'task' + } + }, + requires: ['accounts'], + permission: 'workspace', + params: WorkerStartParams, + handler: async (params, ctx) => startWorker(params, ctx) + }) +] + +/** worker-start, and a follow-up sent to a finished worker, which is worker-start run for the sender. */ +export async function startWorker( + startParams: z.infer, + ctx: WorkerStartContext, + startFollowUp?: WorkerFollowUp +): Promise { + const { runtime, orchestrationMutation, orchestrationCaller } = ctx + const prepared = await prepareWorkerStart(startParams, ctx, startFollowUp) + const { params, followUp, coordinator, bindRun, helperCreator, taskDeps, existingTask, withRun } = + prepared + const db = runtime.getOrchestrationDb() + const mode = decideWorkerStartMode({ + params, + settings: readWorkerStartModeSettings(runtime) + }) + if (params.on) { + // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. + const receipt = await startFederatedWorker({ + params, + runtime, + db, + bindRunId: () => bindRun().run.id, + task: existingTask, + taskDeps, + orchestrationMutation, + callerSession: orchestrationCaller + }) + await stopHelperAfterStart(runtime, receipt, orchestrationMutation) + return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) + } + const receipt = await startLocalWorker({ + params: { ...params, timeoutMs: resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) }, + runtime, + db, + bindRun: () => bindRun().run, + taskDeps, + coordinator, + callerSession: orchestrationCaller, + existingTask, + orchestrationMutation, + mode, + helperCreator, + followUp + }) + await stopHelperAfterStart(runtime, receipt, orchestrationMutation) + return withRun(withWorkerStartNext(receipt)) +} + +/** What every start checks and binds before it is placed, here or on a paired server. */ +export async function prepareWorkerStart( + params: z.infer, + { + runtime, + orchestrationCompatibilityEvidence, + orchestrationCaller + }: Omit, + followUp?: WorkerFollowUp +) { + if (!isWorkerStartTimeoutWithinTimerLimit(params.timeoutMs)) { + throw new OrchestrationError( + 'invalid_argument', + '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' + ) + } + if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { + // Refused here, before any remote call: an Orca session ID names a chat only on its own host. + throw new OrchestrationError( + SESSION_CODES.hostBoundary, + `${params.terminal} names a chat by its Orca session ID, which identifies it only on the host that runs it. Run worker-start on that host. No effects were applied.`, + { effectsApplied: false } + ) + } + if (params.adoptTaskId !== undefined && orchestrationCaller?.kind !== 'peer') { + throw new OrchestrationError( + 'invalid_argument', + 'Only the paired Orca coordinating a Run names its Task IDs. No effects were applied.', + { effectsApplied: false } + ) + } + const placement = params.worktree ?? 'current' + if ( + orchestrationCaller?.kind === 'peer' && + !followUp && + !params.terminal && + /^(current|new-child)$/.test(placement) + ) { + throw new OrchestrationError( + 'invalid_argument', + `--on requires an exact remote worktree selector or new-top-level: ${orchestrationCaller.peerRun.home_label} has no workspace on this server for --worktree ${placement}. No effects were applied.`, + { effectsApplied: false } + ) + } + const db = runtime.getOrchestrationDb() + const coordinator = resolveOrchestrationCaller(runtime, { + callerTerminalHandle: params.from, + callerEvidence: orchestrationCompatibilityEvidence, + callerSession: orchestrationCaller + }) + if (params.spec) { + // Before the Run resolves, so a refused spec cannot leave a new Run bound. + await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) + } + const taskDeps = parseTaskDeps(params.deps) + const qualified = followUp + ? qualifyLiveWorkerFollowUp( + runtime, + coordinator, + params.from, + orchestrationCaller, + params.run!, + followUp + ) + : undefined + const { bindRun, helperCreator } = qualified + ? { bindRun: () => ({ run: qualified.run, created: false }), helperCreator: qualified.creator } + : resolveWorkerStartRun(runtime, { + coordinator, + from: params.from, + callerSession: orchestrationCaller, + runId: params.run, + // The Run takes the title its first Task gets. + objective: params.spec + ? buildOrchestrationTaskDisplayMetadata({ + spec: params.spec, + taskTitle: params.taskTitle + }).taskTitle + : undefined, + taskReferences: [...(params.parent ? [params.parent] : []), ...(taskDeps ?? [])] + }) + // Name the Run in every receipt so a reused, stale binding is visible. + const withRun = (receipt: unknown): unknown => { + if (!receipt || typeof receipt !== 'object') { + return receipt + } + const { run, created } = bindRun() + return { ...receipt, run: { id: run.id, objective: run.objective, created } } + } + const existingTask = params.task ? db.getTask(params.task) : undefined + // --task excludes --spec, so this never creates a Run. + if (params.task && (!existingTask || existingTask.run_id !== bindRun().run.id)) { + throw new OrchestrationError( + 'task_not_found', + `Task ${params.task} was not found in Run ${bindRun().run.id}.` + ) + } + if (helperCreator && !followUp) { + assertHelperStartScope(db, helperCreator, { + task: existingTask, + params, + ...(followUp ? { followUp } : {}) + }) + } + if (existingTask) { + await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) + } + if (followUp) { + const placement = await followUp.place(() => { + if ( + helperCreator && + db.resolveCreatorDispatchId( + resolveDispatchCreator(runtime, params.from, orchestrationCaller) + ) !== helperCreator.id + ) { + throw new OrchestrationError( + 'consumer_fenced', + `Dispatch ${helperCreator.id} is no longer this caller's active work. No effects were applied.`, + { effectsApplied: false } + ) + } + }) + const spec = [ + params.spec, + placement.delivery === 'started_fresh' ? placement.earlierWork : undefined + ] + .filter(Boolean) + .join('\n\n') + params = { + ...params, + worktree: `id:${placement.worktreeId}`, + ...(placement.terminal ? { terminal: placement.terminal } : {}), + ...(placement.agent ? { agent: placement.agent } : {}), + ...(placement.model ? { model: placement.model } : {}), + ...(placement.effort ? { effort: placement.effort } : {}), + spec + } + followUp = { ...followUp, reopen: placement.reopen, earlierWork: placement.earlierWork } + await assertWorkerStartTaskSpecWithinPromptBudget(spec) + } + return { + params, + followUp, + coordinator, + bindRun, + helperCreator, + taskDeps, + existingTask, + withRun + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts deleted file mode 100644 index 3ec374688b0..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../../../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../../../../git/worktrees/catalog/worktree-listing' - -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { AGENT_PROMPT_BRACKETED_PASTE_END } from '../../../../../../shared/agent-launch/startup/agent-prompt-injection' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { - AGENT_PROMPT_TEST_WORKTREE_ID, - createAgentPromptSubmissionRuntime -} from '../../../../terminal/input/agent-prompt-submission-runtime-test-fixture' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from '../../../core' -import { RpcDispatcher } from '../../../dispatcher' -import { ORCHESTRATION_METHODS } from '../orchestration' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' - -vi.mock('../../../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: facade.listWorktrees - } -}) - -vi.mock('../../../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: facade.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - const createWorktreeListingMocks = () => ({ - listWorktrees: vi.fn().mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/prompt-contract', - isBare: false, - isMainWorktree: false - } - ]), - listWorktreesStrict: vi.fn().mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/prompt-contract', - isBare: false, - isMainWorktree: false - } - ]) - }) - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -const COORDINATOR_PANE_KEY = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' -const WORKER_PANE_KEY = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -const REQUEST_ID = 'worker_start_prompt_contract' -const openDatabases: OrchestrationDb[] = [] -const temporaryRoots: string[] = [] - -type PromptContractHarness = { - runtime: Awaited>['runtime'] - handle: string - db: OrchestrationDb - dbPath: string - dispatcher: RpcDispatcher - request: RpcRequest - requestId: string - taskId: string - submittedTurns: () => number - startedTurns: () => number - prematureSubmits: () => number - writes: string[] -} - -async function createPromptContractHarness( - outcome: 'accepted' | 'swallowed', - agent: TuiAgent = 'codex' -): Promise { - let composerReady = false - let submittedTurns = 0 - let startedTurns = 0 - let prematureSubmits = 0 - const fixture = await createAgentPromptSubmissionRuntime((runtime, data) => { - if (data.includes(AGENT_PROMPT_BRACKETED_PASTE_END)) { - setTimeout(() => runtime.onPtyData('pty-prompt', 'partial composer frame', Date.now()), 650) - setTimeout(() => runtime.onPtyData('pty-prompt', '\x1b[?25h', Date.now()), 750) - setTimeout(() => { - composerReady = true - runtime.onPtyData('pty-prompt', 'final composer frame', Date.now()) - }, 1_000) - return - } - if (data !== '\r') { - return - } - submittedTurns += 1 - if (!composerReady) { - prematureSubmits += 1 - } - if (outcome === 'accepted') { - startedTurns += 1 - runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) - } - }, agent) - const { runtime, handle } = fixture - runtime.onPtyData('pty-prompt', '\x1b]0;Codex idle\x07', Date.now()) - - const temporaryRoot = mkdtempSync(join(tmpdir(), 'orca-worker-prompt-contract-')) - temporaryRoots.push(temporaryRoot) - const dbPath = join(temporaryRoot, 'orchestration.db') - const db = new OrchestrationDb(dbPath) - openDatabases.push(db) - runtime.setOrchestrationDb(db) - const run = db.createRun({ - objective: 'Worker prompt contract', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: COORDINATOR_PANE_KEY - }) - const task = db.createTask({ spec: 'start exactly one worker turn', runId: run.id }) - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((candidate) => - candidate === 'term_coord' - ? COORDINATOR_PANE_KEY - : candidate === handle - ? WORKER_PANE_KEY - : null - ) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((candidate) => - candidate === handle ? `runtime_test:${handle}:1` : null - ) - vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) - vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ - handle: 'term_coord', - worktreeId: 'repo::parent', - status: 'running' - } as never) - vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({ - id: 'repo::parent', - repoId: 'repo-1' - } as never) - vi.spyOn(runtime, 'showRepo').mockResolvedValue({ id: 'repo-1', kind: 'git' } as never) - vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({ - worktree: { id: AGENT_PROMPT_TEST_WORKTREE_ID, repoId: 'repo-1' }, - startupTerminal: { spawned: true, handle }, - setupReceipt: { - requested: 'run', - hookFound: false, - startupPolicy: 'start-immediately', - state: 'not_configured' - } - } as never) - vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - - return { - runtime, - handle, - db, - dbPath, - dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }), - request: { - id: `rpc_${outcome}`, - authToken: 'caller-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: `${REQUEST_ID}_${outcome}`, - method: 'orchestration.workerStart', - params: { - task: task.id, - from: 'term_coord', - worktree: 'new-child', - name: `prompt-contract-${outcome}`, - agent - } - }, - requestId: `${REQUEST_ID}_${outcome}`, - taskId: task.id, - submittedTurns: () => submittedTurns, - startedTurns: () => startedTurns, - prematureSubmits: () => prematureSubmits, - writes: fixture.writes - } -} - -describe('orchestration worker-start prompt contract', () => { - afterEach(() => { - for (const db of openDatabases.splice(0)) { - db.close() - } - for (const root of temporaryRoots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('does not attribute output from the old busy turn to a queued prompt', async () => { - vi.useFakeTimers() - const { runtime, handle } = await createAgentPromptSubmissionRuntime(() => undefined, 'codex') - runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) - const pending = runtime.sendTerminalAgentPrompt(handle, 'queued prompt', { - inputKind: 'driving', - acceptQueued: true, - requestId: 'busy-swallowed', - observationTimeoutMs: 0 - }) - - await vi.runAllTimersAsync() - const send = await pending - expect(send).toMatchObject({ - prompt: { - requestId: 'busy-swallowed', - stages: ['input_accepted'] - } - }) - const observed = runtime.observeTerminalAgentPrompt(handle, send.prompt!, 1_000) - setTimeout(() => { - runtime.onPtyData('pty-prompt', 'old turn output', Date.now()) - }, 50) - await vi.runAllTimersAsync() - - await expect(observed).resolves.toMatchObject({ - stages: ['input_accepted'] - }) - }) - - it('refuses an 8 MiB inline spec before Task, Dispatch, or terminal effects', async () => { - const harness = await createPromptContractHarness('accepted') - const tasksBefore = harness.db.listTasks().map((task) => task.id) - const params = harness.request.params as Record - delete params.task - params.spec = 'x'.repeat(8 * 1024 * 1024) - - const response = await harness.dispatcher.dispatch(harness.request) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'worker_prompt_too_large', - data: { effectsApplied: false, maxTaskSpecBytes: expect.any(Number) } - } - }) - expect(harness.db.listTasks().map((task) => task.id)).toEqual(tasksBefore) - expect(harness.db.getDispatchContext(harness.taskId)).toBeUndefined() - expect(harness.writes).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts deleted file mode 100644 index 105d46e90f6..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { z } from 'zod' -import type { WorkerStartParams } from '../../../../../../shared/rpc-contract/orchestration-worker-start-params' - -export type WorkerStartInput = z.infer diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-target.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-target.spec.ts deleted file mode 100644 index 8536e85960a..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-target.spec.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { LaunchedAgentForeground } from '../../../../terminal/wait/launched-agent-foreground' -import type { RuntimeTerminalWait } from '../../../../../../shared/runtime-terminal-contracts' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -export function registerWorkerStartTerminalTargetTests(): void { - describe('worker-start --terminal target', () => { - const harness = createOrchestrationWorkerReleaseHarness() - beforeEach(() => harness.setup()) - afterEach(() => harness.cleanup()) - - it('refuses the coordinator terminal by handle', async () => { - const task = harness.db.createTask({ spec: 'self adoption', runId: harness.activeRunId }) - - await expect( - harness.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - terminal: 'term_coord' - }) - ).rejects.toMatchObject({ - code: 'terminal_is_coordinator', - message: expect.stringContaining("coordinator's own terminal") - }) - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - }) - - it('refuses a different handle that resolves to the coordinator pane', async () => { - const task = harness.db.createTask({ - spec: 'self adoption alias', - runId: harness.activeRunId - }) - vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' || handle === 'term_coord_alias' ? harness.coordinatorPaneKey : null - ) - - await expect( - harness.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - terminal: 'term_coord_alias' - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - }) - }) - - // Manual inject is another self-adoption path; compare target with caller too. - describe('orchestration.dispatch --to the caller', () => { - const harness = createOrchestrationWorkerReleaseHarness() - beforeEach(() => harness.setup()) - afterEach(() => harness.cleanup()) - - it('refuses an injected dispatch aimed at the coordinator handle', async () => { - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - ({ - terminalHandle: handle, - paneKey: harness.coordinatorPaneKey, - processIncarnation: 'runtime_test:term_coord:1' - }) as never - ) - const task = harness.db.createTask({ spec: 'self dispatch', runId: harness.activeRunId }) - - await expect( - harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: 'term_coord', - inject: true - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - expect(harness.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - - it('refuses an injected dispatch to a different handle that resolves to the coordinator pane', async () => { - vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' || handle === 'term_coord_alias' ? harness.coordinatorPaneKey : null - ) - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - ({ - terminalHandle: handle, - paneKey: harness.coordinatorPaneKey, - processIncarnation: 'runtime_test:term_coord:1' - }) as never - ) - const task = harness.db.createTask({ - spec: 'self dispatch alias', - runId: harness.activeRunId - }) - - await expect( - harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: 'term_coord_alias', - inject: true - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - }) - - // Context-only self-dispatch writes no preamble and remains valid for low-level topologies. - it('still records a context-only dispatch aimed at the coordinator handle', async () => { - const task = harness.db.createTask({ spec: 'self context', runId: harness.activeRunId }) - - const result = (await harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: 'term_coord' - })) as { dispatch: { id: string; status: string } } - - expect(result.dispatch.status).toBe('dispatched') - expect(harness.db.getDispatchContextById(result.dispatch.id)?.assignee_handle).toBe( - 'term_coord' - ) - expect(harness.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - - // Self-injection must refuse regardless of agent detection; without-inject advice cannot authorize it. - it.each([ - ['the coordinator handle', 'term_coord'], - ['an alias of the coordinator pane', 'term_coord_alias'] - ])('refuses %s even when no agent is detected', async (_label, target) => { - vi.spyOn(harness.runtime, 'isTerminalRunningAgent').mockResolvedValue(false) - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - (handle === 'term_coord_alias' - ? { - terminalHandle: handle, - paneKey: harness.coordinatorPaneKey, - processIncarnation: 'runtime_test:term_coord:1' - } - : null) as never - ) - const task = harness.db.createTask({ - spec: `self inject ${target}`, - runId: harness.activeRunId - }) - - await expect( - harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: target, - inject: true - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - }) - }) - - const PTY_ID = 'pty_worker' - - // A returned shell also reads ready; prove the launched agent is in front before writing the brief. - describe('a worker start writes its brief only into the agent it launched', () => { - const h = createOrchestrationWorkerReleaseHarness() - afterEach(() => h.cleanup()) - - function launchedPane(foreground: LaunchedAgentForeground): string[] { - h.setup() - const writes: string[] = [] - vi.spyOn(h.runtime, 'readLaunchedAgentForeground').mockResolvedValue(foreground) - vi.spyOn(h.runtime, 'launchedAgentHostProvesAgent').mockReturnValue(true) - vi.spyOn(h.runtime, 'subscribeToTerminalData').mockReturnValue(() => {}) - vi.mocked(h.runtime.sendTerminalAgentPrompt).mockImplementation( - async (handle, text, options) => { - await options?.beforeWrite?.(PTY_ID) - writes.push(text) - return { handle, accepted: true, bytesWritten: text.length } - } - ) - return writes - } - - it('types nothing when the agent exited and its shell is in front', async () => { - const writes = launchedPane('shell') - - await expect(h.startWorker({ agent: 'claude' })).rejects.toThrow() - expect(writes).toEqual([]) - }) - }) - - describe('composer-marker first dispatch readiness', () => { - const h = createOrchestrationWorkerReleaseHarness() - afterEach(() => h.cleanup()) - - it.each(['zcode', 'opencode', 'opencode2'] as const)( - '%s waits for the new composer before dispatch', - async (agent) => { - h.setup() - const gate = h.deferred() - vi.spyOn(h.runtime, 'waitForFreshWorkerComposer').mockReturnValue(gate.promise) - const pending = h.startWorker({ agent }) - await vi.waitFor(() => - expect(h.runtime.waitForFreshWorkerComposer).toHaveBeenCalledWith( - 'term_worker', - agent, - 60_000 - ) - ) - expect(h.runtime.waitForTerminal).not.toHaveBeenCalled() - expect(h.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - gate.resolve({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: true, - status: 'running', - exitCode: null - }) - await pending - expect(h.runtime.sendTerminalAgentPrompt).toHaveBeenCalledOnce() - } - ) - }) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-with-agent.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-with-agent.test.ts deleted file mode 100644 index f640d1041e8..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-with-agent.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -describe('worker-start --terminal with --agent', () => { - const h = createOrchestrationWorkerReleaseHarness() - beforeEach(() => h.setup()) - afterEach(() => h.cleanup()) - - it('refuses, saying --terminal continues the running agent, before any Dispatch', async () => { - await expect( - h.call('orchestration.workerStart', { - from: 'term_coord', - terminal: 'term_worker', - agent: 'codex', - spec: 'reuse the worker' - }) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: - '--terminal continues the agent already running there, in its current conversation. To start fresh, use --worktree or --agent without --terminal.' - }) - expect(h.db.db.prepare('SELECT count(*) AS n FROM dispatch_contexts').get()).toEqual({ n: 0 }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts deleted file mode 100644 index 4ecf136e7e5..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts +++ /dev/null @@ -1,60 +0,0 @@ -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { captureWorkerOutputArchive } from '../../../../orchestration/workers/archives/worker-output-archive' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import { resolveStructuredWorkerForDispatch } from '../structured-workers/orchestration-structured-worker-lifecycle' -import { orchestrationTimestampToMs } from './worker-output' -import { captureWorkerResumeSession } from './worker-resume-session-capture' -import { withTimeout } from '../../../../../../shared/promise-timeout-fallback' - -// Well inside the 30 s remote stop RPC budget. -const STOP_ARCHIVE_TIMEOUT_MS = 5_000 - -/** Archive a worker's output before stop closes its terminal; release would otherwise find nothing to keep. */ -export async function archiveWorkerOutputBeforeStop(args: { - runtime: WorkerTerminalReleaseRuntime - db: OrchestrationDb - dispatchId: string - terminalHandle: string - attachedAt: string -}): Promise { - const { db, dispatchId } = args - // Stopping matters more than the copy; on failure or timeout, release reports the archive unavailable. - try { - const resource = db.getWorkerTerminalResourceByOwner(dispatchId) - const attachedAtMs = orchestrationTimestampToMs(args.attachedAt) - if (resource) { - captureWorkerResumeSession(args.runtime, db, resource, attachedAtMs) - } - if ( - !resource || - resource.ownership_state !== 'owned' || - db.hasWorkerTerminalArchive(dispatchId) - ) { - return - } - const captured = await withTimeout( - captureWorkerOutputArchive({ - runtime: args.runtime, - dispatchId, - terminalHandle: args.terminalHandle, - attachedAtMs, - structuredWorker: resolveStructuredWorkerForDispatch(db, dispatchId) - }), - STOP_ARCHIVE_TIMEOUT_MS, - null - ) - if (!captured) { - throw new Error('capture failed or timed out') - } - db.storeWorkerTerminalArchiveBeforeStop({ - dispatchId, - resourceId: resource.id, - kind: captured.kind, - content: JSON.stringify(captured.content), - archiveSource: captured.kind === 'terminal_tail' ? 'terminal' : 'transcript', - archiveStatus: captured.status - }) - } catch (error) { - console.warn('[orchestration] worker output was not archived before stop', dispatchId, error) - } -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts index fccc693d70a..d717ae5d4ee 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts @@ -4,12 +4,12 @@ import { mapWithConcurrency } from '../../../../../../shared/map-with-concurrenc import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import { WORKER_SETTLED_STATES } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import { WorkerDispatchParams } from '../../../../../../shared/rpc-contract/orchestration-worker-stop-params' +import { WorkerDispatchParams } from '../../../../../../shared/rpc-contract/orchestration/orchestration-worker-stop-params' import type { HelperStopOutcome, WorkerStopReceipt } from '../../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' -import { stopSingleWorker, type StopMutation } from './single-worker-stop' +import { stopSingleWorker, type StopMutation } from './stop/single-worker-stop' export const ORCHESTRATION_WORKER_STOP_METHODS = [ defineOrchestrationMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-lease.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-lease.ts deleted file mode 100644 index 2e0ca071125..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-lease.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { WorkerTerminalResourceRow } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import type { WorkerDispatchRow } from '../../../../orchestration/db/orchestration-records' -import { resolveStructuredWorkerIdentity } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' -import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' - -export function workerTerminalLeaseIsCurrent( - runtime: WorkerTerminalReleaseRuntime, - db: OrchestrationDb, - dispatchId: string, - resource: WorkerTerminalResourceRow, - // Probe the live reminted handle; compare durable worker/resource handles only for stored identity. - liveTerminalHandle: string -): boolean { - const worker = db.getWorkerDispatch(dispatchId) - if (isStructuredWorkerHandle(resource.terminal_handle)) { - return structuredWorkerTerminalLeaseIsCurrent(db, dispatchId, worker, resource) - } - const authority = runtime.getOrchestrationDispatchAuthority(liveTerminalHandle) - // Exited PTYs keep identity/host evidence but cannot mint launch authority. - return Boolean( - worker?.agent_terminal_handle === resource.terminal_handle && - (authority - ? resource.host_scope === JSON.stringify(authority.hostScope) - : runtime.getTerminalLivenessVerdict(liveTerminalHandle)?.status === 'exited') && - db.isDispatchProcessCurrent({ - dispatchId, - paneKey: runtime.getTerminalPaneKey(liveTerminalHandle), - processIncarnation: runtime.getTerminalProcessIncarnation(liveTerminalHandle) - }) && - !db.workerTerminalResourceHasIdentityConflict(resource.id) - ) -} - -/** Check durable pane/lineage identity independently of child liveness. - * Requiring installed session records after restart would falsely retain requested releases as identity_unproven. */ -function structuredWorkerTerminalLeaseIsCurrent( - db: OrchestrationDb, - dispatchId: string, - worker: WorkerDispatchRow | undefined, - resource: WorkerTerminalResourceRow -): boolean { - const identity = resolveStructuredWorkerIdentity(resource.terminal_handle, db) - return Boolean( - worker?.agent_terminal_handle === resource.terminal_handle && - identity && - resource.host_scope === JSON.stringify(identity.hostScope) && - db.isDispatchProcessCurrent({ - dispatchId, - paneKey: identity.paneKey, - processIncarnation: identity.processIncarnation - }) && - !db.workerTerminalResourceHasIdentityConflict(resource.id) - ) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts deleted file mode 100644 index cd1126cf997..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-topology.ts +++ /dev/null @@ -1,205 +0,0 @@ -import type { RuntimeTerminalCreate } from '../../../../../../shared/runtime-terminal-create-contract' -import type { AgentLaunchPreferences } from '../../../../../../shared/agent-session/agent-session-host-authority' -import { narrowStructuredLaunchSeedOptions } from '../../../../../../shared/native-chat/input/native-chat-session-option-defaults' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { createStructuredWorkerSession } from '../structured-workers/orchestration-structured-worker-session' -import { dispatchReportMailbox } from '../../../../orchestration/workers/reports/dispatch-report-mailbox' - -export type WorkerEffect = { - kind: 'worktree' | 'terminal' | 'setup' | 'dispatch_input' - action?: string - role?: string - id?: string - /** A created worktree's name, so the coordinator can tell the user where the worker runs. */ - name?: string - state?: string - tabId?: string - leafId?: string - requested?: string - effective?: string - source?: string - hookFound?: boolean - startupPolicy?: string - terminalId?: string - surface?: 'visible' | 'background' - warning?: string -} - -export type WorkerSetupReceipt = { - requested: 'run' | 'skip' | 'inherit' | 'not_applicable' - effective: 'run' | 'skip' | 'inherit' | 'not_applicable' - source: string - hookFound: boolean - startupPolicy: 'start-immediately' | 'wait-for-setup' - state: - | 'running' - | 'succeeded' - | 'failed' - | 'skipped' - | 'not_configured' - | 'spawn_failed' - | 'not_applicable' -} - -export function requireWorkerAuthority(runtime: OrcaRuntimeService, terminalHandle: string) { - const authority = runtime.getOrchestrationDispatchAuthority(terminalHandle) - const paneKey = authority?.paneKey ?? runtime.getTerminalPaneKey(terminalHandle) - const processIncarnation = - authority?.processIncarnation ?? runtime.getTerminalProcessIncarnation(terminalHandle) - if (!paneKey || !processIncarnation) { - throw new Error('stable_pane_required') - } - return { - paneKey, - processIncarnation, - ...(authority?.launchTokenHash ? { launchTokenHash: authority.launchTokenHash } : {}), - ...(authority?.hostScope ? { hostScope: JSON.stringify(authority.hostScope) } : {}) - } -} - -export async function createExistingWorktreeWorkerTerminal(args: { - runtime: OrcaRuntimeService - worktreeId: string - agent: TuiAgent - launchPreferences?: AgentLaunchPreferences - taskId: string - effects: WorkerEffect[] -}): Promise { - const terminal = await args.runtime.createTerminal(`id:${args.worktreeId}`, { - // Resolve ids through agent config; cursor alone opens the desktop app, its CLI is cursor-agent. - startupAgent: args.agent, - launchSource: 'orchestration', - suppressStartupUpdatePrompt: true, - ...(args.launchPreferences ? { launchPreferences: args.launchPreferences } : {}), - title: `worker-${args.taskId}`, - // Worker creation is background work and must not pull the sidebar away. - surfaceOwner: false - }) - args.effects.push({ - kind: 'terminal', - role: 'agent', - action: 'created', - id: terminal.handle, - surface: terminal.surface, - warning: terminal.warning - }) - return terminal -} - -/** Return structured workers in the terminal authority shape; registry-backed pane/incarnation getters keep requireWorkerAuthority mode-independent. */ -export async function createStructuredWorkerSessionForWorktree(args: { - runtime: OrcaRuntimeService - worktreeId: string - agent: TuiAgent - dispatchId: string - /** `--model`/`--effort`; the session seeds them exactly as a saved selection is seeded. */ - launchPreferences?: AgentLaunchPreferences - effects: WorkerEffect[] -}): Promise>> { - const options = narrowStructuredLaunchSeedOptions(args.launchPreferences) - const created = await createStructuredWorkerSession({ - runtime: args.runtime, - worktreeId: args.worktreeId, - agent: args.agent, - dispatchId: args.dispatchId, - ...(options ? { options } : {}) - }) - args.effects.push({ - kind: 'terminal', - role: 'agent', - action: 'created', - id: created.identity.handle, - surface: 'background' - }) - return created -} - -export function applyWaitForSetupOutcome( - receipt: WorkerSetupReceipt, - effects: WorkerEffect[], - wait: { satisfied: boolean; status: string } -): void { - if (receipt.startupPolicy !== 'wait-for-setup' || receipt.state !== 'running') { - return - } - if (wait.satisfied) { - receipt.state = 'succeeded' - } else if (wait.status === 'exited') { - receipt.state = 'failed' - } else { - return - } - const setupEffect = effects.find((effect) => effect.kind === 'setup') - if (setupEffect) { - setupEffect.state = receipt.state - } -} - -export function monitorWorkerSetup(args: { - runtime: OrcaRuntimeService - db: OrchestrationDb - runId: string - dispatchId: string - setupReceipt: WorkerSetupReceipt - effects: WorkerEffect[] -}): void { - const setupTerminal = args.effects.find( - (effect) => effect.kind === 'terminal' && effect.role === 'setup' && effect.id - ) - if ( - !setupTerminal?.id || - args.setupReceipt.startupPolicy !== 'start-immediately' || - args.setupReceipt.state !== 'running' - ) { - return - } - // Why: setup is intentionally non-gating, but command completion remains durable evidence. - void args.runtime - .waitForSetupTerminalCompletion(setupTerminal.id) - .then((completion) => { - const setupState = completion.exitCode === 0 ? 'succeeded' : 'failed' - const evidence = args.db.updateWorkerSetupEvidence({ - dispatchId: args.dispatchId, - setupState, - effects: args.effects.map((effect) => - effect.kind === 'setup' ? { ...effect, state: setupState } : effect - ) - }) - if (!evidence.changed) { - return - } - const dispatch = args.db.getDispatchContextById(args.dispatchId) - const message = args.db.insertMessage({ - runId: args.runId, - from: `dispatch:${args.dispatchId}`, - to: dispatch ? dispatchReportMailbox(args.db, dispatch) : `run:${args.runId}`, - subject: `Setup ${setupState} for worker ${args.dispatchId}`, - type: 'status', - priority: setupState === 'failed' ? 'high' : 'normal', - payload: JSON.stringify({ - dispatchId: args.dispatchId, - setupState, - terminalHandle: setupTerminal.id - }) - }) - args.runtime.notifyMessageArrived(message.to_handle, message.type) - }) - .catch(() => undefined) -} - -export function isUnknownWorkerStartOutcome(error: unknown, stage: string): boolean { - const code = - error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string' - ? (error as { code: string }).code - : '' - if (code === 'operation_unknown') { - return true - } - if (stage !== 'worktree_create') { - return false - } - const message = error instanceof Error ? error.message : String(error) - return /connection|disconnect|timed?\s*out|runtime changed|outcome unknown/i.test(message) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts deleted file mode 100644 index 8ecf24d3652..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { RpcDispatcher } from '../../../dispatcher' -import type { RpcRequest } from '../../../core' -import { ORCHESTRATION_METHODS } from '../orchestration' -import './worker-opencode-model-preflight' -import '../../../../../../shared/rpc-contract/orchestration-federation-start-params' - -describe('orchestration new-worktree workers', () => { - const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - let db: OrchestrationDb - let runtime: OrcaRuntimeService - let runId: string - const paths: string[] = [] - - beforeEach(() => { - db = new OrchestrationDb(':memory:') - runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - runId = db.createRun({ - objective: 'Test new-worktree workers', - coordinatorHandle: 'term_coord', - coordinatorPaneKey - }).id - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' - ? coordinatorPaneKey - : handle === 'term_worker' - ? 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - : null - ) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => - handle === 'term_worker' ? 'runtime_test:term_worker:1' : null - ) - vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) - vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ - handle: 'term_coord', - worktreeId: 'repo::parent', - status: 'running' - } as never) - vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({ - id: 'repo::parent', - repoId: 'repo' - } as never) - vi.spyOn(runtime, 'showRepo').mockResolvedValue({ - id: 'repo', - kind: 'git' - } as never) - vi.spyOn(runtime, 'createTerminal') - vi.spyOn(runtime, 'listTerminals').mockResolvedValue({ - terminals: [{ handle: 'term_worker', title: 'Codex' }], - totalCount: 1, - truncated: false - } as never) - vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: true, - status: 'running', - exitCode: null - }) - vi.spyOn(runtime, 'waitForSetupTerminalCompletion').mockReturnValue( - new Promise(() => undefined) - ) - vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ - handle: 'term_worker', - accepted: true, - bytesWritten: 1 - }) - }) - - afterEach(() => { - db.close() - for (const path of paths.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } - }) - - async function startWorker(overrides: Record = {}) { - const task = db.createTask({ spec: 'new-worktree task', runId }) - const method = ORCHESTRATION_METHODS.find( - (candidate) => candidate.name === 'orchestration.workerStart' - ) - if (!method) { - throw new Error('workerStart method is not registered') - } - const params = method.params!.parse({ - task: task.id, - from: 'term_coord', - worktree: 'new-child', - name: 'new-worker', - agent: 'codex', - ...overrides - }) - const result = await method.handler(params, { runtime }) - return { result, task } - } - - function mockCreatedWorktree(options?: { - hookFound?: boolean - startupPolicy?: 'start-immediately' | 'wait-for-setup' - state?: 'running' | 'skipped' | 'not_configured' | 'spawn_failed' - terminals?: { handle: string; title: string }[] - setupTerminalHandle?: string - }) { - const hookFound = options?.hookFound ?? true - const state = options?.state ?? (hookFound ? 'running' : 'not_configured') - vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({ - worktree: { id: 'repo::created', repoId: 'repo' }, - startupTerminal: { spawned: true, handle: 'term_worker' }, - setupReceipt: { - requested: state === 'skipped' ? 'skip' : 'run', - hookFound, - startupPolicy: options?.startupPolicy ?? 'start-immediately', - state, - terminalHandle: - options?.setupTerminalHandle ?? - options?.terminals?.find((terminal) => terminal.title === 'Setup')?.handle - } - } as never) - if (options?.terminals) { - vi.mocked(runtime.listTerminals).mockResolvedValue({ - terminals: options.terminals, - totalCount: options.terminals.length, - truncated: false - } as never) - } - } - - it("skips setup when the project's setup is off and the coordinator did not ask for it", async () => { - vi.mocked(runtime.showRepo).mockResolvedValue({ - id: 'repo', - path: '/repo', - displayName: 'repo', - badgeColor: 'gray', - addedAt: 1, - kind: 'git', - hookSettings: { - mode: 'auto', - setupRunPolicy: 'skip-by-default', - scripts: { setup: '', archive: '' } - } - }) - mockCreatedWorktree({ state: 'skipped' }) - - await startWorker() - - expect(runtime.createManagedWorktree).toHaveBeenCalledWith( - expect.objectContaining({ setupDecision: 'skip' }) - ) - }) - - // Composer and idle readiness paths must both record setup evidence; the composer path previously dropped it. - - it('does not inject task input when the gated setup terminal fails to start', async () => { - mockCreatedWorktree({ startupPolicy: 'wait-for-setup', state: 'spawn_failed' }) - vi.mocked(runtime.waitForTerminal).mockResolvedValue({ - handle: 'term_worker', - condition: 'tui-idle', - satisfied: false, - status: 'exited', - exitCode: 1 - }) - - const { result, task } = await startWorker() - - expect(result).toMatchObject({ - state: 'failed', - failedStage: 'setup_start', - setup: { startupPolicy: 'wait-for-setup', state: 'spawn_failed' }, - effects: expect.arrayContaining([ - expect.objectContaining({ kind: 'setup', state: 'spawn_failed' }) - ]) - }) - expect(db.getTask(task.id)?.status).toBe('failed') - expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - - it('returns outcome unknown when worktree creation may have been accepted remotely', async () => { - vi.spyOn(runtime, 'createManagedWorktree').mockRejectedValue( - Object.assign(new Error('connection closed after request acceptance'), { - code: 'operation_unknown' - }) - ) - - const { result, task } = await startWorker() - - expect(result).toMatchObject({ - state: 'outcome_unknown', - failedStage: 'worktree_create' - }) - expect(db.getTask(task.id)?.status).toBe('blocked') - }) - - it('replays a dispatch-input failure after restart without creating another worker', async () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-worker-start-replay-')) - paths.push(dir) - db.close() - db = new OrchestrationDb(join(dir, 'orchestration.db')) - runtime.setOrchestrationDb(db) - runId = db.createRun({ - objective: 'Recover dispatch input', - coordinatorHandle: 'term_coord', - coordinatorPaneKey - }).id - mockCreatedWorktree({ hookFound: false }) - vi.mocked(runtime.sendTerminalAgentPrompt).mockRejectedValueOnce( - new Error('connection closed before dispatch input was accepted') - ) - const task = db.createTask({ spec: 'recover dispatch input', runId }) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const request: RpcRequest = { - id: 'rpc_worker_start', - authToken: 'caller-token', - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'worker_start_request', - method: 'orchestration.workerStart', - params: { - task: task.id, - from: 'term_coord', - worktree: 'new-child', - name: 'recover-input-worker', - agent: 'codex' - } - } - - const first = await dispatcher.dispatch(request) - if (!first.ok) { - throw new Error(`Initial worker start failed: ${first.error.code}`) - } - const firstReceipt = first.result as { - dispatchId: string - residualResources: unknown[] - } - db.close() - - db = new OrchestrationDb(join(dir, 'orchestration.db')) - const restartedRuntime = new OrcaRuntimeService() - restartedRuntime.setOrchestrationDb(db) - vi.spyOn(restartedRuntime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord_reminted' - ? `tab_coord_reminted:${coordinatorPaneKey.split(':')[1]}` - : null - ) - const recreateWorktree = vi - .spyOn(restartedRuntime, 'createManagedWorktree') - .mockRejectedValue(new Error('replay recreated the worktree')) - const reinjectPrompt = vi - .spyOn(restartedRuntime, 'sendTerminalAgentPrompt') - .mockRejectedValue(new Error('replay reinjected the prompt')) - const restartedDispatcher = new RpcDispatcher({ - runtime: restartedRuntime, - methods: ORCHESTRATION_METHODS - }) - const replay = await restartedDispatcher.dispatch({ - ...request, - id: 'rpc_worker_start_retry', - authToken: 'caller-token-after-restart', - params: { ...(request.params as Record), from: 'term_coord_reminted' } - }) - - expect(first).toMatchObject({ - ok: true, - result: { - state: 'failed', - failedStage: 'dispatch_input', - residualResources: expect.arrayContaining([ - expect.objectContaining({ kind: 'worktree', id: 'repo::created' }), - expect.objectContaining({ kind: 'terminal', id: 'term_worker' }) - ]), - mutation: { requestId: 'worker_start_request', replayed: false } - } - }) - expect(replay).toMatchObject({ - ok: true, - result: { - dispatchId: firstReceipt.dispatchId, - state: 'failed', - failedStage: 'dispatch_input', - residualResources: firstReceipt.residualResources, - mutation: { requestId: 'worker_start_request', replayed: true } - } - }) - expect(recreateWorktree).not.toHaveBeenCalled() - expect(reinjectPrompt).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts deleted file mode 100644 index 40d9cfcefe6..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import '../../../../orchestration/db/contract-constants' -import '../../../../orchestration/db/messages/mailbox-routing-page' -import '../../../../orchestration/db/dispatch-row-writer' -import '../../../../orchestration/db/attempt-outcome-projection' -import { ORCHESTRATION_METHODS } from '../orchestration' -import { isStreamingMethod, eraseRpcMethods } from '../../../core' - -function deferred(): { promise: Promise; resolve: (value: T) => void } { - let resolve!: (value: T) => void - const promise = new Promise((promiseResolve) => { - resolve = promiseResolve - }) - return { promise, resolve } -} - -describe('orchestration worker recovery', () => { - let db: OrchestrationDb - let runtime: OrcaRuntimeService - - beforeEach(() => { - db = new OrchestrationDb(':memory:') - runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue( - 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - ) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1') - vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - connected: true, - status: 'running' - } as never) - vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ - handle: 'term_worker', - status: 'running', - tail: ['working'], - truncated: false, - nextCursor: null - }) - vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({ - handle: 'term_worker', - tabId: 'tab-worker', - ptyKilled: true - } as never) - }) - - afterEach(() => db.close()) - - async function call(name: string, params: Record) { - const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( - (candidate) => candidate.name === name - ) - if (!method || isStreamingMethod(method)) { - throw new Error(`Method not found: ${name}`) - } - return method.handler(method.params!.parse(params), { runtime }) - } - - function createWorker(runtimeEpoch = runtime.getRuntimeId(), ready = true) { - const run = db.createRun({ - objective: 'Recovery', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - const task = db.createTask({ spec: 'recover worker', runId: run.id }) - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {}, - runtimeEpoch - }) - db.prepareStartingWorkerAuthority({ - dispatchId: started.dispatch.id, - handle: 'term_worker', - paneKey: 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', - processIncarnation: 'runtime:pty:1', - worktreeId: 'repo::worktree', - setupState: 'not_applicable', - effects: [{ kind: 'terminal', action: 'created', id: 'term_worker' }], - terminalOwnership: 'created' - }) - if (ready) { - db.markWorkerDispatchReady(started.dispatch.id) - } else { - db.markWorkerStartUnknown(started.dispatch.id, 'dispatch_input', 'connection lost') - } - return { run, task, dispatch: started.dispatch } - } - - it('stops an exact worker whose start receipt is unknown', async () => { - const { task, dispatch } = createWorker(runtime.getRuntimeId(), false) - - await expect( - call('orchestration.workerStop', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - state: 'stopped', - processAction: 'closed_agent_terminal' - }) - expect(runtime.closeTerminal).toHaveBeenCalledWith('term_worker') - expect(db.getTask(task.id)?.status).toBe('blocked') - }) - - it('keeps an in-flight stop fenced during runtime-epoch reconciliation', async () => { - const { dispatch } = createWorker('previous_runtime') - const pendingObservation = deferred>>() - vi.mocked(runtime.showTerminal) - .mockReturnValueOnce(pendingObservation.promise) - .mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - connected: true, - status: 'running' - } as never) - - const stop = call('orchestration.workerStop', { dispatch: dispatch.id }) - await vi.waitFor(() => expect(runtime.showTerminal).toHaveBeenCalledTimes(1)) - await expect( - call('orchestration.workerShow', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ worker: { state: 'stopping' } }) - await expect(call('orchestration.workerAbandon', { dispatch: dispatch.id })).rejects.toThrow( - 'is stopping; wait for worker-stop to settle before abandoning' - ) - - pendingObservation.resolve({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - connected: true, - status: 'running' - } as never) - await expect(stop).resolves.toMatchObject({ - state: 'stopped', - processAction: 'closed_agent_terminal' - }) - }) - - it('does not adopt or stop a same-looking pane with a new process incarnation', async () => { - const { task, dispatch } = createWorker() - vi.mocked(runtime.getTerminalProcessIncarnation).mockReturnValue('runtime:pty:2') - - await expect( - call('orchestration.workerShow', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - worker: { state: 'ready' }, - observation: { status: 'identity_changed', exactWorker: false }, - terminal: null - }) - await expect(call('orchestration.workerRead', { dispatch: dispatch.id })).rejects.toMatchObject( - { - code: 'worker_identity_changed' - } - ) - await expect( - call('orchestration.workerStop', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - state: 'stop_unknown', - processAction: 'none' - }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getTask(task.id)?.status).toBe('blocked') - }) - - it('labels an exact but disconnected worker as exited and does not close it again', async () => { - const { task, dispatch } = createWorker() - vi.mocked(runtime.showTerminal).mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - connected: false, - writable: false - } as never) - // `connected: false` is transport state; an exited result requires the - // runtime's authoritative host-side verdict. - vi.spyOn(runtime, 'getTerminalLivenessVerdict').mockReturnValue({ status: 'exited' }) - - await expect( - call('orchestration.workerShow', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - observation: { status: 'exited', exactWorker: true }, - terminal: { handle: 'term_worker', connected: false } - }) - await expect( - call('orchestration.workerStop', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - state: 'stop_unknown', - processAction: 'none' - }) - expect(runtime.closeTerminal).not.toHaveBeenCalled() - expect(db.getTask(task.id)?.status).toBe('blocked') - }) - - it('turns an interrupted start into inspectable unknown after runtime restart', async () => { - const run = db.createRun({ - objective: 'Interrupted start', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - const task = db.createTask({ spec: 'interrupted', runId: run.id }) - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {}, - runtimeEpoch: 'previous_runtime' - }) - db.recordWorkerStage({ - dispatchId: started.dispatch.id, - stage: 'worktree_creating' - }) - - await expect( - call('orchestration.workerShow', { dispatch: started.dispatch.id }) - ).resolves.toMatchObject({ - worker: { state: 'start_unknown', stage: 'worktree_creating' }, - observation: { status: 'unattached', exactWorker: false } - }) - expect(db.getTask(task.id)?.status).toBe('blocked') - }) - - it('turns an interrupted stop into unknown after runtime restart', async () => { - const { task, dispatch } = createWorker('previous_runtime') - db.beginWorkerStop(dispatch.id, 'previous_runtime') - - await expect( - call('orchestration.workerShow', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - worker: { state: 'stop_unknown' } - }) - expect(db.getTask(task.id)?.status).toBe('blocked') - }) - - it('does not let a delayed remote show revive a released worker projection', async () => { - const run = db.createRun({ - objective: 'Fence delayed remote show', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - }) - const task = db.createTask({ spec: 'release remote worker', runId: run.id }) - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {}, - federation: { - environmentId: 'environment_windows', - environmentName: 'windows', - peerFingerprint: 'windows_peer', - protocolVersion: 1 - } - }) - db.reconcileFederatedWorkerStart({ - dispatchId: started.dispatch.id, - state: 'ready', - stage: 'remote_input_accepted', - worktreeId: 'repo::windows-worktree', - terminalHandle: 'term_windows_worker' - }) - db.updateFederatedDispatchResources({ - dispatchId: started.dispatch.id, - remoteRuntimeEpoch: 'windows_epoch_old', - worktreeId: 'repo::windows-worktree', - terminalHandle: 'term_windows_worker' - }) - const pendingShow = deferred() - vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({ - environmentId: 'environment_windows', - name: 'windows', - peerFingerprint: 'windows_peer' - }) - vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockReturnValue(pendingShow.promise) - - const show = call('orchestration.workerShow', { dispatch: started.dispatch.id }) - await vi.waitFor(() => expect(runtime.callOrchestrationWorkerServer).toHaveBeenCalledOnce()) - db.transitionLifecycle({ - entity: 'worker', - id: started.dispatch.id, - from: 'ready', - to: 'ready', - projection: { stage: 'released', agent_terminal_handle: null } - }) - db.db - .prepare( - `UPDATE federated_dispatches - SET remote_runtime_epoch = 'windows_epoch_new', remote_terminal_handle = NULL - WHERE dispatch_id = ?` - ) - .run(started.dispatch.id) - pendingShow.resolve({ - runtimeEpoch: 'windows_epoch_old', - attachment: { - state: 'ready', - stage: 'remote_input_accepted', - last_error: null, - worktree_id: 'repo::windows-worktree', - terminal_handle: 'term_windows_worker', - setup_state: 'not_applicable', - effects: [], - residualResources: [] - }, - terminal: { handle: 'term_windows_worker', connected: true }, - observation: { status: 'live', exactWorker: true } - }) - - await expect(show).resolves.toMatchObject({ - worker: { stage: 'released', agentTerminalHandle: null }, - remoteRuntimeEpoch: 'windows_epoch_new', - terminal: null, - observation: { - status: 'unverifiable', - exactWorker: false, - reason: 'observation_superseded' - } - }) - expect(db.getFederatedDispatch(started.dispatch.id)).toMatchObject({ - remote_runtime_epoch: 'windows_epoch_new', - remote_terminal_handle: null - }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts deleted file mode 100644 index df354916b30..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { stopHelperAfterStart } from './worker-stop' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { z } from 'zod' -import type { RpcContext } from '../../../core' -import { defineOrchestrationMethod } from '../access/orchestration-method-access' -import { startFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-start' -import { startLocalWorker } from './local-worker-start' -import type { WorkerFollowUp } from './worker-follow-up-placement' -import { withWorkerStartNext } from '../receipt-next' -import { - decideWorkerStartMode, - readWorkerStartModeSettings -} from '../structured-workers/orchestration-worker-start-mode' -import { resolveOrchestrationCaller } from '../runs/run-scope' -import { - assertHelperStartScope, - resolveWorkerStartRun, - qualifyLiveWorkerFollowUp -} from './worker-start-authority' -import { parseTaskDeps } from './task-deps-argument' -import { WorkerStartParams } from '../../../../../../shared/rpc-contract/orchestration-worker-start-params' -import { - isWorkerStartTimeoutWithinTimerLimit, - resolveWorkerStartReadinessTimeoutMs -} from '../../../../../../shared/orchestration/orchestration-timing-budgets' -import { buildOrchestrationTaskDisplayMetadata } from '../../../../../../shared/orchestration/orchestration-task-display' -import { assertWorkerStartTaskSpecWithinPromptBudget } from './worker-start-prompt-budget' -import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../../shared/orca-session-address-prefix' -import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as SESSION_CODES } from '../../../../../../shared/orchestration/orchestration-session-caller-codes' -import { resolveDispatchCreator } from '../runs/dispatch-creator' - -type WorkerStartContext = Pick< - RpcContext, - 'runtime' | 'orchestrationMutation' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' -> - -export const ORCHESTRATION_WORKER_START_METHODS = [ - defineOrchestrationMethod({ - name: 'orchestration.workerStart', - access: { - kind: 'writes', - caller: 'from', - server: 'on', - targets: { - task: 'task', - parent: 'task', - deps: 'task', - run: 'run', - retryOf: 'dispatch', - terminal: 'worker', - adoptTaskId: 'task' - } - }, - requires: ['accounts'], - permission: 'workspace', - params: WorkerStartParams, - handler: async (params, ctx) => startWorker(params, ctx) - }) -] - -/** worker-start, and a follow-up sent to a finished worker, which is worker-start run for the sender. */ -export async function startWorker( - startParams: z.infer, - ctx: WorkerStartContext, - startFollowUp?: WorkerFollowUp -): Promise { - const { runtime, orchestrationMutation, orchestrationCaller } = ctx - const prepared = await prepareWorkerStart(startParams, ctx, startFollowUp) - const { params, followUp, coordinator, bindRun, helperCreator, taskDeps, existingTask, withRun } = - prepared - const db = runtime.getOrchestrationDb() - const mode = decideWorkerStartMode({ - params, - settings: readWorkerStartModeSettings(runtime) - }) - if (params.on) { - // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. - const receipt = await startFederatedWorker({ - params, - runtime, - db, - bindRunId: () => bindRun().run.id, - task: existingTask, - taskDeps, - orchestrationMutation, - callerSession: orchestrationCaller - }) - await stopHelperAfterStart(runtime, receipt, orchestrationMutation) - return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) - } - const receipt = await startLocalWorker({ - params: { ...params, timeoutMs: resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) }, - runtime, - db, - bindRun: () => bindRun().run, - taskDeps, - coordinator, - callerSession: orchestrationCaller, - existingTask, - orchestrationMutation, - mode, - helperCreator, - followUp - }) - await stopHelperAfterStart(runtime, receipt, orchestrationMutation) - return withRun(withWorkerStartNext(receipt)) -} - -/** What every start checks and binds before it is placed, here or on a paired server. */ -export async function prepareWorkerStart( - params: z.infer, - { - runtime, - orchestrationCompatibilityEvidence, - orchestrationCaller - }: Omit, - followUp?: WorkerFollowUp -) { - if (!isWorkerStartTimeoutWithinTimerLimit(params.timeoutMs)) { - throw new OrchestrationError( - 'invalid_argument', - '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' - ) - } - if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { - // Refused here, before any remote call: an Orca session ID names a chat only on its own host. - throw new OrchestrationError( - SESSION_CODES.hostBoundary, - `${params.terminal} names a chat by its Orca session ID, which identifies it only on the host that runs it. Run worker-start on that host. No effects were applied.`, - { effectsApplied: false } - ) - } - if (params.adoptTaskId !== undefined && orchestrationCaller?.kind !== 'peer') { - throw new OrchestrationError( - 'invalid_argument', - 'Only the paired Orca coordinating a Run names its Task IDs. No effects were applied.', - { effectsApplied: false } - ) - } - const placement = params.worktree ?? 'current' - if ( - orchestrationCaller?.kind === 'peer' && - !followUp && - !params.terminal && - /^(current|new-child)$/.test(placement) - ) { - throw new OrchestrationError( - 'invalid_argument', - `--on requires an exact remote worktree selector or new-top-level: ${orchestrationCaller.peerRun.home_label} has no workspace on this server for --worktree ${placement}. No effects were applied.`, - { effectsApplied: false } - ) - } - const db = runtime.getOrchestrationDb() - const coordinator = resolveOrchestrationCaller(runtime, { - callerTerminalHandle: params.from, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - if (params.spec) { - // Before the Run resolves, so a refused spec cannot leave a new Run bound. - await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) - } - const taskDeps = parseTaskDeps(params.deps) - const qualified = followUp - ? qualifyLiveWorkerFollowUp( - runtime, - coordinator, - params.from, - orchestrationCaller, - params.run!, - followUp - ) - : undefined - const { bindRun, helperCreator } = qualified - ? { bindRun: () => ({ run: qualified.run, created: false }), helperCreator: qualified.creator } - : resolveWorkerStartRun(runtime, { - coordinator, - from: params.from, - callerSession: orchestrationCaller, - runId: params.run, - // The Run takes the title its first Task gets. - objective: params.spec - ? buildOrchestrationTaskDisplayMetadata({ - spec: params.spec, - taskTitle: params.taskTitle - }).taskTitle - : undefined, - taskReferences: [...(params.parent ? [params.parent] : []), ...(taskDeps ?? [])] - }) - // Name the Run in every receipt so a reused, stale binding is visible. - const withRun = (receipt: unknown): unknown => { - if (!receipt || typeof receipt !== 'object') { - return receipt - } - const { run, created } = bindRun() - return { ...receipt, run: { id: run.id, objective: run.objective, created } } - } - const existingTask = params.task ? db.getTask(params.task) : undefined - // --task excludes --spec, so this never creates a Run. - if (params.task && (!existingTask || existingTask.run_id !== bindRun().run.id)) { - throw new OrchestrationError( - 'task_not_found', - `Task ${params.task} was not found in Run ${bindRun().run.id}.` - ) - } - if (helperCreator && !followUp) { - assertHelperStartScope(db, helperCreator, { - task: existingTask, - params, - ...(followUp ? { followUp } : {}) - }) - } - if (existingTask) { - await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) - } - if (followUp) { - const placement = await followUp.place(() => { - if ( - helperCreator && - db.resolveCreatorDispatchId( - resolveDispatchCreator(runtime, params.from, orchestrationCaller) - ) !== helperCreator.id - ) { - throw new OrchestrationError( - 'consumer_fenced', - `Dispatch ${helperCreator.id} is no longer this caller's active work. No effects were applied.`, - { effectsApplied: false } - ) - } - }) - const spec = [ - params.spec, - placement.delivery === 'started_fresh' ? placement.earlierWork : undefined - ] - .filter(Boolean) - .join('\n\n') - params = { - ...params, - worktree: `id:${placement.worktreeId}`, - ...(placement.terminal ? { terminal: placement.terminal } : {}), - ...(placement.agent ? { agent: placement.agent } : {}), - ...(placement.model ? { model: placement.model } : {}), - ...(placement.effort ? { effort: placement.effort } : {}), - spec - } - followUp = { ...followUp, reopen: placement.reopen, earlierWork: placement.earlierWork } - await assertWorkerStartTaskSpecWithinPromptBudget(spec) - } - return { - params, - followUp, - coordinator, - bindRun, - helperCreator, - taskDeps, - existingTask, - withRun - } -} diff --git a/src/main/runtime/rpc/methods/pairing/mobile-relay-hosts.ts b/src/main/runtime/rpc/methods/pairing/mobile-relay-hosts.ts index 865835145af..17d0f2a8521 100644 --- a/src/main/runtime/rpc/methods/pairing/mobile-relay-hosts.ts +++ b/src/main/runtime/rpc/methods/pairing/mobile-relay-hosts.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { resolveWorktreeCatalogSnapshot } from '../../worktree-catalog-snapshot' +import { resolveWorktreeCatalogSnapshot } from '../../workspace-client-views/worktree-catalog-snapshot' import { MOBILE_RELAY_HOST_WORKTREES_METHOD, MOBILE_RELAY_HOSTS_LIST_METHOD, diff --git a/src/main/runtime/rpc/methods/plugins/plugin-dev-emit.ts b/src/main/runtime/rpc/methods/plugins/plugin-dev-emit.ts index 9663661b91b..a2a84d7235e 100644 --- a/src/main/runtime/rpc/methods/plugins/plugin-dev-emit.ts +++ b/src/main/runtime/rpc/methods/plugins/plugin-dev-emit.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../core' import { PluginDevEmitParams, PluginDevHookParams -} from '../../../../../shared/rpc-contract/plugins-params' +} from '../../../../../shared/rpc-contract/plugins/plugins-params' import { firePluginDevHook } from '../../../../plugins/hooks/plugin-dev-hook-fire' import { emitPluginDevEvent } from '../../../../plugins/plugin-dev-event-emit' import { requirePluginService } from './plugins' diff --git a/src/main/runtime/rpc/methods/plugins/plugin-dev-request.ts b/src/main/runtime/rpc/methods/plugins/plugin-dev-request.ts index 7a6670b66fc..76aa247b388 100644 --- a/src/main/runtime/rpc/methods/plugins/plugin-dev-request.ts +++ b/src/main/runtime/rpc/methods/plugins/plugin-dev-request.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { PluginDevRequestParams } from '../../../../../shared/rpc-contract/plugins-params' +import { PluginDevRequestParams } from '../../../../../shared/rpc-contract/plugins/plugins-params' import { requestPluginDevPanelHandler } from '../../../../plugins/plugin-dev-panel-request' import { requirePluginService } from './plugins' diff --git a/src/main/runtime/rpc/methods/plugins/plugin-install-methods.ts b/src/main/runtime/rpc/methods/plugins/plugin-install-methods.ts index ac5c9ba45f3..82b5e060653 100644 --- a/src/main/runtime/rpc/methods/plugins/plugin-install-methods.ts +++ b/src/main/runtime/rpc/methods/plugins/plugin-install-methods.ts @@ -6,7 +6,7 @@ import { PluginInstallParams, PluginUninstallParams, PluginUpdateParams -} from '../../../../../shared/rpc-contract/plugins-params' +} from '../../../../../shared/rpc-contract/plugins/plugins-params' import { PLUGIN_NOT_FOUND_CODE, PluginCliError diff --git a/src/main/runtime/rpc/methods/plugins/plugin-view.ts b/src/main/runtime/rpc/methods/plugins/plugin-view.ts index c331bc2a99b..5906b23cc5e 100644 --- a/src/main/runtime/rpc/methods/plugins/plugin-view.ts +++ b/src/main/runtime/rpc/methods/plugins/plugin-view.ts @@ -6,7 +6,7 @@ import { PluginShotEditorParams, PluginShotParams, PluginShotReplayParams -} from '../../../../../shared/rpc-contract/plugins-params' +} from '../../../../../shared/rpc-contract/plugins/plugins-params' // Desktop only: a headless `orca serve` has no window to show or capture a plugin in. let pluginViewForRpc: PluginViewDesktop | null = null diff --git a/src/main/runtime/rpc/methods/plugins/plugins.test.ts b/src/main/runtime/rpc/methods/plugins/plugins.test.ts index 6223125b740..7586b4d9b7c 100644 --- a/src/main/runtime/rpc/methods/plugins/plugins.test.ts +++ b/src/main/runtime/rpc/methods/plugins/plugins.test.ts @@ -3,7 +3,7 @@ import { eraseRpcMethods, type RpcContext, type RpcMethod } from '../../core' import type { PluginService } from '../../../../plugins/plugin-service' import { PLUGIN_METHODS, setPluginServiceForRpc } from './plugins' import { PluginLogBuffer } from '../../../../plugins/plugin-log-buffer' -import '../../../../../shared/rpc-contract/plugins-params' +import '../../../../../shared/rpc-contract/plugins/plugins-params' vi.mock('../../../../plugins/plugin-client-list', () => ({ listPluginsForClients: vi.fn().mockResolvedValue([]) diff --git a/src/main/runtime/rpc/methods/plugins/plugins.ts b/src/main/runtime/rpc/methods/plugins/plugins.ts index fecb02ebe0e..4d787a29255 100644 --- a/src/main/runtime/rpc/methods/plugins/plugins.ts +++ b/src/main/runtime/rpc/methods/plugins/plugins.ts @@ -16,7 +16,7 @@ import { PluginSetEnabledParams, PluginSetSystemEnabledParams, PluginsPanelActionParams -} from '../../../../../shared/rpc-contract/plugins-params' +} from '../../../../../shared/rpc-contract/plugins/plugins-params' import { approvePluginFromCli, pluginCliApprovalRequest diff --git a/src/main/runtime/rpc/methods/preflight/preflight.ts b/src/main/runtime/rpc/methods/preflight/preflight.ts index c0562a581ad..e8ea0998ae0 100644 --- a/src/main/runtime/rpc/methods/preflight/preflight.ts +++ b/src/main/runtime/rpc/methods/preflight/preflight.ts @@ -19,7 +19,7 @@ import { PreflightCheck, PreflightDetectRemoteAgents, PreflightDetectRemoteWindowsTerminalCapabilities -} from '../../../../../shared/rpc-contract/preflight-params' +} from '../../../../../shared/rpc-contract/preflight/preflight-params' /** This host's command overrides, so a configured CLI outside PATH is listed like a detected one. */ function hostDetectionOptions( diff --git a/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts b/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts index 4b1f86d9b2c..b004f2774be 100644 --- a/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { projectRepoVisibilityForClient } from '../../repo-visibility-projection' +import { projectRepoVisibilityForClient } from '../../workspace-client-views/repo-visibility-projection' import { ProjectGroupCreate, ProjectGroupImportNested, @@ -8,7 +8,7 @@ import { ProjectGroupSelector, ProjectGroupUpdate, ProjectGroupUpdateMany -} from '../../../../../shared/rpc-contract/repo-params' +} from '../../../../../shared/rpc-contract/projects/repo-params' export const PROJECT_GROUP_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/projects/project-runtime-rpc-methods.ts b/src/main/runtime/rpc/methods/projects/project-runtime-rpc-methods.ts index 7eb3932b67c..e18b18baf0f 100644 --- a/src/main/runtime/rpc/methods/projects/project-runtime-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/projects/project-runtime-rpc-methods.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { projectRepoResultVisibilityForClient } from '../../repo-visibility-projection' +import { projectRepoResultVisibilityForClient } from '../../workspace-client-views/repo-visibility-projection' import { ProjectHostSetupClone, ProjectHostSetupCreate, @@ -7,7 +7,7 @@ import { ProjectHostSetupExistingFolder, ProjectHostSetupUpdate, ProjectUpdate -} from '../../../../../shared/rpc-contract/project-runtime-params' +} from '../../../../../shared/rpc-contract/projects/project-runtime-params' export const PROJECT_RUNTIME_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/projects/repo.ts b/src/main/runtime/rpc/methods/projects/repo.ts index dd1bfdbb411..21672047b84 100644 --- a/src/main/runtime/rpc/methods/projects/repo.ts +++ b/src/main/runtime/rpc/methods/projects/repo.ts @@ -1,5 +1,7 @@ import { defineMethod } from '../../core' -import { resolveReplySnapshot } from '../../content-snapshot-id' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' +import { isRepoHidden } from '../../../../../shared/hidden-projects' +import { resolveReplySnapshot } from '../../workspace-client-views/content-snapshot-id' import { PROJECT_GROUP_METHODS } from './project-group-rpc-methods' import { PROJECT_RUNTIME_METHODS } from './project-runtime-rpc-methods' import { FOLDER_WORKSPACE_METHODS } from '../workspaces/folder-workspace' @@ -11,13 +13,13 @@ import { RepoIssueCommandRead, RepoSelector, RepoShow -} from '../../../../../shared/rpc-contract/github-repo-target-params' +} from '../../../../../shared/rpc-contract/github/github-repo-target-params' import { hostQualifiedRepoSelector } from '../../../workspaces/catalog/runtime-repo-selector' import { repoHooksCheckIsBackground } from '../../../../../shared/repo-hooks-check-wake' import { projectRepoResultVisibilityForClient, projectRepoVisibilityForClient -} from '../../repo-visibility-projection' +} from '../../workspace-client-views/repo-visibility-projection' import { RepoClone, RepoCreate, @@ -28,10 +30,11 @@ import { RepoReorder, RepoSearchRefs, RepoSetBaseRef, + RepoSetHidden, RepoSparsePresetSave, RepoUpdate -} from '../../../../../shared/rpc-contract/repo-params' -import { RepoAddRemote } from '../../../../../shared/rpc-contract/ssh-params' +} from '../../../../../shared/rpc-contract/projects/repo-params' +import { RepoAddRemote } from '../../../../../shared/rpc-contract/ssh/ssh-params' export const REPO_METHODS = [ defineMethod({ @@ -154,6 +157,22 @@ export const REPO_METHODS = [ ) }) }), + defineMethod({ + name: 'repo.setHidden', + permission: 'workspace', + params: RepoSetHidden, + handler: async (params, context) => { + const repo = await context.runtime.setRepoHidden( + hostQualifiedRepoSelector(params.repo, params.repoHostId), + params.hidden + ) + return { + repo: projectRepoVisibilityForClient(repo, context), + hostId: getRepoExecutionHostId(repo), + hidden: isRepoHidden(repo) + } + } + }), defineMethod({ name: 'repo.rm', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/reference/reference.ts b/src/main/runtime/rpc/methods/reference/reference.ts index 0489a9352bb..86e00530764 100644 --- a/src/main/runtime/rpc/methods/reference/reference.ts +++ b/src/main/runtime/rpc/methods/reference/reference.ts @@ -1,5 +1,8 @@ import { defineMethod } from '../../core' -import { ReferenceFind, ReferenceList } from '../../../../../shared/rpc-contract/reference-params' +import { + ReferenceFind, + ReferenceList +} from '../../../../../shared/rpc-contract/references/reference-params' export const REFERENCE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index 5b693508c20..c0168ed85ee 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -7,6 +7,8 @@ import { AI_VAULT_METHODS } from './history/ai-vault' import { AUTOMATION_METHODS } from './automations/automations' import { REPO_METHODS } from './projects/repo' import { WORKTREE_METHODS } from './workspaces/worktree' +import { WORKSPACE_CLEANUP_RUNNER_METHODS } from './workspaces/workspace-cleanup-runner-methods' +import { WORKTREE_ARCHIVE_METHODS } from './workspaces/worktree-archive-methods' import { AGENT_ACTIVITY_METHODS } from './workspaces/agent-activity-methods' import { REFERENCE_METHODS } from './reference/reference' import { TERMINAL_METHODS } from './terminal/terminal' @@ -94,6 +96,8 @@ export const ALL_RPC_METHODS = [ ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, + ...WORKSPACE_CLEANUP_RUNNER_METHODS, + ...WORKTREE_ARCHIVE_METHODS, ...AGENT_ACTIVITY_METHODS, ...REFERENCE_METHODS, ...AGENT_SESSION_METHODS, diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tab-close-methods.ts b/src/main/runtime/rpc/methods/session-tabs/session-tab-close-methods.ts index 95262cf7207..ec085540296 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tab-close-methods.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tab-close-methods.ts @@ -5,7 +5,7 @@ import { defineMethod } from '../../core' import { CloseLifecycleTab, CloseTab -} from '../../../../../shared/rpc-contract/session-tabs-schemas-params' +} from '../../../../../shared/rpc-contract/session-tabs/session-tabs-schemas-params' import { assertProjectedSessionTabVisible } from './session-tab-browser-placement-projection' import { assertAgentSessionTabDestructiveMutationSupported } from './session-tab-agent-status-projection' import { projectSessionTabsForClient } from './session-tabs-inventory' diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tab-markdown-methods.ts b/src/main/runtime/rpc/methods/session-tabs/session-tab-markdown-methods.ts index b9b94f110d2..0e37a46b81b 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tab-markdown-methods.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tab-markdown-methods.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../core' import { ActivateTab, SaveMarkdownTab -} from '../../../../../shared/rpc-contract/session-tabs-schemas-params' +} from '../../../../../shared/rpc-contract/session-tabs/session-tabs-schemas-params' export const SESSION_TAB_MARKDOWN_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts b/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts index e8afa2c0dbf..39662471183 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts @@ -15,7 +15,7 @@ import { MoveTab, SetTabProps, UpdatePaneLayout -} from '../../../../../shared/rpc-contract/session-tabs-schemas-params' +} from '../../../../../shared/rpc-contract/session-tabs/session-tabs-schemas-params' export const SESSION_TAB_MUTATION_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-client-projection.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-client-projection.ts new file mode 100644 index 00000000000..ff38de8ad47 --- /dev/null +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-client-projection.ts @@ -0,0 +1,24 @@ +import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts' +import { projectSessionTabAgentStatus } from './session-tab-agent-status-projection' +import { projectSessionTabBrowserPlacements } from './session-tab-browser-placement-projection' +import { projectSessionTabFileHosts } from './session-tab-file-host-projection' + +export function projectSessionTabsForClient( + snapshot: RuntimeMobileSessionTabsResult, + clientKind: 'mobile' | 'runtime' | undefined, + clientCapabilities: Parameters[2] +): RuntimeMobileSessionTabsResult { + // Phones draw no agent message cards, so they never pay for sender identity. + const { agentSenderAssociations: _desktopOnly, ...phone } = snapshot + return projectSessionTabBrowserPlacements( + projectSessionTabFileHosts( + projectSessionTabAgentStatus( + clientKind === 'mobile' ? phone : snapshot, + clientKind, + clientCapabilities + ), + clientKind + ), + clientCapabilities + ) +} diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts index 375be7af149..901868c9e57 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts @@ -118,8 +118,19 @@ function deferredPtyInventory(): { } } +class CensusRuntime extends OrcaRuntimeService { + projectedFrames = 0 + protected override projectMobileSessionTabsForClient( + snapshot: RuntimeMobileSessionTabsResult, + clientId?: string + ) { + this.projectedFrames += 1 + return super.projectMobileSessionTabsForClient(snapshot, clientId) + } +} + function createRuntimeHarness(initialSnapshots: RuntimeMobileSessionTabsSnapshot[] = []) { - const runtime = new OrcaRuntimeService() + const runtime = new CensusRuntime() runtime.syncWindowGraph(0, { tabs: [], leaves: [], mobileSessionTabs: initialSnapshots }) const census = deferredPtyInventory() const internals = runtime as unknown as RuntimeInventoryInternals @@ -648,3 +659,45 @@ describe('session tabs inventory census boundary', () => { expect(emit).not.toHaveBeenCalled() }) }) + +it.each(['subsumed', 'invalidated', 'aborted'] as const)( + 'does not owe completion for %s held census candidates never emitted', + async (caseName) => { + vi.useFakeTimers({ toFake: ['Date'] }) + const h = createRuntimeHarness() + try { + const created = runtimeSnapshot('wt-census-race', 1) + h.publish([created]) + if (caseName === 'invalidated') { + for (let index = 0; index < 300; index += 1) { + h.publish(index % 2 ? [created] : []) + } + } + if (caseName === 'aborted') { + h.runtime.cleanupSubscription( + 'session.tabs:conn-runtime-census-race:*:req-runtime-census-race' + ) + } + vi.setSystemTime(Date.now() + 46_000) + h.census.resolve(completePtyInventory()) + if (caseName === 'aborted') { + await expect(h.pending).rejects.toThrow('client_disconnected') + expect(h.emit).not.toHaveBeenCalled() + } else { + await h.pending + expect(h.emit.mock.calls).toHaveLength(1) + expect(h.emit.mock.calls[0]?.[0]).toMatchObject({ type: 'snapshots' }) + } + h.runtime.projectedFrames = 0 + const outputs = h.emit.mock.calls.length + h.runtime.markClientHostedPagesReconciled('paired-runtime-census-race') + expect(h.runtime.projectedFrames).toBe(0) + expect(h.emit.mock.calls).toHaveLength(outputs) + } finally { + h.runtime.cleanupSubscription( + 'session.tabs:conn-runtime-census-race:*:req-runtime-census-race' + ) + vi.useRealTimers() + } + } +) diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-collection.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-collection.ts index baddcc5d1bd..895f8f44558 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-collection.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-collection.ts @@ -1,3 +1,5 @@ +import { SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities' +import { projectSessionTabsForClient } from './session-tabs-client-projection' import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts' import type { RpcContext } from '../../core' @@ -34,3 +36,34 @@ export async function collectSessionTabsInventory( changeSequence: collected.changeSequence } } + +export function clientUnderstandsAuthoritativeInventory(context: RpcContext): boolean { + return ( + context.clientCapabilities?.includes( + SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY + ) === true + ) +} + +function projectInventory( + inventory: SessionTabsInventory, + context: RpcContext +): SessionTabsInventory { + return { + snapshots: inventory.snapshots.map((snapshot) => + projectSessionTabsForClient(snapshot, context.clientKind, context.clientCapabilities) + ), + ...(inventory.authoritative && clientUnderstandsAuthoritativeInventory(context) + ? { authoritative: true as const } + : {}) + } +} + +export async function listSessionTabsInventory(context: RpcContext): Promise { + const result = projectInventory((await collectSessionTabsInventory(context)).inventory, context) + if (context.signal?.aborted) { + throw new Error('client_disconnected') + } + context.runtime.observeClientHostedPageSnapshots?.(result.snapshots, context.pairedDeviceId) + return result +} diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory.ts index 7fd80f1dce5..b095b026b07 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory.ts @@ -1,15 +1,14 @@ +import { projectSessionTabsForClient } from './session-tabs-client-projection' +export { projectSessionTabsForClient } from './session-tabs-client-projection' import { collectSessionTabsInventory, - type SessionTabsInventory + clientUnderstandsAuthoritativeInventory } from './session-tabs-inventory-collection' +export { listSessionTabsInventory } from './session-tabs-inventory-collection' import { isDeepStrictEqual } from 'node:util' import '../../../../../shared/protocol-version' -import { SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities' import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts' import type { RpcContext } from '../../core' -import { projectSessionTabAgentStatus } from './session-tab-agent-status-projection' -import { projectSessionTabBrowserPlacements } from './session-tab-browser-placement-projection' -import { projectSessionTabFileHosts } from './session-tab-file-host-projection' import { createSessionTabsStreamDelta } from './session-tabs-sender-delta' import { prepareStructuredTabsIfSupported } from './structured-session-tab-restore' import { createSessionTabsTabDeltaEncoder } from '../../../../../shared/session-tabs-tab-delta' @@ -19,52 +18,6 @@ type SessionTabsChange = RuntimeMobileSessionTabsResult & { removed?: true } const MAX_BUFFERED_CENSUS_CHANGES = 256 const MAX_CENSUS_COLLECTION_ATTEMPTS = 3 -function clientUnderstandsAuthoritativeInventory(context: RpcContext): boolean { - return ( - context.clientCapabilities?.includes( - SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY - ) === true - ) -} - -export function projectSessionTabsForClient( - snapshot: RuntimeMobileSessionTabsResult, - clientKind: 'mobile' | 'runtime' | undefined, - clientCapabilities: Parameters[2] -): RuntimeMobileSessionTabsResult { - // Phones draw no agent message cards, so they never pay for sender identity. - const { agentSenderAssociations: _desktopOnly, ...phone } = snapshot - return projectSessionTabBrowserPlacements( - projectSessionTabFileHosts( - projectSessionTabAgentStatus( - clientKind === 'mobile' ? phone : snapshot, - clientKind, - clientCapabilities - ), - clientKind - ), - clientCapabilities - ) -} - -function projectInventory( - inventory: SessionTabsInventory, - context: RpcContext -): SessionTabsInventory { - return { - snapshots: inventory.snapshots.map((snapshot) => - projectSessionTabsForClient(snapshot, context.clientKind, context.clientCapabilities) - ), - ...(inventory.authoritative && clientUnderstandsAuthoritativeInventory(context) - ? { authoritative: true as const } - : {}) - } -} - -export async function listSessionTabsInventory(context: RpcContext): Promise { - return projectInventory((await collectSessionTabsInventory(context)).inventory, context) -} - export async function subscribeSessionTabsInventory( context: RpcContext, emit: (result: unknown) => void @@ -75,6 +28,7 @@ export async function subscribeSessionTabsInventory( } const cleanupPrefix = `session.tabs:${connectionId ?? 'local'}:*` const subscriptionId = requestId ? `${cleanupPrefix}:${requestId}` : cleanupPrefix + const observation = Symbol('session-tabs-stream') const inventoryController = new AbortController() // For the stream's whole life, not just the census: a desktop unsubscribe arrives as this abort. const onTransportAbort = (): void => runtime.cleanupSubscription(subscriptionId) @@ -163,7 +117,26 @@ export async function subscribeSessionTabsInventory( changeSequence }) } - const publishChange = (snapshot: SessionTabsChange, changeSequence: number): void => { + const emitChange = (projected: SessionTabsChange): void => { + if (closed) { + return + } + emit({ type: 'updated', ...tabDelta.update(withProofDelta(projected)) }) + if (!closed) { + runtime.observeClientHostedPageSnapshots?.( + [ + projected.removed ? { ...projected, clientHostedPagesUnreconciled: undefined } : projected + ], + pairedDeviceId, + observation + ) + } + } + const publishChange = ( + snapshot: SessionTabsChange, + changeSequence: number, + delivery?: 'reconciliation' + ): void => { const { navigationIntent: _intent, ...canonical } = snapshot if (snapshot.removed) { canonicalSnapshotsByWorktree.delete(snapshot.worktree) @@ -173,14 +146,18 @@ export async function subscribeSessionTabsInventory( const projected = projectChange(snapshot) const state = withoutNavigationIntent(projected) const published = publishedSnapshotsByWorktree.get(snapshot.worktree) - if (projected.navigationIntent === undefined && isDeepStrictEqual(published, state)) { + if ( + delivery !== 'reconciliation' && + projected.navigationIntent === undefined && + isDeepStrictEqual(published, state) + ) { deliveredChangeSequenceByWorktree.set(snapshot.worktree, changeSequence) return } - emit({ - type: 'updated', - ...tabDelta.update(withProofDelta(projected)) - }) + emitChange(projected) + if (closed) { + return + } if (projected.removed === true) { publishedSnapshotsByWorktree.delete(snapshot.worktree) deliveredChangeSequenceByWorktree.delete(snapshot.worktree) @@ -190,7 +167,10 @@ export async function subscribeSessionTabsInventory( } } const unsubscribe = runtime.onMobileSessionTabsChanged( - (runtimeSnapshot, changeSequence) => { + (runtimeSnapshot, changeSequence, delivery) => { + if (closed) { + return + } const snapshot = runtimeSnapshot as SessionTabsChange if (!initialized) { bufferChange(snapshot, changeSequence) @@ -202,10 +182,11 @@ export async function subscribeSessionTabsInventory( ) { return } - publishChange(snapshot, changeSequence) + publishChange(snapshot, changeSequence, delivery) }, pairedDeviceId, - context.clientKind + context.clientKind, + { observation: 'caller', acceptsWorktree: () => !closed } ) const stopCapabilities = context.capabilitySource?.observe(() => { if (!initialized || closed) { @@ -216,17 +197,24 @@ export async function subscribeSessionTabsInventory( if (isDeepStrictEqual(publishedSnapshotsByWorktree.get(snapshot.worktree), projected)) { continue } - emit({ type: 'updated', ...tabDelta.update(withProofDelta(projected)) }) + emitChange(projected) + if (closed) { + return + } publishedSnapshotsByWorktree.set(snapshot.worktree, projected) } }) runtime.registerSubscriptionCleanup( subscriptionId, () => { + if (closed) { + return + } closed = true context.signal?.removeEventListener('abort', onTransportAbort) inventoryController.abort() unsubscribe() + runtime.forgetClientHostedPageObservation?.(pairedDeviceId, observation) stopCapabilities?.() canonicalSnapshotsByWorktree.clear() clearBufferedChanges() @@ -278,15 +266,18 @@ export async function subscribeSessionTabsInventory( } const { inventory, changeSequence } = collected censusChangeSequence = changeSequence + const projectedSnapshots = inventory.snapshots.map(projectChange) emit({ type: 'snapshots', ...(inventory.authoritative && clientUnderstandsAuthoritativeInventory(context) ? { authoritative: true as const } : {}), - snapshots: inventory.snapshots.map((snapshot) => - tabDelta.full(withProofDelta(projectChange(snapshot))) - ) + snapshots: projectedSnapshots.map((snapshot) => tabDelta.full(withProofDelta(snapshot))) }) + if (closed) { + return + } + runtime.observeClientHostedPageSnapshots?.(projectedSnapshots, pairedDeviceId, observation) for (const snapshot of inventory.snapshots) { const canonical = withoutNavigationIntent(snapshot) canonicalSnapshotsByWorktree.set(snapshot.worktree, canonical) diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-retirement-proof-delta.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-retirement-proof-delta.ts index 192cbaf5d69..aa42520e124 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-retirement-proof-delta.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-retirement-proof-delta.ts @@ -2,7 +2,7 @@ import '../../../../../shared/protocol-version' import { SESSION_TABS_RETIREMENT_PROOF_DELTA_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities' import type { RuntimeCapability } from '../../../../../shared/protocol-version' import type { RuntimeMobileSessionRetiredTerminalSurface } from '../../../../../shared/runtime-session-contracts' -import { retirementProofKey as proofKey } from '../../../../../shared/workspace-layout/terminal-retirement-proof-ledger' +import { retirementProofKey as proofKey } from '../../../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' type ProofCarrier = { worktree: string diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-subscribe-admission.test.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-subscribe-admission.test.ts index f5cdadc69ab..8e33c108e6d 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-subscribe-admission.test.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-subscribe-admission.test.ts @@ -1,7 +1,7 @@ import { EVERY_AGENT_CHAT } from '../../../../../shared/native-chat/every-agent-chat.test-fixture' -import '../../runtime-client-capabilities' -import type { RuntimeClientCapabilities } from '../../runtime-client-capabilities' +import '../../callers/runtime-client-capabilities' +import type { RuntimeClientCapabilities } from '../../callers/runtime-client-capabilities' import { describe, expect, it, vi } from 'vitest' @@ -21,7 +21,6 @@ import { visibleSnapshot } from './session-tabs-snapshot.test-fixture' const CONNECTION = 'conn-1' const KEY = (requestId: string): string => `session.tabs:${CONNECTION}:wt-1:${requestId}` -const ALL_KEY = (requestId: string): string => `session.tabs:${CONNECTION}:*:${requestId}` type Deferred = { promise: Promise; resolve: (value: T) => void; reject: (e: Error) => void } @@ -108,39 +107,6 @@ async function settle(): Promise { } describe('session.tabs.subscribe registers when the request arrives', () => { - it.each([ - { stage: 'restore', unsubscribe: { worktree: 'id:wt-1', subscriptionId: 'sub-1' } }, - { stage: 'list', unsubscribe: { worktree: 'id:wt-1', subscriptionId: 'sub-1' } }, - { stage: 'list', unsubscribe: { worktree: 'id:wt-1' } } - ])( - 'an unsubscribe ($unsubscribe) during the $stage await ends the stream and leaves nothing', - async ({ stage, unsubscribe }) => { - const host = makeHost({ structuredChat: true }) - const gate = deferred() - const listing = deferred() - if (stage === 'restore') { - host.restore.mockReturnValueOnce(gate.promise) - } else { - host.listMobileSessionTabs.mockReturnValueOnce(listing.promise) - } - const messages: Frame[] = [] - const pending = host.dispatch( - request('sub-1', 'session.tabs.subscribe', { worktree: 'id:wt-1' }), - messages - ) - - await host.dispatch(request('unsub-1', 'session.tabs.unsubscribe', unsubscribe)) - gate.resolve() - listing.resolve(visibleSnapshot()) - await pending - await settle() - - expect(host.isRegistered(KEY('sub-1'))).toBe(false) - expect(host.runtime.onMobileSessionTabsChanged).not.toHaveBeenCalled() - expect(frames(messages)).toEqual(['end']) - } - ) - it('a socket close during setup leaves no registration and no listener', async () => { const host = makeHost() const listing = deferred() @@ -205,30 +171,6 @@ describe('session.tabs.subscribe registers when the request arrives', () => { expect(frames(messages)).toEqual(['end']) }) - it('streams snapshot and updates, then ends once on unsubscribe', async () => { - const host = makeHost() - const messages: Frame[] = [] - - await host.dispatch( - request('sub-1', 'session.tabs.subscribe', { worktree: 'id:wt-1' }), - messages - ) - expect(host.isRegistered(KEY('sub-1'))).toBe(true) - host.tabListeners[0]?.({ ...visibleSnapshot(), snapshotVersion: 2 }, 1) - await host.dispatch( - request('unsub-1', 'session.tabs.unsubscribe', { - worktree: 'id:wt-1', - subscriptionId: 'sub-1' - }) - ) - host.runtime.cleanupSubscriptionsForConnection(CONNECTION) - await settle() - - expect(frames(messages)).toEqual(['snapshot', 'updated', 'end']) - expect(host.stopListening).toHaveBeenCalledTimes(1) - expect(host.isRegistered(KEY('sub-1'))).toBe(false) - }) - it('a worktree-wide unsubscribe spares a subscribe that arrives while it resolves', async () => { const host = makeHost() const first: Frame[] = [] @@ -252,61 +194,4 @@ describe('session.tabs.subscribe registers when the request arrives', () => { expect(host.isRegistered(KEY('sub-1'))).toBe(false) expect(host.isRegistered(KEY('sub-2'))).toBe(true) }) - - it('a request-id unsubscribe ends only its own stream', async () => { - const host = makeHost() - const first: Frame[] = [] - const second: Frame[] = [] - - await host.dispatch(request('sub-1', 'session.tabs.subscribe', { worktree: 'id:wt-1' }), first) - await host.dispatch(request('sub-2', 'session.tabs.subscribe', { worktree: 'id:wt-1' }), second) - await host.dispatch( - request('unsub-1', 'session.tabs.unsubscribe', { - worktree: 'id:wt-1', - subscriptionId: 'sub-1' - }) - ) - await settle() - - expect(frames(first)).toEqual(['snapshot', 'end']) - expect(frames(second)).toEqual(['snapshot']) - expect(host.isRegistered(KEY('sub-1'))).toBe(false) - expect(host.isRegistered(KEY('sub-2'))).toBe(true) - expect(host.stopListening).toHaveBeenCalledTimes(1) - }) -}) - -describe('session.tabs.subscribeAll registers before restoring structured tabs', () => { - it.each([ - { - release: 'unsubscribeAll', - act: (host: ReturnType) => - host.dispatch( - request('unsub-1', 'session.tabs.unsubscribeAll', { subscriptionId: 'sub-1' }) - ) - }, - { - release: 'socket close', - act: async (host: ReturnType) => - host.runtime.cleanupSubscriptionsForConnection(CONNECTION) - } - ])('a $release during the restore leaves no stream behind', async ({ act }) => { - const host = makeHost({ structuredChat: true }) - const gate = deferred() - host.restore.mockReturnValueOnce(gate.promise) - const messages: Frame[] = [] - const pending = host.dispatch(request('sub-1', 'session.tabs.subscribeAll'), messages) - - await act(host) - gate.resolve() - await pending - await settle() - - expect(host.isRegistered(ALL_KEY('sub-1'))).toBe(false) - expect(frames(messages)).not.toContain('snapshots') - expect( - vi.mocked(host.runtime.onMobileSessionTabsChanged).mock.calls.length - - host.stopListening.mock.calls.length - ).toBe(0) - }) }) diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-tab-delta-stream.test.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-tab-delta-stream.test.ts index dd9476d1008..54cabd9027b 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-tab-delta-stream.test.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-tab-delta-stream.test.ts @@ -1,4 +1,4 @@ -import { RuntimeClientCapabilities } from '../../runtime-client-capabilities' +import { RuntimeClientCapabilities } from '../../callers/runtime-client-capabilities' import { RUNTIME_CLIENT_CAPABILITY_METHODS } from '../client-events/runtime-client-capabilities' import { visibleSnapshot } from './session-tabs-snapshot.test-fixture' import { describe, expect, it, vi } from 'vitest' @@ -61,8 +61,11 @@ describe.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'] as const)( } ] } + const observedFrames: RuntimeMobileSessionTabsResult[][] = [] // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these real RPC handlers reach only the runtime members stubbed here. const runtime = { + observeClientHostedPageSnapshots: (frames: RuntimeMobileSessionTabsResult[]) => + observedFrames.push(frames), getRuntimeId: () => 'runtime', getClientSettings: () => ({}), listMobileSessionTabs: async () => initial, @@ -145,9 +148,15 @@ describe.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'] as const)( // A capability the projection ignores sends no frame; the next real change still decodes. await update([...source.current, 'unrelated.test.v1']) expect(messages).toHaveLength(1) + expect(observedFrames).toHaveLength(2) await update(structured) expect(siblingMessages).toHaveLength(1) expect(messages).toHaveLength(2) + expect(observedFrames).toHaveLength(3) + expect(observedFrames.at(-1)?.[0]?.tabs[0]).toMatchObject({ + type: 'agent-session', + title: 'Claude chat' + }) const recovered = decode(messages[1]!) expect(JSON.stringify(recovered)).toContain('Claude chat') const proofState = { retiredTerminalSurfaces: delta ? [] : initial.retiredTerminalSurfaces } diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs-unsubscribe.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs-unsubscribe.ts index 6606dd5dcc8..abe71eb7a62 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs-unsubscribe.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs-unsubscribe.ts @@ -1,6 +1,6 @@ import { defineMethod } from '../../core' -import { SessionTabsUnsubscribe } from '../../../../../shared/rpc-contract/session-tabs-schemas-params' -import { SessionTabsUnsubscribeAllParams } from '../../../../../shared/rpc-contract/session-tabs-params' +import { SessionTabsUnsubscribe } from '../../../../../shared/rpc-contract/session-tabs/session-tabs-schemas-params' +import { SessionTabsUnsubscribeAllParams } from '../../../../../shared/rpc-contract/session-tabs/session-tabs-params' import { getExplicitWorktreeIdSelector } from '../../../workspaces/catalog/runtime-worktree-selection' import { worktreeIdentityKey } from '../../../../../shared/worktree/id' diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs/session-tabs.ts index 19bd962bec7..3505bf65c2f 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tabs.ts @@ -1,5 +1,5 @@ import { isDeepStrictEqual } from 'node:util' -import { terminalCreateFeatureRequirement } from '../../agent-launch-feature-requirement' +import { terminalCreateFeatureRequirement } from '../../startup/agent-launch-feature-requirement' import { terminalImageViewerSupported } from '../../../terminal/launch/terminal-image-viewer-env' import { resolveRuntimeNavigationTarget } from '../../../../../shared/runtime-navigation' import { getExplicitWorktreeIdSelector } from '../../../workspaces/catalog/runtime-worktree-selection' @@ -8,7 +8,7 @@ import { defineMethod, defineStreamingMethod } from '../../core' import { CreateTerminalTab, WorktreeTabSelector -} from '../../../../../shared/rpc-contract/session-tabs-schemas-params' +} from '../../../../../shared/rpc-contract/session-tabs/session-tabs-schemas-params' import { SESSION_TAB_CLOSE_METHODS } from './session-tab-close-methods' import { listSessionTabsInventory, @@ -19,7 +19,7 @@ import { SESSION_TAB_MARKDOWN_METHODS } from './session-tab-markdown-methods' import { SESSION_TAB_MUTATION_METHODS } from './session-tab-mutation-methods' import { createSessionTabsStreamDelta } from './session-tabs-sender-delta' import { prepareStructuredTabsIfSupported } from './structured-session-tab-restore' -import { assertLegacyAiVaultResumeCommandAllowed } from '../../../../ai-vault/structured-session-ownership' +import { assertLegacyAiVaultResumeCommandAllowed } from '../../../../ai-vault/structured-sessions/structured-session-ownership' import '../../../../../shared/protocol-version' import { SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities' import { createSessionTabsTabDeltaEncoder } from '../../../../../shared/session-tabs-tab-delta' @@ -36,7 +36,7 @@ export const SESSION_TAB_METHODS = [ params: WorktreeTabSelector, handler: async (params, { runtime, pairedDeviceId, clientKind, clientCapabilities }) => { await prepareStructuredTabsIfSupported({ runtime, clientKind, clientCapabilities }) - return projectSessionTabsForClient( + const result = projectSessionTabsForClient( await runtime.listMobileSessionTabs(params.worktree, pairedDeviceId, { includeInitialSurfaceLaunch: true, includeAgentSenders: clientKind !== 'mobile' @@ -44,6 +44,8 @@ export const SESSION_TAB_METHODS = [ clientKind, clientCapabilities ) + runtime.observeClientHostedPageSnapshots?.([result], pairedDeviceId) + return result } }), defineMethod({ @@ -129,6 +131,7 @@ export const SESSION_TAB_METHODS = [ }, emit ) => { + const observation = Symbol('session-tabs-stream') let subscriptionId: string | null = null let released = false let endOnRelease = true @@ -164,6 +167,7 @@ export const SESSION_TAB_METHODS = [ closePhoneSession?.() signal?.removeEventListener('abort', release) stopListening() + runtime.forgetClientHostedPageObservation?.(pairedDeviceId, observation) stopCapabilities() if (endOnRelease) { emit({ type: 'end' }) @@ -184,13 +188,30 @@ export const SESSION_TAB_METHODS = [ snapshot: NonNullable, capabilities = capabilitySource?.current ?? clientCapabilities ) => projectSessionTabsForClient(snapshot, clientKind, capabilities) + const emitSnapshot = ( + projected: NonNullable, + type: 'snapshot' | 'updated' + ): void => { + if (released) { + return + } + emit({ + type, + ...(type === 'snapshot' + ? tabDelta.full(withProofDelta(projected)) + : tabDelta.update(withProofDelta(projected))) + }) + if (!released) { + runtime.observeClientHostedPageSnapshots?.([projected], pairedDeviceId, observation) + } + } stopCapabilities = capabilitySource?.observe((previous) => { if (!released && currentSnapshot) { const projected = project(currentSnapshot) // The last frame was projected with the previous set; a change it ignores sends nothing. if (!isDeepStrictEqual(projected, project(currentSnapshot, previous))) { - emit({ type: 'updated', ...tabDelta.update(withProofDelta(projected)) }) + emitSnapshot(projected, 'updated') } } }) ?? (() => {}) @@ -223,45 +244,44 @@ export const SESSION_TAB_METHODS = [ } let subscribedWorktree = initial.worktree currentSnapshot = initial - emit({ - type: 'snapshot', - ...tabDelta.full(withProofDelta(project(initial))) - }) + emitSnapshot(project(initial), 'snapshot') if (released) { return } + const acceptsWorktree = (worktree: string): boolean => { + if (released) { + return false + } + if (worktree !== subscribedWorktree && worktreeIdsEqual(worktree, subscribedWorktree)) { + // Subscribe can precede publication of the host's stored spelling. + try { + subscribedWorktree = + runtime.getExplicitSessionWorktreeIdSelector(`id:${initial.worktree}`) ?? + subscribedWorktree + } catch { + // An ambiguous alias cannot authorize switching to either session. + return false + } + } + return worktree === subscribedWorktree + } stopListening = runtime.onMobileSessionTabsChanged( (snapshot) => { - if ( - snapshot.worktree !== subscribedWorktree && - worktreeIdsEqual(snapshot.worktree, subscribedWorktree) - ) { - // Subscribe can precede publication of the host's stored spelling. - try { - subscribedWorktree = - runtime.getExplicitSessionWorktreeIdSelector(`id:${initial.worktree}`) ?? - subscribedWorktree - } catch { - // An ambiguous alias cannot authorize switching to either session. - return - } - } - if (snapshot.worktree === subscribedWorktree) { - // Keep one stream spelling because clients index frames by worktree. - const streamSnapshot = - snapshot.worktree === initial.worktree - ? snapshot - : { ...snapshot, worktree: initial.worktree } - const { navigationIntent: _intent, ...retained } = streamSnapshot - currentSnapshot = retained - emit({ - type: 'updated', - ...tabDelta.update(withProofDelta(project(streamSnapshot))) - }) + if (released) { + return } + // Keep one stream spelling because clients index frames by worktree. + const streamSnapshot = + snapshot.worktree === initial.worktree + ? snapshot + : { ...snapshot, worktree: initial.worktree } + const { navigationIntent: _intent, ...retained } = streamSnapshot + currentSnapshot = retained + emitSnapshot(project(streamSnapshot), 'updated') }, pairedDeviceId, - clientKind + clientKind, + { observation: 'caller', acceptsWorktree } ) } catch (error) { // A stream already ended by its release must not also report an error. diff --git a/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts b/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts index 55884b0c8fa..451caddf0a8 100644 --- a/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts +++ b/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts @@ -22,7 +22,7 @@ import type { AgentSessionRecordStore } from '../../../agent-session/records/age import { openTestAgentSessionRecordStore } from '../../../agent-session/records/agent-session-record-store-test-harness' import { OrcaRuntimeService } from '../../../orca-runtime' import { RpcDispatcher } from '../../dispatcher' -import type { RpcDispatchStreamingOptions } from '../../dispatcher-stream-options' +import type { RpcDispatchStreamingOptions } from '../../dispatch/dispatcher-stream-options' import { SESSION_TAB_METHODS } from './session-tabs' import { STRUCTURED_AGENT_SESSION_METHODS } from '../structured-sessions/structured-agent-session' import { commitStructuredAgentSessionCreate } from '../structured-sessions/creation/structured-agent-session-create' diff --git a/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs-read.test.ts b/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs-read.test.ts deleted file mode 100644 index 5a4457fbd7d..00000000000 --- a/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs-read.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../../../shared/mobile-bridge-frame-bytes' -import { SIDEBAR_INPUTS_PAGE_MAX_BYTES } from '../../../../../shared/sidebar-list/sidebar-inputs-feed-contract' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { SidebarInputsFeed } from '../../../sidebar-inputs/sidebar-inputs-feed' -import { testDomain } from '../../../sidebar-inputs/sidebar-inputs-feed.test-fixture' -import type { RpcRequest } from '../../core' -import { RpcDispatcher } from '../../dispatcher' -import type { RpcDispatchStreamingOptions } from '../../dispatcher-stream-options' -import { SIDEBAR_INPUT_METHODS } from './sidebar-inputs' - -function makeHost() { - // Rows far larger than one page, so the first reply is a full page. - const rows = testDomain( - 'rows', - Object.fromEntries( - Array.from({ length: 3_000 }, (_, index) => [`row-${index}`, 'r'.padEnd(300, '中')]) - ) - ) - const feed = new SidebarInputsFeed( - () => [rows.domain], - () => {} - ) - const cleanups = new Map void>() - const fake = { - getRuntimeId: () => 'test-runtime', - sidebarInputsFeed: feed, - registerSubscriptionCleanup: (id: string, cleanup: () => void) => cleanups.set(id, cleanup) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: sidebarInputs.read reads only the members above. - const runtime = fake as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SIDEBAR_INPUT_METHODS }) - let requestId = 0 - const read = (context: RpcDispatchStreamingOptions) => { - const request: RpcRequest = { - id: `req-${++requestId}`, - authToken: 'tok', - method: 'sidebarInputs.read', - params: { maxBytes: SIDEBAR_INPUTS_PAGE_MAX_BYTES } - } - return dispatcher.dispatch(request, context) - } - return { rows, read, cleanups } -} - -describe('sidebarInputs.read', () => { - it('serves the host’s own phone a page that fits its bridge frame with the RPC envelope', async () => { - const host = makeHost() - const response = await host.read({ clientKind: 'mobile', connectionId: 'conn-1' }) - expect(response).toMatchObject({ - ok: true, - result: { kind: 'snapshot', next: expect.any(String) } - }) - const frame = Buffer.byteLength(JSON.stringify(response), 'utf8') - expect(frame).toBeGreaterThan(SIDEBAR_INPUTS_PAGE_MAX_BYTES * 0.9) - expect(frame).toBeLessThanOrEqual(MOBILE_BRIDGE_MAX_FRAME_BYTES) - }) - - it('refuses a delegated phone, a paired desktop and a caller without a connection', async () => { - const host = makeHost() - for (const context of [ - { clientKind: 'mobile', connectionId: 'conn-1', pairedDeviceParentId: 'desktop-device' }, - { clientKind: 'runtime', connectionId: 'conn-1' }, - { - clientKind: 'runtime', - connectionId: 'conn-1', - caller: { kind: 'paired-device', deviceId: 'desktop-device' } - }, - { clientKind: 'mobile' } - ] satisfies RpcDispatchStreamingOptions[]) { - expect(await host.read(context)).toMatchObject({ ok: false, error: { code: 'forbidden' } }) - } - expect(host.rows.reads()).toBe(0) - }) - - it('subscribes a connection on its first read and releases it when the connection closes', async () => { - const host = makeHost() - await host.read({ clientKind: 'mobile', connectionId: 'conn-1' }) - await host.read({ clientKind: 'mobile', connectionId: 'conn-1' }) - expect([...host.cleanups.keys()]).toEqual(['sidebar-inputs-feed-conn-1']) - expect(host.rows.watchers()).toBe(1) - host.cleanups.get('sidebar-inputs-feed-conn-1')?.() - expect(host.rows.watchers()).toBe(0) - }) -}) diff --git a/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs.ts b/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs.ts index cedc091af65..d7692fe1e51 100644 --- a/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs.ts +++ b/src/main/runtime/rpc/methods/sidebar-inputs/sidebar-inputs.ts @@ -1,13 +1,13 @@ import { defineMethod } from '../../core' -import { requireSwitchedOn } from '../../../sidebar-inputs/require-switched-on' +import { requireSwitchedOn } from '../../../construction/require-sidebar-inputs-enabled' import { readRuntimeDesktopSidebarFacts } from '../../../sidebar-inputs/sidebar-inputs-feed-domains' -import { isHostOwnPhone } from '../../host-own-phone' +import { isHostOwnPhone } from '../../callers/host-own-phone' import { SidebarInputsReadParams } from '../../../../../shared/sidebar-list/sidebar-inputs-feed-contract' -import { SidebarSessionBeginParams } from '../../../../../shared/rpc-contract/sidebar-session-params' +import { SidebarSessionBeginParams } from '../../../../../shared/rpc-contract/client-ui/sidebar-session-params' import { RepoIconDataUrlsParams } from '../../../../../shared/sidebar-list/repo-icon-data-urls-contract' -import { SetCollapsedParams } from '../../../../../shared/rpc-contract/workspace-view-collapse-params' -import { setCollapsedSection } from '../../../sidebar-inputs/workspace-view-collapse-writes' -import { ClientWorkspaceViewParams } from '../../../../../shared/rpc-contract/client-workspace-view-params' +import { SetCollapsedParams } from '../../../../../shared/rpc-contract/workspaces/workspace-view-collapse-params' +import { setCollapsedSection } from '../../../client/settings/workspace-view-collapse-writes' +import { ClientWorkspaceViewParams } from '../../../../../shared/rpc-contract/client-ui/client-workspace-view-params' // Registered only with ORCA_SIDEBAR_INPUTS=main, so the producers below always exist. diff --git a/src/main/runtime/rpc/methods/skills/skills.ts b/src/main/runtime/rpc/methods/skills/skills.ts index ffef4096075..a6f1348691e 100644 --- a/src/main/runtime/rpc/methods/skills/skills.ts +++ b/src/main/runtime/rpc/methods/skills/skills.ts @@ -43,7 +43,7 @@ import { SkillsCancelInstallParams, SkillsDiscoverParams, SkillsGetInstallProgressParams -} from '../../../../../shared/rpc-contract/skills-params' +} from '../../../../../shared/rpc-contract/skills/skills-params' import { unavailableWhileWslDistroStopped } from '../../../../skills/discovery/skill-discovery-stopped-wsl-roots' import { runAsWslUserAct, wslDistroForPath } from '../../../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/runtime/rpc/methods/source-control/git/git-branch-methods.ts b/src/main/runtime/rpc/methods/source-control/git/git-branch-methods.ts index 0da82cde707..fa1549034db 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git-branch-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git-branch-methods.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../../core' -import { GitSwitchBranch } from '../../../../../../shared/rpc-contract/git-params' +import { GitSwitchBranch } from '../../../../../../shared/rpc-contract/source-control/git-params' export const GIT_BRANCH_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/git/git-commit-action-methods.ts b/src/main/runtime/rpc/methods/source-control/git/git-commit-action-methods.ts index f06916939ba..434e5379fd0 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git-commit-action-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git-commit-action-methods.ts @@ -3,7 +3,7 @@ import { GitCommitAction, GitSequencer, GitCreateBranch -} from '../../../../../../shared/rpc-contract/git-params' +} from '../../../../../../shared/rpc-contract/source-control/git-params' export const GIT_COMMIT_ACTION_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/git/git-commit-message-generation-methods.ts b/src/main/runtime/rpc/methods/source-control/git/git-commit-message-generation-methods.ts index 18204394a50..06c133ab602 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git-commit-message-generation-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git-commit-message-generation-methods.ts @@ -6,7 +6,7 @@ import { GitGenerateCommitMessage, GitGeneratePullRequestFields, WorktreeSelector -} from '../../../../../../shared/rpc-contract/git-params' +} from '../../../../../../shared/rpc-contract/source-control/git-params' type CommitMessageGenerationOverride = { commitMessageAi?: GlobalSettings['commitMessageAi'] diff --git a/src/main/runtime/rpc/methods/source-control/git/git-conflict-projection.test.ts b/src/main/runtime/rpc/methods/source-control/git/git-conflict-projection.test.ts index 14e1c08771a..ba74634fb7f 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git-conflict-projection.test.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git-conflict-projection.test.ts @@ -1,6 +1,6 @@ import { BranchSwitchLandedWithWarningError } from '../../../../../git/worktrees/checkout/branch-switch' -import { mapDispatcherError } from '../../../dispatcher-error-response' -import '../../../unused-default-rpc-methods.test-fixture' +import { mapDispatcherError } from '../../../responses/dispatcher-error-response' +import '../../../dispatch/testing/unused-default-rpc-methods.test-fixture' import { describe, expect, it } from 'vitest' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { RpcDispatcher } from '../../../dispatcher' diff --git a/src/main/runtime/rpc/methods/source-control/git/git-diff-methods.ts b/src/main/runtime/rpc/methods/source-control/git/git-diff-methods.ts index 771c3a47001..edac888c17b 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git-diff-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git-diff-methods.ts @@ -4,7 +4,7 @@ import { GitBranchDiff, GitCommitDiff, GitDiff -} from '../../../../../../shared/rpc-contract/git-params' +} from '../../../../../../shared/rpc-contract/source-control/git-params' // Only WebSocket callers set clientKind; local/in-process diffs retain uncapped fidelity. function remoteDiffContentBudget( diff --git a/src/main/runtime/rpc/methods/source-control/git/git-status-methods.ts b/src/main/runtime/rpc/methods/source-control/git/git-status-methods.ts index d1bd1df21d6..05cf5d744a3 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git-status-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git-status-methods.ts @@ -4,7 +4,7 @@ import { GitStatusParams, GitSubmoduleStatus, WorktreeSelector -} from '../../../../../../shared/rpc-contract/git-params' +} from '../../../../../../shared/rpc-contract/source-control/git-params' import { defineMethod } from '../../../core' function projectConflictOperation( @@ -73,6 +73,13 @@ export const GIT_STATUS_METHODS = [ } } }), + defineMethod({ + name: 'git.atRiskLocalFiles', + permission: 'workspace', + params: WorktreeSelector, + handler: async (params, { runtime, signal }) => + runtime.readRuntimeWorktreeAtRiskLocalFiles(params.worktree, signal) + }), defineMethod({ name: 'git.conflictOperation', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/source-control/git/git.ts b/src/main/runtime/rpc/methods/source-control/git/git.ts index 765985dec8b..ec66085271e 100644 --- a/src/main/runtime/rpc/methods/source-control/git/git.ts +++ b/src/main/runtime/rpc/methods/source-control/git/git.ts @@ -23,7 +23,7 @@ import { GitRemoteFileUrl, GitTargetedRemote, WorktreeSelector -} from '../../../../../../shared/rpc-contract/git-params' +} from '../../../../../../shared/rpc-contract/source-control/git-params' export const GIT_METHODS = [ ...GIT_STATUS_METHODS, diff --git a/src/main/runtime/rpc/methods/source-control/github/github-account-binding-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-account-binding-methods.ts index 29295bade45..a6e33d618a4 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-account-binding-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-account-binding-methods.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../../core' import { BindableAccounts, ValidateAccountBinding -} from '../../../../../../shared/rpc-contract/github-account-binding-params' +} from '../../../../../../shared/rpc-contract/github/github-account-binding-params' export const GITHUB_ACCOUNT_BINDING_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/github/github-issue-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-issue-methods.ts index 421e643d0a6..6bf3eb3fd17 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-issue-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-issue-methods.ts @@ -1,12 +1,12 @@ import { defineMethod } from '../../../core' -import { UploadGitHubAttachment } from '../../../../../../shared/rpc-contract/github-attachment-params' +import { UploadGitHubAttachment } from '../../../../../../shared/rpc-contract/github/github-attachment-params' import { claimClipboardImageUpload } from '../../clipboard/clipboard' import { CreateIssue, Issue, IssueComment, UpdateIssue -} from '../../../../../../shared/rpc-contract/github-issue-params' +} from '../../../../../../shared/rpc-contract/github/github-issue-params' export const GITHUB_ISSUE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/github/github-project-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-project-methods.ts index f886c82220c..0e0a6b1e58b 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-project-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-project-methods.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../../core' -import { SlugRepo } from '../../../../../../shared/rpc-contract/github-repo-target-params' +import { SlugRepo } from '../../../../../../shared/rpc-contract/github/github-repo-target-params' import { ClearProjectItemField, GithubProjectListAccessibleParams, @@ -15,7 +15,7 @@ import { SlugIssueTypeUpdate, SlugIssueUpdate, SlugPullRequestUpdate -} from '../../../../../../shared/rpc-contract/github-project-params' +} from '../../../../../../shared/rpc-contract/github/github-project-params' export const GITHUB_PROJECT_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts index 55191be8241..0c2c03dbfa0 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts @@ -9,7 +9,7 @@ import { PullRequestFileViewed, RerunPullRequestChecks, ReviewThread -} from '../../../../../../shared/rpc-contract/github-pull-request-params' +} from '../../../../../../shared/rpc-contract/github/github-pull-request-params' export const GITHUB_PULL_REQUEST_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-update-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-update-methods.ts index 46daf745355..f8b0d4b9325 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-update-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-update-methods.ts @@ -11,7 +11,7 @@ import { UpdatePr, UpdatePrState, UpdatePrTitle -} from '../../../../../../shared/rpc-contract/github-pull-request-update-params' +} from '../../../../../../shared/rpc-contract/github/github-pull-request-update-params' export const GITHUB_PULL_REQUEST_UPDATE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/github/github-repo-work-item-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-repo-work-item-methods.ts index ae60fba889b..5ba968d4f7b 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-repo-work-item-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-repo-work-item-methods.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../../core' import { RepoSelector, RepoWithGitHubAccountExpectation -} from '../../../../../../shared/rpc-contract/github-repo-target-params' +} from '../../../../../../shared/rpc-contract/github/github-repo-target-params' import { IssuesList, RateLimit, @@ -11,7 +11,7 @@ import { WorkItemDetails, WorkItemsCount, WorkItemsList -} from '../../../../../../shared/rpc-contract/github-repo-work-item-params' +} from '../../../../../../shared/rpc-contract/github/github-repo-work-item-params' export const GITHUB_REPO_WORK_ITEM_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/gitlab/gitlab.ts b/src/main/runtime/rpc/methods/source-control/gitlab/gitlab.ts index 7bfe71d8aa8..23eff18713f 100644 --- a/src/main/runtime/rpc/methods/source-control/gitlab/gitlab.ts +++ b/src/main/runtime/rpc/methods/source-control/gitlab/gitlab.ts @@ -22,7 +22,7 @@ import { WorkItemByPath, WorkItemDetails, WorkItemsList -} from '../../../../../../shared/rpc-contract/gitlab-params' +} from '../../../../../../shared/rpc-contract/source-control/gitlab-params' export const GITLAB_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/source-control/reviews/hosted-review.ts b/src/main/runtime/rpc/methods/source-control/reviews/hosted-review.ts index ab3bcff86ec..7e84c631821 100644 --- a/src/main/runtime/rpc/methods/source-control/reviews/hosted-review.ts +++ b/src/main/runtime/rpc/methods/source-control/reviews/hosted-review.ts @@ -5,7 +5,7 @@ import { HostedReviewCreate, HostedReviewCreationEligibility, HostedReviewForBranch -} from '../../../../../../shared/rpc-contract/hosted-review-params' +} from '../../../../../../shared/rpc-contract/source-control/hosted-review-params' export const HOSTED_REVIEW_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/speech/speech.ts b/src/main/runtime/rpc/methods/speech/speech.ts index 3d4154c1258..7bd238248ab 100644 --- a/src/main/runtime/rpc/methods/speech/speech.ts +++ b/src/main/runtime/rpc/methods/speech/speech.ts @@ -7,7 +7,7 @@ import { OpenAiSpeechKeySet, SpeechModelAction, SpeechSetupRead -} from '../../../../../shared/rpc-contract/speech-params' +} from '../../../../../shared/rpc-contract/speech/speech-params' export const SPEECH_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts b/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts index 8156d14a0dd..49f7020ef75 100644 --- a/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts +++ b/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../../dispatcher' import type { RpcRequest } from '../../core' -import type { RpcCallerScope } from '../../rpc-caller-scope' +import type { RpcCallerScope } from '../../callers/rpc-caller-scope' import { OrcaRuntimeService } from '../../../orca-runtime' import { SSH_EDITABLE_TARGET_FIELDS } from '../../../../../shared/ssh-target-management' import { SSH_METHODS } from './ssh' diff --git a/src/main/runtime/rpc/methods/ssh/ssh.ts b/src/main/runtime/rpc/methods/ssh/ssh.ts index 3e375c15f20..7994ff6c81e 100644 --- a/src/main/runtime/rpc/methods/ssh/ssh.ts +++ b/src/main/runtime/rpc/methods/ssh/ssh.ts @@ -30,7 +30,7 @@ import { SshTarget, SshTargetAdd, SshTargetUpdate -} from '../../../../../shared/rpc-contract/ssh-params' +} from '../../../../../shared/rpc-contract/ssh/ssh-params' // Keep generation optional so older server rows still key by target id. function toSshTargetSummary( diff --git a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.ts b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.ts index 6921708ee00..90ba818387f 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.ts @@ -12,7 +12,7 @@ import { AttachmentUploadAppendParams, AttachmentUploadIdParams, AttachmentUploadStartParams -} from '../../../../../../shared/rpc-contract/agent-session-attachment-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/agent-session-attachment-params' import { remoteFileContentBudget } from '../../files/files-remote-content-budget' import type { AgentSessionAttachmentStore } from '../../../../../native-chat/agent-session-attachments/agent-session-attachment-store' import { getAgentSessionAttachmentStore } from '../../../../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' diff --git a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.test.ts b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.test.ts index bdc668fa950..af7cee4d511 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.test.ts @@ -9,8 +9,8 @@ import { agentSessionRecordFixture } from '../../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' import { setStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { nativeChatScratchFolderFor } from '../../../../../native-chat/native-chat-scratch-folder' -import { nativeChatVisualRevision } from '../../../../../native-chat/native-chat-visual-file-read' +import { nativeChatScratchFolderFor } from '../../../../../native-chat/conversation-files/native-chat-scratch-folder' +import { nativeChatVisualRevision } from '../../../../../native-chat/conversation-files/native-chat-visual-file-read' import { Store } from '../../../../../persistence/loading-store/store' import { closeTestStores, diff --git a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.ts b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.ts index b84641bf277..332225cc9a8 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-visual.ts @@ -5,10 +5,10 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host import { ReadVisualParams, type AgentSessionReadVisualResult -} from '../../../../../../shared/rpc-contract/agent-session-visual-params' -import { nativeChatScratchFolderFor } from '../../../../../native-chat/native-chat-scratch-folder' +} from '../../../../../../shared/rpc-contract/structured-agent-session/agent-session-visual-params' +import { nativeChatScratchFolderFor } from '../../../../../native-chat/conversation-files/native-chat-scratch-folder' import { getProfileUserDataPath } from '../../../../../orca-profiles/profile-storage-paths' -import { readNativeChatVisualFile } from '../../../../../native-chat/native-chat-visual-file-read' +import { readNativeChatVisualFile } from '../../../../../native-chat/conversation-files/native-chat-visual-file-read' import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' diff --git a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-account-usage.ts b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-account-usage.ts index 99b37094639..07dcab44df3 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-account-usage.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-account-usage.ts @@ -9,7 +9,7 @@ import type { RateLimitState } from '../../../../../../shared/rate-limit-types' import { normalizeRuntimePathForComparison } from '../../../../../../shared/cross-platform-path' import { buildCodexResetCreditExpectedScope } from '../../../../../../shared/codex-reset-credit-scope' import { getSystemCodexHomePath } from '../../../../../codex/configuration/homes/codex-home-paths' -import { getSelectedCodexAccountIdForTarget } from '../../../../../codex-accounts/runtime-selection' +import { getSelectedCodexAccountIdForTarget } from '../../../../../codex-accounts/account-management/runtime-selection' import { isCodexMethodNotFoundError, isCodexAppServerUnsupportedError @@ -17,10 +17,10 @@ import { import { CodexUsageApiKeyAuthError } from '../../../../../rate-limits/providers/codex/codex-rpc-rate-limit-mapper' import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' -import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export function sessionAccountUsageOffer( record: AgentSessionRecord, diff --git a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-agents.ts b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-agents.ts index 34b3c50e454..697457398f1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-agents.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-agents.ts @@ -15,10 +15,10 @@ import { requireStructuredCapability } from '../creation/structured-agent-sessio import { AgentsParams, AvailabilityParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { clientReadsStructuredSessionAgent } from '../structured-agent-session-policy' import { bindStructuredAgentSessionStream } from '../subscriptions/structured-agent-session-status-stream' import { structuredAgentSessionAvailabilitySubscriptionId } from '../subscriptions/structured-agent-session-subscription-id' diff --git a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts index 797d930cf09..df3412bce8d 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts @@ -14,11 +14,11 @@ import { HandoffStatusParams, ModelCatalogParams, OptionsParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' -import { ContinuationContextParams } from '../../../../../../shared/rpc-contract/structured-agent-session-identifiers' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' +import { ContinuationContextParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-identifiers' import { agentSessionPinnedLaunchDirectory } from '../../../../agent-session/records/agent-session-record-launch-directory' import { clientRequestsCommands, diff --git a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-usage-limit-continue.ts b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-usage-limit-continue.ts index dcff2f6bf21..fabe4f7cf8c 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-usage-limit-continue.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-usage-limit-continue.ts @@ -1,4 +1,4 @@ -import { CancelUsageLimitContinueParams } from '../../../../../../shared/rpc-contract/usage-limit-continue-params' +import { CancelUsageLimitContinueParams } from '../../../../../../shared/rpc-contract/structured-agent-session/usage-limit-continue-params' import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts index 8bc23998ebd..71a18eea34f 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts @@ -1,8 +1,8 @@ import { defineMethod } from '../../../core' -import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { requireStructuredCapability, requireStructuredCleanupHost diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-conversation-command.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-conversation-command.ts index 0d6edf827d0..605ebc9a7e5 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-conversation-command.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-conversation-command.ts @@ -1,5 +1,5 @@ import type { z } from 'zod' -import type { ConversationCommandParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' +import type { ConversationCommandParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' import { recordMobileChatSend } from '../../../../../telemetry/mobile-client-telemetry' import type { RpcContext } from '../../../core' import { diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-current-requests.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-current-requests.ts index 1849689bc32..c545db5a380 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-current-requests.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-current-requests.ts @@ -1,6 +1,6 @@ import { defineMethod, type RpcContext } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' -import { CurrentRequestsParams } from '../../../../../../shared/rpc-contract/agent-session-current-requests-params' +import { CurrentRequestsParams } from '../../../../../../shared/rpc-contract/structured-agent-session/agent-session-current-requests-params' import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../../../../../../shared/agent-session/requests/agent-session-current-requests-capability' import { agentSessionRefusalError } from '../../../../../../shared/agent-session/failures/agent-session-wire-refusals' diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-hold.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-hold.ts index d94d9a0c5e9..53e541ab803 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-hold.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-hold.ts @@ -7,10 +7,10 @@ import { requireInstalledStructuredHost, requireStructuredCleanupHost } from '../creation/structured-agent-session-gate' -import { HoldParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { HoldParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export const STRUCTURED_AGENT_SESSION_HOLD_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-prompt-response.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-prompt-response.ts index 1663c09fd0b..05a515c2dab 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-prompt-response.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-prompt-response.ts @@ -7,11 +7,11 @@ import { import { RespondParams, SetOptionParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' -import { RespondToQuestionParams } from '../../../../../../shared/rpc-contract/structured-agent-session-question-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' +import { RespondToQuestionParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-question-params' export const STRUCTURED_AGENT_SESSION_PROMPT_RESPONSE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-queued-methods.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-queued-methods.ts index fce56f866c5..c4f257fe004 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-queued-methods.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-queued-methods.ts @@ -9,14 +9,14 @@ import { import { QueuedMessageActionParams, QueuedMessagesResumeParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' import { QueuedMessageMoveParams, QueuedMessageUpdateParams, QueuedMessageEditHoldParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { readsQueuedImageCards } from '../attachments/structured-agent-session-queued-image-capability' export const STRUCTURED_AGENT_SESSION_QUEUED_METHODS = [ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-regenerate-name.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-regenerate-name.ts index 088c300372d..caca3ddf665 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-regenerate-name.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-regenerate-name.ts @@ -2,10 +2,10 @@ import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' -import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export const STRUCTURED_AGENT_SESSION_REGENERATE_NAME_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-rename.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-rename.ts index 5718a73c478..8e41f3797cf 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-rename.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-rename.ts @@ -3,10 +3,10 @@ import { defineMethod } from '../../../core' import { requireRenameStructuredHost } from '../creation/structured-agent-session-gate' -import '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import { RenameParams } from '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import { RenameParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export const STRUCTURED_AGENT_SESSION_RENAME_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-restart-resume.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-restart-resume.ts index 124f9a039c4..0ba05b156a1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-restart-resume.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-restart-resume.ts @@ -11,10 +11,10 @@ import { import { RestartResumableParams, RestartResumeParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import { ContinueInterruptedParams } from '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import { ContinueInterruptedParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { structuredAgentsReadBy } from '../structured-agent-session-policy' export const STRUCTURED_AGENT_SESSION_RESTART_RESUME_METHODS = [ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts index 2c99604dfea..0cfd5c4914a 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts @@ -23,10 +23,10 @@ import { structuredSessionSurfaceIsCurrent, type StructuredSessionSurface } from '../../../../agent-session/structured-agent-session-close' -import { RevealParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { RevealParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export const STRUCTURED_AGENT_SESSION_REVEAL_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-thread-goal.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-thread-goal.ts index 3cb7dbc35d0..7d527bf1a1d 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-thread-goal.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-thread-goal.ts @@ -5,10 +5,10 @@ import { requireStructuredSessionHost as requireSessionHost, structuredCallerFor as callerFor } from '../creation/structured-agent-session-gate' -import { ThreadGoalParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { ThreadGoalParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export const STRUCTURED_AGENT_SESSION_THREAD_GOAL_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-adoption-replay.test.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-adoption-replay.test.ts deleted file mode 100644 index 28de6665313..00000000000 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-adoption-replay.test.ts +++ /dev/null @@ -1,511 +0,0 @@ -import type { AgentProcessVerdict } from '../../../../../../shared/agent-status/process/agent-process-presence' -import { AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-create-capabilities' -import { appendFile, mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import type { AgentStatusIpcPayload } from '../../../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { - STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, - STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY -} from '../../../../../../shared/agent-session/agent-session-runtime-capabilities' -import { readAgentSessionRefusalReference } from '../../../../../../shared/agent-session/failures/agent-session-wire-refusals' -import { readAgentSessionErrorRefusal } from '../../../../../../shared/agent-session/failures/agent-session-write-failure' -import { openTestAgentSessionRecordStore } from '../../../../agent-session/records/agent-session-record-store-test-harness' -import type { StructuredAgentSessionAdapter } from '../../../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { StructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { setStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import { registerBoundPty } from '../../../../orca-runtime-tests/bind-first-pane.test-fixture' -import type { RpcRequest, RpcResponse } from '../../../core' -import type { RpcDispatchStreamingOptions } from '../../../dispatcher-stream-options' -import { RpcDispatcher } from '../../../dispatcher' -import { STRUCTURED_AGENT_SESSION_METHODS } from '../structured-agent-session' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../../../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createStructuredAgentSessionLogger } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { codexProviderHandle } from '../../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { claudeAndCodexAgents } from '../../../../../native-chat/agent-session-wire/providers/testing/structured-agent-session-adapter-router-test-support' -import { prepareStructuredAgentSessionCreateForWorktree } from './structured-agent-session-create' - -const SESSION = 'session-adoption-replay' -const THREAD = 'thread-adoption-replay' -const WORKSPACE = 'workspace-1' -const SOURCE_LEAF = '11111111-1111-4111-8111-111111111111' -const SOURCE_PANE = `tab-source:${SOURCE_LEAF}` -const OPERATION = `${Date.now()}-00000000000000000000000000000001` -const CLIENT = { - clientId: 'device-a', - clientKind: 'runtime' as const, - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY] -} - -let root: string -let host: StructuredAgentSessionHost - -// The source terminal is a shell with nothing left running in it. -vi.mock('../../../../../../shared/process-table-snapshot-reader', async (importOriginal) => ({ - ...(await importOriginal()), - getFreshShellForegroundSnapshot: async () => [ - { pid: 10, ppid: 1, stat: 'Ss+', command: '/bin/zsh' } - ] -})) - -function adapter(): StructuredAgentSessionAdapter { - return { - supportsCreate: () => true, - open: async () => ({ - reportedOptions: { model: '' } - }), - acquire: vi - .fn() - .mockImplementation(async ({ fence, spawnToken }) => ({ - acquisitionGeneration: globalThis.crypto.randomUUID(), - process: { - hostId: 'local', - pid: 4242, - processStartTimeMs: 1_800_000_000_000, - spawnToken - }, - link: { - linkId: `codex-${fence}-${THREAD}`, - handle: codexProviderHandle(THREAD), - origin: 'resumed', - mintedAtFence: fence, - observedAt: 1_800_000_000_000 - } - })), - releaseAcquisition: vi.fn(async () => true), - dispatch: vi.fn(), - cancelTurn: vi.fn(), - answerPrompt: vi.fn(), - setOption: vi.fn() - } -} - -function createParams(operationId = OPERATION, sessionId = SESSION) { - const fields = { - worktree: `id:${WORKSPACE}`, - agent: 'codex' as const, - resumeFrom: { - providerSessionId: THREAD, - cliSource: { workspaceId: WORKSPACE, paneKey: SOURCE_PANE } - } - } - return { - envelope: { - sessionId, - clientOperationId: operationId, - expectedRuntimeFence: null, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.create', - sessionId, - fields - }) - }, - ...fields - } -} - -async function call( - dispatcher: RpcDispatcher, - params: unknown, - client: RpcDispatchStreamingOptions = CLIENT, - unary = false -) { - const replies: RpcResponse[] = [] - const request: RpcRequest = { - id: `request-${replies.length + 1}`, - authToken: 'token', - method: 'agentSession.create', - params - } - if (unary) { - return dispatcher.dispatch(request, client) - } - await dispatcher.dispatchStreaming( - request, - (raw) => replies.push(JSON.parse(raw) as RpcResponse), - client - ) - return replies[0] -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-adoption-rpc-replay-')) - // Why: the adopting create pre-trusts its folder in ~/.codex and Orca's managed Codex home. - vi.stubEnv('HOME', join(root, 'home')) - vi.stubEnv('USERPROFILE', join(root, 'home')) - vi.stubEnv('ORCA_USER_DATA_PATH', join(root, 'user-data')) -}) - -afterEach(async () => { - setStructuredAgentSessionHost(null) - await host?.flushAllStreamedEvents() - await host?.close(SESSION, 'evict') - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -describe('committed adopting create RPC replay', () => { - it.each([ - [true, false], - [false, false], - [true, true] - ] as const)('captures source before routing (unary=%s, absent=%s)', async (unary, absent) => { - const originalHome = join(root, 'account-original') - const driftedHome = join(root, 'account-drifted') - const transcriptPath = join( - originalHome, - 'sessions', - '2026', - '09', - '06', - `rollout-2026-09-06T18-00-00-${THREAD}.jsonl` - ) - await mkdir(dirname(transcriptPath), { recursive: true }) - await writeFile( - transcriptPath, - `${JSON.stringify({ - type: 'session_meta', - payload: { id: THREAD, timestamp: '2026-09-06T18:00:00.000Z', cwd: '/workspace' } - })}\n${JSON.stringify({ - type: 'response_item', - timestamp: '2026-09-06T18:00:01.000Z', - payload: { type: 'message', role: 'user', content: 'durable adopted history' } - })}\n`, - 'utf8' - ) - if (absent) { - await appendFile( - transcriptPath, - `${JSON.stringify({ - type: 'response_item', - timestamp: '2026-09-06T18:10:01.000Z', - payload: { type: 'message', role: 'assistant', content: 'late adopted history' } - })}\n` - ) - } - - let selectedHome = originalHome - const selectAccountHome = vi.fn(() => selectedHome) - let writerVerdict: AgentProcessVerdict = 'live' - const runtime = new OrcaRuntimeService( - { - getSettings: () => ({ - agentDefaultEnv: { codex: {} } - }) - } as never, - undefined, - { - prepareCodexStructuredLaunch: selectAccountHome, - readHookCliWriterObservation: () => ({ - current: () => true, - topology: 'pane-owned', - presence: async () => writerVerdict - }) - } - ) - const sourceRow = { - paneKey: SOURCE_PANE, - worktreeId: WORKSPACE, - agentType: 'codex', - connectionId: null, - receivedAt: 1, - stateStartedAt: 1, - state: 'waiting' as const, - prompt: '', - providerSession: { key: 'session_id' as const, id: THREAD, transcriptPath } - } - let rows: AgentStatusIpcPayload[] = [sourceRow] - registerBoundPty(runtime, 'source-pty', WORKSPACE, null, { - tabId: 'tab-source', - leafId: SOURCE_LEAF, - incarnationId: 'i1' - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the source census reads only listProcesses. - runtime.setPtyController({ - listProcesses: async () => [{ id: 'source-pty', rootProcessId: 10, incarnationId: 'i1' }] - } as never) - const sourceRows = vi - .spyOn(runtime, 'getAgentProviderSessionRows') - .mockImplementation(() => rows) - const sourceRoute = vi.spyOn(runtime, 'getStructuredAgentCliSourceRoute') - vi.spyOn(runtime, 'getStructuredAgentSessionCreateSupport').mockResolvedValue({ - supported: true - }) - const internal = runtime as unknown as { - resolveStructuredAgentSessionLocation: () => Promise<{ - executionHostId: 'local' - wslDistro: null - workspaceId: string - workspaceKind: 'git-worktree' - }> - resolveRuntimeFileTarget: () => Promise<{ worktree: { path: string } }> - ensureStructuredAgentSessionHost: () => Promise - publishStructuredAgentSessionTab: () => Promise - } - internal.resolveStructuredAgentSessionLocation = vi.fn(async () => ({ - executionHostId: 'local' as const, - wslDistro: null, - workspaceId: WORKSPACE, - workspaceKind: 'git-worktree' as const - })) - internal.resolveRuntimeFileTarget = vi.fn(async () => ({ - worktree: { path: '/repos/workspace-1' } - })) - internal.ensureStructuredAgentSessionHost = vi.fn(async () => undefined) - internal.publishStructuredAgentSessionTab = vi - .fn<() => Promise>() - .mockRejectedValueOnce(new Error('simulated lost tab publication')) - .mockResolvedValue(undefined) - - const store = await openTestAgentSessionRecordStore(root) - const sessionAdapter = adapter() - host = new StructuredAgentSessionHost({ - agents: claudeAndCodexAgents(sessionAdapter), - logger: createStructuredAgentSessionLogger(), - store, - adapter: sessionAdapter, - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1' - }) - setStructuredAgentSessionHost(host) - const dispatcher = new RpcDispatcher({ - runtime, - methods: STRUCTURED_AGENT_SESSION_METHODS - }) - const historyFields = { - worktree: `id:${WORKSPACE}`, - agent: 'codex' as const, - resumeFrom: { providerSessionId: THREAD } - } - const historyParams = { - ...historyFields, - envelope: { - ...createParams().envelope, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.create', - sessionId: SESSION, - fields: historyFields - }) - } - } - for (const capabilities of [ - CLIENT.clientCapabilities, - [...CLIENT.clientCapabilities, AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY] - ]) { - expect( - await call( - dispatcher, - historyParams, - { ...CLIENT, clientCapabilities: capabilities }, - unary - ) - ).toMatchObject({ - ok: true, - result: { - ok: false, - refusal: { - code: 'agent_session_conflict', - details: { reason: 'conversationHeldElsewhere' }, - createAttemptRefusedBeforeCommit: true - } - } - }) - expect(store.getRecord(SESSION)).toBeFalsy() - expect(sessionAdapter.acquire).not.toHaveBeenCalled() - } - // createSupport asks create's question before anything closes, leaving out the panes the - // client closes first; for any other pane it refuses as create does. - const support = (closingPaneKeys?: string[]) => - dispatcher.dispatch( - { - id: 'support', - authToken: 'token', - method: 'agentSession.createSupport', - params: { - worktree: `id:${WORKSPACE}`, - agent: 'codex', - resumeFrom: { - providerSessionId: THREAD, - ...(closingPaneKeys ? { closingPaneKeys } : {}) - } - } - }, - { - ...CLIENT, - clientCapabilities: [ - ...CLIENT.clientCapabilities, - STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY - ] - } - ) - expect(await support([SOURCE_PANE])).toMatchObject({ ok: true, result: { supported: true } }) - const created = await call(dispatcher, historyParams, CLIENT, unary) - const createResult = created?.ok ? created.result : undefined - const createRefusal = readAgentSessionRefusalReference( - typeof createResult === 'object' && createResult !== null && 'refusal' in createResult - ? createResult.refusal - : undefined - ) - expect(createRefusal).toMatchObject({ code: 'agent_session_conflict' }) - // As the client reads it: the thrown error carries the response. - expect(readAgentSessionErrorRefusal({ response: await support() })).toEqual(createRefusal) - writerVerdict = 'exited' - const params = createParams() - - // absent row with proven local history now imports (Continue after exit); invalid source still refuses - rows = unary - ? [{ ...sourceRow, providerSession: undefined }] - : [{ ...sourceRow, providerSession: { ...sourceRow.providerSession, id: 'replaced' } }] - const route = vi - .spyOn(runtime, 'routeClientHostedBrowserRpc') - .mockImplementationOnce(async () => { - rows = [sourceRow] - return { handled: false } - }) - expect(await call(dispatcher, params, CLIENT, unary)).toMatchObject({ - ok: true, - result: { ok: false, refusal: { details: { reason: 'transcriptUnreadable' } } } - }) - expect(sessionAdapter.acquire).not.toHaveBeenCalled() - expect(internal.publishStructuredAgentSessionTab).not.toHaveBeenCalled() - if (absent) { - rows = [] - const source = params.resumeFrom.cliSource - const binding = { tabId: 'tab-source', leafId: SOURCE_LEAF, incarnationId: 'i1' } - expect(runtime.getStructuredAgentCliSourceRoute(source)).toBe('native-local') - runtime.registerPty('source-pty', WORKSPACE, null, binding, true) - expect(runtime.getStructuredAgentCliSourceRoute(source)).toBe('unsupported') - runtime.registerPty('source-pty', WORKSPACE, 'ssh', binding, false) - expect(runtime.getStructuredAgentCliSourceRoute(source)).toBe('unsupported') - runtime.registerPty('source-pty', WORKSPACE, null, binding, false) - expect(runtime.getStructuredAgentCliSourceRoute({ ...source, paneKey: 'missing' })).toBe( - 'unknown' - ) - expect(() => - runtime.getStructuredAgentCliSourceRoute({ ...source, workspaceId: 'other' }) - ).toThrow('terminal_not_found') - const direct = { - runtime, - ensureHost: async () => host, - envelope: params.envelope, - worktree: params.worktree, - agent: params.agent, - caller: { callerKey: CLIENT.clientId }, - resumeFrom: params.resumeFrom - } - sourceRoute.mockClear() - const prepared = await prepareStructuredAgentSessionCreateForWorktree(direct) - expect(prepared.attachParams.adopt?.transcriptPath).toBe(await realpath(transcriptPath)) - expect(sourceRoute).toHaveBeenCalledOnce() - sourceRoute.mockClear() - const intent = await runtime.resolveStructuredAgentSessionCreateIntent(direct) - expect(intent.adopt?.transcriptPath).toBe(await realpath(transcriptPath)) - expect(sourceRoute).toHaveBeenCalledOnce() - } - selectAccountHome.mockClear() - sourceRoute.mockClear() - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - route.mockImplementationOnce(async () => { - entered.resolve() - await release.promise - return { handled: false } - }) - const pending = call(dispatcher, params, CLIENT, unary) - await entered.promise - expect(sourceRoute).toHaveBeenCalledOnce() - if (absent) { - runtime.onPtyExit('source-pty', 0) - } - if (unary) { - rows = [] - } else { - sourceRow.worktreeId = 'replacement-workspace' - sourceRow.providerSession.id = 'replacement-thread' - sourceRow.providerSession.transcriptPath = join(root, 'replacement.jsonl') - } - release.resolve() - expect(await pending).toMatchObject({ - ok: true, - result: { ok: false, refusal: { code: 'agent_session_operation_unknown' } } - }) - expect(sourceRoute).toHaveBeenCalledOnce() - expect(store.getRecord(SESSION)?.accountHome).toMatchObject({ path: originalHome }) - await rm(transcriptPath) - selectedHome = driftedHome - setStructuredAgentSessionHost(null) - internal.ensureStructuredAgentSessionHost = vi.fn(async () => { - setStructuredAgentSessionHost(host) - }) - sourceRows.mockImplementation(() => { - if (!unary) { - throw new Error('source snapshot unavailable') - } - return [] - }) - - const replay = await call(dispatcher, params) - expect(replay).toMatchObject({ - ok: true, - result: { - ok: true, - replayed: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ - blocks: expect.arrayContaining([ - expect.objectContaining({ text: 'durable adopted history' }) - ]) - }) - }) - ]) - } - } - } - }) - if (absent) { - expect(JSON.stringify(replay)).toContain('late adopted history') - } - expect(sessionAdapter.acquire).toHaveBeenCalledTimes(1) - expect(internal.publishStructuredAgentSessionTab).toHaveBeenCalledTimes(2) - expect(selectAccountHome).toHaveBeenCalledTimes(1) - // A missing source row admits the holder check; a failed store read reports unavailable preparation. - const another = await call(dispatcher, createParams(OPERATION, 'another-chat')) - expect(another).toMatchObject({ - ok: true, - result: { - ok: false, - refusal: unary - ? { details: { reason: 'conversationHeldElsewhere' } } - : { code: 'structured_agent_session_unsupported' } - } - }) - expect(JSON.stringify(another).includes(`"owner"`)).toBe(unary) - - // Only an exact committed replay bypasses an unavailable writer scan. - const freshRefusal = unary - ? { code: 'agent_session_identity_required' } - : { code: 'structured_agent_session_unsupported' } - const otherOperation = createParams(`${Date.now()}-00000000000000000000000000000002`) - expect(await call(dispatcher, otherOperation)).toMatchObject({ - ok: true, - result: { ok: false, refusal: freshRefusal } - }) - expect(await call(dispatcher, params, { ...CLIENT, clientId: 'device-b' })).toMatchObject({ - ok: true, - result: { ok: false, refusal: freshRefusal } - }) - expect(sessionAdapter.acquire).toHaveBeenCalledTimes(1) - expect(internal.publishStructuredAgentSessionTab).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts index 4c87ea97a71..9ce73b75430 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts @@ -17,7 +17,7 @@ import type { AttachParams, CreateSupportParams, CreateParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' import { commitStructuredAgentSessionCreate, prepareStructuredAgentSessionCreateForWorktree, diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts index 9390069e22e..8a759b451e6 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts @@ -33,7 +33,7 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' import { captureStructuredAgentCliSource, type StructuredAgentCliSourceEvidence -} from '../../../../../native-chat/structured-agent-cli-source' +} from '../../../../../native-chat/conversation-adoption/structured-agent-cli-source' import type { StructuredAgentId } from '../../../../../../shared/agent-session/lifecycle/agent-session-provider-handle' import { resolveUncommittedStructuredCreate } from './structured-agent-session-precommit-refusal' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts index 5fb0666abc1..61bf09140e1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts @@ -8,7 +8,7 @@ import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent- import type { StructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-host' import type { StructuredAgentSessionCaller } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-host-types' import type { RpcContext } from '../../../core' -import { rpcCallerOperationKey } from '../../../rpc-caller-identity' +import { rpcCallerOperationKey } from '../../../callers/rpc-caller-identity' import { structuredAgentSessionHostRefusal } from '../../../../agent-session/structured-agent-session-host-refusal' import { createSupportFollowsHostSetting, diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts index 46a1484336b..5c0825755c3 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts @@ -10,7 +10,7 @@ import { type AgentSessionWireRefusalCode } from '../../../../../../shared/agent-session/failures/agent-session-wire-refusals' import { isAgentSessionCreateAdmissionRefusal } from '../../../../../../shared/agent-session/failures/agent-session-definitive-refusal' -import { AgentConversationCopyError } from '../../../../../native-chat/agent-conversation-copy-error' +import { AgentConversationCopyError } from '../../../../../native-chat/conversation-adoption/agent-conversation-copy-error' import { tuiAgentDisplayName } from '../../../../../../shared/agent-launch/catalog/tui-agent-display-names' export type StructuredCreateRefused = { refusal: AgentSessionWireRefusal } diff --git a/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-conversation-outline.ts b/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-conversation-outline.ts index 4f0f0b6b809..2f397342b83 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-conversation-outline.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-conversation-outline.ts @@ -3,10 +3,10 @@ import { readAgentSessionConversationOutline } from '../../../../../native-chat/agent-session-wire/publication/history/agent-session-conversation-outline' import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' -import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +import { OptionsParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' export const STRUCTURED_AGENT_SESSION_CONVERSATION_OUTLINE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-item.ts b/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-item.ts index 7aa939b2054..9e73e815c6c 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-item.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-item.ts @@ -1,7 +1,7 @@ // Negotiate item-detail.v1 for full journal items beyond preview heads; fit replies to transport limits and mark remaining truncation. import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { ItemParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params' +import { ItemParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' import { shortenedAgentJournalItem } from '../../../../../native-chat/agent-session-wire/publication/history/agent-session-item-wire-form' import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../../../shared/remote-runtime/remote-runtime-memory-limits' import { defineMethod } from '../../../core' diff --git a/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-send-recorded.ts b/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-send-recorded.ts index 03ed27b4470..c7cf8c1a5be 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-send-recorded.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/history/structured-agent-session-send-recorded.ts @@ -1,6 +1,6 @@ // A client that lost a send's reply asks here instead of searching the history pages it loaded. -import { SendRecordedParams } from '../../../../../../shared/rpc-contract/structured-agent-session-send-recorded-params' +import { SendRecordedParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-send-recorded-params' import type { StructuredSendAnswer } from '../../../../../native-chat/agent-session-wire/delivery/structured-agent-session-queued-send-answer' import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' diff --git a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts b/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts index cdb193c92a4..955206c0952 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts @@ -11,10 +11,10 @@ import type { RestTestRig } from '../../../../../native-chat/agent-session-wire/ import { OrcaRuntimeService } from '../../../../orca-runtime' import type { RpcResponse } from '../../../core' import { RpcDispatcher } from '../../../dispatcher' -import type { RpcDispatchStreamingOptions } from '../../../dispatcher-stream-options' +import type { RpcDispatchStreamingOptions } from '../../../dispatch/dispatcher-stream-options' import { STRUCTURED_AGENT_SESSION_METHODS } from '../structured-agent-session' import type * as fileOperations from 'node:fs/promises' -import * as contextSnapshots from '../../../../../native-chat/agent-session-context-snapshots' +import * as contextSnapshots from '../../../../../native-chat/conversation-context/agent-session-context-snapshots' vi.mock('node:fs/promises', { spy: true }) export const actualFiles = await vi.importActual('node:fs/promises') diff --git a/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts b/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts index 9d7d6ea608d..c36db52db9c 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts @@ -45,15 +45,14 @@ import { CreateParams, CreateSupportParams, HistoryParams, - WorkStateParams, RewindParams, SendParams, SleepWorkspaceParams, UnsubscribeParams -} from '../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +} from '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { sendStructuredAgentSessionForClient } from './conversation/structured-agent-session-send-compatibility' import { runConversationCommandForClient } from './conversation/structured-agent-session-conversation-command' import { getStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' @@ -192,16 +191,6 @@ export const STRUCTURED_AGENT_SESSION_METHODS = [ ) } }), - // Waiters poll this instead of history: no history page or running-turn scan, and no transcript in the reply. - defineMethod({ - name: 'agentSession.workState', - permission: 'workspace', - params: WorkStateParams, - handler: async (params, ctx) => - (await requireInstalledHost(ctx, params.sessionId)).backgroundTasks.workState( - params.sessionId - ) - }), STRUCTURED_AGENT_SESSION_SUBSCRIBE_METHOD, defineMethod({ name: 'agentSession.unsubscribe', diff --git a/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts b/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts index 71071e1d5bb..114754dc4f4 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts @@ -181,13 +181,11 @@ export type StructuredCodexRpcHarness = { export async function openStructuredCodexRpcHarness( clientCapabilities: readonly RuntimeCapability[] = DEFAULT_CLIENT_CAPABILITIES, /** What the transport stamps, as a paired device's authenticated socket does. */ - transport: { clientId?: string; pairedDeviceId?: string } = {}, - /** The local CLI names no client kind; an older host lacks newer methods. */ - options: { localCli?: boolean; omitMethods?: readonly string[] } = {} + transport: { clientId?: string; pairedDeviceId?: string } = {} ): Promise { const client = { clientId: 'device-a', - ...(options.localCli ? {} : { clientKind: 'runtime' as const }), + clientKind: 'runtime' as const, clientCapabilities, ...transport } @@ -249,9 +247,7 @@ export async function openStructuredCodexRpcHarness( } const dispatcher = new RpcDispatcher({ runtime: runtime as unknown as OrcaRuntimeService, - methods: STRUCTURED_AGENT_SESSION_METHODS.filter( - (method) => !options.omitMethods?.includes(method.name) - ) + methods: STRUCTURED_AGENT_SESSION_METHODS }) const call: StructuredCodexRpcHarness['call'] = async (method, params) => { const replies: RpcResponse[] = [] diff --git a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts index 8e3046fb5cc..3abe0165bac 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts @@ -9,7 +9,7 @@ import { projectTurnItemEvent } from '../history/structured-agent-session-turn-i import { requireInstalledStructuredHost as requireInstalledHost } from '../creation/structured-agent-session-gate' import { bindStructuredAgentSessionStream } from './structured-agent-session-status-stream' import { structuredAgentSessionSubscriptionId as subscriptionIdFor } from './structured-agent-session-subscription-id' -import { SubscribeParams } from '../../../../../../shared/rpc-contract/structured-agent-session-subscribe-params' +import { SubscribeParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-subscribe-params' import * as queuedImages from '../attachments/structured-agent-session-queued-image-capability' import { projectReceiptDeviceEvent } from './structured-agent-session-receipt-devices' diff --git a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-turn-completion-stream.ts b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-turn-completion-stream.ts index 313d6111ed4..1805bf02341 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-turn-completion-stream.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-turn-completion-stream.ts @@ -8,10 +8,10 @@ import { import { AcknowledgeAttentionParams, SubscribeTurnCompletionsParams -} from '../../../../../../shared/rpc-contract/structured-agent-session-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-continue-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-rename-params' -import '../../../../../../shared/rpc-contract/structured-agent-session-queued-edit-params' +} from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' +import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-queued-edit-params' import { structuredAgentSessionTurnCompletionSubscriptionId } from './structured-agent-session-subscription-id' import { bindStructuredAgentSessionStream } from './structured-agent-session-status-stream' import { clientReadsStructuredSessionAgent } from '../structured-agent-session-policy' diff --git a/src/main/runtime/rpc/methods/terminal/agent-session.ts b/src/main/runtime/rpc/methods/terminal/agent-session.ts index 82d1a4c030c..0bb5f206b7e 100644 --- a/src/main/runtime/rpc/methods/terminal/agent-session.ts +++ b/src/main/runtime/rpc/methods/terminal/agent-session.ts @@ -1,4 +1,4 @@ -import { ensureAgentSessionFeatureRequirement } from '../../agent-launch-feature-requirement' +import { ensureAgentSessionFeatureRequirement } from '../../startup/agent-launch-feature-requirement' import { terminalImageViewerSupported } from '../../../terminal/launch/terminal-image-viewer-env' import { type RuntimeAgentSessionRpcCaller, @@ -9,7 +9,7 @@ import { defineMethod, type RpcContext } from '../../core' import { CreateAgentSessionParams, EnsureAgentSessionParams -} from '../../../../../shared/rpc-contract/agent-session-params' +} from '../../../../../shared/rpc-contract/terminal/agent-session-params' function callerContext(context: RpcContext): RuntimeAgentSessionRpcCaller { const { pairedDeviceId, clientId, clientKind, signal } = context diff --git a/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts b/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts index 05d5db25a7e..ab48bfee7c6 100644 --- a/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts +++ b/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts @@ -1,6 +1,6 @@ -import { SessionReadTerminalScrollbackParams } from '../../../../../shared/rpc-contract/session-terminal-scrollback-params' +import { SessionReadTerminalScrollbackParams } from '../../../../../shared/rpc-contract/session-tabs/session-terminal-scrollback-params' import { defineMethod } from '../../core' -import { servesWslMovedPaneHistory } from '../../../../orcad/orcad-migration-wsl-destination' +import { servesWslMovedPaneHistory } from '../../../../orcad/migration/orcad-migration-wsl-destination' // Defined statically so the params catalog types it; registration is gated per host below. export const SESSION_TERMINAL_SCROLLBACK_METHODS = [ diff --git a/src/main/runtime/rpc/methods/terminal/stream-schemas.ts b/src/main/runtime/rpc/methods/terminal/stream-schemas.ts index d2399e88306..26ccc996875 100644 --- a/src/main/runtime/rpc/methods/terminal/stream-schemas.ts +++ b/src/main/runtime/rpc/methods/terminal/stream-schemas.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { requiredString } from '../../../../../shared/rpc-contract/rpc-param-primitives' -import { TerminalViewport } from '../../../../../shared/rpc-contract/terminal-unary-params' -import { TerminalHandle } from '../../../../../shared/rpc-contract/terminal-stream-params' +import { TerminalViewport } from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' +import { TerminalHandle } from '../../../../../shared/rpc-contract/terminal/terminal-stream-params' export const TerminalMultiplexSubscribeFrame = TerminalHandle.extend({ streamId: z.number().int().min(1), diff --git a/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts index 76b1dad635f..717ca5e0308 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts @@ -4,9 +4,9 @@ import { } from '../../../terminal/input/terminal-input-admission' import { defineMethod, defineStreamingMethod } from '../../core' import { bindStructuredAgentSessionStream } from '../structured-sessions/subscriptions/structured-agent-session-status-stream' -import { TerminalViewClaudeAgent } from '../../../../../shared/rpc-contract/terminal-unary-params' +import { TerminalViewClaudeAgent } from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' -import { assertTerminalAgentSendable } from '../../terminal-agent-send-guard' +import { assertTerminalAgentSendable } from '../../terminal/terminal-agent-send-guard' import { assertTerminalSendExactPtyBinding, terminalInputSourceForClient diff --git a/src/main/runtime/rpc/methods/terminal/terminal-codex-question-skip-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-codex-question-skip-method.ts index 95988fbb55e..c727036a982 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-codex-question-skip-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-codex-question-skip-method.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { TerminalInferCodexQuestionSkip } from '../../../../../shared/rpc-contract/terminal-codex-question-params' +import { TerminalInferCodexQuestionSkip } from '../../../../../shared/rpc-contract/terminal/terminal-codex-question-params' import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' /** Codex reports no async-question skip, and this host's hook state tracks the question, so a diff --git a/src/main/runtime/rpc/methods/terminal/terminal-daemon.ts b/src/main/runtime/rpc/methods/terminal/terminal-daemon.ts index efb29bd6a5e..149fc6f3a8b 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-daemon.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-daemon.ts @@ -1,5 +1,5 @@ -import { TerminalLimitUpdateParams } from '../../../../../shared/rpc-contract/terminal-limit-params' -import { TerminalDaemonRestartSeveredParams } from '../../../../../shared/rpc-contract/terminal-daemon-params' +import { TerminalLimitUpdateParams } from '../../../../../shared/rpc-contract/terminal/terminal-limit-params' +import { TerminalDaemonRestartSeveredParams } from '../../../../../shared/rpc-contract/terminal/terminal-daemon-params' import { readSeveredDaemonStatus, restartSeveredDaemon diff --git a/src/main/runtime/rpc/methods/terminal/terminal-input-delivery.ts b/src/main/runtime/rpc/methods/terminal/terminal-input-delivery.ts index 04863e7695a..d0e8f679b2a 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-input-delivery.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-input-delivery.ts @@ -3,7 +3,7 @@ import { TerminalInputPausedError, type TerminalInputSource } from '../../../terminal/input/terminal-input-admission' -import type { RpcCallerIdentity } from '../../rpc-caller-identity' +import type { RpcCallerIdentity } from '../../callers/rpc-caller-identity' import { InvalidArgumentError } from '../../core' import type { RuntimeTerminalSend } from '../../../../../shared/runtime-terminal-send-contract' import type { OrcaRuntimeService } from '../../../orca-runtime' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts index 8e91a912c23..7d9f201e01b 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts @@ -1,4 +1,4 @@ -import { terminalCreateFeatureRequirement } from '../../agent-launch-feature-requirement' +import { terminalCreateFeatureRequirement } from '../../startup/agent-launch-feature-requirement' import { terminalImageViewerSupported } from '../../../terminal/launch/terminal-image-viewer-env' import { TERMINAL_WORKSPACE_STOP_METHODS } from './terminal-workspace-stop-methods' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../../../shared/sidebar-inputs-switch' @@ -7,7 +7,7 @@ import { navigationTargetsHost, resolveRuntimeNavigationTarget } from '../../../../../shared/runtime-navigation' -import { withTerminalCloseAttribution } from '../../terminal-close-attribution' +import { withTerminalCloseAttribution } from '../../terminal/terminal-close-attribution' import { AgentTeamsPrepareLaunch, AgentTeamsTmuxCompat, @@ -17,8 +17,8 @@ import { TerminalReveal, TerminalSplit, TerminalWait -} from '../../../../../shared/rpc-contract/terminal-unary-params' -import { TerminalResizeForClient } from '../../../../../shared/rpc-contract/terminal-stream-params' +} from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' +import { TerminalResizeForClient } from '../../../../../shared/rpc-contract/terminal/terminal-stream-params' export const TERMINAL_LIFECYCLE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-connection.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-connection.ts index 5b162c4d1c8..75cfcb595f7 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-connection.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-connection.ts @@ -5,7 +5,7 @@ import type { TerminalStreamFrame, TerminalStreamOpcode } from '../../../../../shared/terminal/stream/terminal-stream-protocol' -import type { TerminalOutputFrameChunk } from '../../terminal-output-frame-chunks' +import type { TerminalOutputFrameChunk } from '../../terminal/terminal-output-frame-chunks' import type { TerminalMultiplexSnapshotRequestFrame, TerminalMultiplexSubscribeFrame diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-flow-control.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-flow-control.ts index 23b5d2ba8eb..7273479aea8 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-flow-control.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-flow-control.ts @@ -1,5 +1,5 @@ import { TERMINAL_MULTIPLEX_RECOVERY_SCROLLBACK_ROWS } from '../../../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { drainTerminalMultiplexRoundRobin } from '../../terminal-multiplex-round-robin' +import { drainTerminalMultiplexRoundRobin } from '../../terminal/terminal-multiplex-round-robin' import { sendSnapshotFrames, serializeBudgetedRequestedSnapshot @@ -14,7 +14,7 @@ import { creditAckWindow, releaseAckPendingHoldbackIfDrained } from './terminal-multiplex-ack-window' -import type { TerminalOutputFrameChunk } from '../../terminal-output-frame-chunks' +import type { TerminalOutputFrameChunk } from '../../terminal/terminal-output-frame-chunks' import { markYieldedQueriesDiscardedInFrames, replaySnapshotCoveredStatelessQueries diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-frame-delivery.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-frame-delivery.ts index 321b6481503..15442faa5b1 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-frame-delivery.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-frame-delivery.ts @@ -16,7 +16,7 @@ import { isMultiplexStreamAttached, type TerminalMultiplexConnection } from './terminal-multiplex-connection' -import type { TerminalOutputFrameChunk } from '../../terminal-output-frame-chunks' +import type { TerminalOutputFrameChunk } from '../../terminal/terminal-output-frame-chunks' import type { TerminalStreamInputOutcome } from './terminal-input-delivery' import type { TerminalMultiplexStream } from './terminal-stream-types' import { @@ -25,7 +25,7 @@ import { chargeAckWindow, noteAckGatedSend } from './terminal-multiplex-ack-window' -import type { RpcBinarySendResult } from '../../rpc-binary-sender' +import type { RpcBinarySendResult } from '../../transports/rpc-binary-sender' export function installMultiplexFrameDelivery(state: TerminalMultiplexConnection): void { const { sendBinary, emit } = state diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts index 6ad247c411f..d79e4c6146d 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts @@ -5,7 +5,7 @@ import { TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION, TERMINAL_MULTIPLEX_MAX_QUEUED_PTY_WAITS_PER_CONNECTION } from '../../../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { TerminalMultiplex } from '../../../../../shared/rpc-contract/terminal-stream-params' +import { TerminalMultiplex } from '../../../../../shared/rpc-contract/terminal/terminal-stream-params' import type { TerminalMultiplexConnection } from './terminal-multiplex-connection' import type { TerminalMultiplexStream } from './terminal-stream-types' import { installMultiplexFrameDelivery } from './terminal-multiplex-frame-delivery' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts index d365d39f2bc..cc069a01ea1 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts @@ -4,7 +4,7 @@ import { } from '../../../../../shared/terminal/stream/terminal-stream-protocol' import { recordYieldedTerminalQueries } from './terminal-multiplex-yielded-queries' import { EMPTY_TERMINAL_REPLY_QUERY_SCAN_STATE } from '../../../../../shared/terminal/protocol/queries/terminal-reply-query-scan' -import { iterateTerminalOutputFrameChunks } from '../../terminal-output-frame-chunks' +import { iterateTerminalOutputFrameChunks } from '../../terminal/terminal-output-frame-chunks' import { TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES } from '../../../../../shared/terminal/stream/terminal-multiplex-flow-control' import { createTerminalOutputBatcher } from './terminal-output-batcher' import { appendPendingMultiplexOutput } from './terminal-stream-replay' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-yielded-queries.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-yielded-queries.ts index 7778be70171..e216648af3e 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-yielded-queries.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-yielded-queries.ts @@ -6,7 +6,7 @@ import { import type { RuntimeTerminalDataMeta } from '../../../terminal/output/runtime-terminal-stream-consumers' import type { TerminalMultiplexConnection } from './terminal-multiplex-connection' import type { TerminalMultiplexStream, TerminalOutputChunk } from './terminal-stream-types' -import type { TerminalOutputFrameChunk } from '../../terminal-output-frame-chunks' +import type { TerminalOutputFrameChunk } from '../../terminal/terminal-output-frame-chunks' import { encodeTerminalStreamText } from '../../../../../shared/terminal/stream/terminal-stream-protocol' import { getOutputAfterSnapshotSeq } from './terminal-stream-replay' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-orphan.ts b/src/main/runtime/rpc/methods/terminal/terminal-orphan.ts index e8455a3c204..c75cafccdfd 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-orphan.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-orphan.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { TerminalAdoptOrphans } from '../../../../../shared/rpc-contract/terminal-orphan-params' +import { TerminalAdoptOrphans } from '../../../../../shared/rpc-contract/terminal/terminal-orphan-params' export const TERMINAL_ORPHAN_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/terminal/terminal-output-batcher.ts b/src/main/runtime/rpc/methods/terminal/terminal-output-batcher.ts index f9b4d0a7cb6..b73f0c20b96 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-output-batcher.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-output-batcher.ts @@ -1,9 +1,9 @@ -import type { TerminalOutputMeta } from '../../terminal-output-frame-chunks' +import type { TerminalOutputMeta } from '../../terminal/terminal-output-frame-chunks' import { TERMINAL_OUTPUT_BATCH_MAX_BYTES, type TerminalOutputCadence } from '../../../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { measureTerminalStreamByteLength } from '../../terminal-stream-byte-length' +import { measureTerminalStreamByteLength } from '../../terminal/terminal-stream-byte-length' const TERMINAL_OUTPUT_FLUSH_MS: Record = { focused: 5, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-output-credit.ts b/src/main/runtime/rpc/methods/terminal/terminal-output-credit.ts index 8c74e92c629..6f978408d90 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-output-credit.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-output-credit.ts @@ -6,8 +6,8 @@ import { EMPTY_TERMINAL_REPLY_QUERY_SCAN_STATE, scanTerminalReplyQuerySequences } from '../../../../../shared/terminal/protocol/queries/terminal-reply-query-scan' -import type { TerminalOutputMeta } from '../../terminal-output-frame-chunks' -import { terminalStreamByteLength } from '../../terminal-stream-byte-length' +import type { TerminalOutputMeta } from '../../terminal/terminal-output-frame-chunks' +import { terminalStreamByteLength } from '../../terminal/terminal-stream-byte-length' import { getOutputAfterSnapshotSeq } from './terminal-stream-replay' import type { TerminalOutputChunk } from './terminal-stream-types' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts index fc4879e5de0..969baafb908 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts @@ -2,7 +2,13 @@ import { defineMethod } from '../../core' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' import { remoteFileContentBudget } from '../files/files-remote-content-budget' import { remoteRpcResultExceedsContentBudget } from '../../../../../shared/remote-rpc-content-budget' +import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { + formatOrcaSessionAddress, + type OrcaSessionAddress +} from '../../../../../shared/orca-session-address' +import { + TerminalAgentId, TerminalHandle, TerminalInspectProcess, TerminalListParams, @@ -13,7 +19,7 @@ import { TerminalResolveActive, TerminalResolvePane, TerminalSetPaneTitle -} from '../../../../../shared/rpc-contract/terminal-unary-params' +} from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' export const TERMINAL_QUERY_METHODS = [ defineMethod({ @@ -65,6 +71,22 @@ export const TERMINAL_QUERY_METHODS = [ terminal: runtime.resolveTerminalPane(params.paneKey, params.worktreeId) }) }), + defineMethod({ + // The id lives with the pane's hook server, so a failed earlier commit is retried here. + name: 'terminal.agentId', + permission: 'workspace', + params: TerminalAgentId, + handler: async (params, { runtime }): Promise<{ orcaSessionId: OrcaSessionAddress | null }> => { + // Re-read on each look: the pane may wake or sleep while the worker answers. + const id = await agentHookServer.resolvePaneAgentId( + params.paneKey, + () => + runtime.getWorkspaceSessionForWorktree(params.worktreeId) + ?.sleepingAgentSessionsByPaneKey?.[params.paneKey] + ) + return { orcaSessionId: id ? formatOrcaSessionAddress(id) : null } + } + }), defineMethod({ name: 'terminal.recoverPane', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/terminal/terminal-quick-command-client-capabilities.test.ts b/src/main/runtime/rpc/methods/terminal/terminal-quick-command-client-capabilities.test.ts deleted file mode 100644 index 513ab61129c..00000000000 --- a/src/main/runtime/rpc/methods/terminal/terminal-quick-command-client-capabilities.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getDefaultPersistedState } from '../../../../../shared/constants' -import '../../../../../shared/electron-remote-runtime-client-capabilities' -import '../../../../../shared/remote-runtime/remote-runtime-client-capabilities' -import { LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH } from '../../../../../shared/terminal/quick-commands/terminal-quick-command-prompt-limit' -import type { TerminalQuickCommand } from '../../../../../shared/terminal/quick-commands/terminal-quick-command-types' -import type { TerminalQuickCommandMutation } from '../../../../../shared/terminal/quick-commands/terminal-quick-commands' -import '../../../../../shared/web-runtime-client-capabilities' -import { TERMINAL_QUICK_COMMAND_LARGE_LISTS_RUNTIME_CAPABILITY } from '../../../../../shared/terminal/quick-commands/terminal-quick-command-capabilities' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import '../../../../ipc/desktop-renderer-runtime-capabilities' -import { RuntimeClientSettingsController } from '../../../client/settings/runtime-client-settings' -import { - updateSettings, - type SettingsMutationOperations -} from '../../../../persistence/applying-settings/settings-update' -import type { RpcRequest } from '../../core' -import { RpcDispatcher } from '../../dispatcher' -import '../../runtime-client-capabilities' -import { CLIENT_UI_METHODS } from '../client-state/client-ui' - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -describe('quick-command client compatibility', () => { - const shortCommand: TerminalQuickCommand = { - id: 'status', - label: 'Status', - action: 'terminal-command', - command: 'git status', - appendEnter: true, - scope: { type: 'global' } - } - const longCommand: TerminalQuickCommand = { - id: 'review', - label: 'Review', - action: 'agent-prompt', - agent: 'claude', - prompt: 'x'.repeat(LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH + 1), - scope: { type: 'global' } - } - - function makeDispatcher(commands = [shortCommand, longCommand]) { - const state = getDefaultPersistedState('/tmp') - state.settings.terminalQuickCommands = commands - const scheduleSave = vi.fn() - const operations: SettingsMutationOperations = { - state, - bumpLocalWorktreeScanGeneration: vi.fn(), - removeRetainedBlob: vi.fn(), - scheduleSave, - notifySettingsChanged: vi.fn() - } - const settings = new RuntimeClientSettingsController({ - getSettings: () => state.settings, - updateSettings: (updates, options) => updateSettings(operations, updates, options) - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers call only the quick-command methods stubbed here. - const runtime = { - getRuntimeId: () => 'test-runtime', - getClientTerminalQuickCommands: () => settings.getTerminalQuickCommands(), - updateClientTerminalQuickCommands: (mutation: TerminalQuickCommandMutation) => - settings.updateTerminalQuickCommands(mutation) - } as unknown as OrcaRuntimeService - return { - dispatcher: new RpcDispatcher({ runtime, methods: CLIENT_UI_METHODS }), - state, - scheduleSave - } - } - - it('lets legacy clients edit and delete visible commands while preserving hidden commands', async () => { - const commands = Array.from({ length: 45 }, (_, index) => ({ - ...shortCommand, - id: `command-${index}` - })) - const { dispatcher, state } = makeDispatcher(commands) - const caller = { clientKind: 'runtime' as const, clientCapabilities: [] } - const edited = { ...commands[0], label: 'Edited command' } - - const editResponse = await dispatcher.dispatch( - makeRequest('settings.updateTerminalQuickCommands', { - mutation: { type: 'upsert', command: edited } - }), - caller - ) - expect(editResponse).toMatchObject({ - ok: true, - result: { terminalQuickCommands: [edited, ...commands.slice(1, 40)] } - }) - - const deleteResponse = await dispatcher.dispatch( - makeRequest('settings.updateTerminalQuickCommands', { - mutation: { type: 'delete', id: commands[1].id } - }), - caller - ) - expect(deleteResponse).toMatchObject({ - ok: true, - result: { terminalQuickCommands: [edited, ...commands.slice(2, 41)] } - }) - expect(state.settings.terminalQuickCommands).toEqual([edited, ...commands.slice(2)]) - }) - - it.each(['runtime', 'mobile'] as const)( - 'refuses a stale %s client edit of a hidden prompt before saving anything', - async (clientKind) => { - const { dispatcher, state, scheduleSave } = makeDispatcher() - - const response = await dispatcher.dispatch( - makeRequest('settings.updateTerminalQuickCommands', { - mutation: { type: 'upsert', command: { ...longCommand, prompt: 'Stale short prompt' } } - }), - { - clientKind, - clientCapabilities: [TERMINAL_QUICK_COMMAND_LARGE_LISTS_RUNTIME_CAPABILITY] - } - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: expect.stringContaining('Update this Orca client') - } - }) - expect(state.settings.terminalQuickCommands).toEqual([shortCommand, longCommand]) - expect(scheduleSave).not.toHaveBeenCalled() - } - ) -}) diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-input-sequence.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-input-sequence.ts index d92808f62a8..0741c58eb79 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-input-sequence.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-input-sequence.ts @@ -4,7 +4,7 @@ import { TERMINAL_INPUT_MAX_BYTES } from '../../../../../shared/terminal/input/t import { TerminalOpenInputSession, type TerminalSend -} from '../../../../../shared/rpc-contract/terminal-unary-params' +} from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' import type { RuntimeTerminalSend } from '../../../../../shared/runtime-terminal-send-contract' import { terminalOrderedInputControls, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts index 124761678d3..4b1860dafc4 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts @@ -2,12 +2,12 @@ import { isTerminalInputPaused, TerminalInputPausedError } from '../../../terminal/input/terminal-input-admission' -import { assertLegacyAiVaultResumeCommandAllowed } from '../../../../ai-vault/structured-session-ownership' +import { assertLegacyAiVaultResumeCommandAllowed } from '../../../../ai-vault/structured-sessions/structured-session-ownership' import { InvalidArgumentError, defineMethod } from '../../core' import { isTerminalQueryReply } from '../../../../../shared/terminal/protocol/queries/terminal-query-reply' import { isUntypedTerminalInput } from '../../../../../shared/terminal/input/terminal-untyped-input' -import { assertTerminalAgentSendable } from '../../terminal-agent-send-guard' -import { TerminalSend } from '../../../../../shared/rpc-contract/terminal-unary-params' +import { assertTerminalAgentSendable } from '../../terminal/terminal-agent-send-guard' +import { TerminalSend } from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' import type { RuntimeTerminalSend } from '../../../../../shared/runtime-terminal-send-contract' import { assertTerminalSendExactPtyBinding, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts index 001bfb60da3..8786663266c 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts @@ -1,7 +1,7 @@ import type { z } from 'zod' import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { TerminalSend } from '../../../../../shared/rpc-contract/terminal-unary-params' +import type { TerminalSend } from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' import { isPotentialQuestionAnsweredSubmitInput, isQuestionAnsweredSubmitInput, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-snapshot-publication.ts b/src/main/runtime/rpc/methods/terminal/terminal-snapshot-publication.ts index f2195503001..cf065a455a4 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-snapshot-publication.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-snapshot-publication.ts @@ -7,7 +7,7 @@ import { MOBILE_SNAPSHOT_BYTE_BUDGET, MOBILE_SUBSCRIBE_SCROLLBACK_ROWS } from '../../../terminal/output/mobile-scrollback-limits' -import { terminalStreamByteLengthExceeds } from '../../terminal-stream-byte-length' +import { terminalStreamByteLengthExceeds } from '../../terminal/terminal-stream-byte-length' import { iterateTerminalStreamTextPayloads, requestedSnapshotScrollbackCandidates diff --git a/src/main/runtime/rpc/methods/terminal/terminal-stream-replay.ts b/src/main/runtime/rpc/methods/terminal/terminal-stream-replay.ts index b91c34b0908..ca59518775c 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-stream-replay.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-stream-replay.ts @@ -8,11 +8,11 @@ import { iterateTerminalOutputFrameChunks, type TerminalOutputFrameChunk, type TerminalOutputMeta -} from '../../terminal-output-frame-chunks' +} from '../../terminal/terminal-output-frame-chunks' import { measureTerminalStreamByteLength, terminalStreamByteLength -} from '../../terminal-stream-byte-length' +} from '../../terminal/terminal-stream-byte-length' import { TERMINAL_MULTIPLEX_PENDING_MAX_BYTES } from '../../../../../shared/terminal/stream/terminal-multiplex-flow-control' import type { TerminalMultiplexStream, TerminalOutputChunk } from './terminal-stream-types' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-stream-resume-ledger.ts b/src/main/runtime/rpc/methods/terminal/terminal-stream-resume-ledger.ts index 8952643487b..68a6f7e983e 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-stream-resume-ledger.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-stream-resume-ledger.ts @@ -2,7 +2,7 @@ import { iterateTerminalOutputFrameChunks, type TerminalOutputFrameChunk, type TerminalOutputMeta -} from '../../terminal-output-frame-chunks' +} from '../../terminal/terminal-output-frame-chunks' import { TerminalStreamOpcode } from '../../../../../shared/terminal/stream/terminal-stream-protocol' import type { PublishedOutputPoint, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-stream-types.ts b/src/main/runtime/rpc/methods/terminal/terminal-stream-types.ts index 63556c56a77..046086d624b 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-stream-types.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-stream-types.ts @@ -3,7 +3,7 @@ import type { TerminalSnapshotUnavailableReason } from '../../../../../shared/te import type { TerminalOutputFrameChunk, TerminalOutputMeta -} from '../../terminal-output-frame-chunks' +} from '../../terminal/terminal-output-frame-chunks' import type { TerminalOutputBatcher } from './terminal-output-batcher' import type { TerminalReplyQueryScanState } from '../../../../../shared/terminal/protocol/queries/terminal-reply-query-scan' import type { YieldedTerminalQuery } from './terminal-multiplex-yielded-queries' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary.ts b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary.ts index 3040d173ad1..4a129ed5219 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary.ts @@ -3,7 +3,7 @@ import { encodeTerminalStreamFrame, encodeTerminalStreamJson } from '../../../../../shared/terminal/stream/terminal-stream-protocol' -import type { TerminalOutputMeta } from '../../terminal-output-frame-chunks' +import type { TerminalOutputMeta } from '../../terminal/terminal-output-frame-chunks' import { iterateStreamOutputFrames } from './terminal-stream-resume-ledger' import { EMPTY_TERMINAL_REPLY_QUERY_SCAN_STATE, @@ -12,7 +12,7 @@ import { type TerminalReplyQuerySequence } from '../../../../../shared/terminal/protocol/queries/terminal-reply-query-scan' import { TERMINAL_MULTIPLEX_PENDING_MAX_BYTES } from '../../../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { measureTerminalStreamByteLength } from '../../terminal-stream-byte-length' +import { measureTerminalStreamByteLength } from '../../terminal/terminal-stream-byte-length' import { createTerminalOutputBatcher, type TerminalOutputBatcher } from './terminal-output-batcher' import { trimPendingOutputToBudget } from './terminal-stream-replay' import { allocateTerminalSubscriptionStreamId } from './terminal-subscription-stream-id' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts index 038f2012172..2a06bb37a4b 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts @@ -1,5 +1,5 @@ import { defineStreamingMethod } from '../../core' -import { TerminalSubscribe } from '../../../../../shared/rpc-contract/terminal-stream-params' +import { TerminalSubscribe } from '../../../../../shared/rpc-contract/terminal/terminal-stream-params' import { isTerminalReadPayloadIncomplete } from './terminal-stream-replay' import { runTerminalBinarySubscription } from './terminal-subscribe-binary' import { diff --git a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-types.ts b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-types.ts index ed1bb102662..8cb9562a9ef 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-types.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-types.ts @@ -2,7 +2,7 @@ import type { z } from 'zod' import type { RpcContext } from '../../core' import type { TerminalReplyQuerySequence } from '../../../../../shared/terminal/protocol/queries/terminal-reply-query-scan' import type { TerminalOutputChunk } from './terminal-stream-types' -import type { TerminalSubscribe } from '../../../../../shared/rpc-contract/terminal-stream-params' +import type { TerminalSubscribe } from '../../../../../shared/rpc-contract/terminal/terminal-stream-params' import type { TerminalOutputBatcher } from './terminal-output-batcher' import type { TerminalStreamOpcode } from '../../../../../shared/terminal/stream/terminal-stream-protocol' import type { TerminalSubscriptionRegistration } from './terminal-subscription-registration' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-viewer-colors-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-viewer-colors-method.ts index 850c3c4cf20..7a9cb0cd60c 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-viewer-colors-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-viewer-colors-method.ts @@ -5,7 +5,7 @@ import { setPairedViewerColors } from '../../../terminal/view/terminal-view-attribute-store' import { validateTerminalViewAttributes } from '../../../../../shared/terminal/protocol/queries/terminal-view-attributes' -import { TerminalSetViewerColors } from '../../../../../shared/rpc-contract/terminal-unary-params' +import { TerminalSetViewerColors } from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' export const TERMINAL_VIEWER_COLORS_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts index aca8edec36c..48429cff36f 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts @@ -1,14 +1,14 @@ import { defineMethod } from '../../core' -import { TerminalHandle } from '../../../../../shared/rpc-contract/terminal-unary-params' +import { TerminalHandle } from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' import { TerminalSetAutoRestoreFit, TerminalSetDisplayMode, TerminalUnsubscribe, TerminalUpdateViewport -} from '../../../../../shared/rpc-contract/terminal-viewport-schemas-params' +} from '../../../../../shared/rpc-contract/terminal/terminal-viewport-schemas-params' import { updateViewportForClient } from './terminal-viewport-update' -import { TerminalGetAutoRestoreFitParams } from '../../../../../shared/rpc-contract/terminal-viewport-methods-params' -import { TerminalAckOutput } from '../../../../../shared/rpc-contract/terminal-stream-params' +import { TerminalGetAutoRestoreFitParams } from '../../../../../shared/rpc-contract/terminal/terminal-viewport-methods-params' +import { TerminalAckOutput } from '../../../../../shared/rpc-contract/terminal/terminal-stream-params' import { acknowledgeTerminalStreamOutput } from './terminal-stream-tokens' export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS = [ diff --git a/src/main/runtime/rpc/methods/terminal/terminal-workspace-stop-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-workspace-stop-methods.ts index 4b957d6851e..957ee36ccce 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-workspace-stop-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-workspace-stop-methods.ts @@ -11,7 +11,7 @@ import { TerminalSleep, TerminalStop, TerminalStopExact -} from '../../../../../shared/rpc-contract/terminal-unary-params' +} from '../../../../../shared/rpc-contract/terminal/terminal-unary-params' /** Stopping every terminal of a workspace; closing and sleeping them wait in its lifecycle queue. */ export const TERMINAL_WORKSPACE_STOP_METHODS = [ diff --git a/src/main/runtime/rpc/methods/updater/updater.ts b/src/main/runtime/rpc/methods/updater/updater.ts index 01a760a019f..ba1e3e2cc70 100644 --- a/src/main/runtime/rpc/methods/updater/updater.ts +++ b/src/main/runtime/rpc/methods/updater/updater.ts @@ -5,7 +5,7 @@ import { getRemoteServerUpdaterSnapshot, installRemoteServerUpdater } from '../../../hosts/management/remote-server-updater' -import { UpdaterCheckParams } from '../../../../../shared/rpc-contract/updater-params' +import { UpdaterCheckParams } from '../../../../../shared/rpc-contract/updater/updater-params' export const UPDATER_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/workspace-layout/workspace-layout-apply.test.ts b/src/main/runtime/rpc/methods/workspace-layout/workspace-layout-apply.test.ts index 09f062a2444..0af8a730d3b 100644 --- a/src/main/runtime/rpc/methods/workspace-layout/workspace-layout-apply.test.ts +++ b/src/main/runtime/rpc/methods/workspace-layout/workspace-layout-apply.test.ts @@ -1,8 +1,5 @@ -import { RUNTIME_CAPABILITIES } from '../../../../../shared/protocol-version' -import { - LAYOUT_INTENTS_RUNTIME_CAPABILITY, - LAYOUT_REOPEN_HELD_PANES_CAPABILITY -} from '../../../../../shared/workspace-layout/layout-intents-capability' +import '../../../../../shared/protocol-version' +import '../../../../../shared/workspace-layout/published-layout/layout-intents-capability' import { afterEach, describe, expect, it, vi } from 'vitest' import type { WorkspaceSessionState } from '../../../../../shared/workspace-session/workspace-session-state-types' @@ -11,11 +8,7 @@ import type { ExecutionHostId } from '../../../../../shared/execution-host' import type { LayoutApplyOutcome } from '../../../../../shared/workspace-layout/workspace-layout-command-types' -import type { Tab } from '../../../../../shared/tab-types' - -import type { RuntimeStore } from '../../../construction/runtime-store-contract' - -import '../../../../../shared/workspace-layout/workspace-layout-client-visibility' +import '../../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' import '../../server/runtime-rpc-mobile-method-allowlist' import { OrcaRuntimeService } from '../../../orca-runtime' @@ -76,68 +69,6 @@ afterEach(() => { }) describe('layout.apply', () => { - it('does not advertise layout mutations in a window-owned build', () => { - expect(RUNTIME_CAPABILITIES).not.toContain(LAYOUT_INTENTS_RUNTIME_CAPABILITY) - expect(RUNTIME_CAPABILITIES).not.toContain(LAYOUT_REOPEN_HELD_PANES_CAPABILITY) - }) - - it('gives each title in its tab’s partition in one write, naming a paired server’s tab', async () => { - const applyTabRenames = vi.fn>(async (batches) => [ - { rename: batches[0]!.renames[0]!, code: 'tab_not_found' } - ]) - const hosts: Record = { 'tab-1': 'local', 'tab-2': 'ssh:target-1' } - const store: PartialRuntimeStore = { - getRepo: () => undefined, - getWorkspaceSessionHostIds: () => ['local', 'ssh:target-1', 'runtime:env-1'], - getWorkspaceSession: (host: string) => ({ - ...sessionListing('other'), - tabsByWorktree: {}, - unifiedTabs: { - [WORKTREE]: Object.entries({ ...hosts, 'tab-3': 'runtime:env-1' }) - .filter(([, owner]) => owner === host) - .map(([id]): Tab => ({ - id, - entityId: id, - groupId: 'group-1', - worktreeId: WORKTREE, - contentType: 'terminal', - label: id, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 - })) - } - }), - applyTabRenames - } - const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) - const titled = (tabId: string) => ({ workspace: WORKTREE, tabId, title: `Title ${tabId}` }) - - const reply = await runtime.applyLayoutCommand({ - type: 'renameTabs', - kind: 'generated', - renames: [titled('tab-1'), titled('tab-2'), titled('tab-3')] - }) - - const renameOf = (tabId: string) => ({ type: 'renameTab', kind: 'generated', ...titled(tabId) }) - expect(applyTabRenames).toHaveBeenCalledTimes(1) - expect(applyTabRenames).toHaveBeenCalledWith([ - { hostId: 'local', renames: [renameOf('tab-1')] }, - { hostId: 'ssh:target-1', renames: [renameOf('tab-2')] } - ]) - expect(reply).toEqual({ - ok: true, - result: { - untitled: [ - { workspace: WORKTREE, tabId: 'tab-3', code: 'host_not_owned' }, - { workspace: WORKTREE, tabId: 'tab-1', code: 'tab_not_found' } - ] - }, - frameSeq: 0 - }) - }) - it('names the stream position of the frame its write produced, sent before the reply', async () => { let session = sessionListing('tab-1') const written = new Set<(hostId: ExecutionHostId | null) => void>() diff --git a/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.test.ts b/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.test.ts index 7183e0b98cf..f689a89b63e 100644 --- a/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.test.ts +++ b/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { WorkspaceLayoutStreamEvent } from '../../../../../shared/workspace-layout/workspace-layout-stream-frames' +import type { WorkspaceLayoutStreamEvent } from '../../../../../shared/workspace-layout/published-layout/workspace-layout-stream-frames' import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' import { ALL_RPC_METHODS } from '../rpc-method-registry' diff --git a/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.ts b/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.ts index d56c9ef9d8a..4a2c780ce86 100644 --- a/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.ts +++ b/src/main/runtime/rpc/methods/workspace-layout/workspace-layout.ts @@ -1,5 +1,8 @@ -import { withoutGitGraph } from '../../../../../shared/workspace-layout/workspace-layout-client-visibility' -import { readsGitGraph, createGitGraphFrameProjection } from '../../git-graph-layout-projection' +import { withoutGitGraph } from '../../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' +import { + readsGitGraph, + createGitGraphFrameProjection +} from '../../workspace-client-views/git-graph-layout-projection' // Paired desktops use layout read/stream/apply only when the server offers layout.intents.v1; mobile is excluded. import { @@ -7,9 +10,9 @@ import { LayoutReportViewParams, LayoutSubscribeParams, LayoutUnsubscribeParams -} from '../../../../../shared/rpc-contract/workspace-layout-params' -import { LayoutReopenHeldPanesParams } from '../../../../../shared/rpc-contract/workspace-layout-held-panes-params' -import type { WorkspaceLayoutStreamFrame } from '../../../../../shared/workspace-layout/workspace-layout-stream-frames' +} from '../../../../../shared/rpc-contract/workspace-layout/workspace-layout-params' +import { LayoutReopenHeldPanesParams } from '../../../../../shared/rpc-contract/workspace-layout/workspace-layout-held-panes-params' +import type { WorkspaceLayoutStreamFrame } from '../../../../../shared/workspace-layout/published-layout/workspace-layout-stream-frames' import { defineMethod, defineStreamingMethod } from '../../core' import { getAppEnvironment } from '../../../../../shared/app-environment' import { listEnvironments } from '../../../../../shared/remote-runtime/host-store/runtime-environment-store' diff --git a/src/main/runtime/rpc/methods/workspace-ports/workspace-ports.ts b/src/main/runtime/rpc/methods/workspace-ports/workspace-ports.ts index d39b3c2aa8e..cc62df52bf4 100644 --- a/src/main/runtime/rpc/methods/workspace-ports/workspace-ports.ts +++ b/src/main/runtime/rpc/methods/workspace-ports/workspace-ports.ts @@ -5,7 +5,7 @@ import { WorkspacePortProbePageParams, WorkspacePortScanHostParams, WorkspacePortScanParams -} from '../../../../../shared/rpc-contract/workspace-ports-params' +} from '../../../../../shared/rpc-contract/workspaces/workspace-ports-params' import { probeWorkspacePortPage } from '../../../../ports/workspace-port-page-probe' export const WORKSPACE_PORT_METHODS = [ diff --git a/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts index 24cfcf523b6..2f9d14ce052 100644 --- a/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts +++ b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts @@ -2,7 +2,7 @@ import { defineMethod } from '../../core' import { AgentActivityClearParams, AgentActivitySetReadParams -} from '../../../../../shared/rpc-contract/agent-activity-params' +} from '../../../../../shared/rpc-contract/agent-activity/agent-activity-params' // Desktop Agents-list read and clear for paired clients; the next worktree.ps already reflects them. export const AGENT_ACTIVITY_METHODS = [ diff --git a/src/main/runtime/rpc/methods/workspaces/folder-workspace.ts b/src/main/runtime/rpc/methods/workspaces/folder-workspace.ts index 6360ec63e63..4eaaec576ee 100644 --- a/src/main/runtime/rpc/methods/workspaces/folder-workspace.ts +++ b/src/main/runtime/rpc/methods/workspaces/folder-workspace.ts @@ -1,11 +1,11 @@ import { defineMethod } from '../../core' -import { resolveRpcWorkspaceCreatorProvenance } from '../../workspace-creator-context' +import { resolveRpcWorkspaceCreatorProvenance } from '../../callers/workspace-creator-context' import { FolderWorkspaceCreate, FolderWorkspaceDelete, FolderWorkspacePathStatus, FolderWorkspaceUpdate -} from '../../../../../shared/rpc-contract/folder-workspace-params' +} from '../../../../../shared/rpc-contract/workspaces/folder-workspace-params' export const FOLDER_WORKSPACE_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/workspaces/workspace-cleanup-runner-methods.ts b/src/main/runtime/rpc/methods/workspaces/workspace-cleanup-runner-methods.ts new file mode 100644 index 00000000000..4292497a1bc --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/workspace-cleanup-runner-methods.ts @@ -0,0 +1,44 @@ +import { + WorkspaceCleanupPreviewParams, + WorkspaceCleanupReportUnsavedEditorsParams, + WorkspaceCleanupRunNowParams +} from '../../../../../shared/rpc-contract/workspace-cleanup/workspace-cleanup-runner-params' +import { requireWorkspaceCleanupRunner } from '../../../../workspaces/cleanup/workspace-cleanup-runner-registry' +import { reportClientUnsavedEditors } from '../../../../workspaces/cleanup/workspace-cleanup-client-unsaved-editors' +import { defineMethod } from '../../core' + +/** The cleanup runner of the host that owns the repos; clients merge hosts themselves. */ +export const WORKSPACE_CLEANUP_RUNNER_METHODS = [ + defineMethod({ + name: 'workspaceCleanup.preview', + permission: 'workspace', + params: WorkspaceCleanupPreviewParams, + handler: (params, { runtime }) => requireWorkspaceCleanupRunner(runtime).preview(params.rules) + }), + defineMethod({ + name: 'workspaceCleanup.runNow', + permission: 'workspace', + params: WorkspaceCleanupRunNowParams, + handler: (params, { runtime }) => + requireWorkspaceCleanupRunner(runtime).runNow(params.trigger ?? 'run-now') + }), + defineMethod({ + name: 'workspaceCleanup.report', + permission: 'workspace', + params: null, + handler: (_params, { runtime }) => requireWorkspaceCleanupRunner(runtime).report() + }), + defineMethod({ + name: 'workspaceCleanup.reportUnsavedEditors', + permission: 'workspace', + params: WorkspaceCleanupReportUnsavedEditorsParams, + handler: (params, { runtime, connectionId, signal }) => { + // Socket-scoped: without a live connection nothing would clear the report. + if (!connectionId || signal?.aborted) { + return { recorded: false } + } + reportClientUnsavedEditors(runtime, connectionId, params.reporterId ?? '', params.worktreeIds) + return { recorded: true } + } + }) +] diff --git a/src/main/runtime/rpc/methods/workspaces/workspace-cleanup-scan-method.ts b/src/main/runtime/rpc/methods/workspaces/workspace-cleanup-scan-method.ts new file mode 100644 index 00000000000..8b3f1f89c1b --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/workspace-cleanup-scan-method.ts @@ -0,0 +1,15 @@ +import { WorkspaceCleanupScanParams } from '../../../../../shared/rpc-contract/workspace-cleanup/workspace-cleanup-scan-params' +import { scanWorkspaceCleanup } from '../../../../ipc/workspace-cleanup/workspace-cleanup-scan' +import { defineMethod } from '../../core' + +/** The same scan desktop IPC runs, over the repos this host owns; clients merge hosts themselves. */ +export const WORKSPACE_CLEANUP_SCAN_METHOD = defineMethod({ + name: 'workspaceCleanup.scan', + permission: 'workspace', + params: WorkspaceCleanupScanParams, + handler: (params, { runtime, signal }) => + scanWorkspaceCleanup(runtime.requireStore(), params, { + signal, + getOrchestrationDb: () => runtime.getExistingOrchestrationDb() + }) +}) diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-archive-methods.ts b/src/main/runtime/rpc/methods/workspaces/worktree-archive-methods.ts new file mode 100644 index 00000000000..aa62076298a --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/worktree-archive-methods.ts @@ -0,0 +1,47 @@ +import { + WorktreeArchive, + WorktreeRestore +} from '../../../../../shared/rpc-contract/workspaces/worktree-params' +import { + queueWorkspaceArchive, + queueWorkspaceRestore +} from '../../../workspaces/lifecycle/workspace-lifecycle-commands' +import { defineMethod } from '../../core' +import { resolvePairedCallerHostId } from '../pairing/paired-caller-host-id' + +// Not on the mobile allowlist or in the CLI until archive ships (WORKSPACE_ARCHIVE_SUPPORTED). +export const WORKTREE_ARCHIVE_METHODS = [ + defineMethod({ + name: 'worktree.archive', + permission: 'workspace', + params: WorktreeArchive, + handler: async (params, { runtime }) => { + const hostId = resolvePairedCallerHostId( + () => runtime.listRepos(), + params.worktree, + params.hostId + ) + return queueWorkspaceArchive(runtime, params.worktree, hostId, () => + runtime.archiveManagedWorktree(params.worktree, hostId ? { hostId } : {}) + ) + } + }), + defineMethod({ + name: 'worktree.restore', + permission: 'workspace', + params: WorktreeRestore, + handler: async (params, { runtime }) => { + const hostId = resolvePairedCallerHostId( + () => runtime.listRepos(), + params.worktree, + params.hostId + ) + return queueWorkspaceRestore(runtime, params.worktree, hostId, () => + runtime.restoreArchivedWorktree(params.worktree, { + ...(hostId ? { hostId } : {}), + ...(params.setupDecision ? { setupDecision: params.setupDecision } : {}) + }) + ) + } + }) +] diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-catalog-methods.ts b/src/main/runtime/rpc/methods/workspaces/worktree-catalog-methods.ts index e334199ce90..d6778ea2e11 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-catalog-methods.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-catalog-methods.ts @@ -1,18 +1,18 @@ import { defineMethod } from '../../core' -import { resolveWorktreeCatalogSnapshot } from '../../worktree-catalog-snapshot' -import { coarsenWorktreePsActivity } from '../../worktree-ps-coarse-activity' -import { markWorktreePsOtherClientRows } from '../../worktree-ps-other-client-marks' -import { supportsWorktreeVisibilitySourceDefaults } from '../../worktree-visibility-client-capability' +import { resolveWorktreeCatalogSnapshot } from '../../workspace-client-views/worktree-catalog-snapshot' +import { coarsenWorktreePsActivity } from '../../workspace-client-views/worktree-ps-coarse-activity' +import { markWorktreePsOtherClientRows } from '../../workspace-client-views/worktree-ps-other-client-marks' +import { supportsWorktreeVisibilitySourceDefaults } from '../../workspace-client-views/worktree-visibility-client-capability' import { projectWorktreeListRemovals, projectWorktreePsRemovals -} from '../../worktree-removal-marker-projection' +} from '../../workspace-client-views/worktree-removal-marker-projection' import { snapshotPendingWorktreeRemovals } from '../../../../workspaces/removal/worktree-removal-listing' import { WorktreeDetectedListParams, WorktreeListParams, WorktreePsParams -} from '../../../../../shared/rpc-contract/worktree-params' +} from '../../../../../shared/rpc-contract/workspaces/worktree-params' export const WORKTREE_CATALOG_METHODS = [ defineMethod({ diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-create-args.ts b/src/main/runtime/rpc/methods/workspaces/worktree-create-args.ts index ac762c286f6..cecdcf0def6 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-create-args.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-create-args.ts @@ -1,4 +1,4 @@ -import { pickApprovedSetupHashes } from '../../../../../shared/worktree/approved-setup-hashes' +import { pickApprovedSetupHashes } from '../../../../../shared/worktree/creation/approved-setup-hashes' import { terminalImageViewerSupported } from '../../../terminal/launch/terminal-image-viewer-env' import { callerLaunchSource } from '../../../../agent-launch/agent-started-telemetry' import type { z } from 'zod' @@ -8,7 +8,7 @@ import { hostQualifiedRepoSelector, type RuntimeRepoSelector } from '../../../workspaces/catalog/runtime-repo-selector' -import type { WorktreeCreate } from '../../../../../shared/rpc-contract/worktree-create-params' +import type { WorktreeCreate } from '../../../../../shared/rpc-contract/workspaces/worktree-create-params' type WorktreeCreateParams = z.infer type ManagedWorktreeCreateArgs = Parameters[0] diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-create-exact-name.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree-create-exact-name.test.ts index 46c31e32ed7..3d4ecdf4b43 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-create-exact-name.test.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-create-exact-name.test.ts @@ -1,4 +1,4 @@ -import '../../unused-default-rpc-methods.test-fixture' +import '../../dispatch/testing/unused-default-rpc-methods.test-fixture' import { expect, it, vi } from 'vitest' import { RpcDispatcher } from '../../dispatcher' import type { OrcaRuntimeService } from '../../../orca-runtime' diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts b/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts index d5f43b17663..5b8d0796cf4 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts @@ -1,5 +1,5 @@ import { getLocalWorktreeCatalogVersion } from '../../../../workspaces/catalog/local-worktree-scan-generation' -import { WorktreeAdoptProvisionedRoot } from '../../../../../shared/rpc-contract/worktree-provisioned-root-params' +import { WorktreeAdoptProvisionedRoot } from '../../../../../shared/rpc-contract/workspaces/worktree-provisioned-root-params' import { defineMethod } from '../../core' export const WORKTREE_PROVISIONED_ROOT_METHOD = defineMethod({ diff --git a/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts similarity index 83% rename from src/main/runtime/rpc/worktree-rm-cli.integration.test.ts rename to src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts index fd04b199380..c5862a3bfbf 100644 --- a/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts @@ -5,36 +5,37 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' +import { OrcaRuntimeService } from '../../../orca-runtime' import { partialRuntimeStore, storeRepo, storeWorktreeMeta -} from '../orca-runtime-tests/runtime-store-partial-fixture' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import type { Repo } from '../../../shared/repo-types' -import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' +} from '../../../orca-runtime-tests/runtime-store-partial-fixture' +import type { WorktreeMeta } from '../../../../../shared/worktree/meta-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { HostWorktreeTarget } from '../../../../../shared/worktree/host-qualified-identity' -import * as appEnvironment from '../../../shared/app-environment' -import type { SshTarget } from '../../../shared/ssh-types' +import * as appEnvironment from '../../../../../shared/app-environment' +import type { SshTarget } from '../../../../../shared/ssh-types' -import { getRuntimeMetadataPath } from '../../../shared/runtime-bootstrap' +import { getRuntimeMetadataPath } from '../../../../../shared/runtime-bootstrap' -import { UnixSocketTransport } from './unix-socket-transport' -import { RpcDispatcher } from './dispatcher' -import { WORKTREE_METHODS } from './methods/workspaces/worktree' -import { STATUS_METHODS } from './methods/host-management/status' -import type { RpcRequest } from './core' -import { WorkspaceLifecycleQueue } from '../workspaces/lifecycle/workspace-lifecycle-queue' -import { installRealWorkerThreadChildProcesses } from '../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' -import { removeTree } from '../../../shared/windows-transient-lock-removal' +import { UnixSocketTransport } from '../../transports/unix-socket-transport' +import { RpcDispatcher } from '../../dispatcher' +import { WORKTREE_METHODS } from './worktree' +import { STATUS_METHODS } from '../host-management/status' +import type { RpcRequest } from '../../core' +import { WorkspaceLifecycleQueue } from '../../../workspaces/lifecycle/workspace-lifecycle-queue' +import { installRealWorkerThreadChildProcesses } from '../../../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' +import { removeTree } from '../../../../../shared/windows-transient-lock-removal' import { _resetPendingWorktreeRemovalsForTests, - _settlePendingWorktreeRemovalsForTests -} from '../../workspaces/removal/worktree-background-removal' + _settlePendingWorktreeRemovalsForTests, + loadWorktreeRemovalRecords +} from '../../../../workspaces/removal/worktree-background-removal' installRealWorkerThreadChildProcesses() -const cliPath = '../../../cli/index' +const cliPath = '../../../../../cli/index' const { main }: { main: (argv: string[], cwd: string) => Promise } = await import(cliPath) const exec = promisify(execFile) @@ -71,6 +72,7 @@ beforeEach(async () => { vi.spyOn(console, 'log').mockImplementation(() => {}) vi.spyOn(console, 'error').mockImplementation(() => {}) directory = await realpath(await mkdtemp(join(tmpdir(), 'orca-cli-rm-'))) + await loadWorktreeRemovalRecords(directory) repoPath = join(directory, 'repo') checkout = join(directory, 'checkout') id = `repo::${checkout}` diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-rm-recipe-removal.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree-rm-recipe-removal.test.ts index 969b7ca191c..9522c9bbef7 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-rm-recipe-removal.test.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-rm-recipe-removal.test.ts @@ -1,65 +1,9 @@ -import '../../unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { RpcDispatcher } from '../../dispatcher' -import { WORKTREE_METHODS } from './worktree' +import '../../dispatch/testing/unused-default-rpc-methods.test-fixture' +import { describe, expect, it } from 'vitest' import { classifyRuntimeLongPoll } from '../../server/runtime-rpc-long-poll' const WORKTREE_ID = 'repo-1::/repo/wt' -function makeRuntime(owned: boolean) { - const removeRecipeWorkspace = vi.fn().mockResolvedValue({ removed: true }) - const removeManagedWorktree = vi.fn().mockResolvedValue({}) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture implements every runtime method worktree.rm reaches. - const runtime = { - getRuntimeId: () => 'test-runtime', - listRepos: () => [{ id: 'repo-1', path: '/repo', executionHostId: 'local' }], - showManagedWorktree: vi.fn().mockResolvedValue({ id: WORKTREE_ID, hostId: 'local' }), - ownsRecipeWorkspaceRemoval: vi.fn().mockReturnValue(owned), - removeRecipeWorkspace, - removeManagedWorktree - } as unknown as OrcaRuntimeService - return { runtime, removeRecipeWorkspace, removeManagedWorktree } -} - -async function removeOverRpc(runtime: OrcaRuntimeService) { - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - return dispatcher.dispatch({ - id: 'req-1', - authToken: 'tok', - method: 'worktree.rm', - params: { - worktree: `id:${WORKTREE_ID}`, - hostId: 'runtime:env-a', - force: true, - destroyHost: true - } - }) -} - -describe('worktree.rm of a recipe-provisioned workspace', () => { - it('destroys the environment through the provisioning host instead of deleting locally', async () => { - const { runtime, removeRecipeWorkspace, removeManagedWorktree } = makeRuntime(true) - - const response = await removeOverRpc(runtime) - - expect(response).toMatchObject({ ok: true, result: { removed: true } }) - expect(removeRecipeWorkspace).toHaveBeenCalledWith( - expect.objectContaining({ worktree: `id:${WORKTREE_ID}`, hostId: 'runtime:env-a' }) - ) - expect(removeManagedWorktree).not.toHaveBeenCalled() - }) - - it('leaves workspaces without an owned recipe on the ordinary removal path', async () => { - const { runtime, removeRecipeWorkspace, removeManagedWorktree } = makeRuntime(false) - - await removeOverRpc(runtime) - - expect(removeRecipeWorkspace).not.toHaveBeenCalled() - expect(removeManagedWorktree).toHaveBeenCalled() - }) -}) - describe('worktree.rm long-poll admission', () => { const request = { id: 'req', authToken: 'tok', method: 'worktree.rm' } it('keeps a recipe workspace removal alive while its destroy runs', () => { diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-set-method.ts b/src/main/runtime/rpc/methods/workspaces/worktree-set-method.ts index 1f906db7f38..d4640b2e12a 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-set-method.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-set-method.ts @@ -1,5 +1,5 @@ -import { WorktreeSet } from '../../../../../shared/rpc-contract/worktree-params' -import { displayNameUpdatePinsLabel } from '../../../../../shared/worktree/display-name-provenance' +import { WorktreeSet } from '../../../../../shared/rpc-contract/workspaces/worktree-params' +import { displayNameUpdatePinsLabel } from '../../../../../shared/worktree/metadata/display-name-provenance' import { getWorkspaceStatusWarning } from '../../../../../shared/workspace-status-warning' import { defineMethod } from '../../core' diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-sleep-method.ts b/src/main/runtime/rpc/methods/workspaces/worktree-sleep-method.ts index b1d7beb95c7..3b57ab713c3 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-sleep-method.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-sleep-method.ts @@ -1,4 +1,4 @@ -import { WorktreeSleepParams } from '../../../../../shared/rpc-contract/worktree-params' +import { WorktreeSleepParams } from '../../../../../shared/rpc-contract/workspaces/worktree-params' import { defineMethod } from '../../core' export const WORKTREE_SLEEP_METHOD = defineMethod({ diff --git a/src/main/runtime/rpc/methods/workspaces/worktree.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree.test.ts index 4b4cf4ec6e1..719355d161b 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree.test.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree.test.ts @@ -3,7 +3,7 @@ import { RpcDispatcher } from '../../dispatcher' import type { RpcRequest } from '../../core' import type { OrcaRuntimeService } from '../../../orca-runtime' import { WORKTREE_METHODS } from './worktree' -import { createAutomationDispatchToken } from '../../../../automations/dispatch-tokens' +import { createAutomationDispatchToken } from '../../../../automations/ownership/dispatch-tokens' const repo = { id: 'repo-1', diff --git a/src/main/runtime/rpc/methods/workspaces/worktree.ts b/src/main/runtime/rpc/methods/workspaces/worktree.ts index 2f68f4a50b0..3030b8a9eff 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree.ts @@ -5,7 +5,7 @@ import { releaseAutomationWorkspaceProvenanceRequest, resolveAutomationWorkspaceProvenance, resolveClientAutomationWorkspaceProvenance -} from '../../../../automations/workspace-provenance' +} from '../../../../automations/ownership/workspace-provenance' import { getLocalWorktreeCatalogVersion } from '../../../../workspaces/catalog/local-worktree-scan-generation' import { getExplicitWorktreeIdSelector } from '../../../workspaces/catalog/runtime-worktree-selection' import { splitWorktreeId } from '../../../../../shared/worktree/id' @@ -15,11 +15,11 @@ import { defineMethod } from '../../core' import { buildManagedWorktreeCreateArgs, worktreeCreateRepoSelector } from './worktree-create-args' import { resolvePairedCallerHostId } from '../pairing/paired-caller-host-id' import { resolveRuntimeNavigationTarget } from '../../../../../shared/runtime-navigation' -import { resolveRpcWorkspaceCreatorProvenance } from '../../workspace-creator-context' +import { resolveRpcWorkspaceCreatorProvenance } from '../../callers/workspace-creator-context' import { WorktreeCreate, WorktreePrefetchCreateBase -} from '../../../../../shared/rpc-contract/worktree-create-params' +} from '../../../../../shared/rpc-contract/workspaces/worktree-create-params' import { WorktreeActivate, WorktreeForceDeleteBranch, @@ -32,12 +32,13 @@ import { WorktreeSortOrder, WorktreeTeardownMissingTerminalsParams, WorktreeResolveCallerParent -} from '../../../../../shared/rpc-contract/worktree-params' +} from '../../../../../shared/rpc-contract/workspaces/worktree-params' import { WORKTREE_CATALOG_METHODS } from './worktree-catalog-methods' import { WORKTREE_PROVISIONED_ROOT_METHOD } from './worktree-provisioned-root-method' -import { waitsForWorktreeRemoval } from '../../worktree-removal-marker-projection' +import { waitsForWorktreeRemoval } from '../../workspace-client-views/worktree-removal-marker-projection' import { queueWorkspaceDelete } from '../../../workspaces/lifecycle/workspace-lifecycle-commands' import { WORKTREE_SLEEP_METHOD } from './worktree-sleep-method' +import { WORKSPACE_CLEANUP_SCAN_METHOD } from './workspace-cleanup-scan-method' import { WORKTREE_SET_METHOD } from './worktree-set-method' import { runApprovedCreatedWorktreeSetup } from '../../../workspaces/creation/created-worktree-approved-setup' @@ -97,6 +98,7 @@ export const WORKTREE_METHODS = [ }) }), WORKTREE_SLEEP_METHOD, + WORKSPACE_CLEANUP_SCAN_METHOD, defineMethod({ name: 'worktree.activate', permission: 'workspace', diff --git a/src/main/runtime/rpc/mobile-clipboard-image-provenance.test.ts b/src/main/runtime/rpc/mobile-clipboard-image-provenance.test.ts deleted file mode 100644 index aa1709fcecb..00000000000 --- a/src/main/runtime/rpc/mobile-clipboard-image-provenance.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - hasMobileClipboardImagePath, - MOBILE_CLIPBOARD_IMAGE_PROVENANCE_MAX_ENTRIES, - MOBILE_CLIPBOARD_IMAGE_PROVENANCE_TTL_MS, - mobileClipboardImageProvenanceSizeForTest, - recordMobileClipboardImagePath, - resetMobileClipboardImageProvenanceForTest -} from './mobile-clipboard-image-provenance' - -describe('mobile clipboard image provenance', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-01-01T00:00:00Z')) - resetMobileClipboardImageProvenanceForTest() - }) - - afterEach(() => { - resetMobileClipboardImageProvenanceForTest() - vi.useRealTimers() - }) - - it('expires records without consuming them on repeated checks', () => { - recordMobileClipboardImagePath('device-a', '/tmp/image.png') - - expect(hasMobileClipboardImagePath('device-a', '/tmp/image.png')).toBe(true) - expect(hasMobileClipboardImagePath('device-a', '/tmp/image.png')).toBe(true) - vi.advanceTimersByTime(MOBILE_CLIPBOARD_IMAGE_PROVENANCE_TTL_MS + 1) - expect(hasMobileClipboardImagePath('device-a', '/tmp/image.png')).toBe(false) - expect(mobileClipboardImageProvenanceSizeForTest()).toBe(0) - }) - - it('evicts the oldest record at the global bound and supports test cleanup', () => { - for (let index = 0; index <= MOBILE_CLIPBOARD_IMAGE_PROVENANCE_MAX_ENTRIES; index++) { - recordMobileClipboardImagePath(`device-${index}`, `/tmp/image-${index}.png`) - vi.advanceTimersByTime(1) - } - - expect(mobileClipboardImageProvenanceSizeForTest()).toBe( - MOBILE_CLIPBOARD_IMAGE_PROVENANCE_MAX_ENTRIES - ) - expect(hasMobileClipboardImagePath('device-0', '/tmp/image-0.png')).toBe(false) - expect( - hasMobileClipboardImagePath( - `device-${MOBILE_CLIPBOARD_IMAGE_PROVENANCE_MAX_ENTRIES}`, - `/tmp/image-${MOBILE_CLIPBOARD_IMAGE_PROVENANCE_MAX_ENTRIES}.png` - ) - ).toBe(true) - - resetMobileClipboardImageProvenanceForTest() - expect(mobileClipboardImageProvenanceSizeForTest()).toBe(0) - }) -}) diff --git a/src/main/runtime/rpc/mobile-e2ee-outbound-memory-budget.test.ts b/src/main/runtime/rpc/mobile-e2ee-outbound-memory-budget.test.ts deleted file mode 100644 index 147b850619f..00000000000 --- a/src/main/runtime/rpc/mobile-e2ee-outbound-memory-budget.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createMobileE2EEOutboundMemoryBudget } from './mobile-e2ee-outbound-memory-budget' - -describe('mobile E2EE outbound memory budget', () => { - it('bounds aggregate queued frames and releases claims exactly once', () => { - const budget = createMobileE2EEOutboundMemoryBudget({ - maxQueuedBytes: 5, - maxQueuedFrames: 2 - }) - const first = budget.claimQueuedBytes(3) - const second = budget.claimQueuedBytes(2) - - expect(first).not.toBeNull() - expect(second).not.toBeNull() - expect(budget.claimQueuedBytes(0)).toBeNull() - expect(budget.evidence()).toMatchObject({ queuedBytes: 5, queuedFrames: 2 }) - - first?.() - first?.() - expect(budget.claimQueuedBytes(3)).not.toBeNull() - }) - - it('bounds prospective native buffering across registered sockets', () => { - let firstBuffered = 3 - let secondBuffered = 2 - const budget = createMobileE2EEOutboundMemoryBudget({ - maxBufferedBytes: 8, - maxSocketSources: 2 - }) - const first = budget.registerBufferedAmount(() => firstBuffered)! - const second = budget.registerBufferedAmount(() => secondBuffered)! - - expect(first.canSend(3)).toBe(true) - expect(second.canSend(4)).toBe(false) - expect(budget.registerBufferedAmount(() => 0)).toBeNull() - - first.release() - firstBuffered = 100 - secondBuffered = 0 - expect(second.canSend(8)).toBe(true) - expect(budget.evidence()).toMatchObject({ bufferedBytes: 0, sockets: 1 }) - }) -}) diff --git a/src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.test.ts b/src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.test.ts deleted file mode 100644 index eafbc441bbf..00000000000 --- a/src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { COMPRESSED_FRAMES_CLIENT_CAPABILITY } from '../../../shared/remote-runtime/e2ee/paired-e2ee-compressed-frame' -import { compressMobileE2EEV2Item } from './mobile-e2ee-v2-compressed-frame' - -const capable = [COMPRESSED_FRAMES_CLIENT_CAPABILITY] - -describe('compressMobileE2EEV2Item', () => { - it('leaves frames alone for phones without the capability and for small frames', () => { - const large = { kind: 'text' as const, plaintext: 'x'.repeat(4096) } - const small = { kind: 'text' as const, plaintext: '{"id":"1"}' } - - expect(compressMobileE2EEV2Item(large, [])).toBe(large) - expect(compressMobileE2EEV2Item(small, capable)).toBe(small) - }) - - it('sends plain frames to every phone while the rollback switch is set', () => { - const large = { kind: 'text' as const, plaintext: 'x'.repeat(4096) } - vi.stubEnv('ORCA_DISABLE_MOBILE_COMPRESSED_FRAMES', '1') - try { - expect(compressMobileE2EEV2Item(large, capable)).toBe(large) - } finally { - vi.unstubAllEnvs() - } - }) -}) diff --git a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.test.ts b/src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.test.ts deleted file mode 100644 index 12f4a70e49d..00000000000 --- a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import { deriveSharedKey } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' -import { - encodeMobileE2EEV2Transcript, - validateMobileE2EEV2Handshake, - type MobileE2EEV2Hello -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' -import { sealMobileE2EEV2Frame } from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' -import { - DesktopMobileE2EEV2Session, - MAX_MOBILE_E2EE_V2_TEXT_FRAME_BASE64_CHARACTERS -} from './mobile-e2ee-v2-desktop-session' - -const server = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1)) -const client = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2)) - -function hello(): MobileE2EEV2Hello { - return { - type: 'e2ee_hello', - v: 2, - clientPublicKeyB64: Buffer.from(client.publicKey).toString('base64'), - clientNonceB64: Buffer.from(new Uint8Array(32).fill(3)).toString('base64'), - capabilities: { framing: [2], payloadKinds: ['text', 'binary'] }, - context: { - protocol: 'orca-mobile-e2ee', - initiator: 'mobile', - responder: 'desktop', - transport: 'relay', - relayHostId: 'AbCdEf0123_-xyZ9' - } - } -} - -describe('desktop mobile E2EE v2 session', () => { - it('rejects oversized text frames before base64 decoding', () => { - const session = DesktopMobileE2EEV2Session.create({ - hello: hello(), - serverSecretKey: server.secretKey, - expectedContext: { transport: 'relay', relayHostId: 'AbCdEf0123_-xyZ9' }, - randomBytes: () => new Uint8Array(32).fill(4) - })! - const decode = vi.spyOn(Buffer, 'from') - - expect( - session.openText('A'.repeat(MAX_MOBILE_E2EE_V2_TEXT_FRAME_BASE64_CHARACTERS + 1)) - ).toBeNull() - expect(decode).not.toHaveBeenCalled() - decode.mockRestore() - }) - - it('creates a fresh ready message and opens exact-next auth counter zero', () => { - const clientHello = hello() - const session = DesktopMobileE2EEV2Session.create({ - hello: clientHello, - serverSecretKey: server.secretKey, - expectedContext: { transport: 'relay', relayHostId: 'AbCdEf0123_-xyZ9' }, - randomBytes: () => new Uint8Array(32).fill(4) - })! - const handshake = validateMobileE2EEV2Handshake(clientHello, session.ready)! - const schedule = deriveMobileE2EEV2KeySchedule({ - sharedSecret: deriveSharedKey(client.secretKey, server.publicKey), - transcript: encodeMobileE2EEV2Transcript(handshake), - clientNonce: handshake.clientNonce, - desktopNonce: handshake.desktopNonce - }) - const auth = JSON.stringify({ - type: 'e2ee_auth', - v: 2, - transcriptHashB64: session.transcriptHashB64, - deviceToken: 'token' - }) - const frame = sealMobileE2EEV2Frame({ - payload: new TextEncoder().encode(auth), - key: schedule.mobileToDesktopKey, - sessionId: schedule.sessionId, - direction: 'mobile-to-desktop', - payloadKind: 'text', - counter: 0n - }) - - expect(session.openText(Buffer.from(frame).toString('base64'))).toBe(auth) - expect(session.openText(Buffer.from(frame).toString('base64'))).toBeNull() - }) - - it('rejects a transport or relayHostId mismatch before deriving keys', () => { - expect( - DesktopMobileE2EEV2Session.create({ - hello: hello(), - serverSecretKey: server.secretKey, - expectedContext: { transport: 'direct' } - }) - ).toBeNull() - }) - - it('shares one outbound counter across text and binary', () => { - const session = DesktopMobileE2EEV2Session.create({ - hello: hello(), - serverSecretKey: server.secretKey, - expectedContext: { transport: 'relay', relayHostId: 'AbCdEf0123_-xyZ9' }, - randomBytes: () => new Uint8Array(32).fill(4) - })! - - const text = Buffer.from(session.sealText('one'), 'base64') - const binary = session.sealBinary(new Uint8Array([2])) - expect(text.subarray(16, 24)).toEqual(Buffer.alloc(8, 0)) - expect(binary.subarray(16, 24)).toEqual(Uint8Array.from(Buffer.from('0000000000000001', 'hex'))) - }) -}) diff --git a/src/main/runtime/rpc/mobile-socket-wiring.test.ts b/src/main/runtime/rpc/mobile-socket-wiring.test.ts deleted file mode 100644 index 73fb53cc5f5..00000000000 --- a/src/main/runtime/rpc/mobile-socket-wiring.test.ts +++ /dev/null @@ -1,387 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import type { WebSocket } from 'ws' -import { - encodeMobileE2EEV2Transcript, - validateMobileE2EEV2Handshake, - type MobileE2EEV2Hello, - type MobileE2EEV2Ready -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' -import { sealMobileE2EEV2Frame } from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' -import type { DeviceRegistry } from './server/pairing/device-registry' -import { - deriveSharedKey, - encrypt, - generateKeyPair -} from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' -import { - MobileSocketWiring, - type MobileSocketTransport, - type MobileSocketTransportMetadata -} from './mobile-socket-wiring' - -class FakeSocket { - readonly OPEN = 1 - readyState = this.OPEN - bufferedAmount = 0 - readonly sent: (string | Buffer)[] = [] - readonly send = vi.fn((data: string | Buffer) => this.sent.push(data)) - readonly close = vi.fn() -} - -class FakeTransport implements MobileSocketTransport { - private messageHandler: Parameters[0] | null = null - private closeHandler: Parameters[0] | null = null - readonly setClientId = vi.fn() - readonly terminateClientConnections = vi.fn(() => 0) - - onMessage(handler: Parameters[0]): void { - this.messageHandler = handler - } - - onConnectionClose(handler: Parameters[0]): void { - this.closeHandler = handler - } - - receive(ws: FakeSocket, message: string): void { - this.messageHandler?.(message, vi.fn(), ws as unknown as WebSocket) - } - - disconnect(ws: FakeSocket): void { - this.closeHandler?.(null, ws as unknown as WebSocket, false) - } -} - -function registryFor( - deviceId: string, - token: string, - scope: 'mobile' | 'runtime' = 'mobile' -): DeviceRegistry { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: transport tests use only credential lookups and last-seen writes. - return { - validateToken: (candidate: string) => - candidate === token - ? { - deviceId, - token, - name: 'Phone', - scope, - pairedAt: 1, - lastSeenAt: 0 - } - : null, - resolveAuthenticatedPrincipal: (principal: { deviceId: string; deviceToken?: string }) => - principal.deviceId === deviceId && principal.deviceToken === token - ? { deviceId, token, name: 'Phone', scope, pairedAt: 1, lastSeenAt: 0 } - : null, - updateLastSeen: vi.fn(), - updateLastSeenDeferred: vi.fn() - } as unknown as DeviceRegistry -} - -describe('MobileSocketWiring', () => { - it('preserves the legacy direct handshake, identity, and close cleanup', () => { - const desktop = generateKeyPair() - const phone = generateKeyPair() - const ws = new FakeSocket() - const transport = new FakeTransport() - const onText = vi.fn() - const onClose = vi.fn() - const wiring = new MobileSocketWiring({ - deviceRegistry: registryFor('device-1', 'valid-token', 'runtime'), - e2eeKeypair: { - publicKey: desktop.publicKey, - secretKey: desktop.secretKey, - publicKeyB64: Buffer.from(desktop.publicKey).toString('base64') - }, - onText, - onBinary: vi.fn(), - onClose - }) - wiring.attachTransport(transport) - - transport.receive( - ws, - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: Buffer.from(phone.publicKey).toString('base64') - }) - ) - const sharedKey = deriveSharedKey(phone.secretKey, desktop.publicKey) - transport.receive( - ws, - encrypt( - JSON.stringify({ - type: 'e2ee_auth', - deviceToken: 'valid-token', - clientCapabilities: ['session-tabs.close-intent.v1'] - }), - sharedKey - ) - ) - transport.receive(ws, encrypt('{"id":"rpc-1","method":"status.get"}', sharedKey)) - - // Socket bookkeeping keys on the device id; legacy rows keep their token as the client id. - expect(transport.setClientId).toHaveBeenCalledWith(ws, 'device-1') - expect(onText).toHaveBeenCalledOnce() - expect(onText.mock.calls[0]?.[0]).toMatchObject({ - device: { - deviceId: 'device-1', - deviceToken: 'valid-token', - scope: 'runtime', - clientId: 'valid-token', - credentialRevision: 0 - }, - clientCapabilities: ['session-tabs.close-intent.v1'], - transport: { transport: 'direct' } - }) - - transport.disconnect(ws) - expect(onClose).toHaveBeenCalledWith(expect.objectContaining({ ws }), false) - expect(wiring.channelCount).toBe(0) - expect(wiring.connectionCount).toBe(0) - }) - - it('reports other live sockets of the same device on close', () => { - const desktop = generateKeyPair() - const transport = new FakeTransport() - const onClose = vi.fn() - const wiring = new MobileSocketWiring({ - deviceRegistry: registryFor('device-1', 'valid-token'), - e2eeKeypair: { - publicKey: desktop.publicKey, - secretKey: desktop.secretKey, - publicKeyB64: Buffer.from(desktop.publicKey).toString('base64') - }, - onText: vi.fn(), - onBinary: vi.fn(), - onClose - }) - wiring.attachTransport(transport) - const sockets = [new FakeSocket(), new FakeSocket()] - for (const ws of sockets) { - const phone = generateKeyPair() - transport.receive( - ws, - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: Buffer.from(phone.publicKey).toString('base64') - }) - ) - transport.receive( - ws, - encrypt( - JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), - deriveSharedKey(phone.secretKey, desktop.publicKey) - ) - ) - } - - transport.disconnect(sockets[0]!) - expect(onClose).toHaveBeenLastCalledWith(expect.objectContaining({ ws: sockets[0] }), true) - transport.disconnect(sockets[1]!) - expect(onClose).toHaveBeenLastCalledWith(expect.objectContaining({ ws: sockets[1] }), false) - }) - - it('closes an unknown-token socket even when reporting the failure throws', () => { - const desktop = generateKeyPair() - const phone = generateKeyPair() - const ws = new FakeSocket() - const transport = new FakeTransport() - const notificationError = new Error('renderer exited') - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const onUnpairedDeviceAuthFailure = vi.fn(() => { - throw notificationError - }) - const wiring = new MobileSocketWiring({ - deviceRegistry: registryFor('device-1', 'valid-token'), - e2eeKeypair: { - publicKey: desktop.publicKey, - secretKey: desktop.secretKey, - publicKeyB64: Buffer.from(desktop.publicKey).toString('base64') - }, - onText: vi.fn(), - onBinary: vi.fn(), - onClose: vi.fn(), - onUnpairedDeviceAuthFailure - }) - wiring.attachTransport(transport) - - transport.receive( - ws, - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: Buffer.from(phone.publicKey).toString('base64') - }) - ) - const sharedKey = deriveSharedKey(phone.secretKey, desktop.publicKey) - expect(() => - transport.receive( - ws, - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'stale-token' }), sharedKey) - ) - ).not.toThrow() - - expect(onUnpairedDeviceAuthFailure).toHaveBeenCalledOnce() - expect(onUnpairedDeviceAuthFailure).toHaveBeenCalledWith({ transport: 'direct' }) - expect(consoleError).toHaveBeenCalledWith( - '[mobile] Failed to report unpaired-device auth failure:', - notificationError - ) - expect(transport.setClientId).not.toHaveBeenCalled() - expect(ws.close).toHaveBeenCalledWith(4001, 'Unauthorized') - expect(wiring.channelCount).toBe(0) - consoleError.mockRestore() - }) - - it('rejects a relay socket whose immutable relayDeviceId differs from E2EE identity', () => { - const desktop = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1)) - const phone = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2)) - const ws = new FakeSocket() - const transport = new FakeTransport() - const metadata: MobileSocketTransportMetadata = { - transport: 'relay', - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'outer-device', - basisConnId: 'connection-1', - credentialKind: 'invite' - } - const wiring = new MobileSocketWiring({ - deviceRegistry: registryFor('e2ee-device', 'valid-token'), - e2eeKeypair: { - publicKey: desktop.publicKey, - secretKey: desktop.secretKey, - publicKeyB64: Buffer.from(desktop.publicKey).toString('base64') - }, - onText: vi.fn(), - onBinary: vi.fn(), - onClose: vi.fn() - }) - wiring.attachTransport(transport, () => metadata) - const hello: MobileE2EEV2Hello = { - type: 'e2ee_hello', - v: 2, - clientPublicKeyB64: Buffer.from(phone.publicKey).toString('base64'), - clientNonceB64: Buffer.from(new Uint8Array(32).fill(3)).toString('base64'), - capabilities: { framing: [2], payloadKinds: ['text', 'binary'] }, - context: { - protocol: 'orca-mobile-e2ee', - initiator: 'mobile', - responder: 'desktop', - transport: 'relay', - relayHostId: metadata.relayHostId - } - } - transport.receive(ws, JSON.stringify(hello)) - const ready = JSON.parse(ws.sent[0]!.toString()) as MobileE2EEV2Ready - const handshake = validateMobileE2EEV2Handshake(hello, ready)! - const schedule = deriveMobileE2EEV2KeySchedule({ - sharedSecret: deriveSharedKey(phone.secretKey, desktop.publicKey), - transcript: encodeMobileE2EEV2Transcript(handshake), - clientNonce: handshake.clientNonce, - desktopNonce: handshake.desktopNonce - }) - const auth = sealMobileE2EEV2Frame({ - payload: new TextEncoder().encode( - JSON.stringify({ - type: 'e2ee_auth', - v: 2, - transcriptHashB64: Buffer.from(schedule.transcriptHash).toString('base64'), - deviceToken: 'valid-token' - }) - ), - key: schedule.mobileToDesktopKey, - sessionId: schedule.sessionId, - direction: 'mobile-to-desktop', - payloadKind: 'text', - counter: 0n - }) - transport.receive(ws, Buffer.from(auth).toString('base64')) - - expect(transport.setClientId).not.toHaveBeenCalled() - expect(ws.close).toHaveBeenCalledWith(4001, 'Unauthorized') - }) - - it('keeps post-auth v2 capability-shaped frames on the RPC path', () => { - const desktop = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1)) - const phone = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2)) - const ws = new FakeSocket() - const transport = new FakeTransport() - const onText = vi.fn() - const metadata: MobileSocketTransportMetadata = { - transport: 'relay', - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - basisConnId: 'connection-1', - credentialKind: 'resume' - } - const wiring = new MobileSocketWiring({ - deviceRegistry: registryFor('device-1', 'valid-token'), - e2eeKeypair: { - publicKey: desktop.publicKey, - secretKey: desktop.secretKey, - publicKeyB64: Buffer.from(desktop.publicKey).toString('base64') - }, - onText, - onBinary: vi.fn(), - onClose: vi.fn() - }) - wiring.attachTransport(transport, () => metadata) - const hello: MobileE2EEV2Hello = { - type: 'e2ee_hello', - v: 2, - clientPublicKeyB64: Buffer.from(phone.publicKey).toString('base64'), - clientNonceB64: Buffer.from(new Uint8Array(32).fill(3)).toString('base64'), - capabilities: { framing: [2], payloadKinds: ['text', 'binary'] }, - context: { - protocol: 'orca-mobile-e2ee', - initiator: 'mobile', - responder: 'desktop', - transport: 'relay', - relayHostId: metadata.relayHostId - } - } - transport.receive(ws, JSON.stringify(hello)) - const ready = JSON.parse(ws.sent[0]!.toString()) as MobileE2EEV2Ready - const handshake = validateMobileE2EEV2Handshake(hello, ready)! - const schedule = deriveMobileE2EEV2KeySchedule({ - sharedSecret: deriveSharedKey(phone.secretKey, desktop.publicKey), - transcript: encodeMobileE2EEV2Transcript(handshake), - clientNonce: handshake.clientNonce, - desktopNonce: handshake.desktopNonce - }) - const send = (value: unknown, counter: bigint): void => { - const frame = sealMobileE2EEV2Frame({ - payload: new TextEncoder().encode(JSON.stringify(value)), - key: schedule.mobileToDesktopKey, - sessionId: schedule.sessionId, - direction: 'mobile-to-desktop', - payloadKind: 'text', - counter - }) - transport.receive(ws, Buffer.from(frame).toString('base64')) - } - send( - { - type: 'e2ee_auth', - v: 2, - transcriptHashB64: Buffer.from(schedule.transcriptHash).toString('base64'), - deviceToken: 'valid-token' - }, - 0n - ) - const capabilityFrame = { - type: 'e2ee_client_capabilities', - v: 1, - clientCapabilities: ['agent-session.structured.v1'] - } - send(capabilityFrame, 1n) - send({ id: 'rpc-1', method: 'agentSession.history', params: {} }, 2n) - - expect(onText).toHaveBeenCalledTimes(2) - expect(onText.mock.calls[0]?.[0].clientCapabilities).toEqual([]) - expect(JSON.parse(onText.mock.calls[0]?.[1] ?? '')).toEqual(capabilityFrame) - expect(onText.mock.calls[1]?.[0].clientCapabilities).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/device-key-auth.test.ts b/src/main/runtime/rpc/mobile/device-key-auth.test.ts similarity index 87% rename from src/main/runtime/rpc/device-key-auth.test.ts rename to src/main/runtime/rpc/mobile/device-key-auth.test.ts index d1b56d9acd4..d032522bc0c 100644 --- a/src/main/runtime/rpc/device-key-auth.test.ts +++ b/src/main/runtime/rpc/mobile/device-key-auth.test.ts @@ -7,12 +7,12 @@ import { describe, expect, it, vi } from 'vitest' import { encodeDeviceProofMessage, type DeviceProofPurpose -} from '../../../shared/remote-runtime/pairing/device-key-proof' -import { DeviceRegistry } from './server/pairing/device-registry' -import { DEVICE_REGISTRY_FILENAME } from './server/pairing/mobile-pairing-files' -import { SimulatedMobileE2EEV2Peer } from '../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer' -import { registerSocketDeviceKey } from './server/runtime-rpc-device-key-registration' -import { generateKeyPair } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +} from '../../../../shared/remote-runtime/pairing/device-key-proof' +import { DeviceRegistry } from '../server/pairing/device-registry' +import { DEVICE_REGISTRY_FILENAME } from '../server/pairing/mobile-pairing-files' +import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer' +import { registerSocketDeviceKey } from '../server/runtime-rpc-device-key-registration' +import { generateKeyPair } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' import { MobileSocketWiring, type AuthenticatedMobileSocket, @@ -257,26 +257,4 @@ describe('device-key authentication (host)', () => { }) } }) - - it('answers registry_unavailable, never device_revoked, after loading a corrupt registry', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-device-key-')) - writeFileSync(join(userDataPath, DEVICE_REGISTRY_FILENAME), '[{"deviceId":') - const key = nacl.sign.keyPair() - const attempt = harness(new DeviceRegistry(userDataPath)).connect((hash) => ({ - deviceId: 'keyed', - deviceProofB64: sign(key, 'auth', hash) - })) - expect(attempt.reply).toEqual({ type: 'e2ee_error', error: { code: 'registry_unavailable' } }) - }) - - it('never answers device_revoked for a row that exists without a key', () => { - const registry = freshRegistry() - const legacy = registry.addDevice('Phone', 'mobile') - const key = nacl.sign.keyPair() - const attempt = harness(registry).connect((hash) => ({ - deviceId: legacy.deviceId, - deviceProofB64: sign(key, 'auth', hash) - })) - expect(attempt.reply).toEqual({ type: 'e2ee_error', error: { code: 'bad_auth' } }) - }) }) diff --git a/src/main/runtime/rpc/mobile/e2ee/e2ee-channel-text-backpressure.test.ts b/src/main/runtime/rpc/mobile/e2ee/e2ee-channel-text-backpressure.test.ts new file mode 100644 index 00000000000..14de842631b --- /dev/null +++ b/src/main/runtime/rpc/mobile/e2ee/e2ee-channel-text-backpressure.test.ts @@ -0,0 +1,154 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { WebSocket } from 'ws' +import type { RpcBinarySendResult } from '../../transports/rpc-binary-sender' +import { E2EEChannel, type E2EEChannelOptions } from './e2ee-channel' +import { + deriveSharedKey, + decrypt, + decryptBytes, + encrypt, + generateKeyPair +} from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { createMobileE2EEOutboundMemoryBudget } from './mobile-e2ee-outbound-memory-budget' + +const trackMock = vi.hoisted(() => vi.fn()) + +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) + +// Legacy terminal.subscribe has no seq/resync: congestion must queue text and binary replies in order, never drop them. + +function publicKeyToBase64(key: Uint8Array): string { + return Buffer.from(key).toString('base64') +} + +function createMockWs() { + const sent: (string | Buffer)[] = [] + return { + OPEN: 1 as const, + readyState: 1, + bufferedAmount: 0, + send: vi.fn((data: string | Buffer) => { + sent.push(data) + }), + close: vi.fn(), + sent + } +} + +function setup(overrides?: Partial) { + const serverKeys = generateKeyPair() + const clientKeys = generateKeyPair() + const ws = createMockWs() + const onError = vi.fn() + const channel = new E2EEChannel(ws as unknown as WebSocket, { + serverSecretKey: serverKeys.secretKey, + resolveAuthenticatedDevice: (token) => + token === 'valid-token' + ? { + deviceId: 'device-1', + deviceToken: token, + scope: 'mobile', + clientId: token, + callerFingerprint: 'test-fingerprint', + credentialRevision: 0 + } + : null, + onReady: vi.fn(), + onError, + ...overrides + }) + const sharedKey = deriveSharedKey(clientKeys.secretKey, serverKeys.publicKey) + channel.handleRawMessage( + JSON.stringify({ type: 'e2ee_hello', publicKeyB64: publicKeyToBase64(clientKeys.publicKey) }) + ) + channel.handleRawMessage( + encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), sharedKey) + ) + return { channel, ws, sharedKey, onError } +} + +function emitReply(ctx: ReturnType, payload: string): void { + ctx.channel.onMessage((_plaintext, encryptedReply) => { + encryptedReply(payload) + }) + ctx.channel.handleRawMessage(encrypt('{"id":"x","method":"status.get"}', ctx.sharedKey)) +} + +describe('E2EE text reply backpressure', () => { + beforeEach(() => { + vi.useFakeTimers() + trackMock.mockReset() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('rejects aggregate queue growth across independently backpressured sockets', () => { + const outboundMemoryBudget = createMobileE2EEOutboundMemoryBudget({ + maxBufferedBytes: 1_000, + maxQueuedBytes: 150, + maxQueuedFrames: 10 + }) + const first = setup({ outboundMemoryBudget }) + const second = setup({ outboundMemoryBudget }) + first.ws.bufferedAmount = 1_001 + second.ws.bufferedAmount = 1_001 + + emitReply(first, 'x'.repeat(40)) + emitReply(second, 'x'.repeat(40)) + + expect(first.onError).not.toHaveBeenCalled() + expect(second.onError).toHaveBeenCalledWith(1013, 'Outbound reply buffer overflow') + expect(trackMock).toHaveBeenCalledWith('remote_outbound_budget_close', { + emitter: 'queue' + }) + first.channel.destroy() + expect(outboundMemoryBudget.evidence().queuedBytes).toBe(0) + }) +}) + +describe('E2EE legacy binary reply backpressure', () => { + beforeEach(() => { + vi.useFakeTimers() + trackMock.mockReset() + }) + afterEach(() => { + vi.useRealTimers() + }) + + function decodeSent(ctx: ReturnType, frame: string | Buffer): string { + return typeof frame === 'string' + ? decrypt(frame, ctx.sharedKey)! + : `binary:${Buffer.from(decryptBytes(new Uint8Array(frame), ctx.sharedKey)!).toString()}` + } + + // Legacy binary terminal frames lack gap detection; loss or reordering corrupts the phone screen. + it('holds binary replies in one order with text while the outbound budget is full', () => { + const outboundMemoryBudget = createMobileE2EEOutboundMemoryBudget({ maxBufferedBytes: 1_000 }) + const ctx = setup({ outboundMemoryBudget }) + const baseline = ctx.ws.sent.length + ctx.ws.bufferedAmount = 1_001 + const accepted: RpcBinarySendResult[] = [] + + ctx.channel.onMessage((_plaintext, encryptedReply, encryptedBinaryReply) => { + encryptedReply('{"seq":1}') + accepted.push(encryptedBinaryReply(Buffer.from('2'))) + encryptedReply('{"seq":3}') + accepted.push(encryptedBinaryReply(Buffer.from('4'))) + }) + ctx.channel.handleRawMessage(encrypt('{"id":"x","method":"terminal.subscribe"}', ctx.sharedKey)) + expect(ctx.ws.sent.length).toBe(baseline) + + ctx.ws.bufferedAmount = 0 + vi.runOnlyPendingTimers() + + expect(accepted).toEqual([true, true]) + expect(ctx.ws.sent.slice(baseline).map((frame) => decodeSent(ctx, frame))).toEqual([ + '{"seq":1}', + 'binary:2', + '{"seq":3}', + 'binary:4' + ]) + expect(ctx.onError).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/rpc/e2ee-channel-v2.test.ts b/src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts similarity index 77% rename from src/main/runtime/rpc/e2ee-channel-v2.test.ts rename to src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts index e173857f1d5..ec2f99d97a6 100644 --- a/src/main/runtime/rpc/e2ee-channel-v2.test.ts +++ b/src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts @@ -6,15 +6,15 @@ import { validateMobileE2EEV2Handshake, type MobileE2EEV2Hello, type MobileE2EEV2Ready -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' +} from '../../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' import { openMobileE2EEV2Frame, sealMobileE2EEV2Frame -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' -import { deriveSharedKey } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import type { RpcBinarySendResult } from './rpc-binary-sender' +} from '../../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' +import { deriveSharedKey } from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import type { RpcBinarySendResult } from '../../transports/rpc-binary-sender' import { E2EEChannel } from './e2ee-channel' -import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' +import { deriveMobileE2EEV2KeySchedule } from '../../../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' const server = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1)) const client = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2)) @@ -145,52 +145,6 @@ describe('E2EEChannel v2', () => { beforeEach(() => vi.useFakeTimers()) afterEach(() => vi.useRealTimers()) - it('forwards post-auth capability-shaped frames without mutating authenticated capabilities', () => { - const ctx = setup() - const { schedule } = startV2(ctx) - const onMessage = vi.fn() - ctx.channel.onMessage(onMessage) - authenticate(ctx, schedule) - - const capabilityFrame = JSON.stringify({ - type: 'e2ee_client_capabilities', - v: 1, - clientCapabilities: ['agent-session.structured.v1'] - }) - ctx.channel.handleRawMessage(clientText(capabilityFrame, schedule, 1n)) - - expect(ctx.channel.capabilitySource.current).toEqual([]) - expect(onMessage).toHaveBeenCalledOnce() - expect(onMessage.mock.calls[0]?.[0]).toBe(capabilityFrame) - }) - - it('rejects legacy downgrade and runtime-only capability metadata when mobile v2 is required', () => { - const legacy = setup() - legacy.channel.handleRawMessage( - JSON.stringify({ type: 'e2ee_hello', publicKeyB64: 'legacy-key' }) - ) - expect(legacy.onError).toHaveBeenCalledWith(4001, 'E2EE v2 required') - - const ctx = setup() - const { schedule } = startV2(ctx) - const transcriptHashB64 = Buffer.from(schedule.transcriptHash).toString('base64') - ctx.channel.handleRawMessage( - clientText( - JSON.stringify({ - type: 'e2ee_auth', - v: 2, - transcriptHashB64, - deviceToken: 'valid-token', - clientCapabilities: ['session-tabs.close-intent.v1'] - }), - schedule, - 0n - ) - ) - expect(ctx.resolveAuthenticatedDevice).not.toHaveBeenCalled() - expect(ctx.onError).toHaveBeenCalledWith(4001, 'Invalid e2ee_auth') - }) - it('rejects a captured authenticated mutating trace on a fresh socket', () => { const first = setup() const firstHandshake = startV2(first) diff --git a/src/main/runtime/rpc/e2ee-channel.ts b/src/main/runtime/rpc/mobile/e2ee/e2ee-channel.ts similarity index 95% rename from src/main/runtime/rpc/e2ee-channel.ts rename to src/main/runtime/rpc/mobile/e2ee/e2ee-channel.ts index 526cb1b5d4b..84d91edf2bb 100644 --- a/src/main/runtime/rpc/e2ee-channel.ts +++ b/src/main/runtime/rpc/mobile/e2ee/e2ee-channel.ts @@ -1,12 +1,12 @@ // Keep E2EE framing outside transport-independent plaintext RPC handlers. import type { WebSocket } from 'ws' -import { PAIRED_E2EE_HANDSHAKE_DEADLINE_MS } from '../../../shared/remote-runtime/e2ee/paired-e2ee-handshake-deadline' +import { PAIRED_E2EE_HANDSHAKE_DEADLINE_MS } from '../../../../../shared/remote-runtime/e2ee/paired-e2ee-handshake-deadline' import { deriveSharedKey, encrypt, decrypt, decryptBytes -} from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +} from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' import { DesktopMobileE2EEV2Session, type DesktopMobileE2EEV2Context @@ -24,13 +24,13 @@ import { trackMobileE2EEOutboundBudgetClose, type MobileE2EEOutboundBudgetEmitter } from './mobile-e2ee-outbound-admission' -import { parseRemoteRuntimeJsonText } from '../../../shared/remote-runtime/requests/remote-runtime-request-frames' +import { parseRemoteRuntimeJsonText } from '../../../../../shared/remote-runtime/requests/remote-runtime-request-frames' import type { MobileE2EEOutboundMemoryBudget } from './mobile-e2ee-outbound-memory-budget' import { MobileE2EEDesktopOutboundOwner } from './mobile-e2ee-desktop-outbound-owner' import { createLegacyReplySenders } from './mobile-e2ee-legacy-reply-senders' -import { RuntimeClientCapabilities } from './runtime-client-capabilities' -import type * as RpcBinary from './rpc-binary-sender' -import type { E2EEAuthenticatedDevice } from './server/mobile-e2ee-authenticated-device' +import { RuntimeClientCapabilities } from '../../callers/runtime-client-capabilities' +import type * as RpcBinary from '../../transports/rpc-binary-sender' +import type { E2EEAuthenticatedDevice } from '../../server/mobile-e2ee-authenticated-device' const MAX_CONSECUTIVE_DECRYPT_FAILURES = 5 diff --git a/src/main/runtime/rpc/mobile-e2ee-auth-validation.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-auth-validation.ts similarity index 95% rename from src/main/runtime/rpc/mobile-e2ee-auth-validation.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-auth-validation.ts index f6aaf5f2b89..89bbef5c4ac 100644 --- a/src/main/runtime/rpc/mobile-e2ee-auth-validation.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-auth-validation.ts @@ -1,10 +1,10 @@ import type { DesktopMobileE2EEV2Session } from './mobile-e2ee-v2-desktop-session' -import { publicKeyFromBase64 } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { parseRemoteRuntimeJsonText } from '../../../shared/remote-runtime/requests/remote-runtime-request-frames' +import { publicKeyFromBase64 } from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { parseRemoteRuntimeJsonText } from '../../../../../shared/remote-runtime/requests/remote-runtime-request-frames' import { isDeviceProofB64, verifyDeviceProof -} from '../../../shared/remote-runtime/pairing/device-key-proof' +} from '../../../../../shared/remote-runtime/pairing/device-key-proof' export type ClassifiedE2EEAuth = | { kind: 'token'; deviceToken: string; clientCapabilities?: unknown } diff --git a/src/main/runtime/rpc/mobile-e2ee-desktop-outbound-owner.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-desktop-outbound-owner.ts similarity index 91% rename from src/main/runtime/rpc/mobile-e2ee-desktop-outbound-owner.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-desktop-outbound-owner.ts index c1d968e81ca..52d740f4a57 100644 --- a/src/main/runtime/rpc/mobile-e2ee-desktop-outbound-owner.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-desktop-outbound-owner.ts @@ -1,7 +1,7 @@ import type { WebSocket } from 'ws' -import type { WsOutboundBackpressureQueue } from '../../../shared/ws-outbound-backpressure-queue' +import type { WsOutboundBackpressureQueue } from '../../../../../shared/ws-outbound-backpressure-queue' import { createLegacyMobileE2EEReplyQueue } from './mobile-e2ee-outbound-admission' -import { encryptBytes } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { encryptBytes } from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' import { createDesktopMobileE2EEV2OutboundQueue, desktopMobileE2EEV2OutboundItemBytes, @@ -13,8 +13,8 @@ import { type MobileE2EEOutboundMemoryBudget, type MobileE2EEOutboundSocketMemory } from './mobile-e2ee-outbound-memory-budget' -import type { RpcBinarySendOptions } from './rpc-binary-sender' -import type { RuntimeClientCapabilities } from './runtime-client-capabilities' +import type { RpcBinarySendOptions } from '../../transports/rpc-binary-sender' +import type { RuntimeClientCapabilities } from '../../callers/runtime-client-capabilities' import { compressMobileE2EEV2Item } from './mobile-e2ee-v2-compressed-frame' export class MobileE2EEDesktopOutboundOwner { diff --git a/src/main/runtime/rpc/mobile-e2ee-legacy-reply-senders.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-legacy-reply-senders.ts similarity index 89% rename from src/main/runtime/rpc/mobile-e2ee-legacy-reply-senders.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-legacy-reply-senders.ts index 0536018dd09..d35862ec470 100644 --- a/src/main/runtime/rpc/mobile-e2ee-legacy-reply-senders.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-legacy-reply-senders.ts @@ -1,11 +1,11 @@ import type { WebSocket } from 'ws' -import { encrypt } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { encrypt } from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' import type { MobileE2EEDesktopOutboundOwner } from './mobile-e2ee-desktop-outbound-owner' import { isMobileE2EEBinaryPayloadWithinLimit, isMobileE2EETextPayloadWithinLimit } from './mobile-e2ee-outbound-admission' -import type { RpcBinarySender } from './rpc-binary-sender' +import type { RpcBinarySender } from '../../transports/rpc-binary-sender' /** Reply senders for one legacy-framed request. */ export function createLegacyReplySenders(args: { diff --git a/src/main/runtime/rpc/mobile-e2ee-outbound-admission.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-outbound-admission.ts similarity index 90% rename from src/main/runtime/rpc/mobile-e2ee-outbound-admission.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-outbound-admission.ts index f635a8d179a..e90b2a514f5 100644 --- a/src/main/runtime/rpc/mobile-e2ee-outbound-admission.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-outbound-admission.ts @@ -2,17 +2,17 @@ import type { WebSocket } from 'ws' import { createWsOutboundBackpressureQueue, type WsOutboundBackpressureQueue -} from '../../../shared/ws-outbound-backpressure-queue' +} from '../../../../../shared/ws-outbound-backpressure-queue' import { REMOTE_RUNTIME_MAX_OUTBOUND_BINARY_FRAME_BYTES, REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' +} from '../../../../../shared/remote-runtime/remote-runtime-memory-limits' import type { MobileE2EEOutboundMemoryBudget, MobileE2EEOutboundSocketMemory } from './mobile-e2ee-outbound-memory-budget' -import type { EventProps } from '../../../shared/telemetry-event-classification' -import { track } from '../../telemetry/client' +import type { EventProps } from '../../../../../shared/telemetry-event-classification' +import { track } from '../../../../telemetry/client' export type MobileE2EEOutboundBudgetEmitter = EventProps<'remote_outbound_budget_close'>['emitter'] diff --git a/src/main/runtime/rpc/mobile-e2ee-outbound-memory-budget.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-outbound-memory-budget.ts similarity index 100% rename from src/main/runtime/rpc/mobile-e2ee-outbound-memory-budget.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-outbound-memory-budget.ts diff --git a/src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-compressed-frame.ts similarity index 87% rename from src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-compressed-frame.ts index 0b76d7afc6c..55095361f6a 100644 --- a/src/main/runtime/rpc/mobile-e2ee-v2-compressed-frame.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-compressed-frame.ts @@ -4,10 +4,10 @@ import { COMPRESSED_FRAME_MIN_BYTES, compressedFramesDisabled, encodeCompressedFrame -} from '../../../shared/remote-runtime/e2ee/paired-e2ee-compressed-frame' -import type { RuntimeCapability } from '../../../shared/protocol-version' +} from '../../../../../shared/remote-runtime/e2ee/paired-e2ee-compressed-frame' +import type { RuntimeCapability } from '../../../../../shared/protocol-version' import type { DesktopMobileE2EEV2OutboundItem } from './mobile-e2ee-v2-desktop-outbound' -import type { RpcBinarySendOptions } from './rpc-binary-sender' +import type { RpcBinarySendOptions } from '../../transports/rpc-binary-sender' /** Gzips large text, and binary its sender marked compressible, for clients that read compressed frames. */ export function compressMobileE2EEV2Item( diff --git a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-inbound.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-inbound.ts similarity index 100% rename from src/main/runtime/rpc/mobile-e2ee-v2-desktop-inbound.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-inbound.ts diff --git a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-outbound.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-outbound.ts similarity index 97% rename from src/main/runtime/rpc/mobile-e2ee-v2-desktop-outbound.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-outbound.ts index e0c3068e3f8..046519a098c 100644 --- a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-outbound.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-outbound.ts @@ -2,7 +2,7 @@ import type { WebSocket } from 'ws' import { createWsOutboundBackpressureQueue, type WsOutboundBackpressureQueue -} from '../../../shared/ws-outbound-backpressure-queue' +} from '../../../../../shared/ws-outbound-backpressure-queue' import type { DesktopMobileE2EEV2Session } from './mobile-e2ee-v2-desktop-session' import { mobileE2EEBinaryPayloadAdmissionBytes, diff --git a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.ts b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-session.ts similarity index 91% rename from src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.ts rename to src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-session.ts index 6aa112f6e07..5b8f598db65 100644 --- a/src/main/runtime/rpc/mobile-e2ee-v2-desktop-session.ts +++ b/src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-session.ts @@ -5,14 +5,14 @@ import { type MobileE2EETransport, type MobileE2EEV2Hello, type MobileE2EEV2Ready -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' +} from '../../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' import { openMobileE2EEV2Frame, sealMobileE2EEV2Frame -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' -import { deriveSharedKey } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' -import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +} from '../../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' +import { deriveSharedKey } from '../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { deriveMobileE2EEV2KeySchedule } from '../../../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' +import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../../shared/remote-runtime/remote-runtime-memory-limits' const MOBILE_E2EE_V2_FRAME_OVERHEAD_BYTES = 82 export const MAX_MOBILE_E2EE_V2_TEXT_FRAME_BASE64_CHARACTERS = diff --git a/src/main/runtime/rpc/remote-runtime-client-framing.integration.test.ts b/src/main/runtime/rpc/mobile/e2ee/remote-runtime-client-framing.integration.test.ts similarity index 93% rename from src/main/runtime/rpc/remote-runtime-client-framing.integration.test.ts rename to src/main/runtime/rpc/mobile/e2ee/remote-runtime-client-framing.integration.test.ts index 46464cb59b7..65bc5bcc8a8 100644 --- a/src/main/runtime/rpc/remote-runtime-client-framing.integration.test.ts +++ b/src/main/runtime/rpc/mobile/e2ee/remote-runtime-client-framing.integration.test.ts @@ -5,15 +5,15 @@ import nacl from 'tweetnacl' import { WebSocketServer, type WebSocket } from 'ws' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { E2EEChannel } from './e2ee-channel' -import { sendRemoteRuntimeRequestOnSocket } from '../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { createRemoteRuntimeClientHandshake } from '../../../shared/remote-runtime/remote-runtime-client-framing' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { createRemoteRuntimeClientHandshake } from '../../../../../shared/remote-runtime/remote-runtime-client-framing' import { configureRemoteRuntimeE2EEV2HostLatch, REMOTE_RUNTIME_E2EE_V2_HOSTS_FILENAME -} from '../../../shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch' -import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' +} from '../../../../../shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch' +import type { PairedRuntimeConnection } from '../../../../../shared/remote-runtime/pairing/paired-runtime-connection' import type * as AuthValidation from './mobile-e2ee-auth-validation' -import { E2EE_V2_TOKEN_CAPABILITIES_RUNTIME_CAPABILITY } from '../../../shared/remote-runtime/pairing/device-key-capability' +import { E2EE_V2_TOKEN_CAPABILITIES_RUNTIME_CAPABILITY } from '../../../../../shared/remote-runtime/pairing/device-key-capability' // Hosts released between v2 and capability-carrying v2 token auth refused the extra field. const TOKEN_FOR_HOST_WITHOUT_V2_TOKEN_CAPABILITIES = 'device-token-v2-exact' diff --git a/src/main/runtime/rpc/mobile-socket-wiring.ts b/src/main/runtime/rpc/mobile/mobile-socket-wiring.ts similarity index 91% rename from src/main/runtime/rpc/mobile-socket-wiring.ts rename to src/main/runtime/rpc/mobile/mobile-socket-wiring.ts index 694abee4995..2d506891c55 100644 --- a/src/main/runtime/rpc/mobile-socket-wiring.ts +++ b/src/main/runtime/rpc/mobile/mobile-socket-wiring.ts @@ -1,17 +1,17 @@ -import type { RuntimeClientCapabilities } from './runtime-client-capabilities' +import type { RuntimeClientCapabilities } from '../callers/runtime-client-capabilities' import { randomBytes } from 'node:crypto' import type { WebSocket } from 'ws' -import type { DeviceEntry } from './server/pairing/device-entry' -import type { DeviceRegistry } from './server/pairing/device-registry' -import { EPHEMERAL_DEVICE_SWEEP_INTERVAL_MS } from './server/pairing/ephemeral-device-rows' -import { devicePrincipalOf } from './server/pairing/device-principal' -import type { E2EEKeypair } from './server/pairing/e2ee-keypair' -import { E2EEChannel } from './e2ee-channel' -import type { E2EEAuthenticatedDevice } from './server/mobile-e2ee-authenticated-device' -import { createMobileE2EEOutboundMemoryBudget } from './mobile-e2ee-outbound-memory-budget' -import type { RuntimeCapability } from '../../../shared/protocol-version' -import type { RpcBinarySender } from './rpc-binary-sender' -import type { NetworkSourceClass } from './network-source-class' +import type { DeviceEntry } from '../server/pairing/device-entry' +import type { DeviceRegistry } from '../server/pairing/device-registry' +import { EPHEMERAL_DEVICE_SWEEP_INTERVAL_MS } from '../server/pairing/ephemeral-device-rows' +import { devicePrincipalOf } from '../server/pairing/device-principal' +import type { E2EEKeypair } from '../server/pairing/e2ee-keypair' +import { E2EEChannel } from './e2ee/e2ee-channel' +import type { E2EEAuthenticatedDevice } from '../server/mobile-e2ee-authenticated-device' +import { createMobileE2EEOutboundMemoryBudget } from './e2ee/mobile-e2ee-outbound-memory-budget' +import type { RuntimeCapability } from '../../../../shared/protocol-version' +import type { RpcBinarySender } from '../transports/rpc-binary-sender' +import type { NetworkSourceClass } from '../transports/websocket/source-admission/network-source-class' type MobileSocketPayload = string | Uint8Array diff --git a/src/main/runtime/rpc/unpaired-device-auth-throttle.ts b/src/main/runtime/rpc/mobile/unpaired-device-auth-throttle.ts similarity index 100% rename from src/main/runtime/rpc/unpaired-device-auth-throttle.ts rename to src/main/runtime/rpc/mobile/unpaired-device-auth-throttle.ts diff --git a/src/main/runtime/rpc/network-source-class.test.ts b/src/main/runtime/rpc/network-source-class.test.ts deleted file mode 100644 index 0457e8405f3..00000000000 --- a/src/main/runtime/rpc/network-source-class.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { classifyNetworkSource, networkSourceKey } from './network-source-class' - -describe('classifyNetworkSource', () => { - it.each([ - ['127.0.0.1', 'loopback'], - ['127.8.9.10', 'loopback'], - ['::1', 'loopback'], - ['::ffff:127.0.0.1', 'loopback'], - ['10.1.2.3', 'private'], - ['172.16.0.1', 'private'], - ['172.31.255.254', 'private'], - ['192.168.1.20', 'private'], - ['169.254.10.10', 'private'], - ['::ffff:192.168.1.20', 'private'], - ['::FFFF:10.0.0.1', 'private'], - ['fd12:3456:789a::1', 'private'], - ['fe80::1', 'private'], - ['fe80::1%en0', 'private'], - ['100.64.0.1', 'tailnet'], - ['100.127.255.254', 'tailnet'], - ['::ffff:100.100.100.100', 'tailnet'], - ['fd7a:115c:a1e0::1', 'tailnet'], - ['fd7a:115c:a1e0:ab12:4843:cd96:6258:b240', 'tailnet'], - ['fd7a:115c:a1e1::1', 'private'], - ['8.8.8.8', 'public'], - ['172.32.0.1', 'public'], - ['100.128.0.1', 'public'], - ['192.169.0.1', 'public'], - ['::ffff:203.0.113.9', 'public'], - ['2001:4860:4860::8888', 'public'] - ])('%s is %s', (address, expected) => { - expect(classifyNetworkSource(address)).toBe(expected) - }) -}) - -describe('networkSourceKey', () => { - it('keys IPv6 by /64', () => { - expect(networkSourceKey('2001:db8:1:2:aaaa::1')).toBe('2001:db8:1:2::/64') - expect(networkSourceKey('2001:DB8:1:2:bbbb:cccc:dddd:eeee')).toBe('2001:db8:1:2::/64') - expect(networkSourceKey('2001:db8::1')).toBe('2001:db8:0:0::/64') - expect(networkSourceKey('64:ff9b::192.0.2.1')).toBe('64:ff9b:0:0::/64') - }) -}) diff --git a/src/main/runtime/rpc/orcad-feature-readiness.test.ts b/src/main/runtime/rpc/orcad-feature-readiness.test.ts deleted file mode 100644 index cfa8a9a0e3b..00000000000 --- a/src/main/runtime/rpc/orcad-feature-readiness.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - installOrcadFeatureReadiness, - ORCAD_FEATURES, - rpcMethodFeatureWait -} from './orcad-feature-readiness' - -// No local readiness reset: the shared vitest setup must restore it (asserted below). -afterEach(() => { - vi.useRealTimers() -}) - -describe('OrcadFeatureReadiness', () => { - it('adds no await for open or undeclared features, so ungated dispatch starts synchronously', () => { - expect(rpcMethodFeatureWait([])).toBeNull() - expect(rpcMethodFeatureWait(['accounts'])).toBeNull() - const readiness = installOrcadFeatureReadiness() - expect(rpcMethodFeatureWait([])).toBeNull() - readiness.open('accounts') - expect(rpcMethodFeatureWait(['accounts'])).toBeNull() - }) - - it('starts with every feature closed under orcad and waits for all a method names', async () => { - const readiness = installOrcadFeatureReadiness() - expect(ORCAD_FEATURES.every((feature) => !readiness.isOpen(feature))).toBe(true) - let settled = false - const wait = rpcMethodFeatureWait(['accounts', 'orchestration'])?.then(() => { - settled = true - }) - readiness.open('accounts') - await Promise.resolve() - expect(settled).toBe(false) - readiness.open('orchestration') - await wait - expect(settled).toBe(true) - }) - - it('refuses with runtime_unavailable after the bound and leaves no timer behind', async () => { - vi.useFakeTimers() - installOrcadFeatureReadiness() - const wait = rpcMethodFeatureWait(['sessionSearch'], [], 50) - const refused = expect(wait).rejects.toThrow('runtime_unavailable') - await vi.advanceTimersByTimeAsync(50) - await refused - expect(vi.getTimerCount()).toBe(0) - }) - - // The shared setup resets after every test; these two run in order in one worker. - it('may leave latches closed when a test stops partway', () => { - installOrcadFeatureReadiness() - expect(rpcMethodFeatureWait(['accounts'])).not.toBeNull() - }) - - it('finds every latch open again in the next test', () => { - expect(rpcMethodFeatureWait(['accounts'])).toBeNull() - }) -}) diff --git a/src/main/runtime/rpc/orchestration-11745-regression-verification.test.ts b/src/main/runtime/rpc/orchestration-11745-regression-verification.test.ts deleted file mode 100644 index c0a6b3e576e..00000000000 --- a/src/main/runtime/rpc/orchestration-11745-regression-verification.test.ts +++ /dev/null @@ -1,400 +0,0 @@ -// Pin #11745 through state as well as replies: refused calls must not mutate graphs or fence legitimate coordinators. -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import SyncDatabase from '../../sqlite/sync-database' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - COORDINATOR_HANDLE, - counts, - createHarness, - currentEvidence, - CURRENT_COORDINATOR_HANDLE, - CURRENT_COORDINATOR_PANE, - CURRENT_WORKER_HANDLE, - CURRENT_WORKER_PANE, - evidence, - request, - type LegacyCompatibilityDispatcherHarness -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' - -const tempDirs: string[] = [] -const databases: OrchestrationDb[] = [] - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() - for (const database of databases.splice(0)) { - database.close() - } - for (const dir of tempDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function unattested(proof: OrchestrationCompatibilityEvidence): OrchestrationCompatibilityEvidence { - return { ...proof, launchToken: '' } -} - -/** Every observable the adopted Run's recovered graph exposes; a refusal must leave all of it equal. */ -function adoptedGraph(harness: LegacyCompatibilityDispatcherHarness) { - return { - task: harness.db.getTask(harness.taskId)?.status, - dispatch: harness.db.getDispatchContextById(harness.dispatchId)?.status, - gates: harness.db.listGates({ taskId: harness.taskId }).length, - tasksInRun: harness.db.listTasks({ runId: harness.adoptedRunId }).length, - run: harness.db.getRun(harness.adoptedRunId)?.coordinator_handle ?? null, - tables: counts(harness.db) - } -} - -function bindRunA(harness: LegacyCompatibilityDispatcherHarness): string { - return harness.db.createRun({ - objective: 'run A work', - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }).id -} - -async function legacyClaimsAdoptedRun( - harness: LegacyCompatibilityDispatcherHarness, - id: string -): Promise { - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, - evidence('coordinator'), - `${id}-legacy-claim` - ) - ) - expect(response).toMatchObject({ ok: true }) -} - -async function currentCoordinatorTakesOver( - harness: LegacyCompatibilityDispatcherHarness, - id: string -): Promise { - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: CURRENT_COORDINATOR_HANDLE, takeoverLegacy: true }, - currentEvidence('coordinator'), - `${id}-takeover` - ) - ) - expect(response).toMatchObject({ ok: true }) -} - -describe('#11745 H1 — gate methods authorize the caller Run', () => { - it('G5 leaves a foreign gate pending and its task blocked', async () => { - const harness = createHarness() - bindRunA(harness) - const gate = harness.db.createGate({ taskId: harness.taskId, question: 'Proceed?' }) - const before = adoptedGraph(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.gateResolve', - { id: gate.id, resolution: 'yes', from: CURRENT_COORDINATOR_HANDLE }, - unattested(currentEvidence('coordinator')), - 'v-g5' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { message: `Gate not found: ${gate.id}` } }) - expect(harness.db.getGate(gate.id)).toMatchObject({ status: 'pending', resolution: null }) - expect(adoptedGraph(harness)).toEqual(before) - expect(before.task).toBe('blocked') - }) - - it('POSITIVE: a legitimately bound coordinator still gates its own Run end to end', async () => { - const harness = createHarness() - const runA = bindRunA(harness) - const ownTask = harness.db.createTask({ spec: 'own work', runId: runA }) - - const created = (await harness.dispatcher.dispatch( - request( - 'orchestration.gateCreate', - { - task: ownTask.id, - question: 'Ship?', - options: JSON.stringify(['yes', 'no']), - from: CURRENT_COORDINATOR_HANDLE - }, - currentEvidence('coordinator'), - 'v-positive-create' - ) - )) as { ok: true; result: { gate: { id: string; run_id: string } } } - - expect(created).toMatchObject({ ok: true, result: { gate: { run_id: runA } } }) - expect(harness.db.getTask(ownTask.id)?.status).toBe('blocked') - - const listed = await harness.dispatcher.dispatch( - request( - 'orchestration.gateList', - { from: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('coordinator'), - 'v-positive-list' - ) - ) - expect(listed).toMatchObject({ ok: true, result: { runId: runA, count: 1 } }) - - const resolved = await harness.dispatcher.dispatch( - request( - 'orchestration.gateResolve', - { id: created.result.gate.id, resolution: 'yes', from: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('coordinator'), - 'v-positive-resolve' - ) - ) - expect(resolved).toMatchObject({ ok: true, result: { gate: { status: 'resolved' } } }) - expect(harness.db.getTask(ownTask.id)?.status).toBe('ready') - }) -}) - -describe('#11745 H1 — is --from an authenticated identity?', () => { - // Attestation cannot authorize someone else's declared handle; shared resolveRunScope must fence both gate and older task paths. - it('refuses an attested caller naming ANOTHER coordinator handle in --from', async () => { - const harness = createHarness() - const runA = bindRunA(harness) - const victimTask = harness.db.createTask({ spec: 'victim work', runId: runA }) - - // The attested worker has no Run binding and cannot speak for the declared coordinator. - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.gateCreate', - { task: victimTask.id, question: 'spoofed?', from: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('worker'), - 'v-spoof-gate-create' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'consumer_fenced' } }) - expect(harness.db.getTask(victimTask.id)?.status).not.toBe('blocked') - expect(harness.db.listGates({ taskId: victimTask.id })).toHaveLength(0) - }) - - it('refuses an attested caller rebinding another terminal with runUse', async () => { - const harness = createHarness() - const runA = bindRunA(harness) - const workerRun = harness.db.createRun({ - objective: 'worker Run', - coordinatorHandle: CURRENT_WORKER_HANDLE, - coordinatorPaneKey: CURRENT_WORKER_PANE - }) - const beforeA = harness.db.getRun(runA) - const beforeWorker = harness.db.getRun(workerRun.id) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: workerRun.id, from: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('worker'), - 'v-spoof-run-use' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'consumer_fenced' } }) - expect(harness.db.getRun(runA)).toEqual(beforeA) - expect(harness.db.getRun(workerRun.id)).toEqual(beforeWorker) - }) -}) - -describe('#11745 H3 — adopted Run claimed by the legacy coordinator', () => { - it('still fences the genuinely stale legacy coordinator with legacy_read_only and zero effects', async () => { - const harness = createHarness() - await legacyClaimsAdoptedRun(harness, 'v-h3b') - await currentCoordinatorTakesOver(harness, 'v-h3b') - const before = adoptedGraph(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'stale assignment', - run: harness.adoptedRunId, - callerTerminalHandle: COORDINATOR_HANDLE - }, - evidence('coordinator'), - 'v-h3b-stale' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { code: 'legacy_read_only', data: { effectsApplied: false } } - }) - expect(adoptedGraph(harness)).toEqual(before) - }) -}) - -/** Builds a pre-cutover graph at schema 18 and reopens it so adoption runs. */ -function createAdoptedDb(options: { settleWork: boolean }): { - db: OrchestrationDb - adoptedRunId: string - recoveryMessageId: string -} { - const dir = mkdtempSync(join(tmpdir(), 'orca-11745-m5-')) - tempDirs.push(dir) - const dbPath = join(dir, 'orchestration.db') - - const before = new OrchestrationDb(dbPath) - const task = before.createTask({ - runId: 'run_legacy_local', - spec: 'legacy assignment', - createdByTerminalHandle: 'term_old' - }) - createRootDispatch( - before, - task.id, - 'term_old_worker', - 'tab_old:33333333-3333-4333-8333-333333333333' - ) - const recovery = before.insertMessage({ - runId: 'run_legacy_local', - from: 'term_old_worker', - to: 'term_old', - subject: 'recovered worker outcome', - type: 'worker_done' - }) - before.close() - - const raw = new SyncDatabase(dbPath) - if (options.settleWork) { - raw.exec("UPDATE dispatch_contexts SET status = 'completed'") - } - raw.exec(` - DROP INDEX IF EXISTS idx_messages_delivery_contract; - DROP TABLE legacy_mail_receipts; - DROP TABLE legacy_operation_receipts; - DROP TABLE legacy_compatibility_principals; - DROP TABLE legacy_adoptions; - `) - raw.pragma('user_version = 18') - raw.close() - - const db = new OrchestrationDb(dbPath) - databases.push(db) - return { - db, - adoptedRunId: db.getLegacyAdoption()?.adopted_run_id as string, - recoveryMessageId: recovery.id - } -} - -describe('#11745 M5 — binding an unclaimed adopted Run', () => { - it('binds without --takeover-legacy when no legacy work is live, and keeps legacy mail promoted', () => { - const { db, adoptedRunId, recoveryMessageId } = createAdoptedDb({ settleWork: true }) - expect(db.getMessageById(recoveryMessageId)?.run_id).toBe(adoptedRunId) - - const run = db.bindRun({ - runId: adoptedRunId, - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - - expect(run?.id).toBe(adoptedRunId) - expect(db.getRun(adoptedRunId)).toMatchObject({ - coordinator_handle: CURRENT_COORDINATOR_HANDLE - }) - // The recovered mail must still belong to the adopted Run, not be orphaned by the bind. - expect(db.getMessageById(recoveryMessageId)?.run_id).toBe(adoptedRunId) - expect(db.getCurrentRunForPane(CURRENT_COORDINATOR_PANE)?.id).toBe(adoptedRunId) - }) - - it('still fences the bind while legacy work IS live, with a usable recovery command', () => { - const { db, adoptedRunId, recoveryMessageId } = createAdoptedDb({ settleWork: false }) - - expect(() => - db.bindRun({ - runId: adoptedRunId, - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - ).toThrowError( - expect.objectContaining({ - code: 'consumer_fenced', - data: { - effectsApplied: false, - recoveryCommand: `orca orchestration run-use --id ${adoptedRunId} --takeover-legacy` - } - }) - ) - expect(db.getRun(adoptedRunId)?.coordinator_handle).toBeNull() - expect(db.getMessageById(recoveryMessageId)?.run_id).toBe(adoptedRunId) - }) -}) - -describe('#11745 L6 — indexed getCurrentRunForPane keeps pane equivalence', () => { - function paneDb(): OrchestrationDb { - const dir = mkdtempSync(join(tmpdir(), 'orca-11745-l6-')) - tempDirs.push(dir) - const db = new OrchestrationDb(join(dir, 'orchestration.db')) - databases.push(db) - return db - } - - function leaf(index: number): string { - const hex = index.toString(16).padStart(12, '0') - return `${hex.slice(0, 8)}-0000-4000-8000-${hex}` - } - - it('keeps unparseable pane keys on exact-match semantics', () => { - const db = paneDb() - const noColon = db.createRun({ - objective: 'no colon', - coordinatorHandle: 'term_a', - coordinatorPaneKey: 'nocolonpanekey' - }) - const twoColons = db.createRun({ - objective: 'two colons', - coordinatorHandle: 'term_b', - coordinatorPaneKey: `win:tab:${leaf(3)}` - }) - const emptyLeaf = db.createRun({ - objective: 'empty leaf', - coordinatorHandle: 'term_c', - coordinatorPaneKey: 'tab_empty:' - }) - - expect(db.getCurrentRunForPane('nocolonpanekey')?.id).toBe(noColon.id) - expect(db.getCurrentRunForPane(`win:tab:${leaf(3)}`)?.id).toBe(twoColons.id) - expect(db.getCurrentRunForPane('tab_empty:')?.id).toBe(emptyLeaf.id) - - // Unparseable first segments must match too: suffix index narrows candidates; isEquivalentPaneKey decides. - expect(db.getCurrentRunForPane(`other:tab:${leaf(3)}`)).toBeUndefined() - expect(db.getCurrentRunForPane('other_empty:')).toBeUndefined() - // A shared suffix cannot equate parseable and unparseable keys. - expect(db.getCurrentRunForPane(`tab:${leaf(3)}`)).toBeUndefined() - }) - - it('unbinds the equivalent pane when a reminted key run-uses a new Run', () => { - const db = paneDb() - const first = db.createRun({ - objective: 'first', - coordinatorHandle: 'term_a', - coordinatorPaneKey: `tab_one:${leaf(4)}` - }) - const second = db.createRun({ - objective: 'second', - coordinatorHandle: 'term_a', - coordinatorPaneKey: `tab_two:${leaf(4)}` - }) - db.bindRun({ - runId: second.id, - coordinatorHandle: 'term_a', - coordinatorPaneKey: `tab_two:${leaf(4)}` - }) - - expect(db.getRun(first.id)?.coordinator_pane_key).toBeNull() - expect(db.getCurrentRunForPane(`tab_three:${leaf(4)}`)?.id).toBe(second.id) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-check-wait-session.test.ts b/src/main/runtime/rpc/orchestration-check-wait-session.test.ts deleted file mode 100644 index 5ba9fbd8df0..00000000000 --- a/src/main/runtime/rpc/orchestration-check-wait-session.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** Chat check --wait honors the requested budget; provider shell tools that time out background/yield it rather than killing it. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - createSessionCallerHarness, - idOf, - orchestrationRequest, - resultOf, - SESSION_X, - SESSION_Y, - WORKER_HANDLE, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -describe('check --wait from an agent session', () => { - let h: SessionCallerHarness - - beforeEach(() => { - h = createSessionCallerHarness(hostRef) - }) - - afterEach(() => { - h.close() - vi.restoreAllMocks() - }) - - it('lets a chat hold two waits that share one Delivery and are both fenced on takeover', async () => { - const as = (sessionId: string | undefined, method: string, params: Record) => - h.dispatch(orchestrationRequest(method, params, { sessionId })) - const runId = idOf( - resultOf(await as(SESSION_X, 'orchestration.runCreate', { objective: 'o' })).run - ) - const waiter = vi.spyOn(h.runtime, 'waitForMessage') - const parkTwoWaits = async () => { - const parked = waiter.mock.calls.length + 2 - const waits = Promise.all( - [1, 2].map(() => - as(SESSION_X, 'orchestration.check', { run: runId, wait: true, timeoutMs: 5_000 }) - ) - ) - await vi.waitFor(() => expect(waiter).toHaveBeenCalledTimes(parked)) - return { settled: waits } - } - - const shared = await parkTwoWaits() - await as(undefined, 'orchestration.send', { - from: WORKER_HANDLE, - to: `run:${runId}`, - subject: 'done', - run: runId - }) - const [first, second] = (await shared.settled).map(resultOf) - expect(first.deliveryId).toEqual(expect.any(String)) - expect(second.deliveryId).toBe(first.deliveryId) - await as(SESSION_X, 'orchestration.check', { run: runId, ack: first.deliveryId }) - - const fenced = await parkTwoWaits() - await as(SESSION_Y, 'orchestration.runUse', { id: runId }) - const fencedError = { ok: false, error: expect.objectContaining({ code: 'consumer_fenced' }) } - expect(await fenced.settled).toEqual([ - expect.objectContaining(fencedError), - expect.objectContaining(fencedError) - ]) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-commit-notify-characterization.test.ts b/src/main/runtime/rpc/orchestration-commit-notify-characterization.test.ts deleted file mode 100644 index 9e207811d99..00000000000 --- a/src/main/runtime/rpc/orchestration-commit-notify-characterization.test.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { rmSync } from 'node:fs' - -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' - -import type { OrchestrationDb } from '../orchestration/db/orchestration-db' - -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { OrcaRuntimeService } from '../orca-runtime' - -import type { RpcRequest } from './core' - -import { RpcDispatcher } from './dispatcher' - -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' - -import { createOrchestrationRpcHarness } from './methods/orchestration/rpc-test-harness' - -import { MessageWake } from '../orchestration/mailbox/runtime-message-waiters' - -describe('orchestration commit-notify recovery', () => { - const harness = createOrchestrationRpcHarness() - const paths: string[] = [] - - afterEach(() => { - harness.cleanup() - for (const path of paths.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } - }) - - function request( - rpcId: string, - mutationId: string, - method: 'orchestration.send' | 'orchestration.reply', - params: Record - ): RpcRequest { - return { - id: rpcId, - authToken: 'test-token', - method, - params, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: mutationId - } - } - - function createReadyLocalWorker( - db: OrchestrationDb, - taskId: string, - workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - ) { - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId, - startOptions: {} - }) - db.prepareStartingWorkerAuthority({ - dispatchId: started.dispatch.id, - handle: 'term_worker', - paneKey: workerPaneKey, - processIncarnation: 'runtime_test:term_worker:1', - worktreeId: 'repo::worker', - effects: [], - setupState: 'not_applicable' - }) - db.markWorkerDispatchReady(started.dispatch.id) - return { dispatch: db.getDispatchContextById(started.dispatch.id)! } - } - - async function throwAfterCommitAndReplay( - dispatcher: RpcDispatcher, - runtime: OrcaRuntimeService, - first: RpcRequest, - retryRpcId: string - ) { - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementationOnce(() => { - throw new Error('injected notification failure') - }) - - const failed = await dispatcher.dispatch(first) - const replayed = await dispatcher.dispatch({ ...first, id: retryRpcId }) - - expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) - expect(replayed).toMatchObject({ - ok: true, - result: { mutation: { requestId: first.orchestrationRequestId, replayed: true } } - }) - return replayed as { result: Record } - } - - it('replays one Run send after notification throws post-commit', async () => { - const { db, runtime, activeRunId } = harness.setup() - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const waiting = runtime.waitForMessage(`run:${activeRunId}`, { timeoutMs: 5_000 }) - const replayed = await throwAfterCommitAndReplay( - dispatcher, - runtime, - request('rpc_run_send', 'mutation_run_send', 'orchestration.send', { - from: 'term_coord', - to: `run:${activeRunId}`, - subject: 'one durable Run message' - }), - 'rpc_run_send_retry' - ) - - const messages = db.getInbox(100) - expect(messages).toHaveLength(1) - expect(replayed.result).toMatchObject({ message: { id: messages[0]?.id } }) - await expect(waiting).resolves.toBeInstanceOf(MessageWake) - }) - - it('replays one question reply nudge without duplicating the answer', async () => { - const { db, runtime, activeRunId } = harness.setup() - if (!activeRunId) { - throw new Error('active Run missing') - } - const task = db.createTask({ spec: 'Ask once', runId: activeRunId }) - const { dispatch } = createReadyLocalWorker(db, task.id) - const question = db.createQuestion({ - runId: activeRunId, - dispatchId: dispatch.id, - askerHandle: 'term_worker', - question: 'Continue?' - }) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const waiting = runtime.waitForMessage(`dispatch:${dispatch.id}`, { timeoutMs: 5_000 }) - const replayed = await throwAfterCommitAndReplay( - dispatcher, - runtime, - request('rpc_question_reply', 'mutation_question_reply', 'orchestration.reply', { - id: question.message.id, - run: activeRunId, - body: 'Continue', - from: 'term_coord' - }), - 'rpc_question_reply_retry' - ) - - const answered = db.getQuestion(question.message.id) - expect(answered).toMatchObject({ status: 'answered', answer_body: 'Continue' }) - expect( - db.getInbox(100).filter((message) => message.thread_id === question.message.id) - ).toHaveLength(2) - expect(replayed.result).toMatchObject({ duplicate: false }) - await expect(waiting).resolves.toBeInstanceOf(MessageWake) - }) - - it('replays worker settlement without applying lifecycle state twice', async () => { - const { db, runtime, activeRunId } = harness.setup() - const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => - handle === 'term_worker' - ? workerPaneKey - : handle === 'term_coord' - ? harness.coordinatorPaneKey - : null - ) - const task = db.createTask({ spec: 'Settle once' }) - const { dispatch } = createReadyLocalWorker(db, task.id, workerPaneKey) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const workerDone = request('rpc_worker_done', 'mutation_worker_done', 'orchestration.send', { - from: 'term_worker', - subject: 'Done', - type: 'worker_done', - payload: JSON.stringify({ - taskId: task.id, - dispatchId: dispatch.id, - outcome: 'succeeded' - }) - }) - const waiting = runtime.waitForMessage(`run:${activeRunId}`, { - typeFilter: ['worker_done'], - timeoutMs: 5_000 - }) - let waiterSettled = false - void waiting.then(() => { - waiterSettled = true - }) - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementationOnce(() => { - throw new Error('injected notification failure') - }) - - const failed = await dispatcher.dispatch(workerDone) - await Promise.resolve() - expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) - expect(waiterSettled).toBe(false) - - const replayed = await dispatcher.dispatch({ ...workerDone, id: 'rpc_worker_done_retry' }) - - expect(db.getTask(task.id)?.status).toBe('completed') - expect(db.getDispatchContextById(dispatch.id)?.status).toBe('completed') - expect(db.getInbox(100).filter((message) => message.type === 'worker_done')).toHaveLength(1) - expect(replayed).toMatchObject({ - ok: true, - result: { - lifecycle: { action: 'completed' }, - mutation: { requestId: 'mutation_worker_done', replayed: true } - } - }) - await expect(waiting).resolves.toBeInstanceOf(MessageWake) - }) - - it.each([ - { - seam: 'lifecycle settlement', - inject(db: OrchestrationDb) { - vi.spyOn(db, 'settleWorkerReportInTransaction').mockImplementationOnce(() => { - throw new Error('injected settlement failure') - }) - } - }, - { - seam: 'mutation receipt', - inject(db: OrchestrationDb) { - vi.spyOn(db, 'completeMutationReceipt').mockImplementationOnce(() => { - throw new Error('injected receipt failure') - }) - } - } - ])('atomically rolls back worker_done when $seam fails', async ({ inject }) => { - const { db, runtime, activeRunId } = harness.setup() - const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => - handle === 'term_worker' - ? workerPaneKey - : handle === 'term_coord' - ? harness.coordinatorPaneKey - : null - ) - const task = db.createTask({ spec: 'Commit report and settlement together' }) - const { dispatch } = createReadyLocalWorker(db, task.id, workerPaneKey) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const workerDone = request( - 'rpc_atomic_worker_done', - 'mutation_atomic_worker_done', - 'orchestration.send', - { - from: 'term_worker', - subject: 'Done atomically', - type: 'worker_done', - payload: JSON.stringify({ - taskId: task.id, - dispatchId: dispatch.id, - outcome: 'succeeded' - }) - } - ) - const callerFingerprint = db.getOrCreateLocalMutationCallerFingerprint() - inject(db) - - const failed = await dispatcher.dispatch(workerDone) - - expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) - expect(db.getInbox(100).filter((message) => message.type === 'worker_done')).toHaveLength(0) - expect(db.getTask(task.id)?.status).toBe('dispatched') - expect( - db.getAttemptObservationFacts(dispatch.id).filter((fact) => fact.facet === 'worker_report') - ).toHaveLength(0) - expect(db.getMutationReceipt(callerFingerprint, 'mutation_atomic_worker_done')).toBeUndefined() - const run = db.getRun(activeRunId!)! - expect( - db.getOrCreateRunDelivery({ - runId: activeRunId!, - consumerGeneration: run.consumer_generation - }) - ).toBeUndefined() - - const retried = await dispatcher.dispatch({ ...workerDone, id: 'rpc_atomic_worker_done_retry' }) - - expect(retried).toMatchObject({ - ok: true, - result: { lifecycle: { action: 'completed' } } - }) - expect(db.getInbox(100).filter((message) => message.type === 'worker_done')).toHaveLength(1) - expect(db.getTask(task.id)?.status).toBe('completed') - expect(db.getDispatchContextById(dispatch.id)?.status).toBe('completed') - expect( - db.getAttemptObservationFacts(dispatch.id).filter((fact) => fact.facet === 'worker_report') - ).toHaveLength(1) - expect(db.getMutationReceipt(callerFingerprint, 'mutation_atomic_worker_done')?.state).toBe( - 'completed' - ) - }) - - it('replays one federated enqueue after the relay wake throws post-commit', async () => { - const { db, runtime } = harness.setup() - const task = db.createTask({ spec: 'Receive federated control mail' }) - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {}, - federation: { - environmentId: 'environment_worker', - environmentName: 'worker', - peerFingerprint: 'worker-peer', - protocolVersion: 2 - } - }) - db.markWorkerDispatchReady(started.dispatch.id) - vi.spyOn(runtime, 'ensureOrchestrationFederationRelay').mockImplementationOnce(() => { - throw new Error('injected relay wake failure') - }) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const first = request('rpc_federated_send', 'mutation_federated_send', 'orchestration.send', { - from: 'term_coord', - to: `dispatch:${started.dispatch.id}`, - subject: 'One durable relay item' - }) - - const failed = await dispatcher.dispatch(first) - const replayed = await dispatcher.dispatch({ ...first, id: 'rpc_federated_send_retry' }) - - expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) - expect(replayed).toMatchObject({ - ok: true, - result: { - relay: { dispatchId: started.dispatch.id, accepted: true }, - mutation: { requestId: 'mutation_federated_send', replayed: true } - } - }) - expect(db.listPendingFederationRelay(started.dispatch.id, 'to_worker')).toHaveLength(1) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-contract-fence.test.ts b/src/main/runtime/rpc/orchestration-contract-fence.test.ts deleted file mode 100644 index ad32e63bbd7..00000000000 --- a/src/main/runtime/rpc/orchestration-contract-fence.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { z } from 'zod' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' -import { defineOrchestrationMethod } from './methods/orchestration/access/orchestration-method-access' -import { RpcDispatcher } from './dispatcher' - -describe('orchestration contract fence', () => { - const databases: OrchestrationDb[] = [] - - afterEach(() => { - for (const database of databases.splice(0)) { - database.close() - } - }) - - function createHarness(method: `orchestration.${string}` = 'orchestration.send') { - const database = new OrchestrationDb(':memory:') - databases.push(database) - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(database) - const effect = vi.fn(() => ({ accepted: true })) - const dispatcher = new RpcDispatcher({ - runtime, - methods: [ - defineOrchestrationMethod({ - name: method, - permission: 'workspace', - access: { kind: 'writes', targets: {} }, - params: z.object({ subject: z.string() }), - handler: effect - }) - ] - }) - return { database, dispatcher, effect } - } - - function request(overrides: Partial = {}): RpcRequest { - return { - id: 'rpc_1', - authToken: 'caller-token', - method: 'orchestration.send', - params: { subject: 'hello' }, - orchestrationRequestId: 'mutation_1', - ...overrides - } - } - - it.each([ - [undefined, 'client_contract_missing'], - [0, 'client_contract_unsupported'], - [ORCHESTRATION_CONTRACT_VERSION + 1, 'client_contract_unsupported'] - ])( - 'rejects contract version %s before parsing, receipts, or effects', - async (version, reason) => { - const { database, dispatcher, effect } = createHarness() - const response = await dispatcher.dispatch( - request({ - params: { malformed: true }, - orchestrationContractVersion: version - }) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'orchestration_migration_required', - data: { - reason, - effectsApplied: false, - nextCommandArgs: ['skills', 'get', 'orchestration', '--full'] - } - } - }) - expect(effect).not.toHaveBeenCalled() - const callerFingerprint = database.getOrCreateLocalMutationCallerFingerprint() - expect(database.getMutationReceipt(callerFingerprint, 'mutation_1')).toBeUndefined() - } - ) -}) diff --git a/src/main/runtime/rpc/orchestration-current-authority-precedence.test.ts b/src/main/runtime/rpc/orchestration-current-authority-precedence.test.ts deleted file mode 100644 index 179ef2652cb..00000000000 --- a/src/main/runtime/rpc/orchestration-current-authority-precedence.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - createHarness, - currentEvidence, - CURRENT_COORDINATOR_HANDLE, - CURRENT_COORDINATOR_PANE, - CURRENT_WORKER_HANDLE, - CURRENT_WORKER_PANE, - evidence, - invoke, - request, - WORKER_HANDLE, - WORKER_PANE -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() -}) - -describe('current orchestration authority precedence', () => { - it.each([ - ['heartbeat', undefined], - ['worker_done', 'succeeded'] - ] as const)('routes a current %s before legacy fallback', async (type, outcome) => { - const harness = createHarness() - const { taskId, dispatchId } = createCurrentDispatch(harness) - const payload = JSON.stringify({ - taskId, - dispatchId, - ...(outcome ? { outcome } : {}) - }) - const response = await harness.dispatcher.dispatch({ - ...request( - 'orchestration.send', - { - from: CURRENT_WORKER_HANDLE, - subject: type === 'heartbeat' ? 'alive' : 'Completed', - type, - payload - }, - currentEvidence('worker'), - `current-${type}` - ) - }) - - expect(response).toMatchObject({ - ok: true, - result: { - message: { - from_handle: CURRENT_WORKER_HANDLE, - to_handle: expect.stringMatching(/^run:/), - type, - delivery_contract: 'current_delivery' - } - } - }) - expect(response).not.toHaveProperty('result.legacyCompatibility') - expect(harness.db.getTask(taskId)?.status).toBe( - type === 'worker_done' ? 'completed' : 'dispatched' - ) - }) - - it('routes a current worker mailbox check before legacy fallback', async () => { - const harness = createHarness() - const { runId, dispatchId } = createCurrentDispatch(harness) - const message = harness.db.insertMessage({ - runId, - from: CURRENT_COORDINATOR_HANDLE, - to: `dispatch:${dispatchId}`, - subject: 'current guidance', - deliveryContract: 'current_delivery' - }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { terminal: CURRENT_WORKER_HANDLE }, - currentEvidence('worker'), - 'current-worker-check' - ) - ) - - expect(response).toMatchObject({ - ok: true, - result: { - runId, - dispatchId, - deliveryId: expect.any(String), - messages: [{ id: message.id }], - count: 1 - } - }) - expect(harness.db.getMessageById(message.id)?.read).toBe(1) - - const deliveryId = (response as { result: { deliveryId: string } }).result.deliveryId - // A response lost in transit replays from the request receipt when retried with the same id. - const replayed = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { terminal: CURRENT_WORKER_HANDLE }, - currentEvidence('worker'), - 'current-worker-check' - ) - ) - expect(replayed).toMatchObject({ - ok: true, - result: { deliveryId, messages: [{ id: message.id }], count: 1 } - }) - - const acknowledged = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { terminal: CURRENT_WORKER_HANDLE, ack: deliveryId }, - currentEvidence('worker'), - 'current-worker-check-ack' - ) - ) - - expect(acknowledged).toMatchObject({ - ok: true, - result: { acknowledged: deliveryId, count: 0 } - }) - expect(harness.db.getMessageById(message.id)?.read).toBe(1) - }) - - it.each(['dispatch', 'websocket'] as const)( - '%s routes a reused legacy terminal current check before its retained principal', - async (transport) => { - const harness = createHarness() - const { runId, dispatchId } = await createReusedCurrentDispatch(harness, transport) - const message = harness.db.insertMessage({ - runId, - from: CURRENT_COORDINATOR_HANDLE, - to: `dispatch:${dispatchId}`, - subject: 'reused terminal guidance', - deliveryContract: 'current_delivery' - }) - - const response = await invoke( - harness.dispatcher, - request( - 'orchestration.check', - { terminal: WORKER_HANDLE }, - evidence('worker'), - `reused-current-check-${transport}` - ), - transport - ) - - expect(response).toMatchObject({ - ok: true, - result: { - runId, - dispatchId, - messages: [{ id: message.id }], - count: 1 - } - }) - expect(response).not.toHaveProperty('result.legacyCompatibility') - } - ) - - it.each(['dispatch', 'websocket'] as const)( - '%s routes a reused legacy terminal current ask before its retained principal', - async (transport) => { - const harness = createHarness() - const { dispatchId } = await createReusedCurrentDispatch(harness, transport) - - const response = await invoke( - harness.dispatcher, - { - ...request( - 'orchestration.ask', - { - from: WORKER_HANDLE, - question: 'Continue with the current assignment?', - timeoutMs: 0 - }, - evidence('worker'), - `reused-current-ask-${transport}` - ) - }, - transport - ) - - expect(response).toMatchObject({ - ok: true, - result: { - answer: null, - messageId: expect.any(String), - timedOut: true - } - }) - expect(response).not.toHaveProperty('result.legacyCompatibility') - const questionId = (response as { result: { messageId: string } }).result.messageId - expect(harness.db.getQuestion(questionId)?.dispatch_id).toBe(dispatchId) - } - ) -}) - -function createCurrentDispatch(harness: ReturnType): { - runId: string - taskId: string - dispatchId: string -} { - const run = harness.db.createRun({ - objective: 'current work', - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - const task = harness.db.createTask({ spec: 'current assignment', runId: run.id }) - const dispatch = createRootDispatch( - harness.db, - task.id, - CURRENT_WORKER_HANDLE, - CURRENT_WORKER_PANE, - undefined, - 'process-1' - ) - return { runId: run.id, taskId: task.id, dispatchId: dispatch.id } -} - -async function createReusedCurrentDispatch( - harness: ReturnType, - suffix: string -): Promise<{ - runId: string - taskId: string - dispatchId: string -}> { - const legacyCheck = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { terminal: WORKER_HANDLE, peek: true }, - evidence('worker'), - `attest-legacy-worker-${suffix}` - ) - ) - expect(legacyCheck).toHaveProperty('result.legacyCompatibility') - harness.db.completeDispatch(harness.dispatchId) - - const run = harness.db.createRun({ - objective: 'current work in reused terminal', - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - const task = harness.db.createTask({ spec: 'reused terminal assignment', runId: run.id }) - const dispatch = createRootDispatch( - harness.db, - task.id, - WORKER_HANDLE, - WORKER_PANE, - undefined, - 'process-1' - ) - return { runId: run.id, taskId: task.id, dispatchId: dispatch.id } -} diff --git a/src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.ts b/src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.ts deleted file mode 100644 index 63d4d1ffe3f..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher.test.ts +++ /dev/null @@ -1,467 +0,0 @@ -import { createHash } from 'node:crypto' -import { afterEach, describe, expect, it } from 'vitest' -import type Database from '../../sqlite/sync-database' -import { applyEscalationToDispatch } from '../orchestration/coordinator/escalation/coordinator-escalation-triage' -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - COORDINATOR_HANDLE, - counts, - createHarness, - escalationParams, - evidence, - invoke, - request, - WORKER_HANDLE, - WORKER_PANE -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() -}) - -describe('legacy compatibility through RpcDispatcher', () => { - it.each([ - ['dispatch', true], - ['dispatch', false], - ['websocket', true], - ['websocket', false] - ] as const)( - '%s routes task-only escalation with valid proof=%s and zero partial effects', - async (transport, valid) => { - const harness = createHarness() - const before = counts(harness.db) - const response = await invoke( - harness.dispatcher, - request( - 'orchestration.send', - { - ...escalationParams(harness), - payload: JSON.stringify({ taskId: harness.taskId }) - }, - evidence('worker', valid), - `${transport}-${valid}` - ), - transport - ) - - if (!valid) { - expect(response).toMatchObject({ - ok: false, - error: { code: 'legacy_read_only' } - }) - expect(counts(harness.db)).toEqual(before) - expect(harness.notify).not.toHaveBeenCalled() - return - } - - expect(response).toMatchObject({ - ok: true, - result: { - message: { type: 'escalation', delivery_contract: 'legacy_direct' }, - legacyCompatibility: { replayed: false } - } - }) - const message = (response as { result: { message: { id: string; payload: string } } }).result - .message - expect(JSON.parse(message.payload)).toMatchObject({ - taskId: harness.taskId, - dispatchId: harness.dispatchId - }) - applyEscalationToDispatch(harness.db, harness.db.getMessageById(message.id)!, () => {}) - expect(harness.db.getTask(harness.taskId)?.status).toBe('ready') - expect(harness.db.getDispatchContextById(harness.dispatchId)?.status).toBe('failed') - expect(counts(harness.db)).toEqual({ - ...before, - messages: before.messages + 1, - legacy_compatibility_principals: before.legacy_compatibility_principals + 1, - legacy_operation_receipts: before.legacy_operation_receipts + 1 - }) - expect(harness.notify).toHaveBeenCalledOnce() - } - ) - - it('validates, infers, settles, and replays legacy worker completion exactly once', async () => { - const harness = createHarness() - const baseParams = { - from: WORKER_HANDLE, - to: COORDINATOR_HANDLE, - type: 'worker_done', - body: 'legacy result', - payload: JSON.stringify({ taskId: harness.taskId, dispatchId: harness.dispatchId }) - } - const before = counts(harness.db) - const invalid = await harness.dispatcher.dispatch( - request( - 'orchestration.send', - { ...baseParams, subject: 'Completed', payload: JSON.stringify({ outcome: 'maybe' }) }, - evidence('worker'), - 'invalid-outcome' - ) - ) - - expect(invalid).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) - expect(counts(harness.db)).toEqual(before) - - const firstRequest = request( - 'orchestration.send', - { ...baseParams, subject: 'Completed' }, - evidence('worker'), - 'completion' - ) - const first = await harness.dispatcher.dispatch(firstRequest) - const replay = await harness.dispatcher.dispatch({ ...firstRequest, id: 'rpc_replay' }) - const mismatch = await harness.dispatcher.dispatch({ - ...firstRequest, - id: 'rpc_mismatch', - params: { ...baseParams, subject: 'Changed completion' } - }) - - expect(first).toMatchObject({ - ok: true, - result: { - lifecycle: { action: 'settled', outcome: 'succeeded' }, - legacyCompatibility: { replayed: false } - } - }) - expect(replay).toMatchObject({ - ok: true, - result: { legacyCompatibility: { replayed: true } } - }) - expect(mismatch).toMatchObject({ ok: false, error: { code: 'request_mismatch' } }) - expect(harness.db.getTask(harness.taskId)?.status).toBe('completed') - expect(harness.db.getDispatchContextById(harness.dispatchId)?.status).toBe('completed') - expect(counts(harness.db)).toEqual({ - ...before, - messages: before.messages + 1, - legacy_compatibility_principals: before.legacy_compatibility_principals + 1, - legacy_operation_receipts: before.legacy_operation_receipts + 1 - }) - expect(harness.notify).toHaveBeenCalledOnce() - }) - - it('replays an A-era completion without touching a newer current attempt', async () => { - const harness = createHarness() - const payload = JSON.stringify({ - taskId: harness.taskId, - dispatchId: harness.dispatchId - }) - const completion = harness.db.insertMessage({ - runId: harness.adoptedRunId, - from: WORKER_HANDLE, - to: COORDINATOR_HANDLE, - subject: 'Failed: pinned A treated this as complete', - body: 'persisted result', - type: 'worker_done', - payload, - senderPaneKey: WORKER_PANE, - deliveryContract: 'legacy_direct' - }) - harness.db.settleWorkerReport({ - taskId: harness.taskId, - dispatchId: harness.dispatchId, - outcome: 'succeeded', - result: 'persisted result' - }) - harness.db.commitLegacyCompatibilityPrincipal({ - runId: harness.adoptedRunId, - dispatchId: harness.dispatchId, - role: 'worker', - hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), - terminalHandle: WORKER_HANDLE, - paneKey: WORKER_PANE, - launchTokenHash: createHash('sha256').update('worker-token').digest('hex'), - processIncarnation: 'process-1' - }) - // Recreate the pre-boundary state where A settled before a current attempt was persisted. - const sqlite = (harness.db as unknown as { db: Database.Database }).db - sqlite.prepare("UPDATE tasks SET status = 'ready' WHERE id = ?").run(harness.taskId) - const currentDispatch = createRootDispatch( - harness.db, - harness.taskId, - 'term_current_worker', - 'tab_current_worker:77777777-7777-4777-8777-777777777777', - 'current-launch-hash' - ) - const currentTaskBefore = harness.db.getTask(harness.taskId) - const currentDispatchBefore = harness.db.getDispatchContextById(currentDispatch.id) - const before = counts(harness.db) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.send', - { - from: WORKER_HANDLE, - to: COORDINATOR_HANDLE, - subject: completion.subject, - body: completion.body, - type: 'worker_done', - payload - }, - evidence('worker'), - 'reconstruct-pinned-a-completion' - ) - ) - - expect(response).toMatchObject({ - ok: true, - result: { - message: { id: completion.id }, - lifecycle: { action: 'settled', outcome: 'succeeded', duplicate: true } - } - }) - expect(harness.db.getTask(harness.taskId)).toEqual(currentTaskBefore) - expect(harness.db.getDispatchContextById(harness.dispatchId)?.status).toBe('completed') - expect(harness.db.getDispatchContextById(currentDispatch.id)).toEqual(currentDispatchBefore) - expect(counts(harness.db)).toEqual({ - ...before, - legacy_operation_receipts: before.legacy_operation_receipts + 1 - }) - }) - - it('rejects a reused pane whose live process incarnation is not the legacy worker', async () => { - const harness = createHarness() - const sqlite = (harness.db as unknown as { db: Database.Database }).db - sqlite - .prepare('UPDATE dispatch_contexts SET process_incarnation = ? WHERE id = ?') - .run('different-process', harness.dispatchId) - const before = counts(harness.db) - - const response = await harness.dispatcher.dispatch( - request('orchestration.send', escalationParams(harness), evidence('worker'), 'reused-pane') - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'legacy_read_only' } }) - expect(counts(harness.db)).toEqual(before) - expect(harness.notify).not.toHaveBeenCalled() - }) - - it('keeps distinct compatibility ask invocations on distinct questions', async () => { - const harness = createHarness() - const ask = { - from: WORKER_HANDLE, - to: COORDINATOR_HANDLE, - question: 'Same question?', - options: ['yes', 'no'], - timeoutMs: 1 - } - const first = await harness.dispatcher.dispatch( - request('orchestration.ask', ask, evidence('worker'), 'ask-one') - ) - const replay = await harness.dispatcher.dispatch( - request('orchestration.ask', ask, evidence('worker'), 'ask-one') - ) - const second = await harness.dispatcher.dispatch( - request('orchestration.ask', ask, evidence('worker'), 'ask-two') - ) - - expect(first).toMatchObject({ ok: true, result: { legacyCompatibility: { replayed: false } } }) - expect(replay).toMatchObject({ ok: true, result: { legacyCompatibility: { replayed: true } } }) - expect(second).toMatchObject({ ok: true, result: { legacyCompatibility: { replayed: false } } }) - const firstId = (first as { result: { messageId: string } }).result.messageId - const replayId = (replay as { result: { messageId: string } }).result.messageId - const secondId = (second as { result: { messageId: string } }).result.messageId - expect(replayId).toBe(firstId) - expect(secondId).not.toBe(firstId) - expect(harness.db.getMessageById(firstId)?.type).toBe('decision_gate') - - const coordinatorCheck = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { - terminal: COORDINATOR_HANDLE, - types: 'worker_done,escalation,decision_gate', - format: true - }, - evidence('coordinator'), - 'coordinator-check-decision-gates' - ) - ) - expect(coordinatorCheck).toMatchObject({ - ok: true, - result: { - messages: [ - { id: firstId, type: 'decision_gate' }, - { id: secondId, type: 'decision_gate' } - ], - count: 2 - } - }) - expect((coordinatorCheck as { result: { formatted: string } }).result.formatted).toContain( - `orca orchestration reply --id ${firstId}` - ) - }) - - it('rejects invalid typed ACKs and consumes only the filtered legacy page', async () => { - const harness = createHarness() - await harness.dispatcher.dispatch( - request( - 'orchestration.send', - { - ...escalationParams(harness), - type: 'worker_done', - subject: 'Completed', - payload: JSON.stringify({ taskId: harness.taskId, dispatchId: harness.dispatchId }) - }, - evidence('worker'), - 'settle-for-mail' - ) - ) - const status = harness.db.insertMessage({ - runId: harness.adoptedRunId, - from: COORDINATOR_HANDLE, - to: WORKER_HANDLE, - subject: 'status first', - type: 'status', - deliveryContract: 'legacy_direct' - }) - const question = harness.db.insertMessage({ - runId: harness.adoptedRunId, - from: COORDINATOR_HANDLE, - to: WORKER_HANDLE, - subject: 'question second', - type: 'question', - deliveryContract: 'legacy_direct' - }) - const check = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { terminal: WORKER_HANDLE, types: 'question' }, - evidence('worker'), - 'question-check' - ) - ) - expect(check).toMatchObject({ - ok: true, - result: { - messages: [{ id: question.id }], - legacyCompatibility: { ackMessageIds: [question.id] } - } - }) - - const invalid = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { - terminal: WORKER_HANDLE, - compatibilityAck: JSON.stringify({ - messageIds: [question.id], - types: ['not-a-message-type'] - }) - }, - evidence('worker'), - 'invalid-ack' - ) - ) - expect(invalid).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) - expect(harness.db.getMessageById(status.id)?.read).toBe(0) - expect(harness.db.getMessageById(question.id)?.read).toBe(0) - - const acknowledged = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { - terminal: WORKER_HANDLE, - compatibilityAck: JSON.stringify({ - messageIds: [question.id], - types: ['question'] - }) - }, - evidence('worker'), - 'valid-ack' - ) - ) - expect(acknowledged).toMatchObject({ - ok: true, - result: { acknowledged: [question.id], legacyCompatibility: { acknowledged: true } } - }) - expect(harness.db.getMessageById(status.id)?.read).toBe(0) - expect(harness.db.getMessageById(question.id)?.read).toBe(1) - }) - - it('rejects a legacy coordinator reply outside the adopted Run with zero effects', async () => { - const harness = createHarness() - const unrelatedRun = harness.db.createRun({ - objective: 'unrelated current work', - coordinatorHandle: 'term_unrelated_coord', - coordinatorPaneKey: 'tab_unrelated_coord:55555555-5555-4555-8555-555555555555' - }) - const unrelated = harness.db.insertMessage({ - runId: unrelatedRun.id, - from: 'term_unrelated_worker', - to: `run:${unrelatedRun.id}`, - subject: 'Unrelated current status', - deliveryContract: 'current_delivery' - }) - const before = counts(harness.db) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.reply', - { - id: unrelated.id, - body: 'Forged cross-Run reply', - from: COORDINATOR_HANDLE, - run: harness.adoptedRunId - }, - evidence('coordinator'), - 'cross-run-reply' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'request_mismatch', - data: { effectsApplied: false } - } - }) - expect(counts(harness.db)).toEqual(before) - expect(harness.db.getMessageById(unrelated.id)?.read).toBe(0) - expect(harness.notify).not.toHaveBeenCalled() - }) - - it.each(['dispatch', 'websocket'] as const)( - '%s binds an attested coordinator once and rejects contradictory proof before binding', - async (transport) => { - const invalidHarness = createHarness() - const invalidBefore = counts(invalidHarness.db) - const rejected = await invoke( - invalidHarness.dispatcher, - request( - 'orchestration.runUse', - { id: invalidHarness.adoptedRunId, from: COORDINATOR_HANDLE }, - evidence('coordinator', false), - `run-use-invalid-${transport}` - ), - transport - ) - expect(rejected).toMatchObject({ ok: false, error: { code: 'legacy_read_only' } }) - expect(invalidHarness.db.getRun(invalidHarness.adoptedRunId)?.consumer_generation).toBe(0) - expect(counts(invalidHarness.db)).toEqual(invalidBefore) - - const harness = createHarness() - const runUse = request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, - evidence('coordinator'), - `run-use-${transport}` - ) - const first = await invoke(harness.dispatcher, runUse, transport) - const replay = await invoke( - harness.dispatcher, - { ...runUse, id: 'rpc_run-use-replay' }, - transport - ) - expect(first).toMatchObject({ - ok: true, - result: { run: { consumer_generation: 1 }, mutation: { replayed: false } } - }) - expect(replay).toMatchObject({ - ok: true, - result: { run: { consumer_generation: 1 }, mutation: { replayed: true } } - }) - expect(harness.db.getRun(harness.adoptedRunId)?.consumer_generation).toBe(1) - } - ) -}) diff --git a/src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts b/src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts deleted file mode 100644 index f779d185b37..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-coordinator-race.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -import { createHash } from 'node:crypto' - -import { mkdtempSync, rmSync } from 'node:fs' - -import { tmpdir } from 'node:os' - -import { join } from 'node:path' - -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' - -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' - -import Database from '../../sqlite/sync-database' - -import { OrcaRuntimeService } from '../orca-runtime' - -import { OrchestrationDb } from '../orchestration/db/orchestration-db' - -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' - -import { RpcDispatcher } from './dispatcher' - -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' - -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' - -import { MessageWake } from '../orchestration/mailbox/runtime-message-waiters' - -const COORDINATOR_HANDLE = 'term_legacy_coord' -const COORDINATOR_PANE = 'tab_coord:44444444-4444-4444-8444-444444444444' -const WORKER_HANDLE = 'term_legacy_worker' -const WORKER_PANE = 'tab_worker:33333333-3333-4333-8333-333333333333' - -type Harness = { - db: OrchestrationDb - dispatcher: RpcDispatcher - runtime: OrcaRuntimeService - adoptedRunId: string - taskId: string - dispatchId: string -} - -const tempDirs: string[] = [] -const databases: OrchestrationDb[] = [] - -afterEach(() => { - databases.splice(0).forEach((database) => database.close()) - tempDirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })) -}) - -function createHarness(): Harness { - const dir = mkdtempSync(join(tmpdir(), 'orca-legacy-coordinator-race-')) - tempDirs.push(dir) - const dbPath = join(dir, 'orchestration.db') - const before = new OrchestrationDb(dbPath) - const task = before.createTask({ - runId: 'run_legacy_local', - spec: 'legacy assignment', - createdByTerminalHandle: COORDINATOR_HANDLE - }) - const dispatch = createRootDispatch(before, task.id, WORKER_HANDLE, WORKER_PANE) - before.close() - - const raw = new Database(dbPath) - raw.exec(` - UPDATE dispatch_contexts SET process_incarnation = 'process-1'; - DROP INDEX IF EXISTS idx_messages_delivery_contract; - DROP TABLE legacy_mail_receipts; - DROP TABLE legacy_operation_receipts; - DROP TABLE legacy_compatibility_principals; - DROP TABLE legacy_adoptions; - `) - raw.pragma('user_version = 18') - raw.close() - - const db = new OrchestrationDb(dbPath) - databases.push(db) - const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === COORDINATOR_HANDLE ? COORDINATOR_PANE : handle === WORKER_HANDLE ? WORKER_PANE : null - ) - vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => - runtime.getTerminalPaneKey(handle) - ) - vi.spyOn(runtime, 'verifyOrchestrationCompatibilityCaller').mockImplementation( - (compatibilityEvidence) => { - const coordinator = - compatibilityEvidence?.terminalHandle === COORDINATOR_HANDLE && - compatibilityEvidence.paneKey === COORDINATOR_PANE && - compatibilityEvidence.launchToken === 'coordinator-token' - const worker = - compatibilityEvidence?.terminalHandle === WORKER_HANDLE && - compatibilityEvidence.paneKey === WORKER_PANE && - compatibilityEvidence.launchToken === 'worker-token' - return coordinator || worker - ? { - hostScope: { kind: 'local', hostId: 'local' }, - terminalHandle: coordinator ? COORDINATOR_HANDLE : WORKER_HANDLE, - paneKey: coordinator ? COORDINATOR_PANE : WORKER_PANE, - processIncarnation: 'process-1', - launchTokenHash: createHash('sha256') - .update(coordinator ? 'coordinator-token' : 'worker-token') - .digest('hex') - } - : null - } - ) - return { - db, - dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }), - runtime, - adoptedRunId, - taskId: task.id, - dispatchId: dispatch.id - } -} - -function evidence( - role: 'coordinator' | 'worker' = 'coordinator' -): OrchestrationCompatibilityEvidence { - return { - terminalHandle: role === 'coordinator' ? COORDINATOR_HANDLE : WORKER_HANDLE, - paneKey: role === 'coordinator' ? COORDINATOR_PANE : WORKER_PANE, - launchToken: role === 'coordinator' ? 'coordinator-token' : 'worker-token' - } -} - -function request( - method: string, - params: unknown, - invocationId: string, - callerEvidence = evidence() -): RpcRequest { - return { - id: `rpc_${invocationId}`, - authToken: 'caller-token', - method, - params, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: invocationId, - compatibilityInvocationId: invocationId, - orchestrationCompatibilityEvidence: callerEvidence - } -} - -describe('legacy coordinator takeover races', () => { - it('partitions a coordinator group send by legacy recipient contract', async () => { - const harness = createHarness() - // Use two current-contract Dispatches in the adopted Run: group mail targets Dispatches, so a loose pane cannot prove partitioning. - const currentTask = harness.db.createTask({ - runId: harness.adoptedRunId, - spec: 'current-contract assignment', - createdByTerminalHandle: COORDINATOR_HANDLE - }) - const currentDispatch = createRootDispatch( - harness.db, - currentTask.id, - 'term_current_worker', - 'tab_current_worker:22222222-2222-4222-8222-222222222222' - ) - vi.mocked(harness.runtime.getTerminalPaneKey).mockImplementation((handle) => - handle === COORDINATOR_HANDLE - ? COORDINATOR_PANE - : handle === WORKER_HANDLE - ? WORKER_PANE - : handle === 'term_current_worker' - ? 'tab_current_worker:22222222-2222-4222-8222-222222222222' - : null - ) - vi.spyOn(harness.runtime, 'listTerminals').mockResolvedValue({ - terminals: [ - { handle: COORDINATOR_HANDLE }, - { handle: WORKER_HANDLE }, - { handle: 'term_current_worker' } - ], - totalCount: 3, - truncated: false - } as never) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.send', - { from: COORDINATOR_HANDLE, to: '@all', subject: 'group guidance' }, - 'send-group' - ) - ) - - expect(response).toMatchObject({ ok: true, result: { recipients: 2 } }) - const messages = harness.db - .getInbox(100) - .filter((message) => message.subject === 'group guidance') - expect(messages).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - run_id: harness.adoptedRunId, - to_handle: `dispatch:${harness.dispatchId}`, - delivery_contract: 'legacy_direct' - }), - expect.objectContaining({ - run_id: harness.adoptedRunId, - to_handle: `dispatch:${currentDispatch.id}`, - delivery_contract: 'current_delivery' - }) - ]) - ) - }) - - it('keeps concurrent duplicates on the live ACK-and-wait result', async () => { - const harness = createHarness() - harness.db.insertMessage({ - runId: harness.adoptedRunId, - from: WORKER_HANDLE, - to: `run:${harness.adoptedRunId}`, - subject: 'first delivery' - }) - const firstCheck = await harness.dispatcher.dispatch( - request( - 'orchestration.check', - { terminal: COORDINATOR_HANDLE, run: harness.adoptedRunId }, - 'check-first-delivery' - ) - ) - const deliveryId = (firstCheck as { result: { deliveryId: string } }).result.deliveryId - let resolveWait: (() => void) | undefined - let signalWaitStarted: (() => void) | undefined - const waitStarted = new Promise((resolve) => { - signalWaitStarted = resolve - }) - vi.spyOn(harness.runtime, 'waitForMessage').mockImplementation( - () => - new Promise((resolve) => { - resolveWait = () => resolve(new MessageWake()) - signalWaitStarted?.() - }) - ) - const ackRequest = request( - 'orchestration.check', - { - terminal: COORDINATOR_HANDLE, - run: harness.adoptedRunId, - ack: deliveryId, - wait: true, - timeoutMs: 10_000 - }, - 'check-ack-concurrent' - ) - const original = harness.dispatcher.dispatch(ackRequest) - await waitStarted - const secondLiveDispatcher = new RpcDispatcher({ - runtime: harness.runtime, - methods: ORCHESTRATION_METHODS - }) - const duplicate = secondLiveDispatcher.dispatch({ - ...ackRequest, - id: 'rpc_check-ack-concurrent-duplicate' - }) - let duplicateSettled = false - void duplicate.then(() => { - duplicateSettled = true - }) - await Promise.resolve() - expect(duplicateSettled).toBe(false) - - const arrived = harness.db.insertMessage({ - runId: harness.adoptedRunId, - from: WORKER_HANDLE, - to: `run:${harness.adoptedRunId}`, - subject: 'arrived while waiting' - }) - resolveWait?.() - const [originalResult, duplicateResult] = await Promise.all([original, duplicate]) - expect(originalResult).toMatchObject({ - ok: true, - result: { - messages: [{ id: arrived.id }], - mutation: { requestId: 'check-ack-concurrent', replayed: false } - } - }) - expect(duplicateResult).toMatchObject({ - ok: true, - result: { - messages: [{ id: arrived.id }], - mutation: { requestId: 'check-ack-concurrent', replayed: true } - } - }) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-legacy-fence-jurisdiction.test.ts b/src/main/runtime/rpc/orchestration-legacy-fence-jurisdiction.test.ts deleted file mode 100644 index 41aafc08779..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-fence-jurisdiction.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - COORDINATOR_HANDLE, - createHarness, - currentEvidence, - CURRENT_COORDINATOR_HANDLE, - CURRENT_COORDINATOR_PANE, - evidence, - request, - type LegacyCompatibilityDispatcherHarness -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() -}) - -function unattested(proof: OrchestrationCompatibilityEvidence): OrchestrationCompatibilityEvidence { - return { ...proof, launchToken: '' } -} - -async function claimAdoptedRunAsLegacyCoordinator( - harness: LegacyCompatibilityDispatcherHarness -): Promise { - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, - evidence('coordinator'), - 'legacy-coordinator-run-use' - ) - ) - expect(response).toMatchObject({ ok: true }) - expect(harness.db.getLegacyCoordinatorPrincipal(harness.adoptedRunId)?.status).toBe('committed') -} - -async function takeoverAdoptedRun(harness: LegacyCompatibilityDispatcherHarness): Promise { - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: CURRENT_COORDINATOR_HANDLE, takeoverLegacy: true }, - currentEvidence('coordinator'), - 'current-coordinator-takeover' - ) - ) - expect(response).toMatchObject({ ok: true }) - expect(harness.db.getLegacyCoordinatorPrincipal(harness.adoptedRunId)?.status).toBe('revoked') -} - -describe('legacy coordinator fence jurisdiction', () => { - it('declines jurisdiction over an unbound stranger while the adopted Run is claimed', async () => { - const harness = createHarness() - await claimAdoptedRunAsLegacyCoordinator(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { spec: 'fresh assignment', callerTerminalHandle: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('coordinator'), - 'claimed-stranger-task-create' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'run_required' } }) - expect(harness.db.listTasks({ runId: harness.adoptedRunId })).toHaveLength(1) - }) - - it('releases the fence once the adopted Run is unclaimed and its principal is revoked', async () => { - const harness = createHarness() - await claimAdoptedRunAsLegacyCoordinator(harness) - await takeoverAdoptedRun(harness) - // The new owner moves its pane to another Run, which unbinds the adopted Run. - const elsewhere = harness.db.createRun({ - objective: 'other work', - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - expect(elsewhere.id).not.toBe(harness.adoptedRunId) - harness.db.bindRun({ - runId: elsewhere.id, - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - expect(harness.db.getRun(harness.adoptedRunId)?.coordinator_pane_key).toBeNull() - - const fenced = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { spec: 'unclaimed assignment', callerTerminalHandle: COORDINATOR_HANDLE }, - evidence('coordinator'), - 'unclaimed-revoked-task-create' - ) - ) - expect(fenced).toMatchObject({ ok: false, error: { code: 'run_required' } }) - - const reclaim = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, - evidence('coordinator'), - 'unclaimed-revoked-run-use' - ) - ) - // The Run still holds live legacy work, so the honest downstream error — not a dead-end fence — answers. - expect(reclaim).toMatchObject({ - ok: false, - error: { - code: 'consumer_fenced', - data: { - recoveryCommand: `orca orchestration run-use --id ${harness.adoptedRunId} --takeover-legacy` - } - } - }) - - const recovered = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: COORDINATOR_HANDLE, takeoverLegacy: true }, - evidence('coordinator'), - 'unclaimed-revoked-run-takeover' - ) - ) - expect(recovered).toMatchObject({ ok: true, result: { run: { id: harness.adoptedRunId } } }) - }) - - it('leaves a named adopted Run to the downstream consumer check instead of the fence', async () => { - const harness = createHarness() - await claimAdoptedRunAsLegacyCoordinator(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'stranger assignment', - run: harness.adoptedRunId, - callerTerminalHandle: CURRENT_COORDINATOR_HANDLE - }, - currentEvidence('coordinator'), - 'claimed-stranger-named-run-task-create' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'consumer_fenced' } }) - expect(harness.db.listTasks({ runId: harness.adoptedRunId })).toHaveLength(1) - }) - - it('still fences the legacy coordinator after its principal is revoked by a takeover', async () => { - const harness = createHarness() - await claimAdoptedRunAsLegacyCoordinator(harness) - await takeoverAdoptedRun(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'stale assignment', - run: harness.adoptedRunId, - callerTerminalHandle: COORDINATOR_HANDLE - }, - evidence('coordinator'), - 'revoked-legacy-task-create' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'legacy_read_only' } }) - expect(harness.db.listTasks({ runId: harness.adoptedRunId })).toHaveLength(1) - }) - - it('lets the post-takeover owner operate the adopted Run without attestation', async () => { - const harness = createHarness() - await claimAdoptedRunAsLegacyCoordinator(harness) - await takeoverAdoptedRun(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'owner assignment', - run: harness.adoptedRunId, - callerTerminalHandle: CURRENT_COORDINATOR_HANDLE - }, - unattested(currentEvidence('coordinator')), - 'owner-unattested-task-create' - ) - ) - - expect(response).toMatchObject({ - ok: true, - result: { task: { run_id: harness.adoptedRunId, spec: 'owner assignment' } } - }) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-legacy-run-routing.test.ts b/src/main/runtime/rpc/orchestration-legacy-run-routing.test.ts deleted file mode 100644 index 49e2b78d6ae..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-run-routing.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - COORDINATOR_HANDLE, - createHarness, - currentEvidence, - CURRENT_COORDINATOR_HANDLE, - CURRENT_COORDINATOR_PANE, - evidence, - invoke, - request -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() -}) - -describe('legacy coordinator gate run routing', () => { - it.each(['dispatch', 'websocket'] as const)( - '%s asks an unbound caller to bind a Run instead of fencing it as a legacy coordinator', - async (transport) => { - const harness = createHarness() - - const response = await invoke( - harness.dispatcher, - request( - 'orchestration.taskCreate', - { - spec: 'fresh assignment', - callerTerminalHandle: CURRENT_COORDINATOR_HANDLE - }, - currentEvidence('coordinator'), - `unbound-task-create-${transport}` - ), - transport - ) - - expect(response).toMatchObject({ - ok: false, - error: { code: 'run_required' } - }) - expect(harness.db.listTasks({ runId: harness.adoptedRunId })).toHaveLength(1) - } - ) - - it('routes an unnamed Run to the caller binding even when attestation fails', async () => { - const harness = createHarness() - const run = harness.db.createRun({ - objective: 'current work', - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'fresh assignment', - callerTerminalHandle: CURRENT_COORDINATOR_HANDLE - }, - { ...currentEvidence('coordinator'), launchToken: '' }, - 'unattested-bound-task-create' - ) - ) - - expect(response).toMatchObject({ - ok: true, - result: { task: { run_id: run.id, spec: 'fresh assignment' } } - }) - }) - - it('lets a current coordinator rebind the unclaimed adopted Run with actionable guidance', async () => { - const harness = createHarness() - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.runUse', - { id: harness.adoptedRunId, from: CURRENT_COORDINATOR_HANDLE }, - currentEvidence('coordinator'), - 'unclaimed-adopted-run-use' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'consumer_fenced', - data: { - recoveryCommand: `orca orchestration run-use --id ${harness.adoptedRunId} --takeover-legacy` - } - } - }) - }) - - it('still routes the retained legacy coordinator to the adopted Run without --run', async () => { - const harness = createHarness() - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'retained assignment', - callerTerminalHandle: COORDINATOR_HANDLE - }, - evidence('coordinator'), - 'retained-adopted-task-create' - ) - ) - - expect(response).toMatchObject({ - ok: true, - result: { - task: { run_id: harness.adoptedRunId, spec: 'retained assignment' } - } - }) - }) - - it('still fences a stale legacy coordinator once the adopted Run is claimed', async () => { - const harness = createHarness() - harness.db.bindRun({ - runId: harness.adoptedRunId, - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE, - takeoverLegacy: true - }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.taskCreate', - { - spec: 'stale assignment', - run: harness.adoptedRunId, - callerTerminalHandle: COORDINATOR_HANDLE - }, - evidence('coordinator'), - 'claimed-adopted-task-create' - ) - ) - - expect(response).toMatchObject({ - ok: false, - error: { code: 'legacy_read_only' } - }) - expect(harness.db.listTasks({ runId: harness.adoptedRunId })).toHaveLength(1) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-legacy-session-address-migration.test.ts b/src/main/runtime/rpc/orchestration-legacy-session-address-migration.test.ts deleted file mode 100644 index c662917fc22..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-session-address-migration.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrchestrationDb } from '../orchestration/db/orchestration-db' -import { migrateV43 } from '../orchestration/db/schema/migrate-v43' -import { - ADDRESS_X, - ADDRESS_Y, - createSessionCallerHarness, - orchestrationRequest, - resultOf, - SESSION_X, - SESSION_Y, - WORKER_HANDLE, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -const LEGACY_X = `session:${SESSION_X}` -const LEGACY_Y = `session:${SESSION_Y}` -// Remembered under both spellings; a session of its own, so routing to Y stays unambiguous. -const BOTH_SESSION = '5c5c5c5c-6d6d-4e7e-8f8f-909090909090' - -/** What an earlier build, which spelled a session's address `session:`, left in a v42 database. */ -function seedEarlierBuildRows(db: OrchestrationDb): { toX: string; fromX: string } { - // Subject and body spell the old address too: text, not an address, so it must survive as written. - const toX = db.insertMessage({ - from: WORKER_HANDLE, - to: ADDRESS_X, - subject: LEGACY_X, - body: LEGACY_X - }) - const fromX = db.insertMessage({ from: ADDRESS_X, to: WORKER_HANDLE, subject: 'q', body: 'b' }) - db.db.prepare('UPDATE messages SET to_handle = ? WHERE id = ?').run(LEGACY_X, toX.id) - db.db.prepare('UPDATE messages SET from_handle = ? WHERE id = ?').run(LEGACY_X, fromX.id) - db.db - .prepare( - `INSERT INTO runs (id, objective, consumer_generation, legacy) VALUES - ('run_earlier', 'coordinated by Y', 1, 0), ('run_both', 'remembered twice', 1, 0)` - ) - .run() - const remember = db.db.prepare( - 'INSERT INTO run_coordinator_handles (run_id, terminal_handle) VALUES (?, ?)' - ) - remember.run('run_earlier', LEGACY_Y) - remember.run('run_both', `session:${BOTH_SESSION}`) - remember.run('run_both', `orca_session_id:${BOTH_SESSION}`) - const pointer = db.db.prepare( - `INSERT INTO structured_pointer_operations - (mailbox_handle, session_id, operation_id, batch_fingerprint, minted_at_ms) - VALUES (?, ?, ?, 'batch', 1)` - ) - pointer.run(LEGACY_X, SESSION_X, 'op_legacy_x') - pointer.run(LEGACY_Y, SESSION_Y, 'op_legacy_y') - pointer.run(ADDRESS_Y, SESSION_Y, 'op_current_y') - db.createCoordinatorRun({ spec: 'spec', coordinatorHandle: LEGACY_X }) - db.db.pragma('user_version = 42') - return { toX: toX.id, fromX: fromX.id } -} - -function snapshot(db: OrchestrationDb): unknown[] { - return [ - 'SELECT id, from_handle, to_handle, subject, body FROM messages ORDER BY id', - 'SELECT run_id, terminal_handle FROM run_coordinator_handles ORDER BY run_id, terminal_handle', - 'SELECT mailbox_handle, operation_id FROM structured_pointer_operations ORDER BY mailbox_handle', - 'SELECT coordinator_handle FROM coordinator_runs' - ].map((sql) => db.db.prepare(sql).all()) -} - -describe('a database an earlier build wrote session: addresses into', () => { - let h: SessionCallerHarness - let seeded: { toX: string; fromX: string } - - beforeEach(() => { - h = createSessionCallerHarness(hostRef, () => ({ - present: true, - sessionIds: [SESSION_X, SESSION_Y] - })) - seeded = seedEarlierBuildRows(h.db) - h.db.migrate() - }) - - afterEach(() => { - h.close() - vi.restoreAllMocks() - }) - - it('gives the chat the mail sent to it before the upgrade, through its own check', async () => { - const checked = resultOf( - await h.dispatch(orchestrationRequest('orchestration.check', {}, { sessionId: SESSION_X })) - ) - expect(checked.messages).toEqual([ - expect.objectContaining({ - id: seeded.toX, - to_handle: ADDRESS_X, - subject: LEGACY_X, - body: LEGACY_X - }) - ]) - }) - - it('still routes mail to a chat into the Run it was remembered for under the old spelling', async () => { - const sent = await h.dispatch( - orchestrationRequest('orchestration.send', { - from: WORKER_HANDLE, - to: ADDRESS_Y, - subject: 's' - }) - ) - expect(sent).toMatchObject({ ok: true, result: { message: { to_handle: 'run:run_earlier' } } }) - }) - - it('leaves no address in the old spelling, keeping the current row where both were keyed', () => { - const [messages, remembered, pointers, coordinatorRuns] = snapshot(h.db) - expect(JSON.stringify([messages, remembered, pointers, coordinatorRuns])).not.toMatch( - /"(from_handle|to_handle|terminal_handle|mailbox_handle|coordinator_handle)":"session:/ - ) - expect(remembered).toEqual([ - { run_id: 'run_both', terminal_handle: `orca_session_id:${BOTH_SESSION}` }, - { run_id: 'run_earlier', terminal_handle: ADDRESS_Y } - ]) - expect(pointers).toEqual([ - { mailbox_handle: ADDRESS_X, operation_id: 'op_legacy_x' }, - { mailbox_handle: ADDRESS_Y, operation_id: 'op_current_y' } - ]) - expect(coordinatorRuns).toEqual([{ coordinator_handle: ADDRESS_X }]) - }) - - it('changes nothing when it runs again', () => { - const before = snapshot(h.db) - migrateV43.call(h.db, 42) - expect(snapshot(h.db)).toEqual(before) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts b/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts deleted file mode 100644 index 7d09650965e..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { createHash } from 'node:crypto' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { OrcaRuntimeService } from '../orca-runtime' -import { RpcDispatcher } from './dispatcher' -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - createHarness, - currentEvidence, - CURRENT_COORDINATOR_HANDLE, - CURRENT_COORDINATOR_PANE, - request -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() -}) - -describe('legacy takeover by current runtime authority', () => { - it('accepts a fresh current agent before its first hook observation', async () => { - const harness = createHarness() - const hookServer = new AgentHookServer() - const runtime = new OrcaRuntimeService(null, undefined, { - attestAgentHookCompatibilityAuthority: (candidate) => - hookServer.attestCompatibilityAuthority(candidate) - }) - const proof = currentEvidence('coordinator') - const launchTokenHash = createHash('sha256').update(proof.launchToken!).digest('hex') - runtime.setOrchestrationDb(harness.db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue(CURRENT_COORDINATOR_PANE) - vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({ - runtimeId: 'runtime-current', - terminalHandle: CURRENT_COORDINATOR_HANDLE, - ptyId: 'pty-current', - worktreeId: 'repo::/worktree', - processIncarnation: 'process-current', - paneKey: CURRENT_COORDINATOR_PANE, - launchTokenHash, - hostScope: { kind: 'local', hostId: 'local' } - }) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - - // Legacy compatibility mutations still require a hook observation. - expect(runtime.verifyOrchestrationCompatibilityCaller(proof)).toBeNull() - for (const [invocationId, forgedProof] of [ - ['forged-token', { ...proof, launchToken: 'forged-token' }], - ['forged-pane', { ...proof, paneKey: 'tab_forged:66666666-6666-4666-8666-666666666666' }] - ] as const) { - const rejected = await dispatcher.dispatch( - request( - 'orchestration.runUse', - { - id: harness.adoptedRunId, - from: CURRENT_COORDINATOR_HANDLE, - takeoverLegacy: true - }, - forgedProof, - invocationId - ) - ) - expect(rejected).toMatchObject({ - ok: false, - error: { code: 'legacy_read_only', data: { effectsApplied: false } } - }) - } - - const response = await dispatcher.dispatch( - request( - 'orchestration.runUse', - { - id: harness.adoptedRunId, - from: CURRENT_COORDINATOR_HANDLE, - takeoverLegacy: true - }, - proof, - 'fresh-current-agent-takeover' - ) - ) - - expect(response).toMatchObject({ - ok: true, - result: { - run: { id: harness.adoptedRunId, coordinator_handle: CURRENT_COORDINATOR_HANDLE } - } - }) - expect(harness.db.getRun(harness.adoptedRunId)?.coordinator_pane_key).toBe( - CURRENT_COORDINATOR_PANE - ) - }) - - it('requires a runtime-issued SSH attachment for fresh launch proof', async () => { - const harness = createHarness() - const runtime = new OrcaRuntimeService() - const proof = currentEvidence('coordinator') - const launchTokenHash = createHash('sha256').update(proof.launchToken!).digest('hex') - const host = runtime.registerOrchestrationCompatibilitySshAttachment( - 'saved-target', - 'connection-current' - ) - vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({ - runtimeId: 'runtime-current', - terminalHandle: CURRENT_COORDINATOR_HANDLE, - ptyId: 'pty-current', - worktreeId: 'repo::/worktree', - processIncarnation: 'process-current', - paneKey: CURRENT_COORDINATOR_PANE, - launchTokenHash, - hostScope: { kind: 'ssh', targetId: 'saved-target' } - }) - runtime.setOrchestrationDb(harness.db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue(CURRENT_COORDINATOR_PANE) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - - const params = { - id: harness.adoptedRunId, - from: CURRENT_COORDINATOR_HANDLE, - takeoverLegacy: true - } - const rejected = await dispatcher.dispatch( - request( - 'orchestration.runUse', - params, - { ...proof, host: { ...host, attachmentId: 'caller-chosen' } }, - 'forged-ssh-attachment' - ) - ) - expect(rejected).toMatchObject({ - ok: false, - error: { code: 'legacy_read_only', data: { effectsApplied: false } } - }) - - const response = await dispatcher.dispatch( - request('orchestration.runUse', params, { ...proof, host }, 'valid-ssh-attachment') - ) - expect(response).toMatchObject({ ok: true }) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-legacy-takeover-delivery.test.ts b/src/main/runtime/rpc/orchestration-legacy-takeover-delivery.test.ts deleted file mode 100644 index 8365f3e3205..00000000000 --- a/src/main/runtime/rpc/orchestration-legacy-takeover-delivery.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -import { createHash } from 'node:crypto' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import Database from '../../sqlite/sync-database' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' - -const WORKER_HANDLE = 'term_legacy_worker' -const WORKER_PANE = 'tab_worker:33333333-3333-4333-8333-333333333333' -const COORDINATOR_HANDLE = 'term_legacy_coord' -const COORDINATOR_PANE = 'tab_coord:44444444-4444-4444-8444-444444444444' -const CURRENT_COORDINATOR_HANDLE = 'term_current_coord' -const CURRENT_COORDINATOR_PANE = 'tab_current:55555555-5555-4555-8555-555555555555' -// A coordinator terminal that restarted inside the legacy coordinator's own pane. -const REBOUND_COORDINATOR_HANDLE = 'term_rebound_coord' - -type Harness = { - db: OrchestrationDb - dispatcher: RpcDispatcher - runtime: OrcaRuntimeService - adoptedRunId: string - taskId: string - dispatchId: string -} - -const tempDirs: string[] = [] -const databases: OrchestrationDb[] = [] - -afterEach(() => { - for (const database of databases.splice(0)) { - database.close() - } - for (const dir of tempDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function createHarness(): Harness { - const dir = mkdtempSync(join(tmpdir(), 'orca-legacy-takeover-delivery-')) - tempDirs.push(dir) - const dbPath = join(dir, 'orchestration.db') - const before = new OrchestrationDb(dbPath) - const task = before.createTask({ - runId: 'run_legacy_local', - spec: 'legacy assignment', - createdByTerminalHandle: COORDINATOR_HANDLE - }) - const dispatch = createRootDispatch(before, task.id, WORKER_HANDLE, WORKER_PANE) - before.close() - - const raw = new Database(dbPath) - raw.exec(` - UPDATE dispatch_contexts SET process_incarnation = 'process-1'; - DROP INDEX IF EXISTS idx_messages_delivery_contract; - DROP TABLE legacy_mail_receipts; - DROP TABLE legacy_operation_receipts; - DROP TABLE legacy_compatibility_principals; - DROP TABLE legacy_adoptions; - `) - raw.pragma('user_version = 18') - raw.close() - - const db = new OrchestrationDb(dbPath) - databases.push(db) - const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === COORDINATOR_HANDLE - ? COORDINATOR_PANE - : handle === WORKER_HANDLE - ? WORKER_PANE - : handle === CURRENT_COORDINATOR_HANDLE - ? CURRENT_COORDINATOR_PANE - : handle === REBOUND_COORDINATOR_HANDLE - ? COORDINATOR_PANE - : null - ) - vi.spyOn(runtime, 'verifyOrchestrationCompatibilityCaller').mockImplementation((proof) => { - const valid = - (proof?.terminalHandle === WORKER_HANDLE && proof.paneKey === WORKER_PANE) || - (proof?.terminalHandle === COORDINATOR_HANDLE && proof.paneKey === COORDINATOR_PANE) || - (proof?.terminalHandle === CURRENT_COORDINATOR_HANDLE && - proof.paneKey === CURRENT_COORDINATOR_PANE) - if (!valid || !proof?.launchToken) { - return null - } - return { - hostScope: { kind: 'local', hostId: 'local' }, - terminalHandle: proof.terminalHandle as string, - paneKey: proof.paneKey as string, - processIncarnation: 'process-1', - launchTokenHash: createHash('sha256').update(proof.launchToken).digest('hex') - } - }) - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) - return { - db, - dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }), - runtime, - adoptedRunId, - taskId: task.id, - dispatchId: dispatch.id - } -} - -function evidence( - role: 'worker' | 'coordinator' | 'current-coordinator' -): OrchestrationCompatibilityEvidence { - const map = { - worker: { handle: WORKER_HANDLE, pane: WORKER_PANE }, - coordinator: { handle: COORDINATOR_HANDLE, pane: COORDINATOR_PANE }, - 'current-coordinator': { handle: CURRENT_COORDINATOR_HANDLE, pane: CURRENT_COORDINATOR_PANE } - } - const entry = map[role] - return { - terminalHandle: entry.handle, - paneKey: entry.pane, - launchToken: `${role}-token` - } -} - -function request( - method: string, - params: unknown, - proof: OrchestrationCompatibilityEvidence, - invocationId: string -): RpcRequest { - return { - id: `rpc_${invocationId}`, - authToken: 'caller-token', - method, - params, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: invocationId, - compatibilityInvocationId: invocationId, - orchestrationCompatibilityEvidence: proof - } -} - -function commitLegacyCoordinatorPrincipal(harness: Harness): { id: string } { - const { principal } = harness.db.commitLegacyCompatibilityPrincipal({ - runId: harness.adoptedRunId, - role: 'coordinator', - hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), - terminalHandle: COORDINATOR_HANDLE, - paneKey: COORDINATOR_PANE, - launchTokenHash: 'coord-hash', - processIncarnation: 'process-1' - }) - expect(principal.status).toBe('committed') - return principal -} - -// Check binding here so failure names its cause rather than surfacing in later mail assertions. -function takeOverWithCommittedPrincipal(harness: Harness): void { - commitLegacyCoordinatorPrincipal(harness) - const bound = harness.db.bindRun({ - runId: harness.adoptedRunId, - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE, - takeoverLegacy: true - }) - expect(bound).toMatchObject({ - id: harness.adoptedRunId, - coordinator_handle: CURRENT_COORDINATOR_HANDLE, - coordinator_pane_key: CURRENT_COORDINATOR_PANE - }) - expect(harness.db.getLegacyCoordinatorPrincipal(harness.adoptedRunId)?.status).toBe('revoked') -} - -describe('legacy coordinator delivery targets after takeover', () => { - it('lets a worker ask the new coordinator and get an answer after principal revocation', async () => { - const harness = createHarness() - takeOverWithCommittedPrincipal(harness) - - const asked = (await harness.dispatcher.dispatch( - request( - 'orchestration.ask', - { from: WORKER_HANDLE, to: CURRENT_COORDINATOR_HANDLE, question: 'Ship it?', timeoutMs: 0 }, - evidence('worker'), - 'ask-new-coordinator' - ) - )) as { ok: boolean; result: { messageId: string } } - - expect(asked).toMatchObject({ ok: true, result: { timedOut: true } }) - // The ask must reach the Run mailbox as a current-contract question, or nobody can answer it. - expect(harness.db.getMessageById(asked.result.messageId)).toMatchObject({ - to_handle: `run:${harness.adoptedRunId}`, - delivery_contract: 'current_delivery', - type: 'question' - }) - - const replied = await harness.dispatcher.dispatch( - request( - 'orchestration.reply', - { id: asked.result.messageId, from: CURRENT_COORDINATOR_HANDLE, body: 'Yes, ship it.' }, - evidence('current-coordinator'), - 'reply-from-new-coordinator' - ) - ) - expect(replied).toMatchObject({ ok: true }) - - const resumed = await harness.dispatcher.dispatch( - request( - 'orchestration.ask', - { from: WORKER_HANDLE, resume: asked.result.messageId, timeoutMs: 0 }, - evidence('worker'), - 'ask-resume-after-reply' - ) - ) - expect(resumed).toMatchObject({ ok: true, result: { answer: 'Yes, ship it.' } }) - }) -}) - -// Restart within the legacy pane can rebind while its principal stays committed; refuse legacy_direct mail that neither contract can read. -describe('legacy coordinator delivery targets without a takeover', () => { - function rebindLegacyPaneWithoutTakeover(harness: Harness): { principalId: string } { - const principal = commitLegacyCoordinatorPrincipal(harness) - const run = harness.db.getRun(harness.adoptedRunId) as { consumer_generation: number } - expect( - harness.db.bindRun({ - runId: harness.adoptedRunId, - coordinatorHandle: COORDINATOR_HANDLE, - coordinatorPaneKey: COORDINATOR_PANE, - legacyCoordinatorAuthority: { - runId: harness.adoptedRunId, - principalId: principal.id, - terminalHandle: COORDINATOR_HANDLE, - paneKey: COORDINATOR_PANE, - consumerGeneration: run.consumer_generation - } - }) - ).toMatchObject({ coordinator_handle: COORDINATOR_HANDLE }) - - expect( - harness.db.bindRun({ - runId: harness.adoptedRunId, - coordinatorHandle: REBOUND_COORDINATOR_HANDLE, - coordinatorPaneKey: COORDINATOR_PANE - }) - ).toMatchObject({ coordinator_handle: REBOUND_COORDINATOR_HANDLE }) - expect(harness.db.getLegacyCoordinatorPrincipal(harness.adoptedRunId)?.status).toBe('committed') - return { principalId: principal.id } - } - - it('rejects worker_done to the rebound handle instead of writing unreadable mail', async () => { - const harness = createHarness() - const { principalId } = rebindLegacyPaneWithoutTakeover(harness) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.send', - { - from: WORKER_HANDLE, - to: REBOUND_COORDINATOR_HANDLE, - subject: 'Completed', - type: 'worker_done', - payload: JSON.stringify({ - taskId: harness.taskId, - dispatchId: harness.dispatchId, - outcome: 'succeeded' - }) - }, - evidence('worker'), - 'worker-done-to-rebound-coordinator' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'request_mismatch' } }) - expect(harness.db.getUnreadMessages(REBOUND_COORDINATOR_HANDLE)).toHaveLength(0) - expect(harness.db.getLegacyMailHistory({ principalId }).messages).toHaveLength(0) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-mutation-executor.test.ts b/src/main/runtime/rpc/orchestration-mutation-executor.test.ts deleted file mode 100644 index c3e7a5466b8..00000000000 --- a/src/main/runtime/rpc/orchestration-mutation-executor.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import 'node:crypto' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' -import { OrchestrationMutationExecutor } from './orchestration-mutation-executor' - -const promptParams = { - terminal: 'term-prompt', - text: 'retry safely', - enter: true, - agentPrompt: true, - client: { id: 'orca-cli', type: 'desktop' } -} as const - -function promptRequest(requestId: string): RpcRequest { - return { - id: `rpc-${requestId}`, - authToken: 'token', - method: 'terminal.send', - orchestrationRequestId: requestId, - params: promptParams - } -} - -function workerStartRequest(method: string, requestId: string, params: unknown): RpcRequest { - return { - id: `rpc-${requestId}`, - authToken: 'token', - method, - orchestrationRequestId: requestId, - params - } -} - -function createHarness() { - const db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const binding = vi.spyOn(runtime, 'getTerminalPromptRequestBinding').mockReturnValue({ - ptyId: 'pty-prompt', - processIncarnation: 'incarnation-1', - generation: 1 - }) - // Every handle for this PTY resolves to one pane, so a re-minted handle is the same terminal. - vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue('window-1:leaf-prompt') - return { - db, - runtime, - executor: new OrchestrationMutationExecutor(runtime), - bindTerminal: (next: { generation: number; processIncarnation: string }) => { - binding.mockReturnValue({ ptyId: 'pty-prompt', ...next }) - } - } -} - -describe('terminal prompt mutation receipt retry boundary', () => { - const databases: OrchestrationDb[] = [] - - afterEach(() => { - for (const db of databases.splice(0)) { - db.close() - } - vi.restoreAllMocks() - }) - - it('keeps a failed receipt after the write boundary becomes ambiguous', async () => { - const harness = createHarness() - databases.push(harness.db) - const invoke = vi.fn((mutation) => { - mutation?.markEffectPossible() - throw new Error('terminal_not_writable') - }) - - await expect( - harness.executor.run(promptRequest('post-write'), promptParams, invoke) - ).rejects.toThrow('terminal_not_writable') - await expect( - harness.executor.run(promptRequest('post-write'), promptParams, invoke) - ).rejects.toMatchObject({ code: 'operation_unknown' }) - expect(invoke).toHaveBeenCalledOnce() - }) - - it('returns the durable receipt when a replay-only observation cannot run', async () => { - const harness = createHarness() - databases.push(harness.db) - const requestId = 'observe-replay-rejected' - const params = { ...promptParams, waitSubmitMs: 100 } - const request = { ...promptRequest(requestId), params } - const invoke = vi - .fn() - .mockResolvedValueOnce({ - send: { prompt: { stages: ['input_accepted'] } } - }) - .mockRejectedValueOnce(new Error('terminal was parked')) - - await expect(harness.executor.run(request, params, invoke)).resolves.toMatchObject({ - send: { prompt: { stages: ['input_accepted'] } }, - mutation: { replayed: false } - }) - await expect(harness.executor.run(request, params, invoke)).resolves.toMatchObject({ - send: { prompt: { stages: ['input_accepted'] } }, - mutation: { replayed: true } - }) - expect(invoke).toHaveBeenCalledTimes(2) - }) - - it('reports a replay as incarnation_replaced once the PTY generation advances', async () => { - const harness = createHarness() - databases.push(harness.db) - const requestId = 'stale-binding-replay' - const invoke = vi.fn().mockResolvedValue({ - send: { prompt: { stages: ['input_accepted', 'turn_started'], observation: 'supported' } } - }) - - await expect( - harness.executor.run(promptRequest(requestId), promptParams, invoke) - ).resolves.toMatchObject({ send: { prompt: { observation: 'supported' } } }) - - harness.bindTerminal({ generation: 2, processIncarnation: 'incarnation-2' }) - await expect( - harness.executor.run(promptRequest(requestId), promptParams, invoke) - ).resolves.toMatchObject({ - send: { prompt: { observation: 'incarnation_replaced' } }, - mutation: { replayed: true } - }) - expect(invoke).toHaveBeenCalledOnce() - }) - - it('replays a byte-identical prompt after the handle is re-minted', async () => { - const harness = createHarness() - databases.push(harness.db) - const requestId = 'rebound-handle-replay' - const invoke = vi.fn().mockResolvedValue({ - send: { prompt: { stages: ['input_accepted', 'turn_started'], observation: 'supported' } } - }) - - await harness.executor.run(promptRequest(requestId), promptParams, invoke) - const reminted = { ...promptParams, terminal: 'term_00000000-0000-4000-8000-000000000000' } - const request = { ...promptRequest(requestId), params: reminted } - - await expect(harness.executor.run(request, reminted, invoke)).resolves.toMatchObject({ - send: { prompt: { observation: 'supported' } }, - mutation: { replayed: true } - }) - expect(invoke).toHaveBeenCalledOnce() - }) -}) - -describe('worker start mutation coalescing', () => { - const databases: OrchestrationDb[] = [] - - afterEach(() => { - for (const db of databases.splice(0)) { - db.close() - } - vi.restoreAllMocks() - }) - - it.each(['orchestration.workerStart', 'orchestration.federationAttachStart'])( - 'joins concurrent identical %s calls before durable acceptance', - async (method) => { - const harness = createHarness() - databases.push(harness.db) - const requestId = `concurrent-${method}` - const params = { taskId: 'task-1', taskSpec: 'specification' } - let release!: () => void - const gate = new Promise((resolve) => { - release = resolve - }) - const invoke = vi.fn( - async (mutation?: { identity: Parameters[0] }) => { - if (mutation) { - harness.db.beginMutationReceipt(mutation.identity) - } - await gate - return { accepted: { dispatchId: 'dispatch-1' } } - } - ) - - const calls = Promise.all([ - harness.executor.run(workerStartRequest(method, requestId, params), params, invoke), - harness.executor.run(workerStartRequest(method, requestId, params), params, invoke) - ]) - release() - const [first, replay] = await calls - - expect(invoke).toHaveBeenCalledOnce() - expect(first).toMatchObject({ - accepted: { dispatchId: 'dispatch-1' }, - mutation: { requestId, replayed: false } - }) - expect(replay).toMatchObject({ - accepted: { dispatchId: 'dispatch-1' }, - mutation: { requestId, replayed: true } - }) - } - ) - - it('fences a concurrent worker start with a different payload', async () => { - const harness = createHarness() - databases.push(harness.db) - let release!: () => void - const gate = new Promise((resolve) => { - release = resolve - }) - const invoke = vi.fn( - async (mutation?: { identity: Parameters[0] }) => { - if (mutation) { - harness.db.beginMutationReceipt(mutation.identity) - } - await gate - return { accepted: true } - } - ) - const firstParams = { taskId: 'task-1', taskSpec: 'first' } - const secondParams = { taskId: 'task-1', taskSpec: 'second' } - const first = harness.executor.run( - workerStartRequest('orchestration.workerStart', 'payload-mismatch', firstParams), - firstParams, - invoke - ) - - await expect( - harness.executor.run( - workerStartRequest('orchestration.workerStart', 'payload-mismatch', secondParams), - secondParams, - invoke - ) - ).rejects.toMatchObject({ code: 'request_mismatch' }) - release() - await first - expect(invoke).toHaveBeenCalledOnce() - }) -}) - -describe('a stop or Run cancel interrupted by a restart', () => { - it.each(['orchestration.workerStop', 'orchestration.peerRunCancel'])( - '%s runs again on a retry with the same request ID instead of answering operation_unknown', - async (method) => { - const harness = createHarness() - const params = method === 'orchestration.workerStop' ? { dispatch: 'ctx_1' } : {} - // The first attempt's receipt is pending when this runtime goes away. - void harness.executor.run( - workerStartRequest(method, 'stop-1.1:ctx_1', params), - params, - () => new Promise(() => {}) - ) - const restarted = new OrchestrationMutationExecutor(harness.runtime) - - const invoke = vi.fn(async () => ({ remaining: 0 })) - await expect( - restarted.run(workerStartRequest(method, 'stop-1.1:ctx_1', params), params, invoke) - ).resolves.toMatchObject({ remaining: 0 }) - expect(invoke).toHaveBeenCalledOnce() - harness.db.close() - } - ) -}) diff --git a/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts b/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts deleted file mode 100644 index de2976dc20a..00000000000 --- a/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { createHash } from 'node:crypto' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { z } from 'zod' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' -import { defineOrchestrationMethod } from './methods/orchestration/access/orchestration-method-access' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' - -describe('durable orchestration mutation ledger', () => { - const paths: string[] = [] - - afterEach(() => { - for (const path of paths.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } - }) - - it('returns the accepted Dispatch when worker-start was interrupted by restart', async () => { - const db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const params = { - from: 'term_coord', - task: db.createTask({ runId: 'run_legacy_local', spec: 'restart' }).id - } - const callerFingerprint = db.getOrCreateLocalMutationCallerFingerprint() - const payloadHash = createHash('sha256') - .update(JSON.stringify({ method: 'orchestration.workerStart', params })) - .digest('hex') - const started = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: params.task, - startOptions: {}, - mutationReceipt: { - callerFingerprint, - requestId: 'mutation_worker_start', - method: 'orchestration.workerStart', - payloadHash - } - }) - const effect = vi.fn() - const dispatcher = new RpcDispatcher({ - runtime, - methods: [ - defineOrchestrationMethod({ - name: 'orchestration.workerStart', - permission: 'workspace', - access: { kind: 'writes', targets: {} }, - params: z.object({ from: z.string(), task: z.string() }), - handler: effect - }) - ] - }) - - const result = await dispatcher.dispatch({ - id: 'rpc_worker_start_retry', - authToken: 'caller-token', - method: 'orchestration.workerStart', - params, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'mutation_worker_start' - }) - - expect(result).toMatchObject({ - ok: false, - error: { - code: 'operation_unknown', - data: { - requestId: 'mutation_worker_start', - dispatchId: started.dispatch.id, - recoveryCommand: `orca orchestration worker-show --dispatch ${started.dispatch.id} --json` - } - } - }) - expect(effect).not.toHaveBeenCalled() - db.close() - }) - - it('recovers a lost ask acceptance without creating a second question', async () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-mutation-ask-recovery-')) - paths.push(dir) - const dbPath = join(dir, 'orchestration.db') - const db = new OrchestrationDb(dbPath) - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue('tab_worker:leaf_worker') - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1') - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) - vi.spyOn(runtime, 'waitForMessage').mockImplementation( - async (_address, options) => - await new Promise<'cancelled'>((resolve) => { - options?.signal?.addEventListener('abort', () => resolve('cancelled'), { once: true }) - }) - ) - const run = db.createRun({ - objective: 'Ask recovery', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_coord:leaf_coord' - }) - const task = db.createTask({ spec: 'ask', runId: run.id }) - createRootDispatch( - db, - task.id, - 'term_worker', - 'tab_worker:leaf_worker', - undefined, - 'runtime:pty:1' - ) - const askRequest: RpcRequest = { - id: 'rpc_ask_1', - authToken: 'caller-token', - method: 'orchestration.ask', - params: { from: 'term_worker', question: 'Proceed?', timeoutMs: 60_000 }, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: 'mutation_ask' - } - const controller = new AbortController() - const firstDispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - const first = firstDispatcher.dispatch(askRequest, { signal: controller.signal }) - await vi.waitFor(() => expect(db.getInbox(10)).toHaveLength(1)) - - const restartedDb = new OrchestrationDb(dbPath) - const restartedRuntime = new OrcaRuntimeService() - restartedRuntime.setOrchestrationDb(restartedDb) - vi.spyOn(restartedRuntime, 'getTerminalPaneKey').mockReturnValue('tab_worker:leaf_worker') - vi.spyOn(restartedRuntime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1') - vi.spyOn(restartedRuntime, 'notifyMessageArrived').mockImplementation(() => {}) - const restartedDispatcher = new RpcDispatcher({ - runtime: restartedRuntime, - methods: ORCHESTRATION_METHODS - }) - const recovered = await restartedDispatcher.dispatch({ ...askRequest, id: 'rpc_ask_2' }) - expect(recovered).toMatchObject({ - ok: true, - result: { - accepted: true, - messageId: expect.stringMatching(/^msg_/), - mutation: { requestId: 'mutation_ask', replayed: true } - } - }) - expect(db.getInbox(10)).toHaveLength(1) - - controller.abort() - await first - restartedDb.close() - db.close() - }) -}) diff --git a/src/main/runtime/rpc/orchestration-party-addressing.test.ts b/src/main/runtime/rpc/orchestration-party-addressing.test.ts deleted file mode 100644 index e4d28ced38b..00000000000 --- a/src/main/runtime/rpc/orchestration-party-addressing.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { formatOrcaSessionAddress } from '../../../shared/orca-session-address' -import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' - -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - ADDRESS_Y, - createSessionCallerHarness, - idOf, - orchestrationRequest, - resultOf, - SESSION_X, - SESSION_Y, - sessionRecord, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -type Row = Record - -const SESSION_Z = testOrcaSessionId('3f9a1c7e-6b2d-4e85-a0c4-9d1e7b3f5a26') -const ADDRESS_Z = formatOrcaSessionAddress(SESSION_Z) - -/** Worker Y's two spellings; a chat has only its session address. */ -const handle = mintStructuredWorkerHandle() -const paneKey = mintStructuredWorkerPaneKey(SESSION_Y) -const WORKER_SPELLINGS = [ - ['its handle', handle], - ['its session address', ADDRESS_Y] -] as const - -let h: SessionCallerHarness - -beforeEach(() => { - h = createSessionCallerHarness(hostRef) - h.records.set(SESSION_Z, sessionRecord(SESSION_Z)) - structuredWorkerIdentities.register({ - handle, - sessionId: SESSION_Y, - agent: 'claude', - paneKey, - processIncarnation: structuredWorkerProcessIncarnation(SESSION_Y), - worktreeId: 'wt_1', - hostScope: { kind: 'local', hostId: 'local' } - }) -}) - -afterEach(() => { - h.close() - vi.restoreAllMocks() -}) - -function call(sessionId: string | undefined, method: string, params: Row) { - return h.dispatch(orchestrationRequest(method, params, { sessionId })) -} - -async function as(sessionId: string | undefined, method: string, params: Row): Promise { - return resultOf(await call(sessionId, method, params)) -} - -function chatRun(sessionId = SESSION_X): Promise { - return as(sessionId, 'orchestration.runCreate', { objective: 'o' }).then(({ run }) => idOf(run)) -} - -/** Worker Y assigned a Dispatch in `runId`, as `worker-start` leaves it. */ - -/** The PTY terminal assigned a Dispatch in a Run, so it may ask that Run's coordinator. */ - -describe('every target param resolves both spellings of a party to one canonical address', () => { - it.each(WORKER_SPELLINGS)( - 'dispatch: a worker named by %s is the assignee, and its check reads the Dispatch', - async (_l, to) => { - const runId = await chatRun() - const task = h.db.createTask({ runId, spec: 'work' }) - - const { dispatch } = await as(SESSION_X, 'orchestration.dispatch', { task: task.id, to }) - - expect(dispatch).toMatchObject({ - assignee_handle: handle, - assignee_orca_session_id: SESSION_Y - }) - expect(await as(SESSION_Y, 'orchestration.check', { peek: true })).toMatchObject({ - dispatchId: idOf(dispatch) - }) - } - ) - - it('dispatch: a chat named by its session address is the assignee, by its Orca session ID', async () => { - const runId = await chatRun() - const task = h.db.createTask({ runId, spec: 'work' }) - - const { dispatch } = await as(SESSION_X, 'orchestration.dispatch', { - task: task.id, - to: ADDRESS_Z - }) - - expect(dispatch).toMatchObject({ - assignee_handle: ADDRESS_Z, - assignee_orca_session_id: SESSION_Z, - assignee_pane_key: null, - process_incarnation: null - }) - expect(await as(SESSION_Z, 'orchestration.check', { peek: true })).toMatchObject({ - dispatchId: idOf(dispatch) - }) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-party-agreement.test.ts b/src/main/runtime/rpc/orchestration-party-agreement.test.ts deleted file mode 100644 index 260ff6600ab..00000000000 --- a/src/main/runtime/rpc/orchestration-party-agreement.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { formatOrcaSessionAddress } from '../../../shared/orca-session-address' -import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' - -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - ADDRESS_X, - createSessionCallerHarness, - idOf, - orchestrationRequest, - resultOf, - SESSION_X, - SESSION_Y, - sessionRecord, - WORKER_HANDLE, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -// A `/clear`ed member of X's lineage and of worker Y's, as a later lineage walk will map them. -const ALIAS_X = testOrcaSessionId('5c7e2a94-1d3b-4f68-b9a0-e4c2d6f81b37') -const ALIAS_Y = testOrcaSessionId('8a4d6f20-3e1c-4b79-a5d2-c0f7e9b3a164') - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) -vi.mock('../orchestration/addressing/session-lineage/canonical-orca-session-id', () => ({ - canonicalOrcaSessionId: (id: string) => - id === '5c7e2a94-1d3b-4f68-b9a0-e4c2d6f81b37' - ? '4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37' - : id === '8a4d6f20-3e1c-4b79-a5d2-c0f7e9b3a164' - ? '7e3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64' - : id -})) - -type Row = Record - -const handle = mintStructuredWorkerHandle() -const paneKey = mintStructuredWorkerPaneKey(SESSION_Y) -let h: SessionCallerHarness - -beforeEach(() => { - h = createSessionCallerHarness(hostRef) - h.records.set(ALIAS_X, sessionRecord(ALIAS_X)) - h.records.set(ALIAS_Y, sessionRecord(ALIAS_Y)) -}) - -afterEach(() => { - h.close() - vi.restoreAllMocks() -}) - -function call(sessionId: string | undefined, method: string, params: Row) { - return h.dispatch(orchestrationRequest(method, params, { sessionId })) -} - -async function as(sessionId: string | undefined, method: string, params: Row): Promise { - return resultOf(await call(sessionId, method, params)) -} - -function registerWorker(): void { - structuredWorkerIdentities.register({ - handle, - sessionId: SESSION_Y, - agent: 'claude', - paneKey, - processIncarnation: structuredWorkerProcessIncarnation(SESSION_Y), - worktreeId: 'wt_1', - hostScope: { kind: 'local', hostId: 'local' } - }) -} - -/** A Dispatch naming Y as a structured worker, in a Run a terminal coordinates. */ - -describe('every session-to-party step goes through the canonical session id', () => { - it('binds a claimed alias as its canonical session', async () => { - const { run } = await as(ALIAS_X, 'orchestration.runCreate', { objective: 'o' }) - expect(h.db.getRunRaw(idOf(run))?.coordinator_orca_session_id).toBe(SESSION_X) - expect(await as(SESSION_X, 'orchestration.runCurrent', {})).toMatchObject({ - run: { id: idOf(run) } - }) - }) - - it("delivers mail to an alias's address at the canonical session's mailbox", async () => { - const { message } = await as(undefined, 'orchestration.send', { - from: WORKER_HANDLE, - to: formatOrcaSessionAddress(ALIAS_X), - subject: 's' - }) - expect(message).toMatchObject({ to_handle: ADDRESS_X }) - }) - - it("resolves a worker alias's address to the worker's handle", async () => { - registerWorker() - const { message } = await as(undefined, 'orchestration.send', { - from: formatOrcaSessionAddress(ALIAS_Y), - to: ADDRESS_X, - subject: 's' - }) - expect(message).toMatchObject({ from_handle: handle }) - }) - - it.each([formatOrcaSessionAddress(ALIAS_X), ALIAS_X])( - 'accepts the session declared as its alias %s', - async (declared) => { - const { run } = await as(SESSION_X, 'orchestration.runCreate', { - objective: 'o', - from: declared - }) - expect(run).toMatchObject({ coordinator_handle: null }) - } - ) -}) diff --git a/src/main/runtime/rpc/orchestration-run-use-invalid-takeover.test.ts b/src/main/runtime/rpc/orchestration-run-use-invalid-takeover.test.ts deleted file mode 100644 index cdfeb43ac32..00000000000 --- a/src/main/runtime/rpc/orchestration-run-use-invalid-takeover.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { - cleanupLegacyCompatibilityDispatcherHarnesses, - createHarness, - currentEvidence, - CURRENT_COORDINATOR_HANDLE, - CURRENT_COORDINATOR_PANE, - request, - type LegacyCompatibilityDispatcherHarness -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' - -function snapshot(harness: LegacyCompatibilityDispatcherHarness) { - return Object.fromEntries( - [ - 'runs', - 'run_coordinator_handles', - 'messages', - 'deliveries', - 'dispatch_contexts', - 'legacy_adoptions', - 'legacy_compatibility_principals', - 'legacy_operation_receipts', - 'legacy_mail_receipts', - 'mutation_receipts' - ].map((table) => [table, harness.db.db.prepare(`SELECT * FROM ${table}`).all()]) - ) -} - -// The coordinator's current binding makes any unbinding visible in the snapshot. -function createOrdinaryTarget(harness: LegacyCompatibilityDispatcherHarness) { - harness.db.createRun({ - objective: 'current binding', - coordinatorHandle: CURRENT_COORDINATOR_HANDLE, - coordinatorPaneKey: CURRENT_COORDINATOR_PANE - }) - return harness.db.createRun({ - objective: 'ordinary target', - coordinatorHandle: null, - coordinatorPaneKey: null - }) -} - -afterEach(() => { - cleanupLegacyCompatibilityDispatcherHarnesses() -}) - -describe('run-use rejects legacy takeover of ordinary runs', () => { - it.each(['absent', 'valid'] as const)( - 'returns invalid_argument with %s authority and preserves the database and waiters', - async (authority) => { - const harness = createHarness() - const target = createOrdinaryTarget(harness) - const before = snapshot(harness) - const cancel = vi.spyOn(harness.runtime, 'cancelMessageWaiters') - const rpc = request( - 'orchestration.runUse', - { id: target.id, from: CURRENT_COORDINATOR_HANDLE, takeoverLegacy: true }, - currentEvidence('coordinator'), - `ordinary-takeover-${authority}` - ) - const response = await harness.dispatcher.dispatch({ - ...rpc, - orchestrationCompatibilityEvidence: - authority === 'valid' ? rpc.orchestrationCompatibilityEvidence : undefined - }) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: 'Legacy takeover is only available for the automatically adopted Run.' - } - }) - expect(snapshot(harness)).toEqual(before) - expect(cancel).not.toHaveBeenCalled() - } - ) -}) diff --git a/src/main/runtime/rpc/orchestration-session-caller-test-fixture.ts b/src/main/runtime/rpc/orchestration-session-caller-test-fixture.ts deleted file mode 100644 index 5a902e2a9a1..00000000000 --- a/src/main/runtime/rpc/orchestration-session-caller-test-fixture.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { vi } from 'vitest' -import type { - AgentSessionLease, - AgentSessionRecord -} from '../../../shared/agent-session/lifecycle/agent-session-record' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { formatOrcaSessionAddress } from '../../../shared/orca-session-address' -import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' -import { OrcaRuntimeService } from '../orca-runtime' -import type { TerminalIdentityReadContext } from '../terminal/query/terminal-identity-read-context' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import { structuredWorkerIdentities } from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import type { RpcRequest, RpcResponse } from './core' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -export const SESSION_X = testOrcaSessionId('4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37') -export const SESSION_Y = testOrcaSessionId('7e3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64') -export const ADDRESS_X = formatOrcaSessionAddress(SESSION_X) -export const ADDRESS_Y = formatOrcaSessionAddress(SESSION_Y) -export const PROVIDER_ID_X = 'c0ffee11-2233-4455-8677-8899aabbccdd' -export const WORKSPACE_X = 'repo_1::/work/tree-x' -export const WORKER_HANDLE = 'term_worker' -export const WORKER_PANE = 'tab_worker:77777777-7777-4777-8777-777777777777' - -export type SessionHostRef = { current: unknown } - -/** A live chat session record; the lease and location can be pushed into any state. */ -export function sessionRecord( - sessionId: string, - overrides: { - lease?: Partial - location?: Partial - providerId?: string - } = {} -): AgentSessionRecord { - const base = agentSessionRecordFixture( - agentSessionLeaseFixture({ sessionId, runtimeKind: 'native', ...overrides.lease }) - ) - return { - ...base, - location: { ...base.location, workspaceId: WORKSPACE_X, ...overrides.location }, - providerHandleChain: base.providerHandleChain.map((link) => ({ - ...link, - handle: claudeProviderHandle(overrides.providerId ?? `provider-${sessionId}`, null) - })) - } -} - -class SessionCallerRuntime extends OrcaRuntimeService { - public override getPaneKeyForTerminalHandle( - handle: string, - context?: TerminalIdentityReadContext - ): string | null { - return super.getPaneKeyForTerminalHandle(handle, context) - } -} - -export type SessionCallerHarness = { - runtime: SessionCallerRuntime - db: OrchestrationDb - dispatcher: RpcDispatcher - records: Map - /** Unary socket route: what the local CLI's Unix socket and Electron IPC reach. */ - dispatch: (request: RpcRequest) => Promise - /** Streaming dispatcher, optionally as a paired client on another host. */ - dispatchStreaming: (request: RpcRequest, pairedDeviceId?: string) => Promise - close: () => void -} - -export function createSessionCallerHarness( - hostRef: SessionHostRef, - getVisibleSessionTabIndex: () => { present: boolean; sessionIds: string[] } = () => ({ - present: false, - sessionIds: [] - }) -): SessionCallerHarness { - const db = new OrchestrationDb(':memory:') - const runtime = new SessionCallerRuntime() - runtime.setOrchestrationDb(db) - vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === WORKER_HANDLE ? WORKER_PANE : null - ) - vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => - runtime.getTerminalPaneKey(handle) - ) - const records = new Map([ - [SESSION_X, sessionRecord(SESSION_X, { providerId: PROVIDER_ID_X })], - [SESSION_Y, sessionRecord(SESSION_Y)] - ]) - hostRef.current = { - deps: { - store: { - getRecord: (sessionId: string) => records.get(sessionId) ?? null, - getConversation: (id: string) => { - const record = records.get(id) - return record ? agentSessionConversationView(record) : null - }, - listConversations: () => [...records.values()].map(agentSessionConversationView), - requireWritableRecord: (id: string) => { - const record = records.get(id) - if (!record) { - throw new Error('Missing test record') - } - return record - }, - listRecords: () => [...records.values()], - getVisibleSessionTabIndex - } - } - } - structuredWorkerIdentities.clear() - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - return { - runtime, - db, - dispatcher, - records, - dispatch: (request) => dispatcher.dispatch(request), - dispatchStreaming: async (request, pairedDeviceId) => { - const replies: string[] = [] - await dispatcher.dispatchStreaming( - request, - (reply) => replies.push(reply), - pairedDeviceId ? { pairedDeviceId } : {} - ) - const [reply] = replies - if (replies.length !== 1 || reply === undefined) { - throw new Error(`expected exactly one reply, got ${replies.length}`) - } - const parsed: unknown = JSON.parse(reply) - return parsed - }, - close: () => { - hostRef.current = null - structuredWorkerIdentities.clear() - db.close() - } - } -} - -let requestCounter = 0 - -/** An orchestration request as the CLI sends it, naming its caller by session id when given. */ -export function orchestrationRequest( - method: string, - params: Record, - options: { - sessionId?: string - requestId?: string - evidence?: OrchestrationCompatibilityEvidence - } = {} -): RpcRequest { - requestCounter += 1 - const requestId = options.requestId ?? `req-${requestCounter}` - const evidence = - options.sessionId === undefined - ? options.evidence - : { ...options.evidence, agentSessionId: options.sessionId } - return { - id: `rpc-${requestCounter}`, - authToken: 'test', - method, - params, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, - orchestrationRequestId: requestId, - compatibilityInvocationId: requestId, - ...(evidence ? { orchestrationCompatibilityEvidence: evidence } : {}) - } -} - -export function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -export function resultOf(response: unknown): Record { - if (!isRecord(response) || response.ok !== true || !isRecord(response.result)) { - throw new Error(`expected a successful response, got ${JSON.stringify(response)}`) - } - return response.result -} - -export function idOf(row: unknown): string { - if (!isRecord(row) || typeof row.id !== 'string') { - throw new Error(`expected a row with an id, got ${JSON.stringify(row)}`) - } - return row.id -} diff --git a/src/main/runtime/rpc/orchestration-session-coordinator.test.ts b/src/main/runtime/rpc/orchestration-session-coordinator.test.ts deleted file mode 100644 index 5d2b054b594..00000000000 --- a/src/main/runtime/rpc/orchestration-session-coordinator.test.ts +++ /dev/null @@ -1,375 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - ADDRESS_X, - ADDRESS_Y, - createSessionCallerHarness, - orchestrationRequest, - idOf, - resultOf, - SESSION_X, - SESSION_Y, - WORKER_HANDLE, - WORKER_PANE, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -type Row = Record - -describe('a structured chat coordinates through the same verbs as a terminal', () => { - let h: SessionCallerHarness - - beforeEach(() => { - h = createSessionCallerHarness(hostRef) - }) - - afterEach(() => { - h.close() - vi.restoreAllMocks() - }) - - async function as(sessionId: string | undefined, method: string, params: Row): Promise { - return resultOf(await h.dispatch(orchestrationRequest(method, params, { sessionId }))) - } - - async function runCreate(sessionId: string, objective = 'o'): Promise { - const { run } = await as(sessionId, 'orchestration.runCreate', { objective }) - return idOf(run) - } - - it('runs the supervised loop: run, task, dispatch, worker mail in, check, send, reply, gates', async () => { - const runId = await runCreate(SESSION_X) - expect(h.db.getRunRaw(runId)).toMatchObject({ - coordinator_handle: null, - coordinator_pane_key: null, - coordinator_orca_session_id: SESSION_X - }) - expect(await as(SESSION_X, 'orchestration.runCurrent', {})).toMatchObject({ - run: { id: runId } - }) - - const { task } = await as(SESSION_X, 'orchestration.taskCreate', { spec: 'do it' }) - const taskId = idOf(task) - expect(task).toMatchObject({ run_id: runId, created_by_terminal_handle: null }) - expect(await as(SESSION_X, 'orchestration.taskList', {})).toMatchObject({ runId, count: 1 }) - - const { dispatch } = await as(SESSION_X, 'orchestration.dispatch', { - task: taskId, - to: WORKER_HANDLE - }) - expect(dispatch).toMatchObject({ - assignee_handle: WORKER_HANDLE, - creator_handle: null, - creator_pane_key: null, - creator_orca_session_id: SESSION_X, - depth: 1 - }) - - // The worker writes to its coordinator's public address. - const { message: inbound } = await as(undefined, 'orchestration.send', { - from: WORKER_HANDLE, - to: ADDRESS_X, - subject: 'progress' - }) - expect(inbound).toMatchObject({ to_handle: `run:${runId}`, run_id: runId }) - - const checked = await as(SESSION_X, 'orchestration.check', {}) - expect(checked).toMatchObject({ runId, count: 1, messages: [{ subject: 'progress' }] }) - - const { message: outbound } = await as(SESSION_X, 'orchestration.send', { - to: WORKER_HANDLE, - subject: 'more' - }) - expect(outbound).toMatchObject({ - from_handle: ADDRESS_X, - to_handle: `dispatch:${idOf(dispatch)}`, - run_id: runId - }) - - const replied = await as(SESSION_X, 'orchestration.reply', { - id: idOf(inbound), - body: 'ack' - }) - expect(replied).toMatchObject({ - message: { - from_handle: ADDRESS_X, - to_handle: `dispatch:${idOf(dispatch)}`, - run_id: runId, - thread_id: idOf(inbound) - } - }) - expect(await as(undefined, 'orchestration.check', { terminal: WORKER_HANDLE })).toMatchObject({ - runId, - dispatchId: idOf(dispatch), - count: 2, - messages: [{ id: idOf(outbound) }, { id: idOf(replied.message) }] - }) - - const { gate } = await as(SESSION_X, 'orchestration.gateCreate', { - task: taskId, - question: 'ship?' - }) - expect(await as(SESSION_X, 'orchestration.gateList', {})).toMatchObject({ runId, count: 1 }) - expect( - await as(SESSION_X, 'orchestration.gateResolve', { - id: idOf(gate), - resolution: 'yes' - }) - ).toMatchObject({ gate: { status: 'resolved' } }) - - expect( - await as(SESSION_X, 'orchestration.taskUpdate', { id: taskId, status: 'completed' }) - ).toMatchObject({ task: { status: 'completed' } }) - }) - - it("wakes the previous coordinator's waiting check as fenced when another session takes over", async () => { - const runId = await runCreate(SESSION_X) - const waiter = vi.spyOn(h.runtime, 'waitForMessage') - const waiting = h.dispatch( - orchestrationRequest( - 'orchestration.check', - { run: runId, wait: true, timeoutMs: 5_000 }, - { - sessionId: SESSION_X - } - ) - ) - await vi.waitFor(() => expect(waiter).toHaveBeenCalledWith(`run:${runId}`, expect.anything())) - const deliver = vi.spyOn(h.db, 'getOrCreateRunDelivery') - const acknowledge = vi.spyOn(h.db, 'acknowledgeRunDelivery') - - await as(SESSION_Y, 'orchestration.runUse', { id: runId }) - - const fenced = await waiting - expect(fenced).toMatchObject({ ok: false, error: { code: 'consumer_fenced' } }) - expect(fenced).not.toHaveProperty('result') - - const { message } = await as(undefined, 'orchestration.send', { - from: WORKER_HANDLE, - to: ADDRESS_Y, - subject: 'after takeover', - run: runId - }) - expect( - await h.dispatch( - orchestrationRequest('orchestration.check', { run: runId }, { sessionId: SESSION_X }) - ) - ).toMatchObject({ ok: false, error: { code: 'consumer_fenced' } }) - expect(deliver).not.toHaveBeenCalled() - - const replacement = await as(SESSION_Y, 'orchestration.check', {}) - expect(replacement).toMatchObject({ - runId, - count: 1, - messages: [{ id: idOf(message), to_handle: `run:${runId}`, run_id: runId }] - }) - const ack = replacement.deliveryId - if (typeof ack !== 'string') { - throw new Error('Expected a Run Delivery') - } - expect( - await h.dispatch( - orchestrationRequest('orchestration.check', { run: runId, ack }, { sessionId: SESSION_X }) - ) - ).toMatchObject({ ok: false, error: { code: 'consumer_fenced' } }) - expect(acknowledge).not.toHaveBeenCalled() - expect(await as(SESSION_Y, 'orchestration.check', {})).toMatchObject({ - deliveryId: null, - count: 0 - }) - expect(await as(SESSION_Y, 'orchestration.check', { ack })).toMatchObject({ - acknowledged: ack, - count: 0 - }) - expect(h.db.getDeliveryRaw(ack)?.status).toBe('acknowledged') - }) - - it('stops counting a coordinator Orca session id once an older binary rebinds the Run to a terminal', async () => { - const runId = await runCreate(SESSION_X) - // An older binary's bindRun rewrites handle and pane and bumps the generation, never the Orca session id. - h.db.db - .prepare( - `UPDATE runs SET coordinator_handle = ?, coordinator_pane_key = ?, - consumer_generation = consumer_generation + 1 - WHERE id = ?` - ) - .run(WORKER_HANDLE, WORKER_PANE, runId) - - expect(await as(SESSION_X, 'orchestration.runCurrent', {})).toMatchObject({ run: null }) - expect(await as(undefined, 'orchestration.runCurrent', { from: WORKER_HANDLE })).toMatchObject({ - run: { id: runId } - }) - }) - - it('replays an idempotent retry from the same session and refuses it from another', async () => { - const first = await h.dispatch( - orchestrationRequest( - 'orchestration.runCreate', - { objective: 'o' }, - { - sessionId: SESSION_X, - requestId: 'retry-1' - } - ) - ) - const retry = await h.dispatch( - orchestrationRequest( - 'orchestration.runCreate', - { objective: 'o' }, - { - sessionId: SESSION_X, - requestId: 'retry-1' - } - ) - ) - const other = await h.dispatch( - orchestrationRequest( - 'orchestration.runCreate', - { objective: 'o' }, - { - sessionId: SESSION_Y, - requestId: 'retry-1' - } - ) - ) - - const firstRun = idOf(resultOf(first).run) - expect(resultOf(retry)).toMatchObject({ run: { id: firstRun }, mutation: { replayed: true } }) - expect(other).toMatchObject({ ok: false, error: { code: 'request_mismatch' } }) - expect(h.db.listRuns().runs.filter((run) => run.legacy === 0)).toHaveLength(1) - }) -}) - -describe('a structured worker that names itself by session id', () => { - let h: SessionCallerHarness - const workerSession = SESSION_Y - const handle = mintStructuredWorkerHandle() - const paneKey = mintStructuredWorkerPaneKey(workerSession) - - beforeEach(() => { - h = createSessionCallerHarness(hostRef) - structuredWorkerIdentities.register({ - handle, - sessionId: workerSession, - agent: 'claude', - paneKey, - processIncarnation: structuredWorkerProcessIncarnation(workerSession), - worktreeId: 'wt_1', - hostScope: { kind: 'local', hostId: 'local' } - }) - }) - - afterEach(() => { - h.close() - vi.restoreAllMocks() - }) - - function dispatchToWorker(): { runId: string; dispatchId: string } { - const run = h.db.createRun({ - objective: 'pty coordinator', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_coord:12121212-1212-4212-8212-121212121212' - }) - const dispatch = h.db.createDispatchContext({ - taskId: h.db.createTask({ runId: run.id, spec: 'work' }).id, - assigneeHandle: handle, - assigneePaneKey: paneKey, - processIncarnation: structuredWorkerProcessIncarnation(workerSession), - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER - }) - h.db.insertMessage({ - from: 'term_coord', - to: `dispatch:${dispatch.id}`, - subject: 'instructions', - body: '', - runId: run.id - }) - return { runId: run.id, dispatchId: dispatch.id } - } - - it('sends mail at either of its spellings to its Dispatch once assigned in a Run it coordinated before', async () => { - const { run } = resultOf( - await h.dispatch( - orchestrationRequest( - 'orchestration.runCreate', - { objective: 'o' }, - { sessionId: workerSession } - ) - ) - ) - const runId = idOf(run) - // A chat takes the Run over; the worker's addresses stay remembered as a former coordinator's. - resultOf( - await h.dispatch( - orchestrationRequest('orchestration.runUse', { id: runId }, { sessionId: SESSION_X }) - ) - ) - expect(h.db.getRunMailboxOwnerIdsForHandle(ADDRESS_Y)).toEqual([runId]) - const dispatch = h.db.createDispatchContext({ - taskId: h.db.createTask({ runId, spec: 'work' }).id, - assigneeHandle: handle, - assigneePaneKey: paneKey, - processIncarnation: structuredWorkerProcessIncarnation(workerSession), - creator: { kind: 'session', orcaSessionId: SESSION_X }, - maxDepth: Number.MAX_SAFE_INTEGER - }) - - // Both spellings name one party, so both land in the one mailbox it reads, not the Run's. - for (const to of [ADDRESS_Y, handle]) { - const { message } = resultOf( - await h.dispatch( - orchestrationRequest('orchestration.send', { to, subject: to }, { sessionId: SESSION_X }) - ) - ) - expect(message).toMatchObject({ to_handle: `dispatch:${dispatch.id}` }) - } - const read = resultOf( - await h.dispatch( - orchestrationRequest('orchestration.check', { peek: true }, { sessionId: workerSession }) - ) - ) - expect(read).toMatchObject({ - count: 2, - messages: expect.arrayContaining([ - expect.objectContaining({ subject: handle }), - expect.objectContaining({ subject: ADDRESS_Y }) - ]) - }) - }) - - it('cannot take or read the Run it works for after making a sub-Run, and keeps its mail', async () => { - // The 10-14 incident: a worker made a sub-Run, `check --run ` said "bound to X, not Y", - // and it ran run-use on the parent, unbinding its coordinator. - const { runId } = dispatchToWorker() - const as = (method: string, params: Row) => - h.dispatch(orchestrationRequest(method, params, { sessionId: workerSession })) - resultOf(await as('orchestration.runCreate', { objective: 'sub' })) - - const read = await as('orchestration.check', { run: runId, peek: true }) - expect(read).toMatchObject({ ok: false, error: { code: 'worker_cannot_coordinate_own_run' } }) - expect(JSON.stringify(read)).not.toContain('run-use') - expect(resultOf(await as('orchestration.check', { peek: true }))).toMatchObject({ - messages: [{ subject: 'instructions' }] - }) - - expect(await as('orchestration.runUse', { id: runId })).toMatchObject({ - ok: false, - error: { code: 'worker_cannot_coordinate_own_run', data: { effectsApplied: false } } - }) - expect(h.db.getRunRaw(runId)).toMatchObject({ - coordinator_handle: 'term_coord', - consumer_generation: 1 - }) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-session-recipient.test.ts b/src/main/runtime/rpc/orchestration-session-recipient.test.ts deleted file mode 100644 index 8519ab6ff7c..00000000000 --- a/src/main/runtime/rpc/orchestration-session-recipient.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - ADDRESS_X, - createSessionCallerHarness, - idOf, - orchestrationRequest, - resultOf, - SESSION_X, - SESSION_Y, - WORKER_HANDLE, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -type Row = Record - -describe('a live structured worker addressed by its session id', () => { - let h: SessionCallerHarness - const handle = mintStructuredWorkerHandle() - const paneKey = mintStructuredWorkerPaneKey(SESSION_Y) - - beforeEach(() => { - h = createSessionCallerHarness(hostRef) - structuredWorkerIdentities.register({ - handle, - sessionId: SESSION_Y, - agent: 'claude', - paneKey, - processIncarnation: structuredWorkerProcessIncarnation(SESSION_Y), - worktreeId: 'wt_1', - hostScope: { kind: 'local', hostId: 'local' } - }) - }) - - afterEach(() => { - h.close() - vi.restoreAllMocks() - }) - - async function sendTo(to: string): Promise { - return resultOf( - await h.dispatch( - orchestrationRequest('orchestration.send', { from: 'term_worker', to, subject: 'hello' }) - ) - ) - } - - async function flaglessCheck(): Promise { - return resultOf( - await h.dispatch( - orchestrationRequest('orchestration.check', { peek: true }, { sessionId: SESSION_Y }) - ) - ) - } - - it('lands in its own handle mailbox between Dispatches, which its flagless check reads', async () => { - expect(await sendTo(SESSION_Y)).toMatchObject({ message: { to_handle: handle } }) - expect(await flaglessCheck()).toMatchObject({ messages: [{ subject: 'hello' }] }) - }) -}) - -describe('mail sent to a session address reaches the mailbox that session reads', () => { - let h: SessionCallerHarness - - beforeEach(() => { - h = createSessionCallerHarness(hostRef) - }) - - afterEach(() => { - h.close() - vi.restoreAllMocks() - }) - - async function as(sessionId: string | undefined, method: string, params: Row): Promise { - return resultOf(await h.dispatch(orchestrationRequest(method, params, { sessionId }))) - } - - function sendFromTerminal(to: string): Promise { - return as(undefined, 'orchestration.send', { from: WORKER_HANDLE, to, subject: 'hello' }) - } - - it("files it under the chat's current Run, as a terminal coordinator's pane does", async () => { - await as(SESSION_X, 'orchestration.runCreate', { objective: 'first' }) - const current = idOf( - (await as(SESSION_X, 'orchestration.runCreate', { objective: 'next' })).run - ) - - const { message } = await sendFromTerminal(ADDRESS_X) - - expect(message).toMatchObject({ to_handle: `run:${current}`, run_id: current }) - expect(await as(SESSION_X, 'orchestration.check', {})).toMatchObject({ - runId: current, - messages: [{ subject: 'hello' }] - }) - }) - - it('delivers it to a chat with no Run, which reads its direct mailbox', async () => { - const { message } = await sendFromTerminal(ADDRESS_X) - - expect(message).toMatchObject({ to_handle: ADDRESS_X }) - expect(await as(SESSION_X, 'orchestration.check', {})).toMatchObject({ - messages: [{ subject: 'hello' }] - }) - }) - - it('reaches a chat with no Run after a restart, once the send has started the session host', async () => { - // After restart, start the lazy session host before synchronous recipient-record lookup. - const store = hostRef.current - hostRef.current = null - vi.mocked(h.runtime.ensureStructuredAgentSessionHost).mockImplementation(async () => { - hostRef.current = store - }) - - const { message } = await sendFromTerminal(ADDRESS_X) - - expect(message).toMatchObject({ to_handle: ADDRESS_X }) - }) -}) diff --git a/src/main/runtime/rpc/orchestration-session-run-binding.test.ts b/src/main/runtime/rpc/orchestration-session-run-binding.test.ts deleted file mode 100644 index c4392c25c89..00000000000 --- a/src/main/runtime/rpc/orchestration-session-run-binding.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - createSessionCallerHarness, - orchestrationRequest, - resultOf, - idOf, - SESSION_X, - SESSION_Y, - type SessionCallerHarness -} from './orchestration-session-caller-test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -function deliveryId(result: Record): string { - if (typeof result.deliveryId === 'string') { - return result.deliveryId - } - throw new Error('Expected a Delivery') -} - -describe('structured lead Run binding through the RPC dispatcher', () => { - let h: SessionCallerHarness - let dispatchId: string - let leadHandle: string - - function call(sessionId: string, method: string, params: Record = {}) { - return h - .dispatch(orchestrationRequest(`orchestration.${method}`, params, { sessionId })) - .then(resultOf) - } - - beforeEach(async () => { - h = createSessionCallerHarness(hostRef) - const handle = mintStructuredWorkerHandle() - leadHandle = handle - const paneKey = mintStructuredWorkerPaneKey(SESSION_Y) - structuredWorkerIdentities.register({ - handle, - sessionId: SESSION_Y, - agent: 'claude', - paneKey, - processIncarnation: structuredWorkerProcessIncarnation(SESSION_Y), - worktreeId: 'folder-workspace', - hostScope: { kind: 'local', hostId: 'local' } - }) - const runId = idOf((await call(SESSION_X, 'runCreate', { objective: 'parent' })).run) - dispatchId = h.db.createDispatchContext({ - taskId: h.db.createTask({ runId, spec: 'structured lead' }).id, - assigneeHandle: handle, - assigneePaneKey: paneKey, - processIncarnation: structuredWorkerProcessIncarnation(SESSION_Y), - creator: { kind: 'session', orcaSessionId: SESSION_X }, - maxDepth: Number.MAX_SAFE_INTEGER - }).id - }) - // A Run this lead created earlier and that lost its binding: the one kind a worker may resume. - function orphanedOwnRun(): string { - const id = h.db.createRun({ - objective: 'resume', - coordinatorHandle: leadHandle, - coordinatorPaneKey: null - }).id - h.db.db.prepare('UPDATE runs SET coordinator_handle = NULL WHERE id = ?').run(id) - return id - } - afterEach(() => { - h.runtime.cancelMessageWaiters(`dispatch:${dispatchId}`) - h.close() - vi.restoreAllMocks() - }) - - it.each(['runCreate', 'runUse'] as const)( - 'cancels a parked session Dispatch check on %s', - async (method) => { - const params = method === 'runCreate' ? { objective: 'child' } : { id: orphanedOwnRun() } - const wait = vi.spyOn(h.runtime, 'waitForMessage') - const waiting = call(SESSION_Y, 'check', { wait: true, timeoutMs: 500 }) - await vi.waitFor(() => - expect(wait).toHaveBeenCalledWith(`dispatch:${dispatchId}`, expect.anything()) - ) - const child = idOf((await call(SESSION_Y, method, params)).run) - expect(await waiting).toMatchObject({ cancelled: true, timedOut: false }) - const sent = await call(SESSION_X, 'send', { - to: `dispatch:${dispatchId}`, - subject: 'after bind' - }) - expect(sent.message).toMatchObject({ to_handle: `run:${child}`, run_id: child }) - expect(await call(SESSION_Y, 'check')).toMatchObject({ - messages: [{ subject: 'after bind' }] - }) - expect(h.db.getInbox()).toHaveLength(1) - } - ) - - it.each(['cancel', 'throw'] as const)( - 'replays a pre-bind ack receipt after the following wait ends by %s', - async (ending) => { - await call(SESSION_X, 'send', { to: `dispatch:${dispatchId}`, subject: 'ack me' }) - const ack = deliveryId(await call(SESSION_Y, 'check')) - const acknowledge = vi.spyOn(h.db, 'acknowledgeMailboxDelivery') - const wait = vi.spyOn(h.runtime, 'waitForMessage').mockImplementationOnce(async () => { - await call(SESSION_Y, 'runCreate', { objective: 'child' }) - if (ending === 'throw') { - throw new Error('wait transport interrupted') - } - return 'cancelled' - }) - const request = orchestrationRequest( - 'orchestration.check', - { ack, wait: true, timeoutMs: 500 }, - { - sessionId: SESSION_Y, - requestId: `bind-during-ack-${ending}` - } - ) - const first = await h.dispatch(request) - if (ending === 'throw') { - expect(first).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) - } else { - expect(resultOf(first)).toMatchObject({ acknowledged: ack, count: 0, cancelled: true }) - } - const replay = resultOf(await h.dispatch(request)) - expect(replay).toMatchObject({ acknowledged: ack, count: 0, mutation: { replayed: true } }) - if (ending === 'throw') { - expect(replay.waitInterrupted).toBe('outcome_unknown') - } - expect(acknowledge).toHaveBeenCalledTimes(1) - expect(wait).toHaveBeenCalledTimes(1) - expect(h.db.getDeliveryRaw(ack)?.status).toBe('acknowledged') - } - ) -}) diff --git a/src/main/runtime/rpc/orchestration/callers/orchestration-legacy-session-address-migration.test.ts b/src/main/runtime/rpc/orchestration/callers/orchestration-legacy-session-address-migration.test.ts new file mode 100644 index 00000000000..b0fa20878c0 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/callers/orchestration-legacy-session-address-migration.test.ts @@ -0,0 +1,104 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import { + ADDRESS_X, + ADDRESS_Y, + createSessionCallerHarness, + SESSION_X, + SESSION_Y, + WORKER_HANDLE, + type SessionCallerHarness +} from './session.test-fixture' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock( + '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', + () => ({ + getStructuredAgentSessionHost: () => hostRef.current + }) +) + +const LEGACY_X = `session:${SESSION_X}` +const LEGACY_Y = `session:${SESSION_Y}` +// Remembered under both spellings; a session of its own, so routing to Y stays unambiguous. +const BOTH_SESSION = '5c5c5c5c-6d6d-4e7e-8f8f-909090909090' + +/** What an earlier build, which spelled a session's address `session:`, left in a v42 database. */ +function seedEarlierBuildRows(db: OrchestrationDb): { toX: string; fromX: string } { + // Subject and body spell the old address too: text, not an address, so it must survive as written. + const toX = db.insertMessage({ + from: WORKER_HANDLE, + to: ADDRESS_X, + subject: LEGACY_X, + body: LEGACY_X + }) + const fromX = db.insertMessage({ from: ADDRESS_X, to: WORKER_HANDLE, subject: 'q', body: 'b' }) + db.db.prepare('UPDATE messages SET to_handle = ? WHERE id = ?').run(LEGACY_X, toX.id) + db.db.prepare('UPDATE messages SET from_handle = ? WHERE id = ?').run(LEGACY_X, fromX.id) + db.db + .prepare( + `INSERT INTO runs (id, objective, consumer_generation, legacy) VALUES + ('run_earlier', 'coordinated by Y', 1, 0), ('run_both', 'remembered twice', 1, 0)` + ) + .run() + const remember = db.db.prepare( + 'INSERT INTO run_coordinator_handles (run_id, terminal_handle) VALUES (?, ?)' + ) + remember.run('run_earlier', LEGACY_Y) + remember.run('run_both', `session:${BOTH_SESSION}`) + remember.run('run_both', `orca_session_id:${BOTH_SESSION}`) + const pointer = db.db.prepare( + `INSERT INTO structured_pointer_operations + (mailbox_handle, session_id, operation_id, batch_fingerprint, minted_at_ms) + VALUES (?, ?, ?, 'batch', 1)` + ) + pointer.run(LEGACY_X, SESSION_X, 'op_legacy_x') + pointer.run(LEGACY_Y, SESSION_Y, 'op_legacy_y') + pointer.run(ADDRESS_Y, SESSION_Y, 'op_current_y') + db.createCoordinatorRun({ spec: 'spec', coordinatorHandle: LEGACY_X }) + db.db.pragma('user_version = 42') + return { toX: toX.id, fromX: fromX.id } +} + +function snapshot(db: OrchestrationDb): unknown[] { + return [ + 'SELECT id, from_handle, to_handle, subject, body FROM messages ORDER BY id', + 'SELECT run_id, terminal_handle FROM run_coordinator_handles ORDER BY run_id, terminal_handle', + 'SELECT mailbox_handle, operation_id FROM structured_pointer_operations ORDER BY mailbox_handle', + 'SELECT coordinator_handle FROM coordinator_runs' + ].map((sql) => db.db.prepare(sql).all()) +} + +describe('a database an earlier build wrote session: addresses into', () => { + let h: SessionCallerHarness + + beforeEach(() => { + h = createSessionCallerHarness(hostRef, () => ({ + present: true, + sessionIds: [SESSION_X, SESSION_Y] + })) + seedEarlierBuildRows(h.db) + h.db.migrate() + }) + + afterEach(() => { + h.close() + vi.restoreAllMocks() + }) + + it('leaves no address in the old spelling, keeping the current row where both were keyed', () => { + const [messages, remembered, pointers, coordinatorRuns] = snapshot(h.db) + expect(JSON.stringify([messages, remembered, pointers, coordinatorRuns])).not.toMatch( + /"(from_handle|to_handle|terminal_handle|mailbox_handle|coordinator_handle)":"session:/ + ) + expect(remembered).toEqual([ + { run_id: 'run_both', terminal_handle: `orca_session_id:${BOTH_SESSION}` }, + { run_id: 'run_earlier', terminal_handle: ADDRESS_Y } + ]) + expect(pointers).toEqual([ + { mailbox_handle: ADDRESS_X, operation_id: 'op_legacy_x' }, + { mailbox_handle: ADDRESS_Y, operation_id: 'op_current_y' } + ]) + expect(coordinatorRuns).toEqual([{ coordinator_handle: ADDRESS_X }]) + }) +}) diff --git a/src/main/runtime/rpc/orchestration-peer-caller.ts b/src/main/runtime/rpc/orchestration/callers/orchestration-peer-caller.ts similarity index 84% rename from src/main/runtime/rpc/orchestration-peer-caller.ts rename to src/main/runtime/rpc/orchestration/callers/orchestration-peer-caller.ts index f57053b9d88..82a06b05dfd 100644 --- a/src/main/runtime/rpc/orchestration-peer-caller.ts +++ b/src/main/runtime/rpc/orchestration/callers/orchestration-peer-caller.ts @@ -1,13 +1,13 @@ -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcMethod, RpcRequest, RpcStreamingMethod } from './core' -import type { RpcDispatchStreamingOptions } from './dispatcher-stream-options' -import { OrchestrationError } from '../orchestration/orchestration-error' -import { isGeneratedId } from '../orchestration/db/generated-id' -import { RemoteOwnedPeerRun } from '../../../shared/orchestration/remote-owned-wire' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { RpcMethod, RpcRequest, RpcStreamingMethod } from '../../core' +import type { RpcDispatchStreamingOptions } from '../../dispatch/dispatcher-stream-options' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import { isGeneratedId } from '../../../orchestration/db/generated-id' +import { RemoteOwnedPeerRun } from '../../../../../shared/orchestration/remote-owned-wire' import { peerCoordinatorCaller, type OrchestrationPeerCaller -} from '../orchestration/addressing/orchestration-caller-identity' +} from '../../../orchestration/addressing/orchestration-caller-identity' const NO_EFFECTS = { effectsApplied: false } as const diff --git a/src/main/runtime/rpc/orchestration-session-caller.ts b/src/main/runtime/rpc/orchestration/callers/orchestration-session-caller.ts similarity index 83% rename from src/main/runtime/rpc/orchestration-session-caller.ts rename to src/main/runtime/rpc/orchestration/callers/orchestration-session-caller.ts index 160cf758f1e..c0ac75af5bc 100644 --- a/src/main/runtime/rpc/orchestration-session-caller.ts +++ b/src/main/runtime/rpc/orchestration/callers/orchestration-session-caller.ts @@ -4,32 +4,35 @@ import { agentSessionLeaseAdmitsWriter, agentSessionLeaseIsReleased -} from '../../../shared/agent-session/lifecycle/agent-session-lease-adjudication' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { ORCA_AGENT_SESSION_ID_ENV } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' -import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../shared/orca-session-address-prefix' -import { isOrcaSessionId, parseOrcaSessionAddress } from '../../../shared/orca-session-address' -import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../shared/orchestration/orchestration-session-caller-codes' -import type { OrcaRuntimeService } from '../orca-runtime' +} from '../../../../../shared/agent-session/lifecycle/agent-session-lease-adjudication' +import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record' +import { ORCA_AGENT_SESSION_ID_ENV } from '../../../../../shared/agent-session/lifecycle/agent-session-caller-env' +import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' +import { + isOrcaSessionId, + parseOrcaSessionAddress +} from '../../../../../shared/orca-session-address' +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../../../shared/orchestration/orchestration-session-caller-codes' +import type { OrcaRuntimeService } from '../../../orca-runtime' import type { OrchestrationEntryCaller, OrchestrationSessionCaller -} from '../orchestration/addressing/orchestration-caller-identity' -import { OrchestrationError } from '../orchestration/orchestration-error' -import { canonicalOrcaSessionId } from '../orchestration/addressing/session-lineage/canonical-orca-session-id' -import type { OrchestrationDb } from '../orchestration/db/orchestration-db' +} from '../../../orchestration/addressing/orchestration-caller-identity' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import { canonicalOrcaSessionId } from '../../../orchestration/addressing/session-lineage/canonical-orca-session-id' +import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db' import { resolveDeclaredCallerParty, resolveOrcaSessionParty, resolveOrchestrationParty -} from '../orchestration/addressing/orchestration-party' -import { lookupOrcaAgentSession } from '../orchestration/mailbox/routing/structured-session-mail-address' -import { conversationRecordReader } from '../orchestration/addressing/session-lineage/structured-session-lineage' -import type { AgentSessionRecordStore } from '../agent-session/records/agent-session-record-store' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { structuredWorkerHostScope } from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import type { RpcRequest } from './core' -import type { OrchestrationCallerField } from './methods/orchestration/access/orchestration-method-access' +} from '../../../orchestration/addressing/orchestration-party' +import { lookupOrcaAgentSession } from '../../../orchestration/mailbox/routing/structured-session-mail-address' +import { conversationRecordReader } from '../../../orchestration/addressing/session-lineage/structured-session-lineage' +import type { AgentSessionRecordStore } from '../../../agent-session/records/agent-session-record-store' +import { getStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { structuredWorkerHostScope } from '../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' +import type { RpcRequest } from '../../core' +import type { OrchestrationCallerField } from '../../methods/orchestration/access/orchestration-method-access' export type OrchestrationRequestRoute = { /** Set only by the paired WebSocket route: the request came from another host's client. */ diff --git a/src/main/runtime/rpc/orchestration/callers/orchestration-session-coordinator.test.ts b/src/main/runtime/rpc/orchestration/callers/orchestration-session-coordinator.test.ts new file mode 100644 index 00000000000..ef5a380bb86 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/callers/orchestration-session-coordinator.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerIdentities, + structuredWorkerProcessIncarnation +} from '../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' +import { + ADDRESS_Y, + createSessionCallerHarness, + orchestrationRequest, + idOf, + resultOf, + SESSION_X, + SESSION_Y, + type SessionCallerHarness +} from './session.test-fixture' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock( + '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', + () => ({ + getStructuredAgentSessionHost: () => hostRef.current + }) +) + +describe('a structured worker that names itself by session id', () => { + let h: SessionCallerHarness + const workerSession = SESSION_Y + const handle = mintStructuredWorkerHandle() + const paneKey = mintStructuredWorkerPaneKey(workerSession) + + beforeEach(() => { + h = createSessionCallerHarness(hostRef) + structuredWorkerIdentities.register({ + handle, + sessionId: workerSession, + agent: 'claude', + paneKey, + processIncarnation: structuredWorkerProcessIncarnation(workerSession), + worktreeId: 'wt_1', + hostScope: { kind: 'local', hostId: 'local' } + }) + }) + + afterEach(() => { + h.close() + vi.restoreAllMocks() + }) + + it('sends mail at either of its spellings to its Dispatch once assigned in a Run it coordinated before', async () => { + const { run } = resultOf( + await h.dispatch( + orchestrationRequest( + 'orchestration.runCreate', + { objective: 'o' }, + { sessionId: workerSession } + ) + ) + ) + const runId = idOf(run) + // A chat takes the Run over; the worker's addresses stay remembered as a former coordinator's. + resultOf( + await h.dispatch( + orchestrationRequest('orchestration.runUse', { id: runId }, { sessionId: SESSION_X }) + ) + ) + expect(h.db.getRunMailboxOwnerIdsForHandle(ADDRESS_Y)).toEqual([runId]) + const dispatch = h.db.createDispatchContext({ + taskId: h.db.createTask({ runId, spec: 'work' }).id, + assigneeHandle: handle, + assigneePaneKey: paneKey, + processIncarnation: structuredWorkerProcessIncarnation(workerSession), + creator: { kind: 'session', orcaSessionId: SESSION_X }, + maxDepth: Number.MAX_SAFE_INTEGER + }) + + // Both spellings name one party, so both land in the one mailbox it reads, not the Run's. + for (const to of [ADDRESS_Y, handle]) { + const { message } = resultOf( + await h.dispatch( + orchestrationRequest('orchestration.send', { to, subject: to }, { sessionId: SESSION_X }) + ) + ) + expect(message).toMatchObject({ to_handle: `dispatch:${dispatch.id}` }) + } + const read = resultOf( + await h.dispatch( + orchestrationRequest('orchestration.check', { peek: true }, { sessionId: workerSession }) + ) + ) + expect(read).toMatchObject({ + count: 2, + messages: expect.arrayContaining([ + expect.objectContaining({ subject: handle }), + expect.objectContaining({ subject: ADDRESS_Y }) + ]) + }) + }) +}) diff --git a/src/main/runtime/rpc/orchestration/callers/session.test-fixture.ts b/src/main/runtime/rpc/orchestration/callers/session.test-fixture.ts new file mode 100644 index 00000000000..944f783d970 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/callers/session.test-fixture.ts @@ -0,0 +1,191 @@ +import { agentSessionConversationView } from '../../../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { vi } from 'vitest' +import type { + AgentSessionLease, + AgentSessionRecord +} from '../../../../../shared/agent-session/lifecycle/agent-session-record' +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' +import type { OrchestrationCompatibilityEvidence } from '../../../../../shared/orchestration/orchestration-compatibility-evidence' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' +import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' +import { OrcaRuntimeService } from '../../../orca-runtime' + +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import { structuredWorkerIdentities } from '../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' +import type { RpcRequest, RpcResponse } from '../../core' +import { RpcDispatcher } from '../../dispatcher' +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' +import { claudeProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' + +export const SESSION_X = testOrcaSessionId('4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37') +export const SESSION_Y = testOrcaSessionId('7e3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64') +export const ADDRESS_X = formatOrcaSessionAddress(SESSION_X) +export const ADDRESS_Y = formatOrcaSessionAddress(SESSION_Y) +export const PROVIDER_ID_X = 'c0ffee11-2233-4455-8677-8899aabbccdd' +export const WORKSPACE_X = 'repo_1::/work/tree-x' +export const WORKER_HANDLE = 'term_worker' +export const WORKER_PANE = 'tab_worker:77777777-7777-4777-8777-777777777777' + +export type SessionHostRef = { current: unknown } + +/** A live chat session record; the lease and location can be pushed into any state. */ +export function sessionRecord( + sessionId: string, + overrides: { + lease?: Partial + location?: Partial + providerId?: string + } = {} +): AgentSessionRecord { + const base = agentSessionRecordFixture( + agentSessionLeaseFixture({ sessionId, runtimeKind: 'native', ...overrides.lease }) + ) + return { + ...base, + location: { ...base.location, workspaceId: WORKSPACE_X, ...overrides.location }, + providerHandleChain: base.providerHandleChain.map((link) => ({ + ...link, + handle: claudeProviderHandle(overrides.providerId ?? `provider-${sessionId}`, null) + })) + } +} + +export type SessionCallerHarness = { + runtime: OrcaRuntimeService + db: OrchestrationDb + dispatcher: RpcDispatcher + records: Map + /** Unary socket route: what the local CLI's Unix socket and Electron IPC reach. */ + dispatch: (request: RpcRequest) => Promise + /** Streaming dispatcher, optionally as a paired client on another host. */ + dispatchStreaming: (request: RpcRequest, pairedDeviceId?: string) => Promise + close: () => void +} + +export function createSessionCallerHarness( + hostRef: SessionHostRef, + getVisibleSessionTabIndex: () => { present: boolean; sessionIds: string[] } = () => ({ + present: false, + sessionIds: [] + }) +): SessionCallerHarness { + const db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === WORKER_HANDLE ? WORKER_PANE : null + ) + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => + runtime.getTerminalPaneKey(handle) + ) + const records = new Map([ + [SESSION_X, sessionRecord(SESSION_X, { providerId: PROVIDER_ID_X })], + [SESSION_Y, sessionRecord(SESSION_Y)] + ]) + hostRef.current = { + deps: { + store: { + getRecord: (sessionId: string) => records.get(sessionId) ?? null, + getConversation: (id: string) => { + const record = records.get(id) + return record ? agentSessionConversationView(record) : null + }, + listConversations: () => [...records.values()].map(agentSessionConversationView), + requireWritableRecord: (id: string) => { + const record = records.get(id) + if (!record) { + throw new Error('Missing test record') + } + return record + }, + listRecords: () => [...records.values()], + getVisibleSessionTabIndex + } + } + } + structuredWorkerIdentities.clear() + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + return { + runtime, + db, + dispatcher, + records, + dispatch: (request) => dispatcher.dispatch(request), + dispatchStreaming: async (request, pairedDeviceId) => { + const replies: string[] = [] + await dispatcher.dispatchStreaming( + request, + (reply) => replies.push(reply), + pairedDeviceId ? { pairedDeviceId } : {} + ) + const [reply] = replies + if (replies.length !== 1 || reply === undefined) { + throw new Error(`expected exactly one reply, got ${replies.length}`) + } + const parsed: unknown = JSON.parse(reply) + return parsed + }, + close: () => { + hostRef.current = null + structuredWorkerIdentities.clear() + db.close() + } + } +} + +let requestCounter = 0 + +/** An orchestration request as the CLI sends it, naming its caller by session id when given. */ +export function orchestrationRequest( + method: string, + params: Record, + options: { + sessionId?: string + requestId?: string + evidence?: OrchestrationCompatibilityEvidence + } = {} +): RpcRequest { + requestCounter += 1 + const requestId = options.requestId ?? `req-${requestCounter}` + const evidence = + options.sessionId === undefined + ? options.evidence + : { ...options.evidence, agentSessionId: options.sessionId } + return { + id: `rpc-${requestCounter}`, + authToken: 'test', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: requestId, + compatibilityInvocationId: requestId, + ...(evidence ? { orchestrationCompatibilityEvidence: evidence } : {}) + } +} + +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export function resultOf(response: unknown): Record { + if (!isRecord(response) || response.ok !== true || !isRecord(response.result)) { + throw new Error(`expected a successful response, got ${JSON.stringify(response)}`) + } + return response.result +} + +export function idOf(row: unknown): string { + if (!isRecord(row) || typeof row.id !== 'string') { + throw new Error(`expected a row with an id, got ${JSON.stringify(row)}`) + } + return row.id +} diff --git a/src/main/runtime/rpc/worker-caller-identity-restore-wait.ts b/src/main/runtime/rpc/orchestration/callers/worker-caller-identity-restore-wait.ts similarity index 83% rename from src/main/runtime/rpc/worker-caller-identity-restore-wait.ts rename to src/main/runtime/rpc/orchestration/callers/worker-caller-identity-restore-wait.ts index 1f00507a24a..11c3cc62d40 100644 --- a/src/main/runtime/rpc/worker-caller-identity-restore-wait.ts +++ b/src/main/runtime/rpc/orchestration/callers/worker-caller-identity-restore-wait.ts @@ -1,7 +1,7 @@ -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import type { OrchestrationCallerField } from './methods/orchestration/access/orchestration-method-access' -import { isDispatchMutationMessageType } from '../../../shared/rpc-contract/orchestration-params' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { RpcRequest } from '../../core' +import type { OrchestrationCallerField } from '../../methods/orchestration/access/orchestration-method-access' +import { isDispatchMutationMessageType } from '../../../../../shared/rpc-contract/orchestration/orchestration-params' // The calls a worker makes as itself, each fenced on its terminal's pane and process. const WORKER_REPORT_METHODS: ReadonlySet = new Set([ diff --git a/src/main/runtime/rpc/orchestration/compatibility/orchestration-11745-regression-verification.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-11745-regression-verification.test.ts new file mode 100644 index 00000000000..91d1a18ad97 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-11745-regression-verification.test.ts @@ -0,0 +1,183 @@ +// Pin #11745 through state as well as replies: refused calls must not mutate graphs or fence legitimate coordinators. +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +import SyncDatabase from '../../../../sqlite/sync-database' +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import { + cleanupLegacyCompatibilityDispatcherHarnesses, + COORDINATOR_HANDLE, + counts, + createHarness, + currentEvidence, + CURRENT_COORDINATOR_HANDLE, + CURRENT_COORDINATOR_PANE, + evidence, + request, + type LegacyCompatibilityDispatcherHarness +} from './testing/orchestration-legacy-compatibility-dispatcher-test-fixture' +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' + +const tempDirs: string[] = [] +const databases: OrchestrationDb[] = [] + +afterEach(() => { + cleanupLegacyCompatibilityDispatcherHarnesses() + for (const database of databases.splice(0)) { + database.close() + } + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } +}) + +/** Every observable the adopted Run's recovered graph exposes; a refusal must leave all of it equal. */ +function adoptedGraph(harness: LegacyCompatibilityDispatcherHarness) { + return { + task: harness.db.getTask(harness.taskId)?.status, + dispatch: harness.db.getDispatchContextById(harness.dispatchId)?.status, + gates: harness.db.listGates({ taskId: harness.taskId }).length, + tasksInRun: harness.db.listTasks({ runId: harness.adoptedRunId }).length, + run: harness.db.getRun(harness.adoptedRunId)?.coordinator_handle ?? null, + tables: counts(harness.db) + } +} + +async function legacyClaimsAdoptedRun( + harness: LegacyCompatibilityDispatcherHarness, + id: string +): Promise { + const response = await harness.dispatcher.dispatch( + request( + 'orchestration.runUse', + { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, + evidence('coordinator'), + `${id}-legacy-claim` + ) + ) + expect(response).toMatchObject({ ok: true }) +} + +async function currentCoordinatorTakesOver( + harness: LegacyCompatibilityDispatcherHarness, + id: string +): Promise { + const response = await harness.dispatcher.dispatch( + request( + 'orchestration.runUse', + { id: harness.adoptedRunId, from: CURRENT_COORDINATOR_HANDLE, takeoverLegacy: true }, + currentEvidence('coordinator'), + `${id}-takeover` + ) + ) + expect(response).toMatchObject({ ok: true }) +} + +describe('#11745 H3 — adopted Run claimed by the legacy coordinator', () => { + it('still fences the genuinely stale legacy coordinator with legacy_read_only and zero effects', async () => { + const harness = createHarness() + await legacyClaimsAdoptedRun(harness, 'v-h3b') + await currentCoordinatorTakesOver(harness, 'v-h3b') + const before = adoptedGraph(harness) + + const response = await harness.dispatcher.dispatch( + request( + 'orchestration.taskCreate', + { + spec: 'stale assignment', + run: harness.adoptedRunId, + callerTerminalHandle: COORDINATOR_HANDLE + }, + evidence('coordinator'), + 'v-h3b-stale' + ) + ) + + expect(response).toMatchObject({ + ok: false, + error: { code: 'legacy_read_only', data: { effectsApplied: false } } + }) + expect(adoptedGraph(harness)).toEqual(before) + }) +}) + +/** Builds a pre-cutover graph at schema 18 and reopens it so adoption runs. */ +function createAdoptedDb(options: { settleWork: boolean }): { + db: OrchestrationDb + adoptedRunId: string + recoveryMessageId: string +} { + const dir = mkdtempSync(join(tmpdir(), 'orca-11745-m5-')) + tempDirs.push(dir) + const dbPath = join(dir, 'orchestration.db') + + const before = new OrchestrationDb(dbPath) + const task = before.createTask({ + runId: 'run_legacy_local', + spec: 'legacy assignment', + createdByTerminalHandle: 'term_old' + }) + createRootDispatch( + before, + task.id, + 'term_old_worker', + 'tab_old:33333333-3333-4333-8333-333333333333' + ) + const recovery = before.insertMessage({ + runId: 'run_legacy_local', + from: 'term_old_worker', + to: 'term_old', + subject: 'recovered worker outcome', + type: 'worker_done' + }) + before.close() + + const raw = new SyncDatabase(dbPath) + if (options.settleWork) { + raw.exec("UPDATE dispatch_contexts SET status = 'completed'") + } + raw.exec(` + DROP INDEX IF EXISTS idx_messages_delivery_contract; + DROP TABLE legacy_mail_receipts; + DROP TABLE legacy_operation_receipts; + DROP TABLE legacy_compatibility_principals; + DROP TABLE legacy_adoptions; + `) + raw.pragma('user_version = 18') + raw.close() + + const db = new OrchestrationDb(dbPath) + databases.push(db) + return { + db, + adoptedRunId: db.getLegacyAdoption()?.adopted_run_id as string, + recoveryMessageId: recovery.id + } +} + +describe('#11745 M5 — binding an unclaimed adopted Run', () => { + it('binds without --takeover-legacy when no legacy work is live, and keeps legacy mail promoted', () => { + const { db, adoptedRunId, recoveryMessageId } = createAdoptedDb({ settleWork: true }) + expect(db.getMessageById(recoveryMessageId)?.run_id).toBe(adoptedRunId) + + const run = db.bindRun({ + runId: adoptedRunId, + coordinatorHandle: CURRENT_COORDINATOR_HANDLE, + coordinatorPaneKey: CURRENT_COORDINATOR_PANE + }) + + expect(run?.id).toBe(adoptedRunId) + expect(db.getRun(adoptedRunId)).toMatchObject({ + coordinator_handle: CURRENT_COORDINATOR_HANDLE + }) + // The recovered mail must still belong to the adopted Run, not be orphaned by the bind. + expect(db.getMessageById(recoveryMessageId)?.run_id).toBe(adoptedRunId) + expect(db.getCurrentRunForPane(CURRENT_COORDINATOR_PANE)?.id).toBe(adoptedRunId) + }) +}) diff --git a/src/main/runtime/rpc/orchestration-contract-fence.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-contract-fence.ts similarity index 80% rename from src/main/runtime/rpc/orchestration-contract-fence.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-contract-fence.ts index f54e5f8e345..a3c39a548c8 100644 --- a/src/main/runtime/rpc/orchestration-contract-fence.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-contract-fence.ts @@ -3,10 +3,10 @@ import { isRetiredOrchestrationMethod, orchestrationMigrationData, type OrchestrationMigrationReason -} from '../../../shared/orchestration/orchestration-rpc-contract' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from './core' -import { errorResponse } from './errors' +} from '../../../../../shared/orchestration/orchestration-rpc-contract' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from '../../core' +import { errorResponse } from '../../responses/rpc-response' export function orchestrationMigrationFence( request: RpcRequest, diff --git a/src/main/runtime/rpc/orchestration/compatibility/orchestration-current-authority-precedence.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-current-authority-precedence.test.ts new file mode 100644 index 00000000000..4b921cf7bbe --- /dev/null +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-current-authority-precedence.test.ts @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + cleanupLegacyCompatibilityDispatcherHarnesses, + createHarness, + CURRENT_COORDINATOR_HANDLE, + CURRENT_COORDINATOR_PANE, + evidence, + invoke, + request, + WORKER_HANDLE, + WORKER_PANE +} from './testing/orchestration-legacy-compatibility-dispatcher-test-fixture' +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' + +afterEach(() => { + cleanupLegacyCompatibilityDispatcherHarnesses() +}) + +describe('current orchestration authority precedence', () => { + it.each(['dispatch', 'websocket'] as const)( + '%s routes a reused legacy terminal current check before its retained principal', + async (transport) => { + const harness = createHarness() + const { runId, dispatchId } = await createReusedCurrentDispatch(harness, transport) + const message = harness.db.insertMessage({ + runId, + from: CURRENT_COORDINATOR_HANDLE, + to: `dispatch:${dispatchId}`, + subject: 'reused terminal guidance', + deliveryContract: 'current_delivery' + }) + + const response = await invoke( + harness.dispatcher, + request( + 'orchestration.check', + { terminal: WORKER_HANDLE }, + evidence('worker'), + `reused-current-check-${transport}` + ), + transport + ) + + expect(response).toMatchObject({ + ok: true, + result: { + runId, + dispatchId, + messages: [{ id: message.id }], + count: 1 + } + }) + expect(response).not.toHaveProperty('result.legacyCompatibility') + } + ) +}) + +async function createReusedCurrentDispatch( + harness: ReturnType, + suffix: string +): Promise<{ + runId: string + taskId: string + dispatchId: string +}> { + const legacyCheck = await harness.dispatcher.dispatch( + request( + 'orchestration.check', + { terminal: WORKER_HANDLE, peek: true }, + evidence('worker'), + `attest-legacy-worker-${suffix}` + ) + ) + expect(legacyCheck).toHaveProperty('result.legacyCompatibility') + harness.db.completeDispatch(harness.dispatchId) + + const run = harness.db.createRun({ + objective: 'current work in reused terminal', + coordinatorHandle: CURRENT_COORDINATOR_HANDLE, + coordinatorPaneKey: CURRENT_COORDINATOR_PANE + }) + const task = harness.db.createTask({ spec: 'reused terminal assignment', runId: run.id }) + const dispatch = createRootDispatch( + harness.db, + task.id, + WORKER_HANDLE, + WORKER_PANE, + undefined, + 'process-1' + ) + return { runId: run.id, taskId: task.id, dispatchId: dispatch.id } +} diff --git a/src/main/runtime/rpc/orchestration-legacy-authority.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-authority.ts similarity index 91% rename from src/main/runtime/rpc/orchestration-legacy-authority.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-authority.ts index 78acdfe79cc..89e1fa5df47 100644 --- a/src/main/runtime/rpc/orchestration-legacy-authority.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-authority.ts @@ -1,18 +1,18 @@ -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' +import type { OrchestrationCompatibilityEvidence } from '../../../../../shared/orchestration/orchestration-compatibility-evidence' import type { DispatchContextRow, LegacyCompatibilityPrincipalRow, LegacyPrincipalRole -} from '../orchestration/db/orchestration-records' -import { OrchestrationError } from '../orchestration/orchestration-error' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrchestrationCompatibilityCallerAuthority } from '../orchestration/terminal-authority/orchestration-compatibility-authority' -import '../orchestration/db/orchestration-db' -import { LEGACY_CONTRACT_VERSION } from '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' +} from '../../../orchestration/db/orchestration-records' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { OrchestrationCompatibilityCallerAuthority } from '../../../orchestration/terminal-authority/orchestration-compatibility-authority' +import '../../../orchestration/db/orchestration-db' +import { LEGACY_CONTRACT_VERSION } from '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest } from '../../core' import { equivalentLegacyPaneKey, legacyCoordinatorReadOnly, diff --git a/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-compatibility-dispatcher.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-compatibility-dispatcher.test.ts new file mode 100644 index 00000000000..a2a5c238aa5 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-compatibility-dispatcher.test.ts @@ -0,0 +1,246 @@ +import { createHash } from 'node:crypto' +import { afterEach, describe, expect, it } from 'vitest' +import type Database from '../../../../sqlite/sync-database' +import { + cleanupLegacyCompatibilityDispatcherHarnesses, + COORDINATOR_HANDLE, + counts, + createHarness, + escalationParams, + evidence, + request, + WORKER_HANDLE, + WORKER_PANE +} from './testing/orchestration-legacy-compatibility-dispatcher-test-fixture' +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' + +afterEach(() => { + cleanupLegacyCompatibilityDispatcherHarnesses() +}) + +describe('legacy compatibility through RpcDispatcher', () => { + it('validates, infers, settles, and replays legacy worker completion exactly once', async () => { + const harness = createHarness() + const baseParams = { + from: WORKER_HANDLE, + to: COORDINATOR_HANDLE, + type: 'worker_done', + body: 'legacy result', + payload: JSON.stringify({ taskId: harness.taskId, dispatchId: harness.dispatchId }) + } + const before = counts(harness.db) + const invalid = await harness.dispatcher.dispatch( + request( + 'orchestration.send', + { ...baseParams, subject: 'Completed', payload: JSON.stringify({ outcome: 'maybe' }) }, + evidence('worker'), + 'invalid-outcome' + ) + ) + + expect(invalid).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(counts(harness.db)).toEqual(before) + + const firstRequest = request( + 'orchestration.send', + { ...baseParams, subject: 'Completed' }, + evidence('worker'), + 'completion' + ) + const first = await harness.dispatcher.dispatch(firstRequest) + const replay = await harness.dispatcher.dispatch({ ...firstRequest, id: 'rpc_replay' }) + const mismatch = await harness.dispatcher.dispatch({ + ...firstRequest, + id: 'rpc_mismatch', + params: { ...baseParams, subject: 'Changed completion' } + }) + + expect(first).toMatchObject({ + ok: true, + result: { + lifecycle: { action: 'settled', outcome: 'succeeded' }, + legacyCompatibility: { replayed: false } + } + }) + expect(replay).toMatchObject({ + ok: true, + result: { legacyCompatibility: { replayed: true } } + }) + expect(mismatch).toMatchObject({ ok: false, error: { code: 'request_mismatch' } }) + expect(harness.db.getTask(harness.taskId)?.status).toBe('completed') + expect(harness.db.getDispatchContextById(harness.dispatchId)?.status).toBe('completed') + expect(counts(harness.db)).toEqual({ + ...before, + messages: before.messages + 1, + legacy_compatibility_principals: before.legacy_compatibility_principals + 1, + legacy_operation_receipts: before.legacy_operation_receipts + 1 + }) + expect(harness.notify).toHaveBeenCalledOnce() + }) + + it('replays an A-era completion without touching a newer current attempt', async () => { + const harness = createHarness() + const payload = JSON.stringify({ + taskId: harness.taskId, + dispatchId: harness.dispatchId + }) + const completion = harness.db.insertMessage({ + runId: harness.adoptedRunId, + from: WORKER_HANDLE, + to: COORDINATOR_HANDLE, + subject: 'Failed: pinned A treated this as complete', + body: 'persisted result', + type: 'worker_done', + payload, + senderPaneKey: WORKER_PANE, + deliveryContract: 'legacy_direct' + }) + harness.db.settleWorkerReport({ + taskId: harness.taskId, + dispatchId: harness.dispatchId, + outcome: 'succeeded', + result: 'persisted result' + }) + harness.db.commitLegacyCompatibilityPrincipal({ + runId: harness.adoptedRunId, + dispatchId: harness.dispatchId, + role: 'worker', + hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), + terminalHandle: WORKER_HANDLE, + paneKey: WORKER_PANE, + launchTokenHash: createHash('sha256').update('worker-token').digest('hex'), + processIncarnation: 'process-1' + }) + // Recreate the pre-boundary state where A settled before a current attempt was persisted. + const sqlite = (harness.db as unknown as { db: Database.Database }).db + sqlite.prepare("UPDATE tasks SET status = 'ready' WHERE id = ?").run(harness.taskId) + const currentDispatch = createRootDispatch( + harness.db, + harness.taskId, + 'term_current_worker', + 'tab_current_worker:77777777-7777-4777-8777-777777777777', + 'current-launch-hash' + ) + const currentTaskBefore = harness.db.getTask(harness.taskId) + const currentDispatchBefore = harness.db.getDispatchContextById(currentDispatch.id) + const before = counts(harness.db) + + const response = await harness.dispatcher.dispatch( + request( + 'orchestration.send', + { + from: WORKER_HANDLE, + to: COORDINATOR_HANDLE, + subject: completion.subject, + body: completion.body, + type: 'worker_done', + payload + }, + evidence('worker'), + 'reconstruct-pinned-a-completion' + ) + ) + + expect(response).toMatchObject({ + ok: true, + result: { + message: { id: completion.id }, + lifecycle: { action: 'settled', outcome: 'succeeded', duplicate: true } + } + }) + expect(harness.db.getTask(harness.taskId)).toEqual(currentTaskBefore) + expect(harness.db.getDispatchContextById(harness.dispatchId)?.status).toBe('completed') + expect(harness.db.getDispatchContextById(currentDispatch.id)).toEqual(currentDispatchBefore) + expect(counts(harness.db)).toEqual({ + ...before, + legacy_operation_receipts: before.legacy_operation_receipts + 1 + }) + }) + + it('rejects invalid typed ACKs and consumes only the filtered legacy page', async () => { + const harness = createHarness() + await harness.dispatcher.dispatch( + request( + 'orchestration.send', + { + ...escalationParams(harness), + type: 'worker_done', + subject: 'Completed', + payload: JSON.stringify({ taskId: harness.taskId, dispatchId: harness.dispatchId }) + }, + evidence('worker'), + 'settle-for-mail' + ) + ) + const status = harness.db.insertMessage({ + runId: harness.adoptedRunId, + from: COORDINATOR_HANDLE, + to: WORKER_HANDLE, + subject: 'status first', + type: 'status', + deliveryContract: 'legacy_direct' + }) + const question = harness.db.insertMessage({ + runId: harness.adoptedRunId, + from: COORDINATOR_HANDLE, + to: WORKER_HANDLE, + subject: 'question second', + type: 'question', + deliveryContract: 'legacy_direct' + }) + const check = await harness.dispatcher.dispatch( + request( + 'orchestration.check', + { terminal: WORKER_HANDLE, types: 'question' }, + evidence('worker'), + 'question-check' + ) + ) + expect(check).toMatchObject({ + ok: true, + result: { + messages: [{ id: question.id }], + legacyCompatibility: { ackMessageIds: [question.id] } + } + }) + + const invalid = await harness.dispatcher.dispatch( + request( + 'orchestration.check', + { + terminal: WORKER_HANDLE, + compatibilityAck: JSON.stringify({ + messageIds: [question.id], + types: ['not-a-message-type'] + }) + }, + evidence('worker'), + 'invalid-ack' + ) + ) + expect(invalid).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(harness.db.getMessageById(status.id)?.read).toBe(0) + expect(harness.db.getMessageById(question.id)?.read).toBe(0) + + const acknowledged = await harness.dispatcher.dispatch( + request( + 'orchestration.check', + { + terminal: WORKER_HANDLE, + compatibilityAck: JSON.stringify({ + messageIds: [question.id], + types: ['question'] + }) + }, + evidence('worker'), + 'valid-ack' + ) + ) + expect(acknowledged).toMatchObject({ + ok: true, + result: { acknowledged: [question.id], legacyCompatibility: { acknowledged: true } } + }) + expect(harness.db.getMessageById(status.id)?.read).toBe(0) + expect(harness.db.getMessageById(question.id)?.read).toBe(1) + }) +}) diff --git a/src/main/runtime/rpc/orchestration-legacy-compatibility.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-compatibility.ts similarity index 94% rename from src/main/runtime/rpc/orchestration-legacy-compatibility.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-compatibility.ts index b248fa9eb75..31198515218 100644 --- a/src/main/runtime/rpc/orchestration-legacy-compatibility.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-compatibility.ts @@ -1,13 +1,13 @@ import { createHash } from 'node:crypto' -import type { LegacyCoordinatorAuthorityProof, RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrchestrationCompatibilityCallerAuthority } from '../orchestration/terminal-authority/orchestration-compatibility-authority' -import '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import { ORCHESTRATION_CONTRACT_VERSION as CURRENT_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' +import type { LegacyCoordinatorAuthorityProof, RpcRequest } from '../../core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { OrchestrationCompatibilityCallerAuthority } from '../../../orchestration/terminal-authority/orchestration-compatibility-authority' +import '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import { ORCHESTRATION_CONTRACT_VERSION as CURRENT_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' import { LegacyCompatibilityAuthority } from './orchestration-legacy-authority' import { handleLegacyLifecycleSend } from './orchestration-legacy-lifecycle' import { handleLegacyCheck, handleLegacyReply } from './orchestration-legacy-mail' diff --git a/src/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-coordinator-authority.ts similarity index 95% rename from src/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-coordinator-authority.ts index 19ad40de229..e84256f7666 100644 --- a/src/main/runtime/rpc/orchestration-legacy-coordinator-authority.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-coordinator-authority.ts @@ -1,8 +1,8 @@ -import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrchestrationCompatibilityCallerAuthority } from '../orchestration/terminal-authority/orchestration-compatibility-authority' -import type { OrchestrationDb } from '../orchestration/db/orchestration-db' -import type { LegacyCompatibilityPrincipalRow } from '../orchestration/db/orchestration-records' -import type { LegacyCoordinatorAuthorityProof, RpcRequest } from './core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { OrchestrationCompatibilityCallerAuthority } from '../../../orchestration/terminal-authority/orchestration-compatibility-authority' +import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import type { LegacyCompatibilityPrincipalRow } from '../../../orchestration/db/orchestration-records' +import type { LegacyCoordinatorAuthorityProof, RpcRequest } from '../../core' import { resolveAttestedLegacyPrincipal, verifyAttestedLegacyCandidate, diff --git a/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-coordinator-race.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-coordinator-race.test.ts new file mode 100644 index 00000000000..c685933cfd0 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-coordinator-race.test.ts @@ -0,0 +1,234 @@ +import { createHash } from 'node:crypto' + +import { mkdtempSync, rmSync } from 'node:fs' + +import { tmpdir } from 'node:os' + +import { join } from 'node:path' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' + +import type { OrchestrationCompatibilityEvidence } from '../../../../../shared/orchestration/orchestration-compatibility-evidence' + +import Database from '../../../../sqlite/sync-database' + +import { OrcaRuntimeService } from '../../../orca-runtime' + +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' + +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest } from '../../core' + +import { RpcDispatcher } from '../../dispatcher' + +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' + +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' + +import { MessageWake } from '../../../orchestration/mailbox/runtime-message-waiters' + +const COORDINATOR_HANDLE = 'term_legacy_coord' +const COORDINATOR_PANE = 'tab_coord:44444444-4444-4444-8444-444444444444' +const WORKER_HANDLE = 'term_legacy_worker' +const WORKER_PANE = 'tab_worker:33333333-3333-4333-8333-333333333333' + +type Harness = { + db: OrchestrationDb + dispatcher: RpcDispatcher + runtime: OrcaRuntimeService + adoptedRunId: string + taskId: string + dispatchId: string +} + +const tempDirs: string[] = [] +const databases: OrchestrationDb[] = [] + +afterEach(() => { + databases.splice(0).forEach((database) => database.close()) + tempDirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })) +}) + +function createHarness(): Harness { + const dir = mkdtempSync(join(tmpdir(), 'orca-legacy-coordinator-race-')) + tempDirs.push(dir) + const dbPath = join(dir, 'orchestration.db') + const before = new OrchestrationDb(dbPath) + const task = before.createTask({ + runId: 'run_legacy_local', + spec: 'legacy assignment', + createdByTerminalHandle: COORDINATOR_HANDLE + }) + const dispatch = createRootDispatch(before, task.id, WORKER_HANDLE, WORKER_PANE) + before.close() + + const raw = new Database(dbPath) + raw.exec(` + UPDATE dispatch_contexts SET process_incarnation = 'process-1'; + DROP INDEX IF EXISTS idx_messages_delivery_contract; + DROP TABLE legacy_mail_receipts; + DROP TABLE legacy_operation_receipts; + DROP TABLE legacy_compatibility_principals; + DROP TABLE legacy_adoptions; + `) + raw.pragma('user_version = 18') + raw.close() + + const db = new OrchestrationDb(dbPath) + databases.push(db) + const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === COORDINATOR_HANDLE ? COORDINATOR_PANE : handle === WORKER_HANDLE ? WORKER_PANE : null + ) + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => + runtime.getTerminalPaneKey(handle) + ) + vi.spyOn(runtime, 'verifyOrchestrationCompatibilityCaller').mockImplementation( + (compatibilityEvidence) => { + const coordinator = + compatibilityEvidence?.terminalHandle === COORDINATOR_HANDLE && + compatibilityEvidence.paneKey === COORDINATOR_PANE && + compatibilityEvidence.launchToken === 'coordinator-token' + const worker = + compatibilityEvidence?.terminalHandle === WORKER_HANDLE && + compatibilityEvidence.paneKey === WORKER_PANE && + compatibilityEvidence.launchToken === 'worker-token' + return coordinator || worker + ? { + hostScope: { kind: 'local', hostId: 'local' }, + terminalHandle: coordinator ? COORDINATOR_HANDLE : WORKER_HANDLE, + paneKey: coordinator ? COORDINATOR_PANE : WORKER_PANE, + processIncarnation: 'process-1', + launchTokenHash: createHash('sha256') + .update(coordinator ? 'coordinator-token' : 'worker-token') + .digest('hex') + } + : null + } + ) + return { + db, + dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }), + runtime, + adoptedRunId, + taskId: task.id, + dispatchId: dispatch.id + } +} + +function evidence( + role: 'coordinator' | 'worker' = 'coordinator' +): OrchestrationCompatibilityEvidence { + return { + terminalHandle: role === 'coordinator' ? COORDINATOR_HANDLE : WORKER_HANDLE, + paneKey: role === 'coordinator' ? COORDINATOR_PANE : WORKER_PANE, + launchToken: role === 'coordinator' ? 'coordinator-token' : 'worker-token' + } +} + +function request( + method: string, + params: unknown, + invocationId: string, + callerEvidence = evidence() +): RpcRequest { + return { + id: `rpc_${invocationId}`, + authToken: 'caller-token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: invocationId, + compatibilityInvocationId: invocationId, + orchestrationCompatibilityEvidence: callerEvidence + } +} + +describe('legacy coordinator takeover races', () => { + it('keeps concurrent duplicates on the live ACK-and-wait result', async () => { + const harness = createHarness() + harness.db.insertMessage({ + runId: harness.adoptedRunId, + from: WORKER_HANDLE, + to: `run:${harness.adoptedRunId}`, + subject: 'first delivery' + }) + const firstCheck = await harness.dispatcher.dispatch( + request( + 'orchestration.check', + { terminal: COORDINATOR_HANDLE, run: harness.adoptedRunId }, + 'check-first-delivery' + ) + ) + const deliveryId = (firstCheck as { result: { deliveryId: string } }).result.deliveryId + let resolveWait: (() => void) | undefined + let signalWaitStarted: (() => void) | undefined + const waitStarted = new Promise((resolve) => { + signalWaitStarted = resolve + }) + vi.spyOn(harness.runtime, 'waitForMessage').mockImplementation( + () => + new Promise((resolve) => { + resolveWait = () => resolve(new MessageWake()) + signalWaitStarted?.() + }) + ) + const ackRequest = request( + 'orchestration.check', + { + terminal: COORDINATOR_HANDLE, + run: harness.adoptedRunId, + ack: deliveryId, + wait: true, + timeoutMs: 10_000 + }, + 'check-ack-concurrent' + ) + const original = harness.dispatcher.dispatch(ackRequest) + await waitStarted + const secondLiveDispatcher = new RpcDispatcher({ + runtime: harness.runtime, + methods: ORCHESTRATION_METHODS + }) + const duplicate = secondLiveDispatcher.dispatch({ + ...ackRequest, + id: 'rpc_check-ack-concurrent-duplicate' + }) + let duplicateSettled = false + void duplicate.then(() => { + duplicateSettled = true + }) + await Promise.resolve() + expect(duplicateSettled).toBe(false) + + const arrived = harness.db.insertMessage({ + runId: harness.adoptedRunId, + from: WORKER_HANDLE, + to: `run:${harness.adoptedRunId}`, + subject: 'arrived while waiting' + }) + resolveWait?.() + const [originalResult, duplicateResult] = await Promise.all([original, duplicate]) + expect(originalResult).toMatchObject({ + ok: true, + result: { + messages: [{ id: arrived.id }], + mutation: { requestId: 'check-ack-concurrent', replayed: false } + } + }) + expect(duplicateResult).toMatchObject({ + ok: true, + result: { + messages: [{ id: arrived.id }], + mutation: { requestId: 'check-ack-concurrent', replayed: true } + } + }) + }) +}) diff --git a/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-fence-jurisdiction.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-fence-jurisdiction.test.ts new file mode 100644 index 00000000000..ee380324f5f --- /dev/null +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-fence-jurisdiction.test.ts @@ -0,0 +1,104 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + cleanupLegacyCompatibilityDispatcherHarnesses, + COORDINATOR_HANDLE, + createHarness, + currentEvidence, + CURRENT_COORDINATOR_HANDLE, + CURRENT_COORDINATOR_PANE, + evidence, + request, + type LegacyCompatibilityDispatcherHarness +} from './testing/orchestration-legacy-compatibility-dispatcher-test-fixture' + +afterEach(() => { + cleanupLegacyCompatibilityDispatcherHarnesses() +}) + +async function claimAdoptedRunAsLegacyCoordinator( + harness: LegacyCompatibilityDispatcherHarness +): Promise { + const response = await harness.dispatcher.dispatch( + request( + 'orchestration.runUse', + { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, + evidence('coordinator'), + 'legacy-coordinator-run-use' + ) + ) + expect(response).toMatchObject({ ok: true }) + expect(harness.db.getLegacyCoordinatorPrincipal(harness.adoptedRunId)?.status).toBe('committed') +} + +async function takeoverAdoptedRun(harness: LegacyCompatibilityDispatcherHarness): Promise { + const response = await harness.dispatcher.dispatch( + request( + 'orchestration.runUse', + { id: harness.adoptedRunId, from: CURRENT_COORDINATOR_HANDLE, takeoverLegacy: true }, + currentEvidence('coordinator'), + 'current-coordinator-takeover' + ) + ) + expect(response).toMatchObject({ ok: true }) + expect(harness.db.getLegacyCoordinatorPrincipal(harness.adoptedRunId)?.status).toBe('revoked') +} + +describe('legacy coordinator fence jurisdiction', () => { + it('releases the fence once the adopted Run is unclaimed and its principal is revoked', async () => { + const harness = createHarness() + await claimAdoptedRunAsLegacyCoordinator(harness) + await takeoverAdoptedRun(harness) + // The new owner moves its pane to another Run, which unbinds the adopted Run. + const elsewhere = harness.db.createRun({ + objective: 'other work', + coordinatorHandle: CURRENT_COORDINATOR_HANDLE, + coordinatorPaneKey: CURRENT_COORDINATOR_PANE + }) + expect(elsewhere.id).not.toBe(harness.adoptedRunId) + harness.db.bindRun({ + runId: elsewhere.id, + coordinatorHandle: CURRENT_COORDINATOR_HANDLE, + coordinatorPaneKey: CURRENT_COORDINATOR_PANE + }) + expect(harness.db.getRun(harness.adoptedRunId)?.coordinator_pane_key).toBeNull() + + const fenced = await harness.dispatcher.dispatch( + request( + 'orchestration.taskCreate', + { spec: 'unclaimed assignment', callerTerminalHandle: COORDINATOR_HANDLE }, + evidence('coordinator'), + 'unclaimed-revoked-task-create' + ) + ) + expect(fenced).toMatchObject({ ok: false, error: { code: 'run_required' } }) + + const reclaim = await harness.dispatcher.dispatch( + request( + 'orchestration.runUse', + { id: harness.adoptedRunId, from: COORDINATOR_HANDLE }, + evidence('coordinator'), + 'unclaimed-revoked-run-use' + ) + ) + // The Run still holds live legacy work, so the honest downstream error — not a dead-end fence — answers. + expect(reclaim).toMatchObject({ + ok: false, + error: { + code: 'consumer_fenced', + data: { + recoveryCommand: `orca orchestration run-use --id ${harness.adoptedRunId} --takeover-legacy` + } + } + }) + + const recovered = await harness.dispatcher.dispatch( + request( + 'orchestration.runUse', + { id: harness.adoptedRunId, from: COORDINATOR_HANDLE, takeoverLegacy: true }, + evidence('coordinator'), + 'unclaimed-revoked-run-takeover' + ) + ) + expect(recovered).toMatchObject({ ok: true, result: { run: { id: harness.adoptedRunId } } }) + }) +}) diff --git a/src/main/runtime/rpc/orchestration-legacy-lifecycle.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-lifecycle.ts similarity index 90% rename from src/main/runtime/rpc/orchestration-legacy-lifecycle.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-lifecycle.ts index c0edcfc3a8b..e894a6a08fe 100644 --- a/src/main/runtime/rpc/orchestration-legacy-lifecycle.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-lifecycle.ts @@ -1,8 +1,8 @@ -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { MessageType } from '../orchestration/db/orchestration-records' -import { OrchestrationError } from '../orchestration/orchestration-error' -import { bindCoordinatorMutationPayload } from '../orchestration/workers/reports/dispatch-message-binding' +import type { RpcRequest } from '../../core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { MessageType } from '../../../orchestration/db/orchestration-records' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import { bindCoordinatorMutationPayload } from '../../../orchestration/workers/reports/dispatch-message-binding' import type { LegacyCompatibilityAuthority } from './orchestration-legacy-authority' import { inferLegacyWorkerOutcome, diff --git a/src/main/runtime/rpc/orchestration-legacy-mail.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-mail.ts similarity index 94% rename from src/main/runtime/rpc/orchestration-legacy-mail.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-mail.ts index 3a041f4fc5d..0008cd25e89 100644 --- a/src/main/runtime/rpc/orchestration-legacy-mail.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-mail.ts @@ -1,8 +1,8 @@ -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationError } from '../orchestration/orchestration-error' -import { formatMessageBanner } from '../orchestration/mailbox/formatting/message-formatting' -import { ORCHESTRATION_MESSAGE_WAIT_DEFAULT_TIMEOUT_MS } from '../../../shared/orchestration/mailbox/orchestration-message-wait-timeout' +import type { RpcRequest } from '../../core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import { formatMessageBanner } from '../../../orchestration/mailbox/formatting/message-formatting' +import { ORCHESTRATION_MESSAGE_WAIT_DEFAULT_TIMEOUT_MS } from '../../../../../shared/orchestration/mailbox/orchestration-message-wait-timeout' import type { LegacyCompatibilityAuthority } from './orchestration-legacy-authority' import { operationIdentity, diff --git a/src/main/runtime/rpc/orchestration-legacy-operation.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-operation.ts similarity index 95% rename from src/main/runtime/rpc/orchestration-legacy-operation.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-operation.ts index d22ced5e342..f813b057951 100644 --- a/src/main/runtime/rpc/orchestration-legacy-operation.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-operation.ts @@ -1,13 +1,13 @@ import { createHash, randomUUID } from 'node:crypto' -import type { RpcRequest } from './core' +import type { RpcRequest } from '../../core' import type { MessageType, LegacyCompatibilityPrincipalRow, MessageRow -} from '../orchestration/db/orchestration-records' -import { MESSAGE_TYPES } from '../orchestration/db/orchestration-records' +} from '../../../orchestration/db/orchestration-records' +import { MESSAGE_TYPES } from '../../../orchestration/db/orchestration-records' -import { OrchestrationError } from '../orchestration/orchestration-error' +import { OrchestrationError } from '../../../orchestration/orchestration-error' const MESSAGE_TYPE_SET = new Set(MESSAGE_TYPES) diff --git a/src/main/runtime/rpc/orchestration-legacy-process-identity.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-process-identity.ts similarity index 84% rename from src/main/runtime/rpc/orchestration-legacy-process-identity.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-process-identity.ts index 2ebb9f3ecb3..57e2627e217 100644 --- a/src/main/runtime/rpc/orchestration-legacy-process-identity.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-process-identity.ts @@ -1,5 +1,5 @@ -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { OrchestrationError } from '../orchestration/orchestration-error' +import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { OrchestrationError } from '../../../orchestration/orchestration-error' export function equivalentLegacyPaneKey( a: string | null | undefined, diff --git a/src/main/runtime/rpc/orchestration-legacy-question-takeover.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-question-takeover.test.ts similarity index 90% rename from src/main/runtime/rpc/orchestration-legacy-question-takeover.test.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-question-takeover.test.ts index 821422e0da2..7287c561c28 100644 --- a/src/main/runtime/rpc/orchestration-legacy-question-takeover.test.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-question-takeover.test.ts @@ -3,19 +3,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import Database from '../../sqlite/sync-database' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' +import type { OrchestrationCompatibilityEvidence } from '../../../../../shared/orchestration/orchestration-compatibility-evidence' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import Database from '../../../../sqlite/sync-database' +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import { OrcaRuntimeService } from '../../../orca-runtime' +import type { RpcRequest } from '../../core' +import { RpcDispatcher } from '../../dispatcher' +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' const COORDINATOR_HANDLE = 'term_legacy_coord' const CURRENT_COORDINATOR_HANDLE = 'term_current_coord' diff --git a/src/main/runtime/rpc/orchestration-legacy-question.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-question.ts similarity index 90% rename from src/main/runtime/rpc/orchestration-legacy-question.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-question.ts index baa3b15a3f3..1bb185e98d8 100644 --- a/src/main/runtime/rpc/orchestration-legacy-question.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-question.ts @@ -1,12 +1,12 @@ -import { clampOrchestrationAskTimeoutMs } from '../../../shared/orchestration/mailbox/orchestration-ask-timeout' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationError } from '../orchestration/orchestration-error' -import '../orchestration/db/orchestration-db' -import { LEGACY_CONTRACT_VERSION } from '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' +import { clampOrchestrationAskTimeoutMs } from '../../../../../shared/orchestration/mailbox/orchestration-ask-timeout' +import type { RpcRequest } from '../../core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import '../../../orchestration/db/orchestration-db' +import { LEGACY_CONTRACT_VERSION } from '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' import type { LegacyCompatibilityAuthority } from './orchestration-legacy-authority' import { normalizeLegacyText, diff --git a/src/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-takeover-dispatcher.test.ts similarity index 79% rename from src/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-takeover-dispatcher.test.ts index 9bae96cb7ef..eb4db7608c7 100644 --- a/src/main/runtime/rpc/orchestration-legacy-takeover-dispatcher.test.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-legacy-takeover-dispatcher.test.ts @@ -3,19 +3,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import Database from '../../sqlite/sync-database' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' +import type { OrchestrationCompatibilityEvidence } from '../../../../../shared/orchestration/orchestration-compatibility-evidence' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import Database from '../../../../sqlite/sync-database' +import { OrcaRuntimeService } from '../../../orca-runtime' +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest } from '../../core' +import { RpcDispatcher } from '../../dispatcher' +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' const WORKER_HANDLE = 'term_legacy_worker' const WORKER_PANE = 'tab_worker:33333333-3333-4333-8333-333333333333' @@ -371,54 +371,3 @@ describe('legacy compatibility after explicit takeover', () => { ).resolves.toMatchObject({ ok: false, error: { code: 'legacy_read_only' } }) }) }) - -const COORDINATOR_ALIAS_HANDLE = 'term_legacy_coord_alias' - -describe('injected dispatch from a legacy-adopted coordinator', () => { - it('refuses an alias of the coordinator pane when only dispatch authority resolves the caller', async () => { - const harness = createHarness() - // Graph-only legacy coordinators have no record-backed handle or pane alias. - vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === WORKER_HANDLE - ? WORKER_PANE - : handle === CURRENT_COORDINATOR_HANDLE - ? CURRENT_COORDINATOR_PANE - : null - ) - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation((handle) => - handle === COORDINATOR_HANDLE || handle === COORDINATOR_ALIAS_HANDLE - ? ({ - terminalHandle: handle, - paneKey: COORDINATOR_PANE, - processIncarnation: 'process-1', - hostScope: { kind: 'local', hostId: 'local' } - } as never) - : null - ) - vi.spyOn(harness.runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - vi.spyOn(harness.runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') - const sendPrompt = vi - .spyOn(harness.runtime, 'sendTerminalAgentPrompt') - .mockResolvedValue({ handle: COORDINATOR_ALIAS_HANDLE, accepted: true, bytesWritten: 1 }) - const task = harness.db.createTask({ spec: 'self inject', runId: harness.adoptedRunId }) - - const response = await harness.dispatcher.dispatch( - request( - 'orchestration.dispatch', - { - task: task.id, - run: harness.adoptedRunId, - from: COORDINATOR_HANDLE, - to: COORDINATOR_ALIAS_HANDLE, - inject: true - }, - evidence('coordinator'), - 'legacy-self-inject' - ) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'terminal_is_coordinator' } }) - expect(sendPrompt).not.toHaveBeenCalled() - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - }) -}) diff --git a/src/main/runtime/rpc/orchestration-mutation-request-show-legacy.test.ts b/src/main/runtime/rpc/orchestration/compatibility/orchestration-mutation-request-show-legacy.test.ts similarity index 94% rename from src/main/runtime/rpc/orchestration-mutation-request-show-legacy.test.ts rename to src/main/runtime/rpc/orchestration/compatibility/orchestration-mutation-request-show-legacy.test.ts index 07c5527584e..42a5840f89b 100644 --- a/src/main/runtime/rpc/orchestration-mutation-request-show-legacy.test.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/orchestration-mutation-request-show-legacy.test.ts @@ -5,7 +5,7 @@ import { createHarness, evidence, request -} from './orchestration-legacy-compatibility-dispatcher-test-fixture' +} from './testing/orchestration-legacy-compatibility-dispatcher-test-fixture' afterEach(() => { cleanupLegacyCompatibilityDispatcherHarnesses() diff --git a/src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.ts b/src/main/runtime/rpc/orchestration/compatibility/testing/orchestration-legacy-compatibility-dispatcher-test-fixture.ts similarity index 88% rename from src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.ts rename to src/main/runtime/rpc/orchestration/compatibility/testing/orchestration-legacy-compatibility-dispatcher-test-fixture.ts index 92a88795e62..3af8620e493 100644 --- a/src/main/runtime/rpc/orchestration-legacy-compatibility-dispatcher-test-fixture.ts +++ b/src/main/runtime/rpc/orchestration/compatibility/testing/orchestration-legacy-compatibility-dispatcher-test-fixture.ts @@ -3,19 +3,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, vi } from 'vitest' -import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import Database from '../../sqlite/sync-database' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest, RpcResponse } from './core' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' +import type { OrchestrationCompatibilityEvidence } from '../../../../../../shared/orchestration/orchestration-compatibility-evidence' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import Database from '../../../../../sqlite/sync-database' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import '../../../../orchestration/db/contract-constants' +import '../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../orchestration/db/dispatch-row-writer' +import '../../../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest, RpcResponse } from '../../../core' +import { RpcDispatcher } from '../../../dispatcher' +import { ORCHESTRATION_METHODS } from '../../../methods/orchestration/orchestration' +import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' export const WORKER_HANDLE = 'term_legacy_worker' export const WORKER_PANE = 'tab_worker:33333333-3333-4333-8333-333333333333' diff --git a/src/main/runtime/rpc/orchestration/mutations/orchestration-commit-notify-characterization.test.ts b/src/main/runtime/rpc/orchestration/mutations/orchestration-commit-notify-characterization.test.ts new file mode 100644 index 00000000000..ec2a4886c79 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/mutations/orchestration-commit-notify-characterization.test.ts @@ -0,0 +1,263 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' + +import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db' + +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import type { OrcaRuntimeService } from '../../../orca-runtime' + +import type { RpcRequest } from '../../core' + +import { RpcDispatcher } from '../../dispatcher' + +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' + +import { createOrchestrationRpcHarness } from '../../methods/orchestration/rpc-test-harness' + +import { MessageWake } from '../../../orchestration/mailbox/runtime-message-waiters' + +describe('orchestration commit-notify recovery', () => { + const harness = createOrchestrationRpcHarness() + + afterEach(() => { + harness.cleanup() + }) + + function request( + rpcId: string, + mutationId: string, + method: 'orchestration.send' | 'orchestration.reply', + params: Record + ): RpcRequest { + return { + id: rpcId, + authToken: 'test-token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: mutationId + } + } + + function createReadyLocalWorker( + db: OrchestrationDb, + taskId: string, + workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + ) { + const started = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId, + startOptions: {} + }) + db.prepareStartingWorkerAuthority({ + dispatchId: started.dispatch.id, + handle: 'term_worker', + paneKey: workerPaneKey, + processIncarnation: 'runtime_test:term_worker:1', + worktreeId: 'repo::worker', + effects: [], + setupState: 'not_applicable' + }) + db.markWorkerDispatchReady(started.dispatch.id) + return { dispatch: db.getDispatchContextById(started.dispatch.id)! } + } + + async function throwAfterCommitAndReplay( + dispatcher: RpcDispatcher, + runtime: OrcaRuntimeService, + first: RpcRequest, + retryRpcId: string + ) { + vi.spyOn(runtime, 'notifyMessageArrived').mockImplementationOnce(() => { + throw new Error('injected notification failure') + }) + + const failed = await dispatcher.dispatch(first) + const replayed = await dispatcher.dispatch({ ...first, id: retryRpcId }) + + expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) + expect(replayed).toMatchObject({ + ok: true, + result: { mutation: { requestId: first.orchestrationRequestId, replayed: true } } + }) + return replayed as { result: Record } + } + + it('replays one question reply nudge without duplicating the answer', async () => { + const { db, runtime, activeRunId } = harness.setup() + if (!activeRunId) { + throw new Error('active Run missing') + } + const task = db.createTask({ spec: 'Ask once', runId: activeRunId }) + const { dispatch } = createReadyLocalWorker(db, task.id) + const question = db.createQuestion({ + runId: activeRunId, + dispatchId: dispatch.id, + askerHandle: 'term_worker', + question: 'Continue?' + }) + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + const waiting = runtime.waitForMessage(`dispatch:${dispatch.id}`, { timeoutMs: 5_000 }) + const replayed = await throwAfterCommitAndReplay( + dispatcher, + runtime, + request('rpc_question_reply', 'mutation_question_reply', 'orchestration.reply', { + id: question.message.id, + run: activeRunId, + body: 'Continue', + from: 'term_coord' + }), + 'rpc_question_reply_retry' + ) + + const answered = db.getQuestion(question.message.id) + expect(answered).toMatchObject({ status: 'answered', answer_body: 'Continue' }) + expect( + db.getInbox(100).filter((message) => message.thread_id === question.message.id) + ).toHaveLength(2) + expect(replayed.result).toMatchObject({ duplicate: false }) + await expect(waiting).resolves.toBeInstanceOf(MessageWake) + }) + + it('replays worker settlement without applying lifecycle state twice', async () => { + const { db, runtime, activeRunId } = harness.setup() + const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => + handle === 'term_worker' + ? workerPaneKey + : handle === 'term_coord' + ? harness.coordinatorPaneKey + : null + ) + const task = db.createTask({ spec: 'Settle once' }) + const { dispatch } = createReadyLocalWorker(db, task.id, workerPaneKey) + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + const workerDone = request('rpc_worker_done', 'mutation_worker_done', 'orchestration.send', { + from: 'term_worker', + subject: 'Done', + type: 'worker_done', + payload: JSON.stringify({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded' + }) + }) + const waiting = runtime.waitForMessage(`run:${activeRunId}`, { + typeFilter: ['worker_done'], + timeoutMs: 5_000 + }) + let waiterSettled = false + void waiting.then(() => { + waiterSettled = true + }) + vi.spyOn(runtime, 'notifyMessageArrived').mockImplementationOnce(() => { + throw new Error('injected notification failure') + }) + + const failed = await dispatcher.dispatch(workerDone) + await Promise.resolve() + expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) + expect(waiterSettled).toBe(false) + + const replayed = await dispatcher.dispatch({ ...workerDone, id: 'rpc_worker_done_retry' }) + + expect(db.getTask(task.id)?.status).toBe('completed') + expect(db.getDispatchContextById(dispatch.id)?.status).toBe('completed') + expect(db.getInbox(100).filter((message) => message.type === 'worker_done')).toHaveLength(1) + expect(replayed).toMatchObject({ + ok: true, + result: { + lifecycle: { action: 'completed' }, + mutation: { requestId: 'mutation_worker_done', replayed: true } + } + }) + await expect(waiting).resolves.toBeInstanceOf(MessageWake) + }) + + it.each([ + { + seam: 'lifecycle settlement', + inject(db: OrchestrationDb) { + vi.spyOn(db, 'settleWorkerReportInTransaction').mockImplementationOnce(() => { + throw new Error('injected settlement failure') + }) + } + }, + { + seam: 'mutation receipt', + inject(db: OrchestrationDb) { + vi.spyOn(db, 'completeMutationReceipt').mockImplementationOnce(() => { + throw new Error('injected receipt failure') + }) + } + } + ])('atomically rolls back worker_done when $seam fails', async ({ inject }) => { + const { db, runtime, activeRunId } = harness.setup() + const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + vi.mocked(runtime.getTerminalPaneKey).mockImplementation((handle) => + handle === 'term_worker' + ? workerPaneKey + : handle === 'term_coord' + ? harness.coordinatorPaneKey + : null + ) + const task = db.createTask({ spec: 'Commit report and settlement together' }) + const { dispatch } = createReadyLocalWorker(db, task.id, workerPaneKey) + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + const workerDone = request( + 'rpc_atomic_worker_done', + 'mutation_atomic_worker_done', + 'orchestration.send', + { + from: 'term_worker', + subject: 'Done atomically', + type: 'worker_done', + payload: JSON.stringify({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded' + }) + } + ) + const callerFingerprint = db.getOrCreateLocalMutationCallerFingerprint() + inject(db) + + const failed = await dispatcher.dispatch(workerDone) + + expect(failed).toMatchObject({ ok: false, error: { code: 'runtime_error' } }) + expect(db.getInbox(100).filter((message) => message.type === 'worker_done')).toHaveLength(0) + expect(db.getTask(task.id)?.status).toBe('dispatched') + expect( + db.getAttemptObservationFacts(dispatch.id).filter((fact) => fact.facet === 'worker_report') + ).toHaveLength(0) + expect(db.getMutationReceipt(callerFingerprint, 'mutation_atomic_worker_done')).toBeUndefined() + const run = db.getRun(activeRunId!)! + expect( + db.getOrCreateRunDelivery({ + runId: activeRunId!, + consumerGeneration: run.consumer_generation + }) + ).toBeUndefined() + + const retried = await dispatcher.dispatch({ ...workerDone, id: 'rpc_atomic_worker_done_retry' }) + + expect(retried).toMatchObject({ + ok: true, + result: { lifecycle: { action: 'completed' } } + }) + expect(db.getInbox(100).filter((message) => message.type === 'worker_done')).toHaveLength(1) + expect(db.getTask(task.id)?.status).toBe('completed') + expect(db.getDispatchContextById(dispatch.id)?.status).toBe('completed') + expect( + db.getAttemptObservationFacts(dispatch.id).filter((fact) => fact.facet === 'worker_report') + ).toHaveLength(1) + expect(db.getMutationReceipt(callerFingerprint, 'mutation_atomic_worker_done')?.state).toBe( + 'completed' + ) + }) +}) diff --git a/src/main/runtime/rpc/orchestration-mutation-executor.ts b/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-executor.ts similarity index 96% rename from src/main/runtime/rpc/orchestration-mutation-executor.ts rename to src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-executor.ts index a20faeb6649..c0cca984044 100644 --- a/src/main/runtime/rpc/orchestration-mutation-executor.ts +++ b/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-executor.ts @@ -1,11 +1,11 @@ import { isDurableMutation, isTerminalPromptMutation -} from '../../../shared/orchestration/orchestration-rpc-contract' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' -import { OrchestrationError } from '../orchestration/orchestration-error' -import type { RpcRequest } from './core' +} from '../../../../../shared/orchestration/orchestration-rpc-contract' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { OrchestrationEntryCaller } from '../../../orchestration/addressing/orchestration-caller-identity' +import { OrchestrationError } from '../../../orchestration/orchestration-error' +import type { RpcRequest } from '../../core' import { attachMutationReceipt, EFFECT_FREE_WORKER_DONE_CHECKPOINT, diff --git a/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts b/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts new file mode 100644 index 00000000000..1e0cb5b0326 --- /dev/null +++ b/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts @@ -0,0 +1,95 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { OrcaRuntimeService } from '../../../orca-runtime' +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest } from '../../core' +import { RpcDispatcher } from '../../dispatcher' +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' +import { createRootDispatch } from '../../../orchestration/db/root-dispatch-test-fixture' + +describe('durable orchestration mutation ledger', () => { + const paths: string[] = [] + + afterEach(() => { + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + }) + + it('recovers a lost ask acceptance without creating a second question', async () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-mutation-ask-recovery-')) + paths.push(dir) + const dbPath = join(dir, 'orchestration.db') + const db = new OrchestrationDb(dbPath) + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue('tab_worker:leaf_worker') + vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1') + vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) + vi.spyOn(runtime, 'waitForMessage').mockImplementation( + async (_address, options) => + await new Promise<'cancelled'>((resolve) => { + options?.signal?.addEventListener('abort', () => resolve('cancelled'), { once: true }) + }) + ) + const run = db.createRun({ + objective: 'Ask recovery', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:leaf_coord' + }) + const task = db.createTask({ spec: 'ask', runId: run.id }) + createRootDispatch( + db, + task.id, + 'term_worker', + 'tab_worker:leaf_worker', + undefined, + 'runtime:pty:1' + ) + const askRequest: RpcRequest = { + id: 'rpc_ask_1', + authToken: 'caller-token', + method: 'orchestration.ask', + params: { from: 'term_worker', question: 'Proceed?', timeoutMs: 60_000 }, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: 'mutation_ask' + } + const controller = new AbortController() + const firstDispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + const first = firstDispatcher.dispatch(askRequest, { signal: controller.signal }) + await vi.waitFor(() => expect(db.getInbox(10)).toHaveLength(1)) + + const restartedDb = new OrchestrationDb(dbPath) + const restartedRuntime = new OrcaRuntimeService() + restartedRuntime.setOrchestrationDb(restartedDb) + vi.spyOn(restartedRuntime, 'getTerminalPaneKey').mockReturnValue('tab_worker:leaf_worker') + vi.spyOn(restartedRuntime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1') + vi.spyOn(restartedRuntime, 'notifyMessageArrived').mockImplementation(() => {}) + const restartedDispatcher = new RpcDispatcher({ + runtime: restartedRuntime, + methods: ORCHESTRATION_METHODS + }) + const recovered = await restartedDispatcher.dispatch({ ...askRequest, id: 'rpc_ask_2' }) + expect(recovered).toMatchObject({ + ok: true, + result: { + accepted: true, + messageId: expect.stringMatching(/^msg_/), + mutation: { requestId: 'mutation_ask', replayed: true } + } + }) + expect(db.getInbox(10)).toHaveLength(1) + + controller.abort() + await first + restartedDb.close() + db.close() + }) +}) diff --git a/src/main/runtime/rpc/orchestration-mutation-receipt.ts b/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-receipt.ts similarity index 95% rename from src/main/runtime/rpc/orchestration-mutation-receipt.ts rename to src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-receipt.ts index ed20925ed9a..249af479969 100644 --- a/src/main/runtime/rpc/orchestration-mutation-receipt.ts +++ b/src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-receipt.ts @@ -1,8 +1,8 @@ import { createHash } from 'node:crypto' -import { isTerminalPromptMutation } from '../../../shared/orchestration/orchestration-rpc-contract' -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' +import { isTerminalPromptMutation } from '../../../../../shared/orchestration/orchestration-rpc-contract' +import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { OrchestrationEntryCaller } from '../../../orchestration/addressing/orchestration-caller-identity' export const EFFECT_FREE_WORKER_DONE_CHECKPOINT = JSON.stringify({ pending: { effectFree: 'worker_done' } diff --git a/src/main/runtime/rpc/orchestration-task-dispatch-invariant.test.ts b/src/main/runtime/rpc/orchestration/mutations/orchestration-task-dispatch-invariant.test.ts similarity index 88% rename from src/main/runtime/rpc/orchestration-task-dispatch-invariant.test.ts rename to src/main/runtime/rpc/orchestration/mutations/orchestration-task-dispatch-invariant.test.ts index e22fc77bb49..2190da5931b 100644 --- a/src/main/runtime/rpc/orchestration-task-dispatch-invariant.test.ts +++ b/src/main/runtime/rpc/orchestration/mutations/orchestration-task-dispatch-invariant.test.ts @@ -2,18 +2,18 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import Database from '../../sqlite/sync-database' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest, RpcResponse } from './core' -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { reattachDispatchConsumer } from '../orchestration/db/root-dispatch-test-fixture' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import Database from '../../../../sqlite/sync-database' +import { OrcaRuntimeService } from '../../../orca-runtime' +import { OrchestrationDb } from '../../../orchestration/db/orchestration-db' +import '../../../orchestration/db/contract-constants' +import '../../../orchestration/db/messages/mailbox-routing-page' +import '../../../orchestration/db/dispatch-row-writer' +import '../../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest, RpcResponse } from '../../core' +import { RpcDispatcher } from '../../dispatcher' +import { ORCHESTRATION_METHODS } from '../../methods/orchestration/orchestration' +import { reattachDispatchConsumer } from '../../../orchestration/db/root-dispatch-test-fixture' const COORDINATOR_HANDLE = 'term_invariant_coordinator' const COORDINATOR_PANE = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' diff --git a/src/main/runtime/rpc/relay-transport.test.ts b/src/main/runtime/rpc/relay-transport.test.ts deleted file mode 100644 index 6d6509f0a73..00000000000 --- a/src/main/runtime/rpc/relay-transport.test.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import WebSocketClient, { WebSocketServer, type WebSocket } from 'ws' -import { CloudRelayTransport } from './relay-transport' - -function nextMessage(ws: WebSocket): Promise<{ data: Buffer; isBinary: boolean }> { - return new Promise((resolve) => { - ws.once('message', (data, isBinary) => resolve({ data: Buffer.from(data as Buffer), isBinary })) - }) -} - -describe('CloudRelayTransport', () => { - const servers: WebSocketServer[] = [] - const transports: CloudRelayTransport[] = [] - - afterEach(async () => { - await Promise.all(transports.splice(0).map((transport) => transport.stop())) - await Promise.all( - servers.splice(0).map( - (server) => - new Promise((resolve) => { - for (const client of server.clients) { - client.terminate() - } - server.close(() => resolve()) - }) - ) - ) - }) - - it('authenticates one query-free host-data socket and forwards messages verbatim', async () => { - // Bind the exact loopback address clients dial; wildcard binds let another listener claim that address. - const server = new WebSocketServer({ host: '127.0.0.1', port: 0, perMessageDeflate: false }) - servers.push(server) - await new Promise((resolve) => server.once('listening', resolve)) - const address = server.address() - if (typeof address === 'string' || address === null) { - throw new Error('expected TCP relay test server') - } - const accepted = new Promise<{ socket: WebSocket; path: string }>((resolve) => { - server.once('connection', (socket, request) => resolve({ socket, path: request.url ?? '' })) - }) - let clientSocket: WebSocketClient | null = null - const onConnectionClosed = vi.fn() - const transport = new CloudRelayTransport({ - cellUrl: `http://127.0.0.1:${address.port}`, - relayHostId: 'AbCdEf0123_-xyZ9', - generation: 7, - createSocket: (url) => { - clientSocket = new WebSocketClient(url, { perMessageDeflate: false }) - return clientSocket - }, - onConnectionClosed - }) - transports.push(transport) - const received: (string | Uint8Array)[] = [] - transport.onMessage((message) => received.push(message)) - transport.onConnectionClose(vi.fn()) - await transport.start() - const opening = transport.openConnection({ - connId: 'conn/with spaces', - connTicket: 'ticket-1', - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 1_000 - }) - const { socket, path } = await accepted - const auth = await nextMessage(socket) - await opening - - expect(path).toBe('/v1/host/data/conn%2Fwith%20spaces') - expect(auth.isBinary).toBe(false) - expect(JSON.parse(auth.data.toString())).toEqual({ - type: 'host-data-auth', - v: 1, - connTicket: 'ticket-1', - generation: 7 - }) - socket.send('e2ee-hello') - socket.send(Buffer.from([1, 2, 3]), { binary: true }) - await vi.waitFor(() => expect(received).toHaveLength(2)) - expect(received[0]).toBe('e2ee-hello') - expect(received[1]).toEqual(new Uint8Array([1, 2, 3])) - - expect(clientSocket).not.toBeNull() - const metadata = transport.metadataFor(clientSocket!) - expect(metadata).toEqual({ - transport: 'relay', - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - basisConnId: 'conn/with spaces', - credentialKind: 'resume' - }) - socket.close() - await vi.waitFor(() => expect(onConnectionClosed).toHaveBeenCalledWith('conn/with spaces')) - }) - - it('stop() resolves after the close timeout when a socket never emits close', async () => { - vi.useFakeTimers() - try { - const listeners = new Map void)[]>() - const addListener = (event: string, fn: (...args: unknown[]) => void): void => { - const existing = listeners.get(event) ?? [] - existing.push(fn) - listeners.set(event, existing) - } - const removeListener = (event: string, fn: (...args: unknown[]) => void): void => { - listeners.set( - event, - (listeners.get(event) ?? []).filter((listener) => listener !== fn) - ) - } - const emit = (event: string, ...args: unknown[]): void => { - const eventListeners = listeners.get(event) ?? [] - if (event === 'error' && eventListeners.length === 0) { - throw args[0] - } - for (const fn of eventListeners) { - fn(...args) - } - } - // Model a post-sleep half-open socket whose terminate never emits close, formerly hanging stop forever. - const fakeSocket = { - readyState: 1, - OPEN: 1, - CLOSED: 3, - on: addListener, - once: addListener, - off: removeListener, - send: vi.fn(), - terminate: () => {} - } - const onConnectionClosed = vi.fn() - const transport = new CloudRelayTransport({ - cellUrl: 'http://127.0.0.1:9', - relayHostId: 'AbCdEf0123_-xyZ9', - generation: 1, - createSocket: () => fakeSocket as unknown as WebSocketClient, - onConnectionClosed - }) - let reply: ((response: string) => void) | null = null - const onMessage = vi.fn( - (_message: string | Uint8Array, respond: (response: string) => void) => { - reply = respond - } - ) - transport.onMessage(onMessage) - const opening = transport.openConnection({ - connId: 'conn-1', - connTicket: 'ticket-1', - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 1_000 - }) - emit('open') - await opening - vi.mocked(fakeSocket.send).mockClear() - emit('message', 'before-stop', false) - expect(onMessage).toHaveBeenCalledOnce() - - let stopped = false - const stopPromise = transport.stop().then(() => { - stopped = true - }) - emit('message', 'during-stop', false) - expect(onMessage).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(4_999) - expect(stopped).toBe(false) - await vi.advanceTimersByTimeAsync(1) - await stopPromise - expect(stopped).toBe(true) - expect(onConnectionClosed).toHaveBeenCalledWith('conn-1') - expect(() => transport.metadataFor(fakeSocket as unknown as WebSocketClient)).toThrow( - 'unknown_relay_socket' - ) - const onLateMessage = vi.fn() - transport.onMessage((_message, _reply, socket) => { - transport.metadataFor(socket) - onLateMessage() - }) - // After forced timeout cleanup, late native frames must not reach wiring with released metadata. - expect(() => emit('message', 'late-after-stop', false)).not.toThrow() - expect(onLateMessage).not.toHaveBeenCalled() - expect(reply).not.toBeNull() - await transport.start() - reply!('late-reply') - expect(fakeSocket.send).not.toHaveBeenCalled() - expect(() => emit('error', new Error('late socket failure'))).not.toThrow() - emit('close') - expect(listeners.get('error')).toHaveLength(0) - expect(listeners.get('close')).toHaveLength(0) - expect(vi.getTimerCount()).toBe(0) - expect(() => transport.setGeneration(2)).not.toThrow() - } finally { - vi.useRealTimers() - } - }) - - it('releases an expired attach even when terminate never emits close', async () => { - vi.useFakeTimers() - try { - const listeners = new Map void)[]>() - const addListener = (event: string, fn: (...args: unknown[]) => void): void => { - listeners.set(event, [...(listeners.get(event) ?? []), fn]) - } - const removeListener = (event: string, fn: (...args: unknown[]) => void): void => { - listeners.set( - event, - (listeners.get(event) ?? []).filter((listener) => listener !== fn) - ) - } - const emit = (event: string, ...args: unknown[]): void => { - const eventListeners = listeners.get(event) ?? [] - if (event === 'error' && eventListeners.length === 0) { - throw args[0] - } - for (const fn of eventListeners) { - fn(...args) - } - } - const fakeSocket = { - readyState: 0, - OPEN: 1, - CLOSED: 3, - on: addListener, - once: addListener, - off: removeListener, - send: vi.fn(), - terminate: vi.fn() - } - const onConnectionClosed = vi.fn() - const transport = new CloudRelayTransport({ - cellUrl: 'http://127.0.0.1:9', - relayHostId: 'AbCdEf0123_-xyZ9', - generation: 1, - createSocket: () => fakeSocket as unknown as WebSocketClient, - onConnectionClosed - }) - const opening = transport.openConnection({ - connId: 'conn-attach-timeout', - connTicket: 'ticket-1', - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 1_000 - }) - const rejectedOpening = expect(opening).rejects.toThrow('relay_host_data_attach_timeout') - - await vi.advanceTimersByTimeAsync(1_000) - - await rejectedOpening - expect(fakeSocket.terminate).toHaveBeenCalledOnce() - expect(onConnectionClosed).toHaveBeenCalledWith('conn-attach-timeout') - expect(() => transport.metadataFor(fakeSocket as unknown as WebSocketClient)).toThrow( - 'unknown_relay_socket' - ) - expect(() => transport.setGeneration(2)).not.toThrow() - expect(() => emit('message', 'late-after-attach-timeout', false)).not.toThrow() - expect(() => emit('error', new Error('late attach socket failure'))).not.toThrow() - emit('close') - expect(listeners.get('error')).toHaveLength(0) - expect(listeners.get('close')).toHaveLength(0) - } finally { - vi.useRealTimers() - } - }) - - it('bounds device termination cleanup and deduplicates its close waiter', async () => { - vi.useFakeTimers() - try { - const listeners = new Map void)[]>() - const addListener = (event: string, fn: (...args: unknown[]) => void): void => { - listeners.set(event, [...(listeners.get(event) ?? []), fn]) - } - const removeListener = (event: string, fn: (...args: unknown[]) => void): void => { - listeners.set( - event, - (listeners.get(event) ?? []).filter((listener) => listener !== fn) - ) - } - const emit = (event: string, ...args: unknown[]): void => { - for (const fn of listeners.get(event) ?? []) { - fn(...args) - } - } - const fakeSocket = { - readyState: 1, - OPEN: 1, - CLOSED: 3, - on: addListener, - once: addListener, - off: removeListener, - send: vi.fn(), - terminate: vi.fn() - } - const onConnectionClosed = vi.fn() - const transport = new CloudRelayTransport({ - cellUrl: 'http://127.0.0.1:9', - relayHostId: 'AbCdEf0123_-xyZ9', - generation: 1, - createSocket: () => fakeSocket as unknown as WebSocketClient, - onConnectionClosed - }) - transport.onMessage(() => {}) - const opening = transport.openConnection({ - connId: 'conn-device-termination', - connTicket: 'ticket-1', - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 10_000 - }) - emit('open') - await opening - emit('message', 'attached', false) - transport.setClientId(fakeSocket as unknown as WebSocketClient, 'client-1') - - expect(transport.terminateClientConnections('client-1')).toBe(1) - expect(transport.terminateClientConnections('client-1')).toBe(1) - expect(fakeSocket.terminate).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(1) - await vi.advanceTimersByTimeAsync(5_000) - - expect(onConnectionClosed).toHaveBeenCalledOnce() - expect(onConnectionClosed).toHaveBeenCalledWith('conn-device-termination') - expect(() => transport.metadataFor(fakeSocket as unknown as WebSocketClient)).toThrow( - 'unknown_relay_socket' - ) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/rpc/remote-runtime-server-heartbeat-missed-probe-tolerance.test.ts b/src/main/runtime/rpc/remote-runtime-server-heartbeat-missed-probe-tolerance.test.ts deleted file mode 100644 index d525ca6af92..00000000000 --- a/src/main/runtime/rpc/remote-runtime-server-heartbeat-missed-probe-tolerance.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { WebSocket } from 'ws' -import { RemoteRuntimeServerHeartbeat } from './remote-runtime-server-heartbeat' - -afterEach(() => { - vi.useRealTimers() -}) - -const INTERVAL_MS = 100 - -function makeSocket(): WebSocket { - return { ping: vi.fn(), terminate: vi.fn() } as unknown as WebSocket -} - -describe('RemoteRuntimeServerHeartbeat missed-probe tolerance', () => { - it('lets any proof of life reset accumulated misses', async () => { - vi.useFakeTimers() - let now = 1_000 - const socket = makeSocket() - const heartbeat = new RemoteRuntimeServerHeartbeat(INTERVAL_MS, () => now) - heartbeat.noteAlive(socket) - heartbeat.start(() => [socket]) - now += INTERVAL_MS - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - expect(socket.ping).toHaveBeenCalledTimes(1) - heartbeat.noteAlive(socket) - - // Two silent probes, then a single inbound frame, repeated well past any fixed budget. - for (let cycle = 0; cycle < 5; cycle += 1) { - now += INTERVAL_MS - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - now += INTERVAL_MS - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - heartbeat.noteAlive(socket) - } - - expect(socket.terminate).not.toHaveBeenCalled() - heartbeat.stop() - }) - - it('charges no miss for a paused tick but keeps the ones already banked', async () => { - vi.useFakeTimers() - let now = 1_000 - const socket = makeSocket() - const heartbeat = new RemoteRuntimeServerHeartbeat(INTERVAL_MS, () => now) - heartbeat.noteAlive(socket) - heartbeat.start(() => [socket]) - heartbeat.noteAlive(socket) - - const sweep = async (): Promise => { - now += INTERVAL_MS - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - } - const reaped = (candidate: WebSocket): boolean => - (candidate.terminate as unknown as ReturnType).mock.calls.length > 0 - - // Discover the miss budget; the first sweep consumes the existing pong. - await sweep() - let toleratedMisses = 0 - // Bound discovery so a broken reaper fails here instead of timing out. - while (!reaped(socket) && toleratedMisses < 20) { - await sweep() - toleratedMisses += 1 - } - expect(reaped(socket)).toBe(true) - expect(toleratedMisses).toBeGreaterThan(1) - heartbeat.stop() - - // Bank misses before suspend: the delayed tick must neither charge an unanswerable probe nor erase prior silence. - const resumed = new RemoteRuntimeServerHeartbeat(INTERVAL_MS, () => now) - const resumedSocket = makeSocket() - resumed.noteAlive(resumedSocket) - resumed.start(() => [resumedSocket]) - resumed.noteAlive(resumedSocket) - await sweep() - for (let miss = 0; miss < toleratedMisses - 1; miss += 1) { - await sweep() - } - expect(reaped(resumedSocket)).toBe(false) - - now += 3_600_000 - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - expect(reaped(resumedSocket)).toBe(false) - - await sweep() - expect(reaped(resumedSocket)).toBe(true) - resumed.stop() - }) - - // Clearing banked misses on stall formerly sheltered dead sockets forever. - it('still reaps a dead socket when the host stalls repeatedly', async () => { - vi.useFakeTimers() - let now = 1_000 - const socket = makeSocket() - const heartbeat = new RemoteRuntimeServerHeartbeat(INTERVAL_MS, () => now) - heartbeat.noteAlive(socket) - heartbeat.start(() => [socket]) - heartbeat.noteAlive(socket) - - const reaped = (): boolean => - (socket.terminate as unknown as ReturnType).mock.calls.length > 0 - - // Stall every third tick to reproduce the old perpetual pardon. - for (let tick = 0; tick < 30 && !reaped(); tick += 1) { - now += tick % 3 === 2 ? INTERVAL_MS * 2 : INTERVAL_MS - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - } - - expect(reaped()).toBe(true) - heartbeat.stop() - }) -}) diff --git a/src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts b/src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts deleted file mode 100644 index 9570b4f2d9a..00000000000 --- a/src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { WebSocket } from 'ws' -import { RemoteRuntimeServerHeartbeat } from './remote-runtime-server-heartbeat' -import { setActiveSink } from '../../observability/tracer' - -afterEach(() => { - setActiveSink(null) - vi.useRealTimers() -}) - -describe('RemoteRuntimeServerHeartbeat', () => { - it('defers the first probe until after the WebSocket handshake window', async () => { - vi.useFakeTimers() - const socket = { ping: vi.fn(), terminate: vi.fn() } as unknown as WebSocket - const heartbeat = new RemoteRuntimeServerHeartbeat(100) - heartbeat.noteAlive(socket) - heartbeat.start(() => [socket]) - - expect(socket.ping).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(100) - expect(socket.ping).toHaveBeenCalledTimes(1) - heartbeat.stop() - }) - - it('still reaps a persistently silent client while another remains alive', async () => { - vi.useFakeTimers() - let now = 1_000 - const responsiveSocket = { ping: vi.fn(), terminate: vi.fn() } as unknown as WebSocket - const deadSocket = { ping: vi.fn(), terminate: vi.fn() } as unknown as WebSocket - // Limit of 2 keeps the sweep count readable; production uses the module default. - const heartbeat = new RemoteRuntimeServerHeartbeat(100, () => now, 128, 2) - heartbeat.noteAlive(responsiveSocket) - heartbeat.noteAlive(deadSocket) - heartbeat.start(() => [responsiveSocket, deadSocket]) - expect(responsiveSocket.ping).not.toHaveBeenCalled() - expect(deadSocket.ping).not.toHaveBeenCalled() - - now += 100 - await vi.advanceTimersByTimeAsync(100) - heartbeat.noteAlive(responsiveSocket) - - // First miss re-probes without reaping. - now += 100 - await vi.advanceTimersByTimeAsync(100) - heartbeat.noteAlive(responsiveSocket) - expect(deadSocket.ping).toHaveBeenCalledTimes(2) - expect(deadSocket.terminate).not.toHaveBeenCalled() - - // Consecutive silence reaches the configured limit. - now += 100 - await vi.advanceTimersByTimeAsync(100) - - expect(responsiveSocket.ping).toHaveBeenCalledTimes(3) - expect(responsiveSocket.terminate).not.toHaveBeenCalled() - expect(deadSocket.ping).toHaveBeenCalledTimes(2) - expect(deadSocket.terminate).toHaveBeenCalledTimes(1) - heartbeat.stop() - }) - - it('grants clients a fresh probe after the server event loop resumes', async () => { - vi.useFakeTimers() - let now = 1_000 - const socket = { ping: vi.fn(), terminate: vi.fn() } as unknown as WebSocket - // Limit of 1 isolates the resume grant: without it the very next sweep would reap. - const heartbeat = new RemoteRuntimeServerHeartbeat(100, () => now, 128, 1) - heartbeat.noteAlive(socket) - heartbeat.start(() => [socket]) - now += 100 - await vi.advanceTimersByTimeAsync(100) - heartbeat.noteAlive(socket) - - now += 100 - await vi.advanceTimersByTimeAsync(100) - heartbeat.noteAlive(socket) - now += 3_600_000 - await vi.advanceTimersByTimeAsync(100) - - expect(socket.ping).toHaveBeenCalledTimes(3) - expect(socket.terminate).not.toHaveBeenCalled() - - now += 100 - await vi.advanceTimersByTimeAsync(100) - expect(socket.terminate).toHaveBeenCalledTimes(1) - heartbeat.stop() - }) - - it('writes a trace span for each reap with the socket uptime and last round trip', async () => { - vi.useFakeTimers() - const records: unknown[] = [] - setActiveSink({ push: (record) => records.push(record), flush() {}, close() {} }) - let now = 1_000 - // SAFETY: the heartbeat only calls ping() and terminate() on its sockets. - const socket = { ping: vi.fn(), terminate: vi.fn() } as unknown as WebSocket - const heartbeat = new RemoteRuntimeServerHeartbeat(100, () => now, 128, 1) - heartbeat.track(socket) - heartbeat.noteAlive(socket) - heartbeat.start(() => [socket]) - now += 100 - await vi.advanceTimersByTimeAsync(100) - now += 40 - heartbeat.notePong(socket) - - now += 60 - await vi.advanceTimersByTimeAsync(100) - now += 100 - await vi.advanceTimersByTimeAsync(100) - - expect(socket.terminate).toHaveBeenCalledTimes(1) - expect(records).toEqual([ - expect.objectContaining({ - name: 'remote-runtime.server-socket-reaped', - attributes: expect.objectContaining({ - cause: 'heartbeat_missed_probes', - lastRttMs: 40, - socketUptimeMs: 300, - trackedSockets: 1 - }) - }) - ]) - heartbeat.stop() - }) -}) diff --git a/src/main/runtime/rpc/repo-add-cli.integration.test.ts b/src/main/runtime/rpc/repo-add-cli.integration.test.ts deleted file mode 100644 index 7df22e21d50..00000000000 --- a/src/main/runtime/rpc/repo-add-cli.integration.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { runProcessSync } from '@orca/process-host' -import { expect, it, vi } from 'vitest' -import { z } from 'zod' -import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' -import { getRuntimeMetadataPath } from '../../../shared/runtime-bootstrap' -import type { Repo } from '../../../shared/repo-types' -import { RuntimeRepositoryRegistrationController } from '../repositories/runtime-repository-registration-controller' -import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' -import type { RpcRequest } from './core' -import { repoDispatcher } from './methods/projects/repo-rpc.test-fixture' -import { UnixSocketTransport } from './unix-socket-transport' -import { acquire, release } from '../../github/gh-utils' -import { RuntimeRepositoryForkBackfill } from '../repositories/runtime-repository-fork-backfill' - -vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ - prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) -})) - -vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ - ghExecFileAsync: vi.fn(async () => ({ stdout: '{"isFork":false}' })) -})) - -const cliPath = '../../../cli/index' -const { main }: { main: (argv: string[], cwd: string) => Promise } = await import(cliPath) -const repoReply = z.object({ - result: z.object({ repo: z.object({ id: z.string(), path: z.string(), kind: z.string() }) }) -}) - -it('opens a repo-tool root through the CLI folder route and keeps subproject Git registration', async () => { - const root = await realpath(await mkdtemp(join(tmpdir(), 'orca-repo-cli-'))) - const tree = join(root, 'repo tree') - const project = join(tree, 'project') - const repos: Repo[] = [] - const store = partialRuntimeStore({ - getRepos: () => repos, - getRepo: (id) => repos.find((repo) => repo.id === id), - addRepo: (repo) => repos.push(repo) - }) - const controller = new RuntimeRepositoryRegistrationController({ - getStore: () => store, - invalidateResolvedWorktrees: () => {}, - invalidateWorktreeScan: () => {}, - notifyReposChanged: () => {} - }) - const metadata = new RuntimeRepositoryForkBackfill( - () => store, - () => {} - ) - let background = Promise.resolve() - let heldSlots = 0 - const dispatcher = repoDispatcher({ - getRuntimeId: () => 'repo-cli-test', - addRepo: async (...args) => { - const repo = await controller.add(...args) - background = metadata.enqueue([repo]) - return repo - }, - listVisibleRepos: () => repos, - requireStore: () => store - }) - const kind = process.platform === 'win32' ? 'named-pipe' : 'unix' - const endpoint = - process.platform === 'win32' - ? String.raw`\\.\pipe\orca-repo-cli-${randomUUID()}` - : join(root, 'rpc.sock') - const socket = new UnixSocketTransport({ kind, endpoint }) - const requests: RpcRequest[] = [] - socket.onMessage((message, reply) => { - const request: RpcRequest = JSON.parse(message) - requests.push(request) - void dispatcher.dispatch(request).then((response) => reply(JSON.stringify(response))) - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) - const previousExitCode = process.exitCode - const cli = async (args: string[]) => { - log.mockClear() - errors.mockClear() - process.exitCode = 0 - await main([...args, '--json'], root) - return JSON.parse([...log.mock.calls, ...errors.mock.calls].flat().join('\n')) - } - try { - await mkdir(join(tree, '.repo', 'manifests'), { recursive: true }) - await mkdir(project) - await writeFile(join(tree, '.repo', 'manifest.xml'), '') - for (const path of [project, join(tree, '.repo', 'manifests')]) { - const git = runProcessSync({ program: 'git', args: ['init', '-q', path] }) - expect(git.code, git.stderr).toBe(0) - } - const remote = runProcessSync({ - program: 'git', - args: ['-C', project, 'remote', 'add', 'origin', 'https://github.com/me/widget.git'] - }) - expect(remote.code, remote.stderr).toBe(0) - await socket.start() - await writeFile( - getRuntimeMetadataPath(root), - JSON.stringify({ - runtimeId: 'repo-cli-test', - pid: process.pid, - transports: [{ kind, endpoint }], - authToken: 'test', - startedAt: 1 - }) - ) - vi.stubEnv('ORCA_USER_DATA_PATH', root) - vi.stubEnv('ORCA_PAIRING_CODE', '') - vi.stubEnv('ORCA_REMOTE_PAIRING', '') - vi.stubEnv('ORCA_ENVIRONMENT', '') - - const refusal = await cli(['repo', 'add', '--path', tree]) - expect(refusal).toMatchObject({ - ok: false, - error: { - message: `Not a valid git repository: ${tree}`, - data: { nextSteps: [expect.stringContaining('--kind folder')] } - } - }) - expect(repos).toHaveLength(0) - expect(requests.at(-1)?.params).toEqual({ path: tree }) - - const command = ['repo', 'add', '--path', './repo tree', '--kind', 'folder'] - const first = repoReply.parse(await cli(command)).result.repo - expect(first).toMatchObject({ path: tree, kind: 'folder' }) - const repeated = repoReply.parse(await cli(command)).result.repo - expect(repeated.id).toBe(first.id) - expect(repos).toHaveLength(1) - expect(await cli(['repo', 'list'])).toMatchObject({ result: { repos: [first] } }) - - for (let slot = 0; slot < 4; slot++) { - await acquire() - heldSlots++ - } - const subproject = repoReply.parse( - await cli(['repo', 'add', '--path', project, '--kind', 'git']) - ).result.repo - // Windows Git registration stores the resolved root with forward slashes. - expect(normalizeRuntimePathForComparison(subproject.path)).toBe( - normalizeRuntimePathForComparison(project) - ) - expect(subproject.kind).toBe('git') - expect(await cli(['repo', 'list'])).toMatchObject({ - result: { - repos: [ - expect.objectContaining({ id: first.id }), - expect.objectContaining({ id: subproject.id }) - ] - } - }) - while (heldSlots > 0) { - release() - heldSlots-- - } - await background - expect(repos).toHaveLength(2) - - const beforeInvalid = requests.length - expect(await cli(['repo', 'add', '--path', tree, '--kind', 'repo-tool'])).toMatchObject({ - ok: false, - error: { code: 'invalid_argument' } - }) - expect(requests).toHaveLength(beforeInvalid) - expect(repos).toHaveLength(2) - } finally { - while (heldSlots > 0) { - release() - heldSlots-- - } - await background - await socket.stop() - vi.unstubAllEnvs() - process.exitCode = previousExitCode - log.mockRestore() - errors.mockRestore() - await rm(root, { recursive: true, force: true }) - } -}) diff --git a/src/main/runtime/rpc/responses/browser-error-response.ts b/src/main/runtime/rpc/responses/browser-error-response.ts new file mode 100644 index 00000000000..94ac671964e --- /dev/null +++ b/src/main/runtime/rpc/responses/browser-error-response.ts @@ -0,0 +1,12 @@ +import { BrowserError } from '../../../browser/browser-error' +import type { RpcEnvelopeMeta, RpcFailure } from '../core' +import { errorResponse, mapRuntimeError } from './rpc-response' + +// BrowserError.code uses the browser namespace, separate from the runtime message-code allowlist. +export function mapBrowserError(id: string, meta: RpcEnvelopeMeta, error: unknown): RpcFailure { + if (error instanceof Error && 'code' in error && typeof error.code === 'string') { + const data = error instanceof BrowserError ? error.data : undefined + return errorResponse(id, meta, error.code, error.message, data) + } + return mapRuntimeError(id, meta, error) +} diff --git a/src/main/runtime/rpc/dispatcher-error-response.ts b/src/main/runtime/rpc/responses/dispatcher-error-response.ts similarity index 83% rename from src/main/runtime/rpc/dispatcher-error-response.ts rename to src/main/runtime/rpc/responses/dispatcher-error-response.ts index 0ce216dc096..dd8e87f2b77 100644 --- a/src/main/runtime/rpc/dispatcher-error-response.ts +++ b/src/main/runtime/rpc/responses/dispatcher-error-response.ts @@ -1,4 +1,4 @@ -import { BranchSwitchLandedWithWarningError } from '../../git/worktrees/checkout/branch-switch' +import { BranchSwitchLandedWithWarningError } from '../../../git/worktrees/checkout/branch-switch' import { mapBrowserError } from './browser-error-response' import { ZodError } from 'zod' import { @@ -7,11 +7,11 @@ import { type RpcEnvelopeMeta, type RpcRequest, type RpcResponse -} from './core' +} from '../core' -import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery' -import { errorResponse, mapEmulatorError, mapRuntimeError } from './errors' -import { PluginHookDeniedError } from '../../plugins/hooks/plugin-hook-dispatch' +import { computerUseErrorRecoveryData } from '../../../../shared/computer-use-error-recovery' +import { errorResponse, mapEmulatorError, mapRuntimeError } from './rpc-response' +import { PluginHookDeniedError } from '../../../plugins/hooks/plugin-hook-dispatch' export function invalidArgumentResponse( request: RpcRequest, diff --git a/src/main/runtime/rpc/responses/rpc-response.ts b/src/main/runtime/rpc/responses/rpc-response.ts new file mode 100644 index 00000000000..46da6895962 --- /dev/null +++ b/src/main/runtime/rpc/responses/rpc-response.ts @@ -0,0 +1,319 @@ +import { BranchSwitchCollisionError } from '../../../git/worktrees/checkout/branch-switch-target' +import { SparsePresetValidationError } from '../../../../shared/worktree/creation/sparse-preset-failure' +import { + RECIPE_VM_REFUSAL_CODES, + RecipeVmWakeUnavailableError +} from '../../../../shared/remote-runtime/recipe-vm-wake' +import { RecipeWorkspaceRemovalError } from '../../../../shared/recipe-host-removal' +import { formatTerminalStartFailure } from '../../../../shared/terminal/pty/lifecycle/terminal-start-failure' +// Centralize the runtimeId envelope and error-code contracts that clients use for decisions and display. +import { AGENT_LAUNCH_SURFACE_UNAVAILABLE_CODE } from '../../../../shared/agent-launch/contracts/agent-launch-surface' +import { + agentSessionRefusalReference, + isAgentSessionRefusalError, + type AgentSessionRefusalError +} from '../../../../shared/agent-session/failures/agent-session-wire-refusals' +import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from '../core' +import { CONNECTOR_REPLY_ERROR_CODES } from '../../../../shared/rpc-contract/connectors/connector-params' +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES } from '../../../../shared/orchestration/orchestration-session-caller-codes' +import { ORCHESTRATION_FEDERATION_ERROR_CODES } from '../../../../shared/orchestration/orchestration-federation-error-codes' +import { computerUseErrorRecoveryData } from '../../../../shared/computer-use-error-recovery' +import { COMPUTER_ERROR_CODES } from '../../../../shared/computer-use-runtime-types' +import { TerminalSplitOutcomeError } from '../../../../shared/workspace-layout/terminal-topology/terminal-split-outcome' +import { WslHostWindowsDriveRefusalError } from '../../../../shared/wsl-host-windows-drive-refusal' +import { wslDistroHoldRpcFailure } from '../../../../shared/wsl-distro-stopped-hold' +import { LINEAR_ERROR_CODES } from '../../../../shared/linear/agent-access' +import { AGENT_SESSION_RPC_ERROR_CODES } from '../../../../shared/agent-session/agent-session-host-authority' +import { ARTIFACT_SHARING_DISABLED_CODE } from '../../../../shared/artifacts/artifact-sharing-gate' +import { AGENT_SKILL_SHARING_DISABLED_CODE } from '../../../../shared/agent-skill-sharing-gate' +import { SHARING_UNAVAILABLE_ON_HOST_CODE } from '../../../../shared/sharing-unavailable-on-host' +import { + AGENT_SKILL_NOT_SHAREABLE_CODE, + AGENT_SKILL_SELECTOR_AMBIGUOUS_CODE, + AGENT_SKILL_SELECTOR_NOT_FOUND_CODE, + AGENT_SKILL_SHARING_BUSY_CODE, + AGENT_SKILL_BUNDLE_NAME_TAKEN_CODE, + AGENT_SKILL_SHARING_UNSUPPORTED_ENVIRONMENT_CODE +} from '../../../../shared/agent-skill-sharing-contract' +import { + SKILL_INSTALL_RPC_ERROR_CODE, + classifySkillInstallFailureCode +} from '../../../../shared/skill-install-failure' +import { PLUGIN_CLI_ERROR_CODES } from '../../../../shared/plugins/approval/plugin-cli-approval' +import { GIT_DIFF_TOO_LARGE_CODE } from '../../../../shared/git/diff/git-diff-transport-budget' +import { AUTOMATION_OWNER_CONFLICT_CODES } from '../../../../shared/automations/ownership/automation-owner-conflict' +import { ARCHIVE_HOOK_FAILED_REMOVAL_CODE } from '../../../../shared/worktree/removal/archive-hook-removal-gate' +import { NESTED_WORKER_DEPTH_EXCEEDED_CODE } from '../../../../shared/orchestration/workers/nested-worker-depth' +import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../../shared/project-runtime-repair-message' +import { + WORKTREE_CREATE_COLLISION_CODE, + WORKTREE_CREATE_EXACT_NAME_TAKEN_CODE +} from '../../../../shared/new-workspace/worktree-create-collision' +import { AGENT_LAUNCH_PANE_ALREADY_LIVE_CODE } from '../../../../shared/agent-launch/contracts/agent-launch-pane-already-live' +import { AGENT_LAUNCH_SESSION_ALREADY_EXISTS_CODE } from '../../../../shared/agent-launch/contracts/agent-launch-session-already-exists' +import { AGENT_LAUNCH_TAB_CLOSED_CODE } from '../../../../shared/agent-launch/contracts/agent-launch-tab-closed' +import { AGENT_LAUNCH_TARGET_FORBIDDEN_CODE } from '../../../../shared/agent-launch/contracts/agent-launch-target-forbidden' +import { + parseTerminalSpawnDeferral, + TERMINAL_SPAWN_DEFERRED_CODE +} from '../../../../shared/terminal/pty/admission/spawn-admission-contract' + +export function successResponse(id: string, meta: RpcEnvelopeMeta, result: unknown): RpcSuccess { + return { id, ok: true, result, _meta: meta } +} + +export function errorResponse( + id: string, + meta: RpcEnvelopeMeta, + code: string, + message: string, + data?: unknown +): RpcFailure { + return { + id, + ok: false, + error: data === undefined ? { code, message } : { code, message, data }, + _meta: meta + } +} + +// Runtime plain Error messages are stable codes; changing this allowlist also requires updating the CLI. +const RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ + WORKTREE_CREATE_COLLISION_CODE, + AGENT_LAUNCH_PANE_ALREADY_LIVE_CODE, + AGENT_LAUNCH_SESSION_ALREADY_EXISTS_CODE, + AGENT_LAUNCH_TAB_CLOSED_CODE, + AGENT_LAUNCH_TARGET_FORBIDDEN_CODE, + 'agent_launch_replay_unsupported', + 'runtime_unavailable', + 'chat_fork_source_unavailable', + 'chat_fork_runtime_incompatible', + 'chat_fork_anchor_changed', + 'selector_not_found', + 'selector_ambiguous', + 'terminal_handle_stale', + 'terminal_not_writable', + 'terminal_exited', + 'terminal_gone', + 'terminal_tab_close_timeout', + 'terminal_tab_not_found', + 'terminal_tab_pinned', + 'agent_prompt_blocked', + 'agent_prompt_stalled', + 'no_active_terminal', + 'repo_not_found', + 'timeout', + 'invalid_limit', + 'request_aborted', + 'remote_update_manual_required', + 'remote_update_not_available', + 'remote_update_not_downloaded', + 'connectors_disabled', + 'external_conversation_not_found', + ...CONNECTOR_REPLY_ERROR_CODES, + ...AGENT_SESSION_RPC_ERROR_CODES +]) + +const COMPUTER_PASSTHROUGH_CODES: ReadonlySet = new Set(Object.values(COMPUTER_ERROR_CODES)) +const LINEAR_PASSTHROUGH_CODES: ReadonlySet = new Set(LINEAR_ERROR_CODES) +const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ + ...RECIPE_VM_REFUSAL_CODES, + WORKTREE_CREATE_COLLISION_CODE, + WORKTREE_CREATE_EXACT_NAME_TAKEN_CODE, + AGENT_LAUNCH_SURFACE_UNAVAILABLE_CODE, + 'worktree_id_requires_full_path', + // A workspace selector's choices ride in data; a plain Error('selector_ambiguous') keeps the bare code. + 'selector_ambiguous', + 'run_not_found', + 'run_home_unreachable', + 'run_required', + 'stable_pane_required', + 'consumer_fenced', + 'task_not_found', + 'task_not_startable', + 'inject_rejected', + 'dispatch_not_found', + 'dispatch_run_mismatch', + 'task_run_mismatch', + 'terminal_not_found', + // This live agent session never had a terminal; terminal_handle_stale would falsely imply one died. + 'terminal_unsupported_for_agent_session', + 'recipient_ambiguous', + 'recipient_run_mismatch', + 'dispatch_inactive', + // Its start failed before an agent ran, so there is no output to read. + 'worker_never_started', + 'worker_identity_changed', + 'cursor_invalid', + 'cursor_dispatch_mismatch', + 'source_changed', + 'transcript_required', + // A released worker's original transcript or chat is gone, or it never had one. + 'archive_unavailable', + ...ORCHESTRATION_FEDERATION_ERROR_CODES, + 'dispatch_capability_invalid', + 'agent_unconfigured', + 'worker_prompt_too_large', + 'terminal_worktree_mismatch', + 'terminal_is_coordinator', + // Another open Dispatch holds the terminal; data names it and says no effects were applied. + 'terminal_busy', + // The user chose Keep open; only they can undo it, so a coordinator must not retry blindly. + 'terminal_kept_open', + 'worker_cannot_coordinate_own_run', + 'worker_cannot_take_over_run', + 'request_mismatch', + 'mutation_ledger_full', + 'legacy_read_only', + 'orchestration_migration_required', + 'operation_unknown', + // A re-made pairing: work through the earlier one is not recovered, so the caller is told plainly. + 'server_pairing_changed', + 'dispatch_preamble_undelivered', + 'question_not_found', + 'answer_conflict', + // A worker's permission prompt: only a person allows; Orca answers chat prompts only, while open. + 'approval_requires_person', + 'approval_not_open', + 'approval_option_missing', + 'approval_refused', + 'stale_delivery', + 'invalid_argument', + // Preserve archive-hook failure so callers can retry, waive or skip it (#19334). + ARCHIVE_HOOK_FAILED_REMOVAL_CODE, + // Paired-only method refusal must match the mobile transport allowlist's forbidden code. + 'forbidden', + NESTED_WORKER_DEPTH_EXCEEDED_CODE, + PROJECT_RUNTIME_REPAIR_REQUIRED_CODE, + GIT_DIFF_TOO_LARGE_CODE, + ARTIFACT_SHARING_DISABLED_CODE, + AGENT_SKILL_SHARING_DISABLED_CODE, + SHARING_UNAVAILABLE_ON_HOST_CODE, + AGENT_SKILL_NOT_SHAREABLE_CODE, + AGENT_SKILL_SELECTOR_AMBIGUOUS_CODE, + AGENT_SKILL_SELECTOR_NOT_FOUND_CODE, + AGENT_SKILL_SHARING_BUSY_CODE, + AGENT_SKILL_BUNDLE_NAME_TAKEN_CODE, + AGENT_SKILL_SHARING_UNSUPPORTED_ENVIRONMENT_CODE, + SKILL_INSTALL_RPC_ERROR_CODE, + ...PLUGIN_CLI_ERROR_CODES, + // Keep owner conflicts distinct so clients can choose reload, re-adopt or stop offering the action. + ...Object.values(AUTOMATION_OWNER_CONFLICT_CODES), + ...Object.values(ORCHESTRATION_SESSION_CALLER_ERROR_CODES) +]) + +export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknown): RpcFailure { + const message = error instanceof Error ? error.message : String(error) + if (isAgentSessionRefusalError(error)) { + return agentSessionRefusalErrorResponse(id, meta, error) + } + // A recipe workspace removal keeps its environment's own code (archive hook, PTY stop, selector). + if ( + error instanceof RecipeVmWakeUnavailableError || + error instanceof RecipeWorkspaceRemovalError + ) { + return errorResponse(id, meta, error.code, message, 'data' in error ? error.data : undefined) + } + if ( + error instanceof BranchSwitchCollisionError || + error instanceof TerminalSplitOutcomeError || + error instanceof SparsePresetValidationError || + error instanceof WslHostWindowsDriveRefusalError + ) { + // Keep the existing RPC code while preserving structured details. + return errorResponse(id, meta, 'runtime_error', message, error.data) + } + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' && + COMPUTER_PASSTHROUGH_CODES.has((error as { code: string }).code) + ) { + const code = (error as { code: string }).code + return errorResponse(id, meta, code, message, computerUseErrorRecoveryData(code, message)) + } + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' && + (error as { code: string }).code.startsWith('LINEAGE_') + ) { + return errorResponse( + id, + meta, + (error as { code: string }).code, + message, + (error as { data?: unknown }).data + ) + } + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' && + (LINEAR_PASSTHROUGH_CODES.has((error as { code: string }).code) || + STRUCTURED_RUNTIME_PASSTHROUGH_CODES.has((error as { code: string }).code)) + ) { + return errorResponse( + id, + meta, + (error as { code: string }).code, + message, + (error as { data?: unknown }).data + ) + } + if (RUNTIME_PASSTHROUGH_CODES.has(message)) { + return errorResponse(id, meta, message, formatTerminalStartFailure(error) ?? message) + } + const deferral = parseTerminalSpawnDeferral(message) + if (deferral) { + // Why: only a caller that sent spawnIntent can be deferred, so the code is new to no client. + return errorResponse(id, meta, TERMINAL_SPAWN_DEFERRED_CODE, message, { reason: deferral }) + } + const skillInstallFailure = classifySkillInstallFailureCode(message) + if (skillInstallFailure) { + return errorResponse( + id, + meta, + SKILL_INSTALL_RPC_ERROR_CODE, + skillInstallFailure.code, + skillInstallFailure + ) + } + // Same code older clients match; people read the sentence, programs the hold in `data`. + const held = wslDistroHoldRpcFailure(message) + if (held) { + return errorResponse(id, meta, 'runtime_error', held.message, held.data) + } + if (message === 'invalid_terminal_send') { + return errorResponse(id, meta, 'invalid_argument', 'Missing terminal send payload') + } + return errorResponse(id, meta, 'runtime_error', formatTerminalStartFailure(error) ?? message) +} + +/** Map agent-session refusals before generic code passthrough; preserve released clients' exact code/message and add ignored details only in data. */ +function agentSessionRefusalErrorResponse( + id: string, + meta: RpcEnvelopeMeta, + error: AgentSessionRefusalError +): RpcFailure { + const { code } = error.refusal + return errorResponse( + id, + meta, + RUNTIME_PASSTHROUGH_CODES.has(code) ? code : 'runtime_error', + code, + { refusal: agentSessionRefusalReference(error.refusal) } + ) +} + +// EmulatorError.code likewise uses its own namespace rather than generic runtime_error. +export function mapEmulatorError(id: string, meta: RpcEnvelopeMeta, error: unknown): RpcFailure { + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' + ) { + return errorResponse(id, meta, (error as { code: string }).code, error.message) + } + return mapRuntimeError(id, meta, error) +} diff --git a/src/main/runtime/rpc/rpc-active-caller.ts b/src/main/runtime/rpc/rpc-active-caller.ts deleted file mode 100644 index 975ec4fbdcc..00000000000 --- a/src/main/runtime/rpc/rpc-active-caller.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { AsyncLocalStorage } from 'node:async_hooks' -import { isOrcaSessionId } from '../../../shared/orca-session-address' -import { isAgentRpcCaller, type RpcCallerIdentity } from './rpc-caller-identity' - -type ActiveRpcCall = { - caller: RpcCallerIdentity | undefined - agentSessionId: string | undefined -} - -// Lets code far below a handler tell an agent's CLI call from a person's relayed input. -const activeCall = new AsyncLocalStorage() - -export function runWithActiveRpcCaller( - caller: RpcCallerIdentity | undefined, - run: () => T, - claimedAgentSessionId?: string -): T { - // Only this host's CLI can name a chat here; as in the handoff card, other callers act for a person. - const agentSessionId = - isAgentRpcCaller(caller) && claimedAgentSessionId && isOrcaSessionId(claimedAgentSessionId) - ? claimedAgentSessionId - : undefined - return activeCall.run({ caller, agentSessionId }, run) -} - -/** The caller of the RPC handler this code runs under; undefined outside any handler. */ -export function getActiveRpcCaller(): RpcCallerIdentity | undefined { - return activeCall.getStore()?.caller -} - -/** The chat whose agent sent this call, as its CLI claims it: display attribution, never authority. */ -export function getActiveRpcAgentSessionId(): string | undefined { - return activeCall.getStore()?.agentSessionId -} - -/** Re-enters this call later, for work a queue runs from inside another caller's call. */ -export function captureActiveRpcCall(): (run: () => T) => T { - const call = activeCall.getStore() - return (run) => (call ? activeCall.run(call, run) : activeCall.exit(run)) -} diff --git a/src/main/runtime/rpc/runtime-client-capabilities.test.ts b/src/main/runtime/rpc/runtime-client-capabilities.test.ts deleted file mode 100644 index 54449bff237..00000000000 --- a/src/main/runtime/rpc/runtime-client-capabilities.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseRuntimeClientCapabilities } from './runtime-client-capabilities' - -describe('parseRuntimeClientCapabilities', () => { - it('accepts a bounded string array', () => { - expect(parseRuntimeClientCapabilities(['session-tabs.close-intent.v1', 'future.v1'])).toEqual([ - 'session-tabs.close-intent.v1', - 'future.v1' - ]) - const boundary = Array.from({ length: 64 }, () => 'x'.repeat(128)) - expect(parseRuntimeClientCapabilities(boundary)).toEqual(boundary) - }) - - it.each([ - undefined, - 'session-tabs.close-intent.v1', - [7], - ['future.v1', 7], - [''], - ['x'.repeat(129)], - Array.from({ length: 65 }, () => 'future.v1') - ])('rejects malformed or oversized capability input', (value) => { - expect(parseRuntimeClientCapabilities(value)).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/runtime-source-admission.test.ts b/src/main/runtime/rpc/runtime-source-admission.test.ts deleted file mode 100644 index db8b2360797..00000000000 --- a/src/main/runtime/rpc/runtime-source-admission.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { z } from 'zod' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../orca-runtime' -import { publishHostDescriptor } from '../hosts/platform-probe/host-descriptor' -import { defineMethod, type RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' - -const SOURCE_A = '11111111-1111-4111-8111-111111111111' -const SOURCE_B = '22222222-2222-4222-8222-222222222222' - -describe('runtime source admission', () => { - const published: string[] = [] - - afterEach(() => { - for (const runtimeId of published.splice(0)) { - publishHostDescriptor(runtimeId, null) - } - }) - - function createHarness(installationId: string | null = SOURCE_A) { - const id = randomUUID() - const runtime = { getRuntimeId: () => id } - const runtimeId = runtime.getRuntimeId() - if (installationId) { - publishHostDescriptor(runtimeId, { installationId }) - published.push(runtimeId) - } - const effect = vi.fn(() => ({ sent: true })) - const dispatcher = new RpcDispatcher({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture handler is effect; admission and response metadata read only getRuntimeId. - runtime: runtime as OrcaRuntimeService, - methods: [ - defineMethod({ - name: 'terminal.send', - permission: 'workspace', - params: z.object({ text: z.string() }), - handler: effect - }) - ] - }) - const request = (expectedRuntimeSource?: unknown): RpcRequest => ({ - id: 'rpc_1', - authToken: 'token', - method: 'terminal.send', - params: { text: 'hi' }, - ...(expectedRuntimeSource === undefined ? {} : { expectedRuntimeSource }) - }) - return { runtimeId, dispatcher, effect, request } - } - - it('refuses a request meant for another profile before the handler runs', async () => { - const { runtimeId, dispatcher, effect, request } = createHarness() - - const response = await dispatcher.dispatch(request({ sourceId: SOURCE_B, runtimeId })) - - expect(response).toMatchObject({ ok: false, error: { code: 'runtime_source_mismatch' } }) - expect(effect).not.toHaveBeenCalled() - }) - - it('refuses a request verified against another runtime of the same profile', async () => { - const { dispatcher, effect, request } = createHarness() - - const response = await dispatcher.dispatch( - request({ sourceId: SOURCE_A, runtimeId: 'runtime-other' }) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'runtime_source_mismatch' } }) - expect(effect).not.toHaveBeenCalled() - }) - - it('runs a request meant for this runtime', async () => { - const { runtimeId, dispatcher, effect, request } = createHarness() - - const response = await dispatcher.dispatch(request({ sourceId: SOURCE_A, runtimeId })) - - expect(response).toMatchObject({ ok: true, result: { sent: true } }) - expect(effect).toHaveBeenCalledOnce() - }) - - it('keeps today’s behaviour for a client that sends no expectation (old CLI)', async () => { - const { dispatcher, effect, request } = createHarness(null) - - const response = await dispatcher.dispatch(request()) - - expect(response).toMatchObject({ ok: true }) - expect(effect).toHaveBeenCalledOnce() - }) - - it('refuses when this runtime cannot say which profile it serves', async () => { - const { runtimeId, dispatcher, effect, request } = createHarness(null) - - const response = await dispatcher.dispatch(request({ sourceId: SOURCE_A, runtimeId })) - - expect(response).toMatchObject({ ok: false, error: { code: 'runtime_source_unverifiable' } }) - expect(effect).not.toHaveBeenCalled() - }) - - it.each([null, 'source', { sourceId: SOURCE_A }, { sourceId: '', runtimeId: 'r' }])( - 'refuses a malformed expectation %j', - async (expectation) => { - const { dispatcher, effect, request } = createHarness() - - const response = await dispatcher.dispatch(request(expectation)) - - expect(response).toMatchObject({ ok: false, error: { code: 'bad_request' } }) - expect(effect).not.toHaveBeenCalled() - } - ) - - it('fences the streaming transport too', async () => { - const { runtimeId, dispatcher, effect, request } = createHarness() - const replies: string[] = [] - - await dispatcher.dispatchStreaming(request({ sourceId: SOURCE_B, runtimeId }), (reply) => - replies.push(reply) - ) - - expect(JSON.parse(replies[0])).toMatchObject({ - ok: false, - error: { code: 'runtime_source_mismatch' } - }) - expect(effect).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/rpc/server/network-source-policy-store.ts b/src/main/runtime/rpc/server/network-source-policy-store.ts index d3ac5ea014b..ebdf406b056 100644 --- a/src/main/runtime/rpc/server/network-source-policy-store.ts +++ b/src/main/runtime/rpc/server/network-source-policy-store.ts @@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { isRecord } from '../../../../shared/agent-status/child-work/agent-status-child-work-value-guards' -import type { NetworkSourceClass } from '../network-source-class' +import type { NetworkSourceClass } from '../transports/websocket/source-admission/network-source-class' export const NETWORK_SOURCE_POLICY_FILE = 'runtime-network-source-policy.json' diff --git a/src/main/runtime/rpc/server/pairing/device-credential.ts b/src/main/runtime/rpc/server/pairing/device-credential.ts index bec272a35d1..722896c6965 100644 --- a/src/main/runtime/rpc/server/pairing/device-credential.ts +++ b/src/main/runtime/rpc/server/pairing/device-credential.ts @@ -3,7 +3,7 @@ import type { DeviceScope } from '../../../../../shared/runtime-session-contract import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach' import type { TokenDeviceEntry } from './device-entry' import { validGrants } from './device-registry-row-validation' -import type { RuntimeDeviceGrant } from '../../rpc-method-permission' +import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission' export function mintDeviceCredential(): { deviceId: string; token: string } { return { deviceId: randomUUID(), token: randomBytes(24).toString('hex') } diff --git a/src/main/runtime/rpc/server/pairing/device-entry.ts b/src/main/runtime/rpc/server/pairing/device-entry.ts index 7cb2599939a..00a1efdaa36 100644 --- a/src/main/runtime/rpc/server/pairing/device-entry.ts +++ b/src/main/runtime/rpc/server/pairing/device-entry.ts @@ -2,9 +2,9 @@ import type { DeviceScope } from '../../../../../shared/runtime-session-contract import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' import type { MobilePushRegistration } from '../../../../../shared/mobile-push-contract' import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach' -import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox' -import type { RuntimeDeviceGrant } from '../../rpc-method-permission' -import type { NetworkSourceClass } from '../../network-source-class' +import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox' +import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission' +import type { NetworkSourceClass } from '../../transports/websocket/source-admission/network-source-class' export type DeviceEntry = { deviceId: string diff --git a/src/main/runtime/rpc/server/pairing/device-principal.test.ts b/src/main/runtime/rpc/server/pairing/device-principal.test.ts deleted file mode 100644 index 9e2beeb0a21..00000000000 --- a/src/main/runtime/rpc/server/pairing/device-principal.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { createHash } from 'node:crypto' -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { devicePrincipalOf } from './device-principal' -import { DeviceRegistry } from './device-registry' - -import type { DeviceEntry } from './device-entry' -import './mobile-pairing-files' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { OrcaRuntimeRpcServer } from '../runtime-rpc' -import type { AuthenticatedMobileSocket } from '../../mobile-socket-wiring' - -function socketFor(device: DeviceEntry): AuthenticatedMobileSocket { - return { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch only uses ws as a map key for abort registration. - ws: {} as AuthenticatedMobileSocket['ws'], - connectionId: 'connection-1', - transcriptHashB64: null, - device: { ...devicePrincipalOf(device), deviceToken: device.token }, - clientCapabilities: [], - transport: { transport: 'direct' } - } -} - -describe('device principal', () => { - it('dispatches an old phone with its token as client id and refuses it once re-credentialed', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-device-principal-rpc-')) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: status.get only reads these three members. - const runtime = { - configureNotificationDismissalStore: () => {}, - getRuntimeId: () => 'test-runtime', - getStatus: vi.fn().mockResolvedValue({ graphStatus: 'ok' }) - } as unknown as OrcaRuntimeService - const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false }) - const registry = new DeviceRegistry(userDataPath) - server['deviceRegistry'] = registry - const phone = registry.addDevice('phone', 'mobile') - const socket = socketFor(phone) - const dispatch = vi.spyOn(server['dispatcher'], 'dispatchStreaming') - - const replies: string[] = [] - await server['handleWebSocketMessage']( - JSON.stringify({ id: 'r1', method: 'status.get' }), - (response) => replies.push(response), - () => {}, - undefined, - undefined, - phone.token, - socket - ) - expect(dispatch.mock.calls[0]?.[2]).toMatchObject({ - clientId: phone.token, - pairedDeviceId: phone.deviceId, - authenticatedCallerFingerprint: createHash('sha256').update(phone.token).digest('hex') - }) - - registry['devices'] = registry['devices'].map((row) => ({ ...row, credentialRevision: 1 })) - await server['handleWebSocketMessage']( - JSON.stringify({ id: 'r2', method: 'status.get' }), - (response) => replies.push(response), - () => {}, - undefined, - undefined, - phone.token, - socket - ) - expect(dispatch).toHaveBeenCalledOnce() - expect(JSON.parse(replies.at(-1)!)).toMatchObject({ - id: 'r2', - ok: false, - error: { code: 'unauthorized' } - }) - }) -}) diff --git a/src/main/runtime/rpc/server/pairing/device-principal.ts b/src/main/runtime/rpc/server/pairing/device-principal.ts index 7c67cd51458..8c3091e4964 100644 --- a/src/main/runtime/rpc/server/pairing/device-principal.ts +++ b/src/main/runtime/rpc/server/pairing/device-principal.ts @@ -1,5 +1,5 @@ import type { DeviceEntry } from './device-entry' -import type { RpcCallerScope } from '../../rpc-caller-scope' +import type { RpcCallerScope } from '../../callers/rpc-caller-scope' import { createHash } from 'node:crypto' /** Socket revoke/close uses deviceId; per-client drivers, dictation and file grants use clientId. */ diff --git a/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts b/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts index 8d11465f90b..c076dd99cfc 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts @@ -1,12 +1,12 @@ import type { DeviceScope } from '../../../../../shared/runtime-session-contracts' -import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox' +import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { DeviceEntry } from './device-entry' import { parseMobilePushRegistration } from '../../../../../shared/mobile-push-contract' import { isDevicePublicKeyB64 } from '../../../../../shared/remote-runtime/pairing/device-key-proof' import { isExchangeDeviceToken } from '../../../../../shared/remote-runtime/pairing/ticket-exchange-contract' -import { RUNTIME_DEVICE_GRANTS, type RuntimeDeviceGrant } from '../../rpc-method-permission' +import { RUNTIME_DEVICE_GRANTS, type RuntimeDeviceGrant } from '../../callers/rpc-method-permission' import { isRecord } from '../../../../../shared/agent-status/child-work/agent-status-child-work-value-guards' -import { NETWORK_SOURCE_CLASSES } from '../../network-source-class' +import { NETWORK_SOURCE_CLASSES } from '../../transports/websocket/source-admission/network-source-class' const GRANTABLE: ReadonlySet = new Set(RUNTIME_DEVICE_GRANTS) diff --git a/src/main/runtime/rpc/server/pairing/device-registry-sightings.ts b/src/main/runtime/rpc/server/pairing/device-registry-sightings.ts index 877df5be335..bcf173c50a1 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-sightings.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-sightings.ts @@ -1,7 +1,7 @@ import { withDeviceSighting, type DeviceSightingFraming } from './device-sighting' import { DeviceRegistryStore } from './device-registry-store' import type { DeviceEntry } from './device-entry' -import type { NetworkSourceClass } from '../../network-source-class' +import type { NetworkSourceClass } from '../../transports/websocket/source-admission/network-source-class' // Coalesce reconnect bookkeeping: each Windows save otherwise spawns synchronous ACL PowerShell twice. const LAST_SEEN_FLUSH_DELAY_MS = 250 diff --git a/src/main/runtime/rpc/server/pairing/device-registry.ts b/src/main/runtime/rpc/server/pairing/device-registry.ts index 1d3335c0a32..84904c7c0a7 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry.ts @@ -10,7 +10,7 @@ import { } from './pairing-ticket-exchange' import { planIdleEphemeralPrune } from './ephemeral-device-rows' import { DeviceRegistrySightings } from './device-registry-sightings' -import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox' +import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach' import type { DelegatedPhone } from '../../../../../shared/delegated-mobile-device-contract' @@ -18,7 +18,7 @@ import { planDelegatedMobileDevices, type DelegatedMobileDeviceEntry } from './delegated-mobile-devices' -import type { RuntimeDeviceGrant } from '../../rpc-method-permission' +import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission' import { validGrants } from './device-registry-row-validation' import { expiredPairingOffers, diff --git a/src/main/runtime/rpc/server/pairing/pairing-offer-expiry.ts b/src/main/runtime/rpc/server/pairing/pairing-offer-expiry.ts index 080324c1368..ddfa4c26ffc 100644 --- a/src/main/runtime/rpc/server/pairing/pairing-offer-expiry.ts +++ b/src/main/runtime/rpc/server/pairing/pairing-offer-expiry.ts @@ -6,7 +6,7 @@ import { type TokenDeviceEntry } from './device-entry' import type { DeviceScope } from '../../../../../shared/runtime-session-contracts' -import type { RuntimeDeviceGrant } from '../../rpc-method-permission' +import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission' // Desktop UI offers only; headless serve passes no TTL so its offers never expire. export const MOBILE_PAIRING_OFFER_TTL_MS = 10 * 60_000 diff --git a/src/main/runtime/rpc/server/pairing/pairing-offer-requests.ts b/src/main/runtime/rpc/server/pairing/pairing-offer-requests.ts index 1c06f74ab67..c9d026e5c0e 100644 --- a/src/main/runtime/rpc/server/pairing/pairing-offer-requests.ts +++ b/src/main/runtime/rpc/server/pairing/pairing-offer-requests.ts @@ -13,7 +13,7 @@ import { getDefaultPairingAddress, type DefaultRouteInterfaceLookup } from './network/pairing-network-interfaces' -import type { RuntimeDeviceGrant } from '../../rpc-method-permission' +import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission' import type { RuntimeRpcPairing } from '../runtime-rpc-pairing' import { pairingUnavailable, diff --git a/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts b/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts index f4dbfce7108..0a500107afb 100644 --- a/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts +++ b/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts @@ -1,7 +1,7 @@ import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync, type Stats } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { loadWindowsSecurity, type WindowsSecurity @@ -131,54 +131,9 @@ describeOnWindows('a secure store that exists but cannot be read', () => { expectUntouched(filePath, locked) }) - it('does not blank the plugin secret vault on write', async () => { - vi.doMock('electron', () => ({ - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (value: string) => Buffer.from(`enc:${value}`), - decryptString: (buffer: Buffer) => buffer.toString().replace(/^enc:/, '') - } - })) - const { PluginSecretsStore } = await import('../../../../plugins/plugin-secrets-store') - const dir = join(root, 'plugin-secrets') - mkdirSync(dir, { recursive: true }) - const store = new PluginSecretsStore(dir, 'publisher.plugin') - // Reach the path the store computes rather than restating its layout here. - const filePath = (store as unknown as { filePath: string }).filePath - mkdirSync(join(filePath, '..'), { recursive: true }) - const original = JSON.stringify({ - version: 1, - format: 'electron-safe-storage-v1', - ciphertexts: { existing: Buffer.from('enc:keep-me').toString('base64') } - }) - writeFileSync(filePath, original) - const locked = makeUnreadable(filePath) - - expect(store.set('added', 'value')).toEqual({ ok: false, error: expect.any(String) }) - store.delete('existing') - - expectUntouched(filePath, locked) - vi.doUnmock('electron') - }) - it('does not blank the plugin KV store on write', async () => { - const { PluginKvStore } = await import('../../../../plugins/plugin-storage-store') - const dir = join(root, 'plugin-kv') - mkdirSync(dir, { recursive: true }) - const store = new PluginKvStore(dir, 'publisher.plugin', 'storage.json') - const filePath = (store as unknown as { filePath: string }).filePath - mkdirSync(join(filePath, '..'), { recursive: true }) - const original = JSON.stringify({ keep: 'me' }) - writeFileSync(filePath, original) - const locked = makeUnreadable(filePath) - - expect(store.set('added', 'value')).toEqual({ ok: false, error: expect.any(String) }) - store.delete('keep') - - expectUntouched(filePath, locked) - }) - it('does not drop pending relay revocations', async () => { - const { RelayRevokeOutbox } = await import('../../../mobile-cloud-relay/relay-revoke-outbox') + const { RelayRevokeOutbox } = + await import('../../../mobile-cloud-relay/pairing/relay-revoke-outbox') const dir = join(root, 'relay') mkdirSync(dir, { recursive: true }) const filePath = join(dir, 'mobile-relay-revoke-outbox.json') diff --git a/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts b/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts deleted file mode 100644 index e9c6fc64037..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { EventEmitter } from 'node:events' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { WebSocket } from 'ws' -import { DeviceRegistry } from './pairing/device-registry' -import { OrcaRuntimeService } from '../../orca-runtime' -import { defineStreamingMethod, type RpcContext } from '../core' -import { defineOrchestrationStreamingMethod } from '../methods/orchestration/access/orchestration-method-access' - -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { withCurrentOrchestrationContract } from './runtime-rpc-test-harness' - -describe('runtime RPC browser-host admission', () => { - it('reserves browser-host capacity for a second paired device', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-browser-host-fairness-')) - const blockingHost = defineStreamingMethod({ - name: 'browser.clientHost.attach', - permission: 'workspace', - params: null, - handler: async (_params, { signal }) => - await new Promise((resolve) => signal?.addEventListener('abort', () => resolve())) - }) - const server = new OrcaRuntimeRpcServer({ - runtime: new OrcaRuntimeService(), - userDataPath, - longPollCap: 16, - methods: [blockingHost] - }) - server['deviceRegistry'] = new DeviceRegistry(userDataPath) - const deviceA = server['deviceRegistry'].addDevice('runtime-a', 'runtime') - const deviceB = server['deviceRegistry'].addDevice('runtime-b', 'runtime') - const socketA = new FakeWebSocket() - const socketB = new FakeWebSocket() - const socketAReplacement = new FakeWebSocket() - const connectionIds = new Map([ - [socketA, 'connection-a'], - [socketB, 'connection-b'], - [socketAReplacement, 'connection-a-replacement'] - ]) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the server reads only these wiring members in this test. - server['mobileSocketWiring'] = { - dispose: () => {}, - getConnectionId: (socket) => connectionIds.get(socket as unknown as FakeWebSocket) - } as unknown as NonNullable<(typeof server)['mobileSocketWiring']> - const repliesA: Record[] = [] - const repliesB: Record[] = [] - const dispatch = ( - id: string, - deviceToken: string, - socket: FakeWebSocket, - replies: Record[] - ) => - server['handleWebSocketMessage']( - JSON.stringify({ id, method: 'browser.clientHost.attach', deviceToken }), - (reply) => replies.push(JSON.parse(reply) as Record), - () => {}, - undefined, - socket as unknown as WebSocket - ) - - try { - const deviceAHosts = Array.from({ length: 4 }, (_, index) => - dispatch(`host-a-${index}`, deviceA.token, socketA, repliesA) - ) - await vi.waitFor(() => expect(server['activeBrowserHostLongPolls']).toBe(4)) - - await dispatch('host-a-overflow', deviceA.token, socketA, repliesA) - expect(repliesA).toContainEqual( - expect.objectContaining({ - id: 'host-a-overflow', - ok: false, - error: expect.objectContaining({ - message: 'browser-host capacity reached; retry with backoff' - }) - }) - ) - - const deviceBHost = dispatch('host-b', deviceB.token, socketB, repliesB) - await vi.waitFor(() => expect(server['activeBrowserHostLongPolls']).toBe(5)) - expect(repliesB).toEqual([]) - - socketA.readyState = 3 - socketA.emit('close') - await Promise.all(deviceAHosts) - expect(server['activeBrowserHostLongPolls']).toBe(1) - - const replacement = dispatch( - 'host-a-replacement', - deviceA.token, - socketAReplacement, - repliesA - ) - await vi.waitFor(() => expect(server['activeBrowserHostLongPolls']).toBe(2)) - - socketAReplacement.readyState = 3 - socketAReplacement.emit('close') - socketB.readyState = 3 - socketB.emit('close') - await Promise.all([replacement, deviceBHost]) - expect(server['activeBrowserHostLongPolls']).toBe(0) - } finally { - await server.stop() - rmSync(userDataPath, { recursive: true, force: true }) - } - }) - - it('keeps a wait slot when asks and browser hosts fill their shared budget', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-browser-host-wait-reserve-')) - const block = async (_params: void, { signal }: RpcContext) => - await new Promise((resolve) => signal?.addEventListener('abort', () => resolve())) - const blockingMethod = (name: 'browser.clientHost.attach' | 'terminal.wait') => - defineStreamingMethod({ name, permission: 'workspace', params: null, handler: block }) - const blockingAsk = defineOrchestrationStreamingMethod({ - name: 'orchestration.ask', - permission: 'workspace', - params: null, - access: { kind: 'writes', targets: {} }, - handler: block - }) - const server = new OrcaRuntimeRpcServer({ - runtime: new OrcaRuntimeService(), - userDataPath, - longPollCap: 4, - methods: [ - blockingMethod('browser.clientHost.attach'), - blockingAsk, - blockingMethod('terminal.wait') - ] - }) - server['deviceRegistry'] = new DeviceRegistry(userDataPath) - const deviceA = server['deviceRegistry'].addDevice('runtime-a', 'runtime') - const deviceB = server['deviceRegistry'].addDevice('runtime-b', 'runtime') - const socketA = new FakeWebSocket() - const socketB = new FakeWebSocket() - const replies: Record[] = [] - const dispatch = (id: string, method: string, token: string, socket: FakeWebSocket) => - server['handleWebSocketMessage']( - JSON.stringify(withCurrentOrchestrationContract({ id, method, deviceToken: token })), - (reply) => replies.push(JSON.parse(reply) as Record), - () => {}, - undefined, - socket as unknown as WebSocket - ) - - try { - const active = [ - dispatch('ask-a', 'orchestration.ask', deviceA.token, socketA), - dispatch('ask-b', 'orchestration.ask', deviceA.token, socketA), - dispatch('host-a', 'browser.clientHost.attach', deviceA.token, socketA) - ] - await vi.waitFor(() => expect(server['activeLongPolls']).toBe(3)) - - const hostB = dispatch('host-b', 'browser.clientHost.attach', deviceB.token, socketB) - await vi.waitFor(() => - expect(replies).toContainEqual( - expect.objectContaining({ - id: 'host-b', - ok: false, - error: expect.objectContaining({ - message: 'browser-host capacity reached; retry with backoff' - }) - }) - ) - ) - - const wait = dispatch('wait-a', 'terminal.wait', deviceB.token, socketB) - await vi.waitFor(() => expect(server['activeLongPolls']).toBe(4)) - - socketA.readyState = 3 - socketA.emit('close') - socketB.readyState = 3 - socketB.emit('close') - await Promise.all([...active, hostB, wait]) - expect(server['activeLongPolls']).toBe(0) - } finally { - await server.stop() - rmSync(userDataPath, { recursive: true, force: true }) - } - }) -}) - -class FakeWebSocket extends EventEmitter { - readonly OPEN = 1 - readyState = this.OPEN -} diff --git a/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts b/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts index e6452f65399..a69d3185ca7 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts @@ -1,4 +1,4 @@ -import type { AuthenticatedMobileSocket } from '../mobile-socket-wiring' +import type { AuthenticatedMobileSocket } from '../mobile/mobile-socket-wiring' /** Who connected, without credentials: a phone's clientId can be its bearer token, so it is never logged. */ export function describeClientConnection( diff --git a/src/main/runtime/rpc/server/runtime-rpc-device-key-registration.ts b/src/main/runtime/rpc/server/runtime-rpc-device-key-registration.ts index 74ae8d2ef5b..cbc07ad711a 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-device-key-registration.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-device-key-registration.ts @@ -7,7 +7,7 @@ import { verifyDeviceProof } from '../../../../shared/remote-runtime/pairing/device-key-proof' import type { DeviceRegistry } from './pairing/device-registry' -import type { AuthenticatedMobileSocket } from '../mobile-socket-wiring' +import type { AuthenticatedMobileSocket } from '../mobile/mobile-socket-wiring' /** Fork the installation's token row; possession proof binds to this socket's v2 transcript and cannot be replayed elsewhere. */ export function registerSocketDeviceKey( diff --git a/src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts b/src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts deleted file mode 100644 index 3e4790f5d71..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import { encodeDeviceProofMessage } from '../../../../shared/remote-runtime/pairing/device-key-proof' -import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer' -import { OrcaRuntimeService } from '../../orca-runtime' -import { DeviceRegistry } from './pairing/device-registry' -import { DEVICE_REGISTRY_FILENAME } from './pairing/mobile-pairing-files' -import { makeStore } from './runtime-rpc-worktree-store-fixtures' -import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' -import { - TerminalStreamOpcode, - encodeTerminalStreamFrame, - encodeTerminalStreamText -} from '../../../../shared/terminal/stream/terminal-stream-protocol' -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { - encodePairingOffer, - parsePairingCode -} from '../../../../shared/remote-runtime/pairing/pairing' -import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { waitFor } from './runtime-rpc-test-harness' -import { - connectWs, - nextWsMessage, - waitForWsClose, - authenticateMobileWs -} from './runtime-rpc-mobile-ws-test-harness' - -vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: listings.listWorktrees - } -}) - -vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: listings.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - function createWorktreeListingMocks() { - const worktrees = [ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/foo', - isBare: false, - isMainWorktree: false - } - ] - return { - listWorktrees: vi.fn().mockResolvedValue(worktrees), - listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) - } - } - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -async function authenticateKeyedWs(offer: PairingOffer, deviceId: string, key: nacl.SignKeyPair) { - const ws = await connectWs(offer.endpoint) - const peer = new SimulatedMobileE2EEV2Peer( - nacl.box.keyPair(), - Uint8Array.from(Buffer.from(offer.publicKeyB64, 'base64')), - null - ) - ws.send(JSON.stringify(peer.hello)) - expect(peer.acceptReady(JSON.parse(await nextWsMessage(ws)))).toBe(true) - const transcriptHashB64 = peer.transcriptHashB64 - const proof = nacl.sign.detached( - encodeDeviceProofMessage('auth', Buffer.from(transcriptHashB64, 'base64')), - key.secretKey - ) - ws.send( - peer.sealText( - JSON.stringify({ - type: 'e2ee_auth', - v: 2, - transcriptHashB64, - deviceId, - deviceProofB64: Buffer.from(proof).toString('base64') - }) - ) - ) - expect(JSON.parse(peer.openText(await nextWsMessage(ws))!)).toMatchObject({ - type: 'e2ee_authenticated' - }) - return { ws, peer } -} - -describe('OrcaRuntimeRpcServer', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it.each([ - ['mobile', false], - ['runtime', false], - ['mobile', true] - ] as const)( - 'revoking a %s bearer, removed on disk %s, removes descendants and closes their sockets', - async (scope, removedOnDisk) => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-revoke-')) - const server = new OrcaRuntimeRpcServer({ - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - await server.start() - try { - const offer = server.createPairingOffer({ address: '127.0.0.1', name: 'Parent', scope }) - if (!offer.available) { - throw new Error('WebSocket pairing unavailable') - } - const parsed = parsePairingCode(offer.pairingUrl)! - const parentSocket = await authenticateMobileWs(offer.pairingUrl) - const registry = server.getDeviceRegistry()! - const key = nacl.sign.keyPair() - const fork = registry.forkDeviceKey( - offer.deviceId, - Buffer.from(key.publicKey).toString('base64'), - 'Fork' - ) - const idleFork = registry.forkDeviceKey( - offer.deviceId, - Buffer.alloc(32, 9).toString('base64'), - 'Offline fork' - ) - const { ws: forkSocket } = await authenticateKeyedWs(parsed, fork.deviceId, key) - const children = - scope === 'runtime' - ? registry.upsertDelegatedMobileDevices(fork, [{ phoneKey: 'p', name: 'Pixel' }]) - : [] - const sockets = [parentSocket, forkSocket] - for (const child of children) { - sockets.push( - await authenticateMobileWs( - encodePairingOffer({ - ...parsed, - deviceToken: child.token, - pairedDeviceId: child.deviceId, - scope: 'mobile' - }) - ) - ) - } - const unrelated = registry.addDevice('Unrelated', scope) - const unrelatedSocket = await authenticateMobileWs( - encodePairingOffer({ - ...parsed, - deviceToken: unrelated.token, - pairedDeviceId: unrelated.deviceId - }) - ) - const closed = sockets.map(waitForWsClose) - if (removedOnDisk) { - const path = join(userDataPath, DEVICE_REGISTRY_FILENAME) - const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8')) - writeFileSync(path, JSON.stringify(rows.filter((row) => row.deviceId !== offer.deviceId))) - } - - const revoked = - scope === 'mobile' - ? await server.revokeMobileDevice(offer.deviceId) - : server.revokeRuntimeAccess(offer.deviceId) - - expect(revoked).toBe(true) - for (const device of [fork, idleFork, ...children]) { - expect(registry.getDevice(device.deviceId)).toBeNull() - expect(new DeviceRegistry(userDataPath).getDevice(device.deviceId)).toBeNull() - } - await Promise.all(closed) - expect(registry.validateToken(unrelated.token)?.deviceId).toBe(unrelated.deviceId) - expect(unrelatedSocket.readyState).toBe(unrelatedSocket.OPEN) - unrelatedSocket.close() - } finally { - await server.stop() - } - }, - 15_000 - ) - - it.each(['binary', 'text', 'sibling-cascade'] as const)( - 'retires an established keyed terminal subscription through %s revocation', - async (kind) => { - vi.useFakeTimers({ toFake: ['performance'] }) - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-stream-revoke-')) - const runtime = new OrcaRuntimeService(partialRuntimeStore(makeStore())) - const write = vi.fn(() => true) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'fork-stream-pty' }), - write, - kill: () => true, - getForegroundProcess: async () => null - }) - const cleanup = vi.spyOn(runtime, 'cleanupSubscriptionsForConnection') - const server = new OrcaRuntimeRpcServer({ - runtime, - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - await server.start() - try { - const terminal = await runtime.createTerminal('id:repo-1::/tmp/worktree-a') - const offer = server.createPairingOffer({ - address: '127.0.0.1', - name: 'Parent', - scope: kind === 'sibling-cascade' ? 'mobile' : 'runtime' - }) - if (!offer.available) { - throw new Error('WebSocket pairing unavailable') - } - const registry = server.getDeviceRegistry()! - const key = nacl.sign.keyPair() - const earlier = - kind === 'sibling-cascade' - ? registry.forkDeviceKey( - offer.deviceId, - Buffer.alloc(32, 7).toString('base64'), - 'Earlier' - ) - : null - const fork = registry.forkDeviceKey( - offer.deviceId, - Buffer.from(key.publicKey).toString('base64'), - 'Fork' - ) - const later = - kind === 'sibling-cascade' - ? registry.forkDeviceKey( - offer.deviceId, - Buffer.alloc(32, 8).toString('base64'), - 'Later' - ) - : null - if (kind === 'sibling-cascade') { - server.setMobileRelayBinding(fork.deviceId, { - relayHostId: 'host', - relayDeviceId: fork.deviceId, - ownerIdentityKey: 'owner' - }) - registry.setPushRegistration(fork.deviceId, { - registrationId: 'fork-push', - filter: {}, - expiresAt: 4_000_000_000_000 - }) - } - const { ws, peer } = await authenticateKeyedWs( - parsePairingCode(offer.pairingUrl)!, - fork.deviceId, - key - ) - const responses: { result?: { type?: string; streamId?: number } }[] = [] - ws.on('message', (data, isBinary) => { - if (isBinary && Buffer.isBuffer(data)) { - peer.openBinary(data) - } else if (!isBinary) { - responses.push(JSON.parse(peer.openText(data.toString())!)) - } - }) - ws.send( - peer.sealText( - JSON.stringify({ - id: 'subscribe', - method: 'terminal.subscribe', - params: { terminal: terminal.handle, capabilities: { terminalBinaryStream: 1 } } - }) - ) - ) - await waitFor(() => responses.some((response) => response.result?.type === 'subscribed')) - const streamId = responses.find((response) => response.result?.type === 'subscribed') - ?.result?.streamId - if (streamId === undefined) { - throw new Error('Expected binary terminal subscription') - } - const sendInput = (text: string) => - ws.send( - peer.sealBinary( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId, - seq: 1, - payload: encodeTerminalStreamText(text) - }) - ) - ) - sendInput('before') - await waitFor(() => write.mock.calls.length === 1) - const path = join(userDataPath, DEVICE_REGISTRY_FILENAME) - const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8')) - writeFileSync( - path, - JSON.stringify( - rows.filter( - (row) => - row.deviceId !== (kind === 'sibling-cascade' ? fork.deviceId : offer.deviceId) - ) - ) - ) - // The registry sees another process's edit once its one-second stat window has passed. - vi.advanceTimersByTime(1000) - const closed = waitForWsClose(ws) - - if (kind === 'sibling-cascade') { - expect(await server.revokeMobileDevice(offer.deviceId)).toBe(true) - for (const device of [earlier, fork, later]) { - if (device) { - expect(registry.getDevice(device.deviceId)).toBeNull() - } - } - expect(registry.getDevice(offer.deviceId)).toBeNull() - expect(server.getRelayRevokeOutbox().pendingFor('owner', 'host')).toMatchObject([ - { relayDeviceId: fork.deviceId } - ]) - expect(server.getPushUnregisterOutbox().pending()).toMatchObject([ - { deviceId: fork.deviceId, registrationId: 'fork-push' } - ]) - } else if (kind === 'binary') { - sendInput('after') - } else { - ws.send(peer.sealText(JSON.stringify({ id: 'denied', method: 'status.get' }))) - } - - await waitFor( - () => - cleanup.mock.calls.length > 0 || - write.mock.calls.length > 1 || - responses.some((response) => 'error' in response) - ) - expect(write).toHaveBeenCalledTimes(1) - expect(cleanup).toHaveBeenCalledOnce() - await closed - expect(server['mobileSocketWiring']?.channelCount).toBe(0) - expect(server['mobileSocketWiring']?.connectionCount).toBe(0) - } finally { - cleanup.mockRestore() - await server.stop() - } - } - ) -}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts b/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts index dcbec116c0f..9ba6ed7daf3 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts @@ -6,18 +6,21 @@ import { placeUnshownLiveTerminalsBestEffort } from '../../terminal/adoption/uns import type { RuntimeTransportMetadata } from '../../../../shared/runtime-bootstrap' import { watchRuntimeMetadataOwnership } from './runtime-metadata-ownership-watch' import type { RpcTransport } from '../transport' -import { UnixSocketTransport } from '../unix-socket-transport' -import { PinnedPortUnavailableError, WebSocketTransport } from '../ws-transport' +import { UnixSocketTransport } from '../transports/unix-socket-transport' +import { + PinnedPortUnavailableError, + WebSocketTransport +} from '../transports/websocket/ws-transport' import { clearWsFallbackPort, readWsFallbackPort, wsFallbackPortLadder, writeWsFallbackPort -} from '../ws-fallback-port-store' +} from '../transports/websocket/ws-fallback-port-store' import type { DeviceRegistry } from './pairing/device-registry' import type { E2EEKeypair } from './pairing/e2ee-keypair' -import { UnpairedDeviceAuthThrottle } from '../unpaired-device-auth-throttle' -import { MobileSocketWiring } from '../mobile-socket-wiring' +import { UnpairedDeviceAuthThrottle } from '../mobile/unpaired-device-auth-throttle' +import { MobileSocketWiring } from '../mobile/mobile-socket-wiring' import { createServeNetworkSourceGuard } from './serve-network-source-policy' import { RuntimeRpcWebSocketDispatch } from './runtime-rpc-websocket-dispatch' import { diff --git a/src/main/runtime/rpc/server/runtime-rpc-local-disconnect-forwarding.test.ts b/src/main/runtime/rpc/server/runtime-rpc-local-disconnect-forwarding.test.ts deleted file mode 100644 index 08a971cb977..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-local-disconnect-forwarding.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { mkdtempSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../orca-runtime' -import { defineMethod } from '../core' -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { - _resetOrcadFeatureReadinessForTests, - installOrcadFeatureReadiness -} from '../orcad-feature-readiness' - -// A short RPC gets no handler signal, but a caller that disconnects mid feature-wait is never run. -it('refuses a gated short RPC whose local caller disconnects while it waits', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'local-disconnect-feature-wait-')) - const ran = vi.fn() - const readiness = installOrcadFeatureReadiness() - const server = new OrcaRuntimeRpcServer({ - runtime: new OrcaRuntimeService(), - userDataPath, - methods: [ - defineMethod({ - name: 'aiVault.searchStatus', - requires: ['sessionSearch'], - permission: 'workspace', - params: null, - handler: () => { - ran() - return {} - } - }) - ] - }) - const disconnect = new AbortController() - try { - const pending = server['handleMessage']( - JSON.stringify({ - id: 'req-1', - method: 'aiVault.searchStatus', - authToken: server['authToken'] - }), - { signal: disconnect.signal, startKeepalive: vi.fn() } - ) - disconnect.abort() - await expect(pending).resolves.toMatchObject({ - ok: false, - error: { code: 'runtime_unavailable' } - }) - readiness.open('sessionSearch') - await Promise.resolve() - expect(ran).not.toHaveBeenCalled() - } finally { - _resetOrcadFeatureReadinessForTests() - await server.stop() - rmSync(userDataPath, { recursive: true, force: true }) - } -}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts b/src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts index 3bb962fd169..3e85b91514b 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts @@ -1,13 +1,12 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createConnection } from 'node:net' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../orca-runtime' -import { OrchestrationDb } from '../../orchestration/db/orchestration-db' import '../../orchestration/db/contract-constants' import '../../orchestration/db/messages/mailbox-routing-page' import '../../orchestration/db/dispatch-row-writer' @@ -16,18 +15,7 @@ import '../../orchestration/db/attempt-outcome-projection' import { readRuntimeMetadata } from './runtime-metadata' import { createLongPollServer as createServer } from './runtime-rpc-long-poll-server.test-fixture' -import { - sendRequest, - openFramedSession, - sleep, - waitFor, - seedSupervisedAskWorkers -} from './runtime-rpc-test-harness' import '../../orchestration/db/root-dispatch-test-fixture' -import { - createTranscriptPane, - TRANSCRIPT_PANE_PTY_ID -} from '../../orca-runtime-tests/agent-transcript-pane-test-harness' vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ ...(await importOriginal()), @@ -85,290 +73,4 @@ describe('OrcaRuntimeRpcServer', () => { await server.stop() }) - - // Use real socket keepalives/admission to catch flush/buffer regressions mocks miss (design §§3.1, 6). - describe('long-poll transport (§3.1)', () => { - it('releases terminal.wait long-poll slot when the client closes mid-wait', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const server = createServer({ - runtime, - userDataPath, - keepaliveIntervalMs: 1000, - longPollCap: 1 - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - title: 'Terminal 1', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'pty-1' - } - ] - }) - await server.start() - - try { - const metadata = readRuntimeMetadata(userDataPath) - const listResponse = await sendRequest(metadata!.transports[0]!.endpoint, { - id: 'req_list', - authToken: metadata!.authToken, - method: 'terminal.list' - }) - const handle = ( - listResponse.result as { - terminals: { handle: string }[] - } - ).terminals[0]!.handle - const endpoint = metadata!.transports[0]!.endpoint - - const session = openFramedSession(endpoint, { - id: 'req_terminal_wait', - authToken: metadata!.authToken, - method: 'terminal.wait', - params: { terminal: handle, for: 'exit', timeoutMs: 10_000 } - }) - await waitFor(() => server['activeLongPolls'] === 1) - - session.socket.destroy() - await session.done - await waitFor(() => server['activeLongPolls'] === 0) - - const admitted = openFramedSession(endpoint, { - id: 'req_terminal_wait_2', - authToken: metadata!.authToken, - method: 'terminal.wait', - params: { terminal: handle, for: 'tui-idle', timeoutMs: 50 } - }) - await admitted.done - expect(admitted.frames.find((f) => f.ok !== undefined)).toMatchObject({ - id: 'req_terminal_wait_2', - ok: false, - error: { code: 'timeout' } - }) - } finally { - await server.stop() - } - }) - - it('releases one same-Run wait slot when its client closes and keeps its sibling live', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - // A consuming check now requires a live pane; these transport tests only need it to block. - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => `tab_${handle}:leaf`) - const run = db.createRun({ - objective: 'Concurrent Run waits', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab_term_coord:leaf' - }) - const server = createServer({ - runtime, - userDataPath, - keepaliveIntervalMs: 1000, - longPollCap: 2 - }) - await server.start() - - try { - const metadata = readRuntimeMetadata(userDataPath) - const endpoint = metadata!.transports[0]!.endpoint - const openRunWait = (id: string) => - openFramedSession(endpoint, { - id, - authToken: metadata!.authToken, - method: 'orchestration.check', - params: { terminal: 'term_coord', run: run.id, wait: true, timeoutMs: 10_000 } - }) - - // Fill the cap with two waits on the same Run inbox. - const a = openRunWait('req_a') - const b = openRunWait('req_b') - await waitFor(() => server['activeLongPolls'] === 2) - - a.socket.destroy() - await a.done - await waitFor(() => server['activeLongPolls'] === 1) - - // The freed slot must admit another wait on the same inbox. - const c = openRunWait('req_c') - await waitFor(() => server['activeLongPolls'] === 2) - db.insertMessage({ from: 'term_worker', to: `run:${run.id}`, subject: 'go', runId: run.id }) - runtime.notifyMessageArrived(`run:${run.id}`) - await Promise.all([b.done, c.done]) - const results = [b, c].map((s) => s.frames.find((f) => f.ok !== undefined)?.result) - const batch = { deliveryId: expect.stringMatching(/^delivery_/), count: 1 } - expect(results).toMatchObject([batch, batch]) - expect(db.db.prepare('SELECT COUNT(*) AS n FROM deliveries').get()).toEqual({ n: 1 }) - await waitFor(() => server['activeLongPolls'] === 0) - } finally { - db.close() - await server.stop() - } - }) - - it('destroys active Unix sockets and cancels pending composer readiness when the runtime stops', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const { runtime, handle } = await createTranscriptPane({ - paneTitle: 'shell', - foregroundProcess: 'bash', - data: '' - }) - const server = createServer({ runtime, userDataPath }) - vi.spyOn(server['dispatcher'], 'dispatch').mockImplementation(async (_request, context) => { - await runtime.waitForFreshWorkerComposer(handle, 'claude', 60_000, { - signal: context?.signal - }) - throw new Error('unexpected_composer_ready') - }) - await server.start() - try { - const metadata = readRuntimeMetadata(userDataPath)! - const session = openFramedSession(metadata.transports[0]!.endpoint, { - id: 'req_stop', - authToken: metadata.authToken, - method: 'orchestration.check', - params: { terminal: 'term_stop', wait: true, timeoutMs: 10_000 } - }) - await waitFor(() => runtime['terminalWaiters'].forPty(TRANSCRIPT_PANE_PTY_ID).length === 1) - await server.stop() - await session.done - await waitFor(() => server['activeLongPolls'] === 0) - expect(session.socket.destroyed).toBe(true) - expect(runtime['terminalWaiters'].forPty(TRANSCRIPT_PANE_PTY_ID)).toHaveLength(0) - expect( - runtime['terminalStreamConsumers']['dataListeners'].get(TRANSCRIPT_PANE_PTY_ID) - ).toBeUndefined() - } finally { - await server.stop() - } - }) - - it('reserves long-poll headroom for terminal.wait when orchestration.ask floods', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - // A consuming check now requires a live pane; these transport tests only need it to block. - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => `tab_${handle}:leaf`) - seedSupervisedAskWorkers(db, ['term_w0', 'term_w1', 'term_w2', 'term_w3']) - // Ask sub-cap is half the total: cap 4 admits only two asks. - const server = createServer({ - runtime, - userDataPath, - keepaliveIntervalMs: 1000, - longPollCap: 4 - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - title: 'Terminal 1', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: 'repo-1::/tmp/worktree-a', - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: 'pty-1' - } - ] - }) - await server.start() - - const asks: ReturnType[] = [] - try { - const metadata = readRuntimeMetadata(userDataPath) - const endpoint = metadata!.transports[0]!.endpoint - const listResponse = await sendRequest(endpoint, { - id: 'req_list', - authToken: metadata!.authToken, - method: 'terminal.list' - }) - const handle = (listResponse.result as { terminals: { handle: string }[] }).terminals[0]! - .handle - - // Distinct senders keep four pending asks from waking each other. - for (let i = 0; i < 4; i++) { - asks.push( - openFramedSession(endpoint, { - id: `req_ask_${i}`, - authToken: metadata!.authToken, - method: 'orchestration.ask', - params: { - from: `term_w${i}`, - to: 'term_coord', - question: 'proceed?', - timeoutMs: 10_000 - } - }) - ) - } - // Let every ask reach the admission fence before probing the reserved half. - await waitFor(() => server['activeLongPolls'] >= 2) - await sleep(100) - - // The reserved half still admits a terminal.wait from any other client. - const admitted = openFramedSession(endpoint, { - id: 'req_terminal_wait', - authToken: metadata!.authToken, - method: 'terminal.wait', - params: { terminal: handle, for: 'tui-idle', timeoutMs: 50 } - }) - await admitted.done - expect(admitted.frames.find((f) => f.ok !== undefined)).toMatchObject({ - id: 'req_terminal_wait', - ok: false, - error: { code: 'timeout' } - }) - - // …and a check --wait too, which shares the same reserved class. - const check = openFramedSession(endpoint, { - id: 'req_check_wait', - authToken: metadata!.authToken, - method: 'orchestration.check', - params: { terminal: 'term_other', wait: true, timeoutMs: 100 } - }) - await check.done - expect(check.frames.find((f) => f.ok !== undefined)).toMatchObject({ - id: 'req_check_wait', - ok: true - }) - - // Overflow asks are shed, not queued: the sub-cap holds at half the budget. - expect(server['activeAskLongPolls']).toBe(2) - const shed = asks - .map((a) => a.frames.find((f) => f.ok !== undefined)) - .filter((f) => f !== undefined) - expect(shed).toHaveLength(2) - expect(shed[0]).toMatchObject({ ok: false, error: { code: 'runtime_busy' } }) - } finally { - for (const ask of asks) { - ask.socket.destroy() - } - await Promise.all(asks.map((ask) => ask.done)) - db.close() - await server.stop() - } - }) - }) }) diff --git a/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts b/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts index 88be749ebbf..136a6bf49dc 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts @@ -1,6 +1,6 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' @@ -9,7 +9,6 @@ import { OrcaRuntimeService } from '../../orca-runtime' import * as runtimeMetadataModule from './runtime-metadata' import { readRuntimeMetadata, writeRuntimeMetadata } from './runtime-metadata' import { shortDaemonSocketDir } from '../../../daemon/endpoint/publication/daemon-socket-endpoint-path' -import { createRuntimeTransportMetadata } from './runtime-rpc-socket-metadata' import { OrcaRuntimeRpcServer } from './runtime-rpc' import type { RuntimeMetadata } from '../../../../shared/runtime-bootstrap' @@ -130,31 +129,6 @@ describe('OrcaRuntimeRpcServer', () => { expect(readRuntimeMetadata(userDataPath)).toMatchObject({ runtimeId: 'rt_second_instance' }) }) - it('closes the socket if metadata publication fails during startup', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const server = new OrcaRuntimeRpcServer({ methods: [], runtime, userDataPath }) - const writeMetadataSpy = vi - .spyOn(runtimeMetadataModule, 'writeRuntimeMetadata') - .mockImplementationOnce(() => { - throw new Error('write failed') - }) - const endpoint = createRuntimeTransportMetadata( - userDataPath, - process.pid, - process.platform, - runtime.getRuntimeId() - ).endpoint - - await expect(server.start()).rejects.toThrow('write failed') - expect(readRuntimeMetadata(userDataPath)).toBeNull() - expect(existsSync(endpoint)).toBe(false) - expect(server['transports']).toEqual([]) - expect(server['activeTransports']).toEqual([]) - - writeMetadataSpy.mockRestore() - }) - it.skipIf(process.platform === 'win32')( 'never sweeps inside a relocated socket dir that is not private to this user', async () => { diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts index efddca9334a..eb2b91a8cab 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts @@ -1,7 +1,7 @@ import type { RelayDeviceBinding, RelayRevokeOutboxItem -} from '../../mobile-cloud-relay/relay-revoke-outbox' +} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { DelegatedPhone, DelegatedMobileDeviceSyncResult diff --git a/src/main/runtime/rpc/server/runtime-rpc-network-exposure.ts b/src/main/runtime/rpc/server/runtime-rpc-network-exposure.ts index 6cad8347916..0cd5d2e85e5 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-network-exposure.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-network-exposure.ts @@ -1,5 +1,5 @@ -import { WebSocketTransport } from '../ws-transport' -import { writeWsFallbackPort } from '../ws-fallback-port-store' +import { WebSocketTransport } from '../transports/websocket/ws-transport' +import { writeWsFallbackPort } from '../transports/websocket/ws-fallback-port-store' import { RuntimeRpcLifecycle } from './runtime-rpc-lifecycle' import { WS_BIND_HOST_ALL_INTERFACES, WS_BIND_HOST_LOOPBACK } from './runtime-rpc-pairing-types' diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts index 97cb6df3fd1..a92bb64337a 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts @@ -1,6 +1,6 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { cpSync, mkdirSync, mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing-ticket-exchange.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing-ticket-exchange.ts index 9ed3d91b73d..e26bfef5834 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing-ticket-exchange.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing-ticket-exchange.ts @@ -3,7 +3,7 @@ import type { ExchangePairingTicketResult } from '../../../../shared/remote-runtime/pairing/ticket-exchange-contract' import type { DeviceRegistry } from './pairing/device-registry' -import type { AuthenticatedMobileSocket } from '../mobile-socket-wiring' +import type { AuthenticatedMobileSocket } from '../mobile/mobile-socket-wiring' /** Only a socket that signed in with the pairing token itself may propose its replacement. */ export function exchangeSocketPairingTicket( diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts index 1905219707a..924c96665c4 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts @@ -2,7 +2,7 @@ import type { OrcaRuntimeService } from '../../orca-runtime' import type { RpcAnyMethodDeclaration } from '../core' import type { DeviceRegistry } from './pairing/device-registry' import type { E2EEKeypair } from './pairing/e2ee-keypair' -import type { MobileSocketTransportMetadata } from '../mobile-socket-wiring' +import type { MobileSocketTransportMetadata } from '../mobile/mobile-socket-wiring' import type { ServeNetworkSourceOptions } from './serve-network-source-policy' import type { PairingRelay } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' import type { MobilePairingConnectionMode } from '../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' @@ -16,7 +16,7 @@ import type { import type { RelayDeviceBinding, RelayRevokeOutboxItem -} from '../../mobile-cloud-relay/relay-revoke-outbox' +} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' export const DEFAULT_WS_PORT = 6768 diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing.ts index 0887c8c2bb8..6327d2446b0 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing.ts @@ -1,13 +1,13 @@ -import type { RuntimeDeviceGrant } from '../rpc-method-permission' +import type { RuntimeDeviceGrant } from '../callers/rpc-method-permission' import type { DeviceRegistry } from './pairing/device-registry' import type { DeviceScope } from '../../../../shared/runtime-session-contracts' import type { TokenDeviceEntry } from './pairing/device-entry' import type { E2EEKeypair } from './pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../mobile-socket-wiring' +import type { MobileSocketWiring } from '../mobile/mobile-socket-wiring' import type { RelayDeviceBinding, RelayRevokeOutbox -} from '../../mobile-cloud-relay/relay-revoke-outbox' +} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { PushUnregisterOutbox } from '../../push/push-unregister-outbox' import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' diff --git a/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts b/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts index fa1f5f29c14..a81adad8518 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts @@ -1,4 +1,4 @@ -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { mkdtempSync } from 'node:fs' import { createServer, type Server } from 'node:net' import { tmpdir } from 'node:os' @@ -6,7 +6,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { OrcaRuntimeService } from '../../orca-runtime' import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { PinnedPortUnavailableError } from '../ws-transport' +import { PinnedPortUnavailableError } from '../transports/websocket/ws-transport' const holders: Server[] = [] diff --git a/src/main/runtime/rpc/server/runtime-rpc-relay-pairing-offer-expiry.test.ts b/src/main/runtime/rpc/server/runtime-rpc-relay-pairing-offer-expiry.test.ts index 89ee736a776..36109d49cd0 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-relay-pairing-offer-expiry.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-relay-pairing-offer-expiry.test.ts @@ -1,6 +1,6 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts b/src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts index 2a1c891b5ec..ed6175515b8 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts @@ -1,6 +1,6 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -98,66 +98,6 @@ describe('OrcaRuntimeRpcServer', () => { } }) - it('coalesces concurrent mobile Relay mints for the shared pending credential', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - let resolveFirst: (() => void) | undefined - const firstMint = new Promise((resolve) => { - resolveFirst = resolve - }) - const createPairingRelay = vi.fn(async (relayDeviceId: string) => { - await firstMint - return { - relay: { - v: 1 as const, - directorUrl: 'https://relay.example.com', - cellUrl: 'https://cell.example.com', - assignmentEpoch: 7, - relayHostId: 'AbCdEf0123_-xyZ9', - inviteToken: 'A'.repeat(43), - inviteExpiresAt: Date.now() + 60_000, - e2eeFraming: 2 as const - }, - binding: { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId, - ownerIdentityKey: 'user\0profile\0org' - } - } - }) - server.setMobileRelayPairingProvider({ - createPairingRelay, - onDeviceRevokeQueued: vi.fn(), - getEndpoints: vi.fn(), - provisionRelay: vi.fn() - }) - - await server.start() - try { - const first = server.createMobilePairingOffer({ address: '100.64.1.20', rotate: true }) - const second = server.createMobilePairingOffer({ address: '100.64.1.20', rotate: true }) - await vi.waitFor(() => expect(createPairingRelay).toHaveBeenCalledTimes(1)) - resolveFirst?.() - const [firstOffer, secondOffer] = await Promise.all([first, second]) - expect(firstOffer.available).toBe(true) - expect(secondOffer.available).toBe(true) - if (!firstOffer.available || !secondOffer.available) { - throw new Error('WebSocket pairing unavailable') - } - expect(secondOffer.deviceId).toBe(firstOffer.deviceId) - expect(secondOffer.pairingUrl).toBe(firstOffer.pairingUrl) - expect(createPairingRelay).toHaveBeenCalledTimes(1) - } finally { - await server.stop() - } - }) - it('supersedes an older concurrent Relay mint for a different address without rotate', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const server = new OrcaRuntimeRpcServer({ diff --git a/src/main/runtime/rpc/server/runtime-rpc-reply-size-limit.ts b/src/main/runtime/rpc/server/runtime-rpc-reply-size-limit.ts index abc25717582..92440c753c2 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-reply-size-limit.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-reply-size-limit.ts @@ -1,5 +1,5 @@ import type { RpcResponse } from '../core' -import { isMobileE2EETextPayloadWithinLimit } from '../mobile-e2ee-outbound-admission' +import { isMobileE2EETextPayloadWithinLimit } from '../mobile/e2ee/mobile-e2ee-outbound-admission' import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../shared/remote-runtime/remote-runtime-memory-limits' export const RUNTIME_RPC_REPLY_TOO_LARGE_CODE = 'reply_too_large' diff --git a/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts b/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts index beb2c564224..4d3bf0b8c89 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts @@ -2,11 +2,11 @@ import type { RuntimeMetadata } from '../../../../shared/runtime-bootstrap' import { writeRuntimeMetadata } from './runtime-metadata' import type { RpcMessageContext } from '../transport' import type { PairingOffersRpcContext, RpcRequest, RpcResponse } from '../core' -import { errorResponse } from '../errors' +import { errorResponse } from '../responses/rpc-response' import { RuntimeRpcBinaryRouting } from './runtime-rpc-binary-routing' import { classifyRuntimeLongPoll, type RuntimeLongPollClass } from './runtime-rpc-long-poll' -import { OWNER_RPC_CALLER_SCOPE, type RpcCallerScope } from '../rpc-caller-scope' -import { LOCAL_CLI_RPC_CALLER } from '../rpc-caller-identity' +import { OWNER_RPC_CALLER_SCOPE, type RpcCallerScope } from '../callers/rpc-caller-scope' +import { LOCAL_CLI_RPC_CALLER } from '../callers/rpc-caller-identity' // Short calls that stop on disconnect without long-poll keepalives or admission slots. const DISCONNECT_FORWARDED_METHODS = new Set([ diff --git a/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts b/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts index 2886782aae8..539e8640fa4 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts @@ -1,13 +1,11 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { mkdtempSync } from 'node:fs' -import { createHash } from 'node:crypto' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../orca-runtime' -import { OrchestrationDb } from '../../orchestration/db/orchestration-db' import '../../orchestration/db/contract-constants' import '../../orchestration/db/messages/mailbox-routing-page' import '../../orchestration/db/dispatch-row-writer' @@ -15,8 +13,7 @@ import '../../orchestration/db/attempt-outcome-projection' import { readRuntimeMetadata } from './runtime-metadata' import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { DeviceRegistry } from './pairing/device-registry' -import { sendRequest, withCurrentOrchestrationContract } from './runtime-rpc-test-harness' +import { sendRequest } from './runtime-rpc-test-harness' import { STATUS_METHODS } from '../methods/host-management/status' import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from '../../orchestration/legacy-remote/federation-control' import { ORCHESTRATION_RESET_METHODS } from '../methods/orchestration/runs/reset-methods' @@ -70,135 +67,6 @@ const { getWorktreeListingMocks } = vi.hoisted(() => { }) describe('OrcaRuntimeRpcServer', () => { - it('isolates mutation replay by the authenticated paired device across reconnects', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - const server = new OrcaRuntimeRpcServer({ - runtime, - methods, - userDataPath, - enableWebSocket: false - }) - server['deviceRegistry'] = new DeviceRegistry(userDataPath) - const firstDevice = server['deviceRegistry']!.addDevice('first-cli', 'runtime') - const secondDevice = server['deviceRegistry']!.addDevice('second-cli', 'runtime') - - const resetMessages = async (id: string, authenticatedToken: string) => { - const replies: Record[] = [] - await server['handleWebSocketMessage']( - JSON.stringify( - withCurrentOrchestrationContract({ - id, - method: 'orchestration.reset', - orchestrationRequestId: 'paired-reset-request', - params: { messages: true } - }) - ), - (response) => replies.push(JSON.parse(response) as Record), - () => {}, - undefined, - undefined, - authenticatedToken - ) - return replies[0] - } - - try { - db.insertMessage({ - runId: 'run_legacy_local', - from: 'worker', - to: 'coordinator', - subject: 'before reset' - }) - const first = await resetMessages('reset-first', firstDevice.token) - db.insertMessage({ - runId: 'run_legacy_local', - from: 'worker', - to: 'coordinator', - subject: 'after reset' - }) - const replay = await resetMessages('reset-replay', firstDevice.token) - - expect(first).toMatchObject({ - ok: true, - result: { reset: 'messages', mutation: { replayed: false } } - }) - expect(replay).toMatchObject({ - ok: true, - result: { reset: 'messages', mutation: { replayed: true } } - }) - expect(db.getInbox()).toEqual([expect.objectContaining({ subject: 'after reset' })]) - - const isolated = await resetMessages('reset-second-device', secondDevice.token) - expect(isolated).toMatchObject({ - ok: true, - result: { reset: 'messages', mutation: { replayed: false } } - }) - expect(db.getInbox()).toEqual([]) - } finally { - db.close() - await server.stop() - } - }) - - it('keeps authenticated paired callers attached to existing federated workers', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - const server = new OrcaRuntimeRpcServer({ - runtime, - methods, - userDataPath, - enableWebSocket: false - }) - server['deviceRegistry'] = new DeviceRegistry(userDataPath) - const device = server['deviceRegistry']!.addDevice('existing-cli', 'runtime') - const existingFingerprint = createHash('sha256').update(device.token).digest('hex') - db.createRemoteDispatchAttachment({ - runId: 'run_home', - dispatchId: 'ctx_existing_remote', - taskId: 'task_existing_remote', - homePeerFingerprint: existingFingerprint, - protocolVersion: 1, - runtimeEpoch: 'runtime_before_upgrade', - mutationReceipt: { - callerFingerprint: existingFingerprint, - requestId: 'request_existing_remote', - method: 'orchestration.federationAttachStart', - payloadHash: 'hash_existing_remote' - } - }) - const replies: Record[] = [] - - try { - await server['handleWebSocketMessage']( - JSON.stringify( - withCurrentOrchestrationContract({ - id: 'show-existing-remote', - method: 'orchestration.federationShow', - params: { dispatchId: 'ctx_existing_remote' } - }) - ), - (response) => replies.push(JSON.parse(response) as Record), - () => {}, - undefined, - undefined, - device.token - ) - - expect(replies[0]).toMatchObject({ - ok: true, - result: { dispatchId: 'ctx_existing_remote', attachment: { state: 'starting' } } - }) - } finally { - db.close() - await server.stop() - } - }) - it('rejects requests with the wrong auth token', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService() diff --git a/src/main/runtime/rpc/server/runtime-rpc-ssh-wedge-isolation.test.ts b/src/main/runtime/rpc/server/runtime-rpc-ssh-wedge-isolation.test.ts index 50727a0343d..9dcc5fc034b 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-ssh-wedge-isolation.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-ssh-wedge-isolation.test.ts @@ -1,4 +1,4 @@ -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -9,7 +9,6 @@ import { readRuntimeMetadata } from './runtime-metadata' import { OrcaRuntimeRpcServer } from './runtime-rpc' import { STATUS_METHODS } from '../methods/host-management/status' import { SSH_METHODS } from '../methods/ssh/ssh' -import { sendRequest } from './runtime-rpc-test-harness' // Real socket probes must stay responsive while SSH is wedged on headless serve (#31179). const { connectMock, removeMock } = vi.hoisted(() => { @@ -113,38 +112,6 @@ function openPipelinedSocket(endpoint: string): { } describe('runtime RPC with a wedged SSH layer (#31179)', () => { - it('answers probes on fresh connections while SSH dispatches never settle', async () => { - const { endpoint, token } = await startServer() - // More wedged dispatches than the long-poll cap: short RPCs must not hold admission slots. - for (let i = 0; i < 20; i += 1) { - const wedged = openPipelinedSocket(endpoint) - wedged.write({ - id: `wedged-${i}`, - authToken: token, - method: i % 2 === 0 ? 'ssh.connect' : 'ssh.removeTarget', - params: { targetId: 'ssh-1' } - }) - } - await vi.waitFor(() => - expect(connectMock.mock.calls.length + removeMock.mock.calls.length).toBe(20) - ) - - await expect( - sendRequest(endpoint, { id: 'list', authToken: token, method: 'ssh.listTargets' }) - ).resolves.toMatchObject({ ok: true, result: { targets: [{ id: 'ssh-1' }] } }) - await expect( - sendRequest(endpoint, { - id: 'state', - authToken: token, - method: 'ssh.getState', - params: { targetId: 'ssh-1' } - }) - ).resolves.toMatchObject({ ok: true, result: { state: { status: 'reconnecting' } } }) - await expect( - sendRequest(endpoint, { id: 'status', authToken: token, method: 'status.get' }) - ).resolves.toMatchObject({ ok: true }) - }) - it('answers a probe pipelined behind a wedged dispatch on the same connection', async () => { const { endpoint, token } = await startServer() const session = openPipelinedSocket(endpoint) diff --git a/src/main/runtime/rpc/server/runtime-rpc-startup-failure.ts b/src/main/runtime/rpc/server/runtime-rpc-startup-failure.ts index e2a81fa115d..4f079f9b7fb 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-startup-failure.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-startup-failure.ts @@ -3,7 +3,7 @@ import { dialog, type BrowserWindow, type MessageBoxOptions } from 'electron' import type { RuntimeRpcStartErrorClass } from '../../../../shared/telemetry-daemon-event-schemas' import { translateMain } from '../../../i18n/main-i18n' import { track } from '../../../telemetry/client' -import { waitForWindowToShow } from '../../../window/wait-for-window-to-show' +import { waitForWindowToShow } from '../../../window/visibility/wait-for-window-to-show' const MAX_VISIBLE_CAUSE_LENGTH = 500 diff --git a/src/main/runtime/rpc/server/runtime-rpc-state.ts b/src/main/runtime/rpc/server/runtime-rpc-state.ts index 8edc4ff2ef8..9006bde0562 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-state.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-state.ts @@ -8,11 +8,11 @@ import type { WebSocket } from 'ws' import type { DeviceRegistry } from './pairing/device-registry' import type { E2EEKeypair } from './pairing/e2ee-keypair' import type { RuntimeHostDescriptor } from '../../../../shared/remote-runtime/host-status/runtime-host-descriptor' -import type { UnpairedDeviceAuthThrottle } from '../unpaired-device-auth-throttle' -import type { MobileSocketWiring } from '../mobile-socket-wiring' +import type { UnpairedDeviceAuthThrottle } from '../mobile/unpaired-device-auth-throttle' +import type { MobileSocketWiring } from '../mobile/mobile-socket-wiring' import type { MobileDesktopRelay } from '../../mobile-desktop-relay/mobile-desktop-relay' import type { MobileRelayHostCatalog } from '../../mobile-desktop-relay/mobile-relay-host-catalog' -import { RelayRevokeOutbox } from '../../mobile-cloud-relay/relay-revoke-outbox' +import { RelayRevokeOutbox } from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' import { PushUnregisterOutbox } from '../../push/push-unregister-outbox' import { RuntimeBinaryMessageRouter } from './runtime-binary-message-router' @@ -38,7 +38,7 @@ import { import { DeclaredDesktopClients } from './pairing/declared-desktop-clients' import { AuthenticatedSourceRecorder } from './network-source-policy-store' import type { ServeNetworkSourceOptions } from './serve-network-source-policy' -import type { WebSocketSourceGuard } from '../ws-network-source-guard' +import type { WebSocketSourceGuard } from '../transports/websocket/source-admission/ws-network-source-guard' export class RuntimeRpcState { protected readonly runtime: OrcaRuntimeService diff --git a/src/main/runtime/rpc/server/runtime-rpc-websocket-bind-host.test.ts b/src/main/runtime/rpc/server/runtime-rpc-websocket-bind-host.test.ts deleted file mode 100644 index e9e25652961..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-websocket-bind-host.test.ts +++ /dev/null @@ -1,339 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' -import { mkdtempSync } from 'node:fs' -import 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import WebSocket from 'ws' -import { OrcaRuntimeService } from '../../orca-runtime' -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { WebSocketTransport } from '../ws-transport' -import { DeviceRegistry } from './pairing/device-registry' -import './pairing/mobile-pairing-files' - -vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: listings.listWorktrees - } -}) - -vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: listings.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - function createWorktreeListingMocks() { - const worktrees = [ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/foo', - isBare: false, - isMainWorktree: false - } - ] - return { - listWorktrees: vi.fn().mockResolvedValue(worktrees), - listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) - } - } - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -describe('OrcaRuntimeRpcServer WebSocket bind host (STA-2370)', () => { - const wsTransportOf = (server: OrcaRuntimeRpcServer): WebSocketTransport | undefined => - (server['activeTransports'] as unknown[]).find( - (transport): transport is WebSocketTransport => transport instanceof WebSocketTransport - ) - - it('stays on loopback at startup after a "This computer only" grant has connected', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - // Local-only browser grants also get lastSeenAt; counting them would expose every interface on next launch against the chosen policy. - const registry = new DeviceRegistry(userDataPath) - const device = registry.getOrCreatePendingDevice('Runtime local', 'runtime', 'this-computer') - registry.updateLastSeen(device.deviceId) - - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - - await server.start() - try { - expect(wsTransportOf(server)?.resolvedHost).toBe('127.0.0.1') - } finally { - await server.stop() - } - }) - - it('upgrades a reused pending grant to network reach so its link survives a relaunch', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - - await server.start() - let deviceId: string - try { - const local = server.createPairingOffer({ - address: '127.0.0.1', - scope: 'runtime', - reach: 'this-computer' - }) - expect(local.available).toBe(true) - // Re-advertised pending tokens gaining network reach need that policy persisted or restart leaves LAN unserved. - const network = server.createPairingOffer({ - address: '100.64.1.20', - scope: 'runtime', - reach: 'network' - }) - expect(network.available).toBe(true) - deviceId = network.available ? network.deviceId : '' - expect(deviceId).toBe(local.available ? local.deviceId : '') - server.getDeviceRegistry()?.updateLastSeen(deviceId) - } finally { - await server.stop() - } - - const relaunched = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - await relaunched.start() - try { - expect(wsTransportOf(relaunched)?.resolvedHost).toBe('0.0.0.0') - } finally { - await relaunched.stop() - } - }) - - it('keeps the pinned port when a later widen tears down a live loopback client', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - - await server.start() - try { - const loopbackPort = wsTransportOf(server)!.resolvedPort - // Local-only clients can precede LAN opt-in; rebind disconnects them, so reuse the port for their existing links. - const client = new WebSocket(`ws://127.0.0.1:${loopbackPort}`) - await new Promise((resolve, reject) => { - client.once('open', () => resolve()) - client.once('error', reject) - }) - const closed = new Promise((resolve) => client.once('close', () => resolve())) - - await server.ensureNetworkExposure() - await closed - - expect(wsTransportOf(server)?.resolvedHost).toBe('0.0.0.0') - expect(wsTransportOf(server)?.resolvedPort).toBe(loopbackPort) - - const reconnected = new WebSocket(`ws://127.0.0.1:${loopbackPort}`) - await new Promise((resolve, reject) => { - reconnected.once('open', () => resolve()) - reconnected.once('error', reject) - }) - reconnected.close() - } finally { - await server.stop() - } - }) - - it('reports pairing unavailable but keeps a serving loopback listener when the widen bind fails', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - - await server.start() - try { - const loopbackPort = wsTransportOf(server)?.resolvedPort - // Fail wide bind after loopback stops, then allow same-port loopback recovery so serving and retry survive. - const target = server as unknown as { - startWebSocketTransport: (opts: { host: string }) => Promise - wsBoundHost: string | null - } - const original = target.startWebSocketTransport.bind(server) - vi.spyOn(target, 'startWebSocketTransport').mockImplementation(async (opts) => { - if (opts.host === '0.0.0.0') { - throw new Error('injected wide bind failure') - } - return original(opts) - }) - - const offer = await server.createMobilePairingOffer({ - address: '100.64.1.20', - connectionMode: 'local-only' - }) - // Failed exposure must return unavailable rather than advertise an unserved LAN endpoint (STA-2370). - expect(offer.available).toBe(false) - if (!offer.available) { - expect(offer.reason).toBe('network_exposure_failed') - } - // Recovery must keep loopback serving at the original port. - expect(wsTransportOf(server)?.resolvedHost).toBe('127.0.0.1') - expect(wsTransportOf(server)?.resolvedPort).toBe(loopbackPort) - // Retain loopback bound-host state so the next offer retries. - expect(target.wsBoundHost).toBe('127.0.0.1') - } finally { - await server.stop() - errorSpy.mockRestore() - } - }) - - it('keeps the widened listener tracked when persisting pairing metadata fails', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - - await server.start() - try { - // Fail metadata persistence after successful wide bind; keep that listener tracked for shutdown, never orphaned by loopback recovery. - const target = server as unknown as { - writeMetadata: () => void - wsBoundHost: string | null - activeTransports: unknown[] - } - let injected = false - const originalWrite = target.writeMetadata.bind(server) - vi.spyOn(target, 'writeMetadata').mockImplementation(() => { - if (!injected && target.wsBoundHost === '0.0.0.0') { - injected = true - throw new Error('injected metadata write failure') - } - return originalWrite() - }) - - const offer = await server.createMobilePairingOffer({ - address: '100.64.1.20', - connectionMode: 'local-only' - }) - expect(injected).toBe(true) - // Wide listener already succeeded; metadata failure must preserve available pairing and exactly one tracked transport. - expect(offer.available).toBe(true) - expect(wsTransportOf(server)?.resolvedHost).toBe('0.0.0.0') - expect(target.activeTransports.filter((t) => t instanceof WebSocketTransport)).toHaveLength(1) - } finally { - await server.stop() - errorSpy.mockRestore() - } - }) - - it('does not strand a wide listener when stop() races an in-flight widen', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - - await server.start() - - const target = server as unknown as { - startWebSocketTransport: (opts: { - host: string - }) => Promise<{ transport: WebSocketTransport; endpoint: string }> - activeTransports: unknown[] - } - const original = target.startWebSocketTransport.bind(server) - let releaseWideStart: () => void = () => {} - const wideStartGate = new Promise((resolve) => { - releaseWideStart = resolve - }) - let wideStopSpy: ReturnType = null - vi.spyOn(target, 'startWebSocketTransport').mockImplementation(async (opts) => { - if (opts.host === '0.0.0.0') { - // Hold rebind after loopback stop to race shutdown against pending exposure. - await wideStartGate - const result = await original(opts) - wideStopSpy = vi.spyOn(result.transport, 'stop') - return result - } - return original(opts) - }) - - // Start shutdown while exposure is still in flight. - const widen = server.ensureNetworkExposure() - const stopping = server.stop() - releaseWideStart() - await Promise.all([widen.catch(() => {}), stopping]) - - try { - // Shutdown must await/fence exposure before snapshotting transports or a late wide bind leaks past stop (STA-2370). - expect(target.activeTransports).toHaveLength(0) - expect(wideStopSpy).not.toBeNull() - expect(wideStopSpy).toHaveBeenCalled() - } finally { - errorSpy.mockRestore() - } - }) - - it('refuses a runtime-widening pairing offer while the bind is pinned to loopback', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0, - pinnedBindHost: '127.0.0.1' - }) - - await server.start() - try { - // Remote pairing RPCs must not override the operator's bind pin. - const offer = await server.createMobilePairingOffer({ - address: '100.64.1.20', - connectionMode: 'local-only' - }) - expect(offer.available).toBe(false) - if (!offer.available) { - expect(offer.reason).toBe('network_exposure_failed') - } - expect(wsTransportOf(server)?.resolvedHost).toBe('127.0.0.1') - } finally { - await server.stop() - errorSpy.mockRestore() - } - }) -}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-websocket-dispatch.ts b/src/main/runtime/rpc/server/runtime-rpc-websocket-dispatch.ts index 6ddd445e5e3..7f20aa95723 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-websocket-dispatch.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-websocket-dispatch.ts @@ -6,18 +6,18 @@ import type { import { callerScopeOf, devicePrincipalOf } from './pairing/device-principal' import { registerSocketDeviceKey } from './runtime-rpc-device-key-registration' import { exchangeSocketPairingTicket } from './runtime-rpc-pairing-ticket-exchange' -import type { AuthenticatedMobileSocket } from '../mobile-socket-wiring' +import type { AuthenticatedMobileSocket } from '../mobile/mobile-socket-wiring' import type { RpcRequest, RpcResponse } from '../core' -import type { WebSocketTransport } from '../ws-transport' +import type { WebSocketTransport } from '../transports/websocket/ws-transport' import type { DeviceScope } from '../../../../shared/runtime-session-contracts' import { RuntimeRpcMobileDevices } from './runtime-rpc-mobile-devices' import { classifyRuntimeLongPoll } from './runtime-rpc-long-poll' -import type { RpcBinarySender } from '../rpc-binary-sender' +import type { RpcBinarySender } from '../transports/rpc-binary-sender' import { limitRuntimeRpcReplySize } from './runtime-rpc-reply-size-limit' import { MOBILE_RPC_METHOD_ALLOWLIST } from './runtime-rpc-mobile-method-allowlist' import { MOBILE_RPC_METHOD_ROUTES } from './runtime-rpc-mobile-method-routing' import { parseExecutionHostId } from '../../../../shared/execution-host' -import { WorktreeRemove } from '../../../../shared/rpc-contract/worktree-params' +import { WorktreeRemove } from '../../../../shared/rpc-contract/workspaces/worktree-params' // Stamp proven scope at transport boundary; status.get has no connection context. function injectDeviceScope(response: string, scope: DeviceScope): string { diff --git a/src/main/runtime/rpc/server/runtime-rpc-websocket-fallback-port.test.ts b/src/main/runtime/rpc/server/runtime-rpc-websocket-fallback-port.test.ts index b12529625ce..78d82483610 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-websocket-fallback-port.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-websocket-fallback-port.test.ts @@ -1,13 +1,13 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { existsSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../orca-runtime' import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { WebSocketTransport } from '../ws-transport' +import { WebSocketTransport } from '../transports/websocket/ws-transport' vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { const facade = getWorktreeListingMocks() diff --git a/src/main/runtime/rpc/server/runtime-rpc-websocket-reply-size-limit.test.ts b/src/main/runtime/rpc/server/runtime-rpc-websocket-reply-size-limit.test.ts deleted file mode 100644 index 3520df61319..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-websocket-reply-size-limit.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type WebSocket from 'ws' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../orca-runtime' -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { DeviceRegistry } from './pairing/device-registry' -import { FILE_METHODS } from '../methods/files/files' -import { E2EEChannel } from '../e2ee-channel' -import { - decrypt, - deriveSharedKey, - encrypt, - generateKeyPair -} from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../shared/remote-runtime/remote-runtime-memory-limits' - -import { RUNTIME_RPC_REPLY_TOO_LARGE_CODE } from './runtime-rpc-reply-size-limit' - -function createServer() { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-reply-size-')) - const runtime = new OrcaRuntimeService() - const server = new OrcaRuntimeRpcServer({ - runtime, - methods: FILE_METHODS, - userDataPath, - enableWebSocket: false - }) - server['deviceRegistry'] = new DeviceRegistry(userDataPath) - const device = server['deviceRegistry'].addDevice('paired-desktop', 'runtime') - return { runtime, server, device } -} - -/** Routes the server's replies through a real, authenticated E2EE channel, as a paired client sees them. */ -function connectEncryptedChannel() { - const serverKeys = generateKeyPair() - const clientKeys = generateKeyPair() - const sent: string[] = [] - const ws = { - OPEN: 1, - readyState: 1, - send: vi.fn((data: string) => sent.push(data)), - close: vi.fn() - } - const onError = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: E2EEChannel only reads OPEN/readyState and calls send/close, all provided. - const channel = new E2EEChannel(ws as unknown as WebSocket, { - serverSecretKey: serverKeys.secretKey, - resolveAuthenticatedDevice: (token) => ({ - deviceId: 'd', - deviceToken: token, - scope: 'runtime', - clientId: token, - callerFingerprint: 'test-fingerprint', - credentialRevision: 0 - }), - onReady: vi.fn(), - onError - }) - channel.handleRawMessage( - JSON.stringify({ - type: 'e2ee_hello', - publicKeyB64: Buffer.from(clientKeys.publicKey).toString('base64') - }) - ) - const sharedKey = deriveSharedKey(clientKeys.secretKey, serverKeys.publicKey) - channel.handleRawMessage( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'tok' }), sharedKey) - ) - const handshakeFrames = sent.length - return { - channel, - sharedKey, - onError, - replies: () => - sent - .slice(handshakeFrames) - .map((frame): unknown => JSON.parse(decrypt(frame, sharedKey) ?? 'null')) - } -} - -describe('remote RPC replies over the encrypted channel', () => { - const servers: OrcaRuntimeRpcServer[] = [] - afterEach(async () => { - await Promise.all(servers.splice(0).map((server) => server.stop())) - vi.restoreAllMocks() - }) - - it('answers any other oversized reply with a per-request error', async () => { - const { server, device } = createServer() - servers.push(server) - vi.spyOn(server['dispatcher'], 'dispatchStreaming').mockImplementation( - async (request, reply) => { - reply( - JSON.stringify({ - id: request.id, - ok: true, - result: 'x'.repeat(REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES) - }) - ) - } - ) - const encrypted = connectEncryptedChannel() - encrypted.channel.onMessage((plaintext, reply, sendBinary) => { - void server['handleWebSocketMessage']( - plaintext, - reply, - sendBinary, - undefined, - undefined, - device.token - ) - }) - - encrypted.channel.handleRawMessage( - encrypt( - JSON.stringify({ id: 'big', method: 'agentSessions.list', params: {} }), - encrypted.sharedKey - ) - ) - await vi.waitFor(() => expect(encrypted.replies()).toHaveLength(1)) - - expect(encrypted.onError).not.toHaveBeenCalled() - expect(encrypted.replies()[0]).toMatchObject({ - id: 'big', - ok: false, - error: { code: RUNTIME_RPC_REPLY_TOO_LARGE_CODE } - }) - }) -}) diff --git a/src/main/runtime/rpc/server/serve-network-source-policy.ts b/src/main/runtime/rpc/server/serve-network-source-policy.ts index daab1a2af53..464bb1b83c6 100644 --- a/src/main/runtime/rpc/server/serve-network-source-policy.ts +++ b/src/main/runtime/rpc/server/serve-network-source-policy.ts @@ -1,8 +1,11 @@ // Which source addresses `orca serve` accepts, decided once at startup. import { classifyRemotePairingHostname } from '../../../../shared/remote-runtime/pairing/remote-pairing-address' import { resolveAdvertisedPairingHostname } from './pairing/network/pairing-endpoint' -import { classifyNetworkSource } from '../network-source-class' -import { PublicSourceRefusal, type WebSocketSourceGuard } from '../ws-network-source-guard' +import { classifyNetworkSource } from '../transports/websocket/source-admission/network-source-class' +import { + PublicSourceRefusal, + type WebSocketSourceGuard +} from '../transports/websocket/source-admission/ws-network-source-guard' import type { DeviceEntry } from './pairing/device-entry' import { ensureNetworkSourceGuardSince, diff --git a/src/main/runtime/rpc/shadowed-port-probe.test.ts b/src/main/runtime/rpc/shadowed-port-probe.test.ts deleted file mode 100644 index 7e60cc602d7..00000000000 --- a/src/main/runtime/rpc/shadowed-port-probe.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { createServer, type Server } from 'node:net' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { assertPortNotShadowingListener } from './shadowed-port-probe' -import * as shadowedPortProbe from './shadowed-port-probe' -import { WebSocketTransport } from './ws-transport' - -const servers: Server[] = [] -const transports: WebSocketTransport[] = [] - -async function listen(host: string, port = 0): Promise { - const server = createServer((socket) => socket.destroy()) - servers.push(server) - await new Promise((resolve) => server.listen(port, host, resolve)) - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('no port') - } - return address.port -} - -async function freePort(): Promise { - const server = createServer() - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - await new Promise((resolve) => server.close(() => resolve())) - if (!address || typeof address === 'string') { - throw new Error('no port') - } - return address.port -} - -afterEach(async () => { - await Promise.all(transports.splice(0).map((transport) => transport.stop())) - await Promise.all( - servers.splice(0).map((server) => new Promise((resolve) => server.close(() => resolve()))) - ) -}) - -describe('assertPortNotShadowingListener', () => { - it('reports a port another process answers on as in use', async () => { - const port = await listen('0.0.0.0') - - await expect(assertPortNotShadowingListener('127.0.0.1', port)).rejects.toMatchObject({ - code: 'EADDRINUSE', - port - }) - }) - - it('lets a free port through', async () => { - await expect(assertPortNotShadowingListener('127.0.0.1', await freePort())).resolves.toBe( - undefined - ) - }) - - it('leaves wildcard binds and OS-assigned ports to the kernel', async () => { - const port = await listen('0.0.0.0') - - await expect(assertPortNotShadowingListener('0.0.0.0', port)).resolves.toBe(undefined) - await expect(assertPortNotShadowingListener('127.0.0.1', 0)).resolves.toBe(undefined) - }) -}) - -describe('WebSocketTransport beside a wildcard listener', () => { - it('moves past a port another runtime serves on every interface instead of shadowing it', async () => { - // Windows/macOS allow loopback binds over another process's wildcard, stealing paired clients' desktop-runtime traffic. - const heldPort = await listen('0.0.0.0') - const nextPort = await freePort() - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: heldPort, - fallbackLadder: [nextPort] - }) - transports.push(transport) - - const probe = vi.spyOn(shadowedPortProbe, 'assertPortNotShadowingListener') - try { - await transport.start() - - expect(transport.resolvedPort).toBe(nextPort) - // Linux rejects the overlap itself, so the selected port alone cannot prove the preflight ran. - expect(probe).toHaveBeenCalledWith('127.0.0.1', heldPort) - } finally { - probe.mockRestore() - } - }) -}) diff --git a/src/main/runtime/rpc/agent-launch-feature-requirement.ts b/src/main/runtime/rpc/startup/agent-launch-feature-requirement.ts similarity index 89% rename from src/main/runtime/rpc/agent-launch-feature-requirement.ts rename to src/main/runtime/rpc/startup/agent-launch-feature-requirement.ts index d695a7a407b..2862d25503e 100644 --- a/src/main/runtime/rpc/agent-launch-feature-requirement.ts +++ b/src/main/runtime/rpc/startup/agent-launch-feature-requirement.ts @@ -1,5 +1,5 @@ -import { recognizeAgentLaunchCommand } from '../../../shared/agent-launch/startup/agent-command-line-intent' -import type { OrcadFeature } from './orcad-feature-readiness' +import { recognizeAgentLaunchCommand } from '../../../../shared/agent-launch/startup/agent-command-line-intent' +import type { OrcadFeature } from './orcad-readiness' const ACCOUNTS: readonly OrcadFeature[] = ['accounts'] const NONE: readonly OrcadFeature[] = [] diff --git a/src/main/runtime/rpc/dispatcher-feature-readiness.test.ts b/src/main/runtime/rpc/startup/dispatcher-feature-readiness.test.ts similarity index 97% rename from src/main/runtime/rpc/dispatcher-feature-readiness.test.ts rename to src/main/runtime/rpc/startup/dispatcher-feature-readiness.test.ts index 0faeb4065ce..ecfdc06ba24 100644 --- a/src/main/runtime/rpc/dispatcher-feature-readiness.test.ts +++ b/src/main/runtime/rpc/startup/dispatcher-feature-readiness.test.ts @@ -1,14 +1,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { z } from 'zod' -import { RpcDispatcher } from './dispatcher' -import { defineMethod, defineStreamingMethod, type RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' +import { RpcDispatcher } from '../dispatcher' +import { defineMethod, defineStreamingMethod, type RpcRequest } from '../core' +import type { OrcaRuntimeService } from '../../orca-runtime' import { ensureAgentSessionFeatureRequirement } from './agent-launch-feature-requirement' import { _resetOrcadFeatureReadinessForTests, installOrcadFeatureReadiness, ORCAD_FEATURE_WAIT_MS -} from './orcad-feature-readiness' +} from './orcad-readiness' const request = (method: string, params: unknown = {}): RpcRequest => ({ id: 'r1', diff --git a/src/main/runtime/rpc/orcad-feature-readiness.ts b/src/main/runtime/rpc/startup/orcad-readiness.ts similarity index 100% rename from src/main/runtime/rpc/orcad-feature-readiness.ts rename to src/main/runtime/rpc/startup/orcad-readiness.ts diff --git a/src/main/runtime/rpc/startup-phase-wait.ts b/src/main/runtime/rpc/startup/startup-phase-wait.ts similarity index 100% rename from src/main/runtime/rpc/startup-phase-wait.ts rename to src/main/runtime/rpc/startup/startup-phase-wait.ts diff --git a/src/main/runtime/rpc/static-web-client-handler-stream.test.ts b/src/main/runtime/rpc/static-web-client-handler-stream.test.ts deleted file mode 100644 index 86dfd3faa86..00000000000 --- a/src/main/runtime/rpc/static-web-client-handler-stream.test.ts +++ /dev/null @@ -1,215 +0,0 @@ -import { once } from 'node:events' -import type * as fs from 'node:fs' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync, type ReadStream } from 'node:fs' -import type * as fsPromises from 'node:fs/promises' -import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createStaticWebClientHandler } from './static-web-client-handler' - -const observed = vi.hoisted(() => { - const streams: ReadStream[] = [] - const state: { - statWait: Promise - statError?: Error - missingPath?: string - onSource?: () => void - } = { - statWait: Promise.resolve() - } - return { streams, state, statCalls: 0, completedStats: 0 } -}) -vi.mock('node:fs', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - createReadStream: (...args: Parameters) => { - const stream = original.createReadStream(observed.state.missingPath ?? args[0], args[1]) - observed.streams.push(stream) - observed.state.onSource?.() - return stream - } - } -}) -vi.mock('node:fs/promises', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - stat: async (...args: Parameters) => { - observed.statCalls++ - const value = await original.stat(...args) - await observed.state.statWait - observed.completedStats++ - if (observed.state.statError) { - throw observed.state.statError - } - return value - } - } -}) - -let root: string -const servers: Server[] = [] -beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'orca-static-web-stream-')) - mkdirSync(join(root, 'assets')) - writeFileSync(join(root, 'assets', 'fixture.js'), Buffer.alloc(1024 * 1024, 1)) - writeFileSync(join(root, 'web-index.html'), 'web') - observed.state.statWait = Promise.resolve() - observed.state.statError = undefined - observed.state.missingPath = undefined - observed.state.onSource = undefined - observed.statCalls = 0 - observed.completedStats = 0 -}) -afterEach(async () => { - await Promise.all( - servers.splice(0).map(async (server) => { - server.closeAllConnections() - await new Promise((resolve) => server.close(() => resolve())) - }) - ) - await Promise.all( - observed.streams.splice(0).map(async (stream) => { - if (!stream.closed) { - const closed = new Promise((resolve) => stream.once('close', resolve)) - stream.destroy() - await closed - } - }) - ) - rmSync(root, { recursive: true, force: true }) -}) - -function fakeResponse() { - return Object.assign(new PassThrough({ highWaterMark: 16 }), { - setHeader: vi.fn(), - statusCode: 0, - headersSent: false - }) -} -function fileDescriptor(stream: ReadStream): number | null { - if ('fd' in stream && (typeof stream.fd === 'number' || stream.fd === null)) { - return stream.fd - } - throw new Error('Missing file descriptor') -} -function request(response = fakeResponse()) { - const handler = createStaticWebClientHandler(root) - handler( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This handler reads only these method/url fields. - { method: 'GET', url: '/assets/fixture.js' } as IncomingMessage, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture implements the writable response surface used by this handler. - response as unknown as ServerResponse - ) - return response -} -async function latestSource(count: number): Promise { - await expect.poll(() => observed.streams.length).toBe(count) - const source = observed.streams.at(-1) - if (!source) { - throw new Error('Missing file stream') - } - return source -} -async function startServer(): Promise { - const server = createServer(createStaticWebClientHandler(root)) - servers.push(server) - server.listen(0, '127.0.0.1') - await once(server, 'listening') - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('Missing HTTP address') - } - return `http://127.0.0.1:${address.port}` -} - -it('closes 25 abandoned file readers and removes only owned response listeners', async () => { - const responses: ReturnType[] = [] - const otherClose = vi.fn() - const otherError = vi.fn() - for (let index = 0; index < 25; index++) { - const response = fakeResponse() - response.on('close', otherClose) - response.on('error', otherError) - request(response) - responses.push(response) - const source = await latestSource(index + 1) - await expect.poll(() => source.isPaused()).toBe(true) - const closed = once(response, 'close') - response.destroy() - await closed - } - await expect.poll(() => observed.streams.filter((stream) => !stream.closed).length).toBe(0) - expect(observed.streams.every((stream) => fileDescriptor(stream) === null)).toBe(true) - expect(responses.every((response) => response.listeners('close').length === 1)).toBe(true) - expect(responses.every((response) => response.listeners('error').length === 1)).toBe(true) - expect(otherClose).toHaveBeenCalledTimes(25) - expect(otherError).not.toHaveBeenCalled() -}) - -it.each(['success', 'failure'])( - 'does not revive a response closed during stat %s', - async (outcome) => { - let releaseStat = (): void => {} - observed.state.statWait = new Promise((resolve) => { - releaseStat = resolve - }) - if (outcome === 'failure') { - observed.state.statError = new Error('stat failed after abandonment') - } - const response = request() - expect(observed.statCalls).toBe(1) - const ended = vi.spyOn(response, 'end') - const closed = once(response, 'close') - response.destroy() - await closed - releaseStat() - await expect.poll(() => observed.completedStats).toBe(1) - expect(observed.streams).toHaveLength(0) - expect(response.setHeader).not.toHaveBeenCalled() - expect(ended).not.toHaveBeenCalled() - } -) - -it('closes a file that is still opening when its response is destroyed', async () => { - const response = fakeResponse() - observed.state.onSource = () => { - const source = observed.streams.at(-1) - expect(source && fileDescriptor(source)).toBe(null) - response.destroy() - } - request(response) - const source = await latestSource(1) - await expect.poll(() => source.closed).toBe(true) - expect(fileDescriptor(source)).toBe(null) - expect(response.listenerCount('close')).toBe(0) - expect(response.listenerCount('error')).toBe(0) -}) - -it('disconnects a response when its source fails after headers', async () => { - const response = request() - const source = await latestSource(1) - response.headersSent = true - const closed = once(response, 'close') - source.destroy(new Error('read failed after headers')) - await closed - await expect.poll(() => source.closed).toBe(true) - expect(response.statusCode).toBe(200) - expect(response.destroyed).toBe(true) - expect(response.listenerCount('close')).toBe(0) - expect(response.listenerCount('error')).toBe(0) -}) - -it('answers an actual file-open error with an empty 500 instead of the asset length', async () => { - observed.state.missingPath = join(root, 'missing-after-stat.js') - const url = await startServer() - const response = await fetch(`${url}/assets/fixture.js`) - expect(response.status).toBe(500) - expect(response.headers.get('content-length')).toBe('0') - expect(response.headers.get('cache-control')).toBe('no-store') - expect(await response.text()).toBe('') - await expect.poll(() => observed.streams.every((source) => source.closed)).toBe(true) -}) diff --git a/src/main/runtime/rpc/static-web-client-shared-assets.test.ts b/src/main/runtime/rpc/static-web-client-shared-assets.test.ts deleted file mode 100644 index ccaca342313..00000000000 --- a/src/main/runtime/rpc/static-web-client-shared-assets.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { once } from 'node:events' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { createStaticWebClientHandler } from './static-web-client-handler' - -const roots: string[] = [] -const servers: Server[] = [] -afterEach(async () => { - await Promise.all( - servers.splice(0).map((server) => { - server.closeAllConnections() - return new Promise((resolve) => server.close(() => resolve())) - }) - ) - roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) -}) -function fixture() { - const root = mkdtempSync(join(tmpdir(), 'orca-shared-static-')) - roots.push(root) - const renderer = join(root, 'renderer') - const files = [ - 'web-index.html', - 'assets/shared.js', - 'assets/editor.worker.js', - 'cmaps/Font.bcmap', - 'standard_fonts/Font.pfb', - 'wasm/viewer.wasm' - ] - for (const file of [ - ...files, - 'index.html', - 'popout.html', - 'space.html', - 'assets/desktop.js', - 'assets/shared.js.map' - ]) { - mkdirSync(dirname(join(renderer, file)), { recursive: true }) - writeFileSync(join(renderer, file), file) - } - writeFileSync(join(renderer, '.orca-web-client-files.json'), JSON.stringify(files)) - return { renderer, files } -} -async function serve(root: string) { - const server = createServer(createStaticWebClientHandler(root)) - servers.push(server) - server.listen(0, '127.0.0.1') - await once(server, 'listening') - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('No address') - } - return `http://127.0.0.1:${address.port}` -} -it('serves only the web closure at root and through a reverse proxy, including worker/PDF files', async () => { - const { renderer, files } = fixture() - const endpoint = await serve(renderer) - for (const prefix of ['', '/proxy/orca']) { - for (const file of files) { - const response = await fetch(`${endpoint}${prefix}/${file}`) - expect(response.status, `${prefix}/${file}`).toBe(200) - expect(await response.text()).toBe(file) - } - for (const file of [ - 'popout.html', - 'space.html', - 'assets/desktop.js', - 'assets/shared.js.map', - '.orca-web-client-files.json' - ]) { - expect((await fetch(`${endpoint}${prefix}/${file}`)).status, file).toBe(404) - } - } - expect(await (await fetch(endpoint)).text()).toBe('web-index.html') - const head = await fetch(`${endpoint}/assets/shared.js`, { method: 'HEAD' }) - expect(head.headers.get('content-length')).toBe(String('assets/shared.js'.length)) - expect(await head.text()).toBe('') -}) -it('fails closed when a renderer has no manifest or a corrupt manifest', async () => { - const { renderer } = fixture() - rmSync(join(renderer, '.orca-web-client-files.json')) - const endpoint = await serve(renderer) - expect((await fetch(`${endpoint}/assets/desktop.js`)).status).toBe(404) -}) -it('disables only the browser client when the manifest is truncated or invalid', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - try { - for (const manifest of ['{', JSON.stringify(['../index.html'])]) { - const { renderer } = fixture() - writeFileSync(join(renderer, '.orca-web-client-files.json'), manifest) - const endpoint = await serve(renderer) - for (const file of ['', 'web-index.html', 'assets/shared.js', 'assets/desktop.js']) { - expect((await fetch(`${endpoint}/${file}`)).status, file).toBe(404) - } - } - expect(warn).toHaveBeenCalledTimes(2) - } finally { - warn.mockRestore() - } -}) diff --git a/src/main/runtime/rpc/structured-worker-cli.integration.test.ts b/src/main/runtime/rpc/structured-worker-cli.integration.test.ts deleted file mode 100644 index f54994c3da3..00000000000 --- a/src/main/runtime/rpc/structured-worker-cli.integration.test.ts +++ /dev/null @@ -1,435 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdir, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { activeProviderContext } from '../../../shared/agent-session/agent-session-provider-context' -import { isOrcaSessionId } from '../../../shared/orca-session-address' -import { getRuntimeMetadataPath } from '../../../shared/runtime-bootstrap' -import { structuredAgentSessionTabId } from '../../../shared/agent-session/view/structured-agent-session-projection' -import * as versionProbe from '../../agent-launch/preflight/agent-cli-version-probe' -import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { CODEX_MINIMUM_SUPPORTED_VERSION } from '../../../shared/codex-cli-installation' -import { CodexAppServerRequestError } from '../../codex/app-server/codex-app-server-request-error' - -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' - -import { scriptedCodexTransport } from '../orca-runtime-tests/scripted-codex-transport.test-fixture' -import { chatTabCommandsSettled } from '../orca-runtime-tests/session-layout-apply.test-fixture' -import { - AuthorityRuntime, - authorityProfile, - root, - savedIds -} from '../agent-session/lifecycle/structured-agent-session-tab-authority.test-support' -import { ensureStructuredAgentSessionHost } from '../agent-session/structured-agent-session-runtime' -import { - fakeCodex, - resetProviderFaults -} from '../orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture' -import { structuredWorkerIdentities } from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { releaseStructuredWorkerSession } from './methods/orchestration/structured-workers/orchestration-structured-worker-session' -import { AGENT_LAUNCH_METHODS } from './methods/agent-launch/agent-launch' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { STATUS_METHODS } from './methods/host-management/status' -import { WORKTREE_METHODS } from './methods/workspaces/worktree' -import { REPO_METHODS } from './methods/projects/repo' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { isRecord, resultOf } from './orchestration-session-caller-test-fixture' -import { UnixSocketTransport } from './unix-socket-transport' -import { removalPtyProvider } from './worktree-rm-pty.test-fixture' - -const cliPath = '../../../cli/index' -const { main }: { main: (argv: string[], cwd: string) => Promise } = await import(cliPath) -let rig: Awaited> -class CliRuntime extends AuthorityRuntime { - pointerDelivery() { - return this.orchestrationStructuredMailboxPointerDelivery - } -} -let runtime: CliRuntime -let host: StructuredAgentSessionHost -let db: OrchestrationDb -let codex: ReturnType -let socket: UnixSocketTransport | undefined -let runId: string -let finishTurns = true -let rejectNextTurn = false -const dispatches: string[] = [] -const requests: RpcRequest[] = [] - -beforeEach(async () => { - resetProviderFaults() - finishTurns = true - rejectNextTurn = false - rig = await authorityProfile([]) - await mkdir(join(root, 'codex-home')) - rig.profile.updateSettings({ - agentDefaultSurface: 'chat', - nativeChatInheritShellEnvironment: false, - agentCmdOverrides: { codex: process.execPath }, - agentWorkspaceTrustEnabled: false - }) - runtime = new CliRuntime(rig.profile, undefined, { - prepareCodexStructuredLaunch: () => join(root, 'codex-home') - }) - db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - codex = fakeCodex() - vi.spyOn(versionProbe, 'checkAgentCliVersion').mockResolvedValue({ - status: 'ready', - version: CODEX_MINIMUM_SUPPORTED_VERSION - }) - const openConnection: typeof codex.openConnection = async (...args) => { - const connection = await codex.openConnection(...args) - const request = connection.request.bind(connection) - connection.request = async (method, params) => { - if (method === 'turn/start' && rejectNextTurn) { - rejectNextTurn = false - throw new CodexAppServerRequestError('turn/start', -32000, 'Task refused', 'Task refused') - } - const response = await request(method, params) - if ( - method === 'turn/start' && - isRecord(params) && - isRecord(response) && - isRecord(response.turn) - ) { - const turnId = response.turn.id - const clientUserMessageId = params.clientUserMessageId - if (typeof turnId !== 'string' || typeof clientUserMessageId !== 'string') { - throw new Error('expected string turn and user message identities') - } - setTimeout(() => { - args[1]?.onNotification?.('turn/started', { turn: { id: turnId } }) - args[1]?.onNotification?.('item/completed', { - item: { - type: 'userMessage', - id: `echo-${clientUserMessageId}`, - clientId: clientUserMessageId, - content: [{ type: 'text', text: 'CLI worker brief' }] - } - }) - args[1]?.onNotification?.('item/completed', { - item: { - type: 'agentMessage', - id: `answer-${turnId}`, - text: 'READY from bounded provider' - } - }) - if (finishTurns) { - args[1]?.onNotification?.('turn/completed', { turn: { id: turnId } }) - } - }, 0) - } - return response - } - return connection - } - host = await ensureStructuredAgentSessionHost({ - logger: createStructuredAgentSessionLogger(), - stateDirectory: root, - hostId: 'local', - claimKeyId: 'cli-test', - resolveWorkspacePath: async () => root, - resolveCodexCommand: () => ({ command: process.execPath, prefixArgs: [] }), - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }), - resolveEnvironment: async () => ({ PATH: '/usr/bin' }), - ...scriptedCodexTransport(openConnection), - onRequestFailure: (failure) => runtime.onStructuredRequestFailureForErrorMail(failure), - onSessionStatusChanged: (summary) => runtime.onStructuredSessionStatusForMail(summary), - onSessionTabHidden: (id) => runtime.onStructuredSessionTabHidden(id) - }) - vi.spyOn(runtime, 'getLocalProvider').mockReturnValue(removalPtyProvider([]).provider) - for (const key of [ - 'ORCA_PAIRING_CODE', - 'ORCA_ENVIRONMENT', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_PANE_KEY', - 'ORCA_AGENT_SESSION_ID', - 'ORCA_ORCHESTRATION_RUN_ID' - ]) { - vi.stubEnv(key, undefined) - } - vi.stubEnv('ORCA_USER_DATA_PATH', root) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const dispatcher = new RpcDispatcher({ - runtime, - methods: [ - ...STATUS_METHODS, - ...WORKTREE_METHODS, - ...REPO_METHODS, - ...AGENT_LAUNCH_METHODS, - ...ORCHESTRATION_METHODS - ] - }) - requests.length = 0 - const kind = process.platform === 'win32' ? 'named-pipe' : 'unix' - const endpoint = - process.platform === 'win32' - ? String.raw`\\.\pipe\orca-structured-cli-${randomUUID()}` - : join(root, 'rpc.sock') - socket = new UnixSocketTransport({ kind, endpoint }) - socket.onMessage((message, reply) => { - const request: RpcRequest = JSON.parse(message) - requests.push(request) - void dispatcher.dispatch(request).then((response) => reply(JSON.stringify(response))) - }) - await socket.start() - await writeFile( - getRuntimeMetadataPath(root), - JSON.stringify({ - runtimeId: runtime.getRuntimeId(), - pid: process.pid, - transports: [{ kind, endpoint }], - authToken: 'test', - startedAt: 1 - }) - ) -}) - -afterEach(async () => { - for (const dispatch of dispatches.splice(0)) { - releaseStructuredWorkerSession(dispatch, runtime) - } - await socket?.stop() - socket = undefined - db?.close() - structuredWorkerIdentities.clear() - vi.unstubAllEnvs() - process.exitCode = 0 -}) - -async function cli(argv: string[]) { - vi.mocked(console.log).mockClear() - vi.mocked(console.error).mockClear() - process.exitCode = 0 - await main([...argv, '--json', ...(argv[0] === 'orchestration' ? ['--full'] : [])], root) - const stdout = vi - .mocked(console.log) - .mock.calls.map(([line]) => String(line)) - .join('\n') - const stderr = vi - .mocked(console.error) - .mock.calls.map(([line]) => String(line)) - .join('\n') - const output: unknown = JSON.parse(stdout) - return { output, code: process.exitCode, stdout, stderr } -} - -async function launch() { - const receipt = await cli([ - 'agent', - 'launch', - '--agent', - 'codex', - '--worktree', - `id:${rig.workspace}`, - '--surface', - 'chat', - '--prompt', - 'Coordinator' - ]) - expect(receipt.code, receipt.stdout + receipt.stderr).toBe(0) - const result = resultOf(receipt.output) - const ids = host.deps.store.getVisibleSessionTabIndex().sessionIds - expect(ids).toHaveLength(1) - const sessionId = ids[0]! - expect(isOrcaSessionId(sessionId)).toBe(true) - if (!isOrcaSessionId(sessionId)) { - throw new Error('invalid created session identity') - } - expect(result).toMatchObject({ - worktreeId: rig.workspace, - outcome: { kind: 'structured', sessionId } - }) - vi.stubEnv('ORCA_AGENT_SESSION_ID', sessionId) - runId = db.createRun({ - objective: 'CLI lifecycle', - coordinatorHandle: null, - coordinatorPaneKey: null, - coordinatorOrcaSessionId: sessionId - }).id - await chatTabCommandsSettled() - expect(savedIds(rig)).toContain(sessionId) - return { result, sessionId } -} - -async function start(retryOf?: string) { - const receipt = await cli([ - 'orchestration', - 'worker-start', - '--run', - runId, - '--worktree', - `id:${rig.workspace}`, - '--agent', - 'codex', - ...(retryOf - ? ['--task', db.getDispatchContextById(retryOf)!.task_id, '--retry-of', retryOf] - : ['--spec', 'Reply once then wait']) - ]) - expect(receipt.code, receipt.stdout + receipt.stderr).toBe(0) - const result = resultOf(receipt.output) - expect(result).toMatchObject({ state: 'ready', mode: { mode: 'structured' } }) - if (typeof result.dispatchId !== 'string' || typeof result.taskId !== 'string') { - throw new Error('worker-start did not return dispatch/task identities') - } - const dispatchId = result.dispatchId - const taskId = result.taskId - dispatches.push(dispatchId) - const worker = db.getWorkerDispatch(dispatchId)! - const identity = structuredWorkerIdentities.get(worker.agent_terminal_handle!) - if (!identity) { - throw new Error('worker identity not registered') - } - const record = host.deps.store.getRecord(identity.sessionId)! - const nativeId = activeProviderContext(record).head?.handle.nativeId - const connection = codex.connections.find((c) => c.threadId === nativeId) - if (!connection) { - throw new Error('worker provider not started') - } - await chatTabCommandsSettled() - expect(savedIds(rig)).toContain(identity.sessionId) - expect(runtime.live(identity.sessionId)).toBe(true) - return { result, dispatchId, taskId, worker, identity, connection } -} - -function visible(sessionId: string, expected: boolean) { - expect(host.deps.store.getVisibleSessionTabIndex().sessionIds.includes(sessionId)).toBe(expected) - expect(runtime.live(sessionId)).toBe(expected) - expect(savedIds(rig).includes(sessionId)).toBe(expected) -} - -async function selectSurvivor(sessionId: string) { - const session = rig.profile.getWorkspaceSession('local') - if (!session) { - throw new Error('missing saved workspace session') - } - const tabId = structuredAgentSessionTabId(sessionId) - rig.profile.setWorkspaceSession({ - ...session, - activeWorktreeId: rig.workspace, - activeTabId: tabId, - activeTabIdByWorktree: { ...session.activeTabIdByWorktree, [rig.workspace]: tabId } - }) - await rig.profile.flushPendingOrThrowAsync() - return () => { - const current = rig.profile.getWorkspaceSession('local') - expect(current?.activeWorktreeId).toBe(rig.workspace) - expect(current?.activeTabId).toBe(tabId) - expect(current?.activeTabIdByWorktree?.[rig.workspace]).toBe(tabId) - } -} - -function settle(worker: Awaited>) { - expect( - db.settleWorkerReport({ - taskId: worker.taskId, - dispatchId: worker.dispatchId, - outcome: 'succeeded', - result: JSON.stringify({ summary: 'Completed fixture task' }) - }) - ).toMatchObject({ action: 'settled' }) - expect(db.getWorkerDispatch(worker.dispatchId)?.state).toBe('succeeded') - expect(worker.connection.closed).toBe(false) - expect(db.getWorkerTerminalResourceByOwner(worker.dispatchId)).toMatchObject({ - ownership_state: 'owned' - }) -} - -it.each(['worker-stop', 'worker-release'] as const)( - '%s waits for provider proof before CLI success and exact raw/saved retirement', - async (command) => { - const survivor = await launch() - const worker = await start() - if (command === 'worker-release') { - settle(worker) - } - const selectionPreserved = await selectSurvivor(survivor.sessionId) - const tableId = host.getSessionTabId(worker.identity.sessionId) - expect(tableId).toBe(structuredAgentSessionTabId(worker.identity.sessionId)) - const release = Promise.withResolvers() - const close = worker.connection.close.bind(worker.connection) - vi.spyOn(worker.connection, 'close').mockImplementation(async () => { - await release.promise - return close() - }) - let answered = false - const pending = cli(['orchestration', command, '--dispatch', worker.dispatchId]).then( - (receipt) => { - answered = true - return receipt - } - ) - try { - await vi.waitFor(() => expect(worker.connection.close).toHaveBeenCalled()) - expect(answered).toBe(false) - expect(console.log).not.toHaveBeenCalled() - expect(worker.connection.closed).toBe(false) - expect( - host.deps.store.getRecord(worker.identity.sessionId)?.lease.ownerProcess - ).not.toBeNull() - visible(worker.identity.sessionId, true) - visible(survivor.sessionId, true) - selectionPreserved() - if (command === 'worker-stop') { - expect(db.getWorkerDispatch(worker.dispatchId)?.state).toBe('stopping') - } else { - expect(db.getWorkerTerminalResourceByOwner(worker.dispatchId)).toMatchObject({ - release_state: 'releasing', - archive_status: 'captured' - }) - } - } finally { - release.resolve() - } - const receipt = await pending - expect(receipt.code, receipt.stdout + receipt.stderr).toBe(0) - expect(resultOf(receipt.output)).toMatchObject({ - dispatchId: worker.dispatchId, - state: command === 'worker-stop' ? 'stopped' : 'released', - processAction: 'closed_agent_terminal' - }) - await chatTabCommandsSettled() - await rig.profile.flushPendingOrThrowAsync() - expect(worker.connection.closed).toBe(true) - expect(host.deps.store.getRecord(worker.identity.sessionId)?.lease.ownerProcess).toBeNull() - expect(host.hasSession(worker.identity.sessionId)).toBe(false) - expect(host.getSessionTabId(worker.identity.sessionId)).toBeNull() - visible(worker.identity.sessionId, false) - visible(survivor.sessionId, true) - selectionPreserved() - if (command === 'worker-stop') { - expect(db.getWorkerDispatch(worker.dispatchId)?.state).toBe('stopped') - expect(db.getDispatchContextById(worker.dispatchId)?.status).toBe('failed') - } else { - expect(db.getWorkerTerminalResourceByOwner(worker.dispatchId)).toMatchObject({ - ownership_state: 'released', - release_state: 'released', - archive_status: 'captured' - }) - const archived = await cli([ - 'orchestration', - 'worker-read', - '--dispatch', - worker.dispatchId, - '--source', - 'transcript' - ]) - expect(archived.code, archived.stdout).toBe(0) - expect(resultOf(archived.output)).toMatchObject({ - archived: true, - status: { liveness: 'exited' } - }) - expect(archived.stdout).toContain('READY from bounded provider') - } - } -) diff --git a/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts b/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts deleted file mode 100644 index ed807aa74fc..00000000000 --- a/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts +++ /dev/null @@ -1,370 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing' -import './unused-default-rpc-methods.test-fixture' -import { spawn } from 'node:child_process' -import { once } from 'node:events' -import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' -import { expect, it, vi } from 'vitest' -import { createAgentPromptSubmissionRuntime } from '../terminal/input/agent-prompt-submission-runtime-test-fixture' -import { UnixSocketTransport } from './unix-socket-transport' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { STATUS_METHODS } from './methods/host-management/status' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import { OrcaRuntimeRpcServer } from './server/runtime-rpc' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' -import { bindPaneFirst } from '../orca-runtime-tests/bind-first-pane.test-fixture' -import * as inputAdmission from '../terminal/input/terminal-input-admission' -import { writePtyFromRuntimeController } from '../../ipc/pty/runtime/operations' -import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' -import { createHookListenerState } from '../../../shared/agent-hook-listener/listener-state' -import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' - -vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: listings.listWorktrees - } -}) - -vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: listings.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - function createWorktreeListingMocks() { - const read = async () => [ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'prompt', - isBare: false, - isMainWorktree: false - } - ] - return { listWorktrees: read, listWorktreesStrict: read } - } - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -it.each([ - 'before', - 'after', - 'paired', - 'orchestration', - 'codex-startup', - 'codex-replay', - 'codex-cold-replay' -] as const)( - 'real CLI phone admission and delivery: %s', - async (boundary) => { - const disconnect = boundary === 'before' || boundary === 'after' - const paired = boundary === 'paired' - const codex = boundary.startsWith('codex-') - const replay = boundary === 'codex-replay' || boundary === 'codex-cold-replay' - const hookServer = replay ? new AgentHookServer() : undefined - await hookServer?.start({ env: 'production' }) - const text = codex ? 'x'.repeat(1_000) : 'first' - const hookState = createHookListenerState() - let hook: ReturnType = null - let promptHandle = '' - let held = true - let enters = 0 - const latch = () => Promise.withResolvers() - const [pasted, release, closed, received] = [latch(), latch(), latch(), latch()] - const root = mkdtempSync(join(tmpdir(), 'orca-prompt-socket-')) - const kind = process.platform === 'win32' ? 'named-pipe' : 'unix' - const endpoint = - kind === 'named-pipe' ? `\\\\.\\pipe\\${root.split(/[/\\]/).at(-1)}` : join(root, 'rpc') - const transport = new UnixSocketTransport({ endpoint, kind }) - vi.spyOn(getLocalPtyProvider(), 'write').mockReturnValue(true) - const promptAdmission = vi.spyOn(inputAdmission, 'assertTerminalInputAdmitted') - const rawAdmission = vi.spyOn(inputAdmission, 'createTerminalInputReservation') - const { runtime, handle, writes } = await createAgentPromptSubmissionRuntime( - (_host, data) => { - pasted.resolve() - if (codex && data === '\r') { - enters += 1 - held = enters === 1 - hook = normalizeHookPayload( - hookState, - 'codex', - { - paneKey: 'tab-prompt:22222222-2222-4222-8222-222222222222', - payload: held - ? { - hook_event_name: 'SessionStart', - source: 'startup', - session_id: '11111111-1111-4111-8111-111111111111' - } - : { - hook_event_name: 'UserPromptSubmit', - session_id: '11111111-1111-4111-8111-111111111111', - turn_id: 'turn-1', - prompt: text - } - }, - 'production' - ) - if (hook && hookServer) { - if (!held || boundary !== 'codex-cold-replay') { - hookServer.ingestRemote(hook, 'fixture-connection') - } - if (held) { - hookServer.ingestRemote( - { - ...hook, - hasExplicitPrompt: true, - isReplay: true, - payload: { - ...hook.payload, - state: 'working', - prompt: 'old task', - sessionBoundary: undefined, - mainAgent: { state: 'working', stateStartedAt: 1_000 } - } - }, - 'fixture-connection' - ) - } - } - } - }, - codex ? 'codex' : 'claude', - (host, id, data) => writePtyFromRuntimeController({ runtime: host }, id, data, 'driving'), - { - getAgentStatusSnapshot: () => - hookServer - ? hookServer - .getStatusSnapshot() - .map((row) => ({ ...row, terminalHandle: promptHandle })) - : hook - ? [ - { - ...hook.payload, - paneKey: hook.paneKey, - terminalHandle: promptHandle, - receivedAt: hook.payload.mainAgent?.stateStartedAt ?? 1_000, - stateStartedAt: hook.payload.mainAgent?.stateStartedAt ?? 1_000, - connectionId: null - } - ] - : [] - } - ) - promptHandle = handle - if (codex) { - Object.defineProperty(runtime, 'getPtyWriteHostPlatform', { value: () => 'win32' }) - Object.defineProperty(runtime, 'readCurrentTerminalWaitScreen', { - value: async () => ({ lines: [], draft: held ? '[Pasted Content 1000 chars]' : undefined }) - }) - } - const db = new OrchestrationDb(':memory:') - runtime.setOrchestrationDb(db) - const methods = [...STATUS_METHODS, ...TERMINAL_METHODS, ...ORCHESTRATION_METHODS] - const dispatcher = new RpcDispatcher({ runtime, methods }) - Object.defineProperty(runtime, 'createAgentPromptRenderGate', { - value: () => ({ arm: () => {}, wait: () => release.promise, dispose: () => {} }) - }) - let sent: RpcRequest | undefined - const done: Promise[] = [] - transport.onMessage((raw, reply, context) => { - const request: RpcRequest = JSON.parse(raw) - const prompt = request.method === 'terminal.send' - if (prompt) { - sent = request - received.resolve() - context!.signal.addEventListener('abort', () => closed.resolve(), { once: true }) - } - const admission = prompt && boundary === 'before' ? release.promise : Promise.resolve() - done.push( - admission.then(async () => - reply( - JSON.stringify( - await dispatcher.dispatch(request, { - ...context, - // Model the UI transport on the accepted-paste/observer-loss row. - ...(boundary === 'after' ? { caller: { kind: 'desktop' as const } } : {}) - }) - ) - ) - ) - ) - }) - await transport.start() - const discovery = { - runtimeId: runtime.getRuntimeId(), - pid: process.pid, - startedAt: 1, - authToken: 'fixture-token', - transports: [{ kind, endpoint }] - } - writeFileSync(join(root, 'orca-runtime.json'), JSON.stringify(discovery)) - const preload = join(root, 'exit-on-input.ts') - writeFileSync(preload, "process.stdin.once('data', () => process.exit(0))") - const program = createRequire(resolve('package.json')).resolve('bun/bin/bun.exe') - const env = { - ...Object.fromEntries( - 'HOME USERPROFILE APPDATA LOCALAPPDATA XDG_CONFIG_HOME XDG_CACHE_HOME XDG_DATA_HOME XDG_STATE_HOME ORCA_E2E_HOME_DIR ORCA_E2E_USER_DATA_DIR ORCA_USER_DATA_PATH TEMP TMP TMPDIR CODEX_HOME CLAUDE_CONFIG_DIR' - .split(' ') - .map((key) => [key, root]) - ), - ORCA_BACKGROUND_LAUNCH: '1', - ORCA_DISABLE_MACOS_LOGIN_SHELL: '1', - PATH: process.env.PATH, - SystemRoot: process.env.SystemRoot - } - let args = ['terminal', 'send', '--terminal', handle, '--text', text, '--enter', '--json'] - if (codex) { - args.push('--wait-submit', '5') - } - if (paired) { - args = args.filter((arg) => arg !== '--enter') - } - if (boundary === 'orchestration') { - const pane = { - worktreeId: 'repo-1::/tmp/worktree-a', - tabId: '11111111-1111-4111-8111-111111111111', - leafId: '22222222-2222-4222-8222-222222222222', - ptyId: 'pty-coordinator' - } - bindPaneFirst(runtime, pane) - runtime.registerPty(pane.ptyId, pane.worktreeId, null, pane) - runtime.registerPreAllocatedHandleForPty(pane.ptyId, 'term_coordinator') - const run = db.createRun({ - objective: 'phone admission', - coordinatorHandle: 'term_coordinator', - coordinatorPaneKey: `${pane.tabId}:${pane.leafId}` - }) - const task = db.createTask({ runId: run.id, spec: 'first' }) - args = [ - 'orchestration', - 'dispatch', - '--from', - 'term_coordinator', - '--task', - task.id, - '--to', - handle, - '--inject', - '--json' - ] - } - const server = paired - ? new OrcaRuntimeRpcServer({ - runtime, - methods, - userDataPath: root, - enableWebSocket: true, - wsPort: 0 - }) - : null - if (server) { - await server.start() - const offer = server.createPairingOffer({ - address: '127.0.0.1', - name: 'CLI test', - scope: 'runtime' - }) - if (!offer.available) { - throw new Error('pairing unavailable') - } - args.push('--pairing-code', offer.pairingUrl) - } - if (!disconnect) { - await runtime.handleMobileSubscribe('pty-prompt', 'phone-A', { cols: 45, rows: 20 }) - release.resolve() - } - const command = ['--preload', preload, resolve('src/cli/index.ts'), ...args] - const child = spawn(program, command, { cwd: root, env, stdio: 'pipe' }) - const exited = once(child, 'close') - let output = '' - child.stdout.on('data', (data) => { - output += data.toString() - }) - child.stderr.resume() - try { - if (!disconnect) { - child.stdin.end() - expect((await exited)[0]).toBe(0) - expect(JSON.parse(output).result).toMatchObject( - boundary === 'orchestration' ? { injected: true } : { send: { accepted: true } } - ) - expect(writes).toEqual( - paired - ? ['first'] - : codex - ? [expect.stringContaining(text), '\r', '\r'] - : [expect.stringContaining('first'), '\r'] - ) - if (codex) { - expect(held).toBe(false) - expect(JSON.parse(output).result.send.prompt.stages).toContain('turn_started') - } - expect(paired ? rawAdmission : promptAdmission).toHaveBeenCalledWith( - runtime, - paired ? 'programmatic' : 'pty-prompt', - codex ? 'programmatic' : undefined - ) - expect(runtime.getDriver('pty-prompt')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) - return - } - await Promise.race([ - received.promise, - exited.then(() => expect.fail('CLI exited before sending')) - ]) - await (boundary === 'after' ? pasted.promise : received.promise) - if (boundary === 'after') { - await runtime.handleMobileSubscribe('pty-prompt', 'phone-A', { cols: 45, rows: 20 }) - } - child.stdin.end('exit') // The test-owned child exits itself; no process-tree termination. - await exited - await closed.promise - const secondObserver = new AbortController() - const second = runtime.sendTerminalAgentPrompt(handle, 'second', { - inputKind: 'driving', - observationSignal: secondObserver.signal - }) - void second.catch(() => undefined) - secondObserver.abort() - release.resolve() - await Promise.all(done) - await expect(second).rejects.toThrow('request_aborted') - expect(writes).toEqual(boundary === 'after' ? [expect.stringContaining('first'), '\r'] : []) - if (boundary === 'after' && sent) { - const replay = await dispatcher.dispatch(sent, { caller: { kind: 'desktop' } }) - expect(replay).toMatchObject({ ok: true, result: { mutation: { replayed: true } } }) - expect(writes).toHaveLength(2) - } - } finally { - release.resolve() - if (child.exitCode === null) { - child.stdin.end('exit') - } - await exited - await server?.stop() - hookServer?.stop() - await transport.stop() - await Promise.allSettled(done) - db.close() - vi.restoreAllMocks() - rmSync(root, { recursive: true, force: true }) - } - }, - 20_000 -) diff --git a/src/main/runtime/rpc/terminal-claude-agent-view.test.ts b/src/main/runtime/rpc/terminal-claude-agent-view.test.ts deleted file mode 100644 index c6e45cfedcb..00000000000 --- a/src/main/runtime/rpc/terminal-claude-agent-view.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' -import type { OrcaRuntimeService } from '../orca-runtime' -import { RpcDispatcher } from './dispatcher' -import { createTerminalInputReservation } from '../terminal/input/terminal-input-admission' -import { TERMINAL_CLAUDE_AGENT_VIEW_METHODS } from './methods/terminal/terminal-claude-agent-view-method' - -const identity = { - paneKey: 'tab:11111111-1111-4111-8111-111111111111', - sessionId: 'session', - instanceId: 'mod' -} -const now = 1_700_000_000_000 - -beforeEach(() => { - vi.useFakeTimers({ now }) -}) - -afterEach(() => { - agentHookServer.claudeAgentViews.clear() - vi.restoreAllMocks() - vi.useRealTimers() -}) - -it.each(['permission', 'new-session', 'new-mod', 'new-pty', 'mobile-lock'] as const)( - 'refuses the shortcut when %s arrives before the terminal write', - async (change) => { - let sessionId = identity.sessionId - let permission = false - let ptyId = 'pty' - let mobileLocked = false - vi.spyOn(agentHookServer, 'getStatusSnapshotForPane').mockImplementation(() => [ - { - paneKey: identity.paneKey, - agentType: 'claude', - state: 'done', - prompt: '', - providerSession: { key: 'session_id', id: sessionId }, - connectionId: null, - receivedAt: now, - stateStartedAt: now - } - ]) - agentHookServer.claudeAgentViews.receive({ - ...identity, - action: 'register', - view: { revision: 1 }, - keybindings: JSON.stringify({ - bindings: [{ context: 'Chat', bindings: { 'ctrl+alt+g': 'command:orca-agent-view' } }] - }) - }) - const write = vi.fn() - const overrides: Partial = { - getRuntimeId: () => 'test-runtime', - resolveLiveLeafForHandle: vi.fn(() => ({ ptyId })), - getLiveTerminalPaneKey: () => identity.paneKey, - getDriver: vi.fn(() => - mobileLocked ? { kind: 'mobile', clientId: 'phone' } : { kind: 'desktop' } - ), - getTerminalAgentStatus: vi.fn(async () => ({ - handle: 'terminal', - isRunningAgent: true, - status: permission ? 'permission' : 'idle' - })), - sendTerminal: vi.fn(async (_handle, _action, options) => { - if (change === 'permission') { - permission = true - } - if (change === 'new-session') { - sessionId = 'replacement' - } - if (change === 'new-pty') { - ptyId = 'replacement' - } - if (change === 'mobile-lock') { - mobileLocked = true - } - if (change === 'new-mod') { - agentHookServer.claudeAgentViews.receive({ - ...identity, - instanceId: 'replacement', - action: 'register', - view: { revision: 1 }, - keybindings: JSON.stringify({ - bindings: [{ context: 'Chat', bindings: { 'ctrl+alt+h': 'command:orca-agent-view' } }] - }) - }) - } - expect(options?.inputSource).toBe('desktop') - await options?.beforeWrite?.('pty') - createTerminalInputReservation(runtime, options?.inputSource, undefined)('pty') - write() - return { handle: 'terminal', accepted: true, bytesWritten: 8 } - }) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this scoped dispatcher reaches only the runtime methods defined above. - const runtime = overrides as OrcaRuntimeService - const response = await new RpcDispatcher({ - runtime, - methods: TERMINAL_CLAUDE_AGENT_VIEW_METHODS - }).dispatch({ - id: 'request', - authToken: 'token', - method: 'terminal.viewClaudeAgent', - params: { - terminal: 'terminal', - sessionId: identity.sessionId, - agentId: 'child', - client: { id: 'desktop', type: 'desktop' } - } - }) - expect(response).toMatchObject({ - ok: true, - result: { - view: { status: change === 'permission' ? 'permission' : 'unavailable' } - } - }) - expect(write).not.toHaveBeenCalled() - } -) diff --git a/src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts b/src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts deleted file mode 100644 index 0eb9ea22e5b..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts +++ /dev/null @@ -1,360 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('flushes multibyte live output when encoded bytes reach the batch budget', async () => { - vi.useFakeTimers() - try { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const registry = createSubscriptionRegistryDouble() - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ - data: 'snapshot', - cols: 120, - rows: 40 - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-multibyte-output-batch', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 6, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 } - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - binaryFrames.splice(0) - - const multibyteOutput = '界'.repeat(22_000) - const encodeSpy = vi.spyOn(TextEncoder.prototype, 'encode') - dataListenerRef.current?.(multibyteOutput, { - seq: multibyteOutput.length, - rawLength: multibyteOutput.length - }) - - const outputFrames = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - expect(outputFrames.length).toBeGreaterThan(1) - expect(outputFrames.every((frame) => (frame?.payload.byteLength ?? 0) <= 48 * 1024)).toBe( - true - ) - expect(outputFrames.map((frame) => frame?.seq)).toEqual([16_384, 22_000]) - expect( - outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('') - ).toBe(multibyteOutput) - expect(encodeSpy).not.toHaveBeenCalledWith(multibyteOutput) - encodeSpy.mockRestore() - - registry.cleanupSubscription('terminal-multiplex:conn-multibyte-output-batch') - await dispatchPromise - } finally { - vi.useRealTimers() - } - }) - - it('holds ACK-capable multiplex output over budget until the client acknowledges bytes', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const registry = createSubscriptionRegistryDouble() - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ - data: 'snapshot', - cols: 120, - rows: 40 - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-ack-gated', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 16, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 }, - capabilities: { ackOutput: 1 } - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - binaryFrames.splice(0) - - const output = 'x'.repeat(700 * 1024) - dataListenerRef.current?.(output, { seq: output.length, rawLength: output.length }) - - const initialOutputFrames = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - const initialBytes = initialOutputFrames.reduce( - (total, frame) => total + (frame?.payload.byteLength ?? 0), - 0 - ) - expect(initialBytes).toBeLessThanOrEqual(512 * 1024) - expect(initialOutputFrames.length).toBeGreaterThan(0) - const initialOutput = initialOutputFrames - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - expect(initialOutput.length).toBeLessThan(output.length) - - handlers.get(16)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId: 16, - seq: 2, - payload: encodeTerminalStreamText('still interactive\r') - }) - )! - ) - await vi.waitFor(() => - expect(runtime.sendTerminal).toHaveBeenCalledWith( - 'terminal-1', - { - text: 'still interactive\r', - enter: false, - interrupt: false - }, - { inputKind: 'driving', inputSource: 'desktop' } - ) - ) - - handlers.get(16)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Ack, - streamId: 16, - seq: 3, - payload: encodeTerminalStreamJson({ bytes: initialBytes }) - }) - )! - ) - - const flushedOutputFrames = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - expect(flushedOutputFrames.length).toBeGreaterThan(initialOutputFrames.length) - - runtime.cleanupSubscription('terminal-multiplex:conn-ack-gated') - await dispatchPromise - }) - - it('bounds oversized live output frames for subscribed binary streams', async () => { - vi.useFakeTimers() - try { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const registry = createSubscriptionRegistryDouble() - const dataListenerRef: { current?: (data: string) => void } = {} - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ - data: 'snapshot', - cols: 120, - rows: 40 - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => { - dataListenerRef.current = listener - return vi.fn() - }), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - capabilities: { terminalBinaryStream: 1 } - }), - (msg) => messages.push(msg), - { - connectionId: 'conn-subscribe-output-chunking', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - binaryFrames.splice(0) - - const output = 'output-line\n'.repeat(8_000) - dataListenerRef.current?.(output) - - const outputFrames = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - expect(outputFrames.length).toBeGreaterThan(1) - expect(outputFrames.every((frame) => (frame?.payload.byteLength ?? 0) <= 48 * 1024)).toBe( - true - ) - expect( - outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('') - ).toBe(output) - - runtime.cleanupSubscription('terminal-1:desktop-1') - await dispatchPromise - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery-history.test.ts b/src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery-history.test.ts deleted file mode 100644 index e2b958a68b7..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery-history.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - encodeTerminalStreamFrame, - encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - sendDesktopMultiplexSubscribe, - startDesktopMultiplexSubscribe -} from './terminal-multiplex-test-harness' - -type DataListener = (data: string, meta?: { seq?: number; rawLength?: number }) => void - -// Snapshots bypass ACK windows; repeated history recovery during floods outgrew client intake and prevented backlog drain. -describe('ACK-overflow recovery history under a sustained flood', () => { - it('stays screen-only while the link is saturated and sends history once it drains', async () => { - let seq = 0 - const listener: { current?: DataListener } = {} - const serializeTerminalBuffer = vi.fn( - async (_ptyId: string, opts?: { scrollbackRows?: number }) => ({ - data: (opts?.scrollbackRows ?? 0) > 0 ? 'history\r\nscreen' : 'screen', - cols: 120, - rows: 40, - seq - }) - ) - const harness = startDesktopMultiplexSubscribe({ - serializeTerminalBuffer, - subscribeToTerminalData: vi.fn((_: string, next: DataListener) => { - listener.current = next - return vi.fn() - }) - }) - await vi.waitFor(() => - expect(harness.messages.some((m) => JSON.parse(m).result?.type === 'ready')).toBe(true) - ) - sendDesktopMultiplexSubscribe(harness.handlers) - await vi.waitFor(() => - expect(harness.messages.some((m) => JSON.parse(m).result?.type === 'subscribed')).toBe(true) - ) - harness.binaryFrames.splice(0) - - let inFlight = 0 - let ackSeq = 2 - const takeSent = (): { output: number; recoveryRows: number[] } => { - const frames = harness.binaryFrames.splice(0).map(decodeTerminalStreamFrame) - const output = frames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) - const recoveryRows = frames.flatMap((frame) => { - if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { - return [] - } - const meta = decodeTerminalStreamJson<{ reason?: string; scrollbackRows?: number }>( - frame.payload - ) - return meta?.reason === 'ack-pending-overflow' ? [meta.scrollbackRows ?? -1] : [] - }) - inFlight += output - return { output, recoveryRows } - } - const ack = async (bytes: number): Promise<{ output: number; recoveryRows: number[] }> => { - inFlight -= bytes - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Ack, - streamId: 7, - seq: ackSeq++, - payload: encodeTerminalStreamJson({ bytes }) - }) - )! - ) - await vi.waitFor(() => - expect(serializeTerminalBuffer.mock.results.at(-1)?.type).toBe('return') - ) - await new Promise((resolve) => setTimeout(resolve, 0)) - return takeSent() - } - const flood = (): void => { - const chunk = 'x'.repeat(1024 * 1024) - seq += chunk.length - listener.current?.(chunk, { seq, rawLength: chunk.length }) - } - - flood() - takeSent() - const duringFlood: number[] = [] - for (let round = 0; round < 5; round++) { - // The client acks one batch while the flood keeps the window full. - duringFlood.push(...(await ack(192 * 1024)).recoveryRows) - flood() - takeSent() - } - expect(duringFlood.length).toBeGreaterThan(0) - expect(duringFlood.every((rows) => rows === 0)).toBe(true) - - // The flood stops and the client catches up: one recovery replaces the screen-only image. - const settled: number[] = [] - for (let round = 0; round < 10 && inFlight > 0; round++) { - settled.push(...(await ack(inFlight)).recoveryRows) - } - expect(inFlight).toBe(0) - expect(settled).toEqual([1000]) - expect(serializeTerminalBuffer).toHaveBeenLastCalledWith('pty-1', { scrollbackRows: 1000 }) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts b/src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts deleted file mode 100644 index 8f8d8acce33..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts +++ /dev/null @@ -1,511 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - makeRequest, - sendDesktopMultiplexSubscribe, - startDesktopMultiplexSubscribe, - stubRuntime -} from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('caps stalled ACK output and snapshots before resuming retained tail frames', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) - .mockResolvedValue({ data: 'recovered snapshot', cols: 120, rows: 40, seq: 99 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - cleanupSubscription: vi.fn((id: string) => { - const cleanup = cleanups.get(id) - cleanups.delete(id) - cleanup?.() - }), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-ack-overflow', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 17, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 }, - capabilities: { ackOutput: 1 } - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - binaryFrames.splice(0) - - const output = 'x'.repeat(3 * 1024 * 1024) - dataListenerRef.current?.(output, { seq: output.length, rawLength: output.length }) - - const initialOutputFrames = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - const initialBytes = initialOutputFrames.reduce( - (total, frame) => total + (frame?.payload.byteLength ?? 0), - 0 - ) - expect(initialBytes).toBeLessThanOrEqual(512 * 1024) - - handlers.get(17)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId: 17, - seq: 2, - payload: encodeTerminalStreamText('still interactive\r') - }) - )! - ) - await vi.waitFor(() => - expect(runtime.sendTerminal).toHaveBeenCalledWith( - 'terminal-1', - { - text: 'still interactive\r', - enter: false, - interrupt: false - }, - { inputKind: 'driving', inputSource: 'desktop' } - ) - ) - - binaryFrames.splice(0) - handlers.get(17)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Ack, - streamId: 17, - seq: 3, - payload: encodeTerminalStreamJson({ bytes: initialBytes }) - }) - )! - ) - - await vi.waitFor(() => - expect( - binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .some((frame) => { - if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { - return false - } - const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) - return payload?.reason === 'ack-pending-overflow' - }) - ).toBe(true) - ) - const drainFrames = binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)) - const recoveryStartIndex = drainFrames.findIndex((frame) => { - if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { - return false - } - const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) - return payload?.reason === 'ack-pending-overflow' - }) - const firstOutputAfterAckIndex = drainFrames.findIndex( - (frame) => frame?.opcode === TerminalStreamOpcode.Output - ) - expect(recoveryStartIndex).toBeGreaterThanOrEqual(0) - // Clients discard truncated snapshots; mark usable recovery complete or the gap stays permanent. - expect( - decodeTerminalStreamJson<{ truncated?: boolean }>(drainFrames[recoveryStartIndex]!.payload) - ?.truncated - ).toBe(false) - // Recovery must replace history that ends before dropped output. - expect(runtime.serializeTerminalBuffer).toHaveBeenLastCalledWith('pty-1', { - scrollbackRows: 1000 - }) - expect( - decodeTerminalStreamJson<{ scrollbackRows?: number }>( - drainFrames[recoveryStartIndex]!.payload - )?.scrollbackRows - ).toBe(1000) - expect(firstOutputAfterAckIndex).toBeGreaterThan(recoveryStartIndex) - expect( - drainFrames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - ).toBe('recovered snapshot') - - const outputBytesAfterRecovery = drainFrames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) - expect(outputBytesAfterRecovery).toBeLessThanOrEqual(256 * 1024) - - runtime.cleanupSubscription('terminal-multiplex:conn-ack-overflow') - await dispatchPromise - }) - - it.each([ - { - failure: 'throws', - recover: () => Promise.reject(new Error('snapshot unavailable')) - }, - { - failure: 'returns no snapshot', - recover: () => Promise.resolve(null) - } - ])('ends a stream when ACK overflow recovery serialization $failure', async ({ recover }) => { - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - const serializeTerminalBuffer = vi - .fn() - .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) - .mockImplementation(recover) - const harness = startDesktopMultiplexSubscribe({ - serializeTerminalBuffer, - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ) - }) - - await vi.waitFor(() => - expect(harness.messages.some((message) => JSON.parse(message).result?.type === 'ready')).toBe( - true - ) - ) - sendDesktopMultiplexSubscribe(harness.handlers) - await vi.waitFor(() => - expect( - harness.messages.some((message) => JSON.parse(message).result?.type === 'subscribed') - ).toBe(true) - ) - harness.binaryFrames.splice(0) - - const output = 'x'.repeat(3 * 1024 * 1024) - dataListenerRef.current?.(output, { seq: output.length, rawLength: output.length }) - const inFlightBytes = harness.binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Ack, - streamId: 7, - seq: 2, - payload: encodeTerminalStreamJson({ bytes: inFlightBytes }) - }) - )! - ) - - await vi.waitFor(() => { - const eventTypes = harness.messages.map((message) => JSON.parse(message).result?.type) - expect(eventTypes).toContain('error') - expect(eventTypes).toContain('end') - }) - expect(harness.handlers.has(7)).toBe(false) - expect(serializeTerminalBuffer).toHaveBeenCalledTimes(2) - await Promise.resolve() - await Promise.resolve() - expect(serializeTerminalBuffer).toHaveBeenCalledTimes(2) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - }) - - it('trims recovery-covered ACK pending output instead of replaying it', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - const floodedChars = 3 * 1024 * 1024 - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) - // Recovery seq covers the flood, so all retained chunks already appear in the snapshot. - .mockResolvedValue({ data: 'recovered snapshot', cols: 120, rows: 40, seq: floodedChars }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - cleanupSubscription: vi.fn((id: string) => { - const cleanup = cleanups.get(id) - cleanups.delete(id) - cleanup?.() - }), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-ack-trim', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 31, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 }, - capabilities: { ackOutput: 1 } - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - binaryFrames.splice(0) - - const output = 'x'.repeat(floodedChars) - dataListenerRef.current?.(output, { seq: floodedChars, rawLength: floodedChars }) - const initialBytes = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) - expect(initialBytes).toBeLessThanOrEqual(512 * 1024) - - binaryFrames.splice(0) - handlers.get(31)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Ack, - streamId: 31, - seq: 2, - payload: encodeTerminalStreamJson({ bytes: initialBytes }) - }) - )! - ) - await vi.waitFor(() => - expect( - binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .some((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd) - ).toBe(true) - ) - - const framesAfterRecovery = binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)) - expect( - framesAfterRecovery - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - ).toBe('recovered snapshot') - // Covered chunks would duplicate recovered snapshot content. - expect( - framesAfterRecovery.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - ).toEqual([]) - - binaryFrames.splice(0) - const fresh = 'fresh-after-recovery\r\n' - dataListenerRef.current?.(fresh, { - seq: floodedChars + fresh.length, - rawLength: fresh.length - }) - await vi.waitFor(() => { - const freshOutput = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - expect(freshOutput).toBe(fresh) - }) - - runtime.cleanupSubscription('terminal-multiplex:conn-ack-trim') - await dispatchPromise - }) - - it('sends the next overflow recovery only after output sent ahead of the previous one is acknowledged', async () => { - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - let seq = 0 - const serializeTerminalBuffer = vi.fn(async () => ({ - data: 'recovered', - cols: 120, - rows: 40, - seq - })) - const harness = startDesktopMultiplexSubscribe({ - serializeTerminalBuffer, - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ) - }) - await vi.waitFor(() => - expect(harness.messages.some((message) => JSON.parse(message).result?.type === 'ready')).toBe( - true - ) - ) - sendDesktopMultiplexSubscribe(harness.handlers) - await vi.waitFor(() => - expect( - harness.messages.some((message) => JSON.parse(message).result?.type === 'subscribed') - ).toBe(true) - ) - const flood = (): void => { - const output = 'x'.repeat(3 * 1024 * 1024) - seq += output.length - dataListenerRef.current?.(output, { seq, rawLength: output.length }) - } - const ack = (bytes: number): void => - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Ack, - streamId: 7, - seq: 0, - payload: encodeTerminalStreamJson({ bytes }) - }) - )! - ) - const recoveries = (): number => - harness.binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter( - (frame) => - frame?.opcode === TerminalStreamOpcode.SnapshotStart && - decodeTerminalStreamJson<{ reason?: string }>(frame.payload)?.reason === - 'ack-pending-overflow' - ).length - - flood() - ack(64 * 1024) - await vi.waitFor(() => expect(recoveries()).toBe(1)) - // 448KB sent before the first image is still unacknowledged, so a second flood must not stack another image behind it. - const serializeCalls = serializeTerminalBuffer.mock.calls.length - flood() - ack(64 * 1024) - await Promise.resolve() - expect(serializeTerminalBuffer).toHaveBeenCalledTimes(serializeCalls) - - ack(384 * 1024) - await vi.waitFor(() => expect(recoveries()).toBe(2)) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-desktop-resize-routing.test.ts b/src/main/runtime/rpc/terminal-multiplex-desktop-resize-routing.test.ts deleted file mode 100644 index 9bc7bfb4ac8..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-desktop-resize-routing.test.ts +++ /dev/null @@ -1,541 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('multiplexes terminal streams and routes desktop resize to the source PTY', async () => { - vi.useFakeTimers() - try { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - const dataListenerRef: { - current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void - } = {} - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ - data: 'snapshot', - cols: 120, - rows: 40 - }), - serializeAuthoritativeTerminalBuffer: vi.fn().mockResolvedValue({ - data: 'authoritative snapshot', - cols: 120, - rows: 40 - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn( - ( - _: string, - listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void - ) => { - dataListenerRef.current = listener - return vi.fn() - } - ), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - cleanupSubscription: vi.fn((id: string) => { - const cleanup = cleanups.get(id) - cleanups.delete(id) - cleanup?.() - }), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-1', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - expect(handlers.has(0)).toBe(true) - - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 5, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 300, rows: 150 }, - capabilities: { desktopViewportClaims: 1 } - }) - }) - )! - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - expect(messages.map((msg) => JSON.parse(msg).result)).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: 'fit-override-changed', - streamId: 5, - mode: 'desktop-fit' - }), - expect.objectContaining({ - type: 'driver-changed', - streamId: 5, - driver: { kind: 'idle' } - }) - ]) - ) - expect(runtime.updateRemoteDesktopViewer).toHaveBeenCalledWith( - 'pty-1', - 'multiplex:conn-1:5', - 'desktop-1', - 300, - 150, - false - ) - expect(handlers.has(5)).toBe(true) - - let releaseClaim = (): void => {} - vi.mocked(runtime.updateRemoteDesktopViewer).mockImplementationOnce( - () => - new Promise((resolve) => { - releaseClaim = () => resolve(true) - }) - ) - - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.ClaimViewport, - streamId: 5, - seq: 0, - payload: encodeTerminalStreamJson({ cols: 96, rows: 32 }) - }) - )! - ) - await vi.waitFor(() => - expect(runtime.updateRemoteDesktopViewer).toHaveBeenLastCalledWith( - 'pty-1', - 'multiplex:conn-1:5', - 'desktop-1', - 96, - 32, - true - ) - ) - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Resize, - streamId: 5, - seq: 1, - payload: encodeTerminalStreamJson({ cols: 96, rows: 32 }) - }) - )! - ) - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId: 5, - seq: 2, - payload: encodeTerminalStreamText('ls\r') - }) - )! - ) - expect(runtime.sendTerminal).not.toHaveBeenCalled() - expect(runtime.updateRemoteDesktopViewer).not.toHaveBeenLastCalledWith( - 'pty-1', - 'multiplex:conn-1:5', - 'desktop-1', - 96, - 32, - false - ) - releaseClaim() - await vi.waitFor(() => - expect(runtime.updateRemoteDesktopViewer).toHaveBeenLastCalledWith( - 'pty-1', - 'multiplex:conn-1:5', - 'desktop-1', - 96, - 32, - false - ) - ) - await vi.waitFor(() => - expect(runtime.sendTerminal).toHaveBeenCalledWith( - 'terminal-1', - { - text: 'ls\r', - enter: false, - interrupt: false - }, - { inputKind: 'driving', inputSource: 'desktop' } - ) - ) - const sentAfterSuccessfulClaim = vi.mocked(runtime.sendTerminal).mock.calls.length - vi.mocked(runtime.updateRemoteDesktopViewer).mockResolvedValueOnce(false) - for (const [opcode, seq, payload] of [ - [TerminalStreamOpcode.ClaimViewport, 3, encodeTerminalStreamJson({ cols: 88, rows: 28 })], - [TerminalStreamOpcode.Resize, 4, encodeTerminalStreamJson({ cols: 88, rows: 28 })], - [TerminalStreamOpcode.Input, 5, encodeTerminalStreamText('blocked')] - ] as const) { - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ opcode, streamId: 5, seq, payload }) - )! - ) - } - await vi.waitFor(() => - expect(runtime.updateRemoteDesktopViewer).toHaveBeenLastCalledWith( - 'pty-1', - 'multiplex:conn-1:5', - 'desktop-1', - 88, - 28, - false - ) - ) - expect(runtime.sendTerminal).toHaveBeenCalledTimes(sentAfterSuccessfulClaim) - for (const [opcode, seq, payload] of [ - [TerminalStreamOpcode.ClaimViewport, 6, encodeTerminalStreamJson({ cols: 88, rows: 28 })], - [TerminalStreamOpcode.Resize, 7, encodeTerminalStreamJson({ cols: 88, rows: 28 })], - [TerminalStreamOpcode.Input, 8, encodeTerminalStreamText('retry')] - ] as const) { - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ opcode, streamId: 5, seq, payload }) - )! - ) - } - await vi.waitFor(() => - expect(runtime.sendTerminal).toHaveBeenLastCalledWith( - 'terminal-1', - { - text: 'retry', - enter: false, - interrupt: false - }, - { inputKind: 'driving', inputSource: 'desktop' } - ) - ) - - dataListenerRef.current?.('a') - dataListenerRef.current?.('b') - await vi.runOnlyPendingTimersAsync() - - const outputFrames = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - expect(outputFrames).toHaveLength(1) - expect(outputFrames[0]?.streamId).toBe(5) - expect(outputFrames[0] ? decodeTerminalStreamText(outputFrames[0].payload) : '').toBe('ab') - - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Resize, - streamId: 5, - seq: 3, - payload: encodeTerminalStreamJson({ cols: 100, rows: 30 }) - }) - )! - ) - await vi.waitFor(() => - expect(runtime.updateRemoteDesktopViewer).toHaveBeenLastCalledWith( - 'pty-1', - 'multiplex:conn-1:5', - 'desktop-1', - 100, - 30, - false - ) - ) - - const snapshotStartFrame = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .find((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart) - expect( - snapshotStartFrame && decodeTerminalStreamJson(snapshotStartFrame.payload) - ).toMatchObject({ - cols: 120, - rows: 40 - }) - - const frameCountBeforeSnapshotRequest = binaryFrames.length - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.SnapshotRequest, - streamId: 5, - seq: 4, - payload: encodeTerminalStreamJson({ - requestId: 7, - scrollbackRows: 5000 - }) - }) - )! - ) - await vi.waitFor(() => - expect( - binaryFrames - .slice(frameCountBeforeSnapshotRequest) - .map((frame) => decodeTerminalStreamFrame(frame)) - .some((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd) - ).toBe(true) - ) - const requestedSnapshotFrames = binaryFrames - .slice(frameCountBeforeSnapshotRequest) - .map((frame) => decodeTerminalStreamFrame(frame)) - const requestedSnapshotStart = requestedSnapshotFrames.find( - (frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart - ) - expect( - requestedSnapshotStart && decodeTerminalStreamJson(requestedSnapshotStart.payload) - ).toMatchObject({ - requestId: 7 - }) - // Desktop initial snapshots carry history, not just the screen (#20158). - expect(runtime.serializeTerminalBuffer).toHaveBeenCalledWith('pty-1', { - scrollbackRows: 1000 - }) - expect(runtime.serializeAuthoritativeTerminalBuffer).toHaveBeenLastCalledWith('pty-1', { - scrollbackRows: 5000 - }) - expect( - requestedSnapshotFrames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - ).toBe('authoritative snapshot') - - // Passive streams must neither register nor release active peers' width floors on disconnect. - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 5, - payload: encodeTerminalStreamJson({ - streamId: 6, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' } - }) - }) - )! - ) - await vi.waitFor(() => - expect( - messages.some( - (msg) => - JSON.parse(msg).result?.type === 'subscribed' && - JSON.parse(msg).result?.streamId === 6 - ) - ).toBe(true) - ) - - // Two active floors on one PTY should require only one teardown recomputation. - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 6, - payload: encodeTerminalStreamJson({ - streamId: 7, - terminal: 'terminal-1', - client: { id: 'desktop-2', type: 'desktop' }, - viewport: { cols: 90, rows: 30 } - }) - }) - )! - ) - await vi.waitFor(() => - expect( - messages.some( - (msg) => - JSON.parse(msg).result?.type === 'subscribed' && - JSON.parse(msg).result?.streamId === 7 - ) - ).toBe(true) - ) - - runtime.cleanupSubscription('terminal-multiplex:conn-1') - await dispatchPromise - expect(runtime.unregisterRemoteDesktopViewer).not.toHaveBeenCalled() - expect(runtime.unregisterRemoteDesktopViewers).toHaveBeenCalledTimes(1) - expect(runtime.unregisterRemoteDesktopViewers).toHaveBeenCalledWith('pty-1', [ - 'multiplex:conn-1:5', - 'multiplex:conn-1:7' - ]) - } finally { - vi.useRealTimers() - } - }) - - it('emits a resize drained after the initial snapshot', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - let resolveSnapshot = (_value: { data: string; cols: number; rows: number }): void => {} - let resizeListener: - | ((event: { - cols: number - rows: number - displayMode: string - reason: string - seq?: number - }) => void) - | undefined - const updateRemoteDesktopViewer = vi.fn( - async (_ptyId: string, _key: string, _clientId: string, cols: number, rows: number) => { - if (updateRemoteDesktopViewer.mock.calls.length > 1) { - resizeListener?.({ cols, rows, displayMode: 'desktop', reason: 'apply-layout', seq: 2 }) - } - return true - } - ) - const runtime = stubRuntime({ - updateRemoteDesktopViewer, - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn( - () => - new Promise<{ data: string; cols: number; rows: number }>((resolve) => { - resolveSnapshot = resolve - }) - ), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn((_ptyId, listener) => { - resizeListener = listener - return vi.fn() - }), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - cleanupSubscription: vi.fn((id: string) => { - const cleanup = cleanups.get(id) - cleanups.delete(id) - cleanup?.() - }), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-initial-resize', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 9, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 80, rows: 24 } - }) - }) - )! - ) - await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalled()) - handlers.get(9)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Resize, - streamId: 9, - seq: 2, - payload: encodeTerminalStreamJson({ cols: 132, rows: 43 }) - }) - )! - ) - expect(updateRemoteDesktopViewer).toHaveBeenCalledTimes(1) - - resolveSnapshot({ data: 'snapshot', cols: 80, rows: 24 }) - await vi.waitFor(() => - expect( - binaryFrames.some( - (bytes) => decodeTerminalStreamFrame(bytes)?.opcode === TerminalStreamOpcode.Resized - ) - ).toBe(true) - ) - const opcodes = binaryFrames.map((bytes) => decodeTerminalStreamFrame(bytes)?.opcode) - expect(opcodes.indexOf(TerminalStreamOpcode.Resized)).toBeGreaterThan( - opcodes.indexOf(TerminalStreamOpcode.SnapshotEnd) - ) - - runtime.cleanupSubscription('terminal-multiplex:conn-initial-resize') - await dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts b/src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts deleted file mode 100644 index 596fd7d9b00..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts +++ /dev/null @@ -1,309 +0,0 @@ -import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing' - -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { createAgentPromptSubmissionRuntime } from '../terminal/input/agent-prompt-submission-runtime-test-fixture' -import { settledWriteStub } from '../../providers/settled-pty-write-stub' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText, - decodeTerminalInputAck, - type TerminalInputAckKind -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' - -vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: facade.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - const createWorktreeListingMocks = () => ({ - listWorktreesStrict: async () => [ - { path: '/tmp/worktree-a', head: 'abc', branch: 'test', isBare: false, isMainWorktree: false } - ] - }) - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -type FrameHandler = (frame: NonNullable>) => void - -type ScriptedWrite = 'accept' | 'reject' | 'throw' | 'unverifiable' | 'unhanded' - -function createRuntime( - writes: string[], - writeGate: () => Promise = async () => {}, - scriptedWrites: ScriptedWrite[] = [], - sendOptions: unknown[] = [] -): OrcaRuntimeService { - const registry = createSubscriptionRegistryDouble() - return stubRuntime({ - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', cols: 120, rows: 40 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - cleanupSubscriptionIfOwnedByConnection: vi.fn(registry.cleanupSubscriptionIfOwnedByConnection), - cleanupSubscriptionsForConnection: vi.fn(registry.cleanupSubscriptionsForConnection), - waitForTerminal: vi.fn(() => new Promise(() => {})), - updateDesktopViewport: vi.fn().mockResolvedValue(true), - sendTerminal: vi.fn(async (_handle: string, action: { text?: string }, options: unknown) => { - sendOptions.push(options) - await writeGate() - const scripted = scriptedWrites.shift() ?? 'accept' - if (scripted === 'unverifiable') { - // The SSH provider queued the bytes, then its connection dropped before the handoff settled. - return { - handle: 'terminal-1', - accepted: false, - bytesWritten: 0, - writeSettlement: { - outcome: 'unverifiable' as const, - reason: 'transport_settlement_lost' as const, - bytesHandedToTransport: true - } - } - } - if (scripted === 'unhanded') { - // Settlement lost, but the provider proves no byte left before it was disposed. - return { - handle: 'terminal-1', - accepted: false, - bytesWritten: 0, - writeSettlement: { - outcome: 'unverifiable' as const, - reason: 'transport_settlement_lost' as const, - bytesHandedToTransport: false - } - } - } - if (scripted === 'throw') { - throw new Error('ssh channel write failed') - } - if (scripted === 'reject') { - return { handle: 'terminal-1', accepted: false, bytesWritten: 0 } - } - writes.push(action.text ?? '') - return { handle: 'terminal-1', accepted: true, bytesWritten: action.text?.length ?? 0 } - }) - }) -} - -async function openConnection( - dispatcher: RpcDispatcher, - connectionId: string, - subscribe: { capabilities: Record; inputSessionId?: string } -) { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map() - void dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (message) => messages.push(message), - { - connectionId, - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - await vi.waitFor(() => expect(handlers.has(0)).toBe(true)) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 7, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 }, - ...subscribe - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((message) => JSON.parse(message).result?.type === 'subscribed')).toBe(true) - ) - const subscribed: { - capabilities?: Record - inputLedgerId?: string - } = JSON.parse( - messages.find((message) => JSON.parse(message).result?.type === 'subscribed')! - ).result - return { - subscribed, - sendInput: (seq: number, text: string) => - handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId: 7, - seq, - payload: encodeTerminalStreamText(text) - }) - )! - ), - inputAcks: (kind: TerminalInputAckKind = 'applied') => - binaryFrames.flatMap((bytes) => { - const frame = decodeTerminalStreamFrame(bytes) - return frame?.opcode === TerminalStreamOpcode.InputAck && - decodeTerminalInputAck(frame.payload) === kind - ? [frame.seq] - : [] - }), - writeUnavailableCount: () => - binaryFrames.filter( - (bytes) => - decodeTerminalStreamFrame(bytes)?.opcode === TerminalStreamOpcode.WriteUnavailable - ).length - } -} - -describe('terminal multiplex sequenced input across reconnects', () => { - it('applies a late phone policy drop without replaying withheld input', async () => { - const { runtime, handle, writes } = await createAgentPromptSubmissionRuntime(() => {}) - const write = (_id: string, data: string) => { - writes.push(data) - return true - } - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: () => true, - getForegroundProcess: async () => null - }) - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - const streamRuntime = createRuntime([]) - streamRuntime.getDriver = () => runtime.getDriver('pty-prompt') - streamRuntime.sendTerminal = (_handle, action, options) => - runtime.sendTerminal(handle, action, { - ...options, - beforeWrite: () => { - entered.resolve() - return release.promise - } - }) - const connection = await openConnection( - new RpcDispatcher({ runtime: streamRuntime, methods: TERMINAL_METHODS }), - 'conn-late', - { capabilities: { writeUnavailable: 1, inputAck: 1 }, inputSessionId: 'pane-late' } - ) - connection.sendInput(1, 'withheld') - await entered.promise - await runtime.handleMobileSubscribe('pty-prompt', 'phone-A', { cols: 45, rows: 20 }) - release.resolve() - await vi.waitFor(() => expect(connection.inputAcks()).toEqual([1])) - expect(writes).toEqual([]) - await runtime.reclaimTerminalForDesktop('pty-prompt') - connection.sendInput(1, 'withheld') - connection.sendInput(2, 'next') - await vi.waitFor(() => expect(connection.inputAcks().at(-1)).toBe(2)) - expect(writes).toEqual(['next']) - expect(connection.writeUnavailableCount()).toBe(0) - }) - - it('writes input replayed on a new connection exactly once, even when the dead connection delivers late', async () => { - const writes: string[] = [] - const dispatcher = new RpcDispatcher({ - runtime: createRuntime(writes), - methods: TERMINAL_METHODS - }) - const subscribe = { - capabilities: { ackOutput: 1 as const, inputAck: 1 as const }, - inputSessionId: 'pane-a' - } - const dead = await openConnection(dispatcher, 'conn-dead', subscribe) - expect(dead.subscribed.capabilities).toMatchObject({ inputAck: 1 }) - - dead.sendInput(1, 'PZ600-0') - await vi.waitFor(() => expect(dead.inputAcks()).toEqual([1])) - // The ack for seq 2 never reaches the client: the link went silent. - dead.sendInput(2, '12') - - const replacement = await openConnection(dispatcher, 'conn-replacement', subscribe) - replacement.sendInput(2, '12') - replacement.sendInput(3, '3\r') - // The surviving SSH channel finally flushes the dead connection's buffered copy. - dead.sendInput(3, '3\r') - - await vi.waitFor(() => expect(replacement.inputAcks()).toEqual([2, 3])) - expect(writes).toEqual(['PZ600-0', '12', '3\r']) - }) - - it('never acks a write the PTY refused, and asks the same stream to resend instead of remounting', async () => { - const writes: string[] = [] - const dispatcher = new RpcDispatcher({ - runtime: createRuntime(writes, async () => {}, ['accept', 'reject']), - methods: TERMINAL_METHODS - }) - const subscribe = { - capabilities: { writeUnavailable: 1 as const, inputAck: 1 as const }, - inputSessionId: 'pane-a' - } - const stream = await openConnection(dispatcher, 'conn-first', subscribe) - stream.sendInput(1, 'echo a\r') - stream.sendInput(2, 'echo b\r') - stream.sendInput(3, 'echo c\r') - await vi.waitFor(() => expect(stream.inputAcks('resend')).toEqual([1, 1])) - // Neither the refused seq 2 nor seq 3 behind it may be acked, or the client drops them. - expect(stream.inputAcks()).toEqual([1]) - expect(writes).toEqual(['echo a\r']) - // A remount would throw away the client's journal, so a sequenced refusal must not ask for one. - expect(stream.writeUnavailableCount()).toBe(0) - - // The PTY is writable again: the live stream resends, and typing after it keeps flowing. - stream.sendInput(2, 'echo b\r') - stream.sendInput(3, 'echo c\r') - stream.sendInput(4, 'echo d\r') - await vi.waitFor(() => expect(stream.inputAcks()).toEqual([1, 2, 3, 4])) - expect(writes).toEqual(['echo a\r', 'echo b\r', 'echo c\r', 'echo d\r']) - }) - - it('leaves a client that did not negotiate input acks on the unsequenced path', async () => { - const writes: string[] = [] - const dispatcher = new RpcDispatcher({ - runtime: createRuntime(writes), - methods: TERMINAL_METHODS - }) - // An older client never names an input session; a session id without the capability is ignored too. - const legacy = await openConnection(dispatcher, 'conn-legacy', { - capabilities: { ackOutput: 1 }, - inputSessionId: 'pane-legacy' - }) - expect(legacy.subscribed.capabilities?.inputAck).toBeUndefined() - - legacy.sendInput(2, 'x') - legacy.sendInput(2, 'x') - - await vi.waitFor(() => expect(writes).toEqual(['x', 'x'])) - expect(legacy.inputAcks()).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts b/src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts deleted file mode 100644 index eda46337664..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - encodeTerminalStreamFrame, - encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - WRITE_UNAVAILABLE_OPCODE, - makeRequest, - sendDesktopMultiplexSubscribe, - startDesktopMultiplexSubscribe, - stubRuntime -} from './terminal-multiplex-test-harness' - -describe('terminal multiplex rejected input signalling', () => { - it('does not report a late rejection to a replacement stream with the same id', async () => { - let settleWrite: (result: { - handle: string - accepted: boolean - bytesWritten: number - }) => void = () => {} - const hostWrite = new Promise<{ handle: string; accepted: boolean; bytesWritten: number }>( - (resolve) => { - settleWrite = resolve - } - ) - const sendTerminal = vi.fn(() => hostWrite) - const harness = startDesktopMultiplexSubscribe({ - sendTerminal: sendTerminal as unknown as OrcaRuntimeService['sendTerminal'] - }) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - const capabilities = { ackOutput: 1 as const, writeUnavailable: 1 as const } - sendDesktopMultiplexSubscribe(harness.handlers, capabilities) - await vi.waitFor(() => expect(harness.handlers.has(7)).toBe(true)) - harness.binaryFrames.splice(0) - - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId: 7, - seq: 2, - payload: encodeTerminalStreamText('old') - }) - )! - ) - await vi.waitFor(() => expect(sendTerminal).toHaveBeenCalledOnce()) - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Unsubscribe, - streamId: 7, - seq: 3, - payload: new Uint8Array() - }) - )! - ) - sendDesktopMultiplexSubscribe(harness.handlers, capabilities) - await vi.waitFor(() => - expect( - harness.messages.filter((message) => JSON.parse(message).result?.type === 'subscribed') - ).toHaveLength(2) - ) - harness.binaryFrames.splice(0) - - settleWrite({ handle: 'terminal-1', accepted: false, bytesWritten: 0 }) - await hostWrite - await Promise.resolve() - - expect(harness.binaryFrames.some((frame) => frame[2] === WRITE_UNAVAILABLE_OPCODE)).toBe(false) - }) -}) - -describe('terminal multiplex RPC', () => { - it('never sends the rejection opcode to an un-negotiated legacy binary stream', async () => { - // Legacy mobile knows opcodes only through 12 and must not receive 17. Drive capable desktop second to prove rejection was already processed for both. - const registry = createSubscriptionRegistryDouble() - const sendTerminal = vi.fn().mockRejectedValue(new Error('terminal_not_writable')) - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue(null), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: sendTerminal as unknown as OrcaRuntimeService['sendTerminal'], - updateDesktopViewport: vi.fn().mockResolvedValue(true), - handleMobileSubscribe: vi.fn(), - handleMobileUnsubscribe: vi.fn(), - updateMobileViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - async function subscribeLegacyBinary( - client: { id: string; type: 'mobile' | 'desktop' }, - capabilities: Record - ) { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { terminal: 'terminal-1', client, capabilities }), - (message) => messages.push(message), - { - connectionId: `conn-legacy-${client.id}`, - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - await vi.waitFor(() => - expect(messages.some((message) => JSON.parse(message).result?.type === 'subscribed')).toBe( - true - ) - ) - const streamId = JSON.parse( - messages.find((message) => JSON.parse(message).result?.type === 'subscribed')! - ).result.streamId as number - binaryFrames.splice(0) - return { - binaryFrames, - dispatchPromise, - sendInput: () => - handlers.get(streamId)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId, - seq: 1, - payload: encodeTerminalStreamText('x') - }) - )! - ) - } - } - - const legacy = await subscribeLegacyBinary( - { id: 'mobile-1', type: 'mobile' }, - { terminalBinaryStream: 1 } - ) - const capable = await subscribeLegacyBinary( - { id: 'desktop-1', type: 'desktop' }, - { terminalBinaryStream: 1, writeUnavailable: 1 } - ) - - legacy.sendInput() - capable.sendInput() - - await vi.waitFor(() => expect(sendTerminal).toHaveBeenCalledTimes(2)) - await vi.waitFor(() => - expect(capable.binaryFrames.some((frame) => frame[2] === WRITE_UNAVAILABLE_OPCODE)).toBe(true) - ) - expect(legacy.binaryFrames.some((frame) => frame[2] === WRITE_UNAVAILABLE_OPCODE)).toBe(false) - - runtime.cleanupSubscription('terminal-1:mobile-1') - runtime.cleanupSubscription('terminal-1:desktop-1') - await Promise.all([legacy.dispatchPromise, capable.dispatchPromise]) - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts b/src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts deleted file mode 100644 index 47fdab6a9fc..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts +++ /dev/null @@ -1,302 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' - -import type { RuntimeTerminalDataMeta } from '../terminal/output/runtime-terminal-stream-consumers' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - SET_OUTPUT_PAUSED_OPCODE, - makeRequest, - startDesktopMultiplexSubscribe, - stubRuntime -} from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('withholds sustained output from multiple paused desktop streams', async () => { - const listeners: ((data: string, meta?: RuntimeTerminalDataMeta) => void)[] = [] - const harness = startDesktopMultiplexSubscribe({ - subscribeToTerminalData: vi.fn((_ptyId, listener) => { - listeners.push(listener) - return vi.fn() - }), - serializeAuthoritativeTerminalBuffer: vi.fn().mockResolvedValue({ - data: 'authoritative hidden snapshot', - cols: 120, - rows: 40, - seq: 7, - source: 'headless' - }) - }) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - - for (const streamId of [1, 2, 3]) { - harness.handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: streamId, - payload: encodeTerminalStreamJson({ - streamId, - terminal: `terminal-${streamId}`, - client: { id: `desktop-${streamId}`, type: 'desktop' }, - capabilities: { ackOutput: 1, outputPause: 1 } - }) - }) - )! - ) - } - await vi.waitFor(() => - expect( - harness.messages.filter((message) => JSON.parse(message).result?.type === 'subscribed') - ).toHaveLength(3) - ) - const pauseCapable = harness.messages - .map((message) => JSON.parse(message).result) - .filter((event) => event?.type === 'subscribed') - .every((event) => event.capabilities?.outputPause === 1) - if (pauseCapable) { - for (const streamId of [1, 2, 3]) { - harness.handlers.get(streamId)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: SET_OUTPUT_PAUSED_OPCODE, - streamId, - seq: 10, - payload: encodeTerminalStreamJson({ paused: true }) - }) - )! - ) - } - } - harness.binaryFrames.splice(0) - const chunk = 'x'.repeat(64 * 1024) - for (let turn = 0; turn < 8; turn += 1) { - for (const listener of listeners) { - listener(chunk, { seq: (turn + 1) * chunk.length, rawLength: chunk.length }) - } - } - expect( - harness.binaryFrames.some( - (bytes) => decodeTerminalStreamFrame(bytes)?.opcode === TerminalStreamOpcode.Output - ) - ).toBe(false) - expect(pauseCapable).toBe(true) - - harness.handlers.get(1)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: SET_OUTPUT_PAUSED_OPCODE, - streamId: 1, - seq: 11, - payload: encodeTerminalStreamJson({ paused: false }) - }) - )! - ) - listeners[0]?.('VISIBLE_MARKER', { seq: 8 * chunk.length + 14, rawLength: 14 }) - listeners[0]?.('y'.repeat(64 * 1024), { - seq: 9 * chunk.length + 14, - rawLength: 64 * 1024 - }) - expect( - harness.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') - ).toContain('VISIBLE_MARKER') - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - expect(harness.handlers.size).toBe(0) - }) - - it('drops stale mobile resize re-stream completions for multiplex streams', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const registry = createSubscriptionRegistryDouble() - let resizeListener: - | ((event: { - cols: number - rows: number - displayMode: string - reason: string - seq: number - }) => void) - | undefined - const restreamResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] - const write = vi.fn() - const commit = vi.fn().mockResolvedValue(undefined) - const beginMobileInputFloor = vi.fn(() => ({ commit, rollback: vi.fn() })) - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValueOnce({ data: 'initial', cols: 80, rows: 24 }) - .mockImplementation( - () => - new Promise<{ data: string; cols: number; rows: number }>((resolve) => { - restreamResolves.push(resolve) - }) - ), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - handleMobileSubscribe: vi.fn().mockResolvedValue(undefined), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn((_, listener) => { - resizeListener = listener as typeof resizeListener - return vi.fn() - }), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockImplementation(async (_handle, _action, options) => { - options.reserveWrite('pty-1') - write() - await options.afterWrite('pty-1') - return { accepted: true } - }), - beginMobileInputFloor, - updateMobileViewport: vi.fn().mockResolvedValue({ updated: false, applied: false }) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-stale-multiplex-resize', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 5, - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' } - }) - }) - )! - ) - - await vi.waitFor(() => expect(resizeListener).toBeDefined()) - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Resize, - streamId: 5, - seq: 2, - payload: encodeTerminalStreamJson({ cols: 90, rows: 24 }) - }) - )! - ) - await vi.waitFor(() => expect(runtime.updateMobileViewport).toHaveBeenCalled()) - handlers.get(5)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId: 5, - seq: 3, - payload: encodeTerminalStreamText('x') - }) - )! - ) - await vi.waitFor(() => - expect(runtime.sendTerminal).toHaveBeenCalledWith( - 'terminal-1', - { text: 'x', enter: false, interrupt: false }, - { - inputKind: 'driving', - inputSource: 'mobile', - reserveWrite: expect.any(Function), - afterWrite: expect.any(Function) - } - ) - ) - expect(beginMobileInputFloor.mock.invocationCallOrder[0]).toBeLessThan( - write.mock.invocationCallOrder[0]! - ) - expect(write.mock.invocationCallOrder[0]).toBeLessThan(commit.mock.invocationCallOrder[0]!) - binaryFrames.splice(0) - - resizeListener?.({ - cols: 90, - rows: 24, - displayMode: 'auto', - reason: 'apply-layout', - seq: 2 - }) - resizeListener?.({ - cols: 100, - rows: 24, - displayMode: 'auto', - reason: 'apply-layout', - seq: 3 - }) - await vi.waitFor(() => expect(restreamResolves).toHaveLength(2)) - - restreamResolves[1]?.({ data: 'newer', cols: 100, rows: 24 }) - await vi.waitFor(() => - expect( - binaryFrames.some((frame) => { - const decoded = decodeTerminalStreamFrame(frame) - return ( - decoded?.opcode === TerminalStreamOpcode.SnapshotChunk && - decodeTerminalStreamText(decoded.payload) === 'newer' - ) - }) - ).toBe(true) - ) - restreamResolves[0]?.({ data: 'older', cols: 90, rows: 24 }) - await Promise.resolve() - await Promise.resolve() - - const snapshotData = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - expect(snapshotData).toEqual(['newer']) - - registry.cleanupSubscription('terminal-multiplex:conn-stale-multiplex-resize') - await dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts b/src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts deleted file mode 100644 index 1596d1a5653..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts +++ /dev/null @@ -1,290 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import './dispatcher' -import './methods/terminal/terminal' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - encodeTerminalStreamFrame, - encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION, - TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION -} from '../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { - sendDesktopMultiplexSubscribe, - startDesktopMultiplexSubscribe, - stubRuntime -} from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('cancels a pending desktop PTY wait when its multiplex slot unsubscribes', async () => { - let resolvePty: (ptyId: string) => void = () => {} - let waitSignal: AbortSignal | undefined - const readTerminal = vi.fn().mockResolvedValue({ tail: [], truncated: false }) - const subscribeToTerminalData = vi.fn().mockReturnValue(vi.fn()) - const registerRemoteTerminalViewSubscriber = vi.fn().mockReturnValue(vi.fn()) - const waitForLeafPtyId = vi.fn( - (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => - new Promise((resolve, reject) => { - resolvePty = resolve - waitSignal = signal - signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { - once: true - }) - }) - ) - const harness = startDesktopMultiplexSubscribe({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), - waitForLeafPtyId, - readTerminal, - subscribeToTerminalData, - registerRemoteTerminalViewSubscriber - }) - await vi.waitFor(() => - expect(harness.messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - sendDesktopMultiplexSubscribe(harness.handlers) - await vi.waitFor(() => expect(waitForLeafPtyId).toHaveBeenCalled()) - - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Unsubscribe, - streamId: 7, - seq: 2, - payload: new Uint8Array() - }) - )! - ) - resolvePty('pty-1') - - await vi.waitFor(() => - expect(waitSignal?.aborted || readTerminal.mock.calls.length > 0).toBe(true) - ) - // Closed panes must not become hidden output consumers when their late PTY appears. - expect(waitSignal?.aborted).toBe(true) - expect(readTerminal).not.toHaveBeenCalled() - expect(subscribeToTerminalData).not.toHaveBeenCalled() - expect(registerRemoteTerminalViewSubscriber).not.toHaveBeenCalled() - expect(harness.handlers.has(7)).toBe(false) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - }) - - it('admits 128 active streams, rejects the 129th, and reuses released capacity', async () => { - let dataSubscriberCount = 0 - let viewSubscriberCount = 0 - const harness = startDesktopMultiplexSubscribe({ - subscribeToTerminalData: vi.fn(() => { - dataSubscriberCount += 1 - let released = false - return () => { - if (!released) { - released = true - dataSubscriberCount -= 1 - } - } - }), - registerRemoteTerminalViewSubscriber: vi.fn(() => { - viewSubscriberCount += 1 - let released = false - return () => { - if (!released) { - released = true - viewSubscriberCount -= 1 - } - } - }) - }) - await vi.waitFor(() => - expect(harness.messages.some((message) => JSON.parse(message).result?.type === 'ready')).toBe( - true - ) - ) - const sendSubscribe = (streamId: number): void => { - harness.handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: streamId, - payload: encodeTerminalStreamJson({ - streamId, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - capabilities: { ackOutput: 1 } - }) - }) - )! - ) - } - for ( - let streamId = 1; - streamId <= TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1; - streamId += 1 - ) { - sendSubscribe(streamId) - } - - await vi.waitFor(() => { - const results = harness.messages.map((message) => JSON.parse(message).result) - const subscribedStreamIds = results - .filter((result) => result?.type === 'subscribed') - .map((result) => result.streamId) - expect(subscribedStreamIds).toHaveLength(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) - expect(subscribedStreamIds).toContain(44) - expect(results).toContainEqual({ - type: 'error', - streamId: TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1, - message: 'terminal_stream_limit_exceeded' - }) - expect(results).toContainEqual({ - type: 'end', - streamId: TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1 - }) - }) - expect(dataSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) - expect(viewSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) - - harness.handlers.get(1)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Unsubscribe, - streamId: 1, - seq: TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 2, - payload: new Uint8Array() - }) - )! - ) - await vi.waitFor(() => { - expect(dataSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION - 1) - expect(viewSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION - 1) - expect(harness.handlers.has(1)).toBe(false) - }) - - const retriedStreamId = TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1 - sendSubscribe(retriedStreamId) - await vi.waitFor(() => { - const subscribedStreamIds = harness.messages - .map((message) => JSON.parse(message).result) - .filter((result) => result?.type === 'subscribed') - .map((result) => result.streamId) - expect(subscribedStreamIds).toContain(retriedStreamId) - expect( - harness.binaryFrames.some((bytes) => { - const frame = decodeTerminalStreamFrame(bytes) - return ( - frame?.streamId === retriedStreamId && frame.opcode === TerminalStreamOpcode.SnapshotEnd - ) - }) - ).toBe(true) - }) - expect(dataSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) - expect(viewSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - expect(dataSubscriberCount).toBe(0) - expect(viewSubscriberCount).toBe(0) - }) - - it('queues PTY waits past the running cap independently from active streams', async () => { - const activeStreamCount = 44 - const waitSignals: AbortSignal[] = [] - const resolveWaits: ((ptyId: string) => void)[] = [] - const ptyIds = new Map() - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn((terminal: string) => - terminal.startsWith('pending-') - ? { ptyId: ptyIds.get(terminal) ?? null } - : { ptyId: `pty-${terminal}` } - ), - waitForLeafPtyId: vi.fn( - (handle: string, _timeoutMs?: number, signal?: AbortSignal) => - new Promise((resolve, reject) => { - if (signal) { - waitSignals.push(signal) - } - resolveWaits.push((ptyId) => { - ptyIds.set(handle, ptyId) - resolve(ptyId) - }) - signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { - once: true - }) - }) - ) - }) - const harness = startDesktopMultiplexSubscribe(runtime) - await vi.waitFor(() => - expect(harness.messages.some((message) => JSON.parse(message).result?.type === 'ready')).toBe( - true - ) - ) - const sendSubscribe = (streamId: number, terminal: string): void => { - harness.handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: streamId, - payload: encodeTerminalStreamJson({ - streamId, - terminal, - client: { id: 'desktop-1', type: 'desktop' }, - capabilities: { ackOutput: 1 } - }) - }) - )! - ) - } - - for (let streamId = 1; streamId <= activeStreamCount; streamId += 1) { - sendSubscribe(streamId, `active-${streamId}`) - } - await vi.waitFor(() => - expect( - harness.messages.filter((message) => JSON.parse(message).result?.type === 'subscribed') - ).toHaveLength(activeStreamCount) - ) - - for ( - let offset = 1; - offset <= TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION + 1; - offset += 1 - ) { - sendSubscribe(activeStreamCount + offset, `pending-${offset}`) - } - await vi.waitFor(() => - expect(waitSignals).toHaveLength(TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION) - ) - // Queue beyond the running cap instead of failing restore (STA-2886). - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(waitSignals).toHaveLength(TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION) - - resolveWaits[0]?.('pty-pending-1') - await vi.waitFor(() => - expect(waitSignals).toHaveLength(TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION + 1) - ) - for (const [index, resolve] of resolveWaits.entries()) { - resolve(`pty-pending-${index + 1}`) - } - await vi.waitFor(() => { - const results = harness.messages.map((message) => JSON.parse(message).result) - expect(results.filter((result) => result?.type === 'subscribed')).toHaveLength( - activeStreamCount + TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION + 1 - ) - expect( - results.filter( - (result) => - result?.type === 'error' && result.message === 'terminal_stream_limit_exceeded' - ) - ).toHaveLength(0) - }) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-pty-wait-queue.test.ts b/src/main/runtime/rpc/terminal-multiplex-pty-wait-queue.test.ts deleted file mode 100644 index c1ee43c9ed1..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-pty-wait-queue.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - encodeTerminalStreamFrame, - encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION, - TERMINAL_MULTIPLEX_MAX_QUEUED_PTY_WAITS_PER_CONNECTION -} from '../../../shared/terminal/stream/terminal-multiplex-flow-control' - -import { startDesktopMultiplexSubscribe } from './terminal-multiplex-test-harness' - -function startPendingPtyHarness() { - const waits = new Map void }>() - const ptyIds = new Map() - const requestRendererTerminalTabMount = vi.fn() - const harness = startDesktopMultiplexSubscribe({ - resolveLiveLeafForHandle: vi.fn((handle: string) => ({ ptyId: ptyIds.get(handle) ?? null })), - requestRendererTerminalTabMount, - waitForLeafPtyId: vi.fn( - (handle: string, _timeoutMs?: number, signal?: AbortSignal) => - new Promise((resolve, reject) => { - if (signal) { - waits.set(handle, { - signal, - resolve: (ptyId) => { - ptyIds.set(handle, ptyId) - resolve(ptyId) - } - }) - } - signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { - once: true - }) - }) - ) - }) - const send = (opcode: TerminalStreamOpcode, streamId: number, terminal?: string): void => { - const subscribe = opcode === TerminalStreamOpcode.Subscribe - harness.handlers.get(subscribe ? 0 : streamId)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode, - streamId: subscribe ? 0 : streamId, - seq: streamId, - payload: subscribe - ? encodeTerminalStreamJson({ - streamId, - terminal, - client: { id: 'desktop-1', type: 'desktop' }, - capabilities: { ackOutput: 1 } - }) - : new Uint8Array() - }) - )! - ) - } - const results = (): { type?: string; streamId?: number; message?: string }[] => - harness.messages.map((message) => JSON.parse(message).result) - return { harness, waits, requestRendererTerminalTabMount, send, results } -} - -describe('terminal multiplex PTY wait queue', () => { - it('rejects only past the queue bound and admits queued waits in order', async () => { - const { harness, waits, requestRendererTerminalTabMount, send, results } = - startPendingPtyHarness() - await vi.waitFor(() => expect(results().some((r) => r?.type === 'ready')).toBe(true)) - const total = - TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION + - TERMINAL_MULTIPLEX_MAX_QUEUED_PTY_WAITS_PER_CONNECTION - for (let streamId = 1; streamId <= total + 1; streamId += 1) { - send(TerminalStreamOpcode.Subscribe, streamId, `pane-${streamId}`) - } - await vi.waitFor(() => - expect(results()).toContainEqual({ - type: 'error', - streamId: total + 1, - message: 'terminal_stream_limit_exceeded' - }) - ) - expect( - results().filter((r) => r?.type === 'error' && r.message === 'terminal_stream_limit_exceeded') - ).toHaveLength(1) - await vi.waitFor(() => - expect(waits.size).toBe(TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION) - ) - // Mount only during paced admission, not when subscribe queues the pane. - expect(requestRendererTerminalTabMount).toHaveBeenCalledTimes( - TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION - ) - - waits.get('pane-1')?.resolve('pty-1') - const next = `pane-${TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION + 1}` - await vi.waitFor(() => expect(waits.has(next)).toBe(true)) - await vi.waitFor(() => - expect(results()).toContainEqual(expect.objectContaining({ type: 'subscribed', streamId: 1 })) - ) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await vi.waitFor(() => expect(waits.get(next)?.signal.aborted).toBe(true)) - await harness.dispatchPromise - }) - - it('drops a queued wait on unsubscribe without spending a running slot', async () => { - const { harness, waits, send, results } = startPendingPtyHarness() - await vi.waitFor(() => expect(results().some((r) => r?.type === 'ready')).toBe(true)) - const cap = TERMINAL_MULTIPLEX_MAX_PENDING_PTY_WAITS_PER_CONNECTION - for (let streamId = 1; streamId <= cap + 2; streamId += 1) { - send(TerminalStreamOpcode.Subscribe, streamId, `pane-${streamId}`) - } - await vi.waitFor(() => expect(waits.size).toBe(cap)) - send(TerminalStreamOpcode.Unsubscribe, cap + 1) - waits.get('pane-1')?.resolve('pty-1') - - await vi.waitFor(() => expect(waits.has(`pane-${cap + 2}`)).toBe(true)) - expect(waits.has(`pane-${cap + 1}`)).toBe(false) - - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-round-robin.test.ts b/src/main/runtime/rpc/terminal-multiplex-round-robin.test.ts deleted file mode 100644 index 96e04718c91..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-round-robin.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { drainTerminalMultiplexRoundRobin } from './terminal-multiplex-round-robin' - -describe('terminal multiplex round-robin drain', () => { - it('admits a later interactive stream before older bulk queues refill the window', () => { - const streams = Array.from({ length: 8 }, (_, index) => ({ - streamId: index + 1, - pendingChunks: index === 7 ? 1 : 8 - })) - const order: number[] = [] - let remainingSlots = 8 - - const cursor = drainTerminalMultiplexRoundRobin({ - streams, - cursorStreamId: null, - canContinue: () => remainingSlots > 0, - drainOne: (stream) => { - if (stream.pendingChunks === 0) { - return false - } - stream.pendingChunks -= 1 - remainingSlots -= 1 - order.push(stream.streamId) - return true - } - }) - - expect(order).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) - expect(cursor).toBe(8) - }) - - it('resumes after the previous sender on the next release', () => { - const streams = [1, 2, 3].map((streamId) => ({ streamId, pendingChunks: 2 })) - let slots = 2 - const firstOrder: number[] = [] - const cursor = drainTerminalMultiplexRoundRobin({ - streams, - cursorStreamId: null, - canContinue: () => slots > 0, - drainOne: (stream) => { - stream.pendingChunks -= 1 - slots -= 1 - firstOrder.push(stream.streamId) - return true - } - }) - slots = 2 - const secondOrder: number[] = [] - drainTerminalMultiplexRoundRobin({ - streams, - cursorStreamId: cursor, - canContinue: () => slots > 0, - drainOne: (stream) => { - if (stream.pendingChunks === 0) { - return false - } - stream.pendingChunks -= 1 - slots -= 1 - secondOrder.push(stream.streamId) - return true - } - }) - - expect(firstOrder).toEqual([1, 2]) - expect(secondOrder).toEqual([3, 1]) - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-snapshot-query-replay.test.ts b/src/main/runtime/rpc/terminal-multiplex-snapshot-query-replay.test.ts deleted file mode 100644 index 0f914a7038a..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-snapshot-query-replay.test.ts +++ /dev/null @@ -1,361 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { Terminal } from '@xterm/headless' -import type { RuntimeTerminalDataMeta } from '../terminal/output/runtime-terminal-stream-consumers' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { - sendDesktopMultiplexSubscribe, - startDesktopMultiplexSubscribe -} from './terminal-multiplex-test-harness' -import { TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES } from '../../../shared/terminal/stream/terminal-multiplex-flow-control' - -afterEach(() => vi.useRealTimers()) - -describe.each([ - { parserState: 'ground', pending: '', suffix: 'AFTER', soleOwner: true }, - { parserState: 'CSI', pending: '\x1b[31', suffix: 'mAFTER', soleOwner: true }, - { parserState: 'OSC', pending: '\x1b]777;payload', suffix: 'end\x07AFTER', soleOwner: true }, - { parserState: 'DCS', pending: '\x1bP1qpayload', suffix: 'end\x1b\\AFTER', soleOwner: true }, - { parserState: 'ground with another owner', pending: '', suffix: 'AFTER', soleOwner: false } -])( - 'multiplex snapshot-covered queries with $parserState parser state', - ({ pending, suffix, soleOwner }) => { - it.each(['initial', 'requested'] as const)( - 'preserves DA1 ownership across the %s snapshot without replaying stale CPR', - async (kind) => { - vi.useFakeTimers() - let output: ((data: string, meta?: RuntimeTerminalDataMeta) => void) | undefined - let completeSnapshot: - | ((snapshot: { - data: string - cols: number - rows: number - seq: number - pendingEscapeTailAnsi?: string - }) => void) - | undefined - let holdSnapshot = kind === 'initial' - const answerYieldedTerminalQueries = vi.fn() - const harness = startDesktopMultiplexSubscribe({ - isSoleRemoteTerminalQueryOwner: () => soleOwner, - answerYieldedTerminalQueries, - serializeTerminalBuffer: vi.fn(async () => { - if (!holdSnapshot) { - return { data: '', cols: 80, rows: 24, seq: 0 } - } - return new Promise<{ - data: string - cols: number - rows: number - seq: number - pendingEscapeTailAnsi?: string - }>((resolve) => { - completeSnapshot = resolve - }) - }), - subscribeToTerminalData: vi.fn((_ptyId, listener) => { - output = listener - return vi.fn() - }) - }) - try { - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendDesktopMultiplexSubscribe(harness.handlers) - await vi.waitFor(() => expect(output).toBeDefined()) - if (kind === 'requested') { - await vi.waitFor(() => - expect( - harness.messages.some( - (message) => JSON.parse(message).result?.type === 'subscribed' - ) - ).toBe(true) - ) - holdSnapshot = true - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.SnapshotRequest, - streamId: 7, - seq: 2, - payload: encodeTerminalStreamJson({}) - }) - )! - ) - } - await vi.waitFor(() => expect(completeSnapshot).toBeDefined()) - const prefix = 'covered\x1b[6n\x1b[' - const finalChunk = `c${pending}${suffix}` - const snapshotSeq = prefix.length + 1 + pending.length - output?.(prefix, { seq: prefix.length, rawLength: prefix.length }) - output?.(finalChunk, { - seq: prefix.length + finalChunk.length, - rawLength: finalChunk.length - }) - completeSnapshot?.({ - data: 'covered', - cols: 80, - rows: 24, - seq: snapshotSeq, - pendingEscapeTailAnsi: pending - }) - await vi.runOnlyPendingTimersAsync() - - const frames = harness.binaryFrames.map(decodeTerminalStreamFrame) - const snapshotEnd = frames.findLastIndex( - (frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd - ) - const live = frames - .slice(snapshotEnd + 1) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - expect( - live.map((frame) => frame && decodeTerminalStreamText(frame.payload)).join('') - ).toBe(soleOwner ? `${pending ? '\x18' : ''}\x1b[c${pending}${suffix}` : suffix) - if (soleOwner) { - expect(live[0]?.seq).toBe(0) - } - - const terminal = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) - const replies: string[] = [] - terminal.onData((reply) => replies.push(reply)) - try { - const seeded = new Promise((resolve) => terminal.write(pending, resolve)) - await vi.runOnlyPendingTimersAsync() - await seeded - for (const frame of live) { - if (frame) { - const parsed = new Promise((resolve) => - terminal.write(decodeTerminalStreamText(frame.payload), resolve) - ) - await vi.runOnlyPendingTimersAsync() - await parsed - } - } - expect(replies).toEqual(soleOwner ? ['\x1b[?1;2c'] : []) - expect(terminal.buffer.active.getLine(0)?.translateToString(true)).toBe('AFTER') - } finally { - terminal.dispose() - } - } finally { - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - } - expect(answerYieldedTerminalQueries).not.toHaveBeenCalled() - } - ) - } -) - -it.each([ - { queryCount: 2, action: 'pause' }, - { queryCount: 20, action: 'drain' }, - { queryCount: 200, action: 'drain' } -])( - 'preserves bounded query ownership for $queryCount transformed queries during $action', - async ({ queryCount, action }) => { - vi.useFakeTimers() - let output: ((data: string, meta?: RuntimeTerminalDataMeta) => void) | undefined - let completeSnapshot: - | ((snapshot: { data: string; cols: number; rows: number; seq: number }) => void) - | undefined - let holdSnapshot = false - const answerYieldedTerminalQueries = vi.fn() - const harness = startDesktopMultiplexSubscribe({ - isSoleRemoteTerminalQueryOwner: () => true, - answerYieldedTerminalQueries, - serializeTerminalBuffer: vi.fn(async () => { - if (!holdSnapshot) { - return { data: '', cols: 80, rows: 24, seq: 0 } - } - return new Promise<{ data: string; cols: number; rows: number; seq: number }>((resolve) => { - completeSnapshot = resolve - }) - }), - subscribeToTerminalData: vi.fn((_ptyId, listener) => { - output = listener - return vi.fn() - }) - }) - const send = (opcode: TerminalStreamOpcode, payload: Record): void => { - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode, - streamId: 7, - seq: 2, - payload: encodeTerminalStreamJson(payload) - }) - )! - ) - } - try { - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendDesktopMultiplexSubscribe(harness.handlers, { ackOutput: 1, outputPause: 1 }) - await vi.waitFor(() => - expect( - harness.messages.some((message) => JSON.parse(message).result?.type === 'subscribed') - ).toBe(true) - ) - const fill = 'x'.repeat(TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES - 3) - output?.(fill, { seq: fill.length, rawLength: fill.length }) - await vi.runOnlyPendingTimersAsync() - harness.binaryFrames.splice(0) - holdSnapshot = true - send(TerminalStreamOpcode.SnapshotRequest, {}) - await vi.waitFor(() => expect(completeSnapshot).toBeDefined()) - const rawLength = queryCount * 10 - const seq = fill.length + rawLength - output?.('\x1b[c'.repeat(queryCount), { seq, rawLength, transformed: true }) - completeSnapshot?.({ data: '', cols: 80, rows: 24, seq }) - await vi.runOnlyPendingTimersAsync() - if (action === 'pause') { - send(TerminalStreamOpcode.SetOutputPaused, { paused: true }) - } else { - send(TerminalStreamOpcode.Ack, { bytes: fill.length + 3 }) - await vi.runOnlyPendingTimersAsync() - } - const sentQueries = harness.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => frame && decodeTerminalStreamText(frame.payload)) - .join('') - expect(sentQueries).toBe('\x1b[c'.repeat(action === 'pause' ? 1 : 16)) - if (action === 'pause') { - expect(answerYieldedTerminalQueries).toHaveBeenCalledExactlyOnceWith('pty-1', '\x1b[c') - } else { - expect(answerYieldedTerminalQueries).not.toHaveBeenCalled() - } - } finally { - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - } - } -) - -type ReleaseHeldSnapshot = (extra?: { pendingEscapeTailAnsi?: string }) => void - -async function startSoleQueryOwnerStream() { - let listener: ((data: string, meta?: RuntimeTerminalDataMeta) => void) | undefined - let seq = 0 - let holdNextSnapshot = false - let releaseSnapshot: ReleaseHeldSnapshot | undefined - const answerYieldedTerminalQueries = vi.fn() - const harness = startDesktopMultiplexSubscribe({ - isSoleRemoteTerminalQueryOwner: () => true, - answerYieldedTerminalQueries, - serializeTerminalBuffer: vi.fn(async () => { - if (!holdNextSnapshot) { - return { data: '', cols: 80, rows: 24, seq } - } - holdNextSnapshot = false - return new Promise<{ - data: string - cols: number - rows: number - seq: number - pendingEscapeTailAnsi?: string - }>((resolve) => { - releaseSnapshot = (extra) => resolve({ data: '', cols: 80, rows: 24, seq, ...extra }) - }) - }), - subscribeToTerminalData: vi.fn((_ptyId, onData) => { - listener = onData - return vi.fn() - }) - }) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - return { - answerYieldedTerminalQueries, - holdNextSnapshot: (): void => { - holdNextSnapshot = true - }, - held: async (): Promise => { - await vi.waitFor(() => expect(releaseSnapshot).toBeDefined()) - const release = releaseSnapshot! - releaseSnapshot = undefined - return release - }, - subscribe: async (): Promise => { - sendDesktopMultiplexSubscribe(harness.handlers) - await vi.waitFor(() => expect(listener).toBeDefined()) - }, - waitSubscribed: () => - vi.waitFor(() => - expect( - harness.messages.some((message) => JSON.parse(message).result?.type === 'subscribed') - ).toBe(true) - ), - send: (opcode: TerminalStreamOpcode, payload: Record): void => { - harness.handlers.get(7)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode, - streamId: 7, - seq: 2, - payload: encodeTerminalStreamJson(payload) - }) - )! - ) - }, - emit: async (data: string, { holdInBatcher = false } = {}): Promise => { - seq += data.length - listener?.(data, { seq, rawLength: data.length }) - if (!holdInBatcher) { - await vi.runOnlyPendingTimersAsync() - } - }, - currentSeq: (): number => seq, - snapshotEndCount: (): number => - harness.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd).length, - /** `viewerCutoffSeq` mirrors the viewer dropping seq'd output its recovery snapshot covers. */ - outputAfterLastSnapshot: (viewerCutoffSeq = 0): string => { - const frames = harness.binaryFrames.map(decodeTerminalStreamFrame) - const snapshotEnd = frames.findLastIndex( - (frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd - ) - return frames - .slice(snapshotEnd + 1) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .filter((frame) => !frame?.seq || frame.seq > viewerCutoffSeq) - .map((frame) => frame && decodeTerminalStreamText(frame.payload)) - .join('') - }, - cleanup: async (): Promise => { - harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') - await harness.dispatchPromise - } - } -} - -it('drops a superseded snapshot replay and its escape tail queued behind the ACK window', async () => { - vi.useFakeTimers() - const stream = await startSoleQueryOwnerStream() - try { - await stream.subscribe() - await stream.waitSubscribed() - await stream.emit('x'.repeat(TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES)) - stream.holdNextSnapshot() - stream.send(TerminalStreamOpcode.SnapshotRequest, {}) - const release = await stream.held() - await stream.emit('\x1b[c\x1b[31') - release({ pendingEscapeTailAnsi: '\x1b[31' }) - await vi.runOnlyPendingTimersAsync() - stream.send(TerminalStreamOpcode.SnapshotRequest, {}) - await vi.runOnlyPendingTimersAsync() - stream.send(TerminalStreamOpcode.Ack, { - bytes: TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES - }) - await vi.runOnlyPendingTimersAsync() - - expect(stream.outputAfterLastSnapshot()).toBe('\x1b[c') - expect(stream.answerYieldedTerminalQueries).not.toHaveBeenCalled() - } finally { - await stream.cleanup() - } -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts b/src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts deleted file mode 100644 index f316210e420..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts +++ /dev/null @@ -1,303 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('falls back to smaller requested snapshots when serialized data exceeds the send budget', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValueOnce({ data: 'initial', cols: 120, rows: 40 }) - .mockResolvedValueOnce({ - data: 'x'.repeat(2 * 1024 * 1024 + 1), - cols: 120, - rows: 40 - }) - .mockResolvedValueOnce({ - data: 'budgeted snapshot', - cols: 120, - rows: 40 - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-budgeted-request', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 14, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 } - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - const frameCountBeforeSnapshotRequest = binaryFrames.length - - handlers.get(14)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.SnapshotRequest, - streamId: 14, - seq: 2, - payload: encodeTerminalStreamJson({ - requestId: 55, - scrollbackRows: 5000 - }) - }) - )! - ) - await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(3)) - - const requestedFrames = binaryFrames - .slice(frameCountBeforeSnapshotRequest) - .map((frame) => decodeTerminalStreamFrame(frame)) - const requestedStart = requestedFrames.find( - (frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart - ) - expect(requestedStart && decodeTerminalStreamJson(requestedStart.payload)).toMatchObject({ - requestId: 55, - truncatedByByteBudget: true - }) - expect(runtime.serializeTerminalBuffer).toHaveBeenNthCalledWith(2, 'pty-1', { - scrollbackRows: 5000 - }) - expect(runtime.serializeTerminalBuffer).toHaveBeenNthCalledWith(3, 'pty-1', { - scrollbackRows: 1000 - }) - expect( - requestedFrames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - ).toBe('budgeted snapshot') - - cleanups.get('terminal-multiplex:conn-budgeted-request')?.() - await dispatchPromise - }) - - it('retries requested snapshots after live output overflows during serialization', async () => { - vi.useFakeTimers() - try { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - const dataListenerRef: { current?: (data: string) => void } = {} - let resolveRequestedSnapshot: (value: { - data: string - cols: number - rows: number - }) => void = () => {} - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValueOnce({ data: 'initial', cols: 120, rows: 40 }) - .mockImplementationOnce( - () => - new Promise<{ data: string; cols: number; rows: number }>((resolve) => { - resolveRequestedSnapshot = resolve - }) - ) - .mockResolvedValueOnce({ - data: 'retry snapshot', - cols: 120, - rows: 40 - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => { - dataListenerRef.current = listener - return vi.fn() - }), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateDesktopViewport: vi.fn().mockResolvedValue(true) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-request-overflow', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 12, - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 120, rows: 40 } - }) - }) - )! - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) - ) - const frameCountBeforeSnapshotRequest = binaryFrames.length - - handlers.get(12)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.SnapshotRequest, - streamId: 12, - seq: 2, - payload: encodeTerminalStreamJson({ - requestId: 44, - scrollbackRows: 5000 - }) - }) - )! - ) - await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(2)) - for (let index = 0; index < 400; index += 1) { - dataListenerRef.current?.(String(index).padStart(3, '0') + 'x'.repeat(1021)) - } - resolveRequestedSnapshot({ data: 'requested', cols: 120, rows: 40 }) - await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(3)) - await vi.waitFor(() => - expect( - binaryFrames - .slice(frameCountBeforeSnapshotRequest) - .map((frame) => decodeTerminalStreamFrame(frame)) - .some((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd) - ).toBe(true) - ) - - const requestedFrames = binaryFrames - .slice(frameCountBeforeSnapshotRequest) - .map((frame) => decodeTerminalStreamFrame(frame)) - const requestedStart = requestedFrames.find( - (frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart - ) - expect(requestedStart && decodeTerminalStreamJson(requestedStart.payload)).toMatchObject({ - requestId: 44, - truncated: false - }) - expect( - requestedFrames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - ).toBe('retry snapshot') - expect( - requestedFrames - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - ).toBe('') - - dataListenerRef.current?.('live-after-overflow') - await vi.runOnlyPendingTimersAsync() - const outputAfterOverflow = binaryFrames - .slice(frameCountBeforeSnapshotRequest) - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - .join('') - expect(outputAfterOverflow).toBe('live-after-overflow') - - cleanups.get('terminal-multiplex:conn-request-overflow')?.() - await dispatchPromise - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/rpc/terminal-multiplex-subscribe-slot-recovery.test.ts b/src/main/runtime/rpc/terminal-multiplex-subscribe-slot-recovery.test.ts deleted file mode 100644 index 95fd20f1ef4..00000000000 --- a/src/main/runtime/rpc/terminal-multiplex-subscribe-slot-recovery.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - encodeTerminalStreamFrame, - encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' - -describe('terminal multiplex RPC', () => { - it('keeps an evicted subscribe error from detaching the successor stream', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const cleanups = new Map void>() - let viewSubscriberCount = 0 - const mobileSubscribeWaiters: { - resolve: () => void - reject: (error: Error) => void - }[] = [] - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - registerRemoteTerminalViewSubscriber: vi.fn(() => { - viewSubscriberCount += 1 - let released = false - return () => { - if (!released) { - released = true - viewSubscriberCount -= 1 - } - } - }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snap', cols: 80, rows: 24 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - handleMobileSubscribe: vi.fn( - () => - new Promise((resolve, reject) => { - mobileSubscribeWaiters.push({ resolve: () => resolve(true), reject }) - }) - ), - handleMobileUnsubscribe: vi.fn(), - registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { - cleanups.set(id, cleanup) - }), - waitForTerminal: vi.fn(() => new Promise(() => {})) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.multiplex', {}), - (msg) => messages.push(msg), - { - connectionId: 'conn-evicted-error', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - await vi.waitFor(() => - expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) - ) - const sendSubscribe = (): void => { - handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId: 9, - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' } - }) - }) - )! - ) - } - - // A registers then waits in layout; B evicts it and completes registration. - sendSubscribe() - await vi.waitFor(() => expect(mobileSubscribeWaiters).toHaveLength(1)) - sendSubscribe() - await vi.waitFor(() => expect(mobileSubscribeWaiters).toHaveLength(2)) - mobileSubscribeWaiters[1]!.resolve() - await vi.waitFor(() => - expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength( - 1 - ) - ) - expect(viewSubscriberCount).toBe(1) - - // A's failed continuation must not detach successor B. - mobileSubscribeWaiters[0]!.reject(new Error('mobile_subscribe_failed')) - await Promise.resolve() - await Promise.resolve() - expect(viewSubscriberCount).toBe(1) - - cleanups.get('terminal-multiplex:conn-evicted-error')?.() - await dispatchPromise - expect(viewSubscriberCount).toBe(0) - }) -}) diff --git a/src/main/runtime/rpc/terminal-output-batching.test.ts b/src/main/runtime/rpc/terminal-output-batching.test.ts deleted file mode 100644 index c88ec22d2a6..00000000000 --- a/src/main/runtime/rpc/terminal-output-batching.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import '../../../shared/terminal/stream/terminal-stream-protocol' - -function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { - return { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - // Why: subscribe streams register as remote view subscribers for Phase-5 - registerRemoteTerminalViewSubscriber: () => () => {}, - ...overrides - } as OrcaRuntimeService -} - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -describe('terminal output batching', () => { - it('coalesces desktop terminal output bursts before emitting stream data', async () => { - vi.useFakeTimers() - try { - const messages: string[] = [] - const registry = createSubscriptionRegistryDouble() - const dataListenerRef: { current?: (data: string) => void } = {} - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue(null), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => { - dataListenerRef.current = listener - return vi.fn() - }), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' } - }), - (msg) => messages.push(msg) - ) - - await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined()) - const emitData = dataListenerRef.current - if (!emitData) { - throw new Error('missing terminal data listener') - } - emitData('a') - emitData('b') - - expect(messages.map((msg) => JSON.parse(msg).result?.type)).not.toContain('data') - - await vi.runOnlyPendingTimersAsync() - - const dataMessages = messages - .map((msg) => JSON.parse(msg)) - .filter((message) => message.result?.type === 'data') - expect(dataMessages).toHaveLength(1) - expect(dataMessages[0]).toMatchObject({ - result: { type: 'data', chunk: 'ab' } - }) - - runtime.cleanupSubscription('terminal-1:desktop-1') - await dispatchPromise - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/rpc/terminal-output-frame-chunks.test.ts b/src/main/runtime/rpc/terminal-output-frame-chunks.test.ts deleted file mode 100644 index ce71a4ecfa6..00000000000 --- a/src/main/runtime/rpc/terminal-output-frame-chunks.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { TERMINAL_STREAM_CHUNK_BYTES } from '../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { - iterateTerminalOutputFrameChunks, - type TerminalOutputMeta -} from './terminal-output-frame-chunks' - -const SURROGATE_PAIR = '\u{1f600}' -const LONE_HIGH = '\ud83d' - -function seqPreservingMeta(data: string, seq: number): TerminalOutputMeta { - return { seq, rawLength: data.length } -} - -describe('terminal output frame chunks', () => { - it('keeps every emitted frame within the wire cap and reassembles to the input', () => { - const data = `${'a'.repeat(TERMINAL_STREAM_CHUNK_BYTES - 3)}${SURROGATE_PAIR}${'a'.repeat(200 * 1024)}${SURROGATE_PAIR.repeat(4096)}${LONE_HIGH}` - const frames = [ - ...iterateTerminalOutputFrameChunks(data, seqPreservingMeta(data, 999_999), 'span') - ] - expect(frames.length).toBeGreaterThan(4) - for (const frame of frames) { - expect(frame.bytes.byteLength).toBeLessThanOrEqual(TERMINAL_STREAM_CHUNK_BYTES) - } - expect(Buffer.concat(frames.map((frame) => Buffer.from(frame.bytes))).toString('utf8')).toBe( - Buffer.from(new TextEncoder().encode(data)).toString('utf8') - ) - // Seqs must be strictly increasing and end at the meta high-water mark. - const seqs = frames.map((frame) => frame.seq!) - expect(seqs.every((seq, index) => index === 0 || seq > seqs[index - 1]!)).toBe(true) - expect(seqs.at(-1)).toBe(999_999) - }) - - it('sends a transformed span as capped text frames with its seq only on the last', () => { - const data = 'x'.repeat(TERMINAL_STREAM_CHUNK_BYTES * 2 + 1) - const meta = { seq: 500_000, rawLength: data.length + 8, transformed: true } - - const frames = [...iterateTerminalOutputFrameChunks(data, meta, 'text')] - - expect(frames.map((frame) => frame.opcode)).toEqual([undefined, undefined, undefined]) - expect(frames.map((frame) => frame.seq)).toEqual([undefined, undefined, 500_000]) - expect(frames.map((frame) => new TextDecoder().decode(frame.bytes)).join('')).toBe(data) - expect([...iterateTerminalOutputFrameChunks('', meta, 'text')]).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/terminal-passive-resize-input.test.ts b/src/main/runtime/rpc/terminal-passive-resize-input.test.ts deleted file mode 100644 index f54302dccaa..00000000000 --- a/src/main/runtime/rpc/terminal-passive-resize-input.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { RpcDispatcher } from './dispatcher' - -import { RemoteDesktopTerminalFloor } from '../terminal/layout/remote-desktop-terminal-floor' - -import { TERMINAL_METHODS } from './methods/terminal/terminal' - -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' - -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' - -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' - -async function startStream({ - multiplex, - explicitClaims = true, - restoreOwner = false -}: { - multiplex: boolean - explicitClaims?: boolean - restoreOwner?: boolean -}) { - const processWrites: string[] = [] - const messages: { type?: string; streamId?: number }[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const registry = createSubscriptionRegistryDouble() - const applyLayout = vi.fn(async () => ({ ok: true })) - const floor = new RemoteDesktopTerminalFloor({ - isMobileDriven: () => false, - getTerminalSize: () => ({ cols: 120, rows: 40 }), - resolveHostTarget: () => ({ cols: 120, rows: 40 }), - hostShowsTerminals: () => false, - applyLayout - }) - if (restoreOwner) { - await floor.updateViewer('pty-1', 'retired-stream', 'desktop-1', 120, 40, true) - await floor.unregisterViewers('pty-1', ['retired-stream']) - applyLayout.mockClear() - } - const runtime = stubRuntime({ - ...(restoreOwner ? { updateRemoteDesktopViewer: vi.fn(floor.updateViewer.bind(floor)) } : {}), - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'prompt', cols: 120, rows: 40 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), - getTerminalFitOverride: vi.fn().mockReturnValue(null), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn(async (handle: string, action: { text?: string }) => { - processWrites.push(action.text ?? '') - return { handle, accepted: true, bytesWritten: Buffer.byteLength(action.text ?? '') } - }) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const controller = new AbortController() - const subscribe = { - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - ...(multiplex ? { inputSessionId: 'resize-input-session' } : {}), - ...(restoreOwner ? {} : { viewport: { cols: 120, rows: 40 } }), - capabilities: { - terminalBinaryStream: 1, - ...(multiplex ? { inputAck: 1 } : {}), - ...(explicitClaims ? { desktopViewportClaims: 1 } : {}) - } - } - const done = dispatcher.dispatchStreaming( - makeRequest( - multiplex ? 'terminal.multiplex' : 'terminal.subscribe', - multiplex ? {} : subscribe - ), - (message) => messages.push(JSON.parse(message).result ?? {}), - { - signal: controller.signal, - connectionId: 'conn-resize-input', - sendBinary: () => {}, - registerBinaryStreamHandler: (streamId, handler) => { - handlers.set(streamId, handler) - return () => handlers.delete(streamId) - } - } - ) - if (multiplex) { - await vi.waitFor(() => expect(handlers.has(0)).toBe(true)) - handlers.get(0)?.({ - opcode: TerminalStreamOpcode.Subscribe, - streamId: 0, - seq: 0, - payload: encodeTerminalStreamJson({ ...subscribe, streamId: 7 }) - }) - } - await vi.waitFor(() => - expect(messages.some((message) => message.type === 'subscribed')).toBe(true) - ) - const streamId = messages.find((message) => message.type === 'subscribed')?.streamId - if (typeof streamId !== 'number') { - throw new Error('No subscribed stream id') - } - let inputSeq = 0 - const send = (opcode: TerminalStreamOpcode, payload: Uint8Array): void => { - const frame = decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode, - streamId, - seq: opcode === TerminalStreamOpcode.Input ? ++inputSeq : 0, - payload - }) - ) - if (!frame) { - throw new Error('Invalid test frame') - } - handlers.get(streamId)?.(frame) - } - return { - processWrites, - updateViewport: vi.mocked(runtime.updateRemoteDesktopViewer), - applyLayout, - resize: () => - send(TerminalStreamOpcode.Resize, encodeTerminalStreamJson({ cols: 100, rows: 30 })), - claim: () => - send(TerminalStreamOpcode.ClaimViewport, encodeTerminalStreamJson({ cols: 100, rows: 30 })), - type: (text: string) => send(TerminalStreamOpcode.Input, encodeTerminalStreamText(text)), - close: async () => { - runtime.cleanupSubscription( - multiplex ? 'terminal-multiplex:conn-resize-input' : 'terminal-1:desktop-1' - ) - controller.abort() - await done - } - } -} - -describe.each([true, false])('remote input after passive resize (multiplex=%s)', (multiplex) => { - it.each(['refused', 'thrown'])('preserves typing after a %s passive resize', async (failure) => { - const stream = await startStream({ multiplex, restoreOwner: true }) - const layout = Promise.withResolvers<{ ok: boolean }>() - try { - stream.type('before') - await vi.waitFor(() => expect(stream.processWrites).toEqual(['before'])) - stream.applyLayout.mockReturnValueOnce(layout.promise) - stream.resize() - await vi.waitFor(() => expect(stream.applyLayout).toHaveBeenCalledTimes(1)) - stream.type('during') - stream.resize() - stream.type('after') - await new Promise((resolve) => setImmediate(resolve)) - expect(stream.processWrites).toEqual(['before']) - if (failure === 'thrown') { - layout.reject(new Error('temporary geometry failure')) - } else { - layout.resolve({ ok: false }) - } - await vi.waitFor(() => expect(stream.processWrites).toEqual(['before', 'during', 'after'])) - expect(stream.updateViewport).toHaveBeenLastCalledWith( - 'pty-1', - expect.any(String), - 'desktop-1', - 100, - 30, - false - ) - - expect(stream.applyLayout).toHaveBeenCalledTimes(1) - stream.applyLayout.mockResolvedValueOnce({ ok: false }) - stream.claim() - stream.resize() - stream.type('blocked') - stream.claim() - stream.type('reclaimed') - await vi.waitFor(() => - expect(stream.processWrites).toEqual(['before', 'during', 'after', 'reclaimed']) - ) - } finally { - layout.resolve({ ok: false }) - await stream.close() - } - }) -}) diff --git a/src/main/runtime/rpc/terminal-prompt-delivery-receipt.test.ts b/src/main/runtime/rpc/terminal-prompt-delivery-receipt.test.ts deleted file mode 100644 index 49752d6de8e..00000000000 --- a/src/main/runtime/rpc/terminal-prompt-delivery-receipt.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import { createAgentPromptSubmissionRuntime } from '../terminal/input/agent-prompt-submission-runtime-test-fixture' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' - -vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: facade.listWorktrees - } -}) - -vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: facade.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - const createWorktreeListingMocks = () => ({ - listWorktrees: vi.fn().mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/prompt-receipt', - isBare: false, - isMainWorktree: false - } - ]), - listWorktreesStrict: vi.fn().mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/prompt-receipt', - isBare: false, - isMainWorktree: false - } - ]) - }) - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -function request( - terminal: string, - promptRequestId: string, - text: string, - waitSubmitMs?: number -): RpcRequest { - return { - id: `rpc-${promptRequestId}`, - authToken: 'token', - method: 'terminal.send', - orchestrationRequestId: promptRequestId, - params: { - terminal, - text, - enter: true, - agentPrompt: true, - waitSubmitMs, - client: { id: 'orca-cli', type: 'desktop' } - } - } -} - -async function createHarness(agent: TuiAgent, busy = false) { - const created = await createAgentPromptSubmissionRuntime(() => undefined, agent) - created.runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'unused' }), - write: (_ptyId, data) => { - created.writes.push(data) - return true - }, - kill: () => true, - getForegroundProcess: async () => agent - }) - const db = new OrchestrationDb(':memory:') - created.runtime.setOrchestrationDb(db) - if (busy) { - created.runtime.onPtyData( - 'pty-prompt', - `\x1b]9999;{"state":"working","agentType":"${agent}"}\x07`, - Date.now() - ) - } - return { - ...created, - db, - dispatcher: new RpcDispatcher({ runtime: created.runtime, methods: TERMINAL_METHODS }) - } -} - -describe('durable terminal prompt delivery receipts', () => { - afterEach(() => vi.useRealTimers()) - - it('replays after a dispatcher replacement without duplicate text or Enter', async () => { - vi.useFakeTimers() - const harness = await createHarness('codex', true) - const firstPromise = harness.dispatcher.dispatch( - request(harness.handle, 'crash-retry', 'preserve once') - ) - await vi.runAllTimersAsync() - const first = await firstPromise - const writesAfterFirst = [...harness.writes] - const replacement = new RpcDispatcher({ runtime: harness.runtime, methods: TERMINAL_METHODS }) - const replay = await replacement.dispatch( - request(harness.handle, 'crash-retry', 'preserve once') - ) - - expect(first).toMatchObject({ ok: true, result: { mutation: { replayed: false } } }) - expect(replay).toMatchObject({ ok: true, result: { mutation: { replayed: true } } }) - expect(harness.writes).toEqual(writesAfterFirst) - harness.db.close() - }) - - it('keeps an ambiguous partial write pending and refuses to resend it', async () => { - vi.useFakeTimers() - const harness = await createHarness('aider') - harness.runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'unused' }), - write: (_ptyId, data) => { - harness.writes.push(data) - return data !== '\r' - }, - kill: () => true, - getForegroundProcess: async () => 'aider' - }) - const firstPromise = harness.dispatcher.dispatch( - request(harness.handle, 'partial-retry', 'partial once') - ) - await vi.runAllTimersAsync() - const first = await firstPromise - const writesAfterFailure = [...harness.writes] - const retry = await harness.dispatcher.dispatch( - request(harness.handle, 'partial-retry', 'partial once') - ) - - expect(first).toMatchObject({ ok: false }) - expect(retry).toMatchObject({ ok: false, error: { code: 'operation_unknown' } }) - expect(harness.writes).toEqual(writesAfterFailure) - harness.db.close() - }) - - it('waits on a replay only for observation and never resends', async () => { - vi.useFakeTimers() - const harness = await createHarness('codex', true) - const firstPromise = harness.dispatcher.dispatch( - request(harness.handle, 'observe-retry', 'observe once') - ) - await vi.runAllTimersAsync() - await firstPromise - const writesAfterFirst = [...harness.writes] - harness.runtime.onPtyData( - 'pty-prompt', - '\x1b]9999;{"state":"done","agentType":"codex"}\x07' + - '\x1b]9999;{"state":"working","agentType":"codex"}\x07', - Date.now() - ) - - const observed = await harness.dispatcher.dispatch( - request(harness.handle, 'observe-retry', 'observe once', 1_000) - ) - - expect(observed).toMatchObject({ - ok: true, - result: { - send: { - prompt: { - stages: ['input_accepted', 'turn_started'] - } - }, - mutation: { replayed: true } - } - }) - expect(harness.writes).toEqual(writesAfterFirst) - harness.db.close() - }) - - it('does not let a later queued request claim an earlier lifecycle transition', async () => { - vi.useFakeTimers() - const harness = await createHarness('codex', true) - const firstPromise = harness.dispatcher.dispatch( - request(harness.handle, 'ordered-first', 'first prompt') - ) - await vi.runAllTimersAsync() - await firstPromise - const secondPromise = harness.dispatcher.dispatch( - request(harness.handle, 'ordered-second', 'second prompt') - ) - await vi.runAllTimersAsync() - await secondPromise - - harness.runtime.onPtyData( - 'pty-prompt', - '\x1b]9999;{"state":"done","agentType":"codex"}\x07' + - '\x1b]9999;{"state":"working","agentType":"codex"}\x07', - Date.now() - ) - - const secondObserved = harness.dispatcher.dispatch( - request(harness.handle, 'ordered-second', 'second prompt', 1_000) - ) - await vi.runAllTimersAsync() - const firstObserved = harness.dispatcher.dispatch( - request(harness.handle, 'ordered-first', 'first prompt', 1_000) - ) - await vi.runAllTimersAsync() - - await expect(secondObserved).resolves.toMatchObject({ - ok: true, - result: { send: { prompt: { stages: ['input_accepted'] } } } - }) - await expect(firstObserved).resolves.toMatchObject({ - ok: true, - result: { - send: { prompt: { stages: ['input_accepted', 'turn_started'] } } - } - }) - harness.db.close() - }) - - it('rejects changed payload and replays queued truth after generation replacement', async () => { - vi.useFakeTimers() - const harness = await createHarness('codex', true) - const firstPromise = harness.dispatcher.dispatch( - request(harness.handle, 'bound-request', 'original') - ) - await vi.runAllTimersAsync() - await firstPromise - - const changedPayload = await harness.dispatcher.dispatch( - request(harness.handle, 'bound-request', 'changed') - ) - harness.runtime.synchronizePtyOutputSequenceFromProvider( - 'pty-prompt', - { value: 0, generation: 'reset' }, - harness.runtime.getPtyOutputSequence('pty-prompt') - ) - const changedGeneration = await harness.dispatcher.dispatch( - request(harness.handle, 'bound-request', 'original', 1_000) - ) - - expect(changedPayload).toMatchObject({ ok: false, error: { code: 'request_mismatch' } }) - expect(changedGeneration).toMatchObject({ - ok: true, - result: { - send: { - prompt: { - stages: ['input_accepted'], - observation: 'incarnation_replaced' - } - }, - mutation: { replayed: true } - } - }) - expect(harness.writes.filter((data) => data === '\r')).toHaveLength(1) - harness.db.close() - }) - - it('does not clear a pre-existing provider draft before appending the prompt', async () => { - vi.useFakeTimers() - const harness = await createHarness('codex', true) - harness.runtime.onPtyData('pty-prompt', '› existing human draft', Date.now()) - const responsePromise = harness.dispatcher.dispatch( - request(harness.handle, 'draft-safe', 'appended prompt') - ) - await vi.runAllTimersAsync() - await responsePromise - - expect(harness.writes.join('')).toContain('appended prompt') - expect(harness.writes.join('')).not.toContain('\u0015') - harness.db.close() - }) -}) diff --git a/src/main/runtime/rpc/terminal-provider-snapshot-sequence.test.ts b/src/main/runtime/rpc/terminal-provider-snapshot-sequence.test.ts deleted file mode 100644 index 019ec638070..00000000000 --- a/src/main/runtime/rpc/terminal-provider-snapshot-sequence.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' - -const request: RpcRequest = { - id: 'req-provider-sequence', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: 'terminal-restored', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - } -} - -it('replays post-capture output in the provider snapshot sequence domain', async () => { - const binaryFrames: Uint8Array[] = [] - const registry = createSubscriptionRegistryDouble() - let dataListener: - | ((data: string, meta?: { seq?: number; rawLength?: number }) => void) - | undefined - let resolveSnapshot: - | ((snapshot: { data: string; cols: number; rows: number; seq: number }) => void) - | undefined - const runtime = { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - registerRemoteTerminalViewSubscriber: () => () => {}, - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-restored' }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn((_ptyId, listener) => { - dataListener = listener - return vi.fn() - }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn( - () => - new Promise<{ data: string; cols: number; rows: number; seq: number }>((resolve) => { - resolveSnapshot = resolve - }) - ), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - cleanupSubscriptionIfOwnedByConnection: vi.fn(registry.cleanupSubscriptionIfOwnedByConnection), - waitForTerminal: vi.fn(() => new Promise(() => {})) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming(request, vi.fn(), { - connectionId: 'conn-restored', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - } - }) - - await vi.waitFor(() => expect(resolveSnapshot).toBeDefined()) - resolveSnapshot?.({ data: 'restored snapshot', cols: 80, rows: 24, seq: 900 }) - // Attach anchoring continues at 905, not 5, so snapshot reconciliation retains the new chunk. - dataListener?.('fresh', { seq: 905, rawLength: 5 }) - - await vi.waitFor(() => - expect( - binaryFrames.some((bytes) => { - const frame = decodeTerminalStreamFrame(bytes) - return ( - frame?.opcode === TerminalStreamOpcode.Output && - decodeTerminalStreamText(frame.payload) === 'fresh' - ) - }) - ).toBe(true) - ) - - runtime.cleanupSubscription('terminal-restored:phone-1') - await dispatchPromise -}) - -it('keeps provider-backed alternate-screen resizes geometry-only', async () => { - const binaryFrames: Uint8Array[] = [] - const registry = createSubscriptionRegistryDouble() - let resizeListener: - | ((event: { - cols: number - rows: number - displayMode: string - reason: string - seq: number - }) => void) - | undefined - const serializeTerminalBuffer = vi - .fn() - .mockResolvedValue({ data: 'restored tui', cols: 80, rows: 24 }) - const runtime = { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - registerRemoteTerminalViewSubscriber: () => () => {}, - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-tui' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer, - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(true), - handleMobileSubscribe: vi.fn().mockResolvedValue(undefined), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn((_ptyId, listener) => { - resizeListener = listener - return vi.fn() - }), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - cleanupSubscriptionIfOwnedByConnection: vi.fn(registry.cleanupSubscriptionIfOwnedByConnection), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const dispatchPromise = dispatcher.dispatchStreaming( - { - ...request, - id: 'req-provider-alt-screen', - params: { - terminal: 'terminal-tui', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - } - }, - vi.fn(), - { - connectionId: 'conn-tui-resize', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - } - } - ) - - await vi.waitFor(() => expect(resizeListener).toBeDefined()) - binaryFrames.splice(0) - resizeListener?.({ - cols: 100, - rows: 30, - displayMode: 'auto', - reason: 'apply-layout', - seq: 2 - }) - await vi.waitFor(() => - expect( - binaryFrames.some( - (frame) => decodeTerminalStreamFrame(frame)?.opcode === TerminalStreamOpcode.Resized - ) - ).toBe(true) - ) - - expect(serializeTerminalBuffer).toHaveBeenCalledOnce() - expect( - binaryFrames.some( - (frame) => decodeTerminalStreamFrame(frame)?.opcode === TerminalStreamOpcode.SnapshotStart - ) - ).toBe(false) - - runtime.cleanupSubscription('terminal-tui:phone-1') - await dispatchPromise -}) diff --git a/src/main/runtime/rpc/terminal-send-launch-composer.test.ts b/src/main/runtime/rpc/terminal-send-launch-composer.test.ts deleted file mode 100644 index 3e451fc1b05..00000000000 --- a/src/main/runtime/rpc/terminal-send-launch-composer.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { z } from 'zod' -import { settledWriteStub } from '../../providers/settled-pty-write-stub' -import { OrcaRuntimeService } from '../orca-runtime' -import { makeStore } from './server/runtime-rpc-worktree-store-fixtures' -import { AGENT_PROMPT_TEST_WORKTREE_PATH } from '../terminal/input/agent-prompt-submission-runtime-test-fixture' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' - -vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: facade.listWorktrees - } -}) - -vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: facade.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - const createWorktreeListingMocks = () => ({ - listWorktrees: vi.fn().mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/launch-composer', - isBare: false, - isMainWorktree: false - } - ]), - listWorktreesStrict: vi.fn().mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/launch-composer', - isBare: false, - isMainWorktree: false - } - ]) - }) - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -// Claude's palette-report anchor, then its composer prompt row (draft-paste-ready-scanner.ts). -const CLAUDE_COMPOSER_READY_OUTPUT = '\x1b[?2031h\x1b[?2004h❯\u00a0' -const PTY_ID = 'pty-claude' -// Claude 2.1.314's first-launch trust menu, captured from a real PTY. -const CLAUDE_TRUST_DIALOG_OUTPUT = - '\x1b[?2004h Accessing workspace:\r\n\r\n /private/tmp/repro\r\n\r\n' + - ' Quick safety check: Is this a project you created or one you trust?\r\n\r\n' + - ' ❯ No, exit\r\n Yes, I trust this folder\r\n\r\n Enter to confirm · Esc to cancel\r\n' - -async function launchClaude(command: string | undefined, ordered = false) { - const runtime = new OrcaRuntimeService( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: partial store double; terminal create and send read only its repo and worktree members. - makeStore() as never - ) - const writes: string[] = [] - const write = (_ptyId: string, data: string) => { - writes.push(data) - return true - } - runtime.setPtyController({ - spawn: async () => ({ id: PTY_ID }), - write, - writeWithSettlement: settledWriteStub(write), - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - const { handle } = await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, { - launchAgent: 'claude', - ...(command ? { command } : {}) - }) - vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent') - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const mobile = { - caller: { kind: 'paired-device', deviceId: 'device' }, - clientId: 'phone' - } as const - const client = { id: 'phone', type: 'mobile' } as const - let inputSessionId: string | undefined - let seq = 0 - if (ordered) { - await runtime.handleMobileSubscribe(PTY_ID, 'phone', undefined) - const opened = await dispatcher.dispatch( - { - id: 'open', - authToken: 'token', - method: 'terminal.openInputSession', - params: { terminal: handle, client } - }, - mobile - ) - if (!opened.ok) { - throw new Error(opened.error.message) - } - inputSessionId = z.object({ inputSessionId: z.string() }).parse(opened.result).inputSessionId - } - const send = (text: string, signal?: AbortSignal) => - dispatcher.dispatch( - { - id: 'rpc-send', - authToken: 'token', - method: 'terminal.send', - params: { - terminal: handle, - text, - enter: true, - ...(inputSessionId - ? { client, inputSequence: { sessionId: inputSessionId, seq: ++seq } } - : {}) - } - }, - { ...(ordered ? mobile : {}), ...(signal ? { signal } : {}) } - ) - return { runtime, writes, send } -} - -const PASTE = '\x1b[200~/review\nthis\x1b[201~' - -describe('terminal.send into a freshly launched Claude', () => { - afterEach(() => vi.useRealTimers()) - - it('holds the entire ordered suffix behind the fresh composer and the first submit', async () => { - vi.useFakeTimers() - const { runtime, writes, send } = await launchClaude('claude', true) - const first = send(PASTE) - const second = send('next') - await vi.advanceTimersByTimeAsync(3_000) - expect(writes).toEqual([]) - runtime.onPtyData(PTY_ID, CLAUDE_COMPOSER_READY_OUTPUT, Date.now()) - await vi.runAllTimersAsync() - await expect(Promise.all([first, second])).resolves.toEqual([ - expect.objectContaining({ result: { send: expect.objectContaining({ accepted: true }) } }), - expect.objectContaining({ result: { send: expect.objectContaining({ accepted: true }) } }) - ]) - expect(writes).toEqual([PASTE, '\r', 'next', '\r']) - }) - - it('refuses the send, writing nothing, when the composer never comes up', async () => { - vi.useFakeTimers() - const { writes, send } = await launchClaude('claude') - - const sending = send(PASTE) - await vi.runAllTimersAsync() - - await expect(sending).resolves.toMatchObject({ - ok: true, - result: { send: { accepted: false, bytesWritten: 0 } } - }) - expect(writes).toEqual([]) - }) - - it('lets an answer reach a startup dialog shown before the composer', async () => { - vi.useFakeTimers() - const { runtime, writes, send } = await launchClaude('claude') - - const sending = send('1') - runtime.onPtyData(PTY_ID, CLAUDE_TRUST_DIALOG_OUTPUT, Date.now()) - await vi.advanceTimersByTimeAsync(3_000) - - await expect(sending).resolves.toMatchObject({ ok: true, result: { send: { accepted: true } } }) - expect(writes).toEqual(['1', '\r']) - }) - - it('writes nothing for a held send whose request was cancelled', async () => { - vi.useFakeTimers() - const { runtime, writes, send } = await launchClaude('claude') - const request = new AbortController() - - const sending = send(PASTE, request.signal) - await vi.advanceTimersByTimeAsync(1_000) - request.abort() - runtime.onPtyData(PTY_ID, CLAUDE_COMPOSER_READY_OUTPUT, Date.now()) - await vi.runAllTimersAsync() - - await sending - expect(writes).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/terminal-send-ordered-input.test.ts b/src/main/runtime/rpc/terminal-send-ordered-input.test.ts deleted file mode 100644 index 2b5652cff2d..00000000000 --- a/src/main/runtime/rpc/terminal-send-ordered-input.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcDispatchStreamingOptions } from './dispatcher-stream-options' -import { z } from 'zod' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RuntimeTerminalSend } from '../../../shared/runtime-terminal-send-contract' - -const mobile = { clientId: 'phone', caller: { kind: 'paired-device', deviceId: 'device' } } as const -const client = { id: 'phone', type: 'mobile' } as const - -function fixture() { - let binding = { ptyId: 'pty', processIncarnation: 'process', generation: 1 } - const writes: string[] = [] - let release = (): void => {} - let outcome: 'accepted' | 'refused' | 'unverifiable' = 'accepted' - const sendTerminal: OrcaRuntimeService['sendTerminal'] = vi.fn(async (handle, input, options) => { - await options?.beforeWrite?.('pty') - if (input.text === 'held') { - await new Promise((resolve) => { - release = resolve - }) - } - await options?.beforeWrite?.('pty') - if (outcome === 'refused') { - return { handle, accepted: false, bytesWritten: 0 } - } - writes.push(input.text ?? '') - const send: RuntimeTerminalSend = { - handle, - accepted: true, - bytesWritten: input.text?.length ?? 0, - writeSettlement: - outcome === 'accepted' - ? { outcome: 'accepted' } - : { outcome: 'unverifiable', reason: 'settlement_timeout', bytesHandedToTransport: true } - } - return send - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this dispatcher fixture implements the runtime members read by terminal.send and openInputSession. - const runtime = { - getRuntimeId: () => 'runtime', - getTerminalPromptRequestBinding: () => binding, - resolveLiveLeafForHandle: () => ({ ptyId: binding.ptyId }), - getDriver: () => null, - ensureStructuredAgentSessionHost: async () => null, - sendTerminal, - beginMobileInputFloor: () => ({ commit: async () => {}, rollback: () => {} }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - let id = 0 - const call = (method: string, params: unknown, options: RpcDispatchStreamingOptions = mobile) => - dispatcher.dispatch({ id: String(++id), authToken: 'test', method, params }, options) - const open = async () => { - const response = await call('terminal.openInputSession', { terminal: 'term', client }) - if (!response.ok) { - throw new Error(response.error.message) - } - const parsed = z.object({ inputSessionId: z.string().nullable() }).parse(response.result) - return parsed.inputSessionId - } - const send = ( - sessionId: string, - seq: number, - text: string, - options: RpcDispatchStreamingOptions = mobile - ) => - call( - 'terminal.send', - { terminal: 'term', client, text, inputSequence: { sessionId, seq } }, - options - ) - return { - call, - open, - send, - sendTerminal, - writes, - release: () => release(), - replace: () => { - binding = { ...binding, generation: 2 } - }, - outcome: (value: typeof outcome) => { - outcome = value - } - } -} - -describe('ordered terminal input RPC', () => { - it('serializes the complete send, deduplicates matching payloads, and pins the token while a predecessor is busy', async () => { - const f = fixture() - const token = (await f.open())! - const first = f.send(token, 1, 'held') - await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(1)) - const second = f.send(token, 2, 'next') - const duplicate = f.send(token, 1, 'held') - expect(await f.open()).toBeNull() - await f.call('terminal.send', { terminal: 'term', text: 'bypass', client }) - expect(f.sendTerminal).toHaveBeenCalledTimes(1) - f.release() - await expect(Promise.all([first, second, duplicate])).resolves.toEqual( - expect.arrayContaining([ - expect.objectContaining({ - ok: true, - result: expect.objectContaining({ send: expect.objectContaining({ accepted: true }) }) - }) - ]) - ) - expect(f.writes).toEqual(['held', 'next']) - expect(f.sendTerminal).toHaveBeenLastCalledWith( - 'term', - expect.anything(), - expect.objectContaining({ inputSource: 'mobile', requireWriteSettlement: true }) - ) - }) - - it.each(['refused', 'unverifiable'] as const)( - 'poisons the suffix after %s and never retries ambiguous input', - async (outcome) => { - const f = fixture() - const token = (await f.open())! - f.outcome(outcome) - await f.send(token, 1, 'a') - f.outcome('accepted') - await f.send(token, 1, 'a') - await f.send(token, 2, '\r') - expect(f.writes).toEqual(outcome === 'refused' ? [] : ['a']) - } - ) - - it('retires an idle strict token when a legacy predecessor becomes busy', async () => { - const f = fixture() - const token = (await f.open())! - await f.send(token, 1, 'warm') - const legacy = f.call('terminal.send', { terminal: 'term', client, text: 'held' }) - await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(2)) - try { - expect(await f.send(token, 2, 'suffix')).toMatchObject({ - ok: true, - result: { send: { accepted: false } } - }) - expect(f.sendTerminal).toHaveBeenCalledTimes(2) - } finally { - f.release() - await legacy - } - await f.send(token, 2, 'suffix') - expect(f.writes).toEqual(['warm', 'held']) - }) - - it('charges queued launch-draft payloads before appending them behind a held write', async () => { - const f = fixture() - const token = (await f.open())! - const first = f.send(token, 1, 'held') - await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(1)) - const payload = { - terminal: 'term', - client, - text: '', - resolvedLaunchDraft: { text: 'x'.repeat(9 * 1024 * 1024), createdAt: 0 } - } - const second = f.call('terminal.send', { - ...payload, - inputSequence: { sessionId: token, seq: 2 } - }) - let refused = false - const third = f - .call('terminal.send', { ...payload, inputSequence: { sessionId: token, seq: 3 } }) - .then((reply) => { - refused = - reply.ok && - z.object({ send: z.object({ accepted: z.boolean() }) }).parse(reply.result).send - .accepted === false - }) - try { - await vi.waitFor(() => expect(refused).toBe(true), { timeout: 100 }) - expect(f.sendTerminal).toHaveBeenCalledTimes(1) - } finally { - f.release() - await Promise.all([first, second, third]) - } - }) - - it('charges raw controls retained by the dispatcher while normalized sends wait', async () => { - const f = fixture() - const token = (await f.open())! - const first = f.send(token, 1, 'held') - await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(1)) - const pending = Array.from({ length: 25 }, (_, index) => - f.call('terminal.send', { - terminal: 'term', - client, - text: 'x', - enter: 'e'.repeat(350 * 1024) + index, - interrupt: 'i'.repeat(350 * 1024) + index, - inputSequence: { sessionId: token, seq: index + 2 } - }) - ) - let refused = false - void pending.at(-1)!.then((reply) => { - refused = - reply.ok && - z.object({ send: z.object({ accepted: z.boolean() }) }).parse(reply.result).send - .accepted === false - }) - try { - await vi.waitFor(() => expect(refused).toBe(true), { timeout: 100 }) - expect(f.sendTerminal).toHaveBeenCalledTimes(1) - } finally { - f.release() - await Promise.all([first, ...pending]) - } - }) - - it('keeps a cancelled queued request behind its predecessor and never writes its suffix', async () => { - const f = fixture() - const token = (await f.open())! - const first = f.send(token, 1, 'held') - await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(1)) - const controller = new AbortController() - const suffix = f.send(token, 2, '\r', { ...mobile, signal: controller.signal }) - controller.abort() - expect(await f.open()).toBeNull() - f.release() - await Promise.all([first, suffix]) - expect(f.writes).toEqual(['held']) - }) - - it('rechecks the full binding before a later chunk and suppresses its dependent Return', async () => { - const f = fixture() - const token = (await f.open())! - const first = f.send(token, 1, 'held') - await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(1)) - const suffix = f.send(token, 2, '\r') - f.replace() - f.release() - await Promise.all([first, suffix]) - expect(f.writes).toEqual([]) - }) -}) diff --git a/src/main/runtime/rpc/terminal-send.test.ts b/src/main/runtime/rpc/terminal-send.test.ts deleted file mode 100644 index 33524d16b05..00000000000 --- a/src/main/runtime/rpc/terminal-send.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../../shared/clipboard-text' -import { - TERMINAL_INPUT_MAX_BYTES, - TERMINAL_INPUT_TOO_LARGE_ERROR -} from '../../../shared/terminal/input/terminal-input' - -function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { - return { - getRuntimeId: () => 'test-runtime', - beginMobileInputFloor: vi.fn((ptyId: string, clientId: string) => ({ - commit: async () => { - await overrides.mobileTookFloor?.(ptyId, clientId) - }, - rollback: vi.fn() - })), - ...overrides - } as OrcaRuntimeService -} - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -describe('terminal send RPC', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('awaits a desktop viewport claim before acknowledged input', async () => { - let releaseClaim = (): void => {} - const refreshRemoteDesktopViewer = vi.fn( - () => - new Promise((resolve) => { - releaseClaim = () => resolve(true) - }) - ) - const sendTerminal = vi.fn().mockImplementation(async (_handle, _action, options) => { - await options.beforeWrite?.('pty-1') - return { handle: 'terminal-1', accepted: true, bytesWritten: 1 } - }) - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), - refreshRemoteDesktopViewer, - sendTerminal - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = dispatcher.dispatch( - makeRequest('terminal.send', { - terminal: 'terminal-1', - text: '\x03', - client: { id: 'desktop-1', type: 'desktop' }, - viewport: { cols: 96, rows: 32 }, - claimViewport: true - }), - { caller: { kind: 'desktop' } } - ) - - await vi.waitFor(() => - expect(refreshRemoteDesktopViewer).toHaveBeenCalledWith('pty-1', 'desktop-1', 96, 32, true) - ) - expect(sendTerminal).not.toHaveBeenCalled() - releaseClaim() - await expect(response).resolves.toMatchObject({ ok: true }) - expect(sendTerminal).toHaveBeenCalled() - }) - - it('rejects query replies that spoof a different authenticated mobile client', async () => { - const replies: string[] = [] - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn(), - sendTerminal: vi.fn() - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - await dispatcher.dispatchStreaming( - makeRequest('terminal.send', { - terminal: 'terminal-1', - text: '\x1b[3;4R', - inputKind: 'query-reply', - client: { id: 'spoofed-mobile', type: 'mobile' } - }), - (reply) => replies.push(reply), - { clientId: 'authenticated-mobile' } - ) - - expect(JSON.parse(replies[0]!)).toMatchObject({ - ok: false, - error: { code: 'invalid_argument' } - }) - expect(runtime.resolveLiveLeafForHandle).not.toHaveBeenCalled() - expect(runtime.sendTerminal).not.toHaveBeenCalled() - }) - - it('rejects oversized terminal send text before runtime dispatch', async () => { - const secret = 'terminal-send-secret' - const runtime = stubRuntime({ - sendTerminal: vi.fn() - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('terminal.send', { - terminal: 'terminal-1', - text: [secret, 'x'.repeat(TERMINAL_INPUT_MAX_BYTES + 1)].join('') - }) - ) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: TERMINAL_INPUT_TOO_LARGE_ERROR - } - }) - expect(JSON.stringify(response)).not.toContain(secret) - expect(runtime.sendTerminal).not.toHaveBeenCalled() - }) - - it('rejects multibyte oversized terminal send text before runtime dispatch', async () => { - const runtime = stubRuntime({ - sendTerminal: vi.fn() - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const text = '😀'.repeat(Math.floor(TERMINAL_INPUT_MAX_BYTES / 4) + 1) - - const response = await dispatcher.dispatch( - makeRequest('terminal.send', { - terminal: 'terminal-1', - text - }) - ) - - expect(text.length).toBeLessThan(TERMINAL_INPUT_MAX_BYTES) - expect(response).toMatchObject({ - ok: false, - error: { - code: 'invalid_argument', - message: TERMINAL_INPUT_TOO_LARGE_ERROR - } - }) - expect(runtime.sendTerminal).not.toHaveBeenCalled() - }) - - it('yields while validating large accepted terminal send text before runtime dispatch', async () => { - vi.useFakeTimers() - const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1) - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), - sendTerminal: vi.fn().mockResolvedValue({ - handle: 'terminal-1', - accepted: true, - bytesWritten: text.length - }) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const responsePromise = dispatcher.dispatch( - makeRequest('terminal.send', { - terminal: 'terminal-1', - text - }) - ) - await Promise.resolve() - - expect(runtime.sendTerminal).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(0) - await expect(responsePromise).resolves.toMatchObject({ - ok: true, - result: { send: { accepted: true } } - }) - expect(runtime.sendTerminal).toHaveBeenCalledWith( - 'terminal-1', - { - text, - enter: false, - interrupt: false - }, - { inputKind: 'driving', inputSource: 'legacy', beforeWrite: undefined } - ) - }) - - it('writes zero bytes when a guarded callback observes a handle rebind during status', async () => { - let boundPtyId = 'pty-1' - let statusCalls = 0 - const write = vi.fn() - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn(() => ({ ptyId: boundPtyId })), - getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), - getTerminalAgentStatus: vi.fn().mockImplementation(async () => { - statusCalls += 1 - if (statusCalls === 2) { - boundPtyId = 'pty-2' - } - return { - handle: 'terminal-1', - isRunningAgent: true, - status: 'working' - } - }), - sendTerminal: vi.fn().mockImplementation(async (_handle, _action, options) => { - await options.beforeWrite('pty-1') - write('pty-1', '\r') - return { handle: 'terminal-1', accepted: true, bytesWritten: 1 } - }) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('terminal.send', { - terminal: 'terminal-1', - enter: true, - requireAgentStatus: 'sendable', - client: { id: 'desktop-1', type: 'desktop' } - }) - ) - - expect(response).toMatchObject({ - ok: true, - result: { send: { accepted: false, bytesWritten: 0 } } - }) - expect(runtime.getTerminalAgentStatus).toHaveBeenCalledTimes(2) - expect(write).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/rpc/terminal-stream-byte-length.test.ts b/src/main/runtime/rpc/terminal-stream-byte-length.test.ts deleted file mode 100644 index 2aae5a40b7a..00000000000 --- a/src/main/runtime/rpc/terminal-stream-byte-length.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - measureTerminalStreamByteLength, - terminalStreamByteLength, - terminalStreamByteLengthExceeds -} from './terminal-stream-byte-length' - -describe('measuring a prefix slice that cuts a surrogate pair in half', () => { - // Kept first in the file so the scan is still specializing on this shape when it tiers up. - it('measures the slice like the encoder does in every JIT tier', () => { - const sliced = 'abcdefghijkl\u{1f600}'.slice(0, 13) - expect(sliced.length).toBe(13) - expect(sliced.charCodeAt(12)).toBe(0xd83d) - // 12 ASCII bytes plus U+FFFD for the orphaned high surrogate. - expect(Buffer.byteLength(sliced, 'utf8')).toBe(15) - - const observedByteLengths = new Set() - const observedExceeded = new Set() - const observedMeasurements = new Set() - for (let iteration = 0; iteration < 200_000; iteration += 1) { - observedByteLengths.add(terminalStreamByteLength(sliced)) - observedExceeded.add(terminalStreamByteLengthExceeds(sliced, 15)) - observedMeasurements.add( - JSON.stringify(measureTerminalStreamByteLength(sliced, { stopAfterBytes: 15 })) - ) - } - expect([...observedByteLengths]).toEqual([15]) - expect([...observedExceeded]).toEqual([false]) - expect([...observedMeasurements]).toEqual([ - JSON.stringify({ byteLength: 15, exceededLimit: false }) - ]) - }) -}) - -describe('terminal stream UTF-8 byte accounting', () => { - it('matches the encoder across Unicode widths and the native-call boundary', () => { - const samples = [ - '', - '\u0000\u007f', - '\u0080\u07ff', - '\u0800\uffff', - '\u{10000}\u{10ffff}', - '\ud800', - '\udfff', - '\ud800\ud800', - '\udc00\ud800', - '😀\ud800', - '\ud800😀', - 'e\u0301', - '👩‍💻', - '\r\n\u001b[0m' - ] - for (const units of [15, 16, 17, 32]) { - for (const unit of ['a', 'é', '走', '😀', '\ud800']) { - samples.push(unit.repeat(units).slice(0, units)) - } - } - for (const text of samples) { - const byteLength = Buffer.byteLength(text, 'utf8') - expect(terminalStreamByteLength(text), JSON.stringify(text)).toBe(byteLength) - expect(measureTerminalStreamByteLength(text)).toEqual({ - byteLength, - exceededLimit: false - }) - for (const limit of [-1, 0, 0.5, byteLength - 1, byteLength, byteLength + 1]) { - expect( - terminalStreamByteLengthExceeds(text, limit), - `${JSON.stringify(text)} at ${limit}` - ).toBe(text.length > 0 && byteLength > limit) - } - } - }) - - it.each([ - { text: '', limit: -1, byteLength: 0, exceededLimit: false }, - { text: 'abc', limit: 0, byteLength: 1, exceededLimit: true }, - { text: 'éé', limit: 2, byteLength: 4, exceededLimit: true }, - { text: '😀😀😀', limit: 5, byteLength: 8, exceededLimit: true }, - { text: '\ud800z', limit: 2, byteLength: 3, exceededLimit: true }, - { text: '😀'.repeat(9), limit: 5, byteLength: 8, exceededLimit: true }, - { text: 'é'.repeat(16), limit: 32, byteLength: 32, exceededLimit: false }, - { text: '走'.repeat(16), limit: 48, byteLength: 48, exceededLimit: false } - ])( - 'measures only through the first code point over $limit bytes', - ({ text, limit, ...expected }) => { - expect(measureTerminalStreamByteLength(text, { stopAfterBytes: limit })).toEqual(expected) - } - ) - - it('treats non-finite limits as unbounded for both scan and native inputs', () => { - for (const text of ['', '😀é走a', '😀é走a'.repeat(8)]) { - for (const limit of [Number.NaN, Infinity, -Infinity]) { - expect(terminalStreamByteLengthExceeds(text, limit)).toBe(false) - expect(measureTerminalStreamByteLength(text, { stopAfterBytes: limit })).toEqual({ - byteLength: Buffer.byteLength(text, 'utf8'), - exceededLimit: false - }) - } - } - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-admission.test.ts b/src/main/runtime/rpc/terminal-subscribe-admission.test.ts deleted file mode 100644 index 16dedb9f72d..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-admission.test.ts +++ /dev/null @@ -1,309 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import '../../../shared/rpc-contract/terminal-viewport-schemas-params' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const PTY_ID = 'pty-1' -const SUBSCRIPTION_ID = 'terminal-1:phone-1' - -const binaryParams = { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - viewport: { cols: 40, rows: 20 }, - capabilities: { terminalBinaryStream: 1 } -} - -const leaseOnlyParams = { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1, mobileInputLeaseOnly: 1 } -} - -let nextRequestId = 0 -const subscribeRequest = (params: unknown): RpcRequest => ({ - id: `req-${++nextRequestId}`, - authToken: 'tok', - method: 'terminal.subscribe', - params -}) - -/** What a phone that addresses its request sends; the slot fields stay for older hosts. */ -const phoneUnsubscribeParams = (requestId: string) => ({ - subscriptionId: SUBSCRIPTION_ID, - client: { id: 'phone-1' }, - requestId -}) -const requestUnsubscribe = (requestId: string): RpcRequest => ({ - id: `req-${++nextRequestId}`, - authToken: 'tok', - method: 'terminal.unsubscribe', - params: phoneUnsubscribeParams(requestId) -}) - -const phoneConnection = (connectionId: string, signal?: AbortSignal) => ({ - connectionId, - signal, - sendBinary: vi.fn(), - registerBinaryStreamHandler: vi.fn(() => vi.fn()) -}) - -const resultTypes = (messages: string[]): unknown[] => - messages.map((message) => JSON.parse(message).result?.type) - -const flush = (ms = 20): Promise => new Promise((resolve) => setTimeout(resolve, ms)) - -/** Resolves pending `waitForLeafPtyId` calls on demand and rejects them when their signal aborts, like the runtime. */ -function createPtyWaits() { - const waits: { resolve: (ptyId: string) => void }[] = [] - return { - waits, - waitForLeafPtyId: vi.fn( - (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => - new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(new Error('request_aborted')) - return - } - signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { - once: true - }) - waits.push({ resolve }) - }) - ), - spawn: () => { - for (const wait of waits.splice(0)) { - wait.resolve(PTY_ID) - } - } - } -} - -function stubRuntime(overrides: Record = {}) { - const registry = createSubscriptionRegistryDouble() - const ptyWaits = createPtyWaits() - let ptyReady = false - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This partial runtime supplies the terminal RPC methods these tests invoke. - const runtime = { - getRuntimeId: () => 'test-runtime', - registerRemoteTerminalViewSubscriber: () => () => {}, - requestRendererTerminalTabMount: vi.fn(() => false), - resolveLeafForHandle: vi.fn(() => ({ ptyId: ptyReady ? PTY_ID : null })), - waitForLeafPtyId: ptyWaits.waitForLeafPtyId, - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn(() => vi.fn()), - readTerminal: vi.fn().mockResolvedValue({ tail: ['scrollback'], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValue({ data: 'snapshot', cols: 40, rows: 20, seq: 4 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 40, rows: 20 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn(() => vi.fn()), - subscribeToFitOverrideChanges: vi.fn(() => vi.fn()), - subscribeToPtyExit: vi.fn(() => vi.fn()), - registerOwnedSubscriptionCleanup: registry.registerOwnedSubscriptionCleanup, - cleanupSubscriptionIfOwnedByConnection: registry.cleanupSubscriptionIfOwnedByConnection, - getSubscriptionRegistrationVersion: registry.getSubscriptionRegistrationVersion, - releaseSubscriptionByRequest: registry.releaseSubscriptionByRequest, - ...overrides - } as unknown as OrcaRuntimeService - const spawn = (): void => { - ptyReady = true - ptyWaits.spawn() - } - return { runtime, registry, ptyWaits, spawn } -} - -/** The real runtime, with only handle resolution, the pty wait, the scrollback read and tab mounting doubled. */ -function createRealRuntime() { - const runtime = new OrcaRuntimeService() - const sizes = new Map([[PTY_ID, { cols: 120, rows: 40 }]]) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - resize: (ptyId, cols, rows) => { - sizes.set(ptyId, { cols, rows }) - return true - }, - getSize: (ptyId) => sizes.get(ptyId) ?? null - }) - const ptyWaits = createPtyWaits() - let ptyReady = false - vi.spyOn(runtime, 'resolveLeafForHandle').mockImplementation(() => ({ - ptyId: ptyReady ? PTY_ID : null - })) - vi.spyOn(runtime, 'waitForLeafPtyId').mockImplementation(ptyWaits.waitForLeafPtyId) - vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ - handle: 'terminal-1', - status: 'running', - tail: [], - truncated: false, - nextCursor: null - }) - vi.spyOn(runtime, 'requestRendererTerminalTabMount').mockReturnValue(false) - const spawn = (): void => { - ptyReady = true - ptyWaits.spawn() - } - return { runtime, ptyWaits, spawn, sizes } -} - -describe('terminal.subscribe registers at admission', () => { - it('leaves the desktop driver idle when the phone leaves during the phone-fit layout', async () => { - const { runtime, sizes } = createRealRuntime() - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - let leaveDuringLayout = true - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - resize: (ptyId, cols, rows) => { - sizes.set(ptyId, { cols, rows }) - // The phone's unsubscribe lands while handleMobileSubscribe awaits its layout. - if (leaveDuringLayout) { - leaveDuringLayout = false - runtime.cleanupSubscriptionIfOwnedByConnection(SUBSCRIPTION_ID, 'conn-a') - } - return true - }, - getSize: (ptyId) => sizes.get(ptyId) ?? null - }) - vi.spyOn(runtime, 'resolveLeafForHandle').mockReturnValue({ ptyId: PTY_ID }) - const messages: string[] = [] - - const subscribe = dispatcher.dispatchStreaming( - subscribeRequest(binaryParams), - (message) => messages.push(message), - phoneConnection('conn-a') - ) - await vi.waitFor(() => expect(leaveDuringLayout).toBe(false)) - await subscribe - - await vi.waitFor(() => expect(runtime.getDriver(PTY_ID).kind).toBe('idle'), { - timeout: 2_000 - }) - expect(resultTypes(messages)).toEqual(['end']) - }) - - it('does not follow a released stream end with an error', async () => { - let rejectSubscribe = (_error: Error): void => {} - const { runtime, registry } = stubRuntime({ - resolveLeafForHandle: vi.fn(() => ({ ptyId: PTY_ID })), - handleMobileSubscribe: vi.fn( - () => - new Promise((_resolve, reject) => { - rejectSubscribe = reject - }) - ) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const messages: string[] = [] - const subscribe = dispatcher.dispatchStreaming( - subscribeRequest(leaseOnlyParams), - (message) => messages.push(message), - phoneConnection('conn-a') - ) - await vi.waitFor(() => expect(runtime.handleMobileSubscribe).toHaveBeenCalled()) - - registry.cleanupSubscriptionIfOwnedByConnection(SUBSCRIPTION_ID, 'conn-a') - rejectSubscribe(new Error('subscribe_failed')) - await subscribe - - expect(messages.map((message) => JSON.parse(message))).toEqual([ - expect.objectContaining({ ok: true, result: { type: 'end' } }) - ]) - }) -}) - -describe('terminal.unsubscribe addressed by request', () => { - const liveStub = () => stubRuntime({ resolveLeafForHandle: vi.fn(() => ({ ptyId: PTY_ID })) }) - - it('ends a subscribe still waiting for its pty, addressed by its request id', async () => { - const { runtime, ptyWaits, spawn } = createRealRuntime() - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const pending = subscribeRequest(binaryParams) - const messages: string[] = [] - const subscribe = dispatcher.dispatchStreaming( - pending, - (message) => messages.push(message), - phoneConnection('conn-a') - ) - await vi.waitFor(() => expect(ptyWaits.waitForLeafPtyId).toHaveBeenCalled()) - - await dispatcher.dispatchStreaming(requestUnsubscribe(pending.id), vi.fn(), { - connectionId: 'conn-a' - }) - spawn() - await flush() - - try { - expect(runtime.getDriver(PTY_ID).kind).toBe('idle') - expect(runtime.getTerminalFitOverride(PTY_ID)).toBeNull() - expect(resultTypes(messages)).toEqual(['end']) - } finally { - runtime.cleanupSubscriptionsForConnection('conn-a') - await subscribe - } - }) - - it('never lets a back-to-back unsubscribe overtake the subscribe it names', async () => { - const { runtime, registry } = liveStub() - const register = vi.spyOn(runtime, 'registerOwnedSubscriptionCleanup') - const release = vi.spyOn(runtime, 'releaseSubscriptionByRequest') - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const subscribe = subscribeRequest(binaryParams) - const messages: string[] = [] - - const streaming = dispatcher.dispatchStreaming( - subscribe, - (message) => messages.push(message), - phoneConnection('conn-a') - ) - const unsubscribing = dispatcher.dispatchStreaming(requestUnsubscribe(subscribe.id), vi.fn(), { - connectionId: 'conn-a' - }) - await Promise.all([streaming, unsubscribing]) - await flush() - - expect(register.mock.invocationCallOrder[0]).toBeLessThan(release.mock.invocationCallOrder[0]!) - expect(registry.peekCleanup(SUBSCRIPTION_ID)).toBeUndefined() - expect(registry.requestAddressCount()).toBe(0) - expect(resultTypes(messages).filter((type) => type === 'end')).toHaveLength(1) - }) - - it('heals a half-open socket: the replay on a new socket is what the leave ends', async () => { - const { runtime, spawn } = createRealRuntime() - spawn() - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - // Replay after a reconnect resends the same request id on the new socket. - const replayed = subscribeRequest(binaryParams) - const halfOpenMessages: string[] = [] - const halfOpen = dispatcher.dispatchStreaming( - replayed, - (message) => halfOpenMessages.push(message), - phoneConnection('conn-1') - ) - await vi.waitFor(() => expect(runtime.getDriver(PTY_ID).kind).toBe('mobile')) - const replay = dispatcher.dispatchStreaming(replayed, vi.fn(), phoneConnection('conn-2')) - await halfOpen - expect(resultTypes(halfOpenMessages).at(-1)).toBe('end') - - await dispatcher.dispatchStreaming(requestUnsubscribe(replayed.id), vi.fn(), { - connectionId: 'conn-2' - }) - await replay - - await vi.waitFor(() => expect(runtime.getDriver(PTY_ID).kind).toBe('idle'), { - timeout: 2_000 - }) - // The half-open socket's eventual close finds nothing of its own left. - runtime.cleanupSubscriptionsForConnection('conn-1') - expect(runtime.getDriver(PTY_ID).kind).toBe('idle') - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts deleted file mode 100644 index b5bf8514ed4..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts +++ /dev/null @@ -1,345 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' - -function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { - const registry = createSubscriptionRegistryDouble() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This partial runtime supplies the terminal RPC methods these tests invoke. - return { - getRuntimeId: () => 'test-runtime', - registerOwnedSubscriptionCleanup: registry.registerOwnedSubscriptionCleanup, - subscribeToPtyExit: vi.fn(() => vi.fn()), - // View registration suppresses competing model query replies (terminal-query-authority.md). - registerRemoteTerminalViewSubscriber: () => () => {}, - requestRendererTerminalTabMount: () => false, - ...overrides - } as OrcaRuntimeService -} - -const makeRequest = (method: string, params?: unknown): RpcRequest => ({ - id: 'req-1', - authToken: 'tok', - method, - params -}) - -describe('terminal subscribe buffering', () => { - it('captures live queries before awaiting mobile fit and delivers them after the snapshot', async () => { - const binaryFrames: Uint8Array[] = [] - const registry = createSubscriptionRegistryDouble() - let dataListener: - | ((data: string, meta?: { seq?: number; rawLength?: number }) => void) - | undefined - let resolveMobileSubscribe: () => void = () => {} - const registerRemoteTerminalViewSubscriber = vi.fn(() => vi.fn()) - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - handleMobileSubscribe: vi.fn( - () => - new Promise((resolve) => { - resolveMobileSubscribe = () => resolve(true) - }) - ), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn((_ptyId, listener) => { - dataListener = listener - return vi.fn() - }), - registerRemoteTerminalViewSubscriber, - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValue({ data: 'snapshot', cols: 80, rows: 24, seq: 4 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - }), - vi.fn(), - { - connectionId: 'conn-phone', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - } - ) - - await vi.waitFor(() => expect(runtime.handleMobileSubscribe).toHaveBeenCalled()) - expect(dataListener).toBeDefined() - expect(registerRemoteTerminalViewSubscriber).toHaveBeenCalledWith( - 'pty-1', - undefined, - 'phone-1', - false, - undefined - ) - dataListener?.('\x1b[6n', { seq: 4, rawLength: 4 }) - resolveMobileSubscribe() - - await vi.waitFor(() => - expect( - binaryFrames.some((bytes) => { - const frame = decodeTerminalStreamFrame(bytes) - return ( - frame?.opcode === TerminalStreamOpcode.Output && - decodeTerminalStreamText(frame.payload) === '\x1b[6n' - ) - }) - ).toBe(true) - ) - const queryOutputFrames = binaryFrames.filter((bytes) => { - const frame = decodeTerminalStreamFrame(bytes) - return ( - frame?.opcode === TerminalStreamOpcode.Output && - decodeTerminalStreamText(frame.payload) === '\x1b[6n' - ) - }) - expect(queryOutputFrames).toHaveLength(1) - - runtime.cleanupSubscription('terminal-1:phone-1') - await dispatchPromise - }) - - it('does not register legacy JSON listeners after the stream signal aborts during snapshot', async () => { - vi.useFakeTimers() - try { - const messages: string[] = [] - const controller = new AbortController() - const registry = createSubscriptionRegistryDouble() - let resolveSnapshot: (value: { data: string; cols: number; rows: number }) => void = () => {} - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn( - () => - new Promise<{ data: string; cols: number; rows: number }>((resolve) => { - resolveSnapshot = resolve - }) - ), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' } - }), - (msg) => messages.push(msg), - { connectionId: 'conn-legacy-json', signal: controller.signal } - ) - - await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalled()) - controller.abort() - resolveSnapshot({ data: '', cols: 80, rows: 24 }) - const outcomePromise = Promise.race([ - dispatchPromise.then(() => 'settled'), - new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 0)) - ]) - await vi.advanceTimersByTimeAsync(0) - - expect(await outcomePromise).toBe('settled') - expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled() - expect(runtime.subscribeToFitOverrideChanges).not.toHaveBeenCalled() - // Install cleanup before snapshot work to protect width floors; consume it on abort before adding listeners. - expect(runtime.registerOwnedSubscriptionCleanup).toHaveBeenCalledWith( - 'terminal-1:desktop-1', - expect.any(Function), - 'conn-legacy-json', - 'req-1' - ) - expect(registry.peekCleanup('terminal-1:desktop-1')).toBeUndefined() - expect(runtime.waitForTerminal).not.toHaveBeenCalled() - // After cleanup ends the stream, no snapshot or data may leak. - expect(messages.map((msg) => JSON.parse(msg).result?.type)).toEqual(['end']) - } finally { - vi.useRealTimers() - } - }) - - it('drops stale mobile resize re-stream completions for legacy binary streams', async () => { - const messages: string[] = [] - const binaryFrames: Uint8Array[] = [] - const registry = createSubscriptionRegistryDouble() - let resizeListener: - | ((event: { - cols: number - rows: number - displayMode: string - reason: string - seq: number - }) => void) - | undefined - const restreamResolves: ((value: { - data: string - cols: number - rows: number - oscLinks?: { - row: number - startCol: number - endCol: number - uri: string - }[] - terminalOwner?: 'shell' - }) => void)[] = [] - const serializeTerminalBuffer = vi - .fn() - .mockResolvedValueOnce({ data: 'initial', cols: 80, rows: 24 }) - .mockImplementation( - () => - new Promise<{ - data: string - cols: number - rows: number - oscLinks?: { - row: number - startCol: number - endCol: number - uri: string - }[] - terminalOwner?: 'shell' - }>((resolve) => { - restreamResolves.push(resolve) - }) - ) - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer, - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - handleMobileSubscribe: vi.fn().mockResolvedValue(undefined), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - subscribeToTerminalResize: vi.fn((_, listener) => { - resizeListener = listener as typeof resizeListener - return vi.fn() - }), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})), - sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), - updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true }) - }) - const dispatcher = new RpcDispatcher({ - runtime, - methods: TERMINAL_METHODS - }) - - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - }), - (msg) => messages.push(msg), - { - connectionId: 'conn-stale-resize', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - } - } - ) - - await vi.waitFor(() => expect(resizeListener).toBeDefined()) - binaryFrames.splice(0) - - resizeListener?.({ - cols: 90, - rows: 24, - displayMode: 'auto', - reason: 'apply-layout', - seq: 2 - }) - resizeListener?.({ - cols: 100, - rows: 24, - displayMode: 'auto', - reason: 'apply-layout', - seq: 3 - }) - await vi.waitFor(() => expect(restreamResolves).toHaveLength(2)) - - const newerOscLinks = [{ row: 0, startCol: 4, endCol: 9, uri: 'https://example.com' }] - restreamResolves[1]?.({ - data: 'newer', - cols: 100, - rows: 24, - oscLinks: newerOscLinks, - terminalOwner: 'shell' - }) - await vi.waitFor(() => - expect( - binaryFrames.some((frame) => { - const decoded = decodeTerminalStreamFrame(frame) - return ( - decoded?.opcode === TerminalStreamOpcode.SnapshotChunk && - decodeTerminalStreamText(decoded.payload) === 'newer' - ) - }) - ).toBe(true) - ) - restreamResolves[0]?.({ data: 'older', cols: 90, rows: 24 }) - await Promise.resolve() - await Promise.resolve() - - const snapshotData = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) - expect(snapshotData).toEqual(['newer']) - const snapshotStart = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .find((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart) - expect(snapshotStart && decodeTerminalStreamJson(snapshotStart.payload)).toMatchObject({ - kind: 'resized', - oscLinks: newerOscLinks - }) - expect(snapshotStart && decodeTerminalStreamJson(snapshotStart.payload)).not.toHaveProperty( - 'terminalOwner' - ) - - runtime.cleanupSubscription('terminal-1:phone-1') - await dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-mount-replay.test.ts b/src/main/runtime/rpc/terminal-subscribe-mount-replay.test.ts deleted file mode 100644 index 0c593d079fa..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-mount-replay.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const request: RpcRequest = { - id: 'req-1', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - } -} - -describe('terminal subscribe mount replay', () => { - it('replays a late recovery when readiness lands after the bounded initial response', async () => { - vi.useFakeTimers() - const binaryFrames: Uint8Array[] = [] - const registry = createSubscriptionRegistryDouble() - let mounted = false - let signalWaitStarted!: () => void - const waitStarted = new Promise((resolve) => { - signalWaitStarted = resolve - }) - const runtime = { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-delayed' }), - hasHeadlessTerminalState: vi.fn(() => false), - requestRendererTerminalTabMount: vi.fn(() => true), - getRendererTerminalSerializerGenerationForHandle: vi.fn(() => 1), - getRendererTerminalSerializerGeneration: vi.fn(() => 1), - getPtyOutputSequence: vi.fn(() => (mounted ? 4 : 0)), - replaceHeadlessTerminalFromRendererSnapshotForRecovery: vi.fn(), - waitForRendererTerminalSerializer: vi.fn( - (_ptyId: string, _afterGeneration: number, timeoutMs: number | undefined) => { - expect(timeoutMs).toBeUndefined() - signalWaitStarted() - return new Promise((resolve) => { - setTimeout(() => { - mounted = true - resolve(true) - }, 3_001) - }) - } - ), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), - registerRemoteTerminalViewSubscriber: vi.fn(() => vi.fn()), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn(async () => ({ - data: mounted ? 'delayed idle prompt $ ' : 'late suffix-only redraw', - cols: 80, - rows: 24, - seq: mounted ? 4 : 1 - })), - serializeRendererTerminalBuffer: vi.fn(async () => - mounted ? { data: 'delayed idle prompt $ ', cols: 80, rows: 24, seq: 4 } : null - ), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming(request, vi.fn(), { - connectionId: 'conn-phone', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - }) - - await waitStarted - await vi.advanceTimersByTimeAsync(3_000) - await Promise.resolve() - expect(binaryFrames.length).toBeGreaterThan(0) - expect( - binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') - ).toContain('late suffix-only redraw') - expect( - binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') - ).not.toContain('delayed idle prompt $ ') - await vi.advanceTimersByTimeAsync(1) - await Promise.resolve() - await Promise.resolve() - - expect( - binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') - ).toContain('delayed idle prompt $ ') - - runtime.cleanupSubscription('terminal-1:phone-1') - await dispatchPromise - vi.useRealTimers() - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-ownership.test.ts b/src/main/runtime/rpc/terminal-subscribe-ownership.test.ts deleted file mode 100644 index b750c6cbe2d..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-ownership.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import type { OrcaRuntimeService } from '../orca-runtime' - -import { RuntimeSubscriptionRegistry } from '../client/runtime-subscription-registry' - -import type { RpcRequest } from './core' - -import { RpcDispatcher } from './dispatcher' - -import { TERMINAL_METHODS } from './methods/terminal/terminal' - -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const SUBSCRIPTION_ID = 'terminal-1:phone-1' - -type Waiter = { resolve: () => void } - -function stubRuntime( - registry: ReturnType, - waiters: Waiter[], - overrides: Record = {} -): OrcaRuntimeService { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This partial runtime supplies the terminal RPC methods these tests invoke. - return { - getRuntimeId: () => 'test-runtime', - registerRemoteTerminalViewSubscriber: () => () => {}, - requestRendererTerminalTabMount: () => false, - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn(() => vi.fn()), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValue({ data: 'snapshot', cols: 80, rows: 24, seq: 4 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - cleanupSubscriptionIfOwnedByConnection: vi.fn(registry.cleanupSubscriptionIfOwnedByConnection), - getSubscriptionRegistrationVersion: registry.getSubscriptionRegistrationVersion, - subscribeToPtyExit: vi.fn((_ptyId: string, listener: () => void) => { - waiters.push({ resolve: listener }) - return vi.fn() - }), - ...overrides - } as unknown as OrcaRuntimeService -} - -const makeRequest = (params: unknown): RpcRequest => ({ - id: 'req-1', - authToken: 'tok', - method: 'terminal.subscribe', - params -}) - -const binaryParams = { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } -} - -const leaseOnlyParams = { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1, mobileInputLeaseOnly: 1 } -} - -const streamOptions = (connectionId: string, signal?: AbortSignal) => ({ - signal, - connectionId, - sendBinary: vi.fn(), - registerBinaryStreamHandler: vi.fn(() => vi.fn()) -}) - -describe('terminal.unsubscribe connection ownership', () => { - const unsubscribeRequest = (subscriptionId: string): RpcRequest => ({ - id: 'req-unsub', - authToken: 'tok', - method: 'terminal.unsubscribe', - params: { subscriptionId, client: { id: 'phone-1' } } - }) - - it.each( - [binaryParams, leaseOnlyParams].flatMap((params) => - ['streaming', 'unary'].flatMap((transport) => - [SUBSCRIPTION_ID, 'terminal-1'].map((subscriptionId) => ({ - params, - transport, - subscriptionId - })) - ) - ) - )( - 'keeps the replacement when $transport unsubscribe of $subscriptionId yields', - async ({ params, transport, subscriptionId }) => { - const registry = new RuntimeSubscriptionRegistry() - const runtime = stubRuntime(createSubscriptionRegistryDouble(), [], { - registerOwnedSubscriptionCleanup: registry.registerOwned.bind(registry), - cleanupSubscriptionIfOwnedByConnection: registry.cleanupIfOwnedByConnection.bind(registry), - getSubscriptionRegistrationVersion: registry.getRegistrationVersion.bind(registry) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const connection = streamOptions('conn-a') - const original = dispatcher.dispatchStreaming(makeRequest(params), vi.fn(), connection) - await vi.waitFor(() => expect(runtime.handleMobileSubscribe).toHaveBeenCalledTimes(1)) - - const replies: string[] = [] - const retiring = - transport === 'streaming' - ? dispatcher.dispatchStreaming( - unsubscribeRequest(subscriptionId), - (reply) => replies.push(reply), - { connectionId: 'conn-a' } - ) - : dispatcher - .dispatch(unsubscribeRequest(subscriptionId), { connectionId: 'conn-a' }) - .then((reply) => replies.push(JSON.stringify(reply))) - const replacementMessages: string[] = [] - const replacement = dispatcher.dispatchStreaming( - { ...makeRequest(params), id: 'req-replacement' }, - (reply) => replacementMessages.push(reply), - connection - ) - await retiring - - try { - expect(runtime.handleMobileSubscribe).toHaveBeenCalledTimes(2) - expect(runtime.handleMobileUnsubscribe).toHaveBeenCalledTimes(1) - expect(replacementMessages.some((reply) => JSON.parse(reply).result?.type === 'end')).toBe( - false - ) - expect(JSON.parse(replies[0]!).result).toEqual({ unsubscribed: false }) - } finally { - registry.cleanupForConnection('conn-a') - await Promise.all([original, replacement]) - } - } - ) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts b/src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts deleted file mode 100644 index 4c1ff672509..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const makeRequest = (params: unknown): RpcRequest => ({ - id: 'req-1', - authToken: 'tok', - method: 'terminal.subscribe', - params -}) - -const subscribeParams = { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } -} - -describe('terminal.subscribe reconnect rebind (STA-4510)', () => { - it('keeps the rebound live stream when the pre-reconnect connection aborts', async () => { - const registry = createSubscriptionRegistryDouble() - const dataListeners: ((data: string, meta?: { seq?: number; rawLength?: number }) => void)[] = - [] - - const runtime = { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - registerRemoteTerminalViewSubscriber: () => () => {}, - requestRendererTerminalTabMount: () => false, - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn((_ptyId: string, listener: (typeof dataListeners)[number]) => { - dataListeners.push(listener) - return vi.fn() - }), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValue({ data: 'snapshot', cols: 80, rows: 24, seq: 4 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - // Mirrors bindTerminalWaiterAbort (orca-runtime.ts:34183): abort rejects. - waitForTerminal: vi.fn( - (_handle: string, options?: { signal?: AbortSignal }) => - new Promise((_resolve, reject) => { - options?.signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { - once: true - }) - }) - ) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - // --- connection A: the original mobile socket ------------------------- - const connA = new AbortController() - void dispatcher.dispatchStreaming(makeRequest(subscribeParams), vi.fn(), { - signal: connA.signal, - connectionId: 'conn-a', - sendBinary: vi.fn(), - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - }) - await vi.waitFor(() => expect(dataListeners).toHaveLength(1)) - - // --- connection B: the reconnect re-sends subscribe, no unsubscribe ---- - const connB = new AbortController() - const framesB: Uint8Array[] = [] - void dispatcher.dispatchStreaming(makeRequest(subscribeParams), vi.fn(), { - signal: connB.signal, - connectionId: 'conn-b', - sendBinary: (bytes) => { - framesB.push(bytes) - }, - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - }) - await vi.waitFor(() => expect(dataListeners).toHaveLength(2)) - const liveListener = dataListeners[1] - - // Control: the rebound stream delivers output before the old socket is reaped. - await new Promise((resolve) => setTimeout(resolve, 50)) - framesB.length = 0 - liveListener('before\r\n', { seq: 1, rawLength: 8 }) - await new Promise((resolve) => setTimeout(resolve, 50)) - expect( - framesB.some((b) => decodeTerminalStreamFrame(b)?.opcode === TerminalStreamOpcode.Output) - ).toBe(true) - - // A's own cleanup already ran at rebind time; nothing more may fire after. - const unsubscribesAfterRebind = vi.mocked(runtime.handleMobileUnsubscribe).mock.calls.length - - // --- the half-open socket A is finally detected and closed ------------ - // runtime-rpc.ts:1339-1341 aborts dispatches first, then sweeps the conn. - connA.abort() - registry.cleanupSubscriptionsForConnection('conn-a') - await new Promise((resolve) => setTimeout(resolve, 0)) - - // --- the live (rebound) stream must survive --------------------------- - framesB.length = 0 - liveListener('after\r\n', { seq: 2, rawLength: 7 }) - await new Promise((resolve) => setTimeout(resolve, 20)) - expect( - framesB.some((b) => decodeTerminalStreamFrame(b)?.opcode === TerminalStreamOpcode.Output) - ).toBe(true) - expect(vi.mocked(runtime.handleMobileUnsubscribe).mock.calls.length).toBe( - unsubscribesAfterRebind - ) - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.ts b/src/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.ts deleted file mode 100644 index 3c6f0da3f3e..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Use the real runtime exit predicate: stale-handle wiring doubles it and cannot prove a relay drop preserves the lease. -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const PTY_ID = 'pty-1' - -const subscriptionCases = [ - { - name: 'lease-only', - params: { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1, mobileInputLeaseOnly: 1 } - } - }, - { - name: 'legacy JSON', - params: { terminal: 'terminal-1', client: { id: 'desktop-1', type: 'desktop' } } - }, - { - name: 'binary', - params: { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - } - } -] as const - -type PtyInternals = { - recordPtyWorktree: (ptyId: string, worktreeId: string, state?: { connected?: boolean }) => unknown - ptysById: Map -} - -/** A PTY whose relay dropped: connection lost, no exit code, process possibly still running. */ -function makeRelayDroppedRuntime(): OrcaRuntimeService { - const real = new OrcaRuntimeService() - const internals = real as unknown as PtyInternals - internals.recordPtyWorktree(PTY_ID, 'wt-1', { connected: true }) - const pty = internals.ptysById.get(PTY_ID)! - pty.connected = false - expect(pty.lastExitCode).toBeNull() - return real -} - -function createRuntime(real: OrcaRuntimeService): { - registry: ReturnType - runtime: OrcaRuntimeService -} { - const registry = createSubscriptionRegistryDouble() - const runtime = { - getRuntimeId: () => 'test-runtime', - requestRendererTerminalTabMount: () => false, - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: PTY_ID }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - registerRemoteTerminalViewSubscriber: vi.fn(() => vi.fn()), - subscribeToTerminalData: vi.fn(() => vi.fn()), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi - .fn() - .mockResolvedValue({ data: 'snapshot', cols: 80, rows: 24, seq: 1 }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn(() => vi.fn()), - subscribeToFitOverrideChanges: vi.fn(() => vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => Promise.reject(new Error('unexpected handle waiter'))), - // The one call under test: the real exit predicate, not a double's opinion of it. - subscribeToPtyExit: (ptyId: string, listener: () => void) => - real.subscribeToPtyExit(ptyId, listener) - } as unknown as OrcaRuntimeService - return { registry, runtime } -} - -function makeRequest(params: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method: 'terminal.subscribe', params } -} - -describe('terminal subscribe when the relay dropped without an exit code', () => { - it.each(subscriptionCases)( - 'does not end $name for a process that may still be running', - async ({ params }) => { - const real = makeRelayDroppedRuntime() - const { registry, runtime } = createRuntime(real) - const messages: string[] = [] - const types = (): unknown[] => messages.map((message) => JSON.parse(message).result?.type) - - void new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - .dispatchStreaming(makeRequest(params), (message) => messages.push(message), { - connectionId: 'conn-1', - sendBinary: vi.fn(), - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - }) - .catch(() => undefined) - - const subscriptionId = `terminal-1:${params.client.id}` - await vi.waitFor(() => expect(registry.peekCleanup(subscriptionId)).toBeDefined()) - expect(types()).not.toContain('end') - - // The host comes back and reports the real exit; only now may the lease retire. - real.onPtyExit(PTY_ID, 0) - - await vi.waitFor(() => expect(registry.peekCleanup(subscriptionId)).toBeUndefined()) - expect(types()).toContain('end') - } - ) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-renderer-recovery-output.test.ts b/src/main/runtime/rpc/terminal-subscribe-renderer-recovery-output.test.ts deleted file mode 100644 index c936ec300a4..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-renderer-recovery-output.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const request: RpcRequest = { - id: 'req-output-race', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: 'terminal-output-race', - client: { id: 'phone-output-race', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - } -} - -describe('terminal subscribe renderer recovery output ordering', () => { - it('replays bytes absent from the renderer snapshot using its exact sequence boundary', async () => { - const binaryFrames: Uint8Array[] = [] - const registry = createSubscriptionRegistryDouble() - let outputSequence = 0 - let rendererSerializeCalls = 0 - let onData: - | ((data: string, meta?: { seq?: number; rawLength?: number; cwd?: string }) => void) - | undefined - const runtime = { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-output-race' }), - hasHeadlessTerminalState: vi.fn(() => false), - requestRendererTerminalTabMount: vi.fn(() => true), - getRendererTerminalSerializerGenerationForHandle: vi.fn(() => 1), - getRendererTerminalSerializerGeneration: vi.fn(() => 1), - waitForRendererTerminalSerializer: vi.fn().mockResolvedValue(true), - getPtyOutputSequence: vi.fn(() => outputSequence), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn((_ptyId, listener) => { - onData = listener - return vi.fn() - }), - registerRemoteTerminalViewSubscriber: vi.fn(() => vi.fn()), - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn().mockResolvedValue(null), - serializeRendererTerminalBuffer: vi.fn(async () => { - rendererSerializeCalls += 1 - if (rendererSerializeCalls === 1) { - outputSequence = 6 - onData?.('during', { seq: 6, rawLength: 6 }) - return { data: 'stale renderer', cols: 80, rows: 24 } - } - return { data: 'restored history', cols: 80, rows: 24, seq: 0 } - }), - replaceHeadlessTerminalFromRendererSnapshotForRecovery: vi.fn(() => { - outputSequence = 11 - onData?.('after', { seq: 11, rawLength: 5 }) - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming(request, vi.fn(), { - connectionId: 'conn-phone', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - }) - - await vi.waitFor(() => { - const output = binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') - expect(output).toBe('duringafter') - }) - - const snapshot = binaryFrames - .map((bytes) => decodeTerminalStreamFrame(bytes)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') - expect(snapshot).toBe('restored history') - expect(rendererSerializeCalls).toBe(2) - - runtime.cleanupSubscription('terminal-output-race:phone-output-race') - await dispatchPromise - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-residual-metadata.test.ts b/src/main/runtime/rpc/terminal-subscribe-residual-metadata.test.ts deleted file mode 100644 index 7e7df52023c..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-residual-metadata.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { stubRuntime, makeRequest } from './terminal-multiplex-test-harness' -import type { TerminalOutputMeta } from './terminal-output-frame-chunks' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' - -describe('mobile subscribe residual metadata', () => { - it.each([undefined, 5, 12])( - 'strips a snapshot-boundary query without changing transformed span rawLength %s', - async (transformedRawLength) => { - vi.useFakeTimers() - const controller = new AbortController() - try { - const binaryFrames: Uint8Array[] = [] - let emitOutput: ((data: string, meta?: TerminalOutputMeta) => void) | undefined - let releaseSnapshot: (() => void) | undefined - const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: (_ptyId, listener) => { - emitOutput = listener - return vi.fn() - }, - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn(async () => { - await new Promise((resolve) => { - releaseSnapshot = resolve - }) - // The snapshot ends inside the cursor-position query in the buffered output. - return { data: 'before', cols: 40, rows: 24, seq: 8 } - }), - getTerminalSize: vi.fn().mockReturnValue({ cols: 40, rows: 24 }), - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const dispatchPromise = dispatcher.dispatchStreaming( - makeRequest('terminal.subscribe', { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1 } - }), - vi.fn(), - { - signal: controller.signal, - connectionId: 'phone-connection', - sendBinary: (bytes) => { - binaryFrames.push(bytes) - }, - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - } - ) - await vi.runOnlyPendingTimersAsync() - expect(releaseSnapshot).toBeTypeOf('function') - emitOutput?.('before\x1b[6nafter', { seq: 15, rawLength: 15 }) - if (transformedRawLength !== undefined) { - emitOutput?.('PAINT', { - seq: 15 + transformedRawLength, - rawLength: transformedRawLength, - transformed: true, - cwd: '/workspace' - }) - } - releaseSnapshot?.() - await vi.runOnlyPendingTimersAsync() - - const frames = binaryFrames.flatMap((bytes) => { - const frame = decodeTerminalStreamFrame(bytes) - return frame ? [frame] : [] - }) - const output = frames.filter( - (frame) => - frame.opcode === TerminalStreamOpcode.Output || - frame.opcode === TerminalStreamOpcode.OutputSpan - ) - expect( - output.map((frame) => ({ - opcode: frame.opcode, - seq: frame.seq, - payload: - frame.opcode === TerminalStreamOpcode.Output - ? decodeTerminalStreamText(frame.payload) - : decodeTerminalStreamJson(frame.payload) - })) - ).toEqual([ - { opcode: TerminalStreamOpcode.Output, seq: 15, payload: '\x1b[6nafter' }, - ...(transformedRawLength === undefined - ? [] - : [ - // Phones never decoded OutputSpan, so a transformed span reaches them as text. - { - opcode: TerminalStreamOpcode.Output, - seq: 15 + transformedRawLength, - payload: 'PAINT' - } - ]) - ]) - if (transformedRawLength !== undefined) { - expect( - frames - .filter((frame) => frame.opcode === TerminalStreamOpcode.Metadata) - .map((frame) => decodeTerminalStreamJson(frame.payload)) - ).toEqual([{ cwd: '/workspace' }]) - } - controller.abort() - await dispatchPromise - } finally { - controller.abort() - vi.useRealTimers() - } - } - ) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-resume.test.ts b/src/main/runtime/rpc/terminal-subscribe-resume.test.ts deleted file mode 100644 index 4ff7166ccfb..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-resume.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson, - decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { TerminalPublishedOutputRings } from '../terminal/output/terminal-published-output-ring' - -type Listener = (data: string, meta?: { seq?: number; rawLength?: number; cwd?: string }) => void - -function createHost() { - const registry = createSubscriptionRegistryDouble() - const rings = new TerminalPublishedOutputRings() - const listeners = new Set() - const addListener = (listener: Listener) => { - listeners.add(listener) - return () => { - listeners.delete(listener) - } - } - let seq = 0 - let size = { cols: 40, rows: 20 } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This partial runtime supplies the terminal RPC methods these tests invoke. - const runtime = { - getRuntimeId: () => 'test-runtime', - subscribeToPtyExit: vi.fn(() => vi.fn()), - registerRemoteTerminalViewSubscriber: () => () => {}, - requestRendererTerminalTabMount: () => false, - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: (_ptyId: string, listener: Listener) => addListener(listener), - retainPublishedTerminalOutput: (ptyId: string) => - rings.retain(ptyId, { seq, size: () => size, subscribe: addListener }), - getPtyOutputSequence: () => seq, - readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), - serializeTerminalBuffer: vi.fn(async () => ({ data: 'screen', ...size, seq })), - getTerminalSize: () => size, - getMobileDisplayMode: vi.fn().mockReturnValue('auto'), - getLayout: vi.fn().mockReturnValue({ seq: 1 }), - isTerminalAlternateScreen: vi.fn().mockReturnValue(false), - subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), - subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - waitForTerminal: vi.fn(() => new Promise(() => {})) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - // Mirrors onPtyData publishing a chunk to stream subscribers. - const output = (data: string, cwd?: string) => { - seq += data.length - for (const listener of listeners) { - listener(data, { seq, rawLength: data.length, ...(cwd ? { cwd } : {}) }) - } - } - - const subscribe = async (resume?: { streamToken: string; units: number }) => { - const frames: Uint8Array[] = [] - const messages: string[] = [] - const done = dispatcher.dispatchStreaming( - { - id: 'sub', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - capabilities: { terminalBinaryStream: 1, outputAck: 1 }, - ...(resume ? { resume } : {}) - } - }, - (msg) => messages.push(msg), - { - connectionId: 'conn-phone', - pairedDeviceId: 'phone-device', - sendBinary: (bytes) => { - frames.push(bytes) - }, - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - } - ) - const subscribed = await vi.waitFor(() => { - const result = messages - .map((msg) => JSON.parse(msg).result) - .find((candidate) => candidate?.type === 'subscribed') - expect(result).toBeDefined() - return result - }) - const decoded = () => frames.map((bytes) => decodeTerminalStreamFrame(bytes)!) - const received = () => - decoded() - .filter((frame) => frame.opcode === TerminalStreamOpcode.Output) - .map((frame) => decodeTerminalStreamText(frame.payload)) - .join('') - return { - subscribed, - received, - cwds: () => - decoded().flatMap((frame) => - frame.opcode === TerminalStreamOpcode.Metadata - ? [decodeTerminalStreamJson<{ cwd: string }>(frame.payload)?.cwd] - : [] - ), - // Output leaves through the stream's batcher, so wait for it rather than reading at once. - receives: (text: string) => vi.waitFor(() => expect(received()).toBe(text)), - snapshotKinds: () => - decoded().flatMap((frame) => - frame.opcode === TerminalStreamOpcode.SnapshotStart - ? [decodeTerminalStreamJson<{ kind: string }>(frame.payload)?.kind] - : [] - ), - stop: async () => { - runtime.cleanupSubscription('terminal-1:phone-1') - await done - } - } - } - - return { - output, - subscribe, - resize: (next: { cols: number; rows: number }) => { - size = next - }, - // What a respawn does to the ring (advancePtyLifecycleGeneration). - resetCoverage: () => rings.get('pty-1')?.resetCoverage(seq) - } -} - -/** A phone stream that received 'hello ' and 'world', then ended while 'again' was printed. */ -async function endedStream() { - const host = createHost() - const first = await host.subscribe() - host.output('hello ') - await first.receives('hello ') - host.output('world') - await first.receives('hello world') - await first.stop() - host.output('again') - const token: string = first.subscribed.streamToken - return { host, token, units: 11 } -} - -describe('terminal.subscribe resume', () => { - it('sends only the missed output, then the next resume works from the new token', async () => { - const { host, token, units } = await endedStream() - - const second = await host.subscribe({ streamToken: token, units }) - expect(second.subscribed).toMatchObject({ resumed: true, streamToken: expect.any(String) }) - await second.receives('again') - expect(second.snapshotKinds()).toEqual([]) - - host.output('!') - await second.receives('again!') - await second.stop() - host.output('?') - const third = await host.subscribe({ streamToken: second.subscribed.streamToken, units: 6 }) - expect(third.subscribed.resumed).toBe(true) - await third.receives('?') - await third.stop() - }) - - it('leaves reply queries out of the missed output', async () => { - const host = createHost() - const first = await host.subscribe() - host.output('ready') - await first.receives('ready') - await first.stop() - host.output('a\x1b[cb\x1b[?2031h') - - const second = await host.subscribe({ streamToken: first.subscribed.streamToken, units: 5 }) - expect(second.subscribed.resumed).toBe(true) - await second.receives('ab\x1b[?2031h') - await second.stop() - }) - - it('sends a snapshot after a coverage reset while the stream was live, as on a clear', async () => { - const host = createHost() - const first = await host.subscribe() - host.output('hello ') - await first.receives('hello ') - host.resetCoverage() - host.output('after') - await first.receives('hello after') - await first.stop() - - const next = await host.subscribe({ streamToken: first.subscribed.streamToken, units: 11 }) - expect(next.subscribed.resumed).toBeUndefined() - expect(next.snapshotKinds()).toEqual(['scrollback']) - await next.stop() - }) - - it.each([ - [ - 'a reused token', - async ({ host, token, units }: Awaited>) => { - const used = await host.subscribe({ streamToken: token, units }) - await used.stop() - } - ], - [ - 'a resize', - async ({ host }: Awaited>) => { - host.resize({ cols: 80, rows: 20 }) - host.output('wide') - } - ], - [ - 'a coverage reset, as on respawn', - async ({ host }: Awaited>) => { - host.resetCoverage() - host.output('reborn') - } - ] - ])('sends a snapshot after %s', async (_name, disrupt) => { - const ended = await endedStream() - await disrupt(ended) - - const next = await ended.host.subscribe({ streamToken: ended.token, units: ended.units }) - expect(next.subscribed.resumed).toBeUndefined() - expect(next.snapshotKinds()).toEqual(['scrollback']) - await next.stop() - }) -}) diff --git a/src/main/runtime/rpc/terminal-agent-prompt-send.test.ts b/src/main/runtime/rpc/terminal/terminal-agent-prompt-send.test.ts similarity index 82% rename from src/main/runtime/rpc/terminal-agent-prompt-send.test.ts rename to src/main/runtime/rpc/terminal/terminal-agent-prompt-send.test.ts index eef6afdfda0..0e1b65de35a 100644 --- a/src/main/runtime/rpc/terminal-agent-prompt-send.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-agent-prompt-send.test.ts @@ -1,12 +1,12 @@ -import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing' +import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' import { describe, expect, it, vi } from 'vitest' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { createAgentPromptSubmissionRuntime } from '../terminal/input/agent-prompt-submission-runtime-test-fixture' -import { TERMINAL_METHODS } from './methods/terminal/terminal' +import type { RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { createAgentPromptSubmissionRuntime } from '../../terminal/input/agent-prompt-submission-runtime-test-fixture' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' -vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { +vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { const facade = getWorktreeListingMocks() return { ...(await importOriginal()), diff --git a/src/main/runtime/rpc/terminal-agent-send-guard.ts b/src/main/runtime/rpc/terminal/terminal-agent-send-guard.ts similarity index 96% rename from src/main/runtime/rpc/terminal-agent-send-guard.ts rename to src/main/runtime/rpc/terminal/terminal-agent-send-guard.ts index ddc271c3781..812788f47ec 100644 --- a/src/main/runtime/rpc/terminal-agent-send-guard.ts +++ b/src/main/runtime/rpc/terminal/terminal-agent-send-guard.ts @@ -1,4 +1,4 @@ -import type { OrcaRuntimeService } from '../orca-runtime' +import type { OrcaRuntimeService } from '../../orca-runtime' const AGENT_STATUS_RECHECK_INTERVAL_MS = 150 const AGENT_STATUS_RECHECK_TIMEOUT_MS = 1_050 diff --git a/src/main/runtime/rpc/terminal-close-attribution.ts b/src/main/runtime/rpc/terminal/terminal-close-attribution.ts similarity index 88% rename from src/main/runtime/rpc/terminal-close-attribution.ts rename to src/main/runtime/rpc/terminal/terminal-close-attribution.ts index 49296afc0ff..89d212d6669 100644 --- a/src/main/runtime/rpc/terminal-close-attribution.ts +++ b/src/main/runtime/rpc/terminal/terminal-close-attribution.ts @@ -1,6 +1,6 @@ -import { withSpan } from '../../observability/tracer' -import type { RuntimeTerminalClose } from '../../../shared/runtime-terminal-contracts' -import type { RpcContext } from './core' +import { withSpan } from '../../../observability/tracer' +import type { RuntimeTerminalClose } from '../../../../shared/runtime-terminal-contracts' +import type { RpcContext } from '../core' type TerminalCloseMethod = 'terminal.close' | 'terminal.closeTab' type TerminalCloseTargetKind = 'terminal' | 'terminal-tab' diff --git a/src/main/runtime/rpc/terminal/terminal-multiplex-ack-overflow-recovery.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-ack-overflow-recovery.test.ts new file mode 100644 index 00000000000..7bfb4916a56 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-ack-overflow-recovery.test.ts @@ -0,0 +1,354 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamJson, + decodeTerminalStreamText, + encodeTerminalStreamFrame, + encodeTerminalStreamJson, + encodeTerminalStreamText +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { makeRequest, stubRuntime } from './testing/terminal-multiplex-test-harness' + +describe('terminal multiplex RPC', () => { + it('caps stalled ACK output and snapshots before resuming retained tail frames', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi + .fn() + .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) + .mockResolvedValue({ data: 'recovered snapshot', cols: 120, rows: 40, seq: 99 }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn( + ( + _: string, + listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void + ) => { + dataListenerRef.current = listener + return vi.fn() + } + ), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-ack-overflow', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 17, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) + ) + binaryFrames.splice(0) + + const output = 'x'.repeat(3 * 1024 * 1024) + dataListenerRef.current?.(output, { seq: output.length, rawLength: output.length }) + + const initialOutputFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + const initialBytes = initialOutputFrames.reduce( + (total, frame) => total + (frame?.payload.byteLength ?? 0), + 0 + ) + expect(initialBytes).toBeLessThanOrEqual(512 * 1024) + + handlers.get(17)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId: 17, + seq: 2, + payload: encodeTerminalStreamText('still interactive\r') + }) + )! + ) + await vi.waitFor(() => + expect(runtime.sendTerminal).toHaveBeenCalledWith( + 'terminal-1', + { + text: 'still interactive\r', + enter: false, + interrupt: false + }, + { inputKind: 'driving', inputSource: 'desktop' } + ) + ) + + binaryFrames.splice(0) + handlers.get(17)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Ack, + streamId: 17, + seq: 3, + payload: encodeTerminalStreamJson({ bytes: initialBytes }) + }) + )! + ) + + await vi.waitFor(() => + expect( + binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .some((frame) => { + if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { + return false + } + const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) + return payload?.reason === 'ack-pending-overflow' + }) + ).toBe(true) + ) + const drainFrames = binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)) + const recoveryStartIndex = drainFrames.findIndex((frame) => { + if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { + return false + } + const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) + return payload?.reason === 'ack-pending-overflow' + }) + const firstOutputAfterAckIndex = drainFrames.findIndex( + (frame) => frame?.opcode === TerminalStreamOpcode.Output + ) + expect(recoveryStartIndex).toBeGreaterThanOrEqual(0) + // Clients discard truncated snapshots; mark usable recovery complete or the gap stays permanent. + expect( + decodeTerminalStreamJson<{ truncated?: boolean }>(drainFrames[recoveryStartIndex]!.payload) + ?.truncated + ).toBe(false) + // Recovery must replace history that ends before dropped output. + expect(runtime.serializeTerminalBuffer).toHaveBeenLastCalledWith('pty-1', { + scrollbackRows: 1000 + }) + expect( + decodeTerminalStreamJson<{ scrollbackRows?: number }>( + drainFrames[recoveryStartIndex]!.payload + )?.scrollbackRows + ).toBe(1000) + expect(firstOutputAfterAckIndex).toBeGreaterThan(recoveryStartIndex) + expect( + drainFrames + .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + ).toBe('recovered snapshot') + + const outputBytesAfterRecovery = drainFrames + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + expect(outputBytesAfterRecovery).toBeLessThanOrEqual(256 * 1024) + + runtime.cleanupSubscription('terminal-multiplex:conn-ack-overflow') + await dispatchPromise + }) + + it('trims recovery-covered ACK pending output instead of replaying it', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const floodedChars = 3 * 1024 * 1024 + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi + .fn() + .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) + // Recovery seq covers the flood, so all retained chunks already appear in the snapshot. + .mockResolvedValue({ data: 'recovered snapshot', cols: 120, rows: 40, seq: floodedChars }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn( + ( + _: string, + listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void + ) => { + dataListenerRef.current = listener + return vi.fn() + } + ), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-ack-trim', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 31, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) + ) + binaryFrames.splice(0) + + const output = 'x'.repeat(floodedChars) + dataListenerRef.current?.(output, { seq: floodedChars, rawLength: floodedChars }) + const initialBytes = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + expect(initialBytes).toBeLessThanOrEqual(512 * 1024) + + binaryFrames.splice(0) + handlers.get(31)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Ack, + streamId: 31, + seq: 2, + payload: encodeTerminalStreamJson({ bytes: initialBytes }) + }) + )! + ) + await vi.waitFor(() => + expect( + binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .some((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd) + ).toBe(true) + ) + + const framesAfterRecovery = binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)) + expect( + framesAfterRecovery + .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + ).toBe('recovered snapshot') + // Covered chunks would duplicate recovered snapshot content. + expect( + framesAfterRecovery.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + ).toEqual([]) + + binaryFrames.splice(0) + const fresh = 'fresh-after-recovery\r\n' + dataListenerRef.current?.(fresh, { + seq: floodedChars + fresh.length, + rawLength: fresh.length + }) + await vi.waitFor(() => { + const freshOutput = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + expect(freshOutput).toBe(fresh) + }) + + runtime.cleanupSubscription('terminal-multiplex:conn-ack-trim') + await dispatchPromise + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex-adaptive-ack-window.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-adaptive-ack-window.test.ts similarity index 85% rename from src/main/runtime/rpc/terminal-multiplex-adaptive-ack-window.test.ts rename to src/main/runtime/rpc/terminal/terminal-multiplex-adaptive-ack-window.test.ts index 7b2a87f1137..bbce2d9fa5f 100644 --- a/src/main/runtime/rpc/terminal-multiplex-adaptive-ack-window.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-adaptive-ack-window.test.ts @@ -1,16 +1,16 @@ -import './unused-default-rpc-methods.test-fixture' +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' import { afterEach, describe, expect, it, vi } from 'vitest' import { TerminalStreamOpcode, decodeTerminalStreamFrame, encodeTerminalStreamFrame, encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { TerminalMultiplexLinkEstimate } from './methods/terminal/terminal-multiplex-link-estimate' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { TerminalMultiplexLinkEstimate } from '../methods/terminal/terminal-multiplex-link-estimate' import { sendDesktopMultiplexSubscribe, startDesktopMultiplexSubscribe -} from './terminal-multiplex-test-harness' +} from './testing/terminal-multiplex-test-harness' const STREAM_ID = 7 const CHUNK = 64 * 1024 @@ -82,16 +82,6 @@ describe('terminal multiplex adaptive ACK window', () => { vi.unstubAllEnvs() }) - it('keeps legacy windows when pacing is not opted in, even on a measured slow link', async () => { - measureSlowLink() - const stream = await openAltScreenStream() - stream.write(10) - expect(stream.sentOutputBytes()).toBe(512 * 1024) - stream.ack(512 * 1024) - expect(stream.sentOutputBytes()).toBe(128 * 1024) - await stream.close() - }) - it('returns paced headroom once the queue drains, so later output overflows at the legacy cap', async () => { vi.stubEnv('ORCA_TERMINAL_ADAPTIVE_ACK_WINDOW', '1') measureSlowLink() diff --git a/src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts similarity index 89% rename from src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts rename to src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts index 77b4270b5fe..71d7d383e96 100644 --- a/src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts @@ -1,15 +1,15 @@ import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' +import { RpcDispatcher } from '../dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import { createSubscriptionRegistryDouble } from '../testing/subscription-registry-test-double' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' import { TerminalStreamOpcode, decodeTerminalStreamFrame, decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { makeRequest, stubRuntime } from './terminal-multiplex-test-harness' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { makeRequest, stubRuntime } from './testing/terminal-multiplex-test-harness' describe('terminal multiplex RPC', () => { it('replays only buffered multiplex output not covered by the initial snapshot seq', async () => { diff --git a/src/main/runtime/rpc/terminal/terminal-multiplex-input-sequence-replay.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-input-sequence-replay.test.ts new file mode 100644 index 00000000000..6185fbff07d --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-input-sequence-replay.test.ts @@ -0,0 +1,244 @@ +import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' + +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import { createSubscriptionRegistryDouble } from '../testing/subscription-registry-test-double' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + encodeTerminalStreamFrame, + encodeTerminalStreamJson, + encodeTerminalStreamText, + decodeTerminalInputAck, + type TerminalInputAckKind +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { makeRequest, stubRuntime } from './testing/terminal-multiplex-test-harness' + +vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktreesStrict: facade.listWorktreesStrict + } +}) + +const { getWorktreeListingMocks } = vi.hoisted(() => { + const createWorktreeListingMocks = () => ({ + listWorktreesStrict: async () => [ + { path: '/tmp/worktree-a', head: 'abc', branch: 'test', isBare: false, isMainWorktree: false } + ] + }) + let listings: ReturnType | undefined + return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } +}) + +type FrameHandler = (frame: NonNullable>) => void + +type ScriptedWrite = 'accept' | 'reject' | 'throw' | 'unverifiable' | 'unhanded' + +function createRuntime( + writes: string[], + writeGate: () => Promise = async () => {}, + scriptedWrites: ScriptedWrite[] = [], + sendOptions: unknown[] = [] +): OrcaRuntimeService { + const registry = createSubscriptionRegistryDouble() + return stubRuntime({ + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', cols: 120, rows: 40 }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), + registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), + cleanupSubscription: vi.fn(registry.cleanupSubscription), + cleanupSubscriptionIfOwnedByConnection: vi.fn(registry.cleanupSubscriptionIfOwnedByConnection), + cleanupSubscriptionsForConnection: vi.fn(registry.cleanupSubscriptionsForConnection), + waitForTerminal: vi.fn(() => new Promise(() => {})), + updateDesktopViewport: vi.fn().mockResolvedValue(true), + sendTerminal: vi.fn(async (_handle: string, action: { text?: string }, options: unknown) => { + sendOptions.push(options) + await writeGate() + const scripted = scriptedWrites.shift() ?? 'accept' + if (scripted === 'unverifiable') { + // The SSH provider queued the bytes, then its connection dropped before the handoff settled. + return { + handle: 'terminal-1', + accepted: false, + bytesWritten: 0, + writeSettlement: { + outcome: 'unverifiable' as const, + reason: 'transport_settlement_lost' as const, + bytesHandedToTransport: true + } + } + } + if (scripted === 'unhanded') { + // Settlement lost, but the provider proves no byte left before it was disposed. + return { + handle: 'terminal-1', + accepted: false, + bytesWritten: 0, + writeSettlement: { + outcome: 'unverifiable' as const, + reason: 'transport_settlement_lost' as const, + bytesHandedToTransport: false + } + } + } + if (scripted === 'throw') { + throw new Error('ssh channel write failed') + } + if (scripted === 'reject') { + return { handle: 'terminal-1', accepted: false, bytesWritten: 0 } + } + writes.push(action.text ?? '') + return { handle: 'terminal-1', accepted: true, bytesWritten: action.text?.length ?? 0 } + }) + }) +} + +async function openConnection( + dispatcher: RpcDispatcher, + connectionId: string, + subscribe: { capabilities: Record; inputSessionId?: string } +) { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map() + void dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (message) => messages.push(message), + { + connectionId, + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + await vi.waitFor(() => expect(handlers.has(0)).toBe(true)) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 7, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + ...subscribe + }) + }) + )! + ) + await vi.waitFor(() => + expect(messages.some((message) => JSON.parse(message).result?.type === 'subscribed')).toBe(true) + ) + const subscribed: { + capabilities?: Record + inputLedgerId?: string + } = JSON.parse( + messages.find((message) => JSON.parse(message).result?.type === 'subscribed')! + ).result + return { + subscribed, + sendInput: (seq: number, text: string) => + handlers.get(7)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId: 7, + seq, + payload: encodeTerminalStreamText(text) + }) + )! + ), + inputAcks: (kind: TerminalInputAckKind = 'applied') => + binaryFrames.flatMap((bytes) => { + const frame = decodeTerminalStreamFrame(bytes) + return frame?.opcode === TerminalStreamOpcode.InputAck && + decodeTerminalInputAck(frame.payload) === kind + ? [frame.seq] + : [] + }), + writeUnavailableCount: () => + binaryFrames.filter( + (bytes) => + decodeTerminalStreamFrame(bytes)?.opcode === TerminalStreamOpcode.WriteUnavailable + ).length + } +} + +describe('terminal multiplex sequenced input across reconnects', () => { + it('writes input replayed on a new connection exactly once, even when the dead connection delivers late', async () => { + const writes: string[] = [] + const dispatcher = new RpcDispatcher({ + runtime: createRuntime(writes), + methods: TERMINAL_METHODS + }) + const subscribe = { + capabilities: { ackOutput: 1 as const, inputAck: 1 as const }, + inputSessionId: 'pane-a' + } + const dead = await openConnection(dispatcher, 'conn-dead', subscribe) + expect(dead.subscribed.capabilities).toMatchObject({ inputAck: 1 }) + + dead.sendInput(1, 'PZ600-0') + await vi.waitFor(() => expect(dead.inputAcks()).toEqual([1])) + // The ack for seq 2 never reaches the client: the link went silent. + dead.sendInput(2, '12') + + const replacement = await openConnection(dispatcher, 'conn-replacement', subscribe) + replacement.sendInput(2, '12') + replacement.sendInput(3, '3\r') + // The surviving SSH channel finally flushes the dead connection's buffered copy. + dead.sendInput(3, '3\r') + + await vi.waitFor(() => expect(replacement.inputAcks()).toEqual([2, 3])) + expect(writes).toEqual(['PZ600-0', '12', '3\r']) + }) + + it('never acks a write the PTY refused, and asks the same stream to resend instead of remounting', async () => { + const writes: string[] = [] + const dispatcher = new RpcDispatcher({ + runtime: createRuntime(writes, async () => {}, ['accept', 'reject']), + methods: TERMINAL_METHODS + }) + const subscribe = { + capabilities: { writeUnavailable: 1 as const, inputAck: 1 as const }, + inputSessionId: 'pane-a' + } + const stream = await openConnection(dispatcher, 'conn-first', subscribe) + stream.sendInput(1, 'echo a\r') + stream.sendInput(2, 'echo b\r') + stream.sendInput(3, 'echo c\r') + await vi.waitFor(() => expect(stream.inputAcks('resend')).toEqual([1, 1])) + // Neither the refused seq 2 nor seq 3 behind it may be acked, or the client drops them. + expect(stream.inputAcks()).toEqual([1]) + expect(writes).toEqual(['echo a\r']) + // A remount would throw away the client's journal, so a sequenced refusal must not ask for one. + expect(stream.writeUnavailableCount()).toBe(0) + + // The PTY is writable again: the live stream resends, and typing after it keeps flowing. + stream.sendInput(2, 'echo b\r') + stream.sendInput(3, 'echo c\r') + stream.sendInput(4, 'echo d\r') + await vi.waitFor(() => expect(stream.inputAcks()).toEqual([1, 2, 3, 4])) + expect(writes).toEqual(['echo a\r', 'echo b\r', 'echo c\r', 'echo d\r']) + }) +}) diff --git a/src/main/runtime/rpc/terminal/terminal-multiplex-input-write-rejection.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-input-write-rejection.test.ts new file mode 100644 index 00000000000..7ffd3494d1c --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-input-write-rejection.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + encodeTerminalStreamFrame, + encodeTerminalStreamText +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { + WRITE_UNAVAILABLE_OPCODE, + sendDesktopMultiplexSubscribe, + startDesktopMultiplexSubscribe +} from './testing/terminal-multiplex-test-harness' + +describe('terminal multiplex rejected input signalling', () => { + it('does not report a late rejection to a replacement stream with the same id', async () => { + let settleWrite: (result: { + handle: string + accepted: boolean + bytesWritten: number + }) => void = () => {} + const hostWrite = new Promise<{ handle: string; accepted: boolean; bytesWritten: number }>( + (resolve) => { + settleWrite = resolve + } + ) + const sendTerminal = vi.fn(() => hostWrite) + const harness = startDesktopMultiplexSubscribe({ + sendTerminal: sendTerminal as unknown as OrcaRuntimeService['sendTerminal'] + }) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + const capabilities = { ackOutput: 1 as const, writeUnavailable: 1 as const } + sendDesktopMultiplexSubscribe(harness.handlers, capabilities) + await vi.waitFor(() => expect(harness.handlers.has(7)).toBe(true)) + harness.binaryFrames.splice(0) + + harness.handlers.get(7)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId: 7, + seq: 2, + payload: encodeTerminalStreamText('old') + }) + )! + ) + await vi.waitFor(() => expect(sendTerminal).toHaveBeenCalledOnce()) + harness.handlers.get(7)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Unsubscribe, + streamId: 7, + seq: 3, + payload: new Uint8Array() + }) + )! + ) + sendDesktopMultiplexSubscribe(harness.handlers, capabilities) + await vi.waitFor(() => + expect( + harness.messages.filter((message) => JSON.parse(message).result?.type === 'subscribed') + ).toHaveLength(2) + ) + harness.binaryFrames.splice(0) + + settleWrite({ handle: 'terminal-1', accepted: false, bytesWritten: 0 }) + await hostWrite + await Promise.resolve() + + expect(harness.binaryFrames.some((frame) => frame[2] === WRITE_UNAVAILABLE_OPCODE)).toBe(false) + }) +}) diff --git a/src/main/runtime/rpc/terminal/terminal-multiplex-output-pause-and-viewport.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-output-pause-and-viewport.test.ts new file mode 100644 index 00000000000..6f2aab60aaa --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-output-pause-and-viewport.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it, vi } from 'vitest' + +import type { RuntimeTerminalDataMeta } from '../../terminal/output/runtime-terminal-stream-consumers' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamText, + encodeTerminalStreamFrame, + encodeTerminalStreamJson +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { + SET_OUTPUT_PAUSED_OPCODE, + startDesktopMultiplexSubscribe +} from './testing/terminal-multiplex-test-harness' + +describe('terminal multiplex RPC', () => { + it('withholds sustained output from multiple paused desktop streams', async () => { + const listeners: ((data: string, meta?: RuntimeTerminalDataMeta) => void)[] = [] + const harness = startDesktopMultiplexSubscribe({ + subscribeToTerminalData: vi.fn((_ptyId, listener) => { + listeners.push(listener) + return vi.fn() + }), + serializeAuthoritativeTerminalBuffer: vi.fn().mockResolvedValue({ + data: 'authoritative hidden snapshot', + cols: 120, + rows: 40, + seq: 7, + source: 'headless' + }) + }) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + + for (const streamId of [1, 2, 3]) { + harness.handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: streamId, + payload: encodeTerminalStreamJson({ + streamId, + terminal: `terminal-${streamId}`, + client: { id: `desktop-${streamId}`, type: 'desktop' }, + capabilities: { ackOutput: 1, outputPause: 1 } + }) + }) + )! + ) + } + await vi.waitFor(() => + expect( + harness.messages.filter((message) => JSON.parse(message).result?.type === 'subscribed') + ).toHaveLength(3) + ) + const pauseCapable = harness.messages + .map((message) => JSON.parse(message).result) + .filter((event) => event?.type === 'subscribed') + .every((event) => event.capabilities?.outputPause === 1) + if (pauseCapable) { + for (const streamId of [1, 2, 3]) { + harness.handlers.get(streamId)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: SET_OUTPUT_PAUSED_OPCODE, + streamId, + seq: 10, + payload: encodeTerminalStreamJson({ paused: true }) + }) + )! + ) + } + } + harness.binaryFrames.splice(0) + const chunk = 'x'.repeat(64 * 1024) + for (let turn = 0; turn < 8; turn += 1) { + for (const listener of listeners) { + listener(chunk, { seq: (turn + 1) * chunk.length, rawLength: chunk.length }) + } + } + expect( + harness.binaryFrames.some( + (bytes) => decodeTerminalStreamFrame(bytes)?.opcode === TerminalStreamOpcode.Output + ) + ).toBe(false) + expect(pauseCapable).toBe(true) + + harness.handlers.get(1)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: SET_OUTPUT_PAUSED_OPCODE, + streamId: 1, + seq: 11, + payload: encodeTerminalStreamJson({ paused: false }) + }) + )! + ) + listeners[0]?.('VISIBLE_MARKER', { seq: 8 * chunk.length + 14, rawLength: 14 }) + listeners[0]?.('y'.repeat(64 * 1024), { + seq: 9 * chunk.length + 14, + rawLength: 64 * 1024 + }) + expect( + harness.binaryFrames + .map(decodeTerminalStreamFrame) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .map((frame) => decodeTerminalStreamText(frame!.payload)) + .join('') + ).toContain('VISIBLE_MARKER') + + harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') + await harness.dispatchPromise + expect(harness.handlers.size).toBe(0) + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex-paused-output-drop.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-paused-output-drop.test.ts similarity index 84% rename from src/main/runtime/rpc/terminal-multiplex-paused-output-drop.test.ts rename to src/main/runtime/rpc/terminal/terminal-multiplex-paused-output-drop.test.ts index d4eeeff208a..fed7dcd34c3 100644 --- a/src/main/runtime/rpc/terminal-multiplex-paused-output-drop.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-paused-output-drop.test.ts @@ -1,18 +1,18 @@ import { describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalDataMeta } from '../terminal/output/runtime-terminal-stream-consumers' +import type { RuntimeTerminalDataMeta } from '../../terminal/output/runtime-terminal-stream-consumers' import { TerminalStreamOpcode, decodeTerminalStreamFrame, decodeTerminalStreamText, encodeTerminalStreamFrame, encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' import { TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES, TERMINAL_STREAM_CHUNK_BYTES -} from '../../../shared/terminal/stream/terminal-multiplex-flow-control' -import { startDesktopMultiplexSubscribe } from './terminal-multiplex-test-harness' -import { RuntimeTerminalViewSubscribers } from '../terminal/view/runtime-terminal-view-subscribers' +} from '../../../../shared/terminal/stream/terminal-multiplex-flow-control' +import { startDesktopMultiplexSubscribe } from './testing/terminal-multiplex-test-harness' +import { RuntimeTerminalViewSubscribers } from '../../terminal/view/runtime-terminal-view-subscribers' async function subscribePausable( capabilities: Record, @@ -150,19 +150,4 @@ describe('terminal multiplex paused-output drop notice', () => { expect(answerYieldedTerminalQueries).not.toHaveBeenCalled() await host.close() }) - - it('leaves a query to the other view that also received it at ingestion', async () => { - const answerYieldedTerminalQueries = vi.fn() - const host = await subscribePausable( - { ackOutput: 1, outputPause: 1, outputPauseDropNotice: 1 }, - answerYieldedTerminalQueries - ) - const releaseOtherView = host.viewSubscribers.registerRemote('pty-1', () => false) - fillAckWindow(host) - host.emitOutput('prompt\x1b[c') - releaseOtherView() - host.setPaused(true) - await host.close() - expect(answerYieldedTerminalQueries).not.toHaveBeenCalled() - }) }) diff --git a/src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts new file mode 100644 index 00000000000..ec5d7f546e8 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it, vi } from 'vitest' +import '../dispatcher' +import '../methods/terminal/terminal' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + encodeTerminalStreamFrame, + encodeTerminalStreamJson +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION } from '../../../../shared/terminal/stream/terminal-multiplex-flow-control' +import { + sendDesktopMultiplexSubscribe, + startDesktopMultiplexSubscribe +} from './testing/terminal-multiplex-test-harness' + +describe('terminal multiplex RPC', () => { + it('cancels a pending desktop PTY wait when its multiplex slot unsubscribes', async () => { + let resolvePty: (ptyId: string) => void = () => {} + let waitSignal: AbortSignal | undefined + const readTerminal = vi.fn().mockResolvedValue({ tail: [], truncated: false }) + const subscribeToTerminalData = vi.fn().mockReturnValue(vi.fn()) + const registerRemoteTerminalViewSubscriber = vi.fn().mockReturnValue(vi.fn()) + const waitForLeafPtyId = vi.fn( + (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => + new Promise((resolve, reject) => { + resolvePty = resolve + waitSignal = signal + signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { + once: true + }) + }) + ) + const harness = startDesktopMultiplexSubscribe({ + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), + waitForLeafPtyId, + readTerminal, + subscribeToTerminalData, + registerRemoteTerminalViewSubscriber + }) + await vi.waitFor(() => + expect(harness.messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + sendDesktopMultiplexSubscribe(harness.handlers) + await vi.waitFor(() => expect(waitForLeafPtyId).toHaveBeenCalled()) + + harness.handlers.get(7)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Unsubscribe, + streamId: 7, + seq: 2, + payload: new Uint8Array() + }) + )! + ) + resolvePty('pty-1') + + await vi.waitFor(() => + expect(waitSignal?.aborted || readTerminal.mock.calls.length > 0).toBe(true) + ) + // Closed panes must not become hidden output consumers when their late PTY appears. + expect(waitSignal?.aborted).toBe(true) + expect(readTerminal).not.toHaveBeenCalled() + expect(subscribeToTerminalData).not.toHaveBeenCalled() + expect(registerRemoteTerminalViewSubscriber).not.toHaveBeenCalled() + expect(harness.handlers.has(7)).toBe(false) + + harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') + await harness.dispatchPromise + }) + + it('admits 128 active streams, rejects the 129th, and reuses released capacity', async () => { + let dataSubscriberCount = 0 + let viewSubscriberCount = 0 + const harness = startDesktopMultiplexSubscribe({ + subscribeToTerminalData: vi.fn(() => { + dataSubscriberCount += 1 + let released = false + return () => { + if (!released) { + released = true + dataSubscriberCount -= 1 + } + } + }), + registerRemoteTerminalViewSubscriber: vi.fn(() => { + viewSubscriberCount += 1 + let released = false + return () => { + if (!released) { + released = true + viewSubscriberCount -= 1 + } + } + }) + }) + await vi.waitFor(() => + expect(harness.messages.some((message) => JSON.parse(message).result?.type === 'ready')).toBe( + true + ) + ) + const sendSubscribe = (streamId: number): void => { + harness.handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: streamId, + payload: encodeTerminalStreamJson({ + streamId, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + } + for ( + let streamId = 1; + streamId <= TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1; + streamId += 1 + ) { + sendSubscribe(streamId) + } + + await vi.waitFor(() => { + const results = harness.messages.map((message) => JSON.parse(message).result) + const subscribedStreamIds = results + .filter((result) => result?.type === 'subscribed') + .map((result) => result.streamId) + expect(subscribedStreamIds).toHaveLength(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) + expect(subscribedStreamIds).toContain(44) + expect(results).toContainEqual({ + type: 'error', + streamId: TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1, + message: 'terminal_stream_limit_exceeded' + }) + expect(results).toContainEqual({ + type: 'end', + streamId: TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1 + }) + }) + expect(dataSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) + expect(viewSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) + + harness.handlers.get(1)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Unsubscribe, + streamId: 1, + seq: TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 2, + payload: new Uint8Array() + }) + )! + ) + await vi.waitFor(() => { + expect(dataSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION - 1) + expect(viewSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION - 1) + expect(harness.handlers.has(1)).toBe(false) + }) + + const retriedStreamId = TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION + 1 + sendSubscribe(retriedStreamId) + await vi.waitFor(() => { + const subscribedStreamIds = harness.messages + .map((message) => JSON.parse(message).result) + .filter((result) => result?.type === 'subscribed') + .map((result) => result.streamId) + expect(subscribedStreamIds).toContain(retriedStreamId) + expect( + harness.binaryFrames.some((bytes) => { + const frame = decodeTerminalStreamFrame(bytes) + return ( + frame?.streamId === retriedStreamId && frame.opcode === TerminalStreamOpcode.SnapshotEnd + ) + }) + ).toBe(true) + }) + expect(dataSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) + expect(viewSubscriberCount).toBe(TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION) + + harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') + await harness.dispatchPromise + expect(dataSubscriberCount).toBe(0) + expect(viewSubscriberCount).toBe(0) + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex-resync-replay-trim.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-resync-replay-trim.test.ts similarity index 95% rename from src/main/runtime/rpc/terminal-multiplex-resync-replay-trim.test.ts rename to src/main/runtime/rpc/terminal/terminal-multiplex-resync-replay-trim.test.ts index 20a5c43a7f3..496b6a0418a 100644 --- a/src/main/runtime/rpc/terminal-multiplex-resync-replay-trim.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-resync-replay-trim.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' +import { RpcDispatcher } from '../dispatcher' +import type { RpcRequest } from '../core' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' import { TerminalStreamOpcode, decodeTerminalStreamFrame, @@ -11,7 +11,7 @@ import { decodeTerminalStreamText, encodeTerminalStreamFrame, encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' // Untagged resync resets live high-water, so trim buffered bytes covered by its seq or render them twice. // Tagged requestId snapshots feed side consumers; live view still needs every buffered chunk. diff --git a/src/main/runtime/rpc/terminal-multiplex-round-robin.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-round-robin.ts similarity index 100% rename from src/main/runtime/rpc/terminal-multiplex-round-robin.ts rename to src/main/runtime/rpc/terminal/terminal-multiplex-round-robin.ts diff --git a/src/main/runtime/rpc/terminal/terminal-multiplex-snapshot-query-replay.test.ts b/src/main/runtime/rpc/terminal/terminal-multiplex-snapshot-query-replay.test.ts new file mode 100644 index 00000000000..1174e28cb77 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-multiplex-snapshot-query-replay.test.ts @@ -0,0 +1,140 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { RuntimeTerminalDataMeta } from '../../terminal/output/runtime-terminal-stream-consumers' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamText, + encodeTerminalStreamFrame, + encodeTerminalStreamJson +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { + sendDesktopMultiplexSubscribe, + startDesktopMultiplexSubscribe +} from './testing/terminal-multiplex-test-harness' +import { TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES } from '../../../../shared/terminal/stream/terminal-multiplex-flow-control' + +afterEach(() => vi.useRealTimers()) + +type ReleaseHeldSnapshot = (extra?: { pendingEscapeTailAnsi?: string }) => void + +async function startSoleQueryOwnerStream() { + let listener: ((data: string, meta?: RuntimeTerminalDataMeta) => void) | undefined + let seq = 0 + let holdNextSnapshot = false + let releaseSnapshot: ReleaseHeldSnapshot | undefined + const answerYieldedTerminalQueries = vi.fn() + const harness = startDesktopMultiplexSubscribe({ + isSoleRemoteTerminalQueryOwner: () => true, + answerYieldedTerminalQueries, + serializeTerminalBuffer: vi.fn(async () => { + if (!holdNextSnapshot) { + return { data: '', cols: 80, rows: 24, seq } + } + holdNextSnapshot = false + return new Promise<{ + data: string + cols: number + rows: number + seq: number + pendingEscapeTailAnsi?: string + }>((resolve) => { + releaseSnapshot = (extra) => resolve({ data: '', cols: 80, rows: 24, seq, ...extra }) + }) + }), + subscribeToTerminalData: vi.fn((_ptyId, onData) => { + listener = onData + return vi.fn() + }) + }) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + return { + answerYieldedTerminalQueries, + holdNextSnapshot: (): void => { + holdNextSnapshot = true + }, + held: async (): Promise => { + await vi.waitFor(() => expect(releaseSnapshot).toBeDefined()) + const release = releaseSnapshot! + releaseSnapshot = undefined + return release + }, + subscribe: async (): Promise => { + sendDesktopMultiplexSubscribe(harness.handlers) + await vi.waitFor(() => expect(listener).toBeDefined()) + }, + waitSubscribed: () => + vi.waitFor(() => + expect( + harness.messages.some((message) => JSON.parse(message).result?.type === 'subscribed') + ).toBe(true) + ), + send: (opcode: TerminalStreamOpcode, payload: Record): void => { + harness.handlers.get(7)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode, + streamId: 7, + seq: 2, + payload: encodeTerminalStreamJson(payload) + }) + )! + ) + }, + emit: async (data: string, { holdInBatcher = false } = {}): Promise => { + seq += data.length + listener?.(data, { seq, rawLength: data.length }) + if (!holdInBatcher) { + await vi.runOnlyPendingTimersAsync() + } + }, + currentSeq: (): number => seq, + snapshotEndCount: (): number => + harness.binaryFrames + .map(decodeTerminalStreamFrame) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd).length, + /** `viewerCutoffSeq` mirrors the viewer dropping seq'd output its recovery snapshot covers. */ + outputAfterLastSnapshot: (viewerCutoffSeq = 0): string => { + const frames = harness.binaryFrames.map(decodeTerminalStreamFrame) + const snapshotEnd = frames.findLastIndex( + (frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd + ) + return frames + .slice(snapshotEnd + 1) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .filter((frame) => !frame?.seq || frame.seq > viewerCutoffSeq) + .map((frame) => frame && decodeTerminalStreamText(frame.payload)) + .join('') + }, + cleanup: async (): Promise => { + harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') + await harness.dispatchPromise + } + } +} + +it('drops a superseded snapshot replay and its escape tail queued behind the ACK window', async () => { + vi.useFakeTimers() + const stream = await startSoleQueryOwnerStream() + try { + await stream.subscribe() + await stream.waitSubscribed() + await stream.emit('x'.repeat(TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES)) + stream.holdNextSnapshot() + stream.send(TerminalStreamOpcode.SnapshotRequest, {}) + const release = await stream.held() + await stream.emit('\x1b[c\x1b[31') + release({ pendingEscapeTailAnsi: '\x1b[31' }) + await vi.runOnlyPendingTimersAsync() + stream.send(TerminalStreamOpcode.SnapshotRequest, {}) + await vi.runOnlyPendingTimersAsync() + stream.send(TerminalStreamOpcode.Ack, { + bytes: TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES + }) + await vi.runOnlyPendingTimersAsync() + + expect(stream.outputAfterLastSnapshot()).toBe('\x1b[c') + expect(stream.answerYieldedTerminalQueries).not.toHaveBeenCalled() + } finally { + await stream.cleanup() + } +}) diff --git a/src/main/runtime/rpc/terminal/terminal-output-frame-chunks.test.ts b/src/main/runtime/rpc/terminal/terminal-output-frame-chunks.test.ts new file mode 100644 index 00000000000..c86981dba80 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-output-frame-chunks.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { TERMINAL_STREAM_CHUNK_BYTES } from '../../../../shared/terminal/stream/terminal-multiplex-flow-control' +import { + iterateTerminalOutputFrameChunks, + type TerminalOutputMeta +} from './terminal-output-frame-chunks' + +const SURROGATE_PAIR = '\u{1f600}' +const LONE_HIGH = '\ud83d' + +function seqPreservingMeta(data: string, seq: number): TerminalOutputMeta { + return { seq, rawLength: data.length } +} + +describe('terminal output frame chunks', () => { + it('keeps every emitted frame within the wire cap and reassembles to the input', () => { + const data = `${'a'.repeat(TERMINAL_STREAM_CHUNK_BYTES - 3)}${SURROGATE_PAIR}${'a'.repeat(200 * 1024)}${SURROGATE_PAIR.repeat(4096)}${LONE_HIGH}` + const frames = [ + ...iterateTerminalOutputFrameChunks(data, seqPreservingMeta(data, 999_999), 'span') + ] + expect(frames.length).toBeGreaterThan(4) + for (const frame of frames) { + expect(frame.bytes.byteLength).toBeLessThanOrEqual(TERMINAL_STREAM_CHUNK_BYTES) + } + expect(Buffer.concat(frames.map((frame) => Buffer.from(frame.bytes))).toString('utf8')).toBe( + Buffer.from(new TextEncoder().encode(data)).toString('utf8') + ) + // Seqs must be strictly increasing and end at the meta high-water mark. + const seqs = frames.map((frame) => frame.seq!) + expect(seqs.every((seq, index) => index === 0 || seq > seqs[index - 1]!)).toBe(true) + expect(seqs.at(-1)).toBe(999_999) + }) +}) diff --git a/src/main/runtime/rpc/terminal-output-frame-chunks.ts b/src/main/runtime/rpc/terminal/terminal-output-frame-chunks.ts similarity index 96% rename from src/main/runtime/rpc/terminal-output-frame-chunks.ts rename to src/main/runtime/rpc/terminal/terminal-output-frame-chunks.ts index ae03555d736..c6dd507f91a 100644 --- a/src/main/runtime/rpc/terminal-output-frame-chunks.ts +++ b/src/main/runtime/rpc/terminal/terminal-output-frame-chunks.ts @@ -2,8 +2,8 @@ import { TerminalStreamOpcode, encodeTerminalStreamJson, encodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import { TERMINAL_STREAM_CHUNK_BYTES } from '../../../shared/terminal/stream/terminal-multiplex-flow-control' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { TERMINAL_STREAM_CHUNK_BYTES } from '../../../../shared/terminal/stream/terminal-multiplex-flow-control' import { terminalStreamByteLength } from './terminal-stream-byte-length' export type TerminalOutputMeta = { diff --git a/src/main/runtime/rpc/terminal/terminal-prompt-delivery-receipt.test.ts b/src/main/runtime/rpc/terminal/terminal-prompt-delivery-receipt.test.ts new file mode 100644 index 00000000000..d01addb52d2 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-prompt-delivery-receipt.test.ts @@ -0,0 +1,178 @@ +import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' +import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import { createAgentPromptSubmissionRuntime } from '../../terminal/input/agent-prompt-submission-runtime-test-fixture' +import { OrchestrationDb } from '../../orchestration/db/orchestration-db' +import '../../orchestration/db/contract-constants' +import '../../orchestration/db/messages/mailbox-routing-page' +import '../../orchestration/db/dispatch-row-writer' +import '../../orchestration/db/attempt-outcome-projection' +import type { RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' + +vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktrees: facade.listWorktrees + } +}) + +vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktreesStrict: facade.listWorktreesStrict + } +}) + +const { getWorktreeListingMocks } = vi.hoisted(() => { + const createWorktreeListingMocks = () => ({ + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/prompt-receipt', + isBare: false, + isMainWorktree: false + } + ]), + listWorktreesStrict: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/prompt-receipt', + isBare: false, + isMainWorktree: false + } + ]) + }) + let listings: ReturnType | undefined + return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } +}) + +function request( + terminal: string, + promptRequestId: string, + text: string, + waitSubmitMs?: number +): RpcRequest { + return { + id: `rpc-${promptRequestId}`, + authToken: 'token', + method: 'terminal.send', + orchestrationRequestId: promptRequestId, + params: { + terminal, + text, + enter: true, + agentPrompt: true, + waitSubmitMs, + client: { id: 'orca-cli', type: 'desktop' } + } + } +} + +async function createHarness(agent: TuiAgent, busy = false) { + const created = await createAgentPromptSubmissionRuntime(() => undefined, agent) + created.runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'unused' }), + write: (_ptyId, data) => { + created.writes.push(data) + return true + }, + kill: () => true, + getForegroundProcess: async () => agent + }) + const db = new OrchestrationDb(':memory:') + created.runtime.setOrchestrationDb(db) + if (busy) { + created.runtime.onPtyData( + 'pty-prompt', + `\x1b]9999;{"state":"working","agentType":"${agent}"}\x07`, + Date.now() + ) + } + return { + ...created, + db, + dispatcher: new RpcDispatcher({ runtime: created.runtime, methods: TERMINAL_METHODS }) + } +} + +describe('durable terminal prompt delivery receipts', () => { + afterEach(() => vi.useRealTimers()) + + it('keeps an ambiguous partial write pending and refuses to resend it', async () => { + vi.useFakeTimers() + const harness = await createHarness('aider') + harness.runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'unused' }), + write: (_ptyId, data) => { + harness.writes.push(data) + return data !== '\r' + }, + kill: () => true, + getForegroundProcess: async () => 'aider' + }) + const firstPromise = harness.dispatcher.dispatch( + request(harness.handle, 'partial-retry', 'partial once') + ) + await vi.runAllTimersAsync() + const first = await firstPromise + const writesAfterFailure = [...harness.writes] + const retry = await harness.dispatcher.dispatch( + request(harness.handle, 'partial-retry', 'partial once') + ) + + expect(first).toMatchObject({ ok: false }) + expect(retry).toMatchObject({ ok: false, error: { code: 'operation_unknown' } }) + expect(harness.writes).toEqual(writesAfterFailure) + harness.db.close() + }) + + it('does not let a later queued request claim an earlier lifecycle transition', async () => { + vi.useFakeTimers() + const harness = await createHarness('codex', true) + const firstPromise = harness.dispatcher.dispatch( + request(harness.handle, 'ordered-first', 'first prompt') + ) + await vi.runAllTimersAsync() + await firstPromise + const secondPromise = harness.dispatcher.dispatch( + request(harness.handle, 'ordered-second', 'second prompt') + ) + await vi.runAllTimersAsync() + await secondPromise + + harness.runtime.onPtyData( + 'pty-prompt', + '\x1b]9999;{"state":"done","agentType":"codex"}\x07' + + '\x1b]9999;{"state":"working","agentType":"codex"}\x07', + Date.now() + ) + + const secondObserved = harness.dispatcher.dispatch( + request(harness.handle, 'ordered-second', 'second prompt', 1_000) + ) + await vi.runAllTimersAsync() + const firstObserved = harness.dispatcher.dispatch( + request(harness.handle, 'ordered-first', 'first prompt', 1_000) + ) + await vi.runAllTimersAsync() + + await expect(secondObserved).resolves.toMatchObject({ + ok: true, + result: { send: { prompt: { stages: ['input_accepted'] } } } + }) + await expect(firstObserved).resolves.toMatchObject({ + ok: true, + result: { + send: { prompt: { stages: ['input_accepted', 'turn_started'] } } + } + }) + harness.db.close() + }) +}) diff --git a/src/main/runtime/rpc/terminal/terminal-send-launch-composer.test.ts b/src/main/runtime/rpc/terminal/terminal-send-launch-composer.test.ts new file mode 100644 index 00000000000..65b200707a2 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-send-launch-composer.test.ts @@ -0,0 +1,158 @@ +import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' +import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { settledWriteStub } from '../../../providers/testing/settled-pty-write-stub' +import { OrcaRuntimeService } from '../../orca-runtime' +import { makeStore } from '../server/runtime-rpc-worktree-store-fixtures' +import { AGENT_PROMPT_TEST_WORKTREE_PATH } from '../../terminal/input/agent-prompt-submission-runtime-test-fixture' +import { RpcDispatcher } from '../dispatcher' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' + +vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktrees: facade.listWorktrees + } +}) + +vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { + const facade = getWorktreeListingMocks() + return { + ...(await importOriginal()), + listWorktreesStrict: facade.listWorktreesStrict + } +}) + +const { getWorktreeListingMocks } = vi.hoisted(() => { + const createWorktreeListingMocks = () => ({ + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/launch-composer', + isBare: false, + isMainWorktree: false + } + ]), + listWorktreesStrict: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/launch-composer', + isBare: false, + isMainWorktree: false + } + ]) + }) + let listings: ReturnType | undefined + return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } +}) + +// Claude's palette-report anchor, then its composer prompt row (draft-paste-ready-scanner.ts). +const CLAUDE_COMPOSER_READY_OUTPUT = '\x1b[?2031h\x1b[?2004h❯\u00a0' +const PTY_ID = 'pty-claude' + +async function launchClaude(command: string | undefined, ordered = false) { + const runtime = new OrcaRuntimeService( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: partial store double; terminal create and send read only its repo and worktree members. + makeStore() as never + ) + const writes: string[] = [] + const write = (_ptyId: string, data: string) => { + writes.push(data) + return true + } + runtime.setPtyController({ + spawn: async () => ({ id: PTY_ID }), + write, + writeWithSettlement: settledWriteStub(write), + kill: () => true, + getForegroundProcess: async () => 'claude' + }) + const { handle } = await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, { + launchAgent: 'claude', + ...(command ? { command } : {}) + }) + vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent') + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const mobile = { + caller: { kind: 'paired-device', deviceId: 'device' }, + clientId: 'phone' + } as const + const client = { id: 'phone', type: 'mobile' } as const + let inputSessionId: string | undefined + let seq = 0 + if (ordered) { + await runtime.handleMobileSubscribe(PTY_ID, 'phone', undefined) + const opened = await dispatcher.dispatch( + { + id: 'open', + authToken: 'token', + method: 'terminal.openInputSession', + params: { terminal: handle, client } + }, + mobile + ) + if (!opened.ok) { + throw new Error(opened.error.message) + } + inputSessionId = z.object({ inputSessionId: z.string() }).parse(opened.result).inputSessionId + } + const send = (text: string, signal?: AbortSignal) => + dispatcher.dispatch( + { + id: 'rpc-send', + authToken: 'token', + method: 'terminal.send', + params: { + terminal: handle, + text, + enter: true, + ...(inputSessionId + ? { client, inputSequence: { sessionId: inputSessionId, seq: ++seq } } + : {}) + } + }, + { ...(ordered ? mobile : {}), ...(signal ? { signal } : {}) } + ) + return { runtime, writes, send } +} + +const PASTE = '\x1b[200~/review\nthis\x1b[201~' + +describe('terminal.send into a freshly launched Claude', () => { + afterEach(() => vi.useRealTimers()) + + it('holds the entire ordered suffix behind the fresh composer and the first submit', async () => { + vi.useFakeTimers() + const { runtime, writes, send } = await launchClaude('claude', true) + const first = send(PASTE) + const second = send('next') + await vi.advanceTimersByTimeAsync(3_000) + expect(writes).toEqual([]) + runtime.onPtyData(PTY_ID, CLAUDE_COMPOSER_READY_OUTPUT, Date.now()) + await vi.runAllTimersAsync() + await expect(Promise.all([first, second])).resolves.toEqual([ + expect.objectContaining({ result: { send: expect.objectContaining({ accepted: true }) } }), + expect.objectContaining({ result: { send: expect.objectContaining({ accepted: true }) } }) + ]) + expect(writes).toEqual([PASTE, '\r', 'next', '\r']) + }) + + it('writes nothing for a held send whose request was cancelled', async () => { + vi.useFakeTimers() + const { runtime, writes, send } = await launchClaude('claude') + const request = new AbortController() + + const sending = send(PASTE, request.signal) + await vi.advanceTimersByTimeAsync(1_000) + request.abort() + runtime.onPtyData(PTY_ID, CLAUDE_COMPOSER_READY_OUTPUT, Date.now()) + await vi.runAllTimersAsync() + + await sending + expect(writes).toEqual([]) + }) +}) diff --git a/src/main/runtime/rpc/terminal/terminal-send-ordered-input.test.ts b/src/main/runtime/rpc/terminal/terminal-send-ordered-input.test.ts new file mode 100644 index 00000000000..9aa5cbbb245 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-send-ordered-input.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { RpcDispatchStreamingOptions } from '../dispatch/dispatcher-stream-options' +import { z } from 'zod' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { RuntimeTerminalSend } from '../../../../shared/runtime-terminal-send-contract' + +const mobile = { clientId: 'phone', caller: { kind: 'paired-device', deviceId: 'device' } } as const +const client = { id: 'phone', type: 'mobile' } as const + +function fixture() { + let binding = { ptyId: 'pty', processIncarnation: 'process', generation: 1 } + const writes: string[] = [] + let release = (): void => {} + let outcome: 'accepted' | 'refused' | 'unverifiable' = 'accepted' + const sendTerminal: OrcaRuntimeService['sendTerminal'] = vi.fn(async (handle, input, options) => { + await options?.beforeWrite?.('pty') + if (input.text === 'held') { + await new Promise((resolve) => { + release = resolve + }) + } + await options?.beforeWrite?.('pty') + if (outcome === 'refused') { + return { handle, accepted: false, bytesWritten: 0 } + } + writes.push(input.text ?? '') + const send: RuntimeTerminalSend = { + handle, + accepted: true, + bytesWritten: input.text?.length ?? 0, + writeSettlement: + outcome === 'accepted' + ? { outcome: 'accepted' } + : { outcome: 'unverifiable', reason: 'settlement_timeout', bytesHandedToTransport: true } + } + return send + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this dispatcher fixture implements the runtime members read by terminal.send and openInputSession. + const runtime = { + getRuntimeId: () => 'runtime', + getTerminalPromptRequestBinding: () => binding, + resolveLiveLeafForHandle: () => ({ ptyId: binding.ptyId }), + getDriver: () => null, + ensureStructuredAgentSessionHost: async () => null, + sendTerminal, + beginMobileInputFloor: () => ({ commit: async () => {}, rollback: () => {} }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + let id = 0 + const call = (method: string, params: unknown, options: RpcDispatchStreamingOptions = mobile) => + dispatcher.dispatch({ id: String(++id), authToken: 'test', method, params }, options) + const open = async () => { + const response = await call('terminal.openInputSession', { terminal: 'term', client }) + if (!response.ok) { + throw new Error(response.error.message) + } + const parsed = z.object({ inputSessionId: z.string().nullable() }).parse(response.result) + return parsed.inputSessionId + } + const send = ( + sessionId: string, + seq: number, + text: string, + options: RpcDispatchStreamingOptions = mobile + ) => + call( + 'terminal.send', + { terminal: 'term', client, text, inputSequence: { sessionId, seq } }, + options + ) + return { + call, + open, + send, + sendTerminal, + writes, + release: () => release(), + replace: () => { + binding = { ...binding, generation: 2 } + }, + outcome: (value: typeof outcome) => { + outcome = value + } + } +} + +describe('ordered terminal input RPC', () => { + it('serializes the complete send, deduplicates matching payloads, and pins the token while a predecessor is busy', async () => { + const f = fixture() + const token = (await f.open())! + const first = f.send(token, 1, 'held') + await vi.waitFor(() => expect(f.sendTerminal).toHaveBeenCalledTimes(1)) + const second = f.send(token, 2, 'next') + const duplicate = f.send(token, 1, 'held') + expect(await f.open()).toBeNull() + await f.call('terminal.send', { terminal: 'term', text: 'bypass', client }) + expect(f.sendTerminal).toHaveBeenCalledTimes(1) + f.release() + await expect(Promise.all([first, second, duplicate])).resolves.toEqual( + expect.arrayContaining([ + expect.objectContaining({ + ok: true, + result: expect.objectContaining({ send: expect.objectContaining({ accepted: true }) }) + }) + ]) + ) + expect(f.writes).toEqual(['held', 'next']) + expect(f.sendTerminal).toHaveBeenLastCalledWith( + 'term', + expect.anything(), + expect.objectContaining({ inputSource: 'mobile', requireWriteSettlement: true }) + ) + }) +}) diff --git a/src/main/runtime/rpc/terminal/terminal-stream-byte-length.test.ts b/src/main/runtime/rpc/terminal/terminal-stream-byte-length.test.ts new file mode 100644 index 00000000000..4f012be52f5 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-stream-byte-length.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { + measureTerminalStreamByteLength, + terminalStreamByteLength, + terminalStreamByteLengthExceeds +} from './terminal-stream-byte-length' + +describe('measuring a prefix slice that cuts a surrogate pair in half', () => { + // Kept first in the file so the scan is still specializing on this shape when it tiers up. + it('measures the slice like the encoder does in every JIT tier', () => { + const sliced = 'abcdefghijkl\u{1f600}'.slice(0, 13) + expect(sliced.length).toBe(13) + expect(sliced.charCodeAt(12)).toBe(0xd83d) + // 12 ASCII bytes plus U+FFFD for the orphaned high surrogate. + expect(Buffer.byteLength(sliced, 'utf8')).toBe(15) + + const observedByteLengths = new Set() + const observedExceeded = new Set() + const observedMeasurements = new Set() + for (let iteration = 0; iteration < 200_000; iteration += 1) { + observedByteLengths.add(terminalStreamByteLength(sliced)) + observedExceeded.add(terminalStreamByteLengthExceeds(sliced, 15)) + observedMeasurements.add( + JSON.stringify(measureTerminalStreamByteLength(sliced, { stopAfterBytes: 15 })) + ) + } + expect([...observedByteLengths]).toEqual([15]) + expect([...observedExceeded]).toEqual([false]) + expect([...observedMeasurements]).toEqual([ + JSON.stringify({ byteLength: 15, exceededLimit: false }) + ]) + }) +}) diff --git a/src/main/runtime/rpc/terminal-stream-byte-length.ts b/src/main/runtime/rpc/terminal/terminal-stream-byte-length.ts similarity index 96% rename from src/main/runtime/rpc/terminal-stream-byte-length.ts rename to src/main/runtime/rpc/terminal/terminal-stream-byte-length.ts index 603940fab4b..9901193716e 100644 --- a/src/main/runtime/rpc/terminal-stream-byte-length.ts +++ b/src/main/runtime/rpc/terminal/terminal-stream-byte-length.ts @@ -1,4 +1,4 @@ -import { measureUtf8ByteLength } from '../../../shared/utf8-byte-limits' +import { measureUtf8ByteLength } from '../../../../shared/utf8-byte-limits' export type TerminalStreamByteLengthMeasurement = { byteLength: number diff --git a/src/main/runtime/rpc/terminal/terminal-subscribe-admission.test.ts b/src/main/runtime/rpc/terminal/terminal-subscribe-admission.test.ts new file mode 100644 index 00000000000..597a6384986 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-subscribe-admission.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import '../../../../shared/rpc-contract/terminal/terminal-viewport-schemas-params' + +const PTY_ID = 'pty-1' +const SUBSCRIPTION_ID = 'terminal-1:phone-1' + +const binaryParams = { + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' }, + viewport: { cols: 40, rows: 20 }, + capabilities: { terminalBinaryStream: 1 } +} + +let nextRequestId = 0 +const subscribeRequest = (params: unknown): RpcRequest => ({ + id: `req-${++nextRequestId}`, + authToken: 'tok', + method: 'terminal.subscribe', + params +}) + +/** What a phone that addresses its request sends; the slot fields stay for older hosts. */ +const phoneUnsubscribeParams = (requestId: string) => ({ + subscriptionId: SUBSCRIPTION_ID, + client: { id: 'phone-1' }, + requestId +}) +const requestUnsubscribe = (requestId: string): RpcRequest => ({ + id: `req-${++nextRequestId}`, + authToken: 'tok', + method: 'terminal.unsubscribe', + params: phoneUnsubscribeParams(requestId) +}) + +const phoneConnection = (connectionId: string, signal?: AbortSignal) => ({ + connectionId, + signal, + sendBinary: vi.fn(), + registerBinaryStreamHandler: vi.fn(() => vi.fn()) +}) + +const resultTypes = (messages: string[]): unknown[] => + messages.map((message) => JSON.parse(message).result?.type) + +/** Resolves pending `waitForLeafPtyId` calls on demand and rejects them when their signal aborts, like the runtime. */ +function createPtyWaits() { + const waits: { resolve: (ptyId: string) => void }[] = [] + return { + waits, + waitForLeafPtyId: vi.fn( + (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => + new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error('request_aborted')) + return + } + signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { + once: true + }) + waits.push({ resolve }) + }) + ), + spawn: () => { + for (const wait of waits.splice(0)) { + wait.resolve(PTY_ID) + } + } + } +} + +/** The real runtime, with only handle resolution, the pty wait, the scrollback read and tab mounting doubled. */ +function createRealRuntime() { + const runtime = new OrcaRuntimeService() + const sizes = new Map([[PTY_ID, { cols: 120, rows: 40 }]]) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + resize: (ptyId, cols, rows) => { + sizes.set(ptyId, { cols, rows }) + return true + }, + getSize: (ptyId) => sizes.get(ptyId) ?? null + }) + const ptyWaits = createPtyWaits() + let ptyReady = false + vi.spyOn(runtime, 'resolveLeafForHandle').mockImplementation(() => ({ + ptyId: ptyReady ? PTY_ID : null + })) + vi.spyOn(runtime, 'waitForLeafPtyId').mockImplementation(ptyWaits.waitForLeafPtyId) + vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ + handle: 'terminal-1', + status: 'running', + tail: [], + truncated: false, + nextCursor: null + }) + vi.spyOn(runtime, 'requestRendererTerminalTabMount').mockReturnValue(false) + const spawn = (): void => { + ptyReady = true + ptyWaits.spawn() + } + return { runtime, ptyWaits, spawn, sizes } +} + +describe('terminal.subscribe registers at admission', () => { + it('leaves the desktop driver idle when the phone leaves during the phone-fit layout', async () => { + const { runtime, sizes } = createRealRuntime() + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + let leaveDuringLayout = true + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + resize: (ptyId, cols, rows) => { + sizes.set(ptyId, { cols, rows }) + // The phone's unsubscribe lands while handleMobileSubscribe awaits its layout. + if (leaveDuringLayout) { + leaveDuringLayout = false + runtime.cleanupSubscriptionIfOwnedByConnection(SUBSCRIPTION_ID, 'conn-a') + } + return true + }, + getSize: (ptyId) => sizes.get(ptyId) ?? null + }) + vi.spyOn(runtime, 'resolveLeafForHandle').mockReturnValue({ ptyId: PTY_ID }) + const messages: string[] = [] + + const subscribe = dispatcher.dispatchStreaming( + subscribeRequest(binaryParams), + (message) => messages.push(message), + phoneConnection('conn-a') + ) + await vi.waitFor(() => expect(leaveDuringLayout).toBe(false)) + await subscribe + + await vi.waitFor(() => expect(runtime.getDriver(PTY_ID).kind).toBe('idle'), { + timeout: 2_000 + }) + expect(resultTypes(messages)).toEqual(['end']) + }) +}) + +describe('terminal.unsubscribe addressed by request', () => { + it('heals a half-open socket: the replay on a new socket is what the leave ends', async () => { + const { runtime, spawn } = createRealRuntime() + spawn() + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + // Replay after a reconnect resends the same request id on the new socket. + const replayed = subscribeRequest(binaryParams) + const halfOpenMessages: string[] = [] + const halfOpen = dispatcher.dispatchStreaming( + replayed, + (message) => halfOpenMessages.push(message), + phoneConnection('conn-1') + ) + await vi.waitFor(() => expect(runtime.getDriver(PTY_ID).kind).toBe('mobile')) + const replay = dispatcher.dispatchStreaming(replayed, vi.fn(), phoneConnection('conn-2')) + await halfOpen + expect(resultTypes(halfOpenMessages).at(-1)).toBe('end') + + await dispatcher.dispatchStreaming(requestUnsubscribe(replayed.id), vi.fn(), { + connectionId: 'conn-2' + }) + await replay + + await vi.waitFor(() => expect(runtime.getDriver(PTY_ID).kind).toBe('idle'), { + timeout: 2_000 + }) + // The half-open socket's eventual close finds nothing of its own left. + runtime.cleanupSubscriptionsForConnection('conn-1') + expect(runtime.getDriver(PTY_ID).kind).toBe('idle') + }) +}) diff --git a/src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts b/src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts new file mode 100644 index 00000000000..a7e51b90e1e --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts @@ -0,0 +1,277 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { RpcRequest } from '../core' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import { createSubscriptionRegistryDouble } from '../testing/subscription-registry-test-double' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamJson, + decodeTerminalStreamText +} from '../../../../shared/terminal/stream/terminal-stream-protocol' + +function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { + const registry = createSubscriptionRegistryDouble() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This partial runtime supplies the terminal RPC methods these tests invoke. + return { + getRuntimeId: () => 'test-runtime', + registerOwnedSubscriptionCleanup: registry.registerOwnedSubscriptionCleanup, + subscribeToPtyExit: vi.fn(() => vi.fn()), + // View registration suppresses competing model query replies (terminal-query-authority.md). + registerRemoteTerminalViewSubscriber: () => () => {}, + requestRendererTerminalTabMount: () => false, + ...overrides + } as OrcaRuntimeService +} + +const makeRequest = (method: string, params?: unknown): RpcRequest => ({ + id: 'req-1', + authToken: 'tok', + method, + params +}) + +describe('terminal subscribe buffering', () => { + it('captures live queries before awaiting mobile fit and delivers them after the snapshot', async () => { + const binaryFrames: Uint8Array[] = [] + const registry = createSubscriptionRegistryDouble() + let dataListener: + | ((data: string, meta?: { seq?: number; rawLength?: number }) => void) + | undefined + let resolveMobileSubscribe: () => void = () => {} + const registerRemoteTerminalViewSubscriber = vi.fn(() => vi.fn()) + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + handleMobileSubscribe: vi.fn( + () => + new Promise((resolve) => { + resolveMobileSubscribe = () => resolve(true) + }) + ), + handleMobileUnsubscribe: vi.fn(), + subscribeToTerminalData: vi.fn((_ptyId, listener) => { + dataListener = listener + return vi.fn() + }), + registerRemoteTerminalViewSubscriber, + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi + .fn() + .mockResolvedValue({ data: 'snapshot', cols: 80, rows: 24, seq: 4 }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + isTerminalAlternateScreen: vi.fn().mockReturnValue(false), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), + registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), + cleanupSubscription: vi.fn(registry.cleanupSubscription), + waitForTerminal: vi.fn(() => new Promise(() => {})) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.subscribe', { + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' }, + capabilities: { terminalBinaryStream: 1 } + }), + vi.fn(), + { + connectionId: 'conn-phone', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: vi.fn(() => vi.fn()) + } + ) + + await vi.waitFor(() => expect(runtime.handleMobileSubscribe).toHaveBeenCalled()) + expect(dataListener).toBeDefined() + expect(registerRemoteTerminalViewSubscriber).toHaveBeenCalledWith( + 'pty-1', + undefined, + 'phone-1', + false, + undefined + ) + dataListener?.('\x1b[6n', { seq: 4, rawLength: 4 }) + resolveMobileSubscribe() + + await vi.waitFor(() => + expect( + binaryFrames.some((bytes) => { + const frame = decodeTerminalStreamFrame(bytes) + return ( + frame?.opcode === TerminalStreamOpcode.Output && + decodeTerminalStreamText(frame.payload) === '\x1b[6n' + ) + }) + ).toBe(true) + ) + const queryOutputFrames = binaryFrames.filter((bytes) => { + const frame = decodeTerminalStreamFrame(bytes) + return ( + frame?.opcode === TerminalStreamOpcode.Output && + decodeTerminalStreamText(frame.payload) === '\x1b[6n' + ) + }) + expect(queryOutputFrames).toHaveLength(1) + + runtime.cleanupSubscription('terminal-1:phone-1') + await dispatchPromise + }) + + it('drops stale mobile resize re-stream completions for legacy binary streams', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const registry = createSubscriptionRegistryDouble() + let resizeListener: + | ((event: { + cols: number + rows: number + displayMode: string + reason: string + seq: number + }) => void) + | undefined + const restreamResolves: ((value: { + data: string + cols: number + rows: number + oscLinks?: { + row: number + startCol: number + endCol: number + uri: string + }[] + terminalOwner?: 'shell' + }) => void)[] = [] + const serializeTerminalBuffer = vi + .fn() + .mockResolvedValueOnce({ data: 'initial', cols: 80, rows: 24 }) + .mockImplementation( + () => + new Promise<{ + data: string + cols: number + rows: number + oscLinks?: { + row: number + startCol: number + endCol: number + uri: string + }[] + terminalOwner?: 'shell' + }>((resolve) => { + restreamResolves.push(resolve) + }) + ) + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer, + getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + isTerminalAlternateScreen: vi.fn().mockReturnValue(false), + handleMobileSubscribe: vi.fn().mockResolvedValue(undefined), + handleMobileUnsubscribe: vi.fn(), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + subscribeToTerminalResize: vi.fn((_, listener) => { + resizeListener = listener as typeof resizeListener + return vi.fn() + }), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), + registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), + cleanupSubscription: vi.fn(registry.cleanupSubscription), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true }) + }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.subscribe', { + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' }, + capabilities: { terminalBinaryStream: 1 } + }), + (msg) => messages.push(msg), + { + connectionId: 'conn-stale-resize', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } + } + ) + + await vi.waitFor(() => expect(resizeListener).toBeDefined()) + binaryFrames.splice(0) + + resizeListener?.({ + cols: 90, + rows: 24, + displayMode: 'auto', + reason: 'apply-layout', + seq: 2 + }) + resizeListener?.({ + cols: 100, + rows: 24, + displayMode: 'auto', + reason: 'apply-layout', + seq: 3 + }) + await vi.waitFor(() => expect(restreamResolves).toHaveLength(2)) + + const newerOscLinks = [{ row: 0, startCol: 4, endCol: 9, uri: 'https://example.com' }] + restreamResolves[1]?.({ + data: 'newer', + cols: 100, + rows: 24, + oscLinks: newerOscLinks, + terminalOwner: 'shell' + }) + await vi.waitFor(() => + expect( + binaryFrames.some((frame) => { + const decoded = decodeTerminalStreamFrame(frame) + return ( + decoded?.opcode === TerminalStreamOpcode.SnapshotChunk && + decodeTerminalStreamText(decoded.payload) === 'newer' + ) + }) + ).toBe(true) + ) + restreamResolves[0]?.({ data: 'older', cols: 90, rows: 24 }) + await Promise.resolve() + await Promise.resolve() + + const snapshotData = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + expect(snapshotData).toEqual(['newer']) + const snapshotStart = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart) + expect(snapshotStart && decodeTerminalStreamJson(snapshotStart.payload)).toMatchObject({ + kind: 'resized', + oscLinks: newerOscLinks + }) + expect(snapshotStart && decodeTerminalStreamJson(snapshotStart.payload)).not.toHaveProperty( + 'terminalOwner' + ) + + runtime.cleanupSubscription('terminal-1:phone-1') + await dispatchPromise + }) +}) diff --git a/src/main/runtime/rpc/terminal-subscribe-mounted-pane.test.ts b/src/main/runtime/rpc/terminal/terminal-subscribe-mounted-pane.test.ts similarity index 81% rename from src/main/runtime/rpc/terminal-subscribe-mounted-pane.test.ts rename to src/main/runtime/rpc/terminal/terminal-subscribe-mounted-pane.test.ts index 4309a5a3fb4..c1261653818 100644 --- a/src/main/runtime/rpc/terminal-subscribe-mounted-pane.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-subscribe-mounted-pane.test.ts @@ -1,15 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' import { TerminalStreamOpcode, decodeTerminalStreamFrame, decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import { createSubscriptionRegistryDouble } from '../testing/subscription-registry-test-double' const request: RpcRequest = { id: 'req-1', @@ -173,29 +173,4 @@ describe('terminal subscribe for a pane the desktop already has mounted', () => expect(subscription.outputText()).toBe('z') await subscription.close() }) - - it('falls back to the mount wait within one serialize when the flag outlives its pane', async () => { - // Closed tabs leave stale mounted flags; null IPC replies wait 750ms while busy output can invalidate every renderer attempt. - let sequence = 4 - const subscription = subscribeMobile({ - rendererScreen: () => null, - rendererAnswerDelayMs: 750, - outputSequence: () => (sequence += 1), - waitForRendererTerminalSerializer: (_ptyId, _after, _timeout, signal) => - new Promise((resolve) => { - signal?.addEventListener('abort', () => resolve(false), { once: true }) - }) - }) - - await vi.advanceTimersByTimeAsync(750) - expect(subscription.runtime.requestRendererTerminalTabMount).toHaveBeenCalledWith('terminal-1') - await vi.advanceTimersByTimeAsync(2_999) - expect(subscription.snapshotText()).toBe('') - - // Worst case: one serialize plus the 3 s mount deadline. - await vi.advanceTimersByTimeAsync(1) - expect(subscription.snapshotText()).toContain('restored provider history') - expect(subscription.runtime.serializeRendererTerminalBuffer).toHaveBeenCalledTimes(1) - await subscription.close() - }) }) diff --git a/src/main/runtime/rpc/terminal-subscribe-output-credit.test.ts b/src/main/runtime/rpc/terminal/terminal-subscribe-output-credit.test.ts similarity index 81% rename from src/main/runtime/rpc/terminal-subscribe-output-credit.test.ts rename to src/main/runtime/rpc/terminal/terminal-subscribe-output-credit.test.ts index ac5e7939759..cba3458addc 100644 --- a/src/main/runtime/rpc/terminal-subscribe-output-credit.test.ts +++ b/src/main/runtime/rpc/terminal/terminal-subscribe-output-credit.test.ts @@ -1,16 +1,16 @@ import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { TerminalPublishedOutputRings } from '../terminal/output/terminal-published-output-ring' +import { RpcDispatcher } from '../dispatcher' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import { createSubscriptionRegistryDouble } from '../testing/subscription-registry-test-double' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' +import { TerminalPublishedOutputRings } from '../../terminal/output/terminal-published-output-ring' import { TerminalStreamOpcode, decodeTerminalStreamFrame, decodeTerminalStreamJson, decodeTerminalStreamText -} from '../../../shared/terminal/stream/terminal-stream-protocol' +} from '../../../../shared/terminal/stream/terminal-stream-protocol' const CHUNK = 64 * 1024 @@ -138,28 +138,6 @@ async function startCreditedSubscription() { } describe('terminal.subscribe output credit', () => { - it('holds output beyond the window until the stream token is acked', async () => { - const stream = await startCreditedSubscription() - expect(stream.subscribed).toMatchObject({ outputAck: true, streamToken: expect.any(String) }) - - stream.output(9) - expect(stream.sentOutputUnits()).toBe(512 * 1024) - - await stream.ack(stream.subscribed.streamToken, CHUNK) - expect(stream.sentOutputUnits()).toBe(576 * 1024) - await stream.stop() - }) - - it("credits nothing for another device's ack or an unknown token", async () => { - const stream = await startCreditedSubscription() - stream.output(9) - - await stream.ack(stream.subscribed.streamToken, CHUNK, 'other-device') - await stream.ack('stale-token', CHUNK) - expect(stream.sentOutputUnits()).toBe(512 * 1024) - await stream.stop() - }) - it("sends the PTY's last output, held or batched, when it exits", async () => { const stream = await startCreditedSubscription() stream.output(9) diff --git a/src/main/runtime/rpc/terminal/terminal-subscribe-resume.test.ts b/src/main/runtime/rpc/terminal/terminal-subscribe-resume.test.ts new file mode 100644 index 00000000000..0b82d3e1d09 --- /dev/null +++ b/src/main/runtime/rpc/terminal/terminal-subscribe-resume.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { TERMINAL_METHODS } from '../methods/terminal/terminal' +import { createSubscriptionRegistryDouble } from '../testing/subscription-registry-test-double' +import type { RuntimeTerminalWait } from '../../../../shared/runtime-terminal-contracts' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamJson, + decodeTerminalStreamText +} from '../../../../shared/terminal/stream/terminal-stream-protocol' +import { TerminalPublishedOutputRings } from '../../terminal/output/terminal-published-output-ring' + +type Listener = (data: string, meta?: { seq?: number; rawLength?: number; cwd?: string }) => void + +function createHost() { + const registry = createSubscriptionRegistryDouble() + const rings = new TerminalPublishedOutputRings() + const listeners = new Set() + const addListener = (listener: Listener) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + } + let seq = 0 + let size = { cols: 40, rows: 20 } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This partial runtime supplies the terminal RPC methods these tests invoke. + const runtime = { + getRuntimeId: () => 'test-runtime', + subscribeToPtyExit: vi.fn(() => vi.fn()), + registerRemoteTerminalViewSubscriber: () => () => {}, + requestRendererTerminalTabMount: () => false, + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + handleMobileSubscribe: vi.fn().mockResolvedValue(true), + handleMobileUnsubscribe: vi.fn(), + subscribeToTerminalData: (_ptyId: string, listener: Listener) => addListener(listener), + retainPublishedTerminalOutput: (ptyId: string) => + rings.retain(ptyId, { seq, size: () => size, subscribe: addListener }), + getPtyOutputSequence: () => seq, + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn(async () => ({ data: 'screen', ...size, seq })), + getTerminalSize: () => size, + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + isTerminalAlternateScreen: vi.fn().mockReturnValue(false), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), + registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), + cleanupSubscription: vi.fn(registry.cleanupSubscription), + waitForTerminal: vi.fn(() => new Promise(() => {})) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + // Mirrors onPtyData publishing a chunk to stream subscribers. + const output = (data: string, cwd?: string) => { + seq += data.length + for (const listener of listeners) { + listener(data, { seq, rawLength: data.length, ...(cwd ? { cwd } : {}) }) + } + } + + const subscribe = async (resume?: { streamToken: string; units: number }) => { + const frames: Uint8Array[] = [] + const messages: string[] = [] + const done = dispatcher.dispatchStreaming( + { + id: 'sub', + authToken: 'tok', + method: 'terminal.subscribe', + params: { + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' }, + capabilities: { terminalBinaryStream: 1, outputAck: 1 }, + ...(resume ? { resume } : {}) + } + }, + (msg) => messages.push(msg), + { + connectionId: 'conn-phone', + pairedDeviceId: 'phone-device', + sendBinary: (bytes) => { + frames.push(bytes) + }, + registerBinaryStreamHandler: vi.fn(() => vi.fn()) + } + ) + const subscribed = await vi.waitFor(() => { + const result = messages + .map((msg) => JSON.parse(msg).result) + .find((candidate) => candidate?.type === 'subscribed') + expect(result).toBeDefined() + return result + }) + const decoded = () => frames.map((bytes) => decodeTerminalStreamFrame(bytes)!) + const received = () => + decoded() + .filter((frame) => frame.opcode === TerminalStreamOpcode.Output) + .map((frame) => decodeTerminalStreamText(frame.payload)) + .join('') + return { + subscribed, + received, + cwds: () => + decoded().flatMap((frame) => + frame.opcode === TerminalStreamOpcode.Metadata + ? [decodeTerminalStreamJson<{ cwd: string }>(frame.payload)?.cwd] + : [] + ), + // Output leaves through the stream's batcher, so wait for it rather than reading at once. + receives: (text: string) => vi.waitFor(() => expect(received()).toBe(text)), + snapshotKinds: () => + decoded().flatMap((frame) => + frame.opcode === TerminalStreamOpcode.SnapshotStart + ? [decodeTerminalStreamJson<{ kind: string }>(frame.payload)?.kind] + : [] + ), + stop: async () => { + runtime.cleanupSubscription('terminal-1:phone-1') + await done + } + } + } + + return { + output, + subscribe, + resize: (next: { cols: number; rows: number }) => { + size = next + }, + // What a respawn does to the ring (advancePtyLifecycleGeneration). + resetCoverage: () => rings.get('pty-1')?.resetCoverage(seq) + } +} + +/** A phone stream that received 'hello ' and 'world', then ended while 'again' was printed. */ + +async function endedStream() { + const host = createHost() + const first = await host.subscribe() + host.output('hello ') + await first.receives('hello ') + host.output('world') + await first.receives('hello world') + await first.stop() + host.output('again') + const token: string = first.subscribed.streamToken + return { host, token, units: 11 } +} + +describe('terminal.subscribe resume', () => { + it('sends only the missed output, then the next resume works from the new token', async () => { + const { host, token, units } = await endedStream() + + const second = await host.subscribe({ streamToken: token, units }) + expect(second.subscribed).toMatchObject({ resumed: true, streamToken: expect.any(String) }) + await second.receives('again') + expect(second.snapshotKinds()).toEqual([]) + + host.output('!') + await second.receives('again!') + await second.stop() + host.output('?') + const third = await host.subscribe({ streamToken: second.subscribed.streamToken, units: 6 }) + expect(third.subscribed.resumed).toBe(true) + await third.receives('?') + await third.stop() + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex-test-harness.ts b/src/main/runtime/rpc/terminal/testing/terminal-multiplex-test-harness.ts similarity index 92% rename from src/main/runtime/rpc/terminal-multiplex-test-harness.ts rename to src/main/runtime/rpc/terminal/testing/terminal-multiplex-test-harness.ts index 54a5ae1b935..23024ee52bf 100644 --- a/src/main/runtime/rpc/terminal-multiplex-test-harness.ts +++ b/src/main/runtime/rpc/terminal/testing/terminal-multiplex-test-harness.ts @@ -1,16 +1,16 @@ import { vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal/terminal' -import type { RuntimeTerminalWait } from '../../../shared/runtime-terminal-contracts' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' +import { RpcDispatcher } from '../../dispatcher' +import type { RpcRequest } from '../../core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { TERMINAL_METHODS } from '../../methods/terminal/terminal' +import type { RuntimeTerminalWait } from '../../../../../shared/runtime-terminal-contracts' +import { createSubscriptionRegistryDouble } from '../../testing/subscription-registry-test-double' import { TerminalStreamOpcode, decodeTerminalStreamFrame, encodeTerminalStreamFrame, encodeTerminalStreamJson -} from '../../../shared/terminal/stream/terminal-stream-protocol' +} from '../../../../../shared/terminal/stream/terminal-stream-protocol' export const SET_OUTPUT_PAUSED_OPCODE = 16 as TerminalStreamOpcode export const WRITE_UNAVAILABLE_OPCODE = 17 as TerminalStreamOpcode diff --git a/src/main/runtime/rpc/subscription-registry-test-double.ts b/src/main/runtime/rpc/testing/subscription-registry-test-double.ts similarity index 98% rename from src/main/runtime/rpc/subscription-registry-test-double.ts rename to src/main/runtime/rpc/testing/subscription-registry-test-double.ts index 977650d509a..66f9431d8d2 100644 --- a/src/main/runtime/rpc/subscription-registry-test-double.ts +++ b/src/main/runtime/rpc/testing/subscription-registry-test-double.ts @@ -1,4 +1,4 @@ -import type { SubscriptionRegistration } from '../client/runtime-subscription-registry' +import type { SubscriptionRegistration } from '../../client/runtime-subscription-registry' type Cleanup = () => void | Promise type Entry = { diff --git a/src/main/runtime/rpc/relay-transport.ts b/src/main/runtime/rpc/transports/relay-transport.ts similarity index 97% rename from src/main/runtime/rpc/relay-transport.ts rename to src/main/runtime/rpc/transports/relay-transport.ts index 333ed386055..0762a7acdaf 100644 --- a/src/main/runtime/rpc/relay-transport.ts +++ b/src/main/runtime/rpc/transports/relay-transport.ts @@ -1,7 +1,10 @@ import WebSocket, { type RawData } from 'ws' -import { forEachWithConcurrency } from '../../../shared/map-with-concurrency' -import type { RpcTransport } from './transport' -import type { MobileSocketTransport, MobileSocketTransportMetadata } from './mobile-socket-wiring' +import { forEachWithConcurrency } from '../../../../shared/map-with-concurrency' +import type { RpcTransport } from '../transport' +import type { + MobileSocketTransport, + MobileSocketTransportMetadata +} from '../mobile/mobile-socket-wiring' const MAX_RELAY_MESSAGE_BYTES = 1024 * 1024 // Terminate normally closes next tick; cap slow teardown at 5s so dead sockets cannot block stop or quit. diff --git a/src/main/runtime/rpc/rpc-binary-sender.ts b/src/main/runtime/rpc/transports/rpc-binary-sender.ts similarity index 100% rename from src/main/runtime/rpc/rpc-binary-sender.ts rename to src/main/runtime/rpc/transports/rpc-binary-sender.ts diff --git a/src/main/runtime/rpc/unix-socket-transport.ts b/src/main/runtime/rpc/transports/unix-socket-transport.ts similarity index 97% rename from src/main/runtime/rpc/unix-socket-transport.ts rename to src/main/runtime/rpc/transports/unix-socket-transport.ts index 01eaa2c36b2..04637ee1ba4 100644 --- a/src/main/runtime/rpc/unix-socket-transport.ts +++ b/src/main/runtime/rpc/transports/unix-socket-transport.ts @@ -2,8 +2,8 @@ // Own per-connection cancellation and opt-in long-poll keepalives (design §3.1). import { createServer, type Server, type Socket } from 'node:net' import { chmodSync, existsSync, rmSync } from 'node:fs' -import type { RpcMessageContext, RpcTransport } from './transport' -import { MAX_LOCAL_RUNTIME_RPC_MESSAGE_BYTES } from '../../../shared/local-runtime-rpc-limits' +import type { RpcMessageContext, RpcTransport } from '../transport' +import { MAX_LOCAL_RUNTIME_RPC_MESSAGE_BYTES } from '../../../../shared/local-runtime-rpc-limits' const RUNTIME_RPC_SOCKET_IDLE_TIMEOUT_MS = 30_000 const MAX_RUNTIME_RPC_CONNECTIONS = 32 diff --git a/src/main/runtime/rpc/node-websocket-lifecycle.ts b/src/main/runtime/rpc/transports/websocket/node-websocket-lifecycle.ts similarity index 100% rename from src/main/runtime/rpc/node-websocket-lifecycle.ts rename to src/main/runtime/rpc/transports/websocket/node-websocket-lifecycle.ts diff --git a/src/main/runtime/rpc/remote-runtime-server-heartbeat.ts b/src/main/runtime/rpc/transports/websocket/remote-runtime-server-heartbeat.ts similarity index 98% rename from src/main/runtime/rpc/remote-runtime-server-heartbeat.ts rename to src/main/runtime/rpc/transports/websocket/remote-runtime-server-heartbeat.ts index 27e78964ab9..9aadae81bc0 100644 --- a/src/main/runtime/rpc/remote-runtime-server-heartbeat.ts +++ b/src/main/runtime/rpc/transports/websocket/remote-runtime-server-heartbeat.ts @@ -1,5 +1,5 @@ import type { WebSocket } from 'ws' -import { startSpan } from '../../observability/tracer' +import { startSpan } from '../../../../observability/tracer' // Cellular/Tailscale loss may swallow one pong (STA-3320); require consecutive misses. Three matches web-client tolerance after initial grace. const MISSED_PROBE_LIMIT = 3 diff --git a/src/main/runtime/rpc/shadowed-port-probe.ts b/src/main/runtime/rpc/transports/websocket/shadowed-port-probe.ts similarity index 100% rename from src/main/runtime/rpc/shadowed-port-probe.ts rename to src/main/runtime/rpc/transports/websocket/shadowed-port-probe.ts diff --git a/src/main/runtime/rpc/network-source-class.ts b/src/main/runtime/rpc/transports/websocket/source-admission/network-source-class.ts similarity index 100% rename from src/main/runtime/rpc/network-source-class.ts rename to src/main/runtime/rpc/transports/websocket/source-admission/network-source-class.ts diff --git a/src/main/runtime/rpc/on-link-prefixes.ts b/src/main/runtime/rpc/transports/websocket/source-admission/on-link-prefixes.ts similarity index 100% rename from src/main/runtime/rpc/on-link-prefixes.ts rename to src/main/runtime/rpc/transports/websocket/source-admission/on-link-prefixes.ts diff --git a/src/main/runtime/rpc/ws-network-source-guard.ts b/src/main/runtime/rpc/transports/websocket/source-admission/ws-network-source-guard.ts similarity index 100% rename from src/main/runtime/rpc/ws-network-source-guard.ts rename to src/main/runtime/rpc/transports/websocket/source-admission/ws-network-source-guard.ts diff --git a/src/main/runtime/rpc/ws-unauthenticated-source-cap.ts b/src/main/runtime/rpc/transports/websocket/source-admission/ws-unauthenticated-source-cap.ts similarity index 100% rename from src/main/runtime/rpc/ws-unauthenticated-source-cap.ts rename to src/main/runtime/rpc/transports/websocket/source-admission/ws-unauthenticated-source-cap.ts diff --git a/src/main/runtime/rpc/transports/websocket/static-web-client-handler-stream.test.ts b/src/main/runtime/rpc/transports/websocket/static-web-client-handler-stream.test.ts new file mode 100644 index 00000000000..179ab52aee9 --- /dev/null +++ b/src/main/runtime/rpc/transports/websocket/static-web-client-handler-stream.test.ts @@ -0,0 +1,121 @@ +import { once } from 'node:events' +import type * as fs from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync, type ReadStream } from 'node:fs' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { PassThrough } from 'node:stream' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createStaticWebClientHandler } from './static-web-client-handler' + +const observed = vi.hoisted(() => { + const streams: ReadStream[] = [] + const state: { + onSource?: () => void + } = {} + return { streams, state } +}) +vi.mock('node:fs', async (importOriginal) => { + const original = await importOriginal() + return { + ...original, + createReadStream: (...args: Parameters) => { + const stream = original.createReadStream(args[0], args[1]) + observed.streams.push(stream) + observed.state.onSource?.() + return stream + } + } +}) + +let root: string +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-static-web-stream-')) + mkdirSync(join(root, 'assets')) + writeFileSync(join(root, 'assets', 'fixture.js'), Buffer.alloc(1024 * 1024, 1)) + writeFileSync(join(root, 'web-index.html'), 'web') + observed.state.onSource = undefined +}) +afterEach(async () => { + await Promise.all( + observed.streams.splice(0).map(async (stream) => { + if (!stream.closed) { + const closed = new Promise((resolve) => stream.once('close', resolve)) + stream.destroy() + await closed + } + }) + ) + rmSync(root, { recursive: true, force: true }) +}) + +function fakeResponse() { + return Object.assign(new PassThrough({ highWaterMark: 16 }), { + setHeader: vi.fn(), + statusCode: 0, + headersSent: false + }) +} +function fileDescriptor(stream: ReadStream): number | null { + if ('fd' in stream && (typeof stream.fd === 'number' || stream.fd === null)) { + return stream.fd + } + throw new Error('Missing file descriptor') +} +function request(response = fakeResponse()) { + const handler = createStaticWebClientHandler(root) + handler( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This handler reads only these method/url fields. + { method: 'GET', url: '/assets/fixture.js' } as IncomingMessage, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture implements the writable response surface used by this handler. + response as unknown as ServerResponse + ) + return response +} +async function latestSource(count: number): Promise { + await expect.poll(() => observed.streams.length).toBe(count) + const source = observed.streams.at(-1) + if (!source) { + throw new Error('Missing file stream') + } + return source +} + +it('closes 25 abandoned file readers and removes only owned response listeners', async () => { + const responses: ReturnType[] = [] + const otherClose = vi.fn() + const otherError = vi.fn() + for (let index = 0; index < 25; index++) { + const response = fakeResponse() + response.on('close', otherClose) + response.on('error', otherError) + request(response) + responses.push(response) + const source = await latestSource(index + 1) + await expect.poll(() => source.isPaused()).toBe(true) + const closed = once(response, 'close') + response.destroy() + await closed + } + await expect.poll(() => observed.streams.filter((stream) => !stream.closed).length).toBe(0) + expect(observed.streams.every((stream) => fileDescriptor(stream) === null)).toBe(true) + expect(responses.every((response) => response.listeners('close').length === 1)).toBe(true) + expect(responses.every((response) => response.listeners('error').length === 1)).toBe(true) + expect(otherClose).toHaveBeenCalledTimes(25) + expect(otherError).not.toHaveBeenCalled() +}) + +it('closes a file that is still opening when its response is destroyed', async () => { + const response = fakeResponse() + observed.state.onSource = () => { + const source = observed.streams.at(-1) + expect(source && fileDescriptor(source)).toBe(null) + response.destroy() + } + request(response) + const source = await latestSource(1) + await expect.poll(() => source.closed).toBe(true) + expect(fileDescriptor(source)).toBe(null) + expect(response.listenerCount('close')).toBe(0) + expect(response.listenerCount('error')).toBe(0) +}) diff --git a/src/main/runtime/rpc/static-web-client-handler.ts b/src/main/runtime/rpc/transports/websocket/static-web-client-handler.ts similarity index 98% rename from src/main/runtime/rpc/static-web-client-handler.ts rename to src/main/runtime/rpc/transports/websocket/static-web-client-handler.ts index 752a758c993..5b189ac4ca7 100644 --- a/src/main/runtime/rpc/static-web-client-handler.ts +++ b/src/main/runtime/rpc/transports/websocket/static-web-client-handler.ts @@ -2,7 +2,7 @@ import { createReadStream } from 'node:fs' import { stat } from 'node:fs/promises' import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http' import { basename, extname, isAbsolute, posix, relative, resolve } from 'node:path' -import { readBundledWebClientFiles } from '../../../shared/bundled-web-client-manifest' +import { readBundledWebClientFiles } from '../../../../../shared/bundled-web-client-manifest' const STATIC_WEB_ALLOWED_PATHS = new Set(['/web-index.html']) const STATIC_WEB_ALLOWED_PREFIXES = ['/assets/', '/cmaps/', '/standard_fonts/', '/wasm/'] diff --git a/src/main/runtime/rpc/transports/websocket/ws-empty-payload-frame-write.test.ts b/src/main/runtime/rpc/transports/websocket/ws-empty-payload-frame-write.test.ts new file mode 100644 index 00000000000..b213dfd5eec --- /dev/null +++ b/src/main/runtime/rpc/transports/websocket/ws-empty-payload-frame-write.test.ts @@ -0,0 +1,89 @@ +import type { Socket } from 'node:net' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { WebSocket, WebSocketServer } from 'ws' + +/** Guard config/patches/ws@8.22.0.patch: empty writes can EFAULT under Electron on arm64 39-bit VA kernels, closing ping/pong connections with 1006. */ + +type Peer = { ws: WebSocket; writeLengths: number[] } + +const cleanups: (() => void)[] = [] + +afterEach(() => { + for (const cleanup of cleanups.splice(0)) { + cleanup() + } +}) + +function failEmptyWritesLikeArm64Electron(socket: Socket): number[] { + const writeLengths: number[] = [] + const write = socket.write.bind(socket) + // ws calls write(chunk, cb); Node treats a function encoding as the callback. + vi.spyOn(socket, 'write').mockImplementation((chunk, encoding, cb) => { + writeLengths.push(chunk.length) + if (chunk.length === 0) { + socket.destroy(Object.assign(new Error('write EFAULT'), { code: 'EFAULT' })) + return false + } + return write(chunk, encoding, cb) + }) + return writeLengths +} + +async function connectPair(): Promise<{ server: Peer; client: Peer }> { + const wss = new WebSocketServer({ host: '127.0.0.1', port: 0 }) + cleanups.push(() => wss.close()) + await new Promise((resolve) => wss.once('listening', resolve)) + const address = wss.address() + if (typeof address !== 'object' || address === null) { + throw new Error('WebSocketServer has no TCP address') + } + const { port } = address + + const serverPeer = new Promise((resolve) => { + wss.once('connection', (ws, request) => { + resolve({ ws, writeLengths: failEmptyWritesLikeArm64Electron(request.socket) }) + }) + }) + const clientWs = new WebSocket(`ws://127.0.0.1:${port}`) + cleanups.push(() => clientWs.terminate()) + let clientWriteLengths: number[] = [] + clientWs.once('upgrade', (response) => { + clientWriteLengths = failEmptyWritesLikeArm64Electron(response.socket) + }) + await new Promise((resolve, reject) => { + clientWs.once('open', () => resolve()) + clientWs.once('error', reject) + }) + const server = await serverPeer + return { server, client: { ws: clientWs, writeLengths: clientWriteLengths } } +} + +function sendCallback(): { + done: Promise + cb: (err?: Error | null) => void +} { + let cb: (err?: Error | null) => void = () => {} + const done = new Promise((resolve) => { + cb = vi.fn((err?: Error | null) => resolve(err)) + }) + return { done, cb } +} + +describe('ws empty-payload frame writes', () => { + it('server heartbeat ping with no payload reaches the client and keeps the socket open', async () => { + const { server, client } = await connectPair() + const received = new Promise((resolve) => client.ws.once('ping', resolve)) + const { done, cb } = sendCallback() + + server.ws.ping(undefined, undefined, cb) + + expect(await done).toBeFalsy() + expect((await received).length).toBe(0) + // ws auto-pongs the client's empty ping back on the server's socket. + await new Promise((resolve) => server.ws.once('pong', () => resolve())) + expect(server.writeLengths).not.toContain(0) + expect(client.writeLengths).not.toContain(0) + expect(server.ws.readyState).toBe(WebSocket.OPEN) + expect(cb).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/runtime/rpc/ws-fallback-port-store.ts b/src/main/runtime/rpc/transports/websocket/ws-fallback-port-store.ts similarity index 100% rename from src/main/runtime/rpc/ws-fallback-port-store.ts rename to src/main/runtime/rpc/transports/websocket/ws-fallback-port-store.ts diff --git a/src/main/runtime/rpc/ws-transport-transient-packet-loss.test.ts b/src/main/runtime/rpc/transports/websocket/ws-transport-transient-packet-loss.test.ts similarity index 100% rename from src/main/runtime/rpc/ws-transport-transient-packet-loss.test.ts rename to src/main/runtime/rpc/transports/websocket/ws-transport-transient-packet-loss.test.ts diff --git a/src/main/runtime/rpc/ws-transport.ts b/src/main/runtime/rpc/transports/websocket/ws-transport.ts similarity index 95% rename from src/main/runtime/rpc/ws-transport.ts rename to src/main/runtime/rpc/transports/websocket/ws-transport.ts index d95d95a1a68..282f70a8696 100644 --- a/src/main/runtime/rpc/ws-transport.ts +++ b/src/main/runtime/rpc/transports/websocket/ws-transport.ts @@ -2,7 +2,7 @@ import { createServer as createHttpServer, type Server as HttpServer } from 'node:http' import type { Socket } from 'node:net' import { WebSocketServer, type WebSocket } from 'ws' -import type { RpcTransport } from './transport' +import type { RpcTransport } from '../../transport' import { answerWithoutWebClient, createStaticWebClientHandler } from './static-web-client-handler' import { attachNodeWebSocketLifecycle, @@ -14,11 +14,14 @@ import { } from './node-websocket-lifecycle' import { RemoteRuntimeServerHeartbeat } from './remote-runtime-server-heartbeat' import { assertPortNotShadowingListener } from './shadowed-port-probe' -import { REMOTE_RUNTIME_MAX_INBOUND_FRAME_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import { classifyNetworkSource, type NetworkSourceClass } from './network-source-class' -import { UnauthenticatedSourceCap } from './ws-unauthenticated-source-cap' -import type { WebSocketSourceGuard } from './ws-network-source-guard' -import { reserveBrowserTunnelOrcaListenerPort } from '../../browser/network/tunnels/browser-network-tunnel-destination-policy' +import { REMOTE_RUNTIME_MAX_INBOUND_FRAME_BYTES } from '../../../../../shared/remote-runtime/remote-runtime-memory-limits' +import { + classifyNetworkSource, + type NetworkSourceClass +} from './source-admission/network-source-class' +import { UnauthenticatedSourceCap } from './source-admission/ws-unauthenticated-source-cap' +import type { WebSocketSourceGuard } from './source-admission/ws-network-source-guard' +import { reserveBrowserTunnelOrcaListenerPort } from '../../../../browser/network/tunnels/browser-network-tunnel-destination-policy' export const WEBSOCKET_TRANSPORT_MAX_MESSAGE_BYTES = REMOTE_RUNTIME_MAX_INBOUND_FRAME_BYTES // Allow many remote-desktop streams so stale ones cannot starve control RPCs. diff --git a/src/main/runtime/rpc/unix-socket-transport.test.ts b/src/main/runtime/rpc/unix-socket-transport.test.ts deleted file mode 100644 index 2fe81c1a59b..00000000000 --- a/src/main/runtime/rpc/unix-socket-transport.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { EventEmitter } from 'node:events' -import { StringDecoder } from 'node:string_decoder' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Socket } from 'node:net' -import { UnixSocketTransport } from './unix-socket-transport' - -class FakeSocket extends EventEmitter { - destroyed = false - writable = true - readonly writes: string[] = [] - private idleMs = 0 - private idleHandler: (() => void) | null = null - private idleTimer: NodeJS.Timeout | null = null - - setEncoding(): void {} - setNoDelay(): void {} - end(): void {} - - // Match setTimeout: positive arms, zero suspends, and callback-free rearm preserves the handler. - setTimeout(ms: number, handler?: () => void): this { - if (handler) { - this.idleHandler = handler - } - if (this.idleTimer) { - clearTimeout(this.idleTimer) - this.idleTimer = null - } - this.idleMs = ms - if (ms > 0 && this.idleHandler) { - this.idleTimer = setTimeout(() => this.idleHandler?.(), ms) - } - return this - } - - write(data: string): boolean { - this.writes.push(data) - this.refreshIdleTimer() - return true - } - - destroy(): this { - if (!this.destroyed) { - this.destroyed = true - this.writable = false - if (this.idleTimer) { - clearTimeout(this.idleTimer) - this.idleTimer = null - } - this.emit('close') - } - return this - } - - emit(event: string | symbol, ...args: unknown[]): boolean { - if (event === 'data') { - this.refreshIdleTimer() - } - return super.emit(event, ...args) - } - - // Traffic resets the idle window; net.Socket counts reads and writes alike. - private refreshIdleTimer(): void { - this.setTimeout(this.idleMs) - } -} - -type UnixSocketTransportInternals = { - handleConnection(socket: Socket): void -} - -describe('UnixSocketTransport', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - function createReceiver() { - const transport = new UnixSocketTransport({ endpoint: 'test-pipe', kind: 'named-pipe' }) - const socket = new FakeSocket() - const received: string[] = [] - transport.onMessage((message, reply) => { - received.push(message) - reply('ok') - }) - ;(transport as unknown as UnixSocketTransportInternals).handleConnection( - socket as unknown as Socket - ) - return { socket, received } - } - - it.each([false, true])('preserves the UTF-8 byte boundary with oversized=%s', (oversized) => { - const { socket, received } = createReceiver() - const message = `${'é'.repeat(524287)}a${oversized ? 'x' : ''}` - const wire = Buffer.from(`${message}\n`) - const decoder = new StringDecoder('utf8') - for (let offset = 0; offset < wire.length; offset += 4095) { - socket.emit('data', decoder.write(wire.subarray(offset, offset + 4095))) - } - expect(received).toEqual([oversized ? '' : message]) - }) - - it('clears request keepalive timers when the socket closes before a reply', () => { - const transport = new UnixSocketTransport({ - endpoint: '/tmp/orca-runtime-rpc-test.sock', - kind: 'unix', - keepaliveIntervalMs: 100 - }) - const socket = new FakeSocket() - let aborted = false - - transport.onMessage((_msg, _reply, context) => { - context?.signal?.addEventListener( - 'abort', - () => { - aborted = true - }, - { once: true } - ) - context?.startKeepalive() - }) - - ;(transport as unknown as UnixSocketTransportInternals).handleConnection( - socket as unknown as Socket - ) - socket.emit('data', '{"id":"pending","method":"wait"}\n') - - vi.advanceTimersByTime(100) - expect(socket.writes).toHaveLength(1) - - socket.destroy() - expect(aborted).toBe(true) - - vi.advanceTimersByTime(500) - expect(socket.writes).toHaveLength(1) - }) -}) diff --git a/src/main/runtime/rpc/unpaired-device-auth-throttle.test.ts b/src/main/runtime/rpc/unpaired-device-auth-throttle.test.ts deleted file mode 100644 index fb613482fe2..00000000000 --- a/src/main/runtime/rpc/unpaired-device-auth-throttle.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { UnpairedDeviceAuthThrottle } from './unpaired-device-auth-throttle' - -function throttleAt(clock: { time: number }, onTrigger = vi.fn()) { - const throttle = new UnpairedDeviceAuthThrottle({ - onTrigger, - failureThreshold: 3, - windowMs: 60_000, - now: () => clock.time - }) - return { throttle, onTrigger } -} - -describe('UnpairedDeviceAuthThrottle', () => { - it('stays silent below the failure threshold', () => { - const clock = { time: 0 } - const { throttle, onTrigger } = throttleAt(clock) - throttle.recordFailure() - clock.time += 1000 - throttle.recordFailure() - expect(onTrigger).not.toHaveBeenCalled() - }) - - it('never fires twice in one session even as failures continue', () => { - const clock = { time: 0 } - const { throttle, onTrigger } = throttleAt(clock) - for (let i = 0; i < 20; i++) { - throttle.recordFailure() - clock.time += 500 - } - expect(onTrigger).toHaveBeenCalledOnce() - }) - - it('ignores failures that fall outside the window', () => { - const clock = { time: 0 } - const { throttle, onTrigger } = throttleAt(clock) - throttle.recordFailure() - clock.time += 61_000 - throttle.recordFailure() - clock.time += 61_000 - throttle.recordFailure() - expect(onTrigger).not.toHaveBeenCalled() - - // A real retry burst after the stray singles still triggers. - clock.time += 61_000 - throttle.recordFailure() - clock.time += 100 - throttle.recordFailure() - clock.time += 100 - throttle.recordFailure() - expect(onTrigger).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/runtime/rpc/web-session-pairing.test.ts b/src/main/runtime/rpc/web-session-pairing.test.ts deleted file mode 100644 index 87af647398b..00000000000 --- a/src/main/runtime/rpc/web-session-pairing.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import nacl from 'tweetnacl' -import type { WebSocket } from 'ws' -import { describe, expect, it, vi } from 'vitest' -import { encodeDeviceProofMessage } from '../../../shared/remote-runtime/pairing/device-key-proof' -import { DeviceRegistry } from './server/pairing/device-registry' -import { EPHEMERAL_DEVICE_IDLE_MS } from './server/pairing/ephemeral-device-rows' -import { SimulatedMobileE2EEV2Peer } from '../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer' -import { registerSocketDeviceKey } from './server/runtime-rpc-device-key-registration' -import { generateKeyPair } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { - MobileSocketWiring, - type AuthenticatedMobileSocket, - type MobileSocketTransport, - type MobileSocketTransportMetadata -} from './mobile-socket-wiring' - -class FakeSocket { - readonly OPEN = 1 - readyState = this.OPEN - bufferedAmount = 0 - readonly sent: (string | Buffer)[] = [] - readonly send = vi.fn((data: string | Buffer) => this.sent.push(data)) - readonly close = vi.fn() -} - -class FakeTransport implements MobileSocketTransport { - private messageHandler: Parameters[0] | null = null - readonly setClientId = vi.fn() - readonly terminateClientConnections = vi.fn(() => 0) - onMessage(handler: Parameters[0]): void { - this.messageHandler = handler - } - onConnectionClose(): void {} - receive(ws: FakeSocket, message: string): void { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the wiring only sends, closes and reads OPEN/readyState/bufferedAmount. - this.messageHandler?.(message, vi.fn(), ws as unknown as WebSocket) - } -} - -const desktop = generateKeyPair() -const RELAY_HOST_ID = 'AbCdEf0123_-xyZ9' - -function harness(relay?: (deviceId: string) => MobileSocketTransportMetadata) { - const registry = new DeviceRegistry(mkdtempSync(join(tmpdir(), 'orca-web-session-'))) - const transport = new FakeTransport() - const ready: AuthenticatedMobileSocket[] = [] - const wiring = new MobileSocketWiring({ - deviceRegistry: registry, - e2eeKeypair: { - publicKey: desktop.publicKey, - secretKey: desktop.secretKey, - publicKeyB64: Buffer.from(desktop.publicKey).toString('base64') - }, - onText: vi.fn(), - onBinary: vi.fn(), - onClose: vi.fn(), - onReady: (socket) => ready.push(socket) - }) - let relayDeviceId = '' - wiring.attachTransport(transport, () => (relay ? relay(relayDeviceId) : { transport: 'direct' })) - - function connect(auth: (transcriptHashB64: string) => Record) { - const ws = new FakeSocket() - const peer = new SimulatedMobileE2EEV2Peer( - nacl.box.keyPair(), - desktop.publicKey, - relay ? RELAY_HOST_ID : null - ) - transport.receive(ws, JSON.stringify(peer.hello)) - expect(peer.acceptReady(JSON.parse(String(ws.sent[0])))).toBe(true) - const transcriptHashB64 = peer.transcriptHashB64 - const before = ready.length - transport.receive( - ws, - peer.sealText( - JSON.stringify({ type: 'e2ee_auth', v: 2, transcriptHashB64, ...auth(transcriptHashB64) }) - ) - ) - const reply = ws.sent[1] ? JSON.parse(peer.openText(String(ws.sent[1]))!) : null - return { ws, transcriptHashB64, reply, socket: ready.length > before ? ready.at(-1) : null } - } - return { - registry, - wiring, - transport, - connect, - bindRelay: (deviceId: string) => (relayDeviceId = deviceId) - } -} - -function sign(key: nacl.SignKeyPair, purpose: 'auth' | 'register', transcriptHashB64: string) { - const message = encodeDeviceProofMessage(purpose, Buffer.from(transcriptHashB64, 'base64')) - return Buffer.from(nacl.sign.detached(message, key.secretKey)).toString('base64') -} - -// First pairing accepts direct clients regardless of page origin; origin gating broke LAN/Tailscale web pairing (#27540). - -describe('session-only browser keys', () => { - it('registers an ephemeral row, sweeps it once idle and disconnected, and then revokes it', () => { - const { registry, wiring, transport, connect } = harness() - const paired = registry.addDevice('Browser', 'runtime') - registry.updateLastSeen(paired.deviceId) - const migrating = connect(() => ({ deviceToken: paired.token })) - const key = nacl.sign.keyPair() - const fork = registerSocketDeviceKey(registry, migrating.socket!, { - devicePublicKeyB64: Buffer.from(key.publicKey).toString('base64'), - deviceProofB64: sign(key, 'register', migrating.transcriptHashB64), - ephemeral: true - }) - expect(registry.getDevice(fork.deviceId)?.ephemeral).toBe(true) - - const keyed = connect((hash) => ({ - deviceId: fork.deviceId, - deviceProofB64: sign(key, 'auth', hash) - })) - expect(keyed.reply).toMatchObject({ type: 'e2ee_authenticated' }) - const idle = registry.getDevice(fork.deviceId)!.lastSeenAt + EPHEMERAL_DEVICE_IDLE_MS + 1 - // A live socket keeps the row however long the tab stays open. - expect(wiring.sweepIdleEphemeralDevices(idle)).toEqual([]) - - transport.receive(keyed.ws, 'ignored') - wiring.dispose() - expect(registry.pruneIdleEphemeralDevices(idle, () => false)).toEqual([fork.deviceId]) - const after = connect((hash) => ({ - deviceId: fork.deviceId, - deviceProofB64: sign(key, 'auth', hash) - })) - expect(after.reply).toEqual({ - type: 'e2ee_error', - error: { code: 'device_revoked', deviceId: fork.deviceId } - }) - }) -}) diff --git a/src/main/runtime/rpc/worker-caller-identity-restore-wait.test.ts b/src/main/runtime/rpc/worker-caller-identity-restore-wait.test.ts deleted file mode 100644 index e172fb970e5..00000000000 --- a/src/main/runtime/rpc/worker-caller-identity-restore-wait.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { OrcaRuntimeService } from '../orca-runtime' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' -import '../orchestration/db/contract-constants' -import '../orchestration/db/messages/mailbox-routing-page' -import '../orchestration/db/dispatch-row-writer' -import '../orchestration/db/attempt-outcome-projection' -import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' -import type { RpcResponse } from './core' - -const REJECTED = { - ok: true, - result: { lifecycle: { action: 'rejected', code: 'worker_identity_changed' } } -} -import { RpcDispatcher } from './dispatcher' -import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' - -const COORDINATOR_PANE = 'tab_coord:11111111-1111-4111-8111-111111111111' -const WORKER_PANE = 'tab_worker:44444444-4444-4444-8444-444444444444' -const WORKER_PROCESS = 'pty_worker:incarnation_1' - -/** A worker whose terminal reads as unknown until `restore` publishes the identity Orca recovers. */ -async function startRestartingOrca() { - const db = new OrchestrationDb(':memory:') - const runtime = new OrcaRuntimeService() - runtime.setOrchestrationDb(db) - const restored: { paneKey: string | null; process: string | null } = { - paneKey: null, - process: null - } - vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' ? COORDINATOR_PANE : handle === 'term_worker' ? restored.paneKey : null - ) - vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => - runtime.getTerminalPaneKey(handle) - ) - vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => - handle === 'term_coord' ? 'pty_coord:1' : handle === 'term_worker' ? restored.process : null - ) - vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) - const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) - // Startup recovery runs on the first call; seed after it so it cannot settle the worker. - await dispatcher.dispatch({ - id: 'rpc_warm', - authToken: 'token', - method: 'orchestration.runList', - params: {}, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION - }) - const run = db.createRun({ - objective: 'restart', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: COORDINATOR_PANE - }) - const task = db.createTask({ runId: run.id, spec: 'work' }) - const dispatch = createRootDispatch( - db, - task.id, - 'term_worker', - WORKER_PANE, - undefined, - WORKER_PROCESS - ) - runtime.startupWorkerAuthority.begin() - const workerDone = (): Promise => - dispatcher.dispatch({ - id: 'rpc_done', - authToken: 'token', - method: 'orchestration.send', - params: { - from: 'term_worker', - subject: 'Done', - type: 'worker_done', - payload: JSON.stringify({ taskId: task.id, dispatchId: dispatch.id, outcome: 'succeeded' }) - }, - orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION - }) - const restore = async (identity: { paneKey: string; process: string }): Promise => { - // Let a report that does not wait run to completion first, as it would against a slow restore. - await settleTurns() - restored.paneKey = identity.paneKey - restored.process = identity.process - runtime.startupWorkerAuthority.finish() - } - return { db, runtime, dispatcher, task, dispatch, workerDone, restore } -} - -async function settleTurns(): Promise { - for (let turn = 0; turn < 20; turn += 1) { - await new Promise((resolve) => setImmediate(resolve)) - } -} - -describe('a worker report during an Orca restart', () => { - let db: OrchestrationDb | undefined - afterEach(() => { - vi.useRealTimers() - db?.close() - db = undefined - }) - - it('is accepted once the restore rebinds the same terminal process', async () => { - const orca = await startRestartingOrca() - db = orca.db - const pending = orca.workerDone() - await orca.restore({ paneKey: WORKER_PANE, process: WORKER_PROCESS }) - - expect(await pending).toMatchObject({ ok: true, result: { message: { type: 'worker_done' } } }) - expect( - orca.db.db - .prepare(`SELECT subject, sender_pane_key FROM messages WHERE type = 'worker_done'`) - .all() - ).toEqual([{ subject: 'Done', sender_pane_key: WORKER_PANE }]) - expect(orca.db.getWorkerDispatch(orca.dispatch.id)?.state).not.toBe('dispatched') - }) - - it('is still rejected when the terminal was handed to another dispatch', async () => { - const orca = await startRestartingOrca() - db = orca.db - orca.db.failDispatch(orca.dispatch.id, 'worker stopped') - const newerTask = orca.db.createTask({ runId: orca.task.run_id!, spec: 'newer work' }) - const newer = createRootDispatch( - orca.db, - newerTask.id, - 'term_worker', - WORKER_PANE, - undefined, - 'pty_worker:incarnation_2' - ) - const pending = orca.workerDone() - await orca.restore({ paneKey: WORKER_PANE, process: 'pty_worker:incarnation_2' }) - - expect(await pending).toMatchObject(REJECTED) - expect(orca.db.getDispatchContextById(newer.id)?.status).toBe('dispatched') - }) -}) diff --git a/src/main/runtime/rpc/content-snapshot-id.ts b/src/main/runtime/rpc/workspace-client-views/content-snapshot-id.ts similarity index 100% rename from src/main/runtime/rpc/content-snapshot-id.ts rename to src/main/runtime/rpc/workspace-client-views/content-snapshot-id.ts diff --git a/src/main/runtime/rpc/workspace-client-views/git-graph-layout-projection.test.ts b/src/main/runtime/rpc/workspace-client-views/git-graph-layout-projection.test.ts new file mode 100644 index 00000000000..4f1f4d4cd6f --- /dev/null +++ b/src/main/runtime/rpc/workspace-client-views/git-graph-layout-projection.test.ts @@ -0,0 +1,136 @@ +import { withoutGitGraph } from '../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { WorkspaceLayoutModel } from '../../../../shared/workspace-layout/workspace-layout-model' +import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' +import { expect, it } from 'vitest' +import './git-graph-layout-projection' +import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' +import '../../../../shared/workspace-layout/published-layout/workspace-layout-records' + +function layout(): PublishedWorkspaceLayout { + return { + worktreeId: 'w', + editorFiles: [], + browserTabs: [], + tabs: ['a', 'graph', 'b', 'c'].map((id) => ({ + id, + entityId: id, + kind: id === 'graph' ? 'git-graph' : 'editor', + executionHostId: 'local', + createdAt: 0, + customTitle: null, + color: null + })), + groups: [ + { id: 'g1', tabIds: ['a', 'graph', 'b'] }, + { id: 'g2', tabIds: ['c'] } + ], + groupLayout: { + type: 'split', + direction: 'horizontal', + ratio: 0.3, + first: { type: 'leaf', groupId: 'g1' }, + second: { type: 'leaf', groupId: 'g2' } + } + } +} + +function canonical(original = layout()): WorkspaceLayoutModel { + return { + hostId: 'local', + records: {}, + legacy: { terminalRowOwners: {} }, + workspaces: { + w: { + worktreeId: 'w', + tabs: original.tabs.map(({ kind, ...tab }) => { + if (kind === 'terminal') { + throw new Error('Expected a content fixture') + } + return { ...tab, kind } + }), + groups: original.groups.map(({ id, tabIds }) => ({ id, tabOrder: tabIds })), + groupLayout: original.groupLayout + } + } + } +} + +function applyClient(command: LayoutCommand, model = canonical()) { + return applyLayoutCommand(model, command, { + visibility: withoutGitGraph, + mintId: () => 'minted', + mintLeafId: () => 'leaf', + now: () => 0 + }) +} + +it('translates split paths and identities together while retaining hidden branches', () => { + const model = canonical() + const workspace = model.workspaces.w! + workspace.groups = [ + { id: 'hidden', tabOrder: ['graph'] }, + { id: 'g1', tabOrder: ['a', 'b'] }, + { id: 'g2', tabOrder: ['c'] } + ] + workspace.groupLayout = { + type: 'split', + direction: 'vertical', + ratio: 0.2, + first: { type: 'leaf', groupId: 'hidden' }, + second: workspace.groupLayout! + } + const resized = applyClient( + { + type: 'setGroupRatios', + workspace: 'w', + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } + ] + }, + model + ) + expect(resized.ok && resized.model.workspaces.w!.groupLayout).toEqual({ + ...workspace.groupLayout, + second: { ...layout().groupLayout, ratio: 0.7 } + }) + workspace.groupLayout = { + type: 'split', + direction: 'horizontal', + ratio: 0.3, + first: { + type: 'split', + direction: 'vertical', + ratio: 0.2, + first: { type: 'leaf', groupId: 'hidden' }, + second: { type: 'leaf', groupId: 'g1' } + }, + second: { type: 'leaf', groupId: 'g2' } + } + const identities = applyClient( + { + type: 'setGroupRatios', + workspace: 'w', + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } + ] + }, + model + ) + expect(identities.ok && identities.model.workspaces.w!.groupLayout).toEqual({ + ...workspace.groupLayout, + ratio: 0.7 + }) + expect( + applyClient( + { + type: 'setGroupRatios', + workspace: 'w', + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'vertical', first: 'stale', second: 'g2' } } + ] + }, + model + ) + ).toEqual({ ok: false, code: 'group_set_changed' }) +}) diff --git a/src/main/runtime/rpc/git-graph-layout-projection.ts b/src/main/runtime/rpc/workspace-client-views/git-graph-layout-projection.ts similarity index 86% rename from src/main/runtime/rpc/git-graph-layout-projection.ts rename to src/main/runtime/rpc/workspace-client-views/git-graph-layout-projection.ts index 4d4eaa45273..1298e726fdf 100644 --- a/src/main/runtime/rpc/git-graph-layout-projection.ts +++ b/src/main/runtime/rpc/workspace-client-views/git-graph-layout-projection.ts @@ -1,6 +1,6 @@ -import { GIT_GRAPH_TAB_CAPABILITY } from '../../../shared/source-control/runtime/git-graph-capabilities' -import { visibleGroupTree } from '../../../shared/workspace-layout/workspace-layout-client-visibility' -import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' +import { GIT_GRAPH_TAB_CAPABILITY } from '../../../../shared/source-control/runtime/git-graph-capabilities' +import { visibleGroupTree } from '../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' +import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import { applyPublishedLayoutRecordChanges, splitPublishedLayout, @@ -8,8 +8,8 @@ import { type PublishedLayoutRecords, diffPublishedLayouts, indexPublishedLayout -} from '../../../shared/workspace-layout/workspace-layout-records' -import type { WorkspaceLayoutStreamFrame } from '../../../shared/workspace-layout/workspace-layout-stream-frames' +} from '../../../../shared/workspace-layout/published-layout/workspace-layout-records' +import type { WorkspaceLayoutStreamFrame } from '../../../../shared/workspace-layout/published-layout/workspace-layout-stream-frames' export function readsGitGraph(capabilities?: readonly string[]): boolean { return capabilities?.includes(GIT_GRAPH_TAB_CAPABILITY) === true } diff --git a/src/main/runtime/rpc/repo-visibility-projection.ts b/src/main/runtime/rpc/workspace-client-views/repo-visibility-projection.ts similarity index 84% rename from src/main/runtime/rpc/repo-visibility-projection.ts rename to src/main/runtime/rpc/workspace-client-views/repo-visibility-projection.ts index 9abefc7d149..b4c0c07860f 100644 --- a/src/main/runtime/rpc/repo-visibility-projection.ts +++ b/src/main/runtime/rpc/workspace-client-views/repo-visibility-projection.ts @@ -1,10 +1,10 @@ import { effectiveExternalWorktreeVisibility, isLegacyRepoForExternalWorktreeVisibility -} from '../../../shared/external-worktree-visibility' -import { WORKTREE_VISIBILITY_DEFAULTS_RUNTIME_CAPABILITY } from '../../../shared/worktree-runtime-capabilities' -import type { Repo } from '../../../shared/repo-types' -import type { RpcContext } from './core' +} from '../../../../shared/external-worktree-visibility' +import { WORKTREE_VISIBILITY_DEFAULTS_RUNTIME_CAPABILITY } from '../../../../shared/worktree-runtime-capabilities' +import type { Repo } from '../../../../shared/repo-types' +import type { RpcContext } from '../core' type RepoProjectionContext = Pick diff --git a/src/main/runtime/rpc/worktree-catalog-snapshot.ts b/src/main/runtime/rpc/workspace-client-views/worktree-catalog-snapshot.ts similarity index 100% rename from src/main/runtime/rpc/worktree-catalog-snapshot.ts rename to src/main/runtime/rpc/workspace-client-views/worktree-catalog-snapshot.ts diff --git a/src/main/runtime/rpc/worktree-ps-coarse-activity.ts b/src/main/runtime/rpc/workspace-client-views/worktree-ps-coarse-activity.ts similarity index 80% rename from src/main/runtime/rpc/worktree-ps-coarse-activity.ts rename to src/main/runtime/rpc/workspace-client-views/worktree-ps-coarse-activity.ts index 5cb33a1cdb6..5ea35bcdd84 100644 --- a/src/main/runtime/rpc/worktree-ps-coarse-activity.ts +++ b/src/main/runtime/rpc/workspace-client-views/worktree-ps-coarse-activity.ts @@ -1,5 +1,5 @@ -import type { RuntimeWorktreePsResult } from '../../../shared/runtime-worktree-contracts' -import { compareWorktreePs } from '../workspaces/process-listing/runtime-worktree-status-projection' +import type { RuntimeWorktreePsResult } from '../../../../shared/runtime-worktree-contracts' +import { compareWorktreePs } from '../../workspaces/process-listing/runtime-worktree-status-projection' // Why: mobile reads lastOutputAt only to rank rows; a 30 s floor bounds activity-driven resends to one per bucket. const COARSE_LAST_OUTPUT_AT_MS = 30_000 diff --git a/src/main/runtime/rpc/worktree-ps-other-client-marks.ts b/src/main/runtime/rpc/workspace-client-views/worktree-ps-other-client-marks.ts similarity index 75% rename from src/main/runtime/rpc/worktree-ps-other-client-marks.ts rename to src/main/runtime/rpc/workspace-client-views/worktree-ps-other-client-marks.ts index 96159b70ab4..717c657bc15 100644 --- a/src/main/runtime/rpc/worktree-ps-other-client-marks.ts +++ b/src/main/runtime/rpc/workspace-client-views/worktree-ps-other-client-marks.ts @@ -1,10 +1,10 @@ -import type { RuntimeWorktreePsResult } from '../../../shared/runtime-worktree-contracts' +import type { RuntimeWorktreePsResult } from '../../../../shared/runtime-worktree-contracts' import { EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, isWorkspaceOwnedBySomeoneElse -} from '../../../shared/workspace-creator-visibility' -import type { RpcContext } from './core' -import { isHostOwnPhone } from './host-own-phone' +} from '../../../../shared/workspace-creator-visibility' +import type { RpcContext } from '../core' +import { isHostOwnPhone } from '../callers/host-own-phone' /** Mark ownership for this host's phone to apply its filter; delegated phones belong to another desktop whose view this host cannot infer. */ export function markWorktreePsOtherClientRows( diff --git a/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts b/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts new file mode 100644 index 00000000000..1c64ffde30b --- /dev/null +++ b/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts @@ -0,0 +1,123 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' +import { NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/protocol-version' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import { remoteRuntimeClientCapabilities } from '../../../../shared/remote-runtime/remote-runtime-client-capabilities' +import type { + RuntimeWorktreeListResult, + RuntimeWorktreePsResult +} from '../../../../shared/runtime-worktree-contracts' +import { + _resetPendingWorktreeRemovalsForTests, + _settlePendingWorktreeRemovalsForTests, + startBackgroundWorktreeRemoval, + loadWorktreeRemovalRecords, + waitForWorktreeRemovalAcceptance +} from '../../../workspaces/removal/worktree-background-removal' +import { snapshotPendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-listing' +import { + projectWorktreeListRemovals, + projectWorktreePsRemovals +} from './worktree-removal-marker-projection' + +const removingId = 'repo-1::/work/feature' +const keptId = 'repo-1::/work/other' + +function listResult(): RuntimeWorktreeListResult { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the projection reads only id, hostId and the counts. + return { + worktrees: [ + { id: removingId, hostId: 'local' }, + { id: keptId, hostId: 'local' } + ], + totalCount: 2, + truncated: false + } as unknown as RuntimeWorktreeListResult +} + +function psResult(): RuntimeWorktreePsResult { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the projection reads only worktreeId, hostId and the counts. + return { + worktrees: [ + { worktreeId: removingId, hostId: 'local' }, + { worktreeId: keptId, hostId: 'local' } + ], + totalCount: 2, + truncated: false + } as unknown as RuntimeWorktreePsResult +} + +describe('worktree listings while a checkout is being deleted', () => { + let directory = '' + let cleanup = Promise.withResolvers() + beforeEach(async () => { + cleanup = Promise.withResolvers() + directory = await mkdtemp(join(tmpdir(), 'orca-marker-projection-')) + await loadWorktreeRemovalRecords(directory) + void startBackgroundWorktreeRemoval({ + removal: { + worktreeId: removingId, + repoId: 'repo-1', + repoPath: '/work/repo', + worktree: { path: '/work/feature', branch: 'refs/heads/feature', head: 'abc' }, + deleteBranch: true, + force: false + }, + run: () => cleanup.promise, + publish: () => {} + }) + await waitForWorktreeRemovalAcceptance(removingId) + }) + + afterEach(async () => { + cleanup.resolve({}) + await _settlePendingWorktreeRemovalsForTests() + _resetPendingWorktreeRemovalsForTests() + await rm(directory, { recursive: true, force: true }) + }) + + it('marks the row for a desktop or web client that negotiated the marker', () => { + const context = { clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } + expect( + projectWorktreeListRemovals(listResult(), context, snapshotPendingWorktreeRemovals()) + .worktrees + ).toEqual([ + { id: removingId, hostId: 'local', removing: true, removalRecorded: true }, + { id: keptId, hostId: 'local' } + ]) + expect( + projectWorktreePsRemovals(psResult(), context, snapshotPendingWorktreeRemovals()).worktrees + ).toEqual([ + { worktreeId: removingId, hostId: 'local', removing: true, removalRecorded: true }, + { worktreeId: keptId, hostId: 'local' } + ]) + }) + + it('leaves the row out for a client that would show it as a normal workspace', () => { + // An older desktop or web build, the CLI, the phone, and an in-process caller alike. + for (const clientCapabilities of [ + [], + undefined, + NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES, + remoteRuntimeClientCapabilities() + ]) { + const list = projectWorktreeListRemovals( + listResult(), + { clientCapabilities }, + snapshotPendingWorktreeRemovals() + ) + expect(list.worktrees.map((row) => row.id)).toEqual([keptId]) + expect(list.totalCount).toBe(1) + const ps = projectWorktreePsRemovals( + psResult(), + { clientCapabilities }, + snapshotPendingWorktreeRemovals() + ) + expect(ps.worktrees.map((row) => row.worktreeId)).toEqual([keptId]) + expect(ps.totalCount).toBe(1) + } + }) +}) diff --git a/src/main/runtime/rpc/worktree-removal-marker-projection.ts b/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.ts similarity index 87% rename from src/main/runtime/rpc/worktree-removal-marker-projection.ts rename to src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.ts index ac1a51e9786..f7ddf82a23b 100644 --- a/src/main/runtime/rpc/worktree-removal-marker-projection.ts +++ b/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.ts @@ -1,14 +1,14 @@ -import { WORKTREE_BACKGROUND_REMOVAL_RUNTIME_CAPABILITY } from '../../../shared/worktree-runtime-capabilities' -import type { DetectedWorktreeListResult } from '../../../shared/worktree/types' +import { WORKTREE_BACKGROUND_REMOVAL_RUNTIME_CAPABILITY } from '../../../../shared/worktree-runtime-capabilities' +import type { DetectedWorktreeListResult } from '../../../../shared/worktree/types' import type { RuntimeWorktreeListResult, RuntimeWorktreePsResult -} from '../../../shared/runtime-worktree-contracts' +} from '../../../../shared/runtime-worktree-contracts' import { projectPendingWorktreeRemovals, type PendingWorktreeRemovals -} from '../../workspaces/removal/worktree-removal-listing' -import type { RpcContext } from './core' +} from '../../../workspaces/removal/worktree-removal-listing' +import type { RpcContext } from '../core' // Without negotiation, CLI/host readers act on rows; omit deleting checkouts they cannot use. export function readsWorktreeRemovalMarker( diff --git a/src/main/runtime/rpc/worktree-visibility-client-capability.ts b/src/main/runtime/rpc/workspace-client-views/worktree-visibility-client-capability.ts similarity index 79% rename from src/main/runtime/rpc/worktree-visibility-client-capability.ts rename to src/main/runtime/rpc/workspace-client-views/worktree-visibility-client-capability.ts index 676236eb7cc..b62a326c32b 100644 --- a/src/main/runtime/rpc/worktree-visibility-client-capability.ts +++ b/src/main/runtime/rpc/workspace-client-views/worktree-visibility-client-capability.ts @@ -1,5 +1,5 @@ -import { WORKTREE_VISIBILITY_SOURCE_DEFAULTS_RUNTIME_CAPABILITY } from '../../../shared/worktree-runtime-capabilities' -import type { RpcContext } from './core' +import { WORKTREE_VISIBILITY_SOURCE_DEFAULTS_RUNTIME_CAPABILITY } from '../../../../shared/worktree-runtime-capabilities' +import type { RpcContext } from '../core' export function supportsWorktreeVisibilitySourceDefaults( context: Pick, diff --git a/src/main/runtime/rpc/workspace-creator-context.test.ts b/src/main/runtime/rpc/workspace-creator-context.test.ts deleted file mode 100644 index 35cc80df1a3..00000000000 --- a/src/main/runtime/rpc/workspace-creator-context.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveRpcWorkspaceCreatorProvenance } from './workspace-creator-context' - -describe('resolveRpcWorkspaceCreatorProvenance', () => { - it("records a phone paired here as this host's owner", () => { - expect( - resolveRpcWorkspaceCreatorProvenance({ pairedDeviceId: 'phone', clientKind: 'mobile' }) - ).toEqual({ kind: 'host' }) - }) - - it('records a delegated phone as the desktop that relays it', () => { - expect( - resolveRpcWorkspaceCreatorProvenance({ - pairedDeviceId: 'child', - pairedDeviceParentId: 'desktop', - clientKind: 'mobile' - }) - ).toEqual({ kind: 'paired-device', deviceId: 'desktop' }) - }) - - it('records a paired desktop as itself, and an in-process caller as the host', () => { - expect( - resolveRpcWorkspaceCreatorProvenance({ pairedDeviceId: 'laptop', clientKind: 'runtime' }) - ).toEqual({ kind: 'paired-device', deviceId: 'laptop' }) - expect(resolveRpcWorkspaceCreatorProvenance({})).toEqual({ kind: 'host' }) - }) -}) diff --git a/src/main/runtime/rpc/worktree-removal-marker-projection.test.ts b/src/main/runtime/rpc/worktree-removal-marker-projection.test.ts deleted file mode 100644 index b9ab536b4ce..00000000000 --- a/src/main/runtime/rpc/worktree-removal-marker-projection.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/protocol-version' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' -import { remoteRuntimeClientCapabilities } from '../../../shared/remote-runtime/remote-runtime-client-capabilities' -import type { - RuntimeWorktreeListResult, - RuntimeWorktreePsResult -} from '../../../shared/runtime-worktree-contracts' -import { - _resetPendingWorktreeRemovalsForTests, - startBackgroundWorktreeRemoval -} from '../../workspaces/removal/worktree-background-removal' -import { snapshotPendingWorktreeRemovals } from '../../workspaces/removal/worktree-removal-listing' -import { - projectWorktreeListRemovals, - projectWorktreePsRemovals -} from './worktree-removal-marker-projection' - -const removingId = 'repo-1::/work/feature' -const keptId = 'repo-1::/work/other' - -function listResult(): RuntimeWorktreeListResult { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the projection reads only id, hostId and the counts. - return { - worktrees: [ - { id: removingId, hostId: 'local' }, - { id: keptId, hostId: 'local' } - ], - totalCount: 2, - truncated: false - } as unknown as RuntimeWorktreeListResult -} - -function psResult(): RuntimeWorktreePsResult { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the projection reads only worktreeId, hostId and the counts. - return { - worktrees: [ - { worktreeId: removingId, hostId: 'local' }, - { worktreeId: keptId, hostId: 'local' } - ], - totalCount: 2, - truncated: false - } as unknown as RuntimeWorktreePsResult -} - -describe('worktree listings while a checkout is being deleted', () => { - beforeEach(() => { - void startBackgroundWorktreeRemoval({ - removal: { - worktreeId: removingId, - repoId: 'repo-1', - repoPath: '/work/repo', - worktree: { path: '/work/feature', branch: 'refs/heads/feature', head: 'abc' }, - deleteBranch: true, - force: false - }, - run: () => new Promise(() => {}), - publish: () => {} - }) - }) - - afterEach(() => { - _resetPendingWorktreeRemovalsForTests() - }) - - it('marks the row for a desktop or web client that negotiated the marker', () => { - const context = { clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } - expect( - projectWorktreeListRemovals(listResult(), context, snapshotPendingWorktreeRemovals()) - .worktrees - ).toEqual([ - { id: removingId, hostId: 'local', removing: true }, - { id: keptId, hostId: 'local' } - ]) - expect( - projectWorktreePsRemovals(psResult(), context, snapshotPendingWorktreeRemovals()).worktrees - ).toEqual([ - { worktreeId: removingId, hostId: 'local', removing: true }, - { worktreeId: keptId, hostId: 'local' } - ]) - }) - - it('leaves the row out for a client that would show it as a normal workspace', () => { - // An older desktop or web build, the CLI, the phone, and an in-process caller alike. - for (const clientCapabilities of [ - [], - undefined, - NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES, - remoteRuntimeClientCapabilities() - ]) { - const list = projectWorktreeListRemovals( - listResult(), - { clientCapabilities }, - snapshotPendingWorktreeRemovals() - ) - expect(list.worktrees.map((row) => row.id)).toEqual([keptId]) - expect(list.totalCount).toBe(1) - const ps = projectWorktreePsRemovals( - psResult(), - { clientCapabilities }, - snapshotPendingWorktreeRemovals() - ) - expect(ps.worktrees.map((row) => row.worktreeId)).toEqual([keptId]) - expect(ps.totalCount).toBe(1) - } - }) -}) diff --git a/src/main/runtime/rpc/worktree-rm-pty.test-fixture.ts b/src/main/runtime/rpc/worktree-rm-pty.test-fixture.ts deleted file mode 100644 index a4e2a6474d3..00000000000 --- a/src/main/runtime/rpc/worktree-rm-pty.test-fixture.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { vi } from 'vitest' -import type { IPtyProvider } from '../../providers/pty-provider-contract' -import type { PtyProcessInfo } from '../../providers/pty-process-info' - -/** Only the provider's external effects are controlled; runtime teardown selects the sessions. */ -export function removalPtyProvider(initial: PtyProcessInfo[]) { - let processes = initial - const unused = async (): Promise => { - throw new Error('Unexpected PTY effect') - } - const shutdown = vi.fn(async (id) => { - processes = processes.filter((entry) => entry.id !== id) - }) - const provider: IPtyProvider = { - spawn: unused, - attach: unused, - write: () => {}, - writeWithSettlement: unused, - resize: () => {}, - shutdown, - sendSignal: unused, - getCwd: unused, - getInitialCwd: unused, - clearBuffer: unused, - resetInputModes: unused, - acknowledgeDataEvent: () => {}, - hasChildProcesses: async () => false, - getForegroundProcess: async () => null, - serialize: unused, - revive: unused, - listProcesses: async () => processes, - getDefaultShell: unused, - getProfiles: unused, - onData: () => () => {}, - onReplay: () => () => {}, - onExit: () => () => {} - } - return { provider, shutdown } -} diff --git a/src/main/runtime/rpc/ws-empty-payload-frame-write.test.ts b/src/main/runtime/rpc/ws-empty-payload-frame-write.test.ts deleted file mode 100644 index 4c773e482d8..00000000000 --- a/src/main/runtime/rpc/ws-empty-payload-frame-write.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { Socket } from 'node:net' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { WebSocket, WebSocketServer } from 'ws' - -/** Guard config/patches/ws@8.22.0.patch: empty writes can EFAULT under Electron on arm64 39-bit VA kernels, closing ping/pong connections with 1006. */ - -type Peer = { ws: WebSocket; writeLengths: number[] } - -const cleanups: (() => void)[] = [] - -afterEach(() => { - for (const cleanup of cleanups.splice(0)) { - cleanup() - } -}) - -function failEmptyWritesLikeArm64Electron(socket: Socket): number[] { - const writeLengths: number[] = [] - const write = socket.write.bind(socket) - // ws calls write(chunk, cb); Node treats a function encoding as the callback. - vi.spyOn(socket, 'write').mockImplementation((chunk, encoding, cb) => { - writeLengths.push(chunk.length) - if (chunk.length === 0) { - socket.destroy(Object.assign(new Error('write EFAULT'), { code: 'EFAULT' })) - return false - } - return write(chunk, encoding, cb) - }) - return writeLengths -} - -async function connectPair(): Promise<{ server: Peer; client: Peer }> { - const wss = new WebSocketServer({ host: '127.0.0.1', port: 0 }) - cleanups.push(() => wss.close()) - await new Promise((resolve) => wss.once('listening', resolve)) - const address = wss.address() - if (typeof address !== 'object' || address === null) { - throw new Error('WebSocketServer has no TCP address') - } - const { port } = address - - const serverPeer = new Promise((resolve) => { - wss.once('connection', (ws, request) => { - resolve({ ws, writeLengths: failEmptyWritesLikeArm64Electron(request.socket) }) - }) - }) - const clientWs = new WebSocket(`ws://127.0.0.1:${port}`) - cleanups.push(() => clientWs.terminate()) - let clientWriteLengths: number[] = [] - clientWs.once('upgrade', (response) => { - clientWriteLengths = failEmptyWritesLikeArm64Electron(response.socket) - }) - await new Promise((resolve, reject) => { - clientWs.once('open', () => resolve()) - clientWs.once('error', reject) - }) - const server = await serverPeer - return { server, client: { ws: clientWs, writeLengths: clientWriteLengths } } -} - -function sendCallback(): { - done: Promise - cb: (err?: Error | null) => void -} { - let cb: (err?: Error | null) => void = () => {} - const done = new Promise((resolve) => { - cb = vi.fn((err?: Error | null) => resolve(err)) - }) - return { done, cb } -} - -function closedCode(ws: WebSocket): Promise { - return new Promise((resolve) => ws.once('close', (code) => resolve(code))) -} - -describe('ws empty-payload frame writes', () => { - it('server heartbeat ping with no payload reaches the client and keeps the socket open', async () => { - const { server, client } = await connectPair() - const received = new Promise((resolve) => client.ws.once('ping', resolve)) - const { done, cb } = sendCallback() - - server.ws.ping(undefined, undefined, cb) - - expect(await done).toBeFalsy() - expect((await received).length).toBe(0) - // ws auto-pongs the client's empty ping back on the server's socket. - await new Promise((resolve) => server.ws.once('pong', () => resolve())) - expect(server.writeLengths).not.toContain(0) - expect(client.writeLengths).not.toContain(0) - expect(server.ws.readyState).toBe(WebSocket.OPEN) - expect(cb).toHaveBeenCalledTimes(1) - }) - - it('auto-pong to an empty client ping does not write an empty payload on the server', async () => { - const { server, client } = await connectPair() - const pong = new Promise((resolve) => client.ws.once('pong', resolve)) - - client.ws.ping() - - expect((await pong).length).toBe(0) - expect(server.writeLengths).not.toContain(0) - expect(client.writeLengths).not.toContain(0) - expect(server.ws.readyState).toBe(WebSocket.OPEN) - }) - - it('empty pong and empty text frames are delivered with exactly one callback each', async () => { - const { server, client } = await connectPair() - const pong = new Promise((resolve) => client.ws.once('pong', resolve)) - const message = new Promise((resolve) => - client.ws.once('message', (data: Buffer) => resolve(data.toString())) - ) - const pongCallback = sendCallback() - const sendCallbackState = sendCallback() - - server.ws.pong(undefined, undefined, pongCallback.cb) - server.ws.send('', sendCallbackState.cb) - - expect(await pongCallback.done).toBeFalsy() - expect(await sendCallbackState.done).toBeFalsy() - expect((await pong).length).toBe(0) - expect(await message).toBe('') - expect(pongCallback.cb).toHaveBeenCalledTimes(1) - expect(sendCallbackState.cb).toHaveBeenCalledTimes(1) - expect(server.writeLengths).not.toContain(0) - }) - - it('a close with no code completes the closing handshake instead of 1006', async () => { - const { server, client } = await connectPair() - const clientClosed = closedCode(client.ws) - - server.ws.close() - - expect(await clientClosed).toBe(1005) - expect(server.writeLengths).not.toContain(0) - expect(client.writeLengths).not.toContain(0) - }) -}) diff --git a/src/main/runtime/rpc/ws-network-source-guard.test.ts b/src/main/runtime/rpc/ws-network-source-guard.test.ts deleted file mode 100644 index 6630bded964..00000000000 --- a/src/main/runtime/rpc/ws-network-source-guard.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import 'node:net' -import { describe, expect, it, vi } from 'vitest' -import { PublicSourceRefusal } from './ws-network-source-guard' -import { OnLinkPrefixes, onLinkPrefixList } from './on-link-prefixes' - -describe('PublicSourceRefusal', () => { - it("admits global peers on the server's own interface prefixes", () => { - const onLink = new OnLinkPrefixes(() => - onLinkPrefixList({ - en0: [ - { - address: '2001:db8:aa:1::10', - netmask: 'ffff:ffff:ffff:ffff::', - family: 'IPv6', - mac: '00:00:00:00:00:01', - internal: false, - cidr: '2001:db8:aa:1::10/64', - scopeid: 0 - }, - { - address: '198.51.100.20', - netmask: '255.255.255.0', - family: 'IPv4', - mac: '00:00:00:00:00:01', - internal: false, - cidr: '198.51.100.20/24' - }, - { - // A misconfigured very wide prefix must not open the whole internet. - address: '2001:db8:bb::1', - netmask: 'ffff::', - family: 'IPv6', - mac: '00:00:00:00:00:01', - internal: false, - cidr: '2001:db8:bb::1/16', - scopeid: 0 - } - ] - }) - ) - const guard = new PublicSourceRefusal(onLink, () => 0, vi.fn()) - expect(guard.admit('2001:db8:aa:1:5054:ff:fe12:3456')).toBe(true) - expect(guard.admit('::ffff:198.51.100.77')).toBe(true) - expect(guard.admit('2001:db8:aa:2::1')).toBe(false) - expect(guard.admit('198.51.101.77')).toBe(false) - expect(guard.admit('2001:db8:cc::1')).toBe(false) - }) -}) diff --git a/src/main/runtime/rpc/ws-transport-accept-order.test.ts b/src/main/runtime/rpc/ws-transport-accept-order.test.ts deleted file mode 100644 index 3f8d944acad..00000000000 --- a/src/main/runtime/rpc/ws-transport-accept-order.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, describe, expect, it, vi } from 'vitest' -import WebSocket from 'ws' -import { WebSocketTransport } from './ws-transport' - -type TransportLifecycle = { - heartbeat: { timer: ReturnType | null } - heartbeatConnections: Set - handleConnection(ws: WebSocket): void - wss: { clients: Set } -} - -function createSocket(overrides: { ping?: () => void; terminate?: () => void } = {}): WebSocket { - return Object.assign(new EventEmitter(), { - OPEN: WebSocket.OPEN, - readyState: WebSocket.OPEN, - close: vi.fn(), - ping: vi.fn(overrides.ping), - send: vi.fn(), - terminate: vi.fn(overrides.terminate) - }) as unknown as WebSocket -} - -function createHarness(socket: WebSocket): { - lifecycle: TransportLifecycle - transport: WebSocketTransport -} { - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: 0, - heartbeatIntervalMs: 100, - preAuthTimeoutMs: 1_000 - }) - const lifecycle = transport as unknown as TransportLifecycle - lifecycle.wss = { clients: new Set([socket]) } - return { lifecycle, transport } -} - -afterEach(() => { - vi.useRealTimers() -}) - -describe('WebSocketTransport accepted socket ordering', () => { - it('observes a first-probe message and pong before deciding the socket is dead', async () => { - vi.useFakeTimers() - const events: string[] = [] - let firstProbeListeners: Record | undefined - let socket: WebSocket - socket = createSocket({ - ping: () => { - events.push('ping') - firstProbeListeners ??= Object.fromEntries( - ['pong', 'message', 'close', 'error'].map((event) => [event, socket.listenerCount(event)]) - ) - socket.emit('message', Buffer.from('ready'), false) - events.push('pong') - socket.emit('pong') - } - }) - const { lifecycle, transport } = createHarness(socket) - transport.onMessage((message) => events.push(String(message))) - - socket.once('open', () => events.push('open')) - socket.emit('open') - lifecycle.handleConnection(socket) - transport.setClientId(socket, 'client') - await vi.advanceTimersByTimeAsync(100) - - expect(firstProbeListeners).toEqual({ pong: 1, message: 1, close: 1, error: 1 }) - expect(events.slice(0, 4)).toEqual(['open', 'ping', 'ready', 'pong']) - expect(socket.terminate).not.toHaveBeenCalled() - expect(lifecycle.heartbeatConnections.size).toBe(1) - expect(vi.getTimerCount()).toBe(1) - - events.push('close') - socket.emit('close') - - expect(events.at(-1)).toBe('close') - expect(lifecycle.heartbeatConnections.size).toBe(0) - expect(lifecycle.heartbeat.timer).toBeNull() - expect(vi.getTimerCount()).toBe(0) - expect( - ['pong', 'message', 'close', 'error'].map((event) => socket.listenerCount(event)) - ).toEqual([0, 0, 0, 0]) - }) - - it('reaps an unresponsive accepted socket once consecutive probes go unanswered', async () => { - vi.useFakeTimers() - const events: string[] = [] - let socket: WebSocket - socket = createSocket({ - ping: () => events.push('ping'), - terminate: () => { - events.push('close') - socket.emit('close') - } - }) - const { lifecycle, transport } = createHarness(socket) - - socket.once('open', () => events.push('open')) - socket.emit('open') - lifecycle.handleConnection(socket) - transport.setClientId(socket, 'client') - expect(socket.terminate).not.toHaveBeenCalled() - // A single silent interval is not evidence: the socket is re-probed, not reaped. - await vi.advanceTimersByTimeAsync(100) - expect(socket.terminate).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(299) - expect(socket.terminate).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(1) - - expect(socket.terminate).toHaveBeenCalledTimes(1) - expect(events).toEqual(['open', 'ping', 'ping', 'ping', 'close']) - expect(lifecycle.heartbeatConnections.size).toBe(0) - expect(lifecycle.heartbeat.timer).toBeNull() - expect(vi.getTimerCount()).toBe(0) - }) - - it('keeps later sockets on the shared cadence and reaps them on the shared budget', async () => { - vi.useFakeTimers() - vi.setSystemTime(0) - const firstPingTimes: number[] = [] - let firstSocket: WebSocket - firstSocket = createSocket({ - ping: () => { - firstPingTimes.push(Date.now()) - firstSocket.emit('pong') - } - }) - const { lifecycle, transport } = createHarness(firstSocket) - - lifecycle.handleConnection(firstSocket) - transport.setClientId(firstSocket, 'first-client') - const sharedTimer = lifecycle.heartbeat.timer - expect(firstPingTimes).toEqual([]) - - await vi.advanceTimersByTimeAsync(50) - const laterPingTimes: number[] = [] - const laterReapTimes: number[] = [] - let laterSocket: WebSocket - laterSocket = createSocket({ - ping: () => laterPingTimes.push(Date.now()), - terminate: () => { - laterReapTimes.push(Date.now()) - laterSocket.emit('close') - } - }) - lifecycle.wss.clients.add(laterSocket) - lifecycle.handleConnection(laterSocket) - - expect(lifecycle.heartbeat.timer).toBe(sharedTimer) - expect(laterPingTimes).toEqual([]) - expect(vi.getTimerCount()).toBe(2) - - await vi.advanceTimersByTimeAsync(50) - expect(laterPingTimes).toEqual([]) - expect(laterSocket.terminate).not.toHaveBeenCalled() - - transport.setClientId(laterSocket, 'later-client') - await vi.advanceTimersByTimeAsync(100) - expect(laterPingTimes).toEqual([200]) - - // Re-probed on every sweep while its misses bank, so a recovered path can answer immediately. - await vi.advanceTimersByTimeAsync(299) - expect(laterPingTimes).toEqual([200, 300, 400]) - expect(laterSocket.terminate).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(1) - expect(laterSocket.terminate).toHaveBeenCalledTimes(1) - expect(laterReapTimes).toEqual([500]) - expect(firstPingTimes).toEqual([100, 200, 300, 400, 500]) - expect( - ['pong', 'message', 'close', 'error'].map((event) => laterSocket.listenerCount(event)) - ).toEqual([0, 0, 0, 0]) - - firstSocket.emit('close') - expect(lifecycle.heartbeatConnections.size).toBe(0) - expect(lifecycle.heartbeat.timer).toBeNull() - expect(vi.getTimerCount()).toBe(0) - }) - - it('finalizes an accepted socket when the first probe reports an error', async () => { - vi.useFakeTimers() - const events: string[] = [] - let socket: WebSocket - socket = createSocket({ - ping: () => { - events.push('ping', 'error') - socket.emit('error', new Error('probe failed')) - } - }) - const { lifecycle, transport } = createHarness(socket) - - socket.once('open', () => events.push('open')) - socket.emit('open') - lifecycle.handleConnection(socket) - transport.setClientId(socket, 'client') - await vi.advanceTimersByTimeAsync(100) - events.push('close') - socket.emit('close') - - expect(events.slice(0, 4)).toEqual(['open', 'ping', 'error', 'close']) - expect(socket.close).toHaveBeenCalledTimes(1) - expect(lifecycle.heartbeatConnections.size).toBe(0) - expect(lifecycle.heartbeat.timer).toBeNull() - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/main/runtime/rpc/ws-transport-static-web.test.ts b/src/main/runtime/rpc/ws-transport-static-web.test.ts deleted file mode 100644 index 6918cc6d977..00000000000 --- a/src/main/runtime/rpc/ws-transport-static-web.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { WebSocketTransport } from './ws-transport' - -describe('WebSocketTransport static web client', () => { - const transports: WebSocketTransport[] = [] - - afterEach(async () => { - await Promise.all(transports.map((t) => t.stop().catch(() => {}))) - transports.length = 0 - }) - - function createStaticTransport(staticRoot: string): WebSocketTransport { - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: 0, - staticRoot - }) - transports.push(transport) - return transport - } - - it('serves the built web client from the same server', async () => { - const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) - mkdirSync(join(staticRoot, 'assets')) - writeFileSync(join(staticRoot, 'web-index.html'), 'web') - writeFileSync(join(staticRoot, 'assets', 'app.js'), 'console.log("web")') - const transport = createStaticTransport(staticRoot) - - await transport.start() - - const indexResponse = await fetch(`http://127.0.0.1:${transport.resolvedPort}/web-index.html`) - expect(indexResponse.status).toBe(200) - expect(indexResponse.headers.get('content-type')).toContain('text/html') - await expect(indexResponse.text()).resolves.toBe('web') - - const assetResponse = await fetch(`http://127.0.0.1:${transport.resolvedPort}/assets/app.js`) - expect(assetResponse.status).toBe(200) - expect(assetResponse.headers.get('cache-control')).toContain('immutable') - await expect(assetResponse.text()).resolves.toBe('console.log("web")') - }) - - it('serves web assets when a reverse-proxy path prefix is forwarded', async () => { - const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) - mkdirSync(join(staticRoot, 'assets')) - writeFileSync(join(staticRoot, 'web-index.html'), '') - writeFileSync(join(staticRoot, 'assets', 'app.js'), 'console.log("prefixed")') - const transport = createStaticTransport(staticRoot) - - await transport.start() - - const indexResponse = await fetch( - `http://127.0.0.1:${transport.resolvedPort}/orca/web-index.html` - ) - expect(indexResponse.status).toBe(200) - await expect(indexResponse.text()).resolves.toBe('') - - const assetResponse = await fetch( - `http://127.0.0.1:${transport.resolvedPort}/orca/assets/app.js` - ) - expect(assetResponse.status).toBe(200) - await expect(assetResponse.text()).resolves.toBe('console.log("prefixed")') - }) - - // #30100: with no request listener Node never answered plain HTTP, so curl hung forever. - it('answers plain HTTP with 404 when it has no web client to serve', async () => { - const transport = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) - transports.push(transport) - - await transport.start() - - for (const path of ['/', '/web-index.html', '/does-not-exist']) { - const response = await fetch(`http://127.0.0.1:${transport.resolvedPort}${path}`, { - signal: AbortSignal.timeout(5_000) - }) - expect(response.status).toBe(404) - } - }) - - it('does not expose arbitrary files from the static root', async () => { - const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) - writeFileSync(join(staticRoot, 'package.json'), '{}') - const transport = createStaticTransport(staticRoot) - - await transport.start() - - const response = await fetch(`http://127.0.0.1:${transport.resolvedPort}/package.json`) - expect(response.status).toBe(404) - }) - - it('rejects encoded Windows separators in static paths', async () => { - const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) - mkdirSync(join(staticRoot, 'assets')) - writeFileSync(join(staticRoot, 'package.json'), '{}') - const transport = createStaticTransport(staticRoot) - - await transport.start() - - const response = await fetch( - `http://127.0.0.1:${transport.resolvedPort}/assets/..%5Cpackage.json` - ) - expect(response.status).toBe(400) - }) -}) diff --git a/src/main/runtime/rpc/ws-transport.test.ts b/src/main/runtime/rpc/ws-transport.test.ts deleted file mode 100644 index cab47b68b60..00000000000 --- a/src/main/runtime/rpc/ws-transport.test.ts +++ /dev/null @@ -1,304 +0,0 @@ -import 'node:events' -import { connect } from 'node:net' -import { describe, expect, it, afterEach, vi } from 'vitest' -import WebSocket from 'ws' -import { WebSocketTransport } from './ws-transport' -import './node-websocket-lifecycle' - -describe('WebSocketTransport', () => { - const transports: WebSocketTransport[] = [] - - afterEach(async () => { - await Promise.all(transports.map((t) => t.stop().catch(() => {}))) - transports.length = 0 - }) - - async function createTransport( - handler?: (msg: string, reply: (response: string) => void) => void, - options: { preAuthTimeoutMs?: number } = {} - ) { - const transport = new WebSocketTransport({ - host: '127.0.0.1', - // Port 0 reserves atomically; probed free ports can race. - port: 0, - preAuthTimeoutMs: options.preAuthTimeoutMs - }) - if (handler) { - transport.onMessage(handler) - } - transports.push(transport) - return { transport } - } - - function connectWs(target: number | WebSocketTransport): Promise { - const port = typeof target === 'number' ? target : target.resolvedPort - return new Promise((resolve, reject) => { - const ws = new WebSocket(`ws://127.0.0.1:${port}`) - ws.once('open', () => resolve(ws)) - ws.once('error', reject) - }) - } - - it('rejects oversized messages by closing the connection', async () => { - const { transport } = await createTransport() - - await transport.start() - - const ws = await connectWs(transport) - - const oversized = 'x'.repeat(1024 * 1024 + 100) - - await new Promise((resolve) => { - ws.once('close', () => resolve()) - ws.send(oversized) - }) - }) - - it('terminates every active connection for a revoked client id', async () => { - const { transport } = await createTransport() - const closedClientIds: (string | null)[] = [] - transport.onConnectionClose((clientId) => { - closedClientIds.push(clientId) - }) - - await transport.start() - - const clients = await Promise.all([connectWs(transport), connectWs(transport)]) - const wss = (transport as unknown as { wss: { clients: Set } }).wss - for (const client of wss.clients) { - transport.setClientId(client, 'device-token') - } - - expect(transport.terminateClientConnections('device-token')).toBe(2) - - await Promise.all( - clients.map( - (client) => - new Promise((resolve) => { - if (client.readyState === client.CLOSED) { - resolve() - return - } - client.once('close', () => resolve()) - }) - ) - ) - - await expect - .poll(() => closedClientIds, { timeout: 2_000, interval: 20 }) - .toEqual(['device-token', 'device-token']) - }) - - it('reaps silent pre-auth sockets so they cannot hold the connection cap', async () => { - const { transport } = await createTransport(undefined, { preAuthTimeoutMs: 50 }) - await transport.start() - - const clients = await Promise.all(Array.from({ length: 32 }, () => connectWs(transport))) - await Promise.all( - clients.map( - (client) => - new Promise((resolve) => { - if (client.readyState === client.CLOSED) { - resolve() - return - } - client.once('close', () => resolve()) - }) - ) - ) - - const liveClient = await connectWs(transport) - expect(liveClient.readyState).toBe(liveClient.OPEN) - liveClient.close() - }) - - it('drops a source the guard refuses before any HTTP or upgrade handling', async () => { - const admit = vi.fn(() => false) - const transport = new WebSocketTransport({ host: '127.0.0.1', port: 0, sourceGuard: { admit } }) - transports.push(transport) - await transport.start() - - await expect(connectWs(transport)).rejects.toThrow() - expect(admit).toHaveBeenCalledWith('127.0.0.1') - }) - - it('stops while an HTTP client holds an unanswered request open', async () => { - const transport = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) - transports.push(transport) - await transport.start() - const socket = connect(transport.resolvedPort, '127.0.0.1') - await new Promise((resolve) => socket.once('connect', () => resolve())) - socket.on('error', () => {}) - // Why: the server's automatic 100 Continue proves the request is parsed and in flight. - const continued = new Promise((resolve) => socket.once('data', () => resolve())) - socket.write( - 'POST /unanswered HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 1\r\nExpect: 100-continue\r\n\r\n' - ) - await continued - - await transport.stop() - socket.destroy() - }) - - it('does not wait for an unresponsive client close handshake during stop', async () => { - const { transport } = await createTransport() - await transport.start() - const ws = await connectWs(transport) - const underlying = (ws as unknown as { _socket: { pause: () => void } })._socket - underlying.pause() - - const stopPromise = transport.stop() - const outcome = await Promise.race([ - stopPromise.then(() => 'stopped' as const), - new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 100)) - ]) - - if (outcome === 'pending') { - ws.terminate() - await stopPromise - } - - expect(outcome).toBe('stopped') - }) - - it('falls back to OS-assigned port when preferred port is in use', async () => { - const { transport: first } = await createTransport() - await first.start() - const occupiedPort = first.resolvedPort - - // A conflicting port must fall back rather than fail startup. - const second = new WebSocketTransport({ - host: '127.0.0.1', - port: occupiedPort - }) - transports.push(second) - - await second.start() - - expect(second.resolvedPort).not.toBe(occupiedPort) - expect(second.resolvedPort).toBeGreaterThan(0) - - const ws = await connectWs(second.resolvedPort) - ws.close() - }) - - it('reaps a half-open client that stops responding to pings', async () => { - // Half-open peers otherwise occupy mobile slots for ~2h; verify heartbeat teardown through the production capacity-releasing close handler. - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: 0, - heartbeatIntervalMs: 50 - }) - transport.onMessage(() => {}) - transports.push(transport) - - let serverClosed = false - transport.onConnectionClose(() => { - serverClosed = true - }) - - // Stamp accepted sockets before startup so onConnectionClose sees their client ids. - await transport.start() - - const ws = await connectWs(transport) - // Pause TCP to block auto-pong flushing and model iOS background half-opens. - const underlying = (ws as unknown as { _socket: { pause: () => void } })._socket - underlying.pause() - - // Why: we need a clientId on the ws so onConnectionClose actually - // fires. The transport sets it lazily via setClientId in production - // (after auth); in this test we don't run auth, so reach in. - const wss = (transport as unknown as { wss: { clients: Set<{ readyState: number }> } }).wss - for (const c of wss.clients) { - transport.setClientId(c as never, 'test-client') - } - - await expect.poll(() => serverClosed, { timeout: 2_000, interval: 25 }).toBe(true) - expect(wss.clients.size).toBe(0) - }, 5_000) - - // Persist fallback endpoints so paired phones remain reachable across restarts (STA-1511). - describe('fallback port stability', () => { - async function reserveFreePort(): Promise { - const scratch = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) - await scratch.start() - const port = scratch.resolvedPort - await scratch.stop() - return port - } - - it('binds the persisted fallback port even when the preferred port is free', async () => { - // Fallback pairings must survive even when the preferred port becomes free (STA-1511). - const preferredPort = await reserveFreePort() - const fallbackPort = await reserveFreePort() - - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: preferredPort, - fallbackPort - }) - transports.push(transport) - await transport.start() - expect(transport.resolvedPort).toBe(fallbackPort) - }) - - it('binds the preferred port first when preferPinnedPort is set and both are free', async () => { - // An explicit serve --port pin must precede stale persisted fallback (#8535). - const preferredPort = await reserveFreePort() - const fallbackPort = await reserveFreePort() - - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: preferredPort, - fallbackPort, - preferPinnedPort: true - }) - transports.push(transport) - await transport.start() - expect(transport.resolvedPort).toBe(preferredPort) - }) - - it('falls through to the preferred port when the fallback bind fails with a non-EADDRINUSE error', async () => { - // Persisted ports may enter Windows Hyper-V reserved ranges; EACCES must fall back to preferred, not disable transport. - const preferredPort = await reserveFreePort() - const fallbackPort = await reserveFreePort() - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: preferredPort, - fallbackPort - }) - transports.push(transport) - const withListen = transport as unknown as { tryListen(port: number): Promise } - const realTryListen = withListen.tryListen.bind(transport) - withListen.tryListen = (port: number) => - port === fallbackPort - ? Promise.reject(Object.assign(new Error('listen EACCES'), { code: 'EACCES' })) - : realTryListen(port) - - await transport.start() - expect(transport.resolvedPort).toBe(preferredPort) - }) - - it('tries the deterministic ladder before an OS-assigned port (#15490)', async () => { - const transport = new WebSocketTransport({ - host: '127.0.0.1', - port: 6768, - fallbackPort: 62944, - fallbackLadder: [6769, 6770, 6771] - }) - transports.push(transport) - const attempted: number[] = [] - const withListen = transport as unknown as { tryListen(port: number): Promise } - withListen.tryListen = async (port: number) => { - attempted.push(port) - if (port !== 6770) { - throw Object.assign(new Error('listen EADDRINUSE'), { code: 'EADDRINUSE' }) - } - } - - await transport.start() - expect(attempted).toEqual([62944, 6768, 6769, 6770]) - expect(transport.persistedFallbackFailed).toBe(true) - }) - }) -}) diff --git a/src/main/runtime/rpc/ws-unauthenticated-source-cap.test.ts b/src/main/runtime/rpc/ws-unauthenticated-source-cap.test.ts deleted file mode 100644 index 1f93c78c661..00000000000 --- a/src/main/runtime/rpc/ws-unauthenticated-source-cap.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { Socket } from 'node:net' -import { describe, expect, it, vi } from 'vitest' -import { UnauthenticatedSourceCap } from './ws-unauthenticated-source-cap' - -function peer(remoteAddress: string): Socket & EventEmitter { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the cap reads only remoteAddress and close. - return Object.assign(new EventEmitter(), { remoteAddress }) as unknown as Socket & EventEmitter -} - -describe('UnauthenticatedSourceCap', () => { - it('refuses a source past the cap until one of its sockets closes', () => { - const log = vi.fn() - const cap = new UnauthenticatedSourceCap(2, () => 0, log) - const first = peer('203.0.113.9') - expect(cap.admit(first)).toBe(true) - expect(cap.admit(peer('::ffff:203.0.113.9'))).toBe(true) - expect(cap.admit(peer('203.0.113.9'))).toBe(false) - expect(cap.admit(peer('203.0.113.9'))).toBe(false) - expect(cap.admit(peer('203.0.113.10'))).toBe(true) - expect(log).toHaveBeenCalledOnce() - - first.emit('close') - expect(cap.admit(peer('203.0.113.9'))).toBe(true) - }) - - it('counts an IPv6 /64 as one source', () => { - const cap = new UnauthenticatedSourceCap(1, () => 0, vi.fn()) - expect(cap.admit(peer('2001:db8:1:2::1'))).toBe(true) - expect(cap.admit(peer('2001:db8:1:2::2'))).toBe(false) - expect(cap.admit(peer('2001:db8:1:3::1'))).toBe(true) - }) - - it('frees the slot on authentication and admits a source holding an authenticated socket', () => { - const cap = new UnauthenticatedSourceCap(1, () => 0, vi.fn()) - const client = peer('192.168.1.20') - expect(cap.admit(client)).toBe(true) - cap.noteAuthenticated(client) - expect(cap.admit(peer('192.168.1.20'))).toBe(true) - // Past the cap, but this source has already proven a credential. - expect(cap.admit(peer('192.168.1.20'))).toBe(true) - - client.emit('close') - expect(cap.admit(peer('192.168.1.20'))).toBe(false) - }) -}) diff --git a/src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts b/src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts index 8117c22bc65..54ccb131e75 100644 --- a/src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts +++ b/src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import type { RuntimeCreateAgentSessionRequest } from '../../../../shared/agent-session/agent-session-host-authority' import { OrcaRuntimeService } from '../../orca-runtime' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' function operationId(now = Date.now(), nonce = '0123456789abcdef0123456789abcdef'): string { return `${now}-${nonce}` diff --git a/src/main/runtime/session-graph/session-graph-authority.ts b/src/main/runtime/session-graph/session-graph-authority.ts index 13b1e4c30d0..3aaf7892048 100644 --- a/src/main/runtime/session-graph/session-graph-authority.ts +++ b/src/main/runtime/session-graph/session-graph-authority.ts @@ -123,6 +123,20 @@ export abstract class OrcaRuntimeWithTransitionGraphReloadToTerminalState extend } } + /** Null when no window is attached: there is no renderer to fence. A booting or reloading one throws. */ + protected captureRendererGraphFence(): number | null { + return this.authoritativeWindowId === null ? null : this.captureReadyGraphEpoch() + } + + protected assertRendererGraphFence(fence: number | null): void { + if (fence !== null) { + this.assertStableReadyGraph(fence) + } else if (this.authoritativeWindowId !== null) { + // A window attached mid-operation; its renderer owns the graph again. + throw new Error('runtime_unavailable') + } + } + protected resolveFolderWorkspaceConnectionId(workspace: FolderWorkspace): string | null { const repos = this.store?.getRepos() ?? [] const projectGroups = this.store?.getProjectGroups?.() ?? [] @@ -238,6 +252,29 @@ export abstract class OrcaRuntimeWithTransitionGraphReloadToTerminalState extend /** Reconcile client-hosted pages per paired device; one attached client cannot account for another's pages. */ markClientHostedPagesReconciled(pairedDeviceId: string): void { - this.clientHostedPageReconciliation.markReconciled(pairedDeviceId) + const held = this.clientHostedPageReconciliation.markReconciled(pairedDeviceId) + if (!held?.size) { + return + } + const candidates = this.selectMobileSessionTabsListeners(undefined, pairedDeviceId) + if (candidates.length === 0) { + return + } + const deliver = this.createMobileSessionTabsDelivery() + for (const worktree of held) { + const selected = this.selectMobileSessionTabsListeners(worktree, pairedDeviceId, candidates) + if (selected.length === 0) { + continue + } + deliver( + this.getMobileSessionTabsForWorktree(worktree, pairedDeviceId, { + includeAgentSenders: false + }), + ++this.mobileSessionTabsChangeSequence, + pairedDeviceId, + selected, + 'reconciliation' + ) + } } } diff --git a/src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts b/src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts deleted file mode 100644 index a8b1b6d5b39..00000000000 --- a/src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - withDurableRuntimeStore, - withRuntimePaneAdmission -} from '../../orca-runtime-tests/runtime-durable-store-fixture' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/runtime-mobile-session-tab-contracts' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' -import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const REPO_ID = 'repo-1' -const WORKTREE_ID = `${REPO_ID}::/workspace` -const TAB_ID = 'tab-1' -const SOURCE_LEAF_ID = '11111111-1111-4111-8111-111111111111' -const SOURCE_PTY_ID = 'pty-source' -const SPLIT_PTY_ID = 'pty-split' - -function sourceLayout(): TerminalLayoutSnapshot { - return { - root: { type: 'leaf', leafId: SOURCE_LEAF_ID }, - activeLeafId: SOURCE_LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [SOURCE_LEAF_ID]: SOURCE_PTY_ID } - } -} - -function persistedSession(): WorkspaceSessionState { - return { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: TAB_ID, - ptyId: SOURCE_PTY_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { [TAB_ID]: sourceLayout() } - } -} - -function surface( - leafId: string, - ptyId: string | null, - parentLayout: TerminalLayoutSnapshot -): RuntimeMobileSessionTerminalTab { - return { - type: 'terminal', - id: `${TAB_ID}::${leafId}`, - parentTabId: TAB_ID, - leafId, - ptyId, - title: 'Terminal', - parentLayout, - isActive: leafId === SOURCE_LEAF_ID - } -} - -/** The window's own publication: one surface per pane it has mounted. */ -function windowSnapshot( - version: number, - surfaces: RuntimeMobileSessionTerminalTab[] -): RuntimeMobileSessionTabsSnapshot { - return { - worktree: WORKTREE_ID, - publicationEpoch: 'window', - snapshotVersion: version, - activeGroupId: 'group-1', - activeTabId: `${TAB_ID}::${SOURCE_LEAF_ID}`, - activeTabType: 'terminal', - tabGroups: [{ id: 'group-1', activeTabId: TAB_ID, tabOrder: [TAB_ID] }], - tabs: surfaces - } -} - -function windowGraph( - leaves: { leafId: string; ptyId: string | null }[], - snapshot: RuntimeMobileSessionTabsSnapshot -) { - return { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: SOURCE_LEAF_ID, - layout: null - } - ], - leaves: leaves.map(({ leafId, ptyId }, index) => ({ - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - leafId, - paneRuntimeId: index + 1, - ptyId - })), - mobileSessionTabs: [snapshot] - } -} - -/** What the window's list holds for main's new pane when it lands, after main's own. */ -type WindowListing = 'pane-without-terminal' | 'no-new-pane' - -function setup(listing: WindowListing, pinned = false) { - let session = persistedSession() - if (pinned) { - session = { - ...session, - tabsByWorktree: { - [WORKTREE_ID]: [{ ...session.tabsByWorktree[WORKTREE_ID]![0]!, isPinned: true }] - } - } - } - // The Store tells its write listeners after each write, as main's terminal list relies on. - const written = new Set<(hostId: ExecutionHostId | null) => void>() - const write = (next: WorkspaceSessionState): void => { - session = next - for (const listener of written) { - listener('local') - } - } - const repo = { - id: REPO_ID, - path: '/workspace', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 - } - const store = withDurableRuntimeStore( - withRuntimePaneAdmission({ - getRepos: () => [repo], - getRepo: (id: string) => (id === REPO_ID ? repo : undefined), - getWorkspaceSession: () => session, - getWorkspaceSessionHostIds: (): ExecutionHostId[] => ['local'], - onWorkspaceSessionWritten: (listener: (hostId: ExecutionHostId | null) => void) => { - written.add(listener) - return () => written.delete(listener) - }, - setWorkspaceSession: (next: WorkspaceSessionState) => { - write(next) - }, - // Main's own layout close, as the Store applies it. - applyLayoutCommand: async (command: LayoutCommand, hostIds: readonly ExecutionHostId[]) => { - const change = applyCommandToSession(hostIds[0]!, session, command) - if (change.session) { - write(change.session) - } - return change.value - }, - persistPtyBinding: async () => true, - flushOrThrow: () => undefined - }) - ) - const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: WORKTREE_ID, - path: '/workspace', - connectionId: null, - repo, - folderWorkspace: null - })) - }) - runtime.setPtyController({ - // The real spawn writes the new pane's binding into main's session; the fake does the same. - spawn: vi.fn(async (args: { tabId?: string; leafId?: string }) => { - const layout = session.terminalLayoutsByTabId[args.tabId!]! - write({ - ...session, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - [args.tabId!]: { - ...layout, - ptyIdsByLeafId: { ...layout.ptyIdsByLeafId, [args.leafId!]: SPLIT_PTY_ID } - } - } - }) - return { id: SPLIT_PTY_ID } - }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - // The window's list lags main: built before main's first frame (no new pane), or from it (the - // pane, but not yet its terminal). Either lands after main's own listing. - const revealTerminalSession = vi.fn(async (_worktreeId: string, args: { leafId?: string }) => { - const newLeafId = args.leafId! - const twoPanes = { - ...sourceLayout(), - root: { - type: 'split' as const, - direction: 'vertical' as const, - first: { type: 'leaf' as const, leafId: SOURCE_LEAF_ID }, - second: { type: 'leaf' as const, leafId: newLeafId } - } - } - runtime.syncWindowGraph( - 1, - windowGraph( - [{ leafId: SOURCE_LEAF_ID, ptyId: SOURCE_PTY_ID }], - windowSnapshot( - 2, - listing === 'no-new-pane' - ? [surface(SOURCE_LEAF_ID, SOURCE_PTY_ID, sourceLayout())] - : [surface(SOURCE_LEAF_ID, SOURCE_PTY_ID, twoPanes), surface(newLeafId, null, twoPanes)] - ) - ) - ) - return { tabId: TAB_ID } - }) - const notifier = { - revealTerminalSession, - splitTerminal: vi.fn(), - closeTerminalTab: vi.fn(async () => undefined) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the split and the tab close call only these notices. - runtime.setNotifier(notifier as never) - runtime.syncWindowGraph( - 1, - windowGraph( - [{ leafId: SOURCE_LEAF_ID, ptyId: SOURCE_PTY_ID }], - windowSnapshot(1, [surface(SOURCE_LEAF_ID, SOURCE_PTY_ID, sourceLayout())]) - ) - ) - runtime.registerPty(SOURCE_PTY_ID, WORKTREE_ID, null, { tabId: TAB_ID, leafId: SOURCE_LEAF_ID }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: both members are declared on OrcaRuntimeService's inheritance chain. - const internals = runtime as unknown as { - issuePtyHandle: (pty: unknown) => string - ptysById: Map - } - // A terminal listing can name the source by its terminal, so the split runs main-side. - const handle = internals.issuePtyHandle(internals.ptysById.get(SOURCE_PTY_ID)) - // Main's layout drops the pane, as a close of it would. - const dropPane = (leafId: string): void => { - const layout = session.terminalLayoutsByTabId[TAB_ID]! - const { [leafId]: _dropped, ...ptyIdsByLeafId } = layout.ptyIdsByLeafId ?? {} - write({ - ...session, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - [TAB_ID]: { ...layout, root: sourceLayout().root, ptyIdsByLeafId } - } - }) - } - return { runtime, handle, dropPane } -} - -describe("a tab close by a main-side split's handle while the window's list lags, in a layout-owner build", () => { - it.each(['pane-without-terminal', 'no-new-pane'])( - "closes the tab on main's own record of the pane (%s)", - async (listing) => { - const { runtime, handle } = setup(listing) - - const split = await runtime.splitTerminal(handle, { direction: 'vertical' }) - - await expect(runtime.closeTerminalTab(split.handle)).resolves.toMatchObject({ - tabId: TAB_ID, - closeMode: 'tab' - }) - } - ) - - it('still refuses once main no longer holds the pane', async () => { - const { runtime, handle, dropPane } = setup('no-new-pane') - - const split = await runtime.splitTerminal(handle, { direction: 'vertical' }) - dropPane(split.leafId!) - - await expect(runtime.closeTerminalTab(split.handle)).rejects.toThrow('terminal_handle_stale') - }) -}) - -describe('a CLI close of a pinned tab main owns, in a layout-owner build', () => { - it('refuses the tab close and keeps the tab, as the window-era close did', async () => { - const { runtime, handle } = setup('no-new-pane', true) - - await expect(runtime.closeTerminalTab(handle)).rejects.toThrow('terminal_tab_pinned') - await expect(runtime.closeTerminal(handle)).rejects.toThrow('terminal_tab_pinned') - expect( - runtime.getWorkspaceSessionForWorktree(WORKTREE_ID)?.tabsByWorktree[WORKTREE_ID] - ).toHaveLength(1) - }) -}) diff --git a/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts b/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts index 3b0b7693faa..961fb4eda4d 100644 --- a/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts +++ b/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts @@ -14,7 +14,7 @@ import { } from './mobile-session-tab-close-outcome' import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' import type { RuntimeEdgeCommandSurface } from '../../construction/runtime-edge-command-controller' -import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' +import { rendererPublicationThrottle } from '../../../window/visibility/renderer-publication-throttle' import { retireHeadlessMobileSessionEditorTab } from '../../session-tabs/headless-editor-tabs' import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' @@ -47,14 +47,14 @@ export abstract class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWi tabId: string, options: MobileSessionTabCloseOptions = {} ): Promise { - const graphEpoch = options.clientNavigationId ? this.captureReadyGraphEpoch() : null + const graphFence = options.clientNavigationId ? this.captureRendererGraphFence() : undefined const explicitWorktreeId = this.getExplicitSessionWorktreeIdSelector(worktreeSelector) const worktreeId = explicitWorktreeId ?? (await this.resolveWorkspaceSelector(worktreeSelector)).id this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) const observedPtyIds = await this.refreshMobileSessionPtyRecords() - if (graphEpoch !== null) { - this.assertStableReadyGraph(graphEpoch) + if (graphFence !== undefined) { + this.assertRendererGraphFence(graphFence) } this.restoreLivePairedRendererSessionOwnedMobileTerminals(worktreeId) const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId) diff --git a/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts b/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts index 90d665e1af0..3475a48d110 100644 --- a/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts +++ b/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts @@ -26,6 +26,14 @@ export abstract class OrcaRuntimeWithHasLiveOrPersistedServeOrSshOwnedPtyBinding ...args: Parameters ): ReturnType + protected abstract captureRendererGraphFence( + ...args: Parameters + ): ReturnType + + protected abstract assertRendererGraphFence( + ...args: Parameters + ): ReturnType + protected abstract resolvePtyTabCloseSurfaceAuthority( ...args: Parameters ): ReturnType diff --git a/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts index a191155093d..5be62aad56f 100644 --- a/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts @@ -22,7 +22,7 @@ import { import type { TerminalPaneCloseTarget, TerminalSurfaceCloseTarget -} from '../../../../shared/workspace-layout/terminal-surface-close-target' +} from '../../../../shared/workspace-layout/terminal-surfaces/terminal-surface-close-target' import { retireTerminalSurfacesFromSnapshot } from '../../terminal/surface/mobile-session-terminal-retirement' import type { PtyControllerInventory } from '../../terminal/lifecycle/runtime-pty-controller-contract' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' @@ -51,6 +51,7 @@ export abstract class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs exten ].filter((tab) => !rendererPageIds.has(tab.browserPageId)) : [] const publishedServerTabs = serverTabs.map((tab) => { + const navigation = this.agentBrowserBridge?.getPageNavigationState(tab.browserPageId) const persistedProps = this.getPersistedUnifiedSessionTabProps( worktreeId, this.serveBrowserTabs.unifiedTabId(worktreeId, tab.browserPageId) @@ -64,9 +65,9 @@ export abstract class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs exten browserPageId: tab.browserPageId, browserProfileId: tab.profileId ?? undefined, url: tab.url || 'about:blank', - loading: false, - canGoBack: false, - canGoForward: false, + loading: navigation?.loading ?? false, + canGoBack: navigation?.canGoBack ?? false, + canGoForward: navigation?.canGoForward ?? false, faviconUrl: this.agentBrowserBridge?.getRemoteTabFaviconUrl(tab.browserPageId) ?? null, loadError: tab.loadError ?? undefined, certificateFailure: tab.certificateFailure ?? undefined, diff --git a/src/main/runtime/session-lifecycle/projection/mobile-session-tab-merge.ts b/src/main/runtime/session-lifecycle/projection/mobile-session-tab-merge.ts index 9c24712c556..c6d4a03da47 100644 --- a/src/main/runtime/session-lifecycle/projection/mobile-session-tab-merge.ts +++ b/src/main/runtime/session-lifecycle/projection/mobile-session-tab-merge.ts @@ -4,7 +4,7 @@ import type { } from '../../../../shared/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionTabGroup } from '../../../../shared/runtime-session-contracts' import type { TabGroupLayoutNode } from '../../../../shared/tab-types' -import { collectTabGroupLayoutGroupIds } from '../../../../shared/workspace-layout/tab-group-moves' +import { collectTabGroupLayoutGroupIds } from '../../../../shared/workspace-layout/tab-groups/tab-group-moves' import { isStructuredAgentSessionHostTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' import { collectHeadlessParentTabOrder, diff --git a/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts b/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts index fb15a6994a1..c9cf1c1696c 100644 --- a/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts @@ -21,7 +21,7 @@ import { sshRemotePtyLeaseAllowsReattach } from '../../../../shared/ssh-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { SSH_PANE_RECOVERY_GRACE_MS } from '../../terminal/recovery/ssh-pane-recovery-window' -import { findTerminalTabIdForLeaf } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { findTerminalTabIdForLeaf } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import { isServeMintedPtySessionId } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' export abstract class OrcaRuntimeWithReconcileHeadlessMobileSessionBrowserTabs extends OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession { diff --git a/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts b/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts index 24b4762a578..40dee62d413 100644 --- a/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts +++ b/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts @@ -29,7 +29,7 @@ import type { NewerDaemonReopenResult } from '../../../../shared/newer-daemon-ho import type { WorkspaceLayoutStream } from '../../terminal/surface/workspace-layout-stream' import { getDaemonHistoryDir } from '../../../daemon/launch/daemon-launch-paths' import { HistoryReader } from '../../../daemon/history/restoration/history-reader' -import { servesWslMovedPaneHistory } from '../../../orcad/orcad-migration-wsl-destination' +import { servesWslMovedPaneHistory } from '../../../orcad/migration/orcad-migration-wsl-destination' import { movedPaneHistorySessionId } from '../../../persistence/migrating-orcad-catalog/terminal-history/orcad-terminal-history-installer' import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { agentProviderSessionsEqual } from '../../../../shared/agent-session/lifecycle/agent-session-resume' diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder.ts index a3570e24694..9efcc4bf20e 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder.ts @@ -56,9 +56,15 @@ export function buildRuntimeMobileAgentStatus( return {} } const providerSession = hookRow.providerSession - ? { providerSession: hookRow.providerSession } + ? { + providerSession: hookRow.providerSession, + ...(hookRow.orcaSessionId !== undefined ? { orcaSessionId: hookRow.orcaSessionId } : {}) + } : retained?.providerSession - ? { providerSession: retained.providerSession } + ? { + providerSession: retained.providerSession, + ...(retained.orcaSessionId !== undefined ? { orcaSessionId: retained.orcaSessionId } : {}) + } : {} const leaf = host.getLeaf(tab) const trackerOnlyTitle = host.getTrackedTitle(pty?.ptyId ?? leaf?.ptyId ?? null) diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts index 17761ac1130..09324d0f1c8 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts @@ -3,15 +3,14 @@ import { AGENT_STATUS_STALE_AFTER_MS, agentStatusAuthorityObservedAt } from '../../../../shared/agent-status/contracts/agent-status-freshness' -import { - pickHostTurnEnd, - pickParsedAgentStatusPayload, - type AgentStatusEntry -} from '../../../../shared/agent-status/contracts/agent-status-types' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentProviderSessionMetadata } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import { terminalTitleBlocksExplicitAgentStatus } from '../../workspaces/process-listing/runtime-worktree-status-projection' -import type { HookLiveAgentRow } from '../../workspaces/process-listing/hook-live-agent-row' +import { + toHookLiveAgentRow, + type HookLiveAgentRow +} from '../../workspaces/process-listing/hook-live-agent-row' import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' import { codexAsyncQuestionOutlivesWorkingTitle } from './codex-async-question-title-hold' @@ -106,7 +105,8 @@ export function demoteRuntimeMobileAgentStatus( stateHistory: [], agentType: status.agentType, ...completedTurnFields(status), - ...(status.providerSession ? { providerSession: status.providerSession } : {}) + ...(status.providerSession ? { providerSession: status.providerSession } : {}), + ...(status.orcaSessionId !== undefined ? { orcaSessionId: status.orcaSessionId } : {}) } } @@ -160,6 +160,7 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( ...(status.tabId ? { tabId: status.tabId } : {}), ...(status.terminalTitle ? { terminalTitle: status.terminalTitle } : {}), ...(status.providerSession ? { providerSession: status.providerSession } : {}), + ...(status.orcaSessionId !== undefined ? { orcaSessionId: status.orcaSessionId } : {}), ...(state === 'done' ? completedTurnFields(status) : {}) }) const titleConfirmsState = @@ -220,6 +221,8 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( export type RuntimeHookAgentRowLookup = { providerSession: AgentProviderSessionMetadata | null + /** The host's Orca id for that provider session's conversation (see `AgentStatusEntry`). */ + orcaSessionId: string | null | undefined providerSessionAgentType: string | null providerSessionReceivedAt: number | null agentType: string | null @@ -283,6 +286,7 @@ export function selectRuntimeHookAgentRowForPane( } return { providerSession: session?.providerSession ?? null, + orcaSessionId: session?.orcaSessionId, providerSessionAgentType: session?.agentType ?? null, providerSessionReceivedAt: session?.receivedAt ?? null, agentType: agent?.agentType ?? null, @@ -292,18 +296,6 @@ export function selectRuntimeHookAgentRowForPane( } } -function toHookLiveAgentRow(row: AgentStatusIpcPayload): HookLiveAgentRow { - return { - payload: pickParsedAgentStatusPayload(row), - updatedAt: row.receivedAt, - ...(row.evidenceObservedAt !== undefined ? { evidenceObservedAt: row.evidenceObservedAt } : {}), - stateStartedAt: row.stateStartedAt ?? row.receivedAt, - ...pickHostTurnEnd(row), - ...(row.worktreeId ? { worktreeId: row.worktreeId } : {}), - ...(row.programStatus ? { programStatus: row.programStatus } : {}) - } -} - export function resolveRuntimeHookLiveAgentRow( live: HookLiveAgentRow | null, pty: RuntimePtyWorktreeRecord | null, diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts index bf9ed6af89e..3d608a5fc89 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts @@ -1,6 +1,6 @@ import { normalizeMobileSessionTabSelection } from '../../session-tabs/mobile-session-tab-selection' import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' -import { dropRetirementProofsForLiveSurfaces } from '../../../../shared/workspace-layout/terminal-retirement-proof-ledger' +import { dropRetirementProofsForLiveSurfaces } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' import { orderMobileSessionTabsByGroups } from './mobile-session-tab-merge' import type { RuntimeMobileSessionProjectionHost, diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts index 24f10dc2de4..4df86c84d06 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts +++ b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts @@ -12,7 +12,7 @@ import { Store } from '../../persistence/loading-store/store' import { OrcaRuntimeService } from '../orca-runtime' import { buildHeadlessMobileSessionTerminalTabs } from '../terminal/surface/mobile-session-terminal-projection' import { setRuntimeDesktopSurface } from '../construction/runtime-desktop-surface' -import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' export const ACK_WORKTREE = 'repo1::/tmp/worktree' export const ACK_TAB = '11111111-1111-4111-8111-111111111111' diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts index 756a61d6b83..b545254f31b 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts +++ b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts @@ -1,15 +1,13 @@ // Main-owned counterparts to acknowledged-terminal-tab-retirement.test.ts: close waits for layout durability without a window-ack race. import { afterEach, expect, it, vi } from 'vitest' import { - ACK_INCARNATION, ACK_LEAF, ACK_SECOND_LEAF, ACK_TAB, - ACK_WORKTREE, createAcknowledgedTabRetirementFixture } from './acknowledged-terminal-tab-retirement-fixture' -import '../../persistence/terminal-topology/terminal-topology-membership' -import { _resetClosedPaneFencesForTests } from '../../persistence/terminal-topology/closed-pane-binding-fence' +import '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' +import { _resetClosedPaneFencesForTests } from '../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) @@ -37,38 +35,6 @@ function fixture(bound = false) { return { ...result, stopped } } -it.each([false, true])( - 'durably closes the row in main without the window, graph republished first=%s', - async (graphFirst) => { - const f = fixture() - if (graphFirst) { - f.publish(false, 2) - } - await expect(f.close()).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) - expect(f.closeTerminalTab).not.toHaveBeenCalled() - await f.store.flushPendingOrThrowAsync() - expect(f.readDisk().workspaceSession?.tabsByWorktree?.[ACK_WORKTREE] ?? []).toEqual([]) - } -) - -it.each([false, true])( - 'closes a split after one pane exited, with remote-session promotion=%s', - async (remoteSession) => { - const f = fixture(true) - if (remoteSession) { - f.store.setWorkspaceSession({ - ...f.store.getWorkspaceSession(), - remoteSessionIdsByTabId: { [ACK_TAB]: 'pty-a' } - }) - } - await f.runtime.onPtyExit('pty-a', 0, ACK_INCARNATION, { providerExitObserved: true }) - await expect(f.close()).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) - expect(f.stopped).toContain('pty-b') - } -) - it("stops a sibling a partial mobile snapshot omitted, from main's own panes", async () => { const f = fixture(true) f.publish(true, 2, [ACK_LEAF]) diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts index 8778998d861..fdbff114d03 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts +++ b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts @@ -5,7 +5,7 @@ import { ACK_WORKTREE, createAcknowledgedTabRetirementFixture } from './acknowledged-terminal-tab-retirement-fixture' -import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' // Main-owned closes have no window ack; their counterparts live in acknowledged-terminal-tab-retirement-main-close.test.ts. @@ -24,22 +24,6 @@ function fixture(bound = false) { return result } -itSwitchOff.each([false, true])( - 'durably retires an acknowledged row with graph-before-ack=%s', - async (graphBeforeAck) => { - const f = fixture() - const pending = f.close() - await f.entered.promise - expect(f.hasTab()).toBe(true) - if (graphBeforeAck) { - f.publish(false, 2) - } - f.acknowledgement.resolve() - await expect(pending).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) - } -) - itSwitchOff( 'protects a persisted incarnation replacement on the same leaf and raw PTY ID', async () => { diff --git a/src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts b/src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts index 7ea33b96e62..1cd4e579fbc 100644 --- a/src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts +++ b/src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts @@ -3,7 +3,7 @@ import type { TerminalPaneLayoutNode, TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types' -import { sanitizeTerminalLayoutPaneTitles } from '../../../shared/workspace-layout/terminal-pane-title-sanitization' +import { sanitizeTerminalLayoutPaneTitles } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-title-sanitization' function collectLeafIds(node: TerminalPaneLayoutNode | null): string[] { if (!node) { diff --git a/src/main/runtime/session-tabs/headless-editor-tabs.ts b/src/main/runtime/session-tabs/headless-editor-tabs.ts index bac1681d096..4282c14d591 100644 --- a/src/main/runtime/session-tabs/headless-editor-tabs.ts +++ b/src/main/runtime/session-tabs/headless-editor-tabs.ts @@ -14,7 +14,7 @@ import { editorRowHost } from '../../../shared/workspace-session/session-tab-fil import { editorTabNamesFile, sameEditorFile -} from '../../../shared/workspace-layout/workspace-layout-editor-tab-file' +} from '../../../shared/workspace-layout/editor-tabs/workspace-layout-editor-tab-file' import type { PersistedOpenFile, WorkspaceSessionState diff --git a/src/main/runtime/session-tabs/headless-mobile-session-absorbed-rows.test.ts b/src/main/runtime/session-tabs/headless-mobile-session-absorbed-rows.test.ts deleted file mode 100644 index 2e3e1c3639b..00000000000 --- a/src/main/runtime/session-tabs/headless-mobile-session-absorbed-rows.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultSettings } from '../../../shared/constants' -import { - HEADLESS_PHONE_LAYOUT_CASES, - HEADLESS_PHONE_WORKTREES, - type PhoneLayoutView -} from '../../../shared/workspace-layout/headless-phone-layout.test-fixture' -import { leaf } from '../../../shared/workspace-layout/workspace-layout-session.test-fixture' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { deriveHeadlessLegacyTerminalLeafId } from '../terminal/surface/mobile-session-layout-projection' -import { OrcaRuntimeService } from '../orca-runtime' - -const repos = [ - { id: 'repo-1', path: '/repos', displayName: 'repo-1', badgeColor: 'blue', addedAt: 1 } -] - -function hydratedRuntime(session: WorkspaceSessionState) { - const runtime = new OrcaRuntimeService({ - getRepo: (id: string) => repos.find((repo) => repo.id === id), - getRepos: () => repos, - getAllWorktreeMeta: () => ({}), - getWorktreeMeta: () => undefined, - addRepo: () => {}, - updateRepo: () => { - throw new Error('unused') - }, - setWorktreeMeta: () => { - throw new Error('unused') - }, - removeWorktreeMeta: () => {}, - getGitHubCache: () => ({ pr: {}, issue: {} }), - getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), - addRetiredWorktreeName: () => {}, - mergeRetiredWorktreeNames: () => false, - getSettings: () => getDefaultSettings('/tmp/home'), - getWorkspaceSession: () => session, - setWorkspaceSession: () => {} - }) - runtime.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(undefined, { force: true }) - return runtime -} - -function phoneView(session: WorkspaceSessionState): PhoneLayoutView { - const view: PhoneLayoutView = {} - for (const [worktreeId, snapshot] of hydratedRuntime(session).mobileSessionTabsByWorktree) { - view[worktreeId] = { - panes: snapshot.tabs.flatMap((tab) => - tab.type === 'terminal' ? [`${tab.parentTabId} ${tab.ptyId ?? '-'} ${tab.title}`] : [] - ), - active: snapshot.activeTabId?.split('::')[0] ?? null, - groups: (snapshot.tabGroups ?? []).map((group) => ({ - tabs: group.tabOrder, - active: group.activeTabId - })) - } - } - return view -} - -describe('headless phone terminal tabs', () => { - it.each(HEADLESS_PHONE_LAYOUT_CASES)('$name', (scenario) => { - for (const worktreeId of scenario.phoneFollowsDesktop) { - expect(scenario.desktop[worktreeId]).not.toEqual(scenario.main[worktreeId]) - } - const expected = Object.fromEntries( - Object.entries(scenario.main).map(([worktreeId, view]) => [ - worktreeId, - scenario.phoneFollowsDesktop.includes(worktreeId) ? scenario.desktop[worktreeId] : view - ]) - ) - expect(phoneView(scenario.build())).toEqual(expected) - }) - - it('keeps pane ids in worktrees with no absorbed row', () => { - const scenario = HEADLESS_PHONE_LAYOUT_CASES.find((entry) => - entry.name.startsWith('duplicate in one worktree') - )! - const { B, C, D } = HEADLESS_PHONE_WORKTREES - const leafIds = (worktreeId: string) => - hydratedRuntime(scenario.build()) - .mobileSessionTabsByWorktree.get(worktreeId) - ?.tabs.flatMap((tab) => (tab.type === 'terminal' ? [tab.leafId] : [])) - expect(leafIds(B)).toEqual([leaf(4), leaf(5)]) - expect(leafIds(C)).toEqual([leaf(6)]) - expect(leafIds(D)).toEqual([deriveHeadlessLegacyTerminalLeafId('tab-old')]) - }) -}) diff --git a/src/main/runtime/session-tabs/headless-move-leaf-to-new-tab.test.ts b/src/main/runtime/session-tabs/headless-move-leaf-to-new-tab.test.ts deleted file mode 100644 index c41136d7941..00000000000 --- a/src/main/runtime/session-tabs/headless-move-leaf-to-new-tab.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import '../orca-runtime-tests/runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' - -import { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import type { RuntimeStore } from '../construction/runtime-store-contract' - -import { planTerminalLeafMove } from '../../persistence/terminal-topology/terminal-leaf-move' -import type { TerminalLeafMoveRequest } from '../../../shared/workspace-layout/terminal-leaf-move' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { Tab } from '../../../shared/tab-types' -import { ownedEditorFileId } from '../../../shared/workspace-session/workspace-session-pane-ownership' - -const SIBLING_LEAF_ID = '33333333-3333-4333-8333-333333333333' -const OTHER_LEAF_ID = '44444444-4444-4444-8444-444444444444' -async function setup( - withSession: (session: WorkspaceSessionState) => WorkspaceSessionState = (session) => session, - /** Runs while the move's commit is pending, as another writer would. */ - duringCommit: (session: WorkspaceSessionState) => WorkspaceSessionState = (session) => session -) { - const base = makeWorkspaceSessionWithHeadlessTerminal() - const hostTab = base.tabsByWorktree[TEST_WORKTREE_ID]![0]! - const { runtimeStore, getSession, setSession } = makeRuntimeStoreWithWorkspaceSession( - withSession({ - ...base, - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - hostTab, - { ...hostTab, id: 'other-tab', ptyId: 'other-pty', title: 'Other', sortOrder: 1 } - ] - }, - terminalLayoutsByTabId: { - 'other-tab': { - root: { type: 'leaf', leafId: OTHER_LEAF_ID }, - activeLeafId: OTHER_LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [OTHER_LEAF_ID]: 'other-pty' } - }, - 'host-tab': { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: HEADLESS_LEAF_ID }, - second: { type: 'leaf', leafId: SIBLING_LEAF_ID } - }, - activeLeafId: HEADLESS_LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [HEADLESS_LEAF_ID]: 'persisted-pty', [SIBLING_LEAF_ID]: 'sibling-pty' } - } - } - }) - ) - // The host's real planner over the shared session, as Store.moveTerminalLeafToNewTab runs it. - const commit = vi.fn(async (request: TerminalLeafMoveRequest) => { - setSession(duringCommit(getSession())) - const plan = planTerminalLeafMove([{ hostId: 'local', session: getSession() }], request) - if (plan.sessions[0]) { - setSession(plan.sessions[0].session) - } - return plan.result - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The shared fixture implements RuntimeStore for this runtime. - const runtime = new OrcaRuntimeService(runtimeStore as RuntimeStore) - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - const published: unknown[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => published.push(snapshot)) - const move = ( - targetTabId = 'host-new-tab', - placement?: Parameters[3] - ) => - runtime.moveMobileSessionLeafToNewTab( - `id:${TEST_WORKTREE_ID}`, - { sourceTabId: 'host-tab', targetTabId, leafId: SIBLING_LEAF_ID }, - commit, - placement - ) - return { runtime, getSession, published, commit, move } -} -describe('moveMobileSessionLeafToNewTab on a headless host', () => { - it('moves the live terminal with its pane, so tab-scoped reads find it in the new tab', async () => { - const { runtime, move } = await setup() - runtime.registerPty('sibling-pty', TEST_WORKTREE_ID, null, { - tabId: 'host-tab', - leafId: SIBLING_LEAF_ID - }) - await expect(move()).resolves.toEqual({ status: 'moved', ptyId: 'sibling-pty' }) - const { terminals } = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - expect(terminals.find((terminal) => terminal.leafId === SIBLING_LEAF_ID)?.tabId).toBe( - 'host-new-tab' - ) - }) - it('keeps a tab opened while the move commits, after the tabs the user had', async () => { - const { runtime, move } = await setup(withFileBetweenTerminals, withLateTerminal) - const worktree = `id:${TEST_WORKTREE_ID}` - const listed = async () => (await runtime.listMobileSessionTabs(worktree)).tabGroups?.[0] - const group = (await listed())! - const file = group.tabOrder.find((id) => id !== 'host-tab' && id !== 'other-tab')! - await runtime.moveMobileSessionTab(worktree, { - kind: 'reorder', - tabId: file, - targetGroupId: group.id, - tabOrder: ['host-tab', file, 'other-tab'] - }) - await move('host-new-tab', { targetGroupId: group.id, index: 2 }) - expect((await listed())?.tabOrder).toEqual([ - 'host-tab', - file, - 'host-new-tab', - 'other-tab', - 'late-tab' - ]) - }) - it('keeps a reorder another client made while the move committed', async () => { - let reorder: () => Promise = async () => {} - const { runtime, move } = await setup(undefined, (session) => { - void reorder() - return session - }) - const worktree = `id:${TEST_WORKTREE_ID}` - const listed = async () => (await runtime.listMobileSessionTabs(worktree)).tabGroups?.[0] - const group = (await listed())! - expect(group.tabOrder).toEqual(['host-tab', 'other-tab']) - reorder = async () => { - reorder = async () => {} - await runtime.moveMobileSessionTab(worktree, { - kind: 'reorder', - tabId: 'other-tab', - targetGroupId: group.id, - tabOrder: ['other-tab', 'host-tab'] - }) - } - await move('host-new-tab', { targetGroupId: group.id, index: 0 }) - expect((await listed())?.tabOrder).toEqual(['host-new-tab', 'other-tab', 'host-tab']) - }) - it('refuses a move that would empty its source, which no headless cleanup retires', async () => { - const { runtime, getSession, published, move } = await setup(undefined, (session) => ({ - ...session, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - 'host-tab': { - root: { type: 'leaf', leafId: SIBLING_LEAF_ID }, - activeLeafId: SIBLING_LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [SIBLING_LEAF_ID]: 'sibling-pty' } - } - } - })) - await expect(move()).resolves.toEqual({ status: 'refused', reason: 'last_pane' }) - expect(getSession().terminalLayoutsByTabId['host-tab']?.root).toEqual({ - type: 'leaf', - leafId: SIBLING_LEAF_ID - }) - expect(published).toHaveLength(0) - const { tabs } = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - expect(tabs.some((tab) => tab.type === 'terminal' && tab.parentTabId === 'host-new-tab')).toBe( - false - ) - }) -}) - -/** A session whose worktree also has an editor open beside its two terminal tabs. */ -function withFileBetweenTerminals(session: WorkspaceSessionState): WorkspaceSessionState { - const filePath = '/repo/notes.ts' - const entry = ( - id: string, - entityId: string, - contentType: Tab['contentType'], - sortOrder: number - ) => ({ - id, - entityId, - groupId: 'group-1', - worktreeId: TEST_WORKTREE_ID, - contentType, - label: id, - customLabel: null, - color: null, - sortOrder, - createdAt: 1 - }) - return { - ...session, - openFilesByWorktree: { - [TEST_WORKTREE_ID]: [ - { filePath, relativePath: 'notes.ts', worktreeId: TEST_WORKTREE_ID, language: 'typescript' } - ] - }, - unifiedTabs: { - [TEST_WORKTREE_ID]: [ - entry('host-tab', 'host-tab', 'terminal', 0), - entry('file-tab', ownedEditorFileId(filePath, TEST_WORKTREE_ID, undefined), 'editor', 1), - entry('other-tab', 'other-tab', 'terminal', 2) - ] - }, - tabGroups: { - [TEST_WORKTREE_ID]: [ - { - id: 'group-1', - worktreeId: TEST_WORKTREE_ID, - activeTabId: 'host-tab', - tabOrder: ['host-tab', 'file-tab', 'other-tab'] - } - ] - } - } -} - -const LATE_LEAF_ID = '55555555-5555-4555-8555-555555555555' - -/** A terminal tab another writer opens while the move's commit is pending. */ -function withLateTerminal(session: WorkspaceSessionState): WorkspaceSessionState { - const tabs = session.tabsByWorktree[TEST_WORKTREE_ID] ?? [] - if (tabs.some((tab) => tab.id === 'late-tab')) { - return session - } - return { - ...session, - tabsByWorktree: { - ...session.tabsByWorktree, - [TEST_WORKTREE_ID]: [ - ...tabs, - { ...tabs[0]!, id: 'late-tab', ptyId: 'late-pty', title: 'Late', sortOrder: 9 } - ] - }, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - 'late-tab': { - root: { type: 'leaf', leafId: LATE_LEAF_ID }, - activeLeafId: LATE_LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [LATE_LEAF_ID]: 'late-pty' } - } - } - } -} diff --git a/src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts b/src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts index f0f46d8cb34..6904468f109 100644 --- a/src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts +++ b/src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts @@ -7,13 +7,13 @@ import { import { withSelectedTabs } from './headless-tab-group-selection' import type { RuntimeMobileSessionTabGroup } from '../../../shared/runtime-session-contracts' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { isValidHostTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id' +import { isValidHostTerminalTabId } from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { isTerminalLeafMoveRequest, type TerminalLeafMoveRequest, type TerminalLeafMoveResult -} from '../../../shared/workspace-layout/terminal-leaf-move' +} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' /** Where the client dropped the new tab, in the host's group ids. */ export type MovedPanePlacement = { targetGroupId: string; index?: number } diff --git a/src/main/runtime/session-tabs/headless-tab-group-moves.ts b/src/main/runtime/session-tabs/headless-tab-group-moves.ts index a1e988d23c3..0ce77456697 100644 --- a/src/main/runtime/session-tabs/headless-tab-group-moves.ts +++ b/src/main/runtime/session-tabs/headless-tab-group-moves.ts @@ -9,7 +9,7 @@ import type { import { buildHeadlessTabGroupMove, buildHeadlessTabGroupSplit -} from '../../../shared/workspace-layout/tab-group-moves' +} from '../../../shared/workspace-layout/tab-groups/tab-group-moves' import { randomUUID } from 'node:crypto' import { withSelectedTabs } from './headless-tab-group-selection' import type { TabGroupLayoutNode } from '../../../shared/tab-types' diff --git a/src/main/runtime/session-tabs/headless-tab-properties.ts b/src/main/runtime/session-tabs/headless-tab-properties.ts index 3d773e1780b..dfdc79dabda 100644 --- a/src/main/runtime/session-tabs/headless-tab-properties.ts +++ b/src/main/runtime/session-tabs/headless-tab-properties.ts @@ -12,7 +12,7 @@ import { cloneTerminalLayoutSnapshot } from '../terminal/surface/mobile-session- import { sameStringRecord, terminalLayoutNodeEqual -} from '../../../shared/workspace-layout/terminal-layout-equality' +} from '../../../shared/workspace-layout/terminal-topology/terminal-layout-equality' type HeadlessPaneLayoutEdit = { tabId: string diff --git a/src/main/runtime/session-tabs/headless-terminal-tab-close.ts b/src/main/runtime/session-tabs/headless-terminal-tab-close.ts index e3945b38041..eb5bd2da4f6 100644 --- a/src/main/runtime/session-tabs/headless-terminal-tab-close.ts +++ b/src/main/runtime/session-tabs/headless-terminal-tab-close.ts @@ -13,7 +13,7 @@ import type { RuntimeMobileSessionTerminalTab } from '../../../shared/runtime-mo import { parseAppSshPtyId } from '../../../shared/ssh-pty-id' import { retireMobileSessionTabSelection } from './mobile-session-tab-selection' import { paneTitlesForDesktopWindow } from './desktop-pane-title-forwarding' -import { appendRetiredTerminalSurfaceProofs } from '../../../shared/workspace-layout/terminal-retirement-proof-ledger' +import { appendRetiredTerminalSurfaceProofs } from '../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' import type { TerminalPaneLayoutNode } from '../../../shared/workspace-layout/terminal-tab-types' import type { RuntimeTerminalRename } from '../../../shared/runtime-terminal-contracts' diff --git a/src/main/runtime/session-tabs/main-layout-session-tab-move.ts b/src/main/runtime/session-tabs/main-layout-session-tab-move.ts index 53486cc54db..469b2612a72 100644 --- a/src/main/runtime/session-tabs/main-layout-session-tab-move.ts +++ b/src/main/runtime/session-tabs/main-layout-session-tab-move.ts @@ -13,7 +13,7 @@ import { OrcaRuntimeWithMainLayoutRenames } from './main-layout-renames' import { liveTerminalsOfTab } from '../session-lifecycle/close/closed-tab-terminal' import type { WorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-model' import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { isPaneColumnSplitDropNoOp } from '../../../shared/workspace-layout/pane-column-split-drop-no-op' +import { isPaneColumnSplitDropNoOp } from '../../../shared/workspace-layout/tab-groups/pane-column-split-drop-no-op' import { selectMobileSessionTab } from './mobile-session-tab-selection' export abstract class OrcaRuntimeWithMainLayoutTabMoves extends OrcaRuntimeWithMainLayoutRenames { diff --git a/src/main/runtime/session-tabs/mobile-session-membership.ts b/src/main/runtime/session-tabs/mobile-session-membership.ts index d9fe6ec16ac..4b23804cb30 100644 --- a/src/main/runtime/session-tabs/mobile-session-membership.ts +++ b/src/main/runtime/session-tabs/mobile-session-membership.ts @@ -1,10 +1,11 @@ +import type { MobileSessionTabSubscription } from '../construction/runtime-identity-state' import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from './session-tabs-change-publication' import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as SessionTabsProjection } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' import type { OrcaRuntimeWithGetTerminalInteractiveWait as GetTerminalInteractiveWaitMethods } from '../terminal/wait/terminal-interactive-wait' import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from './pty-backed-session-publication' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { hasHostAuthoritativeTerminalMembership } from '../../persistence/terminal-topology/terminal-topology-membership' +import { hasHostAuthoritativeTerminalMembership } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import type { RuntimeMobileSessionTabsSnapshot, RuntimeSyncedLeaf @@ -22,7 +23,11 @@ export abstract class OrcaRuntimeWithTouchMobileSessionTabsForWorktree extends O ...args: Parameters ): ReturnType - protected abstract hasAgentSenderListeners(): boolean + protected abstract selectMobileSessionTabsListeners( + worktree?: string, + clientNavigationId?: string, + candidates?: Iterable + ): MobileSessionTabSubscription[] abstract getTerminalWorktreeIdForPaneKey( ...args: Parameters @@ -35,14 +40,19 @@ export abstract class OrcaRuntimeWithTouchMobileSessionTabsForWorktree extends O /** Republish only worktrees whose sender scope differs from the one their last frame carried. */ refreshAgentSenderAssociations(): void { - if (!this.hasAgentSenderListeners()) { + const listeners = this.selectMobileSessionTabsListeners().filter( + (subscription) => subscription.clientKind !== 'mobile' + ) + if (listeners.length === 0) { return } const changed = this.agentProjections.senders.changedScopes( this.mobileSessionTabsByWorktree.keys() ) for (const worktreeId of changed) { - this.touchMobileSessionTabsForWorktree(worktreeId) + if (this.selectMobileSessionTabsListeners(worktreeId, undefined, listeners).length > 0) { + this.touchMobileSessionTabsForWorktree(worktreeId) + } } } diff --git a/src/main/runtime/session-tabs/mobile-session-publication-preservation.ts b/src/main/runtime/session-tabs/mobile-session-publication-preservation.ts index c4aa4873899..ec48166dddd 100644 --- a/src/main/runtime/session-tabs/mobile-session-publication-preservation.ts +++ b/src/main/runtime/session-tabs/mobile-session-publication-preservation.ts @@ -18,6 +18,7 @@ export abstract class OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab ex protected abstract getListedBrowserTabsByPageId( ...args: Parameters ): ReturnType + protected abstract notifyMobileSessionTabsChangedNow( ...args: Parameters< ScheduleMobileSessionTabsChangedMethods['notifyMobileSessionTabsChangedNow'] @@ -208,12 +209,16 @@ export abstract class OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab ex tabs: [] } const changeSequence = ++this.mobileSessionTabsChangeSequence - for (const subscription of this.mobileSessionTabListeners) { + for (const subscription of this.selectMobileSessionTabsListeners(worktreeId)) { + if (!this.mobileSessionTabListeners.has(subscription)) { + continue + } subscription.listener( this.clientSessionTabSelections.project(removed, subscription.clientNavigationId), changeSequence ) } + this.clientHostedPageReconciliation.forgetWorktree(worktreeId) this.clientSessionTabSelections.forgetWorktree(worktreeId) } diff --git a/src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts b/src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts index 8b01ffdba50..44455726f30 100644 --- a/src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts +++ b/src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts @@ -1,19 +1,31 @@ +import type { + ClientHostedPageObservation, + MobileSessionTabSubscription +} from '../construction/runtime-identity-state' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts' import { RuntimeWorkspaceFileTargets } from '../workspaces/workspace-file-session-targets' export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorkspaceFileTargets { onMobileSessionTabsChanged( - listener: (snapshot: RuntimeMobileSessionTabsResult, changeSequence: number) => void, + listener: MobileSessionTabSubscription['listener'], clientNavigationId?: string, - clientKind?: 'mobile' | 'runtime' + clientKind?: 'mobile' | 'runtime', + options?: Pick ): () => void { // Drain coalesced notifications before subscribing: the initial snapshot already includes them. this.mobileSessionTabsNotifyCoalescer.flushAll() - const subscription = { listener, clientNavigationId, clientKind } + const subscription = { + listener, + clientNavigationId, + clientKind, + observation: options?.observation, + acceptsWorktree: options?.acceptsWorktree + } this.mobileSessionTabListeners.add(subscription) return () => { // Flush before removal so this listener receives the latest settled state. this.mobileSessionTabsNotifyCoalescer.flushAll() const removed = this.mobileSessionTabListeners.delete(subscription) + this.clientHostedPageReconciliation.forgetObservation(clientNavigationId, subscription) if (removed && clientKind !== 'mobile') { this.releaseAgentSenderHistoryIfUnobserved() } @@ -23,6 +35,60 @@ export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorksp } } + protected deliverMobileSessionTabsFrame( + subscription: MobileSessionTabSubscription, + frame: RuntimeMobileSessionTabsResult, + sequence: number, + delivery?: 'reconciliation' + ): void { + subscription.listener(frame, sequence, delivery) + if ( + subscription.observation === 'caller' || + !this.mobileSessionTabListeners.has(subscription) + ) { + return + } + this.clientHostedPageReconciliation.observe( + [frame], + subscription.clientNavigationId, + subscription + ) + } + + observeClientHostedPageSnapshots( + frames: readonly RuntimeMobileSessionTabsResult[], + clientNavigationId?: string, + observer?: ClientHostedPageObservation + ): void { + this.clientHostedPageReconciliation.observe(frames, clientNavigationId, observer) + } + + forgetClientHostedPageObservation( + clientNavigationId: string | undefined, + observer: ClientHostedPageObservation + ): void { + this.clientHostedPageReconciliation.forgetObservation(clientNavigationId, observer) + } + + protected selectMobileSessionTabsListeners( + worktree?: string, + clientNavigationId?: string, + candidates: Iterable = this.mobileSessionTabListeners + ): MobileSessionTabSubscription[] { + const selected: MobileSessionTabSubscription[] = [] + for (const subscription of candidates) { + if ( + this.mobileSessionTabListeners.has(subscription) && + (clientNavigationId === undefined || + subscription.clientNavigationId === clientNavigationId) && + (worktree === undefined || subscription.acceptsWorktree?.(worktree) !== false) + ) { + selected.push(subscription) + } + } + return selected + } + protected hasAgentSenderListeners(): boolean { for (const { clientKind } of this.mobileSessionTabListeners) { if (clientKind !== 'mobile') { @@ -40,5 +106,6 @@ export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorksp forgetClientNavigationState(clientNavigationId: string): void { this.clientSessionTabSelections.forgetClient(clientNavigationId) + this.clientHostedPageReconciliation.forgetClient(clientNavigationId) } } diff --git a/src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts b/src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts index 3dde336c70a..363ca55c4ab 100644 --- a/src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts +++ b/src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts @@ -158,3 +158,35 @@ describe('session tab workspace path aliases', () => { runtime.cleanupSubscriptionsForConnection('alias-connection') }) }) + +it('rejects ambiguous later aliases while retaining an exact host spelling', async () => { + const runtime = new OrcaRuntimeService() + runtime.attachWindow(1) + const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + const frames: { type?: string; worktree?: string }[] = [] + try { + await rpc.dispatchStreaming( + { + id: 'ambiguous-alias', + authToken: 'test', + method: 'session.tabs.subscribe', + params: { worktree: `id:${ALIAS}` } + }, + (reply) => frames.push(JSON.parse(reply).result), + { connectionId: 'ambiguous-alias' } + ) + publishGraph(runtime, WORKTREE, [snapshot('repo::g:/git/example', 'pty-other')]) + runtime.onMobileSessionTabsChanged(() => {}, undefined, 'mobile')() + expect(frames.filter((frame) => frame.type === 'updated')).toEqual([]) + publishGraph(runtime, ALIAS, [ + snapshot(WORKTREE), + snapshot('repo::g:/git/example', 'pty-other') + ]) + runtime.onMobileSessionTabsChanged(() => {}, undefined, 'mobile')() + expect( + frames.filter((frame) => frame.type === 'updated').map((frame) => frame.worktree) + ).toEqual([ALIAS]) + } finally { + runtime.cleanupSubscriptionsForConnection('ambiguous-alias') + } +}) diff --git a/src/main/runtime/session-tabs/session-tabs-change-publication.ts b/src/main/runtime/session-tabs/session-tabs-change-publication.ts index 95832e5f5e6..dd780267785 100644 --- a/src/main/runtime/session-tabs/session-tabs-change-publication.ts +++ b/src/main/runtime/session-tabs/session-tabs-change-publication.ts @@ -1,3 +1,4 @@ +import type { MobileSessionTabSubscription } from '../construction/runtime-identity-state' import { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab } from './mobile-session-publication-preservation' import type { BrowserTabInfo } from '../../../shared/browser/runtime/runtime-browser-contracts' import type { @@ -67,7 +68,9 @@ export abstract class OrcaRuntimeWithScheduleMobileSessionTabsChanged extends Or return ( result: RuntimeMobileSessionTabsResult, changeSequence: number, - clientNavigationId?: string + clientNavigationId?: string, + candidates?: readonly MobileSessionTabSubscription[], + delivery?: 'reconciliation' ): void => { const { agentSenderAssociations: _senders, ...tabsOnly } = result // A frame for one client is already its projection; projecting again stacks the epoch suffix and revision, so the client fences it. @@ -75,32 +78,31 @@ export abstract class OrcaRuntimeWithScheduleMobileSessionTabsChanged extends Or clientNavigationId === undefined ? this.projectMobileSessionTabsForClient(frame, id) : frame let desktopFrame: RuntimeMobileSessionTabsResult | undefined try { - for (const subscription of this.mobileSessionTabListeners) { - if ( - clientNavigationId !== undefined && - subscription.clientNavigationId !== clientNavigationId - ) { + for (const subscription of this.selectMobileSessionTabsListeners( + result.worktree, + clientNavigationId, + candidates + )) { + if (!this.mobileSessionTabListeners.has(subscription)) { continue } let frame: RuntimeMobileSessionTabsResult = tabsOnly if (subscription.clientKind !== 'mobile') { if (!desktopFrame) { - if (result.agentSenderAssociations) { - desktopFrame = result - } else { + desktopFrame = result + if (!result.agentSenderAssociations) { senderScope ??= this.agentProjections.senders.buildForFramePass() desktopFrame = { ...result, agentSenderAssociations: senderScope(result.worktree) } } } frame = desktopFrame } - subscription.listener(project(frame, subscription.clientNavigationId), changeSequence) + const supplied = project(frame, subscription.clientNavigationId) + this.deliverMobileSessionTabsFrame(subscription, supplied, changeSequence, delivery) } - if (clientNavigationId === undefined && desktopFrame?.agentSenderAssociations) { - this.agentProjections.senders.acknowledgeFrame( - result.worktree, - desktopFrame.agentSenderAssociations - ) + const senders = desktopFrame?.agentSenderAssociations + if (clientNavigationId === undefined && senders) { + this.agentProjections.senders.acknowledgeFrame(result.worktree, senders) } } finally { if (senderScope) { diff --git a/src/main/runtime/session-tabs/structured-session-cli-writer-host.ts b/src/main/runtime/session-tabs/structured-session-cli-writer-host.ts index 65d37a17105..3c66d0102f8 100644 --- a/src/main/runtime/session-tabs/structured-session-cli-writer-host.ts +++ b/src/main/runtime/session-tabs/structured-session-cli-writer-host.ts @@ -8,8 +8,8 @@ import { assertCliConversationWritersExited } from '../agent-session/lifecycle/s import type { EnrichedAgentHookEventPayload } from '../../agent-hooks/server/server-types' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' import { CLI_CONVERSATION_ADOPTING_AGENTS } from '../../../shared/structured-agent-cli-conversation-adoption' -import { recordConversationKey } from '../../native-chat/structured-conversation-key' -import type { StructuredAgentCliSourceRoute } from '../../native-chat/structured-agent-cli-source' +import { recordConversationKey } from '../../native-chat/conversation-adoption/structured-conversation-key' +import type { StructuredAgentCliSourceRoute } from '../../native-chat/conversation-adoption/structured-agent-cli-source' import { OrcaRuntimeWithGetWorktreePs } from '../workspaces/process-listing/workspace-process-listing' export abstract class OrcaRuntimeWithStructuredSessionCliWriterHost extends OrcaRuntimeWithGetWorktreePs { diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index a784ee9e5c0..804ae6c230f 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -3,7 +3,7 @@ import { resolveStructuredAgentSessionForkIntent } from '../../native-chat/agent import { captureStructuredAgentCliSource, structuredAgentCliSourceFromEvidence -} from '../../native-chat/structured-agent-cli-source' +} from '../../native-chat/conversation-adoption/structured-agent-cli-source' import type { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce as RestoreStructuredAgentSessionTabsOnceMethods } from './structured-session-tab-restoration' import { agentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' import { StructuredSessionWorkspaceScope } from './structured-session-workspace-scope' diff --git a/src/main/runtime/session-tabs/structured-session-tab-publication.ts b/src/main/runtime/session-tabs/structured-session-tab-publication.ts index 27d6b3b0a41..4cf0959db74 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-publication.ts +++ b/src/main/runtime/session-tabs/structured-session-tab-publication.ts @@ -9,7 +9,7 @@ import { defaultAgentChatLabel } from '../../../shared/agent-session/agent-sessi import { getHeadlessMobileSessionGroupId } from '../terminal/surface/mobile-session-layout-projection' import type { StructuredSessionSurface } from '../agent-session/structured-agent-session-close' import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { insertTabIdIntoOrder } from '../../../shared/workspace-layout/tab-order' +import { insertTabIdIntoOrder } from '../../../shared/workspace-layout/tab-groups/tab-order' import { chatTabId, resolveChatTabPlacement, diff --git a/src/main/runtime/session-tabs/structured-session-tab-restoration.ts b/src/main/runtime/session-tabs/structured-session-tab-restoration.ts index 4c09deeffb2..762208b1bc4 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-restoration.ts +++ b/src/main/runtime/session-tabs/structured-session-tab-restoration.ts @@ -13,7 +13,7 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import type { RuntimeRepoSearchRefs } from '../../../shared/runtime-worktree-contracts' import { REPO_SEARCH_REFS_DEFAULT_LIMIT as DEFAULT_REPO_SEARCH_REFS_LIMIT } from '../../../shared/repo-search-limits' import type { Repo } from '../../../shared/repo-types' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' import { getLocalProjectGhExecOptions, type LocalProjectGhExecOptions diff --git a/src/main/runtime/session-tabs/terminal-create-closed-tab-durability.test.ts b/src/main/runtime/session-tabs/terminal-create-closed-tab-durability.test.ts index 7ff8238df28..a8fcaa5d071 100644 --- a/src/main/runtime/session-tabs/terminal-create-closed-tab-durability.test.ts +++ b/src/main/runtime/session-tabs/terminal-create-closed-tab-durability.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { hasClosedTerminalTabRecord } from '../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import type { ExecutionHostId } from '../../../shared/execution-host' import { Store } from '../../persistence/loading-store/store' import { closeTestStores, createSqliteTestStore } from '../../persistence/persistence-test-harness' diff --git a/src/main/runtime/sidebar-inputs/cached-scan.test.ts b/src/main/runtime/sidebar-inputs/cached-scan.test.ts index 6f2164f914f..651c2493d4a 100644 --- a/src/main/runtime/sidebar-inputs/cached-scan.test.ts +++ b/src/main/runtime/sidebar-inputs/cached-scan.test.ts @@ -40,16 +40,6 @@ describe('CachedScan', () => { expect(pending).toHaveLength(0) }) - it('scans for a first reader and serves later readers from the cache', async () => { - const { cache, pending, finish } = scanner(false) - const ready = cache.ready() - expect(pending).toHaveLength(1) - await finish() - await ready - await cache.ready() - expect(pending).toHaveLength(0) - }) - it('runs no scan without demand, but makes the next reader scan again', async () => { const { cache, pending, finish } = scanner(false) const first = cache.ready() diff --git a/src/main/runtime/sidebar-inputs/desktop-sidebar-facts.test.ts b/src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.test.ts similarity index 90% rename from src/main/runtime/sidebar-inputs/desktop-sidebar-facts.test.ts rename to src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.test.ts index 2d9c480cf5e..69ed5649795 100644 --- a/src/main/runtime/sidebar-inputs/desktop-sidebar-facts.test.ts +++ b/src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.test.ts @@ -1,11 +1,11 @@ // Runs on plain Node, as orcad does: the reader imports no Electron. import { describe, expect, it } from 'vitest' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../../shared/project-group-types' -import type { Repo } from '../../../shared/repo-types' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { ManualRepoOrderEntry } from '../../../shared/ui-chrome-types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../../shared/project-group-types' +import type { Repo } from '../../../../shared/repo-types' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { ManualRepoOrderEntry } from '../../../../shared/ui-chrome-types' +import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import { readDesktopSidebarFacts, type DesktopSidebarFactSources } from './desktop-sidebar-facts' function repo(id: string, connectionId: string | null = null): Repo { diff --git a/src/main/runtime/sidebar-inputs/desktop-sidebar-facts.ts b/src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.ts similarity index 77% rename from src/main/runtime/sidebar-inputs/desktop-sidebar-facts.ts rename to src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.ts index 7e1a45f8a1a..85c0be95bf6 100644 --- a/src/main/runtime/sidebar-inputs/desktop-sidebar-facts.ts +++ b/src/main/runtime/sidebar-inputs/catalog/desktop-sidebar-facts.ts @@ -6,22 +6,22 @@ import { toRuntimeExecutionHostId, toSshExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import { applyManualRepoOrder } from '../../../shared/manual-repo-order' -import type { DesktopSidebarFacts } from '../../../shared/sidebar-list/desktop-sidebar-facts' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import { getHostDisplayLabelOverrides } from '../../../shared/host-setting-overrides' -import type { SshConnectionState, SshTarget } from '../../../shared/ssh-types' -import type { WslHostStatus } from '../../../shared/wsl-host-types' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { readAllWorktreeMetaForHost } from '../../persistence/host-qualified-worktree-meta' -import type { RuntimeStore } from '../construction/runtime-store-contract' +} from '../../../../shared/execution-host' +import { applyManualRepoOrder } from '../../../../shared/manual-repo-order' +import type { DesktopSidebarFacts } from '../../../../shared/sidebar-list/desktop-sidebar-facts' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-overrides' +import type { SshConnectionState, SshTarget } from '../../../../shared/ssh-types' +import type { WslHostStatus } from '../../../../shared/wsl-host-types' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { readAllWorktreeMetaForHost } from '../../../persistence/host-qualified-worktree-meta' +import type { RuntimeStore } from '../../construction/runtime-store-contract' import { runtimeVisibleFolderWorkspaces, runtimeVisibleRepos -} from '../workspaces/catalog/runtime-visible-catalog' +} from '../../workspaces/catalog/runtime-visible-catalog' export type DesktopSidebarFactSources = { store: Pick< diff --git a/src/main/runtime/sidebar-inputs/mobile-project-sections-snapshot.ts b/src/main/runtime/sidebar-inputs/catalog/mobile-project-sections-snapshot.ts similarity index 91% rename from src/main/runtime/sidebar-inputs/mobile-project-sections-snapshot.ts rename to src/main/runtime/sidebar-inputs/catalog/mobile-project-sections-snapshot.ts index 4bf73533fd2..866972e4ab3 100644 --- a/src/main/runtime/sidebar-inputs/mobile-project-sections-snapshot.ts +++ b/src/main/runtime/sidebar-inputs/catalog/mobile-project-sections-snapshot.ts @@ -2,7 +2,7 @@ import { isDeepStrictEqual } from 'node:util' import type { MobileProjectSectionCatalog, MobileProjectSectionsResult -} from '../../../shared/mobile-project-sections-contract' +} from '../../../../shared/mobile-project-sections-contract' // Retain the last catalog after window close; stale grouping is better than none. let latestCatalog: MobileProjectSectionCatalog | null = null diff --git a/src/main/runtime/sidebar-inputs/catalog/orca-runtime-project-catalog.test.ts b/src/main/runtime/sidebar-inputs/catalog/orca-runtime-project-catalog.test.ts new file mode 100644 index 00000000000..998279420df --- /dev/null +++ b/src/main/runtime/sidebar-inputs/catalog/orca-runtime-project-catalog.test.ts @@ -0,0 +1,109 @@ +// Runs on plain Node, as orcad does: the catalog comes from main's own store, no window publishes it. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { ProjectGroup } from '../../../../shared/project-group-types' + +import type { Repo } from '../../../../shared/repo-types' + +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' + +import { readSidebarFeedDomains } from '../../../../shared/sidebar-list/sidebar-feed-domains' + +import '../../../../shared/mobile-project-sections-contract' +import { OrcaRuntimeService } from '../../orca-runtime' + +import '../../rpc/methods/rpc-method-registry' +import type { RuntimeStore } from '../../construction/runtime-store-contract' + +import { requireSwitchedOn } from '../../construction/require-sidebar-inputs-enabled' + +import { TestPhone } from '../feed/testing/sidebar-inputs-feed.test-fixture' + +import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' + +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) + +function group(id: string): ProjectGroup { + return { + id, + name: id, + parentPath: null, + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 + } +} + +function setup() { + let repos: Repo[] = [ + { id: 'r', path: '/r', displayName: 'r', badgeColor: 'blue', addedAt: 1, projectGroupId: 'a' } + ] + const store: Pick = { + getRepos: () => repos, + getProjectGroups: () => [group('a'), group('school')] + } + const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) + const events: RuntimeClientEvent[] = [] + runtime.onClientEvent((event) => events.push(event)) + const feed = requireSwitchedOn(runtime.sidebarInputsFeed) + /** Moves the repo the way a host's IPC write does: store first, then reposChanged. */ + const write = (groupId: string): void => { + repos = repos.map((entry) => ({ ...entry, projectGroupId: groupId })) + runtime.notifyReposChangedForRemoteClients() + } + return { + runtime, + feed, + write, + move: async (groupId: string) => { + write(groupId) + await vi.advanceTimersByTimeAsync(60) + const notice = events.findLast((event) => event.type === 'sidebarInputsChanged') + if (notice?.type !== 'sidebarInputsChanged') { + throw new Error('no change notice') + } + return notice + } + } +} + +function groupOf(phone: TestPhone): string | null | undefined { + const installed = phone.state.installed + return installed + ? readSidebarFeedDomains(installed).projectCatalog?.repos.find((repo) => repo.id === 'r') + ?.projectGroupId + : undefined +} + +beforeEach(() => { + vi.useFakeTimers() + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('the project catalog in the sidebar feed', () => { + it('reaches a move made while an earlier read is held, with no further trigger', async () => { + const { feed, move } = setup() + const phone = new TestPhone(feed, 'conn-1') + phone.refresh() + await phone.settle() + phone.refresh() + // The host answered the read before the move; its reply reaches the phone only after. + const held = await phone.serveOne() + const notice = await move('school') + phone.notice(notice) + held.deliver() + expect(groupOf(phone)).toBe('a') + await phone.settle() + expect(groupOf(phone)).toBe('school') + phone.disconnect() + }) +}) diff --git a/src/main/runtime/sidebar-inputs/sidebar-project-catalog.test.ts b/src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.test.ts similarity index 94% rename from src/main/runtime/sidebar-inputs/sidebar-project-catalog.test.ts rename to src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.test.ts index 683fa4c9f32..3749ba7f5fa 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-project-catalog.test.ts +++ b/src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' -import type { ProjectGroup } from '../../../shared/project-group-types' -import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' -import type { Repo } from '../../../shared/repo-types' +import type { ProjectGroup } from '../../../../shared/project-group-types' +import { projectHostSetupProjectionFromRepos } from '../../../../shared/project-host-setup-projection' +import type { Repo } from '../../../../shared/repo-types' import { readSidebarProjectCatalog, type SidebarProjectCatalogStore diff --git a/src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.ts b/src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.ts new file mode 100644 index 00000000000..f1a84a8d659 --- /dev/null +++ b/src/main/runtime/sidebar-inputs/catalog/sidebar-project-catalog.ts @@ -0,0 +1,37 @@ +import type { MobileProjectSectionCatalog } from '../../../../shared/mobile-project-sections-contract' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' +import { + buildSidebarProjectCatalog, + type PairedServerCatalog +} from '../../../../shared/sidebar-list/sidebar-project-catalog' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { + runtimeVisibleProjectGroups, + runtimeVisibleProjectHostSetups, + runtimeVisibleRepos +} from '../../workspaces/catalog/runtime-visible-catalog' + +export type SidebarProjectCatalogStore = Pick< + RuntimeStore, + 'getRepos' | 'getProjectGroups' | 'getFolderWorkspaces' | 'getSshTargets' | 'getProjectHostSetups' +> & + Partial> & { + getUI?: () => Pick + } + +/** This host's store as clients may list it, with its paired servers' catalogs. */ +export function readSidebarProjectCatalog( + store: SidebarProjectCatalogStore, + servers: readonly PairedServerCatalog[] +): MobileProjectSectionCatalog { + return buildSidebarProjectCatalog( + { + repos: runtimeVisibleRepos(store), + projectGroups: runtimeVisibleProjectGroups(store), + projects: store.getProjects?.() ?? [], + setups: runtimeVisibleProjectHostSetups(store) + }, + servers, + store.getUI?.() + ) +} diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-log.ts b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-log.ts similarity index 100% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed-log.ts rename to src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-log.ts diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.test.ts b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.test.ts similarity index 96% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.test.ts rename to src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.test.ts index 4352ef4ed23..1edbc41e6a5 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.test.ts +++ b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.test.ts @@ -4,7 +4,7 @@ import { SIDEBAR_INPUTS_PAGE_MIN_BYTES, SIDEBAR_INPUTS_SCHEMA_VERSION, SIDEBAR_INPUTS_SEMANTICS_VERSION -} from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' +} from '../../../../shared/sidebar-list/sidebar-inputs-feed-contract' import { feedEntityFromJson, paginateFeedChanges, diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.ts b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.ts similarity index 97% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.ts rename to src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.ts index 0567299dad6..ff2636e1048 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pages.ts +++ b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.ts @@ -1,4 +1,4 @@ -import type { SidebarInputsDomainChange } from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' +import type { SidebarInputsDomainChange } from '../../../../shared/sidebar-list/sidebar-inputs-feed-contract' /** One published entity: its value and that value's JSON, which the feed diffs and measures. */ export type FeedEntity = { value: unknown; json: string; bytes: number } diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pins.ts b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pins.ts similarity index 94% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pins.ts rename to src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pins.ts index 25fc7500d27..d7812d7fee1 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-pins.ts +++ b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pins.ts @@ -1,4 +1,4 @@ -import type { SidebarInputsReadResult } from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' +import type { SidebarInputsReadResult } from '../../../../shared/sidebar-list/sidebar-inputs-feed-contract' /** A multi-page batch stays readable this long after its last page read. */ export const FEED_PIN_IDLE_MS = 30_000 diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test.ts b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.test.ts similarity index 83% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test.ts rename to src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.test.ts index 0583d3a351e..e5ca73f4f67 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test.ts +++ b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.test.ts @@ -2,12 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { SidebarInputsChangedEvent, SidebarInputsReadResult -} from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' -import '../../../shared/sidebar-list/sidebar-inputs-feed-installer' +} from '../../../../shared/sidebar-list/sidebar-inputs-feed-contract' +import '../../../../shared/sidebar-list/sidebar-inputs-feed-installer' import { SidebarInputsFeed } from './sidebar-inputs-feed' import { FEED_LOG_MAX_REVISIONS } from './sidebar-inputs-feed-log' import { FEED_PIN_IDLE_MS, FEED_PIN_MAX_BATCHES } from './sidebar-inputs-feed-pins' -import { TestPhone, testDomain, truthOf } from './sidebar-inputs-feed.test-fixture' +import { TestPhone, testDomain, truthOf } from './testing/sidebar-inputs-feed.test-fixture' // Three ~100 KiB entities: a snapshot of them spans two 256 KiB pages. const BIG = 'x'.repeat(100 * 1024) @@ -127,26 +127,6 @@ describe('sidebar inputs feed', () => { expect(phone.view()).toEqual(host.truth()) }) - it('serves two phones from one session, which ends with the last of them', async () => { - const host = makeHost() - const first = new TestPhone(host.feed, 'conn-1') - const second = new TestPhone(host.feed, 'conn-2') - first.refresh() - second.refresh() - await Promise.all([first.settle(), second.settle()]) - expect(host.rows.reads()).toBe(1) - - first.disconnect() - host.rows.set('a', 2) - await flush() - second.notice(host.lastEvent()) - await second.settle() - expect(second.view()).toEqual(host.truth()) - - second.disconnect() - expect(host.rows.watchers()).toBe(0) - }) - it('replaces everything after a runtime restart, whose generation is new', async () => { const host = makeHost() const phone = new TestPhone(host.feed, 'conn-1') @@ -201,41 +181,6 @@ describe('sidebar inputs feed', () => { expect(phone.view().rows).toEqual({ a: 1 }) }) - it('re-reads a failed domain on the next read without retrying on its own', async () => { - const host = makeHost() - const phone = new TestPhone(host.feed, 'conn-1') - phone.refresh() - await phone.settle() - host.rows.fail(true) - host.rows.set('a', 2) - await flush() - const failedReads = host.rows.reads() - await vi.advanceTimersByTimeAsync(10_000) - expect(host.rows.reads()).toBe(failedReads) - - host.rows.fail(false) - phone.refresh() - await phone.settle() - expect(host.rows.reads()).toBe(failedReads + 1) - expect(phone.view()).toEqual(host.truth()) - }) - - it('re-reads a failed domain with the next flush another domain causes', async () => { - const host = makeHost() - const phone = new TestPhone(host.feed, 'conn-1') - phone.refresh() - await phone.settle() - host.rows.fail(true) - host.rows.set('a', 2) - await flush() - host.rows.fail(false) - host.view.set('sort', 'recent') - await flush() - phone.notice(host.lastEvent()) - await phone.settle() - expect(phone.view()).toEqual(host.truth()) - }) - it('bounds pinned batches, evicting the oldest', async () => { const host = makeHost({ a: BIG, b: BIG, c: BIG }) host.feed.acquire('conn-1') diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed.ts b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.ts similarity index 99% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed.ts rename to src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.ts index f419c881664..782664780c5 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed.ts +++ b/src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed.ts @@ -7,7 +7,7 @@ import { type SidebarInputsChangedEvent, type SidebarInputsReadParams, type SidebarInputsReadResult -} from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' +} from '../../../../shared/sidebar-list/sidebar-inputs-feed-contract' import { feedEntityFromJson, paginateFeedChanges, diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test-fixture.ts b/src/main/runtime/sidebar-inputs/feed/testing/sidebar-inputs-feed.test-fixture.ts similarity index 96% rename from src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test-fixture.ts rename to src/main/runtime/sidebar-inputs/feed/testing/sidebar-inputs-feed.test-fixture.ts index 8cb4904671c..a3598c8c04d 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed.test-fixture.ts +++ b/src/main/runtime/sidebar-inputs/feed/testing/sidebar-inputs-feed.test-fixture.ts @@ -1,7 +1,7 @@ import type { SidebarInputsChangedEvent, SidebarInputsReadResult -} from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' +} from '../../../../../shared/sidebar-list/sidebar-inputs-feed-contract' import { INITIAL_SIDEBAR_INPUTS_FEED_STATE, refreshSidebarInputs, @@ -10,12 +10,12 @@ import { type SidebarInputsFeedRequest, type SidebarInputsFeedState, type SidebarInputsFeedStep -} from '../../../shared/sidebar-list/sidebar-inputs-feed-installer' +} from '../../../../../shared/sidebar-list/sidebar-inputs-feed-installer' import type { SidebarInputsFeed, SidebarInputsFeedChange, SidebarInputsFeedDomain -} from './sidebar-inputs-feed' +} from '../sidebar-inputs-feed' /** A domain whose entities a test edits; counts its reads and live watchers. */ export function testDomain(name: string, initial: Record = {}) { diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-project-catalog.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-project-catalog.test.ts deleted file mode 100644 index f0a73cdf853..00000000000 --- a/src/main/runtime/sidebar-inputs/orca-runtime-project-catalog.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -// Runs on plain Node, as orcad does: the catalog comes from main's own store, no window publishes it. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import type { ProjectGroup } from '../../../shared/project-group-types' - -import type { Repo } from '../../../shared/repo-types' - -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' - -import { readSidebarFeedDomains } from '../../../shared/sidebar-list/sidebar-feed-domains' - -import '../../../shared/mobile-project-sections-contract' -import { OrcaRuntimeService } from '../orca-runtime' - -import '../rpc/methods/rpc-method-registry' -import type { RuntimeStore } from '../construction/runtime-store-contract' - -import { requireSwitchedOn } from './require-switched-on' - -import { TestPhone } from './sidebar-inputs-feed.test-fixture' - -import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' - -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) - -function group(id: string): ProjectGroup { - return { - id, - name: id, - parentPath: null, - parentGroupId: null, - createdFrom: 'manual', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } -} - -function setup() { - let repos: Repo[] = [ - { id: 'r', path: '/r', displayName: 'r', badgeColor: 'blue', addedAt: 1, projectGroupId: 'a' } - ] - const store: Pick = { - getRepos: () => repos, - getProjectGroups: () => [group('a'), group('school')] - } - const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) - const events: RuntimeClientEvent[] = [] - runtime.onClientEvent((event) => events.push(event)) - const feed = requireSwitchedOn(runtime.sidebarInputsFeed) - /** Moves the repo the way a host's IPC write does: store first, then reposChanged. */ - const write = (groupId: string): void => { - repos = repos.map((entry) => ({ ...entry, projectGroupId: groupId })) - runtime.notifyReposChangedForRemoteClients() - } - return { - runtime, - feed, - write, - move: async (groupId: string) => { - write(groupId) - await vi.advanceTimersByTimeAsync(60) - const notice = events.findLast((event) => event.type === 'sidebarInputsChanged') - if (notice?.type !== 'sidebarInputsChanged') { - throw new Error('no change notice') - } - return notice - } - } -} - -function groupOf(phone: TestPhone): string | null | undefined { - const installed = phone.state.installed - return installed - ? readSidebarFeedDomains(installed).projectCatalog?.repos.find((repo) => repo.id === 'r') - ?.projectGroupId - : undefined -} - -beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() -}) - -describe('the project catalog in the sidebar feed', () => { - it('reaches a move made while an earlier read is held, with no further trigger', async () => { - const { feed, move } = setup() - const phone = new TestPhone(feed, 'conn-1') - phone.refresh() - await phone.settle() - phone.refresh() - // The host answered the read before the move; its reply reaches the phone only after. - const held = await phone.serveOne() - const notice = await move('school') - phone.notice(notice) - held.deliver() - expect(groupOf(phone)).toBe('a') - await phone.settle() - expect(groupOf(phone)).toBe('school') - phone.disconnect() - }) -}) diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-inputs-feed.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-inputs-feed.test.ts index 72934993a12..10241c9befa 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-inputs-feed.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-inputs-feed.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' import { OrcaRuntimeService } from '../orca-runtime' -import { requireSwitchedOn } from './require-switched-on' -import { TestPhone } from './sidebar-inputs-feed.test-fixture' +import { requireSwitchedOn } from '../construction/require-sidebar-inputs-enabled' +import { TestPhone } from './feed/testing/sidebar-inputs-feed.test-fixture' vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts index 78c56efe1d5..2609f99f409 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts @@ -1,6 +1,6 @@ import { getRepoRegistrationHostIds } from '../../../shared/repo-host-identity' import { isRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' -import { OrcaRuntimeWithDetectedCheckoutsAndLiveContent } from './orca-runtime-detected-checkouts-live-content' +import { OrcaRuntimeWithDetectedCheckoutsAndLiveContent } from './workspace-facts/orca-runtime-detected-checkouts-live-content' import type { OrcaRuntimeWithAgentTransitions } from '../construction/orca-runtime-agent-transitions' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../shared/sidebar-inputs-switch' import { DEFAULT_HIDE_SLEEPING_WORKSPACES } from '../../../shared/constants' @@ -12,15 +12,18 @@ import { type ExecutionHostId } from '../../../shared/execution-host' import type { SidebarTemporalSnapshot } from '../../../shared/sidebar-list/sidebar-temporal-snapshot' -import type { WorkspaceRowsProducer } from './workspace-rows-producer' -import { SidebarRetentionOwner, type SidebarRetentionCandidates } from './sidebar-retention-owner' -import type { AgentStatusStoreView } from './workspace-activity-facts-producer' -import { SortStampsProducer } from './sort-stamps-producer' -import { writeUnreadFlag } from './sort-stamp-records' -import { WorkspaceViewers } from './workspace-viewers' +import type { WorkspaceRowsProducer } from './workspace-rows/workspace-rows-producer' +import { + SidebarRetentionOwner, + type SidebarRetentionCandidates +} from './temporal/sidebar-retention-owner' +import type { AgentStatusStoreView } from './workspace-facts/workspace-activity-facts-producer' +import { SortStampsProducer } from './temporal/sort-stamps-producer' +import { writeUnreadFlag } from '../workspaces/metadata/workspace-activity-records' +import { WorkspaceViewers } from './temporal/workspace-viewers' import { clientRaisesUnreadFlagItself } from '../../../shared/workspace-unread-raise-capability' import type { RuntimeCapability } from '../../../shared/protocol-version' -import { TerminalUseProducer } from './terminal-use-producer' +import { TerminalUseProducer } from './temporal/terminal-use-producer' import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { getRepoIdFromWorktreeId, worktreeIdentityKey } from '../../../shared/worktree/id' import { diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-terminal-use.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-terminal-use.test.ts deleted file mode 100644 index 87c015fd692..00000000000 --- a/src/main/runtime/sidebar-inputs/orca-runtime-terminal-use.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Runs on plain Node, as orcad does: the host that owns a workspace records its terminal use. -import { describe, expect, it, vi } from 'vitest' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { - WORKSPACE_CLEANUP_IDLE_MS, - getPersistedWorkspaceCleanupActivityAt, - isWorkspaceOldForCleanup -} from '../../../shared/workspace-cleanup/workspace-cleanup' -import { OrcaRuntimeService } from '../orca-runtime' -import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' -import { - partialRuntimeStore, - storeRepo, - storeWorktreeMeta, - type PartialRuntimeStore -} from '../orca-runtime-tests/runtime-store-partial-fixture' - -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) - -const WT = 'repo-1::/tmp/phone-only' -const DAY_MS = 24 * 60 * 60 * 1000 - -function createHeadlessRuntime(ptyId = 'pty-1') { - // Untouched for 45 days: no agent ran, so no Recent stamp moved. - const meta: Record = { [WT]: storeWorktreeMeta({ lastActivityAt: 1 }) } - const writes: Partial[] = [] - const repo = storeRepo({ id: 'repo-1', path: '/tmp/repo-1', connectionId: null }) - const store: PartialRuntimeStore = { - // An unstamped row's writes resolve their host from its repo's only registration. - getRepos: () => [repo], - getRepo: (id: string) => (id === repo.id ? repo : undefined), - getSettings: () => ({}), - getWorktreeMeta: (id: string) => meta[id], - getAllWorktreeMeta: () => meta, - setWorktreeMeta: ({ id }: HostWorktreeTarget, updates: Partial) => { - writes.push(updates) - meta[id] = { ...meta[id], ...updates } - return meta[id] - } - } - const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) - // No desktop window: the phone is the only client. - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { - tabs: [{ tabId: 'tab-1', worktreeId: WT, title: 'zsh', activeLeafId: 'pane:1', layout: null }], - leaves: [ - { - tabId: 'tab-1', - worktreeId: WT, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId, - paneTitle: null - } - ] - }) - return { runtime, meta, writes } -} - -describe('host-written terminal use', () => { - it('a phone-only workspace whose terminals are closed is not idle to cleanup', () => { - const now = 45 * DAY_MS - vi.useFakeTimers({ now }) - try { - const { runtime, meta } = createHeadlessRuntime() - // Typing in a plain shell from the phone goes through the host's one input funnel. - runtime.terminalRunFacts.recordInput('pty-1', 'driving', 'ls\r', now - 2 * DAY_MS) - runtime.onPtyExit('pty-1', 0) - expect(meta[WT]?.lastTerminalUseAt).toBe(now - 2 * DAY_MS) - const workspace = { isArchived: false, lastActivityAt: meta[WT]?.lastActivityAt ?? 0 } - expect(isWorkspaceOldForCleanup(workspace, now)).toBe(true) - const lastActive = getPersistedWorkspaceCleanupActivityAt({ - lastActivityAt: workspace.lastActivityAt, - lastTerminalUseAt: meta[WT]?.lastTerminalUseAt - }) - expect(isWorkspaceOldForCleanup({ ...workspace, lastActivityAt: lastActive }, now)).toBe( - false - ) - expect(now - lastActive).toBeLessThan(WORKSPACE_CLEANUP_IDLE_MS) - } finally { - vi.useRealTimers() - } - }) - - it('app-written launch input never counts', () => { - const launch = createHeadlessRuntime() - launch.runtime.terminalRunFacts.recordInput('pty-1', 'launch', 'claude\r', 1_000) - expect(launch.writes).toEqual([]) - }) - - it("a paired server's terminal is not this host's to record", () => { - const mirrored = createHeadlessRuntime('remote:server-pty') - mirrored.runtime.terminalRunFacts.recordInput('remote:server-pty', 'driving', 'ls\r', 1_000) - expect(mirrored.writes).toEqual([]) - }) - - it('output never counts as use', () => { - const { runtime, writes } = createHeadlessRuntime() - runtime.onPtyData('pty-1', 'lots of output\r\n', 1) - expect(writes.filter((w) => 'lastTerminalUseAt' in w)).toEqual([]) - }) -}) diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts deleted file mode 100644 index c85f052a214..00000000000 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts +++ /dev/null @@ -1,273 +0,0 @@ -// Runs on plain Node, as orcad does: a host with no window raises and clears its own unread flags. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { OrcaRuntimeService } from '../orca-runtime' -import { RpcDispatcher } from '../rpc/dispatcher' -import type { RpcDispatchStreamingOptions } from '../rpc/dispatcher-stream-options' -import { SESSION_TAB_METHODS } from '../rpc/methods/session-tabs/session-tabs' -import { SIDEBAR_INPUT_METHODS } from '../rpc/methods/sidebar-inputs/sidebar-inputs' -import { requireSwitchedOn } from './require-switched-on' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' -import { remoteRuntimeClientCapabilities } from '../../../shared/remote-runtime/remote-runtime-client-capabilities' -import { WORKSPACE_UNREAD_HOST_RAISES_CAPABILITY } from '../../../shared/workspace-unread-raise-capability' -import { - BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY, - BROWSER_CLIENT_PAGE_METADATA_RUNTIME_CAPABILITY, - BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY -} from '../../../shared/browser/runtime/browser-runtime-capabilities' -import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' -import { - partialRuntimeStore, - storeFolderWorkspace, - storeProjectGroup, - storeRepo, - storeWorktreeMeta, - type PartialRuntimeStore -} from '../orca-runtime-tests/runtime-store-partial-fixture' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' - -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) - -const WT = 'repo-1::/tmp/worktree-a' -const SSH_WT = 'repo-ssh::/home/me/worktree-b' -const HUB_WT = 'repo-hub::/srv/worktree-c' -const FOLDER_ID = '11111111-1111-4111-8111-111111111111' -const FOLDER = folderWorkspaceKey(FOLDER_ID) -const LEAF = '22222222-2222-4222-8222-222222222222' -const PANE = `tab-1:${LEAF}` -const PHONE: RpcDispatchStreamingOptions = { clientKind: 'mobile', connectionId: 'phone-1' } - -/** Desktop request, subscription, browser-host lease, network-tunnel and CLI capability sets. */ -function currentDesktopSockets() { - return { - request: remoteRuntimeClientCapabilities(ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES), - lease: remoteRuntimeClientCapabilities([ - BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY, - BROWSER_CLIENT_PAGE_METADATA_RUNTIME_CAPABILITY - ]), - tunnel: remoteRuntimeClientCapabilities([ - BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY, - BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY - ]), - cli: remoteRuntimeClientCapabilities() - } -} - -function createHeadlessHost() { - const meta: Record = { [WT]: storeWorktreeMeta() } - const sshMeta: Record = { [SSH_WT]: storeWorktreeMeta() } - // A same-id project this host registered under a server's id and locally. - const hubMeta: Record = { [HUB_WT]: storeWorktreeMeta() } - meta[HUB_WT] = storeWorktreeMeta() - const folders: Record = { - [FOLDER_ID]: storeFolderWorkspace({ - id: FOLDER_ID, - projectGroupId: 'group-1', - folderPath: '/tmp/folder' - }) - } - const repos = [ - storeRepo({ id: 'repo-1', path: '/tmp/repo-1', connectionId: null }), - storeRepo({ id: 'repo-ssh', path: '/home/user/repo-ssh', connectionId: 'build-box' }), - storeRepo({ - id: 'repo-hub', - path: '/srv/repo-hub', - connectionId: null, - executionHostId: 'runtime:hub' - }), - storeRepo({ id: 'repo-hub', path: '/tmp/repo-hub', connectionId: null }) - ] - const store: PartialRuntimeStore = { - getRepos: () => repos, - getRepo: (id: string) => repos.find((repo) => repo.id === id), - getProjectGroups: () => [storeProjectGroup({ id: 'group-1', connectionId: null })], - getSettings: () => ({}), - getWorktreeMeta: (id: string) => meta[id], - getAllWorktreeMeta: () => meta, - setWorktreeMeta: ({ id, hostId }: HostWorktreeTarget, updates: Partial) => - Object.assign( - hostId === 'ssh:build-box' - ? sshMeta[id] - : hostId === 'runtime:hub' - ? hubMeta[id] - : meta[id], - updates - ), - getWorktreeMetaForHost: (id: string, hostId: string) => - hostId === 'ssh:build-box' ? sshMeta[id] : hostId === 'runtime:hub' ? hubMeta[id] : meta[id], - getFolderWorkspace: (id: string) => folders[id], - updateFolderWorkspace: (id: string, updates: Partial) => - Object.assign(folders[id], updates) - } - const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) - runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { - tabs: [{ tabId: 'tab-1', worktreeId: WT, title: 'Agent', activeLeafId: LEAF, layout: null }], - leaves: [ - { - tabId: 'tab-1', - worktreeId: WT, - leafId: LEAF, - paneRuntimeId: 1, - ptyId: 'pty-1', - paneTitle: null - } - ] - }) - const server = new AgentHookServer() - runtime.attachAgentStatusStore(server) - const dispatcher = new RpcDispatcher({ - runtime, - methods: [...SIDEBAR_INPUT_METHODS, ...SESSION_TAB_METHODS] - }) - let requestId = 0 - const finishTurn = (worktreeId = WT, connectionId?: string): void => { - for (const state of ['working', 'done'] as const) { - server.ingestTerminalStatus({ - paneKey: PANE, - tabId: 'tab-1', - worktreeId, - ...(connectionId ? { connectionId } : {}), - payload: { state, prompt: 'task', agentType: 'claude' } - }) - } - } - return { - runtime, - meta, - sshMeta, - hubMeta, - folders, - finishTurn, - // The phone's session screen holds this stream while the workspace is open on it. - openOnPhone: (worktreeId: string) => - dispatcher.dispatchStreaming( - { - id: `sub-${++requestId}`, - authToken: 'tok', - method: 'session.tabs.subscribe', - params: { worktree: `id:${worktreeId}` } - }, - () => {}, - PHONE - ), - reportView: (params: unknown, connectionId: string | undefined) => - dispatcher.dispatch( - { id: `view-${++requestId}`, authToken: 'tok', method: 'sidebarInputs.reportView', params }, - { clientKind: 'runtime', connectionId } - ) - } -} - -beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('workspace unread flag on a headless host', () => { - it('flags a finish no one sees, clears it when the phone opens it, and spares it while open', async () => { - const host = createHeadlessHost() - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(true) - - await host.openOnPhone(WT) - expect(host.meta[WT].isUnread).toBe(false) - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(false) - - // Leaving the session (its stream closes with the connection) makes the next finish news. - host.runtime.cleanupSubscriptionsForConnection('phone-1') - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(true) - }) - - it('clears a folder workspace and an SSH worktree on their own records when the phone opens them', async () => { - const host = createHeadlessHost() - host.folders[FOLDER_ID].isUnread = true - host.sshMeta[SSH_WT].isUnread = true - await host.openOnPhone(FOLDER) - expect(host.folders[FOLDER_ID].isUnread).toBe(false) - await host.openOnPhone(SSH_WT) - expect(host.sshMeta[SSH_WT].isUnread).toBe(false) - - // The SSH finish raises the SSH host's record once the phone has left. - host.runtime.cleanupSubscriptionsForConnection('phone-1') - host.finishTurn(SSH_WT, 'build-box') - expect(host.sshMeta[SSH_WT].isUnread).toBe(true) - }) - - // The phone names only an id, so it cannot say which of two same-id copies it shows. - it('clears neither copy of a workspace two hosts register', async () => { - const host = createHeadlessHost() - host.hubMeta[HUB_WT].isUnread = true - host.meta[HUB_WT].isUnread = true - await host.openOnPhone(HUB_WT) - expect(host.hubMeta[HUB_WT].isUnread).toBe(true) - expect(host.meta[HUB_WT].isUnread).toBe(true) - }) - - it('spares the tab a client window shows while its user is present', async () => { - vi.useFakeTimers({ now: 10_000, toFake: ['Date'] }) - try { - const host = createHeadlessHost() - const view = { workspaceIds: [WT], tabIds: ['tab-1'], presentForMs: 60_000 } - expect(await host.reportView(view, 'desktop-1')).toMatchObject({ ok: true }) - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(false) - - // Another tab on screen is not this pane's. - await host.reportView({ ...view, tabIds: ['tab-2'] }, 'desktop-1') - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(true) - - host.meta[WT].isUnread = false - await host.reportView(view, 'desktop-1') - vi.setSystemTime(10_000 + 60_000) - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(true) - - // A client that disconnects stops counting; one with no connection cannot report. - expect(await host.reportView(view, undefined)).toMatchObject({ ok: false }) - host.meta[WT].isUnread = false - await host.reportView({ ...view, presentForMs: null }, 'desktop-1') - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(false) - host.runtime.cleanupSubscriptionsForConnection('desktop-1') - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(true) - } finally { - vi.useRealTimers() - } - }) - - it('leaves raising to an older desktop while it is connected, and still clears on the phone', async () => { - const host = createHeadlessHost() - // Either its request socket or its browser host lease hosts client pages without the capability. - const older = (capabilities: readonly string[]) => - capabilities.filter((capability) => capability !== WORKSPACE_UNREAD_HOST_RAISES_CAPABILITY) - const facts = requireSwitchedOn(host.runtime.sidebarFacts) - facts.noteRuntimeClient('desktop-old', older(currentDesktopSockets().request)) - facts.noteRuntimeClient('desktop-old-lease', older(currentDesktopSockets().lease)) - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(false) - - // The older desktop raised it by its own rule; the phone opening it still clears it here. - host.meta[WT].isUnread = true - await host.openOnPhone(WT) - expect(host.meta[WT].isUnread).toBe(false) - host.runtime.cleanupSubscriptionsForConnection('phone-1') - - host.runtime.cleanupSubscriptionsForConnection('desktop-old') - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(false) - host.runtime.cleanupSubscriptionsForConnection('desktop-old-lease') - host.finishTurn() - expect(host.meta[WT].isUnread).toBe(true) - }) -}) diff --git a/src/main/runtime/sidebar-inputs/repo-icon-data-urls.test.ts b/src/main/runtime/sidebar-inputs/repo-icon-data-urls.test.ts deleted file mode 100644 index 794f8b4415c..00000000000 --- a/src/main/runtime/sidebar-inputs/repo-icon-data-urls.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RepoIcon } from '../../../shared/repo-icon' -import type { Repo } from '../../../shared/repo-types' -import { MAX_REPO_ICON_DATA_URL_BYTES } from '../../../shared/sidebar-list/repo-icon-data-urls-contract' -import { RepoIconDataUrls, repoIconId, type RepoIconPngEncoder } from './repo-icon-data-urls' -import type { RepoIconFetch } from './repo-icon-remote-fetch' -import { pngHeader } from './repo-icon-image-fixture' - -const AVATAR: RepoIcon = { - type: 'image', - src: 'https://github.com/stablyai.png?size=64', - source: 'github' -} - -function upload(bytes: Uint8Array): RepoIcon { - return { - type: 'image', - src: `data:image/png;base64,${Buffer.from(bytes).toString('base64')}`, - source: 'upload' - } -} - -function repo(id: string, repoIcon: RepoIcon | null): Repo { - return { id, path: `/r/${id}`, displayName: id, badgeColor: '#000', addedAt: 0, repoIcon } -} - -function pngResponse(bytes: Uint8Array = pngHeader(64, 64)): Response { - return new Response(Buffer.from(bytes), { headers: { 'content-type': 'image/png' } }) -} - -function setup( - repos: Repo[], - options: { encoder?: RepoIconPngEncoder; fetch?: RepoIconFetch } = {} -) { - let now = 1_000 - const fetch = vi.fn(options.fetch ?? (async () => pngResponse())) - const icons = new RepoIconDataUrls({ - repos: () => repos, - fetch, - encoder: () => options.encoder, - now: () => now - }) - return { icons, fetch, advance: (ms: number) => (now += ms) } -} - -const ENCODED = new Uint8Array([1, 2, 3]) -const ENCODED_URL = 'data:image/png;base64,AQID' - -describe('RepoIconDataUrls without an encoder (orcad)', () => { - it('passes a small fetched image through as a data URL', async () => { - const bytes = pngHeader(64, 64) - const { icons } = setup([repo('a', AVATAR)]) - const id = repoIconId(AVATAR)! - - expect(await icons.read([id])).toEqual({ - icons: [{ id, dataUrl: `data:image/png;base64,${Buffer.from(bytes).toString('base64')}` }] - }) - }) - - it('falls back for an upload too large to pass through', async () => { - const icon = upload(pngHeader(64, 64, MAX_REPO_ICON_DATA_URL_BYTES)) - const { icons } = setup([repo('a', icon)]) - - expect((await icons.read([repoIconId(icon)!])).icons[0].dataUrl).toBeNull() - }) - - it('answers null for an id no repo shows, in request order', async () => { - const { icons, fetch } = setup([repo('a', AVATAR)]) - const id = repoIconId(AVATAR)! - - const reply = await icons.read(['missing', id]) - - expect(reply.icons.map((icon) => [icon.id, icon.dataUrl === null])).toEqual([ - ['missing', true], - [id, false] - ]) - expect(fetch).toHaveBeenCalledTimes(1) - }) -}) - -describe('RepoIconDataUrls.idsByRepo', () => { - it('names each repo’s image by host and repo, the ids a read answers', async () => { - const remote = { ...repo('a', AVATAR), connectionId: 'box' } - const { icons } = setup([ - repo('a', AVATAR), - remote, - repo('glyph', { type: 'emoji', emoji: 'x' }), - repo('none', null) - ]) - const id = repoIconId(AVATAR)! - - expect(icons.idsByRepo()).toEqual({ 'local|a': id, 'ssh:box|a': id }) - expect((await icons.read([id])).icons[0].dataUrl).not.toBeNull() - }) -}) - -describe('RepoIconDataUrls with an encoder (desktop)', () => { - it('re-encodes a large upload rather than dropping it', async () => { - const icon = upload(pngHeader(1024, 1024, 300 * 1024)) - const { icons } = setup([repo('a', icon)], { encoder: () => ENCODED }) - - expect((await icons.read([repoIconId(icon)!])).icons[0].dataUrl).toBe(ENCODED_URL) - }) - - it('steps down to 32 px when the 64 px PNG is over the cap', async () => { - const huge = new Uint8Array(MAX_REPO_ICON_DATA_URL_BYTES) - const encoder = vi.fn((_bytes, edge) => (edge === 64 ? huge : ENCODED)) - const { icons } = setup([repo('a', AVATAR)], { encoder }) - - expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toBe(ENCODED_URL) - expect(encoder.mock.calls.map(([, edge]) => edge)).toEqual([64, 32]) - }) - - it('passes a small image the decoder cannot read through, as orcad would', async () => { - const { icons } = setup([repo('a', AVATAR)], { encoder: () => null }) - expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toMatch( - /^data:image\/png;base64,/ - ) - }) - - it('falls back when neither encoding nor passthrough fits the cap', async () => { - const icon = upload(pngHeader(64, 64, MAX_REPO_ICON_DATA_URL_BYTES)) - const huge = new Uint8Array(MAX_REPO_ICON_DATA_URL_BYTES) - const encoder = vi.fn(() => huge) - const { icons } = setup([repo('a', icon)], { encoder }) - - expect((await icons.read([repoIconId(icon)!])).icons[0].dataUrl).toBeNull() - expect(encoder).toHaveBeenCalledTimes(2) - }) -}) - -describe('RepoIconDataUrls caps', () => { - it('refuses bytes that are not a readable raster image, before decoding', async () => { - const encoder = vi.fn(() => ENCODED) - const { icons } = setup([repo('a', AVATAR)], { - encoder, - fetch: async () => pngResponse(new Uint8Array([1, 2, 3, 4])) - }) - - expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toBeNull() - expect(encoder).not.toHaveBeenCalled() - }) - - it('refuses a fetched image over 512 px before decoding', async () => { - const encoder = vi.fn(() => ENCODED) - const { icons } = setup([repo('a', AVATAR)], { - encoder, - fetch: async () => pngResponse(pngHeader(513, 64)) - }) - - expect((await icons.read([repoIconId(AVATAR)!])).icons[0].dataUrl).toBeNull() - expect(encoder).not.toHaveBeenCalled() - }) - - it('runs at most four fetches at once', async () => { - const releases: (() => void)[] = [] - let active = 0 - let peak = 0 - const avatars = Array.from({ length: 10 }, (_, index): RepoIcon => ({ - ...AVATAR, - src: `https://github.com/owner${index}.png` - })) - const { icons } = setup( - avatars.map((icon, index) => repo(`r${index}`, icon)), - { - fetch: () => { - active += 1 - peak = Math.max(peak, active) - return new Promise((resolve) => - releases.push(() => { - active -= 1 - resolve(pngResponse()) - }) - ) - } - } - ) - - const reply = icons.read(avatars.map((icon) => repoIconId(icon)!)) - for (let settled = 0; settled < avatars.length; settled += 1) { - await vi.waitFor(() => expect(releases.length).toBeGreaterThan(settled)) - releases[settled]() - } - - expect((await reply).icons.every((icon) => icon.dataUrl !== null)).toBe(true) - expect(peak).toBe(4) - }) -}) - -describe('RepoIconDataUrls cache', () => { - it('fetches an avatar shared by two repos once, across concurrent and later reads', async () => { - const { icons, fetch } = setup([repo('a', AVATAR), repo('b', { ...AVATAR, label: 'b' })]) - const id = repoIconId(AVATAR)! - - await Promise.all([icons.read([id, id]), icons.read([id])]) - await icons.read([id]) - - expect(fetch).toHaveBeenCalledTimes(1) - }) - - it('retries a failed fetch after five minutes, a success only after an hour', async () => { - let fail = true - const { icons, fetch, advance } = setup([repo('a', AVATAR)], { - fetch: async () => (fail ? new Response(null, { status: 503 }) : pngResponse()) - }) - const id = repoIconId(AVATAR)! - - expect((await icons.read([id])).icons[0].dataUrl).toBeNull() - fail = false - advance(4 * 60 * 1000) - expect((await icons.read([id])).icons[0].dataUrl).toBeNull() - advance(60 * 1000 + 1) - expect((await icons.read([id])).icons[0].dataUrl).not.toBeNull() - advance(59 * 60 * 1000) - await icons.read([id]) - expect(fetch).toHaveBeenCalledTimes(2) - advance(60 * 1000 + 1) - await icons.read([id]) - expect(fetch).toHaveBeenCalledTimes(3) - }) - - it('evicts the least recently read icons past 1 MiB', async () => { - const avatars = Array.from({ length: 80 }, (_, index): RepoIcon => ({ - ...AVATAR, - src: `https://github.com/owner${index}.png` - })) - // Each encoded icon is just under the 16 KiB cap, so 80 of them overflow 1 MiB. - const nearCap = new Uint8Array(12 * 1024 - 64) - const { icons, fetch } = setup( - avatars.map((icon, index) => repo(`r${index}`, icon)), - { encoder: () => nearCap } - ) - const ids = avatars.map((icon) => repoIconId(icon)!) - - for (let start = 0; start < ids.length; start += 16) { - await icons.read(ids.slice(start, start + 16)) - } - expect(fetch).toHaveBeenCalledTimes(80) - await icons.read([ids[79]]) - expect(fetch).toHaveBeenCalledTimes(80) - await icons.read([ids[0]]) - expect(fetch).toHaveBeenCalledTimes(81) - }) -}) diff --git a/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.test.ts b/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.test.ts deleted file mode 100644 index b3765b0feb3..00000000000 --- a/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - fetchRemoteRepoIcon, - REPO_ICON_FETCH_MAX_BYTES, - type RepoIconFetch -} from './repo-icon-remote-fetch' -import { pngHeader } from './repo-icon-image-fixture' - -const AVATAR = 'https://github.com/stablyai.png?size=64' - -function image(bytes: Uint8Array, headers: Record = {}): Response { - return new Response(Buffer.from(bytes), { - status: 200, - headers: { 'content-type': 'image/png', ...headers } - }) -} - -function redirect(location: string): Response { - return new Response(null, { status: 302, headers: { location } }) -} - -describe('fetchRemoteRepoIcon', () => { - it('follows up to three https redirects without cookies', async () => { - const fetch = vi - .fn() - .mockResolvedValueOnce(redirect('https://avatars.example/a')) - .mockResolvedValueOnce(redirect('/b')) - .mockResolvedValueOnce(redirect('https://avatars.example/c')) - .mockResolvedValueOnce(image(pngHeader(64, 64))) - - const fetched = await fetchRemoteRepoIcon(AVATAR, fetch) - - expect(fetched?.mimeType).toBe('image/png') - expect(fetch.mock.calls.map(([url]) => url)).toEqual([ - AVATAR, - 'https://avatars.example/a', - 'https://avatars.example/b', - 'https://avatars.example/c' - ]) - expect(fetch.mock.calls[0][1]).toMatchObject({ redirect: 'manual', credentials: 'omit' }) - }) - - it('gives up on a redirect loop after three hops', async () => { - const fetch = vi.fn(async () => redirect(AVATAR)) - - expect(await fetchRemoteRepoIcon(AVATAR, fetch)).toBeNull() - expect(fetch).toHaveBeenCalledTimes(4) - }) - - it('refuses a redirect off https', async () => { - const fetch = vi.fn(async () => redirect('http://avatars.example/a')) - - expect(await fetchRemoteRepoIcon(AVATAR, fetch)).toBeNull() - expect(fetch).toHaveBeenCalledTimes(1) - }) - - it('refuses a body declared over the cap without reading it', async () => { - const response = image(pngHeader(64, 64), { - 'content-length': String(REPO_ICON_FETCH_MAX_BYTES + 1) - }) - const cancel = vi.spyOn(response.body!, 'cancel') - - expect(await fetchRemoteRepoIcon(AVATAR, async () => response)).toBeNull() - expect(cancel).toHaveBeenCalled() - }) - - it('stops reading an undeclared body once it passes the cap', async () => { - const chunk = new Uint8Array(16 * 1024) - let pulls = 0 - const body = new ReadableStream({ - pull: (controller) => { - pulls += 1 - controller.enqueue(chunk) - } - }) - const response = new Response(body, { headers: { 'content-type': 'image/png' } }) - - expect(await fetchRemoteRepoIcon(AVATAR, async () => response)).toBeNull() - expect(pulls).toBeLessThan(10) - }) - - it('refuses a reply that is not a raster image', async () => { - const svg = new Response('', { headers: { 'content-type': 'image/svg+xml' } }) - expect(await fetchRemoteRepoIcon(AVATAR, async () => svg)).toBeNull() - const missing = new Response('nope', { status: 404, headers: { 'content-type': 'image/png' } }) - expect(await fetchRemoteRepoIcon(AVATAR, async () => missing)).toBeNull() - }) - - it('refuses non-https and credentialed sources', async () => { - const fetch = vi.fn() - expect(await fetchRemoteRepoIcon('http://github.com/a.png', fetch)).toBeNull() - expect(await fetchRemoteRepoIcon('https://user:pw@github.com/a.png', fetch)).toBeNull() - expect(fetch).not.toHaveBeenCalled() - }) - - it('times out a server that never answers', async () => { - const fetch: RepoIconFetch = (_url, init) => - new Promise((_resolve, reject) => - init.signal?.addEventListener('abort', () => reject(init.signal?.reason)) - ) - - expect(await fetchRemoteRepoIcon(AVATAR, fetch, 20)).toBeNull() - }) - - it('times out a body that stalls after the headers', async () => { - const fetch: RepoIconFetch = async (_url, init) => { - const body = new ReadableStream({ - start: (controller) => { - init.signal?.addEventListener('abort', () => controller.error(init.signal?.reason)) - } - }) - return new Response(body, { headers: { 'content-type': 'image/png' } }) - } - - expect(await fetchRemoteRepoIcon(AVATAR, fetch, 20)).toBeNull() - }) -}) diff --git a/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.test.ts b/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.test.ts new file mode 100644 index 00000000000..fb397039a24 --- /dev/null +++ b/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RepoIcon } from '../../../../shared/repo-icon' +import type { Repo } from '../../../../shared/repo-types' +import { RepoIconDataUrls, repoIconId, type RepoIconPngEncoder } from './repo-icon-data-urls' +import type { RepoIconFetch } from './repo-icon-remote-fetch' +import { pngHeader } from './testing/repo-icon-image-fixture' + +const AVATAR: RepoIcon = { + type: 'image', + src: 'https://github.com/stablyai.png?size=64', + source: 'github' +} + +function repo(id: string, repoIcon: RepoIcon | null): Repo { + return { id, path: `/r/${id}`, displayName: id, badgeColor: '#000', addedAt: 0, repoIcon } +} + +function pngResponse(bytes: Uint8Array = pngHeader(64, 64)): Response { + return new Response(Buffer.from(bytes), { headers: { 'content-type': 'image/png' } }) +} + +function setup( + repos: Repo[], + options: { encoder?: RepoIconPngEncoder; fetch?: RepoIconFetch } = {} +) { + let now = 1_000 + const fetch = vi.fn(options.fetch ?? (async () => pngResponse())) + const icons = new RepoIconDataUrls({ + repos: () => repos, + fetch, + encoder: () => options.encoder, + now: () => now + }) + return { icons, fetch, advance: (ms: number) => (now += ms) } +} + +describe('RepoIconDataUrls cache', () => { + it('retries a failed fetch after five minutes, a success only after an hour', async () => { + let fail = true + const { icons, fetch, advance } = setup([repo('a', AVATAR)], { + fetch: async () => (fail ? new Response(null, { status: 503 }) : pngResponse()) + }) + const id = repoIconId(AVATAR)! + + expect((await icons.read([id])).icons[0].dataUrl).toBeNull() + fail = false + advance(4 * 60 * 1000) + expect((await icons.read([id])).icons[0].dataUrl).toBeNull() + advance(60 * 1000 + 1) + expect((await icons.read([id])).icons[0].dataUrl).not.toBeNull() + advance(59 * 60 * 1000) + await icons.read([id]) + expect(fetch).toHaveBeenCalledTimes(2) + advance(60 * 1000 + 1) + await icons.read([id]) + expect(fetch).toHaveBeenCalledTimes(3) + }) +}) diff --git a/src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts b/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.ts similarity index 95% rename from src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts rename to src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.ts index 3616ca7ddad..03af6dc31b6 100644 --- a/src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts +++ b/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.ts @@ -1,18 +1,18 @@ import { createHash } from 'node:crypto' -import type { RepoIcon } from '../../../shared/repo-icon' -import type { Repo } from '../../../shared/repo-types' -import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions' +import type { RepoIcon } from '../../../../shared/repo-icon' +import type { Repo } from '../../../../shared/repo-types' +import { readRasterImageDimensions } from '../../../../shared/file-preview/raster-image-dimensions' import { MAX_REPO_ICON_DATA_URL_BYTES, repoIconFeedKey, type RepoIconDataUrlsReply -} from '../../../shared/sidebar-list/repo-icon-data-urls-contract' +} from '../../../../shared/sidebar-list/repo-icon-data-urls-contract' import { fetchRemoteRepoIcon, type FetchedRepoIcon, type RepoIconFetch } from './repo-icon-remote-fetch' -import type { RuntimeDesktopSurface } from '../construction/runtime-desktop-surface' +import type { RuntimeDesktopSurface } from '../../construction/runtime-desktop-surface' export type RepoIconPngEncoder = NonNullable diff --git a/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts b/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-remote-fetch.ts similarity index 96% rename from src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts rename to src/main/runtime/sidebar-inputs/repo-icons/repo-icon-remote-fetch.ts index 525672eb455..e63f430b3b8 100644 --- a/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts +++ b/src/main/runtime/sidebar-inputs/repo-icons/repo-icon-remote-fetch.ts @@ -1,4 +1,4 @@ -import { isKnownRasterImageMimeType } from '../../../shared/file-preview/raster-image-preview-limits' +import { isKnownRasterImageMimeType } from '../../../../shared/file-preview/raster-image-preview-limits' export const REPO_ICON_FETCH_MAX_BYTES = 64 * 1024 export const REPO_ICON_FETCH_MAX_REDIRECTS = 3 diff --git a/src/main/runtime/sidebar-inputs/repo-icon-image-fixture.ts b/src/main/runtime/sidebar-inputs/repo-icons/testing/repo-icon-image-fixture.ts similarity index 100% rename from src/main/runtime/sidebar-inputs/repo-icon-image-fixture.ts rename to src/main/runtime/sidebar-inputs/repo-icons/testing/repo-icon-image-fixture.ts diff --git a/src/main/runtime/sidebar-inputs/runtime-workspace-view-change-events.ts b/src/main/runtime/sidebar-inputs/runtime-workspace-view-change-events.ts deleted file mode 100644 index a8974d1839e..00000000000 --- a/src/main/runtime/sidebar-inputs/runtime-workspace-view-change-events.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { isDeepStrictEqual } from 'node:util' -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import { ALL_WORKSPACE_VIEW_UI_FIELDS } from '../../../shared/workspace-view/workspace-view-ui-fields' -import type { RuntimeStore } from '../construction/runtime-store-contract' - -/** The settings a phone's workspace list mirrors: Card layout, card style and pinned placement. */ -const WORKSPACE_VIEW_SETTINGS: readonly (keyof GlobalSettings)[] = [ - 'compactWorktreeCards', - 'experimentalNewWorktreeCardStyle', - 'showPinnedWorktreesInGroups' -] - -function workspaceViewUiValues(ui: PersistedUIState): unknown[] { - return ALL_WORKSPACE_VIEW_UI_FIELDS.map((key) => ui[key]) -} - -/** Publish workspace-option changes promptly without re-reading on every UI drag frame. */ -export function publishWorkspaceViewChanges( - store: Pick | null, - emit: (event: RuntimeClientEvent) => void -): void { - if (!store?.getUI || !store.onUIChanged) { - return - } - let previous = workspaceViewUiValues(store.getUI()) - store.onUIChanged((ui) => { - const next = workspaceViewUiValues(ui) - if (!isDeepStrictEqual(previous, next)) { - previous = next - emit({ type: 'workspaceViewChanged' }) - } - }) - store.onSettingsChanged?.((updates) => { - if (WORKSPACE_VIEW_SETTINGS.some((key) => key in updates)) { - emit({ type: 'workspaceViewChanged' }) - } - }) -} diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-announcements.test.ts b/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-announcements.test.ts deleted file mode 100644 index 05287e24028..00000000000 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-announcements.test.ts +++ /dev/null @@ -1,213 +0,0 @@ -// Exercise every domain's real store writers and announcements (design §9.4); phone reads must not re-read domains. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' -import type { Repo } from '../../../shared/repo-types' -import type { PRInfo } from '../../../shared/github/pull-request-types' -import type { WslHostService } from '../../wsl/host-lifecycle/wsl-host-service' -import { setWslHostService } from '../../wsl/host-lifecycle/wsl-host-service-instance' -import { getGitHubPRCacheKeyCandidates } from '../../../shared/github/github-cache-key' -import { toRuntimeExecutionHostId } from '../../../shared/execution-host' -import { - getWorktreeHostIdentity, - hostWorktreeTarget -} from '../../../shared/worktree/host-qualified-identity' -import { - prGroupOfReviewFact, - WorkspaceReviewFactsSnapshotSchema, - type WorkspaceReviewFact -} from '../../../shared/sidebar-list/workspace-review-facts' -import { fixture } from '../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture' -import { ProducerRevision } from './producer-revision' -import { SidebarInputsFeed } from './sidebar-inputs-feed' -import { - sidebarInputsFeedDomains, - type SidebarInputsFeedSources -} from './sidebar-inputs-feed-domains' -import { TestPhone } from './sidebar-inputs-feed.test-fixture' - -const repo: Repo = { id: 'repo-1', path: '/r', displayName: 'r', badgeColor: 'blue', addedAt: 1 } -const worktree = { - id: 'repo-1::/r/a', - repoId: repo.id, - hostId: 'local', - branch: 'refs/heads/feature', - linkedPR: null -} as const - -async function host() { - const { store } = await fixture() - store.addRepo(repo) - const clientEvents = new Set<(event: RuntimeClientEvent) => void>() - const temporal = new Set<() => void>() - const wslListeners = new Set<() => void>() - const revisions = { - activity: new ProducerRevision(), - paired: new ProducerRevision(), - creations: new ProducerRevision(), - rows: new ProducerRevision(), - detected: new ProducerRevision(), - liveContent: new ProducerRevision() - } - // A WSL registry that only announces; this host has no WSL hosts. - const wsl = { - getStatuses: () => [], - onStatusesChanged: (listener: () => void) => { - wslListeners.add(listener) - return () => wslListeners.delete(listener) - } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the desktop domain reads only these two members. - setWslHostService(wsl as unknown as WslHostService) - const sources: SidebarInputsFeedSources = { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the domains read only the members stubbed here. - facts: { - workspaceActivityFacts: { revision: revisions.activity }, - getWorkspaceActivityFacts: () => ({ revision: 0, facts: {} }), - getSidebarTemporalSnapshot: () => ({ sessionId: null, retention: null }), - onSidebarTemporalChange: (listener: () => void) => { - temporal.add(listener) - return () => temporal.delete(listener) - }, - detectedCheckouts: { - revision: revisions.detected, - snapshot: () => ({}), - watch: (listener: () => void) => revisions.detected.onChange(listener) - }, - workspaceLiveContent: { revision: revisions.liveContent, snapshot: () => ({}) } - } as unknown as SidebarInputsFeedSources['facts'], - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. - pairedServerRows: { - revision: revisions.paired, - snapshot: () => ({ servers: [] }), - catalogs: () => [] - } as unknown as SidebarInputsFeedSources['pairedServerRows'], - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. - workspaceLifecycle: { - revision: revisions.creations, - creationsSnapshot: () => ({ creations: {} }), - hints: () => ({}) - } as unknown as SidebarInputsFeedSources['workspaceLifecycle'], - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above; one cached worktree, already scanned. - workspaceRows: { - revision: revisions.rows, - snapshot: () => ({ revision: 0, rows: {} }), - resolvedWorktrees: () => [worktree], - ready: async () => {} - } as unknown as SidebarInputsFeedSources['workspaceRows'], - repoIcons: { idsByRepo: () => ({}) }, - store: () => store, - onClientEvent: (listener) => { - clientEvents.add(listener) - return () => clientEvents.delete(listener) - } - } - const emit = (event: RuntimeClientEvent): void => - clientEvents.forEach((listener) => listener(event)) - const catalogEvent = (): void => emit({ type: 'reposChanged' }) - // Every public writer of what each domain reads. - const writers: Record void>> = { - activity: { - 'activity producer': () => revisions.activity.bump(), - 'paired server rows': () => revisions.paired.bump(), - // Only a paired server's partition holds activity (its browser and chat tabs). - 'saved session': () => - store.patchWorkspaceSession({ activeTabId: 'tab-1' }, toRuntimeExecutionHostId('env-1')) - }, - temporal: { 'retention owner': () => temporal.forEach((listener) => listener()) }, - creations: { 'lifecycle queue': () => revisions.creations.bump() }, - inProgress: { 'lifecycle queue': () => revisions.creations.bump() }, - workspaces: { 'workspace rows producer': () => revisions.rows.bump() }, - detected: { 'detected checkouts producer': () => revisions.detected.bump() }, - liveContent: { 'live content producer': () => revisions.liveContent.bump() }, - view: { 'ui write': () => store.updateUI({ groupBy: 'pr-status' }) }, - pairedServerHosts: { 'paired server rows': () => revisions.paired.bump() }, - pairedServerRows: { 'paired server rows': () => revisions.paired.bump() }, - desktop: { - 'catalog event': catalogEvent, - 'ui write': () => store.updateUI({ workspaceHostOrder: ['local'] }), - 'settings write': () => - store.updateSettings({ - showPinnedWorktreesInGroups: !store.getSettings().showPinnedWorktreesInGroups - }), - 'saved session': () => store.patchWorkspaceSession({ activeWorktreeId: worktree.id }), - 'pin write': () => - store.setWorktreeMeta(hostWorktreeTarget({ id: worktree.id, hostId: 'local' }), { - isPinned: true - }), - 'WSL status': () => wslListeners.forEach((listener) => listener()) - }, - projectCatalog: { - 'catalog event': catalogEvent, - 'paired server rows': () => revisions.paired.bump(), - 'ui write': () => store.updateUI({ projectOrderBy: 'recent' }), - 'full save': () => - store.setWorktreeLineage(hostWorktreeTarget({ id: worktree.id, hostId: 'local' }), { - worktreeId: worktree.id, - worktreeInstanceId: 'a-1', - parentWorktreeId: 'repo-1::/r/p', - parentWorktreeInstanceId: 'p-1', - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 1 - }) - }, - repoIcons: { 'catalog event': catalogEvent }, - review: { - 'PR cache save': () => store.setGitHubCache({ ...store.getGitHubCache(), pr: {} }), - 'workspace rows producer': () => revisions.rows.bump(), - 'paired server rows': () => revisions.paired.bump(), - 'catalog event': catalogEvent - } - } - return { store, sources, writers } -} - -function feedReviewFact(value: unknown): WorkspaceReviewFact | null { - const parsed = WorkspaceReviewFactsSnapshotSchema.shape.facts.valueType.safeParse(value) - return parsed.success ? parsed.data : null -} - -beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) - -afterEach(() => { - setWslHostService(null) - vi.restoreAllMocks() -}) - -describe('sidebar inputs feed announcements', () => { - it('follows a PR cache save on a quiet desktop into the phone’s PR grouping', async () => { - const { store, sources } = await host() - const events: { generation: string; revision: number }[] = [] - const feed = new SidebarInputsFeed( - () => sidebarInputsFeedDomains(sources), - (event) => events.push(event) - ) - store.updateUI({ groupBy: 'pr-status' }) - const phone = new TestPhone(feed, 'conn-1') - phone.refresh() - await phone.settle() - expect(phone.view().review).toBeUndefined() - - // Nothing else happens on this desktop: no catalog event, no phone read, no metadata write. - const before = events.length - const [key] = getGitHubPRCacheKeyCandidates(repo, 'feature') - store.setGitHubCache({ - ...store.getGitHubCache(), - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: grouping reads only number and state. - pr: { [key]: { data: { number: 7, state: 'merged' } as PRInfo, fetchedAt: 1 } } - }) - await vi.waitFor(() => expect(events.length).toBeGreaterThan(before)) - const notice = events.at(-1) - if (!notice) { - throw new Error('the PR cache save announced nothing') - } - phone.notice(notice) - await phone.settle() - const fact = phone.view().review?.[getWorktreeHostIdentity(worktree)] - expect(fact).toEqual({ provider: 'github', reviewState: 'merged' }) - expect(prGroupOfReviewFact(feedReviewFact(fact))).toBe('done') - phone.disconnect() - }) -}) diff --git a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-domains.ts b/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-domains.ts index ff0304fd5fa..a9a145b663a 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-domains.ts +++ b/src/main/runtime/sidebar-inputs/sidebar-inputs-feed-domains.ts @@ -12,15 +12,15 @@ import { } from '../../persistence/profile-save-domains' import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' import type { OrcaRuntimeWithSidebarTemporal } from './orca-runtime-sidebar-temporal' -import type { PairedServerRowsProducer } from './paired-server-rows-producer' +import type { PairedServerRowsProducer } from './workspace-rows/paired-server-rows-producer' import type { WorkspaceLifecycleQueue } from '../workspaces/lifecycle/workspace-lifecycle-queue' -import type { WorkspaceRowsProducer } from './workspace-rows-producer' -import type { RepoIconDataUrls } from './repo-icon-data-urls' -import type { SidebarInputsFeedDomain } from './sidebar-inputs-feed' -import { readDesktopSidebarFacts } from './desktop-sidebar-facts' +import type { WorkspaceRowsProducer } from './workspace-rows/workspace-rows-producer' +import type { RepoIconDataUrls } from './repo-icons/repo-icon-data-urls' +import type { SidebarInputsFeedDomain } from './feed/sidebar-inputs-feed' +import { readDesktopSidebarFacts } from './catalog/desktop-sidebar-facts' import { readStoreInstallationId } from '../hosts/platform-probe/host-descriptor' import { getCanonicalUserDataPath } from '../../persistence/loading-store/user-data-path' -import { readSidebarProjectCatalog } from './sidebar-project-catalog' +import { readSidebarProjectCatalog } from './catalog/sidebar-project-catalog' import { buildPairedServerReviewFacts, buildWorkspaceReviewFacts diff --git a/src/main/runtime/sidebar-inputs/sidebar-project-catalog.ts b/src/main/runtime/sidebar-inputs/sidebar-project-catalog.ts deleted file mode 100644 index 75f69e9de39..00000000000 --- a/src/main/runtime/sidebar-inputs/sidebar-project-catalog.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { MobileProjectSectionCatalog } from '../../../shared/mobile-project-sections-contract' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import { - buildSidebarProjectCatalog, - type PairedServerCatalog -} from '../../../shared/sidebar-list/sidebar-project-catalog' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import { - runtimeVisibleProjectGroups, - runtimeVisibleProjectHostSetups, - runtimeVisibleRepos -} from '../workspaces/catalog/runtime-visible-catalog' - -export type SidebarProjectCatalogStore = Pick< - RuntimeStore, - 'getRepos' | 'getProjectGroups' | 'getFolderWorkspaces' | 'getSshTargets' | 'getProjectHostSetups' -> & - Partial> & { - getUI?: () => Pick - } - -/** This host's store as clients may list it, with its paired servers' catalogs. */ -export function readSidebarProjectCatalog( - store: SidebarProjectCatalogStore, - servers: readonly PairedServerCatalog[] -): MobileProjectSectionCatalog { - return buildSidebarProjectCatalog( - { - repos: runtimeVisibleRepos(store), - projectGroups: runtimeVisibleProjectGroups(store), - projects: store.getProjects?.() ?? [], - setups: runtimeVisibleProjectHostSetups(store) - }, - servers, - store.getUI?.() - ) -} diff --git a/src/main/runtime/sidebar-inputs/sort-stamp-records-twins.test.ts b/src/main/runtime/sidebar-inputs/sort-stamp-records-twins.test.ts deleted file mode 100644 index bc58ceffa3e..00000000000 --- a/src/main/runtime/sidebar-inputs/sort-stamp-records-twins.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { Repo } from '../../../shared/repo-types' -import { - hostWorktreeTarget, - type HostWorktreeTarget -} from '../../../shared/worktree/host-qualified-identity' -import { readSortStamps, writeSortStamps, writeUnreadFlag } from './sort-stamp-records' - -const WT = 'dup::/wt' -type Row = { lastActivityAt: number; isUnread?: boolean; hostId?: ExecutionHostId } - -function repo(overrides: Partial): Repo { - return { - id: 'dup', - path: '/wt', - displayName: 'dup', - badgeColor: '#000', - addedAt: 1, - ...overrides - } -} - -// Mirrors the persistence store: the raw-id row belongs to whichever twin wrote first. -function twinStore(repos: Repo[]) { - const byHost = new Map() - let rawOwner: ExecutionHostId | undefined - return { - byHost, - getRepos: () => repos, - getWorktreeMeta: (id: string) => (id === WT && rawOwner ? byHost.get(rawOwner) : undefined), - getWorktreeMetaForHost: (id: string, hostId: ExecutionHostId) => - id === WT ? byHost.get(hostId) : undefined, - setWorktreeMeta: (target: HostWorktreeTarget, updates: Partial) => { - rawOwner ??= target.hostId - byHost.set(target.hostId, { - ...(byHost.get(target.hostId) ?? { lastActivityAt: 0 }), - ...updates, - hostId: target.hostId - }) - } - } -} - -describe('sort stamps and unread for a local pane of a same-id twin', () => { - it('reads and writes the local copy, not the twin that wrote first', () => { - const store = twinStore([repo({}), repo({ connectionId: 'box' })]) - store.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'ssh:box' }), { - lastActivityAt: 5 - }) - store.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'local' }), { - lastActivityAt: 1 - }) - const localPane = { worktreeId: WT, sshHostId: null } - - expect(readSortStamps(store, localPane)?.recentAt).toBe(1) - writeSortStamps(store, localPane, { recentAt: 9 }) - expect(writeUnreadFlag(store, localPane, true)).toBe(true) - - expect(store.byHost.get('local')).toMatchObject({ lastActivityAt: 9, isUnread: true }) - expect(store.byHost.get('ssh:box')).toMatchObject({ lastActivityAt: 5 }) - expect(store.byHost.get('ssh:box')?.isUnread).toBeUndefined() - }) - - it('keeps the stamped row when the repo lives on one host', () => { - const store = twinStore([repo({ connectionId: 'box' })]) - store.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'ssh:box' }), { - lastActivityAt: 5 - }) - - writeSortStamps(store, { worktreeId: WT, sshHostId: null }, { recentAt: 9 }) - - expect(store.byHost.get('ssh:box')?.lastActivityAt).toBe(9) - expect(store.byHost.has('local')).toBe(false) - }) -}) diff --git a/src/main/runtime/sidebar-inputs/sort-stamp-records.ts b/src/main/runtime/sidebar-inputs/sort-stamp-records.ts deleted file mode 100644 index b3df494b5f8..00000000000 --- a/src/main/runtime/sidebar-inputs/sort-stamp-records.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { getRepoRegistrationHostIds } from '../../../shared/repo-host-identity' -import type { AgentPaneWorkspace } from '../../agent-hooks/observations/agent-transition-detector' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import type { - SmartStampFields, - SmartTier, - SortStamps -} from '../../../shared/sidebar-list/sort-stamps' -import { folderWorkspaceKey, parseWorkspaceKey } from '../../../shared/workspace-scope' -import type { Repo } from '../../../shared/repo-types' -import { - hostWorktreeTarget, - type HostWorktreeTarget -} from '../../../shared/worktree/host-qualified-identity' -import { resolveWorktreeMetaOwner } from '../../persistence/host-qualified-worktree-meta' - -type StampedRecord = { - lastActivityAt: number - isUnread?: boolean - hostId?: ExecutionHostId -} & SmartStampFields -type StampUpdates = { - lastActivityAt: number - smartTier: SmartTier | undefined - smartAt: number | undefined -} - -/** The per-workspace record reads and writes, which the runtime's store satisfies. */ -export type WorkspaceRecordStore = { - getWorktreeMeta: (worktreeId: string) => (TRecord & { hostId?: ExecutionHostId }) | undefined - setWorktreeMeta: (target: HostWorktreeTarget, updates: TUpdates) => unknown - getRepos: () => readonly Repo[] - getWorktreeMetaForHost?: (worktreeId: string, hostId: ExecutionHostId) => TRecord | undefined - getFolderWorkspace?: (folderWorkspaceId: string) => TRecord | undefined - updateFolderWorkspace?: (folderWorkspaceId: string, updates: TUpdates) => unknown -} - -type UnreadUpdate = { isUnread: boolean } - -/** The record reads and writes stamping and the unread flag need. */ -export type SortStampsStore = WorkspaceRecordStore & { - getAllWorktreeMeta?: () => Record - getFolderWorkspaces?: () => readonly (StampedRecord & { id: string })[] -} - -/** The workspace's own record: folder, SSH host, or local. */ -export function readWorkspaceRecord( - store: WorkspaceRecordStore | null, - { worktreeId, sshHostId }: AgentPaneWorkspace -): TRecord | undefined { - const scope = parseWorkspaceKey(worktreeId) - if (scope?.type === 'folder') { - return store?.getFolderWorkspace?.(scope.folderWorkspaceId) - } - const hostId = sshHostId ?? (store && localTwinHostId(store, worktreeId)) - return hostId - ? store?.getWorktreeMetaForHost?.(worktreeId, hostId) - : store?.getWorktreeMeta(worktreeId) -} - -/** Unhosted panes are local; with same-id twins, raw-id rows may belong elsewhere, so address the local copy explicitly. */ -function localTwinHostId( - store: Pick, 'getRepos'>, - worktreeId: string -): ExecutionHostId | null { - const hosts = getRepoRegistrationHostIds(store.getRepos(), getRepoIdFromWorktreeId(worktreeId)) - return hosts.size > 1 && hosts.has(LOCAL_EXECUTION_HOST_ID) ? LOCAL_EXECUTION_HOST_ID : null -} - -export function writeWorkspaceRecord( - store: WorkspaceRecordStore | null, - { worktreeId, sshHostId }: AgentPaneWorkspace, - updates: TUpdates -): void { - const scope = parseWorkspaceKey(worktreeId) - if (scope?.type === 'folder') { - store?.updateFolderWorkspace?.(scope.folderWorkspaceId, updates) - return - } - // No SSH host and no twin: the row the read above found, by its own stamp. - const hostId = sshHostId ?? (store && localTwinHostId(store, worktreeId)) - const target = hostId - ? hostWorktreeTarget({ id: worktreeId, hostId }) - : store && resolveWorktreeMetaOwner(store, worktreeId) - if (target) { - store?.setWorktreeMeta(target, updates) - } -} - -/** Sets the workspace's unread flag; true when its record held the other value. */ -export function writeUnreadFlag( - store: SortStampsStore | null, - workspace: AgentPaneWorkspace, - isUnread: boolean -): boolean { - const record = readWorkspaceRecord(store, workspace) - // Only a workspace with a record is written; writing would create one for a stale id. - if (!record || Boolean(record.isUnread) === isUnread) { - return false - } - writeWorkspaceRecord(store, workspace, { isUnread }) - return true -} - -// Only a workspace with a record is stamped; writing would create one for a stale id. -export function readSortStamps( - store: SortStampsStore | null, - workspace: AgentPaneWorkspace -): SortStamps | null { - const record = readWorkspaceRecord(store, workspace) - if (!record) { - return null - } - return { - recentAt: record.lastActivityAt, - ...(record.smartTier !== undefined - ? { smartTier: record.smartTier, smartAt: record.smartAt } - : {}) - } -} - -export function writeSortStamps( - store: SortStampsStore | null, - workspace: AgentPaneWorkspace, - stamps: SortStamps -): void { - // Both tier keys are always written, so Rest clears them. - writeWorkspaceRecord(store, workspace, { - lastActivityAt: stamps.recentAt, - smartTier: stamps.smartTier, - smartAt: stamps.smartAt - }) -} - -/** Every workspace whose record holds a tier. */ -export function listTieredWorkspaces(store: SortStampsStore | null): string[] { - const ids: string[] = [] - for (const [worktreeId, meta] of Object.entries(store?.getAllWorktreeMeta?.() ?? {})) { - if (meta.smartTier !== undefined) { - ids.push(worktreeId) - } - } - for (const folder of store?.getFolderWorkspaces?.() ?? []) { - if (folder.smartTier !== undefined) { - ids.push(folderWorkspaceKey(folder.id)) - } - } - return ids -} diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-closed-tab-retention.test.ts b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-closed-tab-retention.test.ts similarity index 90% rename from src/main/runtime/sidebar-inputs/orca-runtime-closed-tab-retention.test.ts rename to src/main/runtime/sidebar-inputs/temporal/orca-runtime-closed-tab-retention.test.ts index 2aa077a1cc8..3c8d6281719 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-closed-tab-retention.test.ts +++ b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-closed-tab-retention.test.ts @@ -1,12 +1,12 @@ // Runs on plain Node, as orcad does: main's "Hide sleeping" retention reads the runtime's own facts. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import type { ResolvedWorktreeSnapshot } from '../workspaces/catalog/runtime-resolved-worktree-cache' -import type { ResolvedWorktree } from '../workspaces/catalog/runtime-worktree-path-identity' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' +import type { ResolvedWorktreeSnapshot } from '../../workspaces/catalog/runtime-resolved-worktree-cache' +import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) const repo = { id: 'repo-1', path: '/r', displayName: 'r', badgeColor: 'blue', addedAt: 1 } const WT = 'repo-1::/r/a' diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-sort-stamps.test.ts similarity index 87% rename from src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts rename to src/main/runtime/sidebar-inputs/temporal/orca-runtime-sort-stamps.test.ts index d98754c6e70..cfa81181c6e 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts +++ b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-sort-stamps.test.ts @@ -1,22 +1,22 @@ // Runs on plain Node, as orcad does: a paired server stamps its own rows through this same wiring. import { describe, expect, it, vi } from 'vitest' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { OrcaRuntimeService } from '../orca-runtime' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' +import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' +import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { OrcaRuntimeService } from '../../orca-runtime' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { hostWorktreeTarget, type HostWorktreeTarget -} from '../../../shared/worktree/host-qualified-identity' +} from '../../../../shared/worktree/host-qualified-identity' import { partialRuntimeStore, storeRepo, storeWorktreeMeta -} from '../orca-runtime-tests/runtime-store-partial-fixture' +} from '../../orca-runtime-tests/runtime-store-partial-fixture' -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) const WT = 'repo-1::/tmp/worktree-a' const FOLDER_ID = 'fw-1' diff --git a/src/main/runtime/sidebar-inputs/temporal/orca-runtime-terminal-use.test.ts b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-terminal-use.test.ts new file mode 100644 index 00000000000..96077a93e50 --- /dev/null +++ b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-terminal-use.test.ts @@ -0,0 +1,82 @@ +// Runs on plain Node, as orcad does: the host that owns a workspace records its terminal use. +import { describe, expect, it, vi } from 'vitest' +import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' +import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' +import { + WORKSPACE_CLEANUP_IDLE_MS, + getPersistedWorkspaceCleanupActivityAt, + isWorkspaceOldForCleanup +} from '../../../../shared/workspace-cleanup/workspace-cleanup' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import { + partialRuntimeStore, + storeRepo, + storeWorktreeMeta, + type PartialRuntimeStore +} from '../../orca-runtime-tests/runtime-store-partial-fixture' + +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) + +const WT = 'repo-1::/tmp/phone-only' +const DAY_MS = 24 * 60 * 60 * 1000 + +function createHeadlessRuntime(ptyId = 'pty-1') { + // Untouched for 45 days: no agent ran, so no Recent stamp moved. + const meta: Record = { [WT]: storeWorktreeMeta({ lastActivityAt: 1 }) } + const repo = storeRepo({ id: 'repo-1', path: '/tmp/repo-1', connectionId: null }) + const store: PartialRuntimeStore = { + // An unstamped row's writes resolve their host from its repo's only registration. + getRepos: () => [repo], + getRepo: (id: string) => (id === repo.id ? repo : undefined), + getSettings: () => ({}), + getWorktreeMeta: (id: string) => meta[id], + getAllWorktreeMeta: () => meta, + setWorktreeMeta: ({ id }: HostWorktreeTarget, updates: Partial) => { + meta[id] = { ...meta[id], ...updates } + return meta[id] + } + } + const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) + // No desktop window: the phone is the only client. + runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { + tabs: [{ tabId: 'tab-1', worktreeId: WT, title: 'zsh', activeLeafId: 'pane:1', layout: null }], + leaves: [ + { + tabId: 'tab-1', + worktreeId: WT, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId, + paneTitle: null + } + ] + }) + return { runtime, meta } +} + +describe('host-written terminal use', () => { + it('a phone-only workspace whose terminals are closed is not idle to cleanup', () => { + const now = 45 * DAY_MS + vi.useFakeTimers({ now }) + try { + const { runtime, meta } = createHeadlessRuntime() + // Typing in a plain shell from the phone goes through the host's one input funnel. + runtime.terminalRunFacts.recordInput('pty-1', 'driving', 'ls\r', now - 2 * DAY_MS) + runtime.onPtyExit('pty-1', 0) + expect(meta[WT]?.lastTerminalUseAt).toBe(now - 2 * DAY_MS) + const workspace = { isArchived: false, lastActivityAt: meta[WT]?.lastActivityAt ?? 0 } + expect(isWorkspaceOldForCleanup(workspace, now)).toBe(true) + const lastActive = getPersistedWorkspaceCleanupActivityAt({ + lastActivityAt: workspace.lastActivityAt, + lastTerminalUseAt: meta[WT]?.lastTerminalUseAt + }) + expect(isWorkspaceOldForCleanup({ ...workspace, lastActivityAt: lastActive }, now)).toBe( + false + ) + expect(now - lastActive).toBeLessThan(WORKSPACE_CLEANUP_IDLE_MS) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-windowless-terminal-activity.ts similarity index 76% rename from src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts rename to src/main/runtime/sidebar-inputs/temporal/orca-runtime-windowless-terminal-activity.ts index c3da1236aa6..521c4e85757 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts +++ b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-windowless-terminal-activity.ts @@ -1,23 +1,26 @@ -import { OrcaRuntimeWithWslMoveTerminalFacts } from '../workspaces/metadata/runtime-wsl-move-terminal-facts' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' -import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../shared/sidebar-inputs-switch' -import { isRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' -import type { RuntimeTerminalSplit } from '../../../shared/runtime-terminal-contracts' -import { parseExecutionHostId } from '../../../shared/execution-host' -import { isRestoreSpawnIntent } from '../../../shared/terminal/pty/admission/spawn-admission-contract' -import { parseWorkspaceKey } from '../../../shared/workspace-scope' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { readWorkspaceRecord, writeWorkspaceRecord } from './sort-stamp-records' -import { createKeyedTrailingEdgeCoalescer } from '../client/events/keyed-trailing-edge-coalescer' +import { OrcaRuntimeWithWslMoveTerminalFacts } from '../../workspaces/metadata/runtime-wsl-move-terminal-facts' +import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' +import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../../shared/sidebar-inputs-switch' +import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' +import type { RuntimeTerminalSplit } from '../../../../shared/runtime-terminal-contracts' +import { parseExecutionHostId } from '../../../../shared/execution-host' +import { isRestoreSpawnIntent } from '../../../../shared/terminal/pty/admission/spawn-admission-contract' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import { + readWorkspaceRecord, + writeWorkspaceRecord +} from '../../workspaces/metadata/workspace-activity-records' +import { createKeyedTrailingEdgeCoalescer } from '../../client/events/keyed-trailing-edge-coalescer' import { agentPaneWorkspace, type AgentPaneWorkspace -} from '../../agent-hooks/observations/agent-transition-detector' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' +} from '../../../agent-hooks/observations/agent-transition-detector' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' import { isWslMoveProjectBlocked, wslMoveProjectRefForWorkspace -} from '../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' +} from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' type Runtime = OrcaRuntimeWithWslMoveTerminalFacts diff --git a/src/main/runtime/sidebar-inputs/temporal/orca-runtime-workspace-unread.test.ts b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-workspace-unread.test.ts new file mode 100644 index 00000000000..a4fe58ddac1 --- /dev/null +++ b/src/main/runtime/sidebar-inputs/temporal/orca-runtime-workspace-unread.test.ts @@ -0,0 +1,223 @@ +// Runs on plain Node, as orcad does: a host with no window raises and clears its own unread flags. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { OrcaRuntimeService } from '../../orca-runtime' +import { RpcDispatcher } from '../../rpc/dispatcher' +import type { RpcDispatchStreamingOptions } from '../../rpc/dispatch/dispatcher-stream-options' +import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs' +import { SIDEBAR_INPUT_METHODS } from '../../rpc/methods/sidebar-inputs/sidebar-inputs' +import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import { + partialRuntimeStore, + storeFolderWorkspace, + storeProjectGroup, + storeRepo, + storeWorktreeMeta, + type PartialRuntimeStore +} from '../../orca-runtime-tests/runtime-store-partial-fixture' +import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' + +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) + +const WT = 'repo-1::/tmp/worktree-a' +const SSH_WT = 'repo-ssh::/home/me/worktree-b' +const HUB_WT = 'repo-hub::/srv/worktree-c' +const FOLDER_ID = '11111111-1111-4111-8111-111111111111' +const FOLDER = folderWorkspaceKey(FOLDER_ID) +const LEAF = '22222222-2222-4222-8222-222222222222' +const PANE = `tab-1:${LEAF}` +const PHONE: RpcDispatchStreamingOptions = { clientKind: 'mobile', connectionId: 'phone-1' } + +function createHeadlessHost() { + const meta: Record = { [WT]: storeWorktreeMeta() } + const sshMeta: Record = { [SSH_WT]: storeWorktreeMeta() } + // A same-id project this host registered under a server's id and locally. + const hubMeta: Record = { [HUB_WT]: storeWorktreeMeta() } + meta[HUB_WT] = storeWorktreeMeta() + const folders: Record = { + [FOLDER_ID]: storeFolderWorkspace({ + id: FOLDER_ID, + projectGroupId: 'group-1', + folderPath: '/tmp/folder' + }) + } + const repos = [ + storeRepo({ id: 'repo-1', path: '/tmp/repo-1', connectionId: null }), + storeRepo({ id: 'repo-ssh', path: '/home/user/repo-ssh', connectionId: 'build-box' }), + storeRepo({ + id: 'repo-hub', + path: '/srv/repo-hub', + connectionId: null, + executionHostId: 'runtime:hub' + }), + storeRepo({ id: 'repo-hub', path: '/tmp/repo-hub', connectionId: null }) + ] + const store: PartialRuntimeStore = { + getRepos: () => repos, + getRepo: (id: string) => repos.find((repo) => repo.id === id), + getProjectGroups: () => [storeProjectGroup({ id: 'group-1', connectionId: null })], + getSettings: () => ({}), + getWorktreeMeta: (id: string) => meta[id], + getAllWorktreeMeta: () => meta, + setWorktreeMeta: ({ id, hostId }: HostWorktreeTarget, updates: Partial) => + Object.assign( + hostId === 'ssh:build-box' + ? sshMeta[id] + : hostId === 'runtime:hub' + ? hubMeta[id] + : meta[id], + updates + ), + getWorktreeMetaForHost: (id: string, hostId: string) => + hostId === 'ssh:build-box' ? sshMeta[id] : hostId === 'runtime:hub' ? hubMeta[id] : meta[id], + getFolderWorkspace: (id: string) => folders[id], + updateFolderWorkspace: (id: string, updates: Partial) => + Object.assign(folders[id], updates) + } + const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) + runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { + tabs: [{ tabId: 'tab-1', worktreeId: WT, title: 'Agent', activeLeafId: LEAF, layout: null }], + leaves: [ + { + tabId: 'tab-1', + worktreeId: WT, + leafId: LEAF, + paneRuntimeId: 1, + ptyId: 'pty-1', + paneTitle: null + } + ] + }) + const server = new AgentHookServer() + runtime.attachAgentStatusStore(server) + const dispatcher = new RpcDispatcher({ + runtime, + methods: [...SIDEBAR_INPUT_METHODS, ...SESSION_TAB_METHODS] + }) + let requestId = 0 + const finishTurn = (worktreeId = WT, connectionId?: string): void => { + for (const state of ['working', 'done'] as const) { + server.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId, + ...(connectionId ? { connectionId } : {}), + payload: { state, prompt: 'task', agentType: 'claude' } + }) + } + } + return { + runtime, + meta, + sshMeta, + hubMeta, + folders, + finishTurn, + // The phone's session screen holds this stream while the workspace is open on it. + openOnPhone: (worktreeId: string) => + dispatcher.dispatchStreaming( + { + id: `sub-${++requestId}`, + authToken: 'tok', + method: 'session.tabs.subscribe', + params: { worktree: `id:${worktreeId}` } + }, + () => {}, + PHONE + ), + reportView: (params: unknown, connectionId: string | undefined) => + dispatcher.dispatch( + { id: `view-${++requestId}`, authToken: 'tok', method: 'sidebarInputs.reportView', params }, + { clientKind: 'runtime', connectionId } + ) + } +} + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('workspace unread flag on a headless host', () => { + it('flags a finish no one sees, clears it when the phone opens it, and spares it while open', async () => { + const host = createHeadlessHost() + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(true) + + await host.openOnPhone(WT) + expect(host.meta[WT].isUnread).toBe(false) + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(false) + + // Leaving the session (its stream closes with the connection) makes the next finish news. + host.runtime.cleanupSubscriptionsForConnection('phone-1') + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(true) + }) + + it('clears a folder workspace and an SSH worktree on their own records when the phone opens them', async () => { + const host = createHeadlessHost() + host.folders[FOLDER_ID].isUnread = true + host.sshMeta[SSH_WT].isUnread = true + await host.openOnPhone(FOLDER) + expect(host.folders[FOLDER_ID].isUnread).toBe(false) + await host.openOnPhone(SSH_WT) + expect(host.sshMeta[SSH_WT].isUnread).toBe(false) + + // The SSH finish raises the SSH host's record once the phone has left. + host.runtime.cleanupSubscriptionsForConnection('phone-1') + host.finishTurn(SSH_WT, 'build-box') + expect(host.sshMeta[SSH_WT].isUnread).toBe(true) + }) + + // The phone names only an id, so it cannot say which of two same-id copies it shows. + it('clears neither copy of a workspace two hosts register', async () => { + const host = createHeadlessHost() + host.hubMeta[HUB_WT].isUnread = true + host.meta[HUB_WT].isUnread = true + await host.openOnPhone(HUB_WT) + expect(host.hubMeta[HUB_WT].isUnread).toBe(true) + expect(host.meta[HUB_WT].isUnread).toBe(true) + }) + + it('spares the tab a client window shows while its user is present', async () => { + vi.useFakeTimers({ now: 10_000, toFake: ['Date'] }) + try { + const host = createHeadlessHost() + const view = { workspaceIds: [WT], tabIds: ['tab-1'], presentForMs: 60_000 } + expect(await host.reportView(view, 'desktop-1')).toMatchObject({ ok: true }) + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(false) + + // Another tab on screen is not this pane's. + await host.reportView({ ...view, tabIds: ['tab-2'] }, 'desktop-1') + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(true) + + host.meta[WT].isUnread = false + await host.reportView(view, 'desktop-1') + vi.setSystemTime(10_000 + 60_000) + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(true) + + // A client that disconnects stops counting; one with no connection cannot report. + expect(await host.reportView(view, undefined)).toMatchObject({ ok: false }) + host.meta[WT].isUnread = false + await host.reportView({ ...view, presentForMs: null }, 'desktop-1') + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(false) + host.runtime.cleanupSubscriptionsForConnection('desktop-1') + host.finishTurn() + expect(host.meta[WT].isUnread).toBe(true) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/runtime/sidebar-inputs/sidebar-retention-owner.test.ts b/src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.test.ts similarity index 92% rename from src/main/runtime/sidebar-inputs/sidebar-retention-owner.test.ts rename to src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.test.ts index 6947e928472..02b08b4604b 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-retention-owner.test.ts +++ b/src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../shared/worktree/types' -import { getWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' -import { SidebarClock } from './sidebar-clock' +import type { Worktree } from '../../../../shared/worktree/types' +import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' +import { SidebarClock } from '../sidebar-clock' import { SidebarRetentionOwner } from './sidebar-retention-owner' function worktree(id: string, overrides: Partial = {}): Worktree { diff --git a/src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts b/src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.ts similarity index 94% rename from src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts rename to src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.ts index 61944831894..81ff76d2026 100644 --- a/src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts +++ b/src/main/runtime/sidebar-inputs/temporal/sidebar-retention-owner.ts @@ -1,17 +1,17 @@ -import { ProducerRevision } from './producer-revision' +import { ProducerRevision } from '../producer-revision' import { getWorktreeIdFromHostIdentity, type HostScopedWorktreeKey -} from '../../../shared/worktree/host-qualified-identity' +} from '../../../../shared/worktree/host-qualified-identity' import { createSleepingSweepRetentionState, updateSleepingSweepRetention -} from '../../../shared/sidebar-list/sleeping-sweep-retention' +} from '../../../../shared/sidebar-list/sleeping-sweep-retention' import type { SidebarRetention, SidebarTemporalSnapshot -} from '../../../shared/sidebar-list/sidebar-temporal-snapshot' -import type { SidebarClock } from './sidebar-clock' +} from '../../../../shared/sidebar-list/sidebar-temporal-snapshot' +import type { SidebarClock } from '../sidebar-clock' /** This host's activity by bare id, read for each listed row: its session names no host. */ export type SidebarRetentionCandidates = { diff --git a/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts b/src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.test.ts similarity index 91% rename from src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts rename to src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.test.ts index d6d91090e99..90449414a14 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.test.ts @@ -1,23 +1,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import type { AgentStatusStoreView } from './workspace-activity-facts-producer' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import type { AgentStatusStoreView } from '../workspace-facts/workspace-activity-facts-producer' -import '../../../shared/agent-status/contracts/agent-status-subject' -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' -import type { TerminalSideEffectFact } from '../../../shared/terminal/output/terminal-side-effect-facts' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { Repo } from '../../../shared/repo-types' -import '../../../shared/sidebar-list/sort-stamps' -import type { SmartStampFields } from '../../../shared/sidebar-list/sort-stamps' -import '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' -import type { AgentTransitionStep } from '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' -import { AgentTransitionDetector } from '../../agent-hooks/observations/agent-transition-detector' -import '../../../shared/sidebar-list/stamp-order' +import '../../../../shared/agent-status/contracts/agent-status-subject' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import type { TerminalSideEffectFact } from '../../../../shared/terminal/output/terminal-side-effect-facts' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { Repo } from '../../../../shared/repo-types' +import '../../../../shared/sidebar-list/sort-stamps' +import type { SmartStampFields } from '../../../../shared/sidebar-list/sort-stamps' +import '../../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' +import type { AgentTransitionStep } from '../../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' +import { AgentTransitionDetector } from '../../../agent-hooks/observations/agent-transition-detector' +import '../../../../shared/sidebar-list/stamp-order' import { SortStampsProducer, type StoredTierEvidence } from './sort-stamps-producer' -import type { SortStampsStore } from './sort-stamp-records' +import type { SortStampsStore } from '../../workspaces/metadata/workspace-activity-records' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) const WT = 'repo-1::/tmp/a' const FOLDER_ID = '11111111-1111-4111-8111-111111111111' diff --git a/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts b/src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.ts similarity index 95% rename from src/main/runtime/sidebar-inputs/sort-stamps-producer.ts rename to src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.ts index 62ac2330c75..114a69ca6fd 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts +++ b/src/main/runtime/sidebar-inputs/temporal/sort-stamps-producer.ts @@ -1,9 +1,9 @@ -import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' +import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' import type { AgentPhase, AgentTransition -} from '../../../shared/agent-status/lifecycle/agent-transitions' +} from '../../../../shared/agent-status/lifecycle/agent-transitions' import { classifySortStampEvent, enterAgentPaneState, @@ -11,15 +11,15 @@ import { REST_PANE, type AgentPaneState, type SortStampEvent -} from '../../../shared/sidebar-list/sort-stamps' -import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' +} from '../../../../shared/sidebar-list/sort-stamps' +import type { TerminalSideEffectBatch } from '../../../../shared/terminal/output/terminal-side-effect-facts' import { agentPaneWorkspace, sameAgentPaneWorkspace, type AgentPaneChange, type AgentPaneWorkspace, type AgentTransitionDetector -} from '../../agent-hooks/observations/agent-transition-detector' +} from '../../../agent-hooks/observations/agent-transition-detector' import { listTieredWorkspaces, readSortStamps, @@ -27,7 +27,7 @@ import { writeSortStamps, writeUnreadFlag, type SortStampsStore -} from './sort-stamp-records' +} from '../../workspaces/metadata/workspace-activity-records' /** What the startup reconcile asks of the host, once its hook rows and PTYs have settled. */ export type StoredTierEvidence = { diff --git a/src/main/runtime/sidebar-inputs/terminal-use-producer.ts b/src/main/runtime/sidebar-inputs/temporal/terminal-use-producer.ts similarity index 91% rename from src/main/runtime/sidebar-inputs/terminal-use-producer.ts rename to src/main/runtime/sidebar-inputs/temporal/terminal-use-producer.ts index 91f894f9d0b..75103173dab 100644 --- a/src/main/runtime/sidebar-inputs/terminal-use-producer.ts +++ b/src/main/runtime/sidebar-inputs/temporal/terminal-use-producer.ts @@ -2,8 +2,8 @@ import { readWorkspaceRecord, writeWorkspaceRecord, type WorkspaceRecordStore -} from './sort-stamp-records' -import type { AgentPaneWorkspace } from '../../agent-hooks/observations/agent-transition-detector' +} from '../../workspaces/metadata/workspace-activity-records' +import type { AgentPaneWorkspace } from '../../../agent-hooks/observations/agent-transition-detector' /** At most one write per workspace per minute; cleanup judges idleness in days. */ export const TERMINAL_USE_THROTTLE_MS = 60_000 diff --git a/src/main/runtime/sidebar-inputs/workspace-viewers.test.ts b/src/main/runtime/sidebar-inputs/temporal/workspace-viewers.test.ts similarity index 100% rename from src/main/runtime/sidebar-inputs/workspace-viewers.test.ts rename to src/main/runtime/sidebar-inputs/temporal/workspace-viewers.test.ts diff --git a/src/main/runtime/sidebar-inputs/workspace-viewers.ts b/src/main/runtime/sidebar-inputs/temporal/workspace-viewers.ts similarity index 90% rename from src/main/runtime/sidebar-inputs/workspace-viewers.ts rename to src/main/runtime/sidebar-inputs/temporal/workspace-viewers.ts index 4224d6e29e9..e5e379f9730 100644 --- a/src/main/runtime/sidebar-inputs/workspace-viewers.ts +++ b/src/main/runtime/sidebar-inputs/temporal/workspace-viewers.ts @@ -1,6 +1,6 @@ -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { worktreeIdentityKey } from '../../../shared/worktree/id' -import type { ClientWorkspaceView } from '../../../shared/rpc-contract/client-workspace-view-params' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { worktreeIdentityKey } from '../../../../shared/worktree/id' +import type { ClientWorkspaceView } from '../../../../shared/rpc-contract/client-ui/client-workspace-view-params' type ClientView = { workspaceKeys: Set; tabIds: Set; presentUntil: number } diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-detected-checkouts-live-content.ts b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-detected-checkouts-live-content.ts similarity index 78% rename from src/main/runtime/sidebar-inputs/orca-runtime-detected-checkouts-live-content.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-detected-checkouts-live-content.ts index 1808afd6342..7d2351b852f 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-detected-checkouts-live-content.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-detected-checkouts-live-content.ts @@ -1,9 +1,9 @@ import { OrcaRuntimeWithWorkspaceReviewFacts } from './orca-runtime-workspace-review-facts' -import { isFolderRepo } from '../../../shared/repo-kind' -import { worktreeIdsEqual } from '../../../shared/worktree/id' -import type { WorkspaceLiveContent } from '../../../shared/sidebar-list/workspace-live-content' -import { runtimeVisibleRepos } from '../workspaces/catalog/runtime-visible-catalog' -import { DetectedCheckoutsProducer } from './detected-checkouts-producer' +import { isFolderRepo } from '../../../../shared/repo-kind' +import { worktreeIdsEqual } from '../../../../shared/worktree/id' +import type { WorkspaceLiveContent } from '../../../../shared/sidebar-list/workspace-live-content' +import { runtimeVisibleRepos } from '../../workspaces/catalog/runtime-visible-catalog' +import { DetectedCheckoutsProducer } from '../workspace-rows/detected-checkouts-producer' import { WorkspaceLiveContentProducer } from './workspace-live-content-producer' /** Two producers published for readers still to come: detected checkouts and live terminal content. */ diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.test.ts similarity index 91% rename from src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.test.ts index e356416d19a..aa6175a5699 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.test.ts @@ -1,10 +1,10 @@ // Runs on plain Node, as orcad does: the producer and its runtime wiring import no Electron. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/runtime-session-contracts' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { OrcaRuntimeService } from '../orca-runtime' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { OrcaRuntimeService } from '../../orca-runtime' -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) const WT = 'repo-1::/tmp/worktree-a' const LEAF = '22222222-2222-4222-8222-222222222222' diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.ts b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.ts similarity index 94% rename from src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.ts index 48ea2cbac3f..a70b7cd0f48 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-activity-facts.ts @@ -1,11 +1,11 @@ -import { OrcaRuntimeWithAgentTransitions } from '../construction/orca-runtime-agent-transitions' -import type { PtyLivenessVerdict } from '../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import { OrcaRuntimeWithAgentTransitions } from '../../construction/orca-runtime-agent-transitions' +import type { PtyLivenessVerdict } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import type { WorkspaceActivityFactsSnapshot, WorkspaceTerminalLiveness -} from '../../../shared/sidebar-list/workspace-activity-facts' -import { worktreeIdentityKey } from '../../../shared/worktree/id' -import { SidebarClock } from './sidebar-clock' +} from '../../../../shared/sidebar-list/workspace-activity-facts' +import { worktreeIdentityKey } from '../../../../shared/worktree/id' +import { SidebarClock } from '../sidebar-clock' import { WorkspaceActivityFactsProducer, type WorkspaceSurfaceActivity diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-review-facts.ts b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-review-facts.ts similarity index 92% rename from src/main/runtime/sidebar-inputs/orca-runtime-workspace-review-facts.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-review-facts.ts index 2d92705e667..21101b009e4 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-review-facts.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/orca-runtime-workspace-review-facts.ts @@ -2,7 +2,7 @@ import { OrcaRuntimeWithWorkspaceActivityFacts } from './orca-runtime-workspace- import { buildWorkspaceReviewFacts, type WorkspaceReviewFactsSnapshot -} from '../../../shared/sidebar-list/workspace-review-facts' +} from '../../../../shared/sidebar-list/workspace-review-facts' /** Read host-persisted PR facts on demand; windows save cache updates within a second, while orcad uses its existing profile. */ export abstract class OrcaRuntimeWithWorkspaceReviewFacts extends OrcaRuntimeWithWorkspaceActivityFacts { diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts b/src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.test.ts similarity index 95% rename from src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.test.ts index e956f8c0519..02f5c9a7322 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { SidebarClock } from './sidebar-clock' -import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../shared/agent-status/contracts/agent-status-freshness' +import { SidebarClock } from '../sidebar-clock' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness' import { WorkspaceActivityFactsProducer, type WorkspaceSurfaceActivity diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts b/src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.ts similarity index 93% rename from src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.ts index 21445f85287..8fc4c62b004 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/workspace-activity-facts-producer.ts @@ -1,12 +1,12 @@ -import { ProducerRevision } from './producer-revision' +import { ProducerRevision } from '../producer-revision' import { AGENT_STATUS_STALE_AFTER_MS, isFreshNonDoneAgentStatus, agentStatusEvidenceObservedAt -} from '../../../shared/agent-status/contracts/agent-status-freshness' -import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +} from '../../../../shared/agent-status/contracts/agent-status-freshness' +import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { resolveAgentStatusWorktreeId } from '../../../shared/agent-status/identity/agent-status-worktree-attribution' +import { resolveAgentStatusWorktreeId } from '../../../../shared/agent-status/identity/agent-status-worktree-attribution' import { IDLE_WORKSPACE_ACTIVITY, isIdleWorkspaceActivity, @@ -16,9 +16,9 @@ import { type LiveAgentWorktreeStatus, type WorkspaceActivityFacts, type WorkspaceActivityFactsSnapshot -} from '../../../shared/sidebar-list/workspace-activity-facts' -import type { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' -import type { SidebarClock } from './sidebar-clock' +} from '../../../../shared/sidebar-list/workspace-activity-facts' +import type { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import type { SidebarClock } from '../sidebar-clock' export type WorkspaceSurfaceActivity = Omit diff --git a/src/main/runtime/sidebar-inputs/workspace-live-content-producer.ts b/src/main/runtime/sidebar-inputs/workspace-facts/workspace-live-content-producer.ts similarity index 89% rename from src/main/runtime/sidebar-inputs/workspace-live-content-producer.ts rename to src/main/runtime/sidebar-inputs/workspace-facts/workspace-live-content-producer.ts index 04fbdfb4587..9052036b3b9 100644 --- a/src/main/runtime/sidebar-inputs/workspace-live-content-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-facts/workspace-live-content-producer.ts @@ -1,8 +1,8 @@ import { workspaceLiveContentEqual, type WorkspaceLiveContent -} from '../../../shared/sidebar-list/workspace-live-content' -import { ProducerRevision } from './producer-revision' +} from '../../../../shared/sidebar-list/workspace-live-content' +import { ProducerRevision } from '../producer-revision' /** Refresh live terminal content through the activity producer's per-workspace funnel, including PTY binds, exits and verdicts. */ export class WorkspaceLiveContentProducer { diff --git a/src/main/runtime/sidebar-inputs/detected-checkouts-producer.ts b/src/main/runtime/sidebar-inputs/workspace-rows/detected-checkouts-producer.ts similarity index 83% rename from src/main/runtime/sidebar-inputs/detected-checkouts-producer.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/detected-checkouts-producer.ts index 9063b79539c..86849dad45e 100644 --- a/src/main/runtime/sidebar-inputs/detected-checkouts-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/detected-checkouts-producer.ts @@ -1,10 +1,10 @@ -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' -import type { Repo } from '../../../shared/repo-types' -import type { DetectedWorktreeListResult } from '../../../shared/worktree/types' -import { getRepoExecutionHostId } from '../../../shared/execution-host' -import { getRepoHostIdentityForParts } from '../../../shared/repo-host-identity' -import { CachedScan } from './cached-scan' -import { ProducerRevision } from './producer-revision' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import type { Repo } from '../../../../shared/repo-types' +import type { DetectedWorktreeListResult } from '../../../../shared/worktree/types' +import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { getRepoHostIdentityForParts } from '../../../../shared/repo-host-identity' +import { CachedScan } from '../cached-scan' +import { ProducerRevision } from '../producer-revision' export type DetectedCheckoutsSources = { /** The git repos to list, as worktree.detectedList resolves them. */ diff --git a/src/main/runtime/sidebar-inputs/paired-server-rows-producer.test.ts b/src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.test.ts similarity index 90% rename from src/main/runtime/sidebar-inputs/paired-server-rows-producer.test.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.test.ts index 74c44787ec7..ce0623ebf26 100644 --- a/src/main/runtime/sidebar-inputs/paired-server-rows-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RUNTIME_PROTOCOL_VERSION } from '../../../shared/protocol-version' +import { RUNTIME_PROTOCOL_VERSION } from '../../../../shared/protocol-version' import { runtimeEnvironmentStatusFromSnapshot, type RuntimeHostStatusSnapshot -} from '../../../shared/remote-runtime/host-status/runtime-host-status' -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { SshConnectionState } from '../../../shared/ssh-types' -import type { MobileDesktopRelayHosts } from '../mobile-desktop-relay/mobile-desktop-relay-hosts' +} from '../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import type { SshConnectionState } from '../../../../shared/ssh-types' +import type { MobileDesktopRelayHosts } from '../../mobile-desktop-relay/mobile-desktop-relay-hosts' import { PairedServerRowsProducer } from './paired-server-rows-producer' function snapshot(environmentId: string, live: boolean): RuntimeHostStatusSnapshot { @@ -271,23 +271,4 @@ describe('PairedServerRowsProducer', () => { rows: [{ worktreeId: 'current' }] }) }) - - it('opens a new watch once the old one ends with its transport, even without a close notice', () => { - const { hosts, watches, publishStatus } = fakeHosts([{ id: 'box', live: true }]) - const producer = new PairedServerRowsProducer({ - hasDemand: () => true, - hostLabelOverrides: () => new Map() - }) - producer.attach(hosts) - const first = watches.get('box') - publishStatus() - expect(watches.get('box')).toBe(first) - - if (first) { - first.ended = true - } - publishStatus() - expect(watches.get('box')).not.toBe(first) - expect(first?.closed).toBe(true) - }) }) diff --git a/src/main/runtime/sidebar-inputs/paired-server-rows-producer.ts b/src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.ts similarity index 91% rename from src/main/runtime/sidebar-inputs/paired-server-rows-producer.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.ts index 9c247699650..7de266282f2 100644 --- a/src/main/runtime/sidebar-inputs/paired-server-rows-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.ts @@ -1,28 +1,28 @@ -import { ProducerRevision } from './producer-revision' -import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { describePairedServerHosts } from '../../../shared/remote-runtime/host-catalog/paired-server-hosts' -import type { MobileRelayServerWorktreeRow } from '../../../shared/remote-runtime/relay/mobile-relay-hosts-contract' +import { ProducerRevision } from '../producer-revision' +import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { describePairedServerHosts } from '../../../../shared/remote-runtime/host-catalog/paired-server-hosts' +import type { MobileRelayServerWorktreeRow } from '../../../../shared/remote-runtime/relay/mobile-relay-hosts-contract' import { normalizePairedServerRow, type PairedServerRowsSnapshot -} from '../../../shared/sidebar-list/paired-server-rows' +} from '../../../../shared/sidebar-list/paired-server-rows' import type { MobileDesktopRelayHostListing, MobileDesktopRelayHosts, MobileDesktopRelayHostWatch -} from '../mobile-desktop-relay/mobile-desktop-relay-hosts' +} from '../../mobile-desktop-relay/mobile-desktop-relay-hosts' import { describeRelayHosts, relayHostFence -} from '../mobile-desktop-relay/mobile-relay-host-descriptions' -import type { ServerWorktreeRows } from '../mobile-desktop-relay/mobile-relay-host-catalog' +} from '../../mobile-desktop-relay/mobile-relay-host-descriptions' +import type { ServerWorktreeRows } from '../../mobile-desktop-relay/mobile-relay-host-catalog' import { SERVER_WORKTREE_LIMIT, WorktreePsReplySchema, stampServerWorktreeRows -} from '../mobile-desktop-relay/server-worktree-fetch' -import type { PairedServerCatalog } from '../../../shared/sidebar-list/sidebar-project-catalog' -import { fetchPairedServerCatalog } from '../../../shared/sidebar-list/paired-server-catalog' +} from '../../mobile-desktop-relay/server-worktree-fetch' +import type { PairedServerCatalog } from '../../../../shared/sidebar-list/sidebar-project-catalog' +import { fetchPairedServerCatalog } from '../../../../shared/sidebar-list/paired-server-catalog' // Owner-approved fallback for changes a server announces no event for (status-only, older servers). export const FALLBACK_REFRESH_MS = 30_000 diff --git a/src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.test.ts similarity index 98% rename from src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.test.ts index 3ee40cb8eee..8c33945d36e 100644 --- a/src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { getRepoHostIdentityForParts } from '../../../shared/repo-host-identity' +import { getRepoHostIdentityForParts } from '../../../../shared/repo-host-identity' import { WorkspaceGitIdentity, type ScannedIdentityRow } from './workspace-git-identity' const REPO = getRepoHostIdentityForParts('repo-1', 'local') diff --git a/src/main/runtime/sidebar-inputs/workspace-git-identity.ts b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.ts similarity index 92% rename from src/main/runtime/sidebar-inputs/workspace-git-identity.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.ts index 8d7cbff00ba..ca941467f9e 100644 --- a/src/main/runtime/sidebar-inputs/workspace-git-identity.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-git-identity.ts @@ -1,21 +1,21 @@ -import type { Worktree } from '../../../shared/worktree/types' +import type { Worktree } from '../../../../shared/worktree/types' import { composeWorktreeHostIdentity, hostWorktreeTarget, type HostScopedWorktreeKey, type HostWorktreeTarget -} from '../../../shared/worktree/host-qualified-identity' -import type { HOSTED_REVIEW_LINK_KEYS } from '../../../shared/worktree/hosted-review-links' +} from '../../../../shared/worktree/host-qualified-identity' +import type { HOSTED_REVIEW_LINK_KEYS } from '../../../../shared/worktree/hosted-review/hosted-review-links' import { branchHostedReviewOwner, hostedReviewClearUpdates, type HostedReviewClearUpdates, type HostedReviewOwner -} from '../../../shared/worktree/hosted-review-branch-ownership' +} from '../../../../shared/worktree/hosted-review/hosted-review-branch-ownership' import { getRepoHostIdentityForParts, type HostScopedRepoKey -} from '../../../shared/repo-host-identity' +} from '../../../../shared/repo-host-identity' type IdentityRow = Pick< Worktree, diff --git a/src/main/runtime/sidebar-inputs/workspace-rows-producer.test.ts b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.test.ts similarity index 81% rename from src/main/runtime/sidebar-inputs/workspace-rows-producer.test.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.test.ts index eca8e46ff60..e16c02b632a 100644 --- a/src/main/runtime/sidebar-inputs/workspace-rows-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.test.ts @@ -1,32 +1,32 @@ // Runs on plain Node, as orcad does: rows come from the runtime's own listing and store. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../shared/repo-types' +import type { Repo } from '../../../../shared/repo-types' -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' -import { OrcaRuntimeService } from '../orca-runtime' +import { OrcaRuntimeService } from '../../orca-runtime' -import type { ResolvedWorktreeSnapshot } from '../workspaces/catalog/runtime-resolved-worktree-cache' +import type { ResolvedWorktreeSnapshot } from '../../workspaces/catalog/runtime-resolved-worktree-cache' -import type { RuntimeStore } from '../construction/runtime-store-contract' +import type { RuntimeStore } from '../../construction/runtime-store-contract' -import type { ResolvedWorktree } from '../workspaces/catalog/runtime-worktree-path-identity' +import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' -import { requireSwitchedOn } from './require-switched-on' +import { requireSwitchedOn } from '../../construction/require-sidebar-inputs-enabled' -import { TestPhone } from './sidebar-inputs-feed.test-fixture' +import { TestPhone } from '../feed/testing/sidebar-inputs-feed.test-fixture' import type { ResolvedWorktreeRepoScans, ResolvedWorktreeScanJoin -} from '../workspaces/catalog/resolved-worktree-scan-join' +} from '../../workspaces/catalog/resolved-worktree-scan-join' -import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' +import { composeWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' -import { getRepoHostIdentityForParts } from '../../../shared/repo-host-identity' +import { getRepoHostIdentityForParts } from '../../../../shared/repo-host-identity' -vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) +vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) const localRepo: Repo = { id: 'repo-1', @@ -118,7 +118,6 @@ function setup(repos: Repo[] = [localRepo, sshRepo]) { let scans = 0 // A new object per scan that really ran git; a cached scan repeats the last one. let gitRun: object = {} - let freshGitRuns = true let scanGate: Promise | null = null // The real listing cache and visibility filter run; only the scan and merge are stubbed. class Probe extends OrcaRuntimeService { @@ -129,7 +128,7 @@ function setup(repos: Repo[] = [localRepo, sshRepo]) { protected override async scanResolvedWorktreeRepos(): Promise { scans += 1 await scanGate - gitRun = freshGitRuns ? {} : gitRun + gitRun = {} return new Map() } @@ -162,10 +161,6 @@ function setup(repos: Repo[] = [localRepo, sshRepo]) { runtime, setWorktreeMeta, scans: () => scans, - /** Whether the next scans run git again or answer from the scan cache. */ - setFreshGitRuns: (fresh: boolean) => { - freshGitRuns = fresh - }, /** Holds every scan until the returned release runs. */ holdScans(): () => void { let release = (): void => {} @@ -281,24 +276,4 @@ describe('WorkspaceRowsProducer', () => { expect(rows.snapshot()?.rows['local|repo-1::/r/a']).toMatchObject({ displayName: 'b' }) detach() }) - - it('keeps a PR linked after a branch switch that a cached rescan did not see yet', async () => { - const { runtime, rows, listing, write, setWorktreeMeta, setFreshGitRuns } = setup() - const detach = rows.revision.onChange(() => {}) - listing.worktrees[0] = { ...listing.worktrees[0], instanceId: 'i-1' } - await rows.settled() - // `git checkout -b b`; the scan cache still answers with branch a. - setFreshGitRuns(false) - listing.worktrees[0] = { ...listing.worktrees[0], linkedPR: 9 } - write(['worktreeMeta']) - runtime.emit({ type: 'worktreesChanged', repoId: 'repo-1' }) - await rows.settled() - // Git runs again and reports the new branch: the new branch's PR stays. - setFreshGitRuns(true) - listing.worktrees[0] = { ...listing.worktrees[0], branch: 'refs/heads/b' } - runtime.emit({ type: 'worktreesChanged', repoId: 'repo-1' }) - await rows.settled() - expect(setWorktreeMeta).not.toHaveBeenCalled() - detach() - }) }) diff --git a/src/main/runtime/sidebar-inputs/workspace-rows-producer.ts b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.ts similarity index 88% rename from src/main/runtime/sidebar-inputs/workspace-rows-producer.ts rename to src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.ts index 0418b5c04f5..6ba75841871 100644 --- a/src/main/runtime/sidebar-inputs/workspace-rows-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.ts @@ -1,26 +1,26 @@ -import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' import { buildWorkspaceRows, type WorkspaceRowsSnapshot -} from '../../../shared/sidebar-list/workspace-rows' -import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' -import type { ResolvedWorktree } from '../workspaces/catalog/runtime-worktree-path-identity' -import type { ResolvedWorktreeSnapshot } from '../workspaces/catalog/runtime-resolved-worktree-cache' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import { runtimeVisibleFolderWorkspaces } from '../workspaces/catalog/runtime-visible-catalog' +} from '../../../../shared/sidebar-list/workspace-rows' +import { composeWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' +import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' +import type { ResolvedWorktreeSnapshot } from '../../workspaces/catalog/runtime-resolved-worktree-cache' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { runtimeVisibleFolderWorkspaces } from '../../workspaces/catalog/runtime-visible-catalog' import type { ResolvedWorktreeRepoScans, ResolvedWorktreeScanJoin -} from '../workspaces/catalog/resolved-worktree-scan-join' +} from '../../workspaces/catalog/resolved-worktree-scan-join' import { savedWorkspaceCatalog, WORKTREE_METADATA_DOMAINS -} from '../../persistence/profile-save-domains' -import { ProducerRevision } from './producer-revision' +} from '../../../persistence/profile-save-domains' +import { ProducerRevision } from '../producer-revision' import { WorkspaceGitIdentity } from './workspace-git-identity' -import { CachedScan } from './cached-scan' -import type { WorkspaceLifecycleQueue } from '../workspaces/lifecycle/workspace-lifecycle-queue' +import { CachedScan } from '../cached-scan' +import type { WorkspaceLifecycleQueue } from '../../workspaces/lifecycle/workspace-lifecycle-queue' // The settings the visibility filter reads: the defaults, and the layouts that classify a checkout. const VISIBILITY_SETTINGS = [ diff --git a/src/main/runtime/speech/mobile-dictation-chunk-order.ts b/src/main/runtime/speech/mobile-dictation-chunk-order.ts index 0b18522fe23..9e5ec6915ed 100644 --- a/src/main/runtime/speech/mobile-dictation-chunk-order.ts +++ b/src/main/runtime/speech/mobile-dictation-chunk-order.ts @@ -1,4 +1,4 @@ -import { MOBILE_DICTATION_MAX_PENDING_AUDIO_BYTES } from '../../../shared/rpc-contract/speech-params' +import { MOBILE_DICTATION_MAX_PENDING_AUDIO_BYTES } from '../../../shared/rpc-contract/speech/speech-params' export type MobileDictationChunk = { audioBase64: string; sampleRate: number } diff --git a/src/main/runtime/speech/runtime-mobile-dictation-controller.test.ts b/src/main/runtime/speech/runtime-mobile-dictation-controller.test.ts index d113ac4a69f..6e37bf80402 100644 --- a/src/main/runtime/speech/runtime-mobile-dictation-controller.test.ts +++ b/src/main/runtime/speech/runtime-mobile-dictation-controller.test.ts @@ -4,7 +4,7 @@ import { setSpeechServiceFactories, type SpeechServiceFactories } from '../../speech/speech-runtime-service' -import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../shared/rpc-contract/speech-params' +import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../shared/rpc-contract/speech/speech-params' import { RuntimeMobileDictationController } from './runtime-mobile-dictation-controller' import type { RuntimeStore } from '../construction/runtime-store-contract' @@ -102,16 +102,6 @@ describe('mobile dictation across a phone reconnect', () => { }) }) - it('releases the speech model when the phone goes quiet for the grace', async () => { - const controller = await startPhoneDictation() - transcription = new Promise(() => {}) - - await vi.advanceTimersByTimeAsync(MOBILE_DICTATION_RECONNECT_GRACE_MS) - - expect(stopDictation).toHaveBeenCalledOnce() - expect(() => controller.feed(chunk)).toThrow('dictation_stream_not_started') - }) - it('feeds resent audio once and in the order it was spoken', async () => { const controller = await startPhoneDictation() const spoken = (seq: number) => ({ diff --git a/src/main/runtime/speech/runtime-mobile-dictation-controller.ts b/src/main/runtime/speech/runtime-mobile-dictation-controller.ts index 2bbf14ed4ed..0f06a9c5c9c 100644 --- a/src/main/runtime/speech/runtime-mobile-dictation-controller.ts +++ b/src/main/runtime/speech/runtime-mobile-dictation-controller.ts @@ -1,5 +1,5 @@ import { getDefaultVoiceSettings } from '../../../shared/constants' -import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../shared/rpc-contract/speech-params' +import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../shared/rpc-contract/speech/speech-params' import { speechModelNotReadyError } from '../../../shared/speech-model-retirement' import { getSpeechModelManager, getSpeechSttService } from '../../speech/speech-runtime-service' import { getCatalogModel, isLocalSpeechModel } from '../../speech/model-catalog' @@ -13,6 +13,10 @@ import { } from './mobile-dictation-chunk-order' import type { RuntimeStore } from '../construction/runtime-store-contract' import { hostDictationTerms } from './runtime-dictation-terms' +import { dictationTextSettingsFor } from '../../../shared/dictation-cleanup' +import type { DictationTerm } from '../../../shared/dictation-dictionary' +import { cleanUpDictatedText } from '../../speech/dictation-cleanup-service' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/execution/commit-message-agent-environment' import { DictationTranscript, type DictationTranscriptSnapshot @@ -22,6 +26,8 @@ type MobileDictationSession = { id: string owner: string clientId: string + /** The dictionary it was transcribed with, which cleanup spells by too. */ + terms: DictationTerm[] state: 'starting' | 'active' | 'closing' transcript: DictationTranscript errors: string[] @@ -74,10 +80,12 @@ export class RuntimeMobileDictationController { } const owner = `mobile:${clientId}:${params.dictationId}` + const terms = hostDictationTerms(store, params.worktreeId) const session: MobileDictationSession = { id: params.dictationId, owner, clientId, + terms, state: 'starting', transcript: new DictationTranscript(), errors: [], @@ -91,9 +99,9 @@ export class RuntimeMobileDictationController { await getSpeechSttService(store).startDictation( modelId, (event) => acceptEvent(session, event), - hostDictationTerms(store, params.worktreeId), + terms, owner, - voice + dictationTextSettingsFor({ ...store.getSettings(), voice }) ) if (this.sessions.get(clientId) !== session) { throw new Error('dictation_canceled') @@ -149,10 +157,11 @@ export class RuntimeMobileDictationController { return { ...reply, ...session.transcript.snapshot() } } - async finish(params: { - dictationId: string - clientId?: string - }): Promise<{ dictationId: string; text: string }> { + /** `agentEnv`: what AI cleanup runs the user's agent with, when it's on. */ + async finish( + params: { dictationId: string; clientId?: string }, + agentEnv?: CommitMessageAgentEnvironmentResolvers + ): Promise<{ dictationId: string; text: string }> { const session = this.requireOwnedSession(params) for (const chunk of session.chunkOrder.drain()) { this.feedChunk(session, chunk) @@ -161,7 +170,17 @@ export class RuntimeMobileDictationController { if (session.errors.length > 0) { throw new Error(session.errors[0]) } - return { dictationId: params.dictationId, text: session.transcript.snapshot().text } + const heard = session.transcript.snapshot().text + // The phone waits out cleanup inside its finish deadline; on any failure it gets the words as heard. + const store = this.requireStore() + const cleaned = await cleanUpDictatedText( + { text: heard, terms: session.terms }, + { getSettings: () => store.getSettings(), getAgentEnvResolvers: () => agentEnv } + ) + return { + dictationId: params.dictationId, + text: cleaned.status === 'cleaned' ? cleaned.text : heard + } } async cancel(params: { diff --git a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-plan.ts b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-plan.ts index 7e79b381145..950021307ba 100644 --- a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-plan.ts +++ b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-plan.ts @@ -2,7 +2,7 @@ import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtim import type { RuntimeTerminalOrphanAdoptionRequest } from '../../../../shared/runtime-terminal-contracts' import type { ExecutionHostId } from '../../../../shared/execution-host' import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { terminalOrphanExecutionOwnersEqual } from './terminal-orphan-owner' import type { TerminalWorkspaceLaunchScope } from '../../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' diff --git a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-rollback.test.ts b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-rollback.test.ts index 5582f1cda85..c6040e3bb44 100644 --- a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-rollback.test.ts +++ b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-rollback.test.ts @@ -11,7 +11,7 @@ import { addWorkspace, emptySession, leaf -} from '../../../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { closeTestStores, createStore, @@ -36,7 +36,6 @@ const testStateDirRef = vi.hoisted(() => ({ dir: '' })) const REPO_ID = 'repo-1' const ORPHAN_TAB = 'tab-orphan' const ORPHAN_LEAF = leaf(2) -const ORPHAN_PANE = `${ORPHAN_TAB}:${ORPHAN_LEAF}` function seededSession(revision: number | undefined): WorkspaceSessionState { const session = addWorkspace(emptySession(), GIT_KEY, [ @@ -155,23 +154,6 @@ describe('orphan adoption whose flush fails', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it.each([ - ['a repo with no fence yet', undefined], - ['a repo whose fence is armed', 3] - ])('leaves no adopted tab, layout or incarnation behind in %s', async (_label, revision) => { - const store = createStore() - store.setWorkspaceSession(seededSession(revision)) - const before = store.getWorkspaceSession() - - await expect(adoptWithFailingFlush(store, revision ?? 0)).rejects.toThrow('disk_full') - - const after = store.getWorkspaceSession() - expect(after.tabsByWorktree[GIT_KEY]?.map((tab) => tab.id)).toEqual(['tab-kept']) - expect(after.terminalLayoutsByTabId[ORPHAN_TAB]).toBeUndefined() - expect(after.terminalPtyIncarnationsByPaneKey?.[ORPHAN_PANE]).toBeUndefined() - expect(after.tabGroups?.[GIT_KEY]).toEqual(before.tabGroups?.[GIT_KEY]) - }) - it('keeps an unrelated edit that landed while it waited to write', async () => { const store = createStore() store.setWorkspaceSession(seededSession(3)) diff --git a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts index 9c604046df8..b4daa1815e1 100644 --- a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts +++ b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts @@ -1,20 +1,20 @@ import { randomUUID } from 'node:crypto' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { RuntimeTerminalOrphanAdoptionRequest } from '../../../../shared/runtime-terminal-contracts' -import { loadWorkspaceLayoutWithoutReport } from '../../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../../shared/workspace-layout/workspace-layout-minted-ids' -import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-save' +import { loadWorkspaceLayoutWithoutReport } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { collectPersistedTerminalLeafIds } from '../surface/mobile-session-layout-projection' import { collectLayoutLeafIdsInOrder, removeLayoutLeaf -} from '../../../../shared/workspace-layout/terminal-pane-tree' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { mergeTerminalOrphanGroupLayout } from './terminal-orphan-topology' import { canonicalizeTerminalSessionWorktreeId } from '../identity/workspace-session-worktree-id' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' type Claim = RuntimeTerminalOrphanAdoptionRequest['claims'][number] type Topology = NonNullable diff --git a/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts b/src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts similarity index 87% rename from src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts rename to src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts index fb6c00f9ea1..3f7c8c12f10 100644 --- a/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts +++ b/src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts @@ -2,23 +2,23 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { Store } from '../../../persistence/loading-store/store' import { placeUnshownLiveTerminals, type LiveTerminalPlacementPorts -} from '../../runtime/terminal/adoption/unshown-live-terminal-placement' -import { WindowSession } from './terminal-topology-window-session-fixture' +} from './unshown-live-terminal-placement' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts index df795e843f5..f48d09c1af9 100644 --- a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts +++ b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it, vi } from 'vitest' import { realpath } from 'node:fs/promises' import { useRuntimeFileHostLifecycle } from '../../files/runtime-file-host.test-fixture' +import { resolveAuthorizedPathMock, statMock } from '../../files/runtime-file-command-mock-registry' vi.mock('fs', async () => (await import('../../files/runtime-file-command-mock-registry')).fsModuleMock() @@ -78,6 +79,43 @@ describe('RuntimeTerminalArtifacts', () => { ).resolves.toEqual({ ok: true }) }) + it('answers the root of a workspace nested inside the tapped one as that workspace', async () => { + resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) + statMock.mockResolvedValue({ isDirectory: () => true, size: 0, dev: 1, ino: 2, mtimeMs: 3 }) + const resolveKnownWorkspaceFileTarget = vi.fn(async (absolutePath: string) => + absolutePath === '/repo/worktrees/wt-2' + ? { + worktree: { id: 'wt-2', repoId: 'repo-1', path: '/repo/worktrees/wt-2' }, + executionHostId: 'local', + relativePath: '' + } + : { + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo' }, + executionHostId: 'local', + relativePath: 'src' + } + ) + const { paths } = createTerminalArtifactSubjects({ + path: '/repo', + resolveKnownWorkspaceFileTarget + }) + const resolve = (pathText: string) => + paths.resolveTerminalPath('id:wt-1', pathText, null, 'client-a', null, true) + + expect(await resolve('/repo/worktrees/wt-2')).toEqual({ + worktree: 'wt-2', + relativePath: '', + absolutePath: '/repo/worktrees/wt-2', + exists: true, + isDirectory: true + }) + expect(await resolve('/repo/src')).toMatchObject({ + worktree: 'wt-1', + relativePath: 'src', + isDirectory: true + }) + }) + // Why: procfs reports size 0 for files with content, so the grant digest cannot trust stat size. it.runIf(process.platform === 'linux')('reads a procfs file that reports size 0', async () => { const { paths, commands } = createTerminalArtifactSubjects({ path: '/repo' }) diff --git a/src/main/runtime/terminal/focus/focus-terminal.ts b/src/main/runtime/terminal/focus/focus-terminal.ts index fea722f6698..78561a831ab 100644 --- a/src/main/runtime/terminal/focus/focus-terminal.ts +++ b/src/main/runtime/terminal/focus/focus-terminal.ts @@ -3,7 +3,7 @@ import type { RuntimeTerminalFocus } from '../../../../shared/runtime-terminal-c import type { RuntimeTerminalReveal, TerminalPaneRevealTarget -} from '../../../../shared/workspace-layout/terminal-pane-reveal' +} from '../../../../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { getLatestPtyTitle } from '../../workspaces/process-listing/runtime-worktree-status-projection' import { copySleepingAgentLaunchConfig } from '../launch/runtime-agent-launch-resolution' diff --git a/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts b/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts index 005bad4d89d..f87c89b12e4 100644 --- a/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts +++ b/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts @@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' await import('../../orca-runtime-tests/runtime-test-module-registration.spec') const { OrcaRuntimeService } = await import('../../orca-runtime') diff --git a/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts b/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts index 63e4edb4d22..8875fd0f0d5 100644 --- a/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts +++ b/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts @@ -2,7 +2,7 @@ import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { forgetFailedAgentLaunches } from '../../../agent-launch/agent-launch-pane-attachment' import type { Store } from '../../../persistence/loading-store/store' import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import type { TerminalLeafMoveRequest } from '../../../../shared/workspace-layout/terminal-leaf-move' +import type { TerminalLeafMoveRequest } from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import type { OrcaRuntimeService } from '../../orca-runtime' type PaneOwnerRuntime = Pick | undefined diff --git a/src/main/runtime/terminal/identity/quarter-circle-title-send-authorization.test.ts b/src/main/runtime/terminal/identity/quarter-circle-title-send-authorization.test.ts deleted file mode 100644 index ccacd82f373..00000000000 --- a/src/main/runtime/terminal/identity/quarter-circle-title-send-authorization.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Quarter-circle progress glyphs alone cannot authorize auto-Enter into an unknown pane owner (STA-4028, #13925). -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { OrcaRuntimeService } from '../../orca-runtime' - -import { assertTerminalAgentSendable } from '../../rpc/terminal-agent-send-guard' - -vi.mock('electron', () => ({ - BrowserWindow: { fromId: vi.fn(() => null) }, - webContents: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - app: { getPath: vi.fn(() => '/tmp') } -})) - -const LEAF_ID = '11111111-1111-4111-8111-111111111111' -const TAB_ID = 'tab-1' -const WORKTREE_ID = 'wt-1' -const PTY_ID = 'pty-1' - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() -}) - -// Captured from Claude Code 2.1.228 while it read this repository's package.json. -const SPINNER_ONLY_TITLE = '◑ Check package version in package.json' - -async function createRuntimeWithTitle( - paneTitle: string, - foregroundProcess: string | null, - launchAgent?: 'claude', - verifiedLaunch = true -): Promise<{ - runtime: OrcaRuntimeService - handle: string - getForegroundProcess: ReturnType -}> { - const runtime = new OrcaRuntimeService(null) - const internals = runtime as unknown as { - resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise - } - vi.spyOn(internals, 'resolveTerminalWorkspaceLaunchScope').mockResolvedValue({ - id: WORKTREE_ID, - path: '/repo/app', - connectionId: null, - repo: null, - folderWorkspace: null - }) - const getForegroundProcess = vi.fn(async () => foregroundProcess) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: PTY_ID, incarnationId: 'initial-incarnation' }), - write: () => true, - kill: () => true, - getForegroundProcess - }) - const terminal = await runtime.createTerminal(`id:${WORKTREE_ID}`, { - tabId: TAB_ID, - leafId: LEAF_ID, - title: 'Terminal', - ...(launchAgent - ? { - launchAgent, - ...(verifiedLaunch - ? { launchConfig: { agentCommand: 'claude', agentArgs: '', agentEnv: {} } } - : {}) - } - : {}) - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - leafId: LEAF_ID, - paneRuntimeId: 1, - ptyId: PTY_ID, - paneTitle - } - ] - }) - return { runtime, handle: terminal.handle, getForegroundProcess } -} - -const AUTHORIZED = 'authorized' - -// The 150ms foreground tick first crosses its unchanged 6,500ms budget at 6,600ms. -const WRAPPER_REJECTION_TICK_MS = 6_600 -const NO_AGENT_GUARD_DEADLINE_MS = 1_050 - -async function readAgentEvidenceAtDeadline( - read: () => Promise, - deadlineMs: number -): Promise { - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - try { - let settled = false - const result = read() - void result.then( - () => { - settled = true - }, - () => { - settled = true - } - ) - await vi.advanceTimersByTimeAsync(deadlineMs - 1) - expect(settled, 'agent evidence settled before its deadline').toBe(false) - await vi.advanceTimersByTimeAsync(1) - expect(settled, 'agent evidence did not settle at its deadline').toBe(true) - expect(vi.getTimerCount()).toBe(0) - return await result - } finally { - try { - await vi.runOnlyPendingTimersAsync() - } finally { - vi.clearAllTimers() - vi.useRealTimers() - } - } -} - -async function guardedSendResult(runtime: OrcaRuntimeService, handle: string): Promise { - try { - await assertTerminalAgentSendable({ runtime, handle, assertWritable: () => {} }) - return AUTHORIZED - } catch (error) { - return error instanceof Error ? error.message : String(error) - } -} - -describe('quarter-circle title send authorization (STA-4028)', () => { - it('refuses a guarded send when a quarter-circle spinner is the only agent evidence', async () => { - const { runtime, handle } = await createRuntimeWithTitle(SPINNER_ONLY_TITLE, 'node') - - expect( - await readAgentEvidenceAtDeadline( - () => runtime.getTerminalAgentStatus(handle), - WRAPPER_REJECTION_TICK_MS - ) - ).toMatchObject({ isRunningAgent: false }) - expect( - await readAgentEvidenceAtDeadline( - () => guardedSendResult(runtime, handle), - WRAPPER_REJECTION_TICK_MS - ) - ).toBe('terminal_guard_no_agent') - }) - - it('refuses a guarded send when the foreground process cannot be read at all', async () => { - // SSH/folder foreground lookup can fail; missing evidence must refuse rather than trust a glyph. - const { runtime, handle } = await createRuntimeWithTitle(SPINNER_ONLY_TITLE, null) - - expect( - await readAgentEvidenceAtDeadline( - () => guardedSendResult(runtime, handle), - NO_AGENT_GUARD_DEADLINE_MS - ) - ).toBe('terminal_guard_no_agent') - }) - - it('authorizes a managed Claude launch when the foreground process is unavailable', async () => { - const { runtime, handle, getForegroundProcess } = await createRuntimeWithTitle( - SPINNER_ONLY_TITLE, - null, - 'claude' - ) - expect( - ( - runtime as unknown as { - ptysById: Map - } - ).ptysById.get(PTY_ID) - ).toMatchObject({ launchAgent: 'claude', launchToken: expect.any(String) }) - - await expect(runtime.getTerminalAgentStatus(handle)).resolves.toMatchObject({ - isRunningAgent: true, - status: 'working' - }) - await expect(guardedSendResult(runtime, handle)).resolves.toBe(AUTHORIZED) - expect(getForegroundProcess).not.toHaveBeenCalled() - }) - - it('does not trust an unverified Claude launch hint', async () => { - const { runtime, handle } = await createRuntimeWithTitle( - SPINNER_ONLY_TITLE, - null, - 'claude', - false - ) - - expect( - await readAgentEvidenceAtDeadline( - () => guardedSendResult(runtime, handle), - NO_AGENT_GUARD_DEADLINE_MS - ) - ).toBe('terminal_guard_no_agent') - }) - - it('does not carry managed Claude identity into a replacement PTY incarnation', async () => { - const { runtime, handle } = await createRuntimeWithTitle(SPINNER_ONLY_TITLE, null, 'claude') - const pty = ( - runtime as unknown as { - ptysById: Map< - string, - { incarnationId: string | null; launchIncarnationId: string | null; launchToken: string } - > - } - ).ptysById.get(PTY_ID) - expect(pty).toMatchObject({ - incarnationId: 'initial-incarnation', - launchIncarnationId: 'initial-incarnation' - }) - - runtime.onPtySpawned(PTY_ID, 'replacement-incarnation', { awaitsRegistration: false }) - - expect(pty).toMatchObject({ - incarnationId: 'replacement-incarnation', - launchIncarnationId: 'initial-incarnation', - launchToken: expect.any(String) - }) - await expect(runtime.getTerminalAgentStatus(handle)).rejects.toThrow('terminal_handle_stale') - - runtime.registerPty(PTY_ID, WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: 'replacement-incarnation' - }) - const replacementHandle = runtime.getTerminalHandleForPaneKey(`${TAB_ID}:${LEAF_ID}`) - if (replacementHandle === null) { - throw new Error('replacement terminal handle was not registered') - } - expect(replacementHandle).not.toBe(handle) - await expect(runtime.getTerminalAgentStatus(replacementHandle)).resolves.toMatchObject({ - isRunningAgent: false - }) - expect( - await readAgentEvidenceAtDeadline( - () => guardedSendResult(runtime, replacementHandle), - NO_AGENT_GUARD_DEADLINE_MS - ) - ).toBe('terminal_guard_no_agent') - }) -}) diff --git a/src/main/runtime/terminal/identity/runtime-terminal-pane-identity.ts b/src/main/runtime/terminal/identity/runtime-terminal-pane-identity.ts index 1352a8d0ad2..b41c3c2e3a4 100644 --- a/src/main/runtime/terminal/identity/runtime-terminal-pane-identity.ts +++ b/src/main/runtime/terminal/identity/runtime-terminal-pane-identity.ts @@ -5,7 +5,7 @@ import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { isValidHostTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidHostTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { randomUUID } from 'node:crypto' export function allocateTerminalPaneIdentity(opts: { tabId?: string; leafId?: string }): { diff --git a/src/main/runtime/terminal/input/terminal-command-paint.ts b/src/main/runtime/terminal/input/terminal-command-paint.ts index 113357a01b4..aa5282d9868 100644 --- a/src/main/runtime/terminal/input/terminal-command-paint.ts +++ b/src/main/runtime/terminal/input/terminal-command-paint.ts @@ -1,5 +1,16 @@ import { stripAnsiEscapeSequences } from '../../../../shared/ansi-escape-sequences' import { createOsc133CommandFinishedScanner } from '../../../../shared/terminal/output/terminal-osc133-command-finished' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { + DraftPasteMarkerSignal, + TuiAgentConfig +} from '../../../../shared/agent-launch/catalog/tui-agent-config-types' +import { TUI_AGENT_CONFIG } from '../../../../shared/agent-launch/catalog/tui-agent-config' +import { + createDraftPasteReadyScanner, + draftPasteReadySignalHasMarker, + type DraftPasteReadyScanner +} from '../../../../shared/draft-paste-ready-scanner' import { normalizeTerminalChunk } from '../output/terminal-ansi-normalization' // eslint-disable-next-line no-control-regex -- control bytes are exactly what is not visible. @@ -9,10 +20,47 @@ function hasVisibleText(normalizedText: string): boolean { return VISIBLE_CHARACTER_RE.test(stripAnsiEscapeSequences(normalizedText)) } +/** + * The composer marker that says this agent's command painted, for agents whose bare-name title + * is weak and whose composer draws a marker only the agent emits (Claude: `❯`+NBSP after + * DECSET 2031, which no shell sends). Why not any visible byte: Orca's zsh OSC 133;C hook runs + * first in `preexec_functions`, so a later user or framework preexec hook can print before the + * agent process exists, and a cold-starting agent can print a banner long before its composer + * (STA-2380). Null for agents whose name-only idle keeps any post-marker paint as corroboration. + */ +function paintSignalOf(config: TuiAgentConfig): DraftPasteMarkerSignal | null { + const signal = config.draftPasteReadySignal + return config.workerStartReadsComposerMarker === true && + signal !== undefined && + draftPasteReadySignalHasMarker(signal) + ? signal + : null +} + +export function agentPaintSignal( + agent: TuiAgent | null | undefined +): DraftPasteMarkerSignal | null { + return agent ? paintSignalOf(TUI_AGENT_CONFIG[agent]) : null +} + +/** One scanner per distinct agent-owned marker, so every PTY attributes paint the same way. */ +const AGENT_PAINT_SIGNALS: readonly DraftPasteMarkerSignal[] = [ + ...new Set( + Object.values(TUI_AGENT_CONFIG) + .map(paintSignalOf) + .filter((signal): signal is DraftPasteMarkerSignal => signal !== null) + ) +] + /** OSC 133;C follows the prompt/echo; only visible bytes after it prove the running command painted. */ export class TerminalCommandPaint { private awaitingPaint = false private markerEndInChunk = -1 + /** Armed at each command start; absent before the first marker, where no command is attributable. */ + private composers: Map< + DraftPasteMarkerSignal, + { scanner: DraftPasteReadyScanner; seen: boolean } + > | null = null private readonly scanner = createOsc133CommandFinishedScanner( () => {}, (endInChunk) => { @@ -25,19 +73,42 @@ export class TerminalCommandPaint { this.scanner.scan(data) if (this.markerEndInChunk !== -1) { // Why the rest of this chunk counts: a fast binary can paint in the same read as the marker. - this.awaitingPaint = !hasVisibleText( - normalizeTerminalChunk(data.slice(this.markerEndInChunk)).text + const commandOutput = data.slice(this.markerEndInChunk) + this.awaitingPaint = !hasVisibleText(normalizeTerminalChunk(commandOutput).text) + this.composers = new Map( + AGENT_PAINT_SIGNALS.map((signal) => [ + signal, + { scanner: createDraftPasteReadyScanner(signal), seen: false } + ]) ) + this.observeComposers(commandOutput) return } if (this.awaitingPaint && hasVisibleText(normalizedText)) { this.awaitingPaint = false } + this.observeComposers(data) + } + + private observeComposers(data: string): void { + if (!this.composers || data.length === 0) { + return + } + for (const composer of this.composers.values()) { + if (!composer.seen && composer.scanner.observe(data).ready) { + composer.seen = true + } + } } hasPainted(): boolean { return !this.awaitingPaint } + + /** Whether the agent's own composer marker has arrived since the command started; true before any marker, like paint. */ + hasAgentComposer(signal: DraftPasteMarkerSignal): boolean { + return this.composers === null || (this.composers.get(signal)?.seen ?? false) + } } export type TerminalCommandPaintRecord = { commandPaint?: TerminalCommandPaint } @@ -56,3 +127,26 @@ export function observeTerminalCommandPaint( export function hasTerminalCommandPainted(record: TerminalCommandPaintRecord): boolean { return record.commandPaint?.hasPainted() ?? true } + +/** Whether `agent`'s command painted: its own composer marker where it has one, else any visible + * post-marker byte. Shares the markerless and lost-history defaults of `hasTerminalCommandPainted`. + * + * Accepted trade-off (STA-2380 C2): a known Claude whose command-start history is complete but + * whose build or platform never sends the supported composer signal (`❯`+NBSP after DECSET 2031; + * the scanner's quiet fallback is deliberately not read here), and whose `✳` rest title is also + * off, now stays pending until the wait's own timeout instead of settling on quiet. There is no + * silence-only fallback by design: silence under a shell auto-title was the false-ready bug, and + * a reported timeout is recoverable where a lost dispatch is not. The marker has been seen in + * captures from 2.1.291 through 2.1.316; no older-version cutoff is claimed. Unchanged and still + * failing open: shells that send no OSC 133;C marker and panes whose output history has a gap + * report "painted" (the pre-existing `?? true`), so this does not prevent every premature ready. */ +export function hasTerminalAgentPainted( + record: TerminalCommandPaintRecord, + agent: TuiAgent | null | undefined +): boolean { + const signal = agentPaintSignal(agent) + if (signal === null) { + return hasTerminalCommandPainted(record) + } + return record.commandPaint?.hasAgentComposer(signal) ?? true +} diff --git a/src/main/runtime/terminal/input/terminal-plugin-hooked-input.ts b/src/main/runtime/terminal/input/terminal-plugin-hooked-input.ts index 57590e3da0e..f24506fa874 100644 --- a/src/main/runtime/terminal/input/terminal-plugin-hooked-input.ts +++ b/src/main/runtime/terminal/input/terminal-plugin-hooked-input.ts @@ -1,5 +1,5 @@ import type { RuntimeTerminalSend } from '../../../../shared/runtime-terminal-send-contract' -import { assertLegacyAiVaultResumeCommandAllowed } from '../../../ai-vault/structured-session-ownership' +import { assertLegacyAiVaultResumeCommandAllowed } from '../../../ai-vault/structured-sessions/structured-session-ownership' import type { RuntimeTerminalWriteOptions } from './runtime-terminal-writer' import { OrcaRuntimeWithControllerKnowsPtyIsLive } from './terminal-input-dispatch' import type { RuntimeAgentPromptWriteOptions } from './agent-prompt-write-options' diff --git a/src/main/runtime/terminal/launch/mobile-terminal-chat-fork-create.ts b/src/main/runtime/terminal/launch/mobile-terminal-chat-fork-create.ts index eba069639dd..63a4efaff68 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-chat-fork-create.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-chat-fork-create.ts @@ -8,19 +8,19 @@ import type { RuntimeMobileSessionCreateTerminalResult } from '../../../../share import { prepareStructuredChatCliFork, isStructuredChatCliForkSourceCurrent -} from '../../../ai-vault/structured-chat-cli-fork' +} from '../../../ai-vault/structured-sessions/structured-chat-cli-fork' import { buildMobileTerminalChatFork } from './mobile-terminal-chat-fork' import { isWslUncPath } from '../../../../shared/wsl-paths' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import { applyRemoteViewerLaunchEnv } from './remote-viewer-launch-env' import { deterministicAgentSessionUuid } from './runtime-agent-launch-resolution' -import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' +import { rendererPublicationThrottle } from '../../../window/visibility/renderer-publication-throttle' import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../../shared/project-runtime-repair-message' import { OrchestrationError } from '../../orchestration/orchestration-error' import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { loadWorkspaceLayoutWithoutReport } from '../../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../../shared/workspace-layout/workspace-layout-minted-ids' +import { loadWorkspaceLayoutWithoutReport } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import { resolveSessionTabRow } from '../../../../shared/workspace-layout/old-client/old-client-session-tab-rows' function resolveSavedChatForkAnchor( diff --git a/src/main/runtime/terminal/launch/mobile-terminal-chat-fork.test.ts b/src/main/runtime/terminal/launch/mobile-terminal-chat-fork.test.ts deleted file mode 100644 index db104413939..00000000000 --- a/src/main/runtime/terminal/launch/mobile-terminal-chat-fork.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { expect, it, vi } from 'vitest' -import type { RuntimeNotifier } from '../../client/events/runtime-notifier-contract' -import './mobile-terminal-chat-fork' -import { prepareStructuredChatCliFork } from '../../../ai-vault/structured-chat-cli-fork' -import '../../orchestration/orchestration-error' -import '../../../../shared/project-runtime-repair-message' -import '../../orca-runtime-tests/orca-runtime-test-lifecycle.spec' -import { committingSpawn } from '../../orca-runtime-tests/bind-first-pane.test-fixture' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { structuredAgentSessionTabId } from '../../../../shared/agent-session/view/structured-agent-session-projection' -vi.mock('../../../ai-vault/structured-chat-cli-fork', () => ({ - prepareStructuredChatCliFork: vi.fn(), - isStructuredChatCliForkSourceCurrent: vi.fn(() => true) -})) -const cwd = process.platform === 'win32' ? 'C:\\repo' : '/tmp/repo' -const filePath = process.platform === 'win32' ? 'C:\\sessions\\chat.jsonl' : '/tmp/chat.jsonl' - -it.each([true, false])( - 'forks a source-selected chat with saved placement available: %s', - async (saved) => { - await import('../../orca-runtime-tests/runtime-test-module-registration.spec') - const { OrcaRuntimeService } = await import('../../orca-runtime') - const { electronMocks } = await import('../../orca-runtime-test-mocks/setup.spec') - const { - TEST_WORKTREE_ID: wt, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal - } = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - const { withChatTabChanges } = await import('../../agent-session/agent-session-tab-layout') - const source = 'source-chat', - row = `agent-session:${source}`, - canonical = 'custom-chat-tab' - const initial = makeWorkspaceSessionWithHeadlessTerminal() - const session = - withChatTabChanges('local', initial, wt, [ - { open: { sessionId: source, agent: 'claude', tabId: canonical } } - ]) ?? initial - const group = session.tabGroups?.[wt]?.[0] - if (!group) { - throw new Error('Missing saved group') - } - group.tabOrder = [canonical, 'host-tab'] - const fixture = makeRuntimeStoreWithWorkspaceSession(saved ? session : initial) - const admit = vi.spyOn(fixture.runtimeStore, 'admitTerminalPane') - const service = new OrcaRuntimeService(fixture.runtimeStore) - const spawn = vi.fn( - async (_options: { worktreeId?: string; tabId?: string; leafId?: string }) => ({ - id: 'pty-fork', - incarnationId: '45454545-4545-4545-8545-454545454545' - }) - ) - service.setPtyController({ - spawn: committingSpawn(service, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - electronMocks.BrowserWindow.fromId.mockReturnValue({ - isDestroyed: () => false, - webContents: { - isDestroyed: () => false, - setBackgroundThrottling: vi.fn(), - capturePage: async () => undefined - } - }) - service.attachWindow(1) - service.syncWindowGraph(1, { tabs: [], leaves: [] }) - const { createMobileCreateTestNotifier } = - await import('../../orca-runtime-tests/orca-runtime-test-scenario-builders.spec') - const reveal = vi.fn>( - (_worktree, opts) => { - if (!opts.tabId || !opts.leafId) { - throw new Error('Missing revealed pane') - } - return { - tabId: opts.tabId, - identity: { - worktreeId: wt, - tabId: opts.tabId, - leafId: opts.leafId, - ptyId: opts.ptyId - } - } - } - ) - service.setNotifier({ - ...createMobileCreateTestNotifier(vi.fn()), - revealTerminalSession: reveal - }) - vi.spyOn(service, 'ensureStructuredAgentSessionHost').mockResolvedValue(undefined) - await service.publishStructuredAgentSessionTab({ - workspaceId: wt, - sessionId: source, - agent: 'claude', - activate: true - }) - vi.mocked(prepareStructuredChatCliFork).mockResolvedValue({ - useRealCodexHome: false, - cliForkSource: { - agent: 'claude', - sourceAgent: 'claude', - sessionId: source, - filePath, - cwd, - codexHome: null, - executionHostPlatform: process.platform - } - }) - const created = await service.createMobileSessionTerminal(`id:${wt}`, { - sourceChatFork: { sessionId: source }, - afterTabId: row, - clientMutationId: 'fork', - navigation: 'caller', - clientNavigationId: 'phone', - supportsSplitGroupPlacement: true - }) - expect(spawn).toHaveBeenCalledOnce() - expect(spawn.mock.calls[0]?.[0]).toEqual( - expect.objectContaining({ - command: expect.stringContaining(source) - }) - ) - expect(admit).toHaveBeenCalledOnce() - expect(admit.mock.calls[0]?.[0]).toMatchObject({ - type: 'createTerminalTab', - tabId: created.tab.parentTabId, - ...(saved ? { afterTabId: canonical, groupId: group.id } : {}) - }) - expect(admit.mock.calls[0]?.[0]).not.toMatchObject({ afterTabId: row }) - expect(reveal).toHaveBeenCalledWith( - wt, - expect.objectContaining({ - tabId: created.tab.parentTabId, - leafId: created.tab.leafId, - ptyId: created.tab.ptyId, - activate: false, - focus: false, - presentation: 'background', - surfaceOwner: false, - ...(saved ? { afterTabId: canonical, targetGroupId: group.id } : {}) - }) - ) - if (saved) { - expect( - fixture.getSession().tabGroups?.[wt]?.find((entry) => entry.id === group.id)?.tabOrder - ).toEqual([canonical, created.tab.parentTabId, 'host-tab']) - expect(fixture.getSession().unifiedTabs?.[wt]).toEqual( - expect.arrayContaining([expect.objectContaining({ id: canonical, entityId: source })]) - ) - } else if (ORCA_LAYOUT_OWNER_IS_MAIN) { - expect(admit.mock.calls[0]?.[0]).toMatchObject({ - afterTabId: structuredAgentSessionTabId(source) - }) - } else { - expect(admit.mock.calls[0]?.[0]).not.toHaveProperty('afterTabId') - expect(reveal.mock.calls[0]?.[1]).not.toHaveProperty('afterTabId') - expect(reveal.mock.calls[0]?.[1]).not.toHaveProperty('targetGroupId') - } - expect((await service.listMobileSessionTabs(`id:${wt}`)).tabs).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: 'agent-session', id: row, sessionId: source }) - ]) - ) - } -) diff --git a/src/main/runtime/terminal/launch/mobile-terminal-create.ts b/src/main/runtime/terminal/launch/mobile-terminal-create.ts index 236ad728edd..98e993a2504 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-create.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-create.ts @@ -1,6 +1,6 @@ import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from '../../session-tabs/session-tabs-change-publication' import { OrcaRuntimeWithFailedStartPanes } from './failed-start-pane' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { AgentProviderSessionMetadata, diff --git a/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts b/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts index 5f2c779aee6..f657a5f947f 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts @@ -14,7 +14,7 @@ import { deriveRemoteRuntimeTerminalCreateHandle } from '../identity/remote-runt import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { mintServePtySessionId } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' import { placeCreatedSessionTab } from '../../../../shared/session-tab-placement' -import { insertTabIdIntoOrder } from '../../../../shared/workspace-layout/tab-order' +import { insertTabIdIntoOrder } from '../../../../shared/workspace-layout/tab-groups/tab-order' import type { OrcaRuntimeWithBuildPtyTerminalSummary as PtyTerminalSummaryMethods } from '../query/pty-terminal-summary' import { buildHeadlessMobileSessionTabGroups, diff --git a/src/main/runtime/terminal/launch/mobile-terminal-renderer-create.ts b/src/main/runtime/terminal/launch/mobile-terminal-renderer-create.ts index f79c0bc11ee..81c59d9b381 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-renderer-create.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-renderer-create.ts @@ -12,7 +12,7 @@ import { MOBILE_TERMINAL_SURFACE_TIMEOUT_MS } from '../view/terminal-surface-deadlines' import { isClientDisconnectedError } from '../../client/runtime-client-disconnect' -import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' +import { rendererPublicationThrottle } from '../../../window/visibility/renderer-publication-throttle' import { deterministicAgentSessionUuid } from './runtime-agent-launch-resolution' import { assertMobileTerminalShellSupported } from './mobile-terminal-shell-refusal' import { anchorTabOfCreate, mainPlacedAfter } from './mobile-terminal-create-anchor' diff --git a/src/main/runtime/terminal/launch/mobile-terminal-startup.ts b/src/main/runtime/terminal/launch/mobile-terminal-startup.ts index b9d77875ad8..552c249d7f5 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-startup.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-startup.ts @@ -1,6 +1,6 @@ import { OrcaRuntimeWithRunCreateMobileSessionTerminal } from './mobile-terminal-renderer-create' import type { TerminalWorkspaceLaunchScope } from '../../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import { isResumableTuiAgent, diff --git a/src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts b/src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts index 3ee250e4a6a..a7311db7968 100644 --- a/src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts +++ b/src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' import { describe, expect, it, vi } from 'vitest' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' import { setupLayoutOwnerRuntime, WORKTREE_ID diff --git a/src/main/runtime/terminal/launch/runtime-pane-admission.ts b/src/main/runtime/terminal/launch/runtime-pane-admission.ts index d6228a06ba2..9f9cc3d102a 100644 --- a/src/main/runtime/terminal/launch/runtime-pane-admission.ts +++ b/src/main/runtime/terminal/launch/runtime-pane-admission.ts @@ -5,15 +5,15 @@ import { normalizeExecutionHostId, toSshExecutionHostId } from '../../../../shared/execution-host' -import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import type { TerminalPaneAdmission, TerminalPaneAdmissionOutcome -} from '../../../persistence/terminal-topology/terminal-pane-admission' +} from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { LayoutRefusalCode } from '../../../../shared/workspace-layout/workspace-layout-command-types' import type { RuntimePtyController } from '../lifecycle/runtime-pty-controller-contract' import type { RuntimeStore } from '../../construction/runtime-store-contract' -import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import { paneStartFailure, type PaneResumeOutcomes, diff --git a/src/main/runtime/terminal/launch/terminal-create-options.ts b/src/main/runtime/terminal/launch/terminal-create-options.ts index ba4cf6a41d1..e9e8f4e29e9 100644 --- a/src/main/runtime/terminal/launch/terminal-create-options.ts +++ b/src/main/runtime/terminal/launch/terminal-create-options.ts @@ -1,4 +1,4 @@ -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { AgentProviderSessionMetadata, SleepingAgentLaunchConfig diff --git a/src/main/runtime/terminal/launch/terminal-pty-exit-waiter.spec.ts b/src/main/runtime/terminal/launch/terminal-pty-exit-waiter.spec.ts index 2fee34fc5a6..3d397a1750f 100644 --- a/src/main/runtime/terminal/launch/terminal-pty-exit-waiter.spec.ts +++ b/src/main/runtime/terminal/launch/terminal-pty-exit-waiter.spec.ts @@ -11,7 +11,7 @@ import { waitForWorkerAgentReady } from '../wait/launched-agent-composer-readine export function registerTerminalPtyExitWaiterTests(): void { describe('idle and fresh readiness waits on an exited terminal', () => { it.each( - (['pi', 'claude', 'codex', 'opencode'] as const).flatMap((agent) => + (['pi', 'claude', 'opencode'] as const).flatMap((agent) => [true, false].map((exitBeforeWait) => ({ agent, exitBeforeWait })) ) )( diff --git a/src/main/runtime/terminal/launch/terminal-split-in-main.ts b/src/main/runtime/terminal/launch/terminal-split-in-main.ts index c4bb3129b04..0b011c412f2 100644 --- a/src/main/runtime/terminal/launch/terminal-split-in-main.ts +++ b/src/main/runtime/terminal/launch/terminal-split-in-main.ts @@ -13,7 +13,7 @@ import { resolvePtyFirstSize, type PtyGridSize } from '../../../ipc/pty/pty-firs import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { randomUUID } from 'node:crypto' import { paneStartFailure } from '../surface/pane-start-statuses' -import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { recordFreshLaunch } from './launch-evidence' export type SplitPaneSource = { worktreeId: string; tabId: string; leafId: string } diff --git a/src/main/runtime/terminal/launch/terminal-split-layout-owner.test.ts b/src/main/runtime/terminal/launch/terminal-split-layout-owner.test.ts deleted file mode 100644 index 48dbb0fa884..00000000000 --- a/src/main/runtime/terminal/launch/terminal-split-layout-owner.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import '../../orca-runtime-tests/runtime-test-module-registration.spec' -import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} from '../../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { createMobileCreateTestNotifier } from '../../orca-runtime-tests/orca-runtime-test-scenario-builders.spec' -import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' -import { ProvisioningRuntime } from '../../orca-runtime-tests/orca-runtime-layout-owner-start-fixture' -import { - committingSpawn, - registerBoundPty -} from '../../orca-runtime-tests/bind-first-pane.test-fixture' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const TAB_ID = 'host-tab' -const NEW_LEAF_ID = '22222222-2222-4222-8222-222222222222' - -function graph() { - return { - tabs: [ - { - tabId: TAB_ID, - worktreeId: TEST_WORKTREE_ID, - title: 'shell', - activeLeafId: HEADLESS_LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: TAB_ID, - worktreeId: TEST_WORKTREE_ID, - leafId: HEADLESS_LEAF_ID, - paneRuntimeId: 1, - ptyId: 'pty-0', - paneTitle: null - } - ] - } -} - -describe('a split of a pane the window draws, in a layout-owner build', () => { - function setup() { - const store = makeRuntimeStoreWithWorkspaceSession(makeWorkspaceSessionWithHeadlessTerminal()) - const notifier = { ...createMobileCreateTestNotifier(vi.fn()), closeTerminalPane: vi.fn() } - const runtime = new ProvisioningRuntime(store.runtimeStore) - runtime.setNotifier(notifier) - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: TEST_WORKTREE_ID, - path: TEST_WORKTREE_PATH, - connectionId: null, - repo: null, - folderWorkspace: null - })) - }) - const statusesSeen: unknown[] = [] - const spawn = vi.fn(async (args: { worktreeId?: string; tabId?: string; leafId?: string }) => { - statusesSeen.push(runtime.startStatusOf(`${args.tabId}:${args.leafId}`)) - return { id: `pty-split-${spawn.mock.calls.length}` } - }) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - getCwd: async () => '/repo/src' - }) - // The source pane's terminal runs, bound in main's layout as its spawn commit left it. - registerBoundPty(runtime, 'pty-0', TEST_WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: HEADLESS_LEAF_ID - }) - runtime.syncWindowGraph(1, graph()) - const handle = runtime.getTerminalHandleForPaneKey(makePaneKey(TAB_ID, HEADLESS_LEAF_ID)) - const leafIds = () => - collectLayoutLeafIdsInOrder(store.getSession().terminalLayoutsByTabId[TAB_ID]!.root!) - return { - ...store, - notifier, - runtime, - spawn, - statusesSeen, - handle: handle!, - splitTerminal: vi.mocked(notifier.splitTerminal), - leafIds - } - } - - it('main writes the pane and starts its terminal there, in the source pane’s folder; the window is not asked', async () => { - const { runtime, handle, splitTerminal, leafIds, spawn, statusesSeen } = setup() - - const split = await runtime.splitTerminal(handle, { - direction: 'vertical', - command: 'make test' - }) - - expect(splitTerminal).not.toHaveBeenCalled() - expect(leafIds()).toEqual([HEADLESS_LEAF_ID, split.leafId]) - expect(spawn).toHaveBeenCalledTimes(1) - expect(spawn.mock.calls[0]![0]).toMatchObject({ - tabId: TAB_ID, - leafId: split.leafId, - cwd: '/repo/src', - resolvedWorkspace: { - id: TEST_WORKTREE_ID, - path: TEST_WORKTREE_PATH, - connectionId: null, - repo: null, - folderWorkspace: null - }, - command: 'make test', - cols: 120, - rows: 40 - }) - // Publish starting status to prevent views spawning duplicates, then clear it after binding. - expect(statusesSeen).toEqual([{ status: 'starting' }]) - expect(runtime.startStatusOf(makePaneKey(TAB_ID, split.leafId ?? ''))).toBeNull() - expect(split.tabId).toBe(TAB_ID) - }) - - it('a split no one asked to see leaves the phones’ active tab alone; one asked for takes it', async () => { - const { runtime, handle } = setup() - const listed = () => runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - const before = (await listed()).activeTabId - - await runtime.splitTerminal(handle, { direction: 'vertical', activate: false }) - expect((await listed()).activeTabId).toBe(before) - - const shown = await runtime.splitTerminal(handle, { direction: 'horizontal' }) - expect((await listed()).activeTabId).toBe(`${TAB_ID}::${shown.leafId}`) - }) - - it('a window split whose terminal fails to start keeps its pane, showing why', async () => { - const { runtime, leafIds, spawn } = setup() - spawn.mockRejectedValueOnce(new Error('shell not found')) - - await expect( - runtime.splitTerminalPane( - { worktreeId: TEST_WORKTREE_ID, tabId: TAB_ID, leafId: HEADLESS_LEAF_ID }, - { direction: 'vertical', newLeafId: NEW_LEAF_ID, keepPaneOnStartFailure: true } - ) - ).rejects.toThrow('shell not found') - - expect(leafIds()).toEqual([HEADLESS_LEAF_ID, NEW_LEAF_ID]) - expect(runtime.startStatusOf(makePaneKey(TAB_ID, NEW_LEAF_ID))).toEqual({ - status: 'failed', - reason: 'shell not found' - }) - }) - - it('a CLI split whose terminal fails to start leaves no pane, and the CLI hears why', async () => { - const { runtime, handle, leafIds, spawn, notifier } = setup() - spawn.mockRejectedValueOnce(new Error('shell not found')) - - await expect(runtime.splitTerminal(handle, { direction: 'vertical' })).rejects.toThrow( - 'shell not found' - ) - - expect(leafIds()).toEqual([HEADLESS_LEAF_ID]) - expect(notifier.closeTerminalPane).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/terminal/launch/terminal-split-retry.test.ts b/src/main/runtime/terminal/launch/terminal-split-retry.test.ts deleted file mode 100644 index ce6fd7f9e9e..00000000000 --- a/src/main/runtime/terminal/launch/terminal-split-retry.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../orca-runtime' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { TerminalSplitOutcomeError } from '../../../../shared/workspace-layout/terminal-split-outcome' - -const WORKTREE_ID = 'repo-1::/workspace' -const TAB_ID = 'tab-1' -const SOURCE_LEAF_ID = '11111111-1111-4111-8111-111111111111' - -type Leaf = { leafId: string; paneRuntimeId: number; ptyId: string | null } - -function createHarness() { - const rendererSplitTerminal = vi.fn() - const runtime = new OrcaRuntimeService() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the split path calls only splitTerminal on the notifier. - runtime.setNotifier({ splitTerminal: rendererSplitTerminal } as never) - const publish = (extra: Leaf[] = []): void => { - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: SOURCE_LEAF_ID, - layout: { type: 'leaf', leafId: SOURCE_LEAF_ID } - } - ], - leaves: [{ leafId: SOURCE_LEAF_ID, paneRuntimeId: 1, ptyId: 'pty-source' }, ...extra].map( - (leaf) => ({ tabId: TAB_ID, worktreeId: WORKTREE_ID, ...leaf }) - ) - }) - } - publish() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: issueHandle and leaves are protected; the test issues the source handle as a graph reader would. - const internals = runtime as unknown as { - issueHandle: (leaf: unknown) => string - leaves: Map - } - const handle = internals.issueHandle([...internals.leaves.values()][0]) - return { runtime, handle, rendererSplitTerminal, publish } -} - -async function timedOutSplit(harness: ReturnType): Promise<{ - error: TerminalSplitOutcomeError - leafId: string -}> { - const split = harness.runtime - .splitTerminal(harness.handle, { command: 'agent --task 1' }) - .catch((error: unknown) => error) - await vi.advanceTimersByTimeAsync(10_000) - const error = await split - if (!(error instanceof TerminalSplitOutcomeError)) { - throw new Error(`expected a pending split, got ${String(error)}`) - } - return { error, leafId: error.data.splitId } -} - -describe.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)( - 'window-made split that outlives its wait (#32169)', - () => { - beforeEach(() => { - vi.useFakeTimers() - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('keeps waiting for a pane the window already listed while its terminal starts', async () => { - const harness = createHarness() - const split = harness.runtime.splitTerminal(harness.handle, { command: 'agent' }) - const leafId = harness.rendererSplitTerminal.mock.calls[0]?.[2]?.newLeafId - harness.publish([{ leafId, paneRuntimeId: 2, ptyId: null }]) - await vi.advanceTimersByTimeAsync(15_000) - harness.publish([{ leafId, paneRuntimeId: 2, ptyId: 'pty-late' }]) - - await expect(split).resolves.toMatchObject({ - leafId, - handle: expect.stringMatching(/^term_/) - }) - }) - - it('a retry returns the late pane without asking the window to split again', async () => { - const harness = createHarness() - const { leafId } = await timedOutSplit(harness) - harness.publish([{ leafId, paneRuntimeId: 2, ptyId: 'pty-late' }]) - - await expect( - harness.runtime.splitTerminal(harness.handle, { retrySplit: leafId }) - ).resolves.toMatchObject({ leafId, tabId: TAB_ID }) - expect(harness.rendererSplitTerminal).toHaveBeenCalledTimes(1) - }) - - it('a retry before the pane appears waits for it without asking the window again', async () => { - const harness = createHarness() - const { leafId } = await timedOutSplit(harness) - - const retry = harness.runtime.splitTerminal(harness.handle, { retrySplit: leafId }) - harness.publish([{ leafId, paneRuntimeId: 2, ptyId: 'pty-late' }]) - - await expect(retry).resolves.toMatchObject({ leafId }) - expect(harness.rendererSplitTerminal).toHaveBeenCalledTimes(1) - }) - - it('a retry for a pane missing from the graph answers pending, never splitting again', async () => { - const harness = createHarness() - const { leafId } = await timedOutSplit(harness) - harness.publish([{ leafId, paneRuntimeId: 2, ptyId: null }]) - // Absent again: closed or remounting, main cannot tell, so it must not claim either. - harness.publish() - - const retry = harness.runtime - .splitTerminal(harness.handle, { retrySplit: leafId }) - .catch((error: unknown) => error) - await vi.advanceTimersByTimeAsync(10_000) - - await expect(retry).resolves.toMatchObject({ - data: { splitId: leafId, splitMayStillComplete: true } - }) - await expect( - harness.runtime.splitTerminal(harness.handle, { - retrySplit: '22222222-2222-4222-8222-222222222222' - }) - ).rejects.toThrow('no record of split') - expect(harness.rendererSplitTerminal).toHaveBeenCalledTimes(1) - }) - } -) diff --git a/src/main/runtime/terminal/launch/terminal-split-retry.ts b/src/main/runtime/terminal/launch/terminal-split-retry.ts index dd76d6cf6d3..8b07e5d9c1b 100644 --- a/src/main/runtime/terminal/launch/terminal-split-retry.ts +++ b/src/main/runtime/terminal/launch/terminal-split-retry.ts @@ -1,5 +1,5 @@ import { BoundedMap } from '../../../../shared/bounded-map' -import { TerminalSplitOutcomeError } from '../../../../shared/workspace-layout/terminal-split-outcome' +import { TerminalSplitOutcomeError } from '../../../../shared/workspace-layout/terminal-topology/terminal-split-outcome' import { SPLIT_PANE_WAIT_TIMEOUT_MESSAGE } from './terminal-split-wait-timeout' /** Where main asked the window to split; a retry answers from it without asking again. */ diff --git a/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts b/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts index 4727d394799..6b64e967fa8 100644 --- a/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts +++ b/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts @@ -5,17 +5,16 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status/contracts/agent-status-types' + import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import type { WorkspaceLayoutStreamEvent } from '../../../../shared/workspace-layout/workspace-layout-stream-frames' + import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, - FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as GIT, openTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ @@ -71,32 +70,7 @@ function status(workspace: string, overrides: Partial = { } satisfies AgentStatusIpcPayload } -const dispatch = (taskId: string, task: string) => - `You are working inside Orca, a multi-agent IDE. You are a dispatched worker. -Your task ID is: ${taskId} - -=== TASK === -${task}` - describe('main titles agent tabs from its own hook status', () => { - it('gives a batch’s titles of several workspaces in one rename and one frame', async () => { - const { runtime, apply, titleOf } = await hostWith([GIT, FOLDER]) - const frames: WorkspaceLayoutStreamEvent[] = [] - runtime.subscribeWorkspaceLayouts((frame) => frames.push(frame)) - - runtime.recordHookStatusTitle(status(GIT)) - runtime.recordHookStatusTitle(status(FOLDER, { prompt: 'Fix the login page' })) - await runtime.hookStatusTitlesSettled() - - expect(apply.mock.calls.map(([command]) => command.type)).toEqual(['renameTabs']) - expect(frames.filter((frame) => frame.type === 'records')).toHaveLength(1) - expect(frames).toHaveLength(1) - expect([titleOf(GIT), titleOf(FOLDER)]).toEqual([ - 'Refactor the auth middleware to use JWT', - 'Fix the login page' - ]) - }) - it('has the titles in the first snapshot a window that starts after them reads', async () => { const { runtime } = await hostWith([GIT]) @@ -109,68 +83,3 @@ describe('main titles agent tabs from its own hook status', () => { expect(tab?.generatedTitle).toBe('Refactor the auth middleware to use JWT') }) }) - -describe('main keeps the window’s generated-title rules', () => { - async function titled( - statuses: AgentStatusIpcPayload[][], - /** Main's dispatch labels; a list gives each read its own, the last one kept. */ - labels: - | Record[] - | Record = {} - ) { - const host = await hostWith([GIT]) - const reads = [labels].flat() - const read = vi.spyOn(host.runtime['agentOrchestrationProjection'], 'getForPaneKey') - read.mockImplementation((paneKey) => reads.at(-1)?.[paneKey]) - for (const each of reads.slice(0, -1)) { - read.mockImplementationOnce((paneKey) => each[paneKey]) - } - for (const batch of statuses) { - for (const row of batch) { - host.runtime.recordHookStatusTitle(row) - } - await host.runtime.hookStatusTitlesSettled() - } - return host - } - const labelsOf = (taskId: string, displayName: string) => ({ - [paneOf(GIT)]: { - taskId, - dispatchId: `ctx-${taskId}`, - taskTitle: displayName, - displayName - } - }) - - it('replaces a dispatch’s preamble title once main has its labels', async () => { - const prompt = dispatch('task-1', 'Implement the detailed worker instructions') - const host = await titled( - [[status(GIT, { prompt })]], - [{}, labelsOf('task-1', 'Better worker label')] - ) - expect(host.titleOf(GIT)).toBe('Implement the detailed worker') - - host.runtime.recordHookStatusTitle(status(GIT, { prompt, state: 'done' })) - await host.runtime.hookStatusTitlesSettled() - expect(host.titleOf(GIT)).toBe('Better worker label') - }) - - it('does not re-pin task A’s label onto a later dispatch of task B', async () => { - const { titleOf } = await titled( - [ - [ - status(GIT, { - prompt: dispatch('task-a', 'Implement task A worker instructions') - }) - ], - [ - status(GIT, { - prompt: dispatch('task-b', 'Implement task B worker instructions') - }) - ] - ], - labelsOf('task-a', 'Worker A label') - ) - expect(titleOf(GIT)).toBe('Implement task B worker instructions') - }) -}) diff --git a/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts b/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts index 0fca7a2941d..79b74962adf 100644 --- a/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts +++ b/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts @@ -5,16 +5,16 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import type { LayoutEditorView } from '../../../../shared/workspace-layout/layout-editor-view' +import type { LayoutEditorView } from '../../../../shared/workspace-layout/editor-tabs/layout-editor-view' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as WT, openTopologyStore, reopenTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) diff --git a/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts b/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts index 7f16df156f0..f5de295e744 100644 --- a/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts +++ b/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts @@ -6,15 +6,15 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import type { LayoutEditorView } from '../../../../shared/workspace-layout/layout-editor-view' +import type { LayoutEditorView } from '../../../../shared/workspace-layout/editor-tabs/layout-editor-view' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as WT, openTopologyStoreWithAuthority -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) @@ -126,29 +126,4 @@ describe("main's Store keeps an editor view where its tab's session is", () => { expect(publishedTab(runtime, FOLDER, 'd1-moved')).toBeUndefined() subscription.unsubscribe() }) - - it('a failed write puts a move across partitions back with its view', async () => { - const { store, authority, subscription } = await harness() - await store.applyLayoutCommand(openDiff(WT, 'd1')) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - authority.failNextWrite() - - await expect( - store.moveTabToWorkspaceAcrossPartitions( - { - type: 'moveTabToWorkspace', - workspace: WT, - toWorkspace: SSH_WORKTREE, - tabs: [{ tabId: 'd1', newTabId: 'd1', newEntityId: 'diff::moved' }], - groupId: `group-${SSH_WORKTREE}` - }, - 'local', - SSH_HOST - ) - ).rejects.toThrow() - - expect(store.getLayoutEditorViews('local')).toEqual({ [WT]: { d1: DIFF_VIEW } }) - expect(store.getLayoutEditorViews(SSH_HOST) ?? {}).toEqual({}) - subscription.unsubscribe() - }) }) diff --git a/src/main/runtime/terminal/layout/headless-terminal-split-layout.ts b/src/main/runtime/terminal/layout/headless-terminal-split-layout.ts index 7cd9ccdb767..fa25665aaa1 100644 --- a/src/main/runtime/terminal/layout/headless-terminal-split-layout.ts +++ b/src/main/runtime/terminal/layout/headless-terminal-split-layout.ts @@ -5,7 +5,7 @@ import type { import { insertLeafBeside, removeLayoutLeaf -} from '../../../../shared/workspace-layout/terminal-pane-tree' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' /** Persist headless splits so snapshot rebuilds cannot collapse them to a stale single pane. */ export function buildHeadlessTerminalSplitLayout( diff --git a/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts b/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts index 68ba0a25dc2..1d16da84661 100644 --- a/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts +++ b/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts @@ -4,7 +4,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../../persistence/loading-store/workspace-sessions/session-host-partitions' import { withDurableRuntimeStore, diff --git a/src/main/runtime/terminal/layout/mobile-presence-lock.test.ts b/src/main/runtime/terminal/layout/mobile-presence-lock.test.ts deleted file mode 100644 index 9fa17d5d1b0..00000000000 --- a/src/main/runtime/terminal/layout/mobile-presence-lock.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { mobilePresenceStore as store } from '../../orca-runtime-test-mocks/mobile-presence-store' -import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import '../input/terminal-input-admission' -import './mobile-subscribe-integration.spec' -import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' -import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache' -import type * as GitUsernameModule from '../../../git/repositories/git-username' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { RuntimePtyController } from '../lifecycle/runtime-pty-controller-contract' - -vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: facade.listWorktrees - } -}) - -vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const facade = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: facade.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - const createWorktreeListingMocks = () => ({ - listWorktrees: vi.fn().mockResolvedValue([]), - listWorktreesStrict: vi.fn().mockResolvedValue([]) - }) - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) -vi.mock('../../../workspace-hooks/hooks', () => ({ - getEffectiveHooks: vi.fn().mockReturnValue(null), - runHook: vi.fn().mockResolvedValue({ success: true, output: '' }) -})) -vi.mock('../../../workspace-hooks/worktree-runner-script', () => ({ - createSetupRunnerScript: vi.fn() -})) -vi.mock('../../../ipc/worktree-logic', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { ...actual, computeWorktreePath: vi.fn(), ensurePathWithinWorkspace: vi.fn() } -}) -vi.mock('../../../ipc/worktrees/removal/registered-worktree-roots-cache', () => ({ - invalidateAuthorizedRootsCache: vi.fn(), - invalidateAuthorizedRootsCacheForRepo: vi.fn() -})) -const repoBranchConflictMock = vi.hoisted(() => vi.fn().mockResolvedValue(null)) - -vi.mock('../../../git/repositories/git-username', async () => { - const actual = await vi.importActual( - '../../../git/repositories/git-username' - ) - return { ...actual, resolveLocalGitUsername: vi.fn(async () => '') } -}) - -// #7588 held-modal cases need per-test indefinite hold without mutating the shared default. -function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) { - vi.mocked(listWorktrees).mockResolvedValue([]) - const effectiveStore = { - ...store, - getSettings: () => ({ ...store.getSettings(), mobileAutoRestoreFitMs }) - } - const runtime = new OrcaRuntimeService(effectiveStore) - const ptySizes = new Map([ - ['pty-1', { cols: 150, rows: 40 }] - ]) - const resizes: { ptyId: string; cols: number; rows: number }[] = [] - const writes: string[] = [] - const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = [] - const fitOverrideEvents: { ptyId: string; mode: string; cols: number; rows: number }[] = [] - let resizeSucceeds = true - - const controller: RuntimePtyController = { - write: (_ptyId, data) => { - writes.push(data) - return true - }, - kill: () => true, - getForegroundProcess: async () => null, - resize: (ptyId, cols, rows) => { - if (!resizeSucceeds) { - return false - } - ptySizes.set(ptyId, { cols, rows }) - resizes.push({ ptyId, cols, rows }) - return true - }, - getSize: (ptyId) => ptySizes.get(ptyId) ?? null - } - runtime.setPtyController(controller) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: (ptyId, mode, cols, rows) => { - fitOverrideEvents.push({ ptyId, mode, cols, rows }) - }, - terminalDriverChanged: (ptyId, driver) => { - driverEvents.push({ ptyId, driver: { ...driver } }) - } - }) - - return { - runtime, - controller, - ptySizes, - resizes, - writes, - driverEvents, - fitOverrideEvents, - setResizeSucceeds: (next: boolean) => { - resizeSucceeds = next - } - } -} - -describe('mobile presence lock — multi-mobile semantics', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('updateDesktopViewport resizes the source PTY and records desktop geometry', async () => { - const { runtime, ptySizes, resizes } = createRuntime() - - expect(await runtime.updateDesktopViewport('pty-1', { cols: 132, rows: 44 })).toBe(true) - - expect(ptySizes.get('pty-1')).toEqual({ cols: 132, rows: 44 }) - expect(resizes.at(-1)).toEqual({ ptyId: 'pty-1', cols: 132, rows: 44 }) - // Controller drift must not overwrite remembered renderer geometry. - ptySizes.set('pty-1', { cols: 160, rows: 50 }) - await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 20 }) - expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) - expect(ptySizes.get('pty-1')).toEqual({ cols: 132, rows: 44 }) - }) - - it('updateDesktopViewport records restore geometry while phone-fit override is held', async () => { - const { runtime, ptySizes, resizes } = createRuntime() - await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 20 }) - expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 20 }) - resizes.length = 0 - - expect(await runtime.updateDesktopViewport('pty-1', { cols: 132, rows: 44 })).toBe(true) - - expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 20 }) - expect(resizes).toEqual([]) - - expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) - expect(ptySizes.get('pty-1')).toEqual({ cols: 132, rows: 44 }) - }) -}) - -// #7588: null-viewport re-subscribe leaves an active subscriber under the held fit override. -async function reachHeldModalWithNullViewportResubscribe( - runtime: OrcaRuntimeService -): Promise { - await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) - runtime.handleMobileUnsubscribe('pty-1', 'phone-A') - await vi.advanceTimersByTimeAsync(300) - await runtime.handleMobileSubscribe('pty-1', 'phone-A', undefined) -} - -describe('mobile presence lock — issue #7588 held-modal restore convergence', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('reclaim after a null-viewport resubscribe restores dims, clears override, notifies both channels', async () => { - const { runtime, ptySizes, fitOverrideEvents } = createRuntime(null) - const listenerEvents: { mode: string; cols: number; rows: number }[] = [] - runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) - - await reachHeldModalWithNullViewportResubscribe(runtime) - expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' }) - expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() - expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) - - const notifierBefore = fitOverrideEvents.length - const listenerBefore = listenerEvents.length - const restored = await runtime.reclaimTerminalForDesktop('pty-1') - - expect(restored).toBe(true) - expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) - expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() - expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) - expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) - }) -}) - -vi.mock('../../../git/refs/resolution/repo-branch-conflict', async (importOriginal) => ({ - ...(await importOriginal>()), - getBranchConflictKind: repoBranchConflictMock -})) diff --git a/src/main/runtime/terminal/layout/mobile-subscribe-integration.spec.ts b/src/main/runtime/terminal/layout/mobile-subscribe-integration.spec.ts deleted file mode 100644 index 03367f9ca29..00000000000 --- a/src/main/runtime/terminal/layout/mobile-subscribe-integration.spec.ts +++ /dev/null @@ -1,279 +0,0 @@ -import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' -import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache' -import { OrcaRuntimeService } from '../../orca-runtime' - -// Legacy restore cases need finite 5s (the clamp floor); production defaults to indefinite hold. -const LEGACY_RESTORE_MS = 5_000 -const settingsState = { - mobileAutoRestoreFitMs: LEGACY_RESTORE_MS as number | null -} - -const store = { - getRepo: () => ({ - id: 'repo-1', - path: '/tmp/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 - }), - getRepos: () => [store.getRepo()], - addRepo: () => {}, - updateRepo: () => undefined as never, - getAllWorktreeMeta: () => ({}), - getWorktreeMeta: () => undefined, - getGitHubCache: () => ({ pr: {}, issue: {} }), - setWorktreeMeta: () => undefined as never, - removeWorktreeMeta: () => {}, - getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), - addRetiredWorktreeName: () => {}, - mergeRetiredWorktreeNames: () => false, - getSettings: () => ({ - workspaceDir: '/tmp/workspaces', - nestWorkspaces: false, - refreshLocalBaseRefOnWorktreeCreate: false, - branchPrefix: 'none', - branchPrefixCustom: '', - mobileAutoRestoreFitMs: settingsState.mobileAutoRestoreFitMs - }), - updateSettings: (updates: { mobileAutoRestoreFitMs?: number | null }) => { - if ('mobileAutoRestoreFitMs' in updates) { - settingsState.mobileAutoRestoreFitMs = updates.mobileAutoRestoreFitMs ?? null - } - } -} - -class ObservableRuntime extends OrcaRuntimeService { - get restoreTimers(): typeof this.pendingRestoreTimers { - return this.pendingRestoreTimers - } - get softLeavers(): typeof this.pendingSoftLeavers { - return this.pendingSoftLeavers - } - get fitOverrides(): typeof this.terminalFitOverrides { - return this.terminalFitOverrides - } - get drivers(): typeof this.terminalDrivers { - return this.terminalDrivers - } -} - -function createRuntime() { - vi.mocked(listWorktrees).mockResolvedValue([ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/foo', - isBare: false, - isMainWorktree: false - } - ]) - const runtime = new ObservableRuntime(store) - const ptySizes = new Map() - ptySizes.set('pty-1', { cols: 150, rows: 40 }) - ptySizes.set('pty-2', { cols: 120, rows: 35 }) - ptySizes.set('pty-3', { cols: 100, rows: 30 }) - - const resizes: { ptyId: string; cols: number; rows: number }[] = [] - const notifications: { ptyId: string; mode: string; cols: number; rows: number }[] = [] - - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - resize: (ptyId, cols, rows) => { - ptySizes.set(ptyId, { cols, rows }) - resizes.push({ ptyId, cols, rows }) - return true - }, - getSize: (ptyId) => ptySizes.get(ptyId) ?? null - }) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: (ptyId, mode, cols, rows) => { - notifications.push({ ptyId, mode, cols, rows }) - }, - terminalDriverChanged: vi.fn() - }) - - return { runtime, ptySizes, resizes, notifications } -} - -describe('mobile subscribe integration', () => { - beforeEach(() => { - vi.useFakeTimers() - settingsState.mobileAutoRestoreFitMs = LEGACY_RESTORE_MS - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('serializeMainTerminalBuffer reports the seq included in the headless snapshot', async () => { - vi.useRealTimers() - const { runtime } = createRuntime() - const first = 'one\r\n' - const second = 'two\r\n' - const third = 'three\r\n' - - runtime.onPtyData('pty-1', first, Date.now()) - const initialSnapshot = await runtime.serializeMainTerminalBuffer('pty-1') - expect(initialSnapshot?.seq).toBe(first.length) - expect(initialSnapshot?.source).toBe('headless') - - type HeadlessStateForTest = { - emulator: { write: (data: string) => Promise | void } - } - const headless = ( - runtime as unknown as { headlessTerminals: Map } - ).headlessTerminals.get('pty-1') - expect(headless).toBeDefined() - const originalWrite = headless!.emulator.write.bind(headless!.emulator) - const secondWriteGate: { release: (() => void) | null } = { release: null } - const secondWriteStarted = new Promise((resolve) => { - headless!.emulator.write = async (data: string): Promise => { - if (data === second) { - resolve() - await new Promise((release) => { - secondWriteGate.release = release - }) - } - await originalWrite(data) - } - }) - - try { - runtime.onPtyData('pty-1', second, Date.now()) - await secondWriteStarted - const racedSnapshot = runtime.serializeMainTerminalBuffer('pty-1') - runtime.onPtyData('pty-1', third, Date.now()) - if (!secondWriteGate.release) { - throw new Error('second write did not block') - } - secondWriteGate.release() - - const snapshot = await racedSnapshot - expect(snapshot?.seq).toBe(first.length + second.length) - expect(snapshot?.source).toBe('headless') - expect(runtime.getPtyOutputSequence('pty-1')).toBe( - first.length + second.length + third.length - ) - - const finalSnapshot = await runtime.serializeMainTerminalBuffer('pty-1') - expect(finalSnapshot?.seq).toBe(first.length + second.length + third.length) - expect(finalSnapshot?.source).toBe('headless') - } finally { - headless!.emulator.write = originalWrite - secondWriteGate.release?.() - } - }) - - it('preserves held-override baseline across resubscribe-after-indefinite-hold', async () => { - // Indefinite-hold re-subscribe must inherit the retained desktop baseline for later Restore. - settingsState.mobileAutoRestoreFitMs = null - const { runtime, ptySizes } = createRuntime() - - await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 }) - expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) - - runtime.handleMobileUnsubscribe('pty-1', 'client-a') - await vi.advanceTimersByTimeAsync(60_000) - expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) - - await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 }) - - await runtime.reclaimTerminalForDesktop('pty-1') - - expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) - }) - - describe('onExternalPtyResize', () => { - it('ignores reports while a mobile-fit override is in place', async () => { - // Phone-fit echoes must not poison the desktop restore baseline; see docs/mobile-fit-hold.md. - const { runtime, ptySizes } = createRuntime() - await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 }) - - runtime.onExternalPtyResize('pty-1', 45, 20) - - runtime.setMobileDisplayMode('pty-1', 'desktop') - await runtime.applyMobileDisplayMode('pty-1') - expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) - }) - - it('updates baseline mid-fit when desktop reports dims that differ from the override', async () => { - // A newly visible desktop tab can report real geometry during phone fit; retain it for restore. - const { runtime, ptySizes } = createRuntime() - ptySizes.set('pty-1', { cols: 80, rows: 24 }) - runtime.onExternalPtyResize('pty-1', 80, 24) - await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 }) - - runtime.onExternalPtyResize('pty-1', 200, 60) - - runtime.setMobileDisplayMode('pty-1', 'desktop') - await runtime.applyMobileDisplayMode('pty-1') - expect(ptySizes.get('pty-1')).toEqual({ cols: 200, rows: 60 }) - }) - }) - - describe('recordRendererGeometry (pty:reportGeometry IPC)', () => { - it('bypasses the cascade-suppress window (it is measurement-only)', async () => { - const { runtime, ptySizes, resizes } = createRuntime() - await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 }) - runtime.setMobileDisplayMode('pty-1', 'desktop') - await runtime.applyMobileDisplayMode('pty-1') - expect(runtime.isResizeSuppressed()).toBe(true) - expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) - resizes.length = 0 - - runtime.recordRendererGeometry('pty-1', 130, 40) - expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) - expect(resizes).toEqual([]) - - runtime.setMobileDisplayMode('pty-1', 'auto') - await runtime.applyMobileDisplayMode('pty-1') - expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) - runtime.setMobileDisplayMode('pty-1', 'desktop') - await runtime.applyMobileDisplayMode('pty-1') - expect(ptySizes.get('pty-1')).toEqual({ cols: 130, rows: 40 }) - }) - }) - - // See docs/mobile-fit-hold.md. - describe('mobileAutoRestoreFitMs (fit hold)', () => { - it('reclaim with WS disconnect between cycles — held branch restores correctly each time', async () => { - // Repeated held-override reclaim must restore desktop geometry, never the current phone fit. - settingsState.mobileAutoRestoreFitMs = null - const { runtime, ptySizes } = createRuntime() - - for (let i = 0; i < 3; i++) { - await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 }) - await runtime.mobileTookFloor('pty-1', 'client-a') - expect(ptySizes.get('pty-1'), `iter ${i}: phone-fit`).toEqual({ cols: 45, rows: 20 }) - - runtime.onClientDisconnected('client-a') - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(60_000) - expect(ptySizes.get('pty-1'), `iter ${i}: held after disconnect`).toEqual({ - cols: 45, - rows: 20 - }) - expect(runtime.isMobileSubscriberActive('pty-1'), `iter ${i}: no subscribers`).toBe(false) - expect(runtime.getTerminalFitOverride('pty-1'), `iter ${i}: override held`).not.toBeNull() - - const ok = await runtime.reclaimTerminalForDesktop('pty-1') - expect(ok, `iter ${i}: reclaim ok`).toBe(true) - expect(ptySizes.get('pty-1'), `iter ${i}: PTY restored to desktop`).toEqual({ - cols: 150, - rows: 40 - }) - expect(runtime.getTerminalFitOverride('pty-1'), `iter ${i}: override cleared`).toBeNull() - } - }) - }) -}) diff --git a/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts b/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts index 25f1889fa46..f466d3bbe42 100644 --- a/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts +++ b/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts @@ -3,7 +3,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { resolveHostId } from '../../../persistence/loading-store/workspace-sessions/session-host-partitions' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { OrcaRuntimeService } from '../../orca-runtime' import type { RuntimeStore } from '../../construction/runtime-store-contract' diff --git a/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts b/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts index 783a56b87b2..2e411948444 100644 --- a/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts +++ b/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts @@ -7,14 +7,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { ownedEditorFileId } from '../../../../shared/workspace-session/workspace-session-pane-ownership' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as WT, openTopologyStore, reopenTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) diff --git a/src/main/runtime/terminal/layout/runtime-layout-apply.ts b/src/main/runtime/terminal/layout/runtime-layout-apply.ts index 01777cc7ea9..ee45084e55c 100644 --- a/src/main/runtime/terminal/layout/runtime-layout-apply.ts +++ b/src/main/runtime/terminal/layout/runtime-layout-apply.ts @@ -6,7 +6,7 @@ import type { RenameTabsCommand, UntitledTab } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import type { TerminalLeafMoveRequest } from '../../../../shared/workspace-layout/terminal-leaf-move' +import type { TerminalLeafMoveRequest } from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import { renameTabCommandsOf } from '../../../../shared/workspace-layout/workspace-layout-commands' import { markAgentLaunchesClosedByUser } from '../../../agent-launch/agent-launch-pane-attachment' import { isWslMoveWorkspaceSessionFrozen } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' diff --git a/src/main/runtime/terminal/layout/runtime-terminal-spawn-placement.ts b/src/main/runtime/terminal/layout/runtime-terminal-spawn-placement.ts index 34764a1e041..ba68e50dd9c 100644 --- a/src/main/runtime/terminal/layout/runtime-terminal-spawn-placement.ts +++ b/src/main/runtime/terminal/layout/runtime-terminal-spawn-placement.ts @@ -1,4 +1,4 @@ -import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' import type { TerminalPaneSplitDirection } from '../../../../shared/workspace-layout/terminal-tab-types' import type { RuntimeTerminalPresentation } from '../../../../shared/runtime-terminal-contracts' diff --git a/src/main/runtime/terminal/layout/terminal-view-presence.ts b/src/main/runtime/terminal/layout/terminal-view-presence.ts index 0a9630d2873..eea640c6680 100644 --- a/src/main/runtime/terminal/layout/terminal-view-presence.ts +++ b/src/main/runtime/terminal/layout/terminal-view-presence.ts @@ -1,7 +1,7 @@ import { setTimeout as delay } from 'node:timers/promises' import { OrcaRuntimeWithRecordAgentPromptLifecycleState } from '../output/terminal-output-generation' import type { TerminalOscLinkRange } from '../../../../shared/terminal/links/terminal-osc-link-ranges' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' import type { RuntimeTerminalWriteOptions } from '../input/runtime-terminal-writer' import type { WriteSettlement } from '../../../../shared/terminal/pty/lifecycle/pty-write-settlement' diff --git a/src/main/runtime/terminal/lifecycle/closed-pane-of-exited-pty.ts b/src/main/runtime/terminal/lifecycle/closed-pane-of-exited-pty.ts index 17675d31c78..ea58e80e0cb 100644 --- a/src/main/runtime/terminal/lifecycle/closed-pane-of-exited-pty.ts +++ b/src/main/runtime/terminal/lifecycle/closed-pane-of-exited-pty.ts @@ -1,5 +1,5 @@ // Close removes the pane before exit; resolve it by PTY and incarnation in closed-pane records, then retire that entry (L80 Q2). -import { closedTerminalPaneOf } from '../../../../shared/workspace-layout/closed-terminal-panes' +import { closedTerminalPaneOf } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-panes' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { ExecutionHostId } from '../../../../shared/execution-host' diff --git a/src/main/runtime/terminal/lifecycle/exited-split-pane-layout-close.ts b/src/main/runtime/terminal/lifecycle/exited-split-pane-layout-close.ts index d6e397c7efa..639d5b66b58 100644 --- a/src/main/runtime/terminal/lifecycle/exited-split-pane-layout-close.ts +++ b/src/main/runtime/terminal/lifecycle/exited-split-pane-layout-close.ts @@ -1,4 +1,4 @@ -import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { RetiredTerminalSurface } from '../surface/mobile-session-terminal-retirement' import { exitedSplitPaneOutcome, type ExitedSplitPaneFacts } from './exited-split-pane-rule' diff --git a/src/main/runtime/terminal/lifecycle/local-pty-foreground-command-line.ts b/src/main/runtime/terminal/lifecycle/local-pty-foreground-command-line.ts index 4d1db9ddd79..fe390cbb741 100644 --- a/src/main/runtime/terminal/lifecycle/local-pty-foreground-command-line.ts +++ b/src/main/runtime/terminal/lifecycle/local-pty-foreground-command-line.ts @@ -1,6 +1,6 @@ import { listRegisteredPtys } from '../../../memory/pty-registry' -import { resolveAgentForegroundCommandLine } from '../../../providers/agent-foreground-process' -import { resolveWindowsAgentForegroundCommandLine } from '../../../providers/windows-agent-foreground-command-line' +import { resolveAgentForegroundCommandLine } from '../../../providers/foreground/agent-process' +import { resolveWindowsAgentForegroundCommandLine } from '../../../providers/foreground/windows/agent-command-line' export async function readLocalPtyForegroundCommandLine( ptyId: string, diff --git a/src/main/runtime/terminal/lifecycle/mobile-session-dead-pty.test.ts b/src/main/runtime/terminal/lifecycle/mobile-session-dead-pty.test.ts deleted file mode 100644 index a7b476527d1..00000000000 --- a/src/main/runtime/terminal/lifecycle/mobile-session-dead-pty.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { rmSync } from 'node:fs' -import { DaemonPtyAdapter } from '../../../daemon/providers/adapter/daemon-pty-adapter' -import { DaemonPtyRouter } from '../../../daemon/providers/routing/daemon-pty-router' -import { DegradedDaemonPtyProvider } from '../../../daemon/providers/routing/degraded-daemon-pty-provider' -import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' -import { - createMockSubprocess, - startDaemonAdapterHarness, - waitFor -} from '../../../daemon/providers/adapter/testing/daemon-pty-adapter-test-harness' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { PtyWriteUnavailableError } from '../../../providers/pty-write-unavailable-error' - -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../../orca-runtime') -const { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const providerSession = { key: 'session_id' as const, id: 'codex-conversation' } - -function mobileChat(provider: IPtyProvider) { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal() - ) - const runtime = new OrcaRuntimeService(runtimeStore) - const spawn = vi.fn() - const write = vi.fn(() => true) - runtime.setPtyController({ - spawn, - write, - kill: () => true, - getForegroundProcess: async () => null, - hasPty: (id) => provider.hasPty?.(id) ?? null, - getPtyAvailability: (id) => provider.getPtyAvailability?.(id) ?? null, - listProcesses: () => provider.listProcesses() - }) - runtime.attachWindow(1) - let snapshotVersion = 0 - const publish = (ptyId: string) => - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'host-tab', - worktreeId: TEST_WORKTREE_ID, - title: 'Codex', - activeLeafId: HEADLESS_LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: 'host-tab', - worktreeId: TEST_WORKTREE_ID, - leafId: HEADLESS_LEAF_ID, - paneRuntimeId: 1, - ptyId, - paneTitle: 'Codex' - } - ], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: ++snapshotVersion, - activeGroupId: null, - activeTabId: 'host-tab', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: `host-tab::${HEADLESS_LEAF_ID}`, - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - ptyId, - title: 'Codex', - isActive: true, - agentStatus: { - agentType: 'codex', - state: 'waiting', - prompt: '', - updatedAt: 1, - stateStartedAt: 1, - stateHistory: [], - paneKey: `host-tab:${HEADLESS_LEAF_ID}`, - providerSession - } - } - ] - } - ] - }) - const read = () => runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - const published = () => runtime['getMobileSessionTabsForWorktree'](TEST_WORKTREE_ID) - return { runtime, publish, read, published, spawn, write } -} - -it.each(['direct', 'router', 'degraded'] as const)( - 'keeps an unattached retained conversation ready, then withholds a gone PTY through %s', - async (route) => { - const subprocesses: ReturnType[] = [] - const harness = await startDaemonAdapterHarness(() => { - const subprocess = createMockSubprocess() - subprocesses.push(subprocess) - return subprocess - }) - const owner = new DaemonPtyAdapter(harness) - try { - await harness.adapter.spawn({ - sessionId: 'persisted-pty', - cwd: TEST_WORKTREE_PATH, - cols: 80, - rows: 24 - }) - harness.adapter.dispose() - const provider = - route === 'direct' - ? owner - : route === 'router' - ? new DaemonPtyRouter({ current: owner, legacy: [] }) - : new DegradedDaemonPtyProvider({ - current: owner, - legacy: [], - fallback: new LocalPtyProvider() - }) - const chat = mobileChat(provider) - chat.publish('persisted-pty') - const before = await chat.read() - expect(owner.hasPty('persisted-pty')).toBe(false) - expect(before.tabs[0]).toMatchObject({ status: 'ready', terminal: expect.any(String) }) - const original = before.tabs[0] - if (original?.type !== 'terminal') { - throw new Error('Expected the retained terminal') - } - - await owner.attach('persisted-pty') - expect((await chat.read()).tabs[0]).toHaveProperty('terminal', original.terminal) - expect(subprocesses).toHaveLength(1) - subprocesses[0]?._simulateExit(0) - await waitFor(() => !owner.hasPty('persisted-pty')) - expect((await chat.read()).tabs[0]).toMatchObject({ - status: 'pending-handle', - terminal: null - }) - chat.publish('persisted-pty') - expect(chat.published().tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null }) - - await owner.spawn({ - sessionId: 'replacement-pty', - cwd: TEST_WORKTREE_PATH, - cols: 80, - rows: 24 - }) - chat.publish('replacement-pty') - const restored = (await chat.read()).tabs[0] - expect(restored).toMatchObject({ - id: original.id, - status: 'ready', - terminal: expect.any(String), - agentStatus: expect.objectContaining({ providerSession }) - }) - expect(restored).not.toHaveProperty('terminal', original.terminal) - expect(chat.spawn).not.toHaveBeenCalled() - expect(chat.write).not.toHaveBeenCalled() - expect(subprocesses.every((subprocess) => subprocess.write.mock.calls.length === 0)).toBe( - true - ) - } finally { - owner.dispose() - harness.adapter.dispose() - await harness.server.shutdown() - rmSync(harness.dir, { recursive: true, force: true }) - } - } -) - -it('withholds an attached PTY during endpoint recovery and restores its same conversation without replay', async () => { - const subprocess = createMockSubprocess() - const harness = await startDaemonAdapterHarness(() => subprocess) - const respawn = vi.fn(async () => {}) - const owner = new DaemonPtyAdapter({ ...harness, respawn }) - try { - await owner.spawn({ sessionId: 'persisted-pty', cwd: TEST_WORKTREE_PATH, cols: 80, rows: 24 }) - const chat = mobileChat(owner) - chat.publish('persisted-pty') - const original = (await chat.read()).tabs[0] - if (original?.type !== 'terminal') { - throw new Error('Expected the attached terminal') - } - expect(original.status).toBe('ready') - const unavailable = new Promise((resolve) => owner.onWriteUnavailable(() => resolve())) - owner['client'].disconnect() - expect(() => owner.write('persisted-pty', 'refused')).toThrow(PtyWriteUnavailableError) - await unavailable - expect(owner.hasPty('persisted-pty')).toBe(true) - expect(chat.published().tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null }) - - // Successful inventory reconnects transport but does not clear the remount fence. - expect((await chat.read()).tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null }) - await owner.attach('persisted-pty') - expect((await chat.read()).tabs[0]).toMatchObject({ - id: original.id, - status: 'ready', - terminal: original.terminal, - agentStatus: expect.objectContaining({ providerSession }) - }) - expect(subprocess.write).not.toHaveBeenCalled() - expect(chat.spawn).not.toHaveBeenCalled() - expect(chat.write).not.toHaveBeenCalled() - expect(respawn).not.toHaveBeenCalled() - - respawn.mockRejectedValue(new Error('daemon remains unavailable')) - await harness.server.shutdown() - await waitFor(() => owner.getDaemonIdentity() === null) - expect((await chat.read()).tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null }) - expect(owner.hasPty('persisted-pty')).toBe(true) - expect(subprocess.write).not.toHaveBeenCalled() - expect(chat.spawn).not.toHaveBeenCalled() - } finally { - owner.dispose() - harness.adapter.dispose() - await harness.server.shutdown() - rmSync(harness.dir, { recursive: true, force: true }) - } -}) diff --git a/src/main/runtime/terminal/lifecycle/orca-runtime-build-controller-terminal-identities.ts b/src/main/runtime/terminal/lifecycle/orca-runtime-build-controller-terminal-identities.ts index 6fce600fd20..4c63c8b1c6a 100644 --- a/src/main/runtime/terminal/lifecycle/orca-runtime-build-controller-terminal-identities.ts +++ b/src/main/runtime/terminal/lifecycle/orca-runtime-build-controller-terminal-identities.ts @@ -1,5 +1,5 @@ import type { PtyControllerTerminalIdentity } from './runtime-pty-controller-contract' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' export function buildControllerTerminalIdentities(sessions: PtyProcessInfo[]): { controllerIdentityByPtyId: Map diff --git a/src/main/runtime/terminal/lifecycle/orca-runtime-exited-split-pane-close.test.ts b/src/main/runtime/terminal/lifecycle/orca-runtime-exited-split-pane-close.test.ts index e6173e952be..fa976a12069 100644 --- a/src/main/runtime/terminal/lifecycle/orca-runtime-exited-split-pane-close.test.ts +++ b/src/main/runtime/terminal/lifecycle/orca-runtime-exited-split-pane-close.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree' +import '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' import { OrcaRuntimeService } from '../../orca-runtime' @@ -109,37 +109,7 @@ function splitRuntime(): { runtime: OrcaRuntimeService; session: () => Workspace return { runtime, session: () => session } } -const panes = (session: WorkspaceSessionState) => - collectLeafIds(session.terminalLayoutsByTabId.tab?.root) - describe('layout-owner build: main closes an exited split pane itself', () => { - it('keeps a split pane whose process failed, behind its "Terminal exited" card', async () => { - const { runtime, session } = splitRuntime() - await runtime.onPtyExit('pty-right', 1, undefined, { providerExitObserved: true }) - expect(panes(session())).toEqual([LEFT, RIGHT]) - }) - - it('keeps a split pane on a -1 nothing vouches for, as the window does on lost contact', async () => { - const { runtime, session } = splitRuntime() - await runtime.onPtyExit('pty-right', -1) - expect(panes(session())).toEqual([LEFT, RIGHT]) - }) - - it('keeps a split pane on a -1 the host confirmed, so recovery can start a shell in it', async () => { - const { runtime, session } = splitRuntime() - await runtime.onPtyExit('pty-right', -1, undefined, { hostExitConfirmed: true }) - expect(panes(session())).toEqual([LEFT, RIGHT]) - }) - - it('keeps a split pane whose exit came with no code, as when its socket closed', async () => { - const { runtime, session } = splitRuntime() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: node-pty reports no exit code on a socket close, despite its types. - await runtime.onPtyExit('pty-right', undefined as unknown as number, undefined, { - providerExitObserved: true - }) - expect(panes(session())).toEqual([LEFT, RIGHT]) - }) - it('tells the phone a closed pane retired, and sends it nothing for a pane main keeps', async () => { const phone = async (runtime: OrcaRuntimeService) => { const tabs = await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`) @@ -159,21 +129,4 @@ describe('layout-owner build: main closes an exited split pane itself', () => { await kept.onPtyExit('pty-right', 1, undefined, { providerExitObserved: true }) expect(await phone(kept)).toEqual({ version: 1, retired: [] }) }) - - it('keeps a newborn split that died while shown before any input or output', async () => { - const { runtime, session } = splitRuntime() - runtime.terminalRunFacts.recordSpawnCommit({ id: 'pty-right' }, { ptyId: 'pty-left' }) - await runtime.onPtyExit('pty-right', 0, undefined, { - providerExitObserved: true, - viewShown: true - }) - expect(panes(session())).toEqual([LEFT, RIGHT]) - }) - - it('closes that newborn split when it ended unseen, as a hidden pane always closed', async () => { - const { runtime, session } = splitRuntime() - runtime.terminalRunFacts.recordSpawnCommit({ id: 'pty-right' }, { ptyId: 'pty-left' }) - await runtime.onPtyExit('pty-right', 0, undefined, { providerExitObserved: true }) - expect(panes(session())).toEqual([LEFT]) - }) }) diff --git a/src/main/runtime/terminal/lifecycle/pty-controller-inventory-listing.ts b/src/main/runtime/terminal/lifecycle/pty-controller-inventory-listing.ts index 675e9638ecf..3f0291a4abd 100644 --- a/src/main/runtime/terminal/lifecycle/pty-controller-inventory-listing.ts +++ b/src/main/runtime/terminal/lifecycle/pty-controller-inventory-listing.ts @@ -1,6 +1,6 @@ import { OrcaRuntimeWithRefreshPtyWorktreeRecordsFromController } from './pty-worktree-refresh' import type * as PtyControllerContract from './runtime-pty-controller-contract' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' import { type ExecutionHostId, getConnectionExecutionHostId diff --git a/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-admission.test.ts b/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-admission.test.ts deleted file mode 100644 index bb5eccad768..00000000000 --- a/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-admission.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' -import { - createInventoryRuntime, - deferred, - processRow, - PREDECESSOR, - PTY, - SUCCESSOR, - WORKTREE -} from './pty-inventory-lifecycle-fixture' - -afterEach(() => vi.restoreAllMocks()) - -describe('inventory admission after a PTY lifecycle change', () => { - it.each(['exit', 'registered-successor', 'spawned-successor', 'unknown-start-spawn'] as const)( - 'rejects a captured predecessor row after %s before it can adopt handles', - async (mode) => { - const reply = deferred() - const { runtime, hasPty } = createInventoryRuntime(() => reply.promise) - if (mode !== 'unknown-start-spawn') { - runtime.register() - } - const pending = runtime.read() - if (mode !== 'unknown-start-spawn') { - runtime.onPtyExit(PTY, 0, PREDECESSOR, { providerExitObserved: true }) - } - if (mode === 'registered-successor') { - runtime.register(SUCCESSOR) - } - if (mode === 'spawned-successor' || mode === 'unknown-start-spawn') { - runtime.onPtySpawned(PTY, SUCCESSOR) - } - const current = runtime.capture() - reply.resolve([processRow()]) - expect(await pending).toBeNull() - expect(runtime.capture()).toEqual(current) - expect(hasPty).not.toHaveBeenCalled() - } - ) - - it.each(['spawn', 'register'] as const)( - 'does not apply stale absence to unknown-at-start %s', - async (kind) => { - const reply = deferred() - const { runtime, hasPty } = createInventoryRuntime(() => reply.promise) - const pending = runtime.read() - if (kind === 'spawn') { - runtime.onPtySpawned(PTY, SUCCESSOR) - } else { - runtime.register(SUCCESSOR) - } - reply.resolve([]) - expect(await pending).toBeNull() - expect(runtime.capture()).toMatchObject({ connected: true, incarnationId: SUCCESSOR }) - expect(hasPty).not.toHaveBeenCalled() - } - ) - - it('fences a same-ID legacy registration with no incarnation', async () => { - const reply = deferred() - const { runtime } = createInventoryRuntime(() => reply.promise) - runtime.registerPty(PTY, WORKTREE) - const pending = runtime.read() - runtime.onPtyExit(PTY, 0, undefined, { providerExitObserved: true }) - runtime.registerPty(PTY, WORKTREE) - reply.resolve([{ id: PTY, cwd: '', title: 'stale legacy title', worktreeId: WORKTREE }]) - expect(await pending).toBeNull() - expect(runtime.capture()).toMatchObject({ - connected: true, - incarnationId: null, - controllerTitle: null - }) - }) - - it('does not let an ignored predecessor exit invalidate a current inventory', async () => { - const reply = deferred() - const { runtime } = createInventoryRuntime(() => reply.promise) - runtime.register(SUCCESSOR) - const pending = runtime.read(null) - runtime.onPtyExit(PTY, 0, PREDECESSOR, { providerExitObserved: true }) - reply.resolve([processRow(PTY, SUCCESSOR)]) - expect((await pending)?.allLivePtyIds).toEqual(new Set([PTY])) - expect(runtime.capture().incarnationId).toBe(SUCCESSOR) - }) - - it('accepts a genuinely new row and a replacement first observed by fresh inventory', async () => { - let sessions = [processRow()] - const { runtime } = createInventoryRuntime(async () => sessions) - expect((await runtime.read())?.allLivePtyIds).toEqual(new Set([PTY])) - expect(runtime.capture().incarnationId).toBe(PREDECESSOR) - sessions = [processRow(PTY, SUCCESSOR)] - expect((await runtime.read())?.allLivePtyIds).toEqual(new Set([PTY])) - expect(runtime.capture()).toMatchObject({ - incarnationId: SUCCESSOR, - handle: `term_${SUCCESSOR}`, - connected: true - }) - }) -}) diff --git a/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-fixture.ts b/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-fixture.ts index e9ee86c9328..cb8f23080ed 100644 --- a/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-fixture.ts +++ b/src/main/runtime/terminal/lifecycle/pty-inventory-lifecycle-fixture.ts @@ -4,7 +4,7 @@ import type { PtyInventoryRefreshOptions, RuntimePtyController } from './runtime-pty-controller-contract' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { registerBoundPty } from '../../orca-runtime-tests/bind-first-pane.test-fixture' diff --git a/src/main/runtime/terminal/lifecycle/pty-registration.ts b/src/main/runtime/terminal/lifecycle/pty-registration.ts index 7c2238096f5..45bba860fa7 100644 --- a/src/main/runtime/terminal/lifecycle/pty-registration.ts +++ b/src/main/runtime/terminal/lifecycle/pty-registration.ts @@ -2,14 +2,14 @@ import { classifyTerminalCreationFailure, terminalExitError } from '../../../../shared/terminal/pty/lifecycle/terminal-start-failure' -import type { PtySpawnResult } from '../../../providers/pty-spawn-result' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import { recordFreshLaunch, retireLaunch } from '../launch/launch-evidence' import type { DaemonLaunchNote } from '../../../daemon/protocol/daemon-launch-note-protocol' import { OrcaRuntimeWithDaemonLaunchNote } from './daemon-launch-note' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import { spawnSurfaceClaimSequence } from '../surface/pty-recorded-surface-topology' diff --git a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts index 134c61a4c2c..d6c5e6cc196 100644 --- a/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts +++ b/src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts @@ -1,5 +1,5 @@ /** Read execution-host process tables: daemon shell-ownership changes only after full-screen exit and misses plain failed/finished commands. Observation failure is unproven. */ -import { confirmShellForegroundProcess } from '../../../providers/agent-foreground-process' +import { confirmShellForegroundProcess } from '../../../providers/foreground/agent-process' import { getFreshProcessTableSnapshot } from '../../../../shared/process-table-snapshot-reader' import { getProcessTableIndex } from '../../../../shared/process-table-index' import { isShellProcess } from '../../../../shared/agent-status/process/shell-process-detection' diff --git a/src/main/runtime/terminal/lifecycle/runtime-pty-controller-contract.ts b/src/main/runtime/terminal/lifecycle/runtime-pty-controller-contract.ts index f05674811c6..d86dff234f5 100644 --- a/src/main/runtime/terminal/lifecycle/runtime-pty-controller-contract.ts +++ b/src/main/runtime/terminal/lifecycle/runtime-pty-controller-contract.ts @@ -20,19 +20,19 @@ import type { } from '../../../../shared/agent-session/agent-session-host-authority' import type { AgentProviderSessionMetadata } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation' import type { PtyBindingSourceExpectation } from '../../../persistence/loading-store/store' -import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' -import type { PtySpawnResult } from '../../../providers/pty-spawn-result' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' +import type { PtySpawnResult } from '../../../providers/pty/spawn-result' import type { TerminalProcessInspection as PtyProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' import type { WriteSettlement } from '../../../../shared/terminal/pty/lifecycle/pty-write-settlement' import type { StartupCwdFallback } from '../../../../shared/startup-cwd-fallback' import type { TerminalInputKind } from '../../../../shared/terminal/input/terminal-input-kind' -import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' export type PtyInventoryRefreshOptions = { includeForegroundProcessEvidence?: boolean diff --git a/src/main/runtime/terminal/lifecycle/terminal-run-facts-input.test.ts b/src/main/runtime/terminal/lifecycle/terminal-run-facts-input.test.ts deleted file mode 100644 index 33a39777c63..00000000000 --- a/src/main/runtime/terminal/lifecycle/terminal-run-facts-input.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { TerminalInputKind } from '../../../../shared/terminal/input/terminal-input-kind' -import { writePtyFromRuntimeController } from '../../../ipc/pty/runtime/operations' -import { getLocalPtyProvider, setLocalPtyProvider } from '../../../ipc/pty/provider/registry' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { settledWriteStub } from '../../../providers/settled-pty-write-stub' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { RuntimePtyController } from './runtime-pty-controller-contract' -import '../../orchestration/mailbox/terminal-pointer/mailbox-pointer-pty-write' -import { sendTerminalStreamInput } from '../../rpc/methods/terminal/terminal-input-delivery' -import { makeStore } from '../../rpc/server/runtime-rpc-worktree-store-fixtures' -import '../../workspaces/startup/runtime-worktree-startup-readiness' - -vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: listings.listWorktrees - } -}) - -vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: listings.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - function createWorktreeListingMocks() { - const worktrees = [ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/run-facts', - isBare: false, - isMainWorktree: false - } - ] - return { - listWorktrees: vi.fn().mockResolvedValue(worktrees), - listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) - } - } - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -const PTY_ID = 'pty-run-facts-input' -const priorProvider = getLocalPtyProvider() - -type FreshRun = { - runtime: OrcaRuntimeService - controller: RuntimePtyController - handle: string - /** The kind each provider write was sent with, and whether input was recorded by then. */ - writes: { data: string; inputRecorded: boolean }[] - kinds: TerminalInputKind[] - firstUserInputAt: () => number | null -} - -/** A fresh shell whose controller writes go through main's real write funnel to a fake provider. */ -async function createFreshRun(): Promise { - const runtime = new OrcaRuntimeService(makeStore() as never) - const firstUserInputAt = (): number | null => - runtime.terminalRunFacts.read(PTY_ID, null).firstUserInputAt - const writes: FreshRun['writes'] = [] - const kinds: TerminalInputKind[] = [] - const write = (_id: string, data: string): boolean => { - writes.push({ data, inputRecorded: firstUserInputAt() !== null }) - if (data.endsWith('\r')) { - runtime.onPtyData(PTY_ID, '\x1b]0;Codex working\x07', Date.now()) - } - return true - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the write funnel calls only write and writeWithSettlement on the provider. - setLocalPtyProvider({ - write, - writeWithSettlement: settledWriteStub(write) - } as unknown as IPtyProvider) - const controller: RuntimePtyController = { - spawn: async () => ({ id: PTY_ID }), - write: (id, data, inputKind) => { - kinds.push(inputKind) - return writePtyFromRuntimeController({ runtime }, id, data, inputKind) - }, - writeWithSettlement: (id, data, inputKind) => { - kinds.push(inputKind) - return writePtyFromRuntimeController({ runtime }, id, data, inputKind, { - waitForSettlement: true - }) - }, - kill: () => true, - getForegroundProcess: async () => null - } - runtime.setPtyController(controller) - const terminal = await runtime.createTerminal('path:/tmp/worktree-a', { launchAgent: 'aider' }) - runtime.terminalRunFacts.recordSpawnCommit({ id: PTY_ID }) - return { runtime, controller, handle: terminal.handle, writes, kinds, firstUserInputAt } -} - -afterEach(() => { - vi.useRealTimers() - setLocalPtyProvider(priorProvider) -}) - -describe('run facts: the controller write funnel', () => { - it('records terminal.send input before the write that could end the process', async () => { - const run = await createFreshRun() - - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'], shouldClearNativeTimers: true }) - try { - await Promise.all([ - run.runtime.sendTerminal( - run.handle, - { text: 'exit', enter: true }, - { inputKind: 'driving' } - ), - vi.runAllTimersAsync() - ]) - - expect(run.firstUserInputAt()).not.toBeNull() - expect(run.writes.map((write) => write.inputRecorded)).toEqual([true, true]) - } finally { - vi.clearAllTimers() - vi.useRealTimers() - } - }) - - it('reads a run launched with a prompt as untyped until someone drives it', async () => { - vi.useFakeTimers() - const run = await createFreshRun() - - const submission = run.runtime.sendTerminalAgentPrompt(run.handle, 'start here', { - inputKind: 'launch' - }) - await vi.runAllTimersAsync() - await submission.catch(() => undefined) - - expect(run.writes.length).toBeGreaterThan(0) - expect(run.firstUserInputAt()).toBeNull() - - await run.runtime.sendTerminal(run.handle, { text: 'y' }, { inputKind: 'driving' }) - expect(run.firstUserInputAt()).not.toBeNull() - }) - - it.each([ - ['a terminal reply', '\x1b[3;4R'], - ['focus reports', '\x1b[I\x1b[O'], - ['the focus-in a desktop sends on reattaching a remote pane', '\x1b[I'] - ])('records nothing for stream input that is only %s', async (_label, text) => { - const run = await createFreshRun() - - await sendTerminalStreamInput(run.runtime, { - terminal: run.handle, - text, - client: undefined, - isMobile: false - }) - - expect(run.writes).toHaveLength(1) - expect(run.firstUserInputAt()).toBeNull() - }) - - it('records dashboard preview typing before the write that could end the process', async () => { - const run = await createFreshRun() - - await expect(run.runtime.writeTerminalPreviewInput(PTY_ID, 'exit\r')).resolves.toBe(true) - - expect(run.writes.map((write) => write.inputRecorded)).toEqual([true]) - }) -}) diff --git a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts index a4fe7679d7d..3a58b49be24 100644 --- a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts +++ b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts @@ -15,7 +15,7 @@ import type { RuntimeVisibleTerminalState } from '../records/runtime-terminal-state-records' import type { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' import type { createAgentStatusOscProcessor } from '../../../../shared/agent-status/transport/agent-status-osc' import { RuntimeTerminalViewSubscribers } from '../view/runtime-terminal-view-subscribers' import { MainDaemonAttachments } from './main-daemon-attachments' diff --git a/src/main/runtime/terminal/output/headless-buffer-snapshot.ts b/src/main/runtime/terminal/output/headless-buffer-snapshot.ts index df00b995cb2..6f49d1bc0ea 100644 --- a/src/main/runtime/terminal/output/headless-buffer-snapshot.ts +++ b/src/main/runtime/terminal/output/headless-buffer-snapshot.ts @@ -50,38 +50,55 @@ export abstract class OrcaRuntimeWithSerializeHeadlessTerminalBuffer extends Orc } await state.writeChain await state.ownership.settle() - // Why: normal history is separated from an active alternate frame, so the - // caller's scrollback policy can be honored without painting it into alt. - const scrollbackRows = opts.scrollbackRows ?? 0 - const snapshot = state.emulator.getSnapshot({ scrollbackRows }) - const terminalOwner = state.ownership.owner - const data = snapshot.rehydrateSequences + snapshot.snapshotAnsi - return data.length > 0 || opts.includeEmpty === true - ? this.preferTrackedLastTitle(ptyId, { - data, - frameRestoreAnsi: snapshot.frameRestoreAnsi, - cols: snapshot.cols, - rows: snapshot.rows, - cwd: snapshot.cwd ?? this.terminalCwdByPtyId.get(ptyId), - lastTitle: snapshot.lastTitle, - seq: state.outputSequence, - source: 'headless' as const, - oscLinks: snapshot.oscLinks, - scrollbackAnsi: snapshot.scrollbackAnsi, - // Capture flags at the image's stream position to prevent duplicate/out-of-order replay pushes and pops. - ...(parseTerminalKittyKeyboardFlags(snapshot.modes?.kittyKeyboardFlags) !== undefined - ? { kittyKeyboardFlags: snapshot.modes.kittyKeyboardFlags } - : {}), - ...(snapshot.pendingEscapeTailAnsi - ? { pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi } - : {}), - ...(terminalOwner ? { terminalOwner } : {}), - // Alt snapshots must preserve xterm history used for TUI scroll-up after tab return. - alternateScreen: snapshot.modes?.alternateScreen ?? state.emulator.isAlternateScreen, - // Do not fold into data: the restorer's later reset would abort this partial escape. - pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi - }) - : null + // Capture image and applied progress in the same ordered operation as parsing. + const completion = state.writeChain.then(() => { + const current = + this.headlessTerminals.get(ptyId) ?? + (this.ptysById.get(ptyId)?.connected === true + ? undefined + : this.headlessExitHolds.get(ptyId)?.exited) + if (current !== state) { + return null + } + // Why: normal history is separated from an active alternate frame, so the + // caller's scrollback policy can be honored without painting it into alt. + const scrollbackRows = opts.scrollbackRows ?? 0 + const snapshot = state.emulator.getSnapshot({ scrollbackRows }) + const terminalOwner = state.ownership.owner + const pendingEscapeTailAnsi = + state.rendererSeedSeq !== undefined + ? state.rendererSeedEscapeTail + : snapshot.pendingEscapeTailAnsi + const data = snapshot.rehydrateSequences + snapshot.snapshotAnsi + return data.length > 0 || opts.includeEmpty === true + ? this.preferTrackedLastTitle(ptyId, { + data, + frameRestoreAnsi: snapshot.frameRestoreAnsi, + cols: snapshot.cols, + rows: snapshot.rows, + cwd: snapshot.cwd ?? this.terminalCwdByPtyId.get(ptyId), + lastTitle: snapshot.lastTitle, + seq: state.outputSequence, + source: 'headless' as const, + oscLinks: snapshot.oscLinks, + scrollbackAnsi: snapshot.scrollbackAnsi, + // Capture flags at the image's stream position to prevent duplicate/out-of-order replay pushes and pops. + ...(parseTerminalKittyKeyboardFlags(snapshot.modes?.kittyKeyboardFlags) !== undefined + ? { kittyKeyboardFlags: snapshot.modes.kittyKeyboardFlags } + : {}), + ...(terminalOwner ? { terminalOwner } : {}), + // Alt snapshots must preserve xterm history used for TUI scroll-up after tab return. + alternateScreen: snapshot.modes?.alternateScreen ?? state.emulator.isAlternateScreen, + // Do not fold into data: the restorer's later reset would abort this partial escape. + pendingEscapeTailAnsi + }) + : null + }) + state.writeChain = completion.then( + () => {}, + () => {} + ) + return completion } /** Keeps the PTY's model readable through its exit until released, so a stream mid-publication can still serialize it. */ diff --git a/src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts b/src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts new file mode 100644 index 00000000000..1b3f757e453 --- /dev/null +++ b/src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts @@ -0,0 +1,86 @@ +import { assert, expect, it } from 'vitest' +import { OrcaRuntimeService } from '../../orca-runtime' +import { HeadlessEmulator } from '../../../daemon/emulation/headless-emulator' + +const grid = { cols: 80, rows: 24 } +const partial = 'prompt\r\n> \x1b[?' + +function createRuntime() { + const runtime = new OrcaRuntimeService() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => grid + }) + return runtime +} + +async function replay( + snapshot: { data: string; pendingEscapeTailAnsi?: string } | null, + suffix: string +) { + assert(snapshot) + const restored = new HeadlessEmulator(grid) + try { + await restored.write(snapshot.data) + await restored.write(snapshot.pendingEscapeTailAnsi ?? '') + await restored.write(suffix) + return restored + .getVisibleLines() + .map((line) => line.trimEnd()) + .filter(Boolean) + } finally { + restored.dispose() + } +} + +it('restores a screen and live suffix without repainting a consumed escape continuation', async () => { + const runtime = createRuntime() + const continuation = '1002h\x1b[>4;2m' + try { + runtime.onPtyData('pty-snapshot', partial, 1) + const pending = runtime.serializeHiddenOutputRecoveryBuffer('pty-snapshot') + queueMicrotask(() => runtime.onPtyData('pty-snapshot', continuation, 2)) + const snapshot = await pending + expect(await replay(snapshot, (partial + continuation).slice(snapshot?.seq))).toEqual([ + 'prompt', + '>' + ]) + } finally { + await runtime.onPtyExit('pty-snapshot', 0) + } +}) + +it.each([false, true])( + 'preserves seeded parser state through replay and live output (reset=%s)', + async (reset) => { + const runtime = createRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => grid, + hasRendererSerializer: () => true, + serializeBuffer: async () => ({ data: 'prompt\r\n> ', ...grid, seq: 13 }) + }) + try { + runtime.onPtyData('pty-seed', partial, 1) + let snapshot = await runtime.serializeHiddenOutputRecoveryBuffer('pty-seed') + expect(snapshot?.seq).toBe(13) + if (reset) { + await runtime.resetHeadlessTerminalInputModes('pty-seed') + snapshot = await runtime.serializeHiddenOutputRecoveryBuffer('pty-seed') + } + const continuation = reset ? 'hello' : '1002h' + const expected = reset ? ['prompt', '> hello'] : ['prompt', '>'] + expect(await replay(snapshot, continuation)).toEqual(expected) + + runtime.onPtyData('pty-seed', continuation, 2) + const live = await runtime.serializeHiddenOutputRecoveryBuffer('pty-seed') + expect(await replay(live, '')).toEqual(expected) + } finally { + await runtime.onPtyExit('pty-seed', 0) + } + } +) diff --git a/src/main/runtime/terminal/output/headless-terminal-state.ts b/src/main/runtime/terminal/output/headless-terminal-state.ts index 6df5db366d7..9ea360a80a1 100644 --- a/src/main/runtime/terminal/output/headless-terminal-state.ts +++ b/src/main/runtime/terminal/output/headless-terminal-state.ts @@ -269,6 +269,7 @@ export abstract class OrcaRuntimeWithCreatePtyHeadlessTerminalState extends Orca // Why on the chain: the ground must land after every PTY chunk already queued. const completion = state.writeChain.then(async () => { await state.emulator.write(state.ownership.groundInputModes()) + state.rendererSeedEscapeTail = undefined }) state.writeChain = completion.catch(() => {}) await completion diff --git a/src/main/runtime/terminal/output/host-terminal-scrollback-read.ts b/src/main/runtime/terminal/output/host-terminal-scrollback-read.ts index a4ffa4a7ac1..6cd26cced20 100644 --- a/src/main/runtime/terminal/output/host-terminal-scrollback-read.ts +++ b/src/main/runtime/terminal/output/host-terminal-scrollback-read.ts @@ -1,5 +1,5 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import type { SessionReadTerminalScrollbackResult } from '../../../../shared/rpc-contract/session-terminal-scrollback-params' +import type { SessionReadTerminalScrollbackResult } from '../../../../shared/rpc-contract/session-tabs/session-terminal-scrollback-params' import { TERMINAL_SCROLLBACK_STORE_BYTE_LIMIT } from '../../../../shared/terminal/replay/terminal-scrollback-limits' export type HostTerminalScrollbackReadDeps = { diff --git a/src/main/runtime/terminal/output/provider-buffer-capture.ts b/src/main/runtime/terminal/output/provider-buffer-capture.ts index 14df40219b6..83e28ef9789 100644 --- a/src/main/runtime/terminal/output/provider-buffer-capture.ts +++ b/src/main/runtime/terminal/output/provider-buffer-capture.ts @@ -3,7 +3,7 @@ import type { RuntimeVisibleTerminalState } from '../records/runtime-terminal-state-records' import { OrcaRuntimeWithSerializeTerminalBufferFromAvailableState } from './terminal-buffer-selection' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' import { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' import type { RuntimeTerminalRead } from '../../../../shared/runtime-terminal-contracts' import type { RuntimeProviderSnapshotReadOptions } from './provider-snapshot-read-options' diff --git a/src/main/runtime/terminal/output/runtime-client-scrollback.ts b/src/main/runtime/terminal/output/runtime-client-scrollback.ts index 53ee72e3c5d..c77a69afb89 100644 --- a/src/main/runtime/terminal/output/runtime-client-scrollback.ts +++ b/src/main/runtime/terminal/output/runtime-client-scrollback.ts @@ -1,5 +1,5 @@ import { OrcaRuntimeWithMigrationCatalog } from '../../hosts/migration/runtime-migration-catalog' -import type { SessionReadTerminalScrollbackResult } from '../../../../shared/rpc-contract/session-terminal-scrollback-params' +import type { SessionReadTerminalScrollbackResult } from '../../../../shared/rpc-contract/session-tabs/session-terminal-scrollback-params' import { readHostTerminalScrollback, type HostTerminalScrollbackReadRequest diff --git a/src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts b/src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts index f0f27f9cde0..94edd862714 100644 --- a/src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts +++ b/src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import '../../orca-runtime-tests/runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../../orca-runtime' import '../../orca-runtime-tests/orca-runtime-test-lifecycle.spec' -import { assertTerminalAgentSendable } from '../../rpc/terminal-agent-send-guard' import { HEADLESS_LEAF_ID, TEST_WORKTREE_ID, @@ -170,146 +169,6 @@ describe('display surfaces after the stale-working title clear', () => { }) // Synthetic: a trust dialog painted after the clear, behind the name title `⠋ Claude Code`. - it.each(['mounted', 'mountedEcho', 'rendererless'] as const)( - 'a trust dialog painted after the clear still reads as a wait on the user (%s)', - async (mode) => { - vi.useFakeTimers() - try { - const ptyId = mode === 'rendererless' ? 'bg-pty' : 'pty-1' - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: ptyId }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - let handle: string - if (mode === 'rendererless') { - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - handle = ( - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'bg-tab', - leafId: HEADLESS_LEAF_ID - }) - ).handle - } else { - syncSinglePty(runtime, ptyId, { tabTitle: 'Terminal 1', paneTitle: null }) - runtime.onPtyData(ptyId, 'boot\r\n', Date.now()) - handle = (await runtime.listTerminals()).terminals[0]?.handle ?? '' - } - runtime.onPtyData(ptyId, '\x1b]0;⠋ Claude Code\x07', Date.now()) - if (mode !== 'rendererless') { - syncSinglePty(runtime, ptyId, { tabTitle: '⠋ Claude Code', paneTitle: '⠋ Claude Code' }) - } - runtime.onPtyData(ptyId, 'still running\r\n', Date.now()) - await vi.advanceTimersByTimeAsync(3_000) - if (mode === 'mountedEcho') { - // The renderer republishes its own cleared title, as a mounted pane does. - syncSinglePty(runtime, ptyId, { tabTitle: 'Claude Code', paneTitle: 'Claude Code' }) - } - await vi.advanceTimersByTimeAsync(1_000) - runtime.onPtyData( - ptyId, - '\r\nDo you trust the files in this folder?\r\n /repo/app\r\n 1. Yes, proceed\r\n 2. No, exit\r\n', - Date.now() - ) - await vi.advanceTimersByTimeAsync(1_000) - await expect(runtime.getTerminalAgentStatus(handle)).resolves.toMatchObject({ - isRunningAgent: true, - status: 'permission' - }) - await expect( - assertTerminalAgentSendable({ runtime, handle, assertWritable: () => {} }) - ).rejects.toThrow('terminal_guard_permission') - await expect(runtime.getTerminalInteractiveWait(handle)).resolves.toMatchObject({ - source: 'prompt-text', - reason: 'agent-trust-workspace' - }) - } finally { - vi.useRealTimers() - } - } - ) // Synthetic: prompt verification behind a standing clear judges against the baseline main had. - it.each([ - ['mounted', 'output only', false], - ['mountedEcho', 'output only', false], - ['rendererless', 'output only', false], - ['mounted', 'a new spinner frame', true], - ['mountedEcho', 'a new spinner frame', true], - ['rendererless', 'a new spinner frame', true] - ] as const)( - 'a prompt sent behind a cleared spinner (%s) answered by %s settles as on main', - async (mode, _after, spinnerFrame) => { - vi.useFakeTimers() - try { - const ptyId = mode === 'rendererless' ? 'bg-pty' : 'pty-1' - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: ptyId }), - write: (_ptyId, data) => { - if (data === '\r') { - runtime.onPtyData( - ptyId, - spinnerFrame ? '\x1b]0;⠙ Claude Code\x07' : '\r\n', - Date.now() - ) - } - return true - }, - kill: () => true, - getForegroundProcess: async () => 'claude' - }) - let handle: string - if (mode === 'rendererless') { - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - handle = ( - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'bg-tab', - leafId: HEADLESS_LEAF_ID - }) - ).handle - } else { - syncSinglePty(runtime, ptyId, { tabTitle: 'Terminal 1', paneTitle: null }) - runtime.onPtyData(ptyId, 'boot\r\n', Date.now()) - handle = (await runtime.listTerminals()).terminals[0]?.handle ?? '' - } - runtime.onPtyData(ptyId, '\x1b]0;⠋ Claude Code\x07', Date.now()) - if (mode !== 'rendererless') { - syncSinglePty(runtime, ptyId, { tabTitle: '⠋ Claude Code', paneTitle: '⠋ Claude Code' }) - } - runtime.onPtyData(ptyId, 'still running\r\n', Date.now()) - await vi.advanceTimersByTimeAsync(3_000) - if (mode === 'mountedEcho') { - syncSinglePty(runtime, ptyId, { tabTitle: 'Claude Code', paneTitle: 'Claude Code' }) - } - if (spinnerFrame) { - // The receipt path takes no output as evidence, so only a new turn settles it. - const submission = runtime.sendTerminalAgentPrompt(handle, 'review this', { - inputKind: 'driving', - acceptQueued: true, - requestId: `after-clear-${mode}` - }) - await vi.advanceTimersByTimeAsync(20_000) - await expect(submission).resolves.toMatchObject({ - prompt: { stages: ['input_accepted', 'turn_started'] } - }) - } else { - // Output after Enter is not a turn start, so a swallowed Enter still reads as stalled. - const submission = runtime.sendTerminalAgentPrompt(handle, 'review this', { - inputKind: 'driving' - }) - const rejected = expect(submission).rejects.toThrow('agent_prompt_stalled') - // Past the 30 s effect window. - await vi.advanceTimersByTimeAsync(40_000) - await rejected - } - } finally { - vi.useRealTimers() - } - } - ) }) diff --git a/src/main/runtime/terminal/output/terminal-buffer-operations.ts b/src/main/runtime/terminal/output/terminal-buffer-operations.ts index a1260a785f3..ec18630b005 100644 --- a/src/main/runtime/terminal/output/terminal-buffer-operations.ts +++ b/src/main/runtime/terminal/output/terminal-buffer-operations.ts @@ -1,4 +1,4 @@ -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' import type { HeadlessSeedMetadata, ProviderTerminalBufferWait, diff --git a/src/main/runtime/terminal/output/terminal-buffer-selection.ts b/src/main/runtime/terminal/output/terminal-buffer-selection.ts index 47b36d163c6..ff42e6edb03 100644 --- a/src/main/runtime/terminal/output/terminal-buffer-selection.ts +++ b/src/main/runtime/terminal/output/terminal-buffer-selection.ts @@ -1,6 +1,6 @@ import { OrcaRuntimeWithCreatePtyHeadlessTerminalState } from './headless-terminal-state' import type { TerminalOscLinkRange } from '../../../../shared/terminal/links/terminal-osc-link-ranges' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' import type { ProviderTerminalBufferWait } from '../records/runtime-terminal-state-records' import { withTimeout } from '../../../../shared/promise-timeout-fallback' import { AUTHORITATIVE_TERMINAL_SNAPSHOT_TIMEOUT_MS } from './provider-snapshot-budget' diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 7c350e70396..403f3032430 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -9,7 +9,7 @@ import { parseLegacyNumericPaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { RecentPtyOutputBuffer } from './recent-pty-output-buffer' import type { ProjectExecutionRuntimeResolution } from '../../../../shared/execution-host/project-execution-runtime' import { resolveLocalProjectRuntimeForWorktreeId } from '../../../workspaces/execution-host/local-project-runtime-resolution' diff --git a/src/main/runtime/terminal/output/terminal-transient-facts.ts b/src/main/runtime/terminal/output/terminal-transient-facts.ts index 4d131eff4ed..8fca1181344 100644 --- a/src/main/runtime/terminal/output/terminal-transient-facts.ts +++ b/src/main/runtime/terminal/output/terminal-transient-facts.ts @@ -1,5 +1,5 @@ import { OrcaRuntimeWithScheduleWaitBlockedCheck } from '../wait/terminal-wait-blocked-checks' -import type { PtyTransientFact } from '../../../providers/pty-provider-events' +import type { PtyTransientFact } from '../../../providers/pty/events' import type { TerminalSideEffectBatch, TerminalSideEffectFact diff --git a/src/main/runtime/terminal/query/pty-terminal-summary.ts b/src/main/runtime/terminal/query/pty-terminal-summary.ts index 5d49d792e0f..559e76f1cd8 100644 --- a/src/main/runtime/terminal/query/pty-terminal-summary.ts +++ b/src/main/runtime/terminal/query/pty-terminal-summary.ts @@ -19,7 +19,7 @@ import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import { ptyHoldsRecordedSurface, type PtySurfaceTopology diff --git a/src/main/runtime/terminal/query/terminal-list-execution-host-scope.spec.ts b/src/main/runtime/terminal/query/terminal-list-execution-host-scope.spec.ts index a047ffdd124..c9cc115a3a7 100644 --- a/src/main/runtime/terminal/query/terminal-list-execution-host-scope.spec.ts +++ b/src/main/runtime/terminal/query/terminal-list-execution-host-scope.spec.ts @@ -5,7 +5,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import '../../../../shared/workspace-scope' import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' import { type ExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' export function registerTerminalListExecutionHostScopeTests(): void { // A scoped list must identify its hosts so omitting a live remote worker cannot be mistaken for exit. diff --git a/src/main/runtime/terminal/records/runtime-leaf-record-projection.ts b/src/main/runtime/terminal/records/runtime-leaf-record-projection.ts index 5e13b11a881..08df636e05d 100644 --- a/src/main/runtime/terminal/records/runtime-leaf-record-projection.ts +++ b/src/main/runtime/terminal/records/runtime-leaf-record-projection.ts @@ -4,16 +4,16 @@ import type { PtyLivenessVerdict } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import type { RuntimeSyncedTab } from '../../../../shared/runtime-session-contracts' import { resolveTerminalTabTitle } from '../../../../shared/tab-title-resolution' -import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' -import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load-types' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' import { paneKeyOf, tabsInOrder, type LayoutTerminalTab } from '../../../../shared/workspace-layout/workspace-layout-model' -import type { PaneTerminalFact } from '../../../../shared/workspace-layout/workspace-layout-pane-status' -import { resolveWorkspaceSelection } from '../../../../shared/workspace-layout/workspace-layout-views' -import { pickStoredFields } from '../../../../shared/workspace-layout/stored-record-fields' +import type { PaneTerminalFact } from '../../../../shared/workspace-layout/commands/workspace-layout-pane-status' +import { resolveWorkspaceSelection } from '../../../../shared/workspace-layout/client-views/workspace-layout-views' +import { pickStoredFields } from '../../../../shared/workspace-layout/persistence/stored-record-fields' import type { RuntimeLeafRecord, RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' import { getPtyTerminalState } from '../wait/terminal-wait-results' diff --git a/src/main/runtime/terminal/records/runtime-terminal-state-records.ts b/src/main/runtime/terminal/records/runtime-terminal-state-records.ts index 0fdfbcbff13..4487e3a30d2 100644 --- a/src/main/runtime/terminal/records/runtime-terminal-state-records.ts +++ b/src/main/runtime/terminal/records/runtime-terminal-state-records.ts @@ -13,7 +13,7 @@ import type { TerminalTitleTracker } from '../../../../shared/terminal/output/te import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { TerminalAgent } from '../../../../shared/agent-status/identity/terminal-agent' import type { HeadlessEmulator } from '../../../daemon/emulation/headless-emulator' -import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' +import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' import type { RetainedTailRedrawCursor } from '../output/tail/terminal-tail-redraw-buffer' import type { TerminalTailWaitState } from '../wait/terminal-wait-tail-state' import type { TerminalCommandPaint } from '../input/terminal-command-paint' diff --git a/src/main/runtime/terminal/recovery/held-pane-reopen.ts b/src/main/runtime/terminal/recovery/held-pane-reopen.ts index 87350e486ae..e18158bdd86 100644 --- a/src/main/runtime/terminal/recovery/held-pane-reopen.ts +++ b/src/main/runtime/terminal/recovery/held-pane-reopen.ts @@ -1,7 +1,7 @@ // For paired desktop Reopen, stop held newer services, then start still-held panes; main's frames carry the result. import type { NewerDaemonReopenResult } from '../../../../shared/newer-daemon-hold' -import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import type { RestoredPane } from './restored-pane-start' /** The pane is 'held' in the layouts main publishes: the status a paired desktop's banner shows. */ diff --git a/src/main/runtime/terminal/recovery/shutdown-reconnect-facts.ts b/src/main/runtime/terminal/recovery/shutdown-reconnect-facts.ts index 1b584b21715..e3fd6e64fb1 100644 --- a/src/main/runtime/terminal/recovery/shutdown-reconnect-facts.ts +++ b/src/main/runtime/terminal/recovery/shutdown-reconnect-facts.ts @@ -4,7 +4,7 @@ import { isPaneSleepRecord } from '../../../../shared/agent-session/lifecycle/ag import { isOwnedSshTargetId } from '../../../../shared/execution-host' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' import type { SshConnectionStatus } from '../../../../shared/ssh-types' -import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' export type ShutdownReconnectFacts = Pick< diff --git a/src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts b/src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts deleted file mode 100644 index b024e777b7d..00000000000 --- a/src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -// Queued pre-sleep hook writes must not replace the newer saved sleep record. -import { describe, expect, it, vi } from 'vitest' -import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { LayoutApplyOutcome } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' -import type { WorktreeSleepResumeCapture } from './worktree-sleep-resume-records' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -// Preserve side-effect order: mocks, lifecycle, fixtures. -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../../orca-runtime') -await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const PANE_KEY = `host-tab:${HEADLESS_LEAF_ID}` -const PTY_ID = 'pty-slept' -const SESSION = { key: 'session_id' as const, id: 'codex-session-1' } - -function codexRow(overrides: Partial = {}): AgentStatusIpcPayload { - return { - paneKey: PANE_KEY, - worktreeId: TEST_WORKTREE_ID, - agentType: 'codex', - providerSession: SESSION, - state: 'working', - prompt: 'keep working', - receivedAt: 10, - stateStartedAt: 10, - connectionId: null, - ...overrides - } -} - -function makeRuntimeWithSlowFirstWrite() { - const { runtimeStore, getSession, setSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal() - ) - let releaseFirstWrite = (): void => {} - const firstWriteDurable = new Promise((resolve) => { - releaseFirstWrite = resolve - }) - const firstWriteEntered = Promise.withResolvers() - let writes = 0 - const applyLayoutCommand = vi.fn( - async ( - command: Parameters[2], - hostIds: ExecutionHostId[] - ): Promise => { - for (const hostId of hostIds) { - const change = applyCommandToSession(hostId, getSession(), command) - if (change.session) { - setSession(change.session) - } - } - writes += 1 - if (writes === 1) { - firstWriteEntered.resolve() - await firstWriteDurable - } - return { ok: true, result: {} } - } - ) - const runtime = new OrcaRuntimeService(Object.assign(runtimeStore, { applyLayoutCommand })) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - return { runtime, getSession, releaseFirstWrite, firstWriteEntered: firstWriteEntered.promise } -} - -function sleepCapture(updatedAt: number): WorktreeSleepResumeCapture { - return new Map([ - [ - PTY_ID, - { - retiredPaneKeys: [], - records: [ - { - paneKey: PANE_KEY, - tabId: 'host-tab', - worktreeId: TEST_WORKTREE_ID, - agent: 'codex', - providerSession: SESSION, - prompt: 'keep working', - state: 'done', - capturedAt: 20, - updatedAt, - origin: 'worktree-sleep', - restoreOnTabOpenOnly: true, - connectionId: null - } - ] - } - ] - ]) -} - -describe('a queued hook status and a workspace sleep', () => { - it('keeps the sleep’s record when a status accepted before the sleep is written after it', async () => { - const { runtime, getSession, releaseFirstWrite, firstWriteEntered } = - makeRuntimeWithSlowFirstWrite() - runtime.recordHookStatusResume(codexRow()) - await firstWriteEntered - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeDefined() - runtime.recordHookStatusResume(codexRow({ state: 'blocked', receivedAt: 11 })) - - const slept = runtime['sleepResumeRecords'].persist(TEST_WORKTREE_ID, sleepCapture(11), [ - PTY_ID - ]) - releaseFirstWrite() - await slept - await runtime['hookStatusResumeWrites'] - - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toMatchObject({ - origin: 'worktree-sleep', - state: 'done', - restoreOnTabOpenOnly: true - }) - }) - - it('keeps a window sleep’s record when a status accepted before it is written after it', async () => { - const { runtime, getSession, releaseFirstWrite, firstWriteEntered } = - makeRuntimeWithSlowFirstWrite() - runtime.recordHookStatusResume(codexRow()) - await firstWriteEntered - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeDefined() - runtime.recordHookStatusResume(codexRow({ state: 'blocked', receivedAt: 11 })) - - const [record] = sleepCapture(11).get(PTY_ID)!.records - const slept = runtime.applyLayoutCommand({ - type: 'sleep', - workspace: TEST_WORKTREE_ID, - tabId: 'host-tab', - paneKeys: [PANE_KEY], - records: [record!] - }) - releaseFirstWrite() - await slept - await runtime['hookStatusResumeWrites'] - - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toMatchObject({ - origin: 'worktree-sleep', - state: 'done' - }) - }) -}) - -it.each([false, true])( - 'orders refused cleanup after queued status and preserves newer same-conversation recipe (%s)', - async (newer) => { - const { runtime, getSession, releaseFirstWrite } = makeRuntimeWithSlowFirstWrite() - runtime.recordHookStatusResume(codexRow()) - await vi.waitFor(() => - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeDefined() - ) - runtime.recordHookStatusResume(codexRow({ state: 'blocked', receivedAt: 11 })) - const sourcePromise = runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) - releaseFirstWrite() - const source = await sourcePromise - if (!source) { - throw new Error('missing captured source') - } - const refused = { - agent: 'codex' as const, - providerSession: SESSION, - expectedStatus: { paneKey: PANE_KEY, receivedAt: 11, stateStartedAt: 10 }, - expectedSavedRecord: { - paneKey: PANE_KEY, - capturedAt: source.capturedAt, - updatedAt: source.updatedAt - } - } - if (newer) { - runtime.recordHookStatusResume(codexRow({ receivedAt: 30, prompt: 'new explicit C' })) - } - await runtime.forgetRefusedSavedResume(TEST_WORKTREE_ID, PANE_KEY, refused, source) - await runtime['hookStatusResumeWrites'] - const record = getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY] - if (newer) { - expect(record).toMatchObject({ prompt: 'new explicit C', updatedAt: 30 }) - } else { - expect(getSession().sleepingAgentSessionsByPaneKey).toEqual({}) - } - } -) diff --git a/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts b/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts index c459c274c5e..9eb24a087e3 100644 --- a/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts +++ b/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts @@ -17,9 +17,9 @@ import { import { ptyIncarnationById, ptyOwnership } from '../../../ipc/pty/provider/ownership-state' import { getLocalPtyProvider, setLocalPtyProvider } from '../../../ipc/pty/provider/registry' import { createPtyIpcSession } from '../../../ipc/pty/session' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { OrcaRuntimeService } from '../../orca-runtime' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' + import { INCARNATION_ID, LEAF_ID, @@ -30,11 +30,10 @@ import { WORKTREE_PATH, makeSession } from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' const REPLACEMENT_PTY_ID = 'pty-close-continuity-replacement' const REPLACEMENT_INCARNATION_ID = '77777777-7777-4777-8777-777777777777' -const LATER_INCARNATION_ID = '88888888-8888-4888-8888-888888888888' const directories: string[] = [] const stores: Store[] = [] @@ -186,18 +185,6 @@ describe('intentional stops keep the pane through the exit', () => { ]) }) - it('retires the pane on a daemon-wide exit that no restart claims', () => { - const harness = createHarness() - - harness.emitDaemonRestartExit() - - // Switch-on, main keeps the pane as the window does on a -1 no host confirmed (lost contact). - expect(harness.boundPtyId()).toBe(ORCA_LAYOUT_OWNER_IS_MAIN ? PTY_ID : null) - expect(harness.rendererExits()).toEqual([ - { id: PTY_ID, code: -1, incarnationId: INCARNATION_ID, hostId: 'local' } - ]) - }) - it('keeps the pane through the synthetic exit and the provider exit that follows it', async () => { const harness = createHarness({ lateProviderExit: true }) @@ -217,37 +204,6 @@ describe('intentional stops keep the pane through the exit', () => { ]) }) - it('never reads the exit of a later process on the same id as the stop', async () => { - const harness = createHarness({ lateProviderExit: true }) - await stopRendererOwnedPty(harness.deps, { id: PTY_ID, keepHistory: true }) - // The later process's commit binds its pane before it registers, as the spawn commit does. - await harness.store.persistPtyBinding({ - worktreeId: WORKTREE_ID, - tabId: TAB_ID, - leafId: LEAF_ID, - ptyId: PTY_ID, - incarnationId: LATER_INCARNATION_ID, - origin: 'reattach' - }) - harness.runtime.registerPty(PTY_ID, WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: LATER_INCARNATION_ID - }) - ptyIncarnationById.set(PTY_ID, LATER_INCARNATION_ID) - - harness.emitProviderExit(LATER_INCARNATION_ID) - - // Why wait: an unstopped exit retires the pane through an async durable save. - await vi.waitFor(() => expect(harness.boundPtyId()).toBeNull()) - expect(harness.rendererExits().at(-1)).toEqual({ - id: PTY_ID, - code: 0, - incarnationId: LATER_INCARNATION_ID, - hostId: 'local' - }) - }) - it('keeps the tab and its wake binding when the runtime puts the worktree to sleep', async () => { const harness = createHarness({ folder: true }) const inventories = [[{ id: PTY_ID, worktreeId: WORKTREE_ID, cwd: WORKTREE_PATH, title: 'a' }]] diff --git a/src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts b/src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts deleted file mode 100644 index fd8618e5025..00000000000 --- a/src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -// An update counts the server's terminals, then stops it: a terminal started between the two -// would die with the stop, uncounted. The last census closes admission so none can start. -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { z } from 'zod' -import { - ORCAD_UPDATE_ADMISSION_FENCE_MS, - OrcadTerminalCensusParamsSchema -} from '../../../../shared/orcad-terminal-census' -import { spawnWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' -import { ORCAD_TERMINAL_CENSUS_METHODS } from '../../rpc/methods/orcad/orcad-terminal-census' -import { TERMINAL_UPDATE_ADMISSION_CLOSED_MESSAGE } from './terminal-update-admission' - -const { collect, listLiveDaemonPtyIds } = vi.hoisted(() => ({ - collect: vi.fn(), - listLiveDaemonPtyIds: vi.fn<() => Promise>() -})) -vi.mock('../../../orcad/orcad-terminal-census', () => ({ collectOrcadTerminalCensus: collect })) -vi.mock('../../../daemon/providers/lifecycle/daemon-provider-state', () => ({ - listLiveDaemonPtyIds -})) - -// Fragments stay side-effect ordered: mocks, then lifecycle, then fixtures. -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../../orca-runtime') -await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { TEST_WORKTREE_ID, store } = - await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const idle = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 7 } -const target = spawnWorktreeTarget(TEST_WORKTREE_ID, null) - -type CensusRequest = Omit, 'activatedAt'> - -function census(runtime: InstanceType, params: CensusRequest) { - // Parsed as the server parses it, so a field the server does not know is dropped here too. - const parsed = OrcadTerminalCensusParamsSchema.parse({ activatedAt: 1, ...params }) - return ORCAD_TERMINAL_CENSUS_METHODS[0]!.handler(parsed, { runtime }) -} - -// What the SSH and WSL updates send as the last count before the stop. -const updateRecount: CensusRequest = { - releaseFinishedAutomationTerminals: true, - closeAdmissionForMs: ORCAD_UPDATE_ADMISSION_FENCE_MS -} - -afterEach(() => { - collect.mockReset() - listLiveDaemonPtyIds.mockReset() -}) - -describe("an update's last terminal census", () => { - it('counts only after a spawn admitted before it has finished starting', async () => { - collect.mockResolvedValue({ ...idle, liveSessions: 1 }) - const runtime = new OrcaRuntimeService(store) - const releaseSpawn = await runtime.acquireWorktreeTerminalSpawn(target) - - const counted = census(runtime, updateRecount) - await vi.waitFor(() => expect(runtime.terminalUpdateAdmission.isClosed()).toBe(true)) - expect(collect).not.toHaveBeenCalled() - releaseSpawn() - - await expect(counted).resolves.toMatchObject({ liveSessions: 1 }) - }) - - it('still lets a client reattach a session the daemon runs, but not one it cannot vouch for', async () => { - collect.mockResolvedValue({ ...idle, liveSessions: 1 }) - const runtime = new OrcaRuntimeService(store) - await census(runtime, updateRecount) - - listLiveDaemonPtyIds.mockResolvedValue(['pty-live']) - const requireAttachOnly = vi.fn() - const release = await runtime.acquireWorktreeTerminalSpawn(target, { - reattachSessionId: 'pty-live', - requireAttachOnly - }) - release() - // Should the session exit before the attach lands, the spawn fails instead of starting one. - expect(requireAttachOnly).toHaveBeenCalledTimes(1) - listLiveDaemonPtyIds.mockResolvedValue(null) - await expect( - runtime.acquireWorktreeTerminalSpawn(target, { reattachSessionId: 'pty-live' }) - ).rejects.toThrow(TERMINAL_UPDATE_ADMISSION_CLOSED_MESSAGE) - }) -}) diff --git a/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts b/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts deleted file mode 100644 index 126ad8e8c4f..00000000000 --- a/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import '../../orca-runtime-tests/runtime-test-module-registration.spec' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { OrcaRuntimeService } from '../../orca-runtime' -import { OrchestrationDb } from '../../orchestration/db/orchestration-db' -import '../../orchestration/db/contract-constants' -import '../../orchestration/db/messages/mailbox-routing-page' -import '../../orchestration/db/dispatch-row-writer' -import '../../orchestration/db/attempt-outcome-projection' -import { - openTopologyStoreWithAuthority, - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' -import { expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -class MainCrewRuntime extends OrcaRuntimeService { - seedPty(id: string, handle: string): void { - this.recordPtyWorktree(id, FIXTURE_GIT_WORKTREE_ID, { connected: true }) - this.terminalIdentity.bindPty(id, handle) - this.terminalIdentity.setHandle(handle, { - handle, - runtimeId: this.runtimeId, - rendererGraphEpoch: this.rendererGraphEpoch, - worktreeId: FIXTURE_GIT_WORKTREE_ID, - tabId: `pty:${id}`, - leafId: `pty:${id}`, - ptyId: id, - ptyGeneration: 0 - }) - } -} - -it('retires raw main bindings on real Store-only writes with Crew as sole observer and no installed graph', async () => { - for (const population of [3, 30]) { - const directory = mkdtempSync(join(tmpdir(), 'orca-pr34890-main-')) - const { store, authority } = await openTopologyStoreWithAuthority( - directory, - emptyTerminalSessionProfile() - ) - const db = new OrchestrationDb(':memory:') - let stop = () => {} - try { - const saved = new WindowSession(getDefaultWorkspaceSession()) - for (let i = 0; i < population; i++) { - const leaf = `aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` - saved.addTab(FIXTURE_GIT_WORKTREE_ID, `tab-main-${i}`, leaf) - saved.bind(`tab-main-${i}`, leaf, `pty-main-${i}`) - } - store.setWorkspaceSession(saved.snapshot(), 'local') - await store.flushPendingOrThrowAsync() - const runtime = new MainCrewRuntime(store) - runtime.setOrchestrationDb(db) - runtime.seedPty('coord', 'term_coord') - for (let i = 0; i < population; i++) { - runtime.seedPty(`pty-main-${i}`, `term_main_${i}`) - } - runtime.seedPty('replacement', 'term_replacement') - const pane = 'tab-main-0:aaaaaaaa-aaaa-4aaa-8aaa-000000000000' - const run = db.createRun({ - objective: 'Main source', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'coord-pane' - }) - db.createDispatchContext({ - taskId: db.createTask({ runId: run.id, spec: 'Main worker' }).id, - assigneeHandle: 'term_missing_stored', - assigneePaneKey: pane, - creator: { kind: 'system' }, - maxDepth: 10 - }) - const capture = vi.spyOn(runtime, 'createTerminalIdentityRawInputs') - const generations = vi.spyOn(store, 'getPtyBindingGeneration') - stop = runtime.watchOrchestrationCrew(() => {}) - const read = () => runtime.getOrchestrationCrewSnapshot('term_coord').sections.managing[0] - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_main_0' }) - expect(runtime.getTerminalHandleForPaneKey(pane)).toBe('term_main_0') - read() - const initial = capture.mock.calls.length - const visits = generations.mock.calls.length - const irrelevant = store.getWorkspaceSession() - store.setWorkspaceSession({ ...irrelevant, activeTabId: 'tab-main-1' }, 'local') - await store.flushPendingOrThrowAsync() - read() - expect(capture).toHaveBeenCalledTimes(initial) - expect(generations.mock.calls.length - visits).toBe(population) - await store.applyLayoutCommand({ - type: 'renameTab', - workspace: FIXTURE_GIT_WORKTREE_ID, - tabId: 'tab-main-0', - kind: 'custom', - title: 'Named main worker' - }) - expect(read().label).toBe( - runtime.orchestrationSenderNames.nameOf( - { address: 'term_main_0', terminalHandle: 'term_main_0', orcaSessionId: null }, - undefined, - 'Main worker', - null - ) ?? 'Main worker' - ) - expect(capture).toHaveBeenCalledTimes(initial) - const current = store.getWorkspaceSession() - const layout = current.terminalLayoutsByTabId['tab-main-0'] - store.setWorkspaceSession( - { - ...current, - terminalLayoutsByTabId: { - ...current.terminalLayoutsByTabId, - 'tab-main-0': { - ...layout, - ptyIdsByLeafId: { - ...layout.ptyIdsByLeafId, - 'aaaaaaaa-aaaa-4aaa-8aaa-000000000000': 'replacement' - } - } - } - }, - 'local' - ) - await store.flushPendingOrThrowAsync() - expect(runtime.getTerminalHandleForPaneKey(pane)).toBe('term_replacement') - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) - expect(capture.mock.calls.length).toBeGreaterThan(initial) - const leaf = 'aaaaaaaa-aaaa-4aaa-8aaa-000000000000' - const beforeGeneration = store.getPtyBindingGeneration('local', leaf) ?? 0 - const beforeCapture = capture.mock.calls.length - const binding = { - worktreeId: FIXTURE_GIT_WORKTREE_ID, - tabId: 'tab-main-0', - leafId: leaf, - ptyId: 'replacement', - correctStartupCwd: '/main-source' - } - expect(await store.persistPtyBinding(binding, 'local')).toBe(true) - expect(store.getPtyBindingGeneration('local', leaf)).toBe(beforeGeneration + 1) - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) - expect(capture.mock.calls.length).toBeGreaterThan(beforeCapture) - const stable = capture.mock.calls.length - authority.failNextWrite() - await expect( - store.persistPtyBinding({ ...binding, correctStartupCwd: '/rolled-back' }, 'local') - ).rejects.toThrow('profile_state_write_failed') - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) - expect( - store.getWorkspaceSession().tabsByWorktree[FIXTURE_GIT_WORKTREE_ID][0].startupCwd - ).toBe('/main-source') - read() - expect(capture.mock.calls.length).toBeLessThanOrEqual(stable + 1) - runtime.seedPty('reentrant', 'term_reentrant') - const seen: (string | null)[] = [] - const stopReentrant = store.onWorkspaceSessionWritten(() => { - seen.push(runtime.getTerminalHandleForPaneKey(pane)) - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_reentrant' }) - }) - try { - const reentrant = structuredClone(store.getWorkspaceSession()) - reentrant.terminalLayoutsByTabId['tab-main-0'].ptyIdsByLeafId = { [leaf]: 'reentrant' } - store.setWorkspaceSession(reentrant, 'local') - await store.flushPendingOrThrowAsync() - expect(seen).toEqual(['term_reentrant']) - } finally { - stopReentrant() - } - expect( - runtime.getTerminalHandleForPaneKey('absent:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb') - ).toBeNull() - } finally { - stop() - db.close() - await store.freezeWritesAsync() - rmSync(directory, { recursive: true, force: true }) - } - } -}) diff --git a/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts b/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts index eb8a038203e..c3f0f57f7e6 100644 --- a/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts +++ b/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts @@ -5,9 +5,9 @@ import { repairMobileSessionTabGroupsAfterRetirement, type RetiredTerminalSurface } from './mobile-session-terminal-retirement' -import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-layout-leaf-retirement' +import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-leaf-retirement' import { rebaseWorkspaceSessionTerminalMembership } from './workspace-session-terminal-membership-authority' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' function visibleTypeForContentType( contentType: string | undefined diff --git a/src/main/runtime/terminal/surface/mobile-session-terminal-projection.ts b/src/main/runtime/terminal/surface/mobile-session-terminal-projection.ts index df6823d1c71..5c8a38adfc5 100644 --- a/src/main/runtime/terminal/surface/mobile-session-terminal-projection.ts +++ b/src/main/runtime/terminal/surface/mobile-session-terminal-projection.ts @@ -5,7 +5,7 @@ import { resolveTerminalTabTitle } from '../../../../shared/tab-title-resolution import { readCanonicalPtyOwners, resolveCanonicalPtyClaim -} from '../../../../shared/workspace-layout/legacy-terminal-row-claims' +} from '../../../../shared/workspace-layout/terminal-topology/legacy-terminal-row-claims' import { cloneTerminalLayoutSnapshot, collectPersistedTerminalLeafIds, diff --git a/src/main/runtime/terminal/surface/mobile-session-terminal-retirement-proof.ts b/src/main/runtime/terminal/surface/mobile-session-terminal-retirement-proof.ts index 82c45a70ce1..1be2c3cb1bc 100644 --- a/src/main/runtime/terminal/surface/mobile-session-terminal-retirement-proof.ts +++ b/src/main/runtime/terminal/surface/mobile-session-terminal-retirement-proof.ts @@ -6,7 +6,7 @@ import { appendRetiredTerminalSurfaceProofs, dropRetirementProofsForLiveSurfaces, retirementProofKey -} from '../../../../shared/workspace-layout/terminal-retirement-proof-ledger' +} from '../../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' /** Carry durable host close proofs through renderer snapshots. Inherit worktreeInstanceId on identity-less host writes * so renderer(A) -> host -> renderer(B) cannot launder A's proofs into B. */ diff --git a/src/main/runtime/terminal/surface/mobile-session-terminal-retirement.ts b/src/main/runtime/terminal/surface/mobile-session-terminal-retirement.ts index fb25bc772a5..c7d48fd6816 100644 --- a/src/main/runtime/terminal/surface/mobile-session-terminal-retirement.ts +++ b/src/main/runtime/terminal/surface/mobile-session-terminal-retirement.ts @@ -8,8 +8,8 @@ import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/runtime-mobile-session-tab-contracts' import type { TabGroupLayoutNode } from '../../../../shared/tab-types' -import { appendRetiredTerminalSurfaceProofs } from '../../../../shared/workspace-layout/terminal-retirement-proof-ledger' -import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-layout-leaf-retirement' +import { appendRetiredTerminalSurfaceProofs } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' +import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-leaf-retirement' export type RetiredTerminalSurface = { worktreeId: string diff --git a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts b/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts deleted file mode 100644 index 8e8d61f4e22..00000000000 --- a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { vi } from 'vitest' - -// Main-owned layout variant: registration must publish once without waiting for a later frame. -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -await import('./orca-runtime-cold-restore-terminal-membership.test') diff --git a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts b/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts deleted file mode 100644 index f3fdadcd7d2..00000000000 --- a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts +++ /dev/null @@ -1,568 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' -import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/runtime-mobile-session-tab-contracts' -import type { - RuntimeMobileSessionTabsResult, - RuntimeMobileSessionTabsSnapshot -} from '../../../../shared/runtime-session-contracts' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { OrcaRuntimeService } from '../../orca-runtime' -import { setRuntimeDesktopSurface } from '../../construction/runtime-desktop-surface' -import { withDurableRuntimeStore } from '../../orca-runtime-tests/runtime-durable-store-fixture' -import { bindPaneFirst } from '../../orca-runtime-tests/bind-first-pane.test-fixture' - -import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' - -const WORKTREE_ID = 'repo::/worktree' -const REPO_ID = 'repo' -const LEFT = '11111111-1111-4111-8111-111111111111' -const RIGHT = '22222222-2222-4222-8222-222222222222' -const SPLIT_ROOT = { - type: 'split' as const, - direction: 'vertical' as const, - first: { type: 'leaf' as const, leafId: LEFT }, - second: { type: 'leaf' as const, leafId: RIGHT } -} - -type RestoreHost = { - repo: { - id: string - path: string - displayName: string - badgeColor: string - addedAt: number - connectionId?: string - executionHostId?: ExecutionHostId - } - hostId: ExecutionHostId - connectionId: string | null - ptyIds: { left: string; right: string } - /** SSH relaunch can register before its persisted PTY binding. */ - persistsPtyBindings: boolean -} - -const LOCAL_HOST: RestoreHost = { - repo: { id: REPO_ID, path: '/worktree', displayName: 'repo', badgeColor: 'blue', addedAt: 1 }, - hostId: LOCAL_EXECUTION_HOST_ID, - connectionId: null, - ptyIds: { left: 'pty-left', right: 'pty-right' }, - persistsPtyBindings: true -} -const SSH_HOST: RestoreHost = { - repo: { ...LOCAL_HOST.repo, connectionId: 'ssh-1' }, - hostId: 'ssh:ssh-1', - connectionId: 'ssh-1', - ptyIds: { left: 'ssh:ssh-1@@pty-left', right: 'ssh:ssh-1@@pty-right' }, - persistsPtyBindings: false -} -const RUNTIME_HOST: RestoreHost = { - ...LOCAL_HOST, - repo: { ...LOCAL_HOST.repo, executionHostId: 'runtime:env-1' }, - hostId: 'runtime:env-1' -} - -// Restore saved split and host-authoritative membership before any PTY registers. -function makeColdRestoredSession(host: RestoreHost): WorkspaceSessionState { - return { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: 'tab', - ptyId: host.persistsPtyBindings ? host.ptyIds.left : null, - worktreeId: WORKTREE_ID, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - tab: { - root: SPLIT_ROOT, - activeLeafId: LEFT, - expandedLeafId: null, - ptyIdsByLeafId: host.persistsPtyBindings - ? { [LEFT]: host.ptyIds.left, [RIGHT]: host.ptyIds.right } - : {} - } - }, - terminalTopologyRevisionByRepoId: { [REPO_ID]: 2 } - } -} - -function makeRendererFrame( - host: RestoreHost, - options: { - version?: number - leaves?: readonly string[] - extraTabs?: readonly RuntimeMobileSessionSnapshotTab[] - } = {} -): RuntimeMobileSessionTabsSnapshot { - const leaves = options.leaves ?? [LEFT, RIGHT] - const ptyIdByLeaf: Record = { - [LEFT]: host.ptyIds.left, - [RIGHT]: host.ptyIds.right - } - const parentLayout = { - root: leaves.length === 2 ? SPLIT_ROOT : { type: 'leaf' as const, leafId: leaves[0] }, - activeLeafId: leaves[0], - expandedLeafId: leaves[0], - ptyIdsByLeafId: Object.fromEntries(leaves.map((leafId) => [leafId, ptyIdByLeaf[leafId]])) - } - const extraTabs = options.extraTabs ?? [] - return { - worktree: WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: options.version ?? 1, - activeGroupId: 'group', - activeTabId: `tab::${leaves[0]}`, - activeTabType: 'terminal', - tabGroups: [ - { id: 'group', activeTabId: 'tab', tabOrder: ['tab', ...extraTabs.map((tab) => tab.id)] } - ], - tabs: [ - ...leaves.map((leafId, index) => ({ - type: 'terminal' as const, - id: `tab::${leafId}`, - parentTabId: 'tab', - leafId, - ptyId: ptyIdByLeaf[leafId], - title: leafId === LEFT ? 'Left' : 'Right', - parentLayout, - isActive: index === 0 - })), - ...extraTabs - ] - } -} - -const RENDERER_TABS = [ - { - tabId: 'tab', - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: LEFT, - layout: SPLIT_ROOT - } -] - -function publishRendererFrame( - runtime: OrcaRuntimeService, - frame: RuntimeMobileSessionTabsSnapshot -): ReturnType { - return runtime.syncWindowGraph(1, { tabs: RENDERER_TABS, leaves: [], mobileSessionTabs: [frame] }) -} - -function coldRestoredRuntime(host: RestoreHost = LOCAL_HOST): { - runtime: OrcaRuntimeService - sessions: Map -} { - const sessions = new Map([ - [host.hostId, makeColdRestoredSession(host)] - ]) - // Live windows own tab publications; main must not rebuild them from persistence. - const liveWindow = { - isDestroyed: () => false, - webContents: { isDestroyed: () => false, send: () => {} } - } - setRuntimeDesktopSurface({ - showNotification: () => false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime reads only liveness and send off its authoritative window on these paths. - findWindowById: () => liveWindow as never, - onIpc: () => {}, - removeIpcListener: () => {} - }) - const runtime = new OrcaRuntimeService( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the list, fence, exit and close paths read only repos and the workspace session; the rest of Store is unreached. - withDurableRuntimeStore({ - getRepos: () => [host.repo], - getRepo: (id: string) => (id === REPO_ID ? host.repo : undefined), - getAllWorktreeMeta: () => ({}), - getWorktreeMeta: () => undefined, - getSettings: () => ({ workspaceDir: '/tmp/workspaces' }), - getProjects: () => [], - getWorkspaceSessionHostIds: () => [...sessions.keys()], - getWorkspaceSession: (hostId?: ExecutionHostId) => - sessions.get(hostId ?? LOCAL_EXECUTION_HOST_ID) ?? getDefaultWorkspaceSession(), - setWorkspaceSession: (next: WorkspaceSessionState, hostId?: ExecutionHostId) => { - sessions.set(hostId ?? LOCAL_EXECUTION_HOST_ID, next) - }, - applyLayoutCommand: async (command: LayoutCommand, hostIds: readonly ExecutionHostId[]) => { - const hostId = hostIds[0] ?? LOCAL_EXECUTION_HOST_ID - const change = applyCommandToSession( - hostId, - sessions.get(hostId) ?? getDefaultWorkspaceSession(), - command - ) - if (change.session) { - sessions.set(hostId, change.session) - } - return change.value - }, - flushPendingOrThrowAsync: async () => {}, - // Production commits asynchronously; fail if these paths synchronously flush. - flushOrThrow: () => { - throw new Error('synchronous flush') - } - }) as never - ) - runtime.attachWindow(1) - return { runtime, sessions } -} - -/** Bind in the host partition before registration, matching PTY spawn commit. */ -function registerBound( - runtime: OrcaRuntimeService, - hostId: ExecutionHostId, - ptyId: string, - connectionId: string | null, - binding: { tabId: string; leafId: string; incarnationId: string } -) { - bindPaneFirst(runtime, { worktreeId: WORKTREE_ID, ptyId, ...binding }, hostId) - runtime.registerPty(ptyId, WORKTREE_ID, connectionId, binding) -} - -function registerLeaf(runtime: OrcaRuntimeService, host: RestoreHost, leaf: 'left' | 'right') { - registerBound(runtime, host.hostId, host.ptyIds[leaf], host.connectionId, { - tabId: 'tab', - leafId: leaf === 'left' ? LEFT : RIGHT, - incarnationId: `incarnation-${leaf}` - }) -} - -function surfaces(result: RuntimeMobileSessionTabsResult | undefined): string[] { - return (result?.tabs ?? []).map((tab) => `${tab.id}:${'status' in tab ? tab.status : ''}`) -} - -async function listedSurfaces(runtime: OrcaRuntimeService): Promise { - return surfaces(await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)) -} - -const COALESCED_PUSH_MS = 250 - -describe('a restored terminal published before its PTY registers', () => { - afterEach(() => { - setRuntimeDesktopSurface(null) - vi.useRealTimers() - }) - - it.each([ - ['local', LOCAL_HOST], - ['SSH without a saved PTY binding', SSH_HOST], - ['runtime host', RUNTIME_HOST] - ])('%s: is listed pending, then pushed ready when its PTY registers', async (_label, host) => { - vi.useFakeTimers() - const { runtime } = coldRestoredRuntime(host) - publishRendererFrame(runtime, makeRendererFrame(host)) - expect(await listedSurfaces(runtime)).toEqual([ - `tab::${LEFT}:pending-handle`, - `tab::${RIGHT}:pending-handle` - ]) - vi.advanceTimersByTime(COALESCED_PUSH_MS) - const published: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((event) => published.push(event)) - - registerLeaf(runtime, host, 'left') - vi.advanceTimersByTime(COALESCED_PUSH_MS) - - // No later renderer/graph event can rescue a missing registration push. - expect(surfaces(published.at(-1))).toEqual([ - `tab::${LEFT}:ready`, - `tab::${RIGHT}:pending-handle` - ]) - const pushes = published.length - expect( - runtime.syncWindowGraph(1, { - tabs: RENDERER_TABS, - leaves: [], - mobileSessionTabs: [], - unchangedMobileSessionWorktrees: [WORKTREE_ID] - }).mobileSessionResyncWorktrees - ).toBeUndefined() - publishRendererFrame(runtime, makeRendererFrame(host)) - vi.advanceTimersByTime(COALESCED_PUSH_MS) - expect(published).toHaveLength(pushes) - expect(await listedSurfaces(runtime)).toEqual([ - `tab::${LEFT}:ready`, - `tab::${RIGHT}:pending-handle` - ]) - - registerLeaf(runtime, host, 'right') - vi.advanceTimersByTime(COALESCED_PUSH_MS) - - expect(surfaces(published.at(-1))).toEqual([`tab::${LEFT}:ready`, `tab::${RIGHT}:ready`]) - unsubscribe() - }) -}) - -describe('a retired restored terminal stays out of a later renderer frame', () => { - afterEach(() => setRuntimeDesktopSurface(null)) - - it('after its process exits and the retirement is saved', async () => { - const { runtime, sessions } = coldRestoredRuntime() - registerLeaf(runtime, LOCAL_HOST, 'left') - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST)) - expect(await listedSurfaces(runtime)).toContain(`tab::${LEFT}:ready`) - - await runtime.onPtyExit('pty-left', 0, 'incarnation-left') - - expect(sessions.get(LOCAL_EXECUTION_HOST_ID)?.terminalLayoutsByTabId.tab?.root).toEqual({ - type: 'leaf', - leafId: RIGHT - }) - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST, { version: 2 })) - expect(await listedSurfaces(runtime)).not.toContain(`tab::${LEFT}:ready`) - expect(await listedSurfaces(runtime)).not.toContain(`tab::${LEFT}:pending-handle`) - }) - - it('after its last pane exits from a runtime-host partition an older copy still lists', async () => { - const { runtime, sessions } = coldRestoredRuntime(RUNTIME_HOST) - // Retain an older same-id copy in another host partition. - sessions.set(LOCAL_EXECUTION_HOST_ID, makeColdRestoredSession(RUNTIME_HOST)) - registerLeaf(runtime, RUNTIME_HOST, 'left') - registerLeaf(runtime, RUNTIME_HOST, 'right') - publishRendererFrame(runtime, makeRendererFrame(RUNTIME_HOST)) - - await runtime.onPtyExit('pty-left', 0, 'incarnation-left') - await runtime.onPtyExit('pty-right', 0, 'incarnation-right') - // Emptying the owner partition exposes the older copy. - expect(sessions.get(RUNTIME_HOST.hostId)?.tabsByWorktree[WORKTREE_ID]).toEqual([]) - - publishRendererFrame(runtime, makeRendererFrame(RUNTIME_HOST, { version: 2 })) - expect(await listedSurfaces(runtime)).toEqual([]) - }) - - it('after the user closes it on the desktop', async () => { - const { runtime, sessions } = coldRestoredRuntime() - registerLeaf(runtime, LOCAL_HOST, 'left') - registerLeaf(runtime, LOCAL_HOST, 'right') - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST)) - expect(await listedSurfaces(runtime)).toEqual([`tab::${LEFT}:ready`, `tab::${RIGHT}:ready`]) - - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST, { version: 2, leaves: [LEFT] })) - await runtime.onPtyExit('pty-right', 0, 'incarnation-right') - expect(sessions.get(LOCAL_EXECUTION_HOST_ID)?.terminalLayoutsByTabId.tab?.root).toEqual({ - type: 'leaf', - leafId: LEFT - }) - - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST, { version: 3 })) - expect(await listedSurfaces(runtime)).toEqual([`tab::${LEFT}:ready`]) - }) -}) - -// Phone closes one SSH tab before a relaunched sibling registers. -const SSH_PTY_X = 'ssh:ssh-1@@pty-x' -const SSH_PTY_Y = 'ssh:ssh-1@@pty-y' - -function makeSshSession(tabIds: readonly ('tab-x' | 'tab-y')[]): WorkspaceSessionState { - // The unbound relaunched tab-x has no persisted relay binding yet. - const specs = { - 'tab-x': { leafId: LEFT, ptyId: null }, - 'tab-y': { leafId: RIGHT, ptyId: SSH_PTY_Y } - } - return { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: tabIds.map((id, index) => ({ - id, - ptyId: specs[id].ptyId, - worktreeId: WORKTREE_ID, - title: id, - customTitle: null, - color: null, - sortOrder: index, - createdAt: index + 1 - })) - }, - terminalLayoutsByTabId: Object.fromEntries( - tabIds.map((id) => [ - id, - { - root: { type: 'leaf' as const, leafId: specs[id].leafId }, - activeLeafId: specs[id].leafId, - expandedLeafId: null, - ptyIdsByLeafId: specs[id].ptyId ? { [specs[id].leafId]: specs[id].ptyId } : {} - } - ]) - ), - terminalTopologyRevisionByRepoId: { [REPO_ID]: 2 } - } -} - -function publishSshRendererFrame(runtime: OrcaRuntimeService): void { - const tabs = [ - { tabId: 'tab-x', leafId: LEFT, ptyId: SSH_PTY_X }, - { tabId: 'tab-y', leafId: RIGHT, ptyId: SSH_PTY_Y } - ] - runtime.syncWindowGraph(1, { - tabs: tabs.map(({ tabId, leafId }) => ({ - tabId, - worktreeId: WORKTREE_ID, - title: tabId, - activeLeafId: leafId, - layout: { type: 'leaf' as const, leafId } - })), - leaves: [], - mobileSessionTabs: [ - { - worktree: WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: 1, - activeGroupId: 'group', - activeTabId: `tab-y::${RIGHT}`, - activeTabType: 'terminal', - tabGroups: [{ id: 'group', activeTabId: 'tab-y', tabOrder: ['tab-x', 'tab-y'] }], - tabs: tabs.map(({ tabId, leafId, ptyId }) => ({ - type: 'terminal' as const, - id: `${tabId}::${leafId}`, - parentTabId: tabId, - leafId, - ptyId, - title: tabId, - isActive: tabId === 'tab-y' - })) - } - ] - }) -} - -describe('a surface the host retired stays retired when a restored sibling registers', () => { - afterEach(() => setRuntimeDesktopSurface(null)) - - it('keeps a phone-closed SSH terminal closed while its remote PTY is still exiting', async () => { - const { runtime, sessions } = coldRestoredRuntime(SSH_HOST) - sessions.set(SSH_HOST.hostId, makeSshSession(['tab-x', 'tab-y'])) - const kill = vi.fn(() => true) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the close path uses only these two relays. - runtime.setNotifier({ - closeTerminal: vi.fn(), - // Renderer persistence commits before its pruned frame arrives. - closeTerminalTab: vi.fn(async () => { - sessions.set(SSH_HOST.hostId, makeSshSession(['tab-x'])) - }) - } as never) - runtime.setPtyController({ - write: () => true, - kill, - listProcesses: vi.fn(async () => - [SSH_PTY_X, SSH_PTY_Y].map((id) => ({ id, cwd: '/worktree', title: 'shell' })) - ), - getForegroundProcess: async () => null - }) - publishSshRendererFrame(runtime) - registerBound(runtime, SSH_HOST.hostId, SSH_PTY_Y, 'ssh-1', { - tabId: 'tab-y', - leafId: RIGHT, - incarnationId: 'incarnation-y' - }) - expect(await listedSurfaces(runtime)).toContain(`tab-y::${RIGHT}:ready`) - - await runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, 'tab-y', { reason: 'user' }) - expect(kill).toHaveBeenCalledWith(SSH_PTY_Y) - registerBound(runtime, SSH_HOST.hostId, SSH_PTY_X, 'ssh-1', { - tabId: 'tab-x', - leafId: LEFT, - incarnationId: 'incarnation-x' - }) - - expect(await listedSurfaces(runtime)).not.toContain(`tab-y::${RIGHT}:ready`) - }) - - it('keeps a phone-closed chat tab closed', async () => { - const { runtime } = coldRestoredRuntime() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the chat close path uses only this relay. - runtime.setNotifier({ closeSessionTab: vi.fn(async () => {}) } as never) - publishRendererFrame( - runtime, - makeRendererFrame(LOCAL_HOST, { - extraTabs: [ - { - type: 'agent-session', - id: 'chat', - title: 'Chat', - sessionId: 'session-chat', - agent: 'claude', - isActive: false - } - ] - }) - ) - expect(await listedSurfaces(runtime)).toContain('chat:') - - await runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, 'chat', { reason: 'user' }) - registerLeaf(runtime, LOCAL_HOST, 'left') - - expect(await listedSurfaces(runtime)).not.toContain('chat:') - }) -}) - -// Paired create has registered/published, but the desktop frame still lacks it; preserve this in-flight tab. -const PHONE_LEAF = '33333333-3333-4333-8333-333333333333' - -async function runtimeWithUnpublishedPhoneCreate(): Promise { - const { runtime } = coldRestoredRuntime() - const handlers = new Map void>() - const webContents = { - isDestroyed: () => false, - setBackgroundThrottling: () => {}, - capturePage: async () => null, - send: (channel: string, payload: { requestId: string }) => { - if (channel !== 'terminal:requestTabCreate') { - return - } - registerBound(runtime, LOCAL_EXECUTION_HOST_ID, 'pty-phone', null, { - tabId: 'tab-phone', - leafId: PHONE_LEAF, - incarnationId: 'incarnation-phone' - }) - handlers.get('terminal:tabCreateReply')?.( - { sender: webContents }, - { requestId: payload.requestId, tabId: 'tab-phone', title: 'Terminal' } - ) - } - } - setRuntimeDesktopSurface({ - showNotification: () => false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create path reads only liveness and these webContents members off its authoritative window. - findWindowById: () => ({ isDestroyed: () => false, webContents }) as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the tab-create reply channel is registered on this path. - onIpc: (channel, listener) => handlers.set(channel, listener as never), - removeIpcListener: (channel) => handlers.delete(channel) - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create path focuses only when activating, which this create does not. - runtime.setNotifier({ focusTerminal: vi.fn() } as never) - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: WORKTREE_ID, - path: '/worktree', - connectionId: null, - repo: LOCAL_HOST.repo, - folderWorkspace: null - })) - }) - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST)) - await runtime.createMobileSessionTerminal(`id:${WORKTREE_ID}`, { - activate: false, - clientNavigationId: 'phone' - }) - return runtime -} - -describe('a surface the host added stays listed when a restored sibling registers', () => { - afterEach(() => setRuntimeDesktopSurface(null)) - - it('keeps a phone-created terminal listed', async () => { - const runtime = await runtimeWithUnpublishedPhoneCreate() - expect(await listedSurfaces(runtime)).toContain(`tab-phone::${PHONE_LEAF}:ready`) - - registerLeaf(runtime, LOCAL_HOST, 'left') - - expect(await listedSurfaces(runtime)).toContain(`tab-phone::${PHONE_LEAF}:ready`) - }) -}) diff --git a/src/main/runtime/terminal/surface/orca-runtime-failed-start-pane-layout-owner.test.ts b/src/main/runtime/terminal/surface/orca-runtime-failed-start-pane-layout-owner.test.ts deleted file mode 100644 index 1a767dc459e..00000000000 --- a/src/main/runtime/terminal/surface/orca-runtime-failed-start-pane-layout-owner.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree' -import { NEWER_DAEMON_HOLD_ERROR } from '../../../../shared/newer-daemon-hold' -import { - setupLayoutOwnerRuntime, - WORKTREE_ID -} from '../../orca-runtime-tests/orca-runtime-layout-owner-start-fixture' -import { PaneOwnerContentionError } from '../../../ipc/pty/pane/pane-spawn-operation' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -describe('layout-owner build: a start main could not make keeps its pane, showing why', () => { - it('writes the pane and shows the failure when the start failed before its pane was written', async () => { - const { runtime, spawn, session } = setupLayoutOwnerRuntime() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - - await expect( - runtime.createTerminal(`id:${WORKTREE_ID}`, { - title: 'Setup', - keepPaneOnStartFailure: true, - startFailure: new Error('agent runtime needs repair') - }) - ).rejects.toThrow('agent runtime needs repair') - - expect(spawn).not.toHaveBeenCalled() - const [row] = session().tabsByWorktree[WORKTREE_ID] ?? [] - expect(row?.customTitle).toBe('Setup') - const [leafId] = collectLeafIds(session().terminalLayoutsByTabId[row!.id]?.root) - expect(runtime.startStatusOf(`${row!.id}:${leafId}`)).toEqual({ - status: 'failed', - reason: 'agent runtime needs repair' - }) - }) - - it('keeps the pane it wrote when the terminal itself fails to start', async () => { - const { runtime, spawn, session } = setupLayoutOwnerRuntime() - spawn.mockRejectedValueOnce(new Error('shell not found')) - - await expect( - runtime.createTerminal(`id:${WORKTREE_ID}`, { keepPaneOnStartFailure: true }) - ).rejects.toThrow('shell not found') - - const [row] = session().tabsByWorktree[WORKTREE_ID] ?? [] - expect(row).toBeDefined() - const { tabId, leafId } = spawn.mock.calls[0]![0] - expect(row!.id).toBe(tabId) - expect(runtime.startStatusOf(`${tabId}:${leafId}`)).toEqual({ - status: 'failed', - reason: 'shell not found' - }) - }) - - it("shows the pane held, not failed, when a newer build's terminal service may still run it", async () => { - const { runtime, spawn } = setupLayoutOwnerRuntime() - spawn.mockRejectedValueOnce(new Error(NEWER_DAEMON_HOLD_ERROR)) - - await expect( - runtime.createTerminal(`id:${WORKTREE_ID}`, { keepPaneOnStartFailure: true }) - ).rejects.toThrow(NEWER_DAEMON_HOLD_ERROR) - - const { tabId, leafId } = spawn.mock.calls[0]![0] - expect(runtime.startStatusOf(`${tabId}:${leafId}`)).toEqual({ - status: 'held', - reason: NEWER_DAEMON_HOLD_ERROR - }) - }) - - it('shows no failure when another owner won the pane, whose terminal the window attaches to', async () => { - const { runtime, spawn } = setupLayoutOwnerRuntime() - spawn.mockRejectedValueOnce(new PaneOwnerContentionError()) - - await expect( - runtime.createTerminal(`id:${WORKTREE_ID}`, { keepPaneOnStartFailure: true }) - ).rejects.toThrow('terminal_pane_owner_changed') - - const { tabId, leafId } = spawn.mock.calls[0]![0] - expect(runtime.startStatusOf(`${tabId}:${leafId}`)).toBeNull() - }) - - it('does not bring back a pane the user closed while its start was failing', async () => { - const { runtime, spawn, session } = setupLayoutOwnerRuntime() - spawn.mockImplementationOnce(async ({ tabId }) => { - await runtime.applyLayoutCommand({ - type: 'closeTabs', - workspace: WORKTREE_ID, - tabIds: [tabId!], - recordClose: 'user' - }) - throw new Error('shell not found') - }) - - await expect( - runtime.createTerminal(`id:${WORKTREE_ID}`, { keepPaneOnStartFailure: true }) - ).rejects.toThrow('shell not found') - - expect(session().tabsByWorktree[WORKTREE_ID] ?? []).toEqual([]) - }) -}) diff --git a/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts b/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts index b9add9059b7..33036d33c4f 100644 --- a/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts +++ b/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts @@ -19,7 +19,7 @@ import { WORKTREE_PATH, makeSession } from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' const SSH_REPO_ID = 'ssh-repo' const SSH_HOST_ID = 'ssh:target-1' diff --git a/src/main/runtime/terminal/surface/orca-runtime-terminal-close-spill-partition.spec.ts b/src/main/runtime/terminal/surface/orca-runtime-terminal-close-spill-partition.spec.ts index 4b7cabfd08c..d2908a7c6a0 100644 --- a/src/main/runtime/terminal/surface/orca-runtime-terminal-close-spill-partition.spec.ts +++ b/src/main/runtime/terminal/surface/orca-runtime-terminal-close-spill-partition.spec.ts @@ -1,23 +1,17 @@ -import { withDurableRuntimeStore } from '../../orca-runtime-tests/runtime-durable-store-fixture' +import '../../orca-runtime-tests/runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' -import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' +import '../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' + import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { buildHeadlessMobileSessionTerminalTabs } from './mobile-session-terminal-projection' -import { OrcaRuntimeService } from '../../orca-runtime' +import './mobile-session-terminal-projection' +import '../../orca-runtime' import { terminalSurfaceCloseMutation } from './terminal-surface-close' import { capturePersistedTerminalTabCopy } from './workspace-session-terminal-tab-retirement-identity' export function registerOrcaRuntimeTerminalCloseSpillPartitionTests(): void { - const REPO = { - id: 'repo', - path: '/worktree', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 - } as const const WORKTREE_ID = 'repo::/worktree' const LEAF = '11111111-1111-4111-8111-111111111111' const SPILL_HOST_ID: ExecutionHostId = 'runtime:env-1' @@ -51,83 +45,7 @@ export function registerOrcaRuntimeTerminalCloseSpillPartitionTests(): void { } } - function harness(sessions: Map) { - const kill = vi.fn(() => true) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This runtime fixture supplies the persistence methods exercised by the test. - const store = withDurableRuntimeStore({ - getRepos: () => [REPO], - getRepo: (id: string) => (id === REPO.id ? REPO : undefined), - getWorktreeMeta: () => undefined, - getAllWorktreeMeta: () => ({}), - getWorkspaceSessionHostIds: () => [...sessions.keys()], - getWorkspaceSession: (hostId?: ExecutionHostId) => - sessions.get(hostId ?? LOCAL_EXECUTION_HOST_ID) ?? getDefaultWorkspaceSession(), - setWorkspaceSession: (session: WorkspaceSessionState, hostId?: ExecutionHostId) => - sessions.set(hostId ?? LOCAL_EXECUTION_HOST_ID, session), - flushOrThrow: vi.fn() - }) as never - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - write: () => true, - kill, - getForegroundProcess: async () => null, - listProcesses: async () => [{ id: 'target-pty', cwd: REPO.path, title: 'Terminal' }] - }) - const tabs = [...sessions.values()].flatMap((session) => - buildHeadlessMobileSessionTerminalTabs( - WORKTREE_ID, - session.tabsByWorktree[WORKTREE_ID] ?? [], - session - ) - ) - const snapshot: RuntimeMobileSessionTabsSnapshot = { - worktree: WORKTREE_ID, - publicationEpoch: 'headless', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: tabs[0]?.id ?? null, - activeTabType: 'terminal', - tabs: tabs.filter((tab, index) => tabs.findIndex((other) => other.id === tab.id) === index) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the published snapshot map is protected; seeding it stands in for a prior publication. - const internals = runtime as unknown as { - mobileSessionTabsByWorktree: Map - } - internals.mobileSessionTabsByWorktree.set(WORKTREE_ID, snapshot) - return { runtime, kill } - } - describe('terminal close across local and runtime session partitions (#18202)', () => { - it('closes and records every copy when legacy reattach left one in two partitions', async () => { - const sessions = new Map([ - [LOCAL_EXECUTION_HOST_ID, sessionWithTab('unrelated', 'unrelated-pty')], - [SPILL_HOST_ID, sessionWithTab('target', 'target-pty')], - ['runtime:env-0', sessionWithTab('target', 'target-pty')] - ]) - const { runtime } = harness(sessions) - runtime.registerPty('target-pty', WORKTREE_ID, null, { - tabId: 'target', - leafId: LEAF, - incarnationId: 'target-incarnation' - }) - - const terminal = (await runtime.listTerminals()).terminals.find( - (candidate) => candidate.tabId === 'target' - )! - await expect(runtime.closeTerminalTab(terminal.handle)).resolves.toMatchObject({ - tabId: 'target' - }) - - for (const hostId of [SPILL_HOST_ID, 'runtime:env-0'] as const) { - const session = sessions.get(hostId)! - expect(session.tabsByWorktree[WORKTREE_ID]).toEqual([]) - expect( - hasClosedTerminalTabRecord(session.closedTerminalTabTombstonesByTabId, 'target') - ).toBe(true) - } - expect(sessions.get(LOCAL_EXECUTION_HOST_ID)?.tabsByWorktree[WORKTREE_ID]).toHaveLength(1) - }) - it('refuses when a second copy was rebound after the close was asked', () => { const sessions = new Map([ [SPILL_HOST_ID, sessionWithTab('target', 'target-pty')], diff --git a/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts index 78e4f1220b1..9de1fedbc9f 100644 --- a/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts @@ -23,12 +23,9 @@ import { makeSession } from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' import { createHarness } from '../../__fixtures__/orca-runtime-terminal-close-continuity-fixtures' -import { expectDesktopDropsPane } from '../../__fixtures__/main-layout-close-fixture' -import { - retireTerminalSurfaceFromPersistence, - sanitizeWorkspaceSessionTerminalRetirements -} from './mobile-session-terminal-persistence-retirement' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import '../../__fixtures__/main-layout-close-fixture' +import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' const splitLayout = { root: { @@ -124,18 +121,6 @@ function rendererSaveWithout( } describe('renderer close intents', () => { - it('keeps a closed tab closed across a renderer save and a reload', async () => { - const { store, runtime, reload } = createPersistedRuntime(makeSession()) - - await runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: WORKTREE_ID, - target: { kind: 'tab', tabId: TAB_ID } - }) - store.setWorkspaceSession(rendererSaveWithout(store.getWorkspaceSession())) - - expect((await reload()).tabsByWorktree[WORKTREE_ID]).toEqual([]) - }) - it('keeps a closed split pane closed across a renderer save and a reload', async () => { const { store, runtime, reload } = createPersistedRuntime(splitSession()) @@ -183,46 +168,6 @@ describe('renderer close intents', () => { }) describe('CLI close of one pane in a split tab', () => { - it.each([ - ['reports no exit', false], - ['throws, as an unreachable SSH host does', new Error('ssh_host_unreachable')] - ] as const)( - 'closes only that pane, never the live sibling, when its stop %s', - async (_case, stopResult) => { - const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) - harness.syncSplitFixtureGraph() - harness.syncFixtureTabWithoutLeaf() - harness.setVerifiedStopResult(stopResult) - // Honor erroneous tab close so widening destroys the sibling and fails visibly. - harness.setCloseTerminalTabAction(() => harness.retirePersistedTab()) - const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( - (candidate) => candidate.ptyId === PTY_ID - )! - - const receipt = await harness.runtime.closeTerminal(terminal.handle) - - const saved = sanitizeWorkspaceSessionTerminalRetirements( - { ...harness.getSession(), terminalLayoutsByTabId: { [TAB_ID]: splitLayout } }, - harness.getSession() - ) - expect(saved.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) - expect(saved.terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ - type: 'leaf', - leafId: SIBLING_LEAF_ID - }) - expectDesktopDropsPane(harness, TAB_ID, LEAF_ID) - expect(harness.closeTerminalTab).not.toHaveBeenCalled() - // Controller kill also records pending SSH stops; it must still run. - expect(harness.kill).toHaveBeenCalledWith(PTY_ID) - expect(harness.kill).not.toHaveBeenCalledWith(SIBLING_PTY_ID) - expect(receipt).toMatchObject({ - tabId: TAB_ID, - ptyKilled: false, - ptyStopVerdict: 'unverifiable' - }) - } - ) - // L255: expected main-owned headless pane-close failure until its fix lands. it('keeps the sibling when the stop delivers the exit before the pane commit', async () => { diff --git a/src/main/runtime/terminal/surface/pane-live-facts.test.ts b/src/main/runtime/terminal/surface/pane-live-facts.test.ts index 3d790dbad7a..b4902d7a107 100644 --- a/src/main/runtime/terminal/surface/pane-live-facts.test.ts +++ b/src/main/runtime/terminal/surface/pane-live-facts.test.ts @@ -10,7 +10,7 @@ import { bindingOf } from './pane-live-facts' import { PaneResumeOutcomes, PaneStartStatuses } from './pane-start-statuses' -import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PaneResumeOutcome } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' const LEAF_ID = '11111111-1111-4111-8111-111111111111' const PANE_KEY = `tab-1:${LEAF_ID}` diff --git a/src/main/runtime/terminal/surface/pane-start-statuses.ts b/src/main/runtime/terminal/surface/pane-start-statuses.ts index 10e6c20ddbd..f716070473a 100644 --- a/src/main/runtime/terminal/surface/pane-start-statuses.ts +++ b/src/main/runtime/terminal/surface/pane-start-statuses.ts @@ -5,7 +5,7 @@ import type { PaneResumeOutcome, PaneStartStatus, PublishedWorkspaceLayout -} from '../../../../shared/workspace-layout/workspace-layout-published' +} from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import { bindingOf, PaneLiveFacts } from './pane-live-facts' export type PaneStartFact = { status: PaneStartStatus; reason?: string } diff --git a/src/main/runtime/terminal/surface/pty-pane-query.ts b/src/main/runtime/terminal/surface/pty-pane-query.ts index d61013ed62f..e8bf61326b8 100644 --- a/src/main/runtime/terminal/surface/pty-pane-query.ts +++ b/src/main/runtime/terminal/surface/pty-pane-query.ts @@ -1,6 +1,6 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' -import type { WorkspaceLayoutLoadContext } from '../../../../shared/workspace-layout/workspace-layout-load-types' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { WorkspaceLayoutLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' import { isPaneSleepRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import { pairedRuntimeHostOfBinding, @@ -12,7 +12,7 @@ import { import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' +import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' export type PtyPane = { diff --git a/src/main/runtime/terminal/surface/published-pane-live-titles.ts b/src/main/runtime/terminal/surface/published-pane-live-titles.ts index 060455f2a0f..6d5eaaece5d 100644 --- a/src/main/runtime/terminal/surface/published-pane-live-titles.ts +++ b/src/main/runtime/terminal/surface/published-pane-live-titles.ts @@ -1,4 +1,4 @@ -import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' /** `titles` in tab and pane order, null for a pane with none; the same layout when all are null. */ export function withLiveTitles( diff --git a/src/main/runtime/terminal/surface/terminal-surface-close.ts b/src/main/runtime/terminal/surface/terminal-surface-close.ts index 4c28b35c94f..4a3273f1e9a 100644 --- a/src/main/runtime/terminal/surface/terminal-surface-close.ts +++ b/src/main/runtime/terminal/surface/terminal-surface-close.ts @@ -3,18 +3,18 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import { hasClosedTerminalTabRecord, recordClosedTerminalTabTombstone -} from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones' +} from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import type { TerminalLayoutSnapshot, TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' -import type { TerminalSurfaceCloseTarget } from '../../../../shared/workspace-layout/terminal-surface-close-target' +import type { TerminalSurfaceCloseTarget } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-surface-close-target' import { closeTerminalTabInWorkspaceSession, type WorkspaceSessionTerminalTabCloseResult } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close' import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import type { DurableProfileStateMutation } from '../../../persistence/loading-store/store-runtime-state' import type { ExecutionHostId } from '../../../../shared/execution-host' import { diff --git a/src/main/runtime/terminal/surface/terminal-surface-index.ts b/src/main/runtime/terminal/surface/terminal-surface-index.ts index c440fcf8735..00e7690c3ed 100644 --- a/src/main/runtime/terminal/surface/terminal-surface-index.ts +++ b/src/main/runtime/terminal/surface/terminal-surface-index.ts @@ -10,12 +10,12 @@ import type { RuntimeSyncedTab, RuntimeSyncWindowGraph } from '../../../../shared/runtime-session-contracts' -import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load-types' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' import type { LayoutTab, WorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-model' -import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { bindingOf } from './pane-live-facts' import { worktreeIdsEqual } from '../../../../shared/worktree/id' import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' diff --git a/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts b/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts index 1f6342333e9..092cc3142ae 100644 --- a/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts +++ b/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts @@ -17,7 +17,7 @@ import type { RuntimeTerminalShow } from '../../../../shared/runtime-terminal-co import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' export const SURFACE_TAB_ID = '44444444-4444-4444-8444-444444444444' diff --git a/src/main/runtime/terminal/surface/workspace-layout-frame-model-check.ts b/src/main/runtime/terminal/surface/workspace-layout-frame-model-check.ts index aafbe2ce07f..f6fa812b6b7 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-frame-model-check.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-frame-model-check.ts @@ -1,7 +1,7 @@ // Applying each records frame must equal a fresh partition projection; tests check every frame and dev builds log Store-write mismatches (workspace-layout-frame-observer.ts). -import { stableJson } from '../../../../shared/workspace-layout/workspace-layout-load-report' -import { applyWorkspaceLayoutRecordChange } from '../../../../shared/workspace-layout/workspace-layout-records' +import { stableJson } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-report' +import { applyWorkspaceLayoutRecordChange } from '../../../../shared/workspace-layout/published-layout/workspace-layout-records' import type { LayoutFrameObservation } from './workspace-layout-frame-observer' /** Empty when the frame holds exactly what changed. */ diff --git a/src/main/runtime/terminal/surface/workspace-layout-frame-observer.ts b/src/main/runtime/terminal/surface/workspace-layout-frame-observer.ts index 9ebf47fc0b9..06d03000961 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-frame-observer.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-frame-observer.ts @@ -1,9 +1,9 @@ // Tests check every records frame against a fresh projection and freeze partition reads; development logs structural frame mismatches, while release builds do neither. import { logLayoutFrameModelErrors } from './workspace-layout-frame-model-check' -import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load-types' -import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-published' -import type { WorkspaceLayoutRecordsFrame } from '../../../../shared/workspace-layout/workspace-layout-stream-frames' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' +import type { WorkspaceLayoutRecordsFrame } from '../../../../shared/workspace-layout/published-layout/workspace-layout-stream-frames' export type LayoutFrameObservation = { frame: WorkspaceLayoutRecordsFrame diff --git a/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts b/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts index fe4b8ade105..52b7714a1db 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts @@ -7,17 +7,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { GeneratedTabTitle } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import type { WorkspaceLayoutStreamEvent } from '../../../../shared/workspace-layout/workspace-layout-stream-frames' + import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID as GIT, openTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { applyWindowLayoutCommand } from '../layout/runtime-layout-apply' import { installLayoutFrameModelCheck } from './workspace-layout-frame-model-check.test-fixture' -import { WorkspaceLayoutStream } from './workspace-layout-stream' +import './workspace-layout-stream' const layoutOwner = vi.hoisted(() => ({ isMain: true })) vi.mock('../../../../shared/layout-owner-switch', () => ({ @@ -62,14 +62,6 @@ async function storeWith(tabs: Record): Promise { const tabIdOf = (workspace: string, index: number) => `tab-${workspace.replace(/\W/g, '-')}-${index}` -function streamOver(store: Store): WorkspaceLayoutStream { - return new WorkspaceLayoutStream({ - store: () => store, - homeHostId: homeOf, - liveTitle: () => null - }) -} - function titles(tabs: Record): GeneratedTabTitle[] { return Object.entries(tabs).flatMap(([workspace, count]) => Array.from({ length: count }, (_, index) => ({ @@ -100,38 +92,6 @@ afterEach(() => { } }) -describe('one records frame per main operation', () => { - it('publishes a pane bind as one binding record, and a same-id respawn as one more', async () => { - const store = await storeWith({ [GIT]: 2 }) - const frames: WorkspaceLayoutStreamEvent[] = [] - streamOver(store).subscribe((frame) => frames.push(frame)) - const bind = (incarnationId: string) => - store.persistPtyBinding({ - worktreeId: GIT, - tabId: tabIdOf(GIT, 1), - leafId: leafOf(1), - ptyId: 'pty-1', - incarnationId - }) - - await bind('inc-1') - await bind('inc-2') - - const binding = (ptyGeneration: number) => [ - { - key: GIT, - change: 'records', - bindings: { set: [{ leafId: leafOf(1), ptyId: 'pty-1', ptyGeneration }] } - } - ] - expect(frames.map((frame) => frame.type === 'records' && frame.workspaces)).toEqual([ - binding(1), - binding(2) - ]) - expect(check.failures).toEqual([]) - }) -}) - describe('a throwing operation listener', () => { it('fails neither the committed operation nor the listeners after it', async () => { const store = await storeWith({ [GIT]: 1 }) diff --git a/src/main/runtime/terminal/surface/workspace-layout-projection.ts b/src/main/runtime/terminal/surface/workspace-layout-projection.ts index 5dd2873215e..a9a6181f6f2 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-projection.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-projection.ts @@ -2,17 +2,17 @@ import type { ExecutionHostId } from '../../../../shared/execution-host' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { loadWorkspaceLayoutWithoutReport } from '../../../../shared/workspace-layout/workspace-layout-load' -import { stableJson } from '../../../../shared/workspace-layout/workspace-layout-load-report' +import { loadWorkspaceLayoutWithoutReport } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { stableJson } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-report' import type { LoadedWorkspaceLayout, WorkspaceLayoutLoadContext -} from '../../../../shared/workspace-layout/workspace-layout-load-types' -import { nameBasedLoadContext } from '../../../../shared/workspace-layout/workspace-layout-minted-ids' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import { publishWorkspaceLayout, type PublishedWorkspaceLayout -} from '../../../../shared/workspace-layout/workspace-layout-published' +} from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import type { RuntimeStore } from '../../construction/runtime-store-contract' export type ProjectedLayout = { layout: PublishedWorkspaceLayout; json: string } diff --git a/src/main/runtime/terminal/surface/workspace-layout-stream.test.ts b/src/main/runtime/terminal/surface/workspace-layout-stream.test.ts index fab3572edd8..f721e7a5b7a 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-stream.test.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-stream.test.ts @@ -4,15 +4,14 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import { localDesktopSession, relaySshSession -} from '../../../../shared/workspace-layout/workspace-layout-profile.test-fixture' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-profile.test-fixture' import { - emptySession, FOLDER_KEY, GIT_KEY, SSH_KEY -} from '../../../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { WorkspaceLayoutStream } from './workspace-layout-stream' -import { collectLayoutEvents } from '../../orca-runtime-tests/workspace-layout-stream-events.test-fixture' +import '../../orca-runtime-tests/workspace-layout-stream-events.test-fixture' const SSH_HOST: ExecutionHostId = 'ssh:target-1' @@ -66,15 +65,6 @@ function setup() { return { ...fake, stream, homes, partitions, liveTitles, liveTitle } } -const flush = () => new Promise((resolve) => queueMicrotask(resolve)) - -function subscribeEvents(stream: WorkspaceLayoutStream) { - const collector = collectLayoutEvents() - const subscription = stream.subscribe(collector.listener) - collector.seed(subscription.snapshot) - return { events: collector.events, collector, subscription } -} - describe('WorkspaceLayoutStream', () => { it('snapshots each workspace from its owning partition only', () => { const { stream, homes } = setup() @@ -94,115 +84,4 @@ describe('WorkspaceLayoutStream', () => { }).subscribe(() => {}).snapshot expect(strayless.map((entry) => entry.key)).toEqual([GIT_KEY, FOLDER_KEY]) }) - - it('numbers each change frame, so a reply can name the frame holding its write', async () => { - const { stream, write } = setup() - const { events, subscription: first } = subscribeEvents(stream) - const session = localDesktopSession() - write(LOCAL_EXECUTION_HOST_ID, session) - await flush() - expect(events).toEqual([]) - expect(stream.settledSeq()).toBe(first.seq) - - session.tabGroups![GIT_KEY]![0]!.tabOrder.reverse() - write(LOCAL_EXECUTION_HOST_ID, session) - // Read before the queued flush runs: the write's frame goes out first. - const replySeq = stream.settledSeq() - expect(events).toEqual([expect.objectContaining({ key: GIT_KEY, seq: first.seq + 1 })]) - expect(replySeq).toBe(first.seq + 1) - await flush() - expect(events).toHaveLength(1) - - first.unsubscribe() - const second = stream.subscribe(() => {}) - expect(second.seq).toBeGreaterThanOrEqual(replySeq) - second.unsubscribe() - }) - - it('keeps delivering to every listener when one throws', async () => { - const { stream, write } = setup() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - stream.subscribe(() => { - throw new Error('listener failed') - }) - const { events } = subscribeEvents(stream) - const session = localDesktopSession() - session.tabGroups![GIT_KEY]![0]!.tabOrder.reverse() - write(LOCAL_EXECUTION_HOST_ID, session) - await flush() - expect(events.map((event) => [event.type, event.key])).toEqual([['workspace', GIT_KEY]]) - write(LOCAL_EXECUTION_HOST_ID, structuredClone(session)) - await flush() - expect(events).toHaveLength(1) - warn.mockRestore() - }) - - it('keeps every invented id when an earlier workspace or tab goes away', async () => { - // Headless rows without tab-bar or pane layout require synthesized groups and panes. - const rowsOnly = (keys: string[], tabs: string[]): WorkspaceSessionState => { - const session = emptySession() - for (const key of keys) { - session.tabsByWorktree[key] = tabs.map((tab, index) => ({ - id: `${key}-${tab}`, - ptyId: null, - worktreeId: key, - title: tab, - customTitle: null, - color: null, - sortOrder: index, - createdAt: Number(tab.slice(1)) - })) - } - return session - } - const keys = ['repo-1::/a', 'repo-1::/b', 'repo-1::/c'] - const fake = fakeStore(new Map([[LOCAL_EXECUTION_HOST_ID, rowsOnly(keys, ['t1', 't2'])]])) - const stream = new WorkspaceLayoutStream({ - store: () => fake.store, - homeHostId: () => LOCAL_EXECUTION_HOST_ID, - liveTitle: () => null - }) - const { events, subscription } = subscribeEvents(stream) - const before = new Map( - subscription.snapshot.map((entry) => [entry.key, JSON.stringify(entry.layout)]) - ) - fake.write(LOCAL_EXECUTION_HOST_ID, rowsOnly(keys.slice(1), ['t1', 't2'])) - await flush() - expect(events).toEqual([{ type: 'removed', key: 'repo-1::/a', seq: expect.any(Number) }]) - - const withoutFirstTab = rowsOnly(keys.slice(1), ['t2']) - fake.write(LOCAL_EXECUTION_HOST_ID, withoutFirstTab) - await flush() - const after = new Map( - events.flatMap((event) => (event.type === 'workspace' ? [[event.key, event.layout]] : [])) - ) - for (const key of keys.slice(1)) { - const earlier = JSON.parse(before.get(key)!) - const later = after.get(key)! - expect(later.groups.map((group) => group.id)).toEqual( - earlier.groups.map((group: { id: string }) => group.id) - ) - expect(JSON.stringify(later.tabs)).toBe(JSON.stringify(earlier.tabs.slice(1))) - } - }) - - it('re-projects every partition after a failed projection', async () => { - const { stream, store, write } = setup() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { events } = subscribeEvents(stream) - store.getWorkspaceSession.mockImplementationOnce(() => { - throw new Error('read failed') - }) - const local = localDesktopSession() - local.tabGroups![GIT_KEY]![0]!.tabOrder.reverse() - write(LOCAL_EXECUTION_HOST_ID, local) - await flush() - expect(events).toEqual([]) - // A later write elsewhere must recover the local edit missed by the failed projection. - write(SSH_HOST, relaySshSession('target-1')) - await flush() - expect(events.map((event) => [event.type, event.key])).toEqual([['workspace', GIT_KEY]]) - expect(warn).toHaveBeenCalledTimes(1) - warn.mockRestore() - }) }) diff --git a/src/main/runtime/terminal/surface/workspace-layout-stream.ts b/src/main/runtime/terminal/surface/workspace-layout-stream.ts index 521845381a3..eb181b875d6 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-stream.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-stream.ts @@ -4,18 +4,18 @@ import { randomUUID } from 'node:crypto' import type { ExecutionHostId } from '../../../../shared/execution-host' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load-types' -import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-published' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import type { PublishedWorkspaceLayout } from '../../../../shared/workspace-layout/published-layout/workspace-layout-published' import { diffPublishedLayouts, indexPublishedLayout, type IndexedLayoutRecords, type WorkspaceLayoutRecordChange -} from '../../../../shared/workspace-layout/workspace-layout-records' +} from '../../../../shared/workspace-layout/published-layout/workspace-layout-records' import type { WorkspaceLayoutEvent, WorkspaceLayoutStreamEvent -} from '../../../../shared/workspace-layout/workspace-layout-stream-frames' +} from '../../../../shared/workspace-layout/published-layout/workspace-layout-stream-frames' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { withLiveTitles } from './published-pane-live-titles' import { paneStartFactsOf, withPaneStartFacts } from './pane-start-statuses' diff --git a/src/main/runtime/terminal/terminal-path-resolver.ts b/src/main/runtime/terminal/terminal-path-resolver.ts index b6bc4130ca1..901b6c972e4 100644 --- a/src/main/runtime/terminal/terminal-path-resolver.ts +++ b/src/main/runtime/terminal/terminal-path-resolver.ts @@ -116,6 +116,23 @@ export class RuntimeTerminalPathResolver { absolutePath ) ).type === 'directory' + // Why: a workspace nested inside this one is inside its root, so the outside-root lookup above never sees it. + const nestedWorkspace = + crossWorkspace && isDirectory && !knownWorkspaceTarget && ownedRelativePath !== '' + ? await this.host.resolveKnownWorkspaceFileTarget?.( + absolutePath, + target.executionHostId + ) + : null + if (nestedWorkspace?.relativePath === '') { + return { + worktree: nestedWorkspace.worktree.id, + relativePath: '', + absolutePath, + exists: true, + isDirectory: true + } + } return { worktree: ownedWorktree.id, relativePath: ownedRelativePath, diff --git a/src/main/runtime/terminal/title/runtime-terminal-names.ts b/src/main/runtime/terminal/title/runtime-terminal-names.ts index 448c6ef3f50..5286ccfc2b5 100644 --- a/src/main/runtime/terminal/title/runtime-terminal-names.ts +++ b/src/main/runtime/terminal/title/runtime-terminal-names.ts @@ -3,9 +3,9 @@ import type { RuntimeTerminalSetPaneTitle } from '../../../../shared/runtime-terminal-contracts' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { RuntimeNestedWorktreeRemoval } from '../../workspaces/removal/runtime-nested-worktree-removal' +import { RuntimeWorkspaceArchive } from '../../workspaces/archive/runtime-workspace-archive' -export abstract class RuntimeTerminalNames extends RuntimeNestedWorktreeRemoval { +export abstract class RuntimeTerminalNames extends RuntimeWorkspaceArchive { async renameTerminal(handle: string, title: string | null): Promise { // Switch point: a terminal main owns is renamed in main's layout, with or without a window. const mainRename = ORCA_LAYOUT_OWNER_IS_MAIN diff --git a/src/main/runtime/terminal/wait/active-worktree-context-fallback.ts b/src/main/runtime/terminal/wait/active-worktree-context-fallback.ts index 97d3f9de86f..ca22e7addce 100644 --- a/src/main/runtime/terminal/wait/active-worktree-context-fallback.ts +++ b/src/main/runtime/terminal/wait/active-worktree-context-fallback.ts @@ -6,10 +6,13 @@ import { } from '../../../../shared/execution-host' import { getActiveSidebarWorkspaceId, parseWorkspaceKey } from '../../../../shared/workspace-scope' import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' +import { worktreeMetaIdentityKey } from '../../../../shared/worktree/identity' -type WorktreeMetaLabel = { displayName?: string } +type WorktreeMetaLabel = { displayName?: string; instanceId?: string; hostId?: ExecutionHostId } export type ActiveWorkspaceContext = { worktreeId: string + /** Host-qualified identity key; absent for folders and rows known only from storage. */ + identityKey?: string path: string branch: string displayName: string @@ -143,8 +146,11 @@ export function resolveStoredWorkspaceContext( if ((!meta && !repo) || !rowHostId || rowHostId === LOCAL_EXECUTION_HOST_ID) { return null } + // Host-qualified: a same-id row of another host never lends this workspace its identity. + const identityKey = worktreeMetaIdentityKey(id, store?.getWorktreeMetaForHost?.(id, rowHostId)) return { worktreeId: id, + ...(identityKey ? { identityKey } : {}), path: parsed.worktreePath, branch: '', displayName: nonEmpty(meta?.displayName, repo?.displayName, parsed.worktreePath) diff --git a/src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts b/src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts index 6075bdc66c6..b27054fa3e8 100644 --- a/src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts +++ b/src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts @@ -8,11 +8,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { recognizeAgentProcess } from '../../../../shared/agent-status/process/agent-process-recognition' import { getStrictProcessTableSnapshotWithAge } from '../../../../shared/process-table-snapshot-reader' import { createPtyForegroundProcessTracker } from '../../../daemon/pty-subprocess/foreground-process-tracker' -import { resolveRemoteForegroundEvidence } from '../../../providers/agent-foreground-process-batch' +import { resolveRemoteForegroundEvidence } from '../../../providers/foreground/agent-process-batch' import { prepareMacosTccLoginShell, wrapShellSpawnForMacosTccAttribution -} from '../../../providers/macos-tcc-login-shell' +} from '../../../providers/shell-launch/macos/tcc-login-shell' import { readLaunchedAgentForeground } from './launched-agent-foreground' import { createLaunchedAgentWriteGuard } from './launched-agent-write-guard' import { waitForWorktreeStartupDraft } from '../../workspaces/startup/runtime-worktree-startup-readiness' diff --git a/src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts b/src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts index e3b7efea742..e44a6ebe0c5 100644 --- a/src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts +++ b/src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts @@ -1,13 +1,6 @@ -import { describe, vi } from 'vitest' -import './agent-transcript-replay-test-harness' -import { describeScreenRuledAgentTranscripts } from './screen-ruled-agent-transcript-suite' - -vi.mock('electron', () => ({ - BrowserWindow: { fromId: vi.fn(() => null) }, - webContents: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - app: { getPath: vi.fn(() => '/tmp') } -})) +import { describe, expect, it } from 'vitest' +import { finalReplayFrame } from './agent-transcript-replay-test-harness' +import { evaluateAgentStateRules } from '../../agent-state-rules/agent-state-rules-engine' // prime-agent 0.9.8 on macOS, OpenRouter, isolated HOME; 0.9.5 recorded for PR #22154 (see // each .meta.json); STA-8741. @@ -30,11 +23,17 @@ const NOT_READY = [ ] describe('Prime Agent readiness from captured bytes', () => { - describeScreenRuledAgentTranscripts({ - agent: 'prime-agent', - foregroundProcess: 'prime-agent', - ready: READY, - notReady: NOT_READY, - readyWithoutScreen: READY.map(({ name }) => name) + it.each(READY)('$name ($what) reads ready', async ({ name, cols, rows }) => { + const { ruledScreenLines } = await finalReplayFrame(name, cols, rows) + expect( + evaluateAgentStateRules('prime-agent', { readScreenLines: () => ruledScreenLines })?.state + ).toBe('idle') + }) + + it.each(NOT_READY)('$name ($what) does not read ready', async ({ name, cols, rows }) => { + const { ruledScreenLines } = await finalReplayFrame(name, cols, rows) + expect( + evaluateAgentStateRules('prime-agent', { readScreenLines: () => ruledScreenLines })?.state + ).not.toBe('idle') }) }) diff --git a/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts b/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts deleted file mode 100644 index 43f4d71c54d..00000000000 --- a/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts +++ /dev/null @@ -1,249 +0,0 @@ -// One replay suite for every agent whose readiness its live screen decides (terminal-wait-detection.ts). -import { describe, expect, it, vi } from 'vitest' -import { - createTranscriptPane, - TRANSCRIPT_PANE_PTY_ID, - waitForTranscriptIdle -} from '../../orca-runtime-tests/agent-transcript-pane-test-harness' -import { - finalReadProjection, - finalReplayFrame, - readRuntimeFixture, - type TranscriptReplayResize -} from './agent-transcript-replay-test-harness' -import { isQuietReadyScreenBody } from './terminal-wait-detection' -import { evaluateAgentStateRules } from '../../agent-state-rules/agent-state-rules-engine' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' - -export type ScreenRuledFixture = { name: string; cols: number; rows: number; what: string } - -export type ScreenRuledAgentSuite = { - agent: TuiAgent - foregroundProcess: string - ready: readonly ScreenRuledFixture[] - notReady: readonly ScreenRuledFixture[] - /** Ready recordings the text rules or the quiet-process lane settle with no screen. */ - readyWithoutScreen: readonly string[] -} - -// Mismatched grids garble cursor-addressed chrome (#23475 review). -const MISMATCHED_GRIDS = [ - [80, 24], - [100, 30], - [60, 20], - [150, 50] -] as const - -// 8s covers 3s quiescence and the 2s poll; 5s refusal allows both plus at least one poll tick. -const READY_TIMEOUT_MS = 8_000 -const REFUSAL_TIMEOUT_MS = 5_000 -// Allow for multi-MB animated recordings taking seconds in onPtyData. -const PANE_SETUP_SLACK_MS = 30_000 - -function chunkCount(name: string): number { - return Math.ceil(readRuntimeFixture(name).length / 64) -} - -/** Whether the agent's own rules read `screenLines` as an idle composer. */ -export function readsIdleComposer(agent: TuiAgent, screenLines: readonly string[]): boolean { - return evaluateAgentStateRules(agent, { readScreenLines: () => screenLines })?.state === 'idle' -} - -export function describeScreenRuledAgentTranscripts(suite: ScreenRuledAgentSuite): void { - const { agent } = suite - const rule = (screenLines: readonly string[]): boolean => readsIdleComposer(agent, screenLines) - const [firstReady] = suite.ready - if (!firstReady) { - throw new Error(`${agent}: a suite needs a ready recording`) - } - - describe('the screen rule on the final recorded frame', () => { - it.each(suite.ready)('$name ($what) reads ready', async ({ name, cols, rows }) => { - const { ruledScreenLines } = await finalReplayFrame(name, cols, rows) - expect(rule(ruledScreenLines)).toBe(true) - }) - it.each(suite.notReady)('$name ($what) does not', async ({ name, cols, rows }) => { - const { ruledScreenLines } = await finalReplayFrame(name, cols, rows) - expect(rule(ruledScreenLines)).toBe(false) - }) - }) - - describe('fails safe on a garbled grid', () => { - it.each(suite.notReady)('$name never reads ready', async ({ name, cols, rows }) => { - const resize: TranscriptReplayResize = { - atChunk: Math.floor(chunkCount(name) / 2), - cols: 100, - rows: 30 - } - const frames = [ - ...(await Promise.all(MISMATCHED_GRIDS.map(([c, r]) => finalReplayFrame(name, c, r)))), - await finalReplayFrame(name, cols, rows, resize) - ] - for (const { ruledScreenLines, waitText } of frames) { - expect(isQuietReadyScreenBody(waitText, agent, () => ruledScreenLines)).toBe(false) - } - }) - }) - - describe('through the runtime', () => { - async function pane(fixture: ScreenRuledFixture) { - const created = await createTranscriptPane({ - paneTitle: 'Terminal', - foregroundProcess: suite.foregroundProcess, - launchAgent: agent, - data: readRuntimeFixture(fixture.name), - size: { cols: fixture.cols, rows: fixture.rows } - }) - // Drain emulator parsing: one multi-MB chunk can outlive the output quiet clock unlike a live PTY's silence. - await created.runtime.readTerminal(created.handle, { screen: true }) - return created - } - - it.each(suite.ready)( - '$name: a tui-idle wait settles once the pane is quiet', - async (fixture) => { - const { runtime, handle } = await pane(fixture) - await expect( - waitForTranscriptIdle({ runtime, handle }, READY_TIMEOUT_MS) - ).resolves.toMatchObject({ - condition: 'tui-idle', - satisfied: true - }) - }, - READY_TIMEOUT_MS + PANE_SETUP_SLACK_MS - ) - - it.each(suite.notReady)( - '$name: a tui-idle wait does not settle ready', - async (fixture) => { - const { runtime, handle } = await pane(fixture) - const result = await waitForTranscriptIdle({ runtime, handle }, REFUSAL_TIMEOUT_MS).catch( - (error: unknown) => ({ satisfied: false, error: String(error) }) - ) - expect(result.satisfied).toBe(false) - }, - REFUSAL_TIMEOUT_MS + PANE_SETUP_SLACK_MS - ) - - // Why 100x30: a grid no recording was painted for. The PTY reports its real size. - it.each(suite.ready)( - '$name: on a grid the PTY does not have, the lanes the screen would shut decide', - async (fixture) => { - const options = { - paneTitle: 'Terminal', - foregroundProcess: suite.foregroundProcess, - launchAgent: agent, - data: readRuntimeFixture(fixture.name), - size: { cols: 100, rows: 30 } - } - const { runtime, handle } = await createTranscriptPane(options) - await runtime.readTerminal(handle, { screen: true }) - options.size = { cols: fixture.cols, rows: fixture.rows } - const result = await waitForTranscriptIdle({ runtime, handle }, READY_TIMEOUT_MS).catch( - () => ({ satisfied: false }) - ) - expect(result.satisfied).toBe(suite.readyWithoutScreen.includes(fixture.name)) - }, - READY_TIMEOUT_MS + PANE_SETUP_SLACK_MS - ) - - // Reattach reflows without a TUI repaint. - it( - 'on a grid reflowed to the PTY size without a repaint, the lanes the screen would shut decide', - async () => { - const options = { - paneTitle: 'Terminal', - foregroundProcess: suite.foregroundProcess, - launchAgent: agent, - data: readRuntimeFixture(firstReady.name), - size: { cols: 100, rows: 30 } - } - const { runtime, handle } = await createTranscriptPane(options) - options.size = { cols: firstReady.cols, rows: firstReady.rows } - runtime.reflowHeadlessTerminalToPtyGrid( - TRANSCRIPT_PANE_PTY_ID, - firstReady.cols, - firstReady.rows - ) - // Echoing the already-reflowed size sends no SIGWINCH, so the TUI never repaints. - runtime.onExternalPtyResize(TRANSCRIPT_PANE_PTY_ID, firstReady.cols, firstReady.rows) - await runtime.readTerminal(handle, { screen: true }) - const result = await waitForTranscriptIdle({ runtime, handle }, READY_TIMEOUT_MS).catch( - () => ({ satisfied: false }) - ) - expect(result.satisfied).toBe(suite.readyWithoutScreen.includes(firstReady.name)) - }, - READY_TIMEOUT_MS + PANE_SETUP_SLACK_MS - ) - - // Why no bytes: a restored pane has no output clock, so the provider's screen is all it has. - // Why the read projection: it is what the probe's screen read returns, draft blanked. - async function probedVerdict(fixture: ScreenRuledFixture): Promise { - const { lines, draft } = await finalReadProjection(fixture.name, fixture.cols, fixture.rows) - const { runtime, handle } = await createTranscriptPane({ - paneTitle: 'Terminal', - foregroundProcess: suite.foregroundProcess, - launchAgent: agent, - data: '' - }) - const read = vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ - handle, - status: 'running', - tail: lines, - ...(draft === undefined ? {} : { draft }), - truncated: false, - nextCursor: null, - source: 'screen' - }) - const result = await waitForTranscriptIdle({ runtime, handle }, 2_500).catch(() => ({ - satisfied: false - })) - // Presence precondition: the visible-screen probe actually ran. - expect(read).toHaveBeenCalled() - return result.satisfied === true - } - - it.each(suite.ready)( - '$name: a restored pane settles from a visible-screen read', - async (fixture) => { - expect(await probedVerdict(fixture)).toBe(true) - }, - 15_000 - ) - - it.each(suite.notReady)( - '$name: a restored pane does not settle from a visible-screen read', - async (fixture) => { - expect(await probedVerdict(fixture)).toBe(false) - }, - 15_000 - ) - - it('waits for quiet again after a ready pane repaints', async () => { - const { runtime, handle } = await pane(firstReady) - vi.useFakeTimers({ - toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] - }) - try { - const settled = vi.fn() - const waiting = runtime.waitForTerminal(handle, { - condition: 'tui-idle', - timeoutMs: READY_TIMEOUT_MS - }) - void waiting.then(settled, () => {}) - await vi.advanceTimersByTimeAsync(2_000) - expect(settled).not.toHaveBeenCalled() - - runtime.onPtyData(TRANSCRIPT_PANE_PTY_ID, readRuntimeFixture(firstReady.name), Date.now()) - await runtime.readTerminal(handle, { screen: true }) - await vi.advanceTimersByTimeAsync(2_000) - expect(settled).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(2_000) - await expect(waiting).resolves.toMatchObject({ condition: 'tui-idle', satisfied: true }) - } finally { - vi.useRealTimers() - } - }) - }) -} diff --git a/src/main/runtime/terminal/wait/terminal-interactive-wait-visibility.test.ts b/src/main/runtime/terminal/wait/terminal-interactive-wait-visibility.test.ts index bfabf727b5e..f69937580d1 100644 --- a/src/main/runtime/terminal/wait/terminal-interactive-wait-visibility.test.ts +++ b/src/main/runtime/terminal/wait/terminal-interactive-wait-visibility.test.ts @@ -12,7 +12,7 @@ import { TRANSCRIPT_PANE_PTY_ID as PTY_ID, waitForTranscriptIdle } from '../../orca-runtime-tests/agent-transcript-pane-test-harness' -import { assertTerminalAgentSendable } from '../../rpc/terminal-agent-send-guard' +import { assertTerminalAgentSendable } from '../../rpc/terminal/terminal-agent-send-guard' import { readRuntimeFixture } from './agent-transcript-replay-test-harness' vi.mock('electron', () => ({ @@ -194,36 +194,6 @@ describe('Interactive wait visibility and terminal admission', () => { await expect(runtime.getTerminalInteractiveWait(handle)).resolves.toBeUndefined() }) - it('does not accrue a probe per poll while the foreground probe wedges', async () => { - // Timeout abandons the wait, not the request; single-flight prevents one stranded remote probe per poll. - let probes = 0 - const { runtime, handle } = await createPane({ - paneTitle: '✻ Claude Code', - foregroundProcess: 'claude', - data: agentStatusOsc('waiting'), - onForegroundProbe: () => { - probes += 1 - }, - foregroundProbeHangs: true - }) - - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - try { - const probing = Promise.all([ - runtime.getTerminalInteractiveWait(handle), - runtime.getTerminalInteractiveWait(handle), - runtime.getTerminalInteractiveWait(handle) - ]) - void probing.catch(() => undefined) - await vi.advanceTimersByTimeAsync(TERMINAL_INTERACTIVE_WAIT_PROBE_TIMEOUT_MS) - await probing - - expect(probes).toBe(1) - } finally { - vi.useRealTimers() - } - }, 20_000) - it('leaves the wait unevaluated when the foreground probe wedges', async () => { // Bound remote PTY probes; a wedged host must leave wait unknown without stalling showTerminal. const { runtime, handle } = await createPane({ diff --git a/src/main/runtime/terminal/wait/terminal-interactive-wait.ts b/src/main/runtime/terminal/wait/terminal-interactive-wait.ts index 27773d46dfa..d123518d53e 100644 --- a/src/main/runtime/terminal/wait/terminal-interactive-wait.ts +++ b/src/main/runtime/terminal/wait/terminal-interactive-wait.ts @@ -171,6 +171,7 @@ export abstract class OrcaRuntimeWithGetTerminalInteractiveWait extends OrcaRunt const resolved = await this.resolveWorkspaceSelector(`id:${worktreeId}`, scope) return { worktreeId: resolved.id, + ...(resolved.identity ? { identityKey: resolved.identity.key } : {}), path: resolved.git.path, branch: resolved.git.branch, displayName: resolved.displayName diff --git a/src/main/runtime/terminal/wait/tui-idle-agent-fixture.mjs b/src/main/runtime/terminal/wait/tui-idle-agent-fixture.mjs deleted file mode 100644 index 9b923de8b64..00000000000 --- a/src/main/runtime/terminal/wait/tui-idle-agent-fixture.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Real-PTY stand-in streams under a name-only OSC title, then settles according to mode. -const mode = process.argv[2] -const workMs = Number(process.argv[3] ?? 6000) -const osc = (title) => `]0;${title}` - -process.stdout.write(osc('Codex')) -const end = Date.now() + workMs -const streaming = setInterval(() => { - if (Date.now() >= end) { - clearInterval(streaming) - if (mode === 'explicit-idle') { - process.stdout.write(osc('Codex ready')) - } - return - } - process.stdout.write(`analysing chunk ${Date.now()}\n`) -}, 250) - -// Stay alive so the PTY foreground process remains this agent, never the shell. -setInterval(() => {}, 1 << 30) diff --git a/src/main/runtime/terminal/wait/tui-idle-claude-cold-start.test.ts b/src/main/runtime/terminal/wait/tui-idle-claude-cold-start.test.ts new file mode 100644 index 00000000000..c5ce9724782 --- /dev/null +++ b/src/main/runtime/terminal/wait/tui-idle-claude-cold-start.test.ts @@ -0,0 +1,127 @@ +/** STA-2380: a shell auto-title names Claude before it draws anything; quiet alone must not make it ready. */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + createTranscriptPane, + TRANSCRIPT_PANE_PTY_ID +} from '../../orca-runtime-tests/agent-transcript-pane-test-harness' +import { waitForWorkerStartComposer } from './launched-agent-composer-readiness' +import { sendAgentTurn } from '../../orchestration/turn-delivery/send-agent-turn' +import type { RuntimePtyController } from '../lifecycle/runtime-pty-controller-contract' + +const POLL_INTERVAL_MS = 2_000 +// Shell integration's prompt and command-start markers, then oh-my-zsh's preexec title for `claude`. +const SHELL_RUNS_CLAUDE = '\x1b]133;A\x07~/repo % claude\r\n\x1b]133;C\x07\x1b]0;claude\x07' +// A later preexec hook (zsh-you-should-use) prints after Orca's marker hook and before Claude runs. +const LATER_PREEXEC_HOOK_PRINTS = + '\x1b[33mFound existing alias for "claude". You should use: "cc"\x1b[0m\r\n' +// Claude's terminal-capability probe: output with nothing visible on screen. +const CLAUDE_CAPABILITY_PROBE = '\x1b[?u\x1b]11;?\x1b\\\x1b[c' +// Claude's composer under the shell's bare title: palette reports on, paste mode on, `❯`+NBSP. +const CLAUDE_COMPOSER_BARE_TITLE = '\x1b[?2031h\x1b[?2004h╭──────╮\r\n│ ❯  │\r\n╰──────╯\x1b[?25h' + +async function startClaudePane(writes?: { data: string; at: number }[]) { + const { runtime, handle } = await createTranscriptPane({ + paneTitle: 'Terminal', + foregroundProcess: 'claude', + launchAgent: 'claude', + data: '' + }) + if (writes) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the harness's own controller, re-set with a recording write. + const { ptyController } = runtime as unknown as { ptyController: RuntimePtyController } + runtime.setPtyController({ + ...ptyController, + write: (_ptyId, data) => { + writes.push({ data, at: Date.now() }) + return true + } + }) + } + vi.useFakeTimers() + const write = (chunk: string) => runtime.onPtyData(TRANSCRIPT_PANE_PTY_ID, chunk, Date.now()) + return { runtime, handle, write } +} + +describe('tui-idle on a slow-starting Claude', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('does not settle on the shell auto-title while Claude has painted nothing', async () => { + const { runtime, handle, write } = await startClaudePane() + write(SHELL_RUNS_CLAUDE) + const settled = vi.fn() + const wait = runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 60_000 }) + wait.then(settled, () => {}) + + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 4) + write(CLAUDE_CAPABILITY_PROBE) + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 4) + expect(settled).not.toHaveBeenCalled() + + // The composer mounts with Claude's own rest title. + write('\x1b]0;✳ Claude Code\x07\x1b[?2004h╭──────╮\r\n│ ❯  │\r\n╰──────╯') + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS) + await expect(wait).resolves.toMatchObject({ satisfied: true }) + }) + + it('does not settle on text a later preexec hook printed before Claude ran (C1 F1)', async () => { + const { runtime, handle, write } = await startClaudePane() + write(SHELL_RUNS_CLAUDE + LATER_PREEXEC_HOOK_PRINTS) + const settled = vi.fn() + const wait = runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 60_000 }) + wait.then(settled, () => {}) + + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 5) + expect(settled).not.toHaveBeenCalled() + + // Claude mounts its composer but the title stays the shell's bare name (title disabled). + write(CLAUDE_COMPOSER_BARE_TITLE) + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 3) + await expect(wait).resolves.toMatchObject({ satisfied: true }) + }) +}) + +describe('worker start on a slow-starting Claude', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('holds readiness and the brief until the composer exists, despite preexec hook text', async () => { + const writes: { data: string; at: number }[] = [] + const { runtime, handle, write } = await startClaudePane(writes) + write(SHELL_RUNS_CLAUDE + LATER_PREEXEC_HOOK_PRINTS) + + // Worker start: readiness race (tui-idle launch lane vs. composer marker), then the dispatch's brief. + let readyAt: number | null = null + const delivered = waitForWorkerStartComposer(runtime, handle, 'claude', 60_000).then( + (ready) => { + readyAt = Date.now() + expect(ready.satisfied).toBe(true) + return sendAgentTurn({ + kind: 'terminal', + runtime, + handle, + turn: { purpose: 'dispatch-preamble', body: 'TASK: brief', operationId: 'op-1' } + }) + } + ) + delivered.catch(() => {}) + + // A whole silent cold start: nothing may reach the PTY while Claude has no composer. + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 6) + expect(readyAt).toBeNull() + expect(writes).toEqual([]) + + const composerAt = Date.now() + write(CLAUDE_COMPOSER_BARE_TITLE) + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 8) + await delivered + expect(readyAt).not.toBeNull() + expect(readyAt!).toBeGreaterThanOrEqual(composerAt) + const brief = writes.find((entry) => entry.data.includes('TASK: brief')) + expect(brief).toBeDefined() + expect(brief!.at).toBeGreaterThanOrEqual(composerAt) + }) +}) diff --git a/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts b/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts index 235ad079e13..1b386ed39a4 100644 --- a/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts +++ b/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts @@ -14,6 +14,7 @@ import { type AgentStateVerdict } from '../../agent-state-rules/agent-state-rules-engine' import type { TuiIdleHookTurn } from './tui-idle-hook-lane' +import { hasTerminalAgentPainted } from '../input/terminal-command-paint' import type { FirstPartyAgentStatus, TuiIdleEvaluationInput, @@ -140,6 +141,8 @@ export function ptyTuiIdleEvidence( agent, firstPartyStatus: source.getFirstPartyAgentStatus(pty.ptyId), readHookTurn: hookTurnReader(source, agent, pty.ptyId), - quiescenceMs: source.quiescenceMs + quiescenceMs: source.quiescenceMs, + // Why per agent: Claude's corroboration is its own composer marker, which no shell hook can print. + readCommandPainted: () => hasTerminalAgentPainted(pty, agent) } } diff --git a/src/main/runtime/terminal/wait/tui-idle-evidence.ts b/src/main/runtime/terminal/wait/tui-idle-evidence.ts index 94d606d578b..89c7e14fb08 100644 --- a/src/main/runtime/terminal/wait/tui-idle-evidence.ts +++ b/src/main/runtime/terminal/wait/tui-idle-evidence.ts @@ -87,7 +87,8 @@ export function hasSustainedTitleIdle( record: TuiIdleEvidenceRecord, agent: TuiAgent | null | undefined, quiescenceMs: number, - launchReadiness = false + launchReadiness = false, + commandPainted: () => boolean = () => true ): boolean { if (record.lastAgentStatus !== 'idle') { return false @@ -98,7 +99,17 @@ export function hasSustainedTitleIdle( return true } // No output clock means no corroboration for name-only titles; await stronger evidence or timeout (#6011). - return hasQuietOutput(record, quiescenceMs) + return hasQuietPaintedOutput(record, quiescenceMs, commandPainted) +} + +/** Why paint too: a shell auto-title names the agent at exec, so a slow boot that has drawn + * nothing yet is quiet under its name long before its composer exists (STA-2380). */ +function hasQuietPaintedOutput( + record: TuiIdleEvidenceRecord, + quiescenceMs: number, + commandPainted: () => boolean +): boolean { + return hasQuietOutput(record, quiescenceMs) && commandPainted() } /** Why a missing clock is not quiet: an adopted or restored pane cannot measure it. */ @@ -140,6 +151,10 @@ export type TuiIdleEvaluationInput = { /** Waiting for a just-launched agent to open its composer, where a name-only title proves * nothing until the stream goes quiet. */ launchReadiness?: boolean + /** Whether the running command has painted since the shell started it: the agent's own + * composer marker where it draws one (Claude), else any visible byte after the command-start + * marker; true when the shell sends no marker. Corroborates name-only titles alongside quiet. */ + readCommandPainted?: () => boolean } export type TuiIdleVerdict = @@ -264,11 +279,25 @@ function rankTuiIdleEvidence(input: TuiIdleEvaluationInput): TuiIdleVerdict { // Screen rules veto weak name/process guesses and replace sustained-title inference. const ruled = input.readAgentRuleVerdict() if (ruled !== null) { - return isSettledWeakIdle(ruled, input.record, input.quiescenceMs, input.launchReadiness) + return isSettledWeakIdle( + ruled, + input.record, + input.quiescenceMs, + input.launchReadiness, + input.readCommandPainted + ) ? READY_WEAK : { kind: 'pending', quietForeground: 'closed' } } - if (hasSustainedTitleIdle(input.record, input.agent, input.quiescenceMs, input.launchReadiness)) { + if ( + hasSustainedTitleIdle( + input.record, + input.agent, + input.quiescenceMs, + input.launchReadiness, + input.readCommandPainted + ) + ) { return READY_WEAK } return { @@ -286,12 +315,14 @@ function isSettledWeakIdle( verdict: AgentStateVerdict, record: TuiIdleEvidenceRecord, quiescenceMs: number, - launchReadiness = false + launchReadiness = false, + commandPainted: () => boolean = () => true ): boolean { return ( verdict.state === 'idle' && verdict.strength === 'weak' && - ((!verdict.requiresQuiet && !launchReadiness) || hasQuietOutput(record, quiescenceMs)) + ((!verdict.requiresQuiet && !launchReadiness) || + hasQuietPaintedOutput(record, quiescenceMs, commandPainted)) ) } diff --git a/src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts b/src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts index fc14365be28..1a30a96daaf 100644 --- a/src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts +++ b/src/main/runtime/terminal/wait/tui-idle-hook-lane-runtime.test.ts @@ -1,13 +1,6 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it, vi, afterEach } from 'vitest' -import { - createTranscriptPane, - TRANSCRIPT_PANE_PTY_ID, - waitForTranscriptIdle -} from '../../orca-runtime-tests/agent-transcript-pane-test-harness' -import { createHookListenerState } from '../../../../shared/agent-hook-listener/listener-state' -import { normalizeHermesEvent } from '../../../../shared/agent-hook-listener/providers/hermes-events' +import { createTranscriptPane } from '../../orca-runtime-tests/agent-transcript-pane-test-harness' + import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' @@ -20,182 +13,6 @@ vi.mock('electron', () => ({ app: { getPath: vi.fn(() => '/tmp') } })) -describe('Hermes captured hook readiness', () => { - const captured = readFileSync( - join(__dirname, '../../__fixtures__', 'hermes-tui-ready.txt'), - 'utf8' - ) - - /** Run managed Hermes payloads through the real normalizer so event-mapping regressions fail at this runtime boundary too. */ - const status = (eventName: string, payload: Record = {}): string => { - const parsed = normalizeHermesEvent(createHookListenerState(), eventName, '', 'pane-1', payload) - expect(parsed, `hermes plugin event ${eventName} must normalize to a status`).not.toBeNull() - return `\x1b]9999;${JSON.stringify(parsed)}\x07` - } - - const readyPane = async () => { - const pane = await createTranscriptPane({ - paneTitle: 'Hermes Agent', - foregroundProcess: 'hermes', - launchAgent: 'hermes', - size: { cols: 120, rows: 31 }, - data: captured - }) - await pane.runtime.readTerminal(pane.handle, { screen: true }) - return pane - } - - describe('Hermes TUI readiness from a captured PTY', () => { - it('settles tui-idle on a ready composer after the session-boundary hook', async () => { - const { runtime, handle } = await readyPane() - // What Orca's own managed plugin sends for `on_session_start`. - runtime.onPtyData( - TRANSCRIPT_PANE_PTY_ID, - status('on_session_start', { session_id: 's1' }), - Date.now() - ) - - const read = vi.spyOn(runtime, 'readTerminal') - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 2_000 }) - ).resolves.toMatchObject({ satisfied: true }) - // The retained screen decides without a provider screen round trip. - expect(read.mock.calls.filter(([, options]) => options?.screen === true)).toEqual([]) - }, 5_000) - - it('settles through a leaf handle whose retained tail never showed the ready screen', async () => { - const { runtime } = await readyPane() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Access the real synced leaf and handle issuer for this route regression. - const internals = runtime as unknown as { - leaves: Map - issueHandle: (leaf: unknown) => string - } - const leaf = internals.leaves.values().next().value - expect(leaf).toBeDefined() - expect([...leaf!.tailBuffer, leaf!.tailPartialLine].join('\n')).not.toMatch(/\bready\b/i) - runtime.onPtyData( - TRANSCRIPT_PANE_PTY_ID, - status('on_session_start', { session_id: 's1' }), - Date.now() - ) - - await expect( - runtime.waitForTerminal(internals.issueHandle(leaf), { - condition: 'tui-idle', - timeoutMs: 2_000 - }) - ).resolves.toMatchObject({ satisfied: true }) - }, 5_000) - - it('does not settle while a turn the user started is still running', async () => { - const { runtime, handle } = await readyPane() - runtime.onPtyData( - TRANSCRIPT_PANE_PTY_ID, - status('on_session_start', { session_id: 's1' }), - Date.now() - ) - // `pre_llm_call` — the first event that means a turn actually began. - runtime.onPtyData( - TRANSCRIPT_PANE_PTY_ID, - status('pre_llm_call', { user_message: 'hi' }), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 550 }) - ).rejects.toThrow('timeout') - }, 3_000) - - it('does not settle on a turn-end done row without a ready screen', async () => { - const { runtime, handle } = await createTranscriptPane({ - paneTitle: 'Hermes Agent', - foregroundProcess: 'hermes', - launchAgent: 'hermes', - data: '' - }) - // `post_llm_call` lands `done` without the boundary flag; the #6011 rule still applies. - runtime.onPtyData( - TRANSCRIPT_PANE_PTY_ID, - status('post_llm_call', { session_id: 's1' }), - Date.now() - ) - - await expect( - runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 550 }) - ).rejects.toThrow('timeout') - }, 3_000) - }) -}) - -describe('Claude indexed task wakeup readiness', () => { - const PANE = 'tab-1:11111111-1111-4111-8111-111111111111' - const ready = readFileSync( - join(import.meta.dirname, '../../__fixtures__/claude-ready-task-wakeup.txt'), - 'utf8' - ) - - function owedRow(paneKey: string): AgentStatusIpcPayload { - const now = Date.now() - return { - paneKey, - state: 'working', - mainAgent: { state: 'done', stateStartedAt: now }, - agentType: 'claude', - prompt: '', - connectionId: null, - launchToken: 'transcript-launch', - claudeTaskWakeupPending: 'notification', - providerSession: { key: 'session_id', id: 'session-a' }, - observation: { - origin: 'hook', - authorityId: 'host-a', - incarnation: 1, - revision: 1, - observedAt: now - }, - receivedAt: now, - stateStartedAt: now - } - } - - afterEach(() => vi.useRealTimers()) - - describe('Claude readiness indexed status reads', () => { - it.each([true, false])( - 'reads only its pane with 512 unrelated agents, including an empty index: pending=%s', - async (pending) => { - const unrelated = Array.from({ length: 512 }, (_, index) => owedRow(`other:${index}`)) - const row = owedRow(PANE) - const full = vi.fn(() => [row, ...unrelated]) - const indexed = vi.fn((paneKey: string) => (pending && paneKey === PANE ? [row] : [])) - const pane = await createTranscriptPane( - { - paneTitle: 'Terminal', - foregroundProcess: 'claude', - data: ready, - launchAgent: 'claude' - }, - { getAgentStatusSnapshot: full, getAgentStatusSnapshotForPane: indexed } - ) - row.receivedAt = Date.now() - full.mockClear() - indexed.mockClear() - try { - const waiting = waitForTranscriptIdle(pane, 2_000) - await (pending - ? expect(waiting).rejects.toThrow(/timeout/) - : expect(waiting).resolves.toMatchObject({ satisfied: true })) - expect(indexed).toHaveBeenCalled() - expect(new Set(indexed.mock.calls.map(([paneKey]) => paneKey))).toEqual(new Set([PANE])) - expect(full).not.toHaveBeenCalled() - } finally { - pane.runtime.onPtyExit(TRANSCRIPT_PANE_PTY_ID, 0) - } - } - ) - }) -}) - describe('Canonical hook status readiness', () => { // The harness pane's identity (agent-transcript-pane-test-harness.ts). const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') @@ -213,14 +30,7 @@ describe('Canonical hook status readiness', () => { '' ].join('\r\n') // OpenCode 1.18's question tool, which paints no dialog wording the blocked layer knows. - const OPENCODE_QUESTION = [ - ' ┃ Which color do you prefer?', - ' ┃ 1. Red', - ' ┃ 2. Blue', - ' ┃ 3. Type your own answer', - ' ┃ ↑↓ select enter submit esc dismiss', - '' - ].join('\r\n') + // Shorter than the 2 s poll, so only the synchronous verdict can settle a wait. const WAIT_MS = 150 @@ -280,63 +90,7 @@ describe('Canonical hook status readiness', () => { ).toBe('ready') }) - it('ignores the row the PTY id held before a respawn', async () => { - const before = Date.now() - 1000 - const rows = (): AgentStatusIpcPayload[] => [ - row({ receivedAt: before, stateStartedAt: before }) - ] - expect(await waitOutcome({ rows })).toBe('ready') - expect( - await waitOutcome({ - rows, - afterCreate: (runtime) => - runtime.synchronizePtyOutputSequenceFromProvider(TRANSCRIPT_PANE_PTY_ID, { - value: 0, - generation: 'reset' - }) - }) - ).toBe('timeout') - }) - // Input starts a possible new turn, including typed agent restarts; prior done hooks cannot settle it. - it.each([ - ['a prompt Orca sent', 'next task\r'], - ['the user restarting the agent in the same shell', 'pi\r'] - ])('reads no done from before %s', async (_label, input) => { - const before = Date.now() - 1000 - const rows = (): AgentStatusIpcPayload[] => [ - row({ receivedAt: before, stateStartedAt: before }) - ] - const typeAt = (at: number) => (runtime: OrcaRuntimeService) => { - runtime.terminalRunFacts.recordInput(TRANSCRIPT_PANE_PTY_ID, 'driving', input, at) - } - expect(await waitOutcome({ rows, afterCreate: typeAt(before - 1) })).toBe('ready') - expect(await waitOutcome({ rows, afterCreate: typeAt(before + 1) })).toBe('timeout') - }) - - it('reads no done from before a prompt sent just ahead of an adoption of the running agent', async () => { - const before = Date.now() - 1000 - const rows = (): AgentStatusIpcPayload[] => [ - row({ receivedAt: before, stateStartedAt: before }) - ] - expect( - await waitOutcome({ - rows, - afterCreate: (runtime) => { - runtime.terminalRunFacts.recordInput( - TRANSCRIPT_PANE_PTY_ID, - 'driving', - 'next\r', - before + 1 - ) - runtime.noteTerminalSpawnCommit({ - id: TRANSCRIPT_PANE_PTY_ID, - agentSessionEnsure: { disposition: 'adopted' } - }) - } - }) - ).toBe('timeout') - }) // Pi brackets each message in OSC 133 zones itself, so a command marker is no process boundary. it('keeps the row while the agent paints its own shell-integration markers', async () => { @@ -366,22 +120,5 @@ describe('Canonical hook status readiness', () => { }) ).toBe('ready') }) - - it('blocks on an open question the hook reports, and settles once it is answered', async () => { - const options = { launchAgent: 'opencode' as const, data: OPENCODE_QUESTION } - expect(await waitOutcome({ ...options, rows: () => [] })).toBe('timeout') - expect( - await waitOutcome({ - ...options, - rows: () => [row({ agentType: 'opencode', state: 'waiting', receivedAt: Date.now() + 1 })] - }) - ).toBe('blocked:agent-interactive-prompt') - expect( - await waitOutcome({ - ...options, - rows: () => [row({ agentType: 'opencode', receivedAt: Date.now() + 1 })] - }) - ).toBe('ready') - }) }) }) diff --git a/src/main/runtime/terminal/wait/tui-idle-name-only-real-pty.integration.test.ts b/src/main/runtime/terminal/wait/tui-idle-name-only-real-pty.integration.test.ts deleted file mode 100644 index 504b2627eff..00000000000 --- a/src/main/runtime/terminal/wait/tui-idle-name-only-real-pty.integration.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { fileURLToPath } from 'node:url' -import * as pty from 'node-pty' -import { describe, it, type TestContext } from 'vitest' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { makeTuiIdleRuntime } from './tui-idle-wait-test-harness' -import type { RuntimeSyncWindowGraph } from '../../../../shared/runtime-session-contracts' -import { TERMINAL_LIFECYCLE_METHODS } from '../../rpc/methods/terminal/terminal-lifecycle-methods' - -// #6011: real bytes, foreground reads and elapsed time prove name-only OSC titles cannot settle a streaming agent immediately. - -const FIXTURE = fileURLToPath(new URL('./tui-idle-agent-fixture.mjs', import.meta.url)) -const WORKTREE_ID = 'repo-1::/tmp/tui-idle-real-pty' -const TAB_ID = '55555555-5555-4555-8555-555555555555' -const LEAF_ID = '66666666-6666-4666-8666-666666666666' -const PTY_ID = 'pty-tui-idle-real' - -const waitMethod = TERMINAL_LIFECYCLE_METHODS.find((method) => method.name === 'terminal.wait')! - -async function startRealAgentPane( - context: TestContext, - mode: 'explicit-idle' | 'quiet', - workMs: number -) { - const child = pty.spawn(process.execPath, [FIXTURE, mode, String(workMs)], { - name: 'xterm-256color', - cols: 120, - rows: 30, - cwd: '/tmp' - }) - context.onTestFinished(() => { - try { - child.kill() - } catch { - // The fixture may already be gone. - } - }) - - // Real foreground read against the real pty, so corroboration is host-produced here too. - const runtime = makeTuiIdleRuntime({ - repoPath: '/tmp/tui-idle-real-pty', - getForegroundProcess: async () => child.process || null - }) - runtime.attachWindow(1) - const graph: RuntimeSyncWindowGraph = { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Agent', - activeLeafId: LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - leafId: LEAF_ID, - paneRuntimeId: 1, - ptyId: PTY_ID, - paneTitle: null, - title: '' - } - ] - } - runtime.syncWindowGraph(1, graph) - - const transcript: string[] = [] - child.onData((data) => { - transcript.push(data) - runtime.onPtyData(PTY_ID, data, Date.now()) - }) - - const { terminals } = await runtime.listTerminals(`id:${WORKTREE_ID}`) - return { runtime, transcript, handle: terminals[0].handle } -} - -/** Exactly what `orca terminal wait --terminal --for tui-idle` reaches over RPC. */ -async function terminalWait( - runtime: OrcaRuntimeService, - terminal: string, - timeoutMs: number -): Promise<{ satisfied: boolean; elapsedMs: number }> { - const startedAt = Date.now() - try { - const result = await waitMethod.handler({ terminal, for: 'tui-idle', timeoutMs }, { runtime }) - return { satisfied: result.wait.satisfied === true, elapsedMs: Date.now() - startedAt } - } catch (error) { - // Why only `timeout`: an unsatisfied wait is the outcome under test, but any other - // failure means the harness broke and must not read as a passing refusal. - if ((error instanceof Error ? error.message : String(error)) !== 'timeout') { - throw error - } - return { satisfied: false, elapsedMs: Date.now() - startedAt } - } -} - -// Each case owns its PTY and runtime; overlap the real idle observation windows. -describe.skipIf(process.platform === 'win32')('tui-idle against a real agent pty', () => { - it.concurrent('does not satisfy while the real process streams under a name-only title', async (context) => { - const { expect } = context - const { runtime, transcript, handle } = await startRealAgentPane(context, 'quiet', 60_000) - // Wait for real control bytes before measuring idle behavior. - await expect.poll(() => transcript.join(''), { timeout: 5_000 }).toContain(']0;Codex') - - const outcome = await terminalWait(runtime, handle, 8_000) - expect(outcome.satisfied).toBe(false) - expect(outcome.elapsedMs).toBeGreaterThanOrEqual(7_500) - }, 25_000) - - it.concurrent('satisfies once the real process emits an explicit idle title', async (context) => { - const { expect } = context - const { runtime, handle } = await startRealAgentPane(context, 'explicit-idle', 3_000) - await new Promise((resolve) => setTimeout(resolve, 500)) - - const outcome = await terminalWait(runtime, handle, 20_000) - expect(outcome.satisfied).toBe(true) - expect(outcome.elapsedMs).toBeGreaterThanOrEqual(1_500) - }, 28_000) - - it.concurrent('satisfies once the real process goes quiet with the agent still in foreground', async (context) => { - const { expect } = context - const { runtime, handle } = await startRealAgentPane(context, 'quiet', 3_000) - await new Promise((resolve) => setTimeout(resolve, 500)) - - const outcome = await terminalWait(runtime, handle, 20_000) - expect(outcome.satisfied).toBe(true) - // Corroboration is never instant: quiescence must elapse after the last byte. - expect(outcome.elapsedMs).toBeGreaterThanOrEqual(3_000) - }, 28_000) -}) diff --git a/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts b/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts new file mode 100644 index 00000000000..b5b756c4cbf --- /dev/null +++ b/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts @@ -0,0 +1,379 @@ +/** STA-2380 (C1 F1): Orca's zsh OSC 133;C hook runs first in `preexec_functions`, so a later user or + * framework preexec hook prints before the agent exists. Real zsh under the production wrapper, a + * silent stand-in `claude`, then the captured bytes replayed through the real tui-idle wait. */ +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import * as pty from 'node-pty' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { getShellLaunchConfig } from '../../../providers/local-pty/local-pty-shell-ready' +import { selectShellStartupFeatures } from '../../../pty/shell-startup/shell-startup-features' +import { hasZsh, ZSH_PATH } from '../../../pty/shell-startup/zsh-startup-hook-pty-harness' +import { + createTranscriptPane, + TRANSCRIPT_PANE_PTY_ID +} from '../../orca-runtime-tests/agent-transcript-pane-test-harness' +import { normalizeTerminalChunk } from '../output/terminal-ansi-normalization' +import { hasTerminalAgentPainted, TerminalCommandPaint } from '../input/terminal-command-paint' + +const itWithZsh = hasZsh ? it : it.skip +const POLL_INTERVAL_MS = 2_000 +const COMMAND_START = '\x1b]133;C' +// The stand-in's first bytes: Claude turns on palette-change reports before its composer (captures +// from 2.1.291 through 2.1.316; no cutoff is claimed). +const AGENT_FIRST_BYTES = '\x1b[?2031h' +const CLAUDE_COMPOSER_PROMPT = '❯ ' +const CLAUDE_REST_TITLE = '✳ Claude Code' +/** Real silence between the shell handing off and the stand-in's first byte. */ +const AGENT_SILENT_MS = 1_200 + +type HookCase = { + name: string + /** The user's .zshrc; `$ORCA_TEST_HOOK_ORDER` receives `preexec_functions` as the hook sees it. */ + zshrc: string + hookName: string + /** Whether bytes from the shell side alone satisfy the any-visible-byte paint latch. */ + anyBytePaintBeforeAgent: boolean + /** Whether the stand-in sets Claude's own rest title; otherwise the pane keeps the hook's bare name. */ + agentSetsRestTitle: boolean + /** Bytes only the user hook emits, to place it in the stream; null for a hook that prints nothing. */ + hookOutput: string | null +} + +const RECORD_HOOK_ORDER = 'print -r -- "${preexec_functions[*]}" > "$ORCA_TEST_HOOK_ORDER"' + +const HOOK_CASES: readonly HookCase[] = [ + { + // oh-my-zsh lib/termsupport.zsh: `title` prints the window and tab titles, nothing visible. + name: 'oh-my-zsh termsupport preexec (title-only)', + zshrc: `autoload -Uz add-zsh-hook +_omz_termsupport_preexec() { ${RECORD_HOOK_ORDER}; print -Pn "\\e]2;claude\\a\\e]1;claude\\a" } +add-zsh-hook preexec _omz_termsupport_preexec +`, + hookName: '_omz_termsupport_preexec', + anyBytePaintBeforeAgent: false, + agentSetsRestTitle: false, + hookOutput: '\x1b]2;claude\x07' + }, + { + // powerlevel10k's _p9k_preexec and starship (precmd only) print nothing at command start. + name: 'powerlevel10k/starship-style preexec (silent)', + zshrc: `autoload -Uz add-zsh-hook +_p9k_preexec() { ${RECORD_HOOK_ORDER}; typeset -g _P9K_TIMER_START=$EPOCHREALTIME } +add-zsh-hook preexec _p9k_preexec +`, + hookName: '_p9k_preexec', + anyBytePaintBeforeAgent: false, + agentSetsRestTitle: true, + hookOutput: null + }, + { + // zsh-you-should-use reminds about an alias from preexec: visible text after Orca's marker. + name: 'zsh-you-should-use preexec (prints) under an oh-my-zsh title', + zshrc: `autoload -Uz add-zsh-hook +_omz_termsupport_preexec() { print -Pn "\\e]2;claude\\a\\e]1;claude\\a" } +_ysu_preexec() { ${RECORD_HOOK_ORDER}; print -P '%F{yellow}Found existing alias for "claude". You should use: "cc".%f' } +add-zsh-hook preexec _omz_termsupport_preexec +add-zsh-hook preexec _ysu_preexec +`, + hookName: '_ysu_preexec', + anyBytePaintBeforeAgent: true, + agentSetsRestTitle: false, + hookOutput: 'Found existing alias for "claude"' + } +] + +type Chunk = { data: string; at: number } + +type Capture = { chunks: Chunk[]; hookOrder: string } + +/** A `claude` that boots silently, then draws Claude's composer frame and waits for input. */ +function standInClaude(setsRestTitle: boolean): string { + const title = setsRestTitle ? `printf '\\033]0;${CLAUDE_REST_TITLE}\\007'\n` : '' + return `#!/bin/sh +sleep ${AGENT_SILENT_MS / 1000} +printf '\\033[?2031h\\033[?2004h' +${title}printf '╭──────────╮\\r\\n│ ${CLAUDE_COMPOSER_PROMPT} │\\r\\n╰──────────╯\\033[?25h' +sleep 60 +` +} + +async function captureLaunch(hookCase: HookCase): Promise { + const root = mkdtempSync(join(tmpdir(), 'orca-preexec-order-')) + const home = join(root, 'home') + const bin = join(root, 'bin') + const fixturePath = `${bin}:/usr/bin:/bin` + mkdirSync(home) + mkdirSync(bin) + // Login profiles can reorder PATH, so restore the stand-in before the startup command runs. + writeFileSync( + join(home, '.zshrc'), + `export PATH=${quotePosixShell(fixturePath)}\n${hookCase.zshrc}` + ) + const standIn = join(bin, 'claude') + writeFileSync(standIn, standInClaude(hookCase.agentSetsRestTitle)) + chmodSync(standIn, 0o755) + const hookOrderPath = join(root, 'hook-order.txt') + + // The production local launch: markers on, the agent command delivered from the first zle line. + const features = selectShellStartupFeatures({ + shellPath: ZSH_PATH, + env: { HOME: home }, + hasStartupCommand: true, + waitsForShellReady: false, + emitsStartupIdentity: false + }) + const launch = getShellLaunchConfig(ZSH_PATH, features, 'claude') + expect(launch.args, 'the zsh wrapper tree must be usable').not.toBeNull() + // Resolve user config from the sandbox HOME only. + const { ORCA_ORIG_ZDOTDIR: _dropped, ...launchEnv } = launch.env + + const proc = pty.spawn(ZSH_PATH, launch.args ?? ['-l'], { + name: 'xterm-256color', + cols: 120, + rows: 30, + cwd: home, + env: { + ...launchEnv, + PATH: fixturePath, + HOME: home, + TERM: 'xterm-256color', + LANG: 'en_US.UTF-8', + ORCA_TEST_HOOK_ORDER: hookOrderPath + } + }) + const chunks: Chunk[] = [] + let output = '' + let answeredCompinit = false + const exited = new Promise((resolve) => { + proc.onExit(() => resolve()) + }) + try { + await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`no composer frame from the stand-in:\n${output}`)), + 25_000 + ) + proc.onData((data) => { + chunks.push({ data, at: Date.now() }) + output += data + // Ubuntu's global zshrc runs a plain compinit, which stops at its insecure-directory prompt + // on CI runners before zle exists; answer it as zsh-startup-hook-pty-harness.ts does. The + // bytes land before Orca's OSC 133;C marker, so stream-offset attribution never sees them. + if (!answeredCompinit && output.includes('Ignore insecure directories')) { + answeredCompinit = true + proc.write('y\r') + } + if (output.includes(CLAUDE_COMPOSER_PROMPT)) { + clearTimeout(timer) + resolve() + } + }) + proc.onExit(() => { + clearTimeout(timer) + reject(new Error(`zsh exited before the stand-in painted:\n${output}`)) + }) + }) + return { chunks, hookOrder: readFileSync(hookOrderPath, 'utf8').trim() } + } finally { + try { + proc.kill() + } catch { + // Already gone. + } + // zsh writes history and session files on the way out; remove the tree after it has gone. + // ast-grep-ignore: test-no-real-time-wait -- the condition is zsh's exit (`exited`); the cap only keeps a shell that ignores SIGHUP from stalling teardown, and rmSync retries cover a late writer. + await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2_000))]) + rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } +} + +type SplitCapture = { + /** The shell and its hooks: every byte before the stand-in's first escape. */ + shell: Chunk[] + /** The stand-in from its first byte on. A chunk that straddled the boundary is split, keeping its time. */ + agent: Chunk[] +} + +/** Attribute bytes by their offset in the accumulated stream, not by PTY read boundaries: the anchor + * may arrive split across reads or coalesced with the shell's last bytes (C2 F2). */ +function splitAtAgentStart(chunks: readonly Chunk[]): SplitCapture { + const stream = chunks.map((chunk) => chunk.data).join('') + const agentOffset = stream.indexOf(AGENT_FIRST_BYTES) + expect(agentOffset, 'the stand-in must have painted').toBeGreaterThan(0) + const shell: Chunk[] = [] + const agent: Chunk[] = [] + let offset = 0 + for (const chunk of chunks) { + const end = offset + chunk.data.length + if (end <= agentOffset) { + shell.push(chunk) + } else if (offset >= agentOffset) { + agent.push(chunk) + } else { + const split = agentOffset - offset + shell.push({ data: chunk.data.slice(0, split), at: chunk.at }) + agent.push({ data: chunk.data.slice(split), at: chunk.at }) + } + offset = end + } + return { shell, agent } +} + +/** The launch sequence as stream offsets over the joined bytes: Orca's command-start marker, then + * the user hook's output, then the agent's first byte and its composer. No assertion reads a PTY + * read boundary or a timestamp, so how the kernel chunked the stream cannot fail it (C3-1). */ +function assertLaunchOrder(chunks: readonly Chunk[], hookCase: HookCase): void { + const { shell, agent } = splitAtAgentStart(chunks) + const shellBytes = shell.map((chunk) => chunk.data).join('') + const agentBytes = agent.map((chunk) => chunk.data).join('') + const commandStart = shellBytes.indexOf(COMMAND_START) + expect(commandStart).toBeGreaterThanOrEqual(0) + expect(shellBytes).not.toContain(AGENT_FIRST_BYTES) + expect(agentBytes.startsWith(AGENT_FIRST_BYTES)).toBe(true) + expect(agentBytes).toContain(CLAUDE_COMPOSER_PROMPT) + if (hookCase.hookOutput !== null) { + // The later hook printed after Orca's marker and before the agent existed: the C1 F1 shape. + expect(shellBytes.indexOf(hookCase.hookOutput, commandStart)).toBeGreaterThan(commandStart) + } +} + +/** PTY read shapes a correct capture may arrive in; `agentOffset` is the anchor's stream offset. */ +const RECHUNKINGS: readonly (readonly [ + string, + (stream: string, agentOffset: number) => string[] +])[] = [ + ['coalesced into one read', (stream) => [stream]], + [ + 'split into 3-byte reads', + (stream) => + Array.from({ length: Math.ceil(stream.length / 3) }, (_, i) => stream.slice(i * 3, i * 3 + 3)) + ], + [ + 'the anchor split across two reads', + (stream, agentOffset) => [stream.slice(0, agentOffset + 3), stream.slice(agentOffset + 3)] + ], + [ + "the shell's last bytes and the agent's first output coalesced in one read", + (stream, agentOffset) => { + const joinEnd = agentOffset + AGENT_FIRST_BYTES.length + 4 + return [ + stream.slice(0, agentOffset - 4), + stream.slice(agentOffset - 4, joinEnd), + stream.slice(joinEnd) + ] + } + ] +] + +/** Feeds captured bytes the way pty-output-ingestion does: normalized, with the pending-escape carry + * kept across calls so an escape cut by a read boundary is not misread. */ +function paintObserver(paint: TerminalCommandPaint): (chunks: readonly Chunk[]) => void { + let pendingAnsi = '' + return (chunks) => { + for (const chunk of chunks) { + const normalized = normalizeTerminalChunk(chunk.data, pendingAnsi) + pendingAnsi = normalized.pendingAnsi + paint.observe(chunk.data, normalized.text) + } + } +} + +describe.skipIf(process.platform === 'win32')('tui-idle under real zsh preexec hooks', () => { + let userDataPath = '' + let previousUserDataPath: string | undefined + + beforeAll(() => { + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + userDataPath = mkdtempSync(join(tmpdir(), 'orca-preexec-order-wrappers-')) + process.env.ORCA_USER_DATA_PATH = userDataPath + }) + + afterAll(() => { + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + rmSync(userDataPath, { recursive: true, force: true }) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + describe.each(HOOK_CASES)('$name', (hookCase) => { + let capture: Capture + + beforeAll(async () => { + capture = await captureLaunch(hookCase) + }, 40_000) + + itWithZsh( + "runs Orca's marker hook before the user hook, so hook output follows OSC 133;C", + () => { + expect(capture.hookOrder.split(/\s+/)[0]).toBe('__orca_osc133_preexec') + expect(capture.hookOrder).toContain(hookCase.hookName) + assertLaunchOrder(capture.chunks, hookCase) + } + ) + + itWithZsh.each(RECHUNKINGS)( + 'attributes paint the same way with the capture %s', + (_label, rechunk) => { + const stream = capture.chunks.map((chunk) => chunk.data).join('') + const agentOffset = stream.indexOf(AGENT_FIRST_BYTES) + const at = capture.chunks[0].at + const rechunked = rechunk(stream, agentOffset).map((data) => ({ data, at })) + expect(rechunked.map((chunk) => chunk.data).join('')).toBe(stream) + assertLaunchOrder(rechunked, hookCase) + const { shell, agent } = splitAtAgentStart(rechunked) + expect(shell.map((chunk) => chunk.data).join('')).toBe(stream.slice(0, agentOffset)) + expect(agent.map((chunk) => chunk.data).join('')).toBe(stream.slice(agentOffset)) + const paint = new TerminalCommandPaint() + const observe = paintObserver(paint) + observe(shell) + expect(paint.hasPainted()).toBe(hookCase.anyBytePaintBeforeAgent) + expect(hasTerminalAgentPainted({ commandPaint: paint }, 'claude')).toBe(false) + observe(agent) + expect(hasTerminalAgentPainted({ commandPaint: paint }, 'claude')).toBe(true) + } + ) + + itWithZsh( + 'keeps `terminal wait --for tui-idle` pending through the silent boot, then settles on the composer', + async () => { + const { shell, agent } = splitAtAgentStart(capture.chunks) + const { runtime, handle } = await createTranscriptPane({ + paneTitle: 'Terminal', + foregroundProcess: 'claude', + launchAgent: 'claude', + data: '' + }) + vi.useFakeTimers() + const replay = async (chunks: readonly Chunk[], previousAt: number): Promise => { + let at = previousAt + for (const chunk of chunks) { + await vi.advanceTimersByTimeAsync(Math.max(0, chunk.at - at)) + at = chunk.at + runtime.onPtyData(TRANSCRIPT_PANE_PTY_ID, chunk.data, Date.now()) + } + return at + } + + const shellDoneAt = await replay(shell, capture.chunks[0].at) + const settled = vi.fn() + const wait = runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 60_000 }) + wait.then(settled, () => {}) + // A cold start slower than the capture: the shell's bytes are all the pane has for 12 s. + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 6) + expect(settled).not.toHaveBeenCalled() + + await replay(agent, shellDoneAt + POLL_INTERVAL_MS * 6) + await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 3) + await expect(wait).resolves.toMatchObject({ satisfied: true }) + } + ) + }) +}) diff --git a/src/main/runtime/workspaces/archive/runtime-workspace-archive.ts b/src/main/runtime/workspaces/archive/runtime-workspace-archive.ts new file mode 100644 index 00000000000..e25ea85f89d --- /dev/null +++ b/src/main/runtime/workspaces/archive/runtime-workspace-archive.ts @@ -0,0 +1,181 @@ +import { getRepoExecutionHostId, parseExecutionHostId } from '../../../../shared/execution-host' +import { isFolderRepo } from '../../../../shared/repo-kind' +import type { SetupDecision } from '../../../../shared/worktree/create-types' +import { splitWorktreeId, worktreeIdentityKey } from '../../../../shared/worktree/id' +import type { Worktree } from '../../../../shared/worktree/types' +import { invalidateAuthorizedRootsCacheForRepo } from '../../../ipc/worktrees/removal/registered-worktree-roots-scoped-invalidation' +import { readWorktreeMetaForHost } from '../../../persistence/host-qualified-worktree-meta' +import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import { assertWslMoveRepoWritable } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' +import { resolveWorktreeRemovalRoute } from '../../../workspaces/removal/worktree-removal-execution-host-route' +import { resolveWorktreeRemovalRepoOwner } from '../../../workspaces/removal/worktree-removal-repo-owner' +import { findPendingWorktreeRemovalConflict } from '../../../workspaces/removal/worktree-removal-table' +import { withProjectWorktreeCreate } from '../../../workspaces/creation/worktree-create-in-flight' +import { getExplicitWorktreeIdSelector } from '../catalog/runtime-worktree-selection' +import { prepareRuntimeLocalWorktreeSetup } from '../creation/runtime-local-worktree-setup' +import { createdWorktreeLifecycleIdentity } from '../lifecycle/worktree-lifecycle-event' +import { RuntimeNestedWorktreeRemoval } from '../removal/runtime-nested-worktree-removal' +import { + markWorktreeCheckoutArchived, + recreateArchivedCheckout, + resolveArchivableCheckout, + unmarkArchiveIfCheckoutRemains +} from './workspace-archive-checkout' + +export type ArchiveManagedWorktreeResult = { + worktreeId: string + path: string + branch: string + warning?: string +} + +export type RestoreArchivedWorktreeResult = { + worktree: Worktree + warning?: string +} + +export abstract class RuntimeWorkspaceArchive extends RuntimeNestedWorktreeRemoval { + // The lifecycle queue is off in some builds; archive and restore of one workspace must never overlap. + private readonly archiveOperations = new Set() + + private async exclusiveArchiveOperation( + worktreeId: string, + run: () => Promise + ): Promise { + const key = worktreeIdentityKey(worktreeId) + if (this.archiveOperations.has(key)) { + throw new Error('This workspace is already being archived or restored.') + } + this.archiveOperations.add(key) + try { + return await run() + } finally { + this.archiveOperations.delete(key) + } + } + + /** Delete the checkout through the normal removal refusals, keeping the branch and every workspace record. */ + async archiveManagedWorktree( + worktreeSelector: string, + options: { hostId?: string } = {} + ): Promise { + const store = this.requireStore() + const requiredHostId = parseExecutionHostId(options.hostId)?.id + const target = await this.resolveWorktreeRemovalTarget(worktreeSelector, requiredHostId) + return this.exclusiveArchiveOperation(target.id, async () => { + const { hostId } = await resolveArchivableCheckout(store, target, requiredHostId) + let warning: string | undefined + try { + ;({ warning } = await this.removeManagedWorktree(`id:${target.id}`, { + archive: { + markArchived: (worktree) => + markWorktreeCheckoutArchived(store, target.id, hostId, worktree) + }, + runHooks: true, + deleteBranch: false, + waitForBackgroundRemoval: true, + ...(options.hostId ? { hostId: options.hostId } : {}) + })) + } catch (error) { + await unmarkArchiveIfCheckoutRemains(store, target, hostId) + throw error + } + const archived = readWorktreeMetaForHost(store, target.id, hostId)?.archivedCheckout + if (!archived) { + // A plain delete that started first took the workspace; nothing was kept. + throw new Error('This workspace was deleted instead of archived.') + } + return { + worktreeId: target.id, + path: target.path, + branch: archived.branch, + ...(warning ? { warning } : {}) + } + }) + } + + /** Recreate an archived workspace's checkout at its old path from its kept branch. */ + async restoreArchivedWorktree( + worktreeSelector: string, + options: { hostId?: string; setupDecision?: SetupDecision } = {} + ): Promise { + const worktreeId = getExplicitWorktreeIdSelector(worktreeSelector) ?? worktreeSelector + const parsed = splitWorktreeId(worktreeId) + if (!parsed) { + throw new Error('selector_not_found') + } + return this.exclusiveArchiveOperation(worktreeId, () => + this.restoreArchivedCheckout(worktreeId, parsed.repoId, parsed.worktreePath, options) + ) + } + + private async restoreArchivedCheckout( + worktreeId: string, + repoId: string, + path: string, + options: { hostId?: string; setupDecision?: SetupDecision } + ): Promise { + const store = this.requireStore() + const owner = resolveWorktreeRemovalRepoOwner( + store, + repoId, + parseExecutionHostId(options.hostId)?.id + ) + if (owner.kind !== 'resolved' || isFolderRepo(owner.repo)) { + throw new Error('This workspace is not archived in a tracked Git project.') + } + const repo = owner.repo + const hostId = getRepoExecutionHostId(repo) + const archived = readWorktreeMetaForHost(store, worktreeId, hostId)?.archivedCheckout + if (!archived) { + throw new Error('This workspace is not archived.') + } + // The owning host restores; a client never recreates another host's checkout. + resolveWorktreeRemovalRoute(hostId) + assertWslMoveRepoWritable(store, repo) + // A removal still deleting this checkout would purge the row once the mark is cleared. + if (findPendingWorktreeRemovalConflict(repo.path, { worktreePath: path })) { + throw new Error('This workspace is still being archived or deleted.') + } + // The create fence keeps the project from being removed while its checkout comes back. + const warning = await withProjectWorktreeCreate(repo, async () => { + const { includeCopyWarning } = await recreateArchivedCheckout( + store, + repo, + worktreeId, + path, + archived.branch + ) + // Fresh activity so an inactive-workspace rule doesn't archive it again right away. + store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId }), { + isArchived: false, + archivedCheckout: undefined, + lastActivityAt: Date.now() + }) + // Archive ran the teardown hook, so setup runs on every restore; no terminal here, so in-process. + const setup = await prepareRuntimeLocalWorktreeSetup({ + request: options.setupDecision ? { setupDecision: options.setupDecision } : {}, + repo, + worktreePath: path, + settings: store.getSettings(), + runtimeTarget: this.getLocalGitExecutionOptionArgs(repo)[0], + shouldUseSetupRunner: false, + warning: includeCopyWarning + }) + return setup.warning + }) + this.invalidateResolvedWorktreeCache() + this.invalidateWorktreeScanCacheForRepo(repo.id) + invalidateAuthorizedRootsCacheForRepo(store, repo) + this.notifyWorktreesChanged(repo.id) + const worktree = await this.showManagedWorktree(`id:${worktreeId}`, hostId) + this.emitWorktreeLifecycle({ + kind: 'created', + worktreeId, + path: worktree.path, + branch: worktree.branch, + ...createdWorktreeLifecycleIdentity(worktree) + }) + return { worktree, ...(warning ? { warning } : {}) } + } +} diff --git a/src/main/runtime/workspaces/archive/workspace-archive-checkout.ts b/src/main/runtime/workspaces/archive/workspace-archive-checkout.ts new file mode 100644 index 00000000000..2a2af0d54ed --- /dev/null +++ b/src/main/runtime/workspaces/archive/workspace-archive-checkout.ts @@ -0,0 +1,175 @@ +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { isFolderRepo } from '../../../../shared/repo-kind' +import type { Repo } from '../../../../shared/repo-types' +import type { GitWorktreeInfo } from '../../../../shared/worktree/types' +import { listWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' +import { areWorktreePathsEqual } from '../../../git/worktrees/catalog/worktree-path-comparison' +import { addWorktree } from '../../../git/worktrees/creation/worktree-add' +import { addSparseWorktree } from '../../../git/worktrees/creation/worktree-sparse-add' +import { localBranchExists } from '../../../git/worktrees/removal/worktree-removal' +import { pruneGitWorktrees } from '../../../git/worktrees/removal/worktree-prune-guard' +import { + gitExecOptions, + normalizeLocalBranchRef +} from '../../../git/worktrees/worktree-operation-options' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' +import { runWorktreeChangeInvalidators } from '../../../ipc/worktrees/listing/worktree-change-invalidators' +import { readWorktreeMetaForHost } from '../../../persistence/host-qualified-worktree-meta' +import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' +import { resolveWorktreeRemovalRepoOwner } from '../../../workspaces/removal/worktree-removal-repo-owner' +import { resolveWorktreeRemovalRoute } from '../../../workspaces/removal/worktree-removal-execution-host-route' +import { findPendingWorktreeRemovalConflict } from '../../../workspaces/removal/worktree-removal-table' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { runtimePathExists } from '../catalog/runtime-worktree-filesystem' +import type { + RemoveManagedWorktreeOptions, + RuntimeWorktreeRemovalTarget +} from '../catalog/runtime-worktree-selection' +import { materializeWorktreeContentPaths } from '../creation/runtime-local-worktree-materialization' + +/** Archive only a live, linked Git checkout on a branch; anything else has nothing to restore. */ +export async function resolveArchivableCheckout( + store: RuntimeStore, + target: RuntimeWorktreeRemovalTarget, + requiredHostId: ExecutionHostId | undefined +): Promise<{ hostId: ExecutionHostId }> { + const owner = resolveWorktreeRemovalRepoOwner(store, target.repoId, requiredHostId) + if (owner.kind !== 'resolved' || isFolderRepo(owner.repo)) { + throw new Error('Only a Git worktree in a tracked project can be archived.') + } + const repo = owner.repo + // The owning host archives; a client never deletes another host's checkout. + resolveWorktreeRemovalRoute(getRepoExecutionHostId(repo)) + if (findPendingWorktreeRemovalConflict(repo.path, { worktreePath: target.path })) { + throw new Error('This workspace is already being deleted.') + } + const registered = ( + await listWorktreesStrict(repo.path, getLocalProjectWorktreeGitOptions(store, repo)) + ).find((worktree) => areWorktreePathsEqual(worktree.path, target.path)) + if (!registered || registered.isMainWorktree || !(await runtimePathExists(target.path))) { + throw new Error('Only a linked Git worktree that is still on disk can be archived.') + } + if (!normalizeLocalBranchRef(registered.branch)) { + throw new Error('Only a workspace on a branch can be archived.') + } + return { hostId: getRepoExecutionHostId(repo) } +} + +// Written and flushed before Git deletes anything, so a crash mid-delete still finds the row archived. +export async function markWorktreeCheckoutArchived( + store: RuntimeStore, + worktreeId: string, + hostId: ExecutionHostId, + worktree: GitWorktreeInfo +): Promise { + const branch = normalizeLocalBranchRef(worktree.branch) + if (!branch) { + throw new Error('Only a workspace on a branch can be archived.') + } + const wasArchived = readWorktreeMetaForHost(store, worktreeId, hostId)?.isArchived === true + store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId }), { + isArchived: true, + archivedCheckout: { branch, archivedAt: Date.now(), ...(wasArchived ? { wasArchived } : {}) } + }) + await (store.flushPendingOrThrowAsync + ? store.flushPendingOrThrowAsync({ drainToStableGeneration: false }) + : store.flushOrThrow?.()) +} + +/** Archive marks the row before Git deletes; a plain delete drops a leftover mark so its row is purged. */ +export function archiveMarkStep( + options: Pick, + store: RuntimeStore, + worktreeId: string, + hostId: ExecutionHostId +): (worktree: GitWorktreeInfo) => Promise { + return ( + options.archive?.markArchived ?? + (async () => { + if (readWorktreeMetaForHost(store, worktreeId, hostId)?.archivedCheckout) { + store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId }), { + archivedCheckout: undefined + }) + } + }) + ) +} + +// A refusal or failure while Git still lists the checkout leaves an ordinary, visible workspace. +export async function unmarkArchiveIfCheckoutRemains( + store: RuntimeStore, + target: RuntimeWorktreeRemovalTarget, + hostId: ExecutionHostId +): Promise { + const owner = resolveWorktreeRemovalRepoOwner(store, target.repoId, hostId) + const mark = readWorktreeMetaForHost(store, target.id, hostId)?.archivedCheckout + if (owner.kind !== 'resolved' || !mark) { + return + } + const registered = await listWorktreesStrict( + owner.repo.path, + getLocalProjectWorktreeGitOptions(store, owner.repo) + ).catch(() => null) + if (registered?.some((worktree) => areWorktreePathsEqual(worktree.path, target.path))) { + store.setWorktreeMeta(hostWorktreeTarget({ id: target.id, hostId }), { + isArchived: mark.wasArchived === true, + archivedCheckout: undefined + }) + } +} + +/** Recreate the checkout, or finish one a crash left registered on its branch; content paths are idempotent. */ +export async function recreateArchivedCheckout( + store: RuntimeStore, + repo: Repo, + worktreeId: string, + path: string, + branch: string +): Promise<{ includeCopyWarning?: string }> { + const gitOptions = getLocalProjectWorktreeGitOptions(store, repo) + let registered = await listWorktreesStrict(repo.path, gitOptions) + let atPath = registered.find((worktree) => areWorktreePathsEqual(worktree.path, path)) + if (atPath && (atPath.prunable || !(await runtimePathExists(path)))) { + // A registration whose folder is gone would block `worktree add`; Git drops it on prune. + await pruneGitWorktrees({ cwd: repo.path, ...gitOptions }) + registered = await listWorktreesStrict(repo.path, gitOptions) + atPath = registered.find((worktree) => areWorktreePathsEqual(worktree.path, path)) + } + if (atPath) { + if (normalizeLocalBranchRef(atPath.branch) !== branch) { + throw new Error(`Another checkout is already at ${path}.`) + } + // Archive only took clean checkouts; anything else is a restore cut short before Git checked out. + const { stdout } = await gitExecFileAsync( + ['status', '--porcelain'], + gitExecOptions(path, gitOptions) + ) + if (stdout.trim()) { + throw new Error( + `The checkout at ${path} is incomplete or changed. Move it away and restore again.` + ) + } + return materializeWorktreeContentPaths(repo, path, gitOptions, untimed) + } + const holder = registered.find((worktree) => normalizeLocalBranchRef(worktree.branch) === branch) + if (holder) { + throw new Error(`Branch "${branch}" is checked out at ${holder.path}. Free it to restore.`) + } + if (!(await localBranchExists(repo.path, branch, gitOptions))) { + throw new Error(`Branch "${branch}" no longer exists, so this workspace cannot be restored.`) + } + const sparse = readWorktreeMetaForHost( + store, + worktreeId, + getRepoExecutionHostId(repo) + )?.sparseDirectories + const addOptions = { ...gitOptions, checkoutExistingBranch: true } + await (sparse?.length + ? addSparseWorktree(repo.path, path, branch, sparse, undefined, false, addOptions) + : addWorktree(repo.path, path, branch, undefined, false, false, addOptions)) + runWorktreeChangeInvalidators(repo.id) + return materializeWorktreeContentPaths(repo, path, gitOptions, untimed) +} + +const untimed = { time: (_phase: string, operation: () => Promise) => operation() } diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-resolution-scan.ts b/src/main/runtime/workspaces/catalog/repo-worktree-resolution-scan.ts index 05a118f2ebf..d95c14c18fb 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-resolution-scan.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-resolution-scan.ts @@ -1,20 +1,24 @@ import type { GitWorktreeInfo } from '../../../../shared/worktree/types' -import { listWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' +import { listWorktreesSharedStrictAllowingTrueEmpty } from '../../../git/worktrees/catalog/worktree-scan-cache' import type { LocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' export type RuntimeWorktreeScanResult = | { ok: true; worktrees: GitWorktreeInfo[] } - | { ok: false; worktrees: GitWorktreeInfo[] } + | { ok: false; worktrees: GitWorktreeInfo[]; trueEmpty?: boolean } +/** Runtime readers never treat an empty catalog as success; `trueEmpty` tells the shared owner it was confirmed. */ export async function scanLocalRepoWorktreesForResolution( repoPath: string, options: LocalProjectWorktreeGitOptions ): Promise { try { + // Equivalent requests from other registrations of this path join one Git process. const worktrees = options.wslDistro - ? await listWorktreesStrict(repoPath, options) - : await listWorktreesStrict(repoPath) - return { ok: true, worktrees } + ? await listWorktreesSharedStrictAllowingTrueEmpty(repoPath, options) + : await listWorktreesSharedStrictAllowingTrueEmpty(repoPath) + return worktrees.length > 0 + ? { ok: true, worktrees } + : { ok: false, worktrees: [], trueEmpty: true } } catch { return { ok: false, worktrees: [] } } diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts index 7418e2203ed..180c0b3773f 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts @@ -1,3 +1,8 @@ +import { + joinResolvedWorktreeScans, + type ResolvedWorktreeRepoScans +} from './resolved-worktree-scan-join' +import { getRepoHostIdentityForParts } from '../../../../shared/repo-host-identity' import { describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../shared/repo-types' @@ -9,12 +14,18 @@ import type { Store } from '../../../persistence/loading-store/store' import { mergeWorktreeMetaForWrite } from '../../../persistence/loading-store/worktree-metadata/worktree-meta-write-normalization' import { buildDetectedGitWorktrees } from '../../../ipc/worktrees/listing/ssh-worktree-fallback' import { + projectRepoWorktreeRows, resolveRepoWorktreeRows, resolveScopedWorktreeIdRow, scanRepoWorktreeRows, type RepoWorktreeRowDeps } from './repo-worktree-row-resolution' import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import { + pendingWorktreeRemovals, + recordedWorktreeRemovals, + finishedWorktreeRemovals +} from '../../../workspaces/removal/worktree-removal-table' import { bumpLocalWorktreeScanGeneration } from '../../../workspaces/catalog/local-worktree-scan-generation' function repo( @@ -234,3 +245,107 @@ describe('folder-to-Git checkout identity', () => { } ) }) + +describe('durable removal projection onto cached host rows', () => { + it('retires admitted rows without another scan and fences old rows after cleanup, only on their host', async () => { + const local = repo('shared', '/local/repo', { executionHostId: 'local' }) + const remote = repo('shared', '/remote/repo', { executionHostId: 'ssh:builder' }) + const deps = createDeps([local, remote]) + const scan = await scanRepoWorktreeRows(deps, local, new Map()) + const id = 'shared::/same/worktree' + const record = { + worktreeId: id, + repoId: local.id, + repoPath: local.path, + worktreePath: '/same/worktree', + branch: 'feature', + head: 'abc123', + deleteBranch: false, + force: false, + requestedAt: 1 + } + pendingWorktreeRemovals.set(id, record) + try { + expect(projectRepoWorktreeRows(deps, local, scan, {})).toMatchObject([{ id }]) + expect(projectRepoWorktreeRows(deps, local, scan, {})[0].removalRecorded).toBeUndefined() + recordedWorktreeRemovals.add(record) + expect(projectRepoWorktreeRows(deps, local, scan, {})).toMatchObject([ + { id, removing: true, removalRecorded: true } + ]) + expect(projectRepoWorktreeRows(deps, remote, scan, {})[0].removalRecorded).toBeUndefined() + pendingWorktreeRemovals.delete(id) + finishedWorktreeRemovals.add(record) + expect(projectRepoWorktreeRows(deps, local, scan, {})).toEqual([]) + expect(projectRepoWorktreeRows(deps, remote, scan, {})).toMatchObject([{ id }]) + } finally { + pendingWorktreeRemovals.delete(id) + } + }) +}) + +it.each([ + [12, 750], + [120, 7500] +])( + 'keeps removal witnesses repo-scoped without recopying on metadata joins (%i repos, %i removals)', + (repoCount, removalCount) => { + const repos = Array.from({ length: repoCount }, (_, i) => + repo(`fleet-${i}`, `/fleet/${i}`, { executionHostId: 'local' }) + ) + const deps = createDeps(repos) + const scans: ResolvedWorktreeRepoScans = new Map( + repos.map((owner) => [ + getRepoHostIdentityForParts(owner.id, 'local'), + { ok: true, worktrees: [], gitRun: null } + ]) + ) + const records = Array.from({ length: removalCount }, (_, i) => ({ + worktreeId: `fleet-0::/retiring/${i}`, + repoId: 'fleet-0', + repoPath: '/fleet/0', + worktreePath: `/retiring/${i}`, + branch: `feature-${i}`, + head: 'abc123', + force: false, + deleteBranch: false, + requestedAt: 1 + })) + for (const record of records) { + pendingWorktreeRemovals.set(record.worktreeId, record) + recordedWorktreeRemovals.add(record) + } + const firstScan = scans.get(getRepoHostIdentityForParts('fleet-0', 'local'))! + firstScan.worktrees = [gitWorktree('/retiring/0')] + try { + const joined = joinResolvedWorktreeScans(deps.store, () => deps, scans) + expect(joined.worktrees).toMatchObject([{ id: records[0].worktreeId, removalRecorded: true }]) + expect([...scans.values()].map((scan) => scan.removals?.size ?? 0)).toEqual([ + removalCount, + ...Array(repoCount - 1).fill(0) + ]) + const witnesses = firstScan.removals! + const enumerateWitnesses = vi.spyOn(witnesses, Symbol.iterator) + const enumerateGlobal = vi.spyOn(pendingWorktreeRemovals, Symbol.iterator) + try { + deps.metaById[records[0].worktreeId] = mergeWorktreeMetaForWrite(undefined, { + displayName: 'changed metadata' + }) + joinResolvedWorktreeScans(deps.store, () => deps, scans) + // Unrelated metadata cannot invalidate removal membership: no witness entries need copying. + expect(enumerateWitnesses).not.toHaveBeenCalled() + expect(enumerateGlobal).not.toHaveBeenCalled() + expect(firstScan.removals).toBe(witnesses) + } finally { + enumerateWitnesses.mockRestore() + enumerateGlobal.mockRestore() + } + pendingWorktreeRemovals.delete(records[0].worktreeId) + finishedWorktreeRemovals.add(records[0]) + expect(joinResolvedWorktreeScans(deps.store, () => deps, scans).worktrees).toEqual([]) + } finally { + for (const record of records) { + pendingWorktreeRemovals.delete(record.worktreeId) + } + } + } +) diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts index 637892c7758..22dacfc9ba4 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts @@ -5,7 +5,8 @@ import { splitWorktreeIdForFilesystem, worktreeIdentityKey } from '../../../../shared/worktree/id' -import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' import { readAllWorktreeMetaForHost, readWorktreeMetaForHost @@ -32,6 +33,11 @@ import { getLocalWorktreeScanGeneration } from '../../../workspaces/catalog/loca import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' import { resolveLocalProjectRuntimesForRepos } from '../../../workspaces/execution-host/local-project-runtime-resolution' import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan' +import { + projectCachedWorktreeRemovals, + type WorktreeRemovalWitnessScan +} from '../../../workspaces/removal/worktree-removal-listing' +import { pendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-table' type RepoWorktreeRowStore = Pick< RuntimeStore, @@ -68,6 +74,8 @@ export type RepoWorktreeRowDeps = { projectRuntimeByRepoId: ReadonlyMap ) => Promise getCachedSuccessfulScan?: (repo: Repo) => RuntimeWorktreeScanResult | undefined + /** Once per new observation, with its scan-start generation; absent keeps per-read pruning. */ + claimLineagePrune?: (scan: RuntimeWorktreeScanResult) => { scanGeneration: number } | null /** Folder workspaces are stamped from runtime-owned identity helpers, so the caller supplies them. */ listFolderWorkspaces: (repo: Repo, repoOwnerCount: number) => Worktree[] } @@ -84,7 +92,8 @@ export function listStoredWorktreeRowsForRepo( readAllWorktreeMetaForHost(store, expectedHostId) )) { const parsed = splitWorktreeId(worktreeId) - if (!parsed || parsed.repoId !== repo.id) { + // An archived row has no checkout, so it must not come back as a live worktree. + if (!parsed || parsed.repoId !== repo.id || meta.archivedCheckout) { continue } // Same repo ids can belong to several hosts; degraded scans must not publish another owner's metadata. @@ -108,16 +117,23 @@ export function listStoredWorktreeRowsForRepo( } /** One git repo's checkouts as its scan saw them; carries no metadata, which is joined at read. */ -export type RepoWorktreeRowsScan = { ok: boolean; worktrees: GitWorktreeInfo[] } +export type RepoWorktreeRowsScan = { + ok: boolean + worktrees: GitWorktreeInfo[] +} & WorktreeRemovalWitnessScan /** The scan half of `resolveRepoWorktreeRows`: slow, and the only part that awaits. */ export async function scanRepoWorktreeRows( - deps: Pick, + deps: Omit, repo: Repo, projectRuntimeByRepoId: ReadonlyMap, repoOwnerCount = deps.store.getRepos().filter((candidate) => candidate.id === repo.id).length ): Promise { const { store } = deps + const removals = + getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID + ? pendingWorktreeRemovals.snapshotForRepo(repo.id) + : undefined const scanGeneration = getLocalWorktreeScanGeneration(repo.id) // Absorb rejection before withTimeout: rejection preserves shipped empty results, but timeout restores last-known rows. const scan: RuntimeWorktreeScanResult = (await withTimeout( @@ -133,10 +149,13 @@ export async function scanRepoWorktreeRows( listStoredWorktreeRowsForRepo(store, repo, repoOwnerCount) } const gitWorktrees = preserveFolderUpgradeWorktreePath(repo, scan.worktrees) - if (scan.ok) { - pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees, { scanGeneration }) + // Cached reads must not re-prune against a generation captured after their rows were observed. + const lineage = + scan.ok && (deps.claimLineagePrune ? deps.claimLineagePrune(scan) : { scanGeneration }) + if (lineage) { + pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees, lineage) } - return { ok: scan.ok, worktrees: gitWorktrees } + return { ok: scan.ok, worktrees: gitWorktrees, removals, projectedRemovals: removals } } /** The join half: a repo's rows from a scan and the metadata as it is now. Synchronous. */ @@ -167,7 +186,7 @@ export function projectRepoWorktreeRows( })) } const expectedHostId = getRepoExecutionHostId(repo) - return (scan?.worktrees ?? []).map((gitWorktree) => { + const rows = (scan?.worktrees ?? []).map((gitWorktree) => { const worktreeId = `${repo.id}::${gitWorktree.path}` const meta = readWorktreeMetaForHost(store, worktreeId, expectedHostId) ?? @@ -187,11 +206,13 @@ export function projectRepoWorktreeRows( branch: gitWorktree.branch, isBare: gitWorktree.isBare, isMainWorktree: gitWorktree.isMainWorktree - }, - displayName: merged.displayName, - comment: merged.comment + } } }) + if (expectedHostId !== LOCAL_EXECUTION_HOST_ID || !scan) { + return rows + } + return projectCachedWorktreeRemovals(repo.id, scan, rows, (row) => row.id) } /** Resolution owns durable identity stamping; memory projection never calls this wrapper. */ diff --git a/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts b/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts index a9b2f8aed0c..d2a63b435dd 100644 --- a/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts +++ b/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts @@ -60,7 +60,7 @@ export function platformsByRepoId( export async function scanResolvedWorktreeRepos( store: RuntimeStore | null, rowDeps: () => RepoWorktreeRowDeps, - scanCacheEntry: (scanScopeKey: string) => object | undefined + scanCacheEntry: (repo: Repo) => object | undefined ): Promise { const scans: ResolvedWorktreeRepoScans = new Map() if (!store) { @@ -79,8 +79,8 @@ export async function scanResolvedWorktreeRepos( projectRuntimeByRepoId, repoOwners.rowsFor(repo.id).length ) - // The key listRepoWorktreesForResolution caches under. - const gitRun = scanCacheEntry(`${repo.id}\0${getRepoExecutionHostId(repo)}`) ?? null + // The owner observation the scan answered from; verification never mints a new one. + const gitRun = scanCacheEntry(repo) ?? null scans.set(resolvedWorktreeRepoScanKey(repo), { ...scan, gitRun }) }) ) diff --git a/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts b/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts index 0435d44b176..f53db1f397f 100644 --- a/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts +++ b/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts @@ -1,6 +1,6 @@ import type { Repo } from '../../../../shared/repo-types' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' -import type { WorkspaceMetadataCursor } from '../../../../shared/worktree/workspace-metadata-set' +import type { WorkspaceMetadataCursor } from '../../../../shared/worktree/metadata/workspace-metadata-set' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' import { readWorktreeMetaForHost } from '../../../persistence/host-qualified-worktree-meta' diff --git a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.test.ts b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.test.ts index 464deed5b46..9fb41be5d5c 100644 --- a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.test.ts +++ b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.test.ts @@ -35,6 +35,12 @@ vi.mock( ) import { RuntimeManagedWorktreeQueries } from './runtime-managed-worktree-queries' +import { runtimeResultForObservation } from './runtime-worktree-catalog-read' +import { + _resetWorktreeCatalogOwnerForTests, + readWorktreeCatalog +} from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { setWorktreeCatalogRouteResolver } from '../../../workspaces/catalog/repo-worktree-catalog-route' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { bumpLocalWorktreeScanGeneration, @@ -324,4 +330,56 @@ describe('RuntimeManagedWorktreeQueries.listDetected overtaken scan', () => { expect(pruneLineageMock).not.toHaveBeenCalled() expect(pruneMetadataMock).not.toHaveBeenCalled() }) + + it('never publishes owner rows as authoritative once the owner retired their route', async () => { + let live = true + setWorktreeCatalogRouteResolver(() => + live ? { repoPath: repo.path, runtimeKey: 'local:default' } : null + ) + try { + const { observation } = await readWorktreeCatalog( + repo, + 'local:default', + { kind: 'runtime', maxAgeMs: 30_000 }, + { + scan: async () => ({ kind: 'rows', worktrees: rows([repo.path]) }), + // The observation carries the pre-scan hygiene claim a pruning listing consumes. + captureWitness: () => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked prune reads only the expectation's presence. + ({ + authorizedRootsRevision: 0, + rootsRevision: 0, + hygieneDue: true, + expectation: { repo, metadata: [] }, + release: () => {} + }) as never + } + ) + const ownerRows = runtimeResultForObservation(observation!) + const scanRepo = vi.fn(async () => ownerRows) + // The route changes while the listing awaits its own metadata prune, after admission. + let helperSawCurrent: boolean | undefined + pruneMetadataMock.mockImplementationOnce(async (args: { isCallerCurrent: () => boolean }) => { + live = false + helperSawCurrent = args.isCallerCurrent() + return { scanGenerationCurrent: true, preservedMetadataCandidateIds: new Set() } + }) + const store = gitStore({ + pruneSessionlessMissingLocalWorktreeMetadataForRepo: vi.fn(() => []), + getProfileStorageDirectory: () => '/profile', + captureNativeLocalWorktreeMetadataScanExpectation: vi.fn(() => ({ repo, metadata: [] })) + }) + + const result = await queries(store, { scanRepo }).listDetected(repo) + + expect(pruneMetadataMock).toHaveBeenCalledTimes(1) + expect(helperSawCurrent).toBe(false) + expect(result).toMatchObject({ authoritative: false, source: 'git' }) + expect(result.worktrees.map((worktree) => worktree.path)).toEqual([repo.path]) + expect(pruneLineageMock).not.toHaveBeenCalled() + } finally { + setWorktreeCatalogRouteResolver(null) + _resetWorktreeCatalogOwnerForTests() + } + }) }) diff --git a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts index ed08471a010..14b01ccf071 100644 --- a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts +++ b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts @@ -25,14 +25,14 @@ import { applyMetadataFallbackVisibility, buildKnownOrcaWorkspaceLayouts, toDetectedWorktree -} from '../../../../shared/worktree/ownership' +} from '../../../../shared/worktree/visibility/ownership' import { isLegacyRepoForExternalWorktreeVisibility } from '../../../../shared/external-worktree-visibility' import { projectWorktreeLineageWithHostPeers } from '../../../workspaces/catalog/worktree-lineage-host-peers' import { createWorktreeVisibilitySourceMatcher, resolveCustomWorktreeVisibilitySources, type WorktreeVisibilitySourceMatcher -} from '../../../../shared/worktree/visibility-sources' +} from '../../../../shared/worktree/visibility/visibility-sources' import { mergeWorktree } from '../../../ipc/worktree-metadata-merge' import { pruneLineageForMissingRepoWorktrees } from '../../../workspaces/catalog/worktree-lineage-pruning' import { @@ -43,7 +43,7 @@ import type { RuntimeStore } from '../../construction/runtime-store-contract' import { getWorkspaceAttachments } from '../../../../shared/workspace-attachments/workspace-attachments' import { scanRuntimeWorktreesUntilNotOvertaken } from './runtime-witnessed-worktree-scan' import { listRuntimeFolderWorkspaces } from './runtime-worktree-filesystem' -import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/configured-worktree-base-path' +import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/paths/configured-worktree-base-path' import { getRetiredNameRegistryForRepo, hasRetiredNameRegistryStore @@ -158,11 +158,9 @@ export class RuntimeManagedWorktreeQueries { worktrees: projectWorktreeLineageWithHostPeers(store, repo, detected) } } - const scan = await scanRuntimeWorktreesUntilNotOvertaken(store, repo, (target) => - this.deps.scanRepo(target) - ) + const scan = await scanRuntimeWorktreesUntilNotOvertaken(store, repo, this.deps.scanRepo) // Publish overtaken scans as non-authoritative: throwing would drop client rows. Prune nothing; the overtaking mutation's event requests a fresh listing. - if (scan.ok && !scan.superseded) { + if (scan.ok && !scan.superseded && scan.authorityCurrent()) { // Headless hosts lack ipcMain listings; runtime must sweep its own metadata too (#17776). if (scan.metadataPruneExpectation && canPruneAuthoritativeLocalMetadata(store)) { await pruneMetadataMissingFromAuthoritativeLocalScan({ @@ -170,12 +168,13 @@ export class RuntimeManagedWorktreeQueries { repo, gitWorktrees: scan.worktrees, scan: scan.metadataPruneExpectation, - scanGeneration: scan.scanGeneration + scanGeneration: scan.scanGeneration, + isCallerCurrent: scan.authorityCurrent }) } - pruneLineageForMissingRepoWorktrees(store, repo, scan.worktrees, { - scanGeneration: scan.scanGeneration - }) + if (scan.lineagePrune && scan.authorityCurrent()) { + pruneLineageForMissingRepoWorktrees(store, repo, scan.worktrees, scan.lineagePrune) + } } const matcher = createWorktreeVisibilitySourceMatcher( [repo.path, ...scan.worktrees.map((worktree) => worktree.path)], @@ -204,7 +203,7 @@ export class RuntimeManagedWorktreeQueries { }) return { repoId: repo.id, - authoritative: scan.ok && !scan.superseded, + authoritative: scan.ok && !scan.superseded && scan.authorityCurrent(), source: scan.ok ? 'git' : 'metadata-fallback', workspaceMetadata: listed.workspaceMetadata, // Stamp the scan's starting generation: that is the catalog its rows describe. diff --git a/src/main/runtime/workspaces/catalog/runtime-witnessed-worktree-scan.ts b/src/main/runtime/workspaces/catalog/runtime-witnessed-worktree-scan.ts index 13937823bba..f1a50b87f83 100644 --- a/src/main/runtime/workspaces/catalog/runtime-witnessed-worktree-scan.ts +++ b/src/main/runtime/workspaces/catalog/runtime-witnessed-worktree-scan.ts @@ -9,12 +9,22 @@ import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution import type { Store } from '../../../persistence/loading-store/store' import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan' +import { + claimRuntimeLineagePrune, + observationForRuntimeResult +} from './runtime-worktree-catalog-read' +import { isCurrentWorktreeCatalogObservation } from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { claimWorktreeCatalogHygiene } from '../../../ipc/worktrees/listing/worktree-catalog-observation-hygiene' export type WitnessedRuntimeWorktreeScan = RuntimeWorktreeScanResult & { /** A concurrent worktree change made these scan rows stale. */ superseded: boolean scanGeneration: number metadataPruneExpectation: NativeLocalWorktreeMetadataScanExpectation | undefined + /** Lineage prunes once per observation; null when another read of these rows already did. */ + lineagePrune: { scanGeneration: number } | null + /** Owner authority for these rows, rechecked after awaits before destructive work. */ + authorityCurrent: () => boolean } /** Refuse destructive pruning on unresolved routes or WSL, whose Linux paths v1 cannot equate with stored UNC aliases. */ @@ -42,20 +52,42 @@ async function scanRuntimeWorktreesWithMutationWitness( scanRepo: (repo: Repo) => Promise ): Promise { // Capture before listing can mutate metadata synchronously; pruning revalidates the original rows. - const scanGeneration = getLocalWorktreeScanGeneration(repo.id) - const metadataPruneExpectation = captureLocalMetadataPruneExpectation(store, repo) + let scanGeneration = getLocalWorktreeScanGeneration(repo.id) + let metadataPruneExpectation: NativeLocalWorktreeMetadataScanExpectation | undefined + let lineagePrune: { scanGeneration: number } | null = null + let authorityCurrent = (): boolean => true let scan: RuntimeWorktreeScanResult try { scan = await scanRepo(repo) } catch { scan = { ok: false, worktrees: [] } } + const observation = observationForRuntimeResult(scan) + if (observation) { + // Shared observations carry their own pre-scan witness; older rows never get today's expectations. + scanGeneration = observation.generation + authorityCurrent = () => isCurrentWorktreeCatalogObservation(observation) + const claim = + isLocalWorktreeScanGenerationCurrent(repo.id, scanGeneration) && authorityCurrent() + ? claimWorktreeCatalogHygiene(observation) + : null + metadataPruneExpectation = claim?.expectation + lineagePrune = claimRuntimeLineagePrune(scan) + } else { + // Only injected scanners land here: production `ok` rows always carry an owner observation. + metadataPruneExpectation = captureLocalMetadataPruneExpectation(store, repo) + lineagePrune = { scanGeneration } + } return { ...scan, // Failed scans are already non-authoritative. - superseded: scan.ok && !isLocalWorktreeScanGenerationCurrent(repo.id, scanGeneration), + superseded: + scan.ok && + (!isLocalWorktreeScanGenerationCurrent(repo.id, scanGeneration) || !authorityCurrent()), scanGeneration, - metadataPruneExpectation + metadataPruneExpectation, + lineagePrune, + authorityCurrent } } diff --git a/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts b/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts index c32fb362212..0a5849ce694 100644 --- a/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts +++ b/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts @@ -1,11 +1,8 @@ -import { - getRepoExecutionHostId, - getRepoRoutingConnectionId -} from '../../../../shared/execution-host' +import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' import type { Repo } from '../../../../shared/repo-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { composeWorktreeId } from '../../../../shared/worktree/id' -import type { PullRequestChange } from '../../../github/pull-request-changed-events' +import type { PullRequestChange } from '../../../github/pull-requests/refresh/pull-request-changed-events' import { OrcaRuntimeWithGetStatus } from '../../hosts/runtime-status' export abstract class RuntimeWorkspaceCatalogEvents extends OrcaRuntimeWithGetStatus { @@ -13,6 +10,10 @@ export abstract class RuntimeWorkspaceCatalogEvents extends OrcaRuntimeWithGetSt abstract invalidateWorktreeScanCacheForRepo(repoId: string): void + protected abstract peekRepoWorktreeListing( + repo: Repo + ): { worktrees: { path: string }[] } | undefined + // Renderer meta writes skip its notifier after optimistic updates; remote clients still need invalidation. notifyWorktreesChangedForRemoteClients(repoId: string): void { this.invalidateResolvedWorktreeCache() @@ -56,9 +57,8 @@ export abstract class RuntimeWorkspaceCatalogEvents extends OrcaRuntimeWithGetSt // Ids spelled as clients listed them; an unlisted path may be another spelling of any checkout, so name none. private listedWorktreeIds(repo: Repo, paths: readonly string[]): string[] | null { - const scan = this.worktreeScanCache.get(`${repo.id}\0${getRepoExecutionHostId(repo)}`) const listed = new Map( - (scan?.listing ?? scan?.result)?.worktrees.map((worktree) => [ + this.peekRepoWorktreeListing(repo)?.worktrees.map((worktree) => [ normalizeRuntimePathForComparison(worktree.path), worktree.path ]) diff --git a/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts b/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts index 10a338ffee2..90226e7b05e 100644 --- a/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts +++ b/src/main/runtime/workspaces/catalog/runtime-workspace-change-events.ts @@ -1,9 +1,10 @@ import type { RuntimeWorktreeLifecycleEvent } from '../lifecycle/worktree-lifecycle-event' import type { AutomationsChangedPayload } from '../../../../shared/runtime-client-events' +import type { WorkspaceCleanupRunFinishedEvent } from '../../../../shared/workspace-cleanup/workspace-cleanup-run' import { wakeFolderRepoGitUpgradeWatch } from '../../../ipc/folder-repo-git-upgrade-wake' import { runWorktreeChangeInvalidators } from '../../../ipc/worktrees/listing/worktree-change-invalidators' -import type { WorktreeSortOrderUpdate } from '../../../../shared/worktree/sort-order-update' -import type { WorkspaceMetadataSet } from '../../../../shared/worktree/workspace-metadata-set' +import type { WorktreeSortOrderUpdate } from '../../../../shared/worktree/metadata/sort-order-update' +import type { WorkspaceMetadataSet } from '../../../../shared/worktree/metadata/workspace-metadata-set' import { NativeChatLaunchDraftOwner } from '../../agent-session/launch/native-chat-launch-draft-owner' export abstract class RuntimeWorkspaceChangeEvents extends NativeChatLaunchDraftOwner { @@ -65,4 +66,9 @@ export abstract class RuntimeWorkspaceChangeEvents extends NativeChatLaunchDraft this.notifier?.automationsChanged?.(payload) this.emitClientEvent({ type: 'automationsChanged', ...payload }) } + + /** The cleanup runner finished a run on this host; clients may toast. */ + notifyWorkspaceCleanupRunFinished(run: WorkspaceCleanupRunFinishedEvent['run']): void { + this.emitClientEvent({ type: 'workspaceCleanupRunFinished', run }) + } } diff --git a/src/main/runtime/workspaces/catalog/runtime-worktree-catalog-read.ts b/src/main/runtime/workspaces/catalog/runtime-worktree-catalog-read.ts new file mode 100644 index 00000000000..3942889786b --- /dev/null +++ b/src/main/runtime/workspaces/catalog/runtime-worktree-catalog-read.ts @@ -0,0 +1,66 @@ +import type { WorktreeCatalogObservation } from '../../../workspaces/catalog/repo-worktree-catalog-observation' +import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan' +import { dropRepeatedWorktreeRows } from './repeated-worktree-rows' +import { isCurrentWorktreeCatalogObservation } from '../../../workspaces/catalog/repo-worktree-catalog-owner' + +const resultByObservation = new WeakMap() +const observationByResult = new WeakMap() +const listingByResult = new WeakMap() +const lineagePrunedObservations = new WeakSet() + +/** One stable runtime result per owner observation, so listing projections and git-run identity follow it. */ +export function runtimeResultForObservation( + observation: WorktreeCatalogObservation +): RuntimeWorktreeScanResult { + const known = resultByObservation.get(observation) + if (known) { + return known + } + // Runtime never reports a confirmed-empty scan as success; strict failures and true-empty both read `ok:false`. + const result = + observation.outcome.kind === 'rows' + ? dropRepeatedWorktreeRows({ ok: true, worktrees: observation.outcome.worktrees }) + : { ok: false, worktrees: [] } + resultByObservation.set(observation, result) + observationByResult.set(result, observation) + return result +} + +export function rememberRuntimeWorktreeListing( + result: RuntimeWorktreeScanResult, + listing: RuntimeWorktreeScanResult +): void { + const observation = observationByResult.get(result) + if (observation) { + listingByResult.set(result, listing) + observationByResult.set(listing, observation) + } +} + +export function runtimeWorktreeListingFor( + result: RuntimeWorktreeScanResult +): RuntimeWorktreeScanResult | undefined { + return listingByResult.get(result) +} + +export function observationForRuntimeResult( + result: RuntimeWorktreeScanResult +): WorktreeCatalogObservation | undefined { + return observationByResult.get(result) +} + +/** Lineage pruning runs once per new observation, with the generation its scan started under. */ +export function claimRuntimeLineagePrune( + result: RuntimeWorktreeScanResult +): { scanGeneration: number } | null { + const observation = observationByResult.get(result) + if ( + !observation || + lineagePrunedObservations.has(observation) || + !isCurrentWorktreeCatalogObservation(observation) + ) { + return null + } + lineagePrunedObservations.add(observation) + return { scanGeneration: observation.generation } +} diff --git a/src/main/runtime/workspaces/catalog/runtime-worktree-scan-state.ts b/src/main/runtime/workspaces/catalog/runtime-worktree-scan-state.ts deleted file mode 100644 index 10b74e296de..00000000000 --- a/src/main/runtime/workspaces/catalog/runtime-worktree-scan-state.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan' - -export type RuntimeWorktreeScanCache = { - generation: number - runtimeKey: string - result: RuntimeWorktreeScanResult - listing?: RuntimeWorktreeScanResult - expiresAt: number - adminFingerprint: string | null - scannedAt: number -} - -export type RuntimeWorktreeScanInFlight = { - generation: number - runtimeKey: string - promise: Promise -} - -export type RuntimeWorktreeScanRefresh = { - result: RuntimeWorktreeScanResult - adminFingerprint: string | null - adminFingerprintProbe: Promise | null - scannedAt: number -} diff --git a/src/main/runtime/workspaces/catalog/runtime-worktree-selection.ts b/src/main/runtime/workspaces/catalog/runtime-worktree-selection.ts index 74e402ab988..d3b61b3f946 100644 --- a/src/main/runtime/workspaces/catalog/runtime-worktree-selection.ts +++ b/src/main/runtime/workspaces/catalog/runtime-worktree-selection.ts @@ -5,7 +5,7 @@ import { type ExecutionHostId } from '../../../../shared/execution-host' import { splitWorktreeId } from '../../../../shared/worktree/id' -import type { GitPushTarget } from '../../../../shared/worktree/types' +import type { GitPushTarget, GitWorktreeInfo } from '../../../../shared/worktree/types' export type RuntimeWorktreeRemovalTarget = { id: string @@ -26,12 +26,19 @@ export type RemoveManagedWorktreeOptions = { hostId?: string /** Reply with the finished delete's result; otherwise a background delete replies on acceptance. */ waitForBackgroundRemoval?: boolean + /** Archive marks the row after every refusal, before Git deletes the checkout; purge then keeps it. */ + archive?: { markArchived: (worktree: GitWorktreeInfo) => Promise } } export function getRuntimeWorktreeRemovalOptionsKey( options: Pick< RemoveManagedWorktreeOptions, - 'force' | 'runHooks' | 'allowUnverifiedPtyStop' | 'allowFailedArchiveHook' | 'deleteBranch' + | 'force' + | 'runHooks' + | 'allowUnverifiedPtyStop' + | 'allowFailedArchiveHook' + | 'deleteBranch' + | 'archive' > ): string { // Forced retries must not coalesce onto an attempt refusing unverified PTY stop. @@ -45,7 +52,9 @@ export function getRuntimeWorktreeRemovalOptionsKey( : options.deleteBranch ? 'delete-branch' : 'keep-branch' - return `${options.force ? 'force' : 'normal'}:${hooksKey}:${ptyKey}:${archiveKey}:${branchKey}` + const removalKey = `${options.force ? 'force' : 'normal'}:${hooksKey}:${ptyKey}:${archiveKey}:${branchKey}` + // An archive keeps the metadata a plain delete purges; they must never share one reply. + return options.archive ? `archive:${removalKey}` : removalKey } // Null host is host-unaware; unstamped legacy rows are adoptable, but either explicit host spelling must match exactly. diff --git a/src/main/runtime/workspaces/catalog/runtime-worktree-visibility.ts b/src/main/runtime/workspaces/catalog/runtime-worktree-visibility.ts index 4853811a3ce..adc9488437b 100644 --- a/src/main/runtime/workspaces/catalog/runtime-worktree-visibility.ts +++ b/src/main/runtime/workspaces/catalog/runtime-worktree-visibility.ts @@ -5,10 +5,10 @@ import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { createWorktreeVisibilitySourceMatcher, resolveCustomWorktreeVisibilitySources -} from '../../../../shared/worktree/visibility-sources' +} from '../../../../shared/worktree/visibility/visibility-sources' import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' import { resolveWorktreeHostRouting } from './worktree-launch-host-repo' -import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/configured-worktree-base-path' +import { resolveConfiguredWorktreeBasePaths } from '../../../../shared/worktree/paths/configured-worktree-base-path' export function buildRuntimeWorktreeVisibilityMatchers( repos: readonly Repo[], diff --git a/src/main/runtime/workspaces/catalog/stale-worktree-registration-preflight.ts b/src/main/runtime/workspaces/catalog/stale-worktree-registration-preflight.ts index c9e5d7cc1e8..a2a9f4e5c38 100644 --- a/src/main/runtime/workspaces/catalog/stale-worktree-registration-preflight.ts +++ b/src/main/runtime/workspaces/catalog/stale-worktree-registration-preflight.ts @@ -1,7 +1,7 @@ import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { LocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal/removal' import { formatWorktreeRemovalError } from '../../../ipc/worktree-logic' import { usesNativeWindowsRemoval } from '../../../git/worktrees/removal/windows-worktree-removal' import { isPrunableGitFileWorktree } from '../../../workspaces/removal/worktree-prunable-git-file' diff --git a/src/main/runtime/workspaces/catalog/workspace-catalog.ts b/src/main/runtime/workspaces/catalog/workspace-catalog.ts index b48f767182e..3e81bcfb1a6 100644 --- a/src/main/runtime/workspaces/catalog/workspace-catalog.ts +++ b/src/main/runtime/workspaces/catalog/workspace-catalog.ts @@ -33,14 +33,26 @@ import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../sha import { withUnregisteredRemovalCheckouts } from '../../../workspaces/removal/worktree-removal-listing' import { withoutInFlightWorktreeCreates } from '../../../workspaces/creation/worktree-create-in-flight' import { preserveFolderUpgradeWorktreePath } from '../../../workspaces/catalog/folder-upgrade-worktree-path' -import type { RuntimeWorktreeScanCache } from './runtime-worktree-scan-state' +import type { GitWorktreeInfo } from '../../../../shared/worktree/types' +import { + peekWorktreeCatalog, + retireObsoleteWorktreeCatalogs +} from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { + claimRuntimeLineagePrune, + rememberRuntimeWorktreeListing, + runtimeResultForObservation, + runtimeWorktreeListingFor +} from './runtime-worktree-catalog-read' import * as ScanCache from './runtime-worktree-scan-cache' const RESOLVED_WORKTREE_CACHE_TTL_MS = 1000 export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFile { - protected abstract refreshRepoWorktreeScan( - ...args: Parameters - ): ReturnType + protected abstract readRepoWorktreeCatalog( + ...args: Parameters + ): ReturnType + + protected abstract listStoredWorktreesForResolution(repo: Repo): GitWorktreeInfo[] protected listKnownResolvedWorktreesForExplicitTarget( targetWorktreeId: string, @@ -130,26 +142,31 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi } protected scanResolvedWorktreeRepos(): Promise { - return scanResolvedWorktreeRepos(this.store, this.repoWorktreeRowDeps.bind(this), (key) => - this.worktreeScanCache.get(key) + return scanResolvedWorktreeRepos( + this.store, + this.repoWorktreeRowDeps.bind(this), + (repo) => this.peekRepoWorktreeObservation(repo)?.observation ) } protected pruneUnregisteredWorktreeScans(): void { - const registered = new Set( - (this.store?.getRepos() ?? []).map((repo) => `${repo.id}\0${getRepoExecutionHostId(repo)}`) - ) - for (const cache of [ - this.worktreeScanCache, - this.worktreeScanGenerations, - this.worktreeScanInFlight - ]) { - for (const key of cache.keys()) { - if (!registered.has(key)) { - cache.delete(key) - } - } + retireObsoleteWorktreeCatalogs() + } + + private peekRepoWorktreeObservation(repo: Repo) { + return this.store + ? peekWorktreeCatalog(repo, ScanCache.resolveWorktreeScanRuntime(this.store, repo).runtimeKey) + : null + } + + /** The listing a client last saw for this repo, current or not, for path spelling. */ + protected peekRepoWorktreeListing(repo: Repo): RuntimeWorktreeScanResult | undefined { + const known = this.peekRepoWorktreeObservation(repo) + if (!known) { + return undefined } + const result = runtimeResultForObservation(known.observation) + return runtimeWorktreeListingFor(result) ?? result } /** The fleet listing from cached scans and the store as it is now, synchronously. */ @@ -172,17 +189,13 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi scanRepo: (repo, projectRuntimeByRepoId) => this.listRepoWorktreesForListing(repo, projectRuntimeByRepoId), getCachedSuccessfulScan: (repo) => { - const key = `${repo.id}\0${getRepoExecutionHostId(repo)}` - const cached = this.worktreeScanCache.get(key) - if ( - cached?.generation === (this.worktreeScanGenerations.get(key) ?? 0) && - cached.runtimeKey === ScanCache.resolveWorktreeScanRuntime(store, repo).runtimeKey && - cached.listing?.ok - ) { - return cached.listing - } - return undefined + const known = this.peekRepoWorktreeObservation(repo) + const listing = known?.current + ? runtimeWorktreeListingFor(runtimeResultForObservation(known.observation)) + : undefined + return listing?.ok ? listing : undefined }, + claimLineagePrune: claimRuntimeLineagePrune, listFolderWorkspaces: (repo, repoOwnerCount) => listRuntimeFolderWorkspaces(store, repo, repoOwnerCount) } @@ -201,9 +214,10 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi /** The resolution scan plus the checkouts this host's removals own that Git no longer lists. */ protected async listRepoWorktreesForListing( repo: Repo, - projectRuntimeByRepoId?: ReadonlyMap + projectRuntimeByRepoId?: ReadonlyMap, + options: { claimsHygiene?: boolean } = {} ): Promise { - const cached = await this.listRepoWorktreesForResolution(repo, projectRuntimeByRepoId) + const cached = await this.listRepoWorktreesForResolution(repo, projectRuntimeByRepoId, options) // Paired detectedList must retain folder-upgrade locators or folder ids lose metadata and terminals (#30150). const scan = { ...cached, worktrees: preserveFolderUpgradeWorktreePath(repo, cached.worktrees) } const listing = @@ -216,81 +230,30 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi ) } : scan - const cachedEntry = this.worktreeScanCache.get(`${repo.id}\0${getRepoExecutionHostId(repo)}`) - if (cachedEntry?.result === cached) { - cachedEntry.listing = listing - } + rememberRuntimeWorktreeListing(cached, listing) return listing } protected async listRepoWorktreesForResolution( repo: Repo, - projectRuntimeByRepoId?: ReadonlyMap + projectRuntimeByRepoId?: ReadonlyMap, + options: { claimsHygiene?: boolean } = {} ): Promise { const { projectRuntime, runtimeKey, sshConnectionId } = ScanCache.resolveWorktreeScanRuntime( this.requireStore(), repo, projectRuntimeByRepoId ) - const now = Date.now() - const scanScopeKey = `${repo.id}\0${getRepoExecutionHostId(repo)}` - const retryCurrent = (): Promise => { - const current = this.store - ?.getRepos() - .find( - (candidate) => - candidate.id === repo.id && - getRepoExecutionHostId(candidate) === getRepoExecutionHostId(repo) - ) - return current - ? this.listRepoWorktreesForResolution(current) - : Promise.resolve({ ok: false, worktrees: [] }) + // Why: this process serves no SSH git, so an SSH repo answers from its stored rows. + if (sshConnectionId) { + return { ok: false, worktrees: this.listStoredWorktreesForResolution(repo) } } - const generation = this.worktreeScanGenerations.get(scanScopeKey) ?? 0 - const cached = this.worktreeScanCache.get(scanScopeKey) - if ( - cached?.generation === generation && - cached.runtimeKey === runtimeKey && - cached.expiresAt > now - ) { - return cached.result - } - const inFlight = this.worktreeScanInFlight.get(scanScopeKey) - if (inFlight?.generation === generation && inFlight.runtimeKey === runtimeKey) { - return (await inFlight.promise).result - } - const reusableCached = - cached?.generation === generation && cached.runtimeKey === runtimeKey ? cached : null - const promise = this.refreshRepoWorktreeScan(repo, projectRuntime, reusableCached) - .then(async (refresh) => { - if (this.worktreeScanInFlight.get(scanScopeKey)?.promise !== promise) { - return { ...refresh, result: await retryCurrent() } - } - if (refresh.result.ok || !sshConnectionId) { - const entry: RuntimeWorktreeScanCache = { - generation, - runtimeKey, - result: refresh.result, - expiresAt: Date.now() + ScanCache.resolveWorktreeScanCacheTtlMs(repo), - adminFingerprint: refresh.adminFingerprint, - scannedAt: refresh.scannedAt - } - this.worktreeScanCache.set(scanScopeKey, entry) - void refresh.adminFingerprintProbe?.then((fingerprint) => { - if (this.worktreeScanCache.get(scanScopeKey) === entry) { - entry.adminFingerprint = fingerprint - } - }) - } - return refresh - }) - .finally(() => { - if (this.worktreeScanInFlight.get(scanScopeKey)?.promise === promise) { - this.worktreeScanInFlight.delete(scanScopeKey) - } - }) - this.worktreeScanInFlight.set(scanScopeKey, { generation, runtimeKey, promise }) - return (await promise).result + return await this.readRepoWorktreeCatalog( + repo, + projectRuntime, + runtimeKey, + options.claimsHygiene === true + ) } listRepos(): Repo[] { diff --git a/src/main/runtime/workspaces/catalog/workspace-repo-scan-refresh.ts b/src/main/runtime/workspaces/catalog/workspace-repo-scan-refresh.ts index aed21d93a36..7928566c51e 100644 --- a/src/main/runtime/workspaces/catalog/workspace-repo-scan-refresh.ts +++ b/src/main/runtime/workspaces/catalog/workspace-repo-scan-refresh.ts @@ -1,29 +1,38 @@ import { RuntimeWorkspaceCatalog } from './workspace-catalog' import type { Repo } from '../../../../shared/repo-types' import type { ProjectExecutionRuntimeResolution } from '../../../../shared/execution-host/project-execution-runtime' -import type { - RuntimeWorktreeScanCache, - RuntimeWorktreeScanRefresh -} from './runtime-worktree-scan-state' -import { resolveWorktreeScanCacheTtlMs } from './runtime-worktree-scan-cache' +import { + resolveWorktreeScanCacheTtlMs, + resolveWorktreeScanRuntime +} from './runtime-worktree-scan-cache' import { WORKTREE_SCAN_ADMIN_FINGERPRINT_TIMEOUT_MS, WORKTREE_SCAN_ADMIN_RECONCILE_INTERVAL_MS } from './worktree-scan-admin-budget' import { getLocalProjectWorktreeGitOptionsForRuntime } from '../../../workspaces/execution-host/project-runtime-git-options' -import { withTimeoutResult } from '../../../../shared/promise-timeout-fallback' import { readRepoWorktreeAdminFingerprint } from './repo-worktree-admin-fingerprint' import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan' import { scanLocalRepoWorktreesForResolution } from './repo-worktree-resolution-scan' -import { dropRepeatedWorktreeRows } from './repeated-worktree-rows' import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import { listStoredWorktreeRowsForRepo } from './repo-worktree-row-resolution' import type { ResolvedWorktree } from './runtime-worktree-path-identity' -import { getRepoExecutionHostId, getRepoSshConnectionId } from '../../../../shared/execution-host' +import { getRepoSshConnectionId } from '../../../../shared/execution-host' import { blockedWslDistroForPath, wslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import { + invalidateWorktreeCatalogForRepo, + peekWorktreeCatalog, + readWorktreeCatalog +} from '../../../workspaces/catalog/repo-worktree-catalog-owner' +import { runtimeResultForObservation } from './runtime-worktree-catalog-read' +import { + needsWorktreeCatalogHygieneClaim, + worktreeCatalogHygienePlan +} from '../../../ipc/worktrees/listing/worktree-catalog-observation-hygiene' +import type { Store } from '../../../persistence/loading-store/store' +import { SUPERSEDED_SCAN_RESCANS } from '../../../ipc/worktrees/listing/overtaken-scan-rerun' const lastFingerprintUnknownWarnAt = new Map() @@ -45,103 +54,86 @@ function warnFingerprintUnknownOnce(repoId: string, reason: string): void { } export abstract class RuntimeWorkspaceRepoScanRefresh extends RuntimeWorkspaceCatalog { - /** Reuse cached scans when a Git-admin fingerprint proves no change. */ - protected async refreshRepoWorktreeScan( + /** Runtime readers accept the owner's observation for the scan TTL, then its admin-fingerprint verifier. */ + protected async readRepoWorktreeCatalog( repo: Repo, projectRuntime: ProjectExecutionRuntimeResolution | undefined, - cached: RuntimeWorktreeScanCache | null - ): Promise { - const scannedAt = Date.now() + runtimeKey: string, + claimsHygiene: boolean + ): Promise { + const gitOptions = getLocalProjectWorktreeGitOptionsForRuntime(repo, projectRuntime) // E9: the admin reads below and the Git scan both boot a stopped distro; keep known rows until it runs. - const wslDistro = getRepoSshConnectionId(repo) - ? undefined - : getLocalProjectWorktreeGitOptionsForRuntime(repo, projectRuntime).wslDistro if ( - !getRepoSshConnectionId(repo) && - wslDistroForPath(repo.path, wslDistro) && - (await blockedWslDistroForPath(repo.path, wslDistro)) + wslDistroForPath(repo.path, gitOptions.wslDistro) && + (await blockedWslDistroForPath(repo.path, gitOptions.wslDistro)) ) { - return cached - ? { - result: cached.result, - adminFingerprint: cached.adminFingerprint, - adminFingerprintProbe: null, - scannedAt: cached.scannedAt - } - : { - result: { ok: false, worktrees: this.listStoredWorktreesForResolution(repo) }, - adminFingerprint: null, - adminFingerprintProbe: null, - scannedAt - } + // Known rows only while nothing has invalidated them; otherwise last stored rows, as non-authoritative. + const known = peekWorktreeCatalog(repo, runtimeKey) + return known?.current + ? runtimeResultForObservation(known.observation) + : { ok: false, worktrees: this.listStoredWorktreesForResolution(repo) } } - // Fingerprint only on-host Git: executionHostId-only SSH and WSL paths cannot be described by local admin reads. - const fingerprintCapable = - !getRepoSshConnectionId(repo) && - // Skip fingerprints when scan TTL already reaches reconciliation; they could never be reused. - resolveWorktreeScanCacheTtlMs(repo) < WORKTREE_SCAN_ADMIN_RECONCILE_INTERVAL_MS && - !getLocalProjectWorktreeGitOptionsForRuntime(repo, projectRuntime).wslDistro - // Probe before scanning so concurrent changes cannot be stamped as already observed. - const probe = fingerprintCapable ? this.startRepoWorktreeAdminFingerprintProbe(repo) : null - const reusable = - cached?.result.ok === true && - scannedAt - cached.scannedAt < WORKTREE_SCAN_ADMIN_RECONCILE_INTERVAL_MS - ? cached - : null - // Unknown probes reuse the cache without resetting scannedAt; rescanning on slow-mount timeouts amplifies load (#19312). - const reuseCached = (): RuntimeWorktreeScanRefresh | null => - reusable - ? { - result: reusable.result, - adminFingerprint: reusable.adminFingerprint, - adminFingerprintProbe: null, - scannedAt: reusable.scannedAt - } - : null - if (probe === 'in-flight') { - const reused = reuseCached() - if (reused) { - warnFingerprintUnknownOnce(repo.id, 'previous probe still pending') - return reused - } - } else if (probe && reusable) { - // Await only for a reusable cache; scan-bound callers cannot use the probe. - const probed = await withTimeoutResult(probe, WORKTREE_SCAN_ADMIN_FINGERPRINT_TIMEOUT_MS) - if (!probed.ok) { - warnFingerprintUnknownOnce(repo.id, 'probe expired') - return ( - reuseCached() ?? - (await this.scanRepoWorktreesForRefresh(repo, projectRuntime, null, scannedAt)) - ) - } - // Only a known matching fingerprint proves no change. - if (probed.value !== null && probed.value === reusable.adminFingerprint) { - return { - result: reusable.result, - adminFingerprint: probed.value, - adminFingerprintProbe: null, - scannedAt: reusable.scannedAt - } - } + // Admission and the owner route must agree: a route replaced while the distro check ran is not read. + const live = this.store + ? resolveWorktreeScanRuntime(this.requireStore(), repo) + : { runtimeKey, projectRuntime } + if ( + live.runtimeKey !== runtimeKey || + getLocalProjectWorktreeGitOptionsForRuntime(repo, live.projectRuntime).wslDistro !== + gitOptions.wslDistro + ) { + return { ok: false, worktrees: this.listStoredWorktreesForResolution(repo) } } - return await this.scanRepoWorktreesForRefresh( + const ttlMs = resolveWorktreeScanCacheTtlMs(repo) + // WSL execution cannot be described by local admin reads; a TTL at the ceiling could never reuse a probe. + const verifier = + ttlMs < WORKTREE_SCAN_ADMIN_RECONCILE_INTERVAL_MS && !gitOptions.wslDistro + ? { + ceilingMs: WORKTREE_SCAN_ADMIN_RECONCILE_INTERVAL_MS, + timeoutMs: WORKTREE_SCAN_ADMIN_FINGERPRINT_TIMEOUT_MS, + probe: () => this.startRepoWorktreeAdminFingerprintProbe(repo), + onUnknown: (reason: string) => warnFingerprintUnknownOnce(repo.id, reason) + } + : undefined + const store = this.store + const { observation, superseded } = await readWorktreeCatalog( repo, - projectRuntime, - probe === 'in-flight' ? null : probe, - scannedAt + runtimeKey, + { + kind: 'runtime', + maxAgeMs: ttlMs, + reusesFailure: true, + // Readers that joined an overtaken scan follow current truth, within the detected listing's bound. + overtakenFlights: SUPERSEDED_SCAN_RESCANS + 1, + ...(verifier ? { verifier } : {}), + ...(claimsHygiene ? { needsHygieneClaim: needsWorktreeCatalogHygieneClaim(repo) } : {}) + }, + { + scan: async () => { + const scan = await withRepositoryGitCause( + repo.path, + gitOptions, + { family: 'catalog', reason: 'runtime-catalog', cache: 'refresh' }, + () => scanLocalRepoWorktreesForResolution(repo.path, gitOptions) + ) + if (scan.ok) { + return { kind: 'rows', worktrees: scan.worktrees } + } + return scan.trueEmpty + ? { kind: 'true-empty' } + : { kind: 'failed', error: new Error(`worktree list failed for ${repo.path}`) } + }, + ...(store + ? worktreeCatalogHygienePlan(store as unknown as Store, repo, gitOptions, claimsHygiene) + : {}) + } ) - } - - private async scanRepoWorktreesForRefresh( - repo: Repo, - projectRuntime: ProjectExecutionRuntimeResolution | undefined, - probe: Promise | null, - scannedAt: number - ): Promise { - const result = dropRepeatedWorktreeRows( - await this.listRepoWorktreesForResolutionUncached(repo, projectRuntime) - ) - return { result, adminFingerprint: null, adminFingerprintProbe: probe, scannedAt } + if (!observation) { + return { ok: false, worktrees: this.listStoredWorktreesForResolution(repo) } + } + const result = runtimeResultForObservation(observation) + // Mutations kept overtaking scans: publish the rows as non-authoritative, never as current truth. + return superseded && result.ok ? { ok: false, worktrees: result.worktrees } : result } /** Allow one outstanding filesystem probe per repo: timeouts do not cancel readdir/stat, so repeated probes could exhaust libuv on wedged mounts. */ @@ -159,25 +151,6 @@ export abstract class RuntimeWorkspaceRepoScanRefresh extends RuntimeWorkspaceCa }) } - protected async listRepoWorktreesForResolutionUncached( - repo: Repo, - projectRuntime: ProjectExecutionRuntimeResolution | undefined - ): Promise { - // Resolve executionHostId-only SSH rows too; client scans of remote paths would lose all worktrees. - const sshConnectionId = getRepoSshConnectionId(repo) - if (!sshConnectionId) { - return await scanLocalRepoWorktreesForResolution( - repo.path, - getLocalProjectWorktreeGitOptionsForRuntime(repo, projectRuntime) - ) - } - // Why: this process serves no SSH git, so an SSH repo answers from its stored rows. - return { - ok: false, - worktrees: this.listStoredWorktreesForResolution(repo) - } - } - protected listStoredWorktreesForResolution(repo: Repo): GitWorktreeInfo[] { return this.store ? listStoredWorktreeRowsForRepo(this.requireStore(), repo) : [] } @@ -191,36 +164,8 @@ export abstract class RuntimeWorkspaceRepoScanRefresh extends RuntimeWorkspaceCa } invalidateWorktreeScanCacheForRepo(repoId: string): void { - const prefix = `${repoId}\0` - const scopeKeys = new Set( - this.store - ?.getRepos() - .filter((repo) => repo.id === repoId) - .map((repo) => `${repoId}\0${getRepoExecutionHostId(repo)}`) ?? [] - ) - for (const keys of [ - this.worktreeScanGenerations.keys(), - this.worktreeScanCache.keys(), - this.worktreeScanInFlight.keys() - ]) { - for (const key of keys) { - if (key.startsWith(prefix)) { - scopeKeys.add(key) - } - } - } - const registered = new Set( - (this.store?.getRepos() ?? []).map((repo) => `${repo.id}\0${getRepoExecutionHostId(repo)}`) - ) - for (const key of scopeKeys) { - if (registered.has(key)) { - this.worktreeScanGenerations.set(key, (this.worktreeScanGenerations.get(key) ?? 0) + 1) - } else { - this.worktreeScanGenerations.delete(key) - this.worktreeScanCache.delete(key) - } - this.worktreeScanInFlight.delete(key) - } + invalidateWorktreeCatalogForRepo(repoId) + this.pruneUnregisteredWorktreeScans() } invalidateWorktreeCatalog(repoId: string): void { @@ -229,16 +174,9 @@ export abstract class RuntimeWorkspaceRepoScanRefresh extends RuntimeWorkspaceCa } protected invalidateSshWorktreeScanCacheInternal(targetId: string): void { + // SSH repos answer from stored rows and own no Git observation here; only projections go stale. const repos = this.store?.getRepos() ?? [] - const affectedRepos = repos.filter((repo) => getRepoSshConnectionId(repo) === targetId) - const affectedScopeKeys = new Set( - affectedRepos.map((repo) => `${repo.id}\0${getRepoExecutionHostId(repo)}`) - ) - for (const key of affectedScopeKeys) { - this.worktreeScanGenerations.set(key, (this.worktreeScanGenerations.get(key) ?? 0) + 1) - this.worktreeScanInFlight.delete(key) - } - if (affectedScopeKeys.size > 0) { + if (repos.some((repo) => getRepoSshConnectionId(repo) === targetId)) { this.resolvedWorktrees.invalidateResolved() } } @@ -265,3 +203,4 @@ export abstract class RuntimeWorkspaceRepoScanRefresh extends RuntimeWorkspaceCa this.notifyReposChanged() } } +import { withRepositoryGitCause } from '../../../git/repository-git-cause' diff --git a/src/main/runtime/workspaces/catalog/worktree-catalog-live-route.test.ts b/src/main/runtime/workspaces/catalog/worktree-catalog-live-route.test.ts new file mode 100644 index 00000000000..59cdb6a54ff --- /dev/null +++ b/src/main/runtime/workspaces/catalog/worktree-catalog-live-route.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + isLiveWorktreeCatalogRoute, + setWorktreeCatalogRouteResolver +} from '../../../workspaces/catalog/repo-worktree-catalog-route' +import { markWorktreeRouteInputsChanged } from '../../../workspaces/catalog/local-worktree-scan-generation' +import { registerWorktreeCatalogRoutes } from './worktree-catalog-live-route' + +function storeWith(repoCount: number) { + const repos: { id: string; path: string; kind: 'git' | 'folder' }[] = Array.from( + { length: repoCount }, + (_unused, index) => ({ id: `repo-${index}`, path: `/repos/app-${index}`, kind: 'git' }) + ) + const projects = repos.map((repo, index) => ({ + id: `project-${index}`, + sourceRepoIds: [repo.id] + })) + return { + repos, + getRepos: vi.fn(() => repos.map((repo) => ({ ...repo }))), + getProjects: vi.fn(() => [...projects]), + getSettings: () => ({}) + } +} + +// Pinned to a non-Windows host, where each project resolves to its own host runtime. +const routeOf = (index: number) => ({ + repoPath: `/repos/app-${index}`, + runtimeKey: `project-${index}:local-host:darwin` +}) +const realPlatform = process.platform + +describe('worktree catalog live route', () => { + beforeEach(() => { + Object.defineProperty(process, 'platform', { value: 'darwin' }) + }) + afterEach(() => { + Object.defineProperty(process, 'platform', { value: realPlatform }) + setWorktreeCatalogRouteResolver(null) + }) + + it('reads the registry and projects once per route change however many owners check', async () => { + for (const repoCount of [12, 120]) { + const store = storeWith(repoCount) + registerWorktreeCatalogRoutes(store as never) + for (let pass = 0; pass < 3; pass += 1) { + for (let index = 0; index < repoCount; index += 1) { + expect(isLiveWorktreeCatalogRoute(`repo-${index}`, 'local', routeOf(index))).toBe(true) + } + await Promise.resolve() + } + expect(store.getRepos).toHaveBeenCalledTimes(1) + expect(store.getProjects.mock.calls.length).toBeLessThanOrEqual(2) + + markWorktreeRouteInputsChanged() + expect(isLiveWorktreeCatalogRoute('repo-0', 'local', routeOf(0))).toBe(true) + expect(store.getRepos).toHaveBeenCalledTimes(2) + } + }) + + it('rejects a captured route as soon as the registration changes, before any later read', () => { + const store = storeWith(2) + registerWorktreeCatalogRoutes(store as never) + expect(isLiveWorktreeCatalogRoute('repo-0', 'local', routeOf(0))).toBe(true) + + store.repos[0].kind = 'folder' + store.repos[1].path = '/repos/renamed' + markWorktreeRouteInputsChanged() + + expect(isLiveWorktreeCatalogRoute('repo-0', 'local', routeOf(0))).toBe(false) + expect(isLiveWorktreeCatalogRoute('repo-1', 'local', routeOf(1))).toBe(false) + expect(isLiveWorktreeCatalogRoute('repo-9', 'local', routeOf(9))).toBe(false) + }) +}) diff --git a/src/main/runtime/workspaces/catalog/worktree-catalog-live-route.ts b/src/main/runtime/workspaces/catalog/worktree-catalog-live-route.ts new file mode 100644 index 00000000000..fbe635cd935 --- /dev/null +++ b/src/main/runtime/workspaces/catalog/worktree-catalog-live-route.ts @@ -0,0 +1,62 @@ +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import { isFolderRepo } from '../../../../shared/repo-kind' +import { + setWorktreeCatalogRouteResolver, + type WorktreeCatalogRoute +} from '../../../workspaces/catalog/repo-worktree-catalog-route' +import { getWorktreeRouteInputsRevision } from '../../../workspaces/catalog/local-worktree-scan-generation' +import { getWslDiscoveryRevision } from '../../../wsl/discovery/wsl-discovery-change' +import { resolveLocalProjectRuntimesForRepos } from '../../../workspaces/execution-host/local-project-runtime-resolution' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { resolveWorktreeScanRuntime } from './runtime-worktree-scan-cache' + +type RouteSnapshot = { + inputsRevision: number + wslRevision: number + routes: Map +} + +/** Every eligible repo's live route from one registry read and one project pass. */ +function buildRoutes(store: RuntimeStore): Map { + const repos = store.getRepos() + const projectRuntimeByRepoId = resolveLocalProjectRuntimesForRepos(store as never, repos) + const routes = new Map() + for (const repo of repos) { + // Only this host's repos run local Git; remote-owned registrations answer from their own host. + if (isFolderRepo(repo) || getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID) { + continue + } + const { projectRuntime, runtimeKey, sshConnectionId } = resolveWorktreeScanRuntime( + store as never, + repo, + projectRuntimeByRepoId + ) + // SSH rows answer from stored metadata and repair states cannot run local Git. + if (sshConnectionId || projectRuntime?.status === 'repair-required') { + continue + } + routes.set(`${repo.id}\0${getRepoExecutionHostId(repo)}`, { repoPath: repo.path, runtimeKey }) + } + return routes +} + +/** The catalog owner asks the live registration, not the caller, which route runs a repo's Git. */ +export function registerWorktreeCatalogRoutes(store: RuntimeStore | null | undefined): void { + if (!store) { + return + } + // Rebuilt only after a route input changes; writers advance these revisions synchronously. + let snapshot: RouteSnapshot | null = null + setWorktreeCatalogRouteResolver((repoId, hostId) => { + const inputsRevision = getWorktreeRouteInputsRevision() + const wslRevision = getWslDiscoveryRevision() + if ( + !snapshot || + snapshot.inputsRevision !== inputsRevision || + snapshot.wslRevision !== wslRevision + ) { + snapshot = { inputsRevision, wslRevision, routes: buildRoutes(store) } + } + return snapshot.routes.get(`${repoId}\0${hostId}`) ?? null + }) +} diff --git a/src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts b/src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts index 953588f35bf..218dfaf6d1e 100644 --- a/src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts +++ b/src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts @@ -31,6 +31,7 @@ vi.mock('./repo-worktree-admin-fingerprint', () => ({ })) import { OrcaRuntimeService } from '../../orca-runtime' +import { _resetWorktreeCatalogOwnerForTests } from '../../../workspaces/catalog/repo-worktree-catalog-owner' import { WORKTREE_SCAN_ADMIN_FINGERPRINT_TIMEOUT_MS } from './worktree-scan-admin-budget' import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' @@ -166,6 +167,8 @@ function stallProbeOnce(): (fingerprint: string | null) => void { describe('worktree scan admin-fingerprint gate', () => { beforeEach(() => { + // The catalog owner is process-wide, like production's single runtime; each case starts unobserved. + _resetWorktreeCatalogOwnerForTests() listWorktreesStrictMock.mockReset() listWorktreesStrictMock.mockResolvedValue([ { path: REPO_PATH, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }, @@ -247,6 +250,8 @@ describe('worktree scan admin-fingerprint gate', () => { describe('scoped explicit worktree-id resolution', () => { beforeEach(() => { + // The catalog owner is process-wide, like production's single runtime; each case starts unobserved. + _resetWorktreeCatalogOwnerForTests() listWorktreesStrictMock.mockReset() listWorktreesStrictMock.mockImplementation(async (repoPath: string) => [ { path: repoPath, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }, diff --git a/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts b/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts index 6b0b8bf52f0..e3faab50234 100644 --- a/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts @@ -14,7 +14,7 @@ import { openWorktreeCreatePathClaim } from '../../../workspaces/creation/worktr import { exactNameLateCollision } from '../../../workspaces/creation/worktree-create-exact-name' import { pendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-table' import { runtimePathExists } from '../catalog/runtime-worktree-filesystem' -import { WorktreeCreate } from '../../../../shared/rpc-contract/worktree-create-params' +import { WorktreeCreate } from '../../../../shared/rpc-contract/workspaces/worktree-create-params' import { buildManagedWorktreeCreateArgs } from '../../rpc/methods/workspaces/worktree-create-args' import { RuntimeRemoteFetchController } from '../../repositories/runtime-remote-fetch-controller' import { resolveRuntimeLocalWorktreeCreateCandidate } from './runtime-local-worktree-create-candidate' @@ -240,12 +240,11 @@ describe('explicit branch reuse with real Git', () => { trackRemoteBranch: true, remoteTrackingBase: f.remoteTrackingBase ?? undefined }) - const result = await create - expect(result.upstreamWarning).toContain('Check the push destination') - expect(result.upstreamWarning).toContain(f.base) + await create + expect(await git(picked.worktreePath, 'rev-parse', 'HEAD')).toBe(f.initialTip) expect(await git(picked.worktreePath, 'symbolic-ref', 'HEAD')).toBe(`refs/heads/${f.branch}`) - await expect(git(picked.worktreePath, 'rev-parse', '@{upstream}')).rejects.toThrow() + expect(await git(f.repoPath, 'config', 'remote.team/upstream.fetch')).toBe( '+refs/heads/main:refs/remotes/team/upstream/main' ) @@ -280,22 +279,51 @@ describe('explicit branch reuse with real Git', () => { } ) - it('pins the branch across path collisions and refuses a branch created after preflight', async () => { + it('pins the selected branch across workspace path collisions', async () => { const f = await fixture() await mkdir(join(f.workspaceRoot, 'My-workspace'), { recursive: true }) const picked = await f.candidate() expect(picked.worktreePath).toBe(join(f.workspaceRoot, 'My-workspace-2')) expect(picked.branchName).toBe(f.branch) - await git(f.repoPath, 'branch', f.branch) - await expect( - addWorktree(f.repoPath, picked.worktreePath, picked.branchName, f.base, false, false, { - trackRemoteBranch: true + }) +}) + +describe('cleanup ownership before candidate fallbacks', () => { + it('keeps generated allocation and ordinary collision suffixes', async () => { + const f = await fixture() + const path = join(f.workspaceRoot, 'nautilus') + const record = { + worktreeId: `repo::${path}`, + repoId: 'repo', + repoPath: f.repoPath, + worktreePath: path, + branch: 'nautilus', + head: f.initialTip, + deleteBranch: true, + force: true, + requestedAt: 0 + } + pendingWorktreeRemovals.set(record.worktreeId, record) + try { + const generated = await f.candidate({ + name: 'nautilus', + nameWasGenerated: true, + branchNameOverride: undefined, + branchIntent: 'create-new' }) - ).rejects.toThrow() - expect(await git(f.repoPath, 'rev-parse', `refs/heads/${f.branch}`)).toBe(f.initialTip) - await expect( - git(f.repoPath, 'rev-parse', '--verify', `refs/heads/${f.branch}-2`) - ).rejects.toThrow() + expect(generated.worktreePath).toBe(join(f.workspaceRoot, 'nautilus-2')) + expect(generated.branchName).toBe('nautilus-2') + await git(f.repoPath, 'branch', 'occupied') + const ordinary = await f.candidate({ + name: 'ordinary', + branchNameOverride: 'occupied', + branchIntent: 'create-new' + }) + expect(ordinary.branchName).toBe('occupied-2') + expect(ordinary.worktreePath).toBe(join(f.workspaceRoot, 'ordinary-2')) + } finally { + pendingWorktreeRemovals.delete(record.worktreeId) + } }) }) @@ -332,41 +360,6 @@ describe('exact-name create with real Git', () => { ) }) - it.each(['an existing folder', 'a pending removal', 'an in-flight create'])( - 'refuses a path held by %s and leaves the claims as they were', - async (holder) => { - const f = await fixture() - const path = join(f.workspaceRoot, 'Login-fix') - const foreign = openWorktreeCreatePathClaim() - if (holder === 'an existing folder') { - await mkdir(path, { recursive: true }) - } else if (holder === 'a pending removal') { - pendingWorktreeRemovals.set('exact-name-test', { - worktreeId: `repo::${path}`, - repoId: 'repo', - repoPath: f.repoPath, - worktreePath: path, - branch: '', - head: '', - deleteBranch: false, - force: false, - requestedAt: 0 - }) - } else { - expect(foreign.claim(path)).toBe(true) - } - try { - await expect(f.candidate(exact('Login fix'))).rejects.toMatchObject(refused) - const probe = openWorktreeCreatePathClaim() - expect(probe.claim(path)).toBe(holder !== 'an in-flight create') - probe.release() - } finally { - foreign.release() - pendingWorktreeRemovals.delete('exact-name-test') - } - } - ) - it('maps a branch created after the check to the refusal with no workspace left', async () => { const f = await fixture() const picked = await f.candidate(exact('late race')) diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts index 1aecde1f210..9e4b0401d9a 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts @@ -10,7 +10,7 @@ import { resolveWorktreeCreateDisplayNameRequest } from '../../../ipc/worktree-d import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' import type { Repo } from '../../../../shared/repo-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' import { getRuntimeFolderWorkspaceInstanceId, @@ -31,6 +31,7 @@ import { type RuntimeFolderWorktreeSetupDeps } from './runtime-folder-worktree-setup' import { buildRuntimeSetupReceipt } from './runtime-local-worktree-setup' +import { createdWorktreeLifecycleIdentity } from '../lifecycle/worktree-lifecycle-event' type RuntimeFolderWorktreeCreateDeps = { store: RuntimeStore @@ -146,7 +147,8 @@ export async function createRuntimeFolderWorktree(args: { kind: 'created', worktreeId: worktree.id, path: worktree.path, - branch: worktree.branch + branch: worktree.branch, + ...createdWorktreeLifecycleIdentity(worktree) }) const setupResult = deps.setup ? await prepareFolderWorktreeSetup({ diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts index 7e1595156b6..b7806ab2def 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts @@ -4,7 +4,7 @@ import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' import type { Worktree } from '../../../../shared/worktree/types' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { startRuntimeLocalWorktreeTerminals, diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts index 278d8fc9d61..3a8b3393fe6 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts @@ -24,7 +24,7 @@ import { WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../../../workspaces/creation/worktree-create-candidates' import { isGeneratedWorktreeCreateName } from '../../../../shared/new-workspace/worktree-create-retry-policy' -import { createRetiredNameLookup } from '../../../../shared/worktree/retired-name-registry' +import { createRetiredNameLookup } from '../../../../shared/worktree/naming/retired-name-registry' import { getRetiredNameRegistryForRepo } from '../../../workspaces/removal/retirement/worktree-name-retirement' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import { @@ -39,7 +39,8 @@ import { resolveCreateBranchName } from './runtime-worktree-create-git' import { runtimePathExists } from '../catalog/runtime-worktree-filesystem' -import { findPendingWorktreeRemovalConflict } from '../../../workspaces/removal/worktree-removal-table' +import { assertNoPendingWorktreeRemovalConflict } from '../../../workspaces/removal/worktree-removal-table' +import { isWorktreePathReserved } from '../../../workspaces/creation/reserved-worktree-path' import type { WorktreeCreatePathClaim } from '../../../workspaces/creation/worktree-create-in-flight' import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' @@ -80,7 +81,6 @@ export async function resolveRuntimeLocalWorktreeCreateCandidate(args: { let branchName = '' let checkoutExistingBranch = false let selectedExistingLocalBranchName: string | null = null - let selectedReuseBranchName: string | null = null let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false @@ -100,7 +100,28 @@ export async function resolveRuntimeLocalWorktreeCreateCandidate(args: { ) : null const isRetiredName = retiredNameRegistry ? createRetiredNameLookup(retiredNameRegistry) : null - selectedReuseBranchName = await resolveLegacyRemoteBranch({ ...args, sanitizedName }) + if (args.request.nameWasGenerated !== true || args.request.branchNameOverride) { + assertNoPendingWorktreeRemovalConflict(args.repo.path, { + worktreePath: + args.request.nameWasGenerated === true + ? undefined + : ensurePathWithinWorkspace( + computeWorktreePath(sanitizedName, args.repo.path, args.worktreePathSettings), + args.workspaceRoot + ), + branch: + args.request.branchNameOverride || + (await resolveCreateBranchName( + args.repo.path, + undefined, + sanitizedName, + args.settings, + args.username, + args.localWorktreeGitOptions + )) + }) + } + let selectedReuseBranchName = await resolveLegacyRemoteBranch({ ...args, sanitizedName }) if (selectedReuseBranchName) { branchName = selectedReuseBranchName } @@ -115,9 +136,9 @@ export async function resolveRuntimeLocalWorktreeCreateCandidate(args: { computeWorktreePath(effectiveSanitizedName, args.repo.path, args.worktreePathSettings), args.workspaceRoot ) - // Orca owns the path until background removal settles. + // Orca owns the path until background removal settles, and while it is archived. return ( - !findPendingWorktreeRemovalConflict(args.repo.path, { worktreePath }) && + !isWorktreePathReserved(args.store, args.repo, worktreePath) && !(await runtimePathExists(worktreePath)) && args.pathClaim.claim(worktreePath) ) diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts index 23ace84b92c..0a24745a40e 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts @@ -1,6 +1,5 @@ -import '../../../../shared/worktree/retired-name-registry' +import '../../../../shared/worktree/naming/retired-name-registry' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { basename } from 'node:path' import '../../../../shared/constants' @@ -15,13 +14,13 @@ const { } = await vi.hoisted(async () => await import('./runtime-local-worktree-create-test-harness')) vi.mock('../../../text-generation/commit-message-text-generation', () => ({ - resolveTextGenerationParams: () => ({ + resolveCommitMessageSettings: () => ({ ok: true, params: { agentId: 'claude', model: 'fixture' } }), generateBranchNameFromContext: async () => ({ success: true, slug: 'fix-auth' }) })) -vi.mock('../../../text-generation/commit-message-agent-environment', () => ({ +vi.mock('../../../text-generation/execution/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: async () => ({ ok: true }) })) @@ -104,33 +103,6 @@ describe('runtime create listing hold', () => { }) }) -describe('runtime concurrent creates on one name', () => { - const addedPaths = (): string[] => mocks.add.mock.calls.map((call) => String(call[1])) - - beforeEach(() => { - mocks.consume.mockResolvedValue({ status: 'miss', reason: 'disabled', rearm: mocks.rearm }) - let reached = 0 - let bothAdding: () => void = () => {} - const gate = new Promise((resolveGate) => (bothAdding = resolveGate)) - // Hold both creates inside Git's add, where neither checkout exists on disk yet. - mocks.add.mockImplementation(async () => { - if (++reached === 2) { - bothAdding() - } - await gate - return {} - }) - }) - - it('releases the claim when the create fails', async () => { - mocks.add.mockRejectedValueOnce(new Error('add failed')) - await expect(createWorktree({ name: 'app' })).rejects.toThrow('add failed') - mocks.add.mockResolvedValue({}) - await createWorktree({ name: 'app' }) - expect(addedPaths().map((path) => basename(path))).toEqual(['app', 'app']) - }) -}) - describe('runtime create base without a tracking ref', () => { const originMain = { remote: 'origin', @@ -150,13 +122,6 @@ describe('runtime create base without a tracking ref', () => { mocks.refresh.mockResolvedValue({ ok: false, errorKind: 'git_error' }) const result = await createWorktree({ baseBranch: 'origin/main', allowLocalBaseFallback: true }) - - expect(mocks.consume).toHaveBeenCalledWith( - expect.objectContaining({ - baseBranch: 'main', - options: expect.not.objectContaining({ remoteTrackingBase: expect.anything() }) - }) - ) expect(result.baseFallback).toEqual({ requestedRef: 'origin/main', localRef: 'main' }) expect(result.addResult).not.toHaveProperty('baseFallback') expect(result.worktree.baseRef).toBe('main') diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-materialization.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-materialization.ts index 514a9902093..461604a4377 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-materialization.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-materialization.ts @@ -147,10 +147,25 @@ export async function materializeRuntimeLocalWorktree(args: { hostId: meta.hostId ?? getRepoExecutionHostId(repo) } const metadataResult = args.onMetadataPersisted(worktree) + const { includeCopyWarning } = await materializeWorktreeContentPaths( + repo, + created.path, + localWorktreeGitOptions, + timing + ) + return { worktree, metadataResult, ...(includeCopyWarning ? { includeCopyWarning } : {}) } +} +/** Repo-configured files a fresh checkout lacks: symlinks, shared directories and .worktreeinclude copies. */ +export async function materializeWorktreeContentPaths( + repo: Repo, + worktreePath: string, + localWorktreeGitOptions: LocalGitExecOptions, + timing: Pick +): Promise<{ includeCopyWarning?: string }> { if ((repo.symlinkPaths ?? []).length > 0) { await timing.time('create_symlinks', () => - createWorktreeLinkedPaths(repo.path, created.path, repo.symlinkPaths ?? []) + createWorktreeLinkedPaths(repo.path, worktreePath, repo.symlinkPaths ?? []) ) } // These discoveries are read-only; overlap them, but keep the shared-path @@ -165,18 +180,18 @@ export async function materializeRuntimeLocalWorktree(args: { ]) if (sharedDirectories.length > 0) { await timing.time('create_shared_directories', () => - createWorktreeSharedPaths(repo.path, created.path, sharedDirectories) + createWorktreeSharedPaths(repo.path, worktreePath, sharedDirectories) ) } if (worktreeIncludePaths.length === 0) { - return { worktree, metadataResult } + return {} } const skippedIncludePaths = await timing.time('copy_worktreeinclude', () => - createWorktreeCopiedPaths(repo.path, created.path, worktreeIncludePaths) + createWorktreeCopiedPaths(repo.path, worktreePath, worktreeIncludePaths) ) const includeCopyWarning = formatWorktreeIncludeCopyWarning(skippedIncludePaths) if (includeCopyWarning) { console.warn(`[worktree-include] ${includeCopyWarning}`) } - return { worktree, metadataResult, ...(includeCopyWarning ? { includeCopyWarning } : {}) } + return includeCopyWarning ? { includeCopyWarning } : {} } diff --git a/src/main/runtime/workspaces/creation/runtime-managed-worktree-create-types.ts b/src/main/runtime/workspaces/creation/runtime-managed-worktree-create-types.ts index 7c410a94b7c..d1871cfc88c 100644 --- a/src/main/runtime/workspaces/creation/runtime-managed-worktree-create-types.ts +++ b/src/main/runtime/workspaces/creation/runtime-managed-worktree-create-types.ts @@ -12,7 +12,7 @@ import type { } from '../../../../shared/worktree/types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../../shared/workspace-source' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { CrossStoreInferredSource, CrossStoreParentRef diff --git a/src/main/runtime/workspaces/creation/runtime-worktree-create-git.test.ts b/src/main/runtime/workspaces/creation/runtime-worktree-create-git.test.ts index 42e33c8b45a..d345dd5b012 100644 --- a/src/main/runtime/workspaces/creation/runtime-worktree-create-git.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-worktree-create-git.test.ts @@ -70,3 +70,35 @@ describe('explicit local branch reuse on the execution host', () => { expect(worktrees).not.toHaveBeenCalled() }) }) + +describe('filesystem aliases of checked-out branches', () => { + const nfcBranch = 'feature/수신'.normalize('NFC') + const nfdBranch = nfcBranch.normalize('NFD') + + function mockGit(checkedOutBranch: string, listRef: (ref: string) => string): void { + git.mockImplementation(async (args: string[]) => + args[0] === 'for-each-ref' ? { stdout: listRef(args[2]) } : { stdout: 'abc123\n' } + ) + worktrees.mockResolvedValue([{ path: '/busy', branch: `refs/heads/${checkedOutBranch}` }]) + } + + it('rejects an NFD name that macOS Git resolves to a checked-out NFC branch (#18447)', async () => { + mockGit(nfcBranch, () => `refs/heads/${nfcBranch}\n`) + + await expect(canCheckoutExistingLocalBranch('/repo', nfdBranch, nfdBranch)).resolves.toBe(false) + }) + + it('rejects a case alias of a checked-out branch on a case-insensitive filesystem', async () => { + mockGit('feature/test', () => '') + + await expect( + canCheckoutExistingLocalBranch('/repo', 'feature/TEST', 'feature/TEST') + ).resolves.toBe(false) + }) + + it('allows a distinct alias on filesystems that store both spellings', async () => { + mockGit(nfcBranch, (ref) => `${ref}\n`) + + await expect(canCheckoutExistingLocalBranch('/repo', nfdBranch, nfdBranch)).resolves.toBe(true) + }) +}) diff --git a/src/main/runtime/workspaces/creation/runtime-worktree-create-git.ts b/src/main/runtime/workspaces/creation/runtime-worktree-create-git.ts index 9a672e2c0ae..1e26a4dde6c 100644 --- a/src/main/runtime/workspaces/creation/runtime-worktree-create-git.ts +++ b/src/main/runtime/workspaces/creation/runtime-worktree-create-git.ts @@ -2,7 +2,7 @@ import { getStoredRepoExecutionHostId } from '../../../workspaces/execution-host import type { BranchPrefixStrategy } from '../../../../shared/ui-chrome-types' import type { Repo } from '../../../../shared/repo-types' import { getPRForBranch } from '../../../github/client/lookup/get-pr-for-branch' -import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { foldGitRefNameCase } from '../../../git/refs/resolution/repo-branch-conflict' import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache' @@ -96,12 +96,15 @@ export async function canCheckoutExistingLocalBranch( } const worktrees = await listWorktrees(repoPath, gitOptions) let busy = worktrees.find((worktree) => normalizeLocalBranchName(worktree.branch) === branchName) - if (explicitReuse && !busy) { + if (!busy) { + // Why: macOS Git resolves case and NFC/NFD aliases to one stored ref; Linux keeps them distinct. + // Explicit reuse already verified that the requested spelling is stored exactly. for (const worktree of worktrees) { const checkedOutBranch = normalizeLocalBranchName(worktree.branch) if ( foldGitRefNameCase(checkedOutBranch) === foldGitRefNameCase(branchName) && - !(await hasExactBranchRef(checkedOutBranch)) + ((!explicitReuse && !(await hasExactBranchRef(branchName))) || + !(await hasExactBranchRef(checkedOutBranch))) ) { busy = worktree break diff --git a/src/main/runtime/workspaces/creation/workspace-creation.ts b/src/main/runtime/workspaces/creation/workspace-creation.ts index d64f593a6ab..51a626f9184 100644 --- a/src/main/runtime/workspaces/creation/workspace-creation.ts +++ b/src/main/runtime/workspaces/creation/workspace-creation.ts @@ -40,6 +40,7 @@ import { workspaceLifecycleKey } from '../lifecycle/workspace-lifecycle-commands import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { applyWorkspaceCreatePluginHook } from '../../../plugins/hooks/workspace-create-plugin-hook' import { withProjectWorktreeCreate } from '../../../workspaces/creation/worktree-create-in-flight' +import { createdWorktreeLifecycleIdentity } from '../lifecycle/worktree-lifecycle-event' export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWithGetWorktreeTerminalProvisioningHost { abstract resolveLineageForWorktreeCreate( @@ -240,7 +241,8 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi kind: 'created', worktreeId: worktree.id, path: worktree.path, - branch: worktree.branch + branch: worktree.branch, + ...createdWorktreeLifecycleIdentity(worktree) }) return { worktree: { diff --git a/src/main/runtime/workspaces/lifecycle/workspace-lifecycle-commands.ts b/src/main/runtime/workspaces/lifecycle/workspace-lifecycle-commands.ts index f44cd12d861..884b4e86936 100644 --- a/src/main/runtime/workspaces/lifecycle/workspace-lifecycle-commands.ts +++ b/src/main/runtime/workspaces/lifecycle/workspace-lifecycle-commands.ts @@ -1,4 +1,4 @@ -import type { NestedWorktreeRemovalApproval } from '../../../../shared/worktree/nested-removal' +import type { NestedWorktreeRemovalApproval } from '../../../../shared/worktree/removal/nested-removal' import type { RuntimeWorktreeTerminalCloseResult, RuntimeWorktreeTerminalSleepResult @@ -12,7 +12,7 @@ import { splitWorktreeId } from '../../../../shared/worktree/id' import { isProvenLivePtyRemovalError, isUnstoppedPtyRemovalError -} from '../../../../shared/worktree/removal' +} from '../../../../shared/worktree/removal/removal' import { getExplicitWorktreeIdSelector, getRuntimeWorktreeRemovalOptionsKey @@ -195,6 +195,35 @@ export function queueWorkspaceDelete( observe: observeTerminals(runtime, selector), delete: options } + return submitCheckoutDelete(runtime, selector, hostId, command) +} + +/** Archive deletes the checkout, so it queues as a delete; its own key refuses to join a plain delete. */ +export function queueWorkspaceArchive( + runtime: LifecycleRuntime & ObservingRuntime, + selector: string, + hostId: string | undefined, + run: () => Promise +): Promise { + return submitCheckoutDelete(runtime, selector, hostId, { + kind: 'delete', + run, + lostContact: deleteLostContact, + observe: observeTerminals(runtime, selector), + delete: { + key: 'archive', + force: false, + label: getExplicitWorktreeIdSelector(selector) ?? selector + } + }) +} + +function submitCheckoutDelete( + runtime: LifecycleRuntime, + selector: string, + hostId: string | undefined, + command: LifecycleCommand +): Promise { const queue = runtime.workspaceLifecycle if (!queue) { return command.run() @@ -214,3 +243,18 @@ export function queueWorkspaceDelete( command ) } + +/** Restore is ordered with this workspace's other commands; one sent during its archive is refused. */ +export function queueWorkspaceRestore( + runtime: LifecycleRuntime, + selector: string, + hostId: string | undefined, + run: () => Promise +): Promise { + // Restore takes a bare worktree id too; key it the same way so it never skips the queue. + const worktreeId = getExplicitWorktreeIdSelector(selector) ?? selector + const key = explicitKey(runtime.listRepos(), `id:${worktreeId}`, hostId) + return key + ? runWorkspaceLifecycleCommand(runtime.workspaceLifecycle, key, { kind: 'wake', run }) + : run() +} diff --git a/src/main/runtime/workspaces/lifecycle/worktree-lifecycle-event.ts b/src/main/runtime/workspaces/lifecycle/worktree-lifecycle-event.ts index b27f9758d83..4ee82b08c4c 100644 --- a/src/main/runtime/workspaces/lifecycle/worktree-lifecycle-event.ts +++ b/src/main/runtime/workspaces/lifecycle/worktree-lifecycle-event.ts @@ -1,3 +1,25 @@ +import type { ExecutionHostId } from '../../../../shared/execution-host' + +/** Host-qualified identity of the worktree, when it has one. Captured before a removal purges + * the metadata row, since listeners hear `removed` only after. */ +type WorktreeLifecycleIdentity = { identityKey?: string; hostId?: ExecutionHostId } + export type RuntimeWorktreeLifecycleEvent = - | { kind: 'created'; worktreeId: string; path: string; branch: string } - | { kind: 'removed'; worktreeId: string; path: string } + | ({ + kind: 'created' + worktreeId: string + path: string + branch: string + } & WorktreeLifecycleIdentity) + | ({ kind: 'removed'; worktreeId: string; path: string } & WorktreeLifecycleIdentity) + +/** A created worktree's identity, from the row Orca just built for it. */ +export function createdWorktreeLifecycleIdentity(worktree: { + identity?: { key: string } + hostId?: ExecutionHostId +}): WorktreeLifecycleIdentity { + return { + ...(worktree.identity ? { identityKey: worktree.identity.key } : {}), + ...(worktree.hostId ? { hostId: worktree.hostId } : {}) + } +} diff --git a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.test.ts b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.test.ts deleted file mode 100644 index 5950106adaf..00000000000 --- a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import '../../../../shared/agent-launch/catalog/tui-agent-display-names' -import type { CliWorktreeBuilder } from '../../rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture' -import '../../../../shared/execution-host' -import { WorktreeCreate } from '../../../../shared/rpc-contract/worktree-create-params' -import { WorktreeCreate as PreObservationCreate } from '../../../../shared/rpc-contract/worktree-create-params.pre-observation.test-fixture' -import { AgentLaunch, AgentLaunchReplay } from '../../../../shared/rpc-contract/agent-launch-params' -import { - AgentLaunch as PreObservationLaunch, - AgentLaunchReplay as PreObservationReplay -} from '../../../../shared/rpc-contract/agent-launch-params.pre-observation.test-fixture' -import { RuntimeWorktreeLineageController } from './runtime-worktree-lineage-controller' - -import type { ResolvedWorktree } from '../catalog/runtime-worktree-path-identity' -import { - formatAmbiguousCwdParentMessage, - type WorktreeLineageInput -} from './runtime-worktree-lineage-resolution' -import { - makeRuntimeOrchestrationDb, - taskLineageRow -} from '../../orca-runtime-tests/runtime-orchestration-db.test-fixture' -import { buildManagedWorktreeCreateArgs } from '../../rpc/methods/workspaces/worktree-create-args' -import { mapRuntimeError } from '../../rpc/errors' - -const fixturesPath = '../../../../cli/test-fixtures' -const { buildWorktree }: { buildWorktree: CliWorktreeBuilder } = await import(fixturesPath) -const root: Omit, 'identity'> = buildWorktree( - '/tmp/owner-choice', - 'main', - 'abc', - 'repo-a' -) -const siblingId = `${root.id}::workspace:11111111-1111-4111-8111-111111111111` -const choices = [`id:${siblingId}`, `id:${root.id}`] -const unresolved = { - cwdParentWorktree: choices[0], - cwdParentAmbiguous: true as const, - callerTerminalHandle: 'term_R' -} - -function worktree(id: string): ResolvedWorktree { - return { - ...root, - ...root.git, - id, - hostId: 'local', - instanceId: id, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 - } -} - -function fixture() { - const db = makeRuntimeOrchestrationDb() - const showTerminal = vi.fn(async (_handle: string) => ({ worktreeId: root.id })) - const resolveWorktree = vi.fn(async (selector: string) => { - if (selector === 'id:stale') { - throw new Error('selector_not_found') - } - return worktree(selector.replace(/^id:/, '')) - }) - const controller = new RuntimeWorktreeLineageController({ - getStore: () => null, - getDb: () => db, - showTerminal, - resolveWorkspace: async (selector: string) => ({ - kind: 'worktree' as const, - worktree: await resolveWorktree(selector) - }) - }) - return { controller, db, showTerminal, resolveWorktree } -} - -function parseVersionedCreate( - newHost: boolean, - route: 'create' | 'launch' | 'replay', - create: Record -) { - if (route === 'create') { - return (newHost ? WorktreeCreate : PreObservationCreate).parse(create) - } - const schema = - route === 'launch' - ? newHost - ? AgentLaunch - : PreObservationLaunch - : newHost - ? AgentLaunchReplay - : PreObservationReplay - const parsed = schema.parse({ - agent: 'codex', - operationId: `${Date.now()}-${'a'.repeat(32)}`, - target: { kind: 'create-worktree', create } - }) - if (parsed.target.kind !== 'create-worktree') { - throw new Error('fixture target changed') - } - return parsed.target.create -} - -afterEach(() => vi.restoreAllMocks()) - -describe('consumed cwd parent at the production authority boundary', () => { - it.each(['absent', 'stale-terminal', 'stale-env', 'stale-task', 'terminal-disappears'])( - 'refuses a retained positive cwd tie (%s), preserving exact RPC recovery', - async (kind) => { - const { controller, showTerminal, db } = fixture() - const input: WorktreeLineageInput = { ...unresolved } - if (kind === 'terminal-disappears') { - expect(await showTerminal('term_R')).toEqual({ worktreeId: root.id }) - expect(await controller.resolveParent(choices[1]!)).toMatchObject({ - worktree: { id: root.id } - }) - } - showTerminal.mockRejectedValue(new Error('terminal_not_found')) - if (kind === 'absent') { - delete input.callerTerminalHandle - } - if (kind === 'stale-env') { - input.envParentWorkspace = 'id:stale' - } - if (kind === 'stale-task') { - input.comment = 'created for task_stale' - vi.spyOn(db, 'getTask').mockReturnValue( - taskLineageRow({ id: 'task_stale', created_by_terminal_handle: 'term_gone' }) - ) - } - for (const order of [choices, choices.toReversed()]) { - let caught: unknown - try { - await controller.resolveCreate( - { ...input, cwdParentWorktree: order[0], cwdParentAmbiguous: true }, - 'local' - ) - } catch (error) { - caught = error - } - expect(caught).toMatchObject({ code: 'LINEAGE_PARENT_AMBIGUOUS' }) - const wire = mapRuntimeError('refusal', { runtimeId: 'runtime-1' }, caught) - expect(wire).toMatchObject({ - ok: false, - error: { - code: 'LINEAGE_PARENT_AMBIGUOUS', - message: formatAmbiguousCwdParentMessage() - } - }) - } - } - ) - - it.each([false, true])( - 'executes old/new client and host schema compatibility (newClient=%s)', - async (newClient) => { - const { controller, showTerminal } = fixture() - const request = { - repo: 'id:repo-a', - name: 'child', - cwdParentWorktree: choices[0], - callerTerminalHandle: 'term_R', - ...(newClient ? { cwdParentAmbiguous: true } : {}) - } - for (const newHost of [false, true]) { - for (const route of ['create', 'launch', 'replay'] as const) { - const parsed = parseVersionedCreate(newHost, route, request) - const { lineage } = buildManagedWorktreeCreateArgs(parsed, {}) - showTerminal.mockResolvedValue({ worktreeId: root.id }) - expect(await controller.resolveCreate(lineage, 'local')).toMatchObject({ - kind: 'lineage', - capture: { source: 'terminal-context' }, - parent: { worktree: { id: root.id } } - }) - showTerminal.mockRejectedValue(new Error('terminal_not_found')) - if (newHost && newClient) { - await expect(controller.resolveCreate(lineage, 'local')).rejects.toMatchObject({ - code: 'LINEAGE_PARENT_AMBIGUOUS' - }) - } else { - expect(lineage).not.toHaveProperty('cwdParentAmbiguous') - expect(await controller.resolveCreate(lineage, 'local')).toMatchObject({ - kind: 'lineage', - capture: { source: 'cwd-context', confidence: 'inferred' }, - parent: { worktree: { id: siblingId } } - }) - } - } - } - } - ) -}) diff --git a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts index 9cc4280d781..66940c6f11e 100644 --- a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts +++ b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal/removal-visibility' import { isCrossStoreInferredSource, type CrossStoreInferredSource, @@ -14,7 +15,7 @@ import { worktreeWorkspaceKey } from '../../../../shared/workspace-scope' import { sharesResolvedWorktreeLineageBoundary } from '../../../../shared/resolved-worktree-lineage' -import { crossStoreParentRefOfRow } from '../../../../shared/worktree/lineage-row-identity' +import { crossStoreParentRefOfRow } from '../../../../shared/worktree/lineage/lineage-row-identity' import type { OrchestrationDb } from '../../orchestration/db/orchestration-db' import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { ResolvedWorktree } from '../catalog/runtime-worktree-path-identity' @@ -48,6 +49,9 @@ type RuntimeWorktreeLineageDependencies = { } function worktreeParent(worktree: ResolvedWorktree): ResolvedWorkspaceParent { + if (isWorktreeRetiredByRemoval(worktree)) { + throw new Error('selector_not_found') + } return { type: 'worktree', workspaceKey: worktreeWorkspaceKey(worktree.id), diff --git a/src/main/runtime/workspaces/managed-workspace-operations.ts b/src/main/runtime/workspaces/managed-workspace-operations.ts index cf501b5048d..d888c32f6cd 100644 --- a/src/main/runtime/workspaces/managed-workspace-operations.ts +++ b/src/main/runtime/workspaces/managed-workspace-operations.ts @@ -6,7 +6,7 @@ import type { DetectedWorktreeListResult, Worktree } from '../../../shared/workt import type { Repo } from '../../../shared/repo-types' import type { RepoRowExecutionHostLookup } from '../../../shared/execution-host/worktree-execution-host-resolution' import { stopMissingWorktreeTerminals } from './removal/missing-worktree-terminal-reconciliation' -import type { WorktreeVisibilitySourceMatcher } from '../../../shared/worktree/visibility-sources' +import type { WorktreeVisibilitySourceMatcher } from '../../../shared/worktree/visibility/visibility-sources' import type { RuntimeStore } from '../construction/runtime-store-contract' import { getWorkspaceAttachments } from '../../../shared/workspace-attachments/workspace-attachments' import type { TerminalWorkspaceLaunchScope } from '../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' diff --git a/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts b/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts index 06e4aa6a71f..872c2e19ba5 100644 --- a/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts +++ b/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts @@ -7,7 +7,7 @@ import { worktreeWorkspaceKey } from '../../../../shared/workspace-scope' import { splitWorktreeId } from '../../../../shared/worktree/id' -import type { WorktreeSortOrderUpdate } from '../../../../shared/worktree/sort-order-update' +import type { WorktreeSortOrderUpdate } from '../../../../shared/worktree/metadata/sort-order-update' import { stripOrcaProvenanceMetaUpdates } from '../../../workspaces/removal/worktree-removal-safety' import { isRemovedFolderWorkspaceInstance } from '../../../workspaces/catalog/folder-workspace-meta-presence' import { worktreeRowTarget } from '../../../persistence/host-qualified-worktree-meta' diff --git a/src/main/runtime/workspaces/metadata/runtime-worktree-base-reconciliation.ts b/src/main/runtime/workspaces/metadata/runtime-worktree-base-reconciliation.ts index be72ac194e9..1ad7825abd5 100644 --- a/src/main/runtime/workspaces/metadata/runtime-worktree-base-reconciliation.ts +++ b/src/main/runtime/workspaces/metadata/runtime-worktree-base-reconciliation.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto' -import type { WorktreeBaseStatusEvent } from '../../../../shared/worktree/base-ref-drift-types' +import type { WorktreeBaseStatusEvent } from '../../../../shared/worktree/base-refs/base-ref-drift-types' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import type { RuntimeNotifier } from '../../client/events/runtime-notifier-contract' import type { diff --git a/src/main/runtime/workspaces/metadata/workspace-activity-records-twins.test.ts b/src/main/runtime/workspaces/metadata/workspace-activity-records-twins.test.ts new file mode 100644 index 00000000000..b3f1646c874 --- /dev/null +++ b/src/main/runtime/workspaces/metadata/workspace-activity-records-twins.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { Repo } from '../../../../shared/repo-types' +import { + hostWorktreeTarget, + type HostWorktreeTarget +} from '../../../../shared/worktree/host-qualified-identity' +import { readSortStamps, writeSortStamps, writeUnreadFlag } from './workspace-activity-records' + +const WT = 'dup::/wt' +type Row = { lastActivityAt: number; isUnread?: boolean; hostId?: ExecutionHostId } + +function repo(overrides: Partial): Repo { + return { + id: 'dup', + path: '/wt', + displayName: 'dup', + badgeColor: '#000', + addedAt: 1, + ...overrides + } +} + +// Mirrors the persistence store: the raw-id row belongs to whichever twin wrote first. +function twinStore(repos: Repo[]) { + const byHost = new Map() + let rawOwner: ExecutionHostId | undefined + return { + byHost, + getRepos: () => repos, + getWorktreeMeta: (id: string) => (id === WT && rawOwner ? byHost.get(rawOwner) : undefined), + getWorktreeMetaForHost: (id: string, hostId: ExecutionHostId) => + id === WT ? byHost.get(hostId) : undefined, + setWorktreeMeta: (target: HostWorktreeTarget, updates: Partial) => { + rawOwner ??= target.hostId + byHost.set(target.hostId, { + ...(byHost.get(target.hostId) ?? { lastActivityAt: 0 }), + ...updates, + hostId: target.hostId + }) + } + } +} + +describe('sort stamps and unread for a local pane of a same-id twin', () => { + it('reads and writes the local copy, not the twin that wrote first', () => { + const store = twinStore([repo({}), repo({ connectionId: 'box' })]) + store.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'ssh:box' }), { + lastActivityAt: 5 + }) + store.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'local' }), { + lastActivityAt: 1 + }) + const localPane = { worktreeId: WT, sshHostId: null } + + expect(readSortStamps(store, localPane)?.recentAt).toBe(1) + writeSortStamps(store, localPane, { recentAt: 9 }) + expect(writeUnreadFlag(store, localPane, true)).toBe(true) + + expect(store.byHost.get('local')).toMatchObject({ lastActivityAt: 9, isUnread: true }) + expect(store.byHost.get('ssh:box')).toMatchObject({ lastActivityAt: 5 }) + expect(store.byHost.get('ssh:box')?.isUnread).toBeUndefined() + }) + + it('keeps the stamped row when the repo lives on one host', () => { + const store = twinStore([repo({ connectionId: 'box' })]) + store.setWorktreeMeta(hostWorktreeTarget({ id: WT, hostId: 'ssh:box' }), { + lastActivityAt: 5 + }) + + writeSortStamps(store, { worktreeId: WT, sshHostId: null }, { recentAt: 9 }) + + expect(store.byHost.get('ssh:box')?.lastActivityAt).toBe(9) + expect(store.byHost.has('local')).toBe(false) + }) +}) diff --git a/src/main/runtime/workspaces/metadata/workspace-activity-records.ts b/src/main/runtime/workspaces/metadata/workspace-activity-records.ts new file mode 100644 index 00000000000..04b68467014 --- /dev/null +++ b/src/main/runtime/workspaces/metadata/workspace-activity-records.ts @@ -0,0 +1,150 @@ +import { getRepoRegistrationHostIds } from '../../../../shared/repo-host-identity' +import type { AgentPaneWorkspace } from '../../../agent-hooks/observations/agent-transition-detector' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import type { + SmartStampFields, + SmartTier, + SortStamps +} from '../../../../shared/sidebar-list/sort-stamps' +import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' +import type { Repo } from '../../../../shared/repo-types' +import { + hostWorktreeTarget, + type HostWorktreeTarget +} from '../../../../shared/worktree/host-qualified-identity' +import { resolveWorktreeMetaOwner } from '../../../persistence/host-qualified-worktree-meta' + +type StampedRecord = { + lastActivityAt: number + isUnread?: boolean + hostId?: ExecutionHostId +} & SmartStampFields +type StampUpdates = { + lastActivityAt: number + smartTier: SmartTier | undefined + smartAt: number | undefined +} + +/** The per-workspace record reads and writes, which the runtime's store satisfies. */ +export type WorkspaceRecordStore = { + getWorktreeMeta: (worktreeId: string) => (TRecord & { hostId?: ExecutionHostId }) | undefined + setWorktreeMeta: (target: HostWorktreeTarget, updates: TUpdates) => unknown + getRepos: () => readonly Repo[] + getWorktreeMetaForHost?: (worktreeId: string, hostId: ExecutionHostId) => TRecord | undefined + getFolderWorkspace?: (folderWorkspaceId: string) => TRecord | undefined + updateFolderWorkspace?: (folderWorkspaceId: string, updates: TUpdates) => unknown +} + +type UnreadUpdate = { isUnread: boolean } + +/** The record reads and writes stamping and the unread flag need. */ +export type SortStampsStore = WorkspaceRecordStore & { + getAllWorktreeMeta?: () => Record + getFolderWorkspaces?: () => readonly (StampedRecord & { id: string })[] +} + +/** The workspace's own record: folder, SSH host, or local. */ +export function readWorkspaceRecord( + store: WorkspaceRecordStore | null, + { worktreeId, sshHostId }: AgentPaneWorkspace +): TRecord | undefined { + const scope = parseWorkspaceKey(worktreeId) + if (scope?.type === 'folder') { + return store?.getFolderWorkspace?.(scope.folderWorkspaceId) + } + const hostId = sshHostId ?? (store && localTwinHostId(store, worktreeId)) + return hostId + ? store?.getWorktreeMetaForHost?.(worktreeId, hostId) + : store?.getWorktreeMeta(worktreeId) +} + +/** Unhosted panes are local; with same-id twins, raw-id rows may belong elsewhere, so address the local copy explicitly. */ +function localTwinHostId( + store: Pick, 'getRepos'>, + worktreeId: string +): ExecutionHostId | null { + const hosts = getRepoRegistrationHostIds(store.getRepos(), getRepoIdFromWorktreeId(worktreeId)) + return hosts.size > 1 && hosts.has(LOCAL_EXECUTION_HOST_ID) ? LOCAL_EXECUTION_HOST_ID : null +} + +export function writeWorkspaceRecord( + store: WorkspaceRecordStore | null, + { worktreeId, sshHostId }: AgentPaneWorkspace, + updates: TUpdates +): void { + const scope = parseWorkspaceKey(worktreeId) + if (scope?.type === 'folder') { + store?.updateFolderWorkspace?.(scope.folderWorkspaceId, updates) + return + } + // No SSH host and no twin: the row the read above found, by its own stamp. + const hostId = sshHostId ?? (store && localTwinHostId(store, worktreeId)) + const target = hostId + ? hostWorktreeTarget({ id: worktreeId, hostId }) + : store && resolveWorktreeMetaOwner(store, worktreeId) + if (target) { + store?.setWorktreeMeta(target, updates) + } +} + +/** Sets the workspace's unread flag; true when its record held the other value. */ +export function writeUnreadFlag( + store: SortStampsStore | null, + workspace: AgentPaneWorkspace, + isUnread: boolean +): boolean { + const record = readWorkspaceRecord(store, workspace) + // Only a workspace with a record is written; writing would create one for a stale id. + if (!record || Boolean(record.isUnread) === isUnread) { + return false + } + writeWorkspaceRecord(store, workspace, { isUnread }) + return true +} + +// Only a workspace with a record is stamped; writing would create one for a stale id. +export function readSortStamps( + store: SortStampsStore | null, + workspace: AgentPaneWorkspace +): SortStamps | null { + const record = readWorkspaceRecord(store, workspace) + if (!record) { + return null + } + return { + recentAt: record.lastActivityAt, + ...(record.smartTier !== undefined + ? { smartTier: record.smartTier, smartAt: record.smartAt } + : {}) + } +} + +export function writeSortStamps( + store: SortStampsStore | null, + workspace: AgentPaneWorkspace, + stamps: SortStamps +): void { + // Both tier keys are always written, so Rest clears them. + writeWorkspaceRecord(store, workspace, { + lastActivityAt: stamps.recentAt, + smartTier: stamps.smartTier, + smartAt: stamps.smartAt + }) +} + +/** Every workspace whose record holds a tier. */ +export function listTieredWorkspaces(store: SortStampsStore | null): string[] { + const ids: string[] = [] + for (const [worktreeId, meta] of Object.entries(store?.getAllWorktreeMeta?.() ?? {})) { + if (meta.smartTier !== undefined) { + ids.push(worktreeId) + } + } + for (const folder of store?.getFolderWorkspaces?.() ?? []) { + if (folder.smartTier !== undefined) { + ids.push(folderWorkspaceKey(folder.id)) + } + } + return ids +} diff --git a/src/main/runtime/workspaces/persisted-surfaces/automation-api-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/automation-api-operations.ts index bdac0f5120f..f094a8752d7 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/automation-api-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/automation-api-operations.ts @@ -15,7 +15,9 @@ import { type AutomationChangeSelector, type AutomationListResult } from '../../../../shared/automations/ownership/automation-list-scope' -import type { AutomationService } from '../../../automations/service' +import type { AutomationService } from '../../../automations/automation-service' +import type { RuntimeAutomationBatchUpdate } from '../../integrations/automations/runtime-automation-batch-update' +import type { AutomationBatchUpdateResult } from '../../../persistence/scheduling-automations/automation-definition-update' import { OrcaRuntimeWithCrewOperations } from './crew-operations' export abstract class OrcaRuntimeWithAutomationApiOperations extends OrcaRuntimeWithCrewOperations { @@ -93,10 +95,11 @@ export abstract class OrcaRuntimeWithAutomationApiOperations extends OrcaRuntime createAutomation( input: RuntimeAutomationCreateInput, - destination?: AutomationDestination + destination?: AutomationDestination, + beforeWrite?: () => void ): Promise { return this.automation.withExternalProbePriority(() => - this.automation.create(input, destination).then((automation) => { + this.automation.create(input, destination, beforeWrite).then((automation) => { const selector = this.automationChangeSelector(automation.id) this.publishAutomationDefinitionChange(selector, selector) return automation @@ -118,6 +121,36 @@ export abstract class OrcaRuntimeWithAutomationApiOperations extends OrcaRuntime }) } + /** Many updates with one write, and one change event per affected host instead of per row. */ + updateAutomations( + entries: readonly RuntimeAutomationBatchUpdate[] + ): Promise { + return this.automation.withExternalProbePriority(() => { + const sources = new Map(entries.map(({ id }) => [id, this.automationChangeSelector(id)])) + return this.automation.updateMany(entries).then((results) => { + const published = new Set() + for (const result of results) { + if (!('automation' in result)) { + continue + } + const before = sources.get(result.id) ?? null + const after = this.automationChangeSelector(result.automation.id) + for (const selector of automationChangePublications(before, after)) { + const key = JSON.stringify(selector ?? null) + if (!published.has(key)) { + published.add(key) + this.notifyAutomationsChanged({ + reason: 'definition', + ...(selector ? { selector } : {}) + }) + } + } + } + return results + }) + }) + } + deleteAutomation( id: string, expectedOwner?: AutomationOwnerPrecondition diff --git a/src/main/runtime/workspaces/persisted-surfaces/has-exact-persisted-terminal-surface-identity.ts b/src/main/runtime/workspaces/persisted-surfaces/has-exact-persisted-terminal-surface-identity.ts index f8dd1f4e3fd..b434a61907b 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/has-exact-persisted-terminal-surface-identity.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/has-exact-persisted-terminal-surface-identity.ts @@ -1,7 +1,7 @@ import { resolveTerminalSessionWorktreeId } from '../catalog/runtime-worktree-path-identity' import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-pane-tree' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { worktreeIdsEqual } from '../../../../shared/worktree/id' import { RuntimeArtifactOperations } from '../../artifacts/runtime-artifact-operations' diff --git a/src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts b/src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts deleted file mode 100644 index f707f8d6e24..00000000000 --- a/src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' -import { OrcaRuntimeService } from '../../orca-runtime' -import { FIRST_SURFACE_PLACEMENT_WAIT_MS } from './restored-terminal-placement' -import type { ResolvedWorktree } from '../catalog/runtime-worktree-path-identity' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) - -// Activation must await main's in-flight placement census so the existing live terminal becomes the first tab without an extra shell. - -const WT = FIXTURE_GIT_WORKTREE_ID -const LIVE_PTY = `${WT}@@live` -const WINDOW_TAB = '33333333-3333-4333-8333-333333333333' -const WINDOW_LEAF = '44444444-4444-4444-8444-444444444444' -const directories: string[] = [] - -class CensusRuntime extends OrcaRuntimeService { - protected override async getResolvedWorktreeMap(): Promise> { - const worktree = this.buildResolvedWorktreeFromId(WT) - return new Map(worktree ? [[WT, worktree]] : []) - } -} - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -async function hostPlacingALiveTerminal() { - const directory = mkdtempSync(join(tmpdir(), 'orca-placement-before-initial-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - const live = [{ id: LIVE_PTY, cwd: '/fixture/local', title: 'zsh', worktreeId: WT }] - let answerCensus = (): void => {} - const census = new Promise((resolve) => { - answerCensus = () => resolve(live) - }) - const listProcesses = vi.fn(() => census) - const spawn = vi.fn() - const runtime = new CensusRuntime(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses - }) - const placing = runtime.placeUnshownLiveTerminals() - await vi.waitFor(() => expect(listProcesses).toHaveBeenCalled()) - const activate = () => - runtime.applyLayoutCommand({ - type: 'createTerminalTab', - workspace: WT, - tabId: WINDOW_TAB, - leafId: WINDOW_LEAF, - initial: 'activation' - }) - const tabsOf = () => store.getWorkspaceSession().tabsByWorktree[WT] ?? [] - return { store, spawn, placing, answerCensus, activate, tabsOf } -} - -it("gives an activating workspace no fresh shell beside a live terminal main's placement is still placing", async () => { - const { store, spawn, placing, answerCensus, activate, tabsOf } = await hostPlacingALiveTerminal() - - const activation = activate() - answerCensus() - await placing - const reply = await activation - - const tabs = tabsOf() - expect(tabs).toHaveLength(1) - expect( - Object.values( - store.getWorkspaceSession().terminalLayoutsByTabId[tabs[0]!.id]?.ptyIdsByLeafId ?? {} - ) - ).toEqual([LIVE_PTY]) - expect(reply.ok && reply.result.tabId).toBeFalsy() - expect(spawn).not.toHaveBeenCalled() -}) - -it('admits the first tab once the cap passes while the placement pass is still reading the census', async () => { - const { placing, answerCensus, activate, tabsOf } = await hostPlacingALiveTerminal() - - const startedAt = performance.now() - const reply = await activate() - const waitedMs = performance.now() - startedAt - - expect(waitedMs).toBeGreaterThanOrEqual(FIRST_SURFACE_PLACEMENT_WAIT_MS - 20) - expect(waitedMs).toBeLessThan(FIRST_SURFACE_PLACEMENT_WAIT_MS + 1_000) - expect(reply.ok && reply.result.tabId).toBe(WINDOW_TAB) - expect(tabsOf().map((tab) => tab.id)).toEqual([WINDOW_TAB]) - answerCensus() - await placing -}) diff --git a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts b/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts deleted file mode 100644 index 10e19b330d0..00000000000 --- a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../../../persistence/loading-store/store' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { ResolvedWorktree } from '../catalog/runtime-worktree-path-identity' -import { TERMINAL_QUERY_METHODS } from '../../rpc/methods/terminal/terminal-query-methods' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) - -// A window sweep must let main place only that workspace's unshown live terminals before listing them. - -const SWEPT = FIXTURE_GIT_WORKTREE_ID -const OTHER = 'repo-local::/fixture/other' -const directories: string[] = [] - -type LiveSession = { - id: string - cwd: string - title: string - worktreeId: string - incarnationId?: string - exiting?: true -} - -class SweepRuntime extends OrcaRuntimeService { - protected override async getResolvedWorktreeMap(): Promise> { - return new Map( - [SWEPT, OTHER].flatMap((id) => { - const worktree = this.buildResolvedWorktreeFromId(id) - return worktree ? [[id, worktree] as const] : [] - }) - ) - } - - ptyRecord(ptyId: string) { - return this.ptysById.get(ptyId) - } -} - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -function session(id: string, worktreeId = SWEPT): LiveSession { - return { id, cwd: '/fixture/local', title: 'zsh', worktreeId, incarnationId: `${id}-inc` } -} - -function runtimeOn(store: Store, live: LiveSession[]): SweepRuntime { - const runtime = new SweepRuntime(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [...live], - listProcessesWithHostScope: async () => ({ processes: [...live], hostIds: ['local' as const] }) - }) - return runtime -} - -async function hostWith(live: LiveSession[]) { - const directory = mkdtempSync(join(tmpdir(), 'orca-sweep-placement-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - return { store, directory, runtime: runtimeOn(store, live) } -} - -function boundPtyIds(store: Store, worktreeId: string): string[] { - const session = store.getWorkspaceSession() - return (session.tabsByWorktree[worktreeId] ?? []).flatMap((tab) => - Object.values(session.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId ?? {}) - ) -} - -function terminalListHandler() { - const method = TERMINAL_QUERY_METHODS.find((candidate) => candidate.name === 'terminal.list') - if (!method) { - throw new Error('terminal.list is not defined') - } - return method.handler -} - -describe('main places the swept workspace’s live terminals, layout-owner build', () => { - it('shows the swept workspace’s unshown terminal in a tab, and leaves another workspace’s', async () => { - const { store, runtime } = await hostWith([session('pty-swept'), session('pty-other', OTHER)]) - - await runtime.placeUnshownLiveTerminalsOf(`id:${SWEPT}`) - - expect(boundPtyIds(store, SWEPT)).toEqual(['pty-swept']) - expect(boundPtyIds(store, OTHER)).toEqual([]) - }) - - it('the sweep’s listing places before it lists, so it names the placed terminal’s pane', async () => { - const { runtime } = await hostWith([session('pty-swept')]) - - const context = { runtime } - const listing = await terminalListHandler()( - { - worktree: `id:${SWEPT}`, - limit: 200, - requireFreshPtyLiveness: true, - includeVisualLayouts: false, - placeUnshownLiveTerminals: true - }, - context - ) - - const listed = listing.terminals.find((terminal) => terminal.ptyId === 'pty-swept') - expect(listed).toMatchObject({ orphaned: false }) - expect(listed?.tabId).not.toMatch(/^pty:/) - }) - - it('leaves a terminal whose registration is still binding its pane, as a census does', async () => { - const { store, runtime } = await hostWith([session('pty-registering')]) - runtime.beginPtyRegistration('pty-registering', 'pty-registering-inc') - - await runtime.placeUnshownLiveTerminals() - - expect(boundPtyIds(store, SWEPT)).toEqual([]) - }) - - it('never brings back a closed tab’s terminal its host is killing', async () => { - const { store, runtime } = await hostWith([{ ...session('pty-closing'), exiting: true }]) - - await runtime.placeUnshownLiveTerminals() - - expect(boundPtyIds(store, SWEPT)).toEqual([]) - }) -}) - -describe('a terminal created by the CLI, across a restart, layout-owner build', () => { - it('is left alone while its run owns it, and after a restart is shown like any other', async () => { - const live = [session('pty-cli')] - const { store, directory, runtime } = await hostWith(live) - // The census records it; the CLI's create marks it owned by this run (terminal-create.ts). - await runtime.listTerminals(`id:${SWEPT}`) - runtime.ptyRecord('pty-cli')!.runtimeSessionOwned = true - - await runtime.placeUnshownLiveTerminals() - expect(boundPtyIds(store, SWEPT)).toEqual([]) - - // Run ownership is not saved; after restart, main must place the surviving unshown terminal as the window-owned sweep would. - const relaunched = await reopenTopologyStore(store, directory) - const restarted = runtimeOn(relaunched, live) - await restarted.placeUnshownLiveTerminals() - - expect(restarted.ptyRecord('pty-cli')?.runtimeSessionOwned).toBe(false) - expect(boundPtyIds(relaunched, SWEPT)).toEqual(['pty-cli']) - }) - - it('one whose pane was saved stays in that pane after a restart, with no second tab', async () => { - const live = [session('pty-cli')] - const { store, directory, runtime } = await hostWith(live) - await runtime.placeUnshownLiveTerminals() - expect(boundPtyIds(store, SWEPT)).toEqual(['pty-cli']) - - const relaunched = await reopenTopologyStore(store, directory) - await runtimeOn(relaunched, live).placeUnshownLiveTerminals() - - expect(boundPtyIds(relaunched, SWEPT)).toEqual(['pty-cli']) - }) -}) diff --git a/src/main/runtime/workspaces/process-listing/hook-live-agent-row.ts b/src/main/runtime/workspaces/process-listing/hook-live-agent-row.ts index 1670ccfbd4e..715ceda491f 100644 --- a/src/main/runtime/workspaces/process-listing/hook-live-agent-row.ts +++ b/src/main/runtime/workspaces/process-listing/hook-live-agent-row.ts @@ -1,3 +1,8 @@ +import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import { + pickHostTurnEnd, + pickParsedAgentStatusPayload +} from '../../../../shared/agent-status/contracts/agent-status-types' import type { RuntimeAgentRowSnapshot } from './runtime-hook-agent-row-selection' export type HookLiveAgentRow = Pick< @@ -11,3 +16,15 @@ export type HookLiveAgentRow = Pick< | 'worktreeId' | 'programStatus' > + +export function toHookLiveAgentRow(row: AgentStatusIpcPayload): HookLiveAgentRow { + return { + payload: pickParsedAgentStatusPayload(row), + updatedAt: row.receivedAt, + ...(row.evidenceObservedAt !== undefined ? { evidenceObservedAt: row.evidenceObservedAt } : {}), + stateStartedAt: row.stateStartedAt ?? row.receivedAt, + ...pickHostTurnEnd(row), + ...(row.worktreeId ? { worktreeId: row.worktreeId } : {}), + ...(row.programStatus ? { programStatus: row.programStatus } : {}) + } +} diff --git a/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts b/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts index 31adeffe75a..76975f86d60 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-hook-agent-row-selection.ts @@ -26,6 +26,7 @@ export type RuntimeAgentRowSnapshot = { updatedAt: number evidenceObservedAt?: number providerSession?: AgentProviderSessionMetadata + orcaSessionId?: string | null programStatus?: ProgramStatusFacet } @@ -161,6 +162,7 @@ export function selectFreshAgentRowForMobileTab(args: { ...pickHostTurnEnd(match), updatedAt: match.receivedAt, ...(match.providerSession ? { providerSession: match.providerSession } : {}), + ...(match.orcaSessionId !== undefined ? { orcaSessionId: match.orcaSessionId } : {}), ...(match.programStatus ? { programStatus: match.programStatus } : {}), ...(match.evidenceObservedAt !== undefined ? { evidenceObservedAt: match.evidenceObservedAt } diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts index f3ec79e8fcb..fdd67af5848 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts @@ -75,6 +75,7 @@ export function attachRuntimeWorktreeAgentRows(args: { parent && parent.tabId === source.tabId ? null : args.conversationName?.(source) const row: RuntimeWorktreeAgentRow = { paneKey: source.paneKey, + ...(source.orcaSessionId ? { orcaSessionId: source.orcaSessionId } : {}), parentPaneKey, state: source.state, ...(source.workingMode ? { workingMode: source.workingMode } : {}), diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-source.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-source.ts index 44714e8d225..75dc10ac717 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-source.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-source.ts @@ -21,6 +21,7 @@ export type RuntimeWorktreeAgentSource = Pick this._orchestrationDb ) + /** The task each pane was dispatched, by pane key, as `worktree.ps` rows title it. */ + listAgentTasksByPaneKey() { + return this.agentOrchestrationProjection.buildByPaneKey() ?? {} + } + async getWorktreePs( limit = DEFAULT_WORKTREE_PS_LIMIT, sourceDefaultsSupported = true, @@ -304,7 +309,11 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven reconcile: (state) => this.mobileNotifications.reconcileStructuredPromptAttention(state), now: () => Date.now() }), - onTurnAttention: chatWorkerTurnStopReporter(this.workerTurnStopReportDeps), + createTurnAttention: () => + chatWorkerTurnStopReporter({ + ...this.workerTurnStopReportDeps, + openExistingDb: () => this.getExistingOrchestrationDb() + }), // Re-read dispatch ownership each sweep; absence of a database cannot keep the worker alive. hasOpenDispatch: (record) => structuredWorkerOwesWork(this.getOrchestrationDbIfAvailable?.() ?? null, record) diff --git a/src/main/runtime/workspaces/process-listing/worktree-ps-degraded-repo-scan.test.ts b/src/main/runtime/workspaces/process-listing/worktree-ps-degraded-repo-scan.test.ts index ada74807a73..c62c1479819 100644 --- a/src/main/runtime/workspaces/process-listing/worktree-ps-degraded-repo-scan.test.ts +++ b/src/main/runtime/workspaces/process-listing/worktree-ps-degraded-repo-scan.test.ts @@ -32,6 +32,7 @@ import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { WorktreeLineage } from '../../../../shared/worktree/lineage-types' import { worktreeWorkspaceKey } from '../../../../shared/workspace-scope' import { OrcaRuntimeService } from '../../orca-runtime' +import { _resetWorktreeCatalogOwnerForTests } from '../../../workspaces/catalog/repo-worktree-catalog-owner' import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' import { @@ -144,6 +145,8 @@ async function advancePastRepoScanBudget(pending: Promise): Promise { describe('worktree.ps on a degraded repo scan', () => { beforeEach(() => { + // The catalog owner is process-wide; a previous case's failed scan must not answer this one. + _resetWorktreeCatalogOwnerForTests() listWorktreesStrictMock.mockReset() listWorktreesStrictMock.mockResolvedValue([]) }) diff --git a/src/main/runtime/workspaces/removal/folder-workspace-pty-teardown.ts b/src/main/runtime/workspaces/removal/folder-workspace-pty-teardown.ts index a44d9a4b008..a84f71ed993 100644 --- a/src/main/runtime/workspaces/removal/folder-workspace-pty-teardown.ts +++ b/src/main/runtime/workspaces/removal/folder-workspace-pty-teardown.ts @@ -1,5 +1,5 @@ import { killAllProcessesForWorktree, type WorktreeTeardownRuntime } from './worktree-teardown' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { teardownStops } from './owned-session-teardown-policy' export type FolderWorkspacePtyTeardownDeps = { diff --git a/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.test.ts b/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.test.ts deleted file mode 100644 index f75ba99cb50..00000000000 --- a/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import type { Repo } from '../../../../shared/repo-types' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { stopMissingWorktreeTerminals } from './missing-worktree-terminal-reconciliation' -import { createAdapter } from '../../../daemon/providers/routing/testing/daemon-pty-router-test-fixture' -import { DaemonPtyRouter } from '../../../daemon/providers/routing/daemon-pty-router' - -function createProvider(sessionIds: string[]): IPtyProvider { - return { - listProcesses: vi.fn(async () => - sessionIds.map((id) => ({ id, cwd: '/workspace', title: 'shell' })) - ), - shutdown: vi.fn(async () => {}) - } as unknown as IPtyProvider -} - -function createRuntime(): OrcaRuntimeService { - return { - stopTerminalsForWorktree: vi.fn(async () => ({ stopped: 0 })) - } as unknown as OrcaRuntimeService -} - -const localRepo: Repo = { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'Repo', - badgeColor: '#000', - addedAt: 1 -} - -describe('stopMissingWorktreeTerminals', () => { - it('stops only locally owned worktrees absent from the authoritative scan', async () => { - const deletedId = 'repo-1::/workspace/deleted' - const survivingId = 'repo-1::/workspace/surviving' - const provider = createProvider([ - `${deletedId}@@deleted-session`, - `${survivingId}@@surviving-session` - ]) - const runtime = createRuntime() - - const result = await stopMissingWorktreeTerminals( - localRepo, - [deletedId, survivingId, 'repo-2::/workspace/other'], - [survivingId], - { - runtime, - getLocalProvider: () => provider - } - ) - - expect(result).toEqual({ stoppedWorktreeIds: [deletedId] }) - expect(provider.shutdown).toHaveBeenCalledWith( - `${deletedId}@@deleted-session`, - expect.objectContaining({ immediate: true }) - ) - expect(provider.shutdown).not.toHaveBeenCalledWith( - `${survivingId}@@surviving-session`, - expect.anything() - ) - }) - - it.each([ - ['legacy connectionId', { connectionId: 'ssh-1' }], - ['unified executionHostId', { executionHostId: 'ssh:ssh-1' as const }] - ])('never sweeps an SSH repo (%s) through the local provider', async (_, host) => { - const deletedId = 'repo-1::/workspace/deleted' - const localProvider = createProvider([`${deletedId}@@local-session`]) - const runtime = createRuntime() - - await stopMissingWorktreeTerminals({ ...localRepo, ...host }, [deletedId], [], { - runtime, - getLocalProvider: () => localProvider - }) - - expect(runtime.stopTerminalsForWorktree).toHaveBeenCalledWith(deletedId, { - resolvedWorktreeId: deletedId, - resolvedConnectionId: 'ssh-1' - }) - expect(localProvider.listProcesses).not.toHaveBeenCalled() - expect(localProvider.shutdown).not.toHaveBeenCalled() - }) - - it.each([false, true])( - 'stops multiple workspaces through scoped daemon listings (unrelated duplicate: %s)', - async (duplicate) => { - const ids = ['repo-1::/workspace/a', 'repo-1::/workspace/b'] - const targetSessions = ids.map((id) => `${id}@@session`) - const currentSessions = [...targetSessions, ...(duplicate ? ['unrelated'] : [])] - const current = createAdapter('current', currentSessions) - const legacy = createAdapter('legacy', duplicate ? ['unrelated'] : []) - const provider = new DaemonPtyRouter({ current, legacy: [legacy] }) - - await expect( - stopMissingWorktreeTerminals(localRepo, ids, [], { - runtime: createRuntime(), - getLocalProvider: () => provider - }) - ).resolves.toEqual({ stoppedWorktreeIds: ids }) - - expect(currentSessions).toEqual(duplicate ? ['unrelated'] : []) - expect( - vi - .mocked(current.shutdown) - .mock.calls.map(([id]) => id) - .sort() - ).toEqual(targetSessions) - expect(legacy.shutdown).not.toHaveBeenCalled() - if (!duplicate) { - expect(current.listProcesses).toHaveBeenCalledOnce() - } - } - ) - - it('does not reuse a failed process scan', async () => { - const ids = ['repo-1::/workspace/a', 'repo-1::/workspace/b'] - const listProcesses = vi - .fn() - .mockRejectedValueOnce(new Error('relay dropped')) - .mockResolvedValue([{ id: `${ids[1]}@@session`, cwd: '/workspace', title: 'shell' }]) - const provider = { listProcesses, shutdown: vi.fn(async () => {}) } as unknown as IPtyProvider - - await stopMissingWorktreeTerminals(localRepo, ids, [], { - runtime: createRuntime(), - getLocalProvider: () => provider - }) - - expect(listProcesses.mock.calls.length).toBeGreaterThan(1) - expect(provider.shutdown).toHaveBeenCalledWith( - `${ids[1]}@@session`, - expect.objectContaining({ immediate: true }) - ) - }) -}) diff --git a/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.ts b/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.ts index 5f208d5520e..e9c3b34475c 100644 --- a/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.ts +++ b/src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.ts @@ -1,5 +1,5 @@ import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { Repo } from '../../../../shared/repo-types' import { splitWorktreeId } from '../../../../shared/worktree/id' import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' diff --git a/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts b/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts index c6bef70cad1..a249cee2918 100644 --- a/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts +++ b/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts @@ -149,9 +149,6 @@ async function deleteRow(purged: string[], stopPtys = vi.fn(async () => {})): Pr return error } -const refusal = (): string => - `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` - /** A delete a quit interrupted, finished at the next start, where Git fails on the locked file. */ function failStartupFinish(): Promise { return finishAtStartup([]) @@ -282,7 +279,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part const purged: string[] = [] const stopPtys = vi.fn(async () => {}) - expect(String(await deleteRow(purged, stopPtys))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged, stopPtys)).toBeInstanceOf(Error) expect(existsSync(lockedFile)).toBe(true) expect(stopPtys).not.toHaveBeenCalled() expect(purged).toEqual([]) @@ -309,7 +306,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') const purged: string[] = [] - expect(String(await deleteRow(purged))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged)).toBeInstanceOf(Error) expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') expect(removeHostTree).not.toHaveBeenCalled() @@ -405,7 +402,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part const retried = retryFailedWorktreeRemoval(worktreeId, 'local', (record) => interruptedLocalWorktreeRemovalJob(record, jobHost(purged)) ) - await expect(retried).rejects.toThrow(refusal()) + await expect(retried).rejects.toThrow(/folder was left on disk/) await _settlePendingWorktreeRemovalsForTests() expect(existsSync(join(worktreePath, 'unsaved.txt'))).toBe(true) @@ -481,7 +478,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') }) - expect(String(await deleteRow(purged, stopPtys))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged, stopPtys)).toBeInstanceOf(Error) expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') expect(removeHostTree).not.toHaveBeenCalled() @@ -493,7 +490,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part await rm(join(worktreePath, '.git')) const purged: string[] = [] - expect(String(await finishAtStartup(purged))).toBe(`Error: ${refusal()}`) + expect(await finishAtStartup(purged)).toBeInstanceOf(Error) expect(existsSync(join(worktreePath, '.git'))).toBe(false) expect(existsSync(lockedFile)).toBe(true) @@ -501,9 +498,9 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part expect(await isRegistered(worktreePath)).toBe(false) expect(await git(['branch', '--list', 'feature'])).toBe('') expect(purged).toEqual([]) - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: refusal() }]) + expect(await listedRows()).toEqual([{ path: worktreePath, removalError: expect.any(String) }]) - expect(String(await deleteRow(purged))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged)).toBeInstanceOf(Error) expect(existsSync(lockedFile)).toBe(true) await rm(worktreePath, { recursive: true }) diff --git a/src/main/runtime/workspaces/removal/runtime-interrupted-local-worktree-removal.test.ts b/src/main/runtime/workspaces/removal/runtime-interrupted-local-worktree-removal.test.ts index b9c69a6d3d5..d684f5ddb61 100644 --- a/src/main/runtime/workspaces/removal/runtime-interrupted-local-worktree-removal.test.ts +++ b/src/main/runtime/workspaces/removal/runtime-interrupted-local-worktree-removal.test.ts @@ -1,37 +1,25 @@ +import type { Repo } from '../../../../shared/repo-types' +import type { GitPushTarget } from '../../../../shared/worktree/types' +import type { WorktreeRemovalRecord } from '../../../workspaces/removal/worktree-removal-records' import { installRealWorkerThreadChildProcesses } from '../../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' -// Use real Git/disk evidence to finish interrupted removal regardless of how far the earlier run progressed. import { execFile } from 'node:child_process' import { existsSync } from 'node:fs' -import { mkdir, mkdtemp, readFile, realpath, rename, unlink, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, realpath, unlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitPushTarget } from '../../../../shared/worktree/types' -import type { Repo } from '../../../../shared/repo-types' + import { getDefaultSettings } from '../../../../shared/constants' import { getProjectHostSetupWorktreeMeta } from '../../../../shared/project-host-setup-lookup' -import { buildDetectedGitWorktrees } from '../../../ipc/worktrees/listing/ssh-worktree-fallback' + import { removeTree } from '../../../../shared/windows-transient-lock-removal' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' import type { Store } from '../../../persistence/loading-store/store' import type * as HostTreeRemoval from '../../../filesystem/host-tree-removal' import { removeHostTree } from '../../../filesystem/host-tree-removal' -import * as nativeFs from '../../../filesystem/asar-transparent-fs' -import * as diskFs from 'node:fs/promises' -import * as nativeRemoval from '../../../git/worktrees/removal/windows-worktree-removal' -import * as graphReader from '../../../git/worktrees/catalog/worktree-list-reader' -import { cleanupLocalOrphanedWorktreeDirectory } from '../../../workspaces/removal/local-orphaned-worktree-cleanup' -import * as removalOwnership from '../../../ipc/worktrees/removal/worktree-removal-ownership' -import { executeWorktreeRemoval } from '../../../ipc/worktrees/removal/execute-worktree-removal' -import { RuntimeWorktreeRemovalInFlight } from './runtime-worktree-removal-in-flight' -import { OrcaRuntimeWithResolveWorktreeRemovalTarget } from '../workspace-removal-target' -import type { WorktreeIpcContext } from '../../../ipc/worktrees/worktree-ipc-context' -import * as backgroundRemoval from '../../../workspaces/removal/worktree-background-removal' -import * as worktreeGit from '../../../git/worktrees/catalog/worktree-listing' -import * as worktreeRemote from '../../../ipc/worktree-remote' + import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -import * as removalTable from '../../../workspaces/removal/worktree-removal-table' import { listWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' import { areWorktreePathsEqual } from '../../../git/worktrees/catalog/worktree-path-comparison' import { @@ -46,19 +34,13 @@ import { resumeInterruptedWorktreeRemovals, waitForPendingWorktreeRemoval } from '../../../workspaces/removal/worktree-background-removal' -import { withUnregisteredRemovalCheckouts } from '../../../workspaces/removal/worktree-removal-listing' + import { readWorktreeRemovalRecords, - writeWorktreeRemovalRecords, - type WorktreeRemovalRecord + writeWorktreeRemovalRecords } from '../../../workspaces/removal/worktree-removal-records' -import { queueWorkspaceDelete } from '../lifecycle/workspace-lifecycle-commands' -import { WorkspaceLifecycleQueue } from '../lifecycle/workspace-lifecycle-queue' -import { interruptedLocalWorktreeRemovalJob } from './runtime-interrupted-local-worktree-removal' -vi.mock('node:fs/promises', async (importOriginal) => { - return { ...(await importOriginal()) } -}) +import { interruptedLocalWorktreeRemovalJob } from './runtime-interrupted-local-worktree-removal' vi.mock('../../../workspaces/execution-host/project-runtime-git-options', () => ({ getLocalProjectWorktreeGitOptions: vi.fn(() => ({})) @@ -68,11 +50,6 @@ vi.mock('../../../filesystem/host-tree-removal', async (importOriginal) => { return { ...actual, removeHostTree: vi.fn(actual.removeHostTree) } }) -vi.mock('../../../ipc/worktrees/removal/worktree-removal-ownership', () => ({ - stopPtysForDestructiveWorktreeRemoval: vi.fn(async () => {}), - removeWorktreeMetadataAndTransientState: vi.fn() -})) - const execFileAsync = promisify(execFile) let scratchDir = '' @@ -81,7 +58,6 @@ let repoPath = '' let worktreePath = '' let repo: Repo let pushTarget: GitPushTarget | undefined -let lifecycle: WorkspaceLifecycleQueue async function git(args: string[], cwd = repoPath): Promise { const { stdout } = await execFileAsync('git', args, { cwd }) @@ -97,7 +73,6 @@ async function isRegistered(path: string): Promise { beforeEach(async () => { pushTarget = undefined - lifecycle = new WorkspaceLifecycleQueue() vi.mocked(getLocalProjectWorktreeGitOptions).mockReturnValue({}) // realpath: macOS hands out /var/... temp paths while Git reports /private/var/.... scratchDir = await realpath(await mkdtemp(join(tmpdir(), 'orca-interrupted-removal-'))) @@ -120,7 +95,6 @@ afterEach(async () => { _resetPendingWorktreeRemovalsForTests() vi.restoreAllMocks() vi.mocked(removeHostTree).mockClear() - vi.mocked(removalOwnership.stopPtysForDestructiveWorktreeRemoval).mockReset() await removeTree(scratchDir) }) @@ -185,14 +159,6 @@ async function finishAfterRestart( return { outcome, purged, remember, records } } -/** The non-main rows a listing shows, with any failed delete's error. */ -async function listedRows(): Promise<{ path: string; removalError?: string }[]> { - const rows = await withUnregisteredRemovalCheckouts(repo.id, await listWorktreesStrict(repoPath)) - return buildDetectedGitWorktrees(removalHost().store, repo, rows) - .filter((row) => row.visible && !row.isMainWorktree) - .map(({ path, removalError }) => ({ path, ...(removalError ? { removalError } : {}) })) -} - function removalHost( repoGone = false, stopPtys = async () => {}, @@ -230,343 +196,7 @@ function removalHost( } } -const deletionOperations = () => - (['rm', 'unlink', 'rmdir'] as const).map((operation) => vi.spyOn(nativeFs, operation)) - -function expectNoTeardownOrDeletion( - ...callbacks: (ReturnType | ReturnType[number])[] -): void { - callbacks.forEach((callback) => expect(callback).not.toHaveBeenCalled()) -} - -type RemovalEntry = 'desktop' | 'runtime' - -async function deleteViaEntry( - entry: RemovalEntry, - force: boolean, - stop = async () => {}, - teardown = vi.fn(), - deleteBranch?: boolean -): Promise { - const worktreeId = `repo-1::${worktreePath}` - const host = removalHost(false, stop, teardown) - const { store } = host - const runtime: OrcaRuntimeWithResolveWorktreeRemovalTarget = Object.assign( - Object.create(OrcaRuntimeWithResolveWorktreeRemovalTarget.prototype), - { - store, - workspaceLifecycle: lifecycle, - listRepos: store.getRepos, - listTerminals: async () => ({ totalCount: 0 }), - requireStore: () => store, - resolveWorktreeRemovalTarget: async () => ({ - id: worktreeId, - repoId: repo.id, - path: worktreePath - }), - removeManagedWorktreeInFlight: new RuntimeWorktreeRemovalInFlight(), - localRemovalJobHost: () => host, - acquireFileWatcherRemoval: host.acquireWatcherRemoval, - stopPtysForDestructiveWorktreeRemoval: stop, - closeFileWatchersForRemoval: host.closeWatchers, - preservedBranchCleanup: { ...host.preservedBranchCleanup, delete: vi.fn() }, - purgeRemovedWorktree: host.purge, - clearOptimisticReconcileToken: () => {}, - publishWorktreeRemovalChange: () => {}, - notifyWorktreesChanged: () => {}, - emitWorktreeLifecycle: () => {} - } - ) - vi.mocked(removalOwnership.stopPtysForDestructiveWorktreeRemoval).mockImplementation(stop) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: native dispatch reads only the fixture-owned context fields below. - const context = { - store, - runtime, - mainWindow: { isDestroyed: () => true } - } as unknown as WorktreeIpcContext - try { - const accepted = - entry === 'desktop' - ? await executeWorktreeRemoval( - context, - { worktreeId, force }, - repo, - repo.id, - worktreePath, - 'local' - ) - : await queueWorkspaceDelete( - runtime, - `id:${worktreeId}`, - 'local', - { force, deleteBranch }, - (removal) => - runtime.removeManagedWorktree(`id:${worktreeId}`, { - ...removal, - waitForBackgroundRemoval: true - }) - ) - return await backgroundRemoval.finishAcceptedWorktreeRemoval(accepted, worktreeId) - } finally { - await _settlePendingWorktreeRemovalsForTests() - } -} - -async function orphanAdmin(): Promise { - const admin = (await readFile(join(worktreePath, '.git'), 'utf8')).trim().replace(/^gitdir: /, '') - await removeTree(admin) - await unlink(join(worktreePath, '.git')) - await writeFile(join(worktreePath, '.git'), ` gitdir: ${admin}\nignored second line\n`) -} - -async function recordFailedRemoval(force: boolean, deleteBranch = true): Promise { - await writeWorktreeRemovalRecords(recordsDir, () => [ - { - worktreeId: `repo-1::${worktreePath}`, - repoId: repo.id, - repoPath, - worktreePath, - branch: 'feature', - head: '', - deleteBranch, - force, - requestedAt: 1, - failure: { message: 'held file', failedAt: 2 } - } - ]) - await loadWorktreeRemovalRecords(recordsDir) -} - describe('finishing an interrupted worktree removal after a restart', () => { - it('refuses an unknown owner through both entries, admission, cleanup and failed listing', async () => { - await orphanAdmin() - const movedOwner = join(scratchDir, 'ENOENT') - await rename(repoPath, movedOwner) - repoPath = movedOwner - repo.path = repoPath - await writeFile(join(repoPath, 'HEAD'), 'ref: refs/heads/main\n') - await writeFile( - join(worktreePath, '.git'), - `gitdir: ${join(repoPath, 'worktrees', 'feature')}\n` - ) - // Successful graph seams isolate proof propagation, not a live permission exploit. - vi.spyOn(worktreeGit, 'listWorktreesStrict').mockResolvedValue([]) - vi.spyOn(graphReader, 'readTranslatedWorktreeGraph').mockResolvedValue([]) - const stat = diskFs.stat - vi.spyOn(diskFs, 'stat').mockImplementation(async (path, options) => { - if (String(path) === join(repoPath, '.git')) { - throw Object.assign(new Error(`EACCES: permission denied, stat '${String(path)}'`), { - code: 'EACCES' - }) - } - return stat(path, options) - }) - const stop = vi.fn(async () => {}) - const teardown = vi.fn() - const operations = deletionOperations() - await expect( - nativeRemoval.removeWindowsCheckout(repoPath, worktreePath, true, {}) - ).rejects.toThrow('Refusing to delete unregistered worktree path') - // Reach both nonnative unregistered consumers after independently checking native admission. - vi.spyOn(nativeRemoval, 'usesNativeWindowsRemoval').mockReturnValue(false) - const metadata = vi.mocked(removalOwnership.removeWorktreeMetadataAndTransientState) - metadata.mockClear() - const pushCleanup = vi.spyOn(worktreeRemote, 'cleanupUnusedWorktreePushTargetRemote') - for (const entry of ['desktop', 'runtime'] as const) { - await expect(deleteViaEntry(entry, true, stop, teardown)).rejects.toThrow( - 'Refusing to delete unregistered worktree path' - ) - } - await expect( - cleanupLocalOrphanedWorktreeDirectory(repoPath, worktreePath, {}, stop) - ).rejects.toThrow('Worktree is no longer registered with Git but its directory remains.') - expectNoTeardownOrDeletion(stop, teardown, ...operations) - expect(removeHostTree).not.toHaveBeenCalled() - expect(metadata).not.toHaveBeenCalled() - expect(pushCleanup).not.toHaveBeenCalled() - expect(await readFile(join(worktreePath, 'seed.txt'), 'utf8')).toBe('seed\n') - await recordFailedRemoval(true) - expect(await readWorktreeRemovalRecords(recordsDir)).toMatchObject([ - { worktreePath, failure: { message: 'held file' } } - ]) - expect(await listedRows()).toEqual([]) - await vi.waitFor(async () => expect(await readWorktreeRemovalRecords(recordsDir)).toEqual([])) - expect(await readFile(join(worktreePath, 'seed.txt'), 'utf8')).toBe('seed\n') - }) - - it.skipIf(process.platform !== 'win32').each([ - { entry: 'desktop', phase: 'child' }, - { entry: 'runtime', phase: 'child' }, - { entry: 'desktop', phase: 'root' }, - { entry: 'runtime', phase: 'root' } - ] as const)( - '$entry completes explicit retry after releasing held $phase across restart', - async ({ entry, phase }) => { - const remoteUrl = 'https://example.invalid/repo.git' - pushTarget = { - remoteName: 'pr-contributor', - branchName: 'feature', - remoteCreated: true, - remoteUrl - } - await git(['remote', 'add', pushTarget.remoteName, remoteUrl]) - await git(['config', `remote.${pushTarget.remoteName}.orca-created`, 'true']) - const sibling = join(scratchDir, 'temporarily-missing') - await git(['worktree', 'add', '-q', sibling, '-b', 'sibling']) - await rename(sibling, join(scratchDir, 'offline')) - const path = phase === 'child' ? join(worktreePath, 'seed.txt') : worktreePath - const locked = Object.assign(new Error('held path'), { code: 'EBUSY', path }) - const held = vi.spyOn(nativeFs, phase === 'child' ? 'rm' : 'rmdir').mockRejectedValue(locked) - const { outcome, records } = await finishAfterRestart({ force: true }) - const message = `${path} is open in another program. Close that program and delete again.` - expect(outcome.status).toBe('failed') - expect(records).toMatchObject([{ failure: { message } }]) - if (phase === 'root') { - expect((await listWorktreesStrict(repoPath)).filter((row) => row.prunable)).toHaveLength(2) - } - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: message }]) - expect(await git(['remote'])).toContain(pushTarget.remoteName) - expect(await isRegistered(worktreePath)).toBe(true) - expect(await git(['branch', '--list', 'feature'])).not.toBe('') - _resetPendingWorktreeRemovalsForTests() - await loadWorktreeRemovalRecords(recordsDir) - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: message }]) - const resume = vi.fn() - resumeInterruptedWorktreeRemovals(resume) - expect(resume).not.toHaveBeenCalled() - await expect(deleteViaEntry(entry, true)).rejects.toThrow() - expect(await isRegistered(worktreePath)).toBe(true) - held.mockRestore() - await deleteViaEntry(entry, true) - expect(existsSync(worktreePath)).toBe(false) - expect(await isRegistered(worktreePath)).toBe(false) - expect(await git(['branch', '--list', 'feature'])).toBe('') - expect(await git(['remote'])).not.toContain(pushTarget.remoteName) - expect(await isRegistered(sibling)).toBe(true) - expect(await readWorktreeRemovalRecords(recordsDir)).toEqual([]) - }, - 60_000 - ) - - it - .skipIf(process.platform !== 'win32') - .each( - (['desktop', 'runtime'] as const).flatMap((entry) => - ['native', 'wsl'].map((route) => ({ entry, route })) - ) - )( - '$entry refuses $route before publication/teardown and honors current native force', - async ({ entry, route }) => { - const seed = await readFile(join(worktreePath, 'seed.txt')) - await orphanAdmin() - if (route === 'wsl') { - await unlink(join(worktreePath, '.git')) - vi.mocked(getLocalProjectWorktreeGitOptions).mockReturnValue({ wslDistro: 'Ubuntu' }) - // A route-list seam, not a distro run: the request must refuse before invoking a job. - vi.spyOn(worktreeGit, 'listWorktreesStrict').mockResolvedValue([]) - } - const retryJob = vi.spyOn(backgroundRemoval, 'retryFailedWorktreeRemoval') - const pushCleanup = vi.spyOn(worktreeRemote, 'cleanupUnusedWorktreePushTargetRemote') - await recordFailedRemoval(true) - const stop = vi.fn(async () => {}) - const teardown = vi.fn() - const operations = deletionOperations() - for (let attempt = 0; attempt < 2; attempt += 1) { - await expect(deleteViaEntry(entry, false, stop, teardown)).rejects.toThrow( - /no longer (?:registered|a Git worktree)/ - ) - expect(retryJob).not.toHaveBeenCalled() - expect(pushCleanup).not.toHaveBeenCalled() - expectNoTeardownOrDeletion(stop, teardown, ...operations) - expect(await readFile(join(worktreePath, 'seed.txt'))).toEqual(seed) - expect(await readWorktreeRemovalRecords(recordsDir)).toMatchObject([ - { force: true, failure: { message: 'held file' } } - ]) - _resetPendingWorktreeRemovalsForTests() - await loadWorktreeRemovalRecords(recordsDir) - } - if (route === 'wsl') { - return - } - const sibling = join(scratchDir, 'temporarily-missing') - await git(['worktree', 'add', '-q', sibling, '-b', 'sibling']) - await rename(sibling, join(scratchDir, 'offline')) - await recordFailedRemoval(false) - const started = Promise.withResolvers() - const paused = Promise.withResolvers() - const retry = deleteViaEntry(entry, true, async () => { - started.resolve() - await paused.promise - }).catch((error: unknown) => error) - try { - await started.promise - expect([...removalTable.pendingWorktreeRemovals.values()]).toMatchObject([ - { force: true, branch: 'feature', deleteBranch: true } - ]) - expect(await readWorktreeRemovalRecords(recordsDir)).toMatchObject([{ force: true }]) - } finally { - paused.resolve() - } - expect(await retry).not.toBeInstanceOf(Error) - expect(await isRegistered(worktreePath)).toBe(false) - expect(await isRegistered(sibling)).toBe(true) - expect(await git(['branch', '--list', 'feature'])).toBe('') - await git(['worktree', 'add', '-q', worktreePath, '-b', 'feature']) - await removeTree(worktreePath) - expect(await isRegistered(worktreePath)).toBe(true) - await deleteViaEntry(entry, true) - expect(await isRegistered(worktreePath)).toBe(false) - expect(await isRegistered(sibling)).toBe(true) - expect(await git(['branch', '--list', 'feature'])).toBe('') - } - ) - - it.skipIf(process.platform !== 'win32').each( - (['desktop', 'runtime'] as const).flatMap((entry) => - ['attached', 'detached', 'folder', 'nested'].map((schedule) => ({ - entry, - schedule - })) - ) - )( - '$entry preserves $schedule replacements before/after teardown', - async ({ entry, schedule }) => { - await orphanAdmin() - await loadWorktreeRemovalRecords(recordsDir) - const change = async () => { - if (schedule === 'nested') { - await git(['worktree', 'add', '-q', join(worktreePath, 'nested'), '-b', 'nested']) - } else { - await rename(worktreePath, join(scratchDir, 'original')) - await (schedule === 'folder' - ? mkdir(worktreePath) - : git([ - 'worktree', - 'add', - '-q', - ...(schedule === 'detached' ? ['--detach'] : ['-b', 'other']), - worktreePath - ])) - } - await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') - } - const stop = vi.fn(change) - const teardown = vi.fn() - await expect(deleteViaEntry(entry, true, stop, teardown)).rejects.toThrow() - expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') - expect(stop).toHaveBeenCalledOnce() - // A second ordinary Delete refuses proofless/nested contents before teardown. - if (['folder', 'nested'].includes(schedule)) { - stop.mockClear() - teardown.mockClear() - const operations = deletionOperations() - await expect(deleteViaEntry(entry, true, stop, teardown)).rejects.toThrow() - expectNoTeardownOrDeletion(stop, teardown, ...operations) - expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') - } - } - ) - it.each(['partial', 'detached', 'keep-registered', 'keep-unregistered'])( 'finishes the accepted %s pending checkout after restart', async (kind) => { @@ -601,156 +231,6 @@ describe('finishing an interrupted worktree removal after a restart', () => { } ) - it.each([false, undefined])( - 'settles persisted failed keep through lifecycle retry, intent=%s', - async (intent) => { - const head = (await git(['rev-parse', 'feature'])).trim() - await git(['worktree', 'remove', worktreePath]) - await mkdir(worktreePath) - await writeFile(join(worktreePath, 'leftover'), 'held') - await recordFailedRemoval(false, false) - const id = `repo-1::${worktreePath}` - const record = removalTable.failedWorktreeRemovals.get(id) - expect(record).toMatchObject({ deleteBranch: false, failure: { message: 'held file' } }) - await expect(deleteViaEntry('runtime', false, undefined, undefined, intent)).rejects.toThrow( - 'folder was left on disk' - ) - expect(removalTable.failedWorktreeRemovals.get(id)).toBe(record) - expect(lifecycle.hints()).toEqual({}) - // Removing only this fixture's leftover is the legitimate external wake for retry. - await removeTree(worktreePath) - await expect(deleteViaEntry('runtime', false, undefined, undefined, true)).rejects.toThrow( - 'different branch choice' - ) - expect(removalTable.failedWorktreeRemovals.get(id)).toBe(record) - expect(lifecycle.hints()).toEqual({}) - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - const stopPtys = async () => { - entered.resolve() - await release.promise - } - const retry = deleteViaEntry('runtime', false, stopPtys, undefined, intent) - try { - await entered.promise - expect(removalTable.pendingWorktreeRemovals.get(id)).toMatchObject({ deleteBranch: false }) - expect(removalTable.failedWorktreeRemovals.has(id)).toBe(false) - } finally { - release.resolve() - } - const result = await retry - expect(result).not.toHaveProperty('preservedBranch') - expect((await git(['rev-parse', 'feature'])).trim()).toBe(head) - expect(await isRegistered(worktreePath)).toBe(false) - expect(existsSync(worktreePath)).toBe(false) - expect(waitForPendingWorktreeRemoval(id)).toBeUndefined() - expect(removalTable.failedWorktreeRemovals.has(id)).toBe(false) - expect(await readWorktreeRemovalRecords(recordsDir)).toEqual([]) - expect(lifecycle.hints()).toEqual({}) - } - ) - - it('keeps the user’s non-forced choice: Git refuses local changes and the row returns as before', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') - - const { outcome, purged, records } = await finishAfterRestart({ force: false }) - - expect(outcome).toMatchObject({ status: 'failed' }) - expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') - expect(existsSync(join(worktreePath, 'seed.txt'))).toBe(true) - expect(await isRegistered(worktreePath)).toBe(true) - expect(await git(['branch', '--list', 'feature'])).not.toBe('') - expect(purged).toEqual([]) - expect(records).toMatchObject([{ failure: { message: expect.any(String) } }]) - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: expect.any(String) }]) - }) - - it.each([true, false])( - 'preserves a nonempty markerless checkout and platform cleanup policy (force %s)', - async (force) => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const admin = (await readFile(join(worktreePath, '.git'), 'utf8')).trim().slice(8) - const backlink = await readFile(join(admin, 'gitdir'), 'utf8') - const branchHead = await git(['rev-parse', 'feature']) - // Git deletes in directory order; without `.git` no `worktree remove` can validate it. - await unlink(join(worktreePath, '.git')) - - const { outcome, purged, records } = await finishAfterRestart({ force }) - - const refusal = `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` - expect(outcome).toEqual({ status: 'failed', error: `Error: ${refusal}` }) - const native = process.platform === 'win32' - if (native && force) { - await expect(deleteViaEntry('runtime', force)).rejects.toThrow(refusal) - await removalTable.persistWorktreeRemovalRecords() - expect(await readWorktreeRemovalRecords(recordsDir)).toEqual(records) - expect(await readFile(join(admin, 'gitdir'), 'utf8')).toBe(backlink) - expect(await git(['rev-parse', 'feature'])).toBe(branchHead) - } - expect(existsSync(join(worktreePath, '.git'))).toBe(false) - expect(await readFile(join(worktreePath, 'seed.txt'), 'utf8')).toBe('seed\n') - expect(removeHostTree).not.toHaveBeenCalled() - expect(await isRegistered(worktreePath)).toBe(native) - expect((await git(['branch', '--list', 'feature'])).trim() !== '').toBe(native) - expect(purged).toEqual([]) - expect(records).toMatchObject([{ failure: { message: refusal } }]) - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: refusal }]) - } - ) - - it('deletes nothing in a folder put at the path after Git unregistered the checkout', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await git(['worktree', 'remove', worktreePath]) - await mkdir(worktreePath, { recursive: true }) - await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') - - const { outcome, purged, records } = await finishAfterRestart({ force: true }) - - const refusal = `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` - expect(outcome).toEqual({ status: 'failed', error: `Error: ${refusal}` }) - expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') - expect(removeHostTree).not.toHaveBeenCalled() - // Git let go of the checkout, so the recorded branch delete runs (merged only); no files. - expect(await git(['branch', '--list', 'feature'])).toBe('') - expect(purged).toEqual([]) - expect(records).toMatchObject([{ failure: { message: refusal } }]) - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: refusal }]) - }) - - it('leaves a different checkout created at the same path since the quit', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const head = (await git(['rev-parse', 'feature'])).trim() - await git(['worktree', 'remove', worktreePath]) - await git(['worktree', 'add', '-q', worktreePath, '-b', 'other']) - await writeFile(join(worktreePath, 'unsaved.txt'), 'work\n') - - const { outcome, purged, records } = await finishAfterRestart({ head, force: true }) - - expect(outcome).toMatchObject({ status: 'failed' }) - expect(records).toEqual([]) - expect(existsSync(join(worktreePath, 'unsaved.txt'))).toBe(true) - expect(await isRegistered(worktreePath)).toBe(true) - expect(purged).toEqual([]) - }) - - it('leaves a repository created at the path after Git unregistered the checkout', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await git(['worktree', 'remove', worktreePath]) - await mkdir(worktreePath, { recursive: true }) - await git(['init', '-q'], worktreePath) - await writeFile(join(worktreePath, 'unsaved.txt'), 'work\n') - - const { outcome, purged, records } = await finishAfterRestart({ force: true }) - - expect(outcome).toMatchObject({ status: 'failed' }) - // Not the removed checkout's leftover, so no row either, as a listing would decide. - expect(records).toEqual([]) - expect(existsSync(join(worktreePath, 'unsaved.txt'))).toBe(true) - expect(removeHostTree).not.toHaveBeenCalled() - expect(purged).toEqual([]) - }) - it('leaves the same branch checked out again at a new head', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) const head = (await git(['rev-parse', 'feature'])).trim() @@ -767,56 +247,6 @@ describe('finishing an interrupted worktree removal after a restart', () => { expect(existsSync(join(worktreePath, 'work.txt'))).toBe(true) expect(purged).toEqual([]) }) - - it('leaves a locked checkout alone even when its .git file is gone', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await git(['worktree', 'lock', worktreePath]) - await unlink(join(worktreePath, '.git')) - - const { outcome, purged, records } = await finishAfterRestart({ force: true }) - - expect(outcome).toMatchObject({ status: 'failed', error: expect.stringMatching(/locked/) }) - expect(existsSync(join(worktreePath, 'seed.txt'))).toBe(true) - // Not pruned either: the lock keeps Git's registration. - expect(await isRegistered(worktreePath)).toBe(true) - expect(purged).toEqual([]) - expect(records).toMatchObject([{ failure: { message: expect.any(String) } }]) - }) - - it('keeps an unmerged branch, as a normal removal does', async () => { - await writeFile(join(worktreePath, 'work.txt'), 'work\n') - await git(['add', '-A'], worktreePath) - await git(['commit', '-qm', 'work'], worktreePath) - const head = (await git(['rev-parse', 'feature'])).trim() - await git(['worktree', 'remove', worktreePath]) - - const { outcome, remember, records } = await finishAfterRestart() - - expect(records).toEqual([]) - expect(outcome).toMatchObject({ - status: 'removed', - preservedBranch: { branchName: 'feature', head } - }) - expect((await git(['rev-parse', 'feature'])).trim()).toBe(head) - expect(remember).toHaveBeenCalledWith( - `repo-1::${worktreePath}`, - undefined, - { preservedBranch: { branchName: 'feature', head } }, - head, - undefined - ) - }) - - it('drops a record whose repo Orca no longer has', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const { outcome, purged, records } = await finishAfterRestart({ repoGone: true }) - - expect(records).toEqual([]) - expect(outcome).toMatchObject({ status: 'removed' }) - expect(purged).toEqual([]) - expect(existsSync(worktreePath)).toBe(true) - }) }) installRealWorkerThreadChildProcesses() diff --git a/src/main/runtime/workspaces/removal/runtime-nested-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-nested-worktree-removal.ts index 333a21d3549..3452fb930c7 100644 --- a/src/main/runtime/workspaces/removal/runtime-nested-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-nested-worktree-removal.ts @@ -1,7 +1,7 @@ import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' -import type { NestedWorktreeRemovalApproval } from '../../../../shared/worktree/nested-removal' +import type { NestedWorktreeRemovalApproval } from '../../../../shared/worktree/removal/nested-removal' import { getRepoExecutionHostId, parseExecutionHostId, diff --git a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts index cb942c3efbb..8834b7664db 100644 --- a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts @@ -6,10 +6,10 @@ import { } from '../../../git/worktrees/removal/windows-worktree-removal' import { pruneGitWorktrees } from '../../../git/worktrees/removal/worktree-prune-guard' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' -import type { ArchiveHookOverride } from '../../../../shared/worktree/archive-hook-removal-gate' +import type { ArchiveHookOverride } from '../../../../shared/worktree/removal/archive-hook-removal-gate' import { gateWorktreeRemovalOnArchiveHook } from '../../../workspaces/removal/worktree-archive-hook-gate' import type { Repo } from '../../../../shared/repo-types' -import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal/removal' import type { LocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { assertWorktreeCleanForRemoval } from '../../../git/worktrees/removal/worktree-removal-preflight' import { listWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing' @@ -34,7 +34,8 @@ import type { RuntimeWorktreeRemovalTarget } from '../catalog/runtime-worktree-s import { removesInBackground, startBackgroundWorktreeRemoval, - waitForPendingWorktreeRemoval + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' import { runSerializedWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-removal-acceptance-queue' @@ -44,11 +45,14 @@ export function removeRuntimeRegisteredLocalWorktree( ): Promise { return runSerializedWorktreeRemovalAcceptance( args.repo.path, - async (): Promise => + async (): Promise => { // Recheck after queue wait: another client may already have accepted this deletion. - waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch) - ? { removing: true } - : acceptRuntimeRegisteredLocalWorktreeRemoval(args) + if (waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch)) { + await waitForWorktreeRemovalAcceptance(args.target.id) + return { removing: true } + } + return acceptRuntimeRegisteredLocalWorktreeRemoval(args) + } ) } @@ -70,6 +74,8 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { requestedDeleteBranch?: boolean acquireWatcherRemoval: (path: string) => Promise<{ finish: (removed: boolean) => Promise }> stopPtys: () => Promise + /** Runs after every refusal and the teardown, before any checkout file is deleted. */ + beforeCheckoutDelete?: (worktree: GitWorktreeInfo) => Promise closeWatchers: (path: string) => Promise preserveBranchHead: ( result: RemoveWorktreeResult | undefined, @@ -174,6 +180,7 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { let accepted = false try { await args.stopPtys() + await args.beforeCheckoutDelete?.(refreshed) if (!markerMissing && linkedPaths.length > 0) { await removeWorktreeLinkedPaths(canonicalPath, linkedPaths) } @@ -208,8 +215,10 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { return result }, publish: () => args.publish(), + admissionFailed: () => gate.finish(false), cleanupPushTargetRemote: () => cleanupRemovedWorktreePushTarget(args) }) + await waitForWorktreeRemovalAcceptance(args.target.id) return { removing: true, ...acceptedFields } } diff --git a/src/main/runtime/workspaces/removal/runtime-unregistered-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-unregistered-worktree-removal.ts index 194c85d5585..00296cb20f4 100644 --- a/src/main/runtime/workspaces/removal/runtime-unregistered-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-unregistered-worktree-removal.ts @@ -23,6 +23,7 @@ import { UNREGISTERED_MISSING_WORKTREE_MESSAGE } from '../../../workspaces/removal/worktree-removal-safety' import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' import type { RuntimeWorktreeRemovalTarget } from '../catalog/runtime-worktree-selection' import { isLocalRuntimeWorktreePathMissing } from '../catalog/runtime-worktree-filesystem' @@ -77,6 +78,12 @@ export async function removeRuntimeUnregisteredWorktree(args: { try { await cleanupPushTarget(args) } finally { + // Deleting an archived workspace forgets it; the purge keeps only rows still marked. + if (removedMeta?.archivedCheckout) { + args.store.setWorktreeMeta(hostWorktreeTarget({ id: target.id, hostId: route.hostId }), { + archivedCheckout: undefined + }) + } await args.finishRemoval() } } finally { diff --git a/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.test.ts b/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.test.ts index f03604f4958..5a275f0e3a2 100644 --- a/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.test.ts +++ b/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.test.ts @@ -1,8 +1,7 @@ import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import { ABANDONED_SWEEP_GRACE_MS } from './forced-sweep-settlement' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' const hostRef: { current: unknown } = { current: null } @@ -12,11 +11,7 @@ vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-r const { killAllProcessesForWorktree } = await import('./worktree-teardown') type TeardownRuntime = NonNullable[1]['runtime']> -const { - classifyWorktreeForceDeleteReason, - isProvenLiveStructuredSessionRemovalError, - isUnstoppedPtyRemovalError -} = await import('../../../../shared/worktree/removal') +await import('../../../../shared/worktree/removal/removal') await import('./structured-session-worktree-teardown') const WORKTREE = 'repo_1::/tmp/wt-a' @@ -173,248 +168,11 @@ function livePtyProvider(): IPtyProvider { }) } -/** The structured sweep's own warn — a forced removal can emit a PTY-sweep one onto the same spy. */ -function structuredSessionWarning(warn: { mock: { calls: unknown[][] } }): string { - return ( - warn.mock.calls - .map((call) => String(call[0])) - .find((message) => message.includes('agent session')) ?? '' - ) -} - describe('worktree teardown and structured agent sessions', () => { beforeEach(() => { hostRef.current = null }) - it('puts the chat tab back when the removal refuses over the session', async () => { - // A refused removal preserves the workspace and must restore its chat tabs. - const host = installHost({ - records: [record('s1', WORKTREE)], - stuck: new Set(['s1']), - visible: ['s1'] - }) - await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).rejects.toThrow( - /still live: 1 agent session \(claude\)/ - ) - expect([...host.visible]).toEqual(['s1']) - }) - - it('leaves the chat tab dropped when a forced removal deletes the workspace anyway', async () => { - // Force removes the workspace regardless of proof; restoring tabs would persist references to a deleted workspace. - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const host = installHost({ - records: [record('s1', WORKTREE)], - stuck: new Set(['s1']), - visible: ['s1'] - }) - await killAllProcessesForWorktree(WORKTREE, destructiveDeps({ allowUnverifiedStop: true })) - expect([...host.visible]).toEqual([]) - warn.mockRestore() - }) - - it('still removes under force when a close does not settle, and says so', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const retired: string[] = [] - installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']), visible: ['s1'] }) - const result = await killAllProcessesForWorktree(WORKTREE, { - ...destructiveDeps({ allowUnverifiedStop: true }), - runtime: runtimeDouble({ - retireStructuredAgentSessionTabFromSnapshot: (sessionId: string) => { - retired.push(sessionId) - return true - } - }) - }) - expect(result.structuredStopped).toBeUndefined() - // The live arm of that record, carrying the verdict the refusal would have shown. - expect(structuredSessionWarning(warn)).toContain('still live: 1 agent session (claude)') - expect(retired).toEqual(['s1']) - warn.mockRestore() - }) - - it('takes the proof when a failed close is re-observed as exited', async () => { - // Later exit evidence can prove a child gone after close threw or restored its tab. - const retired: string[] = [] - const runtime: TeardownRuntime = { - ...presentationRuntime(), - getPtyLivenessVerdict: () => null, - stopTerminalsForWorktree: async () => ({ stopped: 0 }), - retireStructuredAgentSessionTabFromSnapshot: (sessionId: string) => { - if (!retired.includes(sessionId)) { - retired.push(sessionId) - } - return true - } - } - installHost({ records: [record('s1', WORKTREE)], settledThenThrows: new Set(['s1']) }) - await expect( - killAllProcessesForWorktree(WORKTREE, { ...destructiveDeps(), runtime }) - ).resolves.toMatchObject({ structuredStopped: 1 }) - // Retired here because the close gave up before its own retirement step, and a chat tab left - // behind re-attaches a released session pointing at a workspace that is about to be deleted. - expect(retired).toEqual(['s1']) - }) - - it('leaves a same-id workspace on another execution host alone', async () => { - // A workspace id is `repoId::path` with no host component, so the local, SSH and paired-runtime - // copies of one id are DIFFERENT workspaces. Unfenced, deleting the local one closed a chat - // running on somebody else's machine — a destructive cross-host act, not a spurious refusal. - const host = installHost({ - records: [record('s1', WORKTREE, { executionHostId: 'ssh:host-a' })] - }) - await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).resolves.toMatchObject({ - runtimeStopped: 0 - }) - expect(host.closed).toEqual([]) - }) - - it('closes only the session on the host the removal resolved to', async () => { - const host = installHost({ - records: [record('s1', WORKTREE, { executionHostId: 'ssh:host-a' }), record('s2', WORKTREE)] - }) - await expect( - killAllProcessesForWorktree(WORKTREE, { - ...destructiveDeps(), - resolvedConnectionId: 'host-a' - }) - ).resolves.toMatchObject({ structuredStopped: 1 }) - expect(host.closed).toEqual(['s1']) - }) - - it('names the unconfirmed sessions too, instead of counting only the live ones', async () => { - // The PTY sibling may drop everything outside its live list because a fresh inventory PROVED - // those exited. Nothing proves that here: an `unverifiable` session is unclosed as well, so - // naming only the live subset told the user "1 agent session" while two were about to go. - installHost({ - records: [record('s1', WORKTREE), record('s2', WORKTREE, { provider: 'codex' })], - stuck: new Set(['s1']), - unverifiable: new Set(['s2']) - }) - const error = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( - (thrown: Error) => thrown.message - ) - expect(error).toContain( - 'still live: 1 agent session (claude); could not confirm these closed: 1 agent session (codex)' - ) - // The marker still leads, so the toast keeps showing the stronger of the two warnings. - expect(isProvenLiveStructuredSessionRemovalError(error as string)).toBe(true) - }) - - it('refuses in agent-session wording when the close outlives the sweep budget', async () => { - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - try { - // A structured timeout must not use the PTY sentinel or the desktop misclassifies the refusal (#11960). - installHost({ records: [record('s1', WORKTREE)], closeGate: new Promise(() => {}) }) - const outcome = killAllProcessesForWorktree( - WORKTREE, - destructiveDeps({ timeoutMs: 5 }) - ).catch((thrown: Error) => thrown.message) - await vi.advanceTimersByTimeAsync(5) - const error = await outcome - expect(error).toContain('could not confirm these closed: 1 agent session (claude)') - expect(isUnstoppedPtyRemovalError(error as string)).toBe(false) - expect(classifyWorktreeForceDeleteReason(error as string, true)).toBe('running-agent-session') - } finally { - vi.useRealTimers() - } - }) - - it('never wedges Force Delete on a close that will not settle', async () => { - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - installHost({ records: [record('s1', WORKTREE)], closeGate: new Promise(() => {}) }) - const outcome = killAllProcessesForWorktree( - WORKTREE, - destructiveDeps({ allowUnverifiedStop: true, timeoutMs: 5 }) - ) - void outcome.catch(() => undefined) - await vi.advanceTimersByTimeAsync(5 + ABANDONED_SWEEP_GRACE_MS) - await expect(outcome).resolves.toMatchObject({ runtimeStopped: 0 }) - const message = structuredSessionWarning(warn) - expect(message).toContain('could not confirm these closed: 1 agent session (claude)') - // Timeout proves no live child; forced-removal warnings must say unconfirmed. - expect(message).not.toContain('still attached') - } finally { - warn.mockRestore() - vi.useRealTimers() - } - }) - - it('stops issuing new closes once the budget is spent', async () => { - // Stop issuing closes at deadline; the uncancellable in-flight close and untouched tail both remain unverified. - let releaseFirstClose: () => void = () => {} - const firstClose = new Promise((resolve) => { - releaseFirstClose = resolve - }) - const host = installHost({ - records: [record('s1', WORKTREE), record('s2', WORKTREE)], - closeGates: { s1: firstClose } - }) - vi.useFakeTimers() - try { - const outcome = killAllProcessesForWorktree( - WORKTREE, - destructiveDeps({ timeoutMs: 5 }) - ).catch((thrown: Error) => thrown.message) - await vi.advanceTimersByTimeAsync(5) - expect(await outcome).toContain('could not confirm these closed: 2 agent sessions (claude)') - releaseFirstClose() - await vi.advanceTimersByTimeAsync(0) - expect(host.closed).toEqual(['s1']) - } finally { - vi.useRealTimers() - } - }) - - it('starts the terminal sweeps while the structured close is still in flight', async () => { - // Starting PTY sweeps after serial structured closes would spend their shared budget before they can attempt a stop. - let releaseClose: () => void = () => {} - const closeGate = new Promise((resolve) => { - releaseClose = resolve - }) - installHost({ records: [record('s1', WORKTREE)], closeGate }) - let terminalSweepStarted = false - const runtime: TeardownRuntime = { - ...presentationRuntime(), - getPtyLivenessVerdict: () => null, - stopTerminalsForWorktree: async () => { - terminalSweepStarted = true - return { stopped: 0 } - } - } - const removal = killAllProcessesForWorktree(WORKTREE, { ...destructiveDeps(), runtime }) - await vi.waitFor(() => { - expect(terminalSweepStarted).toBe(true) - }) - releaseClose() - await expect(removal).resolves.toMatchObject({ structuredStopped: 1 }) - }) - - it('retires it from the live tab snapshot as well as the durable index', async () => { - // Durable index hiding alone leaves the live snapshot tab able to reattach this session. - const retired: string[] = [] - const runtime: TeardownRuntime = { - ...presentationRuntime(), - getPtyLivenessVerdict: () => null, - stopTerminalsForWorktree: async () => ({ stopped: 0 }), - retireStructuredAgentSessionTabFromSnapshot: (sessionId: string) => { - if (!retired.includes(sessionId)) { - retired.push(sessionId) - } - return true - } - } - installHost({ - records: [record('s1', WORKTREE)], - detached: new Set(['s1']), - visible: ['s1'] - }) - await killAllProcessesForWorktree(WORKTREE, { ...destructiveDeps(), runtime }) - expect(retired).toEqual(['s1']) - }) - it('keeps every chat tab when the removal refuses over a session it could not close', async () => { // Refusal must preserve both the stuck chat and its detached workspace sibling. const host = installHost({ @@ -457,94 +215,4 @@ describe('worktree teardown and structured agent sessions', () => { ).rejects.toThrow(/still live: pty-1/) expect([...host.visible]).toEqual(['s1']) }) - - it('retires a live snapshot tab when folder cleanup cannot close its child', async () => { - const retired: string[] = [] - const host = installHost({ - records: [record('s1', WORKTREE)], - stuck: new Set(['s1']), - visible: ['s1'] - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - await killAllProcessesForWorktree(WORKTREE, { - localProvider, - includeProviderInventory: false as const, - includeLocalRegistry: false as const, - closeStructuredSessions: true, - runtime: runtimeDouble({ - retireStructuredAgentSessionTabFromSnapshot: (sessionId: string) => { - retired.push(sessionId) - return true - } - }) - }) - expect([...host.visible]).toEqual([]) - expect(retired).toEqual(['s1']) - warn.mockRestore() - }) - - it('retires tabs before propagating a best-effort PTY sweep failure', async () => { - const host = installHost({ - records: [record('s1', WORKTREE)], - detached: new Set(['s1']), - visible: ['s1'] - }) - const retired: string[] = [] - const settleModule = await import('./settle-before-deadline') - const settle = settleModule.settleBeforeDeadline - const rejection = vi - .spyOn(settleModule, 'settleBeforeDeadline') - .mockImplementation((run, fallback, deadline, failClosedError, failClosedOnRunError) => { - if (fallback === 0) { - return Promise.reject(new Error('terminal inventory unavailable')) - } - return settle(run, fallback, deadline, failClosedError, failClosedOnRunError) - }) - try { - await expect( - killAllProcessesForWorktree(WORKTREE, { - localProvider, - includeProviderInventory: true, - includeLocalRegistry: false, - closeStructuredSessions: true, - runtime: runtimeDouble({ - retireStructuredAgentSessionTabFromSnapshot: (sessionId: string) => { - retired.push(sessionId) - return true - } - }) - }) - ).rejects.toThrow('terminal inventory unavailable') - } finally { - rejection.mockRestore() - } - expect([...host.visible]).toEqual([]) - expect(retired).toEqual(['s1']) - }) - - it('retires nothing on a reconciliation sweep, which deletes no workspace', async () => { - // Repair-only callers close nothing and must retain tabs for their surviving workspace. - const host = installHost({ - records: [record('s1', WORKTREE)], - detached: new Set(['s1']), - visible: ['s1'] - }) - await killAllProcessesForWorktree(WORKTREE, { - localProvider, - includeProviderInventory: false, - includeLocalRegistry: false - }) - expect([...host.visible]).toEqual(['s1']) - }) - - it('leaves a same-id workspace on another host holding its chat tab', async () => { - // Identical workspace ids on different hosts must not retire one another's tabs. - const host = installHost({ - records: [record('s1', WORKTREE, { executionHostId: 'ssh:host-a' })], - detached: new Set(['s1']), - visible: ['s1'] - }) - await killAllProcessesForWorktree(WORKTREE, destructiveDeps()) - expect([...host.visible]).toEqual(['s1']) - }) }) diff --git a/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts b/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts index 56183c4f854..93332ec0d73 100644 --- a/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts +++ b/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts @@ -7,7 +7,7 @@ import { toSshExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import { STILL_LIVE_DETAIL_PREFIX } from '../../../../shared/worktree/removal' +import { STILL_LIVE_DETAIL_PREFIX } from '../../../../shared/worktree/removal/removal' import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { observeStructuredSession, diff --git a/src/main/runtime/workspaces/removal/unstopped-pty-verification.ts b/src/main/runtime/workspaces/removal/unstopped-pty-verification.ts index 68c6c468766..fb54208b372 100644 --- a/src/main/runtime/workspaces/removal/unstopped-pty-verification.ts +++ b/src/main/runtime/workspaces/removal/unstopped-pty-verification.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { OrcaRuntimeService } from '../../orca-runtime' type UnstoppedPtyRuntime = Pick @@ -6,7 +6,7 @@ import { UNSTOPPED_PTY_DETAIL_SEPARATOR, STILL_LIVE_DETAIL_PREFIX, UNSTOPPED_PTY_REMOVAL_PREFIX -} from '../../../../shared/worktree/removal' +} from '../../../../shared/worktree/removal/removal' import { NO_OBSERVING_PROVIDER_REASON, type PtyLivenessVerdict as UnstoppedPtyVerdict diff --git a/src/main/runtime/workspaces/removal/workspace-removal.ts b/src/main/runtime/workspaces/removal/workspace-removal.ts index 086bee323a6..09ed1513dee 100644 --- a/src/main/runtime/workspaces/removal/workspace-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-removal.ts @@ -13,7 +13,10 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import { finishAcceptedWorktreeRemoval } from '../../../workspaces/removal/worktree-background-removal' +import { + finishAcceptedWorktreeRemoval, + waitForWorktreeRemovalAcceptance +} from '../../../workspaces/removal/worktree-background-removal' import { preservedBranchCleanupScopeKey } from '../../../../shared/git/branches/preserved-branch-cleanup' import { getRuntimeWorktreeRemovalOptionsKey, @@ -37,6 +40,8 @@ import { assertWslMoveWorkspaceWritable, isWslMoveSourceHost } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' +import { worktreeHostIdentity } from '../../../persistence/worktree-meta-host-identity' +import { archiveMarkStep } from '../archive/workspace-archive-checkout' export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorkspaceMetadata { abstract removeWorktreeMetadataAndHistory( @@ -90,25 +95,22 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp // Why: a retry or a second client asking while Git still deletes joins that removal. const pending = this.joinPendingWorktreeRemoval(removalTarget.id, options) if (pending) { + await waitForWorktreeRemovalAcceptance(removalTarget.id, cleanupHostId) return options.waitForBackgroundRemoval ? await pending : { removing: true } } - const emitRemoved = (): void => - this.emitWorktreeLifecycle({ - kind: 'removed', - worktreeId: removalTarget.id, - path: removalTarget.path - }) + // Identity read now: the purge drops the row before listeners hear `removed`. + const removed = { + kind: 'removed' as const, + worktreeId: removalTarget.id, + path: removalTarget.path, + ...worktreeHostIdentity(store, removalTarget.id, fenceHostId) + } + const emitRemoved = (): void => this.emitWorktreeLifecycle(removed) const cleanupScopeKey = preservedBranchCleanupScopeKey({ worktreeId: removalTarget.id, hostId: cleanupHostId }) - const optionsKey = getRuntimeWorktreeRemovalOptionsKey({ - force, - runHooks, - allowUnverifiedPtyStop, - allowFailedArchiveHook, - deleteBranch: options.deleteBranch - }) + const optionsKey = getRuntimeWorktreeRemovalOptionsKey(options) const inFlightRemoval = this.removeManagedWorktreeInFlight.get( cleanupScopeKey, removalTarget.id, @@ -264,6 +266,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp this.stopPtysForDestructiveWorktreeRemoval(removalTarget.id, { allowUnverifiedStop: allowUnverifiedPtyStop }), + beforeCheckoutDelete: archiveMarkStep(options, store, removalTarget.id, removalHostId!), closeWatchers: (path) => this.closeFileWatchersForRemoval(path), preserveBranchHead: (result, fallbackHead) => this.preservedBranchCleanup.preserveHead(result, fallbackHead), diff --git a/src/main/runtime/workspaces/removal/worktree-pty-surface-sweeps.ts b/src/main/runtime/workspaces/removal/worktree-pty-surface-sweeps.ts index 8ff31c0c7af..3d0d4e7e8b6 100644 --- a/src/main/runtime/workspaces/removal/worktree-pty-surface-sweeps.ts +++ b/src/main/runtime/workspaces/removal/worktree-pty-surface-sweeps.ts @@ -1,8 +1,8 @@ /** Sweep provider sessions and local registry independently of the teardown entrypoint to avoid a dependency cycle. */ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import { listRegisteredPtys } from '../../../memory/pty-registry' -import { worktreePtyOwnership } from '../../../providers/worktree-pty-ownership' +import { worktreePtyOwnership } from '../../../providers/pty/worktree-ownership' import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' import { teardownRpcDeadline } from './worktree-teardown-deadline' diff --git a/src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts b/src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts index c0a11289089..4db53a2aaee 100644 --- a/src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts +++ b/src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts @@ -10,12 +10,8 @@ vi.mock('../../../memory/pty-registry', () => ({ import { killAllProcessesForWorktree } from './worktree-teardown' import { ABANDONED_SWEEP_GRACE_MS } from './forced-sweep-settlement' -import { - classifyWorktreeForceDeleteReason, - isProvenLivePtyRemovalError -} from '../../../../shared/worktree/removal' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' // Attach a handler before fake-time advancement so rejections stay attributed to this test, without changing the returned promise. function settleTeardown(promise: Promise): Promise { @@ -72,57 +68,7 @@ describe('destructive teardown when a PTY stop cannot be proven', () => { } }) - it('names the blocking PTYs and the escape hatch when one is still live', async () => { - const localProvider = createProviderStub(async () => [ - { id: 'w1@@live-1', cwd: '/tmp/w1', title: 'shell' } - ]) - ;(localProvider.shutdown as unknown as ReturnType).mockRejectedValue( - new Error('kill failed') - ) - listRegisteredPtysMock.mockReturnValue([]) - - await expect( - killAllProcessesForWorktree('w1', { localProvider, requirePhysicalStop: true }) - ).rejects.toThrow(/still live: w1@@live-1[\s\S]*--force/) - }) - // A different provider's empty list cannot prove an unreachable SSH host's PTY exited. - it("blocks removal when the stop lost contact with the PTY's own host", async () => { - // Retain the owning-host verdict; local absence cannot prove remote exit. - const localProvider = createProviderStub(async () => []) - listRegisteredPtysMock.mockReturnValue([]) - const runtime = { - stopTerminalsForWorktree: async ( - _worktreeId: string, - opts: { - stopPty?: ( - ptyId: string, - stop: () => boolean | Promise - ) => Promise<{ stopped: boolean; owner: boolean }> - } - ) => { - await opts.stopPty?.('ssh:conn-1@@relay-9', () => false) - return { stopped: 0 } - }, - getPtyLivenessVerdict: (ptyId: string) => - ptyId === 'ssh:conn-1@@relay-9' - ? { status: 'unverifiable', reason: 'its SSH provider is no longer registered' } - : null - } - - await expect( - killAllProcessesForWorktree('w1', { - runtime: runtime as never, - localProvider, - resolvedConnectionId: 'conn-1', - includeProviderInventory: false, - includeLocalRegistry: false, - requirePhysicalStop: true - }) - ).rejects.toThrow( - /could not verify[\s\S]*ssh:conn-1@@relay-9[\s\S]*SSH provider is no longer registered[\s\S]*--force/ - ) - }) it('does not infer a remote exit from fallback local inventory without a cached verdict', async () => { const localProvider = createProviderStub(async () => []) @@ -156,47 +102,7 @@ describe('destructive teardown when a PTY stop cannot be proven', () => { expect(localProvider.listProcesses).not.toHaveBeenCalled() }) - it('reports unverifiable separately from live when the process list fails', async () => { - const localProvider = createProviderStub(async () => { - throw new Error('daemon socket closed') - }) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'stale-1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 100 } - ]) - ;(localProvider.shutdown as unknown as ReturnType).mockRejectedValue( - new Error('Session not found: stale-1') - ) - - await expect( - killAllProcessesForWorktree('w1', { - localProvider, - includeProviderInventory: false, - requirePhysicalStop: true - }) - ).rejects.toThrow(/could not verify[\s\S]*stale-1[\s\S]*daemon socket closed/) - }) - // Force must also cross sweep failures before the unproven-stop gate. - it('lets force through a provider whose inventory rejects outright', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - listRegisteredPtysMock.mockReturnValue([]) - const localProvider = createProviderStub(async () => { - throw new Error('ssh channel closed') - }) - - await expect( - killAllProcessesForWorktree('w1', { - localProvider, - requirePhysicalStop: true, - allowUnverifiedStop: true - }) - ).resolves.toEqual({ runtimeStopped: 0, providerStopped: 0, registryStopped: 0 }) - expect(warn).toHaveBeenCalledWith(expect.stringContaining('ssh channel closed')) - } finally { - warn.mockRestore() - } - }) it('lets force through a sweep that never settles before the deadline', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -240,128 +146,8 @@ describe('destructive teardown when a PTY stop cannot be proven', () => { }) // Force must join active shutdowns before filesystem deletion or Windows can fail with EBUSY. - it('waits for in-flight sweeps before force returns', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - const localProvider = createProviderStub(async () => { - throw new Error('ssh channel closed') - }) - let shutdownFinished = false - ;(localProvider.shutdown as unknown as ReturnType).mockImplementation( - async () => { - await new Promise((resolve) => setTimeout(resolve, 20)) - shutdownFinished = true - } - ) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'reg-1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 100 } - ]) - - const result = await killAllProcessesForWorktree('w1', { - localProvider, - requirePhysicalStop: true, - allowUnverifiedStop: true - }) - - expect(shutdownFinished).toBe(true) - expect(result.registryStopped).toBe(1) - } finally { - warn.mockRestore() - } - }) // Wrap raw provider failures in recognizable force-removal wording without losing their cause (#11960). - it('offers force delete for a sweep-level failure without losing the provider wording', async () => { - listRegisteredPtysMock.mockReturnValue([]) - const localProvider = createProviderStub(async () => { - throw new Error('SSH channel closed while listing processes') - }) - - const error = await killAllProcessesForWorktree('repo-1::/w', { - localProvider, - requirePhysicalStop: true - }).then( - () => new Error('expected a rejection'), - (rejection: Error) => rejection - ) - expect(error.message).toContain('SSH channel closed while listing processes') - expect(classifyWorktreeForceDeleteReason(error.message)).toBe('unstopped-pty') - expect(isProvenLivePtyRemovalError(error.message)).toBe(false) - }) // Timeout does not cancel shutdown; force must await it before deletion to avoid partial Windows removal. - it('waits for a shutdown the deadline abandoned before force returns', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - let releaseShutdown: () => void = () => {} - try { - listRegisteredPtysMock.mockReturnValue([]) - const localProvider = createProviderStub(async () => [ - { id: 'w1@@live-1', cwd: '/tmp/w1', title: 'shell' } - ]) - let shutdownFinished = false - ;(localProvider.shutdown as unknown as ReturnType).mockImplementation( - async () => - await new Promise((resolve) => { - releaseShutdown = () => { - shutdownFinished = true - resolve() - } - }) - ) - - const teardown = settleTeardown( - killAllProcessesForWorktree('w1', { - localProvider, - timeoutMs: 30, - requirePhysicalStop: true, - allowUnverifiedStop: true - }) - ) - let returned = false - void teardown.then(() => { - returned = true - }) - await new Promise((resolve) => setTimeout(resolve, 150)) - - expect(shutdownFinished).toBe(false) - expect(returned).toBe(false) - releaseShutdown() - await expect(teardown).resolves.toEqual({ - runtimeStopped: 0, - providerStopped: 0, - registryStopped: 0 - }) - } finally { - releaseShutdown() - warn.mockRestore() - } - }) - - it('lets an explicit force removal proceed past PTYs it could not stop', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - const localProvider = createProviderStub(async () => [ - { id: 'w1@@live-1', cwd: '/tmp/w1', title: 'shell' } - ]) - ;(localProvider.shutdown as unknown as ReturnType).mockRejectedValue( - new Error('kill failed') - ) - listRegisteredPtysMock.mockReturnValue([]) - const onPtyStopped = vi.fn() - - await expect( - killAllProcessesForWorktree('w1', { - localProvider, - onPtyStopped, - requirePhysicalStop: true, - allowUnverifiedStop: true - }) - ).resolves.toMatchObject({ providerStopped: 0 }) - expect(warn).toHaveBeenCalledWith(expect.stringContaining('w1@@live-1')) - // Keep proven-live PTYs discoverable for users and later sweeps. - expect(onPtyStopped).not.toHaveBeenCalled() - } finally { - warn.mockRestore() - } - }) }) diff --git a/src/main/runtime/workspaces/removal/worktree-teardown.test.ts b/src/main/runtime/workspaces/removal/worktree-teardown.test.ts index edcf37c6ede..40e85c75ee4 100644 --- a/src/main/runtime/workspaces/removal/worktree-teardown.test.ts +++ b/src/main/runtime/workspaces/removal/worktree-teardown.test.ts @@ -8,10 +8,9 @@ vi.mock('../../../memory/pty-registry', () => ({ listRegisteredPtys: listRegisteredPtysMock })) -import { killAllProcessesForWorktree, WORKTREE_PROCESS_SWEEP_TIMEOUT_MS } from './worktree-teardown' -import type { IPtyProvider } from '../../../providers/pty-provider-contract' -import type { PtyProcessInfo } from '../../../providers/pty-process-info' -import { DaemonPtyAdapter } from '../../../daemon/providers/adapter/daemon-pty-adapter' +import { killAllProcessesForWorktree } from './worktree-teardown' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' +import type { PtyProcessInfo } from '../../../providers/pty/process-info' function createProviderStub(listProcesses: () => Promise): IPtyProvider { return { @@ -43,184 +42,6 @@ describe('killAllProcessesForWorktree', () => { listRegisteredPtysMock.mockReset() }) - it('stops cwd-owned PTYs even when their ids have no worktree prefix', async () => { - const localProvider = createProviderStub(async () => [ - { id: 'floating-1', cwd: '/repo/app/nested', title: 'shell' }, - { id: 'outside-2', cwd: '/repo/application', title: 'shell' }, - { id: 'repo-1::/repo/app@@legacy-3', title: 'shell' } as PtyProcessInfo - ]) - listRegisteredPtysMock.mockReturnValue([]) - - const result = await killAllProcessesForWorktree('repo-1::/repo/app', { - localProvider, - requirePhysicalStop: true - }) - - expect(localProvider.shutdown).toHaveBeenCalledWith( - 'floating-1', - expect.objectContaining({ immediate: true }) - ) - expect(localProvider.shutdown).toHaveBeenCalledWith( - 'repo-1::/repo/app@@legacy-3', - expect.objectContaining({ immediate: true }) - ) - expect(localProvider.shutdown).not.toHaveBeenCalledWith( - 'outside-2', - expect.objectContaining({ immediate: true }) - ) - expect(result.providerStopped).toBe(2) - }) - - it('does not use cwd fallback against a different authoritative worktree id', async () => { - const localProvider = createProviderStub(async () => [ - { - id: 'owned-by-sibling', - cwd: '/repo/app/nested', - title: 'shell', - worktreeId: 'repo-1::/repo/sibling' - } - ]) - listRegisteredPtysMock.mockReturnValue([]) - - const result = await killAllProcessesForWorktree('repo-1::/repo/app', { - localProvider, - requirePhysicalStop: true - }) - - expect(localProvider.shutdown).not.toHaveBeenCalled() - expect(result.providerStopped).toBe(0) - }) - - it('kills only the deleted instance own sessions when siblings share the list', async () => { - // One provider list spanning all four quadrants: the deleted instance's own - // prefix + tagged sessions must die; the untagged and tagged sibling sessions - // on the shared checkout path must survive. - const deletedInstance = - 'repo-1::/Users/dev/project::workspace:11111111-1111-1111-1111-111111111111' - const siblingInstance = - 'repo-1::/Users/dev/project::workspace:22222222-2222-2222-2222-222222222222' - const localProvider = createProviderStub(async () => [ - { id: `${deletedInstance}@@own00001`, cwd: '/Users/dev/project', title: 'shell' }, - { id: 'own-tagged', cwd: '/Users/dev/project', title: 'shell', worktreeId: deletedInstance }, - { id: 'floating-sibling', cwd: '/Users/dev/project', title: 'shell' }, - { - id: `${siblingInstance}@@sib00000`, - cwd: '/Users/dev/project', - title: 'shell', - worktreeId: siblingInstance - } - ]) - listRegisteredPtysMock.mockReturnValue([]) - - const result = await killAllProcessesForWorktree(deletedInstance, { - localProvider, - requirePhysicalStop: true - }) - - const killed = (localProvider.shutdown as unknown as ReturnType).mock.calls - .map((call) => call[0] as string) - .sort() - expect(killed).toEqual([`${deletedInstance}@@own00001`, 'own-tagged'].sort()) - expect(result.providerStopped).toBe(2) - }) - - it('uses authoritative remote worktree ownership without sweeping the local registry', async () => { - const remoteProvider = createProviderStub(async () => [ - { id: 'pty-remote', cwd: '/remote/w1', title: 'shell', worktreeId: 'w1' }, - { id: 'pty-sibling', cwd: '/remote/w2', title: 'shell', worktreeId: 'w2' } - ]) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'local-1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 200 } - ]) - - const result = await killAllProcessesForWorktree('w1', { - localProvider: remoteProvider, - includeLocalRegistry: false, - requirePhysicalStop: true - }) - - expect(remoteProvider.shutdown).toHaveBeenCalledWith( - 'pty-remote', - expect.objectContaining({ immediate: true }) - ) - expect(remoteProvider.shutdown).not.toHaveBeenCalledWith( - 'pty-sibling', - expect.objectContaining({ immediate: true }) - ) - expect(remoteProvider.shutdown).not.toHaveBeenCalledWith( - 'local-1', - expect.objectContaining({ immediate: true }) - ) - expect(listRegisteredPtysMock).not.toHaveBeenCalled() - expect(result).toEqual({ runtimeStopped: 0, providerStopped: 1, registryStopped: 0 }) - }) - - it('bounds provider shutdown fanout while preserving concurrent batches', async () => { - const sessions = Array.from({ length: 40 }, (_, index) => ({ - id: `w1@@${index}`, - cwd: '/tmp', - title: 'shell' - })) - const localProvider = createProviderStub(async () => sessions) - listRegisteredPtysMock.mockReturnValue([]) - let active = 0 - let maxActive = 0 - const releases: (() => void)[] = [] - ;(localProvider.shutdown as unknown as ReturnType).mockImplementation( - () => - new Promise((resolve) => { - active += 1 - maxActive = Math.max(maxActive, active) - releases.push(() => { - active -= 1 - resolve() - }) - }) - ) - - const teardown = killAllProcessesForWorktree('w1', { localProvider }) - await vi.waitFor(() => expect(localProvider.shutdown).toHaveBeenCalledTimes(32)) - expect(maxActive).toBe(32) - releases.splice(0).forEach((release) => release()) - await vi.waitFor(() => expect(localProvider.shutdown).toHaveBeenCalledTimes(40)) - releases.splice(0).forEach((release) => release()) - - await expect(teardown).resolves.toEqual({ - runtimeStopped: 0, - providerStopped: 40, - registryStopped: 0 - }) - }) - - it('falls back to provider shutdown when the runtime cannot stop an overlapping PTY', async () => { - const stopTerminalsForWorktree = vi.fn( - async ( - _worktreeId: string, - options: { - stopPty: ( - ptyId: string, - stop: () => boolean - ) => Promise<{ stopped: boolean; owner: boolean }> - } - ) => ({ - stopped: (await options.stopPty('w1@@same', () => false)).owner ? 1 : 0 - }) - ) - const runtime = { - stopTerminalsForWorktree - } as unknown as Parameters[1]['runtime'] - const localProvider = createProviderStub(async () => []) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'w1@@same', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 100 } - ]) - - const result = await killAllProcessesForWorktree('w1', { runtime, localProvider }) - - expect(result.runtimeStopped).toBe(0) - expect(result.registryStopped).toBe(1) - expect(localProvider.shutdown).toHaveBeenCalledTimes(1) - }) - it('accepts a failed stop when exact-owner inventory supersedes cached uncertainty', async () => { const worktreeId = 'repo-1::C:/Users/User/orca/workspaces/repo/feature' const ptyId = `${worktreeId}@@windows-pty` @@ -311,47 +132,6 @@ describe('killAllProcessesForWorktree', () => { expect(fallbackProvider.listProcesses).not.toHaveBeenCalled() }) - it('keeps duplicate sweeps behind the runtime physical-stop promise', async () => { - let releasePhysicalStop: () => void = () => undefined - const physicalStop = new Promise((resolve) => { - releasePhysicalStop = () => resolve(true) - }) - const stopTerminalsForWorktree = vi.fn( - async ( - _worktreeId: string, - options: { - stopPty: ( - ptyId: string, - stop: () => Promise - ) => Promise<{ stopped: boolean; owner: boolean }> - } - ) => ({ - stopped: (await options.stopPty('w1@@same', () => physicalStop)).owner ? 1 : 0 - }) - ) - const runtime = { - stopTerminalsForWorktree - } as unknown as Parameters[1]['runtime'] - const localProvider = createProviderStub(async () => [ - { id: 'w1@@same', cwd: '/tmp/w1', title: 'shell' } - ]) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'w1@@same', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 100 } - ]) - - const teardown = killAllProcessesForWorktree('w1', { runtime, localProvider }) - await vi.waitFor(() => expect(stopTerminalsForWorktree).toHaveBeenCalledTimes(1)) - expect(localProvider.shutdown).not.toHaveBeenCalled() - - releasePhysicalStop() - await expect(teardown).resolves.toEqual({ - runtimeStopped: 1, - providerStopped: 0, - registryStopped: 0 - }) - expect(localProvider.shutdown).not.toHaveBeenCalled() - }) - it('fails destructive teardown closed when physical stop misses the deadline', async () => { vi.useFakeTimers() try { @@ -400,201 +180,4 @@ describe('killAllProcessesForWorktree', () => { }) // Bound Windows daemon kill RPCs below the sweep deadline so failures report the stop cause (#9500). - it('destructive teardown surfaces a bounded stop failure when the daemon kill RPC never replies (#9500 regression)', async () => { - vi.useFakeTimers() - try { - const worktreeId = 'w1' - const sessionId = 'w1@@dead0001' - let killRequests = 0 - - // List ownership but never answer kill; absent an explicit timeout override, requests use the daemon's 30s default. - const DAEMON_DEFAULT_REQUEST_TIMEOUT_MS = 30_000 - const fakeClient = { - onDisconnected: () => () => {}, - onEvent: () => () => {}, - ensureConnected: async () => {}, - // Model bounded connection so connect and kill share the real RPC budget. - ensureConnectedWithin: async () => {}, - isConnected: () => true, - getDaemonIdentity: () => null, - disconnect: () => {}, - notify: () => {}, - request: ( - type: string, - _payload?: unknown, - timeoutMs = DAEMON_DEFAULT_REQUEST_TIMEOUT_MS - ): Promise => { - if (type === 'listSessions') { - return Promise.resolve({ - sessions: [{ sessionId, isAlive: true, cwd: '/tmp/w1' }] - }) - } - if (type === 'kill') { - killRequests += 1 - // Only the request's own timeout can reject this silent daemon call. - return new Promise((_resolve, reject) => { - setTimeout( - () => reject(new Error(`Request kill timed out after ${timeoutMs}ms`)), - timeoutMs - ) - }) - } - return Promise.resolve({}) - } - } - - const adapter = new DaemonPtyAdapter({ socketPath: '/tmp/sock', tokenPath: '/tmp/tok' }) - ;(adapter as unknown as { client: typeof fakeClient }).client = fakeClient - - listRegisteredPtysMock.mockReturnValue([]) - - // Capture rejection before advancing time so an incorrect result fails this assertion, not another test. - const outcome = killAllProcessesForWorktree(worktreeId, { - localProvider: adapter as unknown as IPtyProvider, - includeLocalRegistry: false, - requirePhysicalStop: true, - timeoutMs: WORKTREE_PROCESS_SWEEP_TIMEOUT_MS - }).then( - () => { - throw new Error('teardown unexpectedly resolved') - }, - (error: Error) => error - ) - - // Advance through the sweep deadline; a correctly bounded kill must have already reported its stop failure. - await vi.advanceTimersByTimeAsync(WORKTREE_PROCESS_SWEEP_TIMEOUT_MS) - - const error = await outcome - expect(killRequests).toBeGreaterThan(0) - expect(error.message).toContain('Failed to physically stop every PTY') - } finally { - vi.useRealTimers() - } - }) - - it('tolerates an unresolved runtime selector during destructive removal', async () => { - // An absent newly created/removed graph entry means no runtime-owned PTYs, not failed teardown. - const stopTerminalsForWorktree = vi.fn().mockRejectedValue(new Error('selector_not_found')) - const runtime = { - stopTerminalsForWorktree - } as unknown as Parameters[1]['runtime'] - const localProvider = createProviderStub(async () => []) - listRegisteredPtysMock.mockReturnValue([]) - - const result = await killAllProcessesForWorktree('w1', { - runtime, - localProvider, - requirePhysicalStop: true - }) - - expect(result.runtimeStopped).toBe(0) - }) - - it('fails destructive teardown closed when the runtime sweep rejects', async () => { - const stopTerminalsForWorktree = vi.fn().mockRejectedValue(new Error('runtime sweep failed')) - const runtime = { - stopTerminalsForWorktree - } as unknown as Parameters[1]['runtime'] - const localProvider = createProviderStub(async () => []) - listRegisteredPtysMock.mockReturnValue([]) - - await expect( - killAllProcessesForWorktree('w1', { - runtime, - localProvider, - requirePhysicalStop: true - }) - ).rejects.toThrow('runtime sweep failed') - }) - - it('bounds the entire process sweep when a provider never settles', async () => { - vi.useFakeTimers() - try { - const localProvider = createProviderStub(() => new Promise(() => {})) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'registry-1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 12 } - ]) - let completed = false - const teardown = killAllProcessesForWorktree('w1', { - localProvider, - timeoutMs: WORKTREE_PROCESS_SWEEP_TIMEOUT_MS - }).then((result) => { - completed = true - return result - }) - - await vi.advanceTimersByTimeAsync(WORKTREE_PROCESS_SWEEP_TIMEOUT_MS - 1) - expect(completed).toBe(false) - await vi.advanceTimersByTimeAsync(1) - - await expect(teardown).resolves.toEqual({ - runtimeStopped: 0, - providerStopped: 0, - registryStopped: 1 - }) - expect(localProvider.shutdown).toHaveBeenCalledWith( - 'registry-1', - expect.objectContaining({ immediate: true }) - ) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('does not issue shutdown after a timed-out provider list settles late', async () => { - vi.useFakeTimers() - try { - let resolveList: (sessions: { id: string; cwd: string; title: string }[]) => void = () => {} - const localProvider = createProviderStub( - () => - new Promise((resolve) => { - resolveList = resolve - }) - ) - listRegisteredPtysMock.mockReturnValue([]) - const teardown = killAllProcessesForWorktree('w1', { localProvider, timeoutMs: 25 }) - - await vi.advanceTimersByTimeAsync(25) - await expect(teardown).resolves.toMatchObject({ providerStopped: 0 }) - resolveList([{ id: 'w1@@replacement', cwd: '/new', title: 'new' }]) - await Promise.resolve() - - expect(localProvider.shutdown).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - - it('does not mutate PTY state after a shutdown settles beyond the deadline', async () => { - vi.useFakeTimers() - try { - let resolveShutdown: () => void = () => {} - const localProvider = createProviderStub(async () => []) - ;(localProvider.shutdown as unknown as ReturnType).mockImplementation( - () => - new Promise((resolve) => { - resolveShutdown = resolve - }) - ) - listRegisteredPtysMock.mockReturnValue([ - { ptyId: 'registry-1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 12 } - ]) - const onPtyStopped = vi.fn() - const teardown = killAllProcessesForWorktree('w1', { - localProvider, - onPtyStopped, - timeoutMs: 25 - }) - - await vi.advanceTimersByTimeAsync(25) - await expect(teardown).resolves.toMatchObject({ registryStopped: 0 }) - resolveShutdown() - await Promise.resolve() - - expect(onPtyStopped).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/runtime/workspaces/removal/worktree-teardown.ts b/src/main/runtime/workspaces/removal/worktree-teardown.ts index 93aa47774b9..091dceb69e3 100644 --- a/src/main/runtime/workspaces/removal/worktree-teardown.ts +++ b/src/main/runtime/workspaces/removal/worktree-teardown.ts @@ -1,4 +1,4 @@ -import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import type { IPtyProvider } from '../../../providers/pty/provider-contract' import type { OrcaRuntimeService } from '../../orca-runtime' import { isUnstoppedPtyRemovalError, @@ -6,7 +6,7 @@ import { UNSTOPPED_PTY_DETAIL_SEPARATOR, WORKTREE_TEARDOWN_FORCE_HINT, WORKTREE_TEARDOWN_TIMEOUT_PREFIX -} from '../../../../shared/worktree/removal' +} from '../../../../shared/worktree/removal/removal' import { settleBeforeDeadline } from './settle-before-deadline' import { clearStoppedPtyState, diff --git a/src/main/runtime/workspaces/session-hosts/folder-workspace-mixed-host-routing.test.ts b/src/main/runtime/workspaces/session-hosts/folder-workspace-mixed-host-routing.test.ts index 474c9cf2e6e..37163a3ca3b 100644 --- a/src/main/runtime/workspaces/session-hosts/folder-workspace-mixed-host-routing.test.ts +++ b/src/main/runtime/workspaces/session-hosts/folder-workspace-mixed-host-routing.test.ts @@ -6,15 +6,15 @@ import { ROUTING_REPOS } from '../../../../shared/folder-workspaces/folder-workspace-host-routing.test-fixture' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { localDesktopSession } from '../../../../shared/workspace-layout/workspace-layout-profile.test-fixture' +import { localDesktopSession } from '../../../../shared/workspace-layout/persistence/workspace-layout-profile.test-fixture' import { emptySession, FOLDER_KEY, GIT_KEY -} from '../../../../shared/workspace-layout/workspace-layout-session.test-fixture' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { OrcaRuntimeService } from '../../orca-runtime' import { WorkspaceLayoutStream } from '../../terminal/surface/workspace-layout-stream' -import { collectLayoutEvents } from '../../orca-runtime-tests/workspace-layout-stream-events.test-fixture' +import '../../orca-runtime-tests/workspace-layout-stream-events.test-fixture' import { partialRuntimeStore, storeRepo @@ -85,7 +85,6 @@ describe('a workspace the router throws on', () => { const write = () => writeListeners.forEach((listener) => listener(null)) return { stream, route, write } } - const flush = () => new Promise((resolve) => queueMicrotask(resolve)) it('is left out, and every other workspace is still published, logged once', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -94,25 +93,6 @@ describe('a workspace the router throws on', () => { expect(warn).toHaveBeenCalledTimes(1) }) - it('keeps its last published layout instead of sending a removal', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { stream, route, write } = streamThrowingOn(FOLDER_KEY) - route.throws = false - const collector = collectLayoutEvents() - const first = stream.subscribe(collector.listener) - collector.seed(first.snapshot) - const events = collector.events - expect(first.snapshot.map((entry) => entry.key)).toEqual([GIT_KEY, FOLDER_KEY]) - route.throws = true - write() - await flush() - expect(events).toEqual([]) - const later = stream.subscribe(() => {}).snapshot - expect(later.find((entry) => entry.key === FOLDER_KEY)?.layout).toEqual( - first.snapshot.find((entry) => entry.key === FOLDER_KEY)?.layout - ) - }) - it('still fails the whole projection in a window-owned build', () => { mocks.layoutOwnerIsMain = false vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts index dade1601abc..747092f059b 100644 --- a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts +++ b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts @@ -7,7 +7,7 @@ import type { CreateWorktreeResult } from '../../../../shared/worktree/create-ty import type { Repo } from '../../../../shared/repo-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { Worktree } from '../../../../shared/worktree/types' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' import { createSequencedSetupAgentCommands } from '../../../../shared/agent-launch/startup/setup-agent-sequencing' import { getSetupRunnerCommandPlatformForPath } from '../../../../shared/agent-launch/startup/setup-runner-command' diff --git a/src/main/runtime/workspaces/startup/runtime-workspace-navigation.ts b/src/main/runtime/workspaces/startup/runtime-workspace-navigation.ts index 089b889a61e..7a877cda4ea 100644 --- a/src/main/runtime/workspaces/startup/runtime-workspace-navigation.ts +++ b/src/main/runtime/workspaces/startup/runtime-workspace-navigation.ts @@ -1,5 +1,5 @@ import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' import { navigationTargetsClients, diff --git a/src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.ts b/src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.ts index 6c86061cb54..c8d447d76d7 100644 --- a/src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.ts +++ b/src/main/runtime/workspaces/startup/runtime-worktree-agent-startup.ts @@ -5,7 +5,7 @@ import { agentStartedTelemetry } from '../../../agent-launch/agent-started-telem import type { AgentLaunchPreferences } from '../../../../shared/agent-session/agent-session-host-authority' import type { Repo } from '../../../../shared/repo-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import { repoIsRemote } from '../../../../shared/agent-launch/startup/agent-launch-remote' import { getRepoSshConnectionId } from '../../../../shared/execution-host' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' diff --git a/src/main/runtime/workspaces/startup/workspace-create-activation.ts b/src/main/runtime/workspaces/startup/workspace-create-activation.ts index 34a9a28d442..3d2c74c95d6 100644 --- a/src/main/runtime/workspaces/startup/workspace-create-activation.ts +++ b/src/main/runtime/workspaces/startup/workspace-create-activation.ts @@ -1,6 +1,6 @@ import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' -import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { createRuntimeFolderWorktree } from '../creation/runtime-folder-worktree-create' import type { startRuntimeLocalWorktreeTerminals } from './runtime-local-worktree-terminal-startup' diff --git a/src/main/runtime/workspaces/workspace-metadata.ts b/src/main/runtime/workspaces/workspace-metadata.ts index b7d6f85c902..6202e34a4fc 100644 --- a/src/main/runtime/workspaces/workspace-metadata.ts +++ b/src/main/runtime/workspaces/workspace-metadata.ts @@ -2,7 +2,7 @@ import type { RemoteFetchResult, RemoteTrackingBase } from '../repositories/runtime-remote-fetch-controller' -import type { WorktreeBaseStatusEvent } from '../../../shared/worktree/base-ref-drift-types' +import type { WorktreeBaseStatusEvent } from '../../../shared/worktree/base-refs/base-ref-drift-types' import { probeRuntimeWorktreeDrift } from './metadata/runtime-worktree-drift-probe' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import type { GitPushTarget } from '../../../shared/worktree/types' diff --git a/src/main/runtime/workspaces/workspace-removal-target.ts b/src/main/runtime/workspaces/workspace-removal-target.ts index 3c01b337197..4771ad499bb 100644 --- a/src/main/runtime/workspaces/workspace-removal-target.ts +++ b/src/main/runtime/workspaces/workspace-removal-target.ts @@ -35,8 +35,12 @@ import { import { interruptedLocalWorktreeRemovalJob } from './removal/runtime-interrupted-local-worktree-removal' import { retryFailedRemovalUnlessRegistered } from '../../workspaces/removal/worktree-removal-leftover' import type { GitWorktreeInfo } from '../../../shared/worktree/types' -import { removeWorktreeMetaRow } from '../../persistence/host-qualified-worktree-meta' +import { + readWorktreeMetaForHost, + removeWorktreeMetaRow +} from '../../persistence/host-qualified-worktree-meta' import { RuntimeAgentLaunchPreparation } from '../terminal/launch/runtime-agent-launch-preparation' +import { worktreeHostIdentity } from '../../persistence/worktree-meta-host-identity' export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends RuntimeAgentLaunchPreparation { protected abstract resolveExplicitWorktreeIdScoped( @@ -117,20 +121,30 @@ export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends Runtim } protected localRemovalJobHost(store: RuntimeStore) { + // `removed` is heard after the purge drops the row, so its identity is read first. + const purgedIdentities = new Map>() return { store, acquireWatcherRemoval: this.acquireFileWatcherRemoval, closeWatchers: (path) => this.closeFileWatchersForRemoval(path), preservedBranchCleanup: this.preservedBranchCleanup, - purge: ({ worktreeId, repoId }) => - this.purgeRemovedWorktree(store, worktreeId, repoId, LOCAL_EXECUTION_HOST_ID), - onRemoved: ({ worktreeId, worktreePath }) => - this.emitWorktreeLifecycle({ kind: 'removed', worktreeId, path: worktreePath }), + purge: ({ worktreeId, repoId }) => { + purgedIdentities.set( + worktreeId, + worktreeHostIdentity(store, worktreeId, LOCAL_EXECUTION_HOST_ID) + ) + return this.purgeRemovedWorktree(store, worktreeId, repoId, LOCAL_EXECUTION_HOST_ID) + }, + onRemoved: ({ worktreeId, worktreePath }) => { + const identity = purgedIdentities.get(worktreeId) + purgedIdentities.delete(worktreeId) + this.emitWorktreeLifecycle({ kind: 'removed', worktreeId, path: worktreePath, ...identity }) + }, publish: (repoId) => this.publishWorktreeRemovalChange(repoId) } } - // Host state every removal path drops once Git has let go of the checkout. + // Host state every removal path drops once Git has let go of the checkout; an archived row keeps its metadata. // Resolves after the pretrust deletion so a removal ack cannot precede it. protected async purgeRemovedWorktree( store: RuntimeStore, @@ -139,12 +153,18 @@ export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends Runtim removalHostId?: ExecutionHostId ): Promise { this.clearOptimisticReconcileToken(worktreeId) + const archived = Boolean( + (removalHostId + ? readWorktreeMetaForHost(store, worktreeId, removalHostId) + : store.getWorktreeMeta(worktreeId) + )?.archivedCheckout + ) // Only checkout-deleting paths purge here, so the directory itself is gone. const metadataAndHistory = this.removeWorktreeMetadataAndHistory( store, worktreeId, removalHostId, - { dropAgentTrust: true } + { dropAgentTrust: true, keepArchivedMeta: archived } ) this.invalidateResolvedWorktreeCache() this.invalidateWorktreeScanCacheForRepo(repoId) @@ -157,7 +177,7 @@ export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends Runtim worktreeId: string, hostId?: ExecutionHostId, // Why: folder sessions and forgotten orphans keep the directory on disk for siblings. - options: { dropAgentTrust?: boolean } = {} + options: { dropAgentTrust?: boolean; keepArchivedMeta?: boolean } = {} ): Promise { // Purge history/caches before path-derived ids can name a recreated workspace. const persistedHostId = store.getWorktreeMeta(worktreeId)?.hostId @@ -169,7 +189,9 @@ export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends Runtim ) const acceptedRendererSnapshot = this.acceptedRendererMobileSnapshotByWorktree.get(worktreeId) const storedSnapshot = this.mobileSessionTabsByWorktree.get(worktreeId) - removeWorktreeMetaRow(store, worktreeId, hostId) + if (!options.keepArchivedMeta) { + removeWorktreeMetaRow(store, worktreeId, hostId) + } // Retire only this host's panes even when a same-id owner survives. this.dropAgentStatusForRemovedWorktreeFn?.(worktreeId, hostId ?? persistedHostId) if (!preservesSameIdOwner) { diff --git a/src/main/schema-validation/zod-schema-compilation.test.ts b/src/main/schema-validation/zod-schema-compilation.test.ts deleted file mode 100644 index a683a1ded77..00000000000 --- a/src/main/schema-validation/zod-schema-compilation.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { z } from 'zod' -import { getCompiledSchema } from './zod-schema-compilation' - -describe('getCompiledSchema', () => { - it('compiles once per schema identity and leaves the original parser untouched', () => { - const schema = z.object({ value: z.string() }) - const compiled = getCompiledSchema(schema) - expect(compiled).not.toBe(schema) - expect(getCompiledSchema(schema)).toBe(compiled) - expect(getCompiledSchema(z.object({ value: z.string() }))).not.toBe(compiled) - expect(schema.safeParse({ value: 'ok', extra: true })).toEqual( - compiled.safeParse({ value: 'ok', extra: true }) - ) - }) -}) diff --git a/src/main/server/serve-readiness.ts b/src/main/server/serve-readiness.ts index ec1efd1134e..1f05b2987c2 100644 --- a/src/main/server/serve-readiness.ts +++ b/src/main/server/serve-readiness.ts @@ -1,5 +1,5 @@ import type { PairingOfferUnavailableReason } from '../runtime/rpc/server/runtime-rpc-pairing-types' -import type { OrcadHealth } from '../orcad/orcad-health' +import type { OrcadHealth } from '../orcad/diagnostics/orcad-health' import { describePtyProcessCeiling } from '../../shared/terminal/pty/native-process/pty-process-ceiling-state' export type ServePairingUnavailableReason = PairingOfferUnavailableReason | 'disabled_by_operator' diff --git a/src/main/skills/bundled-skill-install/bundled-skill-installation.ts b/src/main/skills/bundled-skill-install/bundled-skill-installation.ts index c15c4ffa2f0..b05d4ea61de 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-installation.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-installation.ts @@ -38,7 +38,7 @@ export async function installBundledSkills( /** Silent path: updates only hash-verified Orca copies of `names`, planned under the same locks. */ export async function autoUpdateInstalledBundledSkills( - input: BundledSkillServiceInput & { names: readonly string[] } + input: BundledSkillServiceInput & { names: readonly string[]; recordOnly?: boolean } ): Promise { return autoUpdateBundledSkills({ ...withDefaults(input), names: input.names }) } diff --git a/src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts b/src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts new file mode 100644 index 00000000000..897a4017fd3 --- /dev/null +++ b/src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts @@ -0,0 +1,198 @@ +import { createHash } from 'node:crypto' +import { appendFile, lstat, readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + bundledSkillInstallAction, + bundledSkillNudgeEntries, + bundledSkillNudgeKey, + bundledSkillPlanState +} from '../../../shared/bundled-skill-summary' +import type { BundledSkillSource } from './bundled-skill-sources' +import { + autoUpdateInstalledBundledSkills, + previewBundledSkillInstall +} from './bundled-skill-installation' +import { + makeSkillHome, + NAME, + NEW_SOURCE, + NEW_TEXT, + OLD_TEXT, + previewAndInstall, + removeSkillHomes, + serviceInput, + writeCopy, + type SkillHome +} from './testing/bundled-skill-home' + +afterEach(removeSkillHomes) + +const digest = (text: string) => createHash('sha256').update(text).digest('hex') +const NEWER_TEXT = `---\nname: ${NAME}\ndescription: Newer\n---\n\nNewer body\n` +/** A newer Orca build on the same host: it knows every older text, but no older build knows its text. */ +const NEWER_SOURCE: BundledSkillSource = { + name: NAME, + text: NEWER_TEXT, + releasedDigests: [digest(OLD_TEXT), digest(NEW_TEXT), digest(NEWER_TEXT)] +} + +const DEV_TEXT = `---\nname: ${NAME}\ndescription: Dev\n---\n\nDev branch body\n` +/** A dev build whose bundle never shipped `NEW_TEXT`, so it cannot recognise that copy by hash. */ +const DEV_SOURCE: BundledSkillSource = { + name: NAME, + text: DEV_TEXT, + releasedDigests: [digest(OLD_TEXT), digest(DEV_TEXT)] +} + +const asBuild = (home: SkillHome, source: BundledSkillSource) => ({ + ...serviceInput(home), + sources: [source] +}) +const autoUpdateAs = (home: SkillHome, source: BundledSkillSource) => + autoUpdateInstalledBundledSkills({ ...asBuild(home, source), names: [NAME] }) +const hasMarker = (home: SkillHome, text: string) => + lstat(join(home.home, '.agents', '.orca-skill-digests', NAME, digest(text))).then( + () => true, + () => false + ) + +describe("another Orca build's copy on the same host", () => { + it('links a newly selected agent to a recognized shared copy', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEWER_TEXT) + await autoUpdateAs(home, NEWER_SOURCE) + + const input = { ...serviceInput(home, { agents: ['cursor'] }), sources: [NEW_SOURCE] } + await previewAndInstall(input) + + expect((await lstat(home.cursor)).isSymbolicLink()).toBe(true) + expect(await readFile(join(home.cursor, 'SKILL.md'), 'utf8')).toBe(NEWER_TEXT) + }) + + it('automatically migrates a former-name agent copy to a recognized shared copy', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEWER_TEXT) + await autoUpdateAs(home, NEWER_SOURCE) + await writeCopy(join(home.home, '.claude', 'skills', 'former-test-skill'), OLD_TEXT) + + await autoUpdateAs(home, { ...NEW_SOURCE, aliases: ['former-test-skill'] }) + + expect((await lstat(home.claude)).isSymbolicLink()).toBe(true) + expect(await readFile(join(home.claude, 'SKILL.md'), 'utf8')).toBe(NEWER_TEXT) + }) + + it('is not reported out of date or downgraded by an older build, until the user edits it', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, OLD_TEXT) + await previewAndInstall(asBuild(home, NEWER_SOURCE)) + + const plan = await previewBundledSkillInstall(asBuild(home, NEW_SOURCE)) + expect(plan.skills[0].ops.map((op) => [op.kind, op.reason])).toEqual([ + ['leave', 'other-build'], + // Claude's link into the shared copy is already right. + ['keep', undefined] + ]) + // Replacing it may downgrade it, so the dialog and setup button never offer to. + expect(plan.skills[0].ops[0].replaceable).toBe(false) + // Setup counts it as installed: nothing to run, replace or fix. + expect(bundledSkillInstallAction(plan)).toEqual({ kind: 'none' }) + expect(bundledSkillPlanState(plan.skills[0])).toBe('current') + expect(bundledSkillNudgeEntries(plan)).toEqual([]) + expect(bundledSkillNudgeKey('local', plan)).toBeNull() + + await autoUpdateInstalledBundledSkills({ ...asBuild(home, NEW_SOURCE), names: [NAME] }) + expect(await readFile(join(home.shared, 'SKILL.md'), 'utf8')).toBe(NEWER_TEXT) + + // The record lives on the planned host's home: the same bytes no Orca wrote elsewhere still count as an edit. + const elsewhere = await makeSkillHome() + await writeCopy(elsewhere.shared, NEWER_TEXT) + const elsewherePlan = await previewBundledSkillInstall(asBuild(elsewhere, NEW_SOURCE)) + expect(elsewherePlan.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'edited' }) + + await appendFile(join(home.shared, 'SKILL.md'), '\nmy note\n') + const edited = await previewBundledSkillInstall(asBuild(home, NEW_SOURCE)) + expect(edited.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'edited' }) + expect(bundledSkillNudgeEntries(edited).map((entry) => entry.name)).toEqual([NAME]) + }) + + it("marks a copy already at the build's own digest when its keep-only update runs", async () => { + const home = await makeSkillHome() + // Written before markers existed; the build that owns these bytes sees it as current. + await writeCopy(home.shared, NEW_TEXT) + expect(await hasMarker(home, NEW_TEXT)).toBe(false) + + const result = await autoUpdateAs(home, NEW_SOURCE) + expect(result.skills).toEqual([]) + expect(await hasMarker(home, NEW_TEXT)).toBe(true) + + const plan = await previewBundledSkillInstall(asBuild(home, DEV_SOURCE)) + expect(plan.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'other-build' }) + expect(bundledSkillNudgeEntries(plan)).toEqual([]) + }) + + it("is not reported out of date when another build installed it under the skill's former name", async () => { + const home = await makeSkillHome() + const FORMER_NAME = 'former-test-skill' + const FORMER_DEV_TEXT = `---\nname: ${FORMER_NAME}\ndescription: Dev\n---\n\nFormer dev body\n` + // A build from before the rename, whose text the renamed build never shipped. + const formerBuild = asBuild(home, { + name: FORMER_NAME, + text: FORMER_DEV_TEXT, + releasedDigests: [digest(FORMER_DEV_TEXT)] + }) + await previewAndInstall(formerBuild) + + const renamed = asBuild(home, { ...NEW_SOURCE, aliases: [FORMER_NAME] }) + const plan = await previewBundledSkillInstall({ ...renamed, installedOnly: true }) + expect(plan.skills.flatMap((skill) => skill.ops.map((op) => op.reason))).not.toContain('edited') + expect(bundledSkillNudgeEntries(plan)).toEqual([]) + + // A user edit to that former-name copy is still asked about. + await appendFile(join(home.home, '.agents', 'skills', FORMER_NAME, 'SKILL.md'), '\nmy note\n') + const edited = await previewBundledSkillInstall({ ...renamed, installedOnly: true }) + expect(bundledSkillNudgeEntries(edited).map((entry) => entry.name)).toEqual([NAME]) + }) + + it('records a current copy on a record-only request but never updates a released one', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEW_TEXT) + const recordOnly = { ...asBuild(home, NEW_SOURCE), names: [NAME], recordOnly: true } + + expect((await autoUpdateInstalledBundledSkills(recordOnly)).skills).toEqual([]) + expect(await hasMarker(home, NEW_TEXT)).toBe(true) + + // A copy at an older release text would be silently updated, but not by a record-only request. + await writeCopy(home.shared, OLD_TEXT) + expect((await autoUpdateInstalledBundledSkills(recordOnly)).skills).toEqual([]) + expect(await readFile(join(home.shared, 'SKILL.md'), 'utf8')).toBe(OLD_TEXT) + expect(await hasMarker(home, OLD_TEXT)).toBe(false) + }) + + it('writes no marker from a preview alone', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEW_TEXT) + + await previewBundledSkillInstall(asBuild(home, NEW_SOURCE)) + expect(await hasMarker(home, NEW_TEXT)).toBe(false) + const plan = await previewBundledSkillInstall(asBuild(home, DEV_SOURCE)) + expect(plan.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'edited' }) + }) + + it("records a paired server's marker on the server's own disk, never the client's", async () => { + const client = await makeSkillHome() + const server = await makeSkillHome() + await writeCopy(client.shared, NEW_TEXT) + await writeCopy(server.shared, NEW_TEXT) + + // The server runs its own keep-only update against its own home. + await autoUpdateAs(server, NEW_SOURCE) + expect(await hasMarker(server, NEW_TEXT)).toBe(true) + expect(await hasMarker(client, NEW_TEXT)).toBe(false) + + const serverPlan = await previewBundledSkillInstall(asBuild(server, DEV_SOURCE)) + const clientPlan = await previewBundledSkillInstall(asBuild(client, DEV_SOURCE)) + expect(serverPlan.skills[0].ops[0]).toMatchObject({ reason: 'other-build' }) + expect(clientPlan.skills[0].ops[0]).toMatchObject({ reason: 'edited' }) + }) +}) diff --git a/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts b/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts index 5e77eda552f..d18609ed54d 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts @@ -8,7 +8,10 @@ import type { BundledSkillOutcome, BundledSkillPlanEntry } from '../../../shared/bundled-skill-plan' -import { isBundledSkillAutoUpdateOp } from '../../../shared/bundled-skill-summary' +import { + holdsCurrentBundledSkillCopy, + isBundledSkillAutoUpdateOp +} from '../../../shared/bundled-skill-summary' import type { BundledSkillSource } from './bundled-skill-sources' import { classifyBundledSkillPath } from './bundled-skill-classification' import { filesystemErrorCode } from './bundled-skill-filesystem-error' @@ -25,6 +28,7 @@ import { } from './bundled-skill-folder-swap' import { findBundledSkillSource } from './bundled-skill-source-selection' import { withBundledSkillTargetLocks } from './bundled-skill-target-locks' +import { recordBundledSkillDigestWritten } from './bundled-skill-written-digests' export type BundledSkillExecuteInput = BundledSkillPlanInput & { /** Per-lock wait; the shared 5s default applies when unset. */ @@ -116,7 +120,12 @@ async function applyContent(run: SkillRun, op: BundledSkillOp): Promise { const statuses = new Map() const ops: BundledSkillOpOutcome[] = [] @@ -211,9 +221,28 @@ async function runSkill(run: SkillRun): Promise { statuses.set(op.path, outcome.strandedPath ? 'done' : outcome.status) ops.push(outcome) } + if ( + holdsCurrentBundledSkillCopy(run.entry) || + run.entry.ops.some((op) => op.content === 'files' && statuses.get(op.path) === 'done') + ) { + await recordOrcaCopy(run.input, run.entry) + } return { name: run.entry.name, status: 'ran', ops } } +/** + * Lets other Orca builds on this host recognise these bytes as Orca's, not a user edit. + * Execution only: preview stays read-only. + */ +function recordOrcaCopy(input: BundledSkillExecuteInput, entry: BundledSkillPlanEntry) { + return recordBundledSkillDigestWritten( + input.filesystem, + input.destination.homeDirectory, + entry.name, + entry.digest + ) +} + /** Re-plan under all target locks and require the previewed digest; stale previews must write nothing. */ export async function executeBundledSkillPlan( input: BundledSkillExecuteInput, @@ -242,10 +271,11 @@ export async function executeBundledSkillPlan( /** * Plans each named installed skill under its locks and applies only hash-verified released-copy * updates; edited, foreign or interrupted locations are never touched. Each write re-checks its - * location, and one skill's failure leaves the others' outcomes intact. + * location, and one skill's failure leaves the others' outcomes intact. `recordOnly` skips every + * update and only records copies that already hold this build's bytes. */ export async function autoUpdateBundledSkills( - input: BundledSkillExecuteInput & { names: readonly string[] } + input: BundledSkillExecuteInput & { names: readonly string[]; recordOnly?: boolean } ): Promise { const unrun = (status: 'changed' | 'busy'): BundledSkillInstallResult => ({ scope: input.destination.scope, @@ -258,12 +288,22 @@ export async function autoUpdateBundledSkills( const safe = entry.ops.filter(isBundledSkillAutoUpdateOp) const required = new Set(safe.flatMap((op) => (op.requires ? [op.requires] : []))) const ops = entry.ops.filter( - (op) => safe.includes(op) || (op.kind === 'keep' && required.has(op.path)) + (op) => + safe.includes(op) || + (required.has(op.path) && + (op.kind === 'keep' || + (op.kind === 'leave' && + op.reason === 'other-build' && + op.cleanup.every((item) => item.action === 'delete')))) ) - if (ops.length > 0) { + if (ops.length > 0 && !input.recordOnly) { const source = findBundledSkillSource(input.sources, entry.name) skills.push(await runSkill({ input, entry: { ...entry, ops }, source })) } + // An already-current copy (keep-only, so nothing ran) written before markers existed. + if (holdsCurrentBundledSkillCopy(entry)) { + await recordOrcaCopy(input, entry) + } } return { scope: plan.scope, skills } }) diff --git a/src/main/skills/bundled-skill-install/bundled-skill-plan.ts b/src/main/skills/bundled-skill-install/bundled-skill-plan.ts index ecf4fe428bb..8cce67ecb15 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-plan.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-plan.ts @@ -1,5 +1,5 @@ import { bundledSkillDigestOf } from './bundled-skill-plan-identity' -import { dirname, join, resolve } from 'node:path' +import { join } from 'node:path' import type { BundledSkillOp, BundledSkillPlan, @@ -20,9 +20,10 @@ import type { BundledSkillFilesystem } from './bundled-skill-filesystem' import { recoverySiblings } from './bundled-skill-swap-recovery' import { findBundledSkillSource } from './bundled-skill-source-selection' import { planFormerSkillPlacements } from './renamed-skill-placement' +import { isOtherBuildCopy } from './bundled-skill-written-digests' import { bundledSkillPathKey, - resolveBundledSkillRealPath, + linkPointsAt, resolveBundledSkillTargets, type BundledSkillTargetRequest, type BundledSkillTargetRoot @@ -54,7 +55,8 @@ type SkillContext = { sharedRoot?: BundledSkillTargetRoot } -type SharedTarget = { path: string; realPath: string; current: boolean } +// `otherBuild`: the shared folder holds another Orca build's copy, so links to it are already right. +type SharedTarget = { path: string; realPath: string; current: boolean; otherBuild?: boolean } const WRITES_SHARED_CURRENT = new Set([ 'keep', @@ -63,18 +65,6 @@ const WRITES_SHARED_CURRENT = new Set([ 'replace' ]) -async function linkPointsAt( - filesystem: BundledSkillFilesystem, - path: string, - rawTarget: string, - realPath: string -): Promise { - const resolved = - (await filesystem.realpath(path)) ?? - resolve(await resolveBundledSkillRealPath(filesystem, dirname(path)), rawTarget) - return bundledSkillPathKey(resolved) === bundledSkillPathKey(realPath) -} - type PlannedTarget = { op: BundledSkillOp holdsOrcaCopy: boolean @@ -82,8 +72,16 @@ type PlannedTarget = { leaves: BundledSkillOp[] } -const ORCA_COPY_CLASSES = new Set(['current', 'released', 'edited']) +type PlannedFolderClass = BundledSkillFolderClass | 'other-build' +const ORCA_COPY_CLASSES = new Set([ + 'current', + 'released', + 'edited', + 'other-build' +]) + +/** Classifies one root's copy of the skill and decides its op, including another build's copy. */ async function planTarget( context: SkillContext, root: BundledSkillTargetRoot, @@ -108,13 +106,19 @@ async function planTarget( context.digest, context.sharedRoot ) - let folderClass: BundledSkillFolderClass = classified.folderClass + let folderClass: PlannedFolderClass = classified.folderClass // Cloud receipts identify a different package; a current replaced copy must settle as keep. if ( (folderClass === 'released' || folderClass === 'edited') && (await hasCloudReceipt(stateDirectory, stateKeys)) ) { folderClass = 'other' + } else if ( + folderClass === 'edited' && + (await isOtherBuildCopy(filesystem, context.input.destination, context.source, observed)) + ) { + // A newer build's bytes are unknown here; never call them stale or offer to downgrade them. + folderClass = 'other-build' } const { restoreFrom, cleanup } = await recoverySiblings( filesystem, @@ -158,14 +162,12 @@ async function planTarget( if (!shared) { return files('write') } - if (!shared.current && former.installed) { - return files('write') - } - if (!shared.current) { - return leave('shared-not-current', false) + if (!shared.current && !(shared.otherBuild && filesystem.supportsLinks)) { + return former.installed ? files('write') : leave('shared-not-current', false) } return filesystem.supportsLinks ? linkToShared('link', shared) : files('copy') case 'edited': + case 'other-build': case 'other': break } @@ -174,12 +176,15 @@ async function planTarget( observed.kind === 'link' && (await linkPointsAt(filesystem, path, observed.target, shared.realPath)) ) { - return shared.current + return shared.current || shared.otherBuild ? { ...base, kind: 'keep', cleanup } : leave('shared-not-current', false) } if (context.force !== 'all' && !context.force.has(bundledSkillPathKey(path))) { - return leave(folderClass === 'edited' ? 'edited' : 'other', true) + // Replacing another build's copy may downgrade it, so only an explicit --force offers that. + return folderClass === 'other-build' + ? leave('other-build', false) + : leave(folderClass === 'edited' ? 'edited' : 'other', true) } return shared?.current && filesystem.supportsLinks ? linkToShared('replace', shared) @@ -224,6 +229,7 @@ async function planTarget( } } +/** Plans the shared root first, then agent roots, which may link to the shared copy. */ async function planSkill( input: BundledSkillPlanInput, roots: readonly BundledSkillTargetRoot[], @@ -244,7 +250,8 @@ async function planSkill( ? { path: sharedTarget.op.path, realPath: join(sharedRoot.realPath, source.name), - current: WRITES_SHARED_CURRENT.has(sharedTarget.op.kind) + current: WRITES_SHARED_CURRENT.has(sharedTarget.op.kind), + otherBuild: sharedTarget.op.reason === 'other-build' } : null const planAgents = async (target: SharedTarget | null) => { diff --git a/src/main/skills/bundled-skill-install/bundled-skill-targets.ts b/src/main/skills/bundled-skill-install/bundled-skill-targets.ts index 8a43cfc0d64..653c60643b3 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-targets.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-targets.ts @@ -111,3 +111,16 @@ export async function resolveBundledSkillTargets( } return [...roots.values()] } + +/** Whether the link at `path` (raw target `rawTarget`) resolves to `realPath`. */ +export async function linkPointsAt( + filesystem: BundledSkillFilesystem, + path: string, + rawTarget: string, + realPath: string +): Promise { + const resolved = + (await filesystem.realpath(path)) ?? + resolve(await resolveBundledSkillRealPath(filesystem, dirname(path)), rawTarget) + return bundledSkillPathKey(resolved) === bundledSkillPathKey(realPath) +} diff --git a/src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts b/src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts new file mode 100644 index 00000000000..d505db57c9a --- /dev/null +++ b/src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts @@ -0,0 +1,64 @@ +import { join } from 'node:path' +import type { BundledSkillObserved } from '../../../shared/bundled-skill-plan' +import type { BundledSkillFilesystem } from './bundled-skill-filesystem' + +const SHA256_HEX = /^[0-9a-f]{64}$/u + +/** + * Why on the planned host's disk, not in userData: every Orca build on a host (installed app, + * dev builds, a CLI, a paired server) shares one skills folder but has its own userData. A build + * reads what the others wrote, so a copy a newer build installed is not mistaken for a user edit. + */ +function writtenDigestPath(homeDirectory: string, name: string, digest: string): string { + return join(homeDirectory, '.agents', '.orca-skill-digests', name, digest) +} + +/** Whether some Orca build on this host installed `SKILL.md` text with this digest. */ +export async function wasBundledSkillDigestWritten( + filesystem: BundledSkillFilesystem, + homeDirectory: string, + name: string, + digest: string +): Promise { + if (!SHA256_HEX.test(digest)) { + return false + } + const stat = await filesystem.stat(writtenDigestPath(homeDirectory, name, digest)) + return stat?.kind === 'directory' +} + +/** One empty marker folder per digest: idempotent, append-only, and safe for concurrent builds. */ +export async function recordBundledSkillDigestWritten( + filesystem: BundledSkillFilesystem, + homeDirectory: string, + name: string, + digest: string +): Promise { + if (!SHA256_HEX.test(digest)) { + return + } + // Best effort: a missing marker only means another build may ask about this copy once. + await filesystem + .ensureDirectory(writtenDigestPath(homeDirectory, name, digest)) + .catch(() => undefined) +} + +/** An unknown single-file copy whose bytes some Orca build on this host wrote: not a user edit. */ +export async function isOtherBuildCopy( + filesystem: BundledSkillFilesystem, + destination: { homeDirectory: string }, + source: { name: string }, + observed: BundledSkillObserved +): Promise { + return ( + observed.kind === 'folder' && + observed.entries.length === 1 && + observed.skillDigest !== null && + (await wasBundledSkillDigestWritten( + filesystem, + destination.homeDirectory, + source.name, + observed.skillDigest + )) + ) +} diff --git a/src/main/skills/bundled-skill-install/renamed-skill-placement.ts b/src/main/skills/bundled-skill-install/renamed-skill-placement.ts index 9cf51ce3ba1..3e681b8cfb1 100644 --- a/src/main/skills/bundled-skill-install/renamed-skill-placement.ts +++ b/src/main/skills/bundled-skill-install/renamed-skill-placement.ts @@ -9,6 +9,7 @@ import { import { classifyBundledSkillPath } from './bundled-skill-classification' import type { BundledSkillPlanInput } from './bundled-skill-plan' import { recoverySiblings } from './bundled-skill-swap-recovery' +import { isOtherBuildCopy } from './bundled-skill-written-digests' import { bundledSkillPathKey, type BundledSkillTargetRoot } from './bundled-skill-targets' export async function planFormerSkillPlacements( @@ -80,9 +81,13 @@ export async function planFormerSkillPlacements( reason ?? (observed.kind === 'unreadable' ? 'unreadable' - : classified.folderClass === 'edited' - ? 'edited' - : 'other') + : classified.folderClass !== 'edited' + ? 'other' + : // A build from before the rename recorded these bytes under the former name. + !cloud && + (await isOtherBuildCopy(filesystem, input.destination, { name }, observed)) + ? 'other-build' + : 'edited') }) continue } diff --git a/src/main/skills/cloud/skill-cloud-grant-installation.test.ts b/src/main/skills/cloud/skill-cloud-grant-installation.test.ts index 2e6e674de9d..cd7cf310f6e 100644 --- a/src/main/skills/cloud/skill-cloud-grant-installation.test.ts +++ b/src/main/skills/cloud/skill-cloud-grant-installation.test.ts @@ -20,7 +20,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('electron', () => ({ app: { getPath: () => '/state', isPackaged: true } })) -vi.mock('../../ipc/runtime-environments/runtime-environment-status-probe', () => ({ +vi.mock('../../ipc/runtime-environments/status/runtime-environment-status-probe', () => ({ getRuntimeEnvironmentStatus: mocks.getRuntimeEnvironmentStatus })) vi.mock('../runtime-transfer/skill-remote-installation', () => ({ diff --git a/src/main/skills/cloud/skill-cloud-grant-installation.ts b/src/main/skills/cloud/skill-cloud-grant-installation.ts index 1823fde289c..0ff4073e025 100644 --- a/src/main/skills/cloud/skill-cloud-grant-installation.ts +++ b/src/main/skills/cloud/skill-cloud-grant-installation.ts @@ -14,7 +14,7 @@ import type { SkillInstallRequest } from '../../../shared/skill-install-contract' import type { SkillCloudDownloadGrant } from '../../../shared/skill-cloud-contract' -import { getRuntimeEnvironmentStatus } from '../../ipc/runtime-environments/runtime-environment-status-probe' +import { getRuntimeEnvironmentStatus } from '../../ipc/runtime-environments/status/runtime-environment-status-probe' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { skillInstallFailureFromError } from '../install/skill-install-operation-error' import { recordSkillCapabilityAbsence } from '../observability/skill-operation-observability' diff --git a/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts b/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts deleted file mode 100644 index 74a81dc0efa..00000000000 --- a/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseWslClaudePluginMetadataOutput } from './claude-plugin-skill-sources-wsl' - -function record(...fields: string[]): string { - return `${fields.join('\0')}\0` -} - -describe('WSL Claude plugin metadata', () => { - it('rejects malformed metadata responses', () => { - expect(() => parseWslClaudePluginMetadataOutput(record('F', '4', '1', ''), 1)).toThrow( - 'invalid response' - ) - }) -}) diff --git a/src/main/skills/install/skill-installation.test.ts b/src/main/skills/install/skill-installation.test.ts index 4390dd339b9..43886af7c4e 100644 --- a/src/main/skills/install/skill-installation.test.ts +++ b/src/main/skills/install/skill-installation.test.ts @@ -27,24 +27,6 @@ describe('skill install service', () => { expect(await readFile(join(claude, 'SKILL.md'), 'utf8')).toBe('unowned') }) - it('removes an owned placement when its provider is deselected', async () => { - const { root, input } = await createSkillInstallHome() - await installSharedSkill(input) - const claude = join(root, 'home', '.claude', 'skills', 'test-skill') - - const updated = await installSharedSkill({ - ...input, - operationId: 'operation_without_claude', - detectedProviders: ['codex'] - }) - - expect(updated.status).toBe('unchanged') - await expect(lstat(claude)).rejects.toMatchObject({ code: 'ENOENT' }) - expect(updated.placements).toEqual([ - expect.objectContaining({ provider: 'agent-skills', topology: 'canonical-copy' }) - ]) - }) - it('preserves the committed canonical install when cancellation reaches provider placement', async () => { const { root, input } = await createSkillInstallHome() const controller = new AbortController() diff --git a/src/main/skills/runtime-transfer/skill-client-mediated-transfer.test.ts b/src/main/skills/runtime-transfer/skill-client-mediated-transfer.test.ts index f142f28c06c..3f56b44205c 100644 --- a/src/main/skills/runtime-transfer/skill-client-mediated-transfer.test.ts +++ b/src/main/skills/runtime-transfer/skill-client-mediated-transfer.test.ts @@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({ downloadSkillPackageGrant: vi.fn() })) -vi.mock('../../ipc/runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../../ipc/runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: mocks.callRuntimeEnvironment })) vi.mock('../package-download/skill-package-download', () => ({ diff --git a/src/main/skills/runtime-transfer/skill-client-mediated-transfer.ts b/src/main/skills/runtime-transfer/skill-client-mediated-transfer.ts index 71df5ee1ab0..d201ef0c84e 100644 --- a/src/main/skills/runtime-transfer/skill-client-mediated-transfer.ts +++ b/src/main/skills/runtime-transfer/skill-client-mediated-transfer.ts @@ -7,7 +7,7 @@ import { SKILL_UPLOAD_CHUNK_MAX_BYTES, SkillUploadBeginResultSchema } from '../../../shared/skill-upload-session-contract' -import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/requests/runtime-environment-transport-routing' import { downloadSkillPackageGrant } from '../package-download/skill-package-download' import { startSkillPhaseOperation } from '../observability/skill-operation-observability' import { retrySkillTransferRpc, throwIfSkillTransferCancelled } from './skill-transfer-rpc-retry' diff --git a/src/main/skills/runtime-transfer/skill-remote-installation.ts b/src/main/skills/runtime-transfer/skill-remote-installation.ts index 0604bd1305e..8609511dca9 100644 --- a/src/main/skills/runtime-transfer/skill-remote-installation.ts +++ b/src/main/skills/runtime-transfer/skill-remote-installation.ts @@ -18,7 +18,7 @@ import { SKILL_INSTALL_PROVIDERS_CAPABILITY, SKILL_UPLOAD_CAPABILITY } from '../../../shared/skill-install-capability' -import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/requests/runtime-environment-transport-routing' import { transferSkillPackageToRuntime } from './skill-client-mediated-transfer' import { SkillInstallFailureSchema } from '../../../shared/skill-install-failure' import { SkillInstallOperationError } from '../install/skill-install-operation-error' diff --git a/src/main/skills/runtime-transfer/skill-runtime-capability.ts b/src/main/skills/runtime-transfer/skill-runtime-capability.ts index f53ed73b451..ac07c0a8786 100644 --- a/src/main/skills/runtime-transfer/skill-runtime-capability.ts +++ b/src/main/skills/runtime-transfer/skill-runtime-capability.ts @@ -4,7 +4,7 @@ import { SKILL_INSTALL_CAPABILITY, SKILL_MANAGEMENT_CAPABILITY } from '../../../shared/skill-install-capability' -import { getRuntimeEnvironmentStatus } from '../../ipc/runtime-environments/runtime-environment-status-probe' +import { getRuntimeEnvironmentStatus } from '../../ipc/runtime-environments/status/runtime-environment-status-probe' export async function supportsSkillRuntimeManagement( userDataPath: string, diff --git a/src/main/source-control/forge-provider.ts b/src/main/source-control/forge-provider.ts index cf4f4b9ba1a..46ed21b53f7 100644 --- a/src/main/source-control/forge-provider.ts +++ b/src/main/source-control/forge-provider.ts @@ -23,12 +23,10 @@ import { getGiteaRepoSlug } from '../gitea/client' import { createGiteaPullRequest } from '../gitea/pull-request-creation' -import { - createGitHubPullRequest, - getGitHubPRLookupRateLimitBlock, - getPRForBranchOutcome, - getRepoSlug -} from '../github/client' +import { createGitHubPullRequest } from '../github/client/create/create-github-pull-request' +import { getGitHubPRLookupRateLimitBlock } from '../github/client/lookup/pr-lookup-rate-limit' +import { getPRForBranchOutcome } from '../github/client/lookup/pr-for-branch-outcome' +import { getRepoSlug } from '../github/client/fetch/repo-slug-upstream' import { getMergeRequest, getMergeRequestForBranchOrThrow, diff --git a/src/main/source-control/forge-review-mappers.ts b/src/main/source-control/forge-review-mappers.ts index 7a3cede98a7..be4598a8070 100644 --- a/src/main/source-control/forge-review-mappers.ts +++ b/src/main/source-control/forge-review-mappers.ts @@ -1,6 +1,6 @@ import type { HostedReviewInfo } from '../../shared/source-control/hosted-review/hosted-review-contracts' import { hostedReviewInfoFromGitHubPRInfo } from '../../shared/source-control/hosted-review/hosted-review-github' -import type { PRInfo } from '../../shared/github/pull-request-types' +import type { PRInfo } from '../../shared/github/pull-requests/pull-request-types' import type { MRInfo } from '../../shared/gitlab-types' import type { AzureDevOpsPullRequestInfo } from '../azure-devops/pull-request-mappers' import type { BitbucketPullRequestInfo } from '../bitbucket/pull-request-mappers' diff --git a/src/main/source-control/hosted-review-base-ref-suffix.test.ts b/src/main/source-control/hosted-review-base-ref-suffix.test.ts index 7de6024d0da..d07f256ac84 100644 --- a/src/main/source-control/hosted-review-base-ref-suffix.test.ts +++ b/src/main/source-control/hosted-review-base-ref-suffix.test.ts @@ -4,7 +4,8 @@ const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) -vi.mock('../github/gh-utils', () => ({ +vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) diff --git a/src/main/source-control/hosted-review-branch-cache.test.ts b/src/main/source-control/hosted-review-branch-cache.test.ts index e833fa2dfca..7058e91a3e0 100644 --- a/src/main/source-control/hosted-review-branch-cache.test.ts +++ b/src/main/source-control/hosted-review-branch-cache.test.ts @@ -2,16 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { HostedReviewInfo } from '../../shared/source-control/hosted-review/hosted-review-contracts' import { __resetHostedReviewBranchCacheForTests, - invalidateHostedReviewBranchCache, withHostedReviewBranchCache } from './hosted-review-branch-cache' import { HOSTED_REVIEW_LOOKUP_DEADLINE_MS, LOOKUP_BACKOFF_MAX_MS, - MAX_BRANCH_MAP_ENTRIES, - MAX_DETACHED_LOOKUPS, - MAX_INFLIGHT_LOOKUPS, - MAX_UNSETTLED_LOOKUP_KEYS, MAX_UNSETTLED_LOOKUPS_PER_KEY } from './hosted-review-refresh-pacing' @@ -31,29 +26,6 @@ function stuckLookup() { return { lookup, resolve: (review) => resolve(review), reject: (error) => reject(error) } } -/** Evict by size alone, leaving an untimed-out straggler behind a replacement owner. */ -function evictInflightRecord(evictedLookup: () => Promise) { - const swallow = (promise: Promise): void => { - void promise.catch(() => {}) - } - swallow(withHostedReviewBranchCache(identity, { headOid: null }, evictedLookup)) - - const filler = stuckLookup() - for (let index = 0; index < MAX_INFLIGHT_LOOKUPS; index += 1) { - swallow( - withHostedReviewBranchCache( - { ...identity, branch: `feature/${index}` }, - { headOid: null }, - filler.lookup - ) - ) - } - - const successor = stuckLookup() - const request = withHostedReviewBranchCache(identity, { headOid: null }, successor.lookup) - return { request, resolve: successor.resolve, reject: successor.reject } -} - const openReview: HostedReviewInfo = { provider: 'github', number: 7, @@ -78,341 +50,7 @@ describe('hosted review branch cache (#11532)', () => { vi.useRealTimers() }) - it('bypasses a merged result for an explicit refresh', async () => { - const lookup = vi.fn(async () => mergedReview) - await withHostedReviewBranchCache(identity, { headOid: 'aaa' }, lookup) - lookup.mockResolvedValue(openReview) - await expect( - withHostedReviewBranchCache(identity, { headOid: 'aaa', force: true }, lookup) - ).resolves.toEqual(openReview) - expect(lookup).toHaveBeenCalledTimes(2) - }) - - it('collapses concurrent callers onto one lookup', async () => { - let resolveLookup: (value: HostedReviewInfo | null) => void = () => {} - const lookup = vi.fn( - () => - new Promise((resolve) => { - resolveLookup = resolve - }) - ) - - const first = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - const second = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - resolveLookup(openReview) - - await expect(first).resolves.toEqual(openReview) - await expect(second).resolves.toEqual(openReview) - expect(lookup).toHaveBeenCalledTimes(1) - }) - - it('separates lookups that differ only by linked review number', async () => { - const lookup = vi.fn(async () => null) - - await withHostedReviewBranchCache({ ...identity, linkedGitHubPR: 1 }, { headOid: null }, lookup) - await withHostedReviewBranchCache({ ...identity, linkedGitHubPR: 2 }, { headOid: null }, lookup) - - expect(lookup).toHaveBeenCalledTimes(2) - }) - - it('backs a failing branch off instead of re-asking every poll', async () => { - const lookup = vi.fn(async () => { - throw new Error('rate limited') - }) - - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).rejects.toThrow( - 'rate limited' - ) - vi.setSystemTime(1_000_000 + 30_000) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).rejects.toThrow( - /backing off/ - ) - expect(lookup).toHaveBeenCalledTimes(1) - - vi.setSystemTime(1_000_000 + 60_001) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).rejects.toThrow( - 'rate limited' - ) - expect(lookup).toHaveBeenCalledTimes(2) - - vi.setSystemTime(1_000_000 + 60_001 + 60_000) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).rejects.toThrow( - /backing off/ - ) - expect(lookup).toHaveBeenCalledTimes(2) - }) - - it('serves the last known review from the failure itself, not only the backoff', async () => { - const lookup = vi - .fn<() => Promise>() - .mockResolvedValueOnce(openReview) - .mockRejectedValueOnce(new Error('transient')) - - await withHostedReviewBranchCache(identity, { headOid: null }, lookup) - vi.setSystemTime(1_000_000 + 60_001) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - openReview - ) - - vi.setSystemTime(1_000_000 + 60_001 + 1_000) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - openReview - ) - expect(lookup).toHaveBeenCalledTimes(2) - }) - - it('resets the escalation once a lookup succeeds', async () => { - const lookup = vi - .fn<() => Promise>() - .mockRejectedValueOnce(new Error('first')) - .mockResolvedValueOnce(openReview) - .mockRejectedValueOnce(new Error('second')) - .mockResolvedValue(mergedReview) - - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).rejects.toThrow( - 'first' - ) - vi.setSystemTime(1_000_000 + 60_001) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - openReview - ) - - // Success resets escalation; the next failed refresh starts at base even when serving stale data. - vi.setSystemTime(1_000_000 + 2 * 60_001) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - openReview - ) - vi.setSystemTime(1_000_000 + 3 * 60_001) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - mergedReview - ) - expect(lookup).toHaveBeenCalledTimes(4) - }) - - it('retires a cached no-review answer when Orca opens a review', async () => { - const lookup = vi - .fn<() => Promise>() - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(openReview) - - await withHostedReviewBranchCache(identity, { headOid: null }, lookup) - invalidateHostedReviewBranchCache('/repo', 'local') - - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - openReview - ) - expect(lookup).toHaveBeenCalledTimes(2) - }) - - it('discards a lookup that was already in flight when Orca opened a review', async () => { - let resolveLookup: (value: HostedReviewInfo | null) => void = () => {} - const lookup = vi - .fn<() => Promise>() - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveLookup = resolve - }) - ) - .mockResolvedValue(openReview) - - const inflight = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - invalidateHostedReviewBranchCache('/repo', 'local') - // Creation invalidation outranks this pre-review lookup's stale null. - resolveLookup(null) - await expect(inflight).resolves.toBeNull() - - await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( - openReview - ) - expect(lookup).toHaveBeenCalledTimes(2) - }) - - it('leaves another repo in-flight lookup cacheable across an invalidation', async () => { - let resolveLookup: (value: HostedReviewInfo | null) => void = () => {} - const other = { ...identity, repoPath: '/other' } - const lookup = vi.fn<() => Promise>().mockImplementationOnce( - () => - new Promise((resolve) => { - resolveLookup = resolve - }) - ) - - const inflight = withHostedReviewBranchCache(other, { headOid: null }, lookup) - invalidateHostedReviewBranchCache('/repo', 'local') - resolveLookup(null) - await inflight - - await withHostedReviewBranchCache(other, { headOid: null }, lookup) - expect(lookup).toHaveBeenCalledTimes(1) - }) - - it('scopes invalidation to one repo', async () => { - const lookup = vi.fn(async () => null) - - await withHostedReviewBranchCache(identity, { headOid: null }, lookup) - await withHostedReviewBranchCache( - { ...identity, repoPath: '/other' }, - { headOid: null }, - lookup - ) - expect(lookup).toHaveBeenCalledTimes(2) - - invalidateHostedReviewBranchCache('/other', 'local') - - await withHostedReviewBranchCache(identity, { headOid: null }, lookup) - expect(lookup).toHaveBeenCalledTimes(2) - await withHostedReviewBranchCache( - { ...identity, repoPath: '/other' }, - { headOid: null }, - lookup - ) - expect(lookup).toHaveBeenCalledTimes(3) - }) - - it('keeps SSH and local repos with the same path apart', async () => { - const lookup = vi.fn(async () => null) - - await withHostedReviewBranchCache(identity, { headOid: null }, lookup) - await withHostedReviewBranchCache( - { ...identity, executionHostId: 'ssh:ssh-1' as const }, - { headOid: null }, - lookup - ) - - expect(lookup).toHaveBeenCalledTimes(2) - }) - - describe('selected-worktree tier', () => { - it('caps the fast tier so a caller cannot promote a whole list', async () => { - const lookup = vi.fn(async () => null) - const branchAt = (index: number) => ({ ...identity, branch: `feature/${index}` }) - - for (let index = 0; index <= 8; index += 1) { - await withHostedReviewBranchCache(branchAt(index), { headOid: null, active: true }, lookup) - } - expect(lookup).toHaveBeenCalledTimes(9) - - vi.setSystemTime(1_000_000 + 60_001) - await withHostedReviewBranchCache(branchAt(0), { headOid: null }, lookup) - expect(lookup).toHaveBeenCalledTimes(9) - await withHostedReviewBranchCache(branchAt(8), { headOid: null }, lookup) - expect(lookup).toHaveBeenCalledTimes(10) - }) - }) - describe('in-flight deadline (P1-D)', () => { - it('releases a stuck lookup at the deadline instead of pinning the branch', async () => { - const { lookup } = stuckLookup() - - const request = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - const rejects = expect(request).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await rejects - - await expect( - withHostedReviewBranchCache(identity, { headOid: null }, lookup) - ).rejects.toThrow(/backing off/) - expect(lookup).toHaveBeenCalledTimes(1) - }) - - it('lets a later poll succeed after a lookup times out', async () => { - const { lookup } = stuckLookup() - - const rejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await rejects - - await vi.advanceTimersByTimeAsync(60_001) - const recovered = vi.fn(async () => openReview) - await expect( - withHostedReviewBranchCache(identity, { headOid: null }, recovered) - ).resolves.toEqual(openReview) - expect(recovered).toHaveBeenCalledTimes(1) - }) - - it('keeps the last known review when a refresh times out', async () => { - await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) - vi.setSystemTime(START + 60_001) - - const { lookup } = stuckLookup() - const request = withHostedReviewBranchCache(identity, { headOid: null }, lookup) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - - await expect(request).resolves.toEqual(openReview) - }) - - it('adopts a lookup that lands after its deadline', async () => { - const { lookup, resolve } = stuckLookup() - - const rejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await rejects - - resolve(openReview) - await vi.advanceTimersByTimeAsync(0) - - // Late answers still spent quota; adopt them when safe so slow hosts can converge. - const next = vi.fn(async () => null) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( - openReview - ) - expect(next).not.toHaveBeenCalled() - }) - - it('keeps escalating when a lookup only ever answers past its deadline', async () => { - const first = stuckLookup() - const firstRejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, first.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await firstRejects - - // A second timeout backs off longer than found-review TTL, exposing escalation. - await vi.advanceTimersByTimeAsync(60_001) - const second = stuckLookup() - const secondRejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, second.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await secondRejects - - second.resolve(openReview) - await vi.advanceTimersByTimeAsync(0) - - // Adopt safe late data without treating missed deadlines as provider recovery. - await vi.advanceTimersByTimeAsync(60_001) - const recovered = vi.fn(async () => mergedReview) - await expect( - withHostedReviewBranchCache(identity, { headOid: null }, recovered) - ).resolves.toEqual(openReview) - expect(recovered).not.toHaveBeenCalled() - }) - - it('does not let a timed-out null wipe the open review it was refreshing', async () => { - await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) - await vi.advanceTimersByTimeAsync(60_001) - - const stale = stuckLookup() - const request = withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await expect(request).resolves.toEqual(openReview) - - stale.resolve(null) - await vi.advanceTimersByTimeAsync(0) - - // A timed-out refresh must not replace its served answer with a long-lived null. - const next = vi.fn(async () => openReview) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( - openReview - ) - expect(next).not.toHaveBeenCalled() - }) - it('does not let a timed-out null short-circuit the lookup replacing it', async () => { const stale = stuckLookup() const rejects = expect( @@ -437,109 +75,6 @@ describe('hosted review branch cache (#11532)', () => { expect(joiner).not.toHaveBeenCalled() }) - it('lets a newer straggler supersede an older one that landed first', async () => { - const first = stuckLookup() - const firstRejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, first.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await firstRejects - - await vi.advanceTimersByTimeAsync(60_001) - const second = stuckLookup() - const secondRejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, second.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await secondRejects - - // Completion order cannot establish freshness; lookup start order does. - first.resolve(null) - await vi.advanceTimersByTimeAsync(0) - second.resolve(openReview) - await vi.advanceTimersByTimeAsync(0) - - const next = vi.fn(async () => null) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( - openReview - ) - expect(next).not.toHaveBeenCalled() - }) - - it('does not let an older straggler overwrite a newer one that landed first', async () => { - const first = stuckLookup() - const firstRejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, first.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await firstRejects - - await vi.advanceTimersByTimeAsync(60_001) - const second = stuckLookup() - const secondRejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, second.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await secondRejects - - // Even when both detach, retain the answer asked most recently. - second.resolve(openReview) - await vi.advanceTimersByTimeAsync(0) - first.resolve(null) - await vi.advanceTimersByTimeAsync(0) - - const next = vi.fn(async () => null) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( - openReview - ) - expect(next).not.toHaveBeenCalled() - }) - - it('does not let a straggler overwrite an answer newer than itself', async () => { - const stale = stuckLookup() - const rejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await rejects - - await vi.advanceTimersByTimeAsync(60_001) - await withHostedReviewBranchCache(identity, { headOid: null }, async () => mergedReview) - - stale.resolve(openReview) - await vi.advanceTimersByTimeAsync(0) - - const next = vi.fn(async () => null) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( - mergedReview - ) - expect(next).not.toHaveBeenCalled() - }) - - it('does not let a straggler evict the lookup that replaced it', async () => { - const stale = stuckLookup() - const rejects = expect( - withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) - ).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - await rejects - - await vi.advanceTimersByTimeAsync(60_001) - const replacement = stuckLookup() - const first = withHostedReviewBranchCache(identity, { headOid: null }, replacement.lookup) - - // A straggler must clear only its own record or the next reader starts a duplicate call. - stale.reject(new Error('late failure')) - await vi.advanceTimersByTimeAsync(0) - - const second = withHostedReviewBranchCache(identity, { headOid: null }, replacement.lookup) - replacement.resolve(openReview) - - await expect(first).resolves.toEqual(openReview) - await expect(second).resolves.toEqual(openReview) - expect(replacement.lookup).toHaveBeenCalledTimes(1) - }) - it('releases a caller by wall clock when the deadline timer never fires', async () => { const { lookup } = stuckLookup() @@ -555,63 +90,6 @@ describe('hosted review branch cache (#11532)', () => { expect(lookup).toHaveBeenCalledTimes(1) }) - it('bounds the in-flight map independently of the completed cache', async () => { - const { lookup } = stuckLookup() - const branchAt = (index: number) => ({ ...identity, branch: `feature/${index}` }) - const swallow = (promise: Promise): void => { - void promise.catch(() => {}) - } - - for (let index = 0; index <= MAX_INFLIGHT_LOOKUPS; index += 1) { - swallow(withHostedReviewBranchCache(branchAt(index), { headOid: null }, lookup)) - } - expect(lookup).toHaveBeenCalledTimes(MAX_INFLIGHT_LOOKUPS + 1) - - swallow(withHostedReviewBranchCache(branchAt(0), { headOid: null }, lookup)) - expect(lookup).toHaveBeenCalledTimes(MAX_INFLIGHT_LOOKUPS + 2) - - swallow( - withHostedReviewBranchCache(branchAt(MAX_INFLIGHT_LOOKUPS), { headOid: null }, lookup) - ) - expect(lookup).toHaveBeenCalledTimes(MAX_INFLIGHT_LOOKUPS + 2) - }) - - it('does not let a cap-evicted straggler clobber the answer that replaced it', async () => { - const evicted = stuckLookup() - const successor = evictInflightRecord(evicted.lookup) - - // Size eviction alone creates a straggler; it must not displace its successor. - evicted.resolve(mergedReview) - await vi.advanceTimersByTimeAsync(0) - - const joiner = vi.fn(async () => null) - const joined = withHostedReviewBranchCache(identity, { headOid: null }, joiner) - - successor.resolve(openReview) - await expect(successor.request).resolves.toEqual(openReview) - await expect(joined).resolves.toEqual(openReview) - expect(joiner).not.toHaveBeenCalled() - }) - - it('does not let a cap-evicted straggler double-count its successor failure', async () => { - const evicted = stuckLookup() - const successor = evictInflightRecord(evicted.lookup) - - evicted.reject(new Error('late failure')) - await vi.advanceTimersByTimeAsync(0) - - successor.reject(new Error('successor failure')) - await expect(successor.request).rejects.toThrow('successor failure') - - // Late rejection must not count a second backoff failure. - await vi.advanceTimersByTimeAsync(60_001) - const recovered = vi.fn(async () => openReview) - await expect( - withHostedReviewBranchCache(identity, { headOid: null }, recovered) - ).resolves.toEqual(openReview) - expect(recovered).toHaveBeenCalledTimes(1) - }) - it('stops asking once a branch has stranded its cap of unsettled lookups', async () => { const wedged = stuckLookup() for (let attempt = 0; attempt < MAX_UNSETTLED_LOOKUPS_PER_KEY; attempt += 1) { @@ -638,117 +116,5 @@ describe('hosted review branch cache (#11532)', () => { ).resolves.toEqual(mergedReview) expect(recovered).toHaveBeenCalledTimes(1) }) - - it('counts a lookup that is still running against the branch cap', async () => { - const swallow = (promise: Promise): void => { - void promise.catch(() => {}) - } - const filler = stuckLookup() - const wedged = stuckLookup() - /** Evict without timeout; reuse filler keys so the in-flight cap fires before unsettled-key admission. */ - const evictInflightRecords = (): void => { - for (let index = 0; index < MAX_INFLIGHT_LOOKUPS; index += 1) { - swallow( - withHostedReviewBranchCache( - { ...identity, branch: `filler/${index}` }, - { headOid: null }, - filler.lookup - ) - ) - } - } - - for (let attempt = 0; attempt < MAX_UNSETTLED_LOOKUPS_PER_KEY; attempt += 1) { - swallow(withHostedReviewBranchCache(identity, { headOid: null }, wedged.lookup)) - evictInflightRecords() - } - expect(wedged.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUPS_PER_KEY) - - // Size-evicted calls are still live before their deadlines; admission must count them. - await expect( - withHostedReviewBranchCache(identity, { headOid: null }, wedged.lookup) - ).rejects.toThrow(/never answered/) - expect(wedged.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUPS_PER_KEY) - }) - - it('stops admitting new branches once the unsettled map is full', async () => { - const swallow = (promise: Promise): void => { - void promise.catch(() => {}) - } - const filler = stuckLookup() - for (let index = 0; index < MAX_UNSETTLED_LOOKUP_KEYS; index += 1) { - swallow( - withHostedReviewBranchCache( - { ...identity, branch: `filler/${index}` }, - { headOid: null }, - filler.lookup - ) - ) - } - expect(filler.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUP_KEYS) - - // Bound new keys before deadline detachment; fresh branches must not be blamed for a lookup they never started. - const fresh = vi.fn(async () => openReview) - const refusal = await withHostedReviewBranchCache( - { ...identity, branch: 'fresh' }, - { headOid: null }, - fresh - ).catch((error: unknown) => (error as Error).message) - expect(refusal).toMatch(/Too many hosted review lookups are already in progress/) - expect(refusal).not.toMatch(/never answered/) - expect(fresh).not.toHaveBeenCalled() - - // The map cap blocks new keys, not recovery retries for existing ones. - const retry = stuckLookup() - swallow( - withHostedReviewBranchCache( - { ...identity, branch: 'filler/0' }, - { headOid: null }, - retry.lookup - ) - ) - expect(retry.lookup).toHaveBeenCalledTimes(1) - }) - - it('names the process-wide cap when abandoned lookups have filled it', async () => { - const wedged = stuckLookup() - for (let index = 0; index < MAX_DETACHED_LOOKUPS; index += 1) { - void withHostedReviewBranchCache( - { ...identity, branch: `wedged/${index}` }, - { headOid: null }, - wedged.lookup - ).catch(() => {}) - } - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - - const fresh = vi.fn(async () => openReview) - const refusal = await withHostedReviewBranchCache( - { ...identity, branch: 'fresh' }, - { headOid: null }, - fresh - ).catch((error: unknown) => (error as Error).message) - expect(refusal).toMatch(/abandoned without answering/) - expect(fresh).not.toHaveBeenCalled() - }) - - it('does not adopt a straggler whose invalidated scope was evicted', async () => { - const stale = stuckLookup() - const inflight = withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) - - invalidateHostedReviewBranchCache('/repo', 'local') - // After generation-map eviction, zero would alias an invalidated lookup's captured generation. - for (let index = 0; index < MAX_BRANCH_MAP_ENTRIES; index += 1) { - invalidateHostedReviewBranchCache(`/filler/${index}`, 'local') - } - - stale.resolve(null) - await expect(inflight).resolves.toBeNull() - - const next = vi.fn(async () => openReview) - await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( - openReview - ) - expect(next).toHaveBeenCalledTimes(1) - }) }) }) diff --git a/src/main/source-control/hosted-review-creation-eligibility.test.ts b/src/main/source-control/hosted-review-creation-eligibility.test.ts index e672df3c077..9de1fc11e94 100644 --- a/src/main/source-control/hosted-review-creation-eligibility.test.ts +++ b/src/main/source-control/hosted-review-creation-eligibility.test.ts @@ -38,13 +38,19 @@ const { getEnterpriseGitHubRepoSlugMock: vi.fn() })) -vi.mock('../github/client', () => ({ - createGitHubPullRequest: createGitHubPullRequestMock, - getRepoSlug: getRepoSlugMock, +vi.mock('../github/client/create/create-github-pull-request', () => ({ + createGitHubPullRequest: createGitHubPullRequestMock +})) + +vi.mock('../github/client/fetch/repo-slug-upstream', () => ({ + getRepoSlug: getRepoSlugMock +})) + +vi.mock('../github/client/lookup/get-pr-for-branch', () => ({ getPRForBranch: vi.fn() })) -vi.mock('../github/github-enterprise-repository', () => ({ +vi.mock('../github/repositories/github-enterprise-repository', () => ({ getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock })) @@ -86,10 +92,17 @@ vi.mock('../gitea/pull-request-creation', () => ({ isGiteaReviewCreationAuthenticated: isGiteaReviewCreationAuthenticatedMock })) -vi.mock('../github/gh-utils', () => ({ +vi.mock('../github/execution/github-operation-slots', () => ({ acquire: vi.fn(), - release: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, + release: vi.fn() +})) + +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) @@ -107,7 +120,9 @@ vi.mock('../gitlab/projects/gitlab-project-ref-resolution', () => ({ connectionId ? {} : { cwd: repoPath } })) -vi.mock('../git/source-control/upstream', () => ({ getUpstreamStatus: getUpstreamStatusMock })) +vi.mock('../git/source-control/upstream/upstream', () => ({ + getUpstreamStatus: getUpstreamStatusMock +})) vi.mock('./hosted-review', () => ({ getHostedReviewForBranch: getHostedReviewForBranchMock @@ -116,7 +131,7 @@ vi.mock('./hosted-review', () => ({ import { createHostedReview, getHostedReviewCreationEligibility } from './hosted-review-creation' import { baseRefExistsOnRemote } from './hosted-review-creation-git-state' -import { _resetOriginGitHubApiRepositoryCache } from '../github/github-api-repository' +import { _resetOriginGitHubApiRepositoryCache } from '../github/repositories/github-api-repository-remote-probe' const LOCAL_REPO_ARGS = { executionHostId: 'local' as const, repoPath: '/repo' } diff --git a/src/main/source-control/hosted-review-creation-git-state.ts b/src/main/source-control/hosted-review-creation-git-state.ts index 57d32686ca1..7f3b420786e 100644 --- a/src/main/source-control/hosted-review-creation-git-state.ts +++ b/src/main/source-control/hosted-review-creation-git-state.ts @@ -5,16 +5,16 @@ import { } from '../../shared/source-control/hosted-review/hosted-review-refs' import { isSafeGitRefName } from '../../shared/git/status/git-status-upstream-ref' import type { GitUpstreamStatus } from '../../shared/git/status/git-status-types' -import { gitExecFileAsync } from '../github/gh-utils' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { isShowRefNoMatchError } from '../../shared/git/refs/git-show-ref-no-match' import { probeExactRefsViaForEachRef } from '../git/refs/resolution/exact-ref-probe' import { gitOptionalLocksDisabledEnv } from '../git/command-runner/git-environment/git-process-env' import { parsePorcelainV1Records, type PorcelainV1Record -} from '../git/source-control/porcelain-v1-records' +} from '../git/source-control/status/porcelain-v1-records' import { resolveDefaultBaseRefViaExec } from '../../shared/git/refs/git-default-base-ref' -import { getUpstreamStatus } from '../git/source-control/upstream' +import { getUpstreamStatus } from '../git/source-control/upstream/upstream' import { findExistingWorktreeSymlinkPaths } from '../git/worktrees/content-paths/worktree-symlink-detection' import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch' import type { ExecutionHostId } from '../../shared/execution-host' diff --git a/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts b/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts index 00ae0c91879..d6da312b510 100644 --- a/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts +++ b/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts @@ -35,9 +35,15 @@ vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) ghExecFileAsync: ghExecFileAsyncMock })) -vi.mock('../github/client', () => ({ - createGitHubPullRequest: vi.fn(), - getRepoSlug: getRepoSlugMock, +vi.mock('../github/client/create/create-github-pull-request', () => ({ + createGitHubPullRequest: vi.fn() +})) + +vi.mock('../github/client/fetch/repo-slug-upstream', () => ({ + getRepoSlug: getRepoSlugMock +})) + +vi.mock('../github/client/lookup/get-pr-for-branch', () => ({ getPRForBranch: vi.fn() })) diff --git a/src/main/source-control/hosted-review-creation-provider.ts b/src/main/source-control/hosted-review-creation-provider.ts index f54d913b457..caa45a48742 100644 --- a/src/main/source-control/hosted-review-creation-provider.ts +++ b/src/main/source-control/hosted-review-creation-provider.ts @@ -4,8 +4,9 @@ import type { HostedReviewCreationProvider } from '../../shared/source-control/h import { isAzureDevOpsReviewCreationAuthenticated } from '../azure-devops/pull-request-creation' import { isBitbucketReviewCreationAuthenticated } from '../bitbucket/pull-request-creation' import { isGiteaReviewCreationAuthenticated } from '../gitea/pull-request-creation' -import { getEnterpriseGitHubRepoSlug } from '../github/github-enterprise-repository' -import { acquire, ghExecFileAsync, release } from '../github/gh-utils' +import { getEnterpriseGitHubRepoSlug } from '../github/repositories/github-enterprise-repository' +import { acquire, release } from '../github/execution/github-operation-slots' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import { getProjectSlug } from '../gitlab/merge-requests/merge-request-lookup' import { acquire as acquireGlab, diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index ec8ca06b16e..5c3bbee61bb 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -38,13 +38,19 @@ const { getEnterpriseGitHubRepoSlugMock: vi.fn() })) -vi.mock('../github/client', () => ({ - createGitHubPullRequest: createGitHubPullRequestMock, - getRepoSlug: getRepoSlugMock, +vi.mock('../github/client/create/create-github-pull-request', () => ({ + createGitHubPullRequest: createGitHubPullRequestMock +})) + +vi.mock('../github/client/fetch/repo-slug-upstream', () => ({ + getRepoSlug: getRepoSlugMock +})) + +vi.mock('../github/client/lookup/get-pr-for-branch', () => ({ getPRForBranch: vi.fn() })) -vi.mock('../github/github-enterprise-repository', () => ({ +vi.mock('../github/repositories/github-enterprise-repository', () => ({ getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock })) @@ -86,10 +92,17 @@ vi.mock('../gitea/pull-request-creation', () => ({ isGiteaReviewCreationAuthenticated: isGiteaReviewCreationAuthenticatedMock })) -vi.mock('../github/gh-utils', () => ({ +vi.mock('../github/execution/github-operation-slots', () => ({ acquire: vi.fn(), - release: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, + release: vi.fn() +})) + +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) @@ -107,7 +120,7 @@ vi.mock('../gitlab/projects/gitlab-project-ref-resolution', () => ({ connectionId ? {} : { cwd: repoPath } })) -vi.mock('../git/source-control/upstream', () => ({ +vi.mock('../git/source-control/upstream/upstream', () => ({ getUpstreamStatus: getUpstreamStatusMock })) @@ -117,7 +130,7 @@ vi.mock('./hosted-review', () => ({ import { createHostedReview } from './hosted-review-creation' -import { _resetOriginGitHubApiRepositoryCache } from '../github/github-api-repository' +import { _resetOriginGitHubApiRepositoryCache } from '../github/repositories/github-api-repository-remote-probe' // Isolate module-level repository identities between tests. beforeEach(() => { diff --git a/src/main/source-control/hosted-review-creation.ts b/src/main/source-control/hosted-review-creation.ts index 07caa8f26b8..ba2bc22a976 100644 --- a/src/main/source-control/hosted-review-creation.ts +++ b/src/main/source-control/hosted-review-creation.ts @@ -8,8 +8,8 @@ import type { } from '../../shared/source-control/hosted-review/hosted-review-contracts' import { supportsHostedReviewCreation } from '../../shared/source-control/hosted-review/hosted-review-creation-providers' import { normalizeHostedReviewBaseRef } from '../../shared/source-control/hosted-review/hosted-review-refs' -import { getRepoSlug } from '../github/client' -import { isDefaultGitHubHost } from '../../shared/github/repository-identity-key' +import { getRepoSlug } from '../github/client/fetch/repo-slug-upstream' +import { isDefaultGitHubHost } from '../../shared/github/repositories/repository-identity-key' import { detectHostedReviewProvider, getForgeProviderForRepository diff --git a/src/main/source-control/hosted-review-execution-host-routing.test.ts b/src/main/source-control/hosted-review-execution-host-routing.test.ts index 2dd8c014ebe..389ee702e6b 100644 --- a/src/main/source-control/hosted-review-execution-host-routing.test.ts +++ b/src/main/source-control/hosted-review-execution-host-routing.test.ts @@ -53,9 +53,16 @@ const { assertRemoteUrlReadableMock: vi.fn() })) -vi.mock('../github/gh-utils', () => ({ - gitExecFileAsync: gitExecFileAsyncMock, - ghExecFileAsync: ghExecFileAsyncMock, +vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: gitExecFileAsyncMock +})) + +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('../github/execution/github-operation-slots', () => ({ acquire: vi.fn(async () => {}), release: vi.fn() })) @@ -78,7 +85,9 @@ vi.mock('../git/command-runner/git-environment/git-process-env', async (importOr gitOptionalLocksDisabledEnv: vi.fn(() => ({})) })) -vi.mock('../git/source-control/upstream', () => ({ getUpstreamStatus: getUpstreamStatusMock })) +vi.mock('../git/source-control/upstream/upstream', () => ({ + getUpstreamStatus: getUpstreamStatusMock +})) vi.mock('../../shared/git/refs/git-default-base-ref', async (importOriginal) => ({ ...(await importOriginal>()), @@ -117,15 +126,15 @@ vi.mock('../github/client/lookup/pr-for-branch-outcome', () => ({ getPRForBranchOutcome: getPRForBranchOutcomeMock })) -vi.mock('../github/client', () => ({ - getRepoSlug: getRepoSlugMock, - getRepoUpstream: getRepoUpstreamMock, - getPRForBranchOutcome: getPRForBranchOutcomeMock, - getGitHubPRLookupRateLimitBlock: vi.fn(async () => null), +vi.mock('../github/client/lookup/pr-lookup-rate-limit', () => ({ + getGitHubPRLookupRateLimitBlock: vi.fn(async () => null) +})) + +vi.mock('../github/client/create/create-github-pull-request', () => ({ createGitHubPullRequest: createGitHubPullRequestMock })) -vi.mock('../github/github-enterprise-repository', () => ({ +vi.mock('../github/repositories/github-enterprise-repository', () => ({ getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock })) diff --git a/src/main/source-control/hosted-review-git-options.ts b/src/main/source-control/hosted-review-git-options.ts index 289691c6f99..5d571e2592d 100644 --- a/src/main/source-control/hosted-review-git-options.ts +++ b/src/main/source-control/hosted-review-git-options.ts @@ -1,5 +1,5 @@ -import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' -import type { GhAccountBinding } from '../../shared/github/account-binding' +import type { GitAdmissionTier } from '../../shared/rpc-contract/source-control/git-admission-tier-params' +import type { GhAccountBinding } from '../../shared/github/accounts/account-binding' export type HostedReviewLocalGitOptions = { wslDistro?: string diff --git a/src/main/source-control/hosted-review.test.ts b/src/main/source-control/hosted-review.test.ts index f61125e3a6f..6d7036953ae 100644 --- a/src/main/source-control/hosted-review.test.ts +++ b/src/main/source-control/hosted-review.test.ts @@ -33,10 +33,19 @@ vi.mock('../gitlab/merge-requests/merge-request-lookup', () => ({ getMergeRequest: vi.fn() })) -vi.mock('../github/client', () => ({ - getRepoSlug: getRepoSlugMock, - getPRForBranchOutcome: getPRForBranchOutcomeMock, - getGitHubPRLookupRateLimitBlock: vi.fn(async () => null), +vi.mock('../github/client/fetch/repo-slug-upstream', () => ({ + getRepoSlug: getRepoSlugMock +})) + +vi.mock('../github/client/lookup/pr-for-branch-outcome', () => ({ + getPRForBranchOutcome: getPRForBranchOutcomeMock +})) + +vi.mock('../github/client/lookup/pr-lookup-rate-limit', () => ({ + getGitHubPRLookupRateLimitBlock: vi.fn(async () => null) +})) + +vi.mock('../github/client/create/create-github-pull-request', () => ({ createGitHubPullRequest: vi.fn() })) @@ -80,54 +89,6 @@ describe('getHostedReviewForBranch', () => { __resetHostedReviewBranchCacheForTests() }) - it('refreshes a self-managed GitLab MR through the provider while old metadata is pending', async () => { - getProjectSlugMock.mockResolvedValue({ host: 'gitlab.example.test', path: 'g/p' }) - const old = { - number: 7, - title: 'MR', - state: 'opened', - url: 'https://gitlab.example.test/g/p/-/merge_requests/7', - pipelineStatus: 'success', - updatedAt: '2026-05-10T00:00:00.000Z', - mergeable: 'MERGEABLE' - } - let finishOld: (value: typeof old) => void = () => {} - const pending = new Promise((resolve) => { - finishOld = resolve - }) - let started!: () => void - const requestStarted = new Promise((resolve) => { - started = resolve - }) - getMergeRequestForBranchMock.mockImplementation( - ( - _repo: string, - _branch: string, - _linked: unknown, - connectionId?: string | null, - options?: { userRefresh?: boolean } - ) => { - started() - if (connectionId !== 'ssh-1') { - return Promise.resolve(null) - } - return options?.userRefresh ? Promise.resolve({ ...old, state: 'merged' }) : pending - } - ) - const input = { - repoPath: '/repo', - executionHostId: 'ssh:ssh-1', - branch: 'feature', - force: true - } as const - const before = getHostedReviewForBranch(input) - await requestStarted - const click = getHostedReviewForBranch({ ...input, userRefresh: true }) - finishOld(old) - await before - await expect(click).resolves.toMatchObject({ provider: 'gitlab', state: 'merged', number: 7 }) - }) - it('maps GitLab merge requests into the hosted review surface', async () => { getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) const mr = { @@ -165,114 +126,4 @@ describe('getHostedReviewForBranch', () => { expect(getProjectSlugMock).toHaveBeenCalledWith('/repo', 'ssh-1') expect(getPRForBranchOutcomeMock).not.toHaveBeenCalled() }) - - it('falls through to GitHub when origin is not GitLab', async () => { - getProjectSlugMock.mockResolvedValue(null) - getRepoSlugMock.mockResolvedValue({ owner: 'o', repo: 'r' }) - getPRForBranchOutcomeMock.mockResolvedValue({ - kind: 'found', - fetchedAt: 1, - pr: { - number: 3, - title: 'GitHub branch', - state: 'open', - url: 'https://github.com/o/r/pull/3', - checksStatus: 'pending', - updatedAt: '2026-05-10T00:00:00.000Z', - mergeable: 'UNKNOWN' - } - }) - - await expect( - getHostedReviewForBranch({ - executionHostId: 'local', - repoPath: '/repo', - branch: 'feature', - linkedGitHubPR: 3 - }) - ).resolves.toMatchObject({ - provider: 'github', - number: 3, - status: 'pending' - }) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith('/repo', 'feature', 3, null, null, { - currentHeadOid: null - }) - }) - - it('routes local WSL project branch lookup through provider detection and the selected provider', async () => { - getProjectSlugMock.mockResolvedValue(null) - getRepoSlugMock.mockResolvedValue(null) - getBitbucketRepoSlugMock.mockResolvedValue({ workspace: 'team', repoSlug: 'orca' }) - getBitbucketPullRequestForBranchMock.mockResolvedValue({ - number: 22, - title: 'Bitbucket WSL branch', - state: 'open', - url: 'https://bitbucket.org/team/orca/pull-requests/22', - status: 'pending', - updatedAt: '2026-06-16T00:00:00.000Z', - mergeable: 'UNKNOWN' - }) - - await expect( - getHostedReviewForBranch({ - executionHostId: 'local', - repoPath: '/repo', - branch: 'feature/wsl', - linkedBitbucketPR: 22, - localGitExecOptions: { wslDistro: 'Ubuntu' } - }) - ).resolves.toMatchObject({ - provider: 'bitbucket', - number: 22, - status: 'pending' - }) - - const executionOptions = { localGitExecOptions: { wslDistro: 'Ubuntu' } } - expect(getProjectSlugMock).toHaveBeenCalledWith('/repo', null, executionOptions) - expect(getRepoSlugMock).toHaveBeenCalledWith('/repo', null, executionOptions) - expect(getBitbucketRepoSlugMock).toHaveBeenCalledWith('/repo', null, executionOptions) - expect(getBitbucketPullRequestForBranchMock).toHaveBeenCalledWith( - '/repo', - 'feature/wsl', - 22, - null, - executionOptions - ) - }) - - it('uses fallback GitHub PR when branch is empty', async () => { - getProjectSlugMock.mockResolvedValue(null) - getRepoSlugMock.mockResolvedValue({ owner: 'o', repo: 'r' }) - getPRForBranchOutcomeMock.mockResolvedValue({ - kind: 'found', - fetchedAt: 1, - pr: { - number: 42, - title: 'Detached GitHub branch', - state: 'open', - url: 'https://github.com/o/r/pull/42', - checksStatus: 'success', - updatedAt: '2026-05-10T00:00:00.000Z', - mergeable: 'MERGEABLE' - } - }) - - await expect( - getHostedReviewForBranch({ - executionHostId: 'local', - repoPath: '/repo', - branch: '', - fallbackGitHubPR: 42 - }) - ).resolves.toMatchObject({ - provider: 'github', - number: 42, - status: 'success' - }) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith('/repo', '', null, null, 42, { - acceptMergedFallbackPR: true, - currentHeadOid: null - }) - }) }) diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 8dd813873b7..8bd616faa04 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -1,4 +1,7 @@ -import { githubRepoContext, withGitHubRepoExecution } from '../github/github-repository-identity' +import { + githubRepoContext, + withGitHubRepoExecution +} from '../github/repositories/github-repository-identity' import type { ExecutionHostId } from '../../shared/execution-host' import { cachedHostedReviewOutcome, diff --git a/src/main/source-control/merged-review-head-equivalence-real-git.test.ts b/src/main/source-control/merged-review-head-equivalence-real-git.test.ts new file mode 100644 index 00000000000..d2cf8090963 --- /dev/null +++ b/src/main/source-control/merged-review-head-equivalence-real-git.test.ts @@ -0,0 +1,207 @@ +import { runProcessSync } from '@orca/process-host' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mergedReviewHeadIsEquivalent } from './merged-review-head-equivalence' +import { getLocalGitCapabilityCache } from '../git/command-runner/host-routing/git-capability-state' +import { isUnsupportedMergeTreeWriteTreeError } from '../../shared/git/branches/git-merge-tree-capability' + +describe('merged review head equivalence (real Git)', () => { + let repoPath = '' + const gitWithInput = (args: string[], input?: string | Uint8Array, cwd = repoPath): string => { + const result = runProcessSync({ program: 'git', args, cwd, input }) + if (result.code !== 0) { + throw new Error(result.stderr) + } + return result.stdout.trim() + } + const git = (...args: string[]): string => gitWithInput(args) + const commit = (file: string, content: string, message: string): string => { + writeFileSync(join(repoPath, file), content) + git('add', file) + git('commit', '--quiet', '-m', message) + return git('rev-parse', 'HEAD') + } + const prove = (reviewHeadOid: string, headOid: string, connectionId?: string) => + mergedReviewHeadIsEquivalent({ + repoPath, + connectionId, + localGitOptions: {}, + reviewHeadOid, + baseBranchName: 'main', + headOid + }) + + beforeEach(() => { + repoPath = mkdtempSync(join(tmpdir(), 'orca-merged-review-equivalence-')) + git('init', '--quiet') + git('symbolic-ref', 'HEAD', 'refs/heads/main') + git('config', 'user.name', 'Orca Test') + git('config', 'user.email', 'orca@example.test') + git('config', 'commit.gpgSign', 'false') + git('config', 'core.hooksPath', '.git/no-hooks') + commit('shared.txt', 'a\nb\nc\nd\ne\nf\n', 'base') + }) + + afterEach(() => { + rmSync(repoPath, { recursive: true, force: true }) + }) + + // Review edits line 1; main later edits line 6 of the same file, then the branch is rebased locally. + function rebasedReview(reviewFile = 'shared.txt'): { reviewHead: string; rebasedHead: string } { + git('checkout', '--quiet', '-b', 'feature') + const reviewHead = commit(reviewFile, 'A\nb\nc\nd\ne\nf\n', 'review') + git('checkout', '--quiet', 'main') + commit('shared.txt', 'a\nb\nc\nd\ne\nF\n', 'upstream change') + git('update-ref', 'refs/remotes/origin/main', 'HEAD') + git('checkout', '--quiet', 'feature') + git('rebase', '--quiet', 'origin/main') + return { reviewHead, rebasedHead: git('rev-parse', 'HEAD') } + } + + function shallowRebasedReview() { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + git('branch', 'review', reviewHead) + const shallowPath = join(repoPath, 'shallow') + git('init', '--quiet', shallowPath) + const fetch = (depth: string) => + gitWithInput( + [ + 'fetch', + '--quiet', + depth, + pathToFileURL(repoPath).href, + '+refs/heads/main:refs/remotes/origin/main', + '+refs/heads/review:refs/remotes/origin/review', + '+refs/heads/feature:refs/remotes/origin/feature' + ], + undefined, + shallowPath + ) + fetch('--depth=1') + return { + request: { + repoPath: shallowPath, + localGitOptions: {}, + reviewHeadOid: reviewHead, + baseBranchName: 'main', + headOid: rebasedHead + }, + deepen: () => fetch('--unshallow') + } + } + + it('proves a rebase when main edited the same file on Git with write-tree support', async ({ + skip + }) => { + const { reviewHead, rebasedHead } = rebasedReview() + try { + git('merge-tree', '--write-tree', 'origin/main', reviewHead) + } catch (error) { + if (isUnsupportedMergeTreeWriteTreeError(error)) { + skip() + } + throw error + } + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + }) + + it('proves a separate-file rebase through the older-Git exact-diff fallback', async () => { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + const capabilities = getLocalGitCapabilityCache({ cwd: repoPath }) + capabilities.rememberUnsupported('merge-tree-write-tree') + try { + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + const extraHead = commit('local.txt', 'unpushed\n', 'local work') + await expect(prove(reviewHead, extraHead)).resolves.toBe(false) + } finally { + capabilities.clear() + } + }) + + it('refuses distinct non-UTF-8 paths with identical blobs in the older-Git fallback', async () => { + const base = git('rev-parse', 'HEAD') + const blob = gitWithInput(['hash-object', '-w', '--stdin'], 'review content\n') + const tree = (pathByte: number) => + gitWithInput( + ['mktree', '-z'], + Buffer.concat([Buffer.from(`100644 blob ${blob}\tpath-`), Buffer.from([pathByte, 0])]) + ) + const reviewHead = git('commit-tree', tree(0xff), '-p', base, '-m', 'review') + const localHead = git('commit-tree', tree(0xfe), '-p', base, '-m', 'local rename') + git('update-ref', 'refs/remotes/origin/main', base) + const capabilities = getLocalGitCapabilityCache({ cwd: repoPath }) + capabilities.rememberUnsupported('merge-tree-write-tree') + try { + await expect(prove(reviewHead, localHead)).resolves.toBe(false) + } finally { + capabilities.clear() + } + }) + + it('retries a same-commit proof after shallow history is deepened', async () => { + const { request, deepen } = shallowRebasedReview() + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(false) + deepen() + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(true) + }) + + it('retries a same-commit proof after deepening through the older-Git fallback', async () => { + const { request, deepen } = shallowRebasedReview() + const capabilities = getLocalGitCapabilityCache({ cwd: request.repoPath }) + capabilities.rememberUnsupported('merge-tree-write-tree') + try { + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(false) + deepen() + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(true) + } finally { + capabilities.clear() + } + }) + + it('rechecks a cached proof after the remote base is rewritten', async () => { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + git('update-ref', 'refs/remotes/origin/main', 'main^') + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(false) + }) + + it('retries after a missing review commit becomes available', async () => { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + const objectPath = join( + repoPath, + '.git', + 'objects', + reviewHead.slice(0, 2), + reviewHead.slice(2) + ) + const object = readFileSync(objectPath) + rmSync(objectPath) + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(false) + writeFileSync(objectPath, object) + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + }) + + it('refuses a rebased head that carries extra work', async () => { + const { reviewHead } = rebasedReview() + const extraHead = commit('local.txt', 'unpushed\n', 'local work') + await expect(prove(reviewHead, extraHead)).resolves.toBe(false) + }) + + it('refuses a reused branch name whose head is just main with the review merged', async () => { + git('checkout', '--quiet', '-b', 'feature') + const reviewHead = commit('shared.txt', 'A\nb\nc\nd\ne\nf\n', 'review') + git('checkout', '--quiet', 'main') + git('merge', '--quiet', '--squash', 'feature') + git('commit', '--quiet', '-m', 'squash') + git('update-ref', 'refs/remotes/origin/main', 'HEAD') + await expect(prove(reviewHead, git('rev-parse', 'HEAD'))).resolves.toBe(false) + }) + + it('does not probe an SSH repository path on this host', async () => { + const { reviewHead, rebasedHead } = rebasedReview() + await expect(prove(reviewHead, rebasedHead, 'ssh-connection')).resolves.toBe(false) + }) +}) diff --git a/src/main/source-control/merged-review-head-equivalence.ts b/src/main/source-control/merged-review-head-equivalence.ts new file mode 100644 index 00000000000..f9771f5cbdb --- /dev/null +++ b/src/main/source-control/merged-review-head-equivalence.ts @@ -0,0 +1,164 @@ +import { gitExecFileAsync, gitExecFileAsyncBuffer } from '../git/command-runner/git-exec-file' +import { gitOptionsForWorktree } from '../git/command-runner/git-runtime-options' +import { createLocalGitObjectQuarantine } from '../git/objects/local-git-object-quarantine' +import { withLocalGitCapabilityCacheForExecution } from '../git/command-runner/host-routing/git-capability-state' +import { isUnsupportedMergeTreeWriteTreeError } from '../../shared/git/branches/git-merge-tree-capability' +import { MergedReviewMembershipMemo } from './merged-review-membership-memo' +import type { HostedReviewLocalGitOptions } from './hosted-review-git-options' + +type Proof = 'equivalent' | 'unproven' + +const BASE_REMOTES = ['origin', 'upstream'] +const GIT_OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/ +// A fetch can make an unproven result provable without changing any commit IDs. +const proofMemo = new MergedReviewMembershipMemo({ + weight: () => 1, + maxWeight: 200, + ttl: (proof) => (proof === 'equivalent' ? 6 * 60 * 60_000 : 0) +}) + +/** + * True when HEAD is a remote base commit plus exactly the merged review's changes (an equivalent + * rebase), so the workspace holds no work beyond the merged review. Unprovable cases return false. + */ +export async function mergedReviewHeadIsEquivalent(args: { + repoPath: string + connectionId?: string | null + localGitOptions: HostedReviewLocalGitOptions + reviewHeadOid: string | undefined + baseBranchName: string | undefined + headOid: string +}): Promise { + const reviewHead = args.reviewHeadOid?.trim().toLowerCase() ?? '' + const head = args.headOid.trim().toLowerCase() + const baseBranch = args.baseBranchName?.trim() ?? '' + // SSH repo paths live on the remote host, which runs its own lookup with local Git. + if ( + args.connectionId || + !GIT_OBJECT_ID.test(reviewHead) || + !GIT_OBJECT_ID.test(head) || + reviewHead === head || + !baseBranch || + baseBranch.startsWith('-') + ) { + return false + } + try { + const gitOptions = { + ...gitOptionsForWorktree(args.repoPath, args.localGitOptions), + timeout: 10_000 + } + // Missing review objects may arrive on the next fetch; do not retain that inconclusive result. + await gitExecFileAsync(['cat-file', '-e', `${reviewHead}^{commit}`], gitOptions) + const baseTips: string[] = [] + for (const remote of BASE_REMOTES) { + try { + const { stdout } = await gitExecFileAsync( + ['rev-parse', '--verify', `refs/remotes/${remote}/${baseBranch}^{commit}`], + gitOptions + ) + const tip = stdout.trim() + if (GIT_OBJECT_ID.test(tip)) { + baseTips.push(tip) + } + } catch { + // Missing remote bases cannot establish equivalence. + } + } + const key = JSON.stringify([ + args.localGitOptions.wslDistro ?? null, + args.repoPath, + baseTips, + reviewHead, + head + ]) + const proof = await proofMemo.read(key, async () => { + try { + return await proveEquivalence( + args.repoPath, + args.localGitOptions, + reviewHead, + baseTips, + head + ) + } catch { + return 'unproven' + } + }) + return proof === 'equivalent' + } catch { + return false + } +} + +async function proveEquivalence( + repoPath: string, + localGitOptions: HostedReviewLocalGitOptions, + reviewHead: string, + baseTips: string[], + head: string +): Promise { + const gitOptions = { ...gitOptionsForWorktree(repoPath, localGitOptions), timeout: 10_000 } + const read = async (argv: string[]) => (await gitExecFileAsync(argv, gitOptions)).stdout.trim() + const headTree = await read(['rev-parse', '--verify', `${head}^{tree}`]) + for (const baseTip of baseTips) { + let base: string + try { + base = await read(['merge-base', head, baseTip]) + } catch { + continue + } + // A base with HEAD's tree means HEAD adds nothing itself, e.g. a reused branch name at main. + if (!GIT_OBJECT_ID.test(base) || (await read(['rev-parse', `${base}^{tree}`])) === headTree) { + continue + } + const proven = await withLocalGitCapabilityCacheForExecution( + { cwd: repoPath, wslDistro: localGitOptions.wslDistro }, + (capabilities) => + capabilities.runWithFallback( + 'merge-tree-write-tree', + async () => { + const run = (env: NodeJS.ProcessEnv | undefined) => + gitExecFileAsync(['merge-tree', '--write-tree', base, reviewHead], { + ...gitOptions, + ...(env ? { env } : {}) + }) + try { + // Quarantine the throwaway merged tree; probe support before older Git sees a quarantine. + const { stdout } = capabilities.isKnownSupported('merge-tree-write-tree') + ? await createLocalGitObjectQuarantine(repoPath, localGitOptions).run(run) + : await run(undefined) + return stdout.split('\n', 1)[0].trim() === headTree + } catch (error) { + if (isUnsupportedMergeTreeWriteTreeError(error)) { + throw error + } + // Conflicts and missing review objects cannot prove equivalence. + return false + } + }, + // Git < 2.38: exact per-path mode/blob transitions only match when base never touched them. + async () => { + const reviewBase = await read(['merge-base', reviewHead, base]) + const delta = async (from: string, to: string) => + ( + await gitExecFileAsyncBuffer( + ['diff-tree', '-r', '-z', '--no-abbrev', '--no-renames', from, to], + gitOptions + ) + ).stdout + const [reviewDelta, headDelta] = await Promise.all([ + delta(reviewBase, reviewHead), + delta(base, head) + ]) + return reviewDelta.length > 0 && reviewDelta.equals(headDelta) + }, + isUnsupportedMergeTreeWriteTreeError + ) + ) + if (proven) { + return 'equivalent' + } + } + return 'unproven' +} diff --git a/src/main/source-control/pull-request-linked-issue.ts b/src/main/source-control/pull-request-linked-issue.ts index 0b7c102f69b..5efbbbc4ecd 100644 --- a/src/main/source-control/pull-request-linked-issue.ts +++ b/src/main/source-control/pull-request-linked-issue.ts @@ -3,7 +3,7 @@ import type { PullRequestLinkedIssue } from '../../shared/source-control/ai/gene import { isLinkedIssueNumber } from '../../shared/source-control/ai/recipes/source-control-ai-action-variables' import type { WorkspaceLinkedItem } from '../../shared/worktree/types' import type { GitRuntimeOptions } from '../git/command-runner/git-runtime-options' -import { getIssue as getGitHubIssue } from '../github/issues' +import { getIssue as getGitHubIssue } from '../github/issues/issues' import { getIssue as getGitLabIssue } from '../gitlab/issues/gitlab-issue-queries' export type PullRequestLinkedIssueMeta = { diff --git a/src/main/source-control/stacked-hosted-review-creation.ts b/src/main/source-control/stacked-hosted-review-creation.ts index 3c6aa158c99..47b9713a1b4 100644 --- a/src/main/source-control/stacked-hosted-review-creation.ts +++ b/src/main/source-control/stacked-hosted-review-creation.ts @@ -1,6 +1,9 @@ -import { withGitHubRepoExecution } from '../github/github-repository-identity' +import { withGitHubRepoExecution } from '../github/repositories/github-repository-identity' import { hostedReviewSshConnectionId } from './hosted-review-execution-host' -import { getHostedReviewLocalGitOptions } from './hosted-review-git-options' +import { + getHostedReviewLocalGitOptions, + type HostedReviewExecutionOptions +} from './hosted-review-git-options' import type { ExecutionHostId } from '../../shared/execution-host' import type { CreateStackedHostedReviewInput, @@ -10,9 +13,9 @@ import type { import { prepareGitHubStackedPullRequest, registerGitHubStackedPullRequest -} from '../github/stacked-pr-creation' +} from '../github/pull-requests/stacks/stacked-pr-creation' import { createHostedReview } from './hosted-review-creation' -import type { HostedReviewExecutionOptions } from './hosted-review-git-options' + import { stackedReviewFailure } from '../../shared/source-control/hosted-review/stacked-hosted-review-failure-copy' export async function createStackedHostedReview( diff --git a/src/main/speech/dictation-cleanup-service.test.ts b/src/main/speech/dictation-cleanup-service.test.ts new file mode 100644 index 00000000000..af9b728e7eb --- /dev/null +++ b/src/main/speech/dictation-cleanup-service.test.ts @@ -0,0 +1,146 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { DICTATION_CLEANUP_TIMEOUT_MS } from '../../shared/dictation-cleanup' +import { + createMockDiscoveryChild, + type MockDiscoveryChild +} from '../text-generation/execution/commit-message-text-generation-test-harness' +import type * as DictationCleanup from '../../shared/dictation-cleanup' +import type * as GenerationLanes from '../text-generation/execution/source-control-generation-lanes' +import { cancelDictationCleanup, cleanUpDictatedText } from './dictation-cleanup-service' + +const children: MockDiscoveryChild[] = [] +const cancelRegistrations: string[] = [] +let agentId = 'claude' + +vi.mock('../../shared/dictation-cleanup', async (importOriginal) => ({ + ...(await importOriginal()), + isDictationCleanupOn: () => true +})) +vi.mock('../text-generation/commit-message-text-generation', () => ({ + resolveCommitMessageSettings: () => ({ ok: true, params: { agentId, model: 'default' } }) +})) +vi.mock('../text-generation/execution/commit-message-agent-environment', () => ({ + prepareLocalCommitMessageAgentEnv: async () => ({ ok: true }) +})) +vi.mock('../text-generation/execution/source-control-generation-lanes', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + setLocalGenerationCancelToken: (lane: string, cancel: () => void) => { + cancelRegistrations.push(lane) + actual.setLocalGenerationCancelToken(lane, cancel) + } + } +}) +vi.mock('../text-generation/execution/source-control-agent-launch', () => ({ + spawnSourceControlAgent: ({ args }: { args: string[] }) => { + const child = createMockDiscoveryChild() + if (args.includes('mcp')) { + // Codex's read-only policy probe: no MCP servers configured. + queueMicrotask(() => { + child.stdout.emit('data', Buffer.from('[]')) + child.emit('close', 0) + }) + } else { + // A killed agent exits, as SIGKILL makes a real one do. + child.kill = vi.fn(() => { + queueMicrotask(() => child.emit('close', null, 'SIGKILL')) + return true + }) + children.push(child) + } + return child + } +})) + +const deps = { getSettings: () => ({}), getAgentEnvResolvers: () => undefined } + +afterEach(() => { + children.length = 0 + cancelRegistrations.length = 0 + agentId = 'claude' + vi.useRealTimers() +}) + +function startCleanup(requestId: string): ReturnType { + return cleanUpDictatedText({ text: requestId, terms: [], requestId }, deps) +} + +/** Starts a cleanup and returns once it can be canceled: its agent running, or queued for one. */ +async function startCancelableCleanup( + requestId: string +): Promise<{ cleanup: ReturnType }> { + const registeredBefore = cancelRegistrations.length + const cleanup = startCleanup(requestId) + await vi.waitFor(() => expect(cancelRegistrations.length).toBeGreaterThan(registeredBefore)) + return { cleanup } +} + +async function expectSecondAgentToFinish( + second: ReturnType +): Promise { + await vi.waitFor(() => expect(children).toHaveLength(2)) + const [firstAgent, secondAgent] = children + expect(firstAgent.kill).toHaveBeenCalled() + expect(secondAgent.kill).not.toHaveBeenCalled() + secondAgent.stdout.emit('data', Buffer.from('Second.')) + secondAgent.emit('close', 0) + await expect(second).resolves.toMatchObject({ status: 'cleaned', text: 'Second.' }) +} + +describe('overlapping dictation cleanups share a folder but stop independently', () => { + it('skipping the first stops only its agent while the second keeps running', async () => { + const first = startCleanup('a') + await vi.waitFor(() => expect(children).toHaveLength(1)) + const { cleanup: second } = await startCancelableCleanup('b') + expect(children).toHaveLength(2) + + cancelDictationCleanup('a') + + await expect(first).resolves.toEqual({ status: 'canceled' }) + await expectSecondAgentToFinish(second) + }) + + it('the first timing out stops only its agent while the second keeps running', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const first = startCleanup('a') + await vi.waitFor(() => expect(children).toHaveLength(1)) + await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) + const { cleanup: second } = await startCancelableCleanup('b') + expect(children).toHaveLength(2) + + await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) + + await expect(first).resolves.toEqual({ status: 'timed-out' }) + await expectSecondAgentToFinish(second) + }) + + // Codex runs one at a time under its home lock, so the second cleanup waits queued. + it('skipping a running Codex cleanup lets the queued one start and finish', async () => { + agentId = 'codex' + const first = startCleanup('a') + await vi.waitFor(() => expect(children).toHaveLength(1)) + const { cleanup: second } = await startCancelableCleanup('b') + expect(children).toHaveLength(1) + + cancelDictationCleanup('a') + + await expect(first).resolves.toEqual({ status: 'canceled' }) + await expectSecondAgentToFinish(second) + }) + + it('a running Codex cleanup timing out lets the queued one start and finish', async () => { + agentId = 'codex' + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const first = startCleanup('a') + await vi.waitFor(() => expect(children).toHaveLength(1)) + await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) + const { cleanup: second } = await startCancelableCleanup('b') + expect(children).toHaveLength(1) + + await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) + + await expect(first).resolves.toEqual({ status: 'timed-out' }) + await expectSecondAgentToFinish(second) + }) +}) diff --git a/src/main/speech/dictation-cleanup-service.ts b/src/main/speech/dictation-cleanup-service.ts new file mode 100644 index 00000000000..a053995aade --- /dev/null +++ b/src/main/speech/dictation-cleanup-service.ts @@ -0,0 +1,108 @@ +import { randomUUID } from 'node:crypto' +import { mkdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + DICTATION_CLEANUP_TIMEOUT_MS, + isDictationCleanupOn, + type DictationCleanupResult +} from '../../shared/dictation-cleanup' +import type { DictationTerm } from '../../shared/dictation-dictionary' +import type { VoiceSettings } from '../../shared/speech-types' +import { getCommitMessageModel } from '../../shared/source-control/ai/generation/commit-message-agent-spec' +import { + prepareLocalCommitMessageAgentEnv, + type CommitMessageAgentEnvironmentResolvers +} from '../text-generation/execution/commit-message-agent-environment' +import { resolveCommitMessageSettings as resolveTextGenerationParams } from '../text-generation/commit-message-text-generation' +import { generateDictationCleanup } from '../text-generation/requests/dictation-cleanup-generation-request' +import { cancelLocalGeneration } from '../text-generation/execution/source-control-generation-lanes' + +export type DictationCleanupDeps = { + getSettings: () => Parameters[0] & { voice?: VoiceSettings } + getAgentEnvResolvers: () => CommitMessageAgentEnvironmentResolvers | undefined +} + +const skipsByRequest = new Map void>() + +export function cancelDictationCleanup(requestId: string): void { + skipsByRequest.get(requestId)?.() +} + +// One folder for every run, so the agent reads no project and keeps one history bucket, not one per dictation. +const cleanupFolder = (): string => join(tmpdir(), 'orca-dictation-cleanup') + +/** Runs the user's agent on dictated text, on this computer, in an empty folder of its own. */ +export async function cleanUpDictatedText( + input: { text: string; terms: readonly DictationTerm[]; requestId?: string }, + deps: DictationCleanupDeps +): Promise { + const settings = deps.getSettings() + if (!input.text.trim() || !isDictationCleanupOn(settings)) { + return { status: 'off' } + } + const startedAt = Date.now() + const stop = Promise.withResolvers<'timed-out' | 'canceled'>() + const timer = setTimeout(() => stop.resolve('timed-out'), DICTATION_CLEANUP_TIMEOUT_MS) + if (input.requestId) { + skipsByRequest.set(input.requestId, () => stop.resolve('canceled')) + } + let stopped = false + const cwd = cleanupFolder() + // Cleanups share the folder, so each gets its own cancel lane; a skip or timeout stops only its own agent. + const laneId = randomUUID() + try { + const resolved = resolveTextGenerationParams(settings, undefined, 'dictationCleanup') + if (!resolved.ok) { + return { status: 'failed', reason: resolved.error } + } + const { params } = resolved + const prepared = await Promise.race([ + prepareLocalCommitMessageAgentEnv(params.agentId, deps.getAgentEnvResolvers()), + stop.promise + ]) + if (typeof prepared === 'string') { + return { status: prepared } + } + if (!prepared.ok) { + return { status: 'failed', reason: prepared.error } + } + await mkdir(cwd, { recursive: true }) + const generation = generateDictationCleanup({ + text: input.text, + voice: settings.voice, + terms: input.terms, + params, + target: { kind: 'local', cwd, laneId, ...(prepared.env ? { env: prepared.env } : {}) } + }) + const outcome = await Promise.race([generation, stop.promise]) + if (typeof outcome === 'string') { + stopped = true + return { status: outcome } + } + if (!outcome.success) { + return outcome.canceled ? { status: 'canceled' } : { status: 'failed', reason: outcome.error } + } + return { + status: 'cleaned', + text: outcome.text, + agentLabel: outcome.agentLabel ?? params.agentId, + model: + (params.agentId !== 'custom' && + getCommitMessageModel(params.agentId, params.model)?.label) || + params.model, + elapsedMs: Date.now() - startedAt + } + } catch (error) { + return { status: 'failed', reason: error instanceof Error ? error.message : String(error) } + } finally { + clearTimeout(timer) + if (input.requestId) { + skipsByRequest.delete(input.requestId) + } + // Stops the agent still running after a timeout or a skip. + if (stopped) { + cancelLocalGeneration('dictation-cleanup', cwd, laneId) + } + } +} diff --git a/src/main/speech/model-catalog.ts b/src/main/speech/model-catalog.ts index e8a315a5c27..cca051424dd 100644 --- a/src/main/speech/model-catalog.ts +++ b/src/main/speech/model-catalog.ts @@ -30,6 +30,20 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [ streaming: false, recommended: true }, + { + // Ahead of v2, which measures the same, so it wins the tie as the most accurate English pick. + id: 'parakeet-unified-en-0.6b', + label: 'Parakeet Unified EN', + type: 'transducer', + provider: 'local', + language: 'en', + ...getGgufSpeechModelDownload('parakeet-unified-en-0.6b'), + languages: ['en'], + ...getSpeechModelErrorRates('parakeet-unified-en-0.6b'), + licence: 'NVIDIA Open Model License', + sampleRate: 16000, + streaming: true + }, { id: 'parakeet-tdt-0.6b-v2-int8', label: 'Parakeet TDT v2', @@ -180,8 +194,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [ ...getSpeechModelErrorRates('nemotron-3.5-asr-streaming-0.6b'), licence: 'OpenMDW-1.1', sampleRate: 16000, - // Decoded per chunk for now; live text arrives with the streaming engine path. - streaming: false + streaming: true }, { id: 'openai-gpt-transcribe', diff --git a/src/main/speech/speech-model-error-rates.ts b/src/main/speech/speech-model-error-rates.ts index 9418e179081..e1714b71a58 100644 --- a/src/main/speech/speech-model-error-rates.ts +++ b/src/main/speech/speech-model-error-rates.ts @@ -18,6 +18,8 @@ const MEASURED = { ['pt', 11.3, '2026-11-09'], ['ru', 3.4, '2026-11-06'] ], + // Streamed, as dictation decodes it; one whole-clip decode scores 2.35. + 'parakeet-unified-en-0.6b': [['en', 2.8, '2026-11-12']], 'parakeet-tdt-0.6b-v2-int8': [['en', 2.8, '2026-11-06']], 'whisper-tiny': [ ['en', 13, '2026-11-09'], diff --git a/src/main/speech/speech-model-gguf-downloads.ts b/src/main/speech/speech-model-gguf-downloads.ts index c8b1c9c0c2a..5c8dd33ea53 100644 --- a/src/main/speech/speech-model-gguf-downloads.ts +++ b/src/main/speech/speech-model-gguf-downloads.ts @@ -17,6 +17,13 @@ const GGUF_DOWNLOADS = { 739_508_576, '5859f77944efcd8eafa23a6350731960b2b55b2203df51f319665c807d802cc7' ], + 'parakeet-unified-en-0.6b': [ + 'handy-computer/parakeet-unified-en-0.6b-gguf', + '843b1b175ace04f5a89d379c79e2518c0d065b25', + 'parakeet-unified-en-0.6b-Q8_0.gguf', + 731_357_568, + '4b50b6dd862bf6e346929aaf4f5eaacec003bfa3f56462d6c874b41ef2f38795' + ], 'parakeet-tdt-0.6b-v2-int8': [ 'handy-computer/parakeet-tdt-0.6b-v2-gguf', '07cee0616125a08ef619729bb47f40ef747e4bc4', diff --git a/src/main/speech/stt-live-decode.test.ts b/src/main/speech/stt-live-decode.test.ts new file mode 100644 index 00000000000..dcd8d97c00d --- /dev/null +++ b/src/main/speech/stt-live-decode.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import type * as TranscribeCpp from 'transcribe-cpp' +import { LiveDecode } from './stt-live-decode' + +// One scripted decode step per feed: the text so far and how much audio (ms) the stream has decoded. +function fakeSession(steps: { text: string; decodedMs: number }[]) { + let step = -1 + const stream = { + feed: async () => { + step += 1 + return { resultChanged: true, audioCommittedMs: steps[step].decodedMs } + }, + finalize: async () => ({}), + get text() { + return { full: steps[step].text } + }, + reset: () => {} + } + const session = { + stream: async () => stream + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: LiveDecode calls only stream(), feed(), finalize(), text and reset(). + return session as unknown as TranscribeCpp.Session +} + +describe('LiveDecode', () => { + it('shows text as it grows and commits it once quiet, covering up to a second before the decode', async () => { + const session = fakeSession([ + { text: 'I have', decodedMs: 1120 }, + { text: 'I have two questions', decodedMs: 2240 }, + { text: 'I have two questions', decodedMs: 3360 }, + { text: 'I have two questions', decodedMs: 4480 }, + { text: 'I have two questions. First', decodedMs: 5600 } + ]) + const live = new LiveDecode(session, {}, 16000, null) + const feed = (index: number) => live.feed(new Float32Array(17920), 32000 + 17920 * (index + 1)) + + expect(await feed(0)).toEqual({ type: 'partial', text: 'I have' }) + expect(await feed(1)).toEqual({ type: 'partial', text: 'I have two questions' }) + expect(await feed(2)).toBeNull() + // Started at 32000 samples (2 s in); quiet from 2.24 s decoded, committed up to 3.48 s decoded. + expect(await feed(3)).toEqual({ + type: 'quiet', + text: 'I have two questions', + covered: 32000 + 55680 + }) + expect(await feed(4)).toEqual({ type: 'partial', text: '. First' }) + expect(await live.end(true)).toBe('. First') + }) +}) diff --git a/src/main/speech/stt-live-decode.ts b/src/main/speech/stt-live-decode.ts new file mode 100644 index 00000000000..541251cfe0f --- /dev/null +++ b/src/main/speech/stt-live-decode.ts @@ -0,0 +1,147 @@ +import type * as TranscribeCpp from 'transcribe-cpp' +import { SILENCE_PROBABILITY, type VadStream } from './stt-vad-pause-segmenter' + +// Commit once the text has not changed for twice this much decoded audio, covering all but this much: +// a CPU replay then starts in the quiet, clear of the last word posted and the next one. +const QUIET_MARGIN_MS = 1000 +// Silence this long sits between words, so a stream ended there cuts none in two. +const PAUSE_SECONDS = 0.15 + +export type LiveDecodeUpdate = + /** Text since the last commit, which may still change. */ + | { type: 'partial'; text: string } + /** The speaker went quiet: `text` is new since the last commit, and `covered` (stream position) accounts for it. */ + | { type: 'quiet'; text: string; covered: number } + +/** + * A streaming model's decode for one dictation, fed every chunk so its text keeps context across pauses. + * transcribe-cpp's own committed text stalls for good after the first sentence (0.4.1, Nemotron), so the + * text is committed here instead, when the speaker goes quiet; this model family never revises emitted text. + */ +export class LiveDecode { + private native: TranscribeCpp.Stream | null = null + /** Stream position (model-rate samples) where `native` began. */ + private from = 0 + private text = '' + /** Characters of `text` already committed. */ + private committed = 0 + /** How much audio `native` had decoded (ms) when its text last changed. */ + private changedAtMs = 0 + /** Silero frames of silence at the end of the audio so far. */ + private silentFrames = 0 + + private readonly pauseFrames: number + + /** Without Silero the stream is never known to be at a pause. */ + constructor( + private readonly session: TranscribeCpp.Session, + private readonly options: TranscribeCpp.StreamOptions, + private readonly modelRate: number, + private silero: { vad: VadStream; frameSamples: number } | null + ) { + this.pauseFrames = silero ? Math.ceil((PAUSE_SECONDS * modelRate) / silero.frameSamples) : 0 + } + + /** A running native stream holds the whole model; nothing else can decode until it ends. */ + get holdsModel(): boolean { + return this.native !== null + } + + /** The speaker is pausing, so ending the stream now cuts no word in two. */ + get atPause(): boolean { + return !!this.silero && this.silentFrames >= this.pauseFrames + } + + /** `position`: stream position (model-rate samples) at the end of `samples`. */ + async feed(samples: Float32Array, position: number): Promise { + // transcribe-cpp rejects an empty feed, and a phone can send one. + if (samples.length === 0) { + return null + } + if (!this.native) { + this.native = await this.session.stream(this.options) + this.from = position - samples.length + this.text = '' + this.committed = 0 + this.changedAtMs = 0 + } + await this.notePauses(samples) + const native = this.native + const update = await native.feed(samples).catch((error: unknown) => { + // A failed stream has let go of the model; the next feed starts a new one. + this.reset() + throw error + }) + const text = update.resultChanged ? native.text.full : this.text + if (text !== this.text) { + this.text = text + this.changedAtMs = update.audioCommittedMs + return { type: 'partial', text: text.slice(this.committed).trim() } + } + if (update.audioCommittedMs - this.changedAtMs < 2 * QUIET_MARGIN_MS) { + return null + } + const quietAt = update.audioCommittedMs - QUIET_MARGIN_MS + return { + type: 'quiet', + text: this.commit(), + covered: this.from + Math.round((quietAt * this.modelRate) / 1000) + } + } + + /** Ends the native stream, returning its uncommitted text, or null when none was running; the next feed starts another. */ + async end(finalize: boolean): Promise { + const native = this.native + if (!native) { + return null + } + this.native = null + try { + if (finalize) { + await native.finalize() + this.text = native.text.full + } + } finally { + native.reset() + } + return this.commit() + } + + private async notePauses(samples: Float32Array): Promise { + try { + for (const probability of (await this.silero?.vad.streamFeed(samples))?.probs ?? []) { + this.silentFrames = probability < SILENCE_PROBABILITY ? this.silentFrames + 1 : 0 + } + } catch (error) { + // Optional, as for pause-cut dictation: without it the stream restarts only at the hard bound. + console.warn('[speech] Silero VAD failed; this dictation restarts only at its bound:', error) + this.silero = null + } + } + + reset(): void { + this.native?.reset() + this.native = null + } + + private commit(): string { + const text = this.text.slice(this.committed).trim() + this.committed = this.text.length + return text + } +} + +/** Runs one decode step on silence, so the stream path's GPU pipelines compile before the first dictation. */ +export async function warmUpLiveDecode( + session: TranscribeCpp.Session, + options: TranscribeCpp.StreamOptions, + modelRate: number +): Promise { + const stream = await session.stream(options) + try { + // Longer than a streaming family's decode step (Nemotron's is 1.12 s). + await stream.feed(new Float32Array(Math.round(modelRate * 1.5))) + } finally { + stream.reset() + } +} diff --git a/src/main/speech/stt-offline-audio-chunker.ts b/src/main/speech/stt-offline-audio-chunker.ts index d34be24ec33..2ed0b531768 100644 --- a/src/main/speech/stt-offline-audio-chunker.ts +++ b/src/main/speech/stt-offline-audio-chunker.ts @@ -88,3 +88,38 @@ export class OfflineAudioChunker { return Math.max(1, bestIndex) } } + +// Without the detector, audio is still cut at the decode bound, just not at pauses. +export type AudioSegmenter = { + readonly heldSamples: number + readonly phraseOpen?: boolean + push(samples: Float32Array): Float32Array[] | Promise + flush(): Float32Array[] | Promise +} + +export function boundedChunks(sampleRate: number): AudioSegmenter { + const chunker = new OfflineAudioChunker(sampleRate) + return { + get heldSamples() { + return chunker.heldSamples + }, + push: (samples) => chunker.push(samples), + flush: () => { + const rest = chunker.flush() + return rest ? [rest] : [] + } + } +} + +export function joinAudio(parts: Float32Array[]): Float32Array { + if (parts.length === 1) { + return parts[0] + } + const joined = new Float32Array(parts.reduce((total, part) => total + part.length, 0)) + let offset = 0 + for (const part of parts) { + joined.set(part, offset) + offset += part.length + } + return joined +} diff --git a/src/main/speech/stt-recognizer.ts b/src/main/speech/stt-recognizer.ts index fb440a87295..d73b24a8030 100644 --- a/src/main/speech/stt-recognizer.ts +++ b/src/main/speech/stt-recognizer.ts @@ -6,14 +6,16 @@ export type SttRecognizerInit = { sampleRate: number /** Absent = auto-detect. */ language?: string - /** Silero VAD GGUF; when present, offline models commit text at each pause. */ + /** Silero VAD GGUF; when present, offline models show live text at each pause. */ vadModelPath?: string } export type SttRecognizerEvent = - /** One decoded offline chunk; `samples` counts the stream's input-rate samples decoded so far. */ + /** Newly committed text; `samples` counts the stream's input-rate samples it and earlier chunks account for. */ | { type: 'chunk'; streamId: string; text: string; samples: number } - /** Pause-cut streams only: speech was heard that no chunk has committed yet. */ + /** The uncommitted text so far, which may still change; the next chunk replaces it. */ + | { type: 'partial'; streamId: string; text: string } + /** Pause-cut streams only: speech was heard whose text hasn't arrived yet. */ | { type: 'speech-pending'; streamId: string; pending: boolean } /** A load step finished, so a slow load is told apart from a hung GPU. */ | { type: 'loading' } diff --git a/src/main/speech/stt-service.ts b/src/main/speech/stt-service.ts index bacc4b753ed..97231babfbc 100644 --- a/src/main/speech/stt-service.ts +++ b/src/main/speech/stt-service.ts @@ -24,7 +24,7 @@ export type SttEvent = | { type: 'ready' } | { type: 'partial'; text?: string } | { type: 'final'; text?: string } - /** Speech was heard that no final has committed yet; only from pause-cut on-device models. */ + /** Speech was heard whose text hasn't arrived yet; only from pause-cut on-device models. */ | { type: 'speech-pending'; pending: boolean } | { type: 'stopped' } | { type: 'error'; error?: string } diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.test.ts b/src/main/speech/stt-transcribe-cpp-recognizer.test.ts new file mode 100644 index 00000000000..0f1eb33bbeb --- /dev/null +++ b/src/main/speech/stt-transcribe-cpp-recognizer.test.ts @@ -0,0 +1,190 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { SttRecognizer, SttRecognizerEvent } from './stt-recognizer' +import { createTranscribeCppRecognizer } from './stt-transcribe-cpp-recognizer' +import { installFakeTranscribeCpp } from './transcribe-cpp-fake.test-fixture' + +// 100 Hz audio in 0.1 s VAD frames. A sample's value names the word spoken there (1 = "one"), 0 is silence. +const RATE = 100 +const WORDS = ['', 'one', 'two', 'three', 'four', 'five'] + +const speech = (word: number, seconds: number, rate = RATE) => + new Float32Array(Math.round(seconds * rate)).fill(word) +const silence = (seconds: number, rate = RATE) => new Float32Array(Math.round(seconds * rate)) + +function audio(...parts: Float32Array[]): Float32Array { + const out = new Float32Array(parts.reduce((total, part) => total + part.length, 0)) + let offset = 0 + for (const part of parts) { + out.set(part, offset) + offset += part.length + } + return out +} + +// Like Parakeet, one decode is one sentence, so a phrase decoded alone ends in a full stop. +function sentence(pcm: Float32Array): string { + const words: string[] = [] + let last = 0 + for (const sample of pcm) { + const word = Math.round(sample) + if (word !== 0 && word !== last) { + words.push(WORDS[word]) + } + last = word + } + const text = words.join(' ') + return text ? `${text[0].toUpperCase()}${text.slice(1)}.` : '' +} + +let decode: (pcm: Float32Array) => string | Promise = sentence +let dispose: (() => void) | undefined + +afterEach(() => { + dispose?.() + dispose = undefined + decode = sentence +}) + +async function start(): Promise<{ recognizer: SttRecognizer; posted: SttRecognizerEvent[] }> { + const fake = installFakeTranscribeCpp({ + sampleRate: RATE, + vadFrameSamples: 10, + speechProbability: (frame) => (frame.some((sample) => Math.round(sample) !== 0) ? 0.9 : 0), + transcribe: (pcm) => decode(pcm) + }) + dispose = fake.dispose + const posted: SttRecognizerEvent[] = [] + const recognizer = await createTranscribeCppRecognizer( + { + speechModulesDir: fake.speechModulesDir, + modelDir: '/models/parakeet', + files: ['model.gguf'], + sampleRate: 16000, + vadModelPath: '/models/silero-vad.gguf' + }, + (event) => posted.push(event) + ) + recognizer.open('s', []) + return { recognizer, posted } +} + +type Transcript = ({ partial: string } | { chunk: string; samples: number })[] + +// Text and coverage only; loading and speech-pending events are other behaviour. +const transcript = (posted: SttRecognizerEvent[]): Transcript => + posted.flatMap((event) => + event.type === 'partial' + ? [{ partial: event.text }] + : event.type === 'chunk' + ? [{ chunk: event.text, samples: event.samples }] + : [] + ) + +describe('createTranscribeCppRecognizer', () => { + it('shows each phrase live at a pause and commits the span as one decode', async () => { + const { recognizer, posted } = await start() + await recognizer.feed('s', audio(speech(1, 2), silence(1), speech(2, 2), silence(1)), RATE) + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + { partial: 'One.' }, + { partial: 'One. Two.' }, + { chunk: 'One two.', samples: 600 } + ]) + }) + + it('commits a single-phrase span with its live text, without decoding again', async () => { + const { recognizer, posted } = await start() + await recognizer.feed('s', audio(speech(1, 2), silence(1)), RATE) + decode = () => 'A second decode.' + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([{ partial: 'One.' }, { chunk: 'One.', samples: 300 }]) + }) + + it('commits once 20 s of audio waits, then starts a new span', async () => { + const { recognizer, posted } = await start() + for (const word of [1, 2, 3, 4, 5]) { + await recognizer.feed('s', audio(speech(word, 4), silence(1)), RATE) + } + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + { partial: 'One.' }, + { partial: 'One. Two.' }, + { partial: 'One. Two. Three.' }, + { partial: 'One. Two. Three. Four.' }, + // The pause's last 0.4 s is held as the next phrase's lead-in, so it isn't covered yet. + { chunk: 'One two three four.', samples: 1960 }, + { partial: 'Five.' }, + { chunk: 'Five.', samples: 2500 } + ]) + }) + + it('commits before a phrase that would take the span past 30 s', async () => { + const { recognizer, posted } = await start() + await recognizer.feed( + 's', + audio(speech(1, 12), silence(1), speech(2, 12), silence(1), speech(3, 12), silence(1)), + RATE + ) + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + { partial: 'One.' }, + { partial: 'One. Two.' }, + { chunk: 'One two.', samples: 2560 }, + { partial: 'Three.' }, + { chunk: 'Three.', samples: 3900 } + ]) + }) + + it('reports coverage in fed input samples, through resampling and dropped silence', async () => { + const { recognizer, posted } = await start() + // 160 Hz in 161-sample feeds: each resamples to 101 samples, so the nominal 1.6 ratio would drift. + for (let feed = 0; feed < 6; feed += 1) { + await recognizer.feed('s', silence(161 / 160, 160), 160) + } + await recognizer.feed('s', audio(speech(1, 2, 160), silence(1, 160)), 160) + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + // Over 5 s of silence: no text, but the host may drop that audio from its replay buffer. + { chunk: '', samples: 893 }, + { partial: 'One.' }, + { chunk: 'One.', samples: 1446 } + ]) + }) + + // The running decode finishes; nothing after it decodes or commits, though the 26 s fed is past the 20 s commit. + it.each<{ cancelDuring: string; expected: Transcript }>([ + { cancelDuring: 'One.', expected: [{ partial: 'One.' }] }, + { cancelDuring: 'Two.', expected: [{ partial: 'One.' }, { partial: 'One. Two.' }] } + ])('skips the rest of a stream canceled while decoding "$cancelDuring"', async (testCase) => { + const { recognizer, posted } = await start() + let decodeStarted!: () => void + const started = new Promise((resolve) => (decodeStarted = resolve)) + let releaseDecode!: () => void + const released = new Promise((resolve) => (releaseDecode = resolve)) + decode = async (pcm) => { + const text = sentence(pcm) + if (text === testCase.cancelDuring) { + decodeStarted() + await released + } + return text + } + const feeding = recognizer.feed( + 's', + audio(speech(1, 12), silence(1), speech(2, 12), silence(1)), + RATE + ) + await started + recognizer.cancel('s') + releaseDecode() + await feeding + recognizer.discard('s') + + expect(transcript(posted)).toEqual(testCase.expected) + }) +}) diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.ts b/src/main/speech/stt-transcribe-cpp-recognizer.ts index f292db59403..d0968dbb69b 100644 --- a/src/main/speech/stt-transcribe-cpp-recognizer.ts +++ b/src/main/speech/stt-transcribe-cpp-recognizer.ts @@ -2,9 +2,16 @@ import { availableParallelism } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import type * as TranscribeCpp from 'transcribe-cpp' +import { appendDictationText } from '../../shared/dictation-transcript-spacing' import { resampleToRate } from './stt-audio-resample' -import { OfflineAudioChunker } from './stt-offline-audio-chunker' -import { VadPauseSegmenter } from './stt-vad-pause-segmenter' +import { + type AudioSegmenter, + boundedChunks, + joinAudio, + OFFLINE_DECODE_CHUNK_SECONDS +} from './stt-offline-audio-chunker' +import { LiveDecode, warmUpLiveDecode } from './stt-live-decode' +import { loadSileroVad, VadPauseSegmenter } from './stt-vad-pause-segmenter' import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer' // Past ~8 threads decode slowed 2-4x under load in the 2026-11 benchmark; E-cores and SMT siblings @@ -14,38 +21,22 @@ function performanceCoreThreads(): number { return Math.min(logical, 8, Math.max(4, Math.floor(logical / 2))) } -// Without the detector, audio is still cut at the decode bound, just not at pauses. -type AudioSegmenter = { - readonly heldSamples: number - readonly phraseOpen?: boolean - push(samples: Float32Array): Float32Array[] | Promise - flush(): Float32Array[] | Promise -} - -function boundedChunks(sampleRate: number): AudioSegmenter { - const chunker = new OfflineAudioChunker(sampleRate) - return { - get heldSamples() { - return chunker.heldSamples - }, - push: (samples) => chunker.push(samples), - flush: () => { - const rest = chunker.flush() - return rest ? [rest] : [] - } - } -} - // Totals, not the nominal rate ratio: per-feed resampling rounds, and the drift would replay decoded audio. type StreamCoverage = { options: TranscribeCpp.TranscribeOptions + /** Streaming models only, unless another dictation already streams. */ + live: LiveDecode | null segmenter: AudioSegmenter vad: TranscribeCpp.VadSession | null inputSamples: number resampledSamples: number reportedSamples: number + /** Stream position the last phrase decode reached, for its speed check. */ + decodedSamples: number slowPhraseDecodes: number speechPending: boolean + /** Phrases since the last commit and their live text. */ + span: { audio: Float32Array[]; samples: number; texts: string[] } } // Whisper pads every decode to a 30 s window, so each phrase costs a full decode. Where that takes longer than the @@ -56,30 +47,10 @@ const SLOW_PHRASE_DECODES_BEFORE_NO_CUTS = 2 // Dropped silence still counts as covered; report it so the host's replay buffer and stall watch don't grow through long pauses. const SILENCE_COVERAGE_REPORT_SECONDS = 5 -// Optional: without it dictation still works, with text only at the decode bound and at stop. -async function loadSileroVad( - transcribe: typeof TranscribeCpp, - path: string | undefined, - sampleRate: number -): Promise { - if (!path) { - return null - } - try { - // Tiny and per-frame; the CPU keeps it off a GPU that may fail over. - const model = await transcribe.TranscribeModel.load(path, { backend: 'cpu' }) - if (model.vadInfo.sampleRate === sampleRate) { - return model - } - console.warn( - `[speech] Silero VAD needs ${model.vadInfo.sampleRate} Hz; this model takes ${sampleRate} Hz` - ) - model.dispose() - } catch (error) { - console.warn('[speech] Silero VAD unavailable; text arrives at stop:', error) - } - return null -} +// The CPU fallback keeps uncommitted audio for a replay and takes over 30 s of it for a stalled GPU. +const COMMIT_AFTER_SECONDS = 20 +// A live dictation with no quiet to commit at restarts its stream by then, at a pause if it can. +const LIVE_COMMIT_BY_SECONDS = 25 export async function createTranscribeCppRecognizer( init: SttRecognizerInit, @@ -119,19 +90,33 @@ export async function createTranscribeCppRecognizer( const vadModel = await loadSileroVad(transcribe, init.vadModelPath, modelRate) const streams = new Map() const openStream = (streamId: string, vocabulary: readonly string[]): StreamCoverage => { + // A dictation that starts beside a live one is pause-cut, so the two don't take the model from each other per feed. + const live = + model.capabilities.supportsStreaming && + ![...streams].some(([id, other]) => id !== streamId && other.live) // A VAD stream is per-dictation state, so each dictation gets its own session. const vad = vadModel?.createVadSession({ nThreads: 1 }) ?? null const stream: StreamCoverage = { options: streamOptions(vocabulary), + live: live + ? new LiveDecode( + session, + streamOptions(vocabulary), + modelRate, + vad && vadModel && { vad, frameSamples: vadModel.vadInfo.frameSamples } + ) + : null, segmenter: boundedChunks(modelRate), vad, inputSamples: 0, resampledSamples: 0, reportedSamples: 0, + decodedSamples: 0, slowPhraseDecodes: 0, - speechPending: false + speechPending: false, + span: { audio: [], samples: 0, texts: [] } } - if (vad && vadModel) { + if (vad && vadModel && !live) { stream.segmenter = new VadPauseSegmenter( vad, modelRate, @@ -139,15 +124,28 @@ export async function createTranscribeCppRecognizer( () => stream.slowPhraseDecodes < SLOW_PHRASE_DECODES_BEFORE_NO_CUTS ) } - streams.get(streamId)?.vad?.dispose() + const replaced = streams.get(streamId) + if (replaced) { + dropStream(replaced) + } streams.set(streamId, stream) return stream } + const dropStream = (stream: StreamCoverage) => { + stream.vad?.dispose() + stream.live?.reset() + } + const transcribeChunk = async ( chunk: Float32Array, options: TranscribeCpp.TranscribeOptions ): Promise => { + // transcribe-cpp lets one native stream hold the model at a time. + const holder = [...streams].find(([, other]) => other.live?.holdsModel) + if (holder) { + await endLive(...holder) + } try { return (await session.run(chunk, options)).text } catch (error) { @@ -159,12 +157,13 @@ export async function createTranscribeCppRecognizer( } } - // The first run compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop. - await transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions) + // Stream position (model-rate samples) the segmenter has handed on, less chunks still waiting to be decoded. + const position = (stream: StreamCoverage, undecoded: number) => + stream.resampledSamples - stream.segmenter.heldSamples - undecoded - // Coverage is in input-rate samples so the host can trim the audio it keeps for a CPU replay. - const report = (streamId: string, stream: StreamCoverage, text: string, undecoded: number) => { - const covered = stream.resampledSamples - stream.segmenter.heldSamples - undecoded + // `covered`: stream position (model-rate samples) the posted text accounts for. Reported in input-rate samples + // so the host can trim the audio it keeps for a CPU replay. + const report = (streamId: string, stream: StreamCoverage, text: string, covered: number) => { stream.reportedSamples = covered post({ type: 'chunk', @@ -177,29 +176,60 @@ export async function createTranscribeCppRecognizer( // Canceled streams, until their queued discard runs; also covers a finish that already closed its stream. const canceled = new Set() - const decode = async (streamId: string, stream: StreamCoverage, chunks: Float32Array[]) => { + const spanLimit = OFFLINE_DECODE_CHUNK_SECONDS * modelRate + + // The span's phrases decode again together, so a pause mid-sentence doesn't capitalize the words after it. + const commit = async (streamId: string, stream: StreamCoverage, undecoded: number) => { + const { audio, texts } = stream.span + if (audio.length === 0 || canceled.has(streamId)) { + return + } + stream.span = { audio: [], samples: 0, texts: [] } + const text = + audio.length === 1 && texts.length === 1 + ? texts[0] + : (await transcribeChunk(joinAudio(audio), stream.options)).trim() + report(streamId, stream, text, position(stream, undecoded)) + } + + /** `live`: decode each phrase as it ends for live text; at stop only the commit decodes. */ + const decode = async ( + streamId: string, + stream: StreamCoverage, + chunks: Float32Array[], + live: boolean + ) => { let undecoded = chunks.reduce((total, chunk) => total + chunk.length, 0) for (const chunk of chunks) { if (canceled.has(streamId)) { return } - const startedAt = performance.now() - const text = await transcribeChunk(chunk, stream.options) - const decodeMs = performance.now() - startedAt - const spokenSince = stream.reportedSamples - undecoded -= chunk.length - report(streamId, stream, text.trim(), undecoded) - if (stream.vad) { - noteDecodeSpeed( - stream, - decodeMs, - ((stream.reportedSamples - spokenSince) / modelRate) * 1000 - ) + if (stream.span.samples + chunk.length > spanLimit) { + await commit(streamId, stream, undecoded) } + undecoded -= chunk.length + stream.span.audio.push(chunk) + stream.span.samples += chunk.length + if (!live) { + continue + } + const startedAt = performance.now() + const text = (await transcribeChunk(chunk, stream.options)).trim() + const decodeMs = performance.now() - startedAt + stream.span.texts.push(text) + post({ type: 'partial', streamId, text: stream.span.texts.reduce(appendDictationText, '') }) + const reached = position(stream, undecoded) + if (stream.vad) { + noteDecodeSpeed(stream, decodeMs, ((reached - stream.decodedSamples) / modelRate) * 1000) + } + stream.decodedSamples = reached } - const dropped = stream.resampledSamples - stream.segmenter.heldSamples - stream.reportedSamples - if (dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) { - report(streamId, stream, '', 0) + if (stream.resampledSamples - stream.reportedSamples >= COMMIT_AFTER_SECONDS * modelRate) { + await commit(streamId, stream, 0) + } + const dropped = position(stream, 0) - stream.reportedSamples + if (stream.span.samples === 0 && dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) { + report(streamId, stream, '', position(stream, 0)) } } @@ -223,12 +253,50 @@ export async function createTranscribeCppRecognizer( } } + const feedLive = async ( + streamId: string, + stream: StreamCoverage, + live: LiveDecode, + samples: Float32Array + ) => { + if (canceled.has(streamId)) { + return + } + const update = await live.feed(samples, stream.resampledSamples) + if (update?.type === 'partial') { + post({ type: 'partial', streamId, text: update.text }) + } else if (update) { + const silence = + update.covered - stream.reportedSamples >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate + if (update.text || silence) { + report(streamId, stream, update.text, update.covered) + } + } + const held = (stream.resampledSamples - stream.reportedSamples) / modelRate + if (held >= LIVE_COMMIT_BY_SECONDS || (held >= COMMIT_AFTER_SECONDS && live.atPause)) { + await endLive(streamId, stream) + } + } + + // At stop, or when another dictation needs the model. + const endLive = async (streamId: string, stream: StreamCoverage) => { + const text = await stream.live?.end(!canceled.has(streamId)) + if (text != null && !canceled.has(streamId)) { + report(streamId, stream, text, stream.resampledSamples) + } + } + const closeStream = (streamId: string): StreamCoverage | undefined => { const stream = streams.get(streamId) streams.delete(streamId) return stream } + // The first decode compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop. + await (model.capabilities.supportsStreaming + ? warmUpLiveDecode(session, baseOptions, modelRate) + : transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions)) + return { open(streamId, vocabulary) { openStream(streamId, vocabulary) @@ -241,11 +309,18 @@ export async function createTranscribeCppRecognizer( ) stream.inputSamples += samples.length stream.resampledSamples += resampled.length + if (stream.live) { + await feedLive(streamId, stream, stream.live, resampled) + return + } const phrases = await stream.segmenter.push(resampled) // A cut phrase stays pending until its text is posted. notePendingSpeech(streamId, stream, phrases.length > 0 || !!stream.segmenter.phraseOpen) - await decode(streamId, stream, phrases) - notePendingSpeech(streamId, stream, !!stream.segmenter.phraseOpen) + // Only beside a live dictation, whose native stream each decode ends, so this one decodes only to commit. + const phraseText = !model.capabilities.supportsStreaming + await decode(streamId, stream, phrases, phraseText) + const textless = !phraseText && stream.span.samples > 0 + notePendingSpeech(streamId, stream, !!stream.segmenter.phraseOpen || textless) }, async finish(streamId) { const stream = closeStream(streamId) @@ -253,15 +328,23 @@ export async function createTranscribeCppRecognizer( return } try { - await decode(streamId, stream, await stream.segmenter.flush()) + if (stream.live) { + await endLive(streamId, stream) + return + } + await decode(streamId, stream, await stream.segmenter.flush(), false) + await commit(streamId, stream, 0) notePendingSpeech(streamId, stream, false) } finally { - stream.vad?.dispose() + dropStream(stream) } }, discard(streamId) { canceled.delete(streamId) - closeStream(streamId)?.vad?.dispose() + const stream = closeStream(streamId) + if (stream) { + dropStream(stream) + } }, cancel(streamId) { canceled.add(streamId) diff --git a/src/main/speech/stt-vad-pause-segmenter.test.ts b/src/main/speech/stt-vad-pause-segmenter.test.ts index a5e8285fb1e..20a18f128fe 100644 --- a/src/main/speech/stt-vad-pause-segmenter.test.ts +++ b/src/main/speech/stt-vad-pause-segmenter.test.ts @@ -1,34 +1,12 @@ import { describe, expect, it } from 'vitest' -import { VadPauseSegmenter, type VadStream } from './stt-vad-pause-segmenter' +import { VadPauseSegmenter } from './stt-vad-pause-segmenter' +import { fakeVadSession } from './transcribe-cpp-fake.test-fixture' // 100 Hz audio in 10-sample (0.1 s) frames; each sample holds its frame's speech probability, so outputs show which frames survived. const RATE = 100 const FRAME = 10 -function fakeVad(): VadStream { - let pending: number[] = [] - let frames = 0 - const score = (flush: boolean) => { - const probs: number[] = [] - while (pending.length >= FRAME || (flush && pending.length > 0)) { - probs.push(pending[0]) - pending = pending.slice(FRAME) - } - const firstFrame = frames - frames = flush ? 0 : frames + probs.length - return { probs, firstFrame, segments: [] } - } - return { - streamFeed: async (pcm) => { - if (!(pcm instanceof Float32Array)) { - throw new Error('the segmenter feeds Float32Array') - } - pending.push(...pcm) - return score(false) - }, - streamFlush: async () => score(true) - } -} +const fakeVad = () => fakeVadSession(FRAME, (frame) => frame[0]) function audio(frames: number[]): Float32Array { return Float32Array.from(frames.flatMap((probability) => Array(FRAME).fill(probability))) diff --git a/src/main/speech/stt-vad-pause-segmenter.ts b/src/main/speech/stt-vad-pause-segmenter.ts index 8e7fc3b3d33..e18c0d0e8a7 100644 --- a/src/main/speech/stt-vad-pause-segmenter.ts +++ b/src/main/speech/stt-vad-pause-segmenter.ts @@ -3,8 +3,8 @@ import { OfflineAudioChunker } from './stt-offline-audio-chunker' // Silero's own defaults: a frame at or above this is speech; inside speech, one below the second is silence. const SPEECH_PROBABILITY = 0.5 -const SILENCE_PROBABILITY = 0.35 -// A pause this long commits the phrase before it. Shorter cuts split phrases, and each piece gets its own capital and full stop. +export const SILENCE_PROBABILITY = 0.35 +// A pause this long ends the phrase before it, which then decodes for live text; every cut costs a decode. export const VAD_PAUSE_SECONDS = 0.6 // Silence kept ahead of detected speech so a soft first syllable isn't clipped. const SPEECH_PREROLL_SECONDS = 0.4 @@ -162,3 +162,28 @@ function concat(a: Float32Array, b: Float32Array): Float32Array { out.set(b, a.length) return out } + +// Optional: without it dictation still works, with text only at the decode bound and at stop. +export async function loadSileroVad( + transcribe: typeof TranscribeCpp, + path: string | undefined, + sampleRate: number +): Promise { + if (!path) { + return null + } + try { + // Tiny and per-frame; the CPU keeps it off a GPU that may fail over. + const model = await transcribe.TranscribeModel.load(path, { backend: 'cpu' }) + if (model.vadInfo.sampleRate === sampleRate) { + return model + } + console.warn( + `[speech] Silero VAD needs ${model.vadInfo.sampleRate} Hz; this model takes ${sampleRate} Hz` + ) + model.dispose() + } catch (error) { + console.warn('[speech] Silero VAD unavailable; text arrives at stop:', error) + } + return null +} diff --git a/src/main/speech/transcribe-cpp-fake.test-fixture.ts b/src/main/speech/transcribe-cpp-fake.test-fixture.ts new file mode 100644 index 00000000000..2435685985a --- /dev/null +++ b/src/main/speech/transcribe-cpp-fake.test-fixture.ts @@ -0,0 +1,103 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { VadStream } from './stt-vad-pause-segmenter' + +export type FakeTranscribeEngine = { + /** The speech model's native rate; the VAD takes the same rate. */ + sampleRate: number + /** Samples per VAD probability. */ + vadFrameSamples: number + /** Speech probability of one VAD frame (the last one of a flush is zero padded). */ + speechProbability: (frame: Float32Array) => number + /** Text of one decode of this audio. */ + transcribe: (pcm: Float32Array) => string | Promise +} + +class OutputTruncated extends Error { + partialResult?: { text: string } +} + +/** A Silero VAD stream scoring each frame with `speechProbability`. */ +export function fakeVadSession( + frameSamples: number, + speechProbability: (frame: Float32Array) => number +): VadStream & { dispose: () => void } { + let pending: number[] = [] + let frames = 0 + const score = (flush: boolean) => { + const probs: number[] = [] + while (pending.length >= frameSamples || (flush && pending.length > 0)) { + const frame = new Float32Array(frameSamples) + frame.set(pending.slice(0, frameSamples)) + probs.push(speechProbability(frame)) + pending = pending.slice(frameSamples) + } + const firstFrame = frames + frames = flush ? 0 : frames + probs.length + return { probs, firstFrame, segments: [] } + } + return { + streamFeed: async (pcm) => { + if (!(pcm instanceof Float32Array)) { + throw new Error('the segmenter feeds Float32Array') + } + pending.push(...pcm) + return score(false) + }, + streamFlush: async () => score(true), + dispose: () => {} + } +} + +function fakeModel(engine: FakeTranscribeEngine) { + const languages: string[] = [] + return { + capabilities: { nativeSampleRate: engine.sampleRate, languages }, + vadInfo: { sampleRate: engine.sampleRate, frameSamples: engine.vadFrameSamples }, + supports: () => false, + createSession: () => ({ + run: async (pcm: Float32Array) => ({ text: await engine.transcribe(pcm) }) + }), + createVadSession: () => fakeVadSession(engine.vadFrameSamples, engine.speechProbability), + dispose: () => {} + } +} + +const MODULE_KEY = Symbol.for('orca.test.fakeTranscribeCpp') + +/** + * Writes a transcribe-cpp package backed by `engine` and returns the node_modules directory holding it, so the + * recognizer loads it the way it loads the real one. The package reads the engine from a global, which works + * whether the test runner transforms the file or Node loads it natively. + */ +export function installFakeTranscribeCpp(engine: FakeTranscribeEngine): { + speechModulesDir: string + dispose: () => void +} { + const speechModulesDir = mkdtempSync(join(tmpdir(), 'orca-fake-transcribe-cpp-')) + const dist = join(speechModulesDir, 'transcribe-cpp', 'dist') + mkdirSync(dist, { recursive: true }) + Reflect.set(globalThis, MODULE_KEY, { + initialize: async () => {}, + OutputTruncated, + TranscribeModel: { + // One model serves both roles: speech decodes and the Silero VAD. + load: async () => fakeModel(engine) + } + }) + writeFileSync(join(speechModulesDir, 'transcribe-cpp', 'package.json'), '{"type":"module"}\n') + writeFileSync( + join(dist, 'index.js'), + `const fake = globalThis[Symbol.for('orca.test.fakeTranscribeCpp')] +export const { initialize, OutputTruncated, TranscribeModel } = fake +` + ) + return { + speechModulesDir, + dispose: () => { + Reflect.deleteProperty(globalThis, MODULE_KEY) + rmSync(speechModulesDir, { recursive: true, force: true }) + } + } +} diff --git a/src/main/ssh/connection/ssh-connection.ts b/src/main/ssh/connection/ssh-connection.ts index 37a621f00d5..9d0c4509fc2 100644 --- a/src/main/ssh/connection/ssh-connection.ts +++ b/src/main/ssh/connection/ssh-connection.ts @@ -56,7 +56,7 @@ import { requiresSystemSshForSecurityKey, shouldUseSystemSshTransport } from '../system-transport/ssh-transport-selection' -import type { FileUploadSession } from '../../providers/filesystem-provider-contract' +import type { FileUploadSession } from '../../providers/filesystem/provider-contract' import { openSshExecChannel, openSshSftpChannel, diff --git a/src/main/providers/ssh-filesystem-provider-sftp.ts b/src/main/ssh/file-transfer/sftp/sftp-download.ts similarity index 100% rename from src/main/providers/ssh-filesystem-provider-sftp.ts rename to src/main/ssh/file-transfer/sftp/sftp-download.ts diff --git a/src/main/ssh/file-transfer/ssh-connection-file-transfers.ts b/src/main/ssh/file-transfer/ssh-connection-file-transfers.ts index f03824f1381..b4492cdbeaf 100644 --- a/src/main/ssh/file-transfer/ssh-connection-file-transfers.ts +++ b/src/main/ssh/file-transfer/ssh-connection-file-transfers.ts @@ -1,6 +1,6 @@ import type { SFTPWrapper } from 'ssh2' import type { SshTarget } from '../../../shared/ssh-types' -import type { FileUploadSession } from '../../providers/filesystem-provider-contract' +import type { FileUploadSession } from '../../providers/filesystem/provider-contract' import { resolveSftpTransferPathIfMapped, type SftpNamespacePathMapping @@ -66,7 +66,7 @@ export async function downloadSshFile( if (!host.usesSystemSshTransport()) { const sftp = await host.sftp() try { - const { fastGetViaSftp } = await import('../../providers/ssh-filesystem-provider-sftp') + const { fastGetViaSftp } = await import('./sftp/sftp-download') await fastGetViaSftp(sftp, remotePath, localPath) } finally { sftp.end() diff --git a/src/main/ssh/host-server/ssh-host-server-connect-events.ts b/src/main/ssh/host-server/ssh-host-server-connect-events.ts index cb46e501da6..899f97ab0ef 100644 --- a/src/main/ssh/host-server/ssh-host-server-connect-events.ts +++ b/src/main/ssh/host-server/ssh-host-server-connect-events.ts @@ -5,7 +5,7 @@ import type { } from '../../../shared/orcad-managed-runtime' import type { SshTarget } from '../../../shared/ssh-types' import type { HostServerOnConnectResult } from './ssh-host-server-on-connect' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/diagnostics/orcad-host-unavailable' export type HostServerConnectEvent = | { diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts index d10c4eed181..ede657e8357 100644 --- a/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts @@ -3,11 +3,8 @@ import type { SshTarget } from '../../../shared/ssh-types' import { OrcadHostUnsupportedError, OrcadStdioBridgeUnavailableError -} from '../../orcad/orcad-host-unavailable' -import { - resolveHostServerOnConnect, - type HostServerOnConnectDeps -} from './ssh-host-server-on-connect' +} from '../../orcad/diagnostics/orcad-host-unavailable' +import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } @@ -180,18 +177,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.recordUnavailable).toHaveBeenCalledWith(target, 'ssh_tunnel_unavailable') }) - it('keeps a staged or converted host fenced when its tunnel fails', async () => { - const failure = new OrcadStdioBridgeUnavailableError('exit 127') - const d = deps({ - managedEnvironmentId: () => 'env-9', - ensureTunnel: vi.fn(async () => { - throw failure - }) - }) - await expect(resolveHostServerOnConnect(target, d)).rejects.toBe(failure) - expect(d.releaseUnreachableSetup).not.toHaveBeenCalled() - }) - it('backs an uncommitted conversion out to the relay when its commit fails', async () => { const d = deps({ managedEnvironmentId: () => 'env-9', @@ -207,30 +192,4 @@ describe('which server an SSH host runs on connect', () => { }) expect(d.abandonConversion).toHaveBeenCalledWith(target) }) - - describe('updating a managed host on connect', () => { - const managed = (overrides: Partial) => - deps({ managedEnvironmentId: () => 'env-9', ...overrides }) - - it('starts a stopped server before the update counts its terminals, as after a reboot', async () => { - const order: string[] = [] - const d = managed({ - ensureServing: vi.fn(async () => { - order.push('start') - return { state: 'started' as const, boundPort: null } - }), - // Wake first so the restarted daemon can supply authoritative idle census. - autoUpdate: vi.fn(async (_id, options) => { - order.push('update') - options.onUpdating() - return { outcome: 'updated' as const, activeVersion: '0.1.0+b' } - }) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9' - }) - expect(order).toEqual(['start', 'update']) - }) - }) }) diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.ts index e0214aaabba..bda0ee93396 100644 --- a/src/main/ssh/host-server/ssh-host-server-on-connect.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.ts @@ -22,7 +22,7 @@ import { deferred, setupFailed } from './ssh-host-server-setup-outcome' import { classifyOrcadHostUnavailable, ORCAD_TUNNEL_UNAVAILABLE_REASON -} from '../../orcad/orcad-host-unavailable' +} from '../../orcad/diagnostics/orcad-host-unavailable' import { decidedEvent, reportHostServerConversion, diff --git a/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts b/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts index bb1f592b654..89d00a123ec 100644 --- a/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts +++ b/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts @@ -7,7 +7,7 @@ import type { import { orcadMigrationConflictGuidance } from '../../managed-server/migration/cutover/orcad-migration-conflict-guidance' import { boundedDetail, setupFailure, type SetupFailure } from './ssh-host-server-setup-failure' import { isSshSessionStartFailure } from '../connection/ssh-session-start-failure' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/diagnostics/orcad-host-unavailable' import { reportHostServerSetupError, type HostServerDecisionTrace diff --git a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts index 99ecc4a210c..9136c2eb5f6 100644 --- a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts +++ b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts @@ -1,6 +1,6 @@ /** Run real managed-orcad deployment against container/loopback host constraints in ssh-hostile-hosts.yml. */ import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' -import type { OrcadHostUnavailableReason } from '../../orcad/orcad-host-unavailable' +import type { OrcadHostUnavailableReason } from '../../orcad/diagnostics/orcad-host-unavailable' /** Every shimmed toolchain command appends its name here; a managed deploy must leave it empty. */ export const FORBIDDEN_TOOL_LOG = '/tmp/orca-forbidden-tool-calls.log' diff --git a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts index 7429b761518..dd605c5aa31 100644 --- a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts +++ b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts @@ -8,7 +8,7 @@ import { ORCAD_MANAGED_REMOTE_PORT } from '../../../shared/orcad-managed-runtime import { ORCAD_RUNTIMES_DIRNAME } from '../../../shared/orcad-artifacts' import type { SshTarget } from '../../../shared/ssh-types' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/diagnostics/orcad-host-unavailable' import { managedOrcadSlot } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { orcadSlotDir, diff --git a/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts index af50a39637a..b3ff4176a7f 100644 --- a/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts @@ -1,5 +1,4 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' import type { SshRemotePtyLease } from '../../../../shared/ssh-types' import type { LegacyRelayEndpoint, @@ -98,466 +97,6 @@ afterEach(() => { }) describe('one target’s legacy relay bridge', () => { - it('serves a leased pane its relay lists, forwarding output only once attached', async () => { - const subject = bridge() - await subject.refresh() - expect(subject.snapshot()).toEqual([ - { ptyId: PTY, targetId: TARGET, tabId: 'tab-1', leafId: 'leaf-1', state: 'live' } - ]) - relay.clients[0].emitData('pty-1', 'early') - await expect(subject.attach(PTY)).resolves.toMatchObject({ - status: 'attached', - replay: 'SCREEN' - }) - relay.clients[0].emitData('pty-1', 'late') - subject.write(PTY, 'ls\r') - expect(events.data).toEqual(['late']) - expect(relay.clients[0].writes).toEqual(['ls\r']) - }) - - it('names a live leased pane by its pane key, with what its relay claims about it', async () => { - const leafId = '33333333-3333-4333-8333-333333333333' - leases = [lease({ leafId })] - const subject = bridge({ - openClient: async () => { - const client = fakeClient(relay) - client.list = async () => [ - { relayPtyId: 'pty-1', incarnationId: 'inc-1', terminalHandle: 'term_a' } - ] - relay.clients.push(client) - return client - } - }) - await subject.refresh() - expect(subject.livePaneForKey(`tab-1:${leafId}`)).toEqual({ - ptyId: PTY, - incarnationId: 'inc-1', - terminalHandle: 'term_a' - }) - // A pane moved to another tab keeps the key its shell was started with. - expect(subject.livePaneForKey(`tab-2:${leafId}`)).toMatchObject({ ptyId: PTY }) - expect(subject.livePaneForKey('tab-1:44444444-4444-4444-8444-444444444444')).toBeNull() - expect(subject.livePaneForKey('tab-1:not-a-leaf')).toBeNull() - relay.clients[0].drop() - // Unverifiable is not live: a pane the relay cannot vouch for names nobody. - expect(subject.livePaneForKey(`tab-1:${leafId}`)).toBeNull() - }) - - it('retires the pane and hangs up when its relay reports the exit', async () => { - const subject = bridge() - await subject.refresh() - await subject.attach(PTY) - relay.clients[0].emitExit('pty-1', 0) - expect(events.exits).toEqual([PTY]) - expect(events.exitedTelemetry).toBe(1) - expect(leases[0].state).toBe('terminated') - expect(subject.snapshot()).toEqual([]) - expect(relay.clients[0].closed).toBe(true) - }) - - it('reads a dropped connection as unverifiable and reattaches once the relay answers', async () => { - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - expect(subject.snapshot()[0].state).toBe('unverifiable') - await vi.advanceTimersByTimeAsync(2_000) - expect(subject.snapshot()[0].state).toBe('unverifiable') - expect(leases[0].state).toBe('detached') - relay.openError = null - await vi.advanceTimersByTimeAsync(4_000) - expect(subject.snapshot()[0].state).toBe('live') - expect(events.exits).toEqual([]) - }) - - it('answers an attach for a leased pane it cannot reach as unverifiable, never exited', async () => { - listing = { kind: 'unverifiable' } - const subject = bridge() - await subject.refresh() - // Publish before relay replies so mounting tabs wait rather than spawn duplicate shells. - expect(subject.snapshot()).toEqual([ - { ptyId: PTY, targetId: TARGET, tabId: 'tab-1', leafId: 'leaf-1', state: 'unverifiable' } - ]) - const attached = subject.attach(PTY) - await vi.advanceTimersByTimeAsync(20_000) - await expect(attached).resolves.toEqual({ status: 'unverifiable' }) - expect(leases[0].state).toBe('detached') - }) - - it('serves a pane whose relay could not be asked at first once it answers', async () => { - relay.openError = new Error('owner claim timed out') - const subject = bridge() - await subject.refresh() - expect(subject.snapshot()[0].state).toBe('unverifiable') - relay.openError = null - await vi.advanceTimersByTimeAsync(2_000) - expect(subject.snapshot()[0].state).toBe('live') - await expect(subject.attach(PTY)).resolves.toMatchObject({ status: 'attached' }) - }) - - it('retires a lease only when every relay for the target answered without it', async () => { - relay.ptys.clear() - await bridge().refresh() - expect(leases[0].state).toBe('terminated') - expect(events.exitedTelemetry).toBe(0) - }) - - it('keeps a lease when a relay could not be asked', async () => { - relay.ptys.clear() - relay.openError = new Error('refused') - await bridge().refresh() - expect(leases[0].state).toBe('detached') - }) - - it('keeps a lease when a relay may run that no endpoint accounts for', async () => { - relay.ptys.clear() - listing = { kind: 'listed', endpoints: [ENDPOINT], exhaustive: false } - await bridge().refresh() - expect(leases[0].state).toBe('detached') - }) - - it('counts a relay whose socket is provably dead as holding nothing', async () => { - relay.openError = new Error('ECONNREFUSED') - endpointExited = true - await bridge().refresh() - expect(leases[0].state).toBe('terminated') - }) - - it('retires on a proven-exited attach refusal, and only re-lists an ambiguous one', async () => { - const subject = bridge() - await subject.refresh() - relay.attachError = new Error('PTY "pty-1" not found') - await expect(subject.attach(PTY)).resolves.toEqual({ status: 'unverifiable' }) - expect(leases[0].state).toBe('detached') - expect(subject.snapshot()[0].state).toBe('unverifiable') - // Re-listed on backoff, never in a tight loop. - await vi.advanceTimersByTimeAsync(2_000) - expect(subject.snapshot()[0].state).toBe('live') - relay.attachError = new Error('PTY "pty-1" not found (process exited)') - await expect(subject.attach(PTY)).resolves.toEqual({ status: 'exited' }) - expect(leases[0].state).toBe('terminated') - }) - - it('never serves a lease a stop is pending for, or one a newer pane won', async () => { - leases = [ - lease({ pendingKill: { requestedAt: 1, attempts: 1 } }), - lease({ ptyId: 'pty-2', supersededBy: 'pty-3' }), - lease({ ptyId: 'pty-4', tabId: undefined }) - ] - relay.ptys = new Set(['pty-1', 'pty-2', 'pty-4']) - const subject = bridge() - await subject.refresh() - expect(subject.snapshot()).toEqual([]) - expect(stops.owes(PTY)).toBe(false) - // An unfenced legacy id cannot prove this pending stop's process. - expect(relay.shutdowns).toEqual([]) - expect(leases[0].pendingKill).toBeUndefined() - }) - - it('stops a closed tab’s shell through the relay and retires it on the relay’s exit report', async () => { - const subject = bridge() - await subject.refresh() - await expect(stops.stop(PTY, subject)).resolves.toEqual({ status: 'requested' }) - expect(relay.shutdowns).toEqual(['pty-1']) - expect(events.exits).toEqual([PTY]) - expect(leases[0].state).toBe('terminated') - await vi.advanceTimersByTimeAsync(30_000) - expect(relay.shutdowns).toEqual(['pty-1']) - }) - - it('retires a stopped shell once a listing proves it gone, without an exit report', async () => { - relay.exitOnShutdown = false - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - await stops.stop(PTY, subject) - expect(leases[0].state).toBe('detached') - await vi.advanceTimersByTimeAsync(2_000) - expect(leases[0].state).toBe('terminated') - expect(stops.size).toBe(0) - }) - - it('holds a close for an unreachable relay as unverifiable and sends it once the relay answers', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await expect(stops.stop(PTY, subject)).resolves.toEqual({ status: 'unverifiable' }) - expect(relay.shutdowns).toEqual([]) - // Loss of contact is never exit. - expect(leases[0].state).toBe('detached') - expect(events.exits).toEqual([]) - relay.openError = null - await vi.advanceTimersByTimeAsync(2_000) - expect(relay.shutdowns).toEqual(['pty-1#inc-1']) - expect(leases[0].state).toBe('terminated') - }) - - it('keeps the identity a first close saw when the tab’s close repeats while unreachable', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await stops.stop(PTY, subject) - await vi.advanceTimersByTimeAsync(2_000) - await stops.stop(PTY, subject) - relay.openError = null - await vi.advanceTimersByTimeAsync(10_000) - expect(relay.shutdowns).toEqual(['pty-1#inc-1']) - }) - - it('never stops a different process that took a closed tab’s recycled relay id', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await stops.stop(PTY, subject) - relay.incarnations.set('pty-1', 'inc-2') - relay.openError = null - await vi.advanceTimersByTimeAsync(10_000) - expect(relay.shutdowns).toEqual([]) - expect(stops.size).toBe(0) - // Retire the closed lease so the stranger cannot be served under its tab. - expect(leases[0].state).toBe('terminated') - expect(subject.snapshot()).toEqual([]) - }) - - it('never re-aims a repeated close at a process that took the closed tab’s relay id', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await stops.stop(PTY, subject) - // A restarted relay reuses the id for another shell, and the close repeats before any flush. - const client = fakeClient(relay) - const recycled = { - paneState: () => 'live' as const, - paneReplaced: () => false, - liveRoute: () => ({ client, relayPtyId: 'pty-1' }), - listedIncarnation: () => 'inc-2', - refresh: async () => {} - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: stop() reads only these members. - await stops.stop(PTY, recycled as unknown as LegacyRelayTargetBridge) - expect(relay.shutdowns).toEqual([]) - expect(leases[0].state).toBe('terminated') - }) - - it('proves a stop only by the relay’s exit report, never by the stop’s reply', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - const subject = bridge() - await subject.refresh() - await expect(stops.stopAndWait(epochPty, subject, Date.now() + 5_000)).resolves.toBe('reported') - }) - - it('settles on the relay’s exit report even when the stop’s own reply is lost', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - const client = fakeClient(relay) - client.shutdown = async () => { - stops.exited(epochPty) - throw new Error('request timed out') - } - const lostReply = { - paneState: () => 'live' as const, - paneReplaced: () => false, - liveRoute: () => ({ client, relayPtyId: 'pty2:epoch:1' }), - listedIncarnation: () => undefined, - refresh: async () => {} - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: stop() reads only these members. - const target = lostReply as unknown as LegacyRelayTargetBridge - await expect(stops.stopAndWait(epochPty, target, Date.now() + 5_000)).resolves.toBe('reported') - }) - - it('still settles on an exit report that trails a failed stop reply', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - relay.shutdownError = new Error('request timed out') - const subject = bridge() - await subject.refresh() - const settled = stops.stopAndWait(epochPty, subject, Date.now() + 5_000) - await vi.advanceTimersByTimeAsync(100) - relay.clients[0].emitExit('pty2:epoch:1', 0) - await expect(settled).resolves.toBe('reported') - }) - - it('still sees an unfenced stop’s exit report that trails its reply, never re-serving the pane', async () => { - relay.exitOnShutdown = false - const subject = bridge() - await subject.refresh() - const settled = stops.stopAndWait(PTY, subject, Date.now() + 5_000) - await vi.advanceTimersByTimeAsync(0) - expect(relay.shutdowns).toEqual(['pty-1']) - expect(subject.snapshot()).toEqual([]) - relay.clients[0].emitExit('pty-1', 0) - await expect(settled).resolves.toBe('reported') - }) - - it('still sees an unfenced stop’s exit report after its reply timed out', async () => { - relay.shutdownError = new Error('request timed out') - const subject = bridge() - await subject.refresh() - const settled = stops.stopAndWait(PTY, subject, Date.now() + 5_000) - await vi.advanceTimersByTimeAsync(100) - expect(subject.snapshot()).toEqual([]) - relay.clients[0].emitExit('pty-1', 0) - await expect(settled).resolves.toBe('reported') - }) - - it('leaves a taken stop unproven while no exit report or complete listing confirms it', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - relay.exitOnShutdown = false - // A relay may run that no endpoint accounts for, so absence from the listing is not exit. - listing = { kind: 'listed', endpoints: [ENDPOINT], exhaustive: false } - const subject = bridge() - await subject.refresh() - const settled = stops.stopAndWait(epochPty, subject, Date.now() + 1_000) - await vi.advanceTimersByTimeAsync(1_000) - await expect(settled).resolves.toBeNull() - expect(relay.shutdowns).toEqual(['pty2:epoch:1']) - }) - - it('never attaches a pane whose tab closed while the attach waited for its relay', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - relay.openError = new Error('ssh down') - const subject = bridge() - await subject.refresh() - const attach = subject.attach(epochPty) - // The tab closes while the attach waits for the unreachable relay. - await stops.stop(epochPty, null) - relay.openError = null - relay.shutdownError = new Error('timed out') - await subject.refresh() - await expect(attach).resolves.toEqual({ status: 'not-bridged' }) - expect(relay.clients.every((client) => client.writes.length === 0)).toBe(true) - }) - - it('sends a close recorded while disconnected once the next bridge lists the pane', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - await expect(stops.stop(epochPty, null)).resolves.toEqual({ status: 'unverifiable' }) - expect(leases[0].state).toBe('detached') - await bridge().refresh() - expect(relay.shutdowns).toEqual(['pty2:epoch:1']) - }) - - it('sends a close recorded while disconnected after a restart before the reconnect', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - await stops.stop(epochPty, null) - // Restart: only the persisted leases survive. - stops = paneStops() - const subject = bridge() - await subject.refresh() - expect(relay.shutdowns).toEqual(['pty2:epoch:1']) - // A pending stop must never offer the shell for reattach. - expect(subject.snapshot()).toEqual([]) - expect(leases[0]).toMatchObject({ state: 'terminated' }) - expect(leases[0].pendingKill).toBeUndefined() - }) - - it('restores a fenced stop across a restart and sends it only to the same process', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await stops.stop(PTY, subject) - subject.dispose() - stops = paneStops() - relay.openError = null - await bridge().refresh() - expect(relay.shutdowns).toEqual(['pty-1#inc-1']) - }) - - it('drops a restored stop whose relay id now names another process, never serving it', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await stops.stop(PTY, subject) - subject.dispose() - stops = paneStops() - relay.incarnations.set('pty-1', 'inc-2') - relay.openError = null - const next = bridge() - await next.refresh() - await vi.advanceTimersByTimeAsync(10_000) - expect(relay.shutdowns).toEqual([]) - expect(leases[0]).toMatchObject({ state: 'terminated' }) - expect(leases[0].pendingKill).toBeUndefined() - expect(next.snapshot()).toEqual([]) - }) - - it('stops serving an unfenced legacy pane once its one stop failed', async () => { - const subject = bridge() - await subject.refresh() - relay.shutdownError = new Error('timed out') - await stops.stop(PTY, subject) - await vi.advanceTimersByTimeAsync(0) - expect(subject.snapshot()).toEqual([]) - expect(subject.livePaneCount()).toBe(0) - }) - - it('never serves an unfenced legacy pane again after its tab closed and Orca restarted', async () => { - await expect(stops.stop(PTY, null)).resolves.toEqual({ status: 'unverifiable' }) - stops = paneStops() - const subject = bridge() - await subject.refresh() - expect(subject.snapshot()).toEqual([]) - expect(relay.shutdowns).toEqual([]) - }) - - it('never replays a blind close for a legacy id that could name another shell', async () => { - await stops.stop(PTY, null) - await bridge().refresh() - expect(relay.shutdowns).toEqual([]) - expect(leases[0].state).toBe('terminated') - }) - - it('never replays a fenced legacy stop to a relay that no longer reports the incarnation', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.openError = new Error('ssh down') - relay.clients[0].drop() - await stops.stop(PTY, subject) - // A restarted or downgraded relay lists the same id with no identity, and may ignore the fence. - relay.incarnations.clear() - relay.openError = null - await vi.advanceTimersByTimeAsync(10_000) - expect(relay.shutdowns).toEqual([]) - }) - - it('never replays an unfenced legacy stop on a later connection, which may be a new relay', async () => { - const subject = bridge() - await subject.refresh() - relay.shutdownError = new Error('timed out') - await expect(stops.stop(PTY, subject)).resolves.toEqual({ status: 'unverifiable' }) - relay.shutdownError = null - relay.clients[0].drop() - await vi.advanceTimersByTimeAsync(10_000) - expect(relay.shutdowns).toEqual([]) - // Unfenced stops get one attempt; retired leases must never target a later relay. - expect(leases[0].state).toBe('terminated') - expect(subject.snapshot()).toEqual([]) - }) - it('never republishes a pane that exited while a refresh was asking its relay', async () => { const subject = bridge() await subject.refresh() @@ -600,8 +139,6 @@ describe('one target’s legacy relay bridge', () => { describe('two relays that list the same relay id', () => { const OTHER: LegacyRelayEndpoint = { ...ENDPOINT, endpoint: '/home/me/.orca-remote/b.sock' } let other: FakeRelay - const clientOf = (endpoint: LegacyRelayEndpoint) => - (endpoint.endpoint === OTHER.endpoint ? other : relay).clients.at(-1)! const twoRelays = (): LegacyRelayTargetBridge => bridge({ openClient: async (endpoint) => { @@ -619,35 +156,6 @@ describe('one target’s legacy relay bridge', () => { other = { ...relay, ptys: new Set(), clients: [], shutdowns: [], incarnations: new Map() } }) - it('keeps the attached relay when a second one later lists the same id', async () => { - const subject = twoRelays() - await subject.refresh() - await expect(subject.attach(PTY)).resolves.toMatchObject({ status: 'attached' }) - other.ptys.add('pty-1') - listing = { kind: 'listed', endpoints: [ENDPOINT, OTHER], exhaustive: true } - await subject.refresh() - subject.write(PTY, 'ls\r') - expect(clientOf(ENDPOINT).writes).toEqual(['ls\r']) - expect(clientOf(OTHER).writes).toEqual([]) - // Only the owning relay speaks for the pane. - clientOf(OTHER).emitData('pty-1', 'foreign') - clientOf(OTHER).emitExit('pty-1', 0) - expect(events.data).toEqual([]) - expect(events.exits).toEqual([]) - expect(leases[0].state).toBe('detached') - }) - - it('retires the pane when its own relay answers without it, never moving it to the other', async () => { - const subject = twoRelays() - await subject.refresh() - relay.ptys.delete('pty-1') - other.ptys.add('pty-1') - listing = { kind: 'listed', endpoints: [ENDPOINT, OTHER], exhaustive: true } - await subject.refresh() - expect(leases[0].state).toBe('terminated') - expect(subject.snapshot()).toEqual([]) - }) - it('serves neither relay when both list the id and neither held it', async () => { other.ptys.add('pty-1') listing = { kind: 'listed', endpoints: [ENDPOINT, OTHER], exhaustive: true } @@ -665,89 +173,5 @@ describe('one target’s legacy relay bridge', () => { await vi.advanceTimersByTimeAsync(60_000) expect(leases[0].state).toBe('terminated') }) - - it('never adopts the one relay listing an id while another could not be asked', async () => { - other.ptys.add('pty-1') - relay.openError = new Error('ssh down') - listing = { kind: 'listed', endpoints: [ENDPOINT, OTHER], exhaustive: true } - const subject = twoRelays() - await subject.refresh() - expect(subject.snapshot()).toEqual([expect.objectContaining({ state: 'unverifiable' })]) - // The unreachable relay answers and both list the id: still nobody's. - relay.openError = null - await vi.advanceTimersByTimeAsync(10_000) - expect(subject.snapshot()).toEqual([expect.objectContaining({ state: 'unverifiable' })]) - expect(other.clients.flatMap((client) => client.writes)).toEqual([]) - }) - - it('never adopts the one relay listing an id while the census may have missed another', async () => { - listing = { kind: 'listed', endpoints: [ENDPOINT], exhaustive: false } - const subject = twoRelays() - await subject.refresh() - expect(subject.snapshot()).toEqual([expect.objectContaining({ state: 'unverifiable' })]) - // The census later accounts for every relay, and the missed one runs the same id. - other.ptys.add('pty-1') - listing = { kind: 'listed', endpoints: [ENDPOINT, OTHER], exhaustive: true } - await vi.advanceTimersByTimeAsync(10_000) - expect(subject.snapshot()).toEqual([expect.objectContaining({ state: 'unverifiable' })]) - subject.write(PTY, 'ls\r') - expect(relay.clients.flatMap((client) => client.writes)).toEqual([]) - }) - - it('serves an epoch-scoped id from its one relay even while the census may have missed one', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - relay.ptys = new Set(['pty2:epoch:1']) - listing = { kind: 'listed', endpoints: [ENDPOINT], exhaustive: false } - const subject = twoRelays() - await subject.refresh() - expect(subject.snapshot()).toEqual([ - expect.objectContaining({ ptyId: epochPty, state: 'live' }) - ]) - }) - - it('keeps the owning relay across a reconnect, when both relays list the id', async () => { - const first = twoRelays() - await first.refresh() - first.dispose() - other.ptys.add('pty-1') - listing = { kind: 'listed', endpoints: [ENDPOINT, OTHER], exhaustive: true } - const successor = twoRelays() - await successor.refresh() - await expect(successor.attach(PTY)).resolves.toMatchObject({ status: 'attached' }) - successor.write(PTY, 'ls\r') - expect(clientOf(ENDPOINT).writes).toEqual(['ls\r']) - expect(clientOf(OTHER).writes).toEqual([]) - }) - - it('keeps an exit the relay reported while its listing was in flight', async () => { - const subject = bridge({ - openClient: async () => { - const client = fakeClient(relay) - const list = client.list.bind(client) - client.list = async () => { - const rows = await list() - // The shell exits after the relay answered but before the pane has an owner. - client.emitExit('pty-1', 3) - return rows - } - relay.clients.push(client) - return client - } - }) - await subject.refresh() - expect(events.exits).toEqual([PTY]) - expect(leases[0].state).toBe('terminated') - expect(subject.snapshot()).toEqual([]) - }) - }) - - it('hangs up every connection on dispose and leaves the relays to their own grace', async () => { - const subject = bridge() - await subject.refresh() - subject.dispose() - expect(relay.clients.every((client) => client.closed)).toBe(true) - expect(leases[0].state).toBe('detached') - expect(subject.snapshot()).toEqual([]) }) }) diff --git a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts index 36579cbd252..2e05b2dc430 100644 --- a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts @@ -11,7 +11,7 @@ import { hashCanonical, readPromptBasePayloadHash, replayStableCallerParams -} from '../../../runtime/rpc/orchestration-mutation-receipt' +} from '../../../runtime/rpc/orchestration/mutations/orchestration-mutation-receipt' import { getCompiledSchema } from '../../../schema-validation/zod-schema-compilation' import type { LegacyRelayCliCall } from './legacy-relay-cli-caller' diff --git a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts index c45e9bcd49d..2aa2245c4ea 100644 --- a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts @@ -28,7 +28,7 @@ import { stringFlag } from './legacy-relay-cli-args' import type { LegacyRelayCliServer } from '../bridge/legacy-relay-client' -import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../../shared/rpc-contract/connector-params' +import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../../shared/rpc-contract/connectors/connector-params' import { cappedInboxLimit, cappedWait, diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts index 3e29de8f0ac..89305c729be 100644 --- a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts @@ -12,7 +12,7 @@ import { isUnconfirmedSshCommandTermination } from '../../remote-exec/remote-exec-command' import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' -import { filesystemTypeIsLocalDisk } from '../../../orcad/orcad-data-root-locality' +import { filesystemTypeIsLocalDisk } from '../../../orcad/instance-lock/orcad-data-root-locality' type RelayEndpointVerdict = 'live' | 'unverifiable' | 'exited' diff --git a/src/main/ssh/migration-source/orcad-migration-bridged-panes.ts b/src/main/ssh/migration-source/orcad-migration-bridged-panes.ts index 812a35bbf29..f7cba30c64e 100644 --- a/src/main/ssh/migration-source/orcad-migration-bridged-panes.ts +++ b/src/main/ssh/migration-source/orcad-migration-bridged-panes.ts @@ -1,6 +1,6 @@ import type { OrcadMigrationCatalogPayload } from '../../../shared/orcad-migration/orcad-migration-manifest' import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' +import { collectLeafIds } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { normalizeWorkspaceSessionKeyToWorkspaceId } from '../../../shared/workspace-scope' export type OrcadMigrationPaneLeasePredicate = (lease: SshRemotePtyLease) => boolean diff --git a/src/main/ssh/remote-exec/ssh-remote-powershell.ts b/src/main/ssh/remote-exec/ssh-remote-powershell.ts index 59c5e0d7cb9..a1bf3a278f6 100644 --- a/src/main/ssh/remote-exec/ssh-remote-powershell.ts +++ b/src/main/ssh/remote-exec/ssh-remote-powershell.ts @@ -1,6 +1,6 @@ import { gunzipSync, gzipSync } from 'node:zlib' import { encodePowerShellCommand } from '../../../shared/powershell-command-encoding' -import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../../providers/windows-shell-args' +import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../../providers/shell-launch/windows/shell-args' // Stock sshd reparses exec through cmd.exe; budget below its 8,191-character ceiling for the added /c wrapper. const WINDOWS_REMOTE_COMMAND_LINE_BUDGET_CHARS = 8_000 diff --git a/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts b/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts deleted file mode 100644 index d72e4dbc362..00000000000 --- a/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { gunzipSync } from 'node:zlib' -import { describe, expect, it } from 'vitest' -import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../../providers/windows-shell-args' -import { decodeRemotePowerShellScript, powerShellCommand } from './ssh-remote-powershell' - -// Stock sshd's cmd.exe DefaultShell rejects oversized exec lines with localized diagnostics. -describe('Windows remote command line limit', () => { - it('carries an oversized script through gzip without altering it', () => { - const script = Array.from( - { length: 200 }, - (_unused, index) => `Write-Output ${index}; $slot = 'C:\\Users\\orca\\stage-${index}'` - ).join('\n') - const command = powerShellCommand(script) - expect(command.length).toBeLessThanOrEqual(CMD_EXE_COMMAND_LINE_MAX_CHARS) - expect(decodeRemotePowerShellScript(command)).toBe(script) - const bootstrap = Buffer.from( - command.match(/-EncodedCommand\s+([A-Za-z0-9+/=]+)$/u)?.[1] ?? '', - 'base64' - ).toString('utf16le') - const payload = bootstrap.match(/FromBase64String\('([A-Za-z0-9+/=]+)'\)/u)?.[1] ?? '' - expect(gunzipSync(Buffer.from(payload, 'base64')).toString('utf-8')).toBe(script) - expect(bootstrap).toContain('Invoke-Expression $OrcaScriptText') - }) -}) diff --git a/src/main/star-nag/agent-value-moment.ts b/src/main/star-nag/agent-value-moment.ts index 52c4909a45a..5171860b9dc 100644 --- a/src/main/star-nag/agent-value-moment.ts +++ b/src/main/star-nag/agent-value-moment.ts @@ -1,5 +1,5 @@ import { app } from 'electron' -import { checkOrcaStarred } from '../github/client' +import { checkOrcaStarred } from '../github/client/fetch/orca-star' import type { Store } from '../persistence/loading-store/store' import type { StarNagPromptMode } from '../../shared/star-nag-telemetry' diff --git a/src/main/star-nag/direct-star-attempt.ts b/src/main/star-nag/direct-star-attempt.ts index 18a22aad6f5..802b43c6b6a 100644 --- a/src/main/star-nag/direct-star-attempt.ts +++ b/src/main/star-nag/direct-star-attempt.ts @@ -1,4 +1,4 @@ -import { starOrca } from '../github/client' +import { starOrca } from '../github/client/fetch/orca-star' import { track } from '../telemetry/client' import { getCohortAtEmit } from '../telemetry/cohort-classifier' import { type StarNagPromptSession, trackStarNagSessionOutcome } from './prompt-session-telemetry' diff --git a/src/main/star-nag/service-direct-star.test.ts b/src/main/star-nag/service-direct-star.test.ts index e694b26557d..fcec053d665 100644 --- a/src/main/star-nag/service-direct-star.test.ts +++ b/src/main/star-nag/service-direct-star.test.ts @@ -30,7 +30,7 @@ vi.mock('electron', () => ({ } })) -vi.mock('../github/client', () => ({ +vi.mock('../github/client/fetch/orca-star', () => ({ checkOrcaStarred: mocks.checkOrcaStarredMock, starOrca: mocks.starOrcaMock })) @@ -84,30 +84,6 @@ describe('StarNagService', () => { expect(ui.starNagCompleted).toBe(true) }) - it('records failed direct star after dismissal without clearing the cooldown or re-showing', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const deferredStar = createDeferred() - starOrcaMock.mockReturnValue(deferredStar.promise) - const { service, ui } = createHarness() - - service.registerIpcHandlers() - getIpcHandler('star-nag:forceShow')() - const starPromise = getIpcHandler('star-nag:starOrca')() - getIpcHandler('star-nag:dismiss')() - - deferredStar.resolve(false) - await expect(starPromise).resolves.toBe(false) - - expect(trackMock).toHaveBeenCalledWith( - 'star_nag_outcome', - expect.objectContaining({ outcome: 'direct_star_failed', mode: 'gh' }) - ) - expect(ui.starNagCompleted).toBeUndefined() - expect(ui.starNagDeferredUntil).toBeGreaterThan(Date.now()) - expect(window.webContents.send).toHaveBeenCalledTimes(1) - }) - it('clears the in-flight direct-star guard after thrown attempts so the user can retry', async () => { const window = createWindow() browserWindowMock.getAllWindows.mockReturnValue([window]) @@ -124,41 +100,4 @@ describe('StarNagService', () => { expect(starOrcaMock).toHaveBeenCalledTimes(2) expect(ui.starNagCompleted).toBe(true) }) - - it('records failed direct star before web fallback and guards duplicate in-flight attempts', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const deferredStar = createDeferred() - starOrcaMock.mockReturnValue(deferredStar.promise) - const { service, ui } = createHarness() - - service.registerIpcHandlers() - getIpcHandler('star-nag:forceShow')() - const starFromNag = getIpcHandler('star-nag:starOrca') - const first = starFromNag() - const second = starFromNag() - - deferredStar.resolve(false) - await expect(first).resolves.toBe(false) - await expect(second).resolves.toBe(false) - - const starAttempts = trackMock.mock.calls.filter( - ([name, payload]) => - name === 'star_nag_outcome' && (payload as { outcome?: string }).outcome === 'star_clicked' - ) - expect(starAttempts).toHaveLength(1) - expect(trackMock).toHaveBeenCalledWith( - 'star_nag_outcome', - expect.objectContaining({ outcome: 'direct_star_failed', mode: 'gh' }) - ) - - getIpcHandler('star-nag:openWeb')() - - expect(trackMock).toHaveBeenCalledWith( - 'star_nag_outcome', - expect.objectContaining({ outcome: 'opened_repo', mode: 'web' }) - ) - expect(ui.starNagCompleted).toBeUndefined() - expect(ui.starNagDeferredUntil).toBeGreaterThan(Date.now()) - }) }) diff --git a/src/main/star-nag/service-force-show-races.test.ts b/src/main/star-nag/service-force-show-races.test.ts index cae9f744075..06891c5170d 100644 --- a/src/main/star-nag/service-force-show-races.test.ts +++ b/src/main/star-nag/service-force-show-races.test.ts @@ -32,7 +32,7 @@ vi.mock('electron', () => ({ } })) -vi.mock('../github/client', () => ({ +vi.mock('../github/client/fetch/orca-star', () => ({ checkOrcaStarred: mocks.checkOrcaStarredMock, starOrca: mocks.starOrcaMock })) diff --git a/src/main/star-nag/service-threshold-prompt.test.ts b/src/main/star-nag/service-threshold-prompt.test.ts deleted file mode 100644 index e9e2bec9b8c..00000000000 --- a/src/main/star-nag/service-threshold-prompt.test.ts +++ /dev/null @@ -1,262 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { STAR_NAG_INITIAL_THRESHOLD } from '../../shared/constants' -import { - createHarness, - createIpcHandlerLookup, - createWindow, - flushAsyncWork, - resetStarNagMocks, - type TestWindow -} from './service-test-harness' - -const mocks = vi.hoisted(() => ({ - appMock: { - getVersion: vi.fn(() => '1.2.3') - }, - browserWindowMock: { - getAllWindows: vi.fn<() => TestWindow[]>(() => []) - }, - checkOrcaStarredMock: vi.fn(), - starOrcaMock: vi.fn(), - trackMock: vi.fn(), - getCohortAtEmitMock: vi.fn(() => ({ nth_repo_added: 3 })), - ipcMainHandleMock: vi.fn() -})) - -vi.mock('electron', () => ({ - app: mocks.appMock, - BrowserWindow: mocks.browserWindowMock, - ipcMain: { - handle: mocks.ipcMainHandleMock - } -})) - -vi.mock('../github/client', () => ({ - checkOrcaStarred: mocks.checkOrcaStarredMock, - starOrca: mocks.starOrcaMock -})) - -vi.mock('../telemetry/client', () => ({ - track: mocks.trackMock -})) - -vi.mock('../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: mocks.getCohortAtEmitMock -})) - -const { browserWindowMock, checkOrcaStarredMock, trackMock } = mocks -const getIpcHandler = createIpcHandlerLookup(mocks.ipcMainHandleMock) - -describe('StarNagService', () => { - let consoleInfoMock: ReturnType - - beforeEach(() => { - resetStarNagMocks(mocks) - consoleInfoMock = vi.spyOn(console, 'info').mockImplementation(() => undefined) - }) - - afterEach(() => { - consoleInfoMock.mockRestore() - }) - - it('preserves the counter and dismissal backoff after an app update', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, emitAgentStarted, store, ui } = createHarness({ - starNagAppVersion: '1.2.2', - starNagBaselineAgents: 10, - starNagNextThreshold: 70, - starNagDeferredUntil: 1 - }) - - service.start() - expect(store.updateUI).not.toHaveBeenCalled() - expect(ui.starNagDeferredUntil).toBe(1) - emitAgentStarted(79) - await flushAsyncWork() - expect(window.webContents.send).not.toHaveBeenCalled() - - emitAgentStarted(80) - await flushAsyncWork() - expect(window.webContents.send).toHaveBeenCalledTimes(1) - expect(trackMock).toHaveBeenCalledWith( - 'star_nag_outcome', - expect.objectContaining({ outcome: 'shown', threshold: 70, agents_since_baseline: 70 }) - ) - }) - - it.each([undefined, null])('initializes a missing baseline (%s) only once', async (baseline) => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, emitAgentStarted, ui } = createHarness({ - starNagAppVersion: undefined, - starNagBaselineAgents: baseline, - starNagNextThreshold: undefined - }) - - service.start() - expect(ui.starNagBaselineAgents).toBe(45) - expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD) - service.stop() - mocks.appMock.getVersion.mockReturnValue('1.2.4') - service.start() - emitAgentStarted(79) - await flushAsyncWork() - expect(window.webContents.send).not.toHaveBeenCalled() - emitAgentStarted(80) - await flushAsyncWork() - expect(window.webContents.send).toHaveBeenCalledTimes(1) - }) - - it('logs a threshold exposure exactly once while the card remains visible', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, emitAgentStarted } = createHarness() - - service.start() - emitAgentStarted(45) - await flushAsyncWork() - emitAgentStarted(46) - - expect(window.webContents.send).toHaveBeenCalledTimes(1) - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'gh', - surface: 'card' - }) - expect(consoleInfoMock).toHaveBeenCalledTimes(1) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold' - }) - }) - - it('shows the browser fallback when checkOrcaStarred cannot determine star state', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - checkOrcaStarredMock.mockResolvedValue(null) - const { service, emitAgentStarted } = createHarness() - - service.start() - emitAgentStarted(45) - await flushAsyncWork() - - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'web', - surface: 'card' - }) - expect(trackMock).toHaveBeenCalledWith('star_nag_outcome', { - outcome: 'shown', - source: 'threshold', - mode: 'web', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - agents_since_baseline_bucket: '35-69', - nth_repo_added: 3 - }) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold' - }) - }) - - it('does not log a threshold exposure when checkOrcaStarred returns true', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - checkOrcaStarredMock.mockResolvedValue(true) - const { service, emitAgentStarted } = createHarness() - - service.start() - emitAgentStarted(45) - await flushAsyncWork() - - expect(window.webContents.send).not.toHaveBeenCalled() - expect(consoleInfoMock).not.toHaveBeenCalled() - }) - - it('does not block a later real prompt after crossing the threshold with no window', async () => { - const { service, emitAgentStarted } = createHarness() - - service.start() - emitAgentStarted(45) - await flushAsyncWork() - - expect(consoleInfoMock).not.toHaveBeenCalled() - expect(trackMock).not.toHaveBeenCalled() - - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - emitAgentStarted(46) - await flushAsyncWork() - - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'gh', - surface: 'card' - }) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 36, - source: 'threshold' - }) - }) - - it('logs dismissal with doubled next_threshold and advances backoff for the active session', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, emitAgentStarted, ui } = createHarness() - - service.start() - service.registerIpcHandlers() - emitAgentStarted(45) - await flushAsyncWork() - getIpcHandler('star-nag:dismiss')() - - expect(consoleInfoMock).toHaveBeenLastCalledWith({ - event: 'star_nag_dismissed', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold', - next_threshold: STAR_NAG_INITIAL_THRESHOLD * 2 - }) - expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD * 2) - expect(ui.starNagBaselineAgents).toBe(45) - expect(ui.starNagDeferredUntil).toBeGreaterThan(Date.now()) - }) - - it('preserves an active cooldown and backoff after an app update', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, emitAgentStarted, store, ui } = createHarness({ - starNagAppVersion: '1.2.2', - starNagNextThreshold: 70, - starNagDeferredUntil: Date.now() + 3 * 24 * 60 * 60 * 1000 - }) - - service.start() - emitAgentStarted(80) - await flushAsyncWork() - - expect(checkOrcaStarredMock).not.toHaveBeenCalled() - expect(window.webContents.send).not.toHaveBeenCalled() - expect(trackMock).not.toHaveBeenCalled() - expect(store.updateUI).not.toHaveBeenCalled() - - ui.starNagDeferredUntil = Date.now() - 1 - emitAgentStarted(81) - await flushAsyncWork() - - expect(window.webContents.send).toHaveBeenCalledTimes(1) - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'gh', - surface: 'card' - }) - }) -}) diff --git a/src/main/star-nag/service.ts b/src/main/star-nag/service.ts index 253e18e828c..ab076140f36 100644 --- a/src/main/star-nag/service.ts +++ b/src/main/star-nag/service.ts @@ -1,6 +1,6 @@ import { BrowserWindow, ipcMain } from 'electron' import { STAR_NAG_INITIAL_THRESHOLD } from '../../shared/constants' -import { checkOrcaStarred } from '../github/client' +import { checkOrcaStarred } from '../github/client/fetch/orca-star' import type { Store } from '../persistence/loading-store/store' import type { StatsCollector } from '../stats/collector' import { track } from '../telemetry/client' diff --git a/src/main/startup/agent-launch-record-warmup.ts b/src/main/startup/agent-accounts/agent-launch-record-warmup.ts similarity index 92% rename from src/main/startup/agent-launch-record-warmup.ts rename to src/main/startup/agent-accounts/agent-launch-record-warmup.ts index 1936ea9e070..bd9814d6b4c 100644 --- a/src/main/startup/agent-launch-record-warmup.ts +++ b/src/main/startup/agent-accounts/agent-launch-record-warmup.ts @@ -1,5 +1,5 @@ import type { BrowserWindow } from 'electron' -import { mainProcessState as state } from './main-process-state' +import { mainProcessState as state } from '../main-process-state' // Defer synchronous disk work (95-280ms measured under load) past first-load renderer startup. export const AGENT_LAUNCH_RECORD_WARMUP_DELAY_MS = 1_500 diff --git a/src/main/startup/codex-account-restart-resume.test.ts b/src/main/startup/agent-accounts/codex-account-restart-resume.test.ts similarity index 92% rename from src/main/startup/codex-account-restart-resume.test.ts rename to src/main/startup/agent-accounts/codex-account-restart-resume.test.ts index 0f682389007..c665233f8d7 100644 --- a/src/main/startup/codex-account-restart-resume.test.ts +++ b/src/main/startup/agent-accounts/codex-account-restart-resume.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' const homes = vi.hoisted(() => ({ original: '', selected: '', system: '' })) vi.mock('electron', () => ({ app: { getPath: () => homes.system } })) -vi.mock('./main-process-state', () => ({ +vi.mock('../main-process-state', () => ({ mainProcessState: { codexRuntimeHome: { isHostSystemDefaultRealHomeSelected: () => false, @@ -15,21 +15,21 @@ vi.mock('./main-process-state', () => ({ store: { getSettings: () => ({}) } } })) -vi.mock('../codex/hooks/installation/hook-service', () => ({ +vi.mock('../../codex/hooks/installation/hook-service', () => ({ codexHookService: { installForLaunchPrep: vi.fn(), refreshRuntimeUserHooksForLaunchPrep: vi.fn() } })) -vi.mock('../codex/hooks/reconciliation/codex-hook-reconcile', () => ({ +vi.mock('../../codex/hooks/reconciliation/codex-hook-reconcile', () => ({ reconcileCodexHooksForLaunch: vi.fn() })) -vi.mock('../codex/configuration/homes/codex-home-paths', () => ({ +vi.mock('../../codex/configuration/homes/codex-home-paths', () => ({ getCodexSessionBackfillStateDirPath: () => join(homes.system, 'backfill'), getSystemCodexHomePath: () => homes.system, getOrcaManagedCodexHomePath: () => join(homes.system, 'legacy') })) -vi.mock('../codex/configuration/settings/codex-config-mirror', () => ({ +vi.mock('../../codex/configuration/settings/codex-config-mirror', () => ({ ensureCodexDaemonSocketGuard: vi.fn() })) diff --git a/src/main/startup/codex-launch-preparation.ts b/src/main/startup/agent-accounts/codex-launch-preparation.ts similarity index 82% rename from src/main/startup/codex-launch-preparation.ts rename to src/main/startup/agent-accounts/codex-launch-preparation.ts index b3c34371d83..61481b0896e 100644 --- a/src/main/startup/codex-launch-preparation.ts +++ b/src/main/startup/agent-accounts/codex-launch-preparation.ts @@ -1,5 +1,5 @@ -import { createCodexRuntimeHomeLaunchPreparation } from '../codex/configuration/homes/codex-runtime-home-launch-preparation' -import { mainProcessState as state } from './main-process-state' +import { createCodexRuntimeHomeLaunchPreparation } from '../../codex/configuration/homes/codex-runtime-home-launch-preparation' +import { mainProcessState as state } from '../main-process-state' export const prepareCodexRuntimeHomeForLaunch = createCodexRuntimeHomeLaunchPreparation({ getRuntimeHome: () => state.codexRuntimeHome, diff --git a/src/main/startup/codex-session-resume-daemon-guard.test.ts b/src/main/startup/agent-accounts/codex-session-resume-daemon-guard.test.ts similarity index 86% rename from src/main/startup/codex-session-resume-daemon-guard.test.ts rename to src/main/startup/agent-accounts/codex-session-resume-daemon-guard.test.ts index cddbb67aa12..71c56522328 100644 --- a/src/main/startup/codex-session-resume-daemon-guard.test.ts +++ b/src/main/startup/agent-accounts/codex-session-resume-daemon-guard.test.ts @@ -2,11 +2,11 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { VerifiedCodexResumeSource } from '../codex/history/resume/codex-session-resume-preparation' +import type { VerifiedCodexResumeSource } from '../../codex/history/resume/codex-session-resume-preparation' import { CODEX_DAEMON_OVERRIDE_MARKER, codexDaemonSocketPathExceedsLimit -} from '../codex/configuration/shared-server/codex-daemon-socket-path-guard' +} from '../../codex/configuration/shared-server/codex-daemon-socket-path-guard' const mocks = vi.hoisted(() => ({ hooksEnabled: false, @@ -20,30 +20,30 @@ const mocks = vi.hoisted(() => ({ })) vi.mock('electron', () => ({ app: { getPath: vi.fn(() => '/tmp/orca-user-data') } })) -vi.mock('../codex/hooks/installation/hook-service', () => ({ +vi.mock('../../codex/hooks/installation/hook-service', () => ({ codexHookService: { installForLaunchPrep: mocks.installForLaunchPrep, refreshRuntimeUserHooksForLaunchPrep: mocks.refreshRuntimeUserHooksForLaunchPrep } })) -vi.mock('../codex/hooks/reconciliation/codex-hook-reconcile', () => ({ +vi.mock('../../codex/hooks/reconciliation/codex-hook-reconcile', () => ({ reconcileCodexHooksForLaunch: mocks.reconcileCodexHooksForLaunch })) -vi.mock('../../shared/agent-hook-listener/configuration/agent-status-hooks-setting', () => ({ +vi.mock('../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting', () => ({ isAgentStatusHooksEnabledForAgent: () => mocks.hooksEnabled })) -vi.mock('../codex/configuration/homes/codex-home-paths', async (importOriginal) => ({ +vi.mock('../../codex/configuration/homes/codex-home-paths', async (importOriginal) => ({ ...(await importOriginal()), getSystemCodexHomePath: () => mocks.systemHomePath, getOrcaManagedCodexHomePath: () => mocks.sharedHomePath })) -vi.mock('../codex/history/resume/codex-session-resume-preparation', () => ({ +vi.mock('../../codex/history/resume/codex-session-resume-preparation', () => ({ prepareCodexSessionResume: mocks.prepareCodexSessionResume })) -vi.mock('../codex/history/resume/codex-legacy-session-resume', () => ({ +vi.mock('../../codex/history/resume/codex-legacy-session-resume', () => ({ prepareLegacySharedCodexSessionResume: mocks.prepareLegacySharedCodexSessionResume })) -vi.mock('./main-process-state', () => ({ +vi.mock('../main-process-state', () => ({ mainProcessState: { codexRuntimeHome: { isHostSystemDefaultRealHomeSelected: () => false, diff --git a/src/main/startup/agent-accounts/codex-session-resume-launch.ts b/src/main/startup/agent-accounts/codex-session-resume-launch.ts new file mode 100644 index 00000000000..879a8ab4e89 --- /dev/null +++ b/src/main/startup/agent-accounts/codex-session-resume-launch.ts @@ -0,0 +1,10 @@ +import { createCodexSessionResumeLaunchPreparation } from '../../codex/history/resume/codex-session-resume-launch-preparation' +import { mainProcessState as state } from '../main-process-state' + +const desktopResumeLaunch = createCodexSessionResumeLaunchPreparation({ + getRuntimeHome: () => state.codexRuntimeHome, + getSettings: () => state.store?.getSettings() +}) + +export const { prepareCodexSessionResumeForLaunch, prepareCodexPinnedLaunchHome } = + desktopResumeLaunch diff --git a/src/main/startup/agent-accounts/main-process-account-services.ts b/src/main/startup/agent-accounts/main-process-account-services.ts new file mode 100644 index 00000000000..7cd4b959165 --- /dev/null +++ b/src/main/startup/agent-accounts/main-process-account-services.ts @@ -0,0 +1,82 @@ +import { app } from 'electron' +import { KeybindingService } from '../../keybindings/keybinding-service' +import { createProviderAccountServices } from '../../providers/accounts/provider-account-services' +import { createCodexSessionMigrationScheduler } from '../../codex/history/backfill/codex-session-migration-scheduler' +import { startCodexSessionBackfillInBackground } from '../../codex/history/backfill/codex-session-backfill' +import { startCodexSessionIndexHealInBackground } from '../../codex/history/index/codex-session-index-heal' +import { startCodexStateDbBackfillRecoveryInBackground } from '../../codex/history/index/codex-state-db-backfill-recovery' +import { getOrcaManagedCodexHomePath } from '../../codex/configuration/homes/codex-home-paths' +import { + hasOpenCodeGoApiKey, + readOpenCodeGoApiKey, + saveOpenCodeGoApiKey +} from '../../opencode/accounts/opencode-go-api-key-store' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { resolveHostCodexSessionSourceHome } from '../../codex/history/rollouts/codex-session-source-home' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' +import { prewarmStructuredAgentModelCatalogs } from '../../runtime/agent-session/model-catalog/structured-agent-model-catalog-wiring' +import { mainProcessState as state } from '../main-process-state' + +// Settings that change which account or binary a new chat's agent runs under. +const MODEL_CATALOG_ACCOUNT_SETTINGS = [ + 'activeCodexManagedAccountId', + 'activeCodexManagedAccountIdsByRuntime', + 'codexManagedAccounts', + 'activeClaudeManagedAccountId', + 'activeClaudeManagedAccountIdsByRuntime', + 'claudeManagedAccounts', + 'agentDefaultEnv', + 'agentCmdOverrides' +] as const + +export function initializeMainProcessAccountServices(): void { + const store = state.store + if (!store || !state.claudeUsage || !state.codexUsage) { + throw new Error('Usage stores must be initialized before account services') + } + state.codexSessionMigration = createCodexSessionMigrationScheduler({ + isEligible: () => + state.codexRuntimeHome?.isHostSystemDefaultSessionMigrationEligible() === true, + isQuitting: () => state.isQuitting, + resolveSystemCodexHomePathOverride: () => + resolveHostCodexSessionSourceHome(store.getSettings()), + prepareScheduledRun: (scanDates) => + state.codexRuntimeHome?.prepareHostSystemDefaultSessionMigrationPass(scanDates), + finishScheduledRun: () => state.codexRuntimeHome?.finishHostSystemDefaultSessionMigrationPass(), + startBackfill: startCodexSessionBackfillInBackground, + startIndexHeal: startCodexSessionIndexHealInBackground + }) + const services = createProviderAccountServices(store, { + codexAccountLifecycle: { onHostSystemDefaultSelected: state.codexSessionMigration.requestRun }, + setClaudeStatusLineListener: (listener) => agentHookServer.setClaudeStatusLineListener(listener) + }) + state.rateLimits = services.rateLimits + state.codexRuntimeHome = services.codexRuntimeHome + state.codexAccounts = services.codexAccounts + state.claudeRuntimeAuth = services.claudeRuntimeAuth + state.claudeAccounts = services.claudeAccounts + void startCodexStateDbBackfillRecoveryInBackground(getOrcaManagedCodexHomePath()) + // Defer shared-home migration; compatibility launches re-arm non-destructive scans for new rollouts (#4444, #8612, #12480). + state.codexSessionMigration.scheduleInitialRun() + store.onSettingsChanged((updates) => { + // An account switch would otherwise leave the next chat's picker on a cold catalog. + if (MODEL_CATALOG_ACCOUNT_SETTINGS.some((key) => key in updates)) { + prewarmStructuredAgentModelCatalogs() + } + }) + store.migrateLegacyOpenCodeGoApiKey({ + has: hasOpenCodeGoApiKey, + read: readOpenCodeGoApiKey, + save: saveOpenCodeGoApiKey + }) + state.keybindings = new KeybindingService({ + homePath: app.getPath('home'), + getLegacyOverrides: () => store.getSettings().keybindings, + legacyTabSwitchDefaults: store.getSettings().tabSwitchKeybindingSeed === 'legacy', + legacySearchDefaults: + (process.platform === 'darwin' + ? store.getSettings().searchKeybindingSeed + : store.getSettings().nonMacSearchKeybindingSeed) === 'legacy' + }) + browserManager.setSettingsResolver(() => ({ keybindings: state.keybindings?.getOverrides() })) +} diff --git a/src/main/startup/agent-hooks-uninstall-preflight-real-removers.test.ts b/src/main/startup/agent-hooks-uninstall-preflight-real-removers.test.ts deleted file mode 100644 index 073c6f01ad2..00000000000 --- a/src/main/startup/agent-hooks-uninstall-preflight-real-removers.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' - -const fixture = vi.hoisted(() => ({ home: '', userData: '', exit: vi.fn() })) - -vi.mock('electron', () => ({ - app: { - exit: fixture.exit, - getPath: (name: string) => (name === 'userData' ? fixture.userData : fixture.home), - getAppPath: () => fixture.userData, - getVersion: () => '0.0.0-test', - isPackaged: false, - on: vi.fn(), - setPath: vi.fn(), - requestSingleInstanceLock: vi.fn() - }, - BrowserWindow: vi.fn(), - ipcMain: { handle: vi.fn() } -})) -vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: vi.fn() })) -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, homedir: () => fixture.home } -}) - -const APP_ENVIRONMENT_SLOT = Symbol.for('orca.host.appEnvironment') - -beforeEach(() => { - fixture.home = mkdtempSync(join(tmpdir(), 'orca-uninstall-hooks-home-')) - fixture.userData = mkdtempSync(join(tmpdir(), 'orca-uninstall-hooks-data-')) - fixture.exit.mockClear() - // Every path the removers resolve from the environment stays in the fixture, on any runner. - vi.stubEnv('HOME', fixture.home) - vi.stubEnv('USERPROFILE', fixture.home) - vi.stubEnv('ORCA_USER_DATA_PATH', fixture.userData) - vi.stubEnv('XDG_CONFIG_HOME', join(fixture.home, '.config')) - vi.stubEnv('APPDATA', join(fixture.home, 'AppData', 'Roaming')) - vi.stubEnv('CODEX_HOME', join(fixture.home, '.codex')) - vi.stubEnv('CLAUDE_CONFIG_DIR', '') - // The uninstaller launches a fresh process: nothing has installed the app environment yet. - Reflect.set(globalThis, APP_ENVIRONMENT_SLOT, null) -}) - -afterEach(() => { - vi.unstubAllEnvs() - rmSync(fixture.home, { recursive: true, force: true }) - rmSync(fixture.userData, { recursive: true, force: true }) -}) - -it("runs every agent's real remover, including Claude's agent view and status-line marker", async () => { - const { installClaudeAgentView } = await import('../claude/agent-view/agent-view-install') - const { markerName } = await import('../claude/agent-view/agent-view-binding-plan') - const { CLAUDE_AGENT_VIEW_COMMAND } = await import('../../shared/claude-agent-view') - const { getStatusLineInstallMarkerPath } = await import('../claude/hook-settings') - const claudeDir = join(fixture.home, '.claude') - mkdirSync(claudeDir, { recursive: true }) - expect(installClaudeAgentView(join(claudeDir, 'settings.json'))).toBe(true) - expect(readFileSync(join(claudeDir, 'keybindings.json'), 'utf8')).toContain( - `command:${CLAUDE_AGENT_VIEW_COMMAND}` - ) - const statusLineMarker = getStatusLineInstallMarkerPath() - mkdirSync(join(statusLineMarker, '..'), { recursive: true }) - writeFileSync(statusLineMarker, '') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const { AGENT_HOOKS_UNINSTALL_FLAG, runAgentHooksUninstallPreflight } = - await import('./agent-hooks-uninstall-preflight') - expect(runAgentHooksUninstallPreflight(['Orca.exe', AGENT_HOOKS_UNINSTALL_FLAG])).toBe(true) - - await vi.waitFor(() => expect(fixture.exit).toHaveBeenCalled(), { timeout: 20_000 }) - // No remover failed, so none hit an uninitialised singleton. - expect(warn).not.toHaveBeenCalled() - expect(fixture.exit).toHaveBeenCalledExactlyOnceWith(0) - // The keybinding goes; the marker stays, recording that Orca disabled it. - expect(readFileSync(join(claudeDir, 'keybindings.json'), 'utf8')).not.toContain( - `command:${CLAUDE_AGENT_VIEW_COMMAND}` - ) - expect(JSON.parse(readFileSync(join(claudeDir, markerName), 'utf8'))).toMatchObject({ - setup: 'pending', - cleanupPending: false - }) - expect(existsSync(statusLineMarker)).toBe(false) -}) diff --git a/src/main/startup/disabled-chromium-features.ts b/src/main/startup/chromium-policy/disabled-chromium-features.ts similarity index 100% rename from src/main/startup/disabled-chromium-features.ts rename to src/main/startup/chromium-policy/disabled-chromium-features.ts diff --git a/src/main/startup/linear-regexp-fallback.ts b/src/main/startup/chromium-policy/linear-regexp-fallback.ts similarity index 100% rename from src/main/startup/linear-regexp-fallback.ts rename to src/main/startup/chromium-policy/linear-regexp-fallback.ts diff --git a/src/main/startup/chromium-policy/privileged-custom-schemes.ts b/src/main/startup/chromium-policy/privileged-custom-schemes.ts new file mode 100644 index 00000000000..dd155bc3341 --- /dev/null +++ b/src/main/startup/chromium-policy/privileged-custom-schemes.ts @@ -0,0 +1,14 @@ +import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../../browser/extensions/api-runtime/browser-extension-api-scheme' +import { JIRA_IMAGE_CUSTOM_SCHEME } from '../../jira/attachments/image-protocol' +import { MEDIA_PREVIEW_CUSTOM_SCHEME } from '../../media/media-preview-protocol' +import { PLUGIN_IMAGE_CUSTOM_SCHEME } from '../../plugins/plugin-image-scheme' +import { PLUGIN_FRAME_CUSTOM_SCHEME } from '../../plugins/panels/guest-isolation/plugin-frame-scheme' + +/** Registered with doc preview's in one call: each registerSchemesAsPrivileged call replaces the last. */ +export const PRIVILEGED_CUSTOM_SCHEMES: Electron.CustomScheme[] = [ + MEDIA_PREVIEW_CUSTOM_SCHEME, + JIRA_IMAGE_CUSTOM_SCHEME, + BROWSER_EXTENSION_API_CUSTOM_SCHEME, + PLUGIN_IMAGE_CUSTOM_SCHEME, + PLUGIN_FRAME_CUSTOM_SCHEME +] diff --git a/src/main/startup/renderer-heap-headroom.ts b/src/main/startup/chromium-policy/renderer-heap-headroom.ts similarity index 100% rename from src/main/startup/renderer-heap-headroom.ts rename to src/main/startup/chromium-policy/renderer-heap-headroom.ts diff --git a/src/main/startup/cli-command-names.ts b/src/main/startup/cli-launch/cli-command-names.ts similarity index 100% rename from src/main/startup/cli-command-names.ts rename to src/main/startup/cli-launch/cli-command-names.ts diff --git a/src/main/startup/cli-launch-redirect.ts b/src/main/startup/cli-launch/cli-launch-redirect.ts similarity index 96% rename from src/main/startup/cli-launch-redirect.ts rename to src/main/startup/cli-launch/cli-launch-redirect.ts index e156f0e3f29..d65041c4adf 100644 --- a/src/main/startup/cli-launch-redirect.ts +++ b/src/main/startup/cli-launch/cli-launch-redirect.ts @@ -1,11 +1,11 @@ import { existsSync } from 'node:fs' import { posix, resolve, win32 } from 'node:path' import { runProcessSync } from '@orca/process-host' -import { CLI_BOOLEAN_FLAGS, findCliCommandIndex } from '../../shared/cli-argument-boundary' -import { ELECTRON_NO_SANDBOX_REQUEST_ENV } from '../../shared/electron-no-sandbox-request' +import { CLI_BOOLEAN_FLAGS, findCliCommandIndex } from '../../../shared/cli-argument-boundary' +import { ELECTRON_NO_SANDBOX_REQUEST_ENV } from '../../../shared/electron-no-sandbox-request' import { CLI_COMMAND_NAMES } from './cli-command-names' -import { reexecHeadlessServeOnX11IfNeeded } from './headless-serve-x11-reexec' -import { argvRequestsServeMode, VALUE_TAKING_FLAGS } from './serve-mode-argv' +import { reexecHeadlessServeOnX11IfNeeded } from '../serve-launch/headless-serve-x11-reexec' +import { argvRequestsServeMode, VALUE_TAKING_FLAGS } from '../serve-launch/serve-mode-argv' export type CliLaunchRedirectResult = { redirected: false } | { redirected: true; status: number } diff --git a/src/main/startup/cloud-session-shutdown-flush.ts b/src/main/startup/cloud-session-shutdown-flush.ts deleted file mode 100644 index 1809141e96a..00000000000 --- a/src/main/startup/cloud-session-shutdown-flush.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { powerMonitor } from 'electron' -import { flushUnsavedCloudSessions } from '../orca-profiles/cloud-session/profile-cloud-session-owner' - -// OS shutdown may skip before-quit and lose rotated tokens; Windows reports session-end per window. -export function installCloudSessionShutdownFlush(): void { - powerMonitor.on('shutdown', flushUnsavedCloudSessions) -} diff --git a/src/main/startup/cloud-startup/cloud-session-shutdown-flush.ts b/src/main/startup/cloud-startup/cloud-session-shutdown-flush.ts new file mode 100644 index 00000000000..e9114caadea --- /dev/null +++ b/src/main/startup/cloud-startup/cloud-session-shutdown-flush.ts @@ -0,0 +1,7 @@ +import { powerMonitor } from 'electron' +import { flushUnsavedCloudSessions } from '../../orca-profiles/cloud-session/profile-cloud-session-owner' + +// OS shutdown may skip before-quit and lose rotated tokens; Windows reports session-end per window. +export function installCloudSessionShutdownFlush(): void { + powerMonitor.on('shutdown', flushUnsavedCloudSessions) +} diff --git a/src/main/startup/cloud-startup/main-process-connector-startup.ts b/src/main/startup/cloud-startup/main-process-connector-startup.ts new file mode 100644 index 00000000000..58b46b681ad --- /dev/null +++ b/src/main/startup/cloud-startup/main-process-connector-startup.ts @@ -0,0 +1,30 @@ +import type { ConnectorCloud } from '../../connector-cloud/connector-cloud' +import { createDesktopConnectorCloud } from '../../connector-cloud/connector-cloud-install' +import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' +import { mainProcessState as state } from '../main-process-state' + +// Desktop only: the connector acts as the signed-in Orca account, which `orca serve` does not have yet. +// Created before the window exists, so its sign-in and sign-out hooks always find it. +export function installDesktopConnectorCloud(): void { + if (!state.runtime || !state.store) { + return + } + state.runtime.setConnectorCloud( + createDesktopConnectorCloud( + state.runtime, + state.store, + getProfileUserDataPath(), + () => state.isQuitting + ) + ) +} + +/** The desktop's connector, for the startup, auth and quit hooks. */ +export function desktopConnectorCloud(): ConnectorCloud | null { + return state.runtime?.getConnectorCloud() ?? null +} + +// Registered with the relay; like it, the first request waits for the persisted proxy. +export function connectDesktopConnectorCloud(): void { + void state.initialProxyApplicationReady.then(() => desktopConnectorCloud()?.connect()) +} diff --git a/src/main/startup/cloud-startup/main-process-push-startup.ts b/src/main/startup/cloud-startup/main-process-push-startup.ts new file mode 100644 index 00000000000..58e988d653d --- /dev/null +++ b/src/main/startup/cloud-startup/main-process-push-startup.ts @@ -0,0 +1,28 @@ +import { getOrcaPushGatewayUrl } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' +import { DesktopPushService } from '../../runtime/push/desktop-push-service' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' +import { mainProcessState as state } from '../main-process-state' + +// Push authenticates by host keypair, so accountless hosts must register phones too; shared startup state supplies the runtime in both modes. +export function startDesktopPushService(runtimeRpc: OrcaRuntimeRpcServer): void { + const runtime: OrcaRuntimeService | null = state.runtime + if (!runtime) { + console.warn('[push] Background push startup skipped: runtime not started') + return + } + try { + const pushService = DesktopPushService.create({ + runtime, + runtimeRpc, + gatewayUrl: getOrcaPushGatewayUrl() + }) + pushService?.start() + state.desktopPushService = pushService + } catch (error) { + console.warn( + '[push] Background push startup unavailable:', + error instanceof Error ? error.message : String(error) + ) + } +} diff --git a/src/main/startup/cloud-startup/main-process-relay-startup.ts b/src/main/startup/cloud-startup/main-process-relay-startup.ts new file mode 100644 index 00000000000..89e8534643c --- /dev/null +++ b/src/main/startup/cloud-startup/main-process-relay-startup.ts @@ -0,0 +1,37 @@ +import { app, powerMonitor } from 'electron' +import { getOrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' +import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' +import type { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' +import { DesktopRelayService } from '../../runtime/mobile-cloud-relay/desktop-relay-service' +import { createDesktopRelayServiceInstaller } from '../../runtime/mobile-cloud-relay/desktop-relay-service-installer' +import { publishDesktopRelayStatus } from './main-process-relay-status' +import { mainProcessState as state } from '../main-process-state' + +// Register before proxy readiness; the installer waits before its first request. +export function startDesktopRelayService(runtimeRpc: OrcaRuntimeRpcServer): void { + const installer = createDesktopRelayServiceInstaller({ + runtimeRpc, + whenNetworkReady: state.initialProxyApplicationReady, + isFenced: () => state.isQuitting, + create: () => { + const cloudAuth = getOrcaCloudAuthConfig() + return cloudAuth.configured + ? new DesktopRelayService({ + authConfig: cloudAuth.config, + userDataPath: getProfileUserDataPath(), + appVersion: app.getVersion(), + runtimeRpc, + onStatus: publishDesktopRelayStatus + }) + : null + }, + onInstalled: (service) => { + state.desktopRelayService = service + } + }) + state.desktopRelayInstaller = installer + runtimeRpc.setMobileRelayPairingProviderInstaller(() => installer.ensure()) + // Sleep can expire the token with no retry timer; resume is the recovery opportunity. + powerMonitor.on('resume', () => state.desktopRelayService?.ensureLive()) + void installer.ensure() +} diff --git a/src/main/startup/cloud-startup/main-process-relay-status.ts b/src/main/startup/cloud-startup/main-process-relay-status.ts new file mode 100644 index 00000000000..501026dfa46 --- /dev/null +++ b/src/main/startup/cloud-startup/main-process-relay-status.ts @@ -0,0 +1,19 @@ +import type { MobileRelayStatusDetail } from '../../../shared/remote-runtime/relay/mobile-relay-status' +import { mainProcessState as state } from '../main-process-state' + +export function getDesktopRelayStatus(): MobileRelayStatusDetail { + return { ...state.desktopRelayStatus } +} + +export function publishDesktopRelayStatus( + status: MobileRelayStatusDetail['status'], + cellUrl?: string, + clockOffsetMs?: number +): void { + state.desktopRelayStatus = { + status, + ...(cellUrl === undefined ? {} : { cellUrl }), + ...(clockOffsetMs === undefined ? {} : { clockOffsetMs }) + } + state.mainWindow?.webContents.send('mobile:relayStatusChanged', getDesktopRelayStatus()) +} diff --git a/src/main/startup/codex-session-resume-launch.ts b/src/main/startup/codex-session-resume-launch.ts deleted file mode 100644 index f7634e5f440..00000000000 --- a/src/main/startup/codex-session-resume-launch.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createCodexSessionResumeLaunchPreparation } from '../codex/history/resume/codex-session-resume-launch-preparation' -import { mainProcessState as state } from './main-process-state' - -const desktopResumeLaunch = createCodexSessionResumeLaunchPreparation({ - getRuntimeHome: () => state.codexRuntimeHome, - getSettings: () => state.store?.getSettings() -}) - -export const { prepareCodexSessionResumeForLaunch, prepareCodexPinnedLaunchHome } = - desktopResumeLaunch diff --git a/src/main/startup/configure-process-profile-state.test.ts b/src/main/startup/configure-process-profile-state.test.ts index 08db1989c61..693d2dff09f 100644 --- a/src/main/startup/configure-process-profile-state.test.ts +++ b/src/main/startup/configure-process-profile-state.test.ts @@ -25,7 +25,8 @@ afterEach(() => { describe('pre-ready profile-state recovery boundary', () => { it('ignores a matching marker when SQLite is missing but an export remains', async () => { const { shouldDisableHttp2ForElectronNetworking } = await import('./configure-process') - const { writeHttp1CompatibilityMarker } = await import('./http1-compatibility-marker') + const { writeHttp1CompatibilityMarker } = + await import('./network-compatibility/http1-compatibility-marker') const { profileStateJsonExportPath } = await import('../persistence/profile-state/legacy-json/profile-state-export-path') const userDataPath = mkdtempSync(join(tmpdir(), 'orca-http1-profile-')) diff --git a/src/main/startup/configure-process.test.ts b/src/main/startup/configure-process.test.ts index f9b8bf88ca2..80cbf4deefa 100644 --- a/src/main/startup/configure-process.test.ts +++ b/src/main/startup/configure-process.test.ts @@ -133,51 +133,6 @@ describe('patchPackagedProcessPath', () => { }) describe('configureDevUserDataPath', () => { - it('forces Electron home into the disposable E2E profile', async () => { - const { app } = await import('electron') - const { configureDevUserDataPath } = await import('./configure-process') - const originalE2EUserDataDir = process.env.ORCA_E2E_USER_DATA_DIR - const originalE2EHomeDir = process.env.ORCA_E2E_HOME_DIR - const originalHome = process.env.HOME - const originalUserProfile = process.env.USERPROFILE - const tempRoot = mkdtempSync(join(tmpdir(), 'orca-configure-e2e-home-')) - const e2eRoot = join(tempRoot, 'user-data') - const e2eHome = join(tempRoot, 'home') - process.env.ORCA_E2E_USER_DATA_DIR = e2eRoot - process.env.ORCA_E2E_HOME_DIR = e2eHome - process.env.HOME = e2eHome - process.env.USERPROFILE = e2eHome - - try { - configureDevUserDataPath(true) - } finally { - rmSync(tempRoot, { recursive: true, force: true }) - if (originalE2EUserDataDir === undefined) { - delete process.env.ORCA_E2E_USER_DATA_DIR - } else { - process.env.ORCA_E2E_USER_DATA_DIR = originalE2EUserDataDir - } - if (originalE2EHomeDir === undefined) { - delete process.env.ORCA_E2E_HOME_DIR - } else { - process.env.ORCA_E2E_HOME_DIR = originalE2EHomeDir - } - if (originalHome === undefined) { - delete process.env.HOME - } else { - process.env.HOME = originalHome - } - if (originalUserProfile === undefined) { - delete process.env.USERPROFILE - } else { - process.env.USERPROFILE = originalUserProfile - } - } - - expect(app.setPath).toHaveBeenCalledWith('home', e2eHome) - expect(app.setPath).toHaveBeenCalledWith('userData', e2eRoot) - }) - it('rejects an E2E launch whose Node home escaped the disposable profile', async () => { const { configureDevUserDataPath } = await import('./configure-process') const originalE2EUserDataDir = process.env.ORCA_E2E_USER_DATA_DIR @@ -293,7 +248,8 @@ describe('configureElectronNetworkCompatibility', () => { it('answers from the marker without reading the settings file', async () => { const { shouldDisableHttp2ForElectronNetworking } = await import('./configure-process') - const { writeHttp1CompatibilityMarker } = await import('./http1-compatibility-marker') + const { writeHttp1CompatibilityMarker } = + await import('./network-compatibility/http1-compatibility-marker') const userDataPath = createUserDataDir({ electronHttp1CompatibilityMode: false }) writeHttp1CompatibilityMarker(userDataPath, true) rmSync(join(userDataPath, 'orca-data.json'), { force: true }) @@ -311,7 +267,8 @@ describe('configureElectronNetworkCompatibility', () => { it('lets the environment override the marker', async () => { const { shouldDisableHttp2ForElectronNetworking } = await import('./configure-process') - const { writeHttp1CompatibilityMarker } = await import('./http1-compatibility-marker') + const { writeHttp1CompatibilityMarker } = + await import('./network-compatibility/http1-compatibility-marker') const userDataPath = createUserDataDir({}) writeHttp1CompatibilityMarker(userDataPath, true) @@ -322,7 +279,8 @@ describe('configureElectronNetworkCompatibility', () => { it('scopes a profile marker to the active profile before trusting it', async () => { const { shouldDisableHttp2ForElectronNetworking } = await import('./configure-process') - const { writeHttp1CompatibilityMarker } = await import('./http1-compatibility-marker') + const { writeHttp1CompatibilityMarker } = + await import('./network-compatibility/http1-compatibility-marker') const userDataPath = mkdtempSync(join(tmpdir(), 'orca-http1-profile-')) tempDirs.push(userDataPath) createProfileState(userDataPath, 'profile-b', { electronHttp1CompatibilityMode: false }) @@ -333,7 +291,8 @@ describe('configureElectronNetworkCompatibility', () => { it('uses a matching profile marker even when the legacy JSON is stale', async () => { const { shouldDisableHttp2ForElectronNetworking } = await import('./configure-process') - const { writeHttp1CompatibilityMarker } = await import('./http1-compatibility-marker') + const { writeHttp1CompatibilityMarker } = + await import('./network-compatibility/http1-compatibility-marker') const userDataPath = mkdtempSync(join(tmpdir(), 'orca-http1-profile-')) tempDirs.push(userDataPath) createProfileState(userDataPath, 'profile-b', { electronHttp1CompatibilityMode: false }) @@ -354,182 +313,3 @@ describe('configureElectronNetworkCompatibility', () => { expect(shouldDisableHttp2ForElectronNetworking({ env: {}, userDataPath })).toBe(false) }) }) - -describe('enableMainProcessGpuFeatures', () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - const originalE2EUserDataDir = process.env.ORCA_E2E_USER_DATA_DIR - - function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { - configurable: true, - value: platform - }) - } - - afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - if (originalE2EUserDataDir === undefined) { - delete process.env.ORCA_E2E_USER_DATA_DIR - } else { - process.env.ORCA_E2E_USER_DATA_DIR = originalE2EUserDataDir - } - }) - - it('disables the GPU sandbox on Linux Wayland without disabling acceleration', async () => { - const { app } = await import('electron') - const { enableMainProcessGpuFeatures } = await import('./configure-process') - const originalWaylandDisplay = process.env.WAYLAND_DISPLAY - - try { - setPlatform('linux') - delete process.env.ORCA_E2E_USER_DATA_DIR - process.env.WAYLAND_DISPLAY = 'wayland-1' - vi.mocked(app.disableHardwareAcceleration).mockClear() - vi.mocked(app.commandLine.appendSwitch).mockClear() - - enableMainProcessGpuFeatures() - } finally { - if (originalWaylandDisplay === undefined) { - delete process.env.WAYLAND_DISPLAY - } else { - process.env.WAYLAND_DISPLAY = originalWaylandDisplay - } - } - - expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('disable-gpu-sandbox') - expect(app.disableHardwareAcceleration).not.toHaveBeenCalled() - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith( - 'enable-features', - expect.stringContaining('EarlyEstablishGpuChannel') - ) - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith( - 'enable-features', - expect.stringContaining('EstablishGpuChannelAsync') - ) - }) - - it('uses Electron Ozone hints to recognize forced Linux Wayland launches', async () => { - const { app } = await import('electron') - const { enableMainProcessGpuFeatures } = await import('./configure-process') - - setPlatform('linux') - delete process.env.ORCA_E2E_USER_DATA_DIR - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockImplementation((switchName: string) => - switchName === 'ozone-platform' ? 'wayland' : '' - ) - - enableMainProcessGpuFeatures() - - expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('disable-gpu-sandbox') - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith( - 'enable-features', - expect.stringContaining('EarlyEstablishGpuChannel') - ) - }) - - it('honors explicit Linux X11 Ozone overrides even when Wayland env vars are present', async () => { - const { app } = await import('electron') - const { enableMainProcessGpuFeatures } = await import('./configure-process') - const originalWaylandDisplay = process.env.WAYLAND_DISPLAY - const originalSessionType = process.env.XDG_SESSION_TYPE - - try { - setPlatform('linux') - delete process.env.ORCA_E2E_USER_DATA_DIR - process.env.WAYLAND_DISPLAY = 'wayland-1' - process.env.XDG_SESSION_TYPE = 'wayland' - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockImplementation((switchName: string) => - switchName === 'ozone-platform' ? 'x11' : '' - ) - - enableMainProcessGpuFeatures() - } finally { - if (originalWaylandDisplay === undefined) { - delete process.env.WAYLAND_DISPLAY - } else { - process.env.WAYLAND_DISPLAY = originalWaylandDisplay - } - if (originalSessionType === undefined) { - delete process.env.XDG_SESSION_TYPE - } else { - process.env.XDG_SESSION_TYPE = originalSessionType - } - } - - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('disable-gpu-sandbox') - expect(app.commandLine.appendSwitch).toHaveBeenCalledWith( - 'enable-features', - 'EarlyEstablishGpuChannel,EstablishGpuChannelAsync' - ) - }) - - it('does not disable the GPU sandbox outside Linux Wayland', async () => { - const { app } = await import('electron') - const { enableMainProcessGpuFeatures } = await import('./configure-process') - const originalWaylandDisplay = process.env.WAYLAND_DISPLAY - const originalSessionType = process.env.XDG_SESSION_TYPE - const originalOzoneHint = process.env.ELECTRON_OZONE_PLATFORM_HINT - - try { - delete process.env.ORCA_E2E_USER_DATA_DIR - delete process.env.WAYLAND_DISPLAY - delete process.env.XDG_SESSION_TYPE - delete process.env.ELECTRON_OZONE_PLATFORM_HINT - - for (const platform of ['linux', 'darwin', 'win32'] as const) { - setPlatform(platform) - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockImplementation((switchName: string) => - switchName === 'enable-features' ? '' : '' - ) - - enableMainProcessGpuFeatures() - - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('disable-gpu-sandbox') - } - } finally { - if (originalWaylandDisplay === undefined) { - delete process.env.WAYLAND_DISPLAY - } else { - process.env.WAYLAND_DISPLAY = originalWaylandDisplay - } - if (originalSessionType === undefined) { - delete process.env.XDG_SESSION_TYPE - } else { - process.env.XDG_SESSION_TYPE = originalSessionType - } - if (originalOzoneHint === undefined) { - delete process.env.ELECTRON_OZONE_PLATFORM_HINT - } else { - process.env.ELECTRON_OZONE_PLATFORM_HINT = originalOzoneHint - } - } - }) - - it('disables the GPU process for Linux E2E runs', async () => { - const { app } = await import('electron') - const { enableMainProcessGpuFeatures } = await import('./configure-process') - - setPlatform('linux') - process.env.ORCA_E2E_USER_DATA_DIR = '/tmp/orca-e2e' - vi.mocked(app.disableHardwareAcceleration).mockClear() - vi.mocked(app.commandLine.appendSwitch).mockClear() - - enableMainProcessGpuFeatures() - - expect(app.disableHardwareAcceleration).toHaveBeenCalledTimes(1) - expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('disable-gpu') - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith( - 'enable-features', - expect.any(String) - ) - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith( - 'max-active-webgl-contexts', - expect.any(String) - ) - }) -}) diff --git a/src/main/startup/configure-process.ts b/src/main/startup/configure-process.ts index 060967d63f2..ef4c976adc2 100644 --- a/src/main/startup/configure-process.ts +++ b/src/main/startup/configure-process.ts @@ -1,22 +1,22 @@ import { app } from 'electron' -import { guardExternalOpensInE2E } from './e2e-external-open-guard' -import { quitProcess } from './process-quit-request' +import { guardExternalOpensInE2E } from './testing/e2e-external-open-guard' +import { quitProcess } from './quit/process-quit-request' import { existsSync, mkdirSync } from 'node:fs' import { homedir } from 'node:os' import { join, resolve } from 'node:path' import { getVersionManagerBinPaths } from '../codex-cli/command' import { isWindowsFnmDefaultAliasDir } from '../../shared/fnm-default-alias-dirs' import { getMainE2EConfig } from './testing/e2e-config' -import { DISABLED_CHROMIUM_FEATURES } from './disabled-chromium-features' -import { readHttp1CompatibilityMarker } from './http1-compatibility-marker' -import { checkServeUserDataPath } from './serve-user-data-path-guard' +import { DISABLED_CHROMIUM_FEATURES } from './chromium-policy/disabled-chromium-features' +import { readHttp1CompatibilityMarker } from './network-compatibility/http1-compatibility-marker' +import { checkServeUserDataPath } from './serve-launch/serve-user-data-path-guard' import { stampRuntimeSourceEnv } from '../../shared/runtime-source-env' import { isLinuxWaylandSession } from '../../shared/linux-wayland-session' import { hasMissingProfileStateDatabaseWithRetainedAuthority, readActiveProfileId, readPersistedHttp1CompatibilityMode -} from './http1-compatibility-profile-state' +} from './network-compatibility/http1-compatibility-profile-state' const DEV_PARENT_SHUTDOWN_GRACE_MS = 3000 const HTTP1_COMPATIBILITY_ENV_VAR = 'ORCA_DISABLE_HTTP2' diff --git a/src/main/startup/event-loop-stall-probe.ts b/src/main/startup/diagnostics/event-loop-stall-probe.ts similarity index 100% rename from src/main/startup/event-loop-stall-probe.ts rename to src/main/startup/diagnostics/event-loop-stall-probe.ts diff --git a/src/main/startup/startup-diagnostics.ts b/src/main/startup/diagnostics/startup-diagnostics.ts similarity index 100% rename from src/main/startup/startup-diagnostics.ts rename to src/main/startup/diagnostics/startup-diagnostics.ts diff --git a/src/main/startup/e2e-external-open-guard.test.ts b/src/main/startup/e2e-external-open-guard.test.ts deleted file mode 100644 index 8a1d224bd74..00000000000 --- a/src/main/startup/e2e-external-open-guard.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { expect, it, vi } from 'vitest' - -const openExternal = vi.hoisted(() => vi.fn()) -vi.mock('electron', () => ({ shell: { openExternal } })) - -const { shell } = await import('electron') -const { guardExternalOpensInE2E } = await import('./e2e-external-open-guard') - -it("never opens the tester's browser or mail client in an e2e launch", async () => { - vi.spyOn(console, 'info').mockImplementation(() => undefined) - guardExternalOpensInE2E() - await shell.openExternal('mailto:a@example.com') - await shell.openExternal('https://example.com') - expect(openExternal).not.toHaveBeenCalled() -}) diff --git a/src/main/startup/ensure-virtual-display.test.ts b/src/main/startup/ensure-virtual-display.test.ts deleted file mode 100644 index b4ed9d23726..00000000000 --- a/src/main/startup/ensure-virtual-display.test.ts +++ /dev/null @@ -1,690 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { spawnMock, existsSyncMock, readFileSyncMock, rmSyncMock, statSyncMock, appMock } = - vi.hoisted(() => ({ - spawnMock: vi.fn(), - existsSyncMock: vi.fn(), - readFileSyncMock: vi.fn(), - rmSyncMock: vi.fn(), - statSyncMock: vi.fn(), - appMock: { - disableHardwareAcceleration: vi.fn(), - commandLine: { appendSwitch: vi.fn(), getSwitchValue: vi.fn() }, - once: vi.fn() - } - })) - -vi.mock('child_process', () => ({ spawn: spawnMock })) -vi.mock('fs', () => ({ - existsSync: existsSyncMock, - readFileSync: readFileSyncMock, - rmSync: rmSyncMock, - statSync: statSyncMock -})) -vi.mock('electron', () => ({ app: appMock })) - -const OWN_UID = 1000 -const OTHER_UID = 1001 -const ORIGINAL_PLATFORM = process.platform -const ORIGINAL_GETUID = Object.getOwnPropertyDescriptor(process, 'getuid') -const ORIGINAL_DISPLAY = process.env.DISPLAY - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) - // Simulated Linux still needs a UID when the Windows test host lacks getuid. - Object.defineProperty(process, 'getuid', { - value: () => OWN_UID, - configurable: true, - writable: true - }) -} - -function mockLiveXDisplay(pid = 4321): void { - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - existsSyncMock.mockReturnValue(true) - readFileSyncMock.mockReturnValue(`${pid}\n`) - vi.spyOn(process, 'kill').mockImplementation(() => true) -} - -function mockXvfbTakesDisplay(pid = 1234): void { - let bound = false - statSyncMock.mockImplementation(() => ({ isSocket: () => true, uid: OWN_UID })) - readFileSyncMock.mockImplementation(() => { - if (!bound) { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - } - return `${pid}\n` - }) - vi.spyOn(process, 'kill').mockImplementation(() => true) - spawnMock.mockImplementation(() => { - bound = true - return { pid, once: vi.fn(), kill: vi.fn(), killed: false } - }) -} - -describe('ensureVirtualDisplayForHeadlessServe', () => { - beforeEach(() => { - spawnMock.mockReset() - existsSyncMock.mockReset() - readFileSyncMock.mockReset() - rmSyncMock.mockReset() - statSyncMock.mockReset() - appMock.disableHardwareAcceleration.mockReset() - appMock.commandLine.appendSwitch.mockReset() - appMock.commandLine.getSwitchValue.mockReset().mockReturnValue('') - appMock.once.mockReset() - delete process.env.DISPLAY - }) - - afterEach(async () => { - const { stopVirtualDisplay } = await import('./ensure-virtual-display') - process.removeListener('exit', stopVirtualDisplay) - stopVirtualDisplay() - vi.restoreAllMocks() - setPlatform(ORIGINAL_PLATFORM) - if (ORIGINAL_GETUID) { - Object.defineProperty(process, 'getuid', ORIGINAL_GETUID) - } else { - Reflect.deleteProperty(process, 'getuid') - } - if (ORIGINAL_DISPLAY === undefined) { - delete process.env.DISPLAY - } else { - process.env.DISPLAY = ORIGINAL_DISPLAY - } - }) - - it('is a no-op (supported) on non-Linux platforms', async () => { - setPlatform('darwin') - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(spawnMock).not.toHaveBeenCalled() - }) - - it('does not start a display outside serve mode on Linux', async () => { - setPlatform('linux') - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: false })).toBe(false) - expect(spawnMock).not.toHaveBeenCalled() - }) - - it('reuses an externally provided DISPLAY without starting Xvfb', async () => { - setPlatform('linux') - process.env.DISPLAY = ':0' - mockLiveXDisplay() - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(spawnMock).not.toHaveBeenCalled() - expect(process.env.DISPLAY).toBe(':0') - expect(appMock.disableHardwareAcceleration).toHaveBeenCalled() - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-gpu') - }) - - it('keeps hardware acceleration when ORCA_SERVE_GPU=1 opts in', async () => { - setPlatform('linux') - process.env.DISPLAY = ':0' - vi.stubEnv('ORCA_SERVE_GPU', '1') - mockLiveXDisplay() - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - try { - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - } finally { - vi.unstubAllEnvs() - } - expect(appMock.disableHardwareAcceleration).not.toHaveBeenCalled() - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalledWith('disable-gpu') - }) - - it('reports unsupported when Xvfb cannot be launched', async () => { - setPlatform('linux') - statSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - spawnMock.mockReturnValue({ pid: undefined, once: vi.fn(), kill: vi.fn(), killed: false }) - const { - ensureVirtualDisplayForHeadlessServe, - MISSING_LINUX_DISPLAY_MESSAGE, - MISSING_SERVE_DISPLAY_MESSAGE, - missingLinuxDisplayMessage - } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(false) - expect(spawnMock).toHaveBeenCalledWith('Xvfb', expect.any(Array), expect.any(Object)) - expect(MISSING_LINUX_DISPLAY_MESSAGE).toContain('endpoint is unavailable') - expect(MISSING_LINUX_DISPLAY_MESSAGE).toContain('XDG_RUNTIME_DIR') - for (const message of [MISSING_LINUX_DISPLAY_MESSAGE, MISSING_SERVE_DISPLAY_MESSAGE]) { - expect(message).toContain('`xvfb` on Debian/Ubuntu') - expect(message).toContain('`xorg-x11-server-Xvfb`') - expect(message).toContain('`xorg-server-xvfb` on Arch') - } - expect(MISSING_SERVE_DISPLAY_MESSAGE).not.toContain('orca-ide serve') - expect(MISSING_SERVE_DISPLAY_MESSAGE).toContain('Wayland alone is not enough') - expect(missingLinuxDisplayMessage(true)).toBe(MISSING_SERVE_DISPLAY_MESSAGE) - expect(missingLinuxDisplayMessage(false)).toBe(MISSING_LINUX_DISPLAY_MESSAGE) - }) - - it('leaves an externally configured stale display untouched', async () => { - setPlatform('linux') - process.env.DISPLAY = ':77' - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - existsSyncMock.mockReturnValue(true) - readFileSyncMock.mockImplementation(() => { - throw new Error('display lock is outside this namespace') - }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(false) - expect(spawnMock).not.toHaveBeenCalled() - expect(rmSyncMock).not.toHaveBeenCalled() - expect(process.env.DISPLAY).toBe(':77') - }) - - // #15084: containers may expose an external X socket without its host lock/PID. - it('serves on an externally configured display that has no lock file', async () => { - setPlatform('linux') - process.env.DISPLAY = ':0' - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(spawnMock).not.toHaveBeenCalled() - expect(rmSyncMock).not.toHaveBeenCalled() - expect(process.env.DISPLAY).toBe(':0') - }) - - // Cleanup unlinks lock first; trusting Orca's own lockless :99 would revive an orphan socket. - it('does not adopt its own :99 socket when the lock is missing', async () => { - setPlatform('linux') - existsSyncMock.mockReturnValue(true) - mockXvfbTakesDisplay() - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(rmSyncMock).toHaveBeenCalled() - expect(spawnMock).toHaveBeenCalledWith( - 'Xvfb', - expect.arrayContaining([':99']), - expect.any(Object) - ) - }) - - it('reuses an existing virtual display only when its X server is alive', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - existsSyncMock.mockReturnValue(true) - readFileSyncMock.mockReturnValue('4321\n') - const killSpy = vi.spyOn(process, 'kill').mockReturnValue(true as never) // PID alive - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(killSpy).toHaveBeenCalledWith(4321, 0) - expect(spawnMock).not.toHaveBeenCalled() - expect(rmSyncMock).not.toHaveBeenCalled() - expect(process.env.DISPLAY).toBe(':99') - killSpy.mockRestore() - }) - - it('treats a stale socket (dead server) as no display and starts a fresh Xvfb', async () => { - setPlatform('linux') - existsSyncMock.mockReturnValue(true) - let bound = false - statSyncMock.mockImplementation(() => ({ isSocket: () => true, uid: OWN_UID })) - readFileSyncMock.mockImplementation(() => (bound ? '1234\n' : '9999\n')) - // Only the newly spawned Xvfb is alive; the orphan lock PID is dead. - const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid) => { - if (pid === 9999) { - throw new Error('ESRCH') - } - return true as never - }) - spawnMock.mockImplementation(() => { - bound = true - return { pid: 1234, once: vi.fn(), kill: vi.fn(), killed: false } - }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(rmSyncMock).toHaveBeenCalled() - expect(spawnMock).toHaveBeenCalledWith( - 'Xvfb', - expect.arrayContaining([':99', '-terminate']), - expect.objectContaining({ detached: true }) - ) - expect(process.env.DISPLAY).toBe(':99') - killSpy.mockRestore() - }) - - // A foreign stale socket can prevent bind; trusting it advertised a dead display and crashed Ozone initialization. - it('reports failure when a stale socket blocks the Xvfb rebind', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - // Foreign ownership prevents unlink and Xvfb never acquires the display. - rmSyncMock.mockImplementation(() => { - throw Object.assign(new Error('permission denied'), { code: 'EACCES' }) - }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - spawnMock.mockReturnValue({ pid: 4242, once: vi.fn(), kill: vi.fn(), killed: false }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - vi.useFakeTimers({ toFake: ['Date'] }) - const sleep = vi - .spyOn(Atomics, 'wait') - .mockImplementation((_array, _index, _value, timeout) => { - vi.setSystemTime(Date.now() + (timeout ?? 0)) - return 'timed-out' - }) - try { - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(false) - expect(process.env.DISPLAY).toBeUndefined() - } finally { - sleep.mockRestore() - vi.useRealTimers() - } - }) - - it('accepts the display once the spawned Xvfb owns its lock', async () => { - setPlatform('linux') - let lockWritten = false - statSyncMock.mockImplementation(() => ({ isSocket: () => lockWritten, uid: OWN_UID })) - rmSyncMock.mockImplementation(() => {}) - readFileSyncMock.mockImplementation(() => { - if (!lockWritten) { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - } - return '4242\n' - }) - vi.spyOn(process, 'kill').mockImplementation(() => true) - spawnMock.mockImplementation(() => { - lockWritten = true - return { pid: 4242, once: vi.fn(), kill: vi.fn(), killed: false } - }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(process.env.DISPLAY).toBe(':99') - }) - - describe('with several accounts on one machine (#26602)', () => { - type FakeDisplay = { uid: number; lockPid: number | null; socket: boolean } - - // Model independent artifacts/ownership for each candidate display. - function mockDisplays(displays: Record, alivePids: number[]): void { - const displayOf = (path: string): FakeDisplay | undefined => { - const match = /(?:\.X(\d+)-lock|X11-unix\/X(\d+))$/.exec(path) - return match ? displays[Number(match[1] ?? match[2])] : undefined - } - const enoent = () => Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - statSyncMock.mockImplementation((path: string) => { - const display = displayOf(path) - const isLock = path.endsWith('-lock') - if (!display || (isLock ? display.lockPid === null : !display.socket)) { - throw enoent() - } - return { uid: display.uid, isSocket: () => !isLock } - }) - readFileSyncMock.mockImplementation((path: string) => { - if (path === '/proc/net/unix') { - return '' - } - const display = displayOf(path) - if (!display || display.lockPid === null) { - throw enoent() - } - return `${display.lockPid}\n` - }) - vi.spyOn(process, 'kill').mockImplementation((pid) => { - if (!alivePids.includes(Number(pid))) { - throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' }) - } - return true - }) - let nextPid = 5000 - spawnMock.mockImplementation((_command: string, args: string[]) => { - const pid = nextPid++ - alivePids.push(pid) - const displayNumber = Number(args[0].slice(1)) - if (!displays[displayNumber]) { - displays[displayNumber] = { uid: OWN_UID, lockPid: pid, socket: true } - } - return { pid, once: vi.fn(), kill: vi.fn(), killed: false } - }) - } - - it("starts its own display instead of attaching to another account's live :99", async () => { - setPlatform('linux') - mockDisplays({ 99: { uid: OTHER_UID, lockPid: 777, socket: true } }, [777]) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(process.env.DISPLAY).toBe(':100') - expect(spawnMock).toHaveBeenCalledWith( - 'Xvfb', - expect.arrayContaining([':100']), - expect.any(Object) - ) - expect(rmSyncMock).not.toHaveBeenCalled() - }) - - it("skips another account's stale :99 that sticky /tmp keeps it from removing", async () => { - setPlatform('linux') - mockDisplays({ 99: { uid: OTHER_UID, lockPid: 777, socket: true } }, []) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(process.env.DISPLAY).toBe(':100') - expect(rmSyncMock).not.toHaveBeenCalled() - }) - - it('reuses its own live display past the ones other accounts hold', async () => { - setPlatform('linux') - mockDisplays( - { - 99: { uid: OTHER_UID, lockPid: 777, socket: true }, - 100: { uid: OWN_UID, lockPid: 888, socket: true } - }, - [777, 888] - ) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(process.env.DISPLAY).toBe(':100') - expect(spawnMock).not.toHaveBeenCalled() - }) - - it("leaves its own account's display alone while that server is still starting", async () => { - setPlatform('linux') - // :99 has its live lock but no socket yet. - mockDisplays({ 99: { uid: OWN_UID, lockPid: 888, socket: false } }, [888]) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(process.env.DISPLAY).toBe(':100') - expect(rmSyncMock).not.toHaveBeenCalled() - }) - - it('does not accept a spawned Xvfb that died after writing its lock and socket', async () => { - setPlatform('linux') - const alive: number[] = [] - mockDisplays({}, alive) - const startXvfb = spawnMock.getMockImplementation()! - spawnMock.mockImplementation((command: string, args: string[]) => { - const child = startXvfb(command, args) - alive.splice(alive.indexOf(child.pid), 1) - return child - }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - vi.useFakeTimers({ toFake: ['Date'] }) - const sleep = vi - .spyOn(Atomics, 'wait') - .mockImplementation((_array, _index, _value, timeout) => { - vi.setSystemTime(Date.now() + (timeout ?? 0)) - return 'timed-out' - }) - try { - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(false) - expect(process.env.DISPLAY).toBeUndefined() - } finally { - sleep.mockRestore() - vi.useRealTimers() - } - }) - - it('moves on when another server wins the free display first', async () => { - setPlatform('linux') - const displays: Record = {} - mockDisplays(displays, [777]) - const startXvfb = spawnMock.getMockImplementation()! - spawnMock.mockImplementationOnce((command: string, args: string[]) => { - // Model another account winning the bind race. - displays[99] = { uid: OTHER_UID, lockPid: 777, socket: true } - return startXvfb(command, args) - }) - const { ensureVirtualDisplayForHeadlessServe } = await import('./ensure-virtual-display') - - expect(ensureVirtualDisplayForHeadlessServe({ isServeMode: true })).toBe(true) - expect(process.env.DISPLAY).toBe(':100') - expect(spawnMock).toHaveBeenCalledTimes(2) - }) - }) - - describe('hasUsableLinuxDisplay', () => { - it('accepts live local X11 and Wayland sockets', async () => { - setPlatform('linux') - mockLiveXDisplay() - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(true) - expect( - hasUsableLinuxDisplay({ - WAYLAND_DISPLAY: 'wayland-0', - XDG_RUNTIME_DIR: '/run/user/1000' - }) - ).toBe(true) - expect(statSyncMock).toHaveBeenCalledWith('/tmp/.X11-unix/X0') - expect(statSyncMock).toHaveBeenCalledWith('/run/user/1000/wayland-0') - }) - - // Abstract sockets are kernel-owned and vanish on exit, so their presence proves a live server. - it('accepts an abstract-namespace X socket with no filesystem socket', async () => { - setPlatform('linux') - statSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - readFileSyncMock.mockImplementation((path: string) => { - if (path === '/proc/net/unix') { - return [ - 'Num RefCount Protocol Flags Type St Inode Path', - '0000000000000000: 00000003 00000000 00000000 0001 03 12014 @/tmp/.X11-unix/X0', - '' - ].join('\n') - } - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(true) - }) - - it('does not confuse a different display number in the abstract table', async () => { - setPlatform('linux') - statSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - readFileSyncMock.mockImplementation((path: string) => { - if (path === '/proc/net/unix') { - return '0000000000000000: 00000003 00000000 00000000 0001 03 12014 @/tmp/.X11-unix/X10\n' - } - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':1' })).toBe(false) - }) - - it('accepts an inherited WAYLAND_SOCKET fd with no WAYLAND_DISPLAY', async () => { - setPlatform('linux') - statSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ WAYLAND_SOCKET: '7' })).toBe(true) - expect(hasUsableLinuxDisplay({ WAYLAND_SOCKET: 'not-an-fd' })).toBe(false) - }) - - // Own lockless :99 can be half-finished teardown even when inherited DISPLAY names it. - it('does not trust a lockless socket on its own managed display number', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':99' })).toBe(false) - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(true) - }) - - it('rejects an orphaned local X11 socket whose server PID is gone', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - existsSyncMock.mockReturnValue(true) - readFileSyncMock.mockReturnValue('9999\n') - vi.spyOn(process, 'kill').mockImplementation(() => { - throw Object.assign(new Error('no such process'), { code: 'ESRCH' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':77' })).toBe(false) - expect(readFileSyncMock).toHaveBeenCalledWith('/tmp/.X77-lock', 'utf8') - }) - - // External lockless sockets can come from container mounts/WSLg; a crashed local X server leaves its lock too. - it('accepts a local X11 socket published without a lock file', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const killSpy = vi.spyOn(process, 'kill') - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(true) - expect(hasUsableLinuxDisplay({ DISPLAY: ':100' })).toBe(true) - expect(killSpy).not.toHaveBeenCalled() - }) - - // Pinned X11 cannot rely on a Wayland fallback in WSLg. - it('accepts a lockless X11 socket when x11 is pinned and Wayland is unavailable', async () => { - setPlatform('linux') - statSyncMock.mockImplementation((path: string) => ({ - isSocket: () => path === '/tmp/.X11-unix/X0' - })) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0', ELECTRON_OZONE_PLATFORM_HINT: 'x11' })).toBe( - true - ) - }) - - it('still rejects a missing socket even when no lock file exists', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => false }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(false) - }) - - it('rejects a lock that exists but cannot be read', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - readFileSyncMock.mockImplementation(() => { - throw Object.assign(new Error('permission denied'), { code: 'EACCES' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(false) - }) - - it('accepts a live local X11 server owned by another user', async () => { - setPlatform('linux') - statSyncMock.mockReturnValue({ isSocket: () => true, uid: OWN_UID }) - existsSyncMock.mockReturnValue(true) - readFileSyncMock.mockReturnValue('4321\n') - vi.spyOn(process, 'kill').mockImplementation(() => { - throw Object.assign(new Error('not permitted'), { code: 'EPERM' }) - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: ':0' })).toBe(true) - }) - - it('rejects absent, blank, and stale local displays', async () => { - setPlatform('linux') - statSyncMock.mockImplementation(() => { - throw new Error('ENOENT') - }) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({})).toBe(false) - expect(hasUsableLinuxDisplay({ DISPLAY: ' ', WAYLAND_DISPLAY: '' })).toBe(false) - expect(hasUsableLinuxDisplay({ DISPLAY: ':77' })).toBe(false) - expect( - hasUsableLinuxDisplay({ WAYLAND_DISPLAY: 'wayland-0', XDG_RUNTIME_DIR: '/run/user/1000' }) - ).toBe(false) - expect(hasUsableLinuxDisplay({ WAYLAND_DISPLAY: 'wayland-0' })).toBe(false) - }) - - it.each([ - ['localhost:10.0', true], - ['build-host.example:1', true], - ['[2001:db8::1]:2.0', true], - ['tcp/build-host.example:3', true], - ['garbage', false], - ['build host:1', false], - ['build-host.example:', false], - ['build-host.example:abc', false] - ])('validates remote X display syntax for %s', async (display, expected) => { - setPlatform('linux') - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({ DISPLAY: display })).toBe(expected) - expect(statSyncMock).not.toHaveBeenCalled() - }) - - it('honors forced X11 and Wayland platform selection', async () => { - setPlatform('linux') - statSyncMock.mockImplementation((path: string) => ({ - isSocket: () => path === '/run/user/1000/wayland-0' - })) - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - const env = { - DISPLAY: ':77', - WAYLAND_DISPLAY: 'wayland-0', - XDG_RUNTIME_DIR: '/run/user/1000' - } - - appMock.commandLine.getSwitchValue.mockReturnValue('x11') - expect(hasUsableLinuxDisplay(env)).toBe(false) - appMock.commandLine.getSwitchValue.mockReturnValue('wayland') - expect(hasUsableLinuxDisplay(env)).toBe(true) - - statSyncMock.mockImplementation((path: string) => ({ - isSocket: () => path === '/tmp/.X11-unix/X0' - })) - expect(hasUsableLinuxDisplay({ ...env, DISPLAY: ':0' })).toBe(false) - - appMock.commandLine.getSwitchValue.mockReturnValue('') - expect(hasUsableLinuxDisplay({ ...env, ELECTRON_OZONE_PLATFORM_HINT: 'x11' })).toBe(false) - }) - - it('never gates a non-Linux platform', async () => { - setPlatform('darwin') - const { hasUsableLinuxDisplay } = await import('./ensure-virtual-display') - - expect(hasUsableLinuxDisplay({})).toBe(true) - expect(statSyncMock).not.toHaveBeenCalled() - }) - }) -}) diff --git a/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts b/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts deleted file mode 100644 index 32983147666..00000000000 --- a/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' - -// Any prompt is the signal; answer Keep Running to avoid relaunch. -const { showMessageBox, userData } = vi.hoisted(() => ({ - showMessageBox: vi.fn(async () => ({ response: 1 })), - userData: { path: '' } -})) - -vi.mock('electron', () => ({ - app: { - isPackaged: true, - getPath: () => userData.path, - getVersion: () => '1.4.184', - getGPUFeatureStatus: () => ({}), - setAboutPanelOptions: vi.fn(), - commandLine: { appendSwitch: vi.fn() }, - disableHardwareAcceleration: vi.fn(), - isReady: () => true, - exit: vi.fn(), - on: vi.fn(), - name: 'Orca' - }, - dialog: { showMessageBox } -})) - -import { grantsFrom } from './windows-install-dir-acl.test-fixture' -import { - DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD, - DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, - GpuCrashFallbackTracker -} from '../crash-reporting/recovery/gpu-crash-fallback-decision' -import { - readGpuFallbackMarker, - writeGpuFallbackMarker, - type GpuFallbackMarker -} from './gpu-fallback-marker' -import { handleGpuChildCrash, presentGpuFallbackRecoveredLaunchPrompt } from './gpu-lifecycle' -import { gpuFallbackEnvironment, mainProcessState as state } from './main-process-state' -import './windows-install-dir-acl-poison-marker' -import { - isInstallDirAclRepairPending, - noteWindowsInstallDirAclProbePending, - resetWindowsInstallDirAclRecoveryForTest, - startWindowsInstallDirAclRepairIfPoisoned -} from './windows-install-dir-acl-recovery' -import { resetWindowsInstallDirAclRepairForTest } from './windows-install-dir-package-acl-repair' - -const INSTALL_DIR = 'C:\\Users\\neil\\AppData\\Local\\Programs\\orca' - -function recoveryOptions(userDataPath?: string): { - platform: 'win32' - installDir: string - appVersion: string - userDataPath: string - recordBreadcrumb: () => void -} { - return { - platform: 'win32', - installDir: INSTALL_DIR, - appVersion: '1.4.184', - userDataPath: userDataPath ?? mkdtempSync(join(tmpdir(), 'orca-acl-gpu-guard-')), - recordBreadcrumb: () => undefined - } -} - -/** Keep repair pending through GPU child deaths. */ -function reportProbePoisoned(): { finishRepair: () => Promise } { - let release = (): void => undefined - const walkingTheTree = new Promise((resolve) => { - release = resolve - }) - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: true }, - { - ...recoveryOptions(), - grants: grantsFrom(async () => { - await walkingTheTree - return { ok: true, failedFileCount: 0 } - }) - } - ) - return { - finishRepair: async () => { - release() - for (let i = 0; i < 200 && isInstallDirAclRepairPending(); i += 1) { - await new Promise((resolve) => setTimeout(resolve, 5)) - } - } - } -} - -async function reportProbePoisonedWithSettledRepair( - granted: boolean, - userDataPath?: string -): Promise { - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: true }, - { - ...recoveryOptions(userDataPath), - grants: grantsFrom(async () => - granted - ? { ok: true, failedFileCount: 0 } - : { ok: false, failedFileCount: 1, reason: 'access denied' } - ) - } - ) - for (let i = 0; i < 200 && isInstallDirAclRepairPending(); i += 1) { - await new Promise((resolve) => setTimeout(resolve, 5)) - } -} - -function reportProbeClean(): void { - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: false }, - recoveryOptions() - ) -} - -async function crashUpToThreshold(): Promise { - for (let i = 1; i < DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD; i += 1) { - await handleGpuChildCrash('crashed', null, i * 200) - } -} - -/** Exercise the real tracker: source matching cannot prove driver bursts survive either ACL verdict. */ -describe('handleGpuChildCrash vs the install-dir ACL verdict', () => { - let tracker: GpuCrashFallbackTracker - const realPlatform = process.platform - - beforeAll(() => { - Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) - }) - - afterAll(() => { - Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true }) - }) - - beforeEach(() => { - userData.path = mkdtempSync(join(tmpdir(), 'orca-acl-gpu-userdata-')) - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - showMessageBox.mockClear() - state.isQuitting = false - state.isServeMode = false - state.gpuFallbackActiveThisLaunch = false - tracker = new GpuCrashFallbackTracker({ - windowMs: DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, - threshold: DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD - }) - state.gpuCrashFallbackTracker = tracker - }) - - // Chromium can abort on crash six before the probe answers; persist recovery across that wait. - it('holds an unconfirmed safe-graphics marker on disk across the wait', async () => { - noteWindowsInstallDirAclProbePending() - await crashUpToThreshold() - const decisive = handleGpuChildCrash('crashed', null, 600) - expect(readGpuFallbackMarker(userData.path)?.userConfirmed).toBe(false) - reportProbePoisoned() - await decisive - expect(readGpuFallbackMarker(userData.path)?.userConfirmed).toBe(false) - }) - - // A pending repair without probe clock used to withdraw the marker inside Chromium's fatal window, causing endless hardware relaunches. - it('keeps the safe-graphics marker on disk while a repair is still in flight', async () => { - reportProbePoisoned() - await crashUpToThreshold() - await handleGpuChildCrash('crashed', null, 600) - - expect(showMessageBox).not.toHaveBeenCalled() - expect(readGpuFallbackMarker(userData.path)?.userConfirmed).toBe(false) - }) - - it('still withdraws the marker once the verdict is terminal rather than a pending repair', async () => { - await reportProbePoisonedWithSettledRepair(false) - await crashUpToThreshold() - await handleGpuChildCrash('crashed', null, 600) - - expect(showMessageBox).not.toHaveBeenCalled() - expect(readGpuFallbackMarker(userData.path)).toBeNull() - }) - - // A quit may begin during the verdict wait; do not answer it with a modal. - it('does not prompt when the user quits during the verdict wait', async () => { - noteWindowsInstallDirAclProbePending() - await crashUpToThreshold() - const decisive = handleGpuChildCrash('crashed', null, 600) - state.isQuitting = true - reportProbeClean() - await decisive - expect(showMessageBox).not.toHaveBeenCalled() - }) - - // Withholding consumes a latched threshold report; re-arm so a repaired tree can recover from later driver crashes. - it('can still engage a later burst after a withheld one, once the tree is repaired', async () => { - const repair = reportProbePoisoned() - await crashUpToThreshold() - await handleGpuChildCrash('crashed', null, 600) - expect(showMessageBox).not.toHaveBeenCalled() - - await repair.finishRepair() - expect(isInstallDirAclRepairPending()).toBe(false) - - for (let i = 1; i <= DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD; i += 1) { - await handleGpuChildCrash('crashed', null, 10_000 + i * 200) - } - expect(showMessageBox).toHaveBeenCalledTimes(1) - }) -}) - -// The pre-window gate may retire an earlier-read marker; asking afterward can permanently pin healthy hardware to software. -describe('presentGpuFallbackRecoveredLaunchPrompt vs a marker retired since it was read', () => { - const realPlatform = process.platform - const window = { isDestroyed: () => false } as unknown as Parameters< - typeof presentGpuFallbackRecoveredLaunchPrompt - >[0] - - beforeAll(() => { - Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) - }) - - afterAll(() => { - Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true }) - }) - - beforeEach(() => { - userData.path = mkdtempSync(join(tmpdir(), 'orca-acl-gpu-recovered-')) - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - showMessageBox.mockClear() - state.isQuitting = false - const info = { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false } - writeGpuFallbackMarker(userData.path, info, { - ...gpuFallbackEnvironment(), - platform: 'win32' - }) - state.activeGpuFallbackMarker = readGpuFallbackMarker(userData.path) as GpuFallbackMarker - }) - - it('stays silent once the install-DACL repair has cleared it', async () => { - await reportProbePoisonedWithSettledRepair(true, userData.path) - expect(readGpuFallbackMarker(userData.path)).toBeNull() - - await presentGpuFallbackRecoveredLaunchPrompt(window) - expect(showMessageBox).not.toHaveBeenCalled() - }) - - // Failed repair leaves a blank suspect window; default Keep would pin a marker no later repair may clear. - it('stays silent while the install DACL is still the suspect', async () => { - await reportProbePoisonedWithSettledRepair(false, userData.path) - expect(readGpuFallbackMarker(userData.path)).not.toBeNull() - - await presentGpuFallbackRecoveredLaunchPrompt(window) - expect(showMessageBox).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/startup/gpu-fallback-marker.test.ts b/src/main/startup/gpu-recovery/gpu-fallback-marker.test.ts similarity index 100% rename from src/main/startup/gpu-fallback-marker.test.ts rename to src/main/startup/gpu-recovery/gpu-fallback-marker.test.ts diff --git a/src/main/startup/gpu-fallback-marker.ts b/src/main/startup/gpu-recovery/gpu-fallback-marker.ts similarity index 100% rename from src/main/startup/gpu-fallback-marker.ts rename to src/main/startup/gpu-recovery/gpu-fallback-marker.ts diff --git a/src/main/startup/gpu-fallback-switches.ts b/src/main/startup/gpu-recovery/gpu-fallback-switches.ts similarity index 100% rename from src/main/startup/gpu-fallback-switches.ts rename to src/main/startup/gpu-recovery/gpu-fallback-switches.ts diff --git a/src/main/startup/gpu-recovery/gpu-lifecycle-install-dir-acl-guard.test.ts b/src/main/startup/gpu-recovery/gpu-lifecycle-install-dir-acl-guard.test.ts new file mode 100644 index 00000000000..753ec176d41 --- /dev/null +++ b/src/main/startup/gpu-recovery/gpu-lifecycle-install-dir-acl-guard.test.ts @@ -0,0 +1,180 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +// Any prompt is the signal; answer Keep Running to avoid relaunch. +const { showMessageBox, userData } = vi.hoisted(() => ({ + showMessageBox: vi.fn(async () => ({ response: 1 })), + userData: { path: '' } +})) + +vi.mock('electron', () => ({ + app: { + isPackaged: true, + getPath: () => userData.path, + getVersion: () => '1.4.184', + getGPUFeatureStatus: () => ({}), + setAboutPanelOptions: vi.fn(), + commandLine: { appendSwitch: vi.fn() }, + disableHardwareAcceleration: vi.fn(), + isReady: () => true, + exit: vi.fn(), + on: vi.fn(), + name: 'Orca' + }, + dialog: { showMessageBox } +})) + +import { grantsFrom } from '../windows-install-permissions/windows-install-dir-acl.test-fixture' +import { + DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD, + DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, + GpuCrashFallbackTracker +} from '../../crash-reporting/recovery/gpu-crash-fallback-decision' +import { readGpuFallbackMarker } from './gpu-fallback-marker' +import { handleGpuChildCrash } from './gpu-lifecycle' +import { mainProcessState as state } from '../main-process-state' +import '../windows-install-permissions/windows-install-dir-acl-poison-marker' +import { + isInstallDirAclRepairPending, + noteWindowsInstallDirAclProbePending, + resetWindowsInstallDirAclRecoveryForTest, + startWindowsInstallDirAclRepairIfPoisoned +} from '../windows-install-permissions/windows-install-dir-acl-recovery' +import { resetWindowsInstallDirAclRepairForTest } from '../windows-install-permissions/windows-install-dir-package-acl-repair' + +const INSTALL_DIR = 'C:\\Users\\neil\\AppData\\Local\\Programs\\orca' + +function recoveryOptions(userDataPath?: string): { + platform: 'win32' + installDir: string + appVersion: string + userDataPath: string + recordBreadcrumb: () => void +} { + return { + platform: 'win32', + installDir: INSTALL_DIR, + appVersion: '1.4.184', + userDataPath: userDataPath ?? mkdtempSync(join(tmpdir(), 'orca-acl-gpu-guard-')), + recordBreadcrumb: () => undefined + } +} + +/** Keep repair pending through GPU child deaths. */ +function reportProbePoisoned(): { finishRepair: () => Promise } { + let release = (): void => undefined + const walkingTheTree = new Promise((resolve) => { + release = resolve + }) + startWindowsInstallDirAclRepairIfPoisoned( + { status: 'ok', matchesPoisonSignature: true }, + { + ...recoveryOptions(), + grants: grantsFrom(async () => { + await walkingTheTree + return { ok: true, failedFileCount: 0 } + }) + } + ) + return { + finishRepair: async () => { + release() + for (let i = 0; i < 200 && isInstallDirAclRepairPending(); i += 1) { + await new Promise((resolve) => setTimeout(resolve, 5)) + } + } + } +} + +async function reportProbePoisonedWithSettledRepair( + granted: boolean, + userDataPath?: string +): Promise { + startWindowsInstallDirAclRepairIfPoisoned( + { status: 'ok', matchesPoisonSignature: true }, + { + ...recoveryOptions(userDataPath), + grants: grantsFrom(async () => + granted + ? { ok: true, failedFileCount: 0 } + : { ok: false, failedFileCount: 1, reason: 'access denied' } + ) + } + ) + for (let i = 0; i < 200 && isInstallDirAclRepairPending(); i += 1) { + await new Promise((resolve) => setTimeout(resolve, 5)) + } +} + +async function crashUpToThreshold(): Promise { + for (let i = 1; i < DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD; i += 1) { + await handleGpuChildCrash('crashed', null, i * 200) + } +} + +/** Exercise the real tracker: source matching cannot prove driver bursts survive either ACL verdict. */ +describe('handleGpuChildCrash vs the install-dir ACL verdict', () => { + let tracker: GpuCrashFallbackTracker + const realPlatform = process.platform + + beforeAll(() => { + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) + }) + + afterAll(() => { + Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true }) + }) + + beforeEach(() => { + userData.path = mkdtempSync(join(tmpdir(), 'orca-acl-gpu-userdata-')) + resetWindowsInstallDirAclRepairForTest() + resetWindowsInstallDirAclRecoveryForTest() + showMessageBox.mockClear() + state.isQuitting = false + state.isServeMode = false + state.gpuFallbackActiveThisLaunch = false + tracker = new GpuCrashFallbackTracker({ + windowMs: DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, + threshold: DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD + }) + state.gpuCrashFallbackTracker = tracker + }) + + // Chromium can abort on crash six before the probe answers; persist recovery across that wait. + it('holds an unconfirmed safe-graphics marker on disk across the wait', async () => { + noteWindowsInstallDirAclProbePending() + await crashUpToThreshold() + const decisive = handleGpuChildCrash('crashed', null, 600) + expect(readGpuFallbackMarker(userData.path)?.userConfirmed).toBe(false) + reportProbePoisoned() + await decisive + expect(readGpuFallbackMarker(userData.path)?.userConfirmed).toBe(false) + }) + + // A pending repair without probe clock used to withdraw the marker inside Chromium's fatal window, causing endless hardware relaunches. + it('keeps the safe-graphics marker on disk while a repair is still in flight', async () => { + reportProbePoisoned() + await crashUpToThreshold() + await handleGpuChildCrash('crashed', null, 600) + + expect(showMessageBox).not.toHaveBeenCalled() + expect(readGpuFallbackMarker(userData.path)?.userConfirmed).toBe(false) + }) + + it('still withdraws the marker once the verdict is terminal rather than a pending repair', async () => { + await reportProbePoisonedWithSettledRepair(false) + await crashUpToThreshold() + await handleGpuChildCrash('crashed', null, 600) + + expect(showMessageBox).not.toHaveBeenCalled() + expect(readGpuFallbackMarker(userData.path)).toBeNull() + }) + + // A quit may begin during the verdict wait; do not answer it with a modal. + + // Withholding consumes a latched threshold report; re-arm so a repaired tree can recover from later driver crashes. +}) + +// The pre-window gate may retire an earlier-read marker; asking afterward can permanently pin healthy hardware to software. diff --git a/src/main/startup/gpu-lifecycle.ts b/src/main/startup/gpu-recovery/gpu-lifecycle.ts similarity index 90% rename from src/main/startup/gpu-lifecycle.ts rename to src/main/startup/gpu-recovery/gpu-lifecycle.ts index db00f19a618..893b337b4da 100644 --- a/src/main/startup/gpu-lifecycle.ts +++ b/src/main/startup/gpu-recovery/gpu-lifecycle.ts @@ -1,6 +1,6 @@ import { app, type BrowserWindow } from 'electron' -import { relaunchApp } from './quit/app-relaunch' -import { destroySystemTray } from '../tray/system-tray' +import { relaunchApp } from '../quit/app-relaunch' +import { destroySystemTray } from '../../tray/system-tray' import { applyGpuFallbackCommandLineSwitches } from './gpu-fallback-switches' import { clearGpuFallbackMarker, @@ -11,20 +11,20 @@ import { import { handleGpuFallbackRecoveredLaunch, promptForGpuFallbackRecoveredLaunch -} from '../crash-reporting/recovery/gpu-fallback-recovered-launch' -import { promptForGpuFallbackRestart } from '../crash-reporting/recovery/gpu-fallback-restart-prompt' -import { engageGpuFallbackAfterCrashBurst } from '../crash-reporting/recovery/gpu-fallback-engagement' -import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { GpuCrashDiagnosticsRecorder } from '../crash-reporting/capture/gpu-crash-diagnostics' +} from '../../crash-reporting/recovery/gpu-fallback-recovered-launch' +import { promptForGpuFallbackRestart } from '../../crash-reporting/recovery/gpu-fallback-restart-prompt' +import { engageGpuFallbackAfterCrashBurst } from '../../crash-reporting/recovery/gpu-fallback-engagement' +import { recordCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { GpuCrashDiagnosticsRecorder } from '../../crash-reporting/capture/gpu-crash-diagnostics' import { isInstallDirAclRepairExhausted, isInstallDirAclRepairPending, isInstallDirAclSuspect, waitForInstallDirAclVerdict -} from './windows-install-dir-acl-recovery' -import { mainProcessState as state, gpuFallbackEnvironment } from './main-process-state' -import { createGpuAccelerationAboutPanelOptions } from '../menu/gpu-acceleration-about-panel' +} from '../windows-install-permissions/windows-install-dir-acl-recovery' +import { mainProcessState as state, gpuFallbackEnvironment } from '../main-process-state' +import { createGpuAccelerationAboutPanelOptions } from '../../menu/gpu-acceleration-about-panel' export function createGpuCrashDiagnosticsRecorder(): GpuCrashDiagnosticsRecorder | null { if (process.platform !== 'win32') { diff --git a/src/main/startup/headless-serve-ssh-registration.ts b/src/main/startup/headless-serve-ssh-registration.ts deleted file mode 100644 index 41f0b4f7395..00000000000 --- a/src/main/startup/headless-serve-ssh-registration.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { registerSshHandlers } from '../ipc/ssh/ssh' -import { mainProcessState as state } from './main-process-state' - -/** Register SSH before any window so headless serve can list/connect targets (#25886, #8489); later window registration is idempotent. */ -export function registerHeadlessServeSshHandlers(store: Store, runtime: OrcaRuntimeService): void { - registerSshHandlers(store, () => state.mainWindow ?? null, runtime) -} diff --git a/src/main/startup/headless-serve-x11-reexec.test.ts b/src/main/startup/headless-serve-x11-reexec.test.ts deleted file mode 100644 index dc538cd1dc0..00000000000 --- a/src/main/startup/headless-serve-x11-reexec.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { reexecHeadlessServeOnX11IfNeeded } from './headless-serve-x11-reexec' - -vi.mock('electron', () => ({ app: { commandLine: { getSwitchValue: () => 'wayland' } } })) - -const EXEC_PATH = '/opt/Orca/orca-ide' - -describe('reexecHeadlessServeOnX11IfNeeded', () => { - afterEach(() => { - vi.restoreAllMocks() - }) - - it('keeps the pid, env and argv order, with the switch ahead of a `--` terminator', () => { - const execve = vi.fn() - const env = { XDG_SESSION_TYPE: 'wayland', HOME: '/home/orca' } - reexecHeadlessServeOnX11IfNeeded({ - isServeMode: true, - readResolvedOzonePlatform: () => 'wayland', - argv: [EXEC_PATH, '--serve', '--', '--ozone-platform=wayland'], - platform: 'linux', - execPath: EXEC_PATH, - env, - execve - }) - expect(execve).toHaveBeenCalledWith( - EXEC_PATH, - [EXEC_PATH, '--ozone-platform=x11', '--serve', '--', '--ozone-platform=wayland'], - env - ) - }) -}) diff --git a/src/main/startup/legacy-worker-renderer-recovery.test.ts b/src/main/startup/legacy-worker-renderer-recovery.test.ts deleted file mode 100644 index 737ebb0eabd..00000000000 --- a/src/main/startup/legacy-worker-renderer-recovery.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { recoverLegacyWorkerTerminalsForRendererStartup } from './legacy-worker-renderer-recovery' -import { - FIRST_WINDOW_STARTUP_SERVICE_TIMEOUT_MS, - LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS, - startFirstWindowStartupServices -} from './first-window-startup-services' - -describe('legacy worker renderer recovery', () => { - it('waits for daemon adoption before renderer recovery can continue', async () => { - let resolveFirstWindow!: () => void - let resolveWslBarrier!: () => void - let resolveProvider!: () => void - const firstWindowReady = new Promise((resolve) => { - resolveFirstWindow = resolve - }) - const wslBarrierReady = new Promise((resolve) => { - resolveWslBarrier = resolve - }) - const providerReady = new Promise((resolve) => { - resolveProvider = resolve - }) - const reconcile = vi.fn().mockResolvedValue(undefined) - const startup = recoverLegacyWorkerTerminalsForRendererStartup({ - firstWindowStartupServicesReady: firstWindowReady, - managedWslCliStartupBarrierReady: wslBarrierReady, - localPtyProviderStartupReady: providerReady, - reconcile, - onDeferredRecoveryError: vi.fn() - }) - - resolveFirstWindow() - await Promise.resolve() - expect(reconcile).not.toHaveBeenCalled() - - resolveWslBarrier() - await Promise.resolve() - expect(reconcile).not.toHaveBeenCalled() - - resolveProvider() - await startup - expect(reconcile).toHaveBeenCalledOnce() - }) - - it('contains provider startup rejection after initial recovery', async () => { - const providerError = new Error('provider failed') - const reconcile = vi.fn().mockResolvedValue(undefined) - let reportError!: (error: unknown) => void - const reportedError = new Promise((resolve) => { - reportError = resolve - }) - - await recoverLegacyWorkerTerminalsForRendererStartup({ - firstWindowStartupServicesReady: Promise.resolve(), - managedWslCliStartupBarrierReady: Promise.resolve(), - localPtyProviderStartupReady: Promise.reject(providerError), - reconcile, - onDeferredRecoveryError: reportError - }) - - await expect(reportedError).resolves.toBe(providerError) - expect(reconcile).not.toHaveBeenCalled() - }) - - it('contains recovery rejection', async () => { - const recoveryError = new Error('recovery failed') - const reconcile = vi.fn().mockRejectedValueOnce(recoveryError) - let reportError!: (error: unknown) => void - const reportedError = new Promise((resolve) => { - reportError = resolve - }) - - await recoverLegacyWorkerTerminalsForRendererStartup({ - firstWindowStartupServicesReady: Promise.resolve(), - managedWslCliStartupBarrierReady: Promise.resolve(), - localPtyProviderStartupReady: Promise.resolve(), - reconcile, - onDeferredRecoveryError: reportError - }) - - await expect(reportedError).resolves.toBe(recoveryError) - expect(reconcile).toHaveBeenCalledOnce() - }) - - it('fails open at the hard cap without allowing a premature recovery', async () => { - vi.useFakeTimers() - let daemonSignal: AbortSignal | undefined - try { - const services = startFirstWindowStartupServices({ - startDaemonPtyProvider: (signal) => { - daemonSignal = signal - return new Promise(() => {}) - }, - startAgentHookServer: () => Promise.resolve(), - onDaemonError: vi.fn(), - onAgentHookServerError: vi.fn() - }) - const reconcile = vi.fn().mockResolvedValue(undefined) - const startup = recoverLegacyWorkerTerminalsForRendererStartup({ - firstWindowStartupServicesReady: services.firstWindowReady, - managedWslCliStartupBarrierReady: Promise.resolve(), - localPtyProviderStartupReady: services.localPtyProviderReady, - reconcile, - onDeferredRecoveryError: vi.fn() - }) - - await vi.advanceTimersByTimeAsync(FIRST_WINDOW_STARTUP_SERVICE_TIMEOUT_MS) - expect(reconcile).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync( - LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS - FIRST_WINDOW_STARTUP_SERVICE_TIMEOUT_MS - ) - await startup - expect(reconcile).toHaveBeenCalledOnce() - expect(daemonSignal?.aborted).toBe(true) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/startup/ensure-virtual-display.ts b/src/main/startup/linux-display/ensure-virtual-display.ts similarity index 100% rename from src/main/startup/ensure-virtual-display.ts rename to src/main/startup/linux-display/ensure-virtual-display.ts diff --git a/src/main/startup/x-display-artifacts.ts b/src/main/startup/linux-display/x-display-artifacts.ts similarity index 100% rename from src/main/startup/x-display-artifacts.ts rename to src/main/startup/linux-display/x-display-artifacts.ts diff --git a/src/main/startup/linux-dev-shm-policy.ts b/src/main/startup/linux-runtime/linux-dev-shm-policy.ts similarity index 94% rename from src/main/startup/linux-dev-shm-policy.ts rename to src/main/startup/linux-runtime/linux-dev-shm-policy.ts index da3356395a7..a6877378de5 100644 --- a/src/main/startup/linux-dev-shm-policy.ts +++ b/src/main/startup/linux-runtime/linux-dev-shm-policy.ts @@ -1,6 +1,6 @@ import { statfsSync } from 'node:fs' import { app } from 'electron' -import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' const DEV_SHM_PATH = '/dev/shm' const DEV_SHM_OVERRIDE_ENV_VAR = 'ORCA_DEV_SHM' diff --git a/src/main/startup/linux-keyring-backend-selection.test.ts b/src/main/startup/linux-runtime/linux-keyring-backend-selection.test.ts similarity index 90% rename from src/main/startup/linux-keyring-backend-selection.test.ts rename to src/main/startup/linux-runtime/linux-keyring-backend-selection.test.ts index 8370626639c..fd7f63595b4 100644 --- a/src/main/startup/linux-keyring-backend-selection.test.ts +++ b/src/main/startup/linux-runtime/linux-keyring-backend-selection.test.ts @@ -108,14 +108,4 @@ describe('resolveLinuxPasswordStore', () => { expect(decision.store).toBeNull() expect(probeCollection).not.toHaveBeenCalled() }) - - it('treats an empty session bus address as no session bus', () => { - const probeCollection = vi.fn((): SecretServiceCollectionState => 'unlocked') - resolveLinuxPasswordStore({ - env: { XDG_CURRENT_DESKTOP: 'Hyprland', DBUS_SESSION_BUS_ADDRESS: ' ' }, - passwordStoreAlreadySelected: false, - probeCollection - }) - expect(probeCollection).not.toHaveBeenCalled() - }) }) diff --git a/src/main/startup/linux-keyring-backend-selection.ts b/src/main/startup/linux-runtime/linux-keyring-backend-selection.ts similarity index 100% rename from src/main/startup/linux-keyring-backend-selection.ts rename to src/main/startup/linux-runtime/linux-keyring-backend-selection.ts diff --git a/src/main/startup/linux-realtime-scheduling-guard.ts b/src/main/startup/linux-runtime/linux-realtime-scheduling-guard.ts similarity index 97% rename from src/main/startup/linux-realtime-scheduling-guard.ts rename to src/main/startup/linux-runtime/linux-realtime-scheduling-guard.ts index f21f480878d..46266cbb27b 100644 --- a/src/main/startup/linux-realtime-scheduling-guard.ts +++ b/src/main/startup/linux-runtime/linux-realtime-scheduling-guard.ts @@ -1,6 +1,6 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { runProcess } from '@orca/process-host' -import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { allowsRealtimePriority, readZeroRtTimeLimit, diff --git a/src/main/startup/linux-rttime-limit.test.ts b/src/main/startup/linux-runtime/linux-rttime-limit.test.ts similarity index 100% rename from src/main/startup/linux-rttime-limit.test.ts rename to src/main/startup/linux-runtime/linux-rttime-limit.test.ts diff --git a/src/main/startup/linux-rttime-limit.ts b/src/main/startup/linux-runtime/linux-rttime-limit.ts similarity index 100% rename from src/main/startup/linux-rttime-limit.ts rename to src/main/startup/linux-runtime/linux-rttime-limit.ts diff --git a/src/main/startup/linux-secret-service-probe.ts b/src/main/startup/linux-runtime/linux-secret-service-probe.ts similarity index 100% rename from src/main/startup/linux-secret-service-probe.ts rename to src/main/startup/linux-runtime/linux-secret-service-probe.ts diff --git a/src/main/startup/select-linux-keyring-backend.ts b/src/main/startup/linux-runtime/select-linux-keyring-backend.ts similarity index 100% rename from src/main/startup/select-linux-keyring-backend.ts rename to src/main/startup/linux-runtime/select-linux-keyring-backend.ts diff --git a/src/main/startup/main-process-account-services.ts b/src/main/startup/main-process-account-services.ts deleted file mode 100644 index 399359df921..00000000000 --- a/src/main/startup/main-process-account-services.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { app } from 'electron' -import { KeybindingService } from '../keybindings/keybinding-service' -import { createProviderAccountServices } from '../providers/accounts/provider-account-services' -import { createCodexSessionMigrationScheduler } from '../codex/history/backfill/codex-session-migration-scheduler' -import { startCodexSessionBackfillInBackground } from '../codex/history/backfill/codex-session-backfill' -import { startCodexSessionIndexHealInBackground } from '../codex/history/index/codex-session-index-heal' -import { startCodexStateDbBackfillRecoveryInBackground } from '../codex/history/index/codex-state-db-backfill-recovery' -import { getOrcaManagedCodexHomePath } from '../codex/configuration/homes/codex-home-paths' -import { - hasOpenCodeGoApiKey, - readOpenCodeGoApiKey, - saveOpenCodeGoApiKey -} from '../opencode/accounts/opencode-go-api-key-store' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' -import { prewarmStructuredAgentModelCatalogs } from '../runtime/agent-session/model-catalog/structured-agent-model-catalog-wiring' -import { mainProcessState as state } from './main-process-state' - -// Settings that change which account or binary a new chat's agent runs under. -const MODEL_CATALOG_ACCOUNT_SETTINGS = [ - 'activeCodexManagedAccountId', - 'activeCodexManagedAccountIdsByRuntime', - 'codexManagedAccounts', - 'activeClaudeManagedAccountId', - 'activeClaudeManagedAccountIdsByRuntime', - 'claudeManagedAccounts', - 'agentDefaultEnv', - 'agentCmdOverrides' -] as const - -export function initializeMainProcessAccountServices(): void { - const store = state.store - if (!store || !state.claudeUsage || !state.codexUsage) { - throw new Error('Usage stores must be initialized before account services') - } - state.codexSessionMigration = createCodexSessionMigrationScheduler({ - isEligible: () => - state.codexRuntimeHome?.isHostSystemDefaultSessionMigrationEligible() === true, - isQuitting: () => state.isQuitting, - resolveSystemCodexHomePathOverride: () => - resolveHostCodexSessionSourceHome(store.getSettings()), - prepareScheduledRun: (scanDates) => - state.codexRuntimeHome?.prepareHostSystemDefaultSessionMigrationPass(scanDates), - finishScheduledRun: () => state.codexRuntimeHome?.finishHostSystemDefaultSessionMigrationPass(), - startBackfill: startCodexSessionBackfillInBackground, - startIndexHeal: startCodexSessionIndexHealInBackground - }) - const services = createProviderAccountServices(store, { - codexAccountLifecycle: { onHostSystemDefaultSelected: state.codexSessionMigration.requestRun }, - setClaudeStatusLineListener: (listener) => agentHookServer.setClaudeStatusLineListener(listener) - }) - state.rateLimits = services.rateLimits - state.codexRuntimeHome = services.codexRuntimeHome - state.codexAccounts = services.codexAccounts - state.claudeRuntimeAuth = services.claudeRuntimeAuth - state.claudeAccounts = services.claudeAccounts - void startCodexStateDbBackfillRecoveryInBackground(getOrcaManagedCodexHomePath()) - // Defer shared-home migration; compatibility launches re-arm non-destructive scans for new rollouts (#4444, #8612, #12480). - state.codexSessionMigration.scheduleInitialRun() - store.onSettingsChanged((updates) => { - // An account switch would otherwise leave the next chat's picker on a cold catalog. - if (MODEL_CATALOG_ACCOUNT_SETTINGS.some((key) => key in updates)) { - prewarmStructuredAgentModelCatalogs() - } - }) - store.migrateLegacyOpenCodeGoApiKey({ - has: hasOpenCodeGoApiKey, - read: readOpenCodeGoApiKey, - save: saveOpenCodeGoApiKey - }) - state.keybindings = new KeybindingService({ - homePath: app.getPath('home'), - getLegacyOverrides: () => store.getSettings().keybindings, - legacyTabSwitchDefaults: store.getSettings().tabSwitchKeybindingSeed === 'legacy', - legacySearchDefaults: - (process.platform === 'darwin' - ? store.getSettings().searchKeybindingSeed - : store.getSettings().nonMacSearchKeybindingSeed) === 'legacy' - }) - browserManager.setSettingsResolver(() => ({ keybindings: state.keybindings?.getOverrides() })) -} diff --git a/src/main/startup/main-process-automations.ts b/src/main/startup/main-process-automations.ts deleted file mode 100644 index e17222404c2..00000000000 --- a/src/main/startup/main-process-automations.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { AutomationService } from '../automations/service' -import { createRuntimeAutomationService } from '../automations/runtime-automation-service' -import { mainProcessState as state } from './main-process-state' - -export function initializeMainProcessAutomations(): AutomationService { - const store = state.store - const runtime = state.runtime - const claudeUsage = state.claudeUsage - const codexUsage = state.codexUsage - if (!store || !runtime || !claudeUsage || !codexUsage) { - throw new Error('Runtime and usage stores must be initialized before automations') - } - const service = createRuntimeAutomationService({ - store, - runtime, - claudeUsage, - codexUsage, - // Remote clients mirror schedules; only server processes execute remote_host_service ownership. - allowRemoteHostScheduling: state.isServeMode - }) - state.automations = service - return service -} diff --git a/src/main/startup/main-process-connector-startup.ts b/src/main/startup/main-process-connector-startup.ts deleted file mode 100644 index a2a94473576..00000000000 --- a/src/main/startup/main-process-connector-startup.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { ConnectorCloud } from '../connector-cloud/connector-cloud' -import { createDesktopConnectorCloud } from '../connector-cloud/connector-cloud-install' -import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' -import { mainProcessState as state } from './main-process-state' - -// Desktop only: the connector acts as the signed-in Orca account, which `orca serve` does not have yet. -// Created before the window exists, so its sign-in and sign-out hooks always find it. -export function installDesktopConnectorCloud(): void { - if (!state.runtime || !state.store) { - return - } - state.runtime.setConnectorCloud( - createDesktopConnectorCloud( - state.runtime, - state.store, - getProfileUserDataPath(), - () => state.isQuitting - ) - ) -} - -/** The desktop's connector, for the startup, auth and quit hooks. */ -export function desktopConnectorCloud(): ConnectorCloud | null { - return state.runtime?.getConnectorCloud() ?? null -} - -// Registered with the relay; like it, the first request waits for the persisted proxy. -export function connectDesktopConnectorCloud(): void { - void state.initialProxyApplicationReady.then(() => desktopConnectorCloud()?.connect()) -} diff --git a/src/main/startup/main-process-ipc-bootstrap.ts b/src/main/startup/main-process-ipc-bootstrap.ts index e987aa33936..02d8e943408 100644 --- a/src/main/startup/main-process-ipc-bootstrap.ts +++ b/src/main/startup/main-process-ipc-bootstrap.ts @@ -1,14 +1,14 @@ import { ipcMain } from 'electron' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { placeUnshownLiveTerminalsBestEffort } from '../runtime/terminal/adoption/unshown-live-terminal-placement' -import { recoverLegacyWorkerTerminalsForRendererStartup } from './legacy-worker-renderer-recovery' -import { logStartupMilestone } from './startup-diagnostics' +import { recoverLegacyWorkerTerminalsForRendererStartup } from './pty-startup/legacy-worker-renderer-recovery' +import { logStartupMilestone } from './diagnostics/startup-diagnostics' import { mainProcessState as state } from './main-process-state' import { consumeQuitAndStopAllSessionsRequest, quitAfterRendererStoppedAllSessions -} from './main-window-actions' -import { resolveOsOpenedDocuments } from './os-opened-documents' +} from './main-window/main-window-actions' +import { resolveOsOpenedDocuments } from './open-routing/os-opened-documents' import { onStructuredAgentSessionsHeldChanged, structuredAgentSessionsHeld diff --git a/src/main/startup/main-process-observers.ts b/src/main/startup/main-process-observers.ts index a4a94d511fa..9ed997eaff7 100644 --- a/src/main/startup/main-process-observers.ts +++ b/src/main/startup/main-process-observers.ts @@ -25,7 +25,7 @@ import { UsageWorktreeHistory } from '../usage/worktree-attribution/usage-worktr import { feedAgentSessionStats } from '../stats/agent-session-stats-feed' import { installRepoMaintenanceIdleGate } from '../workspaces/catalog/repo-maintenance-idle-gate' import { mainProcessState as state } from './main-process-state' -import { runAfterFirstWindowShown } from './first-window-deferral' +import { runAfterFirstWindowShown } from './main-window/first-window-deferral' const TELEMETRY_CLIENT_START_FALLBACK_MS = 15_000 diff --git a/src/main/startup/main-process-plugin-rpc.ts b/src/main/startup/main-process-plugin-rpc.ts deleted file mode 100644 index efe605ae1a3..00000000000 --- a/src/main/startup/main-process-plugin-rpc.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import { applyPluginConsent, applyPluginEnablement } from '../plugins/plugin-enablement' -import type { PluginService } from '../plugins/plugin-service' -import type { PluginCliCatalogs } from '../plugins/plugin-cli-catalog-candidates' -import { clearPluginFrameStorage } from '../plugins/panels/guest-isolation/plugin-frame-guest-sessions' -import { openPluginFrameGuestDevTools } from '../plugins/panels/guest-isolation/plugin-frame-guest-diagnostics' -import { setPluginServiceForRpc } from '../runtime/rpc/methods/plugins/plugins' -import { setPluginInstallServicesForRpc } from '../runtime/rpc/methods/plugins/plugin-install-methods' - -/** Headless RPC resolves these too; consent shares the desktop hash-keyed write path. */ -export function bindPluginRpcServices( - store: Store, - pluginService: PluginService, - catalogs: PluginCliCatalogs -): void { - setPluginServiceForRpc(pluginService, { - applyConsent: (request) => applyPluginConsent({ store, pluginService, ...request }), - applyEnablement: (pluginKey, enabled) => - applyPluginEnablement({ store, pluginService, pluginKey, enabled }), - setPluginSystemEnabled: (pluginSystemEnabled) => - store.updateSettings({ pluginSystemEnabled }, { notifyListeners: true }), - setDevPluginPaths: (devPluginPaths) => - store.updateSettings({ devPluginPaths }, { notifyListeners: true }), - openFrameDevTools: openPluginFrameGuestDevTools - }) - setPluginInstallServicesForRpc({ - pluginService, - catalogs, - applyConsent: (request) => applyPluginConsent({ store, pluginService, ...request }), - store, - afterUninstall: clearPluginFrameStorage - }) -} diff --git a/src/main/startup/main-process-preflight-failure.ts b/src/main/startup/main-process-preflight-failure.ts index 5ac4ff30e66..66462e23346 100644 --- a/src/main/startup/main-process-preflight-failure.ts +++ b/src/main/startup/main-process-preflight-failure.ts @@ -1,10 +1,10 @@ import { app, dialog } from 'electron' import { prepareEarlyMainUiLanguage, translateMain } from '../i18n/main-i18n' import { formatProfileStateStartupFailure } from '../persistence/profile-state/startup/profile-state-startup-failure' -import { isBackgroundLaunch } from '../window/foreground-activation-policy' +import { isBackgroundLaunch } from '../window/activation/foreground-activation-policy' import { mainProcessState as state } from './main-process-state' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from './single-instance-lock' -import { acquireDesktopProfileInstanceLock } from './desktop-profile-instance-lock' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' +import { acquireDesktopProfileInstanceLock } from './profile-startup/desktop-profile-instance-lock' /** False when orcad holds the profile; unlike a second desktop, nothing else would say why. */ export function acquireDesktopProfileLockOrExplain(userDataPath: string): boolean { diff --git a/src/main/startup/main-process-preflight.ts b/src/main/startup/main-process-preflight.ts index a1ecab2621b..090ef91e592 100644 --- a/src/main/startup/main-process-preflight.ts +++ b/src/main/startup/main-process-preflight.ts @@ -4,9 +4,9 @@ import { getRelocatedDaemonHost } from '../daemon/executable-host/windows/daemon import { app, ipcMain, powerMonitor, session } from 'electron' import os from 'node:os' import { join } from 'node:path' -import { maybeRedirectCliLaunch } from './cli-launch-redirect' -import { runProfileStateRecoveryPreflight } from './profile-state-recovery-preflight' -import { argvRequestsServeMode, normalizeServeModeArgv } from './serve-mode-argv' +import { maybeRedirectCliLaunch } from './cli-launch/cli-launch-redirect' +import { runProfileStateRecoveryPreflight } from './profile-startup/profile-state-recovery-preflight' +import { argvRequestsServeMode, normalizeServeModeArgv } from './serve-launch/serve-mode-argv' import { configureDevUserDataPath, configureElectronNetworkCompatibility, @@ -23,8 +23,8 @@ import { installServeSupervisorDisconnectQuit } from '../updater/serve-update-ha import { installUncaughtPipeErrorGuard, installUnhandledRejectionLogging -} from './main-process-error-guards' -import { hydrateShellPath, mergePathSegments } from './hydrate-shell-path' +} from './process-failure/main-process-error-guards' +import { hydrateShellPath, mergePathSegments } from './shell-environment/hydrate-shell-path' import { configureRemoteServerUpdater } from '../runtime/hosts/management/remote-server-updater' import { getRemoteServerUpdaterSnapshot, @@ -33,11 +33,17 @@ import { installRemoteServerUpdate, isQuittingForUpdate } from '../updater/updater-service' -import { getDevInstanceIdentity, shouldApplyPreReadyAppName } from './dev-instance-identity' -import { enableRendererHeapHeadroom } from './renderer-heap-headroom' -import { configureLinuxDevShmUsage } from './linux-dev-shm-policy' -import { isStartupDiagnosticsEnabled, logStartupDiagnostic } from './startup-diagnostics' -import { startEventLoopStallProbe } from './event-loop-stall-probe' +import { + getDevInstanceIdentity, + shouldApplyPreReadyAppName +} from './profile-startup/dev-instance-identity' +import { enableRendererHeapHeadroom } from './chromium-policy/renderer-heap-headroom' +import { configureLinuxDevShmUsage } from './linux-runtime/linux-dev-shm-policy' +import { + isStartupDiagnosticsEnabled, + logStartupDiagnostic +} from './diagnostics/startup-diagnostics' +import { startEventLoopStallProbe } from './diagnostics/event-loop-stall-probe' import { startEventLoopDelayProbe } from '../diagnostics/event-loop-delay-probe' import { isMainThreadDiagnosticsEnabled, @@ -47,21 +53,21 @@ import { import { setSpawnObserver } from '@orca/process-host/spawn-observer' import { settledDiffCache } from '../git/source-control/git-read-cache-invalidation' import { reserveServeStdoutForReadiness } from '../server/serve-stdout-boundary' -import { createServeDesktopActivationGate } from './serve-desktop-activation' +import { createServeDesktopActivationGate } from './serve-launch/serve-desktop-activation' import { shouldBypassSingleInstanceLock, shouldSkipSingleInstanceLock, acquireSingleInstanceLock, logSingleInstanceLockBypass, - logSingleInstanceLockFailure, - SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE -} from './single-instance-lock' + logSingleInstanceLockFailure +} from './profile-startup/single-instance-lock' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' import { setAppEnvironment } from '../../shared/app-environment' import { ElectronAppEnvironment } from '../host/electron-app-environment' import { installMainProcessTreeKillGate } from '../pty/process-retirement/own-chromium-tree-kill-guard' import { setSecretStore } from '../../shared/secret-store' import { ElectronSecretStore } from '../host/electron-secret-store' -import { selectLinuxKeyringBackend } from './select-linux-keyring-backend' +import { selectLinuxKeyringBackend } from './linux-runtime/select-linux-keyring-backend' import { setPtyHostBindings } from '../ipc/pty/pty-host-bindings' import { electronRuntimeDesktopSurface } from '../host/electron-runtime-desktop-surface' import { setRuntimeDesktopSurface } from '../runtime/construction/runtime-desktop-surface' @@ -82,7 +88,7 @@ import { getProfileUserDataPath, initOrcaProfilePaths } from '../orca-profiles/p import { recoverPendingProfileProjectMoves } from '../orca-profiles/project-transfer/profile-project-move-intent' import { initStatsPath } from '../stats/collector' import { registerDocPreviewSchemePrivileges } from '../browser/document-preview/doc-preview-protocol' -import { PRIVILEGED_CUSTOM_SCHEMES } from './privileged-custom-schemes' +import { PRIVILEGED_CUSTOM_SCHEMES } from './chromium-policy/privileged-custom-schemes' import { startCrashpadCapture } from '../crash-reporting/capture/crashpad-capture' import { CrashReportStore } from '../crash-reporting/reports/crash-report-store' import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' @@ -91,14 +97,14 @@ import { ensureVirtualDisplayForHeadlessServe, hasUsableLinuxDisplay, missingLinuxDisplayMessage -} from './ensure-virtual-display' +} from './linux-display/ensure-virtual-display' import { createGpuCrashDiagnosticsRecorder, maybeApplyGpuFallbackForThisLaunch, registerGpuLifecycleHandlers -} from './gpu-lifecycle' +} from './gpu-recovery/gpu-lifecycle' import { mainProcessState as state } from './main-process-state' -import { initializeSyntheticTitleRuntime } from './synthetic-title-runtime' +import { initializeSyntheticTitleRuntime } from './main-window/synthetic-title-runtime' import { initializeBrowserProcessUserAgent } from '../browser/identity/browser-process-user-agent' import { initializeBrowserIdentityModeStore } from '../browser/identity/mode/browser-identity-mode-store' import { acquireProfileStateRuntimeAdmission } from '../persistence/profile-state/access/profile-state-access' @@ -107,7 +113,7 @@ import { acquireDesktopProfileLockOrExplain, handleMainProcessPreflightFailure } from './main-process-preflight-failure' -import { ensureWindowsAppDataPath } from './windows-app-data-path' +import { ensureWindowsAppDataPath } from './windows-startup/windows-app-data-path' export type MainProcessPreflightOptions = { focusExistingWindow: () => void diff --git a/src/main/startup/main-process-push-startup.ts b/src/main/startup/main-process-push-startup.ts deleted file mode 100644 index 7ad0653356d..00000000000 --- a/src/main/startup/main-process-push-startup.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { getOrcaPushGatewayUrl } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' -import { DesktopPushService } from '../runtime/push/desktop-push-service' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' -import { mainProcessState as state } from './main-process-state' - -// Push authenticates by host keypair, so accountless hosts must register phones too; shared startup state supplies the runtime in both modes. -export function startDesktopPushService(runtimeRpc: OrcaRuntimeRpcServer): void { - const runtime: OrcaRuntimeService | null = state.runtime - if (!runtime) { - console.warn('[push] Background push startup skipped: runtime not started') - return - } - try { - const pushService = DesktopPushService.create({ - runtime, - runtimeRpc, - gatewayUrl: getOrcaPushGatewayUrl() - }) - pushService?.start() - state.desktopPushService = pushService - } catch (error) { - console.warn( - '[push] Background push startup unavailable:', - error instanceof Error ? error.message : String(error) - ) - } -} diff --git a/src/main/startup/main-process-quit-pending-writer.test.ts b/src/main/startup/main-process-quit-pending-writer.test.ts deleted file mode 100644 index 95451a1393b..00000000000 --- a/src/main/startup/main-process-quit-pending-writer.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, expect, it, vi } from 'vitest' -import { WILL_QUIT_TEARDOWN_DEADLINE_MS } from '../../shared/quit-teardown-deadline' - -const settled = () => vi.fn(async () => {}) -const idle = () => vi.fn() -const stopAgentHookServer = idle() -const stopStructuredAgentSessionRuntime = settled() -const beginSshShutdown = settled() -const killAllPty = idle() -/** Final-save calls seen by the first microtask after the SSH shutdown began. */ -let flushesByNextMicrotask = -1 - -// Every teardown member settles except the profile store, so only the writer can hold quit. -const dependencies: Record> = { - '../ipc/filesystem-watcher': { closeAllWatchers: settled() }, - '../ipc/worktree-base-directory-watcher': { disposeWorktreeBaseDirectoryWatchers: settled() }, - '../ipc/folder-repo-git-upgrade': { stopFolderRepoGitUpgradeWatch: idle() }, - '../ipc/pty/kill-all': { killAllPty }, - '../daemon/providers/lifecycle/daemon-provider-state': { - disconnectDaemon: settled(), - shutdownDaemon: settled() - }, - '../ipc/ssh/ssh-shutdown-drain': { beginSshShutdown }, - './main-process-connector-startup': { desktopConnectorCloud: () => null }, - '../agent-hooks/server/agent-hook-server': { agentHookServer: { stop: stopAgentHookServer } }, - '../agent-hooks/wsl-relay/wsl-hook-relay-manager': { - wslHookRelayManager: { disposeAll: idle() } - }, - '../agent-hooks/installation/managed-agent-hook-controls': { - removeManagedAgentHooksAsync: vi.fn(async () => []) - }, - '../runtime/agent-session/structured-agent-session-runtime': { - stopStructuredAgentSessionRuntime - }, - '../runtime/agent-session/structured-agent-session-runtime-teardown': { - setStructuredAgentSessionTeardownTrigger: idle() - }, - '../runtime/files/watch/file-watcher-leases': { awaitRuntimeFileWatcherUnsubscribes: settled() }, - '../runtime/rpc/server/runtime-metadata': { clearRuntimeMetadataIfOwned: idle() }, - '../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime': { - shutdownPairedRuntimeBrowserClientHosts: settled() - }, - '../ipc/browser/desktop-browser-bridge-wiring': { disposeDesktopBrowserBridge: idle() }, - '../orca-profiles/profile-cloud-session-owner': { flushUnsavedCloudSessions: idle() }, - '../browser/guest-lifecycle/manager/browser-manager': { - browserManager: { setBrowserGuestStateChangedListener: idle(), setOffscreenTabOpener: idle() } - }, - '../browser/sessions/profiles/browser-session-registry': { browserSessionRegistry: {} }, - '../browser/routing/local-host-partitions/local-ssh-browser-route': { - closeAllLocalSshBrowserRoutes: settled() - }, - '../codex/codex-state-db-backfill-recovery': { stopCodexStateDbBackfillRecoveries: settled() }, - '../codex/codex-account-session-bridge': { stopCodexAccountSessionBridges: idle() }, - '../git/refs/maintenance/local-repo-ref-maintenance': { awaitPackedRefsLockRelease: settled() }, - '../worktree-background-removal': { stopBackgroundWorktreeRemovals: idle() }, - '../dock/unread-badge': { setUnreadDockBadgeCount: idle() }, - '../tray/system-tray': { destroySystemTray: idle() }, - '../telemetry/client': { shutdownTelemetry: settled() }, - '../observability/index': { shutdownObservability: settled() }, - '../updater': { isQuittingForUpdate: vi.fn(() => false) }, - '../updater-lifecycle-diagnostics': { recordUpdaterLifecycle: idle() }, - '../macos-permissions/macos-tcc-prompt-notice': { stopTccPromptNotice: idle() }, - '../pty/history/terminal-history-gc': { cancelHistoryGc: idle() }, - './window-all-closed-quit-policy': { shouldQuitWhenAllWindowsClosed: vi.fn(() => false) }, - './configure-process': { isDevParentShutdownRequested: vi.fn(() => false) }, - '../persistence/loading-store/user-data-path': { - getCanonicalUserDataPath: vi.fn(() => '/unused') - } -} - -afterEach(() => { - vi.doUnmock('electron') - vi.doUnmock('./main-process-state') - for (const moduleName of Object.keys(dependencies)) { - vi.doUnmock(moduleName) - } - vi.restoreAllMocks() - vi.useRealTimers() - vi.resetModules() -}) - -async function startQuit( - flushFinalOrThrowAsync: () => Promise, - services: Record = {} -) { - beginSshShutdown.mockClear() - killAllPty.mockClear() - flushesByNextMicrotask = -1 - vi.resetModules() - vi.useFakeTimers() - const app = Object.assign(new EventEmitter(), { quit: vi.fn() }) - const admission = { release: vi.fn() } - const store = { - flushFinalOrThrowAsync: vi.fn(flushFinalOrThrowAsync), - freezeWritesAsync: settled() - } - beginSshShutdown.mockImplementation(async () => { - void Promise.resolve().then(() => { - flushesByNextMicrotask = store.flushFinalOrThrowAsync.mock.calls.length - }) - }) - const profileStateAdmission: typeof admission | undefined = admission - const state = { - isQuitting: false, - watcherShutdownDone: true, - store, - profileStateAdmission, - ...services - } - vi.doMock('electron', () => ({ app })) - vi.doMock('./main-process-state', () => ({ mainProcessState: state })) - for (const [moduleName, exports] of Object.entries(dependencies)) { - vi.doMock(moduleName, () => exports) - } - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { installMainProcessQuitHandlers } = await import('./main-process-quit') - const { quitTeardownStartGate } = await import('./quit/quit-teardown-start-gate') - quitTeardownStartGate.resetForTests() - installMainProcessQuitHandlers() - app.emit('before-quit', { defaultPrevented: false }) - app.emit('will-quit', { preventDefault: vi.fn() }) - return { app, admission, store, state } -} - -it('quits at the teardown deadline without releasing admission while the writer is pending', async () => { - const { app, admission, store, state } = await startQuit(() => new Promise(() => {})) - await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS - 1) - expect(app.quit).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - expect(app.quit).toHaveBeenCalledOnce() - expect(console.warn).toHaveBeenCalledWith('[shutdown] Quit teardown deadline reached', { - pendingTeardowns: ['state'] - }) - expect(store.flushFinalOrThrowAsync).toHaveBeenCalledOnce() - expect(store.freezeWritesAsync).not.toHaveBeenCalled() - expect(admission.release).not.toHaveBeenCalled() - expect(state.profileStateAdmission).toBe(admission) -}) - -it('writes a pane grid still inside its write burst before the final flush', async () => { - const paneGrids = Promise.withResolvers() - const { store } = await startQuit(async () => {}, { - runtime: { - getOffscreenBrowserBackend: () => null, - getAgentBrowserBridge: () => null, - getEmulatorBridge: () => null, - disposeSkillUploadSessions: settled(), - getRuntimeId: () => undefined, - closeNotificationDismissals: settled(), - flushPaneGrids: () => paneGrids.promise - } - }) - await vi.advanceTimersByTimeAsync(0) - // Before the SSH shutdown too: nothing is awaited between it and the final save. - expect(beginSshShutdown).not.toHaveBeenCalled() - expect(store.flushFinalOrThrowAsync).not.toHaveBeenCalled() - paneGrids.resolve() - await vi.advanceTimersByTimeAsync(0) - expect(beginSshShutdown).toHaveBeenCalledOnce() - expect(store.flushFinalOrThrowAsync).toHaveBeenCalledOnce() - expect(beginSshShutdown.mock.invocationCallOrder[0]).toBeLessThan( - store.flushFinalOrThrowAsync.mock.invocationCallOrder[0]! - ) - // Nothing awaited between them: the save started in the same turn as the SSH shutdown. - expect(flushesByNextMicrotask).toBe(1) -}) - -it.each([ - ['chat teardown', 'RPC stop'], - ['RPC stop', 'chat teardown'] -] as const)( - 'closes notification dismissals only once %s and then %s settle', - async (first, second) => { - const sessionTeardown = Promise.withResolvers() - const rpcStop = Promise.withResolvers() - const release = { 'chat teardown': sessionTeardown.resolve, 'RPC stop': rpcStop.resolve } - stopStructuredAgentSessionRuntime.mockClear() - stopStructuredAgentSessionRuntime.mockImplementationOnce(() => sessionTeardown.promise) - const closeNotificationDismissals = vi.fn(() => new Promise(() => {})) - const { app } = await startQuit(async () => {}, { - runtime: { - getOffscreenBrowserBackend: () => null, - getAgentBrowserBridge: () => null, - getEmulatorBridge: () => null, - disposeSkillUploadSessions: settled(), - getRuntimeId: () => undefined, - closeNotificationDismissals, - flushPaneGrids: () => null - }, - runtimeRpc: { setMobileRelayPairingProvider: idle(), stop: vi.fn(() => rpcStop.promise) } - }) - expect(stopStructuredAgentSessionRuntime).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(0) - expect(closeNotificationDismissals).not.toHaveBeenCalled() - release[first]() - await vi.advanceTimersByTimeAsync(0) - expect(closeNotificationDismissals).not.toHaveBeenCalled() - release[second]() - await vi.advanceTimersByTimeAsync(0) - expect(closeNotificationDismissals).toHaveBeenCalledOnce() - expect(app.quit).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS) - expect(console.warn).toHaveBeenCalledWith('[shutdown] Quit teardown deadline reached', { - pendingTeardowns: ['notification-dismissals'] - }) - expect(app.quit).toHaveBeenCalledOnce() - } -) diff --git a/src/main/startup/main-process-quit-update-veto.test.ts b/src/main/startup/main-process-quit-update-veto.test.ts deleted file mode 100644 index 9a71b26cd7e..00000000000 --- a/src/main/startup/main-process-quit-update-veto.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, expect, it, vi } from 'vitest' - -const dependencyExports: [string, string[]][] = [ - ['../ipc/filesystem-watcher', ['closeAllWatchers']], - ['../ipc/worktree-base-directory-watcher', ['disposeWorktreeBaseDirectoryWatchers']], - ['../ipc/folder-repo-git-upgrade', ['stopFolderRepoGitUpgradeWatch']], - ['../ipc/pty/kill-all', ['killAllPty']], - ['../daemon/providers/lifecycle/daemon-provider-state', ['disconnectDaemon', 'shutdownDaemon']], - ['../ipc/ssh-shutdown-drain', ['beginSshShutdown']], - ['../agent-hooks/server/agent-hook-server', ['agentHookServer']], - ['../agent-hooks/wsl-relay/wsl-hook-relay-manager', ['wslHookRelayManager']], - ['../agent-hooks/installation/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], - [ - '../runtime/agent-session/structured-agent-session-runtime', - ['stopStructuredAgentSessionRuntime'] - ], - [ - '../runtime/agent-session/structured-agent-session-runtime-teardown', - ['setStructuredAgentSessionTeardownTrigger'] - ], - ['../runtime/files/watch/file-watcher-leases', ['awaitRuntimeFileWatcherUnsubscribes']], - ['../runtime/rpc/server/runtime-metadata', ['clearRuntimeMetadataIfOwned']], - [ - '../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime', - ['shutdownPairedRuntimeBrowserClientHosts'] - ], - ['../ipc/browser/desktop-browser-bridge-wiring', ['disposeDesktopBrowserBridge']], - ['../orca-profiles/profile-cloud-session-owner', ['flushUnsavedCloudSessions']], - ['../browser/guest-lifecycle/manager/browser-manager', ['browserManager']], - ['../browser/sessions/profiles/browser-session-registry', ['browserSessionRegistry']], - ['../codex/codex-state-db-backfill-recovery', ['stopCodexStateDbBackfillRecoveries']], - ['../codex/codex-account-session-bridge', ['stopCodexAccountSessionBridges']], - ['../git/refs/maintenance/local-repo-ref-maintenance', ['awaitPackedRefsLockRelease']], - ['../worktree-background-removal', ['stopBackgroundWorktreeRemovals']], - ['./quit/quit-teardown-deadline', ['settleTeardownWithinDeadline', 'settleWithinMs']], - ['./quit/quit-teardown-start-gate', ['quitTeardownStartGate']], - ['../dock/unread-badge', ['setUnreadDockBadgeCount']], - ['../tray/system-tray', ['destroySystemTray']], - ['../telemetry/client', ['shutdownTelemetry']], - ['../observability/index', ['shutdownObservability']], - ['../updater', ['isQuittingForUpdate']], - ['../updater-lifecycle-diagnostics', ['recordUpdaterLifecycle']], - ['../macos-permissions/macos-tcc-prompt-notice', ['stopTccPromptNotice']], - ['../pty/history/terminal-history-gc', ['cancelHistoryGc']], - ['./window-all-closed-quit-policy', ['shouldQuitWhenAllWindowsClosed']], - ['./configure-process', ['isDevParentShutdownRequested']], - ['../persistence/loading-store/user-data-path', ['getCanonicalUserDataPath']] -] - -it('keeps startup services live when the updater has vetoed before-quit', async () => { - vi.resetModules() - const app = new EventEmitter() - const fenceAndCloseNow = vi.fn() - const setMobileRelayPairingProvider = vi.fn() - const unsubscribeAgentAwakeStatusChanges = vi.fn() - const dispose = vi.fn() - const stop = vi.fn() - const state = { - isQuitting: false, - desktopRelayService: { fenceAndCloseNow }, - runtimeRpc: { setMobileRelayPairingProvider }, - unsubscribeAgentAwakeStatusChanges, - agentAwakeService: { dispose }, - rateLimits: { stop } - } - vi.doMock('electron', () => ({ app })) - vi.doMock('./main-process-state', () => ({ mainProcessState: state })) - for (const [moduleName, exports] of dependencyExports) { - vi.doMock(moduleName, () => Object.fromEntries(exports.map((name) => [name, vi.fn()]))) - } - const exitListenersBefore = process.listeners('exit') - const { installMainProcessQuitHandlers } = await import('./main-process-quit') - installMainProcessQuitHandlers() - - app.emit('before-quit', { defaultPrevented: true }) - - expect(state.isQuitting).toBe(false) - expect(fenceAndCloseNow).not.toHaveBeenCalled() - expect(setMobileRelayPairingProvider).not.toHaveBeenCalled() - expect(unsubscribeAgentAwakeStatusChanges).not.toHaveBeenCalled() - expect(dispose).not.toHaveBeenCalled() - expect(stop).not.toHaveBeenCalled() - expect(state.agentAwakeService).toEqual({ dispose }) - expect(state.unsubscribeAgentAwakeStatusChanges).toBe(unsubscribeAgentAwakeStatusChanges) - - app.emit('before-quit', { defaultPrevented: false }) - - expect(state.isQuitting).toBe(true) - expect(fenceAndCloseNow).toHaveBeenCalledOnce() - expect(setMobileRelayPairingProvider).toHaveBeenCalledWith(null) - expect(unsubscribeAgentAwakeStatusChanges).toHaveBeenCalledOnce() - expect(dispose).toHaveBeenCalledOnce() - expect(stop).toHaveBeenCalledOnce() - for (const listener of process.listeners('exit')) { - if (!exitListenersBefore.includes(listener)) { - process.removeListener('exit', listener) - } - } -}) - -afterEach(() => { - vi.doUnmock('electron') - vi.doUnmock('./main-process-state') - for (const [moduleName] of dependencyExports) { - vi.doUnmock(moduleName) - } - vi.resetModules() -}) diff --git a/src/main/startup/main-process-ready-activation-failure.test.ts b/src/main/startup/main-process-ready-activation-failure.test.ts index b2b75c42c2b..c87b24eb29a 100644 --- a/src/main/startup/main-process-ready-activation-failure.test.ts +++ b/src/main/startup/main-process-ready-activation-failure.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { MainProcessRuntimeLaunchOptions } from './main-process-runtime-launch' +import type { MainProcessRuntimeLaunchOptions } from './runtime-startup/main-process-runtime-launch' const phases = vi.hoisted(() => ({ foundation: vi.fn<() => Promise>(), @@ -14,14 +14,16 @@ vi.mock('./main-process-ready-foundation', () => ({ vi.mock('./main-process-ready-runtime', () => ({ initializeReadyRuntimeServices: phases.runtimeServices })) -vi.mock('./main-process-i18n-menu', () => ({ initializeMainProcessI18nAndMenu: phases.menu })) -vi.mock('./main-process-runtime-launch', () => ({ +vi.mock('./main-window/main-process-i18n-menu', () => ({ + initializeMainProcessI18nAndMenu: phases.menu +})) +vi.mock('./runtime-startup/main-process-runtime-launch', () => ({ initializeMainProcessRuntimeLaunch: phases.launch })) const { initializeMainProcessReady } = await import('./main-process-ready') const { mainProcessState: state } = await import('./main-process-state') -const { createServeDesktopActivationGate } = await import('./serve-desktop-activation') +const { createServeDesktopActivationGate } = await import('./serve-launch/serve-desktop-activation') const activateWindow = vi.fn() const launchOptions: MainProcessRuntimeLaunchOptions = { diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index af0d0d23b60..354f4df927b 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -1,5 +1,5 @@ import { app, session } from 'electron' -import { applyBackgroundActivationPolicy } from '../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../window/activation/foreground-activation-policy' import { applyElectronProxySettings } from '../network/proxy-settings' import { installElectronProxyRequestGuard } from '../network/electron-proxy-request-guard' import { handleElectronProxyLogin } from '../network/electron-proxy-credentials' @@ -27,7 +27,7 @@ import { withholdUnreachableKeychainForServe } from '../host/serve-keychain-guar import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' import { neutralizeLegacyTerminalShimDir } from '../pty/shell-startup/legacy-terminal-shim-dir' -import { createWindowsShellPathHydration } from './windows-shell-path-hydration' +import { createWindowsShellPathHydration } from './shell-environment/windows-shell-path-hydration' import { configureWindowsHostGitEnvironmentReadiness } from '../git/command-runner/host-routing/windows-host-git-environment' import { setDefaultWslDistroOverride } from '../git/command-runner/host-routing/wsl-command-resolution' import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' @@ -35,7 +35,7 @@ import { applyAppIcon } from '../window/desktop-integration/app-icon' import { shouldSuppressDevEducation, suppressDevEducationForStore -} from './dev-education-suppression' +} from './profile-startup/dev-education-suppression' import { awaitBrowserSessionProxies, setBrowserNetworkProxySettingsResolver @@ -51,20 +51,20 @@ import { } from '../browser/extensions/browser-extension-startup' import { whenBrowserExtensionSessionsLoaded } from '../browser/extensions/profile-sessions/browser-extension-session-loader' import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' -import { logStartupMilestone } from './startup-diagnostics' -import { writeHttp1CompatibilityMarker } from './http1-compatibility-marker' +import { logStartupMilestone } from './diagnostics/startup-diagnostics' +import { writeHttp1CompatibilityMarker } from './network-compatibility/http1-compatibility-marker' import { mainProcessState as state } from './main-process-state' -import { syncMacMenuBarIcon } from './main-window-actions' -import { updateGpuAccelerationAboutPanel } from './gpu-lifecycle' +import { syncMacMenuBarIcon } from './main-window/main-window-actions' +import { updateGpuAccelerationAboutPanel } from './gpu-recovery/gpu-lifecycle' import { logWslCliReconciliationResults, reconcileManagedWslCliRegistrations } from '../cli/wsl/wsl-cli-registration-reconciliation' -import { createWslCliReconciliationStartupBarrier } from './wsl-cli-reconciliation-startup-barrier' +import { createWslCliReconciliationStartupBarrier } from './wsl-startup/wsl-cli-reconciliation-startup-barrier' import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reportProfileStateWriteFailure } from './profile-state-write-failure' -import { reportProfileStateSaveDelay } from './profile-state-save-delay' +import { reportProfileStateWriteFailure } from './profile-startup/profile-state-write-failure' +import { reportProfileStateSaveDelay } from './profile-startup/profile-state-save-delay' import { preloadSsh2 } from '../ssh/authentication/ssh2-module-load' export async function initializeReadyFoundation(): Promise { diff --git a/src/main/startup/main-process-ready-persistence-cleanup.test.ts b/src/main/startup/main-process-ready-persistence-cleanup.test.ts index ee7765acb9d..4151a587e4d 100644 --- a/src/main/startup/main-process-ready-persistence-cleanup.test.ts +++ b/src/main/startup/main-process-ready-persistence-cleanup.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ServeDesktopActivationGate } from './serve-desktop-activation' +import type { ServeDesktopActivationGate } from './serve-launch/serve-desktop-activation' const { state, foundation, runtime, i18n, launch } = vi.hoisted(() => ({ state: { @@ -25,8 +25,10 @@ function initialActivationGate(): ServeDesktopActivationGate | null { vi.mock('./main-process-state', () => ({ mainProcessState: state })) vi.mock('./main-process-ready-foundation', () => ({ initializeReadyFoundation: foundation })) vi.mock('./main-process-ready-runtime', () => ({ initializeReadyRuntimeServices: runtime })) -vi.mock('./main-process-i18n-menu', () => ({ initializeMainProcessI18nAndMenu: i18n })) -vi.mock('./main-process-runtime-launch', () => ({ initializeMainProcessRuntimeLaunch: launch })) +vi.mock('./main-window/main-process-i18n-menu', () => ({ initializeMainProcessI18nAndMenu: i18n })) +vi.mock('./runtime-startup/main-process-runtime-launch', () => ({ + initializeMainProcessRuntimeLaunch: launch +})) import { initializeMainProcessReady } from './main-process-ready' @@ -66,25 +68,6 @@ describe('startup persistence lifetime', () => { expect(launch).not.toHaveBeenCalled() }) - it('joins concurrent startup branches before closing their Store', async () => { - const failure = new Error('translations failed') - i18n.mockRejectedValueOnce(failure) - let release = () => {} - launch.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - const ready = initializeMainProcessReady(options) - const rejected = expect(ready).rejects.toBe(failure) - await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce()) - expect(state.store.freezeWritesAsync).not.toHaveBeenCalled() - release() - await rejected - expect(state.store.freezeWritesAsync).toHaveBeenCalledOnce() - }) - it('keeps the original startup failure when cleanup also fails', async () => { const log = vi.spyOn(console, 'error').mockImplementation(() => {}) const failure = new Error('foundation failed') diff --git a/src/main/startup/main-process-ready-phase-ordering.test.ts b/src/main/startup/main-process-ready-phase-ordering.test.ts index a66597549b7..2fb4881cd82 100644 --- a/src/main/startup/main-process-ready-phase-ordering.test.ts +++ b/src/main/startup/main-process-ready-phase-ordering.test.ts @@ -13,7 +13,7 @@ vi.mock('./main-process-ready-runtime', () => ({ phaseEvents.push('runtime-services') }) })) -vi.mock('./main-process-i18n-menu', () => ({ +vi.mock('./main-window/main-process-i18n-menu', () => ({ initializeMainProcessI18nAndMenu: vi.fn( () => new Promise((resolve) => { @@ -25,7 +25,7 @@ vi.mock('./main-process-i18n-menu', () => ({ }) ) })) -vi.mock('./main-process-runtime-launch', () => ({ +vi.mock('./runtime-startup/main-process-runtime-launch', () => ({ initializeMainProcessRuntimeLaunch: vi.fn(async () => { phaseEvents.push('launch-start') await Promise.resolve() @@ -34,7 +34,7 @@ vi.mock('./main-process-runtime-launch', () => ({ })) const { initializeMainProcessReady } = await import('./main-process-ready') -const { mainProcessState } = await import('./main-process-state') +await import('./main-process-state') describe('ready-phase concurrency', () => { beforeEach(() => { @@ -42,31 +42,6 @@ describe('ready-phase concurrency', () => { releaseI18n = null }) - it('creates the window without waiting for i18n and the native menu', async () => { - const options = { - openMainWindow: vi.fn(), - handleMacAppActivation: vi.fn() - } as unknown as Parameters[0] - - const ready = initializeMainProcessReady(options) - // Drain the launch phase's microtasks while i18n is still pending. - for (let tick = 0; tick < 8; tick += 1) { - await Promise.resolve() - } - - expect(phaseEvents).toEqual([ - 'foundation', - 'runtime-services', - 'i18n-start', - 'launch-start', - 'window-created' - ]) - - releaseI18n?.() - await ready - expect(phaseEvents.at(-1)).toBe('i18n-done') - }) - it('still resolves only once i18n and the menu have settled', async () => { const options = { openMainWindow: vi.fn(), @@ -87,37 +62,4 @@ describe('ready-phase concurrency', () => { await ready expect(settled).toBe(true) }) - - it('waits for the startup WSL move rewrite before runtime services and the window', async () => { - let finishRewrite: () => void = () => {} - mainProcessState.wslMoveStartupRewriteReady = new Promise((resolve) => { - finishRewrite = () => { - phaseEvents.push('wsl-move-rewrite-done') - resolve() - } - }) - const options = { - openMainWindow: vi.fn(), - handleMacAppActivation: vi.fn() - } as unknown as Parameters[0] - - const ready = initializeMainProcessReady(options) - for (let tick = 0; tick < 8; tick += 1) { - await Promise.resolve() - } - expect(phaseEvents).toEqual(['foundation']) - - finishRewrite() - for (let tick = 0; tick < 8; tick += 1) { - await Promise.resolve() - } - releaseI18n?.() - await ready - mainProcessState.wslMoveStartupRewriteReady = Promise.resolve() - expect(phaseEvents.slice(0, 3)).toEqual([ - 'foundation', - 'wsl-move-rewrite-done', - 'runtime-services' - ]) - }) }) diff --git a/src/main/startup/main-process-ready-runtime.ts b/src/main/startup/main-process-ready-runtime.ts index 4b70bdb6b37..591411a8cb3 100644 --- a/src/main/startup/main-process-ready-runtime.ts +++ b/src/main/startup/main-process-ready-runtime.ts @@ -5,15 +5,18 @@ import { StarNagService } from '../star-nag/service' import { AgentBrowserBridge } from '../browser/agent-browser/agent-browser-bridge' import { EmulatorBridge } from '../emulator/emulator-bridge' import { RpcDispatcher } from '../runtime/rpc/dispatcher' -import { DESKTOP_RPC_CALLER, LOCAL_CLI_RPC_CALLER } from '../runtime/rpc/rpc-caller-identity' +import { + DESKTOP_RPC_CALLER, + LOCAL_CLI_RPC_CALLER +} from '../runtime/rpc/callers/rpc-caller-identity' import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { configureBrowserClientPageAutomationRuntime } from '../browser/client-pages/execution/browser-client-page-automation-runtime' import { BrowserExpectedUrlMismatch } from '../../shared/browser/client-hosting/browser-expected-url' import { BrowserClientPageCommandError } from '../browser/client-pages/execution/browser-client-page-command-failure' import { startPreGoneCrashSampling } from '../crash-reporting/process-exits/process-gone-diagnostics' -import { refuseRealtimeSchedulingUnderZeroRtTime } from './linux-realtime-scheduling-guard' -import { recordProcessGoneCrash } from './main-window-lifecycle-flags' -import { handleGpuChildCrash } from './gpu-lifecycle' +import { refuseRealtimeSchedulingUnderZeroRtTime } from './linux-runtime/linux-realtime-scheduling-guard' +import { recordProcessGoneCrash } from './main-window/main-window-lifecycle-flags' +import { handleGpuChildCrash } from './gpu-recovery/gpu-lifecycle' import { isGpuFallbackCrashCandidate } from '../crash-reporting/recovery/gpu-crash-fallback-decision' import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' @@ -22,30 +25,31 @@ import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/m import { shouldInstallManagedHooks } from './configure-process' import { mainProcessState as state } from './main-process-state' import { initializeMainProcessObservers } from './main-process-observers' -import { installFirstWorkRenameHookSubscription } from './branch-rename-hook' -import { initializeMainProcessAccountServices } from './main-process-account-services' +import { installFirstWorkRenameHookSubscription } from './workspace-startup/branch-rename-hook' +import { initializeMainProcessAccountServices } from './agent-accounts/main-process-account-services' import { initializeMainProcessRuntime, configureRuntimeServices -} from './main-process-runtime-service' -import { initializeMainProcessAutomations } from './main-process-automations' -import { initializeMainProcessPlugins } from './main-process-plugins' +} from './runtime-startup/main-process-runtime-service' +import { initializeMainProcessAutomations } from './runtime-startup/main-process-automations' +import { initializeMainProcessPlugins } from './plugin-startup/main-process-plugins' import { collectWorktreeTrashSweepRoots, sweepStaleWorktreeTrash } from '../workspaces/removal/worktree-trash' -import { loadWorktreeRemovalRecordsForStore } from './worktree-removal-records-load' -import { runAfterFirstWindowShown } from './first-window-deferral' +import { loadWorktreeRemovalRecordsForStore } from './workspace-startup/worktree-removal-records-load' +import { runAfterFirstWindowShown } from './main-window/first-window-deferral' import { startSpeechModelWarmup } from '../speech/speech-model-warmup' -import { logStartupMilestone } from './startup-diagnostics' +import { logStartupMilestone } from './diagnostics/startup-diagnostics' import { refreshInstalledOpenCodeStatusPlugins } from '../opencode/status-hooks/opencode-status-plugin-startup-refresh' -import { pruneDesktopOrcadArtifactCache } from '../orcad/orcad-artifact-cache-retention' +import { pruneDesktopOrcadArtifactCache } from '../orcad/artifact-slots/orcad-artifact-cache-retention' import { runGatedWslMoveDesktopRewritePass } from '../persistence/moving-wsl-projects/desktop-state/wsl-move-desktop-rewrite' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { repairDuplicatePtyPanesOnStart } from '../runtime/terminal/identity/moved-pane-owner-rekey' import { WslUsageReporter } from '../telemetry/wsl-usage-reporter' import { ALL_RPC_METHODS } from '../runtime/rpc/methods/rpc-method-registry' import { startClaudeCodeThemeSync } from '../claude/theme-sync/claude-code-theme-sync-schedule' +import { startWorkspaceCleanupRunner } from '../workspaces/cleanup/workspace-cleanup-runner-startup' // Headless serve has no first window; timer fallback must still sweep trash. const WORKTREE_TRASH_SWEEP_FALLBACK_MS = 15_000 @@ -63,6 +67,7 @@ export async function initializeReadyRuntimeServices(): Promise { initializeMainProcessAccountServices() const runtime = initializeMainProcessRuntime() initializeMainProcessAutomations() + startWorkspaceCleanupRunner(runtime, store) configureRuntimeServices(runtime) installFirstWorkRenameHookSubscription() await initializeMainProcessPlugins(runtime) @@ -88,7 +93,8 @@ export async function initializeReadyRuntimeServices(): Promise { if (!response.ok) { const mismatch = BrowserExpectedUrlMismatch.safeParse(response.error.data) throw new BrowserClientPageCommandError(response.error.code, { - expectedUrlMismatch: mismatch.success ? mismatch.data : undefined + expectedUrlMismatch: mismatch.success ? mismatch.data : undefined, + detail: response.error.message }) } return response.result diff --git a/src/main/startup/main-process-ready.ts b/src/main/startup/main-process-ready.ts index 780f3ad8670..74c5043cd86 100644 --- a/src/main/startup/main-process-ready.ts +++ b/src/main/startup/main-process-ready.ts @@ -1,12 +1,12 @@ -import { initializeMainProcessI18nAndMenu } from './main-process-i18n-menu' +import { initializeMainProcessI18nAndMenu } from './main-window/main-process-i18n-menu' import { mainProcessState as state } from './main-process-state' import { initializeReadyFoundation } from './main-process-ready-foundation' import { initializeReadyRuntimeServices } from './main-process-ready-runtime' -import { releaseDesktopActivationAfter } from './serve-desktop-activation' +import { releaseDesktopActivationAfter } from './serve-launch/serve-desktop-activation' import { initializeMainProcessRuntimeLaunch, type MainProcessRuntimeLaunchOptions -} from './main-process-runtime-launch' +} from './runtime-startup/main-process-runtime-launch' export async function initializeMainProcessReady( launchOptions: MainProcessRuntimeLaunchOptions diff --git a/src/main/startup/main-process-relay-startup.ts b/src/main/startup/main-process-relay-startup.ts deleted file mode 100644 index 539284e7580..00000000000 --- a/src/main/startup/main-process-relay-startup.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { app, powerMonitor } from 'electron' -import { getOrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' -import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' -import type { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' -import { DesktopRelayService } from '../runtime/mobile-cloud-relay/desktop-relay-service' -import { createDesktopRelayServiceInstaller } from '../runtime/mobile-cloud-relay/desktop-relay-service-installer' -import { publishDesktopRelayStatus } from './main-process-relay-status' -import { mainProcessState as state } from './main-process-state' - -// Register before proxy readiness; the installer waits before its first request. -export function startDesktopRelayService(runtimeRpc: OrcaRuntimeRpcServer): void { - const installer = createDesktopRelayServiceInstaller({ - runtimeRpc, - whenNetworkReady: state.initialProxyApplicationReady, - isFenced: () => state.isQuitting, - create: () => { - const cloudAuth = getOrcaCloudAuthConfig() - return cloudAuth.configured - ? new DesktopRelayService({ - authConfig: cloudAuth.config, - userDataPath: getProfileUserDataPath(), - appVersion: app.getVersion(), - runtimeRpc, - onStatus: publishDesktopRelayStatus - }) - : null - }, - onInstalled: (service) => { - state.desktopRelayService = service - } - }) - state.desktopRelayInstaller = installer - runtimeRpc.setMobileRelayPairingProviderInstaller(() => installer.ensure()) - // Sleep can expire the token with no retry timer; resume is the recovery opportunity. - powerMonitor.on('resume', () => state.desktopRelayService?.ensureLive()) - void installer.ensure() -} diff --git a/src/main/startup/main-process-relay-status.ts b/src/main/startup/main-process-relay-status.ts deleted file mode 100644 index f53848fdf63..00000000000 --- a/src/main/startup/main-process-relay-status.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { MobileRelayStatusDetail } from '../../shared/remote-runtime/relay/mobile-relay-status' -import { mainProcessState as state } from './main-process-state' - -export function getDesktopRelayStatus(): MobileRelayStatusDetail { - return { ...state.desktopRelayStatus } -} - -export function publishDesktopRelayStatus( - status: MobileRelayStatusDetail['status'], - cellUrl?: string, - clockOffsetMs?: number -): void { - state.desktopRelayStatus = { - status, - ...(cellUrl === undefined ? {} : { cellUrl }), - ...(clockOffsetMs === undefined ? {} : { clockOffsetMs }) - } - state.mainWindow?.webContents.send('mobile:relayStatusChanged', getDesktopRelayStatus()) -} diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts deleted file mode 100644 index 3bb76f1a7da..00000000000 --- a/src/main/startup/main-process-runtime-service.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { wireRecipeWorkspaceRemoval } from '../ephemeral-vm/recipe-workspace-removal-wiring' -import { wireGitHubIssueLinkTitleFill } from '../github/github-issue-link-title-wiring' -import { - applySessionSearchSettingsChange, - installChildSessionSearchService -} from '../ai-vault-search/session-search-enablement' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { sessionSearchScopeCatalogFromStore } from '../ai-vault-search/scope/session-search-store-scope-catalog' -import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' -import { app } from 'electron' -import { translateMain } from '../i18n/main-i18n' -import { OrcaRuntimeService } from '../runtime/orca-runtime' -import { getLocalPtyProvider } from '../ipc/pty/provider/registry' -import { clearProviderPtyState } from '../ipc/pty/provider/state-cleanup' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { toAgentStatusIpcPayload } from '../agent-hooks/server/server-status-identity' -import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' -import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' -import { loadAgentSessionClaimSigner } from '../runtime/agent-session/ownership/agent-session-claim-identity' -import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' -import { codexAiVaultSessionResumePreparation } from '../codex/history/resume/codex-ai-vault-session-resume' -import { prepareCodexPinnedLaunchHome } from './codex-session-resume-launch' -import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { agentHookRuntimeDeps } from '../agent-hooks/runtime/agent-hook-runtime-deps' -import { getDaemonProvider } from '../daemon/providers/lifecycle/daemon-provider-state' -import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' -import { resolveTuiAgentLaunchEnv } from '../../shared/agent-launch/choices/tui-agent-launch-defaults' -import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' -import { createOrchestrationEnvironmentTransport } from '../ipc/runtime-environments/orchestration-environment-transport' -import { trackRuntimeEnvironmentVerifiedTransitions } from '../ipc/runtime-environments/runtime-environment-verified-transitions' -import { onRuntimeEnvironmentStatusPublished } from '../ipc/runtime-environments/runtime-environment-status-owner' -import { mainProcessState as state } from './main-process-state' -import { suspendEphemeralVmWorkspace } from '../ephemeral-vm/workspace-suspend' -import { - acceptEphemeralVmWorkspaceWake, - resumeEphemeralVmWorkspace -} from '../ephemeral-vm/workspace-resume' -import { registerRecipeVmWaker } from '../runtime/workspaces/sleep/recipe-vm-waker-registry' -import { setSshHostAsleepCheck } from '../ssh/connection/ssh-host-sleep-hold' -import { - isRecipeVmSshTargetAsleep, - setRecipeVmAsleepStoreRoot -} from '../ephemeral-vm/recipe-vm-asleep' -import { openRecipeVmEnvironment } from '../ipc/runtime-environments/runtime-environment-recipe-vm-wake' -import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-workspace-runtime' -import { installWslOrcadAccountShim } from './wsl-orcad-account-env-wiring' -import { - codexStructuredLaunchHomeResolvers, - prepareCodexRuntimeHomeForLaunch -} from './codex-launch-preparation' -import { resolveHostAgentBaseEnvironment } from '../runtime/agent-session/environment/structured-agent-shell-environment' -import type { RuntimeDesktopWindowStatus } from '../../shared/runtime-types' -import { ArtifactCloudService } from '../artifacts/artifact-cloud-service' -import { SkillCloudService } from '../skills/cloud/skill-cloud-package-service' -import { isArtifactSharingEnabled } from '../../shared/artifacts/artifact-sharing-gate' -import { - AgentStatusObservedPaneIdentities, - recordObservedAgentStatusPaneIdentity -} from '../runtime/terminal/identity/agent-status-observed-pane-identity' -import { startAgentStateRulesLiveUpdates } from '../runtime/agent-state-rules/agent-state-rules-live-update' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' -import { openOffscreenBrowserPageLink } from '../runtime/browser/commands/offscreen-browser-page-link' - -export function getDesktopWindowStatus(): RuntimeDesktopWindowStatus { - const activation = state.desktopActivationGate - if (!activation) { - return 'available' - } - const value = activation.getState() - return value === 'ready' ? 'openable' : value -} - -export function initializeMainProcessRuntime(): OrcaRuntimeService { - const store = state.store - const stats = state.stats - if (!store || !stats) { - throw new Error('Store and stats must be initialized before runtime') - } - // Process-scope subscription covers desktop, headless serve and fleet status. - const observedPaneIdentities = new AgentStatusObservedPaneIdentities() - const runtime = new OrcaRuntimeService(store, stats, { - getSetupTerminalTitle: () => translateMain('worktree.setupTerminalTitle', 'Setup'), - ...agentHookRuntimeDeps(agentHookServer, observedPaneIdentities, () => - state.store?.getSettings() - ), - prepareClaudeAuth: (target) => state.claudeRuntimeAuth!.prepareForClaudeLaunch(target), - agentSessionClaimSigner: loadAgentSessionClaimSigner( - getProfileUserDataPath(), - getProfileUserDataPath() - ), - // Resolve provider lazily or later daemon adoption leaves a frozen pre-daemon reference (design §4.3). - getLocalProvider: () => getLocalPtyProvider(), - onPtyStopped: clearProviderPtyState, - // Serve can activate in place; wire now, but enable desktop scanners only for a ready renderer. - onTerminalSideEffects: (batch: TerminalSideEffectBatch) => { - if (state.mainWindow && !state.mainWindow.isDestroyed()) { - state.mainWindow.webContents.send('pty:sideEffect', batch) - } - }, - getDesktopWindowStatus, - attestAgentHookCompatibilityAuthority: (candidate) => - agentHookServer.attestCompatibilityAuthority(candidate), - retireAgentHookCompatibilityAuthority: (paneKey) => - agentHookServer.retirePaneAuthority(paneKey), - canRecoverPersistentLocalPtys: () => getDaemonProvider() !== null, - // Resolve per call: the RPC server/device registry is constructed later with this runtime. - getPairedDeviceName: (pairedDeviceId) => - state.runtimeRpc?.getDeviceRegistry()?.getDevice(pairedDeviceId)?.name ?? null, - // Provide managed Codex homes here for desktop and headless session discovery; core IPC registration is window-only. - getAdditionalAiVaultCodexHomePaths: () => - state.codexRuntimeHome?.getHostCodexHomePathsForSessionDiscovery() ?? [], - prepareAiVaultSessionResume: codexAiVaultSessionResumePreparation(() => ({ - runtimeHome: state.codexRuntimeHome, - systemCodexHomePath: resolveHostCodexSessionSourceHome(store.getSettings()), - preparePinnedLaunchHome: (home) => prepareCodexPinnedLaunchHome(home) - })), - ...codexStructuredLaunchHomeResolvers, - prepareCodexCatalogProbeHome: (homePath) => - state.codexRuntimeHome?.prepareHostCodexHomeForReadOnlyAppServer( - homePath, - resolveTuiAgentLaunchEnv('codex', store.getSettings()) - ), - orchestrationEnvironmentTransport: { - ...createOrchestrationEnvironmentTransport(), - onEnvironmentVerified: (listener) => - onRuntimeEnvironmentStatusPublished(trackRuntimeEnvironmentVerifiedTransitions(listener)) - }, - workspaceSleepPlatform: { - callEnvironment: (environmentId, method, params, timeoutMs) => - callRuntimeEnvironment( - getRuntimeEnvironmentRegistryRoot(), - environmentId, - method, - params, - timeoutMs - ), - ownsVm: (workspaceId) => - findWorkspaceEphemeralVmRuntime(app.getPath('userData'), workspaceId) !== undefined, - suspendVm: (workspaceId) => suspendEphemeralVmWorkspace(store, workspaceId), - acceptWake: (workspaceId) => acceptEphemeralVmWorkspaceWake(workspaceId), - resumeVm: (workspaceId, request) => resumeEphemeralVmWorkspace(store, workspaceId, request) - }, - // Paired/local settings writes must reconcile the scanner child through the same path. - applySessionSearchSettings: applySessionSearchSettingsChange, - skillTransactionRecovery: state.skillTransactionRecovery - }) - // Both desktop and headless serve own a host-local search service. - const sessionSearch = installChildSessionSearchService({ - dataRoot: getCanonicalUserDataPath(), - getSettings: () => store.getSettings(), - // Read the host catalog per search so added repos/renamed workspaces are immediately in scope. - getScopeCatalog: () => sessionSearchScopeCatalogFromStore(store, LOCAL_EXECUTION_HOST_ID) - }) - app.once('will-quit', () => sessionSearch?.dispose()) - // Desktop and headless hosts each evaluate their own panes' rules. - startAgentStateRulesLiveUpdates(store, (rules) => - recordDurableCrashBreadcrumb('agent_state_rules_active', rules) - ) - wireRecipeWorkspaceRemoval(runtime, store, () => app.getPath('userData')) - // Each host titles its own workspaces' untitled GitHub issue links once, when they are linked. - const disposeIssueLinkTitleFill = wireGitHubIssueLinkTitleFill(store, runtime) - app.once('will-quit', disposeIssueLinkTitleFill) - state.runtime = runtime - // Opening a recipe VM's workspace from a client wakes the VM through the runtime's one owner. - registerRecipeVmWaker({ - state: (workspaceId, suspended) => runtime.workspaceVmState(workspaceId, suspended), - noteOpened: (workspaceId) => runtime.noteWorkspaceReopened(workspaceId), - holdOpen: (workspaceId, suspended, timeoutMs, signal) => - runtime.holdWorkspaceVmOpen(workspaceId, suspended, timeoutMs, signal), - openEnvironment: (selector) => { - const root = getRuntimeEnvironmentRegistryRoot() - return openRecipeVmEnvironment(root, resolveEnvironment(root, selector)) - } - }) - // A sleeping VM's SSH host takes no background login until its workspace wakes (#36363). - setRecipeVmAsleepStoreRoot(getRuntimeEnvironmentRegistryRoot) - setSshHostAsleepCheck((targetId) => isRecipeVmSshTargetAsleep(app.getPath('userData'), targetId)) - runtime.attachAgentStatusStore(agentHookServer) - agentHookServer.subscribeEnrichedStatus((enriched) => - recordObservedAgentStatusPaneIdentity(observedPaneIdentities, enriched, runtime) - ) - agentHookServer.setCliWriterExecutionMatcher(observedPaneIdentities, runtime) - agentHookServer.setClaudePermissionHolds(runtime.terminalWorkerApprovals) - // Main records pane resume state from accepted status. - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - agentHookServer.subscribeEnrichedStatus((enriched) => - runtime.recordHookStatusResume(toAgentStatusIpcPayload(enriched)) - ) - agentHookServer.subscribePaneStatusClear((clear) => runtime.forgetHookStatusResume(clear)) - agentHookServer.subscribeStatusDrop((paneKey) => runtime.forgetHookStatusResume({ paneKey })) - } - // Rehydrate before clients attach so restarted runtimes can return their owned pages. - runtime.rehydrateClientHostedBrowserPages() - browserManager.setBrowserGuestStateChangedListener((worktreeId) => { - runtime.notifyMobileSessionTabsChanged(worktreeId) - }) - browserManager.setOffscreenTabOpener((request) => - openOffscreenBrowserPageLink( - (params, caller) => runtime.browserTabCreate(params, caller), - request - ) - ) - browserSessionRegistry.onProfilesChanged = () => runtime.notifyBrowserProfilesChanged() - runtime.startupWorkerAuthority.begin() - return runtime -} - -export function configureRuntimeServices(runtime: OrcaRuntimeService): void { - const store = state.store - const claudeAccounts = state.claudeAccounts - const codexAccounts = state.codexAccounts - const rateLimits = state.rateLimits - if (!store || !claudeAccounts || !codexAccounts || !rateLimits) { - throw new Error('Account services must be initialized before runtime wiring') - } - runtime.setArtifactService( - new ArtifactCloudService(app.getPath('userData'), () => - isArtifactSharingEnabled(state.store?.getSettings()) - ) - ) - runtime.setSkillCloudService(new SkillCloudService(app.getPath('userData'))) - runtime.setAccountServices({ claudeAccounts, codexAccounts, rateLimits }) - installWslOrcadAccountShim(store) - runtime.setCommitMessageAgentEnvironmentResolvers({ - // Resolve every Codex launch through runtime-home, including default-account hooks/auth. - prepareForCodexLaunch: prepareCodexRuntimeHomeForLaunch, - prepareForClaudeLaunch: (target) => state.claudeRuntimeAuth!.prepareForClaudeLaunch(target), - resolveBaseEnvironment: () => resolveHostAgentBaseEnvironment(store.getSettings()) - }) -} diff --git a/src/main/startup/main-process-serve.ts b/src/main/startup/main-process-serve.ts deleted file mode 100644 index 61cc4bacd1f..00000000000 --- a/src/main/startup/main-process-serve.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { app } from 'electron' -import { notifyServeSupervisorReady } from '../updater/serve-update-handoff' -import { clearServeAbortPark } from '../../shared/serve-abort-park' -import { findBundledWebClientRoot } from '../../shared/bundled-web-client-root' -import { buildServePairingReadiness, servePublishMode } from '../server/serve-pairing-readiness' -import { mainProcessState as state } from './main-process-state' -import { getServeOptions, type ServeOptions } from './serve-options' - -export { getServeOptions, type ServeOptions } - -export function getBundledWebClientRoot(): string | undefined { - return findBundledWebClientRoot(app.getAppPath()) -} - -export async function printServeReady(options: ServeOptions): Promise { - const runtime = state.runtime - const runtimeRpc = state.runtimeRpc - if (!runtime || !runtimeRpc) { - throw new Error('Runtime server must be initialized before printing serve readiness') - } - // Validate project root before pairing publication can persist a pending device. - const output = servePublishMode(options) - await state.serveReadinessPublisher.publish( - { - runtimeId: runtime.getRuntimeId(), - ...(await buildServePairingReadiness(options, runtimeRpc)), - // WSL barrier fails open; pending warns clients PTY launch may still race repair. - managedWslCliReconciliation: state.managedWslCliReconciliationStatus - }, - output - ) - notifyServeSupervisorReady(runtime.getRuntimeId()) - // Successful readiness disproves the previous serve-abort park. - clearServeAbortPark(app.getPath('userData')) -} diff --git a/src/main/startup/main-process-state.ts b/src/main/startup/main-process-state.ts index ecb42038b0a..79efb13c884 100644 --- a/src/main/startup/main-process-state.ts +++ b/src/main/startup/main-process-state.ts @@ -17,7 +17,7 @@ import type { DesktopPushService } from '../runtime/push/desktop-push-service' import type { StarNagService } from '../star-nag/service' import type { AgentAwakeService } from '../power/agent-awake-service' import type { CrashReportStore } from '../crash-reporting/reports/crash-report-store' -import type { AutomationService } from '../automations/service' +import type { AutomationService } from '../automations/automation-service' import type { PluginService } from '../plugins/plugin-service' import type { PluginKillListService } from '../plugins/catalog/plugin-kill-list-service' import type { PluginInstallStatsService } from '../plugins/catalog/plugin-install-stats-service' @@ -29,24 +29,27 @@ import type { KeybindingService } from '../keybindings/keybinding-service' import type { MobileRelayStatusDetail } from '../../shared/remote-runtime/relay/mobile-relay-status' import type { AgentBrowserBridge } from '../browser/agent-browser/agent-browser-bridge' import type { EmulatorBridge } from '../emulator/emulator-bridge' -import type { GpuFallbackMarker, GpuFallbackEnvironment } from './gpu-fallback-marker' +import type { GpuFallbackMarker, GpuFallbackEnvironment } from './gpu-recovery/gpu-fallback-marker' import type { createCodexSessionMigrationScheduler } from '../codex/history/backfill/codex-session-migration-scheduler' -import type { getDevInstanceIdentity } from './dev-instance-identity' -import type { createServeDesktopActivationGate } from './serve-desktop-activation' +import type { getDevInstanceIdentity } from './profile-startup/dev-instance-identity' +import type { createServeDesktopActivationGate } from './serve-launch/serve-desktop-activation' import type { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' -import type { createWindowsShellPathHydration } from './windows-shell-path-hydration' -import type { ServeOptions } from './main-process-serve' +import type { createWindowsShellPathHydration } from './shell-environment/windows-shell-path-hydration' +import type { ServeOptions } from './serve-launch/serve-options' import type { HangDetectionMarker } from '../hang-watchdog/hang-detection-marker' import { ServeReadinessPublisher } from '../server/serve-readiness' -import { PluginInstallLinkState, SkillShareDeepLinkState } from './skill-share-deep-link-state' -import { OsOpenedDocumentState } from './os-opened-documents' +import { + PluginInstallLinkState, + SkillShareDeepLinkState +} from './open-routing/skill-share-deep-link-state' +import { OsOpenedDocumentState } from './open-routing/os-opened-documents' import { DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD, DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, GpuCrashFallbackTracker } from '../crash-reporting/recovery/gpu-crash-fallback-decision' import type { GpuCrashDiagnosticsRecorder } from '../crash-reporting/capture/gpu-crash-diagnostics' -import { createWebContentsTimedFlag } from './web-contents-timed-flag' +import { createWebContentsTimedFlag } from './main-window/web-contents-timed-flag' import type { ProfileStateStorageClassification } from '../persistence/profile-state/database/profile-state-storage-classification' import type { ProfileStateRuntimeAdmission } from '../persistence/profile-state/access/profile-state-access' diff --git a/src/main/startup/first-window-deferral.ts b/src/main/startup/main-window/first-window-deferral.ts similarity index 100% rename from src/main/startup/first-window-deferral.ts rename to src/main/startup/main-window/first-window-deferral.ts diff --git a/src/main/startup/main-process-i18n-menu.ts b/src/main/startup/main-window/main-process-i18n-menu.ts similarity index 85% rename from src/main/startup/main-process-i18n-menu.ts rename to src/main/startup/main-window/main-process-i18n-menu.ts index a586fb49562..8478c84e938 100644 --- a/src/main/startup/main-process-i18n-menu.ts +++ b/src/main/startup/main-window/main-process-i18n-menu.ts @@ -1,14 +1,14 @@ import { app, BrowserWindow } from 'electron' -import { setMainUiLanguage } from '../i18n/main-i18n' +import { setMainUiLanguage } from '../../i18n/main-i18n' import { registerAppMenu, rebuildAppMenu, getNextDefaultOnAppearanceSettingValue -} from '../menu/register-app-menu' -import { zoomDashboardPopoutIfFocused } from '../window/dashboard-popout-window' -import { zoomWorkspaceSpaceWindowIfFocused } from '../window/workspace-space-window' -import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' -import { mainProcessState as state } from './main-process-state' +} from '../../menu/register-app-menu' +import { zoomDashboardPopoutIfFocused } from '../../window/dashboard-popout-window' +import { zoomWorkspaceSpaceWindowIfFocused } from '../../window/workspace-space-window' +import { recordCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { mainProcessState as state } from '../main-process-state' import { getAppMenuQuitHandlers, openSettingsFromSystemMenu, @@ -17,9 +17,9 @@ import { sendOpenFeatureTour, sendOpenSetupGuide } from './main-window-actions' -import { ensureAutoUpdaterConfigured } from '../window/attach-main-window-services' -import { logStartupMilestone } from './startup-diagnostics' -import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' +import { ensureAutoUpdaterConfigured } from '../../updater/lifecycle/main-window-updater' +import { logStartupMilestone } from '../diagnostics/startup-diagnostics' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' export async function initializeMainProcessI18nAndMenu(): Promise { const store = state.store diff --git a/src/main/startup/main-window-actions-quit-and-stop-all-sessions.test.ts b/src/main/startup/main-window/main-window-actions-quit-and-stop-all-sessions.test.ts similarity index 76% rename from src/main/startup/main-window-actions-quit-and-stop-all-sessions.test.ts rename to src/main/startup/main-window/main-window-actions-quit-and-stop-all-sessions.test.ts index f4af590118f..138e953b20d 100644 --- a/src/main/startup/main-window-actions-quit-and-stop-all-sessions.test.ts +++ b/src/main/startup/main-window/main-window-actions-quit-and-stop-all-sessions.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { confirmQuitAndStopAllSessions, explainStopAllSessionsUnavailable -} from './quit-and-stop-all-sessions-prompt' +} from '../quit/quit-and-stop-all-sessions-prompt' const electron = vi.hoisted(() => ({ quit: vi.fn(), showMessageBox: vi.fn() })) const prompt = vi.hoisted(() => ({ @@ -19,49 +19,55 @@ vi.mock('electron', () => ({ app: { quit: electron.quit }, dialog: { showMessageBox: electron.showMessageBox } })) -vi.mock('./quit-and-stop-all-sessions-prompt', () => ({ +vi.mock('../quit/quit-and-stop-all-sessions-prompt', () => ({ confirmQuitAndStopAllSessions: prompt.confirm, explainStopAllSessionsUnavailable: prompt.explain })) -vi.mock('../daemon/providers/routing/daemon-newer-protocol-hold', () => ({ +vi.mock('../../daemon/providers/routing/daemon-newer-protocol-hold', () => ({ isHoldingForNewerProtocolDaemon: daemon.holdingNewer })) -vi.mock('../daemon/providers/lifecycle/daemon-provider-state', () => ({ +vi.mock('../../daemon/providers/lifecycle/daemon-provider-state', () => ({ getDaemonProvider: daemon.provider })) -vi.mock('../ipc/pty/pty-management', () => ({ +vi.mock('../../ipc/pty/pty-management', () => ({ confirmNoDaemonSessionsRemain: daemon.noSessionsRemain })) -vi.mock('../updater/updater-service', () => ({ +vi.mock('../../updater/updater-service', () => ({ checkForUpdatesFromMenu: vi.fn(), isQuittingForUpdate: vi.fn() })) -vi.mock('../tray/system-tray', () => ({ +vi.mock('../../tray/system-tray', () => ({ createSystemTray: vi.fn(), setMacMenuBarIconVisible: vi.fn() })) -vi.mock('../window/attach-main-window-services', () => ({ ensureAutoUpdaterConfigured: vi.fn() })) -vi.mock('../window/focus-existing-window', () => ({ +vi.mock('../../updater/lifecycle/main-window-updater', () => ({ + ensureAutoUpdaterConfigured: vi.fn() +})) +vi.mock('../../window/activation/focus-existing-window', () => ({ focusExistingMainWindow: vi.fn(), safelyRevealWindow: vi.fn() })) -vi.mock('../window/dashboard-popout-window', () => ({ getDashboardPopoutWindow: () => null })) -vi.mock('../window/createMainWindow', () => ({ loadMainWindow: vi.fn() })) -vi.mock('./windows-install-dir-acl-recovery', () => ({ +vi.mock('../../window/dashboard-popout-window', () => ({ getDashboardPopoutWindow: () => null })) +vi.mock('../../window/createMainWindow', () => ({ loadMainWindow: vi.fn() })) +vi.mock('../windows-install-permissions/windows-install-dir-acl-recovery', () => ({ describeInstallDirAclPoison: vi.fn(), isBlockingInstallDirAclRepairInFlight: vi.fn() })) -vi.mock('../window/renderer-recovery-prompt', () => ({ presentRendererRecoveryPrompt: vi.fn() })) -vi.mock('../window/renderer-launch-failure-probe', () => ({ probeRendererLaunchCapacity: vi.fn() })) +vi.mock('../../window/renderer-recovery/renderer-recovery-prompt', () => ({ + presentRendererRecoveryPrompt: vi.fn() +})) +vi.mock('../../window/renderer-recovery/renderer-launch-failure-probe', () => ({ + probeRendererLaunchCapacity: vi.fn() +})) -import { safelyRevealWindow } from '../window/focus-existing-window' +import { safelyRevealWindow } from '../../window/activation/focus-existing-window' import { consumeQuitAndStopAllSessionsRequest, quitAfterRendererStoppedAllSessions, quitAndStopAllSessionsFromUserCommand } from './main-window-actions' -import { mainProcessState as state } from './main-process-state' -import { quitTeardownStartGate } from './quit/quit-teardown-start-gate' +import { mainProcessState as state } from '../main-process-state' +import { quitTeardownStartGate } from '../quit/quit-teardown-start-gate' const MAIN_WEB_CONTENTS_ID = 7 diff --git a/src/main/startup/main-window-actions.ts b/src/main/startup/main-window/main-window-actions.ts similarity index 85% rename from src/main/startup/main-window-actions.ts rename to src/main/startup/main-window/main-window-actions.ts index e6ad7d3caf8..988d5e75d0a 100644 --- a/src/main/startup/main-window-actions.ts +++ b/src/main/startup/main-window/main-window-actions.ts @@ -8,42 +8,45 @@ import { type Tray, type WebContents } from 'electron' -import { isNativeBrowserPopupWindow } from '../browser/guest-lifecycle/popups/presentation/native-browser-popup-windows' -import type { UpdateCheckOptions } from '../../shared/update-status-types' -import type { AppMenuQuitHandlers } from '../menu/app-menu-quit-item' +import { isNativeBrowserPopupWindow } from '../../browser/guest-lifecycle/popups/presentation/native-browser-popup-windows' +import type { UpdateCheckOptions } from '../../../shared/update-status-types' +import type { AppMenuQuitHandlers } from '../../menu/app-menu-quit-item' import type { createWebContentsTimedFlag } from './web-contents-timed-flag' -import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { checkForUpdatesFromMenu, isQuittingForUpdate } from '../updater/updater-service' +import { recordCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { checkForUpdatesFromMenu, isQuittingForUpdate } from '../../updater/updater-service' import { createSystemTray, setMacMenuBarIconVisible, type SystemTrayOptions -} from '../tray/system-tray' -import { ensureAutoUpdaterConfigured } from '../window/attach-main-window-services' -import { focusExistingMainWindow, safelyRevealWindow } from '../window/focus-existing-window' -import { mainProcessState as state } from './main-process-state' -import { quitTeardownStartGate } from './quit/quit-teardown-start-gate' -import { getDashboardPopoutWindow } from '../window/dashboard-popout-window' -import { getWorkspaceSpaceWindow } from '../window/workspace-space-window' -import { markUserQuitWindowClose } from '../window/user-quit-window-close' -import { loadMainWindow } from '../window/createMainWindow' +} from '../../tray/system-tray' +import { ensureAutoUpdaterConfigured } from '../../updater/lifecycle/main-window-updater' +import { + focusExistingMainWindow, + safelyRevealWindow +} from '../../window/activation/focus-existing-window' +import { mainProcessState as state } from '../main-process-state' +import { quitTeardownStartGate } from '../quit/quit-teardown-start-gate' +import { getDashboardPopoutWindow } from '../../window/dashboard-popout-window' +import { getWorkspaceSpaceWindow } from '../../window/workspace-space-window' +import { markUserQuitWindowClose } from '../../window/main-window/user-quit-window-close' +import { loadMainWindow } from '../../window/createMainWindow' import { describeInstallDirAclPoison, isBlockingInstallDirAclRepairInFlight -} from './windows-install-dir-acl-recovery' +} from '../windows-install-permissions/windows-install-dir-acl-recovery' import { presentRendererRecoveryPrompt, type RendererRecoveryPromptFailure -} from '../window/renderer-recovery-prompt' -import { probeRendererLaunchCapacity } from '../window/renderer-launch-failure-probe' +} from '../../window/renderer-recovery/renderer-recovery-prompt' +import { probeRendererLaunchCapacity } from '../../window/renderer-recovery/renderer-launch-failure-probe' import { confirmQuitAndStopAllSessions, explainStopAllSessionsUnavailable -} from './quit-and-stop-all-sessions-prompt' -import { isHoldingForNewerProtocolDaemon } from '../daemon/providers/routing/daemon-newer-protocol-hold' -import { getDaemonProvider } from '../daemon/providers/lifecycle/daemon-provider-state' -import { confirmNoDaemonSessionsRemain } from '../ipc/pty/pty-management' +} from '../quit/quit-and-stop-all-sessions-prompt' +import { isHoldingForNewerProtocolDaemon } from '../../daemon/providers/routing/daemon-newer-protocol-hold' +import { getDaemonProvider } from '../../daemon/providers/lifecycle/daemon-provider-state' +import { confirmNoDaemonSessionsRemain } from '../../ipc/pty/pty-management' // Inject the opener to avoid an actions/lifecycle import cycle. let openWindow: (options?: { revealOnDidFinishLoad?: boolean }) => BrowserWindow diff --git a/src/main/startup/main-window-agent-status.ts b/src/main/startup/main-window/main-window-agent-status.ts similarity index 84% rename from src/main/startup/main-window-agent-status.ts rename to src/main/startup/main-window/main-window-agent-status.ts index e4e0b994d4e..4fff79f0d70 100644 --- a/src/main/startup/main-window-agent-status.ts +++ b/src/main/startup/main-window/main-window-agent-status.ts @@ -1,10 +1,11 @@ import type { BrowserWindow } from 'electron' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { setMigrationUnsupportedPtyListener } from '../agent-hooks/observations/migration-unsupported-pty-state' -import { getDashboardPopoutWindow } from '../window/dashboard-popout-window' +import { publishedOrcaSessionId } from '../../agent-hooks/identity/pane-agent-identities' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { setMigrationUnsupportedPtyListener } from '../../agent-hooks/observations/migration-unsupported-pty-state' +import { getDashboardPopoutWindow } from '../../window/dashboard-popout-window' import { stopSyntheticTitleSpinnerTimer } from './synthetic-title-runtime' -import { mainProcessState as state } from './main-process-state' -import { pickHostTurnEnd } from '../../shared/agent-status/contracts/agent-status-types' +import { mainProcessState as state } from '../main-process-state' +import { pickHostTurnEnd } from '../../../shared/agent-status/contracts/agent-status-types' export type MainWindowAgentStatusOptions = { window: BrowserWindow @@ -36,6 +37,8 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt structuredHost, programStatus, programStatusOnly, + agentIdentity, + identityOnly, agentPresence }) => { if (state.mainWindow?.isDestroyed()) { @@ -84,6 +87,9 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt ...(turnStartedAt !== undefined ? { turnStartedAt } : {}), ...pickHostTurnEnd({ turnEndedAt, turnEndDisposition }), ...(providerSession ? { providerSession } : {}), + ...(publishedOrcaSessionId(agentIdentity) !== undefined + ? { orcaSessionId: publishedOrcaSessionId(agentIdentity) } + : {}), ...(promptInteractionKey ? { promptInteractionKey } : {}), ...(restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...(observation ? { observation } : {}), @@ -98,8 +104,8 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt } state.mainWindow?.webContents.send('agentStatus:set', statusEvent) getDashboardPopoutWindow()?.webContents.send('agentStatus:set', statusEvent) - // A facet-only republish (progress tick) is not a state the agent entered. - if (programStatusOnly !== true) { + // A facet-only republish (progress tick) or a settled id is not a state the agent entered. + if (programStatusOnly !== true && identityOnly !== true) { options.onRecordAgentState(payload.agentType ?? 'unknown', payload.state) } } diff --git a/src/main/startup/main-window-controller.ts b/src/main/startup/main-window/main-window-controller.ts similarity index 84% rename from src/main/startup/main-window-controller.ts rename to src/main/startup/main-window/main-window-controller.ts index e8366b54d63..1e3e4031df3 100644 --- a/src/main/startup/main-window-controller.ts +++ b/src/main/startup/main-window/main-window-controller.ts @@ -1,29 +1,29 @@ import { app, type BrowserWindow } from 'electron' -import { createMainWindow, loadMainWindow } from '../window/createMainWindow' +import { createMainWindow, loadMainWindow } from '../../window/createMainWindow' import { recordCrashBreadcrumb, recordCoalescedCrashBreadcrumb -} from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-exits/process-gone-classification' -import { resolveConsent } from '../telemetry/consent' -import { trackAppOpenedOnce } from '../telemetry/client' -import { ensureWindowsUserDataAclGrant } from './windows-user-data-acl' -import { probeWindowsInstallDirAcl } from './windows-install-dir-acl-probe' +} from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { shouldRecoverRendererAfterProcessGone } from '../../crash-reporting/process-exits/process-gone-classification' +import { resolveConsent } from '../../telemetry/consent' +import { trackAppOpenedOnce } from '../../telemetry/client' +import { ensureWindowsUserDataAclGrant } from '../windows-startup/windows-user-data-acl' +import { probeWindowsInstallDirAcl } from '../windows-install-permissions/windows-install-dir-acl-probe' import { noteWindowsInstallDirAclProbePending, startWindowsInstallDirAclRepairIfPoisoned -} from './windows-install-dir-acl-recovery' -import { logStartupMilestone } from './startup-diagnostics' -import { notifyMainWindowBecameVisible } from '../window/main-window-visibility' -import { setTrayAttention } from '../tray/system-tray' +} from '../windows-install-permissions/windows-install-dir-acl-recovery' +import { logStartupMilestone } from '../diagnostics/startup-diagnostics' +import { notifyMainWindowBecameVisible } from '../../window/visibility/main-window-visibility' +import { setTrayAttention } from '../../tray/system-tray' import { createSystemTrayDeferred, showRendererRecoveryPrompt } from './main-window-actions' import { attachMainWindowCoreServices } from './main-window-core-services' import { clearMainWindowAgentStatusListeners, installMainWindowAgentStatusListeners } from './main-window-agent-status' -import { mainProcessState as state } from './main-process-state' +import { mainProcessState as state } from '../main-process-state' import { clearExpectedRendererReload, markExpectedRendererReload, @@ -31,20 +31,20 @@ import { getExpectedTeardownScope, recordProcessGoneCrash } from './main-window-lifecycle-flags' -import { presentGpuFallbackRecoveredLaunchPrompt } from './gpu-lifecycle' +import { presentGpuFallbackRecoveredLaunchPrompt } from '../gpu-recovery/gpu-lifecycle' import { resumeSyntheticTitleSpinnerTimer, stopSyntheticTitleSpinnerTimer } from './synthetic-title-runtime' import { requireMainWindowServices } from './main-window-service-readiness' -import { recordRendererLaunchFailureProbe } from '../window/renderer-launch-failure-probe' -import { trackBrowserExtensionMainWindow } from '../browser/extensions/tabs-and-windows/browser-extension-window-model' +import { recordRendererLaunchFailureProbe } from '../../window/renderer-recovery/renderer-launch-failure-probe' +import { trackBrowserExtensionMainWindow } from '../../browser/extensions/tabs-and-windows/browser-extension-window-model' -import { isResourceWindowVisible } from '../window/resource-view-admission' +import { isResourceWindowVisible } from '../../window/visibility/resource-view-admission' import { applyBackgroundActivationPolicy, applyServeDesktopWindowActivationPolicy -} from '../window/foreground-activation-policy' +} from '../../window/activation/foreground-activation-policy' const TRAY_CREATE_FALLBACK_MS = 12_000 const AGENT_STATE_CRASH_BREADCRUMB_MIN_INTERVAL_MS = 30_000 diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window/main-window-core-services.ts similarity index 78% rename from src/main/startup/main-window-core-services.ts rename to src/main/startup/main-window/main-window-core-services.ts index 5e997750b2b..ac215606b70 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window/main-window-core-services.ts @@ -1,28 +1,28 @@ import type { BrowserWindow } from 'electron' -import { registerCoreHandlers } from '../ipc/register-core-handlers/register-core-handlers' -import { attachMainWindowServices } from '../window/attach-main-window-services' -import { initTccPromptNotice } from '../macos-permissions/macos-tcc-prompt-notice' -import { resolveUpdateInstallMode } from '../updater/updater-service' -import { desktopConnectorCloud } from './main-process-connector-startup' -import { mainProcessState as state } from './main-process-state' -import { prepareCodexAiVaultSessionResume } from '../codex/history/resume/codex-ai-vault-session-resume' -import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { preserveAgentAuthBeforeRestart } from '../providers/accounts/agent-auth-restart-preservation' -import { preserveStateBeforeUpdateRestart } from '../updater/update-restart-preservation' +import { registerCoreHandlers } from '../../ipc/register-core-handlers/register-core-handlers' +import { attachMainWindowServices } from '../../window/attach-main-window-services' +import { initTccPromptNotice } from '../../macos-permissions/macos-tcc-prompt-notice' +import { resolveUpdateInstallMode } from '../../updater/updater-service' +import { desktopConnectorCloud } from '../cloud-startup/main-process-connector-startup' +import { mainProcessState as state } from '../main-process-state' +import { prepareCodexAiVaultSessionResume } from '../../codex/history/resume/codex-ai-vault-session-resume' +import { resolveHostCodexSessionSourceHome } from '../../codex/history/rollouts/codex-session-source-home' +import { preserveAgentAuthBeforeRestart } from '../../providers/accounts/agent-auth-restart-preservation' +import { preserveStateBeforeUpdateRestart } from '../../updater/update-restart-preservation' import { emitPluginWorktreeLifecycle, handleCodexHomePtySpawned, handlePtyExit -} from './main-process-pty-startup' -import { prepareCodexRuntimeHomeForLaunch } from './codex-launch-preparation' -import { resolveHostAgentBaseEnvironment } from '../runtime/agent-session/environment/structured-agent-shell-environment' +} from '../pty-startup/main-process-pty-startup' +import { prepareCodexRuntimeHomeForLaunch } from '../agent-accounts/codex-launch-preparation' +import { resolveHostAgentBaseEnvironment } from '../../runtime/agent-session/environment/structured-agent-shell-environment' import { prepareCodexPinnedLaunchHome, prepareCodexSessionResumeForLaunch -} from './codex-session-resume-launch' +} from '../agent-accounts/codex-session-resume-launch' import { isRecoveryReloadInFlight } from './main-window-lifecycle-flags' -import { RELAY_HOST_CLOSE_REASON } from '../../shared/relay-host-close-reason' -import { holdLaunchReconnectOptOuts } from '../ipc/ssh/ssh-host-user-disconnect' +import { RELAY_HOST_CLOSE_REASON } from '../../../shared/relay-host-close-reason' +import { holdLaunchReconnectOptOuts } from '../../ipc/ssh/ssh-host-user-disconnect' export function attachMainWindowCoreServices( window: BrowserWindow, diff --git a/src/main/startup/main-window-lifecycle-flags.ts b/src/main/startup/main-window/main-window-lifecycle-flags.ts similarity index 79% rename from src/main/startup/main-window-lifecycle-flags.ts rename to src/main/startup/main-window/main-window-lifecycle-flags.ts index d469966e990..64cc5c00fdf 100644 --- a/src/main/startup/main-window-lifecycle-flags.ts +++ b/src/main/startup/main-window/main-window-lifecycle-flags.ts @@ -1,8 +1,8 @@ -import { resolveExpectedTeardownScope } from '../crash-reporting/process-exits/expected-teardown-state' -import type { ExpectedTeardownScope } from '../crash-reporting/process-exits/process-gone-classification' -import { recordProcessGoneCrash as recordProcessGoneCrashEvent } from '../crash-reporting/process-exits/process-gone-recorder' -import { isQuittingForUpdate } from '../updater/updater-service' -import { mainProcessState as state } from './main-process-state' +import { resolveExpectedTeardownScope } from '../../crash-reporting/process-exits/expected-teardown-state' +import type { ExpectedTeardownScope } from '../../crash-reporting/process-exits/process-gone-classification' +import { recordProcessGoneCrash as recordProcessGoneCrashEvent } from '../../crash-reporting/process-exits/process-gone-recorder' +import { isQuittingForUpdate } from '../../updater/updater-service' +import { mainProcessState as state } from '../main-process-state' export function markExpectedRendererReload(webContentsId: number, durationMs = 10_000): void { state.expectedRendererReload.mark(webContentsId, durationMs) diff --git a/src/main/startup/main-window-service-readiness.ts b/src/main/startup/main-window/main-window-service-readiness.ts similarity index 100% rename from src/main/startup/main-window-service-readiness.ts rename to src/main/startup/main-window/main-window-service-readiness.ts diff --git a/src/main/startup/synthetic-title-runtime.ts b/src/main/startup/main-window/synthetic-title-runtime.ts similarity index 92% rename from src/main/startup/synthetic-title-runtime.ts rename to src/main/startup/main-window/synthetic-title-runtime.ts index d4a78ac35bb..284110aa61e 100644 --- a/src/main/startup/synthetic-title-runtime.ts +++ b/src/main/startup/main-window/synthetic-title-runtime.ts @@ -1,21 +1,21 @@ -import { registerPaneKeyTeardownListener, getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import type { AgentStatusState } from '../../shared/agent-status/contracts/agent-status-types' -import { normalizeTerminalTitle } from '../../shared/agent-status/title/agent-title-status' +import { registerPaneKeyTeardownListener, getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import type { AgentStatusState } from '../../../shared/agent-status/contracts/agent-status-types' +import { normalizeTerminalTitle } from '../../../shared/agent-status/title/agent-title-status' import { getSyntheticAgentTitleProfile, shouldDriveSyntheticAgentTitleFromHook, type SyntheticAgentTitleProfile -} from '../../shared/agent-status/title/synthetic-agent-title' +} from '../../../shared/agent-status/title/synthetic-agent-title' import { advanceSyntheticTitleSpinnerEntries, getSyntheticTitleSpinnerPaneKeyToStop, type SyntheticTitleSpinnerEntry -} from '../runtime/terminal/title/synthetic-title-spinner' -import { shouldSendSyntheticTitleFrame } from '../runtime/terminal/title/synthetic-title-visibility' -import { shouldCopySyntheticTitleFrameToPtyData } from '../runtime/terminal/title/synthetic-title-frame-routing' -import { mainProcessState as state } from './main-process-state' -import { CODEX_ASYNC_QUESTION_TOOL } from '../../shared/codex-async-question-input' +} from '../../runtime/terminal/title/synthetic-title-spinner' +import { shouldSendSyntheticTitleFrame } from '../../runtime/terminal/title/synthetic-title-visibility' +import { shouldCopySyntheticTitleFrameToPtyData } from '../../runtime/terminal/title/synthetic-title-frame-routing' +import { mainProcessState as state } from '../main-process-state' +import { CODEX_ASYNC_QUESTION_TOOL } from '../../../shared/codex-async-question-input' // Agent redraws can overwrite one-shot OSC titles; reassert at Pi's 80ms cadence. const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] diff --git a/src/main/startup/web-contents-timed-flag.ts b/src/main/startup/main-window/web-contents-timed-flag.ts similarity index 100% rename from src/main/startup/web-contents-timed-flag.ts rename to src/main/startup/main-window/web-contents-timed-flag.ts diff --git a/src/main/startup/http1-compatibility-marker.ts b/src/main/startup/network-compatibility/http1-compatibility-marker.ts similarity index 93% rename from src/main/startup/http1-compatibility-marker.ts rename to src/main/startup/network-compatibility/http1-compatibility-marker.ts index 54da41194e9..e4c99724cd3 100644 --- a/src/main/startup/http1-compatibility-marker.ts +++ b/src/main/startup/network-compatibility/http1-compatibility-marker.ts @@ -1,7 +1,7 @@ import { readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' -import { durableWriteTempPath, writeFileDurableSync } from '../filesystem/durable-file-write' -import { bestEffortFsyncDirectorySync } from '../../shared/secure-storage/secure-file' +import { durableWriteTempPath, writeFileDurableSync } from '../../filesystem/durable-file-write' +import { bestEffortFsyncDirectorySync } from '../../../shared/secure-storage/secure-file' /** A tiny profile-scoped marker selects HTTP/2 before the first Electron session without reparsing multi-MB settings before Store startup. Profile identity prevents cross-profile reuse. */ diff --git a/src/main/startup/http1-compatibility-profile-state.ts b/src/main/startup/network-compatibility/http1-compatibility-profile-state.ts similarity index 89% rename from src/main/startup/http1-compatibility-profile-state.ts rename to src/main/startup/network-compatibility/http1-compatibility-profile-state.ts index 97e714f1e2c..88230ae75bd 100644 --- a/src/main/startup/http1-compatibility-profile-state.ts +++ b/src/main/startup/network-compatibility/http1-compatibility-profile-state.ts @@ -1,9 +1,9 @@ import { existsSync, readFileSync } from 'node:fs' import { dirname, join } from 'node:path' -import { profileStateJsonExportPaths } from '../persistence/profile-state/legacy-json/profile-state-export-path' -import { hasProfileStateAuthorityMarker } from '../persistence/profile-state/database/profile-state-authority-marker' -import { profileStateDatabaseBackups } from '../persistence/profile-state/backup/profile-state-backup-path' -import { hasProfileStateDatabaseFiles } from '../persistence/profile-state/database/profile-state-storage-classification' +import { profileStateJsonExportPaths } from '../../persistence/profile-state/legacy-json/profile-state-export-path' +import { hasProfileStateAuthorityMarker } from '../../persistence/profile-state/database/profile-state-authority-marker' +import { profileStateDatabaseBackups } from '../../persistence/profile-state/backup/profile-state-backup-path' +import { hasProfileStateDatabaseFiles } from '../../persistence/profile-state/database/profile-state-storage-classification' // Keep the pre-ready graph small; this stable ID mirrors DEFAULT_LOCAL_ORCA_PROFILE_ID. const DEFAULT_LOCAL_PROFILE_ID = 'local-default' diff --git a/src/main/startup/open-routing/orca-deep-link-url.ts b/src/main/startup/open-routing/orca-deep-link-url.ts new file mode 100644 index 00000000000..5f386db779d --- /dev/null +++ b/src/main/startup/open-routing/orca-deep-link-url.ts @@ -0,0 +1,7 @@ +import { isPluginInstallLinkArgument } from '../../../shared/plugins/catalog/plugin-install-link' +import { parseSkillShareId } from '../../../shared/skill-share-link' + +/** macOS open-url: claim only links Orca routes, so other schemes keep their default handling. */ +export function isRoutedOrcaDeepLink(url: string): boolean { + return parseSkillShareId(url) !== null || isPluginInstallLinkArgument(url) +} diff --git a/src/main/startup/orca-protocol-registration.ts b/src/main/startup/open-routing/orca-protocol-registration.ts similarity index 100% rename from src/main/startup/orca-protocol-registration.ts rename to src/main/startup/open-routing/orca-protocol-registration.ts diff --git a/src/main/startup/os-opened-document-resolution.test.ts b/src/main/startup/open-routing/os-opened-document-resolution.test.ts similarity index 92% rename from src/main/startup/os-opened-document-resolution.test.ts rename to src/main/startup/open-routing/os-opened-document-resolution.test.ts index 50d10d338ec..cc79d35ee09 100644 --- a/src/main/startup/os-opened-document-resolution.test.ts +++ b/src/main/startup/open-routing/os-opened-document-resolution.test.ts @@ -4,11 +4,12 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { resolveOsOpenedDocuments } from './os-opened-documents' -vi.mock('../ipc/floating-workspace-directory', () => ({ +vi.mock('../../ipc/floating-workspace-directory', () => ({ ensureDefaultFloatingWorkspacePath: vi.fn() })) -const { ensureDefaultFloatingWorkspacePath } = await import('../ipc/floating-workspace-directory') +const { ensureDefaultFloatingWorkspacePath } = + await import('../../ipc/floating-workspace-directory') describe('resolveOsOpenedDocuments', () => { let floatingRoot: string diff --git a/src/main/startup/open-routing/os-opened-documents.test.ts b/src/main/startup/open-routing/os-opened-documents.test.ts new file mode 100644 index 00000000000..12063024ee0 --- /dev/null +++ b/src/main/startup/open-routing/os-opened-documents.test.ts @@ -0,0 +1,28 @@ +import { resolve, sep } from 'node:path' +import { describe, expect, it } from 'vitest' +import { OsOpenedDocumentState } from './os-opened-documents' + +// Normalize fixture paths with host rules, including Windows drive/separators. +const hostPath = (name: string): string => resolve(sep, 'notes', name) + +describe('OsOpenedDocumentState', () => { + it('does not duplicate a path captured twice', () => { + const state = new OsOpenedDocumentState() + const filePath = hostPath('a.csv') + + state.captureFilePaths([filePath]) + state.captureFilePaths([filePath]) + state.capture(['orca', filePath]) + + expect(state.consume()).toEqual([filePath]) + }) + + it('restores an undelivered batch at the front of the buffer', () => { + const state = new OsOpenedDocumentState() + state.captureFilePaths([hostPath('later.md')]) + + state.restore([hostPath('undelivered.md')]) + + expect(state.consume()).toEqual([hostPath('undelivered.md'), hostPath('later.md')]) + }) +}) diff --git a/src/main/startup/os-opened-documents.ts b/src/main/startup/open-routing/os-opened-documents.ts similarity index 95% rename from src/main/startup/os-opened-documents.ts rename to src/main/startup/open-routing/os-opened-documents.ts index 1e8287d02a9..dfe20bcc1d2 100644 --- a/src/main/startup/os-opened-documents.ts +++ b/src/main/startup/open-routing/os-opened-documents.ts @@ -1,12 +1,12 @@ import { stat } from 'node:fs/promises' import path from 'node:path' import { fileURLToPath } from 'node:url' -import type { FileDocument } from '../../shared/file-listing/file-document' -import { ensureDefaultFloatingWorkspacePath } from '../ipc/floating-workspace-directory' +import type { FileDocument } from '../../../shared/file-listing/file-document' +import { ensureDefaultFloatingWorkspacePath } from '../../ipc/floating-workspace-directory' import { fileDocumentFromFilePath, isMarkdownDocumentName -} from '../../shared/file-listing/markdown-document-paths' +} from '../../../shared/file-listing/markdown-document-paths' export function isOsOpenedDocumentName(name: string): boolean { const extension = path.extname(name).toLowerCase() diff --git a/src/main/startup/open-routing/plugin-install-link-state.test.ts b/src/main/startup/open-routing/plugin-install-link-state.test.ts new file mode 100644 index 00000000000..669985290d8 --- /dev/null +++ b/src/main/startup/open-routing/plugin-install-link-state.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it, vi } from 'vitest' +import { PluginInstallLinkState } from './skill-share-deep-link-state' +import { isRoutedOrcaDeepLink } from './orca-deep-link-url' + +const LINK = 'orca://plugins/acme.dusk?catalog=community' + +describe('PluginInstallLinkState', () => { + it('queues a cold-start link until the renderer pulls it', () => { + const state = new PluginInstallLinkState() + expect(state.capture(['/Applications/Orca.app/Contents/MacOS/Orca', LINK])).toBe(true) + expect(state.consume()).toBe(LINK) + expect(state.consume()).toBeNull() + }) + + it('publishes a second-instance link and keeps malformed ones for the error toast', () => { + const state = new PluginInstallLinkState() + const publish = vi.fn() + expect(state.capture(['orca.exe', 'orca://plugins/not valid'], publish)).toBe(true) + expect(publish).toHaveBeenCalledWith('orca://plugins/not valid') + expect(state.capture(['orca.exe', '--flag'], publish)).toBe(false) + }) +}) + +describe('isRoutedOrcaDeepLink', () => { + it('claims plugin and skill links on macOS open-url, nothing else', () => { + expect(isRoutedOrcaDeepLink(LINK)).toBe(true) + expect(isRoutedOrcaDeepLink('orca://plugins/bad')).toBe(true) + expect(isRoutedOrcaDeepLink('orca://skills/share/abc_1')).toBe(true) + expect(isRoutedOrcaDeepLink('orca://pair?code=x')).toBe(false) + expect(isRoutedOrcaDeepLink('https://example.com/plugins/acme.dusk')).toBe(false) + }) +}) diff --git a/src/main/startup/skill-share-deep-link-state.test.ts b/src/main/startup/open-routing/skill-share-deep-link-state.test.ts similarity index 100% rename from src/main/startup/skill-share-deep-link-state.test.ts rename to src/main/startup/open-routing/skill-share-deep-link-state.test.ts diff --git a/src/main/startup/skill-share-deep-link-state.ts b/src/main/startup/open-routing/skill-share-deep-link-state.ts similarity index 88% rename from src/main/startup/skill-share-deep-link-state.ts rename to src/main/startup/open-routing/skill-share-deep-link-state.ts index 9d58f3d6824..baa00e0d1c7 100644 --- a/src/main/startup/skill-share-deep-link-state.ts +++ b/src/main/startup/open-routing/skill-share-deep-link-state.ts @@ -1,5 +1,5 @@ -import { pluginInstallLinkFromArguments } from '../../shared/plugins/catalog/plugin-install-link' -import { skillShareIdFromArguments } from '../../shared/skill-share-link' +import { pluginInstallLinkFromArguments } from '../../../shared/plugins/catalog/plugin-install-link' +import { skillShareIdFromArguments } from '../../../shared/skill-share-link' const REPEAT_WINDOW_MS = 3_000 const BURST_LIMIT = 5 diff --git a/src/main/startup/orca-deep-link-url.ts b/src/main/startup/orca-deep-link-url.ts deleted file mode 100644 index 528425c05c4..00000000000 --- a/src/main/startup/orca-deep-link-url.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { isPluginInstallLinkArgument } from '../../shared/plugins/catalog/plugin-install-link' -import { parseSkillShareId } from '../../shared/skill-share-link' - -/** macOS open-url: claim only links Orca routes, so other schemes keep their default handling. */ -export function isRoutedOrcaDeepLink(url: string): boolean { - return parseSkillShareId(url) !== null || isPluginInstallLinkArgument(url) -} diff --git a/src/main/startup/os-opened-documents.test.ts b/src/main/startup/os-opened-documents.test.ts deleted file mode 100644 index 684ed8755be..00000000000 --- a/src/main/startup/os-opened-documents.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { resolve, sep } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { MAX_PENDING_OS_OPENED_DOCUMENTS, OsOpenedDocumentState } from './os-opened-documents' - -// Normalize fixture paths with host rules, including Windows drive/separators. -const hostPath = (name: string): string => resolve(sep, 'notes', name) - -describe('OsOpenedDocumentState', () => { - it('does not duplicate a path captured twice', () => { - const state = new OsOpenedDocumentState() - const filePath = hostPath('a.csv') - - state.captureFilePaths([filePath]) - state.captureFilePaths([filePath]) - state.capture(['orca', filePath]) - - expect(state.consume()).toEqual([filePath]) - }) - - it('restores an undelivered batch at the front of the buffer', () => { - const state = new OsOpenedDocumentState() - state.captureFilePaths([hostPath('later.md')]) - - state.restore([hostPath('undelivered.md')]) - - expect(state.consume()).toEqual([hostPath('undelivered.md'), hostPath('later.md')]) - }) - - it('caps the buffer when a restore overflows it', () => { - const state = new OsOpenedDocumentState() - state.captureFilePaths([hostPath('pending.md')]) - const restored = Array.from({ length: MAX_PENDING_OS_OPENED_DOCUMENTS }, (_, index) => - hostPath(`restored-${index}.md`) - ) - - state.restore(restored) - - const pending = state.consume() - expect(pending).toHaveLength(MAX_PENDING_OS_OPENED_DOCUMENTS) - expect(pending).toEqual(restored) - }) -}) - -describe('OsOpenedDocumentState delivery cap', () => { - // Queue limits drop explicit user selections; pin shell order and require diagnostics for lost tail entries. - it('keeps the first paths in shell order and reports the dropped tail', () => { - const state = new OsOpenedDocumentState() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const total = MAX_PENDING_OS_OPENED_DOCUMENTS + 8 - const paths = Array.from({ length: total }, (_, index) => - resolve(`/notes/${String(index).padStart(3, '0')}.md`) - ) - try { - expect(state.captureFilePaths(paths)).toBe(true) - expect(warn).toHaveBeenCalledWith( - expect.stringContaining(`Dropped 8 of ${total} OS-opened documents`) - ) - } finally { - warn.mockRestore() - } - expect(state.consume()).toEqual(paths.slice(0, MAX_PENDING_OS_OPENED_DOCUMENTS)) - }) - - it('reports a drop when an already-full queue rejects a later batch', () => { - const state = new OsOpenedDocumentState() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - state.captureFilePaths( - Array.from({ length: MAX_PENDING_OS_OPENED_DOCUMENTS }, (_, index) => - resolve(`/first/${index}.md`) - ) - ) - expect(warn).not.toHaveBeenCalled() - state.captureFilePaths([resolve('/second/a.md'), resolve('/second/b.md')]) - expect(warn).toHaveBeenCalledWith(expect.stringContaining('Dropped 2 of 2')) - } finally { - warn.mockRestore() - } - expect(state.consume()).toEqual( - Array.from({ length: MAX_PENDING_OS_OPENED_DOCUMENTS }, (_, index) => - resolve(`/first/${index}.md`) - ) - ) - }) -}) diff --git a/src/main/startup/plugin-install-link-state.test.ts b/src/main/startup/plugin-install-link-state.test.ts deleted file mode 100644 index 56bbc158c0c..00000000000 --- a/src/main/startup/plugin-install-link-state.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { PluginInstallLinkState } from './skill-share-deep-link-state' -import { isRoutedOrcaDeepLink } from './orca-deep-link-url' - -const LINK = 'orca://plugins/acme.dusk?catalog=community' - -describe('PluginInstallLinkState', () => { - it('queues a cold-start link until the renderer pulls it', () => { - const state = new PluginInstallLinkState() - expect(state.capture(['/Applications/Orca.app/Contents/MacOS/Orca', LINK])).toBe(true) - expect(state.consume()).toBe(LINK) - expect(state.consume()).toBeNull() - }) - - it('publishes a second-instance link and keeps malformed ones for the error toast', () => { - const state = new PluginInstallLinkState() - const publish = vi.fn() - expect(state.capture(['orca.exe', 'orca://plugins/not valid'], publish)).toBe(true) - expect(publish).toHaveBeenCalledWith('orca://plugins/not valid') - expect(state.capture(['orca.exe', '--flag'], publish)).toBe(false) - }) - - it('drops repeats and bursts', () => { - let now = 0 - const state = new PluginInstallLinkState(() => now) - const publish = vi.fn() - state.capture([LINK], publish) - state.capture([LINK], publish) - expect(publish).toHaveBeenCalledTimes(1) - for (let index = 0; index < 10; index += 1) { - state.capture([`orca://plugins/acme.p${index}`], publish) - } - expect(publish).toHaveBeenCalledTimes(5) - now = 5_000 - state.capture([LINK], publish) - expect(publish).toHaveBeenCalledTimes(6) - }) -}) - -describe('isRoutedOrcaDeepLink', () => { - it('claims plugin and skill links on macOS open-url, nothing else', () => { - expect(isRoutedOrcaDeepLink(LINK)).toBe(true) - expect(isRoutedOrcaDeepLink('orca://plugins/bad')).toBe(true) - expect(isRoutedOrcaDeepLink('orca://skills/share/abc_1')).toBe(true) - expect(isRoutedOrcaDeepLink('orca://pair?code=x')).toBe(false) - expect(isRoutedOrcaDeepLink('https://example.com/plugins/acme.dusk')).toBe(false) - }) -}) diff --git a/src/main/startup/plugin-startup/main-process-plugin-rpc.ts b/src/main/startup/plugin-startup/main-process-plugin-rpc.ts new file mode 100644 index 00000000000..b4400dcf9a7 --- /dev/null +++ b/src/main/startup/plugin-startup/main-process-plugin-rpc.ts @@ -0,0 +1,33 @@ +import type { Store } from '../../persistence/loading-store/store' +import { applyPluginConsent, applyPluginEnablement } from '../../plugins/plugin-enablement' +import type { PluginService } from '../../plugins/plugin-service' +import type { PluginCliCatalogs } from '../../plugins/plugin-cli-catalog-candidates' +import { clearPluginFrameStorage } from '../../plugins/panels/guest-isolation/plugin-frame-guest-sessions' +import { openPluginFrameGuestDevTools } from '../../plugins/panels/guest-isolation/plugin-frame-guest-diagnostics' +import { setPluginServiceForRpc } from '../../runtime/rpc/methods/plugins/plugins' +import { setPluginInstallServicesForRpc } from '../../runtime/rpc/methods/plugins/plugin-install-methods' + +/** Headless RPC resolves these too; consent shares the desktop hash-keyed write path. */ +export function bindPluginRpcServices( + store: Store, + pluginService: PluginService, + catalogs: PluginCliCatalogs +): void { + setPluginServiceForRpc(pluginService, { + applyConsent: (request) => applyPluginConsent({ store, pluginService, ...request }), + applyEnablement: (pluginKey, enabled) => + applyPluginEnablement({ store, pluginService, pluginKey, enabled }), + setPluginSystemEnabled: (pluginSystemEnabled) => + store.updateSettings({ pluginSystemEnabled }, { notifyListeners: true }), + setDevPluginPaths: (devPluginPaths) => + store.updateSettings({ devPluginPaths }, { notifyListeners: true }), + openFrameDevTools: openPluginFrameGuestDevTools + }) + setPluginInstallServicesForRpc({ + pluginService, + catalogs, + applyConsent: (request) => applyPluginConsent({ store, pluginService, ...request }), + store, + afterUninstall: clearPluginFrameStorage + }) +} diff --git a/src/main/startup/main-process-plugins.ts b/src/main/startup/plugin-startup/main-process-plugins.ts similarity index 79% rename from src/main/startup/main-process-plugins.ts rename to src/main/startup/plugin-startup/main-process-plugins.ts index 39c43791044..22dc5d33ad9 100644 --- a/src/main/startup/main-process-plugins.ts +++ b/src/main/startup/plugin-startup/main-process-plugins.ts @@ -1,52 +1,52 @@ import { join } from 'node:path' -import { PluginImageCache } from '../plugins/plugin-image-cache' -import { installPluginImageProtocolHandler } from '../plugins/plugin-image-protocol' -import { getPluginDesktopFrameServices } from '../plugins/panels/desktop-actions/plugin-frame-desktop-services' -import { pluginHostVersion } from '../../shared/plugins/installation/plugin-host-version' +import { PluginImageCache } from '../../plugins/plugin-image-cache' +import { installPluginImageProtocolHandler } from '../../plugins/plugin-image-protocol' +import { getPluginDesktopFrameServices } from '../../plugins/panels/desktop-actions/plugin-frame-desktop-services' +import { pluginHostVersion } from '../../../shared/plugins/installation/plugin-host-version' import { app, BrowserWindow, net } from 'electron' import { performance } from 'node:perf_hooks' -import { PluginService } from '../plugins/plugin-service' -import { PluginKillListService } from '../plugins/catalog/plugin-kill-list-service' -import { PluginInstallStatsService } from '../plugins/catalog/plugin-install-stats-service' -import { PluginMarketplaceService } from '../plugins/catalog/plugin-marketplace-service' -import { PluginMarketplaceInstaller } from '../plugins/catalog/plugin-marketplace-installer' -import { PluginAutoUpdater } from '../plugins/catalog/plugin-auto-updater' -import { PluginReleaseFirstSeenStore } from '../plugins/catalog/plugin-release-first-seen-store' -import { PluginUpdateReviewNotices } from '../plugins/catalog/plugin-update-review-notices' -import { isPluginAutoUpdateOn } from '../../shared/plugins/catalog/plugin-update-policy' -import { PluginBundledBootstrapCoordinator } from '../plugins/plugin-bundled-bootstrap-coordinator' -import { getPluginsDataDir } from '../plugins/plugin-discovery' -import { bundledPluginRootForApp } from '../plugins/plugin-bundled-bootstrap' -import { approveBundledPluginsFromStore } from '../plugins/plugin-bundled-approval' -import { resolvePluginHostEntryPath } from '../plugins/workers/parent-process/plugin-host-process' -import { applyPluginConsent, revokePluginConsent } from '../plugins/plugin-enablement' -import { clearRemovedPluginSettings } from '../plugins/plugin-removal-settings' -import { clearPluginFrameStorage } from '../plugins/panels/guest-isolation/plugin-frame-guest-sessions' +import { PluginService } from '../../plugins/plugin-service' +import { PluginKillListService } from '../../plugins/catalog/plugin-kill-list-service' +import { PluginInstallStatsService } from '../../plugins/catalog/plugin-install-stats-service' +import { PluginMarketplaceService } from '../../plugins/catalog/plugin-marketplace-service' +import { PluginMarketplaceInstaller } from '../../plugins/catalog/plugin-marketplace-installer' +import { PluginAutoUpdater } from '../../plugins/catalog/plugin-auto-updater' +import { PluginReleaseFirstSeenStore } from '../../plugins/catalog/plugin-release-first-seen-store' +import { PluginUpdateReviewNotices } from '../../plugins/catalog/plugin-update-review-notices' +import { isPluginAutoUpdateOn } from '../../../shared/plugins/catalog/plugin-update-policy' +import { PluginBundledBootstrapCoordinator } from '../../plugins/plugin-bundled-bootstrap-coordinator' +import { getPluginsDataDir } from '../../plugins/plugin-discovery' +import { bundledPluginRootForApp } from '../../plugins/plugin-bundled-bootstrap' +import { approveBundledPluginsFromStore } from '../../plugins/plugin-bundled-approval' +import { resolvePluginHostEntryPath } from '../../plugins/workers/parent-process/plugin-host-process' +import { applyPluginConsent, revokePluginConsent } from '../../plugins/plugin-enablement' +import { clearRemovedPluginSettings } from '../../plugins/plugin-removal-settings' +import { clearPluginFrameStorage } from '../../plugins/panels/guest-isolation/plugin-frame-guest-sessions' import { bindPluginRpcServices } from './main-process-plugin-rpc' -import { bindPluginDesktopViews } from '../plugins/view/plugin-view-desktop-binding' +import { bindPluginDesktopViews } from '../../plugins/view/plugin-view-desktop-binding' import { normalizePluginConsents, normalizePluginIdList -} from '../../shared/plugins/approval/plugin-consent-state' -import { projectPluginAgentStatusChangedPayload } from '../plugins/plugin-agent-status-event' -import { setMainPluginLanguagePacks, setMainUiLanguage } from '../i18n/main-i18n' -import { isUsablePluginLanguagePack } from '../../shared/plugins/languages/plugin-language-pack-coverage' -import { rebuildAppMenu } from '../menu/register-app-menu' -import { rebuildSystemTrayMenu } from '../tray/system-tray' -import { logStartupMilestone } from './startup-diagnostics' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +} from '../../../shared/plugins/approval/plugin-consent-state' +import { projectPluginAgentStatusChangedPayload } from '../../plugins/plugin-agent-status-event' +import { setMainPluginLanguagePacks, setMainUiLanguage } from '../../i18n/main-i18n' +import { isUsablePluginLanguagePack } from '../../../shared/plugins/languages/plugin-language-pack-coverage' +import { rebuildAppMenu } from '../../menu/register-app-menu' +import { rebuildSystemTrayMenu } from '../../tray/system-tray' +import { logStartupMilestone } from '../diagnostics/startup-diagnostics' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { bindPluginRuntime, createPluginAgentStatusForwarder, watchPluginWorkspaceContext -} from '../plugins/plugin-runtime-binding' -import { emitPluginWorktreeLifecycle } from './main-process-pty-startup' -import { mainProcessState as state } from './main-process-state' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { PluginStatusBarState } from '../plugins/status-bar/plugin-status-bar-state' -import { createDesktopPluginAppearance } from '../plugins/appearance/desktop-plugin-appearance' -import { bindPluginEditorTypography } from '../plugins/appearance/plugin-editor-typography' -import { ALL_RPC_METHODS } from '../runtime/rpc/methods/rpc-method-registry' +} from '../../plugins/plugin-runtime-binding' +import { emitPluginWorktreeLifecycle } from '../pty-startup/main-process-pty-startup' +import { mainProcessState as state } from '../main-process-state' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { PluginStatusBarState } from '../../plugins/status-bar/plugin-status-bar-state' +import { createDesktopPluginAppearance } from '../../plugins/appearance/desktop-plugin-appearance' +import { bindPluginEditorTypography } from '../../plugins/appearance/plugin-editor-typography' +import { ALL_RPC_METHODS } from '../../runtime/rpc/methods/rpc-method-registry' const PLUGIN_AUTO_UPDATE_STARTUP_DELAY_MS = 60_000 // Why: the official catalog fetch must not compete with first paint; opening the marketplace seeds sooner. @@ -298,7 +298,7 @@ export async function initializeMainProcessPlugins(runtime: OrcaRuntimeService): // Filter hook/worktree events server-side by each plugin subscription. const forwardAgentStatus = createPluginAgentStatusForwarder(pluginDelegate, pluginService) agentHookServer.subscribeEnrichedStatus((enriched) => { - const payload = projectPluginAgentStatusChangedPayload(enriched) + const payload = projectPluginAgentStatusChangedPayload(enriched, store) if (payload) { forwardAgentStatus(payload, enriched.terminalHandle) } diff --git a/src/main/startup/privileged-custom-schemes.ts b/src/main/startup/privileged-custom-schemes.ts deleted file mode 100644 index 89dd69adaa1..00000000000 --- a/src/main/startup/privileged-custom-schemes.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../browser/extensions/api-runtime/browser-extension-api-scheme' -import { JIRA_IMAGE_CUSTOM_SCHEME } from '../jira/attachments/image-protocol' -import { MEDIA_PREVIEW_CUSTOM_SCHEME } from '../media/media-preview-protocol' -import { PLUGIN_IMAGE_CUSTOM_SCHEME } from '../plugins/plugin-image-scheme' -import { PLUGIN_FRAME_CUSTOM_SCHEME } from '../plugins/panels/guest-isolation/plugin-frame-scheme' - -/** Registered with doc preview's in one call: each registerSchemesAsPrivileged call replaces the last. */ -export const PRIVILEGED_CUSTOM_SCHEMES: Electron.CustomScheme[] = [ - MEDIA_PREVIEW_CUSTOM_SCHEME, - JIRA_IMAGE_CUSTOM_SCHEME, - BROWSER_EXTENSION_API_CUSTOM_SCHEME, - PLUGIN_IMAGE_CUSTOM_SCHEME, - PLUGIN_FRAME_CUSTOM_SCHEME -] diff --git a/src/main/startup/bootstrap-fatal-exit-guard.ts b/src/main/startup/process-failure/bootstrap-fatal-exit-guard.ts similarity index 100% rename from src/main/startup/bootstrap-fatal-exit-guard.ts rename to src/main/startup/process-failure/bootstrap-fatal-exit-guard.ts diff --git a/src/main/startup/main-process-error-guards.test.ts b/src/main/startup/process-failure/main-process-error-guards.test.ts similarity index 92% rename from src/main/startup/main-process-error-guards.test.ts rename to src/main/startup/process-failure/main-process-error-guards.test.ts index cc198e46458..186ffed4fe7 100644 --- a/src/main/startup/main-process-error-guards.test.ts +++ b/src/main/startup/process-failure/main-process-error-guards.test.ts @@ -7,7 +7,7 @@ afterEach(() => { describe('main-process fatal error guards (issue #9441)', () => { it('never throws when the breadcrumb sink fails', async () => { vi.resetModules() - vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ + vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: vi.fn(() => { throw new Error('sink offline') }) @@ -26,7 +26,7 @@ describe('main-process fatal error guards (issue #9441)', () => { it('bounds and isolates console formatting for hostile rejection values', async () => { vi.resetModules() const record = vi.fn() - vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ + vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: record })) const { recordFatalMainProcessError } = await import('./main-process-error-guards') @@ -61,7 +61,7 @@ describe('main-process fatal error guards (issue #9441)', () => { it('caps oversized rejection diagnostics before recording or logging', async () => { vi.resetModules() const record = vi.fn() - vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ + vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: record })) const { recordFatalMainProcessError } = await import('./main-process-error-guards') @@ -82,7 +82,7 @@ describe('main-process fatal error guards (issue #9441)', () => { it('rethrows non-pipe errors outside the uncaughtException handler', async () => { vi.resetModules() - vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ + vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: vi.fn() })) const { installUncaughtPipeErrorGuard } = await import('./main-process-error-guards') diff --git a/src/main/startup/main-process-error-guards.ts b/src/main/startup/process-failure/main-process-error-guards.ts similarity index 97% rename from src/main/startup/main-process-error-guards.ts rename to src/main/startup/process-failure/main-process-error-guards.ts index 1f65cc51d36..b0a75f8cade 100644 --- a/src/main/startup/main-process-error-guards.ts +++ b/src/main/startup/process-failure/main-process-error-guards.ts @@ -1,4 +1,4 @@ -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { removeBootstrapFatalExitGuard } from './bootstrap-fatal-exit-guard' type FatalMainProcessErrorKind = 'main_uncaught_exception' | 'main_unhandled_rejection' diff --git a/src/main/startup/desktop-profile-instance-lock.ts b/src/main/startup/profile-startup/desktop-profile-instance-lock.ts similarity index 79% rename from src/main/startup/desktop-profile-instance-lock.ts rename to src/main/startup/profile-startup/desktop-profile-instance-lock.ts index ff95300a834..257da781ab1 100644 --- a/src/main/startup/desktop-profile-instance-lock.ts +++ b/src/main/startup/profile-startup/desktop-profile-instance-lock.ts @@ -1,7 +1,11 @@ /** Share orcad's profile lock to prevent concurrent desktop/serve writers; Electron's own instance lock cannot fence plain Node. */ -import { acquireOrcadInstanceLock, type OrcadInstanceLock } from '../orcad/orcad-instance-lock' -import { OrcadInstanceLockError } from '../orcad/orcad-data-root-privacy' -import { writeStartupDiagnosticLine, type StartupDiagnosticSink } from './startup-diagnostics' +import { acquireOrcadInstanceLock } from '../../orcad/instance-lock/orcad-instance-lock' +import type { OrcadInstanceLock } from '../../orcad/instance-lock/orcad-instance-lock-hold' +import { OrcadInstanceLockError } from '../../orcad/instance-lock/orcad-data-root-privacy' +import { + writeStartupDiagnosticLine, + type StartupDiagnosticSink +} from '../diagnostics/startup-diagnostics' export type DesktopProfileLockResult = | { state: 'acquired'; lock: OrcadInstanceLock } diff --git a/src/main/startup/dev-education-suppression.ts b/src/main/startup/profile-startup/dev-education-suppression.ts similarity index 84% rename from src/main/startup/dev-education-suppression.ts rename to src/main/startup/profile-startup/dev-education-suppression.ts index 1d8fb360a61..aebcfd1204b 100644 --- a/src/main/startup/dev-education-suppression.ts +++ b/src/main/startup/profile-startup/dev-education-suppression.ts @@ -1,12 +1,10 @@ -import { ONBOARDING_FINAL_STEP, ONBOARDING_FLOW_VERSION } from '../../shared/onboarding-defaults' -import { CONTEXTUAL_TOUR_IDS } from '../../shared/contextual-tours' -import { - FEATURE_INTERACTION_IDS, - type FeatureInteractionState -} from '../../shared/feature-interactions' -import { FEATURE_TIP_SEEN_IDS } from '../../shared/feature-tips' -import type { PersistedUIState } from '../../shared/persisted-ui-state-types' -import type { Store } from '../persistence/loading-store/store' +import { ONBOARDING_FINAL_STEP, ONBOARDING_FLOW_VERSION } from '../../../shared/onboarding-defaults' +import { CONTEXTUAL_TOUR_IDS } from '../../../shared/contextual-tours' +import { FEATURE_INTERACTION_IDS } from '../../../shared/feature-interaction-catalog' +import type { FeatureInteractionState } from '../../../shared/feature-interactions' +import { FEATURE_TIP_SEEN_IDS } from '../../../shared/feature-tips' +import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import type { Store } from '../../persistence/loading-store/store' export const DEV_SHOW_FIRST_RUN_EDUCATION_ENV = 'ORCA_DEV_SHOW_FIRST_RUN_EDUCATION' diff --git a/src/main/startup/dev-instance-identity.ts b/src/main/startup/profile-startup/dev-instance-identity.ts similarity index 97% rename from src/main/startup/dev-instance-identity.ts rename to src/main/startup/profile-startup/dev-instance-identity.ts index 1e11943398b..96baec5733a 100644 --- a/src/main/startup/dev-instance-identity.ts +++ b/src/main/startup/profile-startup/dev-instance-identity.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import path from 'node:path' -import type { AppIdentity } from '../../shared/app-identity' +import type { AppIdentity } from '../../../shared/app-identity' const BASE_APP_NAME = 'Orca' const BASE_APP_USER_MODEL_ID = 'com.stablyai.orca' diff --git a/src/main/startup/profile-state-recovery-preflight.test.ts b/src/main/startup/profile-startup/profile-state-recovery-preflight.test.ts similarity index 92% rename from src/main/startup/profile-state-recovery-preflight.test.ts rename to src/main/startup/profile-startup/profile-state-recovery-preflight.test.ts index 4e4af59452c..0c0cd88d412 100644 --- a/src/main/startup/profile-state-recovery-preflight.test.ts +++ b/src/main/startup/profile-startup/profile-state-recovery-preflight.test.ts @@ -14,23 +14,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { PROFILE_STATE_RECOVERY_FLAG, PROFILE_STATE_RECOVERY_RESULT_PREFIX -} from '../../shared/profile-state-recovery-command' -import { acquireProfileStateRuntimeAdmission } from '../persistence/profile-state/access/profile-state-access' -import { profileStateJsonExportPath } from '../persistence/profile-state/legacy-json/profile-state-export-path' +} from '../../../shared/profile-state-recovery-command' +import { acquireProfileStateRuntimeAdmission } from '../../persistence/profile-state/access/profile-state-access' +import { profileStateJsonExportPath } from '../../persistence/profile-state/legacy-json/profile-state-export-path' import { createProfileStateDatabaseBackupId, profileStateDatabaseBackupPath -} from '../persistence/profile-state/backup/profile-state-backup-path' +} from '../../persistence/profile-state/backup/profile-state-backup-path' import { openProfileStateDatabase, openProfileStateDatabaseReadOnly -} from '../persistence/profile-state/database/profile-state-database' +} from '../../persistence/profile-state/database/profile-state-database' import { importProfileStateJson, readProfileStateSnapshot -} from '../persistence/profile-state/documents/profile-state-documents' -import { writeProfileStateDatabaseSnapshotAsync } from '../persistence/profile-state/database/profile-state-database-snapshot' -import * as marker from './http1-compatibility-marker' +} from '../../persistence/profile-state/documents/profile-state-documents' +import { writeProfileStateDatabaseSnapshotAsync } from '../../persistence/profile-state/database/profile-state-database-snapshot' +import * as marker from '../network-compatibility/http1-compatibility-marker' import { profileStateDesktopRecoveryArgs, runProfileStateRecoveryPreflight @@ -51,7 +51,7 @@ vi.mock('electron', () => ({ app: mocks, dialog: { showMessageBox: mocks.showMessageBox } })) -vi.mock('../window/foreground-activation-policy', () => ({ +vi.mock('../../window/activation/foreground-activation-policy', () => ({ applyBackgroundActivationPolicy: mocks.background })) vi.mock('node:fs', async (original) => { diff --git a/src/main/startup/profile-state-recovery-preflight.ts b/src/main/startup/profile-startup/profile-state-recovery-preflight.ts similarity index 91% rename from src/main/startup/profile-state-recovery-preflight.ts rename to src/main/startup/profile-startup/profile-state-recovery-preflight.ts index 098381ba60c..2f57764585f 100644 --- a/src/main/startup/profile-state-recovery-preflight.ts +++ b/src/main/startup/profile-startup/profile-state-recovery-preflight.ts @@ -10,11 +10,11 @@ import { profileStateRecoveryRequestSchema, type ProfileStateRecoveryRequest, type ProfileStateRecoveryResponse -} from '../../shared/profile-state-recovery-command' -import { prepareEarlyMainUiLanguage, translateMain } from '../i18n/main-i18n' -import { acquireProfileStateMaintenance } from '../persistence/profile-state/access/profile-state-access' -import { rollbackProfileState } from '../persistence/profile-state/recovery/profile-state-recovery-command' -import { applyBackgroundActivationPolicy } from '../window/foreground-activation-policy' +} from '../../../shared/profile-state-recovery-command' +import { prepareEarlyMainUiLanguage, translateMain } from '../../i18n/main-i18n' +import { acquireProfileStateMaintenance } from '../../persistence/profile-state/access/profile-state-access' +import { rollbackProfileState } from '../../persistence/profile-state/recovery/profile-state-recovery-command' +import { applyBackgroundActivationPolicy } from '../../window/activation/foreground-activation-policy' import { acquireSingleInstanceLock } from './single-instance-lock' /** The process owning both locks performs recovery before Electron can initialize a runtime. */ diff --git a/src/main/startup/profile-state-save-delay.test.ts b/src/main/startup/profile-startup/profile-state-save-delay.test.ts similarity index 95% rename from src/main/startup/profile-state-save-delay.test.ts rename to src/main/startup/profile-startup/profile-state-save-delay.test.ts index a360d1c97b5..bf5a59ac9d5 100644 --- a/src/main/startup/profile-state-save-delay.test.ts +++ b/src/main/startup/profile-startup/profile-state-save-delay.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' const send = vi.hoisted(() => vi.fn()) -vi.mock('../ipc/ui', () => ({ sendToTrustedUIRenderer: send })) +vi.mock('../../ipc/ui', () => ({ sendToTrustedUIRenderer: send })) import { isProfileStateSaveDelayed, reportProfileStateSaveDelay } from './profile-state-save-delay' diff --git a/src/main/startup/profile-state-save-delay.ts b/src/main/startup/profile-startup/profile-state-save-delay.ts similarity index 89% rename from src/main/startup/profile-state-save-delay.ts rename to src/main/startup/profile-startup/profile-state-save-delay.ts index 7cd965d9374..86f7f003d48 100644 --- a/src/main/startup/profile-state-save-delay.ts +++ b/src/main/startup/profile-startup/profile-state-save-delay.ts @@ -1,4 +1,4 @@ -import { sendToTrustedUIRenderer } from '../ipc/ui' +import { sendToTrustedUIRenderer } from '../../ipc/ui' let saveDelayed = false diff --git a/src/main/startup/profile-state-write-failure.ts b/src/main/startup/profile-startup/profile-state-write-failure.ts similarity index 85% rename from src/main/startup/profile-state-write-failure.ts rename to src/main/startup/profile-startup/profile-state-write-failure.ts index ac56f0f348d..cf1a3de02ae 100644 --- a/src/main/startup/profile-state-write-failure.ts +++ b/src/main/startup/profile-startup/profile-state-write-failure.ts @@ -1,10 +1,10 @@ import { app, dialog, type BrowserWindow, type MessageBoxOptions } from 'electron' -import { translateMain } from '../i18n/main-i18n' -import { profileStateWriterFailureOutcome } from '../persistence/profile-state/writer/profile-state-writer-errors' -import { recordProfileStateWriteFailureReport } from '../persistence/profile-state/writer/profile-state-writer-diagnostics' -import { isBackgroundLaunch } from '../window/foreground-activation-policy' -import { waitForWindowToShow } from '../window/wait-for-window-to-show' -import { mainProcessState } from './main-process-state' +import { translateMain } from '../../i18n/main-i18n' +import { profileStateWriterFailureOutcome } from '../../persistence/profile-state/writer/profile-state-writer-errors' +import { recordProfileStateWriteFailureReport } from '../../persistence/profile-state/writer/profile-state-writer-diagnostics' +import { isBackgroundLaunch } from '../../window/activation/foreground-activation-policy' +import { waitForWindowToShow } from '../../window/visibility/wait-for-window-to-show' +import { mainProcessState } from '../main-process-state' let presenting = false diff --git a/src/main/startup/single-instance-lock.ts b/src/main/startup/profile-startup/single-instance-lock.ts similarity index 92% rename from src/main/startup/single-instance-lock.ts rename to src/main/startup/profile-startup/single-instance-lock.ts index 8edcd844111..c0c9c06502b 100644 --- a/src/main/startup/single-instance-lock.ts +++ b/src/main/startup/profile-startup/single-instance-lock.ts @@ -1,6 +1,9 @@ import type { App } from 'electron' -import { argvRequestsServeMode } from './serve-mode-argv' -import { writeStartupDiagnosticLine, type StartupDiagnosticSink } from './startup-diagnostics' +import { argvRequestsServeMode } from '../serve-launch/serve-mode-argv' +import { + writeStartupDiagnosticLine, + type StartupDiagnosticSink +} from '../diagnostics/startup-diagnostics' export const SINGLE_INSTANCE_LOCK_FAILURE_MESSAGE = '[single-instance] Another Orca instance is already running for this userData profile; exiting this launch after requesting the existing window. If no Orca process is running, this may be an Electron/macOS single-instance lock failure.' @@ -8,7 +11,6 @@ export const SINGLE_INSTANCE_LOCK_BYPASS_ENV = 'ORCA_BYPASS_SINGLE_INSTANCE_LOCK export const SINGLE_INSTANCE_LOCK_E2E_ENFORCE_ENV = 'ORCA_E2E_ENFORCE_SINGLE_INSTANCE_LOCK' export const SINGLE_INSTANCE_LOCK_BYPASS_MESSAGE = '[single-instance] ORCA_BYPASS_SINGLE_INSTANCE_LOCK=1 is set; bypassing the packaged macOS single-instance lock for diagnostics. Do not use this with another Orca instance running for the same profile.' -export { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' // Supervisor duplicate serve launches must not activate desktop; recognize CLI-form argv too (#12677, #11935). Missing argv preserves activation. export function shouldActivateDesktopForSecondInstance(argv: readonly string[] = []): boolean { diff --git a/src/main/startup/profile-state-write-failure.test.ts b/src/main/startup/profile-state-write-failure.test.ts deleted file mode 100644 index 0ded8f3db67..00000000000 --- a/src/main/startup/profile-state-write-failure.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { ProfileStateWriterError } from '../persistence/profile-state/writer/profile-state-writer-errors' - -const fixture = await vi.hoisted(async () => { - const events = await import('node:events') - const state: { isServeMode: boolean; isQuitting: boolean; mainWindow: unknown } = { - isServeMode: false, - isQuitting: false, - mainWindow: null - } - return { show: vi.fn(), background: false, app: new events.EventEmitter(), state } -}) -vi.mock('electron', () => ({ app: fixture.app, dialog: { showMessageBox: fixture.show } })) -vi.mock('../window/foreground-activation-policy', () => ({ - isBackgroundLaunch: () => fixture.background -})) -vi.mock('./main-process-state', () => ({ mainProcessState: fixture.state })) -vi.mock('../persistence/profile-state/writer/profile-state-writer-diagnostics', () => ({ - recordProfileStateWriteFailureReport: vi.fn() -})) - -const { reportProfileStateWriteFailure } = await import('./profile-state-write-failure') -const { recordProfileStateWriteFailureReport } = - await import('../persistence/profile-state/writer/profile-state-writer-diagnostics') - -class FakeWindow extends EventEmitter { - visible: boolean - destroyed = false - readonly webContents = Object.assign(new EventEmitter(), { isDestroyed: () => false }) - readonly reveal = vi.fn() - constructor(visible: boolean) { - super() - this.visible = visible - } - isVisible() { - return this.visible - } - isDestroyed() { - return this.destroyed - } - // Any reveal/activation fails: persistence errors must remain in the background. - show = this.reveal - showInactive = this.reveal - focus = this.reveal - moveTop = this.reveal -} - -const workerExit = new ProfileStateWriterError( - 'profile-state-writer-exit', - 'exited', - 'indeterminate' -) -const conflict = new ProfileStateWriterError( - 'profile-state-revision-conflict', - 'conflict', - 'known-failure' -) - -beforeEach(() => { - fixture.background = false - fixture.state.isServeMode = false - fixture.state.isQuitting = false - fixture.state.mainWindow = null - fixture.show.mockResolvedValue({ response: 0 }) - vi.spyOn(console, 'error').mockImplementation(() => {}) - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) -afterEach(async () => { - // Release pending reporters so module state cannot leak across tests. - fixture.state.isQuitting = true - fixture.app.emit('browser-window-created', {}, new FakeWindow(false)) - await new Promise((resolve) => setImmediate(resolve)) - await new Promise((resolve) => setImmediate(resolve)) - vi.restoreAllMocks() - vi.clearAllMocks() -}) - -it('attaches the alert to the visible main window and explains an unconfirmed write', async () => { - const window = new FakeWindow(true) - fixture.state.mainWindow = window - reportProfileStateWriteFailure(workerExit) - await vi.waitFor(() => expect(fixture.show).toHaveBeenCalledOnce()) - expect(fixture.show).toHaveBeenCalledWith(window, { - type: 'error', - title: 'Saving stopped', - message: 'Orca has stopped saving this profile.', - detail: - 'Orca could not confirm whether your most recent change was saved. New changes will not be saved until you restart Orca.', - buttons: ['OK'] - }) - expect(recordProfileStateWriteFailureReport).toHaveBeenCalledWith(workerExit, 'dialog') -}) - -it('waits for a hidden window to be shown by the user instead of revealing it', async () => { - const window = new FakeWindow(false) - fixture.state.mainWindow = window - reportProfileStateWriteFailure(workerExit) - await new Promise((resolve) => setImmediate(resolve)) - expect(fixture.show).not.toHaveBeenCalled() - expect(window.reveal).not.toHaveBeenCalled() - expect(recordProfileStateWriteFailureReport).toHaveBeenCalledWith(workerExit, 'deferred') - window.visible = true - window.emit('show') - await vi.waitFor(() => - expect(fixture.show).toHaveBeenCalledExactlyOnceWith(window, expect.anything()) - ) -}) - -it('never falls back to a parentless alert when no main window exists', async () => { - reportProfileStateWriteFailure(workerExit) - await new Promise((resolve) => setImmediate(resolve)) - expect(fixture.show).not.toHaveBeenCalled() - const window = new FakeWindow(true) - fixture.app.emit('browser-window-created', {}, window) - fixture.state.mainWindow = window - await vi.waitFor(() => - expect(fixture.show).toHaveBeenCalledExactlyOnceWith(window, expect.anything()) - ) - for (const call of fixture.show.mock.calls) { - expect(call).toHaveLength(2) - } -}) - -it('waits for a replacement after the main window is destroyed', async () => { - const destroyed = new FakeWindow(true) - destroyed.destroyed = true - fixture.state.mainWindow = destroyed - reportProfileStateWriteFailure(workerExit) - await new Promise((resolve) => setImmediate(resolve)) - expect(fixture.show).not.toHaveBeenCalled() - const replacement = new FakeWindow(true) - fixture.state.mainWindow = replacement - fixture.app.emit('browser-window-created', {}, replacement) - await vi.waitFor(() => - expect(fixture.show).toHaveBeenCalledExactlyOnceWith(replacement, expect.anything()) - ) -}) - -it('shows one alert for concurrent failures', async () => { - fixture.state.mainWindow = new FakeWindow(true) - let close!: () => void - fixture.show.mockReturnValue(new Promise((resolve) => (close = () => resolve({ response: 0 })))) - reportProfileStateWriteFailure(workerExit) - reportProfileStateWriteFailure(conflict) - await vi.waitFor(() => expect(fixture.show).toHaveBeenCalledOnce()) - expect(recordProfileStateWriteFailureReport).toHaveBeenCalledWith(conflict, 'duplicate') - close() -}) - -it.each(['background', 'serve'])('keeps %s runs free of native dialogs', async (mode) => { - fixture.background = mode === 'background' - fixture.state.isServeMode = mode === 'serve' - fixture.state.mainWindow = new FakeWindow(true) - reportProfileStateWriteFailure(workerExit) - await new Promise((resolve) => setImmediate(resolve)) - expect(fixture.show).not.toHaveBeenCalled() - expect(console.error).toHaveBeenCalledWith( - expect.stringContaining('stopped saving'), - expect.any(Error) - ) - expect(recordProfileStateWriteFailureReport).toHaveBeenCalledWith(workerExit, 'suppressed') -}) - -it('handles a failed dialog without an unhandled rejection', async () => { - fixture.state.mainWindow = new FakeWindow(true) - fixture.show.mockRejectedValue(new Error('window system unavailable')) - reportProfileStateWriteFailure(workerExit) - await vi.waitFor(() => expect(console.warn).toHaveBeenCalled()) -}) diff --git a/src/main/startup/first-window-startup-services.test.ts b/src/main/startup/pty-startup/first-window-startup-services.test.ts similarity index 100% rename from src/main/startup/first-window-startup-services.test.ts rename to src/main/startup/pty-startup/first-window-startup-services.test.ts diff --git a/src/main/startup/first-window-startup-services.ts b/src/main/startup/pty-startup/first-window-startup-services.ts similarity index 100% rename from src/main/startup/first-window-startup-services.ts rename to src/main/startup/pty-startup/first-window-startup-services.ts diff --git a/src/main/startup/pty-startup/legacy-worker-renderer-recovery.test.ts b/src/main/startup/pty-startup/legacy-worker-renderer-recovery.test.ts new file mode 100644 index 00000000000..4a8b4c899df --- /dev/null +++ b/src/main/startup/pty-startup/legacy-worker-renderer-recovery.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from 'vitest' +import { recoverLegacyWorkerTerminalsForRendererStartup } from './legacy-worker-renderer-recovery' + +describe('legacy worker renderer recovery', () => { + it('contains provider startup rejection after initial recovery', async () => { + const providerError = new Error('provider failed') + const reconcile = vi.fn().mockResolvedValue(undefined) + let reportError!: (error: unknown) => void + const reportedError = new Promise((resolve) => { + reportError = resolve + }) + + await recoverLegacyWorkerTerminalsForRendererStartup({ + firstWindowStartupServicesReady: Promise.resolve(), + managedWslCliStartupBarrierReady: Promise.resolve(), + localPtyProviderStartupReady: Promise.reject(providerError), + reconcile, + onDeferredRecoveryError: reportError + }) + + await expect(reportedError).resolves.toBe(providerError) + expect(reconcile).not.toHaveBeenCalled() + }) + + it('contains recovery rejection', async () => { + const recoveryError = new Error('recovery failed') + const reconcile = vi.fn().mockRejectedValueOnce(recoveryError) + let reportError!: (error: unknown) => void + const reportedError = new Promise((resolve) => { + reportError = resolve + }) + + await recoverLegacyWorkerTerminalsForRendererStartup({ + firstWindowStartupServicesReady: Promise.resolve(), + managedWslCliStartupBarrierReady: Promise.resolve(), + localPtyProviderStartupReady: Promise.resolve(), + reconcile, + onDeferredRecoveryError: reportError + }) + + await expect(reportedError).resolves.toBe(recoveryError) + expect(reconcile).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/startup/legacy-worker-renderer-recovery.ts b/src/main/startup/pty-startup/legacy-worker-renderer-recovery.ts similarity index 100% rename from src/main/startup/legacy-worker-renderer-recovery.ts rename to src/main/startup/pty-startup/legacy-worker-renderer-recovery.ts diff --git a/src/main/startup/main-process-pty-startup.ts b/src/main/startup/pty-startup/main-process-pty-startup.ts similarity index 78% rename from src/main/startup/main-process-pty-startup.ts rename to src/main/startup/pty-startup/main-process-pty-startup.ts index f914308f0c1..0309796d2bf 100644 --- a/src/main/startup/main-process-pty-startup.ts +++ b/src/main/startup/pty-startup/main-process-pty-startup.ts @@ -1,48 +1,48 @@ import { app } from 'electron' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { isLocalExecutionHost } from '../../shared/execution-host' -import { classifyError } from '../telemetry/classify-error' -import { track } from '../telemetry/client' -import { getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { isLocalExecutionHost } from '../../../shared/execution-host' +import { classifyError } from '../../telemetry/classify-error' +import { track } from '../../telemetry/client' +import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' import { getDaemonProvider, listLiveDaemonPtyIds -} from '../daemon/providers/lifecycle/daemon-provider-state' -import { initDaemonPtyProvider } from '../daemon/providers/lifecycle/daemon-provider-init' -import { restartLocalTerminalsAfterElevation } from '../windows/windows-administrator-restart' -import { resolveTerminalSpawnAdmissionMode } from '../daemon/admission/terminal-spawn-admission-mode' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import { initDaemonPtyProvider } from '../../daemon/providers/lifecycle/daemon-provider-init' +import { restartLocalTerminalsAfterElevation } from '../../windows/windows-administrator-restart' +import { resolveTerminalSpawnAdmissionMode } from '../../daemon/admission/terminal-spawn-admission-mode' import { getCodexPaneAccount, hasAnyRecordedLegacyWslCodexPane, hasRecordedManagedHostCodexPane, isCodexPaneHomeRouteProvenAwayFromSharedHome, reconcileCodexPaneAccountsWithLivePtys -} from '../codex/configuration/homes/codex-pane-account-registry' -import type { CodexPaneHomeRoute } from '../codex/configuration/homes/codex-pane-account-registry-types' -import { reconcileRetainedCodexHookHomes } from '../codex/hooks/installation/retained-codex-hook-state' -import { codexHookService } from '../codex/hooks/installation/hook-service' +} from '../../codex/configuration/homes/codex-pane-account-registry' +import type { CodexPaneHomeRoute } from '../../codex/configuration/homes/codex-pane-account-registry-types' +import { reconcileRetainedCodexHookHomes } from '../../codex/hooks/installation/retained-codex-hook-state' +import { codexHookService } from '../../codex/hooks/installation/hook-service' import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { createLocalTmuxManagedPtyResolver } from '../agent-hooks/observations/local-tmux-managed-pty' -import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { createLocalTmuxManagedPtyResolver } from '../../agent-hooks/observations/local-tmux-managed-pty' +import { installLocalHookRootEvidence } from '../../agent-hooks/observations/local-hook-root-evidence' import { indexPersistedPaneKeyPtyIds, resolveAgentWorkspaceExecutionHostId, retireRestoredStatusesWithDeadTerminals -} from '../agent-hooks/observations/restored-status-dead-terminal-sweep' +} from '../../agent-hooks/observations/restored-status-dead-terminal-sweep' import { startFirstWindowStartupServices } from './first-window-startup-services' -import { logStartupMilestone } from './startup-diagnostics' -import type { WindowsDesktopStartupServices } from './windows-desktop-shell-path-startup' -import type { RuntimeWorktreeLifecycleEvent } from '../runtime/workspaces/lifecycle/worktree-lifecycle-event' -import { mainProcessState as state } from './main-process-state' -import { shortPluginBranchName } from '../../shared/plugins/events/plugin-events' -import { notifyWorkspaceCreatedPluginHook } from '../plugins/hooks/workspace-create-plugin-hook' +import { logStartupMilestone } from '../diagnostics/startup-diagnostics' +import type { WindowsDesktopStartupServices } from '../shell-environment/windows-desktop-shell-path-startup' +import type { RuntimeWorktreeLifecycleEvent } from '../../runtime/workspaces/lifecycle/worktree-lifecycle-event' +import { mainProcessState as state } from '../main-process-state' +import { shortPluginBranchName } from '../../../shared/plugins/events/plugin-events' +import { notifyWorkspaceCreatedPluginHook } from '../../plugins/hooks/workspace-create-plugin-hook' +import { pluginListedWorkspaceId } from '../../plugins/workers/host-api/plugin-workspace-projection' export function emitPluginWorktreeLifecycle(event: RuntimeWorktreeLifecycleEvent): void { - const identity = { workspaceId: event.worktreeId, kind: 'worktree', path: event.path } const folder = parseWorkspaceKey(event.worktreeId)?.type === 'folder' if (event.kind === 'created') { notifyWorkspaceCreatedPluginHook({ ...event, folder }) @@ -51,6 +51,16 @@ export function emitPluginWorktreeLifecycle(event: RuntimeWorktreeLifecycleEvent if (folder) { return } + const workspaceListId = pluginListedWorkspaceId({ + id: event.worktreeId, + identityKey: event.identityKey + }) + const identity = { + workspaceId: event.worktreeId, + ...(workspaceListId ? { workspaceListId } : {}), + kind: 'worktree', + path: event.path + } state.pluginService?.emitEvent( event.kind === 'created' ? 'workspace.created' : 'workspace.removed', event.kind === 'created' diff --git a/src/main/startup/quit/app-relaunch.test.ts b/src/main/startup/quit/app-relaunch.test.ts index 3299a686550..03c8687100d 100644 --- a/src/main/startup/quit/app-relaunch.test.ts +++ b/src/main/startup/quit/app-relaunch.test.ts @@ -21,7 +21,7 @@ vi.mock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ import { relaunchApp } from './app-relaunch' import { restartLocalTerminalsAfterElevation } from '../../windows/windows-administrator-restart' -import { _resetHydrateShellPathCache, _setLaunchPathForTests } from '../hydrate-shell-path' +import { _resetHydrateShellPathCache } from '../shell-environment/hydrate-shell-path' beforeEach(() => { appRelaunchMock.mockReset() @@ -67,18 +67,4 @@ describe('relaunchApp', () => { relaunchApp('windows-administrator', undefined, custom) expect(appRelaunchMock).toHaveBeenLastCalledWith(custom) }) - - it('does not carry Orca PATH seeds into the replacement process', () => { - process.env.PATH = '/seeded/newest-nvm/bin:/usr/bin' - _setLaunchPathForTests('/usr/bin') - let inheritedPath: string | undefined - appRelaunchMock.mockImplementation(() => { - inheritedPath = process.env.PATH - }) - - relaunchApp('renderer-request') - - expect(inheritedPath).toBe('/usr/bin') - expect(process.env.PATH).toBe('/seeded/newest-nvm/bin:/usr/bin') - }) }) diff --git a/src/main/startup/quit/app-relaunch.ts b/src/main/startup/quit/app-relaunch.ts index 36a56856e6f..3059783d668 100644 --- a/src/main/startup/quit/app-relaunch.ts +++ b/src/main/startup/quit/app-relaunch.ts @@ -1,7 +1,7 @@ import { app } from 'electron' import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { runWithLaunchPath } from '../hydrate-shell-path' +import { runWithLaunchPath } from '../shell-environment/hydrate-shell-path' import { getWindowsAdministratorRelaunchOptions } from '../../windows/windows-administrator-restart' export type AppRelaunchReason = diff --git a/src/main/startup/quit/main-process-quit-pending-writer.test.ts b/src/main/startup/quit/main-process-quit-pending-writer.test.ts new file mode 100644 index 00000000000..4a565b9e709 --- /dev/null +++ b/src/main/startup/quit/main-process-quit-pending-writer.test.ts @@ -0,0 +1,145 @@ +import { EventEmitter } from 'node:events' +import { afterEach, expect, it, vi } from 'vitest' +import { WILL_QUIT_TEARDOWN_DEADLINE_MS } from '../../../shared/quit-teardown-deadline' + +const settled = () => vi.fn(async () => {}) +const idle = () => vi.fn() +const stopAgentHookServer = idle() +const stopStructuredAgentSessionRuntime = settled() +const beginSshShutdown = settled() +const killAllPty = idle() + +// Every teardown member settles except the profile store, so only the writer can hold quit. +const dependencies: Record> = { + '../../ipc/filesystem/watchers/filesystem-watcher-shutdown': { closeAllWatchers: settled() }, + '../../ipc/worktrees/creation/worktree-base-directory-watcher': { + disposeWorktreeBaseDirectoryWatchers: settled() + }, + '../../ipc/folder-repo-git-upgrade': { stopFolderRepoGitUpgradeWatch: idle() }, + '../../ipc/pty/kill-all': { killAllPty }, + '../../daemon/providers/lifecycle/daemon-provider-state': { + disconnectDaemon: settled(), + shutdownDaemon: settled() + }, + '../../ipc/ssh/ssh-shutdown-drain': { beginSshShutdown }, + '../cloud-startup/main-process-connector-startup': { desktopConnectorCloud: () => null }, + '../../agent-hooks/server/agent-hook-server': { agentHookServer: { stop: stopAgentHookServer } }, + '../../agent-hooks/wsl-relay/wsl-hook-relay-manager': { + wslHookRelayManager: { disposeAll: idle() } + }, + '../../agent-hooks/installation/managed-agent-hook-controls': { + removeManagedAgentHooksAsync: vi.fn(async () => []) + }, + '../../runtime/agent-session/structured-agent-session-runtime': { + stopStructuredAgentSessionRuntime + }, + '../../runtime/agent-session/structured-agent-session-runtime-teardown': { + setStructuredAgentSessionTeardownTrigger: idle() + }, + '../../runtime/files/watch/file-watcher-leases': { + awaitRuntimeFileWatcherUnsubscribes: settled() + }, + '../../runtime/rpc/server/runtime-metadata': { clearRuntimeMetadataIfOwned: idle() }, + '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime': { + shutdownPairedRuntimeBrowserClientHosts: settled() + }, + '../../ipc/browser/desktop-browser-bridge-wiring': { disposeDesktopBrowserBridge: idle() }, + '../../orca-profiles/cloud-session/profile-cloud-session-owner': { + flushUnsavedCloudSessions: idle() + }, + '../../browser/guest-lifecycle/manager/browser-manager': { + browserManager: { setBrowserGuestStateChangedListener: idle(), setOffscreenTabOpener: idle() } + }, + '../../browser/sessions/profiles/browser-session-registry': { browserSessionRegistry: {} }, + '../../browser/routing/local-host-partitions/local-ssh-browser-route': { + closeAllLocalSshBrowserRoutes: settled() + }, + '../../codex/history/index/codex-state-db-backfill-recovery': { + stopCodexStateDbBackfillRecoveries: settled() + }, + '../../codex/history/bridges/codex-account-session-bridge': { + stopCodexAccountSessionBridges: idle() + }, + '../../git/refs/maintenance/local-repo-ref-maintenance': { + awaitPackedRefsLockRelease: settled() + }, + '../../workspaces/removal/worktree-background-removal': { + stopBackgroundWorktreeRemovals: idle() + }, + '../../dock/unread-badge': { setUnreadDockBadgeCount: idle() }, + '../../tray/system-tray': { destroySystemTray: idle() }, + '../../telemetry/client': { shutdownTelemetry: settled() }, + '../../observability/index': { shutdownObservability: settled() }, + '../../updater/updater-service': { isQuittingForUpdate: vi.fn(() => false) }, + '../../updater/updater-lifecycle-diagnostics': { recordUpdaterLifecycle: idle() }, + '../../macos-permissions/macos-tcc-prompt-notice': { stopTccPromptNotice: idle() }, + '../../pty/history/terminal-history-gc': { cancelHistoryGc: idle() }, + './window-all-closed-quit-policy': { shouldQuitWhenAllWindowsClosed: vi.fn(() => false) }, + '../configure-process': { isDevParentShutdownRequested: vi.fn(() => false) }, + '../../persistence/loading-store/user-data-path': { + getCanonicalUserDataPath: vi.fn(() => '/unused') + } +} + +afterEach(() => { + vi.doUnmock('electron') + vi.doUnmock('../main-process-state') + for (const moduleName of Object.keys(dependencies)) { + vi.doUnmock(moduleName) + } + vi.restoreAllMocks() + vi.useRealTimers() + vi.resetModules() +}) + +async function startQuit( + flushFinalOrThrowAsync: () => Promise, + services: Record = {} +) { + beginSshShutdown.mockClear() + killAllPty.mockClear() + vi.resetModules() + vi.useFakeTimers() + const app = Object.assign(new EventEmitter(), { quit: vi.fn() }) + const admission = { release: vi.fn() } + const store = { + flushFinalOrThrowAsync: vi.fn(flushFinalOrThrowAsync), + freezeWritesAsync: settled() + } + const profileStateAdmission: typeof admission | undefined = admission + const state = { + isQuitting: false, + watcherShutdownDone: true, + store, + profileStateAdmission, + ...services + } + vi.doMock('electron', () => ({ app })) + vi.doMock('../main-process-state', () => ({ mainProcessState: state })) + for (const [moduleName, exports] of Object.entries(dependencies)) { + vi.doMock(moduleName, () => exports) + } + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const { installMainProcessQuitHandlers } = await import('./main-process-quit') + const { quitTeardownStartGate } = await import('./quit-teardown-start-gate') + quitTeardownStartGate.resetForTests() + installMainProcessQuitHandlers() + app.emit('before-quit', { defaultPrevented: false }) + app.emit('will-quit', { preventDefault: vi.fn() }) + return { app, admission, store, state } +} + +it('quits at the teardown deadline without releasing admission while the writer is pending', async () => { + const { app, admission, store, state } = await startQuit(() => new Promise(() => {})) + await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS - 1) + expect(app.quit).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(app.quit).toHaveBeenCalledOnce() + expect(console.warn).toHaveBeenCalledWith('[shutdown] Quit teardown deadline reached', { + pendingTeardowns: ['state'] + }) + expect(store.flushFinalOrThrowAsync).toHaveBeenCalledOnce() + expect(store.freezeWritesAsync).not.toHaveBeenCalled() + expect(admission.release).not.toHaveBeenCalled() + expect(state.profileStateAdmission).toBe(admission) +}) diff --git a/src/main/startup/quit/main-process-quit-update-veto.test.ts b/src/main/startup/quit/main-process-quit-update-veto.test.ts new file mode 100644 index 00000000000..053177162a0 --- /dev/null +++ b/src/main/startup/quit/main-process-quit-update-veto.test.ts @@ -0,0 +1,118 @@ +import { EventEmitter } from 'node:events' +import { afterEach, expect, it, vi } from 'vitest' + +const dependencyExports: [string, string[]][] = [ + ['../../ipc/filesystem/watchers/filesystem-watcher-shutdown', ['closeAllWatchers']], + [ + '../../ipc/worktrees/creation/worktree-base-directory-watcher', + ['disposeWorktreeBaseDirectoryWatchers'] + ], + ['../../ipc/folder-repo-git-upgrade', ['stopFolderRepoGitUpgradeWatch']], + ['../../ipc/pty/kill-all', ['killAllPty']], + [ + '../../daemon/providers/lifecycle/daemon-provider-state', + ['disconnectDaemon', 'shutdownDaemon'] + ], + ['../../ipc/ssh/ssh-shutdown-drain', ['beginSshShutdown']], + ['../../agent-hooks/server/agent-hook-server', ['agentHookServer']], + ['../../agent-hooks/wsl-relay/wsl-hook-relay-manager', ['wslHookRelayManager']], + ['../../agent-hooks/installation/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], + [ + '../../runtime/agent-session/structured-agent-session-runtime', + ['stopStructuredAgentSessionRuntime'] + ], + [ + '../../runtime/agent-session/structured-agent-session-runtime-teardown', + ['setStructuredAgentSessionTeardownTrigger'] + ], + ['../../runtime/files/watch/file-watcher-leases', ['awaitRuntimeFileWatcherUnsubscribes']], + ['../../runtime/rpc/server/runtime-metadata', ['clearRuntimeMetadataIfOwned']], + [ + '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime', + ['shutdownPairedRuntimeBrowserClientHosts'] + ], + ['../../ipc/browser/desktop-browser-bridge-wiring', ['disposeDesktopBrowserBridge']], + ['../../orca-profiles/cloud-session/profile-cloud-session-owner', ['flushUnsavedCloudSessions']], + ['../../browser/guest-lifecycle/manager/browser-manager', ['browserManager']], + ['../../browser/sessions/profiles/browser-session-registry', ['browserSessionRegistry']], + [ + '../../codex/history/index/codex-state-db-backfill-recovery', + ['stopCodexStateDbBackfillRecoveries'] + ], + ['../../codex/history/bridges/codex-account-session-bridge', ['stopCodexAccountSessionBridges']], + ['../../git/refs/maintenance/local-repo-ref-maintenance', ['awaitPackedRefsLockRelease']], + ['../../workspaces/removal/worktree-background-removal', ['stopBackgroundWorktreeRemovals']], + ['./quit-teardown-deadline', ['settleTeardownWithinDeadline', 'settleWithinMs']], + ['./quit-teardown-start-gate', ['quitTeardownStartGate']], + ['../../dock/unread-badge', ['setUnreadDockBadgeCount']], + ['../../tray/system-tray', ['destroySystemTray']], + ['../../telemetry/client', ['shutdownTelemetry']], + ['../../observability/index', ['shutdownObservability']], + ['../../updater/updater-service', ['isQuittingForUpdate']], + ['../../updater/updater-lifecycle-diagnostics', ['recordUpdaterLifecycle']], + ['../../macos-permissions/macos-tcc-prompt-notice', ['stopTccPromptNotice']], + ['../../pty/history/terminal-history-gc', ['cancelHistoryGc']], + ['./window-all-closed-quit-policy', ['shouldQuitWhenAllWindowsClosed']], + ['../configure-process', ['isDevParentShutdownRequested']], + ['../../persistence/loading-store/user-data-path', ['getCanonicalUserDataPath']] +] + +it('keeps startup services live when the updater has vetoed before-quit', async () => { + vi.resetModules() + const app = new EventEmitter() + const fenceAndCloseNow = vi.fn() + const setMobileRelayPairingProvider = vi.fn() + const unsubscribeAgentAwakeStatusChanges = vi.fn() + const dispose = vi.fn() + const stop = vi.fn() + const state = { + isQuitting: false, + desktopRelayService: { fenceAndCloseNow }, + runtimeRpc: { setMobileRelayPairingProvider }, + unsubscribeAgentAwakeStatusChanges, + agentAwakeService: { dispose }, + rateLimits: { stop } + } + vi.doMock('electron', () => ({ app })) + vi.doMock('../main-process-state', () => ({ mainProcessState: state })) + for (const [moduleName, exports] of dependencyExports) { + vi.doMock(moduleName, () => Object.fromEntries(exports.map((name) => [name, vi.fn()]))) + } + const exitListenersBefore = process.listeners('exit') + const { installMainProcessQuitHandlers } = await import('./main-process-quit') + installMainProcessQuitHandlers() + + app.emit('before-quit', { defaultPrevented: true }) + + expect(state.isQuitting).toBe(false) + expect(fenceAndCloseNow).not.toHaveBeenCalled() + expect(setMobileRelayPairingProvider).not.toHaveBeenCalled() + expect(unsubscribeAgentAwakeStatusChanges).not.toHaveBeenCalled() + expect(dispose).not.toHaveBeenCalled() + expect(stop).not.toHaveBeenCalled() + expect(state.agentAwakeService).toEqual({ dispose }) + expect(state.unsubscribeAgentAwakeStatusChanges).toBe(unsubscribeAgentAwakeStatusChanges) + + app.emit('before-quit', { defaultPrevented: false }) + + expect(state.isQuitting).toBe(true) + expect(fenceAndCloseNow).toHaveBeenCalledOnce() + expect(setMobileRelayPairingProvider).toHaveBeenCalledWith(null) + expect(unsubscribeAgentAwakeStatusChanges).toHaveBeenCalledOnce() + expect(dispose).toHaveBeenCalledOnce() + expect(stop).toHaveBeenCalledOnce() + for (const listener of process.listeners('exit')) { + if (!exitListenersBefore.includes(listener)) { + process.removeListener('exit', listener) + } + } +}) + +afterEach(() => { + vi.doUnmock('electron') + vi.doUnmock('../main-process-state') + for (const [moduleName] of dependencyExports) { + vi.doUnmock(moduleName) + } + vi.resetModules() +}) diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/quit/main-process-quit.ts similarity index 79% rename from src/main/startup/main-process-quit.ts rename to src/main/startup/quit/main-process-quit.ts index 0aec0ea1f8e..25d974530ef 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/quit/main-process-quit.ts @@ -1,45 +1,46 @@ -import { killWslChannelsInCloseGrace } from '../wsl/execution/wsl-command-channel' -import { markHostShuttingDown } from './quit/host-shutdown-state' +import { killWslChannelsInCloseGrace } from '../../wsl/execution/wsl-command-channel' +import { markHostShuttingDown } from './host-shutdown-state' import { app, type Event } from 'electron' -import { closeAllWatchers } from '../ipc/filesystem/watchers/filesystem-watcher-shutdown' -import { disposeWorktreeBaseDirectoryWatchers } from '../ipc/worktrees/creation/worktree-base-directory-watcher' -import { stopFolderRepoGitUpgradeWatch } from '../ipc/folder-repo-git-upgrade' -import { killAllPty } from '../ipc/pty/kill-all' +import { closeAllWatchers } from '../../ipc/filesystem/watchers/filesystem-watcher-shutdown' +import { disposeWorktreeBaseDirectoryWatchers } from '../../ipc/worktrees/creation/worktree-base-directory-watcher' +import { stopFolderRepoGitUpgradeWatch } from '../../ipc/folder-repo-git-upgrade' +import { killAllPty } from '../../ipc/pty/kill-all' import { disconnectDaemon, shutdownDaemon -} from '../daemon/providers/lifecycle/daemon-provider-state' -import { beginSshShutdown } from '../ipc/ssh/ssh-shutdown-drain' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' -import { removeManagedAgentHooksAsync } from '../agent-hooks/installation/managed-agent-hook-controls' -import { stopStructuredAgentSessionRuntime } from '../runtime/agent-session/structured-agent-session-runtime' -import { setStructuredAgentSessionTeardownTrigger } from '../runtime/agent-session/structured-agent-session-runtime-teardown' -import { awaitRuntimeFileWatcherUnsubscribes } from '../runtime/files/watch/file-watcher-leases' -import { clearRuntimeMetadataIfOwned } from '../runtime/rpc/server/runtime-metadata' -import { shutdownPairedRuntimeBrowserClientHosts } from '../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' -import { disposeDesktopBrowserBridge } from '../ipc/browser/desktop-browser-bridge-wiring' -import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' -import { stopCodexStateDbBackfillRecoveries } from '../codex/history/index/codex-state-db-backfill-recovery' -import { stopCodexAccountSessionBridges } from '../codex/history/bridges/codex-account-session-bridge' -import { awaitPackedRefsLockRelease } from '../git/refs/maintenance/local-repo-ref-maintenance' -import { stopBackgroundWorktreeRemovals } from '../workspaces/removal/worktree-background-removal' -import { settleTeardownWithinDeadline, settleWithinMs } from './quit/quit-teardown-deadline' -import { quitTeardownStartGate } from './quit/quit-teardown-start-gate' -import { setUnreadDockBadgeCount } from '../dock/unread-badge' -import { destroySystemTray } from '../tray/system-tray' -import { shutdownTelemetry } from '../telemetry/client' -import { shutdownObservability } from '../observability/index' -import { isQuittingForUpdate } from '../updater/updater-service' -import { recordUpdaterLifecycle } from '../updater/updater-lifecycle-diagnostics' -import { stopTccPromptNotice } from '../macos-permissions/macos-tcc-prompt-notice' -import { cancelHistoryGc } from '../pty/history/terminal-history-gc' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import { beginSshShutdown } from '../../ipc/ssh/ssh-shutdown-drain' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { wslHookRelayManager } from '../../agent-hooks/wsl-relay/wsl-hook-relay-manager' +import { removeManagedAgentHooksAsync } from '../../agent-hooks/installation/managed-agent-hook-controls' +import { stopStructuredAgentSessionRuntime } from '../../runtime/agent-session/structured-agent-session-runtime' +import { setStructuredAgentSessionTeardownTrigger } from '../../runtime/agent-session/structured-agent-session-runtime-teardown' +import { awaitRuntimeFileWatcherUnsubscribes } from '../../runtime/files/watch/file-watcher-leases' +import { clearRuntimeMetadataIfOwned } from '../../runtime/rpc/server/runtime-metadata' +import { shutdownPairedRuntimeBrowserClientHosts } from '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' +import { disposeDesktopBrowserBridge } from '../../ipc/browser/desktop-browser-bridge-wiring' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' +import { stopCodexStateDbBackfillRecoveries } from '../../codex/history/index/codex-state-db-backfill-recovery' +import { stopCodexAccountSessionBridges } from '../../codex/history/bridges/codex-account-session-bridge' +import { awaitPackedRefsLockRelease } from '../../git/refs/maintenance/local-repo-ref-maintenance' +import { stopBackgroundWorktreeRemovals } from '../../workspaces/removal/worktree-background-removal' +import { settleTeardownWithinDeadline, settleWithinMs } from './quit-teardown-deadline' +import { quitTeardownStartGate } from './quit-teardown-start-gate' +import { setUnreadDockBadgeCount } from '../../dock/unread-badge' +import { destroySystemTray } from '../../tray/system-tray' +import { shutdownTelemetry } from '../../telemetry/client' +import { shutdownObservability } from '../../observability/index' +import { isQuittingForUpdate } from '../../updater/updater-service' +import { recordUpdaterLifecycle } from '../../updater/updater-lifecycle-diagnostics' +import { stopTccPromptNotice } from '../../macos-permissions/macos-tcc-prompt-notice' +import { cancelHistoryGc } from '../../pty/history/terminal-history-gc' import { shouldQuitWhenAllWindowsClosed } from './window-all-closed-quit-policy' -import { desktopConnectorCloud } from './main-process-connector-startup' -import { mainProcessState as state } from './main-process-state' -import { isDevParentShutdownRequested } from './configure-process' -import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' -import { flushUnsavedCloudSessions } from '../orca-profiles/cloud-session/profile-cloud-session-owner' +import { desktopConnectorCloud } from '../cloud-startup/main-process-connector-startup' +import { mainProcessState as state } from '../main-process-state' +import { isDevParentShutdownRequested } from '../configure-process' +import { getCanonicalUserDataPath } from '../../persistence/loading-store/user-data-path' +import { flushUnsavedCloudSessions } from '../../orca-profiles/cloud-session/profile-cloud-session-owner' +import { getWorkspaceCleanupRunner } from '../../workspaces/cleanup/workspace-cleanup-runner-registry' // First will-quit pass awaits teardown; the re-fired pass must exit without starting writes again. let daemonDisconnectDone = false @@ -136,6 +137,9 @@ function installWillQuitHandler(): void { // Final stats flush closes working sessions synchronously; quit supplies no terminating hook to preserve their duration. state.starNag?.stop() state.automations?.stop() + if (state.runtime) { + getWorkspaceCleanupRunner(state.runtime)?.stop() + } // Why: plugin hosts are forked children; dispose sends shutdown and // escalates to SIGKILL so they cannot outlive the app. The promise joins // the teardown barrier below — quitting before it resolves would let @@ -200,7 +204,7 @@ function installWillQuitHandler(): void { })() // Local SSH browser routes own loopback listeners and ssh -N -D children that must not outlive the app (P2-4). const localSshRouteShutdown = - import('../browser/routing/local-host-partitions/local-ssh-browser-route') + import('../../browser/routing/local-host-partitions/local-ssh-browser-route') .then((routes) => routes.closeAllLocalSshBrowserRoutes()) .catch(() => {}) browserManager.setBrowserGuestStateChangedListener(null) diff --git a/src/main/startup/process-quit-request.ts b/src/main/startup/quit/process-quit-request.ts similarity index 100% rename from src/main/startup/process-quit-request.ts rename to src/main/startup/quit/process-quit-request.ts diff --git a/src/main/startup/quit-and-stop-all-sessions-prompt.ts b/src/main/startup/quit/quit-and-stop-all-sessions-prompt.ts similarity index 97% rename from src/main/startup/quit-and-stop-all-sessions-prompt.ts rename to src/main/startup/quit/quit-and-stop-all-sessions-prompt.ts index 388be0b580a..0805e2c6675 100644 --- a/src/main/startup/quit-and-stop-all-sessions-prompt.ts +++ b/src/main/startup/quit/quit-and-stop-all-sessions-prompt.ts @@ -1,5 +1,5 @@ import type { MessageBoxOptions, MessageBoxReturnValue } from 'electron' -import { translateMain } from '../i18n/main-i18n' +import { translateMain } from '../../i18n/main-i18n' const CONFIRM_BUTTON_INDEX = 0 const CANCEL_BUTTON_INDEX = 1 diff --git a/src/main/startup/window-all-closed-quit-policy.ts b/src/main/startup/quit/window-all-closed-quit-policy.ts similarity index 100% rename from src/main/startup/window-all-closed-quit-policy.ts rename to src/main/startup/quit/window-all-closed-quit-policy.ts diff --git a/src/main/startup/runtime-startup/main-process-automations.ts b/src/main/startup/runtime-startup/main-process-automations.ts new file mode 100644 index 00000000000..a7cf2cd291a --- /dev/null +++ b/src/main/startup/runtime-startup/main-process-automations.ts @@ -0,0 +1,23 @@ +import type { AutomationService } from '../../automations/automation-service' +import { createRuntimeAutomationService } from '../../automations/runtime-automation-service' +import { mainProcessState as state } from '../main-process-state' + +export function initializeMainProcessAutomations(): AutomationService { + const store = state.store + const runtime = state.runtime + const claudeUsage = state.claudeUsage + const codexUsage = state.codexUsage + if (!store || !runtime || !claudeUsage || !codexUsage) { + throw new Error('Runtime and usage stores must be initialized before automations') + } + const service = createRuntimeAutomationService({ + store, + runtime, + claudeUsage, + codexUsage, + // Remote clients mirror schedules; only server processes execute remote_host_service ownership. + allowRemoteHostScheduling: state.isServeMode + }) + state.automations = service + return service +} diff --git a/src/main/startup/main-process-runtime-launch.ts b/src/main/startup/runtime-startup/main-process-runtime-launch.ts similarity index 77% rename from src/main/startup/main-process-runtime-launch.ts rename to src/main/startup/runtime-startup/main-process-runtime-launch.ts index d6443259642..4442b5326c5 100644 --- a/src/main/startup/main-process-runtime-launch.ts +++ b/src/main/startup/runtime-startup/main-process-runtime-launch.ts @@ -1,59 +1,60 @@ import { app, type BrowserWindow } from 'electron' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' -import { placeUnshownLiveTerminalsBestEffort } from '../runtime/terminal/adoption/unshown-live-terminal-placement' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +import { placeUnshownLiveTerminalsBestEffort } from '../../runtime/terminal/adoption/unshown-live-terminal-placement' import { getCanonicalUserDataPath, migrateMobilePairingDataToCanonicalUserDataPath -} from '../persistence/loading-store/user-data-path' -import { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' -import { resolveServePinnedBindHost } from './serve-pinned-bind-host' -import { isOrcadSidecarLaunch } from '../window/foreground-activation-policy' -import { registerMobileHandlers } from '../ipc/mobile' -import { createRuntimeEnvironmentMobileRelayHosts } from '../ipc/runtime-environments/runtime-environment-mobile-relay-hosts' -import { getLocalPtyProvider } from '../ipc/pty/provider/registry' -import { registerHeadlessPtyRuntime } from '../ipc/pty/register-headless-runtime' -import { LocalPtyProvider } from '../providers/local-pty/local-pty-provider' -import { publishHeadlessRuntimeGraph } from '../runtime/session-graph/headless-runtime-graph' -import { OffscreenBrowserBackend } from '../browser/backends/offscreen-browser-backend' -import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' -import { getDesktopRelayStatus } from './main-process-relay-status' -import { startDesktopRelayService } from './main-process-relay-startup' -import { getServeOptions, getBundledWebClientRoot, printServeReady } from './main-process-serve' +} from '../../persistence/loading-store/user-data-path' +import { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' +import { resolveServePinnedBindHost } from '../serve-launch/serve-pinned-bind-host' +import { isOrcadSidecarLaunch } from '../../window/activation/foreground-activation-policy' +import { registerMobileHandlers } from '../../ipc/mobile' +import { createRuntimeEnvironmentMobileRelayHosts } from '../../ipc/runtime-environments/mobile-relay/runtime-environment-mobile-relay-hosts' +import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' +import { registerHeadlessPtyRuntime } from '../../ipc/pty/register-headless-runtime' +import { LocalPtyProvider } from '../../providers/local-pty/local-pty-provider' +import { publishHeadlessRuntimeGraph } from '../../runtime/session-graph/headless-runtime-graph' +import { OffscreenBrowserBackend } from '../../browser/backends/offscreen-browser-backend' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' +import { getDesktopRelayStatus } from '../cloud-startup/main-process-relay-status' +import { startDesktopRelayService } from '../cloud-startup/main-process-relay-startup' +import { getServeOptions } from '../serve-launch/serve-options' +import { getBundledWebClientRoot, printServeReady } from '../serve-launch/main-process-serve' import { bindTerminalRuntimeStartupServices, handleCodexHomePtySpawned, handlePtyExit, startTerminalRuntimeStartupServices -} from './main-process-pty-startup' -import { prepareCodexRuntimeHomeForLaunch } from './codex-launch-preparation' -import { prepareCodexSessionResumeForLaunch } from './codex-session-resume-launch' -import { startWindowsDesktopBeforeShellPathReady } from './windows-desktop-shell-path-startup' -import { repairKnownPoisonedInstallDirBeforeWindow } from './windows-install-dir-acl-recovery' -import { installServeQuitHandling } from './serve-quit-handling' -import { installCloudSessionShutdownFlush } from './cloud-session-shutdown-flush' -import { registerHeadlessServeSshHandlers } from './headless-serve-ssh-registration' -import { settleServeDesktopActivation } from './serve-desktop-activation' +} from '../pty-startup/main-process-pty-startup' +import { prepareCodexRuntimeHomeForLaunch } from '../agent-accounts/codex-launch-preparation' +import { prepareCodexSessionResumeForLaunch } from '../agent-accounts/codex-session-resume-launch' +import { startWindowsDesktopBeforeShellPathReady } from '../shell-environment/windows-desktop-shell-path-startup' +import { repairKnownPoisonedInstallDirBeforeWindow } from '../windows-install-permissions/windows-install-dir-acl-recovery' +import { installServeQuitHandling } from '../serve-launch/serve-quit-handling' +import { installCloudSessionShutdownFlush } from '../cloud-startup/cloud-session-shutdown-flush' +import { registerHeadlessServeSshHandlers } from '../serve-launch/headless-serve-ssh-registration' +import { settleServeDesktopActivation } from '../serve-launch/serve-desktop-activation' import { recordRuntimeRpcStartFailure, showRuntimeRpcStartupFailureDialog -} from '../runtime/rpc/server/runtime-rpc-startup-failure' -import { registerCliForHeadlessServe } from './serve-cli-registration' -import { startAppImageCopyPreExtraction } from '../cli/appimage/appimage-copy-pre-extraction' -import { scheduleAllPendingHistoryTreeRemovals } from '../pty/history/terminal-history-deletion' -import { triggerStartupNotificationRegistration } from '../ipc/startup-notification-registration' -import { startDesktopPushService } from './main-process-push-startup' +} from '../../runtime/rpc/server/runtime-rpc-startup-failure' +import { registerCliForHeadlessServe } from '../serve-launch/serve-cli-registration' +import { startAppImageCopyPreExtraction } from '../../cli/appimage/appimage-copy-pre-extraction' +import { scheduleAllPendingHistoryTreeRemovals } from '../../pty/history/terminal-history-deletion' +import { triggerStartupNotificationRegistration } from '../../ipc/startup-notification-registration' +import { startDesktopPushService } from '../cloud-startup/main-process-push-startup' import { connectDesktopConnectorCloud, installDesktopConnectorCloud -} from './main-process-connector-startup' -import { mainProcessState as state } from './main-process-state' -import { logStartupMilestone } from './startup-diagnostics' -import { setupHeadlessServeAutoUpdater } from '../window/main-window-updater' -import { preserveStateBeforeUpdateRestart } from '../updater/update-restart-preservation' -import { resolveUpdateInstallMode } from '../updater/updater-service' -import { scheduleAgentLaunchRecordWarmup } from './agent-launch-record-warmup' -import { emitServeBrowserIdentityActionLine } from '../server/serve-stdout-boundary' -import { getBrowserIdentityModeStatus } from '../browser/identity/mode/browser-identity-mode-store' +} from '../cloud-startup/main-process-connector-startup' +import { mainProcessState as state } from '../main-process-state' +import { logStartupMilestone } from '../diagnostics/startup-diagnostics' +import { setupHeadlessServeAutoUpdater } from '../../updater/lifecycle/main-window-updater' +import { preserveStateBeforeUpdateRestart } from '../../updater/update-restart-preservation' +import { resolveUpdateInstallMode } from '../../updater/updater-service' +import { scheduleAgentLaunchRecordWarmup } from '../agent-accounts/agent-launch-record-warmup' +import { emitServeBrowserIdentityActionLine } from '../../server/serve-stdout-boundary' +import { getBrowserIdentityModeStatus } from '../../browser/identity/mode/browser-identity-mode-store' type RuntimeService = NonNullable diff --git a/src/main/startup/runtime-startup/main-process-runtime-service.ts b/src/main/startup/runtime-startup/main-process-runtime-service.ts new file mode 100644 index 00000000000..3ff04d8e183 --- /dev/null +++ b/src/main/startup/runtime-startup/main-process-runtime-service.ts @@ -0,0 +1,233 @@ +import { wireRecipeWorkspaceRemoval } from '../../ephemeral-vm/recipe-workspace-removal-wiring' +import { wireGitHubIssueLinkTitleFill } from '../../github/workspace-links/github-issue-link-title-wiring' +import { + applySessionSearchSettingsChange, + installChildSessionSearchService +} from '../../ai-vault-search/session-search-enablement' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { sessionSearchScopeCatalogFromStore } from '../../ai-vault-search/scope/session-search-store-scope-catalog' +import { getCanonicalUserDataPath } from '../../persistence/loading-store/user-data-path' +import { app } from 'electron' +import { translateMain } from '../../i18n/main-i18n' +import { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' +import { clearProviderPtyState } from '../../ipc/pty/provider/state-cleanup' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { toAgentStatusIpcPayload } from '../../agent-hooks/server/server-status-identity' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../browser/sessions/profiles/browser-session-registry' +import { loadAgentSessionClaimSigner } from '../../runtime/agent-session/ownership/agent-session-claim-identity' +import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' +import { codexAiVaultSessionResumePreparation } from '../../codex/history/resume/codex-ai-vault-session-resume' +import { prepareCodexPinnedLaunchHome } from '../agent-accounts/codex-session-resume-launch' +import { resolveHostCodexSessionSourceHome } from '../../codex/history/rollouts/codex-session-source-home' +import { agentHookRuntimeDeps } from '../../agent-hooks/runtime/agent-hook-runtime-deps' +import { getDaemonProvider } from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' +import { resolveTuiAgentLaunchEnv } from '../../../shared/agent-launch/choices/tui-agent-launch-defaults' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/requests/runtime-environment-transport-routing' +import { createOrchestrationEnvironmentTransport } from '../../ipc/runtime-environments/requests/orchestration-environment-transport' +import { trackRuntimeEnvironmentVerifiedTransitions } from '../../ipc/runtime-environments/status/runtime-environment-verified-transitions' +import { onRuntimeEnvironmentStatusPublished } from '../../ipc/runtime-environments/status/runtime-environment-status-owner' +import { mainProcessState as state } from '../main-process-state' +import { suspendEphemeralVmWorkspace } from '../../ephemeral-vm/workspace-suspend' +import { + acceptEphemeralVmWorkspaceWake, + resumeEphemeralVmWorkspace +} from '../../ephemeral-vm/workspace-resume' +import { registerRecipeVmWaker } from '../../runtime/workspaces/sleep/recipe-vm-waker-registry' +import { setSshHostAsleepCheck } from '../../ssh/connection/ssh-host-sleep-hold' +import { + isRecipeVmSshTargetAsleep, + setRecipeVmAsleepStoreRoot +} from '../../ephemeral-vm/recipe-vm-asleep' +import { openRecipeVmEnvironment } from '../../ipc/runtime-environments/managed-orcad/runtime-environment-recipe-vm-wake' +import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { findWorkspaceEphemeralVmRuntime } from '../../../shared/ephemeral-vm-workspace-runtime' +import { installWslOrcadAccountShim } from '../wsl-startup/wsl-orcad-account-env-wiring' +import { + codexStructuredLaunchHomeResolvers, + prepareCodexRuntimeHomeForLaunch +} from '../agent-accounts/codex-launch-preparation' +import { resolveHostAgentBaseEnvironment } from '../../runtime/agent-session/environment/structured-agent-shell-environment' +import type { RuntimeDesktopWindowStatus } from '../../../shared/runtime-session-contracts' +import { ArtifactCloudService } from '../../artifacts/artifact-cloud-service' +import { SkillCloudService } from '../../skills/cloud/skill-cloud-package-service' +import { isArtifactSharingEnabled } from '../../../shared/artifacts/artifact-sharing-gate' +import { + AgentStatusObservedPaneIdentities, + recordObservedAgentStatusPaneIdentity +} from '../../runtime/terminal/identity/agent-status-observed-pane-identity' +import { startAgentStateRulesLiveUpdates } from '../../runtime/agent-state-rules/agent-state-rules-live-update' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/catalog/runtime-environment-registry-root' +import { openOffscreenBrowserPageLink } from '../../runtime/browser/commands/offscreen-browser-page-link' + +export function getDesktopWindowStatus(): RuntimeDesktopWindowStatus { + const activation = state.desktopActivationGate + if (!activation) { + return 'available' + } + const value = activation.getState() + return value === 'ready' ? 'openable' : value +} + +export function initializeMainProcessRuntime(): OrcaRuntimeService { + const store = state.store + const stats = state.stats + if (!store || !stats) { + throw new Error('Store and stats must be initialized before runtime') + } + // Process-scope subscription covers desktop, headless serve and fleet status. + const observedPaneIdentities = new AgentStatusObservedPaneIdentities() + const runtime = new OrcaRuntimeService(store, stats, { + getSetupTerminalTitle: () => translateMain('worktree.setupTerminalTitle', 'Setup'), + ...agentHookRuntimeDeps(agentHookServer, observedPaneIdentities, () => + state.store?.getSettings() + ), + prepareClaudeAuth: (target) => state.claudeRuntimeAuth!.prepareForClaudeLaunch(target), + agentSessionClaimSigner: loadAgentSessionClaimSigner( + getProfileUserDataPath(), + getProfileUserDataPath() + ), + // Resolve provider lazily or later daemon adoption leaves a frozen pre-daemon reference (design §4.3). + getLocalProvider: () => getLocalPtyProvider(), + onPtyStopped: clearProviderPtyState, + // Serve can activate in place; wire now, but enable desktop scanners only for a ready renderer. + onTerminalSideEffects: (batch: TerminalSideEffectBatch) => { + if (state.mainWindow && !state.mainWindow.isDestroyed()) { + state.mainWindow.webContents.send('pty:sideEffect', batch) + } + }, + getDesktopWindowStatus, + attestAgentHookCompatibilityAuthority: (candidate) => + agentHookServer.attestCompatibilityAuthority(candidate), + retireAgentHookCompatibilityAuthority: (paneKey) => + agentHookServer.retirePaneAuthority(paneKey), + canRecoverPersistentLocalPtys: () => getDaemonProvider() !== null, + // Resolve per call: the RPC server/device registry is constructed later with this runtime. + getPairedDeviceName: (pairedDeviceId) => + state.runtimeRpc?.getDeviceRegistry()?.getDevice(pairedDeviceId)?.name ?? null, + // Provide managed Codex homes here for desktop and headless session discovery; core IPC registration is window-only. + getAdditionalAiVaultCodexHomePaths: () => + state.codexRuntimeHome?.getHostCodexHomePathsForSessionDiscovery() ?? [], + prepareAiVaultSessionResume: codexAiVaultSessionResumePreparation(() => ({ + runtimeHome: state.codexRuntimeHome, + systemCodexHomePath: resolveHostCodexSessionSourceHome(store.getSettings()), + preparePinnedLaunchHome: (home) => prepareCodexPinnedLaunchHome(home) + })), + ...codexStructuredLaunchHomeResolvers, + prepareCodexCatalogProbeHome: (homePath) => + state.codexRuntimeHome?.prepareHostCodexHomeForReadOnlyAppServer( + homePath, + resolveTuiAgentLaunchEnv('codex', store.getSettings()) + ), + orchestrationEnvironmentTransport: { + ...createOrchestrationEnvironmentTransport(), + onEnvironmentVerified: (listener) => + onRuntimeEnvironmentStatusPublished(trackRuntimeEnvironmentVerifiedTransitions(listener)) + }, + workspaceSleepPlatform: { + callEnvironment: (environmentId, method, params, timeoutMs) => + callRuntimeEnvironment( + getRuntimeEnvironmentRegistryRoot(), + environmentId, + method, + params, + timeoutMs + ), + ownsVm: (workspaceId) => + findWorkspaceEphemeralVmRuntime(app.getPath('userData'), workspaceId) !== undefined, + suspendVm: (workspaceId) => suspendEphemeralVmWorkspace(store, workspaceId), + acceptWake: (workspaceId) => acceptEphemeralVmWorkspaceWake(workspaceId), + resumeVm: (workspaceId, request) => resumeEphemeralVmWorkspace(store, workspaceId, request) + }, + // Paired/local settings writes must reconcile the scanner child through the same path. + applySessionSearchSettings: applySessionSearchSettingsChange, + skillTransactionRecovery: state.skillTransactionRecovery + }) + // Both desktop and headless serve own a host-local search service. + const sessionSearch = installChildSessionSearchService({ + dataRoot: getCanonicalUserDataPath(), + getSettings: () => store.getSettings(), + // Read the host catalog per search so added repos/renamed workspaces are immediately in scope. + getScopeCatalog: () => sessionSearchScopeCatalogFromStore(store, LOCAL_EXECUTION_HOST_ID) + }) + app.once('will-quit', () => sessionSearch?.dispose()) + // Desktop and headless hosts each evaluate their own panes' rules. + startAgentStateRulesLiveUpdates(store, (rules) => + recordDurableCrashBreadcrumb('agent_state_rules_active', rules) + ) + wireRecipeWorkspaceRemoval(runtime, store, () => app.getPath('userData')) + // Each host titles its own workspaces' untitled GitHub issue links once, when they are linked. + const disposeIssueLinkTitleFill = wireGitHubIssueLinkTitleFill(store, runtime) + app.once('will-quit', disposeIssueLinkTitleFill) + state.runtime = runtime + // Opening a recipe VM's workspace from a client wakes the VM through the runtime's one owner. + registerRecipeVmWaker({ + state: (workspaceId, suspended) => runtime.workspaceVmState(workspaceId, suspended), + noteOpened: (workspaceId) => runtime.noteWorkspaceReopened(workspaceId), + holdOpen: (workspaceId, suspended, timeoutMs, signal) => + runtime.holdWorkspaceVmOpen(workspaceId, suspended, timeoutMs, signal), + openEnvironment: (selector) => { + const root = getRuntimeEnvironmentRegistryRoot() + return openRecipeVmEnvironment(root, resolveEnvironment(root, selector)) + } + }) + // A sleeping VM's SSH host takes no background login until its workspace wakes (#36363). + setRecipeVmAsleepStoreRoot(getRuntimeEnvironmentRegistryRoot) + setSshHostAsleepCheck((targetId) => isRecipeVmSshTargetAsleep(app.getPath('userData'), targetId)) + runtime.attachAgentStatusStore(agentHookServer) + agentHookServer.subscribeEnrichedStatus((enriched) => + recordObservedAgentStatusPaneIdentity(observedPaneIdentities, enriched, runtime) + ) + agentHookServer.setCliWriterExecutionMatcher(observedPaneIdentities, runtime) + agentHookServer.setClaudePermissionHolds(runtime.terminalWorkerApprovals) + // Main records pane resume state from accepted status. + if (ORCA_LAYOUT_OWNER_IS_MAIN) { + agentHookServer.subscribeEnrichedStatus((enriched) => + runtime.recordHookStatusResume(toAgentStatusIpcPayload(enriched)) + ) + agentHookServer.subscribePaneStatusClear((clear) => runtime.forgetHookStatusResume(clear)) + agentHookServer.subscribeStatusDrop((paneKey) => runtime.forgetHookStatusResume({ paneKey })) + } + // Rehydrate before clients attach so restarted runtimes can return their owned pages. + runtime.rehydrateClientHostedBrowserPages() + browserManager.setBrowserGuestStateChangedListener((worktreeId) => { + runtime.notifyMobileSessionTabsChanged(worktreeId) + }) + browserManager.setOffscreenTabOpener((request) => + openOffscreenBrowserPageLink( + (params, caller) => runtime.browserTabCreate(params, caller), + request + ) + ) + browserSessionRegistry.onProfilesChanged = () => runtime.notifyBrowserProfilesChanged() + runtime.startupWorkerAuthority.begin() + return runtime +} + +export function configureRuntimeServices(runtime: OrcaRuntimeService): void { + const store = state.store + const claudeAccounts = state.claudeAccounts + const codexAccounts = state.codexAccounts + const rateLimits = state.rateLimits + if (!store || !claudeAccounts || !codexAccounts || !rateLimits) { + throw new Error('Account services must be initialized before runtime wiring') + } + runtime.setArtifactService( + new ArtifactCloudService(app.getPath('userData'), () => + isArtifactSharingEnabled(state.store?.getSettings()) + ) + ) + runtime.setSkillCloudService(new SkillCloudService(app.getPath('userData'))) + runtime.setAccountServices({ claudeAccounts, codexAccounts, rateLimits }) + installWslOrcadAccountShim(store) + runtime.setCommitMessageAgentEnvironmentResolvers({ + // Resolve every Codex launch through runtime-home, including default-account hooks/auth. + prepareForCodexLaunch: prepareCodexRuntimeHomeForLaunch, + prepareForClaudeLaunch: (target) => state.claudeRuntimeAuth!.prepareForClaudeLaunch(target), + resolveBaseEnvironment: () => resolveHostAgentBaseEnvironment(store.getSettings()) + }) +} diff --git a/src/main/startup/serve-launch/headless-serve-ssh-registration.ts b/src/main/startup/serve-launch/headless-serve-ssh-registration.ts new file mode 100644 index 00000000000..6750ad92440 --- /dev/null +++ b/src/main/startup/serve-launch/headless-serve-ssh-registration.ts @@ -0,0 +1,9 @@ +import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { registerSshHandlers } from '../../ipc/ssh/ssh' +import { mainProcessState as state } from '../main-process-state' + +/** Register SSH before any window so headless serve can list/connect targets (#25886, #8489); later window registration is idempotent. */ +export function registerHeadlessServeSshHandlers(store: Store, runtime: OrcaRuntimeService): void { + registerSshHandlers(store, () => state.mainWindow ?? null, runtime) +} diff --git a/src/main/startup/headless-serve-x11-reexec.ts b/src/main/startup/serve-launch/headless-serve-x11-reexec.ts similarity index 97% rename from src/main/startup/headless-serve-x11-reexec.ts rename to src/main/startup/serve-launch/headless-serve-x11-reexec.ts index 68f6319ca60..e6782cfb9d0 100644 --- a/src/main/startup/headless-serve-x11-reexec.ts +++ b/src/main/startup/serve-launch/headless-serve-x11-reexec.ts @@ -2,7 +2,7 @@ import { app } from 'electron' import { HEADLESS_SERVE_OZONE_PLATFORM_SWITCH, hasExplicitOzonePlatform -} from '../../shared/headless-serve-ozone-platform' +} from '../../../shared/headless-serve-ozone-platform' export type HeadlessServeX11ReexecOptions = { isServeMode: boolean diff --git a/src/main/startup/serve-launch/main-process-serve.ts b/src/main/startup/serve-launch/main-process-serve.ts new file mode 100644 index 00000000000..a6c7fa3735b --- /dev/null +++ b/src/main/startup/serve-launch/main-process-serve.ts @@ -0,0 +1,33 @@ +import { app } from 'electron' +import { notifyServeSupervisorReady } from '../../updater/serve-update-handoff' +import { clearServeAbortPark } from '../../../shared/serve-abort-park' +import { findBundledWebClientRoot } from '../../../shared/bundled-web-client-root' +import { buildServePairingReadiness, servePublishMode } from '../../server/serve-pairing-readiness' +import { mainProcessState as state } from '../main-process-state' +import type { ServeOptions } from './serve-options' + +export function getBundledWebClientRoot(): string | undefined { + return findBundledWebClientRoot(app.getAppPath()) +} + +export async function printServeReady(options: ServeOptions): Promise { + const runtime = state.runtime + const runtimeRpc = state.runtimeRpc + if (!runtime || !runtimeRpc) { + throw new Error('Runtime server must be initialized before printing serve readiness') + } + // Validate project root before pairing publication can persist a pending device. + const output = servePublishMode(options) + await state.serveReadinessPublisher.publish( + { + runtimeId: runtime.getRuntimeId(), + ...(await buildServePairingReadiness(options, runtimeRpc)), + // WSL barrier fails open; pending warns clients PTY launch may still race repair. + managedWslCliReconciliation: state.managedWslCliReconciliationStatus + }, + output + ) + notifyServeSupervisorReady(runtime.getRuntimeId()) + // Successful readiness disproves the previous serve-abort park. + clearServeAbortPark(app.getPath('userData')) +} diff --git a/src/main/startup/serve-cli-registration.ts b/src/main/startup/serve-launch/serve-cli-registration.ts similarity index 87% rename from src/main/startup/serve-cli-registration.ts rename to src/main/startup/serve-launch/serve-cli-registration.ts index e4925df94ba..5d15c335957 100644 --- a/src/main/startup/serve-cli-registration.ts +++ b/src/main/startup/serve-launch/serve-cli-registration.ts @@ -1,8 +1,8 @@ import { app } from 'electron' -import { resolveAppImageRuntimeIdentity } from '../updater/linux-package/appimage-runtime-identity' -import { prepareAppImageCopyForServe } from '../cli/appimage/appimage-serve-preparation' -import { CliInstaller } from '../cli/cli-installer' -import { installLinuxBareOrcaDispatcher } from '../cli/launchers/linux-bare-orca-dispatcher' +import { resolveAppImageRuntimeIdentity } from '../../updater/linux-package/appimage-runtime-identity' +import { prepareAppImageCopyForServe } from '../../cli/appimage/appimage-serve-preparation' +import { CliInstaller } from '../../cli/cli-installer' +import { installLinuxBareOrcaDispatcher } from '../../cli/launchers/linux-bare-orca-dispatcher' /** Headless serve has no renderer to run the normal cli:install flow, so it registers here. */ export async function registerCliForHeadlessServe(): Promise { diff --git a/src/main/startup/serve-desktop-activation.test.ts b/src/main/startup/serve-launch/serve-desktop-activation.test.ts similarity index 100% rename from src/main/startup/serve-desktop-activation.test.ts rename to src/main/startup/serve-launch/serve-desktop-activation.test.ts diff --git a/src/main/startup/serve-desktop-activation.ts b/src/main/startup/serve-launch/serve-desktop-activation.ts similarity index 96% rename from src/main/startup/serve-desktop-activation.ts rename to src/main/startup/serve-launch/serve-desktop-activation.ts index 3e653366104..e1bc1731f23 100644 --- a/src/main/startup/serve-desktop-activation.ts +++ b/src/main/startup/serve-launch/serve-desktop-activation.ts @@ -1,4 +1,4 @@ -import type { RuntimeDesktopWindowStatus } from '../../shared/runtime-types' +import type { RuntimeDesktopWindowStatus } from '../../../shared/runtime-session-contracts' type ActivationGateState = Exclude | 'ready' diff --git a/src/main/startup/serve-mode-argv.test.ts b/src/main/startup/serve-launch/serve-mode-argv.test.ts similarity index 100% rename from src/main/startup/serve-mode-argv.test.ts rename to src/main/startup/serve-launch/serve-mode-argv.test.ts diff --git a/src/main/startup/serve-mode-argv.ts b/src/main/startup/serve-launch/serve-mode-argv.ts similarity index 100% rename from src/main/startup/serve-mode-argv.ts rename to src/main/startup/serve-launch/serve-mode-argv.ts diff --git a/src/main/startup/serve-native-quit-guard.ts b/src/main/startup/serve-launch/serve-native-quit-guard.ts similarity index 96% rename from src/main/startup/serve-native-quit-guard.ts rename to src/main/startup/serve-launch/serve-native-quit-guard.ts index d17fc1cc1c8..0c3890ac6e1 100644 --- a/src/main/startup/serve-native-quit-guard.ts +++ b/src/main/startup/serve-launch/serve-native-quit-guard.ts @@ -1,5 +1,5 @@ import { app, powerMonitor, type Event } from 'electron' -import { isProcessQuitRequested, markProcessQuitRequested } from './process-quit-request' +import { isProcessQuitRequested, markProcessQuitRequested } from '../quit/process-quit-request' /** macOS native Quit must close serve windows without disconnecting paired clients (#15537). Signals/supervisor/updates mark process quit; shutdown/logout do too so they remain allowed. */ export function installServeNativeQuitGuard(deps: { diff --git a/src/main/startup/serve-options.ts b/src/main/startup/serve-launch/serve-options.ts similarity index 97% rename from src/main/startup/serve-options.ts rename to src/main/startup/serve-launch/serve-options.ts index a06564ed78e..97e69df8727 100644 --- a/src/main/startup/serve-options.ts +++ b/src/main/startup/serve-launch/serve-options.ts @@ -1,8 +1,8 @@ import { getServeFlagTypoError, getServeOptionValidationError -} from '../../shared/serve-option-validation' -import { resolveOrcadBindHost } from '../../shared/orcad-bind-address' +} from '../../../shared/serve-option-validation' +import { resolveOrcadBindHost } from '../../../shared/orcad-bind-address' export type ServeOptions = { json: boolean diff --git a/src/main/startup/serve-pinned-bind-host.test.ts b/src/main/startup/serve-launch/serve-pinned-bind-host.test.ts similarity index 93% rename from src/main/startup/serve-pinned-bind-host.test.ts rename to src/main/startup/serve-launch/serve-pinned-bind-host.test.ts index 01ffca08b0b..3d30df04722 100644 --- a/src/main/startup/serve-pinned-bind-host.test.ts +++ b/src/main/startup/serve-launch/serve-pinned-bind-host.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import '../runtime/rpc/server/runtime-rpc-pairing-types' +import '../../runtime/rpc/server/runtime-rpc-pairing-types' import './serve-mode-argv' import { getServeOptions } from './serve-options' import './serve-pinned-bind-host' diff --git a/src/main/startup/serve-pinned-bind-host.ts b/src/main/startup/serve-launch/serve-pinned-bind-host.ts similarity index 85% rename from src/main/startup/serve-pinned-bind-host.ts rename to src/main/startup/serve-launch/serve-pinned-bind-host.ts index 6288bd0eefb..a9a6aa4a122 100644 --- a/src/main/startup/serve-pinned-bind-host.ts +++ b/src/main/startup/serve-launch/serve-pinned-bind-host.ts @@ -1,4 +1,4 @@ -import { WS_BIND_HOST_LOOPBACK } from '../runtime/rpc/server/runtime-rpc-pairing-types' +import { WS_BIND_HOST_LOOPBACK } from '../../runtime/rpc/server/runtime-rpc-pairing-types' import type { ServeOptions } from './serve-options' /** Undefined keeps the runtime's own choice: all interfaces for serve, loopback until pairing for the desktop. */ diff --git a/src/main/startup/serve-quit-handling.ts b/src/main/startup/serve-launch/serve-quit-handling.ts similarity index 76% rename from src/main/startup/serve-quit-handling.ts rename to src/main/startup/serve-launch/serve-quit-handling.ts index c7e5a25f1f3..c0b6996b35c 100644 --- a/src/main/startup/serve-quit-handling.ts +++ b/src/main/startup/serve-launch/serve-quit-handling.ts @@ -1,6 +1,6 @@ -import { isQuittingForUpdate } from '../updater/updater-service' -import { quitFromUserCommand } from './main-window-actions' -import { quitProcess } from './process-quit-request' +import { isQuittingForUpdate } from '../../updater/updater-service' +import { quitFromUserCommand } from '../main-window/main-window-actions' +import { quitProcess } from '../quit/process-quit-request' import { installServeNativeQuitGuard } from './serve-native-quit-guard' import { registerServeSignalHandlers } from './serve-signal-handlers' diff --git a/src/main/startup/serve-signal-handlers.ts b/src/main/startup/serve-launch/serve-signal-handlers.ts similarity index 100% rename from src/main/startup/serve-signal-handlers.ts rename to src/main/startup/serve-launch/serve-signal-handlers.ts diff --git a/src/main/startup/serve-user-data-path-guard.test.ts b/src/main/startup/serve-launch/serve-user-data-path-guard.test.ts similarity index 96% rename from src/main/startup/serve-user-data-path-guard.test.ts rename to src/main/startup/serve-launch/serve-user-data-path-guard.test.ts index 5030ced5b37..e5be57f3dcd 100644 --- a/src/main/startup/serve-user-data-path-guard.test.ts +++ b/src/main/startup/serve-launch/serve-user-data-path-guard.test.ts @@ -39,7 +39,7 @@ describe('checkServeUserDataPath', () => { describe('configureOrcaUserDataPathEnv on a serve launch', () => { it('throws before the instance lock instead of publishing a mismatched profile', async () => { vi.doMock('electron', () => ({ app: { getPath: () => '/default/orca' } })) - const { configureOrcaUserDataPathEnv } = await import('./configure-process') + const { configureOrcaUserDataPathEnv } = await import('../configure-process') const argv = process.argv const previous = process.env.ORCA_USER_DATA_PATH process.argv = [...argv, '--serve'] diff --git a/src/main/startup/serve-user-data-path-guard.ts b/src/main/startup/serve-launch/serve-user-data-path-guard.ts similarity index 96% rename from src/main/startup/serve-user-data-path-guard.ts rename to src/main/startup/serve-launch/serve-user-data-path-guard.ts index c447ceb1b9c..32a3d2dd603 100644 --- a/src/main/startup/serve-user-data-path-guard.ts +++ b/src/main/startup/serve-launch/serve-user-data-path-guard.ts @@ -1,4 +1,4 @@ -import { SERVE_USER_DATA_PATH_ENV, isSameUserDataPath } from '../../shared/serve-user-data-path' +import { SERVE_USER_DATA_PATH_ENV, isSameUserDataPath } from '../../../shared/serve-user-data-path' /** Reject mismatched serve profiles before locking: a lock loss on the wrong profile can activate the user's desktop. */ export function checkServeUserDataPath(options: { diff --git a/src/main/startup/serve-native-quit-guard.test.ts b/src/main/startup/serve-native-quit-guard.test.ts deleted file mode 100644 index 8bf75573123..00000000000 --- a/src/main/startup/serve-native-quit-guard.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -type Listener = (...args: any[]) => void -const electron = vi.hoisted(() => { - const beforeQuit: Listener[] = [] - const powerListeners: Record = {} - return { beforeQuit, powerListeners, quit: vi.fn() } -}) - -vi.mock('electron', () => ({ - app: { - quit: electron.quit, - prependListener: (event: string, listener: Listener) => { - if (event === 'before-quit') { - electron.beforeQuit.unshift(listener) - } - } - }, - powerMonitor: { - on: (event: string, listener: Listener) => { - electron.powerListeners[event] = listener - } - } -})) - -import { installServeNativeQuitGuard } from './serve-native-quit-guard' -import { quitProcess, resetProcessQuitRequestForTest } from './process-quit-request' - -function emitBeforeQuit(): { preventDefault: ReturnType } { - const event = { preventDefault: vi.fn() } - for (const listener of electron.beforeQuit) { - listener(event) - } - return event -} - -describe('installServeNativeQuitGuard', () => { - const closeDesktopWindows = vi.fn() - const isQuittingForUpdate = vi.fn(() => false) - - beforeEach(() => { - electron.beforeQuit.length = 0 - for (const key of Object.keys(electron.powerListeners)) { - delete electron.powerListeners[key] - } - electron.quit.mockReset() - closeDesktopWindows.mockReset() - isQuittingForUpdate.mockReturnValue(false) - resetProcessQuitRequestForTest() - }) - - it('turns a macOS Dock or app-switcher Quit into closing the desktop windows (#15537)', () => { - installServeNativeQuitGuard({ platform: 'darwin', isQuittingForUpdate, closeDesktopWindows }) - - const event = emitBeforeQuit() - - expect(event.preventDefault).toHaveBeenCalledOnce() - expect(closeDesktopWindows).toHaveBeenCalledOnce() - }) - - it('lets a signal, supervisor or relaunch quit through, and keeps it allowed on re-entry', () => { - installServeNativeQuitGuard({ platform: 'darwin', isQuittingForUpdate, closeDesktopWindows }) - - quitProcess() - expect(electron.quit).toHaveBeenCalledOnce() - expect(emitBeforeQuit().preventDefault).not.toHaveBeenCalled() - expect(emitBeforeQuit().preventDefault).not.toHaveBeenCalled() - expect(closeDesktopWindows).not.toHaveBeenCalled() - }) - - it('lets an update install quit through', () => { - isQuittingForUpdate.mockReturnValue(true) - installServeNativeQuitGuard({ platform: 'darwin', isQuittingForUpdate, closeDesktopWindows }) - - expect(emitBeforeQuit().preventDefault).not.toHaveBeenCalled() - }) - - it('does not cancel a macOS logout or shutdown', () => { - installServeNativeQuitGuard({ platform: 'darwin', isQuittingForUpdate, closeDesktopWindows }) - - electron.powerListeners.shutdown?.() - - expect(emitBeforeQuit().preventDefault).not.toHaveBeenCalled() - expect(closeDesktopWindows).not.toHaveBeenCalled() - }) - - it.each(['linux', 'win32'] as const)('installs nothing on %s', (platform) => { - installServeNativeQuitGuard({ platform, isQuittingForUpdate, closeDesktopWindows }) - - expect(electron.beforeQuit).toHaveLength(0) - expect(electron.powerListeners).toEqual({}) - }) -}) diff --git a/src/main/startup/serve-signal-handlers.test.ts b/src/main/startup/serve-signal-handlers.test.ts deleted file mode 100644 index 1ec9da580ad..00000000000 --- a/src/main/startup/serve-signal-handlers.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { EventEmitter } from 'node:events' -import { describe, expect, it, vi } from 'vitest' -import { registerServeSignalHandlers, type ServeSignalSource } from './serve-signal-handlers' - -function signalSourceFor(emitter: EventEmitter): ServeSignalSource { - return { - on: (event, listener) => emitter.on(event, listener), - removeListener: (event, listener) => emitter.removeListener(event, listener), - listeners: (event) => - emitter - .listeners(event) - .filter( - (listener): listener is (signal: NodeJS.Signals) => void => typeof listener === 'function' - ) - } -} - -describe('registerServeSignalHandlers', () => { - it('retries a vetoed quit on every delivered signal', () => { - const signalSource = new EventEmitter() - const quitApplication = vi.fn() - - registerServeSignalHandlers(signalSourceFor(signalSource), quitApplication) - signalSource.emit('SIGINT') - signalSource.emit('SIGINT') - signalSource.emit('SIGTERM') - signalSource.emit('SIGHUP') - - expect(quitApplication).toHaveBeenCalledTimes(4) - expect(signalSource.listenerCount('SIGINT')).toBe(1) - expect(signalSource.listenerCount('SIGTERM')).toBe(1) - expect(signalSource.listenerCount('SIGHUP')).toBe(1) - }) - - it('drops every earlier listener before re-adding it, so Node reinstalls its signal handler', () => { - const signalSource = new EventEmitter() - const earlier = vi.fn() - signalSource.on('SIGTERM', earlier) - const counts: number[] = [] - signalSource.on('removeListener', (event) => { - if (event === 'SIGTERM') { - counts.push(signalSource.listenerCount('SIGTERM')) - } - }) - const quitApplication = vi.fn() - - registerServeSignalHandlers(signalSourceFor(signalSource), quitApplication) - signalSource.emit('SIGTERM') - - // Node closes a signal's native handle only when its last listener is removed. - expect(counts).toEqual([0]) - expect(signalSource.listeners('SIGTERM')).toEqual([earlier, quitApplication]) - expect(earlier).toHaveBeenCalledOnce() - expect(quitApplication).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/startup/hydrate-shell-path.ts b/src/main/startup/shell-environment/hydrate-shell-path.ts similarity index 97% rename from src/main/startup/hydrate-shell-path.ts rename to src/main/startup/shell-environment/hydrate-shell-path.ts index 95f1e25ef1c..b155adca4a2 100644 --- a/src/main/startup/hydrate-shell-path.ts +++ b/src/main/startup/shell-environment/hydrate-shell-path.ts @@ -1,9 +1,9 @@ import type { ChildProcess } from 'node:child_process' import { delimiter, win32 as pathWin32 } from 'node:path' import { spawnProcess } from '@orca/process-host' -import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' -import type { ShellHydrationFailureReason } from '../../shared/shell/launch/shell-path-hydration-types' -import { resolveWindowsShellStartupFamily } from '../../shared/windows-terminal-shell' +import { stripAnsiEscapeSequences } from '../../../shared/ansi-escape-sequences' +import type { ShellHydrationFailureReason } from '../../../shared/shell/launch/shell-path-hydration-types' +import { resolveWindowsShellStartupFamily } from '../../../shared/windows-terminal-shell' import { SHELL_PATH_DELIMITER as DELIMITER, shellPathProbe } from './shell-path-probe' import { WindowsShellPathOwnership, createWindowsPathKey } from './windows-shell-path-ownership' import { bindShellProbeLifetime } from './shell-probe-lifetime' diff --git a/src/main/startup/hydrate-shell-path.windows.test.ts b/src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts similarity index 100% rename from src/main/startup/hydrate-shell-path.windows.test.ts rename to src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts diff --git a/src/main/startup/login-shell-environment-cache.test.ts b/src/main/startup/shell-environment/login-shell-environment-cache.test.ts similarity index 100% rename from src/main/startup/login-shell-environment-cache.test.ts rename to src/main/startup/shell-environment/login-shell-environment-cache.test.ts diff --git a/src/main/startup/login-shell-environment.test.ts b/src/main/startup/shell-environment/login-shell-environment.test.ts similarity index 84% rename from src/main/startup/login-shell-environment.test.ts rename to src/main/startup/shell-environment/login-shell-environment.test.ts index d94cbc4aa52..4afb3b9fbf5 100644 --- a/src/main/startup/login-shell-environment.test.ts +++ b/src/main/startup/shell-environment/login-shell-environment.test.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { resetLoginShellEnvironmentCacheForTests, resolveLoginShellEnvironment @@ -46,17 +46,6 @@ afterEach(async () => { }) describe('resolveLoginShellEnvironment', () => { - it('returns variables exported by the profile-loading shell', async () => { - const spawner = vi.fn(async () => ({ - ...process.env, - EXAMPLE_GATEWAY_TOKEN: 'shell-exported' - })) - - await expect( - resolveLoginShellEnvironment({ shellOverride: '/bin/zsh', spawner }) - ).resolves.toMatchObject({ EXAMPLE_GATEWAY_TOKEN: 'shell-exported' }) - }) - it.runIf(realShell !== null)( 'captures a profile export missing from the parent process', async () => { diff --git a/src/main/startup/login-shell-environment.ts b/src/main/startup/shell-environment/login-shell-environment.ts similarity index 99% rename from src/main/startup/login-shell-environment.ts rename to src/main/startup/shell-environment/login-shell-environment.ts index 70d21e43d67..6620ea5e687 100644 --- a/src/main/startup/login-shell-environment.ts +++ b/src/main/startup/shell-environment/login-shell-environment.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { win32 as pathWin32 } from 'node:path' import { spawnProcess } from '@orca/process-host' -import { resolveWindowsShellStartupFamily } from '../../shared/windows-terminal-shell' +import { resolveWindowsShellStartupFamily } from '../../../shared/windows-terminal-shell' import { resolveProfileLoadingFallbackShell, resolveProfileLoadingShell diff --git a/src/main/startup/shell-path-probe.ts b/src/main/startup/shell-environment/shell-path-probe.ts similarity index 95% rename from src/main/startup/shell-path-probe.ts rename to src/main/startup/shell-environment/shell-path-probe.ts index c52a90eed99..e88a9610e16 100644 --- a/src/main/startup/shell-path-probe.ts +++ b/src/main/startup/shell-environment/shell-path-probe.ts @@ -1,5 +1,5 @@ import { delimiter, win32 as pathWin32 } from 'node:path' -import { resolveWindowsShellStartupFamily } from '../../shared/windows-terminal-shell' +import { resolveWindowsShellStartupFamily } from '../../../shared/windows-terminal-shell' export const SHELL_PATH_DELIMITER = '__ORCA_SHELL_PATH__' diff --git a/src/main/startup/shell-probe-lifetime.live-shell.test.ts b/src/main/startup/shell-environment/shell-probe-lifetime.live-shell.test.ts similarity index 95% rename from src/main/startup/shell-probe-lifetime.live-shell.test.ts rename to src/main/startup/shell-environment/shell-probe-lifetime.live-shell.test.ts index e82eefecb7b..1ddb399110b 100644 --- a/src/main/startup/shell-probe-lifetime.live-shell.test.ts +++ b/src/main/startup/shell-environment/shell-probe-lifetime.live-shell.test.ts @@ -72,8 +72,8 @@ describe.skipIf(process.platform === 'win32')('a login shell probe left running' await build({ stdin: { contents: ` - import { captureLoginShellEnvironment } from ${JSON.stringify(resolve('src/main/startup/login-shell-environment.ts'))}; - import { hydrateShellPath } from ${JSON.stringify(resolve('src/main/startup/hydrate-shell-path.ts'))}; + import { captureLoginShellEnvironment } from ${JSON.stringify(resolve('src/main/startup/shell-environment/login-shell-environment.ts'))}; + import { hydrateShellPath } from ${JSON.stringify(resolve('src/main/startup/shell-environment/hydrate-shell-path.ts'))}; // As orcad and Electron do: INT/TERM end in an exit. process.on('SIGTERM', () => process.exit(143)); void ${call}; diff --git a/src/main/startup/shell-probe-lifetime.ts b/src/main/startup/shell-environment/shell-probe-lifetime.ts similarity index 100% rename from src/main/startup/shell-probe-lifetime.ts rename to src/main/startup/shell-environment/shell-probe-lifetime.ts diff --git a/src/main/startup/shell-probe-terminal-detach.live-shell.test.ts b/src/main/startup/shell-environment/shell-probe-terminal-detach.live-shell.test.ts similarity index 93% rename from src/main/startup/shell-probe-terminal-detach.live-shell.test.ts rename to src/main/startup/shell-environment/shell-probe-terminal-detach.live-shell.test.ts index 68052d45f3c..a4cfd4ad656 100644 --- a/src/main/startup/shell-probe-terminal-detach.live-shell.test.ts +++ b/src/main/startup/shell-environment/shell-probe-terminal-detach.live-shell.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import * as pty from 'node-pty' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { hasZsh, ZSH_PATH } from '../pty/shell-startup/zsh-startup-hook-pty-harness' +import { hasZsh, ZSH_PATH } from '../../pty/shell-startup/zsh-startup-hook-pty-harness' const DONE = 'ORCA-PROBE-PARENT-DONE' @@ -16,8 +16,8 @@ function fixtureSource(probe: 'login-environment' | 'path'): string { ? `captureLoginShellEnvironment({ shellOverride: ${JSON.stringify(ZSH_PATH)} })` : `hydrateShellPath({ shellOverride: ${JSON.stringify(ZSH_PATH)} })` return ` - import { captureLoginShellEnvironment } from ${JSON.stringify(resolve('src/main/startup/login-shell-environment.ts'))}; - import { hydrateShellPath } from ${JSON.stringify(resolve('src/main/startup/hydrate-shell-path.ts'))}; + import { captureLoginShellEnvironment } from ${JSON.stringify(resolve('src/main/startup/shell-environment/login-shell-environment.ts'))}; + import { hydrateShellPath } from ${JSON.stringify(resolve('src/main/startup/shell-environment/hydrate-shell-path.ts'))}; const probe = ${call}; setTimeout(() => { process.stdin.setRawMode(true); process.stdin.setRawMode(false); }, 300); probe.then(() => { console.log(${JSON.stringify(DONE)}); process.exit(0); }); diff --git a/src/main/startup/windows-desktop-shell-path-startup.ts b/src/main/startup/shell-environment/windows-desktop-shell-path-startup.ts similarity index 100% rename from src/main/startup/windows-desktop-shell-path-startup.ts rename to src/main/startup/shell-environment/windows-desktop-shell-path-startup.ts diff --git a/src/main/startup/windows-shell-path-hydration.ts b/src/main/startup/shell-environment/windows-shell-path-hydration.ts similarity index 93% rename from src/main/startup/windows-shell-path-hydration.ts rename to src/main/startup/shell-environment/windows-shell-path-hydration.ts index 609501bf1b2..85dc0c2dd90 100644 --- a/src/main/startup/windows-shell-path-hydration.ts +++ b/src/main/startup/shell-environment/windows-shell-path-hydration.ts @@ -1,11 +1,11 @@ import { win32 as pathWin32 } from 'node:path' -import { resolveWindowsGitBashShellPath } from '../pty/shell-startup/git-bash' +import { resolveWindowsGitBashShellPath } from '../../pty/shell-startup/git-bash' import { resolveEffectiveWindowsPowerShell, type WindowsPowerShellImplementation, type WindowsPowerShellShellFamily -} from '../providers/windows-powershell' -import { resolveWindowsPowerShellSpawnChain } from '../providers/windows-powershell-executable' +} from '../../providers/shell-launch/windows/powershell' +import { resolveWindowsPowerShellSpawnChain } from '../../providers/shell-launch/windows/powershell-executable' import { configureWindowsShellPathHydration, hydrateShellPath, diff --git a/src/main/startup/windows-shell-path-ownership.test.ts b/src/main/startup/shell-environment/windows-shell-path-ownership.test.ts similarity index 100% rename from src/main/startup/windows-shell-path-ownership.test.ts rename to src/main/startup/shell-environment/windows-shell-path-ownership.test.ts diff --git a/src/main/startup/windows-shell-path-ownership.ts b/src/main/startup/shell-environment/windows-shell-path-ownership.ts similarity index 100% rename from src/main/startup/windows-shell-path-ownership.ts rename to src/main/startup/shell-environment/windows-shell-path-ownership.ts diff --git a/src/main/startup/windows-shell-path-restoration.windows.test.ts b/src/main/startup/shell-environment/windows-shell-path-restoration.windows.test.ts similarity index 100% rename from src/main/startup/windows-shell-path-restoration.windows.test.ts rename to src/main/startup/shell-environment/windows-shell-path-restoration.windows.test.ts diff --git a/src/main/startup/single-instance-lock-exit.electron.test.ts b/src/main/startup/single-instance-lock-exit.electron.test.ts deleted file mode 100644 index 1c88a312fee..00000000000 --- a/src/main/startup/single-instance-lock-exit.electron.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, describe, expect, it } from 'vitest' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from './single-instance-lock' - -// Before-ready quit is deferred; execute shipped gate termination under real Electron. A live Linux lock race needs ready/display, so isolate loser exit semantics here; lock/argv tests cover ownership. - -const electronBinary = createRequire(import.meta.url)('electron') as string -const GATE_ENTERED = 'GATE_ENTERED' -const CONTINUED_INTO_STARTUP = 'CONTINUED_INTO_STARTUP' -const REACHED_TAIL = 'REACHED_TAIL' -const MARKER_ENV = 'ORCA_PRE_READY_EXIT_FIXTURE_MARKER' - -const fixtureRoots: string[] = [] - -afterAll(() => { - for (const root of fixtureRoots) { - rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) - } -}) - -function readPreReadyTermination(gate: string): string { - const source = readFileSync( - join(process.cwd(), 'src/main/startup/main-process-preflight.ts'), - 'utf8' - ) - const start = source.indexOf(gate) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf('\n }', start) - expect(end).toBeGreaterThan(start) - - return source - .slice(start, end) - .split('\n') - .map((line) => line.trim()) - .filter((line) => line.startsWith('app.')) - .join('\n') -} - -function buildFixtureMain(termination: string): string { - return [ - `const { app } = require('electron')`, - `const { appendFileSync } = require('node:fs')`, - // Use environment for markers because Chromium rewrites argv before main. - `const marker = process.env.${MARKER_ENV}`, - `const mark = (name) => appendFileSync(marker, name + '\\n')`, - `const SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE = ${SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE}`, - `mark('${GATE_ENTERED}')`, - termination, - `mark('${CONTINUED_INTO_STARTUP}')`, - // Model startup tail that must not run after a fatal pre-ready gate. - `mark('${REACHED_TAIL}')`, - `process.exit(0)` - ].join('\n') -} - -type FixtureRun = { status: number | null; markers: string[] } - -function runPreReadyGate(termination: string): FixtureRun { - const root = mkdtempSync(join(tmpdir(), 'orca-pre-ready-exit-')) - fixtureRoots.push(root) - const dir = join(root, 'fixture') - const marker = join(root, 'markers.log') - mkdirSync(dir, { recursive: true }) - writeFileSync( - join(dir, 'package.json'), - '{ "name": "orca-pre-ready-exit-fixture", "main": "main.js" }' - ) - writeFileSync(join(dir, 'main.js'), buildFixtureMain(termination)) - writeFileSync(marker, '') - - const result = spawnSync(electronBinary, [dir, '--no-sandbox'], { - stdio: 'ignore', - timeout: 60_000, - env: { ...process.env, [MARKER_ENV]: marker } - }) - expect(result.error).toBeUndefined() - - return { - status: result.status, - markers: readFileSync(marker, 'utf8').split('\n').filter(Boolean) - } -} - -describe('pre-ready termination under real Electron', () => { - it('stops the duplicate launch before any further startup runs, with the already-running code', () => { - const termination = readPreReadyTermination('if (!hasLock) {') - // Reject an empty source slice or the fixture's own exit passes vacuously. - expect(termination).not.toBe('') - - const run = runPreReadyGate(termination) - - expect(run.markers).toEqual([GATE_ENTERED]) - expect(run.status).toBe(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE) - }, 90_000) - - it('#17615 stops serve when display setup fails instead of entering Chromium startup', () => { - const termination = readPreReadyTermination( - 'if (state.isServeMode && !state.headlessBrowserDisplayAvailable) {' - ) - - const run = runPreReadyGate(termination) - - expect(run.markers).toEqual([GATE_ENTERED]) - expect(run.status).toBe(1) - }, 90_000) -}) diff --git a/src/main/startup/e2e-external-open-guard.ts b/src/main/startup/testing/e2e-external-open-guard.ts similarity index 100% rename from src/main/startup/e2e-external-open-guard.ts rename to src/main/startup/testing/e2e-external-open-guard.ts diff --git a/src/main/startup/e2e-spawn-log-env.test.ts b/src/main/startup/testing/e2e-spawn-log-env.test.ts similarity index 100% rename from src/main/startup/e2e-spawn-log-env.test.ts rename to src/main/startup/testing/e2e-spawn-log-env.test.ts diff --git a/src/main/startup/e2e-spawn-log-env.ts b/src/main/startup/testing/e2e-spawn-log-env.ts similarity index 100% rename from src/main/startup/e2e-spawn-log-env.ts rename to src/main/startup/testing/e2e-spawn-log-env.ts diff --git a/src/main/startup/windows-isolated-spawn-electron-fixture.ts b/src/main/startup/testing/windows-isolated-spawn-electron-fixture.ts similarity index 100% rename from src/main/startup/windows-isolated-spawn-electron-fixture.ts rename to src/main/startup/testing/windows-isolated-spawn-electron-fixture.ts diff --git a/src/main/startup/agent-hooks-uninstall-preflight.ts b/src/main/startup/uninstall/agent-hooks-uninstall-preflight.ts similarity index 84% rename from src/main/startup/agent-hooks-uninstall-preflight.ts rename to src/main/startup/uninstall/agent-hooks-uninstall-preflight.ts index 7d9ea337188..8ad2fe9a29f 100644 --- a/src/main/startup/agent-hooks-uninstall-preflight.ts +++ b/src/main/startup/uninstall/agent-hooks-uninstall-preflight.ts @@ -1,8 +1,8 @@ import { app } from 'electron' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { setAppEnvironment } from '../../shared/app-environment' -import { ElectronAppEnvironment } from '../host/electron-app-environment' -import { ensureWindowsAppDataPath } from './windows-app-data-path' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { setAppEnvironment } from '../../../shared/app-environment' +import { ElectronAppEnvironment } from '../../host/electron-app-environment' +import { ensureWindowsAppDataPath } from '../windows-startup/windows-app-data-path' /** The NSIS uninstaller's flag (config/nsis/orca-installer-hooks.nsh); keep the two in sync. */ export const AGENT_HOOKS_UNINSTALL_FLAG = '--orca-uninstall-remove-agent-hooks' @@ -55,7 +55,7 @@ export function runAgentHooksUninstallPreflight(argv: readonly string[] = proces // Loaded only here, so ordinary startup never pays for every agent's hook module. void removeAgentHooksForUninstall(async () => { const { removeManagedAgentHooks } = - await import('../agent-hooks/installation/managed-agent-hook-controls') + await import('../../agent-hooks/installation/managed-agent-hook-controls') return removeManagedAgentHooks() }).then((code) => { clearTimeout(timeout) diff --git a/src/main/startup/wsl-holder-uninstall-preflight.test.ts b/src/main/startup/uninstall/wsl-holder-uninstall-preflight.test.ts similarity index 77% rename from src/main/startup/wsl-holder-uninstall-preflight.test.ts rename to src/main/startup/uninstall/wsl-holder-uninstall-preflight.test.ts index f3ab7fe6f26..4e38e7f4359 100644 --- a/src/main/startup/wsl-holder-uninstall-preflight.test.ts +++ b/src/main/startup/uninstall/wsl-holder-uninstall-preflight.test.ts @@ -8,22 +8,21 @@ const { exit, stopServers, releaseAll } = vi.hoisted(() => ({ vi.mock('electron', () => ({ app: { exit, getPath: () => 'C:\\Users\\u\\AppData\\Roaming\\orca' } })) -vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: vi.fn() })) -vi.mock('../wsl/discovery/wsl-distro-holder', () => ({ +vi.mock('../windows-startup/windows-app-data-path', () => ({ ensureWindowsAppDataPath: vi.fn() })) +vi.mock('../../wsl/discovery/wsl-distro-holder', () => ({ createWslDistroHolder: () => ({ releaseAll }) })) -vi.mock('../wsl/host-lifecycle/wsl-host-uninstall-server-stop', () => ({ +vi.mock('../../wsl/host-lifecycle/wsl-host-uninstall-server-stop', () => ({ stopWslHostServersForUninstall: stopServers, wslHostUninstallStopDependencies: () => ({ distros: () => [], listRunning: async () => [] }) })) -import type { WslDistroHolder } from '../wsl/discovery/wsl-distro-holder-types' -import type { WslHostUninstallStopDependencies } from '../wsl/host-lifecycle/wsl-host-uninstall-server-stop' +import type { WslDistroHolder } from '../../wsl/discovery/wsl-distro-holder-types' +import type { WslHostUninstallStopDependencies } from '../../wsl/host-lifecycle/wsl-host-uninstall-server-stop' import { releaseWslHoldersForUninstall, runWslHolderUninstallPreflight, - WSL_HOLDER_UNINSTALL_FLAG, - WSL_SERVER_UNINSTALL_FLAG + WSL_HOLDER_UNINSTALL_FLAG } from './wsl-holder-uninstall-preflight' function holderReleasing(states: { distro: string; state: string }[]): WslDistroHolder { @@ -83,15 +82,4 @@ describe('runWslHolderUninstallPreflight', () => { expect(stopServers).not.toHaveBeenCalled() }) - - it('stops the servers when the uninstaller adds the server flag', async () => { - runWslHolderUninstallPreflight([ - 'Orca.exe', - WSL_HOLDER_UNINSTALL_FLAG, - WSL_SERVER_UNINSTALL_FLAG - ]) - await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0)) - - expect(stopServers).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/startup/wsl-holder-uninstall-preflight.ts b/src/main/startup/uninstall/wsl-holder-uninstall-preflight.ts similarity index 90% rename from src/main/startup/wsl-holder-uninstall-preflight.ts rename to src/main/startup/uninstall/wsl-holder-uninstall-preflight.ts index e924122d786..0d71ed1a983 100644 --- a/src/main/startup/wsl-holder-uninstall-preflight.ts +++ b/src/main/startup/uninstall/wsl-holder-uninstall-preflight.ts @@ -1,12 +1,12 @@ import { app } from 'electron' -import { createWslDistroHolder } from '../wsl/discovery/wsl-distro-holder' -import type { WslDistroHolder } from '../wsl/discovery/wsl-distro-holder-types' -import { ensureWindowsAppDataPath } from './windows-app-data-path' +import { createWslDistroHolder } from '../../wsl/discovery/wsl-distro-holder' +import type { WslDistroHolder } from '../../wsl/discovery/wsl-distro-holder-types' +import { ensureWindowsAppDataPath } from '../windows-startup/windows-app-data-path' import { stopWslHostServersForUninstall, wslHostUninstallStopDependencies, type WslHostUninstallStopDependencies -} from '../wsl/host-lifecycle/wsl-host-uninstall-server-stop' +} from '../../wsl/host-lifecycle/wsl-host-uninstall-server-stop' /** The NSIS uninstaller's flag (config/nsis/orca-installer-hooks.nsh); keep the two in sync. */ export const WSL_HOLDER_UNINSTALL_FLAG = '--orca-uninstall-release-wsl-holders' diff --git a/src/main/startup/windows-install-dir-acl-recovery.test.ts b/src/main/startup/windows-install-dir-acl-recovery.test.ts deleted file mode 100644 index 3cd0c8ce706..00000000000 --- a/src/main/startup/windows-install-dir-acl-recovery.test.ts +++ /dev/null @@ -1,870 +0,0 @@ -import { mkdtempSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { resetWindowsSecurityLoadForTests } from '../../shared/windows-security-addon' - -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { readActiveGpuFallbackMarker, writeGpuFallbackMarker } from './gpu-fallback-marker' -import { - probeWindowsInstallDirAcl, - resetWindowsInstallDirAclProbeForTest -} from './windows-install-dir-acl-probe' -import { - hasInstallDirAclPoisonMarker, - writeInstallDirAclPoisonMarker -} from './windows-install-dir-acl-poison-marker' -import { - describeInstallDirAclPoison, - isBlockingInstallDirAclRepairInFlight, - isInstallDirAclRepairExhausted, - isInstallDirAclSuspect, - noteWindowsInstallDirAclProbePending, - repairKnownPoisonedInstallDirBeforeWindow, - resetWindowsInstallDirAclRecoveryForTest, - startWindowsInstallDirAclRepairIfPoisoned, - type WindowsInstallDirAclRecoveryOptions -} from './windows-install-dir-acl-recovery' -import { - resetWindowsInstallDirAclRepairForTest, - WINDOWS_INSTALL_DIR_ACL_REPAIR_MARKER_FILE, - WINDOWS_INSTALL_DIR_ACL_REPAIR_SCHEME_VERSION -} from './windows-install-dir-package-acl-repair' -import type { InstallDirPackageGrantOutcome } from './windows-install-dir-package-acl-grant' -import { - ALL_PACKAGES_ACE, - grantsFrom, - installFakeDacls, - ORPHAN_PACKAGE_ACE, - RESTRICTED_PACKAGES_ACE, - type InstallDirPackageGrant, - type InstallDirPackageGrantPass -} from './windows-install-dir-acl.test-fixture' - -const INSTALL_DIR = 'C:\\Users\\neil\\AppData\\Local\\Programs\\orca' -const APP_VERSION = '1.4.184' - -type Runner = InstallDirPackageGrant - -const OK: InstallDirPackageGrantOutcome = { ok: true, failedFileCount: 0 } -const DENIED: InstallDirPackageGrantOutcome = { - ok: false, - failedFileCount: 1, - reason: 'Access is denied.' -} - -/** Keep probe-to-gate decisions real; fake only DACL reads and grants. */ -function probeThenRecover( - savedAces: (target: string) => string[], - options: { failRepair?: boolean } = {} -): Promise { - const specs: InstallDirPackageGrantPass[] = [] - const grantFn: Runner = async (_installDir, pass) => { - specs.push(pass) - return options.failRepair === true ? DENIED : OK - } - installFakeDacls(savedAces) - return new Promise((resolve) => { - probeWindowsInstallDirAcl({ - platform: 'win32', - installDir: INSTALL_DIR, - fileExists: (path) => path.endsWith('ffmpeg.dll'), - recordBreadcrumb: () => undefined, - onDone: (data) => { - startWindowsInstallDirAclRepairIfPoisoned(data, { - platform: 'win32', - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - userDataPath: mkdtempSync(join(tmpdir(), 'orca-acl-recovery-')), - grants: grantsFrom(grantFn), - recordBreadcrumb: () => undefined - }) - // Wait past the repair's deferred grant hop before asserting. - setTimeout(() => resolve(specs), 25) - } - }) - }) -} - -describe('startWindowsInstallDirAclRepairIfPoisoned', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - it('repairs when the probe sees an orphan package ACE and no well-known grant', async () => { - const specs = await probeThenRecover(() => [ORPHAN_PACKAGE_ACE]) - expect(specs).toEqual(['root', 'tree']) - }) - - // ALL APPLICATION PACKAGES launched clean with an orphan on Windows 10.0.26200/Electron 43.4.1; require no repair or accusation. - it('leaves an install whose package grant is ALL APPLICATION PACKAGES alone', async () => { - const specs = await probeThenRecover(() => [ORPHAN_PACKAGE_ACE, ALL_PACKAGES_ACE]) - expect(specs).toHaveLength(0) - expect(describeInstallDirAclPoison()).toBeNull() - }) - - it('does not touch an install that already carries the restricted grant', async () => { - const specs = await probeThenRecover(() => [ORPHAN_PACKAGE_ACE, RESTRICTED_PACKAGES_ACE]) - expect(specs).toHaveLength(0) - expect(describeInstallDirAclPoison()).toBeNull() - }) - - it('does not act when the probe could not read the DACL', async () => { - installFakeDacls(() => null) - const specs = await new Promise((resolve) => { - const collected: InstallDirPackageGrantPass[] = [] - probeWindowsInstallDirAcl({ - platform: 'win32', - installDir: INSTALL_DIR, - fileExists: () => false, - recordBreadcrumb: () => undefined, - onDone: (data) => { - startWindowsInstallDirAclRepairIfPoisoned(data, { - platform: 'win32', - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - userDataPath: mkdtempSync(join(tmpdir(), 'orca-acl-recovery-')), - grants: grantsFrom(async (_installDir, pass) => { - collected.push(pass) - throw new Error('unreachable') - }), - recordBreadcrumb: () => undefined - }) - setTimeout(() => resolve(collected), 25) - } - }) - }) - expect(specs).toHaveLength(0) - expect(describeInstallDirAclPoison()).toBeNull() - }) -}) - -describe('describeInstallDirAclPoison', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - it('walks a standard user through icacls when the repair could not write', async () => { - await probeThenRecover(() => [ORPHAN_PACKAGE_ACE], { - failRepair: true - }) - const failed = describeInstallDirAclPoison() - expect(failed?.detail).toContain('needs an administrator') - expect(failed?.detail).toContain(`icacls "${INSTALL_DIR}" /grant "*S-1-15-2-2:(RX)" /T /C`) - }) - - it('reports the repair as in flight before the grant has answered', () => { - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: true }, - { - platform: 'win32', - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - userDataPath: mkdtempSync(join(tmpdir(), 'orca-acl-recovery-')), - grants: grantsFrom(() => new Promise(() => undefined)), - recordBreadcrumb: () => undefined - } - ) - expect(describeInstallDirAclPoison()?.detail).toContain('repairing the permissions now') - }) -}) - -const POISON_VERDICT: CrashReportBreadcrumbData = { - status: 'ok', - matchesPoisonSignature: true -} -const GPU_ENV = { appVersion: APP_VERSION, electronVersion: '43.4.1', platform: 'win32' } as const - -function recoveryOptions(userDataPath: string, run: Runner): WindowsInstallDirAclRecoveryOptions { - return { - platform: 'win32', - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - userDataPath, - grants: grantsFrom(run), - recordBreadcrumb: () => undefined - } -} - -const okRun: Runner = async () => OK - -describe('install-dir ACL repair vs the GPU safe-graphics marker', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - it('clears the sticky safe-graphics marker once the real cause is repaired', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gpu-')) - // Model poisoned-DACL GPU deaths that engaged the build's safe-graphics latch. - writeGpuFallbackMarker( - userDataPath, - { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, - GPU_ENV - ) - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).not.toBeNull() - - await new Promise((resolve) => { - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, { - ...recoveryOptions(userDataPath, okRun), - // Wait for both deferred grant passes. - recordBreadcrumb: () => { - setTimeout(resolve, 0) - return undefined - } - }) - }) - - expect(describeInstallDirAclPoison()?.detail).toContain('repaired the permissions') - // Successful ACL repair must retire unconfirmed safe graphics, which hides future sibling-death evidence. - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).toBeNull() - }) - - // Preserve user-confirmed safe graphics; only Orca's automatic latch may be retired. - it('leaves a user-confirmed safe-graphics marker alone', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gpu-')) - writeGpuFallbackMarker( - userDataPath, - { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: true }, - GPU_ENV - ) - - await new Promise((resolve) => { - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, { - ...recoveryOptions(userDataPath, okRun), - recordBreadcrumb: () => { - setTimeout(resolve, 0) - return undefined - } - }) - }) - - expect(describeInstallDirAclPoison()?.detail).toContain('repaired the permissions') - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)?.userConfirmed).toBe(true) - }) -}) - -describe('isInstallDirAclSuspect', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - // GPU deaths can precede the probe by seconds; pending verdict is the misdiagnosis window. - it('holds while the probe verdict is outstanding, and releases on a clean verdict', () => { - noteWindowsInstallDirAclProbePending() - expect(isInstallDirAclSuspect()).toBe(true) - - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: false }, - recoveryOptions(mkdtempSync(join(tmpdir(), 'orca-acl-suspect-')), okRun) - ) - expect(isInstallDirAclSuspect()).toBe(false) - }) - - it('releases once the wait exceeds the grace window, so a silent probe cannot pin it', () => { - noteWindowsInstallDirAclProbePending() - expect(isInstallDirAclSuspect(Date.now() + 14_000)).toBe(true) - expect(isInstallDirAclSuspect(Date.now() + 16_000)).toBe(false) - }) - - it('holds through a repair that failed, and releases once one succeeds', async () => { - const failing: Runner = async () => DENIED - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-suspect-')) - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, failing) - ) - expect(isInstallDirAclSuspect()).toBe(true) - await vi.waitFor(() => expect(describeInstallDirAclPoison()?.detail).toContain('could not')) - expect(isInstallDirAclSuspect()).toBe(true) - - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(mkdtempSync(join(tmpdir(), 'orca-acl-suspect-')), okRun) - ) - await vi.waitFor(() => expect(isInstallDirAclSuspect()).toBe(false)) - }) -}) - -describe('repairKnownPoisonedInstallDirBeforeWindow', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - it('costs a healthy machine one absent-file read and no grant', async () => { - const specs: InstallDirPackageGrantPass[] = [] - const run: Runner = async (_installDir, pass) => { - specs.push(pass) - return OK - } - const mode = await repairKnownPoisonedInstallDirBeforeWindow( - recoveryOptions(mkdtempSync(join(tmpdir(), 'orca-acl-gate-')), run) - ) - expect(mode).toBe('not-marked') - expect(specs).toHaveLength(0) - }) - - // Persisted poison must repair before launch-two window creation; launch one's deferred probe was too late. - it('repairs a launch that a previous one recorded as poisoned, before returning', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-')) - // First launch dies after recording poison but before repair completes. - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - writeGpuFallbackMarker( - userDataPath, - { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, - GPU_ENV - ) - const specs: InstallDirPackageGrantPass[] = [] - const run: Runner = async (_installDir, pass) => { - specs.push(pass) - return OK - } - const mode = await repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, run)) - expect(mode).toBe('repaired') - expect(specs).toEqual(['root', 'tree']) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(false) - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).toBeNull() - }) - - it('gives up on its budget rather than holding the window open forever', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-')) - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - - const mode = await repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, () => new Promise(() => undefined)), - timeoutMs: 20 - }) - expect(mode).toBe('timeout') - }) - - it('is a no-op off win32 and in serve mode', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-')) - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - - expect( - await repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, okRun), - platform: 'darwin' - }) - ).toBe('skipped') - expect( - await repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, okRun), - isServeMode: true - }) - ).toBe('skipped') - }) - - it('retires the marker when a later probe reports the install clean', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-')) - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - - resetWindowsInstallDirAclRecoveryForTest() - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: false }, - recoveryOptions(userDataPath, okRun) - ) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(false) - }) - - // Unreadable DACL cannot retire poison evidence or the next launch repeats a known crash. - it('keeps the marker when the probe could not read the DACL', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-')) - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - resetWindowsInstallDirAclRecoveryForTest() - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'failed', reason: 'all-targets-unreadable' }, - recoveryOptions(userDataPath, okRun) - ) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - }) - - // A 20s gate can time out before its 120s grant. Later poison readings outrank that grant's success claim or it falsely disarms recovery and enables in-process GPU. - it('does not let a timed-out gate repair outrank a poison reading taken after it', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-timeout-')) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - writeGpuFallbackMarker( - userDataPath, - { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, - GPU_ENV - ) - - let releaseIcacls: () => void = () => undefined - const stalled = new Promise((resolve) => { - releaseIcacls = resolve - }) - let repairReported: () => void = () => undefined - const reported = new Promise((resolve) => { - repairReported = resolve - }) - - const mode = await repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, async () => { - await stalled - return OK - }), - recordBreadcrumb: () => { - setTimeout(repairReported, 0) - return undefined - }, - timeoutMs: 20 - }) - expect(mode).toBe('timeout') - - // Probe after window creation supplies newer poison evidence than the still-running grant. - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - - releaseIcacls() - await reported - - expect(isInstallDirAclSuspect()).toBe(true) - expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).not.toBeNull() - }) - - // Reverse ordering: a later poison reading must restore safe graphics already cleared by the grant's disproved success claim. - it('restores the safe-graphics marker when the probe disproves a timed-out gate repair', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-timeout-restore-')) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - writeGpuFallbackMarker( - userDataPath, - { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, - GPU_ENV - ) - - let releaseIcacls: () => void = () => undefined - const stalled = new Promise((resolve) => { - releaseIcacls = resolve - }) - let repairReported: () => void = () => undefined - const reported = new Promise((resolve) => { - repairReported = resolve - }) - - const mode = await repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, async () => { - await stalled - return OK - }), - recordBreadcrumb: () => { - setTimeout(repairReported, 0) - return undefined - }, - timeoutMs: 20 - }) - expect(mode).toBe('timeout') - - releaseIcacls() - await reported - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).toBeNull() - - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) - - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)?.userConfirmed).toBe(false) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - expect(isInstallDirAclSuspect()).toBe(true) - }) -}) - -// With outstanding poison evidence, a completed-repair marker proves no current health; marker-hit means spent budget only. -describe('a repair marker recording a completed repair', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - /** Reset process latches between launches while retaining persisted evidence. */ - async function gateLaunch( - userDataPath: string, - run: Runner - ): Promise>> { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - return repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, run)) - } - - // Three-launch regression: old successful repair, re-poisoning/crash mid-repair, then poison plus stale-success markers. The third gate must grant again within budget. - it('re-runs the grant when a poison marker outlives it', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-repaired-hit-')) - - // First launch repairs and retires poison. - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - expect(await gateLaunch(userDataPath, okRun)).toBe('repaired') - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(false) - - // Second launch dies mid-repair after recording new poison; the old success marker remains. - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - - // Third launch must repair rather than trust first-launch success. - const spent: InstallDirPackageGrantPass[] = [] - const mode = await gateLaunch(userDataPath, async (_installDir, pass) => { - spent.push(pass) - return DENIED - }) - expect(mode).toBe('failed') - expect(spent).toEqual(['root', 'tree']) - expect(isInstallDirAclSuspect()).toBe(true) - expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - }) - - // Spent budget must report unrepaired, without falsely clearing poison. - it('does not let the gate report a spent budget as a repair', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-budget-')) - writeFileSync( - join(userDataPath, WINDOWS_INSTALL_DIR_ACL_REPAIR_MARKER_FILE), - JSON.stringify({ - schemeVersion: WINDOWS_INSTALL_DIR_ACL_REPAIR_SCHEME_VERSION, - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - attemptedAt: Date.now(), - outcome: 'repaired', - attempts: 3 - }) - ) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - const spent: InstallDirPackageGrantPass[] = [] - const mode = await gateLaunch(userDataPath, async (_installDir, pass) => { - spent.push(pass) - return OK - }) - expect(mode).toBe('marker-hit') - expect(spent).toHaveLength(0) - expect(isInstallDirAclSuspect()).toBe(true) - expect(isInstallDirAclRepairExhausted()).toBe(true) - expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - }) - - // A later probe reading outranks gate success if the tree still matches poison. - it('is overruled by a probe that reads the tree poisoned after the gate repaired it', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-noop-grant-')) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - expect( - await repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, okRun)) - ).toBe('repaired') - - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) - - expect(isInstallDirAclSuspect()).toBe(true) - expect(isInstallDirAclRepairExhausted()).toBe(false) - expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - }) - - // Gate success is provisional until probe/grace expiry: child deaths can precede the probe, and early in-process GPU would hide evidence. - it('keeps a gate-repaired tree suspect until this launch probe has read it', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-provisional-')) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - expect( - await repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, okRun)) - ).toBe('repaired') - - // Model window creation dispatching a still-pending probe. - noteWindowsInstallDirAclProbePending() - expect(isInstallDirAclSuspect()).toBe(true) - // Probe timeout bounds suspicion when no reading arrives. - expect(isInstallDirAclSuspect(Date.now() + 15_000)).toBe(false) - - // A clean reading corroborates repair and releases immediately. - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: false }, - recoveryOptions(userDataPath, okRun) - ) - expect(isInstallDirAclSuspect()).toBe(false) - }) - - // Disproved repair must restore cleared safe graphics or hardware relaunch can abort before the re-armed gate repairs. - it('restores the safe-graphics marker a disproved repair claim cleared', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gpu-restore-')) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - writeGpuFallbackMarker( - userDataPath, - { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, - GPU_ENV - ) - expect( - await repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, okRun)) - ).toBe('repaired') - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).toBeNull() - - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) - - expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)?.userConfirmed).toBe(false) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - }) - - // Fresh poison evidence contradicts prior success; rerun within budget rather than disarm the gate or claim repaired permissions. - it('re-runs the grant when a fresh probe verdict contradicts the repaired marker', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-repoisoned-')) - writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) - expect( - await repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, okRun)) - ).toBe('repaired') - - // Next launch re-probes poison after the old repair disarmed the gate. - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - const spent: InstallDirPackageGrantPass[] = [] - const failing: Runner = async (_installDir, pass) => { - spent.push(pass) - return DENIED - } - await new Promise((resolve) => { - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, { - ...recoveryOptions(userDataPath, failing), - recordBreadcrumb: () => { - setTimeout(resolve, 0) - return undefined - } - }) - }) - - expect(spent).toEqual(['root', 'tree']) - expect(isInstallDirAclSuspect()).toBe(true) - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') - }) - - // New poison evidence cannot remove the attempt cap or every launch would re-walk permanently broken trees. - it('still stops at the attempt budget when the probe keeps reporting poison', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-repoisoned-budget-')) - writeFileSync( - join(userDataPath, WINDOWS_INSTALL_DIR_ACL_REPAIR_MARKER_FILE), - JSON.stringify({ - schemeVersion: WINDOWS_INSTALL_DIR_ACL_REPAIR_SCHEME_VERSION, - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - attemptedAt: Date.now(), - outcome: 'repaired', - attempts: 3 - }) - ) - const spent: InstallDirPackageGrantPass[] = [] - const run: Runner = async (_installDir, pass) => { - spent.push(pass) - return OK - } - await new Promise((resolve) => { - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, { - ...recoveryOptions(userDataPath, run), - recordBreadcrumb: () => { - setTimeout(resolve, 0) - return undefined - } - }) - }) - - expect(spent).toHaveLength(0) - // Unrepaired trees retain commands and next-launch gating. - expect(isInstallDirAclSuspect()).toBe(true) - expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') - expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) - }) -}) - -describe('a clean probe verdict', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - // A clean probe retires suspicion even after the gate exhausted its repair budget. - it('retires a verdict the gate could no longer act on', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-clean-')) - writeFileSync( - join(userDataPath, WINDOWS_INSTALL_DIR_ACL_REPAIR_MARKER_FILE), - JSON.stringify({ - schemeVersion: WINDOWS_INSTALL_DIR_ACL_REPAIR_SCHEME_VERSION, - installDir: INSTALL_DIR, - appVersion: APP_VERSION, - attemptedAt: Date.now(), - outcome: 'failed', - attempts: 3 - }) - ) - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - expect( - await repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, okRun)) - ).toBe('marker-hit') - expect(isInstallDirAclSuspect()).toBe(true) - - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: false }, - recoveryOptions(userDataPath, okRun) - ) - expect(isInstallDirAclSuspect()).toBe(false) - expect(describeInstallDirAclPoison()).toBeNull() - }) - - // A clean reading outranks a later failed repair result about a tree with nothing left to fix. - it('outranks a repair verdict that lands after it', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-clean-')) - const failing: Runner = async () => DENIED - let repairSettled = false - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, { - ...recoveryOptions(userDataPath, failing), - recordBreadcrumb: () => { - repairSettled = true - return undefined - } - }) - startWindowsInstallDirAclRepairIfPoisoned( - { status: 'ok', matchesPoisonSignature: false }, - recoveryOptions(userDataPath, okRun) - ) - await vi.waitFor(() => expect(repairSettled).toBe(true)) - expect(isInstallDirAclSuspect()).toBe(false) - expect(describeInstallDirAclPoison()).toBeNull() - }) -}) - -describe('the probe-pending grace window', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - // Reopen must not re-arm the once-per-process probe wait and suppress real GPU recovery for another 15s. - it('is armed by a dispatched probe only, so a reopen cannot re-arm it', async () => { - installFakeDacls(() => [RESTRICTED_PACKAGES_ACE]) - const probeArgs = { - platform: 'win32' as const, - installDir: INSTALL_DIR, - fileExists: () => false, - recordBreadcrumb: () => undefined - } - let settleVerdict: () => void = () => undefined - const verdict = new Promise((resolve) => (settleVerdict = resolve)) - // Use the same dispatch-gated arming as window startup. - const dispatched = probeWindowsInstallDirAcl({ - ...probeArgs, - onDone: (data) => { - startWindowsInstallDirAclRepairIfPoisoned( - data, - recoveryOptions(mkdtempSync(join(tmpdir(), 'orca-acl-rearm-')), okRun) - ) - settleVerdict() - } - }) - if (dispatched) { - noteWindowsInstallDirAclProbePending() - } - expect(dispatched).toBe(true) - expect(isInstallDirAclSuspect()).toBe(true) - await verdict - expect(isInstallDirAclSuspect()).toBe(false) - - // Reopen: the probe declines, so nothing arms the grace window again. - const reopened = probeWindowsInstallDirAcl({ ...probeArgs, onDone: () => undefined }) - if (reopened) { - noteWindowsInstallDirAclProbePending() - } - expect(reopened).toBe(false) - expect(isInstallDirAclSuspect()).toBe(false) - expect(isInstallDirAclSuspect(Date.now() + 14_000)).toBe(false) - }) -}) - -describe('isBlockingInstallDirAclRepairInFlight', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - resetWindowsInstallDirAclRepairForTest() - resetWindowsInstallDirAclRecoveryForTest() - }) - - it('is false on a healthy machine and clears once the gate returns', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-inflight-')) - expect(isBlockingInstallDirAclRepairInFlight()).toBe(false) - - startWindowsInstallDirAclRepairIfPoisoned( - POISON_VERDICT, - recoveryOptions(userDataPath, () => new Promise(() => undefined)) - ) - resetWindowsInstallDirAclRecoveryForTest() - resetWindowsInstallDirAclRepairForTest() - - let inFlightDuringRepair = false - const gate = repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, async () => { - inFlightDuringRepair = isBlockingInstallDirAclRepairInFlight() - return OK - }), - timeoutMs: 5_000 - }) - expect(await gate).toBe('repaired') - expect(inFlightDuringRepair).toBe(true) - expect(isBlockingInstallDirAclRepairInFlight()).toBe(false) - }) - - // A second entry has no `onDone` coming, so waiting out the 20s budget for it - // would hold the window closed for nothing. - it('returns immediately when the once-per-process repair already ran', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-inflight-')) - startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) - resetWindowsInstallDirAclRecoveryForTest() - - const mode = await repairKnownPoisonedInstallDirBeforeWindow({ - ...recoveryOptions(userDataPath, okRun), - timeoutMs: 30_000 - }) - expect(mode).toBe('skipped') - expect(isBlockingInstallDirAclRepairInFlight()).toBe(false) - }) -}) - -afterEach(() => { - resetWindowsSecurityLoadForTests() -}) diff --git a/src/main/startup/windows-install-dir-package-acl-grant.test.ts b/src/main/startup/windows-install-dir-package-acl-grant.test.ts deleted file mode 100644 index aaca43a9c24..00000000000 --- a/src/main/startup/windows-install-dir-package-acl-grant.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - resetWindowsSecurityLoadForTests, - setWindowsSecurityForTests, - type GrantAccessOptions, - type WindowsSecurityAddon -} from '../../shared/windows-security-addon' - -import { grantInstallDirPackageTree } from './windows-install-dir-package-acl-grant' - -type GrantCall = { - path: string - sid: string - accessMask: number - options: GrantAccessOptions -} - -function unexpected(): never { - throw new Error('the package grant must only read DACLs and call grantAccessAsync') -} - -/** Normalize addon namespaced paths for comparison with fixture paths. */ -const plain = (path: string) => (path.startsWith('\\\\?\\') ? path.slice(4) : path) - -/** Fake grants/DACL reads; only protectedDirs refuse inheritance. */ -function installFakeAddon( - fail: (path: string) => boolean = () => false, - protectedDirs: string[] = [] -): GrantCall[] { - const calls: GrantCall[] = [] - const addon: WindowsSecurityAddon = { - currentUserSid: () => 'S-1-5-21-1-2-3-1001', - getDaclAces: (path) => ({ protected: protectedDirs.includes(plain(path)), aces: [] }), - setDaclSddl: unexpected, - setDaclSddlAsync: unexpected, - createFileWithDacl: unexpected, - readFileWithDacl: unexpected, - readGenericCredential: unexpected, - writeGenericCredential: unexpected, - grantAccess: unexpected, - clearStdHandleInheritance: unexpected, - spawnDetachedIsolated: unexpected, - isolatedSpawnBreaksAwayFromJob: unexpected, - hasNativeExport: unexpected, - grantAccessAsync: async (path, sid, accessMask, options) => { - calls.push({ path: plain(path), sid, accessMask, options }) - if (fail(plain(path))) { - throw new Error('SetNamedSecurityInfoW failed with Win32 error 5') - } - } - } - setWindowsSecurityForTests(addon) - return calls -} - -describe('install-dir package grant passes', () => { - let installDir: string - - beforeEach(() => { - installDir = mkdtempSync(join(tmpdir(), 'orca-acl-grant-')) - mkdirSync(join(installDir, 'resources', 'app.asar.unpacked'), { recursive: true }) - writeFileSync(join(installDir, 'ffmpeg.dll'), 'binary') - writeFileSync(join(installDir, 'resources', 'app.asar.unpacked', 'addon.node'), 'binary') - }) - - afterEach(() => { - resetWindowsSecurityLoadForTests() - rmSync(installDir, { recursive: true, force: true }) - }) - - it('does not follow a link out of the install tree', async (context) => { - const outside = mkdtempSync(join(tmpdir(), 'orca-acl-grant-outside-')) - writeFileSync(join(outside, 'elsewhere.dll'), 'binary') - try { - symlinkSync(outside, join(installDir, 'linked'), 'junction') - } catch { - rmSync(outside, { recursive: true, force: true }) - context.skip() - return - } - try { - const calls = installFakeAddon() - await grantInstallDirPackageTree(installDir) - const paths = calls.map((call) => call.path) - expect(paths).not.toContain(join(installDir, 'linked')) - expect(paths.some((path) => path.includes('elsewhere.dll'))).toBe(false) - } finally { - rmSync(join(installDir, 'linked'), { force: true }) - rmSync(outside, { recursive: true, force: true }) - } - }) - - it('keeps going past failed entries and counts them, like icacls /T /C', async () => { - const calls = installFakeAddon((path) => path.endsWith('.dll') || path.endsWith('.node')) - const outcome = await grantInstallDirPackageTree(installDir) - expect(calls).toHaveLength(2) - expect(outcome.ok).toBe(false) - expect(outcome.failedFileCount).toBe(2) - expect(outcome.reason).toMatch(/^failed-files: .*Win32 error 5/) - }) -}) diff --git a/src/main/startup/windows-install-dir-acl-poison-marker.ts b/src/main/startup/windows-install-permissions/windows-install-dir-acl-poison-marker.ts similarity index 100% rename from src/main/startup/windows-install-dir-acl-poison-marker.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-acl-poison-marker.ts diff --git a/src/main/startup/windows-install-dir-acl-probe.ts b/src/main/startup/windows-install-permissions/windows-install-dir-acl-probe.ts similarity index 93% rename from src/main/startup/windows-install-dir-acl-probe.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-acl-probe.ts index bf1ea6b91de..debdabdf867 100644 --- a/src/main/startup/windows-install-dir-acl-probe.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-acl-probe.ts @@ -1,16 +1,15 @@ import { existsSync } from 'node:fs' import { dirname, join } from 'node:path' -import { - sanitizeCrashReportString, - type CrashReportBreadcrumbData -} from '../../shared/crash-reporting' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { loadWindowsSecurity, type WindowsDacl } from '../../shared/windows-security-addon' +import { sanitizeCrashReportString } from '../../../shared/crash-report-redaction' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { loadWindowsSecurity } from '../../../shared/windows-security-addon' +import type { WindowsDacl } from '@orca/windows-security' import { ACCESS_ALLOWED_ACE_TYPE, ACCESS_DENIED_ACE_TYPE, INHERIT_ONLY_ACE -} from '../../shared/windows-secure-dacl' +} from '../../../shared/windows-secure-dacl' import { RESTRICTED_APP_PACKAGES_SID } from './windows-install-dir-package-acl-grant' /** Read-only evidence for electron/electron#51761: orphan package ACEs without either well-known package grant reproduced child-init 0x80000003. Either grant launched clean on Windows 10.0.26200/Electron 43.4.1; report restricted-grant presence separately. */ diff --git a/src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.test.ts b/src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.test.ts new file mode 100644 index 00000000000..6342e219380 --- /dev/null +++ b/src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.test.ts @@ -0,0 +1,201 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { resetWindowsSecurityLoadForTests } from '../../../shared/windows-security-addon' + +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' +import { + readActiveGpuFallbackMarker, + writeGpuFallbackMarker +} from '../gpu-recovery/gpu-fallback-marker' +import { resetWindowsInstallDirAclProbeForTest } from './windows-install-dir-acl-probe' +import { + hasInstallDirAclPoisonMarker, + writeInstallDirAclPoisonMarker +} from './windows-install-dir-acl-poison-marker' +import { + describeInstallDirAclPoison, + isInstallDirAclSuspect, + repairKnownPoisonedInstallDirBeforeWindow, + resetWindowsInstallDirAclRecoveryForTest, + startWindowsInstallDirAclRepairIfPoisoned, + type WindowsInstallDirAclRecoveryOptions +} from './windows-install-dir-acl-recovery' +import { resetWindowsInstallDirAclRepairForTest } from './windows-install-dir-package-acl-repair' +import type { InstallDirPackageGrantOutcome } from './windows-install-dir-package-acl-grant' +import { + grantsFrom, + type InstallDirPackageGrant, + type InstallDirPackageGrantPass +} from './windows-install-dir-acl.test-fixture' + +const INSTALL_DIR = 'C:\\Users\\neil\\AppData\\Local\\Programs\\orca' +const APP_VERSION = '1.4.184' + +type Runner = InstallDirPackageGrant + +const OK: InstallDirPackageGrantOutcome = { ok: true, failedFileCount: 0 } +const DENIED: InstallDirPackageGrantOutcome = { + ok: false, + failedFileCount: 1, + reason: 'Access is denied.' +} + +const POISON_VERDICT: CrashReportBreadcrumbData = { + status: 'ok', + matchesPoisonSignature: true +} +const GPU_ENV = { appVersion: APP_VERSION, electronVersion: '43.4.1', platform: 'win32' } as const + +function recoveryOptions(userDataPath: string, run: Runner): WindowsInstallDirAclRecoveryOptions { + return { + platform: 'win32', + installDir: INSTALL_DIR, + appVersion: APP_VERSION, + userDataPath, + grants: grantsFrom(run), + recordBreadcrumb: () => undefined + } +} + +const okRun: Runner = async () => OK + +describe('install-dir ACL recovery evidence ordering', () => { + beforeEach(() => { + resetWindowsInstallDirAclProbeForTest() + resetWindowsInstallDirAclRepairForTest() + resetWindowsInstallDirAclRecoveryForTest() + }) + + /** Reset process latches between launches while retaining persisted evidence. */ + async function gateLaunch( + userDataPath: string, + run: Runner + ): Promise>> { + resetWindowsInstallDirAclProbeForTest() + resetWindowsInstallDirAclRepairForTest() + resetWindowsInstallDirAclRecoveryForTest() + return repairKnownPoisonedInstallDirBeforeWindow(recoveryOptions(userDataPath, run)) + } + + it('does not let a timed-out gate repair outrank a poison reading taken after it', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-timeout-')) + writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) + writeGpuFallbackMarker( + userDataPath, + { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, + GPU_ENV + ) + + let releaseIcacls: () => void = () => undefined + const stalled = new Promise((resolve) => { + releaseIcacls = resolve + }) + let repairReported: () => void = () => undefined + const reported = new Promise((resolve) => { + repairReported = resolve + }) + + const mode = await repairKnownPoisonedInstallDirBeforeWindow({ + ...recoveryOptions(userDataPath, async () => { + await stalled + return OK + }), + recordBreadcrumb: () => { + setTimeout(repairReported, 0) + return undefined + }, + timeoutMs: 20 + }) + expect(mode).toBe('timeout') + + // Probe after window creation supplies newer poison evidence than the still-running grant. + startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) + expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) + + releaseIcacls() + await reported + + expect(isInstallDirAclSuspect()).toBe(true) + expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') + expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) + expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).not.toBeNull() + }) + + it('restores the safe-graphics marker when the probe disproves a timed-out gate repair', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-gate-timeout-restore-')) + writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) + writeGpuFallbackMarker( + userDataPath, + { engagedAt: Date.now(), crashesInWindow: 3, userConfirmed: false }, + GPU_ENV + ) + + let releaseIcacls: () => void = () => undefined + const stalled = new Promise((resolve) => { + releaseIcacls = resolve + }) + let repairReported: () => void = () => undefined + const reported = new Promise((resolve) => { + repairReported = resolve + }) + + const mode = await repairKnownPoisonedInstallDirBeforeWindow({ + ...recoveryOptions(userDataPath, async () => { + await stalled + return OK + }), + recordBreadcrumb: () => { + setTimeout(repairReported, 0) + return undefined + }, + timeoutMs: 20 + }) + expect(mode).toBe('timeout') + + releaseIcacls() + await reported + expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)).toBeNull() + + startWindowsInstallDirAclRepairIfPoisoned(POISON_VERDICT, recoveryOptions(userDataPath, okRun)) + + expect(readActiveGpuFallbackMarker(userDataPath, GPU_ENV)?.userConfirmed).toBe(false) + expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) + expect(isInstallDirAclSuspect()).toBe(true) + }) + + it('re-runs the grant when a poison marker outlives it', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-acl-repaired-hit-')) + + // First launch repairs and retires poison. + writeInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION) + expect(await gateLaunch(userDataPath, okRun)).toBe('repaired') + expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(false) + + // Second launch dies mid-repair after recording new poison; the old success marker remains. + resetWindowsInstallDirAclRecoveryForTest() + resetWindowsInstallDirAclRepairForTest() + startWindowsInstallDirAclRepairIfPoisoned( + POISON_VERDICT, + recoveryOptions(userDataPath, () => new Promise(() => undefined)) + ) + expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) + + // Third launch must repair rather than trust first-launch success. + const spent: InstallDirPackageGrantPass[] = [] + const mode = await gateLaunch(userDataPath, async (_installDir, pass) => { + spent.push(pass) + return DENIED + }) + expect(mode).toBe('failed') + expect(spent).toEqual(['root', 'tree']) + expect(isInstallDirAclSuspect()).toBe(true) + expect(describeInstallDirAclPoison()?.detail).toContain('could not repair them') + expect(hasInstallDirAclPoisonMarker(userDataPath, INSTALL_DIR, APP_VERSION)).toBe(true) + }) +}) + +afterEach(() => { + resetWindowsSecurityLoadForTests() +}) diff --git a/src/main/startup/windows-install-dir-acl-recovery.ts b/src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.ts similarity index 97% rename from src/main/startup/windows-install-dir-acl-recovery.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.ts index 5c25087ac77..13a334aaa1a 100644 --- a/src/main/startup/windows-install-dir-acl-recovery.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-acl-recovery.ts @@ -1,13 +1,14 @@ +// @protected-copy import { dirname } from 'node:path' -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { translateMain } from '../i18n/main-i18n' -import { logStartupMilestone } from './startup-diagnostics' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' +import { translateMain } from '../../i18n/main-i18n' +import { logStartupMilestone } from '../diagnostics/startup-diagnostics' import { clearGpuFallbackMarker, readGpuFallbackMarker, writeGpuFallbackMarker, type GpuFallbackMarker -} from './gpu-fallback-marker' +} from '../gpu-recovery/gpu-fallback-marker' import { clearInstallDirAclPoisonMarker, hasInstallDirAclPoisonMarker, diff --git a/src/main/startup/windows-install-dir-acl-repair.win32.test.ts b/src/main/startup/windows-install-permissions/windows-install-dir-acl-repair.win32.test.ts similarity index 96% rename from src/main/startup/windows-install-dir-acl-repair.win32.test.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-acl-repair.win32.test.ts index 1e4a572a42a..3e1cc65c824 100644 --- a/src/main/startup/windows-install-dir-acl-repair.win32.test.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-acl-repair.win32.test.ts @@ -2,13 +2,13 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' import { loadWindowsSecurity, WINDOWS_FILE_READ_EXECUTE, type WindowsSecurity -} from '../../shared/windows-security-addon' +} from '../../../shared/windows-security-addon' import { probeWindowsInstallDirAcl, resetWindowsInstallDirAclProbeForTest diff --git a/src/main/startup/windows-install-dir-acl.test-fixture.ts b/src/main/startup/windows-install-permissions/windows-install-dir-acl.test-fixture.ts similarity index 94% rename from src/main/startup/windows-install-dir-acl.test-fixture.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-acl.test-fixture.ts index c49e22868ad..0de350387c4 100644 --- a/src/main/startup/windows-install-dir-acl.test-fixture.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-acl.test-fixture.ts @@ -1,8 +1,8 @@ -import { setWindowsSecurityForTests } from '../../shared/windows-security-addon' +import { setWindowsSecurityForTests } from '../../../shared/windows-security-addon' import { createFakeWindowsSecurity, daclFromSddl -} from '../../shared/windows-security-addon.test-fixture' +} from '../../../shared/windows-security-addon.test-fixture' import type { InstallDirPackageGrantOutcome, InstallDirPackageGrants diff --git a/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.test.ts b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.test.ts new file mode 100644 index 00000000000..eb3d4d96ee4 --- /dev/null +++ b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.test.ts @@ -0,0 +1,82 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + resetWindowsSecurityLoadForTests, + setWindowsSecurityForTests, + type GrantAccessOptions, + type WindowsSecurityAddon +} from '../../../shared/windows-security-addon' + +import { grantInstallDirPackageTree } from './windows-install-dir-package-acl-grant' + +type GrantCall = { + path: string + sid: string + accessMask: number + options: GrantAccessOptions +} + +function unexpected(): never { + throw new Error('the package grant must only read DACLs and call grantAccessAsync') +} + +/** Normalize addon namespaced paths for comparison with fixture paths. */ +const plain = (path: string) => (path.startsWith('\\\\?\\') ? path.slice(4) : path) + +/** Fake grants/DACL reads; only protectedDirs refuse inheritance. */ +function installFakeAddon( + fail: (path: string) => boolean = () => false, + protectedDirs: string[] = [] +): GrantCall[] { + const calls: GrantCall[] = [] + const addon: WindowsSecurityAddon = { + currentUserSid: () => 'S-1-5-21-1-2-3-1001', + getDaclAces: (path) => ({ protected: protectedDirs.includes(plain(path)), aces: [] }), + setDaclSddl: unexpected, + setDaclSddlAsync: unexpected, + createFileWithDacl: unexpected, + readFileWithDacl: unexpected, + readGenericCredential: unexpected, + writeGenericCredential: unexpected, + grantAccess: unexpected, + clearStdHandleInheritance: unexpected, + spawnDetachedIsolated: unexpected, + isolatedSpawnBreaksAwayFromJob: unexpected, + hasNativeExport: unexpected, + grantAccessAsync: async (path, sid, accessMask, options) => { + calls.push({ path: plain(path), sid, accessMask, options }) + if (fail(plain(path))) { + throw new Error('SetNamedSecurityInfoW failed with Win32 error 5') + } + } + } + setWindowsSecurityForTests(addon) + return calls +} + +describe('install-dir package grant passes', () => { + let installDir: string + + beforeEach(() => { + installDir = mkdtempSync(join(tmpdir(), 'orca-acl-grant-')) + mkdirSync(join(installDir, 'resources', 'app.asar.unpacked'), { recursive: true }) + writeFileSync(join(installDir, 'ffmpeg.dll'), 'binary') + writeFileSync(join(installDir, 'resources', 'app.asar.unpacked', 'addon.node'), 'binary') + }) + + afterEach(() => { + resetWindowsSecurityLoadForTests() + rmSync(installDir, { recursive: true, force: true }) + }) + + it('keeps going past failed entries and counts them, like icacls /T /C', async () => { + const calls = installFakeAddon((path) => path.endsWith('.dll') || path.endsWith('.node')) + const outcome = await grantInstallDirPackageTree(installDir) + expect(calls).toHaveLength(2) + expect(outcome.ok).toBe(false) + expect(outcome.failedFileCount).toBe(2) + expect(outcome.reason).toMatch(/^failed-files: .*Win32 error 5/) + }) +}) diff --git a/src/main/startup/windows-install-dir-package-acl-grant.ts b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.ts similarity index 96% rename from src/main/startup/windows-install-dir-package-acl-grant.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.ts index b5937ba7f44..03ece70478a 100644 --- a/src/main/startup/windows-install-dir-package-acl-grant.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-grant.ts @@ -1,11 +1,11 @@ import { readdirSync, type Dirent } from 'node:fs' import { join } from 'node:path' -import { sanitizeCrashReportString } from '../../shared/crash-reporting' +import { sanitizeCrashReportString } from '../../../shared/crash-report-redaction' import { loadWindowsSecurity, WINDOWS_FILE_READ_EXECUTE, type WindowsSecurity -} from '../../shared/windows-security-addon' +} from '../../../shared/windows-security-addon' /** ALL RESTRICTED APPLICATION PACKAGES: the grant that cleared electron/electron#51761. */ export const RESTRICTED_APP_PACKAGES_SID = 'S-1-15-2-2' diff --git a/src/main/startup/windows-install-dir-package-acl-repair.test.ts b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.test.ts similarity index 86% rename from src/main/startup/windows-install-dir-package-acl-repair.test.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.test.ts index 02db09af01b..5a781ede083 100644 --- a/src/main/startup/windows-install-dir-package-acl-repair.test.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -15,13 +15,11 @@ vi.mock('@orca/process-host', () => ({ runProcessSync: runProcessSyncMock })) -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' import { repairWindowsInstallDirPackageAcl, resetWindowsInstallDirAclRepairForTest, WINDOWS_INSTALL_DIR_ACL_REPAIR_BREADCRUMB, - WINDOWS_INSTALL_DIR_ACL_REPAIR_MARKER_FILE, - WINDOWS_INSTALL_DIR_ACL_REPAIR_SCHEME_VERSION, type WindowsInstallDirAclRepairResult } from './windows-install-dir-package-acl-repair' @@ -121,28 +119,6 @@ describe('repairWindowsInstallDirPackageAcl', () => { expect(moved.passes).toHaveLength(2) }) - it('re-runs when the marker is from an older scheme or is corrupt', async () => { - const userDataPath = userDataDir() - const markerFile = join(userDataPath, WINDOWS_INSTALL_DIR_ACL_REPAIR_MARKER_FILE) - writeFileSync( - markerFile, - JSON.stringify({ - schemeVersion: WINDOWS_INSTALL_DIR_ACL_REPAIR_SCHEME_VERSION - 1, - installDir: INSTALL_DIR, - appVersion: APP_VERSION - }) - ) - const stale = fakePackageGrant() - await repair({ userDataPath, grants: stale.grants }) - expect(stale.passes).toHaveLength(2) - - resetWindowsInstallDirAclRepairForTest() - writeFileSync(markerFile, '{ not json') - const corrupt = fakePackageGrant() - await repair({ userDataPath, grants: corrupt.grants }) - expect(corrupt.passes).toHaveLength(2) - }) - it('records the summed failed-entry count when a standard user cannot write the ACL', async () => { const { grants, passes } = fakePackageGrant((pass) => pass === 'tree' diff --git a/src/main/startup/windows-install-dir-package-acl-repair.ts b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.ts similarity index 96% rename from src/main/startup/windows-install-dir-package-acl-repair.ts rename to src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.ts index 970f4923327..8329a51f836 100644 --- a/src/main/startup/windows-install-dir-package-acl-repair.ts +++ b/src/main/startup/windows-install-permissions/windows-install-dir-package-acl-repair.ts @@ -1,10 +1,8 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' -import { - sanitizeCrashReportString, - type CrashReportBreadcrumbData -} from '../../shared/crash-reporting' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { sanitizeCrashReportString } from '../../../shared/crash-report-redaction' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { installDirPackageGrants, RESTRICTED_APP_PACKAGES_SID, diff --git a/src/main/startup/windows-app-data-path.test.ts b/src/main/startup/windows-startup/windows-app-data-path.test.ts similarity index 91% rename from src/main/startup/windows-app-data-path.test.ts rename to src/main/startup/windows-startup/windows-app-data-path.test.ts index 00cd57ae063..97b86b2ec73 100644 --- a/src/main/startup/windows-app-data-path.test.ts +++ b/src/main/startup/windows-startup/windows-app-data-path.test.ts @@ -2,7 +2,7 @@ import { existsSync, mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, win32 } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' import { deriveWindowsAppDataPath, ensureWindowsAppDataPath, @@ -78,12 +78,6 @@ describe('ensureWindowsAppDataPath', () => { expect(host.paths.get('userData')).toBe('C:\\Users\\me\\AppData\\Roaming\\orca') }) - it('leaves userData to an explicit --user-data-dir switch', () => { - const host = createHost('C:\\Users\\me\\AppData\\Roaming', ['user-data-dir']) - ensureWindowsAppDataPath(host, {}, 'win32') - expect(host.calls).toEqual(['get:appData']) - }) - it('creates and sets appData from the environment before userData when the lookup throws', () => { // Use real missing directories to prove profileless sessions get their fallback created. const root = mkdtempSync(join(tmpdir(), 'orca-appdata-')) diff --git a/src/main/startup/windows-app-data-path.ts b/src/main/startup/windows-startup/windows-app-data-path.ts similarity index 100% rename from src/main/startup/windows-app-data-path.ts rename to src/main/startup/windows-startup/windows-app-data-path.ts diff --git a/src/main/startup/windows-isolated-spawner.ts b/src/main/startup/windows-startup/windows-isolated-spawner.ts similarity index 94% rename from src/main/startup/windows-isolated-spawner.ts rename to src/main/startup/windows-startup/windows-isolated-spawner.ts index 6b33f017468..28ae4342107 100644 --- a/src/main/startup/windows-isolated-spawner.ts +++ b/src/main/startup/windows-startup/windows-isolated-spawner.ts @@ -1,5 +1,5 @@ import { setIsolatedSpawner } from '@orca/process-host/isolated-detached-spawn' -import { loadWindowsSecurity } from '../../shared/windows-security-addon' +import { loadWindowsSecurity } from '../../../shared/windows-security-addon' /** Long-lived detached children (the WSL holder) then inherit none of main's handles, e.g. a * DevTools socket. A missing or stale addon keeps libuv's spawn, which inherits them. */ diff --git a/src/main/startup/windows-isolated-spawner.win32.test.ts b/src/main/startup/windows-startup/windows-isolated-spawner.win32.test.ts similarity index 97% rename from src/main/startup/windows-isolated-spawner.win32.test.ts rename to src/main/startup/windows-startup/windows-isolated-spawner.win32.test.ts index 130082cb5b2..b70a1009adf 100644 --- a/src/main/startup/windows-isolated-spawner.win32.test.ts +++ b/src/main/startup/windows-startup/windows-isolated-spawner.win32.test.ts @@ -10,10 +10,10 @@ import { setIsolatedSpawner, spawnDetachedWithoutInheritance } from '@orca/process-host/isolated-detached-spawn' -import { loadWindowsSecurity } from '../../shared/windows-security-addon' +import { loadWindowsSecurity } from '../../../shared/windows-security-addon' const describeOnWindows = process.platform === 'win32' ? describe : describe.skip -const ADDON = resolve(__dirname, '..', '..', '..', 'native', 'windows-security', 'index.js') +const ADDON = resolve(__dirname, '../../../../native/windows-security/index.js') const root = mkdtempSync(join(tmpdir(), 'orca-isolated-spawn-')) const entry = join(root, 'main.cjs') @@ -79,7 +79,7 @@ async function runElectron(mode: 'isolated' | 'libuv', holderMs: number) { describeOnWindows('isolated detached spawn against real Windows processes', () => { beforeAll(async () => { await build({ - entryPoints: [resolve(__dirname, 'windows-isolated-spawn-electron-fixture.ts')], + entryPoints: [resolve(__dirname, '../testing/windows-isolated-spawn-electron-fixture.ts')], outfile: entry, bundle: true, platform: 'node', diff --git a/src/main/startup/windows-renderer-runtime-files.test.ts b/src/main/startup/windows-startup/windows-renderer-runtime-files.test.ts similarity index 97% rename from src/main/startup/windows-renderer-runtime-files.test.ts rename to src/main/startup/windows-startup/windows-renderer-runtime-files.test.ts index c28e9f0bd58..c4add320906 100644 --- a/src/main/startup/windows-renderer-runtime-files.test.ts +++ b/src/main/startup/windows-startup/windows-renderer-runtime-files.test.ts @@ -9,7 +9,7 @@ const { electronApp, handleFailure } = vi.hoisted(() => ({ })) vi.mock('electron', () => ({ app: electronApp })) -vi.mock('./main-process-preflight-failure', () => ({ +vi.mock('../main-process-preflight-failure', () => ({ handleMainProcessPreflightFailure: handleFailure })) diff --git a/src/main/startup/windows-renderer-runtime-files.ts b/src/main/startup/windows-startup/windows-renderer-runtime-files.ts similarity index 95% rename from src/main/startup/windows-renderer-runtime-files.ts rename to src/main/startup/windows-startup/windows-renderer-runtime-files.ts index e3a477c0402..98f48fe6dff 100644 --- a/src/main/startup/windows-renderer-runtime-files.ts +++ b/src/main/startup/windows-startup/windows-renderer-runtime-files.ts @@ -1,7 +1,7 @@ import { app } from 'electron' import { closeSync, fstatSync, openSync } from 'node:fs' import { dirname, join } from 'node:path' -import { handleMainProcessPreflightFailure } from './main-process-preflight-failure' +import { handleMainProcessPreflightFailure } from '../main-process-preflight-failure' /** Every renderer delay-loads this at child init; without it each one dies with 0x80000003 before any page loads. */ const RENDERER_RUNTIME_FILES = ['ffmpeg.dll'] as const diff --git a/src/main/startup/windows-std-handle-inheritance.ts b/src/main/startup/windows-startup/windows-std-handle-inheritance.ts similarity index 91% rename from src/main/startup/windows-std-handle-inheritance.ts rename to src/main/startup/windows-startup/windows-std-handle-inheritance.ts index 224068740f3..f25dead3cad 100644 --- a/src/main/startup/windows-std-handle-inheritance.ts +++ b/src/main/startup/windows-startup/windows-std-handle-inheritance.ts @@ -1,4 +1,4 @@ -import { loadWindowsSecurity } from '../../shared/windows-security-addon' +import { loadWindowsSecurity } from '../../../shared/windows-security-addon' /** libuv spawns with bInheritHandles=TRUE, so an inheritable std handle reaches every child, and a * long-lived one (the WSL holder, the daemon) keeps a launcher's pipe open after Orca exits. */ diff --git a/src/main/startup/windows-std-handle-inheritance.win32.test.ts b/src/main/startup/windows-startup/windows-std-handle-inheritance.win32.test.ts similarity index 89% rename from src/main/startup/windows-std-handle-inheritance.win32.test.ts rename to src/main/startup/windows-startup/windows-std-handle-inheritance.win32.test.ts index 2fd9d6d486c..989804f6e6f 100644 --- a/src/main/startup/windows-std-handle-inheritance.win32.test.ts +++ b/src/main/startup/windows-startup/windows-std-handle-inheritance.win32.test.ts @@ -7,7 +7,7 @@ import { afterAll, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' const describeOnWindows = process.platform === 'win32' ? describe : describe.skip -const ADDON = resolve(__dirname, '..', '..', '..', 'native', 'windows-security', 'index.js') +const ADDON = resolve(__dirname, '..', '..', '..', '..', 'native', 'windows-security', 'index.js') const root = mkdtempSync(join(tmpdir(), 'orca-std-handles-')) const entry = join(root, 'main.cjs') @@ -84,11 +84,4 @@ describeOnWindows('clearing std handle inheritance', () => { }, 90_000) // Cold Electron start on a CI runner plus the 3 s holder exceeds the 5 s default. - it('without it, Electron main lets the holder keep the pipe open until it exits', async () => { - const run = await runChild('electron', 'keep', 3_000) - - expect(run.code, run.output).toBe(0) - expect(run.output).toContain('inherited-output') - expect(run.holderAliveAtClose).toBe(false) - }, 60_000) }) diff --git a/src/main/startup/windows-user-data-acl.test.ts b/src/main/startup/windows-startup/windows-user-data-acl.test.ts similarity index 97% rename from src/main/startup/windows-user-data-acl.test.ts rename to src/main/startup/windows-startup/windows-user-data-acl.test.ts index c278fa95d44..fccc6c71b02 100644 --- a/src/main/startup/windows-user-data-acl.test.ts +++ b/src/main/startup/windows-startup/windows-user-data-acl.test.ts @@ -5,12 +5,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { resetWindowsSecurityLoadForTests, setWindowsSecurityForTests -} from '../../shared/windows-security-addon' +} from '../../../shared/windows-security-addon' import { createFakeWindowsSecurity, FAKE_USER_SID, type FakeWindowsSecurity -} from '../../shared/windows-security-addon.test-fixture' +} from '../../../shared/windows-security-addon.test-fixture' import { ensureWindowsUserDataAclGrant, WINDOWS_ACL_GRANT_MARKER_FILE, diff --git a/src/main/startup/windows-user-data-acl.ts b/src/main/startup/windows-startup/windows-user-data-acl.ts similarity index 96% rename from src/main/startup/windows-user-data-acl.ts rename to src/main/startup/windows-startup/windows-user-data-acl.ts index b39ff0b3559..0bd92275ae2 100644 --- a/src/main/startup/windows-user-data-acl.ts +++ b/src/main/startup/windows-startup/windows-user-data-acl.ts @@ -1,7 +1,7 @@ import { readdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { grantDirAclAsync } from '../windows/windows-directory-acl' -import { loadWindowsSecurity } from '../../shared/windows-security-addon' +import { grantDirAclAsync } from '../../windows/windows-directory-acl' +import { loadWindowsSecurity } from '../../../shared/windows-security-addon' /** #1152: Chromium replaces userData DACL and inherited child ACEs become inherit-only, causing EPERM. Grant explicit root/immediate-child access once per identity; inherited propagation covers descendants (full 28k-file walk measured 62s). Run in the pool; per-write EPERM retries cover startup races. */ diff --git a/src/main/startup/branch-rename-hook.ts b/src/main/startup/workspace-startup/branch-rename-hook.ts similarity index 81% rename from src/main/startup/branch-rename-hook.ts rename to src/main/startup/workspace-startup/branch-rename-hook.ts index 76e96b1af69..f2907c14ef0 100644 --- a/src/main/startup/branch-rename-hook.ts +++ b/src/main/startup/workspace-startup/branch-rename-hook.ts @@ -1,7 +1,7 @@ -import { maybeAutoRenameBranchOnFirstWork } from '../agent-hooks/first-work/first-work-branch-rename' -import { firstWorkRenameDeps } from '../agent-hooks/first-work/first-work-rename-runtime' -import { agentHookServer } from '../agent-hooks/server/agent-hook-server' -import { mainProcessState as state } from './main-process-state' +import { maybeAutoRenameBranchOnFirstWork } from '../../agent-hooks/first-work/first-work-branch-rename' +import { firstWorkRenameDeps } from '../../agent-hooks/first-work/first-work-rename-runtime' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { mainProcessState as state } from '../main-process-state' /** Arms first-work rename from the hook store itself, so headless serve (no window) renames too. */ export function installFirstWorkRenameHookSubscription(): () => void { diff --git a/src/main/startup/worktree-removal-records-load.ts b/src/main/startup/workspace-startup/worktree-removal-records-load.ts similarity index 77% rename from src/main/startup/worktree-removal-records-load.ts rename to src/main/startup/workspace-startup/worktree-removal-records-load.ts index da0766d897e..453a274ef33 100644 --- a/src/main/startup/worktree-removal-records-load.ts +++ b/src/main/startup/workspace-startup/worktree-removal-records-load.ts @@ -1,6 +1,6 @@ -import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import type { Repo } from '../../shared/repo-types' -import { loadWorktreeRemovalRecords } from '../workspaces/removal/worktree-background-removal' +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import { loadWorktreeRemovalRecords } from '../../workspaces/removal/worktree-background-removal' /** Retain failed deletions only while this host has the local repo copy; an SSH copy under the same ID cannot show its deletion row. */ export function loadWorktreeRemovalRecordsForStore(store: { diff --git a/src/main/startup/wsl-orcad-account-env-wiring.test.ts b/src/main/startup/wsl-orcad-account-env-wiring.test.ts deleted file mode 100644 index 72033c147c0..00000000000 --- a/src/main/startup/wsl-orcad-account-env-wiring.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) - -import { oncePerDistro } from './wsl-orcad-account-env-wiring' - -describe('oncePerDistro', () => { - it('tells the user about each distro once per run, whatever its casing', () => { - const send = vi.fn() - const notify = oncePerDistro(send) - notify('Ubuntu') - notify('ubuntu') - notify('Debian') - notify('Ubuntu') - expect(send.mock.calls).toEqual([['Ubuntu'], ['Debian']]) - }) -}) diff --git a/src/main/startup/wsl-cli-reconciliation-startup-barrier.test.ts b/src/main/startup/wsl-startup/wsl-cli-reconciliation-startup-barrier.test.ts similarity index 100% rename from src/main/startup/wsl-cli-reconciliation-startup-barrier.test.ts rename to src/main/startup/wsl-startup/wsl-cli-reconciliation-startup-barrier.test.ts diff --git a/src/main/startup/wsl-cli-reconciliation-startup-barrier.ts b/src/main/startup/wsl-startup/wsl-cli-reconciliation-startup-barrier.ts similarity index 100% rename from src/main/startup/wsl-cli-reconciliation-startup-barrier.ts rename to src/main/startup/wsl-startup/wsl-cli-reconciliation-startup-barrier.ts diff --git a/src/main/startup/wsl-orcad-account-env-wiring.ts b/src/main/startup/wsl-startup/wsl-orcad-account-env-wiring.ts similarity index 76% rename from src/main/startup/wsl-orcad-account-env-wiring.ts rename to src/main/startup/wsl-startup/wsl-orcad-account-env-wiring.ts index f6f73304bfc..c05145db9a5 100644 --- a/src/main/startup/wsl-orcad-account-env-wiring.ts +++ b/src/main/startup/wsl-startup/wsl-orcad-account-env-wiring.ts @@ -1,14 +1,14 @@ import { BrowserWindow } from 'electron' -import { withClaudeProfileTerminalEnv } from '../claude-accounts/profiles/routing/claude-profile-installed-router' -import { getSelectedClaudeAccountIdForTarget } from '../claude-accounts/selection/runtime-selection' -import { getSelectedCodexAccountIdForTarget } from '../codex-accounts/runtime-selection' -import type { Store } from '../persistence/loading-store/store' -import { installWslOrcadAccountEnvDependencies } from '../wsl/orcad/wsl-orcad-account-env' +import { withClaudeProfileTerminalEnv } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' +import { getSelectedClaudeAccountIdForTarget } from '../../claude-accounts/selection/runtime-selection' +import { getSelectedCodexAccountIdForTarget } from '../../codex-accounts/account-management/runtime-selection' +import type { Store } from '../../persistence/loading-store/store' +import { installWslOrcadAccountEnvDependencies } from '../../wsl/orcad/wsl-orcad-account-env' import { WSL_ORCAD_ACCOUNT_NOT_APPLIED_CHANNEL, type WslOrcadAccountNotAppliedEvent -} from '../../shared/wsl-orcad-account-notice' -import { mainProcessState as state } from './main-process-state' +} from '../../../shared/wsl-orcad-account-notice' +import { mainProcessState as state } from '../main-process-state' /** Calls `send` once per distro (case-insensitive) for the life of this process. */ export function oncePerDistro(send: (distro: string) => void): (distro: string) => void { diff --git a/src/main/telemetry/chat-ui-launch-tip-cohort.ts b/src/main/telemetry/chat-ui-launch-tip-cohort.ts index 95e51308ac8..69da98779bc 100644 --- a/src/main/telemetry/chat-ui-launch-tip-cohort.ts +++ b/src/main/telemetry/chat-ui-launch-tip-cohort.ts @@ -1,73 +1,36 @@ -import { randomInt } from 'node:crypto' import type { Store } from '../persistence/loading-store/store' -import type { GlobalSettings } from '../../shared/global-settings-types' import { resolveConsent } from './consent' -import type { - ChatUiLaunchTipCohort, - ChatUiLaunchTipTargeting -} from '../../shared/telemetry-settings-types' +import { getFeatureTipSeenId } from '../../shared/feature-tips' +import type { ChatUiLaunchTipCohort } from '../../shared/telemetry-settings-types' export type { ChatUiLaunchTipCohort } -// Decided once per launch with the cohort, so the tip and its enrollment read the same consent; contributor builds never set it. +// Decided once per launch, so the tip and its telemetry read the same consent; contributor builds never set it. let deferredForConsent = false /** - * Enrolls once, only profiles still due the tip whose events can be measured. While the telemetry - * banner is unresolved the tip waits, so the exposure is never spent unmeasured; opted-out and - * contributor builds stay unenrolled and see the tip as before. + * Only reads back a saved assignment; nothing new is assigned. While the telemetry banner is + * unresolved for a profile still due the tip, the tip waits. */ export function ensureChatUiLaunchTipCohort(store: Store): ChatUiLaunchTipCohort | undefined { deferredForConsent = false try { const settings = store.getSettings() const telemetry = settings.telemetry - const saved = telemetry?.chatUiLaunchTipCohort - const rollout = telemetry?.chatUiLaunchTipRolloutCohort - if (rollout === 'control' || rollout === 'treatment') { - return rollout - } + const saved = telemetry?.chatUiLaunchTipRolloutCohort ?? telemetry?.chatUiLaunchTipCohort if ( - saved === 'treatment' || - saved === 'treatment-live-switch' || - saved === 'treatment-swapped-buttons' || - saved === 'treatment-center' + telemetry && + resolveConsent(settings).effective === 'pending_banner' && + store.getChatUiLaunchTipVariant() !== 'none' && + // Why: some profiles carry the generic id without having seen the tip; check the id that applies. + !store.getFeatureTipsSeenIds().includes(getFeatureTipSeenId('chat-ui-here', telemetry)) ) { - return saved + deferredForConsent = true } - if ( - !telemetry || - store.getChatUiLaunchTipVariant() === 'none' || - (saved !== 'control' && store.getUI().featureTipsSeenIds?.includes('chat-ui-here')) - ) { - return saved === 'control' ? saved : undefined - } - const consent = resolveConsent(settings).effective - if (consent !== 'enabled') { - deferredForConsent = consent === 'pending_banner' - return saved === 'control' ? saved : undefined - } - // Promote 3/7 of the old 70% control group once: 30% + 70% × 3/7 = 60% treatment. - const draw = randomInt(saved === 'control' ? 7 : 10) - const cohort: ChatUiLaunchTipCohort = draw < 4 ? 'control' : 'treatment' - const targeting = - cohort === 'control' ? undefined : assignTargeting(settings.agentDefaultSurface) - store.updateSettings({ - telemetry: { - ...telemetry, - chatUiLaunchTipRolloutCohort: cohort, - ...(targeting - ? { - chatUiLaunchTipTargeting: targeting, - chatUiLaunchTipButtonEmphasis: randomInt(2) === 0 ? 'normal' : 'swapped' - } - : {}) - } - }) - return cohort + return saved } catch (err) { - // Startup must not fail over an experiment; unenrolled profiles see the tip as before. - console.warn('[telemetry] chat UI launch tip cohort assignment failed', err) + // Startup must not fail over this read; the tip still follows the saved settings. + console.warn('[telemetry] chat UI launch tip settings read failed', err) return undefined } } @@ -76,12 +39,3 @@ export function ensureChatUiLaunchTipCohort(store: Store): ChatUiLaunchTipCohort export function isChatUiLaunchTipDeferredForConsent(): boolean { return deferredForConsent } - -function assignTargeting( - defaultSurface: GlobalSettings['agentDefaultSurface'] -): ChatUiLaunchTipTargeting { - if (randomInt(2) === 0) { - return { mode: 'all' } - } - return { mode: 'not-switched', eligible: defaultSurface !== 'chat' } -} diff --git a/src/main/telemetry/structured-chat-prompt-owner.test.ts b/src/main/telemetry/structured-chat-prompt-owner.test.ts deleted file mode 100644 index ff0cdbed471..00000000000 --- a/src/main/telemetry/structured-chat-prompt-owner.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { RpcContext } from '../runtime/rpc/core' -import type { RpcCallerIdentity } from '../runtime/rpc/rpc-caller-identity' -import { structuredCallerFor } from '../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate' -import type { StructuredChatTelemetryEvent } from '../../shared/structured-chat-dispatch-telemetry' -import { _setCommonPropsForTests } from './client' -import { - BASE_COMMON, - cleanupTelemetryClientTest, - setupTelemetryClientTest, - type TelemetryClientTestState -} from './client-test-harness' -import { - recordRemoteStructuredChatTelemetry, - recordStructuredChatPromptAccepted, - subscribeStructuredChatTelemetry -} from './structured-chat-dispatch' - -const HOST_INSTALL = '11111111-1111-4111-8111-111111111111' -const OWNER_INSTALL = '22222222-2222-4222-8222-222222222222' -let active: TelemetryClientTestState | undefined -let relayed: { event: StructuredChatTelemetryEvent; owner: string }[] -let unsubscribe: () => void - -beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-11-08T23:58:00Z')) - relayed = [] - unsubscribe = subscribeStructuredChatTelemetry((event, owner) => relayed.push({ event, owner })) -}) -afterEach(() => { - unsubscribe() - if (active) { - cleanupTelemetryClientTest(active.envStash) - active = undefined - } - vi.useRealTimers() -}) - -function desktop(installId: string, optedIn: boolean): TelemetryClientTestState { - if (active) { - cleanupTelemetryClientTest(active.envStash) - } - active = setupTelemetryClientTest({ - installId, - optedIn, - existedBeforeTelemetryRelease: false, - protectedMilestones: { installCohort: 'fresh' } - }) - _setCommonPropsForTests({ ...BASE_COMMON, install_id: installId }) - return active -} - -function accept( - caller: RpcCallerIdentity, - clientKind?: 'mobile' | 'runtime', - pairedDeviceParentId?: string -): void { - const context: Partial = { caller, clientKind, pairedDeviceParentId } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: caller derivation reads only the supplied transport identity fields. - const identity = structuredCallerFor(context as RpcContext) - if (!identity.userClient) { - throw new Error('expected a transport-proven user') - } - recordStructuredChatPromptAccepted( - { agent_kind: 'codex', runtime: 'unknown', client: identity.userClient }, - identity.telemetryOwnerKey - ) -} - -const captured = (state: TelemetryClientTestState, name: string) => - state.mock.capture.mock.calls.map(([event]) => event).filter((event) => event.event === name) - -it('lets the originating desktop opt in even when its initialized execution host opts out', () => { - const host = desktop(HOST_INSTALL, false) - accept({ kind: 'paired-device', deviceId: 'originating-desktop' }, 'runtime') - expect(relayed).toEqual([ - { - owner: 'originating-desktop', - event: { - type: 'structuredChatPromptAccepted', - id: expect.any(String), - agent_kind: 'codex', - client: 'desktop' - } - } - ]) - expect(host.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) - expect(host.mock.capture.mock.calls).toEqual([]) - - const owner = desktop(OWNER_INSTALL, true) - recordRemoteStructuredChatTelemetry(relayed[0].event) - expect(owner.settings.telemetry?.protectedMilestones).toEqual({ - installCohort: 'fresh', - firstAgentInteractionDay: 20_765, - meaningfulActivityDay: 20_765 - }) - expect(captured(owner, 'first_agent_interaction')[0].properties).toMatchObject({ - install_id: OWNER_INSTALL, - source: 'native_chat' - }) - expect(captured(owner, 'meaningful_activity_day')[0].properties).toMatchObject({ - install_id: OWNER_INSTALL, - trigger: 'native_chat' - }) -}) - -it('respects a delegated phone owners opt-out even when its initialized execution host opts in', () => { - const host = desktop(HOST_INSTALL, true) - accept({ kind: 'paired-device', deviceId: 'delegated-phone' }, 'mobile', 'originating-desktop') - expect(relayed).toEqual([ - { - owner: 'originating-desktop', - event: { - type: 'structuredChatPromptAccepted', - id: expect.any(String), - agent_kind: 'codex', - client: 'mobile' - } - } - ]) - expect(host.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) - expect(host.mock.capture.mock.calls).toEqual([]) - - const owner = desktop(OWNER_INSTALL, false) - recordRemoteStructuredChatTelemetry(relayed[0].event) - expect(owner.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) - expect(owner.mock.capture.mock.calls).toEqual([]) -}) - -it('keeps the local desktop and its directly paired phone on host installation consent', () => { - const host = desktop(HOST_INSTALL, true) - accept({ kind: 'desktop' }) - vi.setSystemTime(new Date('2026-11-09T00:01:00Z')) - accept({ kind: 'paired-device', deviceId: 'direct-phone' }, 'mobile') - expect(relayed).toEqual([]) - expect(host.settings.telemetry?.protectedMilestones).toEqual({ - installCohort: 'fresh', - firstAgentInteractionDay: 20_765, - meaningfulActivityDay: 20_766 - }) - expect(captured(host, 'first_agent_interaction')[0].properties).toMatchObject({ - install_id: HOST_INSTALL, - source: 'native_chat' - }) - expect( - captured(host, 'meaningful_activity_day').map((event) => ({ - install_id: event.properties.install_id, - trigger: event.properties.trigger - })) - ).toEqual([ - { install_id: HOST_INSTALL, trigger: 'native_chat' }, - { install_id: HOST_INSTALL, trigger: 'mobile_chat' } - ]) -}) diff --git a/src/main/text-generation/agent-failure-output.test.ts b/src/main/text-generation/agent-failure-output.test.ts deleted file mode 100644 index b4c24617d9e..00000000000 --- a/src/main/text-generation/agent-failure-output.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - captureAgentGenerationFailureOutput, - formatAgentGenerationFailureOutputForDisplay -} from './agent-failure-output' - -const ESC = String.fromCharCode(27) -const BEL = String.fromCharCode(7) - -describe('captureAgentGenerationFailureOutput', () => { - it('returns null when both streams are blank', () => { - expect(captureAgentGenerationFailureOutput('Pi', 1, ' \n', '\t')).toBeNull() - }) - - it('keeps short streams verbatim', () => { - const capture = captureAgentGenerationFailureOutput('Pi', 1, 'out', 'err') - expect(capture).toEqual({ label: 'Pi', exitCode: 1, stdout: 'out', stderr: 'err' }) - }) - - it('bounds an oversized stream to its head and tail with an omission marker', () => { - const oversized = `${'h'.repeat(20_000)}${'m'.repeat(40_000)}${'t'.repeat(50_000)}` - const capture = captureAgentGenerationFailureOutput('Pi', 1, '', oversized) - const stderr = capture?.stderr ?? '' - expect(stderr.startsWith('h'.repeat(16 * 1024))).toBe(true) - expect(stderr.endsWith('t'.repeat(48 * 1024))).toBe(true) - expect(stderr).toContain('characters omitted') - expect(stderr.length).toBeLessThan(oversized.length) - }) -}) - -describe('formatAgentGenerationFailureOutputForDisplay', () => { - it('renders a header plus the streams that had content, stderr first', () => { - const text = formatAgentGenerationFailureOutputForDisplay({ - label: 'Pi', - exitCode: 1, - stdout: 'partial result', - stderr: 'No API key found for github-copilot.' - }) - expect(text).toBe( - 'Pi exited with code 1.\n\n[stderr]\nNo API key found for github-copilot.\n\n[stdout]\npartial result' - ) - }) - - it('omits a blank stream section and reports an unknown exit code', () => { - const text = formatAgentGenerationFailureOutputForDisplay({ - label: 'Claude', - exitCode: null, - stdout: 'Not logged in · Please run /login', - stderr: ' ' - }) - expect(text).toBe( - 'Claude exited with code unknown.\n\n[stdout]\nNot logged in · Please run /login' - ) - }) - - it('strips ANSI, OSC, and bidi-override characters while keeping line structure', () => { - const text = formatAgentGenerationFailureOutputForDisplay({ - label: 'Pi', - exitCode: 1, - stdout: '', - stderr: `${ESC}]0;title${BEL}${ESC}[91mline one${ESC}[0m\r\nsafe ${String.fromCharCode(0x202e)}evil${String.fromCharCode(0x202c)} tail\rline three` - }) - expect(text).toBe('Pi exited with code 1.\n\n[stderr]\nline one\nsafe evil tail\nline three') - }) - - it('keeps later diagnostics when an OSC sequence is unterminated', () => { - const text = formatAgentGenerationFailureOutputForDisplay({ - label: 'Pi', - exitCode: 1, - stdout: '', - stderr: `${ESC}]0;unfinished title\nNo API key found.\nUse /login to log in.` - }) - expect(text).toContain('No API key found.\nUse /login to log in.') - }) -}) diff --git a/src/main/text-generation/agent-generation-request.ts b/src/main/text-generation/agent-generation-request.ts index cb4eadb106e..04d8d595a46 100644 --- a/src/main/text-generation/agent-generation-request.ts +++ b/src/main/text-generation/agent-generation-request.ts @@ -1,10 +1,7 @@ import { conversationNameTaskPrompt } from '../../shared/source-control/ai/generation/conversation-name-generation' import { textGenerationFailureCodeFields } from '../../shared/text-generation-failure-copy' import { runClaudeGenerationAttempts } from '../../shared/claude-background-run-isolation' -import { - cleanGeneratedCommitMessage, - stripPrefilledReasoningPreamble -} from '../../shared/source-control/ai/generation/commit-message-agent-output' +import { stripPrefilledReasoningPreamble } from '../../shared/source-control/ai/generation/commit-message-agent-output' import type { CommandTemplateBackslash } from '../../shared/source-control/ai/generation/commit-message-prompt' import { isCustomAgentId } from '../../shared/source-control/ai/generation/commit-message-agent-spec' import { @@ -13,11 +10,11 @@ import { } from '../../shared/source-control/ai/generation/commit-message-plan' import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' import { openCodeVariantRetryPlan } from '../../shared/opencode-generation-command' -import { copilotUnavailableModelRetryPlan } from './copilot-unavailable-model-retry' -import { runLocalPlanForAgent } from './source-control-local-generation' +import { copilotUnavailableModelRetryPlan } from './failures/copilot-unavailable-model-retry' +import { runLocalPlanForAgent } from './execution/source-control-local-generation' import { runOpenCodeTextTask } from '../opencode/text-tasks/opencode-text-task' -import { emptyResultFailure } from './source-control-agent-failure' -import { runRemoteSourceControlPlan } from './source-control-remote-generation' +import { cleanAgentAnswer, emptyResultFailure } from './failures/source-control-agent-failure' +import { runRemoteSourceControlPlan } from './execution/source-control-remote-generation' import type { CommitMessageGenerationTarget, InternalTextGenerationResult, @@ -44,7 +41,8 @@ export async function runGenerationRequest(input: { }): Promise { const params = { ...input.params, - backslash: commandBackslashMode(input.target) + backslash: commandBackslashMode(input.target), + toolFree: input.operation === 'dictation-cleanup' } const prompt = input.operation === 'conversation-name' @@ -86,6 +84,13 @@ export async function runGenerationRequest(input: { if (attempt.strictMcp && !attempt.legacyToolPolicy) { return execute(plan) } + // Old CLIs can't deny MCP tools by pattern, so a tool-free task stops rather than load them. + if (params.toolFree && !attempt.strictMcp && attempt.legacyToolPolicy) { + return Promise.resolve({ + success: false, + error: 'This Claude CLI can’t run without tools under its MCP policy. Update Claude Code.' + }) + } const retry = planCommitMessageGeneration(params, prompt, attempt) return retry.ok ? execute(retry.plan) @@ -126,7 +131,7 @@ export async function runGenerationRequest(input: { if (answer === result.rawOutput) { return result } - const rawOutput = cleanGeneratedCommitMessage(answer) + const rawOutput = cleanAgentAnswer(answer, input.operation) return rawOutput ? { ...result, rawOutput } : { success: false, ...emptyResultFailure(input.operation, plan.label) } diff --git a/src/main/text-generation/antigravity-generation-stream.test.ts b/src/main/text-generation/antigravity-generation-stream.test.ts deleted file mode 100644 index 588c7a782eb..00000000000 --- a/src/main/text-generation/antigravity-generation-stream.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { parseAntigravityGenerationOutput } from '../../shared/antigravity-generation-stream' -import { - generateCommitMessageFromContext, - generatePullRequestFieldsFromContext -} from './commit-message-text-generation' -import { generatePullRequestFields } from './source-control-text-generation-requests' -import { - createMockDiscoveryChild, - withPlatform -} from './commit-message-text-generation-test-harness' - -const resultEvent = (response: string, status = 'SUCCESS', error?: string): string => - JSON.stringify({ event: 'result', result: { status, response, error } }) -const context = { - branch: 'feature/large-diff', - base: 'main', - branchChangedByPreparation: false, - currentTitle: '', - currentBody: '', - currentDraft: false, - commitSummary: 'Add fixture', - changeSummary: 'A\tfixture.txt', - patch: `diff --git a/fixture.txt b/fixture.txt\n+${'x'.repeat(200_000)}` -} -const params = { agentId: 'antigravity', model: 'default' } as const -const fields = { base: 'main', title: 'Add fixture', body: 'Describe the fixture', draft: false } - -describe('Antigravity generation stream', () => { - it('generates pull request fields on Windows without putting a large patch on argv', async () => { - await withPlatform('win32', async () => { - const child = createMockDiscoveryChild() - const pending = generatePullRequestFields({ - context, - params, - target: { kind: 'local', cwd: 'C:\\folder-workspace' }, - spawnAgent: (input) => { - if (input.args.includes('--help')) { - const probe = createMockDiscoveryChild() - probe.stdin.end.mockImplementation(() => - queueMicrotask(() => { - probe.stdout.emit('data', Buffer.from(' --settings \n')) - probe.emit('close', 0) - }) - ) - return probe - } - expect(input.args.join(' ').length).toBeLessThan(30_000) - expect(input.args).toContain('--input-format=stream-json') - return child - } - }) - await vi.waitFor(() => expect(child.stdin.end).toHaveBeenCalled()) - const input = JSON.parse(child.stdin.end.mock.calls[0]?.[0] ?? '') - expect(input.message.content[0].text).toContain('(diff truncated,') - expect(input.message.content[0].text.length).toBeGreaterThan(200_000) - child.stdout.emit('data', Buffer.from(resultEvent(JSON.stringify(fields)))) - child.emit('close', 0) - await expect(pending).resolves.toMatchObject({ success: true, fields }) - }) - }) - - it('sends structured stdin and parses only the final answer across remote execution', async () => { - const result = await generatePullRequestFieldsFromContext(context, params, { - kind: 'remote', - cwd: '/folder-workspace', - missingBinaryLocation: 'remote PATH', - execute: async (plan) => { - expect(JSON.parse(plan.stdinPayload ?? '').event).toBe('user') - return { - stdout: [ - JSON.stringify({ event: 'init', init: { tools: ['read_file'] } }), - JSON.stringify({ event: 'step_update', step_update: { text_delta: 'Partial' } }), - resultEvent(JSON.stringify(fields)) - ].join('\r\n'), - stderr: '', - exitCode: 0, - timedOut: false - } - } - }) - expect(result).toMatchObject({ success: true, fields, agentLabel: 'Antigravity' }) - }) - - it('does not treat a failed stream turn as a successful commit message when exit code is zero', async () => { - const result = await generateCommitMessageFromContext( - { branch: 'main', stagedSummary: 'A\tfixture.txt', stagedPatch: '+fixture' }, - params, - { - kind: 'remote', - cwd: '/folder-workspace', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: resultEvent('Partial answer', 'ERROR', 'Model unavailable'), - stderr: '', - exitCode: 0, - timedOut: false - }) - } - ) - expect(result).toMatchObject({ success: false, error: 'Model unavailable' }) - }) - - it('preserves actionable stderr when a nonzero exit has a malformed result event', async () => { - const result = await generateCommitMessageFromContext( - { branch: 'main', stagedSummary: 'A\tfixture.txt', stagedPatch: '+fixture' }, - params, - { - kind: 'remote', - cwd: '/folder-workspace', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: '{"event":"result"}', - stderr: 'Not logged into Antigravity. Run agy login.', - exitCode: 1, - timedOut: false - }) - } - ) - expect(result).toMatchObject({ success: false }) - if (result.success) { - throw new Error('Expected generation to fail') - } - expect(result.error).toContain('Not logged into Antigravity. Run agy login.') - expect(result.error).not.toContain('invalid result') - }) - - it.each([ - 'plain output', - '{"event":"result"}', - '{"event":"step_update","step_update":{"text_delta":"Partial"}}', - '{"event":"result","result":{"status":"SUCCESS","response":42}}' - ])('rejects malformed or incomplete output: %s', (output) => { - expect(parseAntigravityGenerationOutput(output)).toMatchObject({ ok: false }) - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation-branch-name.test.ts b/src/main/text-generation/commit-message-text-generation-branch-name.test.ts deleted file mode 100644 index 78115918849..00000000000 --- a/src/main/text-generation/commit-message-text-generation-branch-name.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { - sourceShapedKimiOutput, - realKimiOccupiedOutput -} from '../../shared/__fixtures__/kimi-generation-source-shaped' -import { describe, expect, it } from 'vitest' -import { generateBranchNameFromContext } from './commit-message-text-generation' - -describe('generateBranchNameFromContext', () => { - it.each(['custom', 'kimi'] as const)('%s branch slug', async (agentId) => { - const result = await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { - agentId, - model: agentId === 'kimi' ? 'default' : '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: - agentId === 'kimi' - ? sourceShapedKimiOutput('"Fix/Login Flow now please"') - : '"Fix/Login Flow now please"\n', - stderr: '', - exitCode: 0, - timedOut: false - }) - } - ) - - expect(result).toEqual({ - success: true, - slug: 'fix-login-flow-now', - agentLabel: agentId === 'kimi' ? 'Kimi' : 'agent' - }) - }) - - it('fails when remote agent output sanitizes to an empty branch slug', async () => { - const result = await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: '!!! ___\n', - stderr: '', - exitCode: 0, - timedOut: false - }) - } - ) - - expect(result).toMatchObject({ - success: false, - error: 'Generated branch name was empty after sanitization.', - failureOutput: { label: 'agent', exitCode: 0, stdout: '!!! ___', stderr: '' } - }) - }) - - it.each(['pi', 'kimi'] as const)('%s failure diagnostics', async (agentId) => { - const result = await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { - agentId, - model: agentId === 'kimi' ? 'default' : 'github-copilot/gpt-5.5' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: agentId === 'kimi' ? realKimiOccupiedOutput : 'partial', - stderr: 'No API key found for github-copilot.', - exitCode: agentId === 'kimi' ? 4 : 1, - timedOut: false - }) - } - ) - - expect(result.success).toBe(false) - if (result.success) { - throw new Error('expected a failure result') - } - if (agentId === 'kimi') { - expect(result.error).toMatch(/Kimi.*active.*Stop.*exit.*try again/) - } - expect(result.failureOutput).toEqual({ - label: agentId === 'kimi' ? 'Kimi' : 'Pi', - exitCode: agentId === 'kimi' ? 4 : 1, - stdout: agentId === 'kimi' ? realKimiOccupiedOutput : 'partial', - stderr: 'No API key found for github-copilot.' - }) - }) - - it('describes a signal-terminated generator without a null exit code', async () => { - const result = await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { - agentId: 'pi', - model: 'github-copilot/gpt-5.5' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: '', - stderr: 'Process killed by host', - exitCode: null, - timedOut: false - }) - } - ) - - expect(result).toMatchObject({ - success: false, - error: 'Pi CLI command was terminated before exiting: Process killed by host' - }) - }) - - it('reruns Copilot once on its default model when the plan hides the saved model', async () => { - const calls: string[][] = [] - const result = await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { agentId: 'copilot', model: 'gpt-5.4', thinkingLevel: 'low' }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan) => { - calls.push(plan.args) - return calls.length === 1 - ? { - stdout: '', - stderr: 'Error: Model "gpt-5.4" from --model flag is not available.\n', - exitCode: 1, - timedOut: false - } - : { stdout: 'fix-login-flow\n', stderr: '', exitCode: 0, timedOut: false } - } - } - ) - - expect(result).toEqual({ success: true, slug: 'fix-login-flow', agentLabel: 'GitHub Copilot' }) - expect(calls).toHaveLength(2) - expect(calls[0]).toEqual(expect.arrayContaining(['--model', 'gpt-5.4', '--effort', 'low'])) - expect(calls[1]).toEqual( - calls[0].filter((arg) => !['--model', 'gpt-5.4', '--effort', 'low'].includes(arg)) - ) - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts b/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts deleted file mode 100644 index 9c5df2c8a15..00000000000 --- a/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { spawn } from 'node:child_process' -import type * as ChildProcess from 'node:child_process' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { generateCommitMessageFromContext } from './commit-message-text-generation' -import { - createChildTerminationExpectation, - withPlatform -} from './commit-message-text-generation-test-harness' - -const { terminateWindowsProcessTreeMock } = vi.hoisted(() => ({ - terminateWindowsProcessTreeMock: vi.fn(async () => {}) -})) - -vi.mock('../pty/process-retirement/windows-process-tree-kill', () => ({ - terminateWindowsProcessTree: terminateWindowsProcessTreeMock -})) - -vi.mock('child_process', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - spawn: vi.fn(actual.spawn) - } -}) - -const spawnMock = vi.mocked(spawn) - -const expectChildTerminated = createChildTerminationExpectation(terminateWindowsProcessTreeMock) - -// Fake Windows direct-child/taskkill paths here; source-control-local-process.test.ts covers supervised POSIX stop and managed-home lock release. -const hostPlatform = process.platform - -afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: hostPlatform }) - vi.unstubAllEnvs() -}) - -beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - // Clear PATH so host agent installs cannot answer fake Windows lookups. - vi.stubEnv('PATH', '') - terminateWindowsProcessTreeMock.mockClear() - terminateWindowsProcessTreeMock.mockResolvedValue(undefined) - spawnMock.mockClear() -}) - -describe('generateCommitMessageFromContext on the Windows direct-child path', () => { - it('caps local agent output before buffering unbounded data', async () => { - const listeners = new Map void>() - const child = { - pid: 123, - kill: vi.fn(), - stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, - stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, - stdin: { end: vi.fn() }, - on: vi.fn((event, callback) => listeners.set(event, callback)) - } - spawnMock.mockReturnValue(child as never) - - const pending = generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'local', - cwd: '/repo' - } - ) - - listeners.get('stdout:data')?.(Buffer.alloc(4 * 1024 * 1024 + 1)) - listeners.get('close')?.(null) - - await expect(pending).resolves.toMatchObject({ - success: false, - error: - 'agent CLI command produced too much output. Check the agent CLI configuration and try again.' - }) - await expectChildTerminated(child) - }) - - it('rejects unsafe argv prompts for Windows batch-script agent commands', async () => { - await withPlatform('win32', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello & goodbye' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'C:/tools/agent.cmd {prompt}' - }, - { - kind: 'local', - cwd: 'C:\\repo' - } - ) - - expect(result).toMatchObject({ - success: false, - error: - "C:/tools/agent.cmd runs through a Windows batch script that cannot take the multi-line prompt as an argument. Point Settings at the agent's executable, or use a custom command without {prompt} so Orca sends the prompt on stdin." - }) - expect(spawnMock).not.toHaveBeenCalled() - }) - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation-regression.test.ts b/src/main/text-generation/commit-message-text-generation-regression.test.ts deleted file mode 100644 index 89193ab9bd3..00000000000 --- a/src/main/text-generation/commit-message-text-generation-regression.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { generateCommitMessageFromContext } from './commit-message-text-generation' - -describe('commit-message generation regressions', () => { - it('renders the complete commit policy before handing execution to the owning host', async () => { - let prompt = '' - let operation = '' - const result = await generateCommitMessageFromContext( - { - branch: 'feature/policy', - stagedSummary: 'M src/policy.ts', - stagedPatch: '+preserve host scope', - linkedIssue: 73 - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent', - commandInputTemplate: - '{basePrompt}\n\nBranch: {branch}\nFiles: {stagedFiles}\nPatch: {stagedPatch}\nIssue: {linkedIssue}' - }, - { - kind: 'remote', - cwd: '/remote/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan, _cwd, _timeout, generationOperation) => { - prompt = plan.stdinPayload ?? '' - operation = generationOperation - return { - stdout: 'Preserve source-control policy\n', - stderr: '', - exitCode: 0, - timedOut: false - } - } - } - ) - - expect(operation).toBe('commit-message') - expect(prompt).toContain('Branch: feature/policy') - expect(prompt).toContain('Files: M src/policy.ts') - expect(prompt).toContain('Patch: +preserve host scope') - expect(prompt).toContain('Issue: 73') - expect(prompt).not.toMatch(/\{(?:branch|stagedFiles|stagedPatch|linkedIssue)\}/) - expect(result).toEqual({ - success: true, - message: 'Preserve source-control policy', - agentLabel: 'agent' - }) - }) - - it('keeps bounded diagnostic captures out of commit-message results', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M src/policy.ts', - stagedPatch: '+change' - }, - { agentId: 'custom', model: '', customAgentCommand: 'agent' }, - { - kind: 'remote', - cwd: '/remote/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: 'prompt echoed from /Users/private/source/repo', - stderr: 'failed reading /Users/private/source/repo/.env', - exitCode: 1, - timedOut: false - }) - } - ) - - expect(result).toMatchObject({ - success: false, - error: 'agent CLI command failed with code 1: failed reading [path]', - canceled: undefined - }) - expect(JSON.stringify(result)).not.toContain('/Users/private') - expect(result).not.toHaveProperty('failureOutput') - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts b/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts deleted file mode 100644 index 6cb496d90e5..00000000000 --- a/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { generateCommitMessageFromContext } from './commit-message-text-generation' - -describe('generateCommitMessageFromContext', () => { - it('uses a prepared remote execution plan instead of running git on the remote side', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent --message {prompt}' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan, cwd, timeoutMs) => { - expect(cwd).toBe('/repo') - expect(timeoutMs).toBe(60_000) - expect(plan.binary).toBe('agent') - expect(plan.args).toHaveLength(2) - expect(plan.args[0]).toBe('--message') - expect(plan.args[1]).toContain('Staged files:\nM\tREADME.md') - return { - stdout: 'Add README note.\n', - stderr: '', - exitCode: 0, - timedOut: false - } - } - } - ) - - expect(result).toEqual({ - success: true, - message: 'Add README note', - agentLabel: 'agent' - }) - }) - - it('sanitizes remote execution transport failures', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => { - throw new Error('relay disconnected while reading /secret/repo') - } - } - ) - - expect(result).toEqual({ - success: false, - error: - 'agent could not be reached on the remote PATH. Try again after the SSH connection recovers.' - }) - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation.ts b/src/main/text-generation/commit-message-text-generation.ts index 6e85a41e920..ee8eebd78e8 100644 --- a/src/main/text-generation/commit-message-text-generation.ts +++ b/src/main/text-generation/commit-message-text-generation.ts @@ -3,7 +3,7 @@ import type { BranchNameWorkContext } from '../../shared/source-control/ai/namin import type { ConversationNameContext } from '../../shared/source-control/ai/generation/conversation-name-generation' import type { CommitMessageDraftContext } from '../../shared/source-control/ai/generation/commit-message-generation' import { LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../shared/source-control/ai/generation/commit-message-host-key' -import type { CommandTemplateBackslash } from '../../shared/source-control/ai/generation/commit-message-prompt' + import type { GeneratedPullRequestFields, PullRequestDraftContext @@ -18,51 +18,33 @@ import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import { discoverModelsLocal, type CommitMessageModelDiscoveryLocalOptions -} from './commit-message-model-discovery' -import { discoverModelsWithHostCache } from './model-discovery-host-cache' -import { spawnSourceControlAgent } from './source-control-agent-launch' -import { generateConversationName } from './conversation-name-generation-request' -import { cancelLocalGeneration } from './source-control-generation-lanes' +} from './models/commit-message-model-discovery' +import { discoverModelsWithHostCache } from './models/model-discovery-host-cache' +import { spawnSourceControlAgent } from './execution/source-control-agent-launch' +import { generateConversationName } from './requests/conversation-name-generation-request' +import { cancelLocalGeneration } from './execution/source-control-generation-lanes' +import { commandBackslashMode } from './agent-generation-request' import { - commandBackslashMode as resolveCommandBackslashMode, generateBranchName, generateCommitMessage, - generatePullRequestFields, - trimGeneratedCommitMessage as trimCommitMessage -} from './source-control-text-generation-requests' + generatePullRequestFields +} from './requests/source-control-text-generation-requests' import type { CommitMessageGenerationTarget, DiscoverCommitMessageModelsResult, GenerateBranchNameResult, GenerateConversationNameResult, GenerateCommitMessageResult, - GeneratePullRequestFieldsResult as GenericGeneratePullRequestFieldsResult, - RemoteCommitMessageExecResult, - TextGenerationOperation + GeneratePullRequestFieldsResult as GenericGeneratePullRequestFieldsResult } from './source-control-text-generation-types' -export type GenerateCommitMessageParams = ResolvedSourceControlAiGenerationParams -export type { - CommitMessageGenerationTarget, - CommitMessageModelDiscoveryLocalOptions, - DiscoverCommitMessageModelsResult, - GenerateBranchNameResult, - GenerateConversationNameResult, - GenerateCommitMessageResult, - RemoteCommitMessageExecResult, - TextGenerationOperation -} export type GeneratePullRequestFieldsResult = GenericGeneratePullRequestFieldsResult type ResolveCommitMessageSettingsResult = - | { ok: true; params: GenerateCommitMessageParams } + | { ok: true; params: ResolvedSourceControlAiGenerationParams } | ({ ok: false } & TextGenerationFailureFields) -export function trimGeneratedCommitMessage(message: string): string { - return trimCommitMessage(message) -} - export function resolveCommitMessageSettings( settings: Parameters[0]['settings'], discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY, @@ -78,22 +60,6 @@ export function resolveCommitMessageSettings( return resolved.ok ? { ok: true, params: resolved.value.params } : resolved } -export function resolveTextGenerationParams( - settings: Parameters[0]['settings'], - discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY, - operation: AiTextOperation = 'commitMessage', - repo?: Pick | null -): ResolveCommitMessageSettingsResult { - return resolveCommitMessageSettings(settings, discoveryHostKey, operation, repo) -} - -export function commandBackslashMode( - target: CommitMessageGenerationTarget, - platform: NodeJS.Platform = process.platform -): CommandTemplateBackslash { - return resolveCommandBackslashMode(target, platform) -} - export function discoverCommitMessageModelsLocal( agentId: TuiAgent, env: NodeJS.ProcessEnv | undefined, @@ -126,7 +92,7 @@ export function cancelGeneratePullRequestFieldsLocal(cwd: string): void { export function generateCommitMessageFromContext( context: CommitMessageDraftContext, - params: GenerateCommitMessageParams, + params: ResolvedSourceControlAiGenerationParams, target: CommitMessageGenerationTarget ): Promise { return generateCommitMessage({ context, params, target, spawnAgent: spawnSourceControlAgent }) @@ -134,7 +100,7 @@ export function generateCommitMessageFromContext( export function generatePullRequestFieldsFromContext( context: PullRequestDraftContext, - params: GenerateCommitMessageParams, + params: ResolvedSourceControlAiGenerationParams, target: CommitMessageGenerationTarget ): Promise { return generatePullRequestFields({ context, params, target, spawnAgent: spawnSourceControlAgent }) @@ -142,7 +108,7 @@ export function generatePullRequestFieldsFromContext( export function generateBranchNameFromContext( context: BranchNameWorkContext, - params: GenerateCommitMessageParams, + params: ResolvedSourceControlAiGenerationParams, target: CommitMessageGenerationTarget ): Promise { return generateBranchName({ context, params, target, spawnAgent: spawnSourceControlAgent }) @@ -150,7 +116,7 @@ export function generateBranchNameFromContext( export function generateConversationNameFromContext( context: ConversationNameContext, - params: GenerateCommitMessageParams, + params: ResolvedSourceControlAiGenerationParams, target: CommitMessageGenerationTarget, shouldExecute?: () => boolean ): Promise { diff --git a/src/main/text-generation/conversation-name-generation-request.test.ts b/src/main/text-generation/conversation-name-generation-request.test.ts deleted file mode 100644 index d92a4052890..00000000000 --- a/src/main/text-generation/conversation-name-generation-request.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { - sourceShapedKimiOutput, - realKimiOccupiedOutput -} from '../../shared/__fixtures__/kimi-generation-source-shaped' -import { describe, expect, it, vi } from 'vitest' -import { createMockDiscoveryChild } from './commit-message-text-generation-test-harness' -import { generateConversationNameFromContext } from './commit-message-text-generation' -import { cancelLocalGeneration } from './source-control-generation-lanes' -import { generateConversationName } from './conversation-name-generation-request' -import type { SpawnedSourceControlAgentProcess } from './source-control-text-generation-types' - -describe('generateConversationName', () => { - it.each([ - [`Fix login ${'x'.repeat(5000)}`, `Name this: Fix login ${'x'.repeat(3990)}`], - [ - "Why quote 'This is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.'? Change it and update README.md.", - 'Change it and update README.md.' - ] - ])( - 'delivers bounded template input with a final naming restriction', - async (firstPrompt, body) => { - let prompt = '' - let operation = '' - const result = await generateConversationNameFromContext( - { firstPrompt }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent', - commandInputTemplate: 'Name this: {firstPrompt}' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan, cwd, timeoutMs, requestedOperation) => { - expect(cwd).toBe('/repo') - expect(timeoutMs).toBe(60_000) - prompt = plan.stdinPayload ?? '' - operation = requestedOperation - return { - stdout: 'draft\n# Title: "Fix login flow"\nExtra line', - stderr: '', - exitCode: 0, - timedOut: false - } - } - } - ) - expect(operation).toBe('conversation-name') - expect(prompt).toContain(body) - expect( - prompt.endsWith( - '\n\nThis is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.' - ) - ).toBe(true) - expect(result).toEqual({ success: true, name: 'Fix login flow', agentLabel: 'agent' }) - } - ) - - it('rejects empty output after sanitization', async () => { - const result = await generateConversationNameFromContext( - { firstPrompt: 'Fix login' }, - { agentId: 'custom', model: '', customAgentCommand: 'agent' }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: 'Title: ""', - stderr: '', - exitCode: 0, - timedOut: false - }) - } - ) - expect(result).toMatchObject({ - success: false, - error: 'Generated chat name was empty after sanitization.' - }) - }) - - it.each(['cancel', 'occupied'])('handles a local %s outcome', async (outcome) => { - const child = createMockDiscoveryChild() - const spawnAgent = vi.fn(() => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The test child implements every process member the generation lane reads. - return child as unknown as SpawnedSourceControlAgentProcess - }) - const pending = generateConversationName({ - context: { firstPrompt: 'Fix login' }, - params: - outcome === 'cancel' - ? { agentId: 'custom', model: '', customAgentCommand: 'agent' } - : { agentId: 'kimi', model: 'default' }, - target: { kind: 'local', cwd: '/repo' }, - spawnAgent - }) - await vi.waitFor(() => expect(spawnAgent).toHaveBeenCalledOnce()) - if (outcome === 'occupied') { - child.stdout.emit('data', Buffer.from(realKimiOccupiedOutput)) - child.emit('close', 4) - expect(await pending).toMatchObject({ - success: false, - error: expect.stringMatching(/Kimi.*active.*Stop.*exit.*try again/) - }) - return - } - cancelLocalGeneration('conversation-name', '/repo') - expect(await pending).toMatchObject({ success: false, canceled: true }) - }) - - it.each(['custom', 'kimi'] as const)('%s local title', async (agentId) => { - const child = createMockDiscoveryChild() - const spawnAgent = vi.fn(() => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The test child implements every process member the generation lane reads. - return child as unknown as SpawnedSourceControlAgentProcess - }) - const pending = generateConversationName({ - context: { firstPrompt: 'Fix login' }, - params: { agentId, model: agentId === 'kimi' ? 'default' : '', customAgentCommand: 'agent' }, - target: { kind: 'local', cwd: '/repo' }, - spawnAgent - }) - await vi.waitFor(() => expect(spawnAgent).toHaveBeenCalledOnce()) - child.stdout.emit( - 'data', - Buffer.from( - agentId === 'kimi' - ? sourceShapedKimiOutput('Title: "Fix login flow"') - : 'Title: "Fix login flow"\n' - ) - ) - child.emit('close', 0) - expect(await pending).toEqual({ - success: true, - name: 'Fix login flow', - agentLabel: agentId === 'kimi' ? 'Kimi' : 'agent' - }) - }) -}) diff --git a/src/main/text-generation/command-environment-process.test.ts b/src/main/text-generation/execution/command-environment-process.test.ts similarity index 98% rename from src/main/text-generation/command-environment-process.test.ts rename to src/main/text-generation/execution/command-environment-process.test.ts index 13ffb231212..19a49f2c792 100644 --- a/src/main/text-generation/command-environment-process.test.ts +++ b/src/main/text-generation/execution/command-environment-process.test.ts @@ -5,7 +5,7 @@ import { afterAll, describe, expect, it } from 'vitest' import { discoverCommitMessageModelsLocal, generateCommitMessageFromContext -} from './commit-message-text-generation' +} from '../commit-message-text-generation' const folder = mkdtempSync(join(tmpdir(), 'orca-command-env-')) const script = join(folder, 'agent.cjs') diff --git a/src/main/text-generation/commit-message-agent-environment.test.ts b/src/main/text-generation/execution/commit-message-agent-environment.test.ts similarity index 75% rename from src/main/text-generation/commit-message-agent-environment.test.ts rename to src/main/text-generation/execution/commit-message-agent-environment.test.ts index 827fca54aa2..1d1c243eb64 100644 --- a/src/main/text-generation/commit-message-agent-environment.test.ts +++ b/src/main/text-generation/execution/commit-message-agent-environment.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { prepareLocalCommitMessageAgentEnv } from './commit-message-agent-environment' -import { ManagedCodexHomeTemporarilyUnavailableError } from '../codex-accounts/host-codex-managed-home-ownership' +import '../../codex-accounts/managed-homes/host-codex-managed-home-ownership' const originalEnv = { ...process.env } const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') @@ -71,7 +71,6 @@ describe('prepareLocalCommitMessageAgentEnv', () => { ANTHROPIC_AUTH_TOKEN: 'chosen-token' } }) - expect(await prepareLocalCommitMessageAgentEnv('custom', undefined)).toEqual({ ok: true }) }) it('hydrates OpenCode config dir from shell startup files for headless generation', async () => { @@ -89,38 +88,7 @@ describe('prepareLocalCommitMessageAgentEnv', () => { }) }) - it('hydrates Pi agent dir from shell startup files for headless generation', async () => { - const home = makeHome() - delete process.env.PI_CODING_AGENT_DIR - writeFileSync(join(home, '.zshrc'), 'export PI_CODING_AGENT_DIR="$HOME/.config/pi-agent"\n') - - const result = await prepareLocalCommitMessageAgentEnv('pi', undefined) - - expect(result).toEqual({ - ok: true, - env: expect.objectContaining({ - PI_CODING_AGENT_DIR: `${home}/.config/pi-agent` - }) - }) - }) - // STA-4422: failed managed-home preparation must not fall through to the user's real account while UI shows a managed account. - it('fails commit generation instead of building a system-account env when the managed home is unreadable', async () => { - process.env.CODEX_HOME = '/home/me/.config/codex' - delete process.env.ORCA_CODEX_HOME - - const result = await prepareLocalCommitMessageAgentEnv('codex', { - prepareForCodexLaunch: () => { - throw new ManagedCodexHomeTemporarilyUnavailableError() - } - }) - - expect(result).toEqual({ - ok: false, - error: 'Failed to prepare the selected agent account for commit message generation.' - }) - expect(result).not.toHaveProperty('env') - }) it('strips a nested-Orca CODEX_HOME override when the launch resolves to the real home', async () => { process.env.CODEX_HOME = '/managed/runtime/home' diff --git a/src/main/text-generation/commit-message-agent-environment.ts b/src/main/text-generation/execution/commit-message-agent-environment.ts similarity index 93% rename from src/main/text-generation/commit-message-agent-environment.ts rename to src/main/text-generation/execution/commit-message-agent-environment.ts index 7ce44a57547..806dc0d4fed 100644 --- a/src/main/text-generation/commit-message-agent-environment.ts +++ b/src/main/text-generation/execution/commit-message-agent-environment.ts @@ -1,11 +1,11 @@ -import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' -import { applyClaudeEnvPatch } from '../claude-accounts/runtime-auth/environment' -import { readShellStartupEnvVar } from '../pty/shell-startup/shell-startup-env' -import { parseWslUncPath } from '../../shared/wsl-paths' +import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' +import { applyClaudeEnvPatch } from '../../claude-accounts/runtime-auth/environment' +import { readShellStartupEnvVar } from '../../pty/shell-startup/shell-startup-env' +import { parseWslUncPath } from '../../../shared/wsl-paths' import { processEnvWithoutAgentSession, stripInheritedAgentSessionEnv -} from '../../shared/agent-launch/startup/parent-agent-session-env' +} from '../../../shared/agent-launch/startup/parent-agent-session-env' export type CommitMessageAgentEnvironmentResolvers = { prepareForCodexLaunch?: ( diff --git a/src/main/text-generation/commit-message-text-generation-cancellation.test.ts b/src/main/text-generation/execution/commit-message-text-generation-cancellation.test.ts similarity index 97% rename from src/main/text-generation/commit-message-text-generation-cancellation.test.ts rename to src/main/text-generation/execution/commit-message-text-generation-cancellation.test.ts index 01e281c9a37..83133beb676 100644 --- a/src/main/text-generation/commit-message-text-generation-cancellation.test.ts +++ b/src/main/text-generation/execution/commit-message-text-generation-cancellation.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { cancelGenerateCommitMessageLocal, generateCommitMessageFromContext -} from './commit-message-text-generation' +} from '../commit-message-text-generation' import { createChildTerminationExpectation, createMockDiscoveryChild, @@ -16,7 +16,7 @@ const { terminateWindowsProcessTreeMock } = vi.hoisted(() => ({ terminateWindowsProcessTreeMock: vi.fn(async () => {}) })) -vi.mock('../pty/process-retirement/windows-process-tree-kill', () => ({ +vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({ terminateWindowsProcessTree: terminateWindowsProcessTreeMock })) diff --git a/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts b/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts new file mode 100644 index 00000000000..4206ed42778 --- /dev/null +++ b/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts @@ -0,0 +1,84 @@ +import { spawn } from 'node:child_process' +import type * as ChildProcess from 'node:child_process' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { generateCommitMessageFromContext } from '../commit-message-text-generation' +import { createChildTerminationExpectation } from './commit-message-text-generation-test-harness' + +const { terminateWindowsProcessTreeMock } = vi.hoisted(() => ({ + terminateWindowsProcessTreeMock: vi.fn(async () => {}) +})) + +vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({ + terminateWindowsProcessTree: terminateWindowsProcessTreeMock +})) + +vi.mock('child_process', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + spawn: vi.fn(actual.spawn) + } +}) + +const spawnMock = vi.mocked(spawn) + +const expectChildTerminated = createChildTerminationExpectation(terminateWindowsProcessTreeMock) + +// Fake Windows direct-child/taskkill paths here; source-control-local-process.test.ts covers supervised POSIX stop and managed-home lock release. +const hostPlatform = process.platform + +afterEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: hostPlatform }) + vi.unstubAllEnvs() +}) + +beforeEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + // Clear PATH so host agent installs cannot answer fake Windows lookups. + vi.stubEnv('PATH', '') + terminateWindowsProcessTreeMock.mockClear() + terminateWindowsProcessTreeMock.mockResolvedValue(undefined) + spawnMock.mockClear() +}) + +describe('generateCommitMessageFromContext on the Windows direct-child path', () => { + it('caps local agent output before buffering unbounded data', async () => { + const listeners = new Map void>() + const child = { + pid: 123, + kill: vi.fn(), + stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, + stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, + stdin: { end: vi.fn() }, + on: vi.fn((event, callback) => listeners.set(event, callback)) + } + spawnMock.mockReturnValue(child as never) + + const pending = generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'local', + cwd: '/repo' + } + ) + + listeners.get('stdout:data')?.(Buffer.alloc(4 * 1024 * 1024 + 1)) + listeners.get('close')?.(null) + + await expect(pending).resolves.toMatchObject({ + success: false, + error: + 'agent CLI command produced too much output. Check the agent CLI configuration and try again.' + }) + await expectChildTerminated(child) + }) +}) diff --git a/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts b/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts new file mode 100644 index 00000000000..1b7445c090c --- /dev/null +++ b/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' + +import { generateCommitMessageFromContext } from '../commit-message-text-generation' + +describe('generateCommitMessageFromContext', () => { + it('sanitizes remote execution transport failures', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => { + throw new Error('relay disconnected while reading /secret/repo') + } + } + ) + + expect(result).toEqual({ + success: false, + error: + 'agent could not be reached on the remote PATH. Try again after the SSH connection recovers.' + }) + }) +}) diff --git a/src/main/text-generation/commit-message-text-generation-test-harness.ts b/src/main/text-generation/execution/commit-message-text-generation-test-harness.ts similarity index 97% rename from src/main/text-generation/commit-message-text-generation-test-harness.ts rename to src/main/text-generation/execution/commit-message-text-generation-test-harness.ts index 948fb2e80c9..e9e923fa3ae 100644 --- a/src/main/text-generation/commit-message-text-generation-test-harness.ts +++ b/src/main/text-generation/execution/commit-message-text-generation-test-harness.ts @@ -1,6 +1,6 @@ import { ChildProcess } from 'node:child_process' import { PassThrough } from 'node:stream' -import { isProviderRecord } from '../provider-process/provider-json-record' +import { isProviderRecord } from '../../provider-process/provider-json-record' import { expect, vi } from 'vitest' export type MockDiscoveryChild = ChildProcess & { diff --git a/src/main/text-generation/source-control-agent-cli-path.test.ts b/src/main/text-generation/execution/source-control-agent-cli-path.test.ts similarity index 92% rename from src/main/text-generation/source-control-agent-cli-path.test.ts rename to src/main/text-generation/execution/source-control-agent-cli-path.test.ts index 307d353d149..7735fd6c874 100644 --- a/src/main/text-generation/source-control-agent-cli-path.test.ts +++ b/src/main/text-generation/execution/source-control-agent-cli-path.test.ts @@ -2,8 +2,8 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { generateConversationNameFromContext } from './commit-message-text-generation' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { generateConversationNameFromContext } from '../commit-message-text-generation' const homes: string[] = [] @@ -47,8 +47,7 @@ describe.runIf(process.platform !== 'win32')('chat naming CLI discovery', () => it.each([ ['./node_modules/.bin:EMPTY', 'node_modules/.bin'], - [':EMPTY', '.'], - ['EMPTY:', '.'] + [':EMPTY', '.'] ])('resolves recipe PATH %s from the workspace before global installs', async (path, folder) => { const home = mkdtempSync(join(tmpdir(), 'orca-naming-recipe-path-')) homes.push(home) diff --git a/src/main/text-generation/source-control-agent-hook-isolation.test.ts b/src/main/text-generation/execution/source-control-agent-hook-isolation.test.ts similarity index 100% rename from src/main/text-generation/source-control-agent-hook-isolation.test.ts rename to src/main/text-generation/execution/source-control-agent-hook-isolation.test.ts diff --git a/src/main/text-generation/source-control-agent-launch.ts b/src/main/text-generation/execution/source-control-agent-launch.ts similarity index 83% rename from src/main/text-generation/source-control-agent-launch.ts rename to src/main/text-generation/execution/source-control-agent-launch.ts index 4f257cb93a2..ac9c59a2e74 100644 --- a/src/main/text-generation/source-control-agent-launch.ts +++ b/src/main/text-generation/execution/source-control-agent-launch.ts @@ -1,18 +1,20 @@ -import { wslDistroForCommand } from '../../shared/wsl-paths' +import { wslDistroForCommand } from '../../../shared/wsl-paths' import { spawnProcess } from '@orca/process-host' -import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { ORCA_AGENT_HOOKS_DISABLED_ENV } from '../../shared/agent-hook-listener/transport/agent-hook-suppression-env' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { resolveCliCommand } from '../codex-cli/command' -import { wslAwareSpawn } from '../git/command-runner/host-routing/wsl-aware-spawn' -import { AGENT_PANE_HOOK_ENV_KEYS } from '../ipc/pty/host-env/spawn-env-keys' -import { processEnvWithoutAgentSession } from '../../shared/agent-launch/startup/parent-agent-session-env' +import { + withCliRuntimeOnPath, + resolveCliCommand +} from '../../../shared/node-cli-command-resolution' +import { ORCA_AGENT_HOOKS_DISABLED_ENV } from '../../../shared/agent-hook-listener/transport/agent-hook-suppression-env' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { wslAwareSpawn } from '../../git/command-runner/host-routing/wsl-aware-spawn' +import { AGENT_PANE_HOOK_ENV_KEYS } from '../../ipc/pty/host-env/spawn-env-keys' +import { processEnvWithoutAgentSession } from '../../../shared/agent-launch/startup/parent-agent-session-env' import { spawnSupervisedAgent } from './source-control-supervised-agent-spawn' import type { SourceControlAgentSpawnInput, SpawnedSourceControlAgentProcess, SpawnSourceControlAgent -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' const WSL_LAUNCHER_ENV_KEYS = [ 'ComSpec', diff --git a/src/main/text-generation/execution/source-control-agent-termination.ts b/src/main/text-generation/execution/source-control-agent-termination.ts new file mode 100644 index 00000000000..d8d89ebbf1d --- /dev/null +++ b/src/main/text-generation/execution/source-control-agent-termination.ts @@ -0,0 +1,27 @@ +import { stopSupervisedChildProcess } from '../../provider-process/supervised-child-process-stop' +import { terminateWindowsProcessTree } from '../../pty/process-retirement/windows-process-tree-kill' +import type { SpawnedSourceControlAgentProcess } from '../source-control-text-generation-types' + +export const SOURCE_CONTROL_KILL_SITE = 'source-control-text-generation' + +export async function killSourceControlAgentProcess( + child: SpawnedSourceControlAgentProcess +): Promise { + const pid = child.pid + if (!pid) { + return + } + if (child.supervised) { + await stopSupervisedChildProcess(child, { site: SOURCE_CONTROL_KILL_SITE }) + return + } + if (process.platform === 'win32') { + // Tree-walk refusal must not release the home lock having killed nothing; root handle kill cannot hit a recycled PID. + await terminateWindowsProcessTree(pid, { site: SOURCE_CONTROL_KILL_SITE }) + } + try { + child.kill('SIGKILL') + } catch { + // The process may exit between the PID check and kill. + } +} diff --git a/src/main/text-generation/source-control-command-line-budget.ts b/src/main/text-generation/execution/source-control-command-line-budget.ts similarity index 80% rename from src/main/text-generation/source-control-command-line-budget.ts rename to src/main/text-generation/execution/source-control-command-line-budget.ts index 35c3b42c461..9b93330861c 100644 --- a/src/main/text-generation/source-control-command-line-budget.ts +++ b/src/main/text-generation/execution/source-control-command-line-budget.ts @@ -1,9 +1,12 @@ import { textGenerationFailure, type TextGenerationFailureFields -} from '../../shared/text-generation-failure-copy' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { commandLineLength, MAX_COMMAND_LINE_CHARS } from '../../shared/windows-command-line-budget' +} from '../../../shared/text-generation-failure-copy' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { + commandLineLength, + MAX_COMMAND_LINE_CHARS +} from '../../../shared/windows-command-line-budget' // Linux caps each argv entry in bytes (128KiB on 4KiB pages), before total argv capacity; reserve headroom for single-prompt arguments. const LINUX_SINGLE_ARGUMENT_BYTE_BUDGET = 120 * 1024 diff --git a/src/main/text-generation/execution/source-control-generation-lanes.ts b/src/main/text-generation/execution/source-control-generation-lanes.ts new file mode 100644 index 00000000000..60adb2f35de --- /dev/null +++ b/src/main/text-generation/execution/source-control-generation-lanes.ts @@ -0,0 +1,31 @@ +import type { TextGenerationOperation } from '../source-control-text-generation-types' + +const cancelTokensByLane = new Map void>() + +/** `laneId` separates runs that share an operation and cwd, so canceling one never reaches another. */ +export function localGenerationLaneKey( + operation: TextGenerationOperation, + cwd: string, + laneId?: string +): string { + const key = `${operation}:local:${cwd}` + return laneId ? `${key}:${laneId}` : key +} + +export function cancelLocalGeneration( + operation: TextGenerationOperation, + cwd: string, + laneId?: string +): void { + cancelTokensByLane.get(localGenerationLaneKey(operation, cwd, laneId))?.() +} + +export function setLocalGenerationCancelToken(laneKey: string, cancel: () => void): void { + cancelTokensByLane.set(laneKey, cancel) +} + +export function clearLocalGenerationCancelToken(laneKey: string, cancel: () => void): void { + if (cancelTokensByLane.get(laneKey) === cancel) { + cancelTokensByLane.delete(laneKey) + } +} diff --git a/src/main/text-generation/source-control-generation-limits.ts b/src/main/text-generation/execution/source-control-generation-limits.ts similarity index 100% rename from src/main/text-generation/source-control-generation-limits.ts rename to src/main/text-generation/execution/source-control-generation-limits.ts diff --git a/src/main/text-generation/source-control-local-generation.ts b/src/main/text-generation/execution/source-control-local-generation.ts similarity index 91% rename from src/main/text-generation/source-control-local-generation.ts rename to src/main/text-generation/execution/source-control-local-generation.ts index 0b96407a53d..19d517c604f 100644 --- a/src/main/text-generation/source-control-local-generation.ts +++ b/src/main/text-generation/execution/source-control-local-generation.ts @@ -1,26 +1,26 @@ -import { wslDistroForCommand } from '../../shared/wsl-paths' -import { mergeCommandEnvironment } from '../../shared/command-environment' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +import { wslDistroForCommand } from '../../../shared/wsl-paths' +import { mergeCommandEnvironment } from '../../../shared/command-environment' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' import { resolveCodexHomeProcessLockKeyForSpawnEnv, withCodexHomeProcessLock -} from '../codex-cli/codex-home-process-lock' +} from '../../codex-cli/codex-home-process-lock' import { clearLocalGenerationCancelToken, localGenerationLaneKey, setLocalGenerationCancelToken } from './source-control-generation-lanes' import { runLocalSourceControlPlan } from './source-control-local-process' -import { prepareSourceControlReadOnlyPlan } from './source-control-read-only-policy' +import { prepareSourceControlReadOnlyPlan } from '../policies/source-control-read-only-policy' import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' -import { textGenerationFailure } from '../../shared/text-generation-failure-copy' +import { textGenerationFailure } from '../../../shared/text-generation-failure-copy' import type { InternalTextGenerationResult, LocalGenerationTarget, LocalProcessExecution, SpawnSourceControlAgent, TextGenerationOperation -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' export function runLocalPlanForAgent(input: { agentId: string @@ -50,6 +50,7 @@ export function runLocalPlanForAgent(input: { cwd: input.target.cwd, env: wslDistro ? input.target.env : target.env, operation: input.operation, + laneId: input.target.laneId, wslDistro, spawnAgent: input.spawnAgent, timeoutMs @@ -60,7 +61,7 @@ export function runLocalPlanForAgent(input: { const deadlineAt = Date.now() + SOURCE_CONTROL_GENERATION_TIMEOUT_MS const deadline = AbortSignal.timeout(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) const signal = AbortSignal.any([canceled.signal, deadline]) - const lane = localGenerationLaneKey(input.operation, input.target.cwd) + const lane = localGenerationLaneKey(input.operation, input.target.cwd, input.target.laneId) const failure = (): InternalTextGenerationResult => canceled.signal.aborted || input.shouldExecute?.() === false ? { success: false, error: 'Generation canceled.', canceled: true } @@ -149,7 +150,7 @@ function runCodexLocalPlanUnderHomeLock( commandEnv?: Record, awaitSettlement = false ): Promise { - const laneKey = localGenerationLaneKey(operation, target.cwd) + const laneKey = localGenerationLaneKey(operation, target.cwd, target.laneId) let canceledWhileQueued = false let publishResult!: (result: InternalTextGenerationResult) => void let rejectResult!: (error: unknown) => void diff --git a/src/main/text-generation/source-control-local-process.test.ts b/src/main/text-generation/execution/source-control-local-process.test.ts similarity index 94% rename from src/main/text-generation/source-control-local-process.test.ts rename to src/main/text-generation/execution/source-control-local-process.test.ts index 28174bd29e6..de2b0e3bd9f 100644 --- a/src/main/text-generation/source-control-local-process.test.ts +++ b/src/main/text-generation/execution/source-control-local-process.test.ts @@ -3,16 +3,16 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { cancelGenerateCommitMessageLocal } from './commit-message-text-generation' +import { cancelGenerateCommitMessageLocal } from '../commit-message-text-generation' import { spawnSourceControlAgent } from './source-control-agent-launch' -import { generateCommitMessage } from './source-control-text-generation-requests' +import { generateCommitMessage } from '../requests/source-control-text-generation-requests' const { terminateTreeMock } = vi.hoisted(() => ({ terminateTreeMock: vi.fn(async () => true) })) -vi.mock('../provider-process/provider-process-teardown', () => ({ +vi.mock('../../provider-process/provider-process-teardown', () => ({ terminateProviderProcessTree: terminateTreeMock })) diff --git a/src/main/text-generation/source-control-local-process.ts b/src/main/text-generation/execution/source-control-local-process.ts similarity index 90% rename from src/main/text-generation/source-control-local-process.ts rename to src/main/text-generation/execution/source-control-local-process.ts index fe75e880b9d..c2f9b18ff8c 100644 --- a/src/main/text-generation/source-control-local-process.ts +++ b/src/main/text-generation/execution/source-control-local-process.ts @@ -1,18 +1,17 @@ -import { textGenerationFailure } from '../../shared/text-generation-failure-copy' +import { textGenerationFailure } from '../../../shared/text-generation-failure-copy' import { killSourceControlAgentProcess } from './source-control-agent-termination' -import { wslDistroForCommand } from '../../shared/wsl-paths' -import { prepareWslPrompt, stageLocalPromptFiles } from './source-control-prompt-files' -import { producePromptRecords } from './source-control-prompt-producer' +import { wslDistroForCommand } from '../../../shared/wsl-paths' +import { prepareWslPrompt, stageLocalPromptFiles } from '../prompts/source-control-prompt-files' +import { producePromptRecords } from '../prompts/source-control-prompt-producer' import { argumentBudgetFailure } from './source-control-command-line-budget' -export { fitsLocalCommandLine } from './source-control-command-line-budget' -import { removeTree } from '../../shared/windows-transient-lock-removal' +import { removeTree } from '../../../shared/windows-transient-lock-removal' import { WindowsCmdLineBreakError } from '@orca/process-host/windows-command-line' -import { WindowsCommandLineBudgetError } from '../../shared/windows-command-line-budget' -import { supervisedProviderSpawnFailure } from '../provider-process/provider-spawn-failure-report' +import { WindowsCommandLineBudgetError } from '../../../shared/windows-command-line-budget' +import { supervisedProviderSpawnFailure } from '../../provider-process/provider-spawn-failure-report' import { finalizeFromAgentOutput, userFacingUnsafeWindowsBatchArgs -} from './source-control-agent-failure' +} from '../failures/source-control-agent-failure' import { clearLocalGenerationCancelToken, localGenerationLaneKey, @@ -27,15 +26,13 @@ import type { LocalProcessExecution, SpawnedSourceControlAgentProcess, LocalSourceControlPlanInput -} from './source-control-text-generation-types' - -export * from './source-control-agent-termination' +} from '../source-control-text-generation-types' export function runLocalSourceControlPlan( input: LocalSourceControlPlanInput ): LocalProcessExecution { let { plan } = input - const { cwd, operation } = input + const { cwd, operation, laneId } = input const distro = plan.promptFile || plan.taskFiles?.length ? wslDistroForCommand(cwd, input.wslDistro) : null const guest = distro ? prepareWslPrompt(plan, distro) : undefined @@ -111,7 +108,7 @@ export function runLocalSourceControlPlan( let outputLimitExceeded = false let settled = false let canceledByUser = false - const laneKey = localGenerationLaneKey(operation, cwd) + const laneKey = localGenerationLaneKey(operation, cwd, laneId) let timer: ReturnType | null = null let terminal = false let terminationComplete: Promise | null = null @@ -238,8 +235,7 @@ export function runLocalSourceControlPlan( stderr, label: plan.label, outputFormat: plan.outputFormat, - operation, - includeStdoutDetail: operation !== 'branch-name' && operation !== 'conversation-name' + operation }) ) } diff --git a/src/main/text-generation/source-control-remote-generation.ts b/src/main/text-generation/execution/source-control-remote-generation.ts similarity index 82% rename from src/main/text-generation/source-control-remote-generation.ts rename to src/main/text-generation/execution/source-control-remote-generation.ts index 6f734710f11..e4c67ece744 100644 --- a/src/main/text-generation/source-control-remote-generation.ts +++ b/src/main/text-generation/execution/source-control-remote-generation.ts @@ -1,17 +1,17 @@ -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { isSshRequestOutcomeUnverifiable } from '../ssh/protocol/ssh-channel-multiplexer' -import { WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR } from '../../shared/windows-batch-spawn' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { isSshRequestOutcomeUnverifiable } from '../../ssh/protocol/ssh-channel-multiplexer' +import { WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR } from '../../../shared/windows-batch-spawn' import { finalizeFromAgentOutput, userFacingUnsafeWindowsBatchArgs -} from './source-control-agent-failure' +} from '../failures/source-control-agent-failure' import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' import type { InternalTextGenerationResult, RemoteCommitMessageExecResult, RemoteGenerationTarget, TextGenerationOperation -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' export async function runRemoteSourceControlPlan(input: { plan: CommitMessagePlan @@ -70,7 +70,6 @@ export async function runRemoteSourceControlPlan(input: { label: plan.label, outputFormat: plan.outputFormat, operation, - includeLocalMacDnsHint: false, - includeStdoutDetail: operation !== 'branch-name' && operation !== 'conversation-name' + includeLocalMacDnsHint: false }) } diff --git a/src/main/text-generation/source-control-supervised-agent-spawn.ts b/src/main/text-generation/execution/source-control-supervised-agent-spawn.ts similarity index 75% rename from src/main/text-generation/source-control-supervised-agent-spawn.ts rename to src/main/text-generation/execution/source-control-supervised-agent-spawn.ts index 70132c52640..10ae41e65b6 100644 --- a/src/main/text-generation/source-control-supervised-agent-spawn.ts +++ b/src/main/text-generation/execution/source-control-supervised-agent-spawn.ts @@ -1,14 +1,17 @@ import { spawnProcess } from '@orca/process-host' -import { pathEnvRelativeTo, withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { resolveGuestNativeAgentCommand } from '../codex-cli/command' -import { createProviderSpawnSpec } from '../provider-process/provider-process-supervisor' -import { guardSupervisedProviderGroup } from '../provider-process/provider-group-orphan-guard' +import { + pathEnvRelativeTo, + withCliRuntimeOnPath +} from '../../../shared/node-cli-command-resolution' +import { resolveGuestNativeAgentCommand } from '../../codex-cli/command' +import { createProviderSpawnSpec } from '../../provider-process/provider-process-supervisor' +import { guardSupervisedProviderGroup } from '../../provider-process/provider-group-orphan-guard' import { SOURCE_CONTROL_KILL_SITE } from './source-control-agent-termination' -import { guestNativeSpawnEnv } from '../ipc/wsl-guest-windows-drive-path' +import { guestNativeSpawnEnv } from '../../ipc/wsl-guest-windows-drive-path' import type { SourceControlAgentSpawnInput, SpawnedSourceControlAgentProcess -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' // Supervisor owns the agent group so parent quit/death still stops generation. export function spawnSupervisedAgent( diff --git a/src/main/text-generation/execution/source-control-wsl-launch.test.ts b/src/main/text-generation/execution/source-control-wsl-launch.test.ts new file mode 100644 index 00000000000..3a9e2c60713 --- /dev/null +++ b/src/main/text-generation/execution/source-control-wsl-launch.test.ts @@ -0,0 +1,105 @@ +import type * as ChildProcess from 'node:child_process' +import { mkdtempSync, writeFileSync, realpathSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi, afterEach } from 'vitest' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import '../../../shared/windows-command-line-budget' +import { withPlatform } from './commit-message-text-generation-test-harness' +import { spawnSourceControlAgent } from './source-control-agent-launch' +import './source-control-local-generation' + +const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) +vi.mock('node:child_process', async (original) => { + const actual = await original() + spawnMock.mockImplementation(actual.spawn) + return { ...actual, spawn: spawnMock } +}) +vi.mock('../../wsl/discovery/wsl-background-distro-gate', () => ({ + noteWslDistroLaunched: vi.fn() +})) +const nativeSpawn = (await vi.importActual('node:child_process')).spawn +afterEach(() => { + spawnMock.mockReset().mockImplementation(nativeSpawn) +}) + +it.skipIf(process.platform === 'win32')( + 'clears profile-restored hook identity after login while preserving shell function commands', + async () => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), 'orca-wsl-hook-isolation-'))) + const profile = join(directory, 'rc') + const shell = join(directory, 'bash') + const reader = join(directory, 'reader.cjs') + writeFileSync( + shell, + `#!/bin/sh\nexec /bin/bash --noprofile --rcfile ${quotePosixShell(profile)} -ic "$2"\n`, + { mode: 0o700 } + ) + writeFileSync( + join(directory, 'getent'), + `#!/bin/sh\nprintf '%s\\n' ${quotePosixShell(`user:x:1:1:User:${directory}:${shell}`)}\n`, + { mode: 0o700 } + ) + writeFileSync( + profile, + `export ORCA_PANE_KEY=profile-pane ORCA_AGENT_PANE=profile-pane ORCA_AGENT_HOOK_PORT=54321 ORCA_AGENT_HOOKS_DISABLED=0 +export CODEX_HOME=profile-managed-home +review_agent() { ${quotePosixShell(process.execPath)} ${quotePosixShell(reader)} "$@"; } +` + ) + writeFileSync( + reader, + `console.log(JSON.stringify({ + pane: process.env.ORCA_PANE_KEY ?? null, + alias: process.env.ORCA_AGENT_PANE ?? null, + port: process.env.ORCA_AGENT_HOOK_PORT ?? null, + disabled: process.env.ORCA_AGENT_HOOKS_DISABLED, + home: process.env.CODEX_HOME, + args: process.argv.slice(2) +})) +` + ) + // Run the real guest login command locally; only replace the Windows executable boundary. + spawnMock.mockImplementationOnce((_program, args, options) => + nativeSpawn('/bin/sh', ['-c', args.at(-1)], options) + ) + try { + const child = withPlatform('win32', () => + spawnSourceControlAgent({ + binary: 'review_agent', + args: ['literal $HOME'], + wslDistro: 'Review', + env: { + ...process.env, + HOME: directory, + SHELL: shell, + PATH: `${directory}:${process.env.PATH}` + }, + stdinMode: 'pipe', + useCwdForNative: true + }) + ) + let stdout = '' + let stderr = '' + child.stdout?.on('data', (chunk) => (stdout += chunk)) + child.stderr?.on('data', (chunk) => (stderr += chunk)) + const closed = new Promise((resolve, reject) => { + child.on('error', reject) + child.on('close', resolve) + }) + child.stdin?.end() + expect(await closed, stderr).toBe(0) + expect(JSON.parse(stdout)).toEqual({ + pane: null, + alias: null, + port: null, + disabled: '1', + home: 'profile-managed-home', + args: ['literal $HOME'] + }) + } finally { + await rm(directory, { recursive: true, force: true }) + } + } +) diff --git a/src/main/text-generation/failures/agent-failure-output.test.ts b/src/main/text-generation/failures/agent-failure-output.test.ts new file mode 100644 index 00000000000..4a17870e634 --- /dev/null +++ b/src/main/text-generation/failures/agent-failure-output.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { + captureAgentGenerationFailureOutput, + formatAgentGenerationFailureOutputForDisplay +} from './agent-failure-output' + +const ESC = String.fromCharCode(27) +const BEL = String.fromCharCode(7) + +describe('captureAgentGenerationFailureOutput', () => { + it('bounds an oversized stream to its head and tail with an omission marker', () => { + const oversized = `${'h'.repeat(20_000)}${'m'.repeat(40_000)}${'t'.repeat(50_000)}` + const capture = captureAgentGenerationFailureOutput('Pi', 1, '', oversized) + const stderr = capture?.stderr ?? '' + expect(stderr.startsWith('h'.repeat(16 * 1024))).toBe(true) + expect(stderr.endsWith('t'.repeat(48 * 1024))).toBe(true) + expect(stderr).toContain('characters omitted') + expect(stderr.length).toBeLessThan(oversized.length) + }) +}) + +describe('formatAgentGenerationFailureOutputForDisplay', () => { + it('strips ANSI, OSC, and bidi-override characters while keeping line structure', () => { + const text = formatAgentGenerationFailureOutputForDisplay({ + label: 'Pi', + exitCode: 1, + stdout: '', + stderr: `${ESC}]0;title${BEL}${ESC}[91mline one${ESC}[0m\r\nsafe ${String.fromCharCode(0x202e)}evil${String.fromCharCode(0x202c)} tail\rline three` + }) + expect(text).toBe('Pi exited with code 1.\n\n[stderr]\nline one\nsafe evil tail\nline three') + }) + + it('keeps later diagnostics when an OSC sequence is unterminated', () => { + const text = formatAgentGenerationFailureOutputForDisplay({ + label: 'Pi', + exitCode: 1, + stdout: '', + stderr: `${ESC}]0;unfinished title\nNo API key found.\nUse /login to log in.` + }) + expect(text).toContain('No API key found.\nUse /login to log in.') + }) +}) diff --git a/src/main/text-generation/agent-failure-output.ts b/src/main/text-generation/failures/agent-failure-output.ts similarity index 94% rename from src/main/text-generation/agent-failure-output.ts rename to src/main/text-generation/failures/agent-failure-output.ts index 7b4e7f6c684..b68e578160e 100644 --- a/src/main/text-generation/agent-failure-output.ts +++ b/src/main/text-generation/failures/agent-failure-output.ts @@ -1,4 +1,4 @@ -import { stripAnsiControlSequences } from '../../shared/source-control/ai/generation/commit-message-agent-output' +import { stripAnsiControlSequences } from '../../../shared/source-control/ai/generation/commit-message-agent-output' /** Bounded failure output is display-on-demand only; never persist or sync it. */ export type AgentGenerationFailureOutput = { diff --git a/src/main/text-generation/commit-message-text-generation-failure-sanitization.test.ts b/src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts similarity index 87% rename from src/main/text-generation/commit-message-text-generation-failure-sanitization.test.ts rename to src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts index 37c7ddaa563..df1c71b8d18 100644 --- a/src/main/text-generation/commit-message-text-generation-failure-sanitization.test.ts +++ b/src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts @@ -1,38 +1,7 @@ import { describe, expect, it } from 'vitest' -import { generateCommitMessageFromContext } from './commit-message-text-generation' +import { generateCommitMessageFromContext } from '../commit-message-text-generation' describe('generateCommitMessageFromContext', () => { - it('exposes raw CLI failure output only after path sanitization', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: 'You are generating a single git commit message for /secret/repo', - stderr: 'raw failure output with /Users/thebr/My Repo/secret/file.ts', - exitCode: 1, - timedOut: false - }) - } - ) - - expect(result).toMatchObject({ - success: false, - error: 'agent CLI command failed with code 1: raw failure output with [path]' - }) - }) - it('formats nonzero exit failures with extracted sanitized CLI details', async () => { const result = await generateCommitMessageFromContext( { diff --git a/src/main/text-generation/copilot-unavailable-model-retry.ts b/src/main/text-generation/failures/copilot-unavailable-model-retry.ts similarity index 86% rename from src/main/text-generation/copilot-unavailable-model-retry.ts rename to src/main/text-generation/failures/copilot-unavailable-model-retry.ts index 65038935df2..9248d36ba65 100644 --- a/src/main/text-generation/copilot-unavailable-model-retry.ts +++ b/src/main/text-generation/failures/copilot-unavailable-model-retry.ts @@ -1,6 +1,6 @@ -import { findOptionOccurrence } from '../../shared/command-option-occurrence' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { escapeRegex } from '../../shared/string-utils' +import { findOptionOccurrence } from '../../../shared/command-option-occurrence' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { escapeRegex } from '../../../shared/string-utils' import type { AgentGenerationFailureOutput } from './agent-failure-output' const PROMPT_VALUE_OPTIONS = ['--prompt', '-p'] diff --git a/src/main/text-generation/failures/kimi-generation-failure.test.ts b/src/main/text-generation/failures/kimi-generation-failure.test.ts new file mode 100644 index 00000000000..46edc2093c9 --- /dev/null +++ b/src/main/text-generation/failures/kimi-generation-failure.test.ts @@ -0,0 +1,119 @@ +import { afterAll, expect, it, vi } from 'vitest' +import { + realKimiPrOutput, + realKimiOccupiedOutput, + sourceShapedKimiOutput +} from '../../../shared/__fixtures__/kimi-generation-source-shaped' +import type * as DnsDiagnosticModule from '../../network/macos-tailscale-dns-diagnostic' +import { finalizeFromAgentOutput } from './source-control-agent-failure' + +const log = vi.spyOn(console, 'error').mockImplementation(() => {}) +afterAll(() => log.mockRestore()) +vi.mock('../../network/macos-tailscale-dns-diagnostic', async (original) => { + const actual = await original() + return { + ...actual, + withMacTailscaleDnsHint: (message: string, detail?: string | null) => + actual.withMacTailscaleDnsHintForDiagnostic(message, detail, { + globalNameservers: ['100.100.100.100'] + }) + } +}) +const invalid = /Kimi returned output Orca couldn't read\. Try again\./ +const occupied = /Kimi.*active in another client.*Stop.*exit.*try again/ +const unknown = /^Kimi couldn't finish.*execution host.*check.*retrying/ +const earlier = sourceShapedKimiOutput('Earlier answer') +const run = (message: string) => `error: failed to run prompt: ${message}\nSee log: private-path` +const network = run('provider.connection_error: getaddrinfo ENOTFOUND private-host') +const agentOptions = + /^Kimi received conflicting or repeated agent options\. Keep a single --agent or --agent-file option in the generation recipe or CLI arguments, then retry\.$/ +const parser = + /^Kimi rejected an option or argument\. Correct the generation recipe or CLI arguments, then retry\.$/ +const delimiters = "private-x' argument '".repeat(12) + +// Source-shaped stderr forms come from the official 2.3.1 terminal error routes. +it.each([ + ['', occupied, realKimiOccupiedOutput, 4], + [run('unrelated private-prose'), occupied, `${earlier}\n${realKimiOccupiedOutput}`, 4], + [ + run('provider.auth_error: private-provider prose'), + /authenticate.*Sign in.*credentials.*retry/, + '{broken' + ], + [network, /connect.*network.*retry/], + [network, /connect.*network.*MagicDNS/, '', 1, true], + ...[ + "error: option '--agent ' cannot be used with option '--agent-file '", + "error: option '--agent-file ' argument 'private-b.md' is invalid. --agent-file may only be specified once.", + "error: option '--agent ' argument 'private-'other' is invalid. --agent may only be specified once." + ].map((stderr) => [stderr, agentOptions] as const), + ...[ + "error: option '--agent ' argument missing", + "error: unknown option '--private-flag'\n(Did you mean --plan?)", + "unknown command 'private-word'. See 'kimi --help'.", + "error: option '--agent-file ' argument 'private-value' is invalid. --agent may only be specified once.", + "error: option '--agent ' argument 'private-value' is invalid. provider.auth_error: private-prose", + "error: option '--private-flag' cannot be used with option '--private-other'" + ].map((stderr) => [stderr, parser] as const), + [run("unknown option '--private-flag'"), unknown, '{"type":"error","code":"unknown.code"}'], + [`error: option '${delimiters}tail`, unknown], + [`error: option '${delimiters}value' is invalid. provider.auth_error: private-prose`, parser], + ["hook narration error: unknown option '--private-flag'", unknown], + ['', /Kimi.*interrupted.*Try again/, '', null], + ['', invalid, realKimiOccupiedOutput, 0], + [ + run('provider.auth_error: private-prose'), + /Kimi returned an empty message\.$/, + sourceShapedKimiOutput(), + 0 + ], + ['', /"title":"Decode Kimi generation output.*\\n\\n/, realKimiPrOutput, 0], + ...[ + '{"role":', + 'NOTICE wrapper log', + '{"role":"assistant","content":42}', + '{"role":"assistant","tool_calls":"bad"}', + '{"role":"tool","content":"missing id"}' + ].map((bad) => ['', invalid, `${earlier}\n${bad}`, 0] as const) +] as const)('%s outcome', (stderr, meaning, stdout = '', code = 1, local: boolean = false) => { + const result = finalizeFromAgentOutput({ + stdout, + stderr, + code, + includeLocalMacDnsHint: local, + label: 'Kimi', + operation: 'commit-message', + outputFormat: 'kimi-stream-json' + }) + expect(result.success).toBe(stdout === realKimiPrOutput) + const text = result.success ? result.rawOutput : result.error + expect(text).toMatch(meaning) + expect(text).not.toMatch( + /private-|PRIVATE_ENV|CODE_SECRET|provider\.[a-z_]+|session\.occupied|unknown\.code|code [014]/ + ) + if (!local) { + expect(text).not.toContain('MagicDNS') + } + if (!result.success && (stdout || stderr)) { + expect(result.failureOutput).toEqual({ label: 'Kimi', exitCode: code, stdout, stderr }) + } +}) + +it('codes a diagnosed failure so clients can translate it, keeping the English error', () => { + const result = finalizeFromAgentOutput({ + stdout: '', + stderr: 'error: Cannot combine --prompt with --auto.', + code: 1, + includeLocalMacDnsHint: false, + label: 'Kimi', + operation: 'commit-message', + outputFormat: 'kimi-stream-json' + }) + expect(result).toMatchObject({ + success: false, + error: + 'Kimi received conflicting options: --prompt with --auto. Correct the generation recipe or CLI arguments before retrying.', + errorCode: 'kimiConflictingOptions', + errorParams: { option: '--prompt', otherOption: '--auto' } + }) +}) diff --git a/src/main/text-generation/kimi-generation-failure.ts b/src/main/text-generation/failures/kimi-generation-failure.ts similarity index 96% rename from src/main/text-generation/kimi-generation-failure.ts rename to src/main/text-generation/failures/kimi-generation-failure.ts index fd106d13dad..1ea8da564d2 100644 --- a/src/main/text-generation/kimi-generation-failure.ts +++ b/src/main/text-generation/failures/kimi-generation-failure.ts @@ -1,9 +1,9 @@ -import { stripAnsiControlSequences } from '../../shared/source-control/ai/generation/commit-message-agent-output' -import { withMacTailscaleDnsHint } from '../network/macos-tailscale-dns-diagnostic' +import { stripAnsiControlSequences } from '../../../shared/source-control/ai/generation/commit-message-agent-output' +import { withMacTailscaleDnsHint } from '../../network/macos-tailscale-dns-diagnostic' import { textGenerationFailure, type TextGenerationFailureFields -} from '../../shared/text-generation-failure-copy' +} from '../../../shared/text-generation-failure-copy' function emptyInputFailure(input: string): TextGenerationFailureFields | null { switch (input) { diff --git a/src/main/text-generation/source-control-agent-failure.ts b/src/main/text-generation/failures/source-control-agent-failure.ts similarity index 77% rename from src/main/text-generation/source-control-agent-failure.ts rename to src/main/text-generation/failures/source-control-agent-failure.ts index 6a0aa9397dd..6e718d745dc 100644 --- a/src/main/text-generation/source-control-agent-failure.ts +++ b/src/main/text-generation/failures/source-control-agent-failure.ts @@ -1,9 +1,9 @@ import { - cleanGeneratedCommitMessage, + cleanGeneratedText, excerptAgentFailureOutput, sanitizeAgentFailureDetail -} from '../../shared/source-control/ai/generation/commit-message-agent-output' -import { withMacTailscaleDnsHint } from '../network/macos-tailscale-dns-diagnostic' +} from '../../../shared/source-control/ai/generation/commit-message-agent-output' +import { withMacTailscaleDnsHint } from '../../network/macos-tailscale-dns-diagnostic' import { captureAgentGenerationFailureOutput, type AgentGenerationFailureOutput @@ -11,19 +11,31 @@ import { import type { InternalTextGenerationResult, TextGenerationOperation -} from './source-control-text-generation-types' -import { parseOpenCodeGenerationOutput } from '../../shared/opencode-generation-output' -import { parseAntigravityGenerationOutput } from '../../shared/antigravity-generation-stream' +} from '../source-control-text-generation-types' +import { parseOpenCodeGenerationOutput } from '../../../shared/opencode-generation-output' +import { parseAntigravityGenerationOutput } from '../../../shared/antigravity-generation-stream' import { findKimiGenerationFailure, parseKimiGenerationOutput -} from '../../shared/kimi-generation-output' +} from '../../../shared/kimi-generation-output' import { formatKimiGenerationFailure } from './kimi-generation-failure' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' import { textGenerationFailure, type TextGenerationFailureFields -} from '../../shared/text-generation-failure-copy' +} from '../../../shared/text-generation-failure-copy' + +// Their stdout is a name or the user's own dictated words, not a diagnostic worth keeping in the error. +const OPERATIONS_WITHOUT_STDOUT_DETAIL: ReadonlySet = new Set([ + 'branch-name', + 'conversation-name', + 'dictation-cleanup' +]) + +/** The agent's answer without CLI framing; dictated text keeps the lines and markers Git text drops. */ +export function cleanAgentAnswer(raw: string, operation: TextGenerationOperation): string { + return cleanGeneratedText(raw, operation === 'dictation-cleanup' ? 'prose' : 'git') +} type AgentCliFailureOptions = { includeLocalMacDnsHint?: boolean @@ -82,7 +94,8 @@ const EMPTY_RESULT_FAILURES = { const UNCODED_EMPTY_RESULT_NAMES = { 'branch-name': 'branch name', - 'conversation-name': 'chat name' + 'conversation-name': 'chat name', + 'dictation-cleanup': 'cleanup' } as const export function emptyResultFailure( @@ -90,7 +103,11 @@ export function emptyResultFailure( label: string, detail?: string | null ): TextGenerationFailureFields { - if (operation === 'branch-name' || operation === 'conversation-name') { + if ( + operation === 'branch-name' || + operation === 'conversation-name' || + operation === 'dictation-cleanup' + ) { // Background rename failures are stored as English rename errors, outside the coded result path. const name = UNCODED_EMPTY_RESULT_NAMES[operation] return { @@ -116,6 +133,11 @@ export function finalizeFromAgentOutput(args: { outputFormat?: CommitMessagePlan['outputFormat'] }): InternalTextGenerationResult { const { code, stdout, stderr, label } = args + const options = { + ...args, + includeStdoutDetail: + args.includeStdoutDetail ?? !OPERATIONS_WITHOUT_STDOUT_DETAIL.has(args.operation) + } const parsed = args.outputFormat === 'opencode-json' ? parseOpenCodeGenerationOutput(stdout) @@ -134,14 +156,14 @@ export function finalizeFromAgentOutput(args: { return { success: false, ...(args.outputFormat === 'kimi-stream-json' - ? formatKimiGenerationFailure(findKimiGenerationFailure(stdout), stderr, code, args) + ? formatKimiGenerationFailure(findKimiGenerationFailure(stdout), stderr, code, options) : agentCliFailure( label, stdout, // Orca's own parse failures (coded) say nothing about why the agent exited. parsed && !parsed.ok && parsed.errorCode === undefined ? parsed.error : stderr, code, - args + options )), failureOutput: captureFailureOutput(label, code, stdout, stderr) } @@ -158,7 +180,7 @@ export function finalizeFromAgentOutput(args: { failureOutput: captureFailureOutput(label, code, stdout, stderr) } } - const cleaned = cleanGeneratedCommitMessage(parsed?.ok ? parsed.text : stdout) + const cleaned = cleanAgentAnswer(parsed?.ok ? parsed.text : stdout, args.operation) if (cleaned) { return { success: true, rawOutput: cleaned, agentLabel: label } } diff --git a/src/main/text-generation/kimi-generation-failure.test.ts b/src/main/text-generation/kimi-generation-failure.test.ts deleted file mode 100644 index a888e6fee27..00000000000 --- a/src/main/text-generation/kimi-generation-failure.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { afterAll, expect, it, vi } from 'vitest' -import { - realKimiPrOutput, - realKimiOccupiedOutput, - sourceShapedKimiOutput -} from '../../shared/__fixtures__/kimi-generation-source-shaped' -import type * as DnsDiagnosticModule from '../network/macos-tailscale-dns-diagnostic' -import { finalizeFromAgentOutput } from './source-control-agent-failure' - -const log = vi.spyOn(console, 'error').mockImplementation(() => {}) -afterAll(() => log.mockRestore()) -vi.mock('../network/macos-tailscale-dns-diagnostic', async (original) => { - const actual = await original() - return { - ...actual, - withMacTailscaleDnsHint: (message: string, detail?: string | null) => - actual.withMacTailscaleDnsHintForDiagnostic(message, detail, { - globalNameservers: ['100.100.100.100'] - }) - } -}) -const invalid = /Kimi returned output Orca couldn't read\. Try again\./ -const occupied = /Kimi.*active in another client.*Stop.*exit.*try again/ -const unknown = /^Kimi couldn't finish.*execution host.*check.*retrying/ -const earlier = sourceShapedKimiOutput('Earlier answer') -const run = (message: string) => `error: failed to run prompt: ${message}\nSee log: private-path` -const network = run('provider.connection_error: getaddrinfo ENOTFOUND private-host') -const agentOptions = - /^Kimi received conflicting or repeated agent options\. Keep a single --agent or --agent-file option in the generation recipe or CLI arguments, then retry\.$/ -const credentials = /credentials.*execution host.*configure.*sign in/ -const parser = - /^Kimi rejected an option or argument\. Correct the generation recipe or CLI arguments, then retry\.$/ -const delimiters = "private-x' argument '".repeat(12) - -// Source-shaped stderr forms come from the official 2.3.1 terminal error routes. -it.each([ - ['', occupied, realKimiOccupiedOutput, 4], - [run('unrelated private-prose'), occupied, `${earlier}\n${realKimiOccupiedOutput}`, 4], - [run('Session "private-session" not found.'), /find.*session.*existing session.*new one/], - [ - run('Session "private-session" was created under a different directory.'), - /another directory.*Resume it there.*workspace/ - ], - [ - run('no provider configured; complete onboarding via /login or the providers endpoint'), - credentials - ], - [ - run( - 'Provider "private-provider" declares api_key_env = "PRIVATE_ENV" in config.toml, but the environment variable is not set or is empty.' - ), - /credential environment variable.*Set it.*execution host/ - ], - [ - run('model private-model does not resolve to a configured provider'), - /usable model.*configure or select/ - ], - [run('Prompt hook blocked the request.'), /hook blocked.*Review.*hooks.*retry/], - [run('Prompt turn ended with reason: cancelled'), /cancelled.*Try again/], - [ - run('provider.auth_error: private-provider prose'), - /authenticate.*Sign in.*credentials.*retry/, - '{broken' - ], - [run('provider.rate_limit: private-provider prose'), /limit.*Wait.*reduce/], - [run('Provider safety policy blocked the response.'), /blocked.*Revise.*prompt.*configuration/], - [run('context.overflow: private-provider prose'), /context.*Shorten.*new session/], - [run('config.invalid: private-provider prose'), /invalid configuration.*Check.*model.*provider/], - [network, /connect.*network.*retry/], - [network, /connect.*network.*MagicDNS/, '', 1, true], - ...[ - "error: option '--agent ' cannot be used with option '--agent-file '", - "error: option '--agent-file ' argument 'private-b.md' is invalid. --agent-file may only be specified once.", - "error: option '--agent ' argument 'private-'other' is invalid. --agent may only be specified once." - ].map((stderr) => [stderr, agentOptions] as const), - ...[ - "error: option '--agent ' argument missing", - "error: unknown option '--private-flag'\n(Did you mean --plan?)", - "unknown command 'private-word'. See 'kimi --help'.", - "error: option '--agent-file ' argument 'private-value' is invalid. --agent may only be specified once.", - "error: option '--agent ' argument 'private-value' is invalid. provider.auth_error: private-prose", - "error: option '--private-flag' cannot be used with option '--private-other'" - ].map((stderr) => [stderr, parser] as const), - [run("unknown option '--private-flag'"), unknown, '{"type":"error","code":"unknown.code"}'], - [`error: option '${delimiters}tail`, unknown], - [`error: option '${delimiters}value' is invalid. provider.auth_error: private-prose`, parser], - ['error: Login required\n\nmessage:\nprivate-prose\nSee log: private-path', credentials], - ['error: Prompt cannot be empty.', /empty prompt.*recipe.*CLI arguments/], - [ - 'error: Cannot combine --prompt with --auto.', - /conflicting.*--prompt.*--auto.*recipe.*arguments/ - ], - [ - 'error: Cannot combine --agent/--agent-file with --session/--continue: the agent is bound at session creation and the bound agent is restored automatically on resume.', - /cannot change the agent.*Remove.*override.*new session/ - ], - ['error: Cannot use --session without an id in prompt mode.', /session id.*recipe.*arguments/], - ["hook narration error: unknown option '--private-flag'", unknown], - ['', /Kimi.*interrupted.*Try again/, '', null], - ['', invalid, realKimiOccupiedOutput, 0], - [ - run('provider.auth_error: private-prose'), - /Kimi returned an empty message\.$/, - sourceShapedKimiOutput(), - 0 - ], - ['', /"title":"Decode Kimi generation output.*\\n\\n/, realKimiPrOutput, 0], - ...[ - '{"role":', - 'NOTICE wrapper log', - '{"role":"assistant","content":42}', - '{"role":"assistant","tool_calls":"bad"}', - '{"role":"tool","content":"missing id"}' - ].map((bad) => ['', invalid, `${earlier}\n${bad}`, 0] as const) -] as const)('%s outcome', (stderr, meaning, stdout = '', code = 1, local: boolean = false) => { - const result = finalizeFromAgentOutput({ - stdout, - stderr, - code, - includeLocalMacDnsHint: local, - label: 'Kimi', - operation: 'commit-message', - outputFormat: 'kimi-stream-json' - }) - expect(result.success).toBe(stdout === realKimiPrOutput) - const text = result.success ? result.rawOutput : result.error - expect(text).toMatch(meaning) - expect(text).not.toMatch( - /private-|PRIVATE_ENV|CODE_SECRET|provider\.[a-z_]+|session\.occupied|unknown\.code|code [014]/ - ) - if (!local) { - expect(text).not.toContain('MagicDNS') - } - if (!result.success && (stdout || stderr)) { - expect(result.failureOutput).toEqual({ label: 'Kimi', exitCode: code, stdout, stderr }) - } -}) - -it('codes a diagnosed failure so clients can translate it, keeping the English error', () => { - const result = finalizeFromAgentOutput({ - stdout: '', - stderr: 'error: Cannot combine --prompt with --auto.', - code: 1, - includeLocalMacDnsHint: false, - label: 'Kimi', - operation: 'commit-message', - outputFormat: 'kimi-stream-json' - }) - expect(result).toMatchObject({ - success: false, - error: - 'Kimi received conflicting options: --prompt with --auto. Correct the generation recipe or CLI arguments before retrying.', - errorCode: 'kimiConflictingOptions', - errorParams: { option: '--prompt', otherOption: '--auto' } - }) -}) diff --git a/src/main/text-generation/codex-model-list-discovery.ts b/src/main/text-generation/models/codex-model-list-discovery.ts similarity index 88% rename from src/main/text-generation/codex-model-list-discovery.ts rename to src/main/text-generation/models/codex-model-list-discovery.ts index 688de29c597..022045816ef 100644 --- a/src/main/text-generation/codex-model-list-discovery.ts +++ b/src/main/text-generation/models/codex-model-list-discovery.ts @@ -1,17 +1,17 @@ import { StringDecoder } from 'node:string_decoder' import type { Writable } from 'node:stream' -import type { AgentSessionModelOption } from '../../shared/agent-session/agent-session-wire' -import type { CommitMessageModel } from '../../shared/source-control/ai/generation/commit-message-agent-spec' -import { createIncrementalNdjsonFramer } from '../../shared/main-process-ndjson-framer' -import { createCodexAppServerRecordDispatcher } from '../codex/app-server/codex-app-server-record-dispatch' -import { isProviderRecord } from '../provider-process/provider-json-record' -import { listCodexModelPages } from '../codex/structured/catalog/codex-structured-model-catalog' -import type { AgentModelProbeSpec } from '../../shared/agent-model-probe-spec' +import type { AgentSessionModelOption } from '../../../shared/agent-session/agent-session-wire' +import type { CommitMessageModel } from '../../../shared/source-control/ai/generation/commit-message-agent-spec' +import { createIncrementalNdjsonFramer } from '../../../shared/main-process-ndjson-framer' +import { createCodexAppServerRecordDispatcher } from '../../codex/app-server/codex-app-server-record-dispatch' +import { isProviderRecord } from '../../provider-process/provider-json-record' +import { listCodexModelPages } from '../../codex/structured/catalog/codex-structured-model-catalog' +import type { AgentModelProbeSpec } from '../../../shared/agent-model-probe-spec' import { discoveredModelsResult } from './commit-message-model-discovery-policy' import type { DiscoverCommitMessageModelsResult, SpawnedSourceControlAgentProcess -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' const APP_SERVER_EXIT_GRACE_MS = 1_500 diff --git a/src/main/text-generation/commit-message-model-discovery-policy.ts b/src/main/text-generation/models/commit-message-model-discovery-policy.ts similarity index 79% rename from src/main/text-generation/commit-message-model-discovery-policy.ts rename to src/main/text-generation/models/commit-message-model-discovery-policy.ts index 1c4f8d4d5fa..4b0881dce3a 100644 --- a/src/main/text-generation/commit-message-model-discovery-policy.ts +++ b/src/main/text-generation/models/commit-message-model-discovery-policy.ts @@ -1,12 +1,12 @@ -import { buildClaudeModelListArgs } from '../../shared/claude-model-list-probe' -import type { CommitMessageModel } from '../../shared/source-control/ai/generation/commit-message-agent-spec' -import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../codex-cli/codex-read-only-app-server-args' -import type { CommandTemplateBackslash } from '../../shared/source-control/ai/generation/commit-message-prompt' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { planAgentBinary } from '../../shared/agent-launch/startup/agent-command-plan' -import type { AgentModelProbeSpec } from '../../shared/agent-model-probe-spec' -import { formatAgentCliFailureMessage } from './source-control-agent-failure' -import type { DiscoverCommitMessageModelsResult } from './source-control-text-generation-types' +import { buildClaudeModelListArgs } from '../../../shared/claude-model-list-probe' +import type { CommitMessageModel } from '../../../shared/source-control/ai/generation/commit-message-agent-spec' +import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../../codex-cli/codex-read-only-app-server-args' +import type { CommandTemplateBackslash } from '../../../shared/source-control/ai/generation/commit-message-prompt' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { planAgentBinary } from '../../../shared/agent-launch/startup/agent-command-plan' +import type { AgentModelProbeSpec } from '../../../shared/agent-model-probe-spec' +import { formatAgentCliFailureMessage } from '../failures/source-control-agent-failure' +import type { DiscoverCommitMessageModelsResult } from '../source-control-text-generation-types' export function staticModelDiscoveryResult( spec: AgentModelProbeSpec, diff --git a/src/main/text-generation/commit-message-model-discovery.ts b/src/main/text-generation/models/commit-message-model-discovery.ts similarity index 89% rename from src/main/text-generation/commit-message-model-discovery.ts rename to src/main/text-generation/models/commit-message-model-discovery.ts index 636320651e9..bac340513a0 100644 --- a/src/main/text-generation/commit-message-model-discovery.ts +++ b/src/main/text-generation/models/commit-message-model-discovery.ts @@ -1,18 +1,18 @@ -import { isMissingProviderExecutable } from '../provider-process/provider-executable-missing' -import { mergeCommandEnvironment } from '../../shared/command-environment' -import type { CommandTemplateBackslash } from '../../shared/source-control/ai/generation/commit-message-prompt' +import { isMissingProviderExecutable } from '../../provider-process/provider-executable-missing' +import { mergeCommandEnvironment } from '../../../shared/command-environment' +import type { CommandTemplateBackslash } from '../../../shared/source-control/ai/generation/commit-message-prompt' import { getAgentModelProbeSpec, type AgentModelProbeSpec -} from '../../shared/agent-model-probe-spec' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +} from '../../../shared/agent-model-probe-spec' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' import { runClaudeBackgroundAttempts, type ClaudeBackgroundFailedExit -} from '../../shared/claude-background-run-isolation' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { resolveCodexHomeProcessLockKeyForSpawnEnv } from '../codex-cli/codex-home-process-lock' -import { supervisedProviderSpawnFailure } from '../provider-process/provider-spawn-failure-report' +} from '../../../shared/claude-background-run-isolation' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import { resolveCodexHomeProcessLockKeyForSpawnEnv } from '../../codex-cli/codex-home-process-lock' +import { supervisedProviderSpawnFailure } from '../../provider-process/provider-spawn-failure-report' import { finalizeModelDiscoveryOutput, planModelDiscovery, @@ -21,21 +21,21 @@ import { import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES, SOURCE_CONTROL_GENERATION_TIMEOUT_MS -} from './source-control-generation-limits' -import { runCodexProcessWithHomeLock } from './source-control-local-generation' -import { formatAgentCliFailureMessage } from './source-control-agent-failure' +} from '../execution/source-control-generation-limits' +import { runCodexProcessWithHomeLock } from '../execution/source-control-local-generation' +import { formatAgentCliFailureMessage } from '../failures/source-control-agent-failure' import { settleCodexModelListing, startCodexModelListDiscovery, type CodexModelListDiscovery } from './codex-model-list-discovery' -import { killSourceControlAgentProcess } from './source-control-local-process' +import { killSourceControlAgentProcess } from '../execution/source-control-agent-termination' import type { DiscoverCommitMessageModelsResult, LocalProcessExecution, SpawnedSourceControlAgentProcess, SpawnSourceControlAgent -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' export type CommitMessageModelDiscoveryLocalOptions = { cwd?: string diff --git a/src/main/text-generation/commit-message-text-generation-model-discovery.test.ts b/src/main/text-generation/models/commit-message-text-generation-model-discovery.test.ts similarity index 88% rename from src/main/text-generation/commit-message-text-generation-model-discovery.test.ts rename to src/main/text-generation/models/commit-message-text-generation-model-discovery.test.ts index e90ec3ca2a4..05f7a410b7a 100644 --- a/src/main/text-generation/commit-message-text-generation-model-discovery.test.ts +++ b/src/main/text-generation/models/commit-message-text-generation-model-discovery.test.ts @@ -1,23 +1,23 @@ import { spawn } from 'node:child_process' import type * as ChildProcess from 'node:child_process' -import type * as CliCommandResolution from '../../shared/node-cli-command-resolution' +import type * as CliCommandResolution from '../../../shared/node-cli-command-resolution' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { discoverCommitMessageModelsLocal } from './commit-message-text-generation' +import { discoverCommitMessageModelsLocal } from '../commit-message-text-generation' import { answerCodexAppServer, createMockDiscoveryChild -} from './commit-message-text-generation-test-harness' +} from '../execution/commit-message-text-generation-test-harness' const { terminateWindowsProcessTreeMock } = vi.hoisted(() => ({ terminateWindowsProcessTreeMock: vi.fn(async () => {}) })) -vi.mock('../pty/process-retirement/windows-process-tree-kill', () => ({ +vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({ terminateWindowsProcessTree: terminateWindowsProcessTreeMock })) // These protocol fixtures use fake processes; installed host CLIs belong to the CLI-path suite. -vi.mock('../../shared/node-cli-command-resolution', async (importOriginal) => ({ +vi.mock('../../../shared/node-cli-command-resolution', async (importOriginal) => ({ ...(await importOriginal()), resolveCliCommand: (command: string) => command })) diff --git a/src/main/text-generation/model-discovery-host-cache.ts b/src/main/text-generation/models/model-discovery-host-cache.ts similarity index 84% rename from src/main/text-generation/model-discovery-host-cache.ts rename to src/main/text-generation/models/model-discovery-host-cache.ts index 5f8bbc55ef9..bd3659245c2 100644 --- a/src/main/text-generation/model-discovery-host-cache.ts +++ b/src/main/text-generation/models/model-discovery-host-cache.ts @@ -1,11 +1,11 @@ -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { InFlightPromiseDedupe, stableInFlightKey } from '../../shared/in-flight-promise-dedupe' -import { setBoundedScopeCacheEntry } from '../../shared/native-chat/native-chat-scope-cache' -import { PRIMARY_AGENT_DIR_ENV_BY_KIND } from '../../shared/pi-agent-kind' -import { onAgentsRefreshedOnHost } from '../preflight/agents-refreshed-on-host' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import { InFlightPromiseDedupe, stableInFlightKey } from '../../../shared/in-flight-promise-dedupe' +import { setBoundedScopeCacheEntry } from '../../../shared/native-chat/native-chat-scope-cache' +import { PRIMARY_AGENT_DIR_ENV_BY_KIND } from '../../../shared/pi-agent-kind' +import { onAgentsRefreshedOnHost } from '../../preflight/agents-refreshed-on-host' import type { CommitMessageModelDiscoveryLocalOptions } from './commit-message-model-discovery' -import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' -import type { DiscoverCommitMessageModelsResult } from './source-control-text-generation-types' +import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../execution/source-control-generation-limits' +import type { DiscoverCommitMessageModelsResult } from '../source-control-text-generation-types' // Pickers list these on open; Codex's listing starts an app-server. Each maps to the config-dir var // that picks its login (mirrors prepareShellConfigDirEnv). diff --git a/src/main/text-generation/source-control-kimi-policy.ts b/src/main/text-generation/policies/source-control-kimi-policy.ts similarity index 86% rename from src/main/text-generation/source-control-kimi-policy.ts rename to src/main/text-generation/policies/source-control-kimi-policy.ts index 8f76561d51e..c64f2d18f96 100644 --- a/src/main/text-generation/source-control-kimi-policy.ts +++ b/src/main/text-generation/policies/source-control-kimi-policy.ts @@ -1,11 +1,11 @@ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml' import { z } from 'zod' -import { findOptionOccurrence } from '../../shared/command-option-occurrence' +import { findOptionOccurrence } from '../../../shared/command-option-occurrence' import { compactRecipeOptions, KIMI_VALUE_OPTIONS -} from '../../shared/source-control/ai/generation/commit-message-generation-options' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +} from '../../../shared/source-control/ai/generation/commit-message-generation-options' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' const object = z.record(z.string(), z.unknown()) export async function prepareKimiTextTaskPolicy( diff --git a/src/main/text-generation/source-control-policy-probe.ts b/src/main/text-generation/policies/source-control-policy-probe.ts similarity index 87% rename from src/main/text-generation/source-control-policy-probe.ts rename to src/main/text-generation/policies/source-control-policy-probe.ts index bc2380d953a..137fc7a7743 100644 --- a/src/main/text-generation/source-control-policy-probe.ts +++ b/src/main/text-generation/policies/source-control-policy-probe.ts @@ -1,13 +1,13 @@ -import { abortSignalReason } from '../../shared/abort-signal-reason' -import { mergeCommandEnvironment } from '../../shared/command-environment' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { killSourceControlAgentProcess } from './source-control-agent-termination' -import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from './source-control-generation-limits' +import { abortSignalReason } from '../../../shared/abort-signal-reason' +import { mergeCommandEnvironment } from '../../../shared/command-environment' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { killSourceControlAgentProcess } from '../execution/source-control-agent-termination' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../execution/source-control-generation-limits' import type { LocalGenerationTarget, LocalProcessExecution, SpawnSourceControlAgent -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' /** Effective configuration may contain credentials; keep both streams private even on failure. */ export function runSourceControlPolicyProbe(input: { diff --git a/src/main/text-generation/source-control-read-only-policy.test.ts b/src/main/text-generation/policies/source-control-read-only-policy.test.ts similarity index 95% rename from src/main/text-generation/source-control-read-only-policy.test.ts rename to src/main/text-generation/policies/source-control-read-only-policy.test.ts index 0f14626cb77..8cdf82b978d 100644 --- a/src/main/text-generation/source-control-read-only-policy.test.ts +++ b/src/main/text-generation/policies/source-control-read-only-policy.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { parse as parseYaml } from 'yaml' import { afterEach, expect, it, vi } from 'vitest' -import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' +import { planCommitMessageGeneration } from '../../../shared/source-control/ai/generation/commit-message-plan' import { prepareSourceControlReadOnlyPlan } from './source-control-read-only-policy' -import { stageLocalPromptFiles } from './source-control-prompt-files' -import './source-control-local-generation' -import './source-control-generation-lanes' +import { stageLocalPromptFiles } from '../prompts/source-control-prompt-files' +import '../execution/source-control-local-generation' +import '../execution/source-control-generation-lanes' const { probe } = vi.hoisted(() => ({ probe: vi.fn() })) vi.mock('./source-control-policy-probe', () => ({ runSourceControlPolicyProbe: probe })) diff --git a/src/main/text-generation/source-control-read-only-policy.ts b/src/main/text-generation/policies/source-control-read-only-policy.ts similarity index 92% rename from src/main/text-generation/source-control-read-only-policy.ts rename to src/main/text-generation/policies/source-control-read-only-policy.ts index 498f1069dc6..51231ac289a 100644 --- a/src/main/text-generation/source-control-read-only-policy.ts +++ b/src/main/text-generation/policies/source-control-read-only-policy.ts @@ -4,23 +4,23 @@ import path from 'node:path' import { prepareKimiTextTaskPolicy } from './source-control-kimi-policy' import { parse as parseJson, type ParseError } from 'jsonc-parser' import { z } from 'zod' -import { findOptionOccurrence } from '../../shared/command-option-occurrence' +import { findOptionOccurrence } from '../../../shared/command-option-occurrence' import { compactRecipeOptions, KIMI_VALUE_OPTIONS -} from '../../shared/source-control/ai/generation/commit-message-generation-options' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { parseWslUncPath, wslDistroForCommand } from '../../shared/wsl-paths' -import { CODEX_DISABLE_PLUGINS_ARGS } from '../codex-cli/codex-read-only-app-server-args' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import { TEXT_TASK_DIRECTORY } from './source-control-prompt-files' +} from '../../../shared/source-control/ai/generation/commit-message-generation-options' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { parseWslUncPath, wslDistroForCommand } from '../../../shared/wsl-paths' +import { CODEX_DISABLE_PLUGINS_ARGS } from '../../codex-cli/codex-read-only-app-server-args' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import { TEXT_TASK_DIRECTORY } from '../prompts/source-control-prompt-files' import { runSourceControlPolicyProbe } from './source-control-policy-probe' import type { LocalGenerationTarget, LocalProcessExecution, SpawnSourceControlAgent, TextGenerationOperation -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' const object = z.record(z.string(), z.unknown()) const strings = z.array(z.string()) diff --git a/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts b/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts new file mode 100644 index 00000000000..ce2baf2088d --- /dev/null +++ b/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts @@ -0,0 +1,210 @@ +import { spawnProcess } from '@orca/process-host' +import type { SpawnSourceControlAgent } from '../source-control-text-generation-types' +import { generateCommitMessage } from '../requests/source-control-text-generation-requests' + +import { existsSync, mkdtempSync, readFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { planCommitMessageGeneration } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { cancelLocalGeneration } from '../execution/source-control-generation-lanes' +import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../execution/source-control-generation-limits' +import { runLocalSourceControlPlan } from '../execution/source-control-local-process' +import { + createMockDiscoveryChild, + withPlatform +} from '../execution/commit-message-text-generation-test-harness' + +vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({ + terminateWindowsProcessTree: vi.fn(async () => true) +})) + +afterEach(() => vi.useRealTimers()) + +// OMP 17.0.5 recorded stdin-only execution: exit 0, empty stdout/stderr, no submitted prompt. +const recordedPrompt = `Name this chat from the user's first request. +Write a short, specific title of at most 48 characters. +Output only the title, with no heading, quotes, or explanation. + +First request: +Trace a lost lighthouse signal. + +Additional instructions: +Return Lighthouse Signal Trace. +` + +it.each(['success', 'failure', 'cancel', 'timeout', 'spawn failure'] as const)( + 'delivers the recorded OMP prompt without stdin and removes the owned file after %s', + async (outcome) => { + vi.useFakeTimers() + const prompt = recordedPrompt + 'x'.repeat(200_000) + const planned = planCommitMessageGeneration({ agentId: 'omp', model: 'default' }, prompt) + if (!planned.ok) { + throw new Error(planned.error) + } + const child = createMockDiscoveryChild() + let promptPath = '' + const execution = withPlatform('win32', () => + runLocalSourceControlPlan({ + plan: planned.plan, + cwd: '/omp-file-test', + env: undefined, + operation: 'conversation-name', + spawnAgent: ({ args }) => { + promptPath = args[planned.plan.promptFile?.argIndex ?? -1]?.slice(1) ?? '' + expect(new TextDecoder().decode(readFileSync(promptPath))).toBe(prompt) + expect(args.join(' ').length).toBeLessThan(1000) + if (outcome === 'spawn failure') { + throw new Error('recorded spawn failure') + } + return child + } + }) + ) + if (outcome === 'success') { + // Like the recorded binary, this child never reads stdin; only the explicit file submits input. + child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace')) + } else if (outcome === 'cancel') { + cancelLocalGeneration('conversation-name', '/omp-file-test') + } else if (outcome === 'timeout') { + await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) + } + if (outcome !== 'spawn failure') { + expect(child.stdin.end).toHaveBeenCalledWith(undefined) + expect(existsSync(promptPath)).toBe(true) + child.emit('close', outcome === 'failure' ? 1 : 0) + } + const result = await execution.result + await execution.processClosed + expect(result.success).toBe(outcome === 'success') + await vi.waitFor(() => expect(existsSync(dirname(promptPath))).toBe(false)) + } +) + +// Pinned OMP17 cli/file-processor.ts:16,49-54,119-122: per-file cap, ordered text decoding. +const attachmentReader = String.raw` +const fs = require('node:fs'); +const args = process.argv.slice(1); +const paths = args.filter(arg => arg.startsWith('@')).map(arg => arg.slice(1)); +const chunks = paths.map(path => fs.readFileSync(path)); +const isImage = bytes => ['GIF87a', 'GIF89a'].includes(bytes.subarray(0, 6).toString()) || + (bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP'); +const fragments = chunks.map(bytes => bytes.length > 5 * 1024 * 1024 + ? '(skipped: too large)' : isImage(bytes) ? '(image instead of text)' : new TextDecoder().decode(bytes)); +let stdin = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => { stdin += chunk; }); +process.stdin.on('end', () => { + fs.writeFileSync(process.env.OMP_RECEIPT, JSON.stringify({ + paths, sizes: chunks.map(bytes => bytes.length), content: paths.length ? fragments.join('') : stdin, stdin, + message: fragments.map((text, index) => '\n' + text + '\n\n').join('') + args.at(-1) + })); + process.stdout.write(process.env.OMP_OUTPUT); + if (process.env.OMP_EXIT === '7') process.stderr.write('Fixture provider unavailable'); + process.exitCode = Number(process.env.OMP_EXIT); +}); +` + +const contractParams = { + agentId: 'omp', + model: 'generated/model', + thinkingLevel: 'low', + agentCommandOverride: 'OMP_RECIPE_ENV=kept node /configured/prefix/omp.js --model prefix/model', + agentArgs: '--model recipe/model --thinking high -- recipe-message', + commandInputTemplate: 'Saved recipe instruction\n{basePrompt}' +} as const +const contractTarget = { kind: 'local', cwd: tmpdir() } as const +const commitContext = { + branch: 'feature', + stagedSummary: 'signal.ts | 1 +', + stagedPatch: '+ Trace lighthouse signal' +} + +type Receipt = { paths: string[]; sizes: number[]; content: string; stdin: string; message: string } +async function withReader( + output: string, + fail: boolean, + run: (spawnAgent: SpawnSourceControlAgent) => Promise +) { + const directory = mkdtempSync(join(tmpdir(), 'orca-omp-contract-')) + const receiptPath = join(directory, 'receipt.json') + try { + const result = await run((input) => { + expect(input.binary).toBe('node') + expect(input.args.slice(0, 1)).toEqual(['/configured/prefix/omp.js']) + expect(input.args).toContain('recipe/model') + expect(input.args).not.toContain('prefix/model') + expect(input.args).not.toContain('generated/model') + expect(input.args).toContain('high') + expect(input.args).not.toContain('low') + expect(input.args.slice(-2)).toEqual(['--', 'recipe-message']) + expect(input.commandEnv).toEqual({ OMP_RECIPE_ENV: 'kept' }) + return spawnProcess({ + program: process.execPath, + args: ['-e', attachmentReader, '--', ...input.args], + cwd: input.cwd, + env: { + ...process.env, + OMP_RECEIPT: receiptPath, + OMP_OUTPUT: output, + OMP_EXIT: fail ? '7' : '0' + }, + stdio: 'pipe' + }) + }) + const receipt: Receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) + await vi.waitFor(() => { + for (const path of receipt.paths) { + expect(existsSync(dirname(path))).toBe(false) + } + }) + return { result, receipt } + } finally { + await rm(directory, { recursive: true, force: true }) + } +} + +it.each(['below', 'at', 'above', 'multibyte', 'BOM run', 'GIF', 'RIFF', 'internal magic'] as const)( + 'delivers complete text recipe content: %s', + async (boundary) => { + const cap = 5 * 1024 * 1024 + const payloadCap = cap - 3 + const patches = { + below: () => 'x'.repeat(payloadCap - 1), + at: () => 'x'.repeat(payloadCap), + above: () => 'x'.repeat(cap + 1), + multibyte: () => + `${'x'.repeat(payloadCap - 1)}🌊界é${'界'.repeat(Math.ceil(cap / 3))}\uFEFFEND`, + 'BOM run': () => `${'\uFEFF'.repeat(Math.ceil(cap / 3))}Preserve every BOM`, + GIF: () => 'GIF89a is the header this change handles. Preserve this as text.', + RIFF: () => 'RIFFxxxxWEBP is the signature this change handles. Preserve this as text.', + 'internal magic': () => `${'x'.repeat(payloadCap)}GIF89a preserve this boundary as text.` + } + const patch = patches[boundary]() + const { result, receipt } = await withReader( + 'Preserve the complete request', + false, + (spawnAgent) => + generateCommitMessage({ + context: { ...commitContext, stagedPatch: patch }, + params: { ...contractParams, commandInputTemplate: '{stagedPatch}' }, + target: contractTarget, + spawnAgent + }) + ) + expect(result).toMatchObject({ success: true, message: 'Preserve the complete request' }) + expect(receipt.content).toBe(patch) + expect(receipt.sizes.every((size) => size <= cap)).toBe(true) + expect(receipt.paths).toHaveLength( + boundary === 'multibyte' + ? 3 + : ['above', 'BOM run', 'internal magic'].includes(boundary) + ? 2 + : 1 + ) + if (boundary === 'at') { + expect(receipt.sizes).toEqual([cap]) + } + } +) diff --git a/src/main/text-generation/source-control-prompt-files.ts b/src/main/text-generation/prompts/source-control-prompt-files.ts similarity index 95% rename from src/main/text-generation/source-control-prompt-files.ts rename to src/main/text-generation/prompts/source-control-prompt-files.ts index 9a419bd23a4..a32f506d03d 100644 --- a/src/main/text-generation/source-control-prompt-files.ts +++ b/src/main/text-generation/prompts/source-control-prompt-files.ts @@ -2,10 +2,10 @@ import { randomUUID } from 'node:crypto' import { mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { getUtf8ChunkEndIndex } from '../../shared/utf8-byte-limits' -import { encodePosixPrintfRecords } from '../../shared/posix-printf-encoding' -import { toWindowsWslUncPath } from '../../shared/wsl-paths' -import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +import { getUtf8ChunkEndIndex } from '../../../shared/utf8-byte-limits' +import { encodePosixPrintfRecords } from '../../../shared/posix-printf-encoding' +import { toWindowsWslUncPath } from '../../../shared/wsl-paths' +import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' // Reserve the transport signature under the native text attachment cap. const PAYLOAD_BYTES = 5 * 1024 * 1024 - 3 diff --git a/src/main/text-generation/source-control-prompt-producer.ts b/src/main/text-generation/prompts/source-control-prompt-producer.ts similarity index 100% rename from src/main/text-generation/source-control-prompt-producer.ts rename to src/main/text-generation/prompts/source-control-prompt-producer.ts diff --git a/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts b/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts new file mode 100644 index 00000000000..67538be68c0 --- /dev/null +++ b/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts @@ -0,0 +1,388 @@ +import { spawnProcess } from '@orca/process-host' +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { planCommitMessageGeneration } from '../../../shared/source-control/ai/generation/commit-message-plan' +import { prepareWslPrompt } from './source-control-prompt-files' +import { runLocalSourceControlPlan } from '../execution/source-control-local-process' +import { cancelLocalGeneration } from '../execution/source-control-generation-lanes' +import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../execution/source-control-generation-limits' +import { + withPlatform, + createMockDiscoveryChild +} from '../execution/commit-message-text-generation-test-harness' +import type { SourceControlAgentSpawnInput } from '../source-control-text-generation-types' +import type * as Removal from '../../../shared/windows-transient-lock-removal' + +const { removeTreeMock } = vi.hoisted(() => ({ removeTreeMock: vi.fn(async () => {}) })) +vi.mock('../../../shared/windows-transient-lock-removal', async (original) => ({ + ...(await original()), + removeTree: removeTreeMock +})) +vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({ + terminateWindowsProcessTree: vi.fn(async () => true) +})) +vi.mock('../../wsl/discovery/wsl-background-distro-gate', () => ({ + noteWslDistroLaunched: vi.fn() +})) + +afterEach(() => { + vi.useRealTimers() + removeTreeMock.mockReset() + removeTreeMock.mockResolvedValue(undefined) +}) + +const cwd = '\\\\wsl.localhost\\Actual\\home\\dev\\repo' +function plan(content = 'sensitive request') { + const planned = planCommitMessageGeneration({ agentId: 'omp', model: 'default' }, content) + if (!planned.ok) { + throw new Error(planned.error) + } + return planned.plan +} +function start(child = createMockDiscoveryChild(), content?: string) { + let launch: SourceControlAgentSpawnInput | undefined + const execution = withPlatform('win32', () => + runLocalSourceControlPlan({ + plan: plan(content), + cwd, + wslDistro: 'Wrong', + env: undefined, + operation: 'conversation-name', + spawnAgent: (input) => { + launch = input + return child + } + }) + ) + const nonce = launch?.preparation?.args[0] + if (!nonce) { + throw new Error('Expected preparation') + } + return { child, launch, nonce, execution, proof: `ORCA_GENERATION_READY:${nonce}\n` } +} +function close(child: ReturnType, code = 0) { + child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace')) + child.emit('exit', code) + child.emit('close', code) +} + +it('waits for fragmented exact proof, streams once and cleans only the actual guest after terminal', async () => { + const { child, launch, nonce, execution, proof } = start() + const writes: string[] = [] + child.stdin.on('data', (chunk) => writes.push(chunk.toString())) + expect(launch?.wslDistro).toBe('Actual') + expect(launch?.args).toContain(`@/tmp/orca-generation-${nonce}/prompt-1.txt`) + expect(child.stdin.end).not.toHaveBeenCalled() + child.stderr.emit('data', Buffer.from(`${proof.trim()}WRONG\n${'x'.repeat(100_000)}\n`)) + child.stderr.emit('data', Buffer.from(proof.slice(0, 17))) + expect(writes).toEqual([]) + child.stderr.emit('data', Buffer.from(proof.slice(17))) + child.stderr.emit('data', Buffer.from(proof)) + expect(writes.join('')).toBe(`A${nonce}\nDsensitive request\nF${nonce}:1\nX${nonce}\n`) + expect(removeTreeMock).not.toHaveBeenCalled() + close(child) + expect(await execution.result).toMatchObject({ success: true }) + await execution.processClosed + expect(removeTreeMock).toHaveBeenCalledExactlyOnceWith( + `\\\\wsl.localhost\\Actual\\tmp\\orca-generation-${nonce}` + ) + child.stderr.emit('data', Buffer.from(proof)) + expect(removeTreeMock).toHaveBeenCalledTimes(1) +}) + +it.each(['missing-proof', 'spawn', 'no-pid', 'missing-stdin'] as const)( + 'settles %s without invented ownership', + async (route) => { + vi.useFakeTimers() + const child = createMockDiscoveryChild() + if (route === 'missing-stdin') { + Object.defineProperty(child, 'stdin', { value: null }) + } + if (route === 'no-pid') { + Object.defineProperty(child, 'pid', { value: undefined }) + } + const execution = withPlatform('win32', () => + runLocalSourceControlPlan({ + plan: plan(), + cwd, + env: undefined, + operation: 'conversation-name', + spawnAgent: () => { + if (route === 'spawn') { + throw new Error('spawn denied') + } + return child + } + }) + ) + if (route === 'no-pid') { + child.emit('error', Object.assign(new Error('not found'), { code: 'ENOENT' })) + } + if (route === 'missing-proof') { + await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) + } + if (route !== 'spawn' && route !== 'no-pid') { + close(child, 1) + } + expect(await execution.result).toMatchObject({ success: false }) + await execution.processClosed + expect(removeTreeMock).not.toHaveBeenCalled() + } +) + +it.each(['pending', 'rejected'] as const)( + 'never gates either promise on %s cleanup, even proof after processClosed', + async (outcome) => { + removeTreeMock.mockImplementation(() => + outcome === 'pending' ? new Promise(() => {}) : Promise.reject(new Error('share unavailable')) + ) + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const { child, execution, proof } = start() + close(child) + expect(await execution.result).toMatchObject({ success: true }) + await execution.processClosed + child.stderr.emit('data', Buffer.from(proof)) + child.stderr.emit('data', Buffer.from(proof)) + expect(removeTreeMock).toHaveBeenCalledTimes(1) + expect(child.stdin.end).not.toHaveBeenCalled() + await Promise.resolve() + } finally { + log.mockRestore() + } + } +) + +const tricky = `${Array.from({ length: 128 }, (_, i) => String.fromCharCode(i)).join('')}\\c\\012\r\n'!%$\`🌊界\ud800` + +async function shellFixture( + content: string, + controls?: (records: string[], nonce: string) => string[], + setup?: (directory: string) => void, + onProof?: (directory: string) => void +) { + const guest = prepareWslPrompt(plan(content), 'Actual') + const [nonce] = guest.preparation.args + const directory = `/tmp/orca-generation-${nonce}` + setup?.(directory) + const child = spawnProcess({ + program: '/bin/sh', + args: [ + '-c', + guest.preparation.script, + 'fixture', + ...guest.preparation.args, + process.execPath, + '-e', + String.raw` +const fs = require('node:fs'); +const paths = process.argv.slice(1).map(arg => arg.slice(1)); +const files = paths.map(path => fs.readFileSync(path)); +process.stdout.write(JSON.stringify({ content: Buffer.concat(files.map(file => Buffer.from(new TextDecoder().decode(file)))).toString('base64'), + sizes: files.map(file => file.length), modes: paths.map(path => fs.statSync(path).mode & 511), directory: fs.statSync(process.env.FIXTURE_DIRECTORY).mode & 511, + eof: require('node:fs').readFileSync(0).length })); +`, + '--', + ...guest.plan.args.filter((arg) => arg.startsWith('@')) + ], + stdio: 'pipe', + env: { ...process.env, FIXTURE_DIRECTORY: directory } + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (bytes) => { + stdout += bytes + }) + const finished = new Promise((resolve, reject) => { + child.once('close', resolve) + child.once('error', reject) + }) + child.stdin.on('error', () => {}) + child.stderr.on('data', (chunk) => { + stderr += chunk + if (guest.observe(chunk)) { + onProof?.(directory) + const records = [...guest.records()] + child.stdin.end((controls ? controls(records, nonce) : records).join('')) + } + }) + try { + const code = await finished + return { + code, + stdout, + stderr, + directory, + existed: existsSync(directory), + sentinel: existsSync(join(directory, 'sentinel')) + ? readFileSync(join(directory, 'sentinel'), 'utf8') + : null + } + } finally { + await rm(directory, { recursive: true, force: true }) + } +} + +it.each(['', tricky.repeat(12), `${'x'.repeat(5 * 1024 * 1024 - 4)}🌊GIF89a${tricky}`])( + 'materializes exact native text with private modes across encoding and file boundaries', + async (content) => { + const result = await shellFixture(content) + expect(result.code).toBe(0) + const receipt = JSON.parse(result.stdout) + expect(Buffer.from(receipt.content, 'base64').toString()).toBe(Buffer.from(content).toString()) + expect(receipt.modes.every((mode: number) => mode === 0o600)).toBe(true) + expect(receipt.directory).toBe(0o700) + expect(receipt.eof).toBe(0) + expect(receipt.sizes.every((size: number) => size <= 5 * 1024 * 1024)).toBe(true) + expect(result.existed).toBe(true) + } +) + +it.each([ + 'collision', + 'partial-data', + 'wrong-end', + 'missing-end', + 'partial-execute', + 'extra-data', + 'wrong-ack' +] as const)('does not execute on %s, and never adopts/deletes a collision', async (route) => { + const result = await shellFixture( + 'private data', + (records, nonce) => { + if (route === 'partial-data') { + return [`A${nonce}\nDpartial`] + } + if (route === 'wrong-end') { + return records.map((record) => (record.startsWith('F') ? `F${nonce}:2\n` : record)) + } + if (route === 'missing-end') { + return records.filter((record) => !record.startsWith('F')) + } + if (route === 'partial-execute') { + return records.map((record) => (record.startsWith('X') ? record.trim() : record)) + } + if (route === 'extra-data') { + return [...records.slice(0, -1), 'Dextra\n', ...records.slice(-1)] + } + if (route === 'wrong-ack') { + return ['Ano\n'] + } + return records + }, + (directory) => { + if (route === 'collision') { + mkdirSync(directory) + writeFileSync(join(directory, 'sentinel'), 'untouched') + } + } + ) + expect(result.code).not.toBe(0) + expect(result.stdout).toBe('') + if (route === 'collision') { + expect(result.stderr).not.toContain('ORCA_GENERATION_READY:') + expect(result.sentinel).toBe('untouched') + } + if (route === 'wrong-ack') { + expect(result.existed).toBe(false) + } +}) + +it('fails a real post-proof storage redirect without running a partial request', async () => { + const result = await shellFixture('private data', undefined, undefined, (directory) => + mkdirSync(join(directory, 'prompt-1.txt')) + ) + expect(result.code).not.toBe(0) + expect(result.stdout).toBe('') + expect(result.existed).toBe(true) +}) + +it.each([ + { boundary: 'data', stopping: 'cancel' }, + { boundary: 'final', stopping: 'cancel' }, + { boundary: 'data', stopping: 'deadline' }, + { boundary: 'final', stopping: 'deadline' } +] as const)( + 'does not authorize after $stopping at $boundary write continuation', + async ({ boundary, stopping }) => { + vi.useFakeTimers() + const { child, execution, proof, nonce } = start() + const writes: string[] = [] + vi.spyOn(child.stdin, 'write').mockImplementation((chunk) => { + const record = String(chunk) + writes.push(record) + if (record.startsWith(boundary === 'data' ? 'D' : 'F')) { + if (stopping === 'cancel') { + cancelLocalGeneration('conversation-name', cwd) + } else { + vi.advanceTimersByTime(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) + } + } + return true + }) + child.stderr.emit('data', Buffer.from(proof)) + close(child) + expect(await execution.result).toMatchObject( + stopping === 'cancel' + ? { success: false, canceled: true } + : { success: false, error: 'Generation timed out after 60s.' } + ) + await execution.processClosed + expect(writes).not.toContain(`X${nonce}\n`) + } +) + +it('delivers a plain UTF-8 policy module and preserves the stdin task after guest materialization', async () => { + const guest = prepareWslPrompt( + { + binary: process.execPath, + args: ['{module}'], + label: 'Policy fixture', + stdinPayload: 'Name this chat 🌊\nlast line', + taskFiles: [ + { name: 'task-policy.mjs', content: 'export const text = "policy 🌊"\n', argIndex: 0 } + ] + }, + 'Actual' + ) + const directory = `/tmp/orca-generation-${guest.preparation.args[0]}` + const child = spawnProcess({ + program: '/bin/sh', + args: [ + '-c', + guest.preparation.script, + 'fixture', + ...guest.preparation.args, + process.execPath, + '-e', + `const fs = require('node:fs'); const {pathToFileURL}=require('node:url'); import(pathToFileURL(process.argv[1])).then(module => process.stdout.write(JSON.stringify({ text: module.text, task: fs.readFileSync(0,'utf8'), prefix: fs.readFileSync(process.argv[1]).subarray(0,3).toString('hex') })))`, + '--', + ...guest.plan.args + ], + stdio: 'pipe' + }) + let stdout = '' + child.stdout.on('data', (chunk) => (stdout += chunk.toString())) + child.stdin.on('error', () => {}) + child.stderr.on('data', (chunk) => { + if (guest.observe(chunk)) { + child.stdin.end([...guest.records()].join('')) + } + }) + try { + const code = await new Promise((resolve, reject) => { + child.once('close', resolve) + child.once('error', reject) + }) + expect(code).toBe(0) + expect(JSON.parse(stdout)).toEqual({ + text: 'policy 🌊', + task: 'Name this chat 🌊\nlast line', + prefix: '657870' + }) + } finally { + await rm(directory, { recursive: true, force: true }) + } +}) diff --git a/src/main/text-generation/pull-request-context.test.ts b/src/main/text-generation/pull-request-context.test.ts deleted file mode 100644 index cce11523519..00000000000 --- a/src/main/text-generation/pull-request-context.test.ts +++ /dev/null @@ -1,482 +0,0 @@ -// Keep remote-state command-order cases together so Git regressions stay reviewable. -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getPullRequestDraftContext } from './pull-request-context' - -type GitExec = Parameters[0] - -afterEach(() => { - vi.restoreAllMocks() -}) - -function createContextInput(base = 'main') { - return { - base, - currentTitle: 'Existing title', - currentBody: 'Existing body', - currentDraft: false - } -} - -describe('getPullRequestDraftContext', () => { - it('fetches the resolved remote base before collecting PR context without mutating HEAD', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'fetch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'remote') { - return { stdout: 'origin\nupstream\n', stderr: '' } - } - if (args[0] === 'show-ref') { - return { - stdout: 'abc refs/remotes/origin/main\n' + 'def refs/remotes/upstream/main\n', - stderr: '' - } - } - if (args[0] === 'branch') { - return { stdout: 'feature/pr-details\n', stderr: '' } - } - if (args[0] === 'merge-base') { - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log') { - return { stdout: '- feat: summarize branch\n', stderr: '' } - } - if (args[0] === 'diff' && args[1] === '--name-status') { - return { stdout: 'M\tsrc/file.ts\n', stderr: '' } - } - if (args[0] === 'diff') { - return { stdout: 'diff --git a/src/file.ts b/src/file.ts\n+change\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - const context = await getPullRequestDraftContext(execGit, createContextInput()) - - expect(context).toMatchObject({ - branch: 'feature/pr-details', - base: 'main', - branchChangedByPreparation: false, - commitSummary: '- feat: summarize branch', - changeSummary: 'M\tsrc/file.ts' - }) - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], - expect.any(Object) - ) - expect(execGit).toHaveBeenCalledWith( - ['show-ref', '--verify', '--quiet', '--', 'refs/remotes/origin/main'], - expect.objectContaining({ maxBuffer: 10 * 1024 * 1024 }) - ) - expect(execGit).toHaveBeenCalledWith( - ['show-ref', '--verify', '--quiet', '--', 'refs/remotes/upstream/main'], - expect.objectContaining({ maxBuffer: 10 * 1024 * 1024 }) - ) - const exactRefCalls = execGit.mock.calls.filter(([args]) => args[0] === 'show-ref') - expect(exactRefCalls).toHaveLength(2) - expect(exactRefCalls.every(([, options]) => options?.timeoutMs === undefined)).toBe(true) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['rebase']), expect.anything()) - expect(execGit).not.toHaveBeenCalledWith( - expect.arrayContaining(['rev-parse']), - expect.anything() - ) - expect(execGit).toHaveBeenCalledWith(['merge-base', 'origin/main', 'HEAD'], expect.any(Object)) - - const commandNames = execGit.mock.calls.map(([args]) => args[0]) - expect(commandNames.indexOf('fetch')).toBeLessThan(commandNames.indexOf('merge-base')) - }) - - it('fetches a configured preferred remote without a suffix scan when its ref is absent', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'fetch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'remote') { - return { stdout: 'origin\n', stderr: '' } - } - if (args[0] === 'show-ref') { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'branch') { - return { stdout: 'feature/pr-details\n', stderr: '' } - } - if (args[0] === 'merge-base') { - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log') { - return { stdout: '- feat: summarize branch\n', stderr: '' } - } - if (args[0] === 'diff') { - return { stdout: 'M\tREADME.md\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await getPullRequestDraftContext(execGit, createContextInput()) - - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], - expect.any(Object) - ) - expect(execGit.mock.calls.some(([args]) => args.join(' ') === 'show-ref -- main')).toBe(false) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['rebase']), expect.anything()) - }) - - it('does not guess between multiple non-preferred remote bases for a bare base name', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'fetch') { - throw new Error(`Unexpected fetch: ${args.join(' ')}`) - } - if (args[0] === 'remote') { - return { stdout: 'contributor-a\ncontributor-b\n', stderr: '' } - } - if (args[0] === 'for-each-ref') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'show-ref') { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'branch') { - return { stdout: 'feature\n', stderr: '' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('main') - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log') { - return { stdout: '- feat: change\n', stderr: '' } - } - if (args[0] === 'diff') { - return { stdout: 'M\tREADME.md\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await getPullRequestDraftContext(execGit, createContextInput()) - - const showRefCalls = execGit.mock.calls.filter(([args]) => args[0] === 'show-ref') - expect(showRefCalls.some(([args]) => args.includes('--verify'))).toBe(false) - const exactProbes = execGit.mock.calls.filter(([args]) => args[0] === 'for-each-ref') - expect(exactProbes).toHaveLength(1) - expect(exactProbes[0][0]).toEqual([ - 'for-each-ref', - '--format=%(refname)', - '--', - 'refs/remotes/origin/main', - 'refs/remotes/upstream/main', - 'refs/remotes/contributor-a/main', - 'refs/remotes/contributor-b/main' - ]) - expect(showRefCalls.some(([args]) => args.join(' ') === 'show-ref -- main')).toBe(true) - - expect(execGit).not.toHaveBeenCalledWith( - expect.arrayContaining(['contributor-a']), - expect.any(Object) - ) - expect(execGit).not.toHaveBeenCalledWith( - expect.arrayContaining(['contributor-b']), - expect.any(Object) - ) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['rebase']), expect.anything()) - }) - - it('does not choose another remote when an exact probe is inconclusive', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'first\nsecond\n' } - } - if (args[0] === 'show-ref') { - throw Object.assign(new Error('remote probe failed'), { code: 128 }) - } - if (args[0] === 'fetch') { - throw new Error(`Unexpected fetch: ${args.join(' ')}`) - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('main') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).resolves.toMatchObject({ - branch: 'feature' - }) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch']), expect.any(Object)) - }) - - it('resolves a unique slash-containing remote with an exact probe', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'foo/bar\n', stderr: '' } - } - if (args[0] === 'for-each-ref') { - return { stdout: 'refs/remotes/foo/bar/feature/fix\n' } - } - if (args[0] === 'fetch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('foo/bar/feature/fix') - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect( - getPullRequestDraftContext(execGit, createContextInput('feature/fix')) - ).resolves.toMatchObject({ branchChangedByPreparation: false }) - - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'foo/bar', '+refs/heads/feature/fix:refs/remotes/foo/bar/feature/fix'], - expect.any(Object) - ) - }) - - it('preserves Git-valid punctuation in configured remote names', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'team@corp\n' } - } - if (args[0] === 'show-ref') { - return args.at(-1) === 'refs/remotes/team@corp/main' - ? { stdout: '' } - : Promise.reject(Object.assign(new Error('missing exact ref'), { code: 1 })) - } - if (args[0] === 'fetch' || args[0] === 'branch') { - return { stdout: '' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('team@corp/main') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await getPullRequestDraftContext(execGit, createContextInput()) - - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'team@corp', '+refs/heads/main:refs/remotes/team@corp/main'], - expect.any(Object) - ) - }) - - it('resolves a unique unconfigured remote suffix with a bounded show-ref fallback', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'fork\n' } - } - if (args[0] === 'show-ref' && args.some((arg) => arg.startsWith('refs/remotes/'))) { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'show-ref') { - return { stdout: 'abc123 refs/remotes/orphan/main\n' } - } - if (args[0] === 'fetch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('orphan/main') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).resolves.toMatchObject({ - branch: 'feature' - }) - - expect(execGit).toHaveBeenCalledWith(['show-ref', '--', 'main'], expect.any(Object)) - expect(execGit).toHaveBeenCalledWith( - ['show-ref', '--', 'main'], - expect.objectContaining({ maxBuffer: 10 * 1024 * 1024 }) - ) - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'orphan', '+refs/heads/main:refs/remotes/orphan/main'], - expect.any(Object) - ) - }) - - it('does not guess when the suffix fallback finds multiple remotes', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'fork\n' } - } - if (args[0] === 'show-ref' && args.some((arg) => arg.startsWith('refs/remotes/'))) { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'show-ref') { - return { - stdout: 'abc123 refs/remotes/orphan-a/main\nabc123 refs/remotes/orphan-b/main\n' - } - } - if (args[0] === 'fetch') { - throw new Error(`Unexpected fetch: ${args.join(' ')}`) - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('main') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).resolves.toMatchObject({ - branch: 'feature' - }) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch']), expect.any(Object)) - }) - - it('treats a suffix fallback overflow or transport error as no match', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'fork\n' } - } - if (args[0] === 'show-ref') { - if (args.some((arg) => arg.startsWith('refs/remotes/'))) { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - throw new Error('git stdout exceeded maxBuffer') - } - if (args[0] === 'fetch') { - throw new Error(`Unexpected fetch: ${args.join(' ')}`) - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('main') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).resolves.toMatchObject({ - branch: 'feature' - }) - expect(execGit).toHaveBeenCalledWith(['show-ref', '--', 'main'], expect.any(Object)) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch']), expect.any(Object)) - }) - - it('preserves a legal branch whose final component is HEAD', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'origin\n', stderr: '' } - } - if (args[0] === 'show-ref') { - return args.at(-1) === 'refs/remotes/origin/feature/HEAD' - ? { stdout: '', stderr: '' } - : Promise.reject(Object.assign(new Error('missing exact ref'), { code: 1 })) - } - if (args[0] === 'fetch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'branch') { - return { stdout: 'feature/current\n', stderr: '' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('origin/feature/HEAD') - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await getPullRequestDraftContext(execGit, createContextInput('feature/HEAD')) - - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/feature/HEAD:refs/remotes/origin/feature/HEAD'], - expect.any(Object) - ) - }) - - it('retains exact-ref precedence when many other remotes share the suffix', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'origin\nfirst\nsecond\n', stderr: '' } - } - if (args[0] === 'show-ref') { - return args.at(-1) === 'refs/remotes/orphan/main' - ? { stdout: '', stderr: '' } - : Promise.reject(Object.assign(new Error('missing exact ref'), { code: 1 })) - } - if (args[0] === 'fetch' || args[0] === 'branch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('orphan/main') - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await getPullRequestDraftContext(execGit, createContextInput('orphan/main')) - - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'orphan', '+refs/heads/main:refs/remotes/orphan/main'], - expect.any(Object) - ) - }) - - it('retains preferred origin precedence when its remote is not configured', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'fork\n', stderr: '' } - } - if (args[0] === 'for-each-ref') { - return { stdout: 'refs/remotes/origin/main\n', stderr: '' } - } - if (args[0] === 'fetch' || args[0] === 'branch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('origin/main') - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await getPullRequestDraftContext(execGit, createContextInput()) - - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], - expect.any(Object) - ) - expect(execGit.mock.calls.filter(([args]) => args[0] === 'for-each-ref')).toHaveLength(1) - }) -}) diff --git a/src/main/text-generation/pull-request-context.ts b/src/main/text-generation/pull-request-context/pull-request-context.ts similarity index 94% rename from src/main/text-generation/pull-request-context.ts rename to src/main/text-generation/pull-request-context/pull-request-context.ts index 4753fa44f09..152d97d772e 100644 --- a/src/main/text-generation/pull-request-context.ts +++ b/src/main/text-generation/pull-request-context/pull-request-context.ts @@ -1,7 +1,7 @@ -import type { PullRequestDraftContext } from '../../shared/source-control/ai/generation/pull-request-generation' -import { isSafeGitRefName } from '../../shared/git/status/git-status-upstream-ref' -import { isSafeReviewHeadFetchRemote } from '../../shared/review-head-tracking-ref' -import { ReviewDraftContextError } from '../../shared/review-draft-context-error' +import type { PullRequestDraftContext } from '../../../shared/source-control/ai/generation/pull-request-generation' +import { isSafeGitRefName } from '../../../shared/git/status/git-status-upstream-ref' +import { isSafeReviewHeadFetchRemote } from '../../../shared/review-head-tracking-ref' +import { ReviewDraftContextError } from '../../../shared/review-draft-context-error' import { canQueryRemoteBaseRefs, getPullRequestRemoteRefState, diff --git a/src/main/text-generation/pull-request-remote-ref-probes.ts b/src/main/text-generation/pull-request-context/pull-request-remote-ref-probes.ts similarity index 94% rename from src/main/text-generation/pull-request-remote-ref-probes.ts rename to src/main/text-generation/pull-request-context/pull-request-remote-ref-probes.ts index 96565d8fa8f..af5680f1b94 100644 --- a/src/main/text-generation/pull-request-remote-ref-probes.ts +++ b/src/main/text-generation/pull-request-context/pull-request-remote-ref-probes.ts @@ -1,10 +1,10 @@ -import { isSafeGitRefName } from '../../shared/git/status/git-status-upstream-ref' -import { isRemoteHeadRef } from '../../shared/source-control/hosted-review/hosted-review-refs' -import { isSafeReviewHeadFetchRemote } from '../../shared/review-head-tracking-ref' +import { isSafeGitRefName } from '../../../shared/git/status/git-status-upstream-ref' +import { isRemoteHeadRef } from '../../../shared/source-control/hosted-review/hosted-review-refs' +import { isSafeReviewHeadFetchRemote } from '../../../shared/review-head-tracking-ref' import { probeExactRefsViaForEachRef, type ExactRefProbeExecOptions -} from '../git/refs/resolution/exact-ref-probe' +} from '../../git/refs/resolution/exact-ref-probe' export type PullRequestGitExec = ( args: string[], diff --git a/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts b/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts new file mode 100644 index 00000000000..d50ffbe63ad --- /dev/null +++ b/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import { generateBranchNameFromContext } from '../commit-message-text-generation' + +describe('generateBranchNameFromContext', () => { + it('reruns Copilot once on its default model when the plan hides the saved model', async () => { + const calls: string[][] = [] + const result = await generateBranchNameFromContext( + { firstPrompt: 'Fix login flow' }, + { agentId: 'copilot', model: 'gpt-5.4', thinkingLevel: 'low' }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async (plan) => { + calls.push(plan.args) + return calls.length === 1 + ? { + stdout: '', + stderr: 'Error: Model "gpt-5.4" from --model flag is not available.\n', + exitCode: 1, + timedOut: false + } + : { stdout: 'fix-login-flow\n', stderr: '', exitCode: 0, timedOut: false } + } + } + ) + + expect(result).toEqual({ success: true, slug: 'fix-login-flow', agentLabel: 'GitHub Copilot' }) + expect(calls).toHaveLength(2) + expect(calls[0]).toEqual(expect.arrayContaining(['--model', 'gpt-5.4', '--effort', 'low'])) + expect(calls[1]).toEqual( + calls[0].filter((arg) => !['--model', 'gpt-5.4', '--effort', 'low'].includes(arg)) + ) + }) +}) diff --git a/src/main/text-generation/commit-message-text-generation-generated-output.test.ts b/src/main/text-generation/requests/commit-message-text-generation-generated-output.test.ts similarity index 94% rename from src/main/text-generation/commit-message-text-generation-generated-output.test.ts rename to src/main/text-generation/requests/commit-message-text-generation-generated-output.test.ts index 4f75dbaed90..f9f05ba52af 100644 --- a/src/main/text-generation/commit-message-text-generation-generated-output.test.ts +++ b/src/main/text-generation/requests/commit-message-text-generation-generated-output.test.ts @@ -4,13 +4,13 @@ import { describe, expect, it } from 'vitest' import { generateCommitMessageFromContext, generatePullRequestFieldsFromContext -} from './commit-message-text-generation' +} from '../commit-message-text-generation' import { realKimiPrOutput, sourceShapedKimiOutput -} from '../../shared/__fixtures__/kimi-generation-source-shaped' -import '../../shared/source-control/ai/generation/commit-message-agent-output' -import './source-control-agent-failure' +} from '../../../shared/__fixtures__/kimi-generation-source-shaped' +import '../../../shared/source-control/ai/generation/commit-message-agent-output' +import '../failures/source-control-agent-failure' describe('generateCommitMessageFromContext', () => { it.each(['custom', 'kimi', 'kimi-literal'] as const)('%s subject and body', async (source) => { diff --git a/src/main/text-generation/requests/commit-message-text-generation-regression.test.ts b/src/main/text-generation/requests/commit-message-text-generation-regression.test.ts new file mode 100644 index 00000000000..0faff1733a0 --- /dev/null +++ b/src/main/text-generation/requests/commit-message-text-generation-regression.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { generateCommitMessageFromContext } from '../commit-message-text-generation' + +describe('commit-message generation regressions', () => { + it('keeps bounded diagnostic captures out of commit-message results', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M src/policy.ts', + stagedPatch: '+change' + }, + { agentId: 'custom', model: '', customAgentCommand: 'agent' }, + { + kind: 'remote', + cwd: '/remote/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: 'prompt echoed from /Users/private/source/repo', + stderr: 'failed reading /Users/private/source/repo/.env', + exitCode: 1, + timedOut: false + }) + } + ) + + expect(result).toMatchObject({ + success: false, + error: 'agent CLI command failed with code 1: failed reading [path]', + canceled: undefined + }) + expect(JSON.stringify(result)).not.toContain('/Users/private') + expect(result).not.toHaveProperty('failureOutput') + }) +}) diff --git a/src/main/text-generation/requests/conversation-name-generation-request.test.ts b/src/main/text-generation/requests/conversation-name-generation-request.test.ts new file mode 100644 index 00000000000..ee6ce11608a --- /dev/null +++ b/src/main/text-generation/requests/conversation-name-generation-request.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'vitest' +import { generateConversationNameFromContext } from '../commit-message-text-generation' + +describe('generateConversationName', () => { + it.each([ + [`Fix login ${'x'.repeat(5000)}`, `Name this: Fix login ${'x'.repeat(3990)}`], + [ + "Why quote 'This is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.'? Change it and update README.md.", + 'Change it and update README.md.' + ] + ])( + 'delivers bounded template input with a final naming restriction', + async (firstPrompt, body) => { + let prompt = '' + let operation = '' + const result = await generateConversationNameFromContext( + { firstPrompt }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent', + commandInputTemplate: 'Name this: {firstPrompt}' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async (plan, cwd, timeoutMs, requestedOperation) => { + expect(cwd).toBe('/repo') + expect(timeoutMs).toBe(60_000) + prompt = plan.stdinPayload ?? '' + operation = requestedOperation + return { + stdout: 'draft\n# Title: "Fix login flow"\nExtra line', + stderr: '', + exitCode: 0, + timedOut: false + } + } + } + ) + expect(operation).toBe('conversation-name') + expect(prompt).toContain(body) + expect( + prompt.endsWith( + '\n\nThis is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.' + ) + ).toBe(true) + expect(result).toEqual({ success: true, name: 'Fix login flow', agentLabel: 'agent' }) + } + ) + + it('rejects empty output after sanitization', async () => { + const result = await generateConversationNameFromContext( + { firstPrompt: 'Fix login' }, + { agentId: 'custom', model: '', customAgentCommand: 'agent' }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: 'Title: ""', + stderr: '', + exitCode: 0, + timedOut: false + }) + } + ) + expect(result).toMatchObject({ + success: false, + error: 'Generated chat name was empty after sanitization.' + }) + }) +}) diff --git a/src/main/text-generation/conversation-name-generation-request.ts b/src/main/text-generation/requests/conversation-name-generation-request.ts similarity index 78% rename from src/main/text-generation/conversation-name-generation-request.ts rename to src/main/text-generation/requests/conversation-name-generation-request.ts index 022534aa8cc..c9e30df82d5 100644 --- a/src/main/text-generation/conversation-name-generation-request.ts +++ b/src/main/text-generation/requests/conversation-name-generation-request.ts @@ -2,15 +2,15 @@ import { renderConversationNamePrompt, sanitizeGeneratedConversationName, type ConversationNameContext -} from '../../shared/source-control/ai/generation/conversation-name-generation' -import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' -import { captureAgentGenerationFailureOutput } from './agent-failure-output' -import { runGenerationRequest } from './agent-generation-request' +} from '../../../shared/source-control/ai/generation/conversation-name-generation' +import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution' +import { captureAgentGenerationFailureOutput } from '../failures/agent-failure-output' +import { runGenerationRequest } from '../agent-generation-request' import type { CommitMessageGenerationTarget, GenerateConversationNameResult, SpawnSourceControlAgent -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' export async function generateConversationName(input: { context: ConversationNameContext diff --git a/src/main/text-generation/requests/dictation-cleanup-generation-request.ts b/src/main/text-generation/requests/dictation-cleanup-generation-request.ts new file mode 100644 index 00000000000..7f11518ce8b --- /dev/null +++ b/src/main/text-generation/requests/dictation-cleanup-generation-request.ts @@ -0,0 +1,42 @@ +import { + buildDictationCleanupPrompt, + sanitizeDictationCleanupOutput +} from '../../../shared/dictation-cleanup' +import type { DictationTerm } from '../../../shared/dictation-dictionary' +import { renderSourceControlActionCommandTemplate } from '../../../shared/source-control/ai/recipes/source-control-ai-actions' +import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution' +import type { VoiceSettings } from '../../../shared/speech-types' +import { runGenerationRequest } from '../agent-generation-request' +import { spawnSourceControlAgent } from '../execution/source-control-agent-launch' +import type { CommitMessageGenerationTarget } from '../source-control-text-generation-types' + +export type GenerateDictationCleanupResult = + | { success: true; text: string; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + +export async function generateDictationCleanup(input: { + text: string + voice: VoiceSettings | undefined + terms: readonly DictationTerm[] + params: ResolvedSourceControlAiGenerationParams + target: CommitMessageGenerationTarget +}): Promise { + const basePrompt = buildDictationCleanupPrompt(input) + const result = await runGenerationRequest({ + params: input.params, + prompt: renderSourceControlActionCommandTemplate( + input.params.commandInputTemplate ?? '{basePrompt}', + { basePrompt } + ), + target: input.target, + operation: 'dictation-cleanup', + spawnAgent: spawnSourceControlAgent + }) + if (!result.success) { + return { success: false, error: result.error, canceled: result.canceled } + } + const text = sanitizeDictationCleanupOutput(result.rawOutput) + return text + ? { success: true, text, agentLabel: result.agentLabel } + : { success: false, error: `${result.agentLabel ?? input.params.agentId} returned no text.` } +} diff --git a/src/main/text-generation/jira-issue-summary-requests.test.ts b/src/main/text-generation/requests/jira-issue-summary-requests.test.ts similarity index 82% rename from src/main/text-generation/jira-issue-summary-requests.test.ts rename to src/main/text-generation/requests/jira-issue-summary-requests.test.ts index bb9b99b1a1e..cff5c158da7 100644 --- a/src/main/text-generation/jira-issue-summary-requests.test.ts +++ b/src/main/text-generation/requests/jira-issue-summary-requests.test.ts @@ -6,11 +6,13 @@ const mocks = vi.hoisted(() => ({ resolve: vi.fn(), status: vi.fn() })) -vi.mock('../jira/client', () => ({ getStatus: mocks.status })) -vi.mock('./commit-message-agent-environment', () => ({ +vi.mock('../../jira/client', () => ({ getStatus: mocks.status })) +vi.mock('../execution/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: mocks.prepare })) -vi.mock('./commit-message-text-generation', () => ({ resolveTextGenerationParams: mocks.resolve })) +vi.mock('../commit-message-text-generation', () => ({ + resolveCommitMessageSettings: mocks.resolve +})) vi.mock('./jira-issue-summary-text-generation', () => ({ generateJiraIssueSummaryFromContext: mocks.generate, cancelGenerateJiraIssueSummaryLocal: mocks.cancel @@ -19,7 +21,7 @@ import { generateJiraIssueSummaryRequest, cancelJiraIssueSummaryRequest } from './jira-issue-summary-requests' -import { getDefaultSettings } from '../../shared/constants' +import { getDefaultSettings } from '../../../shared/constants' function deferred() { let resolve!: (value: T) => void const promise = new Promise((done) => { @@ -44,21 +46,6 @@ beforeEach(() => { mocks.status.mockReturnValue({ sites: [{ id: 'site-1' }, { id: 'site-2' }] }) }) describe('Jira title host ownership', () => { - it('uses the owning host settings and account environment', async () => { - expect(await generateJiraIssueSummaryRequest(host, 'owner-1', args)).toMatchObject({ - success: true - }) - expect(mocks.resolve).toHaveBeenCalledWith(settings, 'local', 'branchName', null) - expect(mocks.prepare).toHaveBeenCalledWith( - 'custom', - expect.objectContaining({ prepareForCodexLaunch: expect.any(Function) }) - ) - expect(mocks.generate).toHaveBeenCalledWith( - args, - expect.anything(), - expect.objectContaining({ kind: 'local', env: { CODEX_HOME: 'host-codex-home' } }) - ) - }) it('does not launch a replaced request after its environment finishes', async () => { const slow = deferred<{ ok: true }>() mocks.prepare.mockReturnValueOnce(slow.promise) diff --git a/src/main/text-generation/jira-issue-summary-requests.ts b/src/main/text-generation/requests/jira-issue-summary-requests.ts similarity index 89% rename from src/main/text-generation/jira-issue-summary-requests.ts rename to src/main/text-generation/requests/jira-issue-summary-requests.ts index eaff34e6c64..30ccfc094e3 100644 --- a/src/main/text-generation/jira-issue-summary-requests.ts +++ b/src/main/text-generation/requests/jira-issue-summary-requests.ts @@ -1,20 +1,20 @@ import os from 'node:os' -import { LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../shared/source-control/ai/generation/commit-message-host-key' +import { LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../../shared/source-control/ai/generation/commit-message-host-key' import type { JiraIssueSummaryGenerationRequest, JiraIssueSummaryGenerationCancellation, JiraIssueSummaryGenerationResult -} from '../../shared/jira/jira-issue-summary-generation' +} from '../../../shared/jira/jira-issue-summary-generation' import { textGenerationFailure, textGenerationFailureCodeFields -} from '../../shared/text-generation-failure-copy' -import { getStatus } from '../jira/client' +} from '../../../shared/text-generation-failure-copy' +import { getStatus } from '../../jira/client' import { prepareLocalCommitMessageAgentEnv, type CommitMessageAgentEnvironmentResolvers -} from './commit-message-agent-environment' -import { resolveTextGenerationParams } from './commit-message-text-generation' +} from '../execution/commit-message-agent-environment' +import { resolveCommitMessageSettings as resolveTextGenerationParams } from '../commit-message-text-generation' import { cancelGenerateJiraIssueSummaryLocal, generateJiraIssueSummaryFromContext diff --git a/src/main/text-generation/jira-issue-summary-text-generation.ts b/src/main/text-generation/requests/jira-issue-summary-text-generation.ts similarity index 76% rename from src/main/text-generation/jira-issue-summary-text-generation.ts rename to src/main/text-generation/requests/jira-issue-summary-text-generation.ts index 727aa349548..b1915f941fa 100644 --- a/src/main/text-generation/jira-issue-summary-text-generation.ts +++ b/src/main/text-generation/requests/jira-issue-summary-text-generation.ts @@ -3,19 +3,19 @@ import { sanitizeGeneratedJiraIssueSummary, type JiraIssueSummaryGenerationContext, type JiraIssueSummaryGenerationResult -} from '../../shared/jira/jira-issue-summary-generation' -import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' +} from '../../../shared/jira/jira-issue-summary-generation' +import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution' import { textGenerationFailure, textGenerationFailureCodeFields -} from '../../shared/text-generation-failure-copy' -import { spawnSourceControlAgent } from './source-control-agent-launch' -import { cancelLocalGeneration } from './source-control-generation-lanes' -import { runGenerationRequest } from './agent-generation-request' +} from '../../../shared/text-generation-failure-copy' +import { spawnSourceControlAgent } from '../execution/source-control-agent-launch' +import { cancelLocalGeneration } from '../execution/source-control-generation-lanes' +import { runGenerationRequest } from '../agent-generation-request' import type { CommitMessageGenerationTarget, SpawnSourceControlAgent -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' // Source-control templates and instructions do not apply to Jira issue titles. export async function generateJiraIssueSummaryFromContext( diff --git a/src/main/text-generation/source-control-text-generation-requests.ts b/src/main/text-generation/requests/source-control-text-generation-requests.ts similarity index 85% rename from src/main/text-generation/source-control-text-generation-requests.ts rename to src/main/text-generation/requests/source-control-text-generation-requests.ts index 8d87c5b60c5..95c17ae8c67 100644 --- a/src/main/text-generation/source-control-text-generation-requests.ts +++ b/src/main/text-generation/requests/source-control-text-generation-requests.ts @@ -2,43 +2,42 @@ import { buildCommitMessagePrompt, splitGeneratedCommitMessage, type CommitMessageDraftContext -} from '../../shared/source-control/ai/generation/commit-message-generation' +} from '../../../shared/source-control/ai/generation/commit-message-generation' import { buildPullRequestFieldsPrompt, parseGeneratedPullRequestFields, type GeneratedPullRequestFields, type PullRequestDraftContext -} from '../../shared/source-control/ai/generation/pull-request-generation' +} from '../../../shared/source-control/ai/generation/pull-request-generation' import { buildBranchNamePrompt, sanitizeBranchSlug, type BranchNameWorkContext -} from '../../shared/source-control/ai/naming/branch-name-from-work' +} from '../../../shared/source-control/ai/naming/branch-name-from-work' import { cleanGeneratedCommitMessage, stripPrefilledReasoningPreamble -} from '../../shared/source-control/ai/generation/commit-message-agent-output' -import { STAGED_DIFF_BYTE_BUDGET } from '../../shared/source-control/ai/generation/commit-message-prompt' -import { isCustomAgentId } from '../../shared/source-control/ai/generation/commit-message-agent-spec' -import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' -import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' -import { formatLinkedIssueTemplateValue } from '../../shared/source-control/ai/recipes/source-control-ai-action-variables' -import { renderSourceControlActionCommandTemplate } from '../../shared/source-control/ai/recipes/source-control-ai-actions' +} from '../../../shared/source-control/ai/generation/commit-message-agent-output' +import { STAGED_DIFF_BYTE_BUDGET } from '../../../shared/source-control/ai/generation/commit-message-prompt' +import { isCustomAgentId } from '../../../shared/source-control/ai/generation/commit-message-agent-spec' +import { planCommitMessageGeneration } from '../../../shared/source-control/ai/generation/commit-message-plan' +import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution' +import { formatLinkedIssueTemplateValue } from '../../../shared/source-control/ai/recipes/source-control-ai-action-variables' +import { renderSourceControlActionCommandTemplate } from '../../../shared/source-control/ai/recipes/source-control-ai-actions' import { textGenerationFailure, textGenerationFailureCodeFields -} from '../../shared/text-generation-failure-copy' -import { captureAgentGenerationFailureOutput } from './agent-failure-output' -import { commandBackslashMode, runGenerationRequest } from './agent-generation-request' -import { fitsLocalCommandLine } from './source-control-local-process' -export { commandBackslashMode } from './agent-generation-request' +} from '../../../shared/text-generation-failure-copy' +import { captureAgentGenerationFailureOutput } from '../failures/agent-failure-output' +import { commandBackslashMode, runGenerationRequest } from '../agent-generation-request' +import { fitsLocalCommandLine } from '../execution/source-control-command-line-budget' import type { CommitMessageGenerationTarget, GenerateBranchNameResult, GenerateCommitMessageResult, GeneratePullRequestFieldsResult, SpawnSourceControlAgent -} from './source-control-text-generation-types' +} from '../source-control-text-generation-types' type GenerateParams = ResolvedSourceControlAiGenerationParams diff --git a/src/main/text-generation/source-control-agent-launch.test.ts b/src/main/text-generation/source-control-agent-launch.test.ts deleted file mode 100644 index b11df24d2ac..00000000000 --- a/src/main/text-generation/source-control-agent-launch.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import 'node:events' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RunProcess from '@orca/process-host' -import type { ProcessSpec } from '@orca/process-host/process-spec' -import '../provider-process/provider-process-supervisor' -import { generateCommitMessageFromContext } from './commit-message-text-generation' -import './commit-message-text-generation-test-harness' -import './source-control-agent-launch' - -const { spawnProcessMock } = vi.hoisted(() => ({ spawnProcessMock: vi.fn() })) - -vi.mock('@orca/process-host', async (importOriginal) => { - const actual = await importOriginal() - spawnProcessMock.mockImplementation(actual.spawnProcess) - return { ...actual, spawnProcess: spawnProcessMock } -}) - -function lastSpawnSpec(): ProcessSpec { - return spawnProcessMock.mock.calls.at(-1)![0] -} - -function decodedSupervisorSpec(spec: ProcessSpec): Record { - return JSON.parse(Buffer.from(spec.env!.ORCA_PROVIDER_SUPERVISOR_SPEC!, 'base64').toString()) -} - -const folder = mkdtempSync(join(tmpdir(), 'orca-agent-launch-')) -afterAll(() => rmSync(folder, { recursive: true, force: true })) - -beforeEach(() => { - spawnProcessMock.mockClear() -}) - -describe.runIf(process.platform !== 'win32')('supervised agent processes', () => { - it('passes the stdin end through so the agent can answer its request', async () => { - const agent = join(folder, 'echo-agent.cjs') - writeFileSync( - agent, - `let prompt = '' -process.stdin.on('data', (chunk) => (prompt += chunk)) -process.stdin.on('end', () => setTimeout(() => console.log(prompt.includes('README') ? 'Update README' : 'no prompt'), 1200)) -` - ) - - await expect( - generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M README.md', - stagedPatch: '+test' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: `"${process.execPath}" "${agent}"` - }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ success: true, message: 'Update README' }) - expect(lastSpawnSpec().program).toBe(process.execPath) - expect(decodedSupervisorSpec(lastSpawnSpec())).toMatchObject({ - lifetime: 'one-shot' - }) - }) - - it('drops the agent session that launched Orca but keeps assignments in the command', async () => { - const agent = join(folder, 'session-agent.cjs') - writeFileSync( - agent, - `process.stdin.resume() -process.stdin.on('end', () => console.log('Thread ' + (process.env.CODEX_THREAD_ID ?? 'unset') + ', effort ' + process.env.CLAUDE_EFFORT)) -` - ) - vi.stubEnv('CODEX_THREAD_ID', 'parent-thread') - try { - await expect( - generateCommitMessageFromContext( - { branch: 'main', stagedSummary: 'M README.md', stagedPatch: '+test' }, - { - agentId: 'custom', - model: '', - customAgentCommand: `CLAUDE_EFFORT=low "${process.execPath}" "${agent}"` - }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ success: true, message: 'Thread unset, effort low' }) - } finally { - vi.unstubAllEnvs() - } - }) -}) diff --git a/src/main/text-generation/source-control-agent-termination.ts b/src/main/text-generation/source-control-agent-termination.ts deleted file mode 100644 index f0d7f8663b1..00000000000 --- a/src/main/text-generation/source-control-agent-termination.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { stopSupervisedChildProcess } from '../provider-process/supervised-child-process-stop' -import { terminateWindowsProcessTree } from '../pty/process-retirement/windows-process-tree-kill' -import type { SpawnedSourceControlAgentProcess } from './source-control-text-generation-types' - -export const SOURCE_CONTROL_KILL_SITE = 'source-control-text-generation' - -export async function killSourceControlAgentProcess( - child: SpawnedSourceControlAgentProcess -): Promise { - const pid = child.pid - if (!pid) { - return - } - if (child.supervised) { - await stopSupervisedChildProcess(child, { site: SOURCE_CONTROL_KILL_SITE }) - return - } - if (process.platform === 'win32') { - // Tree-walk refusal must not release the home lock having killed nothing; root handle kill cannot hit a recycled PID. - await terminateWindowsProcessTree(pid, { site: SOURCE_CONTROL_KILL_SITE }) - } - try { - child.kill('SIGKILL') - } catch { - // The process may exit between the PID check and kill. - } -} diff --git a/src/main/text-generation/source-control-generation-lanes.ts b/src/main/text-generation/source-control-generation-lanes.ts deleted file mode 100644 index ee6081c738c..00000000000 --- a/src/main/text-generation/source-control-generation-lanes.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { TextGenerationOperation } from './source-control-text-generation-types' - -const cancelTokensByLane = new Map void>() - -export function localGenerationLaneKey(operation: TextGenerationOperation, cwd: string): string { - return `${operation}:local:${cwd}` -} - -export function cancelLocalGeneration(operation: TextGenerationOperation, cwd: string): void { - cancelTokensByLane.get(localGenerationLaneKey(operation, cwd))?.() -} - -export function setLocalGenerationCancelToken(laneKey: string, cancel: () => void): void { - cancelTokensByLane.set(laneKey, cancel) -} - -export function clearLocalGenerationCancelToken(laneKey: string, cancel: () => void): void { - if (cancelTokensByLane.get(laneKey) === cancel) { - cancelTokensByLane.delete(laneKey) - } -} diff --git a/src/main/text-generation/source-control-omp-prompt-file.test.ts b/src/main/text-generation/source-control-omp-prompt-file.test.ts deleted file mode 100644 index 871c5d91dbb..00000000000 --- a/src/main/text-generation/source-control-omp-prompt-file.test.ts +++ /dev/null @@ -1,438 +0,0 @@ -import { spawnProcess } from '@orca/process-host' -import * as agentSpecs from '../../shared/source-control/ai/generation/commit-message-agent-spec' -import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' -import type { SpawnSourceControlAgent } from './source-control-text-generation-types' -import { - generateCommitMessage, - generatePullRequestFields, - generateBranchName -} from './source-control-text-generation-requests' -import { generateConversationName } from './conversation-name-generation-request' -import { generateJiraIssueSummaryFromContext } from './jira-issue-summary-text-generation' - -import { existsSync, mkdtempSync, readFileSync } from 'node:fs' -import { rm } from 'node:fs/promises' -import type * as FsPromises from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' -import { cancelLocalGeneration } from './source-control-generation-lanes' -import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' -import { runLocalSourceControlPlan } from './source-control-local-process' -import { - createMockDiscoveryChild, - withPlatform -} from './commit-message-text-generation-test-harness' - -vi.mock('../pty/process-retirement/windows-process-tree-kill', () => ({ - terminateWindowsProcessTree: vi.fn(async () => true) -})) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, rm: vi.fn(actual.rm) } -}) - -const actualFs = await vi.importActual('node:fs/promises') - -afterEach(() => vi.useRealTimers()) - -// OMP 17.0.5 recorded stdin-only execution: exit 0, empty stdout/stderr, no submitted prompt. -const recordedPrompt = `Name this chat from the user's first request. -Write a short, specific title of at most 48 characters. -Output only the title, with no heading, quotes, or explanation. - -First request: -Trace a lost lighthouse signal. - -Additional instructions: -Return Lighthouse Signal Trace. -` - -it.each(['success', 'failure', 'cancel', 'timeout', 'spawn failure'] as const)( - 'delivers the recorded OMP prompt without stdin and removes the owned file after %s', - async (outcome) => { - vi.useFakeTimers() - const prompt = recordedPrompt + 'x'.repeat(200_000) - const planned = planCommitMessageGeneration({ agentId: 'omp', model: 'default' }, prompt) - if (!planned.ok) { - throw new Error(planned.error) - } - const child = createMockDiscoveryChild() - let promptPath = '' - const execution = withPlatform('win32', () => - runLocalSourceControlPlan({ - plan: planned.plan, - cwd: '/omp-file-test', - env: undefined, - operation: 'conversation-name', - spawnAgent: ({ args }) => { - promptPath = args[planned.plan.promptFile?.argIndex ?? -1]?.slice(1) ?? '' - expect(new TextDecoder().decode(readFileSync(promptPath))).toBe(prompt) - expect(args.join(' ').length).toBeLessThan(1000) - if (outcome === 'spawn failure') { - throw new Error('recorded spawn failure') - } - return child - } - }) - ) - if (outcome === 'success') { - // Like the recorded binary, this child never reads stdin; only the explicit file submits input. - child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace')) - } else if (outcome === 'cancel') { - cancelLocalGeneration('conversation-name', '/omp-file-test') - } else if (outcome === 'timeout') { - await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) - } - if (outcome !== 'spawn failure') { - expect(child.stdin.end).toHaveBeenCalledWith(undefined) - expect(existsSync(promptPath)).toBe(true) - child.emit('close', outcome === 'failure' ? 1 : 0) - } - const result = await execution.result - await execution.processClosed - expect(result.success).toBe(outcome === 'success') - await vi.waitFor(() => expect(existsSync(dirname(promptPath))).toBe(false)) - } -) - -// Pinned OMP17 cli/file-processor.ts:16,49-54,119-122: per-file cap, ordered text decoding. -const attachmentReader = String.raw` -const fs = require('node:fs'); -const args = process.argv.slice(1); -const paths = args.filter(arg => arg.startsWith('@')).map(arg => arg.slice(1)); -const chunks = paths.map(path => fs.readFileSync(path)); -const isImage = bytes => ['GIF87a', 'GIF89a'].includes(bytes.subarray(0, 6).toString()) || - (bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP'); -const fragments = chunks.map(bytes => bytes.length > 5 * 1024 * 1024 - ? '(skipped: too large)' : isImage(bytes) ? '(image instead of text)' : new TextDecoder().decode(bytes)); -let stdin = ''; -process.stdin.setEncoding('utf8'); -process.stdin.on('data', chunk => { stdin += chunk; }); -process.stdin.on('end', () => { - fs.writeFileSync(process.env.OMP_RECEIPT, JSON.stringify({ - paths, sizes: chunks.map(bytes => bytes.length), content: paths.length ? fragments.join('') : stdin, stdin, - message: fragments.map((text, index) => '\n' + text + '\n\n').join('') + args.at(-1) - })); - process.stdout.write(process.env.OMP_OUTPUT); - if (process.env.OMP_EXIT === '7') process.stderr.write('Fixture provider unavailable'); - process.exitCode = Number(process.env.OMP_EXIT); -}); -` - -const contractParams = { - agentId: 'omp', - model: 'generated/model', - thinkingLevel: 'low', - agentCommandOverride: 'OMP_RECIPE_ENV=kept node /configured/prefix/omp.js --model prefix/model', - agentArgs: '--model recipe/model --thinking high -- recipe-message', - commandInputTemplate: 'Saved recipe instruction\n{basePrompt}' -} as const -const contractTarget = { kind: 'local', cwd: tmpdir() } as const -const commitContext = { - branch: 'feature', - stagedSummary: 'signal.ts | 1 +', - stagedPatch: '+ Trace lighthouse signal' -} - -type Consumer = { - label: string - run( - params: ResolvedSourceControlAiGenerationParams, - spawnAgent: SpawnSourceControlAgent - ): Promise - output: string - expected: object -} -const consumers: Consumer[] = [ - { - label: 'commit', - run: (params, spawnAgent) => - generateCommitMessage({ context: commitContext, params, target: contractTarget, spawnAgent }), - output: 'Trace lighthouse signal.\n\nPreserve request bytes\n', - expected: { message: 'Trace lighthouse signal\n\nPreserve request bytes' } - }, - { - label: 'PR fields', - run: (params, spawnAgent) => - generatePullRequestFields({ - context: { - branch: 'feature', - base: 'main', - branchChangedByPreparation: true, - currentTitle: '', - currentBody: '', - currentDraft: false, - commitSummary: 'Trace lighthouse signal', - changeSummary: 'signal.ts', - patch: '+ Trace lighthouse signal' - }, - params, - target: contractTarget, - spawnAgent - }), - output: JSON.stringify({ - base: 'main', - title: 'Trace lighthouse signal.', - body: 'Preserve request bytes\n', - draft: true - }), - expected: { - fields: { - base: 'main', - title: 'Trace lighthouse signal', - body: 'Preserve request bytes', - draft: true - }, - branchChangedByPreparation: true - } - }, - { - label: 'branch slug / folder title', - run: (params, spawnAgent) => - generateBranchName({ - context: { firstPrompt: 'Trace lighthouse signal' }, - params, - target: contractTarget, - spawnAgent - }), - output: 'Trace Lighthouse Signal!', - expected: { slug: 'trace-lighthouse-signal' } - }, - { - label: 'conversation name', - run: (params, spawnAgent) => - generateConversationName({ - context: { firstPrompt: 'Trace lighthouse signal' }, - params, - target: contractTarget, - spawnAgent - }), - output: '# Title: "Trace lighthouse signal"\nextra commentary', - expected: { name: 'Trace lighthouse signal' } - }, - { - label: 'Jira summary', - run: (params, spawnAgent) => - generateJiraIssueSummaryFromContext( - { description: 'Trace lighthouse signal' }, - params, - contractTarget, - spawnAgent - ), - output: '"Trace lighthouse signal"\nextra commentary', - expected: { summary: 'Trace lighthouse signal' } - } -] - -type Receipt = { paths: string[]; sizes: number[]; content: string; stdin: string; message: string } -async function withReader( - output: string, - fail: boolean, - run: (spawnAgent: SpawnSourceControlAgent) => Promise -) { - const directory = mkdtempSync(join(tmpdir(), 'orca-omp-contract-')) - const receiptPath = join(directory, 'receipt.json') - try { - const result = await run((input) => { - expect(input.binary).toBe('node') - expect(input.args.slice(0, 1)).toEqual(['/configured/prefix/omp.js']) - expect(input.args).toContain('recipe/model') - expect(input.args).not.toContain('prefix/model') - expect(input.args).not.toContain('generated/model') - expect(input.args).toContain('high') - expect(input.args).not.toContain('low') - expect(input.args.slice(-2)).toEqual(['--', 'recipe-message']) - expect(input.commandEnv).toEqual({ OMP_RECIPE_ENV: 'kept' }) - return spawnProcess({ - program: process.execPath, - args: ['-e', attachmentReader, '--', ...input.args], - cwd: input.cwd, - env: { - ...process.env, - OMP_RECEIPT: receiptPath, - OMP_OUTPUT: output, - OMP_EXIT: fail ? '7' : '0' - }, - stdio: 'pipe' - }) - }) - const receipt: Receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) - await vi.waitFor(() => { - for (const path of receipt.paths) { - expect(existsSync(dirname(path))).toBe(false) - } - }) - return { result, receipt } - } finally { - await rm(directory, { recursive: true, force: true }) - } -} - -it.each(consumers)( - 'preserves $label output and failure classification across stdin/file transport', - async (consumer) => { - const spec = agentSpecs.getCommitMessageAgentSpec('omp') - if (!spec) { - throw new Error('Missing OMP spec') - } - for (const fail of [false, true]) { - const delivered = await withReader(consumer.output, fail, (spawn) => - consumer.run(contractParams, spawn) - ) - expect(delivered.receipt.paths).toHaveLength(1) - expect(delivered.receipt.stdin).toBe('') - expect(delivered.receipt.message.endsWith('recipe-message')).toBe(true) - expect(delivered.receipt.content).toContain('Trace lighthouse signal') - expect(delivered.receipt.content.includes('Saved recipe instruction')).toBe( - consumer.label !== 'Jira summary' - ) - if (fail) { - expect(delivered.result).toMatchObject({ - success: false, - error: expect.stringContaining('OMP CLI command failed with code 7') - }) - } else { - expect(delivered.result).toMatchObject({ - success: true, - agentLabel: 'OMP', - ...consumer.expected - }) - } - const legacy = vi.spyOn(agentSpecs, 'getCommitMessageAgentSpec').mockReturnValue({ - ...spec, - promptDelivery: 'stdin', - buildArgs: (params) => spec.buildArgs(params).slice(0, -1) - }) - try { - const previous = await withReader(consumer.output, fail, (spawn) => - consumer.run(contractParams, spawn) - ) - expect(previous.receipt.paths).toHaveLength(0) - expect(previous.receipt.content).toBe(delivered.receipt.content) - expect(previous.result).toEqual(delivered.result) - } finally { - legacy.mockRestore() - } - } - } -) - -it.each(['below', 'at', 'above', 'multibyte', 'BOM run', 'GIF', 'RIFF', 'internal magic'] as const)( - 'delivers complete text recipe content: %s', - async (boundary) => { - const cap = 5 * 1024 * 1024 - const payloadCap = cap - 3 - const patches = { - below: () => 'x'.repeat(payloadCap - 1), - at: () => 'x'.repeat(payloadCap), - above: () => 'x'.repeat(cap + 1), - multibyte: () => - `${'x'.repeat(payloadCap - 1)}🌊界é${'界'.repeat(Math.ceil(cap / 3))}\uFEFFEND`, - 'BOM run': () => `${'\uFEFF'.repeat(Math.ceil(cap / 3))}Preserve every BOM`, - GIF: () => 'GIF89a is the header this change handles. Preserve this as text.', - RIFF: () => 'RIFFxxxxWEBP is the signature this change handles. Preserve this as text.', - 'internal magic': () => `${'x'.repeat(payloadCap)}GIF89a preserve this boundary as text.` - } - const patch = patches[boundary]() - const { result, receipt } = await withReader( - 'Preserve the complete request', - false, - (spawnAgent) => - generateCommitMessage({ - context: { ...commitContext, stagedPatch: patch }, - params: { ...contractParams, commandInputTemplate: '{stagedPatch}' }, - target: contractTarget, - spawnAgent - }) - ) - expect(result).toMatchObject({ success: true, message: 'Preserve the complete request' }) - expect(receipt.content).toBe(patch) - expect(receipt.sizes.every((size) => size <= cap)).toBe(true) - expect(receipt.paths).toHaveLength( - boundary === 'multibyte' - ? 3 - : ['above', 'BOM run', 'internal magic'].includes(boundary) - ? 2 - : 1 - ) - if (boundary === 'at') { - expect(receipt.sizes).toEqual([cap]) - } - } -) - -it.each(['success', 'spawn failure', 'permanent failure'] as const)( - 'settles independently of bounded async cleanup after %s', - async (outcome) => { - const originalPlatform = process.platform - const rmMock = vi.mocked(rm) - const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) - const locked = Object.assign(new Error('EPERM: prompt handle held'), { code: 'EPERM' }) - let directory = '' - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - rmMock.mockClear() - rmMock.mockImplementationOnce(async () => { - throw locked - }) - if (outcome === 'permanent failure') { - rmMock.mockRejectedValue(locked) - } - try { - const planned = planCommitMessageGeneration( - { agentId: 'omp', model: 'default' }, - recordedPrompt - ) - if (!planned.ok) { - throw new Error(planned.error) - } - const child = createMockDiscoveryChild() - const execution = runLocalSourceControlPlan({ - plan: planned.plan, - cwd: '/omp-cleanup', - env: undefined, - operation: 'conversation-name', - spawnAgent: ({ args }) => { - directory = dirname(args[planned.plan.promptFile?.argIndex ?? -1].slice(1)) - if (outcome === 'spawn failure') { - throw new Error('Fixture spawn failure') - } - return child - } - }) - if (outcome !== 'spawn failure') { - child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace')) - child.emit('close', 0) - } - expect((await execution.result).success).toBe(outcome !== 'spawn failure') - await execution.processClosed - expect(rmMock).toHaveBeenCalledTimes(1) - expect(existsSync(directory)).toBe(true) - if (outcome === 'permanent failure') { - await vi.waitFor( - () => - expect(errors).toHaveBeenCalledWith( - '[commit-message] Failed to remove generation prompt:', - locked - ), - { timeout: 5000 } - ) - expect(rmMock).toHaveBeenCalledTimes(5) - expect(errors).toHaveBeenCalledTimes(1) - expect(existsSync(directory)).toBe(true) - } else { - await vi.waitFor(() => expect(existsSync(directory)).toBe(false), { timeout: 2000 }) - expect(rmMock).toHaveBeenCalledTimes(2) - } - } finally { - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) - rmMock.mockImplementation(actualFs.rm) - if (directory) { - await actualFs.rm(directory, { recursive: true, force: true }) - } - errors.mockRestore() - } - } -) diff --git a/src/main/text-generation/source-control-text-generation-types.ts b/src/main/text-generation/source-control-text-generation-types.ts index bf51fcd19b9..3d21553f4b8 100644 --- a/src/main/text-generation/source-control-text-generation-types.ts +++ b/src/main/text-generation/source-control-text-generation-types.ts @@ -1,6 +1,6 @@ import type { AgentSessionUnavailable } from '../../shared/agent-session/agent-session-availability' import type { spawnProcess } from '@orca/process-host' -import type { AgentGenerationFailureOutput } from './agent-failure-output' +import type { AgentGenerationFailureOutput } from './failures/agent-failure-output' import type { CommitMessageAgentCapability, CommitMessageModelCapability @@ -50,9 +50,10 @@ export type TextGenerationOperation = | 'branch-name' | 'jira-issue-summary' | 'conversation-name' + | 'dictation-cleanup' export type CommitMessageGenerationTarget = - | { kind: 'local'; cwd: string; env?: NodeJS.ProcessEnv; wslDistro?: string } + | { kind: 'local'; cwd: string; env?: NodeJS.ProcessEnv; wslDistro?: string; laneId?: string } | { kind: 'remote' cwd: string @@ -126,6 +127,7 @@ export type LocalSourceControlPlanInput = { cwd: string env: NodeJS.ProcessEnv | undefined operation: TextGenerationOperation + laneId?: string wslDistro?: string spawnAgent: SpawnSourceControlAgent timeoutMs?: number diff --git a/src/main/text-generation/source-control-wsl-launch.test.ts b/src/main/text-generation/source-control-wsl-launch.test.ts deleted file mode 100644 index ae17df2abcc..00000000000 --- a/src/main/text-generation/source-control-wsl-launch.test.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { spawnProcess } from '@orca/process-host' -import type * as ChildProcess from 'node:child_process' -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, realpathSync } from 'node:fs' -import { rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, it, vi, afterEach } from 'vitest' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import '../../shared/windows-command-line-budget' -import { prepareWslPrompt } from './source-control-prompt-files' -import { producePromptRecords } from './source-control-prompt-producer' -import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' -import { withPlatform } from './commit-message-text-generation-test-harness' -import { spawnSourceControlAgent } from './source-control-agent-launch' -import './source-control-local-generation' -import { resolveCommand } from '../git/command-runner/host-routing/wsl-command-resolution' - -const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) -vi.mock('node:child_process', async (original) => { - const actual = await original() - spawnMock.mockImplementation(actual.spawn) - return { ...actual, spawn: spawnMock } -}) -vi.mock('../wsl/discovery/wsl-background-distro-gate', () => ({ noteWslDistroLaunched: vi.fn() })) -const nativeSpawn = (await vi.importActual('node:child_process')).spawn -afterEach(() => { - spawnMock.mockReset().mockImplementation(nativeSpawn) -}) -function planned(agentId: 'omp' | 'codex' = 'omp') { - const result = planCommitMessageGeneration( - { - agentId, - model: 'default', - agentCommandOverride: 'lower=recipe LOWER=UPPER omp --model prefix/model', - agentArgs: '--thinking high --mode text @user.txt -- recipe-message' - }, - 'request' - ) - if (!result.ok) { - throw new Error(result.error) - } - return result.plan -} - -it.skipIf(process.platform === 'win32')( - 'clears profile-restored hook identity after login while preserving shell function commands', - async () => { - const directory = realpathSync(mkdtempSync(join(tmpdir(), 'orca-wsl-hook-isolation-'))) - const profile = join(directory, 'rc') - const shell = join(directory, 'bash') - const reader = join(directory, 'reader.cjs') - writeFileSync( - shell, - `#!/bin/sh\nexec /bin/bash --noprofile --rcfile ${quotePosixShell(profile)} -ic "$2"\n`, - { mode: 0o700 } - ) - writeFileSync( - join(directory, 'getent'), - `#!/bin/sh\nprintf '%s\\n' ${quotePosixShell(`user:x:1:1:User:${directory}:${shell}`)}\n`, - { mode: 0o700 } - ) - writeFileSync( - profile, - `export ORCA_PANE_KEY=profile-pane ORCA_AGENT_PANE=profile-pane ORCA_AGENT_HOOK_PORT=54321 ORCA_AGENT_HOOKS_DISABLED=0 -export CODEX_HOME=profile-managed-home -review_agent() { ${quotePosixShell(process.execPath)} ${quotePosixShell(reader)} "$@"; } -` - ) - writeFileSync( - reader, - `console.log(JSON.stringify({ - pane: process.env.ORCA_PANE_KEY ?? null, - alias: process.env.ORCA_AGENT_PANE ?? null, - port: process.env.ORCA_AGENT_HOOK_PORT ?? null, - disabled: process.env.ORCA_AGENT_HOOKS_DISABLED, - home: process.env.CODEX_HOME, - args: process.argv.slice(2) -})) -` - ) - // Run the real guest login command locally; only replace the Windows executable boundary. - spawnMock.mockImplementationOnce((_program, args, options) => - nativeSpawn('/bin/sh', ['-c', args.at(-1)], options) - ) - try { - const child = withPlatform('win32', () => - spawnSourceControlAgent({ - binary: 'review_agent', - args: ['literal $HOME'], - wslDistro: 'Review', - env: { - ...process.env, - HOME: directory, - SHELL: shell, - PATH: `${directory}:${process.env.PATH}` - }, - stdinMode: 'pipe', - useCwdForNative: true - }) - ) - let stdout = '' - let stderr = '' - child.stdout?.on('data', (chunk) => (stdout += chunk)) - child.stderr?.on('data', (chunk) => (stderr += chunk)) - const closed = new Promise((resolve, reject) => { - child.on('error', reject) - child.on('close', resolve) - }) - child.stdin?.end() - expect(await closed, stderr).toBe(0) - expect(JSON.parse(stdout)).toEqual({ - pane: null, - alias: null, - port: null, - disabled: '1', - home: 'profile-managed-home', - args: ['literal $HOME'] - }) - } finally { - await rm(directory, { recursive: true, force: true }) - } - } -) - -it.each([false, true])( - 'prepares before hostile profiles and preserves login invocation/cwd/env (assigned=%s)', - async (assigned) => { - const directory = realpathSync(mkdtempSync(join(tmpdir(), 'orca-c3-profiles-'))) - const repoPath = join(directory, 'repo') - const startup = join(directory, 'startup') - const changed = join(directory, 'profile-cwd') - const reportPath = join(directory, 'report.json') - if (!assigned) { - mkdirSync(repoPath) - } - mkdirSync(startup) - mkdirSync(changed) - const shell = join(directory, 'bash') - const profile = join(directory, 'rc') - writeFileSync( - shell, - `#!/bin/sh\nexec /bin/bash --noprofile --rcfile ${quotePosixShell(profile)} -ic "$2"\n`, - { mode: 0o700 } - ) - writeFileSync( - join(directory, 'getent'), - `#!/bin/sh\nprintf '%s\\n' ${quotePosixShell(`user:x:1:1:User:${directory}:${shell}`)}\n`, - { mode: 0o700 } - ) - writeFileSync( - join(directory, '.profile'), - `export PATH=${quotePosixShell(directory)}:"$PATH"\n` - ) - writeFileSync( - profile, - ` -export STARTUP_CWD="$PWD" -export PROFILE_LOWER="$lower" -if IFS= read -r stolen; then export STOLEN=yes; else export STOLEN=no; fi -alias mkdir='mkdir -pv' -alias printf='printf CORRUPTED' -set -C -command mkdir -p ${quotePosixShell(repoPath)} -cd ${quotePosixShell(changed)} -omp() { ${quotePosixShell(process.execPath)} ${quotePosixShell(join(directory, 'reader.cjs'))} "$@"; } -` - ) - writeFileSync( - join(directory, 'reader.cjs'), - String.raw` -const fs=require('node:fs'); const path=process.argv.find(arg=>arg.startsWith('@/tmp/')).slice(1); -fs.writeFileSync(process.env.REPORT, JSON.stringify({startup:process.env.STARTUP_CWD,cwd:process.cwd(),stolen:process.env.STOLEN,profileLower:process.env.PROFILE_LOWER,lower:process.env.lower,content:new TextDecoder().decode(fs.readFileSync(path)),stdin:fs.readFileSync(0).length,mask:process.umask()})); -` - ) - const request = prepareWslPrompt(planned(), 'Actual') - // Use the actual resolved native cwd and original wrapper, without starting a guest on this Mac. - const original = withPlatform('win32', () => - resolveCommand( - assigned ? '/usr/bin/env' : 'omp', - assigned - ? [ - 'lower=recipe', - 'LOWER=UPPER', - process.execPath, - join(directory, 'reader.cjs'), - ...request.plan.args - ] - : request.plan.args, - `\\\\wsl.localhost\\Actual${repoPath.replaceAll('/', '\\')}`, - undefined, - { useWslLoginShell: true } - ) - ) - const child = spawnProcess({ - program: '/bin/sh', - args: [ - '-c', - request.preparation.script, - 'fixture', - ...request.preparation.args, - ...original.args.slice(3) - ], - cwd: startup, - env: { ...process.env, HOME: directory, SHELL: shell, REPORT: reportPath, lower: 'base' }, - stdio: 'pipe' - }) - child.stdin.on('error', () => {}) - const stop = new AbortController() - const closed = new Promise((resolve, reject) => { - child.on('close', resolve) - child.on('error', reject) - }) - child.stderr.on('data', (chunk) => { - if (request.observe(chunk)) { - void producePromptRecords( - child.stdin, - request.records(), - stop.signal, - () => !stop.signal.aborted - ) - } - }) - try { - expect(await closed).toBe(0) - const receipt = JSON.parse(readFileSync(reportPath, 'utf8')) - expect(receipt).toMatchObject({ - startup, - cwd: repoPath, - stolen: 'no', - profileLower: 'base', - lower: assigned ? 'recipe' : 'base', - content: 'request', - stdin: 0 - }) - expect(receipt.mask).toBe(process.umask()) - } finally { - stop.abort() - await rm(`/tmp/orca-generation-${request.preparation.args[0]}`, { - recursive: true, - force: true - }) - await rm(directory, { recursive: true, force: true }) - } - } -) diff --git a/src/main/text-generation/source-control-wsl-prompt.test.ts b/src/main/text-generation/source-control-wsl-prompt.test.ts deleted file mode 100644 index 87c5a211844..00000000000 --- a/src/main/text-generation/source-control-wsl-prompt.test.ts +++ /dev/null @@ -1,582 +0,0 @@ -import { spawnProcess } from '@orca/process-host' -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { rm } from 'node:fs/promises' -import { join } from 'node:path' -import { Writable } from 'node:stream' -import { afterEach, expect, it, vi } from 'vitest' -import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' -import { prepareWslPrompt } from './source-control-prompt-files' -import { producePromptRecords } from './source-control-prompt-producer' -import { runLocalSourceControlPlan } from './source-control-local-process' -import { cancelLocalGeneration } from './source-control-generation-lanes' -import { - MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES, - SOURCE_CONTROL_GENERATION_TIMEOUT_MS -} from './source-control-generation-limits' -import { - withPlatform, - createMockDiscoveryChild -} from './commit-message-text-generation-test-harness' -import type { SourceControlAgentSpawnInput } from './source-control-text-generation-types' -import type * as Removal from '../../shared/windows-transient-lock-removal' - -const { removeTreeMock } = vi.hoisted(() => ({ removeTreeMock: vi.fn(async () => {}) })) -vi.mock('../../shared/windows-transient-lock-removal', async (original) => ({ - ...(await original()), - removeTree: removeTreeMock -})) -vi.mock('../pty/process-retirement/windows-process-tree-kill', () => ({ - terminateWindowsProcessTree: vi.fn(async () => true) -})) -vi.mock('../wsl/discovery/wsl-background-distro-gate', () => ({ noteWslDistroLaunched: vi.fn() })) - -afterEach(() => { - vi.useRealTimers() - removeTreeMock.mockReset() - removeTreeMock.mockResolvedValue(undefined) -}) - -const cwd = '\\\\wsl.localhost\\Actual\\home\\dev\\repo' -function plan(content = 'sensitive request') { - const planned = planCommitMessageGeneration({ agentId: 'omp', model: 'default' }, content) - if (!planned.ok) { - throw new Error(planned.error) - } - return planned.plan -} -function start(child = createMockDiscoveryChild(), content?: string) { - let launch: SourceControlAgentSpawnInput | undefined - const execution = withPlatform('win32', () => - runLocalSourceControlPlan({ - plan: plan(content), - cwd, - wslDistro: 'Wrong', - env: undefined, - operation: 'conversation-name', - spawnAgent: (input) => { - launch = input - return child - } - }) - ) - const nonce = launch?.preparation?.args[0] - if (!nonce) { - throw new Error('Expected preparation') - } - return { child, launch, nonce, execution, proof: `ORCA_GENERATION_READY:${nonce}\n` } -} -function close(child: ReturnType, code = 0) { - child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace')) - child.emit('exit', code) - child.emit('close', code) -} - -it('waits for fragmented exact proof, streams once and cleans only the actual guest after terminal', async () => { - const { child, launch, nonce, execution, proof } = start() - const writes: string[] = [] - child.stdin.on('data', (chunk) => writes.push(chunk.toString())) - expect(launch?.wslDistro).toBe('Actual') - expect(launch?.args).toContain(`@/tmp/orca-generation-${nonce}/prompt-1.txt`) - expect(child.stdin.end).not.toHaveBeenCalled() - child.stderr.emit('data', Buffer.from(`${proof.trim()}WRONG\n${'x'.repeat(100_000)}\n`)) - child.stderr.emit('data', Buffer.from(proof.slice(0, 17))) - expect(writes).toEqual([]) - child.stderr.emit('data', Buffer.from(proof.slice(17))) - child.stderr.emit('data', Buffer.from(proof)) - expect(writes.join('')).toBe(`A${nonce}\nDsensitive request\nF${nonce}:1\nX${nonce}\n`) - expect(removeTreeMock).not.toHaveBeenCalled() - close(child) - expect(await execution.result).toMatchObject({ success: true }) - await execution.processClosed - expect(removeTreeMock).toHaveBeenCalledExactlyOnceWith( - `\\\\wsl.localhost\\Actual\\tmp\\orca-generation-${nonce}` - ) - child.stderr.emit('data', Buffer.from(proof)) - expect(removeTreeMock).toHaveBeenCalledTimes(1) -}) - -it.each(['cancel', 'deadline', 'exit', 'overflow', 'stdin-error', 'stdin-close'] as const)( - 'stops pending input on %s, and late proof only cleans without reopening result', - async (route) => { - vi.useFakeTimers() - const { child, execution, proof } = start() - const writes = vi.spyOn(child.stdin, 'write') - if (route === 'cancel') { - cancelLocalGeneration('conversation-name', cwd) - } - if (route === 'deadline') { - await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) - } - if (route === 'exit') { - close(child) - } - if (route === 'overflow') { - child.stdout.emit('data', Buffer.alloc(MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES + 1)) - } - if (route === 'stdin-error') { - child.stdin.emit('error', new Error('EPIPE')) - } - if (route === 'stdin-close') { - child.stdin.emit('close') - } - child.stderr.emit('data', Buffer.from(proof)) - expect(writes).not.toHaveBeenCalled() - close(child) - await execution.result - await execution.processClosed - expect(removeTreeMock).toHaveBeenCalledTimes(1) - child.stdin.emit('error', new Error('late EPIPE')) - } -) - -it.each(['cancel', 'deadline', 'exit', 'error', 'close', 'overflow'] as const)( - 'releases a never-draining producer on %s without final authorization', - async (route) => { - vi.useFakeTimers() - const { child, execution, proof, nonce } = start(undefined, 'x'.repeat(50_000)) - const write = vi.spyOn(child.stdin, 'write').mockReturnValue(false) - child.stderr.emit('data', Buffer.from(proof)) - expect(write).toHaveBeenCalledExactlyOnceWith(`A${nonce}\n`) - if (route === 'cancel') { - cancelLocalGeneration('conversation-name', cwd) - } - if (route === 'deadline') { - await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) - } - if (route === 'exit') { - child.emit('exit', 1) - } - if (route === 'error') { - child.stdin.emit('error', new Error('EPIPE')) - } - if (route === 'close') { - child.stdin.emit('close') - } - if (route === 'overflow') { - child.stderr.emit('data', Buffer.alloc(MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES + 1)) - } - await Promise.resolve() - child.stdin.emit('drain') - close(child, 1) - await execution.result - await execution.processClosed - expect(write).toHaveBeenCalledTimes(1) - expect(child.stdin.listenerCount('drain')).toBe(0) - expect(removeTreeMock).toHaveBeenCalledTimes(1) - } -) - -it.each(['missing-proof', 'spawn', 'no-pid', 'missing-stdin'] as const)( - 'settles %s without invented ownership', - async (route) => { - vi.useFakeTimers() - const child = createMockDiscoveryChild() - if (route === 'missing-stdin') { - Object.defineProperty(child, 'stdin', { value: null }) - } - if (route === 'no-pid') { - Object.defineProperty(child, 'pid', { value: undefined }) - } - const execution = withPlatform('win32', () => - runLocalSourceControlPlan({ - plan: plan(), - cwd, - env: undefined, - operation: 'conversation-name', - spawnAgent: () => { - if (route === 'spawn') { - throw new Error('spawn denied') - } - return child - } - }) - ) - if (route === 'no-pid') { - child.emit('error', Object.assign(new Error('not found'), { code: 'ENOENT' })) - } - if (route === 'missing-proof') { - await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) - } - if (route !== 'spawn' && route !== 'no-pid') { - close(child, 1) - } - expect(await execution.result).toMatchObject({ success: false }) - await execution.processClosed - expect(removeTreeMock).not.toHaveBeenCalled() - } -) - -it.each(['pending', 'rejected'] as const)( - 'never gates either promise on %s cleanup, even proof after processClosed', - async (outcome) => { - removeTreeMock.mockImplementation(() => - outcome === 'pending' ? new Promise(() => {}) : Promise.reject(new Error('share unavailable')) - ) - const log = vi.spyOn(console, 'error').mockImplementation(() => {}) - try { - const { child, execution, proof } = start() - close(child) - expect(await execution.result).toMatchObject({ success: true }) - await execution.processClosed - child.stderr.emit('data', Buffer.from(proof)) - child.stderr.emit('data', Buffer.from(proof)) - expect(removeTreeMock).toHaveBeenCalledTimes(1) - expect(child.stdin.end).not.toHaveBeenCalled() - await Promise.resolve() - } finally { - log.mockRestore() - } - } -) - -const tricky = `${Array.from({ length: 128 }, (_, i) => String.fromCharCode(i)).join('')}\\c\\012\r\n'!%$\`🌊界\ud800` - -async function shellFixture( - content: string, - controls?: (records: string[], nonce: string) => string[], - setup?: (directory: string) => void, - onProof?: (directory: string) => void -) { - const guest = prepareWslPrompt(plan(content), 'Actual') - const [nonce] = guest.preparation.args - const directory = `/tmp/orca-generation-${nonce}` - setup?.(directory) - const child = spawnProcess({ - program: '/bin/sh', - args: [ - '-c', - guest.preparation.script, - 'fixture', - ...guest.preparation.args, - process.execPath, - '-e', - String.raw` -const fs = require('node:fs'); -const paths = process.argv.slice(1).map(arg => arg.slice(1)); -const files = paths.map(path => fs.readFileSync(path)); -process.stdout.write(JSON.stringify({ content: Buffer.concat(files.map(file => Buffer.from(new TextDecoder().decode(file)))).toString('base64'), - sizes: files.map(file => file.length), modes: paths.map(path => fs.statSync(path).mode & 511), directory: fs.statSync(process.env.FIXTURE_DIRECTORY).mode & 511, - eof: require('node:fs').readFileSync(0).length })); -`, - '--', - ...guest.plan.args.filter((arg) => arg.startsWith('@')) - ], - stdio: 'pipe', - env: { ...process.env, FIXTURE_DIRECTORY: directory } - }) - let stdout = '' - let stderr = '' - child.stdout.on('data', (bytes) => { - stdout += bytes - }) - const finished = new Promise((resolve, reject) => { - child.once('close', resolve) - child.once('error', reject) - }) - child.stdin.on('error', () => {}) - child.stderr.on('data', (chunk) => { - stderr += chunk - if (guest.observe(chunk)) { - onProof?.(directory) - const records = [...guest.records()] - child.stdin.end((controls ? controls(records, nonce) : records).join('')) - } - }) - try { - const code = await finished - return { - code, - stdout, - stderr, - directory, - existed: existsSync(directory), - sentinel: existsSync(join(directory, 'sentinel')) - ? readFileSync(join(directory, 'sentinel'), 'utf8') - : null - } - } finally { - await rm(directory, { recursive: true, force: true }) - } -} - -it.each(['', tricky.repeat(12), `${'x'.repeat(5 * 1024 * 1024 - 4)}🌊GIF89a${tricky}`])( - 'materializes exact native text with private modes across encoding and file boundaries', - async (content) => { - const result = await shellFixture(content) - expect(result.code).toBe(0) - const receipt = JSON.parse(result.stdout) - expect(Buffer.from(receipt.content, 'base64').toString()).toBe(Buffer.from(content).toString()) - expect(receipt.modes.every((mode: number) => mode === 0o600)).toBe(true) - expect(receipt.directory).toBe(0o700) - expect(receipt.eof).toBe(0) - expect(receipt.sizes.every((size: number) => size <= 5 * 1024 * 1024)).toBe(true) - expect(result.existed).toBe(true) - } -) - -it.each([ - 'collision', - 'partial-data', - 'wrong-end', - 'missing-end', - 'partial-execute', - 'extra-data', - 'wrong-ack' -] as const)('does not execute on %s, and never adopts/deletes a collision', async (route) => { - const result = await shellFixture( - 'private data', - (records, nonce) => { - if (route === 'partial-data') { - return [`A${nonce}\nDpartial`] - } - if (route === 'wrong-end') { - return records.map((record) => (record.startsWith('F') ? `F${nonce}:2\n` : record)) - } - if (route === 'missing-end') { - return records.filter((record) => !record.startsWith('F')) - } - if (route === 'partial-execute') { - return records.map((record) => (record.startsWith('X') ? record.trim() : record)) - } - if (route === 'extra-data') { - return [...records.slice(0, -1), 'Dextra\n', ...records.slice(-1)] - } - if (route === 'wrong-ack') { - return ['Ano\n'] - } - return records - }, - (directory) => { - if (route === 'collision') { - mkdirSync(directory) - writeFileSync(join(directory, 'sentinel'), 'untouched') - } - } - ) - expect(result.code).not.toBe(0) - expect(result.stdout).toBe('') - if (route === 'collision') { - expect(result.stderr).not.toContain('ORCA_GENERATION_READY:') - expect(result.sentinel).toBe('untouched') - } - if (route === 'wrong-ack') { - expect(result.existed).toBe(false) - } -}) - -it.each([false, true])( - 'bounds real producer work at N and 10N (backpressure=%s)', - async (backpressure) => { - const results: number[] = [] - for (const size of [20_000, 200_000]) { - const guest = prepareWslPrompt( - plan(tricky.repeat(Math.ceil(size / tricky.length)).slice(0, size)), - 'Actual' - ) - let writes = 0 - let maxRecord = 0 - let pending = 0 - let maxPending = 0 - let maxQueued = 0 - const stream = new Writable({ - highWaterMark: 2048, - write(chunk, _encoding, callback) { - writes++ - maxRecord = Math.max(maxRecord, chunk.length) - maxPending = Math.max(maxPending, ++pending) - const complete = () => { - maxQueued = Math.max(maxQueued, stream.writableLength) - pending-- - callback() - } - if (backpressure) { - setImmediate(complete) - } else { - complete() - } - } - }) - let yieldedAt = 0 - setImmediate(() => { - yieldedAt = writes - }) - const finished = new Promise((resolve) => stream.once('finish', resolve)) - await producePromptRecords(stream, guest.records(), new AbortController().signal, () => true) - await finished - expect(maxQueued).toBeLessThanOrEqual(2048 + 1026) - expect(yieldedAt).toBeGreaterThan(0) - expect(yieldedAt).toBeLessThan(writes) - expect(maxRecord).toBeLessThanOrEqual(1026) - expect(maxPending).toBe(1) - results.push(writes) - } - expect(results[1]).toBeLessThanOrEqual(results[0] * 10 + 10) - expect(results[1]).toBeGreaterThan(results[0] * 8) - } -) - -it('fails a real post-proof storage redirect without running a partial request', async () => { - const result = await shellFixture('private data', undefined, undefined, (directory) => - mkdirSync(join(directory, 'prompt-1.txt')) - ) - expect(result.code).not.toBe(0) - expect(result.stdout).toBe('') - expect(result.existed).toBe(true) -}) - -it.each([ - { boundary: 'data', stopping: 'cancel' }, - { boundary: 'final', stopping: 'cancel' }, - { boundary: 'data', stopping: 'deadline' }, - { boundary: 'final', stopping: 'deadline' } -] as const)( - 'does not authorize after $stopping at $boundary write continuation', - async ({ boundary, stopping }) => { - vi.useFakeTimers() - const { child, execution, proof, nonce } = start() - const writes: string[] = [] - vi.spyOn(child.stdin, 'write').mockImplementation((chunk) => { - const record = String(chunk) - writes.push(record) - if (record.startsWith(boundary === 'data' ? 'D' : 'F')) { - if (stopping === 'cancel') { - cancelLocalGeneration('conversation-name', cwd) - } else { - vi.advanceTimersByTime(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) - } - } - return true - }) - child.stderr.emit('data', Buffer.from(proof)) - close(child) - expect(await execution.result).toMatchObject( - stopping === 'cancel' - ? { success: false, canceled: true } - : { success: false, error: 'Generation timed out after 60s.' } - ) - await execution.processClosed - expect(writes).not.toContain(`X${nonce}\n`) - } -) - -it.each(['success', 'nonzero', 'empty', 'storage', 'pipe-close'] as const)( - 'runs the production attempt through real private shell preparation and %s', - async (outcome) => { - let directory = '' - let actualPipeError = false - const execution = withPlatform('win32', () => - runLocalSourceControlPlan({ - plan: plan(tricky.repeat(40)), - cwd, - env: undefined, - operation: 'conversation-name', - spawnAgent: (input) => { - const preparation = input.preparation - if (!preparation) { - throw new Error('Missing preparation') - } - directory = `/tmp/orca-generation-${preparation.args[0]}` - const argv = - outcome === 'pipe-close' - ? [ - '-c', - `exec 0<&-; printf 'ORCA_GENERATION_READY:%s\\n' "$1" >&2; sleep 0.1`, - 'fixture', - preparation.args[0] - ] - : [ - '-c', - preparation.script, - 'fixture', - ...preparation.args, - '/bin/sh', - '-c', - outcome === 'empty' - ? ':' - : `printf '%s' 'Useful name'; exit ${outcome === 'nonzero' ? 7 : 0}` - ] - const child = withPlatform('darwin', () => - spawnProcess({ program: '/bin/sh', args: argv, stdio: 'pipe' }) - ) - child.stdin.on('error', (error) => { - actualPipeError ||= 'code' in error && error.code === 'EPIPE' - }) - if (outcome === 'storage') { - child.stderr.once('data', () => mkdirSync(join(directory, 'prompt-1.txt'))) - } - return child - } - }) - ) - try { - const result = await execution.result - await execution.processClosed - expect(result.success).toBe(outcome === 'success') - expect(removeTreeMock).toHaveBeenCalledTimes(1) - if (outcome === 'pipe-close') { - expect(actualPipeError).toBe(true) - } - if (outcome === 'success') { - const file = readFileSync(join(directory, 'prompt-1.txt')) - expect(new TextDecoder().decode(file)).toBe(Buffer.from(tricky.repeat(40)).toString()) - } - } finally { - if (directory) { - await rm(directory, { recursive: true, force: true }) - } - } - } -) - -it('delivers a plain UTF-8 policy module and preserves the stdin task after guest materialization', async () => { - const guest = prepareWslPrompt( - { - binary: process.execPath, - args: ['{module}'], - label: 'Policy fixture', - stdinPayload: 'Name this chat 🌊\nlast line', - taskFiles: [ - { name: 'task-policy.mjs', content: 'export const text = "policy 🌊"\n', argIndex: 0 } - ] - }, - 'Actual' - ) - const directory = `/tmp/orca-generation-${guest.preparation.args[0]}` - const child = spawnProcess({ - program: '/bin/sh', - args: [ - '-c', - guest.preparation.script, - 'fixture', - ...guest.preparation.args, - process.execPath, - '-e', - `const fs = require('node:fs'); const {pathToFileURL}=require('node:url'); import(pathToFileURL(process.argv[1])).then(module => process.stdout.write(JSON.stringify({ text: module.text, task: fs.readFileSync(0,'utf8'), prefix: fs.readFileSync(process.argv[1]).subarray(0,3).toString('hex') })))`, - '--', - ...guest.plan.args - ], - stdio: 'pipe' - }) - let stdout = '' - child.stdout.on('data', (chunk) => (stdout += chunk.toString())) - child.stdin.on('error', () => {}) - child.stderr.on('data', (chunk) => { - if (guest.observe(chunk)) { - child.stdin.end([...guest.records()].join('')) - } - }) - try { - const code = await new Promise((resolve, reject) => { - child.once('close', resolve) - child.once('error', reject) - }) - expect(code).toBe(0) - expect(JSON.parse(stdout)).toEqual({ - text: 'policy 🌊', - task: 'Name this chat 🌊\nlast line', - prefix: '657870' - }) - } finally { - await rm(directory, { recursive: true, force: true }) - } -}) diff --git a/src/main/tray/tray-attention-icon.test.ts b/src/main/tray/tray-attention-icon.test.ts deleted file mode 100644 index cb92eb09da9..00000000000 --- a/src/main/tray/tray-attention-icon.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const createFromBitmapMock = vi.hoisted(() => - vi.fn((buffer: Buffer, options: { width: number; height: number }) => ({ - __image: true, - buffer, - ...options - })) -) - -vi.mock('electron', () => ({ - nativeImage: { createFromBitmap: createFromBitmapMock } -})) - -import { composeTrayAttentionIcon, tintTrayTemplateForAttention } from './tray-attention-icon' - -type FakeImage = { - getSize: () => { width: number; height: number } - toBitmap: () => Buffer -} - -function fakeBase(width: number, height: number): FakeImage { - // Transparent base isolates pixels contributed by the attention dot/ring. - return { - getSize: () => ({ width, height }), - toBitmap: () => Buffer.alloc(width * height * 4, 0) - } -} - -// Electron bitmaps use BGRA; renderer attention token is amber-500 (#f59e0b). -const AMBER = { b: 0x0b, g: 0x9e, r: 0xf5 } - -describe('composeTrayAttentionIcon', () => { - it('paints an amber dot in the top-right corner and leaves the rest untouched', () => { - createFromBitmapMock.mockClear() - const width = 16 - const height = 16 - composeTrayAttentionIcon(fakeBase(width, height) as never) - const bitmap = createFromBitmapMock.mock.calls[0][0] - - const pixel = (x: number, y: number): [number, number, number, number] => { - const o = (y * width + x) * 4 - return [bitmap[o], bitmap[o + 1], bitmap[o + 2], bitmap[o + 3]] - } - - let amberCount = 0 - let sumX = 0 - let sumY = 0 - let paintedInBottomLeft = 0 - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const [b, g, r, a] = pixel(x, y) - if (b === AMBER.b && g === AMBER.g && r === AMBER.r && a === 0xff) { - amberCount++ - sumX += x - sumY += y - } - if (a !== 0 && x < width / 2 && y >= height / 2) { - paintedInBottomLeft++ - } - } - } - - expect(amberCount).toBeGreaterThan(0) - expect(sumX / amberCount).toBeGreaterThan(width / 2) - expect(sumY / amberCount).toBeLessThan(height / 2) - expect(paintedInBottomLeft).toBe(0) - }) -}) - -describe('tintTrayTemplateForAttention', () => { - it('keeps white edge pixels premultiplied-valid at partial alpha', () => { - createFromBitmapMock.mockClear() - const base = { - getSize: () => ({ width: 1, height: 1 }), - toBitmap: () => Buffer.from([0x00, 0x00, 0x00, 0x80]) - } - - tintTrayTemplateForAttention(base as never, true) - - // Premultiplied alpha requires 0x80 channels for half-covered white, not 0xff. - expect(createFromBitmapMock.mock.calls[0][0]).toEqual(Buffer.from([0x80, 0x80, 0x80, 0x80])) - }) -}) diff --git a/src/main/updater/browser-sidecar-owner.test.ts b/src/main/updater/browser-sidecar-owner.test.ts index e6db659f923..b918c796c49 100644 --- a/src/main/updater/browser-sidecar-owner.test.ts +++ b/src/main/updater/browser-sidecar-owner.test.ts @@ -4,7 +4,7 @@ import { BROWSER_SIDECAR_OWNER_ENV } from '../../shared/browser-sidecar-lifetime import { installServeSupervisorDisconnectQuit } from './serve-update-handoff' const { quit } = vi.hoisted(() => ({ quit: vi.fn() })) -vi.mock('../startup/process-quit-request', () => ({ quitProcess: quit })) +vi.mock('../startup/quit/process-quit-request', () => ({ quitProcess: quit })) vi.mock('../persistence/loading-store/user-data-path', () => ({ getCanonicalUserDataPath: () => { throw new Error('No profile access for sidecar owner') @@ -27,16 +27,3 @@ it('couples the browser to its IPC owner on every platform and removes the inher expect(quit).toHaveBeenCalledOnce() dispose() }) - -it('quits when the owner disappeared before startup finished', () => { - const parent = Object.assign(new EventEmitter(), { connected: false }) - installServeSupervisorDisconnectQuit(true, parent) - expect(quit).toHaveBeenCalledOnce() -}) - -it('removes the listener on disposal', () => { - const parent = Object.assign(new EventEmitter(), { connected: true }) - installServeSupervisorDisconnectQuit(true, parent)() - parent.emit('disconnect') - expect(quit).not.toHaveBeenCalled() -}) diff --git a/src/main/updater/lifecycle/main-window-updater-deferred-setup.test.ts b/src/main/updater/lifecycle/main-window-updater-deferred-setup.test.ts new file mode 100644 index 00000000000..37ba6575344 --- /dev/null +++ b/src/main/updater/lifecycle/main-window-updater-deferred-setup.test.ts @@ -0,0 +1,157 @@ +import { EventEmitter } from 'node:events' +import type { BrowserWindow } from 'electron' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Store } from '../../persistence/loading-store/store' +import type { UpdaterSetupOptions } from './updater-setup' + +const { setupMock, milestoneMock, getMainWindowMock } = vi.hoisted(() => ({ + getMainWindowMock: vi.fn<() => BrowserWindow | null>(() => null), + setupMock: vi.fn<(window: BrowserWindow, options?: UpdaterSetupOptions) => void>(), + milestoneMock: vi.fn<(name: string) => void>() +})) + +vi.mock('electron', () => ({ app: {}, ipcMain: {} })) +vi.mock('../updater-service', () => ({ setupAutoUpdater: setupMock })) +vi.mock('./electron-updater-proxy-session', () => ({ + applyProxyToElectronUpdaterSession: vi.fn() +})) +vi.mock('../../ipc/ui', () => ({ + isTrustedUIRenderer: () => true, + getTrustedUIRendererWindow: getMainWindowMock +})) +vi.mock('../../startup/diagnostics/startup-diagnostics', () => ({ + logStartupMilestone: milestoneMock +})) + +function createWindowOwner() { + const window = Object.assign(new EventEmitter(), { + id: 7, + isDestroyed: vi.fn(() => false) + }) + const ui = { + lastUpdateCheckAt: 123, + pendingUpdateNudgeId: 'pending', + dismissedUpdateNudgeId: 'dismissed', + releaseChannelOverride: 'rc' + } satisfies Partial> + const store = { + getSettings: vi.fn(() => ({})), + getUI: vi.fn(() => ui), + updateUI: vi.fn<(patch: Parameters[0]) => void>(), + flushPendingAsync: vi.fn().mockResolvedValue(undefined) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This owner only reads id/isDestroyed and registers once; EventEmitter supplies the original once contract. + const mainWindow = window as unknown as BrowserWindow + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The complete owner accesses only these three store methods and the checked UI fields above. + const persistence = store as unknown as Store + return { window, mainWindow, store, persistence } +} + +function captureError(action: () => void): unknown { + try { + action() + } catch (error) { + return error + } + throw new Error('Expected action to throw') +} + +describe('completed deferred updater setup ownership', () => { + beforeEach(() => { + vi.resetModules() + vi.useFakeTimers() + setupMock.mockReset() + milestoneMock.mockReset() + }) + + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('does not retain the expired native fallback of a destroyed window', async () => { + vi.useRealTimers() + const updater = await import('./main-window-updater') + const owner = createWindowOwner() + owner.window.isDestroyed.mockReturnValue(true) + function scheduleNativeFallback(): WeakRef { + const nativeSetTimeout = globalThis.setTimeout + const armed = vi + .spyOn(globalThis, 'setTimeout') + .mockImplementation((callback, delay, ...args) => + nativeSetTimeout(callback, delay === 15_000 ? 1 : delay, ...args) + ) + try { + updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) + expect(armed).toHaveBeenCalledOnce() + expect(armed.mock.calls[0]?.[1]).toBe(15_000) + const handle = armed.mock.results[0]?.value + if (!handle) { + throw new Error('Missing native fallback timer') + } + expect(handle.hasRef()).toBe(false) + return new WeakRef(handle) + } finally { + armed.mockClear() + armed.mockRestore() + } + } + // The real deadline has separate paired proof; only this fixture's native wait is shortened. + const weakTimer = scheduleNativeFallback() + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(owner.window.isDestroyed).toHaveBeenCalledOnce() + updater.ensureAutoUpdaterConfigured() + expect(owner.window.isDestroyed).toHaveBeenCalledTimes(2) + expect(setupMock).not.toHaveBeenCalled() + expect(milestoneMock).not.toHaveBeenCalled() + expect(globalThis.gc).toBeTypeOf('function') + for (let turn = 0; turn < 4; turn++) { + await new Promise((resolve) => setImmediate(resolve)) + globalThis.gc?.() + } + expect(weakTimer.deref()).toBeUndefined() + }) + + it('preserves pending retry after a failed destroyed-state read', async () => { + const updater = await import('./main-window-updater') + const owner = createWindowOwner() + const error = new Error('destroyed-state read failed') + owner.window.isDestroyed.mockImplementationOnce(() => { + throw error + }) + updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) + expect(captureError(() => updater.ensureAutoUpdaterConfigured())).toBe(error) + expect(setupMock).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(1) + updater.ensureAutoUpdaterConfigured() + expect(setupMock).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + }) + + it.each(['setup', 'milestone'] as const)( + 'preserves a reentrant successor when the old %s throws', + async (failure) => { + const updater = await import('./main-window-updater') + const old = createWindowOwner() + const successor = createWindowOwner() + const error = new Error('old owner failed after replacement') + const replaceAndThrow = () => { + updater.scheduleMainWindowAutoUpdaterSetup(successor.mainWindow, successor.persistence) + throw error + } + if (failure === 'setup') { + setupMock.mockImplementationOnce(replaceAndThrow) + } else { + milestoneMock.mockImplementationOnce(replaceAndThrow) + } + updater.scheduleMainWindowAutoUpdaterSetup(old.mainWindow, old.persistence) + expect(captureError(() => updater.ensureAutoUpdaterConfigured())).toBe(error) + expect(vi.getTimerCount()).toBe(1) + updater.ensureAutoUpdaterConfigured() + expect(setupMock).toHaveBeenLastCalledWith(successor.mainWindow, expect.any(Object)) + expect(setupMock).toHaveBeenCalledTimes(2) + expect(vi.getTimerCount()).toBe(0) + } + ) +}) diff --git a/src/main/window/main-window-updater.ts b/src/main/updater/lifecycle/main-window-updater.ts similarity index 88% rename from src/main/window/main-window-updater.ts rename to src/main/updater/lifecycle/main-window-updater.ts index 586d0b187b6..c634b515e72 100644 --- a/src/main/window/main-window-updater.ts +++ b/src/main/updater/lifecycle/main-window-updater.ts @@ -1,14 +1,17 @@ import { app, ipcMain } from 'electron' import type { BrowserWindow, IpcMainInvokeEvent } from 'electron' -import type { ReleaseBuildListResult, UpdateCheckOptions } from '../../shared/update-status-types' -import { RELEASE_CHANNELS, type ReleaseChannel } from '../../shared/release-channel' -import { getTrustedUIRendererWindow, isTrustedUIRenderer } from '../ipc/ui' -import type { Store } from '../persistence/loading-store/store' -import { logStartupMilestone } from '../startup/startup-diagnostics' -import { applyProxyToElectronUpdaterSession } from '../updater/lifecycle/electron-updater-proxy-session' -import { updaterErrorMessage } from '../updater/lifecycle/updater-coded-error' -import { updaterCodedMessage } from '../../shared/updater-failure-copy' -import { normalizeUpdateDelayDays } from '../../shared/update-delay' +import type { + ReleaseBuildListResult, + UpdateCheckOptions +} from '../../../shared/update-status-types' +import { RELEASE_CHANNELS, type ReleaseChannel } from '../../../shared/release-channel' +import { getTrustedUIRendererWindow, isTrustedUIRenderer } from '../../ipc/ui' +import type { Store } from '../../persistence/loading-store/store' +import { logStartupMilestone } from '../../startup/diagnostics/startup-diagnostics' +import { applyProxyToElectronUpdaterSession } from './electron-updater-proxy-session' +import { updaterErrorMessage } from './updater-coded-error' +import { updaterCodedMessage } from '../../../shared/updater-failure-copy' +import { normalizeUpdateDelayDays } from '../../../shared/update-delay' import { checkForUpdatesFromMenu, dismissAvailableUpdate, @@ -20,12 +23,9 @@ import { quitAndInstall, setupAutoUpdater, showLinuxPackage -} from '../updater/updater-service' -import type { - PreQuitCleanupFailureMode, - UpdateInstallMode -} from '../updater/lifecycle/updater-state' -import type { UpdaterSetupOptions } from '../updater/lifecycle/updater-setup' +} from '../updater-service' +import type { PreQuitCleanupFailureMode, UpdateInstallMode } from './updater-state' +import type { UpdaterSetupOptions } from './updater-setup' const UPDATER_SETUP_FALLBACK_MS = 15_000 diff --git a/src/main/updater/lifecycle/updater-install-execution.ts b/src/main/updater/lifecycle/updater-install-execution.ts index d135b64bafb..a8f068c7cab 100644 --- a/src/main/updater/lifecycle/updater-install-execution.ts +++ b/src/main/updater/lifecycle/updater-install-execution.ts @@ -1,6 +1,6 @@ import { releaseSessionsForInstaller } from './updater-installer-session-release' import { withUpdaterSpan } from '../../observability/instrumentation' -import { runWithLaunchPath } from '../../startup/hydrate-shell-path' +import { runWithLaunchPath } from '../../startup/shell-environment/hydrate-shell-path' import { markMacQuitAndInstallInFlight, isMacInstallerReady, diff --git a/src/main/window/updater-package-recovery-ipc.test.ts b/src/main/updater/lifecycle/updater-package-recovery-ipc.test.ts similarity index 81% rename from src/main/window/updater-package-recovery-ipc.test.ts rename to src/main/updater/lifecycle/updater-package-recovery-ipc.test.ts index 60c1ab212c9..30adc0f477f 100644 --- a/src/main/window/updater-package-recovery-ipc.test.ts +++ b/src/main/updater/lifecycle/updater-package-recovery-ipc.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import type { IpcMainInvokeEvent, WebContents } from 'electron' -import type { Store } from '../persistence/loading-store/store' -import type * as IpcUiModule from '../ipc/ui' +import type { Store } from '../../persistence/loading-store/store' +import type * as IpcUiModule from '../../ipc/ui' const { handleMock, @@ -31,27 +31,27 @@ vi.mock('electron', () => ({ powerMonitor: { on: vi.fn(), off: vi.fn() } })) -vi.mock('../ipc/repos', () => ({ registerRepoHandlers: vi.fn() })) -vi.mock('../ipc/worktrees', () => ({ registerWorktreeHandlers: vi.fn() })) -vi.mock('../ipc/worktrees/listing/worktree-change-invalidators', () => ({ +vi.mock('../../ipc/repos', () => ({ registerRepoHandlers: vi.fn() })) +vi.mock('../../ipc/worktrees', () => ({ registerWorktreeHandlers: vi.fn() })) +vi.mock('../../ipc/worktrees/listing/worktree-change-invalidators', () => ({ runWorktreeChangeInvalidators: vi.fn() })) -vi.mock('../ipc/pty/provider/registry', () => ({ getLocalPtyProvider: vi.fn() })) -vi.mock('../ipc/pty/register-handlers', () => ({ registerPtyHandlers: vi.fn() })) -vi.mock('../memory/hydrate-local-pty-registry', () => ({ +vi.mock('../../ipc/pty/provider/registry', () => ({ getLocalPtyProvider: vi.fn() })) +vi.mock('../../ipc/pty/register-handlers', () => ({ registerPtyHandlers: vi.fn() })) +vi.mock('../../memory/hydrate-local-pty-registry', () => ({ hydrateLocalPtyRegistryAtBoot: vi.fn() })) -vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ +vi.mock('../../browser/guest-lifecycle/manager/browser-manager', () => ({ browserManager: { unregisterAll: vi.fn() } })) -vi.mock('../macos-permissions/macos-tcc-prompt-notice', () => ({ +vi.mock('../../macos-permissions/macos-tcc-prompt-notice', () => ({ acknowledgePendingTccPromptNotice: vi.fn(), consumePendingTccPromptNotice: vi.fn(), dismissTccPromptNotice: vi.fn(), releasePendingTccPromptNotice: vi.fn() })) -vi.mock('../updater/updater-service', () => ({ +vi.mock('../updater-service', () => ({ checkForUpdates: vi.fn(), checkForUpdatesFromMenu: vi.fn(), downloadUpdate: vi.fn(), @@ -65,7 +65,7 @@ vi.mock('../updater/updater-service', () => ({ })) // Keep the seam mock for wiring proof but delegate to the real predicate for sender-authorization branches. -vi.mock('../ipc/ui', async (importOriginal) => ({ +vi.mock('../../ipc/ui', async (importOriginal) => ({ ...(await importOriginal()), isTrustedUIRenderer: (sender: unknown) => isTrustedUIRendererMock(sender) })) @@ -120,7 +120,7 @@ function expectBothChannelsRejected(sender: Partial): void { describe('updater linux package recovery IPC handlers', () => { beforeAll(async () => { // Read the real predicate using the same trusted-ID state these tests set. - actualUi = await vi.importActual('../ipc/ui') + actualUi = await vi.importActual('../../ipc/ui') }) beforeEach(() => { @@ -141,17 +141,6 @@ describe('updater linux package recovery IPC handlers', () => { vi.unstubAllEnvs() }) - it('serves the current main UI renderer', async () => { - const event = senderEvent(webContents({})) - - await expect(getHandler(RECOVERY_CHANNELS[0])(event)).resolves.toEqual({ - ok: true, - command: "sudo apt install -- ''", - packageFileName: 'p' - }) - await expect(getHandler(RECOVERY_CHANNELS[1])(event)).resolves.toBeUndefined() - }) - // Exercise distinct real authorization branches, not relabelled mock verdicts. it.each([ ['a guest webview', webContents({ getType: () => 'webview' })], diff --git a/src/main/updater/mac-install/updater.mac-install.test.ts b/src/main/updater/mac-install/updater.mac-install.test.ts index e372541c0dc..290508bcc95 100644 --- a/src/main/updater/mac-install/updater.mac-install.test.ts +++ b/src/main/updater/mac-install/updater.mac-install.test.ts @@ -212,134 +212,6 @@ describe('updater mac install handoff', () => { vi.useRealTimers() }) - it('lets leftover ShipIt state be cleared before Squirrel can stage the download', async () => { - vi.useFakeTimers() - let finishPreparing: () => void = () => undefined - prepareShipItStagingMock.mockReturnValue( - new Promise((resolve) => { - finishPreparing = resolve - }) - ) - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn())) - await vi.waitFor(() => expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1)) - autoUpdaterMock.emit('checking-for-update') - autoUpdaterMock.emit('update-available', { version: '1.0.61' }) - await vi.advanceTimersByTimeAsync(0) - - downloadUpdate() - expect(prepareShipItStagingMock).toHaveBeenCalledTimes(1) - expect(autoUpdaterMock.downloadUpdate).not.toHaveBeenCalled() - finishPreparing() - await vi.advanceTimersByTimeAsync(0) - expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1) - }) - - it.runIf(process.platform === 'darwin')( - 'resumes an ordinary quit when Squirrel becomes ready without checking blockers or relaunching', - async () => { - vi.useFakeTimers() - const sendMock = vi.fn() - const mainWindow = updaterMainWindow(sendMock) - - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - getMacUpdateRunningInstancesMock.mockResolvedValue([9654]) - const { setupAutoUpdater, downloadUpdate } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow) - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - autoUpdaterMock.emit('checking-for-update') - autoUpdaterMock.emit('update-available', { version: '1.0.61' }) - // Let async update-available state land before emitting update-downloaded. - await vi.advanceTimersByTimeAsync(0) - downloadUpdate() - autoUpdaterMock.emit('update-downloaded', { version: '1.0.61' }) - - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - - expect(preventDefault).toHaveBeenCalledTimes(1) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - - const nativeDownloadedHandler = nativeUpdaterMock.on.mock.calls.find( - ([eventName]) => eventName === 'update-downloaded' - )?.[1] as (() => void) | undefined - expect(nativeDownloadedHandler).toBeTypeOf('function') - - nativeDownloadedHandler?.() - - await vi.advanceTimersByTimeAsync(0) - expect(appMock.quit).toHaveBeenCalledOnce() - expect(getMacUpdateRunningInstancesMock).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - const resumedPreventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault: resumedPreventDefault }) - appMock.emit('before-quit', { preventDefault: resumedPreventDefault }) - expect(resumedPreventDefault).not.toHaveBeenCalled() - expect(sendMock).toHaveBeenCalledWith('updater:status', { - state: 'downloading', - percent: 100, - version: '1.0.61' - }) - } - ) - - it.runIf(process.platform === 'darwin')( - 'checks blockers for an explicit install requested before Squirrel becomes ready', - async () => { - vi.useFakeTimers() - const send = vi.fn() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - getMacUpdateRunningInstancesMock.mockResolvedValue([9654]) - const { - setupAutoUpdater, - downloadUpdate, - quitAndInstall, - isQuittingForUpdate, - checkForUpdates, - checkForUpdatesFromMenu, - getUpdateStatus - } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(send)) - await vi.waitFor(() => expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledOnce()) - autoUpdaterMock.emit('checking-for-update') - autoUpdaterMock.emit('update-available', { version: '1.0.61' }) - await vi.advanceTimersByTimeAsync(0) - downloadUpdate() - autoUpdaterMock.emit('update-downloaded', { version: '1.0.61' }) - quitAndInstall() - checkForUpdatesFromMenu() - checkForUpdatesFromMenu({ localBuild: true }) - checkForUpdatesFromMenu({ channel: 'stable', targetTag: 'v1.0.70' }) - checkForUpdates() - downloadUpdate() - await vi.advanceTimersByTimeAsync(0) - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledOnce() - expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledOnce() - expect(getUpdateStatus()).toEqual( - expect.objectContaining({ state: 'downloading', percent: 100, version: '1.0.61' }) - ) - const nativeReady = nativeUpdaterMock.on.mock.calls.find( - ([event]) => event === 'update-downloaded' - )?.[1] - nativeReady?.() - await vi.advanceTimersByTimeAsync(0) - - expect(getMacUpdateRunningInstancesMock).toHaveBeenCalledOnce() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - expect(appMock.quit).not.toHaveBeenCalled() - expect(isQuittingForUpdate()).toBe(false) - expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted') - expect(send).toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ state: 'error', version: '1.0.61', retryAction: 'install' }) - ) - } - ) - it.runIf(process.platform === 'darwin')( 'ignores duplicate quit requests while deferred mac install cleanup is running', async () => { @@ -394,83 +266,6 @@ describe('updater mac install handoff', () => { } ) - it.runIf(process.platform === 'darwin')( - 'logs rejected deferred mac install handoffs without unhandled rejection', - async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const reportDownloaded = vi.fn() - const { deferMacQuitUntilInstallerReady, handleMacInstallerReady } = - await import('./updater-mac-install') - - expect( - deferMacQuitUntilInstallerReady( - { state: 'downloading', percent: 100, version: '1.0.61' }, - true, - () => '1.0.61', - vi.fn() - ) - ).toBe(true) - - handleMacInstallerReady( - true, - async () => { - throw new Error('handoff-secret') - }, - reportDownloaded - ) - await Promise.resolve() - - expect(reportDownloaded).not.toHaveBeenCalled() - await vi.waitFor(() => { - expect(warn).toHaveBeenCalledWith( - '[updater] Deferred macOS install handoff failed {"errorType":"Error"}' - ) - }) - expect(JSON.stringify(warn.mock.calls)).not.toContain('handoff-secret') - } - ) - - it.runIf(process.platform === 'darwin')( - 'falls back to a normal quit if Squirrel.Mac never becomes ready', - async () => { - vi.useFakeTimers() - - const sendMock = vi.fn() - const mainWindow = updaterMainWindow(sendMock) - - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow) - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - autoUpdaterMock.emit('checking-for-update') - autoUpdaterMock.emit('update-available', { version: '1.0.61' }) - // Let async update-available state land before emitting update-downloaded. - await vi.advanceTimersByTimeAsync(0) - downloadUpdate() - autoUpdaterMock.emit('update-downloaded', { version: '1.0.61' }) - - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - - expect(preventDefault).toHaveBeenCalledTimes(1) - expect(appMock.quit).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(15000) - - expect(appMock.quit).toHaveBeenCalledTimes(1) - - const secondPreventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault: secondPreventDefault }) - expect(secondPreventDefault).not.toHaveBeenCalled() - appMock.emit('before-quit', { preventDefault: secondPreventDefault }) - expect(secondPreventDefault).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - } - ) - it.runIf(process.platform === 'darwin')( 'keeps the app and terminals open when another bundle instance blocks installation, then allows retry', async () => { @@ -532,230 +327,6 @@ describe('updater mac install handoff', () => { } ) - it.runIf(process.platform === 'darwin')( - 'recovers orphan browser blockers before native install without asking for another download', - async () => { - vi.useFakeTimers() - const send = vi.fn() - const onBeforeQuit = vi.fn() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(send), { onBeforeQuit }) - await prepareStagedMacUpdate(downloadUpdate) - getMacUpdateRunningInstancesMock.mockResolvedValue([9654]) - recoverBrowserSidecarsMock.mockResolvedValue([]) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - expect(recoverBrowserSidecarsMock).toHaveBeenCalledWith(process.execPath, [9654]) - expect(send).toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ - state: 'downloaded', - installing: true - }) - ) - expect(onBeforeQuit).toHaveBeenCalledOnce() - expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce() - expect(send).not.toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ installBlock: expect.anything() }) - ) - } - ) - - it.runIf(process.platform === 'darwin')( - 'keeps the app open when process enumeration fails', - async () => { - vi.useFakeTimers() - const send = vi.fn() - const onBeforeQuit = vi.fn() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate, quitAndInstall, isQuittingForUpdate } = - await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(send), { onBeforeQuit }) - await prepareStagedMacUpdate(downloadUpdate) - getMacUpdateRunningInstancesMock.mockRejectedValue(new Error('probe failed')) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - expect(onBeforeQuit).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - expect(isQuittingForUpdate()).toBe(false) - expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted') - expect(send).toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ - state: 'error', - message: expect.stringContaining('Could not check'), - retryAction: 'install' - }) - ) - expect(send).toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ - message: expect.stringMatching(/close the other Orca instances.*quit Orca/i) - }) - ) - } - ) - - it.runIf(process.platform === 'darwin')( - 'leaves an ordinary quit with a staged update to Squirrel instead of starting a relaunching install', - async () => { - vi.useFakeTimers() - const onBeforeQuit = vi.fn() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn()), { onBeforeQuit }) - await prepareStagedMacUpdate(downloadUpdate) - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - appMock.emit('before-quit', { preventDefault }) - await vi.advanceTimersByTimeAsync(0) - expect(preventDefault).not.toHaveBeenCalled() - expect(getMacUpdateRunningInstancesMock).not.toHaveBeenCalled() - expect(onBeforeQuit).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - } - ) - - it.runIf(process.platform === 'darwin')( - 'blocks duplicate quits while the running-instance check is pending', - async () => { - vi.useFakeTimers() - const onBeforeQuit = vi.fn() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn()), { onBeforeQuit }) - await prepareStagedMacUpdate(downloadUpdate) - - let finishProbe: (pids: number[]) => void = () => {} - getMacUpdateRunningInstancesMock.mockImplementation( - () => - new Promise((resolve) => { - finishProbe = resolve - }) - ) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).toHaveBeenCalledTimes(2) - expect(getMacUpdateRunningInstancesMock).toHaveBeenCalledTimes(1) - finishProbe([9654]) - await vi.advanceTimersByTimeAsync(0) - expect(onBeforeQuit).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - } - ) - - it.runIf(process.platform === 'darwin')( - 'allows ordinary quitting after a refused install without requiring background servers to exit', - async () => { - vi.useFakeTimers() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn())) - await prepareStagedMacUpdate(downloadUpdate) - getMacUpdateRunningInstancesMock.mockResolvedValue([9654]) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).not.toHaveBeenCalled() - // The main will-quit handler requests quit again after asynchronous teardown. - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - } - ) - - it.runIf(process.platform === 'darwin')( - 'prevents duplicate quits until asynchronous update cleanup finishes', - async () => { - vi.useFakeTimers() - let finishCleanup = (): void => {} - const onBeforeQuit = vi.fn( - () => - new Promise((resolve) => { - finishCleanup = resolve - }) - ) - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn()), { onBeforeQuit }) - await prepareStagedMacUpdate(downloadUpdate) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - expect(onBeforeQuit).toHaveBeenCalledTimes(1) - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).toHaveBeenCalledTimes(1) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - finishCleanup() - await vi.advanceTimersByTimeAsync(0) - const nativePreventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault: nativePreventDefault }) - expect(nativePreventDefault).not.toHaveBeenCalled() - expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) - } - ) - - it.runIf(process.platform === 'darwin')( - 'cannot use a previous refusal to bypass a pending retry check', - async () => { - vi.useFakeTimers() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const { setupAutoUpdater, downloadUpdate, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn())) - await prepareStagedMacUpdate(downloadUpdate) - getMacUpdateRunningInstancesMock.mockResolvedValue([9654]) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - let finishProbe = (_pids: number[]): void => {} - getMacUpdateRunningInstancesMock.mockImplementation( - () => - new Promise((resolve) => { - finishProbe = resolve - }) - ) - quitAndInstall() - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(1000) - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).toHaveBeenCalledTimes(2) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - finishProbe([]) - await vi.advanceTimersByTimeAsync(0) - expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce() - } - ) - - it.runIf(process.platform === 'darwin')( - 'permits ordinary shutdown after required update cleanup rejects', - async () => { - vi.useFakeTimers() - autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined) - const onBeforeQuit = vi.fn().mockRejectedValue(new Error('required cleanup failed')) - const { setupAutoUpdater, downloadUpdate, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn()), { - onBeforeQuit, - onBeforeQuitFailure: 'abort' - }) - await prepareStagedMacUpdate(downloadUpdate) - quitAndInstall() - await vi.advanceTimersByTimeAsync(1000) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - const preventDefault = vi.fn() - appMock.emit('before-quit', { preventDefault }) - appMock.emit('before-quit', { preventDefault }) - expect(preventDefault).not.toHaveBeenCalled() - expect(onBeforeQuit).toHaveBeenCalledOnce() - } - ) - it.runIf(process.platform === 'darwin')( 'keeps the install target and quit guard when checks or downloads are requested during a retry', async () => { diff --git a/src/main/updater/nudges/nudge-campaign.ts b/src/main/updater/nudges/nudge-campaign.ts index e26f44b787d..b664fb1cb5c 100644 --- a/src/main/updater/nudges/nudge-campaign.ts +++ b/src/main/updater/nudges/nudge-campaign.ts @@ -9,7 +9,7 @@ export type NudgeConfig = { export async function fetchNudge(): Promise { try { - const res = await net.fetch('https://onorca.dev/whats-new/nudge.json', { + const res = await net.fetch('https://orca.dev/whats-new/nudge.json', { signal: AbortSignal.timeout(5000) }) if (!res.ok) { diff --git a/src/main/updater/releases/updater-changelog.ts b/src/main/updater/releases/updater-changelog.ts index 5a65cf0e034..dbe199bddb7 100644 --- a/src/main/updater/releases/updater-changelog.ts +++ b/src/main/updater/releases/updater-changelog.ts @@ -10,7 +10,7 @@ type ChangelogEntry = { releaseNotesUrl: string } -const CHANGELOG_URL = 'https://onorca.dev/changelog' +const CHANGELOG_URL = 'https://orca.dev/changelog' function isValidEntry(entry: ChangelogEntry): boolean { return ( @@ -29,7 +29,7 @@ export async function fetchChangelog( incomingVersion: string, localVersion: string ): Promise { - const res = await net.fetch('https://onorca.dev/whats-new/changelog.json', { + const res = await net.fetch('https://orca.dev/whats-new/changelog.json', { signal: AbortSignal.timeout(5000) }) if (!res.ok) { diff --git a/src/main/updater/serve-update-handoff.ts b/src/main/updater/serve-update-handoff.ts index 5b42259ff9b..eeb57598236 100644 --- a/src/main/updater/serve-update-handoff.ts +++ b/src/main/updater/serve-update-handoff.ts @@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from ' import { basename, dirname } from 'node:path' import { BROWSER_SIDECAR_OWNER_ENV } from '../../shared/browser-sidecar-lifetime' import { app } from 'electron' -import { quitProcess } from '../startup/process-quit-request' +import { quitProcess } from '../startup/quit/process-quit-request' import { SERVE_UPDATE_HANDOFF_PATH_ENV, getServeUpdateHandoffPath, diff --git a/src/main/updater/updater.quit-and-install.test.ts b/src/main/updater/updater.quit-and-install.test.ts index b38932b1c06..3c501177a47 100644 --- a/src/main/updater/updater.quit-and-install.test.ts +++ b/src/main/updater/updater.quit-and-install.test.ts @@ -39,7 +39,7 @@ vi.mock('./releases/updater-release-readiness', async (importOriginal) => ({ })) vi.mock('../local-builds/local-build-switch', () => moduleFactories.localBuildSwitch()) vi.mock('../local-builds/local-build-feed-server', () => moduleFactories.localBuildFeedServer()) -vi.mock('../startup/hydrate-shell-path', () => ({ +vi.mock('../startup/shell-environment/hydrate-shell-path', () => ({ runWithLaunchPath: (action: () => unknown): unknown => { launchPathScope.active = true launchPathScope.calls += 1 @@ -60,45 +60,6 @@ describe('updater', () => { launchPathScope.calls = 0 }) - it('still surfaces updater error events while a download is in flight', async () => { - fetchNewerReleaseTagsMock.mockResolvedValue({ tags: ['v1.0.61'], state: 'ready' }) - autoUpdaterMock.checkForUpdates.mockImplementation(() => { - autoUpdaterMock.emit('checking-for-update') - queueMicrotask(() => { - autoUpdaterMock.emit('update-available', { version: '1.0.61' }) - }) - return Promise.resolve(undefined) - }) - autoUpdaterMock.downloadUpdate.mockImplementation(() => { - autoUpdaterMock.emit('error', new Error('download failed')) - return new Promise(() => {}) - }) - const sendMock = vi.fn() - const mainWindow = updaterMainWindow(sendMock) - - const { setupAutoUpdater, checkForUpdatesFromMenu, downloadUpdate } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow, { getLastUpdateCheckAt: () => Date.now() }) - checkForUpdatesFromMenu() - - await vi.waitFor(() => { - expect(sendMock).toHaveBeenCalledWith('updater:status', { - state: 'available', - version: '1.0.61', - changelog: null - }) - }) - - sendMock.mockClear() - downloadUpdate() - - expect(autoUpdaterMock.downloadUpdate).toHaveBeenCalledTimes(1) - expect(sendMock).toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ state: 'error', message: 'download failed' }) - ) - }) - it('aborts native install when required pre-quit cleanup fails', async () => { vi.useFakeTimers() @@ -128,18 +89,6 @@ describe('updater', () => { ) }) - it('allows a required profile export to finish beyond the optional cleanup budget', async () => { - vi.useFakeTimers() - const onBeforeQuit = vi.fn(() => new Promise((resolve) => setTimeout(resolve, 5_000))) - const { setupAutoUpdater, quitAndInstall } = await loadUpdaterModule() - setupAutoUpdater(updaterMainWindow(vi.fn()), { onBeforeQuit, onBeforeQuitFailure: 'abort' }) - quitAndInstall() - await vi.advanceTimersByTimeAsync(2_600) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(2_500) - expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledOnce() - }) - it('aborts native install when required pre-quit cleanup times out', async () => { vi.useFakeTimers() @@ -172,35 +121,6 @@ describe('updater', () => { ) }) - it('ignores duplicate quitAndInstall requests while async pre-quit cleanup is running', async () => { - vi.useFakeTimers() - - let finishCleanup!: () => void - const onBeforeQuit = vi.fn( - () => - new Promise((resolve) => { - finishCleanup = resolve - }) - ) - const mainWindow = updaterMainWindow(vi.fn()) - const { setupAutoUpdater, quitAndInstall } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow, { onBeforeQuit }) - quitAndInstall() - - await vi.advanceTimersByTimeAsync(100) - - expect(onBeforeQuit).toHaveBeenCalledTimes(1) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - - quitAndInstall() - finishCleanup() - await vi.advanceTimersByTimeAsync(0) - - expect(onBeforeQuit).toHaveBeenCalledTimes(1) - expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) - }) - it('recovers quit-for-update state on sync quitAndInstall error event without killing PTYs', async () => { vi.useFakeTimers() diff --git a/src/main/usage/cache/usage-cache-json.ts b/src/main/usage/cache/usage-cache-json.ts new file mode 100644 index 00000000000..520cc71ea27 --- /dev/null +++ b/src/main/usage/cache/usage-cache-json.ts @@ -0,0 +1,154 @@ +import { createReadStream } from 'node:fs' +import Assembler from 'stream-json/assembler.js' +import { createJsonTokenReader } from '../../../shared/json-stream/json-token-reader' +import { + JsonStringifyByteLimitError, + stringifyJsonWithinByteLimit +} from '../../../shared/json-stream/node-bounded-json-stringify' + +const TEXT_BATCH_CHARS = 64 * 1024 +const STRING_SLICE_CHARS = 4 * 1024 + +function prepareValue(value: unknown, key: string): unknown { + if (value !== null && typeof value === 'object') { + if ('toJSON' in value && typeof value.toJSON === 'function') { + value = value.toJSON(key) + } + const tag = Object.prototype.toString.call(value) + if ( + value !== null && + typeof value === 'object' && + (tag === '[object Number]' || tag === '[object String]' || tag === '[object Boolean]') + ) { + return value.valueOf() + } + } + return value +} + +function omitted(value: unknown): boolean { + return value === undefined || typeof value === 'function' || typeof value === 'symbol' +} + +function* encodeString(value: string): Generator { + if (value.length <= STRING_SLICE_CHARS) { + yield JSON.stringify(value) + return + } + yield '"' + for (let offset = 0; offset < value.length;) { + let end = Math.min(offset + STRING_SLICE_CHARS, value.length) + const last = value.charCodeAt(end - 1) + const next = value.charCodeAt(end) + // Each piece is encoded independently by both file writes and integrity hashes. + if (last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) { + end-- + } + yield JSON.stringify(value.slice(offset, end)).slice(1, -1) + offset = end + } + yield '"' +} + +function* encodeValue( + value: unknown, + ancestors: Set, + nativeRecord = false +): Generator { + if (typeof value === 'string') { + yield* encodeString(value) + return + } + if (value === null || typeof value !== 'object') { + const text = JSON.stringify(value) + if (text === undefined) { + throw new TypeError('Usage cache value is not JSON serializable') + } + yield text + return + } + if (ancestors.has(value)) { + throw new TypeError('Usage cache contains a circular value') + } + if (nativeRecord) { + try { + yield stringifyJsonWithinByteLimit(value, 256 * 1024).serialized + return + } catch (error) { + if (!(error instanceof JsonStringifyByteLimitError)) { + throw error + } + } + } + ancestors.add(value) + try { + if (Array.isArray(value)) { + yield '[' + for (let index = 0; index < value.length; index++) { + if (index > 0) { + yield ',' + } + const item = prepareValue(value[index], String(index)) + yield* encodeValue(omitted(item) ? null : item, ancestors, true) + } + yield ']' + } else { + yield '{' + let first = true + for (const [key, raw] of Object.entries(value)) { + const item = prepareValue(raw, key) + if (omitted(item)) { + continue + } + if (!first) { + yield ',' + } + first = false + yield* encodeString(key) + yield ':' + yield* encodeValue(item, ancestors) + } + yield '}' + } + } finally { + ancestors.delete(value) + } +} + +/** Batch traversal output without materializing a whole source, string or document. */ +export function* encodeUsageCacheJson(value: unknown): Generator { + let parts: string[] = [] + let length = 0 + for (const part of encodeValue(prepareValue(value, ''), new Set())) { + if (length + part.length > TEXT_BATCH_CHARS && length > 0) { + yield parts.join('') + parts = [] + length = 0 + } + parts.push(part) + length += part.length + } + if (length > 0) { + yield parts.join('') + } +} + +/** EOF validation precedes exposing any of the privately assembled records. */ +export async function parseUsageCacheJson(chunks: AsyncIterable): Promise { + const assembler = new Assembler() + const reader = createJsonTokenReader((token) => assembler.consume(token)) + for await (const text of chunks) { + reader.write(text) + } + reader.end() + return assembler.current +} + +export function readUsageCacheJson(path: string): Promise { + return parseUsageCacheJson( + createReadStream(path, { + encoding: 'utf8', + highWaterMark: TEXT_BATCH_CHARS + }) + ) +} diff --git a/src/main/usage/cache/usage-cache-protected-json.ts b/src/main/usage/cache/usage-cache-protected-json.ts new file mode 100644 index 00000000000..1e91c55469b --- /dev/null +++ b/src/main/usage/cache/usage-cache-protected-json.ts @@ -0,0 +1,85 @@ +import { createHash } from 'node:crypto' +import { encodeUsageCacheJson, parseUsageCacheJson } from './usage-cache-json' + +const INTEGRITY_HEADER = /^\{"usageIntegrity":"([a-f0-9]{64})",/ +const HEADER_CHARS = '{"usageIntegrity":"'.length + 64 + '",'.length + +export function protectedUsageCacheJson( + value: unknown, + domain: string, + sealed = true +): { + bytes: number + encode: () => Generator +} { + const hash = createHash('sha256').update(domain).update('\n') + let bytes = 0 + for (const text of encodeUsageCacheJson(value)) { + hash.update(text) + bytes += Buffer.byteLength(text) + } + const digest = hash.digest('hex') + const prefix = `{"usageIntegrity":"${digest}",` + return { + bytes: bytes + (sealed ? Buffer.byteLength(prefix) - 1 : 0), + encode: function* () { + let first = true + for (const text of encodeUsageCacheJson(value)) { + if (first && sealed) { + if (!text.startsWith('{')) { + throw new Error('Usage cache integrity requires a JSON object.') + } + yield prefix + yield text.slice(1) + } else { + yield text + } + first = false + } + } + } +} + +/** Verify the original decoded text, never an equivalent re-encoding. */ +export async function readProtectedUsageCacheJson( + chunks: AsyncIterable, + domain: string, + strict = true +): Promise<{ parsed: T; verified: boolean }> { + const hash = createHash('sha256').update(domain).update('\n{') + let leading = '' + let header: RegExpExecArray | null | undefined + async function* inspect(): AsyncGenerator { + for await (const text of chunks) { + if (header === undefined) { + const taken = Math.min(HEADER_CHARS - leading.length, text.length) + leading += text.slice(0, taken) + if (leading.length === HEADER_CHARS) { + header = INTEGRITY_HEADER.exec(leading) + if (header) { + hash.update(text.slice(taken)) + } + } + } else if (header) { + hash.update(text) + } + yield text + } + } + const parsed = await parseUsageCacheJson(inspect()) + if (!parsed || typeof parsed !== 'object') { + throw new Error('Saved usage cache must be a JSON object.') + } + header ??= INTEGRITY_HEADER.exec(leading) + if (!header) { + if (strict && parsed.usageIntegrity !== undefined) { + throw new Error('Saved usage cache integrity framing is invalid.') + } + return { parsed, verified: false } + } + const verified = parsed.usageIntegrity === header[1] && hash.digest('hex') === header[1] + if (strict && !verified) { + throw new Error('Saved usage cache integrity does not match its contents.') + } + return { parsed, verified } +} diff --git a/src/main/usage/cache/usage-cache-snapshot-writer.ts b/src/main/usage/cache/usage-cache-snapshot-writer.ts index f3f2527ef4f..03737455a46 100644 --- a/src/main/usage/cache/usage-cache-snapshot-writer.ts +++ b/src/main/usage/cache/usage-cache-snapshot-writer.ts @@ -3,7 +3,8 @@ import { dirname } from 'node:path' import { durableWriteTempPath, removeStaleDurableWriteTempFiles, - writeFileDurableIfCurrent + writeFileDurableIfCurrent, + type DurableFilePayload } from '../../filesystem/durable-file-write' // Serialize durable writes per store and skip superseded snapshots. @@ -20,7 +21,7 @@ export class UsageCacheSnapshotWriter { } /** `serialize` runs only if this snapshot is still the newest one when its turn comes. */ - write(serialize: () => string): Promise { + write(serialize: () => DurableFilePayload): Promise { const generation = ++this.generation const write = this.pending.then(() => this.commit(generation, serialize)) // Keep the queue usable after failure; the caller still receives the rejection. @@ -35,7 +36,7 @@ export class UsageCacheSnapshotWriter { return this.pending } - private async commit(generation: number, serialize: () => string): Promise { + private async commit(generation: number, serialize: () => DurableFilePayload): Promise { if (generation !== this.generation) { return } diff --git a/src/main/usage/cache/usage-inline-cache-preservation.ts b/src/main/usage/cache/usage-inline-cache-preservation.ts index 8a2c3d04081..7125a8f536d 100644 --- a/src/main/usage/cache/usage-inline-cache-preservation.ts +++ b/src/main/usage/cache/usage-inline-cache-preservation.ts @@ -1,5 +1,5 @@ -import { readFile } from 'node:fs/promises' import type { UsageCacheSnapshotWriter } from './usage-cache-snapshot-writer' +import { encodeUsageCacheJson, readUsageCacheJson } from './usage-cache-json' export class UsageInlineCachePreservation { active = false @@ -18,11 +18,12 @@ export class UsageInlineCachePreservation { this.pending = this.pending .catch(() => {}) .then(async () => { - const parsed: { scanState: { enabled: boolean } } = JSON.parse( - await readFile(cacheFile, 'utf8') - ) + const parsed = await readUsageCacheJson<{ scanState: { enabled: boolean } }>(cacheFile) + if (!parsed) { + throw new Error('Saved inline usage cache is invalid') + } parsed.scanState.enabled = enabled() - await writer.write(() => (this.active ? JSON.stringify(parsed) : serializeReport())) + await writer.write(() => (this.active ? encodeUsageCacheJson(parsed) : serializeReport())) }) return this.pending } diff --git a/src/main/usage/cache/usage-source-cache-file.test.ts b/src/main/usage/cache/usage-source-cache-file.test.ts index dc5d2675322..8f5bebf06a6 100644 --- a/src/main/usage/cache/usage-source-cache-file.test.ts +++ b/src/main/usage/cache/usage-source-cache-file.test.ts @@ -1,8 +1,13 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { splitUsageCacheFile, usageSourceCachePath } from './usage-source-cache-file' +import { + readUsageSourceCache, + splitUsageCacheFile, + usageSourceCachePath, + writeUsageSourceCache +} from './usage-source-cache-file' describe('usage source cache file', () => { let directory: string @@ -39,4 +44,78 @@ describe('usage source cache file', () => { sources: [{ path: 'a.jsonl' }] }) }) + + it('preserves large ownership records, JSON values and Unicode across encoded boundaries', async () => { + const ref = { + path: join(directory, 'sources.json'), + schemaVersion: 7, + worktreeFingerprint: 'w', + reuse: true + } + const label = `${'a'.repeat(4095)}😀é\n"\\\u0000\ud800` + const shared = { totalTokens: 29 } + const sources = [ + { + path: label, + ownedEventKeys: Array.from({ length: 1600 }, () => label), + hasDeferredClaims: true, + parseResumeState: { parsedBytes: 123, headDigest: 'head', boundaryDigest: 'tail' }, + dailyAggregates: [shared, shared], + optional: undefined, + extra: [undefined, Infinity], + packed: { toJSON: () => ({ ownedTokenColumns: [29, null] }) } + } + ] + await writeUsageSourceCache(ref, sources) + const saved = readFileSync(ref.path, 'utf8') + expect(saved).not.toContain('optional') + expect(JSON.parse(saved).sources[0].extra).toEqual([null, null]) + expect(await readUsageSourceCache(ref)).toEqual([ + { + path: label, + ownedEventKeys: Array.from({ length: 1600 }, () => label), + hasDeferredClaims: true, + parseResumeState: { parsedBytes: 123, headDigest: 'head', boundaryDigest: 'tail' }, + dailyAggregates: [{ totalTokens: 29 }, { totalTokens: 29 }], + extra: [null, null], + packed: { ownedTokenColumns: [29, null] } + } + ]) + + const prefix = '{"schemaVersion":7,"worktreeFingerprint":"w","sources":[{"path":"' + const padding = 'p'.repeat(65535 - Buffer.byteLength(prefix)) + writeFileSync(ref.path, `${prefix}${padding}😀é"}]}`) + expect(await readUsageSourceCache(ref)).toEqual([{ path: `${padding}😀é` }]) + }) + + it('never reuses a source prefix from a truncated or trailing-invalid document', async () => { + const ref = { + path: join(directory, 'sources.json'), + schemaVersion: 7, + worktreeFingerprint: 'w', + reuse: true + } + const complete = '{"schemaVersion":7,"worktreeFingerprint":"w","sources":[{"tokens":29}]}' + for (const text of [complete.slice(0, -1), `${complete} null`, `${complete} garbage`]) { + writeFileSync(ref.path, text) + expect(await readUsageSourceCache(ref)).toEqual([]) + } + }) + + it('keeps the prior cache and removes the partial temp when encoding fails after writing', async () => { + const ref = { + path: join(directory, 'sources.json'), + schemaVersion: 7, + worktreeFingerprint: 'w', + reuse: true + } + await writeUsageSourceCache(ref, [{ totalTokens: 29 }]) + const cyclic: { self?: unknown } = {} + cyclic.self = cyclic + await expect( + writeUsageSourceCache(ref, [{ path: 'a'.repeat(2_000_000) }, cyclic]) + ).rejects.toThrow() + expect(await readUsageSourceCache(ref)).toEqual([{ totalTokens: 29 }]) + expect(readdirSync(directory)).toEqual(['sources.json']) + }) }) diff --git a/src/main/usage/cache/usage-source-cache-file.ts b/src/main/usage/cache/usage-source-cache-file.ts index 81e7e51463a..d775c5fa708 100644 --- a/src/main/usage/cache/usage-source-cache-file.ts +++ b/src/main/usage/cache/usage-source-cache-file.ts @@ -1,11 +1,13 @@ -import { mkdir, readFile } from 'node:fs/promises' +import { mkdir } from 'node:fs/promises' import { dirname, join, parse } from 'node:path' import { threadId } from 'node:worker_threads' import { durableWriteTempPath, removeStaleDurableWriteTempFiles, - writeFileDurable + writeFileDurable, + type DurableFilePayload } from '../../filesystem/durable-file-write' +import { encodeUsageCacheJson, readUsageCacheJson } from './usage-cache-json' // Only scans need bulky per-source records; worker-owned sidecars keep them off main. @@ -35,7 +37,11 @@ export async function readUsageSourceCache(ref: UsageSourceCacheRef): Promise return [] } try { - const parsed = JSON.parse(await readFile(ref.path, 'utf-8')) + const parsed = await readUsageCacheJson<{ + schemaVersion: number + worktreeFingerprint: string | null + sources: T[] + }>(ref.path) // The sidecar can commit before its report, so validate attribution independently. return parsed?.schemaVersion === ref.schemaVersion && parsed.worktreeFingerprint === ref.worktreeFingerprint && @@ -51,9 +57,9 @@ export async function writeUsageSourceCache( ref: UsageSourceCacheRef, sources: readonly unknown[] ): Promise { - await writeUsageSourceCacheText( + await writeUsageSourceCacheData( ref, - JSON.stringify({ + encodeUsageCacheJson({ schemaVersion: ref.schemaVersion, worktreeFingerprint: ref.worktreeFingerprint, sources @@ -70,7 +76,7 @@ export async function writeUsageSourceCacheText( export async function writeUsageSourceCacheData( ref: UsageSourceCacheRef, - data: string | Uint8Array + data: DurableFilePayload ): Promise { await mkdir(dirname(ref.path), { recursive: true }).catch(() => {}) // Reclaim old durable-write temps left by workers terminated mid-write. @@ -87,25 +93,26 @@ export async function writeUsageSourceCacheData( export async function splitUsageCacheFile( request: UsageCacheSplitRequest ): Promise { - let text: string + let parsed: Record | null try { - text = await readFile(request.cacheFile, 'utf-8') + parsed = await readUsageCacheJson>(request.cacheFile) } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return { reportText: null, migrated: false } } throw error } - const parsed = JSON.parse(text) - if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed[request.sourceKey])) { - return { reportText: text, migrated: false } + const sources = parsed?.[request.sourceKey] + if (!parsed || typeof parsed !== 'object' || !Array.isArray(sources)) { + return { reportText: JSON.stringify(parsed), migrated: false } } - const { [request.sourceKey]: sources, ...report } = parsed + const { [request.sourceKey]: _sources, ...report } = parsed await writeUsageSourceCache( { path: usageSourceCachePath(request.cacheFile), - schemaVersion: report.schemaVersion, - worktreeFingerprint: report.worktreeFingerprint ?? null, + schemaVersion: typeof report.schemaVersion === 'number' ? report.schemaVersion : 0, + worktreeFingerprint: + typeof report.worktreeFingerprint === 'string' ? report.worktreeFingerprint : null, reuse: true }, sources diff --git a/src/main/usage/provider-lifecycle/usage-provider-store-contract.ts b/src/main/usage/provider-lifecycle/usage-provider-store-contract.ts index 586f64a70e8..184e3ef0d54 100644 --- a/src/main/usage/provider-lifecycle/usage-provider-store-contract.ts +++ b/src/main/usage/provider-lifecycle/usage-provider-store-contract.ts @@ -37,6 +37,7 @@ export type UsageProviderStoreLifecycleConfig< integrityVerified?: boolean ) => State | Promise serializeReport?: (state: State) => string + readFallbackCache?: (path: string) => Promise<{ state: State; integrityVerified: boolean }> providerId?: 'claude' sourceKey: SourceKey dataPresenceKey: DataPresenceKey diff --git a/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.test.ts b/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.test.ts index ebbf500cea7..333deb2b3ba 100644 --- a/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.test.ts +++ b/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' @@ -9,6 +9,8 @@ import type { UsageScanWorktreeRef } from './usage-provider-contract' import { UsageProviderStoreLifecycle } from './usage-provider-store-lifecycle' import { splitUsageCacheFile, + readUsageSourceCache, + usageSourceCachePath, type UsageCacheSplitRequest, type UsageCacheSplitResult, type UsageSourceCacheRef @@ -146,6 +148,52 @@ describe('UsageProviderStoreLifecycle', () => { vi.restoreAllMocks() }) + it('preserves inline sources across failed migration, an enabled toggle and a later retry', async () => { + const cacheFile = join(tempDirectory, 'inline.json') + const sidecar = usageSourceCachePath(cacheFile) + const sources = [{ id: 'owner', ownedEventKeys: ['turn-1|10,0,0,0,10|'], checkpoint: 123 }] + writeFileSync( + cacheFile, + JSON.stringify( + makeState({ + processedSources: sources, + sessions: [{ id: 'session' }], + dailyAggregates: [{ day: '2026-04-10' }], + scanState: { enabled: true } + }) + ) + ) + mkdirSync(sidecar) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const first = new TestUsageStore(cacheFile, scan, split, capture) + stores.push(first) + await first.whenLoaded() + expect(first.getState().sessions).toEqual([{ id: 'session' }]) + await first.setEnabled(false) + await first.flush() + expect(JSON.parse(readFileSync(cacheFile, 'utf8'))).toMatchObject({ + processedSources: sources, + dailyAggregates: [{ day: '2026-04-10' }], + scanState: { enabled: false } + }) + rmSync(sidecar, { recursive: true }) + const retried = new TestUsageStore(cacheFile, scan, split, capture) + stores.push(retried) + await retried.whenLoaded() + await retried.flush() + expect(retried.getState().sessions).toEqual([{ id: 'session' }]) + expect(retried.getScanState().enabled).toBe(false) + expect( + await readUsageSourceCache({ + path: sidecar, + schemaVersion: 1, + worktreeFingerprint: null, + reuse: true + }) + ).toEqual(sources) + expect(JSON.parse(readFileSync(cacheFile, 'utf8')).processedSources).toBeUndefined() + }) + it('keeps a successful scan when the first async telemetry consent request rejects', async () => { const cacheFile = join(tempDirectory, 'consent-rejection.json') const consent = vi diff --git a/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts b/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts index 9bbada658b3..a76137d9dd1 100644 --- a/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts +++ b/src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts @@ -1,5 +1,4 @@ import { readFileSync, statSync } from 'node:fs' -import { readFile } from 'node:fs/promises' import { AgentTokenUsageReporter } from '../reporting/token-usage/agent-token-usage-reporter' import { join, parse } from 'node:path' import { @@ -14,6 +13,7 @@ import { } from '../worktree-attribution/usage-worktree-refs' import { UsageInlineCachePreservation } from '../cache/usage-inline-cache-preservation' import { usageSourceCachePath } from '../cache/usage-source-cache-file' +import { readUsageCacheJson } from '../cache/usage-cache-json' import type { UsageProviderStoreState, UsageProviderStoreLifecycleConfig, @@ -180,6 +180,7 @@ export abstract class UsageProviderStoreLifecycle< private async loadOnWorker(cacheFile: string): Promise { try { let fallback = false + let fallbackState: State | null = null const { reportText, migrated, reportIntegrityVerified } = await Promise.resolve() .then(() => this.config.splitCacheFile({ @@ -192,22 +193,29 @@ export abstract class UsageProviderStoreLifecycle< // Preserve usage history when the worker cannot start. console.warn(`${this.config.logTag} Reading the usage cache on the main thread:`, error) fallback = true + const loaded = this.config.readFallbackCache + ? await this.config.readFallbackCache(cacheFile) + : { state: await readUsageCacheJson(cacheFile), integrityVerified: false } + fallbackState = loaded.state + if (!fallbackState) { + throw new Error('Saved usage cache is invalid') + } return { - reportText: await readFile(cacheFile, 'utf-8'), + reportText: '', migrated: false, - reportIntegrityVerified: false + reportIntegrityVerified: loaded.integrityVerified } }) if (reportText === null) { return } - const parsed: State = JSON.parse(reportText) + const parsed: State = fallbackState ?? JSON.parse(reportText) this.inlineCache.active = fallback && !('usageIntegrity' in parsed) && Array.isArray(parsed[this.config.sourceKey]) && parsed[this.config.sourceKey].length > 0 - await this.applyReport(reportText, parsed, !fallback && reportIntegrityVerified === true) + await this.applyReport(reportText, parsed, reportIntegrityVerified === true) if (migrated) { // Future launches can read the compact report synchronously. await this.writeToDisk().catch(() => {}) diff --git a/src/main/usage/source-input/usage-record-coercion.ts b/src/main/usage/source-input/usage-record-coercion.ts index fe0700418d5..a409c7da406 100644 --- a/src/main/usage/source-input/usage-record-coercion.ts +++ b/src/main/usage/source-input/usage-record-coercion.ts @@ -1,11 +1,3 @@ export function ensureNumber(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) ? value : 0 } - -export function extractString(value: unknown): string | null { - if (typeof value !== 'string') { - return null - } - const trimmed = value.trim() - return trimmed.length > 0 ? trimmed : null -} diff --git a/src/main/warp-themes/index.test.ts b/src/main/warp-themes/index.test.ts index 89b72abb79a..d7776d39761 100644 --- a/src/main/warp-themes/index.test.ts +++ b/src/main/warp-themes/index.test.ts @@ -56,24 +56,6 @@ function fileEntry(name: string) { } } -function symlinkEntry(name: string) { - return { - name, - isFile: () => false, - isDirectory: () => false, - isSymbolicLink: () => true - } -} - -function directoryEntry(name: string) { - return { - name, - isFile: () => false, - isDirectory: () => true, - isSymbolicLink: () => false - } -} - function mockDirectory( entries: { name: string @@ -108,220 +90,6 @@ describe('previewWarpThemeImport', () => { parseWarpThemeYamlWithTimeoutMock.mockImplementation(parseWarpThemeYaml) }) - it('sorts theme files before duplicate id suffixing', async () => { - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes.map((theme) => theme.id)).toEqual([ - 'warp:duplicate:a-yml', - 'warp:duplicate:z-yml' - ]) - expect(readFileMock.mock.calls.map(([filePath]) => path.basename(filePath as string))).toEqual([ - 'a.yml', - 'z.yml' - ]) - }) - - it('returns an empty errorless preview when no local Warp theme folder exists', async () => { - statMock.mockImplementation(() => { - throw new Error('missing local themes') - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview).toMatchObject({ - found: false, - sourceLabel: 'Warp themes', - themes: [], - skippedFiles: [] - }) - expect(preview.error).toBeUndefined() - expect(readFileMock).not.toHaveBeenCalled() - }) - - it('returns an empty errorless preview for an empty readable local Warp theme folder', async () => { - opendirMock.mockResolvedValue(mockDirectory([])) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview).toMatchObject({ - found: false, - sourceLabel: 'Warp themes', - themes: [], - skippedFiles: [] - }) - expect(preview.error).toBeUndefined() - expect(readFileMock).not.toHaveBeenCalled() - }) - - it('merges themes from multiple readable Warp directories', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp-preview/themes' - ]) - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath === '/Users/alice/.warp/themes') { - return Promise.resolve(mockDirectory([fileEntry('stable.yaml')])) - } - if (directoryPath === '/Users/alice/.warp-preview/themes') { - return Promise.resolve(mockDirectory([fileEntry('preview.yaml')])) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(readFileMock.mock.calls.map(([filePath]) => filePath)).toEqual([ - path.join('/Users/alice/.warp/themes', 'stable.yaml'), - path.join('/Users/alice/.warp-preview/themes', 'preview.yaml') - ]) - expect(preview.themes.map((theme) => theme.sourceLabel)).toEqual(['.warp', '.warp-preview']) - }) - - it('continues scanning when an earlier Warp directory is empty', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp-oss/themes' - ]) - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath === '/Users/alice/.warp/themes') { - return Promise.resolve(mockDirectory([])) - } - if (directoryPath === '/Users/alice/.warp-oss/themes') { - return Promise.resolve(mockDirectory([fileEntry('oss.yaml')])) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.found).toBe(true) - expect(readFileMock.mock.calls.map(([filePath]) => filePath)).toEqual([ - path.join('/Users/alice/.warp-oss/themes', 'oss.yaml') - ]) - expect(preview.themes.map((theme) => theme.sourceLabel)).toEqual(['.warp-oss']) - }) - - it('dedupes symlinked theme files by canonical path while preserving stable-first order', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp-preview/themes' - ]) - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath === '/Users/alice/.warp/themes') { - return Promise.resolve(mockDirectory([fileEntry('shared.yaml')])) - } - if (directoryPath === '/Users/alice/.warp-preview/themes') { - return Promise.resolve(mockDirectory([fileEntry('shared.yaml')])) - } - return Promise.resolve(mockDirectory([])) - }) - realpathMock.mockResolvedValue('/Users/alice/.warp/themes/shared.yaml') - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(1) - expect(readFileMock).toHaveBeenCalledWith( - path.join('/Users/alice/.warp/themes', 'shared.yaml'), - 'utf-8' - ) - expect(preview.themes[0]?.sourceLabel).toBe('.warp') - expect(preview.skippedFiles).not.toContainEqual({ - label: 'Warp themes', - reason: 'Only the first 200 theme files were scanned.' - }) - }) - - it('discovers YAML files exposed as symlinked Warp theme entries', async () => { - opendirMock.mockResolvedValue(mockDirectory([symlinkEntry('linked.yaml')])) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.found).toBe(true) - expect(readFileMock).toHaveBeenCalledWith( - path.join('/Users/alice/.warp/themes', 'linked.yaml'), - 'utf-8' - ) - }) - - it('dedupes theme files by normalized resolved path when canonical paths are unavailable', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp/themes/../themes' - ]) - opendirMock.mockResolvedValue(mockDirectory([fileEntry('same.yaml')])) - realpathMock.mockRejectedValue(new Error('realpath unavailable')) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(1) - expect(readFileMock).toHaveBeenCalledTimes(1) - }) - - it('applies the theme file cap globally across merged auto-discovery directories', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp-preview/themes' - ]) - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath === '/Users/alice/.warp/themes') { - return Promise.resolve( - mockDirectory( - Array.from({ length: 150 }, (_, index) => fileEntry(`stable-${index}.yaml`)) - ) - ) - } - if (directoryPath === '/Users/alice/.warp-preview/themes') { - return Promise.resolve( - mockDirectory( - Array.from({ length: 150 }, (_, index) => fileEntry(`preview-${index}.yaml`)) - ) - ) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(200) - expect(readFileMock).toHaveBeenCalledTimes(200) - expect(preview.skippedFiles).toContainEqual({ - label: 'Warp themes', - reason: 'Only the first 200 theme files were scanned.' - }) - }) - - it('reports the theme cap when later Warp directories contain themes after the cap is full', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp-preview/themes' - ]) - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath === '/Users/alice/.warp/themes') { - return Promise.resolve( - mockDirectory( - Array.from({ length: 200 }, (_, index) => fileEntry(`stable-${index}.yaml`)) - ) - ) - } - if (directoryPath === '/Users/alice/.warp-preview/themes') { - return Promise.resolve(mockDirectory([fileEntry('preview.yaml')])) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(200) - expect(readFileMock).not.toHaveBeenCalledWith( - path.join('/Users/alice/.warp-preview/themes', 'preview.yaml'), - 'utf-8' - ) - expect(preview.skippedFiles).toContainEqual({ - label: 'Warp themes', - reason: 'Only the first 200 theme files were scanned.' - }) - }) - it('keeps scanning later directories for unique themes after duplicate canonical files', async () => { const stableDirectory = '/Users/alice/.warp/themes' const previewDirectory = '/Users/alice/.warp-preview/themes' @@ -361,100 +129,6 @@ describe('previewWarpThemeImport', () => { expect(readFileMock).toHaveBeenCalledWith(path.join(previewDirectory, 'unique.yaml'), 'utf-8') }) - it('reports bounded skips when local Warp folders are unreadable', async () => { - opendirMock.mockRejectedValue( - new Error("EACCES: permission denied, scandir '/Users/alice/.warp/themes'") - ) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.found).toBe(false) - expect(preview.sourceLabel).toBe('Warp themes') - expect(preview.skippedFiles).toEqual([{ label: '.warp', reason: 'Could not read folder.' }]) - expect(preview.themes).toEqual([]) - }) - - it('labels root skipped entries by auto-discovered Warp data home', async () => { - getWarpThemeDirectoriesMock.mockReturnValue([ - '/Users/alice/.warp/themes', - '/Users/alice/.warp-preview/themes' - ]) - opendirMock.mockRejectedValue(new Error('permission denied')) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.skippedFiles).toEqual([ - { label: '.warp', reason: 'Could not read folder.' }, - { label: '.warp-preview', reason: 'Could not read folder.' } - ]) - }) - - it('returns a bounded preview error for invalid sources without auto discovery', async () => { - const preview = await previewWarpThemeImport({} as Store, { kind: 'surprise' }) - const nullPreview = await previewWarpThemeImport({} as Store, null) - const extraFieldPreview = await previewWarpThemeImport({} as Store, { - kind: 'auto', - path: '/Users/alice/.warp/themes' - }) - - expect(preview).toEqual({ - found: false, - themes: [], - skippedFiles: [], - error: 'Invalid Warp theme import source.' - }) - expect(nullPreview.error).toBe('Invalid Warp theme import source.') - expect(extraFieldPreview.error).toBe('Invalid Warp theme import source.') - expect(getWarpThemeDirectoriesMock).not.toHaveBeenCalled() - }) - - it('uses stable file labels in imported theme ids', async () => { - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath.endsWith('themes')) { - return Promise.resolve( - mockDirectory([directoryEntry('standard'), directoryEntry('custom')]) - ) - } - if (directoryPath.endsWith('standard')) { - return Promise.resolve(mockDirectory([fileEntry('duplicate.yaml')])) - } - if (directoryPath.endsWith('custom')) { - return Promise.resolve(mockDirectory([fileEntry('duplicate.yaml')])) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes.map((theme) => theme.id)).toEqual([ - 'warp:duplicate:custom-duplicate-yaml', - 'warp:duplicate:standard-duplicate-yaml' - ]) - }) - - it('stops scheduling parser work when the preview budget expires', async () => { - let currentTime = 0 - parseWarpThemeYamlWithTimeoutMock.mockImplementation( - (...args: Parameters) => { - currentTime = 10 - return parseWarpThemeYaml(...args) - } - ) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }, undefined, { - operationBudgetMs: 5, - now: () => currentTime - }) - - expect(preview.themes).toHaveLength(1) - expect(parseWarpThemeYamlWithTimeoutMock).toHaveBeenCalledTimes(1) - expect(parseWarpThemeYamlWithTimeoutMock.mock.calls[0]?.[3]).toEqual({ timeoutMs: 5 }) - expect(preview.skippedFiles).toContainEqual({ - label: 'Warp themes', - reason: 'Preview budget expired before 1 theme file could be parsed.' - }) - }) - it('keeps same-basename manual file ids stable independent of dialog order', async () => { const firstPath = path.join('/Users/alice/light', 'duplicate.yaml') const secondPath = path.join('/Users/alice/dark', 'duplicate.yaml') @@ -485,195 +159,6 @@ describe('previewWarpThemeImport', () => { expect(ids.every((id) => id.startsWith('warp:duplicate:duplicate-yaml-'))).toBe(true) }) - it('marks dismissed file pickers as canceled', async () => { - showOpenDialogMock.mockResolvedValueOnce({ canceled: true, filePaths: [] }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'chooseFile' }) - - expect(preview).toEqual({ found: false, canceled: true, themes: [], skippedFiles: [] }) - }) - - it('starts the preview budget after a manual file picker returns', async () => { - let currentTime = 0 - showOpenDialogMock.mockImplementationOnce(() => { - currentTime = 10 - return Promise.resolve({ - canceled: false, - filePaths: [path.join('/Users/alice/themes', 'manual.yaml')] - }) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'chooseFile' }, undefined, { - operationBudgetMs: 5, - now: () => currentTime - }) - - expect(preview.themes).toHaveLength(1) - expect(parseWarpThemeYamlWithTimeoutMock.mock.calls[0]?.[3]).toEqual({ timeoutMs: 5 }) - expect(preview.skippedFiles).toEqual([]) - }) - - it('starts the preview budget after a manual folder picker returns', async () => { - let currentTime = 0 - showOpenDialogMock.mockImplementationOnce(() => { - currentTime = 10 - return Promise.resolve({ - canceled: false, - filePaths: ['/Users/alice/themes'] - }) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'chooseFolder' }, undefined, { - operationBudgetMs: 5, - now: () => currentTime - }) - - expect(preview.themes).toHaveLength(2) - expect(parseWarpThemeYamlWithTimeoutMock.mock.calls[0]?.[3]).toEqual({ timeoutMs: 5 }) - expect(preview.skippedFiles).toEqual([]) - }) - - it('finds themes in a cloned Warp themes repository layout', async () => { - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath.endsWith('themes')) { - return Promise.resolve( - mockDirectory([directoryEntry('standard'), directoryEntry('warp_bundled')]) - ) - } - if (directoryPath.endsWith('standard')) { - return Promise.resolve(mockDirectory([fileEntry('tokyo-night.yaml')])) - } - if (directoryPath.endsWith('warp_bundled')) { - return Promise.resolve(mockDirectory([fileEntry('dracula.yml')])) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.found).toBe(true) - expect(readFileMock.mock.calls.map(([filePath]) => filePath)).toEqual([ - path.join('/Users/alice/.warp/themes', 'standard', 'tokyo-night.yaml'), - path.join('/Users/alice/.warp/themes', 'warp_bundled', 'dracula.yml') - ]) - expect(preview.themes.map((theme) => theme.sourceLabel)).toEqual(['.warp', '.warp']) - }) - - it('caps broad folder scans before walking unbounded child directories', async () => { - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath.endsWith('themes')) { - return Promise.resolve( - mockDirectory( - Array.from({ length: 100 }, (_, index) => directoryEntry(`folder-${index}`)) - ) - ) - } - return Promise.resolve(mockDirectory([fileEntry(`${path.basename(directoryPath)}.yaml`)])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(79) - expect(preview.skippedFiles).toContainEqual({ - label: '.warp', - reason: 'Only the first 80 folders were scanned.' - }) - }) - - it('reports the theme cap when a nested folder fills the cap before later folders', async () => { - opendirMock.mockImplementation((directoryPath: string) => { - if (directoryPath.endsWith('themes')) { - return Promise.resolve( - mockDirectory([directoryEntry('standard'), directoryEntry('warp_bundled')]) - ) - } - if (directoryPath.endsWith('standard')) { - return Promise.resolve( - mockDirectory(Array.from({ length: 200 }, (_, index) => fileEntry(`theme-${index}.yaml`))) - ) - } - if (directoryPath.endsWith('warp_bundled')) { - return Promise.resolve(mockDirectory([fileEntry('extra.yaml')])) - } - return Promise.resolve(mockDirectory([])) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(200) - expect(preview.skippedFiles).toContainEqual({ - label: 'Warp themes', - reason: 'Only the first 200 theme files were scanned.' - }) - expect(opendirMock).not.toHaveBeenCalledWith( - path.join('/Users/alice/.warp/themes', 'warp_bundled'), - expect.anything() - ) - }) - - it('caps entries processed from one large folder', async () => { - opendirMock.mockResolvedValue( - mockDirectory(Array.from({ length: 501 }, (_, index) => fileEntry(`theme-${index}.yaml`))) - ) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.themes).toHaveLength(200) - expect(preview.skippedFiles).toEqual( - expect.arrayContaining([ - { - label: '.warp', - reason: 'Only the first 500 folder entries were scanned.' - }, - { - label: 'Warp themes', - reason: 'Only the first 200 theme files were scanned.' - } - ]) - ) - }) - - it('reports capped manually selected theme files after deterministic YAML sorting', async () => { - const themePaths = Array.from({ length: 201 }, (_, index) => - path.join('/Users/alice/warp-themes', `theme-${String(index).padStart(3, '0')}.yaml`) - ) - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: [ - path.join('/Users/alice/warp-themes', 'aaa-not-theme.txt'), - ...themePaths - ].toReversed() - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'chooseFile' }) - - expect(preview.themes).toHaveLength(200) - expect(readFileMock.mock.calls[0]?.[0]).toBe(themePaths[0]) - expect(readFileMock.mock.calls.at(-1)?.[0]).toBe(themePaths[199]) - expect(preview.skippedFiles).toContainEqual({ - label: 'Selected Warp themes', - reason: 'Only the first 200 theme files were scanned.' - }) - }) - - it('does not report the manual theme cap for extra non-YAML selections', async () => { - const themePaths = Array.from({ length: 200 }, (_, index) => - path.join('/Users/alice/warp-themes', `theme-${String(index).padStart(3, '0')}.yaml`) - ) - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: [...themePaths, path.join('/Users/alice/warp-themes', 'readme.txt')] - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'chooseFile' }) - - expect(preview.themes).toHaveLength(200) - expect(preview.skippedFiles).not.toContainEqual({ - label: 'Selected Warp themes', - reason: 'Only the first 200 theme files were scanned.' - }) - }) - it('stops streaming a large folder after the entry budget', async () => { const yieldedNames: string[] = [] opendirMock.mockResolvedValue({ @@ -692,18 +177,4 @@ describe('previewWarpThemeImport', () => { expect(yieldedNames).not.toContain('theme-501.yaml') expect(yieldedNames).not.toContain('theme-999.yaml') }) - - it('does not copy absolute file paths into skipped reasons', async () => { - opendirMock.mockResolvedValue(mockDirectory([fileEntry('private.yml')])) - statMock.mockImplementation((filePath: string) => { - if (filePath.endsWith('private.yml')) { - throw new Error("EACCES: permission denied, stat '/Users/alice/.warp/themes/private.yml'") - } - return mockStat(filePath) - }) - - const preview = await previewWarpThemeImport({} as Store, { kind: 'auto' }) - - expect(preview.skippedFiles).toEqual([{ label: 'private.yml', reason: 'Could not read file.' }]) - }) }) diff --git a/src/main/window/focus-existing-window.ts b/src/main/window/activation/focus-existing-window.ts similarity index 100% rename from src/main/window/focus-existing-window.ts rename to src/main/window/activation/focus-existing-window.ts diff --git a/src/main/window/activation/foreground-activation-policy.test.ts b/src/main/window/activation/foreground-activation-policy.test.ts new file mode 100644 index 00000000000..c89d058302e --- /dev/null +++ b/src/main/window/activation/foreground-activation-policy.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ app: { dock: { hide: vi.fn() }, setActivationPolicy: vi.fn() } })) + +const { applyBackgroundActivationPolicy, applyServeDesktopWindowActivationPolicy } = + await import('./foreground-activation-policy') + +describe('applyBackgroundActivationPolicy', () => { + function makeApp() { + return { + dock: { hide: vi.fn(() => {}), show: vi.fn(async () => {}) }, + setActivationPolicy: vi.fn((_policy: 'accessory' | 'prohibited' | 'regular') => {}) + } + } + + it('keeps a windowless macOS serve out of the Dock until it hosts a desktop window', () => { + const app = makeApp() + expect( + applyBackgroundActivationPolicy({ + app, + env: {}, + platform: 'darwin', + serveWithoutDesktopWindow: true + }) + ).toBe(true) + expect(app.setActivationPolicy).toHaveBeenLastCalledWith('accessory') + + expect(applyServeDesktopWindowActivationPolicy({ app, env: {}, platform: 'darwin' })).toBe(true) + expect(app.setActivationPolicy).toHaveBeenLastCalledWith('regular') + expect(app.dock.show).toHaveBeenCalledOnce() + }) + + it('never gives a background serve its Dock tile back', () => { + const app = makeApp() + expect( + applyServeDesktopWindowActivationPolicy({ + app, + env: { ORCA_BACKGROUND_LAUNCH: '1' }, + platform: 'darwin' + }) + ).toBe(false) + expect( + applyServeDesktopWindowActivationPolicy({ + app, + env: { ORCA_E2E_HEADFUL: '1' }, + platform: 'darwin' + }) + ).toBe(false) + expect(app.setActivationPolicy).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/window/foreground-activation-policy.ts b/src/main/window/activation/foreground-activation-policy.ts similarity index 94% rename from src/main/window/foreground-activation-policy.ts rename to src/main/window/activation/foreground-activation-policy.ts index 739b9119937..5f0926df050 100644 --- a/src/main/window/foreground-activation-policy.ts +++ b/src/main/window/activation/foreground-activation-policy.ts @@ -117,7 +117,11 @@ function stopAwaitingAppActive(): void { electronApp.off('did-become-active', revealWindowsAwaitingAppActive) } -function revealWindowsAwaitingAppActive(): void { +/** The user is back in Orca. Origin-bar popups (plain BaseWindows) call this on focus, since only BrowserWindows raise `browser-window-focus`. */ +export function revealWindowsAwaitingAppActive(): void { + if (windowsAwaitingAppActive.size === 0) { + return + } stopAwaitingAppActive() for (const window of windowsAwaitingAppActive) { if (!window.isDestroyed()) { @@ -138,7 +142,7 @@ export function showWhenAppActive(window: BaseWindow, env: PolicyEnv = process.e return } if (windowsAwaitingAppActive.size === 0) { - // macOS reports the app's return through any window; elsewhere only BrowserWindows report focus. + // macOS reports the app's return through any window; elsewhere BrowserWindows and origin-bar popups report focus. electronApp.on('browser-window-focus', revealWindowsAwaitingAppActive) electronApp.on('did-become-active', revealWindowsAwaitingAppActive) } diff --git a/src/main/window/macos-app-activation.ts b/src/main/window/activation/macos-app-activation.ts similarity index 100% rename from src/main/window/macos-app-activation.ts rename to src/main/window/activation/macos-app-activation.ts diff --git a/src/main/window/macos-desktop-handoff.ts b/src/main/window/activation/macos-desktop-handoff.ts similarity index 100% rename from src/main/window/macos-desktop-handoff.ts rename to src/main/window/activation/macos-desktop-handoff.ts diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index af4bbf2911a..c8b3ef84955 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -36,23 +36,21 @@ import { openCodeHookService, openCode2HookService } from '../opencode/status-ho import { listLiveDaemonPtyIds } from '../daemon/providers/lifecycle/daemon-provider-state' import { hydrateLocalPtyRegistryAtBoot } from '../memory/hydrate-local-pty-registry' import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' -import { getKnownWorktreeIdsForHistoryGc } from './history-gc-worktree-ids' +import { getKnownWorktreeIdsForHistoryGc } from '../pty/history/history-gc-worktree-ids' import type { ClaudeAccountSelectionTarget } from '../claude-accounts/selection/runtime-selection' import { scheduleWorktreeBaseDirectoryWatcherSync, setWorktreeBaseDirectoryWatcherSyncContext } from '../ipc/worktrees/creation/worktree-base-directory-watcher' import { startFolderRepoGitUpgradeWatch } from '../ipc/folder-repo-git-upgrade' -import { scheduleMainWindowAutoUpdaterSetup } from './main-window-updater' +import { scheduleMainWindowAutoUpdaterSetup } from '../updater/lifecycle/main-window-updater' import { registerRuntimeWindowLifecycle } from './runtime-window-lifecycle' import { ensureStructuredAgentSessionHostUnlessRefused } from '../runtime/agent-session/structured-agent-session-host-refusal' import { getAgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store-registry' -import { registerDroppedPathPreparation } from './dropped-path-preparation-ipc' -import { isPluginFramePermissionRequest } from './host-frame-permission-policy' +import { registerDroppedPathPreparation } from './file-drop/dropped-path-preparation-ipc' +import { isPluginFramePermissionRequest } from './security/host-frame-permission-policy' import { installPluginDesktopFrameServices } from '../plugins/panels/desktop-actions/plugin-frame-desktop-services' -export { ensureAutoUpdaterConfigured, registerUpdaterHandlers } from './main-window-updater' - let appReloadHandlerTokenCounter = 0 let activeAppReloadHandlerToken: number | null = null let tccPromptHandlerTokenCounter = 0 @@ -94,7 +92,7 @@ export function attachMainWindowServices( scheduleWorktreeBaseDirectoryWatcherSync(store, mainWindow) // Folder projects have no watcher target; poll for external git init so they upgrade without restart (#11477). startFolderRepoGitUpgradeWatch(store, mainWindow) - registerWorkspaceCleanupHandlers(store) + registerWorkspaceCleanupHandlers(store, () => runtime.getExistingOrchestrationDb()) registerPtyHandlers( mainWindow, runtime, diff --git a/src/main/window/clipboard-text-publisher.test.ts b/src/main/window/clipboard-text-publisher.test.ts deleted file mode 100644 index 3f585fec2d8..00000000000 --- a/src/main/window/clipboard-text-publisher.test.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' -import { - assertClipboardTextWriteWithinLimitWithYield, - CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS, - CLIPBOARD_TEXT_WRITE_MAX_BYTES -} from '../../shared/clipboard-text' -import { CLIPBOARD_IMAGE_MAX_BASE64_CHARS } from '../../shared/clipboard-image' -import { createClipboardPublisher } from './clipboard-text-publisher' - -vi.mock('electron', () => ({ app: {}, clipboard: {} })) - -const ok: ProcessResult = { code: 0, signal: null, stdout: '', stderr: '', timedOut: false } -const run = vi.fn(async (_spec: ProcessSpec): Promise => ok) -const write = vi.fn() -const clearCache = vi.fn() -function publisher(wayland = true, validate = assertClipboardTextWriteWithinLimitWithYield) { - return createClipboardPublisher({ - isWayland: () => wayland, - helperPath: () => '/bundle/bin/orca-wayland-clipboard', - run, - write, - clearCache, - validate - }) -} -function writer(wayland = true, validate = assertClipboardTextWriteWithinLimitWithYield) { - return publisher(wayland, validate).publishText -} - -describe('terminal clipboard writes', () => { - beforeEach(() => { - vi.resetAllMocks() - run.mockResolvedValue(ok) - }) - - it('publishes different and duplicate text without asking Electron to own the selection', async () => { - const copy = writer() - const text = '遥か\r\nline two\n' - await copy(text) - await copy(text) - expect(run).toHaveBeenCalledTimes(2) - expect(run).toHaveBeenCalledWith({ - program: '/bundle/bin/orca-wayland-clipboard', - input: text, - timeoutMs: 2000, - stdio: ['pipe', 'ignore', 'ignore'] - }) - expect(write).not.toHaveBeenCalled() - expect(clearCache).toHaveBeenCalledTimes(2) - }) - - it('only discards a rejected Chromium source after the new owner is acknowledged', async () => { - let release: (value: typeof ok) => void = () => undefined - run.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - const pending = writer()('copy') - await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) - expect(clearCache).not.toHaveBeenCalled() - release(ok) - await pending - expect(clearCache).toHaveBeenCalledTimes(1) - }) - - it.each([ - ['timeout', { ...ok, code: null, timedOut: true }], - ['helper failure', { ...ok, code: 70 }] - ])('rejects %s without falling back to an unsafe Electron write', async (_label, result) => { - run.mockResolvedValueOnce(result) - await expect(writer()('copy')).rejects.toThrow('Wayland clipboard write failed') - expect(write).not.toHaveBeenCalled() - expect(clearCache).not.toHaveBeenCalled() - }) - - it('preserves the existing clipboard when the bundled helper cannot start', async () => { - run.mockRejectedValueOnce(new Error('ENOENT')) - await expect(writer()('copy')).rejects.toThrow('ENOENT') - expect(write).not.toHaveBeenCalled() - expect(clearCache).not.toHaveBeenCalled() - }) - - it('retains verified Electron writes outside native Wayland', async () => { - await writer(false)('copy') - expect(write).toHaveBeenCalledWith('copy', 'terminal') - expect(run).not.toHaveBeenCalled() - expect(clearCache).not.toHaveBeenCalled() - }) - - it('rejects oversized text before either clipboard backend is invoked', async () => { - await expect(writer()('x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1))).rejects.toThrow( - 'Clipboard text is too large' - ) - expect(run).not.toHaveBeenCalled() - expect(write).not.toHaveBeenCalled() - }) - - it.each([false, true])( - 'keeps a newer copy after yielding validation (Wayland=%s)', - async (wayland) => { - vi.useFakeTimers() - try { - const copy = writer(wayland) - const large = 'x'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS * 2) - const first = copy(large, 'terminal') - const second = copy('newer', 'ordinary') - - await vi.runAllTimersAsync() - await Promise.all([first, second]) - - if (wayland) { - expect(run.mock.calls.map(([spec]) => spec.input === large)).toEqual([true, false]) - expect(run.mock.calls[1]?.[0].input).toBe('newer') - expect(write).not.toHaveBeenCalled() - } else { - expect(write.mock.calls.map(([text, kind]) => [text === large, kind])).toEqual([ - [true, 'terminal'], - [false, 'ordinary'] - ]) - expect(write.mock.calls[1]?.[0]).toBe('newer') - expect(run).not.toHaveBeenCalled() - } - } finally { - vi.useRealTimers() - } - } - ) - - it('preserves request order across yielding validation and resumes after failure', async () => { - let release: (text: string) => void = () => undefined - const validate = vi.fn(async (text: string) => text) - validate.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - run.mockRejectedValueOnce(new Error('helper failed')) - const copy = writer(true, validate) - const first = copy('first') - const firstRejected = expect(first).rejects.toThrow('helper failed') - const second = copy('second') - await vi.waitFor(() => expect(validate).toHaveBeenCalledTimes(1)) - expect(run).not.toHaveBeenCalled() - release('first') - await firstRejected - await second - expect(run.mock.calls.map(([spec]) => spec.input)).toEqual(['first', 'second']) - expect(clearCache).toHaveBeenCalledTimes(1) - }) - - it.each([ - { label: 'count', count: 32, bytes: 1 }, - { label: 'retained bytes', count: 1, bytes: CLIPBOARD_IMAGE_MAX_BASE64_CHARS * 2 } - ])( - 'bounds other clipboard operations by $label and releases capacity after failure', - async ({ count, bytes }) => { - const copy = publisher(false) - let release: () => void = () => undefined - const gate = new Promise((resolve) => { - release = resolve - }) - const publications: number[] = [] - const first = copy.publish(bytes, async () => { - await gate - throw new Error('file helper failed') - }) - const rejected = expect(first).rejects.toThrow('file helper failed') - const queued = Array.from({ length: count - 1 }, (_, index) => - copy.publish(bytes, () => { - publications.push(index) - return index - }) - ) - await expect(copy.publish(bytes, () => publications.push(-1))).rejects.toThrow( - 'Too many pending clipboard writes' - ) - expect(publications).toEqual([]) - const text = copy.publishText('after failed file', 'ordinary') - release() - await rejected - await Promise.all(queued) - await text - expect(publications).toHaveLength(count - 1) - expect(publications).not.toContain(-1) - expect(write).toHaveBeenLastCalledWith('after failed file', 'ordinary') - await expect(copy.publish(bytes, () => 'after flood')).resolves.toBe('after flood') - } - ) - - it('bounds requests queued behind a stalled helper', async () => { - let release: (value: typeof ok) => void = () => undefined - run.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - const copy = writer() - const queued = Array.from({ length: 32 }, (_, index) => copy(String(index))) - await expect(copy('overflow')).rejects.toThrow('Too many pending clipboard writes') - await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) - release(ok) - await Promise.all(queued) - await copy('after flood') - expect(run).toHaveBeenCalledTimes(33) - }) - - it('bounds the total text retained behind a stalled helper', async () => { - let release: (value: typeof ok) => void = () => undefined - run.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - const copy = writer(true, async (text) => text) - const text = 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES / 2 + 1) - const first = copy(text) - await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) - let failure: unknown - void copy(text).catch((error: unknown) => { - failure = error - }) - await vi.waitFor( - () => expect(failure).toEqual(new Error('Too many pending clipboard writes')), - { timeout: 200 } - ) - release(ok) - await first - await copy(text) - expect(run).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/window/clipboard-agent-session-attachment-paste.test.ts b/src/main/window/clipboard/clipboard-agent-session-attachment-paste.test.ts similarity index 86% rename from src/main/window/clipboard-agent-session-attachment-paste.test.ts rename to src/main/window/clipboard/clipboard-agent-session-attachment-paste.test.ts index ababc677469..39d2a67c844 100644 --- a/src/main/window/clipboard-agent-session-attachment-paste.test.ts +++ b/src/main/window/clipboard/clipboard-agent-session-attachment-paste.test.ts @@ -3,7 +3,7 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' +import { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' const mocks = vi.hoisted(() => ({ handle: vi.fn(), @@ -21,22 +21,20 @@ vi.mock('electron', () => ({ ipcMain: { removeHandler: vi.fn(), handle: mocks.handle }, nativeImage: { createFromBuffer: vi.fn() } })) -vi.mock('../ipc/runtime-environments/runtime-environment-transport-routing', () => ({ +vi.mock('../../ipc/runtime-environments/requests/runtime-environment-transport-routing', () => ({ callRuntimeEnvironment: mocks.callRuntimeEnvironment })) -vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ +vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ resolveEnvironment: (_userDataPath: string, selector: string) => ({ id: selector }) })) vi.mock('./clipboard-remote-file-copy', () => ({ cleanupExpiredRemoteClipboardFiles: vi.fn(async () => {}), scheduleLegacyRemoteClipboardFileCleanup: vi.fn() })) -vi.mock('./dashboard-popout-window', () => ({ isDashboardPopoutRenderer: () => false })) +vi.mock('../dashboard-popout-window', () => ({ isDashboardPopoutRenderer: () => false })) -import { - registerClipboardHandlers, - setTrustedClipboardRendererWebContentsId -} from './clipboard-ipc-handlers' +import { registerClipboardHandlers } from './clipboard-ipc-handlers' +import { setTrustedClipboardRendererWebContentsId } from './clipboard-ipc-sender-trust' function saveHandler(): (...args: unknown[]) => Promise { const entry = mocks.handle.mock.calls.find( @@ -103,7 +101,6 @@ describe('clipboard:saveImageAsTempFile for a local structured chat', () => { ) expect(String(saved).startsWith(root)).toBe(true) expect(await readFile(String(saved), 'utf8')).toBe('png') - expect(mocks.callRuntimeEnvironment).not.toHaveBeenCalled() } finally { await rm(root, { recursive: true, force: true }) } diff --git a/src/main/window/clipboard-copied-file-paths.test.ts b/src/main/window/clipboard/clipboard-copied-file-paths.test.ts similarity index 100% rename from src/main/window/clipboard-copied-file-paths.test.ts rename to src/main/window/clipboard/clipboard-copied-file-paths.test.ts diff --git a/src/main/window/clipboard-copied-file-paths.ts b/src/main/window/clipboard/clipboard-copied-file-paths.ts similarity index 100% rename from src/main/window/clipboard-copied-file-paths.ts rename to src/main/window/clipboard/clipboard-copied-file-paths.ts diff --git a/src/main/window/clipboard-dashboard-popout-access.test.ts b/src/main/window/clipboard/clipboard-dashboard-popout-access.test.ts similarity index 94% rename from src/main/window/clipboard-dashboard-popout-access.test.ts rename to src/main/window/clipboard/clipboard-dashboard-popout-access.test.ts index 889afa780e0..62ef2923e39 100644 --- a/src/main/window/clipboard-dashboard-popout-access.test.ts +++ b/src/main/window/clipboard/clipboard-dashboard-popout-access.test.ts @@ -36,16 +36,14 @@ vi.mock('electron', () => ({ nativeImage: { createFromBuffer: vi.fn() } })) -vi.mock('./dashboard-popout-window', () => ({ isDashboardPopoutRenderer })) +vi.mock('../dashboard-popout-window', () => ({ isDashboardPopoutRenderer })) vi.mock('./clipboard-remote-file-copy', () => ({ cleanupExpiredRemoteClipboardFiles: vi.fn(async () => undefined), scheduleLegacyRemoteClipboardFileCleanup: vi.fn() })) -import { - registerClipboardHandlers, - setTrustedClipboardRendererWebContentsId -} from './clipboard-ipc-handlers' +import { registerClipboardHandlers } from './clipboard-ipc-handlers' +import { setTrustedClipboardRendererWebContentsId } from './clipboard-ipc-sender-trust' const popoutEvent = { sender: { diff --git a/src/main/window/clipboard-file-copy.ts b/src/main/window/clipboard/clipboard-file-copy.ts similarity index 98% rename from src/main/window/clipboard-file-copy.ts rename to src/main/window/clipboard/clipboard-file-copy.ts index 43886735ac2..c2cc2044eeb 100644 --- a/src/main/window/clipboard-file-copy.ts +++ b/src/main/window/clipboard/clipboard-file-copy.ts @@ -2,7 +2,7 @@ import { isAbsolute } from 'node:path' import { pathToFileURL } from 'node:url' import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' import { windowsPowerShellPath } from '@orca/process-host/windows-system-binary' -import { withTimeout } from '../../shared/promise-timeout-fallback' +import { withTimeout } from '../../../shared/promise-timeout-fallback' export type ClipboardFileResult = { ok: boolean; reason?: string } diff --git a/src/main/window/clipboard-image-png-encode.ts b/src/main/window/clipboard/clipboard-image-png-encode.ts similarity index 84% rename from src/main/window/clipboard-image-png-encode.ts rename to src/main/window/clipboard/clipboard-image-png-encode.ts index a40df8f3641..701ebd1a0a7 100644 --- a/src/main/window/clipboard-image-png-encode.ts +++ b/src/main/window/clipboard/clipboard-image-png-encode.ts @@ -1,5 +1,5 @@ import type { NativeImage } from 'electron' -import { encodeClipboardImageWithinLimit } from '../../shared/clipboard-image' +import { encodeClipboardImageWithinLimit } from '../../../shared/clipboard-image' export function encodeClipboardNativeImagePng( image: Pick diff --git a/src/main/window/clipboard-image-source.ts b/src/main/window/clipboard/clipboard-image-source.ts similarity index 94% rename from src/main/window/clipboard-image-source.ts rename to src/main/window/clipboard/clipboard-image-source.ts index 6bcb4e168ee..1f64770008f 100644 --- a/src/main/window/clipboard-image-source.ts +++ b/src/main/window/clipboard/clipboard-image-source.ts @@ -1,4 +1,4 @@ -import { clipboardFormatsIncludeImage } from '../../shared/clipboard-image' +import { clipboardFormatsIncludeImage } from '../../../shared/clipboard-image' import { readWindowsCopiedImageFilePath, type WindowsClipboardFileFormats diff --git a/src/main/window/clipboard-image-temp-file.ts b/src/main/window/clipboard/clipboard-image-temp-file.ts similarity index 78% rename from src/main/window/clipboard-image-temp-file.ts rename to src/main/window/clipboard/clipboard-image-temp-file.ts index 20f182648a3..ba443aebdbb 100644 --- a/src/main/window/clipboard-image-temp-file.ts +++ b/src/main/window/clipboard/clipboard-image-temp-file.ts @@ -2,16 +2,16 @@ import fs from 'node:fs/promises' import path from 'node:path' import { randomUUID } from 'node:crypto' -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' -import { getAppEnvironment } from '../../shared/app-environment' -import { assertClipboardImageByteLengthWithinLimit } from '../../shared/clipboard-image' +import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' +import { getAppEnvironment } from '../../../shared/app-environment' +import { assertClipboardImageByteLengthWithinLimit } from '../../../shared/clipboard-image' import { agentSessionPastedImageName, sanitizeAgentSessionAttachmentName, type AgentSessionAttachmentClipboardTarget -} from '../../shared/agent-session/agent-session-attachments' -import { detectImageFileSignature } from '../media/image-file-signature' -import { nativeChatPasteFolder } from './native-chat-paste-files' +} from '../../../shared/agent-session/agent-session-attachments' +import { detectImageFileExtension } from '../../../shared/image-file-signature' +import { nativeChatPasteFolder } from '../../native-chat/paste-files/native-chat-paste-files' export type SaveClipboardImageAsTempFileArgs = { connectionId?: string | null @@ -52,12 +52,8 @@ export async function saveClipboardImageBufferAsTempFile( ? path.join(folder, `orca-paste-${randomUUID()}`, shellInertFileName(args.fileName)) : path.join( folder, - // Phone library picks are often JPEG; agents trust the extension over the bytes. - agentSessionPastedImageName( - Date.now(), - randomUUID(), - detectImageFileSignature(buffer)?.extension - ) + // Phone picks are often JPEG or HEIC; agents trust the extension over the bytes. + agentSessionPastedImageName(Date.now(), randomUUID(), detectImageFileExtension(buffer)) ) if (args?.fileName) { await fs.mkdir(path.dirname(tempPath), { recursive: true }) diff --git a/src/main/window/clipboard-image-thumbnail.ts b/src/main/window/clipboard/clipboard-image-thumbnail.ts similarity index 96% rename from src/main/window/clipboard-image-thumbnail.ts rename to src/main/window/clipboard/clipboard-image-thumbnail.ts index 3d9e9633eea..9976597f0ca 100644 --- a/src/main/window/clipboard-image-thumbnail.ts +++ b/src/main/window/clipboard/clipboard-image-thumbnail.ts @@ -2,7 +2,7 @@ import { clipboardImageThumbnailSize, type ClipboardImageDimensions, type ClipboardImageThumbnail -} from '../../shared/clipboard-image' +} from '../../../shared/clipboard-image' /** Minimal NativeImage surface for tests without an Electron runtime. */ export type ClipboardImageLike = { diff --git a/src/main/window/clipboard-ipc-handlers.ts b/src/main/window/clipboard/clipboard-ipc-handlers.ts similarity index 91% rename from src/main/window/clipboard-ipc-handlers.ts rename to src/main/window/clipboard/clipboard-ipc-handlers.ts index 4ab7419c76c..0696415f903 100644 --- a/src/main/window/clipboard-ipc-handlers.ts +++ b/src/main/window/clipboard/clipboard-ipc-handlers.ts @@ -2,10 +2,10 @@ import { app, clipboard, ipcMain, nativeImage } from 'electron' import { randomUUID } from 'node:crypto' import { open, stat } from 'node:fs/promises' import { runProcess } from '@orca/process-host' -import type { Store } from '../persistence/loading-store/store' -import { PATH_ACCESS_DENIED_MESSAGE } from '../ipc/filesystem/access/filesystem-auth' -import { resolveDesktopAuthorizedPath } from '../ipc/filesystem/access/local-file-access-resolution' -import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' +import type { Store } from '../../persistence/loading-store/store' +import { PATH_ACCESS_DENIED_MESSAGE } from '../../ipc/filesystem/access/filesystem-auth' +import { resolveDesktopAuthorizedPath } from '../../ipc/filesystem/access/local-file-access-resolution' +import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' import { assertTrustedClipboardSender, assertTrustedClipboardTextSender @@ -14,8 +14,8 @@ import { assertClipboardTextWriteWithinLimitWithYield, assertClipboardTextWithinLimitWithYield, type ReadClipboardTextOptions -} from '../../shared/clipboard-text' -import { clipboardHtmlMayHaveLinks } from '../../shared/clipboard-link-html' +} from '../../../shared/clipboard-text' +import { clipboardHtmlMayHaveLinks } from '../../../shared/clipboard-link-html' import { saveClipboardImageBufferAsTempFile, type SaveClipboardImageAsTempFileArgs @@ -25,19 +25,19 @@ import { assertClipboardImageByteLengthWithinLimit, assertClipboardImageDimensionsWithinLimit, type ClipboardImageThumbnail -} from '../../shared/clipboard-image' +} from '../../../shared/clipboard-image' import { writeFileToClipboard, type ClipboardFileDeps, type ClipboardFileResult } from './clipboard-file-copy' -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' +import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { cleanupExpiredRemoteClipboardFiles, scheduleLegacyRemoteClipboardFileCleanup } from './clipboard-remote-file-copy' import { saveClipboardImageBufferInRuntime } from './clipboard-runtime-image-upload' -import { uploadPasteToAgentSessionAttachments } from '../ipc/agent-session-attachment-upload' +import { uploadPasteToAgentSessionAttachments } from '../../ipc/agent-session-attachment-upload' import { readWindowsClipboardImageFileAsPng } from './clipboard-windows-image-file' import { readClipboardImageSource } from './clipboard-image-source' import { readClipboardCopiedFilePaths } from './clipboard-copied-file-paths' @@ -50,12 +50,10 @@ import { publishClipboardOperation, publishClipboardText } from './clipboard-text-publisher' -import { restoreNativeChatPastes } from './native-chat-paste-files' +import { restoreNativeChatPastes } from '../../native-chat/paste-files/native-chat-paste-files' import { savePastedTextAsFile, type SavePastedTextAsFileArgs } from './native-chat-pasted-text-file' -import { agentSessionPastedImageName } from '../../shared/agent-session/agent-session-attachments' -import type { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' - -export { setTrustedClipboardRendererWebContentsId } from './clipboard-ipc-sender-trust' +import { agentSessionPastedImageName } from '../../../shared/agent-session/agent-session-attachments' +import type { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' type ClipboardWriteFileRequest = { filePath: string diff --git a/src/main/window/clipboard-ipc-sender-trust.ts b/src/main/window/clipboard/clipboard-ipc-sender-trust.ts similarity index 86% rename from src/main/window/clipboard-ipc-sender-trust.ts rename to src/main/window/clipboard/clipboard-ipc-sender-trust.ts index 8961d5147de..7febecd0dff 100644 --- a/src/main/window/clipboard-ipc-sender-trust.ts +++ b/src/main/window/clipboard/clipboard-ipc-sender-trust.ts @@ -1,6 +1,6 @@ import type { IpcMainInvokeEvent, WebContents } from 'electron' -import { isTrustedMainRendererSender } from '../ipc/main-renderer-sender-trust' -import { isDashboardPopoutRenderer } from './dashboard-popout-window' +import { isTrustedMainRendererSender } from '../../ipc/main-renderer-sender-trust' +import { isDashboardPopoutRenderer } from '../dashboard-popout-window' let trustedClipboardRendererWebContentsId: number | null = null diff --git a/src/main/window/clipboard-macos-image-paste.test.ts b/src/main/window/clipboard/clipboard-macos-image-paste.test.ts similarity index 86% rename from src/main/window/clipboard-macos-image-paste.test.ts rename to src/main/window/clipboard/clipboard-macos-image-paste.test.ts index 66c5f3b103a..3b3e9bd95b6 100644 --- a/src/main/window/clipboard-macos-image-paste.test.ts +++ b/src/main/window/clipboard/clipboard-macos-image-paste.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as FsPromises from 'node:fs/promises' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import '../../shared/clipboard-image' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import '../../../shared/clipboard-image' const mocks = vi.hoisted(() => ({ handlers: new Map unknown>(), @@ -32,22 +32,20 @@ vi.mock('node:fs/promises', async (importOriginal) => { const fs = await importOriginal() return { ...fs, default: { ...fs, writeFile: mocks.writeFile } } }) -vi.mock('../persistence/loading-store/store', () => ({ Store: vi.fn() })) +vi.mock('../../persistence/loading-store/store', () => ({ Store: vi.fn() })) vi.mock('./clipboard-remote-file-copy', () => ({ cleanupExpiredRemoteClipboardFiles: vi.fn(), scheduleLegacyRemoteClipboardFileCleanup: vi.fn() })) -vi.mock('./native-chat-paste-files', () => ({ +vi.mock('../../native-chat/paste-files/native-chat-paste-files', () => ({ restoreNativeChatPastes: vi.fn(), nativeChatPasteFolder: () => '/tmp/native-chat-pastes' })) -vi.mock('./dashboard-popout-window', () => ({ isDashboardPopoutRenderer: () => false })) +vi.mock('../dashboard-popout-window', () => ({ isDashboardPopoutRenderer: () => false })) -import { Store } from '../persistence/loading-store/store' -import { - registerClipboardHandlers, - setTrustedClipboardRendererWebContentsId -} from './clipboard-ipc-handlers' +import { Store } from '../../persistence/loading-store/store' +import { registerClipboardHandlers } from './clipboard-ipc-handlers' +import { setTrustedClipboardRendererWebContentsId } from './clipboard-ipc-sender-trust' const event = { sender: { diff --git a/src/main/window/clipboard-native-image.ts b/src/main/window/clipboard/clipboard-native-image.ts similarity index 84% rename from src/main/window/clipboard-native-image.ts rename to src/main/window/clipboard/clipboard-native-image.ts index b93b8273478..1028333734c 100644 --- a/src/main/window/clipboard-native-image.ts +++ b/src/main/window/clipboard/clipboard-native-image.ts @@ -2,8 +2,8 @@ import { clipboard, nativeImage, type NativeImage } from 'electron' import { assertClipboardImageByteLengthWithinLimit, assertClipboardImageDimensionsWithinLimit -} from '../../shared/clipboard-image' -import { readRasterImageDimensions } from '../../shared/file-preview/raster-image-dimensions' +} from '../../../shared/clipboard-image' +import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions' export function readClipboardNativeImage(): NativeImage { const image = clipboard.readImage() diff --git a/src/main/window/clipboard-plain-text-read.test.ts b/src/main/window/clipboard/clipboard-plain-text-read.test.ts similarity index 100% rename from src/main/window/clipboard-plain-text-read.test.ts rename to src/main/window/clipboard/clipboard-plain-text-read.test.ts diff --git a/src/main/window/clipboard-plain-text-read.ts b/src/main/window/clipboard/clipboard-plain-text-read.ts similarity index 100% rename from src/main/window/clipboard-plain-text-read.ts rename to src/main/window/clipboard/clipboard-plain-text-read.ts diff --git a/src/main/window/clipboard-publisher-executable.test.ts b/src/main/window/clipboard/clipboard-publisher-executable.test.ts similarity index 100% rename from src/main/window/clipboard-publisher-executable.test.ts rename to src/main/window/clipboard/clipboard-publisher-executable.test.ts diff --git a/src/main/window/clipboard-publisher-executable.ts b/src/main/window/clipboard/clipboard-publisher-executable.ts similarity index 100% rename from src/main/window/clipboard-publisher-executable.ts rename to src/main/window/clipboard/clipboard-publisher-executable.ts diff --git a/src/main/window/clipboard-remote-file-copy.ts b/src/main/window/clipboard/clipboard-remote-file-copy.ts similarity index 100% rename from src/main/window/clipboard-remote-file-copy.ts rename to src/main/window/clipboard/clipboard-remote-file-copy.ts diff --git a/src/main/window/clipboard-remote-file-staging-fs.test.ts b/src/main/window/clipboard/clipboard-remote-file-staging-fs.test.ts similarity index 100% rename from src/main/window/clipboard-remote-file-staging-fs.test.ts rename to src/main/window/clipboard/clipboard-remote-file-staging-fs.test.ts diff --git a/src/main/window/clipboard-remote-file-staging.test.ts b/src/main/window/clipboard/clipboard-remote-file-staging.test.ts similarity index 100% rename from src/main/window/clipboard-remote-file-staging.test.ts rename to src/main/window/clipboard/clipboard-remote-file-staging.test.ts diff --git a/src/main/window/clipboard-remote-file-staging.ts b/src/main/window/clipboard/clipboard-remote-file-staging.ts similarity index 97% rename from src/main/window/clipboard-remote-file-staging.ts rename to src/main/window/clipboard/clipboard-remote-file-staging.ts index d7043d22869..114f5f8272a 100644 --- a/src/main/window/clipboard-remote-file-staging.ts +++ b/src/main/window/clipboard/clipboard-remote-file-staging.ts @@ -5,10 +5,10 @@ import { getOwnedTempStagingRoot, isDirectChild, isMissingPathError, - isSafeOwnedDirectory, removeOwnedDirectory, sweepExpiredOwnedDirectories -} from './owned-temp-staging-root' +} from '../../filesystem/owned-temp-staging-root' +import { isSafeOwnedDirectory } from '../../../shared/owned-private-directory' const REMOTE_CLIPBOARD_STAGING_ROOT_NAME = 'orca-clipboard-files' const REMOTE_CLIPBOARD_LEGACY_PREFIX = 'orca-clipboard-file-' diff --git a/src/main/window/clipboard-runtime-image-upload.ts b/src/main/window/clipboard/clipboard-runtime-image-upload.ts similarity index 95% rename from src/main/window/clipboard-runtime-image-upload.ts rename to src/main/window/clipboard/clipboard-runtime-image-upload.ts index 6b1f293503f..0fd1e14136d 100644 --- a/src/main/window/clipboard-runtime-image-upload.ts +++ b/src/main/window/clipboard/clipboard-runtime-image-upload.ts @@ -1,5 +1,5 @@ -import { assertClipboardImageByteLengthWithinLimit } from '../../shared/clipboard-image' -import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' +import { assertClipboardImageByteLengthWithinLimit } from '../../../shared/clipboard-image' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/requests/runtime-environment-transport-routing' const CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = 512 * 1024 const CLIPBOARD_IMAGE_SINGLE_FRAME_FALLBACK_BASE64_CHARS = 256 * 1024 diff --git a/src/main/window/clipboard/clipboard-text-publisher.test.ts b/src/main/window/clipboard/clipboard-text-publisher.test.ts new file mode 100644 index 00000000000..64c7c3fabfe --- /dev/null +++ b/src/main/window/clipboard/clipboard-text-publisher.test.ts @@ -0,0 +1,136 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' +import { + assertClipboardTextWriteWithinLimitWithYield, + CLIPBOARD_TEXT_WRITE_MAX_BYTES +} from '../../../shared/clipboard-text' +import { CLIPBOARD_IMAGE_MAX_BASE64_CHARS } from '../../../shared/clipboard-image' +import { createClipboardPublisher } from './clipboard-text-publisher' + +vi.mock('electron', () => ({ app: {}, clipboard: {} })) + +const ok: ProcessResult = { code: 0, signal: null, stdout: '', stderr: '', timedOut: false } +const run = vi.fn(async (_spec: ProcessSpec): Promise => ok) +const write = vi.fn() +const clearCache = vi.fn() +function publisher(wayland = true, validate = assertClipboardTextWriteWithinLimitWithYield) { + return createClipboardPublisher({ + isWayland: () => wayland, + helperPath: () => '/bundle/bin/orca-wayland-clipboard', + run, + write, + clearCache, + validate + }) +} +function writer(wayland = true, validate = assertClipboardTextWriteWithinLimitWithYield) { + return publisher(wayland, validate).publishText +} + +describe('terminal clipboard writes', () => { + beforeEach(() => { + vi.resetAllMocks() + run.mockResolvedValue(ok) + }) + + it.each([ + ['timeout', { ...ok, code: null, timedOut: true }], + ['helper failure', { ...ok, code: 70 }] + ])('rejects %s without falling back to an unsafe Electron write', async (_label, result) => { + run.mockResolvedValueOnce(result) + await expect(writer()('copy')).rejects.toThrow('Wayland clipboard write failed') + expect(write).not.toHaveBeenCalled() + expect(clearCache).not.toHaveBeenCalled() + }) + + it('rejects oversized text before either clipboard backend is invoked', async () => { + await expect(writer()('x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1))).rejects.toThrow( + 'Clipboard text is too large' + ) + expect(run).not.toHaveBeenCalled() + expect(write).not.toHaveBeenCalled() + }) + + it.each([ + { label: 'count', count: 32, bytes: 1 }, + { label: 'retained bytes', count: 1, bytes: CLIPBOARD_IMAGE_MAX_BASE64_CHARS * 2 } + ])( + 'bounds other clipboard operations by $label and releases capacity after failure', + async ({ count, bytes }) => { + const copy = publisher(false) + let release: () => void = () => undefined + const gate = new Promise((resolve) => { + release = resolve + }) + const publications: number[] = [] + const first = copy.publish(bytes, async () => { + await gate + throw new Error('file helper failed') + }) + const rejected = expect(first).rejects.toThrow('file helper failed') + const queued = Array.from({ length: count - 1 }, (_, index) => + copy.publish(bytes, () => { + publications.push(index) + return index + }) + ) + await expect(copy.publish(bytes, () => publications.push(-1))).rejects.toThrow( + 'Too many pending clipboard writes' + ) + expect(publications).toEqual([]) + const text = copy.publishText('after failed file', 'ordinary') + release() + await rejected + await Promise.all(queued) + await text + expect(publications).toHaveLength(count - 1) + expect(publications).not.toContain(-1) + expect(write).toHaveBeenLastCalledWith('after failed file', 'ordinary') + await expect(copy.publish(bytes, () => 'after flood')).resolves.toBe('after flood') + } + ) + + it('bounds requests queued behind a stalled helper', async () => { + let release: (value: typeof ok) => void = () => undefined + run.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + const copy = writer() + const queued = Array.from({ length: 32 }, (_, index) => copy(String(index))) + await expect(copy('overflow')).rejects.toThrow('Too many pending clipboard writes') + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) + release(ok) + await Promise.all(queued) + await copy('after flood') + expect(run).toHaveBeenCalledTimes(33) + }) + + it('bounds the total text retained behind a stalled helper', async () => { + let release: (value: typeof ok) => void = () => undefined + run.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + const copy = writer(true, async (text) => text) + const text = 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES / 2 + 1) + const first = copy(text) + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) + let failure: unknown + void copy(text).catch((error: unknown) => { + failure = error + }) + await vi.waitFor( + () => expect(failure).toEqual(new Error('Too many pending clipboard writes')), + { timeout: 200 } + ) + release(ok) + await first + await copy(text) + expect(run).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/window/clipboard-text-publisher.ts b/src/main/window/clipboard/clipboard-text-publisher.ts similarity index 93% rename from src/main/window/clipboard-text-publisher.ts rename to src/main/window/clipboard/clipboard-text-publisher.ts index 022338b6fed..0a66ffb3098 100644 --- a/src/main/window/clipboard-text-publisher.ts +++ b/src/main/window/clipboard/clipboard-text-publisher.ts @@ -5,13 +5,13 @@ import { assertClipboardTextWriteWithinLimitWithYield, CLIPBOARD_TEXT_WRITE_MAX_BYTES, CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR -} from '../../shared/clipboard-text' -import { CLIPBOARD_IMAGE_MAX_BASE64_CHARS } from '../../shared/clipboard-image' -import { isLinuxWaylandSession } from '../../shared/linux-wayland-session' +} from '../../../shared/clipboard-text' +import { CLIPBOARD_IMAGE_MAX_BASE64_CHARS } from '../../../shared/clipboard-image' +import { isLinuxWaylandSession } from '../../../shared/linux-wayland-session' import { writeClipboardTextAndVerify } from './clipboard-text-write-verify' import { stageClipboardPublisher } from './clipboard-publisher-executable' -import { envWithoutAppImageRuntime } from '../pty/shell-startup/appimage-terminal-env' -import { isLegacyAppImageRuntimeIdentity } from '../updater/linux-package/linux-update-package-type' +import { envWithoutAppImageRuntime } from '../../pty/shell-startup/appimage-terminal-env' +import { isLegacyAppImageRuntimeIdentity } from '../../updater/linux-package/linux-update-package-type' const WAYLAND_CLIPBOARD_WRITE_FAILED_ERROR = 'Wayland clipboard write failed' const MAX_PENDING_CLIPBOARD_WRITES = 32 diff --git a/src/main/window/clipboard-text-write-verify.ts b/src/main/window/clipboard/clipboard-text-write-verify.ts similarity index 100% rename from src/main/window/clipboard-text-write-verify.ts rename to src/main/window/clipboard/clipboard-text-write-verify.ts diff --git a/src/main/window/clipboard-windows-image-file.test.ts b/src/main/window/clipboard/clipboard-windows-image-file.test.ts similarity index 97% rename from src/main/window/clipboard-windows-image-file.test.ts rename to src/main/window/clipboard/clipboard-windows-image-file.test.ts index c9657718077..d80d9f45d99 100644 --- a/src/main/window/clipboard-windows-image-file.test.ts +++ b/src/main/window/clipboard/clipboard-windows-image-file.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { CLIPBOARD_IMAGE_MAX_PIXELS } from '../../shared/clipboard-image' +import { CLIPBOARD_IMAGE_MAX_PIXELS } from '../../../shared/clipboard-image' import { readWindowsClipboardImageFileAsPng } from './clipboard-windows-image-file' function fileNameW(filePath: string): Buffer { diff --git a/src/main/window/clipboard-windows-image-file.ts b/src/main/window/clipboard/clipboard-windows-image-file.ts similarity index 99% rename from src/main/window/clipboard-windows-image-file.ts rename to src/main/window/clipboard/clipboard-windows-image-file.ts index 814f262fe33..c6f8483a91c 100644 --- a/src/main/window/clipboard-windows-image-file.ts +++ b/src/main/window/clipboard/clipboard-windows-image-file.ts @@ -4,7 +4,7 @@ import type { NativeImage } from 'electron' import { assertClipboardImageByteLengthWithinLimit, assertClipboardImageDimensionsWithinLimit -} from '../../shared/clipboard-image' +} from '../../../shared/clipboard-image' import { encodeClipboardNativeImagePng } from './clipboard-image-png-encode' type ClipboardImageFileHandle = Pick diff --git a/src/main/window/native-chat-pasted-text-file.test.ts b/src/main/window/clipboard/native-chat-pasted-text-file.test.ts similarity index 79% rename from src/main/window/native-chat-pasted-text-file.test.ts rename to src/main/window/clipboard/native-chat-pasted-text-file.test.ts index 3770e9f8259..e70c9dacaa8 100644 --- a/src/main/window/native-chat-pasted-text-file.test.ts +++ b/src/main/window/clipboard/native-chat-pasted-text-file.test.ts @@ -2,17 +2,17 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' const mocks = vi.hoisted(() => ({ upload: vi.fn() })) vi.mock('electron', () => ({ app: { getPath: () => '/user-data' } })) -vi.mock('../ipc/agent-session-attachment-upload', () => ({ +vi.mock('../../ipc/agent-session-attachment-upload', () => ({ uploadPasteToAgentSessionAttachments: mocks.upload })) import { savePastedTextAsFile } from './native-chat-pasted-text-file' -import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' +import { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' describe('a long paste saved as a file', () => { let root: string diff --git a/src/main/window/native-chat-pasted-text-file.ts b/src/main/window/clipboard/native-chat-pasted-text-file.ts similarity index 79% rename from src/main/window/native-chat-pasted-text-file.ts rename to src/main/window/clipboard/native-chat-pasted-text-file.ts index 406b88e1f78..81fa1571d0c 100644 --- a/src/main/window/native-chat-pasted-text-file.ts +++ b/src/main/window/clipboard/native-chat-pasted-text-file.ts @@ -4,10 +4,10 @@ import { app } from 'electron' import { agentSessionPastedTextName, type AgentSessionAttachmentClipboardTarget -} from '../../shared/agent-session/agent-session-attachments' -import { assertClipboardTextWithinLimit } from '../../shared/clipboard-text' -import { uploadPasteToAgentSessionAttachments } from '../ipc/agent-session-attachment-upload' -import type { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' +} from '../../../shared/agent-session/agent-session-attachments' +import { assertClipboardTextWithinLimit } from '../../../shared/clipboard-text' +import { uploadPasteToAgentSessionAttachments } from '../../ipc/agent-session-attachment-upload' +import type { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' export type SavePastedTextAsFileArgs = { text: string diff --git a/src/main/window/createMainWindow-close-confirmation.test.ts b/src/main/window/createMainWindow-close-confirmation.test.ts deleted file mode 100644 index ad620060a01..00000000000 --- a/src/main/window/createMainWindow-close-confirmation.test.ts +++ /dev/null @@ -1,365 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('./desktop-integration/app-icon', async () => - (await import('./createMainWindow-test-harness')).appIconMock() -) -vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) -vi.mock('../browser/routing/sessions/browser-route-session-runtime', async () => { - const harness = await import('./createMainWindow-test-harness') - return { - browserRouteSessionRegistry: { isAllowedPartition: harness.routePartitionAllowedMock }, - browserRouteWebContentsRegistry: { - attachGuest: harness.attachRouteGuestMock, - retireRenderer: harness.retireRouteRendererMock - } - } -}) -vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { - const harness = await import('./createMainWindow-test-harness') - return { - attachBrowserClientPageRenderer: harness.attachClientPageRendererMock, - retireBrowserClientPageRenderer: harness.retireClientPageRendererMock - } -}) - -import { createMainWindow, WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS } from './createMainWindow' -import { ipcMain } from 'electron' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' -import { - attachClientPageRendererMock, - browserWindowMock, - createRendererRecoveryWindowHarness, - resetMainWindowMocks, - retireClientPageRendererMock, - retireRouteRendererMock -} from './createMainWindow-test-harness' - -describe('createMainWindow', () => { - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - vi.useRealTimers() - }) - - it('sends the next close as a plain close once its renderer cancels the newest quit request', () => { - const ipcHandlers: Record void> = {} - vi.mocked(ipcMain.on).mockImplementation((channel, handler) => { - ipcHandlers[channel] = handler as (...args: any[]) => void - return ipcMain - }) - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - let isQuitting = true - createMainWindow(null, { - getIsQuitting: () => isQuitting, - onQuitAborted: () => { - isQuitting = false - } - }) - const cancel = (senderId: number): void => - ipcHandlers['window:close-cancelled']?.({ sender: { id: senderId } }) - const retryClose = (): unknown => { - windowHandlers.close({ preventDefault: vi.fn() } as never) - return browserWindowInstance.webContents.send.mock.lastCall - } - - expect(retryClose()).toEqual(['window:close-requested', { isQuitting: true, requestId: 1 }]) - // Why: a cancel sent before the renderer saw this quit belongs to an older prompt. - cancel(143) - ipcHandlers['window:close-request-received']?.({ sender: { id: 143 } }, 1) - cancel(99) - expect(retryClose()).toEqual(['window:close-requested', { isQuitting: true, requestId: 2 }]) - ipcHandlers['window:close-request-received']?.({ sender: { id: 143 } }, 2) - cancel(143) - expect(retryClose()).toEqual(['window:close-requested', { isQuitting: false, requestId: 3 }]) - }) - - it('allows close after the renderer process is gone', () => { - const windowHandlers: Record void> = {} - const webContents = { - id: 71, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isCrashed: vi.fn(() => false) - } - const browserWindowInstance = { - webContents, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null, { getIsQuitting: () => true }) - - windowHandlers['render-process-gone']?.( - {} as never, - { - reason: 'crashed', - exitCode: 5 - } as never - ) - expect(retireRouteRendererMock).toHaveBeenCalledWith(71) - const preventDefault = vi.fn() - windowHandlers.close({ preventDefault } as never) - - expect(preventDefault).not.toHaveBeenCalled() - expect(webContents.send).not.toHaveBeenCalledWith( - 'window:close-requested', - expect.objectContaining({ isQuitting: true }) - ) - - consoleError.mockRestore() - }) - - it('does not persist pending bounds after bypassing close for a gone renderer', () => { - vi.useFakeTimers() - - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isCrashed: vi.fn(() => false) - } - const browserWindowInstance = { - webContents, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => false), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - getBounds: vi.fn(() => ({ x: 10, y: 20, width: 1000, height: 700 })), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - const updateUI = vi.fn() - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow({ - getUI: () => ({}), - getSettings: () => ({ windowBackgroundBlur: false }), - updateUI - } as never) - - windowHandlers.resize() - windowHandlers['render-process-gone']?.( - {} as never, - { - reason: 'crashed', - exitCode: 5 - } as never - ) - const preventDefault = vi.fn() - windowHandlers.close({ preventDefault } as never) - vi.advanceTimersByTime(500) - - expect(preventDefault).not.toHaveBeenCalled() - expect(updateUI).not.toHaveBeenCalled() - - consoleError.mockRestore() - }) - - it('resumes close confirmation after a renderer process reloads', () => { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isCrashed: vi.fn(() => false) - } - const browserWindowInstance = { - webContents, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null, { getIsQuitting: () => true }) - - windowHandlers['render-process-gone']?.( - {} as never, - { - reason: 'crashed', - exitCode: 5 - } as never - ) - windowHandlers['did-finish-load']?.() - const preventDefault = vi.fn() - windowHandlers.close({ preventDefault } as never) - - expect(preventDefault).toHaveBeenCalledTimes(1) - expect(retireClientPageRendererMock).toHaveBeenCalledWith(webContents) - expect(attachClientPageRendererMock).toHaveBeenCalledWith(webContents) - expect(webContents.send).toHaveBeenCalledWith('window:close-requested', { - isQuitting: true, - requestId: expect.any(Number) - }) - - consoleError.mockRestore() - }) - - it('destroys an already-unresponsive renderer after an app-wide quit deadline', async () => { - vi.useFakeTimers() - const windowHandlers: Record void> = {} - const webContents = { - id: 42, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isCrashed: vi.fn(() => false) - } - const destroy = vi.fn() - browserWindowMock.mockImplementation(function () { - return { - webContents, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - destroy, - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - }) - createMainWindow(null, { getIsQuitting: () => true }) - - windowHandlers.close({ preventDefault: vi.fn() } as never) - await vi.advanceTimersByTimeAsync(WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS - 1) - expect(destroy).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - - expect(destroy).toHaveBeenCalledOnce() - }) - - it('keeps the renderer-owned close flow after the quit request is acknowledged', async () => { - vi.useFakeTimers() - const windowHandlers: Record void> = {} - const ipcHandlers: Record void> = {} - vi.mocked(ipcMain.on).mockImplementation((channel, handler) => { - ipcHandlers[channel] = handler as (...args: any[]) => void - return ipcMain - }) - const webContents = { - id: 42, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isCrashed: vi.fn(() => false) - } - const destroy = vi.fn() - browserWindowMock.mockImplementation(function () { - return { - webContents, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - destroy, - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - }) - createMainWindow(null, { getIsQuitting: () => true }) - - windowHandlers.close({ preventDefault: vi.fn() } as never) - windowHandlers.close({ preventDefault: vi.fn() } as never) - const closeRequests = vi - .mocked(webContents.send) - .mock.calls.filter(([channel]) => channel === 'window:close-requested') - .map(([, request]) => request as { requestId: number }) - expect(closeRequests).toHaveLength(2) - const [staleRequest, currentRequest] = closeRequests - ipcHandlers['window:close-request-received']?.({ sender: { id: 99 } }, currentRequest.requestId) - ipcHandlers['window:close-request-received']?.({ sender: { id: 42 } }, staleRequest.requestId) - await vi.advanceTimersByTimeAsync(WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS - 1) - expect(destroy).not.toHaveBeenCalled() - ipcHandlers['window:close-request-received']?.({ sender: { id: 42 } }, currentRequest.requestId) - await vi.advanceTimersByTimeAsync(1) - - expect(destroy).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts b/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts deleted file mode 100644 index 7ee68f4178a..00000000000 --- a/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('./desktop-integration/app-icon', async () => - (await import('./createMainWindow-test-harness')).appIconMock() -) -vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) -vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { - const harness = await import('./createMainWindow-test-harness') - return { - attachBrowserClientPageRenderer: harness.attachClientPageRendererMock, - retireBrowserClientPageRenderer: harness.retireClientPageRendererMock - } -}) - -import { createMainWindow } from './createMainWindow' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' -import { - resetPreGoneSystemMemorySamplingForTest, - samplePreGoneSystemMemory -} from '../crash-reporting/memory/pre-gone-host-memory' -import { setSystemMemoryInfoReaderForTest } from '../crash-reporting/memory/system-memory-details' -import { setSwapVolumeFreeSpaceReaderForTest } from '../crash-reporting/memory/swap-volume-free-space' -import { - createRendererRecoveryWindowHarness, - resetMainWindowMocks, - withPlatform -} from './createMainWindow-test-harness' - -// Launch 13084 (Scan-31 1790683596/1790684449/1790684587): the second reload OOMed 3.458 s after the first. -const OOM_AT = [ - '2026-09-29T12:06:19.869Z', - '2026-09-29T12:20:37.207Z', - '2026-09-29T12:20:40.665Z', - '2026-09-29T12:22:59.975Z' -].map((iso) => Date.parse(iso)) -// Commit at the two OOMs of launch 22912 (Scan-30 1790622432/1790622459): 744 MB, then 60 MB of a 130 GB limit. -const HEALTHY_FIRST_OOM_COMMIT_MB = 744 -const EXHAUSTED_COMMIT_MB = 60 -const RECOVERED_COMMIT_MB = 2_029 - -const OOM: Electron.RenderProcessGoneDetails = { reason: 'oom', exitCode: -536870904 } - -function hostWithAvailableCommit(swapFreeMB: number): void { - setSystemMemoryInfoReaderForTest(() => ({ - total: 32_000 * 1024, - free: 976 * 1024, - swapTotal: 130_000 * 1024, - swapFree: swapFreeMB * 1024 - })) - void samplePreGoneSystemMemory(Date.now()) -} - -async function runOomSequence( - platform: NodeJS.Platform, - commitAtEachOomMB: readonly (number | null)[], - goneTimeCommitMB?: number -): Promise<{ reloads: number; onRendererRecoveryExhausted: ReturnType }> { - const onRendererRecoveryExhausted = vi.fn() - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - createMainWindow(null, { onRendererRecoveryExhausted }) - for (const [index, goneAt] of OOM_AT.entries()) { - const commitMB = commitAtEachOomMB[index] - // null: no sampler tick since the previous OOM. - if (commitMB !== null) { - vi.setSystemTime(goneAt - 2_000) - withPlatform(platform, () => hostWithAvailableCommit(commitMB)) - } - vi.setSystemTime(goneAt) - if (goneTimeCommitMB !== undefined) { - // Only the host changes; no sampler tick commits it. - setSystemMemoryInfoReaderForTest(() => ({ swapFree: goneTimeCommitMB * 1024 })) - } - withPlatform(platform, () => windowHandlers['render-process-gone']?.({}, OOM)) - await vi.advanceTimersByTimeAsync(250) - } - return { - reloads: browserWindowInstance.loadFile.mock.calls.length - 1, - onRendererRecoveryExhausted - } -} - -describe('Windows renderer OOM recovery under exhausted commit', () => { - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - resetPreGoneSystemMemorySamplingForTest() - setSwapVolumeFreeSpaceReaderForTest(async () => undefined) - vi.useFakeTimers() - vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - afterEach(() => { - setSystemMemoryInfoReaderForTest(null) - setSwapVolumeFreeSpaceReaderForTest(null) - resetPreGoneSystemMemorySamplingForTest() - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('stops reloading into a repeat OOM and tells the user how much commit is left', async () => { - const { reloads, onRendererRecoveryExhausted } = await runOomSequence('win32', [ - HEALTHY_FIRST_OOM_COMMIT_MB, - EXHAUSTED_COMMIT_MB, - EXHAUSTED_COMMIT_MB, - EXHAUSTED_COMMIT_MB - ]) - expect(reloads).toBe(2) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - expect(onRendererRecoveryExhausted).toHaveBeenCalledWith( - expect.objectContaining({ - details: OOM, - cause: 'low-commit', - lowCommit: { - availableCommitMB: EXHAUSTED_COMMIT_MB, - sincePreviousOomMs: 3_458, - commitReading: 'pre-gone' - } - }) - ) - }) - - // Reproduce the 3.458s OOM gap with no intervening 10s sampler tick. - it('reads commit at gone time when no sampler tick landed since the previous OOM', async () => { - const { reloads, onRendererRecoveryExhausted } = await runOomSequence('win32', [ - HEALTHY_FIRST_OOM_COMMIT_MB, - EXHAUSTED_COMMIT_MB, - null, - EXHAUSTED_COMMIT_MB - ]) - expect(reloads).toBe(2) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - expect(onRendererRecoveryExhausted).toHaveBeenCalledWith( - expect.objectContaining({ - cause: 'low-commit', - lowCommit: { - availableCommitMB: EXHAUSTED_COMMIT_MB, - sincePreviousOomMs: 3_458, - commitReading: 'gone-time' - } - }) - ) - }) - - it('keeps reloading when the gone-time read shows commit recovered and no tick landed', async () => { - const { reloads, onRendererRecoveryExhausted } = await runOomSequence( - 'win32', - [HEALTHY_FIRST_OOM_COMMIT_MB, EXHAUSTED_COMMIT_MB, null, null], - RECOVERED_COMMIT_MB - ) - expect(reloads).toBe(4) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - }) - - it('keeps auto-reloading repeat OOMs once commit has recovered', async () => { - const { reloads, onRendererRecoveryExhausted } = await runOomSequence('win32', [ - HEALTHY_FIRST_OOM_COMMIT_MB, - RECOVERED_COMMIT_MB, - RECOVERED_COMMIT_MB, - RECOVERED_COMMIT_MB - ]) - expect(reloads).toBe(4) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - }) - - it.each(['darwin', 'linux'] as const)('is a no-op on %s', async (platform) => { - const { reloads, onRendererRecoveryExhausted } = await runOomSequence(platform, [ - EXHAUSTED_COMMIT_MB, - EXHAUSTED_COMMIT_MB, - EXHAUSTED_COMMIT_MB, - EXHAUSTED_COMMIT_MB - ]) - expect(reloads).toBe(4) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/window/createMainWindow-markdown-editor-focus.test.ts b/src/main/window/createMainWindow-markdown-editor-focus.test.ts deleted file mode 100644 index a49f4e214b9..00000000000 --- a/src/main/window/createMainWindow-markdown-editor-focus.test.ts +++ /dev/null @@ -1,385 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('./desktop-integration/app-icon', async () => - (await import('./createMainWindow-test-harness')).appIconMock() -) -vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) - -import { createMainWindow } from './createMainWindow' -import { ipcMain } from 'electron' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' -import { - browserWindowMock, - buildFromTemplateMock, - menuPopupMock, - resetMainWindowMocks -} from './createMainWindow-test-harness' - -function openMainWindowForContextMenu() { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn(), - replaceMisspelling: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() }, - getURL: vi.fn(() => 'file:///opt/orca/renderer/index.html'), - isLoadingMainFrame: vi.fn(() => true) - } - const browserWindowInstance = { - webContents, - on: vi.fn(), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - return { webContents, windowHandlers, browserWindowInstance } -} - -describe('createMainWindow', () => { - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - vi.useRealTimers() - }) - - it('intercepts Cmd+B for sidebar when the markdown editor is not focused', () => { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn() - } - const browserWindowInstance = { - webContents, - on: vi.fn(), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - - const preventDefault = vi.fn() - const isDarwin = process.platform === 'darwin' - windowHandlers['before-input-event']( - { preventDefault } as never, - { - type: 'keyDown', - code: 'KeyB', - key: 'b', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - } as never - ) - - expect(preventDefault).toHaveBeenCalledTimes(1) - expect(webContents.send).toHaveBeenCalledWith('ui:toggleLeftSidebar') - }) - - it('leaves bold and logical link shortcuts to the focused markdown editor', () => { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn() - } - const browserWindowInstance = { - webContents, - on: vi.fn(), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - - const setFocusedListener = vi - .mocked(ipcMain.on) - .mock.calls.find(([channel]) => channel === 'ui:setMarkdownEditorFocused')?.[1] - expect(setFocusedListener).toBeTypeOf('function') - setFocusedListener?.({ sender: webContents } as never, true) - - const event = new Event('before-input-event', { cancelable: true }) - const isDarwin = process.platform === 'darwin' - windowHandlers['before-input-event'](event, { - type: 'keyDown', - code: 'KeyB', - key: 'b', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - } as never) - - windowHandlers['before-input-event'](event, { - type: 'keyDown', - code: 'KeyV', - key: 'k', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - }) - expect(event.defaultPrevented).toBe(false) - }) - - it('lets the shortcut recorder capture app shortcuts before main interception', () => { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn() - } - const browserWindowInstance = { - webContents, - on: vi.fn(), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - - const setFocusedListener = vi - .mocked(ipcMain.on) - .mock.calls.find(([channel]) => channel === 'ui:setShortcutRecorderFocused')?.[1] - expect(setFocusedListener).toBeTypeOf('function') - setFocusedListener?.({ sender: webContents } as never, true) - - const preventDefault = vi.fn() - const isDarwin = process.platform === 'darwin' - windowHandlers['before-input-event']( - { preventDefault } as never, - { - type: 'keyDown', - code: 'KeyB', - key: 'b', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - } as never - ) - - expect(preventDefault).not.toHaveBeenCalled() - expect(webContents.send).not.toHaveBeenCalledWith('ui:toggleLeftSidebar') - }) - - it('skips Cmd+B interception when floating terminal input is focused', () => { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn() - } - const browserWindowInstance = { - webContents, - on: vi.fn(), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - - const setFocusedListener = vi - .mocked(ipcMain.on) - .mock.calls.find(([channel]) => channel === 'ui:setFloatingFocus')?.[1] - expect(setFocusedListener).toBeTypeOf('function') - setFocusedListener?.( - { sender: webContents } as never, - { panelFocused: true, terminalFocused: true } as never - ) - - const preventDefault = vi.fn() - const isDarwin = process.platform === 'darwin' - windowHandlers['before-input-event']( - { preventDefault } as never, - { - type: 'keyDown', - code: 'KeyB', - key: 'b', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - } as never - ) - - expect(preventDefault).not.toHaveBeenCalled() - expect(webContents.send).not.toHaveBeenCalledWith('ui:toggleLeftSidebar') - - webContents.send.mockClear() - const newWorkspacePreventDefault = vi.fn() - windowHandlers['before-input-event']( - { preventDefault: newWorkspacePreventDefault } as never, - { - type: 'keyDown', - code: 'KeyN', - key: 'n', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - } as never - ) - - expect(newWorkspacePreventDefault).toHaveBeenCalledTimes(1) - expect(webContents.send).toHaveBeenCalledWith('ui:openNewWorkspace') - }) - - it('retires the edit menu with its document but not on same-document navigation', () => { - const { webContents } = openMainWindowForContextMenu() - const emit = (event: string, ...args: unknown[]): void => { - for (const [name, handler] of webContents.on.mock.calls) { - if (name === event) { - handler(...args) - } - } - } - const openMenu = () => { - const closePopup = vi.fn() - buildFromTemplateMock.mockImplementationOnce(() => ({ - popup: menuPopupMock, - closePopup - })) - emit( - 'context-menu', - {}, - { - x: 1, - y: 2, - isEditable: true, - formControlType: 'input', - dictionarySuggestions: [], - misspelledWord: '' - } - ) - const template = buildFromTemplateMock.mock.calls.at(-1)?.[0] - const paste = Array.isArray(template) - ? template.find((item) => item.label === 'Paste') - : undefined - expect(paste?.click).toBeTypeOf('function') - return { closePopup, paste } - } - const nextDocument = 'file:///opt/orca/renderer/index.html?reload' - - const first = openMenu() - emit('did-start-navigation', {}, `${nextDocument}#hash`, true, true) - expect(first.closePopup).not.toHaveBeenCalled() - emit('did-start-navigation', {}, nextDocument, false, true) - expect(first.closePopup).toHaveBeenCalledTimes(1) - - // The old document still takes right-clicks until the pending reload commits. - const pending = openMenu() - emit('did-frame-navigate', {}, nextDocument, 200, 'OK', false) - expect(pending.closePopup).not.toHaveBeenCalled() - emit('did-frame-navigate', {}, nextDocument, 200, 'OK', true) - expect(pending.closePopup).toHaveBeenCalledTimes(1) - pending.paste.click() - expect(webContents.send).not.toHaveBeenCalledWith('ui:editableContextPaste', expect.anything()) - }) -}) diff --git a/src/main/window/createMainWindow-renderer-crash-recovery.test.ts b/src/main/window/createMainWindow-renderer-crash-recovery.test.ts deleted file mode 100644 index abf52e7510f..00000000000 --- a/src/main/window/createMainWindow-renderer-crash-recovery.test.ts +++ /dev/null @@ -1,383 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('./desktop-integration/app-icon', async () => - (await import('./createMainWindow-test-harness')).appIconMock() -) -vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) -vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { - const harness = await import('./createMainWindow-test-harness') - return { - attachBrowserClientPageRenderer: harness.attachClientPageRendererMock, - retireBrowserClientPageRenderer: harness.retireClientPageRendererMock - } -}) - -import { createMainWindow } from './createMainWindow' -import { ipcMain } from 'electron' -import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-exits/process-gone-classification' -import { - resetExpectedTeardownStateForTest, - resolveExpectedTeardownScope -} from '../crash-reporting/process-exits/expected-teardown-state' -import { - attachClientPageRendererMock, - browserWindowMock, - createRendererRecoveryWindowHarness, - resetMainWindowMocks, - retireClientPageRendererMock, - withPlatform -} from './createMainWindow-test-harness' - -describe('createMainWindow', () => { - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - vi.useRealTimers() - }) - - it('does not read destroyed webContents during closed cleanup', () => { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn(), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn() - } - let webContentsDestroyed = false - const browserWindowInstance = { - get webContents() { - if (webContentsDestroyed) { - throw new Error('Object has been destroyed') - } - return webContents - }, - on: vi.fn((event, handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - - webContentsDestroyed = true - - // Updater teardown may destroy WebContents before closed cleanup; throwing would prevent Squirrel relaunch. - expect(() => windowHandlers.closed?.()).not.toThrow() - }) - - it('retires renderer generations and resets focus on crash, navigation, and destroy', async () => { - const windowHandlers: Record void> = {} - const webContents = { - getURL: vi.fn(() => 'file:///opt/orca/renderer/index.html'), - isDestroyed: vi.fn(() => false), - isLoadingMainFrame: vi.fn(() => false), - mainFrame: {}, - on: vi.fn((event, handler) => { - // Retain multiple lifecycle listeners like EventEmitter. - const previous = windowHandlers[event] - windowHandlers[event] = previous - ? (...args: unknown[]) => { - previous(...args) - handler(...args) - } - : handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDevToolsOpened: vi.fn(), - openDevTools: vi.fn(), - closeDevTools: vi.fn() - } - const browserWindowInstance = { - webContents, - on: vi.fn(), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - createMainWindow(null) - windowHandlers['did-finish-load']?.() - expect(attachClientPageRendererMock).toHaveBeenCalledWith(webContents) - - const setFocusedListener = vi - .mocked(ipcMain.on) - .mock.calls.find(([channel]) => channel === 'ui:setMarkdownEditorFocused')?.[1] - const isDarwin = process.platform === 'darwin' - - const cmdBInput = { - type: 'keyDown', - code: 'KeyB', - key: 'b', - meta: isDarwin, - control: !isDarwin, - alt: false, - shift: false - } as never - - const assertInterceptsAfterReset = (): void => { - webContents.send.mockClear() - const preventDefault = vi.fn() - windowHandlers['before-input-event']({ preventDefault } as never, cmdBInput) - expect(preventDefault).toHaveBeenCalledTimes(1) - expect(webContents.send).toHaveBeenCalledWith('ui:toggleLeftSidebar') - } - - retireClientPageRendererMock.mockClear() - setFocusedListener?.({ sender: webContents } as never, true) - windowHandlers['render-process-gone']?.() - expect(retireClientPageRendererMock).toHaveBeenCalledWith(webContents) - assertInterceptsAfterReset() - windowHandlers['did-finish-load']?.() - - retireClientPageRendererMock.mockClear() - setFocusedListener?.({ sender: webContents } as never, true) - windowHandlers['did-start-navigation']?.({} as never, 'https://example.com/', false, true) - expect(retireClientPageRendererMock).not.toHaveBeenCalled() - - windowHandlers['did-start-navigation']?.( - {} as never, - 'file:///opt/orca/renderer/index.html?reload=1', - false, - true - ) - expect(retireClientPageRendererMock).toHaveBeenCalledWith(webContents) - assertInterceptsAfterReset() - - attachClientPageRendererMock.mockClear() - windowHandlers['did-fail-provisional-load']?.( - {} as never, - -3, - 'aborted', - 'file:///opt/orca/renderer/index.html?reload=1', - true - ) - await Promise.resolve() - expect(attachClientPageRendererMock).toHaveBeenCalledWith(webContents) - - retireClientPageRendererMock.mockClear() - setFocusedListener?.({ sender: webContents } as never, true) - windowHandlers['did-start-navigation']?.({} as never, '#same-document', true, true) - expect(retireClientPageRendererMock).not.toHaveBeenCalled() - windowHandlers['did-start-navigation']?.({} as never, 'https://example.com/', false, false) - expect(retireClientPageRendererMock).not.toHaveBeenCalled() - webContents.send.mockClear() - const subframePreventDefault = vi.fn() - windowHandlers['before-input-event']( - { preventDefault: subframePreventDefault } as never, - cmdBInput - ) - expect(subframePreventDefault).not.toHaveBeenCalled() - expect(webContents.send).not.toHaveBeenCalledWith('ui:toggleLeftSidebar') - - retireClientPageRendererMock.mockClear() - setFocusedListener?.({ sender: webContents } as never, true) - windowHandlers['destroyed']?.() - expect(retireClientPageRendererMock).toHaveBeenCalledWith(webContents) - assertInterceptsAfterReset() - }) - - it('still preserves PTYs and reloads after Windows session-end', () => { - vi.useFakeTimers() - - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - const onBeforeRecoveryReload = vi.fn() - const onRendererRecoveryExhausted = vi.fn() - - withPlatform('win32', () => { - createMainWindow(null, { - onBeforeRecoveryReload, - onRendererRecoveryExhausted, - shouldRecoverRenderer: (details) => - shouldRecoverRendererAfterProcessGone({ - reason: details.reason, - expectedTeardown: resolveExpectedTeardownScope({ - isQuitting: false, - isQuittingForUpdate: false, - isExpectedRendererReload: false, - includeSystemSessionEnd: false - }) - }) - }) - }) - windowHandlers['session-end']?.({} as never) - windowHandlers['render-process-gone']?.( - {} as never, - { reason: 'killed', exitCode: 1 } as Electron.RenderProcessGoneDetails - ) - vi.advanceTimersByTime(250) - - expect(onBeforeRecoveryReload).toHaveBeenCalledWith(143, 'automatic') - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(2) - // Deliberate logoff reloads must never raise recovery dialogs during teardown. - vi.runAllTimers() - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - consoleError.mockRestore() - }) - - it('rechecks the renderer recovery predicate before reloading', () => { - vi.useFakeTimers() - - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - let shouldRecover = true - - createMainWindow(null, { shouldRecoverRenderer: () => shouldRecover }) - - windowHandlers['render-process-gone']?.( - {} as never, - { - reason: 'crashed', - exitCode: 5 - } as Electron.RenderProcessGoneDetails - ) - shouldRecover = false - vi.advanceTimersByTime(250) - - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(1) - expect(browserWindowInstance.loadURL).not.toHaveBeenCalled() - - consoleError.mockRestore() - }) - - it('coalesces repeated renderer losses into one recovery reload', () => { - vi.useFakeTimers() - - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - - createMainWindow(null) - - const details = { - reason: 'crashed', - exitCode: 5 - } as Electron.RenderProcessGoneDetails - windowHandlers['render-process-gone']?.({} as never, details) - windowHandlers['render-process-gone']?.({} as never, details) - vi.advanceTimersByTime(250) - - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(2) - expect(browserWindowInstance.loadURL).not.toHaveBeenCalled() - - consoleError.mockRestore() - }) - - it('does not reload after a clean renderer exit', () => { - vi.useFakeTimers() - - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - - createMainWindow(null) - - windowHandlers['render-process-gone']?.( - {} as never, - { - reason: 'clean-exit', - exitCode: 0 - } as Electron.RenderProcessGoneDetails - ) - vi.advanceTimersByTime(250) - - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(1) - expect(browserWindowInstance.loadURL).not.toHaveBeenCalled() - - consoleError.mockRestore() - }) - - it('cancels renderer recovery when the crashed window is closing', () => { - vi.useFakeTimers() - - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - - createMainWindow(null) - - windowHandlers['render-process-gone']?.( - {} as never, - { - reason: 'crashed', - exitCode: 5 - } as Electron.RenderProcessGoneDetails - ) - windowHandlers.close({ preventDefault: vi.fn() } as never) - vi.advanceTimersByTime(250) - - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(1) - expect(browserWindowInstance.loadURL).not.toHaveBeenCalled() - - consoleError.mockRestore() - }) - - it('serves a manual retry while the breaker stays open for the next crash', () => { - vi.useFakeTimers() - - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const onRendererRecoveryExhausted = vi.fn() - const { browserWindowInstance, windowHandlers } = createRendererRecoveryWindowHarness() - - createMainWindow(null, { onRendererRecoveryExhausted }) - - const details = { reason: 'crashed', exitCode: 5 } as Electron.RenderProcessGoneDetails - const driveCrashCycle = (): void => { - windowHandlers['render-process-gone']?.({} as never, details) - vi.advanceTimersByTime(250) - } - driveCrashCycle() - driveCrashCycle() - driveCrashCycle() - driveCrashCycle() - expect(onRendererRecoveryExhausted).toHaveBeenCalledTimes(1) - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(4) - - // Manual watched retry bypasses the automatic-recovery breaker. - onRendererRecoveryExhausted.mock.calls[0]?.[0].retry() - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(5) - - // Manual retry must not reset the poisoned machine's automatic-reload breaker. - driveCrashCycle() - expect(browserWindowInstance.loadFile).toHaveBeenCalledTimes(5) - expect(onRendererRecoveryExhausted).toHaveBeenCalledTimes(2) - - consoleError.mockRestore() - }) -}) diff --git a/src/main/window/createMainWindow-test-harness.ts b/src/main/window/createMainWindow-test-harness.ts deleted file mode 100644 index f99b477f67c..00000000000 --- a/src/main/window/createMainWindow-test-harness.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { vi } from 'vitest' -import type { Mock } from 'vitest' - -/** Loose spy signature: these stand in for electron APIs the suites only assert calls on. */ -export type MainWindowSpy = Mock<(...args: unknown[]) => unknown> - -export const menuPopupMock: MainWindowSpy = vi.fn() -export const notificationShowMock: MainWindowSpy = vi.fn() -/** Constructor spy: suites read the options object back off `mock.calls`. */ -export const browserWindowMock: Mock< - (options: Electron.BrowserWindowConstructorOptions) => unknown -> = vi.fn() -export const openExternalMock: MainWindowSpy = vi.fn() -export const attachGuestPoliciesMock: MainWindowSpy = vi.fn() -export const attachRouteGuestMock: MainWindowSpy = vi.fn(() => false) -export const retireRouteRendererMock: MainWindowSpy = vi.fn() -export const attachClientPageRendererMock: MainWindowSpy = vi.fn() -export const retireClientPageRendererMock: MainWindowSpy = vi.fn() -export const buildFromTemplateMock: Mock< - (...args: unknown[]) => { popup: MainWindowSpy; closePopup: MainWindowSpy } -> = vi.fn(() => ({ popup: menuPopupMock, closePopup: vi.fn() })) -export const notificationMock: Mock<(...args: unknown[]) => { show: MainWindowSpy }> = vi.fn( - function () { - return { show: notificationShowMock } - } -) -export const powerMonitorOnMock: MainWindowSpy = vi.fn() -export const powerMonitorRemoveListenerMock: MainWindowSpy = vi.fn() -export const routePartitionAllowedMock: Mock<(partition: string) => boolean> = vi.fn(() => false) -export const appMock: { isPackaged: boolean; on: MainWindowSpy; removeListener: MainWindowSpy } = { - isPackaged: true, - on: vi.fn(), - removeListener: vi.fn() -} -export const macosTahoeMock = { value: false } - -type IpcMainMock = { - on: MainWindowSpy - removeListener: MainWindowSpy - handle: MainWindowSpy - removeHandler: MainWindowSpy -} - -const ipcMainMock: IpcMainMock = { - on: vi.fn(), - removeListener: vi.fn(), - handle: vi.fn(), - removeHandler: vi.fn() -} - -export type ElectronModuleMock = { - app: typeof appMock - BrowserWindow: typeof browserWindowMock - ipcMain: IpcMainMock - Menu: { buildFromTemplate: typeof buildFromTemplateMock } - Notification: typeof notificationMock - nativeTheme: { shouldUseDarkColors: boolean } - powerMonitor: { on: MainWindowSpy; removeListener: MainWindowSpy } - screen: { - getPrimaryDisplay: () => { workAreaSize: { width: number; height: number } } - getDisplayMatching: () => { scaleFactor: number } - } - shell: { openExternal: MainWindowSpy } -} - -export type BrowserManagerModuleMock = { - browserManager: { - attachGuestPolicies: MainWindowSpy - setDictationShortcutForwardingPredicate: MainWindowSpy - } -} - -// vi.mock factories are hoisted per suite; builders reuse the Electron surface without duplicating it. -export function electronModuleMock(): ElectronModuleMock { - return { - app: appMock, - BrowserWindow: browserWindowMock, - ipcMain: ipcMainMock, - Menu: { buildFromTemplate: buildFromTemplateMock }, - Notification: notificationMock, - nativeTheme: { shouldUseDarkColors: false }, - powerMonitor: { on: powerMonitorOnMock, removeListener: powerMonitorRemoveListenerMock }, - screen: { - getPrimaryDisplay: () => ({ workAreaSize: { width: 1440, height: 900 } }), - getDisplayMatching: () => ({ scaleFactor: 2 }) - }, - shell: { openExternal: openExternalMock } - } -} - -export function macosTahoeReleaseMock() { - return { - isMacosTahoeOrNewer: vi.fn(() => macosTahoeMock.value) - } -} - -export function appIconMock() { - return { - getAppIconPath: vi.fn(() => 'icon') - } -} - -export function browserManagerMock(): BrowserManagerModuleMock { - return { - browserManager: { - attachGuestPolicies: attachGuestPoliciesMock, - setDictationShortcutForwardingPredicate: vi.fn() - } - } -} - -export function resetMainWindowMocks(): void { - browserWindowMock.mockReset() - openExternalMock.mockReset() - attachGuestPoliciesMock.mockReset() - attachRouteGuestMock.mockReset() - attachRouteGuestMock.mockReturnValue(false) - retireRouteRendererMock.mockReset() - attachClientPageRendererMock.mockReset() - retireClientPageRendererMock.mockReset() - buildFromTemplateMock.mockClear() - menuPopupMock.mockClear() - notificationMock.mockClear() - notificationShowMock.mockClear() - powerMonitorOnMock.mockReset() - powerMonitorRemoveListenerMock.mockReset() - routePartitionAllowedMock.mockReset() - routePartitionAllowedMock.mockReturnValue(false) - appMock.isPackaged = true - macosTahoeMock.value = false - ipcMainMock.on.mockReset() - ipcMainMock.removeListener.mockReset() - ipcMainMock.handle.mockReset() - ipcMainMock.removeHandler.mockReset() -} - -export function withPlatform(platform: NodeJS.Platform, run: () => T): T { - const original = process.platform - Object.defineProperty(process, 'platform', { configurable: true, value: platform }) - try { - return run() - } finally { - Object.defineProperty(process, 'platform', { configurable: true, value: original }) - } -} - -export type RendererRecoveryWindowHarness = { - browserWindowInstance: { - loadFile: Mock<() => Promise> - loadURL: Mock<() => Promise> - webContents: { send: Mock } - } - windowHandlers: Record void> -} - -/** A main window whose webContents events land in `windowHandlers` for suites that drive renderer recovery. */ -export function createRendererRecoveryWindowHarness(): RendererRecoveryWindowHarness { - const windowHandlers: RendererRecoveryWindowHarness['windowHandlers'] = {} - const webContents = { - id: 143, - getURL: vi.fn(() => 'file:///opt/orca/renderer/index.html'), - isDestroyed: vi.fn(() => false), - on: vi.fn((event: string, handler: (...args: unknown[]) => void) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn() - } - const browserWindowInstance = { - webContents, - on: vi.fn((event: string, handler: (...args: unknown[]) => void) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return browserWindowInstance - }) - - return { browserWindowInstance, windowHandlers } -} diff --git a/src/main/window/createMainWindow-user-quit-close.test.ts b/src/main/window/createMainWindow-user-quit-close.test.ts deleted file mode 100644 index 8726de70d0c..00000000000 --- a/src/main/window/createMainWindow-user-quit-close.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('./desktop-integration/app-icon', async () => - (await import('./createMainWindow-test-harness')).appIconMock() -) -vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) - -import { ipcMain } from 'electron' -import { createMainWindow, WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS } from './createMainWindow' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' -import { browserWindowMock, resetMainWindowMocks } from './createMainWindow-test-harness' -import { markUserQuitWindowClose } from './user-quit-window-close' - -type Handler = (...args: any[]) => void - -function setupWindow() { - const windowHandlers: Record = {} - const ipcHandlers: Record = {} - vi.mocked(ipcMain.on).mockImplementation((channel, handler) => { - ipcHandlers[channel] = handler - return ipcMain - }) - const webContents = { - id: 42, - on: vi.fn((event: string, handler: Handler) => { - windowHandlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isCrashed: vi.fn(() => false) - } - const instance = { - webContents, - on: vi.fn((event: string, handler: Handler) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => false), - isFullScreen: vi.fn(() => false), - isMinimized: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - hide: vi.fn(), - destroy: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return instance - }) - return { windowHandlers, ipcHandlers, webContents, instance } -} - -function lastCloseRequestId(send: ReturnType): number { - const requests = send.mock.calls.filter(([channel]) => channel === 'window:close-requested') - const request: unknown = requests.at(-1)?.[1] - return typeof request === 'object' && request !== null && 'requestId' in request - ? Number(request.requestId) - : -1 -} - -describe('serve user-Quit window close', () => { - const originalPlatform = process.platform - - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - vi.useFakeTimers() - }) - - afterEach(() => { - Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) - vi.useRealTimers() - }) - - it('destroys a frozen renderer after the quit ack deadline without quitting the process', async () => { - const { windowHandlers, webContents, instance } = setupWindow() - createMainWindow(null, { getIsQuitting: () => false }) - - markUserQuitWindowClose(instance) - windowHandlers.close({ preventDefault: vi.fn() }) - - expect(webContents.send).toHaveBeenCalledWith('window:close-requested', { - isQuitting: false, - requestId: expect.any(Number) - }) - await vi.advanceTimersByTimeAsync(WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS) - expect(instance.destroy).toHaveBeenCalledOnce() - }) - - it('leaves a responsive renderer free to veto the close', async () => { - const { windowHandlers, ipcHandlers, webContents, instance } = setupWindow() - createMainWindow(null, { getIsQuitting: () => false }) - - markUserQuitWindowClose(instance) - windowHandlers.close({ preventDefault: vi.fn() }) - ipcHandlers['window:close-request-received']?.( - { sender: { id: 42 } }, - lastCloseRequestId(webContents.send) - ) - await vi.advanceTimersByTimeAsync(WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS) - - expect(instance.destroy).not.toHaveBeenCalled() - }) - - it('keeps a plain window close without a deadline', async () => { - const { windowHandlers, instance } = setupWindow() - createMainWindow(null, { getIsQuitting: () => false }) - - markUserQuitWindowClose(instance) - windowHandlers.close({ preventDefault: vi.fn() }) - windowHandlers['will-prevent-unload']?.() - windowHandlers.close({ preventDefault: vi.fn() }) - // The first attempt's deadline is cleared by the veto; the second is a plain close. - await vi.advanceTimersByTimeAsync(WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS * 2) - - expect(instance.destroy).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index b3bbef5bd24..d7a1ef426ac 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -1,13 +1,15 @@ import { app, BrowserWindow, nativeTheme, powerMonitor, screen } from 'electron' import { release } from 'node:os' import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { installRendererHangStackPolicy } from '../hang-watchdog/renderer-hang-stack-policy' import { getAppIconPath } from './desktop-integration/app-icon' import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { getBrowserClientHostId } from '../browser/client-hosts/lifecycle/browser-client-host-id' import { formatBrowserClientHostIdArgument } from '../../shared/browser/client-hosting/browser-client-host-id-argument' import { formatWindowMaterialArgument, resolveWindowMaterial } from '../../shared/window-material' -import { windowMaterialOptions } from './window-material-options' -import { rememberWindowMaterial } from './window-material-suppression' +import { windowMaterialOptions } from './presentation/window-material-options' +import { rememberWindowMaterial } from './presentation/window-material-suppression' import { markSystemSessionEnding } from '../crash-reporting/process-exits/expected-teardown-state' import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { clearTrustedUIRendererWebContentsId, setTrustedUIRendererWebContentsId } from '../ipc/ui' @@ -15,17 +17,17 @@ import { flushUnsavedCloudSessions } from '../orca-profiles/cloud-session/profil import type { Store } from '../persistence/loading-store/store' import { closeDashboardPopout } from './dashboard-popout-window' import { closeWorkspaceSpaceWindow } from './workspace-space-window' -import { - installMainWindowCloseLifecycle, - WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS -} from './main-window-close-lifecycle' -import type { CreateMainWindowOptions, MainWindowLoadObserver } from './main-window-contracts' -import { mainWindowLoadErrorCode } from './main-window-load-error-code' -import { installMainWindowFocusLifecycle } from './main-window-focus-lifecycle' -import { installMainWindowShortcutRouting } from './main-window-shortcut-routing' -import { installMainWindowStateLifecycle } from './main-window-state-lifecycle' -import { installMainWindowActivityRelay } from './main-window-activity' -import { stopHiddenWindowFramePumpOnShow } from './hidden-window-frame-pump' +import { installMainWindowCloseLifecycle } from './main-window/main-window-close-lifecycle' +import type { + CreateMainWindowOptions, + MainWindowLoadObserver +} from './main-window/main-window-contracts' +import { mainWindowLoadErrorCode } from './renderer-recovery/main-window-load-error-code' +import { installMainWindowFocusLifecycle } from './main-window/main-window-focus-lifecycle' +import { installMainWindowShortcutRouting } from './main-window/main-window-shortcut-routing' +import { installMainWindowStateLifecycle } from './main-window/main-window-state-lifecycle' +import { installMainWindowActivityRelay } from './main-window/main-window-activity' +import { stopHiddenWindowFramePumpOnShow } from './visibility/hidden-window-frame-pump' import { wslHostsWindowArguments } from '../wsl/host-lifecycle/wsl-host-gate' import { formatHiddenWindowFramePumpArgument, @@ -39,15 +41,19 @@ import { TITLEBAR_CSS_CENTER, TRAFFIC_LIGHT_RADIUS, TRAFFIC_LIGHT_X -} from './main-window-visual-lifecycle' -import { installMainWindowWebviewSecurity } from './main-window-webview-security' -import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation' +} from './main-window/main-window-visual-lifecycle' +import { installMainWindowWebviewSecurity } from './security/main-window-webview-security' +import { rectHasVisibleAreaOnAnyDisplay } from './presentation/window-bounds-validation' import { installWindowsPathRegistryChangeListener } from '../pty/environment/windows-path-registry-change' import { recordAgentSessionRuntimeEnd } from '../runtime/agent-session/records/agent-session-runtime-end-record' -export { WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS } - export function loadMainWindow(mainWindow: BrowserWindow, observer?: MainWindowLoadObserver): void { + installRendererHangStackPolicy( + mainWindow.webContents, + !app.isPackaged && process.env.ELECTRON_RENDERER_URL + ? process.env.ELECTRON_RENDERER_URL + : pathToFileURL(join(__dirname, '../renderer/index.html')).href + ) const load = !app.isPackaged && process.env.ELECTRON_RENDERER_URL ? mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL) diff --git a/src/main/window/dashboard-popout-window.ts b/src/main/window/dashboard-popout-window.ts index 2da942050a3..441b38458f0 100644 --- a/src/main/window/dashboard-popout-window.ts +++ b/src/main/window/dashboard-popout-window.ts @@ -2,20 +2,23 @@ import { mainI18n, translateMain } from '../i18n/main-i18n' import { app, BrowserWindow, nativeTheme, type WebContents, type Event } from 'electron' import { join } from 'node:path' import type { Store } from '../persistence/loading-store/store' -import { isBackgroundLaunch, showWindowWithoutStealingFocus } from './foreground-activation-policy' -import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation' +import { + isBackgroundLaunch, + showWindowWithoutStealingFocus +} from './activation/foreground-activation-policy' +import { rectHasVisibleAreaOnAnyDisplay } from './presentation/window-bounds-validation' import { sendToTrustedUIRenderer } from '../ipc/ui' -import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' +import { installPrivilegedWindowNavigationPolicy } from './security/privileged-window-navigation' import { stepUIZoomLevel, type UIZoomDirection } from '../../shared/ui-zoom-level' import { nativeZoomCommandMatchesKeybindings } from '../../shared/window-shortcut-policy' -import { - keybindingMatchesAction, - type KeybindingActionId, - type KeybindingInput, - type KeybindingOverrides -} from '../../shared/keybindings' +import { keybindingMatchesAction } from '../../shared/keybindings/matching' +import type { + KeybindingActionId, + KeybindingInput, + KeybindingOverrides +} from '../../shared/keybindings/types' import { wslHostsWindowArguments } from '../wsl/host-lifecycle/wsl-host-gate' -import { isMacAppPasteInput } from './mac-app-paste-input' +import { isMacAppPasteInput } from './editing/mac-app-paste-input' const MIN_WIDTH = 480 const MIN_HEIGHT = 360 diff --git a/src/main/window/macos-tahoe-release.ts b/src/main/window/desktop-integration/macos-tahoe-release.ts similarity index 100% rename from src/main/window/macos-tahoe-release.ts rename to src/main/window/desktop-integration/macos-tahoe-release.ts diff --git a/src/main/window/editable-context-menu-labels.ts b/src/main/window/editing/editable-context-menu-labels.ts similarity index 97% rename from src/main/window/editable-context-menu-labels.ts rename to src/main/window/editing/editable-context-menu-labels.ts index ec7b9c580cd..8dbc18939c1 100644 --- a/src/main/window/editable-context-menu-labels.ts +++ b/src/main/window/editing/editable-context-menu-labels.ts @@ -1,4 +1,4 @@ -import { translateMain } from '../i18n/main-i18n' +import { translateMain } from '../../i18n/main-i18n' /** Labels resolve at menu-build time so they follow the current UI language. */ export function editableContextMenuLabels() { diff --git a/src/main/window/editable-context-menu-popup.ts b/src/main/window/editing/editable-context-menu-popup.ts similarity index 100% rename from src/main/window/editable-context-menu-popup.ts rename to src/main/window/editing/editable-context-menu-popup.ts diff --git a/src/main/window/editable-context-menu.ts b/src/main/window/editing/editable-context-menu.ts similarity index 97% rename from src/main/window/editable-context-menu.ts rename to src/main/window/editing/editable-context-menu.ts index 3322028eec1..4949975c440 100644 --- a/src/main/window/editable-context-menu.ts +++ b/src/main/window/editing/editable-context-menu.ts @@ -3,9 +3,9 @@ import { type RichMarkdownContextMenuCommand, type RichMarkdownContextMenuCommandPayload, type RichMarkdownContextMenuTableTarget -} from '../../shared/rich-markdown-context-menu' -import type { ContextMenuSpelling } from '../../shared/browser/guest-lifecycle/browser-guest-events' -import { translateMain } from '../i18n/main-i18n' +} from '../../../shared/rich-markdown-context-menu' +import type { ContextMenuSpelling } from '../../../shared/browser/guest-lifecycle/browser-guest-events' +import { translateMain } from '../../i18n/main-i18n' import { editableContextMenuLabels } from './editable-context-menu-labels' type EditableContextMenuWebContents = Pick< diff --git a/src/main/window/mac-app-paste-input.test.ts b/src/main/window/editing/mac-app-paste-input.test.ts similarity index 100% rename from src/main/window/mac-app-paste-input.test.ts rename to src/main/window/editing/mac-app-paste-input.test.ts diff --git a/src/main/window/mac-app-paste-input.ts b/src/main/window/editing/mac-app-paste-input.ts similarity index 79% rename from src/main/window/mac-app-paste-input.ts rename to src/main/window/editing/mac-app-paste-input.ts index 2b5c91eef02..0459f5c64af 100644 --- a/src/main/window/mac-app-paste-input.ts +++ b/src/main/window/editing/mac-app-paste-input.ts @@ -1,4 +1,7 @@ -import { logicalKeyTokenFromInput, physicalCodeKeyTokenFromInput } from '../../shared/keybindings' +import { + logicalKeyTokenFromInput, + physicalCodeKeyTokenFromInput +} from '../../../shared/keybindings/input' export function isMacAppPasteInput(input: Electron.Input): boolean { return ( diff --git a/src/main/window/checked-drag-temp-source.ts b/src/main/window/file-drop/checked-drag-temp-source.ts similarity index 94% rename from src/main/window/checked-drag-temp-source.ts rename to src/main/window/file-drop/checked-drag-temp-source.ts index 79a0a0f049b..1f831eb060e 100644 --- a/src/main/window/checked-drag-temp-source.ts +++ b/src/main/window/file-drop/checked-drag-temp-source.ts @@ -2,15 +2,15 @@ import { createWriteStream, type Stats } from 'node:fs' import { lstat, mkdtemp, rm, writeFile, type FileHandle } from 'node:fs/promises' import { basename, join } from 'node:path' import { pipeline } from 'node:stream/promises' -import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../shared/agent-session/agent-session-attachments' -import type { NativeFileDropCopyFailureReason } from '../../shared/file-import/native-file-drop' -import { readNodeFileHandleWithinLimit } from '../../shared/file-content/node-bounded-file-reader' +import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../../shared/agent-session/agent-session-attachments' +import type { NativeFileDropCopyFailureReason } from '../../../shared/file-import/native-file-drop' +import { readNodeFileHandleWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' import type { DragTempCopyBatch, DragTempCopyEnvironment, DragTempCopyItemResult } from './dragged-temp-file-copy' -import { ensureOwnedTempStagingRoot } from './owned-temp-staging-root' +import { ensureOwnedTempStagingRoot } from '../../filesystem/owned-temp-staging-root' const COPY_DIR_PREFIX = 'orca-drop-' const COPY_HIGH_WATER_MARK = 1024 * 1024 diff --git a/src/main/window/darwin-user-temp-dir.test.ts b/src/main/window/file-drop/darwin-user-temp-dir.test.ts similarity index 100% rename from src/main/window/darwin-user-temp-dir.test.ts rename to src/main/window/file-drop/darwin-user-temp-dir.test.ts diff --git a/src/main/window/darwin-user-temp-dir.ts b/src/main/window/file-drop/darwin-user-temp-dir.ts similarity index 100% rename from src/main/window/darwin-user-temp-dir.ts rename to src/main/window/file-drop/darwin-user-temp-dir.ts diff --git a/src/main/window/drag-temp-path.ts b/src/main/window/file-drop/drag-temp-path.ts similarity index 100% rename from src/main/window/drag-temp-path.ts rename to src/main/window/file-drop/drag-temp-path.ts diff --git a/src/main/window/dragged-temp-file-copy.test.ts b/src/main/window/file-drop/dragged-temp-file-copy.test.ts similarity index 98% rename from src/main/window/dragged-temp-file-copy.test.ts rename to src/main/window/file-drop/dragged-temp-file-copy.test.ts index ba806ce338c..868504568b9 100644 --- a/src/main/window/dragged-temp-file-copy.test.ts +++ b/src/main/window/file-drop/dragged-temp-file-copy.test.ts @@ -15,7 +15,7 @@ import { tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -import type * as RuntimeImportLimits from '../ipc/runtime-import-limits' +import type * as RuntimeImportLimits from '../../ipc/runtime-import-limits' const fsFaults: { beforeCopyWrite: (() => void) | null @@ -36,7 +36,7 @@ vi.mock('node:fs/promises', async (importOriginal) => { } }) -vi.mock('../ipc/runtime-import-limits', async (importOriginal) => ({ +vi.mock('../../ipc/runtime-import-limits', async (importOriginal) => ({ ...(await importOriginal()), REMOTE_IMPORT_MAX_FILE_BYTES: 10, REMOTE_IMPORT_MAX_TOTAL_BYTES: 16 diff --git a/src/main/window/dragged-temp-file-copy.ts b/src/main/window/file-drop/dragged-temp-file-copy.ts similarity index 97% rename from src/main/window/dragged-temp-file-copy.ts rename to src/main/window/file-drop/dragged-temp-file-copy.ts index c21519fb377..65f117ef4fe 100644 --- a/src/main/window/dragged-temp-file-copy.ts +++ b/src/main/window/file-drop/dragged-temp-file-copy.ts @@ -1,19 +1,19 @@ import { constants, type Stats } from 'node:fs' import { lstat, open, realpath, rm } from 'node:fs/promises' import { basename, resolve } from 'node:path' -import type { NativeFileDropCopyFailureReason } from '../../shared/file-import/native-file-drop' +import type { NativeFileDropCopyFailureReason } from '../../../shared/file-import/native-file-drop' import { formatByteCeiling, REMOTE_IMPORT_MAX_FILE_BYTES, REMOTE_IMPORT_MAX_TOTAL_BYTES -} from '../ipc/runtime-import-limits' +} from '../../ipc/runtime-import-limits' import { hasDragTempMarker, isPathWithin, mayNeedDragTempCopy, relativeSegments } from './drag-temp-path' -import { getOwnedTempStagingRoot } from './owned-temp-staging-root' +import { getOwnedTempStagingRoot } from '../../filesystem/owned-temp-staging-root' import { classifyFailure, copyCheckedDragTempSource, diff --git a/src/main/window/dropped-path-preparation-ipc.test.ts b/src/main/window/file-drop/dropped-path-preparation-ipc.test.ts similarity index 100% rename from src/main/window/dropped-path-preparation-ipc.test.ts rename to src/main/window/file-drop/dropped-path-preparation-ipc.test.ts diff --git a/src/main/window/dropped-path-preparation-ipc.ts b/src/main/window/file-drop/dropped-path-preparation-ipc.ts similarity index 93% rename from src/main/window/dropped-path-preparation-ipc.ts rename to src/main/window/file-drop/dropped-path-preparation-ipc.ts index 92e5c558c45..fe02210f706 100644 --- a/src/main/window/dropped-path-preparation-ipc.ts +++ b/src/main/window/file-drop/dropped-path-preparation-ipc.ts @@ -2,12 +2,12 @@ import { app, ipcMain, type BrowserWindow } from 'electron' import { createRejectedNativeFileDropPayload, validateNativeFileDropPaths -} from '../../shared/file-import/native-file-drop' +} from '../../../shared/file-import/native-file-drop' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/file-import/native-file-drop-preparation' -import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' +} from '../../../shared/file-import/native-file-drop-preparation' +import { abortWhenRendererGone } from '../../ipc/renderer-lifetime-abort' import { getDragTempCopyRoot } from './dragged-temp-file-copy' import { createDroppedPathPreparationQueue, diff --git a/src/main/window/dropped-path-preparation.test.ts b/src/main/window/file-drop/dropped-path-preparation.test.ts similarity index 85% rename from src/main/window/dropped-path-preparation.test.ts rename to src/main/window/file-drop/dropped-path-preparation.test.ts index 50a3264ebb7..8e4ea2f8cc9 100644 --- a/src/main/window/dropped-path-preparation.test.ts +++ b/src/main/window/file-drop/dropped-path-preparation.test.ts @@ -11,8 +11,8 @@ import { writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' -import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../shared/agent-session/agent-session-attachments' +import { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' +import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../../shared/agent-session/agent-session-attachments' import { runProcess } from '@orca/process-host' import { dirname, join } from 'node:path' import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -278,32 +278,6 @@ describe('dropped path preparation through the shared copy queue', () => { expect(handles.every((handle) => handle.fd === -1)).toBe(true) }) - it.each(['agent', 'main-reader'] as const)( - 'withholds uncopied originals only from agents: %s', - async (consumer) => { - materialize.mockResolvedValue([ - { sourcePath: ORDINARY, status: 'imported', destPath: ORDINARY }, - { sourcePath: TEMP, status: 'uncopied', reason: 'storage-full' } - ]) - const { enqueue } = queue() - const result = await enqueue({ paths: [ORDINARY, TEMP], consumer }) - expect(result.paths).toEqual(consumer === 'agent' ? [ORDINARY] : [ORDINARY, TEMP]) - expect(result.failures).toEqual( - consumer === 'agent' - ? [ - { - byteLength: 0, - pathCount: 1, - reason: 'temp-copy-failed', - target: 'rejected', - commonReason: 'storage-full' - } - ] - : [] - ) - } - ) - it('shares serialization and the pending cap across replacement-window queues', async () => { materialize.mockReturnValue(new Promise(() => undefined)) const lane = createDragTempCopyLane() @@ -334,36 +308,6 @@ describe('dropped path preparation through the shared copy queue', () => { await pending }) - it('aborts running and queued requests on reload and releases their listeners', async () => { - materialize.mockReturnValue(new Promise(() => undefined)) - const { enqueue, controller, dispose } = queue() - const running = enqueue({ paths: [TEMP], consumer: 'agent' }) - const queued = enqueue({ paths: [TEMP], consumer: 'agent' }) - const assertions = [ - expect(running).rejects.toThrow('reloaded'), - expect(queued).rejects.toThrow('reloaded') - ] - await settle() - controller.abort(new Error('reloaded')) - await Promise.all(assertions) - await settle() - expect(materialize).toHaveBeenCalledTimes(1) - expect(dispose).toHaveBeenCalledTimes(2) - }) - - it('reports timeout, keeps ordinary paths, and serves the next copy', async () => { - materialize - .mockReturnValueOnce(new Promise(() => undefined)) - .mockResolvedValueOnce([{ sourcePath: TEMP, status: 'imported', destPath: COPY }]) - const { enqueue } = queue(undefined, 5) - const first = enqueue({ paths: [ORDINARY, TEMP], consumer: 'agent' }) - const next = enqueue({ paths: [TEMP], consumer: 'agent' }) - await expect(first).resolves.toMatchObject({ - paths: [ORDINARY], - failures: [{ commonReason: 'timed-out' }] - }) - await expect(next).resolves.toEqual({ paths: [COPY], failures: [] }) - }) it('passes drag-temp-looking paths unchanged on Linux and Windows', () => { for (const platform of ['linux', 'win32'] as const) { const enqueue = createDroppedPathPreparationQueue({ diff --git a/src/main/window/dropped-path-preparation.ts b/src/main/window/file-drop/dropped-path-preparation.ts similarity index 95% rename from src/main/window/dropped-path-preparation.ts rename to src/main/window/file-drop/dropped-path-preparation.ts index 2e98806c196..ad6588a3b0b 100644 --- a/src/main/window/dropped-path-preparation.ts +++ b/src/main/window/file-drop/dropped-path-preparation.ts @@ -1,11 +1,11 @@ -import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../shared/agent-session/agent-session-attachments' +import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../../shared/agent-session/agent-session-attachments' import { basename } from 'node:path' -import type { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' -import type { NativeFileDropCopyFailureReason } from '../../shared/file-import/native-file-drop' +import type { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' +import type { NativeFileDropCopyFailureReason } from '../../../shared/file-import/native-file-drop' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/file-import/native-file-drop-preparation' +} from '../../../shared/file-import/native-file-drop-preparation' import { DragTempCopyBatch, closeDragTempSource, diff --git a/src/main/window/foreground-activation-policy.test.ts b/src/main/window/foreground-activation-policy.test.ts deleted file mode 100644 index aa37676f455..00000000000 --- a/src/main/window/foreground-activation-policy.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import type { BrowserWindow } from 'electron' -import { describe, expect, it, vi } from 'vitest' - -vi.mock('electron', () => ({ app: { dock: { hide: vi.fn() }, setActivationPolicy: vi.fn() } })) - -const { - applyBackgroundActivationPolicy, - applyServeDesktopWindowActivationPolicy, - showWindowWithoutStealingFocus -} = await import('./foreground-activation-policy') - -function makeWindow(destroyed = false): BrowserWindow & { - show: ReturnType - showInactive: ReturnType -} { - return { - isDestroyed: () => destroyed, - show: vi.fn(() => {}), - showInactive: vi.fn(() => {}) - } as unknown as BrowserWindow & { - show: ReturnType - showInactive: ReturnType - } -} - -describe('showWindowWithoutStealingFocus', () => { - it('never reveals an explicitly background window', () => { - const window = makeWindow() - showWindowWithoutStealingFocus(window, { ORCA_BACKGROUND_LAUNCH: '1' }) - expect(window.showInactive).not.toHaveBeenCalled() - expect(window.show).not.toHaveBeenCalled() - }) - - it('still reveals explicitly headful E2E without activation', () => { - const window = makeWindow() - showWindowWithoutStealingFocus(window, { ORCA_E2E_HEADFUL: '1' }) - expect(window.showInactive).toHaveBeenCalledOnce() - expect(window.show).not.toHaveBeenCalled() - }) -}) - -describe('applyBackgroundActivationPolicy', () => { - function makeApp() { - return { - dock: { hide: vi.fn(() => {}), show: vi.fn(async () => {}) }, - setActivationPolicy: vi.fn((_policy: 'accessory' | 'prohibited' | 'regular') => {}) - } - } - - it('keeps a windowless macOS serve out of the Dock until it hosts a desktop window', () => { - const app = makeApp() - expect( - applyBackgroundActivationPolicy({ - app, - env: {}, - platform: 'darwin', - serveWithoutDesktopWindow: true - }) - ).toBe(true) - expect(app.setActivationPolicy).toHaveBeenLastCalledWith('accessory') - - expect(applyServeDesktopWindowActivationPolicy({ app, env: {}, platform: 'darwin' })).toBe(true) - expect(app.setActivationPolicy).toHaveBeenLastCalledWith('regular') - expect(app.dock.show).toHaveBeenCalledOnce() - }) - - it('never gives a background serve its Dock tile back', () => { - const app = makeApp() - expect( - applyServeDesktopWindowActivationPolicy({ - app, - env: { ORCA_BACKGROUND_LAUNCH: '1' }, - platform: 'darwin' - }) - ).toBe(false) - expect( - applyServeDesktopWindowActivationPolicy({ - app, - env: { ORCA_E2E_HEADFUL: '1' }, - platform: 'darwin' - }) - ).toBe(false) - expect(app.setActivationPolicy).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/window/hidden-window-frame-pump.ts b/src/main/window/hidden-window-frame-pump.ts deleted file mode 100644 index 70ab990920a..00000000000 --- a/src/main/window/hidden-window-frame-pump.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { HIDDEN_WINDOW_FRAME_PUMP_STOP_CHANNEL } from '../../shared/hidden-window-frame-pump' - -type FramePumpWindow = { - on(event: 'show', listener: () => void): unknown - webContents: { - isDestroyed?(): boolean - on(event: 'did-finish-load', listener: () => void): unknown - send(channel: string): void - } -} - -/** The preload pumps from birth; stop it on first show and after any later reload restarts it. */ -export function stopHiddenWindowFramePumpOnShow(window: FramePumpWindow): void { - let shown = false - const stop = (): void => { - if (window.webContents.isDestroyed?.() !== true) { - window.webContents.send(HIDDEN_WINDOW_FRAME_PUMP_STOP_CHANNEL) - } - } - window.on('show', () => { - if (!shown) { - shown = true - stop() - } - }) - window.webContents.on('did-finish-load', () => { - if (shown) { - stop() - } - }) -} diff --git a/src/main/window/history-gc-worktree-ids.test.ts b/src/main/window/history-gc-worktree-ids.test.ts deleted file mode 100644 index 4e3278bced8..00000000000 --- a/src/main/window/history-gc-worktree-ids.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** An incomplete GC live set deletes owned history; regressions here caused the #14863 revert (#14975). */ -import { describe, expect, it } from 'vitest' -import { folderWorkspaceKey } from '../../shared/workspace-scope' -import { getKnownWorktreeIdsForHistoryGc } from './history-gc-worktree-ids' - -const noOtherProfiles = () => ({ ids: new Set(), unreadableProfiles: 0 }) - -const store = (worktreeIds: string[], folderIds: string[]) => - ({ - getAllWorktreeMeta: () => Object.fromEntries(worktreeIds.map((id) => [id, {}])), - getFolderWorkspaces: () => folderIds.map((id) => ({ id })) - }) as never - -describe('getKnownWorktreeIdsForHistoryGc', () => { - it('includes git worktrees', () => { - expect( - getKnownWorktreeIdsForHistoryGc(store(['repo-1::/path/wt'], []), noOtherProfiles) - ).toEqual(new Set(['repo-1::/path/wt'])) - }) - - // Folder PTYs mint history under folder:; omitting their separate store collection falsely marks live history orphaned. - it('includes folder workspaces under their PTY workspace key', () => { - const live = getKnownWorktreeIdsForHistoryGc( - store(['repo-1::/path/wt'], ['fw-1', 'fw-2']), - noOtherProfiles - ) - - expect(live.has(folderWorkspaceKey('fw-1'))).toBe(true) - expect(live.has(folderWorkspaceKey('fw-2'))).toBe(true) - expect(live.size).toBe(3) - }) - - it('is empty only when there is genuinely nothing live', () => { - expect(getKnownWorktreeIdsForHistoryGc(store([], []), noOtherProfiles).size).toBe(0) - }) - - // History is not profile-scoped, so other profiles must remain in the live set. - it('includes worktrees owned by other profiles', () => { - const live = getKnownWorktreeIdsForHistoryGc(store(['repo-1::/b'], ['fw-b']), () => ({ - ids: new Set(['repo-1::/a', folderWorkspaceKey('fw-a')]), - unreadableProfiles: 0 - })) - - expect(live).toEqual( - new Set(['repo-1::/b', folderWorkspaceKey('fw-b'), 'repo-1::/a', folderWorkspaceKey('fw-a')]) - ) - }) - - // Unreadable profiles make ownership unknown; empty means prune nothing, while partial IDs would delete live history. - it('reports nothing live when a profile could not be read', () => { - const live = getKnownWorktreeIdsForHistoryGc(store(['repo-1::/b'], ['fw-b']), () => ({ - ids: new Set(['repo-1::/a']), - unreadableProfiles: 1 - })) - - expect(live.size).toBe(0) - }) -}) diff --git a/src/main/window/host-frame-navigation-guard.test.ts b/src/main/window/host-frame-navigation-guard.test.ts deleted file mode 100644 index 2cd3bea64bb..00000000000 --- a/src/main/window/host-frame-navigation-guard.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { PLUGIN_PANEL_FRAME_NAME_PREFIX } from '../../shared/plugins/frames/plugin-frame-bridge' -import { NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX } from '../../shared/native-chat/native-chat-visual-shell' -import { HostFrameNavigationRegistry, hostFrameKindForName } from './host-frame-navigation-guard' - -function frame(input: { id: number; name?: string; url?: string }) { - let destroyed = false - return { - frameTreeNodeId: input.id, - name: input.name ?? '', - isDestroyed: () => destroyed, - destroy: () => { - destroyed = true - } - } -} - -describe('HostFrameNavigationRegistry', () => { - it('blocks only host-marked plugin srcdoc frames', () => { - const registry = new HostFrameNavigationRegistry() - const plugin = frame({ id: 1, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo` }) - const notebook = frame({ id: 2 }) - registry.register(plugin) - registry.register(notebook) - - expect(registry.shouldBlock(plugin, null, 'about:srcdoc')).toBe(false) - expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(true) - expect(registry.shouldBlock(notebook, notebook, 'https://example.com')).toBe(false) - }) - - it('keeps pre-parse identity after name mutation and ignores destroyed frames', () => { - const registry = new HostFrameNavigationRegistry() - const plugin = frame({ id: 1, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo` }) - registry.register(plugin) - plugin.name = '' - expect(registry.shouldBlock(plugin, null, 'about:srcdoc')).toBe(false) - expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(true) - - plugin.destroy() - expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(false) - }) - - it('contains chat visual frames the same way, as their own kind', () => { - const registry = new HostFrameNavigationRegistry() - const visual = frame({ id: 3, name: `${NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX}abc` }) - registry.register(visual) - expect(hostFrameKindForName(visual.name)).toBe('chat-visual') - expect(hostFrameKindForName(`${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo`)).toBe('plugin-panel') - expect(hostFrameKindForName('orca-chat-visual')).toBeNull() - - expect(registry.shouldBlock(visual, null, 'about:srcdoc')).toBe(false) - // Its own navigation (location, meta refresh, link) and any child it starts are refused. - expect(registry.shouldBlock(visual, visual, 'https://example.com')).toBe(true) - expect(registry.shouldBlock(visual, null, 'https://example.com')).toBe(true) - const child = frame({ id: 4 }) - expect(registry.shouldBlock(child, visual, 'https://example.com')).toBe(true) - }) - - it('does not inspect unrelated guarded frames during registration or navigation', () => { - const registry = new HostFrameNavigationRegistry() - let livenessChecks = 0 - const panels = Array.from({ length: 100 }, (_, id) => ({ - ...frame({ id, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}${id}` }), - isDestroyed: () => { - livenessChecks++ - return false - } - })) - for (const panel of panels) { - registry.register(panel) - } - const ordinary = frame({ id: 101 }) - registry.register(ordinary) - expect(registry.shouldBlock(ordinary, null, 'https://example.com')).toBe(false) - expect(registry.shouldBlock(panels[0], null, 'about:srcdoc')).toBe(false) - expect(registry.shouldBlock(panels[0], panels[0], 'https://example.com')).toBe(true) - expect(registry.shouldBlock(ordinary, panels[1], 'https://example.com')).toBe(true) - expect(livenessChecks).toBeLessThanOrEqual(4) - }) -}) diff --git a/src/main/window/macos-app-activation.test.ts b/src/main/window/macos-app-activation.test.ts deleted file mode 100644 index e4670422cb4..00000000000 --- a/src/main/window/macos-app-activation.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { BrowserWindow } from 'electron' -import { describe, expect, it, vi } from 'vitest' -import { createMacAppActivationHandler } from './macos-app-activation' - -function makeWindow(destroyed = false): BrowserWindow { - return { - isDestroyed: vi.fn(() => destroyed) - } as unknown as BrowserWindow -} - -describe('createMacAppActivationHandler', () => { - it('leaves an existing window to native macOS activation', () => { - const requestActivation = vi.fn() - const handler = createMacAppActivationHandler({ - getWindow: () => makeWindow(), - requestActivation - }) - - handler() - - expect(requestActivation).not.toHaveBeenCalled() - }) - - it.each([null, makeWindow(true)])( - 'requests desktop activation for a missing or destroyed window', - (window) => { - const requestActivation = vi.fn() - const handler = createMacAppActivationHandler({ - getWindow: () => window, - requestActivation - }) - - handler() - - expect(requestActivation).toHaveBeenCalledTimes(1) - } - ) -}) diff --git a/src/main/window/macos-desktop-handoff.test.ts b/src/main/window/macos-desktop-handoff.test.ts deleted file mode 100644 index 1ad987ec0a9..00000000000 --- a/src/main/window/macos-desktop-handoff.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { spawnProcessMock } = vi.hoisted(() => ({ spawnProcessMock: vi.fn() })) - -vi.mock('electron', () => ({ - app: { - getPath: () => '/Applications/Orca.app/Contents/MacOS/Orca', - dock: { hide: vi.fn() }, - setActivationPolicy: vi.fn() - } -})) -vi.mock('@orca/process-host', () => ({ spawnProcess: spawnProcessMock })) - -const { createDesktopHandoff, handOffToDesktopApp } = await import('./macos-desktop-handoff') - -function makeChild(): EventEmitter & { unref: ReturnType } { - return Object.assign(new EventEmitter(), { unref: vi.fn() }) -} - -afterEach(() => { - spawnProcessMock.mockReset() - vi.restoreAllMocks() -}) - -describe('handOffToDesktopApp', () => { - it('opens a new instance of the installed bundle with a Dock launch environment', () => { - const child = makeChild() - spawnProcessMock.mockReturnValue(child) - - handOffToDesktopApp([], { - platform: 'darwin', - env: {}, - reapplyActivationPolicy: vi.fn() - }) - - expect(spawnProcessMock).toHaveBeenCalledWith({ - program: '/usr/bin/open', - args: ['-n', '/Applications/Orca.app'], - env: {}, - detached: true, - stdio: 'ignore' - }) - expect(child.unref).toHaveBeenCalledOnce() - }) - - it('passes buffered links and documents to the new instance', () => { - spawnProcessMock.mockReturnValue(makeChild()) - - handOffToDesktopApp(['orca://skills/share/abc', '/Users/me/notes.md'], { - platform: 'darwin', - env: {}, - executablePath: '/Users/me/Applications/Orca.app/Contents/MacOS/Orca', - reapplyActivationPolicy: vi.fn() - }) - - expect(spawnProcessMock.mock.calls[0][0].args).toEqual([ - '-n', - '/Users/me/Applications/Orca.app', - '--args', - 'orca://skills/share/abc', - '/Users/me/notes.md' - ]) - }) - - it('drops back out of the Dock after launching the desktop app', () => { - spawnProcessMock.mockReturnValue(makeChild()) - const reapplyActivationPolicy = vi.fn() - - handOffToDesktopApp([], { - platform: 'darwin', - env: {}, - reapplyActivationPolicy - }) - - expect(reapplyActivationPolicy).toHaveBeenCalledOnce() - expect(reapplyActivationPolicy.mock.invocationCallOrder[0]).toBeGreaterThan( - spawnProcessMock.mock.invocationCallOrder[0] - ) - }) - - it('logs a failed launch instead of taking main down', () => { - const child = makeChild() - spawnProcessMock.mockReturnValue(child) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - handOffToDesktopApp([], { - platform: 'darwin', - env: {}, - reapplyActivationPolicy: vi.fn() - }) - child.emit('error', new Error('spawn /usr/bin/open ENOENT')) - - expect(warn).toHaveBeenCalledOnce() - }) - - it.each([{ ORCA_BACKGROUND_LAUNCH: '1' }, { ORCA_E2E_USER_DATA_DIR: '/tmp/e2e' }])( - 'never launches the real desktop app from an automated sidecar (%o)', - (env) => { - const reapplyActivationPolicy = vi.fn() - - handOffToDesktopApp([], { - platform: 'darwin', - env, - reapplyActivationPolicy - }) - - expect(spawnProcessMock).not.toHaveBeenCalled() - expect(reapplyActivationPolicy).toHaveBeenCalledOnce() - } - ) -}) - -describe('createDesktopHandoff', () => { - const nextTurn = (): Promise => new Promise((resolve) => setImmediate(resolve)) - - it('hands a multi-file open over in one launch carrying every file', async () => { - const pending: string[] = [] - const handOff = vi.fn() - const requestHandoff = createDesktopHandoff({ - drainArguments: () => pending.splice(0), - handOff - }) - - for (const file of ['/Users/me/a.md', '/Users/me/b.md', '/Users/me/c.csv']) { - pending.push(file) - requestHandoff() - } - expect(handOff).not.toHaveBeenCalled() - await nextTurn() - - expect(handOff).toHaveBeenCalledOnce() - expect(handOff).toHaveBeenCalledWith(['/Users/me/a.md', '/Users/me/b.md', '/Users/me/c.csv']) - }) - - it('launches again for a later open', async () => { - const handOff = vi.fn() - const requestHandoff = createDesktopHandoff({ - drainArguments: () => [], - handOff - }) - - requestHandoff() - await nextTurn() - requestHandoff() - await nextTurn() - - expect(handOff).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/window/main-window-state-lifecycle.test.ts b/src/main/window/main-window-state-lifecycle.test.ts deleted file mode 100644 index 5cc44785853..00000000000 --- a/src/main/window/main-window-state-lifecycle.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' - -const { appMock, launchPolicy } = await vi.hoisted(async () => { - const { EventEmitter } = await import('node:events') - return { appMock: new EventEmitter(), launchPolicy: { background: false, windowless: true } } -}) -vi.mock('electron', () => ({ app: appMock })) -vi.mock('./foreground-activation-policy', () => ({ - isBackgroundLaunch: () => launchPolicy.background, - isWindowlessLaunch: () => launchPolicy.windowless, - showWindowWithoutStealingFocus: vi.fn() -})) -vi.mock('./main-window-visual-lifecycle', () => ({ - MIN_WIDTH: 480, - MIN_HEIGHT: 360, - syncTrafficLightPosition: vi.fn() -})) - -import { installMainWindowStateLifecycle } from './main-window-state-lifecycle' - -beforeEach(() => { - vi.useFakeTimers() - appMock.removeAllListeners() - launchPolicy.background = false - launchPolicy.windowless = true -}) -afterEach(() => vi.useRealTimers()) - -it('continues saving bounds after an updater quit veto and freezes them on allowed quit', async () => { - const mainWindow = Object.assign(new EventEmitter(), { - webContents: Object.assign(new EventEmitter(), { - send: vi.fn(), - setZoomLevel: vi.fn() - }), - isDestroyed: () => false, - isFullScreen: () => false, - isMaximized: () => false, - getBounds: () => ({ x: 0, y: 0, width: 1200, height: 800 }) - }) - const updateUI = vi.fn() - const lifecycle = installMainWindowStateLifecycle({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture implements the window members read by the bounds lifecycle. - mainWindow: mainWindow as never, - revealOnDidFinishLoad: false, - savedMaximized: false, - savedFullScreen: false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Bounds persistence reads only updateUI from this store fixture. - store: { updateUI } as never - }) - appMock.emit('before-quit', { defaultPrevented: true }) - expect(lifecycle.isWindowClosing()).toBe(false) - mainWindow.emit('resize') - await vi.advanceTimersByTimeAsync(500) - expect(updateUI).toHaveBeenCalledWith({ - windowMaximized: false, - windowBounds: { x: 0, y: 0, width: 1200, height: 800 } - }) - - updateUI.mockClear() - appMock.emit('before-quit', { defaultPrevented: false }) - expect(lifecycle.isWindowClosing()).toBe(true) - mainWindow.emit('resize') - await vi.advanceTimersByTimeAsync(500) - expect(updateUI).not.toHaveBeenCalled() - lifecycle.clearInitialRevealFallbackTimer() - lifecycle.dispose() -}) - -function installFullScreenFixture(): { - lifecycle: ReturnType - mainWindow: EventEmitter & { setFullScreen: (flag: boolean) => void } - windowState: { maximized: boolean; fullScreen: boolean; maximizedUnderFullScreen: boolean } - persisted: Record -} { - launchPolicy.windowless = false - const windowState = { maximized: false, fullScreen: false, maximizedUnderFullScreen: false } - const mainWindow = Object.assign(new EventEmitter(), { - webContents: Object.assign(new EventEmitter(), { send: vi.fn(), setZoomLevel: vi.fn() }), - isDestroyed: () => false, - isFullScreen: () => windowState.fullScreen, - getBounds: () => ({ x: 0, y: 0, width: 2560, height: 1440 }), - maximize: () => { - windowState.maximized = true - }, - setFullScreen: (flag: boolean) => { - if (flag) { - windowState.maximizedUnderFullScreen = windowState.maximized - } - windowState.fullScreen = flag - } - }) - const persisted: Record = {} - const lifecycle = installMainWindowStateLifecycle({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture implements the window members read by reveal and fullscreen persistence. - mainWindow: mainWindow as never, - revealOnDidFinishLoad: false, - savedMaximized: true, - savedFullScreen: true, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Fullscreen persistence reads only updateUI from this store fixture. - store: { - updateUI: (patch: Record) => Object.assign(persisted, patch) - } as never - }) - return { lifecycle, mainWindow, windowState, persisted } -} - -it('restores native fullscreen over the maximized frame and keeps that frame while fullscreen', () => { - const { lifecycle, mainWindow, windowState, persisted } = installFullScreenFixture() - const leaveFullScreen = (): void => { - mainWindow.setFullScreen(false) - mainWindow.emit('leave-full-screen') - } - mainWindow.emit('ready-to-show') - expect(windowState).toEqual({ maximized: true, fullScreen: true, maximizedUnderFullScreen: true }) - // macOS emits unmaximize mid-transition, after the fullscreen style mask is set. - mainWindow.emit('unmaximize') - mainWindow.emit('enter-full-screen') - expect(persisted).toEqual({ windowFullScreen: true }) - - leaveFullScreen() - expect(persisted).toEqual({ windowFullScreen: false }) - mainWindow.emit('unmaximize') - expect(persisted).toEqual({ - windowFullScreen: false, - windowMaximized: false, - windowBounds: { x: 0, y: 0, width: 2560, height: 1440 } - }) - - mainWindow.setFullScreen(true) - mainWindow.emit('enter-full-screen') - appMock.emit('before-quit', { defaultPrevented: false }) - leaveFullScreen() - expect(persisted).toMatchObject({ windowFullScreen: true }) - lifecycle.clearInitialRevealFallbackTimer() - lifecycle.dispose() -}) - -it('does not restore native fullscreen for background launches', () => { - launchPolicy.background = true - const { lifecycle, mainWindow, windowState } = installFullScreenFixture() - mainWindow.emit('ready-to-show') - expect(windowState).toEqual({ - maximized: true, - fullScreen: false, - maximizedUnderFullScreen: false - }) - lifecycle.clearInitialRevealFallbackTimer() - lifecycle.dispose() -}) diff --git a/src/main/window/main-window-updater-deferred-setup.test.ts b/src/main/window/main-window-updater-deferred-setup.test.ts deleted file mode 100644 index b1a0d2490fa..00000000000 --- a/src/main/window/main-window-updater-deferred-setup.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { BrowserWindow } from 'electron' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../persistence/loading-store/store' -import type { UpdaterSetupOptions } from '../updater/lifecycle/updater-setup' - -const { setupMock, milestoneMock, getMainWindowMock } = vi.hoisted(() => ({ - getMainWindowMock: vi.fn<() => BrowserWindow | null>(() => null), - setupMock: vi.fn<(window: BrowserWindow, options?: UpdaterSetupOptions) => void>(), - milestoneMock: vi.fn<(name: string) => void>() -})) - -vi.mock('electron', () => ({ app: {}, ipcMain: {} })) -vi.mock('../updater/updater-service', () => ({ setupAutoUpdater: setupMock })) -vi.mock('../updater/lifecycle/electron-updater-proxy-session', () => ({ - applyProxyToElectronUpdaterSession: vi.fn() -})) -vi.mock('../ipc/ui', () => ({ - isTrustedUIRenderer: () => true, - getTrustedUIRendererWindow: getMainWindowMock -})) -vi.mock('../startup/startup-diagnostics', () => ({ logStartupMilestone: milestoneMock })) - -function createWindowOwner() { - const window = Object.assign(new EventEmitter(), { - id: 7, - isDestroyed: vi.fn(() => false) - }) - const ui = { - lastUpdateCheckAt: 123, - pendingUpdateNudgeId: 'pending', - dismissedUpdateNudgeId: 'dismissed', - releaseChannelOverride: 'rc' - } satisfies Partial> - const store = { - getSettings: vi.fn(() => ({})), - getUI: vi.fn(() => ui), - updateUI: vi.fn<(patch: Parameters[0]) => void>(), - flushPendingAsync: vi.fn().mockResolvedValue(undefined) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This owner only reads id/isDestroyed and registers once; EventEmitter supplies the original once contract. - const mainWindow = window as unknown as BrowserWindow - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The complete owner accesses only these three store methods and the checked UI fields above. - const persistence = store as unknown as Store - return { window, mainWindow, store, persistence } -} - -function captureError(action: () => void): unknown { - try { - action() - } catch (error) { - return error - } - throw new Error('Expected action to throw') -} - -describe('completed deferred updater setup ownership', () => { - beforeEach(() => { - vi.resetModules() - vi.useFakeTimers() - setupMock.mockReset() - milestoneMock.mockReset() - }) - - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('does not retain the expired native fallback of a destroyed window', async () => { - vi.useRealTimers() - const updater = await import('./main-window-updater') - const owner = createWindowOwner() - owner.window.isDestroyed.mockReturnValue(true) - function scheduleNativeFallback(): WeakRef { - const nativeSetTimeout = globalThis.setTimeout - const armed = vi - .spyOn(globalThis, 'setTimeout') - .mockImplementation((callback, delay, ...args) => - nativeSetTimeout(callback, delay === 15_000 ? 1 : delay, ...args) - ) - try { - updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) - expect(armed).toHaveBeenCalledOnce() - expect(armed.mock.calls[0]?.[1]).toBe(15_000) - const handle = armed.mock.results[0]?.value - if (!handle) { - throw new Error('Missing native fallback timer') - } - expect(handle.hasRef()).toBe(false) - return new WeakRef(handle) - } finally { - armed.mockClear() - armed.mockRestore() - } - } - // The real deadline has separate paired proof; only this fixture's native wait is shortened. - const weakTimer = scheduleNativeFallback() - await new Promise((resolve) => setTimeout(resolve, 10)) - expect(owner.window.isDestroyed).toHaveBeenCalledOnce() - updater.ensureAutoUpdaterConfigured() - expect(owner.window.isDestroyed).toHaveBeenCalledTimes(2) - expect(setupMock).not.toHaveBeenCalled() - expect(milestoneMock).not.toHaveBeenCalled() - expect(globalThis.gc).toBeTypeOf('function') - for (let turn = 0; turn < 4; turn++) { - await new Promise((resolve) => setImmediate(resolve)) - globalThis.gc?.() - } - expect(weakTimer.deref()).toBeUndefined() - }) - - it('keeps the fallback guard when destruction happens after ready but before immediate', async () => { - const updater = await import('./main-window-updater') - const owner = createWindowOwner() - updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) - owner.window.emit('ready-to-show') - owner.window.isDestroyed.mockReturnValue(true) - await vi.advanceTimersByTimeAsync(0) - expect(owner.window.isDestroyed).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(1) - await vi.advanceTimersByTimeAsync(15_000) - expect(owner.window.isDestroyed).toHaveBeenCalledTimes(2) - expect(setupMock).not.toHaveBeenCalled() - }) - - it('retains original setup order and avoids reentrant initialization', async () => { - const updater = await import('./main-window-updater') - const owner = createWindowOwner() - const trace: string[] = [] - setupMock.mockImplementation(() => { - trace.push('setup') - updater.ensureAutoUpdaterConfigured() - trace.push('setup-return') - }) - milestoneMock.mockImplementation(() => { - trace.push('milestone') - updater.ensureAutoUpdaterConfigured() - }) - updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) - updater.ensureAutoUpdaterConfigured() - expect(trace).toEqual(['setup', 'setup-return', 'milestone']) - expect(setupMock).toHaveBeenCalledOnce() - expect(owner.window.isDestroyed).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - }) - - it('preserves pending retry after a failed destroyed-state read', async () => { - const updater = await import('./main-window-updater') - const owner = createWindowOwner() - const error = new Error('destroyed-state read failed') - owner.window.isDestroyed.mockImplementationOnce(() => { - throw error - }) - updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) - expect(captureError(() => updater.ensureAutoUpdaterConfigured())).toBe(error) - expect(setupMock).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(1) - updater.ensureAutoUpdaterConfigured() - expect(setupMock).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - }) - - it('releases the fallback created after synchronous registration reentry', async () => { - const updater = await import('./main-window-updater') - const owner = createWindowOwner() - const once = owner.window.once.bind(owner.window) - vi.spyOn(owner.window, 'once').mockImplementationOnce((event, listener) => { - updater.ensureAutoUpdaterConfigured() - return once(event, listener) - }) - updater.scheduleMainWindowAutoUpdaterSetup(owner.mainWindow, owner.persistence) - expect(setupMock).toHaveBeenCalledOnce() - expect(milestoneMock).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - owner.window.emit('ready-to-show') - await vi.advanceTimersByTimeAsync(0) - expect(setupMock).toHaveBeenCalledOnce() - }) - - it('keeps a same-ID successor pending after the old window becomes ready', async () => { - const updater = await import('./main-window-updater') - const old = createWindowOwner() - const successor = createWindowOwner() - updater.scheduleMainWindowAutoUpdaterSetup(old.mainWindow, old.persistence) - updater.scheduleMainWindowAutoUpdaterSetup(successor.mainWindow, successor.persistence) - expect(vi.getTimerCount()).toBe(2) - old.window.emit('ready-to-show') - await vi.advanceTimersByTimeAsync(0) - expect(setupMock).toHaveBeenLastCalledWith(old.mainWindow, expect.any(Object)) - expect(vi.getTimerCount()).toBe(1) - updater.ensureAutoUpdaterConfigured() - expect(setupMock).toHaveBeenLastCalledWith(successor.mainWindow, expect.any(Object)) - expect(setupMock).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) - }) - - it.each(['setup', 'milestone'] as const)( - 'preserves a reentrant successor when the old %s throws', - async (failure) => { - const updater = await import('./main-window-updater') - const old = createWindowOwner() - const successor = createWindowOwner() - const error = new Error('old owner failed after replacement') - const replaceAndThrow = () => { - updater.scheduleMainWindowAutoUpdaterSetup(successor.mainWindow, successor.persistence) - throw error - } - if (failure === 'setup') { - setupMock.mockImplementationOnce(replaceAndThrow) - } else { - milestoneMock.mockImplementationOnce(replaceAndThrow) - } - updater.scheduleMainWindowAutoUpdaterSetup(old.mainWindow, old.persistence) - expect(captureError(() => updater.ensureAutoUpdaterConfigured())).toBe(error) - expect(vi.getTimerCount()).toBe(1) - updater.ensureAutoUpdaterConfigured() - expect(setupMock).toHaveBeenLastCalledWith(successor.mainWindow, expect.any(Object)) - expect(setupMock).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) - } - ) - - it('preserves the successor after an old destroyed fallback', async () => { - const updater = await import('./main-window-updater') - const old = createWindowOwner() - const successor = createWindowOwner() - updater.scheduleMainWindowAutoUpdaterSetup(old.mainWindow, old.persistence) - old.window.isDestroyed.mockReturnValue(true) - await vi.advanceTimersByTimeAsync(5_000) - updater.scheduleMainWindowAutoUpdaterSetup(successor.mainWindow, successor.persistence) - await vi.advanceTimersByTimeAsync(10_000) - expect(setupMock).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(1) - updater.ensureAutoUpdaterConfigured() - expect(setupMock).toHaveBeenCalledWith(successor.mainWindow, expect.any(Object)) - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/main/window/main-window-activity.ts b/src/main/window/main-window/main-window-activity.ts similarity index 100% rename from src/main/window/main-window-activity.ts rename to src/main/window/main-window/main-window-activity.ts diff --git a/src/main/window/main-window-close-lifecycle.ts b/src/main/window/main-window/main-window-close-lifecycle.ts similarity index 96% rename from src/main/window/main-window-close-lifecycle.ts rename to src/main/window/main-window/main-window-close-lifecycle.ts index dd6ba13f6cc..2275643160a 100644 --- a/src/main/window/main-window-close-lifecycle.ts +++ b/src/main/window/main-window/main-window-close-lifecycle.ts @@ -1,7 +1,7 @@ import { ipcMain, Menu, Notification, type BrowserWindow } from 'electron' -import { QUIT_RENDERER_ACK_TIMEOUT_MS } from '../../shared/quit-teardown-deadline' -import { translateMain } from '../i18n/main-i18n' -import type { Store } from '../persistence/loading-store/store' +import { QUIT_RENDERER_ACK_TIMEOUT_MS } from '../../../shared/quit-teardown-deadline' +import { translateMain } from '../../i18n/main-i18n' +import type { Store } from '../../persistence/loading-store/store' import { resolveWindowCloseAction } from './window-close-decision' import type { CreateMainWindowOptions } from './main-window-contracts' import type { MainWindowFocusLifecycle } from './main-window-focus-lifecycle' @@ -9,8 +9,6 @@ import type { MainWindowStateLifecycle } from './main-window-state-lifecycle' import { syncTrafficLightPosition } from './main-window-visual-lifecycle' import { consumeUserQuitWindowClose } from './user-quit-window-close' -export const WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS = QUIT_RENDERER_ACK_TIMEOUT_MS - export function installMainWindowCloseLifecycle(args: { focus: MainWindowFocusLifecycle mainWindow: BrowserWindow @@ -50,7 +48,7 @@ export function installMainWindowCloseLifecycle(args: { console.warn('[window] Renderer did not acknowledge quit; destroying unresponsive window') state.freezeBoundsOnQuit() mainWindow.destroy() - }, WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS) + }, QUIT_RENDERER_ACK_TIMEOUT_MS) quitRendererAckTimer.unref?.() } let lastAcknowledgedRequestId = 0 diff --git a/src/main/window/main-window-contracts.ts b/src/main/window/main-window/main-window-contracts.ts similarity index 89% rename from src/main/window/main-window-contracts.ts rename to src/main/window/main-window/main-window-contracts.ts index 91937c3b16b..0d84dd910c7 100644 --- a/src/main/window/main-window-contracts.ts +++ b/src/main/window/main-window/main-window-contracts.ts @@ -1,11 +1,11 @@ -import type { KeybindingOverrides } from '../../shared/keybindings' -import type { LowCommitOomVerdict } from '../crash-reporting/recovery/low-commit-oom-recovery-gate' +import type { KeybindingOverrides } from '../../../shared/keybindings/types' +import type { LowCommitOomVerdict } from '../../crash-reporting/recovery/low-commit-oom-recovery-gate' import type { RecoveryExhaustionCause, RecoveryReloadMilestone, RecoveryReloadTrigger -} from './renderer-recovery-reload-watchdog' -import type { RendererLivenessAtDeath } from './renderer-liveness-at-death' +} from '../renderer-recovery/renderer-recovery-reload-watchdog' +import type { RendererLivenessAtDeath } from '../renderer-recovery/renderer-liveness-at-death' /** Per-load outcome from Electron's load promise, which is scoped to that one load unlike `did-finish-load`. */ export type MainWindowLoadObserver = { diff --git a/src/main/window/main-window-focus-lifecycle.ts b/src/main/window/main-window/main-window-focus-lifecycle.ts similarity index 92% rename from src/main/window/main-window-focus-lifecycle.ts rename to src/main/window/main-window/main-window-focus-lifecycle.ts index ba9c1380998..c14f19d2b31 100644 --- a/src/main/window/main-window-focus-lifecycle.ts +++ b/src/main/window/main-window/main-window-focus-lifecycle.ts @@ -1,32 +1,32 @@ import { ipcMain, type BrowserWindow } from 'electron' -import { isCrashReportReason } from '../../shared/crash-reporting' +import { isCrashReportReason } from '../../../shared/crash-reporting' import { plainTextContextMenuTargetChannel, richMarkdownContextMenuTargetChannel, type RichMarkdownContextMenuTableTarget -} from '../../shared/rich-markdown-context-menu' +} from '../../../shared/rich-markdown-context-menu' import { DEFAULT_RENDERER_RECOVERY_MAX_RECOVERIES, DEFAULT_RENDERER_RECOVERY_WINDOW_MS, RendererRecoveryCircuitBreaker -} from '../crash-reporting/recovery/renderer-recovery-circuit-breaker' -import { createLowCommitOomRecoveryGate } from '../crash-reporting/recovery/low-commit-oom-recovery-gate' +} from '../../crash-reporting/recovery/renderer-recovery-circuit-breaker' +import { createLowCommitOomRecoveryGate } from '../../crash-reporting/recovery/low-commit-oom-recovery-gate' import { buildEditableContextMenuTemplate, matchingRichMarkdownContextMenuTableTarget, parseRichMarkdownContextMenuTableTarget -} from './editable-context-menu' -import { createEditableContextMenuPopup } from './editable-context-menu-popup' +} from '../editing/editable-context-menu' +import { createEditableContextMenuPopup } from '../editing/editable-context-menu-popup' import type { CreateMainWindowOptions, MainWindowLoadObserver } from './main-window-contracts' -import { browserRouteWebContentsRegistry } from '../browser/routing/sessions/browser-route-session-runtime' +import { browserRouteWebContentsRegistry } from '../../browser/routing/sessions/browser-route-session-runtime' import { attachBrowserClientPageRenderer, retireBrowserClientPageRenderer -} from '../browser/client-pages/renderer/browser-client-page-renderer-runtime' -import { registerRendererDocumentNavigation } from './renderer-document-navigation' -import { createRendererRecoveryReloadWatchdog } from './renderer-recovery-reload-watchdog' -import { createRendererLaunchFailureBackoff } from './renderer-launch-failure-backoff' -import { trackRendererLivenessAtDeath } from './renderer-liveness-at-death' +} from '../../browser/client-pages/renderer/browser-client-page-renderer-runtime' +import { registerRendererDocumentNavigation } from '../security/renderer-document-navigation' +import { createRendererRecoveryReloadWatchdog } from '../renderer-recovery/renderer-recovery-reload-watchdog' +import { createRendererLaunchFailureBackoff } from '../renderer-recovery/renderer-launch-failure-backoff' +import { trackRendererLivenessAtDeath } from '../renderer-recovery/renderer-liveness-at-death' export type MainWindowFocusLifecycle = { dispose: () => void diff --git a/src/main/window/main-window-shortcut-actions.ts b/src/main/window/main-window/main-window-shortcut-actions.ts similarity index 92% rename from src/main/window/main-window-shortcut-actions.ts rename to src/main/window/main-window/main-window-shortcut-actions.ts index 03acfaa28ab..ac2c0919428 100644 --- a/src/main/window/main-window-shortcut-actions.ts +++ b/src/main/window/main-window/main-window-shortcut-actions.ts @@ -1,5 +1,5 @@ import type { BrowserWindow } from 'electron' -import type { WindowShortcutAction } from '../../shared/window-shortcut-policy' +import type { WindowShortcutAction } from '../../../shared/window-shortcut-policy' export function sendResolvedWindowShortcutAction( mainWindow: BrowserWindow, @@ -42,9 +42,6 @@ export function sendResolvedWindowShortcutAction( case 'openNewWorkspace': mainWindow.webContents.send('ui:openNewWorkspace') return - case 'deleteCurrentWorkspace': - mainWindow.webContents.send('ui:deleteCurrentWorkspace') - return case 'openWorkspaceBoard': mainWindow.webContents.send('ui:openWorkspaceBoard') return diff --git a/src/main/window/main-window-shortcut-routing.ts b/src/main/window/main-window/main-window-shortcut-routing.ts similarity index 89% rename from src/main/window/main-window-shortcut-routing.ts rename to src/main/window/main-window/main-window-shortcut-routing.ts index ce6f15827eb..13ccda8c893 100644 --- a/src/main/window/main-window-shortcut-routing.ts +++ b/src/main/window/main-window/main-window-shortcut-routing.ts @@ -3,11 +3,9 @@ import type { BrowserWindow } from 'electron' import { ModifierDoubleTapDetector, toModifierDoubleTapEvent -} from '../../shared/modifier-double-tap-detector' -import { - normalizeTerminalShortcutPolicy, - type KeybindingMatchOptions -} from '../../shared/keybindings' +} from '../../../shared/modifier-double-tap-detector' +import { normalizeTerminalShortcutPolicy } from '../../../shared/keybindings/effective' +import type { KeybindingMatchOptions } from '../../../shared/keybindings/types' import { getWindowShortcutActionId, matchesRecentTabSwitcherChord, @@ -15,18 +13,17 @@ import { resolveWindowShortcutAction, windowShortcutActionCapturesTerminal, type WindowShortcutAction -} from '../../shared/window-shortcut-policy' -import type { Store } from '../persistence/loading-store/store' +} from '../../../shared/window-shortcut-policy' +import type { Store } from '../../persistence/loading-store/store' import type { CreateMainWindowOptions } from './main-window-contracts' import type { MainWindowFocusLifecycle } from './main-window-focus-lifecycle' import { sendResolvedWindowShortcutAction } from './main-window-shortcut-actions' -import { isMacAppPasteInput } from './mac-app-paste-input' -import { dictationShortcutMode } from '../../shared/dictation-shortcut-mode' +import { isMacAppPasteInput } from '../editing/mac-app-paste-input' +import { dictationShortcutMode } from '../../../shared/dictation-shortcut-mode' import { - nativeChatPromptClaimsShortcut, textInputOwnsComposition, type TextShortcutInput -} from '../../shared/text-input-shortcut-policy' +} from '../../../shared/text-input-shortcut-policy' export function installMainWindowShortcutRouting(args: { focus: MainWindowFocusLifecycle @@ -47,14 +44,6 @@ export function installMainWindowShortcutRouting(args: { } ): boolean => { const { focusedShortcutContext, isAutoRepeat } = options - // The IPC carries no key event; preserve prompt editing before consuming a destructive chord. - if ( - action.type === 'deleteCurrentWorkspace' && - focusedShortcutContext.context !== 'terminal' && - nativeChatPromptClaimsShortcut(options.input, process.platform, 'workspace.delete') - ) { - return false - } if ( focus.isFloatingTerminalInputFocused() && (action.type === 'toggleLeftSidebar' || action.type === 'toggleRightSidebar') @@ -110,10 +99,7 @@ export function installMainWindowShortcutRouting(args: { return true } - if ( - (action.type === 'toggleQuickCommandsMenu' || action.type === 'deleteCurrentWorkspace') && - isAutoRepeat - ) { + if (action.type === 'toggleQuickCommandsMenu' && isAutoRepeat) { event.preventDefault() return true } diff --git a/src/main/window/main-window/main-window-state-lifecycle.test.ts b/src/main/window/main-window/main-window-state-lifecycle.test.ts new file mode 100644 index 00000000000..e10da85f2c8 --- /dev/null +++ b/src/main/window/main-window/main-window-state-lifecycle.test.ts @@ -0,0 +1,68 @@ +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +const { appMock, launchPolicy } = await vi.hoisted(async () => { + const { EventEmitter } = await import('node:events') + return { appMock: new EventEmitter(), launchPolicy: { background: false, windowless: true } } +}) +vi.mock('electron', () => ({ app: appMock })) +vi.mock('../activation/foreground-activation-policy', () => ({ + isBackgroundLaunch: () => launchPolicy.background, + isWindowlessLaunch: () => launchPolicy.windowless, + showWindowWithoutStealingFocus: vi.fn() +})) +vi.mock('./main-window-visual-lifecycle', () => ({ + MIN_WIDTH: 480, + MIN_HEIGHT: 360, + syncTrafficLightPosition: vi.fn() +})) + +import { installMainWindowStateLifecycle } from './main-window-state-lifecycle' + +beforeEach(() => { + vi.useFakeTimers() + appMock.removeAllListeners() + launchPolicy.background = false + launchPolicy.windowless = true +}) +afterEach(() => vi.useRealTimers()) + +it('continues saving bounds after an updater quit veto and freezes them on allowed quit', async () => { + const mainWindow = Object.assign(new EventEmitter(), { + webContents: Object.assign(new EventEmitter(), { + send: vi.fn(), + setZoomLevel: vi.fn() + }), + isDestroyed: () => false, + isFullScreen: () => false, + isMaximized: () => false, + getBounds: () => ({ x: 0, y: 0, width: 1200, height: 800 }) + }) + const updateUI = vi.fn() + const lifecycle = installMainWindowStateLifecycle({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture implements the window members read by the bounds lifecycle. + mainWindow: mainWindow as never, + revealOnDidFinishLoad: false, + savedMaximized: false, + savedFullScreen: false, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Bounds persistence reads only updateUI from this store fixture. + store: { updateUI } as never + }) + appMock.emit('before-quit', { defaultPrevented: true }) + expect(lifecycle.isWindowClosing()).toBe(false) + mainWindow.emit('resize') + await vi.advanceTimersByTimeAsync(500) + expect(updateUI).toHaveBeenCalledWith({ + windowMaximized: false, + windowBounds: { x: 0, y: 0, width: 1200, height: 800 } + }) + + updateUI.mockClear() + appMock.emit('before-quit', { defaultPrevented: false }) + expect(lifecycle.isWindowClosing()).toBe(true) + mainWindow.emit('resize') + await vi.advanceTimersByTimeAsync(500) + expect(updateUI).not.toHaveBeenCalled() + lifecycle.clearInitialRevealFallbackTimer() + lifecycle.dispose() +}) diff --git a/src/main/window/main-window-state-lifecycle.ts b/src/main/window/main-window/main-window-state-lifecycle.ts similarity index 96% rename from src/main/window/main-window-state-lifecycle.ts rename to src/main/window/main-window/main-window-state-lifecycle.ts index d772aa78b5b..7e6db78021d 100644 --- a/src/main/window/main-window-state-lifecycle.ts +++ b/src/main/window/main-window/main-window-state-lifecycle.ts @@ -1,11 +1,11 @@ import { app, type BrowserWindow, type Event } from 'electron' -import type { Store } from '../persistence/loading-store/store' -import { uiZoomFactorFromLevel } from '../../shared/ui-zoom-level' +import type { Store } from '../../persistence/loading-store/store' +import { uiZoomFactorFromLevel } from '../../../shared/ui-zoom-level' import { isBackgroundLaunch, isWindowlessLaunch, showWindowWithoutStealingFocus -} from './foreground-activation-policy' +} from '../activation/foreground-activation-policy' import { MIN_HEIGHT, MIN_WIDTH, syncTrafficLightPosition } from './main-window-visual-lifecycle' export type MainWindowStateLifecycle = { diff --git a/src/main/window/main-window-visual-lifecycle.ts b/src/main/window/main-window/main-window-visual-lifecycle.ts similarity index 97% rename from src/main/window/main-window-visual-lifecycle.ts rename to src/main/window/main-window/main-window-visual-lifecycle.ts index a79ebdda1ca..8b5ee92bb21 100644 --- a/src/main/window/main-window-visual-lifecycle.ts +++ b/src/main/window/main-window/main-window-visual-lifecycle.ts @@ -1,5 +1,5 @@ import { ipcMain, type BrowserWindow } from 'electron' -import { isMacosTahoeOrNewer } from './macos-tahoe-release' +import { isMacosTahoeOrNewer } from '../desktop-integration/macos-tahoe-release' const activeRepaintJiggles = new WeakSet() export function forceRepaint(window: BrowserWindow): void { diff --git a/src/main/window/user-quit-window-close.ts b/src/main/window/main-window/user-quit-window-close.ts similarity index 100% rename from src/main/window/user-quit-window-close.ts rename to src/main/window/main-window/user-quit-window-close.ts diff --git a/src/main/window/window-close-decision.ts b/src/main/window/main-window/window-close-decision.ts similarity index 100% rename from src/main/window/window-close-decision.ts rename to src/main/window/main-window/window-close-decision.ts diff --git a/src/main/window/window-bounds-validation.ts b/src/main/window/presentation/window-bounds-validation.ts similarity index 100% rename from src/main/window/window-bounds-validation.ts rename to src/main/window/presentation/window-bounds-validation.ts diff --git a/src/main/window/window-material-options.ts b/src/main/window/presentation/window-material-options.ts similarity index 95% rename from src/main/window/window-material-options.ts rename to src/main/window/presentation/window-material-options.ts index f5856b6c231..9bf2d84454c 100644 --- a/src/main/window/window-material-options.ts +++ b/src/main/window/presentation/window-material-options.ts @@ -1,5 +1,5 @@ import type { BrowserWindowConstructorOptions } from 'electron' -import type { WindowMaterial } from '../../shared/window-material' +import type { WindowMaterial } from '../../../shared/window-material' type WindowMaterialOptions = Pick< BrowserWindowConstructorOptions, diff --git a/src/main/window/window-material-suppression.ts b/src/main/window/presentation/window-material-suppression.ts similarity index 91% rename from src/main/window/window-material-suppression.ts rename to src/main/window/presentation/window-material-suppression.ts index 16b2f4ab821..f0a9cc5d397 100644 --- a/src/main/window/window-material-suppression.ts +++ b/src/main/window/presentation/window-material-suppression.ts @@ -1,5 +1,5 @@ import type { BrowserWindow } from 'electron' -import type { WindowMaterial } from '../../shared/window-material' +import type { WindowMaterial } from '../../../shared/window-material' import { MAC_BLUR_VIBRANCY } from './window-material-options' const createdMaterials = new WeakMap() diff --git a/src/main/window/privileged-window-navigation.test.ts b/src/main/window/privileged-window-navigation.test.ts deleted file mode 100644 index a1e706bb699..00000000000 --- a/src/main/window/privileged-window-navigation.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const openExternal = vi.fn() -vi.mock('electron', () => ({ - shell: { openExternal: (url: string) => openExternal(url) } -})) - -import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' - -describe('privileged window navigation policy', () => { - function createFixture(currentUrl: string) { - const handlers = new Map void>() - const contents = { - getURL: () => currentUrl, - setWindowOpenHandler: vi.fn(), - on: vi.fn((event: string, handler: (...args: unknown[]) => void) => { - handlers.set(event, handler) - }) - } - installPrivilegedWindowNavigationPolicy(contents as never) - return { - willNavigate(url: string) { - const event = { preventDefault: vi.fn() } - const handler = handlers.get('will-navigate') - // Assert handler presence or missing navigation guards pass allow-cases vacuously. - if (!handler) { - throw new Error('no will-navigate handler was registered') - } - handler(event, url) - return event - } - } - } - - beforeEach(() => { - openExternal.mockClear() - }) - - it('lets the packaged renderer document reload itself', () => { - const appUrl = - 'file:///Applications/Orca.app/Contents/Resources/app.asar/out/renderer/index.html' - const event = createFixture(appUrl).willNavigate(appUrl) - - expect(event.preventDefault).not.toHaveBeenCalled() - expect(openExternal).not.toHaveBeenCalled() - }) - - it('still blocks and hands off an external http target', () => { - const appUrl = - 'file:///Applications/Orca.app/Contents/Resources/app.asar/out/renderer/index.html' - const event = createFixture(appUrl).willNavigate('https://example.com/') - - expect(event.preventDefault).toHaveBeenCalled() - expect(openExternal).toHaveBeenCalledWith('https://example.com/') - }) - - it('lets the dev renderer origin navigate but blocks foreign documents', () => { - const fixture = createFixture('http://localhost:5173/') - - expect( - fixture.willNavigate('http://localhost:5173/index.html').preventDefault - ).not.toHaveBeenCalled() - expect(fixture.willNavigate('https://example.com/').preventDefault).toHaveBeenCalled() - expect( - fixture.willNavigate('blob:http://localhost:5173/attacker-document').preventDefault - ).toHaveBeenCalled() - }) - - // The exact packaged file host/path defines privilege; foreign hosts and copied paths under other schemes must fail. - it('blocks a foreign file host and a data: URL that reuse the renderer path', () => { - const appUrl = - 'file:///Applications/Orca.app/Contents/Resources/app.asar/out/renderer/index.html' - const fixture = createFixture(appUrl) - - expect( - fixture.willNavigate( - 'file://evil.example/Applications/Orca.app/Contents/Resources/app.asar/out/renderer/index.html' - ).preventDefault - ).toHaveBeenCalled() - expect( - fixture.willNavigate('data:text/html,').preventDefault - ).toHaveBeenCalled() - expect(openExternal).not.toHaveBeenCalled() - }) - - it('still blocks navigation to an unrelated local file', () => { - const appUrl = - 'file:///Applications/Orca.app/Contents/Resources/app.asar/out/renderer/index.html' - const event = createFixture(appUrl).willNavigate('file:///Users/someone/.ssh/id_rsa') - - expect(event.preventDefault).toHaveBeenCalled() - expect(openExternal).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/window/project-move-pause.test.ts b/src/main/window/project-move-pause.test.ts deleted file mode 100644 index 6f4ab7941f7..00000000000 --- a/src/main/window/project-move-pause.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { EventEmitter } from 'node:events' -import { ipcMain as ipc, type BrowserWindow } from 'electron' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ProjectMovePauseRequest } from '../../shared/project-move-pause' -import type { WorkspaceSleepOutcome, WorkspaceSleepTarget } from '../../shared/workspace-sleep' - -type PauseResponseFixture = { requestId?: string; protocol?: number } & ( - | { phase: 'prepare'; targets: WorkspaceSleepTarget[] } - | { phase: 'persist' } - | { phase: 'error'; error: string } -) - -vi.mock('electron', async () => { - const { EventEmitter } = await import('node:events') - return { ipcMain: new EventEmitter() } -}) -import { pauseWorkspacesForProjectMove } from './project-move-pause' - -function fixture() { - const windowEvents = new EventEmitter() - const webContents = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - send: vi.fn<(channel: string, request: ProjectMovePauseRequest) => void>() - }) - const window = Object.assign(windowEvents, { isDestroyed: () => false, webContents }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the broker uses only the lifecycle and webContents members supplied here. - const mainWindow = window as unknown as BrowserWindow - const outcomes: WorkspaceSleepOutcome[] = [ - { - worktreeId: 'wt', - chatFailed: false, - receipts: [{ executionHostId: 'local', stoppedSessionIds: ['chat'] }] - } - ] - const sleepWorkspaces = vi.fn(async () => outcomes) - const request = (): ProjectMovePauseRequest => { - const value = webContents.send.mock.calls.at(-1)?.[1] - if (!value) { - throw new Error('no request') - } - return value - } - const respond = (value: PauseResponseFixture, sender: unknown = webContents): void => { - ipc.emit( - 'ui:projectMovePauseResponse', - { sender }, - { requestId: request().requestId, protocol: 1, ...value } - ) - } - const prepare = (): void => - respond({ - phase: 'prepare', - targets: [{ worktreeId: 'wt', terminalHost: { kind: 'self' }, chatHosts: [{ kind: 'self' }] }] - }) - return { window, mainWindow, webContents, sleepWorkspaces, outcomes, request, respond, prepare } -} - -describe('main-owned project move pause', () => { - beforeEach(() => { - vi.useFakeTimers() - ipc.removeAllListeners() - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('waits for an explicit renderer persistence receipt and preserves all stop receipts', async () => { - const f = fixture() - const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt', 'wt']) - f.prepare() - await vi.advanceTimersByTimeAsync(0) - expect(f.sleepWorkspaces).toHaveBeenCalledWith({ - targets: [ - { worktreeId: 'wt', terminalHost: { kind: 'self' }, chatHosts: [{ kind: 'self' }] } - ], - markChatsAsleep: false, - projectMovePauseId: expect.any(String) - }) - let returned = false - void paused.then(() => { - returned = true - }) - expect(f.request().phase).toBe('persist') - expect(returned).toBe(false) - f.respond({ phase: 'persist' }) - await expect(paused).resolves.toEqual(f.outcomes) - expect(f.request().phase).toBe('release') - expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(0) - expect(f.webContents.eventNames()).toEqual([]) - }) - - it('shares one lifecycle listener across overlapping pauses and releases it after', async () => { - const f = fixture() - const paused = Array.from({ length: 12 }, () => - pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) - ) - - expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(1) - expect(f.window.listenerCount('closed')).toBe(1) - for (const event of ['destroyed', 'render-process-gone', 'did-start-navigation']) { - expect(f.webContents.listenerCount(event)).toBe(1) - } - f.webContents.emit('render-process-gone') - - await Promise.all(paused.map((pause) => expect(pause).rejects.toThrow('renderer_unavailable'))) - expect(f.window.eventNames()).toEqual([]) - expect(f.webContents.eventNames()).toEqual([]) - expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(0) - }) - - it('does not stop hosts when an old preload or follower never answers the handshake', async () => { - const f = fixture() - const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) - const rejected = expect(paused).rejects.toThrow('renderer_timeout') - await vi.advanceTimersByTimeAsync(20_000) - await rejected - expect(f.sleepWorkspaces).not.toHaveBeenCalled() - expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(0) - }) - - it('ignores another window, stale request and unsupported protocol', async () => { - const f = fixture() - const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) - f.respond({ phase: 'prepare', targets: [] }, {}) - f.respond({ phase: 'prepare', targets: [], requestId: 'stale' }) - f.respond({ phase: 'prepare', targets: [], protocol: 0 }) - await vi.advanceTimersByTimeAsync(0) - expect(f.sleepWorkspaces).not.toHaveBeenCalled() - f.prepare() - await vi.advanceTimersByTimeAsync(0) - f.respond({ phase: 'persist' }) - await paused - }) - - it('rejects reload during the host stop instead of accepting a new renderer persistence reply', async () => { - const f = fixture() - const stop = Promise.withResolvers() - f.sleepWorkspaces.mockReturnValue(stop.promise) - const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) - f.prepare() - await vi.advanceTimersByTimeAsync(0) - f.webContents.emit('did-start-navigation', {}, 'about:blank', false, true) - stop.resolve(f.outcomes) - await expect(paused).rejects.toThrow('renderer_unavailable') - expect(f.webContents.send.mock.calls.map(([, value]) => value.phase)).toEqual(['prepare']) - }) - - it('propagates failed durability without returning success to the exporter', async () => { - const f = fixture() - const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) - f.prepare() - await vi.advanceTimersByTimeAsync(0) - f.respond({ phase: 'error', error: 'disk full' }) - await expect(paused).rejects.toMatchObject({ message: 'disk full', outcomes: f.outcomes }) - expect(f.request().phase).toBe('release') - }) - - it('retains partial stop failures and successful sibling receipts when renderer rollback fails', async () => { - const f = fixture() - f.outcomes[0].failure = 'terminal_liveness_unavailable' - f.outcomes.push({ - worktreeId: 'sibling', - chatFailed: false, - receipts: [{ executionHostId: 'runtime:env', stoppedSessionIds: ['remote-chat'] }] - }) - const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt', 'sibling']) - f.respond({ - phase: 'prepare', - targets: ['wt', 'sibling'].map((worktreeId) => ({ - worktreeId, - terminalHost: { kind: 'self' }, - chatHosts: [{ kind: 'self' }] - })) - }) - await vi.advanceTimersByTimeAsync(0) - f.respond({ phase: 'error', error: 'host_terminal_stop_failed' }) - await expect(paused).rejects.toMatchObject({ outcomes: f.outcomes }) - expect(f.outcomes[1]?.receipts[0]?.stoppedSessionIds).toEqual(['remote-chat']) - }) -}) diff --git a/src/main/window/renderer-document-navigation.test.ts b/src/main/window/renderer-document-navigation.test.ts deleted file mode 100644 index 8c5a9d5eb2a..00000000000 --- a/src/main/window/renderer-document-navigation.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { registerRendererDocumentNavigation } from './renderer-document-navigation' - -describe('renderer document navigation', () => { - function createFixture(currentUrl: string, onStarted = vi.fn(() => vi.fn())) { - const handlers = new Map void>() - let loadingMainFrame = false - const on = vi.fn((event: string, handler: (...args: unknown[]) => void) => { - handlers.set(event, handler) - }) - registerRendererDocumentNavigation( - { getURL: () => currentUrl, isLoadingMainFrame: () => loadingMainFrame, on } as never, - onStarted - ) - return { - navigate: handlers.get('did-start-navigation'), - failProvisionalLoad: handlers.get('did-fail-provisional-load'), - willNavigate: handlers.get('will-navigate'), - commitNavigation: handlers.get('did-frame-navigate'), - stopLoading: handlers.get('did-stop-loading'), - onStarted, - setLoadingMainFrame(value: boolean) { - loadingMainFrame = value - } - } - } - - it('shares one reload fence across concurrent provisional navigations', async () => { - const cancel = vi.fn() - const onStarted = vi.fn(() => cancel) - const fixture = createFixture('http://localhost:5173/', onStarted) - - fixture.navigate?.({}, 'http://localhost:5173/reload-a', false, true) - fixture.navigate?.({}, 'http://localhost:5173/reload-b', false, true) - - expect(onStarted).toHaveBeenCalledOnce() - fixture.setLoadingMainFrame(true) - fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload-a', true, 1, 1) - await Promise.resolve() - expect(cancel).not.toHaveBeenCalled() - fixture.setLoadingMainFrame(false) - fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload-b', true, 1, 1) - await Promise.resolve() - expect(cancel).toHaveBeenCalledOnce() - }) - - it('restores an idle surviving document after loading stops', async () => { - const cancel = vi.fn() - const fixture = createFixture( - 'http://localhost:5173/', - vi.fn(() => cancel) - ) - - fixture.navigate?.({}, 'http://localhost:5173/reload', false, true) - fixture.setLoadingMainFrame(true) - fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload', true, 1, 1) - await Promise.resolve() - expect(cancel).not.toHaveBeenCalled() - - fixture.setLoadingMainFrame(false) - fixture.stopLoading?.() - expect(cancel).toHaveBeenCalledOnce() - }) - - it('restores after a concurrent failure and blocked replacement both settle', async () => { - const cancel = vi.fn() - const fixture = createFixture( - 'http://localhost:5173/', - vi.fn(() => cancel) - ) - const event = { defaultPrevented: false } - - fixture.navigate?.({}, 'http://localhost:5173/reload-a', false, true) - fixture.navigate?.({}, 'http://localhost:5173/reload-b', false, true) - fixture.setLoadingMainFrame(true) - fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload-a', true) - await Promise.resolve() - expect(cancel).not.toHaveBeenCalled() - - fixture.willNavigate?.(event, 'http://localhost:5173/reload-b', false, true) - event.defaultPrevented = true - fixture.setLoadingMainFrame(false) - await Promise.resolve() - - expect(cancel).toHaveBeenCalledOnce() - }) - - it('does not let a stale same-URL failure cancel a replacement navigation', async () => { - const cancels: ReturnType[] = [] - const fixture = createFixture( - 'http://localhost:5173/', - vi.fn(() => { - const cancel = vi.fn() - cancels.push(cancel) - return cancel - }) - ) - const url = 'http://localhost:5173/reload' - - fixture.navigate?.({}, url, false, true) - fixture.commitNavigation?.({}, url, -1, '', true, 1, 1) - fixture.navigate?.({}, url, false, true) - fixture.setLoadingMainFrame(true) - fixture.failProvisionalLoad?.({}, -3, 'aborted', url, true, 1, 1) - await Promise.resolve() - - expect(cancels).toHaveLength(2) - expect(cancels[1]).not.toHaveBeenCalled() - - fixture.setLoadingMainFrame(false) - fixture.failProvisionalLoad?.({}, -3, 'aborted', url, true, 1, 1) - await Promise.resolve() - expect(cancels[1]).toHaveBeenCalledOnce() - }) - - it('cancels when a later will-navigate listener blocks the navigation', async () => { - const cancel = vi.fn() - const fixture = createFixture( - 'http://localhost:5173/', - vi.fn(() => cancel) - ) - const event = { defaultPrevented: false } - - fixture.navigate?.({}, 'http://localhost:5173/reload', false, true) - fixture.willNavigate?.(event, 'http://localhost:5173/reload', false, true, 1, 1) - event.defaultPrevented = true - await Promise.resolve() - - expect(cancel).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/window/renderer-launch-failure-probe.test.ts b/src/main/window/renderer-launch-failure-probe.test.ts deleted file mode 100644 index f762eac4d86..00000000000 --- a/src/main/window/renderer-launch-failure-probe.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { runProcessMock, recordDurableCrashBreadcrumbMock } = vi.hoisted(() => ({ - runProcessMock: vi.fn(), - recordDurableCrashBreadcrumbMock: vi.fn() -})) -vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: recordDurableCrashBreadcrumbMock -})) - -import { withPlatform } from './createMainWindow-test-harness' - -import { - probeRendererLaunchCapacity, - recordRendererLaunchFailureProbe -} from './renderer-launch-failure-probe' - -function spawnError(code: string): Error { - return Object.assign(new Error(`spawn /bin/sh ${code}`), { code, errno: -35, syscall: 'spawn' }) -} - -function recordPosixFailure(now: number) { - return withPlatform('darwin', () => recordRendererLaunchFailureProbe({ exitCode: 1003 }, now)) -} - -describe('probeRendererLaunchCapacity', () => { - afterEach(() => { - runProcessMock.mockReset() - recordDurableCrashBreadcrumbMock.mockReset() - }) - - it('reports ok for any child that started, whatever its exit', async () => { - runProcessMock.mockResolvedValue({ - code: 1, - signal: null, - stdout: '', - stderr: '', - timedOut: false - }) - await expect(probeRendererLaunchCapacity('darwin')).resolves.toBe('ok') - expect(runProcessMock).toHaveBeenCalledWith( - expect.objectContaining({ program: '/bin/sh', args: ['-c', 'exit 0'] }) - ) - }) - - // Windows EDR scores a short-lived child per operation; the breadcrumb still records the launch failure. - it('skips the spawn on Windows', async () => { - await expect(probeRendererLaunchCapacity('win32')).resolves.toBe('skipped') - expect(runProcessMock).not.toHaveBeenCalled() - }) - - it('records a skipped Windows probe without spawning a child', async () => { - await expect( - withPlatform('win32', () => recordRendererLaunchFailureProbe({ exitCode: 18 }, 100_000)) - ).resolves.toBe('skipped') - expect(runProcessMock).not.toHaveBeenCalled() - expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledWith('renderer_launch_failed_probe', { - spawnError: 'skipped', - exitCode: 18 - }) - }) - - it('never rejects when the breadcrumb write throws', async () => { - runProcessMock.mockRejectedValue(spawnError('EAGAIN')) - recordDurableCrashBreadcrumbMock.mockImplementation(() => { - throw new Error('disk full') - }) - await expect(recordPosixFailure(90_000)).resolves.toBe('EAGAIN') - }) - - it('records the refused spawn as a durable breadcrumb', async () => { - runProcessMock.mockRejectedValue(spawnError('EAGAIN')) - await expect(recordPosixFailure(10_000)).resolves.toBe('EAGAIN') - expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledWith('renderer_launch_failed_probe', { - spawnError: 'EAGAIN', - exitCode: 1003 - }) - }) - - it('probes once for the duplicate render-process-gone of one failed launch', async () => { - runProcessMock.mockRejectedValue(spawnError('EAGAIN')) - await recordPosixFailure(50_000) - await recordPosixFailure(50_010) - expect(runProcessMock).toHaveBeenCalledOnce() - expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledOnce() - - // The next backoff retry fails again: a fresh probe and breadcrumb. - await recordPosixFailure(50_250) - expect(runProcessMock).toHaveBeenCalledTimes(2) - expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/window/renderer-recovery-reload-watchdog.test.ts b/src/main/window/renderer-recovery-reload-watchdog.test.ts deleted file mode 100644 index 9148ab5a326..00000000000 --- a/src/main/window/renderer-recovery-reload-watchdog.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { BrowserWindow } from 'electron' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { MainWindowLoadObserver } from './main-window-contracts' -import { - createRendererRecoveryReloadWatchdog, - RENDERER_RECOVERY_LOAD_TIMEOUT_MS -} from './renderer-recovery-reload-watchdog' - -vi.mock('electron', () => ({ app: { isPackaged: true } })) - -function createHarness() { - const webContents = Object.assign(new EventEmitter(), { id: 143 }) - const mainWindow = { webContents, isDestroyed: () => false } as unknown as BrowserWindow - const loads: MainWindowLoadObserver[] = [] - const onRecoveryReloadOutcome = vi.fn() - const onRendererRecoveryExhausted = vi.fn() - const watchdog = createRendererRecoveryReloadWatchdog({ - mainWindow, - rendererWebContentsId: webContents.id, - isRecoveryPending: () => false, - isWindowClosing: () => false, - reloadMainWindow: (observer) => loads.push(observer), - opts: { onRecoveryReloadOutcome, onRendererRecoveryExhausted } - }) - const abortLatestLoad = () => loads.at(-1)?.onError?.(new Error('ERR_ABORTED (-3)')) - watchdog.issue({ reason: 'crashed', exitCode: 5 }, 1) - return { - watchdog, - webContents, - loads, - abortLatestLoad, - onRecoveryReloadOutcome, - onRendererRecoveryExhausted - } -} - -describe('superseding recovery navigations', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('removes listeners and the pending stall timer during teardown', () => { - const { watchdog, webContents, loads, onRecoveryReloadOutcome } = createHarness() - expect(webContents.eventNames().sort()).toEqual(['did-fail-load', 'did-navigate', 'dom-ready']) - expect(vi.getTimerCount()).toBe(1) - watchdog.clear() - expect(webContents.eventNames()).toEqual([]) - expect(vi.getTimerCount()).toBe(0) - loads[0]?.onLoaded?.() - loads[0]?.onError?.(new Error('ERR_FILE_NOT_FOUND')) - watchdog.notifySystemResume() - expect(onRecoveryReloadOutcome).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - }) - - it('does not mistake a replacement error page for recovery', () => { - const { - watchdog, - webContents, - abortLatestLoad, - onRecoveryReloadOutcome, - onRendererRecoveryExhausted - } = createHarness() - abortLatestLoad() - webContents.emit('did-navigate') - webContents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///missing', true) - watchdog.notifyDocumentLoaded() - - expect(onRecoveryReloadOutcome).not.toHaveBeenCalledWith( - expect.objectContaining({ status: 'loaded' }) - ) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - expect(onRecoveryReloadOutcome).toHaveBeenCalledWith( - expect.objectContaining({ status: 'failed', errorCode: 'ERR_FILE_NOT_FOUND' }) - ) - watchdog.clear() - }) - - it('ignores subframe failures and aborted replacement navigations', () => { - const { watchdog, webContents, abortLatestLoad, onRecoveryReloadOutcome } = createHarness() - abortLatestLoad() - webContents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///missing', false) - webContents.emit('did-fail-load', {}, -3, 'ERR_ABORTED', 'file:///previous', true) - watchdog.notifyDocumentLoaded() - expect(onRecoveryReloadOutcome).toHaveBeenCalledWith( - expect.objectContaining({ status: 'loaded', superseded: true }) - ) - watchdog.clear() - }) - - it('keeps Reload available if the replacement fails beneath an existing prompt', () => { - const { - watchdog, - webContents, - loads, - abortLatestLoad, - onRecoveryReloadOutcome, - onRendererRecoveryExhausted - } = createHarness() - abortLatestLoad() - webContents.emit('did-navigate') - vi.advanceTimersByTime(RENDERER_RECOVERY_LOAD_TIMEOUT_MS * 2) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - webContents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///missing', true) - watchdog.notifyDocumentLoaded() - expect(onRecoveryReloadOutcome).not.toHaveBeenCalledWith( - expect.objectContaining({ status: 'loaded' }) - ) - onRendererRecoveryExhausted.mock.calls[0]?.[0].retry() - expect(loads).toHaveLength(2) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - watchdog.clear() - }) - - it('recognizes a successful replacement started after the stall prompt', () => { - const { - watchdog, - loads, - abortLatestLoad, - onRecoveryReloadOutcome, - onRendererRecoveryExhausted - } = createHarness() - vi.advanceTimersByTime(RENDERER_RECOVERY_LOAD_TIMEOUT_MS * 2) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - abortLatestLoad() - watchdog.notifyDocumentLoaded() - expect(onRecoveryReloadOutcome).toHaveBeenCalledWith( - expect.objectContaining({ status: 'loaded', superseded: true, afterPrompt: true }) - ) - onRendererRecoveryExhausted.mock.calls[0]?.[0].retry() - expect(loads).toHaveLength(2) - vi.advanceTimersByTime(RENDERER_RECOVERY_LOAD_TIMEOUT_MS * 2) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - watchdog.clear() - }) -}) diff --git a/src/main/window/main-window-load-error-code.ts b/src/main/window/renderer-recovery/main-window-load-error-code.ts similarity index 100% rename from src/main/window/main-window-load-error-code.ts rename to src/main/window/renderer-recovery/main-window-load-error-code.ts diff --git a/src/main/window/renderer-launch-failure-backoff.ts b/src/main/window/renderer-recovery/renderer-launch-failure-backoff.ts similarity index 100% rename from src/main/window/renderer-launch-failure-backoff.ts rename to src/main/window/renderer-recovery/renderer-launch-failure-backoff.ts diff --git a/src/main/window/renderer-recovery/renderer-launch-failure-probe.test.ts b/src/main/window/renderer-recovery/renderer-launch-failure-probe.test.ts new file mode 100644 index 00000000000..18253cdfd15 --- /dev/null +++ b/src/main/window/renderer-recovery/renderer-launch-failure-probe.test.ts @@ -0,0 +1,68 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { runProcessMock, recordDurableCrashBreadcrumbMock } = vi.hoisted(() => ({ + runProcessMock: vi.fn(), + recordDurableCrashBreadcrumbMock: vi.fn() +})) +vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) +vi.mock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ + recordDurableCrashBreadcrumb: recordDurableCrashBreadcrumbMock +})) + +function withPlatform(platform: NodeJS.Platform, run: () => T): T { + const original = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + try { + return run() + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: original }) + } +} + +import { + probeRendererLaunchCapacity, + recordRendererLaunchFailureProbe +} from './renderer-launch-failure-probe' + +function spawnError(code: string): Error { + return Object.assign(new Error(`spawn /bin/sh ${code}`), { code, errno: -35, syscall: 'spawn' }) +} + +function recordPosixFailure(now: number) { + return withPlatform('darwin', () => recordRendererLaunchFailureProbe({ exitCode: 1003 }, now)) +} + +describe('probeRendererLaunchCapacity', () => { + afterEach(() => { + runProcessMock.mockReset() + recordDurableCrashBreadcrumbMock.mockReset() + }) + + it('reports ok for any child that started, whatever its exit', async () => { + runProcessMock.mockResolvedValue({ + code: 1, + signal: null, + stdout: '', + stderr: '', + timedOut: false + }) + await expect(probeRendererLaunchCapacity('darwin')).resolves.toBe('ok') + expect(runProcessMock).toHaveBeenCalledWith( + expect.objectContaining({ program: '/bin/sh', args: ['-c', 'exit 0'] }) + ) + }) + + // Windows EDR scores a short-lived child per operation; the breadcrumb still records the launch failure. + it('skips the spawn on Windows', async () => { + await expect(probeRendererLaunchCapacity('win32')).resolves.toBe('skipped') + expect(runProcessMock).not.toHaveBeenCalled() + }) + + it('never rejects when the breadcrumb write throws', async () => { + runProcessMock.mockRejectedValue(spawnError('EAGAIN')) + recordDurableCrashBreadcrumbMock.mockImplementation(() => { + throw new Error('disk full') + }) + await expect(recordPosixFailure(90_000)).resolves.toBe('EAGAIN') + }) +}) diff --git a/src/main/window/renderer-launch-failure-probe.ts b/src/main/window/renderer-recovery/renderer-launch-failure-probe.ts similarity index 92% rename from src/main/window/renderer-launch-failure-probe.ts rename to src/main/window/renderer-recovery/renderer-launch-failure-probe.ts index 9127b53da17..43ae8dec045 100644 --- a/src/main/window/renderer-launch-failure-probe.ts +++ b/src/main/window/renderer-recovery/renderer-launch-failure-probe.ts @@ -1,6 +1,6 @@ import { runProcess } from '@orca/process-host' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' -import { errnoCodeOrUnknown } from '../../shared/errno-code' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { errnoCodeOrUnknown } from '../../../shared/errno-code' /** 'ok' when a throwaway child could start, the spawn errno (EAGAIN = per-user process limit), or 'skipped' on Windows. */ export type RendererLaunchProbeResult = string diff --git a/src/main/window/renderer-liveness-at-death.test.ts b/src/main/window/renderer-recovery/renderer-liveness-at-death.test.ts similarity index 87% rename from src/main/window/renderer-liveness-at-death.test.ts rename to src/main/window/renderer-recovery/renderer-liveness-at-death.test.ts index 58d2ed252a2..90d4d0b74b0 100644 --- a/src/main/window/renderer-liveness-at-death.test.ts +++ b/src/main/window/renderer-recovery/renderer-liveness-at-death.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' const recordCoalescedDurableCrashBreadcrumb = vi.fn() -vi.mock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ +vi.mock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordCoalescedDurableCrashBreadcrumb: (...args: unknown[]) => recordCoalescedDurableCrashBreadcrumb(...args) })) @@ -97,18 +97,4 @@ describe('trackRendererLivenessAtDeath', () => { expect(state).toMatchObject({ rendererDocumentLoaded: true, rendererDocumentAgeMs: 5_000 }) expect(state.rendererDocumentLoadFailed).toBeUndefined() }) - - it('does not log the replacement renderer as the dead one recovering', () => { - const { window, contents } = createWindow() - const tracker = trackRendererLivenessAtDeath(window, () => now) - contents.emit('did-finish-load') - window.emit('unresponsive') - now += 20_000 - expect(tracker.takeAtRendererGone().rendererUnresponsiveForMs).toBe(20_000) - recordCoalescedDurableCrashBreadcrumb.mockClear() - - window.emit('responsive') - - expect(recordCoalescedDurableCrashBreadcrumb).not.toHaveBeenCalled() - }) }) diff --git a/src/main/window/renderer-liveness-at-death.ts b/src/main/window/renderer-recovery/renderer-liveness-at-death.ts similarity index 85% rename from src/main/window/renderer-liveness-at-death.ts rename to src/main/window/renderer-recovery/renderer-liveness-at-death.ts index cd2bf0c9e73..2c30f95a463 100644 --- a/src/main/window/renderer-liveness-at-death.ts +++ b/src/main/window/renderer-recovery/renderer-liveness-at-death.ts @@ -1,5 +1,5 @@ import type { BrowserWindow } from 'electron' -import { recordCoalescedDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { recordCoalescedDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' /** Windows killed/exit1 cannot identify Task Manager, EDR or Orca as the cause. Retain prior hang/load state to distinguish users terminating a frozen app from unexplained external kills. */ export type RendererLivenessAtDeath = { @@ -34,8 +34,25 @@ export function trackRendererLivenessAtDeath( let documentLoaded = false let documentLoadFailed = false let documentStartedAt = now() + let captureEpoch = 0 + let capture: { stop: () => void } | null = null + const stopCapture = (): void => { + captureEpoch++ + capture?.stop() + capture = null + } const onUnresponsive = (): void => { + if (unresponsiveSince === null) { + const epoch = ++captureEpoch + void import('../../hang-watchdog/renderer-hang-capture') + .then((collector) => { + if (epoch === captureEpoch && unresponsiveSince !== null && !window.isDestroyed()) { + capture = collector.startRendererHangCapture(window) + } + }) + .catch(() => {}) + } unresponsiveSince ??= now() recordCoalescedDurableCrashBreadcrumb({ name: 'renderer_unresponsive', @@ -48,6 +65,7 @@ export function trackRendererLivenessAtDeath( return } const hungForMs = now() - unresponsiveSince + stopCapture() unresponsiveSince = null recordCoalescedDurableCrashBreadcrumb({ name: 'renderer_responsive', @@ -67,6 +85,7 @@ export function trackRendererLivenessAtDeath( } unresponsiveSince = null documentLoaded = false + stopCapture() documentLoadFailed = false documentStartedAt = now() } @@ -90,9 +109,11 @@ export function trackRendererLivenessAtDeath( contents.on('did-start-navigation', onNavigationStart) contents.on('did-fail-load', onLoadFailed) contents.on('did-finish-load', onLoaded) + contents.on('destroyed', stopCapture) return { takeAtRendererGone: () => { + stopCapture() const at = now() const state: RendererLivenessAtDeath = { ...(unresponsiveSince === null diff --git a/src/main/window/renderer-recovery-prompt.ts b/src/main/window/renderer-recovery/renderer-recovery-prompt.ts similarity index 97% rename from src/main/window/renderer-recovery-prompt.ts rename to src/main/window/renderer-recovery/renderer-recovery-prompt.ts index a55ad7789ec..17e12b73280 100644 --- a/src/main/window/renderer-recovery-prompt.ts +++ b/src/main/window/renderer-recovery/renderer-recovery-prompt.ts @@ -1,6 +1,6 @@ import type { MessageBoxOptions, MessageBoxReturnValue } from 'electron' -import { translateMain } from '../i18n/main-i18n' -import type { InstallDirAclPoisonDiagnosis } from '../startup/windows-install-dir-acl-recovery' +import { translateMain } from '../../i18n/main-i18n' +import type { InstallDirAclPoisonDiagnosis } from '../../startup/windows-install-permissions/windows-install-dir-acl-recovery' import type { RecoveryExhaustionCause } from './renderer-recovery-reload-watchdog' import type { RendererLaunchProbeResult } from './renderer-launch-failure-probe' diff --git a/src/main/window/renderer-recovery-reload-watchdog.ts b/src/main/window/renderer-recovery/renderer-recovery-reload-watchdog.ts similarity index 97% rename from src/main/window/renderer-recovery-reload-watchdog.ts rename to src/main/window/renderer-recovery/renderer-recovery-reload-watchdog.ts index e86d18fae6d..872dd815fc2 100644 --- a/src/main/window/renderer-recovery-reload-watchdog.ts +++ b/src/main/window/renderer-recovery/renderer-recovery-reload-watchdog.ts @@ -1,8 +1,11 @@ import { app, type BrowserWindow } from 'electron' -import { isSystemSessionEnding } from '../crash-reporting/process-exits/expected-teardown-state' -import type { LowCommitOomVerdict } from '../crash-reporting/recovery/low-commit-oom-recovery-gate' -import type { CreateMainWindowOptions, MainWindowLoadObserver } from './main-window-contracts' +import { isSystemSessionEnding } from '../../crash-reporting/process-exits/expected-teardown-state' +import type { LowCommitOomVerdict } from '../../crash-reporting/recovery/low-commit-oom-recovery-gate' +import type { + CreateMainWindowOptions, + MainWindowLoadObserver +} from '../main-window/main-window-contracts' import { mainWindowLoadErrorCode } from './main-window-load-error-code' // Field recoveries took up to 30.4s; allow 45s before retrying a load with no document. diff --git a/src/main/window/agent-launch-tab-publish-relay.ts b/src/main/window/renderer-relays/agent-launch-tab-publish-relay.ts similarity index 96% rename from src/main/window/agent-launch-tab-publish-relay.ts rename to src/main/window/renderer-relays/agent-launch-tab-publish-relay.ts index 753b712c273..547e02b7d80 100644 --- a/src/main/window/agent-launch-tab-publish-relay.ts +++ b/src/main/window/renderer-relays/agent-launch-tab-publish-relay.ts @@ -6,7 +6,7 @@ import type { AgentLaunchTabPublished, AgentLaunchTabPublishReply, AgentLaunchTabPublishRequest -} from '../../shared/agent-launch/contracts/agent-launch-tab-publication' +} from '../../../shared/agent-launch/contracts/agent-launch-tab-publication' const AGENT_LAUNCH_TAB_PUBLISH_TIMEOUT_MS = 10_000 diff --git a/src/main/window/agent-pane-activity-relay.ts b/src/main/window/renderer-relays/agent-pane-activity-relay.ts similarity index 93% rename from src/main/window/agent-pane-activity-relay.ts rename to src/main/window/renderer-relays/agent-pane-activity-relay.ts index a8c33e8231d..92c445e1d87 100644 --- a/src/main/window/agent-pane-activity-relay.ts +++ b/src/main/window/renderer-relays/agent-pane-activity-relay.ts @@ -4,7 +4,7 @@ import type { AgentListPublication, AgentPaneActivityChange, AgentPaneActivityReply -} from '../../shared/agent-status/presentation/agent-list-status' +} from '../../../shared/agent-status/presentation/agent-list-status' import { requestRendererReply } from './renderer-reply-request' // Under the client's call timeout, so the client hears a refusal rather than losing the reply. diff --git a/src/main/window/renderer-relays/project-move-pause.test.ts b/src/main/window/renderer-relays/project-move-pause.test.ts new file mode 100644 index 00000000000..0c6407f792d --- /dev/null +++ b/src/main/window/renderer-relays/project-move-pause.test.ts @@ -0,0 +1,108 @@ +import { EventEmitter } from 'node:events' +import { ipcMain as ipc, type BrowserWindow } from 'electron' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ProjectMovePauseRequest } from '../../../shared/project-move-pause' +import type { WorkspaceSleepOutcome, WorkspaceSleepTarget } from '../../../shared/workspace-sleep' + +type PauseResponseFixture = { requestId?: string; protocol?: number } & ( + | { phase: 'prepare'; targets: WorkspaceSleepTarget[] } + | { phase: 'persist' } + | { phase: 'error'; error: string } +) + +vi.mock('electron', async () => { + const { EventEmitter } = await import('node:events') + return { ipcMain: new EventEmitter() } +}) +import { pauseWorkspacesForProjectMove } from './project-move-pause' + +function fixture() { + const windowEvents = new EventEmitter() + const webContents = Object.assign(new EventEmitter(), { + isDestroyed: () => false, + send: vi.fn<(channel: string, request: ProjectMovePauseRequest) => void>() + }) + const window = Object.assign(windowEvents, { isDestroyed: () => false, webContents }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the broker uses only the lifecycle and webContents members supplied here. + const mainWindow = window as unknown as BrowserWindow + const outcomes: WorkspaceSleepOutcome[] = [ + { + worktreeId: 'wt', + chatFailed: false, + receipts: [{ executionHostId: 'local', stoppedSessionIds: ['chat'] }] + } + ] + const sleepWorkspaces = vi.fn(async () => outcomes) + const request = (): ProjectMovePauseRequest => { + const value = webContents.send.mock.calls.at(-1)?.[1] + if (!value) { + throw new Error('no request') + } + return value + } + const respond = (value: PauseResponseFixture, sender: unknown = webContents): void => { + ipc.emit( + 'ui:projectMovePauseResponse', + { sender }, + { requestId: request().requestId, protocol: 1, ...value } + ) + } + const prepare = (): void => + respond({ + phase: 'prepare', + targets: [{ worktreeId: 'wt', terminalHost: { kind: 'self' }, chatHosts: [{ kind: 'self' }] }] + }) + return { window, mainWindow, webContents, sleepWorkspaces, outcomes, request, respond, prepare } +} + +describe('main-owned project move pause', () => { + beforeEach(() => { + vi.useFakeTimers() + ipc.removeAllListeners() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('shares one lifecycle listener across overlapping pauses and releases it after', async () => { + const f = fixture() + const paused = Array.from({ length: 12 }, () => + pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) + ) + + expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(1) + expect(f.window.listenerCount('closed')).toBe(1) + for (const event of ['destroyed', 'render-process-gone', 'did-start-navigation']) { + expect(f.webContents.listenerCount(event)).toBe(1) + } + f.webContents.emit('render-process-gone') + + await Promise.all(paused.map((pause) => expect(pause).rejects.toThrow('renderer_unavailable'))) + expect(f.window.eventNames()).toEqual([]) + expect(f.webContents.eventNames()).toEqual([]) + expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(0) + }) + + it('does not stop hosts when an old preload or follower never answers the handshake', async () => { + const f = fixture() + const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) + const rejected = expect(paused).rejects.toThrow('renderer_timeout') + await vi.advanceTimersByTimeAsync(20_000) + await rejected + expect(f.sleepWorkspaces).not.toHaveBeenCalled() + expect(ipc.listenerCount('ui:projectMovePauseResponse')).toBe(0) + }) + + it('rejects reload during the host stop instead of accepting a new renderer persistence reply', async () => { + const f = fixture() + const stop = Promise.withResolvers() + f.sleepWorkspaces.mockReturnValue(stop.promise) + const paused = pauseWorkspacesForProjectMove(f.mainWindow, f, ['wt']) + f.prepare() + await vi.advanceTimersByTimeAsync(0) + f.webContents.emit('did-start-navigation', {}, 'about:blank', false, true) + stop.resolve(f.outcomes) + await expect(paused).rejects.toThrow('renderer_unavailable') + expect(f.webContents.send.mock.calls.map(([, value]) => value.phase)).toEqual(['prepare']) + }) +}) diff --git a/src/main/window/project-move-pause.ts b/src/main/window/renderer-relays/project-move-pause.ts similarity index 96% rename from src/main/window/project-move-pause.ts rename to src/main/window/renderer-relays/project-move-pause.ts index 76121bdcf7d..81c3551bc2c 100644 --- a/src/main/window/project-move-pause.ts +++ b/src/main/window/renderer-relays/project-move-pause.ts @@ -5,9 +5,9 @@ import { projectMovePauseResponseSchema, type ProjectMovePauseRequest, type ProjectMovePauseResponse -} from '../../shared/project-move-pause' -import type { WorkspaceSleepOutcome, WorkspaceSleepRequest } from '../../shared/workspace-sleep' -import { addFanoutListener, addFanoutListeners } from '../runtime/events/event-listener-fanout' +} from '../../../shared/project-move-pause' +import type { WorkspaceSleepOutcome, WorkspaceSleepRequest } from '../../../shared/workspace-sleep' +import { addFanoutListener, addFanoutListeners } from '../../runtime/events/event-listener-fanout' type SleepRuntime = { sleepWorkspaces: (request: WorkspaceSleepRequest) => Promise diff --git a/src/main/window/renderer-reply-request.ts b/src/main/window/renderer-relays/renderer-reply-request.ts similarity index 93% rename from src/main/window/renderer-reply-request.ts rename to src/main/window/renderer-relays/renderer-reply-request.ts index 80582d8b885..ec2ae0b57f9 100644 --- a/src/main/window/renderer-reply-request.ts +++ b/src/main/window/renderer-relays/renderer-reply-request.ts @@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto' import { ipcMain, type BrowserWindow } from 'electron' -import { addFanoutListener } from '../runtime/events/event-listener-fanout' -import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' +import { addFanoutListener } from '../../runtime/events/event-listener-fanout' +import { abortWhenRendererGone } from '../../ipc/renderer-lifetime-abort' /** Sends one request to the window and resolves with the reply its own renderer sends; rejects when it goes away or times out. */ export function requestRendererReply( diff --git a/src/main/window/runtime-renderer-notification-sender.test.ts b/src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts similarity index 83% rename from src/main/window/runtime-renderer-notification-sender.test.ts rename to src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts index d482bb404fb..5ae840abb4d 100644 --- a/src/main/window/runtime-renderer-notification-sender.test.ts +++ b/src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts @@ -76,22 +76,6 @@ describe('runtime renderer notification sender', () => { expect(missingWebContents.onFailure).not.toHaveBeenCalled() }) - it('reports renderer process loss once per load generation', () => { - const fixture = createSender() - - fixture.sender.onRendererProcessGone() - fixture.sender.onRendererProcessGone() - fixture.sender.onMainFrameReloadStarted() - fixture.sender.onMainFrameLoadFinished() - fixture.sender.onRendererProcessGone() - fixture.sender.onRendererProcessGone() - - expect(fixture.warn).toHaveBeenCalledTimes(2) - expect(fixture.onFailure).toHaveBeenCalledTimes(2) - expect(fixture.onFailure).toHaveBeenNthCalledWith(1, 'renderer-process-gone') - expect(fixture.onFailure).toHaveBeenNthCalledWith(2, 'renderer-process-gone') - }) - it('keeps close terminal when renderer lifecycle events arrive late', () => { const fixture = createSender() diff --git a/src/main/window/runtime-renderer-notification-sender.ts b/src/main/window/renderer-relays/runtime-renderer-notification-sender.ts similarity index 100% rename from src/main/window/runtime-renderer-notification-sender.ts rename to src/main/window/renderer-relays/runtime-renderer-notification-sender.ts diff --git a/src/main/window/renderer-relays/session-tab-close-request-relay.test.ts b/src/main/window/renderer-relays/session-tab-close-request-relay.test.ts new file mode 100644 index 00000000000..62c6a9e939a --- /dev/null +++ b/src/main/window/renderer-relays/session-tab-close-request-relay.test.ts @@ -0,0 +1,109 @@ +import { EventEmitter } from 'node:events' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const ipcEmitter = new EventEmitter() +const ipcMainMock = { + on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { + ipcEmitter.on(channel, listener) + }), + removeListener: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { + ipcEmitter.removeListener(channel, listener) + }) +} + +vi.mock('electron', () => ({ ipcMain: ipcMainMock })) + +function createMainWindow() { + const webContents = Object.assign(new EventEmitter(), { + isDestroyed: () => false, + send: vi.fn() + }) + const mainWindow = Object.assign(new EventEmitter(), { + isDestroyed: () => false, + webContents + }) + return { mainWindow, webContents } +} + +describe('requestSessionTabCloseFromRenderer', () => { + beforeEach(() => { + vi.useRealTimers() + ipcEmitter.removeAllListeners() + ipcMainMock.on.mockClear() + ipcMainMock.removeListener.mockClear() + }) + + it('waits for the targeted renderer acknowledgement', async () => { + const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') + const { mainWindow, webContents } = createMainWindow() + const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') + const request = webContents.send.mock.calls[0]?.[1] as { + requestId: string + tabId: string + worktreeId: string + expiresAt: number + } + + expect(request).toMatchObject({ tabId: 'tab-1', worktreeId: 'wt-1' }) + expect(request.expiresAt).toBeGreaterThan(Date.now()) + ipcEmitter.emit('ui:sessionTabCloseResponse', { sender: {} }, { requestId: request.requestId }) + let settled = false + void pending.finally(() => { + settled = true + }) + await Promise.resolve() + expect(settled).toBe(false) + + ipcEmitter.emit( + 'ui:sessionTabCloseResponse', + { sender: webContents }, + { requestId: request.requestId } + ) + await expect(pending).resolves.toBeUndefined() + }) + + it('propagates renderer cancellation', async () => { + const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') + const { mainWindow, webContents } = createMainWindow() + const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-pinned', 'wt-1') + const request = webContents.send.mock.calls[0]?.[1] as { requestId: string } + + ipcEmitter.emit( + 'ui:sessionTabCloseResponse', + { sender: webContents }, + { requestId: request.requestId, error: 'session_tab_close_canceled' } + ) + + await expect(pending).rejects.toThrow('session_tab_close_canceled') + }) + + it.each(['destroyed', 'render-process-gone', 'did-start-loading'])( + 'rejects when web contents emits %s', + async (eventName) => { + const { requestSessionTabCloseFromRenderer } = + await import('./session-tab-close-request-relay') + const { mainWindow, webContents } = createMainWindow() + const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') + + webContents.emit(eventName) + + await expect(pending).rejects.toThrow('renderer_unavailable') + expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) + } + ) + + it('times out after the renderer confirmation lease and response grace', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') + const { mainWindow, webContents } = createMainWindow() + const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') + const request = webContents.send.mock.calls[0]?.[1] as { expiresAt: number } + const rejection = expect(pending).rejects.toThrow('session_tab_close_timeout') + + await vi.advanceTimersByTimeAsync(request.expiresAt - Date.now() + 5_000) + + await rejection + expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) + }) +}) diff --git a/src/main/window/session-tab-close-request-relay.ts b/src/main/window/renderer-relays/session-tab-close-request-relay.ts similarity index 90% rename from src/main/window/session-tab-close-request-relay.ts rename to src/main/window/renderer-relays/session-tab-close-request-relay.ts index e9564342bdc..7ee2fe87939 100644 --- a/src/main/window/session-tab-close-request-relay.ts +++ b/src/main/window/renderer-relays/session-tab-close-request-relay.ts @@ -5,9 +5,9 @@ import type { BrowserWindow } from 'electron' import type { SessionTabCloseRequest, SessionTabCloseResponse -} from '../../shared/session-tab-close' -import { SESSION_TAB_CLOSE_TIMEOUT_ERROR } from '../../shared/session-tab-close' -import { addFanoutListener, addFanoutListeners } from '../runtime/events/event-listener-fanout' +} from '../../../shared/session-tab-close' +import { SESSION_TAB_CLOSE_TIMEOUT_ERROR } from '../../../shared/session-tab-close' +import { addFanoutListener, addFanoutListeners } from '../../runtime/events/event-listener-fanout' const SESSION_TAB_CLOSE_CONFIRMATION_MS = 5 * 60_000 const SESSION_TAB_CLOSE_RESPONSE_GRACE_MS = 5_000 diff --git a/src/main/window/terminal-pane-move-commit-fence.ts b/src/main/window/renderer-relays/terminal-pane-move-commit-fence.ts similarity index 94% rename from src/main/window/terminal-pane-move-commit-fence.ts rename to src/main/window/renderer-relays/terminal-pane-move-commit-fence.ts index 2e671be6cd9..ed1d9990595 100644 --- a/src/main/window/terminal-pane-move-commit-fence.ts +++ b/src/main/window/renderer-relays/terminal-pane-move-commit-fence.ts @@ -1,4 +1,4 @@ -import type { TerminalLeafMoveResult } from '../../shared/workspace-layout/terminal-leaf-move' +import type { TerminalLeafMoveResult } from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' // Why its own module: the plain-Node runtime commits leaf moves too, so this must stay Electron-free. diff --git a/src/main/window/renderer-relays/terminal-pane-move-request-relay.test.ts b/src/main/window/renderer-relays/terminal-pane-move-request-relay.test.ts new file mode 100644 index 00000000000..f8c6ef346ca --- /dev/null +++ b/src/main/window/renderer-relays/terminal-pane-move-request-relay.test.ts @@ -0,0 +1,76 @@ +import { EventEmitter } from 'node:events' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { TerminalLeafMoveResult } from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' + +const ipcEmitter = new EventEmitter() +const ipcMainMock = { + on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { + ipcEmitter.on(channel, listener) + }), + removeListener: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { + ipcEmitter.removeListener(channel, listener) + }) +} + +vi.mock('electron', () => ({ ipcMain: ipcMainMock })) + +const move = { worktreeId: 'wt-1', sourceTabId: 'tab-1', targetTabId: 'tab-new', leafId: 'leaf-1' } + +function createMainWindow() { + const webContents = Object.assign(new EventEmitter(), { + id: 1, + isDestroyed: () => false, + send: vi.fn<(channel: string, request: { requestId: string }) => void>() + }) + const mainWindow = Object.assign(new EventEmitter(), { + isDestroyed: () => false, + webContents + }) + return { mainWindow, webContents } +} + +async function requestMove() { + const relay = { + ...(await import('./terminal-pane-move-request-relay')), + ...(await import('./terminal-pane-move-commit-fence')) + } + const { mainWindow, webContents } = createMainWindow() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the EventEmitter double implements the BrowserWindow members the relay uses. + const pending = relay.requestTerminalPaneMoveFromRenderer(mainWindow as never, move) + const request = webContents.send.mock.calls[0]![1] + const sender = webContents + const reply = (result: TerminalLeafMoveResult): void => { + ipcEmitter.emit( + 'ui:terminalPaneMoveToNewTabReply', + { sender: webContents }, + { requestId: request.requestId, result } + ) + } + return { relay, pending, sender, webContents, reply } +} + +describe('requestTerminalPaneMoveFromRenderer', () => { + beforeEach(() => { + vi.resetModules() + vi.useFakeTimers() + ipcEmitter.removeAllListeners() + }) + + it('commits nothing the window tries after the client was told the move timed out', async () => { + const { relay, pending, sender, reply } = await requestMove() + const timedOut = expect(pending).rejects.toThrow('terminal_pane_move_timeout') + await vi.advanceTimersByTimeAsync(10_000) + await timedOut + + const commit = vi.fn(async (): Promise => ({ + status: 'moved', + ptyId: 'pty-1' + })) + const late = await relay.commitRelayedPaneMove(sender, move.targetTabId, commit) + + expect(late).toEqual({ status: 'refused', reason: 'pane_unavailable' }) + expect(commit).not.toHaveBeenCalled() + reply({ status: 'refused', reason: 'pane_unavailable' }) + expect(ipcEmitter.listenerCount('ui:terminalPaneMoveToNewTabReply')).toBe(0) + }) +}) diff --git a/src/main/window/terminal-pane-move-request-relay.ts b/src/main/window/renderer-relays/terminal-pane-move-request-relay.ts similarity index 94% rename from src/main/window/terminal-pane-move-request-relay.ts rename to src/main/window/renderer-relays/terminal-pane-move-request-relay.ts index b43c5fa3145..869c08fea56 100644 --- a/src/main/window/terminal-pane-move-request-relay.ts +++ b/src/main/window/renderer-relays/terminal-pane-move-request-relay.ts @@ -6,9 +6,9 @@ import type { TerminalLeafMoveResult, TerminalPaneMoveToNewTabReply, TerminalPaneMoveToNewTabRequest -} from '../../shared/workspace-layout/terminal-leaf-move' -import { addFanoutListener } from '../runtime/events/event-listener-fanout' -import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' +} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' +import { addFanoutListener } from '../../runtime/events/event-listener-fanout' +import { abortWhenRendererGone } from '../../ipc/renderer-lifetime-abort' import { holdRelayedPaneMove, type RelayedPaneMove } from './terminal-pane-move-commit-fence' // Why: under the client's 15s call timeout, so the client hears a refusal rather than losing the reply. diff --git a/src/main/window/terminal-pane-reveal-relay.ts b/src/main/window/renderer-relays/terminal-pane-reveal-relay.ts similarity index 87% rename from src/main/window/terminal-pane-reveal-relay.ts rename to src/main/window/renderer-relays/terminal-pane-reveal-relay.ts index 837cc459556..4185c7dbda4 100644 --- a/src/main/window/terminal-pane-reveal-relay.ts +++ b/src/main/window/renderer-relays/terminal-pane-reveal-relay.ts @@ -3,8 +3,8 @@ import { app, type BrowserWindow } from 'electron' import type { TerminalPaneRevealReply, TerminalPaneRevealTarget -} from '../../shared/workspace-layout/terminal-pane-reveal' -import { focusExistingMainWindow } from './focus-existing-window' +} from '../../../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal' +import { focusExistingMainWindow } from '../activation/focus-existing-window' import { requestRendererReply } from './renderer-reply-request' const TERMINAL_PANE_REVEAL_TIMEOUT_MS = 10_000 diff --git a/src/main/window/terminal-tab-close-request-relay.test.ts b/src/main/window/renderer-relays/terminal-tab-close-request-relay.test.ts similarity index 100% rename from src/main/window/terminal-tab-close-request-relay.test.ts rename to src/main/window/renderer-relays/terminal-tab-close-request-relay.test.ts diff --git a/src/main/window/terminal-tab-close-request-relay.ts b/src/main/window/renderer-relays/terminal-tab-close-request-relay.ts similarity index 93% rename from src/main/window/terminal-tab-close-request-relay.ts rename to src/main/window/renderer-relays/terminal-tab-close-request-relay.ts index 734da561101..8af32bac09e 100644 --- a/src/main/window/terminal-tab-close-request-relay.ts +++ b/src/main/window/renderer-relays/terminal-tab-close-request-relay.ts @@ -5,8 +5,8 @@ import { ipcMain, type BrowserWindow } from 'electron' import type { TerminalTabCloseRequest, TerminalTabCloseResponse -} from '../../shared/workspace-layout/terminal-tab-close' -import { addFanoutListener, addFanoutListeners } from '../runtime/events/event-listener-fanout' +} from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-close' +import { addFanoutListener, addFanoutListeners } from '../../runtime/events/event-listener-fanout' const TERMINAL_TAB_CLOSE_TIMEOUT_MS = 20_000 diff --git a/src/main/window/resource-view-admission.ts b/src/main/window/resource-view-admission.ts deleted file mode 100644 index 8bec07bd3eb..00000000000 --- a/src/main/window/resource-view-admission.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { BrowserWindow, IpcMainInvokeEvent } from 'electron' -import { getRuntimeDesktopSurface } from '../runtime/construction/runtime-desktop-surface' -import type { ResourceViewAdmission } from '../../shared/resource-view-admission' - -export function isResourceWindowVisible(window: BrowserWindow | null): boolean { - return !!window && !window.isDestroyed() && window.isVisible() && !window.isMinimized() -} - -export function assertResourceViewVisible( - event: IpcMainInvokeEvent, - admission?: ResourceViewAdmission -): void { - if ( - admission?.resourceManagerView && - !getRuntimeDesktopSurface().isResourceViewVisible?.(event.sender) - ) { - throw new Error('view_not_visible') - } -} diff --git a/src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts b/src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts index 1675208addd..c3ace70cae0 100644 --- a/src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts +++ b/src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts @@ -11,7 +11,9 @@ vi.mock('electron', () => ({ ipcMain })) vi.mock('../ipc/worktrees/listing/worktree-change-invalidators', () => ({ runWorktreeChangeInvalidators: vi.fn() })) -vi.mock('./renderer-document-navigation', () => ({ registerRendererDocumentNavigation: vi.fn() })) +vi.mock('./security/renderer-document-navigation', () => ({ + registerRendererDocumentNavigation: vi.fn() +})) import { registerRuntimeWindowLifecycle } from './runtime-window-lifecycle' @@ -39,6 +41,7 @@ function attachWindow(id: number): { } const runtime = { attachWindow: vi.fn(), + onClientEvent: vi.fn(() => () => {}), markGraphReloadFailed: vi.fn(), setNotifier: (next: RuntimeNotifier | null) => { attached.notifier = next diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 96b3d4f769d..22c9b64e9ef 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -3,19 +3,19 @@ import { randomUUID } from 'node:crypto' import { ipcMain, type BrowserWindow } from 'electron' import type { CreateWorktreeResult } from '../../shared/worktree/create-types' -import type { WorktreeStartupLaunch } from '../../shared/worktree/launch-types' -import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-types' -import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' +import type { WorktreeStartupLaunch } from '../../shared/worktree/creation/launch-types' +import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-session-contracts' +import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-surfaces/terminal-reveal-identity' import { runWorktreeChangeInvalidators } from '../ipc/worktrees/listing/worktree-change-invalidators' -import { requestAgentLaunchTabPublishFromRenderer } from './agent-launch-tab-publish-relay' -import { requestAgentPaneActivityFromRenderer } from './agent-pane-activity-relay' +import { requestAgentLaunchTabPublishFromRenderer } from './renderer-relays/agent-launch-tab-publish-relay' +import { requestAgentPaneActivityFromRenderer } from './renderer-relays/agent-pane-activity-relay' import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { registerRendererDocumentNavigation } from './renderer-document-navigation' -import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' -import { requestSessionTabCloseFromRenderer } from './session-tab-close-request-relay' -import { requestTerminalPaneMoveFromRenderer } from './terminal-pane-move-request-relay' -import { revealTerminalPaneInWindow } from './terminal-pane-reveal-relay' -import { requestTerminalTabCloseFromRenderer } from './terminal-tab-close-request-relay' +import { registerRendererDocumentNavigation } from './security/renderer-document-navigation' +import { createRuntimeRendererNotificationSender } from './renderer-relays/runtime-renderer-notification-sender' +import { requestSessionTabCloseFromRenderer } from './renderer-relays/session-tab-close-request-relay' +import { requestTerminalPaneMoveFromRenderer } from './renderer-relays/terminal-pane-move-request-relay' +import { revealTerminalPaneInWindow } from './renderer-relays/terminal-pane-reveal-relay' +import { requestTerminalTabCloseFromRenderer } from './renderer-relays/terminal-tab-close-request-relay' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../shared/sidebar-inputs-switch' import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' import { addFanoutListener } from '../runtime/events/event-listener-fanout' @@ -240,17 +240,16 @@ export function registerRuntimeWindowLifecycle( send('runtime:clientHostedBrowserRowsChanged', event), claudeAccountSelected: (change) => send('claudeAccounts:selectedElsewhere', change) }) - // Switch point: the window reads its sidebar from main's feed and re-reads on each notice. - const detachSidebarInputsNotices = ORCA_SIDEBAR_INPUTS_IS_MAIN - ? runtime.onClientEvent( - (event) => { - if (event.type === 'sidebarInputsChanged') { - send('runtime:sidebarInputsChanged', event) - } - }, - { consumesTerminalSideEffects: false } - ) - : null + const detachClientNotices = runtime.onClientEvent( + (event) => { + if (event.type === 'linearLinkedIssueUpdated') { + send('linear:linkedIssueUpdated', event) + } else if (ORCA_SIDEBAR_INPUTS_IS_MAIN && event.type === 'sidebarInputsChanged') { + send('runtime:sidebarInputsChanged', event) + } + }, + { consumesTerminalSideEffects: false } + ) // Only this window's live document speaks for the Agents list; a gone one leaves no verdicts behind. const releaseAgentListVerdicts = addFanoutListener( ipcMain, @@ -284,7 +283,7 @@ export function registerRuntimeWindowLifecycle( runtime.setAgentListPublication(null) }) mainWindow.on('closed', () => { - detachSidebarInputsNotices?.() + detachClientNotices() releaseAgentListVerdicts() runtime.setAgentListPublication(null) rendererNotifications.close() diff --git a/src/main/window/runtime-window-pane-title-notification.test.ts b/src/main/window/runtime-window-pane-title-notification.test.ts deleted file mode 100644 index 60dc06d5afb..00000000000 --- a/src/main/window/runtime-window-pane-title-notification.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { BrowserWindow } from 'electron' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { RuntimeNotifier } from '../runtime/client/events/runtime-notifier-contract' - -vi.mock('electron', () => ({ ipcMain: { on: vi.fn(), removeListener: vi.fn() } })) -vi.mock('../ipc/worktrees/listing/worktree-change-invalidators', () => ({ - runWorktreeChangeInvalidators: vi.fn() -})) -vi.mock('./renderer-document-navigation', () => ({ registerRendererDocumentNavigation: vi.fn() })) -vi.mock('./session-tab-close-request-relay', () => ({ - requestSessionTabCloseFromRenderer: vi.fn() -})) -vi.mock('./terminal-tab-close-request-relay', () => ({ - requestTerminalTabCloseFromRenderer: vi.fn() -})) - -import { registerRuntimeWindowLifecycle } from './runtime-window-lifecycle' - -function attachNotifier() { - const send = vi.fn() - const markGraphReloadFailed = vi.fn() - const attached: { notifier: RuntimeNotifier | null } = { notifier: null } - const windowState = { destroyed: false } - const mainWindow = { - id: 1, - isDestroyed: () => windowState.destroyed, - on: vi.fn(), - webContents: { isDestroyed: () => false, send, on: vi.fn() } - } - const runtime = { - attachWindow: vi.fn(), - markGraphReloadFailed, - setNotifier: (next: RuntimeNotifier | null) => { - attached.notifier = next - } - } - registerRuntimeWindowLifecycle( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration reads only the supplied window lifecycle and webContents members. - mainWindow as unknown as BrowserWindow, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration calls only the supplied runtime attachment and notification members. - runtime as unknown as OrcaRuntimeService - ) - if (!attached.notifier?.setPaneTitle) { - throw new Error('pane-title notifier was not attached') - } - return { setPaneTitle: attached.notifier.setPaneTitle, send, windowState, markGraphReloadFailed } -} - -describe('pane title renderer emission receipts', () => { - it('returns false without emitting to a destroyed desktop', () => { - const { setPaneTitle, send, windowState } = attachNotifier() - windowState.destroyed = true - expect(setPaneTitle('tab-1', 'leaf-1', null)).toBe(false) - expect(send).not.toHaveBeenCalled() - }) - - it('reports a disposed frame once and refuses subsequent emissions', () => { - const { setPaneTitle, send, markGraphReloadFailed } = attachNotifier() - send.mockImplementation(() => { - throw new Error('disposed frame') - }) - expect(setPaneTitle('tab-1', 'leaf-1', 'REVIEWER')).toBe(false) - expect(setPaneTitle('tab-1', 'leaf-1', 'OTHER')).toBe(false) - expect(send).toHaveBeenCalledTimes(1) - expect(markGraphReloadFailed).toHaveBeenCalledExactlyOnceWith(1, 'renderer-frame-unavailable') - }) -}) diff --git a/src/main/window/security/host-frame-navigation-guard.test.ts b/src/main/window/security/host-frame-navigation-guard.test.ts new file mode 100644 index 00000000000..9d48e3aa39b --- /dev/null +++ b/src/main/window/security/host-frame-navigation-guard.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { PLUGIN_PANEL_FRAME_NAME_PREFIX } from '../../../shared/plugins/frames/plugin-frame-bridge' +import { NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX } from '../../../shared/native-chat/native-chat-visual-shell' +import { HostFrameNavigationRegistry, hostFrameKindForName } from './host-frame-navigation-guard' + +function frame(input: { id: number; name?: string; url?: string }) { + let destroyed = false + return { + frameTreeNodeId: input.id, + name: input.name ?? '', + isDestroyed: () => destroyed, + destroy: () => { + destroyed = true + } + } +} + +describe('HostFrameNavigationRegistry', () => { + it('blocks only host-marked plugin srcdoc frames', () => { + const registry = new HostFrameNavigationRegistry() + const plugin = frame({ id: 1, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo` }) + const notebook = frame({ id: 2 }) + registry.register(plugin) + registry.register(notebook) + + expect(registry.shouldBlock(plugin, null, 'about:srcdoc')).toBe(false) + expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(true) + expect(registry.shouldBlock(notebook, notebook, 'https://example.com')).toBe(false) + }) + + it('keeps pre-parse identity after name mutation and ignores destroyed frames', () => { + const registry = new HostFrameNavigationRegistry() + const plugin = frame({ id: 1, name: `${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo` }) + registry.register(plugin) + plugin.name = '' + expect(registry.shouldBlock(plugin, null, 'about:srcdoc')).toBe(false) + expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(true) + + plugin.destroy() + expect(registry.shouldBlock(plugin, plugin, 'https://example.com')).toBe(false) + }) + + it('contains chat visual frames the same way, as their own kind', () => { + const registry = new HostFrameNavigationRegistry() + const visual = frame({ id: 3, name: `${NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX}abc` }) + registry.register(visual) + expect(hostFrameKindForName(visual.name)).toBe('chat-visual') + expect(hostFrameKindForName(`${PLUGIN_PANEL_FRAME_NAME_PREFIX}demo`)).toBe('plugin-panel') + expect(hostFrameKindForName('orca-chat-visual')).toBeNull() + + expect(registry.shouldBlock(visual, null, 'about:srcdoc')).toBe(false) + // Its own navigation (location, meta refresh, link) and any child it starts are refused. + expect(registry.shouldBlock(visual, visual, 'https://example.com')).toBe(true) + expect(registry.shouldBlock(visual, null, 'https://example.com')).toBe(true) + const child = frame({ id: 4 }) + expect(registry.shouldBlock(child, visual, 'https://example.com')).toBe(true) + }) +}) diff --git a/src/main/window/host-frame-navigation-guard.ts b/src/main/window/security/host-frame-navigation-guard.ts similarity index 93% rename from src/main/window/host-frame-navigation-guard.ts rename to src/main/window/security/host-frame-navigation-guard.ts index 47a516eb3ec..a938260eea2 100644 --- a/src/main/window/host-frame-navigation-guard.ts +++ b/src/main/window/security/host-frame-navigation-guard.ts @@ -1,6 +1,6 @@ import type { WebContents, WebFrameMain } from 'electron' -import { NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX } from '../../shared/native-chat/native-chat-visual-shell' -import { PLUGIN_PANEL_FRAME_NAME_PREFIX } from '../../shared/plugins/frames/plugin-frame-bridge' +import { NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX } from '../../../shared/native-chat/native-chat-visual-shell' +import { PLUGIN_PANEL_FRAME_NAME_PREFIX } from '../../../shared/plugins/frames/plugin-frame-bridge' type NavigationFrame = Pick diff --git a/src/main/window/host-frame-permission-policy.test.ts b/src/main/window/security/host-frame-permission-policy.test.ts similarity index 100% rename from src/main/window/host-frame-permission-policy.test.ts rename to src/main/window/security/host-frame-permission-policy.test.ts diff --git a/src/main/window/host-frame-permission-policy.ts b/src/main/window/security/host-frame-permission-policy.ts similarity index 100% rename from src/main/window/host-frame-permission-policy.ts rename to src/main/window/security/host-frame-permission-policy.ts diff --git a/src/main/window/main-window-webview-security.ts b/src/main/window/security/main-window-webview-security.ts similarity index 85% rename from src/main/window/main-window-webview-security.ts rename to src/main/window/security/main-window-webview-security.ts index d403d87e974..315da43ee10 100644 --- a/src/main/window/main-window-webview-security.ts +++ b/src/main/window/security/main-window-webview-security.ts @@ -1,42 +1,42 @@ import type { BrowserWindow } from 'electron' import { join } from 'node:path' -import { ORCA_BROWSER_GUEST_WEB_PREFERENCES } from '../../shared/browser/guest-lifecycle/browser-guest-web-preferences' -import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' -import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' -import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' +import { ORCA_BROWSER_GUEST_WEB_PREFERENCES } from '../../../shared/browser/guest-lifecycle/browser-guest-web-preferences' +import { normalizeBrowserNavigationUrl } from '../../../shared/browser-url' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../browser/sessions/profiles/browser-session-registry' import { enforceLocalSshWebRtcPolicyForGuest, isLocalSshBrowserPartition -} from '../browser/routing/local-host-partitions/local-ssh-browser-partitions' +} from '../../browser/routing/local-host-partitions/local-ssh-browser-partitions' import { browserRouteSessionRegistry, browserRouteWebContentsRegistry -} from '../browser/routing/sessions/browser-route-session-runtime' -import '../../shared/constants' -import { ORCA_BROWSER_BLANK_URL } from '../../shared/browser/browser-blank-page' +} from '../../browser/routing/sessions/browser-route-session-runtime' +import '../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../shared/browser/browser-blank-page' import { DOC_PREVIEW_PARTITION, parseDocPreviewUrl -} from '../../shared/document-preview/doc-preview-scheme' -import { setDocPreviewFailureSink } from '../browser/document-preview/doc-preview-failure-notice' +} from '../../../shared/document-preview/doc-preview-scheme' +import { setDocPreviewFailureSink } from '../../browser/document-preview/doc-preview-failure-notice' import { getDocPreviewGrant, revokeAllDocPreviewGrants -} from '../browser/document-preview/doc-preview-grant-registry' -import { isDocPreviewSession } from '../browser/document-preview/doc-preview-protocol' +} from '../../browser/document-preview/doc-preview-grant-registry' +import { isDocPreviewSession } from '../../browser/document-preview/doc-preview-protocol' import { registerHostFrameNavigationGuard } from './host-frame-navigation-guard' import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' -import { parseChromeExtensionUrl } from '../../shared/browser/extensions/browser-extension-url' -import { getBrowserExtensionSessionForProfile } from '../browser/extensions/profile-sessions/browser-extension-session-loader' -import { installBrowserJavaScriptDialogs } from '../browser/guest-lifecycle/prompts/browser-javascript-dialogs' -import { installNativeChatVisualGuestTheme } from '../host/native-chat-visual-guest-theme' +import { parseChromeExtensionUrl } from '../../../shared/browser/extensions/browser-extension-url' +import { getBrowserExtensionSessionForProfile } from '../../browser/extensions/profile-sessions/browser-extension-session-loader' +import { installBrowserJavaScriptDialogs } from '../../browser/guest-lifecycle/prompts/browser-javascript-dialogs' +import { installNativeChatVisualGuestTheme } from '../../host/native-chat-visual-guest-theme' import { admitPluginFrameAttach, attachPluginFrameGuest, isPluginFramePartition, PLUGIN_FRAME_GUEST_RENDERER_ARGUMENTS -} from '../plugins/panels/guest-isolation/plugin-frame-guest-registry' -import { attachBrowserPasswordGuest } from '../browser-passwords/browser-password-guest-service' +} from '../../plugins/panels/guest-isolation/plugin-frame-guest-registry' +import { attachBrowserPasswordGuest } from '../../browser-passwords/browser-password-guest-service' /** orca-preview is outside normal browser URL admission; require the doc partition and a main-minted user-preview grant. */ function isAdmissibleDocPreviewAttach(partition: string, src: string): boolean { diff --git a/src/main/window/privileged-window-navigation.ts b/src/main/window/security/privileged-window-navigation.ts similarity index 92% rename from src/main/window/privileged-window-navigation.ts rename to src/main/window/security/privileged-window-navigation.ts index fd50766d06c..c9d4fa1db93 100644 --- a/src/main/window/privileged-window-navigation.ts +++ b/src/main/window/security/privileged-window-navigation.ts @@ -1,5 +1,5 @@ import { shell, type WebContents } from 'electron' -import { normalizeExternalBrowserUrl } from '../../shared/browser-url' +import { normalizeExternalBrowserUrl } from '../../../shared/browser-url' import { isRendererDocumentNavigation } from './renderer-document-navigation' /** Keep remote documents from inheriting an Orca window's privileged preload. */ diff --git a/src/main/window/renderer-document-navigation.ts b/src/main/window/security/renderer-document-navigation.ts similarity index 100% rename from src/main/window/renderer-document-navigation.ts rename to src/main/window/security/renderer-document-navigation.ts diff --git a/src/main/window/session-tab-close-request-relay.test.ts b/src/main/window/session-tab-close-request-relay.test.ts deleted file mode 100644 index 11b7a921d01..00000000000 --- a/src/main/window/session-tab-close-request-relay.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { EventEmitter } from 'node:events' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const ipcEmitter = new EventEmitter() -const ipcMainMock = { - on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.on(channel, listener) - }), - removeListener: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.removeListener(channel, listener) - }) -} - -vi.mock('electron', () => ({ ipcMain: ipcMainMock })) - -function createMainWindow() { - const webContents = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - send: vi.fn() - }) - const mainWindow = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - webContents - }) - return { mainWindow, webContents } -} - -describe('requestSessionTabCloseFromRenderer', () => { - beforeEach(() => { - vi.useRealTimers() - ipcEmitter.removeAllListeners() - ipcMainMock.on.mockClear() - ipcMainMock.removeListener.mockClear() - }) - - it('waits for the targeted renderer acknowledgement', async () => { - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') - const request = webContents.send.mock.calls[0]?.[1] as { - requestId: string - tabId: string - worktreeId: string - expiresAt: number - } - - expect(request).toMatchObject({ tabId: 'tab-1', worktreeId: 'wt-1' }) - expect(request.expiresAt).toBeGreaterThan(Date.now()) - ipcEmitter.emit('ui:sessionTabCloseResponse', { sender: {} }, { requestId: request.requestId }) - let settled = false - void pending.finally(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - - ipcEmitter.emit( - 'ui:sessionTabCloseResponse', - { sender: webContents }, - { requestId: request.requestId } - ) - await expect(pending).resolves.toBeUndefined() - }) - - it('propagates renderer cancellation', async () => { - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-pinned', 'wt-1') - const request = webContents.send.mock.calls[0]?.[1] as { requestId: string } - - ipcEmitter.emit( - 'ui:sessionTabCloseResponse', - { sender: webContents }, - { requestId: request.requestId, error: 'session_tab_close_canceled' } - ) - - await expect(pending).rejects.toThrow('session_tab_close_canceled') - }) - - it.each(['destroyed', 'render-process-gone', 'did-start-loading'])( - 'rejects when web contents emits %s', - async (eventName) => { - const { requestSessionTabCloseFromRenderer } = - await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') - - webContents.emit(eventName) - - await expect(pending).rejects.toThrow('renderer_unavailable') - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) - } - ) - - it('times out after the renderer confirmation lease and response grace', async () => { - vi.useFakeTimers() - vi.setSystemTime(1_000) - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') - const request = webContents.send.mock.calls[0]?.[1] as { expiresAt: number } - const rejection = expect(pending).rejects.toThrow('session_tab_close_timeout') - - await vi.advanceTimersByTimeAsync(request.expiresAt - Date.now() + 5_000) - - await rejection - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) - }) - - it('shares one lifecycle listener across overlapping close requests', async () => { - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = Array.from({ length: 15 }, (_, index) => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the EventEmitter double implements the BrowserWindow members the relay uses. - requestSessionTabCloseFromRenderer(mainWindow as never, `tab-${index}`, 'wt-1') - ) - - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(1) - expect(mainWindow.listenerCount('closed')).toBe(1) - for (const event of ['destroyed', 'render-process-gone', 'did-start-loading']) { - expect(webContents.listenerCount(event)).toBe(1) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the relay sends only session tab close requests on this double. - const requests = webContents.send.mock.calls as [string, { requestId: string }][] - for (const [, request] of requests) { - ipcEmitter.emit( - 'ui:sessionTabCloseResponse', - { sender: webContents }, - { requestId: request.requestId } - ) - } - - await Promise.all(pending) - expect(mainWindow.eventNames()).toEqual([]) - expect(webContents.eventNames()).toEqual([]) - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) - }) - - it.each([ - ['window', 'closed'], - ['webContents', 'destroyed'], - ['webContents', 'did-start-loading'] - ] as const)( - 'rejects both overlapping requests on one %s %s and returns to baseline listeners', - async (target, eventName) => { - const { requestSessionTabCloseFromRenderer } = - await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const baseline = { - window: mainWindow.eventNames(), - webContents: webContents.eventNames(), - ipc: ipcEmitter.listenerCount('ui:sessionTabCloseResponse') - } - const pending = ['tab-1', 'tab-2'].map((tabId) => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the EventEmitter double implements the BrowserWindow members the relay uses. - requestSessionTabCloseFromRenderer(mainWindow as never, tabId, 'wt-1') - ) - - ;(target === 'window' ? mainWindow : webContents).emit(eventName) - - await Promise.all( - pending.map((request) => expect(request).rejects.toThrow('renderer_unavailable')) - ) - expect(mainWindow.eventNames()).toEqual(baseline.window) - expect(webContents.eventNames()).toEqual(baseline.webContents) - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(baseline.ipc) - } - ) -}) diff --git a/src/main/window/terminal-pane-move-request-relay.test.ts b/src/main/window/terminal-pane-move-request-relay.test.ts deleted file mode 100644 index cd5c63de623..00000000000 --- a/src/main/window/terminal-pane-move-request-relay.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { EventEmitter } from 'node:events' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalLeafMoveResult } from '../../shared/workspace-layout/terminal-leaf-move' - -const ipcEmitter = new EventEmitter() -const ipcMainMock = { - on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.on(channel, listener) - }), - removeListener: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.removeListener(channel, listener) - }) -} - -vi.mock('electron', () => ({ ipcMain: ipcMainMock })) - -const move = { worktreeId: 'wt-1', sourceTabId: 'tab-1', targetTabId: 'tab-new', leafId: 'leaf-1' } - -function createMainWindow() { - const webContents = Object.assign(new EventEmitter(), { - id: 1, - isDestroyed: () => false, - send: vi.fn<(channel: string, request: { requestId: string }) => void>() - }) - const mainWindow = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - webContents - }) - return { mainWindow, webContents } -} - -async function requestMove() { - const relay = { - ...(await import('./terminal-pane-move-request-relay')), - ...(await import('./terminal-pane-move-commit-fence')) - } - const { mainWindow, webContents } = createMainWindow() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the EventEmitter double implements the BrowserWindow members the relay uses. - const pending = relay.requestTerminalPaneMoveFromRenderer(mainWindow as never, move) - const request = webContents.send.mock.calls[0]![1] - const sender = webContents - const reply = (result: TerminalLeafMoveResult): void => { - ipcEmitter.emit( - 'ui:terminalPaneMoveToNewTabReply', - { sender: webContents }, - { requestId: request.requestId, result } - ) - } - return { relay, pending, sender, webContents, reply } -} - -function deferredCommit() { - let finish: (result: TerminalLeafMoveResult) => void = () => {} - const commit = (): Promise => - new Promise((resolve) => { - finish = resolve - }) - return { commit, finish: (result: TerminalLeafMoveResult) => finish(result) } -} - -describe('requestTerminalPaneMoveFromRenderer', () => { - beforeEach(() => { - vi.resetModules() - vi.useFakeTimers() - ipcEmitter.removeAllListeners() - }) - - it('commits nothing the window tries after the client was told the move timed out', async () => { - const { relay, pending, sender, reply } = await requestMove() - const timedOut = expect(pending).rejects.toThrow('terminal_pane_move_timeout') - await vi.advanceTimersByTimeAsync(10_000) - await timedOut - - const commit = vi.fn(async (): Promise => ({ - status: 'moved', - ptyId: 'pty-1' - })) - const late = await relay.commitRelayedPaneMove(sender, move.targetTabId, commit) - - expect(late).toEqual({ status: 'refused', reason: 'pane_unavailable' }) - expect(commit).not.toHaveBeenCalled() - reply({ status: 'refused', reason: 'pane_unavailable' }) - expect(ipcEmitter.listenerCount('ui:terminalPaneMoveToNewTabReply')).toBe(0) - }) - - it('answers moved once the window commits, even when its reply comes after the deadline', async () => { - const { relay, pending, sender } = await requestMove() - const { commit, finish } = deferredCommit() - const committing = relay.commitRelayedPaneMove(sender, move.targetTabId, commit) - await vi.advanceTimersByTimeAsync(10_000) - finish({ status: 'moved', ptyId: 'pty-1' }) - - await expect(committing).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) - await expect(pending).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) - }) - - it('answers with the commit when the window goes away while it commits', async () => { - const { relay, pending, sender, webContents } = await requestMove() - const { commit, finish } = deferredCommit() - const committing = relay.commitRelayedPaneMove(sender, move.targetTabId, commit) - webContents.emit('render-process-gone') - finish({ status: 'moved', ptyId: 'pty-1' }) - - await expect(committing).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) - await expect(pending).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) - }) -}) diff --git a/src/main/window/terminal-pane-reveal-relay.test.ts b/src/main/window/terminal-pane-reveal-relay.test.ts deleted file mode 100644 index 1bf27204fdf..00000000000 --- a/src/main/window/terminal-pane-reveal-relay.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { BrowserWindow } from 'electron' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - TerminalPaneRevealRequest, - TerminalPaneRevealTarget -} from '../../shared/workspace-layout/terminal-pane-reveal' -import type { FocusExistingMainWindowOptions } from './focus-existing-window' - -const ipcEmitter = new EventEmitter() -const mocks = vi.hoisted(() => ({ - focusExistingMainWindow: vi.fn<(options: FocusExistingMainWindowOptions) => string>() -})) -const ipcMainMock = { - on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.on(channel, listener) - }), - removeListener: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.removeListener(channel, listener) - }) -} - -vi.mock('electron', () => ({ app: {}, ipcMain: ipcMainMock })) -vi.mock('./focus-existing-window', () => ({ - focusExistingMainWindow: mocks.focusExistingMainWindow -})) - -const target: TerminalPaneRevealTarget = { - worktreeId: 'repo-1::/srv/app', - tabId: 'tab-1', - leafId: '11111111-1111-4111-8111-111111111111', - executionHostId: 'runtime:env-1' -} - -function createWindow(options: { rendererDestroyed?: boolean } = {}) { - const webContents = Object.assign(new EventEmitter(), { - isDestroyed: () => options.rendererDestroyed === true, - send: vi.fn<(channel: string, request: TerminalPaneRevealRequest) => void>() - }) - const windowEvents = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - webContents - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture supplies the relay's window/contents event, destruction and send surface. - const mainWindow = windowEvents as unknown as BrowserWindow - const sentRequest = (): TerminalPaneRevealRequest => { - const [channel, request] = webContents.send.mock.calls[0] ?? [] - expect(channel).toBe('ui:revealTerminalPane') - return request ?? { ...target, requestId: '' } - } - return { webContents, mainWindow, windowEvents, sentRequest } -} - -async function loadRelay() { - return (await import('./terminal-pane-reveal-relay')).revealTerminalPaneInWindow -} - -function reply(sender: unknown, requestId: string, revealed: boolean): void { - ipcEmitter.emit('ui:terminalPaneRevealReply', { sender }, { requestId, revealed }) -} - -describe('revealTerminalPaneInWindow', () => { - beforeEach(() => { - ipcEmitter.removeAllListeners() - mocks.focusExistingMainWindow.mockReset() - }) - - afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - }) - - it('raises the window once the targeted renderer has revealed the pane', async () => { - const revealTerminalPaneInWindow = await loadRelay() - const { webContents, mainWindow, sentRequest } = createWindow() - const pending = revealTerminalPaneInWindow(mainWindow, target) - const { requestId } = sentRequest() - expect(sentRequest()).toEqual({ ...target, requestId }) - - // Visible request IDs confer no authority; only the targeted window can answer. - reply({}, requestId, false) - reply(webContents, 'other-request', false) - reply(webContents, requestId, true) - - await expect(pending).resolves.toBe(true) - expect(mocks.focusExistingMainWindow).toHaveBeenCalledTimes(1) - const focus = mocks.focusExistingMainWindow.mock.calls[0]?.[0] - expect(focus?.getWindow()).toBe(mainWindow) - expect(focus?.canOpenWindow?.()).toBe(false) - expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(0) - }) -}) diff --git a/src/main/window/renderer-publication-throttle-electron-fixture.ts b/src/main/window/testing/renderer-publication-throttle-electron-fixture.ts similarity index 93% rename from src/main/window/renderer-publication-throttle-electron-fixture.ts rename to src/main/window/testing/renderer-publication-throttle-electron-fixture.ts index 3a417f1dc9f..ef9c2eb52e0 100644 --- a/src/main/window/renderer-publication-throttle-electron-fixture.ts +++ b/src/main/window/testing/renderer-publication-throttle-electron-fixture.ts @@ -1,6 +1,6 @@ import { app, BrowserWindow } from 'electron' -import { startBrowserScreencast } from '../browser/cdp/screencast/browser-screencast-stream' -import { RendererPublicationThrottle } from './renderer-publication-throttle' +import { startBrowserScreencast } from '../../browser/cdp/screencast/browser-screencast-stream' +import { RendererPublicationThrottle } from '../visibility/renderer-publication-throttle' async function run(): Promise { // Serve must survive with no page open; keep Electron alive after last-window close. diff --git a/src/main/window/visibility/hidden-window-frame-pump.ts b/src/main/window/visibility/hidden-window-frame-pump.ts new file mode 100644 index 00000000000..1f7fb1a7b44 --- /dev/null +++ b/src/main/window/visibility/hidden-window-frame-pump.ts @@ -0,0 +1,31 @@ +import { HIDDEN_WINDOW_FRAME_PUMP_STOP_CHANNEL } from '../../../shared/hidden-window-frame-pump' + +type FramePumpWindow = { + on(event: 'show', listener: () => void): unknown + webContents: { + isDestroyed?(): boolean + on(event: 'did-finish-load', listener: () => void): unknown + send(channel: string): void + } +} + +/** The preload pumps from birth; stop it on first show and after any later reload restarts it. */ +export function stopHiddenWindowFramePumpOnShow(window: FramePumpWindow): void { + let shown = false + const stop = (): void => { + if (window.webContents.isDestroyed?.() !== true) { + window.webContents.send(HIDDEN_WINDOW_FRAME_PUMP_STOP_CHANNEL) + } + } + window.on('show', () => { + if (!shown) { + shown = true + stop() + } + }) + window.webContents.on('did-finish-load', () => { + if (shown) { + stop() + } + }) +} diff --git a/src/main/window/main-window-visibility.ts b/src/main/window/visibility/main-window-visibility.ts similarity index 100% rename from src/main/window/main-window-visibility.ts rename to src/main/window/visibility/main-window-visibility.ts diff --git a/src/main/window/renderer-publication-throttle.electron.test.ts b/src/main/window/visibility/renderer-publication-throttle.electron.test.ts similarity index 89% rename from src/main/window/renderer-publication-throttle.electron.test.ts rename to src/main/window/visibility/renderer-publication-throttle.electron.test.ts index a01dfceb678..90211732c24 100644 --- a/src/main/window/renderer-publication-throttle.electron.test.ts +++ b/src/main/window/visibility/renderer-publication-throttle.electron.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { build } from 'vite' -import { resolveElectronProbeLaunch } from '../browser/electron-fixtures/electron-probe-display-launch' +import { resolveElectronProbeLaunch } from '../../browser/electron-fixtures/electron-probe-display-launch' describe('publication lease release during Electron guest destruction', () => { it('closes streamed guests without terminating the host', async () => { @@ -17,7 +17,10 @@ describe('publication lease release during Electron guest destruction', () => { build: { outDir: root, lib: { - entry: join(import.meta.dirname, 'renderer-publication-throttle-electron-fixture.ts'), + entry: join( + import.meta.dirname, + '../testing/renderer-publication-throttle-electron-fixture.ts' + ), formats: ['cjs'], fileName: () => 'main.cjs' }, diff --git a/src/main/window/renderer-publication-throttle.ts b/src/main/window/visibility/renderer-publication-throttle.ts similarity index 100% rename from src/main/window/renderer-publication-throttle.ts rename to src/main/window/visibility/renderer-publication-throttle.ts diff --git a/src/main/window/visibility/resource-view-admission.ts b/src/main/window/visibility/resource-view-admission.ts new file mode 100644 index 00000000000..4cc6fb030a1 --- /dev/null +++ b/src/main/window/visibility/resource-view-admission.ts @@ -0,0 +1,19 @@ +import type { BrowserWindow, IpcMainInvokeEvent } from 'electron' +import { getRuntimeDesktopSurface } from '../../runtime/construction/runtime-desktop-surface' +import type { ResourceViewAdmission } from '../../../shared/resource-view-admission' + +export function isResourceWindowVisible(window: BrowserWindow | null): boolean { + return !!window && !window.isDestroyed() && window.isVisible() && !window.isMinimized() +} + +export function assertResourceViewVisible( + event: IpcMainInvokeEvent, + admission?: ResourceViewAdmission +): void { + if ( + admission?.resourceManagerView && + !getRuntimeDesktopSurface().isResourceViewVisible?.(event.sender) + ) { + throw new Error('view_not_visible') + } +} diff --git a/src/main/window/wait-for-window-to-show.ts b/src/main/window/visibility/wait-for-window-to-show.ts similarity index 100% rename from src/main/window/wait-for-window-to-show.ts rename to src/main/window/visibility/wait-for-window-to-show.ts diff --git a/src/main/window/workspace-space-window.ts b/src/main/window/workspace-space-window.ts index 08bbfedc31e..da4deba0e58 100644 --- a/src/main/window/workspace-space-window.ts +++ b/src/main/window/workspace-space-window.ts @@ -1,8 +1,11 @@ import { mainI18n, translateMain } from '../i18n/main-i18n' import { app, BrowserWindow, nativeTheme, type WebContents } from 'electron' import { join } from 'node:path' -import { isBackgroundLaunch, showWindowWithoutStealingFocus } from './foreground-activation-policy' -import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' +import { + isBackgroundLaunch, + showWindowWithoutStealingFocus +} from './activation/foreground-activation-policy' +import { installPrivilegedWindowNavigationPolicy } from './security/privileged-window-navigation' import { sendToTrustedUIRenderer } from '../ipc/ui' import type { Store } from '../persistence/loading-store/store' import { stepUIZoomLevel, type UIZoomDirection } from '../../shared/ui-zoom-level' diff --git a/src/main/windows/windows-process-table.test.ts b/src/main/windows/windows-process-table.test.ts index 9df22f2ead4..8b8db53ac11 100644 --- a/src/main/windows/windows-process-table.test.ts +++ b/src/main/windows/windows-process-table.test.ts @@ -1,23 +1,11 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { WindowsProcessTableTimeoutError } from './windows-process-table-timeout-error' -import { tmpdir } from 'node:os' -import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - __setWindowsProcessTableCimScanForTests, __setWindowsProcessTreeLoaderForTests, - __setWindowsProcessTreeRequireForTests, - isWindowsProcessTableAvailable, - isWindowsProcessStartTimeAvailable, - readWindowsProcessIdentityTable, readWindowsProcessIdentityTableFresh, - readWindowsProcessTable, readWindowsProcessTableFresh, - resetWindowsProcessTableForTests, - type WindowsProcessIdentityRow, - type WindowsProcessRow + resetWindowsProcessTableForTests } from './windows-process-table' -import { resetWindowsCommandLineRecoveryHealthForTests } from './windows-command-line-recovery-health' /** None | CreationTime, and CommandLine on top of it. Memory (1) is never asked for. */ const IDENTITY_FLAGS = 4 @@ -55,48 +43,6 @@ const NATIVE: NativeRow[] = [ let coalescingCalls: { flags: number }[] = [] let maxConcurrentNativeCalls = 0 -function coalescingModule(): { - ProcessDataFlag: { None: number; Memory: number; CommandLine: number; CreationTime: number } - getAllProcesses: (cb: (rows: NativeRow[] | undefined) => void, flags?: number) => void -} { - let requestInProgress = false - const queue: ((rows: NativeRow[]) => void)[] = [] - return { - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses: (cb, flags) => { - queue.push(cb) - if (requestInProgress) { - return - } - requestInProgress = true - coalescingCalls.push({ flags: flags ?? 0 }) - // Gate each field on its own bit so identity creation-time omissions differ from coalesced flag errors. - const requested = flags ?? 0 - const rows: NativeRow[] = NATIVE.map((row) => ({ - pid: row.pid, - ppid: row.ppid, - name: row.name, - ...(requested & 2 && row.commandLine !== undefined ? { commandLine: row.commandLine } : {}), - ...(requested & 4 && row.creationTimeMs !== undefined - ? { creationTimeMs: row.creationTimeMs } - : {}) - })) - setTimeout(() => { - while (queue.length) { - queue.splice(0).forEach((callback) => callback(rows)) - } - requestInProgress = false - }, 0) - } - } -} - -/** Share the mock's module-global latch across reads. */ -function installCoalescingModule(): void { - const native = coalescingModule() - __setWindowsProcessTreeLoaderForTests(() => native) -} - /** Bare addon exposes overlap directly; the coalescing mock hides concurrent callers behind its own latch. */ function installBareAddonModule(): void { let inFlight = 0 @@ -139,52 +85,6 @@ describe('windows process table', () => { } }) - it('collapses a 32-wide burst into one scan per flag set', async () => { - installCoalescingModule() - const [identity, detailed] = await Promise.all([ - Promise.all(Array.from({ length: 16 }, () => readWindowsProcessIdentityTable())), - Promise.all(Array.from({ length: 16 }, () => readWindowsProcessTable())) - ]) - expect(coalescingCalls.map((call) => call.flags).sort()).toEqual([ - IDENTITY_FLAGS, - DETAILED_FLAGS - ]) - expect(identity).toHaveLength(16) - expect(detailed).toHaveLength(16) - }) - - // The wrapper discards overlapping flags; identity-first used to strip detailed command lines. - async function expectEachViewGotItsOwnFlags( - identity: Promise, - detailed: Promise - ): Promise { - const [identityRows, detailedRows] = await Promise.all([identity, detailed]) - expect(detailedRows.some((row) => row.command === '"C:/a b/orca.exe" --x')).toBe(true) - expect(identityRows.every((row) => !('command' in row))).toBe(true) - // Verify both row shape and requested flags: either alone misses the other failure mode. - expect(identityRows.map((row) => row.creationTimeMs)).toEqual([undefined, 1_700_000_000_000]) - expect(detailedRows.map((row) => row.creationTimeMs)).toEqual([undefined, 1_700_000_000_000]) - // This coalescing mock serializes itself; measure our gate against the bare addon separately. - expect(coalescingCalls.map((call) => call.flags).sort()).toEqual([ - IDENTITY_FLAGS, - DETAILED_FLAGS - ]) - } - - it('gives each flag set its own data when the identity read is issued first', async () => { - installCoalescingModule() - const identity = readWindowsProcessIdentityTableFresh() - const detailed = readWindowsProcessTableFresh() - await expectEachViewGotItsOwnFlags(identity, detailed) - }) - - it('gives each flag set its own data when the detailed read is issued first', async () => { - installCoalescingModule() - const detailed = readWindowsProcessTableFresh() - const identity = readWindowsProcessIdentityTableFresh() - await expectEachViewGotItsOwnFlags(identity, detailed) - }) - it('never re-enters the bare relay addon when both flag sets overlap', async () => { installBareAddonModule() const detailed = readWindowsProcessTableFresh() @@ -197,29 +97,6 @@ describe('windows process table', () => { expect(maxConcurrentNativeCalls).toBe(1) }) - it('does not serve one flag set from the other cache', async () => { - await readWindowsProcessTable() - await readWindowsProcessIdentityTable() - expect(getAllProcesses).toHaveBeenCalledTimes(2) - }) - - it('rejects an empty identity snapshot rather than reporting an idle machine', async () => { - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => cb([])) - resetWindowsProcessTableForTests() - await expect(readWindowsProcessIdentityTableFresh()).rejects.toThrow(/unreadable/) - }) - - it('applies the deadline to the identity read too', async () => { - vi.useFakeTimers() - getAllProcesses.mockImplementation(() => {}) - resetWindowsProcessTableForTests() - const pending = readWindowsProcessIdentityTableFresh() - const assertion = expect(pending).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(3_000) - await assertion - vi.useRealTimers() - }) - it('shares the wedge gate across flag sets, because they share one addon', async () => { // Both flags share one wedged addon; separate gates would accumulate retained callbacks. vi.useFakeTimers() @@ -238,190 +115,6 @@ describe('windows process table', () => { expect(getAllProcesses).toHaveBeenCalledTimes(1) vi.useRealTimers() }) - - it('only advertises PID-safe ownership when the BINARY reports creation-time support', () => { - expect(isWindowsProcessStartTimeAvailable()).toBe(true) - - // Patched JS can advertise CreationTime over a prebuilt that still ignores flag4. - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - supportedProcessDataFlags: 3, - getAllProcesses - })) - expect(isWindowsProcessStartTimeAvailable()).toBe(false) - - // Older binaries lack the capability export entirely. - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses - })) - expect(isWindowsProcessStartTimeAvailable()).toBe(false) - }) - - it('serves repeat reads from the shared snapshot', async () => { - await readWindowsProcessTable() - await readWindowsProcessTable() - expect(getAllProcesses).toHaveBeenCalledTimes(1) - }) - - it('rejects rather than reporting an empty machine when the module is absent', async () => { - // Absent or failed readers cannot claim no processes are running. - __setWindowsProcessTreeLoaderForTests(() => null) - __setWindowsProcessTableCimScanForTests(async () => { - throw new Error('powershell unavailable') - }) - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/powershell unavailable/) - expect(isWindowsProcessTableAvailable()).toBe(false) - }) - - it('rejects when the snapshot itself fails', async () => { - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => cb(undefined)) - resetWindowsProcessTableForTests() - await expect(readWindowsProcessTableFresh()).rejects.toThrow() - }) - - it('rejects, without throwing inside the addon callback, a snapshot that failed natively', async () => { - // node-addon-api reports a failed worker (e.g. bad_alloc) by passing an Error; a throw inside the addon's - // callback loop is uncaught and ends the terminal host with every PTY on it (#33350). - let thrown: unknown - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => { - try { - cb(new Error('bad allocation')) - } catch (error) { - thrown = error - } - }) - resetWindowsProcessTableForTests() - const read = readWindowsProcessTableFresh() - await vi.waitFor(() => expect(getAllProcesses).toHaveBeenCalled()) - expect(thrown).toBeUndefined() - await expect(read).rejects.toThrow(/no snapshot/) - }) - - it('rejects an empty snapshot rather than reporting an idle machine', async () => { - // A blocked snapshot can return [] without error; it must not prove a live root dead. - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => cb([])) - resetWindowsProcessTableForTests() - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/unreadable/) - }) - - it('rejects when the snapshot never calls back', async () => { - // A missing callback must not strand process queries forever. - vi.useFakeTimers() - getAllProcesses.mockImplementation(() => {}) - resetWindowsProcessTableForTests() - const pending = readWindowsProcessTableFresh() - const assertion = expect(pending).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(3_000) - await assertion - vi.useRealTimers() - }) -}) - -// Relays without a staged addon need fallback; failed evidence otherwise leaves agent names stale. -describe('PowerShell fallback when the native binding is absent', () => { - let platform: PropertyDescriptor | undefined - const cimScan = vi.fn() - const CIM_ROWS = [ - { pid: process.pid, ppid: 0, name: 'node.exe', command: 'node relay.js' }, - { pid: 200, ppid: process.pid, name: 'claude.exe', command: 'claude --resume' } - ] - - beforeEach(() => { - platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - cimScan.mockReset() - cimScan.mockResolvedValue(CIM_ROWS) - __setWindowsProcessTableCimScanForTests(cimScan) - }) - - afterEach(() => { - __setWindowsProcessTableCimScanForTests() - __setWindowsProcessTreeLoaderForTests() - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - }) - - it('engages when the module cannot be required', async () => { - __setWindowsProcessTreeLoaderForTests(() => null) - await expect(readWindowsProcessTableFresh()).resolves.toEqual(CIM_ROWS) - expect(cimScan).toHaveBeenCalledTimes(1) - }) - - it('serves the identity view from the one scan a relay can afford', async () => { - // Share the expensive CIM scan between views. - __setWindowsProcessTreeLoaderForTests(() => null) - // Strip command lines even on fallback so identity callers cannot depend on them. - await expect(readWindowsProcessIdentityTableFresh()).resolves.toEqual([ - { pid: process.pid, ppid: 0, name: 'node.exe' }, - { pid: 200, ppid: process.pid, name: 'claude.exe' } - ]) - await readWindowsProcessTable() - expect(cimScan).toHaveBeenCalledTimes(1) - }) - - it('rejects an identity read that omits our own pid', async () => { - __setWindowsProcessTreeLoaderForTests(() => null) - cimScan.mockResolvedValue([{ pid: 200, ppid: 4, name: 'claude.exe', command: 'claude' }]) - await expect(readWindowsProcessIdentityTableFresh()).rejects.toThrow(/unreadable/) - }) - - it('does not engage when the native binding is present', async () => { - const getAllProcesses = vi.fn() - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => cb(NATIVE)) - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2 }, - getAllProcesses - })) - await readWindowsProcessTableFresh() - expect(cimScan).not.toHaveBeenCalled() - }) - - it('does not engage when a present binding fails its read', async () => { - // Native failure must not start PowerShell at polling cadence. - const getAllProcesses = vi.fn() - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => cb([])) - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2 }, - getAllProcesses - })) - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/unreadable/) - expect(cimScan).not.toHaveBeenCalled() - }) - - it('says so in the log, once, rather than falling back silently', async () => { - // Legitimate relay fallback must still emit a capability warning (#16905). - const fallbackWarnings = (): number => - warn.mock.calls.filter((call) => - String(call[0]).includes('falling back to a powershell.exe CIM scan') - ).length - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - __setWindowsProcessTreeLoaderForTests(() => null) - - await readWindowsProcessTableFresh() - await readWindowsProcessTableFresh() - expect(fallbackWarnings()).toBe(1) - - // Reinjection models a fresh process and must restore its once-only warning. - __setWindowsProcessTreeLoaderForTests(() => null) - await readWindowsProcessTableFresh() - expect(fallbackWarnings()).toBe(2) - warn.mockRestore() - }) - - it('rejects a scan missing our own pid instead of reporting an idle machine', async () => { - __setWindowsProcessTreeLoaderForTests(() => null) - cimScan.mockResolvedValue([{ pid: 200, ppid: 4, name: 'claude.exe', command: 'claude' }]) - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/unreadable/) - }) - - it('stays off Windows-only: darwin still reports unavailable', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - __setWindowsProcessTreeLoaderForTests(() => null) - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/unavailable/) - expect(cimScan).not.toHaveBeenCalled() - }) }) describe('sticky wedge', () => { @@ -440,37 +133,6 @@ describe('sticky wedge', () => { } }) - it('never re-enters the reader while the timed-out read is still out', async () => { - // Cooldowns limit callback rate, not retention; only the outstanding callback can reopen the gate. - vi.useFakeTimers() - const getAllProcesses = vi.fn(() => {}) - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses - })) - - const wedge = readWindowsProcessTableFresh() - const wedgeAssertion = expect(wedge).rejects.toThrow(/timed out/) - await vi.advanceTimersByTimeAsync(3_000) - await wedgeAssertion - expect(getAllProcesses).toHaveBeenCalledTimes(1) - - // Concurrent retries across four old cooldown windows must retain exactly one callback. - for (let window = 0; window < 4; window += 1) { - await vi.advanceTimersByTimeAsync(30_000) - const attempts = [ - readWindowsProcessTableFresh().catch(() => 'rejected'), - readWindowsProcessTableFresh().catch(() => 'rejected'), - readWindowsProcessTableFresh().catch(() => 'rejected') - ] - // Let any accidentally admitted probe reach its own deadline. - await vi.advanceTimersByTimeAsync(3_000) - expect(await Promise.all(attempts)).toEqual(['rejected', 'rejected', 'rejected']) - } - - expect(getAllProcesses).toHaveBeenCalledTimes(1) - }) - it('resumes as soon as the timed-out read finally calls back', async () => { // Only completion of the stuck request proves the queue drained; recovery needs no further cooldown. vi.useFakeTimers() @@ -497,290 +159,4 @@ describe('sticky wedge', () => { await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(NATIVE.length) expect(getAllProcesses).toHaveBeenCalledTimes(2) }) - - it('clears the deadline when the reader throws synchronously', async () => { - // An uncleared timer can wedge a reader after a synchronous throw already recovered. - vi.useFakeTimers() - const getAllProcesses = vi.fn(() => { - throw new Error('addon exploded') - }) - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses - })) - - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/exploded/) - await vi.advanceTimersByTimeAsync(10_000) - - // Recovery must not inherit the old deadline's wedge. - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }, - getAllProcesses: (cb: (rows: typeof NATIVE | undefined) => void) => cb(NATIVE) - })) - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(NATIVE.length) - }) -}) - -// Exercise real require resolution: replacing the loader hid missing relay specifiers (#15749). -describe('resolving the native reader', () => { - let platform: PropertyDescriptor | undefined - const PACKAGE_SPECIFIER = '@vscode/windows-process-tree' - const ADDON_SPECIFIER = './windows-process-tree.node' - const stagedAddonDirs: string[] = [] - - beforeEach(() => { - getAllProcesses.mockReset() - getAllProcesses.mockImplementation((cb: (rows: unknown) => void) => cb(NATIVE)) - platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - }) - - afterEach(() => { - __setWindowsProcessTreeRequireForTests() - __setWindowsProcessTableCimScanForTests() - for (const dir of stagedAddonDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - }) - - function addonReturning(rows: unknown): { - getProcessList: ReturnType - supportedProcessDataFlags: number - } { - return { - getProcessList: vi.fn((cb: (r: unknown) => void) => cb(rows)), - supportedProcessDataFlags: 7 - } - } - - /** Older binaries have no creation-time capability export. */ - function staleAddonReturning(rows: unknown): { getProcessList: ReturnType } { - return { getProcessList: vi.fn((cb: (r: unknown) => void) => cb(rows)) } - } - - it('prefers the npm package where the desktop app installs it', async () => { - const resolve = vi.fn((specifier: string) => { - if (specifier === PACKAGE_SPECIFIER) { - return { ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2 }, getAllProcesses } - } - throw new Error('should not reach the addon') - }) - __setWindowsProcessTreeRequireForTests(resolve) - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(2) - expect(resolve).toHaveBeenCalledWith(PACKAGE_SPECIFIER) - expect(resolve).not.toHaveBeenCalledWith(ADDON_SPECIFIER) - }) - - it('falls through to the addon staged beside the relay bundle', async () => { - const addon = addonReturning(NATIVE) - __setWindowsProcessTreeRequireForTests((specifier: string) => { - if (specifier === ADDON_SPECIFIER) { - return addon - } - throw new Error('MODULE_NOT_FOUND') - }) - const rows = await readWindowsProcessTableFresh() - expect(rows).toEqual([ - { pid: process.pid, ppid: 0, name: 'vitest.exe', command: 'vitest.exe --run' }, - { - pid: 100, - ppid: 4, - name: 'orca.exe', - command: '"C:/a b/orca.exe" --x', - creationTimeMs: 1_700_000_000_000 - } - ]) - expect(isWindowsProcessTableAvailable()).toBe(true) - }) - - it('asks the addon for the command line and creation time, as the package path does', async () => { - const addon = addonReturning(NATIVE) - __setWindowsProcessTreeRequireForTests((specifier: string) => { - if (specifier === ADDON_SPECIFIER) { - return addon - } - throw new Error('MODULE_NOT_FOUND') - }) - await readWindowsProcessTableFresh() - // Detailed reads need creation times for PID-safe teardown and omit unused Memory. - expect(addon.getProcessList).toHaveBeenCalledWith(expect.any(Function), 6) - expect(isWindowsProcessStartTimeAvailable()).toBe(true) - }) - - it('asks the addon for the creation time alone on the identity path', async () => { - const addon = addonReturning(NATIVE) - __setWindowsProcessTreeRequireForTests((specifier: string) => { - if (specifier === ADDON_SPECIFIER) { - return addon - } - throw new Error('MODULE_NOT_FOUND') - }) - await readWindowsProcessIdentityTableFresh() - // CreationTime alone uses a limited handle/GetProcessTimes; no command-line query. - expect(addon.getProcessList).toHaveBeenCalledWith(expect.any(Function), 4) - }) - - it('trusts the staged addon on its own report, not on ours', async () => { - // Old addons still enumerate but cannot prove PID incarnation without creation times. - const addon = staleAddonReturning(NATIVE) - __setWindowsProcessTreeRequireForTests((specifier: string) => { - if (specifier === ADDON_SPECIFIER) { - return addon - } - throw new Error('MODULE_NOT_FOUND') - }) - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(2) - expect(isWindowsProcessTableAvailable()).toBe(true) - expect(isWindowsProcessStartTimeAvailable()).toBe(false) - }) - - it('reaches the CIM scan when neither the package nor the addon is present', async () => { - const cimScan = vi - .fn() - .mockResolvedValue([ - { pid: process.pid, ppid: 0, name: 'node.exe', command: 'node relay.js' } - ]) - __setWindowsProcessTableCimScanForTests(cimScan) - __setWindowsProcessTreeRequireForTests(() => { - throw new Error('MODULE_NOT_FOUND') - }) - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(1) - expect(cimScan).toHaveBeenCalledTimes(1) - expect(isWindowsProcessTableAvailable()).toBe(false) - }) - - it('rejects an addon that loads without the call we need', async () => { - // Unusable addon shapes must fall back rather than reject every subsequent read. - const cimScan = vi - .fn() - .mockResolvedValue([ - { pid: process.pid, ppid: 0, name: 'node.exe', command: 'node relay.js' } - ]) - __setWindowsProcessTableCimScanForTests(cimScan) - __setWindowsProcessTreeRequireForTests((specifier: string) => { - if (specifier === ADDON_SPECIFIER) { - return { notTheApi: true } - } - throw new Error('MODULE_NOT_FOUND') - }) - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(1) - expect(cimScan).toHaveBeenCalledTimes(1) - }) - - // Independent deployment can leave a loadable old addon that still imports ReadProcessMemory. - function withStagedAddonBinary( - bytes: string, - addon: unknown - ): ((specifier: string) => unknown) & { resolve: (specifier: string) => string } { - const dir = mkdtempSync(join(tmpdir(), 'orca-relay-addon-')) - const addonPath = join(dir, 'windows-process-tree.node') - writeFileSync(addonPath, bytes) - stagedAddonDirs.push(dir) - const resolve = (specifier: string): unknown => { - if (specifier === ADDON_SPECIFIER) { - return addon - } - throw new Error('MODULE_NOT_FOUND') - } - resolve.resolve = (specifier: string): string => { - if (specifier === ADDON_SPECIFIER) { - return addonPath - } - throw new Error('MODULE_NOT_FOUND') - } - return resolve - } - - it('refuses a staged relay addon still built from unpatched source', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const cimScan = vi - .fn() - .mockResolvedValue([ - { pid: process.pid, ppid: 0, name: 'node.exe', command: 'node relay.js' } - ]) - __setWindowsProcessTableCimScanForTests(cimScan) - const addon = addonReturning(NATIVE) - __setWindowsProcessTreeRequireForTests( - withStagedAddonBinary('MZ\0KERNEL32.dll\0ReadProcessMemory\0', addon) - ) - - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(1) - expect(addon.getProcessList).not.toHaveBeenCalled() - expect(cimScan).toHaveBeenCalledTimes(1) - expect(isWindowsProcessTableAvailable()).toBe(false) - expect(warn.mock.calls[0]?.[0]).toContain('ReadProcessMemory') - warn.mockRestore() - }) - - it('binds a staged relay addon whose binary carries no such import', async () => { - const addon = addonReturning(NATIVE) - __setWindowsProcessTreeRequireForTests( - withStagedAddonBinary('MZ\0ntdll.dll\0NtQueryInformationProcess\0', addon) - ) - - await expect(readWindowsProcessTableFresh()).resolves.toHaveLength(2) - expect(addon.getProcessList).toHaveBeenCalledTimes(1) - }) - - it('never probes either specifier off Windows', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - const resolve = vi.fn() - __setWindowsProcessTreeRequireForTests(resolve) - await expect(readWindowsProcessTableFresh()).rejects.toThrow(/unavailable/) - expect(resolve).not.toHaveBeenCalled() - }) -}) - -// Kernel command-line refusal leaves enumeration healthy; capability checks alone miss it. -describe('warning when command-line recovery is refused host-wide', () => { - let platform: PropertyDescriptor | undefined - let warn: ReturnType - - beforeEach(() => { - platform = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - resetWindowsCommandLineRecoveryHealthForTests() - warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - - afterEach(() => { - __setWindowsProcessTreeLoaderForTests() - warn.mockRestore() - if (platform) { - Object.defineProperty(process, 'platform', platform) - } - }) - - type NativeRow = { pid: number; ppid: number; name: string; commandLine?: string } - - function loaderReturning(rows: NativeRow[], commandLineFlag: number): void { - __setWindowsProcessTreeLoaderForTests(() => ({ - ProcessDataFlag: { None: 0, Memory: 1, CommandLine: commandLineFlag, CreationTime: 4 }, - getAllProcesses: (cb: (r: NativeRow[] | undefined) => void) => cb(rows) - })) - } - - it('warns once when our own row comes back with no command line', async () => { - loaderReturning([{ pid: process.pid, ppid: 0, name: 'vitest.exe' }], 2) - await readWindowsProcessTableFresh() - await readWindowsProcessTableFresh() - expect(warn).toHaveBeenCalledTimes(1) - expect(warn.mock.calls[0][0]).toContain('ProcessCommandLineInformation') - }) - - it('stays quiet when our own command line came back', async () => { - loaderReturning(NATIVE, 2) - await readWindowsProcessTableFresh() - expect(warn).not.toHaveBeenCalled() - }) - - it('stays quiet when the read never asked for a command line', async () => { - // A reader that requests identity fields only must not read as a refusal. - loaderReturning([{ pid: process.pid, ppid: 0, name: 'vitest.exe' }], 0) - await readWindowsProcessTableFresh() - expect(warn).not.toHaveBeenCalled() - }) }) diff --git a/src/main/worker-threads/worker-thread-request-queue.ts b/src/main/worker-threads/worker-thread-request-queue.ts index bcc917ac0d6..c98a070f32d 100644 --- a/src/main/worker-threads/worker-thread-request-queue.ts +++ b/src/main/worker-threads/worker-thread-request-queue.ts @@ -133,6 +133,11 @@ export class WorkerThreadRequestQueue< return this.host.retired() } + /** A terminated worker that has not exited yet; nothing new can start until it does. */ + get isRetiring(): boolean { + return this.host.isRetiring + } + private pump(): void { if (this.disposed || this.active || this.queue.length === 0) { return diff --git a/src/main/workspace-hooks/created-worktree-setup-trust.ts b/src/main/workspace-hooks/created-worktree-setup-trust.ts index f9b4fdcd706..1d591ee5bf5 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust.ts @@ -4,8 +4,8 @@ import { getSetupTrustContent } from '../../shared/orca-hook-setup-config' import type { OrcaHooks } from '../../shared/orca-yaml-hook-types' import type { Repo } from '../../shared/repo-types' import type { SetupDecision, SetupTrustMismatch } from '../../shared/worktree/create-types' -import type { ApprovedSetupHashes } from '../../shared/worktree/approved-setup-hashes' -import type { WorktreeDefaultTabsLaunch } from '../../shared/worktree/launch-types' +import type { ApprovedSetupHashes } from '../../shared/worktree/creation/approved-setup-hashes' +import type { WorktreeDefaultTabsLaunch } from '../../shared/worktree/creation/launch-types' import { shouldRunSetupForCreate } from './effective-hook-config' /** Same digest as the renderer's hashOrcaHookScript, so host and prompt hashes compare. */ diff --git a/src/main/workspace-hooks/effective-hook-config.ts b/src/main/workspace-hooks/effective-hook-config.ts index 5391d59ee80..c7114f54b77 100644 --- a/src/main/workspace-hooks/effective-hook-config.ts +++ b/src/main/workspace-hooks/effective-hook-config.ts @@ -7,7 +7,7 @@ import type { } from '../../shared/orca-yaml-hook-types' import type { Repo } from '../../shared/repo-types' import type { SetupDecision } from '../../shared/worktree/create-types' -import type { WorktreeDefaultTabsLaunch } from '../../shared/worktree/launch-types' +import type { WorktreeDefaultTabsLaunch } from '../../shared/worktree/creation/launch-types' function getEffectiveHookScript( yamlScript: string | undefined, diff --git a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts deleted file mode 100644 index 683decf17fd..00000000000 --- a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Repo } from '../../shared/repo-types' - -vi.mock('./effective-hook-config', () => ({ - getEffectiveHooksFromConfig: (_repo: unknown, hooks: unknown) => hooks -})) - -const REPO: Repo = { id: 'r', path: '/repo', displayName: 'r', badgeColor: '#000', addedAt: 0 } - -async function runArchive(script: string, timeoutMs = 400) { - const { runHook } = await import('./hooks') - const dir = mkdtempSync(join(tmpdir(), 'orca-hook-deadline-')) - writeFileSync(join(dir, 'orca.yaml'), `scripts:\n archive: |\n ${script}\n`) - try { - return await runHook('archive', dir, REPO, dir, undefined, { timeoutMs }) - } finally { - rmSync(dir, { recursive: true, force: true }) - } -} - -// Real shells expose SIGTERM traps that exit 0 after an archive timeout (#19334). -describe.skipIf(process.platform === 'win32')('archive hook deadline', () => { - it('fails a hook that traps SIGTERM and exits zero, despite its zero exit', async () => { - const result = await runArchive("trap 'exit 0' TERM; sleep 30") - expect(result.success).toBe(false) - // Missing exitCode keeps the removal verdict unverifiable. - expect(result.exitCode).toBeUndefined() - expect(result.output).toContain('timed out') - }, 20_000) -}) diff --git a/src/main/workspace-hooks/hook-termination-real-process.test.ts b/src/main/workspace-hooks/hook-termination-real-process.test.ts index fc4123fd6e5..54fdb9f5bcc 100644 --- a/src/main/workspace-hooks/hook-termination-real-process.test.ts +++ b/src/main/workspace-hooks/hook-termination-real-process.test.ts @@ -49,14 +49,6 @@ async function survivorsAfterDeadline( // Mocked kill probes cannot prove a process group exists; exercise real signals here. describe.skipIf(process.platform === 'win32')('hook termination against real processes', () => { - it('kills the shell and its child when the deadline expires', async () => { - const { shell, child, output } = await survivorsAfterDeadline( - 'echo "archive step 3 of 7"\nsleep 120 &\necho "$$ $!" > "$PWD/pids"\nwait' - ) - expect({ shell, child }).toEqual({ shell: false, child: false }) - expect(output).toContain('archive step 3 of 7') - }, 30_000) - it('kills a descendant that ignores SIGTERM', async () => { // Only the group SIGKILL can end this one; a SIGTERM to the shell alone leaves it running. const { child } = await survivorsAfterDeadline( diff --git a/src/main/workspace-hooks/hooks-archive-exit-observation.test.ts b/src/main/workspace-hooks/hooks-archive-exit-observation.test.ts index f178a4e1a45..11158084d23 100644 --- a/src/main/workspace-hooks/hooks-archive-exit-observation.test.ts +++ b/src/main/workspace-hooks/hooks-archive-exit-observation.test.ts @@ -77,37 +77,12 @@ async function runArchiveWith( // Real-process timeout/group tests live in hook-termination-real-process.test.ts (#19334). describe('archive hook exit observation', () => { - it.each([ - ['a non-zero exit', 23], - ['a shell command-not-found', 127] - ])('reports %s as the observed exit it is', async (_label, code) => { - await expect(runArchiveWith({ code })).resolves.toMatchObject({ - success: false, - exitCode: code - }) - }) - - it('caps what it retains from a hook that floods stdout', async () => { - const megabyte = 'x'.repeat(1024 * 1024) - const result = await runArchiveWith( - { code: 0 }, - Array.from({ length: 12 }, () => megabyte) - ) - expect(result.output.length).toBeLessThan(11 * 1024 * 1024) - expect(result.output).toContain('output truncated at 10485760 bytes') - }) - it('survives an error on the output stream', async () => { await expect( runArchiveWith({ code: 0 }, ['partial'], new Error('EIO: read failed')) ).resolves.toMatchObject({ success: true }) }) - it('names a signalled exit as one rather than reporting "exit code null"', async () => { - const result = await runArchiveWith({ code: null, signal: 'SIGKILL' }) - expect(result.output).toContain('terminated without reporting an exit code') - }) - it.each([ ['was killed by a signal', { code: null, signal: 'SIGKILL' as const }], // Spawn errors carry string codes; a bare Error would not exercise the numeric-code guard. diff --git a/src/main/workspace-hooks/hooks-orca-yaml-unc-drive.test.ts b/src/main/workspace-hooks/hooks-orca-yaml-unc-drive.test.ts deleted file mode 100644 index 1aba51458e0..00000000000 --- a/src/main/workspace-hooks/hooks-orca-yaml-unc-drive.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type * as NodeFs from 'node:fs' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const fsMock = vi.hoisted(() => ({ existsSync: vi.fn(), readFileSync: vi.fn() })) -vi.mock('node:fs', async (importOriginal) => ({ - ...(await importOriginal()), - ...fsMock -})) - -import { hasHooksFile, hasUnrecognizedOrcaYamlKeys, loadHooks } from './hooks' - -const UNC = String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app` -const DRIVE_YAML = String.raw`C:\src\app\orca.yaml` -const originalPlatform = process.platform - -describe('orca.yaml of a UNC drive-mount repo', () => { - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - // WSL 2.7 refuses Windows access to a drive mount over UNC (existsSync swallows it as false). - fsMock.existsSync.mockImplementation((path: string) => path === DRIVE_YAML) - fsMock.readFileSync.mockImplementation((path: string) => { - if (path !== DRIVE_YAML) { - throw Object.assign(new Error(`EPERM: operation not permitted, open '${path}'`), { - code: 'EPERM' - }) - } - return 'scripts:\n setup: pnpm install\nfutureKey: 1\n' - }) - }) - - afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) - }) - - it('reads the setup hooks through the drive path', () => { - expect(hasHooksFile(UNC)).toBe(true) - expect(loadHooks(UNC)?.scripts?.setup).toBe('pnpm install') - expect(hasUnrecognizedOrcaYamlKeys(UNC)).toBe(true) - expect(fsMock.readFileSync).not.toHaveBeenCalledWith( - expect.stringMatching(/^\\\\/), - expect.anything() - ) - }) -}) diff --git a/src/main/workspace-hooks/hooks-runner.test.ts b/src/main/workspace-hooks/hooks-runner.test.ts deleted file mode 100644 index 45205adbc4f..00000000000 --- a/src/main/workspace-hooks/hooks-runner.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import type * as NodeChildProcess from 'node:child_process' -import type * as NodeFs from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -import { describe, expect, it, vi } from 'vitest' - -const { execFileSyncMock, statSyncMock } = vi.hoisted(() => ({ - execFileSyncMock: vi.fn(), - statSyncMock: vi.fn() -})) - -vi.mock('fs', () => ({ - readFileSync: vi.fn(), - statSync: statSyncMock, - existsSync: vi.fn(), - mkdirSync: vi.fn(), - writeFileSync: vi.fn(), - chmodSync: vi.fn() -})) - -vi.mock('child_process', () => ({ - exec: vi.fn(), - execFileSync: execFileSyncMock, - execFile: vi.fn(), - spawn: vi.fn() -})) - -describe('createSetupRunnerScript', () => { - it.skipIf(process.platform === 'win32')( - 'runs a script whose shebang carries invocation-only bash flags', - async () => { - // Reapplying login/interactive flags through set would abort before the first user line. - const { buildPosixRunnerScript } = await import('./setup-runner-script-text') - const { mkdtempSync, rmSync, writeFileSync } = await vi.importActual('node:fs') - const { execFileSync } = await vi.importActual('node:child_process') - - const dir = mkdtempSync(join(tmpdir(), 'orca-posix-runner-')) - try { - const runnerPath = join(dir, 'setup-runner.sh') - writeFileSync( - runnerPath, - buildPosixRunnerScript('#!/bin/bash -l\necho SETUP_RAN\n'), - 'utf-8' - ) - - expect(execFileSync('bash', [runnerPath], { encoding: 'utf-8' })).toContain('SETUP_RAN') - } finally { - rmSync(dir, { recursive: true, force: true }) - } - } - ) -}) diff --git a/src/main/workspace-hooks/issue-command-file.ts b/src/main/workspace-hooks/issue-command-file.ts index 3825f8d96a9..59d633cfa80 100644 --- a/src/main/workspace-hooks/issue-command-file.ts +++ b/src/main/workspace-hooks/issue-command-file.ts @@ -3,8 +3,8 @@ import { readFileSync, existsSync, mkdirSync, writeFileSync, rmSync } from 'node import { join } from 'node:path' import { loadHooks } from './hooks' import type { GitRuntimeOptions } from '../git/command-runner/git-runtime-options' -import { checkIgnoredPaths } from '../git/source-control/check-ignored-paths' -import { listTrackedPathSpecs } from '../git/source-control/discard-changes' +import { checkIgnoredPaths } from '../git/source-control/ignores/check-ignored-paths' +import { listTrackedPathSpecs } from '../git/source-control/mutations/discard-changes' import { guardWslUncPathAccess, WslDistroStoppedError, diff --git a/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts b/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts index 7cfc2f3b40b..855ae0924ae 100644 --- a/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts +++ b/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts @@ -23,7 +23,7 @@ vi.mock('node:fs', async (importOriginal) => ({ mkdirSync: mocks.mkdirSync, rmSync: mocks.rmSync })) -vi.mock('../git/source-control/check-ignored-paths', () => ({ +vi.mock('../git/source-control/ignores/check-ignored-paths', () => ({ checkIgnoredPaths: vi.fn(async () => new Set([''])) })) vi.mock('./hooks', () => ({ loadHooks: mocks.loadHooks })) @@ -32,7 +32,6 @@ import { readIssueCommandUnlessWslStopped, writeIssueCommandUnlessWslStopped } from './issue-command-file' -import { RuntimeRepositoryIssueCommand } from '../runtime/repositories/runtime-repository-issue-command' const WSL_REPO = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' const HOST_REPO = 'C:\\src\\repo' @@ -67,24 +66,6 @@ describe('issue command reads for a stopped WSL distro (E9)', () => { expect(mocks.loadHooks).not.toHaveBeenCalled() }) - it("gates the runtime read a paired client's Settings pane makes, and passes a launch's wake", async () => { - const reader = new RuntimeRepositoryIssueCommand({ - resolveRepo: async () => ({ - id: 'repo-1', - path: WSL_REPO, - displayName: 'repo', - badgeColor: '#000', - addedAt: 1, - kind: 'git' - }), - getLocalGitArgs: () => [] - }) - await expect(reader.read('id:repo-1')).resolves.toMatchObject({ status: 'error' }) - expect(mocks.loadHooks).not.toHaveBeenCalled() - await reader.read('id:repo-1', { wakeWslDistro: true }) - expect(mocks.loadHooks).toHaveBeenCalledWith(WSL_REPO) - }) - it("refuses a write the user didn't make, leaving the hidden file and the distro alone", async () => { await expect(writeIssueCommandUnlessWslStopped(WSL_REPO, 'x', {})).rejects.toThrow( "WSL distro 'Ubuntu' is not running" @@ -94,27 +75,10 @@ describe('issue command reads for a stopped WSL distro (E9)', () => { expect(mocks.rmSync).not.toHaveBeenCalled() }) - it("saves the user's own edit, a user act that may start the distro", async () => { - await writeIssueCommandUnlessWslStopped(WSL_REPO, 'mine', {}, { wakeWslDistro: true }) - expect(mocks.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining('issue-command'), - 'mine\n', - 'utf-8' - ) - }) - it('refuses a host-path repo whose Git runs in the stopped distro', async () => { await expect( writeIssueCommandUnlessWslStopped(HOST_REPO, 'x', () => ({ wslDistro: 'Ubuntu' })) ).rejects.toThrow("WSL distro 'Ubuntu' is not running") expect(mocks.writeFileSync).not.toHaveBeenCalled() }) - - it('still saves a host-path repo whose runtime awaits repair (no Git distro yet)', async () => { - const repairing = (): never => { - throw new Error('Project runtime requires repair') - } - await writeIssueCommandUnlessWslStopped(HOST_REPO, 'mine', repairing) - expect(mocks.writeFileSync).toHaveBeenCalled() - }) }) diff --git a/src/main/workspace-hooks/worktree-runner-script.ts b/src/main/workspace-hooks/worktree-runner-script.ts index 14b1db3a075..62ed9b16523 100644 --- a/src/main/workspace-hooks/worktree-runner-script.ts +++ b/src/main/workspace-hooks/worktree-runner-script.ts @@ -8,7 +8,8 @@ import { import { scriptDeclaresPosixShell } from '../../shared/workspace-setup/setup-script-shebang' import { resolveWindowsShellStartupFamily } from '../../shared/windows-terminal-shell' import { resolveWindowsGitBashShellPath } from '../pty/shell-startup/git-bash' -import { gitExecFileSync } from '../git/command-runner/git-exec-file-sync' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' +import { withRepositoryGitCause } from '../git/repository-git-cause' import { isLocalGitRuntimeRouterInstalled } from '../git/command-runner/host-routing/local-git-runtime-route' import { readWorktreeGitPath } from '../git/worktrees/catalog/worktree-git-path' import { resolveWslWorktreeGitPath } from '../git/worktrees/catalog/wsl-worktree-git-path' @@ -31,18 +32,26 @@ import { isFolderRepo } from '../../shared/repo-kind' import { buildPosixRunnerScript, buildWindowsRunnerScript } from './setup-runner-script-text' import type { Repo } from '../../shared/repo-types' -import type { WorktreeSetupLaunch } from '../../shared/worktree/launch-types' +import type { WorktreeSetupLaunch } from '../../shared/worktree/creation/launch-types' import type { SetupAgentStartupPolicy } from '../../shared/orca-yaml-hook-types' import type { ProjectExecutionRuntimeResolution } from '../../shared/execution-host/project-execution-runtime' type SetupRunnerShellSettings = Record | undefined -function getGitPath(cwd: string, relativePath: string): string { - return gitExecFileSync(['rev-parse', '--git-path', relativePath], { +async function getGitPath(cwd: string, relativePath: string): Promise { + const { stdout } = await withRepositoryGitCause( cwd, - // Host Git on purpose: a read-only path lookup, kept off a synchronous wsl.exe. - hostGit: true - }).trim() + {}, + { family: 'setup', reason: 'setup-runner', cache: 'uncached' }, + () => + gitExecFileAsync(['rev-parse', '--git-path', relativePath], { + cwd, + // Preserve the native fallback even for a Windows-drive WSL-runtime project. + hostGit: true, + timeout: 15_000 + }) + ) + return stdout.trim() } export async function createSetupRunnerScript( @@ -176,7 +185,7 @@ async function resolveGitRunnerScriptPath( : isLocalGitRuntimeRouterInstalled() ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) : null - let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + let runnerScriptPath = fromLink ?? (await getGitPath(worktreePath, gitRelPath)) // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. if (wslWorktree && !fromLink) { diff --git a/src/main/workspaces/catalog/inline-folder-lineage.ts b/src/main/workspaces/catalog/inline-folder-lineage.ts index 24c5dc1ebdb..827feda33c6 100644 --- a/src/main/workspaces/catalog/inline-folder-lineage.ts +++ b/src/main/workspaces/catalog/inline-folder-lineage.ts @@ -1,5 +1,5 @@ import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' -import { folderLineageEdgeOf } from '../../../shared/worktree/folder-lineage-parents' +import { folderLineageEdgeOf } from '../../../shared/worktree/lineage/folder-lineage-parents' import type { WorkspaceLineage } from '../../../shared/worktree/lineage-types' import type { Worktree } from '../../../shared/worktree/types' import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' diff --git a/src/main/workspaces/catalog/local-worktree-scan-generation.ts b/src/main/workspaces/catalog/local-worktree-scan-generation.ts index 5a13b2ac716..dc35b2dbe0b 100644 --- a/src/main/workspaces/catalog/local-worktree-scan-generation.ts +++ b/src/main/workspaces/catalog/local-worktree-scan-generation.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto' -import type { WorktreeCatalogVersion } from '../../../shared/worktree/catalog-version' +import type { WorktreeCatalogVersion } from '../../../shared/worktree/catalog/catalog-version' const generationByRepoId = new Map() let generationSequence = 0 @@ -25,9 +25,37 @@ export function getLocalWorktreeScanGeneration(repoId: string): number { return generation } +const routeInputListeners = new Set<() => void>() +let routeInputsRevision = 0 +let routeInputNotificationQueued = false + +/** Repo, project and runtime-setting writes change which route runs a repo's Git; listeners run after the write. */ +export function onWorktreeRouteInputsChanged(listener: () => void): void { + routeInputListeners.add(listener) +} + +/** Advances synchronously so readers never trust a route snapshot taken before the write. */ +export function getWorktreeRouteInputsRevision(): number { + return routeInputsRevision +} + +export function markWorktreeRouteInputsChanged(): void { + routeInputsRevision += 1 + if (routeInputListeners.size > 0 && !routeInputNotificationQueued) { + routeInputNotificationQueued = true + queueMicrotask(() => { + routeInputNotificationQueued = false + for (const listener of routeInputListeners) { + listener() + } + }) + } +} + export function bumpLocalWorktreeScanGeneration(repoId: string): void { generationByRepoId.set(repoId, ++generationSequence) mutationRevision += 1 + markWorktreeRouteInputsChanged() } export function forgetLocalWorktreeScanGeneration(repoId: string): void { diff --git a/src/main/workspaces/catalog/repo-maintenance-idle-gate.ts b/src/main/workspaces/catalog/repo-maintenance-idle-gate.ts index 1d022caa576..fb104981937 100644 --- a/src/main/workspaces/catalog/repo-maintenance-idle-gate.ts +++ b/src/main/workspaces/catalog/repo-maintenance-idle-gate.ts @@ -1,4 +1,4 @@ -import { app, powerMonitor } from 'electron' +import { powerMonitor } from 'electron' import { disposeLocalRepoRefMaintenance, postponeRepoRefMaintenance, @@ -30,13 +30,8 @@ export function installRepoMaintenanceIdleGate( const onBattery = (): void => { postponeRepoRefMaintenance() } - const onFocus = (): void => { - postponeRepoRefMaintenance() - } powerMonitor.on('on-battery', onBattery) - app.on('browser-window-focus', onFocus) return () => { - app.off('browser-window-focus', onFocus) powerMonitor.off('on-battery', onBattery) // Stop armed timers before removing the activity probe. const stopped = disposeLocalRepoRefMaintenance() diff --git a/src/main/workspaces/catalog/repo-worktree-catalog-observation.ts b/src/main/workspaces/catalog/repo-worktree-catalog-observation.ts new file mode 100644 index 00000000000..fb6082c5f2b --- /dev/null +++ b/src/main/workspaces/catalog/repo-worktree-catalog-observation.ts @@ -0,0 +1,70 @@ +import type { GitWorktreeInfo } from '../../../shared/worktree/types' +import type { NativeLocalWorktreeMetadataScanExpectation } from '../../persistence/tracking-repos/missing-local-worktree-metadata-pruning' + +/** One `git worktree list`; a confirmed missing/non-repo stays distinct from a failed run. */ +export type WorktreeCatalogOutcome = + | { kind: 'rows'; worktrees: GitWorktreeInfo[] } + | { kind: 'true-empty' } + | { kind: 'failed'; error: unknown } + +/** Captured before Git runs; destructive consumers claim it at most once. */ +export type WorktreeCatalogWitness = { + readonly authorizedRootsRevision: number + /** Roots revision after this observation registered its roots; later side effects fence on it. */ + rootsRevision: number + readonly hygieneDue: boolean + readonly expectation?: NativeLocalWorktreeMetadataScanExpectation + /** Returns an unconsumed claim so the evidence gate can re-arm. */ + readonly release: () => void +} + +export type WorktreeCatalogObservation = { + readonly outcome: WorktreeCatalogOutcome + /** Scan start: verification never moves it, so the full-list ceiling cannot slide. */ + readonly startedAt: number + readonly generation: number + readonly revision: number + /** Only runtime-started flights fingerprint first; without one the rows cannot be verified. */ + readonly adminFingerprint: Promise | null + readonly startedBy: WorktreeCatalogReaderKind + witness: WorktreeCatalogWitness | undefined + /** Scan start, or the latest verifier answer that let a runtime reader reuse these rows. */ + confirmedAt: number +} + +export type WorktreeCatalogFlightPlan = { + scan: () => Promise + captureWitness?: () => WorktreeCatalogWitness | undefined + observed?: (observation: WorktreeCatalogObservation) => void +} + +export type WorktreeCatalogVerifier = { + /** Full-list ceiling measured from scan start. */ + ceilingMs: number + /** One outstanding probe per repo; 'in-flight' and timeouts reuse rows without proving them (#19312). */ + probe: () => Promise | 'in-flight' + timeoutMs: number + onUnknown?: (reason: string) => void +} + +export type WorktreeCatalogReaderKind = 'desktop' | 'runtime' + +export type WorktreeCatalogRequirement = { + kind: WorktreeCatalogReaderKind + /** Oldest confirmation this reader accepts; a fresher demand refreshes the shared observation. */ + maxAgeMs: number + /** Reuse failures only from this reader kind's own attempts; another kind's failure never blacks out a retry. */ + reusesFailure?: boolean + verifier?: WorktreeCatalogVerifier + /** Trailing flights this read follows when mutations overtake it; callers with their own rescan loop keep 1. */ + overtakenFlights?: number + /** Destructive hygiene is due: rows without a pre-scan hygiene claim are not good enough for this reader. */ + needsHygieneClaim?: () => boolean +} + +export type WorktreeCatalogRead = { + /** Null only for a request whose route was replaced before any observation existed. */ + observation: WorktreeCatalogObservation | null + /** Invalidations kept overtaking scans; callers must not treat these rows as authoritative. */ + superseded: boolean +} diff --git a/src/main/workspaces/catalog/repo-worktree-catalog-owner.test.ts b/src/main/workspaces/catalog/repo-worktree-catalog-owner.test.ts new file mode 100644 index 00000000000..2cb0ac67dad --- /dev/null +++ b/src/main/workspaces/catalog/repo-worktree-catalog-owner.test.ts @@ -0,0 +1,268 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../../shared/repo-types' +import type { GitWorktreeInfo } from '../../../shared/worktree/types' +import { bumpWorktreeScanGeneration } from '../../git/worktrees/catalog/worktree-scan-cache' +import { setWorktreeCatalogRouteResolver } from './repo-worktree-catalog-route' +import { markWorktreeRouteInputsChanged } from './local-worktree-scan-generation' +import { notifyWslDiscoveryChanged } from '../../wsl/discovery/wsl-discovery-change' +import { + _getWorktreeCatalogOwnerSizeForTests, + _resetWorktreeCatalogOwnerForTests, + retireObsoleteWorktreeCatalogs, + invalidateWorktreeCatalogForRepo, + isCurrentWorktreeCatalogObservation, + readWorktreeCatalog +} from './repo-worktree-catalog-owner' +import type { + WorktreeCatalogFlightPlan, + WorktreeCatalogOutcome +} from './repo-worktree-catalog-observation' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the owner reads only these repo fields. +const repo = { id: 'repo-1', path: '/repos/app', kind: 'git' } as Repo +const row = (path: string): GitWorktreeInfo => ({ + path, + head: 'abc', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: path === '/repos/app' +}) +const desktop = { kind: 'desktop', maxAgeMs: 5_000, overtakenFlights: 3 } as const +const runtime = { + kind: 'runtime', + maxAgeMs: 30_000, + reusesFailure: true, + overtakenFlights: 3 +} as const + +function scanner(outcomes: WorktreeCatalogOutcome[]) { + let resolveNext: (() => void) | null = null + const plan: WorktreeCatalogFlightPlan & { calls: number; gate: boolean; release: () => void } = { + calls: 0, + gate: false, + release: () => resolveNext?.(), + scan: async () => { + const outcome = outcomes[Math.min(plan.calls, outcomes.length - 1)] + plan.calls += 1 + if (plan.gate) { + await new Promise((resolve) => { + resolveNext = resolve + }) + } + if (outcome.kind === 'failed') { + throw outcome.error + } + return outcome + } + } + return plan +} + +const rows = (...paths: string[]): WorktreeCatalogOutcome => ({ + kind: 'rows', + worktrees: paths.map(row) +}) + +describe('repo worktree catalog owner', () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + }) + afterEach(() => { + setWorktreeCatalogRouteResolver(null) + _resetWorktreeCatalogOwnerForTests() + vi.useRealTimers() + }) + + it('serves the sidebar and the runtime from one observation within each reader’s accepted age', async () => { + const plan = scanner([rows('/repos/app'), rows('/repos/app', '/repos/app-feature')]) + + await readWorktreeCatalog(repo, 'local:default', desktop, plan) + vi.advanceTimersByTime(4_000) + const runtimeRead = await readWorktreeCatalog(repo, 'local:default', runtime, plan) + expect(plan.calls).toBe(1) + expect(runtimeRead.observation?.outcome).toEqual(rows('/repos/app')) + + vi.advanceTimersByTime(2_000) + const sidebarRead = await readWorktreeCatalog(repo, 'local:default', desktop, plan) + expect(plan.calls).toBe(2) + expect(sidebarRead.observation?.outcome).toEqual(rows('/repos/app', '/repos/app-feature')) + }) + + it('withdraws destructive authority from rows a newer listing replaced', async () => { + const plan = scanner([rows('/repos/app', '/repos/app-old'), rows('/repos/app')]) + const first = await readWorktreeCatalog(repo, 'local:default', desktop, plan) + vi.advanceTimersByTime(6_000) + + const second = await readWorktreeCatalog(repo, 'local:default', desktop, plan) + + expect(isCurrentWorktreeCatalogObservation(first.observation!)).toBe(false) + expect(isCurrentWorktreeCatalogObservation(second.observation!)).toBe(true) + }) + + it('does not let a runtime verification stretch the sidebar past its 5 seconds', async () => { + const plan = scanner([rows('/repos/app'), rows('/repos/app', '/repos/app-external')]) + const verifier = { + ceilingMs: 300_000, + timeoutMs: 1_000, + probe: () => Promise.resolve('fingerprint-1') + } + await readWorktreeCatalog(repo, 'local:default', { ...runtime, verifier }, plan) + vi.advanceTimersByTime(31_000) + const verified = await readWorktreeCatalog( + repo, + 'local:default', + { ...runtime, verifier }, + plan + ) + expect(plan.calls).toBe(1) + expect(verified.observation?.outcome).toEqual(rows('/repos/app')) + + const sidebar = await readWorktreeCatalog(repo, 'local:default', desktop, plan) + + expect(plan.calls).toBe(2) + expect(sidebar.observation?.outcome).toEqual(rows('/repos/app', '/repos/app-external')) + }) + + it('moves readers that joined an overtaken scan onto one trailing scan', async () => { + const plan = scanner([rows('/repos/app'), rows('/repos/app', '/repos/app-new')]) + plan.gate = true + const first = readWorktreeCatalog(repo, 'local:default', runtime, plan) + const joined = readWorktreeCatalog(repo, 'local:default', desktop, plan) + invalidateWorktreeCatalogForRepo(repo.id) + plan.release() + await vi.waitFor(() => expect(plan.calls).toBe(2)) + plan.release() + + for (const read of await Promise.all([first, joined])) { + expect(read.superseded).toBe(false) + expect(read.observation?.outcome).toEqual(rows('/repos/app', '/repos/app-new')) + } + expect(plan.calls).toBe(2) + }) + + it('stops reusing settled rows after a Git-layer mutation of the repo path', async () => { + const plan = scanner([rows('/repos/app'), rows('/repos/app', '/repos/app-added')]) + await readWorktreeCatalog(repo, 'local:default', runtime, plan) + + bumpWorktreeScanGeneration('/repos/app') + const read = await readWorktreeCatalog(repo, 'local:default', runtime, plan) + + expect(plan.calls).toBe(2) + expect(read.observation?.outcome).toEqual(rows('/repos/app', '/repos/app-added')) + }) + + it('never lets a sidebar failure stop the runtime from listing', async () => { + const plan = scanner([{ kind: 'failed', error: new Error('index.lock') }, rows('/repos/app')]) + const failed = await readWorktreeCatalog(repo, 'local:default', desktop, plan) + expect(failed.observation?.outcome.kind).toBe('failed') + + const read = await readWorktreeCatalog(repo, 'local:default', runtime, plan) + + expect(plan.calls).toBe(2) + expect(read.observation?.outcome).toEqual(rows('/repos/app')) + }) + + it('retires the old Git runtime so switching back lists again', async () => { + const plan = scanner([ + rows('/repos/app'), + rows('/repos/app'), + rows('/repos/app', '/repos/app-new') + ]) + await readWorktreeCatalog(repo, 'local:native', runtime, plan) + await readWorktreeCatalog(repo, 'local:wsl:Ubuntu', runtime, plan) + + const back = await readWorktreeCatalog(repo, 'local:native', runtime, plan) + + expect(plan.calls).toBe(3) + expect(back.observation?.outcome).toEqual(rows('/repos/app', '/repos/app-new')) + }) + + it('lets a request admitted for a replaced runtime neither list nor retire the live one', async () => { + let live = { repoPath: '/repos/app', runtimeKey: 'local:native' } + setWorktreeCatalogRouteResolver(() => live) + const plan = scanner([rows('/repos/app')]) + await readWorktreeCatalog(repo, 'local:native', runtime, plan) + + const delayed = await readWorktreeCatalog(repo, 'local:wsl:Ubuntu', runtime, plan) + const current = await readWorktreeCatalog(repo, 'local:native', runtime, plan) + + expect(delayed).toEqual({ observation: null, superseded: true }) + expect(current.superseded).toBe(false) + expect(plan.calls).toBe(1) + live = { repoPath: '/repos/app-moved', runtimeKey: 'local:native' } + retireObsoleteWorktreeCatalogs() + expect(await readWorktreeCatalog(repo, 'local:native', runtime, plan)).toMatchObject({ + superseded: true + }) + expect(plan.calls).toBe(1) + }) + + it('retires an idle owner when a route input or WSL discovery answer changes, with no reader', async () => { + let live: { repoPath: string; runtimeKey: string } | null = { + repoPath: '/repos/app', + runtimeKey: 'local:default' + } + setWorktreeCatalogRouteResolver(() => live) + const plan = scanner([rows('/repos/app')]) + await readWorktreeCatalog(repo, 'local:default', runtime, plan) + expect(_getWorktreeCatalogOwnerSizeForTests()).toBe(1) + + live = { repoPath: '/repos/app', runtimeKey: 'local:wsl:Ubuntu' } + notifyWslDiscoveryChanged() + expect(_getWorktreeCatalogOwnerSizeForTests()).toBe(0) + + live = { repoPath: '/repos/app', runtimeKey: 'local:default' } + await readWorktreeCatalog(repo, 'local:default', runtime, plan) + live = null + markWorktreeRouteInputsChanged() + await Promise.resolve() + expect(_getWorktreeCatalogOwnerSizeForTests()).toBe(0) + }) + + it('keeps a scan that outlived its repo path out of the live catalog', async () => { + let live = { repoPath: '/repos/app', runtimeKey: 'local:default' } + setWorktreeCatalogRouteResolver(() => live) + const plan = scanner([rows('/repos/app')]) + plan.gate = true + const held = readWorktreeCatalog(repo, 'local:default', runtime, plan) + live = { repoPath: '/repos/app-renamed', runtimeKey: 'local:default' } + plan.release() + + expect((await held).superseded).toBe(true) + expect(plan.calls).toBe(1) + }) + + it('reuses a mismatching verification probe as the rescan fingerprint', async () => { + let fingerprint = 'fingerprint-1' + const probe = vi.fn(() => Promise.resolve(fingerprint)) + const verifier = { ceilingMs: 300_000, timeoutMs: 1_000, probe } + const plan = scanner([rows('/repos/app'), rows('/repos/app', '/repos/app-new')]) + await readWorktreeCatalog(repo, 'local:default', { ...runtime, verifier }, plan) + vi.advanceTimersByTime(31_000) + fingerprint = 'fingerprint-2' + + await readWorktreeCatalog(repo, 'local:default', { ...runtime, verifier }, plan) + + expect(plan.calls).toBe(2) + expect(probe).toHaveBeenCalledTimes(2) + }) + + it('returns an unclaimed hygiene claim when a newer observation replaces it', async () => { + const release = vi.fn() + const plan = { + ...scanner([rows('/repos/app')]), + captureWitness: () => ({ + authorizedRootsRevision: 1, + rootsRevision: 1, + hygieneDue: true, + release + }) + } + await readWorktreeCatalog(repo, 'local:default', desktop, plan) + invalidateWorktreeCatalogForRepo(repo.id) + + await readWorktreeCatalog(repo, 'local:default', desktop, plan) + + expect(release).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/workspaces/catalog/repo-worktree-catalog-owner.ts b/src/main/workspaces/catalog/repo-worktree-catalog-owner.ts new file mode 100644 index 00000000000..fe2778f0032 --- /dev/null +++ b/src/main/workspaces/catalog/repo-worktree-catalog-owner.ts @@ -0,0 +1,325 @@ +import type { Repo } from '../../../shared/repo-types' +import { getRepoExecutionHostId } from '../../../shared/execution-host' +import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' +import { onWorktreeScanGenerationBump } from '../../git/worktrees/catalog/worktree-scan-cache' +import { preserveFolderUpgradeWorktreePath } from './folder-upgrade-worktree-path' +import type { + WorktreeCatalogOutcome, + WorktreeCatalogObservation, + WorktreeCatalogFlightPlan, + WorktreeCatalogRequirement, + WorktreeCatalogRead +} from './repo-worktree-catalog-observation' +import { + getLocalWorktreeScanGeneration, + isLocalWorktreeScanGenerationCurrent, + onWorktreeRouteInputsChanged +} from './local-worktree-scan-generation' +import { + isLiveWorktreeCatalogRoute, + setWorktreeCatalogRouteResolver +} from './repo-worktree-catalog-route' +import { verify } from './repo-worktree-catalog-verification' +import { onWslDiscoveryChanged } from '../../wsl/discovery/wsl-discovery-change' + +type Flight = { + revision: number + promise: Promise +} + +type Entry = { + repoId: string + hostId: string + repoPath: string + runtimeKey: string + revision: number + retired: boolean + success: WorktreeCatalogObservation | null + failure: WorktreeCatalogObservation | null + flight: Flight | null +} + +const entries = new Map() + +onWorktreeScanGenerationBump((repoPath) => invalidateWorktreeCatalogForRepoPath(repoPath)) +// Route-changing writes and WSL discovery answers retire obsolete owners even when no reader follows. +onWorktreeRouteInputsChanged(() => retireObsoleteWorktreeCatalogs()) +onWslDiscoveryChanged(() => retireObsoleteWorktreeCatalogs()) +const entryByObservation = new WeakMap() + +/** Owner identity: repo, host and the project runtime that runs Git (distro, selected Git, repair state). */ +function entryKey(repoId: string, hostId: string, runtimeKey: string): string { + return `${repoId}\0${hostId}\0${runtimeKey}` +} + +function releaseWitness(observation: WorktreeCatalogObservation | null): void { + const witness = observation?.witness + if (witness) { + observation.witness = undefined + witness.release() + } +} + +function retireEntry(key: string, entry: Entry): void { + entries.delete(key) + entry.retired = true + entry.revision += 1 + releaseWitness(entry.success) +} + +function isLive(entry: Entry): boolean { + return ( + !entry.retired && + isLiveWorktreeCatalogRoute(entry.repoId, entry.hostId, { + repoPath: entry.repoPath, + runtimeKey: entry.runtimeKey + }) + ) +} + +/** The owner for a live route; only a live route may create it or retire the repo's other routes. */ +function resolveEntry(repo: Repo, runtimeKey: string): Entry { + const hostId = getRepoExecutionHostId(repo) + const key = entryKey(repo.id, hostId, runtimeKey) + const scope = entryKey(repo.id, hostId, '') + for (const [candidateKey, candidate] of entries) { + // One project runtime runs a repo's Git at a time; rows from another route are obsolete. + if ( + candidateKey.startsWith(scope) && + (candidateKey !== key || !areWorktreePathsEqual(candidate.repoPath, repo.path)) + ) { + retireEntry(candidateKey, candidate) + } + } + let entry = entries.get(key) + if (!entry) { + entry = { + repoId: repo.id, + hostId, + repoPath: repo.path, + runtimeKey, + revision: 0, + retired: false, + success: null, + failure: null, + flight: null + } + entries.set(key, entry) + } + return entry +} + +function isCurrent(entry: Entry, observation: WorktreeCatalogObservation): boolean { + return ( + observation.revision === entry.revision && + isLocalWorktreeScanGenerationCurrent(entry.repoId, observation.generation) && + isLive(entry) + ) +} + +function startFlight( + entry: Entry, + repo: Repo, + requirement: WorktreeCatalogRequirement, + plan: WorktreeCatalogFlightPlan, + pendingProbe: Promise | null +): Flight { + // Capture before Git can yield so a concurrent mutation is never stamped as observed. + const revision = entry.revision + const generation = getLocalWorktreeScanGeneration(entry.repoId) + const startedAt = Date.now() + const probe = pendingProbe ?? requirement.verifier?.probe() ?? null + const adminFingerprint = probe && probe !== 'in-flight' ? probe : null + const witness = plan.captureWitness?.() + const flight: Flight = { + revision, + promise: plan + .scan() + .catch((error: unknown): WorktreeCatalogOutcome => ({ kind: 'failed', error })) + .then((outcome) => { + const observation: WorktreeCatalogObservation = { + outcome: + outcome.kind === 'rows' + ? // Owners are per repo id, so this registration's locator cannot leak into another. + { + kind: 'rows', + worktrees: preserveFolderUpgradeWorktreePath(repo, outcome.worktrees) + } + : outcome, + startedAt, + generation, + revision, + adminFingerprint, + startedBy: requirement.kind, + witness, + confirmedAt: startedAt + } + entryByObservation.set(observation, entry) + if (entry.flight === flight) { + entry.flight = null + } + publish(entry, observation, plan) + return observation + }) + } + entry.flight = flight + return flight +} + +function publish( + entry: Entry, + observation: WorktreeCatalogObservation, + plan: WorktreeCatalogFlightPlan +): void { + const live = isLive(entry) + if (observation.outcome.kind === 'failed') { + // Like the evidence gate's own claim, a failed pass is not retried on every read (#17775); new evidence re-arms it. + observation.witness = undefined + if (live && (entry.failure?.startedAt ?? -1) <= observation.startedAt) { + entry.failure = observation + } + return + } + // An obsolete route or a newer published observation keeps late completions out. + if (!live || (entry.success?.startedAt ?? -1) > observation.startedAt) { + releaseWitness(observation) + return + } + releaseWitness(entry.success) + entry.success = observation + if (entry.failure && entry.failure.startedAt <= observation.startedAt) { + entry.failure = null + } + if (isCurrent(entry, observation)) { + plan.observed?.(observation) + } +} + +function acceptable( + observation: WorktreeCatalogObservation, + requirement: WorktreeCatalogRequirement, + now: number +): boolean { + if (requirement.needsHygieneClaim?.() && !observation.witness?.hygieneDue) { + return false + } + // Verifier confirmations are a runtime admission; other readers need a full observation that young. + const basis = requirement.verifier ? observation.confirmedAt : observation.startedAt + return now - basis <= requirement.maxAgeMs +} + +/** The sole owner of a repo's raw worktree rows: readers state what they accept and share its one flight. */ +export async function readWorktreeCatalog( + repo: Repo, + runtimeKey: string, + requirement: WorktreeCatalogRequirement, + plan: WorktreeCatalogFlightPlan +): Promise { + const hostId = getRepoExecutionHostId(repo) + // A request admitted for a route the registration has since replaced runs no Git and retires nothing. + if (!isLiveWorktreeCatalogRoute(repo.id, hostId, { repoPath: repo.path, runtimeKey })) { + const known = entries.get(entryKey(repo.id, hostId, runtimeKey))?.success ?? null + return { observation: known, superseded: true } + } + const entry = resolveEntry(repo, runtimeKey) + let last: WorktreeCatalogObservation | null = null + for (let flights = 0; flights < (requirement.overtakenFlights ?? 1); flights += 1) { + const now = Date.now() + const failure = entry.failure + if ( + requirement.reusesFailure && + failure?.startedBy === requirement.kind && + isCurrent(entry, failure) && + now - failure.startedAt <= requirement.maxAgeMs + ) { + return { observation: failure, superseded: false } + } + const success = entry.success + let pendingProbe: Promise | null = null + if (success && isCurrent(entry, success)) { + if (acceptable(success, requirement, now)) { + return { observation: success, superseded: false } + } + if (requirement.verifier && !requirement.needsHygieneClaim?.()) { + const verification = await verify(success, requirement.verifier, now) + if (verification.reuse && entry.success === success && isCurrent(entry, success)) { + success.confirmedAt = Math.max(success.confirmedAt, Date.now()) + return { observation: success, superseded: false } + } + pendingProbe = verification.reuse ? null : verification.probe + } + } + // The route can be replaced across any await; obsolete readers never start Git. + if (!isLive(entry)) { + break + } + // At most one flight per owner: a reader arriving after an invalidation waits for the + // overtaken flight, then starts the single trailing one. + last = await (entry.flight ?? startFlight(entry, repo, requirement, plan, pendingProbe)).promise + if (isCurrent(entry, last)) { + return { observation: last, superseded: false } + } + } + return { observation: last ?? entry.success, superseded: true } +} + +/** Last known observation, current or not, for last-known fallbacks and projections. */ +export function peekWorktreeCatalog( + repo: Repo, + runtimeKey: string +): { observation: WorktreeCatalogObservation; current: boolean } | null { + const entry = entries.get(entryKey(repo.id, getRepoExecutionHostId(repo), runtimeKey)) + const observation = entry?.success + if (!entry || !observation || !areWorktreePathsEqual(entry.repoPath, repo.path)) { + return null + } + return { observation, current: isCurrent(entry, observation) } +} + +/** Destructive consumers recheck this after their own awaits, with the owner's own authority rules. */ +export function isCurrentWorktreeCatalogObservation( + observation: WorktreeCatalogObservation +): boolean { + const entry = entryByObservation.get(observation) + // A newer published success supersedes this one even when nothing invalidated the owner. + return entry !== undefined && entry.success === observation && isCurrent(entry, observation) +} + +/** Stops readers from reusing settled rows; joiners of an older flight follow the next one. */ +export function invalidateWorktreeCatalogForRepo(repoId: string): void { + for (const entry of entries.values()) { + if (entry.repoId === repoId) { + entry.revision += 1 + } + } +} + +/** Git-layer mutations know only the path; every namespace listing it is stale. */ +export function invalidateWorktreeCatalogForRepoPath(repoPath: string): void { + for (const entry of entries.values()) { + if (areWorktreePathsEqual(entry.repoPath, repoPath)) { + entry.revision += 1 + } + } +} + +/** Drop owners whose repo, host, path or project runtime is no longer the live route. */ +export function retireObsoleteWorktreeCatalogs(): void { + for (const [key, entry] of entries) { + if (!isLive(entry)) { + retireEntry(key, entry) + } + } +} + +export function _resetWorktreeCatalogOwnerForTests(): void { + // Shared test workers outlive the runtime whose store registered the resolver. + setWorktreeCatalogRouteResolver(null) + for (const [key, entry] of entries) { + retireEntry(key, entry) + } +} + +export function _getWorktreeCatalogOwnerSizeForTests(): number { + return entries.size +} diff --git a/src/main/workspaces/catalog/repo-worktree-catalog-route.ts b/src/main/workspaces/catalog/repo-worktree-catalog-route.ts new file mode 100644 index 00000000000..5bc7daebc84 --- /dev/null +++ b/src/main/workspaces/catalog/repo-worktree-catalog-route.ts @@ -0,0 +1,30 @@ +import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' + +/** Where a registered repo's Git runs right now: its path and project-runtime cache key. */ +export type WorktreeCatalogRoute = Readonly<{ repoPath: string; runtimeKey: string }> + +type RouteResolver = (repoId: string, hostId: string) => WorktreeCatalogRoute | null + +let resolveLiveRoute: RouteResolver | null = null + +/** The live registration decides which route is authoritative, never whichever request arrives last. */ +export function setWorktreeCatalogRouteResolver(resolver: RouteResolver | null): void { + resolveLiveRoute = resolver +} + +/** Without a registered store every request is taken as live (isolated unit callers). */ +export function isLiveWorktreeCatalogRoute( + repoId: string, + hostId: string, + route: WorktreeCatalogRoute +): boolean { + if (!resolveLiveRoute) { + return true + } + const live = resolveLiveRoute(repoId, hostId) + return ( + live !== null && + live.runtimeKey === route.runtimeKey && + areWorktreePathsEqual(live.repoPath, route.repoPath) + ) +} diff --git a/src/main/workspaces/catalog/repo-worktree-catalog-verification.ts b/src/main/workspaces/catalog/repo-worktree-catalog-verification.ts new file mode 100644 index 00000000000..82e064d2b5f --- /dev/null +++ b/src/main/workspaces/catalog/repo-worktree-catalog-verification.ts @@ -0,0 +1,41 @@ +import type { + WorktreeCatalogObservation, + WorktreeCatalogVerifier +} from './repo-worktree-catalog-observation' + +type Verification = { reuse: true } | { reuse: false; probe: Promise | null } + +/** Reuse when a probe proves, or cannot yet disprove (#19312), that rows fingerprinted before their scan still hold. */ +export async function verify( + observation: WorktreeCatalogObservation, + verifier: WorktreeCatalogVerifier, + now: number +): Promise { + // Without a fingerprint from before its scan, no probe can certify these rows. + if ( + observation.outcome.kind !== 'rows' || + !observation.adminFingerprint || + now - observation.startedAt >= verifier.ceilingMs + ) { + return { reuse: false, probe: null } + } + const probe = verifier.probe() + if (probe === 'in-flight') { + verifier.onUnknown?.('previous probe still pending') + return { reuse: true } + } + let timer: ReturnType | undefined + const timeout = new Promise<'timeout'>((resolve) => { + timer = setTimeout(() => resolve('timeout'), verifier.timeoutMs) + }) + const current = await Promise.race([probe, timeout]).finally(() => clearTimeout(timer)) + if (current === 'timeout') { + // Unknown is not proof, but rescanning slow mounts on every read amplifies load (#19312). + verifier.onUnknown?.('probe expired') + return { reuse: true } + } + // A mismatching probe was taken before the rescan, so it becomes that scan's fingerprint. + return current !== null && (await observation.adminFingerprint) === current + ? { reuse: true } + : { reuse: false, probe } +} diff --git a/src/main/workspaces/catalog/repo-worktrees.ts b/src/main/workspaces/catalog/repo-worktrees.ts index 1918d0f7d55..db25e17ea60 100644 --- a/src/main/workspaces/catalog/repo-worktrees.ts +++ b/src/main/workspaces/catalog/repo-worktrees.ts @@ -11,7 +11,7 @@ import { isFolderRepo } from '../../../shared/repo-kind' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { resolveGitRouteForHost } from '../../providers/execution-host-provider-dispatch' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' -import { WorktreeCatalogUnavailableError } from '../../../shared/worktree/worktree-catalog-availability' +import { WorktreeCatalogUnavailableError } from '../../../shared/worktree/catalog/worktree-catalog-availability' type LocalRepoWorktreeListOptions = { wslDistro?: string diff --git a/src/main/workspaces/catalog/worktree-lineage-pruning.ts b/src/main/workspaces/catalog/worktree-lineage-pruning.ts index 9a701ff5def..dee252dd783 100644 --- a/src/main/workspaces/catalog/worktree-lineage-pruning.ts +++ b/src/main/workspaces/catalog/worktree-lineage-pruning.ts @@ -92,7 +92,11 @@ export function pruneLineageForMissingRepoWorktrees( ) ) const isLive = (worktreeId: string): boolean => { - if (liveIds.has(worktreeId) || preservedMetadataCandidateIds?.has(worktreeId)) { + if ( + liveIds.has(worktreeId) || + preservedMetadataCandidateIds?.has(worktreeId) || + store.getWorktreeMeta(worktreeId)?.archivedCheckout + ) { return true } const worktreePath = splitWorktreeId(worktreeId)?.worktreePath diff --git a/src/main/workspaces/cleanup/workspace-cleanup-client-unsaved-editors.ts b/src/main/workspaces/cleanup/workspace-cleanup-client-unsaved-editors.ts new file mode 100644 index 00000000000..cd06facb634 --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-client-unsaved-editors.ts @@ -0,0 +1,48 @@ +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' + +// Per host runtime, per client socket, per reporting window: the workspaces holding unsaved editor buffers. +const reportsByRuntime = new WeakMap< + OrcaRuntimeService, + Map>> +>() + +/** Replaces what one client window reported; every report on a socket goes away when it closes. */ +export function reportClientUnsavedEditors( + runtime: OrcaRuntimeService, + connectionId: string, + reporterId: string, + worktreeIds: readonly string[] +): void { + let reports = reportsByRuntime.get(runtime) + if (!reports) { + reports = new Map() + reportsByRuntime.set(runtime, reports) + } + let byReporter = reports.get(connectionId) + if (!byReporter) { + byReporter = new Map() + reports.set(connectionId, byReporter) + const owned = reports + runtime.registerSubscriptionCleanup( + `workspace-cleanup-unsaved-editors:${connectionId}`, + () => { + owned.delete(connectionId) + }, + connectionId + ) + } + byReporter.set(reporterId, new Set(worktreeIds)) +} + +/** Workspaces any connected client has unsaved editor buffers in. */ +export function listClientUnsavedEditorWorktreeIds(runtime: OrcaRuntimeService): Set { + const ids = new Set() + for (const byReporter of reportsByRuntime.get(runtime)?.values() ?? []) { + for (const reported of byReporter.values()) { + for (const id of reported) { + ids.add(id) + } + } + } + return ids +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-enabled-rules.ts b/src/main/workspaces/cleanup/workspace-cleanup-enabled-rules.ts new file mode 100644 index 00000000000..b977d5118ee --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-enabled-rules.ts @@ -0,0 +1,22 @@ +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { + resolveWorkspaceCleanupPolicy, + WORKSPACE_CLEANUP_RULE_KEYS +} from '../../../shared/workspace-cleanup/workspace-cleanup-policy' +import { listWorkspaceCleanupOwnedRepos } from './workspace-cleanup-run-evidence' + +/** One entry per rule on in a project this process cleans; a new entry means a rule was turned on or changed. */ +export function listEnabledWorkspaceCleanupRules(store: RuntimeStore): Set { + const settings = store.getSettings() + const enabled = new Set() + for (const repo of listWorkspaceCleanupOwnedRepos(store).values()) { + const { rules } = resolveWorkspaceCleanupPolicy(settings, repo) + for (const key of WORKSPACE_CLEANUP_RULE_KEYS) { + if (rules[key].enabled) { + // keepWhen decides what counts as local work, so loosening it can make a workspace removable. + enabled.add(`${repo.id}:${key}:${JSON.stringify(rules[key])}:${rules.keepWhen}`) + } + } + } + return enabled +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-removal-step.ts b/src/main/workspaces/cleanup/workspace-cleanup-removal-step.ts new file mode 100644 index 00000000000..a0dc9e6f25e --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-removal-step.ts @@ -0,0 +1,130 @@ +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { + queueWorkspaceArchive, + queueWorkspaceDelete +} from '../../runtime/workspaces/lifecycle/workspace-lifecycle-commands' +import { getEffectiveHooks } from '../../workspace-hooks/hooks' +import { errorMessage } from '../../../shared/error-message' +import { + evaluateWorkspaceCleanup, + type WorkspaceCleanupEvaluation +} from '../../../shared/workspace-cleanup/workspace-cleanup-evaluation' +import type { WorkspaceCleanupRules } from '../../../shared/workspace-cleanup/workspace-cleanup-policy' +import type { WorkspaceCleanupRunRow } from '../../../shared/workspace-cleanup/workspace-cleanup-run' +import { + collectWorkspaceCleanupWorkspaces, + type WorkspaceCleanupWorkspace +} from './workspace-cleanup-run-evidence' +import { readWorkspaceCleanupTerminalActivity } from './workspace-cleanup-terminal-activity' +import { keptRunOutcome } from './workspace-cleanup-run-summary' + +function selectorFor(workspace: WorkspaceCleanupWorkspace): string { + return `id:${workspace.ref.worktreeId}` +} + +/** The evaluator's verdict plus the checks only a live host can make; any doubt keeps the workspace. */ +export async function decideWorkspaceCleanup( + runtime: OrcaRuntimeService, + workspace: WorkspaceCleanupWorkspace, + now: number +): Promise { + if (workspace.removing) { + return { action: 'keep', cause: 'removing' } + } + const evaluation = evaluateWorkspaceCleanup(workspace.input, workspace.policy, now) + if (evaluation.action === 'keep') { + return evaluation + } + const { reason } = evaluation + // An unattended run never runs repo scripts nobody approved, and never skips the teardown they do. + // The checkout's own orca.yaml can add one the repo root lacks. + if ( + getEffectiveHooks(workspace.repo)?.scripts.archive || + getEffectiveHooks(workspace.repo, workspace.ref.path)?.scripts.archive + ) { + return { action: 'keep', cause: 'archive-script', reason } + } + const terminals = await readWorkspaceCleanupTerminalActivity( + runtime, + workspace.ref.worktreeId, + workspace.paneAgentStates + ) + if (terminals === 'idle') { + return evaluation + } + // Probed only for a would-remove verdict; the evaluator still owns the cause and its priority. + const blocker = terminals === 'running' ? 'running-terminal' : 'terminal-liveness-unknown' + return evaluateWorkspaceCleanup( + { ...workspace.input, blockers: [...workspace.input.blockers, blocker] }, + workspace.policy, + now + ) +} + +function describeRemovalError(error: unknown): string { + return errorMessage(error).split(/\r?\n/)[0] || 'Removal failed.' +} + +type RemovalOutcome = Pick< + WorkspaceCleanupRunRow, + 'outcome' | 'reason' | 'keepCause' | 'waiting' | 'keptOnRecheck' | 'branchKept' | 'error' +> + +/** Re-reads every piece of evidence right before removing one workspace; removal itself goes through the lifecycle queue. */ +export async function removeWorkspaceForCleanup(args: { + runtime: OrcaRuntimeService + store: RuntimeStore + globalRules: () => WorkspaceCleanupRules + workspace: WorkspaceCleanupWorkspace + now: () => number + signal?: AbortSignal +}): Promise { + const { runtime, store, workspace } = args + const selector = selectorFor(workspace) + try { + // Earlier removals in this run took time: decide on what is true now, not what the scan saw. + const [fresh] = await collectWorkspaceCleanupWorkspaces({ + store, + runtime, + globalRules: args.globalRules(), + now: args.now(), + worktreeId: workspace.ref.worktreeId, + signal: args.signal + }) + if (!fresh) { + return { outcome: 'kept', keepCause: 'git-unknown', keptOnRecheck: true } + } + const recheck = await decideWorkspaceCleanup(runtime, fresh, args.now()) + if (recheck.action === 'keep') { + return { ...keptRunOutcome(recheck), keptOnRecheck: true } + } + if (args.signal?.aborted) { + return { outcome: 'failed', error: 'Cleanup stopped before removing this workspace.' } + } + // Only reachable once WORKSPACE_ARCHIVE_SUPPORTED is on; archive keeps the branch and the row. + if (recheck.action === 'archive') { + const hostId = workspace.ref.executionHostId + const archived = await queueWorkspaceArchive(runtime, selector, hostId, () => + runtime.archiveManagedWorktree(selector, hostId ? { hostId } : {}) + ) + return { outcome: 'archived', reason: recheck.reason, branchKept: archived.branch } + } + // Never forced: Git's own dirty-checkout refusal stays the last guard. + const result = await queueWorkspaceDelete( + runtime, + selector, + workspace.ref.executionHostId, + {}, + (removal) => + runtime.removeManagedWorktree(selector, { ...removal, waitForBackgroundRemoval: true }) + ) + return { + outcome: 'removed', + reason: recheck.reason, + ...(result.preservedBranch ? { branchKept: result.preservedBranch.branchName } : {}) + } + } catch (error) { + return { outcome: 'failed', error: describeRemovalError(error) } + } +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-run-evidence.ts b/src/main/workspaces/cleanup/workspace-cleanup-run-evidence.ts new file mode 100644 index 00000000000..bdcc8d4fd8c --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-run-evidence.ts @@ -0,0 +1,242 @@ +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { worktreeIdentityKey } from '../../../shared/worktree/id' +import { listClientUnsavedEditorWorktreeIds } from './workspace-cleanup-client-unsaved-editors' +import { runtimeVisibleRepos } from '../../runtime/workspaces/catalog/runtime-visible-catalog' +import { scanWorkspaceCleanup } from '../../ipc/workspace-cleanup/workspace-cleanup-scan' +import { isFolderRepo } from '../../../shared/repo-kind' +import type { Repo } from '../../../shared/repo-types' +import { + isRepoOnCatalogHost, + LOCAL_EXECUTION_HOST_ID, + normalizeExecutionHostId +} from '../../../shared/execution-host' +import type { RuntimeWorktreePsSummary } from '../../../shared/runtime-worktree-contracts' +import { + getPersistedWorkspaceCleanupActivityAt, + WORKSPACE_CLEANUP_TARGET_BATCH_LIMIT, + type WorkspaceCleanupBlocker, + type WorkspaceCleanupCandidate +} from '../../../shared/workspace-cleanup/workspace-cleanup' +import { + resolveWorkspaceCleanupPolicy, + type ResolvedWorkspaceCleanupPolicy, + type WorkspaceCleanupRules +} from '../../../shared/workspace-cleanup/workspace-cleanup-policy' +import type { WorkspaceCleanupEvaluationInput } from '../../../shared/workspace-cleanup/workspace-cleanup-evaluation' +import type { WorkspaceCleanupWorkspaceRef } from '../../../shared/workspace-cleanup/workspace-cleanup-run' +import { shortWorkspaceCleanupBranchName } from '../../../shared/workspace-cleanup/workspace-cleanup-candidate-fields' +import type { WorkspaceCleanupPaneAgentStates } from './workspace-cleanup-terminal-activity' + +const DAY_MS = 24 * 60 * 60 * 1000 +const WORKTREE_PS_LIMIT = 100_000 +const LIVE_AGENT_STATES = new Set(['working', 'blocked', 'waiting']) + +export type WorkspaceCleanupWorkspace = { + ref: WorkspaceCleanupWorkspaceRef + repo: Repo + policy: ResolvedWorkspaceCleanupPolicy + input: WorkspaceCleanupEvaluationInput + paneAgentStates: WorkspaceCleanupPaneAgentStates + removing: boolean +} + +/** Repos whose checkouts this process owns; a host served by its own orcad is that server's to clean. */ +export function listWorkspaceCleanupOwnedRepos(store: RuntimeStore): Map { + const repos = new Map() + for (const repo of runtimeVisibleRepos(store)) { + if (isRepoOnCatalogHost(repo) && !isFolderRepo(repo)) { + repos.set(repo.id, repo) + } + } + return repos +} + +function isOwnedSummary(summary: RuntimeWorktreePsSummary, repos: Map): boolean { + const hostId = summary.hostId ? normalizeExecutionHostId(summary.hostId) : LOCAL_EXECUTION_HOST_ID + return ( + repos.has(summary.repoId) && + hostId === LOCAL_EXECUTION_HOST_ID && + summary.workspaceKind !== 'folder-workspace' + ) +} + +function summaryActivityAt(summary: RuntimeWorktreePsSummary): number { + return getPersistedWorkspaceCleanupActivityAt({ + lastActivityAt: summary.lastActivityAt ?? 0, + createdAt: summary.createdAt + }) +} + +/** Git evidence costs a status and merge proof per checkout; skip it where no enabled rule can fire. */ +function needsGitEvidence( + summary: RuntimeWorktreePsSummary, + rules: WorkspaceCleanupRules, + now: number +): boolean { + if (summary.isMainWorktree || summary.isPinned) { + return false + } + // These reasons come only from the scan's Git and run/worker evidence. + if ( + rules.merged.enabled || + rules.unchanged.enabled || + rules.automationRuns.enabled || + rules.orchestrationWorkers.enabled + ) { + return true + } + // Filesystem activity can only make a workspace newer, so the persisted stamp bounds the inactive rule. + return ( + rules.inactive.enabled && now - summaryActivityAt(summary) >= rules.inactive.afterDays * DAY_MS + ) +} + +function inputWithoutGit(summary: RuntimeWorktreePsSummary): WorkspaceCleanupEvaluationInput { + const blockers: WorkspaceCleanupBlocker[] = [] + if (summary.isMainWorktree) { + blockers.push('main-worktree') + } + if (summary.isPinned) { + blockers.push('pinned') + } + return { + reasons: [], + blockers, + lastActivityAt: summaryActivityAt(summary), + git: { clean: null, upstreamAhead: null, upstreamBehind: null, checkedAt: null } + } +} + +/** This host's own window persists its unsaved drafts in the session; remote clients report theirs. Keyed by identity so path spellings match. */ +function dirtyEditorWorktreeIds(store: RuntimeStore, runtime: OrcaRuntimeService): Set { + const session = store.getWorkspaceSession?.(LOCAL_EXECUTION_HOST_ID) + const ids = new Set([...listClientUnsavedEditorWorktreeIds(runtime)].map(worktreeIdentityKey)) + for (const [worktreeId, files] of Object.entries(session?.openFilesByWorktree ?? {})) { + if (files.some((file) => file.dirtyDraftContent !== undefined)) { + ids.add(worktreeIdentityKey(worktreeId)) + } + } + return ids +} + +async function scanTargets( + store: RuntimeStore, + runtime: OrcaRuntimeService, + worktreeIds: string[], + signal: AbortSignal | undefined +): Promise> { + const candidates = new Map() + for (let start = 0; start < worktreeIds.length; start += WORKSPACE_CLEANUP_TARGET_BATCH_LIMIT) { + const batch = worktreeIds.slice(start, start + WORKSPACE_CLEANUP_TARGET_BATCH_LIMIT) + // Re-stat activity: a time rule must not fire on a stale persisted stamp. + const result = await scanWorkspaceCleanup( + store, + { worktreeIds: batch, refreshActivity: true }, + // Without the orchestration store the scan can't prove a worker was released. + { signal, getOrchestrationDb: () => runtime.getExistingOrchestrationDb() } + ) + for (const candidate of result.candidates) { + // A same-id repo row on another host scans too; only this host's checkout is evidence here. + if (normalizeExecutionHostId(candidate.executionHostId) === LOCAL_EXECUTION_HOST_ID) { + candidates.set(candidate.worktreeId, candidate) + } + } + } + return candidates +} + +function withHostBlockers( + input: WorkspaceCleanupEvaluationInput, + summary: RuntimeWorktreePsSummary, + agentLive: boolean, + dirtyEditor: boolean +): WorkspaceCleanupEvaluationInput { + const blockers = [...input.blockers] + if (agentLive) { + blockers.push('live-agent') + } + // The workspace a window or phone has open; removing it would pull it out from under the user. + if (summary.isActive) { + blockers.push('active-workspace') + } + // Old hosts omit the count; current ones send zero, so absence is unknown liveness. + if (summary.unverifiableTerminalCount !== 0) { + blockers.push('terminal-liveness-unknown') + } + if (dirtyEditor) { + blockers.push('dirty-editor-buffer') + } + return { ...input, blockers } +} + +/** Every workspace this process owns, with the evidence the evaluator reads; one id narrows it for a re-check. */ +export async function collectWorkspaceCleanupWorkspaces(args: { + store: RuntimeStore + runtime: OrcaRuntimeService + globalRules: WorkspaceCleanupRules + now: number + worktreeId?: string + signal?: AbortSignal +}): Promise { + const { store, runtime, globalRules, now, worktreeId, signal } = args + const repos = listWorkspaceCleanupOwnedRepos(store) + const ps = await runtime.getWorktreePs(WORKTREE_PS_LIMIT) + if (ps.truncated) { + throw new Error('Could not list every workspace on this host.') + } + const summaries = ps.worktrees.filter( + (summary) => + isOwnedSummary(summary, repos) && + (worktreeId === undefined || summary.worktreeId === worktreeId) + ) + const policies = new Map() + for (const repo of repos.values()) { + policies.set( + repo.id, + resolveWorkspaceCleanupPolicy({ workspaceCleanupPolicy: globalRules }, repo) + ) + } + const gitTargets = summaries + .filter((summary) => { + const rules = policies.get(summary.repoId)!.rules + return needsGitEvidence(summary, rules, now) + }) + .map((summary) => summary.worktreeId) + const candidates = await scanTargets(store, runtime, gitTargets, signal) + const dirtyEditors = dirtyEditorWorktreeIds(store, runtime) + const scanned = new Set(gitTargets) + return summaries.map((summary) => { + const repo = repos.get(summary.repoId)! + const candidate = candidates.get(summary.worktreeId) + const agentLive = summary.agents.some((agent) => LIVE_AGENT_STATES.has(agent.state)) + const paneAgentStates = new Map(summary.agents.map((agent) => [agent.paneKey, agent.state])) + // A target Git no longer lists carries no evidence, so it can only be kept. + const baseInput: WorkspaceCleanupEvaluationInput = candidate + ? candidate + : scanned.has(summary.worktreeId) + ? { ...inputWithoutGit(summary), blockers: ['git-status-error'] } + : inputWithoutGit(summary) + return { + ref: { + worktreeId: summary.worktreeId, + ...(candidate?.executionHostId ? { executionHostId: candidate.executionHostId } : {}), + repoId: repo.id, + repoName: repo.displayName, + displayName: summary.displayName, + branch: shortWorkspaceCleanupBranchName(summary.branch), + path: summary.path + }, + repo, + policy: policies.get(summary.repoId)!, + input: withHostBlockers( + baseInput, + summary, + agentLive, + dirtyEditors.has(worktreeIdentityKey(summary.worktreeId)) + ), + paneAgentStates, + removing: summary.removing === true + } + }) +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-run-history.ts b/src/main/workspaces/cleanup/workspace-cleanup-run-history.ts new file mode 100644 index 00000000000..15fae229f70 --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-run-history.ts @@ -0,0 +1,67 @@ +import { + readSidecarSnapshot, + sidecarSnapshotFile, + withSidecarSnapshotQueue, + writeSidecarSnapshot +} from '../../filesystem/sidecar-snapshot-file' +import { + WORKSPACE_CLEANUP_REPORT_RUN_LIMIT, + type WorkspaceCleanupRun +} from '../../../shared/workspace-cleanup/workspace-cleanup-run' + +const HISTORY_FILE_NAME = 'orca-workspace-cleanup-runs.json' +const HISTORY_VERSION = 1 + +type PersistedWorkspaceCleanupRunHistory = { + version: number + runs: WorkspaceCleanupRun[] +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isPersistedRun(value: unknown): value is WorkspaceCleanupRun { + return ( + isRecord(value) && + typeof value.id === 'string' && + typeof value.trigger === 'string' && + typeof value.startedAt === 'number' && + typeof value.finishedAt === 'number' && + isRecord(value.counts) && + typeof value.freedBytes === 'number' && + Array.isArray(value.rows) + ) +} + +function parseHistory(parsed: unknown): WorkspaceCleanupRun[] { + if (!isRecord(parsed) || parsed.version !== HISTORY_VERSION || !Array.isArray(parsed.runs)) { + return [] + } + return parsed.runs.filter(isPersistedRun) +} + +/** Newest first; a missing or unreadable file is an empty history. */ +export async function readWorkspaceCleanupRunHistory( + directory: string +): Promise { + const file = sidecarSnapshotFile(directory, HISTORY_FILE_NAME) + return withSidecarSnapshotQueue(file, async () => parseHistory(await readSidecarSnapshot(file))) +} + +export async function appendWorkspaceCleanupRun( + directory: string, + run: WorkspaceCleanupRun +): Promise { + const file = sidecarSnapshotFile(directory, HISTORY_FILE_NAME) + await withSidecarSnapshotQueue(file, async () => { + const runs = [run, ...parseHistory(await readSidecarSnapshot(file))].slice( + 0, + WORKSPACE_CLEANUP_REPORT_RUN_LIMIT + ) + await writeSidecarSnapshot(file, { + version: HISTORY_VERSION, + runs + } satisfies PersistedWorkspaceCleanupRunHistory) + }) +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-run-summary.ts b/src/main/workspaces/cleanup/workspace-cleanup-run-summary.ts new file mode 100644 index 00000000000..b865a5ea5b1 --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-run-summary.ts @@ -0,0 +1,79 @@ +import type { WorkspaceCleanupEvaluation } from '../../../shared/workspace-cleanup/workspace-cleanup-evaluation' +import { + WORKSPACE_CLEANUP_REPORT_ROW_LIMIT, + WORKSPACE_CLEANUP_UNWATCHED_CAUSES, + type WorkspaceCleanupRun, + type WorkspaceCleanupRunOutcome, + type WorkspaceCleanupRunRow +} from '../../../shared/workspace-cleanup/workspace-cleanup-run' + +export type WorkspaceCleanupKeptOutcome = Pick< + WorkspaceCleanupRunRow, + 'outcome' | 'reason' | 'keepCause' | 'waiting' +> + +export function keptRunOutcome( + evaluation: WorkspaceCleanupEvaluation +): WorkspaceCleanupKeptOutcome { + if (evaluation.action !== 'keep') { + // Archive needs the archive backend; until then the runner only deletes. + return { outcome: 'kept', reason: evaluation.reason, keepCause: 'archive-unavailable' } + } + return { + outcome: 'kept', + keepCause: evaluation.cause, + ...(evaluation.reason ? { reason: evaluation.reason } : {}), + ...(evaluation.waiting ? { waiting: evaluation.waiting } : {}) + } +} + +// Acted-on rows first, then protections, then time rules still counting, then plain non-matches. +function rowRank(row: WorkspaceCleanupRunRow): number { + if (row.outcome !== 'kept') { + return 0 + } + if (row.keepCause === 'no-rule-matched') { + return 3 + } + return row.keepCause === 'waiting' ? 2 : 1 +} + +export function summarizeWorkspaceCleanupRun(args: { + id: string + trigger: WorkspaceCleanupRun['trigger'] + startedAt: number + finishedAt: number + rows: WorkspaceCleanupRunRow[] + error?: string +}): WorkspaceCleanupRun { + const rows = args.rows.filter( + (row) => row.keepCause === undefined || !WORKSPACE_CLEANUP_UNWATCHED_CAUSES.has(row.keepCause) + ) + const counts: Record = { + removed: 0, + archived: 0, + kept: 0, + failed: 0 + } + let freedBytes = 0 + for (const row of rows) { + counts[row.outcome] += 1 + if ((row.outcome === 'removed' || row.outcome === 'archived') && row.sizeBytes) { + freedBytes += row.sizeBytes + } + } + return { + id: args.id, + trigger: args.trigger, + startedAt: args.startedAt, + finishedAt: args.finishedAt, + counts, + freedBytes, + rows: rows + .map((row, index) => ({ row, index })) + .sort((a, b) => rowRank(a.row) - rowRank(b.row) || a.index - b.index) + .slice(0, WORKSPACE_CLEANUP_REPORT_ROW_LIMIT) + .map(({ row }) => row), + ...(args.error ? { error: args.error } : {}) + } +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-runner-registry.ts b/src/main/workspaces/cleanup/workspace-cleanup-runner-registry.ts new file mode 100644 index 00000000000..e109bf2c894 --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-runner-registry.ts @@ -0,0 +1,26 @@ +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { WorkspaceCleanupRunner } from './workspace-cleanup-runner' + +// Keyed by runtime: desktop main and orcad each own one runner for their own repos. +const runners = new WeakMap() + +export function setWorkspaceCleanupRunner( + runtime: OrcaRuntimeService, + runner: WorkspaceCleanupRunner +): void { + runners.set(runtime, runner) +} + +export function getWorkspaceCleanupRunner( + runtime: OrcaRuntimeService +): WorkspaceCleanupRunner | undefined { + return runners.get(runtime) +} + +export function requireWorkspaceCleanupRunner(runtime: OrcaRuntimeService): WorkspaceCleanupRunner { + const runner = runners.get(runtime) + if (!runner) { + throw new Error('Workspace cleanup is not running on this host.') + } + return runner +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-runner-startup.ts b/src/main/workspaces/cleanup/workspace-cleanup-runner-startup.ts new file mode 100644 index 00000000000..646c6147dab --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-runner-startup.ts @@ -0,0 +1,19 @@ +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { WorkspaceCleanupRunner } from './workspace-cleanup-runner' +import { setWorkspaceCleanupRunner } from './workspace-cleanup-runner-registry' + +/** Starts the runner for the repos this process owns: desktop main for local/WSL, each orcad for its own. */ +export function startWorkspaceCleanupRunner( + runtime: OrcaRuntimeService, + store: RuntimeStore +): WorkspaceCleanupRunner | null { + const historyDirectory = store.getProfileStorageDirectory?.() + if (!historyDirectory) { + return null + } + const runner = new WorkspaceCleanupRunner({ runtime, store, historyDirectory }) + setWorkspaceCleanupRunner(runtime, runner) + runner.start() + return runner +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-runner.ts b/src/main/workspaces/cleanup/workspace-cleanup-runner.ts new file mode 100644 index 00000000000..95cab81bd2e --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-runner.ts @@ -0,0 +1,270 @@ +import { randomUUID } from 'node:crypto' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { readWorkspaceSpaceAnalysisSnapshot } from '../space-analysis/workspace-space-analysis-snapshot' +import { + getDefaultWorkspaceCleanupRules, + type WorkspaceCleanupRules +} from '../../../shared/workspace-cleanup/workspace-cleanup-policy' +import type { + WorkspaceCleanupEvaluation, + WorkspaceCleanupRuleReason +} from '../../../shared/workspace-cleanup/workspace-cleanup-evaluation' +import { errorMessage } from '../../../shared/error-message' +import type { + WorkspaceCleanupPreview, + WorkspaceCleanupReport, + WorkspaceCleanupRun, + WorkspaceCleanupRunRow, + WorkspaceCleanupRunTrigger, + WorkspaceCleanupWorkspaceRef +} from '../../../shared/workspace-cleanup/workspace-cleanup-run' +import { + collectWorkspaceCleanupWorkspaces, + type WorkspaceCleanupWorkspace +} from './workspace-cleanup-run-evidence' +import { decideWorkspaceCleanup, removeWorkspaceForCleanup } from './workspace-cleanup-removal-step' +import { keptRunOutcome, summarizeWorkspaceCleanupRun } from './workspace-cleanup-run-summary' +import { + appendWorkspaceCleanupRun, + readWorkspaceCleanupRunHistory +} from './workspace-cleanup-run-history' +import { listEnabledWorkspaceCleanupRules } from './workspace-cleanup-enabled-rules' + +// Let the window restore its terminals and session drafts before the first evidence read. +const STARTUP_DELAY_MS = 2 * 60 * 1000 +const HOURLY_MS = 60 * 60 * 1000 +// One settings write per toggle; coalesce a burst of them into one run. +const SETTINGS_DEBOUNCE_MS = 10 * 1000 + +type DecidedWorkspace = { + workspace: WorkspaceCleanupWorkspace + ref: WorkspaceCleanupWorkspaceRef & { sizeBytes?: number } + evaluation: WorkspaceCleanupEvaluation +} + +export type WorkspaceCleanupRunnerDeps = { + runtime: OrcaRuntimeService + store: RuntimeStore + /** Profile storage directory: the run history and space-analysis sidecars live here. */ + historyDirectory: string +} + +/** Applies the user's cleanup rules to the workspaces this process owns, one run at a time. */ +export class WorkspaceCleanupRunner { + private readonly deps: WorkspaceCleanupRunnerDeps + private current: Promise | null = null + private timer: ReturnType | null = null + private nextRunAt: number | null = null + private enabledRules = new Set() + private unsubscribe: (() => void) | null = null + private readonly abort = new AbortController() + + constructor(deps: WorkspaceCleanupRunnerDeps) { + this.deps = deps + } + + start(): void { + if (this.unsubscribe) { + return + } + this.enabledRules = listEnabledWorkspaceCleanupRules(this.deps.store) + this.unsubscribe = this.deps.runtime.onClientEvent( + (event) => { + if ( + event.type === 'reposChanged' || + (event.type === 'settingsChanged' && event.keys.includes('workspaceCleanupPolicy')) + ) { + this.noteRulesChanged() + } + }, + // Counting as a consumer would turn on per-chunk terminal output scanning on headless hosts. + { consumesTerminalSideEffects: false } + ) + this.schedule(STARTUP_DELAY_MS, 'startup') + } + + stop(): void { + this.unsubscribe?.() + this.unsubscribe = null + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = null + this.nextRunAt = null + this.abort.abort() + } + + isRunning(): boolean { + return this.current !== null + } + + /** Runs now, or joins the run already going: runs never overlap. */ + runNow( + trigger: Extract + ): Promise { + return this.current ?? this.track(this.execute(trigger)) + } + + /** What a run would do now, removing nothing; `rules` previews other global rules. */ + async preview(rules?: WorkspaceCleanupRules): Promise { + const evaluatedAt = Date.now() + const decided = await this.evaluate(rules ?? this.globalRules(), evaluatedAt) + return { evaluatedAt, rows: decided.map(({ ref, evaluation }) => ({ ...ref, evaluation })) } + } + + async report(): Promise { + return { + runs: await readWorkspaceCleanupRunHistory(this.deps.historyDirectory), + running: this.isRunning(), + nextRunAt: this.enabledRules.size > 0 ? this.nextRunAt : null + } + } + + private globalRules(): WorkspaceCleanupRules { + return this.deps.store.getSettings().workspaceCleanupPolicy ?? getDefaultWorkspaceCleanupRules() + } + + private schedule(delayMs: number, trigger: WorkspaceCleanupRunTrigger): void { + if (this.timer) { + clearTimeout(this.timer) + } + this.nextRunAt = Date.now() + delayMs + this.timer = setTimeout(() => { + this.timer = null + void this.runScheduled(trigger) + }, delayMs) + this.timer.unref?.() + } + + private async runScheduled(trigger: WorkspaceCleanupRunTrigger): Promise { + try { + // A run already going may have read the rules before the change that scheduled this one. + await this.current?.catch(() => undefined) + // Off by default: with no rule on, a scheduled run costs nothing and leaves no record. + if (this.unsubscribe && this.enabledRules.size > 0) { + await (this.current ?? this.track(this.execute(trigger))) + } + } catch (error) { + console.error('[workspace-cleanup] Scheduled run failed', error) + } finally { + // A rule change during this run already queued its own run; don't push it out an hour. + if (this.unsubscribe && !this.timer) { + this.schedule(HOURLY_MS, 'hourly') + } + } + } + + private noteRulesChanged(): void { + const previous = this.enabledRules + this.enabledRules = listEnabledWorkspaceCleanupRules(this.deps.store) + if ([...this.enabledRules].some((rule) => !previous.has(rule))) { + this.schedule(SETTINGS_DEBOUNCE_MS, 'settings') + } + } + + private track(run: Promise): Promise { + this.current = run + void run.finally(() => { + if (this.current === run) { + this.current = null + } + }) + return run + } + + /** Every owned workspace with its verdict now; preview and runs share it so they never disagree. */ + private async evaluate( + globalRules: WorkspaceCleanupRules, + now: number + ): Promise { + const [workspaces, sizes] = await Promise.all([ + collectWorkspaceCleanupWorkspaces({ + store: this.deps.store, + runtime: this.deps.runtime, + globalRules, + now, + signal: this.abort.signal + }), + this.readSizes() + ]) + const decided: DecidedWorkspace[] = [] + for (const workspace of workspaces) { + const sizeBytes = sizes.get(workspace.ref.worktreeId) + decided.push({ + workspace, + ref: { ...workspace.ref, ...(sizeBytes !== undefined ? { sizeBytes } : {}) }, + evaluation: await decideWorkspaceCleanup(this.deps.runtime, workspace, now) + }) + } + return decided + } + + private async readSizes(): Promise> { + const analysis = await readWorkspaceSpaceAnalysisSnapshot(this.deps.historyDirectory) + const sizes = new Map() + for (const row of analysis?.worktrees ?? []) { + if (row.status === 'ok') { + sizes.set(row.worktreeId, row.sizeBytes) + } + } + return sizes + } + + private async execute(trigger: WorkspaceCleanupRunTrigger): Promise { + const startedAt = Date.now() + const rows: WorkspaceCleanupRunRow[] = [] + let error: string | undefined + try { + const removals: (DecidedWorkspace & { reason: WorkspaceCleanupRuleReason })[] = [] + for (const { workspace, ref, evaluation } of await this.evaluate( + this.globalRules(), + startedAt + )) { + if (evaluation.action === 'delete') { + removals.push({ workspace, ref, evaluation, reason: evaluation.reason }) + } else { + rows.push({ ...ref, ...keptRunOutcome(evaluation) }) + } + } + // Nested checkouts first, so a parent's removal never sweeps a child it did not re-check. + removals.sort((a, b) => b.ref.path.length - a.ref.path.length) + for (const { workspace, ref, reason } of removals) { + if (this.abort.signal.aborted) { + break + } + const outcome = await removeWorkspaceForCleanup({ + runtime: this.deps.runtime, + store: this.deps.store, + globalRules: () => this.globalRules(), + workspace, + now: () => Date.now(), + signal: this.abort.signal + }) + rows.push({ ...ref, reason, ...outcome }) + } + } catch (cause) { + error = errorMessage(cause) + } + const run = summarizeWorkspaceCleanupRun({ + id: randomUUID(), + trigger, + startedAt, + finishedAt: Date.now(), + rows, + ...(error ? { error } : {}) + }) + await this.record(run) + return run + } + + private async record(run: WorkspaceCleanupRun): Promise { + try { + await appendWorkspaceCleanupRun(this.deps.historyDirectory, run) + } catch (error) { + console.error('[workspace-cleanup] Could not save the run report', error) + } + const { rows: _rows, ...summary } = run + this.deps.runtime.notifyWorkspaceCleanupRunFinished(summary) + } +} diff --git a/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.test.ts b/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.test.ts index c044c7f4c0c..250cdeb75d9 100644 --- a/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.test.ts +++ b/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.test.ts @@ -52,9 +52,7 @@ function makeCandidate( displayName: 'Feature', branch: 'feature', path: '/repo-feature', - tier: 'ready', - selectedByDefault: true, - reasons: ['idle-clean'], + reasons: ['inactive'], blockers: [], lastActivityAt: NOW - 40 * 24 * 60 * 60 * 1000, localContext: { @@ -147,7 +145,7 @@ describe('workspace cleanup scan snapshot', () => { makeBroadResult([stale, other]) ) - const rescanned = makeCandidate({ tier: 'protected', blockers: ['dirty-files'] }) + const rescanned = makeCandidate({ blockers: ['dirty-files'] }) await persistWorkspaceCleanupScanResult( userDataDirHolder.dir, { worktreeId: stale.worktreeId }, @@ -292,7 +290,6 @@ describe('workspace cleanup scan snapshot', () => { const rescannedRemote = makeCandidate({ ...remote, - tier: 'protected', blockers: ['dirty-files'] }) await persistWorkspaceCleanupScanResult( diff --git a/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.ts b/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.ts index e102f3b764c..9973d6253cd 100644 --- a/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.ts +++ b/src/main/workspaces/cleanup/workspace-cleanup-scan-snapshot.ts @@ -21,7 +21,7 @@ import { } from './workspace-snapshot-prune-index' const SNAPSHOT_FILE_NAME = 'orca-workspace-cleanup-scan.json' -const SNAPSHOT_VERSION = 2 +const SNAPSHOT_VERSION = 3 export type WorkspaceCleanupScanSnapshotPruneTarget = WorkspaceSnapshotPruneTarget diff --git a/src/main/workspaces/cleanup/workspace-cleanup-terminal-activity.ts b/src/main/workspaces/cleanup/workspace-cleanup-terminal-activity.ts new file mode 100644 index 00000000000..59e6c6b21c7 --- /dev/null +++ b/src/main/workspaces/cleanup/workspace-cleanup-terminal-activity.ts @@ -0,0 +1,129 @@ +import type { IPtyProvider } from '../../providers/pty/provider-contract' +import { inspectPtyProviderProcess } from '../../providers/pty/process-inspection' +import { worktreePtyOwnership } from '../../providers/pty/worktree-ownership' +import type { RuntimeTerminalListResult } from '../../../shared/runtime-terminal-contracts' +import type { TerminalProcessInspection } from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' +import { + classifyTerminalProcessInspectionFailure, + isClientOnlyUnverifiableInspection +} from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' +import { isShellProcess } from '../../../shared/agent-status/process/shell-process-detection' +import { recognizeAgentProcess } from '../../../shared/agent-status/process/agent-process-recognition' +import type { AgentStatusState } from '../../../shared/agent-status/contracts/agent-status-types' +import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' + +export type WorkspaceCleanupTerminalActivity = 'idle' | 'running' | 'unknown' + +/** Each pane's agent state from the host's agent rows; a pane with no row has no idle proof. */ +export type WorkspaceCleanupPaneAgentStates = ReadonlyMap + +export type WorkspaceCleanupTerminalRuntime = { + listTerminals( + worktreeSelector?: string, + limit?: number, + opts?: { requireFreshPtyLiveness?: boolean } + ): Promise + getLocalProvider(): IPtyProvider | null +} + +const TERMINAL_LIST_LIMIT = 10_000 +const PROVIDER_LIST_DEADLINE_MS = 5_000 + +/** Like the cleanup dialog: an idle shell, or an agent CLI sitting at its prompt, is not running. */ +function classifyInspection( + inspection: TerminalProcessInspection, + paneAgentState: AgentStatusState | undefined +): WorkspaceCleanupTerminalActivity { + if ( + isClientOnlyUnverifiableInspection(inspection) || + inspection.childProcessEvidence === 'unverifiable' + ) { + return 'unknown' + } + const processName = inspection.foregroundProcess + if (!inspection.hasChildProcesses && (!processName || isShellProcess(processName))) { + return 'idle' + } + // Agent CLIs keep helper children (MCP servers); only its own pane's finished turn proves one is idle. + return recognizeAgentProcess(processName) && paneAgentState === 'done' ? 'idle' : 'running' +} + +async function listWorktreePtyIds( + runtime: WorkspaceCleanupTerminalRuntime, + provider: IPtyProvider, + worktreeId: string +): Promise> { + const [listed, sessions] = await Promise.all([ + runtime.listTerminals(`id:${worktreeId}`, TERMINAL_LIST_LIMIT, { + requireFreshPtyLiveness: true + }), + provider.listProcesses({ deadlineMs: Date.now() + PROVIDER_LIST_DEADLINE_MS, worktreeId }) + ]) + if (listed.truncated) { + throw new Error('terminal_list_truncated') + } + // Pty id -> pane key; provider sessions the graph never bound have no pane. + const ptyIds = new Map() + for (const terminal of listed.terminals) { + if (terminal.verdict === 'unverifiable') { + throw new Error('terminal_unverifiable') + } + if (terminal.ptyId && terminal.connected) { + ptyIds.set( + terminal.ptyId, + isTerminalLeafId(terminal.leafId) ? makePaneKey(terminal.tabId, terminal.leafId) : null + ) + } + } + // Removal's teardown also stops provider sessions the graph never bound; inspect what it would stop. + for (const session of sessions.filter(worktreePtyOwnership(worktreeId))) { + if (!ptyIds.has(session.id)) { + ptyIds.set(session.id, null) + } + } + return ptyIds +} + +/** Whether any terminal removal would stop is doing work; any doubt reads as 'unknown'. */ +export async function readWorkspaceCleanupTerminalActivity( + runtime: WorkspaceCleanupTerminalRuntime, + worktreeId: string, + paneAgentStates: WorkspaceCleanupPaneAgentStates +): Promise { + const provider = runtime.getLocalProvider() + if (!provider) { + return 'unknown' + } + let ptyIds: Map + try { + ptyIds = await listWorktreePtyIds(runtime, provider, worktreeId) + } catch { + return 'unknown' + } + let unknown = false + for (const [ptyId, paneKey] of ptyIds) { + let inspection: TerminalProcessInspection + try { + // Teardown stops sessions no window has reattached since a relaunch, so inspect those too. + inspection = await inspectPtyProviderProcess(provider, ptyId, { + scanChildProcesses: true, + includeUnattached: true + }) + } catch (error) { + if (classifyTerminalProcessInspectionFailure(error) === 'terminal_gone') { + continue + } + unknown = true + continue + } + const activity = classifyInspection( + inspection, + paneKey ? paneAgentStates.get(paneKey) : undefined + ) + if (activity === 'running') { + return 'running' + } + unknown ||= activity === 'unknown' + } + return unknown ? 'unknown' : 'idle' +} diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-activity.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-activity.ts index 9737799dc05..55128b9bdbf 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-activity.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-activity.ts @@ -1,4 +1,4 @@ -import type { PreparedCheckoutOrigin } from '../../../../shared/worktree/create-timing-vocabulary' +import type { PreparedCheckoutOrigin } from '../../../../shared/worktree/creation/create-timing-vocabulary' import { beginPreparationWork, type PreparationWork } from '../worktree-create-concurrency' /** Record preparation origin and disk timing without controlling the pool. */ diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-claim.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-claim.ts index 6fd16b56c36..bc78c135452 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-claim.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-claim.ts @@ -1,7 +1,7 @@ import { posix, win32 } from 'node:path' import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path' -import { worktreeBaseRefFamily } from '../../../../shared/worktree/base-ref' -import type { PreparedCheckoutMissReason } from '../../../../shared/worktree/create-timing-vocabulary' +import { worktreeBaseRefFamily } from '../../../../shared/worktree/base-refs/base-ref' +import type { PreparedCheckoutMissReason } from '../../../../shared/worktree/creation/create-timing-vocabulary' export type PreparationSelectionMissReason = Extract< PreparedCheckoutMissReason, diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts index 86ddaf7dca9..12ee38c6978 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts @@ -14,7 +14,7 @@ import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-pat import { WORKTREE_CREATE_PREPARATION_DIRECTORY, createWorktreePreparationLockReason -} from '../../../../shared/worktree/create-preparation' +} from '../../../../shared/worktree/creation/create-preparation' import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' import { prepareWorktreeCreateCheckout } from '../../../git/worktrees/creation/worktree-create-preparation' import { queuePreparedWorktreeTipRefresh } from './worktree-preparation-refresh-queue' diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-reservation.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-reservation.ts index d5f320a03ed..f79ce4ce5c1 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-reservation.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-reservation.ts @@ -1,4 +1,4 @@ -import type { PreparedCheckoutMissReason } from '../../../../shared/worktree/create-timing-vocabulary' +import type { PreparedCheckoutMissReason } from '../../../../shared/worktree/creation/create-timing-vocabulary' import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' import { measureRetargetDivergence } from '../../../git/worktrees/creation/worktree-base-divergence' import { resolveLocalWorktreeBaseRef } from '../../../git/worktrees/creation/worktree-base-ref-probe' diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts index 1be232e1463..e8adc56f8f4 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts @@ -3,8 +3,8 @@ import { parseWorktreePreparationOwnerMachine, parseWorktreePreparationOwnerPid, parseWorktreePreparationPathOwnerPid -} from '../../../../shared/worktree/create-preparation' -import { orcadDataRootIsOnLocalDisk } from '../../../orcad/orcad-data-root-locality' +} from '../../../../shared/worktree/creation/create-preparation' +import { orcadDataRootIsOnLocalDisk } from '../../../orcad/instance-lock/orcad-data-root-locality' import { profileStateAccessMachineIdentity } from '../../../persistence/profile-state/access/profile-state-access-identity' import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' import { listWorktreeGraph } from '../../../git/worktrees/catalog/worktree-scan-cache' diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts index 3beddbfdfc6..483bd2111d8 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts @@ -1,19 +1,11 @@ -import { - mocks, - repo, - store, - flushBackgroundWork -} from '../../../__mocks__/worktree-create-preparation' +import { mocks, repo, store } from '../../../__mocks__/worktree-create-preparation' import { describe, expect, it } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import { hasPendingStalePreparationCleanup } from './worktree-create-preparation-stale-cleanup' -import '../../../../shared/worktree/create-preparation' + +import '../../../../shared/worktree/creation/create-preparation' import { - _resetWorktreeCreatePreparationsForTests, consumePreparedWorktreeCreate, prepareWorktreeCreateForRepo } from './worktree-create-preparation' -import { releaseWorktreeCreatePreparationsForRepo } from './worktree-create-preparation-project-removal' describe('worktree create preparation registry', () => { it('does not claim a preparation after the selected base changes to another branch', async () => { @@ -28,42 +20,6 @@ describe('worktree create preparation registry', () => { baseBranch: 'origin/release' }) ).resolves.toEqual({ status: 'miss', reason: 'base_mismatch' }) - expect(mocks.finalize).not.toHaveBeenCalled() - }) - - it('claims across the local/remote spelling of the same base and reports the retarget', async () => { - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - - // Different canonical refs leave only the branch-family retarget path. - await expect( - consumePreparedWorktreeCreate({ - repoPath: repo.path, - workspaceRoot: '/workspace', - worktreePath: '/workspace/final', - branch: 'feature/test', - baseBranch: 'main' - }) - ).resolves.toEqual({ - status: 'hit', - retargeted: true, - reset: 'none', - buildMs: expect.any(Number), - idleMs: expect.any(Number), - origin: 'prefetch', - result: {}, - rearm: expect.any(Function) - }) - expect(mocks.finalize).toHaveBeenCalledWith( - repo.path, - expect.any(String), - '/workspace/final', - 'feature/test', - 'main', - undefined, - {}, - mocks.prepareCheckout.mock.calls[0]?.[3], - expect.anything() - ) }) it('refuses a same-family retarget whose bases have drifted too far apart', async () => { @@ -80,8 +36,6 @@ describe('worktree create preparation registry', () => { baseBranch: 'main' }) ).resolves.toEqual({ status: 'miss', reason: 'retarget_too_divergent' }) - expect(mocks.finalize).not.toHaveBeenCalled() - expect(mocks.discard).not.toHaveBeenCalled() }) it('separates a drift check that said no from one that could not answer', async () => { @@ -98,34 +52,6 @@ describe('worktree create preparation registry', () => { baseBranch: 'main' }) ).resolves.toEqual({ status: 'miss', reason: 'retarget_unverifiable' }) - expect(mocks.finalize).not.toHaveBeenCalled() - expect(mocks.discard).not.toHaveBeenCalled() - }) - - it('never hands the same prepared checkout to two concurrent creates', async () => { - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - - // The ref probe yields during claim, allowing a second create to race it. - const [first, second] = await Promise.all([ - consumePreparedWorktreeCreate({ - repoPath: repo.path, - workspaceRoot: '/workspace', - worktreePath: '/workspace/first', - branch: 'feature/first', - baseBranch: 'main' - }), - consumePreparedWorktreeCreate({ - repoPath: repo.path, - workspaceRoot: '/workspace', - worktreePath: '/workspace/second', - branch: 'feature/second', - baseBranch: 'main' - }) - ]) - - expect([first.status, second.status]).toContain('hit') - const preparedPaths = mocks.finalize.mock.calls.map((call) => call[1]) - expect(new Set(preparedPaths).size).toBe(preparedPaths.length) }) it('reports which part of the claim key disagreed', async () => { @@ -161,153 +87,5 @@ describe('worktree create preparation registry', () => { baseBranch: 'origin/main' }) ).resolves.toEqual({ status: 'miss', reason: 'repo_mismatch' }) - expect(mocks.finalize).not.toHaveBeenCalled() - }) - - it("discards a removed project's armed checkout and reclaims its crash leftovers", async () => { - const otherRepo = { id: 'repo-2', path: '/other-repo' } as Repo - await prepareWorktreeCreateForRepo(store, otherRepo, 'origin/main') - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - await flushBackgroundWork() - const armedPath = mocks.prepareCheckout.mock.calls[1]?.[1] - const stalePath = '/workspace/.orca-preparing/999999999-11111111-1111-4111-8111-111111111111' - mocks.listWorktreeGraph.mockResolvedValueOnce([ - { - path: stalePath, - branch: undefined, - lockReason: 'orca-create-preparation:v1:999999999:stale', - head: 'deadbeef', - isBare: false, - isMainWorktree: false - } - ]) - - releaseWorktreeCreatePreparationsForRepo(store, repo) - await flushBackgroundWork() - - expect(mocks.discard).toHaveBeenCalledWith( - repo.path, - armedPath, - expect.objectContaining({ signal: undefined }), - expect.any(String), - null - ) - expect(mocks.discard).toHaveBeenCalledWith( - repo.path, - stalePath, - { admissionTier: 'background' }, - 'orca-create-preparation:v1:999999999:stale' - ) - await expect( - consumePreparedWorktreeCreate({ - repoPath: otherRepo.path, - workspaceRoot: '/workspace', - worktreePath: '/workspace/other', - branch: 'feature/other', - baseBranch: 'origin/main' - }) - ).resolves.toMatchObject({ status: 'hit' }) - }) - - it('prepares while stale removal is stalled, shares its scan, and settles removal on reset', async () => { - const stalePath = '/workspace/.orca-preparing/999999999-11111111-1111-4111-8111-111111111111' - let releaseRemoval!: () => void - const removal = new Promise((resolve) => { - releaseRemoval = resolve - }) - mocks.listWorktreeGraph.mockResolvedValueOnce([ - { - path: stalePath, - branch: undefined, - lockReason: 'orca-create-preparation:v1:999999999:stale', - head: 'deadbeef', - isBare: false, - isMainWorktree: false - } - ]) - mocks.discard.mockImplementation((_repo, path) => - path === stalePath ? removal : Promise.resolve() - ) - let ready = false - let reset: Promise | undefined - const preparation = prepareWorktreeCreateForRepo(store, repo, 'origin/main').then(() => { - ready = true - }) - try { - await flushBackgroundWork() - expect(mocks.discard).toHaveBeenCalledWith( - repo.path, - stalePath, - { - admissionTier: 'background' - }, - 'orca-create-preparation:v1:999999999:stale' - ) - expect(ready).toBe(true) - await prepareWorktreeCreateForRepo(store, repo, 'origin/release') - expect(mocks.prepareCheckout).toHaveBeenCalledTimes(2) - expect(mocks.listWorktreeGraph).toHaveBeenCalledTimes(1) - expect(hasPendingStalePreparationCleanup()).toBe(true) - mocks.getWorktreeOptions.mockReturnValue({ wslDistro: 'Ubuntu' }) - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - expect(mocks.prepareCheckout).toHaveBeenCalledTimes(3) - expect(mocks.listWorktreeGraph).toHaveBeenCalledTimes(2) - expect(mocks.listWorktreeGraph).toHaveBeenLastCalledWith(repo.path, { - wslDistro: 'Ubuntu', - includeCreatePreparations: true - }) - let resetFinished = false - reset = _resetWorktreeCreatePreparationsForTests().then(() => { - resetFinished = true - }) - await flushBackgroundWork() - expect(resetFinished).toBe(false) - } finally { - releaseRemoval() - await preparation - await reset - } - expect(hasPendingStalePreparationCleanup()).toBe(false) - }) - - it('unlocks a stale branch-attached final path instead of deleting user work', async () => { - mocks.listWorktreeGraph.mockResolvedValueOnce([ - { - path: '/workspace/final', - branch: 'refs/heads/feature/test', - lockReason: 'orca-create-preparation:v1:999999999:stale', - head: 'deadbeef', - isBare: false, - isMainWorktree: false - } - ]) - - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - - expect(mocks.unlock).toHaveBeenCalledWith( - repo.path, - '/workspace/final', - { admissionTier: 'background' }, - 'orca-create-preparation:v1:999999999:stale' - ) - expect(mocks.discard).not.toHaveBeenCalledWith(repo.path, '/workspace/final', expect.anything()) - }) - - it('does not classify a user branch worktree under the preparation directory as stale', async () => { - mocks.listWorktreeGraph.mockResolvedValueOnce([ - { - path: '/workspace/.orca-preparing/999999999-user-worktree', - branch: 'refs/heads/user-worktree', - lockReason: undefined, - head: 'deadbeef', - isBare: false, - isMainWorktree: false - } - ]) - - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - - expect(mocks.unlock).not.toHaveBeenCalled() - expect(mocks.discard).not.toHaveBeenCalled() }) }) diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation.ts index 7ab008843c8..7a8a7526299 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation.ts @@ -16,7 +16,7 @@ import type { PreparedCheckoutOrigin, PreparedCheckoutReset, WorktreeCreatePhase -} from '../../../../shared/worktree/create-timing-vocabulary' +} from '../../../../shared/worktree/creation/create-timing-vocabulary' import type { AddWorktreeOptions, AddWorktreeResult diff --git a/src/main/workspaces/creation/reserved-worktree-path.ts b/src/main/workspaces/creation/reserved-worktree-path.ts new file mode 100644 index 00000000000..7b75c6e1b36 --- /dev/null +++ b/src/main/workspaces/creation/reserved-worktree-path.ts @@ -0,0 +1,25 @@ +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import { splitWorktreeId } from '../../../shared/worktree/id' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' +import { findPendingWorktreeRemovalConflict } from '../removal/worktree-removal-table' + +/** Paths Orca still owns after Git deleted the checkout: a removal still settling, or an archived workspace. */ +export function isWorktreePathReserved( + store: { getAllWorktreeMeta?: () => Record } | undefined, + repo: Pick, + worktreePath: string +): boolean { + if (findPendingWorktreeRemovalConflict(repo.path, { worktreePath })) { + return true + } + // Any project's archive may sit in a shared workspace root; remote hosts' paths are not this disk. + return Object.entries(store?.getAllWorktreeMeta?.() ?? {}).some(([worktreeId, meta]) => { + if (!meta.archivedCheckout || (meta.hostId && meta.hostId !== LOCAL_EXECUTION_HOST_ID)) { + return false + } + const archivedPath = splitWorktreeId(worktreeId)?.worktreePath + return archivedPath ? areWorktreePathsEqual(archivedPath, worktreePath) : false + }) +} diff --git a/src/main/workspaces/creation/workspace-create-event-fields.ts b/src/main/workspaces/creation/workspace-create-event-fields.ts index 5a2330a16f9..bb41c089f19 100644 --- a/src/main/workspaces/creation/workspace-create-event-fields.ts +++ b/src/main/workspaces/creation/workspace-create-event-fields.ts @@ -4,7 +4,7 @@ import { WORKTREE_CREATE_PHASES, type WorkspaceCreateEntryPoint, type WorktreeCreatePhase -} from '../../../shared/worktree/create-timing-vocabulary' +} from '../../../shared/worktree/creation/create-timing-vocabulary' import type { REPO_FILE_COUNT_BUCKETS, WORKTREE_COUNT_BUCKETS, diff --git a/src/main/workspaces/creation/workspace-create-telemetry.ts b/src/main/workspaces/creation/workspace-create-telemetry.ts index 3ef852c43df..913e56723ad 100644 --- a/src/main/workspaces/creation/workspace-create-telemetry.ts +++ b/src/main/workspaces/creation/workspace-create-telemetry.ts @@ -1,5 +1,5 @@ import type { WorktreeCreateTiming } from '../../../shared/worktree/create-types' -import type { WorkspaceCreateEntryPoint } from '../../../shared/worktree/create-timing-vocabulary' +import type { WorkspaceCreateEntryPoint } from '../../../shared/worktree/creation/create-timing-vocabulary' import { workspaceSourceSchema } from '../../../shared/telemetry-property-schemas' import type { EventProps } from '../../../shared/telemetry-event-classification' import type { WorkspaceSource } from '../../../shared/workspace-source' diff --git a/src/main/workspaces/creation/worktree-create-timing.ts b/src/main/workspaces/creation/worktree-create-timing.ts index 170498e92ea..56d32a63b8a 100644 --- a/src/main/workspaces/creation/worktree-create-timing.ts +++ b/src/main/workspaces/creation/worktree-create-timing.ts @@ -6,7 +6,7 @@ import type { import type { WorktreeCreateExecutionHost, WorktreeCreatePhase -} from '../../../shared/worktree/create-timing-vocabulary' +} from '../../../shared/worktree/creation/create-timing-vocabulary' import type { PreparationWork, WorktreeCreateInFlightHandle } from './worktree-create-concurrency' import { wslDistroForCommand } from '../../../shared/wsl-paths' diff --git a/src/main/workspaces/removal/folder-workspace-archive-hook.ts b/src/main/workspaces/removal/folder-workspace-archive-hook.ts index 987e1f89c56..911fb3e31c7 100644 --- a/src/main/workspaces/removal/folder-workspace-archive-hook.ts +++ b/src/main/workspaces/removal/folder-workspace-archive-hook.ts @@ -1,6 +1,6 @@ import { isRepoOnCatalogHost } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' -import type { ArchiveHookOverride } from '../../../shared/worktree/archive-hook-removal-gate' +import type { ArchiveHookOverride } from '../../../shared/worktree/removal/archive-hook-removal-gate' import { removeFolderSetupRunnerFiles } from '../../workspace-hooks/folder-setup-runner-files' import { getEffectiveHooks, runHook } from '../../workspace-hooks/hooks' import type { HookRuntimeTarget } from '../../workspace-hooks/hook-runtime-target' diff --git a/src/main/workspaces/removal/local-worktree-removal-recovery.test.ts b/src/main/workspaces/removal/local-worktree-removal-recovery.test.ts index a0613588f37..ee90666ddcb 100644 --- a/src/main/workspaces/removal/local-worktree-removal-recovery.test.ts +++ b/src/main/workspaces/removal/local-worktree-removal-recovery.test.ts @@ -29,7 +29,6 @@ import { recoverPartialLocalWorktreeRemoval, removeStaleLocalWorktreeRegistration } from './local-worktree-removal-recovery' -import { NESTED_WORKTREE_REMOVAL_PREFIX } from '../../../shared/worktree/nested-removal' async function withPlatform(platform: NodeJS.Platform, fn: () => Promise): Promise { const original = process.platform @@ -80,69 +79,6 @@ describe('recoverPartialLocalWorktreeRemoval', () => { signal: controller.signal }) ).rejects.toThrow(/aborted/i) - expect(removeLocalWorktreePathMock).toHaveBeenCalledWith( - 'C:/repo/worktree/feature', - {}, - controller.signal - ) - expect(closeWatcher).toHaveBeenCalledOnce() - expect(hostRmMock).toHaveBeenCalledOnce() - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - }) - - it('does not recursively delete while watcher teardown remains unconfirmed', async () => { - await withPlatform('win32', async () => { - const watcherError = new Error('file watcher process did not exit after termination deadline') - - await expect( - recoverPartialLocalWorktreeRemoval({ - error: new Error('git worktree remove failed'), - force: true, - canonicalWorktreePath: 'C:/repo/worktree/feature', - repoPath: 'C:/repo', - localWorktreeGitOptions: {}, - registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, - deleteBranch: true, - closeWatcher: vi.fn().mockRejectedValue(watcherError) - }) - ).rejects.toBe(watcherError) - - expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - }) - - it('does not delete a checkout that now contains a registered worktree', async () => { - await withPlatform('darwin', async () => { - listWorktreesStrictMock.mockResolvedValue([ - { - path: '/Users/dev/orca/workspaces/feature/nested', - head: 'def456', - branch: 'refs/heads/nested', - isBare: false, - isMainWorktree: false - } - ]) - const closeWatcher = vi.fn().mockResolvedValue(undefined) - - await expect( - recoverPartialLocalWorktreeRemoval({ - error: Object.assign(new Error('git worktree remove failed'), { - stderr: - "error: failed to delete '/Users/dev/orca/workspaces/feature': Directory not empty" - }), - force: true, - canonicalWorktreePath: '/Users/dev/orca/workspaces/feature', - repoPath: '/Users/dev/repo', - localWorktreeGitOptions: {}, - registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, - deleteBranch: true, - closeWatcher - }) - ).rejects.toThrow(NESTED_WORKTREE_REMOVAL_PREFIX) - expect(closeWatcher).not.toHaveBeenCalled() - expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() }) }) @@ -170,74 +106,6 @@ describe('recoverPartialLocalWorktreeRemoval', () => { closeWatcher }) ).rejects.toThrow('Worktree is locked by Git. Lock reason: active agent') - - expect(closeWatcher).not.toHaveBeenCalled() - expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() - expect(listWorktreesStrictMock).not.toHaveBeenCalled() - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - }) - - it.each([ - "error: failed to delete 'C:/repo/worktree/feature': Directory not empty", - 'error: failed to delete deep/file.txt: Filename too long' - ])( - 'does not recover a recognized Windows failure while Git still owns the row: %s', - async (stderr) => { - await withPlatform('win32', async () => { - listWorktreesStrictMock.mockResolvedValue([ - { - path: 'C:/repo/worktree/feature', - head: 'abc123', - branch: 'refs/heads/feature', - isBare: false, - isMainWorktree: false - } - ]) - const closeWatcher = vi.fn().mockResolvedValue(undefined) - - await expect( - recoverPartialLocalWorktreeRemoval({ - error: Object.assign(new Error('git worktree remove failed'), { stderr }), - force: true, - canonicalWorktreePath: 'C:/repo/worktree/feature', - repoPath: 'C:/repo', - localWorktreeGitOptions: { wslDistro: 'Ubuntu' }, - registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, - deleteBranch: true, - closeWatcher - }) - ).resolves.toBeUndefined() - - expect(listWorktreesStrictMock).toHaveBeenCalledWith('C:/repo', { wslDistro: 'Ubuntu' }) - expect(closeWatcher).not.toHaveBeenCalled() - expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() - }) - } - ) - - it('does not recover when structural registration verification fails', async () => { - await withPlatform('win32', async () => { - listWorktreesStrictMock.mockRejectedValue(new Error('git list failed')) - const closeWatcher = vi.fn().mockResolvedValue(undefined) - - await expect( - recoverPartialLocalWorktreeRemoval({ - error: Object.assign(new Error('git worktree remove failed'), { - stderr: "error: failed to delete 'C:/repo/worktree/feature': Directory not empty" - }), - force: true, - canonicalWorktreePath: 'C:/repo/worktree/feature', - repoPath: 'C:/repo', - localWorktreeGitOptions: {}, - registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, - deleteBranch: true, - closeWatcher - }) - ).resolves.toBeUndefined() - - expect(closeWatcher).not.toHaveBeenCalled() - expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() }) }) }) @@ -265,8 +133,6 @@ describe('removeStaleLocalWorktreeRegistration', () => { deleteBranch: true }) ).rejects.toThrow('Worktree is locked by Git') - - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() }) it('does not report success when prune leaves the registration behind', async () => { diff --git a/src/main/workspaces/removal/local-worktree-removal-recovery.ts b/src/main/workspaces/removal/local-worktree-removal-recovery.ts index 783c00a2405..3ede1ed9421 100644 --- a/src/main/workspaces/removal/local-worktree-removal-recovery.ts +++ b/src/main/workspaces/removal/local-worktree-removal-recovery.ts @@ -1,7 +1,7 @@ import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' import { pruneGitWorktrees } from '../../git/worktrees/removal/worktree-prune-guard' import type { GitWorktreeInfo } from '../../../shared/worktree/types' -import { assertWorktreeUnlockedForRemoval } from '../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../shared/worktree/removal/removal' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { formatWorktreeRemovalError, isOrphanedWorktreeError } from '../../ipc/worktree-logic' import { listWorktreesStrict } from '../../git/worktrees/catalog/worktree-listing' diff --git a/src/main/workspaces/removal/nested-worktree-removal-plan.ts b/src/main/workspaces/removal/nested-worktree-removal-plan.ts index bc3ca039cd1..b3a4e9d630e 100644 --- a/src/main/workspaces/removal/nested-worktree-removal-plan.ts +++ b/src/main/workspaces/removal/nested-worktree-removal-plan.ts @@ -1,8 +1,8 @@ import type { GitWorktreeInfo } from '../../../shared/worktree/types' -import type { NestedWorktreeRemovalApproval } from '../../../shared/worktree/nested-removal' +import type { NestedWorktreeRemovalApproval } from '../../../shared/worktree/removal/nested-removal' import { composeWorktreeId } from '../../../shared/worktree/id' import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' -import { assertWorktreeUnlockedForRemoval } from '../../../shared/worktree/removal' +import { assertWorktreeUnlockedForRemoval } from '../../../shared/worktree/removal/removal' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { containsPath, diff --git a/src/main/workspaces/removal/retirement/retirable-generated-name.ts b/src/main/workspaces/removal/retirement/retirable-generated-name.ts index c2dc57ae9d6..0dcccb8e696 100644 --- a/src/main/workspaces/removal/retirement/retirable-generated-name.ts +++ b/src/main/workspaces/removal/retirement/retirable-generated-name.ts @@ -1,4 +1,4 @@ -import { creatureNameTier } from '../../../../shared/worktree/retired-name-registry' +import { creatureNameTier } from '../../../../shared/worktree/naming/retired-name-registry' /** Persist canonical generator names only; repeat-suffixed collision fallbacks cannot be generated again. */ export function normalizeRetirableGeneratedName(name: string): string | null { diff --git a/src/main/workspaces/removal/retirement/worktree-name-retirement.ts b/src/main/workspaces/removal/retirement/worktree-name-retirement.ts index 35b5e49eaa5..06eea8a3a31 100644 --- a/src/main/workspaces/removal/retirement/worktree-name-retirement.ts +++ b/src/main/workspaces/removal/retirement/worktree-name-retirement.ts @@ -9,7 +9,7 @@ import { isEmptyRetiredNameRegistry, mergeRetiredNameRegistries, type RetiredNameRegistry -} from '../../../../shared/worktree/retired-name-registry' +} from '../../../../shared/worktree/naming/retired-name-registry' import { isFolderRepo } from '../../../../shared/repo-kind' import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { Repo } from '../../../../shared/repo-types' diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts index 1f335efe069..bd4ddbcb435 100644 --- a/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts +++ b/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts @@ -1,24 +1,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { MARINE_CREATURES } from '../../../../shared/marine-creatures' -import { createRetiredNameLookup } from '../../../../shared/worktree/retired-name-registry' -import { encodeClaudeProjectPath } from '../../../ai-vault/scanners/claude/claude-project-dir-encoding' -import { - RETIREMENT_BACKFILL_RETRY_AFTER_FAILURE_MS, - runRetirementBackfillScan -} from './worktree-retirement-backfill-scan' const { runWslTranscriptFsTaskMock, getWslHomeAsyncMock } = vi.hoisted(() => ({ runWslTranscriptFsTaskMock: vi.fn(), getWslHomeAsyncMock: vi.fn() })) -vi.mock('../../../native-chat/wsl-transcript-fs-gate', async (importOriginal) => ({ - ...((await importOriginal()) as Record), - runWslTranscriptFsTask: runWslTranscriptFsTaskMock -})) +vi.mock( + '../../../native-chat/transcript-filesystem/wsl-transcript-fs-gate', + async (importOriginal) => ({ + ...((await importOriginal()) as Record), + runWslTranscriptFsTask: runWslTranscriptFsTaskMock + }) +) // Keep parseWslPath and hasCachedWslHome real for the backfill path under test. vi.mock('../../../wsl/discovery/distro-catalog', async (importOriginal) => ({ @@ -27,11 +24,12 @@ vi.mock('../../../wsl/discovery/distro-catalog', async (importOriginal) => ({ })) const { discoverRetiredWorktreeNames } = await import('./worktree-retirement-discovery') -const { ensureRetiredWorktreeNamesBackfilled } = await import('./worktree-name-retirement') -const { WslTranscriptFsError } = await import('../../../native-chat/wsl-transcript-fs-gate') +await import('./worktree-name-retirement') +const { WslTranscriptFsError } = + await import('../../../native-chat/transcript-filesystem/wsl-transcript-fs-error') const FIRST = MARINE_CREATURES[0].toLowerCase() -const SECOND = MARINE_CREATURES[1].toLowerCase() + const DISTRO_ROOT = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\orca\\workspaces' describe('retirement discovery on WSL', () => { @@ -117,157 +115,7 @@ describe('retirement discovery on WSL', () => { expect(retired.complete).toBe(false) }) - it('keeps a deleted WSL workspace name spent, so the next create cannot reuse its cwd', async () => { - // The distro bucket outlives the deleted workspace and must keep its name retired. - const distroHome = await mkdtemp(join(tmpdir(), 'orca-wsl-distro-home-')) - const workspaceRoot = await mkdtemp(join(tmpdir(), 'orca-wsl-workspaces-')) - try { - await mkdir(join(distroHome, '.claude', 'projects', `-home-ada-orca-workspaces-${FIRST}`), { - recursive: true - }) - - const retired = await discoverRetiredWorktreeNames({ - // The root is listed under its real (empty) path; the UNC spelling supplies the distro. - workspaceRoots: [DISTRO_ROOT], - home: workspaceRoot, - env: {}, - resolveWslHome: async () => distroHome - }) - - expect(retired.names).toEqual(new Set([FIRST])) - expect(createRetiredNameLookup({ exhaustedTiers: 0, names: [...retired.names] })(FIRST)).toBe( - true - ) - } finally { - await rm(distroHome, { force: true, recursive: true }) - await rm(workspaceRoot, { force: true, recursive: true }) - } - }) - // A distro-root workspace folder encodes to the root prefix `-` on the Linux side. - it.each([ - ['a host bucket under the older \\\\wsl$\\ spelling', 'host', `--wsl--ubuntu-${FIRST}`], - ['a distro bucket', 'distro', `-${FIRST}`] - ])('keeps %s below a distro-root workspace folder spent', async (_case, side, bucket) => { - const homes = { - host: await mkdtemp(join(tmpdir(), 'orca-wsl-host-home-')), - distro: await mkdtemp(join(tmpdir(), 'orca-wsl-distro-home-')) - } - try { - await mkdir(join(homes[side], '.claude', 'projects', bucket), { recursive: true }) - - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['\\\\wsl.localhost\\Ubuntu'], - home: homes.host, - env: {}, - resolveWslHome: async () => homes.distro - }) - - expect(retired.names).toEqual(new Set([FIRST])) - } finally { - await rm(homes.host, { force: true, recursive: true }) - await rm(homes.distro, { force: true, recursive: true }) - } - }) // A refused permission stays refused on retry; a slow route may answer next time. - it.each([ - ['a permission refusal', Object.assign(new Error('EACCES'), { code: 'EACCES' }), 1], - ['a slow route', new WslTranscriptFsError('timeout', 'filesystem access is slow'), 2] - ])( - 'after %s on a long-path transcript, a later create rescans only if retrying can help', - async (_case, refusal, expectedProbes) => { - const distro = '\\\\wsl.localhost\\Ubuntu' - const longRoot = `/${'a'.repeat(229)}` - const distroDir = await mkdtemp(join(tmpdir(), 'orca-wsl-distro-')) - const hostHome = await mkdtemp(join(tmpdir(), 'orca-wsl-host-home-')) - try { - const projects = join(distroDir, 'home', 'ada', '.claude', 'projects') - await mkdir(join(distroDir, longRoot), { recursive: true }) - await mkdir(join(distroDir, 'home', 'ada', 'orca', 'workspaces'), { recursive: true }) - await mkdir(join(projects, `-home-ada-orca-workspaces-${FIRST}`), { recursive: true }) - const hashed = join( - projects, - `${encodeClaudeProjectPath(`${longRoot}/${SECOND}`).slice(0, 200)}-1x2y3z` - ) - await mkdir(hashed, { recursive: true }) - await writeFile(join(hashed, 'session.jsonl'), '{}\n') - let probes = 0 - runWslTranscriptFsTaskMock.mockImplementation( - async (options: { operation: string; path: string }) => { - if (options.path.endsWith('session.jsonl')) { - probes += 1 - throw refusal - } - const local = join(distroDir, options.path.slice(distro.length).replaceAll('\\', '/')) - return options.operation === 'readdir' - ? readdir(local, { withFileTypes: true }) - : stat(local) - } - ) - let now = 0 - vi.spyOn(performance, 'now').mockImplementation(() => now) - const store = {} - const create = () => - runRetirementBackfillScan(store, 'ns', () => - discoverRetiredWorktreeNames({ - workspaceRoots: [DISTRO_ROOT, `${distro}${longRoot}`], - home: hostHome, - env: {}, - resolveWslHome: async () => `${distro}\\home\\ada` - }) - ) - - await expect(create()).resolves.toEqual(new Set([FIRST])) - now += RETIREMENT_BACKFILL_RETRY_AFTER_FAILURE_MS + 1 - await expect(create()).resolves.toEqual(new Set([FIRST])) - - expect(probes).toBe(expectedProbes) - } finally { - await rm(distroDir, { force: true, recursive: true }) - await rm(hostHome, { force: true, recursive: true }) - } - } - ) - - it('reaches distro discovery from the real backfill, not only when called directly', async () => { - const distroHome = await mkdtemp(join(tmpdir(), 'orca-wsl-backfill-home-')) - try { - await mkdir(join(distroHome, '.claude', 'projects', `-home-ada-orca-workspaces-${FIRST}`), { - recursive: true - }) - getWslHomeAsyncMock.mockResolvedValue('\\\\wsl.localhost\\Ubuntu\\home\\ada') - runWslTranscriptFsTaskMock.mockImplementation( - (options: { path: string }, task: (signal: AbortSignal) => Promise) => { - const claudeRoot = join('\\\\wsl.localhost\\Ubuntu\\home\\ada', '.claude', 'projects') - return options.path === claudeRoot - ? readdir(join(distroHome, '.claude', 'projects'), { withFileTypes: true }) - : task(new AbortController().signal) - } - ) - const merged: string[] = [] - - await ensureRetiredWorktreeNamesBackfilled( - { - mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { - merged.push(...names) - return true - } - } as never, - { - id: 'repo-wsl', - path: '\\\\wsl.localhost\\Ubuntu\\home\\ada\\repos\\a', - displayName: 'a', - badgeColor: '', - addedAt: 0 - } as never, - // Use a UNC root directly; parseWslPath ignores UNC repo routing off Windows. - { workspaceDir: DISTRO_ROOT, nestWorkspaces: false } - ) - - expect(merged).toContain(FIRST) - } finally { - await rm(distroHome, { force: true, recursive: true }) - } - }) }) diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts index 5acb7526aec..460ee3c71f7 100644 --- a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts +++ b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts @@ -7,13 +7,16 @@ import { claudeProjectBucketNameBelowScope, mayBeHashedClaudeProjectBucketName } from '../../../ai-vault/scanners/claude/claude-project-dir-encoding' -import { CLAUDE_CWD_BUCKET_LAYOUT } from '../../../ai-vault/session-cwd-bucket-layouts' +import { CLAUDE_CWD_BUCKET_LAYOUT } from '../../../ai-vault/scope/session-cwd-bucket-layouts' import { cachedProjectDirCwd, cwdBucketScopePrefixes -} from '../../../ai-vault/session-scanner-scope-discovery' -import { wslGatedReaddir, wslGatedStat } from '../../../native-chat/wsl-transcript-fs-access' -import { WslTranscriptFsError } from '../../../native-chat/wsl-transcript-fs-error' +} from '../../../ai-vault/scope/session-scanner-scope-discovery' +import { + wslGatedReaddir, + wslGatedStat +} from '../../../native-chat/transcript-filesystem/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../../../native-chat/transcript-filesystem/wsl-transcript-fs-error' import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' import type { RetirementScanResult } from './worktree-retirement-backfill-scan' import { normalizeRetirableGeneratedName } from './retirable-generated-name' diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-namespace.ts b/src/main/workspaces/removal/retirement/worktree-retirement-namespace.ts index fbc9246d900..b23b0229ab4 100644 --- a/src/main/workspaces/removal/retirement/worktree-retirement-namespace.ts +++ b/src/main/workspaces/removal/retirement/worktree-retirement-namespace.ts @@ -2,7 +2,7 @@ import { getRepoExecutionHostId, parseExecutionHostId } from '../../../../shared import { mergeRetiredNameRegistries, type RetiredNameRegistry -} from '../../../../shared/worktree/retired-name-registry' +} from '../../../../shared/worktree/naming/retired-name-registry' import type { Repo } from '../../../../shared/repo-types' import { worktreePathComparisonKey } from '../../catalog/worktree-path-comparison-key' import { sshEndpointKey, type SshIdentityFields } from '../../../ssh/targets/ssh-target-identity' diff --git a/src/main/workspaces/removal/watcher-removal-gate.ts b/src/main/workspaces/removal/watcher-removal-gate.ts index 6d31f0d4c74..dd7eecdcb24 100644 --- a/src/main/workspaces/removal/watcher-removal-gate.ts +++ b/src/main/workspaces/removal/watcher-removal-gate.ts @@ -6,7 +6,7 @@ import { import { TERMINAL_REMOVAL_IN_PROGRESS_MESSAGE, WATCHER_REMOVAL_IN_PROGRESS_MESSAGE -} from '../../../shared/worktree/removal-fence-error' +} from '../../../shared/worktree/removal/removal-fence-error' // Identity tokens let timed-out removals abandon exact installs without late completions releasing newer fences. type WatcherInstallToken = symbol diff --git a/src/main/workspaces/removal/worktree-archive-hook-gate.ts b/src/main/workspaces/removal/worktree-archive-hook-gate.ts index a9ab1792d1f..8186a0035a6 100644 --- a/src/main/workspaces/removal/worktree-archive-hook-gate.ts +++ b/src/main/workspaces/removal/worktree-archive-hook-gate.ts @@ -4,7 +4,7 @@ import { formatArchiveHookFailure, type ArchiveHookOverride, type ArchiveHookRunResult -} from '../../../shared/worktree/archive-hook-removal-gate' +} from '../../../shared/worktree/removal/archive-hook-removal-gate' /** Run before PTY teardown, deregistration or deletion, while the archive hook still has its checkout. */ export function gateWorktreeRemovalOnArchiveHook(args: { diff --git a/src/main/workspaces/removal/worktree-background-removal-records.test.ts b/src/main/workspaces/removal/worktree-background-removal-records.test.ts index 766593102fe..b7bb55be801 100644 --- a/src/main/workspaces/removal/worktree-background-removal-records.test.ts +++ b/src/main/workspaces/removal/worktree-background-removal-records.test.ts @@ -7,16 +7,24 @@ import { _settlePendingWorktreeRemovalsForTests, loadWorktreeRemovalRecords, resumeInterruptedWorktreeRemovals, + retryFailedWorktreeRemoval, startBackgroundWorktreeRemoval, stopBackgroundWorktreeRemovals, - waitForPendingWorktreeRemoval + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from './worktree-background-removal' import { projectPendingWorktreeRemovals, - snapshotPendingWorktreeRemovals + snapshotPendingWorktreeRemovals, + withUnregisteredRemovalCheckouts } from './worktree-removal-listing' import type * as WorktreeRemovalRecords from './worktree-removal-records' -import { readWorktreeRemovalRecords } from './worktree-removal-records' +import { readWorktreeRemovalRecords, writeWorktreeRemovalRecords } from './worktree-removal-records' +import { + assertNoPendingWorktreeRemovalConflict, + pendingWorktreeRemovals, + persistWorktreeRemovalRecords +} from './worktree-removal-table' vi.mock('./worktree-removal-records', async (importOriginal) => { const actual = await importOriginal() @@ -25,6 +33,9 @@ vi.mock('./worktree-removal-records', async (importOriginal) => { writeWorktreeRemovalRecords: vi.fn(actual.writeWorktreeRemovalRecords) } }) +const actualRemovalRecords = await vi.importActual( + './worktree-removal-records' +) const removal = { worktreeId: 'repo-1::/work/feature', @@ -38,12 +49,17 @@ const isPending = (): boolean => waitForPendingWorktreeRemoval(removal.worktreeI let directory = '' beforeEach(async () => { + vi.mocked(writeWorktreeRemovalRecords).mockImplementation( + actualRemovalRecords.writeWorktreeRemovalRecords + ) directory = await mkdtemp(join(tmpdir(), 'orca-worktree-removal-records-')) await loadWorktreeRemovalRecords(directory) }) afterEach(async () => { vi.useRealTimers() + vi.restoreAllMocks() + vi.mocked(writeWorktreeRemovalRecords).mockReset() _resetPendingWorktreeRemovalsForTests() await rm(directory, { recursive: true, force: true }) }) @@ -101,9 +117,39 @@ describe('durable worktree removal records', () => { }) it('marks the row as removing after a restart and finishes it with the same job', async () => { + let releaseWrite!: () => void + const writing = new Promise((resolve) => { + releaseWrite = resolve + }) + vi.mocked(writeWorktreeRemovalRecords).mockImplementationOnce(async (...args) => { + await writing + await actualRemovalRecords.writeWorktreeRemovalRecords(...args) + }) const job = interruptedJob() void startBackgroundWorktreeRemoval({ removal, ...job }) - await vi.waitFor(() => expect(job.started()).toBe(true)) + const initial: { id: string; hostId?: 'local' }[] = [{ id: removal.worktreeId }] + expect( + projectPendingWorktreeRemovals( + initial, + (row) => row.id, + true, + snapshotPendingWorktreeRemovals() + ) + ).toEqual(initial) + expect( + projectPendingWorktreeRemovals( + initial, + (row) => row.id, + false, + snapshotPendingWorktreeRemovals() + ) + ).toEqual(initial) + expect(() => + assertNoPendingWorktreeRemovalConflict('/work/repo', { branch: 'feature' }) + ).toThrow('Cleanup is pending') + expect(await readWorktreeRemovalRecords(directory)).toEqual([]) + releaseWrite() + await waitForWorktreeRemovalAcceptance(removal.worktreeId) stopBackgroundWorktreeRemovals() await _settlePendingWorktreeRemovalsForTests() @@ -117,7 +163,10 @@ describe('durable worktree removal records', () => { ] expect( projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals()) - ).toEqual([{ id: removal.worktreeId, removing: true }, { id: 'repo-1::/work/other' }]) + ).toEqual([ + { id: removal.worktreeId, removing: true, removalRecorded: true }, + { id: 'repo-1::/work/other' } + ]) expect( projectPendingWorktreeRemovals( rows, @@ -142,6 +191,119 @@ describe('durable worktree removal records', () => { expect(isPending()).toBe(false) expect(await readWorktreeRemovalRecords(directory)).toEqual([]) await expect(joined).resolves.toEqual({}) - expect(publish).toHaveBeenCalledTimes(1) + }) + + it('retains the prior failure while a retry is unadmitted and after its save is refused', async () => { + const failed = { + worktreeId: removal.worktreeId, + repoId: removal.repoId, + repoPath: removal.repoPath, + worktreePath: directory, + branch: 'feature', + head: 'abc', + deleteBranch: true, + force: false, + requestedAt: 1, + failure: { message: 'Files are busy. Retry deletion.', failedAt: 2 } + } + await actualRemovalRecords.writeWorktreeRemovalRecords(directory, () => [failed]) + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(directory) + let refuseWrite!: (error: Error) => void + const writing = new Promise((_resolve, reject) => { + refuseWrite = reject + }) + vi.mocked(writeWorktreeRemovalRecords).mockImplementationOnce(() => writing) + const run = vi.fn(async () => ({})) + const retried = retryFailedWorktreeRemoval( + removal.worktreeId, + 'local', + () => ({ + run, + publish: () => {} + }), + true + ) + const refusal = expect(retried).rejects.toThrow('Could not start deletion') + expect( + projectPendingWorktreeRemovals<{ id: string; hostId?: 'local' }>( + [{ id: removal.worktreeId }], + (row) => row.id, + true, + snapshotPendingWorktreeRemovals() + ) + ).toEqual([{ id: removal.worktreeId, removalError: failed.failure.message }]) + expect(await withUnregisteredRemovalCheckouts(removal.repoId, [])).toHaveLength(1) + await persistWorktreeRemovalRecords() + expect(await readWorktreeRemovalRecords(directory)).toEqual([failed]) + refuseWrite(new Error('Disk full')) + await refusal + await _settlePendingWorktreeRemovalsForTests() + expect(run).not.toHaveBeenCalled() + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(directory) + expect(waitForPendingWorktreeRemoval(removal.worktreeId)).toBeUndefined() + expect(() => + assertNoPendingWorktreeRemovalConflict('/work/repo', { branch: 'feature' }) + ).toThrow('Retry deleting it before reusing its path or branch') + expect(await readWorktreeRemovalRecords(directory)).toEqual([failed]) + }) + + it('never resumes a refused force deletion captured alongside another repo admission', async () => { + let releaseWrite!: () => void + const writing = new Promise((resolve) => { + releaseWrite = resolve + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + let refuseSecond!: (error: Error) => void + const secondWrite = new Promise((_resolve, reject) => { + refuseSecond = reject + }) + let secondReservedAtSnapshot = false + vi.mocked(writeWorktreeRemovalRecords) + .mockImplementationOnce(async (directory, current, committed) => { + await writing + await actualRemovalRecords.writeWorktreeRemovalRecords( + directory, + () => { + secondReservedAtSnapshot = pendingWorktreeRemovals.has('repo-2::/other/force') + return current() + }, + committed + ) + }) + .mockImplementationOnce(() => secondWrite) + .mockRejectedValueOnce(new Error('No space for a cleanup rewrite')) + void startBackgroundWorktreeRemoval({ removal, ...interruptedJob() }) + const refused = startBackgroundWorktreeRemoval({ + removal: { + ...removal, + worktreeId: 'repo-2::/other/force', + repoId: 'repo-2', + repoPath: '/other/repo', + worktree: { path: '/other/force', branch: 'refs/heads/force', head: 'def' }, + force: true + }, + run: async () => ({}), + publish: () => {} + }) + const refusal = expect(refused).rejects.toThrow('Could not start deletion') + releaseWrite() + await waitForWorktreeRemovalAcceptance(removal.worktreeId) + expect(secondReservedAtSnapshot).toBe(true) + expect(pendingWorktreeRemovals.has('repo-2::/other/force')).toBe(true) + refuseSecond(new Error('No space for the second record')) + await refusal + await persistWorktreeRemovalRecords() + stopBackgroundWorktreeRemovals() + await _settlePendingWorktreeRemovalsForTests() + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(directory) + + expect( + (await readWorktreeRemovalRecords(directory)).map((record) => record.worktreeId) + ).toEqual([removal.worktreeId]) + expect(waitForPendingWorktreeRemoval('repo-2::/other/force')).toBeUndefined() + expect(waitForPendingWorktreeRemoval(removal.worktreeId)).toBeDefined() }) }) diff --git a/src/main/workspaces/removal/worktree-background-removal.test.ts b/src/main/workspaces/removal/worktree-background-removal.test.ts index 830b069ffca..51ed36ee159 100644 --- a/src/main/workspaces/removal/worktree-background-removal.test.ts +++ b/src/main/workspaces/removal/worktree-background-removal.test.ts @@ -1,9 +1,14 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ExecutionHostId } from '../../../shared/execution-host' import { _resetPendingWorktreeRemovalsForTests, _settlePendingWorktreeRemovalsForTests, startBackgroundWorktreeRemoval, + loadWorktreeRemovalRecords, + waitForWorktreeRemovalAcceptance, waitForPendingWorktreeRemoval } from './worktree-background-removal' @@ -33,8 +38,14 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { } describe('background worktree removal', () => { - afterEach(() => { + let directory = '' + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-background-removal-')) + await loadWorktreeRemovalRecords(directory) + }) + afterEach(async () => { _resetPendingWorktreeRemovalsForTests() + await rm(directory, { recursive: true, force: true }) }) it('resolves with the delete result once Git finishes, after the row has left the table', async () => { @@ -47,6 +58,7 @@ describe('background worktree removal', () => { }) expect(isPending()).toBe(true) + await waitForWorktreeRemovalAcceptance(removal.worktreeId) expect(pendingAtPublish).toEqual([true]) git.resolve({ preservedBranch: { branchName: 'feature', head: 'abc' } }) @@ -58,10 +70,9 @@ describe('background worktree removal', () => { expect(pendingAtPublish).toEqual([true, false]) }) - it('answers a request whose delete a concurrent removal of the same worktree replaced', async () => { + it('joins concurrent requests to the one recorded deletion', async () => { // The desktop IPC and runtime RPC removal paths coalesce separately, so both can be accepted. const first = deferred>() - const second = deferred<{ preservedBranch: { branchName: string; head: string } }>() const firstResult = startBackgroundWorktreeRemoval({ removal, run: () => first.promise, @@ -69,18 +80,13 @@ describe('background worktree removal', () => { }) const secondResult = startBackgroundWorktreeRemoval({ removal, - run: () => second.promise, + run: () => new Promise(() => {}), publish: () => {} }) first.resolve({}) await expect(firstResult).resolves.toEqual({}) - expect(isPending()).toBe(true) - - second.resolve({ preservedBranch: { branchName: 'feature', head: 'abc' } }) - await expect(secondResult).resolves.toEqual({ - preservedBranch: { branchName: 'feature', head: 'abc' } - }) + await expect(secondResult).resolves.toEqual({}) await _settlePendingWorktreeRemovalsForTests() expect(isPending()).toBe(false) }) @@ -129,12 +135,13 @@ describe('background worktree removal', () => { ).not.toThrow() }) - it('marks rows for clients that read the marker and omits them for clients that do not', () => { + it('marks rows for clients that read the marker and omits them for clients that do not', async () => { void startBackgroundWorktreeRemoval({ removal, run: () => new Promise(() => {}), publish: () => {} }) + await waitForWorktreeRemovalAcceptance(removal.worktreeId) const rows = [ { id: removal.worktreeId, hostId: 'local' as const }, { id: 'repo-1::/work/other' }, @@ -144,7 +151,7 @@ describe('background worktree removal', () => { expect( projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals()) ).toEqual([ - { id: removal.worktreeId, hostId: 'local', removing: true }, + { id: removal.worktreeId, hostId: 'local', removing: true, removalRecorded: true }, { id: 'repo-1::/work/other' }, { id: removal.worktreeId, hostId: 'ssh:box' } ]) @@ -185,10 +192,10 @@ describe('background worktree removal', () => { for (const clientReadsMarker of [true, false]) { expect( projectPendingWorktreeRemovals(rows, (row) => row.id, clientReadsMarker, pendingAtScan) - ).toEqual([{ id: other.worktreeId }]) + ).toEqual([{ id: other.worktreeId, removalError: 'git failed' }]) } expect( projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals()) - ).toBe(rows) + ).toEqual([{ id: removal.worktreeId }, { id: other.worktreeId, removalError: 'git failed' }]) }) }) diff --git a/src/main/workspaces/removal/worktree-background-removal.ts b/src/main/workspaces/removal/worktree-background-removal.ts index 4d016dbc1dd..c8da3913a78 100644 --- a/src/main/workspaces/removal/worktree-background-removal.ts +++ b/src/main/workspaces/removal/worktree-background-removal.ts @@ -1,3 +1,15 @@ +import { + addPendingRemoval, + assertAcceptedBranchChoice, + settlementsByWorktreeId, + waitForPendingWorktreeRemoval, + type RemovalSettlement +} from './worktree-removal-settlement' +export { + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance, + finishAcceptedWorktreeRemoval +} from './worktree-removal-settlement' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' import type { GitWorktreeInfo } from '../../../shared/worktree/types' @@ -13,8 +25,9 @@ import { finishedWorktreeRemovals, pendingWorktreeRemovals, persistWorktreeRemovalRecords, - setWorktreeRemovalRecordsDirectory, - worktreeCheckoutExists + recordedWorktreeRemovals, + recordWorktreeRemoval, + setWorktreeRemovalRecordsDirectory } from './worktree-removal-table' export type BackgroundWorktreeRemovalJob = { @@ -24,16 +37,11 @@ export type BackgroundWorktreeRemovalJob = { publish: () => void /** Clean the push-target remote even when Git partially fails. */ cleanupPushTargetRemote?: () => Promise -} - -type RemovalSettlement = { - result: Promise - resolve: (result: RemoveWorktreeResult) => void - reject: (error: unknown) => void + /** Release teardown fences when durable admission fails before run can take ownership. */ + admissionFailed?: () => Promise } const jobsByWorktreeId = new Map>() -const settlementsByWorktreeId = new Map() const stopControllers = new Set() // Loaded removals' terminal/watcher fences, held until the resumed job takes its own gate. const startupFencesByWorktreeId = new Map() @@ -48,7 +56,7 @@ export async function loadWorktreeRemovalRecords( for (const record of await readWorktreeRemovalRecords(directory)) { if (record.failure) { // Removed repos have no listing to clear a failed-removal record. - if (hasRepo(record.repoId) && (await worktreeCheckoutExists(record.worktreePath))) { + if (hasRepo(record.repoId)) { failedWorktreeRemovals.set(record.worktreeId, record) } else { droppedFailure = true @@ -56,7 +64,8 @@ export async function loadWorktreeRemovalRecords( continue } if (!pendingWorktreeRemovals.has(record.worktreeId)) { - addPendingRemoval(record) + recordedWorktreeRemovals.add(record) + addPendingRemoval(record).accept() try { startupFencesByWorktreeId.set( record.worktreeId, @@ -78,57 +87,6 @@ export function releaseStartupRemovalFence(worktreeId: string): void { startupFencesByWorktreeId.delete(worktreeId) } -function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement { - let resolve!: RemovalSettlement['resolve'] - let reject!: RemovalSettlement['reject'] - const result = new Promise((settle, fail) => { - resolve = settle - reject = fail - }) - // Older clients and restart-resumed jobs may have no caller to handle a rejection. - result.catch(() => {}) - const settlement = { result, resolve, reject } - failedWorktreeRemovals.delete(record.worktreeId) - pendingWorktreeRemovals.set(record.worktreeId, record) - settlementsByWorktreeId.set(record.worktreeId, settlement) - return settlement -} - -/** Pending removals are host-local; never join a same-ID checkout on another host. */ -export function waitForPendingWorktreeRemoval( - worktreeId: string, - hostId?: ExecutionHostId, - deleteBranch?: boolean -): Promise | undefined { - if ((hostId ?? LOCAL_EXECUTION_HOST_ID) !== LOCAL_EXECUTION_HOST_ID) { - return undefined - } - assertAcceptedBranchChoice(pendingWorktreeRemovals.get(worktreeId), deleteBranch) - return settlementsByWorktreeId.get(worktreeId)?.result -} - -function assertAcceptedBranchChoice( - record: WorktreeRemovalRecord | undefined, - deleteBranch: boolean | undefined -): void { - if (record && deleteBranch !== undefined && record.deleteBranch !== deleteBranch) { - throw new Error( - `Orca already accepted removal of ${record.worktreePath} with a different branch choice. That cleanup may already have run; check the branch before retrying.` - ) - } -} - -/** Await the delete while preserving the acceptance result fields. */ -export async function finishAcceptedWorktreeRemoval( - accepted: T, - worktreeId: string, - hostId?: ExecutionHostId -): Promise> { - const { removing, ...acceptance } = accepted - const pending = removing ? waitForPendingWorktreeRemoval(worktreeId, hostId) : undefined - return pending ? { ...acceptance, ...(await pending) } : acceptance -} - export function removesInBackground( worktreePath: string, options: { wslDistro?: string } @@ -145,6 +103,14 @@ export function startBackgroundWorktreeRemoval( > & { worktree: Pick } } & BackgroundWorktreeRemovalJob ): Promise { + const pending = waitForPendingWorktreeRemoval( + args.removal.worktreeId, + undefined, + args.removal.deleteBranch + ) + if (pending) { + return pending + } const { worktree, ...accepted } = args.removal const record: WorktreeRemovalRecord = { ...accepted, @@ -154,8 +120,7 @@ export function startBackgroundWorktreeRemoval( requestedAt: Date.now() } const settlement = addPendingRemoval(record) - runBackgroundWorktreeRemoval(record, args, persistWorktreeRemovalRecords()) - publishSafely(args.publish) + runBackgroundWorktreeRemoval(record, args, recordWorktreeRemoval(record)) return settlement.result } @@ -167,6 +132,10 @@ export function retryFailedWorktreeRemoval( force?: boolean, deleteBranch?: boolean ): Promise | undefined { + const pending = waitForPendingWorktreeRemoval(worktreeId, hostId, deleteBranch) + if (pending) { + return pending + } const failed = (hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID ? failedWorktreeRemovals.get(worktreeId) @@ -189,8 +158,7 @@ export function retryFailedWorktreeRemoval( return job.run(stopSignal) } } - runBackgroundWorktreeRemoval(record, leftoverOnly, persistWorktreeRemovalRecords()) - publishSafely(job.publish) + runBackgroundWorktreeRemoval(record, leftoverOnly, recordWorktreeRemoval(record)) return settlement.result } @@ -240,7 +208,31 @@ async function settleBackgroundWorktreeRemoval( recorded: Promise, stopSignal: AbortSignal ): Promise { - await waitForRecordWrite(record, recorded) + try { + await recorded + } catch (error) { + const refusal = new Error( + 'Could not start deletion. The workspace is still on disk; reopen any stopped terminals and try again.', + { cause: error } + ) + if (pendingWorktreeRemovals.get(record.worktreeId) === record) { + pendingWorktreeRemovals.delete(record.worktreeId) + settlementsByWorktreeId.delete(record.worktreeId) + } + try { + await job.admissionFailed?.() + } catch (cleanupError) { + console.warn('[worktrees] failed to release refused removal', cleanupError) + } + settlement?.refuse(refusal) + settlement?.reject(refusal) + publishSafely(job.publish) + return + } + if (settlement) { + settlement.accept() + } + publishSafely(job.publish) let settle: (settlement: RemovalSettlement) => void let failure: WorktreeRemovalRecord['failure'] try { @@ -285,28 +277,6 @@ async function settleBackgroundWorktreeRemoval( } } -// Prefer a durable resume record, but do not hold deletion indefinitely on stalled disk writes. -const RECORD_WRITE_WAIT_MS = 2_000 - -async function waitForRecordWrite( - record: WorktreeRemovalRecord, - recorded: Promise -): Promise { - let timer: ReturnType | undefined - const timedOut = await Promise.race([ - recorded.then(() => false), - new Promise((resolve) => { - timer = setTimeout(() => resolve(true), RECORD_WRITE_WAIT_MS) - }) - ]) - clearTimeout(timer) - if (timedOut) { - console.warn( - `[worktrees] removal record for ${record.worktreePath} not on disk after ${RECORD_WRITE_WAIT_MS} ms; deleting anyway` - ) - } -} - function publishSafely(publish: () => void): void { try { publish() diff --git a/src/main/workspaces/removal/worktree-failed-removal.test.ts b/src/main/workspaces/removal/worktree-failed-removal.test.ts index 72fd9a7255f..53870503ea0 100644 --- a/src/main/workspaces/removal/worktree-failed-removal.test.ts +++ b/src/main/workspaces/removal/worktree-failed-removal.test.ts @@ -25,7 +25,7 @@ import { withUnregisteredRemovalCheckouts } from './worktree-removal-listing' import { readWorktreeRemovalRecords } from './worktree-removal-records' -import { loadWorktreeRemovalRecordsForStore } from '../../startup/worktree-removal-records-load' +import { loadWorktreeRemovalRecordsForStore } from '../../startup/workspace-startup/worktree-removal-records-load' const listWorktreesStrictMock = vi.hoisted(() => vi.fn(async () => [])) @@ -124,7 +124,7 @@ describe('a delete that fails after Git dropped the registration', () => { false, snapshotPendingWorktreeRemovals() ) - ).toEqual(rows) + ).toEqual([{ id: worktreeId, removalError: GIT_ERROR }]) // Nothing fences the leftover: a failed delete must not block terminals indefinitely. beginTerminalInstall(checkout)() }) @@ -230,14 +230,21 @@ describe('a delete that fails after Git dropped the registration', () => { ]) }) - it('ends at the next listing once the checkout is deleted outside Orca', async () => { + it('keeps an absent-folder failure across restart until explicit cleanup succeeds', async () => { await failRemoval() await rm(checkout, { recursive: true }) + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(join(directory, 'profile')) + expect(await listRows()).toEqual([mainWorktree, leftoverRow()]) + const retried = retryFailedWorktreeRemoval(worktreeId, 'local', () => ({ + run: async () => ({}), + publish: () => {} + })) + await expect(retried).resolves.toEqual({}) + await _settlePendingWorktreeRemovalsForTests() expect(await listRows()).toEqual([mainWorktree]) - await vi.waitFor(async () => - expect(await readWorktreeRemovalRecords(join(directory, 'profile'))).toEqual([]) - ) + expect(await readWorktreeRemovalRecords(join(directory, 'profile'))).toEqual([]) }) it('ends at startup once its repo is removed from Orca, leaving the files', async () => { diff --git a/src/main/workspaces/removal/worktree-removal-close-records.test.ts b/src/main/workspaces/removal/worktree-removal-close-records.test.ts index 22c07c01fc6..6146832e6e9 100644 --- a/src/main/workspaces/removal/worktree-removal-close-records.test.ts +++ b/src/main/workspaces/removal/worktree-removal-close-records.test.ts @@ -13,7 +13,7 @@ import { tmpdir } from 'node:os' import { getDefaultWorkspaceSession } from '../../../shared/constants' import { toSshExecutionHostId } from '../../../shared/execution-host' import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import type { ClosedTerminalTabTombstonesByTabId } from '../../../shared/workspace-layout/closed-terminal-tab-tombstones' +import type { ClosedTerminalTabTombstonesByTabId } from '../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' diff --git a/src/main/workspaces/removal/worktree-removal-failure.ts b/src/main/workspaces/removal/worktree-removal-failure.ts index 0aea6fbd3f2..d711f22f7d3 100644 --- a/src/main/workspaces/removal/worktree-removal-failure.ts +++ b/src/main/workspaces/removal/worktree-removal-failure.ts @@ -13,18 +13,18 @@ export async function failureLeftByGit( error: unknown, cleanupPushTargetRemote: (() => Promise) | undefined ): Promise { - if (!(await worktreeCheckoutExists(record.worktreePath))) { - return undefined - } const message = error instanceof Error ? error.message : String(error) const failure = { message: message.replace( / Close (?:that program|any program using it) and delete again\.$/, () => - ` Close any program using it. You may need to delete the remaining folder at ${record.worktreePath} manually to finish removing this workspace.` + ` Close any program using it, then retry deletion. If you removed the folder at ${record.worktreePath} yourself, retry deletion to finish cleanup.` ), failedAt: Date.now() } + if (!(await worktreeCheckoutExists(record.worktreePath))) { + return failure + } try { const registered = await registeredRemovalCheckout(record) if (registered) { diff --git a/src/main/workspaces/removal/worktree-removal-leftover.ts b/src/main/workspaces/removal/worktree-removal-leftover.ts index 3ec38498863..5d735a5cd72 100644 --- a/src/main/workspaces/removal/worktree-removal-leftover.ts +++ b/src/main/workspaces/removal/worktree-removal-leftover.ts @@ -1,4 +1,4 @@ -import { unregisteredFolderRefusal } from '../../../shared/worktree/removal' +import { unregisteredFolderRefusal } from '../../../shared/worktree/removal/removal' import { usesNativeWindowsRemoval } from '../../git/worktrees/removal/windows-worktree-removal' import type { LocalProjectWorktreeGitOptions } from '../execution-host/project-runtime-git-options' import { lstat } from 'node:fs/promises' @@ -14,6 +14,7 @@ import type { WorktreeRemovalRecord } from './worktree-removal-records' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { CLIENT_REMOVAL_HOME } from './worktree-removal-home-guard' import { failedWorktreeRemovals, worktreeCheckoutExists } from './worktree-removal-table' +import { waitForWorktreeRemovalAcceptance } from './worktree-removal-settlement' import { assertWorktreeDoesNotContainRegisteredWorktree, canSafelyRemoveOrphanedWorktreeDirectory @@ -90,5 +91,9 @@ export async function retryFailedRemovalUnlessRegistered( if (failed && !usesNativeWindowsRemoval(worktreePath, localOptions)) { await assertUnregisteredCheckoutGone(failed.worktreePath, registeredWorktrees) } - return retry() !== undefined + if (retry() === undefined) { + return false + } + await waitForWorktreeRemovalAcceptance(worktreeId) + return true } diff --git a/src/main/workspaces/removal/worktree-removal-listing.ts b/src/main/workspaces/removal/worktree-removal-listing.ts index 6ff79174512..a12bd5cc4db 100644 --- a/src/main/workspaces/removal/worktree-removal-listing.ts +++ b/src/main/workspaces/removal/worktree-removal-listing.ts @@ -11,6 +11,7 @@ import { finishedWorktreeRemovals, pendingWorktreeRemovals, persistWorktreeRemovalRecords, + recordedWorktreeRemovals, worktreeCheckoutExists } from './worktree-removal-table' @@ -42,7 +43,9 @@ export async function withUnregisteredRemovalCheckouts( droppedFailure = true return row }) - const unlisted = [...pendingWorktreeRemovals.values(), ...failedWorktreeRemovals.values()].filter( + const unlisted = [ + ...new Map([...pendingWorktreeRemovals, ...failedWorktreeRemovals]).values() + ].filter( (record) => record.repoId === repoId && !gitWorktrees.some((worktree) => areWorktreePathsEqual(worktree.path, record.worktreePath)) @@ -51,8 +54,8 @@ export async function withUnregisteredRemovalCheckouts( for (const record of unlisted) { const failed = failedWorktreeRemovals.get(record.worktreeId) === record if ( - (await worktreeCheckoutExists(record.worktreePath)) && - (!failed || (await isUnregisteredRemovalLeftover(record.repoPath, record.worktreePath))) + (!failed && (await worktreeCheckoutExists(record.worktreePath))) || + (failed && (await isUnregisteredRemovalLeftover(record.repoPath, record.worktreePath))) ) { leftovers.push({ path: record.worktreePath, @@ -80,26 +83,46 @@ export function snapshotPendingWorktreeRemovals(): PendingWorktreeRemovals { /** Older clients cannot read removing markers; omit pending rows they already dropped on acceptance. */ export function projectPendingWorktreeRemovals< - T extends { hostId?: ExecutionHostId; removing?: true } + T extends { + hostId?: ExecutionHostId + removing?: true + removalRecorded?: true + removalError?: string + } >( rows: T[], idOf: (row: T) => string, clientReadsMarker: boolean, pendingAtScan: PendingWorktreeRemovals ): T[] { - if (pendingWorktreeRemovals.size === 0 && pendingAtScan.size === 0) { + if ( + pendingWorktreeRemovals.size === 0 && + pendingAtScan.size === 0 && + failedWorktreeRemovals.size === 0 + ) { return rows } const projected: T[] = [] for (const row of rows) { const id = idOf(row) const local = row.hostId === undefined || row.hostId === LOCAL_EXECUTION_HOST_ID - if (local && pendingWorktreeRemovals.has(id)) { + const pending = local ? pendingWorktreeRemovals.get(id) : undefined + if (pending && recordedWorktreeRemovals.has(pending)) { if (clientReadsMarker) { - projected.push({ ...row, removing: true }) + projected.push({ ...row, removing: true, removalRecorded: true }) } continue } + const failed = local ? failedWorktreeRemovals.get(id) : undefined + if (failed) { + projected.push({ + ...row, + removing: undefined, + removalRecorded: undefined, + removalError: failed.failure?.message + }) + continue + } const scanned = local ? pendingAtScan.get(id) : undefined // Git was read before deletion finished; do not resurrect the stale row as a failed delete. if (!scanned || !finishedWorktreeRemovals.has(scanned)) { @@ -108,3 +131,25 @@ export function projectPendingWorktreeRemovals< } return projected } + +export type WorktreeRemovalWitnessScan = { + removals?: PendingWorktreeRemovals + projectedRemovals?: PendingWorktreeRemovals +} + +/** Reuse repo-local witnesses across metadata joins; replace them only when reservations change. */ +export function projectCachedWorktreeRemovals( + repoId: string, + scan: WorktreeRemovalWitnessScan, + rows: T[], + idOf: (row: T) => string +): T[] { + const current = pendingWorktreeRemovals.snapshotForRepo(repoId) + if (scan.projectedRemovals !== current) { + if (current.size > 0) { + scan.removals = new Map([...(scan.removals ?? []), ...current]) + } + scan.projectedRemovals = current + } + return projectPendingWorktreeRemovals(rows, idOf, true, scan.removals ?? current) +} diff --git a/src/main/workspaces/removal/worktree-removal-records.ts b/src/main/workspaces/removal/worktree-removal-records.ts index a7bd71c18ed..6a255568d30 100644 --- a/src/main/workspaces/removal/worktree-removal-records.ts +++ b/src/main/workspaces/removal/worktree-removal-records.ts @@ -22,7 +22,7 @@ export type WorktreeRemovalRecord = { deleteBranch: boolean force: boolean requestedAt: number - /** Git dropped registration; branch/remote cleanup ran, but the folder remains. */ + /** Cleanup failed; files, Git ownership or metadata may still need an explicit retry. */ failure?: WorktreeRemovalFailure } @@ -97,13 +97,15 @@ export async function readWorktreeRemovalRecords( /** Read current records when the queued write runs so newer state wins. */ export function writeWorktreeRemovalRecords( directory: string, - current: () => WorktreeRemovalRecord[] + current: () => WorktreeRemovalRecord[], + committed?: () => void ): Promise { const file = worktreeRemovalRecordsFile(directory) - return withSidecarSnapshotQueue(file, () => - writeSidecarSnapshot(file, { + return withSidecarSnapshotQueue(file, async () => { + await writeSidecarSnapshot(file, { version: RECORDS_VERSION, removals: current() } satisfies PersistedWorktreeRemovalRecords) - ) + committed?.() + }) } diff --git a/src/main/workspaces/removal/worktree-removal-reservations.ts b/src/main/workspaces/removal/worktree-removal-reservations.ts new file mode 100644 index 00000000000..94f7d4de80e --- /dev/null +++ b/src/main/workspaces/removal/worktree-removal-reservations.ts @@ -0,0 +1,65 @@ +import type { WorktreeRemovalRecord } from './worktree-removal-records' + +const NO_REMOVALS: ReadonlyMap = new Map() + +/** Repo snapshots change only with their reservations, never with unrelated metadata joins. */ +export class WorktreeRemovalReservations extends Map { + private readonly byRepo = new Map>() + private readonly snapshots = new Map>() + + override set(id: string, record: WorktreeRemovalRecord): this { + const previous = this.get(id) + if (previous === record) { + return this + } + if (previous) { + this.removeRepoRecord(id, previous.repoId) + } + super.set(id, record) + let records = this.byRepo.get(record.repoId) + if (!records) { + records = new Map() + this.byRepo.set(record.repoId, records) + } + records.set(id, record) + this.snapshots.delete(record.repoId) + return this + } + + override delete(id: string): boolean { + const previous = this.get(id) + if (!previous) { + return false + } + this.removeRepoRecord(id, previous.repoId) + return super.delete(id) + } + + override clear(): void { + super.clear() + this.byRepo.clear() + this.snapshots.clear() + } + + snapshotForRepo(repoId: string): ReadonlyMap { + const records = this.byRepo.get(repoId) + if (!records) { + return NO_REMOVALS + } + let snapshot = this.snapshots.get(repoId) + if (!snapshot) { + snapshot = new Map(records) + this.snapshots.set(repoId, snapshot) + } + return snapshot + } + + private removeRepoRecord(id: string, repoId: string): void { + const records = this.byRepo.get(repoId) + records?.delete(id) + if (records?.size === 0) { + this.byRepo.delete(repoId) + } + this.snapshots.delete(repoId) + } +} diff --git a/src/main/workspaces/removal/worktree-removal-safety.ts b/src/main/workspaces/removal/worktree-removal-safety.ts index accbeb8cf4e..ed10b9db0ed 100644 --- a/src/main/workspaces/removal/worktree-removal-safety.ts +++ b/src/main/workspaces/removal/worktree-removal-safety.ts @@ -1,7 +1,7 @@ import { lstat, stat, readFile, realpath } from 'node:fs/promises' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import type { GitWorktreeInfo } from '../../../shared/worktree/types' -import { NESTED_WORKTREE_REMOVAL_PREFIX } from '../../../shared/worktree/nested-removal' +import { NESTED_WORKTREE_REMOVAL_PREFIX } from '../../../shared/worktree/removal/nested-removal' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { containsPath, diff --git a/src/main/workspaces/removal/worktree-removal-settlement.ts b/src/main/workspaces/removal/worktree-removal-settlement.ts new file mode 100644 index 00000000000..ee9f9c085cd --- /dev/null +++ b/src/main/workspaces/removal/worktree-removal-settlement.ts @@ -0,0 +1,82 @@ +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' +import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' +import type { WorktreeRemovalRecord } from './worktree-removal-records' +import { pendingWorktreeRemovals } from './worktree-removal-table' + +export type RemovalSettlement = { + accepted: Promise + accept: () => void + refuse: (error: unknown) => void + result: Promise + resolve: (result: RemoveWorktreeResult) => void + reject: (error: unknown) => void +} + +export const settlementsByWorktreeId = new Map() + +export function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement { + let accept!: RemovalSettlement['accept'] + let refuse!: RemovalSettlement['refuse'] + const accepted = new Promise((resolve, reject) => { + accept = resolve + refuse = reject + }) + accepted.catch(() => {}) + let resolve!: RemovalSettlement['resolve'] + let reject!: RemovalSettlement['reject'] + const result = new Promise((settle, fail) => { + resolve = settle + reject = fail + }) + // Older clients and restart-resumed jobs may have no caller to handle a rejection. + result.catch(() => {}) + const settlement = { accepted, accept, refuse, result, resolve, reject } + pendingWorktreeRemovals.set(record.worktreeId, record) + settlementsByWorktreeId.set(record.worktreeId, settlement) + return settlement +} + +/** Acceptance is separate from completion so CLI outcomes can keep waiting for Git. */ +export function waitForWorktreeRemovalAcceptance( + worktreeId: string, + hostId?: ExecutionHostId +): Promise | undefined { + return (hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID + ? settlementsByWorktreeId.get(worktreeId)?.accepted + : undefined +} + +/** Pending removals are host-local; never join a same-ID checkout on another host. */ +export function waitForPendingWorktreeRemoval( + worktreeId: string, + hostId?: ExecutionHostId, + deleteBranch?: boolean +): Promise | undefined { + if ((hostId ?? LOCAL_EXECUTION_HOST_ID) !== LOCAL_EXECUTION_HOST_ID) { + return undefined + } + assertAcceptedBranchChoice(pendingWorktreeRemovals.get(worktreeId), deleteBranch) + return settlementsByWorktreeId.get(worktreeId)?.result +} + +export function assertAcceptedBranchChoice( + record: WorktreeRemovalRecord | undefined, + deleteBranch: boolean | undefined +): void { + if (record && deleteBranch !== undefined && record.deleteBranch !== deleteBranch) { + throw new Error( + `Orca already accepted removal of ${record.worktreePath} with a different branch choice. That cleanup may already have run; check the branch before retrying.` + ) + } +} + +/** Await the delete while preserving the acceptance result fields. */ +export async function finishAcceptedWorktreeRemoval( + accepted: T, + worktreeId: string, + hostId?: ExecutionHostId +): Promise> { + const { removing, ...acceptance } = accepted + const pending = removing ? waitForPendingWorktreeRemoval(worktreeId, hostId) : undefined + return pending ? { ...acceptance, ...(await pending) } : acceptance +} diff --git a/src/main/workspaces/removal/worktree-removal-table.ts b/src/main/workspaces/removal/worktree-removal-table.ts index 069bfea06df..363fab881aa 100644 --- a/src/main/workspaces/removal/worktree-removal-table.ts +++ b/src/main/workspaces/removal/worktree-removal-table.ts @@ -1,9 +1,11 @@ +import { WorktreeRemovalReservations } from './worktree-removal-reservations' import { lstat } from 'node:fs/promises' import { getErrorCode } from '../../git/worktrees/worktree-operation-options' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { writeWorktreeRemovalRecords, type WorktreeRemovalRecord } from './worktree-removal-records' -export const pendingWorktreeRemovals = new Map() +export const pendingWorktreeRemovals = new WorktreeRemovalReservations() +export const recordedWorktreeRemovals = new WeakSet() // Failed leftovers stay visible until gone/replaced or their repo is removed; never retry without a request. export const failedWorktreeRemovals = new Map() // In-flight listings retain completed records only until their stale Git read is projected. @@ -18,14 +20,41 @@ export function persistWorktreeRemovalRecords(): Promise { if (!recordsDirectory) { return Promise.resolve() } - return writeWorktreeRemovalRecords(recordsDirectory, () => [ - ...pendingWorktreeRemovals.values(), - ...failedWorktreeRemovals.values() - ]).catch((error: unknown) => { + return writeWorktreeRemovalRecords(recordsDirectory, journalRecords).catch((error: unknown) => { console.warn('[worktrees] failed to persist worktree removal records', error) }) } +function journalRecords(candidate?: WorktreeRemovalRecord): WorktreeRemovalRecord[] { + const records = new Map(failedWorktreeRemovals) + for (const record of pendingWorktreeRemovals.values()) { + if (recordedWorktreeRemovals.has(record)) { + records.set(record.worktreeId, record) + } + } + if (candidate) { + records.set(candidate.worktreeId, candidate) + } + return [...records.values()] +} + +/** Commit only this admission; unrelated reservations must never reach a restart's journal. */ +export function recordWorktreeRemoval(record: WorktreeRemovalRecord): Promise { + if (!recordsDirectory) { + return Promise.reject( + new Error('Could not start deletion. Reopen the workspace and try again.') + ) + } + return writeWorktreeRemovalRecords( + recordsDirectory, + () => journalRecords(record), + () => { + recordedWorktreeRemovals.add(record) + failedWorktreeRemovals.delete(record.worktreeId) + } + ) +} + /** Unreadable counts as present: only a checkout proven gone ends a failed delete. */ export async function worktreeCheckoutExists(worktreePath: string): Promise { try { @@ -46,7 +75,7 @@ export function findPendingWorktreeRemovalConflict( target: { worktreePath?: string; branch?: string } ): WorktreeRemovalRecord | undefined { const branch = target.branch?.replace(/^refs\/heads\//, '') - for (const removal of pendingWorktreeRemovals.values()) { + for (const removal of [...pendingWorktreeRemovals.values(), ...failedWorktreeRemovals.values()]) { if (!areWorktreePathsEqual(removal.repoPath, repoPath)) { continue } @@ -67,7 +96,9 @@ export function assertNoPendingWorktreeRemovalConflict( const removal = findPendingWorktreeRemovalConflict(repoPath, target) if (removal) { throw new Error( - `Orca is still deleting the workspace at ${removal.worktreePath}. Cleanup is pending; try again shortly.` + removal.failure + ? `Cleanup failed for the workspace at ${removal.worktreePath}. Retry deleting it before reusing its path or branch.` + : `Orca is still deleting the workspace at ${removal.worktreePath}. Cleanup is pending; try again shortly.` ) } } diff --git a/src/main/workspaces/space-analysis/workspace-space-analysis.ts b/src/main/workspaces/space-analysis/workspace-space-analysis.ts index 7e745c307bf..843abf5bef2 100644 --- a/src/main/workspaces/space-analysis/workspace-space-analysis.ts +++ b/src/main/workspaces/space-analysis/workspace-space-analysis.ts @@ -128,7 +128,10 @@ export async function analyzeWorkspaceSpace( const repos = repoResults.map((result) => result.summary) const worktrees = repoResults .flatMap((result) => result.worktrees) - .sort((a, b) => b.sizeBytes - a.sizeBytes || a.displayName.localeCompare(b.displayName)) + .sort( + (a, b) => + b.sizeBytes - a.sizeBytes || (a.displayName ?? '').localeCompare(b.displayName ?? '') + ) throwIfWorkspaceSpaceScanAborted(options.signal) const summary = summarizeWorkspaceSpaceRows(worktrees) let unavailableRepoCount = 0 diff --git a/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts b/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts index 7efc50600d0..56696c38b17 100644 --- a/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts +++ b/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts @@ -33,7 +33,7 @@ function createBaseWorktreeRow(repo: Repo, worktree: Worktree, scannedAt: number executionHostId: getWorktreeExecutionHostId(worktree, repo), repoDisplayName: repo.displayName, repoPath: repo.path, - displayName: worktree.displayName, + displayName: worktree.displayName ?? '', path: worktree.path, branch: worktree.branch, isMainWorktree: worktree.isMainWorktree, diff --git a/src/main/wsl/discovery/distro-catalog.ts b/src/main/wsl/discovery/distro-catalog.ts index 29b97a676f4..16bd61f45dc 100644 --- a/src/main/wsl/discovery/distro-catalog.ts +++ b/src/main/wsl/discovery/distro-catalog.ts @@ -27,6 +27,7 @@ import { type RunningWslDistroReadOptions } from './wsl-running-distro-cache' import { clearWslHomeCache, getCachedWslHome, rememberWslHome } from './wsl-home-cache' +import { notifyWslDiscoveryChanged } from './wsl-discovery-change' // Measured on a slow PC: a cold systemd distro takes 4-11 s to answer its first exec, and killing // wsl.exe mid-boot leaves the distro failing every call with Wsl/Service/E_UNEXPECTED for 14+ s. @@ -76,11 +77,16 @@ function cacheWslDistroList(rawDistros: string[], probeSequence: number): string if (userDistros.length === 0 && wslDistroCache !== null && wslDistroCache.length > 0) { return wslDistroCache } + wslDistroCacheSequence = probeSequence + const changed = wslDistroCache?.join('\0') !== userDistros.join('\0') + wslDistroCache = userDistros + // After the list is written, so route reconciliation never sees half-updated discovery. if (userDistros.length > 0) { dropStaleWslAvailabilityFailure() } - wslDistroCacheSequence = probeSequence - wslDistroCache = userDistros + if (changed) { + notifyWslDiscoveryChanged() + } if (wslDistroCache.length === 0) { armWslDistroListRetry() } diff --git a/src/main/wsl/discovery/wsl-availability.ts b/src/main/wsl/discovery/wsl-availability.ts index e370b0a62f8..0ced1f39a0f 100644 --- a/src/main/wsl/discovery/wsl-availability.ts +++ b/src/main/wsl/discovery/wsl-availability.ts @@ -2,6 +2,7 @@ import { runProcess } from '@orca/process-host' import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' import { buildWslExecArgs } from '../../../shared/wsl-login-shell-command' import { wslExeProcessSpec } from '../execution/wsl-exe-process' +import { notifyWslDiscoveryChanged } from './wsl-discovery-change' type WslAvailabilityCache = | { available: true } @@ -52,8 +53,12 @@ function previousWslAvailabilityFailures(): number { } function writeWslAvailabilityCache(cache: WslAvailabilityCache | null): void { + const changed = (wslAvailableCache?.available ?? null) !== (cache?.available ?? null) wslAvailableCache = cache wslAvailabilityCacheGeneration += 1 + if (changed) { + notifyWslDiscoveryChanged() + } } type WslProbeFailure = { retryable: boolean } @@ -157,6 +162,7 @@ export function dropStaleWslAvailabilityFailure(): void { wslAvailabilityCacheGeneration += 1 if (wslAvailableCache && !wslAvailableCache.available && !('unsupported' in wslAvailableCache)) { wslAvailableCache = null + notifyWslDiscoveryChanged() } } diff --git a/src/main/wsl/discovery/wsl-discovery-change.ts b/src/main/wsl/discovery/wsl-discovery-change.ts new file mode 100644 index 00000000000..0b8dea5b201 --- /dev/null +++ b/src/main/wsl/discovery/wsl-discovery-change.ts @@ -0,0 +1,24 @@ +const listeners = new Set<() => void>() +let revision = 0 + +/** Runtime resolution reads the WSL discovery caches, so a changed answer can move a repo's Git route. */ +export function onWslDiscoveryChanged(listener: () => void): void { + listeners.add(listener) +} + +export function getWslDiscoveryRevision(): number { + return revision +} + +/** Synchronous: owners must stop trusting a route the new answer replaced before anything else runs. */ +export function notifyWslDiscoveryChanged(): void { + revision += 1 + for (const listener of listeners) { + try { + listener() + } catch (error) { + // A listener failure must not break the discovery write that notified it. + console.warn('[wsl] discovery change listener failed:', error) + } + } +} diff --git a/src/main/wsl/discovery/wsl-distro-unsupported.ts b/src/main/wsl/discovery/wsl-distro-unsupported.ts index 2d25769addc..bccb05fd3c6 100644 --- a/src/main/wsl/discovery/wsl-distro-unsupported.ts +++ b/src/main/wsl/discovery/wsl-distro-unsupported.ts @@ -2,7 +2,7 @@ * Distros that can't host Orca's server, each refused with the step that fixes it. There is no * fallback once the WSL bridge is gone, so a refusal must say what to run, not only what failed. */ -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import { OrcadHostGlibcUnsupportedError } from '../../managed-server/lifecycle/orcad-runtime-target' import { RemoteNodeRuntimeSelfTestError } from '../../managed-server/install/orcad-remote-node-runtime-report' import { wslHostAddRefusalText } from '../../../shared/wsl-host-failure-copy' diff --git a/src/main/wsl/discovery/wsl-running-distros.test.ts b/src/main/wsl/discovery/wsl-running-distros.test.ts index 86b34d66051..06f1996abd1 100644 --- a/src/main/wsl/discovery/wsl-running-distros.test.ts +++ b/src/main/wsl/discovery/wsl-running-distros.test.ts @@ -21,7 +21,7 @@ import { } from './distro-catalog' import { filterPathsToRunningWslDistrosAsync } from '../filesystem/wsl-running-path-filter' import '../execution/wsl-interop-spawn-directory' -import { resetWslTranscriptRunningObserverForTests } from '../../native-chat/wsl-transcript-running-observer' +import { resetWslTranscriptRunningObserverForTests } from '../../native-chat/transcript-filesystem/wsl-transcript-running-observer' async function withPlatform(value: NodeJS.Platform, fn: () => Promise): Promise { const original = process.platform @@ -69,32 +69,4 @@ describe('running WSL distro discovery', () => { expect(runProcessMock).toHaveBeenCalledTimes(3) }) }) - - it.each([true, false])( - 'shares the probe while preserving admission and observer failure policies (strict first: %s)', - async (strictFirst) => { - runProcessMock.mockResolvedValueOnce(exited('Ubuntu\n')) - - await withPlatform('win32', async () => { - await listRunningWslDistrosAsync() - let finishProbe: ((result: ProcessResult) => void) | undefined - runProcessMock.mockImplementationOnce( - () => - new Promise((resolve) => { - finishProbe = resolve - }) - ) - const first = listRunningWslDistrosAsync({ requireConfirmed: strictFirst }) - const second = listRunningWslDistrosAsync({ requireConfirmed: !strictFirst }) - const strict = strictFirst ? first : second - const observer = strictFirst ? second : first - const rejected = expect(strict).rejects.toThrow('discovery is unavailable') - expect(runProcessMock).toHaveBeenCalledTimes(2) - finishProbe?.(FAILED) - await rejected - await expect(observer).resolves.toEqual(['Ubuntu']) - expect(runProcessMock).toHaveBeenCalledTimes(2) - }) - } - ) }) diff --git a/src/main/wsl/execution/wsl-guest-process-identity.ts b/src/main/wsl/execution/wsl-guest-process-identity.ts index 4ee30b043e2..cfd98d870a1 100644 --- a/src/main/wsl/execution/wsl-guest-process-identity.ts +++ b/src/main/wsl/execution/wsl-guest-process-identity.ts @@ -1,5 +1,5 @@ /** Use kernel boot ID and /proc start ticks for distro/process identity; wall-clock jumps after host sleep can misidentify live processes (microsoft/WSL#4179/#10006). */ -import type { OrcadProcessIncarnation } from '../../orcad/orcad-process-start-time' +import type { OrcadProcessIncarnation } from '../../orcad/instance-lock/orcad-process-start-time' import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' diff --git a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.test.ts b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.test.ts index b0078d3324b..d0b0117af8a 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.test.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { getDefaultPersistedState } from '../../../shared/constants' import type { PersistedState } from '../../../shared/persisted-state-types' -import '../../persistence/__fixtures__/wsl-mover/wsl-mover-folders-profile' import { heavyWslMoverProfile } from '../../persistence/__fixtures__/wsl-mover/wsl-mover-heavy-profile' import { repo, diff --git a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts index 2947cd711ff..4eeee3fc3d7 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts @@ -16,7 +16,7 @@ import { } from '../../../shared/worktree/id' import { PTY_SESSION_ID_SEPARATOR } from '../../../shared/terminal/pty/lifecycle/pty-session-id-format' import { isWorkspaceKey, parseWorkspaceKey } from '../../../shared/workspace-scope' -import { withCrossStoreChildKey } from '../../../shared/worktree/cross-store-lineage-records' +import { withCrossStoreChildKey } from '../../../shared/worktree/lineage/cross-store-lineage-records' import { WSL_DRIVE_UNC_STATE_DISPOSITIONS } from '../../../shared/wsl-drive-unc-state-dispositions' import { wslMoveRepoPaths } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-scope' import { withoutDiscoveryShadows } from './wsl-drive-unc-discovery-shadows' diff --git a/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts b/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts index 0bef7c7b592..d28d17346ea 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts @@ -1,6 +1,6 @@ import { errorMessage } from '../../../shared/error-message' import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import { WslDistroNotRunningError, WslOrcadLaunchDeferredError diff --git a/src/main/wsl/host-lifecycle/wsl-host-distro-list.test.ts b/src/main/wsl/host-lifecycle/wsl-host-distro-list.test.ts new file mode 100644 index 00000000000..32528ce113a --- /dev/null +++ b/src/main/wsl/host-lifecycle/wsl-host-distro-list.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it, vi } from 'vitest' +import { listWslHostDistros } from './wsl-host-distro-list' + +describe('listWslHostDistros', () => { + it('never reads the running list when the registry cannot be read (no WSL installed)', async () => { + const readRunning = vi.fn() + await expect( + listWslHostDistros({ readRegistrations: async () => null, readRunning }) + ).resolves.toEqual([]) + expect(readRunning).not.toHaveBeenCalled() + }) + + it('never reads the running list when only internal distros are registered', async () => { + const readRunning = vi.fn() + await expect( + listWslHostDistros({ + readRegistrations: async () => [{ id: 'a', distro: 'docker-desktop', version: 2 }], + readRunning + }) + ).resolves.toEqual([]) + expect(readRunning).not.toHaveBeenCalled() + }) + + it('marks user distros running, stopped, or unverifiable from the running list', async () => { + const readRegistrations = async () => [ + { id: 'b', distro: 'Ubuntu', version: 2 as const }, + { id: 'a', distro: 'Debian', version: 1 as const }, + { id: 'c', distro: 'docker-desktop', version: 2 as const } + ] + await expect( + listWslHostDistros({ + readRegistrations, + readRunning: async () => ({ status: 'confirmed', distros: ['ubuntu'] }) + }) + ).resolves.toEqual([ + { id: 'a', name: 'Debian', version: 1, state: 'stopped' }, + { id: 'b', name: 'Ubuntu', version: 2, state: 'running' } + ]) + await expect( + listWslHostDistros({ + readRegistrations, + readRunning: async () => { + throw new Error('wsl.exe failed') + } + }) + ).resolves.toEqual([ + { id: 'a', name: 'Debian', version: 1, state: 'unverifiable' }, + { id: 'b', name: 'Ubuntu', version: 2, state: 'unverifiable' } + ]) + }) +}) diff --git a/src/main/wsl/host-lifecycle/wsl-host-distro-list.ts b/src/main/wsl/host-lifecycle/wsl-host-distro-list.ts index 4a16ab8c785..5b5fa61ebca 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-distro-list.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-distro-list.ts @@ -20,20 +20,19 @@ export type WslHostDistroCandidate = Omit & { id export async function listWslHostDistros( dependencies: WslHostDistroListDependencies = {} ): Promise { - const [registered, running] = await Promise.all([ - (dependencies.readRegistrations ?? readWslDistroRegistrations)(), - (dependencies.readRunning ?? readConfirmedRunningWslDistros)().catch( - (): WslRunningDistrosRead => ({ status: 'unavailable' }) - ) - ]) - if (!registered) { + const registered = await (dependencies.readRegistrations ?? readWslDistroRegistrations)() + const userNames = new Set(filterUserWslDistros((registered ?? []).map(({ distro }) => distro))) + // Without WSL, Windows' wsl.exe stub opens the installer and a UAC prompt: never spawn it for nothing. + if (!registered || userNames.size === 0) { return [] } + const running = await (dependencies.readRunning ?? readConfirmedRunningWslDistros)().catch( + (): WslRunningDistrosRead => ({ status: 'unavailable' }) + ) const runningKeys = running.status === 'confirmed' ? new Set(running.distros.map((name) => name.trim().toLowerCase())) : null - const userNames = new Set(filterUserWslDistros(registered.map(({ distro }) => distro))) return registered .filter(({ distro }) => userNames.has(distro)) .map(({ id, distro, version }) => ({ diff --git a/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts b/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts index 05b54127ddf..1bc383a74f6 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts @@ -1,7 +1,7 @@ /** Before Add persists its record, removal/disable/startup cannot find the connection or detached holder. Every unsuccessful Add must release both here. */ import { errorMessage } from '../../../shared/error-message' import type { WslHostAddResult } from '../../../shared/wsl-host-types' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import type { WslHostConnector } from './wsl-host-connector-contract' import { WslOrcadLaunchDeferredError } from '../orcad/wsl-orcad-connection-errors' import { diff --git a/src/main/wsl/host-lifecycle/wsl-host-gate.ts b/src/main/wsl/host-lifecycle/wsl-host-gate.ts index 4da160636b7..8f5730fc835 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-gate.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-gate.ts @@ -12,7 +12,7 @@ import type { OrcadDeploymentLink } from '../../../shared/remote-runtime/host-ca import { wslHostRunRefusal, WSL_HOST_REMOVING_MESSAGE } from './wsl-host-add-admission' import type { WslHostsMovedProjects, WslHostsPolicyState } from '../../../shared/wsl-hosts-policy' -export const WSL_HOSTS_GATED_OFF_MESSAGE = 'WSL hosts are not available in this build.' +export const WSL_HOSTS_GATED_OFF_MESSAGE = 'WSL hosts are turned off for this launch of Orca.' // Fixed for the run once main reads the disk; nothing can create a host or a move while not open. let promoted: { hasSavedWslHost: boolean; hasWslMoveCutover: boolean } | null = null diff --git a/src/main/wsl/host-lifecycle/wsl-host-service-user-actions.test.ts b/src/main/wsl/host-lifecycle/wsl-host-service-user-actions.test.ts index c4c88b79e08..2c0e65aee9f 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-service-user-actions.test.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-service-user-actions.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { removeThroughOwningService } from '../../ipc/runtime-environments/runtime-environment-host-service-ops' +import { removeThroughOwningService } from '../../ipc/runtime-environments/connectivity/runtime-environment-host-service-ops' import { WslHostService } from './wsl-host-service' import type { WslHostConnector } from './wsl-host-connector-contract' import { setWslHostService } from './wsl-host-service-instance' @@ -49,7 +49,6 @@ describe('WslHostService Remove as a user action', () => { try { await service.add({ distro: 'Ubuntu' }) const [environment] = listEnvironments(userDataPath) - expect(environment).toBeDefined() await removeThroughOwningService(environment!) expect(heard).toEqual([{ kind: 'removed', distro: 'Ubuntu' }]) } finally { diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts index cabb9eded94..47b8f8a55dc 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts @@ -1,4 +1,4 @@ -import { packagedClaudeChatScenario } from '../../../orcad/orcad-structured-chat-scenario' +import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' /** The normal streamed reply stays open for an approval and the user's Stop. */ export function wslClaudeChatScenario(providerSessionId: string, partialReplyAckPath: string) { diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts index 76073103fc8..83f9aec0c30 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts @@ -1,5 +1,5 @@ import type { WslHostStatus } from '../../../../shared/wsl-host-types' -import { hasOrcadTemplate } from '../../../orcad/orcad-artifact-materializer' +import { hasOrcadTemplate } from '../../../orcad/artifact-slots/orcad-artifact-materializer' import { createWslHostConnector } from '../../host-lifecycle/wsl-host-connector' import type { WslHostConnector } from '../../host-lifecycle/wsl-host-connector-contract' import { WslHostService } from '../../host-lifecycle/wsl-host-service' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts index 74ffab31b6d..e99dfddfb14 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts @@ -18,8 +18,8 @@ import { latestNativeChatOrcaStopCut } from '../../../../shared/native-chat/nati import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import type { WslHostStatus } from '../../../../shared/wsl-host-types' import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' -import '../../../orcad/orcad-artifact-materializer' -import { packagedClaudeChatScenario } from '../../../orcad/orcad-structured-chat-scenario' +import '../../../orcad/artifact-slots/orcad-artifact-materializer' +import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' import { wslDistroHolderKey } from '../../discovery/wsl-distro-holder-record' import { wslHostStoppedMessage } from '../../../../shared/wsl-host-stopped-message' import { wslHostConnectOptions } from '../../host-lifecycle/wsl-host-connect-request' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts index bac2b644fd2..2aebf199ad0 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts @@ -13,7 +13,7 @@ import '../../../../shared/remote-runtime/requests/remote-runtime-request-socket import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' -import { packagedClaudeChatScenario } from '../../../orcad/orcad-structured-chat-scenario' +import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import { wslClaudeChatScenario } from './wsl-orcad-chat-scenario' import { envelope } from './wsl-orcad-chat-envelope' diff --git a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts index a534753826a..50b5a2f3ae7 100644 --- a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts +++ b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts @@ -21,7 +21,7 @@ import { } from '../../managed-server/activation/orcad-activation-transaction' import { execOrcadRemote } from '../../managed-server/install/orcad-remote-runtime-control' import { probeInstallLockExistsCommand } from '../../managed-server/install/remote-install-lock-commands' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { parseWslGuestIdentity, wslGuestIdentityShellCommand, diff --git a/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts b/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts index b577859aeea..06252bebd44 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts @@ -54,7 +54,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', () => ({ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: mocks.recover })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) @@ -413,50 +413,6 @@ describe('deployAndLaunchWslOrcad across an app update (E1)', () => { expect(mocks.deploy).toHaveBeenCalledTimes(2) }) - it('keeps retrying an update that only waited, or that a newer host refused', async () => { - mocks.deploy.mockResolvedValue({ - outcome: 'installed-not-activated', - fullVersion: '1.5.0+ab', - code: 'orcad_update_terminals_running', - reason: 'busy' - }) - await launch() - await launch() - mocks.deploy.mockResolvedValue(policyRefused) - await launch() - await launch() - expect(mocks.deploy).toHaveBeenCalledTimes(4) - expect(mocks.adoptRunning).not.toHaveBeenCalled() - }) - - it('lets the next connect try again once an explicit Force went through', async () => { - mocks.deploy.mockResolvedValueOnce(rejected) - await launch() - mocks.deploy.mockResolvedValueOnce({ - outcome: 'installed-and-activated', - fullVersion: '1.5.0+ab', - verdict: {} - }) - await launch(undefined, { intent: 'force' }) - mocks.deploy.mockResolvedValueOnce(rejected) - await launch() - expect(mocks.deploy).toHaveBeenCalledTimes(3) - }) - - it('deploys on the record the wake read when the skipped build stopped meanwhile', async () => { - withRecord(newer) - const stopped = { ...newer, active: null, activatedAt: null } - mocks.adoptRunning.mockResolvedValueOnce(null) - mocks.readRecord.mockResolvedValueOnce(stopped) - mocks.deploy.mockResolvedValueOnce(policyRefused) - await launch() - expect(mocks.incumbent).not.toHaveBeenCalled() - expect(mocks.deploy.mock.calls[0][0]).toMatchObject({ - censusRecord: stopped, - census: { liveSessions: 0 } - }) - }) - it('leaves a host stopped after a rollback for Force, not the build it rolled back from', async () => { // Desktop lacks the previous bundle and cannot restart it. const stopped = { diff --git a/src/main/wsl/orcad/wsl-orcad-deploy.test.ts b/src/main/wsl/orcad/wsl-orcad-deploy.test.ts index 323ca16f7d2..682a54a6756 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy.test.ts @@ -56,7 +56,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', () => ({ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: mocks.recover })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) @@ -198,13 +198,4 @@ describe('deployAndLaunchWslOrcad', () => { await expect(launch()).rejects.toBe(refused) expect(mocks.wake).toHaveBeenCalledTimes(3) }) - - it('refuses to deploy or launch when an unrecorded orcad cannot be proven', async () => { - mocks.adopt.mockRejectedValueOnce( - Object.assign(new Error('cannot be identified'), { name: 'WslOrcadUnrecordedInstanceError' }) - ) - await expect(launch()).rejects.toMatchObject({ name: 'WslOrcadUnrecordedInstanceError' }) - expect(mocks.deploy).not.toHaveBeenCalled() - expect(mocks.wake).not.toHaveBeenCalled() - }) }) diff --git a/src/main/wsl/orcad/wsl-orcad-deploy.ts b/src/main/wsl/orcad/wsl-orcad-deploy.ts index 8901944fd21..db72186bc98 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy.ts @@ -8,7 +8,7 @@ import type { ServeReadiness } from '../../server/serve-readiness' import { recoverInterruptedOrcadActivation } from '../../managed-server/activation/orcad-activation-recovery' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../managed-server/activation/orcad-installed-activation' import { orcadBoundPort } from '../../managed-server/lifecycle/orcad-managed-bound-port' diff --git a/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts b/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts index f861a356a7d..97d94c036d5 100644 --- a/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts +++ b/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts @@ -1,10 +1,10 @@ /** Adopt serving unrecorded orcad under the activation fence only when lock, readiness and installed build identify the same process. Never kill it without census; launching another loses the instance lock. Normal update admission handles version changes. */ -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { parseOrcadInstanceLockRecord, type OrcadLockRecord -} from '../../orcad/orcad-instance-lock-record' -import { compareOrcadProcessIdentity } from '../../orcad/orcad-process-start-time' +} from '../../orcad/instance-lock/orcad-instance-lock-record' +import { compareOrcadProcessIdentity } from '../../orcad/instance-lock/orcad-process-start-time' import type { OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' import { readOrcadActivationRecord, diff --git a/src/main/wsl/orcad/wsl-orcad-liveness-supervisor.test.ts b/src/main/wsl/orcad/wsl-orcad-liveness-supervisor.test.ts index 234c3ad0ed5..21922570d8d 100644 --- a/src/main/wsl/orcad/wsl-orcad-liveness-supervisor.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-liveness-supervisor.test.ts @@ -5,19 +5,7 @@ import type { WslRunningDistrosRead } from '../discovery/wsl-background-distro-g import type { WslGuestIdentity } from '../execution/wsl-guest-process-identity' import type { WslOrcadConnection } from './wsl-orcad-connection-types' import type { WslOrcadConnectionStatus } from './wsl-orcad-connection-status' -import { EXIT_SETTLE_MS } from './wsl-orcad-liveness-evidence' -import { WSL_ORCAD_HEARTBEAT_MS } from './wsl-orcad-liveness-state' -import { WSL_ORCAD_IDLE_VERIFY_MS } from './wsl-orcad-liveness-monitor' -import { - WslDistroNotRunningError, - WslDistroUnverifiableConnectError -} from './wsl-orcad-connection-errors' import { WslOrcadLivenessSupervisor } from './wsl-orcad-liveness-supervisor' -import { WSL_ORCAD_RECONNECT_DELAYS_MS } from './wsl-orcad-reconnect-backoff' -import { - WSL_ORCAD_STOPPING_POLL_MS, - WSL_ORCAD_STOPPING_WINDOW_MS -} from './wsl-orcad-liveness-stopping-poll' import type { WslOrcadWatch } from './wsl-orcad-watch' const CENSUS: OrcadTerminalCensus = { @@ -220,166 +208,6 @@ describe('WslOrcadLivenessSupervisor', () => { expect(h.statuses.at(-1)).toEqual({ state: 'ready', census: CENSUS }) }) - it('reports settling right after an exit, while the running list may be stale (E9)', async () => { - const h = harness({ visible: true }) - await h.supervisor.connect('Ubuntu') - expect(h.supervisor.isSettling('Ubuntu')).toBe(false) - // WSL still lists the stopping distro as running. - h.state.running = { status: 'confirmed', distros: ['Ubuntu'] } - h.lastWatch().exit(1) - expect(h.supervisor.isSettling('Ubuntu')).toBe(true) - h.state.running = { status: 'confirmed', distros: [] } - await h.advance(60_000) - expect(h.statuses.at(-1)).toMatchObject({ state: 'distro-stopped' }) - expect(h.supervisor.isSettling('Ubuntu')).toBe(false) - }) - - it('re-verifies after a no-boot connect is refused, so the distro still gets a verdict (E9)', async () => { - const h = harness({ visible: true }) - await h.supervisor.connect('Ubuntu') - h.state.running = { status: 'confirmed', distros: [] } - h.state.ensureFails = 1 - h.state.ensureError = new WslDistroNotRunningError('Ubuntu') - await expect(h.supervisor.connect('Ubuntu', { noBoot: true })).rejects.toBeInstanceOf( - WslDistroNotRunningError - ) - await h.advance(60_000) - expect(h.statuses.at(-1)).toMatchObject({ state: 'distro-stopped' }) - }) - - it('re-verifies, never arms, when a no-boot connect could not read the running list (E9)', async () => { - const h = harness({ visible: true }) - await h.supervisor.connect('Ubuntu') - const watches = h.watchCount() - h.state.running = { status: 'confirmed', distros: [] } - h.state.ensureFails = 1 - h.state.ensureError = new WslDistroUnverifiableConnectError('Ubuntu') - await expect(h.supervisor.connect('Ubuntu', { noBoot: true })).rejects.toBeInstanceOf( - WslDistroUnverifiableConnectError - ) - expect(h.watchCount()).toBe(watches) - await h.advance(60_000) - expect(h.statuses.at(-1)).toMatchObject({ state: 'distro-stopped' }) - }) - - it('reports settling after a clean exit too (code 0 from wsl --shutdown)', async () => { - const h = harness({ visible: true }) - await h.supervisor.connect('Ubuntu') - h.state.running = { status: 'confirmed', distros: ['Ubuntu'] } - h.lastWatch().exit(0) - // Past the verdict pass (settle and re-read), the window after the exit still holds. - await h.advance(1_000) - expect(h.supervisor.isSettling('Ubuntu')).toBe(true) - await h.advance(10_000) - expect(h.supervisor.isSettling('Ubuntu')).toBe(false) - }) - - it('settles a clean exit before reading identity, so a stale list cannot boot the distro', async () => { - const h = harness({ visible: true }) - await h.supervisor.connect('Ubuntu') - const identityReads = h.readIdentity.mock.calls.length - // wsl --shutdown ends the watch cleanly while WSL still lists the distro for a moment. - h.state.running = { status: 'confirmed', distros: [] } - h.readRunning.mockResolvedValueOnce({ status: 'confirmed', distros: ['Ubuntu'] }) - h.lastWatch().exit(0) - await h.advance(60_000) - expect(h.statuses.at(-1)).toMatchObject({ state: 'distro-stopped' }) - // Never exec'd into the stopping distro. - expect(h.readIdentity).toHaveBeenCalledTimes(identityReads) - }) - - it('re-ensures the holder once a connect is armed', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - // An earlier orcad's idle release may have ended the holder the launch adopted. - expect(h.ensureHolder).toHaveBeenCalledExactlyOnceWith('Ubuntu') - }) - - it('never boots a stopped distro for background work; the gate resumes it once running', async () => { - const h = harness({ visible: false }) - await h.supervisor.connect('Ubuntu') - h.ensureHolder.mockClear() - h.state.running = { status: 'confirmed', distros: [] } - h.lastWatch().exit(1) - await h.advance(60_000) - expect(h.statuses).toEqual([ - { state: 'distro-stopped', terminals: 'exited', recovering: false } - ]) - expect(h.ensure).toHaveBeenCalledTimes(1) - expect(h.ensureHolder).not.toHaveBeenCalled() - // A dial to a kept listener would spawn wsl.exe and boot the stopped distro. - expect(h.retireListener).toHaveBeenCalledExactlyOnceWith('Ubuntu') - expect(h.deferred).toHaveLength(1) - // The user started it some other way: the distro restarted, so relaunch into it. - h.state.running = { status: 'confirmed', distros: ['Ubuntu'] } - h.state.identity = { distroInstance: 'boot:2', orcad: null } - h.deferred[0]() - await h.advance(5_000) - expect(h.ensure).toHaveBeenCalledTimes(2) - expect(h.statuses.at(-1)).toEqual({ state: 'ready', census: CENSUS }) - }) - - it('relaunches a crashed orcad and runs the census before reporting ready', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.state.identity = { distroInstance: 'boot:1', orcad: null } - h.lastWatch().exit(0) - // The distro stays listed: the list is watched through the stopping window before any exec. - await h.advance(5_000 + WSL_ORCAD_STOPPING_WINDOW_MS) - const states = h.statuses.map((status) => - status.state === 'reconnecting' ? `${status.state}:${status.reason}` : status.state - ) - expect(states).toEqual([ - 'reconnecting:orcad-exited', - 'reconnecting:orcad-exited', - 'reconnecting:census', - 'ready' - ]) - expect(h.statuses[0]).toMatchObject({ terminals: 'unverifiable' }) - expect(h.collectCensus).toHaveBeenCalledTimes(1) - }) - - it('keeps watching the incumbent when an update connect fails', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.state.ensureFails = 1 - await expect(h.supervisor.connect('Ubuntu', { intent: 'force' })).rejects.toThrow( - 'relaunch failed' - ) - expect(h.ensure).toHaveBeenLastCalledWith('Ubuntu', { intent: 'force' }) - expect(h.watches).toHaveLength(2) - expect(h.lastWatch().closed).toBe(false) - }) - - it('recovery reconnects only into a distro it confirms running right before spawning (E9)', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.state.identity = { distroInstance: 'boot:1', orcad: null } - h.lastWatch().exit(1) - await h.advance(60_000) - const recoveryCalls = h.ensure.mock.calls.slice(1) - expect(recoveryCalls.length).toBeGreaterThan(0) - for (const [, opts] of recoveryCalls) { - expect(opts).toMatchObject({ requireRunning: h.requireRunning }) - } - // Its backoff gate reads too: every read names the distro, so the wiring can settle it. - for (const [target] of h.readRunning.mock.calls) { - expect(target).toMatchObject({ distro: 'Ubuntu' }) - } - }) - - it('reports ready itself when a user connect supersedes a recovery', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.state.identity = { distroInstance: 'boot:1', orcad: null } - h.lastWatch().exit(0) - // A clean exit is settled (and the list watched) before the verdict, as a failed one is. - await h.advance(EXIT_SETTLE_MS + WSL_ORCAD_STOPPING_WINDOW_MS) - expect(h.statuses.at(-1)).toMatchObject({ state: 'reconnecting' }) - await h.supervisor.connect('Ubuntu') - expect(h.statuses.at(-1)).toEqual({ state: 'ready', census: null }) - }) - it('never reports ready or holds the distro on a wake after the listener was retired', async () => { const h = harness({ visible: false }) // No pid file at arm: the port is the only liveness evidence. @@ -399,201 +227,6 @@ describe('WslOrcadLivenessSupervisor', () => { expect(h.ensure).toHaveBeenCalledTimes(1) }) - it('leaves an orcad nobody uses stopped instead of undoing its idle exit', async () => { - const h = harness({ visible: false }) - await h.supervisor.connect('Ubuntu') - h.state.identity = { distroInstance: 'boot:1', orcad: null } - h.lastWatch().exit(0) - await h.advance(60_000) - expect(h.statuses).toEqual([{ state: 'idle', terminals: 'unverifiable' }]) - expect(h.ensure).toHaveBeenCalledTimes(1) - expect(h.retireListener).toHaveBeenCalledExactlyOnceWith('Ubuntu') - }) - - it('reattaches the watch when orcad is still the same process', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.lastWatch().exit(0) - await h.advance(EXIT_SETTLE_MS + WSL_ORCAD_STOPPING_WINDOW_MS) - expect(h.statuses).toEqual([]) - expect(h.watches).toHaveLength(2) - expect(h.ensure).toHaveBeenCalledTimes(1) - }) - - it('reports unverifiable, never exited, when the running list cannot be read, and keeps looking', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.state.running = { status: 'unavailable' } - h.lastWatch().exit(1) - await h.advance(0) - expect(h.statuses).toEqual([ - { state: 'unverifiable', reason: 'running-list-unavailable', terminals: 'unverifiable' } - ]) - await h.advance(120_000) - expect(h.statuses.every((status) => status.state === 'unverifiable')).toBe(true) - expect(h.ensure).toHaveBeenCalledTimes(1) - const reads = h.readRunning.mock.calls.length - expect(reads).toBeGreaterThan(3) - h.state.running = { status: 'confirmed', distros: ['Ubuntu'] } - await h.advance(30_000) - expect(h.statuses.at(-1)).toEqual({ state: 'ready', census: null }) - }) - - it('re-reads after the settle only from a probe started once the exit has settled', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.jumpClock(1_000) - const exitedAt = h.clock() - h.lastWatch().exit(1) - await h.advance(EXIT_SETTLE_MS) - // A list probe begun inside the window may still show the stopping distro; it must not answer. - expect(h.readRunning).toHaveBeenNthCalledWith(2, { distro: 'Ubuntu', exitedAt }) - }) - - it('waits for a still-listed distro to settle after a failed exit before probing inside it', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.lastWatch().exit(1) - await h.settle() - expect(h.readRunning).toHaveBeenCalledTimes(1) - h.state.running = { status: 'confirmed', distros: [] } - await h.advance(500) - expect(h.readIdentity).toHaveBeenCalledTimes(1) - expect(h.statuses[0]).toMatchObject({ state: 'distro-stopped' }) - }) - - it('gives up after the bounded ladder and says so', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.state.identity = { distroInstance: 'boot:1', orcad: null } - h.state.ensureFails = 100 - h.lastWatch().exit(0) - await h.advance(10 * 60_000) - expect(h.ensure).toHaveBeenCalledTimes(1 + WSL_ORCAD_RECONNECT_DELAYS_MS.length) - expect(h.statuses.at(-1)).toMatchObject({ state: 'failed', terminals: 'unverifiable' }) - }) - - it('re-verifies on power resume instead of trusting its timers, but not on subscribe', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - expect(h.readRunning).not.toHaveBeenCalled() - h.power()?.onSuspend() - await h.advance(WSL_ORCAD_HEARTBEAT_MS * 3) - expect(h.readRunning).not.toHaveBeenCalled() - h.state.identity = { distroInstance: 'boot:9', orcad: null } - h.power()?.onResume() - await h.advance(0) - expect(h.readIdentity).toHaveBeenCalledTimes(2) - expect(h.statuses[0]).toMatchObject({ state: 'reconnecting', reason: 'distro-restarted' }) - }) - - it('heartbeats with the running list only, and re-ensures the holder while running', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - await h.advance(WSL_ORCAD_HEARTBEAT_MS) - expect(h.readRunning).toHaveBeenCalledTimes(1) - expect(h.readIdentity).toHaveBeenCalledTimes(1) - expect(h.ensureHolder).toHaveBeenCalledWith('Ubuntu') - }) - - it('verifies fully on a heartbeat while its watch holds no open socket to prove orcad', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - // The desktop's sockets are all closed: the watch proves nothing, so ask the guest. - h.state.watchProves = false - await h.advance(WSL_ORCAD_HEARTBEAT_MS) - expect(h.readIdentity).toHaveBeenCalledTimes(2) - // Same orcad: still ready, no verdict change. - expect(h.statuses.filter((status) => status.state !== 'ready')).toEqual([]) - }) - - it('bounds detection to the idle verify period while no desktop socket is open', async () => { - const h = harness() - h.state.watchProves = false - await h.supervisor.connect('Ubuntu') - const reads = h.readIdentity.mock.calls.length - await h.advance(WSL_ORCAD_IDLE_VERIFY_MS - 1) - expect(h.readIdentity).toHaveBeenCalledTimes(reads) - await h.advance(1) - expect(h.readIdentity).toHaveBeenCalledTimes(reads + 1) - await h.advance(WSL_ORCAD_IDLE_VERIFY_MS) - expect(h.readIdentity).toHaveBeenCalledTimes(reads + 2) - // With a socket open again, ticks go back to the heartbeat's cheap running-list read. - h.state.watchProves = true - await h.advance(WSL_ORCAD_IDLE_VERIFY_MS + WSL_ORCAD_HEARTBEAT_MS) - expect(h.readIdentity).toHaveBeenCalledTimes(reads + 2) - }) - - it('brings the next full check forward when the last desktop socket closes normally', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - const reads = h.readIdentity.mock.calls.length - await h.advance(WSL_ORCAD_HEARTBEAT_MS / 2) - // The desktop closed its last socket: nothing proves orcad until the next check. - h.state.watchProves = false - h.lastWatch().idle() - await h.advance(WSL_ORCAD_IDLE_VERIFY_MS - 1) - expect(h.readIdentity).toHaveBeenCalledTimes(reads) - await h.advance(1) - expect(h.readIdentity).toHaveBeenCalledTimes(reads + 1) - }) - - it('treats a socket orcad closed for another reason as a verify, not a verdict', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - // A watch riding the desktop's sockets reports no exit code. - h.lastWatch().exit(null) - await h.advance(5_000 + WSL_ORCAD_STOPPING_WINDOW_MS) - expect(h.readIdentity).toHaveBeenCalledTimes(2) - expect(h.statuses.filter((status) => status.state !== 'ready')).toEqual([]) - expect(h.ensure).toHaveBeenCalledTimes(1) - expect(h.watches).toHaveLength(2) - }) - - it('treats a heartbeat far past due as a pause and verifies fully', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - h.jumpClock(WSL_ORCAD_HEARTBEAT_MS * 5) - await h.advance(0) - expect(h.readIdentity).toHaveBeenCalledTimes(2) - }) - - it('ignores wall-clock jumps entirely', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - vi.useFakeTimers({ toFake: ['Date'] }) - try { - vi.setSystemTime(Date.now() + 7 * 24 * 3_600_000) - await h.advance(1_000) - vi.setSystemTime(Date.now() - 30 * 24 * 3_600_000) - await h.advance(1_000) - } finally { - vi.useRealTimers() - } - expect(h.readRunning).not.toHaveBeenCalled() - expect(h.statuses).toEqual([]) - }) - - it('stops supervising on stop, closing the watch and ignoring late exits', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - const watch = h.lastWatch() - await h.supervisor.stop('Ubuntu') - expect(watch.closed).toBe(true) - watch.exit(1) - await h.advance(60_000) - expect(h.readRunning).not.toHaveBeenCalled() - }) - - it('treats a holder exit like a bridge exit', async () => { - const h = harness({ visible: false }) - await h.supervisor.connect('Ubuntu') - h.state.running = { status: 'confirmed', distros: [] } - h.supervisor.noteHolderExit('UBUNTU', { code: 1 }) - await h.advance(0) - expect(h.statuses[0]).toMatchObject({ state: 'distro-stopped', terminals: 'exited' }) - }) - it('lets a user connect supersede the deferred re-check of a stopped distro', async () => { const h = harness({ visible: false }) await h.supervisor.connect('Ubuntu') @@ -608,77 +241,4 @@ describe('WslOrcadLivenessSupervisor', () => { expect(h.ensure).toHaveBeenCalledTimes(2) expect(h.statuses.map((status) => status.state)).toEqual(['distro-stopped', 'ready']) }) - - it('reports a stop once when both the holder and the watch exit', async () => { - const h = harness({ visible: false }) - await h.supervisor.connect('Ubuntu') - h.state.running = { status: 'confirmed', distros: [] } - h.supervisor.noteHolderExit('Ubuntu', { code: 1 }) - h.lastWatch().exit(1) - await h.advance(1_000) - expect(h.statuses.map((status) => status.state)).toEqual(['distro-stopped']) - }) - - describe('after an exit, while the distro may still be stopping (E9)', () => { - const STOPPED: WslRunningDistrosRead = { status: 'confirmed', distros: [] } - - it('publishes distro-stopped within a poll of the list dropping it, never exec-ing into it', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - const identityReads = h.readIdentity.mock.calls.length - h.lastWatch().exit(null) - await h.advance(EXIT_SETTLE_MS + 2_000) - // Still listed mid-window: only the list was read, nothing ran inside the distro. - expect(h.readIdentity).toHaveBeenCalledTimes(identityReads) - expect(h.statuses).toEqual([]) - - h.state.running = STOPPED - await h.advance(WSL_ORCAD_STOPPING_POLL_MS) - expect(h.statuses).toEqual([ - { state: 'distro-stopped', terminals: 'exited', recovering: false } - ]) - expect(h.readIdentity).toHaveBeenCalledTimes(identityReads) - }) - - it('falls back to the identity check once the window ends with the distro still listed', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - const identityReads = h.readIdentity.mock.calls.length - h.supervisor.noteHolderExit('Ubuntu', { code: 1 }) - await h.advance(EXIT_SETTLE_MS + WSL_ORCAD_STOPPING_WINDOW_MS - WSL_ORCAD_STOPPING_POLL_MS) - expect(h.readIdentity).toHaveBeenCalledTimes(identityReads) - await h.advance(WSL_ORCAD_STOPPING_POLL_MS) - expect(h.readIdentity).toHaveBeenCalledTimes(identityReads + 1) - expect(h.statuses).toEqual([]) - }) - - it('adds no running-list reads to heartbeats while the distro runs', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - await h.advance(WSL_ORCAD_HEARTBEAT_MS * 3) - expect(h.readRunning).toHaveBeenCalledTimes(3) - }) - - it('ends a recovery backoff when the distro then stops, rather than wait it out', async () => { - const h = harness() - await h.supervisor.connect('Ubuntu') - // orcad crashed and keeps failing to relaunch: recovery sits in a long backoff. - h.state.identity = { distroInstance: 'boot:1', orcad: null } - h.state.ensureFails = 100 - h.lastWatch().exit(0) - await h.advance(EXIT_SETTLE_MS + WSL_ORCAD_STOPPING_WINDOW_MS + 8_000) - const waiting = h.statuses.at(-1) - expect(waiting).toMatchObject({ state: 'reconnecting' }) - expect(waiting && 'retryInMs' in waiting ? waiting.retryInMs : 0).toBeGreaterThan(2_000) - - h.state.running = STOPPED - h.supervisor.noteHolderExit('Ubuntu', { code: 1 }) - await h.advance(EXIT_SETTLE_MS + 100) - expect(h.statuses.at(-1)).toEqual({ - state: 'distro-stopped', - terminals: 'exited', - recovering: false - }) - }) - }) }) diff --git a/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts b/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts index ff310707c17..1b6c3e8640c 100644 --- a/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts @@ -83,7 +83,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', () => ({ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: async () => ({ outcome: 'none' }) })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: host.deploy })) diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 06f6052d657..2250b5e69d7 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -6,73 +6,85 @@ import type { GrokAccountsApi, MinimaxCredentialsApi, ZcodePlanCredentialsApi -} from './api/agent-account-api' -import type { HooksApi } from './api/agent-hook-api' -import type { SkillsApi } from './api/agent-skill-api' -import type { AgentAwakeApi, AgentStatusApi } from './api/agent-status-api' +} from './api/agent-accounts/agent-account-api' +import type { HooksApi } from './api/agent-hooks/agent-hook-api' +import type { SkillsApi } from './api/skills/agent-skill-api' +import type { AgentAwakeApi, AgentStatusApi } from './api/agent-status/agent-status-api' import type { ClaudeUsageApi, CodexUsageApi, MuseUsageApi, OpenCodeUsageApi, RateLimitsApi -} from './api/agent-usage-api' -import type { AiVaultApi } from './api/ai-vault-api' +} from './api/agent-usage/agent-usage-api' +import type { AiVaultApi } from './api/ai-vault/ai-vault-api' import type { AppApi, E2EApi, PlatformApi } from './api/app-api' -import type { AutomationsApi } from './api/automation-api' +import type { AutomationsApi } from './api/automations/automation-api' import type { BrowserApi } from './api/browser/browser-api' -import type { CliApi } from './api/cli-install-api' -import type { CrashReportsApi, FeedbackApi } from './api/crash-report-api' -import type { DashboardApi, TerminalPreviewApi } from './api/dashboard-api' -import type { DocPreviewApi } from './api/doc-preview-api' -import type { EmulatorApi } from './api/emulator-api' -import type { EphemeralVmApi } from './api/ephemeral-vm-api' -import type { ExportApi, FilesystemApi } from './api/filesystem-api' -import type { GitInspectionApi } from './api/git-inspection-api' -import type { GitOperationApi } from './api/git-operation-api' -import type { GithubAccountApi } from './api/github-account-api' -import type { GithubPullRequestApi } from './api/github-pull-request-api' -import type { GithubWorkItemApi } from './api/github-work-item-api' -import type { GitLabApi } from './api/gitlab-api' -import type { BitbucketApi, HostedReviewApi } from './api/hosted-review-api' -import type { JiraApi } from './api/jira-api' -import type { LinearApi } from './api/linear-api' -import type { MobileApi } from './api/mobile-api' -import type { NativeChatApi } from './api/native-chat-api' -import type { OnboardingApi, StarNagApi } from './api/onboarding-api' -import type { OrcaProfileApi } from './api/orca-profile-api' +import type { CliApi } from './api/cli-install/cli-install-api' +import type { CrashReportsApi, FeedbackApi } from './api/diagnostics/crash-report-api' +import type { DashboardApi, TerminalPreviewApi } from './api/window-ui/dashboard-api' +import type { DocPreviewApi } from './api/document-preview/doc-preview-api' +import type { EmulatorApi } from './api/emulator/emulator-api' +import type { EphemeralVmApi } from './api/cloud-workspaces/ephemeral-vm-api' +import type { ExportApi, FilesystemApi } from './api/filesystem/filesystem-api' +import type { GitInspectionApi } from './api/source-control/git-inspection-api' +import type { GitOperationApi } from './api/source-control/git-operation-api' +import type { GithubAccountApi } from './api/github/github-account-api' +import type { GithubPullRequestApi } from './api/github/github-pull-request-api' +import type { GithubWorkItemApi } from './api/github/github-work-item-api' +import type { GitLabApi } from './api/gitlab/gitlab-api' +import type { BitbucketApi, HostedReviewApi } from './api/hosted-review/hosted-review-api' +import type { JiraApi } from './api/work-items/jira-api' +import type { LinearApi } from './api/work-items/linear-api' +import type { MobileApi } from './api/mobile/mobile-api' +import type { NativeChatApi } from './api/native-chat/native-chat-api' +import type { OnboardingApi, StarNagApi } from './api/onboarding/onboarding-api' +import type { OrcaProfileApi } from './api/profiles/orca-profile-api' import type { ComputerUsePermissionsApi, DeveloperPermissionsApi, MacosTccPromptsApi, NotificationsApi -} from './api/os-permission-api' -import type { PetApi } from './api/pet-api' -import type { AppIconApi } from './api/app-icon-api' -import type { BrowserPasswordsApi } from './api/browser-passwords-api' -import type { PluginsApi } from './api/plugin-host-api' -import type { PreflightApi } from './api/preflight-api' -import type { PtyApi } from './api/pty-api' -import type { ProjectGroupsApi, ProjectsApi, RepositoryApi } from './api/repository-api' -import type { RuntimeApi } from './api/runtime-api' -import type { WslMoveApi } from './api/wsl-move-bridge' -import type { WslDriveProjectApi } from './api/wsl-drive-project-bridge' -import type { WslDriveUncConversionApi } from './api/wsl-drive-unc-conversion-bridge' -import type { KeybindingsApi, SettingsApi } from './api/settings-api' -import type { ShellApi } from './api/shell-api' -import type { SpeechApi } from './api/speech-api' -import type { SshApi } from './api/ssh-api' -import type { PlainSshTerminalApi } from './api/plain-ssh-terminal-bridge' -import type { LegacyRelayBridgeApi } from './api/legacy-relay-bridge-api' -import type { DiagnosticsApi, MemoryApi, StatsApi, TelemetryApi } from './api/telemetry-api' -import type { UiCommandEventApi } from './api/ui-command-event-api' -import type { UiWindowApi } from './api/ui-window-api' -import type { UpdaterApi } from './api/updater-api' -import type { WorkspaceCleanupApi, WorkspaceSpaceApi } from './api/workspace-cleanup-api' -import type { LocalhostWorktreeLabelsApi, WorkspacePortsApi } from './api/workspace-port-api' -import type { LinkPreviewApi } from './api/link-preview-api' -import type { WorkspaceSessionApi } from './api/workspace-session-api' -import type { FolderWorkspacesApi, SparsePresetsApi, WorktreeApi } from './api/worktree-api' +} from './api/desktop-permissions/os-permission-api' +import type { PetApi } from './api/pets/pet-api' +import type { AppIconApi } from './api/window-ui/app-icon-api' +import type { BrowserPasswordsApi } from './api/browser/browser-passwords-api' +import type { PluginsApi } from './api/plugins/plugin-host-api' +import type { PreflightApi } from './api/preflight/preflight-api' +import type { PtyApi } from './api/terminal/pty-api' +import type { ProjectGroupsApi, ProjectsApi, RepositoryApi } from './api/projects/repository-api' +import type { RuntimeApi } from './api/runtime/runtime-api' +import type { WslMoveApi } from './api/wsl/wsl-move-bridge' +import type { WslDriveProjectApi } from './api/wsl/wsl-drive-project-bridge' +import type { WslDriveUncConversionApi } from './api/wsl/wsl-drive-unc-conversion-bridge' +import type { KeybindingsApi, SettingsApi } from './api/preferences/settings-api' +import type { ShellApi } from './api/terminal/shell-api' +import type { SpeechApi } from './api/speech/speech-api' +import type { SshApi } from './api/ssh/ssh-api' +import type { PlainSshTerminalApi } from './api/terminal/plain-ssh-terminal-bridge' +import type { LegacyRelayBridgeApi } from './api/mobile/legacy-relay-bridge-api' +import type { + DiagnosticsApi, + MemoryApi, + StatsApi, + TelemetryApi +} from './api/diagnostics/telemetry-api' +import type { UiCommandEventApi } from './api/window-ui/ui-command-event-api' +import type { UiWindowApi } from './api/window-ui/ui-window-api' +import type { UpdaterApi } from './api/updater/updater-api' +import type { WorkspaceCleanupApi, WorkspaceSpaceApi } from './api/workspaces/workspace-cleanup-api' +import type { + LocalhostWorktreeLabelsApi, + WorkspacePortsApi +} from './api/workspaces/workspace-port-api' +import type { LinkPreviewApi } from './api/link-preview/link-preview-api' +import type { WorkspaceSessionApi } from './api/workspaces/workspace-session-api' +import type { + FolderWorkspacesApi, + SparsePresetsApi, + WorktreeApi +} from './api/workspaces/worktree-api' // Flattens contracts that share one PreloadApi key: an intersection is not type-identical to the flat shape. type Merged = { [K in keyof T]: T[K] } @@ -179,68 +191,6 @@ export type PreloadApi = { speech: SpeechApi } -export type { - ClaudeUsageApi, - CodexUsageApi, - MuseUsageApi, - OpenCodeUsageApi -} from './api/agent-usage-api' -export type { AiVaultApi } from './api/ai-vault-api' -export type { AutomationsApi, ExternalAutomationManagerResult } from './api/automation-api' -export type { AppApi } from './api/app-api' -export type { - BrowserApi, - DetectedBrowserInfo, - DetectedBrowserProfileInfo -} from './api/browser/browser-api' -export type { EmulatorApi } from './api/emulator-api' -export type { ExportApi } from './api/filesystem-api' -export type { - NativeChatApi, - NativeChatAppendedMessages, - NativeChatAppendedPayload, - NativeChatReadSessionResult, - NativeChatSubscribeArgs, - NativeChatSubscriptionFrame -} from './api/native-chat-api' -export type { - PluginAutoUpdateEvent, - PluginHostCustomEditor, - PluginHostNewFile, - PluginHostInstallResult, - PluginHostInstallSource, - PluginHostListEntry, - PluginHostLogLine, - PluginHostPanel, - PluginHostStatus, - PluginMarketplaceHostInstallPreview, - PluginMarketplaceHostListing, - PluginMarketplaceHostSourceState -} from './api/plugin-host-api' -export type { - PreflightApi, - PreflightRuntimeContext, - PreflightStatus, - RefreshAgentsResult -} from './api/preflight-api' -export type { - PtyManagementApi, - PtyManagementDaemonCwdClass, - PtyManagementFolderAccessMismatch, - PtyManagementMacTccAttributionHealth, - PtyManagementSession, - PtyManagementSeveredDaemon, - PtyManagementSeveredDaemonRestartResult -} from './api/pty-management-api' - -export type { - DiagnosticsBundlePayload, - DiagnosticsStatusPayload, - DiagnosticsUploadPayload, - MemoryApi, - StatsApi -} from './api/telemetry-api' - declare global { // oxlint-disable-next-line typescript-eslint/consistent-type-definitions -- declaration merging requires interface interface Window { diff --git a/src/preload/api/agent-account-api.ts b/src/preload/api/agent-accounts/agent-account-api.ts similarity index 91% rename from src/preload/api/agent-account-api.ts rename to src/preload/api/agent-accounts/agent-account-api.ts index 6b97a23cf6f..a762bb57a48 100644 --- a/src/preload/api/agent-account-api.ts +++ b/src/preload/api/agent-accounts/agent-account-api.ts @@ -2,11 +2,11 @@ import type { ClaudeAccountSelectionChange, ClaudeRateLimitAccountsState, CodexRateLimitAccountsState -} from '../../shared/managed-account-types' -import type { CodexConfigSyncStatus } from '../../shared/codex-config-sync-types' -import type { CursorAccountStatus, GrokAccountStatus } from '../../shared/rate-limit-types' -import type { ZcodePlanCredentialsStatus } from '../../shared/zcode-plan-sites' -import type { MiniMaxCredentialsStatus } from '../../shared/minimax-credentials-status' +} from '../../../shared/managed-account-types' +import type { CodexConfigSyncStatus } from '../../../shared/codex-config-sync-types' +import type { CursorAccountStatus, GrokAccountStatus } from '../../../shared/rate-limit-types' +import type { ZcodePlanCredentialsStatus } from '../../../shared/zcode-plan-sites' +import type { MiniMaxCredentialsStatus } from '../../../shared/minimax-credentials-status' export type CodexAccountsApi = { list: () => Promise diff --git a/src/preload/api/claude-accounts-bridge.ts b/src/preload/api/agent-accounts/claude-accounts-bridge.ts similarity index 90% rename from src/preload/api/claude-accounts-bridge.ts rename to src/preload/api/agent-accounts/claude-accounts-bridge.ts index 95da48caf8f..7b5cf96979e 100644 --- a/src/preload/api/claude-accounts-bridge.ts +++ b/src/preload/api/agent-accounts/claude-accounts-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { ClaudeAccountSelectionChange } from '../../shared/managed-account-types' -import type { PreloadApi } from '../api-types' +import type { ClaudeAccountSelectionChange } from '../../../shared/managed-account-types' +import type { PreloadApi } from '../../api-types' export const claudeAccountsApi = { list: () => ipcRenderer.invoke('claudeAccounts:list'), diff --git a/src/preload/api/codex-accounts-bridge.ts b/src/preload/api/agent-accounts/codex-accounts-bridge.ts similarity index 92% rename from src/preload/api/codex-accounts-bridge.ts rename to src/preload/api/agent-accounts/codex-accounts-bridge.ts index e94b5f35b87..35397c26049 100644 --- a/src/preload/api/codex-accounts-bridge.ts +++ b/src/preload/api/agent-accounts/codex-accounts-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import { CODEX_PENDING_LOGIN_URL_CHANGED_CHANNEL } from '../../shared/codex-auth-errors' -import type { PreloadApi } from '../api-types' +import { CODEX_PENDING_LOGIN_URL_CHANGED_CHANNEL } from '../../../shared/codex-auth-errors' +import type { PreloadApi } from '../../api-types' export const codexAccountsApi = { list: () => ipcRenderer.invoke('codexAccounts:list'), diff --git a/src/preload/api/agent-accounts/codex-config-sync-bridge.ts b/src/preload/api/agent-accounts/codex-config-sync-bridge.ts new file mode 100644 index 00000000000..d7b62c4f3aa --- /dev/null +++ b/src/preload/api/agent-accounts/codex-config-sync-bridge.ts @@ -0,0 +1,7 @@ +import { ipcRenderer } from 'electron' +import type { CodexConfigSyncStatus } from '../../../shared/codex-config-sync-types' +import type { PreloadApi } from '../../api-types' + +export const codexConfigSyncApi = { + status: (): Promise => ipcRenderer.invoke('codexConfigSync:status') +} satisfies PreloadApi['codexConfigSync'] diff --git a/src/preload/api/agent-accounts/cursor-accounts-bridge.ts b/src/preload/api/agent-accounts/cursor-accounts-bridge.ts new file mode 100644 index 00000000000..82c27c85c58 --- /dev/null +++ b/src/preload/api/agent-accounts/cursor-accounts-bridge.ts @@ -0,0 +1,7 @@ +import { ipcRenderer } from 'electron' +import type { CursorAccountStatus } from '../../../shared/rate-limit-types' +import type { PreloadApi } from '../../api-types' + +export const cursorAccountsApi = { + getStatus: (): Promise => ipcRenderer.invoke('cursorAccounts:getStatus') +} satisfies PreloadApi['cursorAccounts'] diff --git a/src/preload/api/agent-accounts/grok-accounts-bridge.ts b/src/preload/api/agent-accounts/grok-accounts-bridge.ts new file mode 100644 index 00000000000..8884a5166ea --- /dev/null +++ b/src/preload/api/agent-accounts/grok-accounts-bridge.ts @@ -0,0 +1,7 @@ +import { ipcRenderer } from 'electron' +import type { GrokAccountStatus } from '../../../shared/rate-limit-types' +import type { PreloadApi } from '../../api-types' + +export const grokAccountsApi = { + getStatus: (): Promise => ipcRenderer.invoke('grokAccounts:getStatus') +} satisfies PreloadApi['grokAccounts'] diff --git a/src/preload/api/minimax-credentials-bridge.ts b/src/preload/api/agent-accounts/minimax-credentials-bridge.ts similarity index 83% rename from src/preload/api/minimax-credentials-bridge.ts rename to src/preload/api/agent-accounts/minimax-credentials-bridge.ts index 911ea0cf5d3..27013996fdf 100644 --- a/src/preload/api/minimax-credentials-bridge.ts +++ b/src/preload/api/agent-accounts/minimax-credentials-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import type { MiniMaxCredentialsStatus } from '../../shared/minimax-credentials-status' +import type { PreloadApi } from '../../api-types' +import type { MiniMaxCredentialsStatus } from '../../../shared/minimax-credentials-status' export const minimaxCredentialsApi = { getStatus: (): Promise => diff --git a/src/preload/api/opencode-go-credentials-bridge.ts b/src/preload/api/agent-accounts/opencode-go-credentials-bridge.ts similarity index 90% rename from src/preload/api/opencode-go-credentials-bridge.ts rename to src/preload/api/agent-accounts/opencode-go-credentials-bridge.ts index 35e1a668bc1..a84abf727f7 100644 --- a/src/preload/api/opencode-go-credentials-bridge.ts +++ b/src/preload/api/agent-accounts/opencode-go-credentials-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const opencodeGoCredentialsApi = { getStatus: (): Promise<{ apiKeyConfigured: boolean }> => diff --git a/src/preload/api/zcode-plan-credentials-bridge.ts b/src/preload/api/agent-accounts/zcode-plan-credentials-bridge.ts similarity index 78% rename from src/preload/api/zcode-plan-credentials-bridge.ts rename to src/preload/api/agent-accounts/zcode-plan-credentials-bridge.ts index cee36fa7b87..4080b757709 100644 --- a/src/preload/api/zcode-plan-credentials-bridge.ts +++ b/src/preload/api/agent-accounts/zcode-plan-credentials-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import type { ZcodePlanCredentialsStatus } from '../../shared/zcode-plan-sites' +import type { PreloadApi } from '../../api-types' +import type { ZcodePlanCredentialsStatus } from '../../../shared/zcode-plan-sites' export const zcodePlanCredentialsApi = { getStatus: (): Promise => diff --git a/src/preload/api/agent-hook-api.ts b/src/preload/api/agent-hooks/agent-hook-api.ts similarity index 83% rename from src/preload/api/agent-hook-api.ts rename to src/preload/api/agent-hooks/agent-hook-api.ts index 3eeeb865fc5..37579bff473 100644 --- a/src/preload/api/agent-hook-api.ts +++ b/src/preload/api/agent-hooks/agent-hook-api.ts @@ -1,6 +1,6 @@ -import type { OrcaHooks } from '../../shared/orca-yaml-hook-types' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { SetupScriptImportCandidate } from '../../shared/workspace-setup/setup-script-imports' +import type { OrcaHooks } from '../../../shared/orca-yaml-hook-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { SetupScriptImportCandidate } from '../../../shared/workspace-setup/setup-script-imports' export type HooksApi = { /** `background`: a render-driven probe, refused (status 'error') rather than booting a stopped WSL distro. */ diff --git a/src/preload/api/hooks-bridge.ts b/src/preload/api/agent-hooks/hooks-bridge.ts similarity index 89% rename from src/preload/api/hooks-bridge.ts rename to src/preload/api/agent-hooks/hooks-bridge.ts index 22e68bbd171..be35b2d12ad 100644 --- a/src/preload/api/hooks-bridge.ts +++ b/src/preload/api/agent-hooks/hooks-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { PreloadApi } from '../api-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { PreloadApi } from '../../api-types' export const hooksApi = { check: (args: { repoId: string; hostId?: ExecutionHostId; background?: boolean }) => diff --git a/src/preload/api/agent-awake-bridge.ts b/src/preload/api/agent-status/agent-awake-bridge.ts similarity index 80% rename from src/preload/api/agent-awake-bridge.ts rename to src/preload/api/agent-status/agent-awake-bridge.ts index eff4263398e..c916a71d1e6 100644 --- a/src/preload/api/agent-awake-bridge.ts +++ b/src/preload/api/agent-status/agent-awake-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { ComputerAwakeStatus } from '../../shared/computer-awake-mode' -import type { PreloadApi } from '../api-types' +import type { ComputerAwakeStatus } from '../../../shared/computer-awake-mode' +import type { PreloadApi } from '../../api-types' export const agentAwakeApi = { getStatus: (): Promise => ipcRenderer.invoke('agentAwake:getStatus'), diff --git a/src/preload/api/agent-status-api.ts b/src/preload/api/agent-status/agent-status-api.ts similarity index 87% rename from src/preload/api/agent-status-api.ts rename to src/preload/api/agent-status/agent-status-api.ts index 5df1f88ef65..d6ac9bd64ea 100644 --- a/src/preload/api/agent-status-api.ts +++ b/src/preload/api/agent-status/agent-status-api.ts @@ -3,11 +3,11 @@ import type { AgentStatusClearIpcPayload, AgentStatusIpcPayload, MigrationUnsupportedPtyEntry -} from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' -import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' -import type { ComputerAwakeStatus } from '../../shared/computer-awake-mode' -import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' +} from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { AgentInterruptInferenceRequest } from '../../../shared/agent-status/lifecycle/agent-interrupt-intent' +import type { AgentQuestionAnsweredInferenceRequest } from '../../../shared/agent-status/lifecycle/agent-question-answered-intent' +import type { ComputerAwakeStatus } from '../../../shared/computer-awake-mode' +import type { AgentListPublication } from '../../../shared/agent-status/presentation/agent-list-status' export type AgentStatusApi = { /** Listen for agent status updates forwarded from native hook receivers. */ diff --git a/src/preload/api/agent-status-bridge.ts b/src/preload/api/agent-status/agent-status-bridge.ts similarity index 91% rename from src/preload/api/agent-status-bridge.ts rename to src/preload/api/agent-status/agent-status-bridge.ts index 1a57c712b49..dc1fa46649f 100644 --- a/src/preload/api/agent-status-bridge.ts +++ b/src/preload/api/agent-status/agent-status-bridge.ts @@ -4,11 +4,11 @@ import type { AgentStatusClearIpcPayload, AgentStatusIpcPayload, MigrationUnsupportedPtyEntry -} from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' -import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' -import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' -import type { PreloadApi } from '../api-types' +} from '../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { AgentInterruptInferenceRequest } from '../../../shared/agent-status/lifecycle/agent-interrupt-intent' +import type { AgentQuestionAnsweredInferenceRequest } from '../../../shared/agent-status/lifecycle/agent-question-answered-intent' +import type { AgentListPublication } from '../../../shared/agent-status/presentation/agent-list-status' +import type { PreloadApi } from '../../api-types' export const agentStatusApi = { onSet: (callback: (data: AgentStatusIpcPayload) => void): (() => void) => { diff --git a/src/preload/api/agent-usage-api.ts b/src/preload/api/agent-usage/agent-usage-api.ts similarity index 88% rename from src/preload/api/agent-usage-api.ts rename to src/preload/api/agent-usage/agent-usage-api.ts index 8696c17885e..a1f74dfc7f8 100644 --- a/src/preload/api/agent-usage-api.ts +++ b/src/preload/api/agent-usage/agent-usage-api.ts @@ -1,19 +1,22 @@ import type { BackendConnectionListener, BackendConnectionPurpose -} from '../../shared/backend-service-contract' -import type { ClaudeUsageBreakdownKind, ClaudeUsageSnapshot } from '../../shared/claude-usage-types' -import type { CodexUsageBreakdownKind, CodexUsageSnapshot } from '../../shared/codex-usage-types' +} from '../../../shared/backend-service-contract' +import type { + ClaudeUsageBreakdownKind, + ClaudeUsageSnapshot +} from '../../../shared/claude-usage-types' +import type { CodexUsageBreakdownKind, CodexUsageSnapshot } from '../../../shared/codex-usage-types' import type { OpenCodeUsageBreakdownKind, OpenCodeUsageSnapshot -} from '../../shared/opencode-usage-types' -import type { MuseUsageBreakdownKind, MuseUsageSnapshot } from '../../shared/muse-usage-types' +} from '../../../shared/opencode-usage-types' +import type { MuseUsageBreakdownKind, MuseUsageSnapshot } from '../../../shared/muse-usage-types' import type { CodexRateLimitResetResult, RateLimitRuntimeTarget, RateLimitState -} from '../../shared/rate-limit-types' +} from '../../../shared/rate-limit-types' export type UsageProviderSnapshot = { scanState: unknown diff --git a/src/preload/api/agent-usage/claude-usage-bridge.ts b/src/preload/api/agent-usage/claude-usage-bridge.ts new file mode 100644 index 00000000000..9b3970e5f12 --- /dev/null +++ b/src/preload/api/agent-usage/claude-usage-bridge.ts @@ -0,0 +1,8 @@ +import { backendUsageTransport } from '../../usage/backend-port-client' +import { createUsageProviderApi } from '../../usage/usage-provider-api' +import type { PreloadApi } from '../../api-types' + +export const claudeUsageApi = createUsageProviderApi( + backendUsageTransport, + 'claudeUsage' +) satisfies PreloadApi['claudeUsage'] diff --git a/src/preload/api/agent-usage/codex-usage-bridge.ts b/src/preload/api/agent-usage/codex-usage-bridge.ts new file mode 100644 index 00000000000..a3ee6b5f3c8 --- /dev/null +++ b/src/preload/api/agent-usage/codex-usage-bridge.ts @@ -0,0 +1,8 @@ +import { backendUsageTransport } from '../../usage/backend-port-client' +import { createUsageProviderApi } from '../../usage/usage-provider-api' +import type { PreloadApi } from '../../api-types' + +export const codexUsageApi = createUsageProviderApi( + backendUsageTransport, + 'codexUsage' +) satisfies PreloadApi['codexUsage'] diff --git a/src/preload/api/agent-usage/muse-usage-bridge.ts b/src/preload/api/agent-usage/muse-usage-bridge.ts new file mode 100644 index 00000000000..2c6cd4189e4 --- /dev/null +++ b/src/preload/api/agent-usage/muse-usage-bridge.ts @@ -0,0 +1,8 @@ +import { backendUsageTransport } from '../../usage/backend-port-client' +import { createUsageProviderApi } from '../../usage/usage-provider-api' +import type { PreloadApi } from '../../api-types' + +export const museUsageApi = createUsageProviderApi( + backendUsageTransport, + 'museUsage' +) satisfies PreloadApi['museUsage'] diff --git a/src/preload/api/agent-usage/open-code-usage-bridge.ts b/src/preload/api/agent-usage/open-code-usage-bridge.ts new file mode 100644 index 00000000000..3d00be3eb0d --- /dev/null +++ b/src/preload/api/agent-usage/open-code-usage-bridge.ts @@ -0,0 +1,8 @@ +import { backendUsageTransport } from '../../usage/backend-port-client' +import { createUsageProviderApi } from '../../usage/usage-provider-api' +import type { PreloadApi } from '../../api-types' + +export const openCodeUsageApi = createUsageProviderApi( + backendUsageTransport, + 'openCodeUsage' +) satisfies PreloadApi['openCodeUsage'] diff --git a/src/preload/api/rate-limits-bridge.ts b/src/preload/api/agent-usage/rate-limits-bridge.ts similarity index 93% rename from src/preload/api/rate-limits-bridge.ts rename to src/preload/api/agent-usage/rate-limits-bridge.ts index ccb4582a43d..eb8a2229b03 100644 --- a/src/preload/api/rate-limits-bridge.ts +++ b/src/preload/api/agent-usage/rate-limits-bridge.ts @@ -3,8 +3,8 @@ import type { CodexRateLimitResetResult, RateLimitRuntimeTarget, RateLimitState -} from '../../shared/rate-limit-types' -import type { PreloadApi } from '../api-types' +} from '../../../shared/rate-limit-types' +import type { PreloadApi } from '../../api-types' export const rateLimitsApi = { get: (): Promise => ipcRenderer.invoke('rateLimits:get'), diff --git a/src/preload/api/ai-vault-api.ts b/src/preload/api/ai-vault/ai-vault-api.ts similarity index 84% rename from src/preload/api/ai-vault-api.ts rename to src/preload/api/ai-vault/ai-vault-api.ts index 76716433c64..7b85386576c 100644 --- a/src/preload/api/ai-vault-api.ts +++ b/src/preload/api/ai-vault/ai-vault-api.ts @@ -2,15 +2,15 @@ import type { AiVaultSearchRequest, AiVaultSearchResponse, AiVaultSearchStatus -} from '../../shared/ai-vault/search/ai-vault-search-types' +} from '../../../shared/ai-vault/search/ai-vault-search-types' import type { AiVaultDeleteSessionArgs, AiVaultDeleteSessionResult -} from '../../shared/ai-vault/contracts/ai-vault-session-deletion' +} from '../../../shared/ai-vault/contracts/ai-vault-session-deletion' import type { AiVaultSessionHandoffArgs, AiVaultSessionHandoffResult -} from '../../shared/ai-vault/contracts/ai-vault-session-handoff' +} from '../../../shared/ai-vault/contracts/ai-vault-session-handoff' import type { AiVaultFirstUserPromptArgs, AiVaultFirstUserPromptResult, @@ -18,20 +18,20 @@ import type { AiVaultListResult, AiVaultSubagentListArgs, AiVaultSubagentListResult -} from '../../shared/ai-vault/contracts/ai-vault-types' +} from '../../../shared/ai-vault/contracts/ai-vault-types' import type { AiVaultSessionTitlesArgs, AiVaultSessionTitlesResult -} from '../../shared/ai-vault/contracts/ai-vault-session-title' +} from '../../../shared/ai-vault/contracts/ai-vault-session-title' import type { AiVaultPrepareSessionResumeRequest, AiVaultPrepareSessionResumeResult -} from '../../shared/ai-vault/resume/ai-vault-resume-preparation' -import type { ExecutionHostId, ExecutionHostScope } from '../../shared/execution-host' +} from '../../../shared/ai-vault/resume/ai-vault-resume-preparation' +import type { ExecutionHostId, ExecutionHostScope } from '../../../shared/execution-host' import type { AiVaultScanProgress, AiVaultScanProgressUpdate -} from '../../shared/ai-vault/scanning/ai-vault-scan-progress' +} from '../../../shared/ai-vault/scanning/ai-vault-scan-progress' export type AiVaultApi = { /** Omitted host means this host; `all` is merged by this desktop across every enumerated host. */ diff --git a/src/preload/api/ai-vault-bridge.ts b/src/preload/api/ai-vault/ai-vault-bridge.ts similarity index 81% rename from src/preload/api/ai-vault-bridge.ts rename to src/preload/api/ai-vault/ai-vault-bridge.ts index b772715009c..9a38403e9ba 100644 --- a/src/preload/api/ai-vault-bridge.ts +++ b/src/preload/api/ai-vault/ai-vault-bridge.ts @@ -1,28 +1,28 @@ -import { createSessionSearchClient } from '../../shared/ai-vault/search/ai-vault-search-client' +import { createSessionSearchClient } from '../../../shared/ai-vault/search/ai-vault-search-client' import type { AiVaultSearchRequest, AiVaultSearchStatus -} from '../../shared/ai-vault/search/ai-vault-search-types' -import type { ExecutionHostId, ExecutionHostScope } from '../../shared/execution-host' +} from '../../../shared/ai-vault/search/ai-vault-search-types' +import type { ExecutionHostId, ExecutionHostScope } from '../../../shared/execution-host' import { ipcRenderer } from 'electron' import type { AiVaultDeleteSessionArgs, AiVaultDeleteSessionResult -} from '../../shared/ai-vault/contracts/ai-vault-session-deletion' +} from '../../../shared/ai-vault/contracts/ai-vault-session-deletion' import type { AiVaultFirstUserPromptArgs, AiVaultListArgs, AiVaultSubagentListArgs -} from '../../shared/ai-vault/contracts/ai-vault-types' -import type { AiVaultSessionTitlesArgs } from '../../shared/ai-vault/contracts/ai-vault-session-title' -import type { AiVaultPrepareSessionResumeRequest } from '../../shared/ai-vault/resume/ai-vault-resume-preparation' -import type { AiVaultSessionHandoffArgs } from '../../shared/ai-vault/contracts/ai-vault-session-handoff' -import type { PreloadApi } from '../api-types' +} from '../../../shared/ai-vault/contracts/ai-vault-types' +import type { AiVaultSessionTitlesArgs } from '../../../shared/ai-vault/contracts/ai-vault-session-title' +import type { AiVaultPrepareSessionResumeRequest } from '../../../shared/ai-vault/resume/ai-vault-resume-preparation' +import type { AiVaultSessionHandoffArgs } from '../../../shared/ai-vault/contracts/ai-vault-session-handoff' +import type { PreloadApi } from '../../api-types' import { AI_VAULT_SCAN_PROGRESS_CHANNEL, type AiVaultScanProgress, type AiVaultScanProgressUpdate -} from '../../shared/ai-vault/scanning/ai-vault-scan-progress' +} from '../../../shared/ai-vault/scanning/ai-vault-scan-progress' function searchClient( executionHostScope?: ExecutionHostScope diff --git a/src/preload/api/app-bridge.ts b/src/preload/api/app-bridge.ts index d9b9bd19edf..b684fb55485 100644 --- a/src/preload/api/app-bridge.ts +++ b/src/preload/api/app-bridge.ts @@ -9,8 +9,11 @@ import { KEYBOARD_LAYOUT_CHANGED_CHANNEL, type KeyboardLayoutChangeEvent } from '../../shared/keyboard-layout-events' -import { prepareAndInvokeAppRestart } from '../renderer-restart-wiring' -import { awaitBeforeUnloadCheckpoint, startupDiagnosticsEnabled } from '../preload-runtime-support' +import { prepareAndInvokeAppRestart } from '../renderer/restart/renderer-restart-wiring' +import { + awaitBeforeUnloadCheckpoint, + startupDiagnosticsEnabled +} from '../renderer/renderer-runtime' import type { PreloadApi } from '../api-types' export const appApi = { diff --git a/src/preload/api/app-icon-api.ts b/src/preload/api/app-icon-api.ts deleted file mode 100644 index d41dd0a2957..00000000000 --- a/src/preload/api/app-icon-api.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { CustomAppIconImportResult } from '../../shared/app-icon' - -export type AppIconApi = { - importCustom: () => Promise - readCustomPreview: () => Promise - removeCustom: () => Promise -} diff --git a/src/preload/api/automation-api.ts b/src/preload/api/automation-api.ts deleted file mode 100644 index 18836f504d4..00000000000 --- a/src/preload/api/automation-api.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { ExecutionHostId } from '../../shared/execution-host' -import type { ExternalAutomationManager } from '../../shared/automations/external/external-automation' -import type { AutomationOwnerRef } from '../../shared/automations/ownership/automation-owner-ref' -import type { - ScopedExternalManagerActionRequest, - ScopedExternalManagerListRequest -} from '../../shared/external-automation-scope' -import type { AutomationsChangedPayload } from '../../shared/runtime-client-events' - -export type ExternalAutomationManagerResult = { - /** Null once a probe succeeded and found no manager configured for this scope. */ - manager: ExternalAutomationManager | null - error: string | null - updatedAt: number -} - -// Automation CRUD uses runtime RPC; this IPC API handles desktop-only calls. -export type AutomationsApi = { - listExternalManagerForOwner: ( - request: ScopedExternalManagerListRequest - ) => Promise - runExternalActionForOwner: (request: ScopedExternalManagerActionRequest) => Promise - retainExternalScopes: (request: { owners: readonly AutomationOwnerRef[] }) => Promise - snapshotWorkspaceName: (args: { - workspaceId: string - hostId: ExecutionHostId - displayName: string - }) => Promise - onChanged: (callback: (payload: AutomationsChangedPayload) => void) => () => void -} diff --git a/src/preload/api/automations-bridge.ts b/src/preload/api/automations-bridge.ts deleted file mode 100644 index 1e6135996ce..00000000000 --- a/src/preload/api/automations-bridge.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { ExecutionHostId } from '../../shared/execution-host' -import { ipcRenderer } from 'electron' -import type { ExternalAutomationManagerResult, PreloadApi } from '../api-types' -import type { AutomationOwnerRef } from '../../shared/automations/ownership/automation-owner-ref' -import type { - ScopedExternalManagerActionRequest, - ScopedExternalManagerListRequest -} from '../../shared/external-automation-scope' -import type { AutomationsChangedPayload } from '../../shared/runtime-client-events' - -export const automationsApi = { - listExternalManagerForOwner: ( - request: ScopedExternalManagerListRequest - ): Promise => - ipcRenderer.invoke('automations:listExternalManagerForOwner', request), - runExternalActionForOwner: (request: ScopedExternalManagerActionRequest): Promise => - ipcRenderer.invoke('automations:runExternalActionForOwner', request), - retainExternalScopes: (request: { owners: readonly AutomationOwnerRef[] }): Promise => - ipcRenderer.invoke('automations:retainExternalScopes', request), - snapshotWorkspaceName: (args: { - workspaceId: string - hostId: ExecutionHostId - displayName: string - }): Promise => ipcRenderer.invoke('automations:snapshotWorkspaceName', args), - onChanged: (callback: (payload: AutomationsChangedPayload) => void): (() => void) => { - const listener = (_event: Electron.IpcRendererEvent, payload: AutomationsChangedPayload) => - callback(payload) - ipcRenderer.on('automations:changed', listener) - return () => ipcRenderer.removeListener('automations:changed', listener) - } -} satisfies PreloadApi['automations'] diff --git a/src/preload/api/automations/automation-api.ts b/src/preload/api/automations/automation-api.ts new file mode 100644 index 00000000000..7dcb85528d5 --- /dev/null +++ b/src/preload/api/automations/automation-api.ts @@ -0,0 +1,30 @@ +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ExternalAutomationManager } from '../../../shared/automations/external/external-automation' +import type { AutomationOwnerRef } from '../../../shared/automations/ownership/automation-owner-ref' +import type { + ScopedExternalManagerActionRequest, + ScopedExternalManagerListRequest +} from '../../../shared/external-automation-scope' +import type { AutomationsChangedPayload } from '../../../shared/runtime-client-events' + +export type ExternalAutomationManagerResult = { + /** Null once a probe succeeded and found no manager configured for this scope. */ + manager: ExternalAutomationManager | null + error: string | null + updatedAt: number +} + +// Automation CRUD uses runtime RPC; this IPC API handles desktop-only calls. +export type AutomationsApi = { + listExternalManagerForOwner: ( + request: ScopedExternalManagerListRequest + ) => Promise + runExternalActionForOwner: (request: ScopedExternalManagerActionRequest) => Promise + retainExternalScopes: (request: { owners: readonly AutomationOwnerRef[] }) => Promise + snapshotWorkspaceName: (args: { + workspaceId: string + hostId: ExecutionHostId + displayName: string + }) => Promise + onChanged: (callback: (payload: AutomationsChangedPayload) => void) => () => void +} diff --git a/src/preload/api/automations/automations-bridge.ts b/src/preload/api/automations/automations-bridge.ts new file mode 100644 index 00000000000..6f3f5af4552 --- /dev/null +++ b/src/preload/api/automations/automations-bridge.ts @@ -0,0 +1,32 @@ +import type { ExecutionHostId } from '../../../shared/execution-host' +import { ipcRenderer } from 'electron' +import type { ExternalAutomationManagerResult } from './automation-api' +import type { PreloadApi } from '../../api-types' +import type { AutomationOwnerRef } from '../../../shared/automations/ownership/automation-owner-ref' +import type { + ScopedExternalManagerActionRequest, + ScopedExternalManagerListRequest +} from '../../../shared/external-automation-scope' +import type { AutomationsChangedPayload } from '../../../shared/runtime-client-events' + +export const automationsApi = { + listExternalManagerForOwner: ( + request: ScopedExternalManagerListRequest + ): Promise => + ipcRenderer.invoke('automations:listExternalManagerForOwner', request), + runExternalActionForOwner: (request: ScopedExternalManagerActionRequest): Promise => + ipcRenderer.invoke('automations:runExternalActionForOwner', request), + retainExternalScopes: (request: { owners: readonly AutomationOwnerRef[] }): Promise => + ipcRenderer.invoke('automations:retainExternalScopes', request), + snapshotWorkspaceName: (args: { + workspaceId: string + hostId: ExecutionHostId + displayName: string + }): Promise => ipcRenderer.invoke('automations:snapshotWorkspaceName', args), + onChanged: (callback: (payload: AutomationsChangedPayload) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, payload: AutomationsChangedPayload) => + callback(payload) + ipcRenderer.on('automations:changed', listener) + return () => ipcRenderer.removeListener('automations:changed', listener) + } +} satisfies PreloadApi['automations'] diff --git a/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts b/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts index 48d27c8f339..3f5d1245fc8 100644 --- a/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts +++ b/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts @@ -17,7 +17,7 @@ import type { BrowserPagePromptResult } from '../../../shared/browser/prompts/browser-page-prompt' import { readBrowserClientHostIdArgument } from '../../../shared/browser/client-hosting/browser-client-host-id-argument' -import { browserClientPageRendererRequests } from '../../preload-runtime-support' +import { browserClientPageRendererRequests } from '../../renderer/renderer-runtime' import type { PreloadApi } from '../../api-types' export const browserGuestRegistrationAndDownloadsApi = { diff --git a/src/preload/api/browser-passwords-api.ts b/src/preload/api/browser/browser-passwords-api.ts similarity index 97% rename from src/preload/api/browser-passwords-api.ts rename to src/preload/api/browser/browser-passwords-api.ts index b0fde266456..6f1aac27618 100644 --- a/src/preload/api/browser-passwords-api.ts +++ b/src/preload/api/browser/browser-passwords-api.ts @@ -11,7 +11,7 @@ import type { BrowserPasswordSavePrompt, BrowserPasswordSavePromptResponse, BrowserPasswordsStatus -} from '../../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' type ProfileArgs = { browserProfileId: string } type EntryArgs = ProfileArgs & { entryId: string } diff --git a/src/preload/api/browser-passwords-bridge.ts b/src/preload/api/browser/browser-passwords-bridge.ts similarity index 100% rename from src/preload/api/browser-passwords-bridge.ts rename to src/preload/api/browser/browser-passwords-bridge.ts diff --git a/src/preload/api/claude-usage-bridge.ts b/src/preload/api/claude-usage-bridge.ts deleted file mode 100644 index aee5e62425e..00000000000 --- a/src/preload/api/claude-usage-bridge.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' -import type { PreloadApi } from '../api-types' - -export const claudeUsageApi = createUsageProviderApi( - backendUsageTransport, - 'claudeUsage' -) satisfies PreloadApi['claudeUsage'] diff --git a/src/preload/api/cli-bridge.ts b/src/preload/api/cli-install/cli-bridge.ts similarity index 86% rename from src/preload/api/cli-bridge.ts rename to src/preload/api/cli-install/cli-bridge.ts index 939d8db03e1..5b780534fd3 100644 --- a/src/preload/api/cli-bridge.ts +++ b/src/preload/api/cli-install/cli-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { CliInstallStatus } from '../../shared/cli-install-types' -import type { PreloadApi } from '../api-types' +import type { CliInstallStatus } from '../../../shared/cli-install-types' +import type { PreloadApi } from '../../api-types' export const cliApi = { getInstallStatus: (): Promise => ipcRenderer.invoke('cli:getInstallStatus'), diff --git a/src/preload/api/cli-install-api.ts b/src/preload/api/cli-install/cli-install-api.ts similarity index 87% rename from src/preload/api/cli-install-api.ts rename to src/preload/api/cli-install/cli-install-api.ts index 801d5cd8052..e01b7e18249 100644 --- a/src/preload/api/cli-install-api.ts +++ b/src/preload/api/cli-install/cli-install-api.ts @@ -1,4 +1,4 @@ -import type { CliInstallStatus } from '../../shared/cli-install-types' +import type { CliInstallStatus } from '../../../shared/cli-install-types' export type CliApi = { getInstallStatus: () => Promise diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/cloud-workspaces/ephemeral-vm-api.ts similarity index 86% rename from src/preload/api/ephemeral-vm-api.ts rename to src/preload/api/cloud-workspaces/ephemeral-vm-api.ts index 0c01a8bf0b4..6c0221171b0 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/cloud-workspaces/ephemeral-vm-api.ts @@ -1,14 +1,14 @@ -import type { OrcaHooks } from '../../shared/orca-yaml-hook-types' -import type { PublicKnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { EphemeralVmRecipeDoctorResult } from '../../shared/ephemeral-vm-recipes' -import type { EphemeralVmRecipeResultWarning } from '../../shared/ephemeral-vm-recipe-diagnostics' +import type { OrcaHooks } from '../../../shared/orca-yaml-hook-types' +import type { PublicKnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { EphemeralVmRecipeDoctorResult } from '../../../shared/ephemeral-vm-recipes' +import type { EphemeralVmRecipeResultWarning } from '../../../shared/ephemeral-vm-recipe-diagnostics' import type { EphemeralVmProvisionedRuntimeRecord, EphemeralVmRuntimeRecord, EphemeralVmWorkspaceLifecycleResult -} from '../../shared/ephemeral-vm-runtimes' -import type { EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' -import type { PendingVmCheckout } from '../../shared/pending-vm-checkouts' +} from '../../../shared/ephemeral-vm-runtimes' +import type { EphemeralVmFailure } from '../../../shared/ephemeral-vm-failure-copy' +import type { PendingVmCheckout } from '../../../shared/pending-vm-checkouts' export type EphemeralVmApi = { listRecipes: (args: { repoId: string }) => Promise<{ diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/cloud-workspaces/ephemeral-vm-bridge.ts similarity index 92% rename from src/preload/api/ephemeral-vm-bridge.ts rename to src/preload/api/cloud-workspaces/ephemeral-vm-bridge.ts index dc1b4ea12c7..177cbd0c827 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/cloud-workspaces/ephemeral-vm-bridge.ts @@ -1,10 +1,10 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import { EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL } from '../../shared/ephemeral-vm-runtime-store-events' +import type { PreloadApi } from '../../api-types' +import { EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL } from '../../../shared/ephemeral-vm-runtime-store-events' import { PENDING_VM_CHECKOUTS_CHANGED_CHANNEL, type PendingVmCheckout -} from '../../shared/pending-vm-checkouts' +} from '../../../shared/pending-vm-checkouts' export const ephemeralVmApi = { listRecipes: (args) => ipcRenderer.invoke('ephemeralVm:listRecipes', args), diff --git a/src/preload/api/codex-config-sync-bridge.ts b/src/preload/api/codex-config-sync-bridge.ts deleted file mode 100644 index 82eedfaf0ec..00000000000 --- a/src/preload/api/codex-config-sync-bridge.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { CodexConfigSyncStatus } from '../../shared/codex-config-sync-types' -import type { PreloadApi } from '../api-types' - -export const codexConfigSyncApi = { - status: (): Promise => ipcRenderer.invoke('codexConfigSync:status') -} satisfies PreloadApi['codexConfigSync'] diff --git a/src/preload/api/codex-usage-bridge.ts b/src/preload/api/codex-usage-bridge.ts deleted file mode 100644 index 0705d66ccb5..00000000000 --- a/src/preload/api/codex-usage-bridge.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' -import type { PreloadApi } from '../api-types' - -export const codexUsageApi = createUsageProviderApi( - backendUsageTransport, - 'codexUsage' -) satisfies PreloadApi['codexUsage'] diff --git a/src/preload/api/crash-reports-bridge.ts b/src/preload/api/crash-reports-bridge.ts deleted file mode 100644 index a77ad412eb7..00000000000 --- a/src/preload/api/crash-reports-bridge.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { - CrashReportBreadcrumbData, - CrashReportCopyDiagnosticsArgs, - CrashReportSubmitArgs, - CrashReportSubmitResult, - ReactErrorBoundaryReportArgs, - ReactErrorBoundaryReportResult -} from '../../shared/crash-reporting' -import type { RendererHeapStatistics } from '../../shared/renderer-heap-statistics' -import type { RendererProcessMemory } from '../../shared/renderer-process-memory' -import { readRendererHeapStatistics } from '../renderer-heap-statistics-reader' -import { readRendererProcessMemory } from '../renderer-process-memory-reader' -import type { PreloadApi } from '../api-types' - -export const crashReportsApi = { - getLatestPending: () => ipcRenderer.invoke('crashReports:getLatestPending'), - getLatestReport: () => ipcRenderer.invoke('crashReports:getLatestReport'), - dismiss: (args: { reportId: string }) => ipcRenderer.invoke('crashReports:dismiss', args), - recordRendererError: ( - args: ReactErrorBoundaryReportArgs - ): Promise => - ipcRenderer.invoke('crashReports:recordRendererError', args), - recordBreadcrumb: (args: { name: string; data?: CrashReportBreadcrumbData }): void => - ipcRenderer.send('crashReports:recordBreadcrumb', args), - submit: (args: CrashReportSubmitArgs): Promise => - ipcRenderer.invoke('crashReports:submit', args), - copyLatestDiagnostics: (args?: CrashReportCopyDiagnosticsArgs) => - ipcRenderer.invoke('crashReports:copyLatestDiagnostics', args), - readHeapStatistics: (): RendererHeapStatistics | null => readRendererHeapStatistics(), - readProcessMemory: (): Promise => readRendererProcessMemory() -} satisfies PreloadApi['crashReports'] diff --git a/src/preload/api/cursor-accounts-bridge.ts b/src/preload/api/cursor-accounts-bridge.ts deleted file mode 100644 index 20f8d5d6a00..00000000000 --- a/src/preload/api/cursor-accounts-bridge.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { CursorAccountStatus } from '../../shared/rate-limit-types' -import type { PreloadApi } from '../api-types' - -export const cursorAccountsApi = { - getStatus: (): Promise => ipcRenderer.invoke('cursorAccounts:getStatus') -} satisfies PreloadApi['cursorAccounts'] diff --git a/src/preload/api/computer-use-permissions-bridge.ts b/src/preload/api/desktop-permissions/computer-use-permissions-bridge.ts similarity index 88% rename from src/preload/api/computer-use-permissions-bridge.ts rename to src/preload/api/desktop-permissions/computer-use-permissions-bridge.ts index bd36efbdcc3..a65769c1f3b 100644 --- a/src/preload/api/computer-use-permissions-bridge.ts +++ b/src/preload/api/desktop-permissions/computer-use-permissions-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const computerUsePermissionsApi = { getStatus: () => ipcRenderer.invoke('computerUsePermissions:getStatus'), diff --git a/src/preload/api/developer-permissions-bridge.ts b/src/preload/api/desktop-permissions/developer-permissions-bridge.ts similarity index 91% rename from src/preload/api/developer-permissions-bridge.ts rename to src/preload/api/desktop-permissions/developer-permissions-bridge.ts index 94158cd7818..a5bc6ff8b34 100644 --- a/src/preload/api/developer-permissions-bridge.ts +++ b/src/preload/api/desktop-permissions/developer-permissions-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const developerPermissionsApi = { getStatus: () => ipcRenderer.invoke('developerPermissions:getStatus'), diff --git a/src/preload/api/macos-tcc-prompts-bridge.ts b/src/preload/api/desktop-permissions/macos-tcc-prompts-bridge.ts similarity index 95% rename from src/preload/api/macos-tcc-prompts-bridge.ts rename to src/preload/api/desktop-permissions/macos-tcc-prompts-bridge.ts index ef24b9e203e..40de540121d 100644 --- a/src/preload/api/macos-tcc-prompts-bridge.ts +++ b/src/preload/api/desktop-permissions/macos-tcc-prompts-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const macosTccPromptsApi = { onThreshold: (callback: (payload: { promptCount: number }) => void) => { diff --git a/src/preload/api/os-permission-api.ts b/src/preload/api/desktop-permissions/os-permission-api.ts similarity index 91% rename from src/preload/api/os-permission-api.ts rename to src/preload/api/desktop-permissions/os-permission-api.ts index 1c9e046ca49..1bdab47c701 100644 --- a/src/preload/api/os-permission-api.ts +++ b/src/preload/api/desktop-permissions/os-permission-api.ts @@ -3,13 +3,13 @@ import type { ComputerUsePermissionResetResult, ComputerUsePermissionSetupResult, ComputerUsePermissionStatusResult -} from '../../shared/computer-use-permissions-types' +} from '../../../shared/computer-use-permissions-types' import type { DeveloperPermissionId, DeveloperPermissionRequestResult, DeveloperPermissionState, LocalNetworkConnectionTestResult -} from '../../shared/developer-permissions-types' +} from '../../../shared/developer-permissions-types' import type { NotificationAttentionAcknowledgement, NotificationDeliveryProbeResult, @@ -19,8 +19,8 @@ import type { NotificationPermissionStatusResult, NotificationSoundResult, StructuredNotificationRead -} from '../../shared/notification-settings-types' -import type { AgentSessionExecutionLocation } from '../../shared/agent-session/lifecycle/agent-session-record' +} from '../../../shared/notification-settings-types' +import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record' export type NotificationsApi = { getDesktopAwayState: () => Promise diff --git a/src/preload/api/crash-report-api.ts b/src/preload/api/diagnostics/crash-report-api.ts similarity index 81% rename from src/preload/api/crash-report-api.ts rename to src/preload/api/diagnostics/crash-report-api.ts index 90e13b0ff83..461581d568c 100644 --- a/src/preload/api/crash-report-api.ts +++ b/src/preload/api/diagnostics/crash-report-api.ts @@ -6,13 +6,13 @@ import type { CrashReportSubmitResult, ReactErrorBoundaryReportArgs, ReactErrorBoundaryReportResult -} from '../../shared/crash-reporting' +} from '../../../shared/crash-reporting' import type { FeedbackSubmitArgs, FeedbackSubmitResult -} from '../../shared/feedback-submit-contract' -import type { RendererHeapStatistics } from '../../shared/renderer-heap-statistics' -import type { RendererProcessMemory } from '../../shared/renderer-process-memory' +} from '../../../shared/feedback-submit-contract' +import type { RendererHeapStatistics } from '../../../shared/renderer-heap-statistics' +import type { RendererProcessMemory } from '../../../shared/renderer-process-memory' export type CrashReportsApi = { getLatestPending: () => Promise diff --git a/src/preload/api/diagnostics/crash-reports-bridge.ts b/src/preload/api/diagnostics/crash-reports-bridge.ts new file mode 100644 index 00000000000..c847b9c7f8a --- /dev/null +++ b/src/preload/api/diagnostics/crash-reports-bridge.ts @@ -0,0 +1,32 @@ +import { ipcRenderer } from 'electron' +import type { + CrashReportBreadcrumbData, + CrashReportCopyDiagnosticsArgs, + CrashReportSubmitArgs, + CrashReportSubmitResult, + ReactErrorBoundaryReportArgs, + ReactErrorBoundaryReportResult +} from '../../../shared/crash-reporting' +import type { RendererHeapStatistics } from '../../../shared/renderer-heap-statistics' +import type { RendererProcessMemory } from '../../../shared/renderer-process-memory' +import { readRendererHeapStatistics } from '../../renderer/diagnostics/renderer-heap-statistics-reader' +import { readRendererProcessMemory } from '../../renderer/diagnostics/renderer-process-memory-reader' +import type { PreloadApi } from '../../api-types' + +export const crashReportsApi = { + getLatestPending: () => ipcRenderer.invoke('crashReports:getLatestPending'), + getLatestReport: () => ipcRenderer.invoke('crashReports:getLatestReport'), + dismiss: (args: { reportId: string }) => ipcRenderer.invoke('crashReports:dismiss', args), + recordRendererError: ( + args: ReactErrorBoundaryReportArgs + ): Promise => + ipcRenderer.invoke('crashReports:recordRendererError', args), + recordBreadcrumb: (args: { name: string; data?: CrashReportBreadcrumbData }): void => + ipcRenderer.send('crashReports:recordBreadcrumb', args), + submit: (args: CrashReportSubmitArgs): Promise => + ipcRenderer.invoke('crashReports:submit', args), + copyLatestDiagnostics: (args?: CrashReportCopyDiagnosticsArgs) => + ipcRenderer.invoke('crashReports:copyLatestDiagnostics', args), + readHeapStatistics: (): RendererHeapStatistics | null => readRendererHeapStatistics(), + readProcessMemory: (): Promise => readRendererProcessMemory() +} satisfies PreloadApi['crashReports'] diff --git a/src/preload/api/diagnostics-bridge.ts b/src/preload/api/diagnostics/diagnostics-bridge.ts similarity index 94% rename from src/preload/api/diagnostics-bridge.ts rename to src/preload/api/diagnostics/diagnostics-bridge.ts index bff79fe5817..95bbaa08efc 100644 --- a/src/preload/api/diagnostics-bridge.ts +++ b/src/preload/api/diagnostics/diagnostics-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const diagnosticsApi = { getStatus: () => ipcRenderer.invoke('diagnostics:getStatus'), diff --git a/src/preload/api/diagnostics/e2e-bridge.ts b/src/preload/api/diagnostics/e2e-bridge.ts new file mode 100644 index 00000000000..bfc543d31aa --- /dev/null +++ b/src/preload/api/diagnostics/e2e-bridge.ts @@ -0,0 +1,6 @@ +import { preloadE2EConfig } from '../../renderer/e2e-config' +import type { PreloadApi } from '../../api-types' + +export const e2eApi = { + getConfig: () => preloadE2EConfig +} satisfies PreloadApi['e2e'] diff --git a/src/preload/api/diagnostics/feedback-bridge.ts b/src/preload/api/diagnostics/feedback-bridge.ts new file mode 100644 index 00000000000..3829b24fefa --- /dev/null +++ b/src/preload/api/diagnostics/feedback-bridge.ts @@ -0,0 +1,11 @@ +import { ipcRenderer } from 'electron' +import type { PreloadApi } from '../../api-types' +import type { + FeedbackSubmitArgs, + FeedbackSubmitResult +} from '../../../shared/feedback-submit-contract' + +export const feedbackApi = { + submit: (args: FeedbackSubmitArgs): Promise => + ipcRenderer.invoke('feedback:submit', args) +} satisfies PreloadApi['feedback'] diff --git a/src/preload/api/memory-bridge.ts b/src/preload/api/diagnostics/memory-bridge.ts similarity index 76% rename from src/preload/api/memory-bridge.ts rename to src/preload/api/diagnostics/memory-bridge.ts index fea84ce6173..353557c78ed 100644 --- a/src/preload/api/memory-bridge.ts +++ b/src/preload/api/diagnostics/memory-bridge.ts @@ -1,8 +1,8 @@ import { ipcRenderer } from 'electron' -import type { MemorySnapshot } from '../../shared/process-stats-types' -import type { PreloadApi } from '../api-types' +import type { MemorySnapshot } from '../../../shared/process-stats-types' +import type { PreloadApi } from '../../api-types' -import type { ResourceViewAdmission } from '../../shared/resource-view-admission' +import type { ResourceViewAdmission } from '../../../shared/resource-view-admission' export const memoryApi = { getSnapshot: (admission?: ResourceViewAdmission): Promise => diff --git a/src/preload/api/stats-bridge.ts b/src/preload/api/diagnostics/stats-bridge.ts similarity index 85% rename from src/preload/api/stats-bridge.ts rename to src/preload/api/diagnostics/stats-bridge.ts index f435b9980f5..92558279a6a 100644 --- a/src/preload/api/stats-bridge.ts +++ b/src/preload/api/diagnostics/stats-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const statsApi = { getSummary: (): Promise<{ diff --git a/src/preload/api/telemetry-api.ts b/src/preload/api/diagnostics/telemetry-api.ts similarity index 89% rename from src/preload/api/telemetry-api.ts rename to src/preload/api/diagnostics/telemetry-api.ts index 48b9670d45f..ef15e7f9f4d 100644 --- a/src/preload/api/telemetry-api.ts +++ b/src/preload/api/diagnostics/telemetry-api.ts @@ -1,6 +1,6 @@ -import type { ResourceViewAdmission } from '../../shared/resource-view-admission' -import type { TelemetryConsentState } from '../../shared/telemetry-consent-types' -import type { MemorySnapshot, StatsSummary } from '../../shared/process-stats-types' +import type { ResourceViewAdmission } from '../../../shared/resource-view-admission' +import type { TelemetryConsentState } from '../../../shared/telemetry-consent-types' +import type { MemorySnapshot, StatsSummary } from '../../../shared/process-stats-types' export type StatsApi = { getSummary: () => Promise diff --git a/src/preload/api/doc-preview-api.ts b/src/preload/api/document-preview/doc-preview-api.ts similarity index 94% rename from src/preload/api/doc-preview-api.ts rename to src/preload/api/document-preview/doc-preview-api.ts index 63f62f10bb4..1ce27ceb625 100644 --- a/src/preload/api/doc-preview-api.ts +++ b/src/preload/api/document-preview/doc-preview-api.ts @@ -1,7 +1,7 @@ import type { DocPreviewExternalLink, DocPreviewFailure -} from '../../shared/document-preview/doc-preview-scheme' +} from '../../../shared/document-preview/doc-preview-scheme' export type DocPreviewGrantOwner = | { kind: 'ssh'; connectionId: string } diff --git a/src/preload/api/doc-preview-bridge.ts b/src/preload/api/document-preview/doc-preview-bridge.ts similarity index 89% rename from src/preload/api/doc-preview-bridge.ts rename to src/preload/api/document-preview/doc-preview-bridge.ts index 4dd6ce3598e..f60b3dd8e0a 100644 --- a/src/preload/api/doc-preview-bridge.ts +++ b/src/preload/api/document-preview/doc-preview-bridge.ts @@ -7,9 +7,9 @@ import { DOC_PREVIEW_REVOKE_GRANT_CHANNEL, type DocPreviewFailure, type DocPreviewExternalLink -} from '../../shared/document-preview/doc-preview-scheme' -import type { DocPreviewGrantRequest } from '../api/doc-preview-api' -import type { PreloadApi } from '../api-types' +} from '../../../shared/document-preview/doc-preview-scheme' +import type { DocPreviewGrantRequest } from './doc-preview-api' +import type { PreloadApi } from '../../api-types' export const docPreviewApi = { mintGrant: (request: DocPreviewGrantRequest): Promise<{ grantId: string; url: string }> => diff --git a/src/preload/api/document-preview/export-bridge.ts b/src/preload/api/document-preview/export-bridge.ts new file mode 100644 index 00000000000..b7acabc4a95 --- /dev/null +++ b/src/preload/api/document-preview/export-bridge.ts @@ -0,0 +1,8 @@ +import { ipcRenderer } from 'electron' +import type { PreloadApi } from '../../api-types' +import type { PdfExportResult } from '../../../shared/pdf-export-failure-copy' + +export const exportApi = { + htmlToPdf: (args: { html: string; title: string }): Promise => + ipcRenderer.invoke('export:html-to-pdf', args) +} satisfies PreloadApi['export'] diff --git a/src/preload/api/notebook-bridge.ts b/src/preload/api/document-preview/notebook-bridge.ts similarity index 88% rename from src/preload/api/notebook-bridge.ts rename to src/preload/api/document-preview/notebook-bridge.ts index 206c320a6b3..00f437bcf08 100644 --- a/src/preload/api/notebook-bridge.ts +++ b/src/preload/api/document-preview/notebook-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import type { KernelFrameEvent } from '../../shared/notebook-kernel-types' +import type { PreloadApi } from '../../api-types' +import type { KernelFrameEvent } from '../../../shared/notebook-kernel-types' export const notebookApi = { listPythonEnvironments: (args) => ipcRenderer.invoke('notebook:listPythonEnvironments', args), diff --git a/src/preload/api/e2e-bridge.ts b/src/preload/api/e2e-bridge.ts deleted file mode 100644 index 900b17a9fcf..00000000000 --- a/src/preload/api/e2e-bridge.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { preloadE2EConfig } from '../e2e-config' -import type { PreloadApi } from '../api-types' - -export const e2eApi = { - getConfig: () => preloadE2EConfig -} satisfies PreloadApi['e2e'] diff --git a/src/preload/api/emulator-api.ts b/src/preload/api/emulator/emulator-api.ts similarity index 100% rename from src/preload/api/emulator-api.ts rename to src/preload/api/emulator/emulator-api.ts diff --git a/src/preload/api/emulator-bridge.ts b/src/preload/api/emulator/emulator-bridge.ts similarity index 98% rename from src/preload/api/emulator-bridge.ts rename to src/preload/api/emulator/emulator-bridge.ts index 50fb7c3c166..ea4a3a6f736 100644 --- a/src/preload/api/emulator-bridge.ts +++ b/src/preload/api/emulator/emulator-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const emulatorApi = { startFrameStream: (args: { diff --git a/src/preload/api/export-bridge.ts b/src/preload/api/export-bridge.ts deleted file mode 100644 index 3b9dc540fba..00000000000 --- a/src/preload/api/export-bridge.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import type { PdfExportResult } from '../../shared/pdf-export-failure-copy' - -export const exportApi = { - htmlToPdf: (args: { html: string; title: string }): Promise => - ipcRenderer.invoke('export:html-to-pdf', args) -} satisfies PreloadApi['export'] diff --git a/src/preload/api/feedback-bridge.ts b/src/preload/api/feedback-bridge.ts deleted file mode 100644 index 4c20e90cd8f..00000000000 --- a/src/preload/api/feedback-bridge.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import type { - FeedbackSubmitArgs, - FeedbackSubmitResult -} from '../../shared/feedback-submit-contract' - -export const feedbackApi = { - submit: (args: FeedbackSubmitArgs): Promise => - ipcRenderer.invoke('feedback:submit', args) -} satisfies PreloadApi['feedback'] diff --git a/src/preload/api/filesystem-api.ts b/src/preload/api/filesystem/filesystem-api.ts similarity index 86% rename from src/preload/api/filesystem-api.ts rename to src/preload/api/filesystem/filesystem-api.ts index 876859ba373..c06365f8455 100644 --- a/src/preload/api/filesystem-api.ts +++ b/src/preload/api/filesystem/filesystem-api.ts @@ -1,47 +1,47 @@ -import type { PathExistenceResult } from '../../shared/file-access/path-existence-batch' -import type { RuntimeFileReadChunkResult } from '../../shared/file-content/runtime-file-read' -import type { SearchOptions, SearchResult } from '../../shared/file-search/code-search-types' -import type { PdfExportResult } from '../../shared/pdf-export-failure-copy' -import type { DirEntry } from '../../shared/file-listing/directory-entry' -import type { FsChangedPayload } from '../../shared/file-watch/filesystem-change-event' -import type { MarkdownDocument } from '../../shared/file-listing/file-document' +import type { PathExistenceResult } from '../../../shared/file-access/path-existence-batch' +import type { RuntimeFileReadChunkResult } from '../../../shared/file-content/runtime-file-read' +import type { SearchOptions, SearchResult } from '../../../shared/file-search/code-search-types' +import type { PdfExportResult } from '../../../shared/pdf-export-failure-copy' +import type { DirEntry } from '../../../shared/file-listing/directory-entry' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' +import type { MarkdownDocument } from '../../../shared/file-listing/file-document' import type { ImportItemResult, ResolveDroppedPathsResult -} from '../../shared/file-import/filesystem-import-result' +} from '../../../shared/file-import/filesystem-import-result' import type { StagedRuntimeUploadSource as StagedExternalImportSource, RuntimeUploadFileStreamRequest -} from '../../shared/file-import/runtime-upload-staging-contract' +} from '../../../shared/file-import/runtime-upload-staging-contract' import type { LocalLogTailChangedPayload, LocalLogTailReadArgs, LocalLogTailReadResult, LocalLogTailWatchArgs -} from '../../shared/local-log-tail-types' -import type { SshMutationExpectation } from '../../shared/ssh-types' -import type { LocalFileAccess } from '../../shared/file-access/local-file-access' -import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' -import type { FileBytesWritePrecondition } from '../../shared/file-write/file-bytes-write' +} from '../../../shared/local-log-tail-types' +import type { SshMutationExpectation } from '../../../shared/ssh-types' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' +import type { RemoteFilePreviewAddress } from '../../../shared/file-preview/remote-file-preview-address' +import type { FileBytesWritePrecondition } from '../../../shared/file-write/file-bytes-write' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../shared/file-write/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' import type { CreateVenvResult, KernelFrameEvent, KernelStartResult, PythonEnvironment, PythonEnvironments -} from '../../shared/notebook-kernel-types' +} from '../../../shared/notebook-kernel-types' import type { AgentSessionAttachmentPathUploadResult, AgentSessionAttachmentUploadTarget -} from '../../shared/agent-session/agent-session-attachments' +} from '../../../shared/agent-session/agent-session-attachments' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/file-import/native-file-drop-preparation' +} from '../../../shared/file-import/native-file-drop-preparation' export type ExportApi = { htmlToPdf: (args: { html: string; title: string }) => Promise diff --git a/src/preload/api/fs-bridge.ts b/src/preload/api/filesystem/fs-bridge.ts similarity index 90% rename from src/preload/api/fs-bridge.ts rename to src/preload/api/filesystem/fs-bridge.ts index dcc376428c0..8f6e091c5c3 100644 --- a/src/preload/api/fs-bridge.ts +++ b/src/preload/api/filesystem/fs-bridge.ts @@ -1,38 +1,38 @@ -import type { PathExistenceResult } from '../../shared/file-access/path-existence-batch' +import type { PathExistenceResult } from '../../../shared/file-access/path-existence-batch' import { ipcRenderer, webUtils } from 'electron' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/file-import/native-file-drop-preparation' -import type { SshMutationExpectation } from '../../shared/ssh-types' -import type { LocalFileAccess } from '../../shared/file-access/local-file-access' -import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' -import type { FileBytesWritePrecondition } from '../../shared/file-write/file-bytes-write' +} from '../../../shared/file-import/native-file-drop-preparation' +import type { SshMutationExpectation } from '../../../shared/ssh-types' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' +import type { RemoteFilePreviewAddress } from '../../../shared/file-preview/remote-file-preview-address' +import type { FileBytesWritePrecondition } from '../../../shared/file-write/file-bytes-write' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../shared/file-write/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' import type { RuntimeUploadFileStreamRequest, StagedRuntimeUploadSource as StagedExternalImportSource -} from '../../shared/file-import/runtime-upload-staging-contract' +} from '../../../shared/file-import/runtime-upload-staging-contract' import type { AgentSessionAttachmentPathUploadResult, AgentSessionAttachmentUploadTarget -} from '../../shared/agent-session/agent-session-attachments' -import type { SearchResult } from '../../shared/file-search/code-search-types' -import type { FsChangedPayload } from '../../shared/file-watch/filesystem-change-event' +} from '../../../shared/agent-session/agent-session-attachments' +import type { SearchResult } from '../../../shared/file-search/code-search-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' import type { ImportItemResult, ResolveDroppedPathsResult -} from '../../shared/file-import/filesystem-import-result' +} from '../../../shared/file-import/filesystem-import-result' import type { LocalLogTailChangedPayload, LocalLogTailReadArgs, LocalLogTailReadResult, LocalLogTailWatchArgs -} from '../../shared/local-log-tail-types' -import type { PreloadApi } from '../api-types' +} from '../../../shared/local-log-tail-types' +import type { PreloadApi } from '../../api-types' export const fsApi = { getPathForFile: (file: File): string => webUtils.getPathForFile(file), diff --git a/src/preload/api/cache-bridge.ts b/src/preload/api/github/cache-bridge.ts similarity index 81% rename from src/preload/api/cache-bridge.ts rename to src/preload/api/github/cache-bridge.ts index 73fd9db88c0..d18284662a4 100644 --- a/src/preload/api/cache-bridge.ts +++ b/src/preload/api/github/cache-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const cacheApi = { getGitHub: () => ipcRenderer.invoke('cache:getGitHub'), diff --git a/src/preload/api/gh-bridge-mutations-and-projects.ts b/src/preload/api/github/gh-bridge-mutations-and-projects.ts similarity index 90% rename from src/preload/api/gh-bridge-mutations-and-projects.ts rename to src/preload/api/github/gh-bridge-mutations-and-projects.ts index a057485be6d..9059845c61e 100644 --- a/src/preload/api/gh-bridge-mutations-and-projects.ts +++ b/src/preload/api/github/gh-bridge-mutations-and-projects.ts @@ -1,14 +1,15 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' import { ipcRenderer } from 'electron' -import type { GitHubCommentResult } from '../../shared/github/comment-types' -import type { GitHubAssignableUser, GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import type { GetRateLimitResult } from '../../shared/github/rate-limit-types' +import type { GitHubCommentResult } from '../../../shared/github/comments/comment-types' +import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' +import type { GetRateLimitResult } from '../../../shared/github/api/rate-limit-types' import type { GhAccountBindingInventory, GhAccountBindingValidationResult, GhAuthDiagnostic -} from '../../shared/github/auth-types' -import type { TaskSourceContext } from '../../shared/work-items/task-source-context' +} from '../../../shared/github/accounts/auth-types' +import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import type { GetProjectViewTableResult, GitHubProjectCommentMutationResult, @@ -20,7 +21,7 @@ import type { ListProjectViewsResult, ProjectWorkItemDetailsBySlugResult, ResolveProjectRefResult -} from '../../shared/github/project-result-types' +} from '../../../shared/github/projects/project-result-types' import type { AddIssueCommentBySlugArgs, ClearProjectItemFieldArgs, @@ -38,9 +39,9 @@ import type { UpdateIssueTypeBySlugArgs, UpdatePullRequestBySlugArgs, UpdateProjectItemFieldArgs -} from '../../shared/github/project-request-types' -import type { AppStarSource } from '../../shared/gh-star-source' -import type { PreloadApi } from '../api-types' +} from '../../../shared/github/projects/project-request-types' +import type { AppStarSource } from '../../../shared/gh-star-source' +import type { PreloadApi } from '../../api-types' export const ghMutationsAndProjectsApi = { setPRAutoMerge: (args: { diff --git a/src/preload/api/gh-bridge-pull-requests-and-work-items.ts b/src/preload/api/github/gh-bridge-pull-requests-and-work-items.ts similarity index 90% rename from src/preload/api/gh-bridge-pull-requests-and-work-items.ts rename to src/preload/api/github/gh-bridge-pull-requests-and-work-items.ts index 5d57a2c2dda..86831ee4850 100644 --- a/src/preload/api/gh-bridge-pull-requests-and-work-items.ts +++ b/src/preload/api/github/gh-bridge-pull-requests-and-work-items.ts @@ -1,16 +1,19 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' import { ipcRenderer } from 'electron' -import type { GitHubReactionContent } from '../../shared/github/comment-types' +import type { GitHubReactionContent } from '../../../shared/github/comments/comment-types' import type { GitHubPRRefreshCandidate, GitHubPRRefreshEvent, GitHubPRRefreshReason -} from '../../shared/github/pull-request-refresh-types' -import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import type { GitHubWorkItem, ListWorkItemsResult } from '../../shared/github/work-item-types' -import type { GitHubCreateIssueResult } from '../../shared/issue-mutation-types' -import type { TaskSourceContext } from '../../shared/work-items/task-source-context' -import type { PreloadApi } from '../api-types' +} from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' +import type { + GitHubWorkItem, + ListWorkItemsResult +} from '../../../shared/github/work-items/work-item-types' +import type { GitHubCreateIssueResult } from '../../../shared/issue-mutation-types' +import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' +import type { PreloadApi } from '../../api-types' export const ghPullRequestsAndWorkItemsApi = { viewer: () => ipcRenderer.invoke('gh:viewer'), diff --git a/src/preload/api/gh-bridge.ts b/src/preload/api/github/gh-bridge.ts similarity index 85% rename from src/preload/api/gh-bridge.ts rename to src/preload/api/github/gh-bridge.ts index c7da93698e6..8eb0d90c37f 100644 --- a/src/preload/api/gh-bridge.ts +++ b/src/preload/api/github/gh-bridge.ts @@ -1,4 +1,4 @@ -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' import { ghPullRequestsAndWorkItemsApi } from './gh-bridge-pull-requests-and-work-items' import { ghMutationsAndProjectsApi } from './gh-bridge-mutations-and-projects' diff --git a/src/preload/api/github-account-api.ts b/src/preload/api/github/github-account-api.ts similarity index 89% rename from src/preload/api/github-account-api.ts rename to src/preload/api/github/github-account-api.ts index fe219d55065..04f843c0c2f 100644 --- a/src/preload/api/github-account-api.ts +++ b/src/preload/api/github/github-account-api.ts @@ -1,7 +1,7 @@ import type { GhAccountBindingInventory, GhAccountBindingValidationResult -} from '../../shared/github/auth-types' +} from '../../../shared/github/accounts/auth-types' export type GithubAccountApi = { listBindableAccounts: (args: { diff --git a/src/preload/api/github-pull-request-api.ts b/src/preload/api/github/github-pull-request-api.ts similarity index 88% rename from src/preload/api/github-pull-request-api.ts rename to src/preload/api/github/github-pull-request-api.ts index 38c8208a861..c763ebb7798 100644 --- a/src/preload/api/github-pull-request-api.ts +++ b/src/preload/api/github/github-pull-request-api.ts @@ -1,29 +1,29 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' -import type { AppStarSource } from '../../shared/gh-star-source' -import type { GhAuthDiagnostic } from '../../shared/github/auth-types' -import type { TaskSourceContext } from '../../shared/work-items/task-source-context' -import type { PRCheckDetail, PRCheckRunDetails } from '../../shared/github/check-types' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' +import type { AppStarSource } from '../../../shared/gh-star-source' +import type { GhAuthDiagnostic } from '../../../shared/github/accounts/auth-types' +import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' +import type { PRCheckDetail, PRCheckRunDetails } from '../../../shared/github/checks/check-types' import type { GitHubCommentResult, GitHubPRReviewCommentInput, GitHubReactionContent, PRComment -} from '../../shared/github/comment-types' +} from '../../../shared/github/comments/comment-types' import type { GitHubPRRefreshCandidate, GitHubPRRefreshEnqueueResult, GitHubPRRefreshEvent, GitHubPRRefreshReason, PRRefreshOutcome -} from '../../shared/github/pull-request-refresh-types' +} from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { - GitHubOwnerRepo, GitHubPRFile, GitHubPRFileContents, GitHubViewer, PRInfo -} from '../../shared/github/pull-request-types' -import type { GetRateLimitResult } from '../../shared/github/rate-limit-types' +} from '../../../shared/github/pull-requests/pull-request-types' +import type { GetRateLimitResult } from '../../../shared/github/api/rate-limit-types' import type { GitHubRepoSelectorArgs } from './github-work-item-api' export type GithubPullRequestApi = { diff --git a/src/preload/api/github-work-item-api.ts b/src/preload/api/github/github-work-item-api.ts similarity index 88% rename from src/preload/api/github-work-item-api.ts rename to src/preload/api/github/github-work-item-api.ts index f4ce0fc4d66..7ea10d421bd 100644 --- a/src/preload/api/github-work-item-api.ts +++ b/src/preload/api/github/github-work-item-api.ts @@ -1,4 +1,4 @@ -import type { GhAccountBinding } from '../../shared/github/account-binding' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' import type { GetProjectViewTableResult, GitHubProjectCommentMutationResult, @@ -10,7 +10,7 @@ import type { ListProjectViewsResult, ProjectWorkItemDetailsBySlugResult, ResolveProjectRefResult -} from '../../shared/github/project-result-types' +} from '../../../shared/github/projects/project-result-types' import type { AddIssueCommentBySlugArgs, ClearProjectItemFieldArgs, @@ -28,20 +28,23 @@ import type { UpdateIssueTypeBySlugArgs, UpdateProjectItemFieldArgs, UpdatePullRequestBySlugArgs -} from '../../shared/github/project-request-types' -import type { TaskSourceContext } from '../../shared/work-items/task-source-context' -import type { GitHubCommentResult } from '../../shared/github/comment-types' +} from '../../../shared/github/projects/project-request-types' +import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' +import type { GitHubCommentResult } from '../../../shared/github/comments/comment-types' import type { GitHubAssignableUser, - GitHubOwnerRepo, IssueInfo -} from '../../shared/github/pull-request-types' +} from '../../../shared/github/pull-requests/pull-request-types' +import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { GitHubWorkItem, GitHubWorkItemDetails, ListWorkItemsResult -} from '../../shared/github/work-item-types' -import type { GitHubCreateIssueResult, GitHubIssueUpdate } from '../../shared/issue-mutation-types' +} from '../../../shared/github/work-items/work-item-types' +import type { + GitHubCreateIssueResult, + GitHubIssueUpdate +} from '../../../shared/issue-mutation-types' export type GitHubRepoSelectorArgs = { repoOwnerExecutionHostId?: string diff --git a/src/preload/api/gitlab-api.ts b/src/preload/api/gitlab/gitlab-api.ts similarity index 96% rename from src/preload/api/gitlab-api.ts rename to src/preload/api/gitlab/gitlab-api.ts index 7a651c92a5d..c0380696f34 100644 --- a/src/preload/api/gitlab-api.ts +++ b/src/preload/api/gitlab/gitlab-api.ts @@ -1,5 +1,5 @@ -import type { TaskSourceContext } from '../../shared/work-items/task-source-context' -import type { ClassifiedError } from '../../shared/classified-error' +import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' +import type { ClassifiedError } from '../../../shared/classified-error' import type { GetGitLabRateLimitResult, GitLabAssignableUser, @@ -22,7 +22,7 @@ import type { ListMergeRequestsResult, MRInfo, MRListState -} from '../../shared/gitlab-types' +} from '../../../shared/gitlab-types' export type GitLabRepoSelectorArgs = { repoPath: string diff --git a/src/preload/gitlab.ts b/src/preload/api/gitlab/gitlab.ts similarity index 96% rename from src/preload/gitlab.ts rename to src/preload/api/gitlab/gitlab.ts index ed2904de2a0..3ca2c858a9c 100644 --- a/src/preload/gitlab.ts +++ b/src/preload/api/gitlab/gitlab.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { GitLabMRInvolvement } from '../shared/gitlab-types' -import type { TaskSourceContext } from '../shared/work-items/task-source-context' +import type { GitLabMRInvolvement } from '../../../shared/gitlab-types' +import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' type GitLabRepoSelectorArgs = { repoPath: string diff --git a/src/preload/api/gl-bridge.ts b/src/preload/api/gl-bridge.ts deleted file mode 100644 index 3977536a838..00000000000 --- a/src/preload/api/gl-bridge.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { glApi } from '../gitlab' -import type { PreloadApi } from '../api-types' - -export const glApiBridge = glApi satisfies PreloadApi['gl'] diff --git a/src/preload/api/grok-accounts-bridge.ts b/src/preload/api/grok-accounts-bridge.ts deleted file mode 100644 index 246fc97bc56..00000000000 --- a/src/preload/api/grok-accounts-bridge.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { GrokAccountStatus } from '../../shared/rate-limit-types' -import type { PreloadApi } from '../api-types' - -export const grokAccountsApi = { - getStatus: (): Promise => ipcRenderer.invoke('grokAccounts:getStatus') -} satisfies PreloadApi['grokAccounts'] diff --git a/src/preload/api/hosted-review-bridge.ts b/src/preload/api/hosted-review-bridge.ts deleted file mode 100644 index bcb55e31fb1..00000000000 --- a/src/preload/api/hosted-review-bridge.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { HostedReviewForBranchArgs } from '../../shared/source-control/hosted-review/hosted-review-contracts' -import type { PreloadApi } from '../api-types' - -export const hostedReviewApi = { - forBranch: (args: HostedReviewForBranchArgs) => - ipcRenderer.invoke('hostedReview:forBranch', args), - getCreationEligibility: (args: unknown) => - ipcRenderer.invoke('hostedReview:getCreationEligibility', args), - create: (args: unknown) => ipcRenderer.invoke('hostedReview:create', args), - createStacked: (args: unknown) => ipcRenderer.invoke('hostedReview:createStacked', args) -} satisfies PreloadApi['hostedReview'] diff --git a/src/preload/api/bitbucket-bridge.ts b/src/preload/api/hosted-review/bitbucket-bridge.ts similarity index 78% rename from src/preload/api/bitbucket-bridge.ts rename to src/preload/api/hosted-review/bitbucket-bridge.ts index bdb8c6632cd..cf8138b9fa7 100644 --- a/src/preload/api/bitbucket-bridge.ts +++ b/src/preload/api/hosted-review/bitbucket-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' -import type { BitbucketConnectResult } from '../../shared/bitbucket-credentials' +import type { PreloadApi } from '../../api-types' +import type { BitbucketConnectResult } from '../../../shared/bitbucket-credentials' export const bitbucketApi = { connect: (args: { diff --git a/src/preload/api/hosted-review-api.ts b/src/preload/api/hosted-review/hosted-review-api.ts similarity index 89% rename from src/preload/api/hosted-review-api.ts rename to src/preload/api/hosted-review/hosted-review-api.ts index 78e70ea83b6..a166bb0dfbf 100644 --- a/src/preload/api/hosted-review-api.ts +++ b/src/preload/api/hosted-review/hosted-review-api.ts @@ -2,7 +2,7 @@ import type { BitbucketConnectArgs, BitbucketConnectResult, BitbucketConnectionStatus -} from '../../shared/bitbucket-credentials' +} from '../../../shared/bitbucket-credentials' import type { CreateHostedReviewArgs, CreateHostedReviewResult, @@ -13,7 +13,7 @@ import type { HostedReviewForBranchArgs, HostedReviewForBranchReply, HostedReviewInfo -} from '../../shared/source-control/hosted-review/hosted-review-contracts' +} from '../../../shared/source-control/hosted-review/hosted-review-contracts' export type HostedReviewApi = { forBranch: { diff --git a/src/preload/api/hosted-review/hosted-review-bridge.ts b/src/preload/api/hosted-review/hosted-review-bridge.ts new file mode 100644 index 00000000000..1edc8be8a63 --- /dev/null +++ b/src/preload/api/hosted-review/hosted-review-bridge.ts @@ -0,0 +1,12 @@ +import { ipcRenderer } from 'electron' +import type { HostedReviewForBranchArgs } from '../../../shared/source-control/hosted-review/hosted-review-contracts' +import type { PreloadApi } from '../../api-types' + +export const hostedReviewApi = { + forBranch: (args: HostedReviewForBranchArgs) => + ipcRenderer.invoke('hostedReview:forBranch', args), + getCreationEligibility: (args: unknown) => + ipcRenderer.invoke('hostedReview:getCreationEligibility', args), + create: (args: unknown) => ipcRenderer.invoke('hostedReview:create', args), + createStacked: (args: unknown) => ipcRenderer.invoke('hostedReview:createStacked', args) +} satisfies PreloadApi['hostedReview'] diff --git a/src/preload/api/link-preview-api.ts b/src/preload/api/link-preview/link-preview-api.ts similarity index 86% rename from src/preload/api/link-preview-api.ts rename to src/preload/api/link-preview/link-preview-api.ts index a13ace004c9..88dd24f92a4 100644 --- a/src/preload/api/link-preview-api.ts +++ b/src/preload/api/link-preview/link-preview-api.ts @@ -1,4 +1,4 @@ -import type { LinkPreviewRequest, LinkPreviewResult } from '../../shared/link-preview' +import type { LinkPreviewRequest, LinkPreviewResult } from '../../../shared/link-preview' export type LinkPreviewApi = { get: (request: LinkPreviewRequest) => Promise diff --git a/src/preload/api/link-preview-bridge.ts b/src/preload/api/link-preview/link-preview-bridge.ts similarity index 77% rename from src/preload/api/link-preview-bridge.ts rename to src/preload/api/link-preview/link-preview-bridge.ts index e7933c2988c..d0c3950805c 100644 --- a/src/preload/api/link-preview-bridge.ts +++ b/src/preload/api/link-preview/link-preview-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const linkPreviewApi = { get: (request) => ipcRenderer.invoke('linkPreview:get', request) diff --git a/src/preload/api/legacy-relay-bridge-api.ts b/src/preload/api/mobile/legacy-relay-bridge-api.ts similarity index 97% rename from src/preload/api/legacy-relay-bridge-api.ts rename to src/preload/api/mobile/legacy-relay-bridge-api.ts index 7144cba339d..5eefcd228cb 100644 --- a/src/preload/api/legacy-relay-bridge-api.ts +++ b/src/preload/api/mobile/legacy-relay-bridge-api.ts @@ -8,7 +8,7 @@ import { type LegacyRelayBridgeAttachResult, type LegacyRelayBridgeCloseResult, type LegacyRelayBridgedPane -} from '../../shared/legacy-relay-bridge-contract' +} from '../../../shared/legacy-relay-bridge-contract' export type LegacyRelayBridgeApi = { listPanes: () => Promise diff --git a/src/preload/api/mobile-api.ts b/src/preload/api/mobile/mobile-api.ts similarity index 84% rename from src/preload/api/mobile-api.ts rename to src/preload/api/mobile/mobile-api.ts index 3ad9d32c313..6a6461ab18e 100644 --- a/src/preload/api/mobile-api.ts +++ b/src/preload/api/mobile/mobile-api.ts @@ -1,8 +1,8 @@ -import type { MobileRelayStatusDetail } from '../../shared/remote-runtime/relay/mobile-relay-status' -import type { MobilePairingConnectionMode } from '../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' -import type { RuntimePairingReach } from '../../shared/runtime-pairing-reach' -import type { MobileRelayMintFailure } from '../../shared/remote-runtime/relay/mobile-relay-mint-failure' -import type { RuntimeAccessGrant } from '../../shared/runtime-access-grants' +import type { MobileRelayStatusDetail } from '../../../shared/remote-runtime/relay/mobile-relay-status' +import type { MobilePairingConnectionMode } from '../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' +import type { RuntimePairingReach } from '../../../shared/runtime-pairing-reach' +import type { MobileRelayMintFailure } from '../../../shared/remote-runtime/relay/mobile-relay-mint-failure' +import type { RuntimeAccessGrant } from '../../../shared/runtime-access-grants' export type MobileApi = { listNetworkInterfaces: () => Promise<{ diff --git a/src/preload/api/mobile-bridge.ts b/src/preload/api/mobile/mobile-bridge.ts similarity index 87% rename from src/preload/api/mobile-bridge.ts rename to src/preload/api/mobile/mobile-bridge.ts index eb80fb0dced..0f3ca141a20 100644 --- a/src/preload/api/mobile-bridge.ts +++ b/src/preload/api/mobile/mobile-bridge.ts @@ -1,9 +1,9 @@ import { ipcRenderer } from 'electron' -import type { MobileRelayStatusDetail } from '../../shared/remote-runtime/relay/mobile-relay-status' -import type { MobilePairingConnectionMode } from '../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' -import type { RuntimePairingReach } from '../../shared/runtime-pairing-reach' -import type { MobileRelayMintFailure } from '../../shared/remote-runtime/relay/mobile-relay-mint-failure' -import type { PreloadApi } from '../api-types' +import type { MobileRelayStatusDetail } from '../../../shared/remote-runtime/relay/mobile-relay-status' +import type { MobilePairingConnectionMode } from '../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' +import type { RuntimePairingReach } from '../../../shared/runtime-pairing-reach' +import type { MobileRelayMintFailure } from '../../../shared/remote-runtime/relay/mobile-relay-mint-failure' +import type { PreloadApi } from '../../api-types' export const mobileApi = { listNetworkInterfaces: (): Promise<{ diff --git a/src/preload/api/muse-usage-bridge.ts b/src/preload/api/muse-usage-bridge.ts deleted file mode 100644 index a741ddac1cb..00000000000 --- a/src/preload/api/muse-usage-bridge.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' -import type { PreloadApi } from '../api-types' - -export const museUsageApi = createUsageProviderApi( - backendUsageTransport, - 'museUsage' -) satisfies PreloadApi['museUsage'] diff --git a/src/preload/api/native-chat-api.ts b/src/preload/api/native-chat/native-chat-api.ts similarity index 91% rename from src/preload/api/native-chat-api.ts rename to src/preload/api/native-chat/native-chat-api.ts index e8a905c1529..dfe135dbe8b 100644 --- a/src/preload/api/native-chat-api.ts +++ b/src/preload/api/native-chat/native-chat-api.ts @@ -1,9 +1,9 @@ -import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' -import type { NativeChatVisualTheme } from '../../shared/native-chat/native-chat-visual-shell' +import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' +import type { NativeChatVisualTheme } from '../../../shared/native-chat/native-chat-visual-shell' import type { NativeChatMessage, NativeChatTurnLifecycle -} from '../../shared/native-chat/native-chat-types' +} from '../../../shared/native-chat/native-chat-types' // notFound marks a not-yet-on-disk miss (retry-worthy) vs a real read/parse error (#8401). export type NativeChatReadSessionResult = diff --git a/src/preload/api/native-chat-bridge.ts b/src/preload/api/native-chat/native-chat-bridge.ts similarity index 87% rename from src/preload/api/native-chat-bridge.ts rename to src/preload/api/native-chat/native-chat-bridge.ts index b4067ed7d09..e62ca22808c 100644 --- a/src/preload/api/native-chat-bridge.ts +++ b/src/preload/api/native-chat/native-chat-bridge.ts @@ -2,14 +2,14 @@ import { ipcRenderer } from 'electron' import type { NativeChatAppendedPayload, NativeChatReadSessionResult, - NativeChatSubscriptionFrame, - PreloadApi -} from '../api-types' -import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' + NativeChatSubscriptionFrame +} from './native-chat-api' +import type { PreloadApi } from '../../api-types' +import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' import { NATIVE_CHAT_VISUAL_GUEST_THEME_PUBLISH, type NativeChatVisualTheme -} from '../../shared/native-chat/native-chat-visual-shell' +} from '../../../shared/native-chat/native-chat-visual-shell' export const nativeChatApi = { // Acknowledge the in-memory snapshot before guest creation can start its preload. diff --git a/src/preload/api/notification-sound-playback.test.ts b/src/preload/api/notification-sound-playback.test.ts deleted file mode 100644 index 0507e2c639b..00000000000 --- a/src/preload/api/notification-sound-playback.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { notificationsApi } from './notifications-bridge' - -const SOUND_PATH = join(tmpdir(), 'notification.mp3') - -const { construct, invoke, play } = vi.hoisted(() => ({ - construct: vi.fn((audio: { currentTime: number; volume: number; pause: () => void }) => audio), - invoke: vi.fn(), - play: vi.fn(() => Promise.resolve()) -})) - -vi.mock('electron', () => ({ ipcRenderer: { invoke } })) - -async function loadNotificationsApi(): Promise { - vi.resetModules() - return (await import('./notifications-bridge')).notificationsApi -} - -describe('notificationsApi.playSound', () => { - beforeEach(() => { - construct.mockClear() - play.mockClear() - vi.stubGlobal( - 'Audio', - class extends EventTarget { - currentTime = 0 - volume = 1 - src = '' - pause = vi.fn() - play = play - - constructor() { - super() - construct(this) - } - } - ) - invoke.mockReset() - invoke.mockImplementation((channel: string) => { - if (channel === 'notifications:resolveSoundPath') { - return Promise.resolve({ ok: true, path: SOUND_PATH }) - } - if (channel === 'notifications:loadSound') { - return Promise.resolve({ - ok: true, - data: new Uint8Array([1]), - mimeType: 'audio/mpeg', - path: SOUND_PATH - }) - } - return Promise.resolve(undefined) - }) - }) - - afterEach(() => vi.unstubAllGlobals()) - - it('replays the cached sound for each notification instead of deduping mid-playback', async () => { - const notificationsApi = await loadNotificationsApi() - - await expect(notificationsApi.playSound()).resolves.toEqual({ played: true }) - const audio = construct.mock.calls[0]?.[0] - if (!audio) { - throw new Error('Audio was not constructed') - } - audio.currentTime = 0.75 - await expect(notificationsApi.playSound()).resolves.toEqual({ played: true }) - - expect(audio.currentTime).toBe(0) - expect(construct).toHaveBeenCalledOnce() - expect(play).toHaveBeenCalledTimes(2) - }) - - it('retries after a rejected play without leaving future notifications silent', async () => { - const notificationsApi = await loadNotificationsApi() - play.mockRejectedValueOnce(new Error('audio device unavailable')) - await expect(notificationsApi.playSound()).resolves.toEqual({ - played: false, - reason: 'playback-failed' - }) - await expect(notificationsApi.playSound()).resolves.toEqual({ played: true }) - expect(construct).toHaveBeenCalledOnce() - }) - - it('clamps volume and stays silent when no sound is configured', async () => { - const notificationsApi = await loadNotificationsApi() - await notificationsApi.playSound({ volume: 150 }) - const audio = construct.mock.calls[0]?.[0] - if (!audio) { - throw new Error('Audio was not constructed') - } - expect(audio.volume).toBe(1) - await notificationsApi.playSound({ volume: -10 }) - expect(audio.volume).toBe(0) - invoke.mockResolvedValueOnce({ ok: false, reason: 'missing-path' }) - await expect(notificationsApi.playSound()).resolves.toEqual({ - played: false, - reason: 'missing-path' - }) - expect(audio.pause).toHaveBeenCalledOnce() - expect(play).toHaveBeenCalledTimes(2) - }) - - it('shares one cached Audio across concurrent first playback', async () => { - const notificationsApi = await loadNotificationsApi() - - await expect( - Promise.all([notificationsApi.playSound(), notificationsApi.playSound()]) - ).resolves.toEqual([{ played: true }, { played: true }]) - - expect(construct).toHaveBeenCalledOnce() - expect(play).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/preload/api/notifications/notification-sound-playback.test.ts b/src/preload/api/notifications/notification-sound-playback.test.ts new file mode 100644 index 00000000000..a512929250e --- /dev/null +++ b/src/preload/api/notifications/notification-sound-playback.test.ts @@ -0,0 +1,61 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { notificationsApi } from './notifications-bridge' + +const SOUND_PATH = join(tmpdir(), 'notification.mp3') + +const { invoke, play } = vi.hoisted(() => ({ + invoke: vi.fn(), + play: vi.fn(() => Promise.resolve()) +})) + +vi.mock('electron', () => ({ ipcRenderer: { invoke } })) + +async function loadNotificationsApi(): Promise { + vi.resetModules() + return (await import('./notifications-bridge')).notificationsApi +} + +describe('notificationsApi.playSound', () => { + beforeEach(() => { + play.mockClear() + vi.stubGlobal( + 'Audio', + class extends EventTarget { + currentTime = 0 + volume = 1 + src = '' + pause = vi.fn() + play = play + } + ) + invoke.mockReset() + invoke.mockImplementation((channel: string) => { + if (channel === 'notifications:resolveSoundPath') { + return Promise.resolve({ ok: true, path: SOUND_PATH }) + } + if (channel === 'notifications:loadSound') { + return Promise.resolve({ + ok: true, + data: new Uint8Array([1]), + mimeType: 'audio/mpeg', + path: SOUND_PATH + }) + } + return Promise.resolve(undefined) + }) + }) + + afterEach(() => vi.unstubAllGlobals()) + + it('retries after a rejected play without leaving future notifications silent', async () => { + const notificationsApi = await loadNotificationsApi() + play.mockRejectedValueOnce(new Error('audio device unavailable')) + await expect(notificationsApi.playSound()).resolves.toEqual({ + played: false, + reason: 'playback-failed' + }) + await expect(notificationsApi.playSound()).resolves.toEqual({ played: true }) + }) +}) diff --git a/src/preload/api/notifications-bridge.ts b/src/preload/api/notifications/notifications-bridge.ts similarity index 95% rename from src/preload/api/notifications-bridge.ts rename to src/preload/api/notifications/notifications-bridge.ts index 60c43717b38..f51da880dab 100644 --- a/src/preload/api/notifications-bridge.ts +++ b/src/preload/api/notifications/notifications-bridge.ts @@ -10,9 +10,9 @@ import type { NotificationSoundPathResult, NotificationSoundResult, StructuredNotificationRead -} from '../../shared/notification-settings-types' -import type { AgentSessionExecutionLocation } from '../../shared/agent-session/lifecycle/agent-session-record' -import type { PreloadApi } from '../api-types' +} from '../../../shared/notification-settings-types' +import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { PreloadApi } from '../../api-types' // Reuse sound data to avoid reading large files for every notification. let cachedNotificationSound: { diff --git a/src/preload/api/onboarding-bridge.ts b/src/preload/api/onboarding-bridge.ts deleted file mode 100644 index 5efd171b512..00000000000 --- a/src/preload/api/onboarding-bridge.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { ChatUiLaunchTipVariant } from '../../shared/native-chat/chat-ui-launch-tip-audience' -import type { OnboardingState } from '../../shared/onboarding-state-types' -import type { PreloadApi } from '../api-types' - -export const onboardingApi = { - get: (): Promise => ipcRenderer.invoke('onboarding:get'), - update: ( - updates: Partial> & { - checklist?: Partial - } - ): Promise => ipcRenderer.invoke('onboarding:update', updates), - getChatUiLaunchTipVariant: (): Promise => - ipcRenderer.invoke('onboarding:getChatUiLaunchTipVariant') -} satisfies PreloadApi['onboarding'] diff --git a/src/preload/api/onboarding-api.ts b/src/preload/api/onboarding/onboarding-api.ts similarity index 85% rename from src/preload/api/onboarding-api.ts rename to src/preload/api/onboarding/onboarding-api.ts index 2e1e67a694f..36eb0d7be5a 100644 --- a/src/preload/api/onboarding-api.ts +++ b/src/preload/api/onboarding/onboarding-api.ts @@ -1,5 +1,5 @@ -import type { ChatUiLaunchTipVariant } from '../../shared/native-chat/chat-ui-launch-tip-audience' -import type { OnboardingState } from '../../shared/onboarding-state-types' +import type { ChatUiLaunchTipVariant } from '../../../shared/native-chat/chat-ui-launch-tip-audience' +import type { OnboardingState } from '../../../shared/onboarding-state-types' export type OnboardingApi = { get: () => Promise diff --git a/src/preload/api/onboarding/onboarding-bridge.ts b/src/preload/api/onboarding/onboarding-bridge.ts new file mode 100644 index 00000000000..6e4c25f0dcf --- /dev/null +++ b/src/preload/api/onboarding/onboarding-bridge.ts @@ -0,0 +1,15 @@ +import { ipcRenderer } from 'electron' +import type { ChatUiLaunchTipVariant } from '../../../shared/native-chat/chat-ui-launch-tip-audience' +import type { OnboardingState } from '../../../shared/onboarding-state-types' +import type { PreloadApi } from '../../api-types' + +export const onboardingApi = { + get: (): Promise => ipcRenderer.invoke('onboarding:get'), + update: ( + updates: Partial> & { + checklist?: Partial + } + ): Promise => ipcRenderer.invoke('onboarding:update', updates), + getChatUiLaunchTipVariant: (): Promise => + ipcRenderer.invoke('onboarding:getChatUiLaunchTipVariant') +} satisfies PreloadApi['onboarding'] diff --git a/src/preload/api/star-nag-bridge.ts b/src/preload/api/onboarding/star-nag-bridge.ts similarity index 96% rename from src/preload/api/star-nag-bridge.ts rename to src/preload/api/onboarding/star-nag-bridge.ts index 49e56e4aa91..f63fd1f141d 100644 --- a/src/preload/api/star-nag-bridge.ts +++ b/src/preload/api/onboarding/star-nag-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const starNagApi = { onShow: ( diff --git a/src/preload/api/open-code-usage-bridge.ts b/src/preload/api/open-code-usage-bridge.ts deleted file mode 100644 index 8b583be211d..00000000000 --- a/src/preload/api/open-code-usage-bridge.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' -import type { PreloadApi } from '../api-types' - -export const openCodeUsageApi = createUsageProviderApi( - backendUsageTransport, - 'openCodeUsage' -) satisfies PreloadApi['openCodeUsage'] diff --git a/src/preload/api/pet-api.ts b/src/preload/api/pet-api.ts deleted file mode 100644 index ebb6937b43a..00000000000 --- a/src/preload/api/pet-api.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { CustomPet } from '../../shared/pet-types' -import type { PetImportFailure } from '../../shared/pet-import-failure-copy' - -export type PetApi = { - import: () => Promise - importPetBundle: () => Promise - read: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise - delete: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise -} diff --git a/src/preload/api/pets/pet-api.ts b/src/preload/api/pets/pet-api.ts new file mode 100644 index 00000000000..79052d60cc8 --- /dev/null +++ b/src/preload/api/pets/pet-api.ts @@ -0,0 +1,9 @@ +import type { CustomPet } from '../../../shared/pet-types' +import type { PetImportFailure } from '../../../shared/pet-import-failure-copy' + +export type PetApi = { + import: () => Promise + importPetBundle: () => Promise + read: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise + delete: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise +} diff --git a/src/preload/api/pet-bridge.ts b/src/preload/api/pets/pet-bridge.ts similarity index 76% rename from src/preload/api/pet-bridge.ts rename to src/preload/api/pets/pet-bridge.ts index e957f0b1535..7cbfc2a9d1c 100644 --- a/src/preload/api/pet-bridge.ts +++ b/src/preload/api/pets/pet-bridge.ts @@ -1,7 +1,7 @@ import { ipcRenderer } from 'electron' -import type { CustomPet } from '../../shared/pet-types' -import type { PetImportFailure } from '../../shared/pet-import-failure-copy' -import type { PreloadApi } from '../api-types' +import type { CustomPet } from '../../../shared/pet-types' +import type { PetImportFailure } from '../../../shared/pet-import-failure-copy' +import type { PreloadApi } from '../../api-types' export const petApi = { import: (): Promise => ipcRenderer.invoke('pet:import'), diff --git a/src/preload/api/platform-bridge.test.ts b/src/preload/api/platform-bridge.test.ts deleted file mode 100644 index 1e67947d77c..00000000000 --- a/src/preload/api/platform-bridge.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { platformApi } from './platform-bridge' - -const mocks = vi.hoisted(() => ({ getLinuxDisplayServer: vi.fn(() => null) })) - -vi.mock('../preload-runtime-support', () => ({ - getLinuxDisplayServer: mocks.getLinuxDisplayServer -})) - -// Electron declares getSystemVersion as required on NodeJS.Process; Node does not have it. -const mutableProcess = process as unknown as { getSystemVersion?: () => string } - -async function loadPlatformApi(): Promise { - vi.resetModules() - return (await import('./platform-bridge')).platformApi -} - -describe('platformApi.get', () => { - beforeEach(() => { - mocks.getLinuxDisplayServer.mockClear() - }) - - afterEach(() => { - delete mutableProcess.getSystemVersion - }) - - it('resolves the immutable payload once and returns the identical object', async () => { - const platformApi = await loadPlatformApi() - const getSystemVersion = vi.fn(() => '25.3.0') - mutableProcess.getSystemVersion = getSystemVersion - - const first = platformApi.get() - expect(platformApi.get()).toBe(first) - expect(Object.isFrozen(first)).toBe(true) - - expect(getSystemVersion).toHaveBeenCalledTimes(1) - expect(mocks.getLinuxDisplayServer).toHaveBeenCalledTimes(1) - expect(first.platform).toBe(process.platform) - expect(first.arch).toBe(process.arch) - expect(first.osRelease).toBe('25.3.0') - }) - - it('resolves nothing before the first get, keeping preload startup free', async () => { - await loadPlatformApi() - - expect(mocks.getLinuxDisplayServer).not.toHaveBeenCalled() - }) -}) diff --git a/src/preload/api/platform-bridge.ts b/src/preload/api/platform-bridge.ts index 6ea1102f598..534cd0d80cc 100644 --- a/src/preload/api/platform-bridge.ts +++ b/src/preload/api/platform-bridge.ts @@ -1,4 +1,4 @@ -import { getLinuxDisplayServer } from '../preload-runtime-support' +import { getLinuxDisplayServer } from '../renderer/renderer-runtime' import { parseWindowMaterialArgument } from '../../shared/window-material' import type { PreloadApi } from '../api-types' diff --git a/src/preload/api/plugin-host-api.ts b/src/preload/api/plugins/plugin-host-api.ts similarity index 82% rename from src/preload/api/plugin-host-api.ts rename to src/preload/api/plugins/plugin-host-api.ts index 1767792f4ec..9b52cc6e9f0 100644 --- a/src/preload/api/plugin-host-api.ts +++ b/src/preload/api/plugins/plugin-host-api.ts @@ -1,55 +1,48 @@ -import type { PluginHostImages } from '../../shared/plugins/images/plugin-image-url' -import type { EditorSaveHookDecision } from '../../shared/plugins/events/plugin-editor-save-hook' -import type { PluginUpdateAccessGrowth } from '../../shared/plugins/approval/plugin-update-access-growth' +import type { PluginHostImages } from '../../../shared/plugins/images/plugin-image-url' +import type { EditorSaveHookDecision } from '../../../shared/plugins/events/plugin-editor-save-hook' +import type { PluginUpdateAccessGrowth } from '../../../shared/plugins/approval/plugin-update-access-growth' import type { PluginAutoUpdateState, PluginUpdateReviewNotice -} from '../../shared/plugins/catalog/plugin-update-policy' +} from '../../../shared/plugins/catalog/plugin-update-policy' import type { PluginIconThemeMetadata, PluginIconThemeRegistration -} from '../../shared/plugins/artifacts/plugin-icon-theme-artifact' -import type { PluginThemeRegistration } from '../../shared/plugins/artifacts/plugin-theme-artifact' +} from '../../../shared/plugins/artifacts/plugin-icon-theme-artifact' +import type { PluginThemeRegistration } from '../../../shared/plugins/artifacts/plugin-theme-artifact' import type { PluginSyntaxMetadata, PluginSyntaxPayload -} from '../../shared/plugins/artifacts/plugin-syntax-artifact' -import type { PluginTerminalThemeRegistration } from '../../shared/plugins/artifacts/plugin-terminal-theme-artifact' +} from '../../../shared/plugins/artifacts/plugin-syntax-artifact' +import type { PluginTerminalThemeRegistration } from '../../../shared/plugins/artifacts/plugin-terminal-theme-artifact' import type { PluginFrameEntry, PluginFrameTheme -} from '../../shared/plugins/frames/plugin-frame-bridge' -import type { PluginHostCallOutcome } from '../../shared/plugins/frames/plugin-protocol' +} from '../../../shared/plugins/frames/plugin-frame-bridge' +import type { PluginHostCallOutcome } from '../../../shared/plugins/frames/plugin-protocol' import type { PluginPanelStateRequest, PluginPanelStateResult -} from '../../shared/plugins/declarative/plugin-declarative-panel-state' -import type { PluginConsentRequest } from '../../shared/plugins/approval/plugin-consent-request' -import type { PluginLanguagePackRegistration } from '../../shared/plugins/artifacts/plugin-language-pack-artifact' -import type { PluginChangeEvent } from '../../shared/plugins/events/plugin-change-event' +} from '../../../shared/plugins/declarative/plugin-declarative-panel-state' +import type { PluginConsentRequest } from '../../../shared/plugins/approval/plugin-consent-request' +import type { PluginLanguagePackRegistration } from '../../../shared/plugins/artifacts/plugin-language-pack-artifact' +import type { PluginChangeEvent } from '../../../shared/plugins/events/plugin-change-event' import type { PluginViewReply, PluginViewRequest -} from '../../shared/plugins/view/plugin-view-protocol' -import type { PluginManifest } from '../../shared/plugins/manifest/plugin-manifest' +} from '../../../shared/plugins/view/plugin-view-protocol' +import type { PluginManifest } from '../../../shared/plugins/manifest/plugin-manifest' import type { PluginCatalogGitSource, PluginMarketplaceGitSource -} from '../../shared/plugins/catalog/plugin-marketplace' -import type { PluginCatalogRelease } from '../../shared/plugins/catalog/plugin-catalog-release' -import type { PluginGitSourceResolution } from '../../shared/plugins/installation/plugin-git-resolution' +} from '../../../shared/plugins/catalog/plugin-marketplace' +import type { PluginCatalogRelease } from '../../../shared/plugins/catalog/plugin-catalog-release' +import type { PluginGitSourceResolution } from '../../../shared/plugins/installation/plugin-git-resolution' -export type { - PluginHostCustomEditor, - PluginHostListEntry, - PluginHostNewFile, - PluginHostPanel, - PluginHostStatus -} from '../../shared/plugins/plugin-list-entry' -import type { PluginHostListEntry } from '../../shared/plugins/plugin-list-entry' -import type { PluginStatusBarOverrides } from '../../shared/plugins/contributions/plugin-status-bar-state' -import type { PluginDeclaredSettingsSnapshot } from '../../shared/plugins/contributions/plugin-settings-values' -import type { PluginJsonValue } from '../../shared/plugins/workers/plugin-host-api' +import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry' +import type { PluginStatusBarOverrides } from '../../../shared/plugins/contributions/plugin-status-bar-state' +import type { PluginDeclaredSettingsSnapshot } from '../../../shared/plugins/contributions/plugin-settings-values' +import type { PluginJsonValue } from '../../../shared/plugins/workers/plugin-host-api-storage-schemas' export type PluginHostLogLine = { ts: number @@ -102,6 +95,9 @@ export type PluginMarketplaceHostListing = { official: boolean bundled: boolean blockedByKillList?: { reason: string; advisoryUrl?: string } + /** Estimated listing date (ISO 8601): a community plugin's oldest dated release. Absent for + * official plugins and undated releases. */ + addedAt?: string /** The release record a v2 catalog vouches for; absent for v1 catalogs. */ release?: PluginCatalogRelease /** The offered release's images, verified and cached by main; never hotlinked. */ diff --git a/src/preload/api/plugin-panel-push-bridge.ts b/src/preload/api/plugins/plugin-panel-push-bridge.ts similarity index 100% rename from src/preload/api/plugin-panel-push-bridge.ts rename to src/preload/api/plugins/plugin-panel-push-bridge.ts diff --git a/src/preload/api/plugins-bridge.ts b/src/preload/api/plugins/plugins-bridge.ts similarity index 90% rename from src/preload/api/plugins-bridge.ts rename to src/preload/api/plugins/plugins-bridge.ts index 348cbab6e6d..4202674847f 100644 --- a/src/preload/api/plugins-bridge.ts +++ b/src/preload/api/plugins/plugins-bridge.ts @@ -3,27 +3,27 @@ import { subscribePluginPanelPush } from './plugin-panel-push-bridge' import type { PluginFrameEntry, PluginFrameTheme -} from '../../shared/plugins/frames/plugin-frame-bridge' -import type { PluginHostCallOutcome } from '../../shared/plugins/frames/plugin-protocol' -import type { PluginConsentRequest } from '../../shared/plugins/approval/plugin-consent-request' -import type { PluginChangeEvent } from '../../shared/plugins/events/plugin-change-event' +} from '../../../shared/plugins/frames/plugin-frame-bridge' +import type { PluginHostCallOutcome } from '../../../shared/plugins/frames/plugin-protocol' +import type { PluginConsentRequest } from '../../../shared/plugins/approval/plugin-consent-request' +import type { PluginChangeEvent } from '../../../shared/plugins/events/plugin-change-event' import { PLUGIN_STATUS_BAR_CHANGED_CHANNEL, type PluginStatusBarOverrides -} from '../../shared/plugins/contributions/plugin-status-bar-state' +} from '../../../shared/plugins/contributions/plugin-status-bar-state' import { PLUGIN_VIEW_REPLY_CHANNEL, PLUGIN_VIEW_REQUEST_CHANNEL, type PluginViewRequest -} from '../../shared/plugins/view/plugin-view-protocol' +} from '../../../shared/plugins/view/plugin-view-protocol' import type { PluginAutoUpdateEvent, PluginHostInstallResult, PluginHostInstallSource, - PluginHostListEntry, - PluginHostLogLine, - PreloadApi -} from '../api-types' + PluginHostLogLine +} from './plugin-host-api' +import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry' +import type { PreloadApi } from '../../api-types' export const pluginsApi = { list: (): Promise => ipcRenderer.invoke('plugins:list'), diff --git a/src/preload/api/keybindings-bridge.ts b/src/preload/api/preferences/keybindings-bridge.ts similarity index 93% rename from src/preload/api/keybindings-bridge.ts rename to src/preload/api/preferences/keybindings-bridge.ts index e91e587313d..595bd240f7a 100644 --- a/src/preload/api/keybindings-bridge.ts +++ b/src/preload/api/preferences/keybindings-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { KeybindingActionId, KeybindingFileSnapshot } from '../../shared/keybindings' -import type { PreloadApi } from '../api-types' +import type { KeybindingActionId, KeybindingFileSnapshot } from '../../../shared/keybindings/types' +import type { PreloadApi } from '../../api-types' export const keybindingsApi = { get: (): Promise => ipcRenderer.invoke('keybindings:get'), diff --git a/src/preload/api/settings-api.ts b/src/preload/api/preferences/settings-api.ts similarity index 86% rename from src/preload/api/settings-api.ts rename to src/preload/api/preferences/settings-api.ts index 507a434dbfa..861182dd2e0 100644 --- a/src/preload/api/settings-api.ts +++ b/src/preload/api/preferences/settings-api.ts @@ -1,13 +1,13 @@ -import type { KeybindingActionId, KeybindingFileSnapshot } from '../../shared/keybindings' +import type { KeybindingActionId, KeybindingFileSnapshot } from '../../../shared/keybindings/types' import type { WarpThemeImportPreview, WarpThemeImportSource -} from '../../shared/terminal-themes/terminal-custom-themes' -import type { GlobalSettings } from '../../shared/global-settings-types' +} from '../../../shared/terminal-themes/terminal-custom-themes' +import type { GlobalSettings } from '../../../shared/global-settings-types' import type { TerminalConfigImportPreview, TerminalConfigImportSource -} from '../../shared/terminal/appearance/terminal-config-import-preview' +} from '../../../shared/terminal/appearance/terminal-config-import-preview' export type SettingsApi = { get: () => Promise diff --git a/src/preload/api/settings-bridge.ts b/src/preload/api/preferences/settings-bridge.ts similarity index 89% rename from src/preload/api/settings-bridge.ts rename to src/preload/api/preferences/settings-bridge.ts index fc66f89a0e1..a1abc25a3f3 100644 --- a/src/preload/api/settings-bridge.ts +++ b/src/preload/api/preferences/settings-bridge.ts @@ -2,12 +2,12 @@ import { ipcRenderer } from 'electron' import type { TerminalConfigImportPreview, TerminalConfigImportSource -} from '../../shared/terminal/appearance/terminal-config-import-preview' +} from '../../../shared/terminal/appearance/terminal-config-import-preview' import type { WarpThemeImportPreview, WarpThemeImportSource -} from '../../shared/terminal-themes/terminal-custom-themes' -import type { PreloadApi } from '../api-types' +} from '../../../shared/terminal-themes/terminal-custom-themes' +import type { PreloadApi } from '../../api-types' export const settingsApi = { get: () => ipcRenderer.invoke('settings:get'), diff --git a/src/preload/api/preflight-api.ts b/src/preload/api/preflight/preflight-api.ts similarity index 89% rename from src/preload/api/preflight-api.ts rename to src/preload/api/preflight/preflight-api.ts index 829da72a536..1a302473560 100644 --- a/src/preload/api/preflight-api.ts +++ b/src/preload/api/preflight/preflight-api.ts @@ -1,9 +1,9 @@ -import type { ZCodeInteractiveCapability } from '../../shared/zcode-missing-tui' -import type { ProjectExecutionRuntimeResolution } from '../../shared/execution-host/project-execution-runtime' +import type { ZCodeInteractiveCapability } from '../../../shared/zcode-missing-tui' +import type { ProjectExecutionRuntimeResolution } from '../../../shared/execution-host/project-execution-runtime' import type { PathSource, ShellHydrationFailureReason -} from '../../shared/shell/launch/shell-path-hydration-types' +} from '../../../shared/shell/launch/shell-path-hydration-types' export type PreflightStatus = { git: { installed: boolean } diff --git a/src/preload/api/preflight-bridge.ts b/src/preload/api/preflight/preflight-bridge.ts similarity index 90% rename from src/preload/api/preflight-bridge.ts rename to src/preload/api/preflight/preflight-bridge.ts index ca0f030c155..da0c45ad7a6 100644 --- a/src/preload/api/preflight-bridge.ts +++ b/src/preload/api/preflight/preflight-bridge.ts @@ -1,6 +1,7 @@ import { ipcRenderer } from 'electron' -import type { PreflightRuntimeContext, PreloadApi, RefreshAgentsResult } from '../api-types' -import type { ZCodeInteractiveCapability } from '../../shared/zcode-missing-tui' +import type { PreflightRuntimeContext, RefreshAgentsResult } from './preflight-api' +import type { PreloadApi } from '../../api-types' +import type { ZCodeInteractiveCapability } from '../../../shared/zcode-missing-tui' export const preflightApi = { check: (args?: { diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/profiles/orca-profile-api.ts similarity index 98% rename from src/preload/api/orca-profile-api.ts rename to src/preload/api/profiles/orca-profile-api.ts index 8fe63dd6375..21c5f4262e8 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/profiles/orca-profile-api.ts @@ -24,7 +24,7 @@ import type { SwitchOrcaProfileResult, TransferOrcaProfileProjectArgs, TransferOrcaProfileProjectResult -} from '../../shared/orca-profiles' +} from '../../../shared/orca-profiles' export type OrcaProfileApi = { list: () => Promise diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/profiles/orca-profiles-bridge.ts similarity index 92% rename from src/preload/api/orca-profiles-bridge.ts rename to src/preload/api/profiles/orca-profiles-bridge.ts index f144c9d7697..0a005e384c3 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/profiles/orca-profiles-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, @@ -7,9 +7,9 @@ import { type OrcaProfileListResult, type SwitchOrcaProfileResult, type TransferOrcaProfileProjectResult -} from '../../shared/orca-profiles' -import { prepareAndInvokeAppRestart } from '../renderer-restart-wiring' -import { awaitBeforeUnloadCheckpoint } from '../preload-runtime-support' +} from '../../../shared/orca-profiles' +import { prepareAndInvokeAppRestart } from '../../renderer/restart/renderer-restart-wiring' +import { awaitBeforeUnloadCheckpoint } from '../../renderer/renderer-runtime' export const orcaProfilesApi = { list: () => ipcRenderer.invoke('orcaProfiles:list'), diff --git a/src/preload/api/project-groups-bridge.ts b/src/preload/api/projects/project-groups-bridge.ts similarity index 89% rename from src/preload/api/project-groups-bridge.ts rename to src/preload/api/projects/project-groups-bridge.ts index b7748aca427..006b3f17d72 100644 --- a/src/preload/api/project-groups-bridge.ts +++ b/src/preload/api/projects/project-groups-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { NestedRepoScanResult } from '../../shared/project-group-types' -import type { PreloadApi } from '../api-types' +import type { NestedRepoScanResult } from '../../../shared/project-group-types' +import type { PreloadApi } from '../../api-types' export const projectGroupsApi = { list: () => ipcRenderer.invoke('projectGroups:list'), diff --git a/src/preload/api/projects-bridge.ts b/src/preload/api/projects/projects-bridge.ts similarity index 92% rename from src/preload/api/projects-bridge.ts rename to src/preload/api/projects/projects-bridge.ts index c8114fbdf4a..b7749ea226e 100644 --- a/src/preload/api/projects-bridge.ts +++ b/src/preload/api/projects/projects-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const projectsApi = { list: () => ipcRenderer.invoke('projects:list'), diff --git a/src/preload/api/repos-bridge.ts b/src/preload/api/projects/repos-bridge.ts similarity index 94% rename from src/preload/api/repos-bridge.ts rename to src/preload/api/projects/repos-bridge.ts index af5c8549aa7..b37a526107d 100644 --- a/src/preload/api/repos-bridge.ts +++ b/src/preload/api/projects/repos-bridge.ts @@ -1,7 +1,7 @@ import { ipcRenderer } from 'electron' -import type { BaseRefDefaultResult, BaseRefSearchResult } from '../../shared/repo-types' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { PreloadApi } from '../api-types' +import type { BaseRefDefaultResult, BaseRefSearchResult } from '../../../shared/repo-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { PreloadApi } from '../../api-types' export const reposApi = { list: () => ipcRenderer.invoke('repos:list'), diff --git a/src/preload/api/repository-api.ts b/src/preload/api/projects/repository-api.ts similarity index 88% rename from src/preload/api/repository-api.ts rename to src/preload/api/projects/repository-api.ts index 16c91ac61d3..6e0bdfca26d 100644 --- a/src/preload/api/repository-api.ts +++ b/src/preload/api/projects/repository-api.ts @@ -1,7 +1,10 @@ -import type { RepoCreateFailure } from '../../shared/repo-create-failure-copy' -import type { CloneTargetArgs, CloneTargetCheck } from '../../shared/git/clone/clone-target-check' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { GhAccountBinding } from '../../shared/github/account-binding' +import type { RepoCreateFailure } from '../../../shared/repo-create-failure-copy' +import type { + CloneTargetArgs, + CloneTargetCheck +} from '../../../shared/git/clone/clone-target-check' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding' import type { NestedRepoScanResult, ProjectGroup, @@ -9,7 +12,7 @@ import type { ProjectGroupMutation, ProjectGroupImportMode, ProjectGroupImportResult -} from '../../shared/project-group-types' +} from '../../../shared/project-group-types' import type { Project, ProjectHostSetup, @@ -22,10 +25,10 @@ import type { ProjectHostSetupUpdateArgs, ProjectHostSetupUpdateResult, ProjectUpdateArgs -} from '../../shared/project-types' -import type { BaseRefDefaultResult, BaseRefSearchResult, Repo } from '../../shared/repo-types' -import type { WslMovedProject } from '../../shared/wsl-move/wsl-moved-project' -import type { HostRepoCatalogSnapshot } from '../../shared/host-repo-catalog-snapshot' +} from '../../../shared/project-types' +import type { BaseRefDefaultResult, BaseRefSearchResult, Repo } from '../../../shared/repo-types' +import type { WslMovedProject } from '../../../shared/wsl-move/wsl-moved-project' +import type { HostRepoCatalogSnapshot } from '../../../shared/host-repo-catalog-snapshot' export type RepositoryApi = { list: () => Promise @@ -76,6 +79,7 @@ export type RepositoryApi = { agentWorktreeVisibility?: Repo['agentWorktreeVisibility'] | null sourceControlAi?: Repo['sourceControlAi'] | null externalWorktreeDiscoverySuppressedAt?: Repo['externalWorktreeDiscoverySuppressedAt'] | null + hiddenAt?: Repo['hiddenAt'] | null ghAccount?: GhAccountBinding | null } }) => Promise diff --git a/src/preload/api/managed-orcad-api.ts b/src/preload/api/runtime/managed-orcad-api.ts similarity index 95% rename from src/preload/api/managed-orcad-api.ts rename to src/preload/api/runtime/managed-orcad-api.ts index 6cd260f6bf1..06a25b53738 100644 --- a/src/preload/api/managed-orcad-api.ts +++ b/src/preload/api/runtime/managed-orcad-api.ts @@ -16,12 +16,12 @@ import type { OrcadManagedRollbackResult, OrcadManagedRuntimeStatus, OrcadManagedStopResult -} from '../../shared/orcad-managed-runtime' -import type { PublicKnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../shared/orcad-managed-runtime' +import type { PublicKnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import type { RuntimeSshAccessLinkRequest, RuntimeSshAccessUnlinkRequest -} from '../../shared/runtime-ssh-access' +} from '../../../shared/runtime-ssh-access' export type ManagedOrcadPreloadApi = { deploy: (args: { diff --git a/src/preload/api/runtime-api.ts b/src/preload/api/runtime/runtime-api.ts similarity index 86% rename from src/preload/api/runtime-api.ts rename to src/preload/api/runtime/runtime-api.ts index cd257b576ef..4fe42605caf 100644 --- a/src/preload/api/runtime-api.ts +++ b/src/preload/api/runtime/runtime-api.ts @@ -2,32 +2,30 @@ import type { CrewSubscriptionAttemptArgs, CrewSubscriptionAttemptCallbacks, CrewSubscriptionSetupResult -} from '../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +} from '../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' import type { ManagedOrcadPreloadApi } from './managed-orcad-api' -import type { WslHostsPreloadApi } from './wsl-hosts-api' -import type { RuntimeHostStatusSnapshot } from '../../shared/remote-runtime/host-status/runtime-host-status' +import type { WslHostsPreloadApi } from '../wsl/wsl-hosts-api' +import type { RuntimeHostStatusSnapshot } from '../../../shared/remote-runtime/host-status/runtime-host-status' import type { RuntimeRendererSyncWindowGraph, - RuntimeSyncWindowGraphResult -} from '../../shared/runtime-types' -import type { + RuntimeSyncWindowGraphResult, RuntimeStatus, RuntimeTerminalDriverState -} from '../../shared/runtime-session-contracts' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import type { ClientHostedBrowserRowsEvent } from '../../shared/client-hosted-browser-rows' -import type { SidebarInputsChangedEvent } from '../../shared/sidebar-list/sidebar-inputs-feed-contract' +} from '../../../shared/runtime-session-contracts' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { ClientHostedBrowserRowsEvent } from '../../../shared/client-hosted-browser-rows' +import type { SidebarInputsChangedEvent } from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' import type { PublicKnownRuntimeEnvironment, RuntimeEnvironmentRemoval -} from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { VerifyAndAddRuntimeEnvironmentResult } from '../../shared/remote-runtime/pairing/remote-pairing-verification' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { VerifyAndAddRuntimeEnvironmentResult } from '../../../shared/remote-runtime/pairing/remote-pairing-verification' import type { BrowserClientHostPlacementPreparationRequest, BrowserPageCreationPlacement -} from '../../shared/browser/client-hosting/browser-client-host-placement' -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../shared/remote-runtime/control/remote-runtime-shared-control-types' -import type { WslOrcadAccountNotAppliedEvent } from '../../shared/wsl-orcad-account-notice' +} from '../../../shared/browser/client-hosting/browser-client-host-placement' +import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' +import type { WslOrcadAccountNotAppliedEvent } from '../../../shared/wsl-orcad-account-notice' export type RuntimeEnvironmentSubscriptionHandle = { unsubscribe: () => void diff --git a/src/preload/api/runtime-bridge.ts b/src/preload/api/runtime/runtime-bridge.ts similarity index 91% rename from src/preload/api/runtime-bridge.ts rename to src/preload/api/runtime/runtime-bridge.ts index eaf6c4e7eff..05a122c4fc0 100644 --- a/src/preload/api/runtime-bridge.ts +++ b/src/preload/api/runtime/runtime-bridge.ts @@ -1,15 +1,15 @@ import { ipcRenderer } from 'electron' -import type { ClientHostedBrowserRowsEvent } from '../../shared/client-hosted-browser-rows' -import type { SidebarInputsChangedEvent } from '../../shared/sidebar-list/sidebar-inputs-feed-contract' +import type { ClientHostedBrowserRowsEvent } from '../../../shared/client-hosted-browser-rows' +import type { SidebarInputsChangedEvent } from '../../../shared/sidebar-list/sidebar-inputs-feed-contract' import type { RuntimeRendererSyncWindowGraph, RuntimeStatus, - RuntimeSyncWindowGraphResult -} from '../../shared/runtime-types' -import type { RuntimeTerminalDriverState } from '../../shared/runtime-session-contracts' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import type { RuntimeEnvironmentSubscriptionHandle } from '../runtime-environment-subscriptions' -import type { PreloadApi } from '../api-types' + RuntimeSyncWindowGraphResult, + RuntimeTerminalDriverState +} from '../../../shared/runtime-session-contracts' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { RuntimeEnvironmentSubscriptionHandle } from '../../runtime/runtime-environment-subscriptions' +import type { PreloadApi } from '../../api-types' export const runtimeApi = { syncWindowGraph: (graph: RuntimeRendererSyncWindowGraph): Promise => diff --git a/src/preload/api/runtime-environments-bridge.ts b/src/preload/api/runtime/runtime-environments-bridge.ts similarity index 87% rename from src/preload/api/runtime-environments-bridge.ts rename to src/preload/api/runtime/runtime-environments-bridge.ts index 715605b216f..685561dd6db 100644 --- a/src/preload/api/runtime-environments-bridge.ts +++ b/src/preload/api/runtime/runtime-environments-bridge.ts @@ -2,30 +2,30 @@ import { ipcRenderer } from 'electron' import { RUNTIME_HOST_STATUS_CHANNEL, type RuntimeHostStatusSnapshot -} from '../../shared/remote-runtime/host-status/runtime-host-status' -import type { VerifyAndAddRuntimeEnvironmentResult } from '../../shared/remote-runtime/pairing/remote-pairing-verification' -import type { RuntimeStatus } from '../../shared/runtime-session-contracts' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' +} from '../../../shared/remote-runtime/host-status/runtime-host-status' +import type { VerifyAndAddRuntimeEnvironmentResult } from '../../../shared/remote-runtime/pairing/remote-pairing-verification' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import type { PublicKnownRuntimeEnvironment, RuntimeEnvironmentRemoval -} from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../shared/remote-runtime/control/remote-runtime-shared-control-types' -import { RUNTIME_ENVIRONMENT_DIAGNOSTICS_CHANNEL } from '../../shared/remote-runtime/host-catalog/runtime-environment-diagnostics' -import { RUNTIME_ENVIRONMENT_CATALOG_CHANGED_CHANNEL } from '../../shared/remote-runtime/host-catalog/runtime-environment-catalog-channel' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-types' +import { RUNTIME_ENVIRONMENT_DIAGNOSTICS_CHANNEL } from '../../../shared/remote-runtime/host-catalog/runtime-environment-diagnostics' +import { RUNTIME_ENVIRONMENT_CATALOG_CHANGED_CHANNEL } from '../../../shared/remote-runtime/host-catalog/runtime-environment-catalog-channel' import { WSL_ORCAD_ACCOUNT_NOT_APPLIED_CHANNEL, type WslOrcadAccountNotAppliedEvent -} from '../../shared/wsl-orcad-account-notice' +} from '../../../shared/wsl-orcad-account-notice' import { subscribeRuntimeEnvironmentFromPreload, subscribeCrewAttemptFromPreload, cancelRuntimeEnvironmentSubscriptionFromPreload, type RuntimeEnvironmentSubscriptionHandle -} from '../runtime-environment-subscriptions' -import type { PreloadApi } from '../api-types' +} from '../../runtime/runtime-environment-subscriptions' +import type { PreloadApi } from '../../api-types' import { managedOrcadApi } from './managed-orcad-api' -import { getWslHostsApi } from './wsl-hosts-api' +import { getWslHostsApi } from '../wsl/wsl-hosts-api' export const runtimeEnvironmentsApi = { desktopCreatedChatIds: (): Promise => diff --git a/src/preload/api/session-bridge.ts b/src/preload/api/session-bridge.ts deleted file mode 100644 index 23f6aff19ec..00000000000 --- a/src/preload/api/session-bridge.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' - -export const sessionApi = { - get: (hostId) => ipcRenderer.invoke('session:get', hostId), - listHostIds: () => ipcRenderer.invoke('session:list-host-ids'), - set: (args, hostId) => ipcRenderer.invoke('session:set', args, hostId), - patch: (args, hostId) => ipcRenderer.invoke('session:patch', args, hostId), - closeTerminalSurface: (args) => ipcRenderer.invoke('session:close-terminal-surface', args), - flush: () => ipcRenderer.invoke('session:flush'), - readTerminalScrollback: (args) => - ipcRenderer.sendSync('session:read-terminal-scrollback-sync', args), - hasTerminalScrollback: (args) => - ipcRenderer.sendSync('session:has-terminal-scrollback-sync', args) -} satisfies PreloadApi['session'] diff --git a/src/preload/api/agent-skill-api.ts b/src/preload/api/skills/agent-skill-api.ts similarity index 94% rename from src/preload/api/agent-skill-api.ts rename to src/preload/api/skills/agent-skill-api.ts index def9240bd7d..03be1ca7a10 100644 --- a/src/preload/api/agent-skill-api.ts +++ b/src/preload/api/skills/agent-skill-api.ts @@ -1,9 +1,9 @@ -import type { SkillDiscoveryResult, SkillDiscoveryTarget } from '../../shared/skills' +import type { SkillDiscoveryResult, SkillDiscoveryTarget } from '../../../shared/skills' import type { SkillCloudOperation, SkillCloudOwnedShare, SkillCloudPackageDetails -} from '../../shared/skill-cloud-contract' +} from '../../../shared/skill-cloud-contract' import type { ManagedSkillInstallListOperation, SkillBundleInstallPreviewInput, @@ -25,20 +25,20 @@ import type { SkillSharePublishInput, SkillSharePublishOperation, SkillShareResolvedOperation -} from '../../shared/skill-sharing-contract' +} from '../../../shared/skill-sharing-contract' import type { BundledSkillAutoUpdateRequest, LocalBundledSkillExecuteRequest, BundledSkillInstallResult, BundledSkillPlan, LocalBundledSkillPlanRequest -} from '../../shared/bundled-skill-plan' +} from '../../../shared/bundled-skill-plan' import type { SkillDeletePlan, SkillDeleteRequest, SkillDeleteResult -} from '../../shared/skill-delete-contract' +} from '../../../shared/skill-delete-contract' export type SkillsApi = { discover: (target?: SkillDiscoveryTarget) => Promise diff --git a/src/preload/api/skills-bridge.ts b/src/preload/api/skills/skills-bridge.ts similarity index 95% rename from src/preload/api/skills-bridge.ts rename to src/preload/api/skills/skills-bridge.ts index a270f88da0a..54e73b82282 100644 --- a/src/preload/api/skills-bridge.ts +++ b/src/preload/api/skills/skills-bridge.ts @@ -3,13 +3,13 @@ import type { SkillDeletePlan, SkillDeleteRequest, SkillDeleteResult -} from '../../shared/skill-delete-contract' -import type { SkillDiscoveryResult, SkillDiscoveryTarget } from '../../shared/skills' +} from '../../../shared/skill-delete-contract' +import type { SkillDiscoveryResult, SkillDiscoveryTarget } from '../../../shared/skills' import type { SkillCloudOwnedShare, SkillCloudOperation, SkillCloudPackageDetails -} from '../../shared/skill-cloud-contract' +} from '../../../shared/skill-cloud-contract' import type { SkillBundleInstallPreviewInput, SkillBundleInstallPreviewOperation, @@ -31,15 +31,15 @@ import type { SkillSharePublishInput, SkillSharePublishOperation, SkillShareResolvedOperation -} from '../../shared/skill-sharing-contract' +} from '../../../shared/skill-sharing-contract' import type { BundledSkillAutoUpdateRequest, LocalBundledSkillExecuteRequest, BundledSkillInstallResult, BundledSkillPlan, LocalBundledSkillPlanRequest -} from '../../shared/bundled-skill-plan' -import type { PreloadApi } from '../api-types' +} from '../../../shared/bundled-skill-plan' +import type { PreloadApi } from '../../api-types' export const skillsApi = { discover: (target?: SkillDiscoveryTarget): Promise => diff --git a/src/preload/api/git-bridge.ts b/src/preload/api/source-control/git-bridge.ts similarity index 91% rename from src/preload/api/git-bridge.ts rename to src/preload/api/source-control/git-bridge.ts index 58607ebc9e1..f3cd0546596 100644 --- a/src/preload/api/git-bridge.ts +++ b/src/preload/api/source-control/git-bridge.ts @@ -1,22 +1,23 @@ import type { GitCommitAction, GitCommitActionResult -} from '../../shared/git/commands/git-commit-action' +} from '../../../shared/git/commands/git-commit-action' import { ipcRenderer } from 'electron' import type { GitForkSyncExpectedUpstream, GitForkSyncResult -} from '../../shared/git/remotes/git-fork-sync' -import type { GitStagingArea, GitUpstreamStatus } from '../../shared/git/status/git-status-types' -import type { ConflictResolution } from '../../shared/source-control/listing/source-control-entry-actions' -import type { GitPushTarget } from '../../shared/worktree/types' -import type { GitStageWorktreeScope } from '../../shared/git/paths/git-stage-worktree-scope' +} from '../../../shared/git/remotes/git-fork-sync' +import type { GitStagingArea, GitUpstreamStatus } from '../../../shared/git/status/git-status-types' +import type { ConflictResolution } from '../../../shared/source-control/listing/source-control-entry-actions' +import type { GitPushTarget } from '../../../shared/worktree/types' +import type { WorktreeAtRiskLocalFiles } from '../../../shared/worktree/removal/at-risk-local-files' +import type { GitStageWorktreeScope } from '../../../shared/git/paths/git-stage-worktree-scope' import type { GitHistoryItemRef, GitHistoryOptions, GitHistoryResult -} from '../../shared/git/history/git-history-types' -import type { PreloadApi } from '../api-types' +} from '../../../shared/git/history/git-history-types' +import type { PreloadApi } from '../../api-types' export const gitApi = { status: (args: { @@ -50,6 +51,10 @@ export const gitApi = { paths: string[] connectionId?: string }): Promise => ipcRenderer.invoke('git:checkIgnored', args), + atRiskLocalFiles: (args: { + worktreePath: string + connectionId?: string + }): Promise => ipcRenderer.invoke('git:atRiskLocalFiles', args), findHugeFoldersToIgnore: (args: { worktreePath: string }): Promise => ipcRenderer.invoke('git:findHugeFoldersToIgnore', args), appendGitignore: (args: { worktreePath: string; folderName: string }): Promise => diff --git a/src/preload/api/git-inspection-api.ts b/src/preload/api/source-control/git-inspection-api.ts similarity index 86% rename from src/preload/api/git-inspection-api.ts rename to src/preload/api/source-control/git-inspection-api.ts index 7fa8d767a28..32fefdd910b 100644 --- a/src/preload/api/git-inspection-api.ts +++ b/src/preload/api/source-control/git-inspection-api.ts @@ -2,24 +2,25 @@ import type { GitBranchCompareResult, GitCommitCompareResult, GitDiffResult -} from '../../shared/git/diff/git-diff-compare-types' -import type { GitMutationInFlight } from '../../shared/git/commands/git-mutation-in-flight' +} from '../../../shared/git/diff/git-diff-compare-types' +import type { GitMutationInFlight } from '../../../shared/git/commands/git-mutation-in-flight' import type { GitConflictOperation, GitStagingArea, GitStatusResult, GitUpstreamStatus -} from '../../shared/git/status/git-status-types' -import type { GitPushTarget } from '../../shared/worktree/types' +} from '../../../shared/git/status/git-status-types' +import type { GitPushTarget } from '../../../shared/worktree/types' +import type { WorktreeAtRiskLocalFiles } from '../../../shared/worktree/removal/at-risk-local-files' import type { GitHistoryItemRef, GitHistoryOptions, GitHistoryResult -} from '../../shared/git/history/git-history-types' +} from '../../../shared/git/history/git-history-types' import type { CommitMessageAgentCapability, CommitMessageModelCapability -} from '../../shared/source-control/ai/generation/commit-message-agent-spec' +} from '../../../shared/source-control/ai/generation/commit-message-agent-spec' export type GitInspectionApi = { status: (args: { @@ -56,6 +57,10 @@ export type GitInspectionApi = { paths: string[] connectionId?: string }) => Promise + atRiskLocalFiles: (args: { + worktreePath: string + connectionId?: string + }) => Promise findHugeFoldersToIgnore: (args: { worktreePath: string }) => Promise refs: (args: { worktreePath: string diff --git a/src/preload/api/git-operation-api.ts b/src/preload/api/source-control/git-operation-api.ts similarity index 84% rename from src/preload/api/git-operation-api.ts rename to src/preload/api/source-control/git-operation-api.ts index 0a8bdad2c86..70ee12d7f7d 100644 --- a/src/preload/api/git-operation-api.ts +++ b/src/preload/api/source-control/git-operation-api.ts @@ -1,19 +1,19 @@ import type { GitCommitAction, GitCommitActionResult -} from '../../shared/git/commands/git-commit-action' +} from '../../../shared/git/commands/git-commit-action' import type { GitForkSyncExpectedUpstream, GitForkSyncResult -} from '../../shared/git/remotes/git-fork-sync' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import type { GitPushTarget } from '../../shared/worktree/types' -import type { GitStageWorktreeScope } from '../../shared/git/paths/git-stage-worktree-scope' -import type { ConflictResolution } from '../../shared/source-control/listing/source-control-entry-actions' -import type { HostedReviewProvider } from '../../shared/source-control/hosted-review/hosted-review-contracts' -import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' -import type { SourceControlAiSettings } from '../../shared/source-control/ai/settings/source-control-ai-settings-types' -import type { TextGenerationFailureFields } from '../../shared/text-generation-failure-copy' +} from '../../../shared/git/remotes/git-fork-sync' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import type { GitPushTarget } from '../../../shared/worktree/types' +import type { GitStageWorktreeScope } from '../../../shared/git/paths/git-stage-worktree-scope' +import type { ConflictResolution } from '../../../shared/source-control/listing/source-control-entry-actions' +import type { HostedReviewProvider } from '../../../shared/source-control/hosted-review/hosted-review-contracts' +import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution' +import type { SourceControlAiSettings } from '../../../shared/source-control/ai/settings/source-control-ai-settings-types' +import type { TextGenerationFailureFields } from '../../../shared/text-generation-failure-copy' export type GitOperationApi = { appendGitignore: (args: { worktreePath: string; folderName: string }) => Promise diff --git a/src/preload/api/sparse-presets-bridge.ts b/src/preload/api/source-control/sparse-presets-bridge.ts similarity index 92% rename from src/preload/api/sparse-presets-bridge.ts rename to src/preload/api/source-control/sparse-presets-bridge.ts index 91676740e6e..dfaa9c612e0 100644 --- a/src/preload/api/sparse-presets-bridge.ts +++ b/src/preload/api/source-control/sparse-presets-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const sparsePresetsApi = { list: (args) => ipcRenderer.invoke('sparsePresets:list', args), diff --git a/src/preload/api/speech-api.ts b/src/preload/api/speech/speech-api.ts similarity index 81% rename from src/preload/api/speech-api.ts rename to src/preload/api/speech/speech-api.ts index c7415932ba7..8023455291f 100644 --- a/src/preload/api/speech-api.ts +++ b/src/preload/api/speech/speech-api.ts @@ -1,4 +1,5 @@ -import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' +import type { SecretAtRestProtection } from '../../../shared/secret-at-rest-protection' +import type { DictationCleanupResult } from '../../../shared/dictation-cleanup' import type { DictationContext, OpenAiCompatibleSpeechProvider, @@ -9,7 +10,7 @@ import type { SpeechModelState, SpeechPendingEvent, SpeechTranscriptEvent -} from '../../shared/speech-types' +} from '../../../shared/speech-types' export type SpeechApi = { getCatalog: () => Promise @@ -38,6 +39,13 @@ export type SpeechApi = { stopDictation: (sessionId?: string) => Promise /** Drops the session's audio and any text it hasn't returned yet, without transcribing the rest. */ cancelDictation: (sessionId: string) => Promise + /** Absent in the paired web client: its host cleans up inside `speech.dictation.finish`. */ + cleanUpDictation?: ( + text: string, + context: DictationContext | undefined, + requestId: string + ) => Promise + cancelDictationCleanup?: (requestId: string) => Promise onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onFinalTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onSpeechPending: (callback: (data: SpeechPendingEvent) => void) => () => void diff --git a/src/preload/api/speech-bridge.ts b/src/preload/api/speech/speech-bridge.ts similarity index 90% rename from src/preload/api/speech-bridge.ts rename to src/preload/api/speech/speech-bridge.ts index 66acdfc0bac..5aeb1dce4fd 100644 --- a/src/preload/api/speech-bridge.ts +++ b/src/preload/api/speech/speech-bridge.ts @@ -1,4 +1,5 @@ -import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' +import type { SecretAtRestProtection } from '../../../shared/secret-at-rest-protection' +import type { DictationCleanupResult } from '../../../shared/dictation-cleanup' import { ipcRenderer } from 'electron' import type { DictationContext, @@ -11,8 +12,8 @@ import type { SpeechModelState, SpeechPendingEvent, SpeechTranscriptEvent -} from '../../shared/speech-types' -import type { PreloadApi } from '../api-types' +} from '../../../shared/speech-types' +import type { PreloadApi } from '../../api-types' // On-device sessions get a port to the speech process, so their audio skips main. const audioPorts = new Map() @@ -99,6 +100,14 @@ export const speechApi = { audioPorts.delete(sessionId) return ipcRenderer.invoke('speech:cancelDictation', sessionId) }, + cleanUpDictation: ( + text: string, + context: DictationContext | undefined, + requestId: string + ): Promise => + ipcRenderer.invoke('speech:cleanUpDictation', { text, context, requestId }), + cancelDictationCleanup: (requestId: string): Promise => + ipcRenderer.invoke('speech:cancelDictationCleanup', requestId), onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: SpeechTranscriptEvent): void => diff --git a/src/preload/api/ssh-api.ts b/src/preload/api/ssh/ssh-api.ts similarity index 96% rename from src/preload/api/ssh-api.ts rename to src/preload/api/ssh/ssh-api.ts index fcb008740d0..160e21ebf6c 100644 --- a/src/preload/api/ssh-api.ts +++ b/src/preload/api/ssh/ssh-api.ts @@ -11,8 +11,8 @@ import type { SshTargetAddResult, SshTargetCreateInput, SshTargetUpdateInput -} from '../../shared/ssh-types' -import type { FilesystemPathFlavor } from '../../shared/file-access/filesystem-path-flavor' +} from '../../../shared/ssh-types' +import type { FilesystemPathFlavor } from '../../../shared/file-access/filesystem-path-flavor' export type SshApi = { listTargets: () => Promise diff --git a/src/preload/api/ssh-bridge.ts b/src/preload/api/ssh/ssh-bridge.ts similarity index 96% rename from src/preload/api/ssh-bridge.ts rename to src/preload/api/ssh/ssh-bridge.ts index 9e63dddc6ea..652ef37d957 100644 --- a/src/preload/api/ssh-bridge.ts +++ b/src/preload/api/ssh/ssh-bridge.ts @@ -12,13 +12,13 @@ import type { PortForwardEntry, UnrestoredPortForward, EnrichedDetectedPort -} from '../../shared/ssh-types' +} from '../../../shared/ssh-types' import { admitSshConnectionStateForAuthorityReconciliation, admitSshDetectedPorts -} from '../../shared/ssh-retained-payload-admission' -import type { FilesystemPathFlavor } from '../../shared/file-access/filesystem-path-flavor' -import type { PreloadApi } from '../api-types' +} from '../../../shared/ssh-retained-payload-admission' +import type { FilesystemPathFlavor } from '../../../shared/file-access/filesystem-path-flavor' +import type { PreloadApi } from '../../api-types' export const sshApi = { listTargets: (): Promise => ipcRenderer.invoke('ssh:listTargets'), diff --git a/src/preload/api/git-bash-bridge.ts b/src/preload/api/terminal/git-bash-bridge.ts similarity index 78% rename from src/preload/api/git-bash-bridge.ts rename to src/preload/api/terminal/git-bash-bridge.ts index c2186d12aa3..289cde443b3 100644 --- a/src/preload/api/git-bash-bridge.ts +++ b/src/preload/api/terminal/git-bash-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const gitBashApi = { isAvailable: (): Promise => ipcRenderer.invoke('gitBash:isAvailable') diff --git a/src/preload/api/plain-ssh-terminal-bridge.ts b/src/preload/api/terminal/plain-ssh-terminal-bridge.ts similarity index 96% rename from src/preload/api/plain-ssh-terminal-bridge.ts rename to src/preload/api/terminal/plain-ssh-terminal-bridge.ts index f9f6aa4856e..37da47728e4 100644 --- a/src/preload/api/plain-ssh-terminal-bridge.ts +++ b/src/preload/api/terminal/plain-ssh-terminal-bridge.ts @@ -3,7 +3,7 @@ import { PLAIN_SSH_TERMINAL_CHANNELS, type PlainSshTerminalEvent, type PlainSshTerminalOpenResult -} from '../../shared/plain-ssh-terminal' +} from '../../../shared/plain-ssh-terminal' export type PlainSshTerminalApi = { open: (args: { diff --git a/src/preload/api/pty-api.ts b/src/preload/api/terminal/pty-api.ts similarity index 85% rename from src/preload/api/pty-api.ts rename to src/preload/api/terminal/pty-api.ts index 51d56a86038..4e569e77134 100644 --- a/src/preload/api/pty-api.ts +++ b/src/preload/api/terminal/pty-api.ts @@ -1,45 +1,52 @@ -import type { RuntimeTerminalAttention } from '../../shared/runtime-terminal-contracts' -import type { PaintedRestorePane } from '../../shared/painted-restore-ack' +import type { RuntimeTerminalAttention } from '../../../shared/runtime-terminal-contracts' +import type { PaintedRestorePane } from '../../../shared/painted-restore-ack' import type { PtyFencedTerminationRequest, PtyFencedTerminationOutcome -} from '../../shared/terminal/pty/lifecycle/pty-fenced-termination' -import type { ResourceViewAdmission } from '../../shared/resource-view-admission' -import type { SpawnIntent } from '../../shared/terminal/pty/admission/spawn-admission-contract' +} from '../../../shared/terminal/pty/lifecycle/pty-fenced-termination' +import type { ResourceViewAdmission } from '../../../shared/resource-view-admission' +import type { SpawnIntent } from '../../../shared/terminal/pty/admission/spawn-admission-contract' import type { SavedResumeDecision, TerminalLaunchResult, AgentProviderSessionMetadata, SleepingAgentLaunchConfig -} from '../../shared/agent-session/lifecycle/agent-session-resume' -import type { StartupCommandDelivery } from '../../shared/agent-launch/startup/codex-startup-delivery' -import type { TerminalInputKind } from '../../shared/terminal/input/terminal-input-kind' +} from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { StartupCommandDelivery } from '../../../shared/agent-launch/startup/codex-startup-delivery' +import type { TerminalInputKind } from '../../../shared/terminal/input/terminal-input-kind' import type { TerminalLeafMoveRequest, TerminalLeafMoveResult -} from '../../shared/workspace-layout/terminal-leaf-move' -import type { ProjectExecutionRuntimeResolution } from '../../shared/execution-host/project-execution-runtime' +} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' +import type { ProjectExecutionRuntimeResolution } from '../../../shared/execution-host/project-execution-runtime' import type { PtyListedSession, PtySessionListScope, PtySessionLifecycle -} from '../../shared/terminal/pty/lifecycle/pty-listed-session' -import type { PtyMainDeliveryDiagnostics } from '../../shared/terminal/pty/diagnostics/pty-delivery-diagnostics' -import type { PtyModelRestoreNeededEvent } from '../../shared/terminal/replay/pty-model-restore-marker' +} from '../../../shared/terminal/pty/lifecycle/pty-listed-session' +import type { PtyMainDeliveryDiagnostics } from '../../../shared/terminal/pty/diagnostics/pty-delivery-diagnostics' +import type { PtyModelRestoreNeededEvent } from '../../../shared/terminal/replay/pty-model-restore-marker' import type { PtyRendererDeliveryHealthReply, PtyRendererDeliveryStateReport -} from '../../shared/terminal/pty/diagnostics/pty-renderer-delivery-health' -import type { AgentKind, LaunchSource, RequestKind } from '../../shared/telemetry-events' -import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' -import type { TerminalViewAttributes } from '../../shared/terminal/protocol/queries/terminal-view-attributes' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import type { TerminalPanePlacement } from '../../shared/workspace-layout/terminal-pane-placement' -import type { AgentPaneLaunchRequest } from '../../shared/agent-launch/contracts/agent-pane-launch-request' +} from '../../../shared/terminal/pty/diagnostics/pty-renderer-delivery-health' +import type { + AgentKind, + LaunchSource, + RequestKind +} from '../../../shared/telemetry-property-schemas' +import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' +import type { TerminalViewAttributes } from '../../../shared/terminal/protocol/queries/terminal-view-attributes' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import type { TerminalPanePlacement } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' +import type { AgentPaneLaunchRequest } from '../../../shared/agent-launch/contracts/agent-pane-launch-request' import type { PtyManagementApi } from './pty-management-api' -import type { TerminalProcessInspection } from '../../shared/terminal/pty/lifecycle/terminal-process-inspection' -import type { CodexSharedServerStatus } from '../../shared/codex-shared-server-command' -import type { NewerDaemonHeldScreen, NewerDaemonReopenResult } from '../../shared/newer-daemon-hold' +import type { TerminalProcessInspection } from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' +import type { CodexSharedServerStatus } from '../../../shared/codex-shared-server-command' +import type { + NewerDaemonHeldScreen, + NewerDaemonReopenResult +} from '../../../shared/newer-daemon-hold' export type PtyApi = { spawn: (opts: { diff --git a/src/preload/api/pty-bridge-session-control.ts b/src/preload/api/terminal/pty-bridge-session-control.ts similarity index 84% rename from src/preload/api/pty-bridge-session-control.ts rename to src/preload/api/terminal/pty-bridge-session-control.ts index fc6066b6d48..2d421b6b5bd 100644 --- a/src/preload/api/pty-bridge-session-control.ts +++ b/src/preload/api/terminal/pty-bridge-session-control.ts @@ -1,40 +1,44 @@ -import type { RuntimeTerminalAttention } from '../../shared/runtime-terminal-contracts' -import type { PaintedRestorePane } from '../../shared/painted-restore-ack' +import type { RuntimeTerminalAttention } from '../../../shared/runtime-terminal-contracts' +import type { PaintedRestorePane } from '../../../shared/painted-restore-ack' import type { PtyFencedTerminationRequest, PtyFencedTerminationOutcome -} from '../../shared/terminal/pty/lifecycle/pty-fenced-termination' -import type { ResourceViewAdmission } from '../../shared/resource-view-admission' -import type { SpawnIntent } from '../../shared/terminal/pty/admission/spawn-admission-contract' +} from '../../../shared/terminal/pty/lifecycle/pty-fenced-termination' +import type { ResourceViewAdmission } from '../../../shared/resource-view-admission' +import type { SpawnIntent } from '../../../shared/terminal/pty/admission/spawn-admission-contract' import { ipcRenderer } from 'electron' -import type { ProjectExecutionRuntimeResolution } from '../../shared/execution-host/project-execution-runtime' -import type { StartupCommandDelivery } from '../../shared/agent-launch/startup/codex-startup-delivery' -import type { TerminalInputKind } from '../../shared/terminal/input/terminal-input-kind' +import type { ProjectExecutionRuntimeResolution } from '../../../shared/execution-host/project-execution-runtime' +import type { StartupCommandDelivery } from '../../../shared/agent-launch/startup/codex-startup-delivery' +import type { TerminalInputKind } from '../../../shared/terminal/input/terminal-input-kind' import type { TerminalLeafMoveRequest, TerminalLeafMoveResult -} from '../../shared/workspace-layout/terminal-leaf-move' +} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import type { SavedResumeDecision, TerminalLaunchResult, AgentProviderSessionMetadata, SleepingAgentLaunchConfig -} from '../../shared/agent-session/lifecycle/agent-session-resume' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +} from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import type { PtyListedSession, PtySessionListScope -} from '../../shared/terminal/pty/lifecycle/pty-listed-session' +} from '../../../shared/terminal/pty/lifecycle/pty-listed-session' import type { PtyRendererDeliveryHealthReply, PtyRendererDeliveryStateReport -} from '../../shared/terminal/pty/diagnostics/pty-renderer-delivery-health' -import type { TerminalViewAttributes } from '../../shared/terminal/protocol/queries/terminal-view-attributes' -import type { PtyMainDeliveryDiagnostics } from '../../shared/terminal/pty/diagnostics/pty-delivery-diagnostics' -import type { AgentKind, LaunchSource, RequestKind } from '../../shared/telemetry-events' -import type { PreloadApi } from '../api-types' -import type { TerminalPanePlacement } from '../../shared/workspace-layout/terminal-pane-placement' -import type { AgentPaneLaunchRequest } from '../../shared/agent-launch/contracts/agent-pane-launch-request' +} from '../../../shared/terminal/pty/diagnostics/pty-renderer-delivery-health' +import type { TerminalViewAttributes } from '../../../shared/terminal/protocol/queries/terminal-view-attributes' +import type { PtyMainDeliveryDiagnostics } from '../../../shared/terminal/pty/diagnostics/pty-delivery-diagnostics' +import type { + AgentKind, + LaunchSource, + RequestKind +} from '../../../shared/telemetry-property-schemas' +import type { PreloadApi } from '../../api-types' +import type { TerminalPanePlacement } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' +import type { AgentPaneLaunchRequest } from '../../../shared/agent-launch/contracts/agent-pane-launch-request' export const ptySessionControlApi = { spawn: (opts: { diff --git a/src/preload/api/pty-bridge-stream-and-serialization.ts b/src/preload/api/terminal/pty-bridge-stream-and-serialization.ts similarity index 91% rename from src/preload/api/pty-bridge-stream-and-serialization.ts rename to src/preload/api/terminal/pty-bridge-stream-and-serialization.ts index 9a8474b5661..ded94904c0d 100644 --- a/src/preload/api/pty-bridge-stream-and-serialization.ts +++ b/src/preload/api/terminal/pty-bridge-stream-and-serialization.ts @@ -1,11 +1,14 @@ -import type { PtySessionLifecycle } from '../../shared/terminal/pty/lifecycle/pty-listed-session' +import type { PtySessionLifecycle } from '../../../shared/terminal/pty/lifecycle/pty-listed-session' import { ipcRenderer } from 'electron' -import type { PtyModelRestoreNeededEvent } from '../../shared/terminal/replay/pty-model-restore-marker' -import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' -import type { PreloadApi } from '../api-types' -import type { TerminalProcessInspection } from '../../shared/terminal/pty/lifecycle/terminal-process-inspection' -import type { CodexSharedServerStatus } from '../../shared/codex-shared-server-command' -import type { NewerDaemonHeldScreen, NewerDaemonReopenResult } from '../../shared/newer-daemon-hold' +import type { PtyModelRestoreNeededEvent } from '../../../shared/terminal/replay/pty-model-restore-marker' +import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' +import type { PreloadApi } from '../../api-types' +import type { TerminalProcessInspection } from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' +import type { CodexSharedServerStatus } from '../../../shared/codex-shared-server-command' +import type { + NewerDaemonHeldScreen, + NewerDaemonReopenResult +} from '../../../shared/newer-daemon-hold' export const ptyStreamAndSerializationApi = { inspectProcess: ( diff --git a/src/preload/api/pty-bridge.ts b/src/preload/api/terminal/pty-bridge.ts similarity index 84% rename from src/preload/api/pty-bridge.ts rename to src/preload/api/terminal/pty-bridge.ts index 18f867e6426..18911ecff77 100644 --- a/src/preload/api/pty-bridge.ts +++ b/src/preload/api/terminal/pty-bridge.ts @@ -1,4 +1,4 @@ -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' import { ptySessionControlApi } from './pty-bridge-session-control' import { ptyStreamAndSerializationApi } from './pty-bridge-stream-and-serialization' diff --git a/src/preload/api/pty-management-api.ts b/src/preload/api/terminal/pty-management-api.ts similarity index 94% rename from src/preload/api/pty-management-api.ts rename to src/preload/api/terminal/pty-management-api.ts index 0d5799b74f8..ae0324cd599 100644 --- a/src/preload/api/pty-management-api.ts +++ b/src/preload/api/terminal/pty-management-api.ts @@ -1,5 +1,5 @@ -import type { DaemonPtyCwdClass } from '../../shared/daemon-adoption-telemetry' -import type { DaemonAsyncIoStatus } from '../../shared/daemon-async-io-health' +import type { DaemonPtyCwdClass } from '../../../shared/daemon-adoption-telemetry' +import type { DaemonAsyncIoStatus } from '../../../shared/daemon-async-io-health' // Mirrors DaemonSessionInfo; preload cannot import main-only daemon protocol types. export type PtyManagementSession = { diff --git a/src/preload/api/pwsh-bridge.ts b/src/preload/api/terminal/pwsh-bridge.ts similarity index 77% rename from src/preload/api/pwsh-bridge.ts rename to src/preload/api/terminal/pwsh-bridge.ts index 34ed9880ada..53ef712dc5c 100644 --- a/src/preload/api/pwsh-bridge.ts +++ b/src/preload/api/terminal/pwsh-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const pwshApi = { isAvailable: (): Promise => ipcRenderer.invoke('pwsh:isAvailable') diff --git a/src/preload/api/shell-api.ts b/src/preload/api/terminal/shell-api.ts similarity index 81% rename from src/preload/api/shell-api.ts rename to src/preload/api/terminal/shell-api.ts index fe70305cf47..7f967b85885 100644 --- a/src/preload/api/shell-api.ts +++ b/src/preload/api/terminal/shell-api.ts @@ -1,12 +1,12 @@ -import type { RepoIconPickResult } from '../../shared/repo-icon-pick-failure-copy' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { ShellPathExistence } from '../../shared/file-access/path-existence-batch' +import type { RepoIconPickResult } from '../../../shared/repo-icon-pick-failure-copy' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ShellPathExistence } from '../../../shared/file-access/path-existence-batch' import type { ShellOpenExternalEditorRequest, ShellOpenExternalEditorResult, ShellOpenFileResult, ShellOpenLocalPathResult -} from '../../shared/shell/opening/shell-open-types' +} from '../../../shared/shell/opening/shell-open-types' export type ShellApi = { /** Every OS open names the path's owner; main refuses anything not owned by this computer. */ diff --git a/src/preload/api/shell-bridge.ts b/src/preload/api/terminal/shell-bridge.ts similarity index 84% rename from src/preload/api/shell-bridge.ts rename to src/preload/api/terminal/shell-bridge.ts index d638d61dd7a..852efd71561 100644 --- a/src/preload/api/shell-bridge.ts +++ b/src/preload/api/terminal/shell-bridge.ts @@ -1,14 +1,14 @@ -import type { RepoIconPickResult } from '../../shared/repo-icon-pick-failure-copy' +import type { RepoIconPickResult } from '../../../shared/repo-icon-pick-failure-copy' import { ipcRenderer } from 'electron' import type { ShellOpenExternalEditorRequest, ShellOpenExternalEditorResult, ShellOpenFileResult, ShellOpenLocalPathResult -} from '../../shared/shell/opening/shell-open-types' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { ShellPathExistence } from '../../shared/file-access/path-existence-batch' -import type { PreloadApi } from '../api-types' +} from '../../../shared/shell/opening/shell-open-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ShellPathExistence } from '../../../shared/file-access/path-existence-batch' +import type { PreloadApi } from '../../api-types' export const shellApi = { openPath: (path: string, ownerHostId: ExecutionHostId): Promise => diff --git a/src/preload/api/terminal-preview-bridge.ts b/src/preload/api/terminal/terminal-preview-bridge.ts similarity index 92% rename from src/preload/api/terminal-preview-bridge.ts rename to src/preload/api/terminal/terminal-preview-bridge.ts index fb607d6db96..6283315bddf 100644 --- a/src/preload/api/terminal-preview-bridge.ts +++ b/src/preload/api/terminal/terminal-preview-bridge.ts @@ -2,8 +2,8 @@ import { ipcRenderer } from 'electron' import type { TerminalPreviewConnectResult, TerminalPreviewDataPayload -} from '../../shared/terminal/replay/terminal-preview' -import type { PreloadApi } from '../api-types' +} from '../../../shared/terminal/replay/terminal-preview' +import type { PreloadApi } from '../../api-types' export const terminalPreviewApi = { connect: ( diff --git a/src/preload/api/updater-api.ts b/src/preload/api/updater/updater-api.ts similarity index 90% rename from src/preload/api/updater-api.ts rename to src/preload/api/updater/updater-api.ts index 6c2fe707f54..8630691d70b 100644 --- a/src/preload/api/updater-api.ts +++ b/src/preload/api/updater/updater-api.ts @@ -3,8 +3,8 @@ import type { ReleaseBuildListResult, UpdateCheckOptions, UpdateStatus -} from '../../shared/update-status-types' -import type { ReleaseChannel } from '../../shared/release-channel' +} from '../../../shared/update-status-types' +import type { ReleaseChannel } from '../../../shared/release-channel' export type UpdaterApi = { getVersion: () => Promise diff --git a/src/preload/api/updater-bridge.ts b/src/preload/api/updater/updater-bridge.ts similarity index 85% rename from src/preload/api/updater-bridge.ts rename to src/preload/api/updater/updater-bridge.ts index 325d5ace205..3f393615e9b 100644 --- a/src/preload/api/updater-bridge.ts +++ b/src/preload/api/updater/updater-bridge.ts @@ -1,8 +1,8 @@ import { ipcRenderer } from 'electron' -import type { UpdateStatus } from '../../shared/update-status-types' -import { prepareAndInvokeUpdaterInstall } from '../renderer-restart-wiring' -import { awaitBeforeUnloadCheckpoint, updaterQuitAbortRelay } from '../preload-runtime-support' -import type { PreloadApi } from '../api-types' +import type { UpdateStatus } from '../../../shared/update-status-types' +import { prepareAndInvokeUpdaterInstall } from '../../renderer/restart/renderer-restart-wiring' +import { awaitBeforeUnloadCheckpoint, updaterQuitAbortRelay } from '../../renderer/renderer-runtime' +import type { PreloadApi } from '../../api-types' export const updaterApi = { getStatus: () => ipcRenderer.invoke('updater:getStatus'), diff --git a/src/preload/api/window-ui/app-icon-api.ts b/src/preload/api/window-ui/app-icon-api.ts new file mode 100644 index 00000000000..c3a48f85be3 --- /dev/null +++ b/src/preload/api/window-ui/app-icon-api.ts @@ -0,0 +1,7 @@ +import type { CustomAppIconImportResult } from '../../../shared/app-icon' + +export type AppIconApi = { + importCustom: () => Promise + readCustomPreview: () => Promise + removeCustom: () => Promise +} diff --git a/src/preload/api/app-icon-bridge.ts b/src/preload/api/window-ui/app-icon-bridge.ts similarity index 86% rename from src/preload/api/app-icon-bridge.ts rename to src/preload/api/window-ui/app-icon-bridge.ts index aad315bd00b..ba708ba0f43 100644 --- a/src/preload/api/app-icon-bridge.ts +++ b/src/preload/api/window-ui/app-icon-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const appIconApi = { importCustom: () => ipcRenderer.invoke('appIcon:importCustom'), diff --git a/src/preload/api/dashboard-api.ts b/src/preload/api/window-ui/dashboard-api.ts similarity index 89% rename from src/preload/api/dashboard-api.ts rename to src/preload/api/window-ui/dashboard-api.ts index 36a7747c819..572d6e9c323 100644 --- a/src/preload/api/dashboard-api.ts +++ b/src/preload/api/window-ui/dashboard-api.ts @@ -1,8 +1,11 @@ -import type { DashboardRevealAgentArgs, DashboardSnapshot } from '../../shared/dashboard-snapshot' +import type { + DashboardRevealAgentArgs, + DashboardSnapshot +} from '../../../shared/dashboard-snapshot' import type { TerminalPreviewConnectResult, TerminalPreviewDataPayload -} from '../../shared/terminal/replay/terminal-preview' +} from '../../../shared/terminal/replay/terminal-preview' export type DashboardApi = { openPopout: () => Promise diff --git a/src/preload/api/dashboard-bridge.ts b/src/preload/api/window-ui/dashboard-bridge.ts similarity index 94% rename from src/preload/api/dashboard-bridge.ts rename to src/preload/api/window-ui/dashboard-bridge.ts index 4663b87459e..fe5c17c8a98 100644 --- a/src/preload/api/dashboard-bridge.ts +++ b/src/preload/api/window-ui/dashboard-bridge.ts @@ -1,6 +1,9 @@ import { ipcRenderer } from 'electron' -import type { DashboardRevealAgentArgs, DashboardSnapshot } from '../../shared/dashboard-snapshot' -import type { PreloadApi } from '../api-types' +import type { + DashboardRevealAgentArgs, + DashboardSnapshot +} from '../../../shared/dashboard-snapshot' +import type { PreloadApi } from '../../api-types' export const dashboardApi = { openPopout: (): Promise => ipcRenderer.invoke('dashboardPopout:open'), diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/window-ui/ui-bridge-clipboard-and-window-controls.ts similarity index 94% rename from src/preload/api/ui-bridge-clipboard-and-window-controls.ts rename to src/preload/api/window-ui/ui-bridge-clipboard-and-window-controls.ts index 1aa0df2b6ab..7fb38e7da65 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/window-ui/ui-bridge-clipboard-and-window-controls.ts @@ -1,4 +1,4 @@ -import type { AgentSessionAttachmentClipboardTarget } from '../../shared/agent-session/agent-session-attachments' +import type { AgentSessionAttachmentClipboardTarget } from '../../../shared/agent-session/agent-session-attachments' import { ipcRenderer, webFrame } from 'electron' import { richMarkdownContextMenuCommandChannel, @@ -6,16 +6,16 @@ import { plainTextContextMenuTargetChannel, type RichMarkdownContextMenuCommandPayload, type RichMarkdownContextMenuTableTarget -} from '../../shared/rich-markdown-context-menu' -import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' -import type { TerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' -import type { ClipboardImageThumbnail } from '../../shared/clipboard-image' -import type { ReadClipboardTextOptions } from '../../shared/clipboard-text' +} from '../../../shared/rich-markdown-context-menu' +import type { RuntimeNavigationTarget } from '../../../shared/runtime-navigation' +import type { TerminalSurfaceCloseTarget } from '../../../shared/workspace-layout/terminal-surfaces/terminal-surface-close-target' +import type { ClipboardImageThumbnail } from '../../../shared/clipboard-image' +import type { ReadClipboardTextOptions } from '../../../shared/clipboard-text' import type { AgentPaneActivityReply, AgentPaneActivityRequest -} from '../../shared/agent-status/presentation/agent-list-status' -import type { PreloadApi } from '../api-types' +} from '../../../shared/agent-status/presentation/agent-list-status' +import type { PreloadApi } from '../../api-types' export const uiClipboardAndWindowControlsApi = { onOpenDiffFromMobile: ( diff --git a/src/preload/api/ui-bridge-state-and-menu-commands.ts b/src/preload/api/window-ui/ui-bridge-state-and-menu-commands.ts similarity index 93% rename from src/preload/api/ui-bridge-state-and-menu-commands.ts rename to src/preload/api/window-ui/ui-bridge-state-and-menu-commands.ts index d565a3d81eb..127b72c268a 100644 --- a/src/preload/api/ui-bridge-state-and-menu-commands.ts +++ b/src/preload/api/window-ui/ui-bridge-state-and-menu-commands.ts @@ -1,13 +1,13 @@ -import type { MarkdownDocument } from '../../shared/file-listing/file-document' -import type { BrowserTabCreateRequest } from '../../shared/browser-tab-create-request' +import type { MarkdownDocument } from '../../../shared/file-listing/file-document' +import type { BrowserTabCreateRequest } from '../../../shared/browser-tab-create-request' import { ipcRenderer } from 'electron' -import type { PersistedUIState } from '../../shared/persisted-ui-state-types' -import type { KeybindingActionId } from '../../shared/keybindings' -import type { PreloadApi } from '../api-types' +import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import type { KeybindingActionId } from '../../../shared/keybindings/types' +import type { PreloadApi } from '../../api-types' import type { RemoteCliBrowserScopeQuery, RemoteCliBrowserScopeReply -} from '../../shared/desktop-browser-bridge-protocol' +} from '../../../shared/desktop-browser-bridge-protocol' export const uiStateAndMenuCommandsApi = { getJiraQuickFilters: () => ipcRenderer.invoke('ui:getJiraQuickFilters'), @@ -119,11 +119,6 @@ export const uiStateAndMenuCommandsApi = { ipcRenderer.on('ui:openNewWorkspace', listener) return () => ipcRenderer.removeListener('ui:openNewWorkspace', listener) }, - onDeleteCurrentWorkspace: (callback: () => void): (() => void) => { - const listener = (_event: Electron.IpcRendererEvent) => callback() - ipcRenderer.on('ui:deleteCurrentWorkspace', listener) - return () => ipcRenderer.removeListener('ui:deleteCurrentWorkspace', listener) - }, onOpenWorkspaceBoard: (callback: () => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent) => callback() ipcRenderer.on('ui:openWorkspaceBoard', listener) diff --git a/src/preload/api/ui-bridge-tab-and-browser-commands.ts b/src/preload/api/window-ui/ui-bridge-tab-and-browser-commands.ts similarity index 95% rename from src/preload/api/ui-bridge-tab-and-browser-commands.ts rename to src/preload/api/window-ui/ui-bridge-tab-and-browser-commands.ts index 3b7a092224a..92676911577 100644 --- a/src/preload/api/ui-bridge-tab-and-browser-commands.ts +++ b/src/preload/api/window-ui/ui-bridge-tab-and-browser-commands.ts @@ -1,18 +1,18 @@ import { ipcRenderer } from 'electron' -import { admitCloseActiveTabPayload } from '../close-active-tab-payload-admission' -import type { CloseActiveTabPayload } from '../api/ui-command-event-api' +import { admitCloseActiveTabPayload } from '../../renderer/window-commands/close-active-tab-payload-admission' +import type { CloseActiveTabPayload } from './ui-command-event-api' import type { BrowserHistoryNavigateCommand, BrowserPageCommandTarget, BrowserPageTabShortcut -} from '../../shared/browser-page-command-target' -import type { BrowserPageZoomCommand } from '../../shared/browser-page-zoom' +} from '../../../shared/browser-page-command-target' +import type { BrowserPageZoomCommand } from '../../../shared/browser-page-zoom' import type { WorktreeDefaultTabsLaunch, WorktreeSetupLaunch -} from '../../shared/worktree/launch-types' -import { browserFindSubscriptions } from '../preload-runtime-support' -import type { PreloadApi } from '../api-types' +} from '../../../shared/worktree/creation/launch-types' +import { browserFindSubscriptions } from '../../renderer/renderer-runtime' +import type { PreloadApi } from '../../api-types' export const uiTabAndBrowserCommandsApi = { onRequestTabSetProfile: ( diff --git a/src/preload/api/ui-bridge-terminal-and-session-tabs.ts b/src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts similarity index 90% rename from src/preload/api/ui-bridge-terminal-and-session-tabs.ts rename to src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts index c324db9e5fa..11f75d66557 100644 --- a/src/preload/api/ui-bridge-terminal-and-session-tabs.ts +++ b/src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts @@ -1,33 +1,33 @@ import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition -} from '../../shared/file-access/runtime-editor-file-open' +} from '../../../shared/file-access/runtime-editor-file-open' import { ipcRenderer } from 'electron' -import type { TerminalPaneSplitSource } from '../../shared/feature-education-telemetry' -import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' +import type { TerminalPaneSplitSource } from '../../../shared/feature-education-telemetry' +import type { TerminalTabCreateReply } from '../../../shared/workspace-layout/terminal-surfaces/terminal-reveal-identity' import type { AgentLaunchTabPublishReply, AgentLaunchTabViewerRule, AgentLaunchTabPublishRequest -} from '../../shared/agent-launch/contracts/agent-launch-tab-publication' -import type { AgentLaunchPaneVerdictEvent } from '../../shared/agent-launch/contracts/agent-launch-pane-verdict' -import type { PaneLaunchRecipe } from '../../shared/terminal/pty/lifecycle/terminal-attachment-launch-result' +} from '../../../shared/agent-launch/contracts/agent-launch-tab-publication' +import type { AgentLaunchPaneVerdictEvent } from '../../../shared/agent-launch/contracts/agent-launch-pane-verdict' +import type { PaneLaunchRecipe } from '../../../shared/terminal/pty/lifecycle/terminal-attachment-launch-result' import type { TerminalPaneRevealReply, TerminalPaneRevealRequest -} from '../../shared/workspace-layout/terminal-pane-reveal' +} from '../../../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal' import type { AgentProviderSessionMetadata, SleepingAgentLaunchConfig -} from '../../shared/agent-session/lifecycle/agent-session-resume' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' +} from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import type { RuntimeNavigationTarget } from '../../../shared/runtime-navigation' +import type { RuntimeMobileSessionTabMove } from '../../../shared/runtime-session-contracts' import type { - RuntimeMobileSessionTabMove, RuntimeTerminalCreateRequestPayload, RuntimeTerminalPresentation -} from '../../shared/runtime-types' -import type { PreloadApi } from '../api-types' +} from '../../../shared/runtime-terminal-contracts' +import type { PreloadApi } from '../../api-types' export const uiTerminalAndSessionTabsApi = { onCreateTerminal: ( diff --git a/src/preload/api/ui-bridge.ts b/src/preload/api/window-ui/ui-bridge.ts similarity index 91% rename from src/preload/api/ui-bridge.ts rename to src/preload/api/window-ui/ui-bridge.ts index 200d49ba1c1..0b3b442719b 100644 --- a/src/preload/api/ui-bridge.ts +++ b/src/preload/api/window-ui/ui-bridge.ts @@ -1,4 +1,4 @@ -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' import { uiStateAndMenuCommandsApi } from './ui-bridge-state-and-menu-commands' import { uiTabAndBrowserCommandsApi } from './ui-bridge-tab-and-browser-commands' import { uiTerminalAndSessionTabsApi } from './ui-bridge-terminal-and-session-tabs' diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/window-ui/ui-command-event-api.ts similarity index 83% rename from src/preload/api/ui-command-event-api.ts rename to src/preload/api/window-ui/ui-command-event-api.ts index f9895cec986..a39ca774733 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/window-ui/ui-command-event-api.ts @@ -1,79 +1,79 @@ import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition -} from '../../shared/file-access/runtime-editor-file-open' -import type { JiraQuickFilterState } from '../../shared/jira/jira-quick-filters' +} from '../../../shared/file-access/runtime-editor-file-open' +import type { JiraQuickFilterState } from '../../../shared/jira/jira-quick-filters' import type { JiraSavedFilterState, JiraSavedFilterMutation -} from '../../shared/jira/jira-saved-filters' -import type { BrowserTabCreateRequest } from '../../shared/browser-tab-create-request' -import type { MarkdownDocument } from '../../shared/file-listing/file-document' -import type { PersistedUIState } from '../../shared/persisted-ui-state-types' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +} from '../../../shared/jira/jira-saved-filters' +import type { BrowserTabCreateRequest } from '../../../shared/browser-tab-create-request' +import type { MarkdownDocument } from '../../../shared/file-listing/file-document' +import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import type { AgentLaunchTabPublishReply, AgentLaunchTabViewerRule, AgentLaunchTabPublishRequest -} from '../../shared/agent-launch/contracts/agent-launch-tab-publication' -import type { AgentLaunchPaneVerdictEvent } from '../../shared/agent-launch/contracts/agent-launch-pane-verdict' -import type { PaneLaunchRecipe } from '../../shared/terminal/pty/lifecycle/terminal-attachment-launch-result' +} from '../../../shared/agent-launch/contracts/agent-launch-tab-publication' +import type { AgentLaunchPaneVerdictEvent } from '../../../shared/agent-launch/contracts/agent-launch-pane-verdict' +import type { PaneLaunchRecipe } from '../../../shared/terminal/pty/lifecycle/terminal-attachment-launch-result' import type { TerminalPaneMoveToNewTabReply, TerminalPaneMoveToNewTabRequest -} from '../../shared/workspace-layout/terminal-leaf-move' +} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import type { TerminalPaneRevealReply, TerminalPaneRevealRequest -} from '../../shared/workspace-layout/terminal-pane-reveal' +} from '../../../shared/workspace-layout/terminal-surfaces/terminal-pane-reveal' import type { AgentPaneActivityReply, AgentPaneActivityRequest -} from '../../shared/agent-status/presentation/agent-list-status' -import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' +} from '../../../shared/agent-status/presentation/agent-list-status' +import type { RuntimeNavigationTarget } from '../../../shared/runtime-navigation' import type { ProjectMovePauseRequest, ProjectMovePauseResponse -} from '../../shared/project-move-pause' -import type { TerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' +} from '../../../shared/project-move-pause' +import type { TerminalSurfaceCloseTarget } from '../../../shared/workspace-layout/terminal-surfaces/terminal-surface-close-target' import type { WorktreeDefaultTabsLaunch, WorktreeSetupLaunch, WorktreeStartupLaunch -} from '../../shared/worktree/launch-types' -import type { FeatureInteractionId } from '../../shared/feature-interactions' -import type { KeybindingActionId } from '../../shared/keybindings' -import type { BrowserFindSource } from '../../shared/browser-find-source' +} from '../../../shared/worktree/creation/launch-types' +import type { FeatureInteractionId } from '../../../shared/feature-interaction-catalog' +import type { KeybindingActionId } from '../../../shared/keybindings/types' +import type { BrowserFindSource } from '../../../shared/browser-find-source' import type { BrowserHistoryNavigateCommand, BrowserPageCommandTarget, BrowserPageTabShortcut -} from '../../shared/browser-page-command-target' -import type { BrowserPageZoomCommand } from '../../shared/browser-page-zoom' +} from '../../../shared/browser-page-command-target' +import type { BrowserPageZoomCommand } from '../../../shared/browser-page-zoom' import type { AgentProviderSessionMetadata, SleepingAgentLaunchConfig -} from '../../shared/agent-session/lifecycle/agent-session-resume' -import type { TerminalPaneSplitSource } from '../../shared/feature-education-telemetry' +} from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { TerminalPaneSplitSource } from '../../../shared/feature-education-telemetry' +import type { RuntimeMobileSessionTabMove } from '../../../shared/runtime-session-contracts' import type { - RuntimeMobileSessionTabMove, RuntimeTerminalCreateRequestPayload, RuntimeTerminalPresentation -} from '../../shared/runtime-types' -import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' +} from '../../../shared/runtime-terminal-contracts' +import type { TerminalTabCreateReply } from '../../../shared/workspace-layout/terminal-surfaces/terminal-reveal-identity' import type { TerminalTabCloseRequest, TerminalTabCloseResponse -} from '../../shared/workspace-layout/terminal-tab-close' +} from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-close' import type { SessionTabCloseRequest, SessionTabCloseResponse -} from '../../shared/session-tab-close' -import type { WorkspaceSleepNotice } from '../../shared/workspace-sleep' +} from '../../../shared/session-tab-close' +import type { WorkspaceSleepNotice } from '../../../shared/workspace-sleep' import type { RemoteCliBrowserScopeQuery, RemoteCliBrowserScopeReply -} from '../../shared/desktop-browser-bridge-protocol' +} from '../../../shared/desktop-browser-bridge-protocol' export type CloseActiveTabPayload = { sourceId: string } @@ -117,7 +117,6 @@ export type UiCommandEventApi = { onOpenQuickOpen: (callback: () => void) => () => void onToggleQuickCommandsMenu: (callback: () => void) => () => void onOpenNewWorkspace: (callback: () => void) => () => void - onDeleteCurrentWorkspace: (callback: () => void) => () => void onOpenWorkspaceBoard: (callback: () => void) => () => void onOpenTasks: (callback: () => void) => () => void onToggleAgentDashboard: (callback: () => void) => () => void diff --git a/src/preload/api/ui-window-api.ts b/src/preload/api/window-ui/ui-window-api.ts similarity index 93% rename from src/preload/api/ui-window-api.ts rename to src/preload/api/window-ui/ui-window-api.ts index e97ee1730e6..ee05d53254e 100644 --- a/src/preload/api/ui-window-api.ts +++ b/src/preload/api/window-ui/ui-window-api.ts @@ -1,10 +1,10 @@ -import type { AgentSessionAttachmentClipboardTarget } from '../../shared/agent-session/agent-session-attachments' -import type { ClipboardImageThumbnail } from '../../shared/clipboard-image' -import type { ReadClipboardTextOptions } from '../../shared/clipboard-text' +import type { AgentSessionAttachmentClipboardTarget } from '../../../shared/agent-session/agent-session-attachments' +import type { ClipboardImageThumbnail } from '../../../shared/clipboard-image' +import type { ReadClipboardTextOptions } from '../../../shared/clipboard-text' import type { RichMarkdownContextMenuCommandPayload, RichMarkdownContextMenuTableTarget -} from '../../shared/rich-markdown-context-menu' +} from '../../../shared/rich-markdown-context-menu' export type UiWindowApi = { readClipboardText: (options?: ReadClipboardTextOptions) => Promise diff --git a/src/preload/api/jira-api.ts b/src/preload/api/work-items/jira-api.ts similarity index 92% rename from src/preload/api/jira-api.ts rename to src/preload/api/work-items/jira-api.ts index ce3f1529d11..87c4082f004 100644 --- a/src/preload/api/jira-api.ts +++ b/src/preload/api/work-items/jira-api.ts @@ -1,10 +1,10 @@ -import type { JiraMediaFormat } from '../../shared/jira/jira-attachment-image' -import type { JiraFavouriteFilterList } from '../../shared/jira/jira-favourite-filters' +import type { JiraMediaFormat } from '../../../shared/jira/jira-attachment-image' +import type { JiraFavouriteFilterList } from '../../../shared/jira/jira-favourite-filters' import type { JiraIssueSummaryGenerationRequest, JiraIssueSummaryGenerationCancellation, JiraIssueSummaryGenerationResult -} from '../../shared/jira/jira-issue-summary-generation' +} from '../../../shared/jira/jira-issue-summary-generation' import type { JiraComment, JiraConnectionStatus, @@ -22,7 +22,7 @@ import type { JiraTransition, JiraUser, JiraViewer -} from '../../shared/jira/jira-types' +} from '../../../shared/jira/jira-types' export type JiraApi = { connect: (args: { diff --git a/src/preload/api/jira-bridge.ts b/src/preload/api/work-items/jira-bridge.ts similarity index 94% rename from src/preload/api/jira-bridge.ts rename to src/preload/api/work-items/jira-bridge.ts index f1953137c6d..cc4fa33c3bb 100644 --- a/src/preload/api/jira-bridge.ts +++ b/src/preload/api/work-items/jira-bridge.ts @@ -1,11 +1,11 @@ -import type { JiraMediaFormat } from '../../shared/jira/jira-attachment-image' +import type { JiraMediaFormat } from '../../../shared/jira/jira-attachment-image' import type { JiraIssueSummaryGenerationRequest, JiraIssueSummaryGenerationCancellation -} from '../../shared/jira/jira-issue-summary-generation' +} from '../../../shared/jira/jira-issue-summary-generation' import { ipcRenderer } from 'electron' -import type { JiraIssueListFilters, JiraProjectStatusOrder } from '../../shared/jira/jira-types' -import type { PreloadApi } from '../api-types' +import type { JiraIssueListFilters, JiraProjectStatusOrder } from '../../../shared/jira/jira-types' +import type { PreloadApi } from '../../api-types' export const jiraApi = { connect: (args: { diff --git a/src/preload/api/linear-api.ts b/src/preload/api/work-items/linear-api.ts similarity index 86% rename from src/preload/api/linear-api.ts rename to src/preload/api/work-items/linear-api.ts index 0b924953d86..7a52e1ce96e 100644 --- a/src/preload/api/linear-api.ts +++ b/src/preload/api/work-items/linear-api.ts @@ -1,12 +1,13 @@ -import type { LinearIssueAttributeFilter } from '../../shared/linear/issue-attribute-filter' -import type { LinearIssueUpdate } from '../../shared/issue-mutation-types' -import type { LinearComment, LinearIssue } from '../../shared/linear/issue-types' +import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' +import type { LinearIssueAttributeFilter } from '../../../shared/linear/issue-attribute-filter' +import type { LinearIssueUpdate } from '../../../shared/issue-mutation-types' +import type { LinearComment, LinearIssue } from '../../../shared/linear/issue-types' import type { LinearCustomViewModel, LinearCustomViewSummary, LinearProjectDetail, LinearProjectSummary -} from '../../shared/linear/project-types' +} from '../../../shared/linear/project-types' import type { LinearCollectionResult, LinearConnectionStatus, @@ -16,9 +17,15 @@ import type { LinearViewer, LinearWorkflowState, LinearWorkspaceSelection -} from '../../shared/linear/workspace-types' +} from '../../../shared/linear/workspace-types' + +export type LinearLinkedIssueUpdated = Extract< + RuntimeClientEvent, + { type: 'linearLinkedIssueUpdated' } +> export type LinearApi = { + onLinkedIssueUpdated?: (callback: (event: LinearLinkedIssueUpdated) => void) => () => void connect: (args: { apiKey: string }) => Promise<{ ok: true; viewer: LinearViewer } | { ok: false; error: string }> diff --git a/src/preload/api/linear-bridge.ts b/src/preload/api/work-items/linear-bridge.ts similarity index 88% rename from src/preload/api/linear-bridge.ts rename to src/preload/api/work-items/linear-bridge.ts index 8092a8e70e7..04fa03b99fa 100644 --- a/src/preload/api/linear-bridge.ts +++ b/src/preload/api/work-items/linear-bridge.ts @@ -1,8 +1,15 @@ +import type { LinearLinkedIssueUpdated } from './linear-api' import { ipcRenderer } from 'electron' -import type { LinearProjectDetail } from '../../shared/linear/project-types' -import type { PreloadApi } from '../api-types' +import type { LinearProjectDetail } from '../../../shared/linear/project-types' +import type { PreloadApi } from '../../api-types' export const linearApi = { + onLinkedIssueUpdated: (callback: (event: LinearLinkedIssueUpdated) => void) => { + const listener = (_event: Electron.IpcRendererEvent, update: LinearLinkedIssueUpdated): void => + callback(update) + ipcRenderer.on('linear:linkedIssueUpdated', listener) + return () => ipcRenderer.removeListener('linear:linkedIssueUpdated', listener) + }, connect: (args: { apiKey: string }) => ipcRenderer.invoke('linear:connect', args), disconnect: (args?: { workspaceId?: string }): Promise => diff --git a/src/preload/api/workspace-session-api.ts b/src/preload/api/workspace-session-api.ts deleted file mode 100644 index ccd70c8004b..00000000000 --- a/src/preload/api/workspace-session-api.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { IssueInfo, PRInfo } from '../../shared/github/pull-request-types' -import type { - WorkspaceSessionPatch, - WorkspaceSessionState -} from '../../shared/workspace-session/workspace-session-state-types' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { TerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' - -export type WorkspaceSessionApi = { - session: { - // Omitted hostId selects the local persistence partition. - get: (hostId?: ExecutionHostId) => Promise - /** Read persisted partitions at boot; the host catalog may omit some. */ - listHostIds: () => Promise - set: (args: WorkspaceSessionState, hostId?: ExecutionHostId) => Promise - patch: (args: WorkspaceSessionPatch, hostId?: ExecutionHostId) => Promise - /** Commits a terminal tab or split-pane close into main's membership. */ - closeTerminalSurface: (args: { - worktreeId: string - target: TerminalSurfaceCloseTarget - reason?: 'user' | 'cleanup' - }) => Promise - flush: () => Promise - readTerminalScrollback: (args: { ref: string }) => string | null - /** Stat-only: whether this machine's snapshot store holds `ref`. */ - hasTerminalScrollback: (args: { ref: string }) => boolean - } - cache: { - getGitHub: () => Promise<{ - pr: Record - issue: Record - }> - setGitHub: (args: { - cache: { - pr: Record - issue: Record - } - }) => Promise - } -} diff --git a/src/preload/api/folder-workspaces-bridge.ts b/src/preload/api/workspaces/folder-workspaces-bridge.ts similarity index 90% rename from src/preload/api/folder-workspaces-bridge.ts rename to src/preload/api/workspaces/folder-workspaces-bridge.ts index d085719d8ab..a7aff81b6b7 100644 --- a/src/preload/api/folder-workspaces-bridge.ts +++ b/src/preload/api/workspaces/folder-workspaces-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const folderWorkspacesApi = { list: () => ipcRenderer.invoke('folderWorkspaces:list'), diff --git a/src/preload/api/localhost-worktree-labels-bridge.ts b/src/preload/api/workspaces/localhost-worktree-labels-bridge.ts similarity index 78% rename from src/preload/api/localhost-worktree-labels-bridge.ts rename to src/preload/api/workspaces/localhost-worktree-labels-bridge.ts index a44dcffff69..bb635af83a6 100644 --- a/src/preload/api/localhost-worktree-labels-bridge.ts +++ b/src/preload/api/workspaces/localhost-worktree-labels-bridge.ts @@ -2,8 +2,8 @@ import { ipcRenderer } from 'electron' import type { LocalhostWorktreeLabelResult, LocalhostWorktreeLabelRoute -} from '../../shared/localhost-worktree-labels' -import type { PreloadApi } from '../api-types' +} from '../../../shared/localhost-worktree-labels' +import type { PreloadApi } from '../../api-types' export const localhostWorktreeLabelsApi = { register: (args: LocalhostWorktreeLabelRoute): Promise => diff --git a/src/preload/api/workspaces/session-bridge.ts b/src/preload/api/workspaces/session-bridge.ts new file mode 100644 index 00000000000..3ed06775c0a --- /dev/null +++ b/src/preload/api/workspaces/session-bridge.ts @@ -0,0 +1,12 @@ +import { ipcRenderer } from 'electron' +import type { PreloadApi } from '../../api-types' + +export const sessionApi = { + get: (hostId) => ipcRenderer.invoke('session:get', hostId), + listHostIds: () => ipcRenderer.invoke('session:list-host-ids'), + set: (args, hostId) => ipcRenderer.invoke('session:set', args, hostId), + patch: (args, hostId) => ipcRenderer.invoke('session:patch', args, hostId), + closeTerminalSurface: (args) => ipcRenderer.invoke('session:close-terminal-surface', args), + flush: () => ipcRenderer.invoke('session:flush'), + readTerminalScrollback: (args) => ipcRenderer.invoke('session:read-terminal-scrollback', args) +} satisfies PreloadApi['session'] diff --git a/src/preload/api/workspace-cleanup-api.ts b/src/preload/api/workspaces/workspace-cleanup-api.ts similarity index 89% rename from src/preload/api/workspace-cleanup-api.ts rename to src/preload/api/workspaces/workspace-cleanup-api.ts index 84458b41907..e286bbd2913 100644 --- a/src/preload/api/workspace-cleanup-api.ts +++ b/src/preload/api/workspaces/workspace-cleanup-api.ts @@ -5,14 +5,14 @@ import type { WorkspaceCleanupScanResult, WorkspaceCleanupSnapshotPruneBatchArgs, WorkspaceCleanupSnapshotPruneRecordArgs -} from '../../shared/workspace-cleanup/workspace-cleanup' +} from '../../../shared/workspace-cleanup/workspace-cleanup' import type { WorkspaceSpaceAnalysis, WorkspaceSpaceAnalyzeResult, WorkspaceSpaceScanProgress -} from '../../shared/workspace-disk-space/workspace-space-types' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { WorkspaceSpaceChange } from '../../shared/workspace-disk-space/workspace-space-change' +} from '../../../shared/workspace-disk-space/workspace-space-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { WorkspaceSpaceChange } from '../../../shared/workspace-disk-space/workspace-space-change' export type WorkspaceCleanupApi = { scan: ( diff --git a/src/preload/api/workspace-cleanup-bridge.ts b/src/preload/api/workspaces/workspace-cleanup-bridge.ts similarity index 90% rename from src/preload/api/workspace-cleanup-bridge.ts rename to src/preload/api/workspaces/workspace-cleanup-bridge.ts index f2a6d90152f..4c979e55e84 100644 --- a/src/preload/api/workspace-cleanup-bridge.ts +++ b/src/preload/api/workspaces/workspace-cleanup-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { WorkspaceCleanupScanProgress } from '../../shared/workspace-cleanup/workspace-cleanup' -import type { PreloadApi } from '../api-types' +import type { WorkspaceCleanupScanProgress } from '../../../shared/workspace-cleanup/workspace-cleanup' +import type { PreloadApi } from '../../api-types' export const workspaceCleanupApi = { scan: (args, onProgress) => { diff --git a/src/preload/api/workspace-port-api.ts b/src/preload/api/workspaces/workspace-port-api.ts similarity index 90% rename from src/preload/api/workspace-port-api.ts rename to src/preload/api/workspaces/workspace-port-api.ts index 06c91c645ea..3da0f4e53f8 100644 --- a/src/preload/api/workspace-port-api.ts +++ b/src/preload/api/workspaces/workspace-port-api.ts @@ -1,7 +1,7 @@ import type { LocalhostWorktreeLabelResult, LocalhostWorktreeLabelRoute -} from '../../shared/localhost-worktree-labels' +} from '../../../shared/localhost-worktree-labels' import type { WorkspacePortAdvertisedUrlChangedEvent, WorkspacePortKillRequest, @@ -10,7 +10,7 @@ import type { WorkspacePortPageProbeResult, WorkspacePortScanRequest, WorkspacePortScanResult -} from '../../shared/workspace-ports' +} from '../../../shared/workspace-ports' export type WorkspacePortsApi = { scan: (args: WorkspacePortScanRequest) => Promise diff --git a/src/preload/api/workspace-ports-bridge.ts b/src/preload/api/workspaces/workspace-ports-bridge.ts similarity index 90% rename from src/preload/api/workspace-ports-bridge.ts rename to src/preload/api/workspaces/workspace-ports-bridge.ts index fba9a274adf..9a4c5e65671 100644 --- a/src/preload/api/workspace-ports-bridge.ts +++ b/src/preload/api/workspaces/workspace-ports-bridge.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { WorkspacePortAdvertisedUrlChangedEvent } from '../../shared/workspace-ports' -import type { PreloadApi } from '../api-types' +import type { WorkspacePortAdvertisedUrlChangedEvent } from '../../../shared/workspace-ports' +import type { PreloadApi } from '../../api-types' export const workspacePortsApi = { scan: (args) => ipcRenderer.invoke('workspacePorts:scan', args), diff --git a/src/preload/api/workspaces/workspace-session-api.ts b/src/preload/api/workspaces/workspace-session-api.ts new file mode 100644 index 00000000000..b5c3cef456b --- /dev/null +++ b/src/preload/api/workspaces/workspace-session-api.ts @@ -0,0 +1,38 @@ +import type { IssueInfo, PRInfo } from '../../../shared/github/pull-requests/pull-request-types' +import type { + WorkspaceSessionPatch, + WorkspaceSessionState +} from '../../../shared/workspace-session/workspace-session-state-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { TerminalSurfaceCloseTarget } from '../../../shared/workspace-layout/terminal-surfaces/terminal-surface-close-target' + +export type WorkspaceSessionApi = { + session: { + // Omitted hostId selects the local persistence partition. + get: (hostId?: ExecutionHostId) => Promise + /** Read persisted partitions at boot; the host catalog may omit some. */ + listHostIds: () => Promise + set: (args: WorkspaceSessionState, hostId?: ExecutionHostId) => Promise + patch: (args: WorkspaceSessionPatch, hostId?: ExecutionHostId) => Promise + /** Commits a terminal tab or split-pane close into main's membership. */ + closeTerminalSurface: (args: { + worktreeId: string + target: TerminalSurfaceCloseTarget + reason?: 'user' | 'cleanup' + }) => Promise + flush: () => Promise + readTerminalScrollback: (args: { ref: string }) => Promise + } + cache: { + getGitHub: () => Promise<{ + pr: Record + issue: Record + }> + setGitHub: (args: { + cache: { + pr: Record + issue: Record + } + }) => Promise + } +} diff --git a/src/preload/api/workspace-space-bridge.ts b/src/preload/api/workspaces/workspace-space-bridge.ts similarity index 93% rename from src/preload/api/workspace-space-bridge.ts rename to src/preload/api/workspaces/workspace-space-bridge.ts index cfab82ca3bd..2e6495fa82d 100644 --- a/src/preload/api/workspace-space-bridge.ts +++ b/src/preload/api/workspaces/workspace-space-bridge.ts @@ -2,10 +2,10 @@ import { ipcRenderer } from 'electron' import type { WorkspaceSpaceAnalysis, WorkspaceSpaceScanProgress -} from '../../shared/workspace-disk-space/workspace-space-types' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { WorkspaceSpaceChange } from '../../shared/workspace-disk-space/workspace-space-change' -import type { PreloadApi } from '../api-types' +} from '../../../shared/workspace-disk-space/workspace-space-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { WorkspaceSpaceChange } from '../../../shared/workspace-disk-space/workspace-space-change' +import type { PreloadApi } from '../../api-types' export const workspaceSpaceApi = { analyze: () => ipcRenderer.invoke('workspaceSpace:analyze'), diff --git a/src/preload/api/worktree-api.ts b/src/preload/api/workspaces/worktree-api.ts similarity index 88% rename from src/preload/api/worktree-api.ts rename to src/preload/api/workspaces/worktree-api.ts index c2cb7654a05..93aeff158b6 100644 --- a/src/preload/api/worktree-api.ts +++ b/src/preload/api/workspaces/worktree-api.ts @@ -1,5 +1,5 @@ -import type { WorkspaceMetadataSet } from '../../shared/worktree/workspace-metadata-set' -import type { SparsePresetFailure } from '../../shared/worktree/sparse-preset-failure' +import type { WorkspaceMetadataSet } from '../../../shared/worktree/metadata/workspace-metadata-set' +import type { SparsePresetFailure } from '../../../shared/worktree/creation/sparse-preset-failure' import type { ForgetRemovedWorktreesForExecutionHostArgs, ForgetRemovedWorktreesForExecutionHostResult, @@ -9,20 +9,20 @@ import type { ListDetectedWorktreesArgs, ListKnownWorktreesForExecutionHostArgs, ProviderRequestId -} from '../../shared/detected-worktree-provider-contract' -import type { NestedWorktreeRemovalApproval } from '../../shared/worktree/nested-removal' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { WorkspaceSleepOutcome, WorkspaceSleepRequest } from '../../shared/workspace-sleep' -import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' +} from '../../../shared/detected-worktree-provider-contract' +import type { NestedWorktreeRemovalApproval } from '../../../shared/worktree/removal/nested-removal' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { WorkspaceSleepOutcome, WorkspaceSleepRequest } from '../../../shared/workspace-sleep' +import type { RetiredNameRegistry } from '../../../shared/worktree/naming/retired-name-registry' import type { FolderWorkspacePathStatus, FolderWorkspacePathStatusRequest -} from '../../shared/folder-workspaces/folder-workspace-path-status' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' +} from '../../../shared/folder-workspaces/folder-workspace-path-status' +import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' import type { WorktreeBaseStatusEvent, WorktreeRemoteBranchConflictEvent -} from '../../shared/worktree/base-ref-drift-types' +} from '../../../shared/worktree/base-refs/base-ref-drift-types' import type { AdoptProvisionedRootArgs, CreateWorktreeArgs, @@ -33,9 +33,9 @@ import type { RunApprovedWorktreeSetupArgs, RunApprovedWorktreeSetupResult, SparsePreset -} from '../../shared/worktree/create-types' -import type { WorkspaceLineage, WorktreeLineage } from '../../shared/worktree/lineage-types' -import type { WorktreeMeta } from '../../shared/worktree/meta-types' +} from '../../../shared/worktree/create-types' +import type { WorkspaceLineage, WorktreeLineage } from '../../../shared/worktree/lineage-types' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import type { DetectedWorktreeListResult, GitHubPrStartPoint, @@ -44,7 +44,7 @@ import type { GitWorktreeInfo, Worktree, WorktreeHeadIdentity -} from '../../shared/worktree/types' +} from '../../../shared/worktree/types' export type WorktreeApi = { /** Retired names prevent path reuse; fully spent tiers are compacted into a watermark. */ diff --git a/src/preload/api/worktrees-bridge.ts b/src/preload/api/workspaces/worktrees-bridge.ts similarity index 93% rename from src/preload/api/worktrees-bridge.ts rename to src/preload/api/workspaces/worktrees-bridge.ts index 9bbfb55fed1..d2199d02d4e 100644 --- a/src/preload/api/worktrees-bridge.ts +++ b/src/preload/api/workspaces/worktrees-bridge.ts @@ -2,14 +2,14 @@ import { ipcRenderer } from 'electron' import type { WorktreeBaseStatusEvent, WorktreeRemoteBranchConflictEvent -} from '../../shared/worktree/base-ref-drift-types' -import type { CreateWorktreeProgressEvent } from '../../shared/worktree/create-types' +} from '../../../shared/worktree/base-refs/base-ref-drift-types' +import type { CreateWorktreeProgressEvent } from '../../../shared/worktree/create-types' import type { GitStatusMetadataChangedEvent, WorktreeHeadIdentity -} from '../../shared/worktree/types' -import type { PreloadApi } from '../api-types' -import type { WorkspaceMetadataSet } from '../../shared/worktree/workspace-metadata-set' +} from '../../../shared/worktree/types' +import type { PreloadApi } from '../../api-types' +import type { WorkspaceMetadataSet } from '../../../shared/worktree/metadata/workspace-metadata-set' export const worktreesApi = { listRetiredNames: (args) => ipcRenderer.invoke('worktrees:listRetiredNames', args), diff --git a/src/preload/api/wsl-bridge.ts b/src/preload/api/wsl/wsl-bridge.ts similarity index 83% rename from src/preload/api/wsl-bridge.ts rename to src/preload/api/wsl/wsl-bridge.ts index bc7869000e4..682cb6820ad 100644 --- a/src/preload/api/wsl-bridge.ts +++ b/src/preload/api/wsl/wsl-bridge.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import type { PreloadApi } from '../api-types' +import type { PreloadApi } from '../../api-types' export const wslApi = { isAvailable: (): Promise => ipcRenderer.invoke('wsl:isAvailable'), diff --git a/src/preload/api/wsl-drive-project-bridge.ts b/src/preload/api/wsl/wsl-drive-project-bridge.ts similarity index 93% rename from src/preload/api/wsl-drive-project-bridge.ts rename to src/preload/api/wsl/wsl-drive-project-bridge.ts index dbefb68f3df..75a8d93837c 100644 --- a/src/preload/api/wsl-drive-project-bridge.ts +++ b/src/preload/api/wsl/wsl-drive-project-bridge.ts @@ -2,7 +2,7 @@ import { ipcRenderer } from 'electron' import type { WslDriveProjectConversionResult, WslDriveProjectPreview -} from '../../shared/wsl-drive-project-types' +} from '../../../shared/wsl-drive-project-types' /** Converting a WSL project on a Windows drive to Windows Git; main gates every call. */ export type WslDriveProjectApi = { diff --git a/src/preload/api/wsl-drive-unc-conversion-bridge.ts b/src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts similarity index 77% rename from src/preload/api/wsl-drive-unc-conversion-bridge.ts rename to src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts index 13fb158c4b8..d4b03d5b78e 100644 --- a/src/preload/api/wsl-drive-unc-conversion-bridge.ts +++ b/src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts @@ -2,9 +2,9 @@ import { ipcRenderer } from 'electron' import type { WslDriveUncConversionRequest, WslDriveUncConversionResult -} from '../../shared/wsl-drive-unc-conversion-types' -import type { WslDriveUncPendingRendererRewrite } from '../../shared/wsl-drive-unc-renderer-store-keys' -import type { WslMoveRecordStoreRewrittenResult } from '../../shared/wsl-move/wsl-move-renderer-rewrite-types' +} from '../../../shared/wsl-drive-unc-conversion-types' +import type { WslDriveUncPendingRendererRewrite } from '../../../shared/wsl-drive-unc-renderer-store-keys' +import type { WslMoveRecordStoreRewrittenResult } from '../../../shared/wsl-move/wsl-move-renderer-rewrite-types' /** Converting a UNC Windows-drive project to its drive path; main gates every call. */ export type WslDriveUncConversionApi = { diff --git a/src/preload/api/wsl-hosts-api.ts b/src/preload/api/wsl/wsl-hosts-api.ts similarity index 96% rename from src/preload/api/wsl-hosts-api.ts rename to src/preload/api/wsl/wsl-hosts-api.ts index f90511203fe..9e15134441a 100644 --- a/src/preload/api/wsl-hosts-api.ts +++ b/src/preload/api/wsl/wsl-hosts-api.ts @@ -9,8 +9,8 @@ import { type WslHostDistro, type WslHostServerStop, type WslHostStatus -} from '../../shared/wsl-host-types' -import { isWslHostsServingForWindow } from '../../shared/wsl-host-internal-gate' +} from '../../../shared/wsl-host-types' +import { isWslHostsServingForWindow } from '../../../shared/wsl-host-internal-gate' export type WslHostsPreloadApi = { getCapability: () => Promise diff --git a/src/preload/api/wsl-move-bridge.ts b/src/preload/api/wsl/wsl-move-bridge.ts similarity index 95% rename from src/preload/api/wsl-move-bridge.ts rename to src/preload/api/wsl/wsl-move-bridge.ts index 75f4d13bc89..e7b0786d30b 100644 --- a/src/preload/api/wsl-move-bridge.ts +++ b/src/preload/api/wsl/wsl-move-bridge.ts @@ -6,22 +6,22 @@ import { type WslMoveRequest, type WslMoveResult, type WslMoveUnfinished -} from '../../shared/wsl-move/wsl-move-driver-types' +} from '../../../shared/wsl-move/wsl-move-driver-types' import type { WslMovePendingRendererRewrite, WslMoveRecordStoreRewrittenRequest, WslMoveRecordStoreRewrittenResult -} from '../../shared/wsl-move/wsl-move-renderer-rewrite-types' +} from '../../../shared/wsl-move/wsl-move-renderer-rewrite-types' import type { WslMovedProjectKind, WslMoveUseLocallyResult -} from '../../shared/wsl-move/wsl-moved-project' +} from '../../../shared/wsl-move/wsl-moved-project' import { WSL_MOVE_ORCHESTRATOR_SLEPT_PANES_REQUEST_CHANNEL, WSL_MOVE_ORCHESTRATOR_STATUS_CHANNEL, type WslMoveOrchestratorRecord, type WslMoveOrchestratorUserAction -} from '../../shared/wsl-move/wsl-move-orchestrator-types' +} from '../../../shared/wsl-move/wsl-move-orchestrator-types' /** A WSL move and the renderer half of its desktop rewrite; main gates every call. */ export type WslMoveApi = { diff --git a/src/preload/app-restart-checkpoint-routing.test.ts b/src/preload/app-restart-checkpoint-routing.test.ts deleted file mode 100644 index a62da40ea76..00000000000 --- a/src/preload/app-restart-checkpoint-routing.test.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreloadApi } from './api-types' -import { - ORCA_APP_RESTART_ABORTED_EVENT, - ORCA_APP_RESTART_STARTED_EVENT -} from '../shared/updater-renderer-events' -import { KEYBOARD_LAYOUT_CHANGED_CHANNEL } from '../shared/keyboard-layout-events' - -const { exposeInMainWorld, invoke, on, removeListener, send, sendSync, getPathForFile } = - vi.hoisted(() => ({ - exposeInMainWorld: vi.fn(), - invoke: vi.fn(), - on: vi.fn(), - removeListener: vi.fn(), - send: vi.fn(), - sendSync: vi.fn(), - getPathForFile: vi.fn(() => '/files/notes.txt') - })) - -vi.mock('electron', () => ({ - contextBridge: { exposeInMainWorld }, - ipcRenderer: { invoke, on, removeListener, send, sendSync }, - webFrame: { - getZoomFactor: vi.fn(() => 1), - setZoomFactor: vi.fn(), - setVisualZoomLevelLimits: vi.fn() - }, - webUtils: { getPathForFile } -})) - -describe('native preload destructive app actions', () => { - const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') - let eventTarget: EventTarget - - beforeEach(() => { - vi.resetModules() - exposeInMainWorld.mockReset() - invoke.mockReset() - on.mockReset() - removeListener.mockReset() - send.mockReset() - sendSync.mockReset() - Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) - eventTarget = new EventTarget() - vi.stubGlobal('window', eventTarget) - vi.stubGlobal('document', { addEventListener: vi.fn() }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - if (originalContextIsolated) { - Object.defineProperty(process, 'contextIsolated', originalContextIsolated) - } else { - Reflect.deleteProperty(process, 'contextIsolated') - } - }) - - const loadApi = async (): Promise => { - await import('./index') - return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - } - - it('exposes synchronous file path resolution and a window-local preparation invoke', async () => { - const api = await loadApi() - const file = new File(['x'], 'notes.txt') - expect(api).not.toHaveProperty('getPathForFile') - expect(api.fs.getPathForFile?.(file)).toBe('/files/notes.txt') - expect(getPathForFile).toHaveBeenCalledWith(file) - const request = { paths: ['/files/notes.txt'], consumer: 'agent' as const } - invoke.mockResolvedValue({ paths: request.paths, failures: [] }) - await expect(api.fs.prepareDroppedPaths(request)).resolves.toEqual({ - paths: request.paths, - failures: [] - }) - expect(invoke).toHaveBeenCalledExactlyOnceWith('fs:prepareDroppedPaths', request) - }) - - for (const action of ['reload', 'relaunch'] as const) { - it(`prepares and awaits durability before ${action}`, async () => { - const api = await loadApi() - const calls: string[] = [] - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, () => calls.push('prepared')) - invoke.mockImplementation(async (channel: string) => { - calls.push(channel) - return channel === 'app:await-before-unload-checkpoint' ? { ok: true } : undefined - }) - - await api.app[action]() - - expect(calls).toEqual(['prepared', 'app:await-before-unload-checkpoint', `app:${action}`]) - }) - - it(`refuses ${action} when the durable checkpoint fails`, async () => { - const api = await loadApi() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - invoke.mockImplementation(async (channel: string) => - channel === 'app:await-before-unload-checkpoint' ? { ok: false } : undefined - ) - - await expect(api.app[action]()).rejects.toThrow( - 'Failed to persist renderer state before unload.' - ) - - expect(invoke).not.toHaveBeenCalledWith(`app:${action}`) - expect(aborted).toHaveBeenCalledTimes(1) - }) - } - - it('exposes the durable checkpoint join the lazy-chunk recovery reload depends on', async () => { - const api = await loadApi() - invoke.mockResolvedValue({ ok: true }) - - await expect(api.app.awaitBeforeUnloadCheckpoint()).resolves.toBeUndefined() - expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') - - invoke.mockResolvedValue({ ok: false }) - - await expect(api.app.awaitBeforeUnloadCheckpoint()).rejects.toThrow( - 'Failed to persist renderer state before unload.' - ) - }) - - it('preserves both macOS keyboard preload adapters', async () => { - const api = await loadApi() - invoke.mockResolvedValue(undefined) - - await api.app.getMacCapturedDigitRowChords() - await api.app.getKeyboardLayoutSnapshot() - const onKeyboardLayoutChanged = vi.fn() - const unsubscribe = api.app.onKeyboardLayoutChanged(onKeyboardLayoutChanged) - const listener = on.mock.calls.find( - ([channel]) => channel === KEYBOARD_LAYOUT_CHANGED_CHANNEL - )?.[1] as ((event: unknown, payload: unknown) => void) | undefined - const payload = { phase: 'invalidated', generation: 1 } - listener?.({}, payload) - unsubscribe() - - expect(invoke).toHaveBeenCalledWith('app:getMacCapturedDigitRowChords') - expect(invoke).toHaveBeenCalledWith('app:getKeyboardLayoutSnapshot') - expect(onKeyboardLayoutChanged).toHaveBeenCalledExactlyOnceWith(payload) - expect(removeListener).toHaveBeenCalledWith(KEYBOARD_LAYOUT_CHANGED_CHANNEL, listener) - }) - - it('awaits renderer durability before profile maintenance and preserves its result', async () => { - const api = await loadApi() - const started = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) - let finishCheckpoint = (_result: { ok: boolean }): void => {} - const checkpoint = new Promise((resolve) => { - finishCheckpoint = resolve - }) - const result = { status: 'relaunching' } - invoke.mockImplementation((channel: string) => - channel === 'app:await-before-unload-checkpoint' ? checkpoint : Promise.resolve(result) - ) - - const switching = api.orcaProfiles.switchProfile({ profileId: 'target' }) - await vi.waitFor(() => - expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') - ) - expect(started).toHaveBeenCalledOnce() - expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything()) - finishCheckpoint({ ok: true }) - await expect(switching).resolves.toBe(result) - expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:switch', { profileId: 'target' }) - }) - - it.each(['checkpoint-failed', 'switch-failed', 'already-active'])( - 'resets restart preparation when profile switching returns %s', - async (outcome) => { - const api = await loadApi() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - invoke.mockImplementation(async (channel: string) => { - if (channel === 'app:await-before-unload-checkpoint') { - return { ok: outcome !== 'checkpoint-failed' } - } - if (outcome === 'switch-failed') { - throw new Error('switch failed') - } - return { status: 'already-active' } - }) - const switching = api.orcaProfiles.switchProfile({ profileId: 'target' }) - await (outcome === 'already-active' - ? expect(switching).resolves.toEqual({ status: 'already-active' }) - : expect(switching).rejects.toThrow()) - expect(aborted).toHaveBeenCalledOnce() - if (outcome === 'checkpoint-failed') { - expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything()) - } - } - ) - - it.each(['move', 'copy', 'inactive', 'duplicate', 'recovery'] as const)( - 'prepares only a potentially relaunching project transfer: %s', - async (outcome) => { - const api = await loadApi() - const started = vi.fn() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - const args = { - sourceProfileId: outcome === 'inactive' ? 'inactive' : 'active', - targetProfileId: 'target', - repoId: 'repo', - mode: outcome === 'copy' ? ('copy' as const) : ('move' as const) - } - const result = - outcome === 'duplicate' - ? { status: 'duplicate-target' } - : { status: 'transferred', willRelaunch: outcome === 'move' } - invoke.mockImplementation(async (channel: string) => { - if (channel === 'orcaProfiles:list') { - return { activeProfileId: 'active' } - } - if (channel === 'app:await-before-unload-checkpoint') { - return { ok: true } - } - if (outcome === 'recovery') { - const listener = on.mock.calls.find(([name]) => name === 'app:restart-committed')?.[1] - expect(listener).toBeTypeOf('function') - listener() - throw new Error('move requires recovery') - } - return result - }) - - const transfer = api.orcaProfiles.transferProject(args) - await (outcome === 'recovery' - ? expect(transfer).rejects.toThrow('move requires recovery') - : expect(transfer).resolves.toBe(result)) - const needsPreparation = outcome !== 'copy' && outcome !== 'inactive' - expect(started).toHaveBeenCalledTimes(needsPreparation ? 1 : 0) - expect(aborted).toHaveBeenCalledTimes(outcome === 'duplicate' ? 1 : 0) - expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:transferProject', args) - } - ) -}) diff --git a/src/preload/browser-extension-content-script-api.ts b/src/preload/browser-extension-content-script-api.ts index 70617263a18..3e5c0779803 100644 --- a/src/preload/browser-extension-content-script-api.ts +++ b/src/preload/browser-extension-content-script-api.ts @@ -1,12 +1,12 @@ import { createContentScriptRelayBridge, installContentScriptRelayFilter -} from './browser-extension-content-script-relay' -import { installBrowserExtensionInertApis } from './browser-extension-inert-apis' +} from './browser/extensions/messaging/browser-extension-content-script-relay' +import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis' import { installBrowserExtensionStorageSync, PRELOAD_STORAGE_SYNC_CONSTANTS -} from './browser-extension-storage-sync' +} from './browser/extensions/storage/browser-extension-storage-sync' /** * Orca's content script, bundled into one standalone file that Orca's manifest rewrite puts first diff --git a/src/preload/browser-extension-document-targets.test.ts b/src/preload/browser-extension-document-targets.test.ts deleted file mode 100644 index c58e19fee45..00000000000 --- a/src/preload/browser-extension-document-targets.test.ts +++ /dev/null @@ -1,377 +0,0 @@ -import { runInNewContext } from 'node:vm' -import { webcrypto } from 'node:crypto' -import { describe, expect, it, vi } from 'vitest' -import { - installBrowserExtensionDocumentTargets, - PRELOAD_DOCUMENT_TARGETS_NAMESPACE, - PRELOAD_FIRST_DISCARDED_TAB_ID -} from './browser-extension-document-targets' - -const DISCARDED_TAB = PRELOAD_FIRST_DISCARDED_TAB_ID + 3 - -const ORCA_TOP = 'A'.repeat(32) -const ORCA_AD = 'B'.repeat(32) -const CHROMIUM_TOP = 'C'.repeat(32) -const CHROMIUM_AD = 'D'.repeat(32) - -type NativeListener = (message: unknown, sender: unknown, respond: (value: unknown) => void) => void - -function navigatingDocumentTarget(navigateOnLookup = 1) { - let current = 'old-document' - const delivered: string[] = [] - const listeners = new Set() - const runtime = { - id: 'extension', - getManifest: () => ({ permissions: ['webNavigation', 'scripting'] }), - onMessage: { - addListener: (listener: NativeListener) => listeners.add(listener), - removeListener: (listener: NativeListener) => listeners.delete(listener) - } - } - const chrome = { - runtime, - scripting: { - executeScript: async (injection: { - target: { documentIds?: string[]; tabId: number } - func?: () => unknown - }) => { - if (injection.target.documentIds?.some((id) => id !== current)) { - throw new Error('No matching document') - } - const result = injection.func?.() - return [{ frameId: 0, documentId: current, result }] - } - }, - tabs: { - sendMessage: async (_tabId: number, message: unknown, options?: { documentId?: string }) => { - if (options?.documentId && options.documentId !== current) { - throw new Error('No matching document') - } - if (typeof message === 'string') { - delivered.push(current) - return 'received' - } - for (const listener of listeners) { - listener( - { - orcaDocumentTargetProbe: { - ...(message && - typeof message === 'object' && - 'orcaDocumentTargetProbe' in message && - message.orcaDocumentTargetProbe && - typeof message.orcaDocumentTargetProbe === 'object' - ? message.orcaDocumentTargetProbe - : {}), - response: true - } - }, - { id: 'extension', tab: { id: 3 }, frameId: 0, documentId: current }, - () => {} - ) - } - return true - } - } - } - let lookups = 0 - const bridge = { - call: async () => { - const value = [{ frameId: 0, documentId: current }] - if (++lookups === navigateOnLookup) { - current = 'new-document' - } - return { ok: true as const, value } - }, - listen: () => {}, - onEvent: () => {}, - passesFilter: () => true - } - const realm = { chrome, crypto: webcrypto, setTimeout, clearTimeout } - runInNewContext(`(${installBrowserExtensionDocumentTargets.toString()})(bridge, first)`, { - ...realm, - globalThis: realm, - bridge, - first: PRELOAD_FIRST_DISCARDED_TAB_ID - }) - return { chrome, delivered, listeners } -} - -/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ -function install(permissions: string[], nativeScripting = true) { - const nativeListeners = new Set() - const executeScript = vi.fn( - async (injection: { target: Record; func?: () => unknown }) => { - const frameIds = Array.isArray(injection.target.frameIds) - ? injection.target.frameIds - : Array.isArray(injection.target.documentIds) - ? injection.target.documentIds.map((id) => (id === CHROMIUM_AD ? 42 : 0)) - : [0] - return frameIds.map((frameId: number) => ({ - frameId, - documentId: frameId === 42 ? CHROMIUM_AD : CHROMIUM_TOP, - result: frameId - })) - } - ) - const insertCSS = vi.fn((_injection: unknown, callback?: () => void) => { - callback?.() - return callback ? undefined : Promise.resolve() - }) - const sendMessage = vi.fn( - async ( - tabId: number, - message: unknown, - options?: { frameId?: number; documentId?: string }, - _callback?: () => void - ): Promise => { - if (message && typeof message === 'object' && 'orcaDocumentTargetProbe' in message) { - const frameId = options?.frameId ?? 0 - const probe = message.orcaDocumentTargetProbe - for (const listener of nativeListeners) { - listener( - { - orcaDocumentTargetProbe: { - ...(typeof probe === 'object' ? probe : {}), - response: true - } - }, - { - id: 'extension', - tab: { id: tabId }, - frameId, - documentId: frameId === 42 ? CHROMIUM_AD : CHROMIUM_TOP - }, - () => {} - ) - } - return true - } - return 'pong' - } - ) - const scripting = { executeScript, insertCSS, removeCSS: vi.fn(async () => {}) } - const tabs = { sendMessage } - const calls: unknown[][] = [] - const bridge = { - call: async (namespace: string, method: string, args: unknown[]) => { - // Main's tabs.get: a discarded tab, or (once replaced by its loaded guest) no tab. - if (namespace === 'tabs' && method === 'get') { - return args[0] === DISCARDED_TAB - ? { ok: true as const, value: { id: DISCARDED_TAB, discarded: true } } - : { ok: false as const, error: `No tab with id: ${String(args[0])}.` } - } - expect([namespace, method]).toEqual([PRELOAD_DOCUMENT_TARGETS_NAMESPACE, 'frames']) - calls.push(args) - return { - ok: true as const, - value: [ - { frameId: 0, documentId: ORCA_TOP }, - { frameId: 42, documentId: ORCA_AD } - ] - } - }, - listen: () => {}, - onEvent: () => {}, - passesFilter: () => true - } - const runtime: { - id: string - getManifest: () => unknown - lastError?: unknown - onMessage: { - addListener: (listener: NativeListener) => void - removeListener: (listener: NativeListener) => void - } - } = { - id: 'extension', - getManifest: () => ({ permissions }), - onMessage: { - addListener: (listener) => { - nativeListeners.add(listener) - }, - removeListener: (listener) => { - nativeListeners.delete(listener) - } - } - } - const chrome = { runtime, scripting, tabs } - // `browser` shares chrome's namespace objects, as Orca's installer mirrors them. - const realm = { - chrome: nativeScripting ? chrome : { runtime, tabs }, - browser: nativeScripting ? { scripting, tabs } : { tabs }, - crypto: webcrypto, - setTimeout, - clearTimeout, - Promise, - Map, - Set, - Object, - Array - } - runInNewContext(`(${installBrowserExtensionDocumentTargets.toString()})(bridge, first)`, { - ...realm, - globalThis: realm, - bridge, - first: PRELOAD_FIRST_DISCARDED_TAB_ID, - Error - }) - return { chrome, executeScript, insertCSS, sendMessage, calls, nativeListeners } -} - -describe('Orca documentIds in native scripting targets', () => { - it.each([1, 2])( - 'rejects script navigation at discovery snapshot %i before executing user code', - async (snapshot) => { - const { chrome } = navigatingDocumentTarget(snapshot) - const userCode = vi.fn() - - await expect( - chrome.scripting.executeScript({ - target: { documentIds: ['old-document'], tabId: 3 }, - func: userCode - }) - ).rejects.toThrow(/document/i) - - expect(userCode).not.toHaveBeenCalled() - } - ) - - it.each([1, 2])( - 'rejects message navigation at discovery snapshot %i before delivering the payload', - async (snapshot) => { - const { chrome, delivered, listeners } = navigatingDocumentTarget(snapshot) - - await expect( - chrome.tabs.sendMessage(3, 'document-specific secret', { - documentId: 'old-document' - }) - ).rejects.toThrow(/document/i) - - expect(delivered).toEqual([]) - expect(listeners.size).toBe(0) - } - ) - - it("preserves a native document constraint for Orca's document ids", async () => { - const { chrome, executeScript, calls } = install(['webNavigation', 'scripting']) - const results = await chrome.scripting.executeScript({ - target: { tabId: 3, documentIds: [ORCA_AD] }, - func: () => 1 - }) - expect(executeScript).toHaveBeenCalledTimes(2) - expect(executeScript.mock.calls[1][0].target).toEqual({ tabId: 3, documentIds: [CHROMIUM_AD] }) - expect(results).toEqual([{ frameId: 42, documentId: ORCA_AD, result: 42 }]) - expect(calls).toEqual([[3], [3]]) - }) - - it("passes Chromium's own ids through and keeps the callback form", async () => { - const { chrome, executeScript, insertCSS, sendMessage } = install(['webRequest']) - await chrome.scripting.executeScript({ target: { tabId: 3, documentIds: [CHROMIUM_TOP] } }) - expect(executeScript.mock.calls[0][0].target).toEqual({ tabId: 3, documentIds: [CHROMIUM_TOP] }) - - const done = await new Promise((resolve) => - chrome.scripting.insertCSS( - { target: { tabId: 3, documentIds: [ORCA_TOP] }, css: 'a{}' }, - () => resolve('called back') - ) - ) - expect(done).toBe('called back') - expect(insertCSS.mock.calls[0][0]).toEqual({ - target: { tabId: 3, documentIds: [CHROMIUM_TOP] }, - css: 'a{}' - }) - - await chrome.tabs.sendMessage(3, 'ping', { documentId: ORCA_AD }) - expect(sendMessage).toHaveBeenCalledWith(3, 'ping', { documentId: CHROMIUM_AD }) - }) - - it.each([false, true])( - 'resolves message recipients without requiring scripting even when the namespace exists: %s', - async (nativeScripting) => { - const { chrome, executeScript, sendMessage, nativeListeners } = install( - ['webNavigation'], - nativeScripting - ) - executeScript.mockRejectedValueOnce(new Error('Requires scripting permission')) - - await expect(chrome.tabs.sendMessage(3, 'ping', { documentId: ORCA_AD })).resolves.toBe( - 'pong' - ) - - expect(sendMessage).toHaveBeenLastCalledWith(3, 'ping', { documentId: CHROMIUM_AD }) - expect(executeScript).toHaveBeenCalledTimes(nativeScripting ? 1 : 0) - expect(nativeListeners.size).toBe(0) - } - ) - - it('reaches dynamically injected message listeners that do not handle private probes', async () => { - const { chrome, sendMessage, nativeListeners } = install(['webNavigation', 'scripting']) - sendMessage.mockImplementationOnce(async (_tabId, message) => { - if (typeof message !== 'string') { - throw new Error('Unexpected private packet') - } - return 'dynamic receiver response' - }) - - await expect( - chrome.tabs.sendMessage(3, 'real payload', { documentId: ORCA_TOP }) - ).resolves.toBe('dynamic receiver response') - - expect(sendMessage).toHaveBeenCalledTimes(1) - expect(sendMessage).toHaveBeenCalledWith(3, 'real payload', { documentId: CHROMIUM_TOP }) - expect(nativeListeners.size).toBe(0) - }) - - it('never labels an unexpected native document as the requested Orca document', async () => { - const { chrome, executeScript } = install(['webNavigation', 'scripting']) - executeScript.mockResolvedValueOnce([{ frameId: 0, documentId: CHROMIUM_TOP, result: 0 }]) - executeScript.mockResolvedValueOnce([ - { frameId: 0, documentId: 'replacement-document', result: 1 } - ]) - - await expect( - chrome.scripting.executeScript({ - target: { tabId: 3, documentIds: [ORCA_TOP] } - }) - ).resolves.toEqual([{ frameId: 0, documentId: 'replacement-document', result: 1 }]) - }) - - it('cleans up failed identity probes and reports callback errors without delivering the payload', async () => { - const { chrome, sendMessage, nativeListeners } = install(['webNavigation'], false) - sendMessage.mockRejectedValueOnce(new Error('Receiving end does not exist')) - const callback = vi.fn() - const error = await new Promise((resolve) => { - chrome.tabs.sendMessage(3, 'private payload', { documentId: ORCA_TOP }, () => { - callback() - resolve(chrome.runtime.lastError) - }) - }) - - expect(error).toEqual({ message: 'Receiving end does not exist' }) - expect(callback).toHaveBeenCalledTimes(1) - expect(sendMessage).toHaveBeenCalledTimes(1) - expect(chrome.runtime.lastError).toBeUndefined() - expect(nativeListeners.size).toBe(0) - }) -}) - -describe('calls to a discarded tab', () => { - it("fail with Chrome's errors instead of reaching Electron", async () => { - const { chrome, executeScript, sendMessage } = install(['scripting']) - await expect( - chrome.scripting.executeScript({ target: { tabId: DISCARDED_TAB }, func: () => 1 }) - ).rejects.toThrow('Cannot access contents of url ""') - await expect(chrome.tabs.sendMessage(DISCARDED_TAB, 'ping')).rejects.toThrow( - 'Could not establish connection. Receiving end does not exist.' - ) - const lastError = await new Promise((resolve) => - chrome.scripting.insertCSS({ target: { tabId: DISCARDED_TAB }, css: 'a{}' }, () => - resolve(chrome.runtime.lastError) - ) - ) - expect(lastError).toEqual({ message: expect.stringContaining('Cannot access contents') }) - expect(chrome.runtime.lastError).toBeUndefined() - expect(executeScript).not.toHaveBeenCalled() - expect(sendMessage).not.toHaveBeenCalled() - }) -}) diff --git a/src/preload/browser-extension-native-messaging.test.ts b/src/preload/browser-extension-native-messaging.test.ts deleted file mode 100644 index fdfc7c30987..00000000000 --- a/src/preload/browser-extension-native-messaging.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { runInNewContext } from 'node:vm' -import { describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionInvokeReply } from './browser-extension-main-world' -import { - installBrowserExtensionNativeMessaging, - PRELOAD_NATIVE_MESSAGING_NAMESPACE, - type BrowserExtensionNativeMessagingContext -} from './browser-extension-native-messaging' - -type Reply = BrowserExtensionInvokeReply -type Call = { method: string; args: unknown[] } - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' -} - -/** Calls `path` (e.g. 'onMessage.addListener') on `owner` with its parent as `this`. */ -function call(owner: unknown, path: string, ...args: unknown[]): unknown { - const keys = path.split('.') - const leaf = keys.pop() ?? '' - const parent = keys.reduce( - (value, key) => (isRecord(value) ? value[key] : undefined), - owner - ) - const fn = isRecord(parent) ? parent[leaf] : undefined - if (typeof fn !== 'function') { - throw new Error(`${path} is not a function`) - } - return fn.apply(parent, args) -} - -/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ -function install( - permissions: Record, - context: BrowserExtensionNativeMessagingContext = 'page' -) { - const runtime: Record = { getManifest: () => permissions } - const browserRuntime: Record = {} - const calls: Call[] = [] - const listens: unknown[][] = [] - const pending = new Map void>() - let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null - const bridge = { - call: (namespace: string, method: string, args: unknown[]) => { - expect(namespace).toBe(PRELOAD_NATIVE_MESSAGING_NAMESPACE) - calls.push({ method, args }) - return new Promise((resolve) => pending.set(`${method}:${String(args[0])}`, resolve)) - }, - listen: (namespace: string, event: string, active: boolean) => - listens.push([namespace, event, active]), - onEvent: (handler: typeof dispatch) => { - dispatch = handler - }, - passesFilter: () => true - } - const error = vi.fn() - const realm = { - chrome: { runtime }, - browser: { runtime: browserRuntime }, - console: { error }, - JSON, - Math, - Date, - Promise - } - runInNewContext(`(${installBrowserExtensionNativeMessaging.toString()})(bridge, context)`, { - ...realm, - globalThis: realm, - bridge, - context - }) - return { - runtime, - browserRuntime, - calls, - listens, - error, - /** The id the installer chose for the n-th call's port. */ - portId: (index = 0) => String(calls[index]?.args[0]), - lastError: () => (isRecord(runtime.lastError) ? runtime.lastError.message : undefined), - reply: (key: string, value: Reply) => pending.get(key)?.(value), - emit: (args: unknown[]) => dispatch?.(PRELOAD_NATIVE_MESSAGING_NAMESPACE, 'onPortEvent', args) - } -} - -const tick = () => new Promise((resolve) => setTimeout(resolve, 0)) - -describe('chrome.runtime native messaging in extension contexts', () => { - it('queues posts until the host runs and routes replies by port', async () => { - const page = install({ permissions: ['nativeMessaging'] }) - const port = call(page.runtime, 'connectNative', 'com.example.vault') - const received: unknown[][] = [] - call(port, 'onMessage.addListener', (message: unknown, from: unknown) => - received.push([message, from === port]) - ) - call(port, 'postMessage', { hello: 'é' }) - expect(isRecord(port) && port.name).toBe('') - const id = page.portId() - expect(page.calls).toEqual([{ method: 'connect', args: [id, 'com.example.vault'] }]) - // A reply can beat the connect answer; it still reaches the port. - page.emit([id, 'message', '{"early":true}']) - page.reply(`connect:${id}`, { ok: true, value: undefined }) - await tick() - expect(page.calls[1]).toEqual({ method: 'postMessage', args: [id, '{"hello":"é"}'] }) - page.emit(['another-port', 'message', '{"stray":1}']) - expect(received).toEqual([[{ early: true }, true]]) - expect(page.listens).toEqual([]) - }) - - it('fires onDisconnect with runtime.lastError set only during the call', async () => { - const page = install({ permissions: ['nativeMessaging'] }) - const port = call(page.runtime, 'connectNative', 'com.example.missing') - const seen: unknown[] = [] - call(port, 'onDisconnect.addListener', () => seen.push(page.lastError())) - page.reply(`connect:${page.portId()}`, { - ok: false, - error: 'Specified native messaging host not found.' - }) - await tick() - expect(seen).toEqual(['Specified native messaging host not found.']) - expect(page.runtime.lastError).toBeUndefined() - expect(() => call(port, 'postMessage', 1)).toThrow( - 'Attempting to use a disconnected port object' - ) - }) - - it('lets main release a port the extension dropped while it was starting', async () => { - const worker = install({ permissions: ['nativeMessaging'] }, 'worker') - const port = call(worker.runtime, 'connectNative', 'com.example.vault') - expect(worker.listens).toEqual([[PRELOAD_NATIVE_MESSAGING_NAMESPACE, 'onPortEvent', true]]) - call(port, 'disconnect') - worker.reply(`connect:${worker.portId()}`, { ok: true, value: undefined }) - await tick() - expect(worker.calls.at(-1)).toEqual({ method: 'disconnect', args: [worker.portId()] }) - }) - - it('answers sendNativeMessage with a promise, or a callback that sees lastError', async () => { - const page = install({ permissions: ['nativeMessaging'] }) - const promised = call(page.runtime, 'sendNativeMessage', 'com.example.vault', { q: 1 }) - expect(page.calls[0]).toEqual({ - method: 'sendNativeMessage', - args: ['com.example.vault', '{"q":1}'] - }) - page.reply('sendNativeMessage:com.example.vault', { ok: true, value: '{"a":2}' }) - await expect(promised).resolves.toEqual({ a: 2 }) - - const results: unknown[] = [] - call(page.runtime, 'sendNativeMessage', 'com.example.gone', 1, (response: unknown) => - results.push([response, page.lastError()]) - ) - await tick() - page.reply('sendNativeMessage:com.example.gone', { - ok: false, - error: 'Native host has exited.' - }) - await tick() - expect(results).toEqual([[undefined, 'Native host has exited.']]) - }) -}) diff --git a/src/preload/browser-extension-preload.ts b/src/preload/browser-extension-preload.ts index 43aa35d0415..82df2ff05b1 100644 --- a/src/preload/browser-extension-preload.ts +++ b/src/preload/browser-extension-preload.ts @@ -3,30 +3,30 @@ import { BROWSER_EXTENSION_API_SURFACE, PRELOAD_BROWSER_EXTENSION_EVENT_CHANNEL, PRELOAD_BROWSER_EXTENSION_INVOKE_CHANNEL -} from './browser-extension-api-surface' +} from './browser/extensions/api/browser-extension-api-surface' import { installBrowserExtensionApis, type BrowserExtensionInvokeReply, type BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' +} from './browser/extensions/api/browser-extension-main-world' import { installBrowserExtensionDocumentTargets, PRELOAD_FIRST_DISCARDED_TAB_ID -} from './browser-extension-document-targets' -import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters' -import { installBrowserExtensionInertApis } from './browser-extension-inert-apis' -import { installContentScriptRelayFilter } from './browser-extension-content-script-relay' -import { installBrowserExtensionNativeMessaging } from './browser-extension-native-messaging' -import { installBrowserExtensionFrameLifetime } from './browser-extension-frame-lifetime' -import { installBrowserExtensionStorageRelay } from './browser-extension-storage-relay' +} from './browser/extensions/documents/browser-extension-document-targets' +import { passesBrowserExtensionEventFilter } from './browser/extensions/api/browser-extension-event-filters' +import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis' +import { installContentScriptRelayFilter } from './browser/extensions/messaging/browser-extension-content-script-relay' +import { installBrowserExtensionNativeMessaging } from './browser/extensions/messaging/browser-extension-native-messaging' +import { installBrowserExtensionFrameLifetime } from './browser/extensions/api/browser-extension-frame-lifetime' +import { installBrowserExtensionStorageRelay } from './browser/extensions/storage/browser-extension-storage-relay' import { installBrowserExtensionStorageSync, PRELOAD_STORAGE_SYNC_CONSTANTS -} from './browser-extension-storage-sync' +} from './browser/extensions/storage/browser-extension-storage-sync' import { CHROME_WEB_STORE_ORIGIN, installChromeWebStoreBridge -} from './browser-extension-web-store-bridge' +} from './browser/extensions/web-store/browser-extension-web-store-bridge' const electron: { contextBridge: ContextBridge; ipcRenderer: IpcRenderer } = require('electron') const { contextBridge, ipcRenderer } = electron diff --git a/src/preload/browser-extension-storage-sync.test.ts b/src/preload/browser-extension-storage-sync.test.ts deleted file mode 100644 index 72a2bf1a8a7..00000000000 --- a/src/preload/browser-extension-storage-sync.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { runInNewContext } from 'node:vm' -import { describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionInvokeReply } from './browser-extension-main-world' -import { - installBrowserExtensionStorageSync, - PRELOAD_STORAGE_SYNC_CONSTANTS, - PRELOAD_STORAGE_SYNC_NAMESPACE -} from './browser-extension-storage-sync' - -type Runtime = { lastError?: { message: string } } - -function nativeEvent() { - const listeners = new Set() - return { - listeners, - addListener: vi.fn((callback: unknown) => listeners.add(callback)), - removeListener: vi.fn((callback: unknown) => listeners.delete(callback)) - } -} - -/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ -function install( - reply: (method: string, args: unknown[]) => BrowserExtensionInvokeReply, - forward?: (changes: unknown, from?: string) => void -) { - const runtime: Runtime = {} - const native = nativeEvent() - const nativeSync = { get: vi.fn(), set: vi.fn() } - const chrome = { runtime, storage: { local: {}, sync: nativeSync, onChanged: native } } - let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null - const calls: unknown[][] = [] - const listens: unknown[][] = [] - const bridge = { - call: async (namespace: string, method: string, args: unknown[]) => { - calls.push([namespace, method, args]) - return reply(method, args) - }, - listen: (namespace: string, event: string, active: boolean) => - listens.push([namespace, event, active]), - onEvent: (handler: typeof dispatch) => { - dispatch = handler - }, - passesFilter: () => true - } - const realm = { chrome, console, JSON, Promise } - const relay: unknown = runInNewContext( - `(${installBrowserExtensionStorageSync.toString()})(bridge, constants, forward)`, - { - ...realm, - globalThis: realm, - bridge, - constants: PRELOAD_STORAGE_SYNC_CONSTANTS, - forward - } - ) - return { - relay: (method: string, args: unknown[], from?: string): unknown => - typeof relay === 'function' ? relay(method, args, from) : undefined, - chrome, - native, - nativeSync, - calls, - listens, - emit: (changes: unknown) => dispatch?.(PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', [changes]) - } -} - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' -} - -function call(root: unknown, path: string, ...args: unknown[]): unknown { - const keys = path.split('.') - const name = keys.pop() ?? '' - const owner = keys.reduce( - (value, key) => (isRecord(value) ? value[key] : undefined), - root - ) - const fn = isRecord(owner) ? owner[name] : null - if (typeof fn !== 'function') { - throw new Error(`${path} is not a function`) - } - return fn.call(owner, ...args) -} - -describe('installBrowserExtensionStorageSync', () => { - it('replaces the disabled native area with calls to main, as promises or callbacks', async () => { - const page = install((method) => - method === 'get' ? { ok: true, value: { theme: 'dark' } } : { ok: true, value: undefined } - ) - expect(page.chrome.storage.sync).not.toBe(page.nativeSync) - expect(page.chrome.storage.sync).toMatchObject({ QUOTA_BYTES: 102_400, MAX_ITEMS: 512 }) - - await expect(call(page.chrome, 'storage.sync.get', 'theme')).resolves.toEqual({ - theme: 'dark' - }) - const got = await new Promise((resolve) => call(page.chrome, 'storage.sync.get', resolve)) - expect(got).toEqual({ theme: 'dark' }) - const setDone = vi.fn() - expect( - call(page.chrome, 'storage.sync.set', { at: new Date(0), skip: undefined }, setDone) - ).toBeUndefined() - await vi.waitFor(() => expect(setDone).toHaveBeenCalledWith()) - await expect( - call(page.chrome, 'storage.sync.setAccessLevel', { - accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS' - }) - ).resolves.toBeUndefined() - await expect( - call(page.chrome, 'storage.sync.setAccessLevel', { accessLevel: 'TRUSTED_CONTEXTS' }) - ).rejects.toThrow('This StorageArea is not available for setting access level') - - expect(page.calls).toEqual([ - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', ['theme']], - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', []], - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'set', [{ at: '1970-01-01T00:00:00.000Z' }]] - ]) - expect(page.nativeSync.get).not.toHaveBeenCalled() - expect(page.nativeSync.set).not.toHaveBeenCalled() - }) - - it('sets lastError only inside a failed callback and rejects a failed promise', async () => { - const page = install(() => ({ ok: false, error: 'QUOTA_BYTES quota exceeded' })) - const lastError = await new Promise((resolve) => - call(page.chrome, 'storage.sync.set', { big: 1 }, () => - resolve(page.chrome.runtime.lastError?.message) - ) - ) - expect(lastError).toBe('QUOTA_BYTES quota exceeded') - expect(page.chrome.runtime.lastError).toBeUndefined() - await expect(call(page.chrome, 'storage.sync.set', { big: 1 })).rejects.toThrow( - 'QUOTA_BYTES quota exceeded' - ) - }) - - it("delivers main's sync changes to sync.onChanged and storage.onChanged with 'sync'", async () => { - const own = { mine: { newValue: 1 } } - const page = install((method) => ({ ok: true, value: method === 'set' ? own : undefined })) - const all: unknown[][] = [] - const area: unknown[][] = [] - const onAll = (changes: unknown, areaName: unknown) => all.push([areaName, changes]) - call(page.chrome, 'storage.onChanged.addListener', onAll) - call(page.chrome, 'storage.sync.onChanged.addListener', (changes: unknown) => - area.push([changes]) - ) - // The underlying onChanged keeps its own listeners for local and session. - expect(page.native.listeners.has(onAll)).toBe(true) - expect(call(page.chrome, 'storage.onChanged.hasListener', onAll)).toBe(true) - expect(page.listens).toEqual([[PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', true]]) - - const changes = { theme: { oldValue: 'light', newValue: 'dark' } } - page.emit(changes) - expect(all).toEqual([['sync', changes]]) - expect(area).toEqual([[changes]]) - - // Main skips the writer, which fires its own listeners from the changes main returns. - await expect(call(page.chrome, 'storage.sync.set', { mine: 1 })).resolves.toBeUndefined() - expect(all).toEqual([ - ['sync', changes], - ['sync', own] - ]) - expect(area).toEqual([[changes], [own]]) - - call(page.chrome, 'storage.onChanged.removeListener', onAll) - expect(page.native.listeners.has(onAll)).toBe(false) - page.emit(changes) - expect(all).toHaveLength(2) - expect(area).toHaveLength(3) - }) - - it("makes a content script's relayed call and fires this context's listeners for its writes", async () => { - const changes = { theme: { newValue: 'dark' } } - const worker = install((method) => ({ ok: true, value: method === 'set' ? changes : 'value' })) - const heard: unknown[] = [] - call(worker.chrome, 'storage.sync.onChanged.addListener', (change: unknown) => - heard.push(change) - ) - - await expect(worker.relay('get', ['theme'])).resolves.toEqual({ ok: true, value: 'value' }) - await expect(worker.relay('set', [{ theme: 'dark' }])).resolves.toEqual({ - ok: true, - value: changes - }) - expect(heard).toEqual([changes]) - await expect(worker.relay('setAccessLevel', [{}])).resolves.toMatchObject({ ok: false }) - expect(worker.calls).toEqual([ - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', ['theme']], - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'set', [{ theme: 'dark' }]] - ]) - }) - - it('passes every sync change on to content scripts, naming the one that wrote it', async () => { - const own = { mine: { newValue: 1 } } - const forward = vi.fn() - const worker = install(() => ({ ok: true, value: own }), forward) - // Listens with no listener of its own: content scripts hear other contexts only this way. - expect(worker.listens).toEqual([[PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', true]]) - - const elsewhere = { theme: { newValue: 'dark' } } - worker.emit(elsewhere) - await call(worker.chrome, 'storage.sync.set', { mine: 1 }) - await worker.relay('set', [{ mine: 1 }], 'cs-1') - expect(forward.mock.calls).toEqual([ - [elsewhere, undefined], - [own, undefined], - [own, 'cs-1'] - ]) - }) -}) diff --git a/src/preload/browser-extension-web-store-wording.test.ts b/src/preload/browser-extension-web-store-wording.test.ts deleted file mode 100644 index 382da7dd12a..00000000000 --- a/src/preload/browser-extension-web-store-wording.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it } from 'vitest' -import { adaptChromeWebStoreWordingForOrca } from './browser-extension-web-store-wording' - -const flushMutations = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)) - -afterEach(() => { - document.body.innerHTML = '' -}) - -describe('adaptChromeWebStoreWordingForOrca', () => { - it('renames the install wording but keeps the store name', () => { - document.body.innerHTML = - 'Chrome Web Store' - adaptChromeWebStoreWordingForOrca() - expect(document.querySelector('a')?.textContent).toBe('Chrome Web Store') - expect(document.querySelector('button')?.getAttribute('aria-label')).toBe('Add to Orca') - expect(document.querySelector('span')?.textContent).toBe('Add to Orca') - }) - - it('renames wording the store draws later, including the removal toast', async () => { - adaptChromeWebStoreWordingForOrca() - const button = document.createElement('span') - button.textContent = 'Remove from Chrome' - document.body.appendChild(button) - const toast = document.createElement('div') - toast.textContent = 'Bitwarden has been removed from Chrome.' - document.body.appendChild(toast) - await flushMutations() - expect(button.textContent).toBe('Remove from Orca') - expect(toast.textContent).toBe('Bitwarden has been removed from Orca.') - button.firstChild!.nodeValue = 'Add to Chrome' - await flushMutations() - expect(button.textContent).toBe('Add to Orca') - }) - - it('hides the switch-to-Chrome banner and shows the box again when the store reuses it', async () => { - document.body.innerHTML = - '

Vault

' - adaptChromeWebStoreWordingForOrca() - const banner = document.getElementById('banner')! - expect(banner.style.display).toBe('none') - expect(document.querySelector('h1')?.textContent).toBe('Vault') - banner.innerHTML = '
This item is disabled
Enable now' - await flushMutations() - expect(banner.style.display).toBe('') - }) -}) diff --git a/src/preload/browser-extension-worker-shim.ts b/src/preload/browser-extension-worker-shim.ts index a3aa1b19058..bb595fba55c 100644 --- a/src/preload/browser-extension-worker-shim.ts +++ b/src/preload/browser-extension-worker-shim.ts @@ -5,28 +5,28 @@ import { decodeBrowserExtensionWireJson, encodeBrowserExtensionWireJson } from '../shared/browser/extensions/browser-extension-worker-api' -import { BROWSER_EXTENSION_API_SURFACE } from './browser-extension-api-surface' +import { BROWSER_EXTENSION_API_SURFACE } from './browser/extensions/api/browser-extension-api-surface' import { createContentScriptSyncForward, installContentScriptRelayFilter -} from './browser-extension-content-script-relay' +} from './browser/extensions/messaging/browser-extension-content-script-relay' import { installBrowserExtensionDocumentTargets, PRELOAD_FIRST_DISCARDED_TAB_ID -} from './browser-extension-document-targets' -import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters' -import { installBrowserExtensionInertApis } from './browser-extension-inert-apis' +} from './browser/extensions/documents/browser-extension-document-targets' +import { passesBrowserExtensionEventFilter } from './browser/extensions/api/browser-extension-event-filters' +import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis' import { installBrowserExtensionApis, type BrowserExtensionInvokeReply, type BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' -import { installBrowserExtensionNativeMessaging } from './browser-extension-native-messaging' -import { installBrowserExtensionStorageRelay } from './browser-extension-storage-relay' +} from './browser/extensions/api/browser-extension-main-world' +import { installBrowserExtensionNativeMessaging } from './browser/extensions/messaging/browser-extension-native-messaging' +import { installBrowserExtensionStorageRelay } from './browser/extensions/storage/browser-extension-storage-relay' import { installBrowserExtensionStorageSync, PRELOAD_STORAGE_SYNC_CONSTANTS -} from './browser-extension-storage-sync' +} from './browser/extensions/storage/browser-extension-storage-sync' /** * Orca's API shim for extension service workers, bundled into one standalone script that Orca's diff --git a/src/preload/browser-find-subscriptions.test.ts b/src/preload/browser-find-subscriptions.test.ts deleted file mode 100644 index c25b00baa1d..00000000000 --- a/src/preload/browser-find-subscriptions.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createBrowserFindSubscriptions } from './browser-find-subscriptions' - -const FIRST_SOURCE = { - browserPageId: 'page-1', - browserWorkspaceId: 'workspace-1' -} -const SAME_WORKSPACE_SOURCE = { - browserPageId: 'page-2', - browserWorkspaceId: FIRST_SOURCE.browserWorkspaceId -} -const SAME_PAGE_SOURCE = { - browserPageId: FIRST_SOURCE.browserPageId, - browserWorkspaceId: 'workspace-2' -} - -describe('browser Find subscriptions', () => { - it('dispatches only to the exact browser page and workspace owner', () => { - const subscriptions = createBrowserFindSubscriptions() - const firstCallback = vi.fn() - const sameWorkspaceCallback = vi.fn() - const samePageCallback = vi.fn() - subscriptions.subscribe(FIRST_SOURCE, firstCallback) - subscriptions.subscribe(SAME_WORKSPACE_SOURCE, sameWorkspaceCallback) - subscriptions.subscribe(SAME_PAGE_SOURCE, samePageCallback) - - subscriptions.dispatch(FIRST_SOURCE) - - expect(firstCallback).toHaveBeenCalledOnce() - expect(sameWorkspaceCallback).not.toHaveBeenCalled() - expect(samePageCallback).not.toHaveBeenCalled() - }) - - it('dispatches a page-only target to every workspace holding that page', () => { - const subscriptions = createBrowserFindSubscriptions() - const firstCallback = vi.fn() - const sameWorkspaceCallback = vi.fn() - const samePageCallback = vi.fn() - subscriptions.subscribe(FIRST_SOURCE, firstCallback) - subscriptions.subscribe(SAME_WORKSPACE_SOURCE, sameWorkspaceCallback) - subscriptions.subscribe(SAME_PAGE_SOURCE, samePageCallback) - - subscriptions.dispatch({ browserPageId: FIRST_SOURCE.browserPageId }) - - expect(firstCallback).toHaveBeenCalledOnce() - expect(samePageCallback).toHaveBeenCalledOnce() - expect(sameWorkspaceCallback).not.toHaveBeenCalled() - }) - - it('dispatches an explicitly undefined workspace as page-only, not as a miss', () => { - const subscriptions = createBrowserFindSubscriptions() - const callback = vi.fn() - subscriptions.subscribe(FIRST_SOURCE, callback) - - // Structured-clone IPC preserves explicitly undefined properties. - subscriptions.dispatch({ - browserPageId: FIRST_SOURCE.browserPageId, - browserWorkspaceId: undefined - }) - - expect(callback).toHaveBeenCalledOnce() - }) - - it('rejects malformed identities and blank ids', () => { - const subscriptions = createBrowserFindSubscriptions() - const callback = vi.fn() - subscriptions.subscribe(FIRST_SOURCE, callback) - - subscriptions.dispatch(undefined) - subscriptions.dispatch(['page-1']) - subscriptions.dispatch({ browserWorkspaceId: FIRST_SOURCE.browserWorkspaceId }) - subscriptions.dispatch({ browserPageId: '' }) - subscriptions.dispatch({ - browserPageId: FIRST_SOURCE.browserPageId, - browserWorkspaceId: '' - }) - - expect(callback).not.toHaveBeenCalled() - }) - - it('drops empty ownership entries when subscribers clean up', () => { - const subscriptions = createBrowserFindSubscriptions() - const callback = vi.fn() - const unsubscribe = subscriptions.subscribe(FIRST_SOURCE, callback) - expect(subscriptions.subscribedPageCount()).toBe(1) - - unsubscribe() - - subscriptions.dispatch(FIRST_SOURCE) - subscriptions.dispatch({ browserPageId: FIRST_SOURCE.browserPageId }) - expect(callback).not.toHaveBeenCalled() - expect(subscriptions.subscribedPageCount()).toBe(0) - }) - - it('keeps the other workspaces on a page when one of them unsubscribes', () => { - const subscriptions = createBrowserFindSubscriptions() - const firstCallback = vi.fn() - const samePageCallback = vi.fn() - const unsubscribe = subscriptions.subscribe(FIRST_SOURCE, firstCallback) - subscriptions.subscribe(SAME_PAGE_SOURCE, samePageCallback) - - unsubscribe() - subscriptions.dispatch(SAME_PAGE_SOURCE) - subscriptions.dispatch({ browserPageId: FIRST_SOURCE.browserPageId }) - - expect(firstCallback).not.toHaveBeenCalled() - expect(samePageCallback).toHaveBeenCalledTimes(2) - expect(subscriptions.subscribedPageCount()).toBe(1) - }) -}) diff --git a/src/preload/browser-guest.ts b/src/preload/browser-guest.ts index 3f42876ed39..1903fc84cdc 100644 --- a/src/preload/browser-guest.ts +++ b/src/preload/browser-guest.ts @@ -1,11 +1,11 @@ import type { ContextBridge, IpcRenderer, WebFrame } from 'electron' -import { installBrowserPasswordDetector } from './browser-password-detector' +import { installBrowserPasswordDetector } from './browser/passwords/browser-password-detector' import { installBrowserWindowCloseGuard, PRELOAD_BROWSER_GUEST_WINDOW_CLOSE_CHANNEL -} from './browser-window-close-installation' -import { installBrowserWindowPrompt } from './browser-window-prompt-installation' -import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme' +} from './browser/window-controls/browser-window-close-installation' +import { installBrowserWindowPrompt } from './browser/window-controls/browser-window-prompt-installation' +import { installNativeChatVisualGuestTheme } from './native-chat/native-chat-visual-guest-theme' // Raw require keeps the sandboxed preload standalone in the CJS build. const electron: { diff --git a/src/preload/browser-passkey-request.ts b/src/preload/browser-passkey-request.ts index 5f666278ea3..4066364b673 100644 --- a/src/preload/browser-passkey-request.ts +++ b/src/preload/browser-passkey-request.ts @@ -3,7 +3,7 @@ import { BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL, BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL } from '../shared/browser-passkey-request' -import { installBrowserPasskeyRequestWatch } from './browser-passkey-request-watch' +import { installBrowserPasskeyRequestWatch } from './browser/passkeys/browser-passkey-request-watch' // A session preload: it runs in every frame of every browser page, popup and serve window. const electron: { diff --git a/src/preload/browser-window-close-installation.test.ts b/src/preload/browser-window-close-installation.test.ts deleted file mode 100644 index afca315c1a2..00000000000 --- a/src/preload/browser-window-close-installation.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { buildSync } from 'esbuild' -import { fileURLToPath } from 'node:url' -import { runInNewContext } from 'node:vm' - -import { installBrowserWindowCloseGuard } from './browser-window-close-installation' -import { BROWSER_GUEST_WINDOW_CLOSE_CHANNEL } from '../shared/browser-guest-window-close' - -describe('browser window close guard', () => { - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('replaces the native close with a non-replaceable request to Orca', () => { - const nativeClose = vi.fn() - const requestClose = vi.fn() - vi.stubGlobal('window', { close: nativeClose }) - - installBrowserWindowCloseGuard(requestClose) - - expect(window.close()).toBeUndefined() - expect(nativeClose).not.toHaveBeenCalled() - expect(requestClose).toHaveBeenCalledTimes(1) - expect(Reflect.set(window, 'close', nativeClose)).toBe(false) - }) - - it.each([true, false])('routes a close only from the top frame: %s', (isMainFrame) => { - const sendToHost = vi.fn() - const nativeClose = vi.fn() - const pageWindow = { close: nativeClose } - const preload = buildSync({ - entryPoints: [fileURLToPath(new URL('./browser-guest.ts', import.meta.url))], - bundle: true, - platform: 'node', - format: 'cjs', - external: ['electron'], - write: false - }).outputFiles[0].text - - runInNewContext(preload, { - window: pageWindow, - process: { isMainFrame }, - require: (name: string) => { - expect(name).toBe('electron') - return { - ipcRenderer: { sendToHost }, - contextBridge: { - executeInMainWorld: (script: { - func: (requestClose: () => void) => void - args: [() => void] - }) => script.func(...script.args) - } - } - } - }) - - pageWindow.close() - - expect(nativeClose).toHaveBeenCalledTimes(isMainFrame ? 0 : 1) - expect(sendToHost.mock.calls).toEqual(isMainFrame ? [[BROWSER_GUEST_WINDOW_CLOSE_CHANNEL]] : []) - }) -}) diff --git a/src/preload/browser-extension-api-surface.ts b/src/preload/browser/extensions/api/browser-extension-api-surface.ts similarity index 100% rename from src/preload/browser-extension-api-surface.ts rename to src/preload/browser/extensions/api/browser-extension-api-surface.ts diff --git a/src/preload/browser-extension-event-filters.ts b/src/preload/browser/extensions/api/browser-extension-event-filters.ts similarity index 100% rename from src/preload/browser-extension-event-filters.ts rename to src/preload/browser/extensions/api/browser-extension-event-filters.ts diff --git a/src/preload/browser-extension-frame-lifetime.ts b/src/preload/browser/extensions/api/browser-extension-frame-lifetime.ts similarity index 100% rename from src/preload/browser-extension-frame-lifetime.ts rename to src/preload/browser/extensions/api/browser-extension-frame-lifetime.ts diff --git a/src/preload/browser-extension-inert-apis.test.ts b/src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts similarity index 90% rename from src/preload/browser-extension-inert-apis.test.ts rename to src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts index f54dba1de67..f98d3ca313b 100644 --- a/src/preload/browser-extension-inert-apis.test.ts +++ b/src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts @@ -63,10 +63,4 @@ describe('installBrowserExtensionInertApis', () => { expect(member(chrome, 'storage.managed.onChanged')).toEqual({ native: true }) } }) - - it('keeps members Electron already provides', () => { - const native = vi.fn() - const { chrome } = install('page', {}, { extension: { getViews: native } }) - expect(member(chrome, 'extension.getViews')).toBe(native) - }) }) diff --git a/src/preload/browser-extension-inert-apis.ts b/src/preload/browser/extensions/api/browser-extension-inert-apis.ts similarity index 100% rename from src/preload/browser-extension-inert-apis.ts rename to src/preload/browser/extensions/api/browser-extension-inert-apis.ts diff --git a/src/preload/browser-extension-main-world.test.ts b/src/preload/browser/extensions/api/browser-extension-main-world.test.ts similarity index 100% rename from src/preload/browser-extension-main-world.test.ts rename to src/preload/browser/extensions/api/browser-extension-main-world.test.ts diff --git a/src/preload/browser-extension-main-world.ts b/src/preload/browser/extensions/api/browser-extension-main-world.ts similarity index 100% rename from src/preload/browser-extension-main-world.ts rename to src/preload/browser/extensions/api/browser-extension-main-world.ts diff --git a/src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts b/src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts new file mode 100644 index 00000000000..cd46a140026 --- /dev/null +++ b/src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts @@ -0,0 +1,275 @@ +import { runInNewContext } from 'node:vm' +import { webcrypto } from 'node:crypto' +import { describe, expect, it, vi } from 'vitest' +import { + installBrowserExtensionDocumentTargets, + PRELOAD_DOCUMENT_TARGETS_NAMESPACE, + PRELOAD_FIRST_DISCARDED_TAB_ID +} from './browser-extension-document-targets' + +const DISCARDED_TAB = PRELOAD_FIRST_DISCARDED_TAB_ID + 3 + +const ORCA_TOP = 'A'.repeat(32) +const ORCA_AD = 'B'.repeat(32) +const CHROMIUM_TOP = 'C'.repeat(32) +const CHROMIUM_AD = 'D'.repeat(32) + +type NativeListener = (message: unknown, sender: unknown, respond: (value: unknown) => void) => void + +function navigatingDocumentTarget(navigateOnLookup = 1) { + let current = 'old-document' + const delivered: string[] = [] + const listeners = new Set() + const runtime = { + id: 'extension', + getManifest: () => ({ permissions: ['webNavigation', 'scripting'] }), + onMessage: { + addListener: (listener: NativeListener) => listeners.add(listener), + removeListener: (listener: NativeListener) => listeners.delete(listener) + } + } + const chrome = { + runtime, + scripting: { + executeScript: async (injection: { + target: { documentIds?: string[]; tabId: number } + func?: () => unknown + }) => { + if (injection.target.documentIds?.some((id) => id !== current)) { + throw new Error('No matching document') + } + const result = injection.func?.() + return [{ frameId: 0, documentId: current, result }] + } + }, + tabs: { + sendMessage: async (_tabId: number, message: unknown, options?: { documentId?: string }) => { + if (options?.documentId && options.documentId !== current) { + throw new Error('No matching document') + } + if (typeof message === 'string') { + delivered.push(current) + return 'received' + } + for (const listener of listeners) { + listener( + { + orcaDocumentTargetProbe: { + ...(message && + typeof message === 'object' && + 'orcaDocumentTargetProbe' in message && + message.orcaDocumentTargetProbe && + typeof message.orcaDocumentTargetProbe === 'object' + ? message.orcaDocumentTargetProbe + : {}), + response: true + } + }, + { id: 'extension', tab: { id: 3 }, frameId: 0, documentId: current }, + () => {} + ) + } + return true + } + } + } + let lookups = 0 + const bridge = { + call: async () => { + const value = [{ frameId: 0, documentId: current }] + if (++lookups === navigateOnLookup) { + current = 'new-document' + } + return { ok: true as const, value } + }, + listen: () => {}, + onEvent: () => {}, + passesFilter: () => true + } + const realm = { chrome, crypto: webcrypto, setTimeout, clearTimeout } + runInNewContext(`(${installBrowserExtensionDocumentTargets.toString()})(bridge, first)`, { + ...realm, + globalThis: realm, + bridge, + first: PRELOAD_FIRST_DISCARDED_TAB_ID + }) + return { chrome, delivered, listeners } +} + +/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ +function install(permissions: string[], nativeScripting = true) { + const nativeListeners = new Set() + const executeScript = vi.fn( + async (injection: { target: Record; func?: () => unknown }) => { + const frameIds = Array.isArray(injection.target.frameIds) + ? injection.target.frameIds + : Array.isArray(injection.target.documentIds) + ? injection.target.documentIds.map((id) => (id === CHROMIUM_AD ? 42 : 0)) + : [0] + return frameIds.map((frameId: number) => ({ + frameId, + documentId: frameId === 42 ? CHROMIUM_AD : CHROMIUM_TOP, + result: frameId + })) + } + ) + const insertCSS = vi.fn((_injection: unknown, callback?: () => void) => { + callback?.() + return callback ? undefined : Promise.resolve() + }) + const sendMessage = vi.fn( + async ( + tabId: number, + message: unknown, + options?: { frameId?: number; documentId?: string }, + _callback?: () => void + ): Promise => { + if (message && typeof message === 'object' && 'orcaDocumentTargetProbe' in message) { + const frameId = options?.frameId ?? 0 + const probe = message.orcaDocumentTargetProbe + for (const listener of nativeListeners) { + listener( + { + orcaDocumentTargetProbe: { + ...(typeof probe === 'object' ? probe : {}), + response: true + } + }, + { + id: 'extension', + tab: { id: tabId }, + frameId, + documentId: frameId === 42 ? CHROMIUM_AD : CHROMIUM_TOP + }, + () => {} + ) + } + return true + } + return 'pong' + } + ) + const scripting = { executeScript, insertCSS, removeCSS: vi.fn(async () => {}) } + const tabs = { sendMessage } + const calls: unknown[][] = [] + const bridge = { + call: async (namespace: string, method: string, args: unknown[]) => { + // Main's tabs.get: a discarded tab, or (once replaced by its loaded guest) no tab. + if (namespace === 'tabs' && method === 'get') { + return args[0] === DISCARDED_TAB + ? { ok: true as const, value: { id: DISCARDED_TAB, discarded: true } } + : { ok: false as const, error: `No tab with id: ${String(args[0])}.` } + } + expect([namespace, method]).toEqual([PRELOAD_DOCUMENT_TARGETS_NAMESPACE, 'frames']) + calls.push(args) + return { + ok: true as const, + value: [ + { frameId: 0, documentId: ORCA_TOP }, + { frameId: 42, documentId: ORCA_AD } + ] + } + }, + listen: () => {}, + onEvent: () => {}, + passesFilter: () => true + } + const runtime: { + id: string + getManifest: () => unknown + lastError?: unknown + onMessage: { + addListener: (listener: NativeListener) => void + removeListener: (listener: NativeListener) => void + } + } = { + id: 'extension', + getManifest: () => ({ permissions }), + onMessage: { + addListener: (listener) => { + nativeListeners.add(listener) + }, + removeListener: (listener) => { + nativeListeners.delete(listener) + } + } + } + const chrome = { runtime, scripting, tabs } + // `browser` shares chrome's namespace objects, as Orca's installer mirrors them. + const realm = { + chrome: nativeScripting ? chrome : { runtime, tabs }, + browser: nativeScripting ? { scripting, tabs } : { tabs }, + crypto: webcrypto, + setTimeout, + clearTimeout, + Promise, + Map, + Set, + Object, + Array + } + runInNewContext(`(${installBrowserExtensionDocumentTargets.toString()})(bridge, first)`, { + ...realm, + globalThis: realm, + bridge, + first: PRELOAD_FIRST_DISCARDED_TAB_ID, + Error + }) + return { chrome, executeScript, insertCSS, sendMessage, calls, nativeListeners } +} + +describe('Orca documentIds in native scripting targets', () => { + it.each([1, 2])( + 'rejects script navigation at discovery snapshot %i before executing user code', + async (snapshot) => { + const { chrome } = navigatingDocumentTarget(snapshot) + const userCode = vi.fn() + + await expect( + chrome.scripting.executeScript({ + target: { documentIds: ['old-document'], tabId: 3 }, + func: userCode + }) + ).rejects.toThrow(/document/i) + + expect(userCode).not.toHaveBeenCalled() + } + ) + + it.each([1, 2])( + 'rejects message navigation at discovery snapshot %i before delivering the payload', + async (snapshot) => { + const { chrome, delivered, listeners } = navigatingDocumentTarget(snapshot) + + await expect( + chrome.tabs.sendMessage(3, 'document-specific secret', { + documentId: 'old-document' + }) + ).rejects.toThrow(/document/i) + + expect(delivered).toEqual([]) + expect(listeners.size).toBe(0) + } + ) +}) + +describe('calls to a discarded tab', () => { + it("fail with Chrome's errors instead of reaching Electron", async () => { + const { chrome, executeScript, sendMessage } = install(['scripting']) + await expect( + chrome.scripting.executeScript({ target: { tabId: DISCARDED_TAB }, func: () => 1 }) + ).rejects.toThrow('Cannot access contents of url ""') + await expect(chrome.tabs.sendMessage(DISCARDED_TAB, 'ping')).rejects.toThrow( + 'Could not establish connection. Receiving end does not exist.' + ) + const lastError = await new Promise((resolve) => + chrome.scripting.insertCSS({ target: { tabId: DISCARDED_TAB }, css: 'a{}' }, () => + resolve(chrome.runtime.lastError) + ) + ) + expect(lastError).toEqual({ message: expect.stringContaining('Cannot access contents') }) + expect(chrome.runtime.lastError).toBeUndefined() + expect(executeScript).not.toHaveBeenCalled() + expect(sendMessage).not.toHaveBeenCalled() + }) +}) diff --git a/src/preload/browser-extension-document-targets.ts b/src/preload/browser/extensions/documents/browser-extension-document-targets.ts similarity index 99% rename from src/preload/browser-extension-document-targets.ts rename to src/preload/browser/extensions/documents/browser-extension-document-targets.ts index df091692047..eaac39d963a 100644 --- a/src/preload/browser-extension-document-targets.ts +++ b/src/preload/browser/extensions/documents/browser-extension-document-targets.ts @@ -1,4 +1,4 @@ -import type { BrowserExtensionMainWorldBridge } from './browser-extension-main-world' +import type { BrowserExtensionMainWorldBridge } from '../api/browser-extension-main-world' /** Main-only namespace listing a tab's frames with Orca's documentIds; never on `chrome`. */ export const PRELOAD_DOCUMENT_TARGETS_NAMESPACE = 'orcaDocumentTargets' diff --git a/src/preload/browser-extension-content-script-relay.test.ts b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts similarity index 98% rename from src/preload/browser-extension-content-script-relay.test.ts rename to src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts index 98d21664c1a..4d98f9d5a60 100644 --- a/src/preload/browser-extension-content-script-relay.test.ts +++ b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts @@ -5,7 +5,7 @@ import { createContentScriptRelayBridge, installContentScriptRelayFilter } from './browser-extension-content-script-relay' -import type { BrowserExtensionStorageSyncRelay } from './browser-extension-storage-sync' +import type { BrowserExtensionStorageSyncRelay } from '../storage/browser-extension-storage-sync' type Listener = ( message: unknown, diff --git a/src/preload/browser-extension-content-script-relay.ts b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.ts similarity index 98% rename from src/preload/browser-extension-content-script-relay.ts rename to src/preload/browser/extensions/messaging/browser-extension-content-script-relay.ts index 0188f6bcb9f..50f2ddd8426 100644 --- a/src/preload/browser-extension-content-script-relay.ts +++ b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.ts @@ -1,11 +1,11 @@ import type { BrowserExtensionInvokeReply, BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' +} from '../api/browser-extension-main-world' import type { BrowserExtensionStorageSyncForward, BrowserExtensionStorageSyncRelay -} from './browser-extension-storage-sync' +} from '../storage/browser-extension-storage-sync' /** * Content scripts run in Chromium's per-extension isolated world, which no Orca preload reaches, diff --git a/src/preload/browser-extension-native-messaging.ts b/src/preload/browser/extensions/messaging/browser-extension-native-messaging.ts similarity index 98% rename from src/preload/browser-extension-native-messaging.ts rename to src/preload/browser/extensions/messaging/browser-extension-native-messaging.ts index 88d4a32f85e..3c793e8ec18 100644 --- a/src/preload/browser-extension-native-messaging.ts +++ b/src/preload/browser/extensions/messaging/browser-extension-native-messaging.ts @@ -1,4 +1,4 @@ -import type { BrowserExtensionMainWorldBridge } from './browser-extension-main-world' +import type { BrowserExtensionMainWorldBridge } from '../api/browser-extension-main-world' /** Main-only namespace behind connectNative/sendNativeMessage; never installed on `chrome`. */ export const PRELOAD_NATIVE_MESSAGING_NAMESPACE = 'orcaNativeMessaging' diff --git a/src/preload/browser-extension-storage-relay.test.ts b/src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts similarity index 75% rename from src/preload/browser-extension-storage-relay.test.ts rename to src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts index 4c611b29325..5ba7e59bc13 100644 --- a/src/preload/browser-extension-storage-relay.test.ts +++ b/src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts @@ -1,6 +1,6 @@ import { runInNewContext } from 'node:vm' import { describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionInvokeReply } from './browser-extension-main-world' +import type { BrowserExtensionInvokeReply } from '../api/browser-extension-main-world' import { installBrowserExtensionStorageRelay, PRELOAD_STORAGE_RELAY_NAMESPACE, @@ -149,36 +149,7 @@ function call(root: unknown, path: string, ...args: unknown[]): unknown { return fn.call(owner, ...args) } -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - describe('installBrowserExtensionStorageRelay in a worker', () => { - it('fires onChanged and the area event once per write with only the keys that changed', async () => { - const worker = install('worker') - worker.listen() - expect(worker.listens).toEqual([[PRELOAD_STORAGE_RELAY_NAMESPACE, 'onChanged', true]]) - - await call(worker.chrome, 'storage.local.set', { kept: 'same', changed: 'new', added: [1] }) - await call(worker.chrome, 'storage.local.set', { kept: 'same' }) - await call(worker.chrome, 'storage.local.remove', ['gone', 'missing']) - await call(worker.chrome, 'storage.session.set', { token: 'abc' }) - await call(worker.chrome, 'storage.session.clear') - - const written = { changed: { oldValue: 'old', newValue: 'new' }, added: { newValue: [1] } } - expect(worker.all).toEqual([ - ['local', written], - ['local', { gone: { oldValue: 1 } }], - ['session', { token: { newValue: 'abc' } }], - ['session', { token: { oldValue: 'abc' } }] - ]) - expect(worker.perArea).toEqual([ - ['local', written], - ['local', { gone: { oldValue: 1 } }], - ['session', { token: { newValue: 'abc' } }], - ['session', { token: { oldValue: 'abc' } }] - ]) - expect(worker.calls).toEqual([]) - }) - it('reports old values in write order when writes are not awaited', async () => { const worker = install('worker') worker.listen() @@ -239,37 +210,3 @@ describe('installBrowserExtensionStorageRelay in a worker', () => { expect(worker.perArea).toEqual([['session', { token: { newValue: 'abc' } }]]) }) }) - -describe('installBrowserExtensionStorageRelay in an extension page', () => { - it('reports its own changed keys to main and leaves the native onChanged alone', async () => { - const page = install('page') - expect(page.chrome.storage.onChanged).toEqual({ native: true }) - expect(page.local.area.onChanged).toEqual({ native: true }) - expect(page.hasEventHandler()).toBe(false) - - await call(page.chrome, 'storage.local.set', { kept: 'same', changed: 'new' }) - await call(page.chrome, 'storage.local.set', { kept: 'same' }) - await call(page.chrome, 'storage.local.clear') - await settle() - expect(page.calls).toEqual([ - [ - PRELOAD_STORAGE_RELAY_NAMESPACE, - 'report', - ['local', { changed: { oldValue: 'old', newValue: 'new' } }] - ], - [ - PRELOAD_STORAGE_RELAY_NAMESPACE, - 'report', - [ - 'local', - { - kept: { oldValue: 'same' }, - changed: { oldValue: 'new' }, - gone: { oldValue: 1 } - } - ] - ] - ]) - expect(page.local.data.size).toBe(0) - }) -}) diff --git a/src/preload/browser-extension-storage-relay.ts b/src/preload/browser/extensions/storage/browser-extension-storage-relay.ts similarity index 98% rename from src/preload/browser-extension-storage-relay.ts rename to src/preload/browser/extensions/storage/browser-extension-storage-relay.ts index 9c43ba3bf11..5f090e6fc99 100644 --- a/src/preload/browser-extension-storage-relay.ts +++ b/src/preload/browser/extensions/storage/browser-extension-storage-relay.ts @@ -1,4 +1,4 @@ -import type { BrowserExtensionMainWorldBridge } from './browser-extension-main-world' +import type { BrowserExtensionMainWorldBridge } from '../api/browser-extension-main-world' /** Main-only namespace carrying page storage writes to the worker; never installed on `chrome`. */ export const PRELOAD_STORAGE_RELAY_NAMESPACE = 'orcaStorageRelay' diff --git a/src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts b/src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts new file mode 100644 index 00000000000..40ba69c72d6 --- /dev/null +++ b/src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts @@ -0,0 +1,100 @@ +import { runInNewContext } from 'node:vm' +import { describe, expect, it, vi } from 'vitest' +import type { BrowserExtensionInvokeReply } from '../api/browser-extension-main-world' +import { + installBrowserExtensionStorageSync, + PRELOAD_STORAGE_SYNC_CONSTANTS, + PRELOAD_STORAGE_SYNC_NAMESPACE +} from './browser-extension-storage-sync' + +type Runtime = { lastError?: { message: string } } + +function nativeEvent() { + const listeners = new Set() + return { + listeners, + addListener: vi.fn((callback: unknown) => listeners.add(callback)), + removeListener: vi.fn((callback: unknown) => listeners.delete(callback)) + } +} + +/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ +function install( + reply: (method: string, args: unknown[]) => BrowserExtensionInvokeReply, + forward?: (changes: unknown, from?: string) => void +) { + const runtime: Runtime = {} + const native = nativeEvent() + const nativeSync = { get: vi.fn(), set: vi.fn() } + const chrome = { runtime, storage: { local: {}, sync: nativeSync, onChanged: native } } + let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null + const calls: unknown[][] = [] + const listens: unknown[][] = [] + const bridge = { + call: async (namespace: string, method: string, args: unknown[]) => { + calls.push([namespace, method, args]) + return reply(method, args) + }, + listen: (namespace: string, event: string, active: boolean) => + listens.push([namespace, event, active]), + onEvent: (handler: typeof dispatch) => { + dispatch = handler + }, + passesFilter: () => true + } + const realm = { chrome, console, JSON, Promise } + const relay: unknown = runInNewContext( + `(${installBrowserExtensionStorageSync.toString()})(bridge, constants, forward)`, + { + ...realm, + globalThis: realm, + bridge, + constants: PRELOAD_STORAGE_SYNC_CONSTANTS, + forward + } + ) + return { + relay: (method: string, args: unknown[], from?: string): unknown => + typeof relay === 'function' ? relay(method, args, from) : undefined, + chrome, + native, + nativeSync, + calls, + listens, + emit: (changes: unknown) => dispatch?.(PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', [changes]) + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' +} + +function call(root: unknown, path: string, ...args: unknown[]): unknown { + const keys = path.split('.') + const name = keys.pop() ?? '' + const owner = keys.reduce( + (value, key) => (isRecord(value) ? value[key] : undefined), + root + ) + const fn = isRecord(owner) ? owner[name] : null + if (typeof fn !== 'function') { + throw new Error(`${path} is not a function`) + } + return fn.call(owner, ...args) +} + +describe('installBrowserExtensionStorageSync', () => { + it('sets lastError only inside a failed callback and rejects a failed promise', async () => { + const page = install(() => ({ ok: false, error: 'QUOTA_BYTES quota exceeded' })) + const lastError = await new Promise((resolve) => + call(page.chrome, 'storage.sync.set', { big: 1 }, () => + resolve(page.chrome.runtime.lastError?.message) + ) + ) + expect(lastError).toBe('QUOTA_BYTES quota exceeded') + expect(page.chrome.runtime.lastError).toBeUndefined() + await expect(call(page.chrome, 'storage.sync.set', { big: 1 })).rejects.toThrow( + 'QUOTA_BYTES quota exceeded' + ) + }) +}) diff --git a/src/preload/browser-extension-storage-sync.ts b/src/preload/browser/extensions/storage/browser-extension-storage-sync.ts similarity index 99% rename from src/preload/browser-extension-storage-sync.ts rename to src/preload/browser/extensions/storage/browser-extension-storage-sync.ts index 89c4824a3bb..bd0c5d788df 100644 --- a/src/preload/browser-extension-storage-sync.ts +++ b/src/preload/browser/extensions/storage/browser-extension-storage-sync.ts @@ -1,7 +1,7 @@ import type { BrowserExtensionInvokeReply, BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' +} from '../api/browser-extension-main-world' /** Main-only namespace backing chrome.storage.sync; never installed on `chrome` by that name. */ export const PRELOAD_STORAGE_SYNC_NAMESPACE = 'orcaStorageSync' diff --git a/src/preload/browser-extension-web-store-bridge.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-bridge.ts similarity index 100% rename from src/preload/browser-extension-web-store-bridge.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-bridge.ts diff --git a/src/preload/browser-extension-web-store-main-world.test.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts similarity index 94% rename from src/preload/browser-extension-web-store-main-world.test.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts index 6923b31d5a4..feb494d4ef7 100644 --- a/src/preload/browser-extension-web-store-main-world.test.ts +++ b/src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts @@ -63,12 +63,6 @@ function lastErrors(realm: unknown): [unknown, unknown] { } describe('installChromeWebStoreApis', () => { - it('keeps existing runtime members', () => { - const sendMessage = () => {} - const { realm } = installInFreshRealm(() => ({}), { runtime: { sendMessage } }) - expect(member(realm, 'chrome.runtime.sendMessage')).toBe(sendMessage) - }) - it('sets lastError on runtime and extension only while the callback runs', async () => { const { realm, calls } = installInFreshRealm(() => ({ value: 'user_cancelled', diff --git a/src/preload/browser-extension-web-store-main-world.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.ts similarity index 100% rename from src/preload/browser-extension-web-store-main-world.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.ts diff --git a/src/preload/browser-extension-web-store-wording.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-wording.ts similarity index 100% rename from src/preload/browser-extension-web-store-wording.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-wording.ts diff --git a/src/preload/browser-passkey-request-watch.test.ts b/src/preload/browser/passkeys/browser-passkey-request-watch.test.ts similarity index 100% rename from src/preload/browser-passkey-request-watch.test.ts rename to src/preload/browser/passkeys/browser-passkey-request-watch.test.ts diff --git a/src/preload/browser-passkey-request-watch.ts b/src/preload/browser/passkeys/browser-passkey-request-watch.ts similarity index 100% rename from src/preload/browser-passkey-request-watch.ts rename to src/preload/browser/passkeys/browser-passkey-request-watch.ts diff --git a/src/preload/browser-password-detector.test.ts b/src/preload/browser/passwords/browser-password-detector.test.ts similarity index 90% rename from src/preload/browser-password-detector.test.ts rename to src/preload/browser/passwords/browser-password-detector.test.ts index a06fdf168c5..2044a7f7565 100644 --- a/src/preload/browser-password-detector.test.ts +++ b/src/preload/browser/passwords/browser-password-detector.test.ts @@ -3,11 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { BROWSER_PASSWORDS_GUEST_CHANNELS, BROWSER_PASSWORDS_TO_GUEST_CHANNELS -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import type { BrowserPasswordFillRequest, BrowserPasswordGuestEnable -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { installBrowserPasswordDetector } from './browser-password-detector' const CHANNEL = BROWSER_PASSWORDS_GUEST_CHANNELS @@ -162,26 +162,6 @@ afterEach(() => { }) describe('browser password detector', () => { - it('installs only its main listeners until main enables the document', async () => { - load(LOGIN_FORM) - const addEventListener = vi.mocked(document.addEventListener) - const observe = vi.mocked(MutationObserver.prototype.observe) - - install() - typeInto(el('#pw'), 'secret') - await vi.advanceTimersByTimeAsync(1000) - - expect([...listeners.keys()].sort()).toEqual( - Object.values(BROWSER_PASSWORDS_TO_GUEST_CHANNELS).sort() - ) - expect(addEventListener).not.toHaveBeenCalled() - expect(observe).not.toHaveBeenCalled() - expect(sent).toEqual([]) - - enable() - expect(observe).toHaveBeenCalled() - }) - it('reports no page forms unless main waits on a login that navigated here', async () => { load(LOGIN_FORM) install() @@ -193,44 +173,6 @@ describe('browser password detector', () => { expect(sentOn(CHANNEL.pageForms)).toEqual([]) }) - it('reports the page forms once after enable and again only when they change', async () => { - load(LOGIN_FORM) - install() - enable({ reportPageForms: true }) - await vi.advanceTimersByTimeAsync(600) - - expect(sentOn(CHANNEL.pageForms)).toEqual([ - { - forms: [ - { - formSignature: expect.any(String), - kind: 'login', - usernameFieldName: 'email', - passwordFieldName: 'password', - action: new URL('/session', window.location.href).toString() - } - ] - } - ]) - - document.body.insertAdjacentHTML('beforeend', '

unrelated

') - await vi.advanceTimersByTimeAsync(600) - expect(sentOn(CHANNEL.pageForms)).toHaveLength(1) - - document.body.insertAdjacentHTML( - 'beforeend', - '
' - ) - layout() - await vi.advanceTimersByTimeAsync(600) - expect(sentOn(CHANNEL.pageForms).at(-1)).toEqual({ - forms: [ - expect.objectContaining({ kind: 'login' }), - expect.objectContaining({ kind: 'signup' }) - ] - }) - }) - it('reports trusted typing after the debounce, with only typed values', async () => { load(LOGIN_FORM) el('#email').value = 'prefilled@example.com' diff --git a/src/preload/browser-password-detector.ts b/src/preload/browser/passwords/browser-password-detector.ts similarity index 99% rename from src/preload/browser-password-detector.ts rename to src/preload/browser/passwords/browser-password-detector.ts index ad35208bc1f..6dba6cd7c0b 100644 --- a/src/preload/browser-password-detector.ts +++ b/src/preload/browser/passwords/browser-password-detector.ts @@ -6,7 +6,7 @@ import type { BrowserPasswordGuestCapture, BrowserPasswordGuestPageForms -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { createBrowserPasswordElementTokens } from './browser-password-element-tokens' import { applyBrowserPasswordFill, diff --git a/src/preload/browser-password-element-tokens.ts b/src/preload/browser/passwords/browser-password-element-tokens.ts similarity index 100% rename from src/preload/browser-password-element-tokens.ts rename to src/preload/browser/passwords/browser-password-element-tokens.ts diff --git a/src/preload/browser-password-field-fill.ts b/src/preload/browser/passwords/browser-password-field-fill.ts similarity index 99% rename from src/preload/browser-password-field-fill.ts rename to src/preload/browser/passwords/browser-password-field-fill.ts index ec617be730e..0adcbe2cb78 100644 --- a/src/preload/browser-password-field-fill.ts +++ b/src/preload/browser/passwords/browser-password-field-fill.ts @@ -5,7 +5,7 @@ import type { BrowserPasswordFillRequest, BrowserPasswordFillResult -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { isPlaceholderUsernameValue } from './browser-password-field-rules' import type { BrowserPasswordFormScanner } from './browser-password-form-scan' diff --git a/src/preload/browser-password-field-rules.ts b/src/preload/browser/passwords/browser-password-field-rules.ts similarity index 100% rename from src/preload/browser-password-field-rules.ts rename to src/preload/browser/passwords/browser-password-field-rules.ts diff --git a/src/preload/browser-password-focus-tracker.ts b/src/preload/browser/passwords/browser-password-focus-tracker.ts similarity index 98% rename from src/preload/browser-password-focus-tracker.ts rename to src/preload/browser/passwords/browser-password-focus-tracker.ts index 950bb57df21..000aa06c3c9 100644 --- a/src/preload/browser-password-focus-tracker.ts +++ b/src/preload/browser/passwords/browser-password-focus-tracker.ts @@ -6,7 +6,7 @@ import type { BrowserPasswordFieldRole, BrowserPasswordGuestFieldBlurred, BrowserPasswordGuestFieldFocused -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { PRELOAD_BROWSER_PASSWORDS_GUEST_CHANNELS } from './browser-password-guest-channels' import type { BrowserPasswordGuestPort } from './browser-password-guest-port' import { diff --git a/src/preload/browser-password-form-parser.test.ts b/src/preload/browser/passwords/browser-password-form-parser.test.ts similarity index 80% rename from src/preload/browser-password-form-parser.test.ts rename to src/preload/browser/passwords/browser-password-form-parser.test.ts index 3139ad42165..61fbbcbfe81 100644 --- a/src/preload/browser-password-form-parser.test.ts +++ b/src/preload/browser/passwords/browser-password-form-parser.test.ts @@ -253,57 +253,4 @@ describe('parsePasswordForm', () => { ])('%s', (_name, fields, text, expected) => { expect(parse(fields, text)).toEqual(expected) }) - - describe('username-first steps', () => { - it.each<[string, TestField[], string, string | null]>([ - [ - 'Google: autocomplete=username identifier box', - [input('identifier', { type: 'email', id: 'identifierId', autocomplete: 'username' })], - 'next', - 'identifier' - ], - [ - 'Microsoft: lone email box in a form that says Next', - [input('loginfmt', { type: 'email' })], - 'sign in next', - 'loginfmt' - ], - [ - 'Okta: autocomplete=username with a remember-me checkbox', - [ - input('identifier', { autocomplete: 'username' }), - input('rememberMe', { type: 'checkbox' }) - ], - 'sign in', - 'identifier' - ], - ['lone autocomplete=email box', [input('mail', { autocomplete: 'email' })], 'go', 'mail'], - ['lone field without any sign-in wording', [input('city')], 'submit', null], - [ - 'contact form: autocomplete=email beside other fields', - [input('name'), input('mail', { autocomplete: 'email' }), input('subject')], - 'send', - null - ], - [ - 'newsletter email form', - [input('email', { type: 'email', autocomplete: 'email' })], - 'subscribe to our newsletter', - null - ], - [ - 'newsletter by field name', - [input('newsletter_email', { type: 'email' })], - 'continue', - null - ], - ['lone search box that says next', [input('q', { type: 'search' })], 'next', null] - ])('%s', (_name, fields, text, username) => { - const parsed = parse(fields, text) - expect(parsed ? parsed.username : null).toBe(username) - if (username) { - expect(parsed?.kind).toBe('username-only') - } - }) - }) }) diff --git a/src/preload/browser-password-form-parser.ts b/src/preload/browser/passwords/browser-password-form-parser.ts similarity index 99% rename from src/preload/browser-password-form-parser.ts rename to src/preload/browser/passwords/browser-password-form-parser.ts index f89ca3a3989..aee557fca18 100644 --- a/src/preload/browser-password-form-parser.ts +++ b/src/preload/browser/passwords/browser-password-form-parser.ts @@ -5,7 +5,7 @@ import type { BrowserPasswordFieldRole, BrowserPasswordFormKind -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { autocompleteRoleToken, isCandidatePasswordFormField, diff --git a/src/preload/browser-password-form-scan.ts b/src/preload/browser/passwords/browser-password-form-scan.ts similarity index 99% rename from src/preload/browser-password-form-scan.ts rename to src/preload/browser/passwords/browser-password-form-scan.ts index 57d8c3c7317..74cbbcdba09 100644 --- a/src/preload/browser-password-form-scan.ts +++ b/src/preload/browser/passwords/browser-password-form-scan.ts @@ -6,7 +6,7 @@ import type { BrowserPasswordFieldRole, BrowserPasswordFormSummary -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { isCredentialInputType, type PasswordFieldDescriptor } from './browser-password-field-rules' import { parsePasswordForm, diff --git a/src/preload/browser-password-guest-channels.ts b/src/preload/browser/passwords/browser-password-guest-channels.ts similarity index 95% rename from src/preload/browser-password-guest-channels.ts rename to src/preload/browser/passwords/browser-password-guest-channels.ts index 484fe08099e..cd82664a1cd 100644 --- a/src/preload/browser-password-guest-channels.ts +++ b/src/preload/browser/passwords/browser-password-guest-channels.ts @@ -1,7 +1,7 @@ import type { BROWSER_PASSWORDS_GUEST_CHANNELS, BROWSER_PASSWORDS_TO_GUEST_CHANNELS -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' // Why literals: the sandboxed guest preload's `require` resolves only 'electron', so importing the // shared constants would emit a chunk it cannot load. `satisfies` and the test pin them. diff --git a/src/preload/browser-password-guest-port.ts b/src/preload/browser/passwords/browser-password-guest-port.ts similarity index 100% rename from src/preload/browser-password-guest-port.ts rename to src/preload/browser/passwords/browser-password-guest-port.ts diff --git a/src/preload/browser-password-submit-tracker.ts b/src/preload/browser/passwords/browser-password-submit-tracker.ts similarity index 99% rename from src/preload/browser-password-submit-tracker.ts rename to src/preload/browser/passwords/browser-password-submit-tracker.ts index 1c1894abe57..331f236930f 100644 --- a/src/preload/browser-password-submit-tracker.ts +++ b/src/preload/browser/passwords/browser-password-submit-tracker.ts @@ -7,7 +7,7 @@ import type { BrowserPasswordGuestFormGone, BrowserPasswordGuestSubmitted, BrowserPasswordSubmitSource -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { PRELOAD_BROWSER_PASSWORDS_GUEST_CHANNELS } from './browser-password-guest-channels' import type { BrowserPasswordGuestPort } from './browser-password-guest-port' import { diff --git a/src/preload/browser/window-controls/browser-window-close-installation.test.ts b/src/preload/browser/window-controls/browser-window-close-installation.test.ts new file mode 100644 index 00000000000..9c0a3f9b884 --- /dev/null +++ b/src/preload/browser/window-controls/browser-window-close-installation.test.ts @@ -0,0 +1,22 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { installBrowserWindowCloseGuard } from './browser-window-close-installation' + +describe('browser window close guard', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('replaces the native close with a non-replaceable request to Orca', () => { + const nativeClose = vi.fn() + const requestClose = vi.fn() + vi.stubGlobal('window', { close: nativeClose }) + + installBrowserWindowCloseGuard(requestClose) + + expect(window.close()).toBeUndefined() + expect(nativeClose).not.toHaveBeenCalled() + expect(requestClose).toHaveBeenCalledTimes(1) + expect(Reflect.set(window, 'close', nativeClose)).toBe(false) + }) +}) diff --git a/src/preload/browser-window-close-installation.ts b/src/preload/browser/window-controls/browser-window-close-installation.ts similarity index 100% rename from src/preload/browser-window-close-installation.ts rename to src/preload/browser/window-controls/browser-window-close-installation.ts diff --git a/src/preload/browser-window-prompt-installation.ts b/src/preload/browser/window-controls/browser-window-prompt-installation.ts similarity index 100% rename from src/preload/browser-window-prompt-installation.ts rename to src/preload/browser/window-controls/browser-window-prompt-installation.ts diff --git a/src/preload/doc-preview-link.ts b/src/preload/doc-preview-link.ts index 5cba0144e53..24c402907a4 100644 --- a/src/preload/doc-preview-link.ts +++ b/src/preload/doc-preview-link.ts @@ -1,9 +1,9 @@ import { installDocPreviewLinkInterception, PRELOAD_DOC_PREVIEW_LINK_CLICK_CHANNEL -} from './doc-preview-link-interception' +} from './document-preview/doc-preview-link-interception' import type { IpcRenderer, WebFrame } from 'electron' -import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme' +import { installNativeChatVisualGuestTheme } from './native-chat/native-chat-visual-guest-theme' // Raw require keeps the sandboxed preload standalone in the CJS build. const electron: { diff --git a/src/preload/doc-preview-link-interception.ts b/src/preload/document-preview/doc-preview-link-interception.ts similarity index 97% rename from src/preload/doc-preview-link-interception.ts rename to src/preload/document-preview/doc-preview-link-interception.ts index 99ea276ccf6..d9bee1dd5f3 100644 --- a/src/preload/doc-preview-link-interception.ts +++ b/src/preload/document-preview/doc-preview-link-interception.ts @@ -1,5 +1,5 @@ // Runs in the isolated world so page scripts cannot access the link reporter or its listeners. -import type { DocPreviewLinkModifiers } from '../shared/document-preview/doc-preview-scheme' +import type { DocPreviewLinkModifiers } from '../../shared/document-preview/doc-preview-scheme' export type DocPreviewExternalLinkReporter = ( url: string, diff --git a/src/preload/gitlab-work-item-details.test.ts b/src/preload/gitlab-work-item-details.test.ts deleted file mode 100644 index b7a7c955168..00000000000 --- a/src/preload/gitlab-work-item-details.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' - -const invoke = vi.hoisted(() => vi.fn()) -vi.mock('electron', () => ({ ipcRenderer: { invoke } })) -import { glApi } from './gitlab' - -beforeEach(() => invoke.mockReset()) - -it('preserves the optional review scope through the existing desktop details channel', async () => { - const args = { repoPath: '/repo', iid: 12, type: 'mr' as const, includeReviewDetails: false } - const details = { body: 'MR body', comments: [], pipelineJobs: [] } - invoke.mockResolvedValue(details) - expect(await glApi.workItemDetails(args)).toBe(details) - expect(invoke).toHaveBeenCalledWith('gitlab:workItemDetails', args) - const defaultArgs = { repoPath: '/repo', iid: 12, type: 'mr' as const } - await glApi.workItemDetails(defaultArgs) - expect(invoke).toHaveBeenLastCalledWith('gitlab:workItemDetails', defaultArgs) -}) diff --git a/src/preload/hidden-window-frame-pump.ts b/src/preload/hidden-window-frame-pump.ts deleted file mode 100644 index 94e415f8bbe..00000000000 --- a/src/preload/hidden-window-frame-pump.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { - HIDDEN_WINDOW_FRAME_PUMP_INTERVAL_MS, - hasHiddenWindowFramePumpArgument -} from '../shared/hidden-window-frame-pump' - -// Near-black so the single damaged frame is indistinguishable even if the window were visible. -const FLIP_COLOR = 'rgb(1, 1, 1)' - -type FramePumpStyle = Pick< - CSSStyleDeclaration, - 'getPropertyValue' | 'getPropertyPriority' | 'setProperty' | 'removeProperty' -> - -export type HiddenWindowFramePumpDeps = { - rootStyle: () => FramePumpStyle | null - requestAnimationFrame: (callback: () => void) => unknown - /** Runs callback every ms; returns the cancel function. */ - every: (callback: () => void, ms: number) => () => void -} - -/** Damage one frame per interval by flipping the root background, then restore the inline style exactly. */ -export function startHiddenWindowFramePump(deps: HiddenWindowFramePumpDeps): () => void { - let stopped = false - let flipping = false - const cancel = deps.every(() => { - const style = deps.rootStyle() - if (stopped || flipping || !style) { - return - } - flipping = true - deps.requestAnimationFrame(() => { - const previousValue = style.getPropertyValue('background-color') - const previousPriority = style.getPropertyPriority('background-color') - style.setProperty('background-color', FLIP_COLOR, previousPriority) - deps.requestAnimationFrame(() => { - if (previousValue) { - style.setProperty('background-color', previousValue, previousPriority) - } else { - style.removeProperty('background-color') - } - flipping = false - }) - }) - }, HIDDEN_WINDOW_FRAME_PUMP_INTERVAL_MS) - return () => { - if (!stopped) { - stopped = true - cancel() - } - } -} - -/** Only main's stop ends the pump; Windows can report a never-shown window visible after a desktop change. */ -export function installHiddenWindowFramePump( - argv: readonly string[], - onStopRequest: (stop: () => void) => void, - deps: HiddenWindowFramePumpDeps -): void { - if (hasHiddenWindowFramePumpArgument(argv)) { - onStopRequest(startHiddenWindowFramePump(deps)) - } -} diff --git a/src/preload/index.ts b/src/preload/index.ts index 6ccddcf2d8c..3ddcae7293e 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,97 +1,97 @@ import { contextBridge, ipcRenderer } from 'electron' import { HIDDEN_WINDOW_FRAME_PUMP_STOP_CHANNEL } from '../shared/hidden-window-frame-pump' -import { installHiddenWindowFramePump } from './hidden-window-frame-pump' +import { installHiddenWindowFramePump } from './renderer/hidden-window-frame-pump' import type { PreloadApi } from './api-types' -import { installBrowserFindListener } from './preload-runtime-support' +import { installBrowserFindListener } from './renderer/renderer-runtime' import { appApi } from './api/app-bridge' -import { orcaProfilesApi } from './api/orca-profiles-bridge' +import { orcaProfilesApi } from './api/profiles/orca-profiles-bridge' import { platformApi } from './api/platform-bridge' -import { wslApi } from './api/wsl-bridge' -import { wslMoveApi } from './api/wsl-move-bridge' -import { wslDriveProjectApi } from './api/wsl-drive-project-bridge' -import { wslDriveUncConversionApi } from './api/wsl-drive-unc-conversion-bridge' -import { pwshApi } from './api/pwsh-bridge' -import { gitBashApi } from './api/git-bash-bridge' -import { pluginsApi } from './api/plugins-bridge' -import { reposApi } from './api/repos-bridge' -import { projectsApi } from './api/projects-bridge' -import { projectGroupsApi } from './api/project-groups-bridge' -import { folderWorkspacesApi } from './api/folder-workspaces-bridge' -import { sparsePresetsApi } from './api/sparse-presets-bridge' -import { worktreesApi } from './api/worktrees-bridge' -import { workspaceCleanupApi } from './api/workspace-cleanup-bridge' -import { workspaceSpaceApi } from './api/workspace-space-bridge' -import { workspacePortsApi } from './api/workspace-ports-bridge' -import { linkPreviewApi } from './api/link-preview-bridge' -import { ptyApi } from './api/pty-bridge' -import { feedbackApi } from './api/feedback-bridge' -import { crashReportsApi } from './api/crash-reports-bridge' -import { exportApi } from './api/export-bridge' -import { ghApi } from './api/gh-bridge' -import { hostedReviewApi } from './api/hosted-review-bridge' -import { glApiBridge } from './api/gl-bridge' -import { bitbucketApi } from './api/bitbucket-bridge' -import { linearApi } from './api/linear-bridge' -import { jiraApi } from './api/jira-bridge' -import { starNagApi } from './api/star-nag-bridge' -import { diagnosticsApi } from './api/diagnostics-bridge' -import { settingsApi } from './api/settings-bridge' -import { agentAwakeApi } from './api/agent-awake-bridge' -import { localhostWorktreeLabelsApi } from './api/localhost-worktree-labels-bridge' -import { keybindingsApi } from './api/keybindings-bridge' -import { codexAccountsApi } from './api/codex-accounts-bridge' -import { claudeAccountsApi } from './api/claude-accounts-bridge' -import { cliApi } from './api/cli-bridge' -import { codexConfigSyncApi } from './api/codex-config-sync-bridge' -import { preflightApi } from './api/preflight-bridge' -import { notificationsApi } from './api/notifications-bridge' -import { onboardingApi } from './api/onboarding-bridge' -import { dashboardApi } from './api/dashboard-bridge' -import { terminalPreviewApi } from './api/terminal-preview-bridge' -import { macosTccPromptsApi } from './api/macos-tcc-prompts-bridge' -import { developerPermissionsApi } from './api/developer-permissions-bridge' -import { computerUsePermissionsApi } from './api/computer-use-permissions-bridge' -import { shellApi } from './api/shell-bridge' -import { skillsApi } from './api/skills-bridge' -import { petApi } from './api/pet-bridge' -import { appIconApi } from './api/app-icon-bridge' -import { browserPasswordsApi } from './api/browser-passwords-bridge' +import { wslApi } from './api/wsl/wsl-bridge' +import { wslMoveApi } from './api/wsl/wsl-move-bridge' +import { wslDriveProjectApi } from './api/wsl/wsl-drive-project-bridge' +import { wslDriveUncConversionApi } from './api/wsl/wsl-drive-unc-conversion-bridge' +import { pwshApi } from './api/terminal/pwsh-bridge' +import { gitBashApi } from './api/terminal/git-bash-bridge' +import { pluginsApi } from './api/plugins/plugins-bridge' +import { reposApi } from './api/projects/repos-bridge' +import { projectsApi } from './api/projects/projects-bridge' +import { projectGroupsApi } from './api/projects/project-groups-bridge' +import { folderWorkspacesApi } from './api/workspaces/folder-workspaces-bridge' +import { sparsePresetsApi } from './api/source-control/sparse-presets-bridge' +import { worktreesApi } from './api/workspaces/worktrees-bridge' +import { workspaceCleanupApi } from './api/workspaces/workspace-cleanup-bridge' +import { workspaceSpaceApi } from './api/workspaces/workspace-space-bridge' +import { workspacePortsApi } from './api/workspaces/workspace-ports-bridge' +import { linkPreviewApi } from './api/link-preview/link-preview-bridge' +import { ptyApi } from './api/terminal/pty-bridge' +import { feedbackApi } from './api/diagnostics/feedback-bridge' +import { crashReportsApi } from './api/diagnostics/crash-reports-bridge' +import { exportApi } from './api/document-preview/export-bridge' +import { ghApi } from './api/github/gh-bridge' +import { hostedReviewApi } from './api/hosted-review/hosted-review-bridge' +import { glApi } from './api/gitlab/gitlab' +import { bitbucketApi } from './api/hosted-review/bitbucket-bridge' +import { linearApi } from './api/work-items/linear-bridge' +import { jiraApi } from './api/work-items/jira-bridge' +import { starNagApi } from './api/onboarding/star-nag-bridge' +import { diagnosticsApi } from './api/diagnostics/diagnostics-bridge' +import { settingsApi } from './api/preferences/settings-bridge' +import { agentAwakeApi } from './api/agent-status/agent-awake-bridge' +import { localhostWorktreeLabelsApi } from './api/workspaces/localhost-worktree-labels-bridge' +import { keybindingsApi } from './api/preferences/keybindings-bridge' +import { codexAccountsApi } from './api/agent-accounts/codex-accounts-bridge' +import { claudeAccountsApi } from './api/agent-accounts/claude-accounts-bridge' +import { cliApi } from './api/cli-install/cli-bridge' +import { codexConfigSyncApi } from './api/agent-accounts/codex-config-sync-bridge' +import { preflightApi } from './api/preflight/preflight-bridge' +import { notificationsApi } from './api/notifications/notifications-bridge' +import { onboardingApi } from './api/onboarding/onboarding-bridge' +import { dashboardApi } from './api/window-ui/dashboard-bridge' +import { terminalPreviewApi } from './api/terminal/terminal-preview-bridge' +import { macosTccPromptsApi } from './api/desktop-permissions/macos-tcc-prompts-bridge' +import { developerPermissionsApi } from './api/desktop-permissions/developer-permissions-bridge' +import { computerUsePermissionsApi } from './api/desktop-permissions/computer-use-permissions-bridge' +import { shellApi } from './api/terminal/shell-bridge' +import { skillsApi } from './api/skills/skills-bridge' +import { petApi } from './api/pets/pet-bridge' +import { appIconApi } from './api/window-ui/app-icon-bridge' +import { browserPasswordsApi } from './api/browser/browser-passwords-bridge' import { browserApi } from './api/browser/browser-bridge' -import { emulatorApi } from './api/emulator-bridge' -import { hooksApi } from './api/hooks-bridge' -import { ephemeralVmApi } from './api/ephemeral-vm-bridge' -import { cacheApi } from './api/cache-bridge' -import { sessionApi } from './api/session-bridge' -import { updaterApi } from './api/updater-bridge' -import { docPreviewApi } from './api/doc-preview-bridge' -import { notebookApi } from './api/notebook-bridge' -import { fsApi } from './api/fs-bridge' -import { gitApi } from './api/git-bridge' -import { uiApi } from './api/ui-bridge' -import { statsApi } from './api/stats-bridge' -import { memoryApi } from './api/memory-bridge' -import { claudeUsageApi } from './api/claude-usage-bridge' -import { codexUsageApi } from './api/codex-usage-bridge' -import { openCodeUsageApi } from './api/open-code-usage-bridge' -import { museUsageApi } from './api/muse-usage-bridge' -import { aiVaultApi } from './api/ai-vault-bridge' -import { nativeChatApi } from './api/native-chat-bridge' -import { runtimeApi } from './api/runtime-bridge' -import { runtimeEnvironmentsApi } from './api/runtime-environments-bridge' -import { rateLimitsApi } from './api/rate-limits-bridge' -import { opencodeGoCredentialsApi } from './api/opencode-go-credentials-bridge' -import { minimaxCredentialsApi } from './api/minimax-credentials-bridge' -import { zcodePlanCredentialsApi } from './api/zcode-plan-credentials-bridge' -import { grokAccountsApi } from './api/grok-accounts-bridge' -import { cursorAccountsApi } from './api/cursor-accounts-bridge' -import { sshApi } from './api/ssh-bridge' -import { plainSshTerminalApi } from './api/plain-ssh-terminal-bridge' -import { legacyRelayBridgeApi } from './api/legacy-relay-bridge-api' -import { automationsApi } from './api/automations-bridge' -import { e2eApi } from './api/e2e-bridge' -import { mobileApi } from './api/mobile-bridge' -import { agentStatusApi } from './api/agent-status-bridge' -import { speechApi } from './api/speech-bridge' +import { emulatorApi } from './api/emulator/emulator-bridge' +import { hooksApi } from './api/agent-hooks/hooks-bridge' +import { ephemeralVmApi } from './api/cloud-workspaces/ephemeral-vm-bridge' +import { cacheApi } from './api/github/cache-bridge' +import { sessionApi } from './api/workspaces/session-bridge' +import { updaterApi } from './api/updater/updater-bridge' +import { docPreviewApi } from './api/document-preview/doc-preview-bridge' +import { notebookApi } from './api/document-preview/notebook-bridge' +import { fsApi } from './api/filesystem/fs-bridge' +import { gitApi } from './api/source-control/git-bridge' +import { uiApi } from './api/window-ui/ui-bridge' +import { statsApi } from './api/diagnostics/stats-bridge' +import { memoryApi } from './api/diagnostics/memory-bridge' +import { claudeUsageApi } from './api/agent-usage/claude-usage-bridge' +import { codexUsageApi } from './api/agent-usage/codex-usage-bridge' +import { openCodeUsageApi } from './api/agent-usage/open-code-usage-bridge' +import { museUsageApi } from './api/agent-usage/muse-usage-bridge' +import { aiVaultApi } from './api/ai-vault/ai-vault-bridge' +import { nativeChatApi } from './api/native-chat/native-chat-bridge' +import { runtimeApi } from './api/runtime/runtime-bridge' +import { runtimeEnvironmentsApi } from './api/runtime/runtime-environments-bridge' +import { rateLimitsApi } from './api/agent-usage/rate-limits-bridge' +import { opencodeGoCredentialsApi } from './api/agent-accounts/opencode-go-credentials-bridge' +import { minimaxCredentialsApi } from './api/agent-accounts/minimax-credentials-bridge' +import { zcodePlanCredentialsApi } from './api/agent-accounts/zcode-plan-credentials-bridge' +import { grokAccountsApi } from './api/agent-accounts/grok-accounts-bridge' +import { cursorAccountsApi } from './api/agent-accounts/cursor-accounts-bridge' +import { sshApi } from './api/ssh/ssh-bridge' +import { plainSshTerminalApi } from './api/terminal/plain-ssh-terminal-bridge' +import { legacyRelayBridgeApi } from './api/mobile/legacy-relay-bridge-api' +import { automationsApi } from './api/automations/automations-bridge' +import { e2eApi } from './api/diagnostics/e2e-bridge' +import { mobileApi } from './api/mobile/mobile-bridge' +import { agentStatusApi } from './api/agent-status/agent-status-bridge' +import { speechApi } from './api/speech/speech-bridge' installBrowserFindListener() @@ -131,7 +131,7 @@ const api = { export: exportApi, gh: ghApi, hostedReview: hostedReviewApi, - gl: glApiBridge, + gl: glApi, bitbucket: bitbucketApi, linear: linearApi, jira: jiraApi, diff --git a/src/preload/native-chat-visual-guest-theme.ts b/src/preload/native-chat/native-chat-visual-guest-theme.ts similarity index 95% rename from src/preload/native-chat-visual-guest-theme.ts rename to src/preload/native-chat/native-chat-visual-guest-theme.ts index ef3efe9024c..5237d255702 100644 --- a/src/preload/native-chat-visual-guest-theme.ts +++ b/src/preload/native-chat/native-chat-visual-guest-theme.ts @@ -3,7 +3,7 @@ import { NATIVE_CHAT_VISUAL_GUEST_THEME_READ, NATIVE_CHAT_VISUAL_GUEST_THEME_UPDATE, type NativeChatVisualGuestTheme -} from '../shared/native-chat/native-chat-visual-shell' +} from '../../shared/native-chat/native-chat-visual-shell' export function installNativeChatVisualGuestTheme( ipc: Pick, diff --git a/src/preload/opencode-go-credentials.test.ts b/src/preload/opencode-go-credentials.test.ts deleted file mode 100644 index e7c5f6d4bea..00000000000 --- a/src/preload/opencode-go-credentials.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { opencodeGoCredentialsApi } from './api/opencode-go-credentials-bridge' - -const invoke = vi.hoisted(() => vi.fn(async () => ({ apiKeyConfigured: true }))) -vi.mock('electron', () => ({ ipcRenderer: { invoke } })) - -describe('OpenCode Go credential bridge', () => { - it('exposes only status and write operations', async () => { - expect(await opencodeGoCredentialsApi.getStatus()).toEqual({ apiKeyConfigured: true }) - await opencodeGoCredentialsApi.saveApiKey('fake-key') - await opencodeGoCredentialsApi.clearApiKey() - expect(invoke.mock.calls).toEqual([ - ['opencodeGoCredentials:getStatus'], - ['opencodeGoCredentials:saveApiKey', 'fake-key'], - ['opencodeGoCredentials:clearApiKey'] - ]) - expect(Object.keys(opencodeGoCredentialsApi)).toEqual([ - 'getStatus', - 'saveApiKey', - 'clearApiKey' - ]) - }) -}) diff --git a/src/preload/plugin-frame-guest.test.ts b/src/preload/plugin-frame-guest.test.ts deleted file mode 100644 index 545a4920794..00000000000 --- a/src/preload/plugin-frame-guest.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { buildSync } from 'esbuild' -import { fileURLToPath } from 'node:url' -import { runInNewContext } from 'node:vm' -import { - PLUGIN_FRAME_IPC_CHANNEL, - PLUGIN_FRAME_KEY_CHANNEL, - PLUGIN_FRAME_TRANSPORT_GLOBAL -} from '../shared/plugins/frames/plugin-frame-guest' -import { - createPluginFrameGestureTracker, - createPluginFrameSendBudget, - measurePluginFrameMessageBytes -} from './plugin-frame-guest-send-budget' - -type Transport = { send: (message: unknown) => void; subscribe: (fn: (m: unknown) => void) => void } -type Listener = (event: { isTrusted: boolean } & Record) => void - -const preloadSource = buildSync({ - entryPoints: [fileURLToPath(new URL('./plugin-frame-guest.ts', import.meta.url))], - bundle: true, - platform: 'node', - format: 'cjs', - external: ['electron'], - write: false -}).outputFiles[0].text - -function runPreload(isMainFrame: boolean, contentType = 'text/html') { - const sendToHost = vi.fn() - const ipcListeners: ((event: unknown, message: unknown) => void)[] = [] - const domListeners = new Map() - const activation = { isActive: false } - const pageWindow: Record = { - addEventListener: (name: string, listener: Listener) => domListeners.set(name, listener) - } - runInNewContext(preloadSource, { - window: pageWindow, - document: { contentType }, - Object, - ArrayBuffer, - Array, - Date, - Number, - String, - TextEncoder, - queueMicrotask, - navigator: { userActivation: activation }, - process: { isMainFrame }, - require: (name: string) => { - expect(name).toBe('electron') - return { - ipcRenderer: { - sendToHost, - on: (channel: string, listener: (event: unknown, message: unknown) => void) => { - expect(channel).toBe(PLUGIN_FRAME_IPC_CHANNEL) - ipcListeners.push(listener) - } - }, - contextBridge: { - executeInMainWorld: (script: { func: (...args: unknown[]) => void; args: unknown[] }) => - script.func(...script.args) - } - } - } - }) - const input = (name: string, event: { isTrusted: boolean } & Record) => { - activation.isActive = activation.isActive || event.isTrusted - domListeners.get(name)?.(event) - } - const transport = (): Transport => - Object.getOwnPropertyDescriptor(pageWindow, PLUGIN_FRAME_TRANSPORT_GLOBAL)?.value - return { sendToHost, ipcListeners, pageWindow, input, transport, activation } -} - -describe('plugin frame guest preload', () => { - it('hands the shell a deletable transport and stamps each send with a gesture serial', () => { - const { sendToHost, ipcListeners, pageWindow, input, transport } = runPreload(true) - expect( - Object.getOwnPropertyDescriptor(pageWindow, PLUGIN_FRAME_TRANSPORT_GLOBAL) - ).toMatchObject({ configurable: true, enumerable: false, writable: false }) - transport().send({ orca: 1, kind: 'evt', event: 'ready' }) - expect(sendToHost).toHaveBeenLastCalledWith( - PLUGIN_FRAME_IPC_CHANNEL, - { orca: 1, kind: 'evt', event: 'ready' }, - { gesture: 0 } - ) - // Untrusted (page-dispatched) input is not a gesture. - input('pointerdown', { isTrusted: false }) - transport().send({}) - expect(sendToHost).toHaveBeenLastCalledWith(PLUGIN_FRAME_IPC_CHANNEL, {}, { gesture: 0 }) - input('pointerdown', { isTrusted: true }) - transport().send({}) - expect(sendToHost).toHaveBeenLastCalledWith(PLUGIN_FRAME_IPC_CHANNEL, {}, { gesture: 1 }) - input('keydown', { isTrusted: true, key: 'a', code: 'KeyA' }) - transport().send({}) - expect(sendToHost).toHaveBeenLastCalledWith(PLUGIN_FRAME_IPC_CHANNEL, {}, { gesture: 2 }) - const first = vi.fn() - transport().subscribe(first) - transport().subscribe(vi.fn()) - expect(ipcListeners).toHaveLength(1) - ipcListeners[0]?.({}, { orca: 1, kind: 'res', id: 0 }) - expect(first).toHaveBeenCalledWith({ orca: 1, kind: 'res', id: 0 }) - }) - - it('reports trusted modifier chords on their own channel, never page-dispatched ones', () => { - const { sendToHost, input } = runPreload(true) - const chord = { key: 's', code: 'KeyS', metaKey: true, ctrlKey: false, altKey: false } - input('keydown', { isTrusted: false, ...chord, shiftKey: false }) - expect(sendToHost).not.toHaveBeenCalledWith(PLUGIN_FRAME_KEY_CHANNEL, expect.anything()) - input('keydown', { isTrusted: true, ...chord, shiftKey: false, repeat: false }) - expect(sendToHost).toHaveBeenCalledWith(PLUGIN_FRAME_KEY_CHANNEL, { ...chord, shiftKey: false }) - }) - - it('answers a refused request at once instead of leaving it pending', async () => { - const { sendToHost, transport } = runPreload(true) - const receive = vi.fn() - transport().subscribe(receive) - transport().send({ - orca: 1, - kind: 'req', - id: 7, - method: 'notifications.show', - params: { title: 'x'.repeat(200 * 1024) } - }) - await Promise.resolve() - expect(sendToHost).not.toHaveBeenCalled() - expect(receive).toHaveBeenCalledWith({ - orca: 1, - kind: 'res', - id: 7, - error: expect.objectContaining({ code: 'too_large', retryable: false }) - }) - }) - - it('leaves subframes and non-HTML documents without a transport', () => { - expect(PLUGIN_FRAME_TRANSPORT_GLOBAL in runPreload(false).pageWindow).toBe(false) - expect(PLUGIN_FRAME_TRANSPORT_GLOBAL in runPreload(true, 'image/svg+xml').pageWindow).toBe( - false - ) - }) -}) - -describe('isolated-world send budget', () => { - it('measures UTF-8 like the host, and keeps big payloads to saves and edits', () => { - expect(measurePluginFrameMessageBytes('abc', 1000)).toBe(3) - expect(measurePluginFrameMessageBytes('é', 1000)).toBe(2) - const admit = createPluginFrameSendBudget() - const big = 'x'.repeat(30 * 1024 * 1024) - expect(admit({ kind: 'req', method: 'editor.applyEdit', params: { text: big } })).toBeNull() - expect(admit({ kind: 'req', method: 'files.saveAs', params: { data: big } })).toBeNull() - expect(admit({ kind: 'req', method: 'notifications.show', params: { title: big } })).toEqual({ - code: 'too_large' - }) - }) - - it('refuses floods with a retry hint', () => { - let clock = 0 - const admit = createPluginFrameSendBudget(() => clock, { - maxMessages: 2, - maxBytes: 1_000_000, - perMs: 100 - }) - expect(admit({ a: 1 })).toBeNull() - clock = 40 - expect(admit({ a: 1 })).toBeNull() - expect(admit({ a: 1 })).toEqual({ code: 'rate_limited', retryAfterMs: 60 }) - clock = 100 - expect(admit({ a: 1 })).toBeNull() - }) - - it('counts a gesture only for trusted input, and only while activation lasts', () => { - let clock = 0 - const gestures = createPluginFrameGestureTracker(() => clock) - gestures.note({ isTrusted: false }) - expect(gestures.current(true)).toBe(0) - gestures.note({ isTrusted: true }) - expect(gestures.current(true)).toBe(1) - expect(gestures.current(false)).toBe(0) - clock = 6_000 - expect(gestures.current(true)).toBe(0) - }) -}) diff --git a/src/preload/plugin-frame-guest.ts b/src/preload/plugin-frame-guest.ts index f68e4787b4e..42fdb3ea6cd 100644 --- a/src/preload/plugin-frame-guest.ts +++ b/src/preload/plugin-frame-guest.ts @@ -4,12 +4,12 @@ import { PRELOAD_PLUGIN_FRAME_IPC_CHANNEL, PRELOAD_PLUGIN_FRAME_KEY_CHANNEL, PRELOAD_PLUGIN_FRAME_TRANSPORT_GLOBAL -} from './plugin-frame-guest-transport' +} from './plugins/frames/plugin-frame-guest-transport' import { createPluginFrameGestureTracker, createPluginFrameSendBudget, type PluginFrameSendRefusal -} from './plugin-frame-guest-send-budget' +} from './plugins/frames/plugin-frame-guest-send-budget' // Raw require keeps the sandboxed preload standalone in the CJS build. const electron: { diff --git a/src/preload/plugin-frame-guest-render-lane.test.ts b/src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts similarity index 100% rename from src/preload/plugin-frame-guest-render-lane.test.ts rename to src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts diff --git a/src/preload/plugin-frame-guest-send-budget.ts b/src/preload/plugins/frames/plugin-frame-guest-send-budget.ts similarity index 100% rename from src/preload/plugin-frame-guest-send-budget.ts rename to src/preload/plugins/frames/plugin-frame-guest-send-budget.ts diff --git a/src/preload/plugin-frame-guest-transport.ts b/src/preload/plugins/frames/plugin-frame-guest-transport.ts similarity index 100% rename from src/preload/plugin-frame-guest-transport.ts rename to src/preload/plugins/frames/plugin-frame-guest-transport.ts diff --git a/src/preload/plugins/frames/plugin-frame-guest.test.ts b/src/preload/plugins/frames/plugin-frame-guest.test.ts new file mode 100644 index 00000000000..eef66dc5d5a --- /dev/null +++ b/src/preload/plugins/frames/plugin-frame-guest.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it, vi } from 'vitest' +import { buildSync } from 'esbuild' +import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' +import { + PLUGIN_FRAME_IPC_CHANNEL, + PLUGIN_FRAME_TRANSPORT_GLOBAL +} from '../../../shared/plugins/frames/plugin-frame-guest' +import { + createPluginFrameGestureTracker, + createPluginFrameSendBudget, + measurePluginFrameMessageBytes +} from './plugin-frame-guest-send-budget' + +type Transport = { send: (message: unknown) => void; subscribe: (fn: (m: unknown) => void) => void } +type Listener = (event: { isTrusted: boolean } & Record) => void + +const preloadSource = buildSync({ + entryPoints: [fileURLToPath(new URL('../../plugin-frame-guest.ts', import.meta.url))], + bundle: true, + platform: 'node', + format: 'cjs', + external: ['electron'], + write: false +}).outputFiles[0].text + +function runPreload(isMainFrame: boolean, contentType = 'text/html') { + const sendToHost = vi.fn() + const ipcListeners: ((event: unknown, message: unknown) => void)[] = [] + const domListeners = new Map() + const activation = { isActive: false } + const pageWindow: Record = { + addEventListener: (name: string, listener: Listener) => domListeners.set(name, listener) + } + runInNewContext(preloadSource, { + window: pageWindow, + document: { contentType }, + Object, + ArrayBuffer, + Array, + Date, + Number, + String, + TextEncoder, + queueMicrotask, + navigator: { userActivation: activation }, + process: { isMainFrame }, + require: (name: string) => { + expect(name).toBe('electron') + return { + ipcRenderer: { + sendToHost, + on: (channel: string, listener: (event: unknown, message: unknown) => void) => { + expect(channel).toBe(PLUGIN_FRAME_IPC_CHANNEL) + ipcListeners.push(listener) + } + }, + contextBridge: { + executeInMainWorld: (script: { func: (...args: unknown[]) => void; args: unknown[] }) => + script.func(...script.args) + } + } + } + }) + const input = (name: string, event: { isTrusted: boolean } & Record) => { + activation.isActive = activation.isActive || event.isTrusted + domListeners.get(name)?.(event) + } + const transport = (): Transport => + Object.getOwnPropertyDescriptor(pageWindow, PLUGIN_FRAME_TRANSPORT_GLOBAL)?.value + return { sendToHost, ipcListeners, pageWindow, input, transport, activation } +} + +describe('plugin frame guest preload', () => { + it('leaves subframes and non-HTML documents without a transport', () => { + expect(PLUGIN_FRAME_TRANSPORT_GLOBAL in runPreload(false).pageWindow).toBe(false) + expect(PLUGIN_FRAME_TRANSPORT_GLOBAL in runPreload(true, 'image/svg+xml').pageWindow).toBe( + false + ) + }) +}) + +describe('isolated-world send budget', () => { + it('measures UTF-8 like the host, and keeps big payloads to saves and edits', () => { + expect(measurePluginFrameMessageBytes('abc', 1000)).toBe(3) + expect(measurePluginFrameMessageBytes('é', 1000)).toBe(2) + const admit = createPluginFrameSendBudget() + const big = 'x'.repeat(30 * 1024 * 1024) + expect(admit({ kind: 'req', method: 'editor.applyEdit', params: { text: big } })).toBeNull() + expect(admit({ kind: 'req', method: 'files.saveAs', params: { data: big } })).toBeNull() + expect(admit({ kind: 'req', method: 'notifications.show', params: { title: big } })).toEqual({ + code: 'too_large' + }) + }) + + it('refuses floods with a retry hint', () => { + let clock = 0 + const admit = createPluginFrameSendBudget(() => clock, { + maxMessages: 2, + maxBytes: 1_000_000, + perMs: 100 + }) + expect(admit({ a: 1 })).toBeNull() + clock = 40 + expect(admit({ a: 1 })).toBeNull() + expect(admit({ a: 1 })).toEqual({ code: 'rate_limited', retryAfterMs: 60 }) + clock = 100 + expect(admit({ a: 1 })).toBeNull() + }) + + it('counts a gesture only for trusted input, and only while activation lasts', () => { + let clock = 0 + const gestures = createPluginFrameGestureTracker(() => clock) + gestures.note({ isTrusted: false }) + expect(gestures.current(true)).toBe(0) + gestures.note({ isTrusted: true }) + expect(gestures.current(true)).toBe(1) + expect(gestures.current(false)).toBe(0) + clock = 6_000 + expect(gestures.current(true)).toBe(0) + }) +}) diff --git a/src/preload/preload-runtime-support.ts b/src/preload/preload-runtime-support.ts deleted file mode 100644 index f8753d7794e..00000000000 --- a/src/preload/preload-runtime-support.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { ipcRenderer } from 'electron' -import { createBrowserClientPageRendererRequests } from './browser-client-page-renderer-requests' -import { createBrowserFindSubscriptions } from './browser-find-subscriptions' -import { registerRendererRestartIpcRelays } from './renderer-restart-wiring' -import { createUpdaterQuitAbortRelay } from '../shared/renderer-restart-preparation' -import { ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT } from '../shared/updater-renderer-events' -export async function awaitBeforeUnloadCheckpoint(): Promise { - const result = (await ipcRenderer.invoke('app:await-before-unload-checkpoint')) as { - ok?: unknown - } - if (result?.ok !== true) { - throw new Error('Failed to persist renderer state before unload.') - } -} - -export const startupDiagnosticsEnabled = process.env.ORCA_STARTUP_DIAGNOSTICS === '1' - -export function getLinuxDisplayServer(): 'wayland' | 'x11' | null { - if (process.platform !== 'linux') { - return null - } - if ( - process.env.WAYLAND_DISPLAY || - process.env.XDG_SESSION_TYPE?.toLowerCase() === 'wayland' || - process.env.ELECTRON_OZONE_PLATFORM_HINT?.toLowerCase() === 'wayland' - ) { - return 'wayland' - } - return process.env.DISPLAY ? 'x11' : null -} - -export const browserFindSubscriptions = createBrowserFindSubscriptions() -export const browserClientPageRendererRequests = createBrowserClientPageRendererRequests({ - ipc: ipcRenderer, - isTopFrame: () => window.top === window -}) -let browserFindListenerInstalled = false - -export function installBrowserFindListener(): void { - if (browserFindListenerInstalled) { - return - } - ipcRenderer.on('ui:findInBrowserPage', (_event, source: unknown) => { - browserFindSubscriptions.dispatch(source) - }) - browserFindListenerInstalled = true -} - -export const updaterQuitAbortRelay = createUpdaterQuitAbortRelay( - window, - ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT -) - -registerRendererRestartIpcRelays(ipcRenderer, window, updaterQuitAbortRelay) diff --git a/src/preload/renderer-restart-wiring.test.ts b/src/preload/renderer-restart-wiring.test.ts deleted file mode 100644 index 595ef92a1cf..00000000000 --- a/src/preload/renderer-restart-wiring.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../shared/renderer-shutdown-events' -import { - ORCA_APP_RESTART_ABORTED_EVENT, - ORCA_APP_RESTART_STARTED_EVENT, - ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT -} from '../shared/updater-renderer-events' -import { - prepareAndInvokeAppRestart, - prepareAndInvokeUpdaterInstall, - registerRendererRestartIpcRelays -} from './renderer-restart-wiring' - -function restartIpc(eventTarget: EventTarget) { - const ipcRenderer = Object.assign(new EventEmitter(), { - invoke: vi.fn(async () => {}), - postMessage: vi.fn(), - send: vi.fn(), - sendSync: vi.fn(), - sendToHost: vi.fn() - }) - const relay = { handleStatus: vi.fn(), abort: vi.fn() } - registerRendererRestartIpcRelays(ipcRenderer, eventTarget, relay) - return { ipcRenderer, ...relay } -} - -describe('renderer restart wiring', () => { - it.each(['no-op', 'failure'] as const)( - 'keeps a committed restart prepared after a later %s', - async (outcome) => { - const eventTarget = new EventTarget() - const { ipcRenderer } = restartIpc(eventTarget) - const aborted = vi.fn() - const started = vi.fn() - const checkpoint = vi.fn(async () => {}) - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) - await prepareAndInvokeAppRestart( - eventTarget, - async () => { - ipcRenderer.emit('app:restart-committed') - return true - }, - checkpoint, - Boolean - ) - const subsequent = prepareAndInvokeAppRestart( - eventTarget, - async () => { - if (outcome === 'failure') { - throw new Error('already finalized') - } - return false - }, - checkpoint, - Boolean - ) - await (outcome === 'failure' - ? expect(subsequent).rejects.toThrow('already finalized') - : expect(subsequent).resolves.toBe(false)) - expect(checkpoint).toHaveBeenCalledOnce() - expect(started).toHaveBeenCalledOnce() - expect(aborted).not.toHaveBeenCalled() - } - ) - - it('refuses overlapping preparation without abandoning the accepted restart', async () => { - const eventTarget = new EventTarget() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - const checkpoint = Promise.withResolvers() - const invoke = vi.fn(async () => true) - const first = prepareAndInvokeAppRestart(eventTarget, invoke, () => checkpoint.promise) - const refused = vi.fn(async () => false) - await expect( - prepareAndInvokeAppRestart(eventTarget, refused, async () => {}, Boolean) - ).rejects.toThrow('already in progress') - expect(refused).not.toHaveBeenCalled() - expect(aborted).not.toHaveBeenCalled() - checkpoint.resolve() - await expect(first).resolves.toBe(true) - expect(invoke).toHaveBeenCalledOnce() - }) - - it('retains late commitment across an unrelated unload veto', async () => { - const eventTarget = new EventTarget() - const abandoned = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, abandoned) - eventTarget.addEventListener(ORCA_RENDERER_UNLOAD_PREVENTED_EVENT, abandoned) - const { ipcRenderer } = restartIpc(eventTarget) - const checkpoint = vi.fn(async () => {}) - await prepareAndInvokeAppRestart(eventTarget, async () => true, checkpoint, Boolean) - ipcRenderer.emit('app:restart-committed') - await prepareAndInvokeAppRestart(eventTarget, async () => false, checkpoint, Boolean) - expect(checkpoint).toHaveBeenCalledOnce() - ipcRenderer.emit('window:unload-prevented') - await prepareAndInvokeAppRestart(eventTarget, async () => true, checkpoint, Boolean) - expect(checkpoint).toHaveBeenCalledOnce() - expect(abandoned).not.toHaveBeenCalled() - }) - - it('releases preparation ownership and its listener after checkpoint failure', async () => { - const eventTarget = new EventTarget() - const add = vi.spyOn(eventTarget, 'addEventListener') - const remove = vi.spyOn(eventTarget, 'removeEventListener') - await expect( - prepareAndInvokeAppRestart( - eventTarget, - async () => {}, - async () => { - throw new Error('checkpoint failed') - } - ) - ).rejects.toThrow('checkpoint failed') - await prepareAndInvokeAppRestart( - eventTarget, - async () => {}, - async () => {} - ) - expect(add.mock.calls).toHaveLength(2) - expect(remove.mock.calls).toEqual(add.mock.calls) - }) - - it('marks preparation before invoking main and aborts on IPC failure', async () => { - const eventTarget = new EventTarget() - const calls: string[] = [] - eventTarget.addEventListener(ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT, () => { - calls.push('prepared') - }) - const relay = { - markPrepared: () => calls.push('marked'), - abort: () => calls.push('aborted') - } - const invoke = vi.fn(async () => { - calls.push('invoked') - throw new Error('IPC failed') - }) - - await expect( - prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, async () => { - calls.push('checkpoint-flushed') - }) - ).rejects.toThrow('IPC failed') - - expect(calls).toEqual(['prepared', 'checkpoint-flushed', 'marked', 'invoked', 'aborted']) - }) - - it('never installs the update when the shutdown checkpoint fails to persist', async () => { - const eventTarget = new EventTarget() - const invoke = vi.fn(() => Promise.resolve()) - const relay = { markPrepared: vi.fn(), abort: vi.fn() } - - await expect( - prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, () => - Promise.reject(new Error('Failed to persist renderer state before unload.')) - ) - ).rejects.toThrow('Failed to persist renderer state before unload.') - - expect(invoke).not.toHaveBeenCalled() - expect(relay.markPrepared).not.toHaveBeenCalled() - }) -}) diff --git a/src/preload/browser-client-page-renderer-requests.test.ts b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts similarity index 81% rename from src/preload/browser-client-page-renderer-requests.test.ts rename to src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts index 6baaf0215ba..5f0f88322b2 100644 --- a/src/preload/browser-client-page-renderer-requests.test.ts +++ b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { BrowserClientPageRendererReply, BrowserClientPageRendererRequest -} from '../shared/browser/client-hosting/browser-client-page-renderer-protocol' +} from '../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' import { createBrowserClientPageRendererRequests } from './browser-client-page-renderer-requests' type Listener = (event: unknown, request: unknown) => void @@ -230,51 +230,4 @@ describe('browser client page renderer preload requests', () => { expect(callback).toHaveBeenCalledTimes(2) expect(ipc.sent).toHaveLength(1) }) - - it.each(['dispose', 'unsubscribe', 'replace', 'timeout'] as const)( - 'does not start already-settled callbacks after %s', - async (action) => { - vi.useFakeTimers() - const ipc = new FakeIpc() - const requests = createBrowserClientPageRendererRequests({ - ipc, - isTopFrame: () => true, - timeoutMs: 50 - }) - const callback = vi.fn(() => ({ type: 'mounted' as const, webContentsId: 91 })) - const unsubscribe = requests.subscribe(callback) - for (let index = 0; index < 64; index += 1) { - ipc.emit(request(`request-${index}`)) - } - let errorCode = 'browser_client_page_renderer_preload_disposed' - if (action === 'dispose') { - requests.dispose() - } else if (action === 'unsubscribe') { - unsubscribe() - errorCode = 'browser_client_page_renderer_subscriber_unavailable' - } else if (action === 'replace') { - requests.subscribe(() => ({ type: 'mounted', webContentsId: 92 })) - errorCode = 'browser_client_page_renderer_subscriber_replaced' - } else { - vi.advanceTimersByTime(50) - errorCode = 'browser_client_page_renderer_subscriber_timeout' - } - try { - await flush() - expect(ipc.sent.map(({ reply }) => reply)).toEqual( - Array.from({ length: 64 }, (_, index) => ({ - type: 'failed', - errorCode, - requestId: `request-${index}`, - page: PAGE, - operation: 'mountPage' - })) - ) - expect(vi.getTimerCount()).toBe(0) - expect(callback).not.toHaveBeenCalled() - } finally { - requests.dispose() - } - } - ) }) diff --git a/src/preload/browser-client-page-renderer-requests.ts b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts similarity index 99% rename from src/preload/browser-client-page-renderer-requests.ts rename to src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts index 46aec46359e..d52ef50759e 100644 --- a/src/preload/browser-client-page-renderer-requests.ts +++ b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts @@ -6,7 +6,7 @@ import { BrowserClientPageRendererRequest, type BrowserClientPageRendererOutcome as RendererOutcome, type BrowserClientPageRendererRequest as RendererRequest -} from '../shared/browser/client-hosting/browser-client-page-renderer-protocol' +} from '../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' const DEFAULT_MAX_PENDING = 512 const DEFAULT_TIMEOUT_MS = 10_000 diff --git a/src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts b/src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts new file mode 100644 index 00000000000..f85bfb4835b --- /dev/null +++ b/src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it, vi } from 'vitest' +import { createBrowserFindSubscriptions } from './browser-find-subscriptions' + +const FIRST_SOURCE = { + browserPageId: 'page-1', + browserWorkspaceId: 'workspace-1' +} +const SAME_WORKSPACE_SOURCE = { + browserPageId: 'page-2', + browserWorkspaceId: FIRST_SOURCE.browserWorkspaceId +} +const SAME_PAGE_SOURCE = { + browserPageId: FIRST_SOURCE.browserPageId, + browserWorkspaceId: 'workspace-2' +} + +describe('browser Find subscriptions', () => { + it('dispatches only to the exact browser page and workspace owner', () => { + const subscriptions = createBrowserFindSubscriptions() + const firstCallback = vi.fn() + const sameWorkspaceCallback = vi.fn() + const samePageCallback = vi.fn() + subscriptions.subscribe(FIRST_SOURCE, firstCallback) + subscriptions.subscribe(SAME_WORKSPACE_SOURCE, sameWorkspaceCallback) + subscriptions.subscribe(SAME_PAGE_SOURCE, samePageCallback) + + subscriptions.dispatch(FIRST_SOURCE) + + expect(firstCallback).toHaveBeenCalledOnce() + expect(sameWorkspaceCallback).not.toHaveBeenCalled() + expect(samePageCallback).not.toHaveBeenCalled() + }) + + it('dispatches a page-only target to every workspace holding that page', () => { + const subscriptions = createBrowserFindSubscriptions() + const firstCallback = vi.fn() + const sameWorkspaceCallback = vi.fn() + const samePageCallback = vi.fn() + subscriptions.subscribe(FIRST_SOURCE, firstCallback) + subscriptions.subscribe(SAME_WORKSPACE_SOURCE, sameWorkspaceCallback) + subscriptions.subscribe(SAME_PAGE_SOURCE, samePageCallback) + + subscriptions.dispatch({ browserPageId: FIRST_SOURCE.browserPageId }) + + expect(firstCallback).toHaveBeenCalledOnce() + expect(samePageCallback).toHaveBeenCalledOnce() + expect(sameWorkspaceCallback).not.toHaveBeenCalled() + }) + + it('dispatches an explicitly undefined workspace as page-only, not as a miss', () => { + const subscriptions = createBrowserFindSubscriptions() + const callback = vi.fn() + subscriptions.subscribe(FIRST_SOURCE, callback) + + // Structured-clone IPC preserves explicitly undefined properties. + subscriptions.dispatch({ + browserPageId: FIRST_SOURCE.browserPageId, + browserWorkspaceId: undefined + }) + + expect(callback).toHaveBeenCalledOnce() + }) + + it('rejects malformed identities and blank ids', () => { + const subscriptions = createBrowserFindSubscriptions() + const callback = vi.fn() + subscriptions.subscribe(FIRST_SOURCE, callback) + + subscriptions.dispatch(undefined) + subscriptions.dispatch(['page-1']) + subscriptions.dispatch({ browserWorkspaceId: FIRST_SOURCE.browserWorkspaceId }) + subscriptions.dispatch({ browserPageId: '' }) + subscriptions.dispatch({ + browserPageId: FIRST_SOURCE.browserPageId, + browserWorkspaceId: '' + }) + + expect(callback).not.toHaveBeenCalled() + }) +}) diff --git a/src/preload/browser-find-subscriptions.ts b/src/preload/renderer/browser-pages/browser-find-subscriptions.ts similarity index 94% rename from src/preload/browser-find-subscriptions.ts rename to src/preload/renderer/browser-pages/browser-find-subscriptions.ts index 8bd9e2a76d0..5e4928acd08 100644 --- a/src/preload/browser-find-subscriptions.ts +++ b/src/preload/renderer/browser-pages/browser-find-subscriptions.ts @@ -1,17 +1,15 @@ -import { asBrowserFindTarget, type BrowserFindSource } from '../shared/browser-find-source' +import { asBrowserFindTarget, type BrowserFindSource } from '../../../shared/browser-find-source' type BrowserFindCallback = () => void export function createBrowserFindSubscriptions(): { dispatch: (target: unknown) => void subscribe: (source: BrowserFindSource, callback: BrowserFindCallback) => () => void - subscribedPageCount: () => number } { // Page-only targets must reach every workspace holding that page. const callbacksByPage = new Map>>() return { - subscribedPageCount: () => callbacksByPage.size, dispatch: (target) => { const findTarget = asBrowserFindTarget(target) if (!findTarget) { diff --git a/src/preload/renderer-heap-statistics-reader.test.ts b/src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts similarity index 100% rename from src/preload/renderer-heap-statistics-reader.test.ts rename to src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts diff --git a/src/preload/renderer-heap-statistics-reader.ts b/src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts similarity index 91% rename from src/preload/renderer-heap-statistics-reader.ts rename to src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts index aa578e8ff46..9126e041574 100644 --- a/src/preload/renderer-heap-statistics-reader.ts +++ b/src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts @@ -1,4 +1,4 @@ -import type { RendererHeapStatistics } from '../shared/renderer-heap-statistics' +import type { RendererHeapStatistics } from '../../../shared/renderer-heap-statistics' type HeapStatisticsSource = Pick diff --git a/src/preload/renderer-process-memory-reader.test.ts b/src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts similarity index 100% rename from src/preload/renderer-process-memory-reader.test.ts rename to src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts diff --git a/src/preload/renderer-process-memory-reader.ts b/src/preload/renderer/diagnostics/renderer-process-memory-reader.ts similarity index 89% rename from src/preload/renderer-process-memory-reader.ts rename to src/preload/renderer/diagnostics/renderer-process-memory-reader.ts index 2e501b3e740..01dbb1e2414 100644 --- a/src/preload/renderer-process-memory-reader.ts +++ b/src/preload/renderer/diagnostics/renderer-process-memory-reader.ts @@ -1,4 +1,4 @@ -import type { RendererProcessMemory } from '../shared/renderer-process-memory' +import type { RendererProcessMemory } from '../../../shared/renderer-process-memory' type ProcessMemorySource = Pick diff --git a/src/preload/e2e-config.ts b/src/preload/renderer/e2e-config.ts similarity index 93% rename from src/preload/e2e-config.ts rename to src/preload/renderer/e2e-config.ts index c62c844a7c8..d524eb2c5da 100644 --- a/src/preload/e2e-config.ts +++ b/src/preload/renderer/e2e-config.ts @@ -1,4 +1,4 @@ -import { createE2EConfig } from '../shared/e2e-config' +import { createE2EConfig } from '../../shared/e2e-config' const preloadEnv = ( import.meta as ImportMeta & { diff --git a/src/preload/renderer/hidden-window-frame-pump.ts b/src/preload/renderer/hidden-window-frame-pump.ts new file mode 100644 index 00000000000..015ae7ff6b2 --- /dev/null +++ b/src/preload/renderer/hidden-window-frame-pump.ts @@ -0,0 +1,62 @@ +import { + HIDDEN_WINDOW_FRAME_PUMP_INTERVAL_MS, + hasHiddenWindowFramePumpArgument +} from '../../shared/hidden-window-frame-pump' + +// Near-black so the single damaged frame is indistinguishable even if the window were visible. +const FLIP_COLOR = 'rgb(1, 1, 1)' + +type FramePumpStyle = Pick< + CSSStyleDeclaration, + 'getPropertyValue' | 'getPropertyPriority' | 'setProperty' | 'removeProperty' +> + +export type HiddenWindowFramePumpDeps = { + rootStyle: () => FramePumpStyle | null + requestAnimationFrame: (callback: () => void) => unknown + /** Runs callback every ms; returns the cancel function. */ + every: (callback: () => void, ms: number) => () => void +} + +/** Damage one frame per interval by flipping the root background, then restore the inline style exactly. */ +export function startHiddenWindowFramePump(deps: HiddenWindowFramePumpDeps): () => void { + let stopped = false + let flipping = false + const cancel = deps.every(() => { + const style = deps.rootStyle() + if (stopped || flipping || !style) { + return + } + flipping = true + deps.requestAnimationFrame(() => { + const previousValue = style.getPropertyValue('background-color') + const previousPriority = style.getPropertyPriority('background-color') + style.setProperty('background-color', FLIP_COLOR, previousPriority) + deps.requestAnimationFrame(() => { + if (previousValue) { + style.setProperty('background-color', previousValue, previousPriority) + } else { + style.removeProperty('background-color') + } + flipping = false + }) + }) + }, HIDDEN_WINDOW_FRAME_PUMP_INTERVAL_MS) + return () => { + if (!stopped) { + stopped = true + cancel() + } + } +} + +/** Only main's stop ends the pump; Windows can report a never-shown window visible after a desktop change. */ +export function installHiddenWindowFramePump( + argv: readonly string[], + onStopRequest: (stop: () => void) => void, + deps: HiddenWindowFramePumpDeps +): void { + if (hasHiddenWindowFramePumpArgument(argv)) { + onStopRequest(startHiddenWindowFramePump(deps)) + } +} diff --git a/src/preload/renderer/renderer-runtime.ts b/src/preload/renderer/renderer-runtime.ts new file mode 100644 index 00000000000..d3f4e6d89fc --- /dev/null +++ b/src/preload/renderer/renderer-runtime.ts @@ -0,0 +1,54 @@ +import { ipcRenderer } from 'electron' +import { createBrowserClientPageRendererRequests } from './browser-pages/browser-client-page-renderer-requests' +import { createBrowserFindSubscriptions } from './browser-pages/browser-find-subscriptions' +import { registerRendererRestartIpcRelays } from './restart/renderer-restart-wiring' +import { createUpdaterQuitAbortRelay } from '../../shared/renderer-restart-preparation' +import { ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT } from '../../shared/updater-renderer-events' +export async function awaitBeforeUnloadCheckpoint(): Promise { + const result = (await ipcRenderer.invoke('app:await-before-unload-checkpoint')) as { + ok?: unknown + } + if (result?.ok !== true) { + throw new Error('Failed to persist renderer state before unload.') + } +} + +export const startupDiagnosticsEnabled = process.env.ORCA_STARTUP_DIAGNOSTICS === '1' + +export function getLinuxDisplayServer(): 'wayland' | 'x11' | null { + if (process.platform !== 'linux') { + return null + } + if ( + process.env.WAYLAND_DISPLAY || + process.env.XDG_SESSION_TYPE?.toLowerCase() === 'wayland' || + process.env.ELECTRON_OZONE_PLATFORM_HINT?.toLowerCase() === 'wayland' + ) { + return 'wayland' + } + return process.env.DISPLAY ? 'x11' : null +} + +export const browserFindSubscriptions = createBrowserFindSubscriptions() +export const browserClientPageRendererRequests = createBrowserClientPageRendererRequests({ + ipc: ipcRenderer, + isTopFrame: () => window.top === window +}) +let browserFindListenerInstalled = false + +export function installBrowserFindListener(): void { + if (browserFindListenerInstalled) { + return + } + ipcRenderer.on('ui:findInBrowserPage', (_event, source: unknown) => { + browserFindSubscriptions.dispatch(source) + }) + browserFindListenerInstalled = true +} + +export const updaterQuitAbortRelay = createUpdaterQuitAbortRelay( + window, + ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT +) + +registerRendererRestartIpcRelays(ipcRenderer, window, updaterQuitAbortRelay) diff --git a/src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts b/src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts new file mode 100644 index 00000000000..94000e9bbff --- /dev/null +++ b/src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts @@ -0,0 +1,96 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PreloadApi } from '../../api-types' +import { ORCA_APP_RESTART_STARTED_EVENT } from '../../../shared/updater-renderer-events' + +const { exposeInMainWorld, invoke, on, removeListener, send, sendSync, getPathForFile } = + vi.hoisted(() => ({ + exposeInMainWorld: vi.fn(), + invoke: vi.fn(), + on: vi.fn(), + removeListener: vi.fn(), + send: vi.fn(), + sendSync: vi.fn(), + getPathForFile: vi.fn(() => '/files/notes.txt') + })) + +vi.mock('electron', () => ({ + contextBridge: { exposeInMainWorld }, + ipcRenderer: { invoke, on, removeListener, send, sendSync }, + webFrame: { + getZoomFactor: vi.fn(() => 1), + setZoomFactor: vi.fn(), + setVisualZoomLevelLimits: vi.fn() + }, + webUtils: { getPathForFile } +})) + +describe('native preload destructive app actions', () => { + const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') + let eventTarget: EventTarget + + beforeEach(() => { + vi.resetModules() + exposeInMainWorld.mockReset() + invoke.mockReset() + on.mockReset() + removeListener.mockReset() + send.mockReset() + sendSync.mockReset() + Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) + eventTarget = new EventTarget() + vi.stubGlobal('window', eventTarget) + vi.stubGlobal('document', { addEventListener: vi.fn() }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + if (originalContextIsolated) { + Object.defineProperty(process, 'contextIsolated', originalContextIsolated) + } else { + Reflect.deleteProperty(process, 'contextIsolated') + } + }) + + const loadApi = async (): Promise => { + await import('../../index') + return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi + } + + it('exposes the durable checkpoint join the lazy-chunk recovery reload depends on', async () => { + const api = await loadApi() + invoke.mockResolvedValue({ ok: true }) + + await expect(api.app.awaitBeforeUnloadCheckpoint()).resolves.toBeUndefined() + expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') + + invoke.mockResolvedValue({ ok: false }) + + await expect(api.app.awaitBeforeUnloadCheckpoint()).rejects.toThrow( + 'Failed to persist renderer state before unload.' + ) + }) + + it('awaits renderer durability before profile maintenance and preserves its result', async () => { + const api = await loadApi() + const started = vi.fn() + eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) + let finishCheckpoint = (_result: { ok: boolean }): void => {} + const checkpoint = new Promise((resolve) => { + finishCheckpoint = resolve + }) + const result = { status: 'relaunching' } + invoke.mockImplementation((channel: string) => + channel === 'app:await-before-unload-checkpoint' ? checkpoint : Promise.resolve(result) + ) + + const switching = api.orcaProfiles.switchProfile({ profileId: 'target' }) + await vi.waitFor(() => + expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') + ) + expect(started).toHaveBeenCalledOnce() + expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything()) + finishCheckpoint({ ok: true }) + await expect(switching).resolves.toBe(result) + expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:switch', { profileId: 'target' }) + }) +}) diff --git a/src/preload/renderer/restart/renderer-restart-wiring.test.ts b/src/preload/renderer/restart/renderer-restart-wiring.test.ts new file mode 100644 index 00000000000..dd382790100 --- /dev/null +++ b/src/preload/renderer/restart/renderer-restart-wiring.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it, vi } from 'vitest' + +import { + ORCA_APP_RESTART_ABORTED_EVENT, + ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT +} from '../../../shared/updater-renderer-events' +import { + prepareAndInvokeAppRestart, + prepareAndInvokeUpdaterInstall +} from './renderer-restart-wiring' + +describe('renderer restart wiring', () => { + it('refuses overlapping preparation without abandoning the accepted restart', async () => { + const eventTarget = new EventTarget() + const aborted = vi.fn() + eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) + const checkpoint = Promise.withResolvers() + const invoke = vi.fn(async () => true) + const first = prepareAndInvokeAppRestart(eventTarget, invoke, () => checkpoint.promise) + const refused = vi.fn(async () => false) + await expect( + prepareAndInvokeAppRestart(eventTarget, refused, async () => {}, Boolean) + ).rejects.toThrow('already in progress') + expect(refused).not.toHaveBeenCalled() + expect(aborted).not.toHaveBeenCalled() + checkpoint.resolve() + await expect(first).resolves.toBe(true) + expect(invoke).toHaveBeenCalledOnce() + }) + + it('marks preparation before invoking main and aborts on IPC failure', async () => { + const eventTarget = new EventTarget() + const calls: string[] = [] + eventTarget.addEventListener(ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT, () => { + calls.push('prepared') + }) + const relay = { + markPrepared: () => calls.push('marked'), + abort: () => calls.push('aborted') + } + const invoke = vi.fn(async () => { + calls.push('invoked') + throw new Error('IPC failed') + }) + + await expect( + prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, async () => { + calls.push('checkpoint-flushed') + }) + ).rejects.toThrow('IPC failed') + + expect(calls).toEqual(['prepared', 'checkpoint-flushed', 'marked', 'invoked', 'aborted']) + }) + + it('never installs the update when the shutdown checkpoint fails to persist', async () => { + const eventTarget = new EventTarget() + const invoke = vi.fn(() => Promise.resolve()) + const relay = { markPrepared: vi.fn(), abort: vi.fn() } + + await expect( + prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, () => + Promise.reject(new Error('Failed to persist renderer state before unload.')) + ) + ).rejects.toThrow('Failed to persist renderer state before unload.') + + expect(invoke).not.toHaveBeenCalled() + expect(relay.markPrepared).not.toHaveBeenCalled() + }) +}) diff --git a/src/preload/renderer-restart-wiring.ts b/src/preload/renderer/restart/renderer-restart-wiring.ts similarity index 92% rename from src/preload/renderer-restart-wiring.ts rename to src/preload/renderer/restart/renderer-restart-wiring.ts index 67b14d33c71..eeed8069f01 100644 --- a/src/preload/renderer-restart-wiring.ts +++ b/src/preload/renderer/restart/renderer-restart-wiring.ts @@ -1,16 +1,16 @@ import type { IpcRenderer } from 'electron' -import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../shared/renderer-shutdown-events' +import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../../../shared/renderer-shutdown-events' import { prepareRendererForAppRestart, type UpdaterQuitAbortRelay -} from '../shared/renderer-restart-preparation' -import type { UpdateStatus } from '../shared/update-status-types' +} from '../../../shared/renderer-restart-preparation' +import type { UpdateStatus } from '../../../shared/update-status-types' import { ORCA_APP_RESTART_ABORTED_EVENT, ORCA_APP_RESTART_STARTED_EVENT, ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT, ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT -} from '../shared/updater-renderer-events' +} from '../../../shared/updater-renderer-events' type AppRestartState = { committed: boolean; pending: boolean } const appRestartStates = new WeakMap() diff --git a/src/preload/close-active-tab-payload-admission.test.ts b/src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts similarity index 100% rename from src/preload/close-active-tab-payload-admission.test.ts rename to src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts diff --git a/src/preload/close-active-tab-payload-admission.ts b/src/preload/renderer/window-commands/close-active-tab-payload-admission.ts similarity index 88% rename from src/preload/close-active-tab-payload-admission.ts rename to src/preload/renderer/window-commands/close-active-tab-payload-admission.ts index 17428cb6a7a..cfa12485b72 100644 --- a/src/preload/close-active-tab-payload-admission.ts +++ b/src/preload/renderer/window-commands/close-active-tab-payload-admission.ts @@ -1,4 +1,4 @@ -import type { CloseActiveTabPayload } from './api/ui-command-event-api' +import type { CloseActiveTabPayload } from '../../api/window-ui/ui-command-event-api' export type AdmittedCloseActiveTabPayload = | { kind: 'legacy' } diff --git a/src/preload/runtime-environment-subscriptions.test.ts b/src/preload/runtime-environment-subscriptions.test.ts deleted file mode 100644 index aaeef25d77d..00000000000 --- a/src/preload/runtime-environment-subscriptions.test.ts +++ /dev/null @@ -1,461 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - subscribeRuntimeEnvironmentFromPreload, - subscribeCrewAttemptFromPreload, - cancelRuntimeEnvironmentSubscriptionFromPreload -} from './runtime-environment-subscriptions' - -function deferred(): { - promise: Promise - resolve: (value: T) => void - reject: (error: unknown) => void -} { - let resolve!: (value: T) => void - let reject!: (error: unknown) => void - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve - reject = promiseReject - }) - return { promise, resolve, reject } -} - -type SubscriptionEvent = - | { - subscriptionId: string - type: 'response' - response: { ok: true; id: string; result: unknown; _meta: { runtimeId: string } } - } - | { subscriptionId: string; type: 'binary'; bytes: Uint8Array } - | { subscriptionId: string; type: 'error'; code: string; message: string } - | { subscriptionId: string; type: 'close' } - -type SubscriptionEventListener = (_event: unknown, payload: SubscriptionEvent) => void - -function createIpc() { - const listeners = new Set() - return { - invoke: vi.fn((_channel: string, _args?: unknown) => Promise.resolve({}) as Promise), - send: vi.fn(), - on: vi.fn((_channel: string, listener: SubscriptionEventListener) => { - listeners.add(listener) - }), - removeListener: vi.fn((_channel: string, listener: SubscriptionEventListener) => { - listeners.delete(listener) - }), - emitSubscriptionEvent: (event: SubscriptionEvent): void => { - const currentListeners = Array.from(listeners) - for (const listener of currentListeners) { - listener(null, event) - } - }, - listenerCount: (): number => listeners.size - } -} - -function dispatch(ipc: ReturnType, event: SubscriptionEvent): void { - ipc.emitSubscriptionEvent(event) -} - -describe('subscribeRuntimeEnvironmentFromPreload', () => { - it('registers the subscription event listener before invoking main', async () => { - const subscription = deferred<{ subscriptionId: string; requestId: string }>() - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? (subscription.promise as Promise) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - const onBinary = vi.fn() - - const cleanupPromise = subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse, onBinary }, - () => 'sub-1' - ) - - expect(ipc.on).toHaveBeenCalledWith( - 'runtimeEnvironments:subscriptionEvent', - expect.any(Function) - ) - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:subscribe', { - selector: 'desk', - method: 'terminal.subscribe', - subscriptionId: 'sub-1' - }) - - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'response', - response: { - id: 'rpc-1', - ok: true, - result: { type: 'subscribed' }, - _meta: { runtimeId: 'rt' } - } - }) - expect(onResponse).toHaveBeenCalledWith({ - id: 'rpc-1', - ok: true, - result: { type: 'subscribed' }, - _meta: { runtimeId: 'rt' } - }) - const inboundBytes = new Uint8Array([4, 5, 6]) - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'binary', - bytes: inboundBytes - }) - expect(onBinary).toHaveBeenCalledWith(inboundBytes) - - subscription.resolve({ subscriptionId: 'sub-1', requestId: 'rpc-1' }) - const cleanup = await cleanupPromise - const bytes = new Uint8Array([1, 2, 3]) - cleanup.sendBinary(bytes) - expect(ipc.send).toHaveBeenCalledWith('runtimeEnvironments:subscriptionBinary', { - subscriptionId: 'sub-1', - bytes - }) - cleanup.unsubscribe() - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:unsubscribe', { - subscriptionId: 'sub-1' - }) - expect(ipc.removeListener).toHaveBeenCalledWith( - 'runtimeEnvironments:subscriptionEvent', - ipc.on.mock.calls[0][1] - ) - expect(ipc.listenerCount()).toBe(0) - - onResponse.mockClear() - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'response', - response: { id: 'rpc-2', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponse).not.toHaveBeenCalled() - }) - - it('shares a single channel listener across many subscriptions on one ipc', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string, args: unknown) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ - subscriptionId: (args as { subscriptionId: string }).subscriptionId, - requestId: 'rpc' - }) - : (Promise.resolve({}) as Promise) - ) - - let counter = 0 - const onResponses = Array.from({ length: 25 }, () => vi.fn()) - const handles = await Promise.all( - onResponses.map((onResponse) => - subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'session.tabs.subscribe' }, - { onResponse }, - () => `sub-${counter++}` - ) - ) - ) - - expect(ipc.on).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).not.toHaveBeenCalled() - expect(handles).toHaveLength(25) - - handles[0].unsubscribe() - dispatch(ipc, { - subscriptionId: 'sub-0', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponses[0]).not.toHaveBeenCalled() - expect(onResponses[1]).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).not.toHaveBeenCalled() - expect(ipc.listenerCount()).toBe(1) - - for (const handle of handles.slice(1)) { - handle.unsubscribe() - } - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - }) - - it('keeps the subscription mapped on error frames but releases it on unsubscribe', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-err', requestId: 'rpc-err' }) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - const onError = vi.fn() - - const cleanup = await subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'runtime.clientEvents.subscribe' }, - { onResponse, onError }, - () => 'sub-err' - ) - - for (let i = 0; i < 50; i++) { - dispatch(ipc, { - subscriptionId: 'sub-err', - type: 'error', - code: 'TIMEOUT', - message: 'Timed out waiting for the remote Orca runtime to respond.' - }) - } - expect(onError).toHaveBeenCalledTimes(50) - expect(ipc.removeListener).not.toHaveBeenCalled() - expect(ipc.listenerCount()).toBe(1) - - cleanup.unsubscribe() - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:unsubscribe', { - subscriptionId: 'sub-err' - }) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - onError.mockClear() - dispatch(ipc, { - subscriptionId: 'sub-err', - type: 'error', - code: 'TIMEOUT', - message: 'still erroring' - }) - expect(onError).not.toHaveBeenCalled() - }) - - it('removes the subscription from dispatch when main rejects the subscribe call', async () => { - const subscription = deferred<{ subscriptionId: string; requestId: string }>() - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? (subscription.promise as Promise) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - - const cleanupPromise = subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse }, - () => 'sub-2' - ) - - const error = new Error('subscribe failed') - subscription.reject(error) - await expect(cleanupPromise).rejects.toThrow(error) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - - dispatch(ipc, { - subscriptionId: 'sub-2', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponse).not.toHaveBeenCalled() - }) - - it('releases the subscription from dispatch when main resolves a different id', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-other', requestId: 'rpc' }) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - - await expect( - subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse }, - () => 'sub-expected' - ) - ).rejects.toThrow('Runtime environment subscription id mismatch') - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - - dispatch(ipc, { - subscriptionId: 'sub-expected', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponse).not.toHaveBeenCalled() - }) - - it('releases the subscription when main reports the remote subscription closed', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-closed', requestId: 'rpc-closed' }) - : (Promise.resolve({}) as Promise) - ) - const onClose = vi.fn() - - const cleanup = await subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse: vi.fn(), onClose }, - () => 'sub-closed' - ) - - dispatch(ipc, { subscriptionId: 'other-sub', type: 'close' }) - expect(onClose).not.toHaveBeenCalled() - - dispatch(ipc, { subscriptionId: 'sub-closed', type: 'close' }) - expect(onClose).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - - onClose.mockClear() - cleanup.unsubscribe() - dispatch(ipc, { subscriptionId: 'sub-closed', type: 'close' }) - expect(onClose).not.toHaveBeenCalled() - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:unsubscribe', { - subscriptionId: 'sub-closed' - }) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - }) - - it('releases close frames before calling onClose', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-throw', requestId: 'rpc-throw' }) - : (Promise.resolve({}) as Promise) - ) - const onClose = vi.fn(() => { - throw new Error('close failed') - }) - - await subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse: vi.fn(), onClose }, - () => 'sub-throw' - ) - - expect(() => dispatch(ipc, { subscriptionId: 'sub-throw', type: 'close' })).toThrow( - 'close failed' - ) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - }) -}) - -describe('opt-in crew setup registration', () => { - const args = { - selector: 'desk', - method: 'orchestration.crewSubscribe', - subscriptionId: 'crew', - expectedEnvironmentPairingRevision: 1, - expectedEnvironmentRuntimeId: null - } as const - - it('forwards plain failure after a terminal event and releases the exact registration', async () => { - const ipc = createIpc() - const pending = deferred() - ipc.invoke.mockReturnValue(pending.promise) - const onClose = vi.fn() - const onError = vi.fn() - const first = subscribeCrewAttemptFromPreload(ipc, args, { - onResponse: vi.fn(), - onClose, - onError - }) - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:subscribe', { - ...args, - setupResult: 'crew' - }) - dispatch(ipc, { - subscriptionId: 'crew', - type: 'error', - code: 'remote_runtime_unavailable', - message: 'offline' - }) - dispatch(ipc, { subscriptionId: 'crew', type: 'close' }) - const failure = { - subscriptionId: 'crew', - ok: false, - failure: { message: 'revoked', fact: { kind: 'remote', code: 'unauthorized' } } - } - pending.resolve(failure) - await expect(first).resolves.toBe(failure) - expect(ipc.listenerCount()).toBe(0) - expect(onClose).toHaveBeenCalledTimes(1) - expect(onError).toHaveBeenCalledTimes(1) - }) - - it('releases cancelled registrations while held invoke tails settle in either order', async () => { - const count = 2 - const ipc = createIpc() - const held = Array.from({ length: count }, () => deferred()) - let next = 0 - ipc.invoke.mockImplementation((channel) => - channel === 'runtimeEnvironments:subscribe' ? held[next++].promise : Promise.resolve({}) - ) - const responses = vi.fn() - const attempts = held.map((_, index) => - subscribeCrewAttemptFromPreload( - ipc, - { ...args, subscriptionId: `crew-${index}` }, - { onResponse: responses } - ).catch((error: unknown) => error) - ) - expect(ipc.listenerCount()).toBe(1) - for (let index = 0; index < count; index++) { - await cancelRuntimeEnvironmentSubscriptionFromPreload(ipc, `crew-${index}`) - } - expect(ipc.listenerCount()).toBe(0) - expect(ipc.on).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - for (let index = 0; index < count; index++) { - if (index % 2) { - held[index].reject(new Error('late invoke rejection')) - } else { - held[index].resolve({ subscriptionId: `crew-${index}`, ok: true }) - } - dispatch(ipc, { - subscriptionId: `crew-${index}`, - type: 'response', - response: { id: 'late', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - } - await Promise.all(attempts) - expect(ipc.listenerCount()).toBe(0) - expect(responses).not.toHaveBeenCalled() - expect(ipc.invoke).toHaveBeenCalledTimes(count * 2) - }) - - it('keeps a replacement registration when an old cancelled invoke later rejects', async () => { - const ipc = createIpc() - const old = deferred() - ipc.invoke.mockImplementation((channel) => - channel === 'runtimeEnvironments:subscribe' ? old.promise : Promise.resolve({}) - ) - const first = subscribeCrewAttemptFromPreload(ipc, args, { onResponse: vi.fn() }) - const rejected = expect(first).rejects.toThrow('old invoke') - await cancelRuntimeEnvironmentSubscriptionFromPreload(ipc, 'crew') - ipc.invoke.mockResolvedValue({ subscriptionId: 'crew', ok: true }) - const response = vi.fn() - await subscribeCrewAttemptFromPreload(ipc, args, { onResponse: response }) - old.reject(new Error('old invoke')) - await rejected - dispatch(ipc, { - subscriptionId: 'crew', - type: 'response', - response: { id: 'current', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(response).toHaveBeenCalledOnce() - expect(ipc.listenerCount()).toBe(1) - await cancelRuntimeEnvironmentSubscriptionFromPreload(ipc, 'crew') - }) -}) diff --git a/src/preload/runtime-environment-subscriptions.ts b/src/preload/runtime/runtime-environment-subscriptions.ts similarity index 98% rename from src/preload/runtime-environment-subscriptions.ts rename to src/preload/runtime/runtime-environment-subscriptions.ts index 38baf347fd8..0629a2ca6e5 100644 --- a/src/preload/runtime-environment-subscriptions.ts +++ b/src/preload/runtime/runtime-environment-subscriptions.ts @@ -3,9 +3,9 @@ import { type CrewSubscriptionAttemptArgs, type CrewSubscriptionAttemptCallbacks, type CrewSubscriptionSetupResult -} from '../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +} from '../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' -import type { RuntimeRpcResponse } from '../shared/runtime-rpc-envelope' +import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' type RuntimeEnvironmentSubscribeArgs = { subscriptionId?: string diff --git a/src/preload/ssh-authority-forwarding.test.ts b/src/preload/ssh-authority-forwarding.test.ts deleted file mode 100644 index 70a90a4a4b2..00000000000 --- a/src/preload/ssh-authority-forwarding.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest' -import type { PreloadApi } from './api-types' -import type { SshConnectionState, SshProviderEpoch } from '../shared/ssh-types' -import type { - HostQualifiedDetectedWorktreeResult, - ListDetectedWorktreesArgs -} from '../shared/detected-worktree-provider-contract' -import type { DetectedWorktreeListResult } from '../shared/worktree/types' - -function listDetectedVariableTypeProbe(api: PreloadApi, args: ListDetectedWorktreesArgs) { - return api.worktrees.listDetected(args) -} - -const { exposeInMainWorld, invoke, on, removeListener, send, sendSync } = vi.hoisted(() => ({ - exposeInMainWorld: vi.fn(), - invoke: vi.fn(), - on: vi.fn(), - removeListener: vi.fn(), - send: vi.fn(), - sendSync: vi.fn() -})) - -vi.mock('electron', () => ({ - contextBridge: { exposeInMainWorld }, - ipcRenderer: { invoke, on, removeListener, send, sendSync }, - webFrame: { - getZoomFactor: vi.fn(() => 1), - setZoomFactor: vi.fn(), - setVisualZoomLevelLimits: vi.fn() - }, - webUtils: { getPathForFile: vi.fn(() => '') } -})) - -describe('native preload SSH authority forwarding', () => { - const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') - - beforeEach(() => { - vi.resetModules() - exposeInMainWorld.mockReset() - invoke.mockReset() - on.mockReset() - removeListener.mockReset() - send.mockReset() - sendSync.mockReset() - Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) - vi.stubGlobal('window', { - addEventListener: vi.fn(), - dispatchEvent: vi.fn(), - removeEventListener: vi.fn() - }) - vi.stubGlobal('document', { addEventListener: vi.fn() }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - if (originalContextIsolated) { - Object.defineProperty(process, 'contextIsolated', originalContextIsolated) - } else { - Reflect.deleteProperty(process, 'contextIsolated') - } - }) - - it('retains host-qualified outcomes for variable-form detected-worktree requests', () => { - expectTypeOf(listDetectedVariableTypeProbe).returns.toEqualTypeOf< - Promise - >() - }) - - it('forwards host-qualified metadata-only worktree reads', async () => { - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - const args = { repoId: 'repo-1', executionHostId: 'ssh:ssh-1' as const } - - await api.worktrees.listKnownForExecutionHost?.(args) - - expect(invoke).toHaveBeenCalledWith('worktrees:listKnownForExecutionHost', args) - }) - - it('forwards metadata retirement for authoritatively removed worktrees', async () => { - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - const args = { - repoId: 'repo-1', - executionHostId: 'ssh:ssh-1' as const, - worktreeIds: ['repo-1::/remote/deleted'] - } - - await api.worktrees.forgetRemovedForExecutionHost?.(args) - - expect(invoke).toHaveBeenCalledWith('worktrees:forgetRemovedForExecutionHost', args) - }) - - it('forwards full-pair get and push states without cloning away authority', async () => { - const state: SshConnectionState = { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: 'native-provider-epoch' as SshProviderEpoch, - connectionGeneration: 29 - } - invoke.mockResolvedValueOnce(state) - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - - await expect(api.ssh.getState({ targetId: 'ssh-1' })).resolves.toEqual(state) - expect(invoke).toHaveBeenCalledWith('ssh:getState', { targetId: 'ssh-1' }) - - const onStateChanged = vi.fn() - api.ssh.onStateChanged(onStateChanged) - const listener = on.mock.calls.find(([channel]) => channel === 'ssh:state-changed')?.[1] as ( - event: unknown, - data: { targetId: string; state: SshConnectionState } - ) => void - listener({}, { targetId: 'ssh-1', state }) - - expect(onStateChanged).toHaveBeenCalledWith({ targetId: 'ssh-1', state }) - }) - - it('normalizes partial compatibility authority to unknown for reconciliation', async () => { - const partialState = { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: 'partial-provider-epoch' - } as SshConnectionState - invoke.mockResolvedValueOnce(partialState) - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - - const returned = await api.ssh.getState({ targetId: 'ssh-1' }) - expect(returned).toEqual({ - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: null - }) - - const onStateChanged = vi.fn() - api.ssh.onStateChanged(onStateChanged) - const listener = on.mock.calls.find(([channel]) => channel === 'ssh:state-changed')?.[1] as ( - event: unknown, - data: { targetId: string; state: SshConnectionState } - ) => void - listener({}, { targetId: 'ssh-1', state: partialState }) - - expect(onStateChanged.mock.calls[0]?.[0].state).toEqual({ - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: null - }) - }) - - it('drops malformed full authority before it reaches the renderer', async () => { - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - const onStateChanged = vi.fn() - api.ssh.onStateChanged(onStateChanged) - const listener = on.mock.calls.find(([channel]) => channel === 'ssh:state-changed')?.[1] as ( - event: unknown, - data: { targetId: string; state: SshConnectionState } - ) => void - - listener( - {}, - { - targetId: 'ssh-1', - state: { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: '' as SshProviderEpoch, - connectionGeneration: 29 - } - } - ) - - expect(onStateChanged).not.toHaveBeenCalled() - }) -}) diff --git a/src/preload/updater-package-recovery.test.ts b/src/preload/updater-package-recovery.test.ts deleted file mode 100644 index fb58791e9cc..00000000000 --- a/src/preload/updater-package-recovery.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreloadApi } from './api-types' - -const { exposeInMainWorld, invoke, on, removeListener, send, sendSync } = vi.hoisted(() => ({ - exposeInMainWorld: vi.fn(), - invoke: vi.fn(), - on: vi.fn(), - removeListener: vi.fn(), - send: vi.fn(), - sendSync: vi.fn() -})) - -vi.mock('electron', () => ({ - contextBridge: { exposeInMainWorld }, - ipcRenderer: { invoke, on, removeListener, send, sendSync }, - webFrame: { - getZoomFactor: vi.fn(() => 1), - setZoomFactor: vi.fn(), - setVisualZoomLevelLimits: vi.fn() - }, - webUtils: { getPathForFile: vi.fn(() => '') } -})) - -describe('native preload linux package recovery methods', () => { - const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') - - beforeEach(() => { - vi.resetModules() - exposeInMainWorld.mockReset() - invoke.mockReset() - on.mockReset() - removeListener.mockReset() - send.mockReset() - sendSync.mockReset() - Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) - vi.stubGlobal('window', { - addEventListener: vi.fn(), - dispatchEvent: vi.fn(), - removeEventListener: vi.fn() - }) - vi.stubGlobal('document', { addEventListener: vi.fn() }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - if (originalContextIsolated) { - Object.defineProperty(process, 'contextIsolated', originalContextIsolated) - } else { - Reflect.deleteProperty(process, 'contextIsolated') - } - }) - - const loadApi = async (): Promise => { - await import('./index') - return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - } - - it('invokes only the instructions channel and returns the main-built command', async () => { - const api = await loadApi() - invoke.mockResolvedValueOnce({ - command: "sudo apt install -- '/cache/orca.deb'", - packageFileName: 'orca.deb' - }) - invoke.mockClear() - - await expect(api.updater.getLinuxPackageInstallInstructions()).resolves.toEqual({ - command: "sudo apt install -- '/cache/orca.deb'", - packageFileName: 'orca.deb' - }) - - expect(invoke.mock.calls).toEqual([['updater:getLinuxPackageInstallInstructions']]) - }) - - it('invokes only the show-package channel', async () => { - const api = await loadApi() - invoke.mockResolvedValueOnce(undefined) - invoke.mockClear() - - await expect(api.updater.showLinuxPackage()).resolves.toBeUndefined() - - expect(invoke.mock.calls).toEqual([['updater:showLinuxPackage']]) - }) -}) diff --git a/src/preload/usage-provider-api.test.ts b/src/preload/usage-provider-api.test.ts deleted file mode 100644 index 2faae9158e1..00000000000 --- a/src/preload/usage-provider-api.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createUsageProviderApi } from './usage-provider-api' - -describe('usage provider preload API', () => { - it('keeps every provider on its existing IPC channels', async () => { - const invoke = vi.fn().mockResolvedValue(undefined) - const query = { scope: 'orca' as const, range: '30d' as const } - - for (const prefix of ['claudeUsage', 'codexUsage', 'openCodeUsage', 'museUsage'] as const) { - const api = createUsageProviderApi({ invoke } as never, prefix) - await api.getScanState() - await api.setEnabled({ enabled: true }) - await api.refresh() - await api.getSnapshot({ ...query, limit: 7 }) - await api.getSummary(query) - await api.getDaily(query) - await api.getBreakdown({ ...query, kind: 'project' }) - await api.getRecentSessions({ ...query, limit: 4 }) - - expect(invoke.mock.calls).toEqual([ - [`${prefix}:getScanState`], - [`${prefix}:setEnabled`, { enabled: true }], - [`${prefix}:refresh`, undefined], - [`${prefix}:getSnapshot`, { ...query, limit: 7 }], - [`${prefix}:getSummary`, query], - [`${prefix}:getDaily`, query], - [`${prefix}:getBreakdown`, { ...query, kind: 'project' }], - [`${prefix}:getRecentSessions`, { ...query, limit: 4 }] - ]) - invoke.mockClear() - } - }) -}) diff --git a/src/preload/backend-port-client.ts b/src/preload/usage/backend-port-client.ts similarity index 97% rename from src/preload/backend-port-client.ts rename to src/preload/usage/backend-port-client.ts index dae6df4e82b..13c3bec8d70 100644 --- a/src/preload/backend-port-client.ts +++ b/src/preload/usage/backend-port-client.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import { BackendPortRpc, type BackendPort } from '../shared/backend-port-rpc' +import { BackendPortRpc, type BackendPort } from '../../shared/backend-port-rpc' import { BACKEND_CONNECTION_CHANGED, BACKEND_PORT_DELIVERY, @@ -7,7 +7,7 @@ import { type BackendConnectionPurpose, type BackendConnectionStatus, type BackendConnectionListener -} from '../shared/backend-service-contract' +} from '../../shared/backend-service-contract' let connection: BackendPortRpc | undefined let connecting: Promise | undefined diff --git a/src/preload/usage-provider-api.ts b/src/preload/usage/usage-provider-api.ts similarity index 95% rename from src/preload/usage-provider-api.ts rename to src/preload/usage/usage-provider-api.ts index 3b9723a6aa0..ba73e86e1f9 100644 --- a/src/preload/usage-provider-api.ts +++ b/src/preload/usage/usage-provider-api.ts @@ -1,8 +1,8 @@ import type { BackendConnectionListener, BackendConnectionPurpose -} from '../shared/backend-service-contract' -import type { PreloadApi } from './api-types' +} from '../../shared/backend-service-contract' +import type { PreloadApi } from '../api-types' type UsageProviderApiKey = 'claudeUsage' | 'codexUsage' | 'openCodeUsage' | 'museUsage' type UsageProviderApi = PreloadApi[UsageProviderApiKey] diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index 448d742fa04..0a462615453 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -12,10 +12,6 @@ import { resolveChildWorkspacesToggleGroupKey } from '../components/sidebar/workspace-card/identity/child-workspaces-toggle-target' import { requestTerminalTabRename } from '../components/tab-bar/terminal-tab-rename-request' -import { - deleteActiveWorkspaceFromShortcut, - resolveActiveWorkspaceDeleteTarget -} from '../components/sidebar/workspace-actions/deletion/active-workspace-delete' import { useAppStore } from '../store/index' import type { usePluginCommands } from '@/store/plugins/catalog/plugin-contribution-catalog' import { isGitRepoKind } from '../../../shared/repo-kind' @@ -223,22 +219,6 @@ export function createAppCommandHandlers( }) } ], - [ - 'workspace.delete', - () => { - if (floatingWorkspaceFocused) { - return false - } - const store = useAppStore.getState() - const target = resolveActiveWorkspaceDeleteTarget(store) - if (!target) { - return false - } - return claim('workspace.delete', () => { - deleteActiveWorkspaceFromShortcut(store, target) - }) - } - ], [ 'workspace.openBoard', () => { diff --git a/src/renderer/src/app-shell/appearance/document-theme.ts b/src/renderer/src/app-shell/appearance/document-theme.ts index f5d0fe509d6..4e529761e37 100644 --- a/src/renderer/src/app-shell/appearance/document-theme.ts +++ b/src/renderer/src/app-shell/appearance/document-theme.ts @@ -11,6 +11,7 @@ import { type ColorProbe } from './plugin-theme-tokens' import { CHAT_SELECTION_MIX_TOKEN, chatSelectionMix } from './chat-selection-mix' +import { noticeSurfaceTokens } from './notice-surface-tokens' export type DocumentThemePreference = GlobalSettings['theme'] @@ -185,7 +186,8 @@ function paintPluginTokens( setPluginTokens(root, { ...withFloatingSurfaces(safe), [HOST_PILL_OUTLINE_MIX_TOKEN]: `${hostPillOutlineMix(safe, base, builtIns, probe)}%`, - [CHAT_SELECTION_MIX_TOKEN]: `${chatSelectionMix(safe, base, builtIns, probe)}%` + [CHAT_SELECTION_MIX_TOKEN]: `${chatSelectionMix(safe, base, builtIns, probe)}%`, + ...noticeSurfaceTokens(safe, base, builtIns, probe) }) return safe } diff --git a/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts b/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts new file mode 100644 index 00000000000..e9c4e7936e4 --- /dev/null +++ b/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest' +import { hexToRgb, type Rgba } from '../../../../shared/color/rgba-contrast' +import { noticeSurfaceTokens } from './notice-surface-tokens' + +const DARK_BUILT_INS = { + '--foreground': '#f0f0f0', + '--popover': '#171717', + '--popover-foreground': '#f0f0f0', + '--muted': '#262626', + '--muted-foreground': '#acacac' +} +const probe = (value: string): Rgba | null => (value.startsWith('#') ? hexToRgb(value) : null) + +/** WCAG 2 contrast written out here, so the check shares no math with the code under test. */ +function wcagContrast(firstHex: string, secondHex: string): number { + const luminance = (hex: string): number => { + const [r, g, b] = [1, 3, 5].map((start) => { + const c = Number.parseInt(hex.slice(start, start + 2), 16) / 255 + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4 + }) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + } + const [high, low] = [luminance(firstHex), luminance(secondHex)].sort((a, b) => b - a) + return (high + 0.05) / (low + 0.05) +} + +/** `over` with `top` painted at `alpha`, as the browser blends a bg-muted/N panel. */ +function composite(topHex: string, overHex: string, alpha: number): string { + return `#${[1, 3, 5] + .map((start) => { + const top = Number.parseInt(topHex.slice(start, start + 2), 16) + const under = Number.parseInt(overHex.slice(start, start + 2), 16) + return Math.round(top * alpha + under * (1 - alpha)) + .toString(16) + .padStart(2, '0') + }) + .join('')}` +} + +/** The emitted tokens are the painted colors, so their contrast is what the user sees. */ +function expectReadable(themeTokens: Record): void { + const palette: Record = { ...DARK_BUILT_INS, ...themeTokens } + const text = palette['--popover-foreground'] + const notice: Record = noticeSurfaceTokens( + themeTokens, + 'dark', + DARK_BUILT_INS, + probe + ) + const surface = notice['--notice-surface'] + const muted = notice['--notice-muted-foreground'] + expect(wcagContrast(surface, text)).toBeGreaterThanOrEqual(4.5) + // Toast descriptions paint popover text at 80%. Lifting must not push them under 4.5:1, nor + // below the unlifted popover's own contrast when the theme already sat under it. + const description = (under: string): number => wcagContrast(composite(text, under, 0.8), under) + expect(description(surface)).toBeGreaterThanOrEqual( + Math.min(4.5, description(palette['--popover'])) + ) + expect(wcagContrast(notice['--notice-secondary'], text)).toBeGreaterThanOrEqual(4.5) + expect(wcagContrast(surface, muted)).toBeGreaterThanOrEqual(4.5) + // UpdateErrorCardContent's bg-muted/30, /40 and /50 panels hold muted and body text. Without a + // --notice-muted token, main.css paints them from the palette's --muted. + const mutedPanel = notice['--notice-muted'] ?? palette['--muted'] + for (const alpha of [0.3, 0.4, 0.5]) { + const panel = composite(mutedPanel, surface, alpha) + expect(wcagContrast(panel, muted)).toBeGreaterThanOrEqual(4.5) + expect(wcagContrast(panel, text)).toBeGreaterThanOrEqual(4.5) + } +} + +describe('noticeSurfaceTokens', () => { + // Popovers the theme validator accepts that once painted notice text under 4.5:1: #5a5a5a + // through Chromium's color-mix rounding and an over-lifted 80% description, #383838 through hex + // rounding, white-on-dark-base through dark muted panels, the rest unlifted. + it.each>([ + { '--popover': '#5a5a5a' }, + { '--popover': '#383838' }, + { '--popover': '#444444' }, + { '--popover': '#303030', '--popover-foreground': '#a0a0a0' }, + { '--popover': '#ffffff', '--popover-foreground': '#111111' } + ])('keeps notice text 4.5:1 for an accepted %o', (themeTokens) => { + expectReadable(themeTokens) + }) + + it('outlines secondary buttons only when their fill is gone', () => { + const tokensFor = (popoverForeground: string): Record => + noticeSurfaceTokens( + { '--popover': '#303030', '--popover-foreground': popoverForeground }, + 'dark', + DARK_BUILT_INS, + probe + ) + const unfilled = tokensFor('#989898') + expect(unfilled['--notice-secondary']).toBe(unfilled['--notice-surface']) + expect(unfilled['--notice-secondary-edge']).toBe('var(--notice-border)') + const filled = tokensFor('#a0a0a0') + expect(filled['--notice-secondary']).not.toBe(filled['--notice-surface']) + expect(filled['--notice-secondary-edge']).toBe('transparent') + }) +}) diff --git a/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts b/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts new file mode 100644 index 00000000000..7afca6bb419 --- /dev/null +++ b/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts @@ -0,0 +1,124 @@ +import { MIN_TEXT_CONTRAST } from './plugin-theme-contrast-rules' +import { paintedThemeColors, type ColorProbe } from './plugin-theme-tokens' +import { + contrastRatio, + hexToRgb, + mix, + rgbaToHex, + type Rgba +} from '../../../../shared/color/rgba-contrast' + +export const NOTICE_SURFACE_TOKEN = '--notice-surface' +export const NOTICE_SECONDARY_TOKEN = '--notice-secondary' +export const NOTICE_MUTED_FOREGROUND_TOKEN = '--notice-muted-foreground' +export const NOTICE_SECONDARY_EDGE_TOKEN = '--notice-secondary-edge' +export const NOTICE_MUTED_TOKEN = '--notice-muted' +// Keep in sync with the built-in notice mixes in main.css. +const NOTICE_LIFT = { light: 0, dark: 7 } as const +const NOTICE_SECONDARY_MIX = { light: 6, dark: 10 } as const +// Keep in sync with the [data-description] color-mix in main.css. +const NOTICE_DESCRIPTION_OPACITY = 80 + +const BLACK: Rgba = [0, 0, 0, 1] +const painted = (color: Rgba): Rgba => hexToRgb(rgbaToHex(color)) +const step = (color: Rgba, by: number): Rgba => [ + Math.min(255, Math.max(0, color[0] + by)), + Math.min(255, Math.max(0, color[1] + by)), + Math.min(255, Math.max(0, color[2] + by)), + 1 +] + +/** 4.5:1 even with each color one 8-bit step toward the other, so a theme color that paints a + * channel off (fractional CSS colors round their own way) can't sink below the floor. */ +function readable(a: Rgba, b: Rgba): boolean { + const [lighter, darker] = contrastRatio(a, BLACK) >= contrastRatio(b, BLACK) ? [a, b] : [b, a] + return contrastRatio(step(lighter, -1), step(darker, 1)) >= MIN_TEXT_CONTRAST +} + +/** `tint` mixed into `base` at the deepest percent, from `deepest` down, where `reads` holds. */ +function deepestReadableMix( + tint: Rgba, + base: Rgba, + deepest: number, + reads: (candidate: Rgba) => boolean +): Rgba { + for (let percent = deepest; percent > 0; percent--) { + const candidate = painted(mix(tint, base, percent)) + if (reads(candidate)) { + return candidate + } + } + return painted(base) +} + +/** + * Toasts and corner cards lift the popover toward the foreground and paint popover and muted + * text on it, but a theme's popover pair is only checked unlifted. So the lift and secondary + * fill shrink until popover text stays readable (on the surface, its 80% description blend + * too), and muted text moves toward popover text until it does too, on the surface and on muted + * panels. Emitted as final hex colors: CSS paints exactly the colors measured here. + */ +export function noticeSurfaceTokensFor( + colors: { foreground: Rgba; popover: Rgba; popoverForeground: Rgba; mutedForeground: Rgba }, + base: 'light' | 'dark' +): Record { + const { foreground, popover, popoverForeground, mutedForeground } = colors + if ([foreground, popover, popoverForeground, mutedForeground].some((color) => color[3] < 1)) { + return {} + } + const text = painted(popoverForeground) + // Why: toast descriptions paint popover text at 80% (main.css [data-description]), so the lift + // must keep that blend readable too, not just the opaque text. + const surface = deepestReadableMix( + foreground, + popover, + NOTICE_LIFT[base], + (candidate) => + readable(candidate, text) && + readable(candidate, painted(mix(text, candidate, NOTICE_DESCRIPTION_OPACITY))) + ) + const secondary = deepestReadableMix( + foreground, + surface, + NOTICE_SECONDARY_MIX[base], + (candidate) => readable(candidate, text) + ) + // Muted panels (bg-muted/N) paint between the surface and the secondary fill, so muted text + // must read on both ends. + const mutedReads = (color: Rgba): boolean => + readable(surface, color) && readable(secondary, color) + let muted = painted(mutedForeground) + for (let towardText = 1; towardText <= 100 && !mutedReads(muted); towardText++) { + muted = painted(mix(popoverForeground, mutedForeground, towardText)) + } + const surfaceHex = rgbaToHex(surface) + const secondaryHex = rgbaToHex(secondary) + return { + [NOTICE_SURFACE_TOKEN]: surfaceHex, + [NOTICE_SECONDARY_TOKEN]: secondaryHex, + // Why: with no fill left, secondary buttons need an edge to still read as buttons. + [NOTICE_SECONDARY_EDGE_TOKEN]: + secondaryHex === surfaceHex ? 'var(--notice-border)' : 'transparent', + // Why: built-in palettes set --muted equal to --secondary; keeping that here keeps muted panels + // on the notice surface's polarity when a theme's popover and app polarity differ. + [NOTICE_MUTED_TOKEN]: secondaryHex, + [NOTICE_MUTED_FOREGROUND_TOKEN]: rgbaToHex(muted) + } +} + +/** noticeSurfaceTokensFor a theme's tokens, which already passed safePluginThemeTokens. */ +export function noticeSurfaceTokens( + tokens: Readonly>, + base: 'light' | 'dark', + builtIns: Readonly>, + probe: ColorProbe +): Record { + const effective = paintedThemeColors(tokens, base, builtIns, probe) + const foreground = effective('--foreground') + const popover = effective('--popover') + const popoverForeground = effective('--popover-foreground') + const mutedForeground = effective('--muted-foreground') + return foreground && popover && popoverForeground && mutedForeground + ? noticeSurfaceTokensFor({ foreground, popover, popoverForeground, mutedForeground }, base) + : {} +} diff --git a/src/renderer/src/app-shell/startup-window-parity-differences.test-fixture.ts b/src/renderer/src/app-shell/startup-window-parity-differences.test-fixture.ts deleted file mode 100644 index 63d431f1588..00000000000 --- a/src/renderer/src/app-shell/startup-window-parity-differences.test-fixture.ts +++ /dev/null @@ -1,74 +0,0 @@ -// Shared expected differences between disk restore and Loader-rewritten startup views, each attributed to its Loader rule. - -import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { sweepUnattachedTerminalRows } from '../../../shared/workspace-layout/unattached-terminal-row-sweep' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' - -export const GIT = 'repo-1::/Users/dev/orca' - -/** Main's startup sweep in a layout-owner build; a paired server's partition passes through. */ -export function sweptAtStartup( - hostId: ExecutionHostId, - session: WorkspaceSessionState -): WorkspaceSessionState { - return parseExecutionHostId(hostId)?.kind === 'runtime' - ? session - : sweepUnattachedTerminalRows(session) -} - -export type KnownDifference = { - fixture: string - /** The Loader rule that makes the window show something else. */ - rule: string - /** View paths that differ; see `projectStartupWindowView`. */ - paths: string[] -} - -/** Differences to fix. Entries may only be removed: fix the rule, then delete its entry. */ -export const KNOWN_DIFFERENCES: readonly KnownDifference[] = [] - -export type AcceptedDifference = Omit & { - reason: string - /** Each differing view path with its stored and normalized values; absent means not shown. */ - values: Record -} - -/** Differences that are not bugs: the user sees the same thing, or the window is the outlier. */ -export const ACCEPTED_DIFFERENCES: readonly AcceptedDifference[] = [ - { - fixture: 'row terminal differs from its focused pane’s', - rule: 'row.ptyId rewrite: the Loader sets the row terminal to its focused pane’s, which changes what the tab reattaches', - reason: 'the pane’s own terminal binding wins on mount, so the user sees the same terminal', - values: { [`${GIT} terminal tab-a reattaches`]: { stored: 'pty-stale', normalized: 'pty-a' } } - }, - { - fixture: 'row with no terminal while its pane has one', - rule: 'row.ptyId rewrite: the Loader sets the row terminal to its focused pane’s, which changes what the tab reattaches', - reason: 'the pane’s own terminal binding wins on mount, so the user sees the same terminal', - values: { [`${GIT} terminal tab-a reattaches`]: { stored: null, normalized: 'pty-a' } } - }, - { - fixture: 'legacy surface tombstone on a pane still showing its terminal', - rule: 'tombstones: the Loader closes a pane a legacy surface tombstone names; the window ignores the tombstone and shows the pane', - reason: 'the window is the outlier: main already retires panes these tombstones name', - values: { - [`${GIT} group 0 tabs`]: { stored: ['tab-a', 'tab-b'], normalized: ['tab-a'] }, - [`${GIT} tab tab-b`]: { - stored: { kind: 'terminal', shows: 'tab-b', group: 0, label: 'Terminal 2' } - }, - [`${GIT} terminal tab-b phone and CLI title`]: { stored: 'Terminal 2' }, - [`${GIT} terminal tab-b panes`]: { stored: { pane: 'pty-b' } }, - [`${GIT} terminal tab-b focused pane`]: { stored: 'root' }, - [`${GIT} terminal tab-b reattaches`]: { stored: 'pty-b' } - } - }, - { - fixture: 'tab-bar label differing from the row title', - rule: 'label over title: the Loader writes the tab-bar label into the row title', - reason: - 'the desktop tab shows the label, which is unchanged; only phones and the CLI show the row title', - values: { - [`${GIT} terminal tab-a phone and CLI title`]: { stored: 'Terminal 1', normalized: 'vim' } - } - } -] diff --git a/src/renderer/src/app-shell/startup-window-parity.test.ts b/src/renderer/src/app-shell/startup-window-parity.test.ts deleted file mode 100644 index ad55364b52d..00000000000 --- a/src/renderer/src/app-shell/startup-window-parity.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Compare window startup from disk with the Loader round trip. Enumerate each divergence as a known defect or accepted difference with its reason. - -import { describe, expect, it, vi } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { LEGACY_WORKSPACE_LAYOUT_PROFILES } from '../../../shared/workspace-layout/workspace-layout-legacy-profile.test-fixture' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load' -import { WORKSPACE_LAYOUT_PROFILES } from '../../../shared/workspace-layout/workspace-layout-profile.test-fixture' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save' -import { createStoreSessionMockApi } from '../store/testing/app-store-session-api.test-fixture' -import { createTestStore } from '../store/testing/app-store-test-fixture' -import { GIT, sweptAtStartup } from './startup-window-parity-differences.test-fixture' -import { - bootWindowFromPartitions, - projectStartupWindowView -} from './startup-window-view.test-fixture' - -// Use legacy window boot as the oracle for main-owned layout loading. -const layoutOwner = vi.hoisted(() => ({ isMain: false })) -vi.mock('../../../shared/layout-owner-switch', () => ({ - get ORCA_LAYOUT_OWNER_IS_MAIN() { - return layoutOwner.isMain - } -})) -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } -}) - -createStoreSessionMockApi() - -/** Main's startup sweep, then the shared Loader's round trip, as main would persist it. */ -function normalize(hostId: ExecutionHostId, session: WorkspaceSessionState): WorkspaceSessionState { - let next = 0 - layoutOwner.isMain = true - try { - const loaded = loadWorkspaceLayout(hostId, sweptAtStartup(hostId, structuredClone(session)), { - mintId: () => `minted-${++next}`, - mintLeafId: () => `00000000-0000-4000-9000-${String(++next).padStart(12, '0')}` - }) - return saveWorkspaceLayout(loaded) - } finally { - layoutOwner.isMain = false - } -} - -const PROFILES = [...WORKSPACE_LAYOUT_PROFILES, ...LEGACY_WORKSPACE_LAYOUT_PROFILES] - -describe('the window shows the same session before and after the shared Loader rewrites it', () => { - it('keeps the tab-bar twin selected when a selected legacy copy is dropped', async () => { - const profile = PROFILES.find( - (entry) => entry.name === 'legacy row repeating a tab-bar tab’s terminal, selected' - )! - const view = projectStartupWindowView( - await bootWindowFromPartitions(createTestStore(), [ - { hostId: profile.hostId, session: normalize(profile.hostId, profile.build()) } - ]) - ) - expect(view['active.terminal']).toBe('tab-a') - expect(view[`${GIT} active terminal`]).toBe('tab-a') - }) - - it('restores terminals and saved edit tabs from a session before the tab bar', async () => { - const profile = PROFILES.find( - (entry) => entry.name === 'session from before the tab bar, with an open file' - )! - const view = projectStartupWindowView( - await bootWindowFromPartitions(createTestStore(), [ - { hostId: profile.hostId, session: profile.build() } - ]) - ) - expect(view[`${GIT} group 0 tabs`]).toEqual(['/Users/dev/orca/src/app.ts', 'tab-a', 'tab-b']) - expect(view).toHaveProperty([`${GIT} tab /Users/dev/orca/src/app.ts`]) - }) -}) diff --git a/src/renderer/src/app-shell/startup-window-view.test-fixture.ts b/src/renderer/src/app-shell/startup-window-view.test-fixture.ts deleted file mode 100644 index bfdef958c4c..00000000000 --- a/src/renderer/src/app-shell/startup-window-view.test-fixture.ts +++ /dev/null @@ -1,204 +0,0 @@ -// Boot stored partitions through real startup hydration, then compare user-visible state. - -import { vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { - LOCAL_EXECUTION_HOST_ID, - parseExecutionHostId, - type ExecutionHostId -} from '../../../shared/execution-host' -import type { TabGroupLayoutNode } from '../../../shared/tab-types' -import type { - TerminalLayoutSnapshot, - TerminalPaneLayoutNode -} from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { fetchWorkspaceSessionWithRuntimeHostOwners } from '@/lib/workspace/persistence/workspace-session-host-hydration' -import { collectFolderWorkspaceKeysFromSession } from '@/lib/workspace/persistence/workspace-session-hydration-keys' -import type { AppState } from '../store/types' -import type { createTestStore } from '../store/testing/app-store-test-fixture' -import { reconcileHydratedWorkspaceTabModels } from './reconcile-hydrated-workspace-tab-models' - -/** One stored session partition and the host it is stored under. */ -export type StoredPartition = { hostId: ExecutionHostId; session: WorkspaceSessionState } - -/** First-paint local repos for referenced Git workspaces, without listings. Remote-server catalogs are skipped at startup. */ -function firstPaintRepos(partitions: readonly StoredPartition[]): AppState['repos'] { - const repos = new Map() - for (const { hostId, session } of partitions) { - const host = parseExecutionHostId(hostId) - if (host?.kind === 'runtime') { - continue - } - for (const key of Object.keys(session.tabsByWorktree)) { - const id = getRepoIdFromWorktreeId(key) - if (!key.startsWith(`${id}::`) || repos.has(id)) { - continue - } - repos.set(id, { - id, - path: key.slice(id.length + 2), - displayName: id, - badgeColor: '#000', - addedAt: 0, - connectionId: host?.kind === 'ssh' ? host.targetId : null, - executionHostId: hostId - }) - } - } - return [...repos.values()] -} - -/** Match use-app-startup-hydration’s call order on a fresh test store. */ -export async function bootWindowFromPartitions( - store: ReturnType, - partitions: readonly StoredPartition[] -): Promise { - let minted = 0 - // Group and tab ids the window mints must match across the two boots being compared. - const randomUUID = vi - .spyOn(globalThis.crypto, 'randomUUID') - .mockImplementation(() => `00000000-0000-4000-8000-${String(++minted).padStart(12, '0')}`) - try { - store.setState({ repos: firstPaintRepos(partitions) }) - const read = async (hostId: ExecutionHostId = LOCAL_EXECUTION_HOST_ID) => - structuredClone( - partitions.find((partition) => partition.hostId === hostId)?.session ?? - getDefaultWorkspaceSession() - ) - const hostIdsOfKind = (kind: 'ssh' | 'runtime') => - partitions - .map((partition) => partition.hostId) - .filter((hostId) => parseExecutionHostId(hostId)?.kind === kind) - const sessionRead = await fetchWorkspaceSessionWithRuntimeHostOwners( - { get: read, listHostIds: async () => hostIdsOfKind('ssh') }, - store.getState().repos, - hostIdsOfKind('runtime') - ) - const actions = store.getState() - const options = { - additionalValidWorkspaceKeys: collectFolderWorkspaceKeysFromSession(sessionRead.session) - } - actions.hydrateWorkspaceSession(sessionRead.session, { - ...options, - runtimeHostIdByWorkspaceSessionKey: sessionRead.runtimeHostIdByWorkspaceSessionKey, - contestedHostWorkspaceSessions: sessionRead.contestedHostWorkspaceSessions, - contestedPrimaryHostBySessionKey: sessionRead.contestedPrimaryHostBySessionKey, - hydratedRuntimeSessionHostIds: sessionRead.hydratedRuntimeSessionHostIds - }) - actions.hydrateTabsSession(sessionRead.session, options) - actions.hydrateEditorSession(sessionRead.session, options) - actions.hydrateBrowserSession(sessionRead.session, options) - reconcileHydratedWorkspaceTabModels( - sessionRead.session, - store.getState().reconcileWorktreeTabModels - ) - return store.getState() - } finally { - randomUUID.mockRestore() - } -} - -type PaneView = { pane: string | null } | { split: string; first: PaneView; second: PaneView } - -/** Panes by position, each naming the terminal it binds; leaf ids are not shown. */ -function paneView(node: TerminalPaneLayoutNode, layout: TerminalLayoutSnapshot): PaneView { - if (node.type === 'leaf') { - return { pane: layout.ptyIdsByLeafId?.[node.leafId] ?? null } - } - return { - split: node.direction, - first: paneView(node.first, layout), - second: paneView(node.second, layout) - } -} - -function leafPosition( - node: TerminalPaneLayoutNode, - leafId: string | null, - path = '' -): string | null { - if (node.type === 'leaf') { - return node.leafId === leafId ? path || 'root' : null - } - return ( - leafPosition(node.first, leafId, `${path}1`) ?? leafPosition(node.second, leafId, `${path}2`) - ) -} - -type GroupLayoutView = number | { split: string; first: GroupLayoutView; second: GroupLayoutView } - -function groupLayoutView(node: TabGroupLayoutNode, groupIds: string[]): GroupLayoutView { - if (node.type === 'leaf') { - return groupIds.indexOf(node.groupId) - } - return { - split: node.direction, - first: groupLayoutView(node.first, groupIds), - second: groupLayoutView(node.second, groupIds) - } -} - -/** Project visible path/value pairs. Name groups by position (IDs are invisible); retain tab IDs because they must survive restarts. */ -export function projectStartupWindowView(state: AppState): Record { - const view: Record = { - 'active.workspace': state.activeWorktreeId, - 'active.terminal': state.activeTabId - } - const workspaceKeys = new Set([ - ...Object.keys(state.tabsByWorktree), - ...Object.keys(state.unifiedTabsByWorktree), - ...state.openFiles.map((file) => file.worktreeId), - ...Object.keys(state.browserTabsByWorktree) - ]) - for (const key of [...workspaceKeys].sort()) { - const groups = state.groupsByWorktree[key] ?? [] - const groupIds = groups.map((group) => group.id) - const layout = state.layoutByWorktree[key] - view[`${key} groups`] = layout ? groupLayoutView(layout, groupIds) : groupIds.length - groups.forEach((group, index) => { - view[`${key} group ${index} tabs`] = group.tabOrder - view[`${key} group ${index} active tab`] = group.activeTabId - }) - view[`${key} active group`] = groupIds.indexOf(state.activeGroupIdByWorktree[key] ?? '') - view[`${key} active terminal`] = state.activeTabIdByWorktree[key] ?? null - view[`${key} active file`] = state.activeFileIdByWorktree[key] ?? null - view[`${key} active kind`] = state.activeTabTypeByWorktree[key] ?? null - for (const tab of state.unifiedTabsByWorktree[key] ?? []) { - view[`${key} tab ${tab.id}`] = { - kind: tab.contentType, - shows: tab.entityId, - group: groupIds.indexOf(tab.groupId), - label: tab.customLabel ?? tab.label - } - } - for (const row of state.tabsByWorktree[key] ?? []) { - const panes = state.terminalLayoutsByTabId[row.id] - const terminal = `${key} terminal ${row.id}` - // Phones and the CLI show the row title; the desktop tab shows its tab-bar label. - view[`${terminal} phone and CLI title`] = row.customTitle ?? row.title - view[`${terminal} panes`] = panes?.root ? paneView(panes.root, panes) : null - view[`${terminal} focused pane`] = panes?.root - ? leafPosition(panes.root, panes.activeLeafId) - : null - view[`${terminal} reattaches`] = state.pendingReconnectPtyIdByTabId[row.id] ?? null - } - view[`${key} open files`] = state.openFiles - .filter((file) => file.worktreeId === key) - .map((file) => file.filePath) - view[`${key} browser tabs`] = (state.browserTabsByWorktree[key] ?? []).map((tab) => tab.url) - } - return view -} - -/** Each path whose value differs between two views, with both values. */ -export function diffStartupWindowViews( - stored: Record, - normalized: Record -): { path: string; stored: unknown; normalized: unknown }[] { - const paths = [...new Set([...Object.keys(stored), ...Object.keys(normalized)])].sort() - return paths - .filter((path) => JSON.stringify(stored[path]) !== JSON.stringify(normalized[path])) - .map((path) => ({ path, stored: stored[path], normalized: normalized[path] })) -} diff --git a/src/renderer/src/app-shell/startup/startup-ui-hydration.ts b/src/renderer/src/app-shell/startup/startup-ui-hydration.ts index fcf00d29c53..d3f1b4dedf2 100644 --- a/src/renderer/src/app-shell/startup/startup-ui-hydration.ts +++ b/src/renderer/src/app-shell/startup/startup-ui-hydration.ts @@ -3,9 +3,9 @@ import { replayPendingRuntimeRepoRemovalsForReadyServers } from '@/store/repos/p import { DEFAULT_HIDE_SLEEPING_WORKSPACES, DEFAULT_SHOW_SLEEPING_WORKSPACES, - DEFAULT_STATUS_BAR_ITEMS, - DEFAULT_WORKTREE_CARD_PROPERTIES + DEFAULT_STATUS_BAR_ITEMS } from '../../../../shared/constants' +import { DEFAULT_WORKTREE_CARD_PROPERTIES } from '../../../../shared/worktree/row-display/card-properties' import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' export function hydratePersistedUIAfterStartupRead({ diff --git a/src/renderer/src/app-shell/use-app-shell-services.ts b/src/renderer/src/app-shell/use-app-shell-services.ts index 93465e308d8..c7b9a381e18 100644 --- a/src/renderer/src/app-shell/use-app-shell-services.ts +++ b/src/renderer/src/app-shell/use-app-shell-services.ts @@ -24,6 +24,7 @@ import { useCodexTerminalServerIsolationNotice } from '../components/terminal-pa import { useClaudeThemeSyncOffer } from '../components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer' import { useVisibleHostedReviewRefresh } from './use-visible-hosted-review-refresh' import { useProfileStateSaveDelayNotice } from './use-profile-state-save-delay-notice' +import { useRemoteUnsavedEditorReport } from '../runtime/workspace-cleanup/remote-unsaved-editor-report' /** Keep subscriptions above surfaces that unmount or never appear on Landing. */ export function useAppShellServices(): void { @@ -42,6 +43,7 @@ export function useAppShellServices(): void { useIpcEvents() useProfileStateSaveDelayNotice() useRemoteRuntimeRecoveryTriggers() + useRemoteUnsavedEditorReport() useVisibleHostedReviewRefresh({ enabled: workspaceSessionReady }) useTerminalViewerColorPublication() useReadOnScreenAttention() diff --git a/src/renderer/src/app-shell/use-global-keybindings.ts b/src/renderer/src/app-shell/use-global-keybindings.ts index 4ea218e6480..37ef9290b98 100644 --- a/src/renderer/src/app-shell/use-global-keybindings.ts +++ b/src/renderer/src/app-shell/use-global-keybindings.ts @@ -221,9 +221,6 @@ export function useGlobalKeybindings(args: { } const handlers = createAppCommandHandlers(state, input, context) - if (matchAppShortcut('workspace.delete') && handlers.get('workspace.delete')?.()) { - return - } if ( matchAppShortcut('sidebar.childWorkspaces.toggle') && handlers.get('sidebar.childWorkspaces.toggle')?.() diff --git a/src/renderer/src/app-shell/use-onboarding-and-feature-tips.test.tsx b/src/renderer/src/app-shell/use-onboarding-and-feature-tips.test.tsx new file mode 100644 index 00000000000..454b4d5dda8 --- /dev/null +++ b/src/renderer/src/app-shell/use-onboarding-and-feature-tips.test.tsx @@ -0,0 +1,98 @@ +// @vitest-environment happy-dom + +import { act, type JSX } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { getDefaultOnboardingState } from '../../../shared/onboarding-defaults' +import { createGlobalSettingsFixture } from '../../../shared/global-settings-test-fixture' +import type { ChatUiLaunchTipVariant } from '../../../shared/native-chat/chat-ui-launch-tip-audience' +import type { FeatureTipSeenId } from '../../../shared/feature-tips' +import type { TelemetrySettings } from '../../../shared/telemetry-settings-types' +import { useAppStore } from '@/store' +import { useOnboardingAndFeatureTips } from './use-onboarding-and-feature-tips' + +vi.mock('@/diagnostics/telemetry/telemetry', () => ({ track: vi.fn() })) + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +let container: HTMLDivElement +let root: Root + +function Gate(): JSX.Element | null { + const gate = useOnboardingAndFeatureTips() + if (gate.onboarding === null) { + gate.applyStartupOnboardingState({ ...getDefaultOnboardingState(), closedAt: 1 }) + } + return {String(gate.chatUiHereCornerCardOpen)} +} + +type Launch = { + surface?: 'terminal' | 'chat' + tip?: ChatUiLaunchTipVariant + seen?: FeatureTipSeenId[] + telemetry?: Partial +} + +/** By default, a profile the tip skipped before: earlier launches already marked the older ids seen. */ +const SKIPPED_BEFORE: Partial = { + chatUiLaunchTipCohort: 'control', + chatUiLaunchTipRolloutCohort: 'control' +} + +async function launch({ + surface = 'terminal', + tip = 'chat-ui-off', + seen = ['chat-ui-here', 'chat-ui-here-rollout-v1'], + telemetry = SKIPPED_BEFORE +}: Launch = {}): Promise { + vi.mocked(window.api.onboarding.getChatUiLaunchTipVariant).mockResolvedValue(tip) + useAppStore.setState({ + persistedUIReady: true, + featureTipsSeenIds: seen, + settings: createGlobalSettingsFixture({ + agentDefaultSurface: surface, + aiVaultSearch: { enabled: true, historyDays: null }, + telemetry: { + optedIn: true, + installId: 'install', + existedBeforeTelemetryRelease: true, + ...telemetry + } + }) + }) + await act(async () => root.render()) + return container.querySelector('output')?.textContent === 'true' +} + +function expectNextTipInstead(): void { + expect(useAppStore.getState().modalData).toMatchObject({ tipId: 'cmd-j-palette' }) +} + +beforeEach(() => { + useAppStore.setState(useAppStore.getInitialState(), true) + Object.defineProperty(window, 'api', { + configurable: true, + value: { + ui: { set: vi.fn().mockResolvedValue(undefined) }, + cli: { getInstallStatus: vi.fn().mockResolvedValue({ supported: false }) }, + onboarding: { getChatUiLaunchTipVariant: vi.fn() } + } + }) + container = document.createElement('div') + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) +}) + +it('shows the card once to a previously skipped profile on the terminal', async () => { + expect(await launch()).toBe(true) + expect(useAppStore.getState().featureTipsSeenIds).toContain('chat-ui-here-v2') +}) + +it('keeps a previously skipped profile on Chat UI out for good', async () => { + expect(await launch({ surface: 'chat' })).toBe(false) + expect(useAppStore.getState().featureTipsSeenIds).toContain('chat-ui-here-v2') + expectNextTipInstead() +}) diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index e446274885a..4a0ccb646b0 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -101,6 +101,9 @@ --color-agent-question: var(--agent-question); --color-agent-working: var(--agent-working); --color-agent-question-text: var(--agent-question-text); + --color-question-card-border: var(--question-card-border); + --color-question-option-border: var(--question-option-border); + --color-chat-focus-ring: var(--chat-focus-ring); --color-chart-1: var(--chart-1); --color-chart-2: var(--chart-2); --color-chart-3: var(--chart-3); @@ -176,6 +179,7 @@ --color-git-graph-lane-5: var(--git-graph-lane-5); --color-annotation-highlight: var(--annotation-highlight); --shadow-floating: 0 10px 24px rgb(0 0 0 / 0.18); + --shadow-notice: var(--notice-shadow); --radius-sm: calc(var(--radius) * 0.6); --radius-md: calc(var(--radius) * 0.8); --radius-lg: var(--radius); @@ -262,6 +266,9 @@ --agent-working: var(--color-yellow-500); /* Legible weight for text/glyphs on a tinted --agent-question surface. */ --agent-question-text: var(--color-orange-700); + /* Answer card edge and the outline shared by its option tiles, badges, answer field and Skip. */ + --question-card-border-mix: 14%; + --question-option-border-mix: 16%; /* Keep PR-state hues stable across theme changes. */ --workspace-status-done: #c7a594; --workspace-status-review: #16a34a; @@ -379,6 +386,8 @@ --ai-action-accent: var(--color-violet-400); --agent-question: var(--color-orange-500); --agent-question-text: var(--color-orange-300); + --question-card-border-mix: 16%; + --question-option-border-mix: 12%; --workspace-status-done: #c7a594; --workspace-status-review: #16a34a; --workspace-status-progress: #d4a300; @@ -542,6 +551,52 @@ --linear-priority-bar-inactive-fill: color-mix(in srgb, lch(39.576 1.25 282) 62%, transparent); } +/* One lifted surface for toasts and corner notification cards; the default card/popover blends into the app. + App themes replace the surface, secondary and muted colors with readable hex (notice-surface-tokens.ts). */ +:root { + --notice-muted: var(--muted); + --notice-muted-foreground: var(--muted-foreground); + --notice-secondary-edge: transparent; + --notice-surface: var(--popover); + --notice-border: color-mix(in srgb, var(--foreground) 14%, transparent); + --notice-secondary: color-mix(in srgb, var(--foreground) 6%, var(--notice-surface)); + --notice-shadow: 0 11px 32px -6px rgb(0 0 0 / 0.2), 0 2px 6px rgb(0 0 0 / 0.08); +} + +.dark { + --notice-surface: color-mix(in srgb, var(--foreground) 7%, var(--popover)); + --notice-border: color-mix(in srgb, var(--foreground) 15%, transparent); + --notice-secondary: color-mix(in srgb, var(--foreground) 10%, var(--notice-surface)); + --notice-shadow: + 0 11px 32px -6px rgb(0 0 0 / 0.55), 0 2px 6px rgb(0 0 0 / 0.22), + inset 0 1px 0 rgb(255 255 255 / 0.06); +} + +/* Why: buttons, text and inner panels paint from these; foregrounds pair with the popover the surface lifts, + and every remapped foreground keeps its surface (outline buttons paint text-foreground on bg-background). */ +[data-sonner-toaster], +.notification-card-stack { + --popover: var(--notice-surface); + --card: var(--notice-surface); + --background: var(--notice-surface); + --foreground: var(--popover-foreground); + --card-foreground: var(--popover-foreground); + --muted: var(--notice-muted); + --muted-foreground: var(--notice-muted-foreground); + --secondary: var(--notice-secondary); + --secondary-foreground: var(--popover-foreground); +} + +/* Why inset outline: an edge for themes that leave secondary buttons unfilled, without moving layout. */ +:is([data-sonner-toaster], .notification-card-stack) + :is( + [data-slot='button'][data-variant='secondary'], + [data-sonner-toast] [data-button][data-cancel] + ) { + outline: 1px solid var(--notice-secondary-edge); + outline-offset: -1px; +} + [data-sonner-toaster] { font-family: var(--font-sans); /* Why: above the floating workspace (z-45 panel, z-46 launcher), which parks in the toasts' corner. */ @@ -564,7 +619,7 @@ body[data-modal-overlay-open] [data-toasts-raised] [data-sonner-toaster] { flex-wrap: wrap; gap: 10px; padding: 14px 16px; - box-shadow: var(--shadow-floating); + box-shadow: var(--notice-shadow); } [data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-icon] { @@ -649,28 +704,21 @@ body[data-modal-overlay-open] pointer-events: auto; } -[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-close-button] { +[data-sonner-toaster][data-sonner-theme] + [data-sonner-toast][data-styled='true'] + [data-close-button] { /* Override Sonner’s dark defaults so the close icon contrasts in both themes. */ color: var(--popover-foreground); background: var(--popover); - border-color: rgb(0 0 0 / 0.14); + border-color: var(--notice-border); } -[data-sonner-toaster][data-sonner-theme='dark'] +[data-sonner-toaster][data-sonner-theme] [data-sonner-toast][data-styled='true'] - [data-close-button] { - color: var(--popover-foreground); - background: var(--popover); - border-color: rgb(255 255 255 / 0.14); -} - -.dark [data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-close-button] { - border-color: rgb(255 255 255 / 0.14); -} - -[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-close-button]:hover { + [data-close-button]:hover { color: var(--accent-foreground); background: var(--accent); + border-color: var(--notice-border); } /* Re-evaluate chat colors where the appearance producer supplies their source colors. */ @@ -743,6 +791,17 @@ body[data-modal-overlay-open] var(--chat-source-foreground) var(--chat-composer-border-mix), transparent ); + /* From the chat's own foreground, so the edges stay visible when chat follows the terminal's colors. */ + --question-card-border: color-mix( + in srgb, + var(--chat-source-foreground) var(--question-card-border-mix), + transparent + ); + --question-option-border: color-mix( + in srgb, + var(--chat-source-foreground) var(--question-option-border-mix), + transparent + ); /* Mixed toward the foreground so each clears text contrast on the canvas in either scheme. */ --chat-focus-ring: color-mix(in srgb, var(--chat-source-foreground) 50%, var(--chat-canvas)); --chat-warning: color-mix(in srgb, var(--status-warning) 70%, var(--chat-source-foreground)); @@ -811,6 +870,25 @@ body[data-modal-overlay-open] } } +@utility control-interaction { + @media (hover: hover) { + &:not(:disabled, [aria-disabled='true']):hover { + outline: 1px solid var(--ring); + outline-offset: 1px; + } + } + + &:not(:disabled, [aria-disabled='true']):focus { + outline: 2px solid var(--ring); + outline-offset: 2px; + } + + &:not(:disabled, [aria-disabled='true']):active { + outline: 2px solid var(--ring); + outline-offset: 0; + } +} + /* Tailwind must generate this utility; a plain class silently emits no scrollbar-none CSS. */ @utility scrollbar-none { -ms-overflow-style: none; @@ -1532,6 +1610,20 @@ html.native-shell .app-layout { color: var(--accent-foreground); } +/* Why: the split-pane landing card is a flat surface, so its highlight is a plain fill on + --popover with no ring; these out-rank the palette rules above in both themes. */ +.split-pane-landing [data-slot='command-item'].jump-palette-item[data-selected='true'] { + --jump-palette-selection-surface: color-mix(in srgb, var(--foreground) 12%, var(--popover)); + background: var(--jump-palette-selection-surface); + box-shadow: none; +} + +.dark .split-pane-landing [data-slot='command-item'].jump-palette-item[data-selected='true'] { + --jump-palette-selection-surface: color-mix(in srgb, var(--foreground) 8%, var(--popover)); + background: var(--jump-palette-selection-surface); + box-shadow: none; +} + [data-file-explorer-row][data-selected='true'] { /* Why: flat bg-accent ≈ panel background in light mode, so selection mixes foreground into accent and adds an inset ring to stay legible in both themes. */ @@ -1581,6 +1673,7 @@ html.native-shell .app-layout { /* Why: the brighter border carries the selected state; a translucent wash keeps card text legible instead of lifting the surface toward the foreground color. */ +[data-worktree-family-segment='primary'], [data-worktree-card-surface][data-worktree-card-active='primary'] { border-color: var( --worktree-sidebar-active-border, @@ -1593,6 +1686,7 @@ html.native-shell .app-layout { box-shadow: 0 1px 2px color-mix(in srgb, var(--worktree-sidebar-foreground) 4%, transparent); } +.dark [data-worktree-family-segment='primary'], .dark [data-worktree-card-surface][data-worktree-card-active='primary'] { border-color: var( --worktree-sidebar-active-border, @@ -1618,18 +1712,34 @@ html.native-shell .app-layout { } } +[data-worktree-family-segment='secondary'], [data-worktree-card-surface][data-worktree-card-active='secondary'] { border-color: color-mix(in srgb, var(--sidebar-ring) 25%, transparent); background: color-mix(in srgb, var(--sidebar-accent) 45%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--sidebar-ring) 15%, transparent); } +.dark [data-worktree-family-segment='secondary'], .dark [data-worktree-card-surface][data-worktree-card-active='secondary'] { border-color: color-mix(in srgb, var(--sidebar-ring) 28%, transparent); background: color-mix(in srgb, var(--sidebar-accent) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--sidebar-ring) 18%, transparent); } +/* Family paint owns the surface in both themes, including secondary occurrences. */ +.worktree-sidebar-family-root [data-worktree-card-surface][data-worktree-card-active], +.dark .worktree-sidebar-family-root [data-worktree-card-surface][data-worktree-card-active] { + background: transparent; + border-color: transparent; + box-shadow: none; +} + +/* Continuous segments must not cast a horizontal shadow at every virtual boundary. */ +[data-worktree-family-segment], +.dark [data-worktree-family-segment] { + box-shadow: none; +} + /* #19624: mix text tokens toward sidebar in oklab for theme-stable perceptual dimming; preserve unread amber at full brightness. */ [data-worktree-sleeping-dim] { color: color-mix(in oklab, var(--worktree-sidebar-foreground) 52%, var(--worktree-sidebar)); @@ -2139,6 +2249,38 @@ html.native-shell .app-layout { } } +/* Search and deep-link target: a tint out to the enclosing card's edges that fades. + An inset shadow carries the tint so a highlighted card keeps its own fill and corners. + The bleed vars are measured per target, since nested and sub-row targets sit further in. */ +.settings-target-highlight { + --settings-target-tint: color-mix(in srgb, var(--foreground) 8%, transparent); + box-shadow: + inset 0 0 0 100vmax var(--settings-target-tint), + calc(-1 * var(--settings-target-bleed-left, 0px)) 0 0 var(--settings-target-tint), + var(--settings-target-bleed-right, 0px) 0 0 var(--settings-target-tint); +} + +@media (prefers-reduced-motion: no-preference) { + .settings-target-highlight { + animation: settings-target-highlight-fade 3s ease-out forwards; + } +} + +@keyframes settings-target-highlight-fade { + 60% { + box-shadow: + inset 0 0 0 100vmax var(--settings-target-tint), + calc(-1 * var(--settings-target-bleed-left, 0px)) 0 0 var(--settings-target-tint), + var(--settings-target-bleed-right, 0px) 0 0 var(--settings-target-tint); + } + 100% { + box-shadow: + inset 0 0 0 100vmax transparent, + calc(-1 * var(--settings-target-bleed-left, 0px)) 0 0 transparent, + var(--settings-target-bleed-right, 0px) 0 0 transparent; + } +} + @keyframes settings-shell-enter { from { opacity: 0; diff --git a/src/renderer/src/assets/rich-markdown-editor.css b/src/renderer/src/assets/rich-markdown-editor.css index d8acaf45e86..c93039b73c0 100644 --- a/src/renderer/src/assets/rich-markdown-editor.css +++ b/src/renderer/src/assets/rich-markdown-editor.css @@ -1141,17 +1141,12 @@ .rich-markdown-editor a, .rich-markdown-editor .ProseMirror a { color: var(--text-link, #0969da); + cursor: pointer; text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); text-underline-offset: 0.25em; } -/* Plain clicks place the caret; RichMarkdownEditor exposes link pointers only while Cmd/Ctrl is held. */ -.rich-markdown-mod-held .rich-markdown-editor a, -.rich-markdown-mod-held .rich-markdown-editor .ProseMirror a { - cursor: pointer; -} - .dark .rich-markdown-editor a { color: var(--text-link, #58a6ff); } @@ -1171,9 +1166,7 @@ color: var(--text-link, #58a6ff); } -.rich-markdown-mod-held - .rich-markdown-editor - .rich-markdown-html-superscript-link[data-actionable] { +.rich-markdown-editor .rich-markdown-html-superscript-link[data-actionable] { cursor: pointer; } @@ -1525,6 +1518,9 @@ text-overflow: ellipsis; white-space: nowrap; font-family: var(--font-mono, monospace); + cursor: text; + user-select: text; + outline: none; } .rich-markdown-link-button { diff --git a/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts b/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts index e8e5944834f..302fecfbdac 100644 --- a/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts +++ b/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts @@ -1,13 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { getDefaultSettings } from '../../../shared/constants' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' import { getDefaultNotificationSettings } from '../../../shared/notification-settings-defaults' import { createTabsSliceMockApi } from '../store/slices/tabs/tabs-slice-test-harness' import { createTestStore } from '../store/testing/app-store-test-fixture' import { makeWorktree } from '../store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '../store/repos/repo.test-fixture' -import { isWorkspaceNotificationMutedBySidebarFilters } from './hidden-workspace-notification-mute' vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) @@ -34,10 +31,6 @@ function setNotifyHiddenWorkspaces(notifyHiddenWorkspaces: boolean): void { }) } -function muted(workspaceId: string): boolean { - return isWorkspaceNotificationMutedBySidebarFilters(store.getState(), workspaceId) -} - beforeEach(() => { store = createTestStore() store.setState({ @@ -50,80 +43,6 @@ beforeEach(() => { setNotifyHiddenWorkspaces(false) }) -describe('isWorkspaceNotificationMutedBySidebarFilters', () => { - it('fails open before settings or UI state hydrate, and for an unknown workspace', () => { - expect(muted('repo1::/tmp/unknown')).toBe(false) - store.setState({ persistedUIReady: false }) - expect(muted(CLI_ID)).toBe(false) - store.setState({ persistedUIReady: true, settings: null }) - expect(muted(CLI_ID)).toBe(false) - }) - - it('fails open until terminals reconnect, when Hide sleeping would read restored work as asleep', () => { - store.setState({ hideCliCreatedWorkspaces: false, showSleepingWorkspaces: false }) - store.setState({ workspaceSessionReady: false }) - expect(muted(PLAIN_ID)).toBe(false) - store.setState({ workspaceSessionReady: true }) - expect(muted(PLAIN_ID)).toBe(true) - }) - - it('keeps notifying for a hidden parent the sidebar shows above a visible child', () => { - store.setState({ - worktreeLineageById: { - [PLAIN_ID]: { - worktreeId: PLAIN_ID, - worktreeInstanceId: 'plain', - parentWorktreeId: CLI_ID, - parentWorktreeInstanceId: 'cli', - origin: 'cli', - capture: { source: 'terminal-context', confidence: 'inferred' }, - createdAt: 1 - } - }, - worktreesByRepo: { - repo1: [ - { ...cliRow, instanceId: 'cli' }, - { ...plainRow, instanceId: 'plain' } - ] - } - }) - expect(muted(CLI_ID)).toBe(false) - }) - - it('keeps notifying for an id whose twin on another host the switches show', () => { - store.setState({ - worktreesByRepo: { - repo1: [cliRow, plainRow], - 'repo1@other-host': [{ ...cliRow, cliProvenance: undefined }] - } - }) - expect(muted(CLI_ID)).toBe(false) - }) - - it('mutes another client’s folder workspace under Hide other-client workspaces only', () => { - const folder: FolderWorkspace = { - id: 'f1', - projectGroupId: 'g1', - name: 'notes', - folderPath: '/notes', - creatorProvenance: { kind: 'paired-device', deviceId: 'phone' }, - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } - store.setState({ folderWorkspaces: [folder] }) - expect(muted(folderWorkspaceKey('f1'))).toBe(false) - store.setState({ hideWorkspacesFromOtherDevices: true }) - expect(muted(folderWorkspaceKey('f1'))).toBe(true) - }) -}) - describe('muted workspace attention', () => { it('writes no bell marker for a muted workspace, and still does for a visible one', () => { const terminalTab = (id: string, worktreeId: string) => ({ diff --git a/src/renderer/src/attention/hidden-workspace-notification-mute.ts b/src/renderer/src/attention/hidden-workspace-notification-mute.ts index b43b0f99326..a505e0bf09b 100644 --- a/src/renderer/src/attention/hidden-workspace-notification-mute.ts +++ b/src/renderer/src/attention/hidden-workspace-notification-mute.ts @@ -6,6 +6,7 @@ import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { sidebarHasActiveFilters } from '@/components/sidebar/worktree-list/controls/sidebar-filter-actions' import { computeVisibleWorktreeIds } from '@/components/sidebar/worktree-list/listing/compute-visible-worktrees' import { buildVisibleWorktreeOptionsFromState } from '@/components/sidebar/worktree-list/listing/visible-worktree-options-from-state' +import { NO_HIDDEN_PROJECTS } from '../../../shared/hidden-projects' import { isFolderWorkspaceFromOtherDevice } from '../../../shared/workspace-creator-visibility' import { selectFolderWorkspaces, @@ -46,6 +47,8 @@ export function isWorkspaceNotificationMutedBySidebarFilters( // Use the full sidebar pass (~0.2–0.3ms/1,000 workspaces) to preserve every rule that adds rows back. const visibleIds = computeVisibleWorktreeIds(selectWorktreesByRepo(state), [], { ...inputs, + // Hiding a project is a view choice, never a mute: its workspaces notify as if listed. + hiddenProjects: NO_HIDDEN_PROJECTS, filterRepoIds: [], workspaceHostScope: ALL_EXECUTION_HOSTS_SCOPE, visibleWorkspaceHostIds: null diff --git a/src/renderer/src/components/DetachedHeadBadge.fixture.tsx b/src/renderer/src/components/DetachedHeadBadge.fixture.tsx index 2a854b2862e..12bdbc6ac9a 100644 --- a/src/renderer/src/components/DetachedHeadBadge.fixture.tsx +++ b/src/renderer/src/components/DetachedHeadBadge.fixture.tsx @@ -1,4 +1,4 @@ -import { getWorktreeGitIdentityDisplay } from '../../../shared/worktree/git-identity-display' +import { getWorktreeGitIdentityDisplay } from '../../../shared/worktree/row-display/git-identity-display' import { defineFixture } from '../component-fixtures/component-fixture' import { DetachedHeadBadge } from './DetachedHeadBadge' diff --git a/src/renderer/src/components/DetachedHeadBadge.tsx b/src/renderer/src/components/DetachedHeadBadge.tsx index 4f834cdc32e..8b5fdfa15a7 100644 --- a/src/renderer/src/components/DetachedHeadBadge.tsx +++ b/src/renderer/src/components/DetachedHeadBadge.tsx @@ -3,7 +3,7 @@ import { GitCommitHorizontal } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/class-names' -import type { WorktreeGitIdentityDisplay } from '../../../shared/worktree/git-identity-display' +import type { WorktreeGitIdentityDisplay } from '../../../shared/worktree/row-display/git-identity-display' type DetachedHeadDisplay = Extract diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 7bed3f4f77a..bbc6a2743ad 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -12,7 +12,7 @@ import { type AddRemoteHostMode } from '@/components/sidebar/host-admission/ssh/AddRemoteHostDialog' import { lazyWithRetry } from '@/app-shell/startup/lazy-with-retry' -import type * as SetProjectLocationDialogModule from '@/components/new-workspace/SetProjectLocationDialog' +import type * as SetProjectLocationDialogModule from '@/components/new-workspace/project-location/SetProjectLocationDialog' import { unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result' import { withUiConnectTimeout } from '@/ssh/ssh-connect-ui-timeout' import { isSshConnectInFlight, trackSshConnect } from '@/ssh/ssh-connect-in-flight' @@ -25,26 +25,26 @@ import { import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import type { AddRepoDialogEntryRequest } from '@/components/sidebar/project-admission/dialog/add-repo-dialog-types' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import { NewWorkspaceComposerAdvancedSection } from './new-workspace/NewWorkspaceComposerAdvancedSection' -import { NewWorkspaceComposerAgentSection } from './new-workspace/NewWorkspaceComposerAgentSection' -import { NewWorkspaceComposerFooter } from './new-workspace/NewWorkspaceComposerFooter' -import { NewWorkspaceComposerNameSection } from './new-workspace/NewWorkspaceComposerNameSection' -import { NewWorkspaceComposerProjectSection } from './new-workspace/NewWorkspaceComposerProjectSection' +import { NewWorkspaceComposerAdvancedSection } from './new-workspace/composer/NewWorkspaceComposerAdvancedSection' +import { NewWorkspaceComposerAgentSection } from './new-workspace/composer/NewWorkspaceComposerAgentSection' +import { NewWorkspaceComposerFooter } from './new-workspace/composer/NewWorkspaceComposerFooter' +import { NewWorkspaceComposerNameSection } from './new-workspace/composer/NewWorkspaceComposerNameSection' +import { NewWorkspaceComposerProjectSection } from './new-workspace/composer/NewWorkspaceComposerProjectSection' import { EMPTY_EPHEMERAL_VM_RECIPES, EMPTY_PROJECT_HOST_SETUP_OPTIONS, EMPTY_PROJECT_OPTIONS, - type NeedsProjectHostOption, type NewWorkspaceComposerCardProps -} from './new-workspace/new-workspace-composer-card-props' -import { getSshStatusLabel } from './new-workspace/new-workspace-composer-ssh-status' -import { useNewWorkspaceComposerFileDrop } from './new-workspace/use-new-workspace-composer-file-drop' -import { useComposerFileDragOver } from './new-workspace/use-composer-file-drag-over' +} from './new-workspace/composer/new-workspace-composer-card-props' +import type { NeedsSetupProjectHostOption } from '../lib/workspace/creation/project-host-setup-options' +import { getSshStatusLabel } from './new-workspace/composer/new-workspace-composer-ssh-status' +import { useNewWorkspaceComposerFileDrop } from './new-workspace/composer/use-new-workspace-composer-file-drop' +import { useComposerFileDragOver } from './new-workspace/composer/use-composer-file-drag-over' import { buildDefaultAgentSettingsUpdate } from '../../../shared/agent-launch/choices/default-agent-settings' // Lazy-load the project-location browser outside boot; warming shares this module entry with the click. const loadSetProjectLocationDialog = (): Promise => - import('@/components/new-workspace/SetProjectLocationDialog') + import('@/components/new-workspace/project-location/SetProjectLocationDialog') const SetProjectLocationDialog = lazyWithRetry( () => @@ -119,9 +119,8 @@ export default function NewWorkspaceComposerCard( }, [onNestedDialogOpenChange] ) - const [setLocationOption, setSetLocationOption] = React.useState( - null - ) + const [setLocationOption, setSetLocationOption] = + React.useState(null) // Retain the dialog while its cleared option drives the close animation. const [setLocationDialogMounted, setSetLocationDialogMounted] = React.useState(false) @@ -217,7 +216,7 @@ export default function NewWorkspaceComposerCard( [onAddProjectEntryRequest, openModal] ) const handleSetLocation = React.useCallback( - (option: NeedsProjectHostOption): void => { + (option: NeedsSetupProjectHostOption): void => { setSetLocationDialogMounted(true) setSetLocationOption(option) onNestedDialogOpenChange?.(true) @@ -236,7 +235,7 @@ export default function NewWorkspaceComposerCard( [handleSetLocationClose, onProjectHostSetupChange] ) const handleConnectRunTargetHost = React.useCallback( - async (option: NeedsProjectHostOption): Promise => { + async (option: NeedsSetupProjectHostOption): Promise => { const action = option.connectAction if (!action) { return diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 2951903acf4..42ec4a66bab 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -1,4 +1,4 @@ -import type { ComposerModalData } from './new-workspace/composer-modal-data' +import type { ComposerModalData } from './new-workspace/composer/composer-modal-data' import { toast } from 'sonner' import { formatWorkspaceCreateError, @@ -8,7 +8,7 @@ import type { AgentPickerDraft, AgentPickerEntry } from '../../../shared/agent-launch/picker/agent-launch-picker' -import { DirectWorkItemSetupDialog } from './new-workspace/DirectWorkItemSetupDialog' +import { DirectWorkItemSetupDialog } from './new-workspace/setup/DirectWorkItemSetupDialog' import { agentChoicePending } from '@/lib/agent-session/launch/inventory/host-chat-program' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import React, { Suspense, useCallback, useEffect, useRef, useState } from 'react' @@ -25,7 +25,7 @@ import NewWorkspaceComposerCard from '@/components/NewWorkspaceComposerCard' import AgentSettingsDialog, { restoreAgentSettingsInvoker } from '@/components/agent/AgentSettingsDialog' -import { useComposerHostedAddProject } from './new-workspace/use-composer-hosted-add-project' +import { useComposerHostedAddProject } from './new-workspace/project-selection/use-composer-hosted-add-project' import { useComposerState } from '@/hooks/useComposerState' import { composerLaunchWorkspace, diff --git a/src/renderer/src/components/NotificationCardStack.test.tsx b/src/renderer/src/components/NotificationCardStack.test.tsx new file mode 100644 index 00000000000..97922b47164 --- /dev/null +++ b/src/renderer/src/components/NotificationCardStack.test.tsx @@ -0,0 +1,103 @@ +// @vitest-environment happy-dom +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { NotificationCardStack } from './NotificationCardStack' + +/** A ResizeObserver that reports only what it observes, when the test resizes an element. */ +class FakeResizeObserver implements ResizeObserver { + static all: FakeResizeObserver[] = [] + private readonly targets = new Set() + + constructor(private readonly callback: ResizeObserverCallback) { + FakeResizeObserver.all.push(this) + } + + observe(target: Element): void { + this.targets.add(target) + } + + unobserve(target: Element): void { + this.targets.delete(target) + } + + disconnect(): void { + this.targets.clear() + } + + static resize(target: Element): void { + for (const observer of FakeResizeObserver.all) { + if (observer.targets.has(target)) { + observer.callback([], observer) + } + } + } +} + +function stackOf(card: HTMLElement): HTMLElement { + const stack = card.parentElement + if (!stack) { + throw new Error('card is not in a stack') + } + return stack +} + +/** Pins the stack's scroll metrics; its box stays capped at 220px while content grows. */ +function capStack(stack: HTMLElement, content: { height: number }): void { + Object.defineProperty(stack, 'clientHeight', { configurable: true, get: () => 220 }) + Object.defineProperty(stack, 'scrollHeight', { configurable: true, get: () => content.height }) +} + +describe('NotificationCardStack', () => { + beforeEach(() => { + FakeResizeObserver.all = [] + vi.stubGlobal('ResizeObserver', FakeResizeObserver) + }) + + afterEach(() => { + cleanup() + vi.unstubAllGlobals() + }) + + it('starts scrolling when a card grows inside a stack already at its max height', () => { + render( + +
+ + ) + const card = screen.getByTestId('card') + const stack = stackOf(card) + const content = { height: 220 } + capStack(stack, content) + act(() => FakeResizeObserver.resize(stack)) + expect(stack.hasAttribute('data-overflowing')).toBe(false) + + content.height = 240 + act(() => FakeResizeObserver.resize(card)) + + expect(stack.hasAttribute('data-overflowing')).toBe(true) + }) + + it('watches a card that mounts after the stack', async () => { + const { rerender } = render( + +
+ + ) + const stack = stackOf(screen.getByTestId('first')) + const content = { height: 200 } + capStack(stack, content) + rerender( + +
+
+ + ) + // MutationObserver delivers on a microtask. + await act(async () => {}) + + content.height = 260 + act(() => FakeResizeObserver.resize(screen.getByTestId('second'))) + + expect(stack.hasAttribute('data-overflowing')).toBe(true) + }) +}) diff --git a/src/renderer/src/components/NotificationCardStack.tsx b/src/renderer/src/components/NotificationCardStack.tsx index c315855e263..17ae93a94a3 100644 --- a/src/renderer/src/components/NotificationCardStack.tsx +++ b/src/renderer/src/components/NotificationCardStack.tsx @@ -8,9 +8,15 @@ import { setNotificationCardLayoutVar } from '@/lib/notifications/notification-card-layout-vars' -const STACK_STYLE = { - bottom: NOTIFICATION_CARD_STACK_BOTTOM, - maxHeight: `calc(100vh - 2.5rem - ${NOTIFICATION_CARD_STACK_BOTTOM})` +// Why: the scroll box clips, so it pads out (offset back) to show card shadows; the room collapses while it scrolls. +const SHADOW_ROOM_Y_PX = 40 +const ROOM_Y = 'var(--stack-shadow-room-y)' + +const STACK_STYLE: React.CSSProperties & Record<`--${string}`, string> = { + '--stack-shadow-room-y': `${SHADOW_ROOM_Y_PX}px`, + padding: `${ROOM_Y} 1rem`, + bottom: `calc(${NOTIFICATION_CARD_STACK_BOTTOM} - ${ROOM_Y})`, + maxHeight: `calc(100vh - 2.5rem - ${NOTIFICATION_CARD_STACK_BOTTOM} + 2 * ${ROOM_Y})` } export function NotificationCardStack({ children }: { children: ReactNode }): React.JSX.Element { @@ -24,17 +30,41 @@ export function NotificationCardStack({ children }: { children: ReactNode }): Re const unregister = registerNotificationCardLayoutVarReader(stack) // Why publish: toasts share this corner and would otherwise render behind the cards (z-50). const publish = (): void => { - const height = stack.offsetHeight + const overflowing = stack.hasAttribute('data-overflowing') + const height = stack.offsetHeight - (overflowing ? 0 : 2 * SHADOW_ROOM_Y_PX) + // Toggling swaps padding for max-height, so the content height published above stays valid. + stack.toggleAttribute('data-overflowing', stack.scrollHeight - stack.clientHeight > 1) setNotificationCardLayoutVar( NOTIFICATION_CARD_STACK_HEIGHT_VAR, height > 0 ? `calc(${height}px + 0.5rem)` : null ) } publish() + // Why each card too: once the box hits max-height, a growing card no longer resizes the box. const observer = new ResizeObserver(publish) observer.observe(stack) + for (const card of stack.children) { + observer.observe(card) + } + const cardList = new MutationObserver((records) => { + for (const record of records) { + for (const node of record.addedNodes) { + if (node instanceof Element) { + observer.observe(node) + } + } + for (const node of record.removedNodes) { + if (node instanceof Element) { + observer.unobserve(node) + } + } + } + publish() + }) + cardList.observe(stack, { childList: true }) window.addEventListener('resize', publish) return () => { + cardList.disconnect() observer.disconnect() window.removeEventListener('resize', publish) setNotificationCardLayoutVar(NOTIFICATION_CARD_STACK_HEIGHT_VAR, null) @@ -46,7 +76,7 @@ export function NotificationCardStack({ children }: { children: ReactNode }): Re
{children}
diff --git a/src/renderer/src/components/__mocks__/task-page-jira-favourite-fixture.ts b/src/renderer/src/components/__mocks__/task-page-jira-favourite-fixture.ts deleted file mode 100644 index b724951f850..00000000000 --- a/src/renderer/src/components/__mocks__/task-page-jira-favourite-fixture.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { useMemo, useRef } from 'react' -import { vi, type Mock } from 'vitest' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { JiraIssue } from '../../../../shared/jira/jira-types' -import type { JiraSavedFilterState } from '../../../../shared/jira/jira-saved-filters' -import type { TaskPageLinearViewStateModel } from '../task-page/linear/use-task-page-linear-view-state' -import type { TaskPageLinearCollectionEffectsModel } from '../task-page/linear/use-task-page-linear-collection-effects' -import { useTaskPageJiraListState } from '../task-page/jira/use-task-page-jira-list-state' -import { useTaskPageJiraListEffects } from '../task-page/jira/use-task-page-jira-list-effects' - -const favouriteTransport: { - catalogue: Mock - readSaved: Mock - mutateSaved: Mock - readQuick: Mock - list: Mock - search: Mock - resume: Mock -} = vi.hoisted(() => ({ - catalogue: vi.fn(), - readSaved: vi.fn(), - mutateSaved: vi.fn(), - readQuick: vi.fn(), - list: vi.fn(), - search: vi.fn(), - resume: vi.fn() -})) -export { favouriteTransport } -vi.mock('@/runtime/jira/runtime-jira-favourite-filters-client', () => ({ - jiraListFavouriteFiltersForTarget: favouriteTransport.catalogue -})) -vi.mock('@/runtime/jira/runtime-jira-saved-filter-state', () => ({ - readJiraSavedFilterState: favouriteTransport.readSaved, - mutateJiraSavedFilters: favouriteTransport.mutateSaved -})) -vi.mock('@/runtime/jira/runtime-jira-quick-filter-state', () => ({ - readJiraQuickFilterState: favouriteTransport.readQuick -})) -vi.mock('@/runtime/jira/runtime-jira-detail-client', () => ({ - jiraListPrioritiesForTarget: vi.fn() -})) -vi.mock('@/runtime/jira/runtime-jira-client', () => ({ - jiraGetProjectStatusOrder: vi.fn() -})) - -export const favourite = { - id: 'fav-1', - name: 'My Jira favourite', - jql: 'filter = 12345 ORDER BY updated DESC', - siteId: 'site-a' -} -export const named = { id: 'named', name: 'Custom named filter', jql: 'project = CUSTOM' } -export const emptySaved: JiraSavedFilterState = { filters: [named], activeFilterId: null } -const emptyIssues: JiraIssue[] = [] -const noop = () => {} - -export function resetFavouriteTransport() { - vi.resetAllMocks() - favouriteTransport.catalogue.mockImplementation(async (_target, siteId: string) => ({ - supported: true, - filters: [{ ...favourite, siteId }], - truncated: false - })) - favouriteTransport.readSaved.mockResolvedValue(emptySaved) - favouriteTransport.mutateSaved.mockImplementation(async (_target, mutation) => ({ - ...emptySaved, - activeFilterId: mutation.kind === 'select' ? mutation.id : null - })) - favouriteTransport.readQuick.mockResolvedValue({ statuses: [] }) - favouriteTransport.list.mockResolvedValue(emptyIssues) - favouriteTransport.search.mockResolvedValue(emptyIssues) -} - -export type FavouriteFixtureProps = { hostId?: ExecutionHostId; siteId?: string; enabled?: boolean } -export function useFavouriteTaskPage({ - hostId = 'runtime:owner-a', - siteId = 'site-a', - enabled = true -}: FavouriteFixtureProps = {}) { - const sourceContext = useMemo( - () => ({ - kind: 'task-source' as const, - provider: 'jira' as const, - projectId: 'folder-project', - hostId, - providerIdentity: { provider: 'jira' as const, siteId: siteId === 'all' ? null : siteId } - }), - [hostId, siteId] - ) - const model = { - accountBackedTaskSourceHostId: hostId, - jiraTaskSourceContext: sourceContext, - jiraTaskSourceScopeKey: JSON.stringify([hostId, siteId]), - taskSource: enabled ? 'jira' : 'github', - taskResumeApplied: true, - jiraConnected: true, - selectedJiraSiteId: siteId, - repos: [], - selectedRepos: [], - pageData: {}, - settings: { activeRuntimeEnvironmentId: 'different-focused-server' }, - jiraSearchPersistReadyRef: useRef(true), - selectedJiraIssueKey: null, - selectedJiraIssueFallback: null, - setSelectedJiraIssueKey: noop, - setSelectedJiraIssueFallback: noop, - setTaskResumeState: favouriteTransport.resume, - linkedJiraIssueRefs: [], - linkedJiraIssueRefsSignature: '[]', - listJiraIssues: favouriteTransport.list, - searchJiraIssues: favouriteTransport.search - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The actual Jira hooks only read the supplied fields from the preceding provider pipeline. - const state = useTaskPageJiraListState(model as unknown as TaskPageLinearViewStateModel) - const effects = { ...state, displayedJiraIssues: state.jiraIssues } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: All fields read by the actual Jira list effect are supplied; unrelated provider stages are omitted. - useTaskPageJiraListEffects(effects as unknown as TaskPageLinearCollectionEffectsModel) - return state -} diff --git a/src/renderer/src/components/activity/activity-scope-filter-controls.tsx b/src/renderer/src/components/activity/activity-scope-filter-controls.tsx index 3431c3dcfbc..b4f570bd445 100644 --- a/src/renderer/src/components/activity/activity-scope-filter-controls.tsx +++ b/src/renderer/src/components/activity/activity-scope-filter-controls.tsx @@ -88,6 +88,8 @@ export function ActivityScopeFilterMenuItems(): React.JSX.Element {